text stringlengths 54 60.6k |
|---|
<commit_before>#include "guis/GuiInputConfig.h"
#include "Window.h"
#include "Log.h"
#include "components/TextComponent.h"
#include "components/ImageComponent.h"
#include "components/MenuComponent.h"
#include "components/ButtonComponent.h"
#include "Util.h"
// static const int inputCount = 10;
// static const char* inputName[inputCount] = { "Up", "Down", "Left", "Right", "A", "B", "Start", "Select", "PageUp", "PageDown" };
// static const bool inputSkippable[inputCount] = { false, false, false, false, false, false, false, false, true, true };
// static const char* inputDispName[inputCount] = { "UP", "DOWN", "LEFT", "RIGHT", "A", "B", "START", "SELECT", "PAGE UP", "PAGE DOWN" };
// static const char* inputIcon[inputCount] = { ":/help/dpad_up.svg", ":/help/dpad_down.svg", ":/help/dpad_left.svg", ":/help/dpad_right.svg",
// ":/help/button_a.svg", ":/help/button_b.svg", ":/help/button_start.svg", ":/help/button_select.svg",
// ":/help/button_l.svg", ":/help/button_r.svg" };
static const int inputCount = 24;
static const char* inputName[inputCount] =
{
"Up",
"Down",
"Left",
"Right",
"Start",
"Select",
"A",
"B",
"X",
"Y",
"LeftBottom",
"RightBottom",
"LeftTop",
"RightTop",
"LeftThumb",
"RightThumb",
"LeftAnalogUp",
"LeftAnalogDown",
"LeftAnalogLeft",
"LeftAnalogRight",
"RightAnalogUp",
"RightAnalogDown",
"RightAnalogLeft",
"RightAnalogRight"
};
static const bool inputSkippable[inputCount] =
{
false,
false,
false,
false,
true,
true,
false,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true
};
static const char* inputDispName[inputCount] =
{
"D-PAD UP",
"D-PAD DOWN",
"D-PAD LEFT",
"D-PAD RIGHT",
"START",
"SELECT",
"A",
"B",
"X",
"Y",
"LEFT BOTTOM",
"RIGHT BOTTOM",
"LEFT TOP",
"RIGHT TOP",
"LEFT THUMB",
"RIGHT THUMB",
"LEFT ANALOG UP",
"LEFT ANALOG DOWN",
"LEFT ANALOG LEFT",
"LEFT ANALOG RIGHT",
"RIGHT ANALOG UP",
"RIGHT ANALOG DOWN",
"RIGHT ANALOG LEFT",
"RIGHT ANALOG RIGHT"
};
static const char* inputIcon[inputCount] =
{
":/help/dpad_up.svg",
":/help/dpad_down.svg",
":/help/dpad_left.svg",
":/help/dpad_right.svg",
":/help/button_start.svg",
":/help/button_select.svg",
":/help/button_a.svg",
":/help/button_b.svg",
":/help/button_x.svg",
":/help/button_y.svg",
":/help/button_l.svg",
":/help/button_r.svg",
":/help/button_l.svg",
":/help/button_r.svg",
":/help/analog_thumb.svg",
":/help/analog_thumb.svg",
":/help/analog_up.svg",
":/help/analog_down.svg",
":/help/analog_left.svg",
":/help/analog_right.svg",
":/help/analog_up.svg",
":/help/analog_down.svg",
":/help/analog_left.svg",
":/help/analog_right.svg"
};
//MasterVolUp and MasterVolDown are also hooked up, but do not appear on this screen.
//If you want, you can manually add them to es_input.cfg.
using namespace Eigen;
#define HOLD_TO_SKIP_MS 1000
GuiInputConfig::GuiInputConfig(Window* window, InputConfig* target, bool reconfigureAll, const std::function<void()>& okCallback) : GuiComponent(window),
mBackground(window, ":/frame.png"), mGrid(window, Vector2i(1, 7)),
mTargetConfig(target), mHoldingInput(false), mBusyAnim(window)
{
LOG(LogInfo) << "Configuring device " << target->getDeviceId() << " (" << target->getDeviceName() << ").";
if(reconfigureAll)
target->clear();
mConfiguringAll = reconfigureAll;
mConfiguringRow = mConfiguringAll;
addChild(&mBackground);
addChild(&mGrid);
// 0 is a spacer row
mGrid.setEntry(std::make_shared<GuiComponent>(mWindow), Vector2i(0, 0), false);
mTitle = std::make_shared<TextComponent>(mWindow, "CONFIGURING", Font::get(FONT_SIZE_LARGE), 0x555555FF, ALIGN_CENTER);
mGrid.setEntry(mTitle, Vector2i(0, 1), false, true);
std::stringstream ss;
if(target->getDeviceId() == DEVICE_KEYBOARD)
ss << "KEYBOARD";
else
ss << "GAMEPAD " << (target->getDeviceId() + 1);
mSubtitle1 = std::make_shared<TextComponent>(mWindow, strToUpper(ss.str()), Font::get(FONT_SIZE_MEDIUM), 0x555555FF, ALIGN_CENTER);
mGrid.setEntry(mSubtitle1, Vector2i(0, 2), false, true);
mSubtitle2 = std::make_shared<TextComponent>(mWindow, "HOLD ANY BUTTON TO SKIP", Font::get(FONT_SIZE_SMALL), 0x99999900, ALIGN_CENTER);
mGrid.setEntry(mSubtitle2, Vector2i(0, 3), false, true);
// 4 is a spacer row
mList = std::make_shared<ComponentList>(mWindow);
mGrid.setEntry(mList, Vector2i(0, 5), true, true);
for(int i = 0; i < inputCount; i++)
{
ComponentListRow row;
// icon
auto icon = std::make_shared<ImageComponent>(mWindow);
icon->setImage(inputIcon[i]);
icon->setColorShift(0x777777FF);
icon->setResize(0, Font::get(FONT_SIZE_MEDIUM)->getLetterHeight() * 1.25f);
row.addElement(icon, false);
// spacer between icon and text
auto spacer = std::make_shared<GuiComponent>(mWindow);
spacer->setSize(16, 0);
row.addElement(spacer, false);
auto text = std::make_shared<TextComponent>(mWindow, inputDispName[i], Font::get(FONT_SIZE_MEDIUM), 0x777777FF);
row.addElement(text, true);
auto mapping = std::make_shared<TextComponent>(mWindow, "-NOT DEFINED-", Font::get(FONT_SIZE_MEDIUM, FONT_PATH_LIGHT), 0x999999FF, ALIGN_RIGHT);
setNotDefined(mapping); // overrides text and color set above
row.addElement(mapping, true);
mMappings.push_back(mapping);
row.input_handler = [this, i, mapping](InputConfig* config, Input input) -> bool
{
// ignore input not from our target device
if(config != mTargetConfig)
return false;
// if we're not configuring, start configuring when A is pressed
if(!mConfiguringRow)
{
if(config->isMappedTo("a", input) && input.value)
{
mList->stopScrolling();
mConfiguringRow = true;
setPress(mapping);
return true;
}
// we're not configuring and they didn't press A to start, so ignore this
return false;
}
// we are configuring
if(input.value != 0)
{
// input down
// if we're already holding something, ignore this, otherwise plan to map this input
if(mHoldingInput)
return true;
mHoldingInput = true;
mHeldInput = input;
mHeldTime = 0;
mHeldInputId = i;
return true;
}else{
// input up
// make sure we were holding something and we let go of what we were previously holding
if(!mHoldingInput || mHeldInput.device != input.device || mHeldInput.id != input.id || mHeldInput.type != input.type)
return true;
mHoldingInput = false;
if(assign(mHeldInput, i))
rowDone(); // if successful, move cursor/stop configuring - if not, we'll just try again
return true;
}
};
mList->addRow(row);
}
// only show "HOLD TO SKIP" if this input is skippable
mList->setCursorChangedCallback([this](CursorState state) {
bool skippable = inputSkippable[mList->getCursorId()];
mSubtitle2->setOpacity(skippable * 255);
});
// make the first one say "PRESS ANYTHING" if we're re-configuring everything
if(mConfiguringAll)
setPress(mMappings.front());
// buttons
std::vector< std::shared_ptr<ButtonComponent> > buttons;
buttons.push_back(std::make_shared<ButtonComponent>(mWindow, "OK", "ok", [this, okCallback] {
InputManager::getInstance()->writeDeviceConfig(mTargetConfig); // save
InputManager::getInstance()->doOnFinish(); // execute possible onFinish commands
if(okCallback)
okCallback();
delete this;
}));
mButtonGrid = makeButtonGrid(mWindow, buttons);
mGrid.setEntry(mButtonGrid, Vector2i(0, 6), true, false);
setSize(Renderer::getScreenWidth() * 0.6f, Renderer::getScreenHeight() * 0.75f);
setPosition((Renderer::getScreenWidth() - mSize.x()) / 2, (Renderer::getScreenHeight() - mSize.y()) / 2);
}
void GuiInputConfig::onSizeChanged()
{
mBackground.fitTo(mSize, Vector3f::Zero(), Vector2f(-32, -32));
// update grid
mGrid.setSize(mSize);
//mGrid.setRowHeightPerc(0, 0.025f);
mGrid.setRowHeightPerc(1, mTitle->getFont()->getHeight()*0.75f / mSize.y());
mGrid.setRowHeightPerc(2, mSubtitle1->getFont()->getHeight() / mSize.y());
mGrid.setRowHeightPerc(3, mSubtitle2->getFont()->getHeight() / mSize.y());
//mGrid.setRowHeightPerc(4, 0.03f);
mGrid.setRowHeightPerc(5, (mList->getRowHeight(0) * 5 + 2) / mSize.y());
mGrid.setRowHeightPerc(6, mButtonGrid->getSize().y() / mSize.y());
mBusyAnim.setSize(mSize);
}
void GuiInputConfig::update(int deltaTime)
{
if(mConfiguringRow && mHoldingInput && inputSkippable[mHeldInputId])
{
int prevSec = mHeldTime / 1000;
mHeldTime += deltaTime;
int curSec = mHeldTime / 1000;
if(mHeldTime >= HOLD_TO_SKIP_MS)
{
setNotDefined(mMappings.at(mHeldInputId));
clearAssignment(mHeldInputId);
mHoldingInput = false;
rowDone();
}else{
if(prevSec != curSec)
{
// crossed the second boundary, update text
const auto& text = mMappings.at(mHeldInputId);
std::stringstream ss;
ss << "HOLD FOR " << HOLD_TO_SKIP_MS/1000 - curSec << "S TO SKIP";
text->setText(ss.str());
text->setColor(0x777777FF);
}
}
}
}
// move cursor to the next thing if we're configuring all,
// or come out of "configure mode" if we were only configuring one row
void GuiInputConfig::rowDone()
{
if(mConfiguringAll)
{
if(!mList->moveCursor(1)) // try to move to the next one
{
// at bottom of list, done
mConfiguringAll = false;
mConfiguringRow = false;
mGrid.moveCursor(Vector2i(0, 1));
}else{
// on another one
setPress(mMappings.at(mList->getCursorId()));
}
}else{
// only configuring one row, so stop
mConfiguringRow = false;
}
}
void GuiInputConfig::setPress(const std::shared_ptr<TextComponent>& text)
{
text->setText("PRESS ANYTHING");
text->setColor(0x656565FF);
}
void GuiInputConfig::setNotDefined(const std::shared_ptr<TextComponent>& text)
{
text->setText("-NOT DEFINED-");
text->setColor(0x999999FF);
}
void GuiInputConfig::setAssignedTo(const std::shared_ptr<TextComponent>& text, Input input)
{
text->setText(strToUpper(input.string()));
text->setColor(0x777777FF);
}
void GuiInputConfig::error(const std::shared_ptr<TextComponent>& text, const std::string& msg)
{
text->setText("ALREADY TAKEN");
text->setColor(0x656565FF);
}
bool GuiInputConfig::assign(Input input, int inputId)
{
// input is from InputConfig* mTargetConfig
// if this input is mapped to something other than "nothing" or the current row, error
// (if it's the same as what it was before, allow it)
if(mTargetConfig->getMappedTo(input).size() > 0 && !mTargetConfig->isMappedTo(inputName[inputId], input))
{
error(mMappings.at(inputId), "Already mapped!");
return false;
}
setAssignedTo(mMappings.at(inputId), input);
input.configured = true;
mTargetConfig->mapInput(inputName[inputId], input);
LOG(LogInfo) << " Mapping [" << input.string() << "] -> " << inputName[inputId];
return true;
}
void GuiInputConfig::clearAssignment(int inputId)
{
mTargetConfig->unmapInput(inputName[inputId]);
}<commit_msg>rename buttons to avoid confusion (bottom -> shoulder / top -> trigger).<commit_after>#include "guis/GuiInputConfig.h"
#include "Window.h"
#include "Log.h"
#include "components/TextComponent.h"
#include "components/ImageComponent.h"
#include "components/MenuComponent.h"
#include "components/ButtonComponent.h"
#include "Util.h"
// static const int inputCount = 10;
// static const char* inputName[inputCount] = { "Up", "Down", "Left", "Right", "A", "B", "Start", "Select", "PageUp", "PageDown" };
// static const bool inputSkippable[inputCount] = { false, false, false, false, false, false, false, false, true, true };
// static const char* inputDispName[inputCount] = { "UP", "DOWN", "LEFT", "RIGHT", "A", "B", "START", "SELECT", "PAGE UP", "PAGE DOWN" };
// static const char* inputIcon[inputCount] = { ":/help/dpad_up.svg", ":/help/dpad_down.svg", ":/help/dpad_left.svg", ":/help/dpad_right.svg",
// ":/help/button_a.svg", ":/help/button_b.svg", ":/help/button_start.svg", ":/help/button_select.svg",
// ":/help/button_l.svg", ":/help/button_r.svg" };
static const int inputCount = 24;
static const char* inputName[inputCount] =
{
"Up",
"Down",
"Left",
"Right",
"Start",
"Select",
"A",
"B",
"X",
"Y",
"LeftShoulder",
"RightShoulder",
"LeftTrigger",
"RightTrigger",
"LeftThumb",
"RightThumb",
"LeftAnalogUp",
"LeftAnalogDown",
"LeftAnalogLeft",
"LeftAnalogRight",
"RightAnalogUp",
"RightAnalogDown",
"RightAnalogLeft",
"RightAnalogRight"
};
static const bool inputSkippable[inputCount] =
{
false,
false,
false,
false,
true,
true,
false,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true
};
static const char* inputDispName[inputCount] =
{
"D-PAD UP",
"D-PAD DOWN",
"D-PAD LEFT",
"D-PAD RIGHT",
"START",
"SELECT",
"A",
"B",
"X",
"Y",
"LEFT SHOULDER",
"RIGHT SHOULDER",
"LEFT TRIGGER",
"RIGHT TRIGGER",
"LEFT THUMB",
"RIGHT THUMB",
"LEFT ANALOG UP",
"LEFT ANALOG DOWN",
"LEFT ANALOG LEFT",
"LEFT ANALOG RIGHT",
"RIGHT ANALOG UP",
"RIGHT ANALOG DOWN",
"RIGHT ANALOG LEFT",
"RIGHT ANALOG RIGHT"
};
static const char* inputIcon[inputCount] =
{
":/help/dpad_up.svg",
":/help/dpad_down.svg",
":/help/dpad_left.svg",
":/help/dpad_right.svg",
":/help/button_start.svg",
":/help/button_select.svg",
":/help/button_a.svg",
":/help/button_b.svg",
":/help/button_x.svg",
":/help/button_y.svg",
":/help/button_l.svg",
":/help/button_r.svg",
":/help/button_l.svg",
":/help/button_r.svg",
":/help/analog_thumb.svg",
":/help/analog_thumb.svg",
":/help/analog_up.svg",
":/help/analog_down.svg",
":/help/analog_left.svg",
":/help/analog_right.svg",
":/help/analog_up.svg",
":/help/analog_down.svg",
":/help/analog_left.svg",
":/help/analog_right.svg"
};
//MasterVolUp and MasterVolDown are also hooked up, but do not appear on this screen.
//If you want, you can manually add them to es_input.cfg.
using namespace Eigen;
#define HOLD_TO_SKIP_MS 1000
GuiInputConfig::GuiInputConfig(Window* window, InputConfig* target, bool reconfigureAll, const std::function<void()>& okCallback) : GuiComponent(window),
mBackground(window, ":/frame.png"), mGrid(window, Vector2i(1, 7)),
mTargetConfig(target), mHoldingInput(false), mBusyAnim(window)
{
LOG(LogInfo) << "Configuring device " << target->getDeviceId() << " (" << target->getDeviceName() << ").";
if(reconfigureAll)
target->clear();
mConfiguringAll = reconfigureAll;
mConfiguringRow = mConfiguringAll;
addChild(&mBackground);
addChild(&mGrid);
// 0 is a spacer row
mGrid.setEntry(std::make_shared<GuiComponent>(mWindow), Vector2i(0, 0), false);
mTitle = std::make_shared<TextComponent>(mWindow, "CONFIGURING", Font::get(FONT_SIZE_LARGE), 0x555555FF, ALIGN_CENTER);
mGrid.setEntry(mTitle, Vector2i(0, 1), false, true);
std::stringstream ss;
if(target->getDeviceId() == DEVICE_KEYBOARD)
ss << "KEYBOARD";
else
ss << "GAMEPAD " << (target->getDeviceId() + 1);
mSubtitle1 = std::make_shared<TextComponent>(mWindow, strToUpper(ss.str()), Font::get(FONT_SIZE_MEDIUM), 0x555555FF, ALIGN_CENTER);
mGrid.setEntry(mSubtitle1, Vector2i(0, 2), false, true);
mSubtitle2 = std::make_shared<TextComponent>(mWindow, "HOLD ANY BUTTON TO SKIP", Font::get(FONT_SIZE_SMALL), 0x99999900, ALIGN_CENTER);
mGrid.setEntry(mSubtitle2, Vector2i(0, 3), false, true);
// 4 is a spacer row
mList = std::make_shared<ComponentList>(mWindow);
mGrid.setEntry(mList, Vector2i(0, 5), true, true);
for(int i = 0; i < inputCount; i++)
{
ComponentListRow row;
// icon
auto icon = std::make_shared<ImageComponent>(mWindow);
icon->setImage(inputIcon[i]);
icon->setColorShift(0x777777FF);
icon->setResize(0, Font::get(FONT_SIZE_MEDIUM)->getLetterHeight() * 1.25f);
row.addElement(icon, false);
// spacer between icon and text
auto spacer = std::make_shared<GuiComponent>(mWindow);
spacer->setSize(16, 0);
row.addElement(spacer, false);
auto text = std::make_shared<TextComponent>(mWindow, inputDispName[i], Font::get(FONT_SIZE_MEDIUM), 0x777777FF);
row.addElement(text, true);
auto mapping = std::make_shared<TextComponent>(mWindow, "-NOT DEFINED-", Font::get(FONT_SIZE_MEDIUM, FONT_PATH_LIGHT), 0x999999FF, ALIGN_RIGHT);
setNotDefined(mapping); // overrides text and color set above
row.addElement(mapping, true);
mMappings.push_back(mapping);
row.input_handler = [this, i, mapping](InputConfig* config, Input input) -> bool
{
// ignore input not from our target device
if(config != mTargetConfig)
return false;
// if we're not configuring, start configuring when A is pressed
if(!mConfiguringRow)
{
if(config->isMappedTo("a", input) && input.value)
{
mList->stopScrolling();
mConfiguringRow = true;
setPress(mapping);
return true;
}
// we're not configuring and they didn't press A to start, so ignore this
return false;
}
// we are configuring
if(input.value != 0)
{
// input down
// if we're already holding something, ignore this, otherwise plan to map this input
if(mHoldingInput)
return true;
mHoldingInput = true;
mHeldInput = input;
mHeldTime = 0;
mHeldInputId = i;
return true;
}else{
// input up
// make sure we were holding something and we let go of what we were previously holding
if(!mHoldingInput || mHeldInput.device != input.device || mHeldInput.id != input.id || mHeldInput.type != input.type)
return true;
mHoldingInput = false;
if(assign(mHeldInput, i))
rowDone(); // if successful, move cursor/stop configuring - if not, we'll just try again
return true;
}
};
mList->addRow(row);
}
// only show "HOLD TO SKIP" if this input is skippable
mList->setCursorChangedCallback([this](CursorState state) {
bool skippable = inputSkippable[mList->getCursorId()];
mSubtitle2->setOpacity(skippable * 255);
});
// make the first one say "PRESS ANYTHING" if we're re-configuring everything
if(mConfiguringAll)
setPress(mMappings.front());
// buttons
std::vector< std::shared_ptr<ButtonComponent> > buttons;
buttons.push_back(std::make_shared<ButtonComponent>(mWindow, "OK", "ok", [this, okCallback] {
InputManager::getInstance()->writeDeviceConfig(mTargetConfig); // save
InputManager::getInstance()->doOnFinish(); // execute possible onFinish commands
if(okCallback)
okCallback();
delete this;
}));
mButtonGrid = makeButtonGrid(mWindow, buttons);
mGrid.setEntry(mButtonGrid, Vector2i(0, 6), true, false);
setSize(Renderer::getScreenWidth() * 0.6f, Renderer::getScreenHeight() * 0.75f);
setPosition((Renderer::getScreenWidth() - mSize.x()) / 2, (Renderer::getScreenHeight() - mSize.y()) / 2);
}
void GuiInputConfig::onSizeChanged()
{
mBackground.fitTo(mSize, Vector3f::Zero(), Vector2f(-32, -32));
// update grid
mGrid.setSize(mSize);
//mGrid.setRowHeightPerc(0, 0.025f);
mGrid.setRowHeightPerc(1, mTitle->getFont()->getHeight()*0.75f / mSize.y());
mGrid.setRowHeightPerc(2, mSubtitle1->getFont()->getHeight() / mSize.y());
mGrid.setRowHeightPerc(3, mSubtitle2->getFont()->getHeight() / mSize.y());
//mGrid.setRowHeightPerc(4, 0.03f);
mGrid.setRowHeightPerc(5, (mList->getRowHeight(0) * 5 + 2) / mSize.y());
mGrid.setRowHeightPerc(6, mButtonGrid->getSize().y() / mSize.y());
mBusyAnim.setSize(mSize);
}
void GuiInputConfig::update(int deltaTime)
{
if(mConfiguringRow && mHoldingInput && inputSkippable[mHeldInputId])
{
int prevSec = mHeldTime / 1000;
mHeldTime += deltaTime;
int curSec = mHeldTime / 1000;
if(mHeldTime >= HOLD_TO_SKIP_MS)
{
setNotDefined(mMappings.at(mHeldInputId));
clearAssignment(mHeldInputId);
mHoldingInput = false;
rowDone();
}else{
if(prevSec != curSec)
{
// crossed the second boundary, update text
const auto& text = mMappings.at(mHeldInputId);
std::stringstream ss;
ss << "HOLD FOR " << HOLD_TO_SKIP_MS/1000 - curSec << "S TO SKIP";
text->setText(ss.str());
text->setColor(0x777777FF);
}
}
}
}
// move cursor to the next thing if we're configuring all,
// or come out of "configure mode" if we were only configuring one row
void GuiInputConfig::rowDone()
{
if(mConfiguringAll)
{
if(!mList->moveCursor(1)) // try to move to the next one
{
// at bottom of list, done
mConfiguringAll = false;
mConfiguringRow = false;
mGrid.moveCursor(Vector2i(0, 1));
}else{
// on another one
setPress(mMappings.at(mList->getCursorId()));
}
}else{
// only configuring one row, so stop
mConfiguringRow = false;
}
}
void GuiInputConfig::setPress(const std::shared_ptr<TextComponent>& text)
{
text->setText("PRESS ANYTHING");
text->setColor(0x656565FF);
}
void GuiInputConfig::setNotDefined(const std::shared_ptr<TextComponent>& text)
{
text->setText("-NOT DEFINED-");
text->setColor(0x999999FF);
}
void GuiInputConfig::setAssignedTo(const std::shared_ptr<TextComponent>& text, Input input)
{
text->setText(strToUpper(input.string()));
text->setColor(0x777777FF);
}
void GuiInputConfig::error(const std::shared_ptr<TextComponent>& text, const std::string& msg)
{
text->setText("ALREADY TAKEN");
text->setColor(0x656565FF);
}
bool GuiInputConfig::assign(Input input, int inputId)
{
// input is from InputConfig* mTargetConfig
// if this input is mapped to something other than "nothing" or the current row, error
// (if it's the same as what it was before, allow it)
if(mTargetConfig->getMappedTo(input).size() > 0 && !mTargetConfig->isMappedTo(inputName[inputId], input))
{
error(mMappings.at(inputId), "Already mapped!");
return false;
}
setAssignedTo(mMappings.at(inputId), input);
input.configured = true;
mTargetConfig->mapInput(inputName[inputId], input);
LOG(LogInfo) << " Mapping [" << input.string() << "] -> " << inputName[inputId];
return true;
}
void GuiInputConfig::clearAssignment(int inputId)
{
mTargetConfig->unmapInput(inputName[inputId]);
}<|endoftext|> |
<commit_before>/*
* Copyright (C) 2013
* Alessio Sclocco <a.sclocco@vu.nl>
*
* 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 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cmath>
#include <cstring>
using std::cout;
using std::cerr;
using std::endl;
using std::fixed;
using std::setprecision;
using std::ofstream;
using std::ceil;
using std::pow;
#include <ArgumentList.hpp>
#include <InitializeOpenCL.hpp>
#include <CLData.hpp>
#include <Exceptions.hpp>
#include <Copy.hpp>
#include <utils.hpp>
using isa::utils::ArgumentList;
using isa::OpenCL::initializeOpenCL;
using isa::OpenCL::CLData;
using isa::Exceptions::OpenCLError;
using isa::Benchmarks::Copy;
using isa::utils::same;
const unsigned int nrIterations = 10;
int main(int argc, char * argv[]) {
unsigned int oclPlatform = 0;
unsigned int oclDevice = 0;
unsigned int arrayDim = 0;
unsigned int maxThreads = 0;
// Parse command line
if ( argc != 7 ) {
cerr << "Usage: " << argv[0] << " -opencl_platform <opencl_platform> -opencl_device <opencl_device> -m <max_threads>" << endl;
return 1;
}
ArgumentList commandLine(argc, argv);
try {
oclPlatform = commandLine.getSwitchArgument< unsigned int >("-opencl_platform");
oclDevice = commandLine.getSwitchArgument< unsigned int >("-opencl_device");
maxThreads = commandLine.getSwitchArgument< unsigned int >("-max_threads");
} catch ( exception & err ) {
cerr << err.what() << endl;
return 1;
}
// Initialize OpenCL
vector< cl::Platform > * oclPlatforms = new vector< cl::Platform >();
cl::Context * oclContext = new cl::Context();
vector< cl::Device > * oclDevices = new vector< cl::Device >();
vector< vector< cl::CommandQueue > > * oclQueues = new vector< vector< cl::CommandQueue > >();
try {
initializeOpenCL(oclPlatform, 1, oclPlatforms, oclContext, oclDevices, oclQueues);
} catch ( OpenCLError err ) {
cerr << err.what() << endl;
return 1;
}
(oclDevices->at(oclDevice)).getInfo< unsigned int >(CL_DEVICE_MAX_MEM_ALLOC_SIZE, &arrayDim);
arrayDim /= 4;
CLData< float > * A = new CLData< float >("A", true);
CLData< float > * B = new CLData< float >("B", true);
A->setCLContext(oclContext);
A->setCLQueue(&(oclQueues->at(oclDevice)[0]));
A->allocateHostData(arrayDim);
B->setCLContext(oclContext);
B->setCLQueue(&(oclQueues->at(oclDevice)[0]));
B->allocateHostData(arrayDim);
try {
A->setDeviceWriteOnly();
A->allocateDeviceData();
B->setDeviceWriteOnly();
B->allocateDeviceData();
} catch ( OpenCLError err ) {
cerr << err.what() << endl;
return 1;
}
cout << fixed << setprecision(3) << endl;
for (unsigned int threads0 = 2; threads0 <= maxThreads; threads0 *= 2 ) {
for (unsigned int threads1 = 1; threads1 <= 32; threads1++ ) {
if ( (threads0 * threads1) > maxThreads ) {
continue;
}
Copy< float > copy = Copy< float >("float");
try {
copy.bindOpenCL(oclContext, &(oclDevices->at(oclDevice)), &(oclQueues->at(oclDevice)[0]));
copy.setNrThreads(arrayDim);
copy.setNrThreadsPerBlock(threads0);
copy.setNrRows(threads1);
copy.generateCode();
B->copyHostToDevice(true);
copy(A,B);
(copy.getTimer()).reset();
for ( unsigned int iter = 0; iter < nrIterations; iter++ ) {
copy(A, B);
}
} catch ( OpenCLError err ) {
cerr << err.what() << endl;
return 1;
}
cout << threads0 << " " << threads1 << " " << copy.getGB() / (copy.getTimer()).getAverageTime() << endl;
}
}
cout << endl;
return 0;
}
<commit_msg>Checking memory and using the right cl::Device::getInfo().<commit_after>/*
* Copyright (C) 2013
* Alessio Sclocco <a.sclocco@vu.nl>
*
* 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 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cmath>
#include <cstring>
using std::cout;
using std::cerr;
using std::endl;
using std::fixed;
using std::setprecision;
using std::ofstream;
using std::ceil;
using std::pow;
#include <ArgumentList.hpp>
#include <InitializeOpenCL.hpp>
#include <CLData.hpp>
#include <Exceptions.hpp>
#include <Copy.hpp>
#include <utils.hpp>
using isa::utils::ArgumentList;
using isa::OpenCL::initializeOpenCL;
using isa::OpenCL::CLData;
using isa::Exceptions::OpenCLError;
using isa::Benchmarks::Copy;
using isa::utils::same;
const unsigned int nrIterations = 10;
int main(int argc, char * argv[]) {
unsigned int oclPlatform = 0;
unsigned int oclDevice = 0;
unsigned int arrayDim = 0;
unsigned int maxThreads = 0;
// Parse command line
if ( argc != 7 ) {
cerr << "Usage: " << argv[0] << " -opencl_platform <opencl_platform> -opencl_device <opencl_device> -m <max_threads>" << endl;
return 1;
}
ArgumentList commandLine(argc, argv);
try {
oclPlatform = commandLine.getSwitchArgument< unsigned int >("-opencl_platform");
oclDevice = commandLine.getSwitchArgument< unsigned int >("-opencl_device");
maxThreads = commandLine.getSwitchArgument< unsigned int >("-max_threads");
} catch ( exception & err ) {
cerr << err.what() << endl;
return 1;
}
// Initialize OpenCL
vector< cl::Platform > * oclPlatforms = new vector< cl::Platform >();
cl::Context * oclContext = new cl::Context();
vector< cl::Device > * oclDevices = new vector< cl::Device >();
vector< vector< cl::CommandQueue > > * oclQueues = new vector< vector< cl::CommandQueue > >();
try {
initializeOpenCL(oclPlatform, 1, oclPlatforms, oclContext, oclDevices, oclQueues);
} catch ( OpenCLError err ) {
cerr << err.what() << endl;
return 1;
}
arrayDim = (oclDevices->at(oclDevice)).getInfo< CL_DEVICE_MAX_MEM_ALLOC_SIZE >();
arrayDim /= 4;
CLData< float > * A = new CLData< float >("A", true);
CLData< float > * B = new CLData< float >("B", true);
A->setCLContext(oclContext);
A->setCLQueue(&(oclQueues->at(oclDevice)[0]));
A->allocateHostData(arrayDim);
B->setCLContext(oclContext);
B->setCLQueue(&(oclQueues->at(oclDevice)[0]));
B->allocateHostData(arrayDim);
try {
A->setDeviceWriteOnly();
A->allocateDeviceData();
B->setDeviceWriteOnly();
B->allocateDeviceData();
} catch ( OpenCLError err ) {
cerr << err.what() << endl;
return 1;
}
cout << fixed << setprecision(3) << endl;
for (unsigned int threads0 = 2; threads0 <= maxThreads; threads0 *= 2 ) {
for (unsigned int threads1 = 1; threads1 <= 32; threads1++ ) {
if ( (arrayDim / (threads0 * threads1) != 0) || ((threads0 * threads1) > maxThreads) ) {
continue;
}
Copy< float > copy = Copy< float >("float");
try {
copy.bindOpenCL(oclContext, &(oclDevices->at(oclDevice)), &(oclQueues->at(oclDevice)[0]));
copy.setNrThreads(arrayDim);
copy.setNrThreadsPerBlock(threads0);
copy.setNrRows(threads1);
copy.generateCode();
B->copyHostToDevice(true);
copy(A,B);
(copy.getTimer()).reset();
for ( unsigned int iter = 0; iter < nrIterations; iter++ ) {
copy(A, B);
}
} catch ( OpenCLError err ) {
cerr << err.what() << endl;
return 1;
}
cout << threads0 << " " << threads1 << " " << copy.getGB() / (copy.getTimer()).getAverageTime() << endl;
}
}
cout << endl;
return 0;
}
<|endoftext|> |
<commit_before>#include "main.h"
#include "neuralnet/voting/poll.h"
#include "span.h"
#include "ui_interface.h"
#include "util.h"
#include <boost/algorithm/string/join.hpp>
using namespace NN;
namespace {
//!
//! \brief Parse the weight type from a legacy poll contract.
//!
//! \param value A numeric value extracted from the "<SHARETYPE>" field that
//! matches a value enumerated on \c PollWeightType.
//!
//! \return The matching weight type or the value of "unknown" when the string
//! does not contain a valid weight type number.
//!
PollWeightType ParseWeightType(const std::string& value)
{
try {
const uint32_t parsed = std::stoul(value);
if (parsed > Poll::WeightType::MAX) {
return PollWeightType::UNKNOWN;
}
return static_cast<PollWeightType>(parsed);
} catch (...) {
return PollWeightType::UNKNOWN;
}
}
//!
//! \brief Parse the poll duration from a legacy poll contract.
//!
//! \param value A numeric value extracted from the "<DAYS>" field.
//!
//! \return The parsed number of days or zero when the string does not contain
//! a valid number.
//!
uint32_t ParseDurationDays(const std::string& value)
{
try {
return std::stoul(value);
} catch (...) {
return 0;
}
}
//!
//! \brief Parse the set of available choices from a legacy poll contract.
//!
//! \param value A semicolon-delimited string of labels extracted from the
//! "<ANSWERS>" field. Each label represents one choice.
//!
//! \return The parsed set of poll choices.
//!
Poll::ChoiceList ParseChoices(const std::string& value)
{
Poll::ChoiceList choices;
for (auto& label : split(value, ";")) {
choices.Add(std::move(label));
}
return choices;
}
//!
//! \brief Format the poll expiration timestamp for a legacy poll contract.
//!
//! \param poll The poll object to generate the expiration timestamp for.
//!
//! \return The string representation of the timestamp in seconds at which the
//! poll expires suitable for the "<EXPIRATION>" field of a legacy contract.
//!
std::string FormatLegacyExpiration(const Poll& poll)
{
return std::to_string(poll.m_timestamp + (poll.m_duration_days * 86400));
}
//!
//! \brief Poll choices to return for polls with a yes/no/abstain response type.
//!
const Poll::ChoiceList g_yes_no_abstain_choices(std::vector<Poll::Choice> {
{ "Yes" },
{ "No" },
{ "Abstain" },
});
} // Anonymous namespace
// -----------------------------------------------------------------------------
// Class: Poll
// -----------------------------------------------------------------------------
Poll::Poll()
: m_type(PollType::UNKNOWN)
, m_weight_type(PollWeightType::UNKNOWN)
, m_response_type(PollResponseType::UNKNOWN)
, m_duration_days(0)
, m_timestamp(0)
{
}
Poll::Poll(
PollType type,
PollWeightType weight_type,
PollResponseType response_type,
uint32_t duration_days,
std::string title,
std::string url,
std::string question,
ChoiceList choices,
int64_t timestamp)
: m_type(type)
, m_weight_type(weight_type)
, m_response_type(response_type)
, m_duration_days(duration_days)
, m_title(std::move(title))
, m_url(std::move(url))
, m_question(std::move(question))
, m_choices(std::move(choices))
, m_timestamp(timestamp)
{
}
Poll Poll::Parse(const std::string& contract)
{
return Poll(
PollType::SURVEY,
ParseWeightType(ExtractXML(contract, "<SHARETYPE>", "</SHARETYPE>")),
// Legacy contracts only behaved as multiple-choice polls:
PollResponseType::MULTIPLE_CHOICE,
ParseDurationDays(ExtractXML(contract, "<DAYS>", "</DAYS>")),
ExtractXML(contract, "<TITLE>", "</TITLE>"),
ExtractXML(contract, "<URL>", "</URL>"),
ExtractXML(contract, "<QUESTION>", "</QUESTION>"),
ParseChoices(ExtractXML(contract, "<ANSWERS>", "</ANSWERS>")),
0);
}
bool Poll::WellFormed() const
{
return m_type != PollType::UNKNOWN
&& m_type != PollType::OUT_OF_BOUND
&& m_weight_type != PollWeightType::UNKNOWN
&& m_weight_type != PollWeightType::OUT_OF_BOUND
&& m_response_type != PollResponseType::UNKNOWN
&& m_response_type != PollResponseType::OUT_OF_BOUND
&& m_duration_days >= MIN_DURATION_DAYS
&& m_duration_days <= MAX_DURATION_DAYS
&& !m_title.empty()
&& !m_url.empty()
&& m_choices.WellFormed(m_response_type.Value());
}
bool Poll::WellFormed(const uint32_t version) const
{
if (!WellFormed()) {
return false;
}
// Version 2+ poll contracts in block version 11 and greater disallow the
// deprecated legacy vote weighing methods:
//
if (version >= 2) {
switch (m_weight_type.Value()) {
case PollWeightType::MAGNITUDE:
case PollWeightType::CPID_COUNT:
case PollWeightType::PARTICIPANT_COUNT:
return false;
default:
break;
}
}
return true;
}
bool Poll::IncludesMagnitudeWeight() const
{
return m_weight_type == PollWeightType::BALANCE_AND_MAGNITUDE
|| m_weight_type == PollWeightType::MAGNITUDE;
}
bool Poll::AllowsMultipleChoices() const
{
return m_response_type == PollResponseType::MULTIPLE_CHOICE;
}
int64_t Poll::Age(const int64_t now) const
{
return now - m_timestamp;
}
bool Poll::Expired(const int64_t now) const
{
return Age(now) > m_duration_days * 86400;
}
int64_t Poll::Expiration() const
{
return m_timestamp + (m_duration_days * 86400);
}
const Poll::ChoiceList& Poll::Choices() const
{
if (m_response_type == PollResponseType::YES_NO_ABSTAIN) {
return g_yes_no_abstain_choices;
}
return m_choices;
}
std::string Poll::ToString() const
{
return "<TITLE>" + m_title + "</TITLE>"
+ "<DAYS>" + std::to_string(m_duration_days) + "</DAYS>"
+ "<QUESTION>" + m_question + "</QUESTION>"
+ "<ANSWERS>" + m_choices.ToString() + "</ANSWERS>"
+ "<SHARETYPE>" + std::to_string(m_weight_type.Raw()) + "</SHARETYPE>"
+ "<URL>" + m_url + "</URL>"
+ "<EXPIRATION>" + FormatLegacyExpiration(*this) + "</EXPIRATION>";
}
std::string Poll::WeightTypeToString() const
{
switch (m_weight_type.Value()) {
case PollWeightType::UNKNOWN:
case PollWeightType::OUT_OF_BOUND: return _("Unknown");
case PollWeightType::MAGNITUDE: return _("Magnitude");
case PollWeightType::BALANCE: return _("Balance");
case PollWeightType::BALANCE_AND_MAGNITUDE: return _("Magnitude+Balance");
case PollWeightType::CPID_COUNT: return _("CPID Count");
case PollWeightType::PARTICIPANT_COUNT: return _("Participant Count");
}
assert(false); // Suppress warning
}
// -----------------------------------------------------------------------------
// Class: Poll::ChoiceList
// -----------------------------------------------------------------------------
using ChoiceList = Poll::ChoiceList;
using Choice = Poll::Choice;
ChoiceList::ChoiceList(std::vector<Choice> choices)
: m_choices(std::move(choices))
{
}
ChoiceList::const_iterator ChoiceList::begin() const
{
return m_choices.begin();
}
ChoiceList::const_iterator ChoiceList::end() const
{
return m_choices.end();
}
size_t ChoiceList::size() const
{
return m_choices.size();
}
bool ChoiceList::empty() const
{
return m_choices.empty();
}
bool ChoiceList::WellFormed(const PollResponseType response_type) const
{
if (response_type == PollResponseType::YES_NO_ABSTAIN) {
return m_choices.empty();
}
return !m_choices.empty()
&& m_choices.size() <= POLL_MAX_CHOICES_SIZE
&& std::all_of(
m_choices.begin(),
m_choices.end(),
[](const Choice& choice) { return choice.WellFormed(); });
}
bool ChoiceList::OffsetInRange(const size_t offset) const
{
return offset < m_choices.size();
}
bool ChoiceList::LabelExists(const std::string& label) const
{
return OffsetOf(label).operator bool();
}
boost::optional<uint8_t> ChoiceList::OffsetOf(const std::string& label) const
{
const auto iter = std::find_if(
m_choices.begin(),
m_choices.end(),
[&](const Choice& choice) { return choice.m_label == label; });
if (iter == m_choices.end()) {
return boost::none;
}
return std::distance(m_choices.begin(), iter);
}
const Choice* ChoiceList::At(const size_t offset) const
{
if (offset >= m_choices.size()) {
return nullptr;
}
return &m_choices[offset];
}
void ChoiceList::Add(std::string label)
{
m_choices.emplace_back(std::move(label));
}
std::string ChoiceList::ToString() const
{
std::string out;
auto iter = m_choices.begin();
if (iter != m_choices.end()) {
out += iter->m_label;
++iter;
}
for (; iter != m_choices.end(); ++iter) {
out += ";";
out += iter->m_label;
++iter;
}
return out;
}
<commit_msg>Remove double increment in loop<commit_after>#include "main.h"
#include "neuralnet/voting/poll.h"
#include "span.h"
#include "ui_interface.h"
#include "util.h"
#include <boost/algorithm/string/join.hpp>
using namespace NN;
namespace {
//!
//! \brief Parse the weight type from a legacy poll contract.
//!
//! \param value A numeric value extracted from the "<SHARETYPE>" field that
//! matches a value enumerated on \c PollWeightType.
//!
//! \return The matching weight type or the value of "unknown" when the string
//! does not contain a valid weight type number.
//!
PollWeightType ParseWeightType(const std::string& value)
{
try {
const uint32_t parsed = std::stoul(value);
if (parsed > Poll::WeightType::MAX) {
return PollWeightType::UNKNOWN;
}
return static_cast<PollWeightType>(parsed);
} catch (...) {
return PollWeightType::UNKNOWN;
}
}
//!
//! \brief Parse the poll duration from a legacy poll contract.
//!
//! \param value A numeric value extracted from the "<DAYS>" field.
//!
//! \return The parsed number of days or zero when the string does not contain
//! a valid number.
//!
uint32_t ParseDurationDays(const std::string& value)
{
try {
return std::stoul(value);
} catch (...) {
return 0;
}
}
//!
//! \brief Parse the set of available choices from a legacy poll contract.
//!
//! \param value A semicolon-delimited string of labels extracted from the
//! "<ANSWERS>" field. Each label represents one choice.
//!
//! \return The parsed set of poll choices.
//!
Poll::ChoiceList ParseChoices(const std::string& value)
{
Poll::ChoiceList choices;
for (auto& label : split(value, ";")) {
choices.Add(std::move(label));
}
return choices;
}
//!
//! \brief Format the poll expiration timestamp for a legacy poll contract.
//!
//! \param poll The poll object to generate the expiration timestamp for.
//!
//! \return The string representation of the timestamp in seconds at which the
//! poll expires suitable for the "<EXPIRATION>" field of a legacy contract.
//!
std::string FormatLegacyExpiration(const Poll& poll)
{
return std::to_string(poll.m_timestamp + (poll.m_duration_days * 86400));
}
//!
//! \brief Poll choices to return for polls with a yes/no/abstain response type.
//!
const Poll::ChoiceList g_yes_no_abstain_choices(std::vector<Poll::Choice> {
{ "Yes" },
{ "No" },
{ "Abstain" },
});
} // Anonymous namespace
// -----------------------------------------------------------------------------
// Class: Poll
// -----------------------------------------------------------------------------
Poll::Poll()
: m_type(PollType::UNKNOWN)
, m_weight_type(PollWeightType::UNKNOWN)
, m_response_type(PollResponseType::UNKNOWN)
, m_duration_days(0)
, m_timestamp(0)
{
}
Poll::Poll(
PollType type,
PollWeightType weight_type,
PollResponseType response_type,
uint32_t duration_days,
std::string title,
std::string url,
std::string question,
ChoiceList choices,
int64_t timestamp)
: m_type(type)
, m_weight_type(weight_type)
, m_response_type(response_type)
, m_duration_days(duration_days)
, m_title(std::move(title))
, m_url(std::move(url))
, m_question(std::move(question))
, m_choices(std::move(choices))
, m_timestamp(timestamp)
{
}
Poll Poll::Parse(const std::string& contract)
{
return Poll(
PollType::SURVEY,
ParseWeightType(ExtractXML(contract, "<SHARETYPE>", "</SHARETYPE>")),
// Legacy contracts only behaved as multiple-choice polls:
PollResponseType::MULTIPLE_CHOICE,
ParseDurationDays(ExtractXML(contract, "<DAYS>", "</DAYS>")),
ExtractXML(contract, "<TITLE>", "</TITLE>"),
ExtractXML(contract, "<URL>", "</URL>"),
ExtractXML(contract, "<QUESTION>", "</QUESTION>"),
ParseChoices(ExtractXML(contract, "<ANSWERS>", "</ANSWERS>")),
0);
}
bool Poll::WellFormed() const
{
return m_type != PollType::UNKNOWN
&& m_type != PollType::OUT_OF_BOUND
&& m_weight_type != PollWeightType::UNKNOWN
&& m_weight_type != PollWeightType::OUT_OF_BOUND
&& m_response_type != PollResponseType::UNKNOWN
&& m_response_type != PollResponseType::OUT_OF_BOUND
&& m_duration_days >= MIN_DURATION_DAYS
&& m_duration_days <= MAX_DURATION_DAYS
&& !m_title.empty()
&& !m_url.empty()
&& m_choices.WellFormed(m_response_type.Value());
}
bool Poll::WellFormed(const uint32_t version) const
{
if (!WellFormed()) {
return false;
}
// Version 2+ poll contracts in block version 11 and greater disallow the
// deprecated legacy vote weighing methods:
//
if (version >= 2) {
switch (m_weight_type.Value()) {
case PollWeightType::MAGNITUDE:
case PollWeightType::CPID_COUNT:
case PollWeightType::PARTICIPANT_COUNT:
return false;
default:
break;
}
}
return true;
}
bool Poll::IncludesMagnitudeWeight() const
{
return m_weight_type == PollWeightType::BALANCE_AND_MAGNITUDE
|| m_weight_type == PollWeightType::MAGNITUDE;
}
bool Poll::AllowsMultipleChoices() const
{
return m_response_type == PollResponseType::MULTIPLE_CHOICE;
}
int64_t Poll::Age(const int64_t now) const
{
return now - m_timestamp;
}
bool Poll::Expired(const int64_t now) const
{
return Age(now) > m_duration_days * 86400;
}
int64_t Poll::Expiration() const
{
return m_timestamp + (m_duration_days * 86400);
}
const Poll::ChoiceList& Poll::Choices() const
{
if (m_response_type == PollResponseType::YES_NO_ABSTAIN) {
return g_yes_no_abstain_choices;
}
return m_choices;
}
std::string Poll::ToString() const
{
return "<TITLE>" + m_title + "</TITLE>"
+ "<DAYS>" + std::to_string(m_duration_days) + "</DAYS>"
+ "<QUESTION>" + m_question + "</QUESTION>"
+ "<ANSWERS>" + m_choices.ToString() + "</ANSWERS>"
+ "<SHARETYPE>" + std::to_string(m_weight_type.Raw()) + "</SHARETYPE>"
+ "<URL>" + m_url + "</URL>"
+ "<EXPIRATION>" + FormatLegacyExpiration(*this) + "</EXPIRATION>";
}
std::string Poll::WeightTypeToString() const
{
switch (m_weight_type.Value()) {
case PollWeightType::UNKNOWN:
case PollWeightType::OUT_OF_BOUND: return _("Unknown");
case PollWeightType::MAGNITUDE: return _("Magnitude");
case PollWeightType::BALANCE: return _("Balance");
case PollWeightType::BALANCE_AND_MAGNITUDE: return _("Magnitude+Balance");
case PollWeightType::CPID_COUNT: return _("CPID Count");
case PollWeightType::PARTICIPANT_COUNT: return _("Participant Count");
}
assert(false); // Suppress warning
}
// -----------------------------------------------------------------------------
// Class: Poll::ChoiceList
// -----------------------------------------------------------------------------
using ChoiceList = Poll::ChoiceList;
using Choice = Poll::Choice;
ChoiceList::ChoiceList(std::vector<Choice> choices)
: m_choices(std::move(choices))
{
}
ChoiceList::const_iterator ChoiceList::begin() const
{
return m_choices.begin();
}
ChoiceList::const_iterator ChoiceList::end() const
{
return m_choices.end();
}
size_t ChoiceList::size() const
{
return m_choices.size();
}
bool ChoiceList::empty() const
{
return m_choices.empty();
}
bool ChoiceList::WellFormed(const PollResponseType response_type) const
{
if (response_type == PollResponseType::YES_NO_ABSTAIN) {
return m_choices.empty();
}
return !m_choices.empty()
&& m_choices.size() <= POLL_MAX_CHOICES_SIZE
&& std::all_of(
m_choices.begin(),
m_choices.end(),
[](const Choice& choice) { return choice.WellFormed(); });
}
bool ChoiceList::OffsetInRange(const size_t offset) const
{
return offset < m_choices.size();
}
bool ChoiceList::LabelExists(const std::string& label) const
{
return OffsetOf(label).operator bool();
}
boost::optional<uint8_t> ChoiceList::OffsetOf(const std::string& label) const
{
const auto iter = std::find_if(
m_choices.begin(),
m_choices.end(),
[&](const Choice& choice) { return choice.m_label == label; });
if (iter == m_choices.end()) {
return boost::none;
}
return std::distance(m_choices.begin(), iter);
}
const Choice* ChoiceList::At(const size_t offset) const
{
if (offset >= m_choices.size()) {
return nullptr;
}
return &m_choices[offset];
}
void ChoiceList::Add(std::string label)
{
m_choices.emplace_back(std::move(label));
}
std::string ChoiceList::ToString() const
{
std::string out;
auto iter = m_choices.begin();
if (iter != m_choices.end()) {
out += iter->m_label;
++iter;
}
for (; iter != m_choices.end(); ++iter) {
out += ";";
out += iter->m_label;
}
return out;
}
<|endoftext|> |
<commit_before>#ifndef __DATA_HPP_INCLUDED
#define __DATA_HPP_INCLUDED
#include "Mesh.hpp"
#include "Matrix.hpp"
#include <map>
class local_K_f
{
public:
double val_K[576];
double val_f[24];
int ieq[24];
int nDOF;
};
class Interfaces
{
public:
int IdNeighSub;
vector <int> dofs;
};
class Data
{
public:
Data();
~Data();
void fe_assemb_local_K_f(Mesh &);
void feti_symbolic(Mesh &, vector <Matrix> &);
void feti_numeric(Mesh &, vector <Matrix> &, vector <Vector> &);
void feti_numeric_element(Matrix &, Vector &, local_K_f &);
void stf_mtrx_solid45(local_K_f &, Point *, double ,double);
static double inverse_matrix_3x3(double *, double *);
vector < local_K_f > local_K_f_clust;
vector < vector <int> > l2g;
vector < map<int,int> > g2l;
vector < vector <int> > selectorOfElemPartitId;
vector < map < int,vector < int > > > interface;
vector < vector < Interfaces > > interfaces;
void create_analytic_ker_K(Mesh &, vector <Matrix> &);
};
#endif // __DATA_HPP_INCLUDED
<commit_msg>'fe_assemb_locak_K_f': ratio between materials<commit_after>#ifndef __DATA_HPP_INCLUDED
#define __DATA_HPP_INCLUDED
#include "Mesh.hpp"
#include "Matrix.hpp"
#include <map>
class local_K_f
{
public:
double val_K[576];
double val_f[24];
int ieq[24];
int nDOF;
};
class Interfaces
{
public:
int IdNeighSub;
vector <int> dofs;
};
class Data
{
public:
Data();
~Data();
void fe_assemb_local_K_f(Mesh &, map <string, string> &);
void feti_symbolic(Mesh &, vector <Matrix> &);
void feti_numeric(Mesh &, vector <Matrix> &, vector <Vector> &);
void feti_numeric_element(Matrix &, Vector &, local_K_f &);
void stf_mtrx_solid45(local_K_f &, Point *, double ,double);
static double inverse_matrix_3x3(double *, double *);
vector < local_K_f > local_K_f_clust;
vector < vector <int> > l2g;
vector < map<int,int> > g2l;
vector < vector <int> > selectorOfElemPartitId;
vector < map < int,vector < int > > > interface;
vector < vector < Interfaces > > interfaces;
void create_analytic_ker_K(Mesh &, vector <Matrix> &);
};
#endif // __DATA_HPP_INCLUDED
<|endoftext|> |
<commit_before>#include <osg/Camera>
#include <osg/io_utils>
#include <osg/Notify>
#include <osgDB/Registry>
#include <osgDB/Input>
#include <osgDB/Output>
#include "Matrix.h"
using namespace osg;
using namespace osgDB;
// forward declare functions to use later.
bool Camera_readLocalData(Object& obj, Input& fr);
bool Camera_writeLocalData(const Object& obj, Output& fw);
bool Camera_matchBufferComponentStr(const char* str,Camera::BufferComponent& buffer);
const char* Camera_getBufferComponentStr(Camera::BufferComponent buffer);
// register the read and write functions with the osgDB::Registry.
RegisterDotOsgWrapperProxy g_CameraProxy
(
new osg::Camera,
"Camera",
"Object Node Transform Camera Group",
&Camera_readLocalData,
&Camera_writeLocalData,
DotOsgWrapper::READ_AND_WRITE
);
// register the read and write functions with the osgDB::Registry.
RegisterDotOsgWrapperProxy g_CameraNodeProxy
(
new osg::Camera,
"CameraNode",
"Object Node Transform CameraNode Group",
&Camera_readLocalData,
&Camera_writeLocalData,
DotOsgWrapper::READ_AND_WRITE
);
bool Camera_readLocalData(Object& obj, Input& fr)
{
bool iteratorAdvanced = false;
Camera& camera = static_cast<Camera&>(obj);
if (fr.matchSequence("clearColor %f %f %f %f"))
{
Vec4 color;
fr[1].getFloat(color[0]);
fr[2].getFloat(color[1]);
fr[3].getFloat(color[2]);
fr[4].getFloat(color[3]);
camera.setClearColor(color);
fr +=5 ;
iteratorAdvanced = true;
};
if (fr.matchSequence("clearMask %i"))
{
unsigned int value;
fr[1].getUInt(value);
camera.setClearMask(value);
fr += 2;
iteratorAdvanced = true;
}
osg::ref_ptr<osg::StateAttribute> attribute;
while((attribute=fr.readStateAttribute())!=NULL)
{
osg::Viewport* viewport = dynamic_cast<osg::Viewport*>(attribute.get());
if (viewport) camera.setViewport(viewport);
else
{
osg::ColorMask* colormask = dynamic_cast<osg::ColorMask*>(attribute.get());
camera.setColorMask(colormask);
}
}
if (fr.matchSequence("transformOrder %w"))
{
if (fr[1].matchWord("PRE_MULTIPLY")) camera.setTransformOrder(osg::Camera::PRE_MULTIPLY);
else if (fr[1].matchWord("POST_MULTIPLY")) camera.setTransformOrder(osg::Camera::POST_MULTIPLY);
// the following are for backwards compatibility.
else if (fr[1].matchWord("PRE_MULTIPLE")) camera.setTransformOrder(osg::Camera::PRE_MULTIPLY);
else if (fr[1].matchWord("POST_MULTIPLE")) camera.setTransformOrder(osg::Camera::POST_MULTIPLY);
fr += 2;
iteratorAdvanced = true;
}
Matrix matrix;
if (readMatrix(matrix,fr,"ProjectionMatrix"))
{
camera.setProjectionMatrix(matrix);
iteratorAdvanced = true;
}
if (readMatrix(matrix,fr,"ViewMatrix"))
{
camera.setViewMatrix(matrix);
iteratorAdvanced = true;
}
if (fr.matchSequence("renderOrder %w"))
{
if (fr[1].matchWord("PRE_RENDER")) camera.setRenderOrder(osg::Camera::PRE_RENDER);
else if (fr[1].matchWord("NESTED_RENDER")) camera.setRenderOrder(osg::Camera::NESTED_RENDER);
else if (fr[1].matchWord("POST_RENDER")) camera.setRenderOrder(osg::Camera::POST_RENDER);
fr += 2;
iteratorAdvanced = true;
}
if (fr.matchSequence("renderTargetImplementation %w"))
{
osg::Camera::RenderTargetImplementation implementation = osg::Camera::FRAME_BUFFER;
if (fr[1].matchWord("FRAME_BUFFER_OBJECT")) implementation = osg::Camera::FRAME_BUFFER_OBJECT;
else if (fr[1].matchWord("PIXEL_BUFFER_RTT")) implementation = osg::Camera::PIXEL_BUFFER_RTT;
else if (fr[1].matchWord("PIXEL_BUFFER")) implementation = osg::Camera::PIXEL_BUFFER;
else if (fr[1].matchWord("FRAME_BUFFER")) implementation = osg::Camera::FRAME_BUFFER;
else if (fr[1].matchWord("SEPERATE_WINDOW")) implementation = osg::Camera::SEPERATE_WINDOW;
camera.setRenderTargetImplementation(implementation);
fr += 2;
iteratorAdvanced = true;
}
if (fr.matchSequence("renderTargetImplementation %w"))
{
osg::Camera::RenderTargetImplementation fallback = camera.getRenderTargetFallback();
if (fr[1].matchWord("FRAME_BUFFER_OBJECT")) fallback = osg::Camera::FRAME_BUFFER_OBJECT;
else if (fr[1].matchWord("PIXEL_BUFFER_RTT")) fallback = osg::Camera::PIXEL_BUFFER_RTT;
else if (fr[1].matchWord("PIXEL_BUFFER")) fallback = osg::Camera::PIXEL_BUFFER;
else if (fr[1].matchWord("FRAME_BUFFER")) fallback = osg::Camera::FRAME_BUFFER;
else if (fr[1].matchWord("SEPERATE_WINDOW")) fallback = osg::Camera::SEPERATE_WINDOW;
camera.setRenderTargetImplementation(camera.getRenderTargetImplementation(), fallback);
fr += 2;
iteratorAdvanced = true;
}
if (fr.matchSequence("bufferComponent %w {"))
{
int entry = fr[1].getNoNestedBrackets();
Camera::BufferComponent buffer;
Camera_matchBufferComponentStr(fr[1].getStr(),buffer);
fr += 3;
Camera::Attachment& attachment = camera.getBufferAttachmentMap()[buffer];
// read attachment data.
while (!fr.eof() && fr[0].getNoNestedBrackets()>entry)
{
bool localAdvance = false;
if (fr.matchSequence("internalFormat %i"))
{
// In their infinite wisdom, the Apple engineers changed the type
// of GLenum from 'unsigned int' to 'unsigned long', thus breaking
// the call by reference of getUInt.
unsigned int format;
fr[1].getUInt(format);
attachment._internalFormat = format;
fr += 2;
localAdvance = true;
}
osg::ref_ptr<osg::Object> attribute;
while((attribute=fr.readObject())!=NULL)
{
localAdvance = true;
osg::Texture* texture = dynamic_cast<osg::Texture*>(attribute.get());
if (texture) attachment._texture = texture;
else
{
osg::Image* image = dynamic_cast<osg::Image*>(attribute.get());
attachment._image = image;
}
}
if (fr.matchSequence("level %i"))
{
fr[1].getUInt(attachment._level);
fr += 2;
localAdvance = true;
}
if (fr.matchSequence("face %i"))
{
fr[1].getUInt(attachment._face);
fr += 2;
localAdvance = true;
}
if (fr.matchSequence("mipMapGeneration TRUE"))
{
attachment._mipMapGeneration = true;
fr += 2;
localAdvance = true;
}
if (fr.matchSequence("mipMapGeneration FALSE"))
{
attachment._mipMapGeneration = false;
fr += 2;
localAdvance = true;
}
if (!localAdvance) ++fr;
}
iteratorAdvanced = true;
}
return iteratorAdvanced;
}
bool Camera_writeLocalData(const Object& obj, Output& fw)
{
const Camera& camera = static_cast<const Camera&>(obj);
fw.indent()<<"clearColor "<<camera.getClearColor()<<std::endl;
fw.indent()<<"clearMask 0x"<<std::hex<<camera.getClearMask()<<std::endl;
if (camera.getColorMask())
{
fw.writeObject(*camera.getColorMask());
}
if (camera.getViewport())
{
fw.writeObject(*camera.getViewport());
}
fw.indent()<<"transformOrder ";
switch(camera.getTransformOrder())
{
case(osg::Camera::PRE_MULTIPLY): fw <<"PRE_MULTIPLY"<<std::endl; break;
case(osg::Camera::POST_MULTIPLY): fw <<"POST_MULTIPLY"<<std::endl; break;
}
writeMatrix(camera.getProjectionMatrix(),fw,"ProjectionMatrix");
writeMatrix(camera.getViewMatrix(),fw,"ViewMatrix");
fw.indent()<<"renderOrder ";
switch(camera.getRenderOrder())
{
case(osg::Camera::PRE_RENDER): fw <<"PRE_RENDER"<<std::endl; break;
case(osg::Camera::NESTED_RENDER): fw <<"NESTED_RENDER"<<std::endl; break;
case(osg::Camera::POST_RENDER): fw <<"POST_RENDER"<<std::endl; break;
}
fw.indent()<<"renderTargetImplementation ";
switch(camera.getRenderTargetImplementation())
{
case(osg::Camera::FRAME_BUFFER_OBJECT): fw <<"FRAME_BUFFER_OBJECT"<<std::endl; break;
case(osg::Camera::PIXEL_BUFFER_RTT): fw <<"PIXEL_BUFFER_RTT"<<std::endl; break;
case(osg::Camera::PIXEL_BUFFER): fw <<"PIXEL_BUFFER"<<std::endl; break;
case(osg::Camera::FRAME_BUFFER): fw <<"FRAME_BUFFER"<<std::endl; break;
case(osg::Camera::SEPERATE_WINDOW): fw <<"SEPERATE_WINDOW"<<std::endl; break;
}
fw.indent()<<"renderTargetFallback ";
switch(camera.getRenderTargetFallback())
{
case(osg::Camera::FRAME_BUFFER_OBJECT): fw <<"FRAME_BUFFER_OBJECT"<<std::endl; break;
case(osg::Camera::PIXEL_BUFFER_RTT): fw <<"PIXEL_BUFFER_RTT"<<std::endl; break;
case(osg::Camera::PIXEL_BUFFER): fw <<"PIXEL_BUFFER"<<std::endl; break;
case(osg::Camera::FRAME_BUFFER): fw <<"FRAME_BUFFER"<<std::endl; break;
case(osg::Camera::SEPERATE_WINDOW): fw <<"SEPERATE_WINDOW"<<std::endl; break;
}
fw.indent()<<"drawBuffer "<<std::hex<<camera.getDrawBuffer()<<std::endl;
fw.indent()<<"readBuffer "<<std::hex<<camera.getReadBuffer()<<std::endl;
const osg::Camera::BufferAttachmentMap& bam = camera.getBufferAttachmentMap();
if (!bam.empty())
{
for(osg::Camera::BufferAttachmentMap::const_iterator itr=bam.begin();
itr!=bam.end();
++itr)
{
const osg::Camera::Attachment& attachment = itr->second;
fw.indent()<<"bufferComponent "<<Camera_getBufferComponentStr(itr->first)<<" {"<<std::endl;
fw.moveIn();
fw.indent()<<"internalFormat "<<attachment._internalFormat<<std::endl;
if (attachment._texture.valid())
{
fw.writeObject(*attachment._texture.get());
}
fw.indent()<<"level "<<attachment._level<<std::endl;
fw.indent()<<"face "<<attachment._face<<std::endl;
fw.indent()<<"mipMapGeneration "<<(attachment._mipMapGeneration ? "TRUE" : "FALSE")<<std::endl;
fw.moveOut();
fw.indent()<<"}"<<std::endl;
}
}
return true;
}
bool Camera_matchBufferComponentStr(const char* str,Camera::BufferComponent& buffer)
{
if (strcmp(str,"DEPTH_BUFFER")==0) buffer = osg::Camera::DEPTH_BUFFER;
else if (strcmp(str,"STENCIL_BUFFER")==0) buffer = osg::Camera::STENCIL_BUFFER;
else if (strcmp(str,"COLOR_BUFFER")==0) buffer = osg::Camera::COLOR_BUFFER;
else if (strcmp(str,"COLOR_BUFFER0")==0) buffer = osg::Camera::COLOR_BUFFER0;
else if (strcmp(str,"COLOR_BUFFER1")==0) buffer = osg::Camera::COLOR_BUFFER1;
else if (strcmp(str,"COLOR_BUFFER2")==0) buffer = osg::Camera::COLOR_BUFFER2;
else if (strcmp(str,"COLOR_BUFFER3")==0) buffer = osg::Camera::COLOR_BUFFER3;
else if (strcmp(str,"COLOR_BUFFER4")==0) buffer = osg::Camera::COLOR_BUFFER4;
else if (strcmp(str,"COLOR_BUFFER5")==0) buffer = osg::Camera::COLOR_BUFFER5;
else if (strcmp(str,"COLOR_BUFFER6")==0) buffer = osg::Camera::COLOR_BUFFER6;
else if (strcmp(str,"COLOR_BUFFER7")==0) buffer = osg::Camera::COLOR_BUFFER7;
else return false;
return true;
}
const char* Camera_getBufferComponentStr(Camera::BufferComponent buffer)
{
switch(buffer)
{
case (osg::Camera::DEPTH_BUFFER) : return "DEPTH_BUFFER";
case (osg::Camera::STENCIL_BUFFER) : return "STENCIL_BUFFER";
case (osg::Camera::COLOR_BUFFER) : return "COLOR_BUFFER";
case (osg::Camera::COLOR_BUFFER0) : return "COLOR_BUFFER0";
case (osg::Camera::COLOR_BUFFER1) : return "COLOR_BUFFER1";
case (osg::Camera::COLOR_BUFFER2) : return "COLOR_BUFFER2";
case (osg::Camera::COLOR_BUFFER3) : return "COLOR_BUFFER3";
case (osg::Camera::COLOR_BUFFER4) : return "COLOR_BUFFER4";
case (osg::Camera::COLOR_BUFFER5) : return "COLOR_BUFFER5";
case (osg::Camera::COLOR_BUFFER6) : return "COLOR_BUFFER6";
case (osg::Camera::COLOR_BUFFER7) : return "COLOR_BUFFER7";
default : return "UnknownBufferComponent";
}
}
<commit_msg>Added support for COLOR_BUFFER entries up to 15<commit_after>#include <osg/Camera>
#include <osg/io_utils>
#include <osg/Notify>
#include <osgDB/Registry>
#include <osgDB/Input>
#include <osgDB/Output>
#include "Matrix.h"
using namespace osg;
using namespace osgDB;
// forward declare functions to use later.
bool Camera_readLocalData(Object& obj, Input& fr);
bool Camera_writeLocalData(const Object& obj, Output& fw);
bool Camera_matchBufferComponentStr(const char* str,Camera::BufferComponent& buffer);
const char* Camera_getBufferComponentStr(Camera::BufferComponent buffer);
// register the read and write functions with the osgDB::Registry.
RegisterDotOsgWrapperProxy g_CameraProxy
(
new osg::Camera,
"Camera",
"Object Node Transform Camera Group",
&Camera_readLocalData,
&Camera_writeLocalData,
DotOsgWrapper::READ_AND_WRITE
);
// register the read and write functions with the osgDB::Registry.
RegisterDotOsgWrapperProxy g_CameraNodeProxy
(
new osg::Camera,
"CameraNode",
"Object Node Transform CameraNode Group",
&Camera_readLocalData,
&Camera_writeLocalData,
DotOsgWrapper::READ_AND_WRITE
);
bool Camera_readLocalData(Object& obj, Input& fr)
{
bool iteratorAdvanced = false;
Camera& camera = static_cast<Camera&>(obj);
if (fr.matchSequence("clearColor %f %f %f %f"))
{
Vec4 color;
fr[1].getFloat(color[0]);
fr[2].getFloat(color[1]);
fr[3].getFloat(color[2]);
fr[4].getFloat(color[3]);
camera.setClearColor(color);
fr +=5 ;
iteratorAdvanced = true;
};
if (fr.matchSequence("clearMask %i"))
{
unsigned int value;
fr[1].getUInt(value);
camera.setClearMask(value);
fr += 2;
iteratorAdvanced = true;
}
osg::ref_ptr<osg::StateAttribute> attribute;
while((attribute=fr.readStateAttribute())!=NULL)
{
osg::Viewport* viewport = dynamic_cast<osg::Viewport*>(attribute.get());
if (viewport) camera.setViewport(viewport);
else
{
osg::ColorMask* colormask = dynamic_cast<osg::ColorMask*>(attribute.get());
camera.setColorMask(colormask);
}
}
if (fr.matchSequence("transformOrder %w"))
{
if (fr[1].matchWord("PRE_MULTIPLY")) camera.setTransformOrder(osg::Camera::PRE_MULTIPLY);
else if (fr[1].matchWord("POST_MULTIPLY")) camera.setTransformOrder(osg::Camera::POST_MULTIPLY);
// the following are for backwards compatibility.
else if (fr[1].matchWord("PRE_MULTIPLE")) camera.setTransformOrder(osg::Camera::PRE_MULTIPLY);
else if (fr[1].matchWord("POST_MULTIPLE")) camera.setTransformOrder(osg::Camera::POST_MULTIPLY);
fr += 2;
iteratorAdvanced = true;
}
Matrix matrix;
if (readMatrix(matrix,fr,"ProjectionMatrix"))
{
camera.setProjectionMatrix(matrix);
iteratorAdvanced = true;
}
if (readMatrix(matrix,fr,"ViewMatrix"))
{
camera.setViewMatrix(matrix);
iteratorAdvanced = true;
}
if (fr.matchSequence("renderOrder %w"))
{
if (fr[1].matchWord("PRE_RENDER")) camera.setRenderOrder(osg::Camera::PRE_RENDER);
else if (fr[1].matchWord("NESTED_RENDER")) camera.setRenderOrder(osg::Camera::NESTED_RENDER);
else if (fr[1].matchWord("POST_RENDER")) camera.setRenderOrder(osg::Camera::POST_RENDER);
fr += 2;
iteratorAdvanced = true;
}
if (fr.matchSequence("renderTargetImplementation %w"))
{
osg::Camera::RenderTargetImplementation implementation = osg::Camera::FRAME_BUFFER;
if (fr[1].matchWord("FRAME_BUFFER_OBJECT")) implementation = osg::Camera::FRAME_BUFFER_OBJECT;
else if (fr[1].matchWord("PIXEL_BUFFER_RTT")) implementation = osg::Camera::PIXEL_BUFFER_RTT;
else if (fr[1].matchWord("PIXEL_BUFFER")) implementation = osg::Camera::PIXEL_BUFFER;
else if (fr[1].matchWord("FRAME_BUFFER")) implementation = osg::Camera::FRAME_BUFFER;
else if (fr[1].matchWord("SEPERATE_WINDOW")) implementation = osg::Camera::SEPERATE_WINDOW;
camera.setRenderTargetImplementation(implementation);
fr += 2;
iteratorAdvanced = true;
}
if (fr.matchSequence("renderTargetImplementation %w"))
{
osg::Camera::RenderTargetImplementation fallback = camera.getRenderTargetFallback();
if (fr[1].matchWord("FRAME_BUFFER_OBJECT")) fallback = osg::Camera::FRAME_BUFFER_OBJECT;
else if (fr[1].matchWord("PIXEL_BUFFER_RTT")) fallback = osg::Camera::PIXEL_BUFFER_RTT;
else if (fr[1].matchWord("PIXEL_BUFFER")) fallback = osg::Camera::PIXEL_BUFFER;
else if (fr[1].matchWord("FRAME_BUFFER")) fallback = osg::Camera::FRAME_BUFFER;
else if (fr[1].matchWord("SEPERATE_WINDOW")) fallback = osg::Camera::SEPERATE_WINDOW;
camera.setRenderTargetImplementation(camera.getRenderTargetImplementation(), fallback);
fr += 2;
iteratorAdvanced = true;
}
if (fr.matchSequence("bufferComponent %w {"))
{
int entry = fr[1].getNoNestedBrackets();
Camera::BufferComponent buffer;
Camera_matchBufferComponentStr(fr[1].getStr(),buffer);
fr += 3;
Camera::Attachment& attachment = camera.getBufferAttachmentMap()[buffer];
// read attachment data.
while (!fr.eof() && fr[0].getNoNestedBrackets()>entry)
{
bool localAdvance = false;
if (fr.matchSequence("internalFormat %i"))
{
// In their infinite wisdom, the Apple engineers changed the type
// of GLenum from 'unsigned int' to 'unsigned long', thus breaking
// the call by reference of getUInt.
unsigned int format;
fr[1].getUInt(format);
attachment._internalFormat = format;
fr += 2;
localAdvance = true;
}
osg::ref_ptr<osg::Object> attribute;
while((attribute=fr.readObject())!=NULL)
{
localAdvance = true;
osg::Texture* texture = dynamic_cast<osg::Texture*>(attribute.get());
if (texture) attachment._texture = texture;
else
{
osg::Image* image = dynamic_cast<osg::Image*>(attribute.get());
attachment._image = image;
}
}
if (fr.matchSequence("level %i"))
{
fr[1].getUInt(attachment._level);
fr += 2;
localAdvance = true;
}
if (fr.matchSequence("face %i"))
{
fr[1].getUInt(attachment._face);
fr += 2;
localAdvance = true;
}
if (fr.matchSequence("mipMapGeneration TRUE"))
{
attachment._mipMapGeneration = true;
fr += 2;
localAdvance = true;
}
if (fr.matchSequence("mipMapGeneration FALSE"))
{
attachment._mipMapGeneration = false;
fr += 2;
localAdvance = true;
}
if (!localAdvance) ++fr;
}
iteratorAdvanced = true;
}
return iteratorAdvanced;
}
bool Camera_writeLocalData(const Object& obj, Output& fw)
{
const Camera& camera = static_cast<const Camera&>(obj);
fw.indent()<<"clearColor "<<camera.getClearColor()<<std::endl;
fw.indent()<<"clearMask 0x"<<std::hex<<camera.getClearMask()<<std::endl;
if (camera.getColorMask())
{
fw.writeObject(*camera.getColorMask());
}
if (camera.getViewport())
{
fw.writeObject(*camera.getViewport());
}
fw.indent()<<"transformOrder ";
switch(camera.getTransformOrder())
{
case(osg::Camera::PRE_MULTIPLY): fw <<"PRE_MULTIPLY"<<std::endl; break;
case(osg::Camera::POST_MULTIPLY): fw <<"POST_MULTIPLY"<<std::endl; break;
}
writeMatrix(camera.getProjectionMatrix(),fw,"ProjectionMatrix");
writeMatrix(camera.getViewMatrix(),fw,"ViewMatrix");
fw.indent()<<"renderOrder ";
switch(camera.getRenderOrder())
{
case(osg::Camera::PRE_RENDER): fw <<"PRE_RENDER"<<std::endl; break;
case(osg::Camera::NESTED_RENDER): fw <<"NESTED_RENDER"<<std::endl; break;
case(osg::Camera::POST_RENDER): fw <<"POST_RENDER"<<std::endl; break;
}
fw.indent()<<"renderTargetImplementation ";
switch(camera.getRenderTargetImplementation())
{
case(osg::Camera::FRAME_BUFFER_OBJECT): fw <<"FRAME_BUFFER_OBJECT"<<std::endl; break;
case(osg::Camera::PIXEL_BUFFER_RTT): fw <<"PIXEL_BUFFER_RTT"<<std::endl; break;
case(osg::Camera::PIXEL_BUFFER): fw <<"PIXEL_BUFFER"<<std::endl; break;
case(osg::Camera::FRAME_BUFFER): fw <<"FRAME_BUFFER"<<std::endl; break;
case(osg::Camera::SEPERATE_WINDOW): fw <<"SEPERATE_WINDOW"<<std::endl; break;
}
fw.indent()<<"renderTargetFallback ";
switch(camera.getRenderTargetFallback())
{
case(osg::Camera::FRAME_BUFFER_OBJECT): fw <<"FRAME_BUFFER_OBJECT"<<std::endl; break;
case(osg::Camera::PIXEL_BUFFER_RTT): fw <<"PIXEL_BUFFER_RTT"<<std::endl; break;
case(osg::Camera::PIXEL_BUFFER): fw <<"PIXEL_BUFFER"<<std::endl; break;
case(osg::Camera::FRAME_BUFFER): fw <<"FRAME_BUFFER"<<std::endl; break;
case(osg::Camera::SEPERATE_WINDOW): fw <<"SEPERATE_WINDOW"<<std::endl; break;
}
fw.indent()<<"drawBuffer "<<std::hex<<camera.getDrawBuffer()<<std::endl;
fw.indent()<<"readBuffer "<<std::hex<<camera.getReadBuffer()<<std::endl;
const osg::Camera::BufferAttachmentMap& bam = camera.getBufferAttachmentMap();
if (!bam.empty())
{
for(osg::Camera::BufferAttachmentMap::const_iterator itr=bam.begin();
itr!=bam.end();
++itr)
{
const osg::Camera::Attachment& attachment = itr->second;
fw.indent()<<"bufferComponent "<<Camera_getBufferComponentStr(itr->first)<<" {"<<std::endl;
fw.moveIn();
fw.indent()<<"internalFormat "<<attachment._internalFormat<<std::endl;
if (attachment._texture.valid())
{
fw.writeObject(*attachment._texture.get());
}
fw.indent()<<"level "<<attachment._level<<std::endl;
fw.indent()<<"face "<<attachment._face<<std::endl;
fw.indent()<<"mipMapGeneration "<<(attachment._mipMapGeneration ? "TRUE" : "FALSE")<<std::endl;
fw.moveOut();
fw.indent()<<"}"<<std::endl;
}
}
return true;
}
bool Camera_matchBufferComponentStr(const char* str,Camera::BufferComponent& buffer)
{
if (strcmp(str,"DEPTH_BUFFER")==0) buffer = osg::Camera::DEPTH_BUFFER;
else if (strcmp(str,"STENCIL_BUFFER")==0) buffer = osg::Camera::STENCIL_BUFFER;
else if (strcmp(str,"COLOR_BUFFER")==0) buffer = osg::Camera::COLOR_BUFFER;
else if (strcmp(str,"COLOR_BUFFER0")==0) buffer = osg::Camera::COLOR_BUFFER0;
else if (strcmp(str,"COLOR_BUFFER1")==0) buffer = osg::Camera::COLOR_BUFFER1;
else if (strcmp(str,"COLOR_BUFFER2")==0) buffer = osg::Camera::COLOR_BUFFER2;
else if (strcmp(str,"COLOR_BUFFER3")==0) buffer = osg::Camera::COLOR_BUFFER3;
else if (strcmp(str,"COLOR_BUFFER4")==0) buffer = osg::Camera::COLOR_BUFFER4;
else if (strcmp(str,"COLOR_BUFFER5")==0) buffer = osg::Camera::COLOR_BUFFER5;
else if (strcmp(str,"COLOR_BUFFER6")==0) buffer = osg::Camera::COLOR_BUFFER6;
else if (strcmp(str,"COLOR_BUFFER7")==0) buffer = osg::Camera::COLOR_BUFFER7;
else if (strcmp(str,"COLOR_BUFFER8")==0) buffer = osg::Camera::COLOR_BUFFER8;
else if (strcmp(str,"COLOR_BUFFER9")==0) buffer = osg::Camera::COLOR_BUFFER9;
else if (strcmp(str,"COLOR_BUFFER10")==0) buffer = osg::Camera::COLOR_BUFFER10;
else if (strcmp(str,"COLOR_BUFFER11")==0) buffer = osg::Camera::COLOR_BUFFER11;
else if (strcmp(str,"COLOR_BUFFER12")==0) buffer = osg::Camera::COLOR_BUFFER12;
else if (strcmp(str,"COLOR_BUFFER13")==0) buffer = osg::Camera::COLOR_BUFFER13;
else if (strcmp(str,"COLOR_BUFFER14")==0) buffer = osg::Camera::COLOR_BUFFER14;
else if (strcmp(str,"COLOR_BUFFER15")==0) buffer = osg::Camera::COLOR_BUFFER15;
else return false;
return true;
}
const char* Camera_getBufferComponentStr(Camera::BufferComponent buffer)
{
switch(buffer)
{
case (osg::Camera::DEPTH_BUFFER) : return "DEPTH_BUFFER";
case (osg::Camera::STENCIL_BUFFER) : return "STENCIL_BUFFER";
case (osg::Camera::COLOR_BUFFER) : return "COLOR_BUFFER";
case (osg::Camera::COLOR_BUFFER0) : return "COLOR_BUFFER0";
case (osg::Camera::COLOR_BUFFER1) : return "COLOR_BUFFER1";
case (osg::Camera::COLOR_BUFFER2) : return "COLOR_BUFFER2";
case (osg::Camera::COLOR_BUFFER3) : return "COLOR_BUFFER3";
case (osg::Camera::COLOR_BUFFER4) : return "COLOR_BUFFER4";
case (osg::Camera::COLOR_BUFFER5) : return "COLOR_BUFFER5";
case (osg::Camera::COLOR_BUFFER6) : return "COLOR_BUFFER6";
case (osg::Camera::COLOR_BUFFER7) : return "COLOR_BUFFER7";
case (osg::Camera::COLOR_BUFFER8) : return "COLOR_BUFFER8";
case (osg::Camera::COLOR_BUFFER9) : return "COLOR_BUFFER9";
case (osg::Camera::COLOR_BUFFER10) : return "COLOR_BUFFER10";
case (osg::Camera::COLOR_BUFFER11) : return "COLOR_BUFFER11";
case (osg::Camera::COLOR_BUFFER12) : return "COLOR_BUFFER12";
case (osg::Camera::COLOR_BUFFER13) : return "COLOR_BUFFER13";
case (osg::Camera::COLOR_BUFFER14) : return "COLOR_BUFFER14";
case (osg::Camera::COLOR_BUFFER15) : return "COLOR_BUFFER15";
default : return "UnknownBufferComponent";
}
}
<|endoftext|> |
<commit_before>#define BOOST_TEST_MODULE VectorArithmetics
#include <boost/test/unit_test.hpp>
#include "context_setup.hpp"
BOOST_AUTO_TEST_CASE(assign_expression)
{
const size_t N = 1024;
vex::vector<double> x(ctx, N);
vex::vector<double> y(ctx, N);
vex::vector<double> z(ctx, N);
y = 42;
z = 67;
x = 5 * sin(y) + z;
check_sample(x, [](size_t, double a) {
BOOST_CHECK_CLOSE(a, 5 * sin(42.0) + 67, 1e-12);
});
}
BOOST_AUTO_TEST_CASE(reduce_expression)
{
const size_t N = 1024;
std::vector<double> x = random_vector<double>(N);
vex::vector<double> X(ctx, x);
vex::Reductor<double,vex::SUM> sum(ctx);
vex::Reductor<double,vex::MIN> min(ctx);
vex::Reductor<double,vex::MAX> max(ctx);
BOOST_CHECK_CLOSE(sum(X), std::accumulate(x.begin(), x.end(), 0.0), 1e-6);
BOOST_CHECK_CLOSE(min(X), *std::min_element(x.begin(), x.end()), 1e-6);
BOOST_CHECK_CLOSE(max(X), *std::max_element(x.begin(), x.end()), 1e-6);
BOOST_CHECK_SMALL(max(fabs(X - X)), 1e-12);
}
BOOST_AUTO_TEST_CASE(builtin_functions)
{
const size_t N = 1024;
std::vector<double> x = random_vector<double>(N);
vex::vector<double> X(ctx, x);
vex::vector<double> Y(ctx, N);
Y = pow(sin(X), 2.0) + pow(cos(X), 2.0);
check_sample(Y, [](size_t, double a) { BOOST_CHECK_CLOSE(a, 1, 1e-8); });
}
BOOST_AUTO_TEST_CASE(user_defined_functions)
{
const size_t N = 1024;
vex::vector<double> x(ctx, N);
vex::vector<double> y(ctx, N);
x = 1;
y = 2;
VEX_FUNCTION(greater, size_t(double, double), "return prm1 > prm2;");
vex::Reductor<size_t,vex::SUM> sum(ctx);
BOOST_CHECK( sum( greater(x, y) ) == 0U);
BOOST_CHECK( sum( greater(y, x) ) == N);
}
BOOST_AUTO_TEST_CASE(user_defined_functions_same_signature)
{
const size_t N = 1024;
vex::vector<double> x(ctx, N);
x = 1;
VEX_FUNCTION(times2, double(double), "return prm1 * 2;");
VEX_FUNCTION(times4, double(double), "return prm1 * 4;");
vex::Reductor<size_t,vex::SUM> sum(ctx);
BOOST_CHECK( sum( times2(x) ) == 2 * N );
BOOST_CHECK( sum( times4(x) ) == 4 * N );
}
BOOST_AUTO_TEST_CASE(element_index)
{
const size_t N = 1024;
vex::vector<double> x(ctx, N);
x = sin(0.5 * vex::element_index());
check_sample(x, [](size_t idx, double a) { BOOST_CHECK_CLOSE(a, sin(0.5 * idx), 1e-8); });
}
BOOST_AUTO_TEST_CASE(vector_values)
{
const size_t N = 1024;
VEX_FUNCTION(make_int4, cl_int4(int), "return (int4)(prm1, prm1, prm1, prm1);");
cl_int4 c = {{1, 2, 3, 4}};
vex::vector<cl_int4> X(ctx, N);
X = c * (make_int4(5 + vex::element_index()));
check_sample(X, [c](long idx, cl_int4 v) {
for(int j = 0; j < 4; ++j)
BOOST_CHECK(v.s[j] == c.s[j] * (5 + idx));
});
}
BOOST_AUTO_TEST_CASE(nested_functions)
{
const size_t N = 1024;
VEX_FUNCTION(f, int(int), "return 2 * prm1;");
VEX_FUNCTION(g, int(int), "return 3 * prm1;");
vex::vector<int> x(ctx, N);
x = 1;
x = f(f(x));
check_sample(x, [](size_t, int a) { BOOST_CHECK(a == 4); });
x = 1;
x = g(f(x));
check_sample(x, [](size_t, int a) { BOOST_CHECK(a == 6); });
}
BOOST_AUTO_TEST_CASE(custom_header)
{
const size_t n = 1024;
vex::vector<int> x(ctx, n);
vex::set_program_header(ctx, "#define THE_ANSWER 42\n");
VEX_FUNCTION(answer, int(int), "return prm1 * THE_ANSWER;");
x = answer(1);
check_sample(x, [](size_t, int a) {
BOOST_CHECK(a == 42);
});
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Adding test for combining expressions<commit_after>#define BOOST_TEST_MODULE VectorArithmetics
#include <boost/test/unit_test.hpp>
#include "context_setup.hpp"
BOOST_AUTO_TEST_CASE(assign_expression)
{
const size_t N = 1024;
vex::vector<double> x(ctx, N);
vex::vector<double> y(ctx, N);
vex::vector<double> z(ctx, N);
y = 42;
z = 67;
x = 5 * sin(y) + z;
check_sample(x, [](size_t, double a) {
BOOST_CHECK_CLOSE(a, 5 * sin(42.0) + 67, 1e-12);
});
}
BOOST_AUTO_TEST_CASE(reduce_expression)
{
const size_t N = 1024;
std::vector<double> x = random_vector<double>(N);
vex::vector<double> X(ctx, x);
vex::Reductor<double,vex::SUM> sum(ctx);
vex::Reductor<double,vex::MIN> min(ctx);
vex::Reductor<double,vex::MAX> max(ctx);
BOOST_CHECK_CLOSE(sum(X), std::accumulate(x.begin(), x.end(), 0.0), 1e-6);
BOOST_CHECK_CLOSE(min(X), *std::min_element(x.begin(), x.end()), 1e-6);
BOOST_CHECK_CLOSE(max(X), *std::max_element(x.begin(), x.end()), 1e-6);
BOOST_CHECK_SMALL(max(fabs(X - X)), 1e-12);
}
BOOST_AUTO_TEST_CASE(builtin_functions)
{
const size_t N = 1024;
std::vector<double> x = random_vector<double>(N);
vex::vector<double> X(ctx, x);
vex::vector<double> Y(ctx, N);
Y = pow(sin(X), 2.0) + pow(cos(X), 2.0);
check_sample(Y, [](size_t, double a) { BOOST_CHECK_CLOSE(a, 1, 1e-8); });
}
BOOST_AUTO_TEST_CASE(user_defined_functions)
{
const size_t N = 1024;
vex::vector<double> x(ctx, N);
vex::vector<double> y(ctx, N);
x = 1;
y = 2;
VEX_FUNCTION(greater, size_t(double, double), "return prm1 > prm2;");
vex::Reductor<size_t,vex::SUM> sum(ctx);
BOOST_CHECK( sum( greater(x, y) ) == 0U);
BOOST_CHECK( sum( greater(y, x) ) == N);
}
BOOST_AUTO_TEST_CASE(user_defined_functions_same_signature)
{
const size_t N = 1024;
vex::vector<double> x(ctx, N);
x = 1;
VEX_FUNCTION(times2, double(double), "return prm1 * 2;");
VEX_FUNCTION(times4, double(double), "return prm1 * 4;");
vex::Reductor<size_t,vex::SUM> sum(ctx);
BOOST_CHECK( sum( times2(x) ) == 2 * N );
BOOST_CHECK( sum( times4(x) ) == 4 * N );
}
BOOST_AUTO_TEST_CASE(element_index)
{
const size_t N = 1024;
vex::vector<double> x(ctx, N);
x = sin(0.5 * vex::element_index());
check_sample(x, [](size_t idx, double a) { BOOST_CHECK_CLOSE(a, sin(0.5 * idx), 1e-8); });
}
BOOST_AUTO_TEST_CASE(vector_values)
{
const size_t N = 1024;
VEX_FUNCTION(make_int4, cl_int4(int), "return (int4)(prm1, prm1, prm1, prm1);");
cl_int4 c = {{1, 2, 3, 4}};
vex::vector<cl_int4> X(ctx, N);
X = c * (make_int4(5 + vex::element_index()));
check_sample(X, [c](long idx, cl_int4 v) {
for(int j = 0; j < 4; ++j)
BOOST_CHECK(v.s[j] == c.s[j] * (5 + idx));
});
}
BOOST_AUTO_TEST_CASE(nested_functions)
{
const size_t N = 1024;
VEX_FUNCTION(f, int(int), "return 2 * prm1;");
VEX_FUNCTION(g, int(int), "return 3 * prm1;");
vex::vector<int> x(ctx, N);
x = 1;
x = f(f(x));
check_sample(x, [](size_t, int a) { BOOST_CHECK(a == 4); });
x = 1;
x = g(f(x));
check_sample(x, [](size_t, int a) { BOOST_CHECK(a == 6); });
}
BOOST_AUTO_TEST_CASE(custom_header)
{
const size_t n = 1024;
vex::vector<int> x(ctx, n);
vex::set_program_header(ctx, "#define THE_ANSWER 42\n");
VEX_FUNCTION(answer, int(int), "return prm1 * THE_ANSWER;");
x = answer(1);
check_sample(x, [](size_t, int a) {
BOOST_CHECK(a == 42);
});
}
BOOST_AUTO_TEST_CASE(combine_expressions)
{
const size_t n = 1024;
vex::vector<int> x(ctx, n);
auto sine = sin(2 * M_PI * vex::element_index());
auto cosine = cos(2 * M_PI * vex::element_index());
x = pow(sine, 2.0) + pow(cosine, 2.0);
check_sample(x, [](size_t, double v) { BOOST_CHECK_CLOSE(v, 1.0, 1e-8); });
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>/******************************************************************************
This source file is part of the tomviz project.
Copyright Kitware, Inc.
This source code is released under the New BSD License, (the "License").
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 "ScaleLegend.h"
#include "vtkAxisActor2D.h"
#include "vtkBillboardTextActor3D.h"
#include "vtkCamera.h"
#include "vtkCommand.h"
#include "vtkDistanceWidget.h"
#include "vtkHandleWidget.h"
#include "vtkLengthScaleRepresentation.h"
#include "vtkMath.h"
#include "vtkPointHandleRepresentation2D.h"
#include "vtkProperty2D.h"
#include "vtkRenderWindow.h"
#include "vtkRenderer.h"
#include "vtkTextActor.h"
#include "vtkTextProperty.h"
#include "vtkVolumeScaleRepresentation.h"
#include "pqView.h"
#include "vtkPVAxesWidget.h"
#include "vtkPVRenderView.h"
#include "vtkSMViewProxy.h"
#include "ActiveObjects.h"
#include "DataSource.h"
#include "MainWindow.h"
#include "ModuleManager.h"
#include "Utilities.h"
#include <math.h>
// The Scale legend lives in a sub-render window at the bottom right-hand corner
// of the viewing screen and has its own camera. vtkLinkCameras connects the
// sub-render window camera to the main window camera.
class vtkLinkCameras : public vtkCommand
{
public:
static vtkLinkCameras* New()
{
vtkLinkCameras* cb = new vtkLinkCameras;
return cb;
}
vtkLinkCameras() : Style(tomviz::ScaleLegendStyle::Cube) {}
void SetParentCamera(vtkCamera* c) { this->ParentCamera = c; }
void SetChildCamera(vtkCamera* c) { this->ChildCamera = c; }
void SetScaleLegendStyle(tomviz::ScaleLegendStyle style)
{
this->Style = style;
}
virtual void Execute(vtkObject* vtkNotUsed(caller),
unsigned long vtkNotUsed(eventId),
void* vtkNotUsed(callData))
{
this->OrientCamera();
}
void OrientCamera()
{
double pos[3], fp[3], viewup[3];
this->ParentCamera->GetPosition(pos);
this->ParentCamera->GetFocalPoint(fp);
this->ParentCamera->GetViewUp(viewup);
if (this->Style == tomviz::ScaleLegendStyle::Cube) {
// The child camera's focal point is always the origin, and its position
// is translated to have the same positional offset (both distance and
// orientation) between the camera and the object.
for (int i = 0; i < 3; i++) {
pos[i] -= fp[i];
fp[i] = 0.;
}
this->ChildCamera->SetPosition(pos);
this->ChildCamera->SetFocalPoint(fp);
this->ChildCamera->SetViewUp(viewup);
} else if (this->Style == tomviz::ScaleLegendStyle::Ruler) {
// The child camera's focal point is always the origin, and its position
// is translated to have the same distance (but not orientation) between
// the camera and the object. The camera's view is fixed.
double toFP[3];
this->ChildCamera->GetDirectionOfProjection(toFP);
double dist = sqrt(vtkMath::Distance2BetweenPoints(pos, fp));
for (int i = 0; i < 3; i++) {
pos[i] = 0.;
fp[i] = 0.;
}
pos[2] = -dist;
this->ChildCamera->SetPosition(pos);
this->ChildCamera->SetFocalPoint(fp);
double up[3] = { 0., 1., 0. };
this->ChildCamera->SetViewUp(up);
}
}
private:
vtkCamera* ParentCamera;
vtkCamera* ChildCamera;
tomviz::ScaleLegendStyle Style;
};
namespace tomviz {
ScaleLegend::ScaleLegend(QMainWindow* mw)
: Superclass(mw), mainWindow(mw), m_style(ScaleLegendStyle::Cube),
m_visible(false)
{
// Connect the data manager's "dataSourceAdded" to our "dataSourceAdded" slot
// to allow us to connect to the new data source's length scale information.
ModuleManager& mm = ModuleManager::instance();
QObject::connect(&mm, SIGNAL(dataSourceAdded(DataSource*)), this,
SLOT(dataSourceAdded(DataSource*)));
// Measurement cube
{
m_volumeScaleRep->GetLabel()->GetTextProperty()->SetFontSize(30);
m_volumeScaleRep->SetMinRelativeCubeScreenArea(.0002);
m_volumeScaleRep->SetMaxRelativeCubeScreenArea(.002);
m_handleWidget->CreateDefaultRepresentation();
m_handleWidget->SetRepresentation(m_volumeScaleRep.Get());
m_handleWidget->SetProcessEvents(0);
}
// Ruler
{
m_lengthScaleRep->InstantiateHandleRepresentation();
double p1[3] = { -.5, 0., 0. };
double p2[3] = { .5, 0., 0. };
m_lengthScaleRep->SetPoint1WorldPosition(p1);
m_lengthScaleRep->SetPoint2WorldPosition(p2);
m_lengthScaleRep->GetAxis()->SetTickLength(9);
m_lengthScaleRep->GetLabel()->GetTextProperty()->SetFontSize(30);
m_lengthScaleRep->SetMinRelativeScreenWidth(.03);
m_lengthScaleRep->SetMaxRelativeScreenWidth(.07);
m_distanceWidget->SetRepresentation(m_lengthScaleRep.Get());
}
m_renderer->SetViewport(0.85, 0.0, 1.0, 0.225);
// From vtkPVAxesWidget.cxx:
// Since Layer==1, the renderer is treated as transparent and
// vtkOpenGLRenderer::Clear() won't clear the color-buffer.
m_renderer->SetLayer(vtkPVAxesWidget::RendererLayer);
// Leaving Erase==1 ensures that the depth buffer is cleared. This ensures
// that the orientation widget always stays on top of the rendered scene.
m_renderer->EraseOn();
m_renderer->InteractiveOff();
m_renderer->AddActor(m_volumeScaleRep.Get());
m_renderer->AddActor(m_lengthScaleRep.Get());
// Add our sub-renderer to the main renderer
vtkSMViewProxy* view = ActiveObjects::instance().activeView();
vtkPVRenderView* renderView =
vtkPVRenderView::SafeDownCast(view->GetClientSideView());
renderView->GetRenderWindow()->AddRenderer(m_renderer.Get());
// Set up interactors
m_handleWidget->SetInteractor(renderView->GetInteractor());
m_distanceWidget->SetInteractor(renderView->GetInteractor());
// Set up link between the cameras of the two views
m_linkCameras->SetChildCamera(m_renderer->GetActiveCamera());
m_linkCameras->SetParentCamera(renderView->GetActiveCamera());
m_linkCameras->SetScaleLegendStyle(m_style);
m_linkCamerasId = renderView->GetActiveCamera()->AddObserver(
vtkCommand::ModifiedEvent, m_linkCameras.Get());
// Set initial values
setStyle(ScaleLegendStyle::Cube);
setVisibility(m_visible);
}
ScaleLegend::~ScaleLegend()
{
// Break the connection between the cameras of the two views
vtkSMViewProxy* view = ActiveObjects::instance().activeView();
vtkPVRenderView* renderView =
vtkPVRenderView::SafeDownCast(view->GetClientSideView());
if (renderView) {
renderView->GetActiveCamera()->RemoveObserver(m_linkCamerasId);
}
}
void ScaleLegend::setStyle(ScaleLegendStyle style)
{
m_style = style;
m_linkCameras->SetScaleLegendStyle(m_style);
if (m_style == ScaleLegendStyle::Cube) {
m_volumeScaleRep->SetRepresentationVisibility(m_visible ? 1 : 0);
m_lengthScaleRep->SetRepresentationVisibility(0);
} else if (m_style == ScaleLegendStyle::Ruler) {
m_lengthScaleRep->SetRepresentationVisibility(m_visible ? 1 : 0);
m_volumeScaleRep->SetRepresentationVisibility(0);
}
m_linkCameras->OrientCamera();
render();
}
void ScaleLegend::setVisibility(bool choice)
{
m_visible = choice;
if (m_style == ScaleLegendStyle::Cube) {
m_volumeScaleRep->SetRepresentationVisibility(choice);
} else if (m_style == ScaleLegendStyle::Ruler) {
m_lengthScaleRep->SetRepresentationVisibility(choice);
}
render();
}
void ScaleLegend::dataSourceAdded(DataSource* ds)
{
m_volumeScaleRep->SetLengthUnit(ds->getUnits(0).toStdString().c_str());
m_lengthScaleRep->SetLengthUnit(ds->getUnits(0).toStdString().c_str());
QObject::connect(ds, SIGNAL(dataPropertiesChanged()), this,
SLOT(dataPropertiesChanged()));
render();
}
void ScaleLegend::dataPropertiesChanged()
{
DataSource* data = qobject_cast<DataSource*>(sender());
if (!data) {
return;
}
m_volumeScaleRep->SetLengthUnit(data->getUnits(0).toStdString().c_str());
m_lengthScaleRep->SetLengthUnit(data->getUnits(0).toStdString().c_str());
}
void ScaleLegend::render()
{
pqView* view =
tomviz::convert<pqView*>(ActiveObjects::instance().activeView());
if (view) {
view->render();
}
}
}
<commit_msg>If ParaView warns about OpenGL there is no view<commit_after>/******************************************************************************
This source file is part of the tomviz project.
Copyright Kitware, Inc.
This source code is released under the New BSD License, (the "License").
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 "ScaleLegend.h"
#include "vtkAxisActor2D.h"
#include "vtkBillboardTextActor3D.h"
#include "vtkCamera.h"
#include "vtkCommand.h"
#include "vtkDistanceWidget.h"
#include "vtkHandleWidget.h"
#include "vtkLengthScaleRepresentation.h"
#include "vtkMath.h"
#include "vtkPointHandleRepresentation2D.h"
#include "vtkProperty2D.h"
#include "vtkRenderWindow.h"
#include "vtkRenderer.h"
#include "vtkTextActor.h"
#include "vtkTextProperty.h"
#include "vtkVolumeScaleRepresentation.h"
#include "pqView.h"
#include "vtkPVAxesWidget.h"
#include "vtkPVRenderView.h"
#include "vtkSMViewProxy.h"
#include "ActiveObjects.h"
#include "DataSource.h"
#include "MainWindow.h"
#include "ModuleManager.h"
#include "Utilities.h"
#include <math.h>
// The Scale legend lives in a sub-render window at the bottom right-hand corner
// of the viewing screen and has its own camera. vtkLinkCameras connects the
// sub-render window camera to the main window camera.
class vtkLinkCameras : public vtkCommand
{
public:
static vtkLinkCameras* New()
{
vtkLinkCameras* cb = new vtkLinkCameras;
return cb;
}
vtkLinkCameras() : Style(tomviz::ScaleLegendStyle::Cube) {}
void SetParentCamera(vtkCamera* c) { this->ParentCamera = c; }
void SetChildCamera(vtkCamera* c) { this->ChildCamera = c; }
void SetScaleLegendStyle(tomviz::ScaleLegendStyle style)
{
this->Style = style;
}
virtual void Execute(vtkObject* vtkNotUsed(caller),
unsigned long vtkNotUsed(eventId),
void* vtkNotUsed(callData))
{
this->OrientCamera();
}
void OrientCamera()
{
double pos[3], fp[3], viewup[3];
this->ParentCamera->GetPosition(pos);
this->ParentCamera->GetFocalPoint(fp);
this->ParentCamera->GetViewUp(viewup);
if (this->Style == tomviz::ScaleLegendStyle::Cube) {
// The child camera's focal point is always the origin, and its position
// is translated to have the same positional offset (both distance and
// orientation) between the camera and the object.
for (int i = 0; i < 3; i++) {
pos[i] -= fp[i];
fp[i] = 0.;
}
this->ChildCamera->SetPosition(pos);
this->ChildCamera->SetFocalPoint(fp);
this->ChildCamera->SetViewUp(viewup);
} else if (this->Style == tomviz::ScaleLegendStyle::Ruler) {
// The child camera's focal point is always the origin, and its position
// is translated to have the same distance (but not orientation) between
// the camera and the object. The camera's view is fixed.
double toFP[3];
this->ChildCamera->GetDirectionOfProjection(toFP);
double dist = sqrt(vtkMath::Distance2BetweenPoints(pos, fp));
for (int i = 0; i < 3; i++) {
pos[i] = 0.;
fp[i] = 0.;
}
pos[2] = -dist;
this->ChildCamera->SetPosition(pos);
this->ChildCamera->SetFocalPoint(fp);
double up[3] = { 0., 1., 0. };
this->ChildCamera->SetViewUp(up);
}
}
private:
vtkCamera* ParentCamera;
vtkCamera* ChildCamera;
tomviz::ScaleLegendStyle Style;
};
namespace tomviz {
ScaleLegend::ScaleLegend(QMainWindow* mw)
: Superclass(mw), mainWindow(mw), m_style(ScaleLegendStyle::Cube),
m_visible(false)
{
// Connect the data manager's "dataSourceAdded" to our "dataSourceAdded" slot
// to allow us to connect to the new data source's length scale information.
ModuleManager& mm = ModuleManager::instance();
QObject::connect(&mm, SIGNAL(dataSourceAdded(DataSource*)), this,
SLOT(dataSourceAdded(DataSource*)));
// Measurement cube
{
m_volumeScaleRep->GetLabel()->GetTextProperty()->SetFontSize(30);
m_volumeScaleRep->SetMinRelativeCubeScreenArea(.0002);
m_volumeScaleRep->SetMaxRelativeCubeScreenArea(.002);
m_handleWidget->CreateDefaultRepresentation();
m_handleWidget->SetRepresentation(m_volumeScaleRep.Get());
m_handleWidget->SetProcessEvents(0);
}
// Ruler
{
m_lengthScaleRep->InstantiateHandleRepresentation();
double p1[3] = { -.5, 0., 0. };
double p2[3] = { .5, 0., 0. };
m_lengthScaleRep->SetPoint1WorldPosition(p1);
m_lengthScaleRep->SetPoint2WorldPosition(p2);
m_lengthScaleRep->GetAxis()->SetTickLength(9);
m_lengthScaleRep->GetLabel()->GetTextProperty()->SetFontSize(30);
m_lengthScaleRep->SetMinRelativeScreenWidth(.03);
m_lengthScaleRep->SetMaxRelativeScreenWidth(.07);
m_distanceWidget->SetRepresentation(m_lengthScaleRep.Get());
}
m_renderer->SetViewport(0.85, 0.0, 1.0, 0.225);
// From vtkPVAxesWidget.cxx:
// Since Layer==1, the renderer is treated as transparent and
// vtkOpenGLRenderer::Clear() won't clear the color-buffer.
m_renderer->SetLayer(vtkPVAxesWidget::RendererLayer);
// Leaving Erase==1 ensures that the depth buffer is cleared. This ensures
// that the orientation widget always stays on top of the rendered scene.
m_renderer->EraseOn();
m_renderer->InteractiveOff();
m_renderer->AddActor(m_volumeScaleRep.Get());
m_renderer->AddActor(m_lengthScaleRep.Get());
// Add our sub-renderer to the main renderer
vtkSMViewProxy* view = ActiveObjects::instance().activeView();
if (!view) {
// Something is wrong with the view, exit early.
return;
}
vtkPVRenderView* renderView =
vtkPVRenderView::SafeDownCast(view->GetClientSideView());
renderView->GetRenderWindow()->AddRenderer(m_renderer.Get());
// Set up interactors
m_handleWidget->SetInteractor(renderView->GetInteractor());
m_distanceWidget->SetInteractor(renderView->GetInteractor());
// Set up link between the cameras of the two views
m_linkCameras->SetChildCamera(m_renderer->GetActiveCamera());
m_linkCameras->SetParentCamera(renderView->GetActiveCamera());
m_linkCameras->SetScaleLegendStyle(m_style);
m_linkCamerasId = renderView->GetActiveCamera()->AddObserver(
vtkCommand::ModifiedEvent, m_linkCameras.Get());
// Set initial values
setStyle(ScaleLegendStyle::Cube);
setVisibility(m_visible);
}
ScaleLegend::~ScaleLegend()
{
// Break the connection between the cameras of the two views
vtkSMViewProxy* view = ActiveObjects::instance().activeView();
vtkPVRenderView* renderView =
vtkPVRenderView::SafeDownCast(view->GetClientSideView());
if (renderView) {
renderView->GetActiveCamera()->RemoveObserver(m_linkCamerasId);
}
}
void ScaleLegend::setStyle(ScaleLegendStyle style)
{
m_style = style;
m_linkCameras->SetScaleLegendStyle(m_style);
if (m_style == ScaleLegendStyle::Cube) {
m_volumeScaleRep->SetRepresentationVisibility(m_visible ? 1 : 0);
m_lengthScaleRep->SetRepresentationVisibility(0);
} else if (m_style == ScaleLegendStyle::Ruler) {
m_lengthScaleRep->SetRepresentationVisibility(m_visible ? 1 : 0);
m_volumeScaleRep->SetRepresentationVisibility(0);
}
m_linkCameras->OrientCamera();
render();
}
void ScaleLegend::setVisibility(bool choice)
{
m_visible = choice;
if (m_style == ScaleLegendStyle::Cube) {
m_volumeScaleRep->SetRepresentationVisibility(choice);
} else if (m_style == ScaleLegendStyle::Ruler) {
m_lengthScaleRep->SetRepresentationVisibility(choice);
}
render();
}
void ScaleLegend::dataSourceAdded(DataSource* ds)
{
m_volumeScaleRep->SetLengthUnit(ds->getUnits(0).toStdString().c_str());
m_lengthScaleRep->SetLengthUnit(ds->getUnits(0).toStdString().c_str());
QObject::connect(ds, SIGNAL(dataPropertiesChanged()), this,
SLOT(dataPropertiesChanged()));
render();
}
void ScaleLegend::dataPropertiesChanged()
{
DataSource* data = qobject_cast<DataSource*>(sender());
if (!data) {
return;
}
m_volumeScaleRep->SetLengthUnit(data->getUnits(0).toStdString().c_str());
m_lengthScaleRep->SetLengthUnit(data->getUnits(0).toStdString().c_str());
}
void ScaleLegend::render()
{
pqView* view =
tomviz::convert<pqView*>(ActiveObjects::instance().activeView());
if (view) {
view->render();
}
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2014-2015 Ryan Leckey, All Rights Reserved.
// Distributed under the MIT License
// See accompanying file LICENSE
#include <string>
#include <sstream>
#include "clang.hpp"
#include "arrow/pass/declare.hpp"
#include "arrow/log.hpp"
using arrow::pass::Declare;
using arrow::ptr;
using arrow::Span;
using arrow::Position;
using arrow::make;
using arrow::cast;
using arrow::GContext;
namespace ir = arrow::ir;
namespace ast = arrow::ast;
struct CContext {
GContext ctx;
// Cache for realized types
std::unordered_map<std::string, ptr<ir::Type>> types;
};
struct CRecordContext {
CContext& cctx;
// Member results
std::vector<ptr<ir::TypeRecordMember>>& members;
};
struct CEnumContext {
CContext& cctx;
// Base Type
ptr<ir::Type> type;
};
CXChildVisitResult cx_visit(
CXCursor cursor, CXCursor parent, CXClientData clientData);
static ptr<ir::Type> resolve_c_type(CContext& cctx, CXType type);
static std::unordered_map<std::string, std::string> _c_typenames = {
{"unsigned char", "c_uchar"},
{"unsigned short", "c_ushort"},
{"unsigned int", "c_uint"},
{"unsigned long", "c_ulong"},
{"unsigned long long", "c_ullong"},
{"char", "c_char"},
{"signed char", "c_char"},
{"short", "c_short"},
{"int", "c_int"},
{"long", "c_long"},
{"long long", "c_llong"},
{"long double", "c_ldouble"},
{"double", "c_double"},
{"float", "c_float"},
};
static std::unordered_map<std::string, ptr<ir::Type>> _c_types;
static CXChildVisitResult _ctype_visit(
CXCursor cursor, CXCursor parent, CXClientData clientData
) {
auto c_kind = clang_getCursorKind(cursor);
auto c_name = clang_getCString(clang_getCursorSpelling(cursor));
switch (c_kind) {
case CXCursor_TypedefDecl: {
auto c_type = clang_getCanonicalType(clang_getCursorType(cursor));
auto size_bytes = clang_Type_getSizeOf(c_type);
auto size_bits = size_bytes * 8;
ptr<ir::Type> item;
switch (c_type.kind) {
case CXType_UChar:
case CXType_Char_U:
case CXType_UShort:
case CXType_UInt:
case CXType_ULong:
case CXType_ULongLong:
case CXType_UInt128:
item = arrow::make<ir::TypeInteger>(false, size_bits);
break;
case CXType_SChar:
case CXType_Char_S:
case CXType_Short:
case CXType_Int:
case CXType_Long:
case CXType_LongLong:
case CXType_Int128:
item = arrow::make<ir::TypeInteger>(true, size_bits);
break;
case CXType_Float:
case CXType_Double:
item = arrow::make<ir::TypeReal>(size_bits);
break;
default:
item = nullptr;
}
_c_types[c_name] = item;
} return CXChildVisit_Continue;
default:
break;
}
return CXChildVisit_Continue;
}
static void _require_c_types(GContext& ctx) {
if (_c_types.size() == 0) {
// Initialize clang
auto cx = clang_createIndex(1, 1);
// Declare C file with typedefs to primitive types
std::stringstream stream;
for (auto const& ref : _c_typenames) {
// Skip the stand-alone char type (its doubled because C is weird)
if (ref.first == "char") continue;
stream << "typedef ";
stream << ref.first;
stream << " ";
stream << ref.second;
stream << ";\n";
}
auto buffer = stream.str();
auto file = CXUnsavedFile{"main.c", buffer.c_str(), buffer.size()};
auto tu = clang_parseTranslationUnit(cx, "main.c", nullptr, 0, &file, 1,
CXTranslationUnit_DetailedPreprocessingRecord |
CXTranslationUnit_SkipFunctionBodies);
// Visit!
clang_visitChildren(clang_getTranslationUnitCursor(tu),
&_ctype_visit, nullptr);
// Dispose: clang
clang_disposeTranslationUnit(tu);
clang_disposeIndex(cx);
}
// Emplace into scope
for (auto const& ref : _c_typenames) {
if (_c_types[ref.second]) {
ctx.scope->put(ref.second, _c_types[ref.second]);
}
}
}
static std::string _c_typename(CXType c_type) {
// Ensure we're dealing with a canoncial type
c_type = clang_getCanonicalType(c_type);
auto c_typename = std::string(clang_getCString(
clang_getTypeSpelling(c_type)));
if (clang_isConstQualifiedType(c_type)) {
// Remove 'const ' from typename
c_typename = c_typename.substr(6);
}
// Determine typename
auto typename_ = _c_typenames[c_typename];
if (typename_ == "") {
return "";
}
// Add C basic type
return typename_;
}
static CXChildVisitResult _cx_record_visit(
CXCursor cursor, CXCursor parent, CXClientData clientData
) {
auto& crctx = *reinterpret_cast<CRecordContext*>(clientData);
auto& results = crctx.members;
auto c_kind = clang_getCursorKind(cursor);
auto c_name = clang_getCString(clang_getCursorSpelling(cursor));
if (c_kind == CXCursor_FieldDecl) {
auto c_type = resolve_c_type(crctx.cctx, clang_getCursorType(cursor));
if (!c_type) return CXChildVisit_Break;
results.push_back(make<ir::TypeRecordMember>(
nullptr, c_name, c_type
));
}
return CXChildVisit_Continue;
}
static CXChildVisitResult _cx_enum_visit(
CXCursor cursor, CXCursor parent, CXClientData clientData
) {
auto& cectx = *reinterpret_cast<CEnumContext*>(clientData);
auto c_kind = clang_getCursorKind(cursor);
auto c_name = clang_getCString(clang_getCursorSpelling(cursor));
if (c_kind == CXCursor_EnumConstantDecl) {
std::stringstream stream;
if (cectx.type->is_signed()) {
stream << clang_getEnumConstantDeclValue(cursor);
} else {
stream << clang_getEnumConstantDeclUnsignedValue(cursor);
}
mpz_class value{stream.str(), 10};
auto result = make<ir::Constant>(
c_name, cectx.type, make<ir::Integer>(nullptr, value));
cectx.cctx.ctx.scope->put(c_name, result);
}
return CXChildVisit_Continue;
}
static ptr<ir::Type> resolve_c_type(CContext& cctx, CXType type) {
auto ref = clang_getCanonicalType(type);
// Check the cache (for a realized type)
auto typename_ = std::string(clang_getCString(
clang_getTypeSpelling(ref)));
if (cctx.types.find(typename_) != cctx.types.end()) {
return cctx.types[typename_];
}
ptr<ir::Type> result;
bool continue_ = false;
if (ref.kind == CXType_Record) {
// Record (structure)
// Determine the unqualified name of this record to use
auto decl = clang_getTypeDeclaration(ref);
auto kind = clang_getCursorKind(decl);
auto declname_ = std::string(clang_getCString(
clang_getCursorSpelling(decl)));
auto name = declname_.size() == 0 ? typename_ : declname_;
// NOTE: Unions get expressed as an opaque struct
result = make<ir::TypeRecord>(nullptr, name);
if (kind == CXCursor_StructDecl) {
continue_ = true;
}
} else if (ref.kind == CXType_Enum) {
// Enum
// Determine the unqualified name
auto decl = clang_getTypeDeclaration(ref);
auto declname_ = std::string(clang_getCString(
clang_getCursorSpelling(decl)));
auto name = declname_.size() == 0 ? typename_ : declname_;
// After type resolution .. we need to resolve children
continue_ = true;
// Get the underlying type of this enum and resolve
auto underyling_t = clang_getEnumDeclIntegerType(decl);
result = resolve_c_type(cctx, underyling_t);
// Make an alias
result = make<ir::TypeAlias>(nullptr, name, result);
} else if (ref.kind == CXType_FunctionProto || ref.kind == CXType_FunctionNoProto) {
// Do: Result Type
auto result_t = resolve_c_type(cctx, clang_getResultType(ref));
if (!result_t) return nullptr;
// Do: Parameters
std::vector<ptr<ir::Type>> parameters;
bool failed = false;
for (auto i = 0; i < clang_getNumArgTypes(ref); ++i) {
auto atype = resolve_c_type(cctx, clang_getArgType(ref, i));
if (!atype) {
failed = true;
break;
}
parameters.push_back(atype);
}
if (failed) return nullptr;
// Make: Function Type
// TODO: ABI
result = make<ir::TypeExternFunction>(
nullptr, clang_isFunctionTypeVariadic(ref), "C", parameters, result_t);
} else if (ref.kind == CXType_Pointer) {
auto cpt = clang_getCanonicalType(clang_getPointeeType(type));
if (cpt.kind == CXType_FunctionProto || cpt.kind == CXType_FunctionNoProto) {
// Function Object/Pointer
result = resolve_c_type(cctx, cpt);
// Unwrap into ir::TypeFunction (callbacks)
if (result) {
result = make<ir::TypeFunction>(
nullptr,
cast<ir::TypeExternFunction>(result)->parameters,
cast<ir::TypeExternFunction>(result)->result
);
}
} else if (cpt.kind == CXType_Void) {
// Void Pointer -> *uint8
result = make<ir::TypePointer>(nullptr, make<ir::TypeInteger>(false, 8));
} else {
// Normal Pointer
auto pointee = resolve_c_type(cctx, cpt);
if (!pointee) return nullptr;
result = make<ir::TypePointer>(nullptr, pointee);
}
} else if (ref.kind == CXType_Void) {
result = make<ir::TypeUnit>();
} else {
auto typename_ = _c_typename(ref);
if (typename_ == "") return nullptr;
result = _c_types[typename_];
}
// Cache
if (result) cctx.types[typename_] = result;
// After cache ..
if (continue_) {
if (ref.kind == CXType_Record) {
auto decl = clang_getTypeDeclaration(ref);
// Visit children of structure
CRecordContext crctx = {
cctx,
cast<ir::TypeRecord>(result)->members
};
if (clang_visitChildren(decl, _cx_record_visit, &crctx) != 0) {
// No good.. couldn't resolve whole type
}
} else if (ref.kind == CXType_Enum) {
auto decl = clang_getTypeDeclaration(ref);
// Visit children of enum
CEnumContext cectx = {
cctx,
result
};
if (clang_visitChildren(decl, _cx_enum_visit, &cectx) != 0) {
// No good.. couldn't resolve whole enum
}
}
}
return result;
}
static CXChildVisitResult _cx_visit(
CXCursor cursor, CXCursor parent, CXClientData clientData
) {
auto& cctx = *reinterpret_cast<CContext*>(clientData);
auto c_kind = clang_getCursorKind(cursor);
auto c_name = clang_getCString(clang_getCursorSpelling(cursor));
ptr<ir::Item> item;
switch (c_kind) {
case CXCursor_TypedefDecl: {
auto c_type = resolve_c_type(cctx, clang_getCursorType(cursor));
if (!c_type) break;
// Make: Alias
// TODO: Use TypeAlias (?)
item = c_type;
} break;
case CXCursor_StructDecl:
case CXCursor_EnumDecl: {
auto c_type = resolve_c_type(cctx, clang_getCursorType(cursor));
if (!c_type) break;
item = c_type;
} break;
case CXCursor_FunctionDecl: {
auto type = resolve_c_type(cctx, clang_getCursorType(cursor));
if (!type) break;
// Make: External Function
item = make<ir::ExternFunction>(nullptr, cctx.ctx.module_s.top(), c_name,
cast<ir::TypeExternFunction>(type));
} break;
default:
break;
}
if (item) {
// arrow::Log::get().info("c: {} ({})", c_name, c_kind);
cctx.ctx.scope->put(c_name, item);
} else {
// arrow::Log::get().warn("unhandled: {} ({})", c_name, c_kind);
}
return CXChildVisit_Continue;
}
void Declare::visit_cinclude(ptr<ast::CInclude> x) {
// Require (import) C primitive types
_require_c_types(_ctx);
// Declare C file that includes the requested include
std::stringstream stream;
stream << "#include <" << x->source << ">\n";
// Initialize clang
auto cx = clang_createIndex(1, 1);
auto buffer = stream.str();
auto file = CXUnsavedFile{"main.c", buffer.c_str(), buffer.size()};
auto tu = clang_parseTranslationUnit(cx, "main.c", nullptr, 0, &file, 1,
CXTranslationUnit_DetailedPreprocessingRecord |
CXTranslationUnit_SkipFunctionBodies);
// Visit!
CContext cctx;
cctx.ctx = _ctx;
clang_visitChildren(clang_getTranslationUnitCursor(tu),
&_cx_visit, &cctx);
// Dispose: clang
clang_disposeTranslationUnit(tu);
clang_disposeIndex(cx);
}
<commit_msg>More fixes<commit_after>// Copyright (c) 2014-2015 Ryan Leckey, All Rights Reserved.
// Distributed under the MIT License
// See accompanying file LICENSE
#include <string>
#include <sstream>
#include "clang.hpp"
#include "arrow/pass/declare.hpp"
#include "arrow/log.hpp"
using arrow::pass::Declare;
using arrow::ptr;
using arrow::Span;
using arrow::Position;
using arrow::make;
using arrow::cast;
using arrow::GContext;
namespace ir = arrow::ir;
namespace ast = arrow::ast;
struct CContext {
GContext ctx;
// Cache for realized types
std::unordered_map<std::string, ptr<ir::Type>> types;
};
struct CRecordContext {
CContext& cctx;
// Member results
std::vector<ptr<ir::TypeRecordMember>>& members;
};
struct CEnumContext {
CContext& cctx;
// Base Type
ptr<ir::Type> type;
};
CXChildVisitResult cx_visit(
CXCursor cursor, CXCursor parent, CXClientData clientData);
static ptr<ir::Type> resolve_c_type(CContext& cctx, CXType type);
static std::unordered_map<std::string, std::string> _c_typenames = {
{"unsigned char", "c_uchar"},
{"unsigned short", "c_ushort"},
{"unsigned int", "c_uint"},
{"unsigned long", "c_ulong"},
{"unsigned long long", "c_ullong"},
{"char", "c_char"},
{"signed char", "c_char"},
{"short", "c_short"},
{"int", "c_int"},
{"long", "c_long"},
{"long long", "c_llong"},
{"long double", "c_ldouble"},
{"double", "c_double"},
{"float", "c_float"},
};
static std::unordered_map<std::string, ptr<ir::Type>> _c_types;
static CXChildVisitResult _ctype_visit(
CXCursor cursor, CXCursor parent, CXClientData clientData
) {
auto c_kind = clang_getCursorKind(cursor);
auto c_name = clang_getCString(clang_getCursorSpelling(cursor));
switch (c_kind) {
case CXCursor_TypedefDecl: {
auto c_type = clang_getCanonicalType(clang_getCursorType(cursor));
auto size_bytes = clang_Type_getSizeOf(c_type);
auto size_bits = size_bytes * 8;
ptr<ir::Type> item;
switch (c_type.kind) {
case CXType_UChar:
case CXType_Char_U:
case CXType_UShort:
case CXType_UInt:
case CXType_ULong:
case CXType_ULongLong:
case CXType_UInt128:
item = arrow::make<ir::TypeInteger>(false, size_bits);
break;
case CXType_SChar:
case CXType_Char_S:
case CXType_Short:
case CXType_Int:
case CXType_Long:
case CXType_LongLong:
case CXType_Int128:
item = arrow::make<ir::TypeInteger>(true, size_bits);
break;
case CXType_Float:
case CXType_Double:
item = arrow::make<ir::TypeReal>(size_bits);
break;
default:
item = nullptr;
}
_c_types[c_name] = item;
} return CXChildVisit_Continue;
default:
break;
}
return CXChildVisit_Continue;
}
static void _require_c_types(GContext& ctx) {
if (_c_types.size() == 0) {
// Initialize clang
auto cx = clang_createIndex(1, 1);
// Declare C file with typedefs to primitive types
std::stringstream stream;
for (auto const& ref : _c_typenames) {
// Skip the stand-alone char type (its doubled because C is weird)
if (ref.first == "char") continue;
stream << "typedef ";
stream << ref.first;
stream << " ";
stream << ref.second;
stream << ";\n";
}
auto buffer = stream.str();
auto file = CXUnsavedFile{"main.c", buffer.c_str(), buffer.size()};
auto tu = clang_parseTranslationUnit(cx, "main.c", nullptr, 0, &file, 1,
CXTranslationUnit_DetailedPreprocessingRecord |
CXTranslationUnit_SkipFunctionBodies);
// Visit!
clang_visitChildren(clang_getTranslationUnitCursor(tu),
&_ctype_visit, nullptr);
// Dispose: clang
clang_disposeTranslationUnit(tu);
clang_disposeIndex(cx);
}
// Emplace into scope
for (auto const& ref : _c_typenames) {
if (_c_types[ref.second]) {
ctx.scope->put(ref.second, _c_types[ref.second]);
}
}
}
static std::string _c_typename(CXType c_type) {
// Ensure we're dealing with a canoncial type
c_type = clang_getCanonicalType(c_type);
auto c_typename = std::string(clang_getCString(
clang_getTypeSpelling(c_type)));
if (clang_isConstQualifiedType(c_type)) {
// Remove 'const ' from typename
c_typename = c_typename.substr(6);
}
// Determine typename
auto typename_ = _c_typenames[c_typename];
if (typename_ == "") {
return "";
}
// Add C basic type
return typename_;
}
static CXChildVisitResult _cx_record_visit(
CXCursor cursor, CXCursor parent, CXClientData clientData
) {
auto& crctx = *reinterpret_cast<CRecordContext*>(clientData);
auto& results = crctx.members;
auto c_kind = clang_getCursorKind(cursor);
auto c_name = clang_getCString(clang_getCursorSpelling(cursor));
if (c_kind == CXCursor_FieldDecl) {
auto c_type = resolve_c_type(crctx.cctx, clang_getCursorType(cursor));
if (!c_type) return CXChildVisit_Break;
results.push_back(make<ir::TypeRecordMember>(
nullptr, c_name, c_type
));
}
return CXChildVisit_Continue;
}
static CXChildVisitResult _cx_enum_visit(
CXCursor cursor, CXCursor parent, CXClientData clientData
) {
auto& cectx = *reinterpret_cast<CEnumContext*>(clientData);
auto c_kind = clang_getCursorKind(cursor);
auto c_name = clang_getCString(clang_getCursorSpelling(cursor));
if (c_kind == CXCursor_EnumConstantDecl) {
std::stringstream stream;
if (cectx.type->is_signed()) {
stream << clang_getEnumConstantDeclValue(cursor);
} else {
stream << clang_getEnumConstantDeclUnsignedValue(cursor);
}
mpz_class value{stream.str(), 10};
auto result = make<ir::Constant>(
c_name, cectx.type, make<ir::Integer>(nullptr, value));
cectx.cctx.ctx.scope->put(c_name, result);
}
return CXChildVisit_Continue;
}
static std::string get_c_typename(CXType type) {
auto ref = clang_getCanonicalType(type);
auto typename_ = std::string(clang_getCString(
clang_getTypeSpelling(ref)));
if (ref.kind == CXType_Record || ref.kind == CXType_Enum) {
auto decl = clang_getTypeDeclaration(ref);
auto declname_ = std::string(clang_getCString(
clang_getCursorSpelling(decl)));
typename_ = declname_.size() == 0 ? typename_ : declname_;
}
return typename_;
}
static ptr<ir::Type> resolve_c_type(CContext& cctx, CXType type) {
auto ref = clang_getCanonicalType(type);
// Check the cache (for a realized type)
auto typename_ = get_c_typename(type);
if (cctx.types.find(typename_) != cctx.types.end()) {
return cctx.types[typename_];
}
ptr<ir::Type> result;
bool continue_ = false;
if (ref.kind == CXType_Record) {
// Record (structure)
auto decl = clang_getTypeDeclaration(ref);
auto kind = clang_getCursorKind(decl);
// NOTE: Unions get expressed as an opaque struct
result = make<ir::TypeRecord>(nullptr, typename_);
if (kind == CXCursor_StructDecl) {
continue_ = true;
}
} else if (ref.kind == CXType_Enum) {
// Enum
auto decl = clang_getTypeDeclaration(ref);
// After type resolution .. we need to resolve children
continue_ = true;
// Get the underlying type of this enum and resolve
auto underyling_t = clang_getEnumDeclIntegerType(decl);
result = resolve_c_type(cctx, underyling_t);
// TODO: Make an alias (?)
// result = make<ir::TypeAlias>(nullptr, name, result);
} else if (ref.kind == CXType_FunctionProto || ref.kind == CXType_FunctionNoProto) {
// Do: Result Type
auto result_t = resolve_c_type(cctx, clang_getResultType(ref));
if (!result_t) return nullptr;
// Do: Parameters
std::vector<ptr<ir::Type>> parameters;
bool failed = false;
for (auto i = 0; i < clang_getNumArgTypes(ref); ++i) {
auto atype = resolve_c_type(cctx, clang_getArgType(ref, i));
if (!atype) {
failed = true;
break;
}
parameters.push_back(atype);
}
if (failed) return nullptr;
// Make: Function Type
// TODO: ABI
result = make<ir::TypeExternFunction>(
nullptr, clang_isFunctionTypeVariadic(ref), "C", parameters, result_t);
} else if (ref.kind == CXType_Pointer) {
auto cpt = clang_getCanonicalType(clang_getPointeeType(type));
if (cpt.kind == CXType_FunctionProto || cpt.kind == CXType_FunctionNoProto) {
// Function Object/Pointer
result = resolve_c_type(cctx, cpt);
// Unwrap into ir::TypeFunction (callbacks)
if (result) {
result = make<ir::TypeFunction>(
nullptr,
cast<ir::TypeExternFunction>(result)->parameters,
cast<ir::TypeExternFunction>(result)->result
);
}
} else if (cpt.kind == CXType_Void) {
// Void Pointer -> *uint8
result = make<ir::TypePointer>(nullptr, make<ir::TypeInteger>(false, 8));
} else {
// Normal Pointer
auto pointee = resolve_c_type(cctx, cpt);
if (!pointee) return nullptr;
result = make<ir::TypePointer>(nullptr, pointee);
}
} else if (ref.kind == CXType_Void) {
result = make<ir::TypeUnit>();
} else {
auto typename_ = _c_typename(ref);
if (typename_ == "") return nullptr;
result = _c_types[typename_];
}
// Cache
if (result) cctx.types[typename_] = result;
// After cache ..
if (continue_) {
if (ref.kind == CXType_Record) {
auto decl = clang_getTypeDeclaration(ref);
// Visit children of structure
CRecordContext crctx = {
cctx,
cast<ir::TypeRecord>(result)->members
};
if (clang_visitChildren(decl, _cx_record_visit, &crctx) != 0) {
// No good.. couldn't resolve whole type
}
} else if (ref.kind == CXType_Enum) {
auto decl = clang_getTypeDeclaration(ref);
// Visit children of enum
CEnumContext cectx = {
cctx,
result
};
if (clang_visitChildren(decl, _cx_enum_visit, &cectx) != 0) {
// No good.. couldn't resolve whole enum
}
}
}
return result;
}
static CXChildVisitResult _cx_visit(
CXCursor cursor, CXCursor parent, CXClientData clientData
) {
auto& cctx = *reinterpret_cast<CContext*>(clientData);
auto c_kind = clang_getCursorKind(cursor);
auto c_name = clang_getCString(clang_getCursorSpelling(cursor));
ptr<ir::Item> item;
switch (c_kind) {
case CXCursor_TypedefDecl: {
auto c_type = resolve_c_type(cctx, clang_getCursorType(cursor));
if (!c_type) break;
// Make: Alias
// TODO: Use TypeAlias (?)
item = c_type;
} break;
case CXCursor_UnionDecl:
case CXCursor_StructDecl:
case CXCursor_EnumDecl: {
auto c_type = resolve_c_type(cctx, clang_getCursorType(cursor));
if (!c_type) break;
item = c_type;
} break;
case CXCursor_FunctionDecl: {
auto type = resolve_c_type(cctx, clang_getCursorType(cursor));
if (!type) break;
// Make: External Function
item = make<ir::ExternFunction>(nullptr, cctx.ctx.module_s.top(), c_name,
cast<ir::TypeExternFunction>(type));
} break;
default:
break;
}
if (item) {
// arrow::Log::get().info("c: {} ({})", c_name, c_kind);
cctx.ctx.scope->put(c_name, item);
} else {
// arrow::Log::get().warn("unhandled: {} ({})", c_name, c_kind);
}
return CXChildVisit_Continue;
}
void Declare::visit_cinclude(ptr<ast::CInclude> x) {
// Require (import) C primitive types
_require_c_types(_ctx);
// Declare C file that includes the requested include
std::stringstream stream;
stream << "#include <" << x->source << ">\n";
// Initialize clang
auto cx = clang_createIndex(1, 1);
auto buffer = stream.str();
auto file = CXUnsavedFile{"main.c", buffer.c_str(), buffer.size()};
auto tu = clang_parseTranslationUnit(cx, "main.c", nullptr, 0, &file, 1,
CXTranslationUnit_DetailedPreprocessingRecord |
CXTranslationUnit_SkipFunctionBodies);
// Visit!
CContext cctx;
cctx.ctx = _ctx;
clang_visitChildren(clang_getTranslationUnitCursor(tu),
&_cx_visit, &cctx);
// Dispose: clang
clang_disposeTranslationUnit(tu);
clang_disposeIndex(cx);
}
<|endoftext|> |
<commit_before>
#include <cstdio>
#include <fstream>
#include <gtest/gtest.h>
#include "lw/event.hpp"
#include "lw/fs.hpp"
#include "lw/memory.hpp"
namespace lw {
namespace tests {
struct FileTests : public testing::Test {
event::Loop loop;
std::string file_name = "/tmp/liblw-filetests-testfile";
std::string content_str = "an awesome message to keep";
memory::Buffer contents;
FileTests( void ):
contents( content_str.size() )
{
contents.copy( content_str.begin(), content_str.end() );
}
void TearDown( void ){
std::remove( file_name.c_str() );
}
};
// -------------------------------------------------------------------------- //
TEST_F( FileTests, Open ){
fs::File file( loop );
bool started = false;
bool finished = false;
bool promise_called = false;
file.open( file_name ).then([&]( event::Promise<>&& next ){
EXPECT_TRUE( started );
EXPECT_FALSE( finished );
promise_called = true;
});
started = true;
loop.run();
finished = true;
EXPECT_TRUE( promise_called );
}
// -------------------------------------------------------------------------- //
TEST_F( FileTests, Close ){
fs::File file( loop );
file.open( file_name ).then([&](){
return file.close();
});
loop.run();
}
// -------------------------------------------------------------------------- //
TEST_F( FileTests, Write ){
fs::File file( loop );
file.open( file_name )
.then([&](){ return file.write( contents ); })
.then([&](){ return file.close(); })
;
loop.run();
std::ifstream test_stream( file_name );
std::string test_string;
std::getline( test_stream, test_string );
EXPECT_EQ(
memory::Buffer( test_string.begin(), test_string.end() ),
contents
);
}
// -------------------------------------------------------------------------- //
TEST_F( FileTests, Read ){
fs::File write_file( loop );
fs::File read_file( loop );
bool made_it_to_the_end = false;
write_file
.open( file_name )
.then([&](){ return write_file.write( contents ); })
.then([&](){ return write_file.close(); })
.then([&](){ return read_file.open( file_name ); })
.then([&](){ return read_file.read( contents.size() ); })
.then([&]( memory::Buffer&& data ){
EXPECT_EQ( contents, data );
made_it_to_the_end = true;
});
;
loop.run();
EXPECT_TRUE( made_it_to_the_end );
}
}
}
<commit_msg>Removed dud promise<commit_after>
#include <cstdio>
#include <fstream>
#include <gtest/gtest.h>
#include "lw/event.hpp"
#include "lw/fs.hpp"
#include "lw/memory.hpp"
namespace lw {
namespace tests {
struct FileTests : public testing::Test {
event::Loop loop;
std::string file_name = "/tmp/liblw-filetests-testfile";
std::string content_str = "an awesome message to keep";
memory::Buffer contents;
FileTests( void ):
contents( content_str.size() )
{
contents.copy( content_str.begin(), content_str.end() );
}
void TearDown( void ){
std::remove( file_name.c_str() );
}
};
// -------------------------------------------------------------------------- //
TEST_F( FileTests, Open ){
fs::File file( loop );
bool started = false;
bool finished = false;
bool promise_called = false;
file.open( file_name ).then([&](){
EXPECT_TRUE( started );
EXPECT_FALSE( finished );
promise_called = true;
});
started = true;
loop.run();
finished = true;
EXPECT_TRUE( promise_called );
}
// -------------------------------------------------------------------------- //
TEST_F( FileTests, Close ){
fs::File file( loop );
file.open( file_name ).then([&](){
return file.close();
});
loop.run();
}
// -------------------------------------------------------------------------- //
TEST_F( FileTests, Write ){
fs::File file( loop );
file.open( file_name )
.then([&](){ return file.write( contents ); })
.then([&](){ return file.close(); })
;
loop.run();
std::ifstream test_stream( file_name );
std::string test_string;
std::getline( test_stream, test_string );
EXPECT_EQ(
memory::Buffer( test_string.begin(), test_string.end() ),
contents
);
}
// -------------------------------------------------------------------------- //
TEST_F( FileTests, Read ){
fs::File write_file( loop );
fs::File read_file( loop );
bool made_it_to_the_end = false;
write_file
.open( file_name )
.then([&](){ return write_file.write( contents ); })
.then([&](){ return write_file.close(); })
.then([&](){ return read_file.open( file_name ); })
.then([&](){ return read_file.read( contents.size() ); })
.then([&]( memory::Buffer&& data ){
EXPECT_EQ( contents, data );
made_it_to_the_end = true;
});
;
loop.run();
EXPECT_TRUE( made_it_to_the_end );
}
}
}
<|endoftext|> |
<commit_before>/* Gearman server and library
* Copyright (C) 2008 Brian Aker, Eric Day
* All rights reserved.
*
* Use and distribution licensed under the BSD license. See
* the COPYING file in the parent directory for full text.
*/
#include <config.h>
#include <libtest/test.hpp>
using namespace libtest;
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <sys/time.h>
#include <libgearman/gearman.h>
#include <libhostile/hostile.h>
#include <tests/start_worker.h>
#include <tests/workers.h>
#include "tests/burnin.h"
#define WORKER_FUNCTION_NAME "foo"
struct client_thread_context_st
{
size_t count;
size_t payload_size;
client_thread_context_st() :
count(0),
payload_size(0)
{ }
void increment()
{
count++;
}
};
extern "C" {
static void client_cleanup(void *client)
{
int oldstate;
pthread_setcanceltype(PTHREAD_CANCEL_DISABLE, &oldstate);
gearman_client_free((gearman_client_st *)client);
pthread_setcanceltype(oldstate, NULL);
}
static void *client_thread(void *object)
{
client_thread_context_st *success= (client_thread_context_st *)object;
fatal_assert(success);
fatal_assert(success->count == 0);
gearman_return_t rc;
gearman_client_st *client;
{
int oldstate;
pthread_setcanceltype(PTHREAD_CANCEL_DISABLE, &oldstate);
client= gearman_client_create(NULL);
if (client == NULL)
{
pthread_exit(0);
}
rc= gearman_client_add_server(client, NULL, libtest::default_port());
pthread_setcanceltype(oldstate, NULL);
}
pthread_cleanup_push(client_cleanup, client);
if (gearman_success(rc))
{
gearman_client_set_timeout(client, 400);
for (size_t x= 0; x < 100; x++)
{
int oldstate;
pthread_setcanceltype(PTHREAD_CANCEL_DISABLE, &oldstate);
libtest::vchar_t payload;
payload.resize(success->payload_size);
void *value= gearman_client_do(client, WORKER_FUNCTION_NAME,
NULL,
&payload[0], payload.size(),
NULL, &rc);
pthread_setcanceltype(oldstate, NULL);
if (gearman_success(rc))
{
success->increment();
}
if (value)
{
free(value);
}
}
}
pthread_cleanup_pop(1);
pthread_exit(0);
}
}
static test_return_t worker_ramp_exec(const size_t payload_size)
{
std::vector<pthread_t> children;
children.resize(number_of_cpus());
std::vector<client_thread_context_st> success;
success.resize(children.size());
for (size_t x= 0; x < children.size(); x++)
{
success[x].payload_size= payload_size;
pthread_create(&children[x], NULL, client_thread, &success[x]);
}
for (size_t x= 0; x < children.size(); x++)
{
#if _GNU_SOURCE && defined(TARGET_OS_LINUX) && TARGET_OS_LINUX
{
struct timespec ts;
if (HAVE_LIBRT)
{
if (clock_gettime(CLOCK_REALTIME, &ts) == -1)
{
Error << strerror(errno);
}
}
else
{
struct timeval tv;
if (gettimeofday(&tv, NULL) == -1)
{
Error << strerror(errno);
}
TIMEVAL_TO_TIMESPEC(&tv, &ts);
}
ts.tv_sec+= 10;
int error= pthread_timedjoin_np(children[x], NULL, &ts);
if (error != 0)
{
pthread_cancel(children[x]);
pthread_join(children[x], NULL);
}
}
#else
pthread_join(children[x], NULL);
#endif
}
return TEST_SUCCESS;
}
static test_return_t worker_ramp_TEST(void *)
{
return worker_ramp_exec(0);
}
static test_return_t worker_ramp_1K_TEST(void *)
{
return worker_ramp_exec(1024);
}
static test_return_t worker_ramp_10K_TEST(void *)
{
return worker_ramp_exec(1024*10);
}
static test_return_t worker_ramp_SETUP(void *object)
{
test_skip_valgrind();
worker_handles_st *handles= (worker_handles_st*)object;
gearman_function_t echo_react_fn= gearman_function_create(echo_or_react_worker_v2);
for (uint32_t x= 0; x < 10; x++)
{
worker_handle_st *worker;
if ((worker= test_worker_start(libtest::default_port(), NULL, WORKER_FUNCTION_NAME, echo_react_fn, NULL, gearman_worker_options_t())) == NULL)
{
return TEST_FAILURE;
}
handles->push(worker);
}
return TEST_SUCCESS;
}
static test_return_t worker_ramp_TEARDOWN(void* object)
{
worker_handles_st *handles= (worker_handles_st*)object;
handles->reset();
return TEST_SUCCESS;
}
static test_return_t recv_SETUP(void* object)
{
test_skip_valgrind();
test_skip(true, bool(getenv("YATL_RUN_MASSIVE_TESTS")));
worker_ramp_SETUP(object);
set_recv_close(true, 20, 20);
return TEST_SUCCESS;
}
static test_return_t resv_TEARDOWN(void* object)
{
set_recv_close(true, 0, 0);
worker_handles_st *handles= (worker_handles_st*)object;
handles->kill_all();
return TEST_SUCCESS;
}
static test_return_t send_SETUP(void* object)
{
test_skip_valgrind();
test_skip(true, bool(getenv("YATL_RUN_MASSIVE_TESTS")));
worker_ramp_SETUP(object);
set_send_close(true, 20, 20);
return TEST_SUCCESS;
}
static test_return_t accept_SETUP(void* object)
{
test_skip_valgrind();
test_skip(true, bool(getenv("YATL_RUN_MASSIVE_TESTS")));
worker_ramp_SETUP(object);
set_accept_close(true, 20, 20);
return TEST_SUCCESS;
}
static test_return_t poll_SETUP(void* object)
{
return TEST_SKIPPED; // Not running correctly all of the time.
test_skip_valgrind();
test_skip(true, bool(getenv("YATL_RUN_MASSIVE_TESTS")));
worker_ramp_SETUP(object);
set_poll_close(true, 4, 0);
return TEST_SUCCESS;
}
static test_return_t poll_TEARDOWN(void* object)
{
set_poll_close(true, 0, 0);
worker_handles_st *handles= (worker_handles_st*)object;
handles->kill_all();
return TEST_SUCCESS;
}
static test_return_t send_TEARDOWN(void* object)
{
set_send_close(true, 0, 0);
worker_handles_st *handles= (worker_handles_st*)object;
handles->kill_all();
return TEST_SUCCESS;
}
static test_return_t accept_TEARDOWN(void* object)
{
set_accept_close(true, 0, 0);
worker_handles_st *handles= (worker_handles_st*)object;
handles->kill_all();
return TEST_SUCCESS;
}
/*********************** World functions **************************************/
static void *world_create(server_startup_st& servers, test_return_t& error)
{
if (server_startup(servers, "gearmand", libtest::default_port(), 0, NULL) == false)
{
error= TEST_FAILURE;
return NULL;
}
return new worker_handles_st;
}
static bool world_destroy(void *object)
{
worker_handles_st *handles= (worker_handles_st *)object;
delete handles;
return TEST_SUCCESS;
}
test_st burnin_TESTS[] ={
{"burnin", 0, burnin_TEST },
{0, 0, 0}
};
test_st worker_TESTS[] ={
{"first pass", 0, worker_ramp_TEST },
{"second pass", 0, worker_ramp_TEST },
{"first pass 1K jobs", 0, worker_ramp_1K_TEST },
{"first pass 10K jobs", 0, worker_ramp_10K_TEST },
{0, 0, 0}
};
collection_st collection[] ={
{"burnin", burnin_setup, burnin_cleanup, burnin_TESTS },
{"plain", worker_ramp_SETUP, worker_ramp_TEARDOWN, worker_TESTS },
{"hostile recv()", recv_SETUP, resv_TEARDOWN, worker_TESTS },
{"hostile send()", send_SETUP, send_TEARDOWN, worker_TESTS },
{"hostile accept()", accept_SETUP, accept_TEARDOWN, worker_TESTS },
{"hostile poll()", poll_SETUP, poll_TEARDOWN, worker_TESTS },
{0, 0, 0, 0}
};
void get_world(Framework *world)
{
world->collections(collection);
world->create(world_create);
world->destroy(world_destroy);
}
<commit_msg>Enable poll()<commit_after>/* Gearman server and library
* Copyright (C) 2008 Brian Aker, Eric Day
* All rights reserved.
*
* Use and distribution licensed under the BSD license. See
* the COPYING file in the parent directory for full text.
*/
#include <config.h>
#include <libtest/test.hpp>
using namespace libtest;
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <sys/time.h>
#include <libgearman/gearman.h>
#include <libhostile/hostile.h>
#include <tests/start_worker.h>
#include <tests/workers.h>
#include "tests/burnin.h"
#define WORKER_FUNCTION_NAME "foo"
struct client_thread_context_st
{
size_t count;
size_t payload_size;
client_thread_context_st() :
count(0),
payload_size(0)
{ }
void increment()
{
count++;
}
};
extern "C" {
static void client_cleanup(void *client)
{
int oldstate;
pthread_setcanceltype(PTHREAD_CANCEL_DISABLE, &oldstate);
gearman_client_free((gearman_client_st *)client);
pthread_setcanceltype(oldstate, NULL);
}
static void *client_thread(void *object)
{
client_thread_context_st *success= (client_thread_context_st *)object;
fatal_assert(success);
fatal_assert(success->count == 0);
gearman_return_t rc;
gearman_client_st *client;
{
int oldstate;
pthread_setcanceltype(PTHREAD_CANCEL_DISABLE, &oldstate);
client= gearman_client_create(NULL);
if (client == NULL)
{
pthread_exit(0);
}
rc= gearman_client_add_server(client, NULL, libtest::default_port());
pthread_setcanceltype(oldstate, NULL);
}
pthread_cleanup_push(client_cleanup, client);
if (gearman_success(rc))
{
gearman_client_set_timeout(client, 400);
for (size_t x= 0; x < 100; x++)
{
int oldstate;
pthread_setcanceltype(PTHREAD_CANCEL_DISABLE, &oldstate);
libtest::vchar_t payload;
payload.resize(success->payload_size);
void *value= gearman_client_do(client, WORKER_FUNCTION_NAME,
NULL,
&payload[0], payload.size(),
NULL, &rc);
pthread_setcanceltype(oldstate, NULL);
if (gearman_success(rc))
{
success->increment();
}
if (value)
{
free(value);
}
}
}
pthread_cleanup_pop(1);
pthread_exit(0);
}
}
static test_return_t worker_ramp_exec(const size_t payload_size)
{
std::vector<pthread_t> children;
children.resize(number_of_cpus());
std::vector<client_thread_context_st> success;
success.resize(children.size());
for (size_t x= 0; x < children.size(); x++)
{
success[x].payload_size= payload_size;
pthread_create(&children[x], NULL, client_thread, &success[x]);
}
for (size_t x= 0; x < children.size(); x++)
{
#if _GNU_SOURCE && defined(TARGET_OS_LINUX) && TARGET_OS_LINUX
{
struct timespec ts;
if (HAVE_LIBRT)
{
if (clock_gettime(CLOCK_REALTIME, &ts) == -1)
{
Error << strerror(errno);
}
}
else
{
struct timeval tv;
if (gettimeofday(&tv, NULL) == -1)
{
Error << strerror(errno);
}
TIMEVAL_TO_TIMESPEC(&tv, &ts);
}
ts.tv_sec+= 10;
int error= pthread_timedjoin_np(children[x], NULL, &ts);
if (error != 0)
{
pthread_cancel(children[x]);
pthread_join(children[x], NULL);
}
}
#else
pthread_join(children[x], NULL);
#endif
}
return TEST_SUCCESS;
}
static test_return_t worker_ramp_TEST(void *)
{
return worker_ramp_exec(0);
}
static test_return_t worker_ramp_1K_TEST(void *)
{
return worker_ramp_exec(1024);
}
static test_return_t worker_ramp_10K_TEST(void *)
{
return worker_ramp_exec(1024*10);
}
static test_return_t worker_ramp_SETUP(void *object)
{
test_skip_valgrind();
worker_handles_st *handles= (worker_handles_st*)object;
gearman_function_t echo_react_fn= gearman_function_create(echo_or_react_worker_v2);
for (uint32_t x= 0; x < 10; x++)
{
worker_handle_st *worker;
if ((worker= test_worker_start(libtest::default_port(), NULL, WORKER_FUNCTION_NAME, echo_react_fn, NULL, gearman_worker_options_t())) == NULL)
{
return TEST_FAILURE;
}
handles->push(worker);
}
return TEST_SUCCESS;
}
static test_return_t worker_ramp_TEARDOWN(void* object)
{
worker_handles_st *handles= (worker_handles_st*)object;
handles->reset();
return TEST_SUCCESS;
}
static test_return_t recv_SETUP(void* object)
{
test_skip_valgrind();
test_skip(true, bool(getenv("YATL_RUN_MASSIVE_TESTS")));
worker_ramp_SETUP(object);
set_recv_close(true, 20, 20);
return TEST_SUCCESS;
}
static test_return_t resv_TEARDOWN(void* object)
{
set_recv_close(true, 0, 0);
worker_handles_st *handles= (worker_handles_st*)object;
handles->kill_all();
return TEST_SUCCESS;
}
static test_return_t send_SETUP(void* object)
{
test_skip_valgrind();
test_skip(true, bool(getenv("YATL_RUN_MASSIVE_TESTS")));
worker_ramp_SETUP(object);
set_send_close(true, 20, 20);
return TEST_SUCCESS;
}
static test_return_t accept_SETUP(void* object)
{
test_skip_valgrind();
test_skip(true, bool(getenv("YATL_RUN_MASSIVE_TESTS")));
worker_ramp_SETUP(object);
set_accept_close(true, 20, 20);
return TEST_SUCCESS;
}
static test_return_t poll_SETUP(void* object)
{
test_skip_valgrind();
test_skip(true, bool(getenv("YATL_RUN_MASSIVE_TESTS")));
worker_ramp_SETUP(object);
set_poll_close(true, 4, 0);
return TEST_SUCCESS;
}
static test_return_t poll_TEARDOWN(void* object)
{
set_poll_close(true, 0, 0);
worker_handles_st *handles= (worker_handles_st*)object;
handles->kill_all();
return TEST_SUCCESS;
}
static test_return_t send_TEARDOWN(void* object)
{
set_send_close(true, 0, 0);
worker_handles_st *handles= (worker_handles_st*)object;
handles->kill_all();
return TEST_SUCCESS;
}
static test_return_t accept_TEARDOWN(void* object)
{
set_accept_close(true, 0, 0);
worker_handles_st *handles= (worker_handles_st*)object;
handles->kill_all();
return TEST_SUCCESS;
}
/*********************** World functions **************************************/
static void *world_create(server_startup_st& servers, test_return_t& error)
{
if (server_startup(servers, "gearmand", libtest::default_port(), 0, NULL) == false)
{
error= TEST_FAILURE;
return NULL;
}
return new worker_handles_st;
}
static bool world_destroy(void *object)
{
worker_handles_st *handles= (worker_handles_st *)object;
delete handles;
return TEST_SUCCESS;
}
test_st burnin_TESTS[] ={
{"burnin", 0, burnin_TEST },
{0, 0, 0}
};
test_st worker_TESTS[] ={
{"first pass", 0, worker_ramp_TEST },
{"second pass", 0, worker_ramp_TEST },
{"first pass 1K jobs", 0, worker_ramp_1K_TEST },
{"first pass 10K jobs", 0, worker_ramp_10K_TEST },
{0, 0, 0}
};
collection_st collection[] ={
{"burnin", burnin_setup, burnin_cleanup, burnin_TESTS },
{"plain", worker_ramp_SETUP, worker_ramp_TEARDOWN, worker_TESTS },
{"hostile recv()", recv_SETUP, resv_TEARDOWN, worker_TESTS },
{"hostile send()", send_SETUP, send_TEARDOWN, worker_TESTS },
{"hostile accept()", accept_SETUP, accept_TEARDOWN, worker_TESTS },
{"hostile poll()", poll_SETUP, poll_TEARDOWN, worker_TESTS },
{0, 0, 0, 0}
};
void get_world(Framework *world)
{
world->collections(collection);
world->create(world_create);
world->destroy(world_destroy);
}
<|endoftext|> |
<commit_before>/* -*- mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
// vim:sts=4:sw=4:ts=4:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
/*
* Copyright (C) 2015 the FFLAS-FFPACK group
* Written by Jean-Guillaume Dumas <Jean-Guillaume.Dumas@imag.fr>
*
* This file is Free Software and part of FFLAS-FFPACK.
*
* ========LICENCE========
* This file is part of the library FFLAS-FFPACK.
*
* FFLAS-FFPACK is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* ========LICENCE========
*
*/
//--------------------------------------------------------------------------
// Test for Checker_PLUQ
//--------------------------------------------------------------------------
//#define ENABLE_ALL_CHECKINGS 1
#define ENABLE_CHECKER_Det 1
#define TIME_CHECKER_Det 1
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include "checkers_ffpack.inl"
#include "fflas-ffpack/fflas-ffpack.h"
#include "fflas-ffpack/utils/args-parser.h"
#include "fflas-ffpack/checkers/checkers_ffpack.h"
#include "fflas-ffpack/checkers/checkers_ffpack.inl"
int main(int argc, char** argv) {
size_t iter = 3 ;
Givaro::Integer q = 131071;
size_t MAXN = 1000;
size_t n=0;
size_t seed( time(NULL) );
bool random_dim = false, random_rpm=false;
Argument as[] = {
{ 'q', "-q Q", "Set the field characteristic (-1 for random).", TYPE_INTEGER , &q },
{ 'm', "-m M", "Set the dimension of A.", TYPE_INT , &n },
{ 'n', "-n N", "Set the dimension of A.", TYPE_INT , &n },
{ 'i', "-i R", "Set number of repetitions.", TYPE_INT , &iter },
{ 's', "-s N", "Set the seed.", TYPE_INT , &seed },
{ 'r', "-r Y/N", "Set random RPM or not.", TYPE_BOOL, &random_rpm },
END_OF_ARGUMENTS
};
FFLAS::parseArguments(argc,argv,as);
if (n == 0) random_dim = true;
typedef Givaro::Modular<double> Field;
Field F(q);
Field::RandIter Rand(F,0,seed);
srandom(seed);
size_t pass = 0; // number of tests that have successfully passed
FFLAS::FFLAS_DIAG Diag = FFLAS::FflasNonUnit;
for(size_t it=0; it<iter; ++it) {
#ifdef TIME_CHECKER_Det
FFLAS::Timer init;init.start();
#endif
if (random_dim) {
n = random() % MAXN + 1;
}
Field::Element_ptr A = FFLAS::fflas_new(F,n,n);
size_t *P = FFLAS::fflas_new<size_t>(n);
size_t *Q = FFLAS::fflas_new<size_t>(n);
// generate a random matrix A
// PAR_BLOCK { FFLAS::pfrand(F,Rand, n,n,A,n/MAX_THREADS); }
PAR_BLOCK {
if (random_rpm)
FFPACK::RandomMatrixWithRankandRandomRPM(F,n,n,n,A,n,Rand);
else
FFLAS::pfrand(F,Rand, n,n,A,n/MAX_THREADS);
}
init.stop();
std::cerr << "init: " << init << std::endl;
Field::Element det; F.init(det);
try {
FFPACK::ForceCheck_Det<Field> checker (Rand,n,A,n);
Givaro::Timer chrono; chrono.start();
FFPACK::Det(det,F,n,n,A,n,P,Q,Diag);
chrono.stop();
checker.check(det,A,n,Diag,P,Q);
// FFPACK::Det(det,F,n,n,A,n,P,Q);
// chrono.stop();
// checker.check(det,A,n,FFLAS::FflasNonUnit,P,Q);
F.write(std::cerr << n << 'x' << n << ' ' << Diag << '(', det) << ')' << " Det verification PASSED\n" ;
#ifdef TIME_CHECKER_Det
std::cerr << "Det COMPT: " << chrono << std::endl;
#endif
pass++;
} catch(FailureDetCheck &e) {
F.write(std::cerr << n << 'x' << n << ' ' << Diag << '(', det) << ')' << " Det verification FAILED!\n";
}
FFLAS::fflas_delete(A,P,Q);
Diag = (Diag == FFLAS::FflasNonUnit) ? FFLAS::FflasUnit : FFLAS::FflasNonUnit;
}
std::cerr << pass << "/" << iter << " tests SUCCESSFUL.\n";
return (iter-pass);
}
<commit_msg>oups bad include<commit_after>/* -*- mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
// vim:sts=4:sw=4:ts=4:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
/*
* Copyright (C) 2015 the FFLAS-FFPACK group
* Written by Jean-Guillaume Dumas <Jean-Guillaume.Dumas@imag.fr>
*
* This file is Free Software and part of FFLAS-FFPACK.
*
* ========LICENCE========
* This file is part of the library FFLAS-FFPACK.
*
* FFLAS-FFPACK is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* ========LICENCE========
*
*/
//--------------------------------------------------------------------------
// Test for Checker_PLUQ
//--------------------------------------------------------------------------
//#define ENABLE_ALL_CHECKINGS 1
#define ENABLE_CHECKER_Det 1
#define TIME_CHECKER_Det 1
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include "fflas-ffpack/fflas-ffpack.h"
#include "fflas-ffpack/utils/args-parser.h"
#include "fflas-ffpack/checkers/checkers_ffpack.h"
#include "fflas-ffpack/checkers/checkers_ffpack.inl"
int main(int argc, char** argv) {
size_t iter = 3 ;
Givaro::Integer q = 131071;
size_t MAXN = 1000;
size_t n=0;
size_t seed( time(NULL) );
bool random_dim = false, random_rpm=false;
Argument as[] = {
{ 'q', "-q Q", "Set the field characteristic (-1 for random).", TYPE_INTEGER , &q },
{ 'm', "-m M", "Set the dimension of A.", TYPE_INT , &n },
{ 'n', "-n N", "Set the dimension of A.", TYPE_INT , &n },
{ 'i', "-i R", "Set number of repetitions.", TYPE_INT , &iter },
{ 's', "-s N", "Set the seed.", TYPE_INT , &seed },
{ 'r', "-r Y/N", "Set random RPM or not.", TYPE_BOOL, &random_rpm },
END_OF_ARGUMENTS
};
FFLAS::parseArguments(argc,argv,as);
if (n == 0) random_dim = true;
typedef Givaro::Modular<double> Field;
Field F(q);
Field::RandIter Rand(F,0,seed);
srandom(seed);
size_t pass = 0; // number of tests that have successfully passed
FFLAS::FFLAS_DIAG Diag = FFLAS::FflasNonUnit;
for(size_t it=0; it<iter; ++it) {
#ifdef TIME_CHECKER_Det
FFLAS::Timer init;init.start();
#endif
if (random_dim) {
n = random() % MAXN + 1;
}
Field::Element_ptr A = FFLAS::fflas_new(F,n,n);
size_t *P = FFLAS::fflas_new<size_t>(n);
size_t *Q = FFLAS::fflas_new<size_t>(n);
// generate a random matrix A
// PAR_BLOCK { FFLAS::pfrand(F,Rand, n,n,A,n/MAX_THREADS); }
PAR_BLOCK {
if (random_rpm)
FFPACK::RandomMatrixWithRankandRandomRPM(F,n,n,n,A,n,Rand);
else
FFLAS::pfrand(F,Rand, n,n,A,n/MAX_THREADS);
}
init.stop();
std::cerr << "init: " << init << std::endl;
Field::Element det; F.init(det);
try {
FFPACK::ForceCheck_Det<Field> checker (Rand,n,A,n);
Givaro::Timer chrono; chrono.start();
FFPACK::Det(det,F,n,n,A,n,P,Q,Diag);
chrono.stop();
checker.check(det,A,n,Diag,P,Q);
F.write(std::cerr << n << 'x' << n << ' ' << Diag << '(', det) << ')' << " Det verification PASSED\n" ;
#ifdef TIME_CHECKER_Det
std::cerr << "Det COMPT: " << chrono << std::endl;
#endif
pass++;
} catch(FailureDetCheck &e) {
F.write(std::cerr << n << 'x' << n << ' ' << Diag << '(', det) << ')' << " Det verification FAILED!\n";
}
FFLAS::fflas_delete(A,P,Q);
Diag = (Diag == FFLAS::FflasNonUnit) ? FFLAS::FflasUnit : FFLAS::FflasNonUnit;
}
std::cerr << pass << "/" << iter << " tests SUCCESSFUL.\n";
return (iter-pass);
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <gtest/gtest.h>
#include "../pipeline.h"
#include "../channel.h"
#include "../scheduler.h"
#include <thread>
#include <asyncply/run.h>
class ChannelTest : testing::Test { };
using cmd = cu::pipeline<int>;
cmd::link generator()
{
return [](cmd::in&, cmd::out& yield)
{
for (auto& s : {100, 200, 300})
{
std::cout << "I am generator and push " << s << std::endl;
yield(s);
}
};
}
cmd::link link1()
{
return [](cmd::in& source, cmd::out& yield)
{
for (auto& s : source)
{
std::cout << "I am link1 and push " << s << std::endl;
yield(s);
}
};
}
cmd::link link2()
{
return [](cmd::in& source, cmd::out& yield)
{
for (auto& s : source)
{
std::cout << "I am link2 and push " << s << std::endl;
yield(s);
}
};
}
cmd::link link3()
{
return [](cmd::in& source, cmd::out& yield)
{
for (auto& s : source)
{
std::cout << "I am link3 and push " << s << std::endl;
yield(s);
}
};
}
TEST(ChannelTest, pipeline)
{
cmd(generator(), link1(), link2(), link3());
}
TEST(ChannelTest, goroutines_consumer)
{
cu::scheduler sch;
cu::channel<int> go(sch, 10);
sch.spawn("producer", [&sch, &go](auto& yield) {
// send
for(int i=0; i<200; ++i)
{
std::cout << "sending: " << i << std::endl;
go(yield, i);
}
go.close(yield);
});
sch.spawn("consumer", [&sch, &go](auto& yield) {
// recv
for(;;)
{
auto data = go.get(yield);
if(!data)
{
std::cout << "channel closed" << std::endl;
break;
}
else
{
std::cout << "recving: " << *data << std::endl;
}
}
});
sch.run_until_complete();
}
TEST(CoroTest, TestScheduler)
{
cu::scheduler sch;
cu::semaphore person1(sch, 1);
cu::semaphore person2(sch, 1);
cu::semaphore other(sch, 2);
// person2
sch.spawn("person2", [&](auto& yield) {
std::cout << "Hola person1" << std::endl;
person2.notify(yield);
//
person1.wait(yield);
std::cout << "que tal ?" << std::endl;
person2.notify(yield);
//
person1.wait(yield);
std::cout << "me alegro" << std::endl;
person2.notify(yield);
//
other.notify(yield);
});
// person1
sch.spawn("person1", [&](auto& yield) {
//
person2.wait(yield);
std::cout << "Hola person2" << std::endl;
person1.notify(yield);
//
person2.wait(yield);
std::cout << "bien!" << std::endl;
person1.notify(yield);
//
person2.wait(yield);
std::cout << "y yo ^^" << std::endl;
//
other.notify(yield);
});
// other
sch.spawn("other", [&](auto& yield) {
//
other.wait(yield);
std::cout << "parar!!! tengo algo importante" << std::endl;
});
sch.run_until_complete();
}
<commit_msg>Update test_channel.cpp<commit_after>#include <iostream>
#include <gtest/gtest.h>
#include "../pipeline.h"
#include "../channel.h"
#include "../scheduler.h"
#include <thread>
#include <asyncply/run.h>
class ChannelTest : testing::Test { };
using cmd = cu::pipeline<int>;
cmd::link generator()
{
return [](cmd::in&, cmd::out& yield)
{
for (auto& s : {100, 200, 300})
{
std::cout << "I am generator and push " << s << std::endl;
yield(s);
}
};
}
cmd::link link1()
{
return [](cmd::in& source, cmd::out& yield)
{
for (auto& s : source)
{
std::cout << "I am link1 and push " << s << std::endl;
yield(s);
}
};
}
cmd::link link2()
{
return [](cmd::in& source, cmd::out& yield)
{
for (auto& s : source)
{
std::cout << "I am link2 and push " << s << std::endl;
yield(s);
}
};
}
cmd::link link3()
{
return [](cmd::in& source, cmd::out& yield)
{
for (auto& s : source)
{
std::cout << "I am link3 and push " << s << std::endl;
yield(s);
}
};
}
TEST(ChannelTest, pipeline)
{
cmd(generator(), link1(), link2(), link3());
}
TEST(ChannelTest, goroutines_consumer)
{
cu::scheduler sch;
cu::channel<int> go(sch, 9);
sch.spawn("producer", [&sch, &go](auto& yield) {
// send
for(int i=1; i<=200; ++i)
{
std::cout << "sending: " << i << std::endl;
go(yield, i);
}
go.close(yield);
});
sch.spawn("consumer", [&sch, &go](auto& yield) {
// recv
for(;;)
{
auto data = go.get(yield);
if(!data)
{
std::cout << "channel closed" << std::endl;
break;
}
else
{
std::cout << "recving: " << *data << std::endl;
}
}
});
sch.run_until_complete();
}
TEST(CoroTest, TestScheduler)
{
cu::scheduler sch;
cu::semaphore person1(sch);
cu::semaphore person2(sch);
cu::semaphore other(sch);
// person2
sch.spawn("person2", [&](auto& yield) {
std::cout << "Hola person1" << std::endl;
person2.notify(yield);
//
person1.wait(yield);
std::cout << "que tal ?" << std::endl;
person2.notify(yield);
//
person1.wait(yield);
std::cout << "me alegro" << std::endl;
person2.notify(yield);
//
other.notify(yield);
});
// person1
sch.spawn("person1", [&](auto& yield) {
//
person2.wait(yield);
std::cout << "Hola person2" << std::endl;
person1.notify(yield);
//
person2.wait(yield);
std::cout << "bien!" << std::endl;
person1.notify(yield);
//
person2.wait(yield);
std::cout << "y yo ^^" << std::endl;
//
other.notify(yield);
});
// other
sch.spawn("other", [&](auto& yield) {
//
other.wait(yield);
other.wait(yield);
std::cout << "parar!!! tengo algo importante" << std::endl;
});
sch.run_until_complete();
}
<|endoftext|> |
<commit_before>/*
* CoreHandle.cpp
*
* Copyright (C) 2008 by Universitaet Stuttgart (VIS).
* Alle Rechte vorbehalten.
*/
#include "stdafx.h"
#include "Window.h"
#include "HotKeyButtonParam.h"
#include "MegaMolCore.h"
#include "vislib/assert.h"
#include "vislib/Log.h"
#include "vislib/RawStorage.h"
#include "vislib/types.h"
#include "WindowManager.h"
/****************************************************************************/
/* extern declaration of closeAllWindows. Ugly and I hate it, but it works. */
extern void closeAllWindows(megamol::console::Window *exception = false);
namespace megamol {
namespace console {
/**
* Utility structure for parameter enumeration
*/
typedef struct _paramenumcontext_t {
/** The calling window object */
Window *wnd;
/** Pointer to the core handle */
CoreHandle *hCore;
} ParamEnumContext;
} /* end namespace console */
} /* end namespace megamol */
/****************************************************************************/
/*
* megamol::console::Window::InternalHotKey::InternalHotKey
*/
megamol::console::Window::InternalHotKey::InternalHotKey(
megamol::console::Window *owner,
void (megamol::console::Window::*callback)(void)) : HotKeyAction(),
owner(owner), callback(callback) {
ASSERT(owner != NULL);
ASSERT(callback != NULL);
}
/*
* megamol::console::Window::InternalHotKey::~InternalHotKey
*/
megamol::console::Window::InternalHotKey::~InternalHotKey(void) {
this->owner = NULL; // DO NOT DELETE
this->callback = NULL; // DO NOT DELETE
}
/*
* megamol::console::Window::InternalHotKey::Trigger
*/
void megamol::console::Window::InternalHotKey::Trigger(void) {
// pointer-to-member operator rulz
(this->owner->*this->callback)();
}
/****************************************************************************/
/*
* megamol::console::Window::hasClosed
*/
bool megamol::console::Window::hasClosed = false;
/*
* megamol::console::Window::CloseCallback
*/
void megamol::console::Window::CloseCallback(void *wnd, void *params) {
Window *win = static_cast<Window *>(wnd);
ASSERT(win != NULL);
ASSERT(::mmcIsHandleValid(win->hView));
ASSERT(::mmvIsHandleValid(win->hWnd));
win->MarkToClose();
}
/*
* megamol::console::Window::RenderCallback
*/
void megamol::console::Window::RenderCallback(void *wnd, void *params) {
Window *win = static_cast<Window *>(wnd);
ASSERT(win != NULL);
ASSERT(::mmcIsHandleValid(win->hView));
ASSERT(::mmvIsHandleValid(win->hWnd));
if (::mmcIsViewRunning(win->hView)) {
::mmcRenderView(win->hView, static_cast<bool*>(params));
} else {
win->MarkToClose();
}
#ifdef WITH_TWEAKBAR
win->gui.Draw();
#endif /* WITH_TWEAKBAR */
}
/*
* megamol::console::Window::ResizeCallback
*/
void megamol::console::Window::ResizeCallback(void *wnd,
unsigned int *params) {
Window *win = static_cast<Window *>(wnd);
ASSERT((win != NULL) && (params != NULL));
ASSERT(::mmcIsHandleValid(win->hView));
ASSERT(::mmvIsHandleValid(win->hWnd));
#ifdef WITH_TWEAKBAR
win->gui.SetWindowSize(params[0], params[1]);
#endif /* WITH_TWEAKBAR */
::mmcResizeView(win->hView, params[0], params[1]);
}
/*
* megamol::console::Window::KeyCallback
*/
void megamol::console::Window::KeyCallback(void *wnd, mmvKeyParams *params) {
Window *win = static_cast<Window *>(wnd);
ASSERT((win != NULL) && (params != NULL));
ASSERT(::mmcIsHandleValid(win->hView));
ASSERT(::mmvIsHandleValid(win->hWnd));
win->setModifierStates(params->modAlt, params->modCtrl, params->modShift);
::mmcSet2DMousePosition(win->hView,
static_cast<float>(params->mouseX),
static_cast<float>(params->mouseY));
#ifdef WITH_TWEAKBAR
if (!win->gui.KeyPressed(params->keycode, params->modShift, params->modAlt, params->modCtrl)) {
#endif /* WITH_TWEAKBAR */
vislib::sys::KeyCode key(params->keycode);
if (win->hotkeys.Contains(key)) {
vislib::SmartPtr<HotKeyAction> action = win->hotkeys[key];
if (!action.IsNull()) {
action->Trigger();
return;
}
}
vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_INFO + 1000,
"Unused key %i\n", int(key));
#ifdef WITH_TWEAKBAR
}
#endif /* WITH_TWEAKBAR */
}
/*
* megamol::console::Window::MouseButtonCallback
*/
void megamol::console::Window::MouseButtonCallback(void *wnd,
mmvMouseButtonParams *params) {
Window *win = static_cast<Window *>(wnd);
ASSERT((win != NULL) && (params != NULL));
ASSERT(::mmcIsHandleValid(win->hView));
ASSERT(::mmvIsHandleValid(win->hWnd));
win->setModifierStates(params->modAlt, params->modCtrl, params->modShift);
#ifdef WITH_TWEAKBAR
if (!win->gui.MouseButton(params->button, params->buttonDown) || !params->buttonDown) {
#endif /* WITH_TWEAKBAR */
switch (params->button) {
case 0: case 1: case 2:
if (win->mouseBtns[params->button] != params->buttonDown) {
::mmcSet2DMouseButton(win->hView, params->button,
params->buttonDown);
win->mouseBtns[params->button] = params->buttonDown;
}
break;
default:
break;
}
#ifdef WITH_TWEAKBAR
}
#endif /* WITH_TWEAKBAR */
::mmcSet2DMousePosition(win->hView,
static_cast<float>(params->mouseX),
static_cast<float>(params->mouseY));
}
/*
* megamol::console::Window::MouseMoveCallback
*/
void megamol::console::Window::MouseMoveCallback(void *wnd,
mmvMouseMoveParams *params) {
Window *win = static_cast<Window *>(wnd);
ASSERT((win != NULL) && (params != NULL));
ASSERT(::mmcIsHandleValid(win->hView));
ASSERT(::mmvIsHandleValid(win->hWnd));
win->setModifierStates(params->modAlt, params->modCtrl, params->modShift);
#ifdef WITH_TWEAKBAR
win->gui.MouseMove(params->mouseX, params->mouseY);
#endif /* WITH_TWEAKBAR */
::mmcSet2DMousePosition(win->hView,
static_cast<float>(params->mouseX),
static_cast<float>(params->mouseY));
}
/*
* megamol::console::Window::UpdateFreezeCallback
*/
void megamol::console::Window::UpdateFreezeCallback(void *wnd, int *params) {
Window *win = static_cast<Window *>(wnd);
ASSERT(win != NULL);
ASSERT(::mmcIsHandleValid(win->hView));
ASSERT(::mmvIsHandleValid(win->hWnd));
::mmcFreezeOrUpdateView(win->hView, params[0] != 0);
}
/*
* megamol::console::Window::CloseRequestCallback
*/
void MMAPI_CALLBACK megamol::console::Window::CloseRequestCallback(void* data) {
Window *win = static_cast<Window *>(data);
ASSERT(win != NULL);
win->MarkToClose();
}
/*
* megamol::console::Window::Window
*/
megamol::console::Window::Window(void) : hView(), hWnd(),
#ifdef WITH_TWEAKBAR
gui(),
#endif /* WITH_TWEAKBAR */
isClosed(false), modAlt(false), modCtrl(false), modShift(false),
hotkeys() {
this->mouseBtns[0] = false;
this->mouseBtns[1] = false;
this->mouseBtns[2] = false;
this->hotkeys[vislib::sys::KeyCode(vislib::sys::KeyCode::KEY_ESC)]
= new InternalHotKey(this, &Window::doExitAction);
this->hotkeys[vislib::sys::KeyCode(vislib::sys::KeyCode::KEY_ESC | vislib::sys::KeyCode::KEY_MOD_SHIFT)]
= new InternalHotKey(this, &Window::doExitAction);
this->hotkeys[vislib::sys::KeyCode('q')]
= new InternalHotKey(this, &Window::doExitAction);
this->hotkeys[vislib::sys::KeyCode('Q' | vislib::sys::KeyCode::KEY_MOD_SHIFT)]
= new InternalHotKey(this, &Window::doExitAction);
}
/*
* megamol::console::Window::~Window
*/
megamol::console::Window::~Window(void) {
// Intentionally empty atm
}
/*
* megamol::console::Window::RegisterHotKeys
*/
void megamol::console::Window::RegisterHotKeys(CoreHandle& hCore) {
ParamEnumContext peContext;
peContext.wnd = this;
peContext.hCore = &hCore;
::mmcEnumParametersA(hCore, &Window::registerHotKeys, &peContext);
}
/*
* megamol::console::Window::RegisterHotKeyAction
*/
void megamol::console::Window::RegisterHotKeyAction(
const vislib::sys::KeyCode& key, HotKeyAction *action, const vislib::StringA& target) {
if (!this->hotkeys.Contains(key)) {
// register hotkey 'key' of this window with this parameter
vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_INFO,
"Mapping Key %s to %s\n", key.ToStringA().PeekBuffer(), target.PeekBuffer());
this->hotkeys[key] = action;
} else {
delete action;
}
}
#ifdef WITH_TWEAKBAR
/*
* megamol::console::Window::InitGUI
*/
void megamol::console::Window::InitGUI(CoreHandle& hCore) {
ParamEnumContext peContext;
peContext.wnd = this;
peContext.hCore = &hCore;
this->gui.BeginInitialisation();
::mmcEnumParametersA(hCore, &Window::initGUI, &peContext);
this->gui.EndInitialisation();
}
/*
* megamol::console::Window::initGUI
*/
void MEGAMOLCORE_CALLBACK megamol::console::Window::initGUI(const char *paramName, void *contextPtr) {
ParamEnumContext *context = reinterpret_cast<ParamEnumContext *>(contextPtr);
vislib::SmartPtr<megamol::console::CoreHandle> hParam = new megamol::console::CoreHandle();
vislib::RawStorage desc;
if (context == NULL) { return; }
if (!::mmcGetParameterA(*context->hCore, paramName, *hParam)) { return; }
if (!::mmcIsParameterRelevant(context->wnd->HView(), *hParam)) { return; }
unsigned int len = 0;
::mmcGetParameterTypeDescription(*hParam, NULL, &len);
desc.AssertSize(len);
::mmcGetParameterTypeDescription(*hParam, desc.As<unsigned char>(), &len);
context->wnd->gui.AddParameter(hParam, paramName, desc.As<unsigned char>(), len);
}
#endif /* WITH_TWEAKBAR */
/*
* megamol::console::Window::registerHotKeys
*/
void MEGAMOLCORE_CALLBACK megamol::console::Window::registerHotKeys(const char *paramName, void *contextPtr) {
ParamEnumContext *context = reinterpret_cast<ParamEnumContext *>(contextPtr);
vislib::SmartPtr<megamol::console::CoreHandle> hParam = new megamol::console::CoreHandle();
vislib::RawStorage desc;
if (context == NULL) { return; }
if (!::mmcGetParameterA(*context->hCore, paramName, *hParam)) { return; }
unsigned int len = 0;
::mmcGetParameterTypeDescription(*hParam, NULL, &len);
desc.AssertSize(len);
::mmcGetParameterTypeDescription(*hParam, desc.As<unsigned char>(), &len);
if (!vislib::StringA(desc.As<char>(), 6).Equals("MMBUTN")) { return; }// I r only interested in buttons
if (!::mmcIsParameterRelevant(context->wnd->HView(), *hParam)) { return; }
WORD key = 0;
if (desc.GetSize() == 7) {
key = *desc.AsAt<char>(6);
} else if (desc.GetSize() == 8) {
key = *desc.AsAt<WORD>(6);
}
if (key != 0) {
context->wnd->RegisterHotKeyAction(vislib::sys::KeyCode(key),
new HotKeyButtonParam(hParam), paramName);
}
}
/*
* megamol::console::Window::setModifierStates
*/
void megamol::console::Window::setModifierStates(bool alt, bool ctrl,
bool shift) {
if (alt != this->modAlt) {
::mmcSetInputModifier(this->hView, MMC_INMOD_ALT, alt);
this->modAlt = alt;
}
if (ctrl != this->modCtrl) {
::mmcSetInputModifier(this->hView, MMC_INMOD_CTRL, ctrl);
this->modCtrl = ctrl;
}
if (shift != this->modShift) {
::mmcSetInputModifier(this->hView, MMC_INMOD_SHIFT, shift);
this->modShift = shift;
}
}
/*
* megamol::console::Window::doExitAction
*/
void megamol::console::Window::doExitAction(void) {
if (this->modShift) {
CloseCallback(this, NULL);
} else {
WindowManager::Instance()->MarkAllForClosure();
}
}
<commit_msg>Console GUI shows all parameters (also irrelevant ones)<commit_after>/*
* CoreHandle.cpp
*
* Copyright (C) 2008 by Universitaet Stuttgart (VIS).
* Alle Rechte vorbehalten.
*/
#include "stdafx.h"
#include "Window.h"
#include "HotKeyButtonParam.h"
#include "MegaMolCore.h"
#include "vislib/assert.h"
#include "vislib/Log.h"
#include "vislib/RawStorage.h"
#include "vislib/types.h"
#include "WindowManager.h"
/****************************************************************************/
/* extern declaration of closeAllWindows. Ugly and I hate it, but it works. */
extern void closeAllWindows(megamol::console::Window *exception = false);
namespace megamol {
namespace console {
/**
* Utility structure for parameter enumeration
*/
typedef struct _paramenumcontext_t {
/** The calling window object */
Window *wnd;
/** Pointer to the core handle */
CoreHandle *hCore;
} ParamEnumContext;
} /* end namespace console */
} /* end namespace megamol */
/****************************************************************************/
/*
* megamol::console::Window::InternalHotKey::InternalHotKey
*/
megamol::console::Window::InternalHotKey::InternalHotKey(
megamol::console::Window *owner,
void (megamol::console::Window::*callback)(void)) : HotKeyAction(),
owner(owner), callback(callback) {
ASSERT(owner != NULL);
ASSERT(callback != NULL);
}
/*
* megamol::console::Window::InternalHotKey::~InternalHotKey
*/
megamol::console::Window::InternalHotKey::~InternalHotKey(void) {
this->owner = NULL; // DO NOT DELETE
this->callback = NULL; // DO NOT DELETE
}
/*
* megamol::console::Window::InternalHotKey::Trigger
*/
void megamol::console::Window::InternalHotKey::Trigger(void) {
// pointer-to-member operator rulz
(this->owner->*this->callback)();
}
/****************************************************************************/
/*
* megamol::console::Window::hasClosed
*/
bool megamol::console::Window::hasClosed = false;
/*
* megamol::console::Window::CloseCallback
*/
void megamol::console::Window::CloseCallback(void *wnd, void *params) {
Window *win = static_cast<Window *>(wnd);
ASSERT(win != NULL);
ASSERT(::mmcIsHandleValid(win->hView));
ASSERT(::mmvIsHandleValid(win->hWnd));
win->MarkToClose();
}
/*
* megamol::console::Window::RenderCallback
*/
void megamol::console::Window::RenderCallback(void *wnd, void *params) {
Window *win = static_cast<Window *>(wnd);
ASSERT(win != NULL);
ASSERT(::mmcIsHandleValid(win->hView));
ASSERT(::mmvIsHandleValid(win->hWnd));
if (::mmcIsViewRunning(win->hView)) {
::mmcRenderView(win->hView, static_cast<bool*>(params));
} else {
win->MarkToClose();
}
#ifdef WITH_TWEAKBAR
win->gui.Draw();
#endif /* WITH_TWEAKBAR */
}
/*
* megamol::console::Window::ResizeCallback
*/
void megamol::console::Window::ResizeCallback(void *wnd,
unsigned int *params) {
Window *win = static_cast<Window *>(wnd);
ASSERT((win != NULL) && (params != NULL));
ASSERT(::mmcIsHandleValid(win->hView));
ASSERT(::mmvIsHandleValid(win->hWnd));
#ifdef WITH_TWEAKBAR
win->gui.SetWindowSize(params[0], params[1]);
#endif /* WITH_TWEAKBAR */
::mmcResizeView(win->hView, params[0], params[1]);
}
/*
* megamol::console::Window::KeyCallback
*/
void megamol::console::Window::KeyCallback(void *wnd, mmvKeyParams *params) {
Window *win = static_cast<Window *>(wnd);
ASSERT((win != NULL) && (params != NULL));
ASSERT(::mmcIsHandleValid(win->hView));
ASSERT(::mmvIsHandleValid(win->hWnd));
win->setModifierStates(params->modAlt, params->modCtrl, params->modShift);
::mmcSet2DMousePosition(win->hView,
static_cast<float>(params->mouseX),
static_cast<float>(params->mouseY));
#ifdef WITH_TWEAKBAR
if (!win->gui.KeyPressed(params->keycode, params->modShift, params->modAlt, params->modCtrl)) {
#endif /* WITH_TWEAKBAR */
vislib::sys::KeyCode key(params->keycode);
if (win->hotkeys.Contains(key)) {
vislib::SmartPtr<HotKeyAction> action = win->hotkeys[key];
if (!action.IsNull()) {
action->Trigger();
return;
}
}
vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_INFO + 1000,
"Unused key %i\n", int(key));
#ifdef WITH_TWEAKBAR
}
#endif /* WITH_TWEAKBAR */
}
/*
* megamol::console::Window::MouseButtonCallback
*/
void megamol::console::Window::MouseButtonCallback(void *wnd,
mmvMouseButtonParams *params) {
Window *win = static_cast<Window *>(wnd);
ASSERT((win != NULL) && (params != NULL));
ASSERT(::mmcIsHandleValid(win->hView));
ASSERT(::mmvIsHandleValid(win->hWnd));
win->setModifierStates(params->modAlt, params->modCtrl, params->modShift);
#ifdef WITH_TWEAKBAR
if (!win->gui.MouseButton(params->button, params->buttonDown) || !params->buttonDown) {
#endif /* WITH_TWEAKBAR */
switch (params->button) {
case 0: case 1: case 2:
if (win->mouseBtns[params->button] != params->buttonDown) {
::mmcSet2DMouseButton(win->hView, params->button,
params->buttonDown);
win->mouseBtns[params->button] = params->buttonDown;
}
break;
default:
break;
}
#ifdef WITH_TWEAKBAR
}
#endif /* WITH_TWEAKBAR */
::mmcSet2DMousePosition(win->hView,
static_cast<float>(params->mouseX),
static_cast<float>(params->mouseY));
}
/*
* megamol::console::Window::MouseMoveCallback
*/
void megamol::console::Window::MouseMoveCallback(void *wnd,
mmvMouseMoveParams *params) {
Window *win = static_cast<Window *>(wnd);
ASSERT((win != NULL) && (params != NULL));
ASSERT(::mmcIsHandleValid(win->hView));
ASSERT(::mmvIsHandleValid(win->hWnd));
win->setModifierStates(params->modAlt, params->modCtrl, params->modShift);
#ifdef WITH_TWEAKBAR
win->gui.MouseMove(params->mouseX, params->mouseY);
#endif /* WITH_TWEAKBAR */
::mmcSet2DMousePosition(win->hView,
static_cast<float>(params->mouseX),
static_cast<float>(params->mouseY));
}
/*
* megamol::console::Window::UpdateFreezeCallback
*/
void megamol::console::Window::UpdateFreezeCallback(void *wnd, int *params) {
Window *win = static_cast<Window *>(wnd);
ASSERT(win != NULL);
ASSERT(::mmcIsHandleValid(win->hView));
ASSERT(::mmvIsHandleValid(win->hWnd));
::mmcFreezeOrUpdateView(win->hView, params[0] != 0);
}
/*
* megamol::console::Window::CloseRequestCallback
*/
void MMAPI_CALLBACK megamol::console::Window::CloseRequestCallback(void* data) {
Window *win = static_cast<Window *>(data);
ASSERT(win != NULL);
win->MarkToClose();
}
/*
* megamol::console::Window::Window
*/
megamol::console::Window::Window(void) : hView(), hWnd(),
#ifdef WITH_TWEAKBAR
gui(),
#endif /* WITH_TWEAKBAR */
isClosed(false), modAlt(false), modCtrl(false), modShift(false),
hotkeys() {
this->mouseBtns[0] = false;
this->mouseBtns[1] = false;
this->mouseBtns[2] = false;
this->hotkeys[vislib::sys::KeyCode(vislib::sys::KeyCode::KEY_ESC)]
= new InternalHotKey(this, &Window::doExitAction);
this->hotkeys[vislib::sys::KeyCode(vislib::sys::KeyCode::KEY_ESC | vislib::sys::KeyCode::KEY_MOD_SHIFT)]
= new InternalHotKey(this, &Window::doExitAction);
this->hotkeys[vislib::sys::KeyCode('q')]
= new InternalHotKey(this, &Window::doExitAction);
this->hotkeys[vislib::sys::KeyCode('Q' | vislib::sys::KeyCode::KEY_MOD_SHIFT)]
= new InternalHotKey(this, &Window::doExitAction);
}
/*
* megamol::console::Window::~Window
*/
megamol::console::Window::~Window(void) {
// Intentionally empty atm
}
/*
* megamol::console::Window::RegisterHotKeys
*/
void megamol::console::Window::RegisterHotKeys(CoreHandle& hCore) {
ParamEnumContext peContext;
peContext.wnd = this;
peContext.hCore = &hCore;
::mmcEnumParametersA(hCore, &Window::registerHotKeys, &peContext);
}
/*
* megamol::console::Window::RegisterHotKeyAction
*/
void megamol::console::Window::RegisterHotKeyAction(
const vislib::sys::KeyCode& key, HotKeyAction *action, const vislib::StringA& target) {
if (!this->hotkeys.Contains(key)) {
// register hotkey 'key' of this window with this parameter
vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_INFO,
"Mapping Key %s to %s\n", key.ToStringA().PeekBuffer(), target.PeekBuffer());
this->hotkeys[key] = action;
} else {
delete action;
}
}
#ifdef WITH_TWEAKBAR
/*
* megamol::console::Window::InitGUI
*/
void megamol::console::Window::InitGUI(CoreHandle& hCore) {
ParamEnumContext peContext;
peContext.wnd = this;
peContext.hCore = &hCore;
this->gui.BeginInitialisation();
::mmcEnumParametersA(hCore, &Window::initGUI, &peContext);
this->gui.EndInitialisation();
}
/*
* megamol::console::Window::initGUI
*/
void MEGAMOLCORE_CALLBACK megamol::console::Window::initGUI(const char *paramName, void *contextPtr) {
ParamEnumContext *context = reinterpret_cast<ParamEnumContext *>(contextPtr);
vislib::SmartPtr<megamol::console::CoreHandle> hParam = new megamol::console::CoreHandle();
vislib::RawStorage desc;
if (context == NULL) { return; }
if (!::mmcGetParameterA(*context->hCore, paramName, *hParam)) { return; }
//if (!::mmcIsParameterRelevant(context->wnd->HView(), *hParam)) { return; }
unsigned int len = 0;
::mmcGetParameterTypeDescription(*hParam, NULL, &len);
desc.AssertSize(len);
::mmcGetParameterTypeDescription(*hParam, desc.As<unsigned char>(), &len);
context->wnd->gui.AddParameter(hParam, paramName, desc.As<unsigned char>(), len);
}
#endif /* WITH_TWEAKBAR */
/*
* megamol::console::Window::registerHotKeys
*/
void MEGAMOLCORE_CALLBACK megamol::console::Window::registerHotKeys(const char *paramName, void *contextPtr) {
ParamEnumContext *context = reinterpret_cast<ParamEnumContext *>(contextPtr);
vislib::SmartPtr<megamol::console::CoreHandle> hParam = new megamol::console::CoreHandle();
vislib::RawStorage desc;
if (context == NULL) { return; }
if (!::mmcGetParameterA(*context->hCore, paramName, *hParam)) { return; }
unsigned int len = 0;
::mmcGetParameterTypeDescription(*hParam, NULL, &len);
desc.AssertSize(len);
::mmcGetParameterTypeDescription(*hParam, desc.As<unsigned char>(), &len);
if (!vislib::StringA(desc.As<char>(), 6).Equals("MMBUTN")) { return; }// I r only interested in buttons
if (!::mmcIsParameterRelevant(context->wnd->HView(), *hParam)) { return; }
WORD key = 0;
if (desc.GetSize() == 7) {
key = *desc.AsAt<char>(6);
} else if (desc.GetSize() == 8) {
key = *desc.AsAt<WORD>(6);
}
if (key != 0) {
context->wnd->RegisterHotKeyAction(vislib::sys::KeyCode(key),
new HotKeyButtonParam(hParam), paramName);
}
}
/*
* megamol::console::Window::setModifierStates
*/
void megamol::console::Window::setModifierStates(bool alt, bool ctrl,
bool shift) {
if (alt != this->modAlt) {
::mmcSetInputModifier(this->hView, MMC_INMOD_ALT, alt);
this->modAlt = alt;
}
if (ctrl != this->modCtrl) {
::mmcSetInputModifier(this->hView, MMC_INMOD_CTRL, ctrl);
this->modCtrl = ctrl;
}
if (shift != this->modShift) {
::mmcSetInputModifier(this->hView, MMC_INMOD_SHIFT, shift);
this->modShift = shift;
}
}
/*
* megamol::console::Window::doExitAction
*/
void megamol::console::Window::doExitAction(void) {
if (this->modShift) {
CloseCallback(this, NULL);
} else {
WindowManager::Instance()->MarkAllForClosure();
}
}
<|endoftext|> |
<commit_before>/*
* Licensed to Green Energy Corp (www.greenenergycorp.com) under one or more
* contributor license agreements. See the NOTICE file distributed with this
* work for additional information regarding copyright ownership. Green Enery
* Corp 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.
*/
#include "VtoWriter.h"
#include <APL/Util.h>
namespace apl {
namespace dnp {
VtoWriter::VtoWriter(size_t aMaxVtoChunks) :
mMaxVtoChunks(aMaxVtoChunks)
{}
size_t VtoWriter::Write(const boost::uint8_t* apData,
size_t aLength,
boost::uint8_t aChannelId)
{
/*
* The whole function is thread-safe, from start to finish.
*/
CriticalSection cs(&mLock);
/*
* Only write the maximum amount available or requested. If the
* requested data size is larger than the available buffer space,
* only send what will fit.
*/
size_t num = Min<size_t>(this->NumBytesAvailable(), aLength);
/*
* Chop up the data into Max(255) segments and add it to the queue.
*/
this->Commit(apData, num, aChannelId);
/* Tell any listeners that the queue has new data to be read. */
if (num > 0)
this->NotifyAll();
/* Return the number of bytes from apData that were queued. */
return num;
}
void VtoWriter::_Start()
{
mLock.Lock();
}
void VtoWriter::_End()
{
mLock.Unlock();
}
void VtoWriter::Commit(const boost::uint8_t* apData,
size_t aLength,
boost::uint8_t aChannelId)
{
/*
* The data is segmented into N number of chunks, each of MAX_SIZE
* bytes, and 1 chunk containing the remainder of the data that is
* less than MAX_SIZE bytes. We pre-calculate the chunk size to
* avoid the constant comparison overhead in the loop itself.
*/
size_t complete = aLength / VtoData::MAX_SIZE;
size_t partial = aLength % VtoData::MAX_SIZE;
/* First, write the full-sized blocks */
for (size_t i = 0; i < complete; ++i)
{
QueueVtoObject(apData, VtoData::MAX_SIZE, aChannelId);
apData += VtoData::MAX_SIZE;
}
/* Next, write the remaining data at the end of the stream */
if (partial > 0)
QueueVtoObject(apData, partial, aChannelId);
}
void VtoWriter::QueueVtoObject(const boost::uint8_t* apData,
size_t aLength,
boost::uint8_t aChannelId)
{
/*
* Create a new VtoData instance, set the event data associated
* with it, and then push the object onto the transmission queue.
*/
VtoData vto(apData, aLength);
VtoEvent evt(vto, PC_CLASS_1, aChannelId);
mQueue.push(evt);
}
bool VtoWriter::Read(VtoEvent& arEvent)
{
/*
* The whole function is thread-safe, from start to finish.
*/
CriticalSection cs(&mLock);
/*
* If there is no data on the queue, return false. This allows
* the function to be used in the conditional block of a loop
* construct.
*/
if (this->mQueue.size() == 0)
{
return false;
}
/*
* The queue has data, so pop off the front item, store it in
* arEvent, and return true.
*/
arEvent = this->mQueue.front();
this->mQueue.pop();
return true;
}
size_t VtoWriter::Size()
{
/*
* The whole function is thread-safe, from start to finish.
*/
CriticalSection cs(&mLock);
return mQueue.size();
}
size_t VtoWriter::NumChunksAvailable()
{
return mMaxVtoChunks - mQueue.size();
}
size_t VtoWriter::NumBytesAvailable()
{
return this->NumChunksAvailable() * VtoData::MAX_SIZE;
}
}
}
/* vim: set ts=4 sw=4: */
<commit_msg>Changed VtoWriter.cpp from using nested namespaces to the 'using' keyword.<commit_after>/*
* Licensed to Green Energy Corp (www.greenenergycorp.com) under one or more
* contributor license agreements. See the NOTICE file distributed with this
* work for additional information regarding copyright ownership. Green Enery
* Corp 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.
*/
#include "VtoWriter.h"
#include <APL/Util.h>
using apl::CriticalSection;
using apl::dnp::VtoData;
using apl::dnp::VtoEvent;
using apl::dnp::VtoWriter;
VtoWriter::VtoWriter(size_t aMaxVtoChunks) :
mMaxVtoChunks(aMaxVtoChunks)
{}
size_t VtoWriter::Write(const boost::uint8_t* apData,
size_t aLength,
boost::uint8_t aChannelId)
{
/*
* The whole function is thread-safe, from start to finish.
*/
CriticalSection cs(&mLock);
/*
* Only write the maximum amount available or requested. If the
* requested data size is larger than the available buffer space,
* only send what will fit.
*/
size_t num = Min<size_t>(this->NumBytesAvailable(), aLength);
/*
* Chop up the data into Max(255) segments and add it to the queue.
*/
this->Commit(apData, num, aChannelId);
/* Tell any listeners that the queue has new data to be read. */
if (num > 0)
this->NotifyAll();
/* Return the number of bytes from apData that were queued. */
return num;
}
void VtoWriter::_Start()
{
this->mLock.Lock();
}
void VtoWriter::_End()
{
this->mLock.Unlock();
}
void VtoWriter::Commit(const boost::uint8_t* apData,
size_t aLength,
boost::uint8_t aChannelId)
{
/*
* The data is segmented into N number of chunks, each of MAX_SIZE
* bytes, and 1 chunk containing the remainder of the data that is
* less than MAX_SIZE bytes. We pre-calculate the chunk size to
* avoid the constant comparison overhead in the loop itself.
*/
size_t complete = aLength / VtoData::MAX_SIZE;
size_t partial = aLength % VtoData::MAX_SIZE;
/* First, write the full-sized blocks */
for (size_t i = 0; i < complete; ++i)
{
this->QueueVtoObject(apData, VtoData::MAX_SIZE, aChannelId);
apData += VtoData::MAX_SIZE;
}
/* Next, write the remaining data at the end of the stream */
if (partial > 0)
this->QueueVtoObject(apData, partial, aChannelId);
}
void VtoWriter::QueueVtoObject(const boost::uint8_t* apData,
size_t aLength,
boost::uint8_t aChannelId)
{
/*
* Create a new VtoData instance, set the event data associated
* with it, and then push the object onto the transmission queue.
*/
VtoData vto(apData, aLength);
VtoEvent evt(vto, PC_CLASS_1, aChannelId);
this->mQueue.push(evt);
}
bool VtoWriter::Read(VtoEvent& arEvent)
{
/*
* The whole function is thread-safe, from start to finish.
*/
CriticalSection cs(&mLock);
/*
* If there is no data on the queue, return false. This allows
* the function to be used in the conditional block of a loop
* construct.
*/
if (this->mQueue.size() == 0)
{
return false;
}
/*
* The queue has data, so pop off the front item, store it in
* arEvent, and return true.
*/
arEvent = this->mQueue.front();
this->mQueue.pop();
return true;
}
size_t VtoWriter::Size()
{
/*
* The whole function is thread-safe, from start to finish.
*/
CriticalSection cs(&mLock);
return mQueue.size();
}
size_t VtoWriter::NumChunksAvailable()
{
return mMaxVtoChunks - mQueue.size();
}
size_t VtoWriter::NumBytesAvailable()
{
return this->NumChunksAvailable() * VtoData::MAX_SIZE;
}
/* vim: set ts=4 sw=4: */
<|endoftext|> |
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: PresenterComponent.hxx,v $
*
* $Revision: 1.3 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef SDEXT_PRESENTER_COMPONENT_HXX
#define SDEXT_PRESENTER_COMPONENT_HXX
#include <comphelper/componentmodule.hxx>
namespace sdext { namespace presenter {
const static ::rtl::OUString gsExtensionIdentifier(
::rtl::OUString::createFromAscii("org.openoffice.PresenterScreen"));
DECLARE_COMPONENT_MODULE(PresenterComponent, ClientClass)
} }
#endif
<commit_msg>INTEGRATION: CWS presenterscreen (1.2.4); FILE MERGED 2008/04/22 13:01:55 af 1.2.4.3: #i18486# Made extension identifier platform specific. 2008/04/22 08:24:50 af 1.2.4.2: RESYNC: (1.2-1.3); FILE MERGED 2008/04/16 16:30:29 af 1.2.4.1: #i18486# Dropped dependence on non-URE libraries.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: PresenterComponent.hxx,v $
*
* $Revision: 1.4 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef SDEXT_PRESENTER_COMPONENT_HXX
#define SDEXT_PRESENTER_COMPONENT_HXX
#include <comphelper/componentmodule.hxx>
namespace css = ::com::sun::star;
namespace sdext { namespace presenter {
/** This string is replaced automatically by the makefile during the
building of this extension.
*/
class PresenterComponent
{
public:
const static ::rtl::OUString gsExtensionIdentifier;
static ::rtl::OUString GetBasePath (
const css::uno::Reference<css::uno::XComponentContext>& rxComponentContext);
static ::rtl::OUString GetBasePath (
const css::uno::Reference<css::uno::XComponentContext>& rxComponentContext,
const ::rtl::OUString& rsExtensionIdentifier);
};
} }
#endif
<|endoftext|> |
<commit_before>#include "exception.h"
#include "utils.h"
#include "glm.h"
using CMT::GLM;
#include "nonlinearities.h"
using CMT::Nonlinearity;
using CMT::LogisticFunction;
#include "univariatedistributions.h"
using CMT::UnivariateDistribution;
using CMT::Bernoulli;
#include <cmath>
using std::log;
using std::min;
#include <map>
using std::pair;
using std::make_pair;
#include "Eigen/Core"
using Eigen::Dynamic;
using Eigen::Array;
using Eigen::ArrayXXd;
using Eigen::MatrixXd;
Nonlinearity* const GLM::defaultNonlinearity = new LogisticFunction;
UnivariateDistribution* const GLM::defaultDistribution = new Bernoulli;
CMT::GLM::Parameters::Parameters() :
Trainable::Parameters::Parameters(),
trainWeights(true),
trainBias(true),
trainNonlinearity(false),
regularizeWeights(0.),
regularizeBias(0.),
regularizer(L2)
{
}
CMT::GLM::Parameters::Parameters(const Parameters& params) :
Trainable::Parameters::Parameters(params),
trainWeights(params.trainWeights),
trainBias(params.trainBias),
trainNonlinearity(params.trainNonlinearity),
regularizeWeights(params.regularizeWeights),
regularizeBias(params.regularizeBias),
regularizer(params.regularizer)
{
}
CMT::GLM::Parameters& CMT::GLM::Parameters::operator=(const Parameters& params) {
Trainable::Parameters::operator=(params);
trainWeights = params.trainWeights;
trainBias = params.trainBias;
trainNonlinearity = params.trainNonlinearity;
regularizeWeights = params.regularizeWeights;
regularizeBias = params.regularizeBias;
regularizer = params.regularizer;
return *this;
}
CMT::GLM::GLM(
int dimIn,
Nonlinearity* nonlinearity,
UnivariateDistribution* distribution) :
mDimIn(dimIn),
mNonlinearity(nonlinearity ? nonlinearity : defaultNonlinearity),
mDistribution(distribution ? distribution : defaultDistribution)
{
if(mDimIn < 0)
throw Exception("Input dimensionality should be non-negative.");
if(!mNonlinearity)
throw Exception("No nonlinearity specified.");
if(!mDistribution)
throw Exception("No distribution specified.");
mWeights = VectorXd::Random(dimIn) / 100.;
mBias = 0.;
}
CMT::GLM::GLM(int dimIn) : mDimIn(dimIn) {
if(mDimIn < 0)
throw Exception("Input dimensionality should be non-negative.");
mNonlinearity = defaultNonlinearity;
mDistribution = defaultDistribution;
mWeights = VectorXd::Random(dimIn) / 100.;
mBias = 0.;
}
CMT::GLM::GLM(int dimIn, const GLM& glm) :
mDimIn(dimIn),
mNonlinearity(glm.mNonlinearity),
mDistribution(glm.mDistribution)
{
if(mDimIn < 0)
throw Exception("Input dimensionality should be non-negative.");
mWeights = VectorXd::Random(dimIn) / 100.;
mBias = 0.;
}
CMT::GLM::~GLM() {
}
Array<double, 1, Dynamic> CMT::GLM::logLikelihood(
const MatrixXd& input,
const MatrixXd& output) const
{
if(input.rows() != mDimIn)
throw Exception("Input has wrong dimensionality.");
Array<double, 1, Dynamic> responses;
if(mDimIn)
responses = (mWeights.transpose() * input).array() + mBias;
else
responses = Array<double, 1, Dynamic>::Constant(output.cols(), mBias);
return mDistribution->logLikelihood(output, (*mNonlinearity)(responses));
}
MatrixXd CMT::GLM::sample(const MatrixXd& input) const {
if(input.rows() != mDimIn)
throw Exception("Input has wrong dimensionality.");
if(!mDimIn)
return mDistribution->sample(Array<double, 1, Dynamic>::Constant(input.cols(), mBias));
return mDistribution->sample((*mNonlinearity)((mWeights.transpose() * input).array() + mBias));
}
MatrixXd CMT::GLM::predict(const MatrixXd& input) const {
if(input.rows() != mDimIn)
throw Exception("Input has wrong dimensionality.");
if(!mDimIn)
return Array<double, 1, Dynamic>::Constant(input.cols(), mBias);
return (*mNonlinearity)((mWeights.transpose() * input).array() + mBias);
}
int CMT::GLM::numParameters(const Trainable::Parameters& params_) const {
const Parameters& params = static_cast<const Parameters&>(params_);
int numParams = 0;
if(params.trainWeights)
numParams += mDimIn;
if(params.trainBias)
numParams += 1;
if(params.trainNonlinearity) {
// test if nonlinearity is trainable
TrainableNonlinearity* nonlinearity =
dynamic_cast<TrainableNonlinearity*>(mNonlinearity);
if(!nonlinearity)
throw Exception("Nonlinearity has to be trainable.");
numParams += nonlinearity->numParameters();
}
return numParams;
}
lbfgsfloatval_t* CMT::GLM::parameters(const Trainable::Parameters& params_) const {
const Parameters& params = static_cast<const Parameters&>(params_);
lbfgsfloatval_t* x = lbfgs_malloc(numParameters(params));
int k = 0;
if(params.trainWeights)
for(int i = 0; i < mDimIn; ++i, ++k)
x[k] = mWeights[i];
if(params.trainBias)
x[k++] = mBias;
if(params.trainNonlinearity) {
// test if nonlinearity is trainable
TrainableNonlinearity* nonlinearity =
dynamic_cast<TrainableNonlinearity*>(mNonlinearity);
if(!nonlinearity)
throw Exception("Nonlinearity has to be trainable.");
ArrayXd nonlParams = nonlinearity->parameters();
for(int i = 0; i < nonlParams.size(); ++i, ++k)
x[k] = nonlParams[i];
}
return x;
}
void CMT::GLM::setParameters(
const lbfgsfloatval_t* x,
const Trainable::Parameters& params_)
{
const Parameters& params = static_cast<const Parameters&>(params_);
int k = 0;
if(params.trainWeights)
for(int i = 0; i < mDimIn; ++i, ++k)
mWeights[i] = x[k];
if(params.trainBias)
mBias = x[k++];
if(params.trainNonlinearity) {
// test if nonlinearity is trainable
TrainableNonlinearity* nonlinearity =
dynamic_cast<TrainableNonlinearity*>(mNonlinearity);
if(!nonlinearity)
throw Exception("Nonlinearity has to be trainable.");
ArrayXd nonlParams(nonlinearity->numParameters());
for(int i = 0; i < nonlParams.size(); ++i, ++k)
nonlParams[i] = x[k];
nonlinearity->setParameters(nonlParams);
}
}
double CMT::GLM::parameterGradient(
const MatrixXd& inputCompl,
const MatrixXd& outputCompl,
const lbfgsfloatval_t* x,
lbfgsfloatval_t* g,
const Trainable::Parameters& params_) const
{
const Parameters& params = static_cast<const Parameters&>(params_);
// check if nonlinearity is trainable and/or differentiable
TrainableNonlinearity* trainableNonlinearity =
dynamic_cast<TrainableNonlinearity*>(mNonlinearity);
DifferentiableNonlinearity* differentiableNonlinearity =
dynamic_cast<DifferentiableNonlinearity*>(mNonlinearity);
if((params.trainWeights || params.trainBias) && !differentiableNonlinearity)
throw Exception("Nonlinearity has to be differentiable.");
if(params.trainNonlinearity && !trainableNonlinearity)
throw Exception("Nonlinearity is not trainable.");
int numData = static_cast<int>(inputCompl.cols());
int batchSize = min(params.batchSize, numData);
lbfgsfloatval_t* y = const_cast<lbfgsfloatval_t*>(x);
int offset = 0;
// interpret parameters
VectorLBFGS weights(params.trainWeights ? y : const_cast<double*>(mWeights.data()), mDimIn);
VectorLBFGS weightsGrad(g, mDimIn);
if(params.trainWeights)
offset += weights.size();
double bias = params.trainBias ? y[offset] : mBias;
double* biasGrad = g + offset;
if(params.trainBias)
offset += 1;
VectorLBFGS nonlinearityGrad(g + offset,
trainableNonlinearity ? trainableNonlinearity->numParameters() : 0);
if(params.trainNonlinearity) {
VectorLBFGS nonlParams(y + offset, trainableNonlinearity->numParameters());
trainableNonlinearity->setParameters(nonlParams);
offset += trainableNonlinearity->numParameters();
}
// initialize gradient and log-likelihood
if(g) {
if(params.trainWeights)
weightsGrad.setZero();
if(params.trainBias)
*biasGrad = 0.;
if(params.trainNonlinearity)
nonlinearityGrad.setZero();
}
double logLik = 0.;
#pragma omp parallel for
for(int b = 0; b < inputCompl.cols(); b += batchSize) {
const MatrixXd& input = inputCompl.middleCols(b, min(batchSize, numData - b));
const MatrixXd& output = outputCompl.middleCols(b, min(batchSize, numData - b));
// linear responses
Array<double, 1, Dynamic> responses;
if(mDimIn)
responses = (weights.transpose() * input).array() + bias;
else
responses = Array<double, 1, Dynamic>::Constant(output.cols(), bias);
// nonlinear responses
Array<double, 1, Dynamic> means = mNonlinearity->operator()(responses);
if(g) {
Array<double, 1, Dynamic> tmp1 = mDistribution->gradient(output, means);
if(params.trainWeights || params.trainBias) {
Array<double, 1, Dynamic> tmp2 = differentiableNonlinearity->derivative(responses);
Array<double, 1, Dynamic> tmp3 = tmp1 * tmp2;
// weights gradient
if(params.trainWeights && mDimIn) {
VectorXd weightsGrad_ = (input.array().rowwise() * tmp3).rowwise().sum();
#pragma omp critical
weightsGrad += weightsGrad_;
}
// bias gradient
if(params.trainBias)
#pragma omp critical
*biasGrad += tmp3.sum();
}
if(params.trainNonlinearity) {
VectorXd nonlinearityGrad_ = (trainableNonlinearity->gradient(responses).rowwise() * tmp1).rowwise().sum();
#pragma omp critical
nonlinearityGrad += nonlinearityGrad_;
}
}
#pragma omp critical
logLik += mDistribution->logLikelihood(output, means).sum();
}
double normConst = outputCompl.cols() * log(2.);
if(g) {
for(int i = 0; i < offset; ++i)
g[i] /= normConst;
switch(params.regularizer) {
case Parameters::L1:
if(params.trainWeights && params.regularizeWeights > 0.)
weightsGrad += params.regularizeWeights * signum(weights);
if(params.trainBias && params.regularizeBias > 0.)
if(bias > 0.)
*biasGrad += params.regularizeBias;
else if(bias < 0.)
*biasGrad -= params.regularizeBias;
break;
case Parameters::L2:
if(params.trainWeights && params.regularizeWeights > 0.)
weightsGrad += params.regularizeWeights * 2. * weights;
if(params.trainBias && params.regularizeBias > 0.)
*biasGrad += params.regularizeBias * 2. * bias;
break;
}
}
double value = -logLik / normConst;
switch(params.regularizer) {
case Parameters::L1:
if(params.trainWeights && params.regularizeWeights > 0.)
value += params.regularizeWeights * weights.array().abs().sum();
if(params.trainBias && params.regularizeBias > 0.)
value += params.regularizeBias * abs(bias);
break;
case Parameters::L2:
if(params.trainWeights && params.regularizeWeights > 0.)
value += params.regularizeWeights * weights.array().square().sum();
if(params.trainBias && params.regularizeBias > 0.)
value += params.regularizeBias * bias * bias;
break;
}
return value;
}
pair<pair<ArrayXXd, ArrayXXd>, Array<double, 1, Dynamic> > CMT::GLM::computeDataGradient(
const MatrixXd& input,
const MatrixXd& output) const
{
return make_pair(
make_pair(
ArrayXXd::Zero(input.rows(), input.cols()),
ArrayXXd::Zero(output.rows(), output.cols())),
logLikelihood(input, output));
}
<commit_msg>Fixes faulty merge of glm.cpp.<commit_after>#include "exception.h"
#include "utils.h"
#include "glm.h"
using CMT::GLM;
#include "nonlinearities.h"
using CMT::Nonlinearity;
using CMT::LogisticFunction;
#include "univariatedistributions.h"
using CMT::UnivariateDistribution;
using CMT::Bernoulli;
#include <cmath>
using std::log;
using std::min;
#include <map>
using std::pair;
using std::make_pair;
#include "Eigen/Core"
using Eigen::Dynamic;
using Eigen::Array;
using Eigen::ArrayXXd;
using Eigen::MatrixXd;
Nonlinearity* const GLM::defaultNonlinearity = new LogisticFunction;
UnivariateDistribution* const GLM::defaultDistribution = new Bernoulli;
CMT::GLM::Parameters::Parameters() :
Trainable::Parameters::Parameters(),
trainWeights(true),
trainBias(true),
trainNonlinearity(false)
{
}
CMT::GLM::Parameters::Parameters(const Parameters& params) :
Trainable::Parameters::Parameters(params),
trainWeights(params.trainWeights),
trainBias(params.trainBias),
trainNonlinearity(params.trainNonlinearity),
regularizeWeights(params.regularizeWeights),
regularizeBias(params.regularizeBias)
{
}
CMT::GLM::Parameters& CMT::GLM::Parameters::operator=(const Parameters& params) {
Trainable::Parameters::operator=(params);
trainWeights = params.trainWeights;
trainBias = params.trainBias;
trainNonlinearity = params.trainNonlinearity;
regularizeWeights = params.regularizeWeights;
regularizeBias = params.regularizeBias;
return *this;
}
CMT::GLM::GLM(
int dimIn,
Nonlinearity* nonlinearity,
UnivariateDistribution* distribution) :
mDimIn(dimIn),
mNonlinearity(nonlinearity ? nonlinearity : defaultNonlinearity),
mDistribution(distribution ? distribution : defaultDistribution)
{
if(mDimIn < 0)
throw Exception("Input dimensionality should be non-negative.");
if(!mNonlinearity)
throw Exception("No nonlinearity specified.");
if(!mDistribution)
throw Exception("No distribution specified.");
mWeights = VectorXd::Random(dimIn) / 100.;
mBias = 0.;
}
CMT::GLM::GLM(int dimIn) : mDimIn(dimIn) {
if(mDimIn < 0)
throw Exception("Input dimensionality should be non-negative.");
mNonlinearity = defaultNonlinearity;
mDistribution = defaultDistribution;
mWeights = VectorXd::Random(dimIn) / 100.;
mBias = 0.;
}
CMT::GLM::GLM(int dimIn, const GLM& glm) :
mDimIn(dimIn),
mNonlinearity(glm.mNonlinearity),
mDistribution(glm.mDistribution)
{
if(mDimIn < 0)
throw Exception("Input dimensionality should be non-negative.");
mWeights = VectorXd::Random(dimIn) / 100.;
mBias = 0.;
}
CMT::GLM::~GLM() {
}
Array<double, 1, Dynamic> CMT::GLM::logLikelihood(
const MatrixXd& input,
const MatrixXd& output) const
{
if(input.rows() != mDimIn)
throw Exception("Input has wrong dimensionality.");
Array<double, 1, Dynamic> responses;
if(mDimIn)
responses = (mWeights.transpose() * input).array() + mBias;
else
responses = Array<double, 1, Dynamic>::Constant(output.cols(), mBias);
return mDistribution->logLikelihood(output, (*mNonlinearity)(responses));
}
MatrixXd CMT::GLM::sample(const MatrixXd& input) const {
if(input.rows() != mDimIn)
throw Exception("Input has wrong dimensionality.");
if(!mDimIn)
return mDistribution->sample(Array<double, 1, Dynamic>::Constant(input.cols(), mBias));
return mDistribution->sample((*mNonlinearity)((mWeights.transpose() * input).array() + mBias));
}
MatrixXd CMT::GLM::predict(const MatrixXd& input) const {
if(input.rows() != mDimIn)
throw Exception("Input has wrong dimensionality.");
if(!mDimIn)
return Array<double, 1, Dynamic>::Constant(input.cols(), mBias);
return (*mNonlinearity)((mWeights.transpose() * input).array() + mBias);
}
int CMT::GLM::numParameters(const Trainable::Parameters& params_) const {
const Parameters& params = dynamic_cast<const Parameters&>(params_);
int numParams = 0;
if(params.trainWeights)
numParams += mDimIn;
if(params.trainBias)
numParams += 1;
if(params.trainNonlinearity) {
// test if nonlinearity is trainable
TrainableNonlinearity* nonlinearity =
dynamic_cast<TrainableNonlinearity*>(mNonlinearity);
if(!nonlinearity)
throw Exception("Nonlinearity has to be trainable.");
numParams += nonlinearity->numParameters();
}
return numParams;
}
lbfgsfloatval_t* CMT::GLM::parameters(const Trainable::Parameters& params_) const {
const Parameters& params = dynamic_cast<const Parameters&>(params_);
lbfgsfloatval_t* x = lbfgs_malloc(numParameters(params));
int k = 0;
if(params.trainWeights)
for(int i = 0; i < mDimIn; ++i, ++k)
x[k] = mWeights[i];
if(params.trainBias)
x[k++] = mBias;
if(params.trainNonlinearity) {
// test if nonlinearity is trainable
TrainableNonlinearity* nonlinearity =
dynamic_cast<TrainableNonlinearity*>(mNonlinearity);
if(!nonlinearity)
throw Exception("Nonlinearity has to be trainable.");
ArrayXd nonlParams = nonlinearity->parameters();
for(int i = 0; i < nonlParams.size(); ++i, ++k)
x[k] = nonlParams[i];
}
return x;
}
void CMT::GLM::setParameters(
const lbfgsfloatval_t* x,
const Trainable::Parameters& params_)
{
const Parameters& params = dynamic_cast<const Parameters&>(params_);
int k = 0;
if(params.trainWeights)
for(int i = 0; i < mDimIn; ++i, ++k)
mWeights[i] = x[k];
if(params.trainBias)
mBias = x[k++];
if(params.trainNonlinearity) {
// test if nonlinearity is trainable
TrainableNonlinearity* nonlinearity =
dynamic_cast<TrainableNonlinearity*>(mNonlinearity);
if(!nonlinearity)
throw Exception("Nonlinearity has to be trainable.");
ArrayXd nonlParams(nonlinearity->numParameters());
for(int i = 0; i < nonlParams.size(); ++i, ++k)
nonlParams[i] = x[k];
nonlinearity->setParameters(nonlParams);
}
}
double CMT::GLM::parameterGradient(
const MatrixXd& inputCompl,
const MatrixXd& outputCompl,
const lbfgsfloatval_t* x,
lbfgsfloatval_t* g,
const Trainable::Parameters& params_) const
{
const Parameters& params = dynamic_cast<const Parameters&>(params_);
// check if nonlinearity is trainable and/or differentiable
TrainableNonlinearity* trainableNonlinearity =
dynamic_cast<TrainableNonlinearity*>(mNonlinearity);
DifferentiableNonlinearity* differentiableNonlinearity =
dynamic_cast<DifferentiableNonlinearity*>(mNonlinearity);
if((params.trainWeights || params.trainBias) && !differentiableNonlinearity)
throw Exception("Nonlinearity has to be differentiable.");
if(params.trainNonlinearity && !trainableNonlinearity)
throw Exception("Nonlinearity is not trainable.");
int numData = static_cast<int>(inputCompl.cols());
int batchSize = min(params.batchSize, numData);
lbfgsfloatval_t* y = const_cast<lbfgsfloatval_t*>(x);
int offset = 0;
// interpret parameters
VectorLBFGS weights(params.trainWeights ? y : const_cast<double*>(mWeights.data()), mDimIn);
VectorLBFGS weightsGrad(g, mDimIn);
if(params.trainWeights)
offset += weights.size();
double bias = params.trainBias ? y[offset] : mBias;
double* biasGrad = g + offset;
if(params.trainBias)
offset += 1;
VectorLBFGS nonlinearityGrad(g + offset,
trainableNonlinearity ? trainableNonlinearity->numParameters() : 0);
if(params.trainNonlinearity) {
VectorLBFGS nonlParams(y + offset, trainableNonlinearity->numParameters());
trainableNonlinearity->setParameters(nonlParams);
offset += trainableNonlinearity->numParameters();
}
// initialize gradient and log-likelihood
if(g) {
if(params.trainWeights)
weightsGrad.setZero();
if(params.trainBias)
*biasGrad = 0.;
if(params.trainNonlinearity)
nonlinearityGrad.setZero();
}
double logLik = 0.;
#pragma omp parallel for
for(int b = 0; b < inputCompl.cols(); b += batchSize) {
const MatrixXd& input = inputCompl.middleCols(b, min(batchSize, numData - b));
const MatrixXd& output = outputCompl.middleCols(b, min(batchSize, numData - b));
// linear responses
Array<double, 1, Dynamic> responses;
if(mDimIn)
responses = (weights.transpose() * input).array() + bias;
else
responses = Array<double, 1, Dynamic>::Constant(output.cols(), bias);
// nonlinear responses
Array<double, 1, Dynamic> means = mNonlinearity->operator()(responses);
if(g) {
Array<double, 1, Dynamic> tmp1 = mDistribution->gradient(output, means);
if(params.trainWeights || params.trainBias) {
Array<double, 1, Dynamic> tmp2 = differentiableNonlinearity->derivative(responses);
Array<double, 1, Dynamic> tmp3 = tmp1 * tmp2;
// weights gradient
if(params.trainWeights && mDimIn) {
VectorXd weightsGrad_ = (input.array().rowwise() * tmp3).rowwise().sum();
#pragma omp critical
weightsGrad += weightsGrad_;
}
// bias gradient
if(params.trainBias)
#pragma omp critical
*biasGrad += tmp3.sum();
}
if(params.trainNonlinearity) {
VectorXd nonlinearityGrad_ = (trainableNonlinearity->gradient(responses).rowwise() * tmp1).rowwise().sum();
#pragma omp critical
nonlinearityGrad += nonlinearityGrad_;
}
}
#pragma omp critical
logLik += mDistribution->logLikelihood(output, means).sum();
}
double normConst = outputCompl.cols() * log(2.);
if(g) {
for(int i = 0; i < offset; ++i)
g[i] /= normConst;
if(params.trainWeights)
weightsGrad += params.regularizeWeights.gradient(weights);
if(params.trainBias)
*biasGrad += params.regularizeBias.gradient(MatrixXd::Constant(1, 1, bias))(0, 0);
}
double value = -logLik / normConst;
value += params.regularizeWeights.evaluate(weights);
value += params.regularizeBias.evaluate(MatrixXd::Constant(1, 1, bias));
return value;
}
pair<pair<ArrayXXd, ArrayXXd>, Array<double, 1, Dynamic> > CMT::GLM::computeDataGradient(
const MatrixXd& input,
const MatrixXd& output) const
{
// make sure nonlinearity is differentiable
DifferentiableNonlinearity* nonlinearity =
dynamic_cast<DifferentiableNonlinearity*>(mNonlinearity);
if(!nonlinearity)
throw Exception("Nonlinearity has to be differentiable.");
if(mDimIn && input.rows() != mDimIn)
throw Exception("Input has wrong dimensionality.");
if(output.rows() != 1)
throw Exception("Output has wrong dimensionality.");
if(input.cols() != output.cols())
throw Exception("Number of inputs and outputs should be the same.");
if(!mDimIn)
return make_pair(
make_pair(
ArrayXXd::Zero(input.rows(), input.cols()),
ArrayXXd::Zero(output.rows(), output.cols())),
logLikelihood(input, output));
Array<double, 1, Dynamic> responses = (mWeights.transpose() * input).array() + mBias;
Array<double, 1, Dynamic> tmp0 = (*mNonlinearity)(responses);
Array<double, 1, Dynamic> tmp1 = -mDistribution->gradient(output, tmp0);
Array<double, 1, Dynamic> tmp2 = nonlinearity->derivative(responses);
return make_pair(
make_pair(
mWeights * (tmp1 * tmp2).matrix(),
ArrayXXd::Zero(output.rows(), output.cols())),
mDistribution->logLikelihood(output, tmp0));
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: md5.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: hr $ $Date: 2007-06-27 22:06:40 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_tools.hxx"
#include "md5.hxx"
#include <cstddef>
#include <stdio.h>
#include <tools/string.hxx>
#ifdef WNT
#define FILE_OPEN_READ "rb"
#else
#define FILE_OPEN_READ "r"
#endif
rtlDigestError calc_md5_checksum( const char *filename, ByteString &aChecksum )
{
sal_uInt8 checksum[RTL_DIGEST_LENGTH_MD5];
rtlDigestError error = rtl_Digest_E_None;
FILE *fp = fopen( filename, FILE_OPEN_READ );
if ( fp )
{
rtlDigest digest = rtl_digest_createMD5();
if ( digest )
{
size_t nBytesRead;
sal_uInt8 buffer[0x1000];
while ( rtl_Digest_E_None == error &&
0 != (nBytesRead = fread( buffer, 1, sizeof(buffer), fp )) )
{
error = rtl_digest_updateMD5( digest, buffer, nBytesRead );
}
if ( rtl_Digest_E_None == error )
{
error = rtl_digest_getMD5( digest, checksum, sizeof(checksum) );
}
rtl_digest_destroyMD5( digest );
for ( std::size_t i = 0; i < sizeof(checksum); i++ )
{
if ( checksum[i] < 16 )
aChecksum.Append( "0" );
aChecksum += ByteString::CreateFromInt32( checksum[i], 16 );
}
}
fclose( fp );
}
else
error = rtl_Digest_E_Unknown;
return error;
}
<commit_msg>INTEGRATION: CWS changefileheader (1.7.84); FILE MERGED 2008/03/28 15:41:02 rt 1.7.84.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: md5.cxx,v $
* $Revision: 1.8 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_tools.hxx"
#include "md5.hxx"
#include <cstddef>
#include <stdio.h>
#include <tools/string.hxx>
#ifdef WNT
#define FILE_OPEN_READ "rb"
#else
#define FILE_OPEN_READ "r"
#endif
rtlDigestError calc_md5_checksum( const char *filename, ByteString &aChecksum )
{
sal_uInt8 checksum[RTL_DIGEST_LENGTH_MD5];
rtlDigestError error = rtl_Digest_E_None;
FILE *fp = fopen( filename, FILE_OPEN_READ );
if ( fp )
{
rtlDigest digest = rtl_digest_createMD5();
if ( digest )
{
size_t nBytesRead;
sal_uInt8 buffer[0x1000];
while ( rtl_Digest_E_None == error &&
0 != (nBytesRead = fread( buffer, 1, sizeof(buffer), fp )) )
{
error = rtl_digest_updateMD5( digest, buffer, nBytesRead );
}
if ( rtl_Digest_E_None == error )
{
error = rtl_digest_getMD5( digest, checksum, sizeof(checksum) );
}
rtl_digest_destroyMD5( digest );
for ( std::size_t i = 0; i < sizeof(checksum); i++ )
{
if ( checksum[i] < 16 )
aChecksum.Append( "0" );
aChecksum += ByteString::CreateFromInt32( checksum[i], 16 );
}
}
fclose( fp );
}
else
error = rtl_Digest_E_Unknown;
return error;
}
<|endoftext|> |
<commit_before>#include "stats.h"
#include "simulator.h"
#include "hooks_manager.h"
#include "utils.h"
#include "itostr.h"
#include <math.h>
#include <stdio.h>
#include <sstream>
#include <unordered_set>
#include <string>
#include <cstring>
#include <zlib.h>
template <> UInt64 makeStatsValue<UInt64>(UInt64 t) { return t; }
template <> UInt64 makeStatsValue<SubsecondTime>(SubsecondTime t) { return t.getFS(); }
template <> UInt64 makeStatsValue<ComponentTime>(ComponentTime t) { return t.getElapsedTime().getFS(); }
const char* db_create_stmts[] = {
// Statistics
"CREATE TABLE `names` (nameid INTEGER, objectname TEXT, metricname TEXT);",
"CREATE TABLE `prefixes` (prefixid INTEGER, prefixname TEXT);",
"CREATE TABLE `values` (prefixid INTEGER, nameid INTEGER, core INTEGER, value INTEGER);",
"CREATE INDEX `idx_prefix_name` ON `prefixes`(`prefixname`);",
"CREATE INDEX `idx_value_prefix` ON `values`(`prefixid`);",
// Other users
"CREATE TABLE `topology` (componentname TEXT, coreid INTEGER, masterid INTEGER);",
"CREATE TABLE `marker` (time INTEGER, core INTEGER, thread INTEGER, value0 INTEGER, value1 INTEGER, description TEXT);",
};
const char db_insert_stmt_name[] = "INSERT INTO `names` (nameid, objectname, metricname) VALUES (?, ?, ?);";
const char db_insert_stmt_prefix[] = "INSERT INTO `prefixes` (prefixid, prefixname) VALUES (?, ?);";
const char db_insert_stmt_value[] = "INSERT INTO `values` (prefixid, nameid, core, value) VALUES (?, ?, ?, ?);";
StatsManager::StatsManager()
: m_keyid(0)
, m_prefixnum(0)
, m_db(NULL)
{
init();
}
StatsManager::~StatsManager()
{
if (m_db)
{
sqlite3_finalize(m_stmt_insert_name);
sqlite3_finalize(m_stmt_insert_prefix);
sqlite3_finalize(m_stmt_insert_value);
sqlite3_close(m_db);
}
}
void
StatsManager::init()
{
String filename = Sim()->getConfig()->formatOutputFileName("sim.stats.sqlite3");
int ret;
unlink(filename.c_str());
ret = sqlite3_open(filename.c_str(), &m_db);
LOG_ASSERT_ERROR(ret == SQLITE_OK, "Cannot create DB");
sqlite3_exec(m_db, "PRAGMA synchronous = OFF", NULL, NULL, NULL);
sqlite3_exec(m_db, "PRAGMA journal_mode = MEMORY", NULL, NULL, NULL);
sqlite3_busy_handler(m_db, __busy_handler, this);
for(unsigned int i = 0; i < sizeof(db_create_stmts)/sizeof(db_create_stmts[0]); ++i)
{
int res; char* err;
res = sqlite3_exec(m_db, db_create_stmts[i], NULL, NULL, &err);
LOG_ASSERT_ERROR(res == SQLITE_OK, "Error executing SQL statement \"%s\": %s", db_create_stmts[i], err);
}
sqlite3_prepare(m_db, db_insert_stmt_name, -1, &m_stmt_insert_name, NULL);
sqlite3_prepare(m_db, db_insert_stmt_prefix, -1, &m_stmt_insert_prefix, NULL);
sqlite3_prepare(m_db, db_insert_stmt_value, -1, &m_stmt_insert_value, NULL);
sqlite3_exec(m_db, "BEGIN TRANSACTION", NULL, NULL, NULL);
for(StatsObjectList::iterator it1 = m_objects.begin(); it1 != m_objects.end(); ++it1)
{
for (StatsMetricList::iterator it2 = it1->second.begin(); it2 != it1->second.end(); ++it2)
{
recordMetricName(it2->second.first, it1->first, it2->first);
}
}
sqlite3_exec(m_db, "END TRANSACTION", NULL, NULL, NULL);
}
int
StatsManager::busy_handler(int count)
{
// With a usleep below of 10 ms, at most one warning every 10s
if (count % 1000 == 999)
{
LOG_PRINT_WARNING("Difficulty locking sim.stats.sqlite3, retrying...");
}
usleep(10000);
return 1;
}
void
StatsManager::recordMetricName(UInt64 keyId, std::string objectName, std::string metricName)
{
int res;
sqlite3_reset(m_stmt_insert_name);
sqlite3_bind_int(m_stmt_insert_name, 1, keyId);
sqlite3_bind_text(m_stmt_insert_name, 2, objectName.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(m_stmt_insert_name, 3, metricName.c_str(), -1, SQLITE_TRANSIENT);
res = sqlite3_step(m_stmt_insert_name);
LOG_ASSERT_ERROR(res == SQLITE_DONE, "Error executing SQL statement");
}
void
StatsManager::recordStats(String prefix)
{
LOG_ASSERT_ERROR(m_db, "m_db not yet set up !?");
// Allow lazily-maintained statistics to be updated
Sim()->getHooksManager()->callHooks(HookType::HOOK_PRE_STAT_WRITE, 0);
int res;
int prefixid = ++m_prefixnum;
res = sqlite3_exec(m_db, "BEGIN TRANSACTION", NULL, NULL, NULL);
LOG_ASSERT_ERROR(res == SQLITE_OK, "Error executing SQL statement: %s", sqlite3_errmsg(m_db));
sqlite3_reset(m_stmt_insert_prefix);
sqlite3_bind_int(m_stmt_insert_prefix, 1, prefixid);
sqlite3_bind_text(m_stmt_insert_prefix, 2, prefix.c_str(), -1, SQLITE_TRANSIENT);
res = sqlite3_step(m_stmt_insert_prefix);
LOG_ASSERT_ERROR(res == SQLITE_DONE, "Error executing SQL statement: %s", sqlite3_errmsg(m_db));
for(StatsObjectList::iterator it1 = m_objects.begin(); it1 != m_objects.end(); ++it1)
{
for (StatsMetricList::iterator it2 = it1->second.begin(); it2 != it1->second.end(); ++it2)
{
for(StatsIndexList::iterator it3 = it2->second.second.begin(); it3 != it2->second.second.end(); ++it3)
{
if (!it3->second->isDefault())
{
sqlite3_reset(m_stmt_insert_value);
sqlite3_bind_int(m_stmt_insert_value, 1, prefixid);
sqlite3_bind_int(m_stmt_insert_value, 2, it2->second.first); // Metric ID
sqlite3_bind_int(m_stmt_insert_value, 3, it3->second->index); // Core ID
sqlite3_bind_int64(m_stmt_insert_value, 4, it3->second->recordMetric());
res = sqlite3_step(m_stmt_insert_value);
LOG_ASSERT_ERROR(res == SQLITE_DONE, "Error executing SQL statement: %s", sqlite3_errmsg(m_db));
}
}
}
}
res = sqlite3_exec(m_db, "END TRANSACTION", NULL, NULL, NULL);
LOG_ASSERT_ERROR(res == SQLITE_OK, "Error executing SQL statement: %s", sqlite3_errmsg(m_db));
}
void
StatsManager::registerMetric(StatsMetricBase *metric)
{
std::string _objectName(metric->objectName.c_str()), _metricName(metric->metricName.c_str());
m_objects[_objectName][_metricName].second[metric->index] = metric;
if (m_objects[_objectName][_metricName].first == 0)
{
m_objects[_objectName][_metricName].first = ++m_keyid;
if (m_db)
{
// Metrics name record was already written, but a new metric was registered afterwards: write a new record
recordMetricName(m_keyid, _objectName, _metricName);
}
}
}
StatsMetricBase *
StatsManager::getMetricObject(String objectName, UInt32 index, String metricName)
{
std::string _objectName(objectName.c_str()), _metricName(metricName.c_str());
if (m_objects.count(_objectName) == 0)
return NULL;
if (m_objects[_objectName].count(_metricName) == 0)
return NULL;
if (m_objects[_objectName][_metricName].second.count(index) == 0)
return NULL;
return m_objects[_objectName][_metricName].second[index];
}
void
StatsManager::logTopology(String component, core_id_t core_id, core_id_t master_id)
{
sqlite3_stmt *stmt;
sqlite3_prepare(m_db, "INSERT INTO topology (componentname, coreid, masterid) VALUES (?, ?, ?);", -1, &stmt, NULL);
sqlite3_bind_text(stmt, 1, component.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_int(stmt, 2, core_id);
sqlite3_bind_int(stmt, 3, master_id);
int res = sqlite3_step(stmt);
LOG_ASSERT_ERROR(res == SQLITE_DONE, "Error executing SQL statement: %s", sqlite3_errmsg(m_db));
sqlite3_finalize(stmt);
}
void
StatsManager::logMarker(SubsecondTime time, core_id_t core_id, thread_id_t thread_id, UInt64 value0, UInt64 value1, const char * description)
{
sqlite3_stmt *stmt;
sqlite3_prepare(m_db, "INSERT INTO marker (time, core, thread, value0, value1, description) VALUES (?, ?, ?, ?, ?, ?);", -1, &stmt, NULL);
sqlite3_bind_int64(stmt, 1, time.getFS());
sqlite3_bind_int(stmt, 2, core_id);
sqlite3_bind_int(stmt, 3, thread_id);
sqlite3_bind_int64(stmt, 4, value0);
sqlite3_bind_int64(stmt, 5, value1);
sqlite3_bind_text(stmt, 6, description ? description : "", -1, SQLITE_STATIC);
int res = sqlite3_step(stmt);
LOG_ASSERT_ERROR(res == SQLITE_DONE, "Error executing SQL statement: %s", sqlite3_errmsg(m_db));
sqlite3_finalize(stmt);
}
StatHist &
StatHist::operator += (StatHist & stat)
{
if (n == 0) { min = stat.min; max = stat.max; }
n += stat.n;
s += stat.s;
s2 += stat.s2;
if (stat.n && stat.min < min) min = stat.min;
if (stat.n && stat.max > max) max = stat.max;
for(int i = 0; i < HIST_MAX; ++i)
hist[i] += stat.hist[i];
return *this;
}
void
StatHist::update(unsigned long v)
{
if (n == 0) {
min = v;
max = v;
}
n++;
s += v;
s2 += v*v;
if (v < min) min = v;
if (v > max) max = v;
int bin = floorLog2(v) + 1;
if (bin >= HIST_MAX) bin = HIST_MAX - 1;
hist[bin]++;
}
void
StatHist::print()
{
printf("n(%lu), avg(%.2f), std(%.2f), min(%lu), max(%lu), hist(%lu",
n, n ? s/float(n) : 0, n ? sqrt((s2/n - (s/n)*(s/n))*n/float(n-1)) : 0, min, max, hist[0]);
for(int i = 1; i < HIST_MAX; ++i)
printf(",%lu", hist[i]);
printf(")\n");
}
<commit_msg>[stats] Add a wallclock statistic to automatically keep track of wallclock time between statistics snapshots<commit_after>#include "stats.h"
#include "simulator.h"
#include "hooks_manager.h"
#include "utils.h"
#include "itostr.h"
#include <math.h>
#include <stdio.h>
#include <sstream>
#include <unordered_set>
#include <string>
#include <cstring>
#include <zlib.h>
#include <sys/time.h>
template <> UInt64 makeStatsValue<UInt64>(UInt64 t) { return t; }
template <> UInt64 makeStatsValue<SubsecondTime>(SubsecondTime t) { return t.getFS(); }
template <> UInt64 makeStatsValue<ComponentTime>(ComponentTime t) { return t.getElapsedTime().getFS(); }
const char* db_create_stmts[] = {
// Statistics
"CREATE TABLE `names` (nameid INTEGER, objectname TEXT, metricname TEXT);",
"CREATE TABLE `prefixes` (prefixid INTEGER, prefixname TEXT);",
"CREATE TABLE `values` (prefixid INTEGER, nameid INTEGER, core INTEGER, value INTEGER);",
"CREATE INDEX `idx_prefix_name` ON `prefixes`(`prefixname`);",
"CREATE INDEX `idx_value_prefix` ON `values`(`prefixid`);",
// Other users
"CREATE TABLE `topology` (componentname TEXT, coreid INTEGER, masterid INTEGER);",
"CREATE TABLE `marker` (time INTEGER, core INTEGER, thread INTEGER, value0 INTEGER, value1 INTEGER, description TEXT);",
};
const char db_insert_stmt_name[] = "INSERT INTO `names` (nameid, objectname, metricname) VALUES (?, ?, ?);";
const char db_insert_stmt_prefix[] = "INSERT INTO `prefixes` (prefixid, prefixname) VALUES (?, ?);";
const char db_insert_stmt_value[] = "INSERT INTO `values` (prefixid, nameid, core, value) VALUES (?, ?, ?, ?);";
UInt64 getWallclockTimeCallback(String objectName, UInt32 index, String metricName, void *arg)
{
struct timeval tv = {0,0};
gettimeofday(&tv, NULL);
UInt64 usec = (tv.tv_sec * 1000000) + tv.tv_usec;
return usec;
}
StatsManager::StatsManager()
: m_keyid(0)
, m_prefixnum(0)
, m_db(NULL)
{
init();
registerMetric(new StatsMetricCallback("time", 0, "walltime", getWallclockTimeCallback, (void*)NULL));
}
StatsManager::~StatsManager()
{
if (m_db)
{
sqlite3_finalize(m_stmt_insert_name);
sqlite3_finalize(m_stmt_insert_prefix);
sqlite3_finalize(m_stmt_insert_value);
sqlite3_close(m_db);
}
}
void
StatsManager::init()
{
String filename = Sim()->getConfig()->formatOutputFileName("sim.stats.sqlite3");
int ret;
unlink(filename.c_str());
ret = sqlite3_open(filename.c_str(), &m_db);
LOG_ASSERT_ERROR(ret == SQLITE_OK, "Cannot create DB");
sqlite3_exec(m_db, "PRAGMA synchronous = OFF", NULL, NULL, NULL);
sqlite3_exec(m_db, "PRAGMA journal_mode = MEMORY", NULL, NULL, NULL);
sqlite3_busy_handler(m_db, __busy_handler, this);
for(unsigned int i = 0; i < sizeof(db_create_stmts)/sizeof(db_create_stmts[0]); ++i)
{
int res; char* err;
res = sqlite3_exec(m_db, db_create_stmts[i], NULL, NULL, &err);
LOG_ASSERT_ERROR(res == SQLITE_OK, "Error executing SQL statement \"%s\": %s", db_create_stmts[i], err);
}
sqlite3_prepare(m_db, db_insert_stmt_name, -1, &m_stmt_insert_name, NULL);
sqlite3_prepare(m_db, db_insert_stmt_prefix, -1, &m_stmt_insert_prefix, NULL);
sqlite3_prepare(m_db, db_insert_stmt_value, -1, &m_stmt_insert_value, NULL);
sqlite3_exec(m_db, "BEGIN TRANSACTION", NULL, NULL, NULL);
for(StatsObjectList::iterator it1 = m_objects.begin(); it1 != m_objects.end(); ++it1)
{
for (StatsMetricList::iterator it2 = it1->second.begin(); it2 != it1->second.end(); ++it2)
{
recordMetricName(it2->second.first, it1->first, it2->first);
}
}
sqlite3_exec(m_db, "END TRANSACTION", NULL, NULL, NULL);
}
int
StatsManager::busy_handler(int count)
{
// With a usleep below of 10 ms, at most one warning every 10s
if (count % 1000 == 999)
{
LOG_PRINT_WARNING("Difficulty locking sim.stats.sqlite3, retrying...");
}
usleep(10000);
return 1;
}
void
StatsManager::recordMetricName(UInt64 keyId, std::string objectName, std::string metricName)
{
int res;
sqlite3_reset(m_stmt_insert_name);
sqlite3_bind_int(m_stmt_insert_name, 1, keyId);
sqlite3_bind_text(m_stmt_insert_name, 2, objectName.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(m_stmt_insert_name, 3, metricName.c_str(), -1, SQLITE_TRANSIENT);
res = sqlite3_step(m_stmt_insert_name);
LOG_ASSERT_ERROR(res == SQLITE_DONE, "Error executing SQL statement");
}
void
StatsManager::recordStats(String prefix)
{
LOG_ASSERT_ERROR(m_db, "m_db not yet set up !?");
// Allow lazily-maintained statistics to be updated
Sim()->getHooksManager()->callHooks(HookType::HOOK_PRE_STAT_WRITE, 0);
int res;
int prefixid = ++m_prefixnum;
res = sqlite3_exec(m_db, "BEGIN TRANSACTION", NULL, NULL, NULL);
LOG_ASSERT_ERROR(res == SQLITE_OK, "Error executing SQL statement: %s", sqlite3_errmsg(m_db));
sqlite3_reset(m_stmt_insert_prefix);
sqlite3_bind_int(m_stmt_insert_prefix, 1, prefixid);
sqlite3_bind_text(m_stmt_insert_prefix, 2, prefix.c_str(), -1, SQLITE_TRANSIENT);
res = sqlite3_step(m_stmt_insert_prefix);
LOG_ASSERT_ERROR(res == SQLITE_DONE, "Error executing SQL statement: %s", sqlite3_errmsg(m_db));
for(StatsObjectList::iterator it1 = m_objects.begin(); it1 != m_objects.end(); ++it1)
{
for (StatsMetricList::iterator it2 = it1->second.begin(); it2 != it1->second.end(); ++it2)
{
for(StatsIndexList::iterator it3 = it2->second.second.begin(); it3 != it2->second.second.end(); ++it3)
{
if (!it3->second->isDefault())
{
sqlite3_reset(m_stmt_insert_value);
sqlite3_bind_int(m_stmt_insert_value, 1, prefixid);
sqlite3_bind_int(m_stmt_insert_value, 2, it2->second.first); // Metric ID
sqlite3_bind_int(m_stmt_insert_value, 3, it3->second->index); // Core ID
sqlite3_bind_int64(m_stmt_insert_value, 4, it3->second->recordMetric());
res = sqlite3_step(m_stmt_insert_value);
LOG_ASSERT_ERROR(res == SQLITE_DONE, "Error executing SQL statement: %s", sqlite3_errmsg(m_db));
}
}
}
}
res = sqlite3_exec(m_db, "END TRANSACTION", NULL, NULL, NULL);
LOG_ASSERT_ERROR(res == SQLITE_OK, "Error executing SQL statement: %s", sqlite3_errmsg(m_db));
}
void
StatsManager::registerMetric(StatsMetricBase *metric)
{
std::string _objectName(metric->objectName.c_str()), _metricName(metric->metricName.c_str());
m_objects[_objectName][_metricName].second[metric->index] = metric;
if (m_objects[_objectName][_metricName].first == 0)
{
m_objects[_objectName][_metricName].first = ++m_keyid;
if (m_db)
{
// Metrics name record was already written, but a new metric was registered afterwards: write a new record
recordMetricName(m_keyid, _objectName, _metricName);
}
}
}
StatsMetricBase *
StatsManager::getMetricObject(String objectName, UInt32 index, String metricName)
{
std::string _objectName(objectName.c_str()), _metricName(metricName.c_str());
if (m_objects.count(_objectName) == 0)
return NULL;
if (m_objects[_objectName].count(_metricName) == 0)
return NULL;
if (m_objects[_objectName][_metricName].second.count(index) == 0)
return NULL;
return m_objects[_objectName][_metricName].second[index];
}
void
StatsManager::logTopology(String component, core_id_t core_id, core_id_t master_id)
{
sqlite3_stmt *stmt;
sqlite3_prepare(m_db, "INSERT INTO topology (componentname, coreid, masterid) VALUES (?, ?, ?);", -1, &stmt, NULL);
sqlite3_bind_text(stmt, 1, component.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_int(stmt, 2, core_id);
sqlite3_bind_int(stmt, 3, master_id);
int res = sqlite3_step(stmt);
LOG_ASSERT_ERROR(res == SQLITE_DONE, "Error executing SQL statement: %s", sqlite3_errmsg(m_db));
sqlite3_finalize(stmt);
}
void
StatsManager::logMarker(SubsecondTime time, core_id_t core_id, thread_id_t thread_id, UInt64 value0, UInt64 value1, const char * description)
{
sqlite3_stmt *stmt;
sqlite3_prepare(m_db, "INSERT INTO marker (time, core, thread, value0, value1, description) VALUES (?, ?, ?, ?, ?, ?);", -1, &stmt, NULL);
sqlite3_bind_int64(stmt, 1, time.getFS());
sqlite3_bind_int(stmt, 2, core_id);
sqlite3_bind_int(stmt, 3, thread_id);
sqlite3_bind_int64(stmt, 4, value0);
sqlite3_bind_int64(stmt, 5, value1);
sqlite3_bind_text(stmt, 6, description ? description : "", -1, SQLITE_STATIC);
int res = sqlite3_step(stmt);
LOG_ASSERT_ERROR(res == SQLITE_DONE, "Error executing SQL statement: %s", sqlite3_errmsg(m_db));
sqlite3_finalize(stmt);
}
StatHist &
StatHist::operator += (StatHist & stat)
{
if (n == 0) { min = stat.min; max = stat.max; }
n += stat.n;
s += stat.s;
s2 += stat.s2;
if (stat.n && stat.min < min) min = stat.min;
if (stat.n && stat.max > max) max = stat.max;
for(int i = 0; i < HIST_MAX; ++i)
hist[i] += stat.hist[i];
return *this;
}
void
StatHist::update(unsigned long v)
{
if (n == 0) {
min = v;
max = v;
}
n++;
s += v;
s2 += v*v;
if (v < min) min = v;
if (v > max) max = v;
int bin = floorLog2(v) + 1;
if (bin >= HIST_MAX) bin = HIST_MAX - 1;
hist[bin]++;
}
void
StatHist::print()
{
printf("n(%lu), avg(%.2f), std(%.2f), min(%lu), max(%lu), hist(%lu",
n, n ? s/float(n) : 0, n ? sqrt((s2/n - (s/n)*(s/n))*n/float(n-1)) : 0, min, max, hist[0]);
for(int i = 1; i < HIST_MAX; ++i)
printf(",%lu", hist[i]);
printf(")\n");
}
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
// Base class for generators using external MC generators.
// For example AliGenPythia using Pythia.
// Provides basic functionality: setting of kinematic cuts on
// decay products and particle selection.
// andreas.morsch@cern.ch
#include <TClonesArray.h>
#include <TMath.h>
#include <TPDGCode.h>
#include <TParticle.h>
#include "AliGenMC.h"
#include "AliRun.h"
#include "AliGeometry.h"
ClassImp(AliGenMC)
AliGenMC::AliGenMC()
:AliGenerator(),
fParticles(0),
fParentSelect(8),
fChildSelect(8),
fCutOnChild(0),
fChildPtMin(0.),
fChildPtMax(1.e10),
fChildPMin(0.),
fChildPMax(1.e10),
fChildPhiMin(0.),
fChildPhiMax(2. * TMath::Pi()),
fChildThetaMin(0.),
fChildThetaMax(TMath::Pi()),
fChildYMin(-12.),
fChildYMax(12.),
fXingAngleX(0.),
fXingAngleY(0.),
fForceDecay(kAll),
fMaxLifeTime(1.e-15),
fAProjectile(1),
fZProjectile(1),
fATarget(1),
fZTarget(1),
fProjectile("P"),
fTarget("P"),
fDyBoost(0.),
fGeometryAcceptance(0),
fPdgCodeParticleforAcceptanceCut(0),
fNumberOfAcceptedParticles(0),
fNprimaries(0)
{
// Default Constructor
}
AliGenMC::AliGenMC(Int_t npart)
:AliGenerator(npart),
fParticles(0),
fParentSelect(8),
fChildSelect(8),
fCutOnChild(0),
fChildPtMin(0.),
fChildPtMax(1.e10),
fChildPMin(0.),
fChildPMax(1.e10),
fChildPhiMin(0.),
fChildPhiMax(2. * TMath::Pi()),
fChildThetaMin(0.),
fChildThetaMax(TMath::Pi()),
fChildYMin(-12.),
fChildYMax(12.),
fXingAngleX(0.),
fXingAngleY(0.),
fForceDecay(kAll),
fMaxLifeTime(1.e-15),
fAProjectile(1),
fZProjectile(1),
fATarget(1),
fZTarget(1),
fProjectile("P"),
fTarget("P"),
fDyBoost(0.),
fGeometryAcceptance(0),
fPdgCodeParticleforAcceptanceCut(0),
fNumberOfAcceptedParticles(0),
fNprimaries(0)
{
// Constructor
//
for (Int_t i=0; i<8; i++) fParentSelect[i]=fChildSelect[i]=0;
}
AliGenMC::~AliGenMC()
{
// Destructor
}
void AliGenMC::Init()
{
//
// Initialization
switch (fForceDecay) {
case kBSemiElectronic:
case kSemiElectronic:
case kDiElectron:
case kBJpsiDiElectron:
case kBPsiPrimeDiElectron:
fChildSelect[0] = kElectron;
break;
case kHardMuons:
case kBSemiMuonic:
case kSemiMuonic:
case kDiMuon:
case kBJpsiDiMuon:
case kBPsiPrimeDiMuon:
case kPiToMu:
case kKaToMu:
case kWToMuon:
case kWToCharmToMuon:
case kZDiMuon:
case kZDiElectron:
fChildSelect[0]=kMuonMinus;
break;
case kWToCharm:
break;
case kHadronicD:
case kHadronicDWithout4Bodies:
fChildSelect[0]=kPiPlus;
fChildSelect[1]=kKPlus;
break;
case kPhiKK:
fChildSelect[0]=kKPlus;
break;
case kBJpsi:
fChildSelect[0]=443;
break;
case kOmega:
case kAll:
case kAllMuonic:
case kNoDecay:
case kNoDecayHeavy:
case kNeutralPion:
break;
}
if (fZTarget != 0 && fAProjectile != 0)
{
fDyBoost = - 0.5 * TMath::Log(Double_t(fZProjectile) * Double_t(fATarget) /
(Double_t(fZTarget) * Double_t(fAProjectile)));
}
}
Bool_t AliGenMC::ParentSelected(Int_t ip) const
{
// True if particle is in list of parent particles to be selected
for (Int_t i=0; i<8; i++)
{
if (fParentSelect.At(i) == ip) return kTRUE;
}
return kFALSE;
}
Bool_t AliGenMC::ChildSelected(Int_t ip) const
{
// True if particle is in list of decay products to be selected
for (Int_t i=0; i<5; i++)
{
if (fChildSelect.At(i) == ip) return kTRUE;
}
return kFALSE;
}
Bool_t AliGenMC::KinematicSelection(TParticle *particle, Int_t flag) const
{
// Perform kinematic selection
Float_t pz = particle->Pz();
Float_t e = particle->Energy();
Float_t pt = particle->Pt();
Float_t p = particle->P();
Float_t theta = particle->Theta();
Float_t mass = particle->GetCalcMass();
Float_t mt2 = pt * pt + mass * mass;
Float_t phi = particle->Phi();
Double_t y, y0;
if (TMath::Abs(pz) < e) {
y = 0.5*TMath::Log((e+pz)/(e-pz));
} else {
y = 1.e10;
}
if (mt2) {
y0 = 0.5*TMath::Log((e+TMath::Abs(pz))*(e+TMath::Abs(pz))/mt2);
} else {
if (TMath::Abs(y) < 1.e10) {
y0 = y;
} else {
y0 = 1.e10;
}
}
y = (pz < 0) ? -y0 : y0;
if (flag == 0) {
//
// Primary particle cuts
//
// transverse momentum cut
if (pt > fPtMax || pt < fPtMin) {
// printf("\n failed pt cut %f %f %f \n",pt,fPtMin,fPtMax);
return kFALSE;
}
//
// momentum cut
if (p > fPMax || p < fPMin) {
// printf("\n failed p cut %f %f %f \n",p,fPMin,fPMax);
return kFALSE;
}
//
// theta cut
if (theta > fThetaMax || theta < fThetaMin) {
// printf("\n failed theta cut %f %f %f \n",theta,fThetaMin,fThetaMax);
return kFALSE;
}
//
// rapidity cut
if (y > fYMax || y < fYMin) {
// printf("\n failed y cut %f %f %f \n",y,fYMin,fYMax);
return kFALSE;
}
//
// phi cut
if (phi > fPhiMax || phi < fPhiMin) {
// printf("\n failed phi cut %f %f %f \n",phi,fPhiMin,fPhiMax);
return kFALSE;
}
} else {
//
// Decay product cuts
//
// transverse momentum cut
if (pt > fChildPtMax || pt < fChildPtMin) {
// printf("\n failed pt cut %f %f %f \n",pt,fChildPtMin,fChildPtMax);
return kFALSE;
}
//
// momentum cut
if (p > fChildPMax || p < fChildPMin) {
// printf("\n failed p cut %f %f %f \n",p,fChildPMin,fChildPMax);
return kFALSE;
}
//
// theta cut
if (theta > fChildThetaMax || theta < fChildThetaMin) {
// printf("\n failed theta cut %f %f %f \n",theta,fChildThetaMin,fChildThetaMax);
return kFALSE;
}
//
// rapidity cut
if (y > fChildYMax || y < fChildYMin) {
// printf("\n failed y cut %f %f %f \n",y,fChildYMin,fChildYMax);
return kFALSE;
}
//
// phi cut
if (phi > fChildPhiMax || phi < fChildPhiMin) {
// printf("\n failed phi cut %f %f %f \n",phi,fChildPhiMin,fChildPhiMax);
return kFALSE;
}
}
return kTRUE;
}
Bool_t AliGenMC::CheckAcceptanceGeometry(Int_t np, TClonesArray* particles)
{
// Check the geometrical acceptance for particle.
Bool_t check ;
Int_t numberOfPdgCodeParticleforAcceptanceCut = 0;
Int_t numberOfAcceptedPdgCodeParticleforAcceptanceCut = 0;
TParticle * particle;
Int_t i;
for (i = 0; i < np; i++) {
particle = (TParticle *) particles->At(i);
if( TMath::Abs( particle->GetPdgCode() ) == TMath::Abs( fPdgCodeParticleforAcceptanceCut ) ) {
numberOfPdgCodeParticleforAcceptanceCut++;
if (fGeometryAcceptance->Impact(particle)) numberOfAcceptedPdgCodeParticleforAcceptanceCut++;
}
}
if ( numberOfAcceptedPdgCodeParticleforAcceptanceCut > (fNumberOfAcceptedParticles-1) )
check = kTRUE;
else
check = kFALSE;
return check;
}
Int_t AliGenMC::CheckPDGCode(Int_t pdgcode) const
{
//
// If the particle is in a diffractive state, then take action accordingly
switch (pdgcode) {
case 91:
return 92;
case 110:
//rho_diff0 -- difficult to translate, return rho0
return 113;
case 210:
//pi_diffr+ -- change to pi+
return 211;
case 220:
//omega_di0 -- change to omega0
return 223;
case 330:
//phi_diff0 -- return phi0
return 333;
case 440:
//J/psi_di0 -- return J/psi
return 443;
case 2110:
//n_diffr -- return neutron
return 2112;
case 2210:
//p_diffr+ -- return proton
return 2212;
}
//non diffractive state -- return code unchanged
return pdgcode;
}
void AliGenMC::Boost()
{
//
// Boost cms into LHC lab frame
//
Double_t beta = TMath::TanH(fDyBoost);
Double_t gamma = 1./TMath::Sqrt(1.-beta*beta);
Double_t gb = gamma * beta;
// printf("\n Boosting particles to lab frame %f %f %f", fDyBoost, beta, gamma);
Int_t i;
Int_t np = fParticles->GetEntriesFast();
for (i = 0; i < np; i++)
{
TParticle* iparticle = (TParticle*) fParticles->At(i);
Double_t e = iparticle->Energy();
Double_t px = iparticle->Px();
Double_t py = iparticle->Py();
Double_t pz = iparticle->Pz();
Double_t eb = gamma * e - gb * pz;
Double_t pzb = -gb * e + gamma * pz;
iparticle->SetMomentum(px, py, pzb, eb);
}
}
void AliGenMC::AddHeader(AliGenEventHeader* header)
{
// Passes header either to the container or to gAlice
if (fContainer) {
fContainer->AddHeader(header);
} else {
gAlice->SetGenEventHeader(header);
}
}
<commit_msg>Using double precision<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
// Base class for generators using external MC generators.
// For example AliGenPythia using Pythia.
// Provides basic functionality: setting of kinematic cuts on
// decay products and particle selection.
// andreas.morsch@cern.ch
#include <TClonesArray.h>
#include <TMath.h>
#include <TPDGCode.h>
#include <TParticle.h>
#include "AliGenMC.h"
#include "AliRun.h"
#include "AliGeometry.h"
ClassImp(AliGenMC)
AliGenMC::AliGenMC()
:AliGenerator(),
fParticles(0),
fParentSelect(8),
fChildSelect(8),
fCutOnChild(0),
fChildPtMin(0.),
fChildPtMax(1.e10),
fChildPMin(0.),
fChildPMax(1.e10),
fChildPhiMin(0.),
fChildPhiMax(2. * TMath::Pi()),
fChildThetaMin(0.),
fChildThetaMax(TMath::Pi()),
fChildYMin(-12.),
fChildYMax(12.),
fXingAngleX(0.),
fXingAngleY(0.),
fForceDecay(kAll),
fMaxLifeTime(1.e-15),
fAProjectile(1),
fZProjectile(1),
fATarget(1),
fZTarget(1),
fProjectile("P"),
fTarget("P"),
fDyBoost(0.),
fGeometryAcceptance(0),
fPdgCodeParticleforAcceptanceCut(0),
fNumberOfAcceptedParticles(0),
fNprimaries(0)
{
// Default Constructor
}
AliGenMC::AliGenMC(Int_t npart)
:AliGenerator(npart),
fParticles(0),
fParentSelect(8),
fChildSelect(8),
fCutOnChild(0),
fChildPtMin(0.),
fChildPtMax(1.e10),
fChildPMin(0.),
fChildPMax(1.e10),
fChildPhiMin(0.),
fChildPhiMax(2. * TMath::Pi()),
fChildThetaMin(0.),
fChildThetaMax(TMath::Pi()),
fChildYMin(-12.),
fChildYMax(12.),
fXingAngleX(0.),
fXingAngleY(0.),
fForceDecay(kAll),
fMaxLifeTime(1.e-15),
fAProjectile(1),
fZProjectile(1),
fATarget(1),
fZTarget(1),
fProjectile("P"),
fTarget("P"),
fDyBoost(0.),
fGeometryAcceptance(0),
fPdgCodeParticleforAcceptanceCut(0),
fNumberOfAcceptedParticles(0),
fNprimaries(0)
{
// Constructor
//
for (Int_t i=0; i<8; i++) fParentSelect[i]=fChildSelect[i]=0;
}
AliGenMC::~AliGenMC()
{
// Destructor
}
void AliGenMC::Init()
{
//
// Initialization
switch (fForceDecay) {
case kBSemiElectronic:
case kSemiElectronic:
case kDiElectron:
case kBJpsiDiElectron:
case kBPsiPrimeDiElectron:
fChildSelect[0] = kElectron;
break;
case kHardMuons:
case kBSemiMuonic:
case kSemiMuonic:
case kDiMuon:
case kBJpsiDiMuon:
case kBPsiPrimeDiMuon:
case kPiToMu:
case kKaToMu:
case kWToMuon:
case kWToCharmToMuon:
case kZDiMuon:
case kZDiElectron:
fChildSelect[0]=kMuonMinus;
break;
case kWToCharm:
break;
case kHadronicD:
case kHadronicDWithout4Bodies:
fChildSelect[0]=kPiPlus;
fChildSelect[1]=kKPlus;
break;
case kPhiKK:
fChildSelect[0]=kKPlus;
break;
case kBJpsi:
fChildSelect[0]=443;
break;
case kOmega:
case kAll:
case kAllMuonic:
case kNoDecay:
case kNoDecayHeavy:
case kNeutralPion:
break;
}
if (fZTarget != 0 && fAProjectile != 0)
{
fDyBoost = - 0.5 * TMath::Log(Double_t(fZProjectile) * Double_t(fATarget) /
(Double_t(fZTarget) * Double_t(fAProjectile)));
}
}
Bool_t AliGenMC::ParentSelected(Int_t ip) const
{
// True if particle is in list of parent particles to be selected
for (Int_t i=0; i<8; i++)
{
if (fParentSelect.At(i) == ip) return kTRUE;
}
return kFALSE;
}
Bool_t AliGenMC::ChildSelected(Int_t ip) const
{
// True if particle is in list of decay products to be selected
for (Int_t i=0; i<5; i++)
{
if (fChildSelect.At(i) == ip) return kTRUE;
}
return kFALSE;
}
Bool_t AliGenMC::KinematicSelection(TParticle *particle, Int_t flag) const
{
// Perform kinematic selection
Double_t pz = particle->Pz();
Double_t e = particle->Energy();
Double_t pt = particle->Pt();
Double_t p = particle->P();
Double_t theta = particle->Theta();
Double_t mass = particle->GetCalcMass();
Double_t mt2 = pt * pt + mass * mass;
Double_t phi = particle->Phi();
Double_t y, y0;
if (TMath::Abs(pz) < e) {
y = 0.5*TMath::Log((e+pz)/(e-pz));
} else {
y = 1.e10;
}
if (mt2) {
y0 = 0.5*TMath::Log((e+TMath::Abs(pz))*(e+TMath::Abs(pz))/mt2);
} else {
if (TMath::Abs(y) < 1.e10) {
y0 = y;
} else {
y0 = 1.e10;
}
}
y = (pz < 0) ? -y0 : y0;
if (flag == 0) {
//
// Primary particle cuts
//
// transverse momentum cut
if (pt > fPtMax || pt < fPtMin) {
// printf("\n failed pt cut %f %f %f \n",pt,fPtMin,fPtMax);
return kFALSE;
}
//
// momentum cut
if (p > fPMax || p < fPMin) {
// printf("\n failed p cut %f %f %f \n",p,fPMin,fPMax);
return kFALSE;
}
//
// theta cut
if (theta > fThetaMax || theta < fThetaMin) {
// printf("\n failed theta cut %f %f %f \n",theta,fThetaMin,fThetaMax);
return kFALSE;
}
//
// rapidity cut
if (y > fYMax || y < fYMin) {
// printf("\n failed y cut %f %f %f \n",y,fYMin,fYMax);
return kFALSE;
}
//
// phi cut
if (phi > fPhiMax || phi < fPhiMin) {
// printf("\n failed phi cut %f %f %f \n",phi,fPhiMin,fPhiMax);
return kFALSE;
}
} else {
//
// Decay product cuts
//
// transverse momentum cut
if (pt > fChildPtMax || pt < fChildPtMin) {
// printf("\n failed pt cut %f %f %f \n",pt,fChildPtMin,fChildPtMax);
return kFALSE;
}
//
// momentum cut
if (p > fChildPMax || p < fChildPMin) {
// printf("\n failed p cut %f %f %f \n",p,fChildPMin,fChildPMax);
return kFALSE;
}
//
// theta cut
if (theta > fChildThetaMax || theta < fChildThetaMin) {
// printf("\n failed theta cut %f %f %f \n",theta,fChildThetaMin,fChildThetaMax);
return kFALSE;
}
//
// rapidity cut
if (y > fChildYMax || y < fChildYMin) {
// printf("\n failed y cut %f %f %f \n",y,fChildYMin,fChildYMax);
return kFALSE;
}
//
// phi cut
if (phi > fChildPhiMax || phi < fChildPhiMin) {
// printf("\n failed phi cut %f %f %f \n",phi,fChildPhiMin,fChildPhiMax);
return kFALSE;
}
}
return kTRUE;
}
Bool_t AliGenMC::CheckAcceptanceGeometry(Int_t np, TClonesArray* particles)
{
// Check the geometrical acceptance for particle.
Bool_t check ;
Int_t numberOfPdgCodeParticleforAcceptanceCut = 0;
Int_t numberOfAcceptedPdgCodeParticleforAcceptanceCut = 0;
TParticle * particle;
Int_t i;
for (i = 0; i < np; i++) {
particle = (TParticle *) particles->At(i);
if( TMath::Abs( particle->GetPdgCode() ) == TMath::Abs( fPdgCodeParticleforAcceptanceCut ) ) {
numberOfPdgCodeParticleforAcceptanceCut++;
if (fGeometryAcceptance->Impact(particle)) numberOfAcceptedPdgCodeParticleforAcceptanceCut++;
}
}
if ( numberOfAcceptedPdgCodeParticleforAcceptanceCut > (fNumberOfAcceptedParticles-1) )
check = kTRUE;
else
check = kFALSE;
return check;
}
Int_t AliGenMC::CheckPDGCode(Int_t pdgcode) const
{
//
// If the particle is in a diffractive state, then take action accordingly
switch (pdgcode) {
case 91:
return 92;
case 110:
//rho_diff0 -- difficult to translate, return rho0
return 113;
case 210:
//pi_diffr+ -- change to pi+
return 211;
case 220:
//omega_di0 -- change to omega0
return 223;
case 330:
//phi_diff0 -- return phi0
return 333;
case 440:
//J/psi_di0 -- return J/psi
return 443;
case 2110:
//n_diffr -- return neutron
return 2112;
case 2210:
//p_diffr+ -- return proton
return 2212;
}
//non diffractive state -- return code unchanged
return pdgcode;
}
void AliGenMC::Boost()
{
//
// Boost cms into LHC lab frame
//
Double_t beta = TMath::TanH(fDyBoost);
Double_t gamma = 1./TMath::Sqrt(1.-beta*beta);
Double_t gb = gamma * beta;
// printf("\n Boosting particles to lab frame %f %f %f", fDyBoost, beta, gamma);
Int_t i;
Int_t np = fParticles->GetEntriesFast();
for (i = 0; i < np; i++)
{
TParticle* iparticle = (TParticle*) fParticles->At(i);
Double_t e = iparticle->Energy();
Double_t px = iparticle->Px();
Double_t py = iparticle->Py();
Double_t pz = iparticle->Pz();
Double_t eb = gamma * e - gb * pz;
Double_t pzb = -gb * e + gamma * pz;
iparticle->SetMomentum(px, py, pzb, eb);
}
}
void AliGenMC::AddHeader(AliGenEventHeader* header)
{
// Passes header either to the container or to gAlice
if (fContainer) {
fContainer->AddHeader(header);
} else {
gAlice->SetGenEventHeader(header);
}
}
<|endoftext|> |
<commit_before>#include "tetrisboard.h"
#include "square.h"
#include "block.h"
#include <vector>
#include <queue>
TetrisBoard::TetrisBoard(int nbrOfRows, int nbrOfColumns, BlockType current, BlockType next)
: RawTetrisBoard(nbrOfRows, nbrOfColumns, current, next) {
nbrOfUpdates_ = 0;
setCurrentBlock(current);
setNextBlock(next);
}
void TetrisBoard::restart(BlockType current, BlockType next) {
nextBlockQueue_ = std::queue<BlockType>();
gameEvents_ = std::queue<GameEvent>();
setCurrentBlock(current);
setNextBlock(next);
clearBoard();
nbrOfUpdates_ = 0;
}
void TetrisBoard::triggerEvent(GameEvent gameEvent) {
gameEvents_.push(gameEvent);
switch (gameEvent) {
case GameEvent::BLOCK_COLLISION:
setNextBlock(nextBlockQueue_.front());
nextBlockQueue_.pop();
++nbrOfUpdates_;
break;
}
}
void TetrisBoard::add(BlockType next) {
nextBlockQueue_.push(next);
}
bool TetrisBoard::pollGameEvent(GameEvent& gameEvent) {
if (gameEvents_.empty()) {
return false;
}
gameEvent = gameEvents_.front();
gameEvents_.pop();
return true;
}
void TetrisBoard::addRows(const std::vector<BlockType>& blockTypes) {
squaresToAdd_.insert(squaresToAdd_.end(),blockTypes.begin(), blockTypes.end());
}
std::vector<BlockType> TetrisBoard::addExternalRows() {
std::vector<BlockType> tmp = squaresToAdd_;
squaresToAdd_.clear();
return tmp;
}
<commit_msg>Bug fix in tetrisboard. External rows to be added was not cleared when restarting the game.<commit_after>#include "tetrisboard.h"
#include "square.h"
#include "block.h"
#include <vector>
#include <queue>
TetrisBoard::TetrisBoard(int nbrOfRows, int nbrOfColumns, BlockType current, BlockType next)
: RawTetrisBoard(nbrOfRows, nbrOfColumns, current, next) {
nbrOfUpdates_ = 0;
setCurrentBlock(current);
setNextBlock(next);
}
void TetrisBoard::restart(BlockType current, BlockType next) {
squaresToAdd_.clear();
nextBlockQueue_ = std::queue<BlockType>();
gameEvents_ = std::queue<GameEvent>();
setCurrentBlock(current);
setNextBlock(next);
clearBoard();
nbrOfUpdates_ = 0;
}
void TetrisBoard::triggerEvent(GameEvent gameEvent) {
gameEvents_.push(gameEvent);
switch (gameEvent) {
case GameEvent::BLOCK_COLLISION:
setNextBlock(nextBlockQueue_.front());
nextBlockQueue_.pop();
++nbrOfUpdates_;
break;
}
}
void TetrisBoard::add(BlockType next) {
nextBlockQueue_.push(next);
}
bool TetrisBoard::pollGameEvent(GameEvent& gameEvent) {
if (gameEvents_.empty()) {
return false;
}
gameEvent = gameEvents_.front();
gameEvents_.pop();
return true;
}
void TetrisBoard::addRows(const std::vector<BlockType>& blockTypes) {
squaresToAdd_.insert(squaresToAdd_.end(),blockTypes.begin(), blockTypes.end());
}
std::vector<BlockType> TetrisBoard::addExternalRows() {
std::vector<BlockType> tmp = squaresToAdd_;
squaresToAdd_.clear();
return tmp;
}
<|endoftext|> |
<commit_before>/*************************************************************************
Crazy Eddie's GUI System (http://www.cegui.org.uk)
Copyright (C)2004 - 2005 Paul D Turner (paul@cegui.org.uk)
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*************************************************************************/
#include <xercesc/sax2/Attributes.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/TransService.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/sax2/SAX2XMLReader.hpp>
#include <xercesc/sax2/XMLReaderFactory.hpp>
#include <xercesc/framework/MemBufInputSource.hpp>
#include "CEGUIString.h"
#include "CEGUIXmlHandlerHelper.h"
#include "CEGUIExceptions.h"
#include "CEGUIResourceProvider.h"
#include "CEGUISystem.h"
#include "CEGUILogger.h"
using XERCES_CPP_NAMESPACE::XMLString;
using XERCES_CPP_NAMESPACE::XMLTransService;
using XERCES_CPP_NAMESPACE::XMLPlatformUtils;
using XERCES_CPP_NAMESPACE::XMLTranscoder;
using XERCES_CPP_NAMESPACE::XMLRecognizer;
namespace CEGUI
{
const XMLCh* XmlHandlerHelper::getAttributeValueAsXmlChar(const XERCES_CPP_NAMESPACE::Attributes& attrs, const char* const attributeName)
{
XMLCh* attr_name = XMLString::transcode(attributeName);
const XMLCh* val_str = attrs.getValue(attr_name);
XMLString::release(&attr_name);
return val_str;
}
char* XmlHandlerHelper::getAttributeValueAsChar(const XERCES_CPP_NAMESPACE::Attributes& attrs, const char* const attributeName)
{
return XMLString::transcode(getAttributeValueAsXmlChar(attrs, attributeName));
}
int XmlHandlerHelper::getAttributeValueAsInteger(const XERCES_CPP_NAMESPACE::Attributes& attrs, const char* const attributeName)
{
return XMLString::parseInt(getAttributeValueAsXmlChar(attrs, attributeName));
}
String XmlHandlerHelper::getAttributeValueAsString(const XERCES_CPP_NAMESPACE::Attributes& attrs, const char* const attributeName)
{
return transcodeXmlCharToString(getAttributeValueAsXmlChar(attrs, attributeName));
}
String XmlHandlerHelper::transcodeXmlCharToString(const XMLCh* const xmlch_str)
{
XMLTransService::Codes res;
XMLTranscoder* transcoder = XMLPlatformUtils::fgTransService->makeNewTranscoderFor(XMLRecognizer::UTF_8, res, 4096, XMLPlatformUtils::fgMemoryManager );
if (res == XMLTransService::Ok)
{
String out;
utf8 outBuff[128];
unsigned int outputLength;
unsigned int eaten = 0;
unsigned int offset = 0;
unsigned int inputLength = XMLString::stringLen(xmlch_str);
while (inputLength)
{
outputLength = transcoder->transcodeTo(xmlch_str + offset, inputLength, outBuff, 128, eaten, XMLTranscoder::UnRep_RepChar);
out.append(outBuff, outputLength);
offset += eaten;
inputLength -= eaten;
}
delete transcoder;
return out;
}
else
{
throw GenericException((utf8*)"XmlHandlerHelper::transcodeXmlCharToString - Internal Error: Could not create UTF-8 string transcoder.");
}
}
void XmlHandlerHelper::initialiseSchema(XERCES_CPP_NAMESPACE::SAX2XMLReader* parser, const String& schemaName, const String& xmlFilename, const String& resourceGroup)
{
XERCES_CPP_NAMESPACE_USE;
// enable schema use and set validation options
parser->setFeature(XMLUni::fgXercesSchema, true);
parser->setFeature(XMLUni::fgSAX2CoreValidation, true);
parser->setFeature(XMLUni::fgXercesValidationErrorAsFatal, true);
// load in the raw schema data
RawDataContainer rawSchemaData;
System::getSingleton().getResourceProvider()->loadRawDataContainer(schemaName, rawSchemaData, resourceGroup);
// wrap schema data in a xerces MemBufInputSource object
MemBufInputSource schemaData(
rawSchemaData.getDataPtr(),
static_cast<const unsigned int>(rawSchemaData.getSize()),
schemaName.c_str(),
false);
parser->loadGrammar(schemaData, Grammar::SchemaGrammarType, true);
// enable grammar reuse
parser->setFeature(XMLUni::fgXercesUseCachedGrammarInParse, true);
// set schema for usage
XMLCh* pval = XMLString::transcode(schemaName.c_str());
parser->setProperty(XMLUni::fgXercesSchemaExternalNoNameSpaceSchemaLocation, pval);
XMLString::release(&pval);
}
XERCES_CPP_NAMESPACE::SAX2XMLReader* XmlHandlerHelper::createParser(XERCES_CPP_NAMESPACE::DefaultHandler& handler)
{
XERCES_CPP_NAMESPACE_USE;
SAX2XMLReader* parser = XMLReaderFactory::createXMLReader();
// set basic settings we want from parser
parser->setFeature(XMLUni::fgSAX2CoreNameSpaces, true);
// set handlers
parser->setContentHandler(&handler);
parser->setErrorHandler(&handler);
return parser;
}
void XmlHandlerHelper::parseXMLFile(XERCES_CPP_NAMESPACE::SAX2XMLReader* parser, const String& xmlFilename, const String& resourceGroup)
{
XERCES_CPP_NAMESPACE_USE;
// use resource provider to load file data
RawDataContainer rawXMLData;
System::getSingleton().getResourceProvider()->loadRawDataContainer(xmlFilename, rawXMLData, resourceGroup);
MemBufInputSource fileData(
rawXMLData.getDataPtr(),
static_cast<const unsigned int>(rawXMLData.getSize()),
xmlFilename.c_str(),
false);
// perform parse
parser->parse(fileData);
}
void XmlHandlerHelper::parseXMLFile(XERCES_CPP_NAMESPACE::DefaultHandler& handler, const String& schemaName, const String& xmlFilename, const String& resourceGroup)
{
XERCES_CPP_NAMESPACE_USE;
// create parser
SAX2XMLReader* parser = XmlHandlerHelper::createParser(handler);
// set up schema
XmlHandlerHelper::initialiseSchema(parser, schemaName, xmlFilename, resourceGroup);
// do parse
try
{
XmlHandlerHelper::parseXMLFile(parser, xmlFilename, resourceGroup);
}
catch(const XMLException& exc)
{
if (exc.getCode() != XMLExcepts::NoError)
{
delete parser;
char* excmsg = XMLString::transcode(exc.getMessage());
String message((utf8*)"XmlHandlerHelper::parse - An error occurred while parsing XML file '" + xmlFilename + "'. Additional information: ");
message += excmsg;
XMLString::release(&excmsg);
throw FileIOException(message);
}
}
catch(const SAXParseException& exc)
{
delete parser;
char* excmsg = XMLString::transcode(exc.getMessage());
String message((utf8*)"XmlHandlerHelper::parse - An error occurred while parsing XML file '" + xmlFilename + "'. Additional information: ");
message += excmsg;
XMLString::release(&excmsg);
throw FileIOException(message);
}
catch(...)
{
delete parser;
Logger::getSingleton().logEvent("XmlHandlerHelper::parse - An unexpected error occurred while parsing XML file '" + xmlFilename + "'.", Errors);
throw;
}
// cleanup
delete parser;
}
}
<commit_msg>Added code that tries to get the schema file from the same directory as the xml file being loaded when the default path fails.<commit_after>/*************************************************************************
Crazy Eddie's GUI System (http://www.cegui.org.uk)
Copyright (C)2004 - 2005 Paul D Turner (paul@cegui.org.uk)
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*************************************************************************/
#include <xercesc/sax2/Attributes.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/TransService.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/sax2/SAX2XMLReader.hpp>
#include <xercesc/sax2/XMLReaderFactory.hpp>
#include <xercesc/framework/MemBufInputSource.hpp>
#include "CEGUIString.h"
#include "CEGUIXmlHandlerHelper.h"
#include "CEGUIExceptions.h"
#include "CEGUIResourceProvider.h"
#include "CEGUISystem.h"
#include "CEGUILogger.h"
using XERCES_CPP_NAMESPACE::XMLString;
using XERCES_CPP_NAMESPACE::XMLTransService;
using XERCES_CPP_NAMESPACE::XMLPlatformUtils;
using XERCES_CPP_NAMESPACE::XMLTranscoder;
using XERCES_CPP_NAMESPACE::XMLRecognizer;
namespace CEGUI
{
const XMLCh* XmlHandlerHelper::getAttributeValueAsXmlChar(const XERCES_CPP_NAMESPACE::Attributes& attrs, const char* const attributeName)
{
XMLCh* attr_name = XMLString::transcode(attributeName);
const XMLCh* val_str = attrs.getValue(attr_name);
XMLString::release(&attr_name);
return val_str;
}
char* XmlHandlerHelper::getAttributeValueAsChar(const XERCES_CPP_NAMESPACE::Attributes& attrs, const char* const attributeName)
{
return XMLString::transcode(getAttributeValueAsXmlChar(attrs, attributeName));
}
int XmlHandlerHelper::getAttributeValueAsInteger(const XERCES_CPP_NAMESPACE::Attributes& attrs, const char* const attributeName)
{
return XMLString::parseInt(getAttributeValueAsXmlChar(attrs, attributeName));
}
String XmlHandlerHelper::getAttributeValueAsString(const XERCES_CPP_NAMESPACE::Attributes& attrs, const char* const attributeName)
{
return transcodeXmlCharToString(getAttributeValueAsXmlChar(attrs, attributeName));
}
String XmlHandlerHelper::transcodeXmlCharToString(const XMLCh* const xmlch_str)
{
XMLTransService::Codes res;
XMLTranscoder* transcoder = XMLPlatformUtils::fgTransService->makeNewTranscoderFor(XMLRecognizer::UTF_8, res, 4096, XMLPlatformUtils::fgMemoryManager );
if (res == XMLTransService::Ok)
{
String out;
utf8 outBuff[128];
unsigned int outputLength;
unsigned int eaten = 0;
unsigned int offset = 0;
unsigned int inputLength = XMLString::stringLen(xmlch_str);
while (inputLength)
{
outputLength = transcoder->transcodeTo(xmlch_str + offset, inputLength, outBuff, 128, eaten, XMLTranscoder::UnRep_RepChar);
out.append(outBuff, outputLength);
offset += eaten;
inputLength -= eaten;
}
delete transcoder;
return out;
}
else
{
throw GenericException((utf8*)"XmlHandlerHelper::transcodeXmlCharToString - Internal Error: Could not create UTF-8 string transcoder.");
}
}
void XmlHandlerHelper::initialiseSchema(XERCES_CPP_NAMESPACE::SAX2XMLReader* parser, const String& schemaName, const String& xmlFilename, const String& resourceGroup)
{
XERCES_CPP_NAMESPACE_USE;
// enable schema use and set validation options
parser->setFeature(XMLUni::fgXercesSchema, true);
parser->setFeature(XMLUni::fgSAX2CoreValidation, true);
parser->setFeature(XMLUni::fgXercesValidationErrorAsFatal, true);
// load in the raw schema data
RawDataContainer rawSchemaData;
// try base filename first
try
{
Logger::getSingleton().logEvent("XmlHandlerHelper::initialiseSchema - Attempting to load schema from file '" + schemaName + "'.", Informative);
System::getSingleton().getResourceProvider()->loadRawDataContainer(schemaName, rawSchemaData, resourceGroup);
}
// oops, no file. Try an alternative instead...
catch(InvalidRequestException)
{
// get path from filename
String schemaFilename;
size_t pos = xmlFilename.rfind("/");
if (pos == String::npos) pos = xmlFilename.rfind("\\");
if (pos != String::npos) schemaFilename.assign(xmlFilename, 0, pos + 1);
// append schema filename
schemaFilename += schemaName;
// re-try the load operation.
Logger::getSingleton().logEvent("XmlHandlerHelper::initialiseSchema - Attempting to load schema from file '" + schemaFilename + "'.", Informative);
System::getSingleton().getResourceProvider()->loadRawDataContainer(schemaFilename, rawSchemaData, resourceGroup);
}
// wrap schema data in a xerces MemBufInputSource object
MemBufInputSource schemaData(
rawSchemaData.getDataPtr(),
static_cast<const unsigned int>(rawSchemaData.getSize()),
schemaName.c_str(),
false);
parser->loadGrammar(schemaData, Grammar::SchemaGrammarType, true);
// enable grammar reuse
parser->setFeature(XMLUni::fgXercesUseCachedGrammarInParse, true);
// set schema for usage
XMLCh* pval = XMLString::transcode(schemaName.c_str());
parser->setProperty(XMLUni::fgXercesSchemaExternalNoNameSpaceSchemaLocation, pval);
XMLString::release(&pval);
Logger::getSingleton().logEvent("XmlHandlerHelper::initialiseSchema - XML schema file '" + schemaName + "' has been initialised.", Informative);
}
XERCES_CPP_NAMESPACE::SAX2XMLReader* XmlHandlerHelper::createParser(XERCES_CPP_NAMESPACE::DefaultHandler& handler)
{
XERCES_CPP_NAMESPACE_USE;
SAX2XMLReader* parser = XMLReaderFactory::createXMLReader();
// set basic settings we want from parser
parser->setFeature(XMLUni::fgSAX2CoreNameSpaces, true);
// set handlers
parser->setContentHandler(&handler);
parser->setErrorHandler(&handler);
return parser;
}
void XmlHandlerHelper::parseXMLFile(XERCES_CPP_NAMESPACE::SAX2XMLReader* parser, const String& xmlFilename, const String& resourceGroup)
{
XERCES_CPP_NAMESPACE_USE;
// use resource provider to load file data
RawDataContainer rawXMLData;
System::getSingleton().getResourceProvider()->loadRawDataContainer(xmlFilename, rawXMLData, resourceGroup);
MemBufInputSource fileData(
rawXMLData.getDataPtr(),
static_cast<const unsigned int>(rawXMLData.getSize()),
xmlFilename.c_str(),
false);
// perform parse
parser->parse(fileData);
}
void XmlHandlerHelper::parseXMLFile(XERCES_CPP_NAMESPACE::DefaultHandler& handler, const String& schemaName, const String& xmlFilename, const String& resourceGroup)
{
XERCES_CPP_NAMESPACE_USE;
// create parser
SAX2XMLReader* parser = XmlHandlerHelper::createParser(handler);
// set up schema
XmlHandlerHelper::initialiseSchema(parser, schemaName, xmlFilename, resourceGroup);
// do parse
try
{
XmlHandlerHelper::parseXMLFile(parser, xmlFilename, resourceGroup);
}
catch(const XMLException& exc)
{
if (exc.getCode() != XMLExcepts::NoError)
{
delete parser;
char* excmsg = XMLString::transcode(exc.getMessage());
String message((utf8*)"XmlHandlerHelper::parse - An error occurred while parsing XML file '" + xmlFilename + "'. Additional information: ");
message += excmsg;
XMLString::release(&excmsg);
throw FileIOException(message);
}
}
catch(const SAXParseException& exc)
{
delete parser;
char* excmsg = XMLString::transcode(exc.getMessage());
String message((utf8*)"XmlHandlerHelper::parse - An error occurred while parsing XML file '" + xmlFilename + "'. Additional information: ");
message += excmsg;
XMLString::release(&excmsg);
throw FileIOException(message);
}
catch(...)
{
delete parser;
Logger::getSingleton().logEvent("XmlHandlerHelper::parse - An unexpected error occurred while parsing XML file '" + xmlFilename + "'.", Errors);
throw;
}
// cleanup
delete parser;
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: DAVSession.hxx,v $
*
* $Revision: 1.16 $
*
* last change: $Author: vg $ $Date: 2003-10-06 18:52:36 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _DAVSESSION_HXX_
#define _DAVSESSION_HXX_
#include <memory>
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XOutputStream.hpp>
#endif
#ifndef _DAVEXCEPTION_HXX_
#include "DAVException.hxx"
#endif
#ifndef _DAVPROPERTIES_HXX_
#include "DAVProperties.hxx"
#endif
#ifndef _DAVRESOURCE_HXX_
#include "DAVResource.hxx"
#endif
#ifndef _DAVSESSIONFACTORY_HXX_
#include "DAVSessionFactory.hxx"
#endif
#ifndef _DAVTYPES_HXX_
#include "DAVTypes.hxx"
#endif
#ifndef _DAVREQUESTENVIRONMENT_HXX_
#include "DAVRequestEnvironment.hxx"
#endif
namespace webdav_ucp
{
class DAVAuthListener;
class DAVSession
{
public:
inline void acquire() SAL_THROW(())
{
osl_incrementInterlockedCount( &m_nRefCount );
}
void release() SAL_THROW(())
{
if ( osl_decrementInterlockedCount( &m_nRefCount ) == 0 )
{
m_xFactory->releaseElement( this );
delete this;
}
}
virtual sal_Bool CanUse( const ::rtl::OUString & inPath ) = 0;
virtual sal_Bool UsesProxy() = 0;
// DAV methods
//
virtual void OPTIONS( const ::rtl::OUString & inPath,
DAVCapabilities & outCapabilities,
const DAVRequestEnvironment & rEnv )
throw( DAVException ) = 0;
// allprop & named
virtual void PROPFIND( const ::rtl::OUString & inPath,
const Depth inDepth,
const std::vector< ::rtl::OUString > & inPropertyNames,
std::vector< DAVResource > & ioResources,
const DAVRequestEnvironment & rEnv )
throw( DAVException ) = 0;
// propnames
virtual void PROPFIND( const ::rtl::OUString & inPath,
const Depth inDepth,
std::vector< DAVResourceInfo > & ioResInfo,
const DAVRequestEnvironment & rEnv )
throw( DAVException ) = 0;
virtual void PROPPATCH( const ::rtl::OUString & inPath,
const std::vector< ProppatchValue > & inValues,
const DAVRequestEnvironment & rEnv )
throw( DAVException ) = 0;
virtual void HEAD( const ::rtl::OUString & inPath,
const std::vector< ::rtl::OUString > & inHeaderNames,
DAVResource & ioResource,
const DAVRequestEnvironment & rEnv )
throw( DAVException ) = 0;
virtual com::sun::star::uno::Reference< com::sun::star::io::XInputStream >
GET( const ::rtl::OUString & inPath,
const DAVRequestEnvironment & rEnv )
throw( DAVException ) = 0;
virtual void GET( void* userData,
const ::rtl::OUString & inPath,
const DAVRequestEnvironment & rEnv )
throw( DAVException ) = 0;
virtual void GET( const ::rtl::OUString & inPath,
com::sun::star::uno::Reference< com::sun::star::io::XOutputStream >& o,
const DAVRequestEnvironment & rEnv )
throw( DAVException ) = 0;
virtual com::sun::star::uno::Reference< com::sun::star::io::XInputStream >
GET( const ::rtl::OUString & inPath,
const std::vector< ::rtl::OUString > & inHeaderNames,
DAVResource & ioResource,
const DAVRequestEnvironment & rEnv )
throw( DAVException ) = 0;
virtual void GET( void* userData,
const ::rtl::OUString & inPath,
const std::vector< ::rtl::OUString > & inHeaderNames,
DAVResource & ioResource,
const DAVRequestEnvironment & rEnv )
throw( DAVException ) = 0;
virtual void GET( const ::rtl::OUString & inPath,
com::sun::star::uno::Reference< com::sun::star::io::XOutputStream >& o,
const std::vector< ::rtl::OUString > & inHeaderNames,
DAVResource & ioResource,
const DAVRequestEnvironment & rEnv )
throw( DAVException ) = 0;
virtual void PUT( const ::rtl::OUString & inPath,
const com::sun::star::uno::Reference<
com::sun::star::io::XInputStream >& s,
const DAVRequestEnvironment & rEnv )
throw( DAVException ) = 0;
virtual com::sun::star::uno::Reference< com::sun::star::io::XInputStream >
POST( const rtl::OUString & inPath,
const rtl::OUString & rContentType,
const rtl::OUString & rReferer,
const com::sun::star::uno::Reference<
com::sun::star::io::XInputStream > & inInputStream,
const DAVRequestEnvironment & rEnv )
throw ( DAVException ) = 0;
virtual void POST( const rtl::OUString & inPath,
const rtl::OUString & rContentType,
const rtl::OUString & rReferer,
const com::sun::star::uno::Reference<
com::sun::star::io::XInputStream > & inInputStream,
com::sun::star::uno::Reference<
com::sun::star::io::XOutputStream > & oOutputStream,
const DAVRequestEnvironment & rEnv )
throw ( DAVException ) = 0;
virtual void MKCOL( const ::rtl::OUString & inPath,
const DAVRequestEnvironment & rEnv )
throw( DAVException ) = 0;
virtual void COPY( const ::rtl::OUString & inSource,
const ::rtl::OUString & inDestination,
const DAVRequestEnvironment & rEnv,
sal_Bool inOverwrite = false )
throw( DAVException ) = 0;
virtual void MOVE( const ::rtl::OUString & inSource,
const ::rtl::OUString & inDestination,
const DAVRequestEnvironment & rEnv,
sal_Bool inOverwrite = false )
throw( DAVException ) = 0;
virtual void DESTROY( const ::rtl::OUString & inPath,
const DAVRequestEnvironment & rEnv )
throw( DAVException ) = 0;
// Note: Uncomment the following if locking support is required
/*
virtual void LOCK ( const Lock & inLock,
const DAVRequestEnvironment & rEnv )
throw( DAVException ) = 0;
virtual void UNLOCK ( const Lock & inLock,
const DAVRequestEnvironment & rEnv )
throw( DAVException ) = 0;
*/
protected:
rtl::Reference< DAVSessionFactory > m_xFactory;
DAVSession( rtl::Reference< DAVSessionFactory > const & rFactory )
: m_xFactory( rFactory ), m_nRefCount( 0 ) {}
virtual ~DAVSession() {}
private:
DAVSessionFactory::Map::iterator m_aContainerIt;
oslInterlockedCount m_nRefCount;
friend class DAVSessionFactory;
#if defined WNT && _MSC_VER < 1310
friend struct std::auto_ptr< DAVSession >;
// work around compiler bug...
#else // WNT
friend class std::auto_ptr< DAVSession >;
#endif // WNT
};
}; // namespace webdav_ucp
#endif // _DAVSESSION_HXX_
<commit_msg>INTEGRATION: CWS ooo19126 (1.16.128); FILE MERGED 2005/09/05 18:45:33 rt 1.16.128.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: DAVSession.hxx,v $
*
* $Revision: 1.17 $
*
* last change: $Author: rt $ $Date: 2005-09-09 16:08:17 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _DAVSESSION_HXX_
#define _DAVSESSION_HXX_
#include <memory>
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XOutputStream.hpp>
#endif
#ifndef _DAVEXCEPTION_HXX_
#include "DAVException.hxx"
#endif
#ifndef _DAVPROPERTIES_HXX_
#include "DAVProperties.hxx"
#endif
#ifndef _DAVRESOURCE_HXX_
#include "DAVResource.hxx"
#endif
#ifndef _DAVSESSIONFACTORY_HXX_
#include "DAVSessionFactory.hxx"
#endif
#ifndef _DAVTYPES_HXX_
#include "DAVTypes.hxx"
#endif
#ifndef _DAVREQUESTENVIRONMENT_HXX_
#include "DAVRequestEnvironment.hxx"
#endif
namespace webdav_ucp
{
class DAVAuthListener;
class DAVSession
{
public:
inline void acquire() SAL_THROW(())
{
osl_incrementInterlockedCount( &m_nRefCount );
}
void release() SAL_THROW(())
{
if ( osl_decrementInterlockedCount( &m_nRefCount ) == 0 )
{
m_xFactory->releaseElement( this );
delete this;
}
}
virtual sal_Bool CanUse( const ::rtl::OUString & inPath ) = 0;
virtual sal_Bool UsesProxy() = 0;
// DAV methods
//
virtual void OPTIONS( const ::rtl::OUString & inPath,
DAVCapabilities & outCapabilities,
const DAVRequestEnvironment & rEnv )
throw( DAVException ) = 0;
// allprop & named
virtual void PROPFIND( const ::rtl::OUString & inPath,
const Depth inDepth,
const std::vector< ::rtl::OUString > & inPropertyNames,
std::vector< DAVResource > & ioResources,
const DAVRequestEnvironment & rEnv )
throw( DAVException ) = 0;
// propnames
virtual void PROPFIND( const ::rtl::OUString & inPath,
const Depth inDepth,
std::vector< DAVResourceInfo > & ioResInfo,
const DAVRequestEnvironment & rEnv )
throw( DAVException ) = 0;
virtual void PROPPATCH( const ::rtl::OUString & inPath,
const std::vector< ProppatchValue > & inValues,
const DAVRequestEnvironment & rEnv )
throw( DAVException ) = 0;
virtual void HEAD( const ::rtl::OUString & inPath,
const std::vector< ::rtl::OUString > & inHeaderNames,
DAVResource & ioResource,
const DAVRequestEnvironment & rEnv )
throw( DAVException ) = 0;
virtual com::sun::star::uno::Reference< com::sun::star::io::XInputStream >
GET( const ::rtl::OUString & inPath,
const DAVRequestEnvironment & rEnv )
throw( DAVException ) = 0;
virtual void GET( void* userData,
const ::rtl::OUString & inPath,
const DAVRequestEnvironment & rEnv )
throw( DAVException ) = 0;
virtual void GET( const ::rtl::OUString & inPath,
com::sun::star::uno::Reference< com::sun::star::io::XOutputStream >& o,
const DAVRequestEnvironment & rEnv )
throw( DAVException ) = 0;
virtual com::sun::star::uno::Reference< com::sun::star::io::XInputStream >
GET( const ::rtl::OUString & inPath,
const std::vector< ::rtl::OUString > & inHeaderNames,
DAVResource & ioResource,
const DAVRequestEnvironment & rEnv )
throw( DAVException ) = 0;
virtual void GET( void* userData,
const ::rtl::OUString & inPath,
const std::vector< ::rtl::OUString > & inHeaderNames,
DAVResource & ioResource,
const DAVRequestEnvironment & rEnv )
throw( DAVException ) = 0;
virtual void GET( const ::rtl::OUString & inPath,
com::sun::star::uno::Reference< com::sun::star::io::XOutputStream >& o,
const std::vector< ::rtl::OUString > & inHeaderNames,
DAVResource & ioResource,
const DAVRequestEnvironment & rEnv )
throw( DAVException ) = 0;
virtual void PUT( const ::rtl::OUString & inPath,
const com::sun::star::uno::Reference<
com::sun::star::io::XInputStream >& s,
const DAVRequestEnvironment & rEnv )
throw( DAVException ) = 0;
virtual com::sun::star::uno::Reference< com::sun::star::io::XInputStream >
POST( const rtl::OUString & inPath,
const rtl::OUString & rContentType,
const rtl::OUString & rReferer,
const com::sun::star::uno::Reference<
com::sun::star::io::XInputStream > & inInputStream,
const DAVRequestEnvironment & rEnv )
throw ( DAVException ) = 0;
virtual void POST( const rtl::OUString & inPath,
const rtl::OUString & rContentType,
const rtl::OUString & rReferer,
const com::sun::star::uno::Reference<
com::sun::star::io::XInputStream > & inInputStream,
com::sun::star::uno::Reference<
com::sun::star::io::XOutputStream > & oOutputStream,
const DAVRequestEnvironment & rEnv )
throw ( DAVException ) = 0;
virtual void MKCOL( const ::rtl::OUString & inPath,
const DAVRequestEnvironment & rEnv )
throw( DAVException ) = 0;
virtual void COPY( const ::rtl::OUString & inSource,
const ::rtl::OUString & inDestination,
const DAVRequestEnvironment & rEnv,
sal_Bool inOverwrite = false )
throw( DAVException ) = 0;
virtual void MOVE( const ::rtl::OUString & inSource,
const ::rtl::OUString & inDestination,
const DAVRequestEnvironment & rEnv,
sal_Bool inOverwrite = false )
throw( DAVException ) = 0;
virtual void DESTROY( const ::rtl::OUString & inPath,
const DAVRequestEnvironment & rEnv )
throw( DAVException ) = 0;
// Note: Uncomment the following if locking support is required
/*
virtual void LOCK ( const Lock & inLock,
const DAVRequestEnvironment & rEnv )
throw( DAVException ) = 0;
virtual void UNLOCK ( const Lock & inLock,
const DAVRequestEnvironment & rEnv )
throw( DAVException ) = 0;
*/
protected:
rtl::Reference< DAVSessionFactory > m_xFactory;
DAVSession( rtl::Reference< DAVSessionFactory > const & rFactory )
: m_xFactory( rFactory ), m_nRefCount( 0 ) {}
virtual ~DAVSession() {}
private:
DAVSessionFactory::Map::iterator m_aContainerIt;
oslInterlockedCount m_nRefCount;
friend class DAVSessionFactory;
#if defined WNT && _MSC_VER < 1310
friend struct std::auto_ptr< DAVSession >;
// work around compiler bug...
#else // WNT
friend class std::auto_ptr< DAVSession >;
#endif // WNT
};
}; // namespace webdav_ucp
#endif // _DAVSESSION_HXX_
<|endoftext|> |
<commit_before>
#include "serialport.h"
#include <list>
#include "win/disphelper.h"
#include "win/stdafx.h"
#include "win/enumser.h"
#ifdef WIN32
#define MAX_BUFFER_SIZE 1000
// Declare type of pointer to CancelIoEx function
typedef BOOL (WINAPI *CancelIoExType)(HANDLE hFile, LPOVERLAPPED lpOverlapped);
std::list<int> g_closingHandles;
int bufferSize;
void ErrorCodeToString(const char* prefix, int errorCode, char *errorStr) {
switch(errorCode) {
case ERROR_FILE_NOT_FOUND:
sprintf(errorStr, "%s: File not found", prefix);
break;
case ERROR_INVALID_HANDLE:
sprintf(errorStr, "%s: Invalid handle", prefix);
break;
case ERROR_ACCESS_DENIED:
sprintf(errorStr, "%s: Access denied", prefix);
break;
case ERROR_OPERATION_ABORTED:
sprintf(errorStr, "%s: operation aborted", prefix);
break;
default:
sprintf(errorStr, "%s: Unknown error code %d", prefix, errorCode);
break;
}
}
void EIO_Open(uv_work_t* req) {
OpenBaton* data = static_cast<OpenBaton*>(req->data);
HANDLE file = CreateFile(
data->path,
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED,
NULL);
if (file == INVALID_HANDLE_VALUE) {
DWORD errorCode = GetLastError();
char temp[100];
sprintf(temp, "Opening %s", data->path);
ErrorCodeToString(temp, errorCode, data->errorString);
return;
}
bufferSize = data->bufferSize;
if(bufferSize > MAX_BUFFER_SIZE) {
bufferSize = MAX_BUFFER_SIZE;
}
DCB dcb = { 0 };
dcb.DCBlength = sizeof(DCB);
if(!BuildCommDCB("9600,n,8,1", &dcb)) {
ErrorCodeToString("BuildCommDCB", GetLastError(), data->errorString);
return;
}
dcb.fBinary = true;
dcb.BaudRate = data->baudRate;
dcb.ByteSize = data->dataBits;
switch(data->parity) {
case SERIALPORT_PARITY_NONE:
dcb.Parity = NOPARITY;
break;
case SERIALPORT_PARITY_MARK:
dcb.Parity = MARKPARITY;
break;
case SERIALPORT_PARITY_EVEN:
dcb.Parity = EVENPARITY;
break;
case SERIALPORT_PARITY_ODD:
dcb.Parity = ODDPARITY;
break;
case SERIALPORT_PARITY_SPACE:
dcb.Parity = SPACEPARITY;
break;
}
switch(data->stopBits) {
case SERIALPORT_STOPBITS_ONE:
dcb.StopBits = ONESTOPBIT;
break;
case SERIALPORT_STOPBITS_ONE_FIVE:
dcb.StopBits = ONE5STOPBITS;
break;
case SERIALPORT_STOPBITS_TWO:
dcb.StopBits = TWOSTOPBITS;
break;
}
if(!SetCommState(file, &dcb)) {
ErrorCodeToString("SetCommState", GetLastError(), data->errorString);
return;
}
// Set the com port read/write timeouts
DWORD serialBitsPerByte = 8/*std data bits*/ + 1/*start bit*/;
serialBitsPerByte += (data->parity == SERIALPORT_PARITY_NONE ) ? 0 : 1;
serialBitsPerByte += (data->stopBits == SERIALPORT_STOPBITS_ONE) ? 1 : 2;
DWORD msPerByte = (data->baudRate > 0) ?
((1000 * serialBitsPerByte + data->baudRate - 1) / data->baudRate) :
1;
if (msPerByte < 1) {
msPerByte = 1;
}
COMMTIMEOUTS commTimeouts = {0};
commTimeouts.ReadIntervalTimeout = msPerByte; // Minimize chance of concatenating of separate serial port packets on read
commTimeouts.ReadTotalTimeoutMultiplier = 0; // Do not allow big read timeout when big read buffer used
commTimeouts.ReadTotalTimeoutConstant = 1000; // Total read timeout (period of read loop)
commTimeouts.WriteTotalTimeoutConstant = 1000; // Const part of write timeout
commTimeouts.WriteTotalTimeoutMultiplier = msPerByte; // Variable part of write timeout (per byte)
if(!SetCommTimeouts(file, &commTimeouts)) {
ErrorCodeToString("SetCommTimeouts", GetLastError(), data->errorString);
return;
}
// Remove garbage data in RX/TX queues
PurgeComm(file, PURGE_RXCLEAR);
PurgeComm(file, PURGE_TXCLEAR);
data->result = (int)file;
}
struct WatchPortBaton {
public:
HANDLE fd;
DWORD bytesRead;
char buffer[MAX_BUFFER_SIZE];
char errorString[1000];
DWORD errorCode;
bool disconnected;
v8::Persistent<v8::Value> dataCallback;
v8::Persistent<v8::Value> errorCallback;
v8::Persistent<v8::Value> disconnectedCallback;
};
void EIO_WatchPort(uv_work_t* req) {
WatchPortBaton* data = static_cast<WatchPortBaton*>(req->data);
data->bytesRead = 0;
data->disconnected = false;
// Event used by GetOverlappedResult(..., TRUE) to wait for incoming data or timeout
// Event MUST be used if program has several simultaneous asynchronous operations
// on the same handle (i.e. ReadFile and WriteFile)
HANDLE hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
while(true) {
OVERLAPPED ov = {0};
ov.hEvent = hEvent;
// Start read operation - synchrounous or asynchronous
DWORD bytesReadSync = 0;
if(!ReadFile((HANDLE)data->fd, data->buffer, bufferSize, &bytesReadSync, &ov)) {
data->errorCode = GetLastError();
if(data->errorCode != ERROR_IO_PENDING) {
// Read operation error
if(data->errorCode == ERROR_OPERATION_ABORTED) {
data->disconnected = true;
}
else {
ErrorCodeToString("Reading from COM port (ReadFile)", data->errorCode, data->errorString);
}
break;
}
// Read operation is asynchronous and is pending
// We MUST wait for operation completion before deallocation of OVERLAPPED struct
// or read data buffer
// Wait for async read operation completion or timeout
DWORD bytesReadAsync = 0;
if(!GetOverlappedResult((HANDLE)data->fd, &ov, &bytesReadAsync, TRUE)) {
// Read operation error
data->errorCode = GetLastError();
if(data->errorCode == ERROR_OPERATION_ABORTED) {
data->disconnected = true;
}
else {
ErrorCodeToString("Reading from COM port (GetOverlappedResult)", data->errorCode, data->errorString);
}
break;
}
else {
// Read operation completed asynchronously
data->bytesRead = bytesReadAsync;
}
}
else {
// Read operation completed synchronously
data->bytesRead = bytesReadSync;
}
// Return data received if any
if(data->bytesRead > 0) {
break;
}
}
CloseHandle(hEvent);
}
bool IsClosingHandle(int fd) {
for(std::list<int>::iterator it=g_closingHandles.begin(); it!=g_closingHandles.end(); ++it) {
if(fd == *it) {
g_closingHandles.remove(fd);
return true;
}
}
return false;
}
void EIO_AfterWatchPort(uv_work_t* req) {
WatchPortBaton* data = static_cast<WatchPortBaton*>(req->data);
if(data->disconnected) {
v8::Handle<v8::Value> argv[1];
v8::Function::Cast(*data->disconnectedCallback)->Call(v8::Context::GetCurrent()->Global(), 0, argv);
goto cleanup;
}
if(data->bytesRead > 0) {
v8::Handle<v8::Value> argv[1];
argv[0] = node::Buffer::New(data->buffer, data->bytesRead)->handle_;
v8::Function::Cast(*data->dataCallback)->Call(v8::Context::GetCurrent()->Global(), 1, argv);
} else if(data->errorCode > 0) {
if(data->errorCode == ERROR_INVALID_HANDLE && IsClosingHandle((int)data->fd)) {
goto cleanup;
} else {
v8::Handle<v8::Value> argv[1];
argv[0] = v8::Exception::Error(v8::String::New(data->errorString));
v8::Function::Cast(*data->errorCallback)->Call(v8::Context::GetCurrent()->Global(), 1, argv);
Sleep(100); // prevent the errors from occurring too fast
}
}
AfterOpenSuccess((int)data->fd, data->dataCallback, data->disconnectedCallback, data->errorCallback);
cleanup:
data->dataCallback.Dispose();
data->errorCallback.Dispose();
delete data;
delete req;
}
void AfterOpenSuccess(int fd, v8::Handle<v8::Value> dataCallback, v8::Handle<v8::Value> disconnectedCallback, v8::Handle<v8::Value> errorCallback) {
WatchPortBaton* baton = new WatchPortBaton();
memset(baton, 0, sizeof(WatchPortBaton));
baton->fd = (HANDLE)fd;
baton->dataCallback = v8::Persistent<v8::Value>::New(dataCallback);
baton->errorCallback = v8::Persistent<v8::Value>::New(errorCallback);
baton->disconnectedCallback = v8::Persistent<v8::Value>::New(disconnectedCallback);
uv_work_t* req = new uv_work_t();
req->data = baton;
uv_queue_work(uv_default_loop(), req, EIO_WatchPort, (uv_after_work_cb)EIO_AfterWatchPort);
}
void EIO_Write(uv_work_t* req) {
QueuedWrite* queuedWrite = static_cast<QueuedWrite*>(req->data);
WriteBaton* data = static_cast<WriteBaton*>(queuedWrite->baton);
data->result = 0;
OVERLAPPED ov = {0};
// Event used by GetOverlappedResult(..., TRUE) to wait for outgoing data or timeout
// Event MUST be used if program has several simultaneous asynchronous operations
// on the same handle (i.e. ReadFile and WriteFile)
ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
// Start write operation - synchrounous or asynchronous
DWORD bytesWrittenSync = 0;
if(!WriteFile((HANDLE)data->fd, data->bufferData, data->bufferLength, &bytesWrittenSync, &ov)) {
DWORD lastError = GetLastError();
if(lastError != ERROR_IO_PENDING) {
// Write operation error
ErrorCodeToString("Writing to COM port (WriteFile)", lastError, data->errorString);
}
else {
// Write operation is asynchronous and is pending
// We MUST wait for operation completion before deallocation of OVERLAPPED struct
// or write data buffer
// Wait for async write operation completion or timeout
DWORD bytesWrittenAsync = 0;
if(!GetOverlappedResult((HANDLE)data->fd, &ov, &bytesWrittenAsync, TRUE)) {
// Write operation error
DWORD lastError = GetLastError();
ErrorCodeToString("Writing to COM port (GetOverlappedResult)", lastError, data->errorString);
}
else {
// Write operation completed asynchronously
data->result = bytesWrittenAsync;
}
}
}
else {
// Write operation completed synchronously
data->result = bytesWrittenSync;
}
CloseHandle(ov.hEvent);
}
void EIO_Close(uv_work_t* req) {
CloseBaton* data = static_cast<CloseBaton*>(req->data);
g_closingHandles.push_back(data->fd);
HMODULE hKernel32 = LoadLibrary("kernel32.dll");
// Look up function address
CancelIoExType pCancelIoEx = (CancelIoExType)GetProcAddress(hKernel32, "CancelIoEx");
// Do something with it
if (pCancelIoEx)
{
// Function exists so call it
// Cancel all pending IO Requests for the current device
pCancelIoEx((HANDLE)data->fd, NULL);
}
if(!CloseHandle((HANDLE)data->fd)) {
ErrorCodeToString("closing connection", GetLastError(), data->errorString);
return;
}
}
/*
* listComPorts.c -- list COM ports
*
* http://github.com/todbot/usbSearch/
*
* 2012, Tod E. Kurt, http://todbot.com/blog/
*
*
* Uses DispHealper : http://disphelper.sourceforge.net/
*
* Notable VIDs & PIDs combos:
* VID 0403 - FTDI
*
* VID 0403 / PID 6001 - Arduino Diecimila
*
*/
void EIO_List(uv_work_t* req) {
ListBaton* data = static_cast<ListBaton*>(req->data);
{
DISPATCH_OBJ(wmiSvc);
DISPATCH_OBJ(colDevices);
dhInitialize(TRUE);
dhToggleExceptions(TRUE);
dhGetObject(L"winmgmts:{impersonationLevel=impersonate}!\\\\.\\root\\cimv2", NULL, &wmiSvc);
dhGetValue(L"%o", &colDevices, wmiSvc, L".ExecQuery(%S)", L"Select * from Win32_PnPEntity");
int port_count = 0;
FOR_EACH(objDevice, colDevices, NULL) {
char* name = NULL;
char* pnpid = NULL;
char* manu = NULL;
char* match;
dhGetValue(L"%s", &name, objDevice, L".Name");
dhGetValue(L"%s", &pnpid, objDevice, L".PnPDeviceID");
if( (match = strstr( name, "(COM" )) != NULL ) { // look for "(COM23)"
// 'Manufacturuer' can be null, so only get it if we need it
dhGetValue(L"%s", &manu, objDevice, L".Manufacturer");
port_count++;
char* comname = strtok( match, "()");
ListResultItem* resultItem = new ListResultItem();
resultItem->comName = comname;
resultItem->manufacturer = manu;
resultItem->pnpId = pnpid;
data->results.push_back(resultItem);
dhFreeString(manu);
}
dhFreeString(name);
dhFreeString(pnpid);
} NEXT(objDevice);
SAFE_RELEASE(colDevices);
SAFE_RELEASE(wmiSvc);
dhUninitialize(TRUE);
}
std::vector<UINT> ports;
if (CEnumerateSerial::UsingQueryDosDevice(ports))
{
for (size_t i = 0; i < ports.size(); i++)
{
char comname[64] = { 0 };
sprintf(comname, "COM%u", ports[i]);
bool bFound = false;
for (std::list<ListResultItem*>::iterator ri = data->results.begin(); ri != data->results.end(); ++ri)
{
if (stricmp((*ri)->comName.c_str(), comname) == 0)
{
bFound = true;
break;
}
}
if (!bFound)
{
ListResultItem* resultItem = new ListResultItem();
resultItem->comName = comname;
resultItem->manufacturer = "";
resultItem->pnpId = "";
data->results.push_back(resultItem);
}
}
}
}
void EIO_Flush(uv_work_t* req) {
FlushBaton* data = static_cast<FlushBaton*>(req->data);
if(!FlushFileBuffers((HANDLE)data->fd)) {
ErrorCodeToString("flushing connection", GetLastError(), data->errorString);
return;
}
}
#endif
<commit_msg>Cast size_t to DWORD to avoid compiler warning.<commit_after>#include "serialport.h"
#include <list>
#include "win/disphelper.h"
#include "win/stdafx.h"
#include "win/enumser.h"
#ifdef WIN32
#define MAX_BUFFER_SIZE 1000
// Declare type of pointer to CancelIoEx function
typedef BOOL (WINAPI *CancelIoExType)(HANDLE hFile, LPOVERLAPPED lpOverlapped);
std::list<int> g_closingHandles;
int bufferSize;
void ErrorCodeToString(const char* prefix, int errorCode, char *errorStr) {
switch(errorCode) {
case ERROR_FILE_NOT_FOUND:
sprintf(errorStr, "%s: File not found", prefix);
break;
case ERROR_INVALID_HANDLE:
sprintf(errorStr, "%s: Invalid handle", prefix);
break;
case ERROR_ACCESS_DENIED:
sprintf(errorStr, "%s: Access denied", prefix);
break;
case ERROR_OPERATION_ABORTED:
sprintf(errorStr, "%s: operation aborted", prefix);
break;
default:
sprintf(errorStr, "%s: Unknown error code %d", prefix, errorCode);
break;
}
}
void EIO_Open(uv_work_t* req) {
OpenBaton* data = static_cast<OpenBaton*>(req->data);
HANDLE file = CreateFile(
data->path,
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED,
NULL);
if (file == INVALID_HANDLE_VALUE) {
DWORD errorCode = GetLastError();
char temp[100];
sprintf(temp, "Opening %s", data->path);
ErrorCodeToString(temp, errorCode, data->errorString);
return;
}
bufferSize = data->bufferSize;
if(bufferSize > MAX_BUFFER_SIZE) {
bufferSize = MAX_BUFFER_SIZE;
}
DCB dcb = { 0 };
dcb.DCBlength = sizeof(DCB);
if(!BuildCommDCB("9600,n,8,1", &dcb)) {
ErrorCodeToString("BuildCommDCB", GetLastError(), data->errorString);
return;
}
dcb.fBinary = true;
dcb.BaudRate = data->baudRate;
dcb.ByteSize = data->dataBits;
switch(data->parity) {
case SERIALPORT_PARITY_NONE:
dcb.Parity = NOPARITY;
break;
case SERIALPORT_PARITY_MARK:
dcb.Parity = MARKPARITY;
break;
case SERIALPORT_PARITY_EVEN:
dcb.Parity = EVENPARITY;
break;
case SERIALPORT_PARITY_ODD:
dcb.Parity = ODDPARITY;
break;
case SERIALPORT_PARITY_SPACE:
dcb.Parity = SPACEPARITY;
break;
}
switch(data->stopBits) {
case SERIALPORT_STOPBITS_ONE:
dcb.StopBits = ONESTOPBIT;
break;
case SERIALPORT_STOPBITS_ONE_FIVE:
dcb.StopBits = ONE5STOPBITS;
break;
case SERIALPORT_STOPBITS_TWO:
dcb.StopBits = TWOSTOPBITS;
break;
}
if(!SetCommState(file, &dcb)) {
ErrorCodeToString("SetCommState", GetLastError(), data->errorString);
return;
}
// Set the com port read/write timeouts
DWORD serialBitsPerByte = 8/*std data bits*/ + 1/*start bit*/;
serialBitsPerByte += (data->parity == SERIALPORT_PARITY_NONE ) ? 0 : 1;
serialBitsPerByte += (data->stopBits == SERIALPORT_STOPBITS_ONE) ? 1 : 2;
DWORD msPerByte = (data->baudRate > 0) ?
((1000 * serialBitsPerByte + data->baudRate - 1) / data->baudRate) :
1;
if (msPerByte < 1) {
msPerByte = 1;
}
COMMTIMEOUTS commTimeouts = {0};
commTimeouts.ReadIntervalTimeout = msPerByte; // Minimize chance of concatenating of separate serial port packets on read
commTimeouts.ReadTotalTimeoutMultiplier = 0; // Do not allow big read timeout when big read buffer used
commTimeouts.ReadTotalTimeoutConstant = 1000; // Total read timeout (period of read loop)
commTimeouts.WriteTotalTimeoutConstant = 1000; // Const part of write timeout
commTimeouts.WriteTotalTimeoutMultiplier = msPerByte; // Variable part of write timeout (per byte)
if(!SetCommTimeouts(file, &commTimeouts)) {
ErrorCodeToString("SetCommTimeouts", GetLastError(), data->errorString);
return;
}
// Remove garbage data in RX/TX queues
PurgeComm(file, PURGE_RXCLEAR);
PurgeComm(file, PURGE_TXCLEAR);
data->result = (int)file;
}
struct WatchPortBaton {
public:
HANDLE fd;
DWORD bytesRead;
char buffer[MAX_BUFFER_SIZE];
char errorString[1000];
DWORD errorCode;
bool disconnected;
v8::Persistent<v8::Value> dataCallback;
v8::Persistent<v8::Value> errorCallback;
v8::Persistent<v8::Value> disconnectedCallback;
};
void EIO_WatchPort(uv_work_t* req) {
WatchPortBaton* data = static_cast<WatchPortBaton*>(req->data);
data->bytesRead = 0;
data->disconnected = false;
// Event used by GetOverlappedResult(..., TRUE) to wait for incoming data or timeout
// Event MUST be used if program has several simultaneous asynchronous operations
// on the same handle (i.e. ReadFile and WriteFile)
HANDLE hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
while(true) {
OVERLAPPED ov = {0};
ov.hEvent = hEvent;
// Start read operation - synchrounous or asynchronous
DWORD bytesReadSync = 0;
if(!ReadFile((HANDLE)data->fd, data->buffer, bufferSize, &bytesReadSync, &ov)) {
data->errorCode = GetLastError();
if(data->errorCode != ERROR_IO_PENDING) {
// Read operation error
if(data->errorCode == ERROR_OPERATION_ABORTED) {
data->disconnected = true;
}
else {
ErrorCodeToString("Reading from COM port (ReadFile)", data->errorCode, data->errorString);
}
break;
}
// Read operation is asynchronous and is pending
// We MUST wait for operation completion before deallocation of OVERLAPPED struct
// or read data buffer
// Wait for async read operation completion or timeout
DWORD bytesReadAsync = 0;
if(!GetOverlappedResult((HANDLE)data->fd, &ov, &bytesReadAsync, TRUE)) {
// Read operation error
data->errorCode = GetLastError();
if(data->errorCode == ERROR_OPERATION_ABORTED) {
data->disconnected = true;
}
else {
ErrorCodeToString("Reading from COM port (GetOverlappedResult)", data->errorCode, data->errorString);
}
break;
}
else {
// Read operation completed asynchronously
data->bytesRead = bytesReadAsync;
}
}
else {
// Read operation completed synchronously
data->bytesRead = bytesReadSync;
}
// Return data received if any
if(data->bytesRead > 0) {
break;
}
}
CloseHandle(hEvent);
}
bool IsClosingHandle(int fd) {
for(std::list<int>::iterator it=g_closingHandles.begin(); it!=g_closingHandles.end(); ++it) {
if(fd == *it) {
g_closingHandles.remove(fd);
return true;
}
}
return false;
}
void EIO_AfterWatchPort(uv_work_t* req) {
WatchPortBaton* data = static_cast<WatchPortBaton*>(req->data);
if(data->disconnected) {
v8::Handle<v8::Value> argv[1];
v8::Function::Cast(*data->disconnectedCallback)->Call(v8::Context::GetCurrent()->Global(), 0, argv);
goto cleanup;
}
if(data->bytesRead > 0) {
v8::Handle<v8::Value> argv[1];
argv[0] = node::Buffer::New(data->buffer, data->bytesRead)->handle_;
v8::Function::Cast(*data->dataCallback)->Call(v8::Context::GetCurrent()->Global(), 1, argv);
} else if(data->errorCode > 0) {
if(data->errorCode == ERROR_INVALID_HANDLE && IsClosingHandle((int)data->fd)) {
goto cleanup;
} else {
v8::Handle<v8::Value> argv[1];
argv[0] = v8::Exception::Error(v8::String::New(data->errorString));
v8::Function::Cast(*data->errorCallback)->Call(v8::Context::GetCurrent()->Global(), 1, argv);
Sleep(100); // prevent the errors from occurring too fast
}
}
AfterOpenSuccess((int)data->fd, data->dataCallback, data->disconnectedCallback, data->errorCallback);
cleanup:
data->dataCallback.Dispose();
data->errorCallback.Dispose();
delete data;
delete req;
}
void AfterOpenSuccess(int fd, v8::Handle<v8::Value> dataCallback, v8::Handle<v8::Value> disconnectedCallback, v8::Handle<v8::Value> errorCallback) {
WatchPortBaton* baton = new WatchPortBaton();
memset(baton, 0, sizeof(WatchPortBaton));
baton->fd = (HANDLE)fd;
baton->dataCallback = v8::Persistent<v8::Value>::New(dataCallback);
baton->errorCallback = v8::Persistent<v8::Value>::New(errorCallback);
baton->disconnectedCallback = v8::Persistent<v8::Value>::New(disconnectedCallback);
uv_work_t* req = new uv_work_t();
req->data = baton;
uv_queue_work(uv_default_loop(), req, EIO_WatchPort, (uv_after_work_cb)EIO_AfterWatchPort);
}
void EIO_Write(uv_work_t* req) {
QueuedWrite* queuedWrite = static_cast<QueuedWrite*>(req->data);
WriteBaton* data = static_cast<WriteBaton*>(queuedWrite->baton);
data->result = 0;
OVERLAPPED ov = {0};
// Event used by GetOverlappedResult(..., TRUE) to wait for outgoing data or timeout
// Event MUST be used if program has several simultaneous asynchronous operations
// on the same handle (i.e. ReadFile and WriteFile)
ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
// Start write operation - synchrounous or asynchronous
DWORD bytesWrittenSync = 0;
if(!WriteFile((HANDLE)data->fd, data->bufferData, static_cast<DWORD>(data->bufferLength), &bytesWrittenSync, &ov)) {
DWORD lastError = GetLastError();
if(lastError != ERROR_IO_PENDING) {
// Write operation error
ErrorCodeToString("Writing to COM port (WriteFile)", lastError, data->errorString);
}
else {
// Write operation is asynchronous and is pending
// We MUST wait for operation completion before deallocation of OVERLAPPED struct
// or write data buffer
// Wait for async write operation completion or timeout
DWORD bytesWrittenAsync = 0;
if(!GetOverlappedResult((HANDLE)data->fd, &ov, &bytesWrittenAsync, TRUE)) {
// Write operation error
DWORD lastError = GetLastError();
ErrorCodeToString("Writing to COM port (GetOverlappedResult)", lastError, data->errorString);
}
else {
// Write operation completed asynchronously
data->result = bytesWrittenAsync;
}
}
}
else {
// Write operation completed synchronously
data->result = bytesWrittenSync;
}
CloseHandle(ov.hEvent);
}
void EIO_Close(uv_work_t* req) {
CloseBaton* data = static_cast<CloseBaton*>(req->data);
g_closingHandles.push_back(data->fd);
HMODULE hKernel32 = LoadLibrary("kernel32.dll");
// Look up function address
CancelIoExType pCancelIoEx = (CancelIoExType)GetProcAddress(hKernel32, "CancelIoEx");
// Do something with it
if (pCancelIoEx)
{
// Function exists so call it
// Cancel all pending IO Requests for the current device
pCancelIoEx((HANDLE)data->fd, NULL);
}
if(!CloseHandle((HANDLE)data->fd)) {
ErrorCodeToString("closing connection", GetLastError(), data->errorString);
return;
}
}
/*
* listComPorts.c -- list COM ports
*
* http://github.com/todbot/usbSearch/
*
* 2012, Tod E. Kurt, http://todbot.com/blog/
*
*
* Uses DispHealper : http://disphelper.sourceforge.net/
*
* Notable VIDs & PIDs combos:
* VID 0403 - FTDI
*
* VID 0403 / PID 6001 - Arduino Diecimila
*
*/
void EIO_List(uv_work_t* req) {
ListBaton* data = static_cast<ListBaton*>(req->data);
{
DISPATCH_OBJ(wmiSvc);
DISPATCH_OBJ(colDevices);
dhInitialize(TRUE);
dhToggleExceptions(TRUE);
dhGetObject(L"winmgmts:{impersonationLevel=impersonate}!\\\\.\\root\\cimv2", NULL, &wmiSvc);
dhGetValue(L"%o", &colDevices, wmiSvc, L".ExecQuery(%S)", L"Select * from Win32_PnPEntity");
int port_count = 0;
FOR_EACH(objDevice, colDevices, NULL) {
char* name = NULL;
char* pnpid = NULL;
char* manu = NULL;
char* match;
dhGetValue(L"%s", &name, objDevice, L".Name");
dhGetValue(L"%s", &pnpid, objDevice, L".PnPDeviceID");
if( (match = strstr( name, "(COM" )) != NULL ) { // look for "(COM23)"
// 'Manufacturuer' can be null, so only get it if we need it
dhGetValue(L"%s", &manu, objDevice, L".Manufacturer");
port_count++;
char* comname = strtok( match, "()");
ListResultItem* resultItem = new ListResultItem();
resultItem->comName = comname;
resultItem->manufacturer = manu;
resultItem->pnpId = pnpid;
data->results.push_back(resultItem);
dhFreeString(manu);
}
dhFreeString(name);
dhFreeString(pnpid);
} NEXT(objDevice);
SAFE_RELEASE(colDevices);
SAFE_RELEASE(wmiSvc);
dhUninitialize(TRUE);
}
std::vector<UINT> ports;
if (CEnumerateSerial::UsingQueryDosDevice(ports))
{
for (size_t i = 0; i < ports.size(); i++)
{
char comname[64] = { 0 };
sprintf(comname, "COM%u", ports[i]);
bool bFound = false;
for (std::list<ListResultItem*>::iterator ri = data->results.begin(); ri != data->results.end(); ++ri)
{
if (stricmp((*ri)->comName.c_str(), comname) == 0)
{
bFound = true;
break;
}
}
if (!bFound)
{
ListResultItem* resultItem = new ListResultItem();
resultItem->comName = comname;
resultItem->manufacturer = "";
resultItem->pnpId = "";
data->results.push_back(resultItem);
}
}
}
}
void EIO_Flush(uv_work_t* req) {
FlushBaton* data = static_cast<FlushBaton*>(req->data);
if(!FlushFileBuffers((HANDLE)data->fd)) {
ErrorCodeToString("flushing connection", GetLastError(), data->errorString);
return;
}
}
#endif
<|endoftext|> |
<commit_before>#include "lex.h"
#include "cAstXml.h"
cAstXml::cAstXml(std::string filename) : cVisitor()
{
output.open(filename, std::ofstream::out);
if (!output.is_open()) fatal_error("Unable to open " + filename);
output << "<?xml version=\"1.0\"?>\n";
time_t gm_time = time(NULL);
struct tm *gmt = gmtime(&gm_time);
output << "<Program>\n";
output << "<compiled time=\"" <<
gmt->tm_year+1900 << ":" << gmt->tm_mon+1 << ":" << gmt->tm_mday <<
" " <<
gmt->tm_hour << ":" << gmt->tm_min << ":" << gmt->tm_sec << "\" />\n";
}
cAstXml::~cAstXml()
{
if (output.is_open())
{
output << "</Program>\n";
output.close();
}
}
void cAstXml::VisitAllNodes(cAstNode *node) { node->Visit(this); }
void cAstXml::DefaultVisit(cAstNode *node, std::string name, std::string attr)
{
output << "<" + name + attr;
if (node->HasChildren())
{
output << ">";
VisitAllChildren(node);
}
if (node->HasChildren())
output << "</" + name + ">\n";
else
output << "/>";
}
void cAstXml::Visit(cAddressExpr *node)
{
DefaultVisit(node, "AddressExpr");
}
void cAstXml::Visit(cArrayRef *node)
{
DefaultVisit(node, "ArrayRef");
}
void cAstXml::Visit(cArrayType *node)
{
string attr("");
int size = node->Size() / node->ElementSize();
attr = " Size=\"" + std::to_string(size) + "\" ";
DefaultVisit(node, "ArrayType", attr);
}
void cAstXml::Visit(cAsmNode *node)
{
string attr("");
attr = " Op=\"" + node->GetOp1String() + "\" ";
if (node->UsesTwoArgs())
{
attr += "Op2=\"" + std::to_string(node->GetOp2()) + "\" ";
}
DefaultVisit(node, "Asm", attr);
}
void cAstXml::Visit(cAssignExpr *node)
{
DefaultVisit(node, "AssignExpr");
}
void cAstXml::Visit(cAstNode *node)
{
DefaultVisit(node, "AstNode");
}
void cAstXml::Visit(cBaseDeclNode *node)
{
string attr = " size=\"" + std::to_string(node->Size()) + "\" ";
DefaultVisit(node, "BaseDecl", attr);
}
void cAstXml::Visit(cBinaryExpr *node)
{
string attr = " op=\"" + node->OpToString() + "\" ";
DefaultVisit(node, "BinaryExpr", attr);
}
void cAstXml::Visit(cDecl *node)
{
DefaultVisit(node, "Decl");
}
void cAstXml::Visit(cDeclsList *node)
{
DefaultVisit(node, "DeclsList");
}
void cAstXml::Visit(cExpr *node)
{
DefaultVisit(node, "Expr");
}
void cAstXml::Visit(cExprStmt *node)
{
DefaultVisit(node, "ExprStmt");
}
void cAstXml::Visit(cForStmt *node)
{
DefaultVisit(node, "ForStmt");
}
void cAstXml::Visit(cFuncCall *node)
{
DefaultVisit(node, "FuncCall");
}
void cAstXml::Visit(cFuncDecl *node)
{
string attr = " localsize=\"" + std::to_string(node->GetSize()) + "\" ";
DefaultVisit(node, "FuncDecl", attr);
}
void cAstXml::Visit(cIfStmt *node)
{
DefaultVisit(node, "IfStmt");
}
void cAstXml::Visit(cIntExpr *node)
{
string attr = " value=\"" + std::to_string(node->ConstValue()) +"\" ";
DefaultVisit(node, "IntExpr", attr);
}
void cAstXml::Visit(cNopStmt *node)
{
DefaultVisit(node, "Nop");
}
void cAstXml::Visit(cParams *node)
{
DefaultVisit(node, "Params");
}
void cAstXml::Visit(cPlainVarRef *node)
{
DefaultVisit(node, "PlainVarRef");
}
void cAstXml::Visit(cPointerDeref *node)
{
DefaultVisit(node, "PoitnerDeref");
}
void cAstXml::Visit(cPointerType *node)
{
DefaultVisit(node, "PointerType");
}
void cAstXml::Visit(cPostfixExpr *node)
{
string attr = " op=\"" + node->OpToString() + "\" ";
DefaultVisit(node, "PostfixExpr", attr);
}
void cAstXml::Visit(cPragma *node)
{
string attr = " name=\"" + node->GetOp() + "\" ";
if (node->GetArg().length() > 0)
{
attr += " arg=\"" + EscapeBrackets(node->GetArg()) + "\" ";
}
DefaultVisit(node, "Pragma", attr);
}
void cAstXml::Visit(cPrefixExpr *node)
{
string attr = " op=\"" + node->OpToString() + "\" ";
DefaultVisit(node, "PrefixExpr", attr);
}
void cAstXml::Visit(cReturnStmt *node)
{
DefaultVisit(node, "Return");
}
void cAstXml::Visit(cShortCircuitExpr *node)
{
string attr = " op=\"" + node->OpToString() + "\" ";
DefaultVisit(node, "ShortCircuitExpr", attr);
}
void cAstXml::Visit(cSizeofExpr *node)
{
string attr = " value=\"" + std::to_string(node->ConstValue()) +"\" ";
DefaultVisit(node, "Sizeof");
}
void cAstXml::Visit(cStmt *node)
{
DefaultVisit(node, "Stmt");
}
void cAstXml::Visit(cStmtsList *node)
{
DefaultVisit(node, "StmtsList");
}
void cAstXml::Visit(cStringLit *node)
{
string attr = " value=\"" + node->GetString() + "\" ";
DefaultVisit(node, "StringLit", attr);
}
void cAstXml::Visit(cStructDeref *node)
{
DefaultVisit(node, "StructDeref");
}
void cAstXml::Visit(cStructRef *node)
{
DefaultVisit(node, "StructRef");
}
void cAstXml::Visit(cStructType *node)
{
DefaultVisit(node, "StructType");
}
void cAstXml::Visit(cSymbol *node)
{
string attr = " name=\"" + node->Name() + "\"";
attr += " seq=\"" + std::to_string(node->GetSeq()) + "\" ";
DefaultVisit(node, "Symbol", attr);
}
void cAstXml::Visit(cTypeDecl *node)
{
DefaultVisit(node, "TypeDecl");
}
void cAstXml::Visit(cTypedef *node)
{
DefaultVisit(node, "Typedef");
}
void cAstXml::Visit(cUnaryExpr *node)
{
string attr = " op=\"" + node->OpToString() + "\" ";
DefaultVisit(node, "UnaryExpr", attr);
}
void cAstXml::Visit(cVarDecl *node)
{
string attr = " offset=\"" + std::to_string(node->GetOffset()) + "\" ";
if (node->IsGlobal()) attr += " global=\"true\" ";
if (node->IsStatic()) attr += " static=\"true\" ";
DefaultVisit(node, "VarDecl", attr);
}
void cAstXml::Visit(cVarRef *node){
DefaultVisit(node, "VarRef");
}
void cAstXml::Visit(cWhileStmt *node){
DefaultVisit(node, "While");
}
std::string cAstXml::EscapeBrackets(std::string text)
{
std::string result;
for (auto it=text.begin(); it != text.end(); it++)
{
if ( (*it) == '<')
result += "<";
else if ( (*it) == '>')
result += ">";
else
result.push_back(*it);
}
return result;
}
<commit_msg>Added size to XML for structType<commit_after>#include "lex.h"
#include "cAstXml.h"
cAstXml::cAstXml(std::string filename) : cVisitor()
{
output.open(filename, std::ofstream::out);
if (!output.is_open()) fatal_error("Unable to open " + filename);
output << "<?xml version=\"1.0\"?>\n";
time_t gm_time = time(NULL);
struct tm *gmt = gmtime(&gm_time);
output << "<Program>\n";
output << "<compiled time=\"" <<
gmt->tm_year+1900 << ":" << gmt->tm_mon+1 << ":" << gmt->tm_mday <<
" " <<
gmt->tm_hour << ":" << gmt->tm_min << ":" << gmt->tm_sec << "\" />\n";
}
cAstXml::~cAstXml()
{
if (output.is_open())
{
output << "</Program>\n";
output.close();
}
}
void cAstXml::VisitAllNodes(cAstNode *node) { node->Visit(this); }
void cAstXml::DefaultVisit(cAstNode *node, std::string name, std::string attr)
{
output << "<" + name + attr;
if (node->HasChildren())
{
output << ">";
VisitAllChildren(node);
}
if (node->HasChildren())
output << "</" + name + ">\n";
else
output << "/>";
}
void cAstXml::Visit(cAddressExpr *node)
{
DefaultVisit(node, "AddressExpr");
}
void cAstXml::Visit(cArrayRef *node)
{
DefaultVisit(node, "ArrayRef");
}
void cAstXml::Visit(cArrayType *node)
{
string attr("");
int size = node->Size() / node->ElementSize();
attr = " Size=\"" + std::to_string(size) + "\" ";
DefaultVisit(node, "ArrayType", attr);
}
void cAstXml::Visit(cAsmNode *node)
{
string attr("");
attr = " Op=\"" + node->GetOp1String() + "\" ";
if (node->UsesTwoArgs())
{
attr += "Op2=\"" + std::to_string(node->GetOp2()) + "\" ";
}
DefaultVisit(node, "Asm", attr);
}
void cAstXml::Visit(cAssignExpr *node)
{
DefaultVisit(node, "AssignExpr");
}
void cAstXml::Visit(cAstNode *node)
{
DefaultVisit(node, "AstNode");
}
void cAstXml::Visit(cBaseDeclNode *node)
{
string attr = " size=\"" + std::to_string(node->Size()) + "\" ";
DefaultVisit(node, "BaseDecl", attr);
}
void cAstXml::Visit(cBinaryExpr *node)
{
string attr = " op=\"" + node->OpToString() + "\" ";
DefaultVisit(node, "BinaryExpr", attr);
}
void cAstXml::Visit(cDecl *node)
{
DefaultVisit(node, "Decl");
}
void cAstXml::Visit(cDeclsList *node)
{
DefaultVisit(node, "DeclsList");
}
void cAstXml::Visit(cExpr *node)
{
DefaultVisit(node, "Expr");
}
void cAstXml::Visit(cExprStmt *node)
{
DefaultVisit(node, "ExprStmt");
}
void cAstXml::Visit(cForStmt *node)
{
DefaultVisit(node, "ForStmt");
}
void cAstXml::Visit(cFuncCall *node)
{
DefaultVisit(node, "FuncCall");
}
void cAstXml::Visit(cFuncDecl *node)
{
string attr = " localsize=\"" + std::to_string(node->GetSize()) + "\" ";
DefaultVisit(node, "FuncDecl", attr);
}
void cAstXml::Visit(cIfStmt *node)
{
DefaultVisit(node, "IfStmt");
}
void cAstXml::Visit(cIntExpr *node)
{
string attr = " value=\"" + std::to_string(node->ConstValue()) +"\" ";
DefaultVisit(node, "IntExpr", attr);
}
void cAstXml::Visit(cNopStmt *node)
{
DefaultVisit(node, "Nop");
}
void cAstXml::Visit(cParams *node)
{
DefaultVisit(node, "Params");
}
void cAstXml::Visit(cPlainVarRef *node)
{
DefaultVisit(node, "PlainVarRef");
}
void cAstXml::Visit(cPointerDeref *node)
{
DefaultVisit(node, "PoitnerDeref");
}
void cAstXml::Visit(cPointerType *node)
{
DefaultVisit(node, "PointerType");
}
void cAstXml::Visit(cPostfixExpr *node)
{
string attr = " op=\"" + node->OpToString() + "\" ";
DefaultVisit(node, "PostfixExpr", attr);
}
void cAstXml::Visit(cPragma *node)
{
string attr = " name=\"" + node->GetOp() + "\" ";
if (node->GetArg().length() > 0)
{
attr += " arg=\"" + EscapeBrackets(node->GetArg()) + "\" ";
}
DefaultVisit(node, "Pragma", attr);
}
void cAstXml::Visit(cPrefixExpr *node)
{
string attr = " op=\"" + node->OpToString() + "\" ";
DefaultVisit(node, "PrefixExpr", attr);
}
void cAstXml::Visit(cReturnStmt *node)
{
DefaultVisit(node, "Return");
}
void cAstXml::Visit(cShortCircuitExpr *node)
{
string attr = " op=\"" + node->OpToString() + "\" ";
DefaultVisit(node, "ShortCircuitExpr", attr);
}
void cAstXml::Visit(cSizeofExpr *node)
{
string attr = " value=\"" + std::to_string(node->ConstValue()) +"\" ";
DefaultVisit(node, "Sizeof");
}
void cAstXml::Visit(cStmt *node)
{
DefaultVisit(node, "Stmt");
}
void cAstXml::Visit(cStmtsList *node)
{
DefaultVisit(node, "StmtsList");
}
void cAstXml::Visit(cStringLit *node)
{
string attr = " value=\"" + node->GetString() + "\" ";
DefaultVisit(node, "StringLit", attr);
}
void cAstXml::Visit(cStructDeref *node)
{
DefaultVisit(node, "StructDeref");
}
void cAstXml::Visit(cStructRef *node)
{
DefaultVisit(node, "StructRef");
}
void cAstXml::Visit(cStructType *node)
{
string attr = " size=\"" + std::to_string(node->Size()) + "\" ";
DefaultVisit(node, "StructType", attr);
}
void cAstXml::Visit(cSymbol *node)
{
string attr = " name=\"" + node->Name() + "\"";
attr += " seq=\"" + std::to_string(node->GetSeq()) + "\" ";
DefaultVisit(node, "Symbol", attr);
}
void cAstXml::Visit(cTypeDecl *node)
{
DefaultVisit(node, "TypeDecl");
}
void cAstXml::Visit(cTypedef *node)
{
DefaultVisit(node, "Typedef");
}
void cAstXml::Visit(cUnaryExpr *node)
{
string attr = " op=\"" + node->OpToString() + "\" ";
DefaultVisit(node, "UnaryExpr", attr);
}
void cAstXml::Visit(cVarDecl *node)
{
string attr = " offset=\"" + std::to_string(node->GetOffset()) + "\" ";
if (node->IsGlobal()) attr += " global=\"true\" ";
if (node->IsStatic()) attr += " static=\"true\" ";
DefaultVisit(node, "VarDecl", attr);
}
void cAstXml::Visit(cVarRef *node){
DefaultVisit(node, "VarRef");
}
void cAstXml::Visit(cWhileStmt *node){
DefaultVisit(node, "While");
}
std::string cAstXml::EscapeBrackets(std::string text)
{
std::string result;
for (auto it=text.begin(); it != text.end(); it++)
{
if ( (*it) == '<')
result += "<";
else if ( (*it) == '>')
result += ">";
else
result.push_back(*it);
}
return result;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <ctype.h>
#include <cmath>
#include <algorithm>
#include <boost/math/constants/constants.hpp>
#include "Expressio.hpp"
class Calculator
{
Expressio::Evaluator<double> evaluator;
public:
Calculator()
{
const double pi = boost::math::constants::pi<double>();
const double e = boost::math::constants::e<double>();
evaluator.addConstant("pi", pi);
evaluator.addConstant("e", e);
evaluator.addFunction("abs" , [](double x) { return std::abs(x); });
evaluator.addFunction("cbrt" , [](double x) { return std::cbrt(x); });
evaluator.addFunction("ceil" , [](double x) { return std::ceil(x); });
evaluator.addFunction("exp2" , [](double x) { return std::exp2(x); });
evaluator.addFunction("exp" , [](double x) { return std::exp(x); });
evaluator.addFunction("fact" , [](double x) { return std::tgamma(x); });
evaluator.addFunction("floor", [](double x) { return std::floor(x); });
evaluator.addFunction("log10", [](double x) { return std::log10(x); });
evaluator.addFunction("log2" , [](double x) { return std::log2(x); });
evaluator.addFunction("log" , [](double x) { return std::log(x); });
evaluator.addFunction("round", [](double x) { return std::round(x); });
evaluator.addFunction("sqrt" , [](double x) { return std::sqrt(x); });
evaluator.addFunction("trunc", [](double x) { return std::trunc(x); });
evaluator.addFunction("cos" , [=](double x) { return std::cos(x * pi / 180); });
evaluator.addFunction("sin" , [=](double x) { return std::sin(x * pi / 180); });
evaluator.addFunction("acos" , [=](double x) { return std::acos(x) * 180 / pi; });
evaluator.addFunction("asin" , [=](double x) { return std::asin(x) * 180 / pi; });
auto tan = [=](double x)
{
if (std::fmod(x - 90, 180) == 0) // undefined for ±90° + 180°n, n ∈ ℤ
throw std::invalid_argument("Math error: Invalid angle");
if (std::fmod(x, 180) == 0) // zero for for 180°n, n ∈ ℤ (make it explicit
return 0.0; // to fix rounding issues).
return std::tan(x * pi / 180);
};
evaluator.addFunction("tan" , tan);
evaluator.addFunction("cot" , [=](double x) { return tan(90 - x); });
evaluator.addFunction("atan" , [=](double x) { return std::atan(x) * 180 / pi; });
evaluator.addFunction("acot" , [=](double x) { return 90 - std::atan(x) * 180 / pi; });
evaluator.addFunction("acosh", [](double x) { return std::acosh(x); });
evaluator.addFunction("asinh", [](double x) { return std::asinh(x); });
evaluator.addFunction("atanh", [](double x) { return std::atanh(x); });
evaluator.addFunction("cosh" , [](double x) { return std::cosh(x); });
evaluator.addFunction("sinh" , [](double x) { return std::sinh(x); });
evaluator.addFunction("tanh" , [](double x) { return std::tanh(x); });
evaluator.addFunction("hypot", [](double x, double y) { return std::hypot(x, y); });
evaluator.addFunction("max" , [](double x, double y) { return std::fmax(x, y); });
evaluator.addFunction("min" , [](double x, double y) { return std::fmin(x, y); });
evaluator.addFunction("mod" , [](double x, double y) { return std::fmod(x, y); });
}
std::string calculate(const std::string& expression)
{
std::stringstream result;
try
{
result << evaluator.evaluate(expression);
}
catch (const std::exception& e)
{
result << e.what();
}
return result.str();
}
};
int main(int argc, char* argv[])
{
Calculator c;
if (argc > 1)
{
std::cout << c.calculate(argv[1]) << '\n';
return 0;
}
for (std::string expr; getline(std::cin, expr) && expr != "exit"; )
std::cout << c.calculate(expr) << '\n';
}
<commit_msg>clean up a bit<commit_after>#include <iostream>
#include <ctype.h>
#include <cmath>
#include <algorithm>
#include <boost/math/constants/constants.hpp>
#include "Expressio.hpp"
class Calculator
{
Expressio::Evaluator<double> evaluator;
public:
Calculator()
{
const double pi = boost::math::constants::pi<double>();
const double e = boost::math::constants::e<double>();
evaluator.addConstant("pi", pi);
evaluator.addConstant("e", e);
evaluator.addFunction("abs" , [](double x) { return std::abs(x); });
evaluator.addFunction("cbrt" , [](double x) { return std::cbrt(x); });
evaluator.addFunction("ceil" , [](double x) { return std::ceil(x); });
evaluator.addFunction("exp2" , [](double x) { return std::exp2(x); });
evaluator.addFunction("exp" , [](double x) { return std::exp(x); });
evaluator.addFunction("fact" , [](double x) { return std::tgamma(x); });
evaluator.addFunction("floor", [](double x) { return std::floor(x); });
evaluator.addFunction("log10", [](double x) { return std::log10(x); });
evaluator.addFunction("log2" , [](double x) { return std::log2(x); });
evaluator.addFunction("log" , [](double x) { return std::log(x); });
evaluator.addFunction("round", [](double x) { return std::round(x); });
evaluator.addFunction("sqrt" , [](double x) { return std::sqrt(x); });
evaluator.addFunction("trunc", [](double x) { return std::trunc(x); });
evaluator.addFunction("cos" , [=](double x) { return std::cos(x * pi / 180); });
evaluator.addFunction("sin" , [=](double x) { return std::sin(x * pi / 180); });
evaluator.addFunction("acos" , [=](double x) { return std::acos(x) * 180 / pi; });
evaluator.addFunction("asin" , [=](double x) { return std::asin(x) * 180 / pi; });
auto tan = [=](double x)
{
if (std::fmod(x - 90, 180) == 0) // undefined for ±90° + 180°n, n ∈ ℤ
throw std::invalid_argument("Math error: Invalid angle");
if (std::fmod(x, 180) == 0) // zero for for 180°n, n ∈ ℤ (make it explicit to fix rounding issues)
return 0.0;
return std::tan(x * pi / 180);
};
evaluator.addFunction("tan" , tan );
evaluator.addFunction("cot" , [=](double x) { return tan(90 - x); });
evaluator.addFunction("atan" , [=](double x) { return std::atan(x) * 180 / pi; });
evaluator.addFunction("acot" , [=](double x) { return 90 - std::atan(x) * 180 / pi; });
evaluator.addFunction("acosh", [](double x) { return std::acosh(x); });
evaluator.addFunction("asinh", [](double x) { return std::asinh(x); });
evaluator.addFunction("atanh", [](double x) { return std::atanh(x); });
evaluator.addFunction("cosh" , [](double x) { return std::cosh(x); });
evaluator.addFunction("sinh" , [](double x) { return std::sinh(x); });
evaluator.addFunction("tanh" , [](double x) { return std::tanh(x); });
evaluator.addFunction("hypot", [](double x, double y) { return std::hypot(x, y); });
evaluator.addFunction("max" , [](double x, double y) { return std::fmax(x, y); });
evaluator.addFunction("min" , [](double x, double y) { return std::fmin(x, y); });
evaluator.addFunction("mod" , [](double x, double y) { return std::fmod(x, y); });
}
std::string calculate(const std::string& expression)
{
std::stringstream result;
try
{
result << evaluator.evaluate(expression);
}
catch (const std::exception& e)
{
result << e.what();
}
return result.str();
}
};
int main(int argc, char* argv[])
{
Calculator c;
if (argc > 1)
{
std::cout << c.calculate(argv[1]) << '\n';
return 0;
}
for (std::string expr; getline(std::cin, expr) && expr != "exit"; )
std::cout << c.calculate(expr) << '\n';
}
<|endoftext|> |
<commit_before>#include <vtkVersion.h>
#include <vtkSmartPointer.h>
#include <vtkCubeSource.h>
#include <vtkPolyData.h>
#include <vtkPoints.h>
#include <vtkGlyph3D.h>
#include <vtkCellArray.h>
#include <vtkPolyDataMapper.h>
#include <vtkActor.h>
#include <vtkRenderWindow.h>
#include <vtkRenderer.h>
#include <vtkRenderWindowInteractor.h>
int main(int, char *[])
{
vtkSmartPointer<vtkPoints> points =
vtkSmartPointer<vtkPoints>::New();
points->InsertNextPoint(0,0,0);
points->InsertNextPoint(1,1,1);
points->InsertNextPoint(2,2,2);
vtkSmartPointer<vtkPolyData> polydata =
vtkSmartPointer<vtkPolyData>::New();
polydata->SetPoints(points);
vtkSmartPointer<vtkPolyData> glyph =
vtkSmartPointer<vtkPolyData>::New();
// Create anything you want here, we will use a cube for the demo.
vtkSmartPointer<vtkCubeSource> cubeSource =
vtkSmartPointer<vtkCubeSource>::New();
vtkSmartPointer<vtkGlyph3D> glyph3D =
vtkSmartPointer<vtkGlyph3D>::New();
#if VTK_MAJOR_VERSION <= 5
glyph3D->SetSource(cubeSource->GetOutput());
glyph3D->SetInput(polydata);
#else
glyph3D->SetSourceConnection(cubeSource->GetOutputPort());
glyph3D->SetInputData(polydata);
#endif
glyph3D->Update();
// Visualize
vtkSmartPointer<vtkPolyDataMapper> mapper =
vtkSmartPointer<vtkPolyDataMapper>::New();
mapper->SetInputConnection(glyph3D->GetOutputPort());
vtkSmartPointer<vtkActor> actor =
vtkSmartPointer<vtkActor>::New();
actor->SetMapper(mapper);
vtkSmartPointer<vtkRenderer> renderer =
vtkSmartPointer<vtkRenderer>::New();
vtkSmartPointer<vtkRenderWindow> renderWindow =
vtkSmartPointer<vtkRenderWindow>::New();
renderWindow->AddRenderer(renderer);
vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor =
vtkSmartPointer<vtkRenderWindowInteractor>::New();
renderWindowInteractor->SetRenderWindow(renderWindow);
renderer->AddActor(actor);
renderer->SetBackground(.3, .6, .3); // Background color green
renderWindow->Render();
renderWindowInteractor->Start();
return EXIT_SUCCESS;
}
<commit_msg>ENH: Remove unused variable from vtkGlyph3D.cxx.<commit_after>#include <vtkVersion.h>
#include <vtkSmartPointer.h>
#include <vtkCubeSource.h>
#include <vtkPolyData.h>
#include <vtkPoints.h>
#include <vtkGlyph3D.h>
#include <vtkCellArray.h>
#include <vtkPolyDataMapper.h>
#include <vtkActor.h>
#include <vtkRenderWindow.h>
#include <vtkRenderer.h>
#include <vtkRenderWindowInteractor.h>
int main(int, char *[])
{
vtkSmartPointer<vtkPoints> points =
vtkSmartPointer<vtkPoints>::New();
points->InsertNextPoint(0,0,0);
points->InsertNextPoint(1,1,1);
points->InsertNextPoint(2,2,2);
vtkSmartPointer<vtkPolyData> polydata =
vtkSmartPointer<vtkPolyData>::New();
polydata->SetPoints(points);
// Create anything you want here, we will use a cube for the demo.
vtkSmartPointer<vtkCubeSource> cubeSource =
vtkSmartPointer<vtkCubeSource>::New();
vtkSmartPointer<vtkGlyph3D> glyph3D =
vtkSmartPointer<vtkGlyph3D>::New();
#if VTK_MAJOR_VERSION <= 5
glyph3D->SetSource(cubeSource->GetOutput());
glyph3D->SetInput(polydata);
#else
glyph3D->SetSourceConnection(cubeSource->GetOutputPort());
glyph3D->SetInputData(polydata);
#endif
glyph3D->Update();
// Visualize
vtkSmartPointer<vtkPolyDataMapper> mapper =
vtkSmartPointer<vtkPolyDataMapper>::New();
mapper->SetInputConnection(glyph3D->GetOutputPort());
vtkSmartPointer<vtkActor> actor =
vtkSmartPointer<vtkActor>::New();
actor->SetMapper(mapper);
vtkSmartPointer<vtkRenderer> renderer =
vtkSmartPointer<vtkRenderer>::New();
vtkSmartPointer<vtkRenderWindow> renderWindow =
vtkSmartPointer<vtkRenderWindow>::New();
renderWindow->AddRenderer(renderer);
vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor =
vtkSmartPointer<vtkRenderWindowInteractor>::New();
renderWindowInteractor->SetRenderWindow(renderWindow);
renderer->AddActor(actor);
renderer->SetBackground(.3, .6, .3); // Background color green
renderWindow->Render();
renderWindowInteractor->Start();
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include <Riostream.h>
#include <TChain.h>
#include <TFile.h>
#include <TGraph.h>
#include <TH1F.h>
#include <TKey.h>
#include <TList.h>
#include <TMath.h>
#include <TProfile.h>
#include <TSystem.h>
#include <AliAODEvent.h>
#include <AliAODHandler.h>
#include <AliAODInputHandler.h>
#include <AliAODMCHeader.h>
#include <AliAODMCParticle.h>
#include <AliAODConversionPhoton.h>
#include <AliAODVertex.h>
#include <AliAnalysisManager.h>
#include <AliLog.h>
#include "AliConversionAodSkimTask.h"
#include "TObjectTable.h"
using namespace std;
ClassImp(AliConversionAodSkimTask)
AliConversionAodSkimTask::AliConversionAodSkimTask(const char* name) :
AliAodSkimTask(name), fConvMinPt(-1), fConvMinEta(-999.), fConvMaxEta(999.), fConvMinPhi(999.), fConvMaxPhi(999.),fDoBothConvPtAndAcc(0),
fDoQA(0),fHconvPtBeforeCuts(0), fHconvPtAfterCuts(0), fHconvAccBeforeCuts(0), fHconvAccAfterCuts(0)
{
if (name) {
DefineInput(0, TChain::Class());
DefineOutput(1, TList::Class());
}
}
AliConversionAodSkimTask::~AliConversionAodSkimTask()
{
if (fOutputList) {
delete fOutputList;
}
delete fHevs;
delete fHclus;
delete fHtrack;
delete fHconvPtBeforeCuts;
delete fHconvPtAfterCuts;
delete fHconvAccBeforeCuts;
delete fHconvAccAfterCuts;
}
void AliConversionAodSkimTask::UserCreateOutputObjects()
{
AliAnalysisManager *man = AliAnalysisManager::GetAnalysisManager();
AliAODHandler *oh = (AliAODHandler*)man->GetOutputEventHandler();
if (oh) {
TFile *fout = oh->GetTree()->GetCurrentFile();
fout->SetCompressionLevel(2);
}
// Before running skim, check if the V0Reader is running
TIter next(man->GetTasks());
TObject *obj;
while ((obj = next()))
{
if (strcmp(obj->ClassName(), "AliV0ReaderV1") == 0)
{
AliFatal("Skim task is running but detected V0Reader running in addition. This will cause problems due to relabelling already done now by the V0Reader!");
}
}
// check if convcuts were requested but no gammabranch given
if ((fConvMinPt > 0) || (fConvMinEta != -999) || (fConvMaxEta != 999) || (fConvMinPhi != -999) || (fConvMaxPhi != 999)){
if(!fGammaBr || !fGammaBr.CompareTo("")){
AliFatal(Form("%s: Conversion cuts were requested but no fGammaBr was given", GetName()));
return;
}
}
fOutputList = new TList;
fOutputList->SetOwner();
fHevs = new TH1F("hEvs","",2,-0.5,1.5);
fOutputList->Add(fHevs);
fHclus = new TH1F("hClus",";E (GeV)",200,0,100);
fOutputList->Add(fHclus);
fHtrack = new TH1F("hTrack",";p_{T} (GeV/c)",200,0,100);
fOutputList->Add(fHtrack);
if(fDoQA){
fHconvPtBeforeCuts = new TH1F("fHconvPtBeforeCuts",";p_{T} (GeV/c)",200,0,100);
fOutputList->Add(fHconvPtBeforeCuts);
fHconvPtAfterCuts = new TH1F("fHconvPtAfterCuts",";p_{T} (GeV/c)",200,0,100);
fOutputList->Add(fHconvPtAfterCuts);
fHconvAccBeforeCuts = new TH2F("fHconvAccBeforeCuts",";#eta; #phi",100,-0.9,0.9,100,0.,2*TMath::Pi());
fOutputList->Add(fHconvAccBeforeCuts);
fHconvAccAfterCuts = new TH2F("fHconvAccAfterCuts",";#eta; #phi",100,-0.9,0.9,100,0.,2*TMath::Pi());
fOutputList->Add(fHconvAccAfterCuts);
}
PostData(1, fOutputList);
}
Bool_t AliConversionAodSkimTask::SelectEvent()
{
// Accept event only if an EMCal-cluster with a minimum energy of fClusMinE has been found in the event
Bool_t storeE = kFALSE;
if (fClusMinE>0) {
TClonesArray *cls = fAOD->GetCaloClusters();
for (Int_t i=0; i<cls->GetEntriesFast(); ++i) {
AliAODCaloCluster *clus = static_cast<AliAODCaloCluster*>(cls->At(i));
if (!clus->IsEMCAL())
continue;
Double_t e = clus->E();
fHclus->Fill(e);
if (e>fClusMinE) {
storeE = kTRUE;
}
}
} else {
storeE = kTRUE;
}
// Accept event only if an track with a minimum pT of fTrackMinPt has been found in the event
Bool_t storePt = kFALSE;
if (fTrackMinPt > 0 ){
TClonesArray *tracks = fAOD->GetTracks();
for (Int_t i=0;i<tracks->GetEntries();++i) {
AliAODTrack *t = static_cast<AliAODTrack*>(tracks->At(i));
Double_t pt = t->Pt();
fHtrack->Fill(pt);
if (pt>fTrackMinPt) {
storePt = kTRUE;
}
if(fTrackMaxPt > 0 && fTrackMaxPt < pt){
storePt = kFALSE;
}
}
} else {
storePt = kTRUE;
}
// Accept event only if a conversion with a minimum pT of fConvMinPt has been found in the event
Bool_t storeConvPt = kFALSE;
Bool_t storeConvAcc = kFALSE;
if ((fConvMinPt > 0) || (fConvMinEta != -999) || (fConvMaxEta != 999) || (fConvMinPhi != -999) || (fConvMaxPhi != 999)){
// This is only done if any ConvPt or ConvAcceptance cut was given by user
TClonesArray *convgammas = dynamic_cast<TClonesArray*>(fAOD->FindListObject(fGammaBr));
if(convgammas){
for(Int_t i=0;i<convgammas->GetEntriesFast();i++){
AliAODConversionPhoton* g =dynamic_cast<AliAODConversionPhoton*>(convgammas->At(i));
if(g){
Double_t pt = g->Pt();
Double_t eta = g->Eta();
Double_t phi = g->Phi();
if(fDoQA){
fHconvPtBeforeCuts->Fill(pt);
fHconvAccBeforeCuts->Fill(eta,phi);
}
if(fConvMinPt > 0){
if (pt>fConvMinPt){ // pt cut
storeConvPt = kTRUE;
}
} else{
storeConvPt = kTRUE;
}
if( (eta>fConvMinEta) && (eta<fConvMaxEta) && (phi>fConvMinPhi) && (phi>fConvMaxPhi)){ // will always be true if no cut was set
storeConvAcc = kTRUE;
}
}
}
}
} else { // neither pt cuts nor acceptance cuts were set
storeConvPt = kTRUE;
storeConvAcc = kTRUE;
}
Bool_t store = kFALSE;
if (fDoBothMinTrackAndClus && fClusMinE>0 && fTrackMinPt > 0){
// request that both conditions are full-filled for propagating the event
store = (storeE && storePt);
} else if (!fDoBothMinTrackAndClus && fClusMinE>0 && fTrackMinPt > 0){
// request that at least one of the conditions is fullfilled
store = (storeE || storePt);
} else if (fDoBothConvPtAndAcc && (fConvMinPt >0) && (fConvMinEta!=-999 || fConvMaxEta!=999 || fConvMinPhi!=-999 || fConvMaxPhi!=999)){
store = (storeConvPt && storeConvAcc);
} else if (!fDoBothConvPtAndAcc && (fConvMinPt >0) && (fConvMinEta!=-999 || fConvMaxEta!=999 || fConvMinPhi!=-999 || fConvMaxPhi!=999)){
store = (storeConvPt || storeConvAcc);
} else if ( fClusMinE>0 ){
store = storeE;
} else if ( fTrackMinPt>0 ){
store = storePt;
} else if ( fConvMinPt>0 ){
store = storeConvPt;
} else if (fConvMinEta!=-999 || fConvMaxEta!=999 || fConvMinPhi!=-999 || fConvMaxPhi!=999){
store = storeConvAcc;
} else {
store = kTRUE;
}
if(fDoQA){
TClonesArray *convgammas = dynamic_cast<TClonesArray*>(fAOD->FindListObject(fGammaBr));
if(convgammas){
for(Int_t i=0;i<convgammas->GetEntriesFast();i++){
AliAODConversionPhoton* g =dynamic_cast<AliAODConversionPhoton*>(convgammas->At(i));
if(g){
Double_t pt = g->Pt();
Double_t eta = g->Eta();
Double_t phi = g->Phi();
fHconvPtAfterCuts->Fill(pt);
fHconvAccAfterCuts->Fill(eta,phi);
}
}
}
}
return store;
}
Bool_t AliConversionAodSkimTask::UserNotify()
{
TTree *tree = AliAnalysisManager::GetAnalysisManager()->GetTree();
if (!tree) {
AliError(Form("%s: No current tree!",GetName()));
return kFALSE;
}
Float_t xsection = 0;
Float_t trials = 0;
Int_t pthardbin = 0;
TFile *curfile = tree->GetCurrentFile();
if (!curfile) {
AliError(Form("%s: No current file!",GetName()));
return kFALSE;
}
TChain *chain = dynamic_cast<TChain*>(tree);
if (chain) tree = chain->GetTree();
Int_t nevents = tree->GetEntriesFast();
Int_t slevel = gErrorIgnoreLevel;
gErrorIgnoreLevel = kFatal;
Bool_t res = PythiaInfoFromFile(curfile->GetName(), xsection, trials, pthardbin);
gErrorIgnoreLevel=slevel;
if (res) {
cout << "AliConversionAodSkimTask " << GetName() << " found xsec info: " << xsection << " " << trials << " " << pthardbin << " " << nevents << endl;
fPyxsec = xsection;
fPytrials = trials;
fPypthardbin = pthardbin;
}
return res;
}
void AliConversionAodSkimTask::Terminate(Option_t *)
{
AliAnalysisManager *man = AliAnalysisManager::GetAnalysisManager();
if (man->GetAnalysisType()!=0)
return;
if (fHevs==0)
return;
Int_t norm = fHevs->GetEntries();
if (norm<1)
norm=1;
cout << "AliConversionAodSkimTask " << GetName() << " terminated with accepted fraction of events: " << fHevs->GetBinContent(2)/norm
<< " (" << fHevs->GetBinContent(2) << "/" << fHevs->GetEntries() << ")" << endl;
}
const char *AliConversionAodSkimTask::Str() const
{
return Form("mine%.2f_%dycut%.2f_%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d",
fClusMinE,
fCutMC,
fYCutMC,
fDoCopyHeader,
fDoCopyVZERO,
fDoCopyTZERO,
fDoCopyVertices,
fDoCopyTOF,
fDoCopyTracklets,
fDoCopyTracks,
fDoCopyTrigger,
fDoCopyPTrigger,
fDoCopyCells,
fDoCopyPCells,
fDoCopyClusters,
fDoCopyDiMuons,
fDoCopyTrdTracks,
fDoCopyV0s,
fDoCopyCascades,
fDoCopyZDC,
fDoCopyConv,
fDoCopyMC,
fDoCopyMCHeader);
}
<commit_msg>PWGGA/GammaConv: dummy commit to check broken pull request<commit_after>#include <Riostream.h>
#include <TChain.h>
#include <TFile.h>
#include <TGraph.h>
#include <TH1F.h>
#include <TKey.h>
#include <TList.h>
#include <TMath.h>
#include <TProfile.h>
#include <TSystem.h>
#include <AliAODEvent.h>
#include <AliAODHandler.h>
#include <AliAODInputHandler.h>
#include <AliAODMCHeader.h>
#include <AliAODMCParticle.h>
#include <AliAODConversionPhoton.h>
#include <AliAODVertex.h>
#include <AliAnalysisManager.h>
#include <AliLog.h>
#include "AliConversionAodSkimTask.h"
#include "TObjectTable.h"
using namespace std;
ClassImp(AliConversionAodSkimTask)
AliConversionAodSkimTask::AliConversionAodSkimTask(const char* name) :
AliAodSkimTask(name), fConvMinPt(-1), fConvMinEta(-999.), fConvMaxEta(999.), fConvMinPhi(999.), fConvMaxPhi(999.),fDoBothConvPtAndAcc(0),
fDoQA(0),fHconvPtBeforeCuts(0), fHconvPtAfterCuts(0), fHconvAccBeforeCuts(0), fHconvAccAfterCuts(0)
{
if (name) {
DefineInput(0, TChain::Class());
DefineOutput(1, TList::Class());
}
}
AliConversionAodSkimTask::~AliConversionAodSkimTask()
{
if (fOutputList) {
delete fOutputList;
}
delete fHevs;
delete fHclus;
delete fHtrack;
delete fHconvPtBeforeCuts;
delete fHconvPtAfterCuts;
delete fHconvAccBeforeCuts;
delete fHconvAccAfterCuts;
}
void AliConversionAodSkimTask::UserCreateOutputObjects()
{
AliAnalysisManager *man = AliAnalysisManager::GetAnalysisManager();
AliAODHandler *oh = (AliAODHandler*)man->GetOutputEventHandler();
if (oh) {
TFile *fout = oh->GetTree()->GetCurrentFile();
fout->SetCompressionLevel(2);
}
// Before running skim, check if the V0Reader is running
TIter next(man->GetTasks());
TObject *obj;
while ((obj = next()))
{
if (strcmp(obj->ClassName(), "AliV0ReaderV1") == 0)
{
AliFatal("Skim task is running but detected V0Reader running in addition! This will cause problems due to relabelling already done now by the V0Reader!");
}
}
// check if convcuts were requested but no gammabranch given
if ((fConvMinPt > 0) || (fConvMinEta != -999) || (fConvMaxEta != 999) || (fConvMinPhi != -999) || (fConvMaxPhi != 999)){
if(!fGammaBr || !fGammaBr.CompareTo("")){
AliFatal(Form("%s: Conversion cuts were requested but no fGammaBr was given", GetName()));
return;
}
}
fOutputList = new TList;
fOutputList->SetOwner();
fHevs = new TH1F("hEvs","",2,-0.5,1.5);
fOutputList->Add(fHevs);
fHclus = new TH1F("hClus",";E (GeV)",200,0,100);
fOutputList->Add(fHclus);
fHtrack = new TH1F("hTrack",";p_{T} (GeV/c)",200,0,100);
fOutputList->Add(fHtrack);
if(fDoQA){
fHconvPtBeforeCuts = new TH1F("fHconvPtBeforeCuts",";p_{T} (GeV/c)",200,0,100);
fOutputList->Add(fHconvPtBeforeCuts);
fHconvPtAfterCuts = new TH1F("fHconvPtAfterCuts",";p_{T} (GeV/c)",200,0,100);
fOutputList->Add(fHconvPtAfterCuts);
fHconvAccBeforeCuts = new TH2F("fHconvAccBeforeCuts",";#eta; #phi",100,-0.9,0.9,100,0.,2*TMath::Pi());
fOutputList->Add(fHconvAccBeforeCuts);
fHconvAccAfterCuts = new TH2F("fHconvAccAfterCuts",";#eta; #phi",100,-0.9,0.9,100,0.,2*TMath::Pi());
fOutputList->Add(fHconvAccAfterCuts);
}
PostData(1, fOutputList);
}
Bool_t AliConversionAodSkimTask::SelectEvent()
{
// Accept event only if an EMCal-cluster with a minimum energy of fClusMinE has been found in the event
Bool_t storeE = kFALSE;
if (fClusMinE>0) {
TClonesArray *cls = fAOD->GetCaloClusters();
for (Int_t i=0; i<cls->GetEntriesFast(); ++i) {
AliAODCaloCluster *clus = static_cast<AliAODCaloCluster*>(cls->At(i));
if (!clus->IsEMCAL())
continue;
Double_t e = clus->E();
fHclus->Fill(e);
if (e>fClusMinE) {
storeE = kTRUE;
}
}
} else {
storeE = kTRUE;
}
// Accept event only if an track with a minimum pT of fTrackMinPt has been found in the event
Bool_t storePt = kFALSE;
if (fTrackMinPt > 0 ){
TClonesArray *tracks = fAOD->GetTracks();
for (Int_t i=0;i<tracks->GetEntries();++i) {
AliAODTrack *t = static_cast<AliAODTrack*>(tracks->At(i));
Double_t pt = t->Pt();
fHtrack->Fill(pt);
if (pt>fTrackMinPt) {
storePt = kTRUE;
}
if(fTrackMaxPt > 0 && fTrackMaxPt < pt){
storePt = kFALSE;
}
}
} else {
storePt = kTRUE;
}
// Accept event only if a conversion with a minimum pT of fConvMinPt has been found in the event
Bool_t storeConvPt = kFALSE;
Bool_t storeConvAcc = kFALSE;
if ((fConvMinPt > 0) || (fConvMinEta != -999) || (fConvMaxEta != 999) || (fConvMinPhi != -999) || (fConvMaxPhi != 999)){
// This is only done if any ConvPt or ConvAcceptance cut was given by user
TClonesArray *convgammas = dynamic_cast<TClonesArray*>(fAOD->FindListObject(fGammaBr));
if(convgammas){
for(Int_t i=0;i<convgammas->GetEntriesFast();i++){
AliAODConversionPhoton* g =dynamic_cast<AliAODConversionPhoton*>(convgammas->At(i));
if(g){
Double_t pt = g->Pt();
Double_t eta = g->Eta();
Double_t phi = g->Phi();
if(fDoQA){
fHconvPtBeforeCuts->Fill(pt);
fHconvAccBeforeCuts->Fill(eta,phi);
}
if(fConvMinPt > 0){
if (pt>fConvMinPt){ // pt cut
storeConvPt = kTRUE;
}
} else{
storeConvPt = kTRUE;
}
if( (eta>fConvMinEta) && (eta<fConvMaxEta) && (phi>fConvMinPhi) && (phi>fConvMaxPhi)){ // will always be true if no cut was set
storeConvAcc = kTRUE;
}
}
}
}
} else { // neither pt cuts nor acceptance cuts were set
storeConvPt = kTRUE;
storeConvAcc = kTRUE;
}
Bool_t store = kFALSE;
if (fDoBothMinTrackAndClus && fClusMinE>0 && fTrackMinPt > 0){
// request that both conditions are full-filled for propagating the event
store = (storeE && storePt);
} else if (!fDoBothMinTrackAndClus && fClusMinE>0 && fTrackMinPt > 0){
// request that at least one of the conditions is fullfilled
store = (storeE || storePt);
} else if (fDoBothConvPtAndAcc && (fConvMinPt >0) && (fConvMinEta!=-999 || fConvMaxEta!=999 || fConvMinPhi!=-999 || fConvMaxPhi!=999)){
store = (storeConvPt && storeConvAcc);
} else if (!fDoBothConvPtAndAcc && (fConvMinPt >0) && (fConvMinEta!=-999 || fConvMaxEta!=999 || fConvMinPhi!=-999 || fConvMaxPhi!=999)){
store = (storeConvPt || storeConvAcc);
} else if ( fClusMinE>0 ){
store = storeE;
} else if ( fTrackMinPt>0 ){
store = storePt;
} else if ( fConvMinPt>0 ){
store = storeConvPt;
} else if (fConvMinEta!=-999 || fConvMaxEta!=999 || fConvMinPhi!=-999 || fConvMaxPhi!=999){
store = storeConvAcc;
} else {
store = kTRUE;
}
if(fDoQA){
TClonesArray *convgammas = dynamic_cast<TClonesArray*>(fAOD->FindListObject(fGammaBr));
if(convgammas){
for(Int_t i=0;i<convgammas->GetEntriesFast();i++){
AliAODConversionPhoton* g =dynamic_cast<AliAODConversionPhoton*>(convgammas->At(i));
if(g){
Double_t pt = g->Pt();
Double_t eta = g->Eta();
Double_t phi = g->Phi();
fHconvPtAfterCuts->Fill(pt);
fHconvAccAfterCuts->Fill(eta,phi);
}
}
}
}
return store;
}
Bool_t AliConversionAodSkimTask::UserNotify()
{
TTree *tree = AliAnalysisManager::GetAnalysisManager()->GetTree();
if (!tree) {
AliError(Form("%s: No current tree!",GetName()));
return kFALSE;
}
Float_t xsection = 0;
Float_t trials = 0;
Int_t pthardbin = 0;
TFile *curfile = tree->GetCurrentFile();
if (!curfile) {
AliError(Form("%s: No current file!",GetName()));
return kFALSE;
}
TChain *chain = dynamic_cast<TChain*>(tree);
if (chain) tree = chain->GetTree();
Int_t nevents = tree->GetEntriesFast();
Int_t slevel = gErrorIgnoreLevel;
gErrorIgnoreLevel = kFatal;
Bool_t res = PythiaInfoFromFile(curfile->GetName(), xsection, trials, pthardbin);
gErrorIgnoreLevel=slevel;
if (res) {
cout << "AliConversionAodSkimTask " << GetName() << " found xsec info: " << xsection << " " << trials << " " << pthardbin << " " << nevents << endl;
fPyxsec = xsection;
fPytrials = trials;
fPypthardbin = pthardbin;
}
return res;
}
void AliConversionAodSkimTask::Terminate(Option_t *)
{
AliAnalysisManager *man = AliAnalysisManager::GetAnalysisManager();
if (man->GetAnalysisType()!=0)
return;
if (fHevs==0)
return;
Int_t norm = fHevs->GetEntries();
if (norm<1)
norm=1;
cout << "AliConversionAodSkimTask " << GetName() << " terminated with accepted fraction of events: " << fHevs->GetBinContent(2)/norm
<< " (" << fHevs->GetBinContent(2) << "/" << fHevs->GetEntries() << ")" << endl;
}
const char *AliConversionAodSkimTask::Str() const
{
return Form("mine%.2f_%dycut%.2f_%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d",
fClusMinE,
fCutMC,
fYCutMC,
fDoCopyHeader,
fDoCopyVZERO,
fDoCopyTZERO,
fDoCopyVertices,
fDoCopyTOF,
fDoCopyTracklets,
fDoCopyTracks,
fDoCopyTrigger,
fDoCopyPTrigger,
fDoCopyCells,
fDoCopyPCells,
fDoCopyClusters,
fDoCopyDiMuons,
fDoCopyTrdTracks,
fDoCopyV0s,
fDoCopyCascades,
fDoCopyZDC,
fDoCopyConv,
fDoCopyMC,
fDoCopyMCHeader);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: requeststringresolver.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: kz $ $Date: 2006-12-13 15:09:46 $
*
* 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 "requeststringresolver.hxx"
#include "iahndl.hxx"
using namespace com::sun;
UUIInteractionRequestStringResolver::UUIInteractionRequestStringResolver(
star::uno::Reference< star::lang::XMultiServiceFactory > const &
rServiceFactory)
SAL_THROW(())
: m_xServiceFactory(rServiceFactory),
m_pImpl(new UUIInteractionHelper(rServiceFactory))
{
}
UUIInteractionRequestStringResolver::~UUIInteractionRequestStringResolver()
{
delete m_pImpl;
}
rtl::OUString SAL_CALL
UUIInteractionRequestStringResolver::getImplementationName()
throw (star::uno::RuntimeException)
{
return rtl::OUString::createFromAscii(m_aImplementationName);
}
sal_Bool SAL_CALL
UUIInteractionRequestStringResolver::supportsService(
rtl::OUString const & rServiceName)
throw (star::uno::RuntimeException)
{
star::uno::Sequence< rtl::OUString >
aNames(getSupportedServiceNames_static());
for (sal_Int32 i = 0; i < aNames.getLength(); ++i)
if (aNames[i] == rServiceName)
return true;
return false;
}
star::uno::Sequence< rtl::OUString > SAL_CALL
UUIInteractionRequestStringResolver::getSupportedServiceNames()
throw (star::uno::RuntimeException)
{
return getSupportedServiceNames_static();
}
star::beans::Optional< rtl::OUString > SAL_CALL
UUIInteractionRequestStringResolver::getStringFromInformationalRequest(
const star::uno::Reference<
star::task::XInteractionRequest >& Request )
throw (star::uno::RuntimeException)
{
try
{
return m_pImpl->getStringFromRequest(Request);
}
catch (star::uno::RuntimeException const & ex)
{
throw star::uno::RuntimeException(ex.Message, *this);
}
}
char const UUIInteractionRequestStringResolver::m_aImplementationName[]
= "com.sun.star.comp.uui.UUIInteractionRequestStringResolver";
star::uno::Sequence< rtl::OUString >
UUIInteractionRequestStringResolver::getSupportedServiceNames_static()
{
star::uno::Sequence< rtl::OUString > aNames(1);
aNames[0] = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
"com.sun.star.task.InteractionRequestStringResolver"));
return aNames;
}
star::uno::Reference< star::uno::XInterface > SAL_CALL
UUIInteractionRequestStringResolver::createInstance(
star::uno::Reference< star::lang::XMultiServiceFactory > const &
rServiceFactory)
SAL_THROW((star::uno::Exception))
{
try
{
return *new UUIInteractionRequestStringResolver(rServiceFactory);
}
catch (std::bad_alloc const &)
{
throw star::uno::RuntimeException(
rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("out of memory")),
0);
}
}
<commit_msg>INTEGRATION: CWS changefileheader (1.2.78); FILE MERGED 2008/03/31 15:33:14 rt 1.2.78.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: requeststringresolver.cxx,v $
* $Revision: 1.3 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "requeststringresolver.hxx"
#include "iahndl.hxx"
using namespace com::sun;
UUIInteractionRequestStringResolver::UUIInteractionRequestStringResolver(
star::uno::Reference< star::lang::XMultiServiceFactory > const &
rServiceFactory)
SAL_THROW(())
: m_xServiceFactory(rServiceFactory),
m_pImpl(new UUIInteractionHelper(rServiceFactory))
{
}
UUIInteractionRequestStringResolver::~UUIInteractionRequestStringResolver()
{
delete m_pImpl;
}
rtl::OUString SAL_CALL
UUIInteractionRequestStringResolver::getImplementationName()
throw (star::uno::RuntimeException)
{
return rtl::OUString::createFromAscii(m_aImplementationName);
}
sal_Bool SAL_CALL
UUIInteractionRequestStringResolver::supportsService(
rtl::OUString const & rServiceName)
throw (star::uno::RuntimeException)
{
star::uno::Sequence< rtl::OUString >
aNames(getSupportedServiceNames_static());
for (sal_Int32 i = 0; i < aNames.getLength(); ++i)
if (aNames[i] == rServiceName)
return true;
return false;
}
star::uno::Sequence< rtl::OUString > SAL_CALL
UUIInteractionRequestStringResolver::getSupportedServiceNames()
throw (star::uno::RuntimeException)
{
return getSupportedServiceNames_static();
}
star::beans::Optional< rtl::OUString > SAL_CALL
UUIInteractionRequestStringResolver::getStringFromInformationalRequest(
const star::uno::Reference<
star::task::XInteractionRequest >& Request )
throw (star::uno::RuntimeException)
{
try
{
return m_pImpl->getStringFromRequest(Request);
}
catch (star::uno::RuntimeException const & ex)
{
throw star::uno::RuntimeException(ex.Message, *this);
}
}
char const UUIInteractionRequestStringResolver::m_aImplementationName[]
= "com.sun.star.comp.uui.UUIInteractionRequestStringResolver";
star::uno::Sequence< rtl::OUString >
UUIInteractionRequestStringResolver::getSupportedServiceNames_static()
{
star::uno::Sequence< rtl::OUString > aNames(1);
aNames[0] = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(
"com.sun.star.task.InteractionRequestStringResolver"));
return aNames;
}
star::uno::Reference< star::uno::XInterface > SAL_CALL
UUIInteractionRequestStringResolver::createInstance(
star::uno::Reference< star::lang::XMultiServiceFactory > const &
rServiceFactory)
SAL_THROW((star::uno::Exception))
{
try
{
return *new UUIInteractionRequestStringResolver(rServiceFactory);
}
catch (std::bad_alloc const &)
{
throw star::uno::RuntimeException(
rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("out of memory")),
0);
}
}
<|endoftext|> |
<commit_before>/*
Dwarf Therapist
Copyright (c) 2009 Trey Stout (chmod)
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 <QtGui>
#include "qmath.h"
#include "mainwindow.h"
#include "statetableview.h"
#include "dwarfmodel.h"
#include "dwarfmodelproxy.h"
#include "uberdelegate.h"
#include "rotatedheader.h"
#include "dwarf.h"
#include "defines.h"
#include "columntypes.h"
#include "gridview.h"
#include "viewcolumnset.h"
#include "laborcolumn.h"
#include "happinesscolumn.h"
#include "dwarftherapist.h"
#include "customprofession.h"
#include "viewmanager.h"
StateTableView::StateTableView(QWidget *parent)
: QTreeView(parent)
, m_model(0)
, m_proxy(0)
, m_delegate(new UberDelegate(this))
, m_header(new RotatedHeader(Qt::Horizontal, this))
, m_expanded_rows(QList<int>())
{
read_settings();
setMouseTracking(true);
setEditTriggers(QAbstractItemView::NoEditTriggers);
setUniformRowHeights(true);
setSelectionBehavior(QAbstractItemView::SelectRows);
setSelectionMode(QAbstractItemView::ExtendedSelection);
setIndentation(8);
setFocusPolicy(Qt::NoFocus); // keep the dotted border off of things
setItemDelegate(m_delegate);
setHeader(m_header);
// Set StaticContents to enable minimal repaints on resizes.
viewport()->setAttribute(Qt::WA_StaticContents);
connect(DT, SIGNAL(settings_changed()), this, SLOT(read_settings()));
connect(this, SIGNAL(expanded(const QModelIndex &)), SLOT(index_expanded(const QModelIndex &)));
connect(this, SIGNAL(collapsed(const QModelIndex &)), SLOT(index_collapsed(const QModelIndex &)));
}
StateTableView::~StateTableView()
{}
void StateTableView::read_settings() {
QSettings *s = DT->user_settings();
//font
QFont fnt = s->value("options/grid/font", QFont("Segoe UI", 8)).value<QFont>();
setFont(fnt);
//cell size
m_grid_size = s->value("options/grid/cell_size", DEFAULT_CELL_SIZE).toInt();
int pad = s->value("options/grid/cell_padding", 0).toInt();
setIconSize(QSize(m_grid_size - 2 - pad * 2, m_grid_size - 2 - pad * 2));
set_single_click_labor_changes(s->value("options/single_click_labor_changes", true).toBool());
}
void StateTableView::set_model(DwarfModel *model, DwarfModelProxy *proxy) {
QTreeView::setModel(proxy);
m_model = model;
m_proxy = proxy;
m_delegate->set_model(model);
m_delegate->set_proxy(proxy);
connect(m_header, SIGNAL(section_right_clicked(int)), m_model, SLOT(section_right_clicked(int)));
connect(this, SIGNAL(activated(const QModelIndex&)), proxy, SLOT(cell_activated(const QModelIndex&)));
connect(m_model, SIGNAL(preferred_header_size(int, int)), m_header, SLOT(resizeSection(int, int)));
connect(m_model, SIGNAL(set_index_as_spacer(int)), m_header, SLOT(set_index_as_spacer(int)));
connect(m_model, SIGNAL(clear_spacers()), m_header, SLOT(clear_spacers()));
set_single_click_labor_changes(DT->user_settings()->value("options/single_click_labor_changes", true).toBool());
}
void StateTableView::new_custom_profession() {
QModelIndex idx = currentIndex();
if (idx.isValid()) {
int id = idx.data(DwarfModel::DR_ID).toInt();
Dwarf *d = m_model->get_dwarf_by_id(id);
if (d)
emit new_custom_profession(d);
}
}
void StateTableView::filter_dwarves(QString text) {
m_proxy->setFilterFixedString(text);
m_proxy->setFilterKeyColumn(0);
m_proxy->setFilterRole(Qt::DisplayRole);
}
void StateTableView::jump_to_dwarf(QTreeWidgetItem* current, QTreeWidgetItem*) {
if (!current)
return;
int dwarf_id = current->data(0, Qt::UserRole).toInt();
Dwarf *d = m_model->get_dwarf_by_id(dwarf_id);
if (d && d->m_name_idx.isValid()) {
QModelIndex proxy_idx = m_proxy->mapFromSource(d->m_name_idx);
if (proxy_idx.isValid()) {
scrollTo(proxy_idx);
selectionModel()->select(proxy_idx, QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows);
}
}
}
void StateTableView::jump_to_profession(QListWidgetItem* current, QListWidgetItem*) {
if (!current)
return;
QString prof_name = current->text();
QModelIndexList matches = m_proxy->match(m_proxy->index(0,0), Qt::DisplayRole, prof_name);
if (matches.size() > 0) {
QModelIndex group_header = matches.at(0);
scrollTo(group_header);
expand(group_header);
selectionModel()->select(group_header, QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows);
}
}
void StateTableView::set_single_click_labor_changes(bool enabled) {
TRACE << "setting single click labor changes:" << enabled;
disconnect(this, SIGNAL(clicked(const QModelIndex&)), 0, 0);
if (enabled && m_proxy) {
connect(this, SIGNAL(clicked(const QModelIndex&)), m_proxy, SLOT(cell_activated(const QModelIndex&)));
}
}
void StateTableView::contextMenuEvent(QContextMenuEvent *event) {
QModelIndex idx = indexAt(event->pos());
if (!idx.isValid())
return;
QMenu m(this); // this will be the popup menu
if (idx.column() == 0 && !idx.data(DwarfModel::DR_IS_AGGREGATE).toBool()) {
// we're on top of a dwarf's name
int id = idx.data(DwarfModel::DR_ID).toInt();
m.addAction(tr("Set Nickname..."), this, SLOT(set_nickname()));
//m.addAction(tr("View Details..."), this, "add_custom_profession()");
m.addSeparator();
QMenu sub(&m);
sub.setTitle(tr("Custom Professions"));
QAction *a = sub.addAction(tr("New custom profession from this dwarf..."), this, SLOT(custom_profession_from_dwarf()));
a->setData(id);
sub.addAction(tr("Reset to default profession"), this, SLOT(reset_custom_profession()));
sub.addSeparator();
foreach(CustomProfession *cp, DT->get_custom_professions()) {
sub.addAction(cp->get_name(), this, SLOT(apply_custom_profession()));
}
m.addMenu(&sub);
} else if (idx.data(DwarfModel::DR_COL_TYPE).toInt() == CT_LABOR) {
// labor column
QString set_name = idx.data(DwarfModel::DR_SET_NAME).toString();
ViewColumnSet *set = DT->get_main_window()->get_view_manager()->get_set(set_name);
if (idx.data(DwarfModel::DR_IS_AGGREGATE).toBool()) { //aggregate labor
QModelIndex first_col = idx.sibling(idx.row(), 0);
QString group_name = idx.data(DwarfModel::DR_GROUP_NAME).toString();
foreach(Dwarf *d, m_model->get_dwarf_groups()->value(group_name)) {
}
QAction *a = m.addAction(tr("Toggle %1 for %2").arg(set_name).arg(group_name));
a->setData(group_name);
connect(a, SIGNAL(triggered()), set, SLOT(toggle_for_dwarf_group()));
} else { // single dwarf labor
// find the dwarf...
int dwarf_id = idx.data(DwarfModel::DR_ID).toInt();
Dwarf *d = m_model->get_dwarf_by_id(dwarf_id);
QAction *a = m.addAction(tr("Toggle %1 for %2").arg(set_name).arg(d->nice_name()));
a->setData(dwarf_id);
connect(a, SIGNAL(triggered()), set, SLOT(toggle_for_dwarf()));
}
}
m.exec(viewport()->mapToGlobal(event->pos()));
}
void StateTableView::set_nickname() {
const QItemSelection sel = selectionModel()->selection();
QModelIndexList first_col;
foreach(QModelIndex i, sel.indexes()) {
if (i.column() == 0 && !i.data(DwarfModel::DR_IS_AGGREGATE).toBool())
first_col << i;
}
if (first_col.size() != 1) {
QMessageBox::warning(this, tr("Too many!"), tr("Slow down, killer. One at a time."));
return;
}
int id = first_col[0].data(DwarfModel::DR_ID).toInt();
Dwarf *d = m_model->get_dwarf_by_id(id);
if (d) {
QString new_nick = QInputDialog::getText(this, tr("New Nickname"), tr("Nickname"), QLineEdit::Normal, d->nickname());
if (new_nick.length() > 28) {
QMessageBox::warning(this, tr("Nickname too long"), tr("Nicknames must be under 28 characters long."));
return;
}
d->set_nickname(new_nick);
m_model->setData(first_col[0], d->nice_name(), Qt::DisplayRole);
}
m_model->calculate_pending();
}
void StateTableView::custom_profession_from_dwarf() {
QAction *a = qobject_cast<QAction*>(QObject::sender());
int id = a->data().toInt();
Dwarf *d = m_model->get_dwarf_by_id(id);
DT->custom_profession_from_dwarf(d);
}
void StateTableView::apply_custom_profession() {
QAction *a = qobject_cast<QAction*>(QObject::sender());
CustomProfession *cp = DT->get_custom_profession(a->text());
if (!cp)
return;
const QItemSelection sel = selectionModel()->selection();
foreach(const QModelIndex idx, sel.indexes()) {
if (idx.column() == 0 && !idx.data(DwarfModel::DR_IS_AGGREGATE).toBool()) {
Dwarf *d = m_model->get_dwarf_by_id(idx.data(DwarfModel::DR_ID).toInt());
if (d)
d->apply_custom_profession(cp);
}
}
m_model->calculate_pending();
}
void StateTableView::reset_custom_profession() {
const QItemSelection sel = selectionModel()->selection();
foreach(const QModelIndex idx, sel.indexes()) {
if (idx.column() == 0 && !idx.data(DwarfModel::DR_IS_AGGREGATE).toBool()) {
Dwarf *d = m_model->get_dwarf_by_id(idx.data(DwarfModel::DR_ID).toInt());
if (d)
d->reset_custom_profession();
}
}
m_model->calculate_pending();
}
/************************************************************************/
/* Handlers for expand/collapse persistence */
/************************************************************************/
void StateTableView::expandAll() {
m_expanded_rows.clear();
for(int i = 0; i < m_proxy->rowCount(); ++i) {
m_expanded_rows << i;
}
QTreeView::expandAll();
}
void StateTableView::collapseAll() {
m_expanded_rows.clear();
QTreeView::collapseAll();
}
void StateTableView::index_expanded(const QModelIndex &idx) {
m_expanded_rows << idx.row();
}
void StateTableView::index_collapsed(const QModelIndex &idx) {
int i = m_expanded_rows.indexOf(idx.row());
if (i != -1)
m_expanded_rows.removeAt(i);
}
void StateTableView::restore_expanded_items() {
disconnect(this, SIGNAL(expanded(const QModelIndex &)), 0, 0);
foreach(int row, m_expanded_rows) {
expand(m_proxy->index(row, 0));
}
connect(this, SIGNAL(expanded(const QModelIndex &)), SLOT(index_expanded(const QModelIndex &)));
}<commit_msg> * fixing a context problem in the draw context menu method. Weird huh? * I'm pretty certain this fixes issue 58 (can't repro it anymore)<commit_after>/*
Dwarf Therapist
Copyright (c) 2009 Trey Stout (chmod)
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 <QtGui>
#include "qmath.h"
#include "mainwindow.h"
#include "statetableview.h"
#include "dwarfmodel.h"
#include "dwarfmodelproxy.h"
#include "uberdelegate.h"
#include "rotatedheader.h"
#include "dwarf.h"
#include "defines.h"
#include "columntypes.h"
#include "gridview.h"
#include "viewcolumnset.h"
#include "laborcolumn.h"
#include "happinesscolumn.h"
#include "dwarftherapist.h"
#include "customprofession.h"
#include "viewmanager.h"
StateTableView::StateTableView(QWidget *parent)
: QTreeView(parent)
, m_model(0)
, m_proxy(0)
, m_delegate(new UberDelegate(this))
, m_header(new RotatedHeader(Qt::Horizontal, this))
, m_expanded_rows(QList<int>())
{
read_settings();
setMouseTracking(true);
setEditTriggers(QAbstractItemView::NoEditTriggers);
setUniformRowHeights(true);
setSelectionBehavior(QAbstractItemView::SelectRows);
setSelectionMode(QAbstractItemView::ExtendedSelection);
setIndentation(8);
setFocusPolicy(Qt::NoFocus); // keep the dotted border off of things
setItemDelegate(m_delegate);
setHeader(m_header);
// Set StaticContents to enable minimal repaints on resizes.
viewport()->setAttribute(Qt::WA_StaticContents);
connect(DT, SIGNAL(settings_changed()), this, SLOT(read_settings()));
connect(this, SIGNAL(expanded(const QModelIndex &)), SLOT(index_expanded(const QModelIndex &)));
connect(this, SIGNAL(collapsed(const QModelIndex &)), SLOT(index_collapsed(const QModelIndex &)));
}
StateTableView::~StateTableView()
{}
void StateTableView::read_settings() {
QSettings *s = DT->user_settings();
//font
QFont fnt = s->value("options/grid/font", QFont("Segoe UI", 8)).value<QFont>();
setFont(fnt);
//cell size
m_grid_size = s->value("options/grid/cell_size", DEFAULT_CELL_SIZE).toInt();
int pad = s->value("options/grid/cell_padding", 0).toInt();
setIconSize(QSize(m_grid_size - 2 - pad * 2, m_grid_size - 2 - pad * 2));
set_single_click_labor_changes(s->value("options/single_click_labor_changes", true).toBool());
}
void StateTableView::set_model(DwarfModel *model, DwarfModelProxy *proxy) {
QTreeView::setModel(proxy);
m_model = model;
m_proxy = proxy;
m_delegate->set_model(model);
m_delegate->set_proxy(proxy);
connect(m_header, SIGNAL(section_right_clicked(int)), m_model, SLOT(section_right_clicked(int)));
connect(this, SIGNAL(activated(const QModelIndex&)), proxy, SLOT(cell_activated(const QModelIndex&)));
connect(m_model, SIGNAL(preferred_header_size(int, int)), m_header, SLOT(resizeSection(int, int)));
connect(m_model, SIGNAL(set_index_as_spacer(int)), m_header, SLOT(set_index_as_spacer(int)));
connect(m_model, SIGNAL(clear_spacers()), m_header, SLOT(clear_spacers()));
set_single_click_labor_changes(DT->user_settings()->value("options/single_click_labor_changes", true).toBool());
}
void StateTableView::new_custom_profession() {
QModelIndex idx = currentIndex();
if (idx.isValid()) {
int id = idx.data(DwarfModel::DR_ID).toInt();
Dwarf *d = m_model->get_dwarf_by_id(id);
if (d)
emit new_custom_profession(d);
}
}
void StateTableView::filter_dwarves(QString text) {
m_proxy->setFilterFixedString(text);
m_proxy->setFilterKeyColumn(0);
m_proxy->setFilterRole(Qt::DisplayRole);
}
void StateTableView::jump_to_dwarf(QTreeWidgetItem* current, QTreeWidgetItem*) {
if (!current)
return;
int dwarf_id = current->data(0, Qt::UserRole).toInt();
Dwarf *d = m_model->get_dwarf_by_id(dwarf_id);
if (d && d->m_name_idx.isValid()) {
QModelIndex proxy_idx = m_proxy->mapFromSource(d->m_name_idx);
if (proxy_idx.isValid()) {
scrollTo(proxy_idx);
selectionModel()->select(proxy_idx, QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows);
}
}
}
void StateTableView::jump_to_profession(QListWidgetItem* current, QListWidgetItem*) {
if (!current)
return;
QString prof_name = current->text();
QModelIndexList matches = m_proxy->match(m_proxy->index(0,0), Qt::DisplayRole, prof_name);
if (matches.size() > 0) {
QModelIndex group_header = matches.at(0);
scrollTo(group_header);
expand(group_header);
selectionModel()->select(group_header, QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows);
}
}
void StateTableView::set_single_click_labor_changes(bool enabled) {
TRACE << "setting single click labor changes:" << enabled;
disconnect(this, SIGNAL(clicked(const QModelIndex&)), 0, 0);
if (enabled && m_proxy) {
connect(this, SIGNAL(clicked(const QModelIndex&)), m_proxy, SLOT(cell_activated(const QModelIndex&)));
}
}
void StateTableView::contextMenuEvent(QContextMenuEvent *event) {
QModelIndex idx = indexAt(event->pos());
if (!idx.isValid())
return;
if (idx.column() == 0 && !idx.data(DwarfModel::DR_IS_AGGREGATE).toBool()) {
// we're on top of a dwarf's name
QMenu m(this); // this will be the popup menu
int id = idx.data(DwarfModel::DR_ID).toInt();
m.addAction(tr("Set Nickname..."), this, SLOT(set_nickname()));
//m.addAction(tr("View Details..."), this, "add_custom_profession()");
m.addSeparator();
QMenu sub(&m);
sub.setTitle(tr("Custom Professions"));
QAction *a = sub.addAction(tr("New custom profession from this dwarf..."), this, SLOT(custom_profession_from_dwarf()));
a->setData(id);
sub.addAction(tr("Reset to default profession"), this, SLOT(reset_custom_profession()));
sub.addSeparator();
foreach(CustomProfession *cp, DT->get_custom_professions()) {
sub.addAction(cp->get_name(), this, SLOT(apply_custom_profession()));
}
m.addMenu(&sub);
m.exec(viewport()->mapToGlobal(event->pos()));
} else if (idx.data(DwarfModel::DR_COL_TYPE).toInt() == CT_LABOR) {
// labor column
QMenu m(this); // this will be the popup menu
QString set_name = idx.data(DwarfModel::DR_SET_NAME).toString();
ViewColumnSet *set = DT->get_main_window()->get_view_manager()->get_set(set_name);
if (idx.data(DwarfModel::DR_IS_AGGREGATE).toBool()) { //aggregate labor
QModelIndex first_col = idx.sibling(idx.row(), 0);
QString group_name = idx.data(DwarfModel::DR_GROUP_NAME).toString();
foreach(Dwarf *d, m_model->get_dwarf_groups()->value(group_name)) {
}
QAction *a = m.addAction(tr("Toggle %1 for %2").arg(set_name).arg(group_name));
a->setData(group_name);
connect(a, SIGNAL(triggered()), set, SLOT(toggle_for_dwarf_group()));
} else { // single dwarf labor
// find the dwarf...
int dwarf_id = idx.data(DwarfModel::DR_ID).toInt();
Dwarf *d = m_model->get_dwarf_by_id(dwarf_id);
QAction *a = m.addAction(tr("Toggle %1 for %2").arg(set_name).arg(d->nice_name()));
a->setData(dwarf_id);
connect(a, SIGNAL(triggered()), set, SLOT(toggle_for_dwarf()));
}
m.exec(viewport()->mapToGlobal(event->pos()));
}
}
void StateTableView::set_nickname() {
const QItemSelection sel = selectionModel()->selection();
QModelIndexList first_col;
foreach(QModelIndex i, sel.indexes()) {
if (i.column() == 0 && !i.data(DwarfModel::DR_IS_AGGREGATE).toBool())
first_col << i;
}
if (first_col.size() != 1) {
QMessageBox::warning(this, tr("Too many!"), tr("Slow down, killer. One at a time."));
return;
}
int id = first_col[0].data(DwarfModel::DR_ID).toInt();
Dwarf *d = m_model->get_dwarf_by_id(id);
if (d) {
QString new_nick = QInputDialog::getText(this, tr("New Nickname"), tr("Nickname"), QLineEdit::Normal, d->nickname());
if (new_nick.length() > 28) {
QMessageBox::warning(this, tr("Nickname too long"), tr("Nicknames must be under 28 characters long."));
return;
}
d->set_nickname(new_nick);
m_model->setData(first_col[0], d->nice_name(), Qt::DisplayRole);
}
m_model->calculate_pending();
}
void StateTableView::custom_profession_from_dwarf() {
QAction *a = qobject_cast<QAction*>(QObject::sender());
int id = a->data().toInt();
Dwarf *d = m_model->get_dwarf_by_id(id);
DT->custom_profession_from_dwarf(d);
}
void StateTableView::apply_custom_profession() {
QAction *a = qobject_cast<QAction*>(QObject::sender());
CustomProfession *cp = DT->get_custom_profession(a->text());
if (!cp)
return;
const QItemSelection sel = selectionModel()->selection();
foreach(const QModelIndex idx, sel.indexes()) {
if (idx.column() == 0 && !idx.data(DwarfModel::DR_IS_AGGREGATE).toBool()) {
Dwarf *d = m_model->get_dwarf_by_id(idx.data(DwarfModel::DR_ID).toInt());
if (d)
d->apply_custom_profession(cp);
}
}
m_model->calculate_pending();
}
void StateTableView::reset_custom_profession() {
const QItemSelection sel = selectionModel()->selection();
foreach(const QModelIndex idx, sel.indexes()) {
if (idx.column() == 0 && !idx.data(DwarfModel::DR_IS_AGGREGATE).toBool()) {
Dwarf *d = m_model->get_dwarf_by_id(idx.data(DwarfModel::DR_ID).toInt());
if (d)
d->reset_custom_profession();
}
}
m_model->calculate_pending();
}
/************************************************************************/
/* Handlers for expand/collapse persistence */
/************************************************************************/
void StateTableView::expandAll() {
m_expanded_rows.clear();
for(int i = 0; i < m_proxy->rowCount(); ++i) {
m_expanded_rows << i;
}
QTreeView::expandAll();
}
void StateTableView::collapseAll() {
m_expanded_rows.clear();
QTreeView::collapseAll();
}
void StateTableView::index_expanded(const QModelIndex &idx) {
m_expanded_rows << idx.row();
}
void StateTableView::index_collapsed(const QModelIndex &idx) {
int i = m_expanded_rows.indexOf(idx.row());
if (i != -1)
m_expanded_rows.removeAt(i);
}
void StateTableView::restore_expanded_items() {
disconnect(this, SIGNAL(expanded(const QModelIndex &)), 0, 0);
foreach(int row, m_expanded_rows) {
expand(m_proxy->index(row, 0));
}
connect(this, SIGNAL(expanded(const QModelIndex &)), SLOT(index_expanded(const QModelIndex &)));
}<|endoftext|> |
<commit_before>/*
* The StockMap class is a hash table of any number of Stock objects,
* each with a different URI.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "MapStock.hxx"
#include "Stock.hxx"
#include "Item.hxx"
#include "pool.hxx"
#include "util/djbhash.h"
#include "util/DeleteDisposer.hxx"
#include <daemon/log.h>
#include <assert.h>
#include <string.h>
#include <boost/intrusive/unordered_set.hpp>
struct StockMap final : StockHandler {
struct Item
: boost::intrusive::unordered_set_base_hook<boost::intrusive::link_mode<boost::intrusive::normal_link>> {
Stock stock;
template<typename... Args>
explicit Item(Args&&... args):stock(std::forward<Args>(args)...) {}
gcc_pure
static size_t KeyHasher(const char *key) {
assert(key != nullptr);
return djb_hash_string(key);
}
gcc_pure
static size_t ValueHasher(const Item &value) {
return KeyHasher(value.stock.GetUri());
}
gcc_pure
static bool KeyValueEqual(const char *a, const Item &b) {
assert(a != nullptr);
return strcmp(a, b.stock.GetUri()) == 0;
}
struct Hash {
gcc_pure
size_t operator()(const Item &value) const {
return ValueHasher(value);
}
};
struct Equal {
gcc_pure
bool operator()(const Item &a, const Item &b) const {
return KeyValueEqual(a.stock.GetUri(), b);
}
};
};
typedef boost::intrusive::unordered_set<Item,
boost::intrusive::hash<Item::Hash>,
boost::intrusive::equal<Item::Equal>,
boost::intrusive::constant_time_size<false>> Map;
struct pool &pool;
const StockClass &cls;
void *const class_ctx;
/**
* The maximum number of items in each stock.
*/
const unsigned limit;
/**
* The maximum number of permanent idle items in each stock.
*/
const unsigned max_idle;
Map map;
static constexpr size_t N_BUCKETS = 251;
Map::bucket_type buckets[N_BUCKETS];
StockMap(struct pool &_pool, const StockClass &_cls, void *_class_ctx,
unsigned _limit, unsigned _max_idle)
:pool(*pool_new_libc(&_pool, "hstock")),
cls(_cls), class_ctx(_class_ctx),
limit(_limit), max_idle(_max_idle),
map(Map::bucket_traits(buckets, N_BUCKETS)) {}
~StockMap() {
map.clear_and_dispose(DeleteDisposer());
pool_unref(&pool);
}
void Erase(gcc_unused Stock &stock, const char *uri) {
#ifndef NDEBUG
auto i = map.find(uri, Item::KeyHasher, Item::KeyValueEqual);
assert(i != map.end());
assert(&i->stock == &stock);
#endif
map.erase_and_dispose(uri, Item::KeyHasher, Item::KeyValueEqual,
DeleteDisposer());
}
void FadeAll() {
for (auto &i : map)
i.stock.FadeAll();
}
void AddStats(StockStats &data) const {
for (const auto &i : map)
i.stock.AddStats(data);
}
Stock &GetStock(const char *uri);
void Get(struct pool &caller_pool,
const char *uri, void *info,
StockGetHandler &handler,
struct async_operation_ref &async_ref) {
Stock &stock = GetStock(uri);
stock.Get(caller_pool, info, handler, async_ref);
}
StockItem *GetNow(struct pool &caller_pool, const char *uri, void *info,
GError **error_r) {
Stock &stock = GetStock(uri);
return stock.GetNow(caller_pool, info, error_r);
}
void Put(gcc_unused const char *uri, StockItem &object, bool destroy) {
#ifndef NDEBUG
auto i = map.find(uri, Item::KeyHasher, Item::KeyValueEqual);
assert(i != map.end());
assert(&i->stock == &object.stock);
#endif
object.Put(destroy);
}
/* virtual methods from class StockHandler */
void OnStockEmpty(Stock &stock, const char *uri) override;
};
void
StockMap::OnStockEmpty(Stock &stock, const char *uri)
{
daemon_log(5, "hstock(%p) remove empty stock(%p, '%s')\n",
(const void *)this, (const void *)&stock, uri);
Erase(stock, uri);
}
StockMap *
hstock_new(struct pool &pool, const StockClass &cls, void *class_ctx,
unsigned limit, unsigned max_idle)
{
assert(max_idle > 0);
return new StockMap(pool, cls, class_ctx,
limit, max_idle);
}
void
hstock_free(StockMap *hstock)
{
delete hstock;
}
void
hstock_fade_all(StockMap &hstock)
{
hstock.FadeAll();
}
void
hstock_add_stats(const StockMap &stock, StockStats &data)
{
stock.AddStats(data);
}
inline Stock &
StockMap::GetStock(const char *uri)
{
Map::insert_commit_data hint;
auto i = map.insert_check(uri, Item::KeyHasher, Item::KeyValueEqual, hint);
if (i.second) {
auto *item = new Item(pool, cls, class_ctx,
uri, limit, max_idle,
this);
map.insert_commit(*item, hint);
return item->stock;
} else
return i.first->stock;
}
void
hstock_get(StockMap &hstock, struct pool &pool,
const char *uri, void *info,
StockGetHandler &handler,
struct async_operation_ref &async_ref)
{
return hstock.Get(pool, uri, info, handler, async_ref);
}
StockItem *
hstock_get_now(StockMap &hstock, struct pool &pool,
const char *uri, void *info,
GError **error_r)
{
return hstock.GetNow(pool, uri, info, error_r);
}
void
hstock_put(StockMap &hstock, const char *uri, StockItem &object, bool destroy)
{
hstock.Put(uri, object, destroy);
}
<commit_msg>stock/Map: use iterator_to() instead of find() in Erase()<commit_after>/*
* The StockMap class is a hash table of any number of Stock objects,
* each with a different URI.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "MapStock.hxx"
#include "Stock.hxx"
#include "Item.hxx"
#include "pool.hxx"
#include "util/djbhash.h"
#include "util/DeleteDisposer.hxx"
#include "util/Cast.hxx"
#include <daemon/log.h>
#include <assert.h>
#include <string.h>
#include <boost/intrusive/unordered_set.hpp>
struct StockMap final : StockHandler {
struct Item
: boost::intrusive::unordered_set_base_hook<boost::intrusive::link_mode<boost::intrusive::normal_link>> {
Stock stock;
template<typename... Args>
explicit Item(Args&&... args):stock(std::forward<Args>(args)...) {}
static Item &Cast(Stock &s) {
return ContainerCast2(s, &Item::stock);
}
gcc_pure
static size_t KeyHasher(const char *key) {
assert(key != nullptr);
return djb_hash_string(key);
}
gcc_pure
static size_t ValueHasher(const Item &value) {
return KeyHasher(value.stock.GetUri());
}
gcc_pure
static bool KeyValueEqual(const char *a, const Item &b) {
assert(a != nullptr);
return strcmp(a, b.stock.GetUri()) == 0;
}
struct Hash {
gcc_pure
size_t operator()(const Item &value) const {
return ValueHasher(value);
}
};
struct Equal {
gcc_pure
bool operator()(const Item &a, const Item &b) const {
return KeyValueEqual(a.stock.GetUri(), b);
}
};
};
typedef boost::intrusive::unordered_set<Item,
boost::intrusive::hash<Item::Hash>,
boost::intrusive::equal<Item::Equal>,
boost::intrusive::constant_time_size<false>> Map;
struct pool &pool;
const StockClass &cls;
void *const class_ctx;
/**
* The maximum number of items in each stock.
*/
const unsigned limit;
/**
* The maximum number of permanent idle items in each stock.
*/
const unsigned max_idle;
Map map;
static constexpr size_t N_BUCKETS = 251;
Map::bucket_type buckets[N_BUCKETS];
StockMap(struct pool &_pool, const StockClass &_cls, void *_class_ctx,
unsigned _limit, unsigned _max_idle)
:pool(*pool_new_libc(&_pool, "hstock")),
cls(_cls), class_ctx(_class_ctx),
limit(_limit), max_idle(_max_idle),
map(Map::bucket_traits(buckets, N_BUCKETS)) {}
~StockMap() {
map.clear_and_dispose(DeleteDisposer());
pool_unref(&pool);
}
void Erase(Item &item) {
auto i = map.iterator_to(item);
map.erase_and_dispose(i, DeleteDisposer());
}
void FadeAll() {
for (auto &i : map)
i.stock.FadeAll();
}
void AddStats(StockStats &data) const {
for (const auto &i : map)
i.stock.AddStats(data);
}
Stock &GetStock(const char *uri);
void Get(struct pool &caller_pool,
const char *uri, void *info,
StockGetHandler &handler,
struct async_operation_ref &async_ref) {
Stock &stock = GetStock(uri);
stock.Get(caller_pool, info, handler, async_ref);
}
StockItem *GetNow(struct pool &caller_pool, const char *uri, void *info,
GError **error_r) {
Stock &stock = GetStock(uri);
return stock.GetNow(caller_pool, info, error_r);
}
void Put(gcc_unused const char *uri, StockItem &object, bool destroy) {
#ifndef NDEBUG
auto i = map.find(uri, Item::KeyHasher, Item::KeyValueEqual);
assert(i != map.end());
assert(&i->stock == &object.stock);
#endif
object.Put(destroy);
}
/* virtual methods from class StockHandler */
void OnStockEmpty(Stock &stock, const char *uri) override;
};
void
StockMap::OnStockEmpty(Stock &stock, const char *uri)
{
auto &item = Item::Cast(stock);
daemon_log(5, "hstock(%p) remove empty stock(%p, '%s')\n",
(const void *)this, (const void *)&stock, uri);
Erase(item);
}
StockMap *
hstock_new(struct pool &pool, const StockClass &cls, void *class_ctx,
unsigned limit, unsigned max_idle)
{
assert(max_idle > 0);
return new StockMap(pool, cls, class_ctx,
limit, max_idle);
}
void
hstock_free(StockMap *hstock)
{
delete hstock;
}
void
hstock_fade_all(StockMap &hstock)
{
hstock.FadeAll();
}
void
hstock_add_stats(const StockMap &stock, StockStats &data)
{
stock.AddStats(data);
}
inline Stock &
StockMap::GetStock(const char *uri)
{
Map::insert_commit_data hint;
auto i = map.insert_check(uri, Item::KeyHasher, Item::KeyValueEqual, hint);
if (i.second) {
auto *item = new Item(pool, cls, class_ctx,
uri, limit, max_idle,
this);
map.insert_commit(*item, hint);
return item->stock;
} else
return i.first->stock;
}
void
hstock_get(StockMap &hstock, struct pool &pool,
const char *uri, void *info,
StockGetHandler &handler,
struct async_operation_ref &async_ref)
{
return hstock.Get(pool, uri, info, handler, async_ref);
}
StockItem *
hstock_get_now(StockMap &hstock, struct pool &pool,
const char *uri, void *info,
GError **error_r)
{
return hstock.GetNow(pool, uri, info, error_r);
}
void
hstock_put(StockMap &hstock, const char *uri, StockItem &object, bool destroy)
{
hstock.Put(uri, object, destroy);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2015 The Bitcoin Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chain.h"
#include "chainparams.h"
#include "pow.h"
#include "random.h"
#include "util.h"
#include "test/test_bitcoin.h"
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(pow_tests, BasicTestingSetup)
/* Test calculation of next difficulty target with no constraints applying */
BOOST_AUTO_TEST_CASE(get_next_work)
{
const auto chainParams = CreateChainParams(CBaseChainParams::MAIN);
int64_t nLastRetargetTime = 1261130161; // Block #30240
CBlockIndex pindexLast;
pindexLast.nHeight = 32255;
pindexLast.nTime = 1262152739; // Block #32255
pindexLast.nBits = 0x1d00ffff;
BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, chainParams->GetConsensus()), 0x1d00d86a);
}
/* Test the constraint on the upper bound for next work */
BOOST_AUTO_TEST_CASE(get_next_work_pow_limit)
{
const auto chainParams = CreateChainParams(CBaseChainParams::MAIN);
int64_t nLastRetargetTime = 1231006505; // Block #0
CBlockIndex pindexLast;
pindexLast.nHeight = 2015;
pindexLast.nTime = 1233061996; // Block #2015
pindexLast.nBits = 0x1d00ffff;
BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, chainParams->GetConsensus()), 0x1d00ffff);
}
/* Test the constraint on the lower bound for actual time taken */
BOOST_AUTO_TEST_CASE(get_next_work_lower_limit_actual)
{
const auto chainParams = CreateChainParams(CBaseChainParams::MAIN);
int64_t nLastRetargetTime = 1279008237; // Block #66528
CBlockIndex pindexLast;
pindexLast.nHeight = 68543;
pindexLast.nTime = 1279297671; // Block #68543
pindexLast.nBits = 0x1c05a3f4;
BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, chainParams->GetConsensus()), 0x1c0168fd);
}
/* Test the constraint on the upper bound for actual time taken */
BOOST_AUTO_TEST_CASE(get_next_work_upper_limit_actual)
{
const auto chainParams = CreateChainParams(CBaseChainParams::MAIN);
int64_t nLastRetargetTime = 1263163443; // NOTE: Not an actual block time
CBlockIndex pindexLast;
pindexLast.nHeight = 46367;
pindexLast.nTime = 1269211443; // Block #46367
pindexLast.nBits = 0x1c387f6f;
BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, chainParams->GetConsensus()), 0x1d00e1fd);
}
BOOST_AUTO_TEST_CASE(GetBlockProofEquivalentTime_test)
{
const auto chainParams = CreateChainParams(CBaseChainParams::MAIN);
std::vector<CBlockIndex> blocks(10000);
for (int i = 0; i < 10000; i++) {
blocks[i].pprev = i ? &blocks[i - 1] : nullptr;
blocks[i].nHeight = i;
blocks[i].nTime = 1269211443 + i * chainParams->GetConsensus().nPowTargetSpacing;
blocks[i].nBits = 0x207fffff; /* target 0x7fffff000... */
blocks[i].nChainWork = i ? blocks[i - 1].nChainWork + GetBlockProof(blocks[i - 1]) : arith_uint256(0);
}
for (int j = 0; j < 1000; j++) {
CBlockIndex *p1 = &blocks[InsecureRandRange(10000)];
CBlockIndex *p2 = &blocks[InsecureRandRange(10000)];
CBlockIndex *p3 = &blocks[InsecureRandRange(10000)];
int64_t tdiff = GetBlockProofEquivalentTime(*p1, *p2, *p3, chainParams->GetConsensus());
BOOST_CHECK_EQUAL(tdiff, p1->GetBlockTime() - p2->GetBlockTime());
}
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Viacoin: pow tests<commit_after>// Copyright (c) 2015 The Bitcoin Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chain.h"
#include "chainparams.h"
#include "pow.h"
#include "random.h"
#include "util.h"
#include "test/test_bitcoin.h"
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(pow_tests, BasicTestingSetup)
/* Test calculation of next difficulty target with no constraints applying */
BOOST_AUTO_TEST_CASE(get_next_work)
{
const auto chainParams = CreateChainParams(CBaseChainParams::MAIN);
int64_t nLastRetargetTime = 1358118740; // Block #278207
CBlockIndex pindexLast;
pindexLast.nHeight = 280223;
pindexLast.nTime = 1358378777; // Block #280223
pindexLast.nBits = 0x1c0ac141;
BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, chainParams->GetConsensus()), 0x1c02b050);
}
/* Test the constraint on the upper bound for next work */
BOOST_AUTO_TEST_CASE(get_next_work_pow_limit)
{
const auto chainParams = CreateChainParams(CBaseChainParams::MAIN);
int64_t nLastRetargetTime = 1317972665; // Block #0
CBlockIndex pindexLast;
pindexLast.nHeight = 2015;
pindexLast.nTime = 1318480354; // Block #2015
pindexLast.nBits = 0x1e0ffff0;
BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, chainParams->GetConsensus()), 0x1e01ffff);
}
/* Test the constraint on the lower bound for actual time taken */
BOOST_AUTO_TEST_CASE(get_next_work_lower_limit_actual)
{
const auto chainParams = CreateChainParams(CBaseChainParams::MAIN);
int64_t nLastRetargetTime = 1401682934; // Block #66528 // Note: Not an actual block time
CBlockIndex pindexLast;
pindexLast.nHeight = 578591;
pindexLast.nTime = 1401757934; // Block #68543
pindexLast.nBits = 0x1b075cf1;
BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, chainParams->GetConsensus()), 0x1b01d73c);
}
/* Test the constraint on the upper bound for actual time taken */
BOOST_AUTO_TEST_CASE(get_next_work_upper_limit_actual)
{
const auto chainParams = CreateChainParams(CBaseChainParams::MAIN);
int64_t nLastRetargetTime = 1463690315; // NOTE: Not an actual block time
CBlockIndex pindexLast;
pindexLast.nHeight = 1001951;
pindexLast.nTime = 1464900315; // Block #1001951
pindexLast.nBits = 0x1b015318;
BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, chainParams->GetConsensus()), 0x1b015334);
}
BOOST_AUTO_TEST_CASE(GetBlockProofEquivalentTime_test)
{
const auto chainParams = CreateChainParams(CBaseChainParams::MAIN);
std::vector<CBlockIndex> blocks(10000);
for (int i = 0; i < 10000; i++) {
blocks[i].pprev = i ? &blocks[i - 1] : nullptr;
blocks[i].nHeight = i;
blocks[i].nTime = 1269211443 + i * chainParams->GetConsensus().nPowTargetSpacing;
blocks[i].nBits = 0x207fffff; /* target 0x7fffff000... */
blocks[i].nChainWork = i ? blocks[i - 1].nChainWork + GetBlockProof(blocks[i - 1]) : arith_uint256(0);
}
for (int j = 0; j < 1000; j++) {
CBlockIndex *p1 = &blocks[InsecureRandRange(10000)];
CBlockIndex *p2 = &blocks[InsecureRandRange(10000)];
CBlockIndex *p3 = &blocks[InsecureRandRange(10000)];
int64_t tdiff = GetBlockProofEquivalentTime(*p1, *p2, *p3, chainParams->GetConsensus());
BOOST_CHECK_EQUAL(tdiff, p1->GetBlockTime() - p2->GetBlockTime());
}
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>#include "test.h"
std::shared_ptr<tw::itask> generic_task() {
auto task = tw::make_task(tw::root, []{});
return task;
}
TEST_CASE("sequenced") {
tw::sequential seq;
int value = 5;
auto functor = [&value]{ value *= 2; };
seq.execute(functor, *generic_task().get());
REQUIRE(10 == value);
}
TEST_CASE("parallel") {
tw::parallel par(4);
std::atomic_bool done(false);
int value = 5;
auto functor = [&value, &done]{ value *= 2; done = true; };
par.execute(functor, *generic_task().get());
while (!done);
REQUIRE(10 == value);
}
TEST_CASE("schedule_all_without_executor") {
int x = 13;
auto task = tw::make_task(tw::root, [&x]{ x *= 2; });
task->schedule_all();
task->future().wait();
REQUIRE(26 == x);
}
TEST_CASE("schedule_all_without_executor_wait_method") {
int x = 13;
auto task = tw::make_task(tw::root, [&x]{ x *= 2; });
REQUIRE_THROWS_AS(task->wait(), tw::transwarp_error); // not scheduled yet
REQUIRE_THROWS_AS(task->get(), tw::transwarp_error); // not scheduled yet
task->schedule_all();
task->wait();
REQUIRE(26 == x);
}
TEST_CASE("schedule_all_with_task_specific_executor") {
int value = 42;
auto functor = [value] { return value*2; };
auto task = tw::make_task(tw::root, functor);
task->set_executor(std::make_shared<tw::sequential>());
task->schedule_all();
REQUIRE(84 == task->get());
}
TEST_CASE("invalid_task_specific_executor") {
auto task = tw::make_task(tw::root, []{});
REQUIRE_THROWS_AS(task->set_executor(nullptr), tw::transwarp_error);
}
TEST_CASE("parallel_with_zero_threads") {
REQUIRE_THROWS_AS(tw::parallel{0}, tw::invalid_parameter);
}
struct mock_exec : tw::executor {
bool called = false;
std::string name() const override {
return "mock_exec";
}
void execute(const std::function<void()>& functor, const tw::itask&) override {
called = true;
functor();
}
};
TEST_CASE("set_executor_name_and_reset") {
auto task = tw::make_task(tw::root, []{});
auto exec = std::make_shared<mock_exec>();
task->set_executor(exec);
REQUIRE(exec->name() == *task->node()->executor());
task->remove_executor();
REQUIRE_FALSE(task->node()->executor());
}
TEST_CASE("set_executor_without_exec_passed_to_schedule") {
int value = 42;
auto functor = [value] { return value*2; };
auto task = tw::make_task(tw::root, functor);
auto exec = std::make_shared<mock_exec>();
task->set_executor(exec);
task->schedule();
REQUIRE(exec->called);
REQUIRE(84 == task->future().get());
}
TEST_CASE("set_executor_with_exec_passed_to_schedule") {
int value = 42;
auto functor = [value] { return value*2; };
auto task = tw::make_task(tw::root, functor);
auto exec = std::make_shared<mock_exec>();
task->set_executor(exec);
tw::sequential exec_seq;
task->schedule(exec_seq);
REQUIRE(exec->called);
REQUIRE(84 == task->future().get());
}
TEST_CASE("remove_executor_with_exec_passed_to_schedule") {
int value = 42;
auto functor = [value] { return value*2; };
auto task = tw::make_task(tw::root, functor);
auto exec = std::make_shared<mock_exec>();
task->set_executor(exec);
task->remove_executor();
mock_exec exec_seq;
task->schedule(exec_seq);
REQUIRE_FALSE(exec->called);
REQUIRE(exec_seq.called);
REQUIRE(84 == task->future().get());
}
TEST_CASE("set_executor_all") {
auto t1 = tw::make_task(tw::root, []{});
auto t2 = tw::make_task(tw::wait, []{}, t1);
auto exec = std::make_shared<tw::sequential>();
t2->set_executor_all(exec);
REQUIRE(*(t1->node()->executor()) == exec->name());
REQUIRE(*(t2->node()->executor()) == exec->name());
}
TEST_CASE("remove_executor_all") {
auto t1 = tw::make_task(tw::root, []{});
auto t2 = tw::make_task(tw::wait, []{}, t1);
auto exec = std::make_shared<tw::sequential>();
t2->set_executor_all(exec);
REQUIRE(*(t1->node()->executor()) == exec->name());
REQUIRE(*(t2->node()->executor()) == exec->name());
t2->remove_executor_all();
REQUIRE_FALSE(t1->node()->executor());
REQUIRE_FALSE(t2->node()->executor());
}
<commit_msg>Small cleanup.<commit_after>#include "test.h"
std::shared_ptr<tw::itask> generic_task() {
auto task = tw::make_task(tw::root, []{});
return task;
}
TEST_CASE("sequenced") {
tw::sequential seq;
int value = 5;
auto functor = [&value]{ value *= 2; };
seq.execute(functor, *generic_task());
REQUIRE(10 == value);
}
TEST_CASE("parallel") {
tw::parallel par(4);
std::atomic_bool done(false);
int value = 5;
auto functor = [&value, &done]{ value *= 2; done = true; };
par.execute(functor, *generic_task());
while (!done);
REQUIRE(10 == value);
}
TEST_CASE("schedule_all_without_executor") {
int x = 13;
auto task = tw::make_task(tw::root, [&x]{ x *= 2; });
task->schedule_all();
task->future().wait();
REQUIRE(26 == x);
}
TEST_CASE("schedule_all_without_executor_wait_method") {
int x = 13;
auto task = tw::make_task(tw::root, [&x]{ x *= 2; });
REQUIRE_THROWS_AS(task->wait(), tw::transwarp_error); // not scheduled yet
REQUIRE_THROWS_AS(task->get(), tw::transwarp_error); // not scheduled yet
task->schedule_all();
task->wait();
REQUIRE(26 == x);
}
TEST_CASE("schedule_all_with_task_specific_executor") {
int value = 42;
auto functor = [value] { return value*2; };
auto task = tw::make_task(tw::root, functor);
task->set_executor(std::make_shared<tw::sequential>());
task->schedule_all();
REQUIRE(84 == task->get());
}
TEST_CASE("invalid_task_specific_executor") {
auto task = tw::make_task(tw::root, []{});
REQUIRE_THROWS_AS(task->set_executor(nullptr), tw::transwarp_error);
}
TEST_CASE("parallel_with_zero_threads") {
REQUIRE_THROWS_AS(tw::parallel{0}, tw::invalid_parameter);
}
struct mock_exec : tw::executor {
bool called = false;
std::string name() const override {
return "mock_exec";
}
void execute(const std::function<void()>& functor, const tw::itask&) override {
called = true;
functor();
}
};
TEST_CASE("set_executor_name_and_reset") {
auto task = tw::make_task(tw::root, []{});
auto exec = std::make_shared<mock_exec>();
task->set_executor(exec);
REQUIRE(exec->name() == *task->node()->executor());
task->remove_executor();
REQUIRE_FALSE(task->node()->executor());
}
TEST_CASE("set_executor_without_exec_passed_to_schedule") {
int value = 42;
auto functor = [value] { return value*2; };
auto task = tw::make_task(tw::root, functor);
auto exec = std::make_shared<mock_exec>();
task->set_executor(exec);
task->schedule();
REQUIRE(exec->called);
REQUIRE(84 == task->future().get());
}
TEST_CASE("set_executor_with_exec_passed_to_schedule") {
int value = 42;
auto functor = [value] { return value*2; };
auto task = tw::make_task(tw::root, functor);
auto exec = std::make_shared<mock_exec>();
task->set_executor(exec);
tw::sequential exec_seq;
task->schedule(exec_seq);
REQUIRE(exec->called);
REQUIRE(84 == task->future().get());
}
TEST_CASE("remove_executor_with_exec_passed_to_schedule") {
int value = 42;
auto functor = [value] { return value*2; };
auto task = tw::make_task(tw::root, functor);
auto exec = std::make_shared<mock_exec>();
task->set_executor(exec);
task->remove_executor();
mock_exec exec_seq;
task->schedule(exec_seq);
REQUIRE_FALSE(exec->called);
REQUIRE(exec_seq.called);
REQUIRE(84 == task->future().get());
}
TEST_CASE("set_executor_all") {
auto t1 = tw::make_task(tw::root, []{});
auto t2 = tw::make_task(tw::wait, []{}, t1);
auto exec = std::make_shared<tw::sequential>();
t2->set_executor_all(exec);
REQUIRE(*(t1->node()->executor()) == exec->name());
REQUIRE(*(t2->node()->executor()) == exec->name());
}
TEST_CASE("remove_executor_all") {
auto t1 = tw::make_task(tw::root, []{});
auto t2 = tw::make_task(tw::wait, []{}, t1);
auto exec = std::make_shared<tw::sequential>();
t2->set_executor_all(exec);
REQUIRE(*(t1->node()->executor()) == exec->name());
REQUIRE(*(t2->node()->executor()) == exec->name());
t2->remove_executor_all();
REQUIRE_FALSE(t1->node()->executor());
REQUIRE_FALSE(t2->node()->executor());
}
<|endoftext|> |
<commit_before>/*****************************************************************************\
* ANALYSIS PERFORMANCE TOOLS *
* libparaver-api *
* Paraver Main Computing Library *
*****************************************************************************
* ___ This library is free software; you can redistribute it and/or *
* / __ modify it under the terms of the GNU LGPL as published *
* / / _____ by the Free Software Foundation; either version 2.1 *
* / / / \ of the License, or (at your option) any later version. *
* ( ( ( B S C ) *
* \ \ \_____/ This library is distributed in 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 LGPL for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
* The GNU LEsser General Public License is contained in the file COPYING. *
* --------- *
* Barcelona Supercomputing Center - Centro Nacional de Supercomputacion *
\*****************************************************************************/
#include <iostream>
#include <string>
#include <sstream>
#include <type_traits>
#include "tracebodyio_v1.h"
using namespace std;
string TraceBodyIO_v1::multiEventLine;
TraceBodyIO_v1::TMultiEventCommonInfo TraceBodyIO_v1::multiEventCommonInfo =
{ nullptr, (TThreadOrder)0, (TCPUOrder)0, (TRecordTime)0 };
string TraceBodyIO_v1::line;
ostringstream TraceBodyIO_v1::ostr;
// Optimization on conversion string to numbers, but with no error control
//#define USE_ATOLL
// Even more optimization using custom function instead of atoll with error checking
#define USE_PRV_ATOLL
constexpr bool prv_atoll_v( string::const_iterator& it, const string::const_iterator& end )
{
return true;
}
template <typename T, typename... Targs>
constexpr bool prv_atoll_v( string::const_iterator& it, const string::const_iterator& end, T& result, Targs&... Fargs )
{
result = 0;
int negative = 1;
if( it == end )
return false;
if( *it == '-' )
{
if( is_unsigned<T>::value )
return false;
negative = -1;
++it;
}
if( *it >= '0' && *it <= '9' )
{
result = ( *it++ - '0' );
while( *it >= '0' && *it <= '9' )
result = ( result * 10 ) + ( *it++ - '0' );
result *= negative;
}
if( it == end )
return sizeof...( Targs ) == 0;
return prv_atoll_v( ++it, end, Fargs... );
}
TraceBodyIO_v1::TraceBodyIO_v1( Trace* trace )
: whichTrace( trace )
{}
bool TraceBodyIO_v1::ordered() const
{
return false;
}
void TraceBodyIO_v1::read( TraceStream *file, MemoryBlocks& records,
unordered_set<TState>& states, unordered_set<TEventType>& events,
MetadataManager& traceInfo, TRecordTime& endTime ) const
{
file->getline( line );
if ( line.size() == 0 )
return;
switch ( line[0] )
{
case CommentRecord:
readTraceInfo( line, traceInfo );
break;
case StateRecord:
readState( line, records, states );
break;
case EventRecord:
readEvent( line, records, events );
break;
case CommRecord:
readComm( line, records );
break;
case GlobalCommRecord:
//readGlobalComm( line, records );
break;
default:
cerr << "TraceBodyIO_v1::read()" << endl;
cerr << "Unkwnown record type." << endl;
break;
};
}
void TraceBodyIO_v1::bufferWrite( fstream& whichStream, bool writeReady, bool lineClear ) const
{
if ( writeReady )
{
whichStream << line << '\n';
if ( lineClear )
line.clear();
}
}
void TraceBodyIO_v1::write( fstream& whichStream,
const KTrace& whichTrace,
MemoryTrace::iterator *record,
PRV_INT32 numIter ) const
{
bool writeReady = false;
TRecordType type = record->getType();
line.clear();
if ( type == EMPTYREC )
{
writeReady = writePendingMultiEvent( whichTrace );
bufferWrite( whichStream, writeReady );
}
else
{
if ( type & STATE )
{
writeReady = writePendingMultiEvent( whichTrace );
bufferWrite( whichStream, writeReady );
writeReady = writeState( whichTrace, record );
}
else if ( type & EVENT )
{
if ( !sameMultiEvent( record ) )
{
writeReady = writePendingMultiEvent( whichTrace );
multiEventCommonInfo.myStream = &whichStream;
multiEventCommonInfo.cpu = record->getCPU();
multiEventCommonInfo.thread = record->getThread();
multiEventCommonInfo.time = record->getTime();
multiEventLine.clear();
}
appendEvent( record );
}
else if ( type & COMM )
{
writeReady = writePendingMultiEvent( whichTrace );
bufferWrite( whichStream, writeReady );
writeReady = writeComm( whichTrace, record );
}
else if ( type & GLOBCOMM )
{
writeReady = writePendingMultiEvent( whichTrace );
bufferWrite( whichStream, writeReady );
writeReady = writeGlobalComm( whichTrace, record );
}
else if ( type & RSEND || type & RRECV )
writeReady = false;
else
{
writeReady = false;
cerr << "TraceBodyIO_v1::write()" << endl;
cerr << "Unkwnown record type in memory." << endl;
}
bufferWrite( whichStream, writeReady, false );
}
}
void TraceBodyIO_v1::writeCommInfo( fstream& whichStream,
const KTrace& whichTrace,
PRV_INT32 numIter ) const
{}
/**********************
Read line functions
***********************/
inline void TraceBodyIO_v1::readTraceInfo( const std::string& line, MetadataManager& traceInfo ) const
{
traceInfo.NewMetadata( line );
// dummy set also to false if it is a comment
}
inline void TraceBodyIO_v1::readState( const string& line, MemoryBlocks& records,
unordered_set<TState>& states ) const
{
TCPUOrder CPU;
TApplOrder appl;
TTaskOrder task;
TThreadOrder thread;
TRecordTime time;
TRecordTime endtime;
TState state;
auto it = line.begin() + 2;
// Read the common info
if ( !readCommon( it, line.cend(), CPU, appl, task, thread, time ) )
{
cerr << "Error reading state record." << endl;
cerr << line << endl;
return;
}
if( !prv_atoll_v( it, line.cend(), endtime, state ) )
{
cerr << "Error reading state record." << endl;
cerr << line << endl;
return;
}
records.newRecord();
records.setType( STATE + BEGIN );
records.setTime( time );
records.setCPU( CPU );
records.setThread( appl - 1, task - 1, thread - 1 );
records.setState( state );
records.setStateEndTime( endtime );
if ( endtime != -1 )
{
records.newRecord();
records.setType( STATE + END );
records.setTime( endtime );
records.setCPU( CPU );
records.setThread( appl - 1, task - 1, thread - 1 );
records.setState( state );
records.setStateEndTime( time );
}
states.insert( state );
}
inline void TraceBodyIO_v1::readEvent( const string& line, MemoryBlocks& records,
unordered_set<TEventType>& events ) const
{
TCPUOrder CPU;
TApplOrder appl;
TTaskOrder task;
TThreadOrder thread;
TRecordTime time;
TEventType eventtype;
TEventValue eventvalue;
auto it = line.begin() + 2;
// Read the common info
if ( !readCommon( it, line.cend(), CPU, appl, task, thread, time ) )
{
cerr << "Error reading event record." << endl;
cerr << line << endl;
return;
}
while ( it != line.end() )
{
if( !prv_atoll_v( it, line.cend(), eventtype, eventvalue ) )
{
cerr << "Error reading event record." << endl;
cerr << line << endl;
return;
}
records.newRecord();
records.setType( EVENT );
records.setTime( time );
records.setCPU( CPU );
records.setThread( appl - 1, task - 1, thread - 1 );
records.setEventType( eventtype );
records.setEventValue( eventvalue );
events.insert( eventtype );
}
}
inline void TraceBodyIO_v1::readComm( const string& line, MemoryBlocks& records ) const
{
TCPUOrder CPU;
TApplOrder appl;
TTaskOrder task;
TThreadOrder thread;
TRecordTime logSend;
TRecordTime phySend;
TRecordTime logReceive;
TRecordTime phyReceive;
TCPUOrder remoteCPU;
TApplOrder remoteAppl;
TTaskOrder remoteTask;
TThreadOrder remoteThread;
TCommSize commSize;
TCommTag commTag;
auto it = line.begin() + 2;
// Read the common info
if ( !readCommon( it, line.cend(), CPU, appl, task, thread, logSend ) )
{
cerr << "Error reading communication record." << endl;
cerr << line << endl;
return;
}
if( !prv_atoll_v( it, line.cend(), phySend, remoteCPU, remoteAppl, remoteTask, remoteThread, logReceive, phyReceive, commSize, commTag ) )
{
cerr << "Error reading communication record." << endl;
cerr << line << endl;
return;
}
records.newComm();
records.setSenderCPU( CPU );
records.setSenderThread( appl - 1, task - 1, thread - 1 );
records.setReceiverCPU( remoteCPU );
records.setReceiverThread( remoteAppl - 1, remoteTask - 1, remoteThread - 1 );
records.setLogicalSend( logSend );
records.setPhysicalSend( phySend );
records.setLogicalReceive( logReceive );
records.setPhysicalReceive( phyReceive );
records.setCommSize( commSize );
records.setCommTag( commTag );
}
inline void TraceBodyIO_v1::readGlobalComm( const string& line, MemoryBlocks& records ) const
{}
inline bool TraceBodyIO_v1::readCommon( string::const_iterator& it,
const string::const_iterator& end,
TCPUOrder& CPU,
TApplOrder& appl,
TTaskOrder& task,
TThreadOrder& thread,
TRecordTime& time ) const
{
return prv_atoll_v( it, end, CPU, appl, task, thread, time ) &&
resourceModel->isValidGlobalCPU( CPU ) &&
processModel->isValidThread( appl - 1, task - 1, thread - 1 );
}
/**************************
Write records functions
***************************/
bool TraceBodyIO_v1::writeState( const KTrace& whichTrace,
const MemoryTrace::iterator *record ) const
{
if ( record->getType() & END )
return false;
ostr.clear();
ostr.str( "" );
ostr << fixed;
ostr << dec;
ostr.precision( 0 );
ostr << StateRecord << ':';
writeCommon( ostr, whichTrace, record );
ostr << record->getStateEndTime() << ':' << record->getState();
line += ostr.str();
return true;
}
bool TraceBodyIO_v1::writePendingMultiEvent( const KTrace& whichTrace ) const
{
TApplOrder appl;
TTaskOrder task;
TThreadOrder thread;
bool writeLine = !multiEventLine.empty();
if ( writeLine )
{
ostr.clear();
ostr.str( "" );
ostr << fixed;
ostr << dec;
ostr.precision( 0 );
ostr << EventRecord << ':';
ostr << multiEventCommonInfo.cpu << ':';
whichTrace.getThreadLocation( multiEventCommonInfo.thread, appl, task, thread );
ostr << appl + 1 << ':' << task + 1 << ':' << thread + 1 << ':';
ostr << multiEventCommonInfo.time << ':';
ostr << multiEventLine;
line += ostr.str();
bufferWrite( *multiEventCommonInfo.myStream, true );
multiEventCommonInfo.myStream = nullptr;
multiEventCommonInfo.cpu = 0;
multiEventCommonInfo.thread = 0;
multiEventCommonInfo.time = 0;
multiEventLine.clear();
}
return false;
}
void TraceBodyIO_v1::appendEvent( const MemoryTrace::iterator *record ) const
{
ostr.clear();
ostr.str( "" );
ostr << fixed;
ostr << dec;
ostr.precision( 0 );
if ( !multiEventLine.empty() )
ostr << ':';
ostr << record->getEventType() << ':' << record->getEventValueAsIs();
multiEventLine += ostr.str();
}
bool TraceBodyIO_v1::writeComm( const KTrace& whichTrace,
const MemoryTrace::iterator *record ) const
{
TCommID commID;
TApplOrder recvAppl;
TTaskOrder recvTask;
TThreadOrder recvThread;
ostr.clear();
ostr.str( "" );
ostr << fixed;
ostr << dec;
ostr.precision( 0 );
if ( !( record->getType() == ( COMM + LOG + SEND ) ) )
return false;
commID = record->getCommIndex();
ostr << CommRecord << ':';
writeCommon( ostr, whichTrace, record );
ostr << whichTrace.getPhysicalSend( commID ) << ':';
if ( whichTrace.existResourceInfo() )
ostr << whichTrace.getReceiverCPU( commID ) << ':';
else
ostr << '0' << ':';
whichTrace.getThreadLocation( whichTrace.getReceiverThread( commID ),
recvAppl, recvTask, recvThread );
ostr << recvAppl + 1 << ':' << recvTask + 1 << ':' << recvThread + 1 << ':';
ostr << whichTrace.getLogicalReceive( commID ) << ':';
ostr << whichTrace.getPhysicalReceive( commID ) << ':';
ostr << whichTrace.getCommSize( commID ) << ':';
ostr << whichTrace.getCommTag( commID );
line += ostr.str();
return true;
}
bool TraceBodyIO_v1::writeGlobalComm( const KTrace& whichTrace,
const MemoryTrace::iterator *record ) const
{
return true;
}
void TraceBodyIO_v1::writeCommon( ostringstream& line,
const KTrace& whichTrace,
const MemoryTrace::iterator *record ) const
{
TApplOrder appl;
TTaskOrder task;
TThreadOrder thread;
if ( whichTrace.existResourceInfo() )
line << record->getCPU() << ':';
else
line << '0' << ':';
whichTrace.getThreadLocation( record->getThread(), appl, task, thread );
line << appl + 1 << ':' << task + 1 << ':' << thread + 1 << ':';
line << record->getTime() << ':';
}
bool TraceBodyIO_v1::sameMultiEvent( const MemoryTrace::iterator *record ) const
{
return ( multiEventCommonInfo.cpu == record->getCPU() &&
multiEventCommonInfo.thread == record->getThread() &&
multiEventCommonInfo.time == record->getTime() );
}
<commit_msg>Write 'line' when unkwnown record is read from trace.<commit_after>/*****************************************************************************\
* ANALYSIS PERFORMANCE TOOLS *
* libparaver-api *
* Paraver Main Computing Library *
*****************************************************************************
* ___ This library is free software; you can redistribute it and/or *
* / __ modify it under the terms of the GNU LGPL as published *
* / / _____ by the Free Software Foundation; either version 2.1 *
* / / / \ of the License, or (at your option) any later version. *
* ( ( ( B S C ) *
* \ \ \_____/ This library is distributed in 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 LGPL for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
* The GNU LEsser General Public License is contained in the file COPYING. *
* --------- *
* Barcelona Supercomputing Center - Centro Nacional de Supercomputacion *
\*****************************************************************************/
#include <iostream>
#include <string>
#include <sstream>
#include <type_traits>
#include "tracebodyio_v1.h"
using namespace std;
string TraceBodyIO_v1::multiEventLine;
TraceBodyIO_v1::TMultiEventCommonInfo TraceBodyIO_v1::multiEventCommonInfo =
{ nullptr, (TThreadOrder)0, (TCPUOrder)0, (TRecordTime)0 };
string TraceBodyIO_v1::line;
ostringstream TraceBodyIO_v1::ostr;
// Optimization on conversion string to numbers, but with no error control
//#define USE_ATOLL
// Even more optimization using custom function instead of atoll with error checking
#define USE_PRV_ATOLL
constexpr bool prv_atoll_v( string::const_iterator& it, const string::const_iterator& end )
{
return true;
}
template <typename T, typename... Targs>
constexpr bool prv_atoll_v( string::const_iterator& it, const string::const_iterator& end, T& result, Targs&... Fargs )
{
result = 0;
int negative = 1;
if( it == end )
return false;
if( *it == '-' )
{
if( is_unsigned<T>::value )
return false;
negative = -1;
++it;
}
if( *it >= '0' && *it <= '9' )
{
result = ( *it++ - '0' );
while( *it >= '0' && *it <= '9' )
result = ( result * 10 ) + ( *it++ - '0' );
result *= negative;
}
if( it == end )
return sizeof...( Targs ) == 0;
return prv_atoll_v( ++it, end, Fargs... );
}
TraceBodyIO_v1::TraceBodyIO_v1( Trace* trace )
: whichTrace( trace )
{}
bool TraceBodyIO_v1::ordered() const
{
return false;
}
void TraceBodyIO_v1::read( TraceStream *file, MemoryBlocks& records,
unordered_set<TState>& states, unordered_set<TEventType>& events,
MetadataManager& traceInfo, TRecordTime& endTime ) const
{
file->getline( line );
if ( line.size() == 0 )
return;
switch ( line[0] )
{
case CommentRecord:
readTraceInfo( line, traceInfo );
break;
case StateRecord:
readState( line, records, states );
break;
case EventRecord:
readEvent( line, records, events );
break;
case CommRecord:
readComm( line, records );
break;
case GlobalCommRecord:
//readGlobalComm( line, records );
break;
default:
cerr << "Unkwnown record type." << endl;
cerr << line << endl;
break;
};
}
void TraceBodyIO_v1::bufferWrite( fstream& whichStream, bool writeReady, bool lineClear ) const
{
if ( writeReady )
{
whichStream << line << '\n';
if ( lineClear )
line.clear();
}
}
void TraceBodyIO_v1::write( fstream& whichStream,
const KTrace& whichTrace,
MemoryTrace::iterator *record,
PRV_INT32 numIter ) const
{
bool writeReady = false;
TRecordType type = record->getType();
line.clear();
if ( type == EMPTYREC )
{
writeReady = writePendingMultiEvent( whichTrace );
bufferWrite( whichStream, writeReady );
}
else
{
if ( type & STATE )
{
writeReady = writePendingMultiEvent( whichTrace );
bufferWrite( whichStream, writeReady );
writeReady = writeState( whichTrace, record );
}
else if ( type & EVENT )
{
if ( !sameMultiEvent( record ) )
{
writeReady = writePendingMultiEvent( whichTrace );
multiEventCommonInfo.myStream = &whichStream;
multiEventCommonInfo.cpu = record->getCPU();
multiEventCommonInfo.thread = record->getThread();
multiEventCommonInfo.time = record->getTime();
multiEventLine.clear();
}
appendEvent( record );
}
else if ( type & COMM )
{
writeReady = writePendingMultiEvent( whichTrace );
bufferWrite( whichStream, writeReady );
writeReady = writeComm( whichTrace, record );
}
else if ( type & GLOBCOMM )
{
writeReady = writePendingMultiEvent( whichTrace );
bufferWrite( whichStream, writeReady );
writeReady = writeGlobalComm( whichTrace, record );
}
else if ( type & RSEND || type & RRECV )
writeReady = false;
else
{
writeReady = false;
cerr << "TraceBodyIO_v1::write()" << endl;
cerr << "Unkwnown record type in memory." << endl;
}
bufferWrite( whichStream, writeReady, false );
}
}
void TraceBodyIO_v1::writeCommInfo( fstream& whichStream,
const KTrace& whichTrace,
PRV_INT32 numIter ) const
{}
/**********************
Read line functions
***********************/
inline void TraceBodyIO_v1::readTraceInfo( const std::string& line, MetadataManager& traceInfo ) const
{
traceInfo.NewMetadata( line );
// dummy set also to false if it is a comment
}
inline void TraceBodyIO_v1::readState( const string& line, MemoryBlocks& records,
unordered_set<TState>& states ) const
{
TCPUOrder CPU;
TApplOrder appl;
TTaskOrder task;
TThreadOrder thread;
TRecordTime time;
TRecordTime endtime;
TState state;
auto it = line.begin() + 2;
// Read the common info
if ( !readCommon( it, line.cend(), CPU, appl, task, thread, time ) )
{
cerr << "Error reading state record." << endl;
cerr << line << endl;
return;
}
if( !prv_atoll_v( it, line.cend(), endtime, state ) )
{
cerr << "Error reading state record." << endl;
cerr << line << endl;
return;
}
records.newRecord();
records.setType( STATE + BEGIN );
records.setTime( time );
records.setCPU( CPU );
records.setThread( appl - 1, task - 1, thread - 1 );
records.setState( state );
records.setStateEndTime( endtime );
if ( endtime != -1 )
{
records.newRecord();
records.setType( STATE + END );
records.setTime( endtime );
records.setCPU( CPU );
records.setThread( appl - 1, task - 1, thread - 1 );
records.setState( state );
records.setStateEndTime( time );
}
states.insert( state );
}
inline void TraceBodyIO_v1::readEvent( const string& line, MemoryBlocks& records,
unordered_set<TEventType>& events ) const
{
TCPUOrder CPU;
TApplOrder appl;
TTaskOrder task;
TThreadOrder thread;
TRecordTime time;
TEventType eventtype;
TEventValue eventvalue;
auto it = line.begin() + 2;
// Read the common info
if ( !readCommon( it, line.cend(), CPU, appl, task, thread, time ) )
{
cerr << "Error reading event record." << endl;
cerr << line << endl;
return;
}
while ( it != line.end() )
{
if( !prv_atoll_v( it, line.cend(), eventtype, eventvalue ) )
{
cerr << "Error reading event record." << endl;
cerr << line << endl;
return;
}
records.newRecord();
records.setType( EVENT );
records.setTime( time );
records.setCPU( CPU );
records.setThread( appl - 1, task - 1, thread - 1 );
records.setEventType( eventtype );
records.setEventValue( eventvalue );
events.insert( eventtype );
}
}
inline void TraceBodyIO_v1::readComm( const string& line, MemoryBlocks& records ) const
{
TCPUOrder CPU;
TApplOrder appl;
TTaskOrder task;
TThreadOrder thread;
TRecordTime logSend;
TRecordTime phySend;
TRecordTime logReceive;
TRecordTime phyReceive;
TCPUOrder remoteCPU;
TApplOrder remoteAppl;
TTaskOrder remoteTask;
TThreadOrder remoteThread;
TCommSize commSize;
TCommTag commTag;
auto it = line.begin() + 2;
// Read the common info
if ( !readCommon( it, line.cend(), CPU, appl, task, thread, logSend ) )
{
cerr << "Error reading communication record." << endl;
cerr << line << endl;
return;
}
if( !prv_atoll_v( it, line.cend(), phySend, remoteCPU, remoteAppl, remoteTask, remoteThread, logReceive, phyReceive, commSize, commTag ) )
{
cerr << "Error reading communication record." << endl;
cerr << line << endl;
return;
}
records.newComm();
records.setSenderCPU( CPU );
records.setSenderThread( appl - 1, task - 1, thread - 1 );
records.setReceiverCPU( remoteCPU );
records.setReceiverThread( remoteAppl - 1, remoteTask - 1, remoteThread - 1 );
records.setLogicalSend( logSend );
records.setPhysicalSend( phySend );
records.setLogicalReceive( logReceive );
records.setPhysicalReceive( phyReceive );
records.setCommSize( commSize );
records.setCommTag( commTag );
}
inline void TraceBodyIO_v1::readGlobalComm( const string& line, MemoryBlocks& records ) const
{}
inline bool TraceBodyIO_v1::readCommon( string::const_iterator& it,
const string::const_iterator& end,
TCPUOrder& CPU,
TApplOrder& appl,
TTaskOrder& task,
TThreadOrder& thread,
TRecordTime& time ) const
{
return prv_atoll_v( it, end, CPU, appl, task, thread, time ) &&
resourceModel->isValidGlobalCPU( CPU ) &&
processModel->isValidThread( appl - 1, task - 1, thread - 1 );
}
/**************************
Write records functions
***************************/
bool TraceBodyIO_v1::writeState( const KTrace& whichTrace,
const MemoryTrace::iterator *record ) const
{
if ( record->getType() & END )
return false;
ostr.clear();
ostr.str( "" );
ostr << fixed;
ostr << dec;
ostr.precision( 0 );
ostr << StateRecord << ':';
writeCommon( ostr, whichTrace, record );
ostr << record->getStateEndTime() << ':' << record->getState();
line += ostr.str();
return true;
}
bool TraceBodyIO_v1::writePendingMultiEvent( const KTrace& whichTrace ) const
{
TApplOrder appl;
TTaskOrder task;
TThreadOrder thread;
bool writeLine = !multiEventLine.empty();
if ( writeLine )
{
ostr.clear();
ostr.str( "" );
ostr << fixed;
ostr << dec;
ostr.precision( 0 );
ostr << EventRecord << ':';
ostr << multiEventCommonInfo.cpu << ':';
whichTrace.getThreadLocation( multiEventCommonInfo.thread, appl, task, thread );
ostr << appl + 1 << ':' << task + 1 << ':' << thread + 1 << ':';
ostr << multiEventCommonInfo.time << ':';
ostr << multiEventLine;
line += ostr.str();
bufferWrite( *multiEventCommonInfo.myStream, true );
multiEventCommonInfo.myStream = nullptr;
multiEventCommonInfo.cpu = 0;
multiEventCommonInfo.thread = 0;
multiEventCommonInfo.time = 0;
multiEventLine.clear();
}
return false;
}
void TraceBodyIO_v1::appendEvent( const MemoryTrace::iterator *record ) const
{
ostr.clear();
ostr.str( "" );
ostr << fixed;
ostr << dec;
ostr.precision( 0 );
if ( !multiEventLine.empty() )
ostr << ':';
ostr << record->getEventType() << ':' << record->getEventValueAsIs();
multiEventLine += ostr.str();
}
bool TraceBodyIO_v1::writeComm( const KTrace& whichTrace,
const MemoryTrace::iterator *record ) const
{
TCommID commID;
TApplOrder recvAppl;
TTaskOrder recvTask;
TThreadOrder recvThread;
ostr.clear();
ostr.str( "" );
ostr << fixed;
ostr << dec;
ostr.precision( 0 );
if ( !( record->getType() == ( COMM + LOG + SEND ) ) )
return false;
commID = record->getCommIndex();
ostr << CommRecord << ':';
writeCommon( ostr, whichTrace, record );
ostr << whichTrace.getPhysicalSend( commID ) << ':';
if ( whichTrace.existResourceInfo() )
ostr << whichTrace.getReceiverCPU( commID ) << ':';
else
ostr << '0' << ':';
whichTrace.getThreadLocation( whichTrace.getReceiverThread( commID ),
recvAppl, recvTask, recvThread );
ostr << recvAppl + 1 << ':' << recvTask + 1 << ':' << recvThread + 1 << ':';
ostr << whichTrace.getLogicalReceive( commID ) << ':';
ostr << whichTrace.getPhysicalReceive( commID ) << ':';
ostr << whichTrace.getCommSize( commID ) << ':';
ostr << whichTrace.getCommTag( commID );
line += ostr.str();
return true;
}
bool TraceBodyIO_v1::writeGlobalComm( const KTrace& whichTrace,
const MemoryTrace::iterator *record ) const
{
return true;
}
void TraceBodyIO_v1::writeCommon( ostringstream& line,
const KTrace& whichTrace,
const MemoryTrace::iterator *record ) const
{
TApplOrder appl;
TTaskOrder task;
TThreadOrder thread;
if ( whichTrace.existResourceInfo() )
line << record->getCPU() << ':';
else
line << '0' << ':';
whichTrace.getThreadLocation( record->getThread(), appl, task, thread );
line << appl + 1 << ':' << task + 1 << ':' << thread + 1 << ':';
line << record->getTime() << ':';
}
bool TraceBodyIO_v1::sameMultiEvent( const MemoryTrace::iterator *record ) const
{
return ( multiEventCommonInfo.cpu == record->getCPU() &&
multiEventCommonInfo.thread == record->getThread() &&
multiEventCommonInfo.time == record->getTime() );
}
<|endoftext|> |
<commit_before>#include "glm/gtc/matrix_transform.hpp"
#include "Object.hh"
GLnewin::Object::Object() : _mesh({-1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f}), _rotPosScale(NULL) {
_shader.setVertex(GLnewin::Shader::fileToString("vert.glsl"));
_shader.setFragment(GLnewin::Shader::fileToString("frag.glsl"));
_shader.link();
_mesh.setShader(&_shader);
_rotPosScale = new Uniform<glm::mat4>(_shader.genUniform(glm::mat4(), "object"));
}
void GLnewin::Object::draw() noexcept {
_mesh.draw();
}
void GLnewin::Object::setPos(const glm::vec3& v) noexcept {
_pos = v;
*_rotPosScale = glm::translate(glm::mat4(), _pos);
_rotPosScale->upload();
}
void GLnewin::Object::setRot(const glm::vec3& v) noexcept {
_rot = v;
}
void GLnewin::Object::setScale(const glm::vec3& v) noexcept {
_scale = v;
}
<commit_msg>mistake<commit_after>#include "glm/gtc/matrix_transform.hpp"
#include "Object.hh"
GLnewin::Object::Object() : _mesh({-1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f}), _rotPosScale(NULL) {
_shader.setVertex(GLnewin::Shader::fileToString("shaders/vert.glsl"));
_shader.setFragment(GLnewin::Shader::fileToString("shaders/frag.glsl"));
_shader.link();
_mesh.setShader(&_shader);
_rotPosScale = new Uniform<glm::mat4>(_shader.genUniform(glm::mat4(), "object"));
}
void GLnewin::Object::draw() noexcept {
_mesh.draw();
}
void GLnewin::Object::setPos(const glm::vec3& v) noexcept {
_pos = v;
*_rotPosScale = glm::translate(glm::mat4(), _pos);
_rotPosScale->upload();
}
void GLnewin::Object::setRot(const glm::vec3& v) noexcept {
_rot = v;
}
void GLnewin::Object::setScale(const glm::vec3& v) noexcept {
_scale = v;
}
<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2011, Willow Garage, Inc.
* Copyright (c) 2012-, Open Perception, 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.
*
*/
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/common/time.h> //fps calculations
#include <pcl/io/openni_grabber.h>
#include <pcl/visualization/boost.h>
#include <pcl/visualization/common/float_image_utils.h>
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/visualization/image_viewer.h>
#include <pcl/io/openni_camera/openni_driver.h>
#include <pcl/console/parse.h>
#include <pcl/visualization/mouse_event.h>
using namespace std;
#define SHOW_FPS 1
#if SHOW_FPS
#define FPS_CALC(_WHAT_) \
do \
{ \
static unsigned count = 0;\
static double last = pcl::getTime ();\
double now = pcl::getTime (); \
++count; \
if (now - last >= 1.0) \
{ \
std::cout << "Average framerate("<< _WHAT_ << "): " << double(count)/double(now - last) << " Hz" << std::endl; \
count = 0; \
last = now; \
} \
}while(false)
#else
#define FPS_CALC(_WHAT_) \
do \
{ \
}while(false)
#endif
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class SimpleOpenNIViewer
{
public:
SimpleOpenNIViewer (pcl::OpenNIGrabber& grabber)
: grabber_ (grabber),
image_viewer_ ("PCL/OpenNI RGB image viewer"),
depth_image_viewer_ ("PCL/OpenNI depth image viewer"),
image_cld_init_ (false), depth_image_cld_init_ (false),
rgb_data_ (0), depth_data_ (0), rgb_data_size_ (0)
{
}
void
image_callback (const boost::shared_ptr<openni_wrapper::Image> &image,
const boost::shared_ptr<openni_wrapper::DepthImage> &depth_image, float)
{
FPS_CALC ("image callback");
boost::mutex::scoped_lock lock (image_mutex_);
// Copy data
image_ = image;
if (image->getEncoding() != openni_wrapper::Image::RGB)
{
if (rgb_data_size_ < image->getWidth () * image->getHeight ())
{
if (rgb_data_)
delete [] rgb_data_;
rgb_data_size_ = image->getWidth () * image->getHeight ();
rgb_data_ = new unsigned char [rgb_data_size_ * 3];
}
image_->fillRGB (image_->getWidth (), image_->getHeight (), rgb_data_);
}
// Copy data
depth_image_ = depth_image;
if (depth_data_)
delete[] depth_data_;
depth_data_ = pcl::visualization::FloatImageUtils::getVisualImage (
reinterpret_cast<const unsigned short*> (depth_image->getDepthMetaData ().Data ()),
depth_image->getWidth (), depth_image->getHeight (),
std::numeric_limits<unsigned short>::min (),
// Scale so that the colors look brigher on screen
std::numeric_limits<unsigned short>::max () / 10,
true);
}
void
keyboard_callback (const pcl::visualization::KeyboardEvent& event, void* cookie)
{
string* message = static_cast<string*> (cookie);
cout << (*message) << " :: ";
if (event.getKeyCode ())
cout << "the key \'" << event.getKeyCode () << "\' (" << event.getKeyCode () << ") was";
else
cout << "the special key \'" << event.getKeySym () << "\' was";
if (event.keyDown ())
cout << " pressed" << endl;
else
cout << " released" << endl;
}
void
mouse_callback (const pcl::visualization::MouseEvent& mouse_event, void* cookie)
{
string* message = static_cast<string*> (cookie);
if (mouse_event.getType () == pcl::visualization::MouseEvent::MouseButtonPress && mouse_event.getButton () == pcl::visualization::MouseEvent::LeftButton)
{
cout << (*message) << " :: " << mouse_event.getX () << " , " << mouse_event.getY () << endl;
}
}
void
run ()
{
string mouseMsg2D ("Mouse coordinates in image viewer");
string keyMsg2D ("Key event for image viewer");
image_viewer_.registerMouseCallback (&SimpleOpenNIViewer::mouse_callback, *this, static_cast<void*> (&mouseMsg2D));
image_viewer_.registerKeyboardCallback(&SimpleOpenNIViewer::keyboard_callback, *this, static_cast<void*> (&keyMsg2D));
depth_image_viewer_.registerMouseCallback (&SimpleOpenNIViewer::mouse_callback, *this, static_cast<void*> (&mouseMsg2D));
depth_image_viewer_.registerKeyboardCallback(&SimpleOpenNIViewer::keyboard_callback, *this, static_cast<void*> (&keyMsg2D));
boost::function<void (const boost::shared_ptr<openni_wrapper::Image>&, const boost::shared_ptr<openni_wrapper::DepthImage>&, float) > image_cb = boost::bind (&SimpleOpenNIViewer::image_callback, this, _1, _2, _3);
boost::signals2::connection image_connection = grabber_.registerCallback (image_cb);
grabber_.start ();
while (!image_viewer_.wasStopped () && !depth_image_viewer_.wasStopped ())
{
boost::shared_ptr<openni_wrapper::Image> image;
boost::shared_ptr<openni_wrapper::DepthImage> depth_image;
if (!image_cld_init_)
{
image_viewer_.setPosition (0, 0);
image_cld_init_ = !image_cld_init_;
}
if (image_mutex_.try_lock ())
{
// Swap data
image_.swap (image);
depth_image_.swap (depth_image);
// Unlock
image_mutex_.unlock ();
}
// Add to renderer
if (image)
{
if (image->getEncoding() == openni_wrapper::Image::RGB)
image_viewer_.addRGBImage (image->getMetaData ().Data (), image->getWidth (), image->getHeight ());
else
image_viewer_.addRGBImage (rgb_data_, image->getWidth (), image->getHeight ());
}
if (depth_image)
{
depth_image_viewer_.addRGBImage (depth_data_, depth_image->getWidth (), depth_image->getHeight ());
if (!depth_image_cld_init_)
{
depth_image_viewer_.setPosition (depth_image->getWidth (), 0);
depth_image_cld_init_ = !depth_image_cld_init_;
}
}
image_viewer_.spinOnce ();
depth_image_viewer_.spinOnce ();
boost::this_thread::sleep (boost::posix_time::microseconds (100));
}
grabber_.stop ();
image_connection.disconnect ();
if (rgb_data_)
delete[] rgb_data_;
if (depth_data_)
delete[] depth_data_;
}
pcl::OpenNIGrabber& grabber_;
boost::mutex image_mutex_;
boost::shared_ptr<openni_wrapper::Image> image_;
boost::shared_ptr<openni_wrapper::DepthImage> depth_image_;
pcl::visualization::ImageViewer image_viewer_;
pcl::visualization::ImageViewer depth_image_viewer_;
bool image_cld_init_, depth_image_cld_init_;
unsigned char* rgb_data_, *depth_data_;
unsigned rgb_data_size_;
};
void
usage (char ** argv)
{
cout << "usage: " << argv[0] << " [((<device_id> | <path-to-oni-file>) [-imagemode <mode>] | -l [<device_id>]| -h | --help)]" << endl;
cout << argv[0] << " -h | --help : shows this help" << endl;
cout << argv[0] << " -l : list all available devices" << endl;
cout << argv[0] << " -l <device-id> : list all available modes for specified device" << endl;
cout << " device_id may be #1, #2, ... for the first, second etc device in the list"
#ifndef _WIN32
<< " or" << endl
<< " bus@address for the device connected to a specific usb-bus / address combination or" << endl
<< " <serial-number>"
#endif
<< endl;
cout << endl;
cout << "examples:" << endl;
cout << argv[0] << " \"#1\"" << endl;
cout << " uses the first device." << endl;
cout << argv[0] << " \"./temp/test.oni\"" << endl;
cout << " uses the oni-player device to play back oni file given by path." << endl;
cout << argv[0] << " -l" << endl;
cout << " lists all available devices." << endl;
cout << argv[0] << " -l \"#2\"" << endl;
cout << " lists all available modes for the second device" << endl;
#ifndef _WIN32
cout << argv[0] << " A00361800903049A" << endl;
cout << " uses the device with the serial number \'A00361800903049A\'." << endl;
cout << argv[0] << " 1@16" << endl;
cout << " uses the device on address 16 at USB bus 1." << endl;
#endif
}
int
main (int argc, char ** argv)
{
std::string device_id ("");
pcl::OpenNIGrabber::Mode image_mode = pcl::OpenNIGrabber::OpenNI_Default_Mode;
if (argc >= 2)
{
device_id = argv[1];
if (device_id == "--help" || device_id == "-h")
{
usage (argv);
return (0);
}
else if (device_id == "-l")
{
if (argc >= 3)
{
pcl::OpenNIGrabber grabber (argv[2]);
boost::shared_ptr<openni_wrapper::OpenNIDevice> device = grabber.getDevice ();
std::vector<std::pair<int, XnMapOutputMode> > modes;
if (device->hasImageStream ())
{
cout << endl << "Supported image modes for device: " << device->getVendorName () << " , " << device->getProductName () << endl;
modes = grabber.getAvailableImageModes ();
for (std::vector<std::pair<int, XnMapOutputMode> >::const_iterator it = modes.begin (); it != modes.end (); ++it)
{
cout << it->first << " = " << it->second.nXRes << " x " << it->second.nYRes << " @ " << it->second.nFPS << endl;
}
}
}
else
{
openni_wrapper::OpenNIDriver& driver = openni_wrapper::OpenNIDriver::getInstance ();
if (driver.getNumberDevices () > 0)
{
for (unsigned deviceIdx = 0; deviceIdx < driver.getNumberDevices (); ++deviceIdx)
{
cout << "Device: " << deviceIdx + 1 << ", vendor: " << driver.getVendorName (deviceIdx) << ", product: " << driver.getProductName (deviceIdx)
<< ", connected: " << driver.getBus (deviceIdx) << " @ " << driver.getAddress (deviceIdx) << ", serial number: \'" << driver.getSerialNumber (deviceIdx) << "\'" << endl;
}
}
else
cout << "No devices connected." << endl;
cout <<"Virtual Devices available: ONI player" << endl;
}
return (0);
}
}
else
{
openni_wrapper::OpenNIDriver& driver = openni_wrapper::OpenNIDriver::getInstance ();
if (driver.getNumberDevices() > 0)
cout << "Device Id not set, using first device." << endl;
}
unsigned mode;
if (pcl::console::parse (argc, argv, "-imagemode", mode) != -1)
image_mode = static_cast<pcl::OpenNIGrabber::Mode> (mode);
pcl::OpenNIGrabber grabber (device_id, pcl::OpenNIGrabber::OpenNI_Default_Mode, image_mode);
SimpleOpenNIViewer v (grabber);
v.run ();
return (0);
}
<commit_msg>added the capability to switch between shift values and raw 12bit depth<commit_after>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2011, Willow Garage, Inc.
* Copyright (c) 2012-, Open Perception, 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.
*
*/
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/common/time.h> //fps calculations
#include <pcl/io/openni_grabber.h>
#include <pcl/visualization/boost.h>
#include <pcl/visualization/common/float_image_utils.h>
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/visualization/image_viewer.h>
#include <pcl/io/openni_camera/openni_driver.h>
#include <pcl/console/parse.h>
#include <pcl/visualization/mouse_event.h>
using namespace std;
#define SHOW_FPS 1
#if SHOW_FPS
#define FPS_CALC(_WHAT_) \
do \
{ \
static unsigned count = 0;\
static double last = pcl::getTime ();\
double now = pcl::getTime (); \
++count; \
if (now - last >= 1.0) \
{ \
std::cout << "Average framerate("<< _WHAT_ << "): " << double(count)/double(now - last) << " Hz" << std::endl; \
count = 0; \
last = now; \
} \
}while(false)
#else
#define FPS_CALC(_WHAT_) \
do \
{ \
}while(false)
#endif
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class SimpleOpenNIViewer
{
public:
SimpleOpenNIViewer (pcl::OpenNIGrabber& grabber)
: grabber_ (grabber),
image_viewer_ ("PCL/OpenNI RGB image viewer"),
depth_image_viewer_ ("PCL/OpenNI depth image viewer"),
image_cld_init_ (false), depth_image_cld_init_ (false),
rgb_data_ (0), depth_data_ (0), rgb_data_size_ (0)
{
}
void
image_callback (const boost::shared_ptr<openni_wrapper::Image> &image,
const boost::shared_ptr<openni_wrapper::DepthImage> &depth_image, float)
{
FPS_CALC ("image callback");
boost::mutex::scoped_lock lock (image_mutex_);
// Copy data
image_ = image;
if (image->getEncoding() != openni_wrapper::Image::RGB)
{
if (rgb_data_size_ < image->getWidth () * image->getHeight ())
{
if (rgb_data_)
delete [] rgb_data_;
rgb_data_size_ = image->getWidth () * image->getHeight ();
rgb_data_ = new unsigned char [rgb_data_size_ * 3];
}
image_->fillRGB (image_->getWidth (), image_->getHeight (), rgb_data_);
}
// Copy data
depth_image_ = depth_image;
if (depth_data_)
delete[] depth_data_;
depth_data_ = pcl::visualization::FloatImageUtils::getVisualImage (
reinterpret_cast<const unsigned short*> (depth_image->getDepthMetaData ().Data ()),
depth_image->getWidth (), depth_image->getHeight (),
std::numeric_limits<unsigned short>::min (),
// Scale so that the colors look brigher on screen
std::numeric_limits<unsigned short>::max () / 10,
true);
}
void
keyboard_callback (const pcl::visualization::KeyboardEvent& event, void* cookie)
{
string* message = static_cast<string*> (cookie);
cout << (*message) << " :: ";
if (event.getKeyCode ())
cout << "the key \'" << event.getKeyCode () << "\' (" << event.getKeyCode () << ") was";
else
cout << "the special key \'" << event.getKeySym () << "\' was";
if (event.keyDown ())
cout << " pressed" << endl;
else
cout << " released" << endl;
}
void
mouse_callback (const pcl::visualization::MouseEvent& mouse_event, void* cookie)
{
string* message = static_cast<string*> (cookie);
if (mouse_event.getType () == pcl::visualization::MouseEvent::MouseButtonPress && mouse_event.getButton () == pcl::visualization::MouseEvent::LeftButton)
{
cout << (*message) << " :: " << mouse_event.getX () << " , " << mouse_event.getY () << endl;
}
}
void
run ()
{
string mouseMsg2D ("Mouse coordinates in image viewer");
string keyMsg2D ("Key event for image viewer");
image_viewer_.registerMouseCallback (&SimpleOpenNIViewer::mouse_callback, *this, static_cast<void*> (&mouseMsg2D));
image_viewer_.registerKeyboardCallback(&SimpleOpenNIViewer::keyboard_callback, *this, static_cast<void*> (&keyMsg2D));
depth_image_viewer_.registerMouseCallback (&SimpleOpenNIViewer::mouse_callback, *this, static_cast<void*> (&mouseMsg2D));
depth_image_viewer_.registerKeyboardCallback(&SimpleOpenNIViewer::keyboard_callback, *this, static_cast<void*> (&keyMsg2D));
boost::function<void (const boost::shared_ptr<openni_wrapper::Image>&, const boost::shared_ptr<openni_wrapper::DepthImage>&, float) > image_cb = boost::bind (&SimpleOpenNIViewer::image_callback, this, _1, _2, _3);
boost::signals2::connection image_connection = grabber_.registerCallback (image_cb);
grabber_.start ();
while (!image_viewer_.wasStopped () && !depth_image_viewer_.wasStopped ())
{
boost::shared_ptr<openni_wrapper::Image> image;
boost::shared_ptr<openni_wrapper::DepthImage> depth_image;
if (!image_cld_init_)
{
image_viewer_.setPosition (0, 0);
image_cld_init_ = !image_cld_init_;
}
if (image_mutex_.try_lock ())
{
// Swap data
image_.swap (image);
depth_image_.swap (depth_image);
// Unlock
image_mutex_.unlock ();
}
// Add to renderer
if (image)
{
if (image->getEncoding() == openni_wrapper::Image::RGB)
image_viewer_.addRGBImage (image->getMetaData ().Data (), image->getWidth (), image->getHeight ());
else
image_viewer_.addRGBImage (rgb_data_, image->getWidth (), image->getHeight ());
}
if (depth_image)
{
depth_image_viewer_.addRGBImage (depth_data_, depth_image->getWidth (), depth_image->getHeight ());
if (!depth_image_cld_init_)
{
depth_image_viewer_.setPosition (depth_image->getWidth (), 0);
depth_image_cld_init_ = !depth_image_cld_init_;
}
}
image_viewer_.spinOnce ();
depth_image_viewer_.spinOnce ();
boost::this_thread::sleep (boost::posix_time::microseconds (100));
}
grabber_.stop ();
image_connection.disconnect ();
if (rgb_data_)
delete[] rgb_data_;
if (depth_data_)
delete[] depth_data_;
}
pcl::OpenNIGrabber& grabber_;
boost::mutex image_mutex_;
boost::shared_ptr<openni_wrapper::Image> image_;
boost::shared_ptr<openni_wrapper::DepthImage> depth_image_;
pcl::visualization::ImageViewer image_viewer_;
pcl::visualization::ImageViewer depth_image_viewer_;
bool image_cld_init_, depth_image_cld_init_;
unsigned char* rgb_data_, *depth_data_;
unsigned rgb_data_size_;
};
void
usage (char ** argv)
{
cout << "usage: " << argv[0] << " [((<device_id> | <path-to-oni-file>) [-imagemode <mode>] | [-depthformat <format>] | -l [<device_id>]| -h | --help)]" << endl;
cout << argv[0] << " -h | --help : shows this help" << endl;
cout << argv[0] << " -l : list all available devices" << endl;
cout << argv[0] << " -l <device-id> : list all available modes for specified device" << endl;
cout << " device_id may be #1, #2, ... for the first, second etc device in the list"
#ifndef _WIN32
<< " or" << endl
<< " bus@address for the device connected to a specific usb-bus / address combination or" << endl
<< " <serial-number>"
#endif
<< endl;
cout << endl;
cout << "examples:" << endl;
cout << argv[0] << " \"#1\"" << endl;
cout << " uses the first device." << endl;
cout << argv[0] << " \"./temp/test.oni\"" << endl;
cout << " uses the oni-player device to play back oni file given by path." << endl;
cout << argv[0] << " -l" << endl;
cout << " lists all available devices." << endl;
cout << argv[0] << " -l \"#2\"" << endl;
cout << " lists all available modes for the second device" << endl;
#ifndef _WIN32
cout << argv[0] << " A00361800903049A" << endl;
cout << " uses the device with the serial number \'A00361800903049A\'." << endl;
cout << argv[0] << " 1@16" << endl;
cout << " uses the device on address 16 at USB bus 1." << endl;
#endif
}
int
main (int argc, char ** argv)
{
std::string device_id ("");
pcl::OpenNIGrabber::Mode image_mode = pcl::OpenNIGrabber::OpenNI_Default_Mode;
if (argc >= 2)
{
device_id = argv[1];
if (device_id == "--help" || device_id == "-h")
{
usage (argv);
return (0);
}
else if (device_id == "-l")
{
if (argc >= 3)
{
pcl::OpenNIGrabber grabber (argv[2]);
boost::shared_ptr<openni_wrapper::OpenNIDevice> device = grabber.getDevice ();
std::vector<std::pair<int, XnMapOutputMode> > modes;
if (device->hasImageStream ())
{
cout << endl << "Supported image modes for device: " << device->getVendorName () << " , " << device->getProductName () << endl;
modes = grabber.getAvailableImageModes ();
for (std::vector<std::pair<int, XnMapOutputMode> >::const_iterator it = modes.begin (); it != modes.end (); ++it)
{
cout << it->first << " = " << it->second.nXRes << " x " << it->second.nYRes << " @ " << it->second.nFPS << endl;
}
}
}
else
{
openni_wrapper::OpenNIDriver& driver = openni_wrapper::OpenNIDriver::getInstance ();
if (driver.getNumberDevices () > 0)
{
for (unsigned deviceIdx = 0; deviceIdx < driver.getNumberDevices (); ++deviceIdx)
{
cout << "Device: " << deviceIdx + 1 << ", vendor: " << driver.getVendorName (deviceIdx) << ", product: " << driver.getProductName (deviceIdx)
<< ", connected: " << driver.getBus (deviceIdx) << " @ " << driver.getAddress (deviceIdx) << ", serial number: \'" << driver.getSerialNumber (deviceIdx) << "\'" << endl;
}
}
else
cout << "No devices connected." << endl;
cout <<"Virtual Devices available: ONI player" << endl;
}
return (0);
}
}
else
{
openni_wrapper::OpenNIDriver& driver = openni_wrapper::OpenNIDriver::getInstance ();
if (driver.getNumberDevices() > 0)
cout << "Device Id not set, using first device." << endl;
}
unsigned mode;
if (pcl::console::parse (argc, argv, "-imagemode", mode) != -1)
image_mode = static_cast<pcl::OpenNIGrabber::Mode> (mode);
int depthformat = openni_wrapper::OpenNIDevice::OpenNI_12_bit_depth;
pcl::console::parse_argument (argc, argv, "-depthformat", depthformat);
pcl::OpenNIGrabber grabber (device_id, pcl::OpenNIGrabber::OpenNI_Default_Mode, image_mode);
// Set the depth output format
grabber.getDevice ()->setDepthOutputFormat (static_cast<openni_wrapper::OpenNIDevice::DepthMode> (depthformat));
SimpleOpenNIViewer v (grabber);
v.run ();
return (0);
}
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2013-2016.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://www.opensource.org/licenses/MIT)
//=======================================================================
#include <array.hpp>
#include "drivers/keyboard.hpp"
#include "terminal.hpp"
#include "console.hpp"
#include "assert.hpp"
#include "logging.hpp"
#include "scheduler.hpp"
namespace {
stdio::terminal_driver terminal_driver_impl;
stdio::terminal_driver* tty_driver = &terminal_driver_impl;
constexpr const size_t MAX_TERMINALS = 2;
size_t active_terminal;
std::array<stdio::virtual_terminal, MAX_TERMINALS> terminals;
void input_thread(void* data){
auto& terminal = *reinterpret_cast<stdio::virtual_terminal*>(data);
auto pid = scheduler::get_pid();
logging::logf(logging::log_level::TRACE, "stdio: Input Thread for terminal %u started (pid:%u)\n", terminal.id, pid);
bool shift = false;
while(true){
// Wait for some input
scheduler::block_process(pid);
// Handle keyboard input
while(!terminal.keyboard_buffer.empty()){
auto key = terminal.keyboard_buffer.pop();
if(terminal.canonical){
//Key released
if(key & 0x80){
key &= ~(0x80);
if(key == keyboard::KEY_LEFT_SHIFT || key == keyboard::KEY_RIGHT_SHIFT){
shift = false;
}
}
//Key pressed
else {
if(key == keyboard::KEY_LEFT_SHIFT || key == keyboard::KEY_RIGHT_SHIFT){
shift = true;
} else if(key == keyboard::KEY_BACKSPACE){
if(!terminal.input_buffer.empty()){
terminal.input_buffer.pop_last();
terminal.print('\b');
}
} else {
auto qwertz_key =
shift
? keyboard::shift_key_to_ascii(key)
: keyboard::key_to_ascii(key);
if(qwertz_key){
terminal.input_buffer.push(qwertz_key);
terminal.print(qwertz_key);
if(qwertz_key == '\n'){
// Transfer current line to the canonical buffer
while(!terminal.input_buffer.empty()){
terminal.canonical_buffer.push(terminal.input_buffer.pop());
}
terminal.input_queue.notify_one();
}
}
}
}
} else {
// The complete processing of the key will be done by the
// userspace program
auto code = keyboard::raw_key_to_keycode(key);
terminal.raw_buffer.push(static_cast<size_t>(code));
terminal.input_queue.notify_one();
thor_assert(!terminal.raw_buffer.full(), "raw buffer is full!");
}
}
// Handle mouse input
while(!terminal.mouse_buffer.empty()){
auto key = terminal.mouse_buffer.pop();
if(!terminal.canonical && terminal.mouse){
terminal.raw_buffer.push(key);
terminal.input_queue.notify_one();
thor_assert(!terminal.raw_buffer.full(), "raw buffer is full!");
}
}
}
}
} //end of anonymous namespace
void stdio::virtual_terminal::print(char key){
//TODO If it is not the active terminal, buffer it
k_print(key);
}
void stdio::virtual_terminal::send_input(char key){
if(!input_thread_pid){
return;
}
// Simply give the input to the input thread
keyboard_buffer.push(key);
thor_assert(!keyboard_buffer.full(), "keyboard buffer is full!");
// Need hint here because it is coming from an IRQ
scheduler::unblock_process_hint(input_thread_pid);
}
void stdio::virtual_terminal::send_mouse_input(std::keycode key){
if(!input_thread_pid){
return;
}
// Simply give the input to the input thread
mouse_buffer.push(size_t(key));
thor_assert(!mouse_buffer.full(), "mouse buffer is full!");
// Need hint here because it is coming from an IRQ
scheduler::unblock_process_hint(input_thread_pid);
}
size_t stdio::virtual_terminal::read_input_can(char* buffer, size_t max){
size_t read = 0;
while(true){
while(!canonical_buffer.empty()){
auto c = canonical_buffer.pop();
buffer[read++] = c;
if(read >= max || c == '\n'){
return read;
}
}
input_queue.wait();
}
}
// TODO In case of max < read, the timeout is not respected
size_t stdio::virtual_terminal::read_input_can(char* buffer, size_t max, size_t ms){
size_t read = 0;
while(true){
while(!canonical_buffer.empty()){
auto c = canonical_buffer.pop();
buffer[read++] = c;
if(read >= max || c == '\n'){
return read;
}
}
if(!ms){
return read;
}
if(!input_queue.wait_for(ms)){
return read;
}
}
}
size_t stdio::virtual_terminal::read_input_raw(){
if(raw_buffer.empty()){
input_queue.wait();
}
return raw_buffer.pop();
}
size_t stdio::virtual_terminal::read_input_raw(size_t ms){
if(raw_buffer.empty()){
if(!ms){
return static_cast<size_t>(std::keycode::TIMEOUT);
}
if(!input_queue.wait_for(ms)){
return static_cast<size_t>(std::keycode::TIMEOUT);
}
}
thor_assert(!raw_buffer.empty(), "There is a problem with the sleep queue");
return raw_buffer.pop();
}
void stdio::virtual_terminal::set_canonical(bool can){
logging::logf(logging::log_level::TRACE, "Switched terminal %u canonical mode from %u to %u\n", id, uint64_t(canonical), uint64_t(can));
canonical = can;
}
void stdio::virtual_terminal::set_mouse(bool m){
logging::logf(logging::log_level::TRACE, "Switched terminal %u mouse handling mode from %u to %u\n", id, uint64_t(mouse), uint64_t(m));
mouse = m;
}
bool stdio::virtual_terminal::is_canonical() const {
return canonical;
}
void stdio::init_terminals(){
size_t id = 0;
for(auto& terminal : terminals){
terminal.id = id++;
terminal.active = false;
terminal.canonical = true;
terminal.mouse = false;
}
active_terminal = 0;
terminals[active_terminal].active = true;
}
void stdio::register_devices(){
for(auto& terminal : terminals){
std::string name = std::string("tty") + std::to_string(terminal.id);
devfs::register_device("/dev/", name, devfs::device_type::CHAR_DEVICE, tty_driver, &terminal);
}
}
void stdio::finalize(){
for(auto& terminal : terminals){
auto* user_stack = new char[scheduler::user_stack_size];
auto* kernel_stack = new char[scheduler::kernel_stack_size];
auto& input_process = scheduler::create_kernel_task_args("tty_input", user_stack, kernel_stack, &input_thread, &terminal);
input_process.ppid = 1;
input_process.priority = scheduler::DEFAULT_PRIORITY;
scheduler::queue_system_process(input_process.pid);
terminal.input_thread_pid = input_process.pid;
}
}
size_t stdio::terminal_driver::read(void* data, char* buffer, size_t count, size_t& read){
auto* terminal = reinterpret_cast<stdio::virtual_terminal*>(data);
if (terminal->is_canonical()) {
read = terminal->read_input_can(reinterpret_cast<char*>(buffer), count);
} else {
buffer[0] = terminal->read_input_raw();
read = 1;
}
return 0;
}
size_t stdio::terminal_driver::read(void* data, char* buffer, size_t count, size_t& read, size_t ms){
auto* terminal = reinterpret_cast<stdio::virtual_terminal*>(data);
if(terminal->is_canonical()){
read = terminal->read_input_can(reinterpret_cast<char*>(buffer), count, ms);
} else {
buffer[0] = terminal->read_input_raw();
read = 1;
}
return 0;
}
size_t stdio::terminal_driver::write(void* data, const char* buffer, size_t count, size_t& written){
auto* terminal = reinterpret_cast<stdio::virtual_terminal*>(data);
for(size_t i = 0; i < count;++i){
terminal->print(buffer[i]);
}
written = count;
return 0;
}
stdio::virtual_terminal& stdio::get_active_terminal(){
return terminals[active_terminal];
}
stdio::virtual_terminal& stdio::get_terminal(size_t id){
thor_assert(id < MAX_TERMINALS, "Out of bound tty");
return terminals[id];
}
<commit_msg>Fix timeout<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2013-2016.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://www.opensource.org/licenses/MIT)
//=======================================================================
#include <array.hpp>
#include "drivers/keyboard.hpp"
#include "terminal.hpp"
#include "console.hpp"
#include "assert.hpp"
#include "logging.hpp"
#include "scheduler.hpp"
namespace {
stdio::terminal_driver terminal_driver_impl;
stdio::terminal_driver* tty_driver = &terminal_driver_impl;
constexpr const size_t MAX_TERMINALS = 2;
size_t active_terminal;
std::array<stdio::virtual_terminal, MAX_TERMINALS> terminals;
void input_thread(void* data){
auto& terminal = *reinterpret_cast<stdio::virtual_terminal*>(data);
auto pid = scheduler::get_pid();
logging::logf(logging::log_level::TRACE, "stdio: Input Thread for terminal %u started (pid:%u)\n", terminal.id, pid);
bool shift = false;
while(true){
// Wait for some input
scheduler::block_process(pid);
// Handle keyboard input
while(!terminal.keyboard_buffer.empty()){
auto key = terminal.keyboard_buffer.pop();
if(terminal.canonical){
//Key released
if(key & 0x80){
key &= ~(0x80);
if(key == keyboard::KEY_LEFT_SHIFT || key == keyboard::KEY_RIGHT_SHIFT){
shift = false;
}
}
//Key pressed
else {
if(key == keyboard::KEY_LEFT_SHIFT || key == keyboard::KEY_RIGHT_SHIFT){
shift = true;
} else if(key == keyboard::KEY_BACKSPACE){
if(!terminal.input_buffer.empty()){
terminal.input_buffer.pop_last();
terminal.print('\b');
}
} else {
auto qwertz_key =
shift
? keyboard::shift_key_to_ascii(key)
: keyboard::key_to_ascii(key);
if(qwertz_key){
terminal.input_buffer.push(qwertz_key);
terminal.print(qwertz_key);
if(qwertz_key == '\n'){
// Transfer current line to the canonical buffer
while(!terminal.input_buffer.empty()){
terminal.canonical_buffer.push(terminal.input_buffer.pop());
}
terminal.input_queue.notify_one();
}
}
}
}
} else {
// The complete processing of the key will be done by the
// userspace program
auto code = keyboard::raw_key_to_keycode(key);
terminal.raw_buffer.push(static_cast<size_t>(code));
terminal.input_queue.notify_one();
thor_assert(!terminal.raw_buffer.full(), "raw buffer is full!");
}
}
// Handle mouse input
while(!terminal.mouse_buffer.empty()){
auto key = terminal.mouse_buffer.pop();
if(!terminal.canonical && terminal.mouse){
terminal.raw_buffer.push(key);
terminal.input_queue.notify_one();
thor_assert(!terminal.raw_buffer.full(), "raw buffer is full!");
}
}
}
}
} //end of anonymous namespace
void stdio::virtual_terminal::print(char key){
//TODO If it is not the active terminal, buffer it
k_print(key);
}
void stdio::virtual_terminal::send_input(char key){
if(!input_thread_pid){
return;
}
// Simply give the input to the input thread
keyboard_buffer.push(key);
thor_assert(!keyboard_buffer.full(), "keyboard buffer is full!");
// Need hint here because it is coming from an IRQ
scheduler::unblock_process_hint(input_thread_pid);
}
void stdio::virtual_terminal::send_mouse_input(std::keycode key){
if(!input_thread_pid){
return;
}
// Simply give the input to the input thread
mouse_buffer.push(size_t(key));
thor_assert(!mouse_buffer.full(), "mouse buffer is full!");
// Need hint here because it is coming from an IRQ
scheduler::unblock_process_hint(input_thread_pid);
}
size_t stdio::virtual_terminal::read_input_can(char* buffer, size_t max){
size_t read = 0;
while(true){
while(!canonical_buffer.empty()){
auto c = canonical_buffer.pop();
buffer[read++] = c;
if(read >= max || c == '\n'){
return read;
}
}
input_queue.wait();
}
}
// TODO In case of max < read, the timeout is not respected
size_t stdio::virtual_terminal::read_input_can(char* buffer, size_t max, size_t ms){
size_t read = 0;
while(true){
while(!canonical_buffer.empty()){
auto c = canonical_buffer.pop();
buffer[read++] = c;
if(read >= max || c == '\n'){
return read;
}
}
if(!ms){
return read;
}
if(!input_queue.wait_for(ms)){
return read;
}
}
}
size_t stdio::virtual_terminal::read_input_raw(){
if(raw_buffer.empty()){
input_queue.wait();
}
return raw_buffer.pop();
}
size_t stdio::virtual_terminal::read_input_raw(size_t ms){
if(raw_buffer.empty()){
if(!ms){
return static_cast<size_t>(std::keycode::TIMEOUT);
}
if(!input_queue.wait_for(ms)){
return static_cast<size_t>(std::keycode::TIMEOUT);
}
}
thor_assert(!raw_buffer.empty(), "There is a problem with the sleep queue");
return raw_buffer.pop();
}
void stdio::virtual_terminal::set_canonical(bool can){
logging::logf(logging::log_level::TRACE, "Switched terminal %u canonical mode from %u to %u\n", id, uint64_t(canonical), uint64_t(can));
canonical = can;
}
void stdio::virtual_terminal::set_mouse(bool m){
logging::logf(logging::log_level::TRACE, "Switched terminal %u mouse handling mode from %u to %u\n", id, uint64_t(mouse), uint64_t(m));
mouse = m;
}
bool stdio::virtual_terminal::is_canonical() const {
return canonical;
}
void stdio::init_terminals(){
size_t id = 0;
for(auto& terminal : terminals){
terminal.id = id++;
terminal.active = false;
terminal.canonical = true;
terminal.mouse = false;
}
active_terminal = 0;
terminals[active_terminal].active = true;
}
void stdio::register_devices(){
for(auto& terminal : terminals){
std::string name = std::string("tty") + std::to_string(terminal.id);
devfs::register_device("/dev/", name, devfs::device_type::CHAR_DEVICE, tty_driver, &terminal);
}
}
void stdio::finalize(){
for(auto& terminal : terminals){
auto* user_stack = new char[scheduler::user_stack_size];
auto* kernel_stack = new char[scheduler::kernel_stack_size];
auto& input_process = scheduler::create_kernel_task_args("tty_input", user_stack, kernel_stack, &input_thread, &terminal);
input_process.ppid = 1;
input_process.priority = scheduler::DEFAULT_PRIORITY;
scheduler::queue_system_process(input_process.pid);
terminal.input_thread_pid = input_process.pid;
}
}
size_t stdio::terminal_driver::read(void* data, char* buffer, size_t count, size_t& read){
auto* terminal = reinterpret_cast<stdio::virtual_terminal*>(data);
if (terminal->is_canonical()) {
read = terminal->read_input_can(reinterpret_cast<char*>(buffer), count);
} else {
buffer[0] = terminal->read_input_raw();
read = 1;
}
return 0;
}
size_t stdio::terminal_driver::read(void* data, char* buffer, size_t count, size_t& read, size_t ms){
auto* terminal = reinterpret_cast<stdio::virtual_terminal*>(data);
if(terminal->is_canonical()){
read = terminal->read_input_can(reinterpret_cast<char*>(buffer), count, ms);
} else {
buffer[0] = terminal->read_input_raw(ms);
read = 1;
}
return 0;
}
size_t stdio::terminal_driver::write(void* data, const char* buffer, size_t count, size_t& written){
auto* terminal = reinterpret_cast<stdio::virtual_terminal*>(data);
for(size_t i = 0; i < count;++i){
terminal->print(buffer[i]);
}
written = count;
return 0;
}
stdio::virtual_terminal& stdio::get_active_terminal(){
return terminals[active_terminal];
}
stdio::virtual_terminal& stdio::get_terminal(size_t id){
thor_assert(id < MAX_TERMINALS, "Out of bound tty");
return terminals[id];
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2005 Till Adam <adam@kde.org>
*
* 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; version 2 of the License
*
* 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.
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of this program with any edition of
* the Qt library by Trolltech AS, Norway (or with modified versions
* of Qt that use the same license as Qt), and distribute linked
* combinations including the two. You must obey the GNU General
* Public License in all respects for all of the code used other than
* Qt. If you modify this file, you may extend this exception to
* your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from
* your version.
*/
#include "copyfolderjob.h"
#include "folderstorage.h"
#include "kmfoldercachedimap.h"
#include "kmfolder.h"
#include "kmfolderdir.h"
#include "kmfoldertype.h"
#include "kmfoldermgr.h"
#include "kmcommands.h"
#include "kmmsgbase.h"
#include "undostack.h"
#include <kdebug.h>
#include <klocale.h>
#include <config.h>
using namespace KMail;
CopyFolderJob::CopyFolderJob( const FolderStorage* const storage, KMFolderDir* const newParent )
: FolderJob( 0, tOther, (storage ? storage->folder() : 0) ),
mStorage( storage ), mNewParent( newParent ),
mNewFolder( 0 ), mChildFolderNodeIterator( *mStorage->folder()->createChildFolder() ),
mNextChildFolder( 0 )
{
}
CopyFolderJob::~CopyFolderJob()
{
kdDebug(5006) << k_funcinfo << endl;
}
/*
* The basic strategy is to first create the target folder, then copy all the mail
* from the source to the target folder, then recurse for each of the folder's children
*/
void CopyFolderJob::execute()
{
if ( createTargetDir() ) {
copyMessagesToTargetDir();
}
}
void CopyFolderJob::copyMessagesToTargetDir()
{
// Hmmmm. Tasty hack. Can I have fries with that?
const_cast<FolderStorage*>( mStorage )->blockSignals( true );
// move all messages to the new folder
QPtrList<KMMsgBase> msgList;
for ( int i = 0; i < mStorage->count(); i++ )
{
const KMMsgBase* msgBase = mStorage->getMsgBase( i );
assert( msgBase );
msgList.append( msgBase );
}
if ( msgList.count() == 0 ) {
slotCopyNextChild(); // no contents, check subfolders
const_cast<FolderStorage*>( mStorage )->blockSignals( false );
} else {
KMCommand *command = new KMCopyCommand( mNewFolder, msgList );
connect( command, SIGNAL( completed( KMCommand * ) ),
this, SLOT( slotCopyCompleted( KMCommand * ) ) );
command->start();
}
}
void CopyFolderJob::slotCopyCompleted( KMCommand* command )
{
kdDebug(5006) << k_funcinfo << (command?command->result():0) << endl;
disconnect( command, SIGNAL( completed( KMCommand * ) ),
this, SLOT( slotCopyCompleted( KMCommand * ) ) );
const_cast<FolderStorage*>( mStorage )->blockSignals( false );
if ( command && command->result() != KMCommand::OK ) {
rollback();
}
// if we have children, recurse
if ( mStorage->folder()->child() ) {
slotCopyNextChild();
} else {
emit folderCopyComplete( true );
deleteLater();
}
}
void CopyFolderJob::slotCopyNextChild( bool success )
{
//kdDebug(5006) << k_funcinfo << endl;
if ( mNextChildFolder )
mNextChildFolder->close(); // refcount
// previous sibling failed
if ( !success ) {
kdDebug(5006) << "Failed to copy one subfolder, let's not continue: " << mNewFolder->prettyURL() << endl;
rollback();
emit folderCopyComplete( false );
deleteLater();
}
KMFolderNode* node = mChildFolderNodeIterator.current();
while ( node && node->isDir() ) {
++mChildFolderNodeIterator;
node = mChildFolderNodeIterator.current();
}
if ( node ) {
mNextChildFolder = static_cast<KMFolder*>(node);
++mChildFolderNodeIterator;
} else {
// no more children, we are done
emit folderCopyComplete( true );
deleteLater();
return;
}
KMFolderDir * const dir = mNewFolder->createChildFolder();
if ( !dir ) {
kdDebug(5006) << "Failed to create subfolders of: " << mNewFolder->prettyURL() << endl;
emit folderCopyComplete( false );
deleteLater();
return;
}
// let it do its thing and report back when we are ready to do the next sibling
mNextChildFolder->open(); // refcount
FolderJob* job = new CopyFolderJob( mNextChildFolder->storage(), dir);
connect( job, SIGNAL( folderCopyComplete( bool ) ),
this, SLOT( slotCopyNextChild( bool ) ) );
job->start();
}
// FIXME factor into CreateFolderJob and make async, so it works with online imap
// FIXME this is the same in renamejob. Refactor RenameJob to use a copy job and then delete
bool CopyFolderJob::createTargetDir()
{
KMFolderMgr* folderMgr = kmkernel->folderMgr();
if ( mNewParent->type() == KMImapDir ) {
folderMgr = kmkernel->imapFolderMgr();
} else if ( mNewParent->type() == KMDImapDir ) {
folderMgr = kmkernel->dimapFolderMgr();
}
// get the default mailbox type
KConfig * const config = KMKernel::config();
KConfigGroupSaver saver(config, "General");
int deftype = config->readNumEntry("default-mailbox-format", 1);
if ( deftype < 0 || deftype > 1 ) deftype = 1;
// the type of the new folder
KMFolderType typenew =
( deftype == 0 ) ? KMFolderTypeMbox : KMFolderTypeMaildir;
if ( mNewParent->owner() )
typenew = mNewParent->owner()->folderType();
mNewFolder = folderMgr->createFolder( mStorage->folder()->name(), false, typenew, mNewParent );
if ( !mNewFolder )
{
kdWarning(5006) << k_funcinfo << "could not create folder" << endl;
emit folderCopyComplete( false );
deleteLater();
return false;
}
if ( mNewParent->type() == KMDImapDir ) {
KMFolderCachedImap* cached = dynamic_cast<KMFolderCachedImap*>( mNewFolder->storage() );
cached->initializeFrom( dynamic_cast<KMFolderCachedImap*>( mNewParent->owner() ) );
}
// inherit the folder type
// FIXME we should probably copy over most if not all settings
mNewFolder->storage()->setContentsType( mStorage->contentsType(), true /*quiet*/ );
mNewFolder->storage()->writeConfig();
kdDebug(5006)<< "CopyJob::createTargetDir - " << mStorage->folder()->idString()
<< " |=> " << mNewFolder->idString() << endl;
return true;
}
void CopyFolderJob::rollback()
{
// FIXME do something
KMFolderMgr * const folderMgr = mNewFolder->createChildFolder()->manager();
folderMgr->remove( mNewFolder );
emit folderCopyComplete( false );
deleteLater();
}
#include "copyfolderjob.moc"
<commit_msg>Better fix.<commit_after>/**
* Copyright (c) 2005 Till Adam <adam@kde.org>
*
* 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; version 2 of the License
*
* 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.
*
* In addition, as a special exception, the copyright holders give
* permission to link the code of this program with any edition of
* the Qt library by Trolltech AS, Norway (or with modified versions
* of Qt that use the same license as Qt), and distribute linked
* combinations including the two. You must obey the GNU General
* Public License in all respects for all of the code used other than
* Qt. If you modify this file, you may extend this exception to
* your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from
* your version.
*/
#include "copyfolderjob.h"
#include "folderstorage.h"
#include "kmfoldercachedimap.h"
#include "kmfolder.h"
#include "kmfolderdir.h"
#include "kmfoldertype.h"
#include "kmfoldermgr.h"
#include "kmcommands.h"
#include "kmmsgbase.h"
#include "undostack.h"
#include <kdebug.h>
#include <klocale.h>
#include <config.h>
using namespace KMail;
CopyFolderJob::CopyFolderJob( const FolderStorage* const storage, KMFolderDir* const newParent )
: FolderJob( 0, tOther, (storage ? storage->folder() : 0) ),
mStorage( storage ), mNewParent( newParent ),
mNewFolder( 0 ), mChildFolderNodeIterator( *mStorage->folder()->createChildFolder() ),
mNextChildFolder( 0 )
{
}
CopyFolderJob::~CopyFolderJob()
{
kdDebug(5006) << k_funcinfo << endl;
}
/*
* The basic strategy is to first create the target folder, then copy all the mail
* from the source to the target folder, then recurse for each of the folder's children
*/
void CopyFolderJob::execute()
{
if ( createTargetDir() ) {
copyMessagesToTargetDir();
}
}
void CopyFolderJob::copyMessagesToTargetDir()
{
// Hmmmm. Tasty hack. Can I have fries with that?
const_cast<FolderStorage*>( mStorage )->blockSignals( true );
// move all messages to the new folder
QPtrList<KMMsgBase> msgList;
for ( int i = 0; i < mStorage->count(); i++ )
{
const KMMsgBase* msgBase = mStorage->getMsgBase( i );
assert( msgBase );
msgList.append( msgBase );
}
if ( msgList.count() == 0 ) {
slotCopyNextChild(); // no contents, check subfolders
const_cast<FolderStorage*>( mStorage )->blockSignals( false );
} else {
KMCommand *command = new KMCopyCommand( mNewFolder, msgList );
connect( command, SIGNAL( completed( KMCommand * ) ),
this, SLOT( slotCopyCompleted( KMCommand * ) ) );
command->start();
}
}
void CopyFolderJob::slotCopyCompleted( KMCommand* command )
{
kdDebug(5006) << k_funcinfo << (command?command->result():0) << endl;
disconnect( command, SIGNAL( completed( KMCommand * ) ),
this, SLOT( slotCopyCompleted( KMCommand * ) ) );
const_cast<FolderStorage*>( mStorage )->blockSignals( false );
if ( command && command->result() != KMCommand::OK ) {
rollback();
}
// if we have children, recurse
if ( mStorage->folder()->child() ) {
slotCopyNextChild();
} else {
emit folderCopyComplete( true );
deleteLater();
}
}
void CopyFolderJob::slotCopyNextChild( bool success )
{
//kdDebug(5006) << k_funcinfo << endl;
if ( mNextChildFolder )
mNextChildFolder->close(); // refcount
// previous sibling failed
if ( !success ) {
kdDebug(5006) << "Failed to copy one subfolder, let's not continue: " << mNewFolder->prettyURL() << endl;
rollback();
emit folderCopyComplete( false );
deleteLater();
}
KMFolderNode* node = mChildFolderNodeIterator.current();
while ( node && node->isDir() ) {
++mChildFolderNodeIterator;
node = mChildFolderNodeIterator.current();
}
if ( node ) {
mNextChildFolder = static_cast<KMFolder*>(node);
++mChildFolderNodeIterator;
} else {
// no more children, we are done
emit folderCopyComplete( true );
deleteLater();
return;
}
KMFolderDir * const dir = mNewFolder->createChildFolder();
if ( !dir ) {
kdDebug(5006) << "Failed to create subfolders of: " << mNewFolder->prettyURL() << endl;
emit folderCopyComplete( false );
deleteLater();
return;
}
// let it do its thing and report back when we are ready to do the next sibling
mNextChildFolder->open(); // refcount
FolderJob* job = new CopyFolderJob( mNextChildFolder->storage(), dir);
connect( job, SIGNAL( folderCopyComplete( bool ) ),
this, SLOT( slotCopyNextChild( bool ) ) );
job->start();
}
// FIXME factor into CreateFolderJob and make async, so it works with online imap
// FIXME this is the same in renamejob. Refactor RenameJob to use a copy job and then delete
bool CopyFolderJob::createTargetDir()
{
KMFolderMgr* folderMgr = kmkernel->folderMgr();
if ( mNewParent->type() == KMImapDir ) {
folderMgr = kmkernel->imapFolderMgr();
} else if ( mNewParent->type() == KMDImapDir ) {
folderMgr = kmkernel->dimapFolderMgr();
}
// get the default mailbox type
KConfig * const config = KMKernel::config();
KConfigGroupSaver saver(config, "General");
int deftype = config->readNumEntry("default-mailbox-format", 1);
if ( deftype < 0 || deftype > 1 ) deftype = 1;
// the type of the new folder
KMFolderType typenew =
( deftype == 0 ) ? KMFolderTypeMbox : KMFolderTypeMaildir;
if ( mNewParent->owner() )
typenew = mNewParent->owner()->folderType();
mNewFolder = folderMgr->createFolder( mStorage->folder()->name(), false, typenew, mNewParent );
if ( !mNewFolder )
{
kdWarning(5006) << k_funcinfo << "could not create folder" << endl;
emit folderCopyComplete( false );
deleteLater();
return false;
}
if ( typenew == KMFolderTypeCachedImap ) {
KMFolderCachedImap* cached = dynamic_cast<KMFolderCachedImap*>( mNewFolder->storage() );
cached->initializeFrom( dynamic_cast<KMFolderCachedImap*>( mNewParent->owner() ) );
}
// inherit the folder type
// FIXME we should probably copy over most if not all settings
mNewFolder->storage()->setContentsType( mStorage->contentsType(), true /*quiet*/ );
mNewFolder->storage()->writeConfig();
kdDebug(5006)<< "CopyJob::createTargetDir - " << mStorage->folder()->idString()
<< " |=> " << mNewFolder->idString() << endl;
return true;
}
void CopyFolderJob::rollback()
{
// FIXME do something
KMFolderMgr * const folderMgr = mNewFolder->createChildFolder()->manager();
folderMgr->remove( mNewFolder );
emit folderCopyComplete( false );
deleteLater();
}
#include "copyfolderjob.moc"
<|endoftext|> |
<commit_before>#pragma once
#include <experimental/optional>
#include <functional>
#include <memory>
#include "base/not_null.hpp"
#include "geometry/affine_map.hpp"
#include "geometry/named_quantities.hpp"
#include "geometry/orthogonal_map.hpp"
#include "geometry/rotation.hpp"
#include "ksp_plugin/celestial.hpp"
#include "ksp_plugin/frames.hpp"
#include "ksp_plugin/vessel.hpp"
#include "physics/discrete_trajectory.hpp"
#include "physics/dynamic_frame.hpp"
#include "physics/ephemeris.hpp"
#include "physics/rigid_motion.hpp"
#include "quantities/quantities.hpp"
namespace principia {
namespace ksp_plugin {
namespace internal_renderer {
using base::not_null;
using geometry::AffineMap;
using geometry::Instant;
using geometry::OrthogonalMap;
using geometry::Position;
using geometry::RigidTransformation;
using geometry::Rotation;
using physics::DiscreteTrajectory;
using physics::Ephemeris;
using physics::Frenet;
using physics::RigidMotion;
using quantities::Length;
class Renderer {
public:
Renderer(not_null<Celestial const*> sun,
not_null<std::unique_ptr<NavigationFrame>> plotting_frame);
// Changes the plotting frame of the renderer.
virtual void SetPlottingFrame(
not_null<std::unique_ptr<NavigationFrame>> plotting_frame);
// Returns the current plotting frame. This may not be the last set by
// |SetPlottingFrame| if it is overridden by a target vessel.
virtual not_null<NavigationFrame const*> GetPlottingFrame() const;
// Overrides the current plotting frame with one that is centred on the given
// |vessel|.
virtual void SetTargetVessel(
not_null<Vessel*> vessel,
not_null<Celestial const*> celestial,
not_null<Ephemeris<Barycentric> const*> ephemeris);
// Reverts to frame last set by |SetPlottingFrame|. The second version only
// has an effect if the given |vessel| is the current target vessel.
virtual void ClearTargetVessel();
virtual void ClearTargetVesselIf(not_null<Vessel*> vessel);
// Determines if there is a target vessel and returns it.
virtual bool HasTargetVessel() const;
virtual Vessel& GetTargetVessel();
virtual Vessel const& GetTargetVessel() const;
// If there is a target vessel, returns its prediction after extending it up
// to |time|.
virtual DiscreteTrajectory<Barycentric> const& GetTargetVesselPrediction(
Instant const& time) const;
// Returns a trajectory in |World| corresponding to the trajectory defined by
// |begin| and |end|, as seen in the current plotting frame. In this function
// and others in this class, |sun_world_position| is the current position of
// the sun in |World| space as returned by |Planetarium.fetch.Sun.position|;
// it is used to define the relation between |WorldSun| and |World|.
virtual not_null<std::unique_ptr<DiscreteTrajectory<World>>>
RenderBarycentricTrajectoryInWorld(
Instant const& time,
DiscreteTrajectory<Barycentric>::Iterator const& begin,
DiscreteTrajectory<Barycentric>::Iterator const& end,
Position<World> const& sun_world_position,
Rotation<Barycentric, AliceSun> const& planetarium_rotation) const;
// Returns a trajectory in the current plotting frame corresponding to the
// trajectory defined by |begin| and |end|. If there is a target vessel, its
// prediction must not be empty.
virtual not_null<std::unique_ptr<DiscreteTrajectory<Navigation>>>
RenderBarycentricTrajectoryInPlotting(
DiscreteTrajectory<Barycentric>::Iterator const& begin,
DiscreteTrajectory<Barycentric>::Iterator const& end) const;
// Returns a trajectory in |World| corresponding to the trajectory defined by
// |begin| and |end| in the current plotting frame.
virtual not_null<std::unique_ptr<DiscreteTrajectory<World>>>
RenderPlottingTrajectoryInWorld(
Instant const& time,
DiscreteTrajectory<Navigation>::Iterator const& begin,
DiscreteTrajectory<Navigation>::Iterator const& end,
Position<World> const& sun_world_position,
Rotation<Barycentric, AliceSun> const& planetarium_rotation) const;
// Coordinate transforms.
virtual RigidMotion<Barycentric, Navigation> BarycentricToPlotting(
Instant const& time) const;
virtual RigidTransformation<Barycentric, World> BarycentricToWorld(
Instant const& time,
Position<World> const& sun_world_position,
Rotation<Barycentric, AliceSun> const& planetarium_rotation) const;
virtual OrthogonalMap<Barycentric, World> BarycentricToWorld(
Rotation<Barycentric, AliceSun> const& planetarium_rotation) const;
virtual OrthogonalMap<Barycentric, WorldSun> BarycentricToWorldSun(
Rotation<Barycentric, AliceSun> const& planetarium_rotation) const;
// Converts from the Frenet frame of the manœuvre's initial time in the
// plotted frame to the |World| coordinates.
virtual OrthogonalMap<Frenet<Navigation>, World> FrenetToWorld(
Instant const& time,
NavigationManœuvre const& manœuvre,
Rotation<Barycentric, AliceSun> const& planetarium_rotation) const;
// Converts from the Frenet frame of the vessel's free-falling trajectory in
// the plotted frame to the |World| coordinates.
virtual OrthogonalMap<Frenet<Navigation>, World> FrenetToWorld(
Vessel const& vessel,
Rotation<Barycentric, AliceSun> const& planetarium_rotation) const;
// Converts from the Frenet frame of the vessel's free-falling trajectory in
// the given |navigation_frame| to the |World| coordinates.
virtual OrthogonalMap<Frenet<Navigation>, World> FrenetToWorld(
Vessel const& vessel,
NavigationFrame const& navigation_frame,
Rotation<Barycentric, AliceSun> const& planetarium_rotation) const;
virtual OrthogonalMap<Navigation, Barycentric> PlottingToBarycentric(
Instant const& time) const;
virtual RigidTransformation<Navigation, World> PlottingToWorld(
Instant const& time,
Position<World> const& sun_world_position,
Rotation<Barycentric, AliceSun> const& planetarium_rotation) const;
virtual OrthogonalMap<Navigation, World> PlottingToWorld(
Instant const& time,
Rotation<Barycentric, AliceSun> const& planetarium_rotation) const;
virtual RigidTransformation<World, Barycentric> WorldToBarycentric(
Instant const& time,
Position<World> const& sun_world_position,
Rotation<Barycentric, AliceSun> const& planetarium_rotation) const;
virtual OrthogonalMap<World, Barycentric> WorldToBarycentric(
Rotation<Barycentric, AliceSun> const& planetarium_rotation) const;
virtual RigidTransformation<World, Navigation> WorldToPlotting(
Instant const& time,
Position<World> const& sun_world_position,
Rotation<Barycentric, AliceSun> const& planetarium_rotation) const;
virtual void WriteToMessage(not_null<serialization::Renderer*> message) const;
static not_null<std::unique_ptr<Renderer>> ReadFromMessage(
serialization::Renderer const& message,
not_null<Celestial const*> sun,
not_null<Ephemeris<Barycentric> const*> ephemeris);
private:
struct Target {
Target(not_null<Vessel*> vessel,
not_null<Celestial const*> celestial,
not_null<Ephemeris<Barycentric> const*> ephemeris);
not_null<Vessel*> const vessel;
not_null<Celestial const*> const celestial;
not_null<std::unique_ptr<NavigationFrame>> const target_frame;
};
// Returns a plotting frame suitable for evaluation at |time|, possibly by
// extending the prediction if there is a target vessel.
not_null<NavigationFrame const*> GetPlottingFrame(Instant const& time) const;
not_null<Celestial const*> const sun_;
not_null<std::unique_ptr<NavigationFrame>> plotting_frame_;
std::experimental::optional<Target> target_;
};
} // namespace internal_renderer
using internal_renderer::Renderer;
} // namespace ksp_plugin
} // namespace principia
<commit_msg>Add virtual destructor to Renderer<commit_after>#pragma once
#include <experimental/optional>
#include <functional>
#include <memory>
#include "base/not_null.hpp"
#include "geometry/affine_map.hpp"
#include "geometry/named_quantities.hpp"
#include "geometry/orthogonal_map.hpp"
#include "geometry/rotation.hpp"
#include "ksp_plugin/celestial.hpp"
#include "ksp_plugin/frames.hpp"
#include "ksp_plugin/vessel.hpp"
#include "physics/discrete_trajectory.hpp"
#include "physics/dynamic_frame.hpp"
#include "physics/ephemeris.hpp"
#include "physics/rigid_motion.hpp"
#include "quantities/quantities.hpp"
namespace principia {
namespace ksp_plugin {
namespace internal_renderer {
using base::not_null;
using geometry::AffineMap;
using geometry::Instant;
using geometry::OrthogonalMap;
using geometry::Position;
using geometry::RigidTransformation;
using geometry::Rotation;
using physics::DiscreteTrajectory;
using physics::Ephemeris;
using physics::Frenet;
using physics::RigidMotion;
using quantities::Length;
class Renderer {
public:
Renderer(not_null<Celestial const*> sun,
not_null<std::unique_ptr<NavigationFrame>> plotting_frame);
virtual ~Renderer() = default;
// Changes the plotting frame of the renderer.
virtual void SetPlottingFrame(
not_null<std::unique_ptr<NavigationFrame>> plotting_frame);
// Returns the current plotting frame. This may not be the last set by
// |SetPlottingFrame| if it is overridden by a target vessel.
virtual not_null<NavigationFrame const*> GetPlottingFrame() const;
// Overrides the current plotting frame with one that is centred on the given
// |vessel|.
virtual void SetTargetVessel(
not_null<Vessel*> vessel,
not_null<Celestial const*> celestial,
not_null<Ephemeris<Barycentric> const*> ephemeris);
// Reverts to frame last set by |SetPlottingFrame|. The second version only
// has an effect if the given |vessel| is the current target vessel.
virtual void ClearTargetVessel();
virtual void ClearTargetVesselIf(not_null<Vessel*> vessel);
// Determines if there is a target vessel and returns it.
virtual bool HasTargetVessel() const;
virtual Vessel& GetTargetVessel();
virtual Vessel const& GetTargetVessel() const;
// If there is a target vessel, returns its prediction after extending it up
// to |time|.
virtual DiscreteTrajectory<Barycentric> const& GetTargetVesselPrediction(
Instant const& time) const;
// Returns a trajectory in |World| corresponding to the trajectory defined by
// |begin| and |end|, as seen in the current plotting frame. In this function
// and others in this class, |sun_world_position| is the current position of
// the sun in |World| space as returned by |Planetarium.fetch.Sun.position|;
// it is used to define the relation between |WorldSun| and |World|.
virtual not_null<std::unique_ptr<DiscreteTrajectory<World>>>
RenderBarycentricTrajectoryInWorld(
Instant const& time,
DiscreteTrajectory<Barycentric>::Iterator const& begin,
DiscreteTrajectory<Barycentric>::Iterator const& end,
Position<World> const& sun_world_position,
Rotation<Barycentric, AliceSun> const& planetarium_rotation) const;
// Returns a trajectory in the current plotting frame corresponding to the
// trajectory defined by |begin| and |end|. If there is a target vessel, its
// prediction must not be empty.
virtual not_null<std::unique_ptr<DiscreteTrajectory<Navigation>>>
RenderBarycentricTrajectoryInPlotting(
DiscreteTrajectory<Barycentric>::Iterator const& begin,
DiscreteTrajectory<Barycentric>::Iterator const& end) const;
// Returns a trajectory in |World| corresponding to the trajectory defined by
// |begin| and |end| in the current plotting frame.
virtual not_null<std::unique_ptr<DiscreteTrajectory<World>>>
RenderPlottingTrajectoryInWorld(
Instant const& time,
DiscreteTrajectory<Navigation>::Iterator const& begin,
DiscreteTrajectory<Navigation>::Iterator const& end,
Position<World> const& sun_world_position,
Rotation<Barycentric, AliceSun> const& planetarium_rotation) const;
// Coordinate transforms.
virtual RigidMotion<Barycentric, Navigation> BarycentricToPlotting(
Instant const& time) const;
virtual RigidTransformation<Barycentric, World> BarycentricToWorld(
Instant const& time,
Position<World> const& sun_world_position,
Rotation<Barycentric, AliceSun> const& planetarium_rotation) const;
virtual OrthogonalMap<Barycentric, World> BarycentricToWorld(
Rotation<Barycentric, AliceSun> const& planetarium_rotation) const;
virtual OrthogonalMap<Barycentric, WorldSun> BarycentricToWorldSun(
Rotation<Barycentric, AliceSun> const& planetarium_rotation) const;
// Converts from the Frenet frame of the manœuvre's initial time in the
// plotted frame to the |World| coordinates.
virtual OrthogonalMap<Frenet<Navigation>, World> FrenetToWorld(
Instant const& time,
NavigationManœuvre const& manœuvre,
Rotation<Barycentric, AliceSun> const& planetarium_rotation) const;
// Converts from the Frenet frame of the vessel's free-falling trajectory in
// the plotted frame to the |World| coordinates.
virtual OrthogonalMap<Frenet<Navigation>, World> FrenetToWorld(
Vessel const& vessel,
Rotation<Barycentric, AliceSun> const& planetarium_rotation) const;
// Converts from the Frenet frame of the vessel's free-falling trajectory in
// the given |navigation_frame| to the |World| coordinates.
virtual OrthogonalMap<Frenet<Navigation>, World> FrenetToWorld(
Vessel const& vessel,
NavigationFrame const& navigation_frame,
Rotation<Barycentric, AliceSun> const& planetarium_rotation) const;
virtual OrthogonalMap<Navigation, Barycentric> PlottingToBarycentric(
Instant const& time) const;
virtual RigidTransformation<Navigation, World> PlottingToWorld(
Instant const& time,
Position<World> const& sun_world_position,
Rotation<Barycentric, AliceSun> const& planetarium_rotation) const;
virtual OrthogonalMap<Navigation, World> PlottingToWorld(
Instant const& time,
Rotation<Barycentric, AliceSun> const& planetarium_rotation) const;
virtual RigidTransformation<World, Barycentric> WorldToBarycentric(
Instant const& time,
Position<World> const& sun_world_position,
Rotation<Barycentric, AliceSun> const& planetarium_rotation) const;
virtual OrthogonalMap<World, Barycentric> WorldToBarycentric(
Rotation<Barycentric, AliceSun> const& planetarium_rotation) const;
virtual RigidTransformation<World, Navigation> WorldToPlotting(
Instant const& time,
Position<World> const& sun_world_position,
Rotation<Barycentric, AliceSun> const& planetarium_rotation) const;
virtual void WriteToMessage(not_null<serialization::Renderer*> message) const;
static not_null<std::unique_ptr<Renderer>> ReadFromMessage(
serialization::Renderer const& message,
not_null<Celestial const*> sun,
not_null<Ephemeris<Barycentric> const*> ephemeris);
private:
struct Target {
Target(not_null<Vessel*> vessel,
not_null<Celestial const*> celestial,
not_null<Ephemeris<Barycentric> const*> ephemeris);
not_null<Vessel*> const vessel;
not_null<Celestial const*> const celestial;
not_null<std::unique_ptr<NavigationFrame>> const target_frame;
};
// Returns a plotting frame suitable for evaluation at |time|, possibly by
// extending the prediction if there is a target vessel.
not_null<NavigationFrame const*> GetPlottingFrame(Instant const& time) const;
not_null<Celestial const*> const sun_;
not_null<std::unique_ptr<NavigationFrame>> plotting_frame_;
std::experimental::optional<Target> target_;
};
} // namespace internal_renderer
using internal_renderer::Renderer;
} // namespace ksp_plugin
} // namespace principia
<|endoftext|> |
<commit_before>#ifndef RADIUMENGINE_VIEWER_HPP
#define RADIUMENGINE_VIEWER_HPP
#include <GuiBase/RaGuiBase.hpp>
#include <atomic>
#include <memory>
#include <Engine/RadiumEngine.hpp>
#include <QOpenGLWidget>
#include <QThread>
#include <Core/Math/LinearAlgebra.hpp>
#include <GuiBase/Viewer/Gizmo/GizmoManager.hpp>
#include <GuiBase/Utils/FeaturePickingManager.hpp>
// Forward declarations
namespace Ra
{
namespace Core
{
struct KeyEvent;
struct MouseEvent;
}
}
namespace Ra
{
namespace Engine
{
class Renderer;
}
}
namespace Ra
{
namespace Gui
{
class CameraInterface;
class GizmoManager;
}
}
namespace Ra
{
namespace Gui
{
// FIXME (Charly) : Which way do we want to be able to change renderers ?
// Can it be done during runtime ? Must it be at startup ? ...
// For now, default ForwardRenderer is used.
/// The Viewer is the main display class. It's the central screen QWidget.
/// Its acts as a bridge between the interface, the engine and the renderer
/// Among its responsibilities are :
/// * Owning the renderer and camera, and managing their lifetime.
/// * setting up the renderer and camera by keeping it informed of interfaces changes
/// (e.g. resize).
/// * catching user interaction (mouse clicks) at the lowest level and forward it to
/// the camera and the rest of the application
/// * Expose the asynchronous rendering interface
class RA_GUIBASE_API Viewer : public QOpenGLWidget
{
Q_OBJECT
public:
/// Constructor
explicit Viewer( QWidget* parent = nullptr );
/// Destructor
~Viewer();
//
// Accessors
//
/// Access to camera interface.
CameraInterface* getCameraInterface();
/// Access to gizmo manager
GizmoManager* getGizmoManager();
/// Read-only access to renderer
const Engine::Renderer* getRenderer() const;
/// Read-write access to renderer
Engine::Renderer* getRenderer();
/// Access to the feature picking manager
FeaturePickingManager* getFeaturePickingManager();
//
// Rendering management
//
/// Start rendering (potentially asynchronously in a separate thread)
void startRendering( const Scalar dt );
/// Blocks until rendering is finished.
void waitForRendering();
//
// Misc functions
//
/// Load data from a file.
void handleFileLoading( const std::string& file );
/// Load data from a FileData.
void handleFileLoading( const Ra::Asset::FileData &filedata );
/// Emits signals corresponding to picking requests.
void processPicking();
/// Moves the camera so that the whole scene is visible.
void fitCameraToScene( const Core::Aabb& sceneAabb );
/// Returns the names of the different registred renderers.
std::vector<std::string> getRenderersName() const;
/// Write the current frame as an image. Supports either BMP or PNG file names.
void grabFrame( const std::string& filename );
signals:
void glInitialized(); //! Emitted when GL context is ready. We except call to addRenderer here
void rendererReady(); //! Emitted when the rendered is correctly initialized
void leftClickPicking ( int id ); //! Emitted when the result of a left click picking is known
void rightClickPicking( int id ); //! Emitted when the resut of a right click picking is known
public slots:
/// Tell the renderer to reload all shaders.
void reloadShaders();
/// Set the final display texture
void displayTexture( const QString& tex );
/// Set the renderer
void changeRenderer( int index );
/// Toggle the post-process effetcs
void enablePostProcess(int enabled);
/// Toggle the debug drawing
void enableDebugDraw(int enabled);
/// Resets the camaera to initial values
void resetCamera();
/** Add a renderer and return its index. Need to be called when catching
* \param e : unique_ptr to your own renderer
* \return index of the newly added renderer
* \code
* int rendererId = addRenderer(new MyRenderer(width(), height()));
* changeRenderer(rendererId);
* getRenderer()->initialize();
* auto light = Ra::Core::make_shared<Engine::DirectionalLight>();
* getRenderer()->addLight( light );
* m_camera->attachLight( light );
* \endcode
*/
int addRenderer(std::shared_ptr<Engine::Renderer> e);
private slots:
/// These slots are connected to the base class signals to properly handle
/// concurrent access to the renderer.
void onAboutToCompose();
void onAboutToResize();
void onFrameSwapped();
void onResized();
protected:
/// Initialize renderer internal state + configure lights.
void intializeRenderer(Engine::Renderer* renderer);
//
// QOpenGlWidget primitives
//
/// Initialize openGL. Called on by the first "show" call to the main window.
virtual void initializeGL() override;
/// Resize the view port and the camera. Called by the resize event.
virtual void resizeGL( int width, int height ) override;
/// Paint event is set to a no-op to prevent synchronous rendering.
/// We don't implement paintGL as well.
virtual void paintEvent( QPaintEvent* e ) override {}
//
// Qt input events.
//
virtual void keyPressEvent( QKeyEvent* event ) override;
virtual void keyReleaseEvent( QKeyEvent* event ) override;
/// We intercept the mouse events in this widget to get the coordinates of the mouse
/// in screen space.
virtual void mousePressEvent( QMouseEvent* event ) override;
virtual void mouseReleaseEvent( QMouseEvent* event ) override;
virtual void mouseMoveEvent( QMouseEvent* event ) override;
virtual void wheelEvent( QWheelEvent* event ) override;
public:
Scalar m_dt;
protected:
/// Owning pointer to the renderers.
std::vector<std::shared_ptr<Engine::Renderer>> m_renderers;
Engine::Renderer* m_currentRenderer;
/// Owning Pointer to the feature picking manager.
FeaturePickingManager* m_featurePickingManager;
/// Owning pointer to the camera.
std::unique_ptr<CameraInterface> m_camera;
/// Owning (QObject child) pointer to gizmo manager.
GizmoManager* m_gizmoManager;
/// Thread in which rendering is done.
QThread* m_renderThread; // We have to use a QThread for MT rendering
/// GL initialization status
std::atomic_bool m_glInitStatus;
};
} // namespace Gui
} // namespace Ra
#endif // RADIUMENGINE_VIEWER_HPP
<commit_msg>add missing include directive<commit_after>#ifndef RADIUMENGINE_VIEWER_HPP
#define RADIUMENGINE_VIEWER_HPP
#include <GuiBase/RaGuiBase.hpp>
#include <atomic>
#include <memory>
#include <atomic>
#include <Engine/RadiumEngine.hpp>
#include <QOpenGLWidget>
#include <QThread>
#include <Core/Math/LinearAlgebra.hpp>
#include <GuiBase/Viewer/Gizmo/GizmoManager.hpp>
#include <GuiBase/Utils/FeaturePickingManager.hpp>
// Forward declarations
namespace Ra
{
namespace Core
{
struct KeyEvent;
struct MouseEvent;
}
}
namespace Ra
{
namespace Engine
{
class Renderer;
}
}
namespace Ra
{
namespace Gui
{
class CameraInterface;
class GizmoManager;
}
}
namespace Ra
{
namespace Gui
{
// FIXME (Charly) : Which way do we want to be able to change renderers ?
// Can it be done during runtime ? Must it be at startup ? ...
// For now, default ForwardRenderer is used.
/// The Viewer is the main display class. It's the central screen QWidget.
/// Its acts as a bridge between the interface, the engine and the renderer
/// Among its responsibilities are :
/// * Owning the renderer and camera, and managing their lifetime.
/// * setting up the renderer and camera by keeping it informed of interfaces changes
/// (e.g. resize).
/// * catching user interaction (mouse clicks) at the lowest level and forward it to
/// the camera and the rest of the application
/// * Expose the asynchronous rendering interface
class RA_GUIBASE_API Viewer : public QOpenGLWidget
{
Q_OBJECT
public:
/// Constructor
explicit Viewer( QWidget* parent = nullptr );
/// Destructor
~Viewer();
//
// Accessors
//
/// Access to camera interface.
CameraInterface* getCameraInterface();
/// Access to gizmo manager
GizmoManager* getGizmoManager();
/// Read-only access to renderer
const Engine::Renderer* getRenderer() const;
/// Read-write access to renderer
Engine::Renderer* getRenderer();
/// Access to the feature picking manager
FeaturePickingManager* getFeaturePickingManager();
//
// Rendering management
//
/// Start rendering (potentially asynchronously in a separate thread)
void startRendering( const Scalar dt );
/// Blocks until rendering is finished.
void waitForRendering();
//
// Misc functions
//
/// Load data from a file.
void handleFileLoading( const std::string& file );
/// Load data from a FileData.
void handleFileLoading( const Ra::Asset::FileData &filedata );
/// Emits signals corresponding to picking requests.
void processPicking();
/// Moves the camera so that the whole scene is visible.
void fitCameraToScene( const Core::Aabb& sceneAabb );
/// Returns the names of the different registred renderers.
std::vector<std::string> getRenderersName() const;
/// Write the current frame as an image. Supports either BMP or PNG file names.
void grabFrame( const std::string& filename );
signals:
void glInitialized(); //! Emitted when GL context is ready. We except call to addRenderer here
void rendererReady(); //! Emitted when the rendered is correctly initialized
void leftClickPicking ( int id ); //! Emitted when the result of a left click picking is known
void rightClickPicking( int id ); //! Emitted when the resut of a right click picking is known
public slots:
/// Tell the renderer to reload all shaders.
void reloadShaders();
/// Set the final display texture
void displayTexture( const QString& tex );
/// Set the renderer
void changeRenderer( int index );
/// Toggle the post-process effetcs
void enablePostProcess(int enabled);
/// Toggle the debug drawing
void enableDebugDraw(int enabled);
/// Resets the camaera to initial values
void resetCamera();
/** Add a renderer and return its index. Need to be called when catching
* \param e : unique_ptr to your own renderer
* \return index of the newly added renderer
* \code
* int rendererId = addRenderer(new MyRenderer(width(), height()));
* changeRenderer(rendererId);
* getRenderer()->initialize();
* auto light = Ra::Core::make_shared<Engine::DirectionalLight>();
* getRenderer()->addLight( light );
* m_camera->attachLight( light );
* \endcode
*/
int addRenderer(std::shared_ptr<Engine::Renderer> e);
private slots:
/// These slots are connected to the base class signals to properly handle
/// concurrent access to the renderer.
void onAboutToCompose();
void onAboutToResize();
void onFrameSwapped();
void onResized();
protected:
/// Initialize renderer internal state + configure lights.
void intializeRenderer(Engine::Renderer* renderer);
//
// QOpenGlWidget primitives
//
/// Initialize openGL. Called on by the first "show" call to the main window.
virtual void initializeGL() override;
/// Resize the view port and the camera. Called by the resize event.
virtual void resizeGL( int width, int height ) override;
/// Paint event is set to a no-op to prevent synchronous rendering.
/// We don't implement paintGL as well.
virtual void paintEvent( QPaintEvent* e ) override {}
//
// Qt input events.
//
virtual void keyPressEvent( QKeyEvent* event ) override;
virtual void keyReleaseEvent( QKeyEvent* event ) override;
/// We intercept the mouse events in this widget to get the coordinates of the mouse
/// in screen space.
virtual void mousePressEvent( QMouseEvent* event ) override;
virtual void mouseReleaseEvent( QMouseEvent* event ) override;
virtual void mouseMoveEvent( QMouseEvent* event ) override;
virtual void wheelEvent( QWheelEvent* event ) override;
public:
Scalar m_dt;
protected:
/// Owning pointer to the renderers.
std::vector<std::shared_ptr<Engine::Renderer>> m_renderers;
Engine::Renderer* m_currentRenderer;
/// Owning Pointer to the feature picking manager.
FeaturePickingManager* m_featurePickingManager;
/// Owning pointer to the camera.
std::unique_ptr<CameraInterface> m_camera;
/// Owning (QObject child) pointer to gizmo manager.
GizmoManager* m_gizmoManager;
/// Thread in which rendering is done.
QThread* m_renderThread; // We have to use a QThread for MT rendering
/// GL initialization status
std::atomic_bool m_glInitStatus;
};
} // namespace Gui
} // namespace Ra
#endif // RADIUMENGINE_VIEWER_HPP
<|endoftext|> |
<commit_before>#include <HealthEcho/HealthEcho.h>
#include <iostream>
#include <nsh/nsh.h>
#include <nsh/nsh_oam_echo.h>
#include <Packet.h>
#include <Interfaces/NetInterface.h>
void HealthEcho::Receive(nshdev::PacketRef& packetRef, nshdev::NetInterface& receiveInterface)
{
const nsh_hdr* nsh = reinterpret_cast<const nsh_hdr*>(packetRef.Data());
unsigned next = nsh_get_next_header(nsh);
bool oam = nsh_is_oam_packet(nsh);
std::cout << "Received NSH packet SPI=" << nsh_get_path_id(&nsh->service_hdr) << ", SI=" << unsigned(nsh_get_service_index(&nsh->service_hdr)) << ", OAM=" << oam << ", next type=" << next << std::endl;
if(oam && next == 254)
{
uint8_t* pEcho = packetRef.Data() + nsh_get_size(nsh);
nsh_oam_echo* echo = reinterpret_cast<nsh_oam_echo*>(pEcho);
std::cout << "Echo subcode="<< nsh_oam_get_subcode(echo) << ", length=" << nsh_oam_get_length(echo) << ", dst=" << nsh_oam_get_dst_id(echo) << ", trn=" << nsh_oam_get_trn_id(echo) << std::endl;
if(nsh_oam_get_subcode(echo) == NSH_ECHO_REQUEST)
{
nsh_oam_set_subcode(echo, NSH_ECHO_RESPOND);
receiveInterface.ReturnToSender(packetRef);
}
}
}
<commit_msg>comment-out the verbose logging<commit_after>#include <HealthEcho/HealthEcho.h>
#include <iostream>
#include <nsh/nsh.h>
#include <nsh/nsh_oam_echo.h>
#include <Packet.h>
#include <Interfaces/NetInterface.h>
void HealthEcho::Receive(nshdev::PacketRef& packetRef, nshdev::NetInterface& receiveInterface)
{
const nsh_hdr* nsh = reinterpret_cast<const nsh_hdr*>(packetRef.Data());
unsigned next = nsh_get_next_header(nsh);
bool oam = nsh_is_oam_packet(nsh);
// std::cout << "Received NSH packet SPI=" << nsh_get_path_id(&nsh->service_hdr) << ", SI=" << unsigned(nsh_get_service_index(&nsh->service_hdr)) << ", OAM=" << oam << ", next type=" << next << std::endl;
if(oam && next == 254)
{
uint8_t* pEcho = packetRef.Data() + nsh_get_size(nsh);
nsh_oam_echo* echo = reinterpret_cast<nsh_oam_echo*>(pEcho);
// std::cout << "Echo subcode="<< nsh_oam_get_subcode(echo) << ", length=" << nsh_oam_get_length(echo) << ", dst=" << nsh_oam_get_dst_id(echo) << ", trn=" << nsh_oam_get_trn_id(echo) << std::endl;
if(nsh_oam_get_subcode(echo) == NSH_ECHO_REQUEST)
{
nsh_oam_set_subcode(echo, NSH_ECHO_RESPOND);
receiveInterface.ReturnToSender(packetRef);
}
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <SFML/Graphics.hpp>
#include <SFML/OpenGL.hpp>
#include <DMUtils/maths.hpp>
#include <DMUtils/sfml.hpp>
#include <Lightsystem/SpotLight.hpp>
namespace DMGDVT {
namespace LS {
SpotLight::SpotLight(bool iso) : SpotLight(sf::Vector2f(0,0),0,sf::Color(0,0,0,0)) {
}
SpotLight::~SpotLight() {
}
SpotLight::SpotLight(sf::Vector2f ctr, float r, sf::Color c, bool iso) : SpotLight(ctr,r,c,0.0f,2.0f*M_PIf,1.0f,0.0f,1.0f,iso) {
}
SpotLight::SpotLight(sf::Vector2f ctr, float r, sf::Color c, float da, float sa, float i, float b, float lf, bool iso) : Light(iso),
_position(ctr), _radius(r), _color(c), _directionAngle(da), _spreadAngle(sa), _bleed(b), _linearity(lf) {
setSpreadAngle(sa);
setIntensity(i);
computeAABB();
//32 points for a full circle, so we keep same spacing
if(_spreadAngle > M_PIf * 3.0f/4.0f) _precision = 32;
else if(_spreadAngle > M_PIf) _precision = 16;
else if (_spreadAngle < M_PIf/2.0f) _precision = 4;
else _precision = 8;
}
void SpotLight::preRender(sf::Shader* shader) {
if(shader==nullptr) return; //oopsie, can't work without the shader
const float diam = _radius*2.0f;
if(_renderTexture==nullptr) _renderTexture = new sf::RenderTexture();
if(diam != _renderTexture->getSize().x && !_renderTexture->create(diam,diam)) {
std::cerr << "Error : couldn't create a texture of size " << diam << " x " << diam << std::endl;
delete _renderTexture;
_renderTexture=nullptr;
return; //somehow texture failed, maybe too big, abort
}
float r = _color.r * _intensity;
float g = _color.g * _intensity;
float b = _color.b * _intensity;
sf::Color c(r,g,b,255);
_renderTexture->clear();
//shader parameters
shader->setParameter(DMGDVT::LS::Light::LAS_PARAM_CENTER,sf::Vector2f(_radius,_radius));
shader->setParameter(DMGDVT::LS::Light::LAS_PARAM_RADIUS,_radius);
shader->setParameter(DMGDVT::LS::Light::LAS_PARAM_COLOR,c);
shader->setParameter(DMGDVT::LS::Light::LAS_PARAM_BLEED,_bleed);
shader->setParameter(DMGDVT::LS::Light::LAS_PARAM_LINEARITY,_linearity);
shader->setParameter(DMGDVT::LS::Light::LAS_PARAM_OUTLINE,false); //for debug
shader->setParameter(DMGDVT::LS::Light::LAS_PARAM_ISOMETRIC,_isometric);
if(_spreadAngle==M_PIf*2.0f) {
_sprite.setTexture(_renderTexture->getTexture());
_sprite.setOrigin(sf::Vector2f(_radius,_radius));
_sprite.setPosition(_position);
sf::RectangleShape rect(sf::Vector2f(diam,diam));
_renderTexture->draw(rect,shader);
} else {
_sprite.setTexture(_renderTexture->getTexture());
_sprite.setPosition(_position);
_sprite.setOrigin(sf::Vector2f(_radius,_radius));
sf::ConvexShape shape;
float deltaAngle = _spreadAngle / (float)(_precision-1);
shape.setPointCount(_precision+1);
shape.setPoint(0,sf::Vector2f(_radius,_radius));
for(int i=0;i<_precision;++i) {
float angle = - _spreadAngle/2.0f + (float)i*deltaAngle;
shape.setPoint(i+1,DMUtils::sfml::rotate(shape.getPoint(0)+sf::Vector2f(0.0f,_radius),angle,shape.getPoint(0)));
}
_renderTexture->draw(shape,shader);
_sprite.setRotation(DMUtils::maths::radToDeg(_directionAngle));
}
_renderTexture->display();
}
void SpotLight::render(const sf::IntRect& screen, sf::RenderTarget& target, sf::Shader* shader, const sf::RenderStates &states) {
if(_intensity <= 0.0f) return;
if(_renderTexture!=nullptr) {
//draw the sprite
target.draw(_sprite,states);
} else {
//need to find a way to put thiis as common code between render and preRender
float r = _color.r * _intensity;
float g = _color.g * _intensity;
float b = _color.b * _intensity;
sf::Color c(r,g,b,255);
const float diam = _radius*2.0f;
sf::Vector2f radVec(_radius,_radius);
sf::Vector2f newCenter = _position - sf::Vector2f(screen.left,screen.top);
// for some reason in this case it considers the center to be from the bottom of the screen
shader->setParameter(DMGDVT::LS::Light::LAS_PARAM_CENTER,sf::Vector2f(newCenter.x,screen.height - newCenter.y));
shader->setParameter(DMGDVT::LS::Light::LAS_PARAM_RADIUS,_radius);
shader->setParameter(DMGDVT::LS::Light::LAS_PARAM_COLOR,c);
shader->setParameter(DMGDVT::LS::Light::LAS_PARAM_BLEED,_bleed);
shader->setParameter(DMGDVT::LS::Light::LAS_PARAM_LINEARITY,_linearity);
shader->setParameter(DMGDVT::LS::Light::LAS_PARAM_OUTLINE,false); //for debug
shader->setParameter(DMGDVT::LS::Light::LAS_PARAM_ISOMETRIC,_isometric);
sf::RenderStates st(states);
st.shader = shader;
if(_spreadAngle==M_PIf*2.0f) {
sf::RectangleShape rect(sf::Vector2f(diam,diam));
rect.setOrigin(radVec);
rect.setPosition(_position);
target.draw(rect,st);
} else {
sf::ConvexShape shape;
shape.setPosition(_position);
shape.setOrigin(radVec);
float deltaAngle = _spreadAngle / (float)(_precision-1);
shape.setPointCount(_precision+1);
shape.setPoint(0,sf::Vector2f(_radius,_radius));
for(int i=0;i<_precision;++i) {
float angle = - _spreadAngle/2.0f + (float)i*deltaAngle;
shape.setPoint(i+1,DMUtils::sfml::rotate(shape.getPoint(0)+sf::Vector2f(0.0f,_radius),angle,shape.getPoint(0)));
}
shape.setRotation(DMUtils::maths::radToDeg(_directionAngle));
target.draw(shape,st);
}
}
}
void SpotLight::debugRender(sf::RenderTarget& target, const sf::RenderStates &states) {
if(_intensity <= 0.0f) return;
if(_spreadAngle == M_PIf*2.0f) {
sf::CircleShape shape(_radius);
shape.setPosition(_position);
shape.setOrigin(sf::Vector2f(1,1)*_radius);
shape.setFillColor(_color);
target.draw(shape,states);
} else {
sf::ConvexShape shape;
shape.setPointCount(4);
shape.setFillColor(sf::Color(_color.r,_color.g,_color.b,125));
sf::Vector2f v(0,_radius);
//*
shape.setPosition(_position);
shape.setPoint(0,sf::Vector2f(0,0));
shape.setPoint(1,DMUtils::sfml::rotate(v,-_spreadAngle/2.0f));
shape.setPoint(2,v);
shape.setPoint(3,DMUtils::sfml::rotate(v,_spreadAngle/2.0f));
shape.setRotation(DMUtils::maths::radToDeg(_directionAngle));
target.draw(shape,states);
}
}
void SpotLight::drawAABB(const sf::IntRect& screen, sf::RenderTarget& target) {
sf::IntRect box = getAABB();
sf::Vertex lines[] = {
sf::Vertex(sf::Vector2f(box.left, box.top),_color),
sf::Vertex(sf::Vector2f(box.left+box.width, box.top),_color),
sf::Vertex(sf::Vector2f(box.left+box.width, box.top+box.height),_color),
sf::Vertex(sf::Vector2f(box.left, box.top+box.height),_color),
lines[0]
};
target.draw(lines,5,sf::LinesStrip);
}
void SpotLight::computeAABB() {
if(_spreadAngle == M_PIf*2.0f) {
_aabb.left = -_radius;
_aabb.top = -_radius;
_aabb.width = _aabb.height = _radius*2.0f;
} else {
// @TODO : move the rotation function to a real good DMGDVT::sfUtils folder
sf::Vector2f v = DMUtils::sfml::rotate<float>(sf::Vector2f(0.0,_radius),_directionAngle);
sf::Vector2f left = DMUtils::sfml::rotate<float>(v,-_spreadAngle/2.0f,_directionAngle);
sf::Vector2f right = DMUtils::sfml::rotate<float>(v,_spreadAngle/2.0f,_directionAngle);
int xmin = DMUtils::maths::min<float>(v.x, left.x, right.x, 0.0f);
int xmax = DMUtils::maths::max<float>(v.x, left.x, right.x, 0.0f);
int ymin = DMUtils::maths::min<float>(v.y, left.y, right.y, 0.0f);
int ymax = DMUtils::maths::max<float>(v.y, left.y, right.y, 0.0f);
_aabb.left = xmin;
_aabb.top = ymin;
_aabb.width = xmax - xmin;
_aabb.height = ymax - ymin;
}
}
/*** GETTER - SETTER ***/
sf::IntRect SpotLight::getAABB() {
return sf::IntRect(sf::Vector2i(_aabb.left+static_cast<int>(_position.x),_aabb.top+static_cast<int>(_position.y)),sf::Vector2i(_aabb.width,_aabb.height));
}
void SpotLight::setPosition(sf::Vector2f c) {
_position = c;
_sprite.setPosition(c);
}
sf::Vector2f SpotLight::getPosition() const {
return _position;
}
void SpotLight::setRadius(float r) {
_radius = r;
}
float SpotLight::getRadius() const {
return _radius;
}
void SpotLight::setColor(sf::Color c) {
_color = c;
}
sf::Color SpotLight::getColor() const {
return _color;
}
void SpotLight::setDirectionAngle(float da) {
_directionAngle = da;
_sprite.setRotation(DMUtils::maths::radToDeg(_directionAngle));
}
float SpotLight::getDirectionAngle() const {
return _directionAngle;
}
void SpotLight::rotate(float delta) {
float a = _directionAngle + delta;
while(a > 2.0*M_PIf) a -= 2.0*M_PIf;
while(a < 0) a += 2.0*M_PIf;
setDirectionAngle(a);
}
void SpotLight::setSpreadAngle(float sa) {
if(sa<0) sa = -sa;
while(sa > 2.0f*M_PIf) sa = 2.0f*M_PIf;
_spreadAngle = sa;
}
float SpotLight::getSpreadAngle() const {
return _spreadAngle;
}
void SpotLight::setIntensity(float i) {
DMUtils::maths::clamp(i,0.0f,1.0f);
_intensity = i;
}
float SpotLight::getIntensity() const {
return _intensity;
}
void SpotLight::setBleed(float b) {
_bleed = b;
}
float SpotLight::getBleed() const {
return _bleed;
}
void SpotLight::setLinearity(float lf) {
_linearity = lf;
}
float SpotLight::getLinearity() const {
return _linearity;
}
void SpotLight::setPrecision(int p) {
_precision = p;
}
int SpotLight::getPrecision() const {
return _precision;
}
/*** PROTECTED ***/
}
}
<commit_msg>Corrected debugRender for SpotLight (fix issue #6)<commit_after>#include <iostream>
#include <SFML/Graphics.hpp>
#include <SFML/OpenGL.hpp>
#include <DMUtils/maths.hpp>
#include <DMUtils/sfml.hpp>
#include <Lightsystem/SpotLight.hpp>
namespace DMGDVT {
namespace LS {
SpotLight::SpotLight(bool iso) : SpotLight(sf::Vector2f(0,0),0,sf::Color(0,0,0,0)) {
}
SpotLight::~SpotLight() {
}
SpotLight::SpotLight(sf::Vector2f ctr, float r, sf::Color c, bool iso) : SpotLight(ctr,r,c,0.0f,2.0f*M_PIf,1.0f,0.0f,1.0f,iso) {
}
SpotLight::SpotLight(sf::Vector2f ctr, float r, sf::Color c, float da, float sa, float i, float b, float lf, bool iso) : Light(iso),
_position(ctr), _radius(r), _color(c), _directionAngle(da), _spreadAngle(sa), _bleed(b), _linearity(lf) {
setSpreadAngle(sa);
setIntensity(i);
computeAABB();
//32 points for a full circle, so we keep same spacing
if(_spreadAngle > M_PIf * 3.0f/4.0f) _precision = 32;
else if(_spreadAngle > M_PIf) _precision = 16;
else if (_spreadAngle < M_PIf/2.0f) _precision = 4;
else _precision = 8;
}
void SpotLight::preRender(sf::Shader* shader) {
if(shader==nullptr) return; //oopsie, can't work without the shader
const float diam = _radius*2.0f;
if(_renderTexture==nullptr) _renderTexture = new sf::RenderTexture();
if(diam != _renderTexture->getSize().x && !_renderTexture->create(diam,diam)) {
std::cerr << "Error : couldn't create a texture of size " << diam << " x " << diam << std::endl;
delete _renderTexture;
_renderTexture=nullptr;
return; //somehow texture failed, maybe too big, abort
}
float r = _color.r * _intensity;
float g = _color.g * _intensity;
float b = _color.b * _intensity;
sf::Color c(r,g,b,255);
_renderTexture->clear();
//shader parameters
shader->setParameter(DMGDVT::LS::Light::LAS_PARAM_CENTER,sf::Vector2f(_radius,_radius));
shader->setParameter(DMGDVT::LS::Light::LAS_PARAM_RADIUS,_radius);
shader->setParameter(DMGDVT::LS::Light::LAS_PARAM_COLOR,c);
shader->setParameter(DMGDVT::LS::Light::LAS_PARAM_BLEED,_bleed);
shader->setParameter(DMGDVT::LS::Light::LAS_PARAM_LINEARITY,_linearity);
shader->setParameter(DMGDVT::LS::Light::LAS_PARAM_OUTLINE,false); //for debug
shader->setParameter(DMGDVT::LS::Light::LAS_PARAM_ISOMETRIC,_isometric);
if(_spreadAngle==M_PIf*2.0f) {
_sprite.setTexture(_renderTexture->getTexture());
_sprite.setOrigin(sf::Vector2f(_radius,_radius));
_sprite.setPosition(_position);
sf::RectangleShape rect(sf::Vector2f(diam,diam));
_renderTexture->draw(rect,shader);
} else {
_sprite.setTexture(_renderTexture->getTexture());
_sprite.setPosition(_position);
_sprite.setOrigin(sf::Vector2f(_radius,_radius));
sf::ConvexShape shape;
float deltaAngle = _spreadAngle / (float)(_precision-1);
shape.setPointCount(_precision+1);
shape.setPoint(0,sf::Vector2f(_radius,_radius));
for(int i=0;i<_precision;++i) {
float angle = - _spreadAngle/2.0f + (float)i*deltaAngle;
shape.setPoint(i+1,DMUtils::sfml::rotate(shape.getPoint(0)+sf::Vector2f(0.0f,_radius),angle,shape.getPoint(0)));
}
_renderTexture->draw(shape,shader);
_sprite.setRotation(DMUtils::maths::radToDeg(_directionAngle));
}
_renderTexture->display();
}
void SpotLight::render(const sf::IntRect& screen, sf::RenderTarget& target, sf::Shader* shader, const sf::RenderStates &states) {
if(_intensity <= 0.0f) return;
if(_renderTexture!=nullptr) {
//draw the sprite
target.draw(_sprite,states);
} else {
//need to find a way to put thiis as common code between render and preRender
float r = _color.r * _intensity;
float g = _color.g * _intensity;
float b = _color.b * _intensity;
sf::Color c(r,g,b,255);
const float diam = _radius*2.0f;
sf::Vector2f radVec(_radius,_radius);
sf::Vector2f newCenter = _position - sf::Vector2f(screen.left,screen.top);
// for some reason in this case it considers the center to be from the bottom of the screen
shader->setParameter(DMGDVT::LS::Light::LAS_PARAM_CENTER,sf::Vector2f(newCenter.x,screen.height - newCenter.y));
shader->setParameter(DMGDVT::LS::Light::LAS_PARAM_RADIUS,_radius);
shader->setParameter(DMGDVT::LS::Light::LAS_PARAM_COLOR,c);
shader->setParameter(DMGDVT::LS::Light::LAS_PARAM_BLEED,_bleed);
shader->setParameter(DMGDVT::LS::Light::LAS_PARAM_LINEARITY,_linearity);
shader->setParameter(DMGDVT::LS::Light::LAS_PARAM_OUTLINE,false); //for debug
shader->setParameter(DMGDVT::LS::Light::LAS_PARAM_ISOMETRIC,_isometric);
sf::RenderStates st(states);
st.shader = shader;
if(_spreadAngle==M_PIf*2.0f) {
sf::RectangleShape rect(sf::Vector2f(diam,diam));
rect.setOrigin(radVec);
rect.setPosition(_position);
target.draw(rect,st);
} else {
sf::ConvexShape shape;
shape.setPosition(_position);
shape.setOrigin(radVec);
float deltaAngle = _spreadAngle / (float)(_precision-1);
shape.setPointCount(_precision+1);
shape.setPoint(0,sf::Vector2f(_radius,_radius));
for(int i=0;i<_precision;++i) {
float angle = - _spreadAngle/2.0f + (float)i*deltaAngle;
shape.setPoint(i+1,DMUtils::sfml::rotate(shape.getPoint(0)+sf::Vector2f(0.0f,_radius),angle,shape.getPoint(0)));
}
shape.setRotation(DMUtils::maths::radToDeg(_directionAngle));
target.draw(shape,st);
}
}
}
void SpotLight::debugRender(sf::RenderTarget& target, const sf::RenderStates &states) {
if(_intensity <= 0.0f) return;
if(_spreadAngle == M_PIf*2.0f) {
sf::CircleShape shape(_radius);
shape.setPosition(_position);
shape.setOrigin(sf::Vector2f(1,1)*_radius);
shape.setFillColor(_color);
target.draw(shape,states);
} else {
sf::ConvexShape shape;
shape.setPointCount(4);
shape.setFillColor(sf::Color(_color.r,_color.g,_color.b,125));
sf::Vector2f v(0,_radius);
//*
shape.setPosition(_position);shape.setPointCount(_precision+1);
shape.setPoint(0,sf::Vector2f(0,0));
float deltaAngle = _spreadAngle / (float)(_precision-1);
for(int i=0;i<_precision;++i) {
float angle = - _spreadAngle/2.0f + (float)i*deltaAngle;
shape.setPoint(i+1,DMUtils::sfml::rotate(shape.getPoint(0)+sf::Vector2f(0.0f,_radius),angle,shape.getPoint(0)));
}
shape.setRotation(DMUtils::maths::radToDeg(_directionAngle));
target.draw(shape,states);
}
}
void SpotLight::drawAABB(const sf::IntRect& screen, sf::RenderTarget& target) {
sf::IntRect box = getAABB();
sf::Vertex lines[] = {
sf::Vertex(sf::Vector2f(box.left, box.top),_color),
sf::Vertex(sf::Vector2f(box.left+box.width, box.top),_color),
sf::Vertex(sf::Vector2f(box.left+box.width, box.top+box.height),_color),
sf::Vertex(sf::Vector2f(box.left, box.top+box.height),_color),
lines[0]
};
target.draw(lines,5,sf::LinesStrip);
}
void SpotLight::computeAABB() {
if(_spreadAngle == M_PIf*2.0f) {
_aabb.left = -_radius;
_aabb.top = -_radius;
_aabb.width = _aabb.height = _radius*2.0f;
} else {
// @TODO : move the rotation function to a real good DMGDVT::sfUtils folder
sf::Vector2f v = DMUtils::sfml::rotate<float>(sf::Vector2f(0.0,_radius),_directionAngle);
sf::Vector2f left = DMUtils::sfml::rotate<float>(v,-_spreadAngle/2.0f,_directionAngle);
sf::Vector2f right = DMUtils::sfml::rotate<float>(v,_spreadAngle/2.0f,_directionAngle);
int xmin = DMUtils::maths::min<float>(v.x, left.x, right.x, 0.0f);
int xmax = DMUtils::maths::max<float>(v.x, left.x, right.x, 0.0f);
int ymin = DMUtils::maths::min<float>(v.y, left.y, right.y, 0.0f);
int ymax = DMUtils::maths::max<float>(v.y, left.y, right.y, 0.0f);
_aabb.left = xmin;
_aabb.top = ymin;
_aabb.width = xmax - xmin;
_aabb.height = ymax - ymin;
}
}
/*** GETTER - SETTER ***/
sf::IntRect SpotLight::getAABB() {
return sf::IntRect(sf::Vector2i(_aabb.left+static_cast<int>(_position.x),_aabb.top+static_cast<int>(_position.y)),sf::Vector2i(_aabb.width,_aabb.height));
}
void SpotLight::setPosition(sf::Vector2f c) {
_position = c;
_sprite.setPosition(c);
}
sf::Vector2f SpotLight::getPosition() const {
return _position;
}
void SpotLight::setRadius(float r) {
_radius = r;
}
float SpotLight::getRadius() const {
return _radius;
}
void SpotLight::setColor(sf::Color c) {
_color = c;
}
sf::Color SpotLight::getColor() const {
return _color;
}
void SpotLight::setDirectionAngle(float da) {
_directionAngle = da;
_sprite.setRotation(DMUtils::maths::radToDeg(_directionAngle));
}
float SpotLight::getDirectionAngle() const {
return _directionAngle;
}
void SpotLight::rotate(float delta) {
float a = _directionAngle + delta;
while(a > 2.0*M_PIf) a -= 2.0*M_PIf;
while(a < 0) a += 2.0*M_PIf;
setDirectionAngle(a);
}
void SpotLight::setSpreadAngle(float sa) {
if(sa<0) sa = -sa;
while(sa > 2.0f*M_PIf) sa = 2.0f*M_PIf;
_spreadAngle = sa;
}
float SpotLight::getSpreadAngle() const {
return _spreadAngle;
}
void SpotLight::setIntensity(float i) {
DMUtils::maths::clamp(i,0.0f,1.0f);
_intensity = i;
}
float SpotLight::getIntensity() const {
return _intensity;
}
void SpotLight::setBleed(float b) {
_bleed = b;
}
float SpotLight::getBleed() const {
return _bleed;
}
void SpotLight::setLinearity(float lf) {
_linearity = lf;
}
float SpotLight::getLinearity() const {
return _linearity;
}
void SpotLight::setPrecision(int p) {
_precision = p;
}
int SpotLight::getPrecision() const {
return _precision;
}
/*** PROTECTED ***/
}
}
<|endoftext|> |
<commit_before><commit_msg>FEM: sort equation commands<commit_after><|endoftext|> |
<commit_before>/*
The MIT License (MIT)
Copyright (c) 2013 Rajendra Kumar Uppal
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 <iostream>
#include "Semaphore.h"
#include "Thread.h"
using std::cout;
using std::cin;
using std::endl;
#define print(s) cout<<endl<<(s)<<endl
void Test_Semaphore()
{
Semaphore::get();
}
int main()
{
Test_Semaphore();
print("Press eny key to continue...");
cin.get();
return 0;
}
// ~EOF
<commit_msg>Created and tested Semaphore object<commit_after>/*
The MIT License (MIT)
Copyright (c) 2013 Rajendra Kumar Uppal
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 <iostream>
#include "Semaphore.h"
#include "Thread.h"
using std::cout;
using std::cin;
using std::endl;
#define print(s) cout<<endl<<(s)<<endl
void Test_Semaphore()
{
Semaphore sem(5, 10000);
}
int main()
{
Test_Semaphore();
print("Press eny key to continue...");
cin.get();
return 0;
}
// ~EOF
<|endoftext|> |
<commit_before>//===- IndexBody.cpp - Indexing statements --------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "IndexingContext.h"
#include "clang/AST/RecursiveASTVisitor.h"
using namespace clang;
using namespace clang::index;
namespace {
class BodyIndexer : public RecursiveASTVisitor<BodyIndexer> {
IndexingContext &IndexCtx;
const NamedDecl *Parent;
const DeclContext *ParentDC;
SmallVector<Stmt*, 16> StmtStack;
typedef RecursiveASTVisitor<BodyIndexer> base;
public:
BodyIndexer(IndexingContext &indexCtx,
const NamedDecl *Parent, const DeclContext *DC)
: IndexCtx(indexCtx), Parent(Parent), ParentDC(DC) { }
bool shouldWalkTypesOfTypeLocs() const { return false; }
bool dataTraverseStmtPre(Stmt *S) {
StmtStack.push_back(S);
return true;
}
bool dataTraverseStmtPost(Stmt *S) {
assert(StmtStack.back() == S);
StmtStack.pop_back();
return true;
}
bool TraverseTypeLoc(TypeLoc TL) {
IndexCtx.indexTypeLoc(TL, Parent, ParentDC);
return true;
}
bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
IndexCtx.indexNestedNameSpecifierLoc(NNS, Parent, ParentDC);
return true;
}
SymbolRoleSet getRolesForRef(const Expr *E,
SmallVectorImpl<SymbolRelation> &Relations) {
SymbolRoleSet Roles{};
assert(!StmtStack.empty() && E == StmtStack.back());
if (StmtStack.size() == 1)
return Roles;
auto It = StmtStack.end()-2;
while (isa<CastExpr>(*It) || isa<ParenExpr>(*It)) {
if (auto ICE = dyn_cast<ImplicitCastExpr>(*It)) {
if (ICE->getCastKind() == CK_LValueToRValue)
Roles |= (unsigned)(unsigned)SymbolRole::Read;
}
if (It == StmtStack.begin())
break;
--It;
}
const Stmt *Parent = *It;
if (auto BO = dyn_cast<BinaryOperator>(Parent)) {
if (BO->getOpcode() == BO_Assign && BO->getLHS()->IgnoreParenCasts() == E)
Roles |= (unsigned)SymbolRole::Write;
} else if (auto UO = dyn_cast<UnaryOperator>(Parent)) {
if (UO->isIncrementDecrementOp()) {
Roles |= (unsigned)SymbolRole::Read;
Roles |= (unsigned)SymbolRole::Write;
} else if (UO->getOpcode() == UO_AddrOf) {
Roles |= (unsigned)SymbolRole::AddressOf;
}
} else if (auto CA = dyn_cast<CompoundAssignOperator>(Parent)) {
if (CA->getLHS()->IgnoreParenCasts() == E) {
Roles |= (unsigned)SymbolRole::Read;
Roles |= (unsigned)SymbolRole::Write;
}
} else if (auto CE = dyn_cast<CallExpr>(Parent)) {
if (CE->getCallee()->IgnoreParenCasts() == E) {
addCallRole(Roles, Relations);
if (auto *ME = dyn_cast<MemberExpr>(E)) {
if (auto *CXXMD = dyn_cast_or_null<CXXMethodDecl>(ME->getMemberDecl()))
if (CXXMD->isVirtual() && !ME->hasQualifier()) {
Roles |= (unsigned)SymbolRole::Dynamic;
auto BaseTy = ME->getBase()->IgnoreImpCasts()->getType();
if (!BaseTy.isNull())
if (auto *CXXRD = BaseTy->getPointeeCXXRecordDecl())
Relations.emplace_back((unsigned)SymbolRole::RelationReceivedBy,
CXXRD);
}
}
} else if (auto CXXOp = dyn_cast<CXXOperatorCallExpr>(CE)) {
if (CXXOp->getNumArgs() > 0 && CXXOp->getArg(0)->IgnoreParenCasts() == E) {
OverloadedOperatorKind Op = CXXOp->getOperator();
if (Op == OO_Equal) {
Roles |= (unsigned)SymbolRole::Write;
} else if ((Op >= OO_PlusEqual && Op <= OO_PipeEqual) ||
Op == OO_LessLessEqual || Op == OO_GreaterGreaterEqual ||
Op == OO_PlusPlus || Op == OO_MinusMinus) {
Roles |= (unsigned)SymbolRole::Read;
Roles |= (unsigned)SymbolRole::Write;
} else if (Op == OO_Amp) {
Roles |= (unsigned)SymbolRole::AddressOf;
}
}
}
}
return Roles;
}
void addCallRole(SymbolRoleSet &Roles,
SmallVectorImpl<SymbolRelation> &Relations) {
Roles |= (unsigned)SymbolRole::Call;
if (auto *FD = dyn_cast<FunctionDecl>(ParentDC))
Relations.emplace_back((unsigned)SymbolRole::RelationCalledBy, FD);
else if (auto *MD = dyn_cast<ObjCMethodDecl>(ParentDC))
Relations.emplace_back((unsigned)SymbolRole::RelationCalledBy, MD);
}
bool VisitDeclRefExpr(DeclRefExpr *E) {
SmallVector<SymbolRelation, 4> Relations;
SymbolRoleSet Roles = getRolesForRef(E, Relations);
return IndexCtx.handleReference(E->getDecl(), E->getLocation(),
Parent, ParentDC, Roles, Relations, E);
}
bool VisitMemberExpr(MemberExpr *E) {
SourceLocation Loc = E->getMemberLoc();
if (Loc.isInvalid())
Loc = E->getLocStart();
SmallVector<SymbolRelation, 4> Relations;
SymbolRoleSet Roles = getRolesForRef(E, Relations);
return IndexCtx.handleReference(E->getMemberDecl(), Loc,
Parent, ParentDC, Roles, Relations, E);
}
bool VisitDesignatedInitExpr(DesignatedInitExpr *E) {
for (DesignatedInitExpr::reverse_designators_iterator
D = E->designators_rbegin(), DEnd = E->designators_rend();
D != DEnd; ++D) {
if (D->isFieldDesignator())
return IndexCtx.handleReference(D->getField(), D->getFieldLoc(),
Parent, ParentDC, SymbolRoleSet(),
{}, E);
}
return true;
}
bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
SmallVector<SymbolRelation, 4> Relations;
SymbolRoleSet Roles = getRolesForRef(E, Relations);
return IndexCtx.handleReference(E->getDecl(), E->getLocation(),
Parent, ParentDC, Roles, Relations, E);
}
bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
auto isDynamic = [](const ObjCMessageExpr *MsgE)->bool {
if (MsgE->getReceiverKind() != ObjCMessageExpr::Instance)
return false;
if (auto *RecE = dyn_cast<ObjCMessageExpr>(
MsgE->getInstanceReceiver()->IgnoreParenCasts())) {
if (RecE->getMethodFamily() == OMF_alloc)
return false;
}
return true;
};
if (ObjCMethodDecl *MD = E->getMethodDecl()) {
SymbolRoleSet Roles{};
SmallVector<SymbolRelation, 2> Relations;
addCallRole(Roles, Relations);
if (E->isImplicit())
Roles |= (unsigned)SymbolRole::Implicit;
if (isDynamic(E)) {
Roles |= (unsigned)SymbolRole::Dynamic;
if (auto *RecD = E->getReceiverInterface())
Relations.emplace_back((unsigned)SymbolRole::RelationReceivedBy, RecD);
}
return IndexCtx.handleReference(MD, E->getSelectorStartLoc(),
Parent, ParentDC, Roles, Relations, E);
}
return true;
}
bool VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
if (E->isExplicitProperty())
return IndexCtx.handleReference(E->getExplicitProperty(), E->getLocation(),
Parent, ParentDC, SymbolRoleSet(), {}, E);
// No need to do a handleReference for the objc method, because there will
// be a message expr as part of PseudoObjectExpr.
return true;
}
bool VisitMSPropertyRefExpr(MSPropertyRefExpr *E) {
return IndexCtx.handleReference(E->getPropertyDecl(), E->getMemberLoc(),
Parent, ParentDC, SymbolRoleSet(), {}, E);
}
bool VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
return IndexCtx.handleReference(E->getProtocol(), E->getProtocolIdLoc(),
Parent, ParentDC, SymbolRoleSet(), {}, E);
}
bool passObjCLiteralMethodCall(const ObjCMethodDecl *MD, const Expr *E) {
SymbolRoleSet Roles{};
SmallVector<SymbolRelation, 2> Relations;
addCallRole(Roles, Relations);
Roles |= (unsigned)SymbolRole::Implicit;
return IndexCtx.handleReference(MD, E->getLocStart(),
Parent, ParentDC, Roles, Relations, E);
}
bool VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
if (ObjCMethodDecl *MD = E->getBoxingMethod()) {
return passObjCLiteralMethodCall(MD, E);
}
return true;
}
bool VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
if (ObjCMethodDecl *MD = E->getDictWithObjectsMethod()) {
return passObjCLiteralMethodCall(MD, E);
}
return true;
}
bool VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
if (ObjCMethodDecl *MD = E->getArrayWithObjectsMethod()) {
return passObjCLiteralMethodCall(MD, E);
}
return true;
}
bool VisitCXXConstructExpr(CXXConstructExpr *E) {
SymbolRoleSet Roles{};
SmallVector<SymbolRelation, 2> Relations;
addCallRole(Roles, Relations);
return IndexCtx.handleReference(E->getConstructor(), E->getLocation(),
Parent, ParentDC, Roles, Relations, E);
}
bool TraverseCXXOperatorCallExpr(CXXOperatorCallExpr *E,
DataRecursionQueue *Q = nullptr) {
if (E->getOperatorLoc().isInvalid())
return true; // implicit.
return base::TraverseCXXOperatorCallExpr(E);
}
bool VisitDeclStmt(DeclStmt *S) {
if (IndexCtx.shouldIndexFunctionLocalSymbols()) {
IndexCtx.indexDeclGroupRef(S->getDeclGroup());
return true;
}
DeclGroupRef DG = S->getDeclGroup();
for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) {
const Decl *D = *I;
if (!D)
continue;
if (!IndexCtx.isFunctionLocalDecl(D))
IndexCtx.indexTopLevelDecl(D);
}
return true;
}
bool TraverseLambdaCapture(LambdaExpr *LE, const LambdaCapture *C) {
if (C->capturesThis() || C->capturesVLAType())
return true;
if (C->capturesVariable() && IndexCtx.shouldIndexFunctionLocalSymbols())
return IndexCtx.handleReference(C->getCapturedVar(), C->getLocation(),
Parent, ParentDC, SymbolRoleSet());
// FIXME: Lambda init-captures.
return true;
}
// RecursiveASTVisitor visits both syntactic and semantic forms, duplicating
// the things that we visit. Make sure to only visit the semantic form.
// Also visit things that are in the syntactic form but not the semantic one,
// for example the indices in DesignatedInitExprs.
bool TraverseInitListExpr(InitListExpr *S, DataRecursionQueue *Q = nullptr) {
class SyntacticFormIndexer :
public RecursiveASTVisitor<SyntacticFormIndexer> {
IndexingContext &IndexCtx;
const NamedDecl *Parent;
const DeclContext *ParentDC;
public:
SyntacticFormIndexer(IndexingContext &indexCtx,
const NamedDecl *Parent, const DeclContext *DC)
: IndexCtx(indexCtx), Parent(Parent), ParentDC(DC) { }
bool shouldWalkTypesOfTypeLocs() const { return false; }
bool VisitDesignatedInitExpr(DesignatedInitExpr *E) {
for (DesignatedInitExpr::reverse_designators_iterator
D = E->designators_rbegin(), DEnd = E->designators_rend();
D != DEnd; ++D) {
if (D->isFieldDesignator())
return IndexCtx.handleReference(D->getField(), D->getFieldLoc(),
Parent, ParentDC, SymbolRoleSet(),
{}, E);
}
return true;
}
};
auto visitForm = [&](InitListExpr *Form) {
for (Stmt *SubStmt : Form->children()) {
if (!TraverseStmt(SubStmt))
return false;
}
return true;
};
InitListExpr *SemaForm = S->isSemanticForm() ? S : S->getSemanticForm();
InitListExpr *SyntaxForm = S->isSemanticForm() ? S->getSyntacticForm() : S;
if (SemaForm) {
// Visit things present in syntactic form but not the semantic form.
if (SyntaxForm) {
SyntacticFormIndexer(IndexCtx, Parent, ParentDC).TraverseStmt(SyntaxForm);
}
return visitForm(SemaForm);
}
// No semantic, try the syntactic.
if (SyntaxForm) {
return visitForm(SyntaxForm);
}
return true;
}
};
} // anonymous namespace
void IndexingContext::indexBody(const Stmt *S, const NamedDecl *Parent,
const DeclContext *DC) {
if (!S)
return;
if (!DC)
DC = Parent->getLexicalDeclContext();
BodyIndexer(*this, Parent, DC).TraverseStmt(const_cast<Stmt*>(S));
}
<commit_msg>[index] Fix issue where data visitation was disabled with C++ operator call expressions, during indexing.<commit_after>//===- IndexBody.cpp - Indexing statements --------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "IndexingContext.h"
#include "clang/AST/RecursiveASTVisitor.h"
using namespace clang;
using namespace clang::index;
namespace {
class BodyIndexer : public RecursiveASTVisitor<BodyIndexer> {
IndexingContext &IndexCtx;
const NamedDecl *Parent;
const DeclContext *ParentDC;
SmallVector<Stmt*, 16> StmtStack;
typedef RecursiveASTVisitor<BodyIndexer> base;
public:
BodyIndexer(IndexingContext &indexCtx,
const NamedDecl *Parent, const DeclContext *DC)
: IndexCtx(indexCtx), Parent(Parent), ParentDC(DC) { }
bool shouldWalkTypesOfTypeLocs() const { return false; }
bool dataTraverseStmtPre(Stmt *S) {
StmtStack.push_back(S);
return true;
}
bool dataTraverseStmtPost(Stmt *S) {
assert(StmtStack.back() == S);
StmtStack.pop_back();
return true;
}
bool TraverseTypeLoc(TypeLoc TL) {
IndexCtx.indexTypeLoc(TL, Parent, ParentDC);
return true;
}
bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
IndexCtx.indexNestedNameSpecifierLoc(NNS, Parent, ParentDC);
return true;
}
SymbolRoleSet getRolesForRef(const Expr *E,
SmallVectorImpl<SymbolRelation> &Relations) {
SymbolRoleSet Roles{};
assert(!StmtStack.empty() && E == StmtStack.back());
if (StmtStack.size() == 1)
return Roles;
auto It = StmtStack.end()-2;
while (isa<CastExpr>(*It) || isa<ParenExpr>(*It)) {
if (auto ICE = dyn_cast<ImplicitCastExpr>(*It)) {
if (ICE->getCastKind() == CK_LValueToRValue)
Roles |= (unsigned)(unsigned)SymbolRole::Read;
}
if (It == StmtStack.begin())
break;
--It;
}
const Stmt *Parent = *It;
if (auto BO = dyn_cast<BinaryOperator>(Parent)) {
if (BO->getOpcode() == BO_Assign && BO->getLHS()->IgnoreParenCasts() == E)
Roles |= (unsigned)SymbolRole::Write;
} else if (auto UO = dyn_cast<UnaryOperator>(Parent)) {
if (UO->isIncrementDecrementOp()) {
Roles |= (unsigned)SymbolRole::Read;
Roles |= (unsigned)SymbolRole::Write;
} else if (UO->getOpcode() == UO_AddrOf) {
Roles |= (unsigned)SymbolRole::AddressOf;
}
} else if (auto CA = dyn_cast<CompoundAssignOperator>(Parent)) {
if (CA->getLHS()->IgnoreParenCasts() == E) {
Roles |= (unsigned)SymbolRole::Read;
Roles |= (unsigned)SymbolRole::Write;
}
} else if (auto CE = dyn_cast<CallExpr>(Parent)) {
if (CE->getCallee()->IgnoreParenCasts() == E) {
addCallRole(Roles, Relations);
if (auto *ME = dyn_cast<MemberExpr>(E)) {
if (auto *CXXMD = dyn_cast_or_null<CXXMethodDecl>(ME->getMemberDecl()))
if (CXXMD->isVirtual() && !ME->hasQualifier()) {
Roles |= (unsigned)SymbolRole::Dynamic;
auto BaseTy = ME->getBase()->IgnoreImpCasts()->getType();
if (!BaseTy.isNull())
if (auto *CXXRD = BaseTy->getPointeeCXXRecordDecl())
Relations.emplace_back((unsigned)SymbolRole::RelationReceivedBy,
CXXRD);
}
}
} else if (auto CXXOp = dyn_cast<CXXOperatorCallExpr>(CE)) {
if (CXXOp->getNumArgs() > 0 && CXXOp->getArg(0)->IgnoreParenCasts() == E) {
OverloadedOperatorKind Op = CXXOp->getOperator();
if (Op == OO_Equal) {
Roles |= (unsigned)SymbolRole::Write;
} else if ((Op >= OO_PlusEqual && Op <= OO_PipeEqual) ||
Op == OO_LessLessEqual || Op == OO_GreaterGreaterEqual ||
Op == OO_PlusPlus || Op == OO_MinusMinus) {
Roles |= (unsigned)SymbolRole::Read;
Roles |= (unsigned)SymbolRole::Write;
} else if (Op == OO_Amp) {
Roles |= (unsigned)SymbolRole::AddressOf;
}
}
}
}
return Roles;
}
void addCallRole(SymbolRoleSet &Roles,
SmallVectorImpl<SymbolRelation> &Relations) {
Roles |= (unsigned)SymbolRole::Call;
if (auto *FD = dyn_cast<FunctionDecl>(ParentDC))
Relations.emplace_back((unsigned)SymbolRole::RelationCalledBy, FD);
else if (auto *MD = dyn_cast<ObjCMethodDecl>(ParentDC))
Relations.emplace_back((unsigned)SymbolRole::RelationCalledBy, MD);
}
bool VisitDeclRefExpr(DeclRefExpr *E) {
SmallVector<SymbolRelation, 4> Relations;
SymbolRoleSet Roles = getRolesForRef(E, Relations);
return IndexCtx.handleReference(E->getDecl(), E->getLocation(),
Parent, ParentDC, Roles, Relations, E);
}
bool VisitMemberExpr(MemberExpr *E) {
SourceLocation Loc = E->getMemberLoc();
if (Loc.isInvalid())
Loc = E->getLocStart();
SmallVector<SymbolRelation, 4> Relations;
SymbolRoleSet Roles = getRolesForRef(E, Relations);
return IndexCtx.handleReference(E->getMemberDecl(), Loc,
Parent, ParentDC, Roles, Relations, E);
}
bool VisitDesignatedInitExpr(DesignatedInitExpr *E) {
for (DesignatedInitExpr::reverse_designators_iterator
D = E->designators_rbegin(), DEnd = E->designators_rend();
D != DEnd; ++D) {
if (D->isFieldDesignator())
return IndexCtx.handleReference(D->getField(), D->getFieldLoc(),
Parent, ParentDC, SymbolRoleSet(),
{}, E);
}
return true;
}
bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
SmallVector<SymbolRelation, 4> Relations;
SymbolRoleSet Roles = getRolesForRef(E, Relations);
return IndexCtx.handleReference(E->getDecl(), E->getLocation(),
Parent, ParentDC, Roles, Relations, E);
}
bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
auto isDynamic = [](const ObjCMessageExpr *MsgE)->bool {
if (MsgE->getReceiverKind() != ObjCMessageExpr::Instance)
return false;
if (auto *RecE = dyn_cast<ObjCMessageExpr>(
MsgE->getInstanceReceiver()->IgnoreParenCasts())) {
if (RecE->getMethodFamily() == OMF_alloc)
return false;
}
return true;
};
if (ObjCMethodDecl *MD = E->getMethodDecl()) {
SymbolRoleSet Roles{};
SmallVector<SymbolRelation, 2> Relations;
addCallRole(Roles, Relations);
if (E->isImplicit())
Roles |= (unsigned)SymbolRole::Implicit;
if (isDynamic(E)) {
Roles |= (unsigned)SymbolRole::Dynamic;
if (auto *RecD = E->getReceiverInterface())
Relations.emplace_back((unsigned)SymbolRole::RelationReceivedBy, RecD);
}
return IndexCtx.handleReference(MD, E->getSelectorStartLoc(),
Parent, ParentDC, Roles, Relations, E);
}
return true;
}
bool VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
if (E->isExplicitProperty())
return IndexCtx.handleReference(E->getExplicitProperty(), E->getLocation(),
Parent, ParentDC, SymbolRoleSet(), {}, E);
// No need to do a handleReference for the objc method, because there will
// be a message expr as part of PseudoObjectExpr.
return true;
}
bool VisitMSPropertyRefExpr(MSPropertyRefExpr *E) {
return IndexCtx.handleReference(E->getPropertyDecl(), E->getMemberLoc(),
Parent, ParentDC, SymbolRoleSet(), {}, E);
}
bool VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
return IndexCtx.handleReference(E->getProtocol(), E->getProtocolIdLoc(),
Parent, ParentDC, SymbolRoleSet(), {}, E);
}
bool passObjCLiteralMethodCall(const ObjCMethodDecl *MD, const Expr *E) {
SymbolRoleSet Roles{};
SmallVector<SymbolRelation, 2> Relations;
addCallRole(Roles, Relations);
Roles |= (unsigned)SymbolRole::Implicit;
return IndexCtx.handleReference(MD, E->getLocStart(),
Parent, ParentDC, Roles, Relations, E);
}
bool VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
if (ObjCMethodDecl *MD = E->getBoxingMethod()) {
return passObjCLiteralMethodCall(MD, E);
}
return true;
}
bool VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
if (ObjCMethodDecl *MD = E->getDictWithObjectsMethod()) {
return passObjCLiteralMethodCall(MD, E);
}
return true;
}
bool VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
if (ObjCMethodDecl *MD = E->getArrayWithObjectsMethod()) {
return passObjCLiteralMethodCall(MD, E);
}
return true;
}
bool VisitCXXConstructExpr(CXXConstructExpr *E) {
SymbolRoleSet Roles{};
SmallVector<SymbolRelation, 2> Relations;
addCallRole(Roles, Relations);
return IndexCtx.handleReference(E->getConstructor(), E->getLocation(),
Parent, ParentDC, Roles, Relations, E);
}
bool TraverseCXXOperatorCallExpr(CXXOperatorCallExpr *E,
DataRecursionQueue *Q = nullptr) {
if (E->getOperatorLoc().isInvalid())
return true; // implicit.
return base::TraverseCXXOperatorCallExpr(E, Q);
}
bool VisitDeclStmt(DeclStmt *S) {
if (IndexCtx.shouldIndexFunctionLocalSymbols()) {
IndexCtx.indexDeclGroupRef(S->getDeclGroup());
return true;
}
DeclGroupRef DG = S->getDeclGroup();
for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) {
const Decl *D = *I;
if (!D)
continue;
if (!IndexCtx.isFunctionLocalDecl(D))
IndexCtx.indexTopLevelDecl(D);
}
return true;
}
bool TraverseLambdaCapture(LambdaExpr *LE, const LambdaCapture *C) {
if (C->capturesThis() || C->capturesVLAType())
return true;
if (C->capturesVariable() && IndexCtx.shouldIndexFunctionLocalSymbols())
return IndexCtx.handleReference(C->getCapturedVar(), C->getLocation(),
Parent, ParentDC, SymbolRoleSet());
// FIXME: Lambda init-captures.
return true;
}
// RecursiveASTVisitor visits both syntactic and semantic forms, duplicating
// the things that we visit. Make sure to only visit the semantic form.
// Also visit things that are in the syntactic form but not the semantic one,
// for example the indices in DesignatedInitExprs.
bool TraverseInitListExpr(InitListExpr *S, DataRecursionQueue *Q = nullptr) {
class SyntacticFormIndexer :
public RecursiveASTVisitor<SyntacticFormIndexer> {
IndexingContext &IndexCtx;
const NamedDecl *Parent;
const DeclContext *ParentDC;
public:
SyntacticFormIndexer(IndexingContext &indexCtx,
const NamedDecl *Parent, const DeclContext *DC)
: IndexCtx(indexCtx), Parent(Parent), ParentDC(DC) { }
bool shouldWalkTypesOfTypeLocs() const { return false; }
bool VisitDesignatedInitExpr(DesignatedInitExpr *E) {
for (DesignatedInitExpr::reverse_designators_iterator
D = E->designators_rbegin(), DEnd = E->designators_rend();
D != DEnd; ++D) {
if (D->isFieldDesignator())
return IndexCtx.handleReference(D->getField(), D->getFieldLoc(),
Parent, ParentDC, SymbolRoleSet(),
{}, E);
}
return true;
}
};
auto visitForm = [&](InitListExpr *Form) {
for (Stmt *SubStmt : Form->children()) {
if (!TraverseStmt(SubStmt, Q))
return false;
}
return true;
};
InitListExpr *SemaForm = S->isSemanticForm() ? S : S->getSemanticForm();
InitListExpr *SyntaxForm = S->isSemanticForm() ? S->getSyntacticForm() : S;
if (SemaForm) {
// Visit things present in syntactic form but not the semantic form.
if (SyntaxForm) {
SyntacticFormIndexer(IndexCtx, Parent, ParentDC).TraverseStmt(SyntaxForm);
}
return visitForm(SemaForm);
}
// No semantic, try the syntactic.
if (SyntaxForm) {
return visitForm(SyntaxForm);
}
return true;
}
};
} // anonymous namespace
void IndexingContext::indexBody(const Stmt *S, const NamedDecl *Parent,
const DeclContext *DC) {
if (!S)
return;
if (!DC)
DC = Parent->getLexicalDeclContext();
BodyIndexer(*this, Parent, DC).TraverseStmt(const_cast<Stmt*>(S));
}
<|endoftext|> |
<commit_before>// Copyright (C) 2007-2013 CEA/DEN, EDF R&D, OPEN CASCADE
//
// Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
//
// 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.
//
// 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
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
// SMESH SMDS : implementaion of Salome mesh data structure
// File : SMDS_MeshElement.hxx
// Module : SMESH
//
#ifndef _SMDS_MeshElement_HeaderFile
#define _SMDS_MeshElement_HeaderFile
#include "SMESH_SMDS.hxx"
#include "SMDSAbs_ElementType.hxx"
#include "SMDS_MeshObject.hxx"
#include "SMDS_ElemIterator.hxx"
#include "SMDS_MeshElementIDFactory.hxx"
#include "SMDS_StdIterator.hxx"
#include <vector>
#include <iostream>
#include <vtkType.h>
#include <vtkCellType.h>
//typedef unsigned short UShortType;
typedef short ShortType;
typedef int LongType;
class SMDS_MeshNode;
class SMDS_MeshEdge;
class SMDS_MeshFace;
class SMDS_Mesh;
// ============================================================
/*!
* \brief Base class for elements
*/
// ============================================================
class SMDS_EXPORT SMDS_MeshElement:public SMDS_MeshObject
{
public:
SMDS_ElemIteratorPtr nodesIterator() const;
SMDS_ElemIteratorPtr edgesIterator() const;
SMDS_ElemIteratorPtr facesIterator() const;
virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType type) const;
virtual SMDS_ElemIteratorPtr interlacedNodesElemIterator() const;
virtual SMDS_NodeIteratorPtr nodeIterator() const;
virtual SMDS_NodeIteratorPtr interlacedNodesIterator() const;
virtual SMDS_NodeIteratorPtr nodesIteratorToUNV() const;
// std-like iteration on nodes
typedef SMDS_StdIterator< const SMDS_MeshNode*, SMDS_ElemIteratorPtr > iterator;
iterator begin_nodes() const { return iterator( nodesIterator() ); }
iterator end_nodes() const { return iterator(); }
virtual int NbNodes() const;
virtual int NbEdges() const;
virtual int NbFaces() const;
inline int GetID() const { return myID; };
///Return the type of the current element
virtual SMDSAbs_ElementType GetType() const = 0;
virtual SMDSAbs_EntityType GetEntityType() const = 0;
virtual SMDSAbs_GeometryType GetGeomType() const = 0;
virtual vtkIdType GetVtkType() const = 0;
virtual bool IsPoly() const { return false; }
virtual bool IsQuadratic() const;
virtual bool IsMediumNode(const SMDS_MeshNode* node) const;
virtual int NbCornerNodes() const;
friend SMDS_EXPORT std::ostream & operator <<(std::ostream & OS, const SMDS_MeshElement *);
friend SMDS_EXPORT bool SMDS_MeshElementIDFactory::BindID(int ID,SMDS_MeshElement* elem);
friend class SMDS_Mesh;
friend class SMESHDS_Mesh;
friend class SMESHDS_SubMesh;
friend class SMDS_MeshElementIDFactory;
// ===========================
// Access to nodes by index
// ===========================
/*!
* \brief Return node by its index
* \param ind - node index
* \retval const SMDS_MeshNode* - the node
*/
virtual const SMDS_MeshNode* GetNode(const int ind) const;
/*!
* \brief Return node by its index
* \param ind - node index
* \retval const SMDS_MeshNode* - the node
*
* Index is wrapped if it is out of a valid range
*/
const SMDS_MeshNode* GetNodeWrap(const int ind) const { return GetNode( WrappedIndex( ind )); }
/*!
* \brief Return true if index of node is valid (0 <= ind < NbNodes())
* \param ind - node index
* \retval bool - index check result
*/
virtual bool IsValidIndex(const int ind) const;
/*!
* \brief Return a valid node index, fixing the given one if necessary
* \param ind - node index
* \retval int - valid node index
*/
int WrappedIndex(const int ind) const {
if ( ind < 0 ) return NbNodes() + ind % NbNodes();
if ( ind >= NbNodes() ) return ind % NbNodes();
return ind;
}
/*!
* \brief Check if a node belongs to the element
* \param node - the node to check
* \retval int - node index within the element, -1 if not found
*/
int GetNodeIndex( const SMDS_MeshNode* node ) const;
inline ShortType getMeshId() const { return myMeshId; }
inline LongType getshapeId() const { return myShapeId; }
inline int getIdInShape() const { return myIdInShape; }
inline int getVtkId() const { return myVtkID; }
/*!
* \brief Filters of elements, to be used with SMDS_SetIterator
*/
struct TypeFilter
{
SMDSAbs_ElementType _type;
TypeFilter( SMDSAbs_ElementType t = SMDSAbs_NbElementTypes ):_type(t) {}
bool operator()(const SMDS_MeshElement* e) const { return e && e->GetType() == _type; }
};
struct EntityFilter
{
SMDSAbs_EntityType _type;
EntityFilter( SMDSAbs_EntityType t = SMDSEntity_Last ):_type(t) {}
bool operator()(const SMDS_MeshElement* e) const { return e && e->GetEntityType() == _type; }
};
struct GeomFilter
{
SMDSAbs_GeometryType _type;
GeomFilter( SMDSAbs_GeometryType t = SMDSGeom_NONE ):_type(t) {}
bool operator()(const SMDS_MeshElement* e) const { return e && e->GetGeomType() == _type; }
};
protected:
inline void setId(int id) {myID = id; }
inline void setShapeId(LongType shapeId) {myShapeId = shapeId; }
inline void setIdInShape(int id) { myIdInShape = id; }
inline void setVtkId(int vtkId) { myVtkID = vtkId; }
SMDS_MeshElement(int ID=-1);
SMDS_MeshElement(int id, ShortType meshId, LongType shapeId = 0);
virtual void init(int id = -1, ShortType meshId = -1, LongType shapeId = 0);
virtual void Print(std::ostream & OS) const;
//! Element index in vector SMDS_Mesh::myNodes or SMDS_Mesh::myCells
int myID;
//! index in vtkUnstructuredGrid
int myVtkID;
//! SMDS_Mesh identification in SMESH
ShortType myMeshId;
//! SubShape and SubMesh identification in SMESHDS
LongType myShapeId;
//! Element index in SMESHDS_SubMesh vector
int myIdInShape;
};
// ============================================================
/*!
* \brief Comparator of elements by ID for usage in std containers
*/
// ============================================================
struct TIDCompare {
bool operator () (const SMDS_MeshElement* e1, const SMDS_MeshElement* e2) const
{ return e1->GetType() == e2->GetType() ? e1->GetID() < e2->GetID() : e1->GetType() < e2->GetType(); }
};
#endif
<commit_msg>0022108: EDF 2547 SMESH: Duplicate elements only<commit_after>// Copyright (C) 2007-2013 CEA/DEN, EDF R&D, OPEN CASCADE
//
// Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
//
// 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.
//
// 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
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
// SMESH SMDS : implementaion of Salome mesh data structure
// File : SMDS_MeshElement.hxx
// Module : SMESH
//
#ifndef _SMDS_MeshElement_HeaderFile
#define _SMDS_MeshElement_HeaderFile
#include "SMESH_SMDS.hxx"
#include "SMDSAbs_ElementType.hxx"
#include "SMDS_MeshObject.hxx"
#include "SMDS_ElemIterator.hxx"
#include "SMDS_MeshElementIDFactory.hxx"
#include "SMDS_StdIterator.hxx"
#include <vector>
#include <iostream>
#include <vtkType.h>
#include <vtkCellType.h>
//typedef unsigned short UShortType;
typedef short ShortType;
typedef int LongType;
class SMDS_MeshNode;
class SMDS_MeshEdge;
class SMDS_MeshFace;
class SMDS_Mesh;
// ============================================================
/*!
* \brief Base class for elements
*/
// ============================================================
class SMDS_EXPORT SMDS_MeshElement:public SMDS_MeshObject
{
public:
SMDS_ElemIteratorPtr nodesIterator() const;
SMDS_ElemIteratorPtr edgesIterator() const;
SMDS_ElemIteratorPtr facesIterator() const;
virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType type) const;
virtual SMDS_ElemIteratorPtr interlacedNodesElemIterator() const;
virtual SMDS_NodeIteratorPtr nodeIterator() const;
virtual SMDS_NodeIteratorPtr interlacedNodesIterator() const;
virtual SMDS_NodeIteratorPtr nodesIteratorToUNV() const;
// std-like iteration on nodes
typedef SMDS_StdIterator< const SMDS_MeshNode*, SMDS_ElemIteratorPtr > iterator;
iterator begin_nodes() const { return iterator( nodesIterator() ); }
iterator end_nodes() const { return iterator(); }
virtual int NbNodes() const;
virtual int NbEdges() const;
virtual int NbFaces() const;
inline int GetID() const { return myID; };
///Return the type of the current element
virtual SMDSAbs_ElementType GetType() const = 0;
virtual SMDSAbs_EntityType GetEntityType() const = 0;
virtual SMDSAbs_GeometryType GetGeomType() const = 0;
virtual vtkIdType GetVtkType() const = 0;
virtual bool IsPoly() const { return false; }
virtual bool IsQuadratic() const;
virtual bool IsMediumNode(const SMDS_MeshNode* node) const;
virtual int NbCornerNodes() const;
friend SMDS_EXPORT std::ostream & operator <<(std::ostream & OS, const SMDS_MeshElement *);
friend SMDS_EXPORT bool SMDS_MeshElementIDFactory::BindID(int ID,SMDS_MeshElement* elem);
friend class SMDS_Mesh;
friend class SMESHDS_Mesh;
friend class SMESHDS_SubMesh;
friend class SMDS_MeshElementIDFactory;
// ===========================
// Access to nodes by index
// ===========================
/*!
* \brief Return node by its index
* \param ind - node index
* \retval const SMDS_MeshNode* - the node
*/
virtual const SMDS_MeshNode* GetNode(const int ind) const;
/*!
* \brief Return node by its index
* \param ind - node index
* \retval const SMDS_MeshNode* - the node
*
* Index is wrapped if it is out of a valid range
*/
const SMDS_MeshNode* GetNodeWrap(const int ind) const { return GetNode( WrappedIndex( ind )); }
/*!
* \brief Return true if index of node is valid (0 <= ind < NbNodes())
* \param ind - node index
* \retval bool - index check result
*/
virtual bool IsValidIndex(const int ind) const;
/*!
* \brief Return a valid node index, fixing the given one if necessary
* \param ind - node index
* \retval int - valid node index
*/
int WrappedIndex(const int ind) const {
if ( ind < 0 ) return NbNodes() + ind % NbNodes();
if ( ind >= NbNodes() ) return ind % NbNodes();
return ind;
}
/*!
* \brief Check if a node belongs to the element
* \param node - the node to check
* \retval int - node index within the element, -1 if not found
*/
int GetNodeIndex( const SMDS_MeshNode* node ) const;
inline ShortType getMeshId() const { return myMeshId; }
inline LongType getshapeId() const { return myShapeId; }
inline int getIdInShape() const { return myIdInShape; }
inline int getVtkId() const { return myVtkID; }
/*!
* \brief Filters of elements, to be used with SMDS_SetIterator
*/
struct Filter
{
virtual bool operator()(const SMDS_MeshElement* e) const = 0;
~Filter() {}
};
struct NonNullFilter: public Filter
{
bool operator()(const SMDS_MeshElement* e) const { return e; }
};
struct TypeFilter : public Filter
{
SMDSAbs_ElementType _type;
TypeFilter( SMDSAbs_ElementType t = SMDSAbs_NbElementTypes ):_type(t) {}
bool operator()(const SMDS_MeshElement* e) const { return e && e->GetType() == _type; }
};
struct EntityFilter : public Filter
{
SMDSAbs_EntityType _type;
EntityFilter( SMDSAbs_EntityType t = SMDSEntity_Last ):_type(t) {}
bool operator()(const SMDS_MeshElement* e) const { return e && e->GetEntityType() == _type; }
};
struct GeomFilter : public Filter
{
SMDSAbs_GeometryType _type;
GeomFilter( SMDSAbs_GeometryType t = SMDSGeom_NONE ):_type(t) {}
bool operator()(const SMDS_MeshElement* e) const { return e && e->GetGeomType() == _type; }
};
protected:
inline void setId(int id) {myID = id; }
inline void setShapeId(LongType shapeId) {myShapeId = shapeId; }
inline void setIdInShape(int id) { myIdInShape = id; }
inline void setVtkId(int vtkId) { myVtkID = vtkId; }
SMDS_MeshElement(int ID=-1);
SMDS_MeshElement(int id, ShortType meshId, LongType shapeId = 0);
virtual void init(int id = -1, ShortType meshId = -1, LongType shapeId = 0);
virtual void Print(std::ostream & OS) const;
//! Element index in vector SMDS_Mesh::myNodes or SMDS_Mesh::myCells
int myID;
//! index in vtkUnstructuredGrid
int myVtkID;
//! SMDS_Mesh identification in SMESH
ShortType myMeshId;
//! SubShape and SubMesh identification in SMESHDS
LongType myShapeId;
//! Element index in SMESHDS_SubMesh vector
int myIdInShape;
};
// ============================================================
/*!
* \brief Comparator of elements by ID for usage in std containers
*/
// ============================================================
struct TIDCompare {
bool operator () (const SMDS_MeshElement* e1, const SMDS_MeshElement* e2) const
{ return e1->GetType() == e2->GetType() ? e1->GetID() < e2->GetID() : e1->GetType() < e2->GetType(); }
};
#endif
<|endoftext|> |
<commit_before>// Copyright (C) 2007-2013 CEA/DEN, EDF R&D, OPEN CASCADE
//
// Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
//
// 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.
//
// 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
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
// SMESH SMESH_Tree : tree implementation
// File : SMESH_Tree.hxx
// Created : Tue Jan 16 16:00:00 2007
// Author : Nicolas Geimer & Aurlien Motteux (OCC)
// Module : SMESH
//
#ifndef _SMESH_Tree_HXX_
#define _SMESH_Tree_HXX_
#include "SMESH_Utils.hxx"
//================================================================================
// Data limiting the tree height
struct SMESH_TreeLimit {
// MaxLevel of the Tree
int myMaxLevel;
// Minimal size of the Box
double myMinBoxSize;
// Default:
// maxLevel-> 8^8 = 16777216 terminal trees at most
// minSize -> box size not checked
SMESH_TreeLimit(int maxLevel=8, double minSize=0.):myMaxLevel(maxLevel),myMinBoxSize(minSize) {}
virtual ~SMESH_TreeLimit() {} // it can be inherited
};
//================================================================================
/*!
* \brief Base class for 2D and 3D trees
*/
//================================================================================
template< class BND_BOX,
int NB_CHILDREN>
class SMESH_Tree
{
public:
typedef BND_BOX box_type;
// Constructor. limit must be provided at tree root construction.
// limit will be deleted by SMESH_Tree
SMESH_Tree (SMESH_TreeLimit* limit=0);
// Destructor
virtual ~SMESH_Tree ();
// Compute the Tree. Must be called by constructor of inheriting class
void compute();
// Tell if Tree is a leaf or not.
// An inheriting class can influence it via myIsLeaf protected field
bool isLeaf() const;
// Return its level
int level() const { return myLevel; }
// Return Bounding Box of the Tree
const box_type* getBox() const { return myBox; }
// Return height of the tree, full or from this level to topest leaf
int getHeight(const bool full=true) const;
static int nbChildren() { return NB_CHILDREN; }
// Compute the biggest dimension of my box
virtual double maxSize() const = 0;
protected:
// Return box of the whole tree
virtual box_type* buildRootBox() = 0;
// Allocate a child
virtual SMESH_Tree* newChild() const = 0;
// Allocate a bndbox according to childIndex. childIndex is zero based
virtual box_type* newChildBox(int childIndex) const = 0;
// Fill in data of the children
virtual void buildChildrenData() = 0;
// members
// Array of children
SMESH_Tree** myChildren;
// Point the father, NULL for the level 0
SMESH_Tree* myFather;
// Tell us if the Tree is a leaf or not
bool myIsLeaf;
// Tree limit
const SMESH_TreeLimit* myLimit;
// Bounding box of a tree
box_type* myBox;
private:
// Build the children recursively
void buildChildren();
// Level of the Tree
int myLevel;
};
//===========================================================================
/*!
* Constructor. limit must be provided at tree root construction.
* limit will be deleted by SMESH_Tree.
*/
//===========================================================================
template< class BND_BOX, int NB_CHILDREN>
SMESH_Tree<BND_BOX,NB_CHILDREN>::SMESH_Tree (SMESH_TreeLimit* limit):
myChildren(0),
myFather(0),
myIsLeaf( false ),
myLimit( limit ),
myLevel(0),
myBox(0)
{
//if ( !myLimit ) myLimit = new SMESH_TreeLimit();
}
//================================================================================
/*!
* \brief Compute the Tree
*/
//================================================================================
template< class BND_BOX, int NB_CHILDREN>
void SMESH_Tree<BND_BOX,NB_CHILDREN>::compute()
{
if ( myLevel==0 )
{
if ( !myLimit ) myLimit = new SMESH_TreeLimit();
myBox = buildRootBox();
if ( myLimit->myMinBoxSize > 0. && maxSize() <= myLimit->myMinBoxSize )
myIsLeaf = true;
else
buildChildren();
}
}
//======================================
/*!
* \brief SMESH_Tree Destructor
*/
//======================================
template< class BND_BOX, int NB_CHILDREN>
SMESH_Tree<BND_BOX,NB_CHILDREN>::~SMESH_Tree ()
{
if ( myChildren )
{
if ( !isLeaf() )
{
for(int i = 0; i<NB_CHILDREN; i++)
delete myChildren[i];
delete[] myChildren;
myChildren = 0;
}
}
if ( myBox )
delete myBox;
myBox = 0;
if ( level() == 0 )
delete myLimit;
myLimit = 0;
}
//=================================================================
/*!
* \brief Build the children boxes and call buildChildrenData()
*/
//=================================================================
template< class BND_BOX, int NB_CHILDREN>
void SMESH_Tree<BND_BOX,NB_CHILDREN>::buildChildren()
{
if ( isLeaf() ) return;
myChildren = new SMESH_Tree*[NB_CHILDREN];
// get the whole model size
double rootSize = 0;
{
SMESH_Tree* root = this;
while ( root->myLevel > 0 )
root = root->myFather;
rootSize = root->maxSize();
}
for (int i = 0; i < NB_CHILDREN; i++)
{
// The child is of the same type than its father (For instance, a SMESH_OctreeNode)
// We allocate the memory we need for the child
myChildren[i] = newChild();
// and we assign to him its box.
myChildren[i]->myFather = this;
if (myChildren[i]->myLimit)
delete myChildren[i]->myLimit;
myChildren[i]->myLimit = myLimit;
myChildren[i]->myLevel = myLevel + 1;
myChildren[i]->myBox = newChildBox( i );
myChildren[i]->myBox->Enlarge( rootSize * 1e-10 );
if ( myLimit->myMinBoxSize > 0. && myChildren[i]->maxSize() <= myLimit->myMinBoxSize )
myChildren[i]->myIsLeaf = true;
}
// After building the NB_CHILDREN boxes, we put the data into the children.
buildChildrenData();
//After we pass to the next level of the Tree
for (int i = 0; i<NB_CHILDREN; i++)
myChildren[i]->buildChildren();
}
//================================================================================
/*!
* \brief Tell if Tree is a leaf or not
* An inheriting class can influence it via myIsLeaf protected field
*/
//================================================================================
template< class BND_BOX, int NB_CHILDREN>
bool SMESH_Tree<BND_BOX,NB_CHILDREN>::isLeaf() const
{
return myIsLeaf || ((myLimit->myMaxLevel > 0) ? (level() >= myLimit->myMaxLevel) : false );
}
//================================================================================
/*!
* \brief Return height of the tree, full or from this level to topest leaf
*/
//================================================================================
template< class BND_BOX, int NB_CHILDREN>
int SMESH_Tree<BND_BOX,NB_CHILDREN>::getHeight(const bool full) const
{
if ( full && myFather )
return myFather->getHeight( true );
if ( isLeaf() )
return 1;
int heigth = 0;
for (int i = 0; i<NB_CHILDREN; i++)
{
int h = myChildren[i]->getHeight( false );
if ( h > heigth )
heigth = h;
}
return heigth + 1;
}
#endif
<commit_msg>22355: EDF SMESH: New 1D hypothesis "Adaptive"<commit_after>// Copyright (C) 2007-2013 CEA/DEN, EDF R&D, OPEN CASCADE
//
// Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
//
// 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.
//
// 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
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
// SMESH SMESH_Tree : tree implementation
// File : SMESH_Tree.hxx
// Created : Tue Jan 16 16:00:00 2007
// Author : Nicolas Geimer & Aurlien Motteux (OCC)
// Module : SMESH
//
#ifndef _SMESH_Tree_HXX_
#define _SMESH_Tree_HXX_
#include "SMESH_Utils.hxx"
//================================================================================
// Data limiting the tree height
struct SMESH_TreeLimit {
// MaxLevel of the Tree
int myMaxLevel;
// Minimal size of the Box
double myMinBoxSize;
// Default:
// maxLevel-> 8^8 = 16777216 terminal trees at most
// minSize -> box size not checked
SMESH_TreeLimit(int maxLevel=8, double minSize=0.):myMaxLevel(maxLevel),myMinBoxSize(minSize) {}
virtual ~SMESH_TreeLimit() {} // it can be inherited
};
//================================================================================
/*!
* \brief Base class for 2D and 3D trees
*/
//================================================================================
template< class BND_BOX,
int NB_CHILDREN>
class SMESH_Tree
{
public:
typedef BND_BOX box_type;
// Constructor. limit must be provided at tree root construction.
// limit will be deleted by SMESH_Tree
SMESH_Tree (SMESH_TreeLimit* limit=0);
// Destructor
virtual ~SMESH_Tree ();
// Compute the Tree. Must be called by constructor of inheriting class
void compute();
// Tell if Tree is a leaf or not.
// An inheriting class can influence it via myIsLeaf protected field
bool isLeaf() const;
// Return its level
int level() const { return myLevel; }
// Return Bounding Box of the Tree
const box_type* getBox() const { return myBox; }
// Return height of the tree, full or from this level to topest leaf
int getHeight(const bool full=true) const;
static int nbChildren() { return NB_CHILDREN; }
// Compute the biggest dimension of my box
virtual double maxSize() const = 0;
protected:
// Return box of the whole tree
virtual box_type* buildRootBox() = 0;
// Allocate a child
virtual SMESH_Tree* newChild() const = 0;
// Allocate a bndbox according to childIndex. childIndex is zero based
virtual box_type* newChildBox(int childIndex) const = 0;
// Fill in data of the children
virtual void buildChildrenData() = 0;
// members
// Array of children
SMESH_Tree** myChildren;
// Point the father, NULL for the level 0
SMESH_Tree* myFather;
// Tell us if the Tree is a leaf or not
bool myIsLeaf;
// Tree limit
const SMESH_TreeLimit* myLimit;
// Bounding box of a tree
box_type* myBox;
// Level of the Tree
int myLevel;
// Build the children recursively
void buildChildren();
};
//===========================================================================
/*!
* Constructor. limit must be provided at tree root construction.
* limit will be deleted by SMESH_Tree.
*/
//===========================================================================
template< class BND_BOX, int NB_CHILDREN>
SMESH_Tree<BND_BOX,NB_CHILDREN>::SMESH_Tree (SMESH_TreeLimit* limit):
myChildren(0),
myFather(0),
myIsLeaf( false ),
myLimit( limit ),
myLevel(0),
myBox(0)
{
//if ( !myLimit ) myLimit = new SMESH_TreeLimit();
}
//================================================================================
/*!
* \brief Compute the Tree
*/
//================================================================================
template< class BND_BOX, int NB_CHILDREN>
void SMESH_Tree<BND_BOX,NB_CHILDREN>::compute()
{
if ( myLevel==0 )
{
if ( !myLimit ) myLimit = new SMESH_TreeLimit();
myBox = buildRootBox();
if ( myLimit->myMinBoxSize > 0. && maxSize() <= myLimit->myMinBoxSize )
myIsLeaf = true;
else
buildChildren();
}
}
//======================================
/*!
* \brief SMESH_Tree Destructor
*/
//======================================
template< class BND_BOX, int NB_CHILDREN>
SMESH_Tree<BND_BOX,NB_CHILDREN>::~SMESH_Tree ()
{
if ( myChildren )
{
if ( !isLeaf() )
{
for(int i = 0; i<NB_CHILDREN; i++)
delete myChildren[i];
delete[] myChildren;
myChildren = 0;
}
}
if ( myBox )
delete myBox;
myBox = 0;
if ( level() == 0 )
delete myLimit;
myLimit = 0;
}
//=================================================================
/*!
* \brief Build the children boxes and call buildChildrenData()
*/
//=================================================================
template< class BND_BOX, int NB_CHILDREN>
void SMESH_Tree<BND_BOX,NB_CHILDREN>::buildChildren()
{
if ( isLeaf() ) return;
myChildren = new SMESH_Tree*[NB_CHILDREN];
// get the whole model size
double rootSize = 0;
{
SMESH_Tree* root = this;
while ( root->myLevel > 0 )
root = root->myFather;
rootSize = root->maxSize();
}
for (int i = 0; i < NB_CHILDREN; i++)
{
// The child is of the same type than its father (For instance, a SMESH_OctreeNode)
// We allocate the memory we need for the child
myChildren[i] = newChild();
// and we assign to him its box.
myChildren[i]->myFather = this;
if (myChildren[i]->myLimit)
delete myChildren[i]->myLimit;
myChildren[i]->myLimit = myLimit;
myChildren[i]->myLevel = myLevel + 1;
myChildren[i]->myBox = newChildBox( i );
myChildren[i]->myBox->Enlarge( rootSize * 1e-10 );
if ( myLimit->myMinBoxSize > 0. && myChildren[i]->maxSize() <= myLimit->myMinBoxSize )
myChildren[i]->myIsLeaf = true;
}
// After building the NB_CHILDREN boxes, we put the data into the children.
buildChildrenData();
//After we pass to the next level of the Tree
for (int i = 0; i<NB_CHILDREN; i++)
myChildren[i]->buildChildren();
}
//================================================================================
/*!
* \brief Tell if Tree is a leaf or not
* An inheriting class can influence it via myIsLeaf protected field
*/
//================================================================================
template< class BND_BOX, int NB_CHILDREN>
bool SMESH_Tree<BND_BOX,NB_CHILDREN>::isLeaf() const
{
return myIsLeaf || ((myLimit->myMaxLevel > 0) ? (level() >= myLimit->myMaxLevel) : false );
}
//================================================================================
/*!
* \brief Return height of the tree, full or from this level to topest leaf
*/
//================================================================================
template< class BND_BOX, int NB_CHILDREN>
int SMESH_Tree<BND_BOX,NB_CHILDREN>::getHeight(const bool full) const
{
if ( full && myFather )
return myFather->getHeight( true );
if ( isLeaf() )
return 1;
int heigth = 0;
for (int i = 0; i<NB_CHILDREN; i++)
{
int h = myChildren[i]->getHeight( false );
if ( h > heigth )
heigth = h;
}
return heigth + 1;
}
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "webkit/plugins/ppapi/ppb_pdf_impl.h"
#include "app/resource_bundle.h"
#include "base/metrics/histogram.h"
#include "base/utf_string_conversions.h"
#include "build/build_config.h"
#include "grit/webkit_resources.h"
#include "grit/webkit_strings.h"
#include "skia/ext/platform_canvas.h"
#include "ppapi/c/pp_resource.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/icu/public/i18n/unicode/usearch.h"
#include "webkit/glue/webkit_glue.h"
#include "webkit/plugins/ppapi/plugin_delegate.h"
#include "webkit/plugins/ppapi/plugin_module.h"
#include "webkit/plugins/ppapi/ppapi_plugin_instance.h"
#include "webkit/plugins/ppapi/ppb_image_data_impl.h"
#include "webkit/plugins/ppapi/ppb_pdf.h"
#include "webkit/plugins/ppapi/var.h"
namespace webkit {
namespace ppapi {
#if defined(OS_LINUX)
class PrivateFontFile : public Resource {
public:
PrivateFontFile(PluginModule* module, int fd)
: Resource(module),
fd_(fd) {
}
virtual ~PrivateFontFile() {
}
// Resource overrides.
PrivateFontFile* AsPrivateFontFile() { return this; }
bool GetFontTable(uint32_t table,
void* output,
uint32_t* output_length);
private:
int fd_;
};
#endif
namespace {
struct ResourceImageInfo {
PP_ResourceImage pp_id;
int res_id;
};
static const ResourceImageInfo kResourceImageMap[] = {
{ PP_RESOURCEIMAGE_PDF_BUTTON_FTH, IDR_PDF_BUTTON_FTH },
{ PP_RESOURCEIMAGE_PDF_BUTTON_FTH_HOVER, IDR_PDF_BUTTON_FTH_HOVER },
{ PP_RESOURCEIMAGE_PDF_BUTTON_FTH_PRESSED, IDR_PDF_BUTTON_FTH_PRESSED },
{ PP_RESOURCEIMAGE_PDF_BUTTON_FTW, IDR_PDF_BUTTON_FTW },
{ PP_RESOURCEIMAGE_PDF_BUTTON_FTW_HOVER, IDR_PDF_BUTTON_FTW_HOVER },
{ PP_RESOURCEIMAGE_PDF_BUTTON_FTW_PRESSED, IDR_PDF_BUTTON_FTW_PRESSED },
{ PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN, IDR_PDF_BUTTON_ZOOMIN },
{ PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_HOVER, IDR_PDF_BUTTON_ZOOMIN_HOVER },
{ PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_PRESSED, IDR_PDF_BUTTON_ZOOMIN_PRESSED },
{ PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT, IDR_PDF_BUTTON_ZOOMOUT },
{ PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_HOVER, IDR_PDF_BUTTON_ZOOMOUT_HOVER },
{ PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_PRESSED,
IDR_PDF_BUTTON_ZOOMOUT_PRESSED },
{ PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_0, IDR_PDF_THUMBNAIL_0 },
{ PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_1, IDR_PDF_THUMBNAIL_1 },
{ PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_2, IDR_PDF_THUMBNAIL_2 },
{ PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_3, IDR_PDF_THUMBNAIL_3 },
{ PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_4, IDR_PDF_THUMBNAIL_4 },
{ PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_5, IDR_PDF_THUMBNAIL_5 },
{ PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_6, IDR_PDF_THUMBNAIL_6 },
{ PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_7, IDR_PDF_THUMBNAIL_7 },
{ PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_8, IDR_PDF_THUMBNAIL_8 },
{ PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_9, IDR_PDF_THUMBNAIL_9 },
{ PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_NUM_BACKGROUND,
IDR_PDF_THUMBNAIL_NUM_BACKGROUND },
};
PP_Var GetLocalizedString(PP_Module module_id, PP_ResourceString string_id) {
PluginModule* module = ResourceTracker::Get()->GetModule(module_id);
if (!module)
return PP_MakeUndefined();
std::string rv;
if (string_id == PP_RESOURCESTRING_PDFGETPASSWORD) {
rv = UTF16ToUTF8(webkit_glue::GetLocalizedString(IDS_PDF_NEED_PASSWORD));
} else if (string_id == PP_RESOURCESTRING_PDFLOADING) {
rv = UTF16ToUTF8(webkit_glue::GetLocalizedString(IDS_PDF_PAGE_LOADING));
} else if (string_id == PP_RESOURCESTRING_PDFLOAD_FAILED) {
rv = UTF16ToUTF8(webkit_glue::GetLocalizedString(IDS_PDF_PAGE_LOAD_FAILED));
} else {
NOTREACHED();
}
return StringVar::StringToPPVar(module, rv);
}
PP_Resource GetResourceImage(PP_Module module_id, PP_ResourceImage image_id) {
int res_id = 0;
for (size_t i = 0; i < arraysize(kResourceImageMap); ++i) {
if (kResourceImageMap[i].pp_id == image_id) {
res_id = kResourceImageMap[i].res_id;
break;
}
}
if (res_id == 0)
return 0;
SkBitmap* res_bitmap =
ResourceBundle::GetSharedInstance().GetBitmapNamed(res_id);
PluginModule* module = ResourceTracker::Get()->GetModule(module_id);
if (!module)
return 0;
scoped_refptr<PPB_ImageData_Impl> image_data(new PPB_ImageData_Impl(module));
if (!image_data->Init(PPB_ImageData_Impl::GetNativeImageDataFormat(),
res_bitmap->width(), res_bitmap->height(), false)) {
return 0;
}
ImageDataAutoMapper mapper(image_data);
if (!mapper.is_valid())
return 0;
skia::PlatformCanvas* canvas = image_data->mapped_canvas();
SkBitmap& ret_bitmap =
const_cast<SkBitmap&>(canvas->getTopPlatformDevice().accessBitmap(true));
if (!res_bitmap->copyTo(&ret_bitmap, SkBitmap::kARGB_8888_Config, NULL)) {
return 0;
}
return image_data->GetReference();
}
PP_Resource GetFontFileWithFallback(
PP_Module module_id,
const PP_FontDescription_Dev* description,
PP_PrivateFontCharset charset) {
#if defined(OS_LINUX)
PluginModule* module = ResourceTracker::Get()->GetModule(module_id);
if (!module)
return 0;
scoped_refptr<StringVar> face_name(StringVar::FromPPVar(description->face));
if (!face_name)
return 0;
int fd = webkit_glue::MatchFontWithFallback(
face_name->value().c_str(),
description->weight >= PP_FONTWEIGHT_BOLD,
description->italic,
charset);
if (fd == -1)
return 0;
scoped_refptr<PrivateFontFile> font(new PrivateFontFile(module, fd));
return font->GetReference();
#else
// For trusted PPAPI plugins, this is only needed in Linux since font loading
// on Windows and Mac works through the renderer sandbox.
return 0;
#endif
}
bool GetFontTableForPrivateFontFile(PP_Resource font_file,
uint32_t table,
void* output,
uint32_t* output_length) {
#if defined(OS_LINUX)
scoped_refptr<PrivateFontFile> font(
Resource::GetAs<PrivateFontFile>(font_file));
if (!font.get())
return false;
return font->GetFontTable(table, output, output_length);
#else
return false;
#endif
}
void SearchString(PP_Module module,
const unsigned short* input_string,
const unsigned short* input_term,
bool case_sensitive,
PP_PrivateFindResult** results,
int* count) {
const char16* string = reinterpret_cast<const char16*>(input_string);
const char16* term = reinterpret_cast<const char16*>(input_term);
UErrorCode status = U_ZERO_ERROR;
UStringSearch* searcher = usearch_open(
term, -1, string, -1, webkit_glue::GetWebKitLocale().c_str(), 0,
&status);
DCHECK(status == U_ZERO_ERROR || status == U_USING_FALLBACK_WARNING ||
status == U_USING_DEFAULT_WARNING);
UCollationStrength strength = case_sensitive ? UCOL_TERTIARY : UCOL_PRIMARY;
UCollator* collator = usearch_getCollator(searcher);
if (ucol_getStrength(collator) != strength) {
ucol_setStrength(collator, strength);
usearch_reset(searcher);
}
status = U_ZERO_ERROR;
int match_start = usearch_first(searcher, &status);
DCHECK(status == U_ZERO_ERROR);
std::vector<PP_PrivateFindResult> pp_results;
while (match_start != USEARCH_DONE) {
size_t matched_length = usearch_getMatchedLength(searcher);
PP_PrivateFindResult result;
result.start_index = match_start;
result.length = matched_length;
pp_results.push_back(result);
match_start = usearch_next(searcher, &status);
DCHECK(status == U_ZERO_ERROR);
}
*count = pp_results.size();
if (*count) {
*results = reinterpret_cast<PP_PrivateFindResult*>(
malloc(*count * sizeof(PP_PrivateFindResult)));
memcpy(*results, &pp_results[0], *count * sizeof(PP_PrivateFindResult));
} else {
*results = NULL;
}
usearch_close(searcher);
}
void DidStartLoading(PP_Instance instance_id) {
PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id);
if (!instance)
return;
instance->delegate()->DidStartLoading();
}
void DidStopLoading(PP_Instance instance_id) {
PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id);
if (!instance)
return;
instance->delegate()->DidStopLoading();
}
void SetContentRestriction(PP_Instance instance_id, int restrictions) {
PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id);
if (!instance)
return;
instance->delegate()->SetContentRestriction(restrictions);
}
void HistogramPDFPageCount(int count) {
UMA_HISTOGRAM_COUNTS_10000("PDF.PageCount", count);
}
void UserMetricsRecordAction(PP_Var action) {
scoped_refptr<StringVar> action_str(StringVar::FromPPVar(action));
if (action_str)
webkit_glue::UserMetricsRecordAction(action_str->value());
}
const PPB_PDF ppb_pdf = {
&GetLocalizedString,
&GetResourceImage,
&GetFontFileWithFallback,
&GetFontTableForPrivateFontFile,
&SearchString,
&DidStartLoading,
&DidStopLoading,
&SetContentRestriction,
&HistogramPDFPageCount,
&UserMetricsRecordAction
};
} // namespace
// static
const PPB_PDF* PPB_PDF_Impl::GetInterface() {
return &ppb_pdf;
}
#if defined(OS_LINUX)
bool PrivateFontFile::GetFontTable(uint32_t table,
void* output,
uint32_t* output_length) {
size_t temp_size = static_cast<size_t>(*output_length);
bool rv = webkit_glue::GetFontTable(
fd_, table, static_cast<uint8_t*>(output), &temp_size);
*output_length = static_cast<uint32_t>(temp_size);
return rv;
}
#endif
} // namespace ppapi
} // namespace webkit
<commit_msg>Modify inclusion to use system icu headers when -Duse_system_icu=1<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "webkit/plugins/ppapi/ppb_pdf_impl.h"
#include "app/resource_bundle.h"
#include "base/metrics/histogram.h"
#include "base/utf_string_conversions.h"
#include "build/build_config.h"
#include "grit/webkit_resources.h"
#include "grit/webkit_strings.h"
#include "skia/ext/platform_canvas.h"
#include "ppapi/c/pp_resource.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "unicode/usearch.h"
#include "webkit/glue/webkit_glue.h"
#include "webkit/plugins/ppapi/plugin_delegate.h"
#include "webkit/plugins/ppapi/plugin_module.h"
#include "webkit/plugins/ppapi/ppapi_plugin_instance.h"
#include "webkit/plugins/ppapi/ppb_image_data_impl.h"
#include "webkit/plugins/ppapi/ppb_pdf.h"
#include "webkit/plugins/ppapi/var.h"
namespace webkit {
namespace ppapi {
#if defined(OS_LINUX)
class PrivateFontFile : public Resource {
public:
PrivateFontFile(PluginModule* module, int fd)
: Resource(module),
fd_(fd) {
}
virtual ~PrivateFontFile() {
}
// Resource overrides.
PrivateFontFile* AsPrivateFontFile() { return this; }
bool GetFontTable(uint32_t table,
void* output,
uint32_t* output_length);
private:
int fd_;
};
#endif
namespace {
struct ResourceImageInfo {
PP_ResourceImage pp_id;
int res_id;
};
static const ResourceImageInfo kResourceImageMap[] = {
{ PP_RESOURCEIMAGE_PDF_BUTTON_FTH, IDR_PDF_BUTTON_FTH },
{ PP_RESOURCEIMAGE_PDF_BUTTON_FTH_HOVER, IDR_PDF_BUTTON_FTH_HOVER },
{ PP_RESOURCEIMAGE_PDF_BUTTON_FTH_PRESSED, IDR_PDF_BUTTON_FTH_PRESSED },
{ PP_RESOURCEIMAGE_PDF_BUTTON_FTW, IDR_PDF_BUTTON_FTW },
{ PP_RESOURCEIMAGE_PDF_BUTTON_FTW_HOVER, IDR_PDF_BUTTON_FTW_HOVER },
{ PP_RESOURCEIMAGE_PDF_BUTTON_FTW_PRESSED, IDR_PDF_BUTTON_FTW_PRESSED },
{ PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN, IDR_PDF_BUTTON_ZOOMIN },
{ PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_HOVER, IDR_PDF_BUTTON_ZOOMIN_HOVER },
{ PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMIN_PRESSED, IDR_PDF_BUTTON_ZOOMIN_PRESSED },
{ PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT, IDR_PDF_BUTTON_ZOOMOUT },
{ PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_HOVER, IDR_PDF_BUTTON_ZOOMOUT_HOVER },
{ PP_RESOURCEIMAGE_PDF_BUTTON_ZOOMOUT_PRESSED,
IDR_PDF_BUTTON_ZOOMOUT_PRESSED },
{ PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_0, IDR_PDF_THUMBNAIL_0 },
{ PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_1, IDR_PDF_THUMBNAIL_1 },
{ PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_2, IDR_PDF_THUMBNAIL_2 },
{ PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_3, IDR_PDF_THUMBNAIL_3 },
{ PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_4, IDR_PDF_THUMBNAIL_4 },
{ PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_5, IDR_PDF_THUMBNAIL_5 },
{ PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_6, IDR_PDF_THUMBNAIL_6 },
{ PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_7, IDR_PDF_THUMBNAIL_7 },
{ PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_8, IDR_PDF_THUMBNAIL_8 },
{ PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_9, IDR_PDF_THUMBNAIL_9 },
{ PP_RESOURCEIMAGE_PDF_BUTTON_THUMBNAIL_NUM_BACKGROUND,
IDR_PDF_THUMBNAIL_NUM_BACKGROUND },
};
PP_Var GetLocalizedString(PP_Module module_id, PP_ResourceString string_id) {
PluginModule* module = ResourceTracker::Get()->GetModule(module_id);
if (!module)
return PP_MakeUndefined();
std::string rv;
if (string_id == PP_RESOURCESTRING_PDFGETPASSWORD) {
rv = UTF16ToUTF8(webkit_glue::GetLocalizedString(IDS_PDF_NEED_PASSWORD));
} else if (string_id == PP_RESOURCESTRING_PDFLOADING) {
rv = UTF16ToUTF8(webkit_glue::GetLocalizedString(IDS_PDF_PAGE_LOADING));
} else if (string_id == PP_RESOURCESTRING_PDFLOAD_FAILED) {
rv = UTF16ToUTF8(webkit_glue::GetLocalizedString(IDS_PDF_PAGE_LOAD_FAILED));
} else {
NOTREACHED();
}
return StringVar::StringToPPVar(module, rv);
}
PP_Resource GetResourceImage(PP_Module module_id, PP_ResourceImage image_id) {
int res_id = 0;
for (size_t i = 0; i < arraysize(kResourceImageMap); ++i) {
if (kResourceImageMap[i].pp_id == image_id) {
res_id = kResourceImageMap[i].res_id;
break;
}
}
if (res_id == 0)
return 0;
SkBitmap* res_bitmap =
ResourceBundle::GetSharedInstance().GetBitmapNamed(res_id);
PluginModule* module = ResourceTracker::Get()->GetModule(module_id);
if (!module)
return 0;
scoped_refptr<PPB_ImageData_Impl> image_data(new PPB_ImageData_Impl(module));
if (!image_data->Init(PPB_ImageData_Impl::GetNativeImageDataFormat(),
res_bitmap->width(), res_bitmap->height(), false)) {
return 0;
}
ImageDataAutoMapper mapper(image_data);
if (!mapper.is_valid())
return 0;
skia::PlatformCanvas* canvas = image_data->mapped_canvas();
SkBitmap& ret_bitmap =
const_cast<SkBitmap&>(canvas->getTopPlatformDevice().accessBitmap(true));
if (!res_bitmap->copyTo(&ret_bitmap, SkBitmap::kARGB_8888_Config, NULL)) {
return 0;
}
return image_data->GetReference();
}
PP_Resource GetFontFileWithFallback(
PP_Module module_id,
const PP_FontDescription_Dev* description,
PP_PrivateFontCharset charset) {
#if defined(OS_LINUX)
PluginModule* module = ResourceTracker::Get()->GetModule(module_id);
if (!module)
return 0;
scoped_refptr<StringVar> face_name(StringVar::FromPPVar(description->face));
if (!face_name)
return 0;
int fd = webkit_glue::MatchFontWithFallback(
face_name->value().c_str(),
description->weight >= PP_FONTWEIGHT_BOLD,
description->italic,
charset);
if (fd == -1)
return 0;
scoped_refptr<PrivateFontFile> font(new PrivateFontFile(module, fd));
return font->GetReference();
#else
// For trusted PPAPI plugins, this is only needed in Linux since font loading
// on Windows and Mac works through the renderer sandbox.
return 0;
#endif
}
bool GetFontTableForPrivateFontFile(PP_Resource font_file,
uint32_t table,
void* output,
uint32_t* output_length) {
#if defined(OS_LINUX)
scoped_refptr<PrivateFontFile> font(
Resource::GetAs<PrivateFontFile>(font_file));
if (!font.get())
return false;
return font->GetFontTable(table, output, output_length);
#else
return false;
#endif
}
void SearchString(PP_Module module,
const unsigned short* input_string,
const unsigned short* input_term,
bool case_sensitive,
PP_PrivateFindResult** results,
int* count) {
const char16* string = reinterpret_cast<const char16*>(input_string);
const char16* term = reinterpret_cast<const char16*>(input_term);
UErrorCode status = U_ZERO_ERROR;
UStringSearch* searcher = usearch_open(
term, -1, string, -1, webkit_glue::GetWebKitLocale().c_str(), 0,
&status);
DCHECK(status == U_ZERO_ERROR || status == U_USING_FALLBACK_WARNING ||
status == U_USING_DEFAULT_WARNING);
UCollationStrength strength = case_sensitive ? UCOL_TERTIARY : UCOL_PRIMARY;
UCollator* collator = usearch_getCollator(searcher);
if (ucol_getStrength(collator) != strength) {
ucol_setStrength(collator, strength);
usearch_reset(searcher);
}
status = U_ZERO_ERROR;
int match_start = usearch_first(searcher, &status);
DCHECK(status == U_ZERO_ERROR);
std::vector<PP_PrivateFindResult> pp_results;
while (match_start != USEARCH_DONE) {
size_t matched_length = usearch_getMatchedLength(searcher);
PP_PrivateFindResult result;
result.start_index = match_start;
result.length = matched_length;
pp_results.push_back(result);
match_start = usearch_next(searcher, &status);
DCHECK(status == U_ZERO_ERROR);
}
*count = pp_results.size();
if (*count) {
*results = reinterpret_cast<PP_PrivateFindResult*>(
malloc(*count * sizeof(PP_PrivateFindResult)));
memcpy(*results, &pp_results[0], *count * sizeof(PP_PrivateFindResult));
} else {
*results = NULL;
}
usearch_close(searcher);
}
void DidStartLoading(PP_Instance instance_id) {
PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id);
if (!instance)
return;
instance->delegate()->DidStartLoading();
}
void DidStopLoading(PP_Instance instance_id) {
PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id);
if (!instance)
return;
instance->delegate()->DidStopLoading();
}
void SetContentRestriction(PP_Instance instance_id, int restrictions) {
PluginInstance* instance = ResourceTracker::Get()->GetInstance(instance_id);
if (!instance)
return;
instance->delegate()->SetContentRestriction(restrictions);
}
void HistogramPDFPageCount(int count) {
UMA_HISTOGRAM_COUNTS_10000("PDF.PageCount", count);
}
void UserMetricsRecordAction(PP_Var action) {
scoped_refptr<StringVar> action_str(StringVar::FromPPVar(action));
if (action_str)
webkit_glue::UserMetricsRecordAction(action_str->value());
}
const PPB_PDF ppb_pdf = {
&GetLocalizedString,
&GetResourceImage,
&GetFontFileWithFallback,
&GetFontTableForPrivateFontFile,
&SearchString,
&DidStartLoading,
&DidStopLoading,
&SetContentRestriction,
&HistogramPDFPageCount,
&UserMetricsRecordAction
};
} // namespace
// static
const PPB_PDF* PPB_PDF_Impl::GetInterface() {
return &ppb_pdf;
}
#if defined(OS_LINUX)
bool PrivateFontFile::GetFontTable(uint32_t table,
void* output,
uint32_t* output_length) {
size_t temp_size = static_cast<size_t>(*output_length);
bool rv = webkit_glue::GetFontTable(
fd_, table, static_cast<uint8_t*>(output), &temp_size);
*output_length = static_cast<uint32_t>(temp_size);
return rv;
}
#endif
} // namespace ppapi
} // namespace webkit
<|endoftext|> |
<commit_before>/*!
* Copyright (c) 2015 by Contributors
* \file im2rec.cc
* \brief convert images into image recordio format
* Image Record Format: zeropad[64bit] imid[64bit] img-binary-content
* The 64bit zero pad was reserved for future purposes
*
* Image List Format: unique-image-index label[s] path-to-image
* \sa dmlc/recordio.h
*/
#include <cctype>
#include <cstring>
#include <vector>
#include <iomanip>
#include <sstream>
#include <dmlc/base.h>
#include <dmlc/io.h>
#include <dmlc/timer.h>
#include <dmlc/logging.h>
#include <dmlc/recordio.h>
#include <opencv2/opencv.hpp>
#include "../src/io/image_recordio.h"
int main(int argc, char *argv[]) {
if (argc < 4) {
printf("Usage: <image.lst> <image_root_dir> <output.rec> [additional parameters in form key=value]\n"\
"Possible additional parameters:\n"\
"\tresize=newsize resize the shorter edge of image to the newsize, original images will be packed by default\n"\
"\tlabel_width=WIDTH[default=1] specify the label_width in the list, by default set to 1\n"\
"\tnsplit=NSPLIT[default=1] used for part generation, logically split the image.list to NSPLIT parts by position\n"\
"\tpart=PART[default=0] used for part generation, pack the images from the specific part in image.list\n"
"\tcenter_crop=CENTER_CROP[default=0] specify whether to crop the center image to make it rectangular.\n");
return 0;
}
int label_width = 1;
int new_size = -1;
int nsplit = 1;
int partid = 0;
int center_crop = 0;
for (int i = 4; i < argc; ++i) {
char key[128], val[128];
if (sscanf(argv[i], "%[^=]=%s", key, val) == 2) {
if (!strcmp(key, "resize")) new_size = atoi(val);
if (!strcmp(key, "label_width")) label_width = atoi(val);
if (!strcmp(key, "nsplit")) nsplit = atoi(val);
if (!strcmp(key, "part")) partid = atoi(val);
if (!strcmp(key, "center_crop")) center_crop = atoi(val);
}
}
if (new_size > 0) {
LOG(INFO) << "New Image Size: Short Edge " << new_size;
} else {
LOG(INFO) << "Keep origin image size";
}
if (center_crop) {
LOG(INFO) << "Center cropping to rectangular";
}
using namespace dmlc;
const static size_t kBufferSize = 1 << 20UL;
std::string root = argv[2];
mxnet::io::ImageRecordIO rec;
size_t imcnt = 0;
double tstart = dmlc::GetTime();
dmlc::InputSplit *flist = dmlc::InputSplit::
Create(argv[1], partid, nsplit, "text");
std::ostringstream os;
if (nsplit == 1) {
os << argv[3];
} else {
os << argv[3] << ".part" << std::setw(3) << std::setfill('0') << partid;
}
LOG(INFO) << "Write to output: " << os.str();
dmlc::Stream *fo = dmlc::Stream::Create(os.str().c_str(), "w");
LOG(INFO) << "Output: " << argv[3];
dmlc::RecordIOWriter writer(fo);
std::string fname, path, blob;
std::vector<unsigned char> decode_buf;
std::vector<unsigned char> encode_buf;
std::vector<int> encode_params;
encode_params.push_back(CV_IMWRITE_JPEG_QUALITY);
encode_params.push_back(80);
dmlc::InputSplit::Blob line;
while (flist->NextRecord(&line)) {
std::string sline(static_cast<char*>(line.dptr), line.size);
std::istringstream is(sline);
if (!(is >> rec.header.image_id[0] >> rec.header.label)) continue;
for (int k = 1; k < label_width; ++ k) {
float tmp;
CHECK(is >> tmp)
<< "Invalid ImageList, did you provide the correct label_width?";
}
CHECK(std::getline(is, fname));
// eliminate invalid chars in the end
while (fname.length() != 0 &&
(isspace(*fname.rbegin()) || !isprint(*fname.rbegin()))) {
fname.resize(fname.length() - 1);
}
// eliminate invalid chars in beginning.
const char *p = fname.c_str();
while (isspace(*p)) ++p;
path = root + p;
// use "r" is equal to rb in dmlc::Stream
dmlc::Stream *fi = dmlc::Stream::Create(path.c_str(), "r");
rec.SaveHeader(&blob);
decode_buf.clear();
size_t imsize = 0;
while (true) {
decode_buf.resize(imsize + kBufferSize);
size_t nread = fi->Read(BeginPtr(decode_buf) + imsize, kBufferSize);
imsize += nread;
decode_buf.resize(imsize);
if (nread != kBufferSize) break;
}
delete fi;
if (new_size > 0) {
cv::Mat img = cv::imdecode(decode_buf, CV_LOAD_IMAGE_COLOR);
CHECK(img.data != NULL) << "OpenCV decode fail:" << path;
if (center_crop) {
if (img.rows > img.cols) {
int margin = (img.rows - img.cols)/2;
img = img(cv::Range(margin, margin+img.cols), cv::Range(0, img.cols));
} else {
int margin = (img.cols - img.rows)/2;
img = img(cv::Range(0, img.rows), cv::Range(margin, margin + img.rows));
}
}
cv::Mat res;
if (img.rows > img.cols) {
cv::resize(img, res, cv::Size(new_size, img.rows * new_size / img.cols),
0, 0, CV_INTER_LINEAR);
} else {
cv::resize(img, res, cv::Size(new_size * img.cols / img.rows, new_size),
0, 0, CV_INTER_LINEAR);
}
encode_buf.clear();
CHECK(cv::imencode(".jpg", res, encode_buf, encode_params));
size_t bsize = blob.size();
blob.resize(bsize + encode_buf.size());
memcpy(BeginPtr(blob) + bsize,
BeginPtr(encode_buf), encode_buf.size());
} else {
size_t bsize = blob.size();
blob.resize(bsize + decode_buf.size());
memcpy(BeginPtr(blob) + bsize,
BeginPtr(decode_buf), decode_buf.size());
}
writer.WriteRecord(BeginPtr(blob), blob.size());
// write header
++imcnt;
if (imcnt % 1000 == 0) {
LOG(INFO) << imcnt << " images processed, " << GetTime() - tstart << " sec elapsed";
}
}
LOG(INFO) << "Total: " << imcnt << " images processed, " << GetTime() - tstart << " sec elapsed";
delete fo;
delete flist;
return 0;
}
<commit_msg>quality option for im2rec<commit_after>/*!
* Copyright (c) 2015 by Contributors
* \file im2rec.cc
* \brief convert images into image recordio format
* Image Record Format: zeropad[64bit] imid[64bit] img-binary-content
* The 64bit zero pad was reserved for future purposes
*
* Image List Format: unique-image-index label[s] path-to-image
* \sa dmlc/recordio.h
*/
#include <cctype>
#include <cstring>
#include <vector>
#include <iomanip>
#include <sstream>
#include <dmlc/base.h>
#include <dmlc/io.h>
#include <dmlc/timer.h>
#include <dmlc/logging.h>
#include <dmlc/recordio.h>
#include <opencv2/opencv.hpp>
#include "../src/io/image_recordio.h"
int main(int argc, char *argv[]) {
if (argc < 4) {
printf("Usage: <image.lst> <image_root_dir> <output.rec> [additional parameters in form key=value]\n"\
"Possible additional parameters:\n"\
"\tresize=newsize resize the shorter edge of image to the newsize, original images will be packed by default\n"\
"\tlabel_width=WIDTH[default=1] specify the label_width in the list, by default set to 1\n"\
"\tnsplit=NSPLIT[default=1] used for part generation, logically split the image.list to NSPLIT parts by position\n"\
"\tpart=PART[default=0] used for part generation, pack the images from the specific part in image.list\n"
"\tcenter_crop=CENTER_CROP[default=0] specify whether to crop the center image to make it rectangular.\n"
"\tquality=QUALITY[default=80] JPEG quality for encoding, 1-100.\n");
return 0;
}
int label_width = 1;
int new_size = -1;
int nsplit = 1;
int partid = 0;
int center_crop = 0;
int quality = 80;
for (int i = 4; i < argc; ++i) {
char key[128], val[128];
if (sscanf(argv[i], "%[^=]=%s", key, val) == 2) {
if (!strcmp(key, "resize")) new_size = atoi(val);
if (!strcmp(key, "label_width")) label_width = atoi(val);
if (!strcmp(key, "nsplit")) nsplit = atoi(val);
if (!strcmp(key, "part")) partid = atoi(val);
if (!strcmp(key, "center_crop")) center_crop = atoi(val);
if (!strcmp(key, "quality")) quality = atoi(val);
}
}
if (new_size > 0) {
LOG(INFO) << "New Image Size: Short Edge " << new_size;
} else {
LOG(INFO) << "Keep origin image size";
}
if (center_crop) {
LOG(INFO) << "Center cropping to rectangular";
}
using namespace dmlc;
const static size_t kBufferSize = 1 << 20UL;
std::string root = argv[2];
mxnet::io::ImageRecordIO rec;
size_t imcnt = 0;
double tstart = dmlc::GetTime();
dmlc::InputSplit *flist = dmlc::InputSplit::
Create(argv[1], partid, nsplit, "text");
std::ostringstream os;
if (nsplit == 1) {
os << argv[3];
} else {
os << argv[3] << ".part" << std::setw(3) << std::setfill('0') << partid;
}
LOG(INFO) << "Write to output: " << os.str();
dmlc::Stream *fo = dmlc::Stream::Create(os.str().c_str(), "w");
LOG(INFO) << "Output: " << argv[3];
dmlc::RecordIOWriter writer(fo);
std::string fname, path, blob;
std::vector<unsigned char> decode_buf;
std::vector<unsigned char> encode_buf;
std::vector<int> encode_params;
encode_params.push_back(CV_IMWRITE_JPEG_QUALITY);
encode_params.push_back(quality);
LOG(INFO) << "JPEG encoding quality: " << quality;
dmlc::InputSplit::Blob line;
while (flist->NextRecord(&line)) {
std::string sline(static_cast<char*>(line.dptr), line.size);
std::istringstream is(sline);
if (!(is >> rec.header.image_id[0] >> rec.header.label)) continue;
for (int k = 1; k < label_width; ++ k) {
float tmp;
CHECK(is >> tmp)
<< "Invalid ImageList, did you provide the correct label_width?";
}
CHECK(std::getline(is, fname));
// eliminate invalid chars in the end
while (fname.length() != 0 &&
(isspace(*fname.rbegin()) || !isprint(*fname.rbegin()))) {
fname.resize(fname.length() - 1);
}
// eliminate invalid chars in beginning.
const char *p = fname.c_str();
while (isspace(*p)) ++p;
path = root + p;
// use "r" is equal to rb in dmlc::Stream
dmlc::Stream *fi = dmlc::Stream::Create(path.c_str(), "r");
rec.SaveHeader(&blob);
decode_buf.clear();
size_t imsize = 0;
while (true) {
decode_buf.resize(imsize + kBufferSize);
size_t nread = fi->Read(BeginPtr(decode_buf) + imsize, kBufferSize);
imsize += nread;
decode_buf.resize(imsize);
if (nread != kBufferSize) break;
}
delete fi;
if (new_size > 0) {
cv::Mat img = cv::imdecode(decode_buf, CV_LOAD_IMAGE_COLOR);
CHECK(img.data != NULL) << "OpenCV decode fail:" << path;
if (center_crop) {
if (img.rows > img.cols) {
int margin = (img.rows - img.cols)/2;
img = img(cv::Range(margin, margin+img.cols), cv::Range(0, img.cols));
} else {
int margin = (img.cols - img.rows)/2;
img = img(cv::Range(0, img.rows), cv::Range(margin, margin + img.rows));
}
}
cv::Mat res;
if (img.rows > img.cols) {
cv::resize(img, res, cv::Size(new_size, img.rows * new_size / img.cols),
0, 0, CV_INTER_LINEAR);
} else {
cv::resize(img, res, cv::Size(new_size * img.cols / img.rows, new_size),
0, 0, CV_INTER_LINEAR);
}
encode_buf.clear();
CHECK(cv::imencode(".jpg", res, encode_buf, encode_params));
size_t bsize = blob.size();
blob.resize(bsize + encode_buf.size());
memcpy(BeginPtr(blob) + bsize,
BeginPtr(encode_buf), encode_buf.size());
} else {
size_t bsize = blob.size();
blob.resize(bsize + decode_buf.size());
memcpy(BeginPtr(blob) + bsize,
BeginPtr(decode_buf), decode_buf.size());
}
writer.WriteRecord(BeginPtr(blob), blob.size());
// write header
++imcnt;
if (imcnt % 1000 == 0) {
LOG(INFO) << imcnt << " images processed, " << GetTime() - tstart << " sec elapsed";
}
}
LOG(INFO) << "Total: " << imcnt << " images processed, " << GetTime() - tstart << " sec elapsed";
delete fo;
delete flist;
return 0;
}
<|endoftext|> |
<commit_before>/* Luwra
* Minimal-overhead Lua wrapper for C++
*
* Copyright (C) 2015, Ole Krüger <ole@vprsm.de>
*/
#ifndef LUWRA_USERTYPES_H_
#define LUWRA_USERTYPES_H_
#include "common.hpp"
#include "types.hpp"
#include "stack.hpp"
#include "functions.hpp"
#include <map>
LUWRA_NS_BEGIN
namespace internal {
template <typename T, typename... A> inline
int construct_user_type(State* state) {
return internal::Layout<int(A...)>::direct(
state,
1,
&Value<T&>::template push<A...>,
state
);
}
template <typename T> inline
int destruct_user_type(State* state) {
if (!lua_islightuserdata(state, 1))
Value<T&>::read(state, 1).~T();
return 0;
}
template <typename T>
std::string user_type_identifier =
"UD#" + std::to_string(uintmax_t(&destruct_user_type<T>));
template <typename T>
std::string stringify_user_type(T& val) {
return
internal::user_type_identifier<T>
+ "@"
+ std::to_string(uintmax_t(&val));
}
template <typename T, typename R, R T::* property_pointer> inline
int access_user_type_property(State* state) {
if (lua_gettop(state) > 1) {
// Setter
(Value<T&>::read(state, 1).*property_pointer) = Value<R>::read(state, 2);
return 0;
} else {
// Getter
return push(state, Value<T&>::read(state, 1).*property_pointer);
}
}
template <typename T, typename S>
struct MethodWrapper {
static_assert(
sizeof(T) == -1,
"The MethodWrapper template expects a type name and a function signature as parameter"
);
};
template <typename T, typename R, typename... A>
struct MethodWrapper<T, R(A...)> {
using MethodPointerType = R (T::*)(A...);
using FunctionSignature = R (T&, A...);
template <MethodPointerType method_pointer> static inline
R call(T& parent, A... args) {
return (parent.*method_pointer)(std::forward<A>(args)...);
}
};
}
/**
* User type T.
* Instances created using this specialization are allocated and constructed as full user data
* types in Lua. The default garbage-collecting hook will destruct the user type, once it has
* been marked.
*/
template <typename T>
struct Value<T&> {
static inline
T& read(State* state, int n) {
return *static_cast<T*>(
luaL_checkudata(state, n, internal::user_type_identifier<T>.c_str())
);
}
template <typename... A> static inline
int push(State* state, A&&... args) {
void* mem = lua_newuserdata(state, sizeof(T));
if (!mem) {
luaL_error(state, "Failed to allocate user type");
return -1;
}
// Call constructor on instance
new (mem) T(std::forward<A>(args)...);
// Set metatable for this type
luaL_getmetatable(state, internal::user_type_identifier<T>.c_str());
lua_setmetatable(state, -2);
return 1;
}
};
/**
* User type T.
* Instances created using this specialization are allocated as light user data in Lua.
* The default garbage-collector does not destruct light user data types.
*/
template <typename T>
struct Value<T*> {
static inline
T* read(State* state, int n) {
return static_cast<T*>(
luaL_checkudata(state, n, internal::user_type_identifier<T>.c_str())
);
}
static inline
int push(State* state, T* instance) {
// push instance as light user data
lua_pushlightuserdata(state, instance);
// Set metatable for this type
luaL_getmetatable(state, internal::user_type_identifier<T>.c_str());
lua_setmetatable(state, -2);
return 1;
}
};
/**
* Constructor function for a type `T`. Variadic arguments must be used to specify which parameters
* to use during construction.
*/
template <typename T, typename... A>
constexpr CFunction wrap_constructor = &internal::construct_user_type<T, A...>;
/**
* Works similiar to `wrap_function`. Given a class or struct declaration as follows:
*
* struct T {
* R my_method(A0, A1 ... An);
* };
*
* You might wrap this method easily:
*
* CFunction wrapped_meth = wrap_method<T, R(A0, A1 ... An), &T::my_method>;
*
* In Lua, assuming `instance` is a userdata instance of type `T`, x0, x1 ... xn are instances
* of A0, A1 ... An, and the method has been bound as `my_method`; it is possible to invoke the
* method like so:
*
* instance:my_method(x0, x1 ... xn)
*/
template <
typename T,
typename S,
typename internal::MethodWrapper<T, S>::MethodPointerType method_pointer
>
constexpr CFunction wrap_method =
wrap_function<
typename internal::MethodWrapper<T, S>::FunctionSignature,
internal::MethodWrapper<T, S>::template call<method_pointer>
>;
/**
* Property accessor method
*
* struct T {
* R my_property;
* };
*
* The wrapped property accessor is also a function:
*
* CFunction wrapped_property = wrap_property<T, R, &T::my_property>;
*/
template <
typename T,
typename R,
R T::* property_pointer
>
constexpr CFunction wrap_property =
&internal::access_user_type_property<T, R, property_pointer>;
/**
* Register the metatable for user type `T`. This function allows you to register methods
* which are shared across all instances of this type. A garbage-collector hook is also inserted.
* Meta-methods can be added and/or overwritten aswell.
*/
template <typename T> static inline
void register_user_type(
State* state,
const std::map<const char*, CFunction>& methods,
const std::map<const char*, CFunction>& meta_methods = {}
) {
// Setup an appropriate meta table name
luaL_newmetatable(state, internal::user_type_identifier<T>.c_str());
// Register methods
if (methods.size() > 0 && meta_methods.count("__index") == 0) {
push(state, "__index");
lua_newtable(state);
for (auto& method: methods) {
push(state, method.first);
push(state, method.second);
lua_rawset(state, -3);
}
lua_rawset(state, -3);
}
// Register garbage-collection hook
if (meta_methods.count("__gc") == 0) {
push(state, "__gc");
push(state, &internal::destruct_user_type<T>);
lua_rawset(state, -3);
}
// Register string representation function
if (meta_methods.count("__tostring") == 0) {
push(state, "__tostring");
push(state, wrap_function<std::string(T&), &internal::stringify_user_type<T>>);
lua_rawset(state, -3);
}
// Insert meta methods
for (const auto& metamethod: meta_methods) {
push(state, metamethod.first);
push(state, metamethod.second);
lua_rawset(state, -3);
}
// Pop meta table off the stack
lua_pop(state, -1);
}
LUWRA_NS_END
#endif
<commit_msg>Check user types on the stack via a type identifier<commit_after>/* Luwra
* Minimal-overhead Lua wrapper for C++
*
* Copyright (C) 2015, Ole Krüger <ole@vprsm.de>
*/
#ifndef LUWRA_USERTYPES_H_
#define LUWRA_USERTYPES_H_
#include "common.hpp"
#include "types.hpp"
#include "stack.hpp"
#include "functions.hpp"
#include <map>
LUWRA_NS_BEGIN
namespace internal {
using UserTypeID = const void*;
/**
* User type identifier
*/
template <typename T>
UserTypeID user_type_id = (void*) INTPTR_MAX;
/**
* Registry name for a meta table which is associated with a user type
*/
template <typename T>
std::string user_type_reg_name =
"UD#" + std::to_string(uintptr_t(&user_type_id<T>));
/**
* Register a new meta table for a user type T.
*/
template <typename T> static inline
void new_user_type_id(State* state) {
luaL_newmetatable(state, user_type_reg_name<T>.c_str());
// Use the address as user type identifier
user_type_id<T> = lua_topointer(state, -1);
}
/**
* Get the identifier for a user type at the given index.
*/
static inline
UserTypeID get_user_type_id(State* state, int index) {
if (!lua_isuserdata(state, index))
return nullptr;
if (lua_getmetatable(state, index)) {
UserTypeID type_id = lua_topointer(state, -1);
lua_pop(state, 1);
return type_id;
} else {
return nullptr;
}
}
/**
* Check if the value at the given index if a user type T.
*/
template <typename T> static inline
T* check_user_type(State* state, int index) {
UserTypeID uid = get_user_type_id(state, index);
if (uid == user_type_id<T>) {
return static_cast<T*>(lua_touserdata(state, index));
} else {
std::string error_msg =
"Expected user type " + std::to_string(uintptr_t(user_type_id<T>));
luaL_argerror(state, index, error_msg.c_str());
return nullptr;
}
}
template <typename T> static inline
void apply_user_type_meta_table(State* state) {
luaL_getmetatable(state, user_type_reg_name<T>.c_str());
lua_setmetatable(state, -2);
}
/**
* Lua C function to construct a user type T with parameters A
*/
template <typename T, typename... A> static inline
int construct_user_type(State* state) {
return internal::Layout<int(A...)>::direct(
state,
1,
&Value<T&>::template push<A...>,
state
);
}
/**
* Lua C function to destruct a user type T
*/
template <typename T> static inline
int destruct_user_type(State* state) {
if (!lua_islightuserdata(state, 1))
Value<T&>::read(state, 1).~T();
return 0;
}
/**
* Create a string representation for user type T.
*/
template <typename T> static
std::string stringify_user_type(T& val) {
return
internal::user_type_reg_name<T>
+ "@"
+ std::to_string(uintptr_t(&val));
}
/**
* Lua C function for a property accessor.
*/
template <typename T, typename R, R T::* property_pointer> static inline
int access_user_type_property(State* state) {
if (lua_gettop(state) > 1) {
// Setter
(Value<T&>::read(state, 1).*property_pointer) = Value<R>::read(state, 2);
return 0;
} else {
// Getter
return push(state, Value<T&>::read(state, 1).*property_pointer);
}
}
template <typename T, typename S>
struct MethodWrapper {
static_assert(
sizeof(T) == -1,
"The MethodWrapper template expects a type name and a function signature as parameter"
);
};
template <typename T, typename R, typename... A>
struct MethodWrapper<T, R(A...)> {
using MethodPointerType = R (T::*)(A...);
using FunctionSignature = R (T&, A...);
/**
* This function is a wrapped around the invocation of a given method.
*/
template <MethodPointerType method_pointer> static inline
R call(T& parent, A... args) {
return (parent.*method_pointer)(std::forward<A>(args)...);
}
};
}
/**
* User type T.
* Instances created using this specialization are allocated and constructed as full user data
* types in Lua. The default garbage-collecting hook will destruct the user type, once it has
* been marked.
*/
template <typename T>
struct Value<T&> {
static inline
T& read(State* state, int n) {
return *internal::check_user_type<T>(state, n);
}
template <typename... A> static inline
int push(State* state, A&&... args) {
void* mem = lua_newuserdata(state, sizeof(T));
if (!mem) {
luaL_error(state, "Failed to allocate user type");
return -1;
}
// Call constructor on instance
new (mem) T(std::forward<A>(args)...);
// Set metatable for this type
internal::apply_user_type_meta_table<T>(state);
return 1;
}
};
/**
* User type T.
* Instances created using this specialization are allocated as light user data in Lua.
* The default garbage-collector does not destruct light user data types.
*/
template <typename T>
struct Value<T*> {
static inline
T* read(State* state, int n) {
return internal::check_user_type<T>(state, n);
}
static inline
int push(State* state, T* instance) {
// push instance as light user data
lua_pushlightuserdata(state, instance);
// Set metatable for this type
internal::apply_user_type_meta_table<T>(state);
return 1;
}
};
/**
* Constructor function for a type `T`. Variadic arguments must be used to specify which parameters
* to use during construction.
*/
template <typename T, typename... A>
constexpr CFunction wrap_constructor = &internal::construct_user_type<T, A...>;
/**
* Works similiar to `wrap_function`. Given a class or struct declaration as follows:
*
* struct T {
* R my_method(A0, A1 ... An);
* };
*
* You might wrap this method easily:
*
* CFunction wrapped_meth = wrap_method<T, R(A0, A1 ... An), &T::my_method>;
*
* In Lua, assuming `instance` is a userdata instance of type `T`, x0, x1 ... xn are instances
* of A0, A1 ... An, and the method has been bound as `my_method`; it is possible to invoke the
* method like so:
*
* instance:my_method(x0, x1 ... xn)
*/
template <
typename T,
typename S,
typename internal::MethodWrapper<T, S>::MethodPointerType method_pointer
>
constexpr CFunction wrap_method =
wrap_function<
typename internal::MethodWrapper<T, S>::FunctionSignature,
internal::MethodWrapper<T, S>::template call<method_pointer>
>;
/**
* Property accessor method
*
* struct T {
* R my_property;
* };
*
* The wrapped property accessor is also a function:
*
* CFunction wrapped_property = wrap_property<T, R, &T::my_property>;
*/
template <
typename T,
typename R,
R T::* property_pointer
>
constexpr CFunction wrap_property =
&internal::access_user_type_property<T, R, property_pointer>;
/**
* Register the metatable for user type `T`. This function allows you to register methods
* which are shared across all instances of this type. A garbage-collector hook is also inserted.
* Meta-methods can be added and/or overwritten aswell.
*/
template <typename T> static inline
void register_user_type(
State* state,
const std::map<const char*, CFunction>& methods,
const std::map<const char*, CFunction>& meta_methods = {}
) {
// Setup an appropriate meta table name
// luaL_newmetatable(state, internal::user_type_reg_name<T>.c_str());
internal::new_user_type_id<T>(state);
// Register methods
if (methods.size() > 0 && meta_methods.count("__index") == 0) {
push(state, "__index");
lua_newtable(state);
for (auto& method: methods) {
push(state, method.first);
push(state, method.second);
lua_rawset(state, -3);
}
lua_rawset(state, -3);
}
// Register garbage-collection hook
if (meta_methods.count("__gc") == 0) {
push(state, "__gc");
push(state, &internal::destruct_user_type<T>);
lua_rawset(state, -3);
}
// Register string representation function
if (meta_methods.count("__tostring") == 0) {
push(state, "__tostring");
push(state, wrap_function<std::string(T&), &internal::stringify_user_type<T>>);
lua_rawset(state, -3);
}
// Insert meta methods
for (const auto& metamethod: meta_methods) {
push(state, metamethod.first);
push(state, metamethod.second);
lua_rawset(state, -3);
}
// Pop meta table off the stack
lua_pop(state, -1);
}
LUWRA_NS_END
#endif
<|endoftext|> |
<commit_before>/**********************************************************************
*
* GEOS - Geometry Engine Open Source
* http://geos.osgeo.org
*
* Copyright (C) 2018 Paul Ramsey <pramsey@cleverlephant.ca>
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************
*
* Last port: algorithm/Orientation.java @ 2017-09-04
*
**********************************************************************/
#include <cassert>
#include <cmath>
#include <vector>
#include <geos/algorithm/Orientation.h>
#include <geos/algorithm/CGAlgorithmsDD.h>
#include <geos/geom/CoordinateSequence.h>
#include <geos/geom/CoordinateArraySequence.h>
#include <geos/geom/Coordinate.h>
#include <geos/geom/Location.h>
#include <geos/util/IllegalArgumentException.h>
namespace geos {
namespace algorithm { // geos.algorithm
/* public static */
int
Orientation::index(const geom::Coordinate& p1, const geom::Coordinate& p2,
const geom::Coordinate& q)
{
return CGAlgorithmsDD::orientationIndex(p1, p2, q);
}
/* public static */
bool
Orientation::isCCW(const geom::CoordinateSequence* ring)
{
// # of points without closing endpoint
int nPts = ring->size() - 1;
// sanity check
if (nPts < 3)
throw util::IllegalArgumentException(
"Ring has fewer than 4 points, so orientation cannot be determined");
/**
* Find first highest point after a lower point, if one exists
* (e.g. a rising segment)
* If one does not exist, hiIndex will remain 0
* and the ring must be flat.
* Note this relies on the convention that
* rings have the same start and end point.
*/
geom::Coordinate upHiPt;
ring->getAt(0, upHiPt);
double prevY = upHiPt.y;
geom::Coordinate upLowPt;
upLowPt.setNull();
// const geom::Coordinate& upLowPt = nullptr;
int iUpHi = 0;
for (int i = 1; i <= nPts; i++) {
double py = ring->getY(i);
/**
* If segment is upwards and endpoint is higher, record it
*/
if (py > prevY && py >= upHiPt.y) {
ring->getAt(i, upHiPt);
iUpHi = i;
ring->getAt(i-1, upLowPt);
}
prevY = py;
}
/**
* Check if ring is flat and return default value if so
*/
if (iUpHi == 0) return false;
/**
* Find the next lower point after the high point
* (e.g. a falling segment).
* This must exist since ring is not flat.
*/
int iDownLow = iUpHi;
do {
iDownLow = (iDownLow + 1) % nPts;
} while (iDownLow != iUpHi && ring->getY(iDownLow) == upHiPt.y );
const geom::Coordinate& downLowPt = ring->getAt(iDownLow);
int iDownHi = iDownLow > 0 ? iDownLow - 1 : nPts - 1;
const geom::Coordinate& downHiPt = ring->getAt(iDownHi);
/**
* Two cases can occur:
* 1) the hiPt and the downPrevPt are the same.
* This is the general position case of a "pointed cap".
* The ring orientation is determined by the orientation of the cap
* 2) The hiPt and the downPrevPt are different.
* In this case the top of the cap is flat.
* The ring orientation is given by the direction of the flat segment
*/
if (upHiPt.equals2D(downHiPt)) {
/**
* Check for the case where the cap has configuration A-B-A.
* This can happen if the ring does not contain 3 distinct points
* (including the case where the input array has fewer than 4 elements), or
* it contains coincident line segments.
*/
if (upLowPt.equals2D(upHiPt) || downLowPt.equals2D(upHiPt) || upLowPt.equals2D(downLowPt))
return false;
/**
* It can happen that the top segments are coincident.
* This is an invalid ring, which cannot be computed correctly.
* In this case the orientation is 0, and the result is false.
*/
int orientationIndex = index(upLowPt, upHiPt, downLowPt);
return orientationIndex == COUNTERCLOCKWISE;
}
else {
/**
* Flat cap - direction of flat top determines orientation
*/
double delX = downHiPt.x - upHiPt.x;
return delX < 0;
}
}
#if 0
/* public static */
bool
Orientation::isCCW(const geom::CoordinateSequence* ring)
{
// sanity check
if(ring->getSize() < 4) {
throw util::IllegalArgumentException("Ring has fewer than 4 points, so orientation cannot be determined");
}
// # of points without closing endpoint
const std::size_t nPts = ring->getSize() - 1;
assert(nPts >= 3); // This is here for scan-build
// find highest point
const geom::Coordinate* hiPt = &ring->getAt(0);
size_t hiIndex = 0;
for(std::size_t i = 1; i <= nPts; ++i) {
const geom::Coordinate* p = &ring->getAt(i);
if(p->y > hiPt->y) {
hiPt = p;
hiIndex = i;
}
}
// find distinct point before highest point
auto iPrev = hiIndex;
do {
if(iPrev == 0) {
iPrev = nPts;
}
iPrev = iPrev - 1;
}
while(ring->getAt(iPrev) == *hiPt && iPrev != hiIndex);
// find distinct point after highest point
auto iNext = hiIndex;
do {
iNext = (iNext + 1) % nPts;
}
while(ring->getAt(iNext) == *hiPt && iNext != hiIndex);
const geom::Coordinate* prev = &ring->getAt(iPrev);
const geom::Coordinate* next = &ring->getAt(iNext);
/*
* This check catches cases where the ring contains an A-B-A
* configuration of points.
* This can happen if the ring does not contain 3 distinct points
* (including the case where the input array has fewer than 4 elements),
* or it contains coincident line segments.
*/
if(prev->equals2D(*hiPt) || next->equals2D(*hiPt) ||
prev->equals2D(*next)) {
return false;
// MD - don't bother throwing exception,
// since this isn't a complete check for ring validity
//throw IllegalArgumentException("degenerate ring (does not contain 3 distinct points)");
}
int disc = Orientation::index(*prev, *hiPt, *next);
/*
* If disc is exactly 0, lines are collinear.
* There are two possible cases:
* (1) the lines lie along the x axis in opposite directions
* (2) the lines lie on top of one another
*
* (1) is handled by checking if next is left of prev ==> CCW
* (2) should never happen, so we're going to ignore it!
* (Might want to assert this)
*/
bool isCCW = false;
if(disc == 0) {
// poly is CCW if prev x is right of next x
isCCW = (prev->x > next->x);
}
else {
// if area is positive, points are ordered CCW
isCCW = (disc > 0);
}
return isCCW;
}
#endif
} // namespace geos.algorithm
} //namespace geos
<commit_msg>Orientation.cpp: fix warning about implicit cast of size_t to int<commit_after>/**********************************************************************
*
* GEOS - Geometry Engine Open Source
* http://geos.osgeo.org
*
* Copyright (C) 2018 Paul Ramsey <pramsey@cleverlephant.ca>
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************
*
* Last port: algorithm/Orientation.java @ 2017-09-04
*
**********************************************************************/
#include <cassert>
#include <cmath>
#include <vector>
#include <geos/algorithm/Orientation.h>
#include <geos/algorithm/CGAlgorithmsDD.h>
#include <geos/geom/CoordinateSequence.h>
#include <geos/geom/CoordinateArraySequence.h>
#include <geos/geom/Coordinate.h>
#include <geos/geom/Location.h>
#include <geos/util/IllegalArgumentException.h>
namespace geos {
namespace algorithm { // geos.algorithm
/* public static */
int
Orientation::index(const geom::Coordinate& p1, const geom::Coordinate& p2,
const geom::Coordinate& q)
{
return CGAlgorithmsDD::orientationIndex(p1, p2, q);
}
/* public static */
bool
Orientation::isCCW(const geom::CoordinateSequence* ring)
{
// # of points without closing endpoint
int nPts = static_cast<int>(ring->size()) - 1;
// sanity check
if (nPts < 3)
throw util::IllegalArgumentException(
"Ring has fewer than 4 points, so orientation cannot be determined");
/**
* Find first highest point after a lower point, if one exists
* (e.g. a rising segment)
* If one does not exist, hiIndex will remain 0
* and the ring must be flat.
* Note this relies on the convention that
* rings have the same start and end point.
*/
geom::Coordinate upHiPt;
ring->getAt(0, upHiPt);
double prevY = upHiPt.y;
geom::Coordinate upLowPt;
upLowPt.setNull();
// const geom::Coordinate& upLowPt = nullptr;
int iUpHi = 0;
for (int i = 1; i <= nPts; i++) {
double py = ring->getY(i);
/**
* If segment is upwards and endpoint is higher, record it
*/
if (py > prevY && py >= upHiPt.y) {
ring->getAt(i, upHiPt);
iUpHi = i;
ring->getAt(i-1, upLowPt);
}
prevY = py;
}
/**
* Check if ring is flat and return default value if so
*/
if (iUpHi == 0) return false;
/**
* Find the next lower point after the high point
* (e.g. a falling segment).
* This must exist since ring is not flat.
*/
int iDownLow = iUpHi;
do {
iDownLow = (iDownLow + 1) % nPts;
} while (iDownLow != iUpHi && ring->getY(iDownLow) == upHiPt.y );
const geom::Coordinate& downLowPt = ring->getAt(iDownLow);
int iDownHi = iDownLow > 0 ? iDownLow - 1 : nPts - 1;
const geom::Coordinate& downHiPt = ring->getAt(iDownHi);
/**
* Two cases can occur:
* 1) the hiPt and the downPrevPt are the same.
* This is the general position case of a "pointed cap".
* The ring orientation is determined by the orientation of the cap
* 2) The hiPt and the downPrevPt are different.
* In this case the top of the cap is flat.
* The ring orientation is given by the direction of the flat segment
*/
if (upHiPt.equals2D(downHiPt)) {
/**
* Check for the case where the cap has configuration A-B-A.
* This can happen if the ring does not contain 3 distinct points
* (including the case where the input array has fewer than 4 elements), or
* it contains coincident line segments.
*/
if (upLowPt.equals2D(upHiPt) || downLowPt.equals2D(upHiPt) || upLowPt.equals2D(downLowPt))
return false;
/**
* It can happen that the top segments are coincident.
* This is an invalid ring, which cannot be computed correctly.
* In this case the orientation is 0, and the result is false.
*/
int orientationIndex = index(upLowPt, upHiPt, downLowPt);
return orientationIndex == COUNTERCLOCKWISE;
}
else {
/**
* Flat cap - direction of flat top determines orientation
*/
double delX = downHiPt.x - upHiPt.x;
return delX < 0;
}
}
#if 0
/* public static */
bool
Orientation::isCCW(const geom::CoordinateSequence* ring)
{
// sanity check
if(ring->getSize() < 4) {
throw util::IllegalArgumentException("Ring has fewer than 4 points, so orientation cannot be determined");
}
// # of points without closing endpoint
const std::size_t nPts = ring->getSize() - 1;
assert(nPts >= 3); // This is here for scan-build
// find highest point
const geom::Coordinate* hiPt = &ring->getAt(0);
size_t hiIndex = 0;
for(std::size_t i = 1; i <= nPts; ++i) {
const geom::Coordinate* p = &ring->getAt(i);
if(p->y > hiPt->y) {
hiPt = p;
hiIndex = i;
}
}
// find distinct point before highest point
auto iPrev = hiIndex;
do {
if(iPrev == 0) {
iPrev = nPts;
}
iPrev = iPrev - 1;
}
while(ring->getAt(iPrev) == *hiPt && iPrev != hiIndex);
// find distinct point after highest point
auto iNext = hiIndex;
do {
iNext = (iNext + 1) % nPts;
}
while(ring->getAt(iNext) == *hiPt && iNext != hiIndex);
const geom::Coordinate* prev = &ring->getAt(iPrev);
const geom::Coordinate* next = &ring->getAt(iNext);
/*
* This check catches cases where the ring contains an A-B-A
* configuration of points.
* This can happen if the ring does not contain 3 distinct points
* (including the case where the input array has fewer than 4 elements),
* or it contains coincident line segments.
*/
if(prev->equals2D(*hiPt) || next->equals2D(*hiPt) ||
prev->equals2D(*next)) {
return false;
// MD - don't bother throwing exception,
// since this isn't a complete check for ring validity
//throw IllegalArgumentException("degenerate ring (does not contain 3 distinct points)");
}
int disc = Orientation::index(*prev, *hiPt, *next);
/*
* If disc is exactly 0, lines are collinear.
* There are two possible cases:
* (1) the lines lie along the x axis in opposite directions
* (2) the lines lie on top of one another
*
* (1) is handled by checking if next is left of prev ==> CCW
* (2) should never happen, so we're going to ignore it!
* (Might want to assert this)
*/
bool isCCW = false;
if(disc == 0) {
// poly is CCW if prev x is right of next x
isCCW = (prev->x > next->x);
}
else {
// if area is positive, points are ordered CCW
isCCW = (disc > 0);
}
return isCCW;
}
#endif
} // namespace geos.algorithm
} //namespace geos
<|endoftext|> |
<commit_before><commit_msg>latest<commit_after><|endoftext|> |
<commit_before>#include "rampancy/Cortex.h"
#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/CallGraphSCCPass.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/Assembly/PrintModulePass.h"
#include "llvm/Analysis/DebugInfo.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Analysis/LoopPass.h"
#include "llvm/Analysis/RegionPass.h"
#include "llvm/Analysis/CallGraph.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Target/TargetLibraryInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Support/PassNameParser.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/IRReader.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PluginLoader.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/SystemUtils.h"
#include "llvm/Support/ToolOutputFile.h"
#include "llvm/LinkAllPasses.h"
#include "llvm/LinkAllVMCore.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
#include <memory>
#include <algorithm>
#include "rampancy/Compiler.h"
#include "rampancy/CompilerManager.h"
#include "rampancy/CompilerRegistry.h"
#include "ExpertSystem/FunctionKnowledgeConversionPass.h"
extern "C" {
#include "clips.h"
}
namespace rampancy {
static llvm::ManagedStatic<Cortex> rampantCortexObject;
Cortex* Cortex::getRampantCortex() {
return &*rampantCortexObject;
}
Cortex::Cortex(void* theEnv) {
if(theEnv) {
env = new CLIPSEnvironment(theEnv);
} else {
env = new CLIPSEnvironment();
}
context = new llvm::LLVMContext();
manager = new CompilerManager();
manager->setContext(context);
manager->setEnvironment(env);
}
Cortex::~Cortex() {
delete manager;
delete context;
delete env;
}
llvm::LLVMContext* Cortex::getContext() {
return context;
}
void Cortex::setContext(llvm::LLVMContext* llvmContext) {
context = llvmContext;
manager->setContext(context);
}
CLIPSEnvironment* Cortex::getEnvironment() {
return env;
}
void Cortex::setEnvironment(CLIPSEnvironment* theEnv) {
env = theEnv;
manager->setEnvironment(env);
}
void Cortex::compileToKnowledge(void* theEnv) {
//we need to get the first argument from theEnv to find out where to
//route it to
DATA_OBJECT arg0;
char* copy;
copy = CharBuffer(512);
//change this so that only the first argument is handled by
//compileToKnowledge
if((EnvArgCountCheck(theEnv, (char*)"rampancy-compile", AT_LEAST, 1) == -1)) {
EnvPrintRouter(theEnv, (char*)"werror",
(char*)"\nCompile arguments are <compiler> ...\n"
"It is up to the compiler backend to handle the rest of the arguments\n");
return;
}
if((EnvArgTypeCheck(theEnv, (char*)"rampancy-compile", 1, SYMBOL, &arg0) == 0)) {
EnvPrintRouter(theEnv, (char*)"werror",
(char*)"\ncompiler name must be a symbol!\n");
return;
}
std::string tmp (DOToString(arg0));
//we need some indirection to prevent the CLIPS garbage collector from
//coming down like a fucking hammer on what we're doing here. Awesomely,
//this will all be cleaned up at the end of the function :D.
llvm::StringRef logicalName(tmp);
llvm::Module* module = compile(logicalName, theEnv);
if(!module) {
EnvPrintRouter(theEnv, (char*)"werror",
(char*)"\nThe compiler failed to compile the target file\n");
return;
}
convertToKnowledge(logicalName, module, theEnv);
}
void Cortex::interpretToKnowledge(void* theEnv) {
//we need to get the first argument from theEnv to find out where to
//route it to
DATA_OBJECT arg0;
char* copy;
copy = CharBuffer(512);
if((EnvArgCountCheck(theEnv, (char*)"rampancy-interpret", EXACTLY, 2) == -1)) {
EnvPrintRouter(theEnv, (char*)"werror",
(char*)"\nInterpret arguments are <compiler> <code>\n");
return;
}
if((EnvArgTypeCheck(theEnv, (char*)"rampancy-interpret", 1, SYMBOL, &arg0) == 0)) {
EnvPrintRouter(theEnv, (char*)"werror",
(char*)"\nCompiler name must be a symbol!\n");
return;
}
std::string tmp (DOToString(arg0));
//we need some indirection to prevent the CLIPS garbage collector from
//coming down like a fucking hammer on what we're doing here. Awesomely,
//this will all be cleaned up at the end of the function :D.
llvm::StringRef logicalName(tmp);
llvm::Module* module = interpret(logicalName, theEnv);
if(!module) {
EnvPrintRouter(theEnv, (char*)"werror",
(char*)"\nThe compiler failed to interpret the target file\n");
return;
}
convertToKnowledge(logicalName, module, theEnv);
}
llvm::Module* Cortex::compile(llvm::StringRef logicalName, void* theEnv) {
return manager->compile(logicalName, theEnv);
}
llvm::Module* Cortex::interpret(llvm::StringRef logicalName, void* theEnv) {
return manager->interpret(logicalName, theEnv);
}
llvm::Module* Cortex::compile(char* logicalName, int argc, char** argv) {
return manager->compile(logicalName, argc, argv);
}
llvm::Module* Cortex::compile(llvm::StringRef logicalName, int argc, char** argv) {
return manager->compile(logicalName, argc, argv);
}
llvm::Module* Cortex::interpret(llvm::StringRef logicalName,
llvm::StringRef input) {
return manager->interpret(logicalName, input);
}
llvm::Module* Cortex::interpret(char* logicalName, llvm::StringRef input) {
return manager->interpret(logicalName, input);
}
void Cortex::convertToKnowledge(llvm::StringRef logicalName,
llvm::Module* module) {
convertToKnowledge(logicalName, module, env->getEnvironment());
}
void Cortex::convertToKnowledge(llvm::StringRef logicalName,
llvm::Module* module, void* theEnv) {
CompilerRegistry* compilers = CompilerRegistry::getCompilerRegistry();
Compiler* target = compilers->getCompiler(logicalName);
if(!target) {
EnvPrintRouter(theEnv, (char*)"werror",
(char*)"\nProvided logical name does not exist\n");
return;
} else {
CLIPSEnvironment* tEnv = new CLIPSEnvironment(theEnv);
DATA_OBJECT rtn;
char* cmd = CharBuffer(512);
char* cmd2 = CharBuffer(512);
EnvFunctionCall(tEnv->getEnvironment(), "gensym*", NULL, &rtn);
std::string gensym(DOToString(rtn));
sprintf(cmd, "(defmodule module-%s (import core ?ALL) (import llvm ?ALL) (export ?ALL))", gensym.c_str());
sprintf(cmd2, "(set-current-module module-%s)", gensym.c_str());
tEnv->build(cmd);
tEnv->eval(cmd2);
free(cmd);
free(cmd2);
//we need to cheat a little bit and create the module here
KnowledgeConstructor tmp;
tmp.route(module);
tEnv->makeInstances((char*)tmp.getInstancesAsString().c_str());
llvm::PassManager tmpPassManager;
llvm::PassManagerBuilder builder;
//taken from opt
llvm::TargetLibraryInfo *tli =
new llvm::TargetLibraryInfo(llvm::Triple(module->getTargetTriple()));
tmpPassManager.add(tli);
llvm::TargetData *td = 0;
const std::string &moduleDataLayout = module->getDataLayout();
if(!moduleDataLayout.empty())
td = new llvm::TargetData(moduleDataLayout);
if(td)
tmpPassManager.add(td);
llvm::PassManager& PM = tmpPassManager;
//add em all!
builder.OptLevel = 2;
builder.DisableSimplifyLibCalls = false;
builder.populateModulePassManager(PM);
//let's see if this fixes the issue
llvm::PassRegistry* registry = llvm::PassRegistry::getPassRegistry();
const llvm::PassInfo* ci = registry->getPassInfo(
llvm::StringRef("function-to-knowledge"));
const llvm::PassInfo* ls = registry->getPassInfo(
llvm::StringRef("loop-simplify"));
const llvm::PassInfo* bce = registry->getPassInfo(
llvm::StringRef("break-crit-edges"));
ExpertSystem::FunctionKnowledgeConversionPass* copy =
(ExpertSystem::FunctionKnowledgeConversionPass*)ci->createPass();
copy->setEnvironment(tEnv);
tmpPassManager.add(ls->createPass());
tmpPassManager.add(bce->createPass());
tmpPassManager.add(copy);
tmpPassManager.add(llvm::createVerifierPass());
tmpPassManager.run(*module);
}
}
}
<commit_msg>Reformatted Cortex.cpp<commit_after>#include "rampancy/Cortex.h"
#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/CallGraphSCCPass.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/Assembly/PrintModulePass.h"
#include "llvm/Analysis/DebugInfo.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Analysis/LoopPass.h"
#include "llvm/Analysis/RegionPass.h"
#include "llvm/Analysis/CallGraph.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Target/TargetLibraryInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Support/PassNameParser.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/IRReader.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PluginLoader.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/SystemUtils.h"
#include "llvm/Support/ToolOutputFile.h"
#include "llvm/LinkAllPasses.h"
#include "llvm/LinkAllVMCore.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
#include <memory>
#include <algorithm>
#include "rampancy/Compiler.h"
#include "rampancy/CompilerManager.h"
#include "rampancy/CompilerRegistry.h"
#include "ExpertSystem/FunctionKnowledgeConversionPass.h"
extern "C" {
#include "clips.h"
}
namespace rampancy {
static llvm::ManagedStatic<Cortex> rampantCortexObject;
Cortex* Cortex::getRampantCortex() {
return &*rampantCortexObject;
}
Cortex::Cortex(void* theEnv) {
if(theEnv) {
env = new CLIPSEnvironment(theEnv);
} else {
env = new CLIPSEnvironment();
}
context = new llvm::LLVMContext();
manager = new CompilerManager();
manager->setContext(context);
manager->setEnvironment(env);
}
Cortex::~Cortex() {
delete manager;
delete context;
delete env;
}
llvm::LLVMContext* Cortex::getContext() {
return context;
}
void Cortex::setContext(llvm::LLVMContext* llvmContext) {
context = llvmContext;
manager->setContext(context);
}
CLIPSEnvironment* Cortex::getEnvironment() {
return env;
}
void Cortex::setEnvironment(CLIPSEnvironment* theEnv) {
env = theEnv;
manager->setEnvironment(env);
}
void Cortex::compileToKnowledge(void* theEnv) {
//we need to get the first argument from theEnv to find out where to
//route it to
DATA_OBJECT arg0;
char* copy;
copy = CharBuffer(512);
//change this so that only the first argument is handled by
//compileToKnowledge
if((EnvArgCountCheck(theEnv, (char*)"rampancy-compile", AT_LEAST, 1) == -1)) {
EnvPrintRouter(theEnv, (char*)"werror",
(char*)"\nCompile arguments are <compiler> ...\n"
"It is up to the compiler backend to handle the rest of the arguments\n");
return;
}
if((EnvArgTypeCheck(theEnv, (char*)"rampancy-compile", 1, SYMBOL, &arg0) == 0)) {
EnvPrintRouter(theEnv, (char*)"werror",
(char*)"\ncompiler name must be a symbol!\n");
return;
}
std::string tmp (DOToString(arg0));
//we need some indirection to prevent the CLIPS garbage collector from
//coming down like a fucking hammer on what we're doing here. Awesomely,
//this will all be cleaned up at the end of the function :D.
llvm::StringRef logicalName(tmp);
llvm::Module* module = compile(logicalName, theEnv);
if(!module) {
EnvPrintRouter(theEnv, (char*)"werror",
(char*)"\nThe compiler failed to compile the target file\n");
return;
}
convertToKnowledge(logicalName, module, theEnv);
}
void Cortex::interpretToKnowledge(void* theEnv) {
//we need to get the first argument from theEnv to find out where to
//route it to
DATA_OBJECT arg0;
char* copy;
copy = CharBuffer(512);
if((EnvArgCountCheck(theEnv, (char*)"rampancy-interpret", EXACTLY, 2) == -1)) {
EnvPrintRouter(theEnv, (char*)"werror",
(char*)"\nInterpret arguments are <compiler> <code>\n");
return;
}
if((EnvArgTypeCheck(theEnv, (char*)"rampancy-interpret", 1, SYMBOL, &arg0) == 0)) {
EnvPrintRouter(theEnv, (char*)"werror",
(char*)"\nCompiler name must be a symbol!\n");
return;
}
std::string tmp (DOToString(arg0));
//we need some indirection to prevent the CLIPS garbage collector from
//coming down like a fucking hammer on what we're doing here. Awesomely,
//this will all be cleaned up at the end of the function :D.
llvm::StringRef logicalName(tmp);
llvm::Module* module = interpret(logicalName, theEnv);
if(!module) {
EnvPrintRouter(theEnv, (char*)"werror",
(char*)"\nThe compiler failed to interpret the target file\n");
return;
}
convertToKnowledge(logicalName, module, theEnv);
}
llvm::Module* Cortex::compile(llvm::StringRef logicalName, void* theEnv) {
return manager->compile(logicalName, theEnv);
}
llvm::Module* Cortex::interpret(llvm::StringRef logicalName, void* theEnv) {
return manager->interpret(logicalName, theEnv);
}
llvm::Module* Cortex::compile(char* logicalName, int argc, char** argv) {
return manager->compile(logicalName, argc, argv);
}
llvm::Module* Cortex::compile(llvm::StringRef logicalName, int argc, char** argv) {
return manager->compile(logicalName, argc, argv);
}
llvm::Module* Cortex::interpret(llvm::StringRef logicalName,
llvm::StringRef input) {
return manager->interpret(logicalName, input);
}
llvm::Module* Cortex::interpret(char* logicalName, llvm::StringRef input) {
return manager->interpret(logicalName, input);
}
void Cortex::convertToKnowledge(llvm::StringRef logicalName,
llvm::Module* module) {
convertToKnowledge(logicalName, module, env->getEnvironment());
}
void Cortex::convertToKnowledge(llvm::StringRef logicalName,
llvm::Module* module, void* theEnv) {
CompilerRegistry* compilers = CompilerRegistry::getCompilerRegistry();
Compiler* target = compilers->getCompiler(logicalName);
if(!target) {
EnvPrintRouter(theEnv, (char*)"werror",
(char*)"\nProvided logical name does not exist\n");
return;
} else {
CLIPSEnvironment* tEnv = new CLIPSEnvironment(theEnv);
DATA_OBJECT rtn;
char* cmd = CharBuffer(512);
char* cmd2 = CharBuffer(512);
EnvFunctionCall(tEnv->getEnvironment(), "gensym*", NULL, &rtn);
std::string gensym(DOToString(rtn));
sprintf(cmd, "(defmodule module-%s (import core ?ALL) (import llvm ?ALL) (export ?ALL))", gensym.c_str());
sprintf(cmd2, "(set-current-module module-%s)", gensym.c_str());
tEnv->build(cmd);
tEnv->eval(cmd2);
free(cmd);
free(cmd2);
//we need to cheat a little bit and create the module here
KnowledgeConstructor tmp;
tmp.route(module);
tEnv->makeInstances((char*)tmp.getInstancesAsString().c_str());
llvm::PassManager tmpPassManager;
llvm::PassManagerBuilder builder;
//taken from opt
llvm::TargetLibraryInfo *tli =
new llvm::TargetLibraryInfo(llvm::Triple(module->getTargetTriple()));
tmpPassManager.add(tli);
llvm::TargetData *td = 0;
const std::string &moduleDataLayout = module->getDataLayout();
if(!moduleDataLayout.empty())
td = new llvm::TargetData(moduleDataLayout);
if(td)
tmpPassManager.add(td);
llvm::PassManager& PM = tmpPassManager;
//add em all!
builder.OptLevel = 2;
builder.DisableSimplifyLibCalls = false;
builder.populateModulePassManager(PM);
//let's see if this fixes the issue
llvm::PassRegistry* registry = llvm::PassRegistry::getPassRegistry();
const llvm::PassInfo* ci = registry->getPassInfo(
llvm::StringRef("function-to-knowledge"));
const llvm::PassInfo* ls = registry->getPassInfo(
llvm::StringRef("loop-simplify"));
const llvm::PassInfo* bce = registry->getPassInfo(
llvm::StringRef("break-crit-edges"));
ExpertSystem::FunctionKnowledgeConversionPass* copy =
(ExpertSystem::FunctionKnowledgeConversionPass*)ci->createPass();
copy->setEnvironment(tEnv);
tmpPassManager.add(ls->createPass());
tmpPassManager.add(bce->createPass());
tmpPassManager.add(copy);
tmpPassManager.add(llvm::createVerifierPass());
tmpPassManager.run(*module);
}
}
}
<|endoftext|> |
<commit_before>#include "Font.h"
#include <fstream>
#include <sstream>
using namespace std;
Font::Font()
{
m_pBitmap = nullptr;
}
Font::~Font()
{
if (m_pBitmap)
{
delete m_pBitmap;
m_pBitmap = nullptr;
}
}
bool Font::LoadFont(string fntFile, SDL_Renderer *renderer)
{
string line;
string read, key, value;
size_t i;
// Load the .fnt file
ifstream fnt(fntFile);
if (fnt.is_open())
{
// Parse the .fnt file
while(!fnt.eof())
{
stringstream lineStream;
getline(fnt, line);
lineStream << line;
// read the line's type
lineStream >> read;
if (read == "common")
{
while (!lineStream.eof())
{
stringstream converter;
lineStream >> read;
i = read.find('=');
key = read.substr(0, i);
value = read.substr(i+1);
// assign th correct value
converter << value;
if (key == "lineHeight")
converter >> m_Charset.lineHeight;
else if (key == "base")
converter >> m_Charset.base;
else if (key == "scaleW")
converter >> m_Charset.width;
else if (key == "scaleH")
converter >> m_Charset.height;
else if (key == "pages")
converter >> m_Charset.pages;
}
}
// Use this to load the proper font image
else if (read == "page")
{
string filename;
while (!lineStream.eof())
{
stringstream converter;
lineStream >> read;
i = read.find('=');
key = read.substr(0, i);
value = read.substr(i+1);
// assign th correct value
converter << value;
if (key == "file")
{
converter >> filename;
// Remove quotation marks around filename
filename = filename.substr(1, filename.size()-2);
filename = "data/fonts/" + filename; // TODO: remove hard coded value
}
}
if (!filename.empty())
{
m_pBitmap = new Texture;
if (!m_pBitmap->LoadFile(filename, renderer))
return false;
}
}
else if (read == "char")
{
unsigned short charID = 0;
while (!lineStream.eof())
{
stringstream converter;
lineStream >> read;
i = read.find('=');
key = read.substr(0, i);
value = read.substr(i + 1);
// assign the correct value
converter << value;
if (key == "id")
converter >> charID;
else if (key == "x")
converter >> m_Charset.chars[charID].x;
else if (key == "y")
converter >> m_Charset.chars[charID].y;
else if (key == "width")
converter >> m_Charset.chars[charID].width;
else if (key == "height")
converter >> m_Charset.chars[charID].height;
else if (key == "xoffset"){
converter >> m_Charset.chars[charID].xOffset;
if (m_Charset.chars[charID].xOffset == 65535)
std::cout << charID << std::endl;
}
else if (key == "yoffset")
converter >> m_Charset.chars[charID].yOffset;
else if (key == "xadvance")
converter >> m_Charset.chars[charID].xAdvance;
else if (key == "page")
converter >> m_Charset.chars[charID].page;
}
}
}
fnt.close();
return true;
}
else
return false;
}
void Font::Render(int x, int y, string text)
{
if (m_pBitmap)
{
SDL_Rect src;
int cursorX = x;
for (unsigned int i = 0; i < text.size(); i++)
{
int cursorY = y;
src.x = m_Charset.chars[text[i]].x;
src.y = m_Charset.chars[text[i]].y;
src.w = m_Charset.chars[text[i]].width;
src.h = m_Charset.chars[text[i]].height;
cursorX += m_Charset.chars[text[i]].xOffset;
cursorY += m_Charset.chars[text[i]].yOffset;
m_pBitmap->Render(cursorX, cursorY, &src);
cursorX += m_Charset.chars[text[i]].xAdvance;
}
}
}
void Font::Render(int x, int y, unsigned short c)
{
if (m_pBitmap)
{
SDL_Rect src;
int cursorX = x;
int cursorY = y;
src.x = m_Charset.chars[c].x;
src.y = m_Charset.chars[c].y;
src.w = m_Charset.chars[c].width;
src.h = m_Charset.chars[c].height;
cursorX += m_Charset.chars[c].xOffset;
cursorY += m_Charset.chars[c].yOffset;
m_pBitmap->Render(cursorX, cursorY, &src);
}
}<commit_msg>Update Font.cpp<commit_after>#include "Font.h"
#include <fstream>
#include <sstream>
using namespace std;
Font::Font()
{
m_pBitmap = nullptr;
}
Font::~Font()
{
if (m_pBitmap)
{
delete m_pBitmap;
m_pBitmap = nullptr;
}
}
bool Font::LoadFont(string fntFile, SDL_Renderer *renderer)
{
string line;
string read, key, value;
size_t i;
// Load the .fnt file
ifstream fnt(fntFile);
if (fnt.is_open())
{
// Parse the .fnt file
while(!fnt.eof())
{
stringstream lineStream;
getline(fnt, line);
lineStream << line;
// read the line's type
lineStream >> read;
if (read == "common")
{
while (!lineStream.eof())
{
stringstream converter;
lineStream >> read;
i = read.find('=');
key = read.substr(0, i);
value = read.substr(i+1);
// assign th correct value
converter << value;
if (key == "lineHeight")
converter >> m_Charset.lineHeight;
else if (key == "base")
converter >> m_Charset.base;
else if (key == "scaleW")
converter >> m_Charset.width;
else if (key == "scaleH")
converter >> m_Charset.height;
else if (key == "pages")
converter >> m_Charset.pages;
}
}
// Use this to load the proper font image
else if (read == "page")
{
string filename;
while (!lineStream.eof())
{
stringstream converter;
lineStream >> read;
i = read.find('=');
key = read.substr(0, i);
value = read.substr(i+1);
// assign th correct value
converter << value;
if (key == "file")
{
converter >> filename;
// Remove quotation marks around filename
filename = filename.substr(1, filename.size()-2);
filename = "data/fonts/" + filename; // TODO: remove hard coded value
}
}
if (!filename.empty())
{
m_pBitmap = new Texture;
if (!m_pBitmap->LoadFile(filename, renderer))
return false;
}
}
else if (read == "char")
{
unsigned short charID = 0;
while (!lineStream.eof())
{
stringstream converter;
lineStream >> read;
i = read.find('=');
key = read.substr(0, i);
value = read.substr(i + 1);
// assign the correct value
converter << value;
if (key == "id")
converter >> charID;
else if (key == "x")
converter >> m_Charset.chars[charID].x;
else if (key == "y")
converter >> m_Charset.chars[charID].y;
else if (key == "width")
converter >> m_Charset.chars[charID].width;
else if (key == "height")
converter >> m_Charset.chars[charID].height;
else if (key == "xoffset")
converter >> m_Charset.chars[charID].xOffset;
else if (key == "yoffset")
converter >> m_Charset.chars[charID].yOffset;
else if (key == "xadvance")
converter >> m_Charset.chars[charID].xAdvance;
else if (key == "page")
converter >> m_Charset.chars[charID].page;
}
}
}
fnt.close();
return true;
}
else
return false;
}
void Font::Render(int x, int y, string text)
{
if (m_pBitmap)
{
SDL_Rect src;
int cursorX = x;
for (unsigned int i = 0; i < text.size(); i++)
{
int cursorY = y;
src.x = m_Charset.chars[text[i]].x;
src.y = m_Charset.chars[text[i]].y;
src.w = m_Charset.chars[text[i]].width;
src.h = m_Charset.chars[text[i]].height;
cursorX += m_Charset.chars[text[i]].xOffset;
cursorY += m_Charset.chars[text[i]].yOffset;
m_pBitmap->Render(cursorX, cursorY, &src);
cursorX += m_Charset.chars[text[i]].xAdvance;
}
}
}
void Font::Render(int x, int y, unsigned short c)
{
if (m_pBitmap)
{
SDL_Rect src;
int cursorX = x;
int cursorY = y;
src.x = m_Charset.chars[c].x;
src.y = m_Charset.chars[c].y;
src.w = m_Charset.chars[c].width;
src.h = m_Charset.chars[c].height;
cursorX += m_Charset.chars[c].xOffset;
cursorY += m_Charset.chars[c].yOffset;
m_pBitmap->Render(cursorX, cursorY, &src);
}
}
<|endoftext|> |
<commit_before>#include "MeshManager.h"
MeshManager::MeshManager() :
m_pGraphicsManager(nullptr),
m_pTextureManager(nullptr),
m_pMaterialManager(nullptr),
m_pMemory(nullptr),
m_pUniformBuffer(nullptr),
m_pDescriptorSet(nullptr),
m_InuseDynamicOffsetCount(0)
{
}
MeshManager::~MeshManager()
{
}
V3D_RESULT MeshManager::Initialize(GraphicsManager* pGraphicsManager, TextureManager* pTextureManager, MaterialManager* pMaterialManager, uint32_t maxMesh)
{
m_pGraphicsManager = pGraphicsManager;
m_pTextureManager = pTextureManager;
m_pMaterialManager = pMaterialManager;
m_MaxMesh = maxMesh;
m_UnuseUniformDynamicOffsets.reserve(maxMesh);
// ----------------------------------------------------------------------------------------------------
// jtH[obt@쐬
// ----------------------------------------------------------------------------------------------------
BufferSubresourceDesc uniformBufferSubresource;
uniformBufferSubresource.usageFlags = V3D_BUFFER_USAGE_UNIFORM;
uniformBufferSubresource.size = sizeof(Mesh::Uniform);
uniformBufferSubresource.count = maxMesh;
BufferMemoryLayout uniformBufferMemoryLayout;
uint64_t uniformBufferMemorySize;
CalcBufferMemoryLayout(pGraphicsManager->GetDevicePtr(), V3D_MEMORY_PROPERTY_HOST_VISIBLE, 1, &uniformBufferSubresource, &uniformBufferMemoryLayout, &uniformBufferMemorySize);
V3DBufferDesc uniformBufferDesc{};
uniformBufferDesc.usageFlags = V3D_BUFFER_USAGE_UNIFORM;
uniformBufferDesc.size = uniformBufferMemorySize;
V3D_RESULT result = m_pGraphicsManager->GetDevicePtr()->CreateBuffer(uniformBufferDesc, &m_pUniformBuffer);
if (result != V3D_OK)
{
return result;
}
result = m_pGraphicsManager->GetDevicePtr()->AllocateResourceMemoryAndBind(V3D_MEMORY_PROPERTY_HOST_VISIBLE, m_pUniformBuffer);
if (result != V3D_OK)
{
return result;
}
m_pUniformBuffer->GetResourceMemory(&m_pMemory);
m_UniformStride = TO_UI32(uniformBufferMemoryLayout.stride);
// ----------------------------------------------------------------------------------------------------
// fXNv^Zbg쐬
// ----------------------------------------------------------------------------------------------------
result = pGraphicsManager->CreateDescriptorSet(GRAPHICS_RENDERPASS_TYPE_DFFERED_GEOMETRY, GRAPHICS_PIPELINE_TYPE_GEOMETRY, GRAPHICS_DESCRIPTOR_SET_TYPE_MESH, &m_pDescriptorSet);
if (result != V3D_OK)
{
return result;
}
result = m_pDescriptorSet->SetBuffer(0, m_pUniformBuffer, 0, sizeof(Mesh::Uniform));
if (result != V3D_OK)
{
return result;
}
m_pDescriptorSet->Update();
return V3D_OK;
}
void MeshManager::Finalize()
{
if (m_MeshMap.empty() == false)
{
MeshManager::MeshMap::iterator it_begin = m_MeshMap.begin();
MeshManager::MeshMap::iterator it_end = m_MeshMap.end();
MeshManager::MeshMap::iterator it;
for (it = it_begin; it != it_end; ++it)
{
it->second->Dispose();
}
m_MeshMap.clear();
}
SAFE_RELEASE(m_pDescriptorSet);
SAFE_RELEASE(m_pUniformBuffer);
SAFE_RELEASE(m_pMemory);
m_pGraphicsManager = nullptr;
m_pTextureManager = nullptr;
m_pMaterialManager = nullptr;
}
V3D_RESULT MeshManager::BeginUpdate()
{
return m_pMemory->BeginMap();
}
V3D_RESULT MeshManager::EndUpdate()
{
return m_pMemory->EndMap();
}
MeshPtr MeshManager::Load(const wchar_t* pFilePath, const Mesh::LoadDesc& loadDesc)
{
std::shared_ptr<Mesh> mesh = std::make_shared<Mesh>();
MeshManager::MeshMap::iterator it_mesh = m_MeshMap.find(pFilePath);
if (it_mesh != m_MeshMap.end())
{
return it_mesh->second;
}
V3D_RESULT result = mesh->Initialize(m_pGraphicsManager, m_pTextureManager, m_pMaterialManager, this);
if (result != V3D_OK)
{
return nullptr;
}
result = mesh->LoadFromFile(pFilePath, loadDesc);
if (result != V3D_OK)
{
return nullptr;
}
m_NamingService.Add(pFilePath, mesh->m_Name);
m_MeshMap[pFilePath] = mesh;
return std::move(mesh);
}
void MeshManager::GetDescriptorSet(IV3DDescriptorSet** ppDescriptorSet)
{
SAFE_ADD_REF(m_pDescriptorSet);
*ppDescriptorSet = m_pDescriptorSet;
}
void MeshManager::RetainUniformDynamicOffset(uint32_t* pDynamicOffset)
{
if (m_UnuseUniformDynamicOffsets.empty() == false)
{
*pDynamicOffset = m_UnuseUniformDynamicOffsets.back();
m_UnuseUniformDynamicOffsets.pop_back();
}
else
{
*pDynamicOffset = m_InuseDynamicOffsetCount * m_UniformStride;
m_InuseDynamicOffsetCount++;
}
}
void MeshManager::ReleaseUniformDynamicOffset(uint32_t dynamicOffset)
{
ASSERT(m_InuseDynamicOffsetCount > 0);
m_UnuseUniformDynamicOffsets.push_back(dynamicOffset);
m_InuseDynamicOffsetCount--;
}
void MeshManager::Add(const wchar_t* pName, MeshPtr mesh)
{
m_NamingService.Add(pName, mesh->m_Name);
ASSERT(m_MeshMap.find(mesh->m_Name) == m_MeshMap.end());
m_MeshMap[mesh->m_Name] = mesh;
}
<commit_msg>リソースのメモリプロパティのチェックをするようにした<commit_after>#include "MeshManager.h"
MeshManager::MeshManager() :
m_pGraphicsManager(nullptr),
m_pTextureManager(nullptr),
m_pMaterialManager(nullptr),
m_pMemory(nullptr),
m_pUniformBuffer(nullptr),
m_pDescriptorSet(nullptr),
m_InuseDynamicOffsetCount(0)
{
}
MeshManager::~MeshManager()
{
}
V3D_RESULT MeshManager::Initialize(GraphicsManager* pGraphicsManager, TextureManager* pTextureManager, MaterialManager* pMaterialManager, uint32_t maxMesh)
{
m_pGraphicsManager = pGraphicsManager;
m_pTextureManager = pTextureManager;
m_pMaterialManager = pMaterialManager;
m_MaxMesh = maxMesh;
m_UnuseUniformDynamicOffsets.reserve(maxMesh);
// ----------------------------------------------------------------------------------------------------
// jtH[obt@쐬
// ----------------------------------------------------------------------------------------------------
BufferSubresourceDesc uniformBufferSubresource;
uniformBufferSubresource.usageFlags = V3D_BUFFER_USAGE_UNIFORM;
uniformBufferSubresource.size = sizeof(Mesh::Uniform);
uniformBufferSubresource.count = maxMesh;
BufferMemoryLayout uniformBufferMemoryLayout;
uint64_t uniformBufferMemorySize;
CalcBufferMemoryLayout(pGraphicsManager->GetDevicePtr(), V3D_MEMORY_PROPERTY_HOST_VISIBLE, 1, &uniformBufferSubresource, &uniformBufferMemoryLayout, &uniformBufferMemorySize);
V3DBufferDesc uniformBufferDesc{};
uniformBufferDesc.usageFlags = V3D_BUFFER_USAGE_UNIFORM;
uniformBufferDesc.size = uniformBufferMemorySize;
V3D_RESULT result = m_pGraphicsManager->GetDevicePtr()->CreateBuffer(uniformBufferDesc, &m_pUniformBuffer);
if (result != V3D_OK)
{
return result;
}
V3DFlags memoryPropertyFlags = V3D_MEMORY_PROPERTY_HOST_VISIBLE | V3D_MEMORY_PROPERTY_HOST_COHERENT;
result = m_pGraphicsManager->GetDevicePtr()->CheckResourceMemoryProperty(memoryPropertyFlags, m_pUniformBuffer);
if (result != V3D_OK)
{
memoryPropertyFlags = V3D_MEMORY_PROPERTY_HOST_VISIBLE;
}
result = m_pGraphicsManager->GetDevicePtr()->AllocateResourceMemoryAndBind(memoryPropertyFlags, m_pUniformBuffer);
if (result != V3D_OK)
{
return result;
}
m_pUniformBuffer->GetResourceMemory(&m_pMemory);
m_UniformStride = TO_UI32(uniformBufferMemoryLayout.stride);
// ----------------------------------------------------------------------------------------------------
// fXNv^Zbg쐬
// ----------------------------------------------------------------------------------------------------
result = pGraphicsManager->CreateDescriptorSet(GRAPHICS_RENDERPASS_TYPE_DFFERED_GEOMETRY, GRAPHICS_PIPELINE_TYPE_GEOMETRY, GRAPHICS_DESCRIPTOR_SET_TYPE_MESH, &m_pDescriptorSet);
if (result != V3D_OK)
{
return result;
}
result = m_pDescriptorSet->SetBuffer(0, m_pUniformBuffer, 0, sizeof(Mesh::Uniform));
if (result != V3D_OK)
{
return result;
}
m_pDescriptorSet->Update();
return V3D_OK;
}
void MeshManager::Finalize()
{
if (m_MeshMap.empty() == false)
{
MeshManager::MeshMap::iterator it_begin = m_MeshMap.begin();
MeshManager::MeshMap::iterator it_end = m_MeshMap.end();
MeshManager::MeshMap::iterator it;
for (it = it_begin; it != it_end; ++it)
{
it->second->Dispose();
}
m_MeshMap.clear();
}
SAFE_RELEASE(m_pDescriptorSet);
SAFE_RELEASE(m_pUniformBuffer);
SAFE_RELEASE(m_pMemory);
m_pGraphicsManager = nullptr;
m_pTextureManager = nullptr;
m_pMaterialManager = nullptr;
}
V3D_RESULT MeshManager::BeginUpdate()
{
return m_pMemory->BeginMap();
}
V3D_RESULT MeshManager::EndUpdate()
{
return m_pMemory->EndMap();
}
MeshPtr MeshManager::Load(const wchar_t* pFilePath, const Mesh::LoadDesc& loadDesc)
{
std::shared_ptr<Mesh> mesh = std::make_shared<Mesh>();
MeshManager::MeshMap::iterator it_mesh = m_MeshMap.find(pFilePath);
if (it_mesh != m_MeshMap.end())
{
return it_mesh->second;
}
V3D_RESULT result = mesh->Initialize(m_pGraphicsManager, m_pTextureManager, m_pMaterialManager, this);
if (result != V3D_OK)
{
return nullptr;
}
result = mesh->LoadFromFile(pFilePath, loadDesc);
if (result != V3D_OK)
{
return nullptr;
}
m_NamingService.Add(pFilePath, mesh->m_Name);
m_MeshMap[pFilePath] = mesh;
return std::move(mesh);
}
void MeshManager::GetDescriptorSet(IV3DDescriptorSet** ppDescriptorSet)
{
SAFE_ADD_REF(m_pDescriptorSet);
*ppDescriptorSet = m_pDescriptorSet;
}
void MeshManager::RetainUniformDynamicOffset(uint32_t* pDynamicOffset)
{
if (m_UnuseUniformDynamicOffsets.empty() == false)
{
*pDynamicOffset = m_UnuseUniformDynamicOffsets.back();
m_UnuseUniformDynamicOffsets.pop_back();
}
else
{
*pDynamicOffset = m_InuseDynamicOffsetCount * m_UniformStride;
m_InuseDynamicOffsetCount++;
}
}
void MeshManager::ReleaseUniformDynamicOffset(uint32_t dynamicOffset)
{
ASSERT(m_InuseDynamicOffsetCount > 0);
m_UnuseUniformDynamicOffsets.push_back(dynamicOffset);
m_InuseDynamicOffsetCount--;
}
void MeshManager::Add(const wchar_t* pName, MeshPtr mesh)
{
m_NamingService.Add(pName, mesh->m_Name);
ASSERT(m_MeshMap.find(mesh->m_Name) == m_MeshMap.end());
m_MeshMap[mesh->m_Name] = mesh;
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2012 - 2014 Jolla Ltd.
** Contact: http://jolla.com/
**
** This file is part of Qt Creator.
**
** 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.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Digia.
**
****************************************************************************/
#include "mertarget.h"
#include "merconstants.h"
#include "merqtversion.h"
#include "mersdk.h"
#include "mersdkkitinformation.h"
#include "mersdkmanager.h"
#include "mertargetkitinformation.h"
#include "mertoolchain.h"
#include <debugger/debuggeritemmanager.h>
#include <debugger/debuggerkitinformation.h>
#include <projectexplorer/toolchainmanager.h>
#include <qtsupport/qtkitinformation.h>
#include <qtsupport/qtversionfactory.h>
#include <qtsupport/qtversionmanager.h>
#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
#include <QDir>
#include <QStringList>
namespace Mer {
namespace Internal {
using namespace Mer::Constants;
const char* wrapperScripts[] =
{
MER_WRAPPER_QMAKE,
MER_WRAPPER_MAKE,
MER_WRAPPER_GCC,
MER_WRAPPER_DEPLOY,
MER_WRAPPER_RPM,
MER_WRAPPER_RPMBUILD,
MER_WRAPPER_RPMVALIDATION,
};
MerTarget::MerTarget(MerSdk* mersdk):
m_sdk(mersdk),
m_defaultGdb(QLatin1String(Constants::MER_DEBUGGER_DEFAULT_FILENAME))
{
}
MerTarget::~MerTarget()
{
}
QString MerTarget::name() const
{
return m_name;
}
void MerTarget::setName(const QString &name)
{
m_name = name;
}
void MerTarget::setQmakeQuery(const QString &qmakeQuery)
{
m_qmakeQuery = qmakeQuery;
}
void MerTarget::setGccDumpMachine(const QString &gccMachineDump)
{
m_gccMachineDump = gccMachineDump;
// the dump contains a linefeed
m_gccMachineDump.remove(QRegExp(QLatin1String("\\n")));
}
void MerTarget::setDefaultGdb(const QString &name)
{
m_defaultGdb=name;
}
bool MerTarget::fromMap(const QVariantMap &data)
{
m_name = data.value(QLatin1String(Constants::MER_TARGET_NAME)).toString();
m_qmakeQuery = data.value(QLatin1String(Constants::MER_TARGET_QMAKE_DUMP)).toString();
m_gccMachineDump = data.value(QLatin1String(Constants::MER_TARGET_GCC_DUMP)).toString();
m_defaultGdb = data.value(QLatin1String(Constants::MER_TARGET_DEFAULT_DEBUGGER)).toString();
return isValid();
}
QVariantMap MerTarget::toMap() const
{
QVariantMap result;
result.insert(QLatin1String(Constants::MER_TARGET_NAME), m_name);
result.insert(QLatin1String(Constants::MER_TARGET_QMAKE_DUMP), m_qmakeQuery);
result.insert(QLatin1String(Constants::MER_TARGET_GCC_DUMP), m_gccMachineDump);
result.insert(QLatin1String(Constants::MER_TARGET_DEFAULT_DEBUGGER), m_defaultGdb);
return result;
}
bool MerTarget::isValid() const
{
return !m_name.isEmpty() && !m_qmakeQuery.isEmpty() && !m_gccMachineDump.isEmpty();
}
QString MerTarget::targetPath() const
{
return MerSdkManager::sdkToolsDirectory() + m_sdk->virtualMachineName() + QLatin1Char('/') + m_name;
}
bool MerTarget::createScripts() const
{
if (!isValid())
return false;
const QString targetPath(this->targetPath());
QDir targetDir(targetPath);
if (!targetDir.exists() && !targetDir.mkpath(targetPath)) {
qWarning() << "Could not create target directory." << targetDir;
return false;
}
bool result = true;
for (size_t i = 0; i < sizeof(wrapperScripts) / sizeof(wrapperScripts[0]); ++i)
result &= createScript(targetPath, i);
const QString qmakepath = targetPath + QLatin1Char('/') + QLatin1String(Constants::QMAKE_QUERY);
const QString gccpath = targetPath + QLatin1Char('/') + QLatin1String(Constants::GCC_DUMPMACHINE);
QString patchedQmakeQuery = m_qmakeQuery;
patchedQmakeQuery.replace(QLatin1String(":/"),
QString::fromLatin1(":%1/%2/").arg(m_sdk->sharedTargetsPath()).arg(m_name));
result &= createCacheFile(qmakepath, patchedQmakeQuery);
result &= createCacheFile(gccpath, m_gccMachineDump);
return result;
}
void MerTarget::deleteScripts() const
{
Utils::FileUtils::removeRecursively(Utils::FileName::fromString(targetPath()));
}
ProjectExplorer::Kit* MerTarget::createKit() const
{
if (!isValid())
return 0;
const QString sysroot(m_sdk->sharedTargetsPath() + QLatin1String("/") + m_name);
Utils::FileName path = Utils::FileName::fromString(sysroot);
if (!path.toFileInfo().exists()) {
qWarning() << "Sysroot does not exist" << sysroot;
return 0;
}
ProjectExplorer::Kit *k = new ProjectExplorer::Kit();
k->setAutoDetected(true);
k->setUnexpandedDisplayName(QString::fromLatin1("%1-%2").arg(m_sdk->virtualMachineName(), m_name));
k->setIconPath(Utils::FileName::fromString(QLatin1String(Constants::MER_OPTIONS_CATEGORY_ICON)));
ProjectExplorer::SysRootKitInformation::setSysRoot(k, Utils::FileName::fromUserInput(sysroot));
ProjectExplorer::DeviceTypeKitInformation::setDeviceTypeId(k, Constants::MER_DEVICE_TYPE);
k->setMutable(ProjectExplorer::DeviceKitInformation::id(), true);
const QString gdb = Utils::HostOsInfo::withExecutableSuffix(m_defaultGdb);
QString gdbDir = QCoreApplication::applicationDirPath();
if (Utils::HostOsInfo::isMacHost()) {
QDir dir = QDir(gdbDir);
dir.cdUp();
dir.cdUp();
dir.cdUp();
gdbDir = dir.path();
}
Utils::FileName gdbFileName = Utils::FileName::fromString(gdbDir + QLatin1String("/") + gdb);
Debugger::DebuggerItem debugger;
debugger.setCommand(gdbFileName);
debugger.setEngineType(Debugger::GdbEngineType);
const QString vmName = m_sdk->virtualMachineName();
debugger.setUnexpandedDisplayName(QObject::tr("GDB for %1 %2").arg(vmName, m_name));
debugger.setAutoDetected(true);
debugger.setAbi(ProjectExplorer::Abi::abiFromTargetTriplet(m_gccMachineDump)); // TODO is this OK?
QVariant id = Debugger::DebuggerItemManager::registerDebugger(debugger);
Debugger::DebuggerKitInformation::setDebugger(k, id);
MerSdkKitInformation::setSdk(k,m_sdk);
MerTargetKitInformation::setTargetName(k,name());
return k;
}
MerQtVersion* MerTarget::createQtVersion() const
{
const Utils::FileName qmake =
Utils::FileName::fromString(targetPath() + QLatin1Char('/') +
QLatin1String(Constants::MER_WRAPPER_QMAKE));
// Is there a qtversion present for this qmake?
QtSupport::BaseQtVersion *qtv = QtSupport::QtVersionManager::qtVersionForQMakeBinary(qmake);
if (qtv && !qtv->isValid()) {
QtSupport::QtVersionManager::removeVersion(qtv);
qtv = 0;
}
if (!qtv)
qtv = new MerQtVersion(qmake, true, targetPath());
//QtSupport::QtVersionFactory::createQtVersionFromQMakePath(qmake, true, targetPath());
QTC_ASSERT(qtv && qtv->type() == QLatin1String(Constants::MER_QT), return 0);
MerQtVersion *merqtv = static_cast<MerQtVersion *>(qtv);
const QString vmName = m_sdk->virtualMachineName();
merqtv->setVirtualMachineName(vmName);
merqtv->setTargetName(m_name);
merqtv->setUnexpandedDisplayName(
QString::fromLatin1("Qt %1 in %2 %3").arg(qtv->qtVersionString(),
vmName, m_name));
return merqtv;
}
MerToolChain* MerTarget::createToolChain() const
{
const Utils::FileName gcc =
Utils::FileName::fromString(targetPath() + QLatin1Char('/') +
QLatin1String(Constants::MER_WRAPPER_GCC));
QList<ProjectExplorer::ToolChain *> toolChains = ProjectExplorer::ToolChainManager::toolChains();
foreach (ProjectExplorer::ToolChain *tc, toolChains) {
if (tc->compilerCommand() == gcc && tc->isAutoDetected()) {
QTC_ASSERT(tc->type() == QLatin1String(Constants::MER_TOOLCHAIN_TYPE), return 0);
}
}
MerToolChain* mertoolchain = new MerToolChain(ProjectExplorer::ToolChain::AutoDetection);
const QString vmName = m_sdk->virtualMachineName();
mertoolchain->setDisplayName(QString::fromLatin1("GCC (%1 %2)").arg(vmName, m_name));
mertoolchain->setVirtualMachine(vmName);
mertoolchain->setTargetName(m_name);
mertoolchain->setCompilerCommand(gcc);
return mertoolchain;
}
bool MerTarget::createScript(const QString &targetPath, int scriptIndex) const
{
bool ok = false;
const char* wrapperScriptCopy = wrapperScripts[scriptIndex];
const QFile::Permissions rwrw = QFile::ReadOwner|QFile::ReadUser|QFile::ReadGroup
|QFile::WriteOwner|QFile::WriteUser|QFile::WriteGroup;
const QFile::Permissions rwxrwx = rwrw|QFile::ExeOwner|QFile::ExeUser|QFile::ExeGroup;
QString wrapperScriptCommand = QLatin1String(wrapperScriptCopy);
if (Utils::HostOsInfo::isWindowsHost())
wrapperScriptCommand.chop(4); // remove the ".cmd"
QString wrapperBinaryPath = QCoreApplication::applicationDirPath();
if (Utils::HostOsInfo::isWindowsHost())
wrapperBinaryPath += QLatin1String("/merssh.exe");
else if (Utils::HostOsInfo::isMacHost())
wrapperBinaryPath += QLatin1String("/../Resources/merssh");
else
wrapperBinaryPath += QLatin1String("/merssh");
using namespace Utils;
const QString scriptCopyPath = targetPath + QLatin1Char('/') + QLatin1String(wrapperScriptCopy);
QDir targetDir(targetPath);
const QString targetName = targetDir.dirName();
targetDir.cdUp();
const QString merDevToolsDir = QDir::toNativeSeparators(targetDir.canonicalPath());
QFile script(scriptCopyPath);
ok = script.open(QIODevice::WriteOnly);
if (!ok) {
qWarning() << "Could not open script" << scriptCopyPath;
return false;
}
QString scriptContent;
if (HostOsInfo::isWindowsHost()) {
scriptContent += QLatin1String("@echo off\nSetLocal EnableDelayedExpansion\n");
scriptContent += QLatin1String("set ARGUMENTS=\nFOR %%a IN (%*) DO set ARGUMENTS=!ARGUMENTS! ^ '%%a'\n");
scriptContent += QLatin1String("set ") +
QLatin1String(Mer::Constants::MER_SSH_TARGET_NAME) +
QLatin1Char('=') + targetName + QLatin1Char('\n');
scriptContent += QLatin1String("set ") +
QLatin1String(Mer::Constants::MER_SSH_SDK_TOOLS) +
QLatin1Char('=') + merDevToolsDir + QDir::separator() + targetName + QLatin1Char('\n');
scriptContent += QLatin1String("SetLocal DisableDelayedExpansion\n");
scriptContent += QLatin1Char('"') +
QDir::toNativeSeparators(wrapperBinaryPath) + QLatin1String("\" ") +
wrapperScriptCommand + QLatin1Char(' ') + QLatin1String("%ARGUMENTS%\n");
}
if (HostOsInfo::isAnyUnixHost()) {
scriptContent += QLatin1String("#!/bin/sh\n");
scriptContent += QLatin1String("ARGUMENTS=\"\";for ARGUMENT in \"$@\"; do ARGUMENTS=\"${ARGUMENTS} '${ARGUMENT}'\" ; done;\n");
scriptContent += QLatin1String("export ") +
QLatin1String(Mer::Constants::MER_SSH_TARGET_NAME) +
QLatin1Char('=') + targetName + QLatin1Char('\n');
scriptContent += QLatin1String("export ") +
QLatin1String(Mer::Constants::MER_SSH_SDK_TOOLS) +
QLatin1Char('=') + merDevToolsDir + QDir::separator() + targetName + QLatin1Char('\n');
scriptContent += QLatin1String("exec ");
scriptContent += QLatin1Char('"') +
QDir::toNativeSeparators(wrapperBinaryPath) + QLatin1String("\" ") +
wrapperScriptCommand + QLatin1Char(' ') + QLatin1String("${ARGUMENTS}");
}
ok = script.write(scriptContent.toUtf8()) != -1;
if (!ok) {
qWarning() << "Could not write script" << scriptCopyPath;
return false;
}
ok = QFile::setPermissions(scriptCopyPath, rwxrwx);
if (!ok) {
qWarning() << "Could not set file permissions on script" << scriptCopyPath;
return false;
}
return ok;
}
bool MerTarget::createCacheFile(const QString &fileName, const QString &content) const
{
bool ok = false;
QFile file(fileName);
ok = file.open(QIODevice::WriteOnly);
if (!ok) {
qWarning() << "Could not open cache file" << fileName;
return false;
}
ok = file.write(content.toUtf8()) != -1;
if (!ok) {
qWarning() << "Could not write cache file " << fileName;
return false;
}
file.close();
return ok;
}
bool MerTarget::operator==(const MerTarget &other) const
{
return m_name == other.m_name && m_qmakeQuery == other.m_qmakeQuery && m_gccMachineDump == other.m_gccMachineDump;
}
}
}
<commit_msg>Mer: Update after Clean exported headers of the Debugger plugin.<commit_after>/****************************************************************************
**
** Copyright (C) 2012 - 2014 Jolla Ltd.
** Contact: http://jolla.com/
**
** This file is part of Qt Creator.
**
** 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.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Digia.
**
****************************************************************************/
#include "mertarget.h"
#include "merconstants.h"
#include "merqtversion.h"
#include "mersdk.h"
#include "mersdkkitinformation.h"
#include "mersdkmanager.h"
#include "mertargetkitinformation.h"
#include "mertoolchain.h"
#include <debugger/debuggeritem.h>
#include <debugger/debuggeritemmanager.h>
#include <debugger/debuggerkitinformation.h>
#include <projectexplorer/toolchainmanager.h>
#include <qtsupport/qtkitinformation.h>
#include <qtsupport/qtversionfactory.h>
#include <qtsupport/qtversionmanager.h>
#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
#include <QDir>
#include <QStringList>
namespace Mer {
namespace Internal {
using namespace Mer::Constants;
const char* wrapperScripts[] =
{
MER_WRAPPER_QMAKE,
MER_WRAPPER_MAKE,
MER_WRAPPER_GCC,
MER_WRAPPER_DEPLOY,
MER_WRAPPER_RPM,
MER_WRAPPER_RPMBUILD,
MER_WRAPPER_RPMVALIDATION,
};
MerTarget::MerTarget(MerSdk* mersdk):
m_sdk(mersdk),
m_defaultGdb(QLatin1String(Constants::MER_DEBUGGER_DEFAULT_FILENAME))
{
}
MerTarget::~MerTarget()
{
}
QString MerTarget::name() const
{
return m_name;
}
void MerTarget::setName(const QString &name)
{
m_name = name;
}
void MerTarget::setQmakeQuery(const QString &qmakeQuery)
{
m_qmakeQuery = qmakeQuery;
}
void MerTarget::setGccDumpMachine(const QString &gccMachineDump)
{
m_gccMachineDump = gccMachineDump;
// the dump contains a linefeed
m_gccMachineDump.remove(QRegExp(QLatin1String("\\n")));
}
void MerTarget::setDefaultGdb(const QString &name)
{
m_defaultGdb=name;
}
bool MerTarget::fromMap(const QVariantMap &data)
{
m_name = data.value(QLatin1String(Constants::MER_TARGET_NAME)).toString();
m_qmakeQuery = data.value(QLatin1String(Constants::MER_TARGET_QMAKE_DUMP)).toString();
m_gccMachineDump = data.value(QLatin1String(Constants::MER_TARGET_GCC_DUMP)).toString();
m_defaultGdb = data.value(QLatin1String(Constants::MER_TARGET_DEFAULT_DEBUGGER)).toString();
return isValid();
}
QVariantMap MerTarget::toMap() const
{
QVariantMap result;
result.insert(QLatin1String(Constants::MER_TARGET_NAME), m_name);
result.insert(QLatin1String(Constants::MER_TARGET_QMAKE_DUMP), m_qmakeQuery);
result.insert(QLatin1String(Constants::MER_TARGET_GCC_DUMP), m_gccMachineDump);
result.insert(QLatin1String(Constants::MER_TARGET_DEFAULT_DEBUGGER), m_defaultGdb);
return result;
}
bool MerTarget::isValid() const
{
return !m_name.isEmpty() && !m_qmakeQuery.isEmpty() && !m_gccMachineDump.isEmpty();
}
QString MerTarget::targetPath() const
{
return MerSdkManager::sdkToolsDirectory() + m_sdk->virtualMachineName() + QLatin1Char('/') + m_name;
}
bool MerTarget::createScripts() const
{
if (!isValid())
return false;
const QString targetPath(this->targetPath());
QDir targetDir(targetPath);
if (!targetDir.exists() && !targetDir.mkpath(targetPath)) {
qWarning() << "Could not create target directory." << targetDir;
return false;
}
bool result = true;
for (size_t i = 0; i < sizeof(wrapperScripts) / sizeof(wrapperScripts[0]); ++i)
result &= createScript(targetPath, i);
const QString qmakepath = targetPath + QLatin1Char('/') + QLatin1String(Constants::QMAKE_QUERY);
const QString gccpath = targetPath + QLatin1Char('/') + QLatin1String(Constants::GCC_DUMPMACHINE);
QString patchedQmakeQuery = m_qmakeQuery;
patchedQmakeQuery.replace(QLatin1String(":/"),
QString::fromLatin1(":%1/%2/").arg(m_sdk->sharedTargetsPath()).arg(m_name));
result &= createCacheFile(qmakepath, patchedQmakeQuery);
result &= createCacheFile(gccpath, m_gccMachineDump);
return result;
}
void MerTarget::deleteScripts() const
{
Utils::FileUtils::removeRecursively(Utils::FileName::fromString(targetPath()));
}
ProjectExplorer::Kit* MerTarget::createKit() const
{
if (!isValid())
return 0;
const QString sysroot(m_sdk->sharedTargetsPath() + QLatin1String("/") + m_name);
Utils::FileName path = Utils::FileName::fromString(sysroot);
if (!path.toFileInfo().exists()) {
qWarning() << "Sysroot does not exist" << sysroot;
return 0;
}
ProjectExplorer::Kit *k = new ProjectExplorer::Kit();
k->setAutoDetected(true);
k->setUnexpandedDisplayName(QString::fromLatin1("%1-%2").arg(m_sdk->virtualMachineName(), m_name));
k->setIconPath(Utils::FileName::fromString(QLatin1String(Constants::MER_OPTIONS_CATEGORY_ICON)));
ProjectExplorer::SysRootKitInformation::setSysRoot(k, Utils::FileName::fromUserInput(sysroot));
ProjectExplorer::DeviceTypeKitInformation::setDeviceTypeId(k, Constants::MER_DEVICE_TYPE);
k->setMutable(ProjectExplorer::DeviceKitInformation::id(), true);
const QString gdb = Utils::HostOsInfo::withExecutableSuffix(m_defaultGdb);
QString gdbDir = QCoreApplication::applicationDirPath();
if (Utils::HostOsInfo::isMacHost()) {
QDir dir = QDir(gdbDir);
dir.cdUp();
dir.cdUp();
dir.cdUp();
gdbDir = dir.path();
}
Utils::FileName gdbFileName = Utils::FileName::fromString(gdbDir + QLatin1String("/") + gdb);
Debugger::DebuggerItem debugger;
debugger.setCommand(gdbFileName);
debugger.setEngineType(Debugger::GdbEngineType);
const QString vmName = m_sdk->virtualMachineName();
debugger.setUnexpandedDisplayName(QObject::tr("GDB for %1 %2").arg(vmName, m_name));
debugger.setAutoDetected(true);
debugger.setAbi(ProjectExplorer::Abi::abiFromTargetTriplet(m_gccMachineDump)); // TODO is this OK?
QVariant id = Debugger::DebuggerItemManager::registerDebugger(debugger);
Debugger::DebuggerKitInformation::setDebugger(k, id);
MerSdkKitInformation::setSdk(k,m_sdk);
MerTargetKitInformation::setTargetName(k,name());
return k;
}
MerQtVersion* MerTarget::createQtVersion() const
{
const Utils::FileName qmake =
Utils::FileName::fromString(targetPath() + QLatin1Char('/') +
QLatin1String(Constants::MER_WRAPPER_QMAKE));
// Is there a qtversion present for this qmake?
QtSupport::BaseQtVersion *qtv = QtSupport::QtVersionManager::qtVersionForQMakeBinary(qmake);
if (qtv && !qtv->isValid()) {
QtSupport::QtVersionManager::removeVersion(qtv);
qtv = 0;
}
if (!qtv)
qtv = new MerQtVersion(qmake, true, targetPath());
//QtSupport::QtVersionFactory::createQtVersionFromQMakePath(qmake, true, targetPath());
QTC_ASSERT(qtv && qtv->type() == QLatin1String(Constants::MER_QT), return 0);
MerQtVersion *merqtv = static_cast<MerQtVersion *>(qtv);
const QString vmName = m_sdk->virtualMachineName();
merqtv->setVirtualMachineName(vmName);
merqtv->setTargetName(m_name);
merqtv->setUnexpandedDisplayName(
QString::fromLatin1("Qt %1 in %2 %3").arg(qtv->qtVersionString(),
vmName, m_name));
return merqtv;
}
MerToolChain* MerTarget::createToolChain() const
{
const Utils::FileName gcc =
Utils::FileName::fromString(targetPath() + QLatin1Char('/') +
QLatin1String(Constants::MER_WRAPPER_GCC));
QList<ProjectExplorer::ToolChain *> toolChains = ProjectExplorer::ToolChainManager::toolChains();
foreach (ProjectExplorer::ToolChain *tc, toolChains) {
if (tc->compilerCommand() == gcc && tc->isAutoDetected()) {
QTC_ASSERT(tc->type() == QLatin1String(Constants::MER_TOOLCHAIN_TYPE), return 0);
}
}
MerToolChain* mertoolchain = new MerToolChain(ProjectExplorer::ToolChain::AutoDetection);
const QString vmName = m_sdk->virtualMachineName();
mertoolchain->setDisplayName(QString::fromLatin1("GCC (%1 %2)").arg(vmName, m_name));
mertoolchain->setVirtualMachine(vmName);
mertoolchain->setTargetName(m_name);
mertoolchain->setCompilerCommand(gcc);
return mertoolchain;
}
bool MerTarget::createScript(const QString &targetPath, int scriptIndex) const
{
bool ok = false;
const char* wrapperScriptCopy = wrapperScripts[scriptIndex];
const QFile::Permissions rwrw = QFile::ReadOwner|QFile::ReadUser|QFile::ReadGroup
|QFile::WriteOwner|QFile::WriteUser|QFile::WriteGroup;
const QFile::Permissions rwxrwx = rwrw|QFile::ExeOwner|QFile::ExeUser|QFile::ExeGroup;
QString wrapperScriptCommand = QLatin1String(wrapperScriptCopy);
if (Utils::HostOsInfo::isWindowsHost())
wrapperScriptCommand.chop(4); // remove the ".cmd"
QString wrapperBinaryPath = QCoreApplication::applicationDirPath();
if (Utils::HostOsInfo::isWindowsHost())
wrapperBinaryPath += QLatin1String("/merssh.exe");
else if (Utils::HostOsInfo::isMacHost())
wrapperBinaryPath += QLatin1String("/../Resources/merssh");
else
wrapperBinaryPath += QLatin1String("/merssh");
using namespace Utils;
const QString scriptCopyPath = targetPath + QLatin1Char('/') + QLatin1String(wrapperScriptCopy);
QDir targetDir(targetPath);
const QString targetName = targetDir.dirName();
targetDir.cdUp();
const QString merDevToolsDir = QDir::toNativeSeparators(targetDir.canonicalPath());
QFile script(scriptCopyPath);
ok = script.open(QIODevice::WriteOnly);
if (!ok) {
qWarning() << "Could not open script" << scriptCopyPath;
return false;
}
QString scriptContent;
if (HostOsInfo::isWindowsHost()) {
scriptContent += QLatin1String("@echo off\nSetLocal EnableDelayedExpansion\n");
scriptContent += QLatin1String("set ARGUMENTS=\nFOR %%a IN (%*) DO set ARGUMENTS=!ARGUMENTS! ^ '%%a'\n");
scriptContent += QLatin1String("set ") +
QLatin1String(Mer::Constants::MER_SSH_TARGET_NAME) +
QLatin1Char('=') + targetName + QLatin1Char('\n');
scriptContent += QLatin1String("set ") +
QLatin1String(Mer::Constants::MER_SSH_SDK_TOOLS) +
QLatin1Char('=') + merDevToolsDir + QDir::separator() + targetName + QLatin1Char('\n');
scriptContent += QLatin1String("SetLocal DisableDelayedExpansion\n");
scriptContent += QLatin1Char('"') +
QDir::toNativeSeparators(wrapperBinaryPath) + QLatin1String("\" ") +
wrapperScriptCommand + QLatin1Char(' ') + QLatin1String("%ARGUMENTS%\n");
}
if (HostOsInfo::isAnyUnixHost()) {
scriptContent += QLatin1String("#!/bin/sh\n");
scriptContent += QLatin1String("ARGUMENTS=\"\";for ARGUMENT in \"$@\"; do ARGUMENTS=\"${ARGUMENTS} '${ARGUMENT}'\" ; done;\n");
scriptContent += QLatin1String("export ") +
QLatin1String(Mer::Constants::MER_SSH_TARGET_NAME) +
QLatin1Char('=') + targetName + QLatin1Char('\n');
scriptContent += QLatin1String("export ") +
QLatin1String(Mer::Constants::MER_SSH_SDK_TOOLS) +
QLatin1Char('=') + merDevToolsDir + QDir::separator() + targetName + QLatin1Char('\n');
scriptContent += QLatin1String("exec ");
scriptContent += QLatin1Char('"') +
QDir::toNativeSeparators(wrapperBinaryPath) + QLatin1String("\" ") +
wrapperScriptCommand + QLatin1Char(' ') + QLatin1String("${ARGUMENTS}");
}
ok = script.write(scriptContent.toUtf8()) != -1;
if (!ok) {
qWarning() << "Could not write script" << scriptCopyPath;
return false;
}
ok = QFile::setPermissions(scriptCopyPath, rwxrwx);
if (!ok) {
qWarning() << "Could not set file permissions on script" << scriptCopyPath;
return false;
}
return ok;
}
bool MerTarget::createCacheFile(const QString &fileName, const QString &content) const
{
bool ok = false;
QFile file(fileName);
ok = file.open(QIODevice::WriteOnly);
if (!ok) {
qWarning() << "Could not open cache file" << fileName;
return false;
}
ok = file.write(content.toUtf8()) != -1;
if (!ok) {
qWarning() << "Could not write cache file " << fileName;
return false;
}
file.close();
return ok;
}
bool MerTarget::operator==(const MerTarget &other) const
{
return m_name == other.m_name && m_qmakeQuery == other.m_qmakeQuery && m_gccMachineDump == other.m_gccMachineDump;
}
}
}
<|endoftext|> |
<commit_before>// up_and_down.cc,v 1.4 2003/04/09 15:49:55 wolf Exp
// (c) Wolfgang Bangerth
//
// Try something remarkably simple: take some arbitrary (discrete)
// function and transfer it to a coarser grid. transfer it back to the
// fine grid. store it and call it X. transfer down to the coarse grid
// and back up again. Should still be X, no?
//
// do this on differently refined anisotropic grids
#include "../tests.h"
#include <base/quadrature_lib.h>
#include <base/logstream.h>
#include <lac/vector.h>
#include <grid/tria.h>
#include <grid/tria_iterator.h>
#include <dofs/dof_accessor.h>
#include <grid/grid_generator.h>
#include <grid/grid_tools.h>
#include <fe/fe_dgq.h>
#include <fe/fe_dgp.h>
#include <fe/fe_system.h>
#include <fe/fe_values.h>
#include <vector>
#include <fstream>
#include <string>
#define PRECISION 2
template <int dim>
Point<dim> transform (const Point<dim> p)
{
switch (dim)
{
case 1:
return p;
case 2:
return Point<dim>(p(0)*(1+p(1)), p(1)*(1+p(0)));
case 3:
return Point<dim>(p(0)*(1+p(1))*(1+p(2)),
p(1)*(1+p(0))*(1+p(2)),
p(2)*(1+p(0))*(1+p(1)));
default:
Assert (false, ExcNotImplemented());
return Point<dim>();
};
}
template <int dim>
void check_element (const Triangulation<dim> &tr,
const FiniteElement<dim> &fe)
{
DoFHandler<dim> dof_handler(tr);
dof_handler.distribute_dofs (fe);
// create a mostly arbitrary
// function plus a trend on this
// grid
Vector<double> tmp(dof_handler.n_dofs());
for (unsigned int i=0; i<tmp.size(); ++i)
tmp(i) = i;//(i + 13*i%17);
// restrict this function to the
// next coarser level and
// distribute it again to the
// higher level
Vector<double> x(tmp.size());
Vector<double> v(fe.dofs_per_cell);
for (typename DoFHandler<dim>::cell_iterator cell=dof_handler.begin();
cell!=dof_handler.end(); ++cell)
if (cell->has_children() &&
cell->child(0)->active())
{
// first make sure that what
// we do is reasonable. for
// this, _all_ children have
// to be active, not only
// some of them
for (unsigned int c=0; c<cell->n_children(); ++c)
Assert (cell->child(c)->active(), ExcInternalError());
// then restrict and prolongate
cell->get_interpolated_dof_values (tmp, v);
cell->set_dof_values_by_interpolation (v, x);
};
// now x is a function on the fine
// grid that is representable on
// the coarse grid. so another
// cycle should not alter it any
// more:
Vector<double> x2(x.size());
for (typename DoFHandler<dim>::cell_iterator cell=dof_handler.begin();
cell!=dof_handler.end(); ++cell)
if (cell->has_children() &&
cell->child(0)->active())
{
cell->get_interpolated_dof_values (x, v);
cell->set_dof_values_by_interpolation (v, x2);
};
// then check that this is so:
x2 -= x;
const double relative_residual = (x2.l2_norm() / x.l2_norm());
const double threshold = 1e-6;
deallog << ", dofs_per_cell=" << fe.dofs_per_cell
<< "; relative residual: "
<< (relative_residual<threshold ? "ok" : "botched up!")
<< std::endl;
}
template <int dim>
void test ()
{
const std::string ref_case_names[7]=
{"RefinementCase<dim>::cut_x",
"RefinementCase<dim>::cut_y",
"RefinementCase<dim>::cut_xy",
"RefinementCase<dim>::cut_z",
"RefinementCase<dim>::cut_xz",
"RefinementCase<dim>::cut_yz",
"RefinementCase<dim>::cut_xyz"};
const unsigned int n_ref_cases_for_dim[4]={0,1,3,7};
// now for a list of finite
// elements, for which we want to
// test. we happily waste tons of
// memory here, but who cares...
const FiniteElement<dim> *fe_list[]
=
{
// FE_DGQ
new FE_DGQ<dim>(0),
new FE_DGQ<dim>(1),
new FE_DGQ<dim>(2),
(dim<3 ? new FE_DGQ<dim>(3) : 0),
(dim<3 ? new FE_DGQ<dim>(4) : 0),
// FE_DGP
new FE_DGP<dim>(0),
new FE_DGP<dim>(1),
new FE_DGP<dim>(2),
new FE_DGP<dim>(3),
// some composed elements
// of increasing
// complexity, to check the
// logics by which the
// matrices of the composed
// elements are assembled
// from those of the base
// elements.
new FESystem<dim> (FE_DGQ<dim>(1), 2),
new FESystem<dim> (FE_DGP<dim>(1), 1,
FE_DGQ<dim>(2), 2),
new FESystem<dim> (FE_DGP<dim>(1), 2,
FE_DGQ<dim>(2), 2,
FE_DGP<dim>(0), 1),
new FESystem<dim> (FE_DGQ<dim>(1), 2,
FESystem<dim> (FE_DGQ<dim>(1), 2,
FE_DGP<dim>(2), 2,
FE_DGQ<dim>(2), 1), 2,
FE_DGP<dim>(0), 1),
new FESystem<dim> (FE_DGP<dim>(1), 2,
FESystem<dim> (FE_DGP<dim>(1), 2,
FE_DGQ<dim>(2), 2,
FESystem<dim>(FE_DGQ<dim>(0),
3),
1), 2,
FE_DGQ<dim>(0), 1),
// some continuous FEs
new FE_Q<dim>(1),
new FE_Q<dim>(2),
new FESystem<dim> (FE_Q<dim>(1), 2),
new FESystem<dim> (FE_DGQ<dim>(1), 2,
FESystem<dim> (FE_Q<dim>(1), 2,
FE_Q<dim>(2), 1,
FE_DGP<dim>(2), 1), 2,
FE_Q<dim>(3),1)
};
for (unsigned int j=0; j<n_ref_cases_for_dim[dim]; ++j)
{
// make a coarse triangulation as a
// hypercube. if in more than 1d, distort it
// so that it is no more an affine image of
// the hypercube, to make things more
// difficult. then refine it globally once
// and refine again in an anisotropic way
Triangulation<dim> tr;
GridGenerator::hyper_cube(tr, 0., 1.);
Point<dim> (*p) (Point<dim>) = &transform<dim>;
GridTools::transform (p, tr);
tr.refine_global (1);
typename Triangulation<dim>::active_cell_iterator cell=tr.begin_active(),
endc=tr.end();
for (; cell!=endc; ++cell)
cell->set_refine_flag(RefinementCase<dim>(j+1));
tr.execute_coarsening_and_refinement();
for (unsigned int i=0; i<sizeof(fe_list)/sizeof(fe_list[0]); ++i)
if (fe_list[i] != 0)
{
deallog << dim << "d, uniform grid, fe #" << i
<< ", " << ref_case_names[j];
check_element (tr, *fe_list[i]);
}
}
}
int
main()
{
std::ofstream logfile ("up_and_down/output");
logfile.precision (PRECISION);
logfile.setf(std::ios::fixed);
deallog.attach(logfile);
deallog.depth_console(0);
deallog.threshold_double(1.e-10);
test<1>();
test<2>();
test<3>();
return 0;
}
<commit_msg>Include header file that is now apparently necessary.<commit_after>// up_and_down.cc,v 1.4 2003/04/09 15:49:55 wolf Exp
// (c) Wolfgang Bangerth
//
// Try something remarkably simple: take some arbitrary (discrete)
// function and transfer it to a coarser grid. transfer it back to the
// fine grid. store it and call it X. transfer down to the coarse grid
// and back up again. Should still be X, no?
//
// do this on differently refined anisotropic grids
#include "../tests.h"
#include <base/quadrature_lib.h>
#include <base/logstream.h>
#include <lac/vector.h>
#include <grid/tria.h>
#include <grid/tria_iterator.h>
#include <dofs/dof_accessor.h>
#include <grid/grid_generator.h>
#include <grid/grid_tools.h>
#include <fe/fe_q.h>
#include <fe/fe_dgq.h>
#include <fe/fe_dgp.h>
#include <fe/fe_system.h>
#include <fe/fe_values.h>
#include <vector>
#include <fstream>
#include <string>
#define PRECISION 2
template <int dim>
Point<dim> transform (const Point<dim> p)
{
switch (dim)
{
case 1:
return p;
case 2:
return Point<dim>(p(0)*(1+p(1)), p(1)*(1+p(0)));
case 3:
return Point<dim>(p(0)*(1+p(1))*(1+p(2)),
p(1)*(1+p(0))*(1+p(2)),
p(2)*(1+p(0))*(1+p(1)));
default:
Assert (false, ExcNotImplemented());
return Point<dim>();
};
}
template <int dim>
void check_element (const Triangulation<dim> &tr,
const FiniteElement<dim> &fe)
{
DoFHandler<dim> dof_handler(tr);
dof_handler.distribute_dofs (fe);
// create a mostly arbitrary
// function plus a trend on this
// grid
Vector<double> tmp(dof_handler.n_dofs());
for (unsigned int i=0; i<tmp.size(); ++i)
tmp(i) = i;//(i + 13*i%17);
// restrict this function to the
// next coarser level and
// distribute it again to the
// higher level
Vector<double> x(tmp.size());
Vector<double> v(fe.dofs_per_cell);
for (typename DoFHandler<dim>::cell_iterator cell=dof_handler.begin();
cell!=dof_handler.end(); ++cell)
if (cell->has_children() &&
cell->child(0)->active())
{
// first make sure that what
// we do is reasonable. for
// this, _all_ children have
// to be active, not only
// some of them
for (unsigned int c=0; c<cell->n_children(); ++c)
Assert (cell->child(c)->active(), ExcInternalError());
// then restrict and prolongate
cell->get_interpolated_dof_values (tmp, v);
cell->set_dof_values_by_interpolation (v, x);
};
// now x is a function on the fine
// grid that is representable on
// the coarse grid. so another
// cycle should not alter it any
// more:
Vector<double> x2(x.size());
for (typename DoFHandler<dim>::cell_iterator cell=dof_handler.begin();
cell!=dof_handler.end(); ++cell)
if (cell->has_children() &&
cell->child(0)->active())
{
cell->get_interpolated_dof_values (x, v);
cell->set_dof_values_by_interpolation (v, x2);
};
// then check that this is so:
x2 -= x;
const double relative_residual = (x2.l2_norm() / x.l2_norm());
const double threshold = 1e-6;
deallog << ", dofs_per_cell=" << fe.dofs_per_cell
<< "; relative residual: "
<< (relative_residual<threshold ? "ok" : "botched up!")
<< std::endl;
}
template <int dim>
void test ()
{
const std::string ref_case_names[7]=
{"RefinementCase<dim>::cut_x",
"RefinementCase<dim>::cut_y",
"RefinementCase<dim>::cut_xy",
"RefinementCase<dim>::cut_z",
"RefinementCase<dim>::cut_xz",
"RefinementCase<dim>::cut_yz",
"RefinementCase<dim>::cut_xyz"};
const unsigned int n_ref_cases_for_dim[4]={0,1,3,7};
// now for a list of finite
// elements, for which we want to
// test. we happily waste tons of
// memory here, but who cares...
const FiniteElement<dim> *fe_list[]
=
{
// FE_DGQ
new FE_DGQ<dim>(0),
new FE_DGQ<dim>(1),
new FE_DGQ<dim>(2),
(dim<3 ? new FE_DGQ<dim>(3) : 0),
(dim<3 ? new FE_DGQ<dim>(4) : 0),
// FE_DGP
new FE_DGP<dim>(0),
new FE_DGP<dim>(1),
new FE_DGP<dim>(2),
new FE_DGP<dim>(3),
// some composed elements
// of increasing
// complexity, to check the
// logics by which the
// matrices of the composed
// elements are assembled
// from those of the base
// elements.
new FESystem<dim> (FE_DGQ<dim>(1), 2),
new FESystem<dim> (FE_DGP<dim>(1), 1,
FE_DGQ<dim>(2), 2),
new FESystem<dim> (FE_DGP<dim>(1), 2,
FE_DGQ<dim>(2), 2,
FE_DGP<dim>(0), 1),
new FESystem<dim> (FE_DGQ<dim>(1), 2,
FESystem<dim> (FE_DGQ<dim>(1), 2,
FE_DGP<dim>(2), 2,
FE_DGQ<dim>(2), 1), 2,
FE_DGP<dim>(0), 1),
new FESystem<dim> (FE_DGP<dim>(1), 2,
FESystem<dim> (FE_DGP<dim>(1), 2,
FE_DGQ<dim>(2), 2,
FESystem<dim>(FE_DGQ<dim>(0),
3),
1), 2,
FE_DGQ<dim>(0), 1),
// some continuous FEs
new FE_Q<dim>(1),
new FE_Q<dim>(2),
new FESystem<dim> (FE_Q<dim>(1), 2),
new FESystem<dim> (FE_DGQ<dim>(1), 2,
FESystem<dim> (FE_Q<dim>(1), 2,
FE_Q<dim>(2), 1,
FE_DGP<dim>(2), 1), 2,
FE_Q<dim>(3),1)
};
for (unsigned int j=0; j<n_ref_cases_for_dim[dim]; ++j)
{
// make a coarse triangulation as a
// hypercube. if in more than 1d, distort it
// so that it is no more an affine image of
// the hypercube, to make things more
// difficult. then refine it globally once
// and refine again in an anisotropic way
Triangulation<dim> tr;
GridGenerator::hyper_cube(tr, 0., 1.);
Point<dim> (*p) (Point<dim>) = &transform<dim>;
GridTools::transform (p, tr);
tr.refine_global (1);
typename Triangulation<dim>::active_cell_iterator cell=tr.begin_active(),
endc=tr.end();
for (; cell!=endc; ++cell)
cell->set_refine_flag(RefinementCase<dim>(j+1));
tr.execute_coarsening_and_refinement();
for (unsigned int i=0; i<sizeof(fe_list)/sizeof(fe_list[0]); ++i)
if (fe_list[i] != 0)
{
deallog << dim << "d, uniform grid, fe #" << i
<< ", " << ref_case_names[j];
check_element (tr, *fe_list[i]);
}
}
}
int
main()
{
std::ofstream logfile ("up_and_down/output");
logfile.precision (PRECISION);
logfile.setf(std::ios::fixed);
deallog.attach(logfile);
deallog.depth_console(0);
deallog.threshold_double(1.e-10);
test<1>();
test<2>();
test<3>();
return 0;
}
<|endoftext|> |
<commit_before>/**
* @file
*
* @brief Write key sets using yaml-cpp
*
* @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
*/
#include "write.hpp"
#include "yaml.h"
#include <kdbease.h>
#include <kdblogger.h>
#include <kdbplugin.h>
#include <fstream>
using namespace std;
using namespace kdb;
namespace
{
/**
* @brief Save a key set in a YAML emitter
*
* @param mappings The key set that should be stored in `emitter`
* @param parent This key stores the common prefix for the key name
* @param node This emitter stores the converted key set
*/
void convertKeySetToEmitter (KeySet const & mappings, Key const & parent, YAML::Emitter & emitter)
{
for (auto key : mappings)
{
const char * name = elektraKeyGetRelativeName (key.getKey (), parent.getKey ());
emitter << YAML::Key << name << YAML::Value << key.get<string> ();
ELEKTRA_LOG_DEBUG ("%s: %s", key.get<string> ().c_str (), key.getName ().c_str ());
}
}
} // end namespace
/**
* @brief This function saves the key-value pairs stored in `mappings` as YAML data in the location specified via `parent`.
*
* @param mappings This key set stores the mappings that should be saved as YAML data.
* @param parent This key specifies the path to the YAML data file that should be written.
*/
void yamlcpp::yamlWrite (KeySet const & mappings, Key const & parent)
{
ofstream output (parent.getString ());
YAML::Emitter emitter (output);
emitter << YAML::BeginMap;
convertKeySetToEmitter (mappings, parent, emitter);
emitter << YAML::EndMap;
}
<commit_msg>YAML CPP: Write data recursively<commit_after>/**
* @file
*
* @brief Write key sets using yaml-cpp
*
* @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
*/
#include "write.hpp"
#include "yaml.h"
#include <kdbease.h>
#include <kdblogger.h>
#include <kdbplugin.h>
#include <fstream>
using namespace std;
using namespace kdb;
namespace
{
void addKey (YAML::Node data, NameIterator & keyIterator, Key const & key)
{
if (keyIterator == --key.end ())
{
data[*keyIterator] = YAML::Node (key.getString ());
return;
}
YAML::Node dictionary = (data[*keyIterator] && data[*keyIterator].IsMap ()) ? data[*keyIterator] : YAML::Node (YAML::NodeType::Map);
data[*keyIterator] = dictionary;
addKey (dictionary, ++keyIterator, key);
}
void addKeys (YAML::Node data, KeySet const & mappings, Key const & parent)
{
for (auto key : mappings)
{
auto parentIterator = parent.begin ();
auto keyIterator = key.begin ();
while (parentIterator != parent.end () && keyIterator != key.end ())
{
parentIterator++;
keyIterator++;
}
addKey (data, keyIterator, key);
}
}
} // end namespace
/**
* @brief This function saves the key-value pairs stored in `mappings` as YAML data in the location specified via `parent`.
*
* @param mappings This key set stores the mappings that should be saved as YAML data.
* @param parent This key specifies the path to the YAML data file that should be written.
*/
void yamlcpp::yamlWrite (KeySet const & mappings, Key const & parent)
{
ofstream output (parent.getString ());
auto data = YAML::Node (YAML::NodeType::Map);
addKeys (data, mappings, parent);
output << data;
}
<|endoftext|> |
<commit_before>#include <cstdio>
#include <cstdlib>
#include <cstring>
#include "Graph.h"
#include "Postgres.h"
using namespace std;
/**
* A simple in-memory stored Graph, with the word indexer and the edge
* matrix.
*/
class InMemoryGraph : public Graph {
private:
char** index2gloss;
edge** edges;
uint32_t* edgesSizes;
uint64_t size;
public:
InMemoryGraph(char** index2gloss, edge** edges, uint32_t* edgesSizes, uint64_t size)
: index2gloss(index2gloss), edges(edges), edgesSizes(edgesSizes), size(size) { }
~InMemoryGraph() {
for (int i = 0; i < size; ++i) {
free(index2gloss[i]);
free(edges[i]);
}
free(index2gloss);
free(edges);
free(edgesSizes);
}
virtual const edge* outgoingEdgesFast(word source, uint32_t* size) {
*size = edgesSizes[source];
return edges[source];
}
virtual const char* gloss(word word) {
return index2gloss[word];
}
virtual const vector<word> keys() {
vector<word> keys(size);
for (int i = 0; i < size; ++i) {
keys[i] = i;
}
return keys;
}
};
Graph* ReadGraph() {
printf("Reading graph...\n");
const uint32_t numWords
= atoi(PGIterator("SELECT COUNT(*) FROM word_indexer;").next()[0]);
// Read words
char** index2gloss = (char**) malloc( numWords * sizeof(char*) );
// (query)
char wordQuery[127];
snprintf(wordQuery, 127, "SELECT * FROM %s;", PG_TABLE_WORD.c_str());
PGIterator words = PGIterator(wordQuery);
uint64_t wordI = 0;
while (words.hasNext()) {
PGRow row = words.next();
size_t len = strlen(row[1]);
char* gloss = (char*) malloc( len * sizeof(char) );
strncpy(gloss, row[1], len);
index2gloss[atoi(row[0])] = gloss;
wordI += 1;
if (wordI % 1000000 == 0) {
printf("loaded %luM words\n", wordI / 1000000);
}
}
// Read edges
struct edge** edges = (struct edge**) malloc((numWords+1) * sizeof(struct edge*));
uint32_t* edgesSizes = (uint32_t*) malloc((numWords+1) * sizeof(uint32_t));
uint32_t* edgeCapacities = (uint32_t*) malloc((numWords+1) * sizeof(uint32_t));
for (uint32_t i = 0; i < numWords; ++i) {
edgesSizes[i] = 0;
edges[i] = (struct edge*) malloc(32 * sizeof(struct edge));
edgeCapacities[i] = 32;
}
// (query)
char edgeQuery[127];
snprintf(edgeQuery, 127, "SELECT * FROM %s;", PG_TABLE_EDGE.c_str());
PGIterator edgeIter = PGIterator(edgeQuery);
uint64_t edgeI = 0;
while (edgeIter.hasNext()) {
PGRow row = edgeIter.next();
edge edge;
edge.source = atol(row[0]);
edge.sink = atoi(row[1]);
edge.type = atoi(row[2]);
edge.cost = atof(row[3]);
if (edgesSizes[edge.source] >= edgeCapacities[edge.source]) {
struct edge* newEdges = (struct edge*) malloc(edgeCapacities[edge.source] * 2 * sizeof(struct edge));
memcpy(newEdges, edges[edge.source], edgeCapacities[edge.source] * sizeof(struct edge));
free(edges[edge.source]);
edges[edge.source] = newEdges;
}
edges[edge.source][edgesSizes[edge.source]] = edge;
edgesSizes[edge.source] += 1;
edgeI += 1;
if (edgeI % 1000000 == 0) {
printf("loaded %luM edges\n", edgeI / 1000000);
}
}
free(edgeCapacities);
// Finish
printf("%s\n", "Done reading the graph.");
return new InMemoryGraph(index2gloss, edges, edgesSizes, numWords);
}
class MockGraph : public Graph {
public:
MockGraph() {
noEdges = new vector<edge>();
// Edges out of Lemur
lemurEdges = new vector<edge>();
edge lemurToTimone;
lemurToTimone.source = 2479928;
lemurToTimone.sink = 16442985;
lemurToTimone.type = 1;
lemurToTimone.cost = 0.01;
lemurEdges->push_back(lemurToTimone);
edge lemurToAnimal;
lemurToAnimal.source = 2479928;
lemurToAnimal.sink = 3701;
lemurToAnimal.type = 0;
lemurToAnimal.cost = 0.42;
lemurEdges->push_back(lemurToAnimal);
// Edges out of Animal
animalEdges = new vector<edge>();
edge animalToCat;
animalToCat.source = 3701;
animalToCat.sink = 27970;
animalToCat.type = 1;
animalToCat.cost = 42.00;
animalEdges->push_back(animalToCat);
// Other edges
timoneEdges = new vector<edge>();
catEdges = new vector<edge>();
haveEdges = new vector<edge>();
tailEdges = new vector<edge>();
}
~MockGraph() {
delete noEdges, lemurEdges, animalEdges, timoneEdges,
catEdges, haveEdges, tailEdges;
}
virtual const edge* outgoingEdgesFast(word source, uint32_t* outputLength) {
vector<edge> edges = outgoingEdges(source);
*outputLength = edges.size();
edge* rtn = (struct edge*) malloc( edges.size() * sizeof(edge) ); // WARNING: memory leak
for (int i = 0; i < edges.size(); ++i) {
rtn[i] = edges[i];
}
return rtn;
}
virtual const vector<edge> outgoingEdges(word source) {
switch (source) {
case 2479928: // lemur
return *lemurEdges;
case 3701: // animal
return *animalEdges;
case 16442985: // timone
return *timoneEdges;
case 27970: // cat
return *catEdges;
case 3844: // have
return *haveEdges;
case 14221: // tail
return *tailEdges;
default:
return *noEdges;
}
}
virtual const char* gloss(word word) {
switch (word) {
case 2479928: // lemur
return "lemur";
case 3701: // animal
return "animal";
case 16442985: // timone
return "Timone";
case 27970: // cat
return "cat";
case 3844: // have
return "have";
case 14221: // tail
return "tail";
default:
return "<<unk>>";
}
}
virtual const vector<word> keys() {
vector<word> keys(6);
keys[0] = 2479928;
keys[1] = 3701;
keys[2] = 16442985;
keys[3] = 27970;
keys[4] = 3844;
keys[5] = 14221;
return keys;
}
private:
vector<edge>* noEdges;
vector<edge>* lemurEdges;
vector<edge>* animalEdges;
vector<edge>* timoneEdges;
vector<edge>* catEdges;
vector<edge>* haveEdges;
vector<edge>* tailEdges;
};
Graph* ReadMockGraph() {
return new MockGraph();
}
<commit_msg>Seems to have fixed the memory bug<commit_after>#include <cstdio>
#include <cstdlib>
#include <cstring>
#include "Graph.h"
#include "Postgres.h"
using namespace std;
/**
* A simple in-memory stored Graph, with the word indexer and the edge
* matrix.
*/
class InMemoryGraph : public Graph {
private:
char** index2gloss;
edge** edges;
uint32_t* edgesSizes;
uint64_t size;
public:
InMemoryGraph(char** index2gloss, edge** edges, uint32_t* edgesSizes, uint64_t size)
: index2gloss(index2gloss), edges(edges), edgesSizes(edgesSizes), size(size) { }
~InMemoryGraph() {
for (int i = 0; i < size; ++i) {
free(index2gloss[i]);
free(edges[i]);
}
free(index2gloss);
free(edges);
free(edgesSizes);
}
virtual const edge* outgoingEdgesFast(word source, uint32_t* size) {
*size = edgesSizes[source];
return edges[source];
}
virtual const char* gloss(word word) {
return index2gloss[word];
}
virtual const vector<word> keys() {
vector<word> keys(size);
for (int i = 0; i < size; ++i) {
keys[i] = i;
}
return keys;
}
};
Graph* ReadGraph() {
printf("Reading graph...\n");
const uint32_t numWords
= atoi(PGIterator("SELECT COUNT(*) FROM word_indexer;").next()[0]);
// Read words
char** index2gloss = (char**) malloc( numWords * sizeof(char*) );
// (query)
char wordQuery[127];
snprintf(wordQuery, 127, "SELECT * FROM %s;", PG_TABLE_WORD.c_str());
PGIterator words = PGIterator(wordQuery);
uint64_t wordI = 0;
while (words.hasNext()) {
PGRow row = words.next();
size_t len = strlen(row[1]);
char* gloss = (char*) malloc( len * sizeof(char) );
strncpy(gloss, row[1], len);
index2gloss[atoi(row[0])] = gloss;
wordI += 1;
if (wordI % 1000000 == 0) {
printf("loaded %luM words\n", wordI / 1000000);
}
}
// Read edges
struct edge** edges = (struct edge**) malloc((numWords+1) * sizeof(struct edge*));
uint32_t* edgesSizes = (uint32_t*) malloc((numWords+1) * sizeof(uint32_t));
uint32_t* edgeCapacities = (uint32_t*) malloc((numWords+1) * sizeof(uint32_t));
for (uint32_t i = 0; i < numWords + 1; ++i) {
edgesSizes[i] = 0;
edges[i] = (struct edge*) malloc(4 * sizeof(struct edge));
edgeCapacities[i] = 4;
}
// (query)
char edgeQuery[127];
snprintf(edgeQuery, 127, "SELECT * FROM %s;", PG_TABLE_EDGE.c_str());
PGIterator edgeIter = PGIterator(edgeQuery);
uint64_t edgeI = 0;
while (edgeIter.hasNext()) {
PGRow row = edgeIter.next();
edge edge;
edge.source = atol(row[0]);
edge.sink = atoi(row[1]);
edge.type = atoi(row[2]);
edge.cost = atof(row[3]);
if (edgesSizes[edge.source] >= edgeCapacities[edge.source] - 1) {
struct edge* newEdges = (struct edge*) malloc(edgeCapacities[edge.source] * 2 * sizeof(struct edge));
memcpy(newEdges, edges[edge.source], edgeCapacities[edge.source] * sizeof(struct edge));
free(edges[edge.source]);
edges[edge.source] = newEdges;
}
edges[edge.source][edgesSizes[edge.source]] = edge;
edgesSizes[edge.source] += 1;
edgeI += 1;
if (edgeI % 1000000 == 0) {
printf("loaded %luM edges\n", edgeI / 1000000);
}
}
free(edgeCapacities);
// Finish
printf("%s\n", "Done reading the graph.");
return new InMemoryGraph(index2gloss, edges, edgesSizes, numWords);
}
class MockGraph : public Graph {
public:
MockGraph() {
noEdges = new vector<edge>();
// Edges out of Lemur
lemurEdges = new vector<edge>();
edge lemurToTimone;
lemurToTimone.source = 2479928;
lemurToTimone.sink = 16442985;
lemurToTimone.type = 1;
lemurToTimone.cost = 0.01;
lemurEdges->push_back(lemurToTimone);
edge lemurToAnimal;
lemurToAnimal.source = 2479928;
lemurToAnimal.sink = 3701;
lemurToAnimal.type = 0;
lemurToAnimal.cost = 0.42;
lemurEdges->push_back(lemurToAnimal);
// Edges out of Animal
animalEdges = new vector<edge>();
edge animalToCat;
animalToCat.source = 3701;
animalToCat.sink = 27970;
animalToCat.type = 1;
animalToCat.cost = 42.00;
animalEdges->push_back(animalToCat);
// Other edges
timoneEdges = new vector<edge>();
catEdges = new vector<edge>();
haveEdges = new vector<edge>();
tailEdges = new vector<edge>();
}
~MockGraph() {
delete noEdges, lemurEdges, animalEdges, timoneEdges,
catEdges, haveEdges, tailEdges;
}
virtual const edge* outgoingEdgesFast(word source, uint32_t* outputLength) {
vector<edge> edges = outgoingEdges(source);
*outputLength = edges.size();
edge* rtn = (struct edge*) malloc( edges.size() * sizeof(edge) ); // WARNING: memory leak
for (int i = 0; i < edges.size(); ++i) {
rtn[i] = edges[i];
}
return rtn;
}
virtual const vector<edge> outgoingEdges(word source) {
switch (source) {
case 2479928: // lemur
return *lemurEdges;
case 3701: // animal
return *animalEdges;
case 16442985: // timone
return *timoneEdges;
case 27970: // cat
return *catEdges;
case 3844: // have
return *haveEdges;
case 14221: // tail
return *tailEdges;
default:
return *noEdges;
}
}
virtual const char* gloss(word word) {
switch (word) {
case 2479928: // lemur
return "lemur";
case 3701: // animal
return "animal";
case 16442985: // timone
return "Timone";
case 27970: // cat
return "cat";
case 3844: // have
return "have";
case 14221: // tail
return "tail";
default:
return "<<unk>>";
}
}
virtual const vector<word> keys() {
vector<word> keys(6);
keys[0] = 2479928;
keys[1] = 3701;
keys[2] = 16442985;
keys[3] = 27970;
keys[4] = 3844;
keys[5] = 14221;
return keys;
}
private:
vector<edge>* noEdges;
vector<edge>* lemurEdges;
vector<edge>* animalEdges;
vector<edge>* timoneEdges;
vector<edge>* catEdges;
vector<edge>* haveEdges;
vector<edge>* tailEdges;
};
Graph* ReadMockGraph() {
return new MockGraph();
}
<|endoftext|> |
<commit_before>#include "Http.hpp"
#include "Logger.hpp"
#include "version.hpp"
#include <boost/asio/system_timer.hpp>
#include <boost/spirit/include/qi.hpp>
#include <date/date.h>
Http::Http(std::string token) :
m_SslContext(asio::ssl::context::sslv23),
m_Token(token),
m_NetworkThreadRunning(true),
m_NetworkThread(std::bind(&Http::NetworkThreadFunc, this))
{
}
Http::~Http()
{
m_NetworkThreadRunning = false;
m_NetworkThread.join();
// drain requests queue
QueueEntry *entry;
while (m_Queue.pop(entry))
delete entry;
}
void Http::NetworkThreadFunc()
{
std::unordered_map<std::string, TimePoint_t> path_ratelimit;
unsigned int retry_counter = 0;
unsigned int const MaxRetries = 3;
bool skip_entry = false;
if (!Connect())
return;
while (m_NetworkThreadRunning)
{
TimePoint_t current_time = std::chrono::steady_clock::now();
std::list<QueueEntry*> skipped_entries;
QueueEntry *entry;
while (m_Queue.pop(entry))
{
// check if we're rate-limited
auto pr_it = path_ratelimit.find(entry->Request->target().to_string());
if (pr_it != path_ratelimit.end())
{
// rate-limit for this path exists
// are we still within the rate-limit timepoint?
if (current_time < pr_it->second)
{
// yes, ignore this request for now
skipped_entries.push_back(entry);
continue;
}
// no, delete rate-limit and go on
path_ratelimit.erase(pr_it);
Logger::Get()->Log(LogLevel::DEBUG, "rate-limit on path '{}' lifted",
entry->Request->target().to_string());
}
boost::system::error_code error_code;
Response_t response;
Streambuf_t sb;
retry_counter = 0;
skip_entry = false;
do
{
bool do_reconnect = false;
beast::http::write(*m_SslStream, *entry->Request, error_code);
if (error_code)
{
Logger::Get()->Log(LogLevel::ERROR, "Error while sending HTTP {} request to '{}': {}",
entry->Request->method_string().to_string(),
entry->Request->target().to_string(),
error_code.message());
do_reconnect = true;
}
else
{
beast::http::read(*m_SslStream, sb, response, error_code);
if (error_code)
{
Logger::Get()->Log(LogLevel::ERROR, "Error while retrieving HTTP {} response from '{}': {}",
entry->Request->method_string().to_string(),
entry->Request->target().to_string(),
error_code.message());
do_reconnect = true;
}
}
if (do_reconnect)
{
if (retry_counter++ >= MaxRetries || !ReconnectRetry())
{
// we failed to reconnect, discard this request
Logger::Get()->Log(LogLevel::WARNING, "Failed to send request, discarding");
skip_entry = true;
break; // break out of do-while loop
}
}
} while (error_code);
if (skip_entry)
continue; // continue queue loop
auto it_r = response.find("X-RateLimit-Remaining");
if (it_r != response.end())
{
if (it_r->value().compare("0") == 0)
{
// we're now officially rate-limited
// the next call to this path will fail
std::string limited_url = entry->Request->target().to_string();
auto lit = path_ratelimit.find(limited_url);
if (lit != path_ratelimit.end())
{
Logger::Get()->Log(LogLevel::ERROR,
"Error while processing rate-limit: already rate-limited path '{}'",
limited_url);
// skip this request, we'll re-add it to the queue to retry later
skipped_entries.push_back(entry);
continue;
}
it_r = response.find("X-RateLimit-Reset");
if (it_r != response.end())
{
auto date_str = response.find(boost::beast::http::field::date)->value().to_string();
std::istringstream date_ss{ date_str };
date::sys_seconds date_utc;
date_ss >> date::parse("%a, %d %b %Y %T %Z", date_utc); // RFC2616 HTTP header date format
std::chrono::seconds timepoint_now = date_utc.time_since_epoch();
Logger::Get()->Log(LogLevel::DEBUG, "rate-limiting path {} until {} (current time: {})",
limited_url,
it_r->value().to_string(),
timepoint_now.count());
string const &reset_time_str = it_r->value().to_string();
long long reset_time_secs = 0;
boost::spirit::qi::parse(reset_time_str.begin(), reset_time_str.end(),
boost::spirit::qi::any_int_parser<long long>(),
reset_time_secs);
TimePoint_t reset_time = std::chrono::steady_clock::now()
+ std::chrono::seconds(reset_time_secs - timepoint_now.count() + 1); // add a buffer of 1 second
path_ratelimit.insert({ limited_url, reset_time });
}
}
}
if (entry->Callback)
entry->Callback(sb, response);
delete entry;
entry = nullptr;
}
// add skipped entries back to queue
for (auto e : skipped_entries)
m_Queue.push(e);
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
Disconnect();
}
bool Http::Connect()
{
Logger::Get()->Log(LogLevel::DEBUG, "Http::Connect");
// connect to REST API
asio::ip::tcp::resolver r{ m_IoService };
boost::system::error_code error;
auto target = r.resolve({ "discordapp.com", "https" }, error);
if (error)
{
Logger::Get()->Log(LogLevel::ERROR, "Can't resolve Discord API URL: {} ({})",
error.message(), error.value());
return false;
}
m_SslStream.reset(new SslStream_t(m_IoService, m_SslContext));
asio::connect(m_SslStream->lowest_layer(), target, error);
if (error)
{
Logger::Get()->Log(LogLevel::ERROR, "Can't connect to Discord API: {} ({})",
error.message(), error.value());
return false;
}
// SSL handshake
m_SslStream->set_verify_mode(asio::ssl::verify_none, error);
if (error)
{
Logger::Get()->Log(LogLevel::ERROR,
"Can't configure SSL stream peer verification mode for Discord API: {} ({})",
error.message(), error.value());
return false;
}
m_SslStream->handshake(asio::ssl::stream_base::client, error);
if (error)
{
Logger::Get()->Log(LogLevel::ERROR, "Can't establish secured connection to Discord API: {} ({})",
error.message(), error.value());
return false;
}
return true;
}
void Http::Disconnect()
{
Logger::Get()->Log(LogLevel::DEBUG, "Http::Disconnect");
boost::system::error_code error;
m_SslStream->shutdown(error);
if (error && error != boost::asio::error::eof)
{
Logger::Get()->Log(LogLevel::WARNING, "Error while shutting down SSL on HTTP connection: {} ({})",
error.message(), error.value());
}
m_SslStream->lowest_layer().shutdown(asio::ip::tcp::socket::shutdown_both, error);
if (error && error != boost::asio::error::eof)
{
Logger::Get()->Log(LogLevel::WARNING, "Error while shutting down HTTP connection: {} ({})",
error.message(), error.value());
}
m_SslStream->lowest_layer().close(error);
if (error)
{
Logger::Get()->Log(LogLevel::WARNING, "Error while closing HTTP connection: {} ({})",
error.message(), error.value());
}
}
bool Http::ReconnectRetry()
{
Logger::Get()->Log(LogLevel::DEBUG, "Http::ReconnectRetry");
unsigned int reconnect_counter = 0;
do
{
Logger::Get()->Log(LogLevel::INFO, "trying reconnect #{}...", reconnect_counter + 1);
Disconnect();
if (Connect())
{
Logger::Get()->Log(LogLevel::INFO, "reconnect succeeded, resending request");
return true;
}
else
{
unsigned int seconds_to_wait = static_cast<unsigned int>(std::pow(2U, reconnect_counter));
Logger::Get()->Log(LogLevel::WARNING, "reconnect failed, waiting {} seconds...", seconds_to_wait);
std::this_thread::sleep_for(std::chrono::seconds(seconds_to_wait));
}
} while (++reconnect_counter < 3);
Logger::Get()->Log(LogLevel::ERROR, "Could not reconnect to Discord");
return false;
}
Http::SharedRequest_t Http::PrepareRequest(beast::http::verb const method,
std::string const &url, std::string const &content)
{
Logger::Get()->Log(LogLevel::DEBUG, "Http::PrepareRequest");
auto req = std::make_shared<Request_t>();
req->method(method);
req->target("/api/v6" + url);
req->version(11);
req->insert(beast::http::field::connection, "keep-alive");
req->insert(beast::http::field::host, "discordapp.com");
req->insert(beast::http::field::user_agent,
"DiscordBot (github.com/maddinat0r/samp-discord-connector, " PLUGIN_VERSION ")");
if (!content.empty())
req->insert(beast::http::field::content_type, "application/json");
req->insert(beast::http::field::authorization , "Bot " + m_Token);
req->body() = content;
req->prepare_payload();
return req;
}
void Http::SendRequest(beast::http::verb const method, std::string const &url,
std::string const &content, ResponseCallback_t &&callback)
{
Logger::Get()->Log(LogLevel::DEBUG, "Http::SendRequest");
SharedRequest_t req = PrepareRequest(method, url, content);
m_Queue.push(new QueueEntry(req, std::move(callback)));
}
Http::ResponseCallback_t Http::CreateResponseCallback(ResponseCb_t &&callback)
{
if (callback == nullptr)
return nullptr;
return [callback](Streambuf_t &sb, Response_t &resp)
{
callback({ resp.result_int(), resp.reason().to_string(),
beast::buffers_to_string(resp.body().data()), beast::buffers_to_string(sb.data()) });
};
}
void Http::Get(std::string const &url, ResponseCb_t &&callback)
{
Logger::Get()->Log(LogLevel::DEBUG, "Http::Get");
SendRequest(beast::http::verb::get, url, "",
CreateResponseCallback(std::move(callback)));
}
void Http::Post(std::string const &url, std::string const &content,
ResponseCb_t &&callback /*= nullptr*/)
{
Logger::Get()->Log(LogLevel::DEBUG, "Http::Post");
SendRequest(beast::http::verb::post, url, content,
CreateResponseCallback(std::move(callback)));
}
void Http::Delete(std::string const &url)
{
Logger::Get()->Log(LogLevel::DEBUG, "Http::Delete");
SendRequest(beast::http::verb::delete_, url, "", nullptr);
}
void Http::Put(std::string const &url)
{
Logger::Get()->Log(LogLevel::DEBUG, "Http::Put");
SendRequest(beast::http::verb::put, url, "", nullptr);
}
void Http::Patch(std::string const &url, std::string const &content)
{
Logger::Get()->Log(LogLevel::DEBUG, "Http::Patch");
SendRequest(beast::http::verb::patch, url, content, nullptr);
}
<commit_msg>use port instead of service name on resolve<commit_after>#include "Http.hpp"
#include "Logger.hpp"
#include "version.hpp"
#include <boost/asio/system_timer.hpp>
#include <boost/spirit/include/qi.hpp>
#include <date/date.h>
Http::Http(std::string token) :
m_SslContext(asio::ssl::context::sslv23),
m_Token(token),
m_NetworkThreadRunning(true),
m_NetworkThread(std::bind(&Http::NetworkThreadFunc, this))
{
}
Http::~Http()
{
m_NetworkThreadRunning = false;
m_NetworkThread.join();
// drain requests queue
QueueEntry *entry;
while (m_Queue.pop(entry))
delete entry;
}
void Http::NetworkThreadFunc()
{
std::unordered_map<std::string, TimePoint_t> path_ratelimit;
unsigned int retry_counter = 0;
unsigned int const MaxRetries = 3;
bool skip_entry = false;
if (!Connect())
return;
while (m_NetworkThreadRunning)
{
TimePoint_t current_time = std::chrono::steady_clock::now();
std::list<QueueEntry*> skipped_entries;
QueueEntry *entry;
while (m_Queue.pop(entry))
{
// check if we're rate-limited
auto pr_it = path_ratelimit.find(entry->Request->target().to_string());
if (pr_it != path_ratelimit.end())
{
// rate-limit for this path exists
// are we still within the rate-limit timepoint?
if (current_time < pr_it->second)
{
// yes, ignore this request for now
skipped_entries.push_back(entry);
continue;
}
// no, delete rate-limit and go on
path_ratelimit.erase(pr_it);
Logger::Get()->Log(LogLevel::DEBUG, "rate-limit on path '{}' lifted",
entry->Request->target().to_string());
}
boost::system::error_code error_code;
Response_t response;
Streambuf_t sb;
retry_counter = 0;
skip_entry = false;
do
{
bool do_reconnect = false;
beast::http::write(*m_SslStream, *entry->Request, error_code);
if (error_code)
{
Logger::Get()->Log(LogLevel::ERROR, "Error while sending HTTP {} request to '{}': {}",
entry->Request->method_string().to_string(),
entry->Request->target().to_string(),
error_code.message());
do_reconnect = true;
}
else
{
beast::http::read(*m_SslStream, sb, response, error_code);
if (error_code)
{
Logger::Get()->Log(LogLevel::ERROR, "Error while retrieving HTTP {} response from '{}': {}",
entry->Request->method_string().to_string(),
entry->Request->target().to_string(),
error_code.message());
do_reconnect = true;
}
}
if (do_reconnect)
{
if (retry_counter++ >= MaxRetries || !ReconnectRetry())
{
// we failed to reconnect, discard this request
Logger::Get()->Log(LogLevel::WARNING, "Failed to send request, discarding");
skip_entry = true;
break; // break out of do-while loop
}
}
} while (error_code);
if (skip_entry)
continue; // continue queue loop
auto it_r = response.find("X-RateLimit-Remaining");
if (it_r != response.end())
{
if (it_r->value().compare("0") == 0)
{
// we're now officially rate-limited
// the next call to this path will fail
std::string limited_url = entry->Request->target().to_string();
auto lit = path_ratelimit.find(limited_url);
if (lit != path_ratelimit.end())
{
Logger::Get()->Log(LogLevel::ERROR,
"Error while processing rate-limit: already rate-limited path '{}'",
limited_url);
// skip this request, we'll re-add it to the queue to retry later
skipped_entries.push_back(entry);
continue;
}
it_r = response.find("X-RateLimit-Reset");
if (it_r != response.end())
{
auto date_str = response.find(boost::beast::http::field::date)->value().to_string();
std::istringstream date_ss{ date_str };
date::sys_seconds date_utc;
date_ss >> date::parse("%a, %d %b %Y %T %Z", date_utc); // RFC2616 HTTP header date format
std::chrono::seconds timepoint_now = date_utc.time_since_epoch();
Logger::Get()->Log(LogLevel::DEBUG, "rate-limiting path {} until {} (current time: {})",
limited_url,
it_r->value().to_string(),
timepoint_now.count());
string const &reset_time_str = it_r->value().to_string();
long long reset_time_secs = 0;
boost::spirit::qi::parse(reset_time_str.begin(), reset_time_str.end(),
boost::spirit::qi::any_int_parser<long long>(),
reset_time_secs);
TimePoint_t reset_time = std::chrono::steady_clock::now()
+ std::chrono::seconds(reset_time_secs - timepoint_now.count() + 1); // add a buffer of 1 second
path_ratelimit.insert({ limited_url, reset_time });
}
}
}
if (entry->Callback)
entry->Callback(sb, response);
delete entry;
entry = nullptr;
}
// add skipped entries back to queue
for (auto e : skipped_entries)
m_Queue.push(e);
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
Disconnect();
}
bool Http::Connect()
{
Logger::Get()->Log(LogLevel::DEBUG, "Http::Connect");
// connect to REST API
asio::ip::tcp::resolver r{ m_IoService };
boost::system::error_code error;
auto target = r.resolve("discordapp.com", "443", error);
if (error)
{
Logger::Get()->Log(LogLevel::ERROR, "Can't resolve Discord API URL: {} ({})",
error.message(), error.value());
return false;
}
m_SslStream.reset(new SslStream_t(m_IoService, m_SslContext));
asio::connect(m_SslStream->lowest_layer(), target, error);
if (error)
{
Logger::Get()->Log(LogLevel::ERROR, "Can't connect to Discord API: {} ({})",
error.message(), error.value());
return false;
}
// SSL handshake
m_SslStream->set_verify_mode(asio::ssl::verify_none, error);
if (error)
{
Logger::Get()->Log(LogLevel::ERROR,
"Can't configure SSL stream peer verification mode for Discord API: {} ({})",
error.message(), error.value());
return false;
}
m_SslStream->handshake(asio::ssl::stream_base::client, error);
if (error)
{
Logger::Get()->Log(LogLevel::ERROR, "Can't establish secured connection to Discord API: {} ({})",
error.message(), error.value());
return false;
}
return true;
}
void Http::Disconnect()
{
Logger::Get()->Log(LogLevel::DEBUG, "Http::Disconnect");
boost::system::error_code error;
m_SslStream->shutdown(error);
if (error && error != boost::asio::error::eof)
{
Logger::Get()->Log(LogLevel::WARNING, "Error while shutting down SSL on HTTP connection: {} ({})",
error.message(), error.value());
}
m_SslStream->lowest_layer().shutdown(asio::ip::tcp::socket::shutdown_both, error);
if (error && error != boost::asio::error::eof)
{
Logger::Get()->Log(LogLevel::WARNING, "Error while shutting down HTTP connection: {} ({})",
error.message(), error.value());
}
m_SslStream->lowest_layer().close(error);
if (error)
{
Logger::Get()->Log(LogLevel::WARNING, "Error while closing HTTP connection: {} ({})",
error.message(), error.value());
}
}
bool Http::ReconnectRetry()
{
Logger::Get()->Log(LogLevel::DEBUG, "Http::ReconnectRetry");
unsigned int reconnect_counter = 0;
do
{
Logger::Get()->Log(LogLevel::INFO, "trying reconnect #{}...", reconnect_counter + 1);
Disconnect();
if (Connect())
{
Logger::Get()->Log(LogLevel::INFO, "reconnect succeeded, resending request");
return true;
}
else
{
unsigned int seconds_to_wait = static_cast<unsigned int>(std::pow(2U, reconnect_counter));
Logger::Get()->Log(LogLevel::WARNING, "reconnect failed, waiting {} seconds...", seconds_to_wait);
std::this_thread::sleep_for(std::chrono::seconds(seconds_to_wait));
}
} while (++reconnect_counter < 3);
Logger::Get()->Log(LogLevel::ERROR, "Could not reconnect to Discord");
return false;
}
Http::SharedRequest_t Http::PrepareRequest(beast::http::verb const method,
std::string const &url, std::string const &content)
{
Logger::Get()->Log(LogLevel::DEBUG, "Http::PrepareRequest");
auto req = std::make_shared<Request_t>();
req->method(method);
req->target("/api/v6" + url);
req->version(11);
req->insert(beast::http::field::connection, "keep-alive");
req->insert(beast::http::field::host, "discordapp.com");
req->insert(beast::http::field::user_agent,
"DiscordBot (github.com/maddinat0r/samp-discord-connector, " PLUGIN_VERSION ")");
if (!content.empty())
req->insert(beast::http::field::content_type, "application/json");
req->insert(beast::http::field::authorization , "Bot " + m_Token);
req->body() = content;
req->prepare_payload();
return req;
}
void Http::SendRequest(beast::http::verb const method, std::string const &url,
std::string const &content, ResponseCallback_t &&callback)
{
Logger::Get()->Log(LogLevel::DEBUG, "Http::SendRequest");
SharedRequest_t req = PrepareRequest(method, url, content);
m_Queue.push(new QueueEntry(req, std::move(callback)));
}
Http::ResponseCallback_t Http::CreateResponseCallback(ResponseCb_t &&callback)
{
if (callback == nullptr)
return nullptr;
return [callback](Streambuf_t &sb, Response_t &resp)
{
callback({ resp.result_int(), resp.reason().to_string(),
beast::buffers_to_string(resp.body().data()), beast::buffers_to_string(sb.data()) });
};
}
void Http::Get(std::string const &url, ResponseCb_t &&callback)
{
Logger::Get()->Log(LogLevel::DEBUG, "Http::Get");
SendRequest(beast::http::verb::get, url, "",
CreateResponseCallback(std::move(callback)));
}
void Http::Post(std::string const &url, std::string const &content,
ResponseCb_t &&callback /*= nullptr*/)
{
Logger::Get()->Log(LogLevel::DEBUG, "Http::Post");
SendRequest(beast::http::verb::post, url, content,
CreateResponseCallback(std::move(callback)));
}
void Http::Delete(std::string const &url)
{
Logger::Get()->Log(LogLevel::DEBUG, "Http::Delete");
SendRequest(beast::http::verb::delete_, url, "", nullptr);
}
void Http::Put(std::string const &url)
{
Logger::Get()->Log(LogLevel::DEBUG, "Http::Put");
SendRequest(beast::http::verb::put, url, "", nullptr);
}
void Http::Patch(std::string const &url, std::string const &content)
{
Logger::Get()->Log(LogLevel::DEBUG, "Http::Patch");
SendRequest(beast::http::verb::patch, url, content, nullptr);
}
<|endoftext|> |
<commit_before>/* vim: set ai et ts=4 sw=4: */
#include <HttpServer.h>
#include <PersistentStorage.h>
#include <PgsqlServer.h>
#include <TcpServer.h>
#include <atomic>
#include <iostream>
#include <map>
#include <signal.h>
#include <sstream>
#include <string>
#include <unistd.h>
#include <utility>
PersistentStorage storage;
static std::atomic_bool terminate_flag(false);
static void httpIndexGetHandler(const HttpRequest&, HttpResponse& resp) {
resp.setStatus(HTTP_STATUS_OK);
std::ostringstream oss;
oss << "HurmaDB is " << (terminate_flag.load() ? "terminating" : "running") << "!\n\n";
resp.setBody(oss.str());
}
static void httpKVGetHandler(const HttpRequest& req, HttpResponse& resp) {
bool found;
const std::string& key = req.getQueryMatch(0);
const std::string& value = storage.get(key, &found);
resp.setStatus(found ? HTTP_STATUS_OK : HTTP_STATUS_NOT_FOUND);
resp.setBody(value);
}
/**
* @todo Rewrite using Storage::getRange instead of deprecated getRangeJson
*/
static void httpKVGetRangeHandler(const HttpRequest& req, HttpResponse& resp) {
const std::string& key_from = req.getQueryMatch(0);
const std::string& key_to = req.getQueryMatch(1);
const std::string& valuesJson = storage.getRangeJson(key_from, key_to);
resp.setStatus(HTTP_STATUS_OK);
resp.setBody(valuesJson);
}
static void httpKVPutHandler(const HttpRequest& req, HttpResponse& resp) {
const std::string& key = req.getQueryMatch(0);
const std::string& value = req.getBody();
bool ok = true;
try {
storage.set(key, value);
} catch(const std::runtime_error& e) {
// Most likely validation failed
ok = false;
}
resp.setStatus(ok ? HTTP_STATUS_OK : HTTP_STATUS_BAD_REQUEST);
}
static void httpKVDeleteHandler(const HttpRequest& req, HttpResponse& resp) {
bool found = false;
const std::string& key = req.getQueryMatch(0);
storage.del(key, &found);
resp.setStatus(found ? HTTP_STATUS_OK : HTTP_STATUS_NOT_FOUND);
}
/* Required for generating code coverage report */
static void httpStopPutHandler(const HttpRequest&, HttpResponse& resp) {
terminate_flag.store(true);
resp.setStatus(HTTP_STATUS_OK);
}
int main(int argc, char** argv) {
int c;
bool httpPortSet = false;
bool pgsqlPortSet = false;
int httpPort = 8080;
int pgsqlPort = 5432;
while((c = getopt(argc, argv, "p:h:")) != -1)
switch(c) {
case 'h':
httpPort = atoi(optarg);
httpPortSet = true;
break;
case 'p':
pgsqlPort = atoi(optarg);
pgsqlPortSet = true;
break;
}
if((!httpPortSet) || (!pgsqlPortSet)) {
std::cerr << "Usage: " << argv[0] << " -h http_port -p pgsql_port" << std::endl;
return 2;
}
if(httpPort <= 0 || httpPort >= 65536) {
std::cerr << "Invalid HTTP port number!" << std::endl;
return 2;
}
if(pgsqlPort <= 0 || pgsqlPort >= 65536) {
std::cerr << "Invalid PgSql port number!" << std::endl;
return 2;
}
HttpServer httpServer;
PgsqlServer pgsqlServer(&storage);
httpServer.addHandler(HTTP_GET, "(?i)^/$", &httpIndexGetHandler);
httpServer.addHandler(HTTP_PUT, "(?i)^/v1/_stop/?$", &httpStopPutHandler);
httpServer.addHandler(HTTP_GET, "(?i)^/v1/kv/([\\w-]+)/?$", &httpKVGetHandler);
httpServer.addHandler(HTTP_GET, "(?i)^/v1/kv/([\\w-]+)/([\\w-]+)/?$", &httpKVGetRangeHandler);
httpServer.addHandler(HTTP_PUT, "(?i)^/v1/kv/([\\w-]+)/?$", &httpKVPutHandler);
httpServer.addHandler(HTTP_DELETE, "(?i)^/v1/kv/([\\w-]+)/?$", &httpKVDeleteHandler);
std::cout << "Starting HTTP server on port " << httpPort << std::endl;
httpServer.listen("127.0.0.1", httpPort);
std::cout << "Starting PgSql server on port " << pgsqlPort << std::endl;
pgsqlServer.listen("127.0.0.1", pgsqlPort);
// Unlike POSIX accept() procedure none of these .accept methods is blocking
while(!terminate_flag.load()) {
// TODO: This seems to be a bottleneck during test execution.
// Run every accept() on a separate thread to speed things up.
pgsqlServer.accept(terminate_flag);
httpServer.accept(terminate_flag);
}
return 0;
}
<commit_msg>Doxygen: add a simple main page<commit_after>/* vim: set ai et ts=4 sw=4: */
/**
* @mainpage HurmaDB
*
* HurmaDB is an experimental database.
*
* @todo Write a better main page.
*/
#include <HttpServer.h>
#include <PersistentStorage.h>
#include <PgsqlServer.h>
#include <TcpServer.h>
#include <atomic>
#include <iostream>
#include <map>
#include <signal.h>
#include <sstream>
#include <string>
#include <unistd.h>
#include <utility>
PersistentStorage storage;
static std::atomic_bool terminate_flag(false);
static void httpIndexGetHandler(const HttpRequest&, HttpResponse& resp) {
resp.setStatus(HTTP_STATUS_OK);
std::ostringstream oss;
oss << "HurmaDB is " << (terminate_flag.load() ? "terminating" : "running") << "!\n\n";
resp.setBody(oss.str());
}
static void httpKVGetHandler(const HttpRequest& req, HttpResponse& resp) {
bool found;
const std::string& key = req.getQueryMatch(0);
const std::string& value = storage.get(key, &found);
resp.setStatus(found ? HTTP_STATUS_OK : HTTP_STATUS_NOT_FOUND);
resp.setBody(value);
}
/**
* @todo Rewrite using Storage::getRange instead of deprecated getRangeJson
*/
static void httpKVGetRangeHandler(const HttpRequest& req, HttpResponse& resp) {
const std::string& key_from = req.getQueryMatch(0);
const std::string& key_to = req.getQueryMatch(1);
const std::string& valuesJson = storage.getRangeJson(key_from, key_to);
resp.setStatus(HTTP_STATUS_OK);
resp.setBody(valuesJson);
}
static void httpKVPutHandler(const HttpRequest& req, HttpResponse& resp) {
const std::string& key = req.getQueryMatch(0);
const std::string& value = req.getBody();
bool ok = true;
try {
storage.set(key, value);
} catch(const std::runtime_error& e) {
// Most likely validation failed
ok = false;
}
resp.setStatus(ok ? HTTP_STATUS_OK : HTTP_STATUS_BAD_REQUEST);
}
static void httpKVDeleteHandler(const HttpRequest& req, HttpResponse& resp) {
bool found = false;
const std::string& key = req.getQueryMatch(0);
storage.del(key, &found);
resp.setStatus(found ? HTTP_STATUS_OK : HTTP_STATUS_NOT_FOUND);
}
/* Required for generating code coverage report */
static void httpStopPutHandler(const HttpRequest&, HttpResponse& resp) {
terminate_flag.store(true);
resp.setStatus(HTTP_STATUS_OK);
}
int main(int argc, char** argv) {
int c;
bool httpPortSet = false;
bool pgsqlPortSet = false;
int httpPort = 8080;
int pgsqlPort = 5432;
while((c = getopt(argc, argv, "p:h:")) != -1)
switch(c) {
case 'h':
httpPort = atoi(optarg);
httpPortSet = true;
break;
case 'p':
pgsqlPort = atoi(optarg);
pgsqlPortSet = true;
break;
}
if((!httpPortSet) || (!pgsqlPortSet)) {
std::cerr << "Usage: " << argv[0] << " -h http_port -p pgsql_port" << std::endl;
return 2;
}
if(httpPort <= 0 || httpPort >= 65536) {
std::cerr << "Invalid HTTP port number!" << std::endl;
return 2;
}
if(pgsqlPort <= 0 || pgsqlPort >= 65536) {
std::cerr << "Invalid PgSql port number!" << std::endl;
return 2;
}
HttpServer httpServer;
PgsqlServer pgsqlServer(&storage);
httpServer.addHandler(HTTP_GET, "(?i)^/$", &httpIndexGetHandler);
httpServer.addHandler(HTTP_PUT, "(?i)^/v1/_stop/?$", &httpStopPutHandler);
httpServer.addHandler(HTTP_GET, "(?i)^/v1/kv/([\\w-]+)/?$", &httpKVGetHandler);
httpServer.addHandler(HTTP_GET, "(?i)^/v1/kv/([\\w-]+)/([\\w-]+)/?$", &httpKVGetRangeHandler);
httpServer.addHandler(HTTP_PUT, "(?i)^/v1/kv/([\\w-]+)/?$", &httpKVPutHandler);
httpServer.addHandler(HTTP_DELETE, "(?i)^/v1/kv/([\\w-]+)/?$", &httpKVDeleteHandler);
std::cout << "Starting HTTP server on port " << httpPort << std::endl;
httpServer.listen("127.0.0.1", httpPort);
std::cout << "Starting PgSql server on port " << pgsqlPort << std::endl;
pgsqlServer.listen("127.0.0.1", pgsqlPort);
// Unlike POSIX accept() procedure none of these .accept methods is blocking
while(!terminate_flag.load()) {
// TODO: This seems to be a bottleneck during test execution.
// Run every accept() on a separate thread to speed things up.
pgsqlServer.accept(terminate_flag);
httpServer.accept(terminate_flag);
}
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include "Util.h"
#include "System.h"
using namespace std;
int main(int argc, char** argv)
{
System::get(new System());
if(System::ptr() && System::get().hasError()) {
std::cout << System::get().getError() << std::endl;
return 1;
}
return System::get().run() ? 0 : 1;
}
<commit_msg>const arg and exception change in main()<commit_after>#include <iostream>
#include "Util.h"
#include "System.h"
using namespace std;
int main(int argc, const char** argv)
{
try{
System::get(new System());
}catch(const std::exception& e){
std::cout << e.what() << std::endl;
return 1;
}
if(System::get().hasError()) {
std::cout << System::get().getError() << std::endl;
return 1;
}
return System::get().run() ? 0 : 1;
}
<|endoftext|> |
<commit_before>#include "PeLdr.h"
#include "Debug.h"
static
INT ShowUsage()
{
printf("-- PE Loader Sample --\n\n");
printf("PeLdr [PE-File]\n");
printf("\n");
return 0;
}
int wmain(int argc, wchar_t *argv[])
{
PE_LDR_PARAM peLdr;
if(argc < 2)
return ShowUsage();
PeLdrInit(&peLdr);
PeLdrSetExecutablePath(&peLdr, argv[1]);
PeLdrStart(&peLdr);
return 0;
}<commit_msg>Update Main.cpp<commit_after>#include "PeLdr.h"
#include "Debug.h"
int wmain()
{
PE_LDR_PARAM peLdr;
PeLdrInit(&peLdr);
PeLdrStart(&peLdr);
return 0;
}
<|endoftext|> |
<commit_before>// Copyright 2022 The SiliFuzz Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "./tool_libs/snap_group.h"
#include <sys/mman.h>
#include <cstddef>
#include <string>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/container/flat_hash_set.h"
#include "absl/status/status.h"
#include "./common/mapped_memory_map.h"
#include "./common/snapshot_test_util.h"
#include "./util/testing/status_macros.h"
#include "./util/testing/status_matchers.h"
namespace silifuzz {
namespace {
using ::silifuzz::testing::StatusIs;
using ::testing::Contains;
using ::testing::HasSubstr;
using ::testing::IsEmpty;
using ::testing::Not;
constexpr size_t kNumMappings1 = 2;
const Snap::MemoryMapping kMemoryMappings1[kNumMappings1] = {
{.start_address = 0x1234000ULL,
.num_bytes = 0x4000,
.perms = PROT_READ | PROT_EXEC},
{.start_address = 0x5678000ULL,
.num_bytes = 0x1000,
.perms = PROT_READ | PROT_WRITE},
};
const Snap kSnap1{
.id = "snap1",
.memory_mappings =
{
.size = kNumMappings1,
.elements = kMemoryMappings1,
},
};
// No conflict with kSnap1.
constexpr size_t kNumMappings2 = 2;
const Snap::MemoryMapping kMemoryMappings2[kNumMappings2] = {
{.start_address = 0x3456000ULL,
.num_bytes = 0x4000,
.perms = PROT_READ | PROT_EXEC},
{.start_address = 0x789a000ULL,
.num_bytes = 0x1000,
.perms = PROT_READ | PROT_WRITE},
};
const Snap kSnap2{
.id = "snap2",
.memory_mappings =
{
.size = kNumMappings2,
.elements = kMemoryMappings2,
},
};
// Read-only mapping conflict with kSnap1
constexpr size_t kNumMappings3 = 2;
const Snap::MemoryMapping kMemoryMappings3[kNumMappings3] = {
{.start_address = 0x1234000ULL,
.num_bytes = 0x4000,
.perms = PROT_READ | PROT_EXEC},
{.start_address = 0x6789000ULL,
.num_bytes = 8192,
.perms = PROT_READ | PROT_WRITE},
};
const Snap kSnap3{
.id = "snap3",
.memory_mappings =
{
.size = kNumMappings3,
.elements = kMemoryMappings3,
},
};
// Writable mapping conflict with kSnap1, same permissions.
constexpr size_t kNumMappings4 = 2;
const Snap::MemoryMapping kMemoryMappings4[kNumMappings4] = {
{.start_address = 0x2345000ULL,
.num_bytes = 0x4000,
.perms = PROT_READ | PROT_EXEC},
{.start_address = 0x5678000ULL,
.num_bytes = 0x1000,
.perms = PROT_READ | PROT_WRITE},
};
const Snap kSnap4{
.id = "snap4",
.memory_mappings =
{
.size = kNumMappings4,
.elements = kMemoryMappings4,
},
};
// Writable mapping conflict with kSnap1, different permissions.
// Read-only conflict with kSnap2.
constexpr size_t kNumMappings5 = 2;
const Snap::MemoryMapping kMemoryMappings5[kNumMappings5] = {
{.start_address = 0x3456000ULL,
.num_bytes = 0x4000,
.perms = PROT_READ | PROT_EXEC},
{.start_address = 0x5678000ULL,
.num_bytes = 0x1000,
.perms = PROT_READ | PROT_WRITE | PROT_EXEC},
};
const Snap kSnap5{
.id = "snap5",
.memory_mappings =
{
.size = kNumMappings5,
.elements = kMemoryMappings5,
},
};
TEST(SnapshotSummary, ConstructFromSnapshot) {
Snapshot snapshot = TestSnapshots::Create(TestSnapshots::kEndsAsExpected);
SnapshotGroup::SnapshotSummary memory_summary(snapshot);
EXPECT_EQ(memory_summary.id(), snapshot.id());
EXPECT_EQ(memory_summary.memory_mappings(), snapshot.memory_mappings());
}
TEST(SnapshotSummary, ConstructFromSnap) {
SnapshotGroup::SnapshotSummary memory_summary(kSnap1);
EXPECT_EQ(memory_summary.id(), kSnap1.id);
ASSERT_EQ(memory_summary.memory_mappings().size(), kNumMappings1);
for (size_t i = 0; i < kNumMappings1; ++i) {
const auto& mapping = memory_summary.memory_mappings()[i];
const Snap::MemoryMapping expected = kSnap1.memory_mappings.elements[i];
EXPECT_EQ(mapping.start_address(), expected.start_address);
EXPECT_EQ(mapping.num_bytes(), expected.num_bytes);
EXPECT_EQ(mapping.perms().ToMProtect(), expected.perms);
}
}
TEST(SnapshotGroup, CanAddSnapshotIntoEmptyGroup) {
SnapshotGroup snapshot_group(SnapshotGroup::kNoConflictAllowed);
SnapshotGroup::SnapshotSummary snapshot_summary_1(kSnap1);
EXPECT_OK(snapshot_group.CanAddSnapshot(snapshot_summary_1));
snapshot_group.AddSnapshot(snapshot_summary_1);
EXPECT_EQ(snapshot_group.size(), 1);
}
TEST(SnapshotGroup, PersistentConflict) {
MappedMemoryMap m;
m.AddNew(0ULL, ~0ULL, MemoryPerms::AllPlusMapped());
SnapshotGroup snapshot_group(SnapshotGroup::kNoConflictAllowed, m);
SnapshotGroup::SnapshotSummary snapshot_summary_1(kSnap1);
EXPECT_THAT(snapshot_group.CanAddSnapshot(snapshot_summary_1),
StatusIs(absl::StatusCode::kAlreadyExists,
HasSubstr("mapping conflict")));
}
TEST(SnapshotGroup, CanAddSnapshotNoConflict) {
SnapshotGroup snapshot_group(SnapshotGroup::kNoConflictAllowed);
SnapshotGroup::SnapshotSummary snapshot_summary_1(kSnap1);
snapshot_group.AddSnapshot(snapshot_summary_1);
SnapshotGroup::SnapshotSummary snapshot_summary_2(kSnap2);
EXPECT_OK(snapshot_group.CanAddSnapshot(snapshot_summary_2));
snapshot_group.AddSnapshot(snapshot_summary_2);
EXPECT_EQ(snapshot_group.size(), 2);
}
TEST(SnapshotGroup, CannotAddSnapshotWithReadOnlyConflict) {
SnapshotGroup snapshot_group(SnapshotGroup::kNoConflictAllowed);
SnapshotGroup::SnapshotSummary snapshot_summary_1(kSnap1);
snapshot_group.AddSnapshot(snapshot_summary_1);
SnapshotGroup::SnapshotSummary snapshot_summary_3(kSnap3);
EXPECT_THAT(snapshot_group.CanAddSnapshot(snapshot_summary_3),
StatusIs(absl::StatusCode::kAlreadyExists));
EXPECT_EQ(snapshot_group.size(), 1);
}
TEST(SnapshotGroup, CanAddSnapshotWriteConflictSamePerms) {
SnapshotGroup snapshot_group(SnapshotGroup::kAllowWriteConflictsWithSamePerm);
SnapshotGroup::SnapshotSummary snapshot_summary_1(kSnap1);
snapshot_group.AddSnapshot(snapshot_summary_1);
SnapshotGroup::SnapshotSummary snapshot_summary_4(kSnap4);
EXPECT_OK(snapshot_group.CanAddSnapshot(snapshot_summary_4));
snapshot_group.AddSnapshot(snapshot_summary_4);
EXPECT_EQ(snapshot_group.size(), 2);
}
TEST(SnapshotGroup, CannotAddSnapshotWriteConflictDifferentPerms) {
SnapshotGroup snapshot_group(SnapshotGroup::kAllowWriteConflictsWithSamePerm);
SnapshotGroup::SnapshotSummary snapshot_summary_1(kSnap1);
snapshot_group.AddSnapshot(snapshot_summary_1);
SnapshotGroup::SnapshotSummary snapshot_summary_5(kSnap5);
EXPECT_THAT(snapshot_group.CanAddSnapshot(snapshot_summary_5),
StatusIs(absl::StatusCode::kAlreadyExists));
EXPECT_EQ(snapshot_group.size(), 1);
}
TEST(SnapPartition, OneSnapPerGroup) {
const SnapshotGroup::SnapshotSummary snapshot_summary_1(kSnap1);
const SnapshotGroup::SnapshotSummary snapshot_summary_2(kSnap2);
const SnapshotGroup::SnapshotSummary snapshot_summary_3(kSnap3);
const SnapshotGroup::SnapshotSummary snapshot_summary_4(kSnap4);
const SnapshotGroup::SnapshotSummary snapshot_summary_5(kSnap5);
const SnapshotGroup::SnapshotSummaryList kSnapshotSummaryList{
snapshot_summary_1, snapshot_summary_2, snapshot_summary_3,
snapshot_summary_4, snapshot_summary_5};
// Number of groups == Number of Snaphots. This should trivially
// put exactly 1 snap per group.
SnapshotPartition partition(kSnapshotSummaryList.size(),
SnapshotGroup::kAllowWriteConflictsWithSamePerm);
SnapshotGroup::SnapshotSummaryList rejected =
partition.PartitionSnapshots(kSnapshotSummaryList);
EXPECT_THAT(rejected, IsEmpty());
for (const auto& group : partition.snapshot_groups()) {
EXPECT_EQ(group.size(), 1);
}
}
// Partition a small example of snapshots with various memory
// mapping conflicts. The example is constructed so that all
// snapshots can be added.
TEST(SnapshotGroup, PartitionSmallExample) {
const SnapshotGroup::SnapshotSummary snapshot_summary_1(kSnap1);
const SnapshotGroup::SnapshotSummary snapshot_summary_2(kSnap2);
const SnapshotGroup::SnapshotSummary snapshot_summary_3(kSnap3);
const SnapshotGroup::SnapshotSummary snapshot_summary_4(kSnap4);
const SnapshotGroup::SnapshotSummary snapshot_summary_5(kSnap5);
const SnapshotGroup::SnapshotSummaryList kSnapshotSummaryList{
snapshot_summary_1, snapshot_summary_2, snapshot_summary_3,
snapshot_summary_4, snapshot_summary_5};
constexpr int kNumGroups = 3;
SnapshotPartition partition(kNumGroups,
SnapshotGroup::kAllowWriteConflictsWithSamePerm);
SnapshotGroup::SnapshotSummaryList rejected =
partition.PartitionSnapshots(kSnapshotSummaryList);
EXPECT_TRUE(rejected.empty());
absl::flat_hash_set<SnapshotGroup::Id> grouped_ids;
const size_t group_size_lower_bound =
kSnapshotSummaryList.size() / kNumGroups;
const size_t group_size_upper_bound =
(kSnapshotSummaryList.size() + kNumGroups - 1) / kNumGroups;
// We expect a roughly even distribution.
for (const auto& group : partition.snapshot_groups()) {
EXPECT_GE(group.size(), group_size_lower_bound);
EXPECT_LE(group.size(), group_size_upper_bound);
const SnapshotGroup::IdList id_list = group.id_list();
grouped_ids.insert(id_list.begin(), id_list.end());
}
// Check that all snapshots are indeed added.
EXPECT_EQ(grouped_ids.size(), kSnapshotSummaryList.size());
for (const auto& summary : kSnapshotSummaryList) {
EXPECT_THAT(grouped_ids, Contains(summary.id()));
}
}
// Partition a small example of snapshots with various memory
// mapping conflicts. The example is constructed so that not
// all snapshots can be added as there is too few groups.
TEST(SnapshotGroup, PartitionTooFewGroupsToFit) {
const SnapshotGroup::SnapshotSummary snapshot_summary_1(kSnap1);
const SnapshotGroup::SnapshotSummary snapshot_summary_2(kSnap2);
const SnapshotGroup::SnapshotSummary snapshot_summary_3(kSnap3);
const SnapshotGroup::SnapshotSummary snapshot_summary_4(kSnap4);
const SnapshotGroup::SnapshotSummary snapshot_summary_5(kSnap5);
const SnapshotGroup::SnapshotSummaryList kSnapshotSummaryList{
snapshot_summary_1, snapshot_summary_2, snapshot_summary_3,
snapshot_summary_4, snapshot_summary_5};
// We need 3 groups at least.
constexpr int kNumGroups = 2;
SnapshotPartition partition(kNumGroups,
SnapshotGroup::kAllowWriteConflictsWithSamePerm);
SnapshotGroup::SnapshotSummaryList rejected =
partition.PartitionSnapshots(kSnapshotSummaryList);
// There should be rejected snapshots.
EXPECT_THAT(rejected, Not(IsEmpty()));
}
} // namespace
} // namespace silifuzz
<commit_msg>Migrate snap_group_test to exclusively use Snapshot as the data holder<commit_after>// Copyright 2022 The SiliFuzz Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "./tool_libs/snap_group.h"
#include <sys/mman.h>
#include <cstddef>
#include <string>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/container/flat_hash_set.h"
#include "absl/status/status.h"
#include "./common/mapped_memory_map.h"
#include "./common/snapshot_test_util.h"
#include "./util/testing/status_macros.h"
#include "./util/testing/status_matchers.h"
namespace silifuzz {
namespace {
using ::silifuzz::testing::StatusIs;
using ::testing::Contains;
using ::testing::HasSubstr;
using ::testing::IsEmpty;
using ::testing::Not;
const std::vector<Snapshot>& TestSnapshots() {
static std::vector<Snapshot>* snapshots = [] {
Snapshot s1(Snapshot::Architecture::kX86_64, "snap1");
s1.add_memory_mapping(
MemoryMapping::MakeSized(0x1234000ULL, 0x4000, MemoryPerms::XR()));
s1.add_memory_mapping(
MemoryMapping::MakeSized(0x5678000ULL, 0x1000, MemoryPerms::RW()));
// No conflict with kSnap1.
Snapshot s2(Snapshot::Architecture::kX86_64, "snap2");
s2.add_memory_mapping(
MemoryMapping::MakeSized(0x3456000ULL, 0x4000, MemoryPerms::XR()));
s2.add_memory_mapping(
MemoryMapping::MakeSized(0x789a000ULL, 0x1000, MemoryPerms::RW()));
// Read-only mapping conflict with kSnap1
Snapshot s3(Snapshot::Architecture::kX86_64, "snap3");
s3.add_memory_mapping(
MemoryMapping::MakeSized(0x1234000ULL, 0x4000, MemoryPerms::XR()));
s3.add_memory_mapping(
MemoryMapping::MakeSized(0x6789000ULL, 0x2000, MemoryPerms::RW()));
// Writable mapping conflict with kSnap1, same permissions.
Snapshot s4(Snapshot::Architecture::kX86_64, "snap4");
s4.add_memory_mapping(
MemoryMapping::MakeSized(0x2345000ULL, 0x4000, MemoryPerms::XR()));
s4.add_memory_mapping(
MemoryMapping::MakeSized(0x5678000ULL, 0x2000, MemoryPerms::RW()));
// Writable mapping conflict with kSnap1, different permissions.
// Read-only conflict with kSnap2.
Snapshot s5(Snapshot::Architecture::kX86_64, "snap5");
s5.add_memory_mapping(
MemoryMapping::MakeSized(0x3456000ULL, 0x4000, MemoryPerms::XR()));
s5.add_memory_mapping(
MemoryMapping::MakeSized(0x5678000ULL, 0x2000, MemoryPerms::RWX()));
std::vector<Snapshot>* rv = new std::vector<Snapshot>();
rv->push_back(std::move(s1));
rv->push_back(std::move(s2));
rv->push_back(std::move(s3));
rv->push_back(std::move(s4));
rv->push_back(std::move(s5));
return rv;
}();
return *snapshots;
}
TEST(SnapshotSummary, ConstructFromSnapshot) {
Snapshot snapshot = TestSnapshots::Create(TestSnapshots::kEndsAsExpected);
SnapshotGroup::SnapshotSummary memory_summary(snapshot);
EXPECT_EQ(memory_summary.id(), snapshot.id());
EXPECT_EQ(memory_summary.memory_mappings(), snapshot.memory_mappings());
}
TEST(SnapshotGroup, CanAddSnapshotIntoEmptyGroup) {
SnapshotGroup snapshot_group(SnapshotGroup::kNoConflictAllowed);
SnapshotGroup::SnapshotSummary snapshot_summary_1(TestSnapshots()[0]);
EXPECT_OK(snapshot_group.CanAddSnapshot(snapshot_summary_1));
snapshot_group.AddSnapshot(snapshot_summary_1);
EXPECT_EQ(snapshot_group.size(), 1);
}
TEST(SnapshotGroup, PersistentConflict) {
MappedMemoryMap m;
m.AddNew(0ULL, ~0ULL, MemoryPerms::AllPlusMapped());
SnapshotGroup snapshot_group(SnapshotGroup::kNoConflictAllowed, m);
SnapshotGroup::SnapshotSummary snapshot_summary_1(TestSnapshots()[0]);
EXPECT_THAT(snapshot_group.CanAddSnapshot(snapshot_summary_1),
StatusIs(absl::StatusCode::kAlreadyExists,
HasSubstr("mapping conflict")));
}
TEST(SnapshotGroup, CanAddSnapshotNoConflict) {
SnapshotGroup snapshot_group(SnapshotGroup::kNoConflictAllowed);
SnapshotGroup::SnapshotSummary snapshot_summary_1(TestSnapshots()[0]);
snapshot_group.AddSnapshot(snapshot_summary_1);
SnapshotGroup::SnapshotSummary snapshot_summary_2(TestSnapshots()[1]);
EXPECT_OK(snapshot_group.CanAddSnapshot(snapshot_summary_2));
snapshot_group.AddSnapshot(snapshot_summary_2);
EXPECT_EQ(snapshot_group.size(), 2);
}
TEST(SnapshotGroup, CannotAddSnapshotWithReadOnlyConflict) {
SnapshotGroup snapshot_group(SnapshotGroup::kNoConflictAllowed);
SnapshotGroup::SnapshotSummary snapshot_summary_1(TestSnapshots()[0]);
snapshot_group.AddSnapshot(snapshot_summary_1);
SnapshotGroup::SnapshotSummary snapshot_summary_3(TestSnapshots()[2]);
EXPECT_THAT(snapshot_group.CanAddSnapshot(snapshot_summary_3),
StatusIs(absl::StatusCode::kAlreadyExists));
EXPECT_EQ(snapshot_group.size(), 1);
}
TEST(SnapshotGroup, CanAddSnapshotWriteConflictSamePerms) {
SnapshotGroup snapshot_group(SnapshotGroup::kAllowWriteConflictsWithSamePerm);
SnapshotGroup::SnapshotSummary snapshot_summary_1(TestSnapshots()[0]);
snapshot_group.AddSnapshot(snapshot_summary_1);
SnapshotGroup::SnapshotSummary snapshot_summary_4(TestSnapshots()[3]);
EXPECT_OK(snapshot_group.CanAddSnapshot(snapshot_summary_4));
snapshot_group.AddSnapshot(snapshot_summary_4);
EXPECT_EQ(snapshot_group.size(), 2);
}
TEST(SnapshotGroup, CannotAddSnapshotWriteConflictDifferentPerms) {
SnapshotGroup snapshot_group(SnapshotGroup::kAllowWriteConflictsWithSamePerm);
SnapshotGroup::SnapshotSummary snapshot_summary_1(TestSnapshots()[0]);
snapshot_group.AddSnapshot(snapshot_summary_1);
SnapshotGroup::SnapshotSummary snapshot_summary_5(TestSnapshots()[4]);
EXPECT_THAT(snapshot_group.CanAddSnapshot(snapshot_summary_5),
StatusIs(absl::StatusCode::kAlreadyExists));
EXPECT_EQ(snapshot_group.size(), 1);
}
TEST(SnapPartition, OneSnapPerGroup) {
SnapshotGroup::SnapshotSummaryList kSnapshotSummaryList;
for (const auto& s : TestSnapshots()) {
kSnapshotSummaryList.emplace_back(s);
}
// Number of groups == Number of Snaphots. This should trivially
// put exactly 1 snap per group.
SnapshotPartition partition(kSnapshotSummaryList.size(),
SnapshotGroup::kAllowWriteConflictsWithSamePerm);
SnapshotGroup::SnapshotSummaryList rejected =
partition.PartitionSnapshots(kSnapshotSummaryList);
EXPECT_THAT(rejected, IsEmpty());
for (const auto& group : partition.snapshot_groups()) {
EXPECT_EQ(group.size(), 1);
}
}
// Partition a small example of snapshots with various memory
// mapping conflicts. The example is constructed so that all
// snapshots can be added.
TEST(SnapshotGroup, PartitionSmallExample) {
SnapshotGroup::SnapshotSummaryList kSnapshotSummaryList;
for (const auto& s : TestSnapshots()) {
kSnapshotSummaryList.emplace_back(s);
}
constexpr int kNumGroups = 3;
SnapshotPartition partition(kNumGroups,
SnapshotGroup::kAllowWriteConflictsWithSamePerm);
SnapshotGroup::SnapshotSummaryList rejected =
partition.PartitionSnapshots(kSnapshotSummaryList);
EXPECT_TRUE(rejected.empty());
absl::flat_hash_set<SnapshotGroup::Id> grouped_ids;
const size_t group_size_lower_bound =
kSnapshotSummaryList.size() / kNumGroups;
const size_t group_size_upper_bound =
(kSnapshotSummaryList.size() + kNumGroups - 1) / kNumGroups;
// We expect a roughly even distribution.
for (const auto& group : partition.snapshot_groups()) {
EXPECT_GE(group.size(), group_size_lower_bound);
EXPECT_LE(group.size(), group_size_upper_bound);
const SnapshotGroup::IdList id_list = group.id_list();
grouped_ids.insert(id_list.begin(), id_list.end());
}
// Check that all snapshots are indeed added.
EXPECT_EQ(grouped_ids.size(), kSnapshotSummaryList.size());
for (const auto& summary : kSnapshotSummaryList) {
EXPECT_THAT(grouped_ids, Contains(summary.id()));
}
}
// Partition a small example of snapshots with various memory
// mapping conflicts. The example is constructed so that not
// all snapshots can be added as there is too few groups.
TEST(SnapshotGroup, PartitionTooFewGroupsToFit) {
SnapshotGroup::SnapshotSummaryList kSnapshotSummaryList;
for (const auto& s : TestSnapshots()) {
kSnapshotSummaryList.emplace_back(s);
}
// We need 3 groups at least.
constexpr int kNumGroups = 2;
SnapshotPartition partition(kNumGroups,
SnapshotGroup::kAllowWriteConflictsWithSamePerm);
SnapshotGroup::SnapshotSummaryList rejected =
partition.PartitionSnapshots(kSnapshotSummaryList);
// There should be rejected snapshots.
EXPECT_THAT(rejected, Not(IsEmpty()));
}
} // namespace
} // namespace silifuzz
<|endoftext|> |
<commit_before>///
/// @file EratMedium.cpp
/// @brief Segmented sieve of Eratosthenes optimized for medium
/// sieving primes.
///
/// Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primesieve/config.hpp>
#include <primesieve/EratMedium.hpp>
#include <primesieve/primesieve_error.hpp>
#include <primesieve/Wheel.hpp>
#include <stdint.h>
#include <cassert>
#include <list>
namespace primesieve {
/// @param stop Upper bound for sieving.
/// @param sieveSize Sieve size in bytes.
/// @param limit Sieving primes must be <= limit.
///
EratMedium::EratMedium(uint64_t stop, uint_t sieveSize, uint_t limit) :
Modulo210Wheel_t(stop, sieveSize),
limit_(limit)
{
// ensure multipleIndex < 2^23 in crossOff()
if (sieveSize > (1u << 21))
throw primesieve_error("EratMedium: sieveSize must be <= 2^21, 2048 kilobytes");
if (limit > sieveSize * 9)
throw primesieve_error("EratMedium: limit must be <= sieveSize * 9");
buckets_.emplace_back();
}
/// Add a new sieving prime to EratMedium
void EratMedium::storeSievingPrime(uint_t prime, uint_t multipleIndex, uint_t wheelIndex)
{
assert(prime <= limit_);
uint_t sievingPrime = prime / NUMBERS_PER_BYTE;
if (!buckets_.back().store(sievingPrime, multipleIndex, wheelIndex))
buckets_.emplace_back();
}
/// Cross-off the multiples of medium sieving
/// primes from the sieve array.
///
void EratMedium::crossOff(byte_t* sieve, uint_t sieveSize)
{
for (auto& bucket : buckets_)
crossOff(sieve, sieveSize, bucket);
}
/// Cross-off the multiples of the sieving primes within the current
/// bucket. This is an implementation of the segmented sieve of
/// Eratosthenes with wheel factorization optimized for medium sieving
/// primes that have a few multiples per segment. This algorithm uses
/// a modulo 210 wheel that skips multiples of 2, 3, 5 and 7.
///
void EratMedium::crossOff(byte_t* sieve, uint_t sieveSize, Bucket& bucket)
{
SievingPrime* sPrime = bucket.begin();
SievingPrime* sEnd = bucket.end();
// process 3 sieving primes per loop iteration to
// increase instruction level parallelism
for (; sPrime + 3 <= sEnd; sPrime += 3)
{
uint_t multipleIndex0 = sPrime[0].getMultipleIndex();
uint_t wheelIndex0 = sPrime[0].getWheelIndex();
uint_t sievingPrime0 = sPrime[0].getSievingPrime();
uint_t multipleIndex1 = sPrime[1].getMultipleIndex();
uint_t wheelIndex1 = sPrime[1].getWheelIndex();
uint_t sievingPrime1 = sPrime[1].getSievingPrime();
uint_t multipleIndex2 = sPrime[2].getMultipleIndex();
uint_t wheelIndex2 = sPrime[2].getWheelIndex();
uint_t sievingPrime2 = sPrime[2].getSievingPrime();
while (multipleIndex0 < sieveSize)
{
unsetBit(sieve, sievingPrime0, &multipleIndex0, &wheelIndex0);
if (multipleIndex1 >= sieveSize) break;
unsetBit(sieve, sievingPrime1, &multipleIndex1, &wheelIndex1);
if (multipleIndex2 >= sieveSize) break;
unsetBit(sieve, sievingPrime2, &multipleIndex2, &wheelIndex2);
}
while (multipleIndex0 < sieveSize) unsetBit(sieve, sievingPrime0, &multipleIndex0, &wheelIndex0);
while (multipleIndex1 < sieveSize) unsetBit(sieve, sievingPrime1, &multipleIndex1, &wheelIndex1);
while (multipleIndex2 < sieveSize) unsetBit(sieve, sievingPrime2, &multipleIndex2, &wheelIndex2);
multipleIndex0 -= sieveSize;
multipleIndex1 -= sieveSize;
multipleIndex2 -= sieveSize;
sPrime[0].set(multipleIndex0, wheelIndex0);
sPrime[1].set(multipleIndex1, wheelIndex1);
sPrime[2].set(multipleIndex2, wheelIndex2);
}
// process remaining sieving primes
for (; sPrime != sEnd; sPrime++)
{
uint_t multipleIndex = sPrime->getMultipleIndex();
uint_t wheelIndex = sPrime->getWheelIndex();
uint_t sievingPrime = sPrime->getSievingPrime();
while (multipleIndex < sieveSize)
unsetBit(sieve, sievingPrime, &multipleIndex, &wheelIndex);
multipleIndex -= sieveSize;
sPrime->set(multipleIndex, wheelIndex);
}
}
} // namespace
<commit_msg>Update comments<commit_after>///
/// @file EratMedium.cpp
/// @brief Segmented sieve of Eratosthenes optimized for medium
/// sieving primes.
///
/// Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primesieve/config.hpp>
#include <primesieve/EratMedium.hpp>
#include <primesieve/primesieve_error.hpp>
#include <primesieve/Wheel.hpp>
#include <stdint.h>
#include <cassert>
#include <list>
namespace primesieve {
/// @stop: Upper bound for sieving
/// @sieveSize: Sieve size in bytes
/// @limit: Sieving primes must be <= limit
///
EratMedium::EratMedium(uint64_t stop, uint_t sieveSize, uint_t limit) :
Modulo210Wheel_t(stop, sieveSize),
limit_(limit)
{
// ensure multipleIndex < 2^23 in crossOff()
if (sieveSize > (1u << 21))
throw primesieve_error("EratMedium: sieveSize must be <= 2^21, 2048 kilobytes");
if (limit > sieveSize * 9)
throw primesieve_error("EratMedium: limit must be <= sieveSize * 9");
buckets_.emplace_back();
}
/// Add a new sieving prime to EratMedium
void EratMedium::storeSievingPrime(uint_t prime, uint_t multipleIndex, uint_t wheelIndex)
{
assert(prime <= limit_);
uint_t sievingPrime = prime / NUMBERS_PER_BYTE;
if (!buckets_.back().store(sievingPrime, multipleIndex, wheelIndex))
buckets_.emplace_back();
}
/// Cross-off the multiples of medium sieving
/// primes from the sieve array
///
void EratMedium::crossOff(byte_t* sieve, uint_t sieveSize)
{
for (auto& bucket : buckets_)
crossOff(sieve, sieveSize, bucket);
}
/// Cross-off the multiples of the sieving primes in the
/// current bucket. This is an implementation of the segmented
/// sieve of Eratosthenes with wheel factorization optimized for
/// medium sieving primes that have a few multiples per segment
///
void EratMedium::crossOff(byte_t* sieve, uint_t sieveSize, Bucket& bucket)
{
SievingPrime* sPrime = bucket.begin();
SievingPrime* sEnd = bucket.end();
// process 3 sieving primes per loop iteration to
// increase instruction level parallelism
for (; sPrime + 3 <= sEnd; sPrime += 3)
{
uint_t multipleIndex0 = sPrime[0].getMultipleIndex();
uint_t wheelIndex0 = sPrime[0].getWheelIndex();
uint_t sievingPrime0 = sPrime[0].getSievingPrime();
uint_t multipleIndex1 = sPrime[1].getMultipleIndex();
uint_t wheelIndex1 = sPrime[1].getWheelIndex();
uint_t sievingPrime1 = sPrime[1].getSievingPrime();
uint_t multipleIndex2 = sPrime[2].getMultipleIndex();
uint_t wheelIndex2 = sPrime[2].getWheelIndex();
uint_t sievingPrime2 = sPrime[2].getSievingPrime();
while (multipleIndex0 < sieveSize)
{
unsetBit(sieve, sievingPrime0, &multipleIndex0, &wheelIndex0);
if (multipleIndex1 >= sieveSize) break;
unsetBit(sieve, sievingPrime1, &multipleIndex1, &wheelIndex1);
if (multipleIndex2 >= sieveSize) break;
unsetBit(sieve, sievingPrime2, &multipleIndex2, &wheelIndex2);
}
while (multipleIndex0 < sieveSize) unsetBit(sieve, sievingPrime0, &multipleIndex0, &wheelIndex0);
while (multipleIndex1 < sieveSize) unsetBit(sieve, sievingPrime1, &multipleIndex1, &wheelIndex1);
while (multipleIndex2 < sieveSize) unsetBit(sieve, sievingPrime2, &multipleIndex2, &wheelIndex2);
multipleIndex0 -= sieveSize;
multipleIndex1 -= sieveSize;
multipleIndex2 -= sieveSize;
sPrime[0].set(multipleIndex0, wheelIndex0);
sPrime[1].set(multipleIndex1, wheelIndex1);
sPrime[2].set(multipleIndex2, wheelIndex2);
}
// process remaining sieving primes
for (; sPrime != sEnd; sPrime++)
{
uint_t multipleIndex = sPrime->getMultipleIndex();
uint_t wheelIndex = sPrime->getWheelIndex();
uint_t sievingPrime = sPrime->getSievingPrime();
while (multipleIndex < sieveSize)
unsetBit(sieve, sievingPrime, &multipleIndex, &wheelIndex);
multipleIndex -= sieveSize;
sPrime->set(multipleIndex, wheelIndex);
}
}
} // namespace
<|endoftext|> |
<commit_before>#ifndef NGRAM_HH
#define NGRAM_HH
#include <algorithm>
#include <vector>
#include <cassert>
#include "Vocabulary.hh"
// Binary search
template <class Vector, class Value>
inline int
find(Vector &nodes, const Value &value, int first, int end)
{
int middle;
int half;
int len = end - first;
while (len > 3) { // FIXME: magic value
half = len / 2;
middle = first + half;
// Equal
if (nodes[middle] == value)
return middle;
// First half
if (nodes[middle] > value) {
end = middle;
len = end - first;
}
// Second half
else {
first = middle + 1;
len = end - first;
}
}
while (first < end) {
if (nodes[first] == value)
return first;
first++;
}
return -1;
}
class Ngram : private Vocabulary {
public:
friend class ArpaNgramReader;
friend class BinNgramReader; // For accessing m_nodes directly
class Node {
public:
int word;
float log_prob;
float back_off;
int first;
inline Node() : word(0), log_prob(0), back_off(0), first(-1) { }
inline Node(unsigned short word, float log_prob, float back_off)
: word(word), log_prob(log_prob), back_off(back_off), first(-1) { }
inline bool operator<(int value) const { return word < value; }
inline bool operator>(int value) const { return word > value; }
inline bool operator==(int value) const { return word == value; }
};
template<class RandomAccessIterator>
float log_prob(RandomAccessIterator begin, RandomAccessIterator end) const;
inline Ngram() : m_order(0) { }
inline int order() const { return m_order; }
inline int size() const { return Vocabulary::size(); }
inline const std::string &word(unsigned int index) const
{ return Vocabulary::word(index); }
inline Node *node(int index) { return &m_nodes[index]; }
inline const Node *node(int index) const { return &m_nodes[index]; }
inline int nodes() const { return m_nodes.size(); }
inline int index(const std::string &word) const
{ return Vocabulary::index(word); }
inline const Node *child(int word, const Node *node = NULL) const
{
if (node == NULL)
return &m_nodes[word];
if (node->first < 0)
return NULL;
int end = (node + 1)->first;
if (end < 0)
end = m_nodes.size();
int index = find(m_nodes, word, node->first, end);
if (index < 0)
return NULL;
return &m_nodes[index];
}
private:
int m_order;
std::vector<Node> m_nodes;
};
template<class RandomAccessIterator>
float
Ngram::log_prob(RandomAccessIterator begin, RandomAccessIterator end) const
{
RandomAccessIterator it;
float log_prob = 0;
for (; begin != end; begin++) {
const Node *node = this->node(*begin);
assert(node != NULL); // We must have a unigram for each word.
for (it = begin+1; it != end; it++) {
const Node *next = this->child(*it, node);
if (!next)
break;
node = next;
}
// Full ngram found
if (it == end) {
log_prob += node->log_prob;
return log_prob;
}
// Backoff found
if (it + 1 == end)
log_prob += node->back_off;
}
assert(false);
return 0;
}
#endif /* NGRAM_HH */
<commit_msg>added last_order in ngram<commit_after>#ifndef NGRAM_HH
#define NGRAM_HH
#include <algorithm>
#include <vector>
#include <cassert>
#include "Vocabulary.hh"
// Binary search
template <class Vector, class Value>
inline int
find(Vector &nodes, const Value &value, int first, int end)
{
int middle;
int half;
int len = end - first;
while (len > 3) { // FIXME: magic value
half = len / 2;
middle = first + half;
// Equal
if (nodes[middle] == value)
return middle;
// First half
if (nodes[middle] > value) {
end = middle;
len = end - first;
}
// Second half
else {
first = middle + 1;
len = end - first;
}
}
while (first < end) {
if (nodes[first] == value)
return first;
first++;
}
return -1;
}
class Ngram : private Vocabulary {
public:
friend class ArpaNgramReader;
friend class BinNgramReader; // For accessing m_nodes directly
class Node {
public:
int word;
float log_prob;
float back_off;
int first;
inline Node() : word(0), log_prob(0), back_off(0), first(-1) { }
inline Node(unsigned short word, float log_prob, float back_off)
: word(word), log_prob(log_prob), back_off(back_off), first(-1) { }
inline bool operator<(int value) const { return word < value; }
inline bool operator>(int value) const { return word > value; }
inline bool operator==(int value) const { return word == value; }
};
template<class RandomAccessIterator>
float log_prob(RandomAccessIterator begin, RandomAccessIterator end) const;
inline Ngram() : m_order(0) { }
inline int order() const { return m_order; }
inline int size() const { return Vocabulary::size(); }
inline const std::string &word(unsigned int index) const
{ return Vocabulary::word(index); }
inline Node *node(int index) { return &m_nodes[index]; }
inline const Node *node(int index) const { return &m_nodes[index]; }
inline int nodes() const { return m_nodes.size(); }
inline int index(const std::string &word) const
{ return Vocabulary::index(word); }
inline const Node *child(int word, const Node *node = NULL) const
{
if (node == NULL)
return &m_nodes[word];
if (node->first < 0)
return NULL;
int end = (node + 1)->first;
if (end < 0)
end = m_nodes.size();
int index = find(m_nodes, word, node->first, end);
if (index < 0)
return NULL;
return &m_nodes[index];
}
inline int last_order() { return m_last_order; }
private:
int m_order;
std::vector<Node> m_nodes;
int m_last_order; // Order of the last match
};
template<class RandomAccessIterator>
float
Ngram::log_prob(RandomAccessIterator begin, RandomAccessIterator end) const
{
RandomAccessIterator it;
float log_prob = 0;
m_last_order = end - begin;
assert(m_last_order <= m_order);
for (; begin != end; begin++) {
const Node *node = this->node(*begin);
assert(node != NULL); // We must have a unigram for each word.
// Find the longest branch that matches history (starting from node)
for (it = begin+1; it != end; it++) {
const Node *next = this->child(*it, node);
if (!next)
break;
node = next;
}
// Full ngram found
if (it == end) {
log_prob += node->log_prob;
return log_prob;
}
m_last_order--;
// Backoff found
if (it + 1 == end)
log_prob += node->back_off;
}
assert(false);
return 0;
}
#endif /* NGRAM_HH */
<|endoftext|> |
<commit_before>// UCN Spin class
// Author: Matthew Raso-Barnett 19/08/2010
#include <iostream>
#include <cassert>
#include <stdexcept>
#include "Constants.h"
#include "Units.h"
#include "Spin.h"
#include "TRandom.h"
/////////////////////////////////////////////////////////////////////////////
// //
// Spin //
// //
/////////////////////////////////////////////////////////////////////////////
//#define PRINT_CONSTRUCTORS
//#define VERBOSE
using namespace std;
ClassImp(Spin)
//_____________________________________________________________________________
Spin::Spin()
:TObject()
{
// Constructor
// Info("Spin","Default Constructor");
}
//_____________________________________________________________________________
Spin::Spin(const Spin& other)
:TObject(other), fSpinor(other.fSpinor)
{
// Copy Constructor
// Info("Spin","Copy Constructor");
}
//_____________________________________________________________________________
Spin& Spin::operator=(const Spin& other)
{
// Assignment
// Info("Spin","Assignment");
if(this!=&other) {
TObject::operator=(other);
fSpinor = other.fSpinor;
}
return *this;
}
//_____________________________________________________________________________
Spin::~Spin()
{
// Destructor
// Info("Spin","Destructor");
}
//_____________________________________________________________________________
Bool_t Spin::Precess(const TVector3& avgMagField, const Double_t precessTime)
{
// -- Choose method for spin precession
// Quantum mechanical method
fSpinor.Precess(avgMagField, precessTime);
return kTRUE;
}
//_____________________________________________________________________________
void Spin::Print(Option_t* /*option*/) const
{
fSpinor.Print();
}
//_____________________________________________________________________________
Bool_t Spin::Polarise(const TVector3& axis, const Bool_t up)
{
// -- Set Spin's polarisation along defined axis
if (up == kTRUE) {
fSpinor.PolariseUp(axis);
} else {
fSpinor.PolariseDown(axis);
}
return kTRUE;
}
//_____________________________________________________________________________
Double_t Spin::CalculateProbSpinUp(const TVector3& axis) const
{
// -- Calculate probability of being spin 'up' along provided axis
return fSpinor.CalculateProbSpinUp(axis);
}
//_____________________________________________________________________________
Bool_t Spin::IsSpinUp(const TVector3& axis) const
{
// -- Calculate whether particle is in the Spin-up state defined by measurement Axis
// -- This is a non-destructive calculation, that does not leave the the particle in this
// -- state after the calculation, as opposed to MeasureSpinUp()
Double_t probSpinUp = this->CalculateProbSpinUp(axis);
// Check for errorneous probability
if (probSpinUp < 0.0 || probSpinUp > 1.0) {
if (TMath::Abs(probSpinUp - 1.0) < 1.E-10) {
probSpinUp = 1.0;
} else if (TMath::Abs(probSpinUp) < 1.E-10) {
probSpinUp = 0.0;
} else {
bool up = probSpinUp > 1.0 ? false : true;
cout << probSpinUp - 1.0 << endl;
cout << "Up? " << up << endl;
bool equal = probSpinUp == 1.0 ? true : false;
cout << "Equal to 1? " << equal << endl;
axis.Print();
throw runtime_error("Spin::IsSpinUp - Found probability outside of 0 -> 1 range.");
}
}
// Roll dice to determine whether Spin Up or Spin Down
if (gRandom->Uniform(0.0,1.0) <= probSpinUp) {return kTRUE;}
// Spin down
return kFALSE;
}
/////////////////////////////////////////////////////////////////////////////
// //
// Spinor //
// //
/////////////////////////////////////////////////////////////////////////////
ClassImp(Spinor)
//_____________________________________________________________________________
Spinor::Spinor()
:TObject(), fUpRe(0.), fUpIm(0.), fDownRe(0.), fDownIm(0.)
{
// Constructor
// Info("Spinor","Default Constructor");
}
//_____________________________________________________________________________
Spinor::Spinor(const Spinor& other)
:TObject(other), fUpRe(other.fUpRe), fUpIm(other.fUpIm), fDownRe(other.fDownRe),
fDownIm(other.fDownIm)
{
// Copy Constructor
// Info("Spinor","Copy Constructor");
}
//_____________________________________________________________________________
Spinor& Spinor::operator=(const Spinor& other)
{
// Assignment
// Info("Spinor","Assignment");
if(this!=&other) {
TObject::operator=(other);
fUpRe = other.fUpRe;
fUpIm = other.fUpIm;
fDownRe = other.fDownRe;
fDownIm = other.fDownIm;
}
return *this;
}
//_____________________________________________________________________________
Spinor::~Spinor()
{
// Destructor
// Info("Spinor","Destructor");
}
//_____________________________________________________________________________
void Spinor::PolariseUp(const TVector3& axis)
{
// -- Set spinor components to be eigenvector of the operator for spin in the direction
// -- defined by 'axis'. Expressions derived in notebook.
TVector3 unit = axis.Unit();
const Double_t mag = 1.0/TMath::Sqrt(2.0 + 2.0*TMath::Abs(unit.Z()));
fUpRe = (unit.Z() + 1.0)*mag;
fUpIm = 0.;
fDownRe = unit.X()*mag;
fDownIm = unit.Y()*mag;
}
//_____________________________________________________________________________
void Spinor::PolariseDown(const TVector3& axis)
{
// -- Set spinor components to be eigenvector of the operator for spin in the direction
// -- defined by 'axis'. Expressions derived in notebook.
TVector3 unit = axis.Unit();
const Double_t mag = 1.0/TMath::Sqrt(2.0 + 2.0*TMath::Abs(unit.Z()));
fUpRe = (unit.Z() - 1.0)*mag;
fUpIm = 0.;
fDownRe = unit.X()*mag;
fDownIm = unit.Y()*mag;
}
//_____________________________________________________________________________
void Spinor::Print(Option_t* /*option*/) const
{
cout << "Spin Up: " << fUpRe << " + i" << fUpIm << endl;
cout << "Spin Down: " << fDownRe << "+ i" << fDownIm << endl;
}
//_____________________________________________________________________________
Bool_t Spinor::Precess(const TVector3& avgMagField, const Double_t precessTime)
{
// -- Take mag field (in the global coordinate system) and precess about it
#ifdef VERBOSE
cout << "Precess Spinor:" << endl;
this->Print();
#endif
Double_t omegaX = Neutron::gyromag_ratio*avgMagField.X();
Double_t omegaY = Neutron::gyromag_ratio*avgMagField.Y();
Double_t omegaZ = Neutron::gyromag_ratio*avgMagField.Z();
// Precession frequency
Double_t omega = TMath::Sqrt(omegaX*omegaX + omegaY*omegaY + omegaZ*omegaZ);
if (omega == 0.0) return kFALSE;
Double_t precessAngle = (omega*precessTime)/2.0;
// Spin Up Real Part
const Double_t newUpRe = fUpRe*TMath::Cos(precessAngle) + (fUpIm*(omegaZ/omega) - fDownIm*(omegaX/omega) - fDownRe*(omegaY/omega))*TMath::Sin(precessAngle);
// Spin Up Imaginary Part
const Double_t newUpIm = fUpIm*TMath::Cos(precessAngle) + (fDownRe*(omegaX/omega) - fUpRe*(omegaZ/omega) - fDownIm*(omegaY/omega))*TMath::Sin(precessAngle);
// Spin Down Real Part
const Double_t newDownRe = fDownRe*TMath::Cos(precessAngle) + (fUpIm*(omegaX/omega) - fDownIm*(omegaZ/omega) + fUpRe*(omegaY/omega))*TMath::Sin(precessAngle);
// Spin Down Imaginary Part
const Double_t newDownIm = fDownIm*TMath::Cos(precessAngle) + (fDownRe*(omegaZ/omega) - fUpRe*(omegaX/omega) + fUpIm*(omegaY/omega))*TMath::Sin(precessAngle);
// Update spinor
fUpRe = newUpRe;
fUpIm = newUpIm;
fDownRe = newDownRe;
fDownIm = newDownIm;
#ifdef VERBOSE
cout << "Precess Time: " << precessTime << endl;
cout << "Mag Field - Bx: " << avgMagField.X() << "\t";
cout << "By: " << avgMagField.Y() << "\t Bz: " << avgMagField.Z() << endl;
cout << "Omega - X: " << omegaX << "\t";
cout << "Y: " << omegaY << "\t Z: " << omegaZ << "\t Mag: " << omega << endl;
cout << "Precess Angle: " << precessAngle << endl;
this->Print();
cout << "-----------------------------------------------" << endl;
#endif
return kTRUE;
}
//_____________________________________________________________________________
Double_t Spinor::CalculateProbSpinUp(const TVector3& axis) const
{
// -- Calculate probability of being spin 'up' along provided axis
// -- See notebook for equations
TVector3 measurementAxis = axis.Unit();
const Double_t ux = measurementAxis.X();
const Double_t uy = measurementAxis.Y();
// Take absolute value of Z component to ensure we don't take uz = -1
const Double_t uz = TMath::Abs(measurementAxis.Z());
const Double_t denominator = 2.0 + 2.0*uz;
// Calculate the numerator components -- all equations are in notebook
Double_t numer1 = (uz + 1.0)*(uz + 1.0)*(fUpRe*fUpRe + fUpIm*fUpIm);
Double_t numer2 = (ux*ux + uy*uy)*(fDownRe*fDownRe + fDownIm*fDownIm);
Double_t numer3 = (uz + 1.0)*(ux*(fUpRe*fDownRe + fUpIm*fDownIm) + uy*(fUpRe*fDownIm - fUpIm*fDownRe));
Double_t numer4 = (uz + 1.0)*(ux*(fDownRe*fUpRe + fDownIm*fUpIm) - uy*(fDownRe*fUpIm - fDownIm*fUpRe));
// Calculate probability
Double_t prob = (numer1 + numer2 + numer3 + numer4)/denominator;
#ifdef VERBOSE
cout << "Calculate Prob Spin Up: " << endl;
this->Print();
cout << "denominator: " << denominator << endl;
cout << "Numer1: " << numer1 << "\t";
cout << "Numer2: " << numer2 << "\t";
cout << "Numer3: " << numer3 << "\t";
cout << "Numer4: " << numer4 << "\t" << endl;
cout << "Probability: " << prob << endl;
cout << "-----------------------------------------------" << endl;
#endif
// assert(prob >= 0.0 && prob <= 1.0);
return prob;
}
<commit_msg>Temp add test for correct probablity to spin <commit_after>// UCN Spin class
// Author: Matthew Raso-Barnett 19/08/2010
#include <iostream>
#include <cassert>
#include <stdexcept>
#include "Constants.h"
#include "Units.h"
#include "Spin.h"
#include "TRandom.h"
/////////////////////////////////////////////////////////////////////////////
// //
// Spin //
// //
/////////////////////////////////////////////////////////////////////////////
//#define PRINT_CONSTRUCTORS
//#define VERBOSE
using namespace std;
ClassImp(Spin)
//_____________________________________________________________________________
Spin::Spin()
:TObject()
{
// Constructor
// Info("Spin","Default Constructor");
}
//_____________________________________________________________________________
Spin::Spin(const Spin& other)
:TObject(other), fSpinor(other.fSpinor)
{
// Copy Constructor
// Info("Spin","Copy Constructor");
}
//_____________________________________________________________________________
Spin& Spin::operator=(const Spin& other)
{
// Assignment
// Info("Spin","Assignment");
if(this!=&other) {
TObject::operator=(other);
fSpinor = other.fSpinor;
}
return *this;
}
//_____________________________________________________________________________
Spin::~Spin()
{
// Destructor
// Info("Spin","Destructor");
}
//_____________________________________________________________________________
Bool_t Spin::Precess(const TVector3& avgMagField, const Double_t precessTime)
{
// -- Choose method for spin precession
// Quantum mechanical method
fSpinor.Precess(avgMagField, precessTime);
return kTRUE;
}
//_____________________________________________________________________________
void Spin::Print(Option_t* /*option*/) const
{
fSpinor.Print();
}
//_____________________________________________________________________________
Bool_t Spin::Polarise(const TVector3& axis, const Bool_t up)
{
// -- Set Spin's polarisation along defined axis
if (up == kTRUE) {
fSpinor.PolariseUp(axis);
} else {
fSpinor.PolariseDown(axis);
}
return kTRUE;
}
//_____________________________________________________________________________
Double_t Spin::CalculateProbSpinUp(const TVector3& axis) const
{
// -- Calculate probability of being spin 'up' along provided axis
return fSpinor.CalculateProbSpinUp(axis);
}
//_____________________________________________________________________________
Bool_t Spin::IsSpinUp(const TVector3& axis) const
{
// -- Calculate whether particle is in the Spin-up state defined by measurement Axis
// -- This is a non-destructive calculation, that does not leave the the particle in this
// -- state after the calculation, as opposed to MeasureSpinUp()
Double_t probSpinUp = this->CalculateProbSpinUp(axis);
// Check for errorneous probability
if (probSpinUp < 0.0 || probSpinUp > 1.0) {
if (TMath::Abs(probSpinUp - 1.0) < 1.E-10) {
probSpinUp = 1.0;
} else if (TMath::Abs(probSpinUp) < 1.E-10) {
probSpinUp = 0.0;
} else {
bool up = probSpinUp > 1.0 ? false : true;
cout << probSpinUp - 1.0 << endl;
cout << "Up? " << up << endl;
bool equal = probSpinUp == 1.0 ? true : false;
cout << "Equal to 1? " << equal << endl;
axis.Print();
throw runtime_error("Spin::IsSpinUp - Found probability outside of 0 -> 1 range.");
}
}
// Roll dice to determine whether Spin Up or Spin Down
if (gRandom->Uniform(0.0,1.0) <= probSpinUp) {return kTRUE;}
// Spin down
return kFALSE;
}
/////////////////////////////////////////////////////////////////////////////
// //
// Spinor //
// //
/////////////////////////////////////////////////////////////////////////////
ClassImp(Spinor)
//_____________________________________________________________________________
Spinor::Spinor()
:TObject(), fUpRe(0.), fUpIm(0.), fDownRe(0.), fDownIm(0.)
{
// Constructor
// Info("Spinor","Default Constructor");
}
//_____________________________________________________________________________
Spinor::Spinor(const Spinor& other)
:TObject(other), fUpRe(other.fUpRe), fUpIm(other.fUpIm), fDownRe(other.fDownRe),
fDownIm(other.fDownIm)
{
// Copy Constructor
// Info("Spinor","Copy Constructor");
}
//_____________________________________________________________________________
Spinor& Spinor::operator=(const Spinor& other)
{
// Assignment
// Info("Spinor","Assignment");
if(this!=&other) {
TObject::operator=(other);
fUpRe = other.fUpRe;
fUpIm = other.fUpIm;
fDownRe = other.fDownRe;
fDownIm = other.fDownIm;
}
return *this;
}
//_____________________________________________________________________________
Spinor::~Spinor()
{
// Destructor
// Info("Spinor","Destructor");
}
//_____________________________________________________________________________
void Spinor::PolariseUp(const TVector3& axis)
{
// -- Set spinor components to be eigenvector of the operator for spin in the direction
// -- defined by 'axis'. Expressions derived in notebook.
TVector3 unit = axis.Unit();
const Double_t mag = 1.0/TMath::Sqrt(2.0 + 2.0*TMath::Abs(unit.Z()));
fUpRe = (unit.Z() + 1.0)*mag;
fUpIm = 0.;
fDownRe = unit.X()*mag;
fDownIm = unit.Y()*mag;
}
//_____________________________________________________________________________
void Spinor::PolariseDown(const TVector3& axis)
{
// -- Set spinor components to be eigenvector of the operator for spin in the direction
// -- defined by 'axis'. Expressions derived in notebook.
TVector3 unit = axis.Unit();
const Double_t mag = 1.0/TMath::Sqrt(2.0 + 2.0*TMath::Abs(unit.Z()));
fUpRe = (unit.Z() - 1.0)*mag;
fUpIm = 0.;
fDownRe = unit.X()*mag;
fDownIm = unit.Y()*mag;
}
//_____________________________________________________________________________
void Spinor::Print(Option_t* /*option*/) const
{
cout << "Spin Up: " << fUpRe << " + i" << fUpIm << endl;
cout << "Spin Down: " << fDownRe << "+ i" << fDownIm << endl;
}
//_____________________________________________________________________________
Bool_t Spinor::Precess(const TVector3& avgMagField, const Double_t precessTime)
{
// -- Take mag field (in the global coordinate system) and precess about it
#ifdef VERBOSE
cout << "Precess Spinor:" << endl;
this->Print();
#endif
Double_t omegaX = Neutron::gyromag_ratio*avgMagField.X();
Double_t omegaY = Neutron::gyromag_ratio*avgMagField.Y();
Double_t omegaZ = Neutron::gyromag_ratio*avgMagField.Z();
// Precession frequency
Double_t omega = TMath::Sqrt(omegaX*omegaX + omegaY*omegaY + omegaZ*omegaZ);
if (omega == 0.0) return kFALSE;
Double_t precessAngle = (omega*precessTime)/2.0;
// Spin Up Real Part
const Double_t newUpRe = fUpRe*TMath::Cos(precessAngle) + (fUpIm*(omegaZ/omega) - fDownIm*(omegaX/omega) - fDownRe*(omegaY/omega))*TMath::Sin(precessAngle);
// Spin Up Imaginary Part
const Double_t newUpIm = fUpIm*TMath::Cos(precessAngle) + (fDownRe*(omegaX/omega) - fUpRe*(omegaZ/omega) - fDownIm*(omegaY/omega))*TMath::Sin(precessAngle);
// Spin Down Real Part
const Double_t newDownRe = fDownRe*TMath::Cos(precessAngle) + (fUpIm*(omegaX/omega) - fDownIm*(omegaZ/omega) + fUpRe*(omegaY/omega))*TMath::Sin(precessAngle);
// Spin Down Imaginary Part
const Double_t newDownIm = fDownIm*TMath::Cos(precessAngle) + (fDownRe*(omegaZ/omega) - fUpRe*(omegaX/omega) + fUpIm*(omegaY/omega))*TMath::Sin(precessAngle);
// Update spinor
fUpRe = newUpRe;
fUpIm = newUpIm;
fDownRe = newDownRe;
fDownIm = newDownIm;
#ifdef VERBOSE
cout << "Precess Time: " << precessTime << endl;
cout << "Mag Field - Bx: " << avgMagField.X() << "\t";
cout << "By: " << avgMagField.Y() << "\t Bz: " << avgMagField.Z() << endl;
cout << "Omega - X: " << omegaX << "\t";
cout << "Y: " << omegaY << "\t Z: " << omegaZ << "\t Mag: " << omega << endl;
cout << "Precess Angle: " << precessAngle << endl;
this->Print();
cout << "-----------------------------------------------" << endl;
#endif
this->CalculateProbSpinUp(TVector3(1.,0.,0.));
this->CalculateProbSpinUp(TVector3(0.,1.,0.));
this->CalculateProbSpinUp(TVector3(0.,0.,1.));
return kTRUE;
}
//_____________________________________________________________________________
Double_t Spinor::CalculateProbSpinUp(const TVector3& axis) const
{
// -- Calculate probability of being spin 'up' along provided axis
// -- See notebook for equations
TVector3 measurementAxis = axis.Unit();
const Double_t ux = measurementAxis.X();
const Double_t uy = measurementAxis.Y();
// Take absolute value of Z component to ensure we don't take uz = -1
const Double_t uz = TMath::Abs(measurementAxis.Z());
const Double_t denominator = 2.0 + 2.0*uz;
// Calculate the numerator components -- all equations are in notebook
Double_t numer1 = (uz + 1.0)*(uz + 1.0)*(fUpRe*fUpRe + fUpIm*fUpIm);
Double_t numer2 = (ux*ux + uy*uy)*(fDownRe*fDownRe + fDownIm*fDownIm);
Double_t numer3 = (uz + 1.0)*(ux*(fUpRe*fDownRe + fUpIm*fDownIm) + uy*(fUpRe*fDownIm - fUpIm*fDownRe));
Double_t numer4 = (uz + 1.0)*(ux*(fDownRe*fUpRe + fDownIm*fUpIm) - uy*(fDownRe*fUpIm - fDownIm*fUpRe));
// Calculate probability
Double_t prob = (numer1 + numer2 + numer3 + numer4)/denominator;
#ifdef VERBOSE
cout << "Calculate Prob Spin Up: " << endl;
this->Print();
cout << "denominator: " << denominator << endl;
cout << "Numer1: " << numer1 << "\t";
cout << "Numer2: " << numer2 << "\t";
cout << "Numer3: " << numer3 << "\t";
cout << "Numer4: " << numer4 << "\t" << endl;
cout << "Probability: " << prob << endl;
cout << "-----------------------------------------------" << endl;
#endif
assert(prob >= 0.0 && prob <= 1.0);
return prob;
}
<|endoftext|> |
<commit_before>#include "bitcoinamountfield.h"
#include "qvaluecombobox.h"
#include "bitcoinunits.h"
#include "guiconstants.h"
#include <QLabel>
#include <QLineEdit>
#include <QRegExpValidator>
#include <QHBoxLayout>
#include <QKeyEvent>
#include <QDoubleSpinBox>
#include <QComboBox>
#include <QApplication>
#include <qmath.h>
BitcoinAmountField::BitcoinAmountField(QWidget *parent):
QWidget(parent), amount(0), currentUnit(-1)
{
amount = new QDoubleSpinBox(this);
amount->setLocale(QLocale::c());
amount->setDecimals(8);
amount->installEventFilter(this);
amount->setMaximumWidth(170);
QHBoxLayout *layout = new QHBoxLayout(this);
layout->addWidget(amount);
unit = new QValueComboBox(this);
unit->setModel(new BitcoinUnits(this));
layout->addWidget(unit);
layout->addStretch(1);
layout->setContentsMargins(0,0,0,0);
setLayout(layout);
setFocusPolicy(Qt::TabFocus);
setFocusProxy(amount);
// If one if the widgets changes, the combined content changes as well
connect(amount, SIGNAL(valueChanged(QString)), this, SIGNAL(textChanged()));
connect(unit, SIGNAL(currentIndexChanged(int)), this, SLOT(unitChanged(int)));
// Set default based on configuration
unitChanged(unit->currentIndex());
}
void BitcoinAmountField::setText(const QString &text)
{
if (text.isEmpty())
amount->clear();
else
amount->setValue(text.toDouble());
}
void BitcoinAmountField::clear()
{
amount->clear();
unit->setCurrentIndex(0);
}
bool BitcoinAmountField::validate()
{
bool valid = true;
if (amount->value() == 0.0)
valid = false;
if (valid && !BitcoinUnits::parse(currentUnit, text(), 0))
valid = false;
setValid(valid);
return valid;
}
void BitcoinAmountField::setValid(bool valid)
{
if (valid)
amount->setStyleSheet("");
else
amount->setStyleSheet(STYLE_INVALID);
}
QString BitcoinAmountField::text() const
{
if (amount->text().isEmpty())
return QString();
else
return amount->text();
}
bool BitcoinAmountField::eventFilter(QObject *object, QEvent *event)
{
if (event->type() == QEvent::FocusIn)
{
// Clear invalid flag on focus
setValid(true);
}
else if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease)
{
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
if (keyEvent->key() == Qt::Key_Comma)
{
// Translate a comma into a period
QKeyEvent periodKeyEvent(event->type(), Qt::Key_Period, keyEvent->modifiers(), ".", keyEvent->isAutoRepeat(), keyEvent->count());
qApp->sendEvent(object, &periodKeyEvent);
return true;
}
}
return QWidget::eventFilter(object, event);
}
QWidget *BitcoinAmountField::setupTabChain(QWidget *prev)
{
QWidget::setTabOrder(prev, amount);
return amount;
}
qint64 BitcoinAmountField::value(bool *valid_out) const
{
qint64 val_out = 0;
bool valid = BitcoinUnits::parse(currentUnit, text(), &val_out);
if(valid_out)
{
*valid_out = valid;
}
return val_out;
}
void BitcoinAmountField::setValue(qint64 value)
{
setText(BitcoinUnits::format(currentUnit, value));
}
void BitcoinAmountField::unitChanged(int idx)
{
// Use description tooltip for current unit for the combobox
unit->setToolTip(unit->itemData(idx, Qt::ToolTipRole).toString());
// Determine new unit ID
int newUnit = unit->itemData(idx, BitcoinUnits::UnitRole).toInt();
// Parse current value and convert to new unit
bool valid = false;
qint64 currentValue = value(&valid);
currentUnit = newUnit;
// Set max length after retrieving the value, to prevent truncation
amount->setDecimals(BitcoinUnits::decimals(currentUnit));
amount->setMaximum(qPow(10, BitcoinUnits::amountDigits(currentUnit)) - qPow(10, -amount->decimals()));
if(valid)
{
// If value was valid, re-place it in the widget with the new unit
setValue(currentValue);
}
else
{
// If current value is invalid, just clear field
setText("");
}
setValid(true);
}
void BitcoinAmountField::setDisplayUnit(int newUnit)
{
unit->setValue(newUnit);
}
<commit_msg>Change up/down increment in UI to 0.001 BTC (issue #760)<commit_after>#include "bitcoinamountfield.h"
#include "qvaluecombobox.h"
#include "bitcoinunits.h"
#include "guiconstants.h"
#include <QLabel>
#include <QLineEdit>
#include <QRegExpValidator>
#include <QHBoxLayout>
#include <QKeyEvent>
#include <QDoubleSpinBox>
#include <QComboBox>
#include <QApplication>
#include <qmath.h>
BitcoinAmountField::BitcoinAmountField(QWidget *parent):
QWidget(parent), amount(0), currentUnit(-1)
{
amount = new QDoubleSpinBox(this);
amount->setLocale(QLocale::c());
amount->setDecimals(8);
amount->installEventFilter(this);
amount->setMaximumWidth(170);
amount->setSingleStep(0.001);
QHBoxLayout *layout = new QHBoxLayout(this);
layout->addWidget(amount);
unit = new QValueComboBox(this);
unit->setModel(new BitcoinUnits(this));
layout->addWidget(unit);
layout->addStretch(1);
layout->setContentsMargins(0,0,0,0);
setLayout(layout);
setFocusPolicy(Qt::TabFocus);
setFocusProxy(amount);
// If one if the widgets changes, the combined content changes as well
connect(amount, SIGNAL(valueChanged(QString)), this, SIGNAL(textChanged()));
connect(unit, SIGNAL(currentIndexChanged(int)), this, SLOT(unitChanged(int)));
// Set default based on configuration
unitChanged(unit->currentIndex());
}
void BitcoinAmountField::setText(const QString &text)
{
if (text.isEmpty())
amount->clear();
else
amount->setValue(text.toDouble());
}
void BitcoinAmountField::clear()
{
amount->clear();
unit->setCurrentIndex(0);
}
bool BitcoinAmountField::validate()
{
bool valid = true;
if (amount->value() == 0.0)
valid = false;
if (valid && !BitcoinUnits::parse(currentUnit, text(), 0))
valid = false;
setValid(valid);
return valid;
}
void BitcoinAmountField::setValid(bool valid)
{
if (valid)
amount->setStyleSheet("");
else
amount->setStyleSheet(STYLE_INVALID);
}
QString BitcoinAmountField::text() const
{
if (amount->text().isEmpty())
return QString();
else
return amount->text();
}
bool BitcoinAmountField::eventFilter(QObject *object, QEvent *event)
{
if (event->type() == QEvent::FocusIn)
{
// Clear invalid flag on focus
setValid(true);
}
else if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease)
{
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
if (keyEvent->key() == Qt::Key_Comma)
{
// Translate a comma into a period
QKeyEvent periodKeyEvent(event->type(), Qt::Key_Period, keyEvent->modifiers(), ".", keyEvent->isAutoRepeat(), keyEvent->count());
qApp->sendEvent(object, &periodKeyEvent);
return true;
}
}
return QWidget::eventFilter(object, event);
}
QWidget *BitcoinAmountField::setupTabChain(QWidget *prev)
{
QWidget::setTabOrder(prev, amount);
return amount;
}
qint64 BitcoinAmountField::value(bool *valid_out) const
{
qint64 val_out = 0;
bool valid = BitcoinUnits::parse(currentUnit, text(), &val_out);
if(valid_out)
{
*valid_out = valid;
}
return val_out;
}
void BitcoinAmountField::setValue(qint64 value)
{
setText(BitcoinUnits::format(currentUnit, value));
}
void BitcoinAmountField::unitChanged(int idx)
{
// Use description tooltip for current unit for the combobox
unit->setToolTip(unit->itemData(idx, Qt::ToolTipRole).toString());
// Determine new unit ID
int newUnit = unit->itemData(idx, BitcoinUnits::UnitRole).toInt();
// Parse current value and convert to new unit
bool valid = false;
qint64 currentValue = value(&valid);
currentUnit = newUnit;
// Set max length after retrieving the value, to prevent truncation
amount->setDecimals(BitcoinUnits::decimals(currentUnit));
amount->setMaximum(qPow(10, BitcoinUnits::amountDigits(currentUnit)) - qPow(10, -amount->decimals()));
if(valid)
{
// If value was valid, re-place it in the widget with the new unit
setValue(currentValue);
}
else
{
// If current value is invalid, just clear field
setText("");
}
setValid(true);
}
void BitcoinAmountField::setDisplayUnit(int newUnit)
{
unit->setValue(newUnit);
}
<|endoftext|> |
<commit_before>// Copyright 2008 Google 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.
// Implementation of the NPN API
// The NPN API is defined in npapi.h, but isn't actually exposed as such by the
// browser. It is exposed through a static set of functions passed to the
// initialization entrypoint. This file contains the glue between the NPN
// functions and the browser functions.
#include <npupp.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
static NPNetscapeFuncs g_browser_functions;
// Gets the NPAPI major version.
static inline uint16_t GetMajorVersion(uint16_t version) {
return version >> 8;
}
// Gets the NPAPI minor version.
static inline uint16_t GetMinorVersion(uint16_t version) {
return version & 0xff;
}
// Work-around of NPN_HasProperty, using NPN_Enumerate.
static bool HasPropertyWorkaround(NPP npp,
NPObject *npobj,
NPIdentifier property_name) {
NPIdentifier *identifiers = NULL;
uint32_t count;
bool result = NPN_Enumerate(npp, npobj, &identifiers, &count);
if (!result || !identifiers)
return false;
bool found = false;
for (unsigned int i = 0; i < count; ++i) {
if (identifiers[i] == property_name) {
found = true;
break;
}
}
NPN_MemFree(identifiers);
return result;
}
// Check for the work-around case.
bool IsHasPropertyWorkaround() {
return g_browser_functions.hasproperty == HasPropertyWorkaround;
}
NPError InitializeNPNApi(NPNetscapeFuncs *funcs) {
if (!funcs)
return NPERR_INVALID_FUNCTABLE_ERROR;
if (GetMajorVersion(funcs->version) > NP_VERSION_MAJOR)
return NPERR_INCOMPATIBLE_VERSION_ERROR;
// We need at least NPRuntime.
if (GetMinorVersion(funcs->version) < NPVERS_HAS_NPRUNTIME_SCRIPTING)
return NPERR_INCOMPATIBLE_VERSION_ERROR;
// np_runtime_size is the offset of the function directly after the last
// NPRuntime function, that is, the minimum NPRuntime size.
size_t np_runtime_size =
reinterpret_cast<char *>(&g_browser_functions.pushpopupsenabledstate) -
reinterpret_cast<char *>(&g_browser_functions);
// Did browser lie about supporting NPRuntime ?
if (funcs->size < np_runtime_size)
return NPERR_INCOMPATIBLE_VERSION_ERROR;
memset(&g_browser_functions, 0, sizeof(g_browser_functions));
// Only copy functions we know about, and that the browser has.
size_t size = std::min(sizeof(g_browser_functions),
static_cast<size_t>(funcs->size));
memcpy(&g_browser_functions, funcs, size);
// Safari doesn't implement NPN_HasProperty although it claims to support
// NPRuntime. We have a (slower) workaround using NPN_Enumerate.
// NOTE: it doesn't implement NPN_HasMethod or NPN_IntFromIdentifier either.
if (!g_browser_functions.hasproperty && g_browser_functions.enumerate) {
g_browser_functions.hasproperty = HasPropertyWorkaround;
}
return NPERR_NO_ERROR;
}
// npapi.h functions
void NP_LOADDS NPN_Version(int* plugin_major,
int* plugin_minor,
int* netscape_major,
int* netscape_minor) {
*plugin_major = NP_VERSION_MAJOR;
*plugin_minor = NP_VERSION_MINOR;
*netscape_major = GetMajorVersion(g_browser_functions.version);
*netscape_minor = GetMinorVersion(g_browser_functions.version);
}
NPError NP_LOADDS NPN_GetURLNotify(NPP instance,
const char* url,
const char* target,
void* notify_data) {
if (GetMinorVersion(g_browser_functions.version) < NPVERS_HAS_NOTIFICATION)
return NPERR_INCOMPATIBLE_VERSION_ERROR;
return g_browser_functions.geturlnotify(instance, url, target, notify_data);
}
NPError NP_LOADDS NPN_GetURL(NPP instance,
const char* url,
const char* target) {
return g_browser_functions.geturl(instance, url, target);
}
NPError NP_LOADDS NPN_PostURLNotify(NPP instance,
const char* url,
const char* target,
uint32_t len,
const char* buf,
NPBool file,
void* notify_data) {
if (GetMinorVersion(g_browser_functions.version) < NPVERS_HAS_NOTIFICATION)
return NPERR_INCOMPATIBLE_VERSION_ERROR;
return g_browser_functions.posturlnotify(instance, url, target, len, buf,
file, notify_data);
}
NPError NP_LOADDS NPN_PostURL(NPP instance,
const char* url,
const char* target,
uint32_t len,
const char* buf,
NPBool file) {
return g_browser_functions.posturl(instance, url, target, len, buf, file);
}
NPError NP_LOADDS NPN_RequestRead(NPStream* stream, NPByteRange* range_list) {
return g_browser_functions.requestread(stream, range_list);
}
NPError NP_LOADDS NPN_NewStream(NPP instance,
NPMIMEType type,
const char* target,
NPStream** stream) {
if (GetMinorVersion(g_browser_functions.version) < NPVERS_HAS_STREAMOUTPUT)
return NPERR_INCOMPATIBLE_VERSION_ERROR;
return g_browser_functions.newstream(instance, type, target, stream);
}
int32_t NP_LOADDS NPN_Write(NPP instance,
NPStream* stream,
int32_t len,
void* buffer) {
if (GetMinorVersion(g_browser_functions.version) < NPVERS_HAS_STREAMOUTPUT)
return NPERR_INCOMPATIBLE_VERSION_ERROR;
return g_browser_functions.write(instance, stream, len, buffer);
}
NPError NP_LOADDS NPN_DestroyStream(NPP instance,
NPStream* stream,
NPReason reason) {
if (GetMinorVersion(g_browser_functions.version) < NPVERS_HAS_STREAMOUTPUT)
return NPERR_INCOMPATIBLE_VERSION_ERROR;
return g_browser_functions.destroystream(instance, stream, reason);
}
void NP_LOADDS NPN_Status(NPP instance, const char* message) {
g_browser_functions.status(instance, message);
}
const char* NP_LOADDS NPN_UserAgent(NPP instance) {
return g_browser_functions.uagent(instance);
}
void* NP_LOADDS NPN_MemAlloc(uint32_t size) {
return g_browser_functions.memalloc(size);
}
void NP_LOADDS NPN_MemFree(void* ptr) {
g_browser_functions.memfree(ptr);
}
uint32_t NP_LOADDS NPN_MemFlush(uint32_t size) {
return g_browser_functions.memflush(size);
}
void NP_LOADDS NPN_ReloadPlugins(NPBool reload_pages) {
g_browser_functions.reloadplugins(reload_pages);
}
NPError NP_LOADDS NPN_GetValue(NPP instance,
NPNVariable variable,
void *value) {
return g_browser_functions.getvalue(instance, variable, value);
}
NPError NP_LOADDS NPN_SetValue(NPP instance,
NPPVariable variable,
void *value) {
return g_browser_functions.setvalue(instance, variable, value);
}
void NP_LOADDS NPN_InvalidateRect(NPP instance, NPRect *invalid_rect) {
g_browser_functions.invalidaterect(instance, invalid_rect);
}
void NP_LOADDS NPN_InvalidateRegion(NPP instance, NPRegion invalid_region) {
g_browser_functions.invalidateregion(instance, invalid_region);
}
void NP_LOADDS NPN_ForceRedraw(NPP instance) {
g_browser_functions.forceredraw(instance);
}
void NP_LOADDS NPN_PushPopupsEnabledState(NPP instance, NPBool enabled) {
if (GetMinorVersion(g_browser_functions.version) <
NPVERS_HAS_POPUPS_ENABLED_STATE)
return;
g_browser_functions.pushpopupsenabledstate(instance, enabled);
}
void NP_LOADDS NPN_PopPopupsEnabledState(NPP instance) {
if (GetMinorVersion(g_browser_functions.version) <
NPVERS_HAS_POPUPS_ENABLED_STATE)
return;
g_browser_functions.poppopupsenabledstate(instance);
}
void NP_LOADDS NPN_PluginThreadAsyncCall(NPP instance,
void (*func) (void *),
void *user_data) {
if (GetMinorVersion(g_browser_functions.version) <
NPVERS_HAS_PLUGIN_THREAD_ASYNC_CALL)
return;
g_browser_functions.pluginthreadasynccall(instance, func, user_data);
}
// npruntime.h functions
void NPN_ReleaseVariantValue(NPVariant *variant) {
g_browser_functions.releasevariantvalue(variant);
}
NPIdentifier NPN_GetStringIdentifier(const NPUTF8 *name) {
return g_browser_functions.getstringidentifier(name);
}
void NPN_GetStringIdentifiers(const NPUTF8 **names,
int32_t count,
NPIdentifier *identifiers) {
g_browser_functions.getstringidentifiers(names, count, identifiers);
}
NPIdentifier NPN_GetIntIdentifier(int32_t intid) {
return g_browser_functions.getintidentifier(intid);
}
bool NPN_IdentifierIsString(NPIdentifier identifier) {
return g_browser_functions.identifierisstring(identifier);
}
NPUTF8 *NPN_UTF8FromIdentifier(NPIdentifier identifier) {
return g_browser_functions.utf8fromidentifier(identifier);
}
int32_t NPN_IntFromIdentifier(NPIdentifier identifier) {
if (g_browser_functions.intfromidentifier != NULL) {
return g_browser_functions.intfromidentifier(identifier);
} else {
int32_t result = 0;
NPUTF8 *str = NPN_UTF8FromIdentifier(identifier);
if (str != NULL) {
result = atoi(str);
NPN_MemFree(str);
} else if (identifier != 0) { // Safari 3.0 just gives us an int*
result = *static_cast<int32_t*>(identifier);
}
return result;
}
}
NPObject *NPN_CreateObject(NPP npp, NPClass *_class) {
return g_browser_functions.createobject(npp, _class);
}
NPObject *NPN_RetainObject(NPObject *npobj) {
return g_browser_functions.retainobject(npobj);
}
void NPN_ReleaseObject(NPObject *npobj) {
g_browser_functions.releaseobject(npobj);
}
bool NPN_Invoke(NPP npp,
NPObject *npobj,
NPIdentifier method_name,
const NPVariant *args,
uint32_t arg_count,
NPVariant *result) {
return g_browser_functions.invoke(npp, npobj, method_name, args, arg_count,
result);
}
bool NPN_InvokeDefault(NPP npp,
NPObject *npobj,
const NPVariant *args,
uint32_t arg_count,
NPVariant *result) {
return g_browser_functions.invokeDefault(npp, npobj, args, arg_count, result);
}
bool NPN_Evaluate(NPP npp,
NPObject *npobj,
NPString *script,
NPVariant *result) {
return g_browser_functions.evaluate(npp, npobj, script, result);
}
bool NPN_GetProperty(NPP npp,
NPObject *npobj,
NPIdentifier property_name,
NPVariant *result) {
return g_browser_functions.getproperty(npp, npobj, property_name, result);
}
bool NPN_SetProperty(NPP npp,
NPObject *npobj,
NPIdentifier property_name,
const NPVariant *value) {
return g_browser_functions.setproperty(npp, npobj, property_name, value);
}
bool NPN_RemoveProperty(NPP npp, NPObject *npobj, NPIdentifier property_name) {
return g_browser_functions.removeproperty(npp, npobj, property_name);
}
bool NPN_HasProperty(NPP npp, NPObject *npobj, NPIdentifier property_name) {
return g_browser_functions.hasproperty(npp, npobj, property_name);
}
bool NPN_HasMethod(NPP npp, NPObject *npobj, NPIdentifier method_name) {
return g_browser_functions.hasmethod(npp, npobj, method_name);
}
bool NPN_Enumerate(NPP npp,
NPObject *npobj,
NPIdentifier **identifier,
uint32_t *count) {
if (GetMinorVersion(g_browser_functions.version) < NPVERS_HAS_NPOBJECT_ENUM)
return false;
return g_browser_functions.enumerate(npp, npobj, identifier, count);
}
bool NPN_Construct(NPP npp,
NPObject *npobj,
const NPVariant *args,
uint32_t arg_count,
NPVariant *result) {
return g_browser_functions.construct(npp, npobj, args, arg_count, result);
}
void NPN_SetException(NPObject *npobj, const NPUTF8 *message) {
g_browser_functions.setexception(npobj, message);
}
<commit_msg>Work-around nspluginwrapper bug on linux.<commit_after>// Copyright 2008 Google 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.
// Implementation of the NPN API
// The NPN API is defined in npapi.h, but isn't actually exposed as such by the
// browser. It is exposed through a static set of functions passed to the
// initialization entrypoint. This file contains the glue between the NPN
// functions and the browser functions.
#include <npupp.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
static NPNetscapeFuncs g_browser_functions;
// Gets the NPAPI major version.
static inline uint16_t GetMajorVersion(uint16_t version) {
return version >> 8;
}
// Gets the NPAPI minor version.
static inline uint16_t GetMinorVersion(uint16_t version) {
return version & 0xff;
}
// Work-around of NPN_HasProperty, using NPN_Enumerate.
static bool HasPropertyWorkaround(NPP npp,
NPObject *npobj,
NPIdentifier property_name) {
NPIdentifier *identifiers = NULL;
uint32_t count;
bool result = NPN_Enumerate(npp, npobj, &identifiers, &count);
if (!result || !identifiers)
return false;
bool found = false;
for (unsigned int i = 0; i < count; ++i) {
if (identifiers[i] == property_name) {
found = true;
break;
}
}
NPN_MemFree(identifiers);
return result;
}
// Check for the work-around case.
bool IsHasPropertyWorkaround() {
return g_browser_functions.hasproperty == HasPropertyWorkaround;
}
NPError InitializeNPNApi(NPNetscapeFuncs *funcs) {
if (!funcs)
return NPERR_INVALID_FUNCTABLE_ERROR;
if (GetMajorVersion(funcs->version) > NP_VERSION_MAJOR)
return NPERR_INCOMPATIBLE_VERSION_ERROR;
// We need at least NPRuntime.
if (GetMinorVersion(funcs->version) < NPVERS_HAS_NPRUNTIME_SCRIPTING)
return NPERR_INCOMPATIBLE_VERSION_ERROR;
// np_runtime_size is the offset of the function directly after the last
// NPRuntime function, that is, the minimum NPRuntime size.
size_t np_runtime_size =
reinterpret_cast<char *>(&g_browser_functions.pushpopupsenabledstate) -
reinterpret_cast<char *>(&g_browser_functions);
// Did browser lie about supporting NPRuntime ?
if (funcs->size < np_runtime_size)
return NPERR_INCOMPATIBLE_VERSION_ERROR;
memset(&g_browser_functions, 0, sizeof(g_browser_functions));
// Only copy functions we know about, and that the browser has.
size_t size = std::min(sizeof(g_browser_functions),
static_cast<size_t>(funcs->size));
memcpy(&g_browser_functions, funcs, size);
// Safari doesn't implement NPN_HasProperty although it claims to support
// NPRuntime. We have a (slower) workaround using NPN_Enumerate.
// NOTE: it doesn't implement NPN_HasMethod or NPN_IntFromIdentifier either.
if (!g_browser_functions.hasproperty && g_browser_functions.enumerate) {
g_browser_functions.hasproperty = HasPropertyWorkaround;
}
return NPERR_NO_ERROR;
}
// npapi.h functions
void NP_LOADDS NPN_Version(int* plugin_major,
int* plugin_minor,
int* netscape_major,
int* netscape_minor) {
*plugin_major = NP_VERSION_MAJOR;
*plugin_minor = NP_VERSION_MINOR;
*netscape_major = GetMajorVersion(g_browser_functions.version);
*netscape_minor = GetMinorVersion(g_browser_functions.version);
}
NPError NP_LOADDS NPN_GetURLNotify(NPP instance,
const char* url,
const char* target,
void* notify_data) {
if (GetMinorVersion(g_browser_functions.version) < NPVERS_HAS_NOTIFICATION)
return NPERR_INCOMPATIBLE_VERSION_ERROR;
return g_browser_functions.geturlnotify(instance, url, target, notify_data);
}
NPError NP_LOADDS NPN_GetURL(NPP instance,
const char* url,
const char* target) {
return g_browser_functions.geturl(instance, url, target);
}
NPError NP_LOADDS NPN_PostURLNotify(NPP instance,
const char* url,
const char* target,
uint32_t len,
const char* buf,
NPBool file,
void* notify_data) {
if (GetMinorVersion(g_browser_functions.version) < NPVERS_HAS_NOTIFICATION)
return NPERR_INCOMPATIBLE_VERSION_ERROR;
return g_browser_functions.posturlnotify(instance, url, target, len, buf,
file, notify_data);
}
NPError NP_LOADDS NPN_PostURL(NPP instance,
const char* url,
const char* target,
uint32_t len,
const char* buf,
NPBool file) {
return g_browser_functions.posturl(instance, url, target, len, buf, file);
}
NPError NP_LOADDS NPN_RequestRead(NPStream* stream, NPByteRange* range_list) {
return g_browser_functions.requestread(stream, range_list);
}
NPError NP_LOADDS NPN_NewStream(NPP instance,
NPMIMEType type,
const char* target,
NPStream** stream) {
if (GetMinorVersion(g_browser_functions.version) < NPVERS_HAS_STREAMOUTPUT)
return NPERR_INCOMPATIBLE_VERSION_ERROR;
return g_browser_functions.newstream(instance, type, target, stream);
}
int32_t NP_LOADDS NPN_Write(NPP instance,
NPStream* stream,
int32_t len,
void* buffer) {
if (GetMinorVersion(g_browser_functions.version) < NPVERS_HAS_STREAMOUTPUT)
return NPERR_INCOMPATIBLE_VERSION_ERROR;
return g_browser_functions.write(instance, stream, len, buffer);
}
NPError NP_LOADDS NPN_DestroyStream(NPP instance,
NPStream* stream,
NPReason reason) {
if (GetMinorVersion(g_browser_functions.version) < NPVERS_HAS_STREAMOUTPUT)
return NPERR_INCOMPATIBLE_VERSION_ERROR;
return g_browser_functions.destroystream(instance, stream, reason);
}
void NP_LOADDS NPN_Status(NPP instance, const char* message) {
g_browser_functions.status(instance, message);
}
const char* NP_LOADDS NPN_UserAgent(NPP instance) {
return g_browser_functions.uagent(instance);
}
void* NP_LOADDS NPN_MemAlloc(uint32_t size) {
return g_browser_functions.memalloc(size);
}
void NP_LOADDS NPN_MemFree(void* ptr) {
g_browser_functions.memfree(ptr);
}
uint32_t NP_LOADDS NPN_MemFlush(uint32_t size) {
return g_browser_functions.memflush(size);
}
void NP_LOADDS NPN_ReloadPlugins(NPBool reload_pages) {
g_browser_functions.reloadplugins(reload_pages);
}
NPError NP_LOADDS NPN_GetValue(NPP instance,
NPNVariable variable,
void *value) {
return g_browser_functions.getvalue(instance, variable, value);
}
NPError NP_LOADDS NPN_SetValue(NPP instance,
NPPVariable variable,
void *value) {
return g_browser_functions.setvalue(instance, variable, value);
}
void NP_LOADDS NPN_InvalidateRect(NPP instance, NPRect *invalid_rect) {
g_browser_functions.invalidaterect(instance, invalid_rect);
}
void NP_LOADDS NPN_InvalidateRegion(NPP instance, NPRegion invalid_region) {
g_browser_functions.invalidateregion(instance, invalid_region);
}
void NP_LOADDS NPN_ForceRedraw(NPP instance) {
g_browser_functions.forceredraw(instance);
}
void NP_LOADDS NPN_PushPopupsEnabledState(NPP instance, NPBool enabled) {
if (GetMinorVersion(g_browser_functions.version) <
NPVERS_HAS_POPUPS_ENABLED_STATE)
return;
g_browser_functions.pushpopupsenabledstate(instance, enabled);
}
void NP_LOADDS NPN_PopPopupsEnabledState(NPP instance) {
if (GetMinorVersion(g_browser_functions.version) <
NPVERS_HAS_POPUPS_ENABLED_STATE)
return;
g_browser_functions.poppopupsenabledstate(instance);
}
void NP_LOADDS NPN_PluginThreadAsyncCall(NPP instance,
void (*func) (void *),
void *user_data) {
if (GetMinorVersion(g_browser_functions.version) <
NPVERS_HAS_PLUGIN_THREAD_ASYNC_CALL)
return;
g_browser_functions.pluginthreadasynccall(instance, func, user_data);
}
// npruntime.h functions
void NPN_ReleaseVariantValue(NPVariant *variant) {
g_browser_functions.releasevariantvalue(variant);
}
NPIdentifier NPN_GetStringIdentifier(const NPUTF8 *name) {
return g_browser_functions.getstringidentifier(name);
}
void NPN_GetStringIdentifiers(const NPUTF8 **names,
int32_t count,
NPIdentifier *identifiers) {
#ifdef OS_LINUX
// GetStringIdentifiers is broken in nspluginwrapper 1.2.0 and 1.2.2 so we
// use GetStringIdentifier instead for maximum compatibility. See
// https://www.redhat.com/archives/nspluginwrapper-devel-list/2009-June/msg00000.html
for (int32_t i = 0; i < count; ++i) {
identifiers[i] = NPN_GetStringIdentifier(names[i]);
}
#else
g_browser_functions.getstringidentifiers(names, count, identifiers);
#endif
}
NPIdentifier NPN_GetIntIdentifier(int32_t intid) {
return g_browser_functions.getintidentifier(intid);
}
bool NPN_IdentifierIsString(NPIdentifier identifier) {
return g_browser_functions.identifierisstring(identifier);
}
NPUTF8 *NPN_UTF8FromIdentifier(NPIdentifier identifier) {
return g_browser_functions.utf8fromidentifier(identifier);
}
int32_t NPN_IntFromIdentifier(NPIdentifier identifier) {
if (g_browser_functions.intfromidentifier != NULL) {
return g_browser_functions.intfromidentifier(identifier);
} else {
int32_t result = 0;
NPUTF8 *str = NPN_UTF8FromIdentifier(identifier);
if (str != NULL) {
result = atoi(str);
NPN_MemFree(str);
} else if (identifier != 0) { // Safari 3.0 just gives us an int*
result = *static_cast<int32_t*>(identifier);
}
return result;
}
}
NPObject *NPN_CreateObject(NPP npp, NPClass *_class) {
return g_browser_functions.createobject(npp, _class);
}
NPObject *NPN_RetainObject(NPObject *npobj) {
return g_browser_functions.retainobject(npobj);
}
void NPN_ReleaseObject(NPObject *npobj) {
g_browser_functions.releaseobject(npobj);
}
bool NPN_Invoke(NPP npp,
NPObject *npobj,
NPIdentifier method_name,
const NPVariant *args,
uint32_t arg_count,
NPVariant *result) {
return g_browser_functions.invoke(npp, npobj, method_name, args, arg_count,
result);
}
bool NPN_InvokeDefault(NPP npp,
NPObject *npobj,
const NPVariant *args,
uint32_t arg_count,
NPVariant *result) {
return g_browser_functions.invokeDefault(npp, npobj, args, arg_count, result);
}
bool NPN_Evaluate(NPP npp,
NPObject *npobj,
NPString *script,
NPVariant *result) {
return g_browser_functions.evaluate(npp, npobj, script, result);
}
bool NPN_GetProperty(NPP npp,
NPObject *npobj,
NPIdentifier property_name,
NPVariant *result) {
return g_browser_functions.getproperty(npp, npobj, property_name, result);
}
bool NPN_SetProperty(NPP npp,
NPObject *npobj,
NPIdentifier property_name,
const NPVariant *value) {
return g_browser_functions.setproperty(npp, npobj, property_name, value);
}
bool NPN_RemoveProperty(NPP npp, NPObject *npobj, NPIdentifier property_name) {
return g_browser_functions.removeproperty(npp, npobj, property_name);
}
bool NPN_HasProperty(NPP npp, NPObject *npobj, NPIdentifier property_name) {
return g_browser_functions.hasproperty(npp, npobj, property_name);
}
bool NPN_HasMethod(NPP npp, NPObject *npobj, NPIdentifier method_name) {
return g_browser_functions.hasmethod(npp, npobj, method_name);
}
bool NPN_Enumerate(NPP npp,
NPObject *npobj,
NPIdentifier **identifier,
uint32_t *count) {
if (GetMinorVersion(g_browser_functions.version) < NPVERS_HAS_NPOBJECT_ENUM)
return false;
return g_browser_functions.enumerate(npp, npobj, identifier, count);
}
bool NPN_Construct(NPP npp,
NPObject *npobj,
const NPVariant *args,
uint32_t arg_count,
NPVariant *result) {
return g_browser_functions.construct(npp, npobj, args, arg_count, result);
}
void NPN_SetException(NPObject *npobj, const NPUTF8 *message) {
g_browser_functions.setexception(npobj, message);
}
<|endoftext|> |
<commit_before>#include "Tree.hpp"
#include <stdexcept>
#include <iostream>
#include <omp.h>
#include "pll_util.hpp"
#include "epa_pll_util.hpp"
#include "file_io.hpp"
#include "Sequence.hpp"
#include "optimize.hpp"
#include "set_manipulators.hpp"
#include "logging.hpp"
using namespace std;
Tree::Tree(const string &tree_file, const MSA &msa, Model &model,
Options options, const MSA &query)
: ref_msa_(msa), query_msa_(query), model_(model), options_(options)
{
// parse, build tree
nums_ = Tree_Numbers();
tie(partition_, tree_) =
build_partition_from_file(tree_file, model_, nums_, ref_msa_.num_sites());
// split msa if no separate query msa was supplied
if (query.num_sites() == 0)
split_combined_msa(ref_msa_, query_msa_, tree_, nums_.tip_nodes);
valid_map_ = vector<Range>(nums_.tip_nodes);
link_tree_msa(tree_, partition_, ref_msa_, nums_.tip_nodes, valid_map_);
// find_collapse_equal_sequences(query_msa_);
compute_and_set_empirical_frequencies(partition_, model_);
// perform branch length and model optimization on the reference tree
optimize(model_, tree_, partition_, nums_, options_.opt_branches,
options_.opt_model);
precompute_clvs(tree_, partition_, nums_);
lgr << "\nPost-optimization reference tree log-likelihood: ";
lgr << to_string(this->ref_tree_logl()) << endl;
}
double Tree::ref_tree_logl()
{
return pll_compute_edge_loglikelihood(
partition_, tree_->clv_index, tree_->scaler_index, tree_->back->clv_index,
tree_->back->scaler_index, tree_->pmatrix_index, 0);
}
Tree::~Tree()
{
// free data segment of tree nodes
utree_free_node_data(tree_);
pll_partition_destroy(partition_);
pll_utree_destroy(tree_);
}
PQuery_Set Tree::place()
{
const auto num_branches = nums_.branches;
const auto num_queries = query_msa_.size();
// get all edges
vector<pll_utree_t *> branches(num_branches);
auto num_traversed_branches = utree_query_branches(tree_, &branches[0]);
assert(num_traversed_branches == num_branches);
lgr << "\nPlacing "<< to_string(num_queries) << " reads on " <<
to_string(num_branches) << " branches." << endl;
// build all tiny trees with corresponding edges
vector<Tiny_Tree> insertion_trees;
for (auto node : branches)
insertion_trees.emplace_back(node, partition_, model_, !options_.prescoring);
/* clarification: last arg here is a flag specifying whether to optimize the branches.
we don't want that if the mode is prescoring */
// output class
PQuery_Set pquerys(get_numbered_newick_string(tree_));
for (const auto & s : query_msa_)
pquerys.emplace_back(s, num_branches);
// place all s on every edge
double logl, distal, pendant;
// omp_set_num_threads(4);
#pragma omp parallel for
for (unsigned int branch_id = 0; branch_id < num_branches; ++branch_id)
{
for (unsigned int sequence_id = 0; sequence_id < num_queries; ++sequence_id)
{
tie(logl, distal, pendant) = insertion_trees[branch_id].place(query_msa_[sequence_id]);
pquerys[sequence_id][branch_id] = Placement(
branch_id,
logl,
pendant,
distal);
}
}
// now that everything has been placed, we can compute the likelihood weight ratio
compute_and_set_lwr(pquerys);
/* prescoring was chosen: perform a second round, but only on candidate edges identified
during the first run */
// TODO for MPI: think about how to split up the work, probably build list of sequences
// per branch, then pass
if (options_.prescoring)
{
discard_by_accumulated_threshold(pquerys, 0.95);// TODO outside input? constant?
for (auto &pq : pquerys)
for (auto &placement : pq)
{
unsigned int id = placement.branch_id();
insertion_trees[id].opt_branches(true); // TODO only needs to be done once
tie(logl, distal, pendant) = insertion_trees[id].place(pq.sequence());
placement.likelihood(logl);
placement.pendant_length(pendant);
placement.distal_length(distal);
}
compute_and_set_lwr(pquerys);
}
// finally, trim the output
if (options_.acc_threshold)
discard_by_accumulated_threshold(pquerys, options_.support_threshold);
else
discard_by_support_threshold(pquerys, options_.support_threshold);
return pquerys;
}
<commit_msg>enabled collapse of query msa<commit_after>#include "Tree.hpp"
#include <stdexcept>
#include <iostream>
#include <omp.h>
#include "pll_util.hpp"
#include "epa_pll_util.hpp"
#include "file_io.hpp"
#include "Sequence.hpp"
#include "optimize.hpp"
#include "set_manipulators.hpp"
#include "logging.hpp"
using namespace std;
Tree::Tree(const string &tree_file, const MSA &msa, Model &model,
Options options, const MSA &query)
: ref_msa_(msa), query_msa_(query), model_(model), options_(options)
{
// parse, build tree
nums_ = Tree_Numbers();
tie(partition_, tree_) =
build_partition_from_file(tree_file, model_, nums_, ref_msa_.num_sites());
// split msa if no separate query msa was supplied
if (query.num_sites() == 0)
split_combined_msa(ref_msa_, query_msa_, tree_, nums_.tip_nodes);
valid_map_ = vector<Range>(nums_.tip_nodes);
link_tree_msa(tree_, partition_, ref_msa_, nums_.tip_nodes, valid_map_);
find_collapse_equal_sequences(query_msa_);
compute_and_set_empirical_frequencies(partition_, model_);
// perform branch length and model optimization on the reference tree
optimize(model_, tree_, partition_, nums_, options_.opt_branches,
options_.opt_model);
precompute_clvs(tree_, partition_, nums_);
lgr << "\nPost-optimization reference tree log-likelihood: ";
lgr << to_string(this->ref_tree_logl()) << endl;
}
double Tree::ref_tree_logl()
{
return pll_compute_edge_loglikelihood(
partition_, tree_->clv_index, tree_->scaler_index, tree_->back->clv_index,
tree_->back->scaler_index, tree_->pmatrix_index, 0);
}
Tree::~Tree()
{
// free data segment of tree nodes
utree_free_node_data(tree_);
pll_partition_destroy(partition_);
pll_utree_destroy(tree_);
}
PQuery_Set Tree::place()
{
const auto num_branches = nums_.branches;
const auto num_queries = query_msa_.size();
// get all edges
vector<pll_utree_t *> branches(num_branches);
auto num_traversed_branches = utree_query_branches(tree_, &branches[0]);
assert(num_traversed_branches == num_branches);
lgr << "\nPlacing "<< to_string(num_queries) << " reads on " <<
to_string(num_branches) << " branches." << endl;
// build all tiny trees with corresponding edges
vector<Tiny_Tree> insertion_trees;
for (auto node : branches)
insertion_trees.emplace_back(node, partition_, model_, !options_.prescoring);
/* clarification: last arg here is a flag specifying whether to optimize the branches.
we don't want that if the mode is prescoring */
// output class
PQuery_Set pquerys(get_numbered_newick_string(tree_));
for (const auto & s : query_msa_)
pquerys.emplace_back(s, num_branches);
// place all s on every edge
double logl, distal, pendant;
// omp_set_num_threads(4);
#pragma omp parallel for
for (unsigned int branch_id = 0; branch_id < num_branches; ++branch_id)
{
for (unsigned int sequence_id = 0; sequence_id < num_queries; ++sequence_id)
{
tie(logl, distal, pendant) = insertion_trees[branch_id].place(query_msa_[sequence_id]);
pquerys[sequence_id][branch_id] = Placement(
branch_id,
logl,
pendant,
distal);
}
}
// now that everything has been placed, we can compute the likelihood weight ratio
compute_and_set_lwr(pquerys);
/* prescoring was chosen: perform a second round, but only on candidate edges identified
during the first run */
// TODO for MPI: think about how to split up the work, probably build list of sequences
// per branch, then pass
if (options_.prescoring)
{
discard_by_accumulated_threshold(pquerys, 0.95);// TODO outside input? constant?
for (auto &pq : pquerys)
for (auto &placement : pq)
{
unsigned int id = placement.branch_id();
insertion_trees[id].opt_branches(true); // TODO only needs to be done once
tie(logl, distal, pendant) = insertion_trees[id].place(pq.sequence());
placement.likelihood(logl);
placement.pendant_length(pendant);
placement.distal_length(distal);
}
compute_and_set_lwr(pquerys);
}
// finally, trim the output
if (options_.acc_threshold)
discard_by_accumulated_threshold(pquerys, options_.support_threshold);
else
discard_by_support_threshold(pquerys, options_.support_threshold);
return pquerys;
}
<|endoftext|> |
<commit_before>/************************************
* file enc : ASCII
* author : wuyanyi09@gmail.com
************************************/
#ifndef CPPJIEBA_TRIE_H
#define CPPJIEBA_TRIE_H
#include <iostream>
#include <fstream>
#include <map>
#include <cstring>
#include <stdint.h>
#include <cmath>
#include <limits>
#include "Limonp/str_functs.hpp"
#include "Limonp/logger.hpp"
#include "Limonp/InitOnOff.hpp"
#include "TransCode.hpp"
namespace CppJieba
{
using namespace Limonp;
const double MIN_DOUBLE = -3.14e+100;
const double MAX_DOUBLE = 3.14e+100;
const size_t DICT_COLUMN_NUM = 3;
typedef unordered_map<uint16_t, struct TrieNode*> TrieNodeMap;
struct TrieNodeInfo;
struct TrieNode
{
TrieNodeMap hmap;
bool isLeaf;
const TrieNodeInfo * ptTrieNodeInfo;
TrieNode(): isLeaf(false), ptTrieNodeInfo(NULL)
{}
};
struct TrieNodeInfo
{
Unicode word;
size_t freq;
string tag;
double logFreq; //logFreq = log(freq/sum(freq));
};
inline ostream& operator << (ostream& os, const TrieNodeInfo & nodeInfo)
{
return os << nodeInfo.word << ":" << nodeInfo.freq << ":" << nodeInfo.tag << ":" << nodeInfo.logFreq ;
}
typedef map<size_t, const TrieNodeInfo*> DagType;
class Trie: public InitOnOff
{
private:
TrieNode* _root;
vector<TrieNodeInfo> _nodeInfos;
int64_t _freqSum;
double _minLogFreq;
public:
Trie()
{
_root = new TrieNode;
_freqSum = 0;
_minLogFreq = MAX_DOUBLE;
_setInitFlag(false);
}
Trie(const string& filePath)
{
Trie();
_setInitFlag(init(filePath));
}
~Trie()
{
_deleteNode(_root);
}
public:
bool init(const string& filePath)
{
assert(!_getInitFlag());
_loadDict(filePath, _nodeInfos);
_createTrie(_nodeInfos, _root);
_freqSum = _calculateFreqSum(_nodeInfos);
assert(_freqSum);
_minLogFreq = _calculateLogFreqAndGetMinValue(_nodeInfos, _freqSum);
return _setInitFlag(true);
}
public:
const TrieNodeInfo* find(Unicode::const_iterator begin, Unicode::const_iterator end)const
{
TrieNodeMap::const_iterator citer;
const TrieNode* p = _root;
for(Unicode::const_iterator it = begin; it != end; it++)
{
citer = p->hmap.find(*it);
if(p->hmap.end() == citer)
{
return NULL;
}
p = citer->second;
}
if(p->isLeaf)
{
return p->ptTrieNodeInfo;
}
return NULL;
}
bool find(Unicode::const_iterator begin, Unicode::const_iterator end, DagType & res, size_t offset = 0) const
{
const TrieNode* p = _root;
TrieNodeMap::const_iterator citer;
for (Unicode::const_iterator itr = begin; itr != end; itr++)
{
citer = p->hmap.find(*itr);
if(p->hmap.end() == citer)
{
break;
}
p = citer->second;
if(p->isLeaf)
{
res[itr - begin + offset] = p->ptTrieNodeInfo;
}
}
return !res.empty();
}
public:
double getMinLogFreq() const {return _minLogFreq;};
private:
void _insertNode(const TrieNodeInfo& nodeInfo, TrieNode* ptNode) const
{
const Unicode& unico = nodeInfo.word;
TrieNodeMap::const_iterator citer;
for(size_t i = 0; i < unico.size(); i++)
{
uint16_t cu = unico[i];
assert(ptNode);
citer = ptNode->hmap.find(cu);
if(ptNode->hmap.end() == citer)
{
TrieNode * next = new TrieNode;
ptNode->hmap[cu] = next;
ptNode = next;
}
else
{
ptNode = citer->second;
}
}
ptNode->isLeaf = true;
ptNode->ptTrieNodeInfo = &nodeInfo;
}
private:
void _loadDict(const string& filePath, vector<TrieNodeInfo>& nodeInfos) const
{
ifstream ifs(filePath.c_str());
if(!ifs)
{
LogFatal("open %s failed.", filePath.c_str());
exit(1);
}
string line;
vector<string> buf;
nodeInfos.clear();
TrieNodeInfo nodeInfo;
for(size_t lineno = 0 ; getline(ifs, line); lineno++)
{
split(line, buf, " ");
assert(buf.size() == DICT_COLUMN_NUM);
if(!TransCode::decode(buf[0], nodeInfo.word))
{
LogError("line[%u:%s] illegal.", lineno, line.c_str());
continue;
}
nodeInfo.freq = atoi(buf[1].c_str());
nodeInfo.tag = buf[2];
nodeInfos.push_back(nodeInfo);
}
}
bool _createTrie(const vector<TrieNodeInfo>& nodeInfos, TrieNode * ptNode)
{
for(size_t i = 0; i < _nodeInfos.size(); i++)
{
_insertNode(_nodeInfos[i], ptNode);
}
return true;
}
size_t _calculateFreqSum(const vector<TrieNodeInfo>& nodeInfos) const
{
size_t freqSum = 0;
for(size_t i = 0; i < nodeInfos.size(); i++)
{
freqSum += nodeInfos[i].freq;
}
return freqSum;
}
double _calculateLogFreqAndGetMinValue(vector<TrieNodeInfo>& nodeInfos, size_t freqSum) const
{
assert(freqSum);
double minLogFreq = MAX_DOUBLE;
for(size_t i = 0; i < nodeInfos.size(); i++)
{
TrieNodeInfo& nodeInfo = nodeInfos[i];
assert(nodeInfo.freq);
nodeInfo.logFreq = log(double(nodeInfo.freq)/double(freqSum));
if(minLogFreq > nodeInfo.logFreq)
{
minLogFreq = nodeInfo.logFreq;
}
}
return minLogFreq;
}
void _deleteNode(TrieNode* node)
{
if(!node)
{
return;
}
for(TrieNodeMap::iterator it = node->hmap.begin(); it != node->hmap.end(); it++)
{
TrieNode* next = it->second;
_deleteNode(next);
}
delete node;
}
};
}
#endif
<commit_msg>remove isLeaf is flag<commit_after>/************************************
* file enc : ASCII
* author : wuyanyi09@gmail.com
************************************/
#ifndef CPPJIEBA_TRIE_H
#define CPPJIEBA_TRIE_H
#include <iostream>
#include <fstream>
#include <map>
#include <cstring>
#include <stdint.h>
#include <cmath>
#include <limits>
#include "Limonp/str_functs.hpp"
#include "Limonp/logger.hpp"
#include "Limonp/InitOnOff.hpp"
#include "TransCode.hpp"
namespace CppJieba
{
using namespace Limonp;
const double MIN_DOUBLE = -3.14e+100;
const double MAX_DOUBLE = 3.14e+100;
const size_t DICT_COLUMN_NUM = 3;
typedef unordered_map<uint16_t, struct TrieNode*> TrieNodeMap;
struct TrieNodeInfo;
struct TrieNode
{
TrieNodeMap hmap;
const TrieNodeInfo * ptTrieNodeInfo;
TrieNode(): ptTrieNodeInfo(NULL)
{}
};
struct TrieNodeInfo
{
Unicode word;
size_t freq;
string tag;
double logFreq; //logFreq = log(freq/sum(freq));
};
inline ostream& operator << (ostream& os, const TrieNodeInfo & nodeInfo)
{
return os << nodeInfo.word << ":" << nodeInfo.freq << ":" << nodeInfo.tag << ":" << nodeInfo.logFreq ;
}
typedef map<size_t, const TrieNodeInfo*> DagType;
class Trie: public InitOnOff
{
private:
TrieNode* _root;
vector<TrieNodeInfo> _nodeInfos;
int64_t _freqSum;
double _minLogFreq;
public:
Trie()
{
_root = new TrieNode;
_freqSum = 0;
_minLogFreq = MAX_DOUBLE;
_setInitFlag(false);
}
Trie(const string& filePath)
{
Trie();
_setInitFlag(init(filePath));
}
~Trie()
{
_deleteNode(_root);
}
public:
bool init(const string& filePath)
{
assert(!_getInitFlag());
_loadDict(filePath, _nodeInfos);
_createTrie(_nodeInfos, _root);
_freqSum = _calculateFreqSum(_nodeInfos);
assert(_freqSum);
_minLogFreq = _calculateLogFreqAndGetMinValue(_nodeInfos, _freqSum);
return _setInitFlag(true);
}
public:
const TrieNodeInfo* find(Unicode::const_iterator begin, Unicode::const_iterator end)const
{
TrieNodeMap::const_iterator citer;
const TrieNode* p = _root;
for(Unicode::const_iterator it = begin; it != end; it++)
{
citer = p->hmap.find(*it);
if(p->hmap.end() == citer)
{
return NULL;
}
p = citer->second;
}
return p->ptTrieNodeInfo;
}
bool find(Unicode::const_iterator begin, Unicode::const_iterator end, DagType & res, size_t offset = 0) const
{
const TrieNode* p = _root;
TrieNodeMap::const_iterator citer;
for (Unicode::const_iterator itr = begin; itr != end; itr++)
{
citer = p->hmap.find(*itr);
if(p->hmap.end() == citer)
{
break;
}
p = citer->second;
if(p->ptTrieNodeInfo)
{
res[itr - begin + offset] = p->ptTrieNodeInfo;
}
}
return !res.empty();
}
public:
double getMinLogFreq() const {return _minLogFreq;};
private:
void _insertNode(const TrieNodeInfo& nodeInfo, TrieNode* ptNode) const
{
const Unicode& unico = nodeInfo.word;
TrieNodeMap::const_iterator citer;
for(size_t i = 0; i < unico.size(); i++)
{
uint16_t cu = unico[i];
assert(ptNode);
citer = ptNode->hmap.find(cu);
if(ptNode->hmap.end() == citer)
{
TrieNode * next = new TrieNode;
ptNode->hmap[cu] = next;
ptNode = next;
}
else
{
ptNode = citer->second;
}
}
ptNode->ptTrieNodeInfo = &nodeInfo;
}
private:
void _loadDict(const string& filePath, vector<TrieNodeInfo>& nodeInfos) const
{
ifstream ifs(filePath.c_str());
if(!ifs)
{
LogFatal("open %s failed.", filePath.c_str());
exit(1);
}
string line;
vector<string> buf;
nodeInfos.clear();
TrieNodeInfo nodeInfo;
for(size_t lineno = 0 ; getline(ifs, line); lineno++)
{
split(line, buf, " ");
assert(buf.size() == DICT_COLUMN_NUM);
if(!TransCode::decode(buf[0], nodeInfo.word))
{
LogError("line[%u:%s] illegal.", lineno, line.c_str());
continue;
}
nodeInfo.freq = atoi(buf[1].c_str());
nodeInfo.tag = buf[2];
nodeInfos.push_back(nodeInfo);
}
}
bool _createTrie(const vector<TrieNodeInfo>& nodeInfos, TrieNode * ptNode)
{
for(size_t i = 0; i < _nodeInfos.size(); i++)
{
_insertNode(_nodeInfos[i], ptNode);
}
return true;
}
size_t _calculateFreqSum(const vector<TrieNodeInfo>& nodeInfos) const
{
size_t freqSum = 0;
for(size_t i = 0; i < nodeInfos.size(); i++)
{
freqSum += nodeInfos[i].freq;
}
return freqSum;
}
double _calculateLogFreqAndGetMinValue(vector<TrieNodeInfo>& nodeInfos, size_t freqSum) const
{
assert(freqSum);
double minLogFreq = MAX_DOUBLE;
for(size_t i = 0; i < nodeInfos.size(); i++)
{
TrieNodeInfo& nodeInfo = nodeInfos[i];
assert(nodeInfo.freq);
nodeInfo.logFreq = log(double(nodeInfo.freq)/double(freqSum));
if(minLogFreq > nodeInfo.logFreq)
{
minLogFreq = nodeInfo.logFreq;
}
}
return minLogFreq;
}
void _deleteNode(TrieNode* node)
{
if(!node)
{
return;
}
for(TrieNodeMap::iterator it = node->hmap.begin(); it != node->hmap.end(); it++)
{
TrieNode* next = it->second;
_deleteNode(next);
}
delete node;
}
};
}
#endif
<|endoftext|> |
<commit_before>#ifndef CPPJIEBA_TRIE_HPP
#define CPPJIEBA_TRIE_HPP
#include "Limonp/StdExtension.hpp"
#include <vector>
#include <queue>
namespace CppJieba
{
using namespace std;
struct DictUnit
{
Unicode word;
double weight;
string tag;
};
// for debugging
inline ostream & operator << (ostream& os, const DictUnit& unit)
{
string s;
s << unit.word;
return os << string_format("%s %s %.3lf", s.c_str(), unit.tag.c_str(), unit.weight);
}
typedef LocalVector<std::pair<size_t, const DictUnit*> > DagType;
struct SegmentChar
{
uint16_t uniCh;
DagType dag;
const DictUnit * pInfo;
double weight;
size_t nextPos;
SegmentChar():uniCh(0), pInfo(NULL), weight(0.0), nextPos(0)
{}
~SegmentChar()
{}
};
typedef Unicode::value_type TrieKey;
class TrieNode
{
public:
typedef unordered_map<TrieKey, TrieNode*> NextMap;
public:
TrieNode * fail;
NextMap * next;
const DictUnit * ptValue;
public:
TrieNode(): fail(NULL), next(NULL), ptValue(NULL)
{}
const TrieNode * findNext(TrieKey key) const
{
if(next == NULL)
{
return NULL;
}
typename NextMap::const_iterator iter = next->find(key);
if(iter == next->end())
{
return NULL;
}
return iter->second;
}
};
class Trie
{
private:
TrieNode* _root;
public:
Trie(const vector<Unicode>& keys, const vector<const DictUnit*> & valuePointers)
{
_root = new TrieNode;
_createTrie(keys, valuePointers);
_build();// build automation
}
~Trie()
{
if(_root)
{
_deleteNode(_root);
}
}
public:
const DictUnit* find(typename Unicode::const_iterator begin, typename Unicode::const_iterator end) const
{
typename TrieNode::NextMap::const_iterator citer;
const TrieNode* ptNode = _root;
for(typename Unicode::const_iterator it = begin; it != end; it++)
{// build automation
assert(ptNode);
if(NULL == ptNode->next || ptNode->next->end() == (citer = ptNode->next->find(*it)))
{
return NULL;
}
ptNode = citer->second;
}
return ptNode->ptValue;
}
// aho-corasick-automation
void find(
typename Unicode::const_iterator begin,
typename Unicode::const_iterator end,
vector<struct SegmentChar>& res
) const
{
res.resize(end - begin);
const TrieNode * now = _root;
//typename TrieNode::NextMap::const_iterator iter;
const TrieNode* node;
// compiler will complain warnings if only "i < end - begin" .
for (size_t i = 0; i < size_t(end - begin); i++)
{
Unicode::value_type ch = *(begin + i);
res[i].uniCh = ch;
assert(res[i].dag.empty());
res[i].dag.push_back(pair<typename vector<Unicode >::size_type, const DictUnit* >(i, NULL));
bool flag = false;
// rollback
while( now != _root )
{
node = now->findNext(ch);
if (node != NULL)
{
flag = true;
break;
}
else
{
now = now->fail;
}
}
if(!flag)
{
node = now->findNext(ch);
}
if(node == NULL)
{
now = _root;
}
else
{
now = node;
const TrieNode * temp = now;
while(temp != _root)
{
if (temp->ptValue)
{
size_t pos = i - temp->ptValue->word.size() + 1;
res[pos].dag.push_back(pair<typename vector<Unicode >::size_type, const DictUnit* >(i, temp->ptValue));
if(pos == i)
{
res[pos].dag[0].second = temp->ptValue;
}
}
temp = temp->fail;
assert(temp);
}
}
}
}
bool find(
typename Unicode::const_iterator begin,
typename Unicode::const_iterator end,
DagType & res,
size_t offset = 0) const
{
const TrieNode * ptNode = _root;
typename TrieNode::NextMap::const_iterator citer;
for(typename Unicode::const_iterator itr = begin; itr != end ; itr++)
{
assert(ptNode);
if(NULL == ptNode->next || ptNode->next->end() == (citer = ptNode->next->find(*itr)))
{
break;
}
ptNode = citer->second;
if(ptNode->ptValue)
{
if(itr == begin && res.size() == 1) // first singleword
{
res[0].second = ptNode->ptValue;
}
else
{
res.push_back(pair<typename vector<Unicode >::size_type, const DictUnit* >(itr - begin + offset, ptNode->ptValue));
}
}
}
return !res.empty();
}
private:
void _build()
{
queue<TrieNode*> que;
assert(_root->ptValue == NULL);
assert(_root->next);
_root->fail = NULL;
for(typename TrieNode::NextMap::iterator iter = _root->next->begin(); iter != _root->next->end(); iter++) {
iter->second->fail = _root;
que.push(iter->second);
}
TrieNode* back = NULL;
typename TrieNode::NextMap::iterator backiter;
while(!que.empty()) {
TrieNode * now = que.front();
que.pop();
if(now->next == NULL) {
continue;
}
for(typename TrieNode::NextMap::iterator iter = now->next->begin(); iter != now->next->end(); iter++) {
back = now->fail;
while(back != NULL) {
if(back->next && (backiter = back->next->find(iter->first)) != back->next->end())
{
iter->second->fail = backiter->second;
break;
}
back = back->fail;
}
if(back == NULL) {
iter->second->fail = _root;
}
que.push(iter->second);
}
}
}
private:
void _createTrie(const vector<Unicode>& keys, const vector<const DictUnit*> & valuePointers)
{
if(valuePointers.empty() || keys.empty())
{
return;
}
assert(keys.size() == valuePointers.size());
for(size_t i = 0; i < keys.size(); i++)
{
_insertNode(keys[i], valuePointers[i]);
}
}
private:
void _insertNode(const Unicode& key, const DictUnit* ptValue)
{
TrieNode* ptNode = _root;
typename TrieNode::NextMap::const_iterator kmIter;
for(typename Unicode::const_iterator citer = key.begin(); citer != key.end(); citer++)
{
if(NULL == ptNode->next)
{
ptNode->next = new typename TrieNode::NextMap;
}
kmIter = ptNode->next->find(*citer);
if(ptNode->next->end() == kmIter)
{
TrieNode * nextNode = new TrieNode;
nextNode->next = NULL;
nextNode->ptValue = NULL;
(*ptNode->next)[*citer] = nextNode;
ptNode = nextNode;
}
else
{
ptNode = kmIter->second;
}
}
ptNode->ptValue = ptValue;
}
void _deleteNode(TrieNode* node)
{
if(!node)
{
return;
}
if(node->next)
{
typename TrieNode::NextMap::iterator it;
for(it = node->next->begin(); it != node->next->end(); it++)
{
_deleteNode(it->second);
}
delete node->next;
}
delete node;
}
};
}
#endif
<commit_msg>修复typename在不同版本编译器的兼容问题<commit_after>#ifndef CPPJIEBA_TRIE_HPP
#define CPPJIEBA_TRIE_HPP
#include "Limonp/StdExtension.hpp"
#include <vector>
#include <queue>
namespace CppJieba
{
using namespace std;
struct DictUnit
{
Unicode word;
double weight;
string tag;
};
// for debugging
inline ostream & operator << (ostream& os, const DictUnit& unit)
{
string s;
s << unit.word;
return os << string_format("%s %s %.3lf", s.c_str(), unit.tag.c_str(), unit.weight);
}
typedef LocalVector<std::pair<size_t, const DictUnit*> > DagType;
struct SegmentChar
{
uint16_t uniCh;
DagType dag;
const DictUnit * pInfo;
double weight;
size_t nextPos;
SegmentChar():uniCh(0), pInfo(NULL), weight(0.0), nextPos(0)
{}
~SegmentChar()
{}
};
typedef Unicode::value_type TrieKey;
class TrieNode
{
public:
typedef unordered_map<TrieKey, TrieNode*> NextMap;
public:
TrieNode * fail;
NextMap * next;
const DictUnit * ptValue;
public:
TrieNode(): fail(NULL), next(NULL), ptValue(NULL)
{}
const TrieNode * findNext(TrieKey key) const
{
if(next == NULL)
{
return NULL;
}
NextMap::const_iterator iter = next->find(key);
if(iter == next->end())
{
return NULL;
}
return iter->second;
}
};
class Trie
{
private:
TrieNode* _root;
public:
Trie(const vector<Unicode>& keys, const vector<const DictUnit*> & valuePointers)
{
_root = new TrieNode;
_createTrie(keys, valuePointers);
_build();// build automation
}
~Trie()
{
if(_root)
{
_deleteNode(_root);
}
}
public:
const DictUnit* find(Unicode::const_iterator begin, Unicode::const_iterator end) const
{
TrieNode::NextMap::const_iterator citer;
const TrieNode* ptNode = _root;
for(Unicode::const_iterator it = begin; it != end; it++)
{// build automation
assert(ptNode);
if(NULL == ptNode->next || ptNode->next->end() == (citer = ptNode->next->find(*it)))
{
return NULL;
}
ptNode = citer->second;
}
return ptNode->ptValue;
}
// aho-corasick-automation
void find(
Unicode::const_iterator begin,
Unicode::const_iterator end,
vector<struct SegmentChar>& res
) const
{
res.resize(end - begin);
const TrieNode * now = _root;
const TrieNode* node;
// compiler will complain warnings if only "i < end - begin" .
for (size_t i = 0; i < size_t(end - begin); i++)
{
Unicode::value_type ch = *(begin + i);
res[i].uniCh = ch;
assert(res[i].dag.empty());
res[i].dag.push_back(pair<vector<Unicode >::size_type, const DictUnit* >(i, NULL));
bool flag = false;
// rollback
while( now != _root )
{
node = now->findNext(ch);
if (node != NULL)
{
flag = true;
break;
}
else
{
now = now->fail;
}
}
if(!flag)
{
node = now->findNext(ch);
}
if(node == NULL)
{
now = _root;
}
else
{
now = node;
const TrieNode * temp = now;
while(temp != _root)
{
if (temp->ptValue)
{
size_t pos = i - temp->ptValue->word.size() + 1;
res[pos].dag.push_back(pair<vector<Unicode >::size_type, const DictUnit* >(i, temp->ptValue));
if(pos == i)
{
res[pos].dag[0].second = temp->ptValue;
}
}
temp = temp->fail;
assert(temp);
}
}
}
}
bool find(
Unicode::const_iterator begin,
Unicode::const_iterator end,
DagType & res,
size_t offset = 0) const
{
const TrieNode * ptNode = _root;
TrieNode::NextMap::const_iterator citer;
for(Unicode::const_iterator itr = begin; itr != end ; itr++)
{
assert(ptNode);
if(NULL == ptNode->next || ptNode->next->end() == (citer = ptNode->next->find(*itr)))
{
break;
}
ptNode = citer->second;
if(ptNode->ptValue)
{
if(itr == begin && res.size() == 1) // first singleword
{
res[0].second = ptNode->ptValue;
}
else
{
res.push_back(pair<vector<Unicode >::size_type, const DictUnit* >(itr - begin + offset, ptNode->ptValue));
}
}
}
return !res.empty();
}
private:
void _build()
{
queue<TrieNode*> que;
assert(_root->ptValue == NULL);
assert(_root->next);
_root->fail = NULL;
for(TrieNode::NextMap::iterator iter = _root->next->begin(); iter != _root->next->end(); iter++) {
iter->second->fail = _root;
que.push(iter->second);
}
TrieNode* back = NULL;
TrieNode::NextMap::iterator backiter;
while(!que.empty()) {
TrieNode * now = que.front();
que.pop();
if(now->next == NULL) {
continue;
}
for(TrieNode::NextMap::iterator iter = now->next->begin(); iter != now->next->end(); iter++) {
back = now->fail;
while(back != NULL) {
if(back->next && (backiter = back->next->find(iter->first)) != back->next->end())
{
iter->second->fail = backiter->second;
break;
}
back = back->fail;
}
if(back == NULL) {
iter->second->fail = _root;
}
que.push(iter->second);
}
}
}
private:
void _createTrie(const vector<Unicode>& keys, const vector<const DictUnit*> & valuePointers)
{
if(valuePointers.empty() || keys.empty())
{
return;
}
assert(keys.size() == valuePointers.size());
for(size_t i = 0; i < keys.size(); i++)
{
_insertNode(keys[i], valuePointers[i]);
}
}
private:
void _insertNode(const Unicode& key, const DictUnit* ptValue)
{
TrieNode* ptNode = _root;
TrieNode::NextMap::const_iterator kmIter;
for(Unicode::const_iterator citer = key.begin(); citer != key.end(); citer++)
{
if(NULL == ptNode->next)
{
ptNode->next = new TrieNode::NextMap;
}
kmIter = ptNode->next->find(*citer);
if(ptNode->next->end() == kmIter)
{
TrieNode * nextNode = new TrieNode;
nextNode->next = NULL;
nextNode->ptValue = NULL;
(*ptNode->next)[*citer] = nextNode;
ptNode = nextNode;
}
else
{
ptNode = kmIter->second;
}
}
ptNode->ptValue = ptValue;
}
void _deleteNode(TrieNode* node)
{
if(!node)
{
return;
}
if(node->next)
{
TrieNode::NextMap::iterator it;
for(it = node->next->begin(); it != node->next->end(); it++)
{
_deleteNode(it->second);
}
delete node->next;
}
delete node;
}
};
}
#endif
<|endoftext|> |
<commit_before>#include <vector>
#include <string>
#include "JsonBox.h"
#include "area.hpp"
#include "entity.hpp"
#include "inventory.hpp"
#include "creature.hpp"
#include "dialogue.hpp"
#include "entity_manager.hpp"
Area::Area(std::string id, Dialogue dialogue, Inventory items,
std::vector<Creature*> creatures) : Entity(id)
{
this->dialogue = dialogue;
this->items = items;
for(auto creature : creatures)
{
this->creatures.push_back(*creature);
}
}
Area::Area(std::string id, JsonBox::Value& v, EntityManager* mgr) : Entity(id)
{
this->load(v, mgr);
}
void Area::load(JsonBox::Value& v, EntityManager* mgr)
{
JsonBox::Object o = v.getObject();
// Build the dialogue
// This is an optional parameter because it will not be saved
// when the area is modified
if(o.find("dialogue") != o.end())
this->dialogue = Dialogue(o["dialogue"]);
// Build the inventory
this->items = Inventory(o["inventory"], mgr);
// Build the creature list
this->creatures.clear();
for(auto creature : o["creatures"].getArray())
{
// Create a new creature instance indentical to the version
// in the entity manager
Creature c(*mgr->getEntity<Creature>(creature.getString()));
this->creatures.push_back(c);
}
// Attach doors
if(o.find("doors") != o.end())
{
this->doors.clear();
for(auto door : o["doors"].getArray())
{
this->doors.push_back(mgr->getEntity<Door>(door.getString()));
}
}
return;
}
JsonBox::Object Area::getJson()
{
JsonBox::Object o;
// We don't need to save the dialogue because it doesn't change
// Save the inventory
o["inventory"] = this->items.getJson();
// Save the creatures
JsonBox::Array a;
for(auto creature : this->creatures)
{
a.push_back(JsonBox::Value(creature.id));
}
o["creatures"] = a;
return o;
}
<commit_msg>Door lock status is now (optionally) saved and loaded by the areas<commit_after>#include <vector>
#include <string>
#include "JsonBox.h"
#include "area.hpp"
#include "door.hpp"
#include "entity.hpp"
#include "inventory.hpp"
#include "creature.hpp"
#include "dialogue.hpp"
#include "entity_manager.hpp"
Area::Area(std::string id, Dialogue dialogue, Inventory items,
std::vector<Creature*> creatures) : Entity(id)
{
this->dialogue = dialogue;
this->items = items;
for(auto creature : creatures)
{
this->creatures.push_back(*creature);
}
}
Area::Area(std::string id, JsonBox::Value& v, EntityManager* mgr) : Entity(id)
{
this->load(v, mgr);
}
void Area::load(JsonBox::Value& v, EntityManager* mgr)
{
JsonBox::Object o = v.getObject();
// Build the dialogue
// This is an optional parameter because it will not be saved
// when the area is modified
if(o.find("dialogue") != o.end())
this->dialogue = Dialogue(o["dialogue"]);
// Build the inventory
this->items = Inventory(o["inventory"], mgr);
// Build the creature list
this->creatures.clear();
for(auto creature : o["creatures"].getArray())
{
// Create a new creature instance indentical to the version
// in the entity manager
Creature c(*mgr->getEntity<Creature>(creature.getString()));
this->creatures.push_back(c);
}
// Attach doors
if(o.find("doors") != o.end())
{
this->doors.clear();
for(auto door : o["doors"].getArray())
{
Door* d = nullptr;
// Each door is either an array of the type [id, locked] or
// a single id string.
if(door.isString())
{
d = mgr->getEntity<Door>(door.getString());
}
else
{
d = mgr->getEntity<Door>(door.getArray()[0].getString());
d->locked = door.getArray()[1].getInteger();
}
this->doors.push_back(d);
}
}
return;
}
JsonBox::Object Area::getJson()
{
JsonBox::Object o;
// We don't need to save the dialogue because it doesn't change
// Save the inventory
o["inventory"] = this->items.getJson();
// Save the creatures
JsonBox::Array a;
for(auto creature : this->creatures)
{
a.push_back(JsonBox::Value(creature.id));
}
o["creatures"] = a;
// Save the doors
a.clear();
for(auto door : this->doors)
{
JsonBox::Array d;
d.push_back(door->id);
d.push_back(door->locked);
a.push_back(d);
}
o["doors"] = a;
return o;
}
<|endoftext|> |
<commit_before>#include "RTIMULib.h"
#include <fstream>
#include <iostream>
std::ostream &operator<<(std::ostream &stream, const RTVector3 &vector)
{
stream<<vector.x()<<" "<<vector.y()<<" "<<vector.z();
return stream;
}
std::ostream &operator<<(std::ostream &stream, const RTQuaternion &q)
{
stream<<q.scalar()<<" "<<q.x()<<" "<<q.y()<<" "<<q.z();
return stream;
}
std::ostream &operator<<(std::ostream &stream, const RTIMU_DATA &data)
{
stream<<data.fusionQPose<< " " << data.accel;
return stream;
}
int main(int argc, char **argv)
{
int sampleCount = 0;
int sampleRate = 0;
uint64_t rateTimer;
uint64_t displayTimer;
uint64_t now;
RTIMUSettings *settings = new RTIMUSettings("RTIMULib");
RTIMU *imu = RTIMU::createIMU(settings);
if ((imu == NULL) || (imu->IMUType() == RTIMU_TYPE_NULL)) {
std::cerr<<"No IMU found\n"<<std::endl;
exit(1);
}
imu->IMUInit();
imu->setSlerpPower(0.02);
imu->setGyroEnable(true);
imu->setAccelEnable(true);
imu->setCompassEnable(true);
std::fstream fs;
fs.open("output.m", std::fstream::out);
fs << "[\n";
rateTimer = RTMath::currentUSecsSinceEpoch();
for (int i = 0; i < 1000; ++i)
{
usleep(imu->IMUGetPollInterval() * 1000);
while(imu->IMURead())
{
RTIMU_DATA imuData = imu->getIMUData();
fs << imuData.timestamp << " " << imuData << std::endl;
}
}
fs << "];";
fs.close();
delete imu;
delete settings;
}
<commit_msg>Apply clang formatting to blow.cpp<commit_after>#include "RTIMULib.h"
#include <fstream>
#include <iostream>
std::ostream &operator<<(std::ostream &stream, const RTVector3 &vector)
{
stream << vector.x() << " " << vector.y() << " " << vector.z();
return stream;
}
std::ostream &operator<<(std::ostream &stream, const RTQuaternion &q)
{
stream << q.scalar() << " " << q.x() << " " << q.y() << " " << q.z();
return stream;
}
std::ostream &operator<<(std::ostream &stream, const RTIMU_DATA &data)
{
stream << data.fusionQPose << " " << data.accel;
return stream;
}
int main(int argc, char **argv)
{
int sampleCount = 0;
int sampleRate = 0;
uint64_t rateTimer;
uint64_t displayTimer;
uint64_t now;
RTIMUSettings *settings = new RTIMUSettings("RTIMULib");
RTIMU *imu = RTIMU::createIMU(settings);
if ((imu == NULL) || (imu->IMUType() == RTIMU_TYPE_NULL))
{
std::cerr << "No IMU found\n" << std::endl;
exit(1);
}
imu->IMUInit();
imu->setSlerpPower(0.02);
imu->setGyroEnable(true);
imu->setAccelEnable(true);
imu->setCompassEnable(true);
std::fstream fs;
fs.open("output.m", std::fstream::out);
fs << "[\n";
rateTimer = RTMath::currentUSecsSinceEpoch();
for (int i = 0; i < 1000; ++i)
{
usleep(imu->IMUGetPollInterval() * 1000);
while (imu->IMURead())
{
RTIMU_DATA imuData = imu->getIMUData();
fs << imuData.timestamp << " " << imuData << std::endl;
}
}
fs << "];";
fs.close();
delete imu;
delete settings;
}
<|endoftext|> |
<commit_before>
#include <girepository.h>
#include <glib.h>
#include "boxed.h"
#include "debug.h"
#include "function.h"
#include "gi.h"
#include "gobject.h"
#include "type.h"
#include "util.h"
#include "value.h"
using v8::Array;
using v8::External;
using v8::Function;
using v8::FunctionTemplate;
using v8::Isolate;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::String;
//using v8::WeakCallbackInfo;
using v8::Persistent;
using Nan::New;
using Nan::WeakCallbackType;
namespace GNodeJS {
// https://github.com/TooTallNate/node-weak/blob/master/src/weakref.cc
/*static void InitBoxedFromStruct (Local<Object> self, GIStructInfo *info) {
* gpointer pointer = self->GetAlignedPointerFromInternalField(0);
*
* int n_fields = g_struct_info_get_n_fields(info);
* for (int i = 0; i < n_fields; i++) {
* GIFieldInfo *field = g_struct_info_get_field(info, i);
* const char *fieldName = g_base_info_get_name(field);
* GIArgument value;
*
* if (g_field_info_get_field(field, pointer, &value)) {
* GITypeInfo *fieldType = g_field_info_get_type(field);
* char *_name = g_strdup_printf("_%s", fieldName);
*
* self->Set(
* UTF8(_name),
* GIArgumentToV8(fieldType, &value));
*
* g_base_info_unref (fieldType);
* g_free(_name);
* }
*
* g_base_info_unref (field);
* }
*}
static void InitBoxedFromUnion (Local<Object> self, GIUnionInfo *info) {
void *boxed = self->GetAlignedPointerFromInternalField(0);
int n_fields = g_union_info_get_n_fields(info);
for (int i = 0; i < n_fields; i++) {
GIArgument value;
GIFieldInfo *field = g_union_info_get_field(info, i);
bool success = g_field_info_get_field(field, boxed, &value);
if (success) {
GITypeInfo *field_type = g_field_info_get_type(field);
const char *fieldName = g_base_info_get_name(field);
self->Set( UTF8(fieldName), GIArgumentToV8(field_type, &value));
GIStructInfo *union_type;
GIFieldInfo *union_field;
GITypeInfo *union_info;
union_field = g_union_info_get_field(info, value.v_int);
union_info = g_field_info_get_type(union_field);
GITypeTag tag = g_type_info_get_tag(union_info);
if (tag == GI_TYPE_TAG_INTERFACE) {
union_type = g_type_info_get_interface(union_info);
GType gtype = g_registered_type_info_get_g_type(union_type);
auto tpl = GetBoxedTemplate(union_type, gtype);
auto p_tpl = tpl->PrototypeTemplate();
Nan::Set(self, UTF8("__p_tpl__"), p_tpl->NewInstance());
g_base_info_unref(union_type);
}
g_base_info_unref(union_info);
g_base_info_unref(union_field);
g_base_info_unref(field_type);
}
g_base_info_unref(field);
//if (success) break;
}
}
*/
size_t Boxed::GetSize (GIBaseInfo *boxed_info) {
GIInfoType i_type = g_base_info_get_type(boxed_info);
if (i_type == GI_INFO_TYPE_STRUCT) {
return g_struct_info_get_size((GIStructInfo*)boxed_info);
} else if (i_type == GI_INFO_TYPE_UNION) {
return g_union_info_get_size((GIUnionInfo*)boxed_info);
} else {
g_assert_not_reached();
}
}
static void BoxedDestroyed(const Nan::WeakCallbackInfo<Boxed> &info);
static void BoxedConstructor(const Nan::FunctionCallbackInfo<Value> &args) {
/* See gobject.cc for how this works */
if (!args.IsConstructCall ()) {
Nan::ThrowTypeError("Not a construct call");
return;
}
void *boxed = NULL;
unsigned long size = 0;
Local<Object> self = args.This ();
GIBaseInfo *gi_info = (GIBaseInfo *) External::Cast (
*args.Data ())->Value ();
GIInfoType type = g_base_info_get_type (gi_info);
if (args[0]->IsExternal ()) {
/* The External case. This is how WrapperFromBoxed is called. */
void *data = External::Cast(*args[0])->Value();
boxed = data;
// FIXME? void *boxed = g_boxed_copy(g_type, data);
self->SetAlignedPointerInInternalField (0, data);
// TODO: this
// if (type == GI_INFO_TYPE_UNION)
// DEBUG("BoxedConstructor: union gi_info: %s", g_base_info_get_name(gi_info));
} else {
size = Boxed::GetSize(gi_info);
boxed = g_slice_alloc0(size);
self->SetAlignedPointerInInternalField (0, boxed);
}
auto* cont = new Boxed();
cont->data = boxed;
cont->size = size;
cont->g_type = g_registered_type_info_get_g_type(gi_info);
cont->persistent = new Nan::Persistent<Object>(self);
cont->persistent->SetWeak(cont, BoxedDestroyed, Nan::WeakCallbackType::kParameter);
}
static void BoxedDestroyed(const Nan::WeakCallbackInfo<Boxed> &info) {
Boxed *box = info.GetParameter();
if (G_TYPE_IS_BOXED(box->g_type)) {
g_boxed_free(box->g_type, box->data);
} else {
//
if (box->size != 0)
g_slice_free1(box->size, box->data);
//else
//DEBUG("BoxedDestroyed: not a boxed %zu", box->g_type);
//WARN("NOT FREED %#zx", (ulong)box->data);
}
delete box->persistent;
delete box;
}
void FieldGetter(Local<String> property, Nan::NAN_GETTER_ARGS_TYPE info) {
// Local<v8::String> property
Local<Object> self = info.This();
External *data = External::Cast(*info.Data());
void *boxed = self->GetAlignedPointerFromInternalField(0);
if (boxed == NULL) {
g_warning("FieldGetter: NULL boxed pointer");
return;
}
GIArgument value;
GIFieldInfo *field = static_cast<GIFieldInfo*>(data->Value());
g_assert(field);
if (g_field_info_get_field(field, boxed, &value)) {
GITypeInfo *field_type = g_field_info_get_type(field);
info.GetReturnValue().Set(GIArgumentToV8(field_type, &value));
g_base_info_unref (field_type);
// GNodeJS::reeGIArgument(field_type, &value);
} else {
DEBUG("FieldGetter: couldnt get field %s", g_base_info_get_name(field));
DEBUG("FieldGetter: property name: %s", *Nan::Utf8String(property) );
}
}
void FieldSetter(Local<String> property,
Local<Value> value,
Nan::NAN_SETTER_ARGS_TYPE info) {
//Isolate *isolate = info.GetIsolate();
Local<Object> self = info.This();
void *boxed = self->GetAlignedPointerFromInternalField(0);
GIFieldInfo *field = static_cast<GIFieldInfo*>(External::Cast(*info.Data())->Value());
GITypeInfo *field_type = g_field_info_get_type(field);
GIArgument arg;
if (V8ToGIArgument(field_type, &arg, value, true)) {
if (g_field_info_set_field(field, boxed, &arg) == FALSE)
DEBUG("FieldSetter: couldnt set field %s", g_base_info_get_name(field));
FreeGIArgument(field_type, &arg);
} else {
DEBUG("FieldSetter: couldnt convert value for field %s", g_base_info_get_name(field));
}
g_base_info_unref (field_type);
}
Local<FunctionTemplate> GetBoxedTemplate(GIBaseInfo *info, GType gtype) {
void *data = NULL;
if (gtype != G_TYPE_NONE)
data = g_type_get_qdata(gtype, GNodeJS::template_quark());
// Template already created
if (data) {
Persistent<FunctionTemplate> *persistent = (Persistent<FunctionTemplate> *) data;
Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate> (*persistent);
return tpl;
}
// Template not created yet
auto tpl = New<FunctionTemplate>(BoxedConstructor, New<External>(info));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
if (gtype != G_TYPE_NONE) {
const char *class_name = g_type_name(gtype);
tpl->SetClassName( UTF8(class_name) );
tpl->Set(UTF8("gtype"), Nan::New<Number>(gtype));
} else {
const char *class_name = g_base_info_get_name (info);
tpl->SetClassName( UTF8(class_name) );
}
if (GI_IS_STRUCT_INFO(info)) {
//int n_fields = g_struct_info_get_n_fields(info);
//for (int i = 0; i < n_fields; i++) {
//GIFieldInfo *field = g_struct_info_get_field(info, i);
//const char *name = g_base_info_get_name(field);
////char *jsName = Util::toCamelCase(name);
//Nan::SetAccessor( tpl->InstanceTemplate(),
//UTF8(name), //UTF8(jsName),
//FieldGetter, //FieldSetter,
//Nan::New<External>(field));
////g_base_info_unref (field);
//}
} else if (GI_IS_UNION_INFO(info)) {
// XXX this
} else if (g_base_info_get_type (info) == GI_INFO_TYPE_BOXED) {
// XXX this
} else {
g_assert_not_reached ();
}
if (gtype == G_TYPE_NONE)
return tpl;
Isolate *isolate = Isolate::GetCurrent();
auto *persistent = new v8::Persistent<FunctionTemplate>(isolate, tpl);
persistent->SetWeak(
g_base_info_ref(info),
GNodeJS::ClassDestroyed,
WeakCallbackType::kParameter);
g_type_set_qdata(gtype, GNodeJS::template_quark(), persistent);
return tpl;
}
static Local<FunctionTemplate> GetBoxedTemplateFromGI(GIBaseInfo *info) {
GType gtype = g_registered_type_info_get_g_type ((GIRegisteredTypeInfo *) info);
if (gtype == G_TYPE_NONE) {
/* g_warning("GetBoxedTemplateFromGI: gtype == G_TYPE_NONE for %s",
* g_base_info_get_name(info)); */
} else {
g_type_ensure(gtype);
}
return GetBoxedTemplate (info, gtype);
}
Local<Function> MakeBoxedClass(GIBaseInfo *info) {
Local<FunctionTemplate> tpl = GetBoxedTemplateFromGI (info);
return tpl->GetFunction ();
}
Local<Value> WrapperFromBoxed(GIBaseInfo *info, void *data) {
Local<Function> constructor = MakeBoxedClass (info);
Local<Value> boxed_external = Nan::New<External> (data);
Local<Value> args[] = { boxed_external };
Local<Object> obj = Nan::NewInstance(constructor, 1, args).ToLocalChecked();
return obj;
}
void* BoxedFromWrapper(Local<Value> value) {
Local<Object> object = value->ToObject ();
g_assert(object->InternalFieldCount() > 0);
void *boxed = object->GetAlignedPointerFromInternalField(0);
return boxed;
}
};
<commit_msg>boxed.cc: add warnings<commit_after>
#include <girepository.h>
#include <glib.h>
#include "boxed.h"
#include "debug.h"
#include "function.h"
#include "gi.h"
#include "gobject.h"
#include "type.h"
#include "util.h"
#include "value.h"
using v8::Array;
using v8::External;
using v8::Function;
using v8::FunctionTemplate;
using v8::Isolate;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::String;
//using v8::WeakCallbackInfo;
using v8::Persistent;
using Nan::New;
using Nan::WeakCallbackType;
namespace GNodeJS {
// https://github.com/TooTallNate/node-weak/blob/master/src/weakref.cc
/*static void InitBoxedFromStruct (Local<Object> self, GIStructInfo *info) {
* gpointer pointer = self->GetAlignedPointerFromInternalField(0);
*
* int n_fields = g_struct_info_get_n_fields(info);
* for (int i = 0; i < n_fields; i++) {
* GIFieldInfo *field = g_struct_info_get_field(info, i);
* const char *fieldName = g_base_info_get_name(field);
* GIArgument value;
*
* if (g_field_info_get_field(field, pointer, &value)) {
* GITypeInfo *fieldType = g_field_info_get_type(field);
* char *_name = g_strdup_printf("_%s", fieldName);
*
* self->Set(
* UTF8(_name),
* GIArgumentToV8(fieldType, &value));
*
* g_base_info_unref (fieldType);
* g_free(_name);
* }
*
* g_base_info_unref (field);
* }
*}
static void InitBoxedFromUnion (Local<Object> self, GIUnionInfo *info) {
void *boxed = self->GetAlignedPointerFromInternalField(0);
int n_fields = g_union_info_get_n_fields(info);
for (int i = 0; i < n_fields; i++) {
GIArgument value;
GIFieldInfo *field = g_union_info_get_field(info, i);
bool success = g_field_info_get_field(field, boxed, &value);
if (success) {
GITypeInfo *field_type = g_field_info_get_type(field);
const char *fieldName = g_base_info_get_name(field);
self->Set( UTF8(fieldName), GIArgumentToV8(field_type, &value));
GIStructInfo *union_type;
GIFieldInfo *union_field;
GITypeInfo *union_info;
union_field = g_union_info_get_field(info, value.v_int);
union_info = g_field_info_get_type(union_field);
GITypeTag tag = g_type_info_get_tag(union_info);
if (tag == GI_TYPE_TAG_INTERFACE) {
union_type = g_type_info_get_interface(union_info);
GType gtype = g_registered_type_info_get_g_type(union_type);
auto tpl = GetBoxedTemplate(union_type, gtype);
auto p_tpl = tpl->PrototypeTemplate();
Nan::Set(self, UTF8("__p_tpl__"), p_tpl->NewInstance());
g_base_info_unref(union_type);
}
g_base_info_unref(union_info);
g_base_info_unref(union_field);
g_base_info_unref(field_type);
}
g_base_info_unref(field);
//if (success) break;
}
}
*/
size_t Boxed::GetSize (GIBaseInfo *boxed_info) {
GIInfoType i_type = g_base_info_get_type(boxed_info);
if (i_type == GI_INFO_TYPE_STRUCT) {
return g_struct_info_get_size((GIStructInfo*)boxed_info);
} else if (i_type == GI_INFO_TYPE_UNION) {
return g_union_info_get_size((GIUnionInfo*)boxed_info);
} else {
g_assert_not_reached();
}
}
static void BoxedDestroyed(const Nan::WeakCallbackInfo<Boxed> &info);
static void BoxedConstructor(const Nan::FunctionCallbackInfo<Value> &args) {
/* See gobject.cc for how this works */
if (!args.IsConstructCall ()) {
Nan::ThrowTypeError("Not a construct call");
return;
}
void *boxed = NULL;
unsigned long size = 0;
Local<Object> self = args.This ();
GIBaseInfo *gi_info = (GIBaseInfo *) External::Cast (*args.Data ())->Value ();
if (args[0]->IsExternal ()) {
/* The External case. This is how WrapperFromBoxed is called. */
void *data = External::Cast(*args[0])->Value();
boxed = data;
// FIXME? void *boxed = g_boxed_copy(g_type, data);
self->SetAlignedPointerInInternalField (0, data);
// TODO: this
// if (type == GI_INFO_TYPE_UNION)
// DEBUG("BoxedConstructor: union gi_info: %s", g_base_info_get_name(gi_info));
} else {
/* User code calling `new Pango.AttrList()` */
size = Boxed::GetSize(gi_info);
boxed = g_slice_alloc0(size);
self->SetAlignedPointerInInternalField (0, boxed);
if (size == 0) {
g_warning("Boxed: %s: requested size is 0", g_base_info_get_name(gi_info));
} else if (!boxed) {
g_warning("Boxed: %s: allocation returned NULL", g_base_info_get_name(gi_info));
}
}
auto* cont = new Boxed();
cont->data = boxed;
cont->size = size;
cont->g_type = g_registered_type_info_get_g_type(gi_info);
cont->persistent = new Nan::Persistent<Object>(self);
cont->persistent->SetWeak(cont, BoxedDestroyed, Nan::WeakCallbackType::kParameter);
}
static void BoxedDestroyed(const Nan::WeakCallbackInfo<Boxed> &info) {
Boxed *box = info.GetParameter();
GIBaseInfo *base_info = g_irepository_find_by_gtype(NULL, box->g_type);
if (G_TYPE_IS_BOXED(box->g_type)) {
g_boxed_free(box->g_type, box->data);
} else {
//
if (box->size != 0)
g_slice_free1(box->size, box->data);
else if (box->data)
g_warning("BoxedDestroyed: %s: memory not freed", g_base_info_get_name(base_info));
}
delete box->persistent;
delete box;
}
void FieldGetter(Local<String> property, Nan::NAN_GETTER_ARGS_TYPE info) {
// Local<v8::String> property
Local<Object> self = info.This();
External *data = External::Cast(*info.Data());
void *boxed = self->GetAlignedPointerFromInternalField(0);
if (boxed == NULL) {
g_warning("FieldGetter: NULL boxed pointer");
return;
}
GIArgument value;
GIFieldInfo *field = static_cast<GIFieldInfo*>(data->Value());
g_assert(field);
if (g_field_info_get_field(field, boxed, &value)) {
GITypeInfo *field_type = g_field_info_get_type(field);
info.GetReturnValue().Set(GIArgumentToV8(field_type, &value));
g_base_info_unref (field_type);
// GNodeJS::reeGIArgument(field_type, &value);
} else {
DEBUG("FieldGetter: couldnt get field %s", g_base_info_get_name(field));
DEBUG("FieldGetter: property name: %s", *Nan::Utf8String(property) );
}
}
void FieldSetter(Local<String> property,
Local<Value> value,
Nan::NAN_SETTER_ARGS_TYPE info) {
//Isolate *isolate = info.GetIsolate();
Local<Object> self = info.This();
void *boxed = self->GetAlignedPointerFromInternalField(0);
GIFieldInfo *field = static_cast<GIFieldInfo*>(External::Cast(*info.Data())->Value());
GITypeInfo *field_type = g_field_info_get_type(field);
GIArgument arg;
if (V8ToGIArgument(field_type, &arg, value, true)) {
if (g_field_info_set_field(field, boxed, &arg) == FALSE)
DEBUG("FieldSetter: couldnt set field %s", g_base_info_get_name(field));
FreeGIArgument(field_type, &arg);
} else {
DEBUG("FieldSetter: couldnt convert value for field %s", g_base_info_get_name(field));
}
g_base_info_unref (field_type);
}
Local<FunctionTemplate> GetBoxedTemplate(GIBaseInfo *info, GType gtype) {
void *data = NULL;
if (gtype != G_TYPE_NONE)
data = g_type_get_qdata(gtype, GNodeJS::template_quark());
// Template already created
if (data) {
Persistent<FunctionTemplate> *persistent = (Persistent<FunctionTemplate> *) data;
Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate> (*persistent);
return tpl;
}
// Template not created yet
auto tpl = New<FunctionTemplate>(BoxedConstructor, New<External>(info));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
if (gtype != G_TYPE_NONE) {
const char *class_name = g_type_name(gtype);
tpl->SetClassName( UTF8(class_name) );
tpl->Set(UTF8("gtype"), Nan::New<Number>(gtype));
} else {
const char *class_name = g_base_info_get_name (info);
tpl->SetClassName( UTF8(class_name) );
}
if (GI_IS_STRUCT_INFO(info)) {
//int n_fields = g_struct_info_get_n_fields(info);
//for (int i = 0; i < n_fields; i++) {
//GIFieldInfo *field = g_struct_info_get_field(info, i);
//const char *name = g_base_info_get_name(field);
////char *jsName = Util::toCamelCase(name);
//Nan::SetAccessor( tpl->InstanceTemplate(),
//UTF8(name), //UTF8(jsName),
//FieldGetter, //FieldSetter,
//Nan::New<External>(field));
////g_base_info_unref (field);
//}
} else if (GI_IS_UNION_INFO(info)) {
// XXX this
} else if (g_base_info_get_type (info) == GI_INFO_TYPE_BOXED) {
// XXX this
} else {
g_assert_not_reached ();
}
if (gtype == G_TYPE_NONE)
return tpl;
Isolate *isolate = Isolate::GetCurrent();
auto *persistent = new v8::Persistent<FunctionTemplate>(isolate, tpl);
persistent->SetWeak(
g_base_info_ref(info),
GNodeJS::ClassDestroyed,
WeakCallbackType::kParameter);
g_type_set_qdata(gtype, GNodeJS::template_quark(), persistent);
return tpl;
}
static Local<FunctionTemplate> GetBoxedTemplateFromGI(GIBaseInfo *info) {
GType gtype = g_registered_type_info_get_g_type ((GIRegisteredTypeInfo *) info);
if (gtype == G_TYPE_NONE) {
/* g_warning("GetBoxedTemplateFromGI: gtype == G_TYPE_NONE for %s",
* g_base_info_get_name(info)); */
} else {
g_type_ensure(gtype);
}
return GetBoxedTemplate (info, gtype);
}
Local<Function> MakeBoxedClass(GIBaseInfo *info) {
Local<FunctionTemplate> tpl = GetBoxedTemplateFromGI (info);
return tpl->GetFunction ();
}
Local<Value> WrapperFromBoxed(GIBaseInfo *info, void *data) {
Local<Function> constructor = MakeBoxedClass (info);
Local<Value> boxed_external = Nan::New<External> (data);
Local<Value> args[] = { boxed_external };
Local<Object> obj = Nan::NewInstance(constructor, 1, args).ToLocalChecked();
return obj;
}
void* BoxedFromWrapper(Local<Value> value) {
Local<Object> object = value->ToObject ();
g_assert(object->InternalFieldCount() > 0);
void *boxed = object->GetAlignedPointerFromInternalField(0);
return boxed;
}
};
<|endoftext|> |
<commit_before>// basic file operations
#include <iostream>
#include <fstream>
#include <dai/alldai.h> // Include main libDAI header file
#include <CImg.h> // This example needs CImg to be installed
using namespace dai;
using namespace std;
Factor createFactorRecommendation( const Var &n1, const Var &n2, Real alpha) {
VarSet var_set = VarSet( n1, n2 );
Factor fac(var_set);
map<Var, size_t> state;
for (size_t i=0; i<n1.states(); ++i) {
state[n1] = i;
for (size_t j=0; j<n2.states(); ++j) {
state[n2] = j;
size_t index = calcLinearState(var_set, state);
if (i==j) {
fac.set(index, 0.5 + alpha);
} else {
fac.set(index, 0.5 - alpha);
}
}
}
return fac;
}
FactorGraph example2fg() {
vector<Var> vars;
vector<Factor> factors;
size_t N = 5;
size_t M = 5;
Real alpha = 0.1;
// Reserve memory for the variables
vars.reserve(N + M);
// Create a binary variable for each movie/person
for( size_t i = 0; i < N+M; i++ )
vars.push_back(Var(i, 2));
factors.push_back(createFactorRecommendation(vars[0], vars[N], alpha));
factors.push_back(createFactorRecommendation(vars[0], vars[N+1], alpha));
factors.push_back(createFactorRecommendation(vars[0], vars[N+2], alpha));
factors.push_back(createFactorRecommendation(vars[0], vars[N+3], alpha));
factors.push_back(createFactorRecommendation(vars[1], vars[N+1], alpha));
factors.push_back(createFactorRecommendation(vars[1], vars[N+2], alpha));
factors.push_back(createFactorRecommendation(vars[1], vars[N+3], alpha));
factors.push_back(createFactorRecommendation(vars[2], vars[N+2], alpha));
factors.push_back(createFactorRecommendation(vars[2], vars[N+3], alpha));
factors.push_back(createFactorRecommendation(vars[3], vars[N+1], alpha));
factors.push_back(createFactorRecommendation(vars[3], vars[N+2], alpha));
factors.push_back(createFactorRecommendation(vars[3], vars[N+3], alpha));
factors.push_back(createFactorRecommendation(vars[4], vars[N+1], alpha));
factors.push_back(createFactorRecommendation(vars[4], vars[N+2], alpha));
factors.push_back(createFactorRecommendation(vars[4], vars[N+3], alpha));
Factor fac1(vars[2]);
fac1.set(0, 0.9);
Factor fac2(vars[3]);
fac2.set(0, 0.9);
factors.push_back(fac1);
factors.push_back(fac2);
// Create the factor graph out of the variables and factors
cout << "Creating the factor graph..." << endl;
return FactorGraph( factors.begin(), factors.end(), vars.begin(), vars.end(), factors.size(), vars.size() );
}
double doInference( FactorGraph& fg, string algOpts, size_t maxIter, double tol, vector<double> &m) {
// Construct inference algorithm
cout << "Inference algorithm: " << algOpts << endl;
cout << "Constructing inference algorithm object..." << endl;
InfAlg* ia = newInfAlgFromString( algOpts, fg );
// Initialize inference algorithm
cout << "Initializing inference algorithm..." << endl;
ia->init();
// Initialize vector for storing the recommendations
m = vector<double>( fg.nrVars(), 0.0 );
// maxDiff stores the current convergence level
double maxDiff = 1.0;
// Iterate while maximum number of iterations has not been
// reached and requested convergence level has not been reached
cout << "Starting inference algorithm..." << endl;
for( size_t iter = 0; iter < maxIter && maxDiff > tol; iter++ ) {
// Set recommendations to beliefs
for( size_t i = 0; i < fg.nrVars(); i++ )
m[i] = ia->beliefV(i)[0];
// Perform the requested inference algorithm for only one step
ia->setMaxIter( iter + 1 );
maxDiff = ia->run();
// Output progress
cout << " Iterations = " << iter << ", maxDiff = " << maxDiff << endl;
}
cout << "Finished inference algorithm" << endl;
// Clean up inference algorithm
delete ia;
// Return reached convergence level
return maxDiff;
}
// vector of users, containing a vector of ratings. Each rating consists of a movie id (first) and the rating (second)
vector<vector<pair<int, int> > > extract_ratings(string file_name) {
ifstream fin;
fin.open(file_name.c_str(), ifstream::in);
vector<vector<pair<int, int> > > ratings;
int num_entries;
fin >> num_entries;
for (int i=0; i<num_entries; ++i) {
int user, movie, rating;
long long time;
fin >> user >> movie >> rating >> time;
user--;
//cout << user << " " << movie << " " << rating << endl;
while (user >= ratings.size()) {
ratings.push_back(vector<pair<int, int> >());
}
ratings[user].push_back(make_pair<int, int>(movie, rating));
}
return ratings;
}
FactorGraph data2fg(const vector<vector<pair<int, int> > >& votings, int user) {
// We will create a variable for every potential user/movie. We know the number of users, let us estimate the number of movies.
int num_users = votings.size();
int num_movies = 0;
for (size_t i=0; i<votings.size(); ++i) {
if (votings[i].size() > 0) {
num_movies = max(num_movies, votings[i][votings[i].size() - 1].first);
}
}
Real alpha = 0.0001;
int threshold = 4;
vector<Var> vars;
vector<Factor> factors;
// Reserve memory for the variables
vars.reserve(num_users + num_movies);
// Create a binary variable for each movie/person
for( size_t i = 0; i < num_users + num_movies; i++ )
vars.push_back(Var(i, 2));
for (size_t i=0; i<votings.size(); ++i) {
for (size_t j=0; j<votings[i].size(); ++j) {
if (votings[i][j].second >= threshold) {
factors.push_back(createFactorRecommendation(vars[i], vars[num_users + votings[i][j].first], alpha));
}
}
}
// calculate some metrics for the user.
int normalization_factor_p = 4;
double sum = 0;
double sq_sum = 0;
for (size_t i=0; i<votings[user].size(); ++i) {
sum += votings[user][i].second;
}
double mean = sum / votings[user].size();
for (size_t i=0; i<votings[user].size(); ++i) {
sq_sum += pow(votings[user][i].second - mean, 2);
}
double stdev = std::sqrt(sq_sum / votings[user].size());
for (size_t i=0; i<votings[user].size(); ++i) {
Factor fac(vars[num_users + votings[user][i].first]);
double like = max(0.1, min(0.9, 0.5 + (votings[user][i].second - mean)/(stdev * normalization_factor_p)));
cout << votings[user][i].second << " to " << like << endl;
fac.set(0, like);
factors.push_back(fac);
}
// Create the factor graph out of the variables and factors
cout << "Creating the factor graph..." << endl;
return FactorGraph(factors.begin(), factors.end(), vars.begin(), vars.end(), factors.size(), vars.size() );
}
/// Main program
int main(int argc,char **argv) {
cimg_usage( "This example shows how libDAI can be used for a simple recommendation task" );
const char *infname = cimg_option( "-method", "BP[updates=SEQMAX,maxiter=100,tol=1e-19,logdomain=0]", "Inference method in format name[key1=val1,...,keyn=valn]" );
const size_t maxiter = cimg_option( "-maxiter", 100, "Maximum number of iterations for inference method" );
const bool run_toy_example = cimg_option( "-run_toy_example", 0, "Should we only run a small example?" );
const double tol = cimg_option( "-tol", 1e-19, "Desired tolerance level for inference method" );
if (run_toy_example) {
FactorGraph fg = example2fg();
vector<double> m; // Stores the final recommendations
cout << "Solving the inference problem...please be patient!" << endl;
doInference(fg, infname, maxiter, tol, m);
cout << "Printing result: " << endl;
for (int i=0; i<m.size(); ++i) {
cout << i << " : " << m[i] << endl;
}
} else {
cout << "reading data now..." << endl;
vector<vector<pair<int, int> > > input_data = extract_ratings("u1.base");
int user = 5;
cout << "building factor graph..." << endl;
FactorGraph fg = data2fg(input_data, user);
vector<double> m; // Stores the final recommendations
cout << "Solving the inference problem...please be patient!" << endl;
doInference(fg, infname, maxiter, tol, m);
cout << "Printing result: " << endl;
vector<pair<double, int> > ratings;
for (size_t i = input_data.size(); i<m.size(); ++i) {
ratings.push_back(make_pair<double, int>(m[i], i - input_data.size() + 1));
}
sort(ratings.begin(), ratings.end());
for (size_t i=0; i<ratings.size(); ++i) {
cout << ratings[i].second << " : " << ratings[i].first << endl;
}
}
return 0;
}
<commit_msg>Precision Implemented<commit_after>// basic file operations
#include <iostream>
#include <fstream>
#include <algorithm> // std::max, min
#include <dai/alldai.h> // Include main libDAI header file
#include <CImg.h> // This example needs CImg to be installed
using namespace dai;
using namespace std;
Factor createFactorRecommendation( const Var &n1, const Var &n2, Real alpha) {
VarSet var_set = VarSet( n1, n2 );
Factor fac(var_set);
map<Var, size_t> state;
for (size_t i=0; i<n1.states(); ++i) {
state[n1] = i;
for (size_t j=0; j<n2.states(); ++j) {
state[n2] = j;
size_t index = calcLinearState(var_set, state);
if (i==j) {
fac.set(index, 0.5 + alpha);
} else {
fac.set(index, 0.5 - alpha);
}
}
}
return fac;
}
FactorGraph example2fg() {
vector<Var> vars;
vector<Factor> factors;
size_t N = 5;
size_t M = 5;
Real alpha = 0.1;
// Reserve memory for the variables
vars.reserve(N + M);
// Create a binary variable for each movie/person
for( size_t i = 0; i < N+M; i++ )
vars.push_back(Var(i, 2));
factors.push_back(createFactorRecommendation(vars[0], vars[N], alpha));
factors.push_back(createFactorRecommendation(vars[0], vars[N+1], alpha));
factors.push_back(createFactorRecommendation(vars[0], vars[N+2], alpha));
factors.push_back(createFactorRecommendation(vars[0], vars[N+3], alpha));
factors.push_back(createFactorRecommendation(vars[1], vars[N+1], alpha));
factors.push_back(createFactorRecommendation(vars[1], vars[N+2], alpha));
factors.push_back(createFactorRecommendation(vars[1], vars[N+3], alpha));
factors.push_back(createFactorRecommendation(vars[2], vars[N+2], alpha));
factors.push_back(createFactorRecommendation(vars[2], vars[N+3], alpha));
factors.push_back(createFactorRecommendation(vars[3], vars[N+1], alpha));
factors.push_back(createFactorRecommendation(vars[3], vars[N+2], alpha));
factors.push_back(createFactorRecommendation(vars[3], vars[N+3], alpha));
factors.push_back(createFactorRecommendation(vars[4], vars[N+1], alpha));
factors.push_back(createFactorRecommendation(vars[4], vars[N+2], alpha));
factors.push_back(createFactorRecommendation(vars[4], vars[N+3], alpha));
Factor fac1(vars[2]);
fac1.set(0, 0.9);
Factor fac2(vars[3]);
fac2.set(0, 0.9);
factors.push_back(fac1);
factors.push_back(fac2);
// Create the factor graph out of the variables and factors
cout << "Creating the factor graph..." << endl;
return FactorGraph( factors.begin(), factors.end(), vars.begin(), vars.end(), factors.size(), vars.size() );
}
double doInference( FactorGraph& fg, string algOpts, size_t maxIter, double tol, vector<double> &m) {
// Construct inference algorithm
cout << "Inference algorithm: " << algOpts << endl;
cout << "Constructing inference algorithm object..." << endl;
InfAlg* ia = newInfAlgFromString( algOpts, fg );
// Initialize inference algorithm
cout << "Initializing inference algorithm..." << endl;
ia->init();
// Initialize vector for storing the recommendations
m = vector<double>( fg.nrVars(), 0.0 );
// maxDiff stores the current convergence level
double maxDiff = 1.0;
// Iterate while maximum number of iterations has not been
// reached and requested convergence level has not been reached
cout << "Starting inference algorithm..." << endl;
for( size_t iter = 0; iter < maxIter && maxDiff > tol; iter++ ) {
// Set recommendations to beliefs
for( size_t i = 0; i < fg.nrVars(); i++ )
m[i] = ia->beliefV(i)[0];
// Perform the requested inference algorithm for only one step
ia->setMaxIter( iter + 1 );
maxDiff = ia->run();
// Output progress
cout << " Iterations = " << iter << ", maxDiff = " << maxDiff << endl;
}
cout << "Finished inference algorithm" << endl;
// Clean up inference algorithm
delete ia;
// Return reached convergence level
return maxDiff;
}
// vector of users, containing a vector of ratings. Each rating consists of a movie id (first) and the rating (second)
vector<vector<pair<int, int> > > extract_ratings(string file_name) {
ifstream fin;
fin.open(file_name.c_str(), ifstream::in);
vector<vector<pair<int, int> > > ratings;
int num_entries;
fin >> num_entries;
for (int i=0; i<num_entries; ++i) {
int user, movie, rating;
long long time;
fin >> user >> movie >> rating >> time;
user--;
//cout << user << " " << movie << " " << rating << endl;
while (user >= ratings.size()) {
ratings.push_back(vector<pair<int, int> >());
}
ratings[user].push_back(make_pair<int, int>(movie, rating));
}
return ratings;
}
FactorGraph data2fg(const vector<vector<pair<int, int> > >& votings, int user) {
// We will create a variable for every potential user/movie. We know the number of users, let us estimate the number of movies.
int num_users = votings.size();
int num_movies = 0;
for (size_t i=0; i<votings.size(); ++i) {
if (votings[i].size() > 0) {
num_movies = max(num_movies, votings[i][votings[i].size() - 1].first);
}
}
Real alpha = 0.0001;
int threshold = 4;
vector<Var> vars;
vector<Factor> factors;
// Reserve memory for the variables
vars.reserve(num_users + num_movies);
// Create a binary variable for each movie/person
for( size_t i = 0; i < num_users + num_movies; i++ )
vars.push_back(Var(i, 2));
for (size_t i=0; i<votings.size(); ++i) {
for (size_t j=0; j<votings[i].size(); ++j) {
if (votings[i][j].second >= threshold) {
factors.push_back(createFactorRecommendation(vars[i], vars[num_users + votings[i][j].first], alpha));
}
}
}
// calculate some metrics for the user.
int normalization_factor_p = 4;
double sum = 0;
double sq_sum = 0;
for (size_t i=0; i<votings[user].size(); ++i) {
sum += votings[user][i].second;
}
double mean = sum / votings[user].size();
for (size_t i=0; i<votings[user].size(); ++i) {
sq_sum += pow(votings[user][i].second - mean, 2);
}
double stdev = std::sqrt(sq_sum / votings[user].size());
for (size_t i=0; i<votings[user].size(); ++i) {
Factor fac(vars[num_users + votings[user][i].first]);
double like = max(0.1, min(0.9, 0.5 + (votings[user][i].second - mean)/(stdev * normalization_factor_p)));
//cout << votings[user][i].second << " to " << like << endl;
fac.set(0, like);
factors.push_back(fac);
}
// Create the factor graph out of the variables and factors
cout << "Creating the factor graph..." << endl;
return FactorGraph(factors.begin(), factors.end(), vars.begin(), vars.end(), factors.size(), vars.size() );
}
bool compareSecondRating(const pair<int, int>& i, const pair<int, int>& j) {
return i.second > j.second;
}
double getPrecision(vector<vector<pair<int, int> > >& test_data,
const vector<pair<double, int> >& ratings, int user, size_t N) {
// get the top predicted elements.
vector<int> predicted;
for (size_t i=0; i < std::min(N, ratings.size()); ++i) {
predicted.push_back(ratings[i].second);
}
// sort the test data according to the ratings and then take the top N elements.
sort(test_data[user].begin(), test_data[user].end(), compareSecondRating);
vector<int> wanted;
for (size_t i=0; i < std::min(N, test_data[user].size()); ++i) {
if (test_data[user][i].second >= 5) {
wanted.push_back(test_data[user][i].first);
}
}
// compute the intersection.
vector<int> v(N);
sort(predicted.begin(), predicted.end());
sort(wanted.begin(), wanted.end());
vector<int>::iterator it = set_intersection(predicted.begin(), predicted.end(), wanted.begin(), wanted.end(), v.begin());
v.resize(it-v.begin());
std::cout << "The intersection has " << (v.size()) << " elements:\n";
return v.size() / static_cast<double>(N);
}
/// Main program
int main(int argc,char **argv) {
cimg_usage( "This example shows how libDAI can be used for a simple recommendation task" );
const char *infname = cimg_option( "-method", "BP[updates=SEQMAX,maxiter=100,tol=1e-19,logdomain=0]", "Inference method in format name[key1=val1,...,keyn=valn]" );
const size_t maxiter = cimg_option( "-maxiter", 100, "Maximum number of iterations for inference method" );
const bool run_toy_example = cimg_option( "-run_toy_example", 0, "Should we only run a small example?" );
const double tol = cimg_option( "-tol", 1e-19, "Desired tolerance level for inference method" );
if (run_toy_example) {
FactorGraph fg = example2fg();
vector<double> m; // Stores the final recommendations
cout << "Solving the inference problem...please be patient!" << endl;
doInference(fg, infname, maxiter, tol, m);
cout << "Printing result: " << endl;
for (int i=0; i<m.size(); ++i) {
cout << i << " : " << m[i] << endl;
}
} else {
cout << "reading data now..." << endl;
vector<vector<pair<int, int> > > input_data = extract_ratings("u1.base");
vector<vector<pair<int, int> > > test_data = extract_ratings("u1.test");
int user = 5;
cout << "building factor graph..." << endl;
FactorGraph fg = data2fg(input_data, user);
vector<double> m; // Stores the final recommendations
cout << "Solving the inference problem...please be patient!" << endl;
doInference(fg, infname, maxiter, tol, m);
cout << "Printing result: " << endl;
vector<pair<double, int> > ratings;
for (size_t i = input_data.size(); i<m.size(); ++i) {
// push back the negative so we can use the standard sorting.
ratings.push_back(make_pair<double, int>(-m[i], i - input_data.size() + 1));
}
sort(ratings.begin(), ratings.end());
double precision10 = getPrecision(test_data, ratings, user, 10);
double precision20 = getPrecision(test_data, ratings, user, 20);
//double recall10 = getRecall(test_data, ratings, user, 10);
//double recall20 = getRecall(test_data, ratings, user, 20);
cout <<"Precision (N=10): " << precision10 << endl;
cout <<"Precision (N=20): " << precision20 << endl;
//cout <<"Recall (N=10): " << recall10 << endl;
//cout <<"Recall (N=10): " << recall20 << endl;
}
return 0;
}
<|endoftext|> |
<commit_before>#include <Accelerometer_GY_521_mock.h>
int Accelerometer_GY_521_mock::_init_accelerometer_sensor(){
size_t len = 0;
char *update_string = NULL;
logger.log(LOG_DEBUG, "Opening the file for Accelerometer values");
//Opening the file (
save_file = fopen(SAVE_ACCELEROMETER_FILENAME, "r");
//Registering the update frequency
if(save_file == NULL){
logger.log(LOG_ERROR, "Failing to open %s", SAVE_ACCELEROMETER_FILENAME);
return -1;
}
// If the first line is empty
if(getline(&update_string, &len, save_file) == -1){
logger.log(LOG_ERROR, "Gyroscope save file is empty");
return -1;
}
// We test if the save file has been save with the same update frequency
if(atoi(update_string) != update_frequency_ms){
logger.log(LOG_ERROR, "Error the file has been recorded at %sms, expecting %ims", update_string, update_frequency_ms);
return -1;
}
logger.log(LOG_DEBUG, "Accelerometer successfully mocked");
free(update_string);
return 0;
}
int Accelerometer_GY_521_mock::_teardown_accelerometer_sensor(){
return 0;
}
double Accelerometer_GY_521_mock::_get_x_acceleration(){
double value = 0.0;
load_from_file(&value, AXIS_X);
return value;
}
double Accelerometer_GY_521_mock::_get_y_acceleration(){
double value = 0.0;
load_from_file(&value, AXIS_Y);
return value;
}
double Accelerometer_GY_521_mock::_get_z_acceleration(){
double value = 0.0;
load_from_file(&value, AXIS_Z);
return value;
}
/**
* Allow to load the values directly from a file
* It can manage values refreshment when needed
* this function can't be common between gyroscope and accelerometer values because of static values
*/
int Accelerometer_GY_521_mock::load_from_file(double *buffer, axis axis_desired){
static bool x_new = true;
static bool y_new = true;
static bool z_new = true;
static double x_value = 0.0;
static double y_value = 0.0;
static double z_value = 0.0;
double values_array[3];
char *values = NULL;
size_t len;
// If the value has already been fetched, we must triger a new line reading
if( (axis_desired == AXIS_X && !x_new) || (axis_desired == AXIS_Y && !y_new) || (axis_desired == AXIS_Z && !z_new)){
if(getline(&values, &len, save_file) == -1){
free(values);
logger.log(LOG_ERROR, "File %s empty", SAVE_ACCELEROMETER_FILENAME);
return -1;
}
// We then get extract decimal values separated by space from the string
int j=0;
int previous_index = 0;
for(int i=0; values[i] != '\0'; i++){
// if we have found a separator;
if(values[i] == ' '){
values[i] = '\0';
values_array[j] = atof(&values[previous_index]);
j++;
//The begining of the next value in the string
previous_index = i+1;
}
}
values_array[j] = atof(&values[previous_index]);
x_value = values_array[0];
y_value = values_array[1];
z_value = values_array[2];
}
// We return the value demanded and turn the associated new flag to false
switch (axis_desired){
case AXIS_X:
*buffer = x_value;
x_new = false;
break;
case AXIS_Y:
*buffer = y_value;
y_new = false;
break;
case AXIS_Z:
z_new = false;
*buffer = z_value;
break;
}
free(values);
return 0;
}
<commit_msg>Adding proper closing for accelerometer mock<commit_after>#include <Accelerometer_GY_521_mock.h>
int Accelerometer_GY_521_mock::_init_accelerometer_sensor(){
size_t len = 0;
char *update_string = NULL;
logger.log(LOG_DEBUG, "Opening the file for Accelerometer values");
//Opening the file (
save_file = fopen(SAVE_ACCELEROMETER_FILENAME, "r");
//Registering the update frequency
if(save_file == NULL){
logger.log(LOG_ERROR, "Failing to open %s", SAVE_ACCELEROMETER_FILENAME);
return -1;
}
// If the first line is empty
if(getline(&update_string, &len, save_file) == -1){
logger.log(LOG_ERROR, "Gyroscope save file is empty");
return -1;
}
// We test if the save file has been save with the same update frequency
if(atoi(update_string) != update_frequency_ms){
logger.log(LOG_ERROR, "Error the file has been recorded at %sms, expecting %ims", update_string, update_frequency_ms);
return -1;
}
logger.log(LOG_DEBUG, "Accelerometer successfully mocked");
free(update_string);
return 0;
}
int Accelerometer_GY_521_mock::_teardown_accelerometer_sensor(){
int error_code = 0;
if(fclose(save_file))
error_code = -1;
return error_code;
}
double Accelerometer_GY_521_mock::_get_x_acceleration(){
double value = 0.0;
load_from_file(&value, AXIS_X);
return value;
}
double Accelerometer_GY_521_mock::_get_y_acceleration(){
double value = 0.0;
load_from_file(&value, AXIS_Y);
return value;
}
double Accelerometer_GY_521_mock::_get_z_acceleration(){
double value = 0.0;
load_from_file(&value, AXIS_Z);
return value;
}
/**
* Allow to load the values directly from a file
* It can manage values refreshment when needed
* this function can't be common between gyroscope and accelerometer values because of static values
*/
int Accelerometer_GY_521_mock::load_from_file(double *buffer, axis axis_desired){
static bool x_new = true;
static bool y_new = true;
static bool z_new = true;
static double x_value = 0.0;
static double y_value = 0.0;
static double z_value = 0.0;
double values_array[3];
char *values = NULL;
size_t len;
// If the value has already been fetched, we must triger a new line reading
if( (axis_desired == AXIS_X && !x_new) || (axis_desired == AXIS_Y && !y_new) || (axis_desired == AXIS_Z && !z_new)){
if(getline(&values, &len, save_file) == -1){
free(values);
logger.log(LOG_ERROR, "File %s empty", SAVE_ACCELEROMETER_FILENAME);
return -1;
}
// We then get extract decimal values separated by space from the string
int j=0;
int previous_index = 0;
for(int i=0; values[i] != '\0'; i++){
// if we have found a separator;
if(values[i] == ' '){
values[i] = '\0';
values_array[j] = atof(&values[previous_index]);
j++;
//The begining of the next value in the string
previous_index = i+1;
}
}
values_array[j] = atof(&values[previous_index]);
x_value = values_array[0];
y_value = values_array[1];
z_value = values_array[2];
}
// We return the value demanded and turn the associated new flag to false
switch (axis_desired){
case AXIS_X:
*buffer = x_value;
x_new = false;
break;
case AXIS_Y:
*buffer = y_value;
y_new = false;
break;
case AXIS_Z:
z_new = false;
*buffer = z_value;
break;
}
free(values);
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland
* All rights reserved.
*
* This library/application is free software; you can redistribute and/or modify it under the terms of
* the license that is included with this library/application in the file license.txt.
*/
//--- test modules used --------------------------------------------------------
#include "TestSuite.h"
//--- interface include --------------------------------------------------------
#include "StatisticTestCase.h"
//--- standard modules used ----------------------------------------------------
#include "DiffTimer.h"
#include "System.h"
#include "AnyIterators.h"
//--- c-library modules used ---------------------------------------------------
//---- StatisticTestCase ----------------------------------------------------------------
StatisticTestCase::StatisticTestCase(TString tstrName) : TestCase(tstrName)
{
StartTrace(StatisticTestCase.Ctor);
}
StatisticTestCase::~StatisticTestCase()
{
StartTrace(StatisticTestCase.Dtor);
}
void StatisticTestCase::LoadData()
{
StartTrace(StatisticTestCase.LoadData);
if ( !t_assertm(System::LoadConfigFile(fStatistics, getClassName(), "any", fFilename), "could not load statistics file!") ) {
fFilename = getClassName();
fFilename << ".any";
}
fDatetime = GenTimeStamp();
System::HostName(fHostName);
fHostName << '_' << WD_BUILDFLAGS;
TraceAny(fStatistics, "filename of statistics file is [" << fFilename << "], timestamp [" << fDatetime << "]");
}
void StatisticTestCase::StoreData()
{
StartTrace(StatisticTestCase.StoreData);
iostream *pStream = System::OpenOStream(fFilename, "");
if ( t_assert(pStream != NULL) ) {
fStatistics.PrintOn(*pStream, true);
}
delete pStream;
}
void StatisticTestCase::setUp()
{
StartTrace(StatisticTestCase.setUp);
LoadData();
}
void StatisticTestCase::tearDown()
{
StartTrace(StatisticTestCase.tearDown);
StoreData();
}
String StatisticTestCase::GenTimeStamp()
{
StartTrace(StatisticTestCase.GenTimeStamp);
const int dateSz = 40;
time_t now = time(0);
struct tm res, *tt;
tt = System::LocalTime(&now, &res);
char date[dateSz];
strftime(date, dateSz, "%Y%m%d%H%M%S", tt);
return date;
}
void StatisticTestCase::AddStatisticOutput(String strTestName, long lMilliTime)
{
StartTrace(StatisticTestCase.AddStatisticOutput);
fStatistics[fHostName][fDatetime][strTestName] = lMilliTime;
}
void StatisticTestCase::ExportCsvStatistics(long lModulus)
{
StartTrace(StatisticTestCase.ExportCsvStatistics);
Anything anyCsv;
long lDestDateIdx = 0L;
TraceAny(fStatistics, "Collected Statistics");
ROAnything roaStatistics(fStatistics), roaHostEntry;
AnyExtensions::Iterator<ROAnything> aHostIterator(roaStatistics);
while ( aHostIterator.Next(roaHostEntry) ) {
const char *pHostName = roaStatistics.SlotName(aHostIterator.Index());
TraceAny(roaHostEntry, "current entry for host [" << pHostName << "]");
ROAnything roaDateEntry;
AnyExtensions::Iterator<ROAnything> aDateIterator(roaHostEntry);
while ( aDateIterator.Next(roaDateEntry) ) {
if ( aDateIterator.Index() % lModulus == 0 ) {
lDestDateIdx++;
}
const char *pDT = roaHostEntry.SlotName(aDateIterator.Index());
anyCsv["TestName"][lDestDateIdx] = pDT;
anyCsv["HostName"][lDestDateIdx] = pHostName;
TraceAny(roaDateEntry, "date entry per [" << pDT << "]");
ROAnything roaCaseEntry;
AnyExtensions::Iterator<ROAnything> aCaseIterator(roaDateEntry);
while ( aCaseIterator.Next(roaCaseEntry) ) {
const char *pCaseName = roaDateEntry.SlotName(aCaseIterator.Index());
anyCsv[pCaseName][lDestDateIdx] = roaCaseEntry.AsCharPtr();
}
}
}
TraceAny(anyCsv, "collected");
iostream *pStream = System::OpenOStream(getClassName(), "csv");
if ( t_assert(pStream != NULL) ) {
ROAnything roaRowEntry, roaCvs(anyCsv);
AnyExtensions::Iterator<ROAnything> aRowIterator(roaCvs);
while ( aRowIterator.Next(roaRowEntry) ) {
(*pStream) << roaCvs.SlotName(aRowIterator.Index()) << ',';
ROAnything roaCol;
AnyExtensions::Iterator<ROAnything> aColIterator(roaRowEntry);
while ( aColIterator.Next(roaCol) ) {
(*pStream) << roaCol.AsString() << ',';
}
(*pStream) << "\r\n";
}
}
delete pStream;
}
<commit_msg>added compiler infoo to existing host and flags<commit_after>/*
* Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland
* All rights reserved.
*
* This library/application is free software; you can redistribute and/or modify it under the terms of
* the license that is included with this library/application in the file license.txt.
*/
//--- test modules used --------------------------------------------------------
#include "TestSuite.h"
//--- interface include --------------------------------------------------------
#include "StatisticTestCase.h"
//--- standard modules used ----------------------------------------------------
#include "DiffTimer.h"
#include "System.h"
#include "AnyIterators.h"
//--- c-library modules used ---------------------------------------------------
//---- StatisticTestCase ----------------------------------------------------------------
StatisticTestCase::StatisticTestCase(TString tstrName) : TestCase(tstrName)
{
StartTrace(StatisticTestCase.Ctor);
}
StatisticTestCase::~StatisticTestCase()
{
StartTrace(StatisticTestCase.Dtor);
}
void StatisticTestCase::LoadData()
{
StartTrace(StatisticTestCase.LoadData);
if ( !t_assertm(System::LoadConfigFile(fStatistics, getClassName(), "any", fFilename), "could not load statistics file!") ) {
fFilename = getClassName();
fFilename << ".any";
}
fDatetime = GenTimeStamp();
System::HostName(fHostName);
fHostName << '_' << WD_BUILDFLAGS << '_' << WD_COMPILER;
TraceAny(fStatistics, "filename of statistics file is [" << fFilename << "], timestamp [" << fDatetime << "]");
}
void StatisticTestCase::StoreData()
{
StartTrace(StatisticTestCase.StoreData);
iostream *pStream = System::OpenOStream(fFilename, "");
if ( t_assert(pStream != NULL) ) {
fStatistics.PrintOn(*pStream, true);
}
delete pStream;
}
void StatisticTestCase::setUp()
{
StartTrace(StatisticTestCase.setUp);
LoadData();
}
void StatisticTestCase::tearDown()
{
StartTrace(StatisticTestCase.tearDown);
StoreData();
}
String StatisticTestCase::GenTimeStamp()
{
StartTrace(StatisticTestCase.GenTimeStamp);
const int dateSz = 40;
time_t now = time(0);
struct tm res, *tt;
tt = System::LocalTime(&now, &res);
char date[dateSz];
strftime(date, dateSz, "%Y%m%d%H%M%S", tt);
return date;
}
void StatisticTestCase::AddStatisticOutput(String strTestName, long lMilliTime)
{
StartTrace(StatisticTestCase.AddStatisticOutput);
fStatistics[fHostName][fDatetime][strTestName] = lMilliTime;
}
void StatisticTestCase::ExportCsvStatistics(long lModulus)
{
StartTrace(StatisticTestCase.ExportCsvStatistics);
Anything anyCsv;
long lDestDateIdx = 0L;
TraceAny(fStatistics, "Collected Statistics");
ROAnything roaStatistics(fStatistics), roaHostEntry;
AnyExtensions::Iterator<ROAnything> aHostIterator(roaStatistics);
while ( aHostIterator.Next(roaHostEntry) ) {
const char *pHostName = roaStatistics.SlotName(aHostIterator.Index());
TraceAny(roaHostEntry, "current entry for host [" << pHostName << "]");
ROAnything roaDateEntry;
AnyExtensions::Iterator<ROAnything> aDateIterator(roaHostEntry);
while ( aDateIterator.Next(roaDateEntry) ) {
if ( aDateIterator.Index() % lModulus == 0 ) {
lDestDateIdx++;
}
const char *pDT = roaHostEntry.SlotName(aDateIterator.Index());
anyCsv["TestName"][lDestDateIdx] = pDT;
anyCsv["HostName"][lDestDateIdx] = pHostName;
TraceAny(roaDateEntry, "date entry per [" << pDT << "]");
ROAnything roaCaseEntry;
AnyExtensions::Iterator<ROAnything> aCaseIterator(roaDateEntry);
while ( aCaseIterator.Next(roaCaseEntry) ) {
const char *pCaseName = roaDateEntry.SlotName(aCaseIterator.Index());
anyCsv[pCaseName][lDestDateIdx] = roaCaseEntry.AsCharPtr();
}
}
}
TraceAny(anyCsv, "collected");
iostream *pStream = System::OpenOStream(getClassName(), "csv");
if ( t_assert(pStream != NULL) ) {
ROAnything roaRowEntry, roaCvs(anyCsv);
AnyExtensions::Iterator<ROAnything> aRowIterator(roaCvs);
while ( aRowIterator.Next(roaRowEntry) ) {
(*pStream) << roaCvs.SlotName(aRowIterator.Index()) << ',';
ROAnything roaCol;
AnyExtensions::Iterator<ROAnything> aColIterator(roaRowEntry);
while ( aColIterator.Next(roaCol) ) {
(*pStream) << roaCol.AsString() << ',';
}
(*pStream) << "\r\n";
}
}
delete pStream;
}
<|endoftext|> |
<commit_before>#include <ir/index_manager/index/IndexReader.h>
#include <ir/index_manager/index/TermReader.h>
#include <ir/index_manager/index/Indexer.h>
#include <ir/index_manager/index/MultiIndexBarrelReader.h>
#include <util/ThreadModel.h>
using namespace izenelib::ir::indexmanager;
IndexReader::IndexReader(Indexer* pIndex)
:pIndexer_(pIndex)
,pBarrelsInfo_(NULL)
,pBarrelReader_(NULL)
,pForwardIndexReader_(NULL)
,pDocFilter_(NULL)
,pDocLengthReader_(NULL)
{
pBarrelsInfo_ = pIndexer_->getBarrelsInfo();
Directory* pDirectory = pIndexer_->getDirectory();
if(pDirectory->fileExists(DELETED_DOCS))
{
pDocFilter_ = new BitVector;
pDocFilter_->read(pDirectory, DELETED_DOCS);
}
///todo since only one collection is used within indexmanager, so we only get collectionmeta for one collection to build
///up the DocLengthReader
if(pIndexer_->getIndexManagerConfig()->indexStrategy_.indexDocLength_)
pDocLengthReader_ = new DocLengthReader(pIndexer_->getCollectionsMeta().begin()->second.getDocumentSchema(),
pIndexer_->getDirectory());
}
IndexReader::~IndexReader(void)
{
if (pBarrelReader_)
{
delete pBarrelReader_;
pBarrelReader_ = NULL;
}
if(pForwardIndexReader_)
delete pForwardIndexReader_;
if(pDocFilter_)
{
if(pIndexer_->getDirectory()->fileExists(DELETED_DOCS))
pIndexer_->getDirectory()->deleteFile(DELETED_DOCS);
pDocFilter_->write(pIndexer_->getDirectory(), DELETED_DOCS);
delete pDocFilter_;
}
if(pDocLengthReader_) {delete pDocLengthReader_; pDocLengthReader_ = NULL;}
}
void IndexReader::delDocFilter()
{
if(pDocFilter_)
{
if(pIndexer_->getDirectory()->fileExists(DELETED_DOCS))
pIndexer_->getDirectory()->deleteFile(DELETED_DOCS);
delete pDocFilter_;
pDocFilter_ = NULL;
}
}
docid_t IndexReader::maxDoc()
{
return pBarrelsInfo_->maxDocId();
}
size_t IndexReader::docLength(docid_t docId, fieldid_t fid)
{
if (pBarrelReader_ == NULL)
createBarrelReader();
return pDocLengthReader_->docLength(docId, fid);
}
double IndexReader::getAveragePropertyLength(fieldid_t fid)
{
if (pBarrelReader_ == NULL)
createBarrelReader();
boost::mutex::scoped_lock indexReaderLock(this->mutex_);
return pDocLengthReader_->averagePropertyLength(fid);
}
void IndexReader::createBarrelReader()
{
boost::mutex::scoped_lock lock(this->mutex_);
if (pBarrelReader_)
return;
// delete pBarrelReader_;
int32_t bc = pBarrelsInfo_->getBarrelCount();
BarrelInfo* pLastBarrel = pBarrelsInfo_->getLastBarrel();
if ( (bc > 0) && pLastBarrel)
{
if (pLastBarrel->getDocCount() <= 0)///skip empty barrel
bc--;
pLastBarrel = (*pBarrelsInfo_)[bc - 1];
}
if (bc == 1)
{
if (pLastBarrel && pLastBarrel->getWriter())
pBarrelReader_ = pLastBarrel->getWriter()->inMemoryReader();
else
pBarrelReader_ = new SingleIndexBarrelReader(pIndexer_,pLastBarrel);
}
else if (bc > 1)
{
pBarrelReader_ = new MultiIndexBarrelReader(pIndexer_,pBarrelsInfo_);
}
else
return;
if(pDocLengthReader_)
pDocLengthReader_->load(pBarrelsInfo_->maxDocId());
//pIndexer_->setDirty(false);///clear dirty_ flag
}
TermReader* IndexReader::getTermReader(collectionid_t colID)
{
//boost::try_mutex::scoped_try_lock lock(pIndexer_->mutex_);
//if(!lock.owns_lock())
//return NULL;
izenelib::util::ScopedReadLock<izenelib::util::ReadWriteLock> lock(pIndexer_->mutex_);
if (pBarrelReader_ == NULL)
createBarrelReader();
if (pBarrelReader_ == NULL)
return NULL;
boost::mutex::scoped_lock indexReaderLock(this->mutex_);
TermReader* pTermReader = pBarrelReader_->termReader(colID);
if (pTermReader)
return pTermReader->clone();
else
return NULL;
}
void IndexReader::reopen()
{
//if(pBarrelReader_)
//delete pBarrelReader_;
//pBarrelReader_ = NULL;
/////pBarrelReader_->reopen();
{
boost::mutex::scoped_lock lock(this->mutex_);
if(pBarrelReader_)
{
delete pBarrelReader_;
pBarrelReader_ = NULL;
}
}
createBarrelReader();
}
ForwardIndexReader* IndexReader::getForwardIndexReader()
{
if(!pForwardIndexReader_)
pForwardIndexReader_ = new ForwardIndexReader(pIndexer_->getDirectory());
return pForwardIndexReader_->clone();
}
count_t IndexReader::numDocs()
{
return pBarrelsInfo_->getDocCount();
}
BarrelInfo* IndexReader::findDocumentInBarrels(collectionid_t colID, docid_t docID)
{
for (int i = pBarrelsInfo_->getBarrelCount() - 1; i >= 0; i--)
{
BarrelInfo* pBarrelInfo = (*pBarrelsInfo_)[i];
if ((pBarrelInfo->baseDocIDMap.find(colID) != pBarrelInfo->baseDocIDMap.end())&&
(pBarrelInfo->baseDocIDMap[colID] <= docID))
return pBarrelInfo;
}
return NULL;
}
void IndexReader::deleteDocumentPhysically(IndexerDocument* pDoc)
{
if (pBarrelReader_ == NULL)
createBarrelReader();
boost::mutex::scoped_lock lock(this->mutex_);
pBarrelReader_->deleteDocumentPhysically(pDoc);
DocId uniqueID;
pDoc->getDocId(uniqueID);
BarrelInfo* pBarrelInfo = findDocumentInBarrels(uniqueID.colId, uniqueID.docId);
pBarrelInfo->deleteDocument(uniqueID.docId);
map<IndexerPropertyConfig, IndexerDocumentPropertyType> propertyValueList;
pDoc->getPropertyList(propertyValueList);
for (map<IndexerPropertyConfig, IndexerDocumentPropertyType>::iterator iter = propertyValueList.begin(); iter != propertyValueList.end(); ++iter)
{
if(!iter->first.isIndex())
continue;
if (!iter->first.isForward())
{
pIndexer_->getBTreeIndexer()->remove(uniqueID.colId, iter->first.getPropertyId(), boost::get<PropertyType>(iter->second), uniqueID.docId);
}
}
pIndexer_->setDirty(true);//flush barrelsinfo when Indexer quit
}
void IndexReader::delDocument(collectionid_t colID,docid_t docId)
{
BarrelInfo* pBarrelInfo = findDocumentInBarrels(colID, docId);
if(NULL == pBarrelInfo)
return;
pBarrelInfo->deleteDocument(docId);
if(!pDocFilter_)
{
pDocFilter_ = new BitVector(pBarrelsInfo_->getDocCount() + 1);
}
pDocFilter_->set(docId);
cout<<docId<<endl;
}
freq_t IndexReader::docFreq(collectionid_t colID, Term* term)
{
//boost::try_mutex::scoped_try_lock lock(pIndexer_->mutex_);
//if(!lock.owns_lock())
//return 0;
izenelib::util::ScopedReadLock<izenelib::util::ReadWriteLock> lock(pIndexer_->mutex_);
if (pBarrelReader_ == NULL)
createBarrelReader();
if (pBarrelReader_ == NULL)
return 0;
boost::mutex::scoped_lock indexReaderLock(this->mutex_);
TermReader* pTermReader = pBarrelReader_->termReader(colID);
if (pTermReader)
{
return pTermReader->docFreq(term);
}
return 0;
}
TermInfo* IndexReader::termInfo(collectionid_t colID,Term* term)
{
//boost::try_mutex::scoped_try_lock lock(pIndexer_->mutex_);
//if(!lock.owns_lock())
//return NULL;
izenelib::util::ScopedReadLock<izenelib::util::ReadWriteLock> lock(pIndexer_->mutex_);
if (pBarrelReader_ == NULL)
createBarrelReader();
if (pBarrelReader_ == NULL)
return NULL;
boost::mutex::scoped_lock indexReaderLock(this->mutex_);
TermReader* pTermReader = pBarrelReader_->termReader(colID);
if (pTermReader)
{
return pTermReader->termInfo(term);
}
return 0;
}
size_t IndexReader::getDistinctNumTerms(collectionid_t colID, const std::string& property)
{
//collection has been removed, need to rebuild the barrel reader
if (pBarrelReader_ == NULL)
createBarrelReader();
if (pBarrelReader_ == NULL)
return 0;
boost::mutex::scoped_lock indexReaderLock(this->mutex_);
return pBarrelReader_->getDistinctNumTerms(colID, property);
}
<commit_msg>clear<commit_after>#include <ir/index_manager/index/IndexReader.h>
#include <ir/index_manager/index/TermReader.h>
#include <ir/index_manager/index/Indexer.h>
#include <ir/index_manager/index/MultiIndexBarrelReader.h>
#include <util/ThreadModel.h>
using namespace izenelib::ir::indexmanager;
IndexReader::IndexReader(Indexer* pIndex)
:pIndexer_(pIndex)
,pBarrelsInfo_(NULL)
,pBarrelReader_(NULL)
,pForwardIndexReader_(NULL)
,pDocFilter_(NULL)
,pDocLengthReader_(NULL)
{
pBarrelsInfo_ = pIndexer_->getBarrelsInfo();
Directory* pDirectory = pIndexer_->getDirectory();
if(pDirectory->fileExists(DELETED_DOCS))
{
pDocFilter_ = new BitVector;
pDocFilter_->read(pDirectory, DELETED_DOCS);
}
///todo since only one collection is used within indexmanager, so we only get collectionmeta for one collection to build
///up the DocLengthReader
if(pIndexer_->getIndexManagerConfig()->indexStrategy_.indexDocLength_)
pDocLengthReader_ = new DocLengthReader(pIndexer_->getCollectionsMeta().begin()->second.getDocumentSchema(),
pIndexer_->getDirectory());
}
IndexReader::~IndexReader(void)
{
if (pBarrelReader_)
{
delete pBarrelReader_;
pBarrelReader_ = NULL;
}
if(pForwardIndexReader_)
delete pForwardIndexReader_;
if(pDocFilter_)
{
if(pIndexer_->getDirectory()->fileExists(DELETED_DOCS))
pIndexer_->getDirectory()->deleteFile(DELETED_DOCS);
pDocFilter_->write(pIndexer_->getDirectory(), DELETED_DOCS);
delete pDocFilter_;
}
if(pDocLengthReader_) {delete pDocLengthReader_; pDocLengthReader_ = NULL;}
}
void IndexReader::delDocFilter()
{
if(pDocFilter_)
{
if(pIndexer_->getDirectory()->fileExists(DELETED_DOCS))
pIndexer_->getDirectory()->deleteFile(DELETED_DOCS);
delete pDocFilter_;
pDocFilter_ = NULL;
}
}
docid_t IndexReader::maxDoc()
{
return pBarrelsInfo_->maxDocId();
}
size_t IndexReader::docLength(docid_t docId, fieldid_t fid)
{
if (pBarrelReader_ == NULL)
createBarrelReader();
return pDocLengthReader_->docLength(docId, fid);
}
double IndexReader::getAveragePropertyLength(fieldid_t fid)
{
if (pBarrelReader_ == NULL)
createBarrelReader();
boost::mutex::scoped_lock indexReaderLock(this->mutex_);
return pDocLengthReader_->averagePropertyLength(fid);
}
void IndexReader::createBarrelReader()
{
boost::mutex::scoped_lock lock(this->mutex_);
if (pBarrelReader_)
return;
// delete pBarrelReader_;
int32_t bc = pBarrelsInfo_->getBarrelCount();
BarrelInfo* pLastBarrel = pBarrelsInfo_->getLastBarrel();
if ( (bc > 0) && pLastBarrel)
{
if (pLastBarrel->getDocCount() <= 0)///skip empty barrel
bc--;
pLastBarrel = (*pBarrelsInfo_)[bc - 1];
}
if (bc == 1)
{
if (pLastBarrel && pLastBarrel->getWriter())
pBarrelReader_ = pLastBarrel->getWriter()->inMemoryReader();
else
pBarrelReader_ = new SingleIndexBarrelReader(pIndexer_,pLastBarrel);
}
else if (bc > 1)
{
pBarrelReader_ = new MultiIndexBarrelReader(pIndexer_,pBarrelsInfo_);
}
else
return;
if(pDocLengthReader_)
pDocLengthReader_->load(pBarrelsInfo_->maxDocId());
//pIndexer_->setDirty(false);///clear dirty_ flag
}
TermReader* IndexReader::getTermReader(collectionid_t colID)
{
//boost::try_mutex::scoped_try_lock lock(pIndexer_->mutex_);
//if(!lock.owns_lock())
//return NULL;
izenelib::util::ScopedReadLock<izenelib::util::ReadWriteLock> lock(pIndexer_->mutex_);
if (pBarrelReader_ == NULL)
createBarrelReader();
if (pBarrelReader_ == NULL)
return NULL;
boost::mutex::scoped_lock indexReaderLock(this->mutex_);
TermReader* pTermReader = pBarrelReader_->termReader(colID);
if (pTermReader)
return pTermReader->clone();
else
return NULL;
}
void IndexReader::reopen()
{
//if(pBarrelReader_)
//delete pBarrelReader_;
//pBarrelReader_ = NULL;
/////pBarrelReader_->reopen();
{
boost::mutex::scoped_lock lock(this->mutex_);
if(pBarrelReader_)
{
delete pBarrelReader_;
pBarrelReader_ = NULL;
}
}
createBarrelReader();
}
ForwardIndexReader* IndexReader::getForwardIndexReader()
{
if(!pForwardIndexReader_)
pForwardIndexReader_ = new ForwardIndexReader(pIndexer_->getDirectory());
return pForwardIndexReader_->clone();
}
count_t IndexReader::numDocs()
{
return pBarrelsInfo_->getDocCount();
}
BarrelInfo* IndexReader::findDocumentInBarrels(collectionid_t colID, docid_t docID)
{
for (int i = pBarrelsInfo_->getBarrelCount() - 1; i >= 0; i--)
{
BarrelInfo* pBarrelInfo = (*pBarrelsInfo_)[i];
if ((pBarrelInfo->baseDocIDMap.find(colID) != pBarrelInfo->baseDocIDMap.end())&&
(pBarrelInfo->baseDocIDMap[colID] <= docID))
return pBarrelInfo;
}
return NULL;
}
void IndexReader::deleteDocumentPhysically(IndexerDocument* pDoc)
{
if (pBarrelReader_ == NULL)
createBarrelReader();
boost::mutex::scoped_lock lock(this->mutex_);
pBarrelReader_->deleteDocumentPhysically(pDoc);
DocId uniqueID;
pDoc->getDocId(uniqueID);
BarrelInfo* pBarrelInfo = findDocumentInBarrels(uniqueID.colId, uniqueID.docId);
pBarrelInfo->deleteDocument(uniqueID.docId);
map<IndexerPropertyConfig, IndexerDocumentPropertyType> propertyValueList;
pDoc->getPropertyList(propertyValueList);
for (map<IndexerPropertyConfig, IndexerDocumentPropertyType>::iterator iter = propertyValueList.begin(); iter != propertyValueList.end(); ++iter)
{
if(!iter->first.isIndex())
continue;
if (!iter->first.isForward())
{
pIndexer_->getBTreeIndexer()->remove(uniqueID.colId, iter->first.getPropertyId(), boost::get<PropertyType>(iter->second), uniqueID.docId);
}
}
pIndexer_->setDirty(true);//flush barrelsinfo when Indexer quit
}
void IndexReader::delDocument(collectionid_t colID,docid_t docId)
{
BarrelInfo* pBarrelInfo = findDocumentInBarrels(colID, docId);
if(NULL == pBarrelInfo)
return;
pBarrelInfo->deleteDocument(docId);
if(!pDocFilter_)
{
pDocFilter_ = new BitVector(pBarrelsInfo_->getDocCount() + 1);
}
pDocFilter_->set(docId);
}
freq_t IndexReader::docFreq(collectionid_t colID, Term* term)
{
//boost::try_mutex::scoped_try_lock lock(pIndexer_->mutex_);
//if(!lock.owns_lock())
//return 0;
izenelib::util::ScopedReadLock<izenelib::util::ReadWriteLock> lock(pIndexer_->mutex_);
if (pBarrelReader_ == NULL)
createBarrelReader();
if (pBarrelReader_ == NULL)
return 0;
boost::mutex::scoped_lock indexReaderLock(this->mutex_);
TermReader* pTermReader = pBarrelReader_->termReader(colID);
if (pTermReader)
{
return pTermReader->docFreq(term);
}
return 0;
}
TermInfo* IndexReader::termInfo(collectionid_t colID,Term* term)
{
//boost::try_mutex::scoped_try_lock lock(pIndexer_->mutex_);
//if(!lock.owns_lock())
//return NULL;
izenelib::util::ScopedReadLock<izenelib::util::ReadWriteLock> lock(pIndexer_->mutex_);
if (pBarrelReader_ == NULL)
createBarrelReader();
if (pBarrelReader_ == NULL)
return NULL;
boost::mutex::scoped_lock indexReaderLock(this->mutex_);
TermReader* pTermReader = pBarrelReader_->termReader(colID);
if (pTermReader)
{
return pTermReader->termInfo(term);
}
return 0;
}
size_t IndexReader::getDistinctNumTerms(collectionid_t colID, const std::string& property)
{
//collection has been removed, need to rebuild the barrel reader
if (pBarrelReader_ == NULL)
createBarrelReader();
if (pBarrelReader_ == NULL)
return 0;
boost::mutex::scoped_lock indexReaderLock(this->mutex_);
return pBarrelReader_->getDistinctNumTerms(colID, property);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: sequenceashashmap.hxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: ihi $ $Date: 2007-11-19 16:32:28 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _COMPHELPER_SEQUENCEASHASHMAP_HXX_
#define _COMPHELPER_SEQUENCEASHASHMAP_HXX_
//_______________________________________________
// includes
#ifndef INCLUDED_HASH_MAP
#include <hash_map>
#define INCLUDED_HASH_MAP
#endif
#ifndef INCLUDED_ALGORITHM
#include <algorithm>
#define INCLUDED_ALGORITHM
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_NAMEDVALUE_HPP_
#include <com/sun/star/beans/NamedValue.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_IllegalTypeException_HPP_
#include <com/sun/star/beans/IllegalTypeException.hpp>
#endif
#ifndef INCLUDED_COMPHELPERDLLAPI_H
#include "comphelper/comphelperdllapi.h"
#endif
// see method dbg_dumpToFile() below!
#if OSL_DEBUG_LEVEL > 1
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#include <stdio.h>
#endif
//_______________________________________________
// namespace
namespace comphelper{
//_______________________________________________
// definitions
/** @short Implements a stl hash map on top of some
specialized sequence from type PropertyValue
or NamedValue.
@descr That provides the possibility to modify
such name sequences very easy ...
*/
struct SequenceAsHashMapBase : public ::std::hash_map<
::rtl::OUString ,
::com::sun::star::uno::Any ,
::rtl::OUStringHash ,
::std::equal_to< ::rtl::OUString > >
{
};
class COMPHELPER_DLLPUBLIC SequenceAsHashMap : public SequenceAsHashMapBase
{
//-------------------------------------------
public:
//---------------------------------------
/** @short creates an empty hash map.
*/
SequenceAsHashMap();
//---------------------------------------
/** @see operator<<(const ::com::sun::star::uno::Any&)
*/
SequenceAsHashMap(const ::com::sun::star::uno::Any& aSource);
//---------------------------------------
/** @see operator<<(const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >&)
*/
SequenceAsHashMap(const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& lSource);
//---------------------------------------
/** @see operator<<(const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >&)
*/
SequenceAsHashMap(const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lSource);
//---------------------------------------
/** @see operator<<(const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >&)
*/
SequenceAsHashMap(const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& lSource);
//---------------------------------------
/** @short not realy used but maybe usefull :-)
*/
~SequenceAsHashMap();
//---------------------------------------
/** @short fill this map from the given
any, which of course must contain
a suitable sequence of element types
"css.beans.PropertyValue" or "css.beans.NamedValue".
@attention If the given Any is an empty one
(if its set to VOID), no exception
is thrown. In such case this instance will
be created as an empty one too!
@param aSource
contains the new items for this map.
@throw An <type scope="com::sun::star::beans">IllegalTypeException</type>
is thrown, if the given any does not contain a suitable sequence ...
but not if its a VOID Any!
*/
void operator<<(const ::com::sun::star::uno::Any& aSource);
//---------------------------------------
/** @short fill this map from the given
sequence, where every Any must contain
an item from type "css.beans.PropertyValue"
"css.beans.NamedValue".
@param lSource
contains the new items for this map.
@throw An <type scope="com::sun::star::beans">IllegalTypeException</type>
is thrown, if the given any sequence
uses wrong types for its items. VOID Any will be ignored!
*/
void operator<<(const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& lSource);
//---------------------------------------
/** @short fill this map from the given
PropertyValue sequence.
@param lSource
contains the new items for this map.
*/
void operator<<(const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lSource);
//---------------------------------------
/** @short fill this map from the given
NamedValue sequence.
@param lSource
contains the new items for this map.
*/
void operator<<(const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& lSource);
//---------------------------------------
/** @short converts this map instance to an
PropertyValue sequence.
@param lDestination
target sequence for converting.
*/
void operator>>(::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lDestination) const;
//---------------------------------------
/** @short converts this map instance to an
NamedValue sequence.
@param lDestination
target sequence for converting.
*/
void operator>>(::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& lDestination) const;
//---------------------------------------
/** @short return this map instance as an
Any, which can be
used in const environments only.
@descr Its made const to prevent using of the
return value directly as an in/out parameter!
usage: myMethod(stlDequeAdapter.getAsAnyList());
@param bAsPropertyValue
switch between using of PropertyValue or NamedValue as
value type.
@return A const Any, which
contains all items of this map.
*/
const ::com::sun::star::uno::Any getAsConstAny(::sal_Bool bAsPropertyValue) const;
//---------------------------------------
/** @short return this map instance as a
sequence< Any >, which can be
used in const environments only.
@descr Its made const to prevent using of the
return value directly as an in/out parameter!
usage: myMethod(stlDequeAdapter.getAsAnyList());
@param bAsPropertyValue
switch between using of PropertyValue or NamedValue as
value type.
@return A const sequence which elements of Any, which
contains all items of this map.
*/
const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any > getAsConstAnyList(::sal_Bool bAsPropertyValue) const;
//---------------------------------------
/** @short return this map instance to as a
NamedValue sequence, which can be
used in const environments only.
@descr Its made const to prevent using of the
return value directly as an in/out parameter!
usage: myMethod(stlDequeAdapter.getAsNamedValueList());
@return A const sequence of type NamedValue, which
contains all items of this map.
*/
const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue > getAsConstNamedValueList() const;
//---------------------------------------
/** @short return this map instance to as a
PropertyValue sequence, which can be
used in const environments only.
@descr Its made const to prevent using of the
return value directly as an in/out parameter!
usage: myMethod(stlDequeAdapter.getAsPropertyValueList());
@return A const sequence of type PropertyValue, which
contains all items of this map.
*/
const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > getAsConstPropertyValueList() const;
//---------------------------------------
/** @short check if the specified item exists
and return its (unpacked!) value or it returns the
specified default value otherwhise.
@descr If a value should be extracted only in case
the requsted property exists realy (without creating
of new items as it the index operator of a
has_map does!) this method can be used.
@param sKey
key name of the item.
@param aDefault
the default value, which is returned
if the specified item could not
be found.
@return The (unpacked!) value of the specified property or
the given default value otherwhise.
@attention "unpacked" means the Any content of every iterator->second!
*/
template< class TValueType >
TValueType getUnpackedValueOrDefault(const ::rtl::OUString& sKey ,
const TValueType& aDefault) const
{
const_iterator pIt = find(sKey);
if (pIt == end())
return aDefault;
TValueType aValue = TValueType();
if (!(pIt->second >>= aValue))
return aDefault;
return aValue;
}
//---------------------------------------
/** @short creates a new item with the specified
name and value only in case such item name
does not already exist.
@descr To check if the property already exists only
her name is used for compare. Its value isnt
checked!
@param sKey
key name of the property.
@param aValue
the new (unpacked!) value.
Note: This value will be transformed to an Any
internaly, because only Any values can be
part of a PropertyValue or NamedValue structure.
@return TRUE if this property was added as new item;
FALSE if it already exists.
*/
template< class TValueType >
sal_Bool createItemIfMissing(const ::rtl::OUString& sKey ,
const TValueType& aValue)
{
if (find(sKey) == end())
{
(*this)[sKey] = ::com::sun::star::uno::makeAny(aValue);
return sal_True;
}
return sal_False;
}
//---------------------------------------
/** @short check if all items of given map
exists in these called map also.
@descr Every item of the given map must exists
with same name and value inside these map.
But these map can contain additional items
which are not part of the search-map.
@param rCheck
the map containing all items for checking.
@return
TRUE if all items of Rcheck could be found
in these map; FALSE otherwise.
*/
sal_Bool match(const SequenceAsHashMap& rCheck) const;
//---------------------------------------
/** @short merge all values from the given map into
this one.
@descr Existing items will be overwritten ...
missing items will be created new ...
but non specified items will stay alive !
@param rSource
the map containing all items for the update.
*/
void update(const SequenceAsHashMap& rSource);
//---------------------------------------
/** @short can be used to generate a file dump of
the current content of this instance.
@descr Because the content of STL container
cant be analyzed easy, such dump function
seem to be usefull.
Of course its available in debug versions
only.
@param pFileName
a system file name.
(doesnt matter if relativ or absolute)
@param pComment
used to mark the dump inside the same log file.
Can be usefull to analyze changes of this
hash map due to the parts of an operation.
*/
#if OSL_DEBUG_LEVEL > 1
void dbg_dumpToFile(const char* pFileName, const char* pComment) const;
#endif
};
} // namespace comphelper
#endif // _COMPHELPER_SEQUENCEASHASHMAP_HXX_
<commit_msg>INTEGRATION: CWS changefileheader (1.8.58); FILE MERGED 2008/04/01 15:05:24 thb 1.8.58.3: #i85898# Stripping all external header guards 2008/04/01 12:26:26 thb 1.8.58.2: #i85898# Stripping all external header guards 2008/03/31 12:19:29 rt 1.8.58.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: sequenceashashmap.hxx,v $
* $Revision: 1.9 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _COMPHELPER_SEQUENCEASHASHMAP_HXX_
#define _COMPHELPER_SEQUENCEASHASHMAP_HXX_
//_______________________________________________
// includes
#ifndef INCLUDED_HASH_MAP
#include <hash_map>
#define INCLUDED_HASH_MAP
#endif
#ifndef INCLUDED_ALGORITHM
#include <algorithm>
#define INCLUDED_ALGORITHM
#endif
#include <com/sun/star/uno/Sequence.hxx>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/beans/NamedValue.hpp>
#ifndef _COM_SUN_STAR_BEANS_IllegalTypeException_HPP_
#include <com/sun/star/beans/IllegalTypeException.hpp>
#endif
#include "comphelper/comphelperdllapi.h"
// see method dbg_dumpToFile() below!
#if OSL_DEBUG_LEVEL > 1
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#include <stdio.h>
#endif
//_______________________________________________
// namespace
namespace comphelper{
//_______________________________________________
// definitions
/** @short Implements a stl hash map on top of some
specialized sequence from type PropertyValue
or NamedValue.
@descr That provides the possibility to modify
such name sequences very easy ...
*/
struct SequenceAsHashMapBase : public ::std::hash_map<
::rtl::OUString ,
::com::sun::star::uno::Any ,
::rtl::OUStringHash ,
::std::equal_to< ::rtl::OUString > >
{
};
class COMPHELPER_DLLPUBLIC SequenceAsHashMap : public SequenceAsHashMapBase
{
//-------------------------------------------
public:
//---------------------------------------
/** @short creates an empty hash map.
*/
SequenceAsHashMap();
//---------------------------------------
/** @see operator<<(const ::com::sun::star::uno::Any&)
*/
SequenceAsHashMap(const ::com::sun::star::uno::Any& aSource);
//---------------------------------------
/** @see operator<<(const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >&)
*/
SequenceAsHashMap(const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& lSource);
//---------------------------------------
/** @see operator<<(const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >&)
*/
SequenceAsHashMap(const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lSource);
//---------------------------------------
/** @see operator<<(const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >&)
*/
SequenceAsHashMap(const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& lSource);
//---------------------------------------
/** @short not realy used but maybe usefull :-)
*/
~SequenceAsHashMap();
//---------------------------------------
/** @short fill this map from the given
any, which of course must contain
a suitable sequence of element types
"css.beans.PropertyValue" or "css.beans.NamedValue".
@attention If the given Any is an empty one
(if its set to VOID), no exception
is thrown. In such case this instance will
be created as an empty one too!
@param aSource
contains the new items for this map.
@throw An <type scope="com::sun::star::beans">IllegalTypeException</type>
is thrown, if the given any does not contain a suitable sequence ...
but not if its a VOID Any!
*/
void operator<<(const ::com::sun::star::uno::Any& aSource);
//---------------------------------------
/** @short fill this map from the given
sequence, where every Any must contain
an item from type "css.beans.PropertyValue"
"css.beans.NamedValue".
@param lSource
contains the new items for this map.
@throw An <type scope="com::sun::star::beans">IllegalTypeException</type>
is thrown, if the given any sequence
uses wrong types for its items. VOID Any will be ignored!
*/
void operator<<(const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& lSource);
//---------------------------------------
/** @short fill this map from the given
PropertyValue sequence.
@param lSource
contains the new items for this map.
*/
void operator<<(const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lSource);
//---------------------------------------
/** @short fill this map from the given
NamedValue sequence.
@param lSource
contains the new items for this map.
*/
void operator<<(const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& lSource);
//---------------------------------------
/** @short converts this map instance to an
PropertyValue sequence.
@param lDestination
target sequence for converting.
*/
void operator>>(::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& lDestination) const;
//---------------------------------------
/** @short converts this map instance to an
NamedValue sequence.
@param lDestination
target sequence for converting.
*/
void operator>>(::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& lDestination) const;
//---------------------------------------
/** @short return this map instance as an
Any, which can be
used in const environments only.
@descr Its made const to prevent using of the
return value directly as an in/out parameter!
usage: myMethod(stlDequeAdapter.getAsAnyList());
@param bAsPropertyValue
switch between using of PropertyValue or NamedValue as
value type.
@return A const Any, which
contains all items of this map.
*/
const ::com::sun::star::uno::Any getAsConstAny(::sal_Bool bAsPropertyValue) const;
//---------------------------------------
/** @short return this map instance as a
sequence< Any >, which can be
used in const environments only.
@descr Its made const to prevent using of the
return value directly as an in/out parameter!
usage: myMethod(stlDequeAdapter.getAsAnyList());
@param bAsPropertyValue
switch between using of PropertyValue or NamedValue as
value type.
@return A const sequence which elements of Any, which
contains all items of this map.
*/
const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any > getAsConstAnyList(::sal_Bool bAsPropertyValue) const;
//---------------------------------------
/** @short return this map instance to as a
NamedValue sequence, which can be
used in const environments only.
@descr Its made const to prevent using of the
return value directly as an in/out parameter!
usage: myMethod(stlDequeAdapter.getAsNamedValueList());
@return A const sequence of type NamedValue, which
contains all items of this map.
*/
const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue > getAsConstNamedValueList() const;
//---------------------------------------
/** @short return this map instance to as a
PropertyValue sequence, which can be
used in const environments only.
@descr Its made const to prevent using of the
return value directly as an in/out parameter!
usage: myMethod(stlDequeAdapter.getAsPropertyValueList());
@return A const sequence of type PropertyValue, which
contains all items of this map.
*/
const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > getAsConstPropertyValueList() const;
//---------------------------------------
/** @short check if the specified item exists
and return its (unpacked!) value or it returns the
specified default value otherwhise.
@descr If a value should be extracted only in case
the requsted property exists realy (without creating
of new items as it the index operator of a
has_map does!) this method can be used.
@param sKey
key name of the item.
@param aDefault
the default value, which is returned
if the specified item could not
be found.
@return The (unpacked!) value of the specified property or
the given default value otherwhise.
@attention "unpacked" means the Any content of every iterator->second!
*/
template< class TValueType >
TValueType getUnpackedValueOrDefault(const ::rtl::OUString& sKey ,
const TValueType& aDefault) const
{
const_iterator pIt = find(sKey);
if (pIt == end())
return aDefault;
TValueType aValue = TValueType();
if (!(pIt->second >>= aValue))
return aDefault;
return aValue;
}
//---------------------------------------
/** @short creates a new item with the specified
name and value only in case such item name
does not already exist.
@descr To check if the property already exists only
her name is used for compare. Its value isnt
checked!
@param sKey
key name of the property.
@param aValue
the new (unpacked!) value.
Note: This value will be transformed to an Any
internaly, because only Any values can be
part of a PropertyValue or NamedValue structure.
@return TRUE if this property was added as new item;
FALSE if it already exists.
*/
template< class TValueType >
sal_Bool createItemIfMissing(const ::rtl::OUString& sKey ,
const TValueType& aValue)
{
if (find(sKey) == end())
{
(*this)[sKey] = ::com::sun::star::uno::makeAny(aValue);
return sal_True;
}
return sal_False;
}
//---------------------------------------
/** @short check if all items of given map
exists in these called map also.
@descr Every item of the given map must exists
with same name and value inside these map.
But these map can contain additional items
which are not part of the search-map.
@param rCheck
the map containing all items for checking.
@return
TRUE if all items of Rcheck could be found
in these map; FALSE otherwise.
*/
sal_Bool match(const SequenceAsHashMap& rCheck) const;
//---------------------------------------
/** @short merge all values from the given map into
this one.
@descr Existing items will be overwritten ...
missing items will be created new ...
but non specified items will stay alive !
@param rSource
the map containing all items for the update.
*/
void update(const SequenceAsHashMap& rSource);
//---------------------------------------
/** @short can be used to generate a file dump of
the current content of this instance.
@descr Because the content of STL container
cant be analyzed easy, such dump function
seem to be usefull.
Of course its available in debug versions
only.
@param pFileName
a system file name.
(doesnt matter if relativ or absolute)
@param pComment
used to mark the dump inside the same log file.
Can be usefull to analyze changes of this
hash map due to the parts of an operation.
*/
#if OSL_DEBUG_LEVEL > 1
void dbg_dumpToFile(const char* pFileName, const char* pComment) const;
#endif
};
} // namespace comphelper
#endif // _COMPHELPER_SEQUENCEASHASHMAP_HXX_
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkPlot.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 "vtkPlot.h"
#include "vtkAxis.h"
#include "vtkPen.h"
#include "vtkBrush.h"
#include "vtkTable.h"
#include "vtkDataObject.h"
#include "vtkIdTypeArray.h"
#include "vtkContextMapper2D.h"
#include "vtkObjectFactory.h"
#include "vtkStringArray.h"
#include "vtksys/ios/sstream"
vtkCxxSetObjectMacro(vtkPlot, Selection, vtkIdTypeArray);
vtkCxxSetObjectMacro(vtkPlot, XAxis, vtkAxis);
vtkCxxSetObjectMacro(vtkPlot, YAxis, vtkAxis);
//-----------------------------------------------------------------------------
vtkPlot::vtkPlot()
{
this->Pen = vtkPen::New();
this->Pen->SetWidth(2.0);
this->Brush = vtkBrush::New();
this->Labels = NULL;
this->UseIndexForXSeries = false;
this->Data = vtkContextMapper2D::New();
this->Selection = NULL;
this->XAxis = NULL;
this->YAxis = NULL;
this->TooltipDefaultLabelFormat = "%l: %x, %y";
}
//-----------------------------------------------------------------------------
vtkPlot::~vtkPlot()
{
if (this->Pen)
{
this->Pen->Delete();
this->Pen = NULL;
}
if (this->Brush)
{
this->Brush->Delete();
this->Brush = NULL;
}
if (this->Data)
{
this->Data->Delete();
this->Data = NULL;
}
if (this->Selection)
{
this->Selection->Delete();
this->Selection = NULL;
}
this->SetLabels(NULL);
this->SetXAxis(NULL);
this->SetYAxis(NULL);
}
//-----------------------------------------------------------------------------
bool vtkPlot::PaintLegend(vtkContext2D*, const vtkRectf&, int)
{
return false;
}
//-----------------------------------------------------------------------------
vtkIdType vtkPlot::GetNearestPoint(const vtkVector2f&, const vtkVector2f&,
vtkVector2f*)
{
return -1;
}
//-----------------------------------------------------------------------------
vtkStdString vtkPlot::GetTooltipLabel(const vtkVector2f &plotPos,
vtkIdType seriesIndex,
vtkIdType)
{
vtkStdString tooltipLabel;
vtkStdString &format = this->TooltipLabelFormat.empty() ?
this->TooltipDefaultLabelFormat : this->TooltipLabelFormat;
// Parse TooltipLabelFormat and build tooltipLabel
bool escapeNext = false;
for (size_t i = 0; i < format.length(); ++i)
{
if (escapeNext)
{
switch (format[i])
{
case 'x':
tooltipLabel += this->GetNumber(plotPos.X(), this->XAxis);
break;
case 'y':
tooltipLabel += this->GetNumber(plotPos.Y(), this->YAxis);
break;
case 'i':
if (this->IndexedLabels &&
seriesIndex >= 0 &&
seriesIndex < this->IndexedLabels->GetNumberOfTuples())
{
tooltipLabel += this->IndexedLabels->GetValue(seriesIndex);
}
break;
case 'l':
// GetLabel() is GetLabel(0) in this implementation
tooltipLabel += this->GetLabel();
break;
default: // If no match, insert the entire format tag
tooltipLabel += "%";
tooltipLabel += format[i];
break;
}
escapeNext = false;
}
else
{
if (format[i] == '%')
{
escapeNext = true;
}
else
{
tooltipLabel += format[i];
}
}
}
return tooltipLabel;
}
//-----------------------------------------------------------------------------
vtkStdString vtkPlot::GetNumber(double position, vtkAxis *axis)
{
// Determine and format the X and Y position in the chart
vtksys_ios::ostringstream ostr;
ostr.imbue(vtkstd::locale::classic());
ostr.setf(ios::fixed, ios::floatfield);
if (axis)
{
ostr.precision(this->XAxis->GetPrecision());
}
if (axis && axis->GetLogScale())
{
// If axes are set to logarithmic scale we need to convert the
// axis value using 10^(axis value)
ostr << pow(double(10.0), double(position));
}
else
{
ostr << position;
}
return ostr.str();
}
//-----------------------------------------------------------------------------
bool vtkPlot::SelectPoints(const vtkVector2f&, const vtkVector2f&)
{
return false;
}
//-----------------------------------------------------------------------------
void vtkPlot::SetColor(unsigned char r, unsigned char g, unsigned char b,
unsigned char a)
{
this->Pen->SetColor(r, g, b, a);
}
//-----------------------------------------------------------------------------
void vtkPlot::SetColor(double r, double g, double b)
{
this->Pen->SetColorF(r, g, b);
}
//-----------------------------------------------------------------------------
void vtkPlot::GetColor(double rgb[3])
{
this->Pen->GetColorF(rgb);
}
//-----------------------------------------------------------------------------
void vtkPlot::GetColor(unsigned char rgb[3])
{
double rgbF[3];
this->GetColor(rgbF);
rgb[0] = static_cast<unsigned char>(255. * rgbF[0] + 0.5);
rgb[1] = static_cast<unsigned char>(255. * rgbF[1] + 0.5);
rgb[2] = static_cast<unsigned char>(255. * rgbF[2] + 0.5);
}
//-----------------------------------------------------------------------------
void vtkPlot::SetWidth(float width)
{
this->Pen->SetWidth(width);
}
//-----------------------------------------------------------------------------
float vtkPlot::GetWidth()
{
return this->Pen->GetWidth();
}
//-----------------------------------------------------------------------------
void vtkPlot::SetLabel(const vtkStdString& label)
{
vtkStringArray *labels = vtkStringArray::New();
labels->InsertNextValue(label);
this->SetLabels(labels);
labels->Delete();
}
//-----------------------------------------------------------------------------
vtkStdString vtkPlot::GetLabel()
{
return this->GetLabel(0);
}
//-----------------------------------------------------------------------------
void vtkPlot::SetLabels(vtkStringArray *labels)
{
if (this->Labels == labels)
{
return;
}
this->Labels = labels;
this->Modified();
}
//-----------------------------------------------------------------------------
vtkStringArray * vtkPlot::GetLabels()
{
// If the label string is empty, return the y column name
if (this->Labels)
{
return this->Labels;
}
else if (this->AutoLabels)
{
return this->AutoLabels;
}
else if (this->Data->GetInput() &&
this->Data->GetInputArrayToProcess(1, this->Data->GetInput()))
{
this->AutoLabels = vtkSmartPointer<vtkStringArray>::New();
this->AutoLabels->InsertNextValue(this->Data->GetInputArrayToProcess(1, this->Data->GetInput())->GetName());
return this->AutoLabels;
}
else
{
return NULL;
}
}
//-----------------------------------------------------------------------------
int vtkPlot::GetNumberOfLabels()
{
vtkStringArray *labels = this->GetLabels();
if (labels)
{
return labels->GetNumberOfValues();
}
else
{
return 0;
}
}
//-----------------------------------------------------------------------------
void vtkPlot::SetIndexedLabels(vtkStringArray *labels)
{
if (this->IndexedLabels == labels)
{
return;
}
if (labels)
{
this->TooltipDefaultLabelFormat = "%i: %x, %y";
}
else
{
this->TooltipDefaultLabelFormat = "%l: %x, %y";
}
this->IndexedLabels = labels;
this->Modified();
}
//-----------------------------------------------------------------------------
vtkStringArray * vtkPlot::GetIndexedLabels()
{
return this->IndexedLabels.GetPointer();
}
//-----------------------------------------------------------------------------
void vtkPlot::SetTooltipLabelFormat(const vtkStdString &labelFormat)
{
if (this->TooltipLabelFormat == labelFormat)
{
return;
}
this->TooltipLabelFormat = labelFormat;
this->Modified();
}
//-----------------------------------------------------------------------------
vtkStdString vtkPlot::GetTooltipLabelFormat()
{
return this->TooltipLabelFormat;
}
//-----------------------------------------------------------------------------
vtkStdString vtkPlot::GetLabel(vtkIdType index)
{
vtkStringArray *labels = this->GetLabels();
if (labels && index >= 0 && index < labels->GetNumberOfValues())
{
return labels->GetValue(index);
}
else
{
return vtkStdString();
}
}
//-----------------------------------------------------------------------------
void vtkPlot::SetInput(vtkTable *table)
{
this->Data->SetInput(table);
this->AutoLabels = 0; // No longer valid
}
//-----------------------------------------------------------------------------
void vtkPlot::SetInput(vtkTable *table, const vtkStdString &xColumn,
const vtkStdString &yColumn)
{
vtkDebugMacro(<< "Setting input, X column = \"" << xColumn.c_str()
<< "\", " << "Y column = \"" << yColumn.c_str() << "\"");
this->Data->SetInput(table);
this->Data->SetInputArrayToProcess(0, 0, 0,
vtkDataObject::FIELD_ASSOCIATION_ROWS,
xColumn.c_str());
this->Data->SetInputArrayToProcess(1, 0, 0,
vtkDataObject::FIELD_ASSOCIATION_ROWS,
yColumn.c_str());
this->AutoLabels = 0; // No longer valid
}
//-----------------------------------------------------------------------------
void vtkPlot::SetInput(vtkTable *table, vtkIdType xColumn,
vtkIdType yColumn)
{
this->SetInput(table,
table->GetColumnName(xColumn),
table->GetColumnName(yColumn));
}
//-----------------------------------------------------------------------------
vtkTable* vtkPlot::GetInput()
{
return this->Data->GetInput();
}
//-----------------------------------------------------------------------------
void vtkPlot::SetInputArray(int index, const vtkStdString &name)
{
this->Data->SetInputArrayToProcess(index, 0, 0,
vtkDataObject::FIELD_ASSOCIATION_ROWS,
name.c_str());
this->AutoLabels = 0; // No longer valid
}
//-----------------------------------------------------------------------------
void vtkPlot::SetProperty(const vtkStdString&, const vtkVariant&)
{
}
//-----------------------------------------------------------------------------
vtkVariant vtkPlot::GetProperty(const vtkStdString&)
{
return vtkVariant();
}
//-----------------------------------------------------------------------------
void vtkPlot::PrintSelf(ostream &os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
<commit_msg>ENH: Use vtkNew for temporary variable.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkPlot.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 "vtkPlot.h"
#include "vtkAxis.h"
#include "vtkPen.h"
#include "vtkBrush.h"
#include "vtkTable.h"
#include "vtkDataObject.h"
#include "vtkIdTypeArray.h"
#include "vtkContextMapper2D.h"
#include "vtkObjectFactory.h"
#include "vtkStringArray.h"
#include "vtkNew.h"
#include "vtksys/ios/sstream"
vtkCxxSetObjectMacro(vtkPlot, Selection, vtkIdTypeArray);
vtkCxxSetObjectMacro(vtkPlot, XAxis, vtkAxis);
vtkCxxSetObjectMacro(vtkPlot, YAxis, vtkAxis);
//-----------------------------------------------------------------------------
vtkPlot::vtkPlot()
{
this->Pen = vtkPen::New();
this->Pen->SetWidth(2.0);
this->Brush = vtkBrush::New();
this->Labels = NULL;
this->UseIndexForXSeries = false;
this->Data = vtkContextMapper2D::New();
this->Selection = NULL;
this->XAxis = NULL;
this->YAxis = NULL;
this->TooltipDefaultLabelFormat = "%l: %x, %y";
}
//-----------------------------------------------------------------------------
vtkPlot::~vtkPlot()
{
if (this->Pen)
{
this->Pen->Delete();
this->Pen = NULL;
}
if (this->Brush)
{
this->Brush->Delete();
this->Brush = NULL;
}
if (this->Data)
{
this->Data->Delete();
this->Data = NULL;
}
if (this->Selection)
{
this->Selection->Delete();
this->Selection = NULL;
}
this->SetLabels(NULL);
this->SetXAxis(NULL);
this->SetYAxis(NULL);
}
//-----------------------------------------------------------------------------
bool vtkPlot::PaintLegend(vtkContext2D*, const vtkRectf&, int)
{
return false;
}
//-----------------------------------------------------------------------------
vtkIdType vtkPlot::GetNearestPoint(const vtkVector2f&, const vtkVector2f&,
vtkVector2f*)
{
return -1;
}
//-----------------------------------------------------------------------------
vtkStdString vtkPlot::GetTooltipLabel(const vtkVector2f &plotPos,
vtkIdType seriesIndex,
vtkIdType)
{
vtkStdString tooltipLabel;
vtkStdString &format = this->TooltipLabelFormat.empty() ?
this->TooltipDefaultLabelFormat : this->TooltipLabelFormat;
// Parse TooltipLabelFormat and build tooltipLabel
bool escapeNext = false;
for (size_t i = 0; i < format.length(); ++i)
{
if (escapeNext)
{
switch (format[i])
{
case 'x':
tooltipLabel += this->GetNumber(plotPos.X(), this->XAxis);
break;
case 'y':
tooltipLabel += this->GetNumber(plotPos.Y(), this->YAxis);
break;
case 'i':
if (this->IndexedLabels &&
seriesIndex >= 0 &&
seriesIndex < this->IndexedLabels->GetNumberOfTuples())
{
tooltipLabel += this->IndexedLabels->GetValue(seriesIndex);
}
break;
case 'l':
// GetLabel() is GetLabel(0) in this implementation
tooltipLabel += this->GetLabel();
break;
default: // If no match, insert the entire format tag
tooltipLabel += "%";
tooltipLabel += format[i];
break;
}
escapeNext = false;
}
else
{
if (format[i] == '%')
{
escapeNext = true;
}
else
{
tooltipLabel += format[i];
}
}
}
return tooltipLabel;
}
//-----------------------------------------------------------------------------
vtkStdString vtkPlot::GetNumber(double position, vtkAxis *axis)
{
// Determine and format the X and Y position in the chart
vtksys_ios::ostringstream ostr;
ostr.imbue(vtkstd::locale::classic());
ostr.setf(ios::fixed, ios::floatfield);
if (axis)
{
ostr.precision(this->XAxis->GetPrecision());
}
if (axis && axis->GetLogScale())
{
// If axes are set to logarithmic scale we need to convert the
// axis value using 10^(axis value)
ostr << pow(double(10.0), double(position));
}
else
{
ostr << position;
}
return ostr.str();
}
//-----------------------------------------------------------------------------
bool vtkPlot::SelectPoints(const vtkVector2f&, const vtkVector2f&)
{
return false;
}
//-----------------------------------------------------------------------------
void vtkPlot::SetColor(unsigned char r, unsigned char g, unsigned char b,
unsigned char a)
{
this->Pen->SetColor(r, g, b, a);
}
//-----------------------------------------------------------------------------
void vtkPlot::SetColor(double r, double g, double b)
{
this->Pen->SetColorF(r, g, b);
}
//-----------------------------------------------------------------------------
void vtkPlot::GetColor(double rgb[3])
{
this->Pen->GetColorF(rgb);
}
//-----------------------------------------------------------------------------
void vtkPlot::GetColor(unsigned char rgb[3])
{
double rgbF[3];
this->GetColor(rgbF);
rgb[0] = static_cast<unsigned char>(255. * rgbF[0] + 0.5);
rgb[1] = static_cast<unsigned char>(255. * rgbF[1] + 0.5);
rgb[2] = static_cast<unsigned char>(255. * rgbF[2] + 0.5);
}
//-----------------------------------------------------------------------------
void vtkPlot::SetWidth(float width)
{
this->Pen->SetWidth(width);
}
//-----------------------------------------------------------------------------
float vtkPlot::GetWidth()
{
return this->Pen->GetWidth();
}
//-----------------------------------------------------------------------------
void vtkPlot::SetLabel(const vtkStdString& label)
{
vtkNew<vtkStringArray> labels;
labels->InsertNextValue(label);
this->SetLabels(labels.GetPointer());
}
//-----------------------------------------------------------------------------
vtkStdString vtkPlot::GetLabel()
{
return this->GetLabel(0);
}
//-----------------------------------------------------------------------------
void vtkPlot::SetLabels(vtkStringArray *labels)
{
if (this->Labels == labels)
{
return;
}
this->Labels = labels;
this->Modified();
}
//-----------------------------------------------------------------------------
vtkStringArray * vtkPlot::GetLabels()
{
// If the label string is empty, return the y column name
if (this->Labels)
{
return this->Labels;
}
else if (this->AutoLabels)
{
return this->AutoLabels;
}
else if (this->Data->GetInput() &&
this->Data->GetInputArrayToProcess(1, this->Data->GetInput()))
{
this->AutoLabels = vtkSmartPointer<vtkStringArray>::New();
this->AutoLabels->InsertNextValue(this->Data->GetInputArrayToProcess(1, this->Data->GetInput())->GetName());
return this->AutoLabels;
}
else
{
return NULL;
}
}
//-----------------------------------------------------------------------------
int vtkPlot::GetNumberOfLabels()
{
vtkStringArray *labels = this->GetLabels();
if (labels)
{
return labels->GetNumberOfValues();
}
else
{
return 0;
}
}
//-----------------------------------------------------------------------------
void vtkPlot::SetIndexedLabels(vtkStringArray *labels)
{
if (this->IndexedLabels == labels)
{
return;
}
if (labels)
{
this->TooltipDefaultLabelFormat = "%i: %x, %y";
}
else
{
this->TooltipDefaultLabelFormat = "%l: %x, %y";
}
this->IndexedLabels = labels;
this->Modified();
}
//-----------------------------------------------------------------------------
vtkStringArray * vtkPlot::GetIndexedLabels()
{
return this->IndexedLabels.GetPointer();
}
//-----------------------------------------------------------------------------
void vtkPlot::SetTooltipLabelFormat(const vtkStdString &labelFormat)
{
if (this->TooltipLabelFormat == labelFormat)
{
return;
}
this->TooltipLabelFormat = labelFormat;
this->Modified();
}
//-----------------------------------------------------------------------------
vtkStdString vtkPlot::GetTooltipLabelFormat()
{
return this->TooltipLabelFormat;
}
//-----------------------------------------------------------------------------
vtkStdString vtkPlot::GetLabel(vtkIdType index)
{
vtkStringArray *labels = this->GetLabels();
if (labels && index >= 0 && index < labels->GetNumberOfValues())
{
return labels->GetValue(index);
}
else
{
return vtkStdString();
}
}
//-----------------------------------------------------------------------------
void vtkPlot::SetInput(vtkTable *table)
{
this->Data->SetInput(table);
this->AutoLabels = 0; // No longer valid
}
//-----------------------------------------------------------------------------
void vtkPlot::SetInput(vtkTable *table, const vtkStdString &xColumn,
const vtkStdString &yColumn)
{
vtkDebugMacro(<< "Setting input, X column = \"" << xColumn.c_str()
<< "\", " << "Y column = \"" << yColumn.c_str() << "\"");
this->Data->SetInput(table);
this->Data->SetInputArrayToProcess(0, 0, 0,
vtkDataObject::FIELD_ASSOCIATION_ROWS,
xColumn.c_str());
this->Data->SetInputArrayToProcess(1, 0, 0,
vtkDataObject::FIELD_ASSOCIATION_ROWS,
yColumn.c_str());
this->AutoLabels = 0; // No longer valid
}
//-----------------------------------------------------------------------------
void vtkPlot::SetInput(vtkTable *table, vtkIdType xColumn,
vtkIdType yColumn)
{
this->SetInput(table,
table->GetColumnName(xColumn),
table->GetColumnName(yColumn));
}
//-----------------------------------------------------------------------------
vtkTable* vtkPlot::GetInput()
{
return this->Data->GetInput();
}
//-----------------------------------------------------------------------------
void vtkPlot::SetInputArray(int index, const vtkStdString &name)
{
this->Data->SetInputArrayToProcess(index, 0, 0,
vtkDataObject::FIELD_ASSOCIATION_ROWS,
name.c_str());
this->AutoLabels = 0; // No longer valid
}
//-----------------------------------------------------------------------------
void vtkPlot::SetProperty(const vtkStdString&, const vtkVariant&)
{
}
//-----------------------------------------------------------------------------
vtkVariant vtkPlot::GetProperty(const vtkStdString&)
{
return vtkVariant();
}
//-----------------------------------------------------------------------------
void vtkPlot::PrintSelf(ostream &os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
<|endoftext|> |
<commit_before>//
// Created by ARJ on 11/22/15.
//
#include "ufrp4.h"
#include <iostream>
#include <memory>
using namespace ufrp;
using namespace std;
struct A {
expr_ptr_for<VarExpr<int>>::type e;
A() : e(makeexpr<VarExpr<int>>(6)) {}
};
int main() {
ConstExpr<int, 112> c;
VarExpr<int> v2(2);
VarExpr<int> v(1);
VarExpr<int> v3(268);
auto v4 = v;
cout << v2 + v4 + v3 + c << endl;
}<commit_msg>Fiddling.<commit_after>//
// Created by ARJ on 11/22/15.
//
#include "ufrp4.h"
#include <iostream>
#include <memory>
using namespace ufrp;
using namespace std;
struct A {
};
int main() {
ConstExpr<int, 112> c;
VarExpr<int> v2(2);
VarExpr<int> v(1);
VarExpr<int> v3(268);
auto v4 = v;
cout << v2 + v4 + v3 + c << endl;
}<|endoftext|> |
<commit_before>/*
* TODO: Implemenet O(|V|^2) version of inserts for Floyd Warshall.
*/
#include <string.h> //< memset, memcpy
unsigned int transitive_closure(bool *adjacency_matrix, const unsigned int n, bool *current) {
const unsigned int SIZE = n*n; //< Size of matrix
//bool *current = new bool[SIZE]; //< Temp array stating if there is a path from (i,j)
bool *previous = new bool[SIZE]; //< Temp array stating if there is a path from (i,j)
unsigned int i, j, k; //< Indices for the loop
unsigned int entry, col; //< Position in matrix
unsigned int count = 0; //< Number of transitive closures
bool *tmp; //< Keeps T(k) and T(k-1) respectively
bool gotIntermediate; //< Indicate if node_k was used as intermediate node
// All are not connected at first
memset( current, false, SIZE*sizeof(bool));
// Get all closures without any intermediate nodes
for(i = 0; i < n; i++) {
for(j = 0; j < n; j++) {
entry = i*n + j;
if(adjacency_matrix[entry] || i == j) {
count++;
current[entry] = true;
}
}
}
for(k = 0; k < n; k++) {
// Swap current and previous
tmp = current;
current = previous;
previous = tmp;
for(i = 0; i < n; i++) {
col = i*n; //<- Current column
if(i != k) {
for(j = 0; j < n; j++) {
// Check if there is a path using node_k as intermediate,
// i.e. node_i -> ... -> node_k -> node_j
entry = col + j;
gotIntermediate = previous[col + k] & previous[k*n + j];
// If a _new_ closure was intermediate found using k as
// intermediate, then increment the counter
if(!previous[entry] && gotIntermediate) count++;
// Update the current value
current[entry] = previous[entry] | gotIntermediate;
}
} else {
// Nothing can change using the the k'th node as intermediate,
// e.g. node_1 -> node_1 -> node_5 is the same as node_1 -> node_1
memcpy(¤t[col], &previous[col], n*sizeof(bool));
}
}
}
//delete[] current;
delete[] previous;
// The total number of pairs that is part of the transitive closure
return count;
}
<commit_msg>Removed wrong delete of array<commit_after>/*
* TODO: Implemenet O(|V|^2) version of inserts for Floyd Warshall.
*/
#include <string.h> //< memset, memcpy
unsigned int transitive_closure(bool *adjacency_matrix, const unsigned int n, bool *current) {
const unsigned int SIZE = n*n; //< Size of matrix
//bool *current = new bool[SIZE]; //< Temp array stating if there is a path from (i,j)
bool *previous = new bool[SIZE]; //< Temp array stating if there is a path from (i,j)
unsigned int i, j, k; //< Indices for the loop
unsigned int entry, col; //< Position in matrix
unsigned int count = 0; //< Number of transitive closures
bool *tmp; //< Keeps T(k) and T(k-1) respectively
bool gotIntermediate; //< Indicate if node_k was used as intermediate node
// All are not connected at first
memset( current, false, SIZE*sizeof(bool));
// Get all closures without any intermediate nodes
for(i = 0; i < n; i++) {
for(j = 0; j < n; j++) {
entry = i*n + j;
if(adjacency_matrix[entry] || i == j) {
count++;
current[entry] = true;
}
}
}
for(k = 0; k < n; k++) {
// Swap current and previous
tmp = current;
current = previous;
previous = tmp;
for(i = 0; i < n; i++) {
col = i*n; //<- Current column
if(i != k) {
for(j = 0; j < n; j++) {
// Check if there is a path using node_k as intermediate,
// i.e. node_i -> ... -> node_k -> node_j
entry = col + j;
gotIntermediate = previous[col + k] & previous[k*n + j];
// If a _new_ closure was intermediate found using k as
// intermediate, then increment the counter
if(!previous[entry] && gotIntermediate) count++;
// Update the current value
current[entry] = previous[entry] | gotIntermediate;
}
} else {
// Nothing can change using the the k'th node as intermediate,
// e.g. node_1 -> node_1 -> node_5 is the same as node_1 -> node_1
memcpy(¤t[col], &previous[col], n*sizeof(bool));
}
}
}
// TODO: Fix memory leak!
//delete[] current;
//delete[] previous;
// The total number of pairs that is part of the transitive closure
return count;
}
<|endoftext|> |
<commit_before>// * BeginRiceCopyright *****************************************************
//
// Copyright ((c)) 2002-2014, Rice University
// 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 Rice University (RICE) 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 RICE 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 RICE 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.
//
// ******************************************************* EndRiceCopyright *
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <iostream>
#include <unistd.h>
#include <assert.h>
#include <string.h>
#include <sstream>
#include "pin.H"
#include "cctlib.H"
using namespace std;
using namespace PinCCTLib;
#include <unordered_set>
#include <vector>
#include <unordered_map>
#include <algorithm>
#define MAX_FOOTPRINT_CONTEXTS_TO_LOG (1000)
struct node_metric_t {
unordered_set<void *> addressSet;
uint64_t accessNum;
};
struct sort_format_t {
ContextHandle_t handle;
uint64_t footprint;
uint64_t accessNum;
};
unordered_map<THREADID, unordered_map<uint32_t, struct node_metric_t>> hmap_vector;
INT32 Usage2() {
PIN_ERROR("Pin tool to gather calling context on each load and store.\n" + KNOB_BASE::StringKnobSummary() + "\n");
return -1;
}
// Main for DeadSpy, initialize the tool, register instrumentation functions and call the target program.
FILE* gTraceFile;
// Initialized the needed data structures before launching the target program
void ClientInit(int argc, char* argv[]) {
// Create output file
char name[MAX_FILE_PATH] = "client.out.";
char* envPath = getenv("CCTLIB_CLIENT_OUTPUT_FILE");
if(envPath) {
// assumes max of MAX_FILE_PATH
strcpy(name, envPath);
}
gethostname(name + strlen(name), MAX_FILE_PATH - strlen(name));
pid_t pid = getpid();
sprintf(name + strlen(name), "%d", pid);
cerr << "\n Creating log file at:" << name << "\n";
gTraceFile = fopen(name, "w");
// print the arguments passed
fprintf(gTraceFile, "\n");
for(int i = 0 ; i < argc; i++) {
fprintf(gTraceFile, "%s ", argv[i]);
}
fprintf(gTraceFile, "\n");
}
VOID MemFunc(THREADID id, void* addr) {
// at memory instruction record the footprint
void **metric = GetIPNodeMetric(id, 0);
if (*metric == NULL) {
// use ctxthndl as the key to associate footprint with the trace
ContextHandle_t ctxthndl = GetContextHandle(id, 0);
*metric = &(hmap_vector[id])[ctxthndl];
(hmap_vector[id])[ctxthndl].addressSet.insert(addr);
(hmap_vector[id])[ctxthndl].accessNum++;
}
else {
(static_cast<struct node_metric_t*>(*metric))->addressSet.insert(addr);
(static_cast<struct node_metric_t*>(*metric))->accessNum++;
}
}
VOID InstrumentInsCallback(INS ins, VOID* v, const uint32_t slot) {
if (!INS_IsMemoryRead(ins) && !INS_IsMemoryWrite(ins)) return;
if (INS_IsStackRead(ins) || INS_IsStackWrite(ins)) return;
if (INS_IsBranchOrCall(ins) || INS_IsRet(ins)) return;
UINT32 memOperands = INS_MemoryOperandCount(ins);
for (UINT32 memOp = 0; memOp < memOperands; memOp++)
{
INS_InsertPredicatedCall(ins, IPOINT_BEFORE, (AFUNPTR)MemFunc, IARG_THREAD_ID, IARG_MEMORYOP_EA, memOp, IARG_END);
}
}
void MergeFootPrint(const THREADID threadid, ContextHandle_t myHandle, ContextHandle_t parentHandle, void **myMetric, void **parentMetric)
{
if (*myMetric == NULL) return;
struct node_metric_t *hset = static_cast<struct node_metric_t*>(*myMetric);
if (*parentMetric == NULL) {
*parentMetric = &((hmap_vector[threadid])[parentHandle]);
(hmap_vector[threadid])[parentHandle].addressSet.insert(hset->addressSet.begin(), hset->addressSet.end());
(hmap_vector[threadid])[parentHandle].accessNum += hset->accessNum;
}
else {
(static_cast<struct node_metric_t*>(*parentMetric))->addressSet.insert(hset->addressSet.begin(), hset->addressSet.end());
(static_cast<struct node_metric_t*>(*parentMetric))->accessNum += hset->accessNum;
}
}
inline bool FootPrintCompare(const struct sort_format_t &first, const struct sort_format_t &second)
{
return first.footprint > second.footprint ? true : false;
}
void PrintTopFootPrintPath(THREADID threadid)
{
uint64_t cntxtNum = 0;
vector<struct sort_format_t> TmpList;
fprintf(gTraceFile, "*************** Dump Data from Thread %d ****************\n", threadid);
unordered_map<uint32_t, struct node_metric_t> &hmap = hmap_vector[threadid];
unordered_map<uint32_t, struct node_metric_t>::iterator it;
for (it = hmap.begin(); it != hmap.end(); ++it) {
struct sort_format_t tmp;
tmp.handle = (*it).first;
tmp.footprint = (uint64_t)(*it).second.addressSet.size();
tmp.accessNum = (uint64_t)(*it).second.accessNum;
TmpList.emplace_back(tmp);
}
sort(TmpList.begin(), TmpList.end(), FootPrintCompare);
vector<struct sort_format_t>::iterator ListIt;
for (ListIt = TmpList.begin(); ListIt != TmpList.end(); ++ListIt) {
if (cntxtNum < MAX_FOOTPRINT_CONTEXTS_TO_LOG) {
fprintf(gTraceFile, "Footprint is %lu, #access is, context is %lu", (*ListIt).footprint, (*ListIt).accessNum);
PrintFullCallingContext((*ListIt).handle);
fprintf(gTraceFile, "\n------------------------------------------------\n");
}
else {
break;
}
cntxtNum++;
}
}
VOID ThreadFiniFunc(THREADID threadid, const CONTEXT *ctxt, INT32 code, VOID *v)
{
// traverse CCT bottom to up
TraverseCCTBottomUp(threadid, MergeFootPrint);
// print the footprint for functions
PIN_LockClient();
PrintTopFootPrintPath(threadid);
PIN_UnlockClient();
}
VOID FiniFunc(INT32 code, VOID *v)
{
// do whatever you want to the full CCT with footpirnt
}
int main(int argc, char* argv[]) {
// Initialize PIN
if(PIN_Init(argc, argv))
return Usage2();
// Initialize Symbols, we need them to report functions and lines
PIN_InitSymbols();
// Init Client
ClientInit(argc, argv);
// Intialize CCTLib
PinCCTLibInit(INTERESTING_INS_MEMORY_ACCESS, gTraceFile, InstrumentInsCallback, 0);
// fini function for post-mortem analysis
PIN_AddThreadFiniFunction(ThreadFiniFunc, 0);
PIN_AddFiniFunction(FiniFunc, 0);
// Launch program now
PIN_StartProgram();
return 0;
}
<commit_msg>fix glitches<commit_after>// * BeginRiceCopyright *****************************************************
//
// Copyright ((c)) 2002-2014, Rice University
// 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 Rice University (RICE) 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 RICE 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 RICE 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.
//
// ******************************************************* EndRiceCopyright *
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <iostream>
#include <unistd.h>
#include <assert.h>
#include <string.h>
#include <sstream>
#include "pin.H"
#include "cctlib.H"
using namespace std;
using namespace PinCCTLib;
#include <unordered_set>
#include <vector>
#include <unordered_map>
#include <algorithm>
#define MAX_FOOTPRINT_CONTEXTS_TO_LOG (1000)
struct node_metric_t {
unordered_set<void *> addressSet;
uint64_t accessNum;
};
struct sort_format_t {
ContextHandle_t handle;
uint64_t footprint;
uint64_t accessNum;
};
unordered_map<THREADID, unordered_map<uint32_t, struct node_metric_t>> hmap_vector;
INT32 Usage2() {
PIN_ERROR("Pin tool to gather calling context on each load and store.\n" + KNOB_BASE::StringKnobSummary() + "\n");
return -1;
}
// Main for DeadSpy, initialize the tool, register instrumentation functions and call the target program.
FILE* gTraceFile;
// Initialized the needed data structures before launching the target program
void ClientInit(int argc, char* argv[]) {
// Create output file
char name[MAX_FILE_PATH] = "client.out.";
char* envPath = getenv("CCTLIB_CLIENT_OUTPUT_FILE");
if(envPath) {
// assumes max of MAX_FILE_PATH
strcpy(name, envPath);
}
gethostname(name + strlen(name), MAX_FILE_PATH - strlen(name));
pid_t pid = getpid();
sprintf(name + strlen(name), "%d", pid);
cerr << "\n Creating log file at:" << name << "\n";
gTraceFile = fopen(name, "w");
// print the arguments passed
fprintf(gTraceFile, "\n");
for(int i = 0 ; i < argc; i++) {
fprintf(gTraceFile, "%s ", argv[i]);
}
fprintf(gTraceFile, "\n");
}
VOID MemFunc(THREADID id, void* addr) {
// at memory instruction record the footprint
void **metric = GetIPNodeMetric(id, 0);
if (*metric == NULL) {
// use ctxthndl as the key to associate footprint with the trace
ContextHandle_t ctxthndl = GetContextHandle(id, 0);
*metric = &(hmap_vector[id])[ctxthndl];
(hmap_vector[id])[ctxthndl].addressSet.insert(addr);
(hmap_vector[id])[ctxthndl].accessNum++;
}
else {
(static_cast<struct node_metric_t*>(*metric))->addressSet.insert(addr);
(static_cast<struct node_metric_t*>(*metric))->accessNum++;
}
}
VOID InstrumentInsCallback(INS ins, VOID* v, const uint32_t slot) {
if (!INS_IsMemoryRead(ins) && !INS_IsMemoryWrite(ins)) return;
if (INS_IsStackRead(ins) || INS_IsStackWrite(ins)) return;
if (INS_IsBranchOrCall(ins) || INS_IsRet(ins)) return;
UINT32 memOperands = INS_MemoryOperandCount(ins);
for (UINT32 memOp = 0; memOp < memOperands; memOp++)
{
INS_InsertPredicatedCall(ins, IPOINT_BEFORE, (AFUNPTR)MemFunc, IARG_THREAD_ID, IARG_MEMORYOP_EA, memOp, IARG_END);
}
}
void MergeFootPrint(const THREADID threadid, ContextHandle_t myHandle, ContextHandle_t parentHandle, void **myMetric, void **parentMetric)
{
if (*myMetric == NULL) return;
struct node_metric_t *hset = static_cast<struct node_metric_t*>(*myMetric);
if (*parentMetric == NULL) {
*parentMetric = &((hmap_vector[threadid])[parentHandle]);
(hmap_vector[threadid])[parentHandle].addressSet.insert(hset->addressSet.begin(), hset->addressSet.end());
(hmap_vector[threadid])[parentHandle].accessNum += hset->accessNum;
}
else {
(static_cast<struct node_metric_t*>(*parentMetric))->addressSet.insert(hset->addressSet.begin(), hset->addressSet.end());
(static_cast<struct node_metric_t*>(*parentMetric))->accessNum += hset->accessNum;
}
}
inline bool FootPrintCompare(const struct sort_format_t &first, const struct sort_format_t &second)
{
return first.footprint > second.footprint ? true : false;
}
void PrintTopFootPrintPath(THREADID threadid)
{
uint64_t cntxtNum = 0;
vector<struct sort_format_t> TmpList;
fprintf(gTraceFile, "*************** Dump Data from Thread %d ****************\n", threadid);
unordered_map<uint32_t, struct node_metric_t> &hmap = hmap_vector[threadid];
unordered_map<uint32_t, struct node_metric_t>::iterator it;
for (it = hmap.begin(); it != hmap.end(); ++it) {
struct sort_format_t tmp;
tmp.handle = (*it).first;
tmp.footprint = (uint64_t)(*it).second.addressSet.size();
tmp.accessNum = (uint64_t)(*it).second.accessNum;
TmpList.emplace_back(tmp);
}
sort(TmpList.begin(), TmpList.end(), FootPrintCompare);
vector<struct sort_format_t>::iterator ListIt;
for (ListIt = TmpList.begin(); ListIt != TmpList.end(); ++ListIt) {
if (cntxtNum < MAX_FOOTPRINT_CONTEXTS_TO_LOG) {
fprintf(gTraceFile, "Footprint is %lu, #access is %lu, context is:", (*ListIt).footprint, (*ListIt).accessNum);
PrintFullCallingContext((*ListIt).handle);
fprintf(gTraceFile, "\n------------------------------------------------\n");
}
else {
break;
}
cntxtNum++;
}
}
VOID ThreadFiniFunc(THREADID threadid, const CONTEXT *ctxt, INT32 code, VOID *v)
{
// traverse CCT bottom to up
TraverseCCTBottomUp(threadid, MergeFootPrint);
// print the footprint for functions
PIN_LockClient();
PrintTopFootPrintPath(threadid);
PIN_UnlockClient();
}
VOID FiniFunc(INT32 code, VOID *v)
{
// do whatever you want to the full CCT with footpirnt
}
int main(int argc, char* argv[]) {
// Initialize PIN
if(PIN_Init(argc, argv))
return Usage2();
// Initialize Symbols, we need them to report functions and lines
PIN_InitSymbols();
// Init Client
ClientInit(argc, argv);
// Intialize CCTLib
PinCCTLibInit(INTERESTING_INS_MEMORY_ACCESS, gTraceFile, InstrumentInsCallback, 0);
// fini function for post-mortem analysis
PIN_AddThreadFiniFunction(ThreadFiniFunc, 0);
PIN_AddFiniFunction(FiniFunc, 0);
// Launch program now
PIN_StartProgram();
return 0;
}
<|endoftext|> |
<commit_before>//
// Author: NagaChaitanya Vellanki
//
#include <GLFW/glfw3.h>
#include <iostream>
#include <string>
static float LINE_LENGTH = 6.0f;
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) {
glfwSetWindowShouldClose(window, GL_TRUE);
}
}
// variables : A B
// constants : + −
// start : A
// rules : (A → B−A−B), (B → A+B+A)
// angle : 60°
// A, B move forward
// + turn left by 60 degrees
// - turn right by 60 degrees
static std::string current("A");
static int generation = 0;
void lSystemRepresentation() {
while(generation < 8) {
std::string next;
for(std::string::iterator it = current.begin(); it != current.end(); it++) {
switch(*it) {
case 'A':
next.append("B-A-B");
break;
case 'B':
next.append("A+B+A");
break;
case '-':
next.append("-");
break;
case '+':
next.append("+");
break;
};
}
current = next;
generation++;
//std::cout << "Generation: " << generation++ << " " << current << std::endl;
}
}
int main(int argc, char *argv[]) {
GLFWwindow* window;
if(!glfwInit()) {
return -1;
}
GLFWmonitor* monitor = glfwGetPrimaryMonitor();
const GLFWvidmode* vidmode = glfwGetVideoMode(monitor);
window = glfwCreateWindow(vidmode->width, vidmode->height, "Sierpinski Triangle", monitor, NULL);
if(!window) {
glfwTerminate();
return -1;
}
glfwSetKeyCallback(window, key_callback);
glfwMakeContextCurrent(window);
int width, height;
glfwGetFramebufferSize(window, &width, &height);
float x = 0.0f;
float y = 0.0f;
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0f, width, 0.0f, height, 0.0, 1.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
lSystemRepresentation();
while(!glfwWindowShouldClose(window)) {
x = width / 4;
y = 0.0f;
glClear(GL_COLOR_BUFFER_BIT);
glPushMatrix();
for(std::string::iterator it = current.begin(); it != current.end(); it++) {
if(*it == 'A' || *it == 'B') {
glColor4f(0.5f, 1.0f, 0.0f, 1.0f);
glLineWidth(2.0f);
glBegin(GL_LINES);
glVertex2f(x, y);
x = x + LINE_LENGTH;
glVertex2f(x, y);
glEnd();
}
if(*it == '-' || *it == '+') {
glTranslatef(x, y, 0.0f);
x = 0.0f;
y = 0.0f;
float angle = ((*it == '-') ? -60.0f : 60.0f);
glRotatef(angle, 0.0f, 0.0f, 1.0f);
}
}
glPopMatrix();
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwTerminate();
return 0;
}
<commit_msg>Change line width<commit_after>//
// Author: NagaChaitanya Vellanki
//
#include <GLFW/glfw3.h>
#include <iostream>
#include <string>
static float LINE_LENGTH = 6.0f;
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) {
glfwSetWindowShouldClose(window, GL_TRUE);
}
}
// variables : A B
// constants : + −
// start : A
// rules : (A → B−A−B), (B → A+B+A)
// angle : 60°
// A, B move forward
// + turn left by 60 degrees
// - turn right by 60 degrees
static std::string current("A");
static int generation = 0;
void lSystemRepresentation() {
while(generation < 8) {
std::string next;
for(std::string::iterator it = current.begin(); it != current.end(); it++) {
switch(*it) {
case 'A':
next.append("B-A-B");
break;
case 'B':
next.append("A+B+A");
break;
case '-':
next.append("-");
break;
case '+':
next.append("+");
break;
};
}
current = next;
generation++;
//std::cout << "Generation: " << generation++ << " " << current << std::endl;
}
}
int main(int argc, char *argv[]) {
GLFWwindow* window;
if(!glfwInit()) {
return -1;
}
GLFWmonitor* monitor = glfwGetPrimaryMonitor();
const GLFWvidmode* vidmode = glfwGetVideoMode(monitor);
window = glfwCreateWindow(vidmode->width, vidmode->height, "Sierpinski Triangle", monitor, NULL);
if(!window) {
glfwTerminate();
return -1;
}
glfwSetKeyCallback(window, key_callback);
glfwMakeContextCurrent(window);
int width, height;
glfwGetFramebufferSize(window, &width, &height);
float x = 0.0f;
float y = 0.0f;
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0f, width, 0.0f, height, 0.0, 1.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
lSystemRepresentation();
while(!glfwWindowShouldClose(window)) {
x = width / 4;
y = 0.0f;
glClear(GL_COLOR_BUFFER_BIT);
glPushMatrix();
for(std::string::iterator it = current.begin(); it != current.end(); it++) {
if(*it == 'A' || *it == 'B') {
glColor4f(0.5f, 1.0f, 0.0f, 1.0f);
glLineWidth(4.0f);
glBegin(GL_LINES);
glVertex2f(x, y);
x = x + LINE_LENGTH;
glVertex2f(x, y);
glEnd();
}
if(*it == '-' || *it == '+') {
glTranslatef(x, y, 0.0f);
x = 0.0f;
y = 0.0f;
float angle = ((*it == '-') ? -60.0f : 60.0f);
glRotatef(angle, 0.0f, 0.0f, 1.0f);
}
}
glPopMatrix();
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwTerminate();
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>unused include<commit_after><|endoftext|> |
<commit_before>/****************************************************************************
* Copyright (C) 2012-2016 by Savoir-faire Linux *
* Author : Emmanuel Lepage Vallee <emmanuel.lepage@savoirfairelinux.com> *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2.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 General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
***************************************************************************/
#include "availableaccountmodel.h"
//Qt
#include <QtCore/QItemSelectionModel>
#include <QtCore/QCoreApplication>
//DRing
#include <account_const.h>
//Ring
#include "contactmethod.h"
#include "uri.h"
class AvailableAccountModelPrivate final : public QObject
{
Q_OBJECT
public:
AvailableAccountModelPrivate(AvailableAccountModel* parent);
QItemSelectionModel* m_pSelectionModel;
static Account* m_spPriorAccount ;
static void setPriorAccount ( const Account* account );
static Account* firstRegisteredAccount( URI::SchemeType type = URI::SchemeType::NONE );
AvailableAccountModel* q_ptr;
public Q_SLOTS:
void checkRemovedAccount(Account* a);
void checkStateChanges(Account* account, const Account::RegistrationState state);
void selectionChanged(const QModelIndex& idx, const QModelIndex& previous);
};
Account* AvailableAccountModelPrivate::m_spPriorAccount = nullptr;
AvailableAccountModelPrivate::AvailableAccountModelPrivate(AvailableAccountModel* parent) :m_pSelectionModel(nullptr),q_ptr(parent)
{
connect(&AccountModel::instance(), &AccountModel::accountRemoved , this, &AvailableAccountModelPrivate::checkRemovedAccount );
connect(&AccountModel::instance(), &AccountModel::accountStateChanged, this, &AvailableAccountModelPrivate::checkStateChanges );
}
AvailableAccountModel::AvailableAccountModel(QObject* parent) : QSortFilterProxyModel(parent),
d_ptr(new AvailableAccountModelPrivate(this))
{
setSourceModel(&AccountModel::instance());
}
AvailableAccountModel::~AvailableAccountModel()
{
delete d_ptr;
}
AvailableAccountModel& AvailableAccountModel::instance()
{
static auto instance = new AvailableAccountModel(QCoreApplication::instance());
return *instance;
}
//Do not show the checkbox
QVariant AvailableAccountModel::data(const QModelIndex& idx,int role ) const
{
return (role == Qt::CheckStateRole) ? QVariant() : mapToSource(idx).data(role);
}
///Disable the unavailable accounts
Qt::ItemFlags AvailableAccountModel::flags (const QModelIndex& idx) const
{
const QModelIndex& src = mapToSource(idx);
if (qvariant_cast<Account::RegistrationState>(src.data(static_cast<int>(Account::Role::RegistrationState))) != Account::RegistrationState::READY)
return Qt::NoItemFlags;
return sourceModel()->flags(idx);
}
//Do not display disabled account
bool AvailableAccountModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const
{
return sourceModel()->index(source_row,0,source_parent).data(Qt::CheckStateRole) == Qt::Checked;
}
///Return the current account
Account* AvailableAccountModel::currentDefaultAccount(ContactMethod* method)
{
// Start by validating the scheme used by the ContactMethod
URI::SchemeType type = (!method) ? URI::SchemeType::NONE : method->uri().schemeType();
// If the scheme type could not be strictly determined, try using the protocol hint
if (type == URI::SchemeType::NONE && method) {
switch (method->protocolHint()) {
case URI::ProtocolHint::SIP_OTHER:
case URI::ProtocolHint::SIP_HOST:
type = URI::SchemeType::SIP;
break;
case URI::ProtocolHint::IP:
break;
case URI::ProtocolHint::RING:
case URI::ProtocolHint::RING_USERNAME:
type = URI::SchemeType::RING;
break;
}
}
return currentDefaultAccount(type);
} //currentDefaultAccount
/// Validation method to check if the account is in a good state and support the scheme provided
bool AvailableAccountModel::validAccountForScheme(Account* account, URI::SchemeType scheme)
{
return (account
&& account->registrationState() == Account::RegistrationState::READY
&& account->isEnabled()
&& (account->supportScheme(scheme)));
}
Account* AvailableAccountModel::currentDefaultAccount(URI::SchemeType schemeType)
{
// Always try to respect user choice
auto userChosenAccount = AccountModel::instance().userChosenAccount();
if (userChosenAccount && validAccountForScheme(userChosenAccount, schemeType)) {
return userChosenAccount;
}
// If the current selected choice is not valid, try the previous account selected
auto priorAccount = AvailableAccountModelPrivate::m_spPriorAccount;
//we prefer not to use Ip2Ip if possible
if (priorAccount && priorAccount->isIp2ip()) {
priorAccount = nullptr;
}
if(validAccountForScheme(priorAccount, schemeType)) {
return priorAccount;
} else {
auto account = AvailableAccountModelPrivate::firstRegisteredAccount(schemeType);
AvailableAccountModelPrivate::setPriorAccount(account);
return account;
}
}
///Set the previous account used
void AvailableAccountModelPrivate::setPriorAccount(const Account* account)
{
const bool changed = (account && m_spPriorAccount != account) || (!account && m_spPriorAccount);
m_spPriorAccount = const_cast<Account*>(account);
if (changed) {
auto& self = AvailableAccountModel::instance();
Account* a = account ? const_cast<Account*>(account) : self.currentDefaultAccount();
emit self.currentDefaultAccountChanged(a);
if (self.d_ptr->m_pSelectionModel) {
const QModelIndex idx = self.mapFromSource(a->index());
if (idx.isValid())
self.d_ptr->m_pSelectionModel->setCurrentIndex(self.mapFromSource(a->index()), QItemSelectionModel::ClearAndSelect);
else
self.d_ptr->m_pSelectionModel->clearSelection();
}
}
}
///Get the first registerred account (default account)
Account* AvailableAccountModelPrivate::firstRegisteredAccount(URI::SchemeType type)
{
return AccountModel::instance().findAccountIf([&type](const Account& account) {
return account.registrationState() == Account::RegistrationState::READY
&& account.isEnabled()
&& account.supportScheme(type);
});
}
QItemSelectionModel* AvailableAccountModel::selectionModel() const
{
if (!d_ptr->m_pSelectionModel) {
d_ptr->m_pSelectionModel = new QItemSelectionModel(const_cast<AvailableAccountModel*>(this));
connect(d_ptr->m_pSelectionModel, &QItemSelectionModel::currentChanged,d_ptr,&AvailableAccountModelPrivate::selectionChanged);
Account* a = d_ptr->firstRegisteredAccount();
if (a)
d_ptr->m_pSelectionModel->setCurrentIndex(mapFromSource(a->index()), QItemSelectionModel::ClearAndSelect);
}
return d_ptr->m_pSelectionModel;
}
void AvailableAccountModelPrivate::selectionChanged(const QModelIndex& idx, const QModelIndex& previous)
{
Q_UNUSED(previous)
Account* a = qvariant_cast<Account*>(idx.data(static_cast<int>(Account::Role::Object)));
setPriorAccount(a);
}
void AvailableAccountModelPrivate::checkRemovedAccount(Account* a)
{
if (a == m_spPriorAccount) {
Account* a2 = firstRegisteredAccount();
qDebug() << "The current default account has been removed, now defaulting to" << a2;
setPriorAccount(a2);
}
}
void AvailableAccountModelPrivate::checkStateChanges(Account* account, const Account::RegistrationState state)
{
Q_UNUSED(account)
Q_UNUSED(state)
Account* a = firstRegisteredAccount();
if ( m_spPriorAccount != a ) {
qDebug() << "The current default account changed to" << a;
setPriorAccount(a);
}
}
#include <availableaccountmodel.moc>
<commit_msg>availableAccount: Fallback to RING account when nothing else exists<commit_after>/****************************************************************************
* Copyright (C) 2012-2016 by Savoir-faire Linux *
* Author : Emmanuel Lepage Vallee <emmanuel.lepage@savoirfairelinux.com> *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2.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 General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
***************************************************************************/
#include "availableaccountmodel.h"
//Qt
#include <QtCore/QItemSelectionModel>
#include <QtCore/QCoreApplication>
//DRing
#include <account_const.h>
//Ring
#include "contactmethod.h"
#include "uri.h"
class AvailableAccountModelPrivate final : public QObject
{
Q_OBJECT
public:
AvailableAccountModelPrivate(AvailableAccountModel* parent);
QItemSelectionModel* m_pSelectionModel;
static Account* m_spPriorAccount ;
static void setPriorAccount ( const Account* account );
static Account* firstRegisteredAccount( URI::SchemeType type = URI::SchemeType::NONE );
AvailableAccountModel* q_ptr;
public Q_SLOTS:
void checkRemovedAccount(Account* a);
void checkStateChanges(Account* account, const Account::RegistrationState state);
void selectionChanged(const QModelIndex& idx, const QModelIndex& previous);
};
Account* AvailableAccountModelPrivate::m_spPriorAccount = nullptr;
AvailableAccountModelPrivate::AvailableAccountModelPrivate(AvailableAccountModel* parent) :m_pSelectionModel(nullptr),q_ptr(parent)
{
connect(&AccountModel::instance(), &AccountModel::accountRemoved , this, &AvailableAccountModelPrivate::checkRemovedAccount );
connect(&AccountModel::instance(), &AccountModel::accountStateChanged, this, &AvailableAccountModelPrivate::checkStateChanges );
}
AvailableAccountModel::AvailableAccountModel(QObject* parent) : QSortFilterProxyModel(parent),
d_ptr(new AvailableAccountModelPrivate(this))
{
setSourceModel(&AccountModel::instance());
}
AvailableAccountModel::~AvailableAccountModel()
{
delete d_ptr;
}
AvailableAccountModel& AvailableAccountModel::instance()
{
static auto instance = new AvailableAccountModel(QCoreApplication::instance());
return *instance;
}
//Do not show the checkbox
QVariant AvailableAccountModel::data(const QModelIndex& idx,int role ) const
{
return (role == Qt::CheckStateRole) ? QVariant() : mapToSource(idx).data(role);
}
///Disable the unavailable accounts
Qt::ItemFlags AvailableAccountModel::flags (const QModelIndex& idx) const
{
const QModelIndex& src = mapToSource(idx);
if (qvariant_cast<Account::RegistrationState>(src.data(static_cast<int>(Account::Role::RegistrationState))) != Account::RegistrationState::READY)
return Qt::NoItemFlags;
return sourceModel()->flags(idx);
}
//Do not display disabled account
bool AvailableAccountModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const
{
return sourceModel()->index(source_row,0,source_parent).data(Qt::CheckStateRole) == Qt::Checked;
}
///Return the current account
Account* AvailableAccountModel::currentDefaultAccount(ContactMethod* method)
{
// Start by validating the scheme used by the ContactMethod
URI::SchemeType type = (!method) ? URI::SchemeType::NONE : method->uri().schemeType();
// If the scheme type could not be strictly determined, try using the protocol hint
if (type == URI::SchemeType::NONE && method) {
switch (method->protocolHint()) {
case URI::ProtocolHint::SIP_OTHER:
case URI::ProtocolHint::SIP_HOST:
type = URI::SchemeType::SIP;
break;
case URI::ProtocolHint::IP:
break;
case URI::ProtocolHint::RING:
case URI::ProtocolHint::RING_USERNAME:
type = URI::SchemeType::RING;
break;
}
}
return currentDefaultAccount(type);
} //currentDefaultAccount
/// Validation method to check if the account is in a good state and support the scheme provided
bool AvailableAccountModel::validAccountForScheme(Account* account, URI::SchemeType scheme)
{
return (account
&& account->registrationState() == Account::RegistrationState::READY
&& account->isEnabled()
&& (account->supportScheme(scheme)));
}
Account* AvailableAccountModel::currentDefaultAccount(URI::SchemeType schemeType)
{
// Always try to respect user choice
auto userChosenAccount = AccountModel::instance().userChosenAccount();
if (userChosenAccount && validAccountForScheme(userChosenAccount, schemeType)) {
return userChosenAccount;
}
// If the current selected choice is not valid, try the previous account selected
auto priorAccount = AvailableAccountModelPrivate::m_spPriorAccount;
//we prefer not to use Ip2Ip if possible
if (priorAccount && priorAccount->isIp2ip()) {
priorAccount = nullptr;
}
if(validAccountForScheme(priorAccount, schemeType)) {
return priorAccount;
} else {
auto account = AvailableAccountModelPrivate::firstRegisteredAccount(schemeType);
// If there is only RING account, it will still be nullptr. Given there is
// *only* RING accounts, then the user probably want a call using the
// Ring protocol. This will happen when using the name directory instead
// of the hash
if (!account)
account = AvailableAccountModelPrivate::firstRegisteredAccount(
URI::SchemeType::RING
);
AvailableAccountModelPrivate::setPriorAccount(account);
return account;
}
}
///Set the previous account used
void AvailableAccountModelPrivate::setPriorAccount(const Account* account)
{
const bool changed = (account && m_spPriorAccount != account) || (!account && m_spPriorAccount);
m_spPriorAccount = const_cast<Account*>(account);
if (changed) {
auto& self = AvailableAccountModel::instance();
Account* a = account ? const_cast<Account*>(account) : self.currentDefaultAccount();
emit self.currentDefaultAccountChanged(a);
if (self.d_ptr->m_pSelectionModel) {
const QModelIndex idx = self.mapFromSource(a->index());
if (idx.isValid())
self.d_ptr->m_pSelectionModel->setCurrentIndex(self.mapFromSource(a->index()), QItemSelectionModel::ClearAndSelect);
else
self.d_ptr->m_pSelectionModel->clearSelection();
}
}
}
///Get the first registerred account (default account)
Account* AvailableAccountModelPrivate::firstRegisteredAccount(URI::SchemeType type)
{
return AccountModel::instance().findAccountIf([&type](const Account& account) {
return account.registrationState() == Account::RegistrationState::READY
&& account.isEnabled()
&& account.supportScheme(type);
});
}
QItemSelectionModel* AvailableAccountModel::selectionModel() const
{
if (!d_ptr->m_pSelectionModel) {
d_ptr->m_pSelectionModel = new QItemSelectionModel(const_cast<AvailableAccountModel*>(this));
connect(d_ptr->m_pSelectionModel, &QItemSelectionModel::currentChanged,d_ptr,&AvailableAccountModelPrivate::selectionChanged);
Account* a = d_ptr->firstRegisteredAccount();
if (a)
d_ptr->m_pSelectionModel->setCurrentIndex(mapFromSource(a->index()), QItemSelectionModel::ClearAndSelect);
}
return d_ptr->m_pSelectionModel;
}
void AvailableAccountModelPrivate::selectionChanged(const QModelIndex& idx, const QModelIndex& previous)
{
Q_UNUSED(previous)
Account* a = qvariant_cast<Account*>(idx.data(static_cast<int>(Account::Role::Object)));
setPriorAccount(a);
}
void AvailableAccountModelPrivate::checkRemovedAccount(Account* a)
{
if (a == m_spPriorAccount) {
Account* a2 = firstRegisteredAccount();
qDebug() << "The current default account has been removed, now defaulting to" << a2;
setPriorAccount(a2);
}
}
void AvailableAccountModelPrivate::checkStateChanges(Account* account, const Account::RegistrationState state)
{
Q_UNUSED(account)
Q_UNUSED(state)
Account* a = firstRegisteredAccount();
if ( m_spPriorAccount != a ) {
qDebug() << "The current default account changed to" << a;
setPriorAccount(a);
}
}
#include <availableaccountmodel.moc>
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: BIndexes.cxx,v $
*
* $Revision: 1.21 $
*
* last change: $Author: hr $ $Date: 2006-06-20 01:09:21 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _CONNECTIVITY_ADABAS_INDEXES_HXX_
#include "adabas/BIndexes.hxx"
#endif
#ifndef _CONNECTIVITY_ADABAS_INDEX_HXX_
#include "adabas/BIndex.hxx"
#endif
#ifndef _CONNECTIVITY_ADABAS_TABLE_HXX_
#include "adabas/BTable.hxx"
#endif
#ifndef _CONNECTIVITY_SDBCX_INDEX_HXX_
#include "connectivity/sdbcx/VIndex.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_INDEXTYPE_HPP_
#include <com/sun/star/sdbc/IndexType.hpp>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _CONNECTIVITY_ADABAS_CATALOG_HXX_
#include "adabas/BCatalog.hxx"
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include "connectivity/dbexception.hxx"
#endif
using namespace ::comphelper;
using namespace connectivity;
using namespace connectivity::adabas;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
typedef connectivity::sdbcx::OCollection OCollection_TYPE;
sdbcx::ObjectType OIndexes::createObject(const ::rtl::OUString& _rName)
{
::rtl::OUString aName,aQualifier;
sal_Int32 nLen = _rName.indexOf('.');
if(nLen != -1)
{
aQualifier = _rName.copy(0,nLen);
aName = _rName.copy(nLen+1);
}
else
aName = _rName;
Reference< XResultSet > xResult = m_pTable->getMetaData()->getIndexInfo(Any(),
m_pTable->getSchema(),m_pTable->getTableName(),sal_False,sal_False);
sdbcx::ObjectType xRet = NULL;
if(xResult.is())
{
Reference< XRow > xRow(xResult,UNO_QUERY);
while(xResult->next())
{
if(xRow->getString(6) == aName && (!aQualifier.getLength() || xRow->getString(5) == aQualifier ))
{
OAdabasIndex* pRet = new OAdabasIndex(m_pTable,aName,aQualifier,!xRow->getBoolean(4),
aName == ::rtl::OUString::createFromAscii("SYSPRIMARYKEYINDEX"),
xRow->getShort(7) == IndexType::CLUSTERED);
xRet = pRet;
break;
}
}
::comphelper::disposeComponent(xResult);
}
return xRet;
}
// -------------------------------------------------------------------------
void OIndexes::impl_refresh() throw(RuntimeException)
{
m_pTable->refreshIndexes();
}
// -------------------------------------------------------------------------
Reference< XPropertySet > OIndexes::createEmptyObject()
{
return new OAdabasIndex(m_pTable);
}
// -------------------------------------------------------------------------
sdbcx::ObjectType OIndexes::cloneObject(const Reference< XPropertySet >& _xDescriptor)
{
sdbcx::ObjectType xName;
if(!m_pTable->isNew())
{
xName = OCollection_TYPE::cloneObject(_xDescriptor);
}
return xName;
}
// -------------------------------------------------------------------------
// XAppend
void OIndexes::appendObject( const Reference< XPropertySet >& descriptor )
{
::rtl::OUString aName = getString(descriptor->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME)));
if(!m_pTable->isNew())
{
::rtl::OUString aSql = ::rtl::OUString::createFromAscii("CREATE ");
::rtl::OUString aQuote = m_pTable->getMetaData()->getIdentifierQuoteString( );
const ::rtl::OUString& sDot = OAdabasCatalog::getDot();
if(getBOOL(descriptor->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISUNIQUE))))
aSql = aSql + ::rtl::OUString::createFromAscii("UNIQUE ");
aSql = aSql + ::rtl::OUString::createFromAscii("INDEX ");
if(aName.getLength())
{
aSql = aSql + aQuote + aName + aQuote
+ ::rtl::OUString::createFromAscii(" ON ")
+ aQuote + m_pTable->getSchema() + aQuote + sDot
+ aQuote + m_pTable->getTableName() + aQuote
+ ::rtl::OUString::createFromAscii(" ( ");
Reference<XColumnsSupplier> xColumnSup(descriptor,UNO_QUERY);
Reference<XIndexAccess> xColumns(xColumnSup->getColumns(),UNO_QUERY);
Reference< XPropertySet > xColProp;
sal_Int32 nCount = xColumns->getCount();
for(sal_Int32 i=0;i<nCount;++i)
{
xColumns->getByIndex(i) >>= xColProp;
aSql = aSql + aQuote + getString(xColProp->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME))) + aQuote;
aSql = aSql + (getBOOL(xColProp->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISASCENDING)))
?
::rtl::OUString::createFromAscii(" ASC")
:
::rtl::OUString::createFromAscii(" DESC"))
+ ::rtl::OUString::createFromAscii(",");
}
aSql = aSql.replaceAt(aSql.getLength()-1,1,::rtl::OUString::createFromAscii(")"));
}
else
{
aSql = aSql + aQuote + m_pTable->getSchema() + aQuote + sDot + aQuote + m_pTable->getTableName() + aQuote;
Reference<XColumnsSupplier> xColumnSup(descriptor,UNO_QUERY);
Reference<XIndexAccess> xColumns(xColumnSup->getColumns(),UNO_QUERY);
Reference< XPropertySet > xColProp;
if(xColumns->getCount() != 1)
throw SQLException();
xColumns->getByIndex(0) >>= xColProp;
aSql = aSql + sDot + aQuote + getString(xColProp->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME))) + aQuote;
}
Reference< XStatement > xStmt = m_pTable->getConnection()->createStatement( );
xStmt->execute(aSql);
::comphelper::disposeComponent(xStmt);
}
else
::dbtools::throwFunctionSequenceException(static_cast<XTypeProvider*>(this));
}
// -------------------------------------------------------------------------
// XDrop
void OIndexes::dropObject(sal_Int32 /*_nPos*/,const ::rtl::OUString _sElementName)
{
if(!m_pTable->isNew())
{
::rtl::OUString aName,aSchema;
sal_Int32 nLen = _sElementName.indexOf('.');
aSchema = _sElementName.copy(0,nLen);
aName = _sElementName.copy(nLen+1);
::rtl::OUString aSql = ::rtl::OUString::createFromAscii("DROP INDEX ");
::rtl::OUString aQuote = m_pTable->getMetaData()->getIdentifierQuoteString( );
const ::rtl::OUString& sDot = OAdabasCatalog::getDot();
if (aSchema.getLength())
(((aSql += aQuote) += aSchema) += aQuote) += sDot;
(((aSql += aQuote) += aName) += aQuote) += ::rtl::OUString::createFromAscii(" ON ");
(((aSql += aQuote) += m_pTable->getSchema()) += aQuote) += sDot;
((aSql += aQuote) += m_pTable->getTableName()) += aQuote;
Reference< XStatement > xStmt = m_pTable->getConnection()->createStatement( );
xStmt->execute(aSql);
::comphelper::disposeComponent(xStmt);
}
}
// -------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS qiq (1.20.104); FILE MERGED 2006/06/27 14:03:30 fs 1.20.104.2: RESYNC: (1.20-1.21); FILE MERGED 2006/06/16 11:32:30 fs 1.20.104.1: during #i51143#:<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: BIndexes.cxx,v $
*
* $Revision: 1.22 $
*
* last change: $Author: obo $ $Date: 2006-07-10 14:22:04 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _CONNECTIVITY_ADABAS_INDEXES_HXX_
#include "adabas/BIndexes.hxx"
#endif
#ifndef _CONNECTIVITY_ADABAS_INDEX_HXX_
#include "adabas/BIndex.hxx"
#endif
#ifndef _CONNECTIVITY_ADABAS_TABLE_HXX_
#include "adabas/BTable.hxx"
#endif
#ifndef _CONNECTIVITY_SDBCX_INDEX_HXX_
#include "connectivity/sdbcx/VIndex.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_INDEXTYPE_HPP_
#include <com/sun/star/sdbc/IndexType.hpp>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _CONNECTIVITY_ADABAS_CATALOG_HXX_
#include "adabas/BCatalog.hxx"
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include "connectivity/dbexception.hxx"
#endif
using namespace ::comphelper;
using namespace connectivity;
using namespace connectivity::adabas;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
typedef connectivity::sdbcx::OCollection OCollection_TYPE;
sdbcx::ObjectType OIndexes::createObject(const ::rtl::OUString& _rName)
{
::rtl::OUString aName,aQualifier;
sal_Int32 nLen = _rName.indexOf('.');
if(nLen != -1)
{
aQualifier = _rName.copy(0,nLen);
aName = _rName.copy(nLen+1);
}
else
aName = _rName;
Reference< XResultSet > xResult = m_pTable->getMetaData()->getIndexInfo(Any(),
m_pTable->getSchema(),m_pTable->getTableName(),sal_False,sal_False);
sdbcx::ObjectType xRet = NULL;
if(xResult.is())
{
Reference< XRow > xRow(xResult,UNO_QUERY);
while(xResult->next())
{
if(xRow->getString(6) == aName && (!aQualifier.getLength() || xRow->getString(5) == aQualifier ))
{
OAdabasIndex* pRet = new OAdabasIndex(m_pTable,aName,aQualifier,!xRow->getBoolean(4),
aName == ::rtl::OUString::createFromAscii("SYSPRIMARYKEYINDEX"),
xRow->getShort(7) == IndexType::CLUSTERED);
xRet = pRet;
break;
}
}
::comphelper::disposeComponent(xResult);
}
return xRet;
}
// -------------------------------------------------------------------------
void OIndexes::impl_refresh() throw(RuntimeException)
{
m_pTable->refreshIndexes();
}
// -------------------------------------------------------------------------
Reference< XPropertySet > OIndexes::createDescriptor()
{
return new OAdabasIndex(m_pTable);
}
// -------------------------------------------------------------------------
// XAppend
sdbcx::ObjectType OIndexes::appendObject( const ::rtl::OUString& _rForName, const Reference< XPropertySet >& descriptor )
{
if ( m_pTable->isNew() )
::dbtools::throwFunctionSequenceException(static_cast<XTypeProvider*>(this));
::rtl::OUString aSql = ::rtl::OUString::createFromAscii("CREATE ");
::rtl::OUString aQuote = m_pTable->getMetaData()->getIdentifierQuoteString( );
const ::rtl::OUString& sDot = OAdabasCatalog::getDot();
if(getBOOL(descriptor->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISUNIQUE))))
aSql = aSql + ::rtl::OUString::createFromAscii("UNIQUE ");
aSql = aSql + ::rtl::OUString::createFromAscii("INDEX ");
if(_rForName.getLength())
{
aSql = aSql + aQuote + _rForName + aQuote
+ ::rtl::OUString::createFromAscii(" ON ")
+ aQuote + m_pTable->getSchema() + aQuote + sDot
+ aQuote + m_pTable->getTableName() + aQuote
+ ::rtl::OUString::createFromAscii(" ( ");
Reference<XColumnsSupplier> xColumnSup(descriptor,UNO_QUERY);
Reference<XIndexAccess> xColumns(xColumnSup->getColumns(),UNO_QUERY);
Reference< XPropertySet > xColProp;
sal_Int32 nCount = xColumns->getCount();
for(sal_Int32 i=0;i<nCount;++i)
{
xColumns->getByIndex(i) >>= xColProp;
aSql = aSql + aQuote + getString(xColProp->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME))) + aQuote;
aSql = aSql + (getBOOL(xColProp->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_ISASCENDING)))
?
::rtl::OUString::createFromAscii(" ASC")
:
::rtl::OUString::createFromAscii(" DESC"))
+ ::rtl::OUString::createFromAscii(",");
}
aSql = aSql.replaceAt(aSql.getLength()-1,1,::rtl::OUString::createFromAscii(")"));
}
else
{
aSql = aSql + aQuote + m_pTable->getSchema() + aQuote + sDot + aQuote + m_pTable->getTableName() + aQuote;
Reference<XColumnsSupplier> xColumnSup(descriptor,UNO_QUERY);
Reference<XIndexAccess> xColumns(xColumnSup->getColumns(),UNO_QUERY);
Reference< XPropertySet > xColProp;
if(xColumns->getCount() != 1)
throw SQLException();
xColumns->getByIndex(0) >>= xColProp;
aSql = aSql + sDot + aQuote + getString(xColProp->getPropertyValue(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_NAME))) + aQuote;
}
Reference< XStatement > xStmt = m_pTable->getConnection()->createStatement( );
xStmt->execute(aSql);
::comphelper::disposeComponent(xStmt);
return createObject( _rForName );
}
// -------------------------------------------------------------------------
// XDrop
void OIndexes::dropObject(sal_Int32 /*_nPos*/,const ::rtl::OUString _sElementName)
{
if(!m_pTable->isNew())
{
::rtl::OUString aName,aSchema;
sal_Int32 nLen = _sElementName.indexOf('.');
aSchema = _sElementName.copy(0,nLen);
aName = _sElementName.copy(nLen+1);
::rtl::OUString aSql = ::rtl::OUString::createFromAscii("DROP INDEX ");
::rtl::OUString aQuote = m_pTable->getMetaData()->getIdentifierQuoteString( );
const ::rtl::OUString& sDot = OAdabasCatalog::getDot();
if (aSchema.getLength())
(((aSql += aQuote) += aSchema) += aQuote) += sDot;
(((aSql += aQuote) += aName) += aQuote) += ::rtl::OUString::createFromAscii(" ON ");
(((aSql += aQuote) += m_pTable->getSchema()) += aQuote) += sDot;
((aSql += aQuote) += m_pTable->getTableName()) += aQuote;
Reference< XStatement > xStmt = m_pTable->getConnection()->createStatement( );
xStmt->execute(aSql);
::comphelper::disposeComponent(xStmt);
}
}
// -------------------------------------------------------------------------
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: KConnection.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: obo $ $Date: 2006-09-17 02:51:42 $
*
* 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_connectivity.hxx"
#include "KConnection.hxx"
#ifndef _CONNECTIVITY_KAB_DATABASEMETADATA_HXX_
#include "KDatabaseMetaData.hxx"
#endif
#ifndef _CONNECTIVITY_KAB_STATEMENT_HXX_
#include "KStatement.hxx"
#endif
#ifndef _CONNECTIVITY_KAB_PREPAREDSTATEMENT_HXX_
#include "KPreparedStatement.hxx"
#endif
#ifndef _CONNECTIVITY_KAB_DRIVER_HXX_
#include "KDriver.hxx"
#endif
#ifndef _CONNECTIVITY_KAB_CATALOG_HXX_
#include "KCatalog.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_
#include <com/sun/star/sdbc/ColumnValue.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_TRANSACTIONISOLATION_HPP_
#include <com/sun/star/sdbc/TransactionIsolation.hpp>
#endif
#ifndef INCLUDED_VCL_KDE_HEADERS_H
#include <vcl/kde_headers.h>
#endif
using namespace connectivity::kab;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::sdbc;
using namespace com::sun::star::sdbcx;
IMPLEMENT_SERVICE_INFO(KabConnection, "com.sun.star.sdbc.drivers.KabConnection", "com.sun.star.sdbc.Connection")
//-----------------------------------------------------------------------------
KabConnection::KabConnection(KabDriver* _pDriver)
: OMetaConnection_BASE(m_aMutex),
OSubComponent<KabConnection, KabConnection_BASE>((::cppu::OWeakObject*)_pDriver, this),
m_xMetaData(NULL),
m_pAddressBook(NULL),
m_pDriver(_pDriver)
{
m_pDriver->acquire();
}
//-----------------------------------------------------------------------------
KabConnection::~KabConnection()
{
if (!isClosed())
close();
m_pDriver->release();
m_pDriver = NULL;
}
//-----------------------------------------------------------------------------
void SAL_CALL KabConnection::release() throw()
{
relase_ChildImpl();
}
// -----------------------------------------------------------------------------
void KabConnection::construct(const ::rtl::OUString&, const Sequence< PropertyValue >&) throw(SQLException)
{
osl_incrementInterlockedCount( &m_refCount );
// create a KDE address book object
m_pAddressBook = KABC::StdAddressBook::self();
m_pAddressBook->setAutomaticSave(false);
// perharps we should analyze the URL to know whether the addressbook is local, over LDAP, etc...
// perharps we should get some user and password information from "info" properties
osl_decrementInterlockedCount( &m_refCount );
}
// XServiceInfo
// --------------------------------------------------------------------------------
Reference< XStatement > SAL_CALL KabConnection::createStatement( ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(KabConnection_BASE::rBHelper.bDisposed);
// create a statement
// the statement can only be executed once
Reference< XStatement > xReturn = new KabStatement(this);
m_aStatements.push_back(WeakReferenceHelper(xReturn));
return xReturn;
}
// --------------------------------------------------------------------------------
Reference< XPreparedStatement > SAL_CALL KabConnection::prepareStatement( const ::rtl::OUString& _sSql ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(KabConnection_BASE::rBHelper.bDisposed);
// create a statement
// the statement can only be executed more than once
Reference< XPreparedStatement > xReturn = new KabPreparedStatement(this, _sSql);
m_aStatements.push_back(WeakReferenceHelper(xReturn));
return xReturn;
}
// --------------------------------------------------------------------------------
Reference< XPreparedStatement > SAL_CALL KabConnection::prepareCall( const ::rtl::OUString& ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(KabConnection_BASE::rBHelper.bDisposed);
// not implemented yet :-) a task to do
return NULL;
}
// --------------------------------------------------------------------------------
::rtl::OUString SAL_CALL KabConnection::nativeSQL( const ::rtl::OUString& _sSql ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
// when you need to transform SQL92 to you driver specific you can do it here
return _sSql;
}
// --------------------------------------------------------------------------------
void SAL_CALL KabConnection::setAutoCommit( sal_Bool ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(KabConnection_BASE::rBHelper.bDisposed);
// here you have to set your commit mode please have a look at the jdbc documentation to get a clear explanation
}
// --------------------------------------------------------------------------------
sal_Bool SAL_CALL KabConnection::getAutoCommit( ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(KabConnection_BASE::rBHelper.bDisposed);
// you have to distinguish which if you are in autocommit mode or not
// at normal case true should be fine here
return sal_True;
}
// --------------------------------------------------------------------------------
void SAL_CALL KabConnection::commit( ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(KabConnection_BASE::rBHelper.bDisposed);
// when you database does support transactions you should commit here
}
// --------------------------------------------------------------------------------
void SAL_CALL KabConnection::rollback( ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(KabConnection_BASE::rBHelper.bDisposed);
// same as commit but for the other case
}
// --------------------------------------------------------------------------------
sal_Bool SAL_CALL KabConnection::isClosed( ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
// just simple -> we are closed when we are disposed, that means someone called dispose(); (XComponent)
return KabConnection_BASE::rBHelper.bDisposed;
}
// --------------------------------------------------------------------------------
Reference< XDatabaseMetaData > SAL_CALL KabConnection::getMetaData( ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(KabConnection_BASE::rBHelper.bDisposed);
// here we have to create the class with biggest interface
// The answer is 42 :-)
Reference< XDatabaseMetaData > xMetaData = m_xMetaData;
if (!xMetaData.is())
{
xMetaData = new KabDatabaseMetaData(this); // need the connection because it can return it
m_xMetaData = xMetaData;
}
return xMetaData;
}
// --------------------------------------------------------------------------------
void SAL_CALL KabConnection::setReadOnly( sal_Bool ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(KabConnection_BASE::rBHelper.bDisposed);
// set you connection to readonly
}
// --------------------------------------------------------------------------------
sal_Bool SAL_CALL KabConnection::isReadOnly( ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(KabConnection_BASE::rBHelper.bDisposed);
// return if your connection to readonly
return sal_False;
}
// --------------------------------------------------------------------------------
void SAL_CALL KabConnection::setCatalog( const ::rtl::OUString& ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(KabConnection_BASE::rBHelper.bDisposed);
// if your database doesn't work with catalogs you go to next method otherwise you kjnow what to do
}
// --------------------------------------------------------------------------------
::rtl::OUString SAL_CALL KabConnection::getCatalog( ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(KabConnection_BASE::rBHelper.bDisposed);
// return your current catalog
return ::rtl::OUString();
}
// --------------------------------------------------------------------------------
void SAL_CALL KabConnection::setTransactionIsolation( sal_Int32 ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(KabConnection_BASE::rBHelper.bDisposed);
// set your isolation level
// please have a look at @see com.sun.star.sdbc.TransactionIsolation
}
// --------------------------------------------------------------------------------
sal_Int32 SAL_CALL KabConnection::getTransactionIsolation( ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(KabConnection_BASE::rBHelper.bDisposed);
// please have a look at @see com.sun.star.sdbc.TransactionIsolation
return TransactionIsolation::NONE;
}
// --------------------------------------------------------------------------------
Reference< ::com::sun::star::container::XNameAccess > SAL_CALL KabConnection::getTypeMap( ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(KabConnection_BASE::rBHelper.bDisposed);
// if your driver has special database types you can return it here
return NULL;
}
// --------------------------------------------------------------------------------
void SAL_CALL KabConnection::setTypeMap( const Reference< ::com::sun::star::container::XNameAccess >& ) throw(SQLException, RuntimeException)
{
// the other way around
}
// --------------------------------------------------------------------------------
// XCloseable
void SAL_CALL KabConnection::close( ) throw(SQLException, RuntimeException)
{
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(KabConnection_BASE::rBHelper.bDisposed);
}
dispose();
}
// --------------------------------------------------------------------------------
// XWarningsSupplier
Any SAL_CALL KabConnection::getWarnings( ) throw(SQLException, RuntimeException)
{
// when you collected some warnings -> return it
return Any();
}
// --------------------------------------------------------------------------------
void SAL_CALL KabConnection::clearWarnings( ) throw(SQLException, RuntimeException)
{
// you should clear your collected warnings here
}
//------------------------------------------------------------------------------
void KabConnection::disposing()
{
// we noticed that we should be destroied in near future so we have to dispose our statements
::osl::MutexGuard aGuard(m_aMutex);
for (OWeakRefArray::iterator i = m_aStatements.begin(); m_aStatements.end() != i; ++i)
{
Reference< XComponent > xComp(i->get(), UNO_QUERY);
if (xComp.is())
xComp->dispose();
}
m_aStatements.clear();
if (m_pAddressBook != NULL)
{
m_pAddressBook->close();
m_pAddressBook = NULL;
}
m_xMetaData = ::com::sun::star::uno::WeakReference< ::com::sun::star::sdbc::XDatabaseMetaData>();
dispose_ChildImpl();
KabConnection_BASE::disposing();
}
// -----------------------------------------------------------------------------
Reference< XTablesSupplier > SAL_CALL KabConnection::createCatalog()
{
::osl::MutexGuard aGuard( m_aMutex );
Reference< XTablesSupplier > xTab = m_xCatalog;
if (!m_xCatalog.is())
{
KabCatalog *pCat = new KabCatalog(this);
xTab = pCat;
m_xCatalog = xTab;
}
return xTab;
}
// -----------------------------------------------------------------------------
::KABC::AddressBook* KabConnection::getAddressBook() const
{
return m_pAddressBook;
}
// -----------------------------------------------------------------------------
extern "C" void* SAL_CALL createKabConnection( void* _pDriver )
{
KabConnection* pConnection = new KabConnection( static_cast< KabDriver* >( _pDriver ) );
// by definition, the pointer crossing library boundaries as void ptr is acquired once
pConnection->acquire();
return pConnection;
}
<commit_msg>INTEGRATION: CWS changefileheader (1.7.216); FILE MERGED 2008/04/01 15:08:51 thb 1.7.216.3: #i85898# Stripping all external header guards 2008/04/01 10:53:06 thb 1.7.216.2: #i85898# Stripping all external header guards 2008/03/28 15:23:44 rt 1.7.216.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: KConnection.cxx,v $
* $Revision: 1.8 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_connectivity.hxx"
#include "KConnection.hxx"
#include "KDatabaseMetaData.hxx"
#include "KStatement.hxx"
#include "KPreparedStatement.hxx"
#include "KDriver.hxx"
#include "KCatalog.hxx"
#include <com/sun/star/sdbc/ColumnValue.hpp>
#include <com/sun/star/sdbc/TransactionIsolation.hpp>
#include <vcl/kde_headers.h>
using namespace connectivity::kab;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::sdbc;
using namespace com::sun::star::sdbcx;
IMPLEMENT_SERVICE_INFO(KabConnection, "com.sun.star.sdbc.drivers.KabConnection", "com.sun.star.sdbc.Connection")
//-----------------------------------------------------------------------------
KabConnection::KabConnection(KabDriver* _pDriver)
: OMetaConnection_BASE(m_aMutex),
OSubComponent<KabConnection, KabConnection_BASE>((::cppu::OWeakObject*)_pDriver, this),
m_xMetaData(NULL),
m_pAddressBook(NULL),
m_pDriver(_pDriver)
{
m_pDriver->acquire();
}
//-----------------------------------------------------------------------------
KabConnection::~KabConnection()
{
if (!isClosed())
close();
m_pDriver->release();
m_pDriver = NULL;
}
//-----------------------------------------------------------------------------
void SAL_CALL KabConnection::release() throw()
{
relase_ChildImpl();
}
// -----------------------------------------------------------------------------
void KabConnection::construct(const ::rtl::OUString&, const Sequence< PropertyValue >&) throw(SQLException)
{
osl_incrementInterlockedCount( &m_refCount );
// create a KDE address book object
m_pAddressBook = KABC::StdAddressBook::self();
m_pAddressBook->setAutomaticSave(false);
// perharps we should analyze the URL to know whether the addressbook is local, over LDAP, etc...
// perharps we should get some user and password information from "info" properties
osl_decrementInterlockedCount( &m_refCount );
}
// XServiceInfo
// --------------------------------------------------------------------------------
Reference< XStatement > SAL_CALL KabConnection::createStatement( ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(KabConnection_BASE::rBHelper.bDisposed);
// create a statement
// the statement can only be executed once
Reference< XStatement > xReturn = new KabStatement(this);
m_aStatements.push_back(WeakReferenceHelper(xReturn));
return xReturn;
}
// --------------------------------------------------------------------------------
Reference< XPreparedStatement > SAL_CALL KabConnection::prepareStatement( const ::rtl::OUString& _sSql ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(KabConnection_BASE::rBHelper.bDisposed);
// create a statement
// the statement can only be executed more than once
Reference< XPreparedStatement > xReturn = new KabPreparedStatement(this, _sSql);
m_aStatements.push_back(WeakReferenceHelper(xReturn));
return xReturn;
}
// --------------------------------------------------------------------------------
Reference< XPreparedStatement > SAL_CALL KabConnection::prepareCall( const ::rtl::OUString& ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(KabConnection_BASE::rBHelper.bDisposed);
// not implemented yet :-) a task to do
return NULL;
}
// --------------------------------------------------------------------------------
::rtl::OUString SAL_CALL KabConnection::nativeSQL( const ::rtl::OUString& _sSql ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
// when you need to transform SQL92 to you driver specific you can do it here
return _sSql;
}
// --------------------------------------------------------------------------------
void SAL_CALL KabConnection::setAutoCommit( sal_Bool ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(KabConnection_BASE::rBHelper.bDisposed);
// here you have to set your commit mode please have a look at the jdbc documentation to get a clear explanation
}
// --------------------------------------------------------------------------------
sal_Bool SAL_CALL KabConnection::getAutoCommit( ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(KabConnection_BASE::rBHelper.bDisposed);
// you have to distinguish which if you are in autocommit mode or not
// at normal case true should be fine here
return sal_True;
}
// --------------------------------------------------------------------------------
void SAL_CALL KabConnection::commit( ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(KabConnection_BASE::rBHelper.bDisposed);
// when you database does support transactions you should commit here
}
// --------------------------------------------------------------------------------
void SAL_CALL KabConnection::rollback( ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(KabConnection_BASE::rBHelper.bDisposed);
// same as commit but for the other case
}
// --------------------------------------------------------------------------------
sal_Bool SAL_CALL KabConnection::isClosed( ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
// just simple -> we are closed when we are disposed, that means someone called dispose(); (XComponent)
return KabConnection_BASE::rBHelper.bDisposed;
}
// --------------------------------------------------------------------------------
Reference< XDatabaseMetaData > SAL_CALL KabConnection::getMetaData( ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(KabConnection_BASE::rBHelper.bDisposed);
// here we have to create the class with biggest interface
// The answer is 42 :-)
Reference< XDatabaseMetaData > xMetaData = m_xMetaData;
if (!xMetaData.is())
{
xMetaData = new KabDatabaseMetaData(this); // need the connection because it can return it
m_xMetaData = xMetaData;
}
return xMetaData;
}
// --------------------------------------------------------------------------------
void SAL_CALL KabConnection::setReadOnly( sal_Bool ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(KabConnection_BASE::rBHelper.bDisposed);
// set you connection to readonly
}
// --------------------------------------------------------------------------------
sal_Bool SAL_CALL KabConnection::isReadOnly( ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(KabConnection_BASE::rBHelper.bDisposed);
// return if your connection to readonly
return sal_False;
}
// --------------------------------------------------------------------------------
void SAL_CALL KabConnection::setCatalog( const ::rtl::OUString& ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(KabConnection_BASE::rBHelper.bDisposed);
// if your database doesn't work with catalogs you go to next method otherwise you kjnow what to do
}
// --------------------------------------------------------------------------------
::rtl::OUString SAL_CALL KabConnection::getCatalog( ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(KabConnection_BASE::rBHelper.bDisposed);
// return your current catalog
return ::rtl::OUString();
}
// --------------------------------------------------------------------------------
void SAL_CALL KabConnection::setTransactionIsolation( sal_Int32 ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(KabConnection_BASE::rBHelper.bDisposed);
// set your isolation level
// please have a look at @see com.sun.star.sdbc.TransactionIsolation
}
// --------------------------------------------------------------------------------
sal_Int32 SAL_CALL KabConnection::getTransactionIsolation( ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(KabConnection_BASE::rBHelper.bDisposed);
// please have a look at @see com.sun.star.sdbc.TransactionIsolation
return TransactionIsolation::NONE;
}
// --------------------------------------------------------------------------------
Reference< ::com::sun::star::container::XNameAccess > SAL_CALL KabConnection::getTypeMap( ) throw(SQLException, RuntimeException)
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(KabConnection_BASE::rBHelper.bDisposed);
// if your driver has special database types you can return it here
return NULL;
}
// --------------------------------------------------------------------------------
void SAL_CALL KabConnection::setTypeMap( const Reference< ::com::sun::star::container::XNameAccess >& ) throw(SQLException, RuntimeException)
{
// the other way around
}
// --------------------------------------------------------------------------------
// XCloseable
void SAL_CALL KabConnection::close( ) throw(SQLException, RuntimeException)
{
{
::osl::MutexGuard aGuard( m_aMutex );
checkDisposed(KabConnection_BASE::rBHelper.bDisposed);
}
dispose();
}
// --------------------------------------------------------------------------------
// XWarningsSupplier
Any SAL_CALL KabConnection::getWarnings( ) throw(SQLException, RuntimeException)
{
// when you collected some warnings -> return it
return Any();
}
// --------------------------------------------------------------------------------
void SAL_CALL KabConnection::clearWarnings( ) throw(SQLException, RuntimeException)
{
// you should clear your collected warnings here
}
//------------------------------------------------------------------------------
void KabConnection::disposing()
{
// we noticed that we should be destroied in near future so we have to dispose our statements
::osl::MutexGuard aGuard(m_aMutex);
for (OWeakRefArray::iterator i = m_aStatements.begin(); m_aStatements.end() != i; ++i)
{
Reference< XComponent > xComp(i->get(), UNO_QUERY);
if (xComp.is())
xComp->dispose();
}
m_aStatements.clear();
if (m_pAddressBook != NULL)
{
m_pAddressBook->close();
m_pAddressBook = NULL;
}
m_xMetaData = ::com::sun::star::uno::WeakReference< ::com::sun::star::sdbc::XDatabaseMetaData>();
dispose_ChildImpl();
KabConnection_BASE::disposing();
}
// -----------------------------------------------------------------------------
Reference< XTablesSupplier > SAL_CALL KabConnection::createCatalog()
{
::osl::MutexGuard aGuard( m_aMutex );
Reference< XTablesSupplier > xTab = m_xCatalog;
if (!m_xCatalog.is())
{
KabCatalog *pCat = new KabCatalog(this);
xTab = pCat;
m_xCatalog = xTab;
}
return xTab;
}
// -----------------------------------------------------------------------------
::KABC::AddressBook* KabConnection::getAddressBook() const
{
return m_pAddressBook;
}
// -----------------------------------------------------------------------------
extern "C" void* SAL_CALL createKabConnection( void* _pDriver )
{
KabConnection* pConnection = new KabConnection( static_cast< KabDriver* >( _pDriver ) );
// by definition, the pointer crossing library boundaries as void ptr is acquired once
pConnection->acquire();
return pConnection;
}
<|endoftext|> |
<commit_before>#pragma once
#include "syslog.h"
#include <string>
#include "blackhole/error.hpp"
#include "blackhole/repository/factory/traits.hpp"
namespace blackhole {
namespace sink {
enum class priority_t : unsigned {
emerg = LOG_EMERG,
alert = LOG_ALERT,
crit = LOG_CRIT,
err = LOG_ERR,
warning = LOG_WARNING,
notice = LOG_NOTICE,
info = LOG_INFO,
debug = LOG_DEBUG
};
template<typename Level>
struct priority_traits;
namespace backend {
class native_t {
const std::string m_identity;
public:
native_t(const std::string& identity, int option = LOG_PID, int facility = LOG_USER) :
m_identity(identity)
{
initialize(option, facility);
}
~native_t() {
::closelog();
}
void write(priority_t priority, const std::string& message) {
::syslog(static_cast<unsigned>(priority), "%s", message.c_str());
}
private:
void initialize(int option, int facility) {
if (m_identity.empty()) {
throw error_t("no syslog identity has been specified");
}
::openlog(m_identity.c_str(), option, facility);
}
};
} // namespace backend
namespace syslog {
struct config_t {
std::string identity;
int option;
int facility;
config_t() {}
config_t(const std::string& identity, int option = LOG_PID, int facility = LOG_USER) :
identity(identity),
option(option),
facility(facility)
{}
config_t(const std::string& identity, int facility) :
identity(identity),
option(LOG_PID),
facility(facility)
{}
};
} // namespace syslog
template<typename Level, typename Backend = backend::native_t>
class syslog_t {
Backend m_backend;
public:
typedef syslog::config_t config_type;
static const char* name() {
return "syslog";
}
syslog_t(const config_type& config) :
m_backend(config.identity, config.option, config.facility)
{
static_assert(std::is_enum<Level>::value, "level type must be enum");
}
syslog_t(const std::string& identity, int option = LOG_PID, int facility = LOG_USER) :
m_backend(identity, option, facility)
{
static_assert(std::is_enum<Level>::value, "level type must be enum");
}
void consume(Level level, const std::string& message) {
priority_t priority = priority_traits<Level>::map(level);
m_backend.write(priority, message);
}
Backend& backend() {
return m_backend;
}
};
} // namespace sink
template<typename Level>
struct factory_traits<sink::syslog_t<Level>> {
typedef sink::syslog_t<Level> sink_type;
typedef typename sink_type::config_type config_type;
static void map_config(const aux::extractor<sink_type>& ex, config_type& config) {
ex["identity"].to(config.identity);
}
};
} // namespace blackhole
<commit_msg>[Bug Fix] Fixed undefined behaviour.<commit_after>#pragma once
#include "syslog.h"
#include <string>
#include "blackhole/error.hpp"
#include "blackhole/repository/factory/traits.hpp"
namespace blackhole {
namespace sink {
enum class priority_t : unsigned {
emerg = LOG_EMERG,
alert = LOG_ALERT,
crit = LOG_CRIT,
err = LOG_ERR,
warning = LOG_WARNING,
notice = LOG_NOTICE,
info = LOG_INFO,
debug = LOG_DEBUG
};
template<typename Level>
struct priority_traits;
namespace backend {
class native_t {
const std::string m_identity;
public:
native_t(const std::string& identity, int option = LOG_PID, int facility = LOG_USER) :
m_identity(identity)
{
initialize(option, facility);
}
~native_t() {
::closelog();
}
void write(priority_t priority, const std::string& message) {
::syslog(static_cast<unsigned>(priority), "%s", message.c_str());
}
private:
void initialize(int option, int facility) {
if (m_identity.empty()) {
throw error_t("no syslog identity has been specified");
}
::openlog(m_identity.c_str(), option, facility);
}
};
} // namespace backend
namespace syslog {
struct config_t {
std::string identity;
int option;
int facility;
config_t() :
identity("blackhole"),
option(LOG_PID),
facility(LOG_USER)
{}
config_t(const std::string& identity, int option = LOG_PID, int facility = LOG_USER) :
identity(identity),
option(option),
facility(facility)
{}
config_t(const std::string& identity, int facility) :
identity(identity),
option(LOG_PID),
facility(facility)
{}
};
} // namespace syslog
template<typename Level, typename Backend = backend::native_t>
class syslog_t {
Backend m_backend;
public:
typedef syslog::config_t config_type;
static const char* name() {
return "syslog";
}
syslog_t(const config_type& config) :
m_backend(config.identity, config.option, config.facility)
{
static_assert(std::is_enum<Level>::value, "level type must be enum");
}
syslog_t(const std::string& identity, int option = LOG_PID, int facility = LOG_USER) :
m_backend(identity, option, facility)
{
static_assert(std::is_enum<Level>::value, "level type must be enum");
}
void consume(Level level, const std::string& message) {
priority_t priority = priority_traits<Level>::map(level);
m_backend.write(priority, message);
}
Backend& backend() {
return m_backend;
}
};
} // namespace sink
template<typename Level>
struct factory_traits<sink::syslog_t<Level>> {
typedef sink::syslog_t<Level> sink_type;
typedef typename sink_type::config_type config_type;
static void map_config(const aux::extractor<sink_type>& ex, config_type& config) {
ex["identity"].to(config.identity);
}
};
} // namespace blackhole
<|endoftext|> |
<commit_before>/*
* Copyright 2010-2012 Anders Wallin (anders.e.e.wallin "at" gmail.com)
*
* This file is part of OpenVoronoi.
*
* OpenVoronoi is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenVoronoi 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 OpenVoronoi. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <queue>
#include <set>
#include <boost/tuple/tuple.hpp>
#include "common/point.hpp"
#include "graph.hpp"
#include "vertex_positioner.hpp"
#include "filter.hpp"
#include "kdtree.hpp"
/*! \mainpage OpenVoronoi
*
* \author Anders E. Wallin (anders.e.e.wallin "at" gmail.com)
* \section intro_sec Introduction
*
* OpenVoronoi is a c++ library with python bindings (using boost::python) for calculating 2D voronoi-diagrams of point,
* line-segment, and circular-arc(not implement yet!) sites.
* An incremental topology-oriented algorithm is used.
*
* See github for build/install instructions https://github.com/aewallin/openvoronoi
*
* DEB packages for Ubuntu are available at https://launchpad.net/~anders-e-e-wallin/+archive/cam
*
* Output gallery: https://picasaweb.google.com/106188605401091280402/OpenVoronoiExamples
*
* \section Utilities
* - Offset
* - Medial-Axis
* - SVG output
*
* \section Tests
* Tests are written for CTest.
* - "ctest -R cpp" runs only the c++ tests (these are fast)
* - "ctest" runs all tests (some may be slow)
* Some tests use truetype-tracer (font geometry source), and some use CGAL_RPG (random polygon generator).
*
* \section coverage Code Coverage Testing
* - compile using CMAKE_BUILD_TYPE=Coverage (uses "-fprofile-arcs -ftest-coverage" )
* - install the library "sudo make install"
* - Run the custom target coverage-report with "make coverage-report". It will do the following:
* - reset lcov counters "lcov --directory ./ --zerocounters"
* - run CTest c++ tests with "ctest -R cpptest"
* - generate an info-file with "lcov --directory ./ --capture --output-file app.info"
* - generate html output with "genhtml --output-directory coverage --title OpenVoronoi Test Coverage app.info"
* - point your browser to build/doc/index.html to see the output
*
* \section debian Debian source package
* - See the files in src/deb for more information.
* - A debian source package in <build>/Debian is built with the spackage target, run with "make spackage"
* - remember to set the "Release" build-type
* - disable building of tests (these require ttt and rpg which pbuilder/PPA does not find)
* - The source-package can be tested with pbuilder
* - to test-build the package (assuming you are on a precise distribution) run e.g. "sudo pbuilder build openvoronoi_12.02.257-ubuntu1~precise1.dsc" (this may take some time)
* - to test-build for other distributions:
* - "sudo pbuilder build --distribution lucid openvoronoi_12.02.257-ubuntu1~lucid1.dsc"
* - The source-package(s) can be uploaded to the Launchpad PPA with dput (this requires that you have write-access to the PPA)
* - "dput ppa:anders-e-e-wallin/cam *.changes"
*/
namespace ovd
{
/*!
* \namespace ovd
* \brief OpenVoronoi classes and functions
*/
class VoronoiDiagramChecker;
/// \brief KD-tree for 2D point location
///
/// a kd-tree is used for nearest-neighbor search when inserting point sites
struct kd_point {
/// default ctor
kd_point() : p(0,0), face(0) { }
/// kd-point with given position and HEFace
kd_point(Point pt, HEFace f) : p(pt), face(f) { }
/// kd-point at given position
kd_point(Point pt) : p(pt), face(0) { }
/// distance (suared) to given point
double dist(const kd_point& pt) const {
return (p.x-pt.p.x)*(p.x-pt.p.x) + (p.y-pt.p.y)*(p.y-pt.p.y);
}
/// return x or y coordinate of Point
double operator[](unsigned int i) const {
return i == 0 ? p.x : p.y;
}
/// return x or y coordinate of Point
double& operator[](unsigned int i) {
return i == 0 ? p.x : p.y;
}
Point p; ///< position of 2D PointSite
HEFace face; ///< the HEFace correspoinding to the PointSite
};
/// type of the KD-tree used for nearest-neighbor search
typedef kdtree::KDTree<kd_point> kd_type;
/// \brief Voronoi diagram.
///
/// see http://en.wikipedia.org/wiki/Voronoi_diagram
///
/// the dual of a voronoi diagram is the delaunay diagram(triangulation).
/// voronoi-faces are dual to delaunay-vertices.
/// vornoi-vertices are dual to delaunay-faces
/// voronoi-edges are dual to delaunay-edges
class VoronoiDiagram {
public:
VoronoiDiagram(double far, unsigned int n_bins);
virtual ~VoronoiDiagram();
int insert_point_site(const Point& p, int step=0);
bool insert_line_site(int idx1, int idx2, int step=99); // default step should make algorithm run until the end!
void insert_arc_site(int idx1, int idx2, const Point& c, bool cw, int step=99);
/// return the far radius
double get_far_radius() const {return far_radius;}
/// return number of point sites in diagram
int num_point_sites() const {return num_psites-3;} // the three initial vertices don't count
/// return number of line-segments sites in diagram
int num_line_sites() const {return num_lsites;}
/// return number of voronoi-vertices
int num_vertices() const { return g.num_vertices()-num_point_sites(); }
/// return number of faces in graph
int num_faces() const { return g.num_faces(); }
int num_split_vertices() const;
/// return reference to graph \todo not elegant. only used by vd2svg ?
HEGraph& get_graph_reference() {return g;}
std::string print() const;
/// reset vertex index count \todo not very elegant...
static void reset_vertex_count() { VoronoiVertex::reset_count(); }
/// turn on debug output
void debug_on() {debug=true;}
/// set silent mode on/off
void set_silent(bool b) {
silent=b;
vpos->set_silent(silent);
}
bool check();
void filter( Filter* flt);
void filter_reset();
protected:
/// type for item in VertexQueue. pair of vertex-desxriptor and in_circle predicate
typedef std::pair<HEVertex, double> VertexDetPair;
/// \brief comparison-predicate for VertexQueue
///
/// in augment_vertex_set() we grow the delete-tree by processing vertices
/// one-by-one from a priority_queue. This is the priority_queue sort predicate.
/// We handle vertices with a large fabs( in_circle() ) first, since we
/// believe their predicate to be more reliable.
class abs_comparison {
public:
/// return true if absolute-value of lhs.second is smaller than rhs.second
bool operator() (const VertexDetPair& lhs, const VertexDetPair&rhs) const {
return ( fabs(lhs.second) < fabs(rhs.second) );
}
};
/// priority_queue for vertex for processing
// sorted by decreasing fabs() of in_circle-predicate, so that the vertices whose IN/OUT status we are 'most certain' about are processed first
typedef std::priority_queue< VertexDetPair , std::vector<VertexDetPair>, abs_comparison > VertexQueue;
/// \brief data required for adding a new edge
///
/// used in add_edge() for storing information related to
/// the new edge.
struct EdgeData {
HEEdge v1_prv; ///< edge prior to v1
HEVertex v1; ///< NEW edge source
HEEdge v1_nxt; ///< edge following v1
HEEdge v2_prv; ///< edge prior to v2
HEVertex v2; ///< NEW edge target
HEEdge v2_nxt; ///< edge following v2
HEFace f; ///< face of v1 and v2
};
void initialize();
HEVertex find_seed_vertex(HEFace f, Site* site);
EdgeVector find_in_out_edges();
EdgeData find_edge_data(HEFace f, VertexVector startverts, std::pair<HEVertex,HEVertex> segment);
EdgeVector find_split_edges(HEFace f, Point pt1, Point pt2);
bool find_split_vertex(HEFace f, HEVertex& v);
std::pair<HEVertex,HEVertex> find_endpoints(int idx1, int idx2);
bool null_vertex_target( HEVertex v , HEVertex& trg);
void augment_vertex_set( Site* site);
bool predicate_c4(HEVertex v);
bool predicate_c5(HEVertex v);
void mark_adjacent_faces(HEVertex v, Site* site);
void mark_adjacent_faces_p( HEVertex v );
void mark_vertex(HEVertex& v, Site* site);
void add_vertices( Site* site );
HEFace add_face(Site* site);
void add_edges(HEFace new_f1, HEFace f);
void add_edges(HEFace new_f1, HEFace f, HEFace new_f2, std::pair<HEVertex,HEVertex> seg);
void add_edge(EdgeData ed, HEFace new1, HEFace new2=0);
void add_separator(HEFace f, HEFace nf, boost::tuple<HEEdge, HEVertex, HEEdge,bool> target, HEVertex endp, Site* s1, Site* s2);
void add_split_vertex(HEFace f, Site* s);
boost::tuple<HEVertex,HEFace,HEVertex,HEVertex,HEFace> find_null_face(HEVertex start, HEVertex other, Point l, Point dir, Site* new_site);
boost::tuple<HEEdge,HEVertex,HEEdge,bool> find_separator_target(HEFace f, HEVertex endp);
std::pair<HEVertex,HEFace> process_null_edge(Point dir, HEEdge next_edge , bool k3, bool next_prev);
HEVertex add_separator_vertex(HEVertex endp, HEEdge edge, Point sep_dir);
void repair_face( HEFace f );
void repair_face( HEFace f , std::pair<HEVertex,HEVertex> segs,
std::pair<HEFace,HEFace> nulled_faces,
std::pair<HEFace,HEFace> null_faces );
void remove_vertex_set();
void remove_split_vertex(HEFace f);
void reset_status();
int num_new_vertices(HEFace f);
// HELPER-CLASSES
VoronoiDiagramChecker* vd_checker; ///< sanity-checks on the diagram are done by this helper class
kd_type* kd_tree; ///< kd-tree for nearest neighbor search during point Site insertion
VertexPositioner* vpos; ///< an algorithm for positioning vertices
// DATA
typedef std::map<int,HEVertex> VertexMap; ///< type for vertex-index to vertex-descriptor map
typedef std::pair<int,HEVertex> VertexMapPair; ///< associate vertex index with vertex descriptor
VertexMap vertex_map; ///< map from int handles to vertex-descriptors, used in insert_line_site()
VertexQueue vertexQueue; ///< queue of vertices to be processed
HEGraph g; ///< the half-edge diagram of the vd
double far_radius; ///< sites must fall within a circle with radius far_radius
int num_psites; ///< the number of point sites
int num_lsites; ///< the number of line-segment sites
int num_arc_sites; ///< the number of arc-sites
FaceVector incident_faces; ///< temporary variable for ::INCIDENT faces, will be reset to ::NONINCIDENT after a site has been inserted
std::set<HEVertex> modified_vertices; ///< temporary variable for in-vertices, out-vertices that need to be reset after a site has been inserted
VertexVector v0; ///< IN-vertices, i.e. to-be-deleted
bool debug; ///< turn debug output on/off
bool silent; ///< no warnings emitted when silent==true
private:
VoronoiDiagram(); // don't use.
};
/// \brief error-functor to locate ::SPLIT vertices
///
/// for passing to numerical boost::toms748 root-finding algorithm
class SplitPointError {
public:
/// \param gi graph
/// \param split_edge the edge on which we want to position a SPLIT vertex
/// \param pt1 first point of split-line
/// \param pt2 second point of split-line
SplitPointError(HEGraph& gi, HEEdge split_edge, Point pt1, Point pt2) :
g(gi), edge(split_edge), p1(pt1), p2(pt2)
{}
/// \return signed distance to the pt1-pt2 line from edge-point at given offset \a t
double operator()(const double t) {
Point p = g[edge].point(t);
// line: pt1 + u*(pt2-pt1) = p
// (p-pt1) dot (pt2-pt1) = u* (pt2-pt1) dot (pt2-pt1)
double u = (p-p1).dot(p2-p1) / ( (p2-p1).dot(p2-p1) );
Point proj = p1 + u*(p2-p1);
double dist = (proj-p).norm();
double sign;
if ( p.is_right(p1,p2) )
sign = +1;
else
sign = -1;
return sign*dist;
}
private:
HEGraph& g; ///< reference to vd-graph
HEEdge edge; ///< the HEEdge on which we position the new SPLIT vertex
Point p1; ///< first point of the split-line
Point p2; ///< second point of the split-line
};
} // end ovd namespace
// end voronoidiagram.hpp
<commit_msg>minor documentation added<commit_after>/*
* Copyright 2010-2012 Anders Wallin (anders.e.e.wallin "at" gmail.com)
*
* This file is part of OpenVoronoi.
*
* OpenVoronoi is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenVoronoi 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 OpenVoronoi. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <queue>
#include <set>
#include <boost/tuple/tuple.hpp>
#include "common/point.hpp"
#include "graph.hpp"
#include "vertex_positioner.hpp"
#include "filter.hpp"
#include "kdtree.hpp"
/*! \mainpage OpenVoronoi
*
* \author Anders E. Wallin (anders.e.e.wallin "at" gmail.com)
* \section intro_sec Introduction
*
* OpenVoronoi is a c++ library with python bindings (using boost::python) for calculating 2D voronoi-diagrams of point,
* line-segment, and circular-arc(not implement yet!) sites.
* An incremental topology-oriented algorithm is used.
*
* See github for build/install instructions https://github.com/aewallin/openvoronoi
*
* DEB packages for Ubuntu are available at https://launchpad.net/~anders-e-e-wallin/+archive/cam
*
* Output gallery: https://picasaweb.google.com/106188605401091280402/OpenVoronoiExamples
*
* \section Utilities
* - Offset
* - Medial-Axis
* - SVG output
*
* \section Tests
* Tests are written for CTest.
* - "ctest -R cpp" runs only the c++ tests (these are fast)
* - "ctest" runs all tests (some may be slow)
* Some tests use truetype-tracer (font geometry source), and some use CGAL_RPG (random polygon generator).
*
* \section coverage Code Coverage Testing
* - compile using CMAKE_BUILD_TYPE=Coverage (uses "-fprofile-arcs -ftest-coverage" )
* - install the library "sudo make install"
* - Run the custom target coverage-report with "make coverage-report". It will do the following:
* - reset lcov counters "lcov --directory ./ --zerocounters"
* - run CTest c++ tests with "ctest -R cpptest"
* - generate an info-file with "lcov --directory ./ --capture --output-file app.info"
* - generate html output with "genhtml --output-directory coverage --title OpenVoronoi Test Coverage app.info"
* - point your browser to build/doc/index.html to see the output
*
* \section debian Debian source package
* - See the files in src/deb for more information.
* - A debian source package in <build>/Debian is built with the spackage target, run with "make spackage"
* - remember to set the "Release" build-type
* - disable building of tests (these require ttt and rpg which pbuilder/PPA does not find)
* - The source-package can be tested with pbuilder
* - To test-build the package (assuming you are on a precise distribution). This will take a long time.
* - "sudo pbuilder build openvoronoi_12.02.257-ubuntu1~precise1.dsc"
* - To test-build for other distributions:
* - "sudo pbuilder build --distribution lucid openvoronoi_12.02.257-ubuntu1~lucid1.dsc"
* - The source-package(s) can be uploaded to the Launchpad PPA with dput (this requires that you have write-access to the PPA)
* - "dput ppa:anders-e-e-wallin/cam *.changes"
*/
namespace ovd
{
/*!
* \namespace ovd
* \brief OpenVoronoi classes and functions
*/
class VoronoiDiagramChecker;
/// \brief KD-tree for 2D point location
///
/// a kd-tree is used for nearest-neighbor search when inserting point sites
struct kd_point {
/// default ctor
kd_point() : p(0,0), face(0) { }
/// kd-point with given position and HEFace
kd_point(Point pt, HEFace f) : p(pt), face(f) { }
/// kd-point at given position
kd_point(Point pt) : p(pt), face(0) { }
/// distance (suared) to given point
double dist(const kd_point& pt) const {
return (p.x-pt.p.x)*(p.x-pt.p.x) + (p.y-pt.p.y)*(p.y-pt.p.y);
}
/// return x or y coordinate of Point
double operator[](unsigned int i) const {
return i == 0 ? p.x : p.y;
}
/// return x or y coordinate of Point
double& operator[](unsigned int i) {
return i == 0 ? p.x : p.y;
}
Point p; ///< position of 2D PointSite
HEFace face; ///< the HEFace correspoinding to the PointSite
};
/// type of the KD-tree used for nearest-neighbor search
typedef kdtree::KDTree<kd_point> kd_type;
/// \brief Voronoi diagram.
///
/// see http://en.wikipedia.org/wiki/Voronoi_diagram
///
/// the dual of a voronoi diagram is the delaunay diagram(triangulation).
/// voronoi-faces are dual to delaunay-vertices.
/// vornoi-vertices are dual to delaunay-faces
/// voronoi-edges are dual to delaunay-edges
class VoronoiDiagram {
public:
VoronoiDiagram(double far, unsigned int n_bins);
virtual ~VoronoiDiagram();
int insert_point_site(const Point& p, int step=0);
bool insert_line_site(int idx1, int idx2, int step=99); // default step should make algorithm run until the end!
void insert_arc_site(int idx1, int idx2, const Point& c, bool cw, int step=99);
/// return the far radius
double get_far_radius() const {return far_radius;}
/// return number of point sites in diagram
int num_point_sites() const {return num_psites-3;} // the three initial vertices don't count
/// return number of line-segments sites in diagram
int num_line_sites() const {return num_lsites;}
/// return number of voronoi-vertices
int num_vertices() const { return g.num_vertices()-num_point_sites(); }
/// return number of faces in graph
int num_faces() const { return g.num_faces(); }
int num_split_vertices() const;
/// return reference to graph \todo not elegant. only used by vd2svg ?
HEGraph& get_graph_reference() {return g;}
std::string print() const;
/// reset vertex index count \todo not very elegant...
static void reset_vertex_count() { VoronoiVertex::reset_count(); }
/// turn on debug output
void debug_on() {debug=true;}
/// set silent mode on/off
void set_silent(bool b) {
silent=b;
vpos->set_silent(silent);
}
bool check();
void filter( Filter* flt);
void filter_reset();
protected:
/// type for item in VertexQueue. pair of vertex-desxriptor and in_circle predicate
typedef std::pair<HEVertex, double> VertexDetPair;
/// \brief comparison-predicate for VertexQueue
///
/// in augment_vertex_set() we grow the delete-tree by processing vertices
/// one-by-one from a priority_queue. This is the priority_queue sort predicate.
/// We handle vertices with a large fabs( in_circle() ) first, since we
/// believe their predicate to be more reliable.
class abs_comparison {
public:
/// return true if absolute-value of lhs.second is smaller than rhs.second
bool operator() (const VertexDetPair& lhs, const VertexDetPair&rhs) const {
return ( fabs(lhs.second) < fabs(rhs.second) );
}
};
/// priority_queue for vertex for processing
// sorted by decreasing fabs() of in_circle-predicate, so that the vertices whose IN/OUT status we are 'most certain' about are processed first
typedef std::priority_queue< VertexDetPair , std::vector<VertexDetPair>, abs_comparison > VertexQueue;
/// \brief data required for adding a new edge
///
/// used in add_edge() for storing information related to
/// the new edge.
struct EdgeData {
HEEdge v1_prv; ///< edge prior to v1
HEVertex v1; ///< NEW edge source
HEEdge v1_nxt; ///< edge following v1
HEEdge v2_prv; ///< edge prior to v2
HEVertex v2; ///< NEW edge target
HEEdge v2_nxt; ///< edge following v2
HEFace f; ///< face of v1 and v2
};
void initialize();
HEVertex find_seed_vertex(HEFace f, Site* site);
EdgeVector find_in_out_edges();
EdgeData find_edge_data(HEFace f, VertexVector startverts, std::pair<HEVertex,HEVertex> segment);
EdgeVector find_split_edges(HEFace f, Point pt1, Point pt2);
bool find_split_vertex(HEFace f, HEVertex& v);
std::pair<HEVertex,HEVertex> find_endpoints(int idx1, int idx2);
bool null_vertex_target( HEVertex v , HEVertex& trg);
void augment_vertex_set( Site* site);
bool predicate_c4(HEVertex v);
bool predicate_c5(HEVertex v);
void mark_adjacent_faces(HEVertex v, Site* site);
void mark_adjacent_faces_p( HEVertex v );
void mark_vertex(HEVertex& v, Site* site);
void add_vertices( Site* site );
HEFace add_face(Site* site);
void add_edges(HEFace new_f1, HEFace f);
void add_edges(HEFace new_f1, HEFace f, HEFace new_f2, std::pair<HEVertex,HEVertex> seg);
void add_edge(EdgeData ed, HEFace new1, HEFace new2=0);
void add_separator(HEFace f, HEFace nf, boost::tuple<HEEdge, HEVertex, HEEdge,bool> target, HEVertex endp, Site* s1, Site* s2);
void add_split_vertex(HEFace f, Site* s);
boost::tuple<HEVertex,HEFace,HEVertex,HEVertex,HEFace> find_null_face(HEVertex start, HEVertex other, Point l, Point dir, Site* new_site);
boost::tuple<HEEdge,HEVertex,HEEdge,bool> find_separator_target(HEFace f, HEVertex endp);
std::pair<HEVertex,HEFace> process_null_edge(Point dir, HEEdge next_edge , bool k3, bool next_prev);
HEVertex add_separator_vertex(HEVertex endp, HEEdge edge, Point sep_dir);
void repair_face( HEFace f );
void repair_face( HEFace f , std::pair<HEVertex,HEVertex> segs,
std::pair<HEFace,HEFace> nulled_faces,
std::pair<HEFace,HEFace> null_faces );
void remove_vertex_set();
void remove_split_vertex(HEFace f);
void reset_status();
int num_new_vertices(HEFace f);
// HELPER-CLASSES
VoronoiDiagramChecker* vd_checker; ///< sanity-checks on the diagram are done by this helper class
kd_type* kd_tree; ///< kd-tree for nearest neighbor search during point Site insertion
VertexPositioner* vpos; ///< an algorithm for positioning vertices
// DATA
typedef std::map<int,HEVertex> VertexMap; ///< type for vertex-index to vertex-descriptor map
typedef std::pair<int,HEVertex> VertexMapPair; ///< associate vertex index with vertex descriptor
VertexMap vertex_map; ///< map from int handles to vertex-descriptors, used in insert_line_site()
VertexQueue vertexQueue; ///< queue of vertices to be processed
HEGraph g; ///< the half-edge diagram of the vd
double far_radius; ///< sites must fall within a circle with radius far_radius
int num_psites; ///< the number of point sites
int num_lsites; ///< the number of line-segment sites
int num_arc_sites; ///< the number of arc-sites
FaceVector incident_faces; ///< temporary variable for ::INCIDENT faces, will be reset to ::NONINCIDENT after a site has been inserted
std::set<HEVertex> modified_vertices; ///< temporary variable for in-vertices, out-vertices that need to be reset after a site has been inserted
VertexVector v0; ///< IN-vertices, i.e. to-be-deleted
bool debug; ///< turn debug output on/off
bool silent; ///< no warnings emitted when silent==true
private:
VoronoiDiagram(); // don't use.
};
/// \brief error-functor to locate ::SPLIT vertices
///
/// for passing to numerical boost::toms748 root-finding algorithm
class SplitPointError {
public:
/// \param gi graph
/// \param split_edge the edge on which we want to position a SPLIT vertex
/// \param pt1 first point of split-line
/// \param pt2 second point of split-line
SplitPointError(HEGraph& gi, HEEdge split_edge, Point pt1, Point pt2) :
g(gi), edge(split_edge), p1(pt1), p2(pt2)
{}
/// \return signed distance to the pt1-pt2 line from edge-point at given offset \a t
double operator()(const double t) {
Point p = g[edge].point(t);
// line: pt1 + u*(pt2-pt1) = p
// (p-pt1) dot (pt2-pt1) = u* (pt2-pt1) dot (pt2-pt1)
double u = (p-p1).dot(p2-p1) / ( (p2-p1).dot(p2-p1) );
Point proj = p1 + u*(p2-p1);
double dist = (proj-p).norm();
double sign;
if ( p.is_right(p1,p2) )
sign = +1;
else
sign = -1;
return sign*dist;
}
private:
HEGraph& g; ///< reference to vd-graph
HEEdge edge; ///< the HEEdge on which we position the new SPLIT vertex
Point p1; ///< first point of the split-line
Point p2; ///< second point of the split-line
};
} // end ovd namespace
// end voronoidiagram.hpp
<|endoftext|> |
<commit_before>/*
* Implementation of a ACME client.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#ifndef BENG_PROXY_GLUE_HTTP_CLIENT_HXX
#define BENG_PROXY_GLUE_HTTP_CLIENT_HXX
#include "http_headers.hxx"
#include "net/AddressInfo.hxx"
#include "strmap.hxx"
#include <http/method.h>
#include <http/status.h>
#include <string>
struct pool;
struct Balancer;
class StockMap;
struct TcpBalancer;
struct SocketFilter;
class SocketFilterFactory;
class Istream;
class EventLoop;
class HttpHeaders;
class HttpResponseHandler;
class CancellablePointer;
struct GlueHttpServerAddress {
const char *const host_and_port;
AddressInfo addresses;
const bool ssl;
GlueHttpServerAddress(bool _ssl,
const char *_host_and_port, int default_port);
};
struct GlueHttpResponse {
http_status_t status;
StringMap headers;
std::string body;
GlueHttpResponse(http_status_t _status,
StringMap &&_headers, std::string &&_body)
:status(_status), headers(std::move(_headers)), body(_body) {}
};
class GlueHttpClient {
Balancer *const balancer;
StockMap *const tcp_stock;
TcpBalancer *const tcp_balancer;
public:
explicit GlueHttpClient(EventLoop &event_loop);
~GlueHttpClient();
GlueHttpClient(const GlueHttpClient &) = delete;
GlueHttpClient &operator=(const GlueHttpClient &) = delete;
void Request(struct pool &p, EventLoop &event_loop,
GlueHttpServerAddress &server,
http_method_t method, const char *uri,
HttpHeaders &&headers, Istream *body,
HttpResponseHandler &handler,
CancellablePointer &cancel_ptr);
GlueHttpResponse Request(EventLoop &event_loop,
struct pool &p, GlueHttpServerAddress &server,
http_method_t method, const char *uri,
HttpHeaders &&headers,
Istream *body=nullptr);
};
#endif
<commit_msg>certdb/GlueHttpClient: clean up forward declarations<commit_after>/*
* Implementation of a ACME client.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#ifndef BENG_PROXY_GLUE_HTTP_CLIENT_HXX
#define BENG_PROXY_GLUE_HTTP_CLIENT_HXX
#include "http_headers.hxx"
#include "net/AddressInfo.hxx"
#include "strmap.hxx"
#include <http/method.h>
#include <http/status.h>
#include <string>
struct pool;
struct Balancer;
class StockMap;
struct TcpBalancer;
class Istream;
class EventLoop;
class HttpHeaders;
class HttpResponseHandler;
class CancellablePointer;
struct GlueHttpServerAddress {
const char *const host_and_port;
AddressInfo addresses;
const bool ssl;
GlueHttpServerAddress(bool _ssl,
const char *_host_and_port, int default_port);
};
struct GlueHttpResponse {
http_status_t status;
StringMap headers;
std::string body;
GlueHttpResponse(http_status_t _status,
StringMap &&_headers, std::string &&_body)
:status(_status), headers(std::move(_headers)), body(_body) {}
};
class GlueHttpClient {
Balancer *const balancer;
StockMap *const tcp_stock;
TcpBalancer *const tcp_balancer;
public:
explicit GlueHttpClient(EventLoop &event_loop);
~GlueHttpClient();
GlueHttpClient(const GlueHttpClient &) = delete;
GlueHttpClient &operator=(const GlueHttpClient &) = delete;
void Request(struct pool &p, EventLoop &event_loop,
GlueHttpServerAddress &server,
http_method_t method, const char *uri,
HttpHeaders &&headers, Istream *body,
HttpResponseHandler &handler,
CancellablePointer &cancel_ptr);
GlueHttpResponse Request(EventLoop &event_loop,
struct pool &p, GlueHttpServerAddress &server,
http_method_t method, const char *uri,
HttpHeaders &&headers,
Istream *body=nullptr);
};
#endif
<|endoftext|> |
<commit_before>/******************************************************************************
**
** Copyright (C) 2009-2011 Kyle Lutz <kyle.r.lutz@gmail.com>
** All rights reserved.
**
** This file is a part of the chemkit project. For more information
** see <http://www.chemkit.org>.
**
** 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 chemkit project nor the names of its
** contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
******************************************************************************/
#include "pluginmanager.h"
#include <map>
#include <cstdlib>
#include <iostream>
#include <boost/filesystem.hpp>
#include <boost/algorithm/string/case_conv.hpp>
#include "plugin.h"
#include "foreach.h"
#include "dynamiclibrary.h"
namespace chemkit {
// === PluginManagerPrivate ================================================ //
class PluginManagerPrivate
{
public:
std::vector<Plugin *> plugins;
std::string errorString;
bool defaultPluginsLoaded;
std::map<std::string, std::map<std::string, PluginManager::Function> > pluginClasses;
};
// === PluginManager ======================================================= //
/// \class PluginManager pluginmanager.h chemkit/pluginmanager.h
/// \ingroup chemkit
/// \brief The PluginManager class manages the loading and unloading
/// of plugins.
///
/// \see Plugin
// --- Construction and Destruction ---------------------------------------- //
PluginManager::PluginManager()
: d(new PluginManagerPrivate)
{
d->defaultPluginsLoaded = false;
}
PluginManager::~PluginManager()
{
foreach(Plugin *plugin, d->plugins){
DynamicLibrary *library = plugin->library();
delete plugin;
delete library;
}
delete d;
}
// --- Properties ---------------------------------------------------------- //
/// Returns the plugin with \p name. Returns \c 0 if no plugin with
// \p name is loaded.
Plugin* PluginManager::plugin(const std::string &name) const
{
foreach(Plugin *plugin, d->plugins){
if(plugin->name() == name){
return plugin;
}
}
return 0;
}
/// Returns a list of all the loaded plugins.
const std::vector<Plugin *>& PluginManager::plugins() const
{
return d->plugins;
}
/// Returns the number of loaded plugins.
int PluginManager::pluginCount() const
{
return d->plugins.size();
}
// --- Plugin Loading ------------------------------------------------------ //
/// Loads a plugin from \p fileName. Returns \c false if an error
/// occurs.
bool PluginManager::loadPlugin(const std::string &fileName)
{
DynamicLibrary *library = new DynamicLibrary;
library->setFileName(fileName);
bool ok = library->open();
if(!ok){
std::cerr << "PluginManager: Error: Failed to load plugin: (" << fileName << "):"
<< library->errorString() << std::endl;
return false;
}
typedef Plugin* (*InitFunction)();
InitFunction initFunction = reinterpret_cast<InitFunction>(library->resolve("chemkit_plugin_init"));
if(!initFunction){
std::cerr << "PluginManager: Error: Failed to load plugin: (" << fileName << "):"
<< "Plugin contains no init() function." << std::endl;
return false;
}
Plugin *plugin = initFunction();
if(!plugin){
std::cerr << "PluginManager: Error: Failed to load plugin: (" << fileName << "):"
<< "Calling the plugin's init() function failed." << std::endl;
return false;
}
plugin->setLibrary(library);
d->plugins.push_back(plugin);
return true;
}
/// Loads all plugins from \p directory.
void PluginManager::loadPlugins(const std::string &directory)
{
boost::filesystem::path dir(directory);
if(!boost::filesystem::exists(dir)){
return;
}
for(boost::filesystem::directory_iterator iter(dir); iter != boost::filesystem::directory_iterator(); ++iter){
std::string fileName = boost::filesystem::path(iter->path().filename()).string();
if(DynamicLibrary::isLibrary(fileName)){
loadPlugin(iter->path().string());
}
}
}
void PluginManager::loadDefaultPlugins()
{
if(d->defaultPluginsLoaded){
return;
}
// list of directories to load plugins from
std::vector<std::string> directories;
// add default plugin directory
#if defined(CHEMKIT_OS_LINUX)
directories.push_back(CHEMKIT_INSTALL_PREFIX "/share/chemkit/plugins/");
#endif
// add directory from the CHEMKIT_PLUGIN_PATH environment variable
const char *path = getenv("CHEMKIT_PLUGIN_PATH");
if(path){
directories.push_back(path);
}
// load plugins from each directory
foreach(const std::string &directory, directories){
loadPlugins(directory);
}
d->defaultPluginsLoaded = true;
}
/// Unloads the plugin.
bool PluginManager::unloadPlugin(Plugin *plugin)
{
if(!plugin){
return false;
}
d->plugins.erase(std::remove(d->plugins.begin(), d->plugins.end(), plugin));
DynamicLibrary *library = plugin->library();
delete plugin;
delete library;
return true;
}
/// Unloads the plugin with \p name.
bool PluginManager::unloadPlugin(const std::string &name)
{
return unloadPlugin(plugin((name)));
}
// --- Error Handling ------------------------------------------------------ //
void PluginManager::setErrorString(const std::string &errorString)
{
d->errorString = errorString;
}
/// Returns a string describing the last error that occured.
std::string PluginManager::errorString() const
{
return d->errorString;
}
// --- Static Methods ------------------------------------------------------ //
/// Returns the instance of the plugin manager.
PluginManager* PluginManager::instance()
{
static PluginManager singleton;
return &singleton;
}
// --- Internal Methods ---------------------------------------------------- //
/// Registers a new plugin function for \p className and
/// \p pluginName.
bool PluginManager::registerPluginClass(const std::string &className, const std::string &pluginName, Function function)
{
std::map<std::string, Function> &classPlugins = d->pluginClasses[className];
// use lower case plugin name
std::string lowerCasePluginName = boost::algorithm::to_lower_copy(pluginName);
// prevent overwriting of previously registered plugins
if(classPlugins.find(lowerCasePluginName) != classPlugins.end()){
return false;
}
// add plugin class
classPlugins[lowerCasePluginName] = function;
return true;
}
/// Unregisters a plugin function for \p className and \p pluginName.
bool PluginManager::unregisterPluginClass(const std::string &className, const std::string &pluginName)
{
std::map<std::string, Function> &classPlugins = d->pluginClasses[className];
// use lower case plugin name
std::string lowerCasePluginName = boost::algorithm::to_lower_copy(pluginName);
// remove plugin class
return classPlugins.erase(lowerCasePluginName) > 0;
}
/// Returns a vector of strings containing the names of registered
/// plugins for \p className.
std::vector<std::string> PluginManager::pluginClassNames(const std::string &className) const
{
// ensure default plugins are loaded
const_cast<PluginManager *>(this)->loadDefaultPlugins();
const std::map<std::string, Function> &classPlugins = d->pluginClasses[className];
std::vector<std::string> names;
for(std::map<std::string, Function>::const_iterator i = classPlugins.begin(); i != classPlugins.end(); ++i){
names.push_back(i->first);
}
return names;
}
/// Returns the registered function for the given \p className and \p pluginName.
PluginManager::Function PluginManager::pluginClassFunction(const std::string &className, const std::string &pluginName) const
{
// ensure default plugins are loaded
const_cast<PluginManager *>(this)->loadDefaultPlugins();
// use lower case plugin name
std::string lowerCasePluginName = boost::algorithm::to_lower_copy(pluginName);
const std::map<std::string, Function> &classPlugins = d->pluginClasses[className];
std::map<std::string, Function>::const_iterator location = classPlugins.find(lowerCasePluginName);
if(location == classPlugins.end()){
return 0;
}
return location->second;
}
} // end chemkit namespace
<commit_msg>Fix PluginManager::loadDefaultPlugins() on unix<commit_after>/******************************************************************************
**
** Copyright (C) 2009-2011 Kyle Lutz <kyle.r.lutz@gmail.com>
** All rights reserved.
**
** This file is a part of the chemkit project. For more information
** see <http://www.chemkit.org>.
**
** 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 chemkit project nor the names of its
** contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
******************************************************************************/
#include "pluginmanager.h"
#include <map>
#include <cstdlib>
#include <iostream>
#include <boost/filesystem.hpp>
#include <boost/algorithm/string/case_conv.hpp>
#include "plugin.h"
#include "foreach.h"
#include "dynamiclibrary.h"
namespace chemkit {
// === PluginManagerPrivate ================================================ //
class PluginManagerPrivate
{
public:
std::vector<Plugin *> plugins;
std::string errorString;
bool defaultPluginsLoaded;
std::map<std::string, std::map<std::string, PluginManager::Function> > pluginClasses;
};
// === PluginManager ======================================================= //
/// \class PluginManager pluginmanager.h chemkit/pluginmanager.h
/// \ingroup chemkit
/// \brief The PluginManager class manages the loading and unloading
/// of plugins.
///
/// \see Plugin
// --- Construction and Destruction ---------------------------------------- //
PluginManager::PluginManager()
: d(new PluginManagerPrivate)
{
d->defaultPluginsLoaded = false;
}
PluginManager::~PluginManager()
{
foreach(Plugin *plugin, d->plugins){
DynamicLibrary *library = plugin->library();
delete plugin;
delete library;
}
delete d;
}
// --- Properties ---------------------------------------------------------- //
/// Returns the plugin with \p name. Returns \c 0 if no plugin with
// \p name is loaded.
Plugin* PluginManager::plugin(const std::string &name) const
{
foreach(Plugin *plugin, d->plugins){
if(plugin->name() == name){
return plugin;
}
}
return 0;
}
/// Returns a list of all the loaded plugins.
const std::vector<Plugin *>& PluginManager::plugins() const
{
return d->plugins;
}
/// Returns the number of loaded plugins.
int PluginManager::pluginCount() const
{
return d->plugins.size();
}
// --- Plugin Loading ------------------------------------------------------ //
/// Loads a plugin from \p fileName. Returns \c false if an error
/// occurs.
bool PluginManager::loadPlugin(const std::string &fileName)
{
DynamicLibrary *library = new DynamicLibrary;
library->setFileName(fileName);
bool ok = library->open();
if(!ok){
std::cerr << "PluginManager: Error: Failed to load plugin: (" << fileName << "):"
<< library->errorString() << std::endl;
return false;
}
typedef Plugin* (*InitFunction)();
InitFunction initFunction = reinterpret_cast<InitFunction>(library->resolve("chemkit_plugin_init"));
if(!initFunction){
std::cerr << "PluginManager: Error: Failed to load plugin: (" << fileName << "):"
<< "Plugin contains no init() function." << std::endl;
return false;
}
Plugin *plugin = initFunction();
if(!plugin){
std::cerr << "PluginManager: Error: Failed to load plugin: (" << fileName << "):"
<< "Calling the plugin's init() function failed." << std::endl;
return false;
}
plugin->setLibrary(library);
d->plugins.push_back(plugin);
return true;
}
/// Loads all plugins from \p directory.
void PluginManager::loadPlugins(const std::string &directory)
{
boost::filesystem::path dir(directory);
if(!boost::filesystem::exists(dir)){
return;
}
for(boost::filesystem::directory_iterator iter(dir); iter != boost::filesystem::directory_iterator(); ++iter){
std::string fileName = boost::filesystem::path(iter->path().filename()).string();
if(DynamicLibrary::isLibrary(fileName)){
loadPlugin(iter->path().string());
}
}
}
void PluginManager::loadDefaultPlugins()
{
if(d->defaultPluginsLoaded){
return;
}
// list of directories to load plugins from
std::vector<std::string> directories;
// add default plugin directory
#if defined(CHEMKIT_OS_UNIX)
directories.push_back(CHEMKIT_INSTALL_PREFIX "/share/chemkit/plugins/");
#endif
// add directory from the CHEMKIT_PLUGIN_PATH environment variable
const char *path = getenv("CHEMKIT_PLUGIN_PATH");
if(path){
directories.push_back(path);
}
// load plugins from each directory
foreach(const std::string &directory, directories){
loadPlugins(directory);
}
d->defaultPluginsLoaded = true;
}
/// Unloads the plugin.
bool PluginManager::unloadPlugin(Plugin *plugin)
{
if(!plugin){
return false;
}
d->plugins.erase(std::remove(d->plugins.begin(), d->plugins.end(), plugin));
DynamicLibrary *library = plugin->library();
delete plugin;
delete library;
return true;
}
/// Unloads the plugin with \p name.
bool PluginManager::unloadPlugin(const std::string &name)
{
return unloadPlugin(plugin((name)));
}
// --- Error Handling ------------------------------------------------------ //
void PluginManager::setErrorString(const std::string &errorString)
{
d->errorString = errorString;
}
/// Returns a string describing the last error that occured.
std::string PluginManager::errorString() const
{
return d->errorString;
}
// --- Static Methods ------------------------------------------------------ //
/// Returns the instance of the plugin manager.
PluginManager* PluginManager::instance()
{
static PluginManager singleton;
return &singleton;
}
// --- Internal Methods ---------------------------------------------------- //
/// Registers a new plugin function for \p className and
/// \p pluginName.
bool PluginManager::registerPluginClass(const std::string &className, const std::string &pluginName, Function function)
{
std::map<std::string, Function> &classPlugins = d->pluginClasses[className];
// use lower case plugin name
std::string lowerCasePluginName = boost::algorithm::to_lower_copy(pluginName);
// prevent overwriting of previously registered plugins
if(classPlugins.find(lowerCasePluginName) != classPlugins.end()){
return false;
}
// add plugin class
classPlugins[lowerCasePluginName] = function;
return true;
}
/// Unregisters a plugin function for \p className and \p pluginName.
bool PluginManager::unregisterPluginClass(const std::string &className, const std::string &pluginName)
{
std::map<std::string, Function> &classPlugins = d->pluginClasses[className];
// use lower case plugin name
std::string lowerCasePluginName = boost::algorithm::to_lower_copy(pluginName);
// remove plugin class
return classPlugins.erase(lowerCasePluginName) > 0;
}
/// Returns a vector of strings containing the names of registered
/// plugins for \p className.
std::vector<std::string> PluginManager::pluginClassNames(const std::string &className) const
{
// ensure default plugins are loaded
const_cast<PluginManager *>(this)->loadDefaultPlugins();
const std::map<std::string, Function> &classPlugins = d->pluginClasses[className];
std::vector<std::string> names;
for(std::map<std::string, Function>::const_iterator i = classPlugins.begin(); i != classPlugins.end(); ++i){
names.push_back(i->first);
}
return names;
}
/// Returns the registered function for the given \p className and \p pluginName.
PluginManager::Function PluginManager::pluginClassFunction(const std::string &className, const std::string &pluginName) const
{
// ensure default plugins are loaded
const_cast<PluginManager *>(this)->loadDefaultPlugins();
// use lower case plugin name
std::string lowerCasePluginName = boost::algorithm::to_lower_copy(pluginName);
const std::map<std::string, Function> &classPlugins = d->pluginClasses[className];
std::map<std::string, Function>::const_iterator location = classPlugins.find(lowerCasePluginName);
if(location == classPlugins.end()){
return 0;
}
return location->second;
}
} // end chemkit namespace
<|endoftext|> |
<commit_before>// Copyright 2015 Google 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 "gsf.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using ::testing::ElementsAre;
using ::testing::ElementsAreArray;
using std::string;
using std::vector;
// TODO(schwehr): Remove iostream.
#include <iostream>
// GSF error value.
// TODO(schwehr): Why is this not in the header?
extern int gsfError;
namespace generic_sensor_format {
namespace {
class PacketCounts {
public:
PacketCounts() : counts_(NUM_REC_TYPES, 0) {}
void add(int packet_num) { ++counts_[packet_num]; }
vector<int> counts_;
void Verify(const vector<int> &expected) {
ASSERT_EQ(NUM_REC_TYPES, expected.size());
for (int i=0; i < NUM_REC_TYPES; ++i) {
EXPECT_EQ(expected[i], counts_[i]);
}
}
};
#if 0
string RecordTypeStr(unsigned int record_id) {
switch (record_id) {
case GSF_RECORD_HEADER:
return "GSF_RECORD_HEADER";
case GSF_RECORD_SWATH_BATHYMETRY_PING:
return "GSF_RECORD_SWATH_BATHYMETRY_PING";
case GSF_RECORD_SOUND_VELOCITY_PROFILE:
return "GSF_RECORD_SOUND_VELOCITY_PROFILE";
case GSF_RECORD_PROCESSING_PARAMETERS:
return "GSF_RECORD_PROCESSING_PARAMETERS";
case GSF_RECORD_SENSOR_PARAMETERS:
return "GSF_RECORD_SENSOR_PARAMETERS";
case GSF_RECORD_COMMENT:
return "GSF_RECORD_COMMENT";
case GSF_RECORD_HISTORY:
return "GSF_RECORD_HISTORY";
case GSF_RECORD_NAVIGATION_ERROR:
return "GSF_RECORD_NAVIGATION_ERROR";
case GSF_RECORD_SWATH_BATHY_SUMMARY:
return "GSF_RECORD_SWATH_BATHY_SUMMARY";
case GSF_RECORD_SINGLE_BEAM_PING:
return "GSF_RECORD_SINGLE_BEAM_PING";
case GSF_RECORD_HV_NAVIGATION_ERROR:
return "GSF_RECORD_HV_NAVIGATION_ERROR";
case GSF_RECORD_ATTITUDE:
return "GSF_RECORD_ATTITUDE";
}
return "UNKNOWN";
}
#endif
TEST(GsfRead2_9Test, CountPackets) {
int handle;
ASSERT_EQ(0, gsfOpen("../data/6_184_1440.mb121", GSF_READONLY, &handle));
ASSERT_GE(handle, 0);
gsfDataID data_id;
gsfRecords records;
int num_bytes;
num_bytes = gsfRead(handle, GSF_NEXT_RECORD, &data_id, &records, nullptr, 0);
PacketCounts counts;
while (num_bytes >= 0) {
counts.add(data_id.recordID);
num_bytes
= gsfRead(handle, GSF_NEXT_RECORD, &data_id, &records, nullptr, 0);
}
ASSERT_EQ(GSF_READ_TO_END_OF_FILE, gsfError);
counts.Verify({0, 0, 132, 21, 1, 0, 2, 1, 0, 1, 0, 0, 132});
}
TEST(GsfReadTest, ReadVersion2_9) {
int handle;
ASSERT_EQ(0, gsfOpen("../data/6_184_1440.mb121", GSF_READONLY, &handle));
ASSERT_GE(handle, 0);
gsfDataID data_id;
gsfRecords records;
int num_bytes;
num_bytes = gsfRead(handle, GSF_NEXT_RECORD, &data_id, &records, nullptr, 0);
ASSERT_EQ(48, num_bytes);
ASSERT_FALSE(data_id.checksumFlag);
ASSERT_EQ(0, data_id.reserved);
ASSERT_EQ(9, data_id.recordID);
ASSERT_EQ(GSF_RECORD_SWATH_BATHY_SUMMARY, data_id.recordID);
// TODO(schwehr): Why does this sometimes fail?
// ASSERT_EQ(0, data_id.record_number);
ASSERT_EQ(947169642, records.summary.start_time.tv_sec);
ASSERT_EQ(799999952, records.summary.start_time.tv_nsec);
ASSERT_EQ(947171370, records.summary.end_time.tv_sec);
ASSERT_EQ(700000047, records.summary.end_time.tv_nsec);
ASSERT_DOUBLE_EQ(37.963955, records.summary.min_latitude);
ASSERT_DOUBLE_EQ(-76.3502001, records.summary.min_longitude);
ASSERT_DOUBLE_EQ(38.0030681, records.summary.max_latitude);
ASSERT_DOUBLE_EQ(-76.2895285, records.summary.max_longitude);
ASSERT_DOUBLE_EQ(12.12, records.summary.min_depth);
ASSERT_DOUBLE_EQ(13.12, records.summary.max_depth);
int count = 0;
++count;
num_bytes = gsfRead(handle, GSF_NEXT_RECORD, &data_id, &records, nullptr, 0);
ASSERT_EQ(84, num_bytes);
ASSERT_FALSE(data_id.checksumFlag);
ASSERT_EQ(0, data_id.reserved);
ASSERT_EQ(6, data_id.recordID);
ASSERT_EQ(GSF_RECORD_COMMENT, data_id.recordID);
// ASSERT_EQ(-2, data_id.record_number);
ASSERT_EQ(947169642, records.comment.comment_time.tv_sec);
ASSERT_EQ(799999952, records.comment.comment_time.tv_nsec);
ASSERT_STREQ("Bathy converted from HIPS file: B_SB BH_SB 2000-001 6_184_1440",
records.comment.comment);
++count;
num_bytes = gsfRead(handle, GSF_NEXT_RECORD, &data_id, &records, nullptr, 0);
ASSERT_EQ(988, num_bytes);
ASSERT_FALSE(data_id.checksumFlag);
ASSERT_EQ(0, data_id.reserved);
ASSERT_EQ(4, data_id.recordID);
ASSERT_EQ(GSF_RECORD_PROCESSING_PARAMETERS, data_id.recordID);
// ASSERT_EQ(-2, data_id.record_number);
++count;
num_bytes = gsfRead(handle, GSF_NEXT_RECORD, &data_id, &records, nullptr, 0);
ASSERT_EQ(212, num_bytes);
ASSERT_FALSE(data_id.checksumFlag);
ASSERT_EQ(0, data_id.reserved);
ASSERT_EQ(3, data_id.recordID);
ASSERT_EQ(GSF_RECORD_SOUND_VELOCITY_PROFILE, data_id.recordID);
// ASSERT_EQ(-2, data_id.record_number);
++count;
num_bytes = gsfRead(handle, GSF_NEXT_RECORD, &data_id, &records, nullptr, 0);
ASSERT_EQ(68, num_bytes);
ASSERT_FALSE(data_id.checksumFlag);
ASSERT_EQ(0, data_id.reserved);
ASSERT_EQ(6, data_id.recordID);
ASSERT_EQ(GSF_RECORD_COMMENT, data_id.recordID);
// ASSERT_EQ(-2, data_id.record_number);
ASSERT_EQ(947169629, records.comment.comment_time.tv_sec);
ASSERT_EQ(799999952, records.comment.comment_time.tv_nsec);
ASSERT_STREQ("SVP_FILE_NAME: D:\\hips\\Svp\\SheetB\\all_Bsheet.svp",
records.comment.comment);
for (; count < 40; ++count) {
num_bytes =
gsfRead(handle, GSF_NEXT_RECORD, &data_id, &records, nullptr, 0);
ASSERT_GE(num_bytes, 0);
}
++count;
num_bytes = gsfRead(handle, GSF_NEXT_RECORD, &data_id, &records, nullptr, 0);
ASSERT_EQ(28, num_bytes);
ASSERT_FALSE(data_id.checksumFlag);
ASSERT_EQ(0, data_id.reserved);
ASSERT_EQ(GSF_RECORD_ATTITUDE, data_id.recordID);
++count;
num_bytes = gsfRead(handle, GSF_NEXT_RECORD, &data_id, &records, nullptr, 0);
ASSERT_EQ(412, num_bytes);
ASSERT_FALSE(data_id.checksumFlag);
ASSERT_EQ(0, data_id.reserved);
ASSERT_EQ(GSF_RECORD_SWATH_BATHYMETRY_PING, data_id.recordID);
for (; count < 288; ++count) {
num_bytes =
gsfRead(handle, GSF_NEXT_RECORD, &data_id, &records, nullptr, 0);
ASSERT_GE(num_bytes, 0);
#if 0
std::cout << "rec: count: " << count
<< " #" << data_id.record_number
<< " id: " << data_id.recordID
<< " size: " << num_bytes
<< " --> " << RecordTypeStr(data_id.recordID)
<< "\n";
#endif
}
++count;
num_bytes = gsfRead(handle, GSF_NEXT_RECORD, &data_id, &records, nullptr, 0);
ASSERT_EQ(60, num_bytes);
ASSERT_FALSE(data_id.checksumFlag);
ASSERT_EQ(0, data_id.reserved);
ASSERT_EQ(GSF_RECORD_HISTORY, data_id.recordID);
ASSERT_EQ(1253181992, records.history.history_time.tv_sec);
ASSERT_EQ(0, records.history.history_time.tv_nsec);
ASSERT_STREQ("PIXAR", records.history.host_name);
ASSERT_STREQ("ltyson", records.history.operator_name);
ASSERT_STREQ("HIPStoGSF", records.history.command_line);
ASSERT_STREQ("version 6.1", records.history.comment);
num_bytes = gsfRead(handle, GSF_NEXT_RECORD, &data_id, &records, nullptr, 0);
ASSERT_EQ(-1, num_bytes);
ASSERT_EQ(GSF_READ_TO_END_OF_FILE, gsfError);
}
} // namespace
} // namespace generic_sensor_format
<commit_msg>Check the attitude packet and start on swath ping.<commit_after>// Copyright 2015 Google 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 "gsf.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using ::testing::ElementsAre;
using ::testing::ElementsAreArray;
using std::string;
using std::vector;
// TODO(schwehr): Remove iostream.
#include <iostream>
// GSF error value.
// TODO(schwehr): Why is this not in the header?
extern int gsfError;
namespace generic_sensor_format {
namespace {
class PacketCounts {
public:
PacketCounts() : counts_(NUM_REC_TYPES, 0) {}
void add(int packet_num) { ++counts_[packet_num]; }
vector<int> counts_;
void Verify(const vector<int> &expected) {
ASSERT_EQ(NUM_REC_TYPES, expected.size());
for (int i=0; i < NUM_REC_TYPES; ++i) {
EXPECT_EQ(expected[i], counts_[i]);
}
}
};
#if 0
string RecordTypeStr(unsigned int record_id) {
switch (record_id) {
case GSF_RECORD_HEADER:
return "GSF_RECORD_HEADER";
case GSF_RECORD_SWATH_BATHYMETRY_PING:
return "GSF_RECORD_SWATH_BATHYMETRY_PING";
case GSF_RECORD_SOUND_VELOCITY_PROFILE:
return "GSF_RECORD_SOUND_VELOCITY_PROFILE";
case GSF_RECORD_PROCESSING_PARAMETERS:
return "GSF_RECORD_PROCESSING_PARAMETERS";
case GSF_RECORD_SENSOR_PARAMETERS:
return "GSF_RECORD_SENSOR_PARAMETERS";
case GSF_RECORD_COMMENT:
return "GSF_RECORD_COMMENT";
case GSF_RECORD_HISTORY:
return "GSF_RECORD_HISTORY";
case GSF_RECORD_NAVIGATION_ERROR:
return "GSF_RECORD_NAVIGATION_ERROR";
case GSF_RECORD_SWATH_BATHY_SUMMARY:
return "GSF_RECORD_SWATH_BATHY_SUMMARY";
case GSF_RECORD_SINGLE_BEAM_PING:
return "GSF_RECORD_SINGLE_BEAM_PING";
case GSF_RECORD_HV_NAVIGATION_ERROR:
return "GSF_RECORD_HV_NAVIGATION_ERROR";
case GSF_RECORD_ATTITUDE:
return "GSF_RECORD_ATTITUDE";
}
return "UNKNOWN";
}
#endif
TEST(GsfRead2_9Test, CountPackets) {
int handle;
ASSERT_EQ(0, gsfOpen("../data/6_184_1440.mb121", GSF_READONLY, &handle));
ASSERT_GE(handle, 0);
gsfDataID data_id;
gsfRecords records;
int num_bytes;
num_bytes = gsfRead(handle, GSF_NEXT_RECORD, &data_id, &records, nullptr, 0);
PacketCounts counts;
while (num_bytes >= 0) {
counts.add(data_id.recordID);
num_bytes
= gsfRead(handle, GSF_NEXT_RECORD, &data_id, &records, nullptr, 0);
}
ASSERT_EQ(GSF_READ_TO_END_OF_FILE, gsfError);
counts.Verify({0, 0, 132, 21, 1, 0, 2, 1, 0, 1, 0, 0, 132});
}
TEST(GsfReadTest, ReadVersion2_9) {
int handle;
ASSERT_EQ(0, gsfOpen("../data/6_184_1440.mb121", GSF_READONLY, &handle));
ASSERT_GE(handle, 0);
gsfDataID data_id;
gsfRecords records;
int num_bytes;
num_bytes = gsfRead(handle, GSF_NEXT_RECORD, &data_id, &records, nullptr, 0);
ASSERT_EQ(48, num_bytes);
ASSERT_FALSE(data_id.checksumFlag);
ASSERT_EQ(0, data_id.reserved);
ASSERT_EQ(9, data_id.recordID);
ASSERT_EQ(GSF_RECORD_SWATH_BATHY_SUMMARY, data_id.recordID);
// TODO(schwehr): Why does this sometimes fail?
// ASSERT_EQ(0, data_id.record_number);
ASSERT_EQ(947169642, records.summary.start_time.tv_sec);
ASSERT_EQ(799999952, records.summary.start_time.tv_nsec);
ASSERT_EQ(947171370, records.summary.end_time.tv_sec);
ASSERT_EQ(700000047, records.summary.end_time.tv_nsec);
ASSERT_DOUBLE_EQ(37.963955, records.summary.min_latitude);
ASSERT_DOUBLE_EQ(-76.3502001, records.summary.min_longitude);
ASSERT_DOUBLE_EQ(38.0030681, records.summary.max_latitude);
ASSERT_DOUBLE_EQ(-76.2895285, records.summary.max_longitude);
ASSERT_DOUBLE_EQ(12.12, records.summary.min_depth);
ASSERT_DOUBLE_EQ(13.12, records.summary.max_depth);
int count = 0;
++count;
num_bytes = gsfRead(handle, GSF_NEXT_RECORD, &data_id, &records, nullptr, 0);
ASSERT_EQ(84, num_bytes);
ASSERT_FALSE(data_id.checksumFlag);
ASSERT_EQ(0, data_id.reserved);
ASSERT_EQ(6, data_id.recordID);
ASSERT_EQ(GSF_RECORD_COMMENT, data_id.recordID);
// ASSERT_EQ(-2, data_id.record_number);
ASSERT_EQ(947169642, records.comment.comment_time.tv_sec);
ASSERT_EQ(799999952, records.comment.comment_time.tv_nsec);
ASSERT_STREQ("Bathy converted from HIPS file: B_SB BH_SB 2000-001 6_184_1440",
records.comment.comment);
++count;
num_bytes = gsfRead(handle, GSF_NEXT_RECORD, &data_id, &records, nullptr, 0);
ASSERT_EQ(988, num_bytes);
ASSERT_FALSE(data_id.checksumFlag);
ASSERT_EQ(0, data_id.reserved);
ASSERT_EQ(4, data_id.recordID);
ASSERT_EQ(GSF_RECORD_PROCESSING_PARAMETERS, data_id.recordID);
// ASSERT_EQ(-2, data_id.record_number);
++count;
num_bytes = gsfRead(handle, GSF_NEXT_RECORD, &data_id, &records, nullptr, 0);
ASSERT_EQ(212, num_bytes);
ASSERT_FALSE(data_id.checksumFlag);
ASSERT_EQ(0, data_id.reserved);
ASSERT_EQ(3, data_id.recordID);
ASSERT_EQ(GSF_RECORD_SOUND_VELOCITY_PROFILE, data_id.recordID);
// ASSERT_EQ(-2, data_id.record_number);
++count;
num_bytes = gsfRead(handle, GSF_NEXT_RECORD, &data_id, &records, nullptr, 0);
ASSERT_EQ(68, num_bytes);
ASSERT_FALSE(data_id.checksumFlag);
ASSERT_EQ(0, data_id.reserved);
ASSERT_EQ(6, data_id.recordID);
ASSERT_EQ(GSF_RECORD_COMMENT, data_id.recordID);
// ASSERT_EQ(-2, data_id.record_number);
ASSERT_EQ(947169629, records.comment.comment_time.tv_sec);
ASSERT_EQ(799999952, records.comment.comment_time.tv_nsec);
ASSERT_STREQ("SVP_FILE_NAME: D:\\hips\\Svp\\SheetB\\all_Bsheet.svp",
records.comment.comment);
for (; count < 40; ++count) {
num_bytes =
gsfRead(handle, GSF_NEXT_RECORD, &data_id, &records, nullptr, 0);
ASSERT_GE(num_bytes, 0);
}
++count;
num_bytes = gsfRead(handle, GSF_NEXT_RECORD, &data_id, &records, nullptr, 0);
ASSERT_EQ(28, num_bytes);
ASSERT_FALSE(data_id.checksumFlag);
ASSERT_EQ(0, data_id.reserved);
ASSERT_EQ(GSF_RECORD_ATTITUDE, data_id.recordID);
ASSERT_EQ(1, records.attitude.num_measurements);
ASSERT_EQ(947169765, records.attitude.attitude_time[0].tv_sec);
ASSERT_EQ(600000023, records.attitude.attitude_time[0].tv_nsec);
ASSERT_DOUBLE_EQ(-1.0, records.attitude.pitch[0]);
ASSERT_DOUBLE_EQ(-1.0, records.attitude.roll[0]);
ASSERT_DOUBLE_EQ(0.08, records.attitude.heave[0]);
ASSERT_DOUBLE_EQ(127.0, records.attitude.heading[0]);
++count;
num_bytes = gsfRead(handle, GSF_NEXT_RECORD, &data_id, &records, nullptr, 0);
ASSERT_EQ(412, num_bytes);
ASSERT_FALSE(data_id.checksumFlag);
ASSERT_EQ(0, data_id.reserved);
ASSERT_EQ(GSF_RECORD_SWATH_BATHYMETRY_PING, data_id.recordID);
ASSERT_EQ(947169765, records.mb_ping.ping_time.tv_sec);
ASSERT_EQ(600000023, records.mb_ping.ping_time.tv_nsec);
EXPECT_DOUBLE_EQ(38.0007082, records.mb_ping.latitude);
EXPECT_DOUBLE_EQ(-76.3465419, records.mb_ping.longitude);
EXPECT_DOUBLE_EQ(9999.9899999999998, records.mb_ping.height);
EXPECT_DOUBLE_EQ(9999.9899999999998, records.mb_ping.sep);
EXPECT_EQ(1, records.mb_ping.number_beams);
EXPECT_EQ(1, records.mb_ping.center_beam);
EXPECT_EQ(0, records.mb_ping.ping_flags);
EXPECT_EQ(0, records.mb_ping.reserved);
EXPECT_DOUBLE_EQ(-0.1, records.mb_ping.tide_corrector);
EXPECT_DOUBLE_EQ(99.989999999999995, records.mb_ping.gps_tide_corrector);
EXPECT_DOUBLE_EQ(99.989999999999995, records.mb_ping.depth_corrector);
EXPECT_DOUBLE_EQ(127, records.mb_ping.heading);
EXPECT_DOUBLE_EQ(-1.0, records.mb_ping.pitch);
EXPECT_DOUBLE_EQ(-1.0, records.mb_ping.roll);
EXPECT_DOUBLE_EQ(0.08, records.mb_ping.heave);
EXPECT_DOUBLE_EQ(131.41, records.mb_ping.course);
EXPECT_DOUBLE_EQ(6.04, records.mb_ping.speed);
ASSERT_EQ(26, records.mb_ping.scaleFactors.numArraySubrecords);
EXPECT_EQ(32, records.mb_ping.scaleFactors.scaleTable[0].compressionFlag);
EXPECT_DOUBLE_EQ(
10000, records.mb_ping.scaleFactors.scaleTable[0].multiplier);
EXPECT_DOUBLE_EQ(-13, records.mb_ping.scaleFactors.scaleTable[0].offset);
// double *depth;
// double *nominal_depth;
// double *across_track;
// double *along_track;
// double *travel_time;
// double *beam_angle;
// double *mc_amplitude;
// double *mr_amplitude;
// double *echo_width;
// double *quality_factor;
// double *receive_heave;
// double *depth_error;
// double *across_track_error;
// double *along_track_error;
// unsigned char *quality_flags;
// unsigned char *beam_flags;
// double *signal_to_noise;
// double *beam_angle_forward;
// double *vertical_error;
// double *horizontal_error;
// unsigned short *sector_number;
// unsigned short *detection_info;
// double *incident_beam_adj;
// unsigned short *system_cleaning;
// double *doppler_corr;
// double *sonar_vert_uncert;
// int sensor_id;
// gsfSensorSpecific sensor_data;
// gsfBRBIntensity *brb_inten;
for (; count < 288; ++count) {
num_bytes =
gsfRead(handle, GSF_NEXT_RECORD, &data_id, &records, nullptr, 0);
ASSERT_GE(num_bytes, 0);
#if 0
std::cout << "rec: count: " << count
<< " #" << data_id.record_number
<< " id: " << data_id.recordID
<< " size: " << num_bytes
<< " --> " << RecordTypeStr(data_id.recordID)
<< "\n";
#endif
}
++count;
num_bytes = gsfRead(handle, GSF_NEXT_RECORD, &data_id, &records, nullptr, 0);
ASSERT_EQ(60, num_bytes);
ASSERT_FALSE(data_id.checksumFlag);
ASSERT_EQ(0, data_id.reserved);
ASSERT_EQ(GSF_RECORD_HISTORY, data_id.recordID);
ASSERT_EQ(1253181992, records.history.history_time.tv_sec);
ASSERT_EQ(0, records.history.history_time.tv_nsec);
ASSERT_STREQ("PIXAR", records.history.host_name);
ASSERT_STREQ("ltyson", records.history.operator_name);
ASSERT_STREQ("HIPStoGSF", records.history.command_line);
ASSERT_STREQ("version 6.1", records.history.comment);
num_bytes = gsfRead(handle, GSF_NEXT_RECORD, &data_id, &records, nullptr, 0);
ASSERT_EQ(-1, num_bytes);
ASSERT_EQ(GSF_READ_TO_END_OF_FILE, gsfError);
}
} // namespace
} // namespace generic_sensor_format
<|endoftext|> |
<commit_before>/*
* Launch WAS child processes.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "was_launch.hxx"
#include "system/fd_util.h"
#include "system/fd-util.h"
#include "system/sigutil.h"
#include "spawn/Spawn.hxx"
#include "spawn/Prepared.hxx"
#include "spawn/ChildOptions.hxx"
#include "gerrno.h"
#include "util/ConstBuffer.hxx"
#include <daemon/log.h>
#include <inline/compiler.h>
#include <sys/socket.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#ifdef __linux
#include <sched.h>
#endif
void
WasProcess::Close()
{
if (control_fd >= 0) {
close(control_fd);
control_fd = -1;
}
if (input_fd >= 0) {
close(input_fd);
input_fd = -1;
}
if (output_fd >= 0) {
close(output_fd);
output_fd = -1;
}
}
struct was_run_args {
sigset_t signals;
const ChildOptions *options;
int control_fd, input_fd, output_fd;
const char *executable_path;
ConstBuffer<const char *> args;
ConstBuffer<const char *> env;
};
gcc_noreturn
static int
was_run(void *ctx)
{
struct was_run_args *args = (struct was_run_args *)ctx;
install_default_signal_handlers();
leave_signal_section(&args->signals);
args->options->Apply();
dup2(args->input_fd, 0);
dup2(args->output_fd, 1);
/* fd2 is retained */
dup2(args->control_fd, 3);
PreparedChildProcess exec;
exec.Append(args->executable_path);
for (auto i : args->args)
exec.Append(i);
for (auto i : args->env)
exec.PutEnv(i);
args->options->jail.InsertWrapper(exec, nullptr);
Exec(std::move(exec));
}
bool
was_launch(WasProcess *process,
const char *executable_path,
ConstBuffer<const char *> args,
ConstBuffer<const char *> env,
const ChildOptions &options,
GError **error_r)
{
int control_fds[2], input_fds[2], output_fds[2];
if (socketpair_cloexec(AF_UNIX, SOCK_STREAM, 0, control_fds) < 0) {
set_error_errno_msg(error_r, "failed to create socket pair");
return false;
}
if (pipe_cloexec(input_fds) < 0) {
set_error_errno_msg(error_r, "failed to create first pipe");
close(control_fds[0]);
close(control_fds[1]);
return false;
}
if (pipe_cloexec(output_fds) < 0) {
set_error_errno_msg(error_r, "failed to create second pipe");
close(control_fds[0]);
close(control_fds[1]);
close(input_fds[0]);
close(input_fds[1]);
return false;
}
struct was_run_args run_args = {
.signals = sigset_t(),
.options = &options,
.control_fd = control_fds[1],
.input_fd = output_fds[0],
.output_fd = input_fds[1],
.executable_path = executable_path,
.args = args,
.env = env,
};
int clone_flags = SIGCHLD;
clone_flags = options.ns.GetCloneFlags(clone_flags);
/* avoid race condition due to libevent signal handler in child
process */
enter_signal_section(&run_args.signals);
char stack[8192];
long pid = clone(was_run, stack + sizeof(stack),
clone_flags, &run_args);
if (pid < 0) {
leave_signal_section(&run_args.signals);
set_error_errno_msg(error_r, "clone() failed");
close(control_fds[0]);
close(control_fds[1]);
close(input_fds[0]);
close(input_fds[1]);
close(output_fds[0]);
close(output_fds[1]);
return false;
}
leave_signal_section(&run_args.signals);
close(control_fds[1]);
close(input_fds[1]);
close(output_fds[0]);
fd_set_nonblock(input_fds[0], true);
fd_set_nonblock(output_fds[1], true);
process->pid = pid;
process->control_fd = control_fds[0];
process->input_fd = input_fds[0];
process->output_fd = output_fds[1];
return true;
}
<commit_msg>was/launch: use PreparedChildProcess::*_fd<commit_after>/*
* Launch WAS child processes.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "was_launch.hxx"
#include "system/fd_util.h"
#include "system/fd-util.h"
#include "system/sigutil.h"
#include "spawn/Spawn.hxx"
#include "spawn/Prepared.hxx"
#include "spawn/ChildOptions.hxx"
#include "gerrno.h"
#include "util/ConstBuffer.hxx"
#include <daemon/log.h>
#include <inline/compiler.h>
#include <sys/socket.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#ifdef __linux
#include <sched.h>
#endif
void
WasProcess::Close()
{
if (control_fd >= 0) {
close(control_fd);
control_fd = -1;
}
if (input_fd >= 0) {
close(input_fd);
input_fd = -1;
}
if (output_fd >= 0) {
close(output_fd);
output_fd = -1;
}
}
struct was_run_args {
sigset_t signals;
const ChildOptions *options;
int control_fd, input_fd, output_fd;
const char *executable_path;
ConstBuffer<const char *> args;
ConstBuffer<const char *> env;
};
gcc_noreturn
static int
was_run(void *ctx)
{
struct was_run_args *args = (struct was_run_args *)ctx;
install_default_signal_handlers();
leave_signal_section(&args->signals);
args->options->Apply();
PreparedChildProcess exec;
exec.stdin_fd = args->input_fd;
exec.stdout_fd = args->output_fd;
/* fd2 is retained */
exec.control_fd = args->control_fd;
exec.Append(args->executable_path);
for (auto i : args->args)
exec.Append(i);
for (auto i : args->env)
exec.PutEnv(i);
args->options->jail.InsertWrapper(exec, nullptr);
Exec(std::move(exec));
}
bool
was_launch(WasProcess *process,
const char *executable_path,
ConstBuffer<const char *> args,
ConstBuffer<const char *> env,
const ChildOptions &options,
GError **error_r)
{
int control_fds[2], input_fds[2], output_fds[2];
if (socketpair_cloexec(AF_UNIX, SOCK_STREAM, 0, control_fds) < 0) {
set_error_errno_msg(error_r, "failed to create socket pair");
return false;
}
if (pipe_cloexec(input_fds) < 0) {
set_error_errno_msg(error_r, "failed to create first pipe");
close(control_fds[0]);
close(control_fds[1]);
return false;
}
if (pipe_cloexec(output_fds) < 0) {
set_error_errno_msg(error_r, "failed to create second pipe");
close(control_fds[0]);
close(control_fds[1]);
close(input_fds[0]);
close(input_fds[1]);
return false;
}
struct was_run_args run_args = {
.signals = sigset_t(),
.options = &options,
.control_fd = control_fds[1],
.input_fd = output_fds[0],
.output_fd = input_fds[1],
.executable_path = executable_path,
.args = args,
.env = env,
};
int clone_flags = SIGCHLD;
clone_flags = options.ns.GetCloneFlags(clone_flags);
/* avoid race condition due to libevent signal handler in child
process */
enter_signal_section(&run_args.signals);
char stack[8192];
long pid = clone(was_run, stack + sizeof(stack),
clone_flags, &run_args);
if (pid < 0) {
leave_signal_section(&run_args.signals);
set_error_errno_msg(error_r, "clone() failed");
close(control_fds[0]);
close(control_fds[1]);
close(input_fds[0]);
close(input_fds[1]);
close(output_fds[0]);
close(output_fds[1]);
return false;
}
leave_signal_section(&run_args.signals);
close(control_fds[1]);
close(input_fds[1]);
close(output_fds[0]);
fd_set_nonblock(input_fds[0], true);
fd_set_nonblock(output_fds[1], true);
process->pid = pid;
process->control_fd = control_fds[0];
process->input_fd = input_fds[0];
process->output_fd = output_fds[1];
return true;
}
<|endoftext|> |
<commit_before>/*
* Web Application Socket client.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "was_server.hxx"
#include "was_quark.h"
#include "was_control.hxx"
#include "was_output.hxx"
#include "was_input.hxx"
#include "http_response.hxx"
#include "async.hxx"
#include "direct.hxx"
#include "istream/istream.hxx"
#include "istream/istream_null.hxx"
#include "strmap.hxx"
#include "pool.hxx"
#include "util/ConstBuffer.hxx"
#include <was/protocol.h>
#include <daemon/log.h>
#include <errno.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
struct WasServer final : WasControlHandler {
struct pool *const pool;
const int control_fd, input_fd, output_fd;
WasControl *control;
WasServerHandler &handler;
struct {
struct pool *pool = nullptr;
http_method_t method;
const char *uri;
/**
* Request headers being assembled. This pointer is set to
* nullptr before before the request is dispatched to the
* handler.
*/
struct strmap *headers;
WasInput *body;
bool pending = false;
} request;
struct {
http_status_t status;
WasOutput *body;
} response;
WasServer(struct pool &_pool,
int _control_fd, int _input_fd, int _output_fd,
WasServerHandler &_handler)
:pool(&_pool),
control_fd(_control_fd), input_fd(_input_fd), output_fd(_output_fd),
control(was_control_new(pool, control_fd, *this)),
handler(_handler) {}
void CloseFiles() {
close(control_fd);
close(input_fd);
close(output_fd);
}
void ReleaseError(GError *error);
void ReleaseUnused();
/**
* Abort receiving the response status/headers from the WAS server.
*/
void AbortError(GError *error) {
ReleaseError(error);
handler.OnWasClosed();
}
/**
* Abort receiving the response status/headers from the WAS server.
*/
void AbortUnused() {
ReleaseUnused();
handler.OnWasClosed();
}
/* virtual methods from class WasControlHandler */
bool OnWasControlPacket(enum was_command cmd,
ConstBuffer<void> payload) override;
bool OnWasControlDrained() override {
if (request.pending) {
auto *headers = request.headers;
request.headers = nullptr;
Istream *body = nullptr;
if (request.body != nullptr)
body = &was_input_enable(*request.body);
handler.OnWasRequest(*request.pool, request.method,
request.uri, std::move(*headers),
body);
/* XXX check if connection has been closed */
}
return true;
}
void OnWasControlDone() override {
control = nullptr;
}
void OnWasControlError(GError *error) override;
};
void
WasServer::ReleaseError(GError *error)
{
if (control != nullptr) {
was_control_free(control);
control = nullptr;
}
if (request.pool != nullptr) {
if (request.body != nullptr)
was_input_free_p(&request.body, error);
else
g_error_free(error);
if (request.headers == nullptr && response.body != nullptr)
was_output_free_p(&response.body);
pool_unref(request.pool);
} else
g_error_free(error);
CloseFiles();
}
void
WasServer::ReleaseUnused()
{
if (control != nullptr) {
was_control_free(control);
control = nullptr;
}
if (request.pool != nullptr) {
if (request.body != nullptr)
was_input_free_unused_p(&request.body);
if (request.headers == nullptr && response.body != nullptr)
was_output_free_p(&response.body);
pool_unref(request.pool);
}
CloseFiles();
}
/*
* Output handler
*/
static bool
was_server_output_length(uint64_t length, void *ctx)
{
WasServer *server = (WasServer *)ctx;
assert(server->control != nullptr);
assert(server->response.body != nullptr);
return was_control_send_uint64(server->control,
WAS_COMMAND_LENGTH, length);
}
static bool
was_server_output_premature(uint64_t length, GError *error, void *ctx)
{
WasServer *server = (WasServer *)ctx;
if (server->control == nullptr)
/* this can happen if was_input_free() call destroys the
WasOutput instance; this check means to work around this
circular call */
return true;
assert(server->response.body != nullptr);
server->response.body = nullptr;
/* XXX send PREMATURE, recover */
(void)length;
server->AbortError(error);
return false;
}
static void
was_server_output_eof(void *ctx)
{
WasServer *server = (WasServer *)ctx;
assert(server->response.body != nullptr);
server->response.body = nullptr;
}
static void
was_server_output_abort(GError *error, void *ctx)
{
WasServer *server = (WasServer *)ctx;
assert(server->response.body != nullptr);
server->response.body = nullptr;
server->AbortError(error);
}
static constexpr WasOutputHandler was_server_output_handler = {
.length = was_server_output_length,
.premature = was_server_output_premature,
.eof = was_server_output_eof,
.abort = was_server_output_abort,
};
/*
* Input handler
*/
static void
was_server_input_close(void *ctx)
{
WasServer *server = (WasServer *)ctx;
/* this happens when the request handler isn't interested in the
request body */
assert(server->request.headers == nullptr);
assert(server->request.body != nullptr);
server->request.body = nullptr;
if (server->control != nullptr)
was_control_send_empty(server->control, WAS_COMMAND_STOP);
// TODO: handle PREMATURE packet which we'll receive soon
}
static void
was_server_input_eof(void *ctx)
{
WasServer *server = (WasServer *)ctx;
assert(server->request.headers == nullptr);
assert(server->request.body != nullptr);
server->request.body = nullptr;
// XXX
}
static void
was_server_input_abort(void *ctx)
{
WasServer *server = (WasServer *)ctx;
assert(server->request.headers == nullptr);
assert(server->request.body != nullptr);
server->request.body = nullptr;
server->AbortUnused();
}
static constexpr WasInputHandler was_server_input_handler = {
.close = was_server_input_close,
.eof = was_server_input_eof,
.premature = was_server_input_abort, // TODO: implement
.abort = was_server_input_abort,
};
/*
* Control channel handler
*/
bool
WasServer::OnWasControlPacket(enum was_command cmd, ConstBuffer<void> payload)
{
GError *error;
switch (cmd) {
const uint64_t *length_p;
const char *p;
http_method_t method;
case WAS_COMMAND_NOP:
break;
case WAS_COMMAND_REQUEST:
if (request.pool != nullptr) {
error = g_error_new_literal(was_quark(), 0,
"misplaced REQUEST packet");
AbortError(error);
return false;
}
request.pool = pool_new_linear(pool, "was_server_request", 32768);
request.method = HTTP_METHOD_GET;
request.uri = nullptr;
request.headers = strmap_new(request.pool);
request.body = nullptr;
response.body = nullptr;
break;
case WAS_COMMAND_METHOD:
if (payload.size != sizeof(method)) {
error = g_error_new_literal(was_quark(), 0,
"malformed METHOD packet");
AbortError(error);
return false;
}
method = *(const http_method_t *)payload.data;
if (request.method != HTTP_METHOD_GET &&
method != request.method) {
/* sending that packet twice is illegal */
error = g_error_new_literal(was_quark(), 0,
"misplaced METHOD packet");
AbortError(error);
return false;
}
if (!http_method_is_valid(method)) {
error = g_error_new_literal(was_quark(), 0,
"invalid METHOD packet");
AbortError(error);
return false;
}
request.method = method;
break;
case WAS_COMMAND_URI:
if (request.pool == nullptr || request.uri != nullptr) {
error = g_error_new_literal(was_quark(), 0,
"misplaced URI packet");
AbortError(error);
return false;
}
request.uri = p_strndup(request.pool,
(const char *)payload.data, payload.size);
break;
case WAS_COMMAND_SCRIPT_NAME:
case WAS_COMMAND_PATH_INFO:
case WAS_COMMAND_QUERY_STRING:
// XXX
break;
case WAS_COMMAND_HEADER:
if (request.pool == nullptr || request.headers == nullptr) {
error = g_error_new_literal(was_quark(), 0,
"misplaced HEADER packet");
AbortError(error);
return false;
}
p = (const char *)memchr(payload.data, '=', payload.size);
if (p == nullptr) {
error = g_error_new_literal(was_quark(), 0,
"malformed HEADER packet");
AbortError(error);
return false;
}
// XXX parse buffer
break;
case WAS_COMMAND_PARAMETER:
// XXX
break;
case WAS_COMMAND_STATUS:
error = g_error_new_literal(was_quark(), 0,
"misplaced STATUS packet");
AbortError(error);
return false;
case WAS_COMMAND_NO_DATA:
if (request.pool == nullptr || request.uri == nullptr ||
request.headers == nullptr) {
error = g_error_new_literal(was_quark(), 0,
"misplaced NO_DATA packet");
AbortError(error);
return false;
}
request.body = nullptr;
request.pending = true;
break;
case WAS_COMMAND_DATA:
if (request.pool == nullptr || request.uri == nullptr ||
request.headers == nullptr) {
error = g_error_new_literal(was_quark(), 0,
"misplaced DATA packet");
AbortError(error);
return false;
}
request.body = was_input_new(request.pool,
input_fd,
&was_server_input_handler,
this);
request.pending = true;
break;
case WAS_COMMAND_LENGTH:
if (request.pool == nullptr ||
(request.headers != nullptr && !request.pending)) {
error = g_error_new_literal(was_quark(), 0,
"misplaced LENGTH packet");
AbortError(error);
return false;
}
length_p = (const uint64_t *)payload.data;
if (request.body == nullptr ||
payload.size != sizeof(*length_p)) {
error = g_error_new_literal(was_quark(), 0,
"malformed LENGTH packet");
AbortError(error);
return false;
}
if (!was_input_set_length(request.body, *length_p)) {
error = g_error_new_literal(was_quark(), 0,
"invalid LENGTH packet");
AbortError(error);
return false;
}
break;
case WAS_COMMAND_STOP:
case WAS_COMMAND_PREMATURE:
// XXX
error = g_error_new(was_quark(), 0,
"unexpected packet: %d", cmd);
AbortError(error);
return false;
}
return true;
}
void
WasServer::OnWasControlError(GError *error)
{
control = nullptr;
AbortError(error);
}
/*
* constructor
*
*/
WasServer *
was_server_new(struct pool *pool, int control_fd, int input_fd, int output_fd,
WasServerHandler &handler)
{
assert(pool != nullptr);
assert(control_fd >= 0);
assert(input_fd >= 0);
assert(output_fd >= 0);
return NewFromPool<WasServer>(*pool, *pool,
control_fd, input_fd, output_fd,
handler);
}
void
was_server_free(WasServer *server)
{
GError *error = g_error_new_literal(was_quark(), 0,
"shutting down WAS connection");
server->ReleaseError(error);
}
void
was_server_response(WasServer *server, http_status_t status,
struct strmap *headers, Istream *body)
{
assert(server != nullptr);
assert(server->request.pool != nullptr);
assert(server->request.headers == nullptr);
assert(server->response.body == nullptr);
assert(http_status_is_valid(status));
assert(!http_status_is_empty(status) || body == nullptr);
was_control_bulk_on(server->control);
if (!was_control_send(server->control, WAS_COMMAND_STATUS,
&status, sizeof(status)))
return;
if (body != nullptr && http_method_is_empty(server->request.method)) {
if (server->request.method == HTTP_METHOD_HEAD) {
off_t available = body->GetAvailable(false);
if (available >= 0) {
if (headers == nullptr)
headers = strmap_new(server->request.pool);
headers->Set("content-length",
p_sprintf(server->request.pool, "%lu",
(unsigned long)available));
}
}
body->CloseUnused();
body = nullptr;
}
if (headers != nullptr)
was_control_send_strmap(server->control, WAS_COMMAND_HEADER,
headers);
if (body != nullptr) {
server->response.body = was_output_new(*server->request.pool,
server->output_fd, *body,
was_server_output_handler,
server);
if (!was_control_send_empty(server->control, WAS_COMMAND_DATA) ||
!was_output_check_length(*server->response.body))
return;
} else {
if (!was_control_send_empty(server->control, WAS_COMMAND_NO_DATA))
return;
}
was_control_bulk_off(server->control);
}
<commit_msg>was/server: change one "malformed LENGTH" to "misplaced ..."<commit_after>/*
* Web Application Socket client.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "was_server.hxx"
#include "was_quark.h"
#include "was_control.hxx"
#include "was_output.hxx"
#include "was_input.hxx"
#include "http_response.hxx"
#include "async.hxx"
#include "direct.hxx"
#include "istream/istream.hxx"
#include "istream/istream_null.hxx"
#include "strmap.hxx"
#include "pool.hxx"
#include "util/ConstBuffer.hxx"
#include <was/protocol.h>
#include <daemon/log.h>
#include <errno.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
struct WasServer final : WasControlHandler {
struct pool *const pool;
const int control_fd, input_fd, output_fd;
WasControl *control;
WasServerHandler &handler;
struct {
struct pool *pool = nullptr;
http_method_t method;
const char *uri;
/**
* Request headers being assembled. This pointer is set to
* nullptr before before the request is dispatched to the
* handler.
*/
struct strmap *headers;
WasInput *body;
bool pending = false;
} request;
struct {
http_status_t status;
WasOutput *body;
} response;
WasServer(struct pool &_pool,
int _control_fd, int _input_fd, int _output_fd,
WasServerHandler &_handler)
:pool(&_pool),
control_fd(_control_fd), input_fd(_input_fd), output_fd(_output_fd),
control(was_control_new(pool, control_fd, *this)),
handler(_handler) {}
void CloseFiles() {
close(control_fd);
close(input_fd);
close(output_fd);
}
void ReleaseError(GError *error);
void ReleaseUnused();
/**
* Abort receiving the response status/headers from the WAS server.
*/
void AbortError(GError *error) {
ReleaseError(error);
handler.OnWasClosed();
}
/**
* Abort receiving the response status/headers from the WAS server.
*/
void AbortUnused() {
ReleaseUnused();
handler.OnWasClosed();
}
/* virtual methods from class WasControlHandler */
bool OnWasControlPacket(enum was_command cmd,
ConstBuffer<void> payload) override;
bool OnWasControlDrained() override {
if (request.pending) {
auto *headers = request.headers;
request.headers = nullptr;
Istream *body = nullptr;
if (request.body != nullptr)
body = &was_input_enable(*request.body);
handler.OnWasRequest(*request.pool, request.method,
request.uri, std::move(*headers),
body);
/* XXX check if connection has been closed */
}
return true;
}
void OnWasControlDone() override {
control = nullptr;
}
void OnWasControlError(GError *error) override;
};
void
WasServer::ReleaseError(GError *error)
{
if (control != nullptr) {
was_control_free(control);
control = nullptr;
}
if (request.pool != nullptr) {
if (request.body != nullptr)
was_input_free_p(&request.body, error);
else
g_error_free(error);
if (request.headers == nullptr && response.body != nullptr)
was_output_free_p(&response.body);
pool_unref(request.pool);
} else
g_error_free(error);
CloseFiles();
}
void
WasServer::ReleaseUnused()
{
if (control != nullptr) {
was_control_free(control);
control = nullptr;
}
if (request.pool != nullptr) {
if (request.body != nullptr)
was_input_free_unused_p(&request.body);
if (request.headers == nullptr && response.body != nullptr)
was_output_free_p(&response.body);
pool_unref(request.pool);
}
CloseFiles();
}
/*
* Output handler
*/
static bool
was_server_output_length(uint64_t length, void *ctx)
{
WasServer *server = (WasServer *)ctx;
assert(server->control != nullptr);
assert(server->response.body != nullptr);
return was_control_send_uint64(server->control,
WAS_COMMAND_LENGTH, length);
}
static bool
was_server_output_premature(uint64_t length, GError *error, void *ctx)
{
WasServer *server = (WasServer *)ctx;
if (server->control == nullptr)
/* this can happen if was_input_free() call destroys the
WasOutput instance; this check means to work around this
circular call */
return true;
assert(server->response.body != nullptr);
server->response.body = nullptr;
/* XXX send PREMATURE, recover */
(void)length;
server->AbortError(error);
return false;
}
static void
was_server_output_eof(void *ctx)
{
WasServer *server = (WasServer *)ctx;
assert(server->response.body != nullptr);
server->response.body = nullptr;
}
static void
was_server_output_abort(GError *error, void *ctx)
{
WasServer *server = (WasServer *)ctx;
assert(server->response.body != nullptr);
server->response.body = nullptr;
server->AbortError(error);
}
static constexpr WasOutputHandler was_server_output_handler = {
.length = was_server_output_length,
.premature = was_server_output_premature,
.eof = was_server_output_eof,
.abort = was_server_output_abort,
};
/*
* Input handler
*/
static void
was_server_input_close(void *ctx)
{
WasServer *server = (WasServer *)ctx;
/* this happens when the request handler isn't interested in the
request body */
assert(server->request.headers == nullptr);
assert(server->request.body != nullptr);
server->request.body = nullptr;
if (server->control != nullptr)
was_control_send_empty(server->control, WAS_COMMAND_STOP);
// TODO: handle PREMATURE packet which we'll receive soon
}
static void
was_server_input_eof(void *ctx)
{
WasServer *server = (WasServer *)ctx;
assert(server->request.headers == nullptr);
assert(server->request.body != nullptr);
server->request.body = nullptr;
// XXX
}
static void
was_server_input_abort(void *ctx)
{
WasServer *server = (WasServer *)ctx;
assert(server->request.headers == nullptr);
assert(server->request.body != nullptr);
server->request.body = nullptr;
server->AbortUnused();
}
static constexpr WasInputHandler was_server_input_handler = {
.close = was_server_input_close,
.eof = was_server_input_eof,
.premature = was_server_input_abort, // TODO: implement
.abort = was_server_input_abort,
};
/*
* Control channel handler
*/
bool
WasServer::OnWasControlPacket(enum was_command cmd, ConstBuffer<void> payload)
{
GError *error;
switch (cmd) {
const uint64_t *length_p;
const char *p;
http_method_t method;
case WAS_COMMAND_NOP:
break;
case WAS_COMMAND_REQUEST:
if (request.pool != nullptr) {
error = g_error_new_literal(was_quark(), 0,
"misplaced REQUEST packet");
AbortError(error);
return false;
}
request.pool = pool_new_linear(pool, "was_server_request", 32768);
request.method = HTTP_METHOD_GET;
request.uri = nullptr;
request.headers = strmap_new(request.pool);
request.body = nullptr;
response.body = nullptr;
break;
case WAS_COMMAND_METHOD:
if (payload.size != sizeof(method)) {
error = g_error_new_literal(was_quark(), 0,
"malformed METHOD packet");
AbortError(error);
return false;
}
method = *(const http_method_t *)payload.data;
if (request.method != HTTP_METHOD_GET &&
method != request.method) {
/* sending that packet twice is illegal */
error = g_error_new_literal(was_quark(), 0,
"misplaced METHOD packet");
AbortError(error);
return false;
}
if (!http_method_is_valid(method)) {
error = g_error_new_literal(was_quark(), 0,
"invalid METHOD packet");
AbortError(error);
return false;
}
request.method = method;
break;
case WAS_COMMAND_URI:
if (request.pool == nullptr || request.uri != nullptr) {
error = g_error_new_literal(was_quark(), 0,
"misplaced URI packet");
AbortError(error);
return false;
}
request.uri = p_strndup(request.pool,
(const char *)payload.data, payload.size);
break;
case WAS_COMMAND_SCRIPT_NAME:
case WAS_COMMAND_PATH_INFO:
case WAS_COMMAND_QUERY_STRING:
// XXX
break;
case WAS_COMMAND_HEADER:
if (request.pool == nullptr || request.headers == nullptr) {
error = g_error_new_literal(was_quark(), 0,
"misplaced HEADER packet");
AbortError(error);
return false;
}
p = (const char *)memchr(payload.data, '=', payload.size);
if (p == nullptr) {
error = g_error_new_literal(was_quark(), 0,
"malformed HEADER packet");
AbortError(error);
return false;
}
// XXX parse buffer
break;
case WAS_COMMAND_PARAMETER:
// XXX
break;
case WAS_COMMAND_STATUS:
error = g_error_new_literal(was_quark(), 0,
"misplaced STATUS packet");
AbortError(error);
return false;
case WAS_COMMAND_NO_DATA:
if (request.pool == nullptr || request.uri == nullptr ||
request.headers == nullptr) {
error = g_error_new_literal(was_quark(), 0,
"misplaced NO_DATA packet");
AbortError(error);
return false;
}
request.body = nullptr;
request.pending = true;
break;
case WAS_COMMAND_DATA:
if (request.pool == nullptr || request.uri == nullptr ||
request.headers == nullptr) {
error = g_error_new_literal(was_quark(), 0,
"misplaced DATA packet");
AbortError(error);
return false;
}
request.body = was_input_new(request.pool,
input_fd,
&was_server_input_handler,
this);
request.pending = true;
break;
case WAS_COMMAND_LENGTH:
if (request.pool == nullptr ||
request.body == nullptr ||
(request.headers != nullptr && !request.pending)) {
error = g_error_new_literal(was_quark(), 0,
"misplaced LENGTH packet");
AbortError(error);
return false;
}
length_p = (const uint64_t *)payload.data;
if (payload.size != sizeof(*length_p)) {
error = g_error_new_literal(was_quark(), 0,
"malformed LENGTH packet");
AbortError(error);
return false;
}
if (!was_input_set_length(request.body, *length_p)) {
error = g_error_new_literal(was_quark(), 0,
"invalid LENGTH packet");
AbortError(error);
return false;
}
break;
case WAS_COMMAND_STOP:
case WAS_COMMAND_PREMATURE:
// XXX
error = g_error_new(was_quark(), 0,
"unexpected packet: %d", cmd);
AbortError(error);
return false;
}
return true;
}
void
WasServer::OnWasControlError(GError *error)
{
control = nullptr;
AbortError(error);
}
/*
* constructor
*
*/
WasServer *
was_server_new(struct pool *pool, int control_fd, int input_fd, int output_fd,
WasServerHandler &handler)
{
assert(pool != nullptr);
assert(control_fd >= 0);
assert(input_fd >= 0);
assert(output_fd >= 0);
return NewFromPool<WasServer>(*pool, *pool,
control_fd, input_fd, output_fd,
handler);
}
void
was_server_free(WasServer *server)
{
GError *error = g_error_new_literal(was_quark(), 0,
"shutting down WAS connection");
server->ReleaseError(error);
}
void
was_server_response(WasServer *server, http_status_t status,
struct strmap *headers, Istream *body)
{
assert(server != nullptr);
assert(server->request.pool != nullptr);
assert(server->request.headers == nullptr);
assert(server->response.body == nullptr);
assert(http_status_is_valid(status));
assert(!http_status_is_empty(status) || body == nullptr);
was_control_bulk_on(server->control);
if (!was_control_send(server->control, WAS_COMMAND_STATUS,
&status, sizeof(status)))
return;
if (body != nullptr && http_method_is_empty(server->request.method)) {
if (server->request.method == HTTP_METHOD_HEAD) {
off_t available = body->GetAvailable(false);
if (available >= 0) {
if (headers == nullptr)
headers = strmap_new(server->request.pool);
headers->Set("content-length",
p_sprintf(server->request.pool, "%lu",
(unsigned long)available));
}
}
body->CloseUnused();
body = nullptr;
}
if (headers != nullptr)
was_control_send_strmap(server->control, WAS_COMMAND_HEADER,
headers);
if (body != nullptr) {
server->response.body = was_output_new(*server->request.pool,
server->output_fd, *body,
was_server_output_handler,
server);
if (!was_control_send_empty(server->control, WAS_COMMAND_DATA) ||
!was_output_check_length(*server->response.body))
return;
} else {
if (!was_control_send_empty(server->control, WAS_COMMAND_NO_DATA))
return;
}
was_control_bulk_off(server->control);
}
<|endoftext|> |
<commit_before>/* _______ __ __ __ ______ __ __ _______ __ __
* / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\
* / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / /
* / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / /
* / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / /
* /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ /
* \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/
*
* Copyright (c) 2004, 2005, 2006 Olof Naessn and Per Larsson
*
* Js_./
* Per Larsson a.k.a finalman _RqZ{a<^_aa
* Olof Naessn a.k.a jansem/yakslem _asww7!uY`> )\a//
* _Qhm`] _f "'c 1!5m
* Visit: http://guichan.darkbits.org )Qk<P ` _: :+' .' "{[
* .)j(] .d_/ '-( P . S
* License: (BSD) <Td/Z <fP"5(\"??"\a. .L
* Redistribution and use in source and _dV>ws?a-?' ._/L #'
* binary forms, with or without )4d[#7r, . ' )d`)[
* modification, are permitted provided _Q-5'5W..j/?' -?!\)cam'
* that the following conditions are met: j<<WP+k/);. _W=j f
* 1. Redistributions of source code must .$%w\/]Q . ."' . mj$
* retain the above copyright notice, ]E.pYY(Q]>. a J@\
* this list of conditions and the j(]1u<sE"L,. . ./^ ]{a
* following disclaimer. 4'_uomm\. )L);-4 (3=
* 2. Redistributions in binary form must )_]X{Z('a_"a7'<a"a, ]"[
* reproduce the above copyright notice, #}<]m7`Za??4,P-"'7. ).m
* this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ/
* following disclaimer in the <B!</]C)d_, '(<' .f. =C+m
* documentation and/or other materials .Z!=J ]e []('-4f _ ) -.)m]'
* provided with the distribution. .w[5]' _[ /.)_-"+? _/ <W"
* 3. Neither the name of Guichan nor the :$we` _! + _/ . j?
* names of its contributors may be used =3)= _f (_yQmWW$#( "
* to endorse or promote products derived - W, sQQQQmZQ#Wwa]..
* from this software without specific (js, \[QQW$QWW#?!V"".
* prior written permission. ]y:.<\.. .
* -]n w/ ' [.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )/ )/ !
* HOLDERS AND CONTRIBUTORS "AS IS" AND ANY < (; sac , '
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- %
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P"_(\?d'.,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f/<[]/ ?"
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. .
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%"' " -'.a_ _,
* 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.
*/
/*
* For comments regarding functions please see the header file.
*/
#include "guichan/widgets/window.hpp"
#include "guichan/exception.hpp"
#include "guichan/font.hpp"
#include "guichan/graphics.hpp"
#include "guichan/mouseinput.hpp"
#include <iostream>
namespace gcn
{
Window::Window()
:mIsMoving(false)
{
setBorderSize(1);
setPadding(2);
setTitleBarHeight(16);
setAlignment(Graphics::CENTER);
addMouseListener(this);
setMovable(true);
setOpaque(true);
setFocusable(true);
}
Window::Window(const std::string& caption)
:mIsMoving(false)
{
setCaption(caption);
setBorderSize(1);
setPadding(2);
setTitleBarHeight(16);
setAlignment(Graphics::CENTER);
addMouseListener(this);
setMovable(true);
setOpaque(true);
setFocusable(true);
}
Window::~Window()
{
}
void Window::setPadding(unsigned int padding)
{
mPadding = padding;
}
unsigned int Window::getPadding() const
{
return mPadding;
}
void Window::setTitleBarHeight(unsigned int height)
{
mTitleBarHeight = height;
}
unsigned int Window::getTitleBarHeight()
{
return mTitleBarHeight;
}
void Window::setCaption(const std::string& caption)
{
mCaption = caption;
}
const std::string& Window::getCaption() const
{
return mCaption;
}
void Window::setAlignment(unsigned int alignment)
{
mAlignment = alignment;
}
unsigned int Window::getAlignment() const
{
return mAlignment;
}
void Window::draw(Graphics* graphics)
{
Color faceColor = getBaseColor();
Color highlightColor, shadowColor;
int alpha = getBaseColor().a;
int width = getWidth() + getBorderSize() * 2 - 1;
int height = getHeight() + getBorderSize() * 2 - 1;
highlightColor = faceColor + 0x303030;
highlightColor.a = alpha;
shadowColor = faceColor - 0x303030;
shadowColor.a = alpha;
Rectangle d = getChildrenArea();
// Fill the background around the content
graphics->setColor(faceColor);
// Fill top
graphics->fillRectangle(Rectangle(0,0,getWidth(),d.y - 1));
// Fill left
graphics->fillRectangle(Rectangle(0,d.y - 1, d.x - 1, getHeight() - d.y + 1));
// Fill right
graphics->fillRectangle(Rectangle(d.x + d.width + 1,
d.y - 1,
getWidth() - d.x - d.width - 1,
getHeight() - d.y + 1));
// Fill bottom
graphics->fillRectangle(Rectangle(d.x - 1,
d.y + d.height + 1,
d.width + 2,
getHeight() - d.height - d.y - 1));
if (isOpaque())
{
graphics->fillRectangle(d);
}
// Construct a rectangle one pixel bigger than the content
d.x -= 1;
d.y -= 1;
d.width += 2;
d.height += 2;
// Draw a border around the content
graphics->setColor(shadowColor);
// Top line
graphics->drawLine(d.x,
d.y,
d.x + d.width - 2,
d.y);
// Left line
graphics->drawLine(d.x,
d.y + 1,
d.x,
d.y + d.height - 1);
graphics->setColor(highlightColor);
// Right line
graphics->drawLine(d.x + d.width - 1,
d.y,
d.x + d.width - 1,
d.y + d.height - 2);
// Bottom line
graphics->drawLine(d.x + 1,
d.y + d.height - 1,
d.x + d.width - 1,
d.y + d.height - 1);
drawChildren(graphics);
int textX;
int textY;
textY = ((int)getTitleBarHeight() - getFont()->getHeight()) / 2;
switch (getAlignment())
{
case Graphics::LEFT:
textX = 4;
break;
case Graphics::CENTER:
textX = getWidth() / 2;
break;
case Graphics::RIGHT:
textX = getWidth() - 4;
break;
default:
throw GCN_EXCEPTION("Unknown alignment.");
}
graphics->setColor(getForegroundColor());
graphics->setFont(getFont());
graphics->pushClipArea(Rectangle(0, 0, getWidth(), getTitleBarHeight() - 1));
graphics->drawText(getCaption(), textX, textY, getAlignment());
graphics->popClipArea();
}
void Window::drawBorder(Graphics* graphics)
{
Color faceColor = getBaseColor();
Color highlightColor, shadowColor;
int alpha = getBaseColor().a;
int width = getWidth() + getBorderSize() * 2 - 1;
int height = getHeight() + getBorderSize() * 2 - 1;
highlightColor = faceColor + 0x303030;
highlightColor.a = alpha;
shadowColor = faceColor - 0x303030;
shadowColor.a = alpha;
unsigned int i;
for (i = 0; i < getBorderSize(); ++i)
{
graphics->setColor(highlightColor);
graphics->drawLine(i,i, width - i, i);
graphics->drawLine(i,i + 1, i, height - i - 1);
graphics->setColor(shadowColor);
graphics->drawLine(width - i,i + 1, width - i, height - i);
graphics->drawLine(i,height - i, width - i - 1, height - i);
}
}
void Window::mousePressed(MouseEvent& mouseEvent)
{
if (getParent() != NULL)
{
getParent()->moveToTop(this);
}
mDragOffsetX = mouseEvent.getX();
mDragOffsetY = mouseEvent.getY();
mIsMoving = mouseEvent.getY() <= (int)mTitleBarHeight;
std::cout << mouseEvent.getY() << " " << mTitleBarHeight << std::endl;
mouseEvent.consume();
}
void Window::mouseDragged(MouseEvent& mouseEvent)
{
if (isMovable() && mIsMoving)
{
setPosition(mouseEvent.getX() - mDragOffsetX + getX(),
mouseEvent.getY() - mDragOffsetY + getY());
}
mouseEvent.consume();
}
Rectangle Window::getChildrenArea()
{
return Rectangle(getPadding(),
getTitleBarHeight(),
getWidth() - getPadding() * 2,
getHeight() - getPadding() - getTitleBarHeight());
}
void Window::setMovable(bool movable)
{
mMovable = movable;
}
bool Window::isMovable() const
{
return mMovable;
}
void Window::setOpaque(bool opaque)
{
mOpaque = opaque;
}
bool Window::isOpaque()
{
return mOpaque;
}
void Window::resizeToContent()
{
WidgetListIterator it;
int w = 0, h = 0;
for (it = mWidgets.begin(); it != mWidgets.end(); it++)
{
if ((*it)->getX() + (*it)->getWidth() > w)
{
w = (*it)->getX() + (*it)->getWidth();
}
if ((*it)->getY() + (*it)->getHeight() > h)
{
h = (*it)->getY() + (*it)->getHeight();
}
}
setSize(w + 2* getPadding(), h + getPadding() + getTitleBarHeight());
}
}
<commit_msg>Debug printing has been removed.<commit_after>/* _______ __ __ __ ______ __ __ _______ __ __
* / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\
* / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / /
* / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / /
* / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / /
* /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ /
* \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/
*
* Copyright (c) 2004, 2005, 2006 Olof Naessn and Per Larsson
*
* Js_./
* Per Larsson a.k.a finalman _RqZ{a<^_aa
* Olof Naessn a.k.a jansem/yakslem _asww7!uY`> )\a//
* _Qhm`] _f "'c 1!5m
* Visit: http://guichan.darkbits.org )Qk<P ` _: :+' .' "{[
* .)j(] .d_/ '-( P . S
* License: (BSD) <Td/Z <fP"5(\"??"\a. .L
* Redistribution and use in source and _dV>ws?a-?' ._/L #'
* binary forms, with or without )4d[#7r, . ' )d`)[
* modification, are permitted provided _Q-5'5W..j/?' -?!\)cam'
* that the following conditions are met: j<<WP+k/);. _W=j f
* 1. Redistributions of source code must .$%w\/]Q . ."' . mj$
* retain the above copyright notice, ]E.pYY(Q]>. a J@\
* this list of conditions and the j(]1u<sE"L,. . ./^ ]{a
* following disclaimer. 4'_uomm\. )L);-4 (3=
* 2. Redistributions in binary form must )_]X{Z('a_"a7'<a"a, ]"[
* reproduce the above copyright notice, #}<]m7`Za??4,P-"'7. ).m
* this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ/
* following disclaimer in the <B!</]C)d_, '(<' .f. =C+m
* documentation and/or other materials .Z!=J ]e []('-4f _ ) -.)m]'
* provided with the distribution. .w[5]' _[ /.)_-"+? _/ <W"
* 3. Neither the name of Guichan nor the :$we` _! + _/ . j?
* names of its contributors may be used =3)= _f (_yQmWW$#( "
* to endorse or promote products derived - W, sQQQQmZQ#Wwa]..
* from this software without specific (js, \[QQW$QWW#?!V"".
* prior written permission. ]y:.<\.. .
* -]n w/ ' [.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )/ )/ !
* HOLDERS AND CONTRIBUTORS "AS IS" AND ANY < (; sac , '
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- %
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P"_(\?d'.,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f/<[]/ ?"
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. .
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%"' " -'.a_ _,
* 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.
*/
/*
* For comments regarding functions please see the header file.
*/
#include "guichan/widgets/window.hpp"
#include "guichan/exception.hpp"
#include "guichan/font.hpp"
#include "guichan/graphics.hpp"
#include "guichan/mouseinput.hpp"
namespace gcn
{
Window::Window()
:mIsMoving(false)
{
setBorderSize(1);
setPadding(2);
setTitleBarHeight(16);
setAlignment(Graphics::CENTER);
addMouseListener(this);
setMovable(true);
setOpaque(true);
setFocusable(true);
}
Window::Window(const std::string& caption)
:mIsMoving(false)
{
setCaption(caption);
setBorderSize(1);
setPadding(2);
setTitleBarHeight(16);
setAlignment(Graphics::CENTER);
addMouseListener(this);
setMovable(true);
setOpaque(true);
setFocusable(true);
}
Window::~Window()
{
}
void Window::setPadding(unsigned int padding)
{
mPadding = padding;
}
unsigned int Window::getPadding() const
{
return mPadding;
}
void Window::setTitleBarHeight(unsigned int height)
{
mTitleBarHeight = height;
}
unsigned int Window::getTitleBarHeight()
{
return mTitleBarHeight;
}
void Window::setCaption(const std::string& caption)
{
mCaption = caption;
}
const std::string& Window::getCaption() const
{
return mCaption;
}
void Window::setAlignment(unsigned int alignment)
{
mAlignment = alignment;
}
unsigned int Window::getAlignment() const
{
return mAlignment;
}
void Window::draw(Graphics* graphics)
{
Color faceColor = getBaseColor();
Color highlightColor, shadowColor;
int alpha = getBaseColor().a;
int width = getWidth() + getBorderSize() * 2 - 1;
int height = getHeight() + getBorderSize() * 2 - 1;
highlightColor = faceColor + 0x303030;
highlightColor.a = alpha;
shadowColor = faceColor - 0x303030;
shadowColor.a = alpha;
Rectangle d = getChildrenArea();
// Fill the background around the content
graphics->setColor(faceColor);
// Fill top
graphics->fillRectangle(Rectangle(0,0,getWidth(),d.y - 1));
// Fill left
graphics->fillRectangle(Rectangle(0,d.y - 1, d.x - 1, getHeight() - d.y + 1));
// Fill right
graphics->fillRectangle(Rectangle(d.x + d.width + 1,
d.y - 1,
getWidth() - d.x - d.width - 1,
getHeight() - d.y + 1));
// Fill bottom
graphics->fillRectangle(Rectangle(d.x - 1,
d.y + d.height + 1,
d.width + 2,
getHeight() - d.height - d.y - 1));
if (isOpaque())
{
graphics->fillRectangle(d);
}
// Construct a rectangle one pixel bigger than the content
d.x -= 1;
d.y -= 1;
d.width += 2;
d.height += 2;
// Draw a border around the content
graphics->setColor(shadowColor);
// Top line
graphics->drawLine(d.x,
d.y,
d.x + d.width - 2,
d.y);
// Left line
graphics->drawLine(d.x,
d.y + 1,
d.x,
d.y + d.height - 1);
graphics->setColor(highlightColor);
// Right line
graphics->drawLine(d.x + d.width - 1,
d.y,
d.x + d.width - 1,
d.y + d.height - 2);
// Bottom line
graphics->drawLine(d.x + 1,
d.y + d.height - 1,
d.x + d.width - 1,
d.y + d.height - 1);
drawChildren(graphics);
int textX;
int textY;
textY = ((int)getTitleBarHeight() - getFont()->getHeight()) / 2;
switch (getAlignment())
{
case Graphics::LEFT:
textX = 4;
break;
case Graphics::CENTER:
textX = getWidth() / 2;
break;
case Graphics::RIGHT:
textX = getWidth() - 4;
break;
default:
throw GCN_EXCEPTION("Unknown alignment.");
}
graphics->setColor(getForegroundColor());
graphics->setFont(getFont());
graphics->pushClipArea(Rectangle(0, 0, getWidth(), getTitleBarHeight() - 1));
graphics->drawText(getCaption(), textX, textY, getAlignment());
graphics->popClipArea();
}
void Window::drawBorder(Graphics* graphics)
{
Color faceColor = getBaseColor();
Color highlightColor, shadowColor;
int alpha = getBaseColor().a;
int width = getWidth() + getBorderSize() * 2 - 1;
int height = getHeight() + getBorderSize() * 2 - 1;
highlightColor = faceColor + 0x303030;
highlightColor.a = alpha;
shadowColor = faceColor - 0x303030;
shadowColor.a = alpha;
unsigned int i;
for (i = 0; i < getBorderSize(); ++i)
{
graphics->setColor(highlightColor);
graphics->drawLine(i,i, width - i, i);
graphics->drawLine(i,i + 1, i, height - i - 1);
graphics->setColor(shadowColor);
graphics->drawLine(width - i,i + 1, width - i, height - i);
graphics->drawLine(i,height - i, width - i - 1, height - i);
}
}
void Window::mousePressed(MouseEvent& mouseEvent)
{
if (getParent() != NULL)
{
getParent()->moveToTop(this);
}
mDragOffsetX = mouseEvent.getX();
mDragOffsetY = mouseEvent.getY();
mIsMoving = mouseEvent.getY() <= (int)mTitleBarHeight;
mouseEvent.consume();
}
void Window::mouseDragged(MouseEvent& mouseEvent)
{
if (isMovable() && mIsMoving)
{
setPosition(mouseEvent.getX() - mDragOffsetX + getX(),
mouseEvent.getY() - mDragOffsetY + getY());
}
mouseEvent.consume();
}
Rectangle Window::getChildrenArea()
{
return Rectangle(getPadding(),
getTitleBarHeight(),
getWidth() - getPadding() * 2,
getHeight() - getPadding() - getTitleBarHeight());
}
void Window::setMovable(bool movable)
{
mMovable = movable;
}
bool Window::isMovable() const
{
return mMovable;
}
void Window::setOpaque(bool opaque)
{
mOpaque = opaque;
}
bool Window::isOpaque()
{
return mOpaque;
}
void Window::resizeToContent()
{
WidgetListIterator it;
int w = 0, h = 0;
for (it = mWidgets.begin(); it != mWidgets.end(); it++)
{
if ((*it)->getX() + (*it)->getWidth() > w)
{
w = (*it)->getX() + (*it)->getWidth();
}
if ((*it)->getY() + (*it)->getHeight() > h)
{
h = (*it)->getY() + (*it)->getHeight();
}
}
setSize(w + 2* getPadding(), h + getPadding() + getTitleBarHeight());
}
}
<|endoftext|> |
<commit_before>#include "ExecStats.h"
#include <iostream>
#include <iomanip>
#include <cassert>
namespace dev
{
namespace eth
{
namespace jit
{
void ExecStats::stateChanged(ExecState _state)
{
assert(m_state != ExecState::Finished);
auto now = clock::now();
if (_state != ExecState::Started)
{
assert(time[(int)m_state] == ExecStats::duration::zero());
time[(int)m_state] = now - m_tp;
}
m_state = _state;
m_tp = now;
}
namespace
{
struct StatsAgg
{
using unit = std::chrono::microseconds;
ExecStats::duration tot = ExecStats::duration::zero();
ExecStats::duration min = ExecStats::duration::max();
ExecStats::duration max = ExecStats::duration::zero();
size_t count = 0;
void update(ExecStats::duration _d)
{
++count;
tot += _d;
min = _d < min ? _d : min;
max = _d > max ? _d : max;
}
void output(char const* _name, std::ostream& _os)
{
auto avg = tot / count;
_os << std::setfill(' ')
<< std::setw(12) << std::left << _name
<< std::setw(10) << std::right << std::chrono::duration_cast<unit>(tot).count()
<< std::setw(10) << std::right << std::chrono::duration_cast<unit>(avg).count()
<< std::setw(10) << std::right << std::chrono::duration_cast<unit>(min).count()
<< std::setw(10) << std::right << std::chrono::duration_cast<unit>(max).count()
<< std::endl;
}
};
char const* getExecStateName(ExecState _state)
{
switch (_state)
{
case ExecState::Started: return "Start";
case ExecState::CacheLoad: return "CacheLoad";
case ExecState::CacheWrite: return "CacheWrite";
case ExecState::Compilation: return "Compilation";
case ExecState::CodeGen: return "CodeGen";
case ExecState::Execution: return "Execution";
case ExecState::Return: return "Return";
case ExecState::Finished: return "Finish";
}
return nullptr;
}
}
StatsCollector::~StatsCollector()
{
if (stats.empty())
return;
std::cout << " [us] total avg min max\n";
for (int i = 0; i < (int)ExecState::Finished; ++i)
{
StatsAgg agg;
for (auto&& s : stats)
agg.update(s->time[i]);
agg.output(getExecStateName(ExecState(i)), std::cout);
}
}
}
}
}
<commit_msg>Safe assert<commit_after>#include "ExecStats.h"
#include <iostream>
#include <iomanip>
#include <cassert>
namespace dev
{
namespace eth
{
namespace jit
{
void ExecStats::stateChanged(ExecState _state)
{
if (!CHECK(m_state != ExecState::Finished))
return;
auto now = clock::now();
if (_state != ExecState::Started)
{
assert(time[(int)m_state] == ExecStats::duration::zero());
time[(int)m_state] = now - m_tp;
}
m_state = _state;
m_tp = now;
}
namespace
{
struct StatsAgg
{
using unit = std::chrono::microseconds;
ExecStats::duration tot = ExecStats::duration::zero();
ExecStats::duration min = ExecStats::duration::max();
ExecStats::duration max = ExecStats::duration::zero();
size_t count = 0;
void update(ExecStats::duration _d)
{
++count;
tot += _d;
min = _d < min ? _d : min;
max = _d > max ? _d : max;
}
void output(char const* _name, std::ostream& _os)
{
auto avg = tot / count;
_os << std::setfill(' ')
<< std::setw(12) << std::left << _name
<< std::setw(10) << std::right << std::chrono::duration_cast<unit>(tot).count()
<< std::setw(10) << std::right << std::chrono::duration_cast<unit>(avg).count()
<< std::setw(10) << std::right << std::chrono::duration_cast<unit>(min).count()
<< std::setw(10) << std::right << std::chrono::duration_cast<unit>(max).count()
<< std::endl;
}
};
char const* getExecStateName(ExecState _state)
{
switch (_state)
{
case ExecState::Started: return "Start";
case ExecState::CacheLoad: return "CacheLoad";
case ExecState::CacheWrite: return "CacheWrite";
case ExecState::Compilation: return "Compilation";
case ExecState::CodeGen: return "CodeGen";
case ExecState::Execution: return "Execution";
case ExecState::Return: return "Return";
case ExecState::Finished: return "Finish";
}
return nullptr;
}
}
StatsCollector::~StatsCollector()
{
if (stats.empty())
return;
std::cout << " [us] total avg min max\n";
for (int i = 0; i < (int)ExecState::Finished; ++i)
{
StatsAgg agg;
for (auto&& s : stats)
agg.update(s->time[i]);
agg.output(getExecStateName(ExecState(i)), std::cout);
}
}
}
}
}
<|endoftext|> |
<commit_before>
#include <cmath>
#include <QColor>
#include <QVector2D>
#include <QVector4D>
#include <QOpenGLShaderProgram>
#include <QOpenGLShader>
#include "OpenGLFunctions.h"
#include "MathMacros.h"
#include "Plane3.h"
#include "AdaptiveGrid.h"
const char * AdaptiveGrid::s_vsSource = R"(
#version 150
uniform mat4 transform;
uniform vec2 distance;
in vec4 a_vertex;
flat out float v_type;
out vec3 v_vertex;
void main()
{
float m = 1.0 - distance[1];
float t = a_vertex.w;
vec4 vertex = transform * vec4(a_vertex.xyz, 1.0);
v_vertex = vertex.xyz;
// interpolate minor grid lines alpha based on distance
v_type = mix(1.0 - t, 1.0 - 2.0 * m * t, step(a_vertex.w, 0.7998));
gl_Position = vertex;
}
)";
const char * AdaptiveGrid::s_fsSource = R"(
#version 150
uniform vec2 distance;
uniform float znear;
uniform float zfar;
uniform vec3 color;
flat in float v_type;
in vec3 v_vertex;
out vec4 fragColor;
void main()
{
float t = v_type;
float z = gl_FragCoord.z;
// complete function
// z = (2.0 * zfar * znear / (zfar + znear - (zfar - znear) * (2.0 * z - 1.0)));
// normalized to [0,1]
// z = (z - znear) / (zfar - znear);
// simplyfied with wolfram alpha
z = - znear * z / (zfar * z - zfar - znear * z);
float g = mix(t, 1.0, z * z);
float l = clamp(8.0 - length(v_vertex) / distance[0], 0.0, 1.0);
fragColor = vec4(color, l * (1.0 - g * g));
}
)";
AdaptiveGrid::AdaptiveGrid(
OpenGLFunctions & gl
, unsigned short segments
, const QVector3D & location
, const QVector3D & normal)
: m_program(new QOpenGLShaderProgram)
, m_buffer(QOpenGLBuffer::VertexBuffer)
, m_location(location)
, m_normal(normal)
, m_size(0)
{
m_transform = transform(m_location, m_normal);
m_program->addShaderFromSourceCode(QOpenGLShader::Vertex, s_vsSource);
m_program->addShaderFromSourceCode(QOpenGLShader::Fragment, s_fsSource);
m_program->link();
setColor(QColor::fromRgbF(0.8, 0.8, 0.8));
m_vao.create();
m_vao.bind();
setupGridLineBuffer(segments);
const int a_vertex = m_program->attributeLocation("a_vertex");
gl.glVertexAttribPointer(a_vertex, 4, GL_FLOAT, GL_FALSE, sizeof(float) * 4, nullptr);
gl.glEnableVertexAttribArray(a_vertex);
m_vao.release();
}
AdaptiveGrid::~AdaptiveGrid()
{
}
void AdaptiveGrid::setupGridLineBuffer(unsigned short segments)
{
std::vector<QVector4D> points;
float type;
int n = 1;
const float g(static_cast<float>(segments));
type = .2f; // sub gridlines, every 0.125, except every 0.5
for (float f = -g + .125f; f < g; f += .125f)
if (n++ % 4)
{
points.push_back(QVector4D( g, 0.f, f, type));
points.push_back(QVector4D(-g, 0.f, f, type));
points.push_back(QVector4D( f, 0.f, g, type));
points.push_back(QVector4D( f, 0.f,-g, type));
}
type = .4f; // grid lines every 1.0 units, offseted by 0.5
for (float f = -g + .5f; f < g; f += 1.f)
{
points.push_back(QVector4D( g, 0.f, f, type));
points.push_back(QVector4D(-g, 0.f, f, type));
points.push_back(QVector4D( f, 0.f, g, type));
points.push_back(QVector4D( f, 0.f,-g, type));
}
type = .8f; // grid lines every 1.0 units
for (float f = -g + 1.f; f < g; f += 1.f)
{
points.push_back(QVector4D( g, 0.f, f, type));
points.push_back(QVector4D(-g, 0.f, f, type));
points.push_back(QVector4D( f, 0.f, g, type));
points.push_back(QVector4D( f, 0.f,-g, type));
}
// use hesse normal form and transform each grid line onto the specified plane.
QMatrix4x4 T; // ToDo
for (QVector4D & point : points)
point = QVector4D(QVector3D(T * QVector4D(point.toVector3D(), 1.f)), point.w());
m_size = points.size(); // segments * 64 - 4;
m_buffer.create();
m_buffer.setUsagePattern(QOpenGLBuffer::StaticDraw);
m_buffer.bind();
m_buffer.allocate(points.data(), sizeof(float)* 4 * points.size());
}
void AdaptiveGrid::setNearFar(
float zNear
, float zFar)
{
m_program->bind();
m_program->setUniformValue("znear", zNear);
m_program->setUniformValue("zfar", zFar);
m_program->release();
}
void AdaptiveGrid::setColor(const QColor & color)
{
m_program->bind();
m_program->setUniformValue("color", QVector3D(color.redF(), color.greenF(), color.blueF()));
m_program->release();
}
void AdaptiveGrid::update(
const QVector3D & viewpoint
, const QMatrix4x4 & modelViewProjection)
{
// Project the camera's eye position onto the grid plane.
bool intersects; // should always intersect.
const QVector3D i = intersection(intersects, m_location, m_normal
, viewpoint, viewpoint - m_normal);
// This transforms the horizontal plane vectors u and v onto the actual
// grid plane. Than express the intersection i as a linear combination of
// u and v by solving the linear equation system.
// Finally round the s and t values to get the nearest major grid point.
const float l = (viewpoint - i).length();
const float distancelog = log(l * .4998f) / log(8.f);
const float distance = pow(8.f, ceil(distancelog));
QMatrix4x4 T; // ToDo
const QVector3D uv(QVector3D(T * QVector4D(distance, 0.f, 0.f, 1.f)) - m_location);
const float u[3] = { uv.x(), uv.y(), uv.z() };
const QVector3D vv(QVector3D(T * QVector4D(0.f, 0.f, distance, 1.f)) - m_location);
const float v[3] = { vv.x(), vv.y(), vv.z() };
const size_t j = u[0] != 0.0 ? 0 : u[1] != 0.0 ? 1 : 2;
const size_t k = v[0] != 0.0 && j != 0 ? 0 : v[1] != 0.0 && j != 1 ? 1 : 2;
const QVector3D av(i - m_location);
const float a[3] = { av.x(), av.y(), av.z() };
const float t = v[k] ? a[k] / v[k] : 0.f;
const float s = u[j] ? (a[j] - t * v[j]) / u[j] : 0.f;
const QVector3D irounded = round(s) * uv + round(t) * vv;
QMatrix4x4 offset;
offset.translate(irounded);
offset.scale(distance);
m_program->bind();
m_program->setUniformValue("distance", QVector2D(l, mod(distancelog, 1.f)));
m_program->setUniformValue("transform", modelViewProjection * offset);
m_program->release();
}
void AdaptiveGrid::draw(
OpenGLFunctions & gl)
{
gl.glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
gl.glEnable(GL_BLEND);
gl.glEnable(GL_DEPTH_TEST);
m_program->bind();
m_vao.bind();
gl.glDrawArrays(GL_LINES, 0, m_size);
m_vao.release();
m_program->release();
gl.glDisable(GL_BLEND);
}
<commit_msg>VS2012 does not support raw string literals...<commit_after>
#include <cmath>
#include <QColor>
#include <QVector2D>
#include <QVector4D>
#include <QOpenGLShaderProgram>
#include <QOpenGLShader>
#include "OpenGLFunctions.h"
#include "MathMacros.h"
#include "Plane3.h"
#include "AdaptiveGrid.h"
const char * AdaptiveGrid::s_vsSource = "(\
#version 150\
uniform mat4 transform;\
uniform vec2 distance;\
in vec4 a_vertex;\
flat out float v_type;\
out vec3 v_vertex;\
\
void main()\
{\
float m = 1.0 - distance[1];\
float t = a_vertex.w;\
vec4 vertex = transform * vec4(a_vertex.xyz, 1.0);\
v_vertex = vertex.xyz;\
// interpolate minor grid lines alpha based on distance\
v_type = mix(1.0 - t, 1.0 - 2.0 * m * t, step(a_vertex.w, 0.7998));\
gl_Position = vertex;\
}\
)";
const char * AdaptiveGrid::s_fsSource = "(\
\
#version 150\
\
uniform vec2 distance;\
uniform float znear;\
uniform float zfar;\
uniform vec3 color;\
flat in float v_type;\
in vec3 v_vertex;\
out vec4 fragColor;\
void main()\
{\
float t = v_type;\
float z = gl_FragCoord.z;\
\
// complete function\
// z = (2.0 * zfar * znear / (zfar + znear - (zfar - znear) * (2.0 * z - 1.0)));\
// normalized to [0,1]\
// z = (z - znear) / (zfar - znear);\
\
// simplyfied with wolfram alpha\
z = - znear * z / (zfar * z - zfar - znear * z);\
\
float g = mix(t, 1.0, z * z);\
float l = clamp(8.0 - length(v_vertex) / distance[0], 0.0, 1.0);\
fragColor = vec4(color, l * (1.0 - g * g));\
}\
)";
AdaptiveGrid::AdaptiveGrid(
OpenGLFunctions & gl
, unsigned short segments
, const QVector3D & location
, const QVector3D & normal)
: m_program(new QOpenGLShaderProgram)
, m_buffer(QOpenGLBuffer::VertexBuffer)
, m_location(location)
, m_normal(normal)
, m_size(0)
{
m_transform = transform(m_location, m_normal);
m_program->addShaderFromSourceCode(QOpenGLShader::Vertex, s_vsSource);
m_program->addShaderFromSourceCode(QOpenGLShader::Fragment, s_fsSource);
m_program->link();
setColor(QColor::fromRgbF(0.8, 0.8, 0.8));
m_vao.create();
m_vao.bind();
setupGridLineBuffer(segments);
const int a_vertex = m_program->attributeLocation("a_vertex");
gl.glVertexAttribPointer(a_vertex, 4, GL_FLOAT, GL_FALSE, sizeof(float) * 4, nullptr);
gl.glEnableVertexAttribArray(a_vertex);
m_vao.release();
}
AdaptiveGrid::~AdaptiveGrid()
{
}
void AdaptiveGrid::setupGridLineBuffer(unsigned short segments)
{
std::vector<QVector4D> points;
float type;
int n = 1;
const float g(static_cast<float>(segments));
type = .2f; // sub gridlines, every 0.125, except every 0.5
for (float f = -g + .125f; f < g; f += .125f)
if (n++ % 4)
{
points.push_back(QVector4D( g, 0.f, f, type));
points.push_back(QVector4D(-g, 0.f, f, type));
points.push_back(QVector4D( f, 0.f, g, type));
points.push_back(QVector4D( f, 0.f,-g, type));
}
type = .4f; // grid lines every 1.0 units, offseted by 0.5
for (float f = -g + .5f; f < g; f += 1.f)
{
points.push_back(QVector4D( g, 0.f, f, type));
points.push_back(QVector4D(-g, 0.f, f, type));
points.push_back(QVector4D( f, 0.f, g, type));
points.push_back(QVector4D( f, 0.f,-g, type));
}
type = .8f; // grid lines every 1.0 units
for (float f = -g + 1.f; f < g; f += 1.f)
{
points.push_back(QVector4D( g, 0.f, f, type));
points.push_back(QVector4D(-g, 0.f, f, type));
points.push_back(QVector4D( f, 0.f, g, type));
points.push_back(QVector4D( f, 0.f,-g, type));
}
// use hesse normal form and transform each grid line onto the specified plane.
QMatrix4x4 T; // ToDo
for (QVector4D & point : points)
point = QVector4D(QVector3D(T * QVector4D(point.toVector3D(), 1.f)), point.w());
m_size = points.size(); // segments * 64 - 4;
m_buffer.create();
m_buffer.setUsagePattern(QOpenGLBuffer::StaticDraw);
m_buffer.bind();
m_buffer.allocate(points.data(), sizeof(float)* 4 * points.size());
}
void AdaptiveGrid::setNearFar(
float zNear
, float zFar)
{
m_program->bind();
m_program->setUniformValue("znear", zNear);
m_program->setUniformValue("zfar", zFar);
m_program->release();
}
void AdaptiveGrid::setColor(const QColor & color)
{
m_program->bind();
m_program->setUniformValue("color", QVector3D(color.redF(), color.greenF(), color.blueF()));
m_program->release();
}
void AdaptiveGrid::update(
const QVector3D & viewpoint
, const QMatrix4x4 & modelViewProjection)
{
// Project the camera's eye position onto the grid plane.
bool intersects; // should always intersect.
const QVector3D i = intersection(intersects, m_location, m_normal
, viewpoint, viewpoint - m_normal);
// This transforms the horizontal plane vectors u and v onto the actual
// grid plane. Than express the intersection i as a linear combination of
// u and v by solving the linear equation system.
// Finally round the s and t values to get the nearest major grid point.
const float l = (viewpoint - i).length();
const float distancelog = log(l * .4998f) / log(8.f);
const float distance = pow(8.f, ceil(distancelog));
QMatrix4x4 T; // ToDo
const QVector3D uv(QVector3D(T * QVector4D(distance, 0.f, 0.f, 1.f)) - m_location);
const float u[3] = { uv.x(), uv.y(), uv.z() };
const QVector3D vv(QVector3D(T * QVector4D(0.f, 0.f, distance, 1.f)) - m_location);
const float v[3] = { vv.x(), vv.y(), vv.z() };
const size_t j = u[0] != 0.0 ? 0 : u[1] != 0.0 ? 1 : 2;
const size_t k = v[0] != 0.0 && j != 0 ? 0 : v[1] != 0.0 && j != 1 ? 1 : 2;
const QVector3D av(i - m_location);
const float a[3] = { av.x(), av.y(), av.z() };
const float t = v[k] ? a[k] / v[k] : 0.f;
const float s = u[j] ? (a[j] - t * v[j]) / u[j] : 0.f;
const QVector3D irounded = round(s) * uv + round(t) * vv;
QMatrix4x4 offset;
offset.translate(irounded);
offset.scale(distance);
m_program->bind();
m_program->setUniformValue("distance", QVector2D(l, mod(distancelog, 1.f)));
m_program->setUniformValue("transform", modelViewProjection * offset);
m_program->release();
}
void AdaptiveGrid::draw(
OpenGLFunctions & gl)
{
gl.glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
gl.glEnable(GL_BLEND);
gl.glEnable(GL_DEPTH_TEST);
m_program->bind();
m_vao.bind();
gl.glDrawArrays(GL_LINES, 0, m_size);
m_vao.release();
m_program->release();
gl.glDisable(GL_BLEND);
}
<|endoftext|> |
<commit_before>#include "DRAMAnalyzer.h"
#include "DRAMAnalyzerSettings.h"
#include <AnalyzerChannelData.h>
#include <iostream>
DRAMAnalyzer::DRAMAnalyzer()
: Analyzer(),
mSettings( new DRAMAnalyzerSettings() ),
mSimulationInitilized( false )
{
SetAnalyzerSettings( mSettings.get() );
}
DRAMAnalyzer::~DRAMAnalyzer()
{
KillThread();
}
void DRAMAnalyzer::WorkerThread()
{
mResults.reset( new DRAMAnalyzerResults( this, mSettings.get() ) );
SetAnalyzerResults( mResults.get() );
mResults->AddChannelBubblesWillAppearOn( mSettings->mCASbChannel );
mRASb = GetAnalyzerChannelData( mSettings->mRASbChannel );
mCASb = GetAnalyzerChannelData( mSettings->mCASbChannel );
mWb = GetAnalyzerChannelData( mSettings->mWbChannel );
mOEb = GetAnalyzerChannelData( mSettings->mOEbChannel );
bool valid_row_addr = false;
for( ; ; ) {
U64 next_RAS = mRASb->GetSampleOfNextEdge();
U64 next_CAS = mCASb->GetSampleOfNextEdge();
// std::cout << next_RAS << " " << next_CAS << std::endl;
bool prev_RASb_is_high = mRASb->GetBitState() == BIT_HIGH;
bool prev_CASb_is_high = mCASb->GetBitState() == BIT_HIGH;
if ( next_RAS <= next_CAS) {
mRASb->AdvanceToNextEdge();
mCASb->AdvanceToAbsPosition( mRASb->GetSampleNumber());
} else {
mCASb->AdvanceToNextEdge();
mRASb->AdvanceToAbsPosition( mCASb->GetSampleNumber());
}
if ( prev_RASb_is_high && prev_CASb_is_high) {
if ( mRASb->GetBitState() == BIT_HIGH) {
if ( mCASb->GetBitState() == BIT_HIGH) {
/* no transition */
} else {
/* CAS */
}
} else {
if ( mCASb->GetBitState() == BIT_HIGH) {
/* RAS */
valid_row_addr = true;
} else {
/* simultaneous flip */
}
}
} else if ( !prev_RASb_is_high && prev_CASb_is_high) {
if ( mRASb->GetBitState() == BIT_HIGH) {
if ( mCASb->GetBitState() == BIT_HIGH) {
/* RASb up */
} else {
/* simult */
}
} else {
if ( mCASb->GetBitState() == BIT_HIGH) {
/* no transition */
} else {
/* write/read */
U64 starting_sample = mCASb->GetSampleNumber();
std::cout << "write/read: " << starting_sample << std::endl;
//we have a byte to save.
Frame frame;
frame.mData1 = 1;
frame.mFlags = 0;
frame.mStartingSampleInclusive = starting_sample;
frame.mEndingSampleInclusive = starting_sample + 100;
mResults->AddMarker( starting_sample, AnalyzerResults::DownArrow, mSettings->mCASbChannel);
mResults->AddFrame( frame );
mResults->CommitResults();
ReportProgress( frame.mEndingSampleInclusive );
}
}
} else if ( prev_RASb_is_high && !prev_CASb_is_high) {
if ( mRASb->GetBitState() == BIT_HIGH) {
if ( mCASb->GetBitState() == BIT_HIGH) {
valid_row_addr = false;
} else {
/* no transition */
}
} else {
if ( mCASb->GetBitState() == BIT_HIGH) {
/* simultaneous flip */
} else {
/* RAS down after CAS down */
}
}
} else if ( !prev_RASb_is_high && !prev_CASb_is_high) {
if ( mRASb->GetBitState() == BIT_HIGH) {
if ( mCASb->GetBitState() == BIT_HIGH) {
/* simultaneous flip */
} else {
/* RAS up */
}
} else {
if ( mCASb->GetBitState() == BIT_HIGH) {
/* CAS up */
} else {
/* no transition */
}
}
}
CheckIfThreadShouldExit();
}
}
bool DRAMAnalyzer::NeedsRerun()
{
return false;
}
U32 DRAMAnalyzer::GenerateSimulationData( U64 minimum_sample_index, U32 device_sample_rate, SimulationChannelDescriptor** simulation_channels )
{
if( mSimulationInitilized == false )
{
mSimulationDataGenerator.Initialize( GetSimulationSampleRate(), mSettings.get() );
mSimulationInitilized = true;
}
return mSimulationDataGenerator.GenerateSimulationData( minimum_sample_index, device_sample_rate, simulation_channels );
}
U32 DRAMAnalyzer::GetMinimumSampleRateHz()
{
return 100000;
}
const char* DRAMAnalyzer::GetAnalyzerName() const
{
return "Asynchoronous DRAM Analyzer";
}
const char* GetAnalyzerName()
{
return "Asynchoronous DRAM Analyzer";
}
Analyzer* CreateAnalyzer()
{
return new DRAMAnalyzer();
}
void DestroyAnalyzer( Analyzer* analyzer )
{
delete analyzer;
}
<commit_msg>Cleaned up analyzer state machine<commit_after>#include "DRAMAnalyzer.h"
#include "DRAMAnalyzerSettings.h"
#include <AnalyzerChannelData.h>
#include <iostream>
DRAMAnalyzer::DRAMAnalyzer()
: Analyzer(),
mSettings( new DRAMAnalyzerSettings() ),
mSimulationInitilized( false )
{
SetAnalyzerSettings( mSettings.get() );
}
DRAMAnalyzer::~DRAMAnalyzer()
{
KillThread();
}
void DRAMAnalyzer::WorkerThread()
{
mResults.reset( new DRAMAnalyzerResults( this, mSettings.get() ) );
SetAnalyzerResults( mResults.get() );
mResults->AddChannelBubblesWillAppearOn( mSettings->mCASbChannel );
mRASb = GetAnalyzerChannelData( mSettings->mRASbChannel );
mCASb = GetAnalyzerChannelData( mSettings->mCASbChannel );
mWb = GetAnalyzerChannelData( mSettings->mWbChannel );
mOEb = GetAnalyzerChannelData( mSettings->mOEbChannel );
bool valid_row_addr = false;
for( ; ; ) {
U64 next_RAS = mRASb->GetSampleOfNextEdge();
U64 next_CAS = mCASb->GetSampleOfNextEdge();
// std::cout << next_RAS << " " << next_CAS << std::endl;
bool prev_RASb_is_high = mRASb->GetBitState() == BIT_HIGH;
bool prev_CASb_is_high = mCASb->GetBitState() == BIT_HIGH;
if ( next_RAS <= next_CAS) {
mRASb->AdvanceToNextEdge();
mCASb->AdvanceToAbsPosition( mRASb->GetSampleNumber());
} else {
mCASb->AdvanceToNextEdge();
mRASb->AdvanceToAbsPosition( mCASb->GetSampleNumber());
}
bool curr_RASb_is_high = mRASb->GetBitState() == BIT_HIGH;
bool curr_CASb_is_high = mCASb->GetBitState() == BIT_HIGH;
if ( prev_RASb_is_high && prev_CASb_is_high) {
if ( curr_RASb_is_high && curr_CASb_is_high) {
/* no transition */
} else if ( curr_RASb_is_high && !curr_CASb_is_high) {
/* CAS */
} else if ( !curr_RASb_is_high && curr_CASb_is_high) {
/* RAS */
valid_row_addr = true;
U64 starting_sample = mRASb->GetSampleNumber();
mResults->AddMarker( starting_sample, AnalyzerResults::DownArrow, mSettings->mRASbChannel);
mResults->AddResultString( "Valid Addr Required");
mResults->CommitResults();
ReportProgress( starting_sample);
} else if ( !curr_RASb_is_high && !curr_CASb_is_high) {
/* simultaneous flip */
}
} else if ( prev_RASb_is_high && !prev_CASb_is_high) {
if ( curr_RASb_is_high && curr_CASb_is_high) {
valid_row_addr = false;
} else if ( curr_RASb_is_high && !curr_CASb_is_high) {
/* no transition */
} else if ( !curr_RASb_is_high && curr_CASb_is_high) {
/* simultaneous flip */
} else if ( !curr_RASb_is_high && !curr_CASb_is_high) {
/* RAS down after CAS down (hidden refresh) */
U64 starting_sample = mRASb->GetSampleNumber();
mResults->AddMarker( starting_sample, AnalyzerResults::Square, mSettings->mRASbChannel);
mResults->CommitResults();
ReportProgress( starting_sample);
}
} else if ( !prev_RASb_is_high && prev_CASb_is_high) {
if ( curr_RASb_is_high && curr_CASb_is_high) {
/* RASb up */
} else if ( curr_RASb_is_high && !curr_CASb_is_high) {
/* simult */
} else if ( !curr_RASb_is_high && curr_CASb_is_high) {
/* no transition */
} else if ( !curr_RASb_is_high && !curr_CASb_is_high) {
/* write/read */
U64 starting_sample = mCASb->GetSampleNumber();
mResults->AddMarker( starting_sample, AnalyzerResults::DownArrow, mSettings->mCASbChannel);
mResults->CommitResults();
ReportProgress( starting_sample);
#if 0
//we have a byte to save.
Frame frame;
frame.mData1 = 1;
frame.mFlags = 0;
frame.mStartingSampleInclusive = starting_sample;
frame.mEndingSampleInclusive = starting_sample + 100;
mResults->AddFrame( frame );
mResults->CommitResults();
ReportProgress( frame.mEndingSampleInclusive );
#endif
}
} else if ( !prev_RASb_is_high && !prev_CASb_is_high) {
if ( curr_RASb_is_high && curr_CASb_is_high) {
/* simultaneous flip */
} else if ( curr_RASb_is_high && !curr_CASb_is_high) {
/* RAS up */
/* write/read */
U64 starting_sample = mRASb->GetSampleNumber();
mResults->AddMarker( starting_sample, AnalyzerResults::UpArrow, mSettings->mRASbChannel);
mResults->CommitResults();
ReportProgress( starting_sample);
} else if ( !curr_RASb_is_high && curr_CASb_is_high) {
/* CAS up */
} else if ( !curr_RASb_is_high && !curr_CASb_is_high) {
/* no transition */
}
}
CheckIfThreadShouldExit();
}
}
bool DRAMAnalyzer::NeedsRerun()
{
return false;
}
U32 DRAMAnalyzer::GenerateSimulationData( U64 minimum_sample_index, U32 device_sample_rate, SimulationChannelDescriptor** simulation_channels )
{
if( mSimulationInitilized == false )
{
mSimulationDataGenerator.Initialize( GetSimulationSampleRate(), mSettings.get() );
mSimulationInitilized = true;
}
return mSimulationDataGenerator.GenerateSimulationData( minimum_sample_index, device_sample_rate, simulation_channels );
}
U32 DRAMAnalyzer::GetMinimumSampleRateHz()
{
return 100000;
}
const char* DRAMAnalyzer::GetAnalyzerName() const
{
return "Asynchoronous DRAM Analyzer";
}
const char* GetAnalyzerName()
{
return "Asynchoronous DRAM Analyzer";
}
Analyzer* CreateAnalyzer()
{
return new DRAMAnalyzer();
}
void DestroyAnalyzer( Analyzer* analyzer )
{
delete analyzer;
}
<|endoftext|> |
<commit_before>//===--- Pseudorandom.cpp - Pseudorandom Utility Functions ---===//
//
// This file is part of the Election Method Mathematics
// Application (EMMA) project.
//
// Copyright (c) 2015 - 2016 Frank D. Martinez and the EMMA project authors
// Licensed under the GNU Affero General Public License, version 3.0.
//
// See the file called "LICENSE" included with this distribution
// for license information.
//
//===----------------------------------------------------------------------===//
//
// A collection of utility functions for when pseudorandom
// number generation and/or selection are required, such normal
// distributions, selection from a collection, etc.
//
//===----------------------------------------------------------------------===//
#include "Pseudorandom.h"
#include <random>
namespace Pseudorandom {
std::default_random_engine prn_generator;
std::normal_distribution<> the_normal_distribution;
double normallyDistributedDouble() {
return the_normal_distribution(prn_generator);
}
}
<commit_msg>using a higher quality PRNG than the default<commit_after>//===--- Pseudorandom.cpp - Pseudorandom Utility Functions ---===//
//
// This file is part of the Election Method Mathematics
// Application (EMMA) project.
//
// Copyright (c) 2015 - 2016 Frank D. Martinez and the EMMA project authors
// Licensed under the GNU Affero General Public License, version 3.0.
//
// See the file called "LICENSE" included with this distribution
// for license information.
//
//===----------------------------------------------------------------------===//
//
// A collection of utility functions for when pseudorandom
// number generation and/or selection are required, such normal
// distributions, selection from a collection, etc.
//
//===----------------------------------------------------------------------===//
#include "Pseudorandom.h"
#include <random>
namespace Pseudorandom {
std::mt19937_64 prn_generator;
std::normal_distribution<> the_normal_distribution;
double normallyDistributedDouble() {
return the_normal_distribution(prn_generator);
}
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.