text
stringlengths 54
60.6k
|
|---|
<commit_before>//
// Matirx.hpp
// ~~~~~~~~~~
//
// Copyright (c) 2014 Rick Yang (rick68 at gmail dot com)
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
#ifndef EIGENJS_MATRIX_HPP
#define EIGENJS_MATRIX_HPP
#include <node.h>
#include <v8.h>
#include <nan.h>
#include <eigen3/Eigen/Eigen>
#include <sstream>
namespace EigenJS {
class Matrix : public node::ObjectWrap {
public:
static void Init(v8::Handle<v8::Object> exports) {
NanScope();
v8::Local<v8::FunctionTemplate> tpl = NanNew<v8::FunctionTemplate>(New);
tpl->SetClassName(NanNew("Matrix"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
NODE_SET_PROTOTYPE_METHOD(tpl, "rows", rows);
NODE_SET_PROTOTYPE_METHOD(tpl, "cols", cols);
NODE_SET_PROTOTYPE_METHOD(tpl, "set", set);
NODE_SET_PROTOTYPE_METHOD(tpl, "get", get);
NODE_SET_PROTOTYPE_METHOD(tpl, "toString", toString);
NanAssignPersistent(constructor, tpl->GetFunction());
exports->Set(NanNew("Matrix"), tpl->GetFunction());
}
static NAN_METHOD(rows) {
const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
NanScope();
NanReturnValue(NanNew<v8::Integer>(obj->matrix_.rows()));
}
static NAN_METHOD(cols) {
const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
NanScope();
NanReturnValue(NanNew<v8::Integer>(obj->matrix_.cols()));
}
static NAN_METHOD(set) {
NanScope();
if (args.Length() == 3 &&
args[0]->IsNumber() &&
args[1]->IsNumber() &&
args[2]->IsNumber()) {
matrix_type::Index row = args[0]->Uint32Value();
matrix_type::Index col = args[1]->Uint32Value();
element_type value = args[2]->NumberValue();
Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
if (is_out_of_range(obj->matrix_, row, col))
NanReturnUndefined();
obj->matrix_(row, col) = value;
}
NanReturnValue(NanNew(args.This()));
}
static NAN_METHOD(get) {
const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
NanScope();
if (args.Length() == 2 &&
args[0]->IsNumber() &&
args[1]->IsNumber()) {
matrix_type::Index row = args[0]->Uint32Value();
matrix_type::Index col = args[1]->Uint32Value();
if (is_out_of_range(obj->matrix_, row, col))
NanReturnUndefined();
element_type value = obj->matrix_(row, col);
NanReturnValue(NanNew(value));
}
NanReturnUndefined();
}
static NAN_METHOD(toString) {
const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
NanScope();
std::ostringstream result;
result << obj->matrix_;
NanReturnValue(NanNew(result.str().c_str()));
}
private:
typedef double element_type;
typedef Eigen::Matrix<
element_type
, Eigen::Dynamic
, Eigen::Dynamic
> matrix_type;
Matrix(matrix_type::Index rows, matrix_type::Index cols)
: matrix_(matrix_type::Zero(rows, cols))
{}
~Matrix() {}
static NAN_METHOD(New) {
NanScope();
if (args.Length() < 2) {
NanThrowError("Tried creating matrix without rows and columns arguments");
NanReturnUndefined();
}
if (args.IsConstructCall()) {
matrix_type::Index rows = args[0]->Uint32Value();
matrix_type::Index columns = args[1]->Uint32Value();
Matrix* obj = new Matrix(rows, columns);
obj->Wrap(args.This());
NanReturnValue(args.This());
} else {
v8::Local<v8::Function> ctr = NanNew(constructor);
v8::Local<v8::Value> argv[] = {args[0], args[1]};
NanReturnValue(
ctr->NewInstance(
sizeof(argv)/sizeof(v8::Local<v8::Value>)
, argv
)
);
}
}
static v8::Persistent<v8::Function> constructor;
private:
static bool is_out_of_range(
const matrix_type& matrix
, const matrix_type::Index& row
, const matrix_type::Index& col) {
return row < 0 || row >= matrix.rows() || col < 0 || col >= matrix.cols()
? NanThrowError("Row or column numbers are out of range"), true
: false;
}
private:
matrix_type matrix_;
};
v8::Persistent<v8::Function> Matrix::constructor;
} // namespace EigenJS
#endif // EIGENJS_MATRIX_HPP
<commit_msg>src: add 'Matrix.set()' to support Array argument<commit_after>//
// Matirx.hpp
// ~~~~~~~~~~
//
// Copyright (c) 2014 Rick Yang (rick68 at gmail dot com)
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
#ifndef EIGENJS_MATRIX_HPP
#define EIGENJS_MATRIX_HPP
#include <node.h>
#include <v8.h>
#include <nan.h>
#include <eigen3/Eigen/Eigen>
#include <sstream>
namespace EigenJS {
class Matrix : public node::ObjectWrap {
public:
static void Init(v8::Handle<v8::Object> exports) {
NanScope();
v8::Local<v8::FunctionTemplate> tpl = NanNew<v8::FunctionTemplate>(New);
tpl->SetClassName(NanNew("Matrix"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
NODE_SET_PROTOTYPE_METHOD(tpl, "rows", rows);
NODE_SET_PROTOTYPE_METHOD(tpl, "cols", cols);
NODE_SET_PROTOTYPE_METHOD(tpl, "set", set);
NODE_SET_PROTOTYPE_METHOD(tpl, "get", get);
NODE_SET_PROTOTYPE_METHOD(tpl, "toString", toString);
NanAssignPersistent(constructor, tpl->GetFunction());
exports->Set(NanNew("Matrix"), tpl->GetFunction());
}
static NAN_METHOD(rows) {
const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
NanScope();
NanReturnValue(NanNew<v8::Integer>(obj->matrix_.rows()));
}
static NAN_METHOD(cols) {
const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
NanScope();
NanReturnValue(NanNew<v8::Integer>(obj->matrix_.cols()));
}
static NAN_METHOD(set) {
Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
NanScope();
if (args.Length() == 1 && args[0]->IsArray()) {
v8::Local<v8::Array> array = args[0].As<v8::Array>();
uint32_t len = array->Length();
const matrix_type::Index& rows = obj->matrix_.rows();
for (uint32_t i = 0; i < len; ++i) {
v8::Local<v8::Value> elem = array->Get(i);
obj->matrix_(i / rows, i % rows) = elem->NumberValue();
}
} else if (
args.Length() == 3 &&
args[0]->IsNumber() &&
args[1]->IsNumber() &&
args[2]->IsNumber()) {
matrix_type::Index row = args[0]->Uint32Value();
matrix_type::Index col = args[1]->Uint32Value();
element_type value = args[2]->NumberValue();
if (is_out_of_range(obj->matrix_, row, col))
NanReturnUndefined();
obj->matrix_(row, col) = value;
}
NanReturnValue(NanNew(args.This()));
}
static NAN_METHOD(get) {
const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
NanScope();
if (args.Length() == 2 &&
args[0]->IsNumber() &&
args[1]->IsNumber()) {
matrix_type::Index row = args[0]->Uint32Value();
matrix_type::Index col = args[1]->Uint32Value();
if (is_out_of_range(obj->matrix_, row, col))
NanReturnUndefined();
element_type value = obj->matrix_(row, col);
NanReturnValue(NanNew(value));
}
NanReturnUndefined();
}
static NAN_METHOD(toString) {
const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
NanScope();
std::ostringstream result;
result << obj->matrix_;
NanReturnValue(NanNew(result.str().c_str()));
}
private:
typedef double element_type;
typedef Eigen::Matrix<
element_type
, Eigen::Dynamic
, Eigen::Dynamic
> matrix_type;
Matrix(matrix_type::Index rows, matrix_type::Index cols)
: matrix_(matrix_type::Zero(rows, cols))
{}
~Matrix() {}
static NAN_METHOD(New) {
NanScope();
if (args.Length() < 2) {
NanThrowError("Tried creating matrix without rows and columns arguments");
NanReturnUndefined();
}
if (args.IsConstructCall()) {
matrix_type::Index rows = args[0]->Uint32Value();
matrix_type::Index columns = args[1]->Uint32Value();
Matrix* obj = new Matrix(rows, columns);
obj->Wrap(args.This());
NanReturnValue(args.This());
} else {
v8::Local<v8::Function> ctr = NanNew(constructor);
v8::Local<v8::Value> argv[] = {args[0], args[1]};
NanReturnValue(
ctr->NewInstance(
sizeof(argv)/sizeof(v8::Local<v8::Value>)
, argv
)
);
}
}
static v8::Persistent<v8::Function> constructor;
private:
static bool is_out_of_range(
const matrix_type& matrix
, const matrix_type::Index& row
, const matrix_type::Index& col) {
return row < 0 || row >= matrix.rows() || col < 0 || col >= matrix.cols()
? NanThrowError("Row or column numbers are out of range"), true
: false;
}
private:
matrix_type matrix_;
};
v8::Persistent<v8::Function> Matrix::constructor;
} // namespace EigenJS
#endif // EIGENJS_MATRIX_HPP
<|endoftext|>
|
<commit_before>// [[Rcpp::depends(BH)]]
#include "Random.h"
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_01.hpp>
#include <boost/random/uniform_real_distribution.hpp>
#include <boost/random/normal_distribution.hpp>
#include <boost/random/poisson_distribution.hpp>
#include <boost/random/exponential_distribution.hpp>
#include <boost/math/distributions/gamma.hpp>
#include <boost/math/distributions/normal.hpp>
#include <boost/math/distributions/exponential.hpp>
#include <stdint.h>
#define Q_GAMMA_THRESHOLD 1E-6
#define Q_GAMMA_MIN_VALUE 0.0
typedef boost::random::mt19937 RNGType;
//typedef boost::random::mt11213b RNGType; // should be faster
static RNGType rng;
void gaps::random::setSeed(uint32_t seed)
{
rng.seed(seed);
}
double gaps::random::normal(double mean, double var)
{
boost::random::normal_distribution<double> dist(mean, var);
return dist(rng);
}
int gaps::random::poisson(double lambda)
{
boost::random::poisson_distribution<> dist(lambda);
return dist(rng);
}
double gaps::random::exponential(double lambda)
{
boost::random::exponential_distribution<> dist(lambda);
return dist(rng);
}
double gaps::random::uniform()
{
boost::random::uniform_01<RNGType&> dist(rng); // could be moved out
return dist();
}
double gaps::random::uniform(double a, double b)
{
if (a == b)
{
return a;
}
else if (a < b)
{
boost::random::uniform_real_distribution<> dist(a,b);
return dist(rng);
}
}
uint64_t gaps::random::uniform64()
{
boost::random::uniform_int_distribution<uint64_t> dist(0,
std::numeric_limits<uint64_t>::max());
return dist(rng);
}
uint64_t gaps::random::uniform64(uint64_t a, uint64_t b)
{
if (a == b)
{
return a;
}
else if (a < b)
{
boost::random::uniform_int_distribution<uint64_t> dist(a,b);
return dist(rng);
}
}
double gaps::random::d_gamma(double d, double shape, double scale)
{
boost::math::gamma_distribution<> gam(shape, scale);
return pdf(gam, d);
}
double gaps::random::p_gamma(double p, double shape, double scale)
{
boost::math::gamma_distribution<> gam(shape, scale);
return cdf(gam, p);
}
double gaps::random::q_gamma(double q, double shape, double scale)
{
if (q < Q_GAMMA_THRESHOLD)
{
return Q_GAMMA_MIN_VALUE;
}
else
{
boost::math::gamma_distribution<> gam(shape, scale);
return quantile(gam, q);
}
}
double gaps::random::d_norm(double d, double mean, double sd)
{
boost::math::normal_distribution<> norm(mean, sd);
return pdf(norm, d);
}
double gaps::random::q_norm(double q, double mean, double sd)
{
boost::math::normal_distribution<> norm(mean, sd);
return quantile(norm, q);
}
double gaps::random::p_norm(double p, double mean, double sd)
{
boost::math::normal_distribution<> norm(mean, sd);
return cdf(norm, p);
}
<commit_msg>disable optimization around boost - needed for valgrind<commit_after>// [[Rcpp::depends(BH)]]
// needed to run in valgrind
#pragma GCC push_options
#pragma GCC optimize ("O0")
#include "Random.h"
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_01.hpp>
#include <boost/random/uniform_real_distribution.hpp>
#include <boost/random/normal_distribution.hpp>
#include <boost/random/poisson_distribution.hpp>
#include <boost/random/exponential_distribution.hpp>
#include <boost/math/distributions/gamma.hpp>
#include <boost/math/distributions/normal.hpp>
#include <boost/math/distributions/exponential.hpp>
#include <stdint.h>
#define Q_GAMMA_THRESHOLD 1E-6
#define Q_GAMMA_MIN_VALUE 0.0
typedef boost::random::mt19937 RNGType;
//typedef boost::random::mt11213b RNGType; // should be faster
static RNGType rng;
void gaps::random::setSeed(uint32_t seed)
{
rng.seed(seed);
}
double gaps::random::normal(double mean, double var)
{
boost::random::normal_distribution<double> dist(mean, var);
return dist(rng);
}
int gaps::random::poisson(double lambda)
{
boost::random::poisson_distribution<> dist(lambda);
return dist(rng);
}
double gaps::random::exponential(double lambda)
{
boost::random::exponential_distribution<> dist(lambda);
return dist(rng);
}
double gaps::random::uniform()
{
boost::random::uniform_01<RNGType&> dist(rng); // could be moved out
return dist();
}
double gaps::random::uniform(double a, double b)
{
if (a == b)
{
return a;
}
else if (a < b)
{
boost::random::uniform_real_distribution<> dist(a,b);
return dist(rng);
}
}
uint64_t gaps::random::uniform64()
{
boost::random::uniform_int_distribution<uint64_t> dist(0,
std::numeric_limits<uint64_t>::max());
return dist(rng);
}
uint64_t gaps::random::uniform64(uint64_t a, uint64_t b)
{
if (a == b)
{
return a;
}
else if (a < b)
{
boost::random::uniform_int_distribution<uint64_t> dist(a,b);
return dist(rng);
}
}
double gaps::random::d_gamma(double d, double shape, double scale)
{
boost::math::gamma_distribution<> gam(shape, scale);
return pdf(gam, d);
}
double gaps::random::p_gamma(double p, double shape, double scale)
{
boost::math::gamma_distribution<> gam(shape, scale);
return cdf(gam, p);
}
double gaps::random::q_gamma(double q, double shape, double scale)
{
if (q < Q_GAMMA_THRESHOLD)
{
return Q_GAMMA_MIN_VALUE;
}
else
{
boost::math::gamma_distribution<> gam(shape, scale);
return quantile(gam, q);
}
}
double gaps::random::d_norm(double d, double mean, double sd)
{
boost::math::normal_distribution<> norm(mean, sd);
return pdf(norm, d);
}
double gaps::random::q_norm(double q, double mean, double sd)
{
boost::math::normal_distribution<> norm(mean, sd);
return quantile(norm, q);
}
double gaps::random::p_norm(double p, double mean, double sd)
{
boost::math::normal_distribution<> norm(mean, sd);
return cdf(norm, p);
}
#pragma GCC pop_options<|endoftext|>
|
<commit_before>#include <SDL.h>
#include <iostream>
#include "SnakeEngine.h"
#include <vector>
const int SCREEN_WIDTH = 1920;
const int SCREEN_HEIGHT = 1200;
//const int SCREEN_WIDTH = 1366;
//const int SCREEN_HEIGHT = 768;
const int SNAKE_GRID_WIDTH = BOARD_WIDTH;
const int SNAKE_GRID_HEIGHT = BOARD_HEIGHT;
const int SNAKE_CELL_W_PX = SCREEN_WIDTH/SNAKE_GRID_WIDTH;
const int SNAKE_CELL_H_PX = SCREEN_HEIGHT/SNAKE_GRID_HEIGHT;
// Fixed game logic step
const Uint32 TICK_STEP = 60; // ms
void updateRects(std::vector<SDL_Rect>* rectVec, std::vector<SnakeEngine::BoardPos*>* snakeVec)
{
int numRects = rectVec->size();
int numSnakeSquares = snakeVec->size();
// Just fill rectVec with sufficient rectangles at first
while (numSnakeSquares > numRects) {
SDL_Rect fillerRect;
fillerRect.w = SNAKE_CELL_W_PX;
fillerRect.h = SNAKE_CELL_H_PX;
rectVec->insert(rectVec->begin(), fillerRect);
numRects = rectVec->size();
}
int rectVecIndex = 0;
for (auto& pos : *snakeVec) {
int gridX = pos->x;
int gridY = pos->y;
int screenX = gridX*SNAKE_CELL_W_PX;
int screenY = gridY*SNAKE_CELL_H_PX;
rectVec->at(rectVecIndex).x = screenX;
rectVec->at(rectVecIndex).y = screenY;
rectVecIndex++;
}
}
int main(int arc, char* argv[])
{
// Create SnakeEngine object, which is responsible for all game logic
SnakeEngine engine(SnakeEngine::NORTH);
///////////////////////////////////////////////////////
// Init a bunch of SDL stuff (graphics and user input)
///////////////////////////////////////////////////////
// INIT engine
if (SDL_Init(SDL_INIT_EVERYTHING) == -1) {
std::cout << SDL_GetError() << std::endl;
return 1;
}
// Make the window
SDL_Window *screen = nullptr;
screen = SDL_CreateWindow("MaxGFX Extreme",
0,
0,
SCREEN_WIDTH,
SCREEN_HEIGHT,
SDL_WINDOW_FULLSCREEN);
if (screen == nullptr) {
std::cout << SDL_GetError() << std::endl;
return 1;
}
// Make the renderer
SDL_Renderer *renderer = nullptr;
renderer = SDL_CreateRenderer(screen, -1, SDL_RENDERER_ACCELERATED);
if (renderer == nullptr) {
std::cout << SDL_GetError() << std::endl;
return 1;
}
// Make event object to receive input events
SDL_Event event;
// Set background to black
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderClear(renderer);
// Create a vector for holding all SDL_Rects needed to draw snake
std::vector<SDL_Rect> snakeRects;
// Fill it
updateRects(&snakeRects, engine.getSnakeVector());
// Create a rect for an apple
SDL_Rect appleRect;
appleRect.w = SNAKE_CELL_W_PX;
appleRect.h = SNAKE_CELL_H_PX;
appleRect.x = engine.getAppleX()*SNAKE_CELL_W_PX;
appleRect.y = engine.getAppleY()*SNAKE_CELL_H_PX;
// Remove the cursor and set a delay for the startup
SDL_ShowCursor(0);
SDL_Delay(500);
///////////////////////////////////////////////////////
// GAME LOOP
///////////////////////////////////////////////////////
bool running = true;
Uint32 lastTick = SDL_GetTicks()-100;
bool doTick = true;
while (running)
{
// Checks for input events, such as clicking "X"/close on the window or keyboard input
if (SDL_PollEvent(&event))
{
if (event.type == SDL_QUIT)
{
running = false;
}
if (event.type == SDL_KEYDOWN)
{
switch(event.key.keysym.sym) {
case SDLK_ESCAPE:
running = false;
break;
case SDLK_w:
engine.setDirection(SnakeEngine::NORTH);
break;
case SDLK_a:
engine.setDirection(SnakeEngine::WEST);
break;
case SDLK_s:
engine.setDirection(SnakeEngine::SOUTH);
break;
case SDLK_d:
engine.setDirection(SnakeEngine::EAST);
break;
}
}
}
// Game logic
if (!doTick) {
if ((SDL_GetTicks() - lastTick) > TICK_STEP) {
doTick = true;
lastTick = SDL_GetTicks();
}
}
if (doTick) {
engine.tick();
doTick = false;
if (engine.hasCrashed()) {
running = false;
SDL_Delay(1000);
}
}
// Rendering
updateRects(&snakeRects, engine.getSnakeVector());
appleRect.x = engine.getAppleX()*SNAKE_CELL_W_PX;
appleRect.y = engine.getAppleY()*SNAKE_CELL_H_PX;
// Set background to black and clear
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderClear(renderer);
// Draw snake
SDL_SetRenderDrawColor(renderer, 12, 172, 12, 255);
for (auto& rect : snakeRects) {
SDL_RenderFillRect(renderer, &rect);
}
// Draw an apple
SDL_SetRenderDrawColor(renderer, 202, 3, 3, 255);
SDL_RenderFillRect(renderer, &appleRect);
SDL_RenderPresent(renderer);
}
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(screen);
SDL_Quit();
return 0;
}<commit_msg>No longer needed Source.cpp, now main.cpp<commit_after><|endoftext|>
|
<commit_before>// Vaca - Visual Application Components Abstraction
// Copyright (c) 2005-2009 David Capello
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
// * Neither the name of the author nor the names of its contributors
// may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
#include "Vaca/System.h"
#include "Vaca/Rect.h"
#include "Vaca/Point.h"
#include "Vaca/Size.h"
#include "Vaca/Color.h"
#include "Vaca/Debug.h"
#include "Vaca/ImageList.h"
#include "Vaca/Mutex.h"
#include "Vaca/ScopedLock.h"
#include <lmcons.h>
using namespace Vaca;
/// Returns the parameters in the command line.
///
/// @c System::getArgs()[0] is the name of the executable file.
///
std::vector<String> System::getArgs()
{
// Convert the command-line to a vector of arguments...
std::vector<String> args;
Char* cmdline = wcsdup(GetCommandLine());
Char quote;
for (int i = 0; cmdline[i] != 0; ) {
// eat spaces
while (cmdline[i] != 0 && iswspace(cmdline[i]))
++i;
// string with quotes?
if (cmdline[i] == '\"' || cmdline[i] == '\'')
quote = cmdline[i++];
else if (cmdline[i] == 0)
break;
else
quote = 0;
// read the string
String arg;
for (; cmdline[i] != 0; ++i) {
// with quotes
if (quote != 0) {
if (cmdline[i] == quote) {
++i;
break;
}
else if (cmdline[i] == '\\' && cmdline[i+1] == quote)
++i;
}
// without quotes
else if (iswspace(cmdline[i]))
break;
arg.push_back(cmdline[i]);
}
args.push_back(arg);
}
std::free(cmdline);
return args;
}
/// Prints a line in the console.
///
void System::println(String line)
{
#ifdef _UNICODE
_putws(line.c_str());
#else
puts(line.c_str());
#endif
}
void System::printf(LPCTSTR fmt, ...)
{
Char buf[1024]; // TODO: overflow
va_list ap;
va_start(ap, fmt);
#ifdef UNICODE
vswprintf(buf, fmt, ap);
#else
vsprintf(buf, fmt, ap);
#endif
va_end(ap);
#ifdef UNICODE
fputws(buf, stdout);
#else
fputs(buf, stdout);
#endif
}
void System::print(String buf)
{
#ifdef UNICODE
fputws(buf.c_str(), stdout);
#else
fputs(buf.c_str(), stdout);
#endif
}
String System::getCurrentDirectory()
{
Char* buf = new Char[MAX_PATH];
if (GetCurrentDirectory(MAX_PATH, buf) > 0)
return String(buf);
else
return L"";
}
String System::getWindowsDirectory()
{
Char* buf = new Char[MAX_PATH];
if (GetWindowsDirectory(buf, MAX_PATH) > 0)
return String(buf);
else
return L"";
}
///
/// TODO folderCsidl can't be a virtual folder
///
/// CSIDL_ADMINTOOLS
/// CSIDL_ALTSTARTUP
/// CSIDL_APPDATA
/// CSIDL_BITBUCKET
/// CSIDL_CDBURN_AREA
/// CSIDL_COMMON_ADMINTOOLS
/// CSIDL_COMMON_ALTSTARTUP
/// CSIDL_COMMON_APPDATA
/// CSIDL_COMMON_DESKTOPDIRECTORY
/// CSIDL_COMMON_DOCUMENTS
/// CSIDL_COMMON_FAVORITES
/// CSIDL_COMMON_MUSIC
/// CSIDL_COMMON_OEM_LINKS
/// CSIDL_COMMON_PICTURES
/// CSIDL_COMMON_PROGRAMS
/// CSIDL_COMMON_STARTMENU
/// CSIDL_COMMON_STARTUP
/// CSIDL_COMMON_TEMPLATES
/// CSIDL_COMMON_VIDEO
/// CSIDL_COMPUTERSNEARME
/// CSIDL_CONNECTIONS
/// CSIDL_CONTROLS
/// CSIDL_COOKIES
/// CSIDL_DESKTOP
/// CSIDL_DESKTOPDIRECTORY
/// CSIDL_DRIVES
/// CSIDL_FAVORITES
/// CSIDL_FONTS
/// CSIDL_HISTORY
/// CSIDL_INTERNET
/// CSIDL_INTERNET_CACHE
/// CSIDL_LOCAL_APPDATA
/// CSIDL_MYPICTURES
/// CSIDL_NETHOOD
/// CSIDL_NETWORK
/// CSIDL_PERSONAL
/// CSIDL_PRINTERS
/// CSIDL_PRINTHOOD
/// CSIDL_PROFILE
/// CSIDL_PROGRAMS
/// CSIDL_PROGRAM_FILES
/// CSIDL_PROGRAM_FILESX86
/// CSIDL_PROGRAM_FILES_COMMON
/// CSIDL_PROGRAM_FILES_COMMONX86
/// CSIDL_RECENT
/// CSIDL_RESOURCES
/// CSIDL_RESOURCES_LOCALIZED
/// CSIDL_SENDTO
/// CSIDL_STARTMENU
/// CSIDL_STARTUP
/// CSIDL_SYSTEM
/// CSIDL_SYSTEMX86
/// CSIDL_TEMPLATES
/// CSIDL_WINDOWS
///
String System::getShellFolderPath(int folderCsidl, bool create)
{
Char* buf = new Char[MAX_PATH];
if (SHGetSpecialFolderPath(NULL, buf, folderCsidl, create))
return String(buf);
else
return L"";
}
ImageList System::getImageList(bool smallImage)
{
HIMAGELIST himl;
SHFILEINFO shfi;
himl = reinterpret_cast<HIMAGELIST>
(SHGetFileInfo(L"",
0, &shfi, sizeof(shfi),
SHGFI_SYSICONINDEX |
(smallImage ? SHGFI_SMALLICON:
SHGFI_LARGEICON)));
return ImageList(himl); // TODO this can't be delete!!!
}
int System::getFileImageIndex(const String& fileName, bool smallImage)
{
SHFILEINFO shfi;
SHGetFileInfo(fileName.c_str(), 0, &shfi, sizeof(shfi),
SHGFI_SYSICONINDEX |
(smallImage ? SHGFI_SMALLICON:
SHGFI_LARGEICON));
return shfi.iIcon;
}
/// Returns the screen size.
///
Size System::getScreenSize()
{
return Size(GetSystemMetrics(SM_CXFULLSCREEN),
GetSystemMetrics(SM_CYFULLSCREEN));
}
/// Returns the work-area of the screen, it is like the desktop area,
/// that is not overlapped by the task-bar.
///
/// @warning
/// Win32: It is a call to @msdn{SystemParametersInfo} using
/// @msdn{SPI_GETWORKAREA}.
///
Rect System::getWorkAreaBounds()
{
RECT rc;
// returns the work-area rectangle
if (SystemParametersInfo(SPI_GETWORKAREA, 0, reinterpret_cast<PVOID>(&rc), 0))
return Rect(&rc);
// returns the full-screen rectangle
else
return Rect(Point(0, 0), System::getScreenSize());
}
/// Returns color from the system. It's a wrapper for the Win32's GetSysColor.
///
/// @param index
/// Can be one of the following values:
/// @li COLOR_3DDKSHADOW
/// @li COLOR_3DFACE
/// @li COLOR_3DHILIGHT
/// @li COLOR_3DHIGHLIGHT
/// @li COLOR_3DLIGHT
/// @li COLOR_BTNHILIGHT
/// @li COLOR_3DSHADOW
/// @li COLOR_ACTIVEBORDER
/// @li COLOR_ACTIVECAPTION
/// @li COLOR_APPWORKSPACE
/// @li COLOR_BACKGROUND
/// @li COLOR_DESKTOP
/// @li COLOR_BTNFACE
/// @li COLOR_BTNHIGHLIGHT
/// @li COLOR_BTNSHADOW
/// @li COLOR_BTNTEXT
/// @li COLOR_CAPTIONTEXT
/// @li COLOR_GRAYTEXT
/// @li COLOR_HIGHLIGHT
/// @li COLOR_HIGHLIGHTTEXT
/// @li COLOR_INACTIVEBORDER
/// @li COLOR_INACTIVECAPTION
/// @li COLOR_INACTIVECAPTIONTEXT
/// @li COLOR_INFOBK
/// @li COLOR_INFOTEXT
/// @li COLOR_MENU
/// @li COLOR_MENUTEXT
/// @li COLOR_SCROLLBAR
/// @li COLOR_WINDOW
/// @li COLOR_WINDOWFRAME
/// @li COLOR_WINDOWTEXT
/// @li COLOR_HOTLIGHT
/// @li COLOR_GRADIENTACTIVECAPTION
/// @li COLOR_GRADIENTINACTIVECAPTION
///
/// @todo make the index a Enum
///
Color System::getColor(int index)
{
return Color(GetSysColor(index));
}
bool System::getKeyState(Keys::Type keyCode)
{
// you can't use getKeyState for modifiers
assert((keyCode & Keys::Modifiers) == 0);
return (GetKeyState(keyCode) & 0x8000) != 0;
}
/// Returns the cursor position in the screen.
///
Point System::getCursorPos()
{
POINT pt;
GetCursorPos(&pt);
return Point(pt.x, pt.y);
}
void System::setCursorPos(const Point& pt)
{
SetCursorPos(pt.x, pt.y);
}
String System::getUserName()
{
Char buf[UNLEN+1];
// char buf[UNLEN+1];
DWORD len = UNLEN+1;
if (GetUserName(buf, &len))
return String(buf);
else
return String();
}
// Prototypes for Win2000/XP API
// typedef BOOLEAN (*GUNEProc)(EXTENDED_NAME_FORMAT NameFormat, LPTSTR lpNameBuffer, PULONG nSize);
String System::getFriendlyUserName()
{
#if 0 // TODO
#if (_WIN32_WINNT >= 0x0500)
HMODULE hSecur32 = GetModuleHandle(L"SECUR32.DLL");
if (!hSecur32)
hSecur32 = LoadLibrary(L"SECUR32.DLL");
GUNEProc pGUNE = (GUNEProc)GetProcAddress(hSecur32, "GetUserNameExW");
if (pGUNE != NULL) {
Char buf[UNLEN+1];
ULONG len = UNLEN+1;
if (pGUNE(NameDisplay, buf, &len))
return String(buf);
}
#endif
#endif
return getUserName();
}
// int System::getWheelScrollLines()
// {
// UINT pulScrollLines = 0;
// return SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, &pulScrollLines, 0);
// }
int System::getOS()
{
static Mutex mutex;
static volatile OS::Type cached = OS::Unknown;
ScopedLock hold(mutex);
if (cached != OS::Unknown)
return cached;
OSVERSIONINFOEX osvi;
BOOL bOsVersionInfoEx;
ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
if (!(bOsVersionInfoEx = GetVersionEx((OSVERSIONINFO*)&osvi))) {
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
if (!GetVersionEx((OSVERSIONINFO*)&osvi))
return OS::Unknown;
}
switch (osvi.dwPlatformId) {
case VER_PLATFORM_WIN32_NT:
if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2)
return cached = OS::WinServer2003;
else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1)
return cached = OS::WinXP;
else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0)
return cached = OS::Win2K;
else if (osvi.dwMajorVersion <= 4)
return cached = OS::WinNT;
break;
case VER_PLATFORM_WIN32_WINDOWS:
if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0) {
if (osvi.szCSDVersion[1] == 'C' || osvi.szCSDVersion[1] == 'B')
return cached = OS::Win95R2;
else
return cached = OS::Win95;
}
else if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10) {
if (osvi.szCSDVersion[1] == 'A')
return cached = OS::Win98SE;
else
return cached = OS::Win98;
}
else if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90)
return cached = OS::WinMe;
break;
case VER_PLATFORM_WIN32s:
return cached = OS::Win32s;
}
return cached = OS::Unknown;
}
bool System::isWin95_98_Me()
{
return (getOS() & (OS::Win95 | OS::Win98 | OS::WinMe)) != 0;
}
bool System::isWinNT_2K_XP()
{
return (getOS() & (OS::WinNT | OS::Win2K | OS::WinXP | OS::WinServer2003)) != 0;
}
bool System::isWin2K_XP()
{
return (getOS() & (OS::Win2K | OS::WinXP | OS::WinServer2003)) != 0;
}
bool System::isWinXP()
{
return (getOS() & OS::WinXP) != 0;
}
<commit_msg>Fixed System::getWorkAreaBounds() documentation.<commit_after>// Vaca - Visual Application Components Abstraction
// Copyright (c) 2005-2009 David Capello
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
// * Neither the name of the author nor the names of its contributors
// may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
#include "Vaca/System.h"
#include "Vaca/Rect.h"
#include "Vaca/Point.h"
#include "Vaca/Size.h"
#include "Vaca/Color.h"
#include "Vaca/Debug.h"
#include "Vaca/ImageList.h"
#include "Vaca/Mutex.h"
#include "Vaca/ScopedLock.h"
#include <lmcons.h>
using namespace Vaca;
/// Returns the parameters in the command line.
///
/// @c System::getArgs()[0] is the name of the executable file.
///
std::vector<String> System::getArgs()
{
// Convert the command-line to a vector of arguments...
std::vector<String> args;
Char* cmdline = wcsdup(GetCommandLine());
Char quote;
for (int i = 0; cmdline[i] != 0; ) {
// eat spaces
while (cmdline[i] != 0 && iswspace(cmdline[i]))
++i;
// string with quotes?
if (cmdline[i] == '\"' || cmdline[i] == '\'')
quote = cmdline[i++];
else if (cmdline[i] == 0)
break;
else
quote = 0;
// read the string
String arg;
for (; cmdline[i] != 0; ++i) {
// with quotes
if (quote != 0) {
if (cmdline[i] == quote) {
++i;
break;
}
else if (cmdline[i] == '\\' && cmdline[i+1] == quote)
++i;
}
// without quotes
else if (iswspace(cmdline[i]))
break;
arg.push_back(cmdline[i]);
}
args.push_back(arg);
}
std::free(cmdline);
return args;
}
/// Prints a line in the console.
///
void System::println(String line)
{
#ifdef _UNICODE
_putws(line.c_str());
#else
puts(line.c_str());
#endif
}
void System::printf(LPCTSTR fmt, ...)
{
Char buf[1024]; // TODO: overflow
va_list ap;
va_start(ap, fmt);
#ifdef UNICODE
vswprintf(buf, fmt, ap);
#else
vsprintf(buf, fmt, ap);
#endif
va_end(ap);
#ifdef UNICODE
fputws(buf, stdout);
#else
fputs(buf, stdout);
#endif
}
void System::print(String buf)
{
#ifdef UNICODE
fputws(buf.c_str(), stdout);
#else
fputs(buf.c_str(), stdout);
#endif
}
String System::getCurrentDirectory()
{
Char* buf = new Char[MAX_PATH];
if (GetCurrentDirectory(MAX_PATH, buf) > 0)
return String(buf);
else
return L"";
}
String System::getWindowsDirectory()
{
Char* buf = new Char[MAX_PATH];
if (GetWindowsDirectory(buf, MAX_PATH) > 0)
return String(buf);
else
return L"";
}
///
/// TODO folderCsidl can't be a virtual folder
///
/// CSIDL_ADMINTOOLS
/// CSIDL_ALTSTARTUP
/// CSIDL_APPDATA
/// CSIDL_BITBUCKET
/// CSIDL_CDBURN_AREA
/// CSIDL_COMMON_ADMINTOOLS
/// CSIDL_COMMON_ALTSTARTUP
/// CSIDL_COMMON_APPDATA
/// CSIDL_COMMON_DESKTOPDIRECTORY
/// CSIDL_COMMON_DOCUMENTS
/// CSIDL_COMMON_FAVORITES
/// CSIDL_COMMON_MUSIC
/// CSIDL_COMMON_OEM_LINKS
/// CSIDL_COMMON_PICTURES
/// CSIDL_COMMON_PROGRAMS
/// CSIDL_COMMON_STARTMENU
/// CSIDL_COMMON_STARTUP
/// CSIDL_COMMON_TEMPLATES
/// CSIDL_COMMON_VIDEO
/// CSIDL_COMPUTERSNEARME
/// CSIDL_CONNECTIONS
/// CSIDL_CONTROLS
/// CSIDL_COOKIES
/// CSIDL_DESKTOP
/// CSIDL_DESKTOPDIRECTORY
/// CSIDL_DRIVES
/// CSIDL_FAVORITES
/// CSIDL_FONTS
/// CSIDL_HISTORY
/// CSIDL_INTERNET
/// CSIDL_INTERNET_CACHE
/// CSIDL_LOCAL_APPDATA
/// CSIDL_MYPICTURES
/// CSIDL_NETHOOD
/// CSIDL_NETWORK
/// CSIDL_PERSONAL
/// CSIDL_PRINTERS
/// CSIDL_PRINTHOOD
/// CSIDL_PROFILE
/// CSIDL_PROGRAMS
/// CSIDL_PROGRAM_FILES
/// CSIDL_PROGRAM_FILESX86
/// CSIDL_PROGRAM_FILES_COMMON
/// CSIDL_PROGRAM_FILES_COMMONX86
/// CSIDL_RECENT
/// CSIDL_RESOURCES
/// CSIDL_RESOURCES_LOCALIZED
/// CSIDL_SENDTO
/// CSIDL_STARTMENU
/// CSIDL_STARTUP
/// CSIDL_SYSTEM
/// CSIDL_SYSTEMX86
/// CSIDL_TEMPLATES
/// CSIDL_WINDOWS
///
String System::getShellFolderPath(int folderCsidl, bool create)
{
Char* buf = new Char[MAX_PATH];
if (SHGetSpecialFolderPath(NULL, buf, folderCsidl, create))
return String(buf);
else
return L"";
}
ImageList System::getImageList(bool smallImage)
{
HIMAGELIST himl;
SHFILEINFO shfi;
himl = reinterpret_cast<HIMAGELIST>
(SHGetFileInfo(L"",
0, &shfi, sizeof(shfi),
SHGFI_SYSICONINDEX |
(smallImage ? SHGFI_SMALLICON:
SHGFI_LARGEICON)));
return ImageList(himl); // TODO this can't be delete!!!
}
int System::getFileImageIndex(const String& fileName, bool smallImage)
{
SHFILEINFO shfi;
SHGetFileInfo(fileName.c_str(), 0, &shfi, sizeof(shfi),
SHGFI_SYSICONINDEX |
(smallImage ? SHGFI_SMALLICON:
SHGFI_LARGEICON));
return shfi.iIcon;
}
/// Returns the screen size.
///
Size System::getScreenSize()
{
return Size(GetSystemMetrics(SM_CXFULLSCREEN),
GetSystemMetrics(SM_CYFULLSCREEN));
}
/// Returns the work-area of the screen, it is like the desktop area,
/// that is not overlapped by the task-bar.
///
/// @win32
/// It is a call to @msdn{SystemParametersInfo} using @msdn{SPI_GETWORKAREA}.
/// @endwin32
///
Rect System::getWorkAreaBounds()
{
RECT rc;
// returns the work-area rectangle
if (SystemParametersInfo(SPI_GETWORKAREA, 0, reinterpret_cast<PVOID>(&rc), 0))
return Rect(&rc);
// returns the full-screen rectangle
else
return Rect(Point(0, 0), System::getScreenSize());
}
/// Returns color from the system. It's a wrapper for the Win32's GetSysColor.
///
/// @param index
/// Can be one of the following values:
/// @li COLOR_3DDKSHADOW
/// @li COLOR_3DFACE
/// @li COLOR_3DHILIGHT
/// @li COLOR_3DHIGHLIGHT
/// @li COLOR_3DLIGHT
/// @li COLOR_BTNHILIGHT
/// @li COLOR_3DSHADOW
/// @li COLOR_ACTIVEBORDER
/// @li COLOR_ACTIVECAPTION
/// @li COLOR_APPWORKSPACE
/// @li COLOR_BACKGROUND
/// @li COLOR_DESKTOP
/// @li COLOR_BTNFACE
/// @li COLOR_BTNHIGHLIGHT
/// @li COLOR_BTNSHADOW
/// @li COLOR_BTNTEXT
/// @li COLOR_CAPTIONTEXT
/// @li COLOR_GRAYTEXT
/// @li COLOR_HIGHLIGHT
/// @li COLOR_HIGHLIGHTTEXT
/// @li COLOR_INACTIVEBORDER
/// @li COLOR_INACTIVECAPTION
/// @li COLOR_INACTIVECAPTIONTEXT
/// @li COLOR_INFOBK
/// @li COLOR_INFOTEXT
/// @li COLOR_MENU
/// @li COLOR_MENUTEXT
/// @li COLOR_SCROLLBAR
/// @li COLOR_WINDOW
/// @li COLOR_WINDOWFRAME
/// @li COLOR_WINDOWTEXT
/// @li COLOR_HOTLIGHT
/// @li COLOR_GRADIENTACTIVECAPTION
/// @li COLOR_GRADIENTINACTIVECAPTION
///
/// @todo make the index a Enum
///
Color System::getColor(int index)
{
return Color(GetSysColor(index));
}
bool System::getKeyState(Keys::Type keyCode)
{
// you can't use getKeyState for modifiers
assert((keyCode & Keys::Modifiers) == 0);
return (GetKeyState(keyCode) & 0x8000) != 0;
}
/// Returns the cursor position in the screen.
///
Point System::getCursorPos()
{
POINT pt;
GetCursorPos(&pt);
return Point(pt.x, pt.y);
}
void System::setCursorPos(const Point& pt)
{
SetCursorPos(pt.x, pt.y);
}
String System::getUserName()
{
Char buf[UNLEN+1];
// char buf[UNLEN+1];
DWORD len = UNLEN+1;
if (GetUserName(buf, &len))
return String(buf);
else
return String();
}
// Prototypes for Win2000/XP API
// typedef BOOLEAN (*GUNEProc)(EXTENDED_NAME_FORMAT NameFormat, LPTSTR lpNameBuffer, PULONG nSize);
String System::getFriendlyUserName()
{
#if 0 // TODO
#if (_WIN32_WINNT >= 0x0500)
HMODULE hSecur32 = GetModuleHandle(L"SECUR32.DLL");
if (!hSecur32)
hSecur32 = LoadLibrary(L"SECUR32.DLL");
GUNEProc pGUNE = (GUNEProc)GetProcAddress(hSecur32, "GetUserNameExW");
if (pGUNE != NULL) {
Char buf[UNLEN+1];
ULONG len = UNLEN+1;
if (pGUNE(NameDisplay, buf, &len))
return String(buf);
}
#endif
#endif
return getUserName();
}
// int System::getWheelScrollLines()
// {
// UINT pulScrollLines = 0;
// return SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, &pulScrollLines, 0);
// }
int System::getOS()
{
static Mutex mutex;
static volatile OS::Type cached = OS::Unknown;
ScopedLock hold(mutex);
if (cached != OS::Unknown)
return cached;
OSVERSIONINFOEX osvi;
BOOL bOsVersionInfoEx;
ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
if (!(bOsVersionInfoEx = GetVersionEx((OSVERSIONINFO*)&osvi))) {
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
if (!GetVersionEx((OSVERSIONINFO*)&osvi))
return OS::Unknown;
}
switch (osvi.dwPlatformId) {
case VER_PLATFORM_WIN32_NT:
if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2)
return cached = OS::WinServer2003;
else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1)
return cached = OS::WinXP;
else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0)
return cached = OS::Win2K;
else if (osvi.dwMajorVersion <= 4)
return cached = OS::WinNT;
break;
case VER_PLATFORM_WIN32_WINDOWS:
if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0) {
if (osvi.szCSDVersion[1] == 'C' || osvi.szCSDVersion[1] == 'B')
return cached = OS::Win95R2;
else
return cached = OS::Win95;
}
else if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10) {
if (osvi.szCSDVersion[1] == 'A')
return cached = OS::Win98SE;
else
return cached = OS::Win98;
}
else if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90)
return cached = OS::WinMe;
break;
case VER_PLATFORM_WIN32s:
return cached = OS::Win32s;
}
return cached = OS::Unknown;
}
bool System::isWin95_98_Me()
{
return (getOS() & (OS::Win95 | OS::Win98 | OS::WinMe)) != 0;
}
bool System::isWinNT_2K_XP()
{
return (getOS() & (OS::WinNT | OS::Win2K | OS::WinXP | OS::WinServer2003)) != 0;
}
bool System::isWin2K_XP()
{
return (getOS() & (OS::Win2K | OS::WinXP | OS::WinServer2003)) != 0;
}
bool System::isWinXP()
{
return (getOS() & OS::WinXP) != 0;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: StorageNativeOutputStream.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: vg $ $Date: 2005-03-23 09:41:52 $
*
* 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): Ocke Janssen
*
*
************************************************************************/
#if HAVE_CONFIG_H
#include <config.h>
#endif
#include "StorageNativeOutputStream.h"
#include "uno/mapping.hxx"
#include "uno/environment.hxx"
#include "cppuhelper/bootstrap.hxx"
#include "cppuhelper/compbase1.hxx"
#include "cppuhelper/component_context.hxx"
#ifndef _COM_SUN_STAR_EMBED_XTRANSACTEDOBJECT_HPP_
#include <com/sun/star/embed/XTransactedObject.hpp>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _COM_SUN_STAR_IO_XSTREAM_HPP_
#include <com/sun/star/io/XStream.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XDOCUMENTSUBSTORAGESUPPLIER_HPP_
#include <com/sun/star/document/XDocumentSubStorageSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_XSTORAGE_HPP_
#include <com/sun/star/embed/XStorage.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_ELEMENTMODES_HPP_
#include <com/sun/star/embed/ElementModes.hpp>
#endif
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#include "hsqldb/HStorageAccess.h"
#include "hsqldb/HStorageMap.hxx"
#include "jvmaccess/virtualmachine.hxx"
#include "com/sun/star/lang/XSingleComponentFactory.hpp"
#include <rtl/logfile.hxx>
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::document;
using namespace ::com::sun::star::embed;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::lang;
using namespace ::connectivity::hsqldb;
#define OUSTR(x) ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(x) )
/*****************************************************************************/
/* exception macros */
#define ThrowException(env, type, msg) { \
env->ThrowNew(env->FindClass(type), msg); }
// -----------------------------------------------------------------------------
/*
* Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream
* Method: openStream
* Signature: (Ljava/lang/String;Ljava/lang/String;I)V
*/
JNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream_openStream
(JNIEnv * env, jobject obj_this, jstring name, jstring key, jint mode)
{
#if OSL_DEBUG_LEVEL > 1
{
::rtl::OUString sOrgName = StorageContainer::jstring2ustring(env,name);
sOrgName += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(".output"));
::rtl::OString sName = ::rtl::OUStringToOString(sOrgName,RTL_TEXTENCODING_ASCII_US);
getStreams()[sOrgName] = fopen( sName.getStr(), "a+" );
}
#endif
StorageContainer::registerStream(env,name,key,mode);
}
/*
* Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream
* Method: write
* Signature: (Ljava/lang/String;Ljava/lang/String;[BII)V
*/
JNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream_write__Ljava_lang_String_2Ljava_lang_String_2_3BII
(JNIEnv * env, jobject obj_this, jstring key, jstring name, jbyteArray buffer, jint off, jint len)
{
Java_com_sun_star_sdbcx_comp_hsqldb_NativeStorageAccess_write(env,obj_this,name,key,buffer,off,len);
}
// -----------------------------------------------------------------------------
/*
* Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream
* Method: write
* Signature: (Ljava/lang/String;Ljava/lang/String;[B)V
*/
JNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream_write__Ljava_lang_String_2Ljava_lang_String_2_3B
(JNIEnv * env, jobject obj_this, jstring key, jstring name, jbyteArray buffer)
{
Java_com_sun_star_sdbcx_comp_hsqldb_NativeStorageAccess_write(env,obj_this,name,key,buffer,0,env->GetArrayLength(buffer));
}
// -----------------------------------------------------------------------------
/*
* Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream
* Method: close
* Signature: (Ljava/lang/String;Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream_close
(JNIEnv * env, jobject obj_this, jstring key, jstring name)
{
::boost::shared_ptr<StreamHelper> pHelper = StorageContainer::getRegisteredStream(env,name,key);
Reference< XOutputStream> xFlush = pHelper.get() ? pHelper->getOutputStream() : Reference< XOutputStream>();
if ( xFlush.is() )
try
{
xFlush->flush();
}
catch(Exception&)
{}
#if OSL_DEBUG_LEVEL > 1
{
::rtl::OUString sOrgName = StorageContainer::jstring2ustring(env,name);
sOrgName += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(".output"));
fclose( getStreams()[sOrgName] );
getStreams().erase(sOrgName);
}
#endif
StorageContainer::revokeStream(env,name,key);
}
// -----------------------------------------------------------------------------
/*
* Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream
* Method: write
* Signature: (Ljava/lang/String;Ljava/lang/String;I)V
*/
JNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream_write__Ljava_lang_String_2Ljava_lang_String_2I
(JNIEnv * env, jobject obj_this, jstring key, jstring name,jint b)
{
Java_com_sun_star_sdbcx_comp_hsqldb_NativeStorageAccess_writeInt(env,obj_this,name,key,b);
}
// -----------------------------------------------------------------------------
/*
* Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream
* Method: flush
* Signature: (Ljava/lang/String;Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream_flush
(JNIEnv * env, jobject obj_this, jstring key, jstring name)
{
}
// -----------------------------------------------------------------------------
/*
* Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream
* Method: sync
* Signature: (Ljava/lang/String;Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream_sync
(JNIEnv * env, jobject obj_this, jstring key, jstring name)
{
TStorages::mapped_type aStoragePair = StorageContainer::getRegisteredStorage(StorageContainer::jstring2ustring(env,key));
Reference<XTransactedObject> xTrans(aStoragePair.first.first,UNO_QUERY);
if ( xTrans.is() )
{
try
{
TStreamMap::iterator aIter = aStoragePair.second.begin();
TStreamMap::iterator aEnd = aStoragePair.second.end();
for (;aIter != aEnd ; ++aIter)
{
::boost::shared_ptr<StreamHelper> pHelper = aIter->second;
Reference< XOutputStream> xFlush = pHelper.get() ? pHelper->getOutputStream() : Reference< XOutputStream>();
if ( xFlush.is() )
try
{
xFlush->flush();
}
catch(Exception&)
{}
}
xTrans->commit();
}
catch(Exception& e)
{
OSL_ENSURE(0,"Exception catched! : sync();");
StorageContainer::throwJavaException(e,env);
}
}
}
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS dba28 (1.3.22); FILE MERGED 2005/03/23 14:58:43 fs 1.3.22.2: #i45314# implement sync as flush, but *without* commit 2005/03/21 12:53:34 fs 1.3.22.1: copying the changes from CWS dba26 herein, since they're needed to fix i45314<commit_after>/*************************************************************************
*
* $RCSfile: StorageNativeOutputStream.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-03-30 11:52:17 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): Ocke Janssen
*
*
************************************************************************/
#if HAVE_CONFIG_H
#include <config.h>
#endif
#include "StorageNativeOutputStream.h"
#include "uno/mapping.hxx"
#include "uno/environment.hxx"
#include "cppuhelper/bootstrap.hxx"
#include "cppuhelper/compbase1.hxx"
#include "cppuhelper/component_context.hxx"
#ifndef CONNECTIVITY_HSQLDB_ACCESSLOG_HXX
#include "accesslog.hxx"
#endif
#ifndef _COM_SUN_STAR_EMBED_XTRANSACTEDOBJECT_HPP_
#include <com/sun/star/embed/XTransactedObject.hpp>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _COM_SUN_STAR_IO_XSTREAM_HPP_
#include <com/sun/star/io/XStream.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XDOCUMENTSUBSTORAGESUPPLIER_HPP_
#include <com/sun/star/document/XDocumentSubStorageSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_XSTORAGE_HPP_
#include <com/sun/star/embed/XStorage.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_ELEMENTMODES_HPP_
#include <com/sun/star/embed/ElementModes.hpp>
#endif
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#include "hsqldb/HStorageAccess.hxx"
#include "hsqldb/HStorageMap.hxx"
#include "jvmaccess/virtualmachine.hxx"
#include "com/sun/star/lang/XSingleComponentFactory.hpp"
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::document;
using namespace ::com::sun::star::embed;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::lang;
using namespace ::connectivity::hsqldb;
#define OUSTR(x) ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(x) )
/*****************************************************************************/
/* exception macros */
#define ThrowException(env, type, msg) { \
env->ThrowNew(env->FindClass(type), msg); }
// -----------------------------------------------------------------------------
/*
* Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream
* Method: openStream
* Signature: (Ljava/lang/String;Ljava/lang/String;I)V
*/
JNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream_openStream
(JNIEnv * env, jobject obj_this, jstring name, jstring key, jint mode)
{
#if OSL_DEBUG_LEVEL > 1
{
OperationLogFile( env, name, "output" ).logOperation( "openStream" );
LogFile( env, name, "output" ).create();
}
#endif
StorageContainer::registerStream(env,name,key,mode);
}
/*
* Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream
* Method: write
* Signature: (Ljava/lang/String;Ljava/lang/String;[BII)V
*/
JNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream_write__Ljava_lang_String_2Ljava_lang_String_2_3BII
(JNIEnv * env, jobject obj_this, jstring key, jstring name, jbyteArray buffer, jint off, jint len)
{
#if OSL_DEBUG_LEVEL > 1
OperationLogFile( env, name, "output" ).logOperation( "write( byte[], int, int )" );
DataLogFile aDataLog( env, name, "output" );
write_to_storage_stream_from_buffer( env, obj_this, name, key, buffer, off, len, &aDataLog );
#else
write_to_storage_stream_from_buffer( env, obj_this, name, key, buffer, off, len );
#endif
}
// -----------------------------------------------------------------------------
/*
* Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream
* Method: write
* Signature: (Ljava/lang/String;Ljava/lang/String;[B)V
*/
JNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream_write__Ljava_lang_String_2Ljava_lang_String_2_3B
(JNIEnv * env, jobject obj_this, jstring key, jstring name, jbyteArray buffer)
{
#if OSL_DEBUG_LEVEL > 1
OperationLogFile( env, name, "output" ).logOperation( "write( byte[] )" );
DataLogFile aDataLog( env, name, "output" );
write_to_storage_stream_from_buffer( env, obj_this, name, key, buffer, 0, env->GetArrayLength( buffer ), &aDataLog );
#else
write_to_storage_stream_from_buffer( env, obj_this, name, key, buffer, 0, env->GetArrayLength( buffer ) );
#endif
}
// -----------------------------------------------------------------------------
/*
* Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream
* Method: close
* Signature: (Ljava/lang/String;Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream_close
(JNIEnv * env, jobject obj_this, jstring key, jstring name)
{
#if OSL_DEBUG_LEVEL > 1
OperationLogFile aOpLog( env, name, "output" );
aOpLog.logOperation( "close" );
LogFile aDataLog( env, name, "output" );
#endif
::boost::shared_ptr<StreamHelper> pHelper = StorageContainer::getRegisteredStream(env,name,key);
Reference< XOutputStream> xFlush = pHelper.get() ? pHelper->getOutputStream() : Reference< XOutputStream>();
if ( xFlush.is() )
try
{
xFlush->flush();
}
catch(Exception&)
{}
#if OSL_DEBUG_LEVEL > 1
aDataLog.close();
aOpLog.close();
#endif
StorageContainer::revokeStream(env,name,key);
}
// -----------------------------------------------------------------------------
/*
* Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream
* Method: write
* Signature: (Ljava/lang/String;Ljava/lang/String;I)V
*/
JNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream_write__Ljava_lang_String_2Ljava_lang_String_2I
(JNIEnv * env, jobject obj_this, jstring key, jstring name,jint b)
{
#if OSL_DEBUG_LEVEL > 1
OperationLogFile( env, name, "output" ).logOperation( "write( int )" );
DataLogFile aDataLog( env, name, "output" );
write_to_storage_stream( env, obj_this, name, key, b, &aDataLog );
#else
write_to_storage_stream( env, obj_this, name, key, b );
#endif
}
// -----------------------------------------------------------------------------
/*
* Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream
* Method: flush
* Signature: (Ljava/lang/String;Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream_flush
(JNIEnv * env, jobject obj_this, jstring key, jstring name)
{
#if OSL_DEBUG_LEVEL > 1
OperationLogFile( env, name, "output" ).logOperation( "flush" );
#endif
}
// -----------------------------------------------------------------------------
/*
* Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream
* Method: sync
* Signature: (Ljava/lang/String;Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeOutputStream_sync
(JNIEnv * env, jobject obj_this, jstring key, jstring name)
{
#if OSL_DEBUG_LEVEL > 1
OperationLogFile( env, name, "output" ).logOperation( "sync" );
#endif
::boost::shared_ptr< StreamHelper > pStream = StorageContainer::getRegisteredStream( env, name, key );
Reference< XOutputStream > xFlush = pStream.get() ? pStream->getOutputStream() : Reference< XOutputStream>();
OSL_ENSURE( xFlush.is(), "StorageNativeOutputStream::sync: could not retrieve an output stream!" );
if ( xFlush.is() )
{
try
{
xFlush->flush();
}
catch(Exception&)
{
OSL_ENSURE( false, "StorageNativeOutputStream::sync: could not flush output stream!" );
}
}
}
// -----------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2008-2009
*
* School of Computing, University of Utah,
* Salt Lake City, UT 84112, USA
*
* and the Gauss Group
* http://www.cs.utah.edu/formal_verification
*
* See LICENSE for licensing information
*/
/*
* ISP: MPI Dynamic Verification Tool
*
* File: Transition.hpp
* Description: Implements handling of a single transition in an interleaving
* Contact: isp-dev@cs.utah.edu
*/
#ifndef _CB_HPP
#define _CB_HPP
/*
#include "Envelope.hpp"
#include <vector>
#include <cassert>
*/
/*
* This implements a single transition
*/
class CB {
public:
int _pid;
int _index;
CB () { }
CB (int i, int ind) : _pid(i), _index(ind) {
}
CB(const CB& c) : _pid(c._pid), _index(c._index){}
bool operator== (const CB &c) {
return _pid == c._pid && _index == c._index;
}
bool operator!= (const CB &c) {
return !(*this == c);
}
friend bool operator< (const CB &a, const CB &b) {
return a._pid < b._pid || (a._pid == b._pid && a._index < b._index);
}
/*
CB& operator= (const CB &c) {
this->_pid = c._pid;
this->_index = c._index;
return *this;
}*/
std::unique_ptr<CB> Copy() {
std::unique_ptr<CB> ptr(new CB(*this));
return std::move(ptr);
}
};
#endif
<commit_msg>Changed method names to be more consistent.<commit_after>/*
* Copyright (c) 2008-2009
*
* School of Computing, University of Utah,
* Salt Lake City, UT 84112, USA
*
* and the Gauss Group
* http://www.cs.utah.edu/formal_verification
*
* See LICENSE for licensing information
*/
/*
* ISP: MPI Dynamic Verification Tool
*
* File: Transition.hpp
* Description: Implements handling of a single transition in an interleaving
* Contact: isp-dev@cs.utah.edu
*/
#ifndef _CB_HPP
#define _CB_HPP
/*
#include "Envelope.hpp"
#include <vector>
#include <cassert>
*/
/*
* This implements a single transition
*/
class CB {
public:
int _pid;
int _index;
CB () { }
CB (int i, int ind) : _pid(i), _index(ind) {
}
CB(const CB& c) : _pid(c._pid), _index(c._index){}
bool operator== (const CB &c) {
return _pid == c._pid && _index == c._index;
}
bool operator!= (const CB &c) {
return !(*this == c);
}
friend bool operator< (const CB &a, const CB &b) {
return a._pid < b._pid || (a._pid == b._pid && a._index < b._index);
}
/*
CB& operator= (const CB &c) {
this->_pid = c._pid;
this->_index = c._index;
return *this;
}*/
std::unique_ptr<CB> copy() {
std::unique_ptr<CB> ptr(new CB(*this));
return std::move(ptr);
}
};
#endif
<|endoftext|>
|
<commit_before>#include "UnrealCVPrivate.h"
#include "ViewMode.h"
#include "BufferVisualizationData.h"
/**
FViewMode is a helper class to tweak render options. Important options are
Tonemapper
EyeAdaptation
TemporalAA
MotionBlur
Lighting
Bloom
ColorGrading
GammaCorrection
DepthOfField
LensFlare
Vignette
*/
void BasicSetting(FEngineShowFlags& ShowFlags)
{
ShowFlags = FEngineShowFlags(EShowFlagInitMode::ESFIM_All0);
ShowFlags.SetRendering(true);
ShowFlags.SetStaticMeshes(true);
ShowFlags.SetLandscape(true);
ShowFlags.SetInstancedFoliage(true);
ShowFlags.SetInstancedGrass(true);
ShowFlags.SetInstancedStaticMeshes(true);
ShowFlags.SetSkeletalMeshes(true);
}
void FViewMode::Lit(FEngineShowFlags& ShowFlags)
{
BasicSetting(ShowFlags);
ShowFlags = FEngineShowFlags(EShowFlagInitMode::ESFIM_Game);
ApplyViewMode(VMI_Lit, true, ShowFlags);
ShowFlags.SetMaterials(true);
ShowFlags.SetLighting(true);
ShowFlags.SetPostProcessing(true);
// ToneMapper needs to be enabled, otherwise the screen will be very dark
ShowFlags.SetTonemapper(true);
// TemporalAA needs to be disabled, otherwise the previous frame might contaminate current frame.
// Check: https://answers.unrealengine.com/questions/436060/low-quality-screenshot-after-setting-the-actor-pos.html for detail
// ShowFlags.SetTemporalAA(true);
ShowFlags.SetTemporalAA(false);
ShowFlags.SetAntiAliasing(true);
ShowFlags.SetEyeAdaptation(false); // Eye adaption is a slow temporal procedure, not useful for image capture
}
void FViewMode::BufferVisualization(FEngineShowFlags& ShowFlags)
{
ApplyViewMode(EViewModeIndex::VMI_VisualizeBuffer, true, ShowFlags); // This did more than just SetVisualizeBuffer(true);
// EngineShowFlagOverride()
// From ShowFlags.cpp
ShowFlags.SetPostProcessing(true);
ShowFlags.SetMaterials(true);
ShowFlags.SetVisualizeBuffer(true);
// ToneMapper needs to be disabled
ShowFlags.SetTonemapper(false);
// TemporalAA needs to be disabled, or it will contaminate the following frame
ShowFlags.SetTemporalAA(false);
}
/** ViewMode showing post process */
void FViewMode::PostProcess(FEngineShowFlags& ShowFlags)
{
BasicSetting(ShowFlags);
// These are minimal setting
ShowFlags.SetPostProcessing(true);
ShowFlags.SetPostProcessMaterial(true);
// ShowFlags.SetVertexColors(true); // This option will change object material to vertex color material, which don't produce surface normal
GVertexColorViewMode = EVertexColorViewMode::Color;
}
void FViewMode::Wireframe(FEngineShowFlags& ShowFlags)
{
// ApplyViewMode(VMI_Wireframe, true, ShowFlags);
ShowFlags.SetPostProcessing(true);
ShowFlags.SetWireframe(true);
}
void FViewMode::VertexColor(FEngineShowFlags& ShowFlags)
{
ApplyViewMode(VMI_Lit, true, ShowFlags);
// From MeshPaintEdMode.cpp:2942
ShowFlags.SetMaterials(false);
ShowFlags.SetLighting(false);
ShowFlags.SetBSPTriangles(true);
ShowFlags.SetVertexColors(true);
ShowFlags.SetPostProcessing(false);
ShowFlags.SetHMDDistortion(false);
ShowFlags.SetTonemapper(false); // This won't take effect here
GVertexColorViewMode = EVertexColorViewMode::Color;
}
void FViewMode::Unlit(FEngineShowFlags& ShowFlags)
{
ApplyViewMode(VMI_Unlit, true, ShowFlags);
ShowFlags.SetMaterials(false);
ShowFlags.SetVertexColors(false);
ShowFlags.SetLightFunctions(false);
ShowFlags.SetLighting(false);
ShowFlags.SetAtmosphericFog(false);
}
<commit_msg>Enable materials flag in the ShowFlags, so that the leaves will be accurately displayed in the depth and normal ground truth.<commit_after>#include "UnrealCVPrivate.h"
#include "ViewMode.h"
#include "BufferVisualizationData.h"
/**
FViewMode is a helper class to tweak render options. Important options are
Tonemapper
EyeAdaptation
TemporalAA
MotionBlur
Lighting
Bloom
ColorGrading
GammaCorrection
DepthOfField
LensFlare
Vignette
*/
void BasicSetting(FEngineShowFlags& ShowFlags)
{
ShowFlags = FEngineShowFlags(EShowFlagInitMode::ESFIM_All0);
ShowFlags.SetRendering(true);
ShowFlags.SetStaticMeshes(true);
ShowFlags.SetLandscape(true);
ShowFlags.SetMaterials(true); // Important for the correctness of tree leaves.
ShowFlags.SetInstancedFoliage(true);
ShowFlags.SetInstancedGrass(true);
ShowFlags.SetInstancedStaticMeshes(true);
ShowFlags.SetSkeletalMeshes(true);
// ShowFlags = FEngineShowFlags(EShowFlagInitMode::ESFIM_Game);
// ApplyViewMode(EViewModeIndex::VMI_VisualizeBuffer, true, ShowFlags); // This did more than just SetVisualizeBuffer(true);
}
void FViewMode::Lit(FEngineShowFlags& ShowFlags)
{
BasicSetting(ShowFlags);
ShowFlags = FEngineShowFlags(EShowFlagInitMode::ESFIM_Game);
ApplyViewMode(VMI_Lit, true, ShowFlags);
ShowFlags.SetMaterials(true);
ShowFlags.SetLighting(true);
ShowFlags.SetPostProcessing(true);
// ToneMapper needs to be enabled, otherwise the screen will be very dark
ShowFlags.SetTonemapper(true);
// TemporalAA needs to be disabled, otherwise the previous frame might contaminate current frame.
// Check: https://answers.unrealengine.com/questions/436060/low-quality-screenshot-after-setting-the-actor-pos.html for detail
// ShowFlags.SetTemporalAA(true);
ShowFlags.SetTemporalAA(false);
ShowFlags.SetAntiAliasing(true);
ShowFlags.SetEyeAdaptation(false); // Eye adaption is a slow temporal procedure, not useful for image capture
}
void FViewMode::BufferVisualization(FEngineShowFlags& ShowFlags)
{
ApplyViewMode(EViewModeIndex::VMI_VisualizeBuffer, true, ShowFlags); // This did more than just SetVisualizeBuffer(true);
// EngineShowFlagOverride()
// From ShowFlags.cpp
ShowFlags.SetPostProcessing(true);
ShowFlags.SetMaterials(true);
ShowFlags.SetVisualizeBuffer(true);
// ToneMapper needs to be disabled
ShowFlags.SetTonemapper(false);
// TemporalAA needs to be disabled, or it will contaminate the following frame
ShowFlags.SetTemporalAA(false);
}
/** ViewMode showing post process */
void FViewMode::PostProcess(FEngineShowFlags& ShowFlags)
{
BasicSetting(ShowFlags);
// These are minimal setting
ShowFlags.SetPostProcessing(true);
ShowFlags.SetPostProcessMaterial(true);
// ShowFlags.SetVertexColors(true); // This option will change object material to vertex color material, which don't produce surface normal
GVertexColorViewMode = EVertexColorViewMode::Color;
}
void FViewMode::Wireframe(FEngineShowFlags& ShowFlags)
{
// ApplyViewMode(VMI_Wireframe, true, ShowFlags);
ShowFlags.SetPostProcessing(true);
ShowFlags.SetWireframe(true);
}
void FViewMode::VertexColor(FEngineShowFlags& ShowFlags)
{
ApplyViewMode(VMI_Lit, true, ShowFlags);
// From MeshPaintEdMode.cpp:2942
ShowFlags.SetMaterials(false);
ShowFlags.SetLighting(false);
ShowFlags.SetBSPTriangles(true);
ShowFlags.SetVertexColors(true);
ShowFlags.SetPostProcessing(false);
ShowFlags.SetHMDDistortion(false);
ShowFlags.SetTonemapper(false); // This won't take effect here
GVertexColorViewMode = EVertexColorViewMode::Color;
}
void FViewMode::Unlit(FEngineShowFlags& ShowFlags)
{
ApplyViewMode(VMI_Unlit, true, ShowFlags);
ShowFlags.SetMaterials(false);
ShowFlags.SetVertexColors(false);
ShowFlags.SetLightFunctions(false);
ShowFlags.SetLighting(false);
ShowFlags.SetAtmosphericFog(false);
}
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright (c) 2015-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cstdio>
#include <string>
#include <cstring>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <signal.h>
namespace asgard {
const std::size_t UNIX_PATH_MAX = 108;
const std::size_t buffer_size = 4096;
struct driver_connector {
//Buffer
char write_buffer[buffer_size];
char receive_buffer[buffer_size];
// The socket file descriptor
int socket_fd;
// The socket addresses
struct sockaddr_un client_address;
struct sockaddr_un server_address;
};
bool open_driver_connection(driver_connector& driver, const char* client_socket_path, const char* server_socket_path){
// Open the socket
driver.socket_fd = socket(AF_UNIX, SOCK_DGRAM, 0);
if(driver.socket_fd < 0){
std::cerr << "asgard:driversystem: socket() failed" << std::endl;
return false;
}
// Init the client address
memset(&driver.client_address, 0, sizeof(struct sockaddr_un));
driver.client_address.sun_family = AF_UNIX;
snprintf(driver.client_address.sun_path, UNIX_PATH_MAX, client_socket_path);
// Unlink the client socket
unlink(client_socket_path);
// Bind to client socket
if(bind(driver.socket_fd, (const struct sockaddr *) &driver.client_address, sizeof(struct sockaddr_un)) < 0){
std::cerr << "asgard:driver: bind() failed" << std::endl;
return false;
}
// Init the server address
memset(&driver.server_address, 0, sizeof(struct sockaddr_un));
driver.server_address.sun_family = AF_UNIX;
snprintf(driver.server_address.sun_path, UNIX_PATH_MAX, server_socket_path);
return true;
}
int register_source(driver_connector& driver, const std::string& source_name){
socklen_t address_length = sizeof(struct sockaddr_un);
// Register the source
auto nbytes = snprintf(driver.write_buffer, buffer_size, "REG_SOURCE %s", source_name.c_str());
sendto(driver.socket_fd, driver.write_buffer, nbytes, 0, (struct sockaddr *) &driver.server_address, sizeof(struct sockaddr_un));
auto bytes_received = recvfrom(driver.socket_fd, driver.receive_buffer, buffer_size, 0, (struct sockaddr *) &(driver.server_address), &address_length);
driver.receive_buffer[bytes_received] = '\0';
auto source_id = atoi(driver.receive_buffer);
std::cout << "asgard:driver: remote source: " << source_id << std::endl;
return source_id;
}
int register_sensor(driver_connector& driver, int source_id, const std::string& type, const std::string& name){
socklen_t address_length = sizeof(struct sockaddr_un);
// Register the sensor
auto nbytes = snprintf(driver.write_buffer, buffer_size, "REG_SENSOR %d %s %s", source_id, type.c_str(), name.c_str());
sendto(driver.socket_fd, driver.write_buffer, nbytes, 0, (struct sockaddr *) &driver.server_address, sizeof(struct sockaddr_un));
auto bytes_received = recvfrom(driver.socket_fd, driver.receive_buffer, buffer_size, 0, (struct sockaddr *) &(driver.server_address), &address_length);
driver.receive_buffer[bytes_received] = '\0';
auto sensor_id = atoi(driver.receive_buffer);
std::cout << "asgard:driver: remote sensor(" << name << "):" << sensor_id << std::endl;
return sensor_id;
}
void send_data(driver_connector& driver, int source_id, int sensor_id, double value){
// Send the data
auto nbytes = snprintf(driver.write_buffer, buffer_size, "DATA %d %d %.2f", source_id, sensor_id, value);
sendto(driver.socket_fd, driver.write_buffer, nbytes, 0, (struct sockaddr *) &driver.server_address, sizeof(struct sockaddr_un));
}
void unregister_sensor(driver_connector& driver, int source_id, int sensor_id){
// Unregister the sensor, if necessary
if(sensor_id >= 0){
auto nbytes = snprintf(driver.write_buffer, buffer_size, "UNREG_SENSOR %d %d", source_id, sensor_id);
sendto(driver.socket_fd, driver.write_buffer, nbytes, 0, (struct sockaddr *) &driver.server_address, sizeof(struct sockaddr_un));
}
}
void unregister_source(driver_connector& driver, int source_id){
// Unregister the source, if necessary
if(source_id >= 0){
auto nbytes = snprintf(driver.write_buffer, buffer_size, "UNREG_SOURCE %d", source_id);
sendto(driver.socket_fd, driver.write_buffer, nbytes, 0, (struct sockaddr *) &driver.server_address, sizeof(struct sockaddr_un));
}
}
} //end of namespace asgard
<commit_msg>Add revoke_root utility<commit_after>//=======================================================================
// Copyright (c) 2015-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cstdio>
#include <string> #include <cstring>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <signal.h>
namespace asgard {
const std::size_t UNIX_PATH_MAX = 108;
const std::size_t buffer_size = 4096;
struct driver_connector {
//Buffer
char write_buffer[buffer_size];
char receive_buffer[buffer_size];
// The socket file descriptor
int socket_fd;
// The socket addresses
struct sockaddr_un client_address;
struct sockaddr_un server_address;
};
bool open_driver_connection(driver_connector& driver, const char* client_socket_path, const char* server_socket_path){
// Open the socket
driver.socket_fd = socket(AF_UNIX, SOCK_DGRAM, 0);
if(driver.socket_fd < 0){
std::cerr << "asgard:driversystem: socket() failed" << std::endl;
return false;
}
// Init the client address
memset(&driver.client_address, 0, sizeof(struct sockaddr_un));
driver.client_address.sun_family = AF_UNIX;
snprintf(driver.client_address.sun_path, UNIX_PATH_MAX, client_socket_path);
// Unlink the client socket
unlink(client_socket_path);
// Bind to client socket
if(bind(driver.socket_fd, (const struct sockaddr *) &driver.client_address, sizeof(struct sockaddr_un)) < 0){
std::cerr << "asgard:driver: bind() failed" << std::endl;
return false;
}
// Init the server address
memset(&driver.server_address, 0, sizeof(struct sockaddr_un));
driver.server_address.sun_family = AF_UNIX;
snprintf(driver.server_address.sun_path, UNIX_PATH_MAX, server_socket_path);
return true;
}
int register_source(driver_connector& driver, const std::string& source_name){
socklen_t address_length = sizeof(struct sockaddr_un);
// Register the source
auto nbytes = snprintf(driver.write_buffer, buffer_size, "REG_SOURCE %s", source_name.c_str());
sendto(driver.socket_fd, driver.write_buffer, nbytes, 0, (struct sockaddr *) &driver.server_address, sizeof(struct sockaddr_un));
auto bytes_received = recvfrom(driver.socket_fd, driver.receive_buffer, buffer_size, 0, (struct sockaddr *) &(driver.server_address), &address_length);
driver.receive_buffer[bytes_received] = '\0';
auto source_id = atoi(driver.receive_buffer);
std::cout << "asgard:driver: remote source: " << source_id << std::endl;
return source_id;
}
int register_sensor(driver_connector& driver, int source_id, const std::string& type, const std::string& name){
socklen_t address_length = sizeof(struct sockaddr_un);
// Register the sensor
auto nbytes = snprintf(driver.write_buffer, buffer_size, "REG_SENSOR %d %s %s", source_id, type.c_str(), name.c_str());
sendto(driver.socket_fd, driver.write_buffer, nbytes, 0, (struct sockaddr *) &driver.server_address, sizeof(struct sockaddr_un));
auto bytes_received = recvfrom(driver.socket_fd, driver.receive_buffer, buffer_size, 0, (struct sockaddr *) &(driver.server_address), &address_length);
driver.receive_buffer[bytes_received] = '\0';
auto sensor_id = atoi(driver.receive_buffer);
std::cout << "asgard:driver: remote sensor(" << name << "):" << sensor_id << std::endl;
return sensor_id;
}
void send_data(driver_connector& driver, int source_id, int sensor_id, double value){
// Send the data
auto nbytes = snprintf(driver.write_buffer, buffer_size, "DATA %d %d %.2f", source_id, sensor_id, value);
sendto(driver.socket_fd, driver.write_buffer, nbytes, 0, (struct sockaddr *) &driver.server_address, sizeof(struct sockaddr_un));
}
void unregister_sensor(driver_connector& driver, int source_id, int sensor_id){
// Unregister the sensor, if necessary
if(sensor_id >= 0){
auto nbytes = snprintf(driver.write_buffer, buffer_size, "UNREG_SENSOR %d %d", source_id, sensor_id);
sendto(driver.socket_fd, driver.write_buffer, nbytes, 0, (struct sockaddr *) &driver.server_address, sizeof(struct sockaddr_un));
}
}
void unregister_source(driver_connector& driver, int source_id){
// Unregister the source, if necessary
if(source_id >= 0){
auto nbytes = snprintf(driver.write_buffer, buffer_size, "UNREG_SOURCE %d", source_id);
sendto(driver.socket_fd, driver.write_buffer, nbytes, 0, (struct sockaddr *) &driver.server_address, sizeof(struct sockaddr_un));
}
}
bool revoke_root(){
if (getuid() == 0) {
if (setgid(1000) != 0){
std::cout << "asgard:dht11: setgid: Unable to drop group privileges: " << strerror(errno) << std::endl;
return false;
}
if (setuid(1000) != 0){
std::cout << "asgard:dht11: setgid: Unable to drop user privileges: " << strerror(errno) << std::endl;
return false;
}
}
if (setuid(0) != -1){
std::cout << "asgard:dht11: managed to regain root privileges, exiting..." << std::endl;
return false;
}
return true;
}
} //end of namespace asgard
<|endoftext|>
|
<commit_before>/*
* Adplug - Replayer for many OPL2/OPL3 audio file formats.
* Copyright (C) 1999 - 2002 Simon Peter <dn.tlp@gmx.net>, et al.
*
* 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
*
* adplug.cpp - CAdPlug helper class implementation, by Simon Peter <dn.tlp@gmx.net>
*/
/***** Includes *****/
#include <fstream.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <string>
#include "adplug.h"
#include "debug.h"
/***** Replayer includes *****/
#include "hsc.h"
#include "mtk.h"
#include "hsp.h"
#include "s3m.h"
#include "raw.h"
#include "d00.h"
#include "sa2.h"
#include "amd.h"
#include "rad.h"
#include "a2m.h"
#include "mid.h"
#include "imf.h"
#include "sng.h"
#include "ksm.h"
#include "mkj.h"
#include "dfm.h"
#include "lds.h"
#include "bam.h"
#include "fmc.h"
#include "bmf.h"
#include "flash.h"
#include "hyp.h"
#include "psi.h"
#include "rat.h"
#include "hybrid.h"
#include "mad.h"
#include "adtrack.h"
// These players use C++ templates, which aren't supported by WATCOM C++
#ifndef __WATCOMC__
#include "u6m.h"
#include "rol.h"
#endif
/***** Defines *****/
#define VERSION "1.3" // AdPlug library version string
/***** Static variables initializers *****/
const unsigned short CPlayer::note_table[12] = {363,385,408,432,458,485,514,544,577,611,647,686};
const unsigned char CPlayer::op_table[9] = {0x00, 0x01, 0x02, 0x08, 0x09, 0x0a, 0x10, 0x11, 0x12};
/***** List of all players that come in the standard AdPlug distribution *****/
// WARNING: The order of this list is on purpose! AdPlug tries the players in
// this order, which is to be preserved, because some players take precedence
// above other players.
// The list is terminated with an all-NULL element.
static const struct Players {
CPlayer *(*factory) (Copl *newopl);
} allplayers[] = {
{CmidPlayer::factory}, {CksmPlayer::factory},
#ifndef __WATCOMC__
{CrolPlayer::factory},
#endif
{CsngPlayer::factory}, {Ca2mLoader::factory}, {CradLoader::factory},
{CamdLoader::factory}, {Csa2Loader::factory}, {CrawPlayer::factory},
{Cs3mPlayer::factory}, {CmtkLoader::factory}, {CmkjPlayer::factory},
{CdfmLoader::factory}, {CbamPlayer::factory}, {CxadbmfPlayer::factory},
{CxadflashPlayer::factory}, {CxadhypPlayer::factory}, {CxadpsiPlayer::factory},
{CxadratPlayer::factory}, {CxadhybridPlayer::factory}, {CfmcLoader::factory},
{CmadLoader::factory},
#ifndef __WATCOMC__
{Cu6mPlayer::factory},
#endif
{Cd00Player::factory}, {ChspLoader::factory}, {ChscPlayer::factory},
{CimfPlayer::factory}, {CldsLoader::factory}, {CadtrackLoader::factory},
{0}
};
/***** Public methods *****/
CPlayer *CAdPlug::factory(const char *fn, Copl *opl)
{
ifstream f(fn, ios::in | ios::binary);
if(!f.is_open()) return 0;
return factory(f,opl,fn);
}
CPlayer *CAdPlug::factory(istream &f, Copl *opl, const char *fn)
{
CPlayer *p;
unsigned int i;
LogWrite("*** CAdPlug::factory(f,opl,\"%s\") ***\n",fn);
for(i=0;allplayers[i].factory;i++) {
LogWrite("Trying: %d\n",i);
if((p = allplayers[i].factory(opl)))
if(p->load(f,fn)) {
LogWrite("got it!\n");
LogWrite("--- CAdPlug::factory ---\n");
return p;
} else {
delete p;
f.seekg(0);
}
}
LogWrite("End of list!\n");
LogWrite("--- CAdPlug::factory ---\n");
return 0;
}
unsigned long CAdPlug::songlength(CPlayer *p, unsigned int subsong)
{
float slength = 0.0f;
// get song length
p->rewind(subsong);
while(p->update() && slength < 600000) // song length limit: 10 minutes
slength += 1000/p->getrefresh();
p->rewind(subsong);
return (unsigned long)slength;
}
void CAdPlug::seek(CPlayer *p, unsigned long ms)
{
float pos = 0.0f;
p->rewind();
while(pos < ms && p->update()) // seek to new position
pos += 1000/p->getrefresh();
}
std::string CAdPlug::get_version()
{
return std::string(VERSION);
}
void CAdPlug::debug_output(std::string filename)
{
LogFile(filename.c_str());
LogWrite("CAdPlug::debug_output(\"%s\"): Redirected.\n",filename.c_str());
}
<commit_msg>CFF loader support<commit_after>/*
* Adplug - Replayer for many OPL2/OPL3 audio file formats.
* Copyright (C) 1999 - 2002 Simon Peter <dn.tlp@gmx.net>, et al.
*
* 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
*
* adplug.cpp - CAdPlug helper class implementation, by Simon Peter <dn.tlp@gmx.net>
*/
/***** Includes *****/
#include <fstream.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <string>
#include "adplug.h"
#include "debug.h"
/***** Replayer includes *****/
#include "hsc.h"
#include "mtk.h"
#include "hsp.h"
#include "s3m.h"
#include "raw.h"
#include "d00.h"
#include "sa2.h"
#include "amd.h"
#include "rad.h"
#include "a2m.h"
#include "mid.h"
#include "imf.h"
#include "sng.h"
#include "ksm.h"
#include "mkj.h"
#include "dfm.h"
#include "lds.h"
#include "bam.h"
#include "fmc.h"
#include "bmf.h"
#include "flash.h"
#include "hyp.h"
#include "psi.h"
#include "rat.h"
#include "hybrid.h"
#include "mad.h"
#include "adtrack.h"
#include "cff.h"
// These players use C++ templates, which aren't supported by WATCOM C++
#ifndef __WATCOMC__
#include "u6m.h"
#include "rol.h"
#endif
/***** Defines *****/
#define VERSION "1.3" // AdPlug library version string
/***** Static variables initializers *****/
const unsigned short CPlayer::note_table[12] = {363,385,408,432,458,485,514,544,577,611,647,686};
const unsigned char CPlayer::op_table[9] = {0x00, 0x01, 0x02, 0x08, 0x09, 0x0a, 0x10, 0x11, 0x12};
/***** List of all players that come in the standard AdPlug distribution *****/
// WARNING: The order of this list is on purpose! AdPlug tries the players in
// this order, which is to be preserved, because some players take precedence
// above other players.
// The list is terminated with an all-NULL element.
static const struct Players {
CPlayer *(*factory) (Copl *newopl);
} allplayers[] = {
{CmidPlayer::factory}, {CksmPlayer::factory},
#ifndef __WATCOMC__
{CrolPlayer::factory},
#endif
{CsngPlayer::factory}, {Ca2mLoader::factory}, {CradLoader::factory},
{CamdLoader::factory}, {Csa2Loader::factory}, {CrawPlayer::factory},
{Cs3mPlayer::factory}, {CmtkLoader::factory}, {CmkjPlayer::factory},
{CdfmLoader::factory}, {CbamPlayer::factory}, {CxadbmfPlayer::factory},
{CxadflashPlayer::factory}, {CxadhypPlayer::factory}, {CxadpsiPlayer::factory},
{CxadratPlayer::factory}, {CxadhybridPlayer::factory}, {CfmcLoader::factory},
{CmadLoader::factory}, {CcffLoader::factory},
#ifndef __WATCOMC__
{Cu6mPlayer::factory},
#endif
{Cd00Player::factory}, {ChspLoader::factory}, {ChscPlayer::factory},
{CimfPlayer::factory}, {CldsLoader::factory}, {CadtrackLoader::factory},
{0}
};
/***** Public methods *****/
CPlayer *CAdPlug::factory(const char *fn, Copl *opl)
{
ifstream f(fn, ios::in | ios::binary);
if(!f.is_open()) return 0;
return factory(f,opl,fn);
}
CPlayer *CAdPlug::factory(istream &f, Copl *opl, const char *fn)
{
CPlayer *p;
unsigned int i;
LogWrite("*** CAdPlug::factory(f,opl,\"%s\") ***\n",fn);
for(i=0;allplayers[i].factory;i++) {
LogWrite("Trying: %d\n",i);
if((p = allplayers[i].factory(opl)))
if(p->load(f,fn)) {
LogWrite("got it!\n");
LogWrite("--- CAdPlug::factory ---\n");
return p;
} else {
delete p;
f.seekg(0);
}
}
LogWrite("End of list!\n");
LogWrite("--- CAdPlug::factory ---\n");
return 0;
}
unsigned long CAdPlug::songlength(CPlayer *p, unsigned int subsong)
{
float slength = 0.0f;
// get song length
p->rewind(subsong);
while(p->update() && slength < 600000) // song length limit: 10 minutes
slength += 1000/p->getrefresh();
p->rewind(subsong);
return (unsigned long)slength;
}
void CAdPlug::seek(CPlayer *p, unsigned long ms)
{
float pos = 0.0f;
p->rewind();
while(pos < ms && p->update()) // seek to new position
pos += 1000/p->getrefresh();
}
std::string CAdPlug::get_version()
{
return std::string(VERSION);
}
void CAdPlug::debug_output(std::string filename)
{
LogFile(filename.c_str());
LogWrite("CAdPlug::debug_output(\"%s\"): Redirected.\n",filename.c_str());
}
<|endoftext|>
|
<commit_before>#include "GurobiSolver.h"
#include <Eigen/Core>
#include "gurobi_c++.h"
#include "Optimization.h"
#include "drake/common/drake_assert.h"
namespace drake {
namespace solvers {
bool GurobiSolver::available() const { return true; }
// TODO(naveenoid): This is currently largely copy-pasta from the deprecated
// Gurobi wrapper in solvers. Utilise sparsity in the constraint matrices,
// i.e. Something like :
// Eigen::SparseMatrix<double, Eigen::RowMajor> sparseA(A.sparseView());
// sparseA.makeCompressed();
// error = GRBaddconstrs(model, A.rows(), sparseA.nonZeros(),
// sparseA.InnerIndices(), sparseA.OuterStarts(),
// sparseA.Values(),sense, b.data(), NULL);
// return(error);
template <typename DerivedA, typename DerivedB>
int myGRBaddconstrs(GRBmodel* model, Eigen::MatrixBase<DerivedA> const& A,
Eigen::MatrixBase<DerivedB> const& b, char sense,
double sparseness_threshold = 1e-14) {
int error = 0, nnz = 0;
std::vector<int> cind(A.cols(), 0);
std::vector<double> cval(A.cols(), 0.0);
for (size_t i = 0; i < A.rows(); i++) {
nnz = 0;
for (size_t j = 0; j < A.cols(); j++) {
if (std::abs(A(i, j)) > sparseness_threshold) {
cval[nnz] = A(i, j);
cind[nnz++] = j;
}
}
error = GRBaddconstr(model, nnz, &cind[0], &cval[0], sense, b(i), NULL);
if (error) break;
}
return error;
}
SolutionResult GurobiSolver::Solve(OptimizationProblem& prog) const {
// We only process quadratic costs and linear / bounding box
// constraints
GRBenv* env = NULL;
GRBloadenv(&env, NULL);
// Corresponds to no console or file logging.
GRBsetintparam(env, GRB_INT_PAR_OUTPUTFLAG, 0);
DRAKE_ASSERT(prog.generic_costs().empty());
DRAKE_ASSERT(prog.generic_constraints().empty());
Eigen::VectorXd solution(prog.num_vars());
int num_vars = prog.num_vars();
// bound constraints
std::vector<double> xlow(num_vars, -std::numeric_limits<double>::infinity());
std::vector<double> xupp(num_vars, std::numeric_limits<double>::infinity());
for (auto const& binding : prog.bounding_box_constraints()) {
auto const& c = binding.constraint();
const Eigen::VectorXd& lower_bound = c->lower_bound();
const Eigen::VectorXd& upper_bound = c->upper_bound();
for (const DecisionVariableView& v : binding.variable_list()) {
for (size_t k = 0; k < v.size(); k++) {
const int idx = v.index() + k;
xlow[idx] = std::max(lower_bound(k), xlow[idx]);
xupp[idx] = std::min(upper_bound(k), xupp[idx]);
}
}
}
int error = 0;
GRBmodel* model = NULL;
double sparseness_threshold = 1e-14;
GRBnewmodel(env, &model, "QP", num_vars, NULL, &xlow[0], &xupp[0], NULL,
NULL);
int start_row = 0;
int num_constraint_vars = 0;
double individual_quadratic_cost_value = 0.0;
int row_ind = 0, col_ind = 0;
for (auto const& binding : prog.quadratic_costs()) {
auto const& c = binding.constraint();
num_constraint_vars = binding.GetNumElements();
Eigen::MatrixXd Q = 0.5 * (c->Q());
Eigen::VectorXd b = c->b();
// Check for square matrices
DRAKE_ASSERT(Q.rows() == Q.cols());
// Check for symmetric matrices
DRAKE_ASSERT(Q.transpose() == Q);
// Check for Quadratic and Linear Cost dimensions
DRAKE_ASSERT(Q.rows() == num_constraint_vars);
DRAKE_ASSERT(b.cols() == 1);
DRAKE_ASSERT(b.rows() == num_constraint_vars);
// adding each Q term (only upper triangular)
for (size_t i = 0; i < num_constraint_vars; i++) {
for (size_t j = i; j < num_constraint_vars; j++) {
if (std::abs(Q(i, j)) > sparseness_threshold) {
row_ind = i + start_row;
col_ind = j + start_row;
// TODO(naveenoid) : Port to batch addition mode of this function
// by utilising the Upper right (or lower left) triangular matrix.
// The single element addition method used below is recommended
// initiall by Gurobi since it has a low cost
individual_quadratic_cost_value = Q(i, j);
error = GRBaddqpterms(model, 1, &row_ind, &col_ind,
&individual_quadratic_cost_value);
}
}
}
GRBsetdblattrarray(model, "Obj", start_row, num_constraint_vars, b.data());
start_row = start_row + Q.rows();
}
// TODO(naveenoid) : needs test coverage
for (auto const& binding : prog.linear_equality_constraints()) {
auto const& c = binding.constraint();
myGRBaddconstrs(model, c->A(), c->lower_bound(), GRB_EQUAL, 1e-18);
}
for (auto const& binding : prog.linear_constraints()) {
auto const& c = binding.constraint();
if (c->lower_bound() !=
-Eigen::MatrixXd::Constant((c->lower_bound()).rows(), 1,
std::numeric_limits<double>::infinity())) {
myGRBaddconstrs(model, c->A(), c->lower_bound(), GRB_GREATER_EQUAL,
1e-18);
}
if (c->upper_bound() !=
Eigen::MatrixXd::Constant((c->upper_bound()).rows(), 1,
std::numeric_limits<double>::infinity())) {
myGRBaddconstrs(model, c->A(), c->upper_bound(), GRB_LESS_EQUAL, 1e-18);
}
}
SolutionResult result = SolutionResult::kSolutionFound;
error = GRBoptimize(model);
int optimstatus;
double objval;
if (error) {
// TODO(naveenoid) : log error message using GRBgeterrormsg(env)
result = SolutionResult::kInvalidInput;
} else {
error = GRBgetintattr(model, GRB_INT_ATTR_STATUS, &optimstatus);
error = GRBgetdblattr(model, GRB_DBL_ATTR_OBJVAL, &objval);
if (optimstatus != GRB_OPTIMAL) {
if (optimstatus == GRB_INF_OR_UNBD) {
result = SolutionResult::kInfeasibleConstraints;
} else {
result = SolutionResult::kUnknownError;
}
}
}
Eigen::VectorXd sol_vector = Eigen::VectorXd::Zero(num_vars);
GRBgetdblattrarray(model, GRB_DBL_ATTR_X, 0, num_vars, sol_vector.data());
prog.SetDecisionVariableValues(sol_vector);
prog.SetSolverResult("Gurobi", 0);
GRBfreemodel(model);
GRBfreeenv(env);
return result;
}
} // namespace drake
} // namespace solvers
<commit_msg>initialization of some variables<commit_after>#include "GurobiSolver.h"
#include <Eigen/Core>
#include "gurobi_c++.h"
#include "Optimization.h"
#include "drake/common/drake_assert.h"
namespace drake {
namespace solvers {
bool GurobiSolver::available() const { return true; }
// TODO(naveenoid): This is currently largely copy-pasta from the deprecated
// Gurobi wrapper in solvers. Utilise sparsity in the constraint matrices,
// i.e. Something like :
// Eigen::SparseMatrix<double, Eigen::RowMajor> sparseA(A.sparseView());
// sparseA.makeCompressed();
// error = GRBaddconstrs(model, A.rows(), sparseA.nonZeros(),
// sparseA.InnerIndices(), sparseA.OuterStarts(),
// sparseA.Values(),sense, b.data(), NULL);
// return(error);
template <typename DerivedA, typename DerivedB>
int myGRBaddconstrs(GRBmodel* model, Eigen::MatrixBase<DerivedA> const& A,
Eigen::MatrixBase<DerivedB> const& b, char sense,
double sparseness_threshold = 1e-14) {
int error = 0, nnz = 0;
std::vector<int> cind(A.cols(), 0);
std::vector<double> cval(A.cols(), 0.0);
for (size_t i = 0; i < A.rows(); i++) {
nnz = 0;
for (size_t j = 0; j < A.cols(); j++) {
if (std::abs(A(i, j)) > sparseness_threshold) {
cval[nnz] = A(i, j);
cind[nnz++] = j;
}
}
error = GRBaddconstr(model, nnz, &cind[0], &cval[0], sense, b(i), NULL);
if (error) break;
}
return error;
}
SolutionResult GurobiSolver::Solve(OptimizationProblem& prog) const {
// We only process quadratic costs and linear / bounding box
// constraints
GRBenv* env = NULL;
GRBloadenv(&env, NULL);
// Corresponds to no console or file logging.
GRBsetintparam(env, GRB_INT_PAR_OUTPUTFLAG, 0);
DRAKE_ASSERT(prog.generic_costs().empty());
DRAKE_ASSERT(prog.generic_constraints().empty());
Eigen::VectorXd solution(prog.num_vars());
int num_vars = prog.num_vars();
// bound constraints
std::vector<double> xlow(num_vars, -std::numeric_limits<double>::infinity());
std::vector<double> xupp(num_vars, std::numeric_limits<double>::infinity());
for (auto const& binding : prog.bounding_box_constraints()) {
auto const& c = binding.constraint();
const Eigen::VectorXd& lower_bound = c->lower_bound();
const Eigen::VectorXd& upper_bound = c->upper_bound();
for (const DecisionVariableView& v : binding.variable_list()) {
for (size_t k = 0; k < v.size(); k++) {
const int idx = v.index() + k;
xlow[idx] = std::max(lower_bound(k), xlow[idx]);
xupp[idx] = std::min(upper_bound(k), xupp[idx]);
}
}
}
int error = 0;
GRBmodel* model = NULL;
double sparseness_threshold = 1e-14;
GRBnewmodel(env, &model, "QP", num_vars, NULL, &xlow[0], &xupp[0], NULL,
NULL);
int start_row = 0;
int num_constraint_vars = 0;
double individual_quadratic_cost_value = 0.0;
int row_ind = 0, col_ind = 0;
for (auto const& binding : prog.quadratic_costs()) {
auto const& c = binding.constraint();
num_constraint_vars = binding.GetNumElements();
Eigen::MatrixXd Q = 0.5 * (c->Q());
Eigen::VectorXd b = c->b();
// Check for square matrices
DRAKE_ASSERT(Q.rows() == Q.cols());
// Check for symmetric matrices
DRAKE_ASSERT(Q.transpose() == Q);
// Check for Quadratic and Linear Cost dimensions
DRAKE_ASSERT(Q.rows() == num_constraint_vars);
DRAKE_ASSERT(b.cols() == 1);
DRAKE_ASSERT(b.rows() == num_constraint_vars);
// adding each Q term (only upper triangular)
for (size_t i = 0; i < num_constraint_vars; i++) {
for (size_t j = i; j < num_constraint_vars; j++) {
if (std::abs(Q(i, j)) > sparseness_threshold) {
row_ind = i + start_row;
col_ind = j + start_row;
// TODO(naveenoid) : Port to batch addition mode of this function
// by utilising the Upper right (or lower left) triangular matrix.
// The single element addition method used below is recommended
// initiall by Gurobi since it has a low cost
individual_quadratic_cost_value = Q(i, j);
error = GRBaddqpterms(model, 1, &row_ind, &col_ind,
&individual_quadratic_cost_value);
}
}
}
GRBsetdblattrarray(model, "Obj", start_row, num_constraint_vars, b.data());
start_row = start_row + Q.rows();
}
// TODO(naveenoid) : needs test coverage
for (auto const& binding : prog.linear_equality_constraints()) {
auto const& c = binding.constraint();
myGRBaddconstrs(model, c->A(), c->lower_bound(), GRB_EQUAL, 1e-18);
}
for (auto const& binding : prog.linear_constraints()) {
auto const& c = binding.constraint();
if (c->lower_bound() !=
-Eigen::MatrixXd::Constant((c->lower_bound()).rows(), 1,
std::numeric_limits<double>::infinity())) {
myGRBaddconstrs(model, c->A(), c->lower_bound(), GRB_GREATER_EQUAL,
1e-18);
}
if (c->upper_bound() !=
Eigen::MatrixXd::Constant((c->upper_bound()).rows(), 1,
std::numeric_limits<double>::infinity())) {
myGRBaddconstrs(model, c->A(), c->upper_bound(), GRB_LESS_EQUAL, 1e-18);
}
}
SolutionResult result = SolutionResult::kSolutionFound;
error = GRBoptimize(model);
int optimstatus = 0;
double objval = 0.0;
if (error) {
// TODO(naveenoid) : log error message using GRBgeterrormsg(env)
result = SolutionResult::kInvalidInput;
} else {
error = GRBgetintattr(model, GRB_INT_ATTR_STATUS, &optimstatus);
error = GRBgetdblattr(model, GRB_DBL_ATTR_OBJVAL, &objval);
if (optimstatus != GRB_OPTIMAL) {
if (optimstatus == GRB_INF_OR_UNBD) {
result = SolutionResult::kInfeasibleConstraints;
} else {
result = SolutionResult::kUnknownError;
}
}
}
Eigen::VectorXd sol_vector = Eigen::VectorXd::Zero(num_vars);
GRBgetdblattrarray(model, GRB_DBL_ATTR_X, 0, num_vars, sol_vector.data());
prog.SetDecisionVariableValues(sol_vector);
prog.SetSolverResult("Gurobi", 0);
GRBfreemodel(model);
GRBfreeenv(env);
return result;
}
} // namespace drake
} // namespace solvers
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "xwalk/application/browser/application_protocols.h"
#include <algorithm>
#include <string>
#include <vector>
#include "base/files/file_path.h"
#include "base/memory/weak_ptr.h"
#include "base/threading/thread_restrictions.h"
#include "base/threading/worker_pool.h"
#include "base/threading/sequenced_worker_pool.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/resource_request_info.h"
#include "url/url_util.h"
#include "net/base/net_errors.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_response_info.h"
#include "net/url_request/url_request_error_job.h"
#include "net/url_request/url_request_file_job.h"
#include "net/url_request/url_request_simple_job.h"
#include "xwalk/application/common/application_data.h"
#include "xwalk/application/common/application_file_util.h"
#include "xwalk/application/common/application_manifest_constants.h"
#include "xwalk/application/common/application_resource.h"
#include "xwalk/application/common/constants.h"
#include "xwalk/application/common/manifest_handlers/main_document_handler.h"
using content::ResourceRequestInfo;
using xwalk::application::ApplicationData;
using xwalk::application::MainDocumentInfo;
namespace keys = xwalk::application_manifest_keys;
namespace {
net::HttpResponseHeaders* BuildHttpHeaders(
const std::string& mime_type, const std::string& method,
const base::FilePath& file_path, const base::FilePath& relative_path,
bool is_authority_match) {
std::string raw_headers;
if (method == "GET") {
if (relative_path.empty())
raw_headers.append("HTTP/1.1 400 Bad Request");
else if (!is_authority_match)
raw_headers.append("HTTP/1.1 403 Forbidden");
else if (file_path.empty())
raw_headers.append("HTTP/1.1 404 Not Found");
else
raw_headers.append("HTTP/1.1 200 OK");
} else {
raw_headers.append("HTTP/1.1 501 Not Implemented");
}
raw_headers.append(1, '\0');
raw_headers.append("Access-Control-Allow-Origin: *");
if (!mime_type.empty()) {
raw_headers.append(1, '\0');
raw_headers.append("Content-Type: ");
raw_headers.append(mime_type);
}
raw_headers.append(2, '\0');
return new net::HttpResponseHeaders(raw_headers);
}
class GeneratedMainDocumentJob: public net::URLRequestSimpleJob {
public:
GeneratedMainDocumentJob(
net::URLRequest* request,
net::NetworkDelegate* network_delegate,
const base::FilePath& relative_path,
const scoped_refptr<const ApplicationData> application)
: net::URLRequestSimpleJob(request, network_delegate),
application_(application),
mime_type_("text/html"),
relative_path_(relative_path) {
}
// Overridden from URLRequestSimpleJob:
virtual int GetData(std::string* mime_type,
std::string* charset,
std::string* data,
const net::CompletionCallback& callback) const OVERRIDE {
*mime_type = mime_type_;
*charset = "utf-8";
*data = "<!DOCTYPE html>\n<body>\n";
MainDocumentInfo* main_info = xwalk::application::ToMainDocumentInfo(
application_->GetManifestData(keys::kAppMainKey));
const std::vector<std::string>& main_scripts = main_info->GetMainScripts();
for (size_t i = 0; i < main_scripts.size(); ++i) {
*data += "<script src=\"";
*data += main_scripts[i];
*data += "\"></script>\n";
}
return net::OK;
}
virtual void GetResponseInfo(net::HttpResponseInfo* info) OVERRIDE {
response_info_.headers = BuildHttpHeaders(mime_type_, "GET", relative_path_,
relative_path_, true);
*info = response_info_;
}
private:
virtual ~GeneratedMainDocumentJob() {}
scoped_refptr<const ApplicationData> application_;
const std::string mime_type_;
const base::FilePath relative_path_;
net::HttpResponseInfo response_info_;
};
void ReadResourceFilePath(
const xwalk::application::ApplicationResource& resource,
base::FilePath* file_path) {
*file_path = resource.GetFilePath();
}
class URLRequestApplicationJob : public net::URLRequestFileJob {
public:
URLRequestApplicationJob(
net::URLRequest* request,
net::NetworkDelegate* network_delegate,
const scoped_refptr<base::TaskRunner>& file_task_runner,
const std::string& application_id,
const base::FilePath& directory_path,
const base::FilePath& relative_path,
bool is_authority_match)
: net::URLRequestFileJob(
request, network_delegate, base::FilePath(), file_task_runner),
relative_path_(relative_path),
is_authority_match_(is_authority_match),
resource_(application_id, directory_path, relative_path),
weak_factory_(this) {
}
virtual void GetResponseInfo(net::HttpResponseInfo* info) OVERRIDE {
std::string mime_type;
GetMimeType(&mime_type);
std::string method = request()->method();
response_info_.headers = BuildHttpHeaders(mime_type, method, file_path_,
relative_path_, is_authority_match_);
*info = response_info_;
}
virtual void Start() OVERRIDE {
base::FilePath* read_file_path = new base::FilePath;
bool posted = base::WorkerPool::PostTaskAndReply(
FROM_HERE,
base::Bind(&ReadResourceFilePath, resource_,
base::Unretained(read_file_path)),
base::Bind(&URLRequestApplicationJob::OnFilePathRead,
weak_factory_.GetWeakPtr(),
base::Owned(read_file_path)),
true /* task is slow */);
DCHECK(posted);
}
private:
virtual ~URLRequestApplicationJob() {}
void OnFilePathRead(base::FilePath* read_file_path) {
file_path_ = *read_file_path;
if (file_path_.empty())
NotifyHeadersComplete();
else
URLRequestFileJob::Start();
}
net::HttpResponseInfo response_info_;
base::FilePath relative_path_;
bool is_authority_match_;
xwalk::application::ApplicationResource resource_;
base::WeakPtrFactory<URLRequestApplicationJob> weak_factory_;
};
class ApplicationProtocolHandler
: public net::URLRequestJobFactory::ProtocolHandler {
public:
explicit ApplicationProtocolHandler(const ApplicationData* application)
: application_(application) {
CHECK(application_);
}
virtual ~ApplicationProtocolHandler() {}
virtual net::URLRequestJob* MaybeCreateJob(
net::URLRequest* request,
net::NetworkDelegate* network_delegate) const OVERRIDE;
private:
const ApplicationData* application_;
DISALLOW_COPY_AND_ASSIGN(ApplicationProtocolHandler);
};
net::URLRequestJob*
ApplicationProtocolHandler::MaybeCreateJob(
net::URLRequest* request, net::NetworkDelegate* network_delegate) const {
std::string application_id = request->url().host();
bool is_authority_match = application_id == application_->ID();
base::FilePath relative_path =
xwalk::application::ApplicationURLToRelativeFilePath(request->url());
base::FilePath directory_path;
if (is_authority_match)
directory_path = application_->Path();
std::string path = request->url().path();
if (is_authority_match &&
path.size() > 1 &&
path.substr(1) == xwalk::application::kGeneratedMainDocumentFilename) {
return new GeneratedMainDocumentJob(request, network_delegate,
relative_path, application_);
}
return new URLRequestApplicationJob(
request,
network_delegate,
content::BrowserThread::GetBlockingPool()->
GetTaskRunnerWithShutdownBehavior(
base::SequencedWorkerPool::SKIP_ON_SHUTDOWN),
application_id,
directory_path,
relative_path,
is_authority_match);
}
} // namespace
linked_ptr<net::URLRequestJobFactory::ProtocolHandler>
CreateApplicationProtocolHandler(const ApplicationData* application) {
return linked_ptr<net::URLRequestJobFactory::ProtocolHandler>(
new ApplicationProtocolHandler(application));
}
<commit_msg>[Runtime] Add CSP supporting for Crosswalk scheme<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "xwalk/application/browser/application_protocols.h"
#include <algorithm>
#include <map>
#include <string>
#include <vector>
#include "base/files/file_path.h"
#include "base/memory/weak_ptr.h"
#include "base/strings/stringprintf.h"
#include "base/strings/string_util.h"
#include "base/threading/thread_restrictions.h"
#include "base/threading/worker_pool.h"
#include "base/threading/sequenced_worker_pool.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/resource_request_info.h"
#include "url/url_util.h"
#include "net/base/net_errors.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_response_info.h"
#include "net/url_request/url_request_error_job.h"
#include "net/url_request/url_request_file_job.h"
#include "net/url_request/url_request_simple_job.h"
#include "xwalk/application/common/application_data.h"
#include "xwalk/application/common/application_file_util.h"
#include "xwalk/application/common/application_manifest_constants.h"
#include "xwalk/application/common/application_resource.h"
#include "xwalk/application/common/constants.h"
#include "xwalk/application/common/manifest_handlers/csp_handler.h"
#include "xwalk/application/common/manifest_handlers/main_document_handler.h"
using content::ResourceRequestInfo;
using xwalk::application::ApplicationData;
using xwalk::application::CSPInfo;
using xwalk::application::MainDocumentInfo;
namespace keys = xwalk::application_manifest_keys;
namespace {
net::HttpResponseHeaders* BuildHttpHeaders(
const std::string& content_security_policy,
const std::string& mime_type, const std::string& method,
const base::FilePath& file_path, const base::FilePath& relative_path,
bool is_authority_match) {
std::string raw_headers;
if (method == "GET") {
if (relative_path.empty())
raw_headers.append("HTTP/1.1 400 Bad Request");
else if (!is_authority_match)
raw_headers.append("HTTP/1.1 403 Forbidden");
else if (file_path.empty())
raw_headers.append("HTTP/1.1 404 Not Found");
else
raw_headers.append("HTTP/1.1 200 OK");
} else {
raw_headers.append("HTTP/1.1 501 Not Implemented");
}
if (!content_security_policy.empty()) {
raw_headers.append(1, '\0');
raw_headers.append("Content-Security-Policy: ");
raw_headers.append(content_security_policy);
}
raw_headers.append(1, '\0');
raw_headers.append("Access-Control-Allow-Origin: *");
if (!mime_type.empty()) {
raw_headers.append(1, '\0');
raw_headers.append("Content-Type: ");
raw_headers.append(mime_type);
}
raw_headers.append(2, '\0');
return new net::HttpResponseHeaders(raw_headers);
}
class GeneratedMainDocumentJob: public net::URLRequestSimpleJob {
public:
GeneratedMainDocumentJob(
net::URLRequest* request,
net::NetworkDelegate* network_delegate,
const base::FilePath& relative_path,
const scoped_refptr<const ApplicationData> application,
const std::string& content_security_policy)
: net::URLRequestSimpleJob(request, network_delegate),
application_(application),
mime_type_("text/html"),
relative_path_(relative_path),
content_security_policy_(content_security_policy) {
}
// Overridden from URLRequestSimpleJob:
virtual int GetData(std::string* mime_type,
std::string* charset,
std::string* data,
const net::CompletionCallback& callback) const OVERRIDE {
*mime_type = mime_type_;
*charset = "utf-8";
*data = "<!DOCTYPE html>\n<body>\n";
MainDocumentInfo* main_info = xwalk::application::ToMainDocumentInfo(
application_->GetManifestData(keys::kAppMainKey));
const std::vector<std::string>& main_scripts = main_info->GetMainScripts();
for (size_t i = 0; i < main_scripts.size(); ++i) {
*data += "<script src=\"";
*data += main_scripts[i];
*data += "\"></script>\n";
}
return net::OK;
}
virtual void GetResponseInfo(net::HttpResponseInfo* info) OVERRIDE {
response_info_.headers = BuildHttpHeaders(content_security_policy_,
mime_type_, "GET", relative_path_,
relative_path_, true);
*info = response_info_;
}
private:
virtual ~GeneratedMainDocumentJob() {}
scoped_refptr<const ApplicationData> application_;
const std::string mime_type_;
const base::FilePath relative_path_;
net::HttpResponseInfo response_info_;
std::string content_security_policy_;
};
void ReadResourceFilePath(
const xwalk::application::ApplicationResource& resource,
base::FilePath* file_path) {
*file_path = resource.GetFilePath();
}
class URLRequestApplicationJob : public net::URLRequestFileJob {
public:
URLRequestApplicationJob(
net::URLRequest* request,
net::NetworkDelegate* network_delegate,
const scoped_refptr<base::TaskRunner>& file_task_runner,
const std::string& application_id,
const base::FilePath& directory_path,
const base::FilePath& relative_path,
const std::string& content_security_policy,
bool is_authority_match)
: net::URLRequestFileJob(
request, network_delegate, base::FilePath(), file_task_runner),
relative_path_(relative_path),
content_security_policy_(content_security_policy),
is_authority_match_(is_authority_match),
resource_(application_id, directory_path, relative_path),
weak_factory_(this) {
}
virtual void GetResponseInfo(net::HttpResponseInfo* info) OVERRIDE {
std::string mime_type;
GetMimeType(&mime_type);
std::string method = request()->method();
response_info_.headers = BuildHttpHeaders(
content_security_policy_, mime_type, method, file_path_,
relative_path_, is_authority_match_);
*info = response_info_;
}
virtual void Start() OVERRIDE {
base::FilePath* read_file_path = new base::FilePath;
bool posted = base::WorkerPool::PostTaskAndReply(
FROM_HERE,
base::Bind(&ReadResourceFilePath, resource_,
base::Unretained(read_file_path)),
base::Bind(&URLRequestApplicationJob::OnFilePathRead,
weak_factory_.GetWeakPtr(),
base::Owned(read_file_path)),
true /* task is slow */);
DCHECK(posted);
}
private:
virtual ~URLRequestApplicationJob() {}
void OnFilePathRead(base::FilePath* read_file_path) {
file_path_ = *read_file_path;
if (file_path_.empty())
NotifyHeadersComplete();
else
URLRequestFileJob::Start();
}
net::HttpResponseInfo response_info_;
base::FilePath relative_path_;
std::string content_security_policy_;
bool is_authority_match_;
xwalk::application::ApplicationResource resource_;
base::WeakPtrFactory<URLRequestApplicationJob> weak_factory_;
};
class ApplicationProtocolHandler
: public net::URLRequestJobFactory::ProtocolHandler {
public:
explicit ApplicationProtocolHandler(const ApplicationData* application)
: application_(application) {
CHECK(application_);
}
virtual ~ApplicationProtocolHandler() {}
virtual net::URLRequestJob* MaybeCreateJob(
net::URLRequest* request,
net::NetworkDelegate* network_delegate) const OVERRIDE;
private:
const ApplicationData* application_;
DISALLOW_COPY_AND_ASSIGN(ApplicationProtocolHandler);
};
net::URLRequestJob*
ApplicationProtocolHandler::MaybeCreateJob(
net::URLRequest* request, net::NetworkDelegate* network_delegate) const {
std::string application_id = request->url().host();
bool is_authority_match = application_id == application_->ID();
base::FilePath relative_path =
xwalk::application::ApplicationURLToRelativeFilePath(request->url());
base::FilePath directory_path;
if (is_authority_match)
directory_path = application_->Path();
std::string content_security_policy;
const CSPInfo* csp_info = static_cast<CSPInfo*>(
application_->GetManifestData(keys::kCSPKey));
if (csp_info) {
const std::map<std::string, std::vector<std::string> >& policies =
csp_info->GetDirectives();
for (std::map<std::string, std::vector<std::string> >::const_iterator it =
policies.begin(); it != policies.end(); ++it) {
content_security_policy += base::StringPrintf(
"%s %s;", (it->first).c_str(), JoinString(it->second, ' ').c_str());
}
}
std::string path = request->url().path();
if (is_authority_match &&
path.size() > 1 &&
path.substr(1) == xwalk::application::kGeneratedMainDocumentFilename) {
return new GeneratedMainDocumentJob(request, network_delegate,
relative_path, application_,
content_security_policy);
}
return new URLRequestApplicationJob(
request,
network_delegate,
content::BrowserThread::GetBlockingPool()->
GetTaskRunnerWithShutdownBehavior(
base::SequencedWorkerPool::SKIP_ON_SHUTDOWN),
application_id,
directory_path,
relative_path,
content_security_policy,
is_authority_match);
}
} // namespace
linked_ptr<net::URLRequestJobFactory::ProtocolHandler>
CreateApplicationProtocolHandler(const ApplicationData* application) {
return linked_ptr<net::URLRequestJobFactory::ProtocolHandler>(
new ApplicationProtocolHandler(application));
}
<|endoftext|>
|
<commit_before>/*******************************************************************************
*
* MIT License
*
* Copyright (c) 2017 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*******************************************************************************/
#include <algorithm>
#include <cassert>
#include <miopen/errors.hpp>
#include <miopen/logger.hpp>
#include <miopen/tensor.hpp>
#include <numeric>
#include <string>
namespace miopen {
TensorDescriptor::TensorDescriptor() {}
TensorDescriptor::TensorDescriptor(miopenDataType_t t, std::initializer_list<std::size_t> plens)
: lens(plens), type(t)
{
if(t != miopenFloat)
{
MIOPEN_THROW(miopenStatusNotImplemented, "Only float datatype is supported");
}
this->CalculateStrides();
}
TensorDescriptor::TensorDescriptor(miopenDataType_t t,
std::initializer_list<std::size_t> plens,
std::initializer_list<std::size_t> pstrides)
: lens(plens), strides(pstrides), type(t)
{
if(t != miopenFloat)
{
MIOPEN_THROW(miopenStatusNotImplemented, "Only float datatype is supported");
}
}
TensorDescriptor::TensorDescriptor(miopenDataType_t t, const int* plens, int size)
: lens(plens, plens + size), type(t)
{
if(t != miopenFloat)
{
MIOPEN_THROW(miopenStatusNotImplemented, "Only float datatype is supported");
}
this->CalculateStrides();
}
TensorDescriptor::TensorDescriptor(miopenDataType_t t,
const int* plens,
const int* pstrides,
int size)
: lens(plens, plens + size), strides(pstrides, pstrides + size), type(t)
{
if(t != miopenFloat)
{
MIOPEN_THROW(miopenStatusNotImplemented, "Only float datatype is supported");
}
}
void TensorDescriptor::CalculateStrides()
{
strides.clear();
strides.resize(lens.size(), 0);
strides.back() = 1;
std::partial_sum(lens.rbegin(), lens.rend() - 1, strides.rbegin() + 1, std::multiplies<int>());
}
const std::vector<std::size_t>& TensorDescriptor::GetLengths() const { return lens; }
const std::vector<std::size_t>& TensorDescriptor::GetStrides() const { return strides; }
int TensorDescriptor::GetSize() const
{
assert(lens.size() == strides.size());
return lens.size();
}
std::size_t TensorDescriptor::GetElementSize() const
{
assert(lens.size() == strides.size());
return std::accumulate(
lens.begin(), lens.end(), std::size_t{1}, std::multiplies<std::size_t>());
}
miopenDataType_t TensorDescriptor::GetType() const { return this->type; }
std::size_t TensorDescriptor::GetIndex(std::initializer_list<int> l) const
{
assert(l.size() <= this->GetSize());
return std::inner_product(l.begin(), l.end(), strides.begin(), std::size_t{0});
}
std::size_t TensorDescriptor::GetElementSpace() const
{
std::vector<std::size_t> maxIndices(lens.size());
std::transform(lens.begin(),
lens.end(),
std::vector<std::size_t>(lens.size(), 1).begin(),
maxIndices.begin(),
std::minus<size_t>());
return std::inner_product(
maxIndices.begin(), maxIndices.end(), strides.begin(), std::size_t{0}) +
1;
}
std::size_t TensorDescriptor::GetNumBytes() const
{
std::size_t typesize = 0;
switch(this->type)
{
case miopenHalf: typesize = 2; break;
case miopenFloat: typesize = 4; break;
}
return typesize * this->GetElementSpace();
}
bool TensorDescriptor::operator==(const TensorDescriptor& rhs) const
{
assert(this->lens.size() == rhs.strides.size());
return this->type == rhs.type && this->lens == rhs.lens;
}
bool TensorDescriptor::operator!=(const TensorDescriptor& rhs) const { return !(*this == rhs); }
std::string TensorDescriptor::ToString() const
{
std::string result;
for(auto i : this->lens)
{
result += std::to_string(i) + ", ";
}
return result.substr(0, result.length() - 2);
}
std::ostream& operator<<(std::ostream& stream, const TensorDescriptor& t)
{
return LogRange(stream, t.lens, ", ");
}
} // namespace miopen
// TODO(paul): Remove
MIOPEN_EXPORT
int miopenGetTensorIndex(miopenTensorDescriptor_t tensorDesc, std::initializer_list<int> indices)
{
return miopen::deref(tensorDesc).GetIndex(indices);
}
<commit_msg>added back strides in the equality of tensors<commit_after>/*******************************************************************************
*
* MIT License
*
* Copyright (c) 2017 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*******************************************************************************/
#include <algorithm>
#include <cassert>
#include <miopen/errors.hpp>
#include <miopen/logger.hpp>
#include <miopen/tensor.hpp>
#include <numeric>
#include <string>
namespace miopen {
TensorDescriptor::TensorDescriptor() {}
TensorDescriptor::TensorDescriptor(miopenDataType_t t, std::initializer_list<std::size_t> plens)
: lens(plens), type(t)
{
if(t != miopenFloat)
{
MIOPEN_THROW(miopenStatusNotImplemented, "Only float datatype is supported");
}
this->CalculateStrides();
}
TensorDescriptor::TensorDescriptor(miopenDataType_t t,
std::initializer_list<std::size_t> plens,
std::initializer_list<std::size_t> pstrides)
: lens(plens), strides(pstrides), type(t)
{
if(t != miopenFloat)
{
MIOPEN_THROW(miopenStatusNotImplemented, "Only float datatype is supported");
}
}
TensorDescriptor::TensorDescriptor(miopenDataType_t t, const int* plens, int size)
: lens(plens, plens + size), type(t)
{
if(t != miopenFloat)
{
MIOPEN_THROW(miopenStatusNotImplemented, "Only float datatype is supported");
}
this->CalculateStrides();
}
TensorDescriptor::TensorDescriptor(miopenDataType_t t,
const int* plens,
const int* pstrides,
int size)
: lens(plens, plens + size), strides(pstrides, pstrides + size), type(t)
{
if(t != miopenFloat)
{
MIOPEN_THROW(miopenStatusNotImplemented, "Only float datatype is supported");
}
}
void TensorDescriptor::CalculateStrides()
{
strides.clear();
strides.resize(lens.size(), 0);
strides.back() = 1;
std::partial_sum(lens.rbegin(), lens.rend() - 1, strides.rbegin() + 1, std::multiplies<int>());
}
const std::vector<std::size_t>& TensorDescriptor::GetLengths() const { return lens; }
const std::vector<std::size_t>& TensorDescriptor::GetStrides() const { return strides; }
int TensorDescriptor::GetSize() const
{
assert(lens.size() == strides.size());
return lens.size();
}
std::size_t TensorDescriptor::GetElementSize() const
{
assert(lens.size() == strides.size());
return std::accumulate(
lens.begin(), lens.end(), std::size_t{1}, std::multiplies<std::size_t>());
}
miopenDataType_t TensorDescriptor::GetType() const { return this->type; }
std::size_t TensorDescriptor::GetIndex(std::initializer_list<int> l) const
{
assert(l.size() <= this->GetSize());
return std::inner_product(l.begin(), l.end(), strides.begin(), std::size_t{0});
}
std::size_t TensorDescriptor::GetElementSpace() const
{
std::vector<std::size_t> maxIndices(lens.size());
std::transform(lens.begin(),
lens.end(),
std::vector<std::size_t>(lens.size(), 1).begin(),
maxIndices.begin(),
std::minus<size_t>());
return std::inner_product(
maxIndices.begin(), maxIndices.end(), strides.begin(), std::size_t{0}) +
1;
}
std::size_t TensorDescriptor::GetNumBytes() const
{
std::size_t typesize = 0;
switch(this->type)
{
case miopenHalf: typesize = 2; break;
case miopenFloat: typesize = 4; break;
}
return typesize * this->GetElementSpace();
}
bool TensorDescriptor::operator==(const TensorDescriptor& rhs) const
{
assert(this->lens.size() == rhs.strides.size());
return this->type == rhs.type && this->lens == rhs.lens && this->strides == rhs.strides;
}
bool TensorDescriptor::operator!=(const TensorDescriptor& rhs) const { return !(*this == rhs); }
std::string TensorDescriptor::ToString() const
{
std::string result;
for(auto i : this->lens)
{
result += std::to_string(i) + ", ";
}
return result.substr(0, result.length() - 2);
}
std::ostream& operator<<(std::ostream& stream, const TensorDescriptor& t)
{
return LogRange(stream, t.lens, ", ");
}
} // namespace miopen
// TODO(paul): Remove
MIOPEN_EXPORT
int miopenGetTensorIndex(miopenTensorDescriptor_t tensorDesc, std::initializer_list<int> indices)
{
return miopen::deref(tensorDesc).GetIndex(indices);
}
<|endoftext|>
|
<commit_before>#pragma once
/**
@file
@brief format string
Copyright (C) 2011 Cybozu Labs, Inc., all rights reserved.
*/
#include <string>
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <cybozu/exception.hpp>
namespace cybozu {
std::string format(const char *format, ...)
{
#ifdef _MSC_VER
va_list args;
va_start(args, format);
_locale_t curLoc = _get_current_locale();
va_start(args, format);
int size = _vscprintf_l(format, curLoc, args);
va_end(args);
if (size < 0 || size >= INT_MAX) throw cybozu::Exception("format:_vscprintf_l");
std::string str;
str.resize(size + 1);
va_start(args, format);
int ret = _vsprintf_s_l(&str[0], size + 1, format, curLoc, args);
va_end(args);
if (ret < 0) throw cybozu::Exception("format:_vsprintf_s_l");
str.resize(size);
return str;
#else
char *p;
va_list args;
va_start(args, format);
int ret = vasprintf(&p, format, args);
va_end(args);
if (ret < 0) throw cybozu::Exception("format:vasnprintf");
try {
std::string str(p, ret);
free(p);
return str;
} catch (...) {
free(p);
throw std::bad_alloc();
}
#endif
}
} // cybozu
<commit_msg>add vformat<commit_after>#pragma once
/**
@file
@brief format string
Copyright (C) 2011 Cybozu Labs, Inc., all rights reserved.
*/
#include <string>
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <cybozu/exception.hpp>
namespace cybozu {
inline void vformat(std::string& str, const char *format, va_list args)
{
#ifdef _MSC_VER
va_list args2;
va_copy(args2, args);
_locale_t curLoc = _get_current_locale();
int size = _vscprintf_l(format, curLoc, args);
if (size < 0 || size >= INT_MAX) throw cybozu::Exception("vformat:_vscprintf_l");
str.resize(size + 1);
int ret = _vsprintf_s_l(&str[0], size + 1, format, curLoc, args2);
if (ret < 0) throw cybozu::Exception("vformat:_vsprintf_s_l");
str.resize(size);
#else
char *p;
int ret = vasprintf(&p, format, args);
if (ret < 0) throw cybozu::Exception("vformat:vasnprintf");
try {
str.assign(p, ret);
free(p);
} catch (...) {
free(p);
throw std::bad_alloc();
}
#endif
}
inline void format(std::string& str, const char *format, ...)
{
va_list args;
va_start(args, format);
cybozu::vformat(str, format, args);
va_end(args);
}
inline std::string format(const char *format, ...)
{
std::string str;
va_list args;
va_start(args, format);
cybozu::vformat(str, format, args);
va_end(args);
return str;
}
} // cybozu
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright (c) 2014-2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef ETL_EVALUATOR_HPP
#define ETL_EVALUATOR_HPP
#include "traits_lite.hpp" //forward declaration of the traits
#include "visitor.hpp" //forward declaration of the traits
namespace etl {
namespace detail {
struct temporary_allocator_static_visitor : etl_visitor<temporary_allocator_static_visitor> {
template<typename E>
using enabled = cpp::bool_constant<decay_traits<E>::needs_temporary_visitor>;
using etl_visitor<temporary_allocator_static_visitor>::operator();
template <typename T, typename AExpr, typename Op, typename Forced>
void operator()(etl::temporary_unary_expr<T, AExpr, Op, Forced>& v) const {
v.allocate_temporary();
(*this)(v.a());
}
template <typename T, typename AExpr, typename BExpr, typename Op, typename Forced>
void operator()(etl::temporary_binary_expr<T, AExpr, BExpr, Op, Forced>& v) const {
v.allocate_temporary();
(*this)(v.a());
(*this)(v.b());
}
};
struct evaluator_static_visitor : etl_visitor<evaluator_static_visitor> {
template<typename E>
using enabled = cpp::bool_constant<decay_traits<E>::needs_evaluator_visitor>;
using etl_visitor<evaluator_static_visitor>::operator();
template <typename T, typename AExpr, typename Op, typename Forced>
void operator()(etl::temporary_unary_expr<T, AExpr, Op, Forced>& v) const {
(*this)(v.a());
v.evaluate();
}
template <typename T, typename AExpr, typename BExpr, typename Op, typename Forced>
void operator()(etl::temporary_binary_expr<T, AExpr, BExpr, Op, Forced>& v) const {
(*this)(v.a());
(*this)(v.b());
v.evaluate();
}
};
} //end of namespace detail
template<typename Expr, typename Result>
struct standard_evaluator {
template<typename E>
static void evaluate_only(E&& expr){
apply_visitor<detail::temporary_allocator_static_visitor>(expr);
apply_visitor<detail::evaluator_static_visitor>(expr);
}
template<typename E, typename R>
struct vectorized_assign : cpp::and_u<
vectorize_expr,
decay_traits<E>::vectorizable,
intrinsic_traits<value_t<R>>::vectorizable, intrinsic_traits<value_t<E>>::vectorizable,
std::is_same<typename intrinsic_traits<value_t<R>>::intrinsic_type, typename intrinsic_traits<value_t<E>>::intrinsic_type>::value> {};
template<typename E, typename R, cpp_enable_if(!vectorized_assign<E, R>::value && has_direct_access<R>::value && !is_temporary_expr<E>::value)>
static void assign_evaluate(E&& expr, R&& result){
evaluate_only(expr);
auto m = result.memory_start();
const std::size_t size = etl::size(result);
std::size_t iend = 0;
if(unroll_normal_loops){
iend = size & std::size_t(-4);
for(std::size_t i = 0; i < iend; i += 4){
m[i] = expr[i];
m[i+1] = expr[i+1];
m[i+2] = expr[i+2];
m[i+3] = expr[i+3];
}
}
for(std::size_t i = iend; i < size; ++i){
m[i] = expr[i];
}
}
template<typename E, typename R, cpp_enable_if(!vectorized_assign<E, R>::value && !has_direct_access<R>::value && !is_temporary_expr<E>::value)>
static void assign_evaluate(E&& expr, R&& result){
evaluate_only(expr);
const std::size_t size = etl::size(result);
for(std::size_t i = 0; i < size; ++i){
result[i] = expr[i];
}
}
template<typename E, typename R, cpp_enable_if(vectorized_assign<E, R>::value && !is_temporary_expr<E>::value)>
static void assign_evaluate(E&& expr, R&& result){
evaluate_only(expr);
using IT = intrinsic_traits<value_t<E>>;
auto m = result.memory_start();
const std::size_t size = etl::size(result);
std::size_t i = 0;
//1. Peel loop
constexpr const auto size_1 = sizeof(value_t<E>);
auto u_bytes = (reinterpret_cast<uintptr_t>(m) % IT::alignment);
if(u_bytes >= size_1 && u_bytes % size_1 == 0){
auto u_loads = std::min(u_bytes & -size_1, size);
for(; i < u_loads; ++i){
m[i] = expr[i];
}
}
//2. Vectorized loop
if(size - i >= IT::size){
if(reinterpret_cast<uintptr_t>(m + i) % IT::alignment == 0){
if(unroll_vectorized_loops && size - i > IT::size * 4){
for(; i + IT::size * 4 - 1 < size; i += IT::size * 4){
vec::store(m + i, expr.load(i));
vec::store(m + i + 1 * IT::size, expr.load(i + 1 * IT::size));
vec::store(m + i + 2 * IT::size, expr.load(i + 2 * IT::size));
vec::store(m + i + 3 * IT::size, expr.load(i + 3 * IT::size));
}
} else {
for(; i + IT::size - 1 < size; i += IT::size){
vec::store(m + i, expr.load(i));
}
}
} else {
if(unroll_vectorized_loops && size - i > IT::size * 4){
for(; i + IT::size * 4 - 1 < size; i += IT::size * 4){
vec::storeu(m + i, expr.load(i));
vec::storeu(m + i + 1 * IT::size, expr.load(i + 1 * IT::size));
vec::storeu(m + i + 2 * IT::size, expr.load(i + 2 * IT::size));
vec::storeu(m + i + 3 * IT::size, expr.load(i + 3 * IT::size));
}
} else {
for(; i + IT::size - 1 < size; i += IT::size){
vec::storeu(m + i, expr.load(i));
}
}
}
}
//3. Remainder loop
//Finish the iterations in a non-vectorized fashion
for(; i < size; ++i){
m[i] = expr[i];
}
}
template<typename E, typename R, cpp_disable_if(is_temporary_expr<E>::value)>
static void add_evaluate(E&& expr, R&& result){
evaluate_only(expr);
for(std::size_t i = 0; i < etl::size(result); ++i){
result[i] += expr[i];
}
}
template<typename E, typename R, cpp_disable_if(is_temporary_expr<E>::value)>
static void sub_evaluate(E&& expr, R&& result){
evaluate_only(expr);
for(std::size_t i = 0; i < etl::size(result); ++i){
result[i] -= expr[i];
}
}
template<typename E, typename R, cpp_disable_if(is_temporary_expr<E>::value)>
static void mul_evaluate(E&& expr, R&& result){
evaluate_only(expr);
for(std::size_t i = 0; i < etl::size(result); ++i){
result[i] *= expr[i];
}
}
template<typename E, typename R, cpp_disable_if(is_temporary_expr<E>::value)>
static void div_evaluate(E&& expr, R&& result){
evaluate_only(expr);
for(std::size_t i = 0; i < etl::size(result); ++i){
result[i] /= expr[i];
}
}
template<typename E, typename R, cpp_disable_if(is_temporary_expr<E>::value)>
static void mod_evaluate(E&& expr, R&& result){
evaluate_only(expr);
for(std::size_t i = 0; i < etl::size(result); ++i){
result[i] %= expr[i];
}
}
//Note: In case of direct evaluation, the temporary_expr itself must
//not beevaluated by the static_visitor, otherwise, the result would
//be evaluated twice and a temporary would be allocated for nothing
template<typename E, typename R, cpp_enable_if(is_temporary_unary_expr<E>::value)>
static void assign_evaluate(E&& expr, R&& result){
apply_visitor<detail::temporary_allocator_static_visitor>(expr.a());
apply_visitor<detail::evaluator_static_visitor>(expr.a());
expr.direct_evaluate(result);
}
template<typename E, typename R, cpp_enable_if(is_temporary_binary_expr<E>::value)>
static void assign_evaluate(E&& expr, R&& result){
apply_visitor<detail::temporary_allocator_static_visitor>(expr.a());
apply_visitor<detail::temporary_allocator_static_visitor>(expr.b());
apply_visitor<detail::evaluator_static_visitor>(expr.a());
apply_visitor<detail::evaluator_static_visitor>(expr.b());
expr.direct_evaluate(result);
}
};
//Only containers of the same storage order can be assigned directly
//Generators can be assigned to everything
template<typename Expr, typename Result>
struct direct_assign_compatible : cpp::or_u<
decay_traits<Expr>::is_generator,
decay_traits<Expr>::storage_order == decay_traits<Result>::storage_order> {};
template<typename Expr, typename Result, cpp_enable_if(direct_assign_compatible<Expr, Result>::value)>
void assign_evaluate(Expr&& expr, Result&& result){
standard_evaluator<Expr, Result>::assign_evaluate(std::forward<Expr>(expr), std::forward<Result>(result));
}
template<typename Expr, typename Result, cpp_disable_if(direct_assign_compatible<Expr, Result>::value)>
void assign_evaluate(Expr&& expr, Result&& result){
standard_evaluator<Expr, Result>::assign_evaluate(transpose(expr), std::forward<Result>(result));
}
template<typename Expr, typename Result, cpp_enable_if(direct_assign_compatible<Expr, Result>::value)>
void add_evaluate(Expr&& expr, Result&& result){
standard_evaluator<Expr, Result>::add_evaluate(std::forward<Expr>(expr), std::forward<Result>(result));
}
template<typename Expr, typename Result, cpp_disable_if(direct_assign_compatible<Expr, Result>::value)>
void add_evaluate(Expr&& expr, Result&& result){
standard_evaluator<Expr, Result>::add_evaluate(transpose(expr), std::forward<Result>(result));
}
template<typename Expr, typename Result, cpp_enable_if(direct_assign_compatible<Expr, Result>::value)>
void sub_evaluate(Expr&& expr, Result&& result){
standard_evaluator<Expr, Result>::sub_evaluate(std::forward<Expr>(expr), std::forward<Result>(result));
}
template<typename Expr, typename Result, cpp_disable_if(direct_assign_compatible<Expr, Result>::value)>
void sub_evaluate(Expr&& expr, Result&& result){
standard_evaluator<Expr, Result>::sub_evaluate(transpose(expr), std::forward<Result>(result));
}
template<typename Expr, typename Result, cpp_enable_if(direct_assign_compatible<Expr, Result>::value)>
void mul_evaluate(Expr&& expr, Result&& result){
standard_evaluator<Expr, Result>::mul_evaluate(std::forward<Expr>(expr), std::forward<Result>(result));
}
template<typename Expr, typename Result, cpp_disable_if(direct_assign_compatible<Expr, Result>::value)>
void mul_evaluate(Expr&& expr, Result&& result){
standard_evaluator<Expr, Result>::mul_evaluate(transpose(expr), std::forward<Result>(result));
}
template<typename Expr, typename Result, cpp_enable_if(direct_assign_compatible<Expr, Result>::value)>
void div_evaluate(Expr&& expr, Result&& result){
standard_evaluator<Expr, Result>::div_evaluate(std::forward<Expr>(expr), std::forward<Result>(result));
}
template<typename Expr, typename Result, cpp_disable_if(direct_assign_compatible<Expr, Result>::value)>
void div_evaluate(Expr&& expr, Result&& result){
standard_evaluator<Expr, Result>::div_evaluate(transpose(expr), std::forward<Result>(result));
}
template<typename Expr, typename Result, cpp_enable_if(direct_assign_compatible<Expr, Result>::value)>
void mod_evaluate(Expr&& expr, Result&& result){
standard_evaluator<Expr, Result>::mod_evaluate(std::forward<Expr>(expr), std::forward<Result>(result));
}
template<typename Expr, typename Result, cpp_disable_if(direct_assign_compatible<Expr, Result>::value)>
void mod_evaluate(Expr&& expr, Result&& result){
standard_evaluator<Expr, Result>::mod_evaluate(transpose(expr), std::forward<Result>(result));
}
/*!
* \brief Force the internal evaluation of an expression
* \param expr The expression to force inner evaluation
*
* This function can be used when complex expressions are used
* lazily.
*/
template<typename Expr>
void force(Expr&& expr){
standard_evaluator<Expr, void>::evaluate_only(std::forward<Expr>(expr));
}
} //end of namespace etl
#endif
<commit_msg>Improve support for compound assignment<commit_after>//=======================================================================
// Copyright (c) 2014-2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#ifndef ETL_EVALUATOR_HPP
#define ETL_EVALUATOR_HPP
#include "traits_lite.hpp" //forward declaration of the traits
#include "visitor.hpp" //forward declaration of the traits
namespace etl {
namespace detail {
struct temporary_allocator_static_visitor : etl_visitor<temporary_allocator_static_visitor> {
template<typename E>
using enabled = cpp::bool_constant<decay_traits<E>::needs_temporary_visitor>;
using etl_visitor<temporary_allocator_static_visitor>::operator();
template <typename T, typename AExpr, typename Op, typename Forced>
void operator()(etl::temporary_unary_expr<T, AExpr, Op, Forced>& v) const {
v.allocate_temporary();
(*this)(v.a());
}
template <typename T, typename AExpr, typename BExpr, typename Op, typename Forced>
void operator()(etl::temporary_binary_expr<T, AExpr, BExpr, Op, Forced>& v) const {
v.allocate_temporary();
(*this)(v.a());
(*this)(v.b());
}
};
struct evaluator_static_visitor : etl_visitor<evaluator_static_visitor> {
template<typename E>
using enabled = cpp::bool_constant<decay_traits<E>::needs_evaluator_visitor>;
using etl_visitor<evaluator_static_visitor>::operator();
template <typename T, typename AExpr, typename Op, typename Forced>
void operator()(etl::temporary_unary_expr<T, AExpr, Op, Forced>& v) const {
(*this)(v.a());
v.evaluate();
}
template <typename T, typename AExpr, typename BExpr, typename Op, typename Forced>
void operator()(etl::temporary_binary_expr<T, AExpr, BExpr, Op, Forced>& v) const {
(*this)(v.a());
(*this)(v.b());
v.evaluate();
}
};
} //end of namespace detail
template<typename Expr, typename Result>
struct standard_evaluator {
template<typename E>
static void evaluate_only(E&& expr){
apply_visitor<detail::temporary_allocator_static_visitor>(expr);
apply_visitor<detail::evaluator_static_visitor>(expr);
}
template<typename E, typename R>
struct vectorized_assign : cpp::and_u<
vectorize_expr,
decay_traits<E>::vectorizable,
intrinsic_traits<value_t<R>>::vectorizable, intrinsic_traits<value_t<E>>::vectorizable,
std::is_same<typename intrinsic_traits<value_t<R>>::intrinsic_type, typename intrinsic_traits<value_t<E>>::intrinsic_type>::value> {};
template<typename E, typename R, cpp_enable_if(!vectorized_assign<E, R>::value && has_direct_access<R>::value && !is_temporary_expr<E>::value)>
static void assign_evaluate(E&& expr, R&& result){
evaluate_only(expr);
auto m = result.memory_start();
const std::size_t size = etl::size(result);
std::size_t iend = 0;
if(unroll_normal_loops){
iend = size & std::size_t(-4);
for(std::size_t i = 0; i < iend; i += 4){
m[i] = expr[i];
m[i+1] = expr[i+1];
m[i+2] = expr[i+2];
m[i+3] = expr[i+3];
}
}
for(std::size_t i = iend; i < size; ++i){
m[i] = expr[i];
}
}
template<typename E, typename R, cpp_enable_if(!vectorized_assign<E, R>::value && !has_direct_access<R>::value && !is_temporary_expr<E>::value)>
static void assign_evaluate(E&& expr, R&& result){
evaluate_only(expr);
const std::size_t size = etl::size(result);
for(std::size_t i = 0; i < size; ++i){
result[i] = expr[i];
}
}
template<typename E, typename R, cpp_enable_if(vectorized_assign<E, R>::value && !is_temporary_expr<E>::value)>
static void assign_evaluate(E&& expr, R&& result){
evaluate_only(expr);
using IT = intrinsic_traits<value_t<E>>;
auto m = result.memory_start();
const std::size_t size = etl::size(result);
std::size_t i = 0;
//1. Peel loop
constexpr const auto size_1 = sizeof(value_t<E>);
auto u_bytes = (reinterpret_cast<uintptr_t>(m) % IT::alignment);
if(u_bytes >= size_1 && u_bytes % size_1 == 0){
auto u_loads = std::min(u_bytes & -size_1, size);
for(; i < u_loads; ++i){
m[i] = expr[i];
}
}
//2. Vectorized loop
if(size - i >= IT::size){
if(reinterpret_cast<uintptr_t>(m + i) % IT::alignment == 0){
if(unroll_vectorized_loops && size - i > IT::size * 4){
for(; i + IT::size * 4 - 1 < size; i += IT::size * 4){
vec::store(m + i, expr.load(i));
vec::store(m + i + 1 * IT::size, expr.load(i + 1 * IT::size));
vec::store(m + i + 2 * IT::size, expr.load(i + 2 * IT::size));
vec::store(m + i + 3 * IT::size, expr.load(i + 3 * IT::size));
}
} else {
for(; i + IT::size - 1 < size; i += IT::size){
vec::store(m + i, expr.load(i));
}
}
} else {
if(unroll_vectorized_loops && size - i > IT::size * 4){
for(; i + IT::size * 4 - 1 < size; i += IT::size * 4){
vec::storeu(m + i, expr.load(i));
vec::storeu(m + i + 1 * IT::size, expr.load(i + 1 * IT::size));
vec::storeu(m + i + 2 * IT::size, expr.load(i + 2 * IT::size));
vec::storeu(m + i + 3 * IT::size, expr.load(i + 3 * IT::size));
}
} else {
for(; i + IT::size - 1 < size; i += IT::size){
vec::storeu(m + i, expr.load(i));
}
}
}
}
//3. Remainder loop
//Finish the iterations in a non-vectorized fashion
for(; i < size; ++i){
m[i] = expr[i];
}
}
template<typename E, typename R>
static void add_evaluate(E&& expr, R&& result){
evaluate_only(expr);
for(std::size_t i = 0; i < etl::size(result); ++i){
result[i] += expr[i];
}
}
template<typename E, typename R>
static void sub_evaluate(E&& expr, R&& result){
evaluate_only(expr);
for(std::size_t i = 0; i < etl::size(result); ++i){
result[i] -= expr[i];
}
}
template<typename E, typename R>
static void mul_evaluate(E&& expr, R&& result){
evaluate_only(expr);
for(std::size_t i = 0; i < etl::size(result); ++i){
result[i] *= expr[i];
}
}
template<typename E, typename R>
static void div_evaluate(E&& expr, R&& result){
evaluate_only(expr);
for(std::size_t i = 0; i < etl::size(result); ++i){
result[i] /= expr[i];
}
}
template<typename E, typename R>
static void mod_evaluate(E&& expr, R&& result){
evaluate_only(expr);
for(std::size_t i = 0; i < etl::size(result); ++i){
result[i] %= expr[i];
}
}
//Note: In case of direct evaluation, the temporary_expr itself must
//not beevaluated by the static_visitor, otherwise, the result would
//be evaluated twice and a temporary would be allocated for nothing
template<typename E, typename R, cpp_enable_if(is_temporary_unary_expr<E>::value)>
static void assign_evaluate(E&& expr, R&& result){
apply_visitor<detail::temporary_allocator_static_visitor>(expr.a());
apply_visitor<detail::evaluator_static_visitor>(expr.a());
expr.direct_evaluate(result);
}
template<typename E, typename R, cpp_enable_if(is_temporary_binary_expr<E>::value)>
static void assign_evaluate(E&& expr, R&& result){
apply_visitor<detail::temporary_allocator_static_visitor>(expr.a());
apply_visitor<detail::temporary_allocator_static_visitor>(expr.b());
apply_visitor<detail::evaluator_static_visitor>(expr.a());
apply_visitor<detail::evaluator_static_visitor>(expr.b());
expr.direct_evaluate(result);
}
};
//Only containers of the same storage order can be assigned directly
//Generators can be assigned to everything
template<typename Expr, typename Result>
struct direct_assign_compatible : cpp::or_u<
decay_traits<Expr>::is_generator,
decay_traits<Expr>::storage_order == decay_traits<Result>::storage_order> {};
template<typename Expr, typename Result, cpp_enable_if(direct_assign_compatible<Expr, Result>::value)>
void assign_evaluate(Expr&& expr, Result&& result){
standard_evaluator<Expr, Result>::assign_evaluate(std::forward<Expr>(expr), std::forward<Result>(result));
}
template<typename Expr, typename Result, cpp_disable_if(direct_assign_compatible<Expr, Result>::value)>
void assign_evaluate(Expr&& expr, Result&& result){
standard_evaluator<Expr, Result>::assign_evaluate(transpose(expr), std::forward<Result>(result));
}
template<typename Expr, typename Result, cpp_enable_if(direct_assign_compatible<Expr, Result>::value)>
void add_evaluate(Expr&& expr, Result&& result){
standard_evaluator<Expr, Result>::add_evaluate(std::forward<Expr>(expr), std::forward<Result>(result));
}
template<typename Expr, typename Result, cpp_disable_if(direct_assign_compatible<Expr, Result>::value)>
void add_evaluate(Expr&& expr, Result&& result){
standard_evaluator<Expr, Result>::add_evaluate(transpose(expr), std::forward<Result>(result));
}
template<typename Expr, typename Result, cpp_enable_if(direct_assign_compatible<Expr, Result>::value)>
void sub_evaluate(Expr&& expr, Result&& result){
standard_evaluator<Expr, Result>::sub_evaluate(std::forward<Expr>(expr), std::forward<Result>(result));
}
template<typename Expr, typename Result, cpp_disable_if(direct_assign_compatible<Expr, Result>::value)>
void sub_evaluate(Expr&& expr, Result&& result){
standard_evaluator<Expr, Result>::sub_evaluate(transpose(expr), std::forward<Result>(result));
}
template<typename Expr, typename Result, cpp_enable_if(direct_assign_compatible<Expr, Result>::value)>
void mul_evaluate(Expr&& expr, Result&& result){
standard_evaluator<Expr, Result>::mul_evaluate(std::forward<Expr>(expr), std::forward<Result>(result));
}
template<typename Expr, typename Result, cpp_disable_if(direct_assign_compatible<Expr, Result>::value)>
void mul_evaluate(Expr&& expr, Result&& result){
standard_evaluator<Expr, Result>::mul_evaluate(transpose(expr), std::forward<Result>(result));
}
template<typename Expr, typename Result, cpp_enable_if(direct_assign_compatible<Expr, Result>::value)>
void div_evaluate(Expr&& expr, Result&& result){
standard_evaluator<Expr, Result>::div_evaluate(std::forward<Expr>(expr), std::forward<Result>(result));
}
template<typename Expr, typename Result, cpp_disable_if(direct_assign_compatible<Expr, Result>::value)>
void div_evaluate(Expr&& expr, Result&& result){
standard_evaluator<Expr, Result>::div_evaluate(transpose(expr), std::forward<Result>(result));
}
template<typename Expr, typename Result, cpp_enable_if(direct_assign_compatible<Expr, Result>::value)>
void mod_evaluate(Expr&& expr, Result&& result){
standard_evaluator<Expr, Result>::mod_evaluate(std::forward<Expr>(expr), std::forward<Result>(result));
}
template<typename Expr, typename Result, cpp_disable_if(direct_assign_compatible<Expr, Result>::value)>
void mod_evaluate(Expr&& expr, Result&& result){
standard_evaluator<Expr, Result>::mod_evaluate(transpose(expr), std::forward<Result>(result));
}
/*!
* \brief Force the internal evaluation of an expression
* \param expr The expression to force inner evaluation
*
* This function can be used when complex expressions are used
* lazily.
*/
template<typename Expr>
void force(Expr&& expr){
standard_evaluator<Expr, void>::evaluate_only(std::forward<Expr>(expr));
}
} //end of namespace etl
#endif
<|endoftext|>
|
<commit_before>#ifndef HELLOBYEPROTO_HPP
#define HELLOBYEPROTO_HPP
#include "stateMachine.hpp"
template <class Identifier, class Packet> class HelloByeServerHello {
using SM = StateMachine<Identifier, Packet>;
private:
int clientCookie;
int serverCookie;
public:
HelloByeServerHello();
__attribute__((always_inline)) void fun(
typename SM::State &state, Packet *pkt, typename SM::FunIface &funIface);
static void run(typename SM::State &state, Packet *pkt, typename SM::FunIface &funIface) {
HelloByeServerHello *t = reinterpret_cast<HelloByeServerHello *>(state.stateData);
t->fun(state, pkt, funIface);
}
};
template <class Identifier, class Packet> class HelloByeServerBye {
using SM = StateMachine<Identifier, Packet>;
private:
int clientCookie;
int serverCookie;
public:
HelloByeServerBye();
__attribute__((always_inline)) void fun(
typename SM::State &state, Packet *pkt, typename SM::FunIface &funIface);
static void run(typename SM::State &state, Packet *pkt, typename SM::FunIface &funIface) {
HelloByeServerBye *t = reinterpret_cast<HelloByeServerBye *>(state.stateData);
t->fun(state, pkt, funIface);
}
};
template <class Identifier, class Packet> class HelloByeClientHello {
using SM = StateMachine<Identifier, Packet>;
friend class HelloByeServerBye<Identifier, Packet>;
private:
int clientCookie;
public:
HelloByeClientHello();
__attribute__((always_inline)) void fun(
typename SM::State &state, Packet *pkt, typename SM::FunIface &funIface);
static void run(typename SM::State &state, Packet *pkt, typename SM::FunIface &funIface) {
HelloByeClientHello *t = reinterpret_cast<HelloByeClientHello *>(state.stateData);
t->fun(state, pkt, funIface);
}
};
template <class Identifier, class Packet> class HelloByeClientBye {
using SM = StateMachine<Identifier, Packet>;
private:
int clientCookie;
int serverCookie;
public:
HelloByeClientBye();
HelloByeClientBye(const HelloByeClientHello<Identifier,Packet>& h);
__attribute__((always_inline)) void fun(
typename SM::State &state, Packet *pkt, typename SM::FunIface &funIface);
static void run(typename SM::State &state, Packet *pkt, typename SM::FunIface &funIface) {
HelloByeClientBye *t = reinterpret_cast<HelloByeClientBye *>(state.stateData);
t->fun(state, pkt, funIface);
}
};
#endif /* HELLOBYEPROTO_HPP */
<commit_msg>more HelloBye Header code<commit_after>#ifndef HELLOBYEPROTO_HPP
#define HELLOBYEPROTO_HPP
#include "common.hpp"
#include "stateMachine.hpp"
enum class HelloByeServer : StateID {
Hello,
Bye,
Terminate,
};
enum class HelloByeClient : StateID {
Hello,
Bye,
Terminate,
};
template <class Identifier, class Packet> class HelloByeServerHello;
template <class Identifier, class Packet> class HelloByeServerBye;
template <class Identifier, class Packet> class HelloByeClientHello;
template <class Identifier, class Packet> class HelloByeClientBye;
template <class Identifier, class Packet> class HelloByeServerHello {
using SM = StateMachine<Identifier, Packet>;
private:
int clientCookie;
int serverCookie;
public:
HelloByeServerHello();
__attribute__((always_inline)) void fun(
typename SM::State &state, Packet *pkt, typename SM::FunIface &funIface);
static void run(typename SM::State &state, Packet *pkt, typename SM::FunIface &funIface) {
HelloByeServerHello *t = reinterpret_cast<HelloByeServerHello *>(state.stateData);
t->fun(state, pkt, funIface);
// Finish transision to other state
if(state.state == HelloByeServer::Bye){
state.stateData = new HelloByeServerBye<Identifier,Packet>(t);
delete(t);
} else if(state.state == HelloByeServer::Terminate){
delete(t);
}
}
};
template <class Identifier, class Packet> class HelloByeServerBye {
using SM = StateMachine<Identifier, Packet>;
private:
int clientCookie;
int serverCookie;
public:
HelloByeServerBye(const HelloByeServerHello<Identifier, Packet> &in);
__attribute__((always_inline)) void fun(
typename SM::State &state, Packet *pkt, typename SM::FunIface &funIface);
static void run(typename SM::State &state, Packet *pkt, typename SM::FunIface &funIface) {
HelloByeServerBye *t = reinterpret_cast<HelloByeServerBye *>(state.stateData);
t->fun(state, pkt, funIface);
}
};
template <class Identifier, class Packet> class HelloByeClientHello {
using SM = StateMachine<Identifier, Packet>;
friend class HelloByeClientBye<Identifier, Packet>;
private:
int clientCookie;
public:
HelloByeClientHello();
__attribute__((always_inline)) void fun(
typename SM::State &state, Packet *pkt, typename SM::FunIface &funIface);
static void run(typename SM::State &state, Packet *pkt, typename SM::FunIface &funIface) {
HelloByeClientHello *t = reinterpret_cast<HelloByeClientHello *>(state.stateData);
t->fun(state, pkt, funIface);
}
};
template <class Identifier, class Packet> class HelloByeClientBye {
using SM = StateMachine<Identifier, Packet>;
private:
int clientCookie;
int serverCookie;
public:
HelloByeClientBye(const HelloByeClientHello<Identifier, Packet> &h);
__attribute__((always_inline)) void fun(
typename SM::State &state, Packet *pkt, typename SM::FunIface &funIface);
static void run(typename SM::State &state, Packet *pkt, typename SM::FunIface &funIface) {
HelloByeClientBye *t = reinterpret_cast<HelloByeClientBye *>(state.stateData);
t->fun(state, pkt, funIface);
}
};
#endif /* HELLOBYEPROTO_HPP */
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2009-2011, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
/// \file kernel/userver.hh
/// \brief Definition of the UServer class.
#ifndef KERNEL_USERVER_HH
# define KERNEL_USERVER_HH
# include <memory>
# include <sstream>
# include <libport/config.h>
# include <libport/attributes.hh>
# if LIBPORT_HAVE_WINDOWS_H
// Without this, windows.h may include winsock.h, which will conflict with
// winsock2.h when we will try to include it.
# define WIN32_LEAN_AND_MEAN
# endif
# include <libport/fwd.hh>
# include <libport/compiler.hh>
# include <libport/file-library.hh>
# include <libport/lockable.hh>
# include <libport/ufloat.h>
# include <libport/utime.hh>
# include <libport/pthread.h>
#include <sched/scheduler.hh>
# include <kernel/fwd.hh>
# include <kernel/utypes.hh>
# include <urbi/export.hh>
# include <urbi/object/object.hh>
# include <urbi/urbi-root.hh>
namespace kernel
{
/// Global variable for the server
extern URBI_SDK_API class UServer* urbiserver;
/// The current server.
UServer& server();
/// Convenience wrapper to get urbiserver's current runner.
runner::Runner& runner();
/// Convenience wrapper to get urbiserver's current interpreter.
runner::Interpreter& interpreter();
/// Convenience wrapper for Logger objects, to avoid having to
/// export the symbols of Interpreter.
URBI_SDK_API std::string current_function_name();
URBI_SDK_API std::string current_file();
URBI_SDK_API int current_line();
/// Convenience wrapper to get urbiserver's current scheduler.
sched::Scheduler& scheduler();
//! Handle all Urbi system processing.
/*! There must be one UServer defined in the program and it must be overloaded
to make it specific to the particular robot.
UServer is used to store the UConnection list and the UDevice list.
This object does all the internal processing of Urbi and handles the pool
of UCommand's.
*/
class URBI_SDK_API UServer
{
public:
UServer(UrbiRoot& urbi_root);
virtual ~UServer();
public:
//! Initialization of the server. Displays the header message & init stuff
/*! This function must be called once the server is operational and
* able to print messages. It is a requirement for Urbi compliance to print
* the header at start, so this function *must* be called. Beside, it also
* do initalization work for the devices and system variables.
*
* \param interactive whether the ghostconnection is interactive.
* FIXME: this interface is unpleasant, something
* nicer is needed.
*/
void initialize(bool interactive = false);
/// Accessors for interactive value bound to System.interactive,
// also define the behavior when receiving SIGINT.
bool interactive_get() const;
void interactive_set(bool);
/// Support a kernel and a user mode.
///
/// Exceptions may not be launched in user mode, they are hard
/// error. This is used to catch error when the system is
/// incomplete, say when an error occurs when loading urbi/urbi.u.
/// Therefore, "of course", defaults to mode_kernel.
enum mode_type
{
mode_kernel,
mode_user,
};
ATTRIBUTE_R(mode_type, mode);
public:
/// Process the jobs.
/// \return the time when should be called again.
libport::utime_t work();
/// Set the system.args list in Urbi.
void main(int argc, const char* argv[]);
//! Overload this function to return the running time of the server.
/*! The running time of the server must be in microseconds.
*/
virtual libport::utime_t getTime() const = 0;
/// Path to explore when looking for .u files.
libport::file_library search_path;
/// Return the full file name, handle paths.
/// Return \a f on failure.
virtual std::string find_file(const libport::path& path) const;
/// Load a file into the connection.
/// Returns UFAIL if anything goes wrong, USUCCESS otherwise.
virtual UErrorValue load_file(const std::string& file_name,
UConnection& dest);
/// Load \a fn in the ghostqueue.
UErrorValue load_init_file(const char* fn);
/// Same but calls init_error on errors.
void xload_init_file(const char* fn);
/// Save content to a file
/// This function must be redefined by the robot-specific server.
/// Returns UFAIL if anything goes wrong, USUCCESS otherwise.
virtual UErrorValue save_file(const std::string& filename,
const std::string& content) = 0;
//! Overload this function to specify how your system will reboot
virtual void reboot() = 0;
//! Overload this function to specify how your system will shutdown
virtual void shutdown();
//! Function called before work
/*! Redefine this virtual function if you need to do pre-processing before
the work function starts.
*/
virtual void beforeWork();
//! Function called after work
/*! Redefine this virtual function if you need to do post-processing
before the work function ends.
*/
virtual void afterWork();
/// Display a message on the robot console.
void display(const char*);
//! Accessor for lastTime_.
libport::utime_t lastTime();
//! Update lastTime_ to current time.
//! Update the server's time using the robot-specific implementation
/*! It is necessary to have an update of the server time to
increase the performance of successive calls to getTime.
It allows also to see a whole processing session (like the
processing of the command tree) as occuring AT the same time,
from the server's point of view.
*/
void updateTime();
/*----------------.
| Configuration. |
`----------------*/
ATTRIBUTE_RW(bool, opt_banner);
/*--------------.
| Connections. |
`--------------*/
public:
/// Add a new connection to the connection list.
/// Take ownership on c. Also perform some error testing on the connection
/// value and UError return code
/// \precondition c != 0
void connection_add(UConnection* c);
/// \returns A usual connection to stop dependencies.
/// (kernel/ghost-connection.hh is not public).
UConnection& ghost_connection_get();
/*--------------------.
| Scheduler, runner. |
`--------------------*/
public:
const sched::Scheduler& scheduler_get() const;
sched::Scheduler& scheduler_get();
runner::Runner& getCurrentRunner() const;
runner::Runner* getCurrentRunnerOpt() const;
boost::asio::io_service& get_io_service();
/// Wake up from main loop.
void wake_up();
/*--------------------------------------.
| Thread-safe asynchronous scheduling |
`---------------------------------------*/
public:
/// Schedule a call in a new job.
void schedule(urbi::object::rObject target, libport::Symbol method,
const urbi::object::objects_type& args =
urbi::object::objects_type());
/// Schedule callback in a new job.
void schedule(libport::Symbol method, boost::function0<void> callback);
/// Schedule callback in the shared asynchronous job handler.
void schedule_fast(boost::function0<void> callback);
private:
struct AsyncJob
{
AsyncJob(urbi::object::rObject t, libport::Symbol m,
const urbi::object::objects_type& a);
AsyncJob(boost::function0<void> callback, libport::Symbol m);
urbi::object::rObject target;
libport::Symbol method;
urbi::object::objects_type args;
boost::function0<void> callback;
bool synchronous;
};
std::vector<AsyncJob> async_jobs_;
libport::Lockable async_jobs_lock_;
void async_jobs_process_();
void schedule(const AsyncJob& j);
/* We use an always running job fast_async_jobs_job_ to handle all
* fast_async_jobs_ callback.
* When it has nothing to do, it sleeps by freezing
* fast_async_jobs_tag_. This tag is unfrozen by work() if
* fast_async_jobs_start_ is true (because tags are not thread-safe).
*/
std::vector<boost::function0<void> > fast_async_jobs_;
bool fast_async_jobs_start_; // must wake async jobs handler
object::rObject fast_async_jobs_tag_;
libport::Lockable fast_async_jobs_lock_;
sched::rJob fast_async_jobs_job_; // For the sake of consistency.
void fast_async_jobs_run_();
protected:
/// Overload this function to specify how your robot is displaying messages.
virtual void effectiveDisplay(const char* s) = 0;
private:
// Pointer to stop the header dependency.
sched::Scheduler* scheduler_;
private:
/// \{ Various parts of @c UServer::work.
/// Scan currently opened connections for deleting marked commands or
/// killall order
void work_handle_stopall_();
void work_test_cpuoverload_();
/// \}
public:
/// Stops all commands in all connections.
bool stopall;
/// True iff current thread is different from server thread Id.
bool isAnotherThread() const;
UrbiRoot& urbi_root_get();
void connection_remove(UConnection& connection);
private:
/// Store the time on the last call to updateTime().
libport::utime_t lastTime_;
/// List of active connections: includes one UGhostConnection.
// FIXME: This is meant to become a runner::Job and move out of this class.
/// A pointer to stop dependencies.
std::auto_ptr<kernel::ConnectionSet> connections_;
/// The ghost connection used for urbi.u, URBI.INI, etc.
// Does not need to be an auto_ptr, as it is stored in connections_
// which handles memory management.
UGhostConnection* ghost_;
/// Whether this server is in interactive mode.
bool interactive_;
/// Store the server thread Id.
pthread_t thread_id_;
/// Urbi SDK installation
UrbiRoot& urbi_root_;
/// Socket pair used to wake us up
std::pair<libport::Socket*, libport::Socket*> wake_up_pipe_;
/// Dead jobs from last sched cycle.
sched::jobs_type dead_jobs_;
};
}
// Disable debug traces until we find a better means to do it.
# define DEBUG(Msg) ((void) 0)
# include <kernel/userver.hxx>
#endif // !KERNEL_USERVER_HH
<commit_msg>comment changes.<commit_after>/*
* Copyright (C) 2009-2011, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
/// \file kernel/userver.hh
/// \brief Definition of the UServer class.
#ifndef KERNEL_USERVER_HH
# define KERNEL_USERVER_HH
# include <memory>
# include <sstream>
# include <libport/config.h>
# include <libport/attributes.hh>
# if LIBPORT_HAVE_WINDOWS_H
// Without this, windows.h may include winsock.h, which will conflict with
// winsock2.h when we will try to include it.
# define WIN32_LEAN_AND_MEAN
# endif
# include <libport/fwd.hh>
# include <libport/compiler.hh>
# include <libport/file-library.hh>
# include <libport/lockable.hh>
# include <libport/ufloat.h>
# include <libport/utime.hh>
# include <libport/pthread.h>
# include <sched/scheduler.hh>
# include <kernel/fwd.hh>
# include <kernel/utypes.hh>
# include <urbi/export.hh>
# include <urbi/object/object.hh>
# include <urbi/urbi-root.hh>
namespace kernel
{
/// Global variable for the server
extern URBI_SDK_API class UServer* urbiserver;
/// The current server.
UServer& server();
/// Convenience wrapper to get urbiserver's current runner.
runner::Runner& runner();
/// Convenience wrapper to get urbiserver's current interpreter.
runner::Interpreter& interpreter();
/// Convenience wrapper for Logger objects, to avoid having to
/// export the symbols of Interpreter.
URBI_SDK_API std::string current_function_name();
URBI_SDK_API std::string current_file();
URBI_SDK_API int current_line();
/// Convenience wrapper to get urbiserver's current scheduler.
sched::Scheduler& scheduler();
//! Handle all Urbi system processing.
/*! There must be one UServer defined in the program and it must be
overloaded to make it specific to the particular robot.
UServer is used to store the UConnection list.
This object does all the internal processing of Urbi.
*/
class URBI_SDK_API UServer
{
public:
UServer(UrbiRoot& urbi_root);
virtual ~UServer();
public:
//! Initialization of the server. Displays the header message & init stuff
/*! This function must be called once the server is operational and
* able to print messages. It is a requirement for Urbi compliance to print
* the header at start, so this function *must* be called. Beside, it also
* do initalization work for the devices and system variables.
*
* \param interactive whether the ghostconnection is interactive.
* FIXME: this interface is unpleasant, something
* nicer is needed.
*/
void initialize(bool interactive = false);
/// Accessors for interactive value bound to System.interactive,
// also define the behavior when receiving SIGINT.
bool interactive_get() const;
void interactive_set(bool);
/// Support a kernel and a user mode.
///
/// Exceptions may not be launched in user mode, they are hard
/// error. This is used to catch error when the system is
/// incomplete, say when an error occurs when loading urbi/urbi.u.
/// Therefore, "of course", defaults to mode_kernel.
enum mode_type
{
mode_kernel,
mode_user,
};
ATTRIBUTE_R(mode_type, mode);
public:
/// Process the jobs.
/// \return the time when should be called again.
libport::utime_t work();
/// Set the system.args list in Urbi.
void main(int argc, const char* argv[]);
//! Overload this function to return the running time of the server.
/*! The running time of the server must be in microseconds.
*/
virtual libport::utime_t getTime() const = 0;
/// Path to explore when looking for .u files.
libport::file_library search_path;
/// Return the full file name, handle paths.
/// Return \a f on failure.
virtual std::string find_file(const libport::path& path) const;
/// Load a file into the connection.
/// Returns UFAIL if anything goes wrong, USUCCESS otherwise.
virtual UErrorValue load_file(const std::string& file_name,
UConnection& dest);
/// Load \a fn in the ghostqueue.
UErrorValue load_init_file(const char* fn);
/// Same but calls init_error on errors.
void xload_init_file(const char* fn);
/// Save content to a file
/// This function must be redefined by the robot-specific server.
/// Returns UFAIL if anything goes wrong, USUCCESS otherwise.
virtual UErrorValue save_file(const std::string& filename,
const std::string& content) = 0;
//! Overload this function to specify how your system will reboot
virtual void reboot() = 0;
//! Overload this function to specify how your system will shutdown
virtual void shutdown();
//! Function called before work
/*! Redefine this virtual function if you need to do pre-processing before
the work function starts.
*/
virtual void beforeWork();
//! Function called after work
/*! Redefine this virtual function if you need to do post-processing
before the work function ends.
*/
virtual void afterWork();
/// Display a message on the robot console.
void display(const char*);
//! Accessor for lastTime_.
libport::utime_t lastTime();
//! Update lastTime_ to current time.
//! Update the server's time using the robot-specific implementation
/*! It is necessary to have an update of the server time to
increase the performance of successive calls to getTime.
It allows also to see a whole processing session (like the
processing of the command tree) as occuring AT the same time,
from the server's point of view.
*/
void updateTime();
/*----------------.
| Configuration. |
`----------------*/
ATTRIBUTE_RW(bool, opt_banner);
/*--------------.
| Connections. |
`--------------*/
public:
/// Add a new connection to the connection list.
/// Take ownership on c. Also perform some error testing on the connection
/// value and UError return code
/// \precondition c != 0
void connection_add(UConnection* c);
/// \returns A usual connection to stop dependencies.
/// (kernel/ghost-connection.hh is not public).
UConnection& ghost_connection_get();
/*--------------------.
| Scheduler, runner. |
`--------------------*/
public:
const sched::Scheduler& scheduler_get() const;
sched::Scheduler& scheduler_get();
runner::Runner& getCurrentRunner() const;
runner::Runner* getCurrentRunnerOpt() const;
boost::asio::io_service& get_io_service();
/// Wake up from main loop.
void wake_up();
/*--------------------------------------.
| Thread-safe asynchronous scheduling |
`---------------------------------------*/
public:
/// Schedule a call in a new job.
void schedule(urbi::object::rObject target, libport::Symbol method,
const urbi::object::objects_type& args =
urbi::object::objects_type());
/// Schedule callback in a new job.
void schedule(libport::Symbol method, boost::function0<void> callback);
/// Schedule callback in the shared asynchronous job handler.
void schedule_fast(boost::function0<void> callback);
private:
struct AsyncJob
{
AsyncJob(urbi::object::rObject t, libport::Symbol m,
const urbi::object::objects_type& a);
AsyncJob(boost::function0<void> callback, libport::Symbol m);
urbi::object::rObject target;
libport::Symbol method;
urbi::object::objects_type args;
boost::function0<void> callback;
bool synchronous;
};
std::vector<AsyncJob> async_jobs_;
libport::Lockable async_jobs_lock_;
void async_jobs_process_();
void schedule(const AsyncJob& j);
/* We use an always running job fast_async_jobs_job_ to handle all
* fast_async_jobs_ callback.
* When it has nothing to do, it sleeps by freezing
* fast_async_jobs_tag_. This tag is unfrozen by work() if
* fast_async_jobs_start_ is true (because tags are not thread-safe).
*/
std::vector<boost::function0<void> > fast_async_jobs_;
bool fast_async_jobs_start_; // must wake async jobs handler
object::rObject fast_async_jobs_tag_;
libport::Lockable fast_async_jobs_lock_;
sched::rJob fast_async_jobs_job_; // For the sake of consistency.
void fast_async_jobs_run_();
protected:
/// Overload this function to specify how your robot is displaying messages.
virtual void effectiveDisplay(const char* s) = 0;
private:
// Pointer to stop the header dependency.
sched::Scheduler* scheduler_;
private:
/// \{ Various parts of @c UServer::work.
/// Scan currently opened connections for deleting marked commands or
/// killall order
void work_handle_stopall_();
void work_test_cpuoverload_();
/// \}
public:
/// Stops all commands in all connections.
bool stopall;
/// True iff current thread is different from server thread Id.
bool isAnotherThread() const;
UrbiRoot& urbi_root_get();
void connection_remove(UConnection& connection);
private:
/// Store the time on the last call to updateTime().
libport::utime_t lastTime_;
/// List of active connections: includes one UGhostConnection.
// FIXME: This is meant to become a runner::Job and move out of this class.
/// A pointer to stop dependencies.
std::auto_ptr<kernel::ConnectionSet> connections_;
/// The ghost connection used for urbi.u, URBI.INI, etc.
// Does not need to be an auto_ptr, as it is stored in connections_
// which handles memory management.
UGhostConnection* ghost_;
/// Whether this server is in interactive mode.
bool interactive_;
/// Store the server thread Id.
pthread_t thread_id_;
/// Urbi SDK installation
UrbiRoot& urbi_root_;
/// Socket pair used to wake us up
std::pair<libport::Socket*, libport::Socket*> wake_up_pipe_;
/// Dead jobs from last sched cycle.
sched::jobs_type dead_jobs_;
};
}
// Disable debug traces until we find a better means to do it.
# define DEBUG(Msg) ((void) 0)
# include <kernel/userver.hxx>
#endif // !KERNEL_USERVER_HH
<|endoftext|>
|
<commit_before>#pragma once
#ifndef SCOPEEXIT_HPP
# define SCOPEEXIT_HPP
#include <utility>
/* This counts the number of args */
#define NARGS_SEQ(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
#define NARGS(...) NARGS_SEQ(__VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
/* This will let macros expand before concating them */
#define PRIMITIVE_CAT(x, y) x ## y
#define CAT(x, y) PRIMITIVE_CAT(x, y)
/* This will pop the last argument off */
#define POP_LAST(...) CAT(POP_LAST_, NARGS(__VA_ARGS__))(__VA_ARGS__)
#define POP_LAST_1(x1)
#define POP_LAST_2(x1, x2) x1
#define POP_LAST_3(x1, x2, x3) x1, x2
#define POP_LAST_4(x1, x2, x3, x4) x1, x2, x3
#define POP_LAST_5(x1, x2, x3, x4, x5) x1, x2, x3, x4
#define POP_LAST_6(x1, x2, x3, x4, x5, x6) x1, x2, x3, x4, x5
#define POP_LAST_7(x1, x2, x3, x4, x5, x6, x7) x1, x2, x3, x4, x5, x6
#define POP_LAST_8(x1, x2, x3, x4, x5, x6, x7, x8) x1, x2, x3, x4, x5, x6, x7
#define POP_LAST_9(x1, x2, x3, x4, x5, x6, x7, x8, x9) x1, x2, x3, x4, x5, x6, x7, x8
#define POP_LAST_10(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10) x1, x2, x3, x4, x5, x6, x7, x8, x9
/* This will return the last argument */
#define LAST(...) CAT(LAST_, NARGS(__VA_ARGS__))(__VA_ARGS__)
#define LAST_1(x1) x1
#define LAST_2(x1, x2) x2
#define LAST_3(x1, x2, x3) x3
#define LAST_4(x1, x2, x3, x4) x4
#define LAST_5(x1, x2, x3, x4, x5) x5
#define LAST_6(x1, x2, x3, x4, x5, x6) x6
#define LAST_7(x1, x2, x3, x4, x5, x6, x7) x7
#define LAST_8(x1, x2, x3, x4, x5, x6, x7, x8) x8
#define LAST_9(x1, x2, x3, x4, x5, x6, x7, x8, x9) x9
#define LAST_10(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10) x10
namespace detail
{
template <typename T>
class scope_exit
{
public:
explicit scope_exit(T&& f) : f_(::std::move(f))
{
static_assert(noexcept(f_()), "throwing functors are unsupported");
}
scope_exit(scope_exit&& other) : f_(::std::move(other.f_)) { }
~scope_exit() noexcept { f_(); }
private:
T f_;
};
class scope_exit_helper { };
template<typename T>
inline scope_exit<T> make_scope_exit(T&& f)
{
return scope_exit<T>(::std::forward<T>(f));
}
template<typename T>
inline scope_exit<T> operator+(scope_exit_helper&&, T&& f)
{
return scope_exit<T>(::std::forward<T>(f));
}
}
#define SCOPE_EXIT(...) auto const CAT(scope_exit_, __LINE__) \
(::detail::make_scope_exit([POP_LAST(__VA_ARGS__)]() mutable noexcept\
{ LAST(__VA_ARGS__); }))
#define SCOPE_EXIT_ auto const CAT(scope_exit_, __LINE__) = \
::detail::scope_exit_helper()+[&]() mutable noexcept
#define SCOPE_EXIT__(...) auto const CAT(scope_exit_, __LINE__) = \
::detail::scope_exit_helper()+[__VA_ARGS__]() mutable noexcept
#endif // SCOPEEXIT_HPP
<commit_msg>some fixes<commit_after>#pragma once
#ifndef SCOPEEXIT_HPP
# define SCOPEEXIT_HPP
#include <utility>
/* This counts the number of args */
#define NARGS_SEQ(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
#define NARGS(...) NARGS_SEQ(__VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
/* This will let macros expand before concating them */
#define PRIMITIVE_CAT(x, y) x ## y
#define CAT(x, y) PRIMITIVE_CAT(x, y)
/* This will pop the last argument off */
#define POP_LAST(...) CAT(POP_LAST_, NARGS(__VA_ARGS__))(__VA_ARGS__)
#define POP_LAST_1(x1)
#define POP_LAST_2(x1, x2) x1
#define POP_LAST_3(x1, x2, x3) x1, x2
#define POP_LAST_4(x1, x2, x3, x4) x1, x2, x3
#define POP_LAST_5(x1, x2, x3, x4, x5) x1, x2, x3, x4
#define POP_LAST_6(x1, x2, x3, x4, x5, x6) x1, x2, x3, x4, x5
#define POP_LAST_7(x1, x2, x3, x4, x5, x6, x7) x1, x2, x3, x4, x5, x6
#define POP_LAST_8(x1, x2, x3, x4, x5, x6, x7, x8) x1, x2, x3, x4, x5, x6, x7
#define POP_LAST_9(x1, x2, x3, x4, x5, x6, x7, x8, x9) x1, x2, x3, x4, x5, x6, x7, x8
#define POP_LAST_10(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10) x1, x2, x3, x4, x5, x6, x7, x8, x9
/* This will return the last argument */
#define LAST(...) CAT(LAST_, NARGS(__VA_ARGS__))(__VA_ARGS__)
#define LAST_1(x1) x1
#define LAST_2(x1, x2) x2
#define LAST_3(x1, x2, x3) x3
#define LAST_4(x1, x2, x3, x4) x4
#define LAST_5(x1, x2, x3, x4, x5) x5
#define LAST_6(x1, x2, x3, x4, x5, x6) x6
#define LAST_7(x1, x2, x3, x4, x5, x6, x7) x7
#define LAST_8(x1, x2, x3, x4, x5, x6, x7, x8) x8
#define LAST_9(x1, x2, x3, x4, x5, x6, x7, x8, x9) x9
#define LAST_10(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10) x10
namespace detail
{
template <typename T>
class scope_exit
{
public:
explicit scope_exit(T&& f) : f_(::std::forward<T>(f))
{
static_assert(noexcept(f_()), "throwing functors are unsupported");
}
scope_exit(scope_exit&& other) : f_(::std::move(other.f_)) { }
~scope_exit() noexcept { f_(); }
private:
T f_;
};
class scope_exit_helper { };
template<typename T>
inline scope_exit<T> make_scope_exit(T&& f)
{
return scope_exit<T>(::std::forward<T>(f));
}
template<typename T>
inline scope_exit<T> operator+(scope_exit_helper&&, T&& f)
{
return scope_exit<T>(::std::forward<T>(f));
}
}
#define SCOPE_EXIT(...) auto const CAT(scope_exit_, __LINE__) \
(::detail::make_scope_exit([POP_LAST(__VA_ARGS__)]() mutable noexcept\
{ LAST(__VA_ARGS__); }))
#define SCOPE_EXIT_ auto const CAT(scope_exit_, __LINE__) = \
::detail::scope_exit_helper()+[&]() mutable noexcept
#define SCOPE_EXIT__(...) auto const CAT(scope_exit_, __LINE__) = \
::detail::scope_exit_helper()+[__VA_ARGS__]() mutable noexcept
#endif // SCOPEEXIT_HPP
<|endoftext|>
|
<commit_before>#ifndef TOKEN_I_HH
#define TOKEN_I_HH
#ifndef TOKEN_HH
#error "Please include via parent file"
#endif
#include <utility>
#include "decl.hh"
#include "util.hh"
// Type mapping
template<Token::Type t, typename T>
T to_type() = delete;
template<>
std::string to_type<Token::Type::identifier>() = delete;
template<>
bool to_type<Token::Type::boolean>() = delete;
template<>
Number to_type<Token::Type::number>() = delete;
template<>
char to_type<Token::Type::character>() = delete;
template<>
std::string to_type<Token::Type::string>() = delete;
template<>
Token::Notation to_type<Token::Type::notation>() = delete;
// std::string -> Token::Type is ambigious
template<>
inline constexpr
Token::Type to_tag<Token::Type, Number>(){
return Token::Type::number;
}
template<>
inline constexpr
Token::Type to_tag<Token::Type, bool>(){
return Token::Type::boolean;
}
template<>
inline constexpr
Token::Type to_tag<Token::Type, char>(){
return Token::Type::character;
}
template<>
inline constexpr
Token::Type to_tag<Token::Type, Token::Notation>(){
return Token::Type::notation;
}
// Token definitions
inline
Token::~Token(){
using namespace std;
switch(type_){
case Type::identifier:
case Type::string:
str_.~string();
break;
case Type::number:
num_.~Number();
break;
case Type::uninitialized:
case Type::boolean:
case Type::character:
case Type::notation:
default:
break;
}
type_ = Type::uninitialized;
}
template<>
inline
std::string Token::get() const{
switch(type_){
case Type::identifier:
case Type::string:
return str_;
default:
UNEXP_CONVERSION("(no string token)", "string");
}
}
template<>
inline
Number Token::get() const{
if(type_ == Type::number)
return num_;
else
UNEXP_CONVERSION("(no number token)", "number");
}
template<>
inline
bool Token::get() const{
if(type_ == Type::boolean)
return b_;
else
UNEXP_CONVERSION("(no boolean token)", "boolean");
}
template<>
inline
char Token::get() const{
if(type_ == Type::character)
return c_;
else
UNEXP_CONVERSION("(no char token)", "char");
}
template<>
inline
Token::Notation Token::get() const{
if(type_ == Type::notation)
return not_;
else
UNEXP_CONVERSION("(no notation token)", "notation");
}
#endif // TOKEN_I_HH
<commit_msg>bitly cleanup<commit_after>#ifndef TOKEN_I_HH
#define TOKEN_I_HH
#ifndef TOKEN_HH
#error "Please include via parent file"
#endif
#include <utility>
#include "decl.hh"
#include "util.hh"
// Type mapping
template<Token::Type t, typename T>
T to_type() = delete;
template<>
std::string to_type<Token::Type::identifier>() = delete;
template<>
bool to_type<Token::Type::boolean>() = delete;
template<>
Number to_type<Token::Type::number>() = delete;
template<>
char to_type<Token::Type::character>() = delete;
template<>
std::string to_type<Token::Type::string>() = delete;
template<>
Token::Notation to_type<Token::Type::notation>() = delete;
// std::string -> Token::Type is ambigious
template<>
inline constexpr
Token::Type to_tag<Token::Type, std::string>() = delete;
template<>
inline constexpr
Token::Type to_tag<Token::Type, Number>(){
return Token::Type::number;
}
template<>
inline constexpr
Token::Type to_tag<Token::Type, bool>(){
return Token::Type::boolean;
}
template<>
inline constexpr
Token::Type to_tag<Token::Type, char>(){
return Token::Type::character;
}
template<>
inline constexpr
Token::Type to_tag<Token::Type, Token::Notation>(){
return Token::Type::notation;
}
// Token definitions
inline
Token::~Token(){
using namespace std;
switch(type_){
case Type::identifier:
case Type::string:
str_.~string();
break;
case Type::number:
num_.~Number();
break;
case Type::uninitialized:
case Type::boolean:
case Type::character:
case Type::notation:
default:
break;
}
type_ = Type::uninitialized;
}
template<>
inline
std::string Token::get() const{
switch(type_){
case Type::identifier:
case Type::string:
return str_;
default:
UNEXP_CONVERSION("(no string token)", "string");
}
}
template<>
inline
Number Token::get() const{
if(type_ == Type::number)
return num_;
else
UNEXP_CONVERSION("(no number token)", "number");
}
template<>
inline
bool Token::get() const{
if(type_ == Type::boolean)
return b_;
else
UNEXP_CONVERSION("(no boolean token)", "boolean");
}
template<>
inline
char Token::get() const{
if(type_ == Type::character)
return c_;
else
UNEXP_CONVERSION("(no char token)", "char");
}
template<>
inline
Token::Notation Token::get() const{
if(type_ == Type::notation)
return not_;
else
UNEXP_CONVERSION("(no notation token)", "notation");
}
#endif // TOKEN_I_HH
<|endoftext|>
|
<commit_before>/*
* DISTRHO Plugin Framework (DPF)
* Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com>
*
* Permission to use, copy, modify, and/or distribute this software for any purpose with
* or without fee is hereby granted, provided that the above copyright notice and this
* permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
* TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
* NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
* IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "DistrhoUIInternal.hpp"
#if DISTRHO_PLUGIN_WANT_DIRECT_ACCESS
# error DSSI UIs do not support direct access!
#endif
#include "../extra/d_sleep.hpp"
#include <lo/lo.h>
START_NAMESPACE_DISTRHO
// -----------------------------------------------------------------------
struct OscData {
lo_address addr;
const char* path;
lo_server server;
OscData()
: addr(nullptr),
path(nullptr),
server(nullptr) {}
void idle() const
{
if (server == nullptr)
return;
while (lo_server_recv_noblock(server, 0) != 0) {}
}
void send_configure(const char* const key, const char* const value) const
{
char targetPath[std::strlen(path)+11];
std::strcpy(targetPath, path);
std::strcat(targetPath, "/configure");
lo_send(addr, targetPath, "ss", key, value);
}
void send_control(const int32_t index, const float value) const
{
char targetPath[std::strlen(path)+9];
std::strcpy(targetPath, path);
std::strcat(targetPath, "/control");
lo_send(addr, targetPath, "if", index, value);
}
void send_midi(uchar data[4]) const
{
char targetPath[std::strlen(path)+6];
std::strcpy(targetPath, path);
std::strcat(targetPath, "/midi");
lo_send(addr, targetPath, "m", data);
}
void send_update(const char* const url) const
{
char targetPath[std::strlen(path)+8];
std::strcpy(targetPath, path);
std::strcat(targetPath, "/update");
lo_send(addr, targetPath, "s", url);
}
void send_exiting() const
{
char targetPath[std::strlen(path)+9];
std::strcpy(targetPath, path);
std::strcat(targetPath, "/exiting");
lo_send(addr, targetPath, "");
}
};
// -----------------------------------------------------------------------
class UIDssi
{
public:
UIDssi(const OscData& oscData, const char* const uiTitle)
: fUI(this, 0, nullptr, setParameterCallback, setStateCallback, sendNoteCallback, setSizeCallback),
fHostClosed(false),
fShowCalled(false),
fOscData(oscData)
{
fUI.setTitle(uiTitle);
}
~UIDssi()
{
if (fOscData.server != nullptr && ! fHostClosed)
fOscData.send_exiting();
}
void exec()
{
for (;;)
{
fOscData.idle();
if (! fUI.idle())
{
// host might not have called show yet
if (fShowCalled)
break;
}
else if (fHostClosed)
break;
d_msleep(30);
}
}
// -------------------------------------------------------------------
#if DISTRHO_PLUGIN_WANT_STATE
void dssiui_configure(const char* key, const char* value)
{
fUI.stateChanged(key, value);
}
#endif
void dssiui_control(ulong index, float value)
{
fUI.parameterChanged(index, value);
}
#if DISTRHO_PLUGIN_WANT_PROGRAMS
void dssiui_program(ulong bank, ulong program)
{
fUI.programChanged(bank * 128 + program);
}
#endif
void dssiui_show()
{
fShowCalled = true;
fUI.setVisible(true);
}
void dssiui_hide()
{
fUI.setVisible(false);
}
void dssiui_quit()
{
fHostClosed = true;
fUI.quit();
}
// -------------------------------------------------------------------
protected:
void setParameterValue(const uint32_t rindex, const float value)
{
if (fOscData.server == nullptr)
return;
fOscData.send_control(rindex, value);
}
void setState(const char* const key, const char* const value)
{
if (fOscData.server == nullptr)
return;
fOscData.send_configure(key, value);
}
void sendNote(const uint8_t channel, const uint8_t note, const uint8_t velocity)
{
if (fOscData.server == nullptr)
return;
if (channel > 0xF)
return;
uint8_t mdata[4] = { 0, channel, note, velocity };
mdata[1] += (velocity != 0) ? 0x90 : 0x80;
fOscData.send_midi(mdata);
}
void setSize(const uint width, const uint height)
{
fUI.setSize(width, height);
}
private:
UIExporter fUI;
bool fHostClosed;
bool fShowCalled;
const OscData& fOscData;
// -------------------------------------------------------------------
// Callbacks
#define uiPtr ((UIDssi*)ptr)
static void setParameterCallback(void* ptr, uint32_t rindex, float value)
{
uiPtr->setParameterValue(rindex, value);
}
static void setStateCallback(void* ptr, const char* key, const char* value)
{
uiPtr->setState(key, value);
}
static void sendNoteCallback(void* ptr, uint8_t channel, uint8_t note, uint8_t velocity)
{
uiPtr->sendNote(channel, note, velocity);
}
static void setSizeCallback(void* ptr, uint width, uint height)
{
uiPtr->setSize(width, height);
}
#undef uiPtr
};
// -----------------------------------------------------------------------
static OscData gOscData;
static const char* gUiTitle = nullptr;
static UIDssi* globalUI = nullptr;
static void initUiIfNeeded()
{
if (globalUI != nullptr)
return;
if (d_lastUiSampleRate == 0.0)
d_lastUiSampleRate = 44100.0;
globalUI = new UIDssi(gOscData, gUiTitle);
}
// -----------------------------------------------------------------------
int osc_debug_handler(const char* path, const char*, lo_arg**, int, lo_message, void*)
{
d_debug("osc_debug_handler(\"%s\")", path);
return 0;
#ifndef DEBUG
// unused
(void)path;
#endif
}
void osc_error_handler(int num, const char* msg, const char* path)
{
d_stderr("osc_error_handler(%i, \"%s\", \"%s\")", num, msg, path);
}
#if DISTRHO_PLUGIN_WANT_STATE
int osc_configure_handler(const char*, const char*, lo_arg** argv, int, lo_message, void*)
{
const char* const key = &argv[0]->s;
const char* const value = &argv[1]->s;
d_debug("osc_configure_handler(\"%s\", \"%s\")", key, value);
initUiIfNeeded();
globalUI->dssiui_configure(key, value);
return 0;
}
#endif
int osc_control_handler(const char*, const char*, lo_arg** argv, int, lo_message, void*)
{
const int32_t rindex = argv[0]->i;
const float value = argv[1]->f;
d_debug("osc_control_handler(%i, %f)", rindex, value);
int32_t index = rindex - DISTRHO_PLUGIN_NUM_INPUTS - DISTRHO_PLUGIN_NUM_OUTPUTS;
// latency
#if DISTRHO_PLUGIN_WANT_LATENCY
index -= 1;
#endif
if (index < 0)
return 0;
initUiIfNeeded();
globalUI->dssiui_control(index, value);
return 0;
}
#if DISTRHO_PLUGIN_WANT_PROGRAMS
int osc_program_handler(const char*, const char*, lo_arg** argv, int, lo_message, void*)
{
const int32_t bank = argv[0]->i;
const int32_t program = argv[1]->f;
d_debug("osc_program_handler(%i, %i)", bank, program);
initUiIfNeeded();
globalUI->dssiui_program(bank, program);
return 0;
}
#endif
int osc_sample_rate_handler(const char*, const char*, lo_arg** argv, int, lo_message, void*)
{
const int32_t sampleRate = argv[0]->i;
d_debug("osc_sample_rate_handler(%i)", sampleRate);
d_lastUiSampleRate = sampleRate;
return 0;
}
int osc_show_handler(const char*, const char*, lo_arg**, int, lo_message, void*)
{
d_debug("osc_show_handler()");
initUiIfNeeded();
globalUI->dssiui_show();
return 0;
}
int osc_hide_handler(const char*, const char*, lo_arg**, int, lo_message, void*)
{
d_debug("osc_hide_handler()");
if (globalUI != nullptr)
globalUI->dssiui_hide();
return 0;
}
int osc_quit_handler(const char*, const char*, lo_arg**, int, lo_message, void*)
{
d_debug("osc_quit_handler()");
if (globalUI != nullptr)
globalUI->dssiui_quit();
return 0;
}
END_NAMESPACE_DISTRHO
// -----------------------------------------------------------------------
int main(int argc, char* argv[])
{
USE_NAMESPACE_DISTRHO
// dummy test mode
if (argc == 1)
{
gUiTitle = "DSSI UI Test";
initUiIfNeeded();
globalUI->dssiui_show();
globalUI->exec();
delete globalUI;
globalUI = nullptr;
return 0;
}
if (argc != 5)
{
fprintf(stderr, "Usage: %s <osc-url> <plugin-dll> <plugin-label> <instance-name>\n", argv[0]);
return 1;
}
const char* oscUrl = argv[1];
const char* uiTitle = argv[4];
char* const oscHost = lo_url_get_hostname(oscUrl);
char* const oscPort = lo_url_get_port(oscUrl);
char* const oscPath = lo_url_get_path(oscUrl);
size_t oscPathSize = strlen(oscPath);
lo_address oscAddr = lo_address_new(oscHost, oscPort);
lo_server oscServer = lo_server_new_with_proto(nullptr, LO_UDP, osc_error_handler);
char* const oscServerPath = lo_server_get_url(oscServer);
char pluginPath[strlen(oscServerPath)+oscPathSize];
strcpy(pluginPath, oscServerPath);
strcat(pluginPath, oscPath+1);
#if DISTRHO_PLUGIN_WANT_STATE
char oscPathConfigure[oscPathSize+11];
strcpy(oscPathConfigure, oscPath);
strcat(oscPathConfigure, "/configure");
lo_server_add_method(oscServer, oscPathConfigure, "ss", osc_configure_handler, nullptr);
#endif
char oscPathControl[oscPathSize+9];
strcpy(oscPathControl, oscPath);
strcat(oscPathControl, "/control");
lo_server_add_method(oscServer, oscPathControl, "if", osc_control_handler, nullptr);
d_stdout("oscServerPath: \"%s\"", oscServerPath);
d_stdout("pluginPath: \"%s\"", pluginPath);
d_stdout("oscPathControl: \"%s\"", oscPathControl);
#if DISTRHO_PLUGIN_WANT_PROGRAMS
char oscPathProgram[oscPathSize+9];
strcpy(oscPathProgram, oscPath);
strcat(oscPathProgram, "/program");
lo_server_add_method(oscServer, oscPathProgram, "ii", osc_program_handler, nullptr);
#endif
char oscPathSampleRate[oscPathSize+13];
strcpy(oscPathSampleRate, oscPath);
strcat(oscPathSampleRate, "/sample-rate");
lo_server_add_method(oscServer, oscPathSampleRate, "i", osc_sample_rate_handler, nullptr);
char oscPathShow[oscPathSize+6];
strcpy(oscPathShow, oscPath);
strcat(oscPathShow, "/show");
lo_server_add_method(oscServer, oscPathShow, "", osc_show_handler, nullptr);
char oscPathHide[oscPathSize+6];
strcpy(oscPathHide, oscPath);
strcat(oscPathHide, "/hide");
lo_server_add_method(oscServer, oscPathHide, "", osc_hide_handler, nullptr);
char oscPathQuit[oscPathSize+6];
strcpy(oscPathQuit, oscPath);
strcat(oscPathQuit, "/quit");
lo_server_add_method(oscServer, oscPathQuit, "", osc_quit_handler, nullptr);
lo_server_add_method(oscServer, nullptr, nullptr, osc_debug_handler, nullptr);
gUiTitle = uiTitle;
gOscData.addr = oscAddr;
gOscData.path = oscPath;
gOscData.server = oscServer;
gOscData.send_update(pluginPath);
// wait for init
for (int i=0; i < 100; ++i)
{
lo_server_recv(oscServer);
if (d_lastUiSampleRate != 0.0 || globalUI != nullptr)
break;
d_msleep(50);
}
int ret = 1;
if (d_lastUiSampleRate != 0.0 || globalUI != nullptr)
{
initUiIfNeeded();
globalUI->exec();
delete globalUI;
globalUI = nullptr;
ret = 0;
}
#if DISTRHO_PLUGIN_WANT_STATE
lo_server_del_method(oscServer, oscPathConfigure, "ss");
#endif
lo_server_del_method(oscServer, oscPathControl, "if");
#if DISTRHO_PLUGIN_WANT_PROGRAMS
lo_server_del_method(oscServer, oscPathProgram, "ii");
#endif
lo_server_del_method(oscServer, oscPathSampleRate, "i");
lo_server_del_method(oscServer, oscPathShow, "");
lo_server_del_method(oscServer, oscPathHide, "");
lo_server_del_method(oscServer, oscPathQuit, "");
lo_server_del_method(oscServer, nullptr, nullptr);
std::free(oscServerPath);
std::free(oscHost);
std::free(oscPort);
std::free(oscPath);
lo_address_free(oscAddr);
lo_server_free(oscServer);
return ret;
}
<commit_msg>Revert DSSI UI auto-close fix, no longer needed<commit_after>/*
* DISTRHO Plugin Framework (DPF)
* Copyright (C) 2012-2014 Filipe Coelho <falktx@falktx.com>
*
* Permission to use, copy, modify, and/or distribute this software for any purpose with
* or without fee is hereby granted, provided that the above copyright notice and this
* permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
* TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
* NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
* IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "DistrhoUIInternal.hpp"
#if DISTRHO_PLUGIN_WANT_DIRECT_ACCESS
# error DSSI UIs do not support direct access!
#endif
#include "../extra/d_sleep.hpp"
#include <lo/lo.h>
START_NAMESPACE_DISTRHO
// -----------------------------------------------------------------------
struct OscData {
lo_address addr;
const char* path;
lo_server server;
OscData()
: addr(nullptr),
path(nullptr),
server(nullptr) {}
void idle() const
{
if (server == nullptr)
return;
while (lo_server_recv_noblock(server, 0) != 0) {}
}
void send_configure(const char* const key, const char* const value) const
{
char targetPath[std::strlen(path)+11];
std::strcpy(targetPath, path);
std::strcat(targetPath, "/configure");
lo_send(addr, targetPath, "ss", key, value);
}
void send_control(const int32_t index, const float value) const
{
char targetPath[std::strlen(path)+9];
std::strcpy(targetPath, path);
std::strcat(targetPath, "/control");
lo_send(addr, targetPath, "if", index, value);
}
void send_midi(uchar data[4]) const
{
char targetPath[std::strlen(path)+6];
std::strcpy(targetPath, path);
std::strcat(targetPath, "/midi");
lo_send(addr, targetPath, "m", data);
}
void send_update(const char* const url) const
{
char targetPath[std::strlen(path)+8];
std::strcpy(targetPath, path);
std::strcat(targetPath, "/update");
lo_send(addr, targetPath, "s", url);
}
void send_exiting() const
{
char targetPath[std::strlen(path)+9];
std::strcpy(targetPath, path);
std::strcat(targetPath, "/exiting");
lo_send(addr, targetPath, "");
}
};
// -----------------------------------------------------------------------
class UIDssi
{
public:
UIDssi(const OscData& oscData, const char* const uiTitle)
: fUI(this, 0, nullptr, setParameterCallback, setStateCallback, sendNoteCallback, setSizeCallback),
fHostClosed(false),
fOscData(oscData)
{
fUI.setTitle(uiTitle);
}
~UIDssi()
{
if (fOscData.server != nullptr && ! fHostClosed)
fOscData.send_exiting();
}
void exec()
{
for (;;)
{
fOscData.idle();
if (fHostClosed || ! fUI.idle())
break;
d_msleep(30);
}
}
// -------------------------------------------------------------------
#if DISTRHO_PLUGIN_WANT_STATE
void dssiui_configure(const char* key, const char* value)
{
fUI.stateChanged(key, value);
}
#endif
void dssiui_control(ulong index, float value)
{
fUI.parameterChanged(index, value);
}
#if DISTRHO_PLUGIN_WANT_PROGRAMS
void dssiui_program(ulong bank, ulong program)
{
fUI.programChanged(bank * 128 + program);
}
#endif
void dssiui_show()
{
fUI.setVisible(true);
}
void dssiui_hide()
{
fUI.setVisible(false);
}
void dssiui_quit()
{
fHostClosed = true;
fUI.quit();
}
// -------------------------------------------------------------------
protected:
void setParameterValue(const uint32_t rindex, const float value)
{
if (fOscData.server == nullptr)
return;
fOscData.send_control(rindex, value);
}
void setState(const char* const key, const char* const value)
{
if (fOscData.server == nullptr)
return;
fOscData.send_configure(key, value);
}
void sendNote(const uint8_t channel, const uint8_t note, const uint8_t velocity)
{
if (fOscData.server == nullptr)
return;
if (channel > 0xF)
return;
uint8_t mdata[4] = { 0, channel, note, velocity };
mdata[1] += (velocity != 0) ? 0x90 : 0x80;
fOscData.send_midi(mdata);
}
void setSize(const uint width, const uint height)
{
fUI.setSize(width, height);
}
private:
UIExporter fUI;
bool fHostClosed;
const OscData& fOscData;
// -------------------------------------------------------------------
// Callbacks
#define uiPtr ((UIDssi*)ptr)
static void setParameterCallback(void* ptr, uint32_t rindex, float value)
{
uiPtr->setParameterValue(rindex, value);
}
static void setStateCallback(void* ptr, const char* key, const char* value)
{
uiPtr->setState(key, value);
}
static void sendNoteCallback(void* ptr, uint8_t channel, uint8_t note, uint8_t velocity)
{
uiPtr->sendNote(channel, note, velocity);
}
static void setSizeCallback(void* ptr, uint width, uint height)
{
uiPtr->setSize(width, height);
}
#undef uiPtr
};
// -----------------------------------------------------------------------
static OscData gOscData;
static const char* gUiTitle = nullptr;
static UIDssi* globalUI = nullptr;
static void initUiIfNeeded()
{
if (globalUI != nullptr)
return;
if (d_lastUiSampleRate == 0.0)
d_lastUiSampleRate = 44100.0;
globalUI = new UIDssi(gOscData, gUiTitle);
}
// -----------------------------------------------------------------------
int osc_debug_handler(const char* path, const char*, lo_arg**, int, lo_message, void*)
{
d_debug("osc_debug_handler(\"%s\")", path);
return 0;
#ifndef DEBUG
// unused
(void)path;
#endif
}
void osc_error_handler(int num, const char* msg, const char* path)
{
d_stderr("osc_error_handler(%i, \"%s\", \"%s\")", num, msg, path);
}
#if DISTRHO_PLUGIN_WANT_STATE
int osc_configure_handler(const char*, const char*, lo_arg** argv, int, lo_message, void*)
{
const char* const key = &argv[0]->s;
const char* const value = &argv[1]->s;
d_debug("osc_configure_handler(\"%s\", \"%s\")", key, value);
initUiIfNeeded();
globalUI->dssiui_configure(key, value);
return 0;
}
#endif
int osc_control_handler(const char*, const char*, lo_arg** argv, int, lo_message, void*)
{
const int32_t rindex = argv[0]->i;
const float value = argv[1]->f;
d_debug("osc_control_handler(%i, %f)", rindex, value);
int32_t index = rindex - DISTRHO_PLUGIN_NUM_INPUTS - DISTRHO_PLUGIN_NUM_OUTPUTS;
// latency
#if DISTRHO_PLUGIN_WANT_LATENCY
index -= 1;
#endif
if (index < 0)
return 0;
initUiIfNeeded();
globalUI->dssiui_control(index, value);
return 0;
}
#if DISTRHO_PLUGIN_WANT_PROGRAMS
int osc_program_handler(const char*, const char*, lo_arg** argv, int, lo_message, void*)
{
const int32_t bank = argv[0]->i;
const int32_t program = argv[1]->f;
d_debug("osc_program_handler(%i, %i)", bank, program);
initUiIfNeeded();
globalUI->dssiui_program(bank, program);
return 0;
}
#endif
int osc_sample_rate_handler(const char*, const char*, lo_arg** argv, int, lo_message, void*)
{
const int32_t sampleRate = argv[0]->i;
d_debug("osc_sample_rate_handler(%i)", sampleRate);
d_lastUiSampleRate = sampleRate;
return 0;
}
int osc_show_handler(const char*, const char*, lo_arg**, int, lo_message, void*)
{
d_debug("osc_show_handler()");
initUiIfNeeded();
globalUI->dssiui_show();
return 0;
}
int osc_hide_handler(const char*, const char*, lo_arg**, int, lo_message, void*)
{
d_debug("osc_hide_handler()");
if (globalUI != nullptr)
globalUI->dssiui_hide();
return 0;
}
int osc_quit_handler(const char*, const char*, lo_arg**, int, lo_message, void*)
{
d_debug("osc_quit_handler()");
if (globalUI != nullptr)
globalUI->dssiui_quit();
return 0;
}
END_NAMESPACE_DISTRHO
// -----------------------------------------------------------------------
int main(int argc, char* argv[])
{
USE_NAMESPACE_DISTRHO
// dummy test mode
if (argc == 1)
{
gUiTitle = "DSSI UI Test";
initUiIfNeeded();
globalUI->dssiui_show();
globalUI->exec();
delete globalUI;
globalUI = nullptr;
return 0;
}
if (argc != 5)
{
fprintf(stderr, "Usage: %s <osc-url> <plugin-dll> <plugin-label> <instance-name>\n", argv[0]);
return 1;
}
const char* oscUrl = argv[1];
const char* uiTitle = argv[4];
char* const oscHost = lo_url_get_hostname(oscUrl);
char* const oscPort = lo_url_get_port(oscUrl);
char* const oscPath = lo_url_get_path(oscUrl);
size_t oscPathSize = strlen(oscPath);
lo_address oscAddr = lo_address_new(oscHost, oscPort);
lo_server oscServer = lo_server_new_with_proto(nullptr, LO_UDP, osc_error_handler);
char* const oscServerPath = lo_server_get_url(oscServer);
char pluginPath[strlen(oscServerPath)+oscPathSize];
strcpy(pluginPath, oscServerPath);
strcat(pluginPath, oscPath+1);
#if DISTRHO_PLUGIN_WANT_STATE
char oscPathConfigure[oscPathSize+11];
strcpy(oscPathConfigure, oscPath);
strcat(oscPathConfigure, "/configure");
lo_server_add_method(oscServer, oscPathConfigure, "ss", osc_configure_handler, nullptr);
#endif
char oscPathControl[oscPathSize+9];
strcpy(oscPathControl, oscPath);
strcat(oscPathControl, "/control");
lo_server_add_method(oscServer, oscPathControl, "if", osc_control_handler, nullptr);
d_stdout("oscServerPath: \"%s\"", oscServerPath);
d_stdout("pluginPath: \"%s\"", pluginPath);
d_stdout("oscPathControl: \"%s\"", oscPathControl);
#if DISTRHO_PLUGIN_WANT_PROGRAMS
char oscPathProgram[oscPathSize+9];
strcpy(oscPathProgram, oscPath);
strcat(oscPathProgram, "/program");
lo_server_add_method(oscServer, oscPathProgram, "ii", osc_program_handler, nullptr);
#endif
char oscPathSampleRate[oscPathSize+13];
strcpy(oscPathSampleRate, oscPath);
strcat(oscPathSampleRate, "/sample-rate");
lo_server_add_method(oscServer, oscPathSampleRate, "i", osc_sample_rate_handler, nullptr);
char oscPathShow[oscPathSize+6];
strcpy(oscPathShow, oscPath);
strcat(oscPathShow, "/show");
lo_server_add_method(oscServer, oscPathShow, "", osc_show_handler, nullptr);
char oscPathHide[oscPathSize+6];
strcpy(oscPathHide, oscPath);
strcat(oscPathHide, "/hide");
lo_server_add_method(oscServer, oscPathHide, "", osc_hide_handler, nullptr);
char oscPathQuit[oscPathSize+6];
strcpy(oscPathQuit, oscPath);
strcat(oscPathQuit, "/quit");
lo_server_add_method(oscServer, oscPathQuit, "", osc_quit_handler, nullptr);
lo_server_add_method(oscServer, nullptr, nullptr, osc_debug_handler, nullptr);
gUiTitle = uiTitle;
gOscData.addr = oscAddr;
gOscData.path = oscPath;
gOscData.server = oscServer;
gOscData.send_update(pluginPath);
// wait for init
for (int i=0; i < 100; ++i)
{
lo_server_recv(oscServer);
if (d_lastUiSampleRate != 0.0 || globalUI != nullptr)
break;
d_msleep(50);
}
int ret = 1;
if (d_lastUiSampleRate != 0.0 || globalUI != nullptr)
{
initUiIfNeeded();
globalUI->exec();
delete globalUI;
globalUI = nullptr;
ret = 0;
}
#if DISTRHO_PLUGIN_WANT_STATE
lo_server_del_method(oscServer, oscPathConfigure, "ss");
#endif
lo_server_del_method(oscServer, oscPathControl, "if");
#if DISTRHO_PLUGIN_WANT_PROGRAMS
lo_server_del_method(oscServer, oscPathProgram, "ii");
#endif
lo_server_del_method(oscServer, oscPathSampleRate, "i");
lo_server_del_method(oscServer, oscPathShow, "");
lo_server_del_method(oscServer, oscPathHide, "");
lo_server_del_method(oscServer, oscPathQuit, "");
lo_server_del_method(oscServer, nullptr, nullptr);
std::free(oscServerPath);
std::free(oscHost);
std::free(oscPort);
std::free(oscPath);
lo_address_free(oscAddr);
lo_server_free(oscServer);
return ret;
}
<|endoftext|>
|
<commit_before>/*
* Filter.hh
*
* Copyright 2001, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
* Copyright 2001, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_FILTER_HH
#define _LOG4CPP_FILTER_HH
#include "log4cpp/LoggingEvent.hh"
namespace log4cpp {
class Filter {
public:
typedef enum { DENY = -1,
NEUTRAL = 0,
ACCEPT = 1
} Decision;
Filter();
virtual ~Filter();
virtual void setChainedFilter(Filter* filter);
virtual Filter* getChainedFilter();
virtual Filter* getEndOfChain();
virtual void appendChainedFilter(Filter* filter);
virtual Decision decide(const LoggingEvent& event) = 0;
protected:
virtual Decision _decide(const LoggingEvent& event) = 0;
private:
Filter* _chainedFilter;
};
}
#endif // _LOG4CPP_FILTER_HH
<commit_msg>Added DoxyGen comments.<commit_after>/*
* Filter.hh
*
* Copyright 2001, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
* Copyright 2001, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_FILTER_HH
#define _LOG4CPP_FILTER_HH
#include "log4cpp/LoggingEvent.hh"
namespace log4cpp {
/**
Users should extend this class to implement customized logging
event filtering. Note that {@link log4cpp::Category} and {@link
log4cpp::Appender} have built-in filtering rules. It is suggested
that you first use and understand the built-in rules before rushing
to write your own custom filters.
<p>This abstract class assumes and also imposes that filters be
organized in a linear chain. The {@link #decide
decide(LoggingEvent)} method of each filter is called sequentially,
in the order of their addition to the chain.
<p>The {@link #decide decide(LoggingEvent)} method must return a
Decision value, either DENY, NEUTRAL or ACCCEPT.
<p>If the value DENY is returned, then the log event is
dropped immediately without consulting with the remaining
filters.
<p>If the value NEUTRAL is returned, then the next filter
in the chain is consulted. If there are no more filters in the
chain, then the log event is logged. Thus, in the presence of no
filters, the default behaviour is to log all logging events.
<p>If the value ACCEPT is returned, then the log
event is logged without consulting the remaining filters.
<p>The philosophy of log4j filters is largely inspired from the
Linux ipchains.
**/
class Filter {
public:
typedef enum { DENY = -1,
NEUTRAL = 0,
ACCEPT = 1
} Decision;
/**
* Default Constructor for Filter
**/
Filter();
/**
* Destructor for Filter
**/
virtual ~Filter();
/**
* Set the next Filter in the Filter chain
* @param filter The filter to chain
**/
virtual void setChainedFilter(Filter* filter);
/**
* Get the next Filter in the Filter chain
* @return The next Filter or NULL if the current filter is the last
* in the chain
**/
virtual Filter* getChainedFilter();
/**
* Get the last Filter in the Filter chain
* @return The last Filter in the Filter chain
**/
virtual Filter* getEndOfChain();
/**
* Add a Filter to the end of the Filter chain. Convience method for
* getEndOfChain()->setChainedFilter(filter).
* @param filter The filter to add to the end of the chain.
**/
virtual void appendChainedFilter(Filter* filter);
/**
* Decide whether to accept or deny a LoggingEvent. This method will
* walk the entire chain until a non neutral decision has been made
* or the end of the chain has been reached.
* @param event The LoggingEvent to decide on.
* @return The Decision
**/
virtual Decision decide(const LoggingEvent& event) = 0;
protected:
/**
* Decide whether <b>this</b> Filter accepts or denies the given
* LoggingEvent. Actual implementation of Filter should override this
* method and not <code>decide(LoggingEvent&)</code>.
* @param event The LoggingEvent to decide on.
* @return The Decision
**/
virtual Decision _decide(const LoggingEvent& event) = 0;
private:
Filter* _chainedFilter;
};
}
#endif // _LOG4CPP_FILTER_HH
<|endoftext|>
|
<commit_before>/* nobleNote, a note taking application
* Copyright (C) 2012 Christian Metscher <hakaishi@web.de>,
Fabian Deuchler <Taiko000@gmail.com>
* 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.
* nobleNote is licensed under the MIT, see `http://copyfree.org/licenses/mit/license.txt'.
*/
#include "backup.h"
#include "htmlnotereader.h"
#include "abstractnotereader.h"
#include <QDirIterator>
#include <QMessageBox>
#include <QSettings>
#include <QtConcurrentMap>
#include <QAbstractItemModel>
Backup::Backup(QWidget *parent): QDialog(parent){
setupUi(this);
splitter = new QSplitter(groupBox);
gridLayout_2->addWidget(splitter);
treeWidget = new QTreeWidget(splitter);
treeWidget->setAlternatingRowColors(true);
treeWidget->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);
treeWidget->setSortingEnabled(true);
treeWidget->setHeaderLabel(tr("Backups of deleted notes"));
treeWidget->setSelectionMode(QAbstractItemView::MultiSelection);
treeWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
frame = new QFrame(splitter);
gridLayout3 = new QGridLayout(frame);
label = new QLabel(frame);
label->setText(tr("Preview of the selected backup"));
gridLayout3->addWidget(label, 0, 0, 1, 1);
textEdit = new QTextEdit(this);
textEdit->setDisabled(frame);
gridLayout3->addWidget(textEdit, 1, 0, 1, 1);
document = new QTextDocument(this);
textEdit->setDocument(document);
setupTreeData();
deleteOldButton = new QPushButton(tr("&Delete all old backups and file entries"),this);
buttonBox->addButton(deleteOldButton ,QDialogButtonBox::ActionRole);
connect(treeWidget, SIGNAL(itemSelectionChanged()), this, SLOT(showPreview()));
connect(this, SIGNAL(accepted()), this, SLOT(restoreBackup()));
connect(deleteOldButton, SIGNAL(clicked(bool)), this, SLOT(deleteOldBackupsAndFileEntries()));
}
void Backup::setupTreeData()
{
treeWidget->clear(); //if there already is any data
//get backup uuids
QDir backupDir(QSettings().value("backupDirPath").toString());
QList<QFileInfo> backupList = backupDir.entryInfoList(QDir::Files, QDir::Name);
QStringList backupUuids;
foreach(QFileInfo backup, backupList)
backupUuids << "{" + backup.fileName() + "}";
//get note files
QDirIterator itFiles(QSettings().value("rootPath").toString(),
QDirIterator::Subdirectories);
QStringList noteFiles;
while(itFiles.hasNext()){
QString filePath = itFiles.next();
if(itFiles.fileInfo().isFile())
noteFiles << filePath;
}
QStringList noteUuids; //get note uuids
foreach(QString note, noteFiles)
noteUuids << getFileData(note).first();
foreach(QString uuid, noteUuids)
if(backupUuids.contains(uuid))
backupUuids.removeOne(uuid);
if(backupUuids.isEmpty())
return;
QHash<QString,QStringList> backupHash;
foreach(QString str, backupUuids)
{
str.remove("{");
str.remove("}");
QStringList data = getFileData(QSettings().value("backupDirPath").toString()
+ "/" + str);
QString uuid = data.takeFirst();
backupHash.insert(uuid, data);
}
foreach(QString key, backupHash.keys())
{
QTreeWidgetItem *item = new QTreeWidgetItem(treeWidget);
item->setText(0,backupHash[key].first());
item->setData(0,Qt::UserRole,backupHash[key]);
}
}
QStringList Backup::getFileData(const QString &file)
{
AbstractNoteReader *reader = new HtmlNoteReader(file,document);
QStringList list;
QString uuid = reader->uuid();
list << uuid << reader->title() << QFileInfo(file).absoluteFilePath() << document->toHtml();
return list;
}
void Backup::showPreview()
{
//TODO:Even with no backup a preview is shown...
if(treeWidget->selectedItems().isEmpty())
return;
QStringList data = treeWidget->selectedItems().first()->data(0,Qt::UserRole).toStringList();
if(data.isEmpty())
return;
textEdit->setText(data.last());
}
void Backup::restoreBackup()
{
//TODO: enable restore and deletion for multiple backups
/* if(!treeWidget->selectionModel()->currentIndex().isValid())
return;
if(treeWidget->selectionModel()->currentIndex().data(Qt::UserRole).toStringList().isEmpty())
return;
QStringList dataList = treeWidget->selectionModel()->currentIndex().data(Qt::UserRole).toStringList();
QString title = dataList.takeFirst();
if(!QFile(dataList.first()).exists())
return;
else
{
if(!QDir(QSettings().value("rootPath").toString()+"/restored notes").exists())
QDir().mkpath(QSettings().value("rootPath").toString()+"/restored notes");
QFile(dataList.first()).copy(QSettings().value("rootPath").toString()+"/restored notes/"+title);
}*/
}
void Backup::getNoteUuidList(){
QFutureIterator<QUuid> it(future1->future());
while(it.hasNext())
notesUuids << it.next();
}
void Backup::deleteOldBackupsAndFileEntries(){
notesUuids.clear(); //make sure that it's empty
//searching for existing Notes
QDirIterator itFiles(QSettings().value("rootPath").toString(),
QDirIterator::Subdirectories);
QStringList noteFiles;
while(itFiles.hasNext()){
QString filePath = itFiles.next();
if(itFiles.fileInfo().isFile())
noteFiles << filePath;
}
future1 = new QFutureWatcher<QUuid>(this);
QUuid (*uuidPtr)(QString) = & HtmlNoteReader::uuid; // function pointer, because uuid method is overloaded
future1->setFuture(QtConcurrent::mapped(noteFiles, uuidPtr));
indexDialog = new QProgressDialog(this);
indexDialog->setLabelText(QString(tr("Indexing notes...")));
QObject::connect(future1, SIGNAL(finished()), this, SLOT(getNoteUuidList()));
QObject::connect(future1, SIGNAL(finished()), this, SLOT(progressChanges()));
QObject::connect(future1, SIGNAL(finished()), indexDialog, SLOT(reset()));
QObject::connect(indexDialog, SIGNAL(canceled()), future1, SLOT(cancel()));
QObject::connect(future1, SIGNAL(progressRangeChanged(int,int)),
indexDialog, SLOT(setRange(int,int)));
QObject::connect(future1, SIGNAL(progressValueChanged(int)), indexDialog,
SLOT(setValue(int)));
indexDialog->exec();
}
void actualRemoval(const QString& backupAndUuid){
if(!backupAndUuid.contains("Notes/"))
QFile::remove(backupAndUuid);
else
QSettings().remove(backupAndUuid);
}
void Backup::progressChanges(){
//get backup files
QStringList backups;
QDir backupDir(QSettings().value("backupDirPath").toString());
QList<QFileInfo> backupList = backupDir.entryInfoList(QDir::Files, QDir::Name);
foreach(QFileInfo backup, backupList)
backups << backup.absoluteFilePath();
//add QSettings Uuids to the backups
QStringList backupsAndUuids = backups + QSettings().allKeys().filter("Notes/");
//We only need the redundant backups and Uuids
foreach(QString str, backupsAndUuids){
if(!str.contains("Notes/") && notesUuids.contains(QFileInfo(str).fileName()))
backupsAndUuids.removeOne(str);
if(str.contains("Notes/")){
QString settings = str;
settings.remove("Notes/");
settings.remove("_size");
settings.remove("_cursor_position");
if(notesUuids.contains(settings))
backupsAndUuids.removeOne(str);
}
}
QString redundantBackupList;
foreach(QString str, backupsAndUuids)
if(!str.contains("Notes/"))
redundantBackupList += (str+"\n");
if(backupsAndUuids.isEmpty()){
QMessageBox::information(this, tr("No redundant data!"), tr("no redundant"
" Everything is clean! No redundant data!"));
return;
}
else{
if(QMessageBox::warning(this,tr("Deleting backups and file entries"),
tr("Do you really want to delete the backups and entries for the "
"following files?\n\n%1\nYou won't be able to restore them!").arg(
redundantBackupList),
QMessageBox::Yes | QMessageBox::Abort) != QMessageBox::Yes)
return;
}
progressDialog = new QProgressDialog(this);
progressDialog->setLabelText(QString(tr("Progressing files...")));
future2 = new QFutureWatcher<void>(this);
future2->setFuture(QtConcurrent::map(backupsAndUuids, actualRemoval));
QObject::connect(future2, SIGNAL(finished()), progressDialog, SLOT(reset()));
QObject::connect(future2, SIGNAL(finished()), this, SLOT(setupTreeData()));
QObject::connect(progressDialog, SIGNAL(canceled()), future2, SLOT(cancel()));
QObject::connect(future2, SIGNAL(progressRangeChanged(int,int)), progressDialog,
SLOT(setRange(int,int)));
QObject::connect(future2, SIGNAL(progressValueChanged(int)), progressDialog,
SLOT(setValue(int)));
progressDialog->exec();
}
<commit_msg>minor fix<commit_after>/* nobleNote, a note taking application
* Copyright (C) 2012 Christian Metscher <hakaishi@web.de>,
Fabian Deuchler <Taiko000@gmail.com>
* 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.
* nobleNote is licensed under the MIT, see `http://copyfree.org/licenses/mit/license.txt'.
*/
#include "backup.h"
#include "htmlnotereader.h"
#include "abstractnotereader.h"
#include <QDirIterator>
#include <QMessageBox>
#include <QSettings>
#include <QtConcurrentMap>
#include <QAbstractItemModel>
Backup::Backup(QWidget *parent): QDialog(parent){
setupUi(this);
splitter = new QSplitter(groupBox);
gridLayout_2->addWidget(splitter);
treeWidget = new QTreeWidget(splitter);
treeWidget->setAlternatingRowColors(true);
treeWidget->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);
treeWidget->setSortingEnabled(true);
treeWidget->setHeaderLabel(tr("Backups of deleted notes"));
treeWidget->setSelectionMode(QAbstractItemView::MultiSelection);
treeWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
frame = new QFrame(splitter);
gridLayout3 = new QGridLayout(frame);
label = new QLabel(frame);
label->setText(tr("Preview of the selected backup"));
gridLayout3->addWidget(label, 0, 0, 1, 1);
textEdit = new QTextEdit(this);
textEdit->setDisabled(frame);
gridLayout3->addWidget(textEdit, 1, 0, 1, 1);
document = new QTextDocument(this);
textEdit->setDocument(document);
setupTreeData();
deleteOldButton = new QPushButton(tr("&Delete all old backups and file entries"),this);
buttonBox->addButton(deleteOldButton ,QDialogButtonBox::ActionRole);
connect(treeWidget, SIGNAL(itemSelectionChanged()), this, SLOT(showPreview()));
connect(this, SIGNAL(accepted()), this, SLOT(restoreBackup()));
connect(deleteOldButton, SIGNAL(clicked(bool)), this, SLOT(deleteOldBackupsAndFileEntries()));
}
void Backup::setupTreeData()
{
treeWidget->clear(); //if there already is any data
//get backup uuids
QDir backupDir(QSettings().value("backupDirPath").toString());
QList<QFileInfo> backupList = backupDir.entryInfoList(QDir::Files, QDir::Name);
QStringList backupUuids;
foreach(QFileInfo backup, backupList)
backupUuids << "{" + backup.fileName() + "}";
//get note files
QDirIterator itFiles(QSettings().value("rootPath").toString(),
QDirIterator::Subdirectories);
QStringList noteFiles;
while(itFiles.hasNext()){
QString filePath = itFiles.next();
if(itFiles.fileInfo().isFile())
noteFiles << filePath;
}
QStringList noteUuids; //get note uuids
foreach(QString note, noteFiles)
noteUuids << getFileData(note).first();
foreach(QString uuid, noteUuids)
if(backupUuids.contains(uuid))
backupUuids.removeOne(uuid);
if(backupUuids.isEmpty())
return;
QHash<QString,QStringList> backupHash;
foreach(QString str, backupUuids)
{
str.remove("{");
str.remove("}");
QStringList data = getFileData(QSettings().value("backupDirPath").toString()
+ "/" + str);
QString uuid = data.takeFirst();
backupHash.insert(uuid, data);
}
foreach(QString key, backupHash.keys())
{
QTreeWidgetItem *item = new QTreeWidgetItem(treeWidget);
item->setText(0,backupHash[key].first());
item->setData(0,Qt::UserRole,backupHash[key]);
}
}
QStringList Backup::getFileData(const QString &file)
{
AbstractNoteReader *reader = new HtmlNoteReader(file,document);
QStringList list;
QString uuid = reader->uuid();
list << uuid << reader->title() << QFileInfo(file).absoluteFilePath() << document->toHtml();
return list;
}
void Backup::showPreview()
{
//TODO:Even with no backup a preview is shown...
if(treeWidget->selectedItems().isEmpty())
return;
QStringList data = treeWidget->selectedItems().last()->data(0,Qt::UserRole).toStringList();
if(data.isEmpty())
return;
textEdit->setText(data.last());
}
void Backup::restoreBackup()
{
//TODO: enable restore and deletion for multiple backups
/* if(!treeWidget->selectionModel()->currentIndex().isValid())
return;
if(treeWidget->selectionModel()->currentIndex().data(Qt::UserRole).toStringList().isEmpty())
return;
QStringList dataList = treeWidget->selectionModel()->currentIndex().data(Qt::UserRole).toStringList();
QString title = dataList.takeFirst();
if(!QFile(dataList.first()).exists())
return;
else
{
if(!QDir(QSettings().value("rootPath").toString()+"/restored notes").exists())
QDir().mkpath(QSettings().value("rootPath").toString()+"/restored notes");
QFile(dataList.first()).copy(QSettings().value("rootPath").toString()+"/restored notes/"+title);
}*/
}
void Backup::getNoteUuidList(){
QFutureIterator<QUuid> it(future1->future());
while(it.hasNext())
notesUuids << it.next();
}
void Backup::deleteOldBackupsAndFileEntries(){
notesUuids.clear(); //make sure that it's empty
//searching for existing Notes
QDirIterator itFiles(QSettings().value("rootPath").toString(),
QDirIterator::Subdirectories);
QStringList noteFiles;
while(itFiles.hasNext()){
QString filePath = itFiles.next();
if(itFiles.fileInfo().isFile())
noteFiles << filePath;
}
future1 = new QFutureWatcher<QUuid>(this);
QUuid (*uuidPtr)(QString) = & HtmlNoteReader::uuid; // function pointer, because uuid method is overloaded
future1->setFuture(QtConcurrent::mapped(noteFiles, uuidPtr));
indexDialog = new QProgressDialog(this);
indexDialog->setLabelText(QString(tr("Indexing notes...")));
QObject::connect(future1, SIGNAL(finished()), this, SLOT(getNoteUuidList()));
QObject::connect(future1, SIGNAL(finished()), this, SLOT(progressChanges()));
QObject::connect(future1, SIGNAL(finished()), indexDialog, SLOT(reset()));
QObject::connect(indexDialog, SIGNAL(canceled()), future1, SLOT(cancel()));
QObject::connect(future1, SIGNAL(progressRangeChanged(int,int)),
indexDialog, SLOT(setRange(int,int)));
QObject::connect(future1, SIGNAL(progressValueChanged(int)), indexDialog,
SLOT(setValue(int)));
indexDialog->exec();
}
void actualRemoval(const QString& backupAndUuid){
if(!backupAndUuid.contains("Notes/"))
QFile::remove(backupAndUuid);
else
QSettings().remove(backupAndUuid);
}
void Backup::progressChanges(){
//get backup files
QStringList backups;
QDir backupDir(QSettings().value("backupDirPath").toString());
QList<QFileInfo> backupList = backupDir.entryInfoList(QDir::Files, QDir::Name);
foreach(QFileInfo backup, backupList)
backups << backup.absoluteFilePath();
//add QSettings Uuids to the backups
QStringList backupsAndUuids = backups + QSettings().allKeys().filter("Notes/");
//We only need the redundant backups and Uuids
foreach(QString str, backupsAndUuids){
if(!str.contains("Notes/") && notesUuids.contains(QFileInfo(str).fileName()))
backupsAndUuids.removeOne(str);
if(str.contains("Notes/")){
QString settings = str;
settings.remove("Notes/");
settings.remove("_size");
settings.remove("_cursor_position");
if(notesUuids.contains(settings))
backupsAndUuids.removeOne(str);
}
}
QString redundantBackupList;
foreach(QString str, backupsAndUuids)
if(!str.contains("Notes/"))
redundantBackupList += (str+"\n");
if(backupsAndUuids.isEmpty()){
QMessageBox::information(this, tr("No redundant data!"), tr("no redundant"
" Everything is clean! No redundant data!"));
return;
}
else{
if(QMessageBox::warning(this,tr("Deleting backups and file entries"),
tr("Do you really want to delete the backups and entries for the "
"following files?\n\n%1\nYou won't be able to restore them!").arg(
redundantBackupList),
QMessageBox::Yes | QMessageBox::Abort) != QMessageBox::Yes)
return;
}
progressDialog = new QProgressDialog(this);
progressDialog->setLabelText(QString(tr("Progressing files...")));
future2 = new QFutureWatcher<void>(this);
future2->setFuture(QtConcurrent::map(backupsAndUuids, actualRemoval));
QObject::connect(future2, SIGNAL(finished()), progressDialog, SLOT(reset()));
QObject::connect(future2, SIGNAL(finished()), this, SLOT(setupTreeData()));
QObject::connect(progressDialog, SIGNAL(canceled()), future2, SLOT(cancel()));
QObject::connect(future2, SIGNAL(progressRangeChanged(int,int)), progressDialog,
SLOT(setRange(int,int)));
QObject::connect(future2, SIGNAL(progressValueChanged(int)), progressDialog,
SLOT(setValue(int)));
progressDialog->exec();
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "base58.h"
#include "hash.h"
#include "uint256.h"
#include <assert.h>
#include <stdint.h>
#include <string.h>
#include <vector>
#include <string>
#include <boost/variant/apply_visitor.hpp>
#include <boost/variant/static_visitor.hpp>
/* All alphanumeric characters except for "0", "I", "O", and "l" */
static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
bool DecodeBase58(const char* psz, std::vector<unsigned char>& vch)
{
// Skip leading spaces.
while (*psz && isspace(*psz))
psz++;
// Skip and count leading '1's.
int zeroes = 0;
while (*psz == '1') {
zeroes++;
psz++;
}
// Allocate enough space in big-endian base256 representation.
std::vector<unsigned char> b256(strlen(psz) * 733 / 1000 + 1); // log(58) / log(256), rounded up.
// Process the characters.
while (*psz && !isspace(*psz)) {
// Decode base58 character
const char* ch = strchr(pszBase58, *psz);
if (ch == NULL)
return false;
// Apply "b256 = b256 * 58 + ch".
int carry = ch - pszBase58;
for (std::vector<unsigned char>::reverse_iterator it = b256.rbegin(); it != b256.rend(); it++) {
carry += 58 * (*it);
*it = carry % 256;
carry /= 256;
}
assert(carry == 0);
psz++;
}
// Skip trailing spaces.
while (isspace(*psz))
psz++;
if (*psz != 0)
return false;
// Skip leading zeroes in b256.
std::vector<unsigned char>::iterator it = b256.begin();
while (it != b256.end() && *it == 0)
it++;
// Copy result into output vector.
vch.reserve(zeroes + (b256.end() - it));
vch.assign(zeroes, 0x00);
while (it != b256.end())
vch.push_back(*(it++));
return true;
}
std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend)
{
// Skip & count leading zeroes.
int zeroes = 0;
while (pbegin != pend && *pbegin == 0) {
pbegin++;
zeroes++;
}
// Allocate enough space in big-endian base58 representation.
std::vector<unsigned char> b58((pend - pbegin) * 138 / 100 + 1); // log(256) / log(58), rounded up.
// Process the bytes.
while (pbegin != pend) {
int carry = *pbegin;
// Apply "b58 = b58 * 256 + ch".
for (std::vector<unsigned char>::reverse_iterator it = b58.rbegin(); it != b58.rend(); it++) {
carry += 256 * (*it);
*it = carry % 58;
carry /= 58;
}
assert(carry == 0);
pbegin++;
}
// Skip leading zeroes in base58 result.
std::vector<unsigned char>::iterator it = b58.begin();
while (it != b58.end() && *it == 0)
it++;
// Translate the result into a string.
std::string str;
str.reserve(zeroes + (b58.end() - it));
str.assign(zeroes, '1');
while (it != b58.end())
str += pszBase58[*(it++)];
return str;
}
std::string EncodeBase58(const std::vector<unsigned char>& vch)
{
return EncodeBase58(&vch[0], &vch[0] + vch.size());
}
bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet)
{
return DecodeBase58(str.c_str(), vchRet);
}
std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn)
{
// add 4-byte hash check to the end
std::vector<unsigned char> vch(vchIn);
uint256 hash = Hash(vch.begin(), vch.end());
vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4);
return EncodeBase58(vch);
}
bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet)
{
if (!DecodeBase58(psz, vchRet) ||
(vchRet.size() < 4)) {
vchRet.clear();
return false;
}
// re-calculate the checksum, insure it matches the included 4-byte checksum
uint256 hash = Hash(vchRet.begin(), vchRet.end() - 4);
if (memcmp(&hash, &vchRet.end()[-4], 4) != 0) {
vchRet.clear();
return false;
}
vchRet.resize(vchRet.size() - 4);
return true;
}
bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet)
{
return DecodeBase58Check(str.c_str(), vchRet);
}
CBase58Data::CBase58Data()
{
vchVersion.clear();
vchData.clear();
}
void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const void* pdata, size_t nSize)
{
vchVersion = vchVersionIn;
vchData.resize(nSize);
if (!vchData.empty())
memcpy(&vchData[0], pdata, nSize);
}
void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const unsigned char* pbegin, const unsigned char* pend)
{
SetData(vchVersionIn, (void*)pbegin, pend - pbegin);
}
bool CBase58Data::SetString(const char* psz, unsigned int nVersionBytes)
{
std::vector<unsigned char> vchTemp;
bool rc58 = DecodeBase58Check(psz, vchTemp);
if ((!rc58) || (vchTemp.size() < nVersionBytes)) {
vchData.clear();
vchVersion.clear();
return false;
}
vchVersion.assign(vchTemp.begin(), vchTemp.begin() + nVersionBytes);
vchData.resize(vchTemp.size() - nVersionBytes);
if (!vchData.empty())
memcpy(&vchData[0], &vchTemp[nVersionBytes], vchData.size());
OPENSSL_cleanse(&vchTemp[0], vchData.size());
return true;
}
bool CBase58Data::SetString(const std::string& str)
{
return SetString(str.c_str());
}
std::string CBase58Data::ToString() const
{
std::vector<unsigned char> vch = vchVersion;
vch.insert(vch.end(), vchData.begin(), vchData.end());
return EncodeBase58Check(vch);
}
int CBase58Data::CompareTo(const CBase58Data& b58) const
{
if (vchVersion < b58.vchVersion)
return -1;
if (vchVersion > b58.vchVersion)
return 1;
if (vchData < b58.vchData)
return -1;
if (vchData > b58.vchData)
return 1;
return 0;
}
namespace
{
class CBitcoinAddressVisitor : public boost::static_visitor<bool>
{
private:
CBitcoinAddress* addr;
public:
CBitcoinAddressVisitor(CBitcoinAddress* addrIn) : addr(addrIn) {}
bool operator()(const CKeyID& id) const { return addr->Set(id); }
bool operator()(const CScriptID& id) const { return addr->Set(id); }
bool operator()(const CNoDestination& no) const { return false; }
};
} // anon namespace
bool CBitcoinAddress::Set(const CKeyID& id)
{
SetData(Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS), &id, 20);
return true;
}
bool CBitcoinAddress::Set(const CScriptID& id)
{
SetData(Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS), &id, 20);
return true;
}
bool CBitcoinAddress::Set(const CTxDestination& dest)
{
return boost::apply_visitor(CBitcoinAddressVisitor(this), dest);
}
bool CBitcoinAddress::IsValid() const
{
return IsValid(Params());
}
bool CBitcoinAddress::IsValid(const CChainParams& params) const
{
bool fCorrectSize = vchData.size() == 20;
bool fKnownVersion = vchVersion == params.Base58Prefix(CChainParams::PUBKEY_ADDRESS) ||
vchVersion == params.Base58Prefix(CChainParams::SCRIPT_ADDRESS);
return fCorrectSize && fKnownVersion;
}
CTxDestination CBitcoinAddress::Get() const
{
if (!IsValid())
return CNoDestination();
uint160 id;
memcpy(&id, &vchData[0], 20);
if (vchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS))
return CKeyID(id);
else if (vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS))
return CScriptID(id);
else
return CNoDestination();
}
bool CBitcoinAddress::GetKeyID(CKeyID& keyID) const
{
if (!IsValid() || vchVersion != Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS))
return false;
uint160 id;
memcpy(&id, &vchData[0], 20);
keyID = CKeyID(id);
return true;
}
bool CBitcoinAddress::IsScript() const
{
return IsValid() && vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS);
}
void CBitcoinSecret::SetKey(const CKey& vchSecret)
{
assert(vchSecret.IsValid());
SetData(Params().Base58Prefix(CChainParams::SECRET_KEY), vchSecret.begin(), vchSecret.size());
if (vchSecret.IsCompressed())
vchData.push_back(1);
}
CKey CBitcoinSecret::GetKey()
{
CKey ret;
ret.Set(&vchData[0], &vchData[32], vchData.size() > 32 && vchData[32] == 1);
return ret;
}
bool CBitcoinSecret::IsValid() const
{
bool fExpectedFormat = vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1);
bool fCorrectVersion = vchVersion == Params().Base58Prefix(CChainParams::SECRET_KEY);
return fExpectedFormat && fCorrectVersion;
}
bool CBitcoinSecret::SetString(const char* pszSecret)
{
return CBase58Data::SetString(pszSecret) && IsValid();
}
bool CBitcoinSecret::SetString(const std::string& strSecret)
{
return SetString(strSecret.c_str());
}
<commit_msg>Fixing out of bounds error in GetKey()<commit_after>// Copyright (c) 2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "base58.h"
#include "hash.h"
#include "uint256.h"
#include <assert.h>
#include <stdint.h>
#include <string.h>
#include <vector>
#include <string>
#include <boost/variant/apply_visitor.hpp>
#include <boost/variant/static_visitor.hpp>
/* All alphanumeric characters except for "0", "I", "O", and "l" */
static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
bool DecodeBase58(const char* psz, std::vector<unsigned char>& vch)
{
// Skip leading spaces.
while (*psz && isspace(*psz))
psz++;
// Skip and count leading '1's.
int zeroes = 0;
while (*psz == '1') {
zeroes++;
psz++;
}
// Allocate enough space in big-endian base256 representation.
std::vector<unsigned char> b256(strlen(psz) * 733 / 1000 + 1); // log(58) / log(256), rounded up.
// Process the characters.
while (*psz && !isspace(*psz)) {
// Decode base58 character
const char* ch = strchr(pszBase58, *psz);
if (ch == NULL)
return false;
// Apply "b256 = b256 * 58 + ch".
int carry = ch - pszBase58;
for (std::vector<unsigned char>::reverse_iterator it = b256.rbegin(); it != b256.rend(); it++) {
carry += 58 * (*it);
*it = carry % 256;
carry /= 256;
}
assert(carry == 0);
psz++;
}
// Skip trailing spaces.
while (isspace(*psz))
psz++;
if (*psz != 0)
return false;
// Skip leading zeroes in b256.
std::vector<unsigned char>::iterator it = b256.begin();
while (it != b256.end() && *it == 0)
it++;
// Copy result into output vector.
vch.reserve(zeroes + (b256.end() - it));
vch.assign(zeroes, 0x00);
while (it != b256.end())
vch.push_back(*(it++));
return true;
}
std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend)
{
// Skip & count leading zeroes.
int zeroes = 0;
while (pbegin != pend && *pbegin == 0) {
pbegin++;
zeroes++;
}
// Allocate enough space in big-endian base58 representation.
std::vector<unsigned char> b58((pend - pbegin) * 138 / 100 + 1); // log(256) / log(58), rounded up.
// Process the bytes.
while (pbegin != pend) {
int carry = *pbegin;
// Apply "b58 = b58 * 256 + ch".
for (std::vector<unsigned char>::reverse_iterator it = b58.rbegin(); it != b58.rend(); it++) {
carry += 256 * (*it);
*it = carry % 58;
carry /= 58;
}
assert(carry == 0);
pbegin++;
}
// Skip leading zeroes in base58 result.
std::vector<unsigned char>::iterator it = b58.begin();
while (it != b58.end() && *it == 0)
it++;
// Translate the result into a string.
std::string str;
str.reserve(zeroes + (b58.end() - it));
str.assign(zeroes, '1');
while (it != b58.end())
str += pszBase58[*(it++)];
return str;
}
std::string EncodeBase58(const std::vector<unsigned char>& vch)
{
return EncodeBase58(&vch[0], &vch[0] + vch.size());
}
bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet)
{
return DecodeBase58(str.c_str(), vchRet);
}
std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn)
{
// add 4-byte hash check to the end
std::vector<unsigned char> vch(vchIn);
uint256 hash = Hash(vch.begin(), vch.end());
vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4);
return EncodeBase58(vch);
}
bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet)
{
if (!DecodeBase58(psz, vchRet) ||
(vchRet.size() < 4)) {
vchRet.clear();
return false;
}
// re-calculate the checksum, insure it matches the included 4-byte checksum
uint256 hash = Hash(vchRet.begin(), vchRet.end() - 4);
if (memcmp(&hash, &vchRet.end()[-4], 4) != 0) {
vchRet.clear();
return false;
}
vchRet.resize(vchRet.size() - 4);
return true;
}
bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet)
{
return DecodeBase58Check(str.c_str(), vchRet);
}
CBase58Data::CBase58Data()
{
vchVersion.clear();
vchData.clear();
}
void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const void* pdata, size_t nSize)
{
vchVersion = vchVersionIn;
vchData.resize(nSize);
if (!vchData.empty())
memcpy(&vchData[0], pdata, nSize);
}
void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const unsigned char* pbegin, const unsigned char* pend)
{
SetData(vchVersionIn, (void*)pbegin, pend - pbegin);
}
bool CBase58Data::SetString(const char* psz, unsigned int nVersionBytes)
{
std::vector<unsigned char> vchTemp;
bool rc58 = DecodeBase58Check(psz, vchTemp);
if ((!rc58) || (vchTemp.size() < nVersionBytes)) {
vchData.clear();
vchVersion.clear();
return false;
}
vchVersion.assign(vchTemp.begin(), vchTemp.begin() + nVersionBytes);
vchData.resize(vchTemp.size() - nVersionBytes);
if (!vchData.empty())
memcpy(&vchData[0], &vchTemp[nVersionBytes], vchData.size());
OPENSSL_cleanse(&vchTemp[0], vchData.size());
return true;
}
bool CBase58Data::SetString(const std::string& str)
{
return SetString(str.c_str());
}
std::string CBase58Data::ToString() const
{
std::vector<unsigned char> vch = vchVersion;
vch.insert(vch.end(), vchData.begin(), vchData.end());
return EncodeBase58Check(vch);
}
int CBase58Data::CompareTo(const CBase58Data& b58) const
{
if (vchVersion < b58.vchVersion)
return -1;
if (vchVersion > b58.vchVersion)
return 1;
if (vchData < b58.vchData)
return -1;
if (vchData > b58.vchData)
return 1;
return 0;
}
namespace
{
class CBitcoinAddressVisitor : public boost::static_visitor<bool>
{
private:
CBitcoinAddress* addr;
public:
CBitcoinAddressVisitor(CBitcoinAddress* addrIn) : addr(addrIn) {}
bool operator()(const CKeyID& id) const { return addr->Set(id); }
bool operator()(const CScriptID& id) const { return addr->Set(id); }
bool operator()(const CNoDestination& no) const { return false; }
};
} // anon namespace
bool CBitcoinAddress::Set(const CKeyID& id)
{
SetData(Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS), &id, 20);
return true;
}
bool CBitcoinAddress::Set(const CScriptID& id)
{
SetData(Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS), &id, 20);
return true;
}
bool CBitcoinAddress::Set(const CTxDestination& dest)
{
return boost::apply_visitor(CBitcoinAddressVisitor(this), dest);
}
bool CBitcoinAddress::IsValid() const
{
return IsValid(Params());
}
bool CBitcoinAddress::IsValid(const CChainParams& params) const
{
bool fCorrectSize = vchData.size() == 20;
bool fKnownVersion = vchVersion == params.Base58Prefix(CChainParams::PUBKEY_ADDRESS) ||
vchVersion == params.Base58Prefix(CChainParams::SCRIPT_ADDRESS);
return fCorrectSize && fKnownVersion;
}
CTxDestination CBitcoinAddress::Get() const
{
if (!IsValid())
return CNoDestination();
uint160 id;
memcpy(&id, &vchData[0], 20);
if (vchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS))
return CKeyID(id);
else if (vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS))
return CScriptID(id);
else
return CNoDestination();
}
bool CBitcoinAddress::GetKeyID(CKeyID& keyID) const
{
if (!IsValid() || vchVersion != Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS))
return false;
uint160 id;
memcpy(&id, &vchData[0], 20);
keyID = CKeyID(id);
return true;
}
bool CBitcoinAddress::IsScript() const
{
return IsValid() && vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS);
}
void CBitcoinSecret::SetKey(const CKey& vchSecret)
{
assert(vchSecret.IsValid());
SetData(Params().Base58Prefix(CChainParams::SECRET_KEY), vchSecret.begin(), vchSecret.size());
if (vchSecret.IsCompressed())
vchData.push_back(1);
}
CKey CBitcoinSecret::GetKey()
{
CKey ret;
assert(vchData.size() >= 32);
ret.Set(vchData.begin(), vchData.begin() + 32, vchData.size() > 32 && vchData[32] == 1);
return ret;
}
bool CBitcoinSecret::IsValid() const
{
bool fExpectedFormat = vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1);
bool fCorrectVersion = vchVersion == Params().Base58Prefix(CChainParams::SECRET_KEY);
return fExpectedFormat && fCorrectVersion;
}
bool CBitcoinSecret::SetString(const char* pszSecret)
{
return CBase58Data::SetString(pszSecret) && IsValid();
}
bool CBitcoinSecret::SetString(const std::string& strSecret)
{
return SetString(strSecret.c_str());
}
<|endoftext|>
|
<commit_before>// This file is part of the dune-gdt project:
// https://github.com/dune-community/dune-gdt
// Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// or GPL-2.0+ (http://opensource.org/licenses/gpl-license)
// with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
// Felix Schindler (2013 - 2017)
// Rene Milk (2014, 2016 - 2018)
// Sven Kaulmann (2014)
// Tobias Leibner (2014, 2016 - 2017)
#ifndef DUNE_GDT_SPACES_INTERFACE_HH
#define DUNE_GDT_SPACES_INTERFACE_HH
#include <dune/geometry/type.hh>
#include <dune/xt/grid/type_traits.hh>
#include <dune/gdt/exceptions.hh>
#include <dune/gdt/local/finite-elements/interfaces.hh>
#include <dune/gdt/spaces/basis/interface.hh>
#include <dune/gdt/spaces/mapper/interfaces.hh>
#include <dune/gdt/spaces/parallel/communication.hh>
#include <dune/gdt/type_traits.hh>
namespace Dune {
namespace GDT {
template <class GridView, size_t range_dim = 1, size_t range_dim_columns = 1, class RangeField = double>
class SpaceInterface
{
static_assert(XT::Grid::is_view<GridView>::value, "");
public:
using GridViewType = GridView;
using GV = GridViewType;
using D = typename GridViewType::ctype;
static const constexpr size_t d = GridViewType::dimension;
using R = RangeField;
static const constexpr size_t r = range_dim;
static const constexpr size_t rC = range_dim_columns;
using GlobalBasisType = GlobalBasisInterface<GridViewType, r, rC, R>;
using MapperType = MapperInterface<GridViewType>;
using FiniteElementType = LocalFiniteElementInterface<D, d, R, r, rC>;
using DofCommunicatorType = typename DofCommunicationChooser<GridViewType>::Type;
SpaceInterface()
: dof_communicator_(nullptr)
{
}
virtual ~SpaceInterface() = default;
virtual const GridViewType& grid_view() const = 0;
/**
* \name These methods provide the actual functionality, they have to be implemented.
* \{
**/
virtual const MapperType& mapper() const = 0;
virtual const GlobalBasisType& basis() const = 0;
virtual const FiniteElementType& finite_element(const GeometryType& geometry_type) const = 0;
/// \}
/**
* \name These methods help to identify the space, they have to be implemented.
* \{
**/
virtual SpaceType type() const = 0;
virtual int min_polorder() const = 0;
virtual int max_polorder() const = 0;
/**
* To query if elements of this space (functions) are continuous (i.e., in C^0), use `continuous(0)`.
*/
virtual bool continuous(const int diff_order) const = 0;
virtual bool continuous_normal_components() const = 0;
/**
* If this returns true, every finite_element() is expected to provide lagrange_points().
*/
virtual bool is_lagrangian() const = 0;
/// \}
/**
* \name These methods are required for MPI communication, they are provided.
* \{
*/
virtual const DofCommunicatorType& dof_communicator() const
{
if (!dof_communicator_)
DUNE_THROW(Exceptions::space_error,
"The actual space has to either implement its own dof_communicator() or call "
"create_communicator() in the ctor!");
return *dof_communicator_;
}
/// \}
protected:
void create_communicator()
{
if (!dof_communicator_) {
dof_communicator_ =
std::shared_ptr<DofCommunicatorType>(DofCommunicationChooser<GridViewType>::create(grid_view()));
DofCommunicationChooser<GridViewType>::prepare(*this, *dof_communicator_);
}
}
private:
std::shared_ptr<DofCommunicatorType> dof_communicator_;
}; // class SpaceInterface
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_SPACES_INTERFACE_HH
<commit_msg>[spaces] add contains(), operator<<<commit_after>// This file is part of the dune-gdt project:
// https://github.com/dune-community/dune-gdt
// Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// or GPL-2.0+ (http://opensource.org/licenses/gpl-license)
// with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
// Felix Schindler (2013 - 2017)
// Rene Milk (2014, 2016 - 2018)
// Sven Kaulmann (2014)
// Tobias Leibner (2014, 2016 - 2017)
#ifndef DUNE_GDT_SPACES_INTERFACE_HH
#define DUNE_GDT_SPACES_INTERFACE_HH
#include <dune/geometry/type.hh>
#include <dune/xt/la/container/vector-interface.hh>
#include <dune/xt/grid/type_traits.hh>
#include <dune/gdt/exceptions.hh>
#include <dune/gdt/local/finite-elements/interfaces.hh>
#include <dune/gdt/spaces/basis/interface.hh>
#include <dune/gdt/spaces/mapper/interfaces.hh>
#include <dune/gdt/spaces/parallel/communication.hh>
#include <dune/gdt/type_traits.hh>
namespace Dune {
namespace GDT {
// forward
template <class V, class GV, size_t r, size_t rC, class R>
class ConstDiscreteFunction;
template <class GridView, size_t range_dim = 1, size_t range_dim_columns = 1, class RangeField = double>
class SpaceInterface
{
static_assert(XT::Grid::is_view<GridView>::value, "");
public:
using GridViewType = GridView;
using GV = GridViewType;
using D = typename GridViewType::ctype;
static const constexpr size_t d = GridViewType::dimension;
using R = RangeField;
static const constexpr size_t r = range_dim;
static const constexpr size_t rC = range_dim_columns;
using GlobalBasisType = GlobalBasisInterface<GridViewType, r, rC, R>;
using MapperType = MapperInterface<GridViewType>;
using FiniteElementType = LocalFiniteElementInterface<D, d, R, r, rC>;
using DofCommunicatorType = typename DofCommunicationChooser<GridViewType>::Type;
SpaceInterface()
: dof_communicator_(nullptr)
{
}
virtual ~SpaceInterface() = default;
/// \name These methods provide the actual functionality, they have to be implemented.
/// \{
virtual const GridViewType& grid_view() const = 0;
virtual const MapperType& mapper() const = 0;
virtual const GlobalBasisType& basis() const = 0;
virtual const FiniteElementType& finite_element(const GeometryType& geometry_type) const = 0;
/// \}
/// \name These methods help to identify the space, they have to be implemented.
/// \{
virtual SpaceType type() const = 0;
virtual int min_polorder() const = 0;
virtual int max_polorder() const = 0;
/**
* To query if elements of this space (functions) are continuous (i.e., in C^0), use `continuous(0)`.
*/
virtual bool continuous(const int diff_order) const = 0;
virtual bool continuous_normal_components() const = 0;
/**
* If this returns true, every finite_element() is expected to provide lagrange_points().
*/
virtual bool is_lagrangian() const = 0;
/// \}
/// \name These methods are required for MPI communication, they are provided.
/// \{
virtual const DofCommunicatorType& dof_communicator() const
{
if (!dof_communicator_)
DUNE_THROW(Exceptions::space_error,
"The actual space has to either implement its own dof_communicator() or call "
"create_communicator() in the ctor!");
return *dof_communicator_;
}
/// \}
/// \name These methods are provided for convenience.
/// \{
template <class V>
bool contains(const XT::LA::VectorInterface<V>& vector) const
{
return vector.size() == this->mapper().size();
}
/**
* \note A return value of true cannot be ultimately trusted yet.
*
* \sa https://github.com/dune-community/dune-gdt/issues/123
*/
template <class V>
bool contains(const ConstDiscreteFunction<V, GV, r, rC, R>& function) const
{
// this is the only case where we are sure^^
if (&function.space() == this)
return true;
if (function.space().type() != this->type())
return false;
if (function.space().mapper().size() != this->mapper().size())
return false;
// the spaces might still differ (different grid views of same size), but we have no means to check this
return true;
}
/// \}
protected:
void create_communicator()
{
if (!dof_communicator_) {
dof_communicator_ =
std::shared_ptr<DofCommunicatorType>(DofCommunicationChooser<GridViewType>::create(grid_view()));
DofCommunicationChooser<GridViewType>::prepare(*this, *dof_communicator_);
}
}
private:
std::shared_ptr<DofCommunicatorType> dof_communicator_;
}; // class SpaceInterface
template <class GV, size_t r, size_t rC, class R>
std::ostream& operator<<(std::ostream& out, const SpaceInterface<GV, r, rC, R>& space)
{
out << "Space(" << space.type() << ", " << space.mapper().size() << " DoFs)";
return out;
}
} // namespace GDT
} // namespace Dune
#include <dune/gdt/discretefunction/default.hh>
#endif // DUNE_GDT_SPACES_INTERFACE_HH
<|endoftext|>
|
<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2009 Gael Guennebaud <g.gael@free.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "main.h"
#include <unsupported/Eigen/AlignedVector3>
template<typename Scalar>
void alignedvector3()
{
Scalar s1 = internal::random<Scalar>();
Scalar s2 = internal::random<Scalar>();
typedef Matrix<Scalar,3,1> RefType;
typedef Matrix<Scalar,3,3> Mat33;
typedef AlignedVector3<Scalar> FastType;
RefType r1(RefType::Random()), r2(RefType::Random()), r3(RefType::Random()),
r4(RefType::Random()), r5(RefType::Random()), r6(RefType::Random());
FastType f1(r1), f2(r2), f3(r3), f4(r4), f5(r5), f6(r6);
Mat33 m1(Mat33::Random());
VERIFY_IS_APPROX(f1,r1);
VERIFY_IS_APPROX(f4,r4);
VERIFY_IS_APPROX(f4+f1,r4+r1);
VERIFY_IS_APPROX(f4-f1,r4-r1);
VERIFY_IS_APPROX(f4+f1-f2,r4+r1-r2);
VERIFY_IS_APPROX(f4+=f3,r4+=r3);
VERIFY_IS_APPROX(f4-=f5,r4-=r5);
VERIFY_IS_APPROX(f4-=f5+f1,r4-=r5+r1);
VERIFY_IS_APPROX(f5+f1-s1*f2,r5+r1-s1*r2);
VERIFY_IS_APPROX(f5+f1/s2-s1*f2,r5+r1/s2-s1*r2);
VERIFY_IS_APPROX(m1*f4,m1*r4);
VERIFY_IS_APPROX(f4.transpose()*m1,r4.transpose()*m1);
VERIFY_IS_APPROX(f2.dot(f3),r2.dot(r3));
VERIFY_IS_APPROX(f2.cross(f3),r2.cross(r3));
VERIFY_IS_APPROX(f2.norm(),r2.norm());
VERIFY_IS_APPROX(f2.normalized(),r2.normalized());
VERIFY_IS_APPROX((f2+f1).normalized(),(r2+r1).normalized());
f2.normalize();
r2.normalize();
VERIFY_IS_APPROX(f2,r2);
}
void test_alignedvector3()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST( alignedvector3<float>() );
}
}
<commit_msg>Fix compilation of alignedvector3 unit test<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2009 Gael Guennebaud <g.gael@free.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "main.h"
#include <unsupported/Eigen/AlignedVector3>
namespace Eigen {
template<typename T,typename Derived>
T test_relative_error(const AlignedVector3<T> &a, const MatrixBase<Derived> &b)
{
return test_relative_error(a.coeffs().template head<3>(), b);
}
}
template<typename Scalar>
void alignedvector3()
{
Scalar s1 = internal::random<Scalar>();
Scalar s2 = internal::random<Scalar>();
typedef Matrix<Scalar,3,1> RefType;
typedef Matrix<Scalar,3,3> Mat33;
typedef AlignedVector3<Scalar> FastType;
RefType r1(RefType::Random()), r2(RefType::Random()), r3(RefType::Random()),
r4(RefType::Random()), r5(RefType::Random()), r6(RefType::Random());
FastType f1(r1), f2(r2), f3(r3), f4(r4), f5(r5), f6(r6);
Mat33 m1(Mat33::Random());
VERIFY_IS_APPROX(f1,r1);
VERIFY_IS_APPROX(f4,r4);
VERIFY_IS_APPROX(f4+f1,r4+r1);
VERIFY_IS_APPROX(f4-f1,r4-r1);
VERIFY_IS_APPROX(f4+f1-f2,r4+r1-r2);
VERIFY_IS_APPROX(f4+=f3,r4+=r3);
VERIFY_IS_APPROX(f4-=f5,r4-=r5);
VERIFY_IS_APPROX(f4-=f5+f1,r4-=r5+r1);
VERIFY_IS_APPROX(f5+f1-s1*f2,r5+r1-s1*r2);
VERIFY_IS_APPROX(f5+f1/s2-s1*f2,r5+r1/s2-s1*r2);
VERIFY_IS_APPROX(m1*f4,m1*r4);
VERIFY_IS_APPROX(f4.transpose()*m1,r4.transpose()*m1);
VERIFY_IS_APPROX(f2.dot(f3),r2.dot(r3));
VERIFY_IS_APPROX(f2.cross(f3),r2.cross(r3));
VERIFY_IS_APPROX(f2.norm(),r2.norm());
VERIFY_IS_APPROX(f2.normalized(),r2.normalized());
VERIFY_IS_APPROX((f2+f1).normalized(),(r2+r1).normalized());
f2.normalize();
r2.normalize();
VERIFY_IS_APPROX(f2,r2);
}
void test_alignedvector3()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST( alignedvector3<float>() );
}
}
<|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_RASTER_HPP
#define MAPNIK_RASTER_HPP
// mapnik
#include <mapnik/box2d.hpp>
#include <mapnik/image_data.hpp>
#include <mapnik/noncopyable.hpp>
// boost
#include <boost/optional.hpp>
namespace mapnik {
class raster : private mapnik::noncopyable
{
public:
box2d<double> ext_;
image_data_32 data_;
double filter_factor_;
bool premultiplied_alpha_;
boost::optional<double> nodata_;
raster(box2d<double> const& ext,
unsigned width,
unsigned height,
double filter_factor,
bool premultiplied_alpha = false)
: ext_(ext),
data_(width,height),
filter_factor_(filter_factor),
premultiplied_alpha_(premultiplied_alpha) {}
void set_nodata(double nodata)
{
nodata_ = nodata;
}
boost::optional<double> const& nodata() const
{
return nodata_;
}
double get_filter_factor() const
{
return filter_factor_;
}
void set_filter_factor(double factor)
{
filter_factor_ = factor;
}
};
}
#endif // MAPNIK_RASTER_HPP
<commit_msg>mapnik::raster : allow passing image_data into ctor<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#ifndef MAPNIK_RASTER_HPP
#define MAPNIK_RASTER_HPP
// mapnik
#include <mapnik/box2d.hpp>
#include <mapnik/image_data.hpp>
#include <mapnik/noncopyable.hpp>
// boost
#include <boost/optional.hpp>
namespace mapnik {
class raster : private mapnik::noncopyable
{
public:
box2d<double> ext_;
image_data_32 data_;
double filter_factor_;
bool premultiplied_alpha_;
boost::optional<double> nodata_;
raster(box2d<double> const& ext,
unsigned width,
unsigned height,
double filter_factor,
bool premultiplied_alpha = false)
: ext_(ext),
data_(width,height),
filter_factor_(filter_factor),
premultiplied_alpha_(premultiplied_alpha) {}
raster(box2d<double> const& ext, image_data_32 && data,
double filter_factor, bool premultiplied_alpha = false)
: ext_(ext),
data_(std::move(data)),
filter_factor_(filter_factor),
premultiplied_alpha_(premultiplied_alpha) {}
void set_nodata(double nodata)
{
nodata_ = nodata;
}
boost::optional<double> const& nodata() const
{
return nodata_;
}
double get_filter_factor() const
{
return filter_factor_;
}
void set_filter_factor(double factor)
{
filter_factor_ = factor;
}
};
}
#endif // MAPNIK_RASTER_HPP
<|endoftext|>
|
<commit_before>#pragma once
#ifndef SIPL_MATRIX_MATRIX_H
#define SIPL_MATRIX_MATRIX_H
#include "matrix/MatrixBase.hpp"
#include "matrix/Vector.hpp"
#include "matrix/Wrappers.hpp"
#include <cmath>
#include <iostream>
namespace sipl
{
// Need to use 'this' pointer below because templated base class members are
// not visible in a certain phase of compilation. See here:
// http://stackoverflow.com/a/6592617
// Initial class for statically-allocated matrices
template <typename Dtype, int32_t Rows, int32_t Cols>
class Matrix : public MatrixBase<Dtype,
Rows,
Cols,
StaticArrayWrapper<Dtype, Rows * Cols>>
{
public:
using ContainerType = StaticArrayWrapper<Dtype, Rows * Cols>;
using BaseClass = MatrixBase<Dtype, Rows, Cols, ContainerType>;
using BaseClass::BaseClass;
// Explicitly import BaseClass member variables so we don't have to use
// 'this' pointer because of 2-phase lookup (see here for more information:
// http://stackoverflow.com/a/4643295)
using BaseClass::nelements_;
using BaseClass::nbytes_;
using BaseClass::data_;
using BaseClass::dims;
Matrix() : BaseClass() {}
Matrix(Dtype fill_value) : BaseClass()
{
std::fill(std::begin(data_), std::end(data_), fill_value);
}
Matrix(std::initializer_list<std::initializer_list<Dtype>> list)
: BaseClass()
{
assert(int32_t(list.size()) == Rows && "size mismatch");
for (const auto l : list) {
assert(int32_t(l.size()) == Cols && "size mismatch");
}
int32_t i = 0;
for (const auto l : list) {
std::copy(std::begin(l), std::end(l),
std::begin(data_) + i++ * l.size());
}
}
template <typename OtherType>
Matrix<OtherType, Rows, Cols> as_type() const
{
return apply([](auto e) { return OtherType(e); });
}
// Template magic from: http://stackoverflow.com/a/26383814
template <typename UnaryFunctor,
typename OutputType =
typename std::result_of<UnaryFunctor&(Dtype)>::type>
decltype(auto) apply(UnaryFunctor f) const
{
Matrix<OutputType, Rows, Cols> new_m;
std::transform(std::begin(*this), std::end(*this), std::begin(new_m),
f);
return new_m;
}
Matrix rescale(Dtype new_min, Dtype new_max) const
{
return apply([ min = this->min(), max = this->max(), new_min, new_max ](
auto e) {
return Dtype(((new_max - new_min) / double(max - min)) * e +
((new_min * max + min * new_max) / double(max - min)));
});
}
Matrix clip(Dtype new_min, Dtype new_max) const
{
Matrix new_m;
for (int32_t i = 0; i < this->size(); ++i) {
auto e = std::round((*this)[i]);
if (e < new_min) {
new_m[i] = new_min;
} else if (e > new_max) {
new_m[i] = new_max;
} else {
new_m[i] = e;
}
}
return new_m;
}
};
// Specialization of the above for dynamically-allocated matrices.
template <typename Dtype>
class Matrix<Dtype, Dynamic, Dynamic>
: public MatrixBase<Dtype,
Dynamic,
Dynamic,
DynamicArrayWrapper<Dtype, Dynamic>>
{
public:
using ContainerType = DynamicArrayWrapper<Dtype, Dynamic>;
using BaseClass = MatrixBase<Dtype, Dynamic, Dynamic, ContainerType>;
using BaseClass::BaseClass;
using BaseClass::nelements_;
using BaseClass::nbytes_;
using BaseClass::data_;
using BaseClass::dims;
Matrix(int32_t rows, int32_t cols)
{
nelements_ = rows * cols;
data_ = ContainerType(nelements_);
nbytes_ = nelements_ * int32_t(sizeof(Dtype));
dims = {rows, cols};
}
Matrix(int32_t rows, int32_t cols, Dtype fill_value)
{
nelements_ = rows * cols;
data_ = ContainerType(nelements_);
nbytes_ = nelements_ * int32_t(sizeof(Dtype));
dims = {rows, cols};
std::fill(std::begin(data_), std::end(data_), fill_value);
}
Matrix(std::array<int32_t, 2> new_dims, Dtype fill_value)
{
nelements_ = new_dims[0] * new_dims[1];
data_ = ContainerType(nelements_);
nbytes_ = nelements_ * int32_t(sizeof(Dtype));
dims = new_dims;
std::fill(std::begin(data_), std::end(data_), fill_value);
}
Matrix(std::array<int32_t, 2> new_dims)
{
nelements_ = new_dims[0] * new_dims[1];
data_ = ContainerType(nelements_);
nbytes_ = nelements_ * int32_t(sizeof(Dtype));
dims = new_dims;
}
Matrix(std::initializer_list<std::initializer_list<Dtype>> list)
{
int32_t nrows = list.size();
int32_t ncols = list.begin()->size();
for (const auto l : list) {
assert(int32_t(l.size()) == ncols &&
"initializer_list size mismatch");
}
nelements_ = nrows * ncols;
nbytes_ = nelements_ * int32_t(sizeof(Dtype));
data_ = ContainerType(nelements_);
dims = {nrows, ncols};
int32_t i = 0;
for (const auto l : list) {
std::copy(std::begin(l), std::end(l),
std::begin(data_) + i++ * l.size());
}
}
// Extract a patch centered at (center_y, center_x) with radius ry and
// rx. Change boundaries depending on BorderType
Matrix patch(int32_t center_y,
int32_t center_x,
int32_t ry,
int32_t rx,
const BorderType border_type = BorderType::REPLICATE) const
{
assert(center_y >= 0 && center_y < dims[0] && "center_y out of bounds");
assert(center_x >= 0 && center_x < dims[1] && "center_x out of bounds");
Matrix patch(2 * ry + 1, 2 * rx + 1);
for (int32_t y = center_y - ry, r = 0; y <= center_y + ry; ++y, ++r) {
for (int32_t x = center_x - rx, c = 0; x <= center_x + rx;
++x, ++c) {
switch (border_type) {
case BorderType::REPLICATE:
patch(r, c) = (*this)(this->clamp_row_index(y),
this->clamp_col_index(x));
}
}
}
return patch;
}
template <typename OtherType>
Matrix<OtherType, Dynamic, Dynamic> as_type() const
{
return apply([](auto e) { return OtherType(e); });
}
// Template magic from: http://stackoverflow.com/a/26383814
template <typename UnaryFunctor,
typename OutputType =
typename std::result_of<UnaryFunctor&(Dtype)>::type>
decltype(auto) apply(UnaryFunctor f) const
{
Matrix<OutputType, Dynamic, Dynamic> new_m(dims);
std::transform(std::begin(*this), std::end(*this), std::begin(new_m),
f);
return new_m;
}
Matrix clip(Dtype new_min, Dtype new_max) const
{
Matrix new_m(dims);
for (int32_t i = 0; i < this->size(); ++i) {
auto e = std::round((*this)[i]);
if (e < new_min) {
new_m[i] = new_min;
} else if (e > new_max) {
new_m[i] = new_max;
} else {
new_m[i] = e;
}
}
return new_m;
}
Matrix rescale(Dtype new_min, Dtype new_max) const
{
return apply([ min = this->min(), max = this->max(), new_min, new_max ](
auto e) {
return Dtype(((new_max - new_min) / double(max - min)) * e +
((new_min * max + min * new_max) / double(max - min)));
});
}
};
// Specialization of the above for dynamically-allocated Matrix with Vector
// elements.
// XXX Only specialized for fixed-sized Vector elements at this time
template <typename Dtype, int32_t Length>
class Matrix<Vector<Dtype, Length>, Dynamic, Dynamic>
: public MatrixBase<Vector<Dtype, Length>,
Dynamic,
Dynamic,
DynamicArrayWrapper<Vector<Dtype, Length>, Length>>
{
public:
using value_type = Vector<Dtype, Length>;
using ContainerType = DynamicArrayWrapper<value_type, Length>;
using BaseClass = MatrixBase<value_type, Dynamic, Dynamic, ContainerType>;
using BaseClass::BaseClass;
using BaseClass::nelements_;
using BaseClass::nbytes_;
using BaseClass::data_;
using BaseClass::dims;
Matrix(std::array<int32_t, 2> dims_)
{
nelements_ = dims_[0] * dims_[1];
data_ = ContainerType(nelements_);
nbytes_ = nelements_ * int32_t(sizeof(Dtype));
dims = dims_;
}
Matrix(std::array<int32_t, 2> dims_, Dtype fillval)
{
nelements_ = dims_[0] * dims_[1];
data_ = ContainerType(nelements_);
nbytes_ = nelements_ * int32_t(sizeof(Dtype));
dims = dims_;
std::fill(std::begin(data_), std::end(data_), fillval);
}
Matrix(int32_t rows, int32_t cols)
{
nelements_ = rows * cols;
nbytes_ = nelements_ * Length * int32_t(sizeof(Dtype));
data_ = ContainerType(nelements_);
dims = {rows, cols};
}
Matrix(int32_t rows, int32_t cols, value_type fill_value)
{
nelements_ = rows * cols;
data_ = ContainerType(nelements_);
nbytes_ = nelements_ * Length * int32_t(sizeof(Dtype));
dims = {rows, cols};
std::fill(std::begin(data_), std::end(data_), fill_value);
}
// Extract a patch centered at (center_y, center_x) with radius ry and
// rx. Change boundaries depending on BorderType
Matrix patch(int32_t center_y,
int32_t center_x,
int32_t ry,
int32_t rx,
const BorderType border_type = BorderType::REPLICATE) const
{
assert(center_y >= 0 && center_y < dims[0] && "center_y out of bounds");
assert(center_x >= 0 && center_x < dims[1] && "center_x out of bounds");
Matrix patch(2 * ry + 1, 2 * rx + 1);
for (int32_t y = center_y - ry, r = 0; y <= center_y + ry; ++y, ++r) {
for (int32_t x = center_x - rx, c = 0; x <= center_x + rx;
++x, ++c) {
switch (border_type) {
case BorderType::REPLICATE:
patch(r, c) = (*this)(this->clamp_row_index(y),
this->clamp_col_index(x));
}
}
}
return patch;
}
template <typename OtherType>
Matrix<OtherType, Dynamic, Dynamic> as_type() const
{
return apply([](auto e) { return OtherType(e); });
}
Matrix clip(Dtype new_min, Dtype new_max) const
{
Matrix new_m(dims);
for (int32_t i = 0; i < this->size(); ++i) {
for (int32_t c = 0; c < new_m[0].size(); ++c) {
auto e = std::round((*this)[i][c]);
if (e < new_min) {
new_m[i][c] = new_min;
} else if (e > new_max) {
new_m[i][c] = new_max;
} else {
new_m[i][c] = e;
}
}
}
return new_m;
}
std::string str() const
{
std::stringstream ss;
ss << "[";
for (int32_t i = 0; i < dims[0] - 1; ++i) {
for (int32_t j = 0; j < dims[1] - 1; ++j) {
ss << (*this)(i, j) << " ";
}
ss << (*this)(i, dims[1] - 1) << ";" << std::endl;
}
for (int32_t j = 0; j < dims[1] - 1; ++j) {
ss << (*this)(dims[0] - 1, j) << " ";
}
ss << this->back() << "]";
return ss.str();
}
// Template magic from: http://stackoverflow.com/a/26383814
template <typename UnaryFunctor,
typename OutputType = typename std::result_of<
UnaryFunctor&(Vector<Dtype, Length>)>::type>
decltype(auto) apply(UnaryFunctor f) const
{
Matrix<OutputType, Dynamic, Dynamic> new_m(dims);
std::transform(std::begin(*this), std::end(*this), std::begin(new_m),
f);
return new_m;
}
};
// Static aliases
template <typename T>
using Matrix44 = Matrix<T, 4, 4>;
using Matrix44d = Matrix44<double>;
template <typename T>
using Matrix33 = Matrix<T, 3, 3>;
using Matrix33i = Matrix33<int32_t>;
using Matrix33d = Matrix33<double>;
using Matrix33f = Matrix33<float>;
using Matrix33b = Matrix33<uint8_t>;
// Dynamic aliases
template <typename T>
using MatrixX = Matrix<T, Dynamic, Dynamic>;
using MatrixXd = MatrixX<double>;
using MatrixXi = MatrixX<int32_t>;
using MatrixXb = MatrixX<uint8_t>;
}
#endif
<commit_msg>Add static Ones() function<commit_after>#pragma once
#ifndef SIPL_MATRIX_MATRIX_H
#define SIPL_MATRIX_MATRIX_H
#include "matrix/MatrixBase.hpp"
#include "matrix/Vector.hpp"
#include "matrix/Wrappers.hpp"
#include <cmath>
#include <iostream>
namespace sipl
{
// Need to use 'this' pointer below because templated base class members are
// not visible in a certain phase of compilation. See here:
// http://stackoverflow.com/a/6592617
// Initial class for statically-allocated matrices
template <typename Dtype, int32_t Rows, int32_t Cols>
class Matrix : public MatrixBase<Dtype,
Rows,
Cols,
StaticArrayWrapper<Dtype, Rows * Cols>>
{
public:
using ContainerType = StaticArrayWrapper<Dtype, Rows * Cols>;
using BaseClass = MatrixBase<Dtype, Rows, Cols, ContainerType>;
using BaseClass::BaseClass;
// Explicitly import BaseClass member variables so we don't have to use
// 'this' pointer because of 2-phase lookup (see here for more information:
// http://stackoverflow.com/a/4643295)
using BaseClass::nelements_;
using BaseClass::nbytes_;
using BaseClass::data_;
using BaseClass::dims;
Matrix() : BaseClass() {}
Matrix(Dtype fill_value) : BaseClass()
{
std::fill(std::begin(data_), std::end(data_), fill_value);
}
Matrix(std::initializer_list<std::initializer_list<Dtype>> list)
: BaseClass()
{
assert(int32_t(list.size()) == Rows && "size mismatch");
for (const auto l : list) {
assert(int32_t(l.size()) == Cols && "size mismatch");
}
int32_t i = 0;
for (const auto l : list) {
std::copy(std::begin(l), std::end(l),
std::begin(data_) + i++ * l.size());
}
}
template <typename OtherType>
Matrix<OtherType, Rows, Cols> as_type() const
{
return apply([](auto e) { return OtherType(e); });
}
// Template magic from: http://stackoverflow.com/a/26383814
template <typename UnaryFunctor,
typename OutputType =
typename std::result_of<UnaryFunctor&(Dtype)>::type>
decltype(auto) apply(UnaryFunctor f) const
{
Matrix<OutputType, Rows, Cols> new_m;
std::transform(std::begin(*this), std::end(*this), std::begin(new_m),
f);
return new_m;
}
Matrix rescale(Dtype new_min, Dtype new_max) const
{
return apply([ min = this->min(), max = this->max(), new_min,
new_max ](auto e) {
return Dtype(((new_max - new_min) / double(max - min)) * e +
((new_min * max + min * new_max) / double(max - min)));
});
}
Matrix clip(Dtype new_min, Dtype new_max) const
{
Matrix new_m;
for (int32_t i = 0; i < this->size(); ++i) {
auto e = std::round((*this)[i]);
if (e < new_min) {
new_m[i] = new_min;
} else if (e > new_max) {
new_m[i] = new_max;
} else {
new_m[i] = e;
}
}
return new_m;
}
static Matrix Ones() { return Matrix(Dtype(1)); }
};
// Specialization of the above for dynamically-allocated matrices.
template <typename Dtype>
class Matrix<Dtype, Dynamic, Dynamic>
: public MatrixBase<Dtype,
Dynamic,
Dynamic,
DynamicArrayWrapper<Dtype, Dynamic>>
{
public:
using ContainerType = DynamicArrayWrapper<Dtype, Dynamic>;
using BaseClass = MatrixBase<Dtype, Dynamic, Dynamic, ContainerType>;
using BaseClass::BaseClass;
using BaseClass::nelements_;
using BaseClass::nbytes_;
using BaseClass::data_;
using BaseClass::dims;
Matrix(int32_t rows, int32_t cols)
{
nelements_ = rows * cols;
data_ = ContainerType(nelements_);
nbytes_ = nelements_ * int32_t(sizeof(Dtype));
dims = {rows, cols};
}
Matrix(int32_t rows, int32_t cols, Dtype fill_value)
{
nelements_ = rows * cols;
data_ = ContainerType(nelements_);
nbytes_ = nelements_ * int32_t(sizeof(Dtype));
dims = {rows, cols};
std::fill(std::begin(data_), std::end(data_), fill_value);
}
Matrix(std::array<int32_t, 2> new_dims, Dtype fill_value)
{
nelements_ = new_dims[0] * new_dims[1];
data_ = ContainerType(nelements_);
nbytes_ = nelements_ * int32_t(sizeof(Dtype));
dims = new_dims;
std::fill(std::begin(data_), std::end(data_), fill_value);
}
Matrix(std::array<int32_t, 2> new_dims)
{
nelements_ = new_dims[0] * new_dims[1];
data_ = ContainerType(nelements_);
nbytes_ = nelements_ * int32_t(sizeof(Dtype));
dims = new_dims;
}
Matrix(std::initializer_list<std::initializer_list<Dtype>> list)
{
int32_t nrows = list.size();
int32_t ncols = list.begin()->size();
for (const auto l : list) {
assert(int32_t(l.size()) == ncols &&
"initializer_list size mismatch");
}
nelements_ = nrows * ncols;
nbytes_ = nelements_ * int32_t(sizeof(Dtype));
data_ = ContainerType(nelements_);
dims = {nrows, ncols};
int32_t i = 0;
for (const auto l : list) {
std::copy(std::begin(l), std::end(l),
std::begin(data_) + i++ * l.size());
}
}
// Extract a patch centered at (center_y, center_x) with radius ry and
// rx. Change boundaries depending on BorderType
Matrix patch(int32_t center_y,
int32_t center_x,
int32_t ry,
int32_t rx,
const BorderType border_type = BorderType::REPLICATE) const
{
assert(center_y >= 0 && center_y < dims[0] && "center_y out of bounds");
assert(center_x >= 0 && center_x < dims[1] && "center_x out of bounds");
Matrix patch(2 * ry + 1, 2 * rx + 1);
for (int32_t y = center_y - ry, r = 0; y <= center_y + ry; ++y, ++r) {
for (int32_t x = center_x - rx, c = 0; x <= center_x + rx;
++x, ++c) {
switch (border_type) {
case BorderType::REPLICATE:
patch(r, c) = (*this)(this->clamp_row_index(y),
this->clamp_col_index(x));
}
}
}
return patch;
}
template <typename OtherType>
Matrix<OtherType, Dynamic, Dynamic> as_type() const
{
return apply([](auto e) { return OtherType(e); });
}
// Template magic from: http://stackoverflow.com/a/26383814
template <typename UnaryFunctor,
typename OutputType =
typename std::result_of<UnaryFunctor&(Dtype)>::type>
decltype(auto) apply(UnaryFunctor f) const
{
Matrix<OutputType, Dynamic, Dynamic> new_m(dims);
std::transform(std::begin(*this), std::end(*this), std::begin(new_m),
f);
return new_m;
}
Matrix clip(Dtype new_min, Dtype new_max) const
{
Matrix new_m(dims);
for (int32_t i = 0; i < this->size(); ++i) {
auto e = std::round((*this)[i]);
if (e < new_min) {
new_m[i] = new_min;
} else if (e > new_max) {
new_m[i] = new_max;
} else {
new_m[i] = e;
}
}
return new_m;
}
Matrix rescale(Dtype new_min, Dtype new_max) const
{
return apply([ min = this->min(), max = this->max(), new_min,
new_max ](auto e) {
return Dtype(((new_max - new_min) / double(max - min)) * e +
((new_min * max + min * new_max) / double(max - min)));
});
}
static Matrix Ones(int32_t height, int32_t width)
{
return Matrix(height, width, Dtype(1));
}
static Matrix Ones(const std::array<int32_t, 2>& dims)
{
return Matrix(dims, Dtype(1));
}
};
// Specialization of the above for dynamically-allocated Matrix with Vector
// elements.
// XXX Only specialized for fixed-sized Vector elements at this time
template <typename Dtype, int32_t Length>
class Matrix<Vector<Dtype, Length>, Dynamic, Dynamic>
: public MatrixBase<Vector<Dtype, Length>,
Dynamic,
Dynamic,
DynamicArrayWrapper<Vector<Dtype, Length>, Length>>
{
public:
using value_type = Vector<Dtype, Length>;
using ContainerType = DynamicArrayWrapper<value_type, Length>;
using BaseClass = MatrixBase<value_type, Dynamic, Dynamic, ContainerType>;
using BaseClass::BaseClass;
using BaseClass::nelements_;
using BaseClass::nbytes_;
using BaseClass::data_;
using BaseClass::dims;
Matrix(std::array<int32_t, 2> dims_)
{
nelements_ = dims_[0] * dims_[1];
data_ = ContainerType(nelements_);
nbytes_ = nelements_ * int32_t(sizeof(Dtype));
dims = dims_;
}
Matrix(std::array<int32_t, 2> dims_, Dtype fillval)
{
nelements_ = dims_[0] * dims_[1];
data_ = ContainerType(nelements_);
nbytes_ = nelements_ * int32_t(sizeof(Dtype));
dims = dims_;
std::fill(std::begin(data_), std::end(data_), fillval);
}
Matrix(int32_t rows, int32_t cols)
{
nelements_ = rows * cols;
nbytes_ = nelements_ * Length * int32_t(sizeof(Dtype));
data_ = ContainerType(nelements_);
dims = {rows, cols};
}
Matrix(int32_t rows, int32_t cols, value_type fill_value)
{
nelements_ = rows * cols;
data_ = ContainerType(nelements_);
nbytes_ = nelements_ * Length * int32_t(sizeof(Dtype));
dims = {rows, cols};
std::fill(std::begin(data_), std::end(data_), fill_value);
}
// Extract a patch centered at (center_y, center_x) with radius ry and
// rx. Change boundaries depending on BorderType
Matrix patch(int32_t center_y,
int32_t center_x,
int32_t ry,
int32_t rx,
const BorderType border_type = BorderType::REPLICATE) const
{
assert(center_y >= 0 && center_y < dims[0] && "center_y out of bounds");
assert(center_x >= 0 && center_x < dims[1] && "center_x out of bounds");
Matrix patch(2 * ry + 1, 2 * rx + 1);
for (int32_t y = center_y - ry, r = 0; y <= center_y + ry; ++y, ++r) {
for (int32_t x = center_x - rx, c = 0; x <= center_x + rx;
++x, ++c) {
switch (border_type) {
case BorderType::REPLICATE:
patch(r, c) = (*this)(this->clamp_row_index(y),
this->clamp_col_index(x));
}
}
}
return patch;
}
template <typename OtherType>
Matrix<OtherType, Dynamic, Dynamic> as_type() const
{
return apply([](auto e) { return OtherType(e); });
}
Matrix clip(Dtype new_min, Dtype new_max) const
{
Matrix new_m(dims);
for (int32_t i = 0; i < this->size(); ++i) {
for (int32_t c = 0; c < new_m[0].size(); ++c) {
auto e = std::round((*this)[i][c]);
if (e < new_min) {
new_m[i][c] = new_min;
} else if (e > new_max) {
new_m[i][c] = new_max;
} else {
new_m[i][c] = e;
}
}
}
return new_m;
}
std::string str() const
{
std::stringstream ss;
ss << "[";
for (int32_t i = 0; i < dims[0] - 1; ++i) {
for (int32_t j = 0; j < dims[1] - 1; ++j) {
ss << (*this)(i, j) << " ";
}
ss << (*this)(i, dims[1] - 1) << ";" << std::endl;
}
for (int32_t j = 0; j < dims[1] - 1; ++j) {
ss << (*this)(dims[0] - 1, j) << " ";
}
ss << this->back() << "]";
return ss.str();
}
// Template magic from: http://stackoverflow.com/a/26383814
template <typename UnaryFunctor,
typename OutputType = typename std::result_of<
UnaryFunctor&(Vector<Dtype, Length>)>::type>
decltype(auto) apply(UnaryFunctor f) const
{
Matrix<OutputType, Dynamic, Dynamic> new_m(dims);
std::transform(std::begin(*this), std::end(*this), std::begin(new_m),
f);
return new_m;
}
};
// Static aliases
template <typename T>
using Matrix44 = Matrix<T, 4, 4>;
using Matrix44d = Matrix44<double>;
template <typename T>
using Matrix33 = Matrix<T, 3, 3>;
using Matrix33i = Matrix33<int32_t>;
using Matrix33d = Matrix33<double>;
using Matrix33f = Matrix33<float>;
using Matrix33b = Matrix33<uint8_t>;
// Dynamic aliases
template <typename T>
using MatrixX = Matrix<T, Dynamic, Dynamic>;
using MatrixXd = MatrixX<double>;
using MatrixXi = MatrixX<int32_t>;
using MatrixXb = MatrixX<uint8_t>;
}
#endif
<|endoftext|>
|
<commit_before>// Copyright 2015 Project Vogue. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <unordered_set>
#include "elang/optimizer/validator.h"
#include "base/logging.h"
#include "base/numerics/safe_conversions.h"
#include "elang/optimizer/depth_first_traversal.h"
#include "elang/optimizer/error_code.h"
#include "elang/optimizer/factory.h"
#include "elang/optimizer/function.h"
#include "elang/optimizer/nodes.h"
#include "elang/optimizer/node_visitor.h"
#include "elang/optimizer/types.h"
namespace elang {
namespace optimizer {
//////////////////////////////////////////////////////////////////////
//
// Validator::Context
//
class Validator::Context : public NodeVisitor {
public:
explicit Context(Validator* validator);
~Context() = default;
bool is_valid() const { return is_valid_; }
private:
void Error(ErrorCode error_code, Node* node, Thing* detail);
void Error(ErrorCode error_code, Node* node);
void ErrorInInput(Node* node, int index);
void ValidatePhiInputs(Node* node,
PhiOwnerNode* owner,
const ZoneDeque<PhiInputHolder*>& phi_inputs);
// NodeVisitor member functions
void DoDefaultVisit(Node* node) final;
void VisitCall(CallNode* node) final;
void VisitEffectGet(EffectGetNode* node) final;
void VisitEffectPhi(EffectPhiNode* node) final;
void VisitElement(ElementNode* node) final;
void VisitEntry(EntryNode* node) final;
void VisitExit(ExitNode* node) final;
void VisitGet(GetNode* node) final;
void VisitIf(IfNode* node) final;
void VisitIfFalse(IfFalseNode* node) final;
void VisitIfTrue(IfTrueNode* node) final;
void VisitLength(LengthNode* node) final;
void VisitLoad(LoadNode* node) final;
void VisitPhi(PhiNode* node) final;
void VisitRet(RetNode* node) final;
void VisitParameter(ParameterNode* node) final;
bool is_valid_;
Validator* const validator_;
DISALLOW_COPY_AND_ASSIGN(Context);
};
Validator::Context::Context(Validator* validator)
: is_valid_(true), validator_(validator) {
}
void Validator::Context::Error(ErrorCode error_code,
Node* node,
Thing* detail) {
validator_->Error(error_code, node, detail);
is_valid_ = false;
}
void Validator::Context::Error(ErrorCode error_code, Node* node) {
validator_->Error(error_code, node);
is_valid_ = false;
}
void Validator::Context::ErrorInInput(Node* node, int index) {
Error(ErrorCode::ValidateNodeInvalidInput, node, validator_->NewInt32(index));
}
void Validator::Context::ValidatePhiInputs(
Node* node,
PhiOwnerNode* owner,
const ZoneDeque<PhiInputHolder*>& phi_inputs) {
std::unordered_set<Node*> predecessors;
for (auto predecessor : owner->inputs())
predecessors.insert(predecessor);
std::unordered_set<Node*> controls;
auto index = 0;
for (auto const phi_input : phi_inputs) {
auto const input = phi_input->value();
if (input->output_type() != node->output_type())
ErrorInInput(node, index);
if (!input->IsValidEffect() && !input->IsValidData())
ErrorInInput(node, index);
auto const control = phi_input->control();
if (controls.count(control))
ErrorInInput(node, index);
if (!predecessors.count(control))
ErrorInInput(node, index);
controls.insert(control);
++index;
}
for (auto predecessor : owner->inputs()) {
if (controls.count(predecessor))
continue;
Error(ErrorCode::ValidatePhiNodeMissing, node, predecessor);
}
}
// NodeVisitor functions
void Validator::Context::DoDefaultVisit(Node* node) {
}
void Validator::Context::VisitCall(CallNode* node) {
auto const tuple_type = node->output_type()->as<TupleType>();
if (!tuple_type || tuple_type->size() != 3)
return Error(ErrorCode::ValidateEntryNodeInvalidOutput, node);
if (!tuple_type->get(0)->is<ControlType>())
return Error(ErrorCode::ValidateEntryNodeInvalidOutput, node);
if (!tuple_type->get(1)->is<EffectType>())
return Error(ErrorCode::ValidateEntryNodeInvalidOutput, node);
if (!node->input(0)->output_type()->is<ControlType>())
ErrorInInput(node, 0);
if (!node->input(1)->output_type()->is<EffectType>())
ErrorInInput(node, 1);
auto const callee_type = node->input(2)->output_type()->as<FunctionType>();
if (!callee_type)
return ErrorInInput(node, 2);
if (tuple_type->get(2) != callee_type->return_type())
ErrorInInput(node, 2);
if (node->input(3)->output_type() != callee_type->parameters_type())
ErrorInInput(node, 3);
}
void Validator::Context::VisitEffectGet(EffectGetNode* node) {
if (!node->output_type()->is<EffectType>())
Error(ErrorCode::ValidateNodeInvalidOutput, node);
if (!node->input(0)->IsValidEffectAt(node->field()))
ErrorInInput(node, 0);
}
void Validator::Context::VisitEffectPhi(EffectPhiNode* node) {
if (!node->owner()->IsValidControl())
return Error(ErrorCode::ValidatePhiNodeInvalidOwner, node, node->owner());
ValidatePhiInputs(node, node->owner(), node->phi_inputs());
}
void Validator::Context::VisitElement(ElementNode* node) {
auto const pointer_type = node->input(0)->output_type()->as<PointerType>();
if (!pointer_type)
return ErrorInInput(node, 0);
auto const array_type = pointer_type->pointee()->as<ArrayType>();
if (!array_type)
return ErrorInInput(node, 0);
if (node->output_type() != array_type->element_type())
return Error(ErrorCode::ValidateNodeInvalidOutput, node);
if (array_type->rank() == 1) {
if (!node->input(1)->output_type()->is<Int32Type>())
ErrorInInput(node, 1);
return;
}
auto const indexes_type = node->input(1)->output_type()->as<TupleType>();
if (!indexes_type || array_type->rank() != indexes_type->size())
return ErrorInInput(node, 1);
for (auto const type : indexes_type->components()) {
if (!type->is<Int32Type>())
return ErrorInInput(node, 1);
}
}
void Validator::Context::VisitEntry(EntryNode* node) {
auto const tuple_type = node->output_type()->as<TupleType>();
if (!tuple_type || tuple_type->size() != 3)
return Error(ErrorCode::ValidateEntryNodeInvalidOutput, node);
if (!tuple_type->get(0)->is<ControlType>())
Error(ErrorCode::ValidateEntryNodeNoControlOutput, node);
if (!tuple_type->get(1)->is<EffectType>())
Error(ErrorCode::ValidateEntryNodeNoEffectOutput, node);
if (node->users().empty())
Error(ErrorCode::ValidateEntryNodeNoUsers, node);
}
void Validator::Context::VisitExit(ExitNode* node) {
if (!node->input(0)->IsValidControl())
ErrorInInput(node, 0);
}
void Validator::Context::VisitGet(GetNode* node) {
auto const tuple_type = node->input(0)->output_type()->as<TupleType>();
if (!tuple_type)
return ErrorInInput(node, 0);
if (node->field() >= tuple_type->size())
return ErrorInInput(node, 0);
}
void Validator::Context::VisitIf(IfNode* node) {
if (!node->input(0)->IsValidControl())
ErrorInInput(node, 0);
if (!node->input(1)->IsValidData())
ErrorInInput(node, 1);
if (!node->input(1)->output_type()->is<BoolType>())
ErrorInInput(node, 1);
}
void Validator::Context::VisitIfFalse(IfFalseNode* node) {
if (!node->input(0)->IsValidControl())
ErrorInInput(node, 0);
if (!node->input(0)->is<IfNode>())
ErrorInInput(node, 0);
}
void Validator::Context::VisitIfTrue(IfTrueNode* node) {
if (!node->input(0)->IsValidControl())
ErrorInInput(node, 0);
if (!node->input(0)->is<IfNode>())
ErrorInInput(node, 0);
}
void Validator::Context::VisitLength(LengthNode* node) {
auto const pointer_type = node->input(0)->output_type()->as<PointerType>();
if (!pointer_type)
return ErrorInInput(node, 0);
auto const array_type = pointer_type->pointee()->as<ArrayType>();
if (!array_type)
return ErrorInInput(node, 0);
if (node->output_type() != array_type->element_type())
return Error(ErrorCode::ValidateNodeInvalidOutput, node);
auto const rank_node = node->input(1)->as<Int32Node>();
if (!rank_node)
return ErrorInInput(node, 1);
if (rank_node->data() >= base::checked_cast<int>(array_type->rank()))
return ErrorInInput(node, 1);
}
void Validator::Context::VisitLoad(LoadNode* node) {
if (!node->input(0)->IsValidEffect())
ErrorInInput(node, 0);
if (!node->input(1)->IsValidData())
ErrorInInput(node, 1);
if (!node->input(1)->output_type()->is<PointerType>())
ErrorInInput(node, 1);
if (!node->input(2)->IsValidData())
ErrorInInput(node, 2);
auto const pointer_type = node->input(2)->output_type()->as<PointerType>();
if (!pointer_type || node->output_type() != pointer_type->pointee())
ErrorInInput(node, 1);
}
void Validator::Context::VisitParameter(ParameterNode* node) {
auto const entry_node = node->input(0)->as<EntryNode>();
if (!entry_node) {
ErrorInInput(node, 0);
return;
}
if (node->output_type() != entry_node->parameter_type(node->field())) {
Error(ErrorCode::ValidateNodeInvalidOutput, node);
return;
}
}
void Validator::Context::VisitPhi(PhiNode* node) {
if (!node->owner()->IsValidControl())
return Error(ErrorCode::ValidatePhiNodeInvalidOwner, node, node->owner());
ValidatePhiInputs(node, node->owner(), node->phi_inputs());
}
void Validator::Context::VisitRet(RetNode* node) {
if (!node->input(0)->IsValidControl())
ErrorInInput(node, 0);
if (!node->input(1)->IsValidEffect())
ErrorInInput(node, 1);
if (!node->input(2)->IsValidData())
ErrorInInput(node, 2);
}
//////////////////////////////////////////////////////////////////////
//
// Validator
//
Validator::Validator(Factory* factory, const Function* function)
: ErrorReporter(factory), factory_(factory), function_(function) {
}
Validator::~Validator() {
}
Node* Validator::NewInt32(int data) {
return factory_->NewInt32(data);
}
bool Validator::Validate(Node* node) {
Context context(this);
node->Accept(&context);
return context.is_valid();
}
bool Validator::Validate() {
DepthFirstTraversal<OnInputEdge, const Function> walker;
Context context(this);
walker.Traverse(function_, &context);
return context.is_valid();
}
} // namespace optimizer
} // namespace elang
<commit_msg>elang/optimizer: Make |Validator| to work with |ElementNode| and |LengthNode| correctlly.<commit_after>// Copyright 2015 Project Vogue. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <unordered_set>
#include "elang/optimizer/validator.h"
#include "base/logging.h"
#include "base/numerics/safe_conversions.h"
#include "elang/optimizer/depth_first_traversal.h"
#include "elang/optimizer/error_code.h"
#include "elang/optimizer/factory.h"
#include "elang/optimizer/function.h"
#include "elang/optimizer/nodes.h"
#include "elang/optimizer/node_visitor.h"
#include "elang/optimizer/types.h"
namespace elang {
namespace optimizer {
//////////////////////////////////////////////////////////////////////
//
// Validator::Context
//
class Validator::Context : public NodeVisitor {
public:
explicit Context(Validator* validator);
~Context() = default;
bool is_valid() const { return is_valid_; }
private:
void Error(ErrorCode error_code, Node* node, Thing* detail);
void Error(ErrorCode error_code, Node* node);
void ErrorInInput(Node* node, int index);
void ValidatePhiInputs(Node* node,
PhiOwnerNode* owner,
const ZoneDeque<PhiInputHolder*>& phi_inputs);
// NodeVisitor member functions
void DoDefaultVisit(Node* node) final;
void VisitCall(CallNode* node) final;
void VisitEffectGet(EffectGetNode* node) final;
void VisitEffectPhi(EffectPhiNode* node) final;
void VisitElement(ElementNode* node) final;
void VisitEntry(EntryNode* node) final;
void VisitExit(ExitNode* node) final;
void VisitGet(GetNode* node) final;
void VisitIf(IfNode* node) final;
void VisitIfFalse(IfFalseNode* node) final;
void VisitIfTrue(IfTrueNode* node) final;
void VisitLength(LengthNode* node) final;
void VisitLoad(LoadNode* node) final;
void VisitPhi(PhiNode* node) final;
void VisitRet(RetNode* node) final;
void VisitParameter(ParameterNode* node) final;
bool is_valid_;
Validator* const validator_;
DISALLOW_COPY_AND_ASSIGN(Context);
};
Validator::Context::Context(Validator* validator)
: is_valid_(true), validator_(validator) {
}
void Validator::Context::Error(ErrorCode error_code,
Node* node,
Thing* detail) {
validator_->Error(error_code, node, detail);
is_valid_ = false;
}
void Validator::Context::Error(ErrorCode error_code, Node* node) {
validator_->Error(error_code, node);
is_valid_ = false;
}
void Validator::Context::ErrorInInput(Node* node, int index) {
Error(ErrorCode::ValidateNodeInvalidInput, node, validator_->NewInt32(index));
}
void Validator::Context::ValidatePhiInputs(
Node* node,
PhiOwnerNode* owner,
const ZoneDeque<PhiInputHolder*>& phi_inputs) {
std::unordered_set<Node*> predecessors;
for (auto predecessor : owner->inputs())
predecessors.insert(predecessor);
std::unordered_set<Node*> controls;
auto index = 0;
for (auto const phi_input : phi_inputs) {
auto const input = phi_input->value();
if (input->output_type() != node->output_type())
ErrorInInput(node, index);
if (!input->IsValidEffect() && !input->IsValidData())
ErrorInInput(node, index);
auto const control = phi_input->control();
if (controls.count(control))
ErrorInInput(node, index);
if (!predecessors.count(control))
ErrorInInput(node, index);
controls.insert(control);
++index;
}
for (auto predecessor : owner->inputs()) {
if (controls.count(predecessor))
continue;
Error(ErrorCode::ValidatePhiNodeMissing, node, predecessor);
}
}
// NodeVisitor functions
void Validator::Context::DoDefaultVisit(Node* node) {
}
void Validator::Context::VisitCall(CallNode* node) {
auto const tuple_type = node->output_type()->as<TupleType>();
if (!tuple_type || tuple_type->size() != 3)
return Error(ErrorCode::ValidateEntryNodeInvalidOutput, node);
if (!tuple_type->get(0)->is<ControlType>())
return Error(ErrorCode::ValidateEntryNodeInvalidOutput, node);
if (!tuple_type->get(1)->is<EffectType>())
return Error(ErrorCode::ValidateEntryNodeInvalidOutput, node);
if (!node->input(0)->output_type()->is<ControlType>())
ErrorInInput(node, 0);
if (!node->input(1)->output_type()->is<EffectType>())
ErrorInInput(node, 1);
auto const callee_type = node->input(2)->output_type()->as<FunctionType>();
if (!callee_type)
return ErrorInInput(node, 2);
if (tuple_type->get(2) != callee_type->return_type())
ErrorInInput(node, 2);
if (node->input(3)->output_type() != callee_type->parameters_type())
ErrorInInput(node, 3);
}
void Validator::Context::VisitEffectGet(EffectGetNode* node) {
if (!node->output_type()->is<EffectType>())
Error(ErrorCode::ValidateNodeInvalidOutput, node);
if (!node->input(0)->IsValidEffectAt(node->field()))
ErrorInInput(node, 0);
}
void Validator::Context::VisitEffectPhi(EffectPhiNode* node) {
if (!node->owner()->IsValidControl())
return Error(ErrorCode::ValidatePhiNodeInvalidOwner, node, node->owner());
ValidatePhiInputs(node, node->owner(), node->phi_inputs());
}
void Validator::Context::VisitElement(ElementNode* node) {
auto const array_pointer_type =
node->input(0)->output_type()->as<PointerType>();
if (!array_pointer_type)
return ErrorInInput(node, 0);
auto const array_type = array_pointer_type->pointee()->as<ArrayType>();
if (!array_type)
return ErrorInInput(node, 0);
auto const pointer_type = node->output_type()->as<PointerType>();
if (pointer_type && (pointer_type->pointee() != array_type->element_type()))
return Error(ErrorCode::ValidateNodeInvalidOutput, node);
if (array_type->rank() == 1) {
if (!node->input(1)->output_type()->is<Int32Type>())
ErrorInInput(node, 1);
return;
}
auto const indexes_type = node->input(1)->output_type()->as<TupleType>();
if (!indexes_type || array_type->rank() != indexes_type->size())
return ErrorInInput(node, 1);
for (auto const type : indexes_type->components()) {
if (!type->is<Int32Type>())
return ErrorInInput(node, 1);
}
}
void Validator::Context::VisitEntry(EntryNode* node) {
auto const tuple_type = node->output_type()->as<TupleType>();
if (!tuple_type || tuple_type->size() != 3)
return Error(ErrorCode::ValidateEntryNodeInvalidOutput, node);
if (!tuple_type->get(0)->is<ControlType>())
Error(ErrorCode::ValidateEntryNodeNoControlOutput, node);
if (!tuple_type->get(1)->is<EffectType>())
Error(ErrorCode::ValidateEntryNodeNoEffectOutput, node);
if (node->users().empty())
Error(ErrorCode::ValidateEntryNodeNoUsers, node);
}
void Validator::Context::VisitExit(ExitNode* node) {
if (!node->input(0)->IsValidControl())
ErrorInInput(node, 0);
}
void Validator::Context::VisitGet(GetNode* node) {
auto const tuple_type = node->input(0)->output_type()->as<TupleType>();
if (!tuple_type)
return ErrorInInput(node, 0);
if (node->field() >= tuple_type->size())
return ErrorInInput(node, 0);
}
void Validator::Context::VisitIf(IfNode* node) {
if (!node->input(0)->IsValidControl())
ErrorInInput(node, 0);
if (!node->input(1)->IsValidData())
ErrorInInput(node, 1);
if (!node->input(1)->output_type()->is<BoolType>())
ErrorInInput(node, 1);
}
void Validator::Context::VisitIfFalse(IfFalseNode* node) {
if (!node->input(0)->IsValidControl())
ErrorInInput(node, 0);
if (!node->input(0)->is<IfNode>())
ErrorInInput(node, 0);
}
void Validator::Context::VisitIfTrue(IfTrueNode* node) {
if (!node->input(0)->IsValidControl())
ErrorInInput(node, 0);
if (!node->input(0)->is<IfNode>())
ErrorInInput(node, 0);
}
void Validator::Context::VisitLength(LengthNode* node) {
auto const pointer_type = node->input(0)->output_type()->as<PointerType>();
if (!pointer_type)
return ErrorInInput(node, 0);
auto const array_type = pointer_type->pointee()->as<ArrayType>();
if (!array_type)
return ErrorInInput(node, 0);
auto const rank_node = node->input(1)->as<Int32Node>();
if (!rank_node)
return ErrorInInput(node, 1);
if (rank_node->data() >= base::checked_cast<int>(array_type->rank()))
return ErrorInInput(node, 1);
}
void Validator::Context::VisitLoad(LoadNode* node) {
if (!node->input(0)->IsValidEffect())
ErrorInInput(node, 0);
if (!node->input(1)->IsValidData())
ErrorInInput(node, 1);
if (!node->input(1)->output_type()->is<PointerType>())
ErrorInInput(node, 1);
if (!node->input(2)->IsValidData())
ErrorInInput(node, 2);
auto const pointer_type = node->input(2)->output_type()->as<PointerType>();
if (!pointer_type || node->output_type() != pointer_type->pointee())
ErrorInInput(node, 1);
}
void Validator::Context::VisitParameter(ParameterNode* node) {
auto const entry_node = node->input(0)->as<EntryNode>();
if (!entry_node) {
ErrorInInput(node, 0);
return;
}
if (node->output_type() != entry_node->parameter_type(node->field())) {
Error(ErrorCode::ValidateNodeInvalidOutput, node);
return;
}
}
void Validator::Context::VisitPhi(PhiNode* node) {
if (!node->owner()->IsValidControl())
return Error(ErrorCode::ValidatePhiNodeInvalidOwner, node, node->owner());
ValidatePhiInputs(node, node->owner(), node->phi_inputs());
}
void Validator::Context::VisitRet(RetNode* node) {
if (!node->input(0)->IsValidControl())
ErrorInInput(node, 0);
if (!node->input(1)->IsValidEffect())
ErrorInInput(node, 1);
if (!node->input(2)->IsValidData())
ErrorInInput(node, 2);
}
//////////////////////////////////////////////////////////////////////
//
// Validator
//
Validator::Validator(Factory* factory, const Function* function)
: ErrorReporter(factory), factory_(factory), function_(function) {
}
Validator::~Validator() {
}
Node* Validator::NewInt32(int data) {
return factory_->NewInt32(data);
}
bool Validator::Validate(Node* node) {
Context context(this);
node->Accept(&context);
return context.is_valid();
}
bool Validator::Validate() {
DepthFirstTraversal<OnInputEdge, const Function> walker;
Context context(this);
walker.Traverse(function_, &context);
return context.is_valid();
}
} // namespace optimizer
} // namespace elang
<|endoftext|>
|
<commit_before>#include <babylon/engines/extensions/multi_render_extension.h>
#include <babylon/core/logging.h>
#include <babylon/engines/thin_engine.h>
#include <babylon/materials/textures/imulti_render_target_options.h>
#include <babylon/materials/textures/internal_texture.h>
#include <babylon/maths/isize.h>
namespace BABYLON {
MultiRenderExtension::MultiRenderExtension(ThinEngine* engine) : _this{engine}
{
}
MultiRenderExtension::~MultiRenderExtension() = default;
void MultiRenderExtension::unBindMultiColorAttachmentFramebuffer(
const std::vector<InternalTexturePtr>& textures, bool disableGenerateMipMaps,
const std::function<void()>& onBeforeUnbind)
{
_this->_currentRenderTarget = nullptr;
// If MSAA, we need to bitblt back to main texture
auto& gl = *_this->_gl;
auto& attachments = textures[0]->_attachments;
auto count = attachments.size();
if (textures[0]->_MSAAFramebuffer) {
gl.bindFramebuffer(GL::READ_FRAMEBUFFER, textures[0]->_MSAAFramebuffer.get());
gl.bindFramebuffer(GL::DRAW_FRAMEBUFFER, textures[0]->_framebuffer.get());
for (size_t i = 0; i < count; ++i) {
const auto iStr = std::to_string(i);
auto& texture = textures[i];
for (size_t j = 0; j < count; ++j) {
attachments[j] = GL::NONE;
}
attachments[i] = gl[_this->webGLVersion() > 1.f ? "COLOR_ATTACHMENT" + iStr :
"COLOR_ATTACHMENT" + iStr + "_WEBGL"];
gl.readBuffer(attachments[i]);
gl.drawBuffers(attachments);
gl.blitFramebuffer(0, 0, texture->width, texture->height, 0, 0, texture->width,
texture->height, GL::COLOR_BUFFER_BIT, GL::NEAREST);
}
for (size_t i = 0; i < count; i++) {
const auto iStr = std::to_string(i);
attachments[i] = gl[_this->webGLVersion() > 1.f ? "COLOR_ATTACHMENT" + iStr :
"COLOR_ATTACHMENT" + iStr + "_WEBGL"];
}
gl.drawBuffers(attachments);
}
for (size_t i = 0; i < count; ++i) {
const auto& texture = textures[i];
if (texture->generateMipMaps && !disableGenerateMipMaps && !texture->isCube) {
_this->_bindTextureDirectly(GL::TEXTURE_2D, texture);
gl.generateMipmap(GL::TEXTURE_2D);
_this->_bindTextureDirectly(GL::TEXTURE_2D, nullptr);
}
}
if (onBeforeUnbind) {
if (textures[0]->_MSAAFramebuffer) {
// Bind the correct framebuffer
_this->_bindUnboundFramebuffer(textures[0]->_framebuffer);
}
onBeforeUnbind();
}
_this->_bindUnboundFramebuffer(nullptr);
}
std::vector<InternalTexturePtr>
MultiRenderExtension::createMultipleRenderTarget(ISize size,
const IMultiRenderTargetOptions& options)
{
auto generateMipMaps = options.generateMipMaps.value_or(false);
auto generateDepthBuffer = options.generateDepthBuffer.value_or(true);
auto generateStencilBuffer = options.generateStencilBuffer.value_or(false);
auto generateDepthTexture = options.generateDepthTexture.value_or(false);
auto textureCount = options.textureCount.value_or(1);
auto defaultType = Constants::TEXTURETYPE_UNSIGNED_INT;
auto defaultSamplingMode = Constants::TEXTURE_TRILINEAR_SAMPLINGMODE;
const auto& types = options.types;
const auto& samplingModes = options.samplingModes;
auto width = size.width;
auto height = size.height;
auto& gl = *_this->_gl;
// Create the framebuffer
auto framebuffer = gl.createFramebuffer();
_this->_bindUnboundFramebuffer(framebuffer);
std::vector<InternalTexturePtr> textures;
std::vector<GL::GLenum> attachments;
auto depthStencilBuffer = _this->_setupFramebufferDepthAttachments(
generateStencilBuffer, generateDepthBuffer, width, height);
for (unsigned int i = 0; i < textureCount; ++i) {
const auto iStr = std::to_string(i);
auto samplingMode = (i < samplingModes.size()) ? samplingModes[i] : defaultSamplingMode;
auto type = (i < types.size()) ? types[i] : defaultType;
if (type == Constants::TEXTURETYPE_FLOAT && !_this->_caps.textureFloatLinearFiltering) {
// if floating point linear (GL::FLOAT) then force to NEAREST_SAMPLINGMODE
samplingMode = Constants::TEXTURE_NEAREST_SAMPLINGMODE;
}
else if (type == Constants::TEXTURETYPE_HALF_FLOAT
&& !_this->_caps.textureHalfFloatLinearFiltering) {
// if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
samplingMode = Constants::TEXTURE_NEAREST_SAMPLINGMODE;
}
auto filters = _this->_getSamplingParameters(samplingMode, generateMipMaps);
if (type == Constants::TEXTURETYPE_FLOAT && !_this->_caps.textureFloat) {
type = Constants::TEXTURETYPE_UNSIGNED_INT;
BABYLON_LOG_WARN(
"MultiRenderExtension",
"Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type")
}
auto texture = InternalTexture::New(_this, InternalTextureSource::MultiRenderTarget);
auto attachment = gl[_this->webGLVersion() > 1.f ? "COLOR_ATTACHMENT" + iStr :
"COLOR_ATTACHMENT" + iStr + "_WEBGL"];
textures.emplace_back(texture);
attachments.emplace_back(attachment);
gl.activeTexture(gl["TEXTURE" + iStr]);
gl.bindTexture(GL::TEXTURE_2D, texture->_webGLTexture.get());
gl.texParameteri(GL::TEXTURE_2D, GL::TEXTURE_MAG_FILTER, filters.mag);
gl.texParameteri(GL::TEXTURE_2D, GL::TEXTURE_MIN_FILTER, filters.min);
gl.texParameteri(GL::TEXTURE_2D, GL::TEXTURE_WRAP_S, GL::CLAMP_TO_EDGE);
gl.texParameteri(GL::TEXTURE_2D, GL::TEXTURE_WRAP_T, GL::CLAMP_TO_EDGE);
gl.texImage2D(GL::TEXTURE_2D, 0,
static_cast<int>(_this->_getRGBABufferInternalSizedFormat(type)), width, height,
0, GL::RGBA, _this->_getWebGLTextureType(type), nullptr);
gl.framebufferTexture2D(GL::DRAW_FRAMEBUFFER, attachment, GL::TEXTURE_2D,
texture->_webGLTexture.get(), 0);
if (generateMipMaps) {
gl.generateMipmap(GL::TEXTURE_2D);
}
// Unbind
_this->_bindTextureDirectly(GL::TEXTURE_2D, nullptr);
texture->_framebuffer = std::move(framebuffer);
texture->_depthStencilBuffer = std::move(depthStencilBuffer);
texture->baseWidth = width;
texture->baseHeight = height;
texture->width = width;
texture->height = height;
texture->isReady = true;
texture->samples = 1;
texture->generateMipMaps = generateMipMaps;
texture->samplingMode = samplingMode;
texture->type = type;
texture->_generateDepthBuffer = generateDepthBuffer;
texture->_generateStencilBuffer = generateStencilBuffer;
texture->_attachments = attachments;
texture->_textureArray = textures;
_this->_internalTexturesCache.emplace_back(texture);
}
if (generateDepthTexture && _this->_caps.depthTextureExtension) {
// Depth texture
auto depthTexture = InternalTexture::New(_this, InternalTextureSource::MultiRenderTarget);
gl.activeTexture(GL::TEXTURE0);
gl.bindTexture(GL::TEXTURE_2D, depthTexture->_webGLTexture.get());
gl.texParameteri(GL::TEXTURE_2D, GL::TEXTURE_MAG_FILTER, GL::NEAREST);
gl.texParameteri(GL::TEXTURE_2D, GL::TEXTURE_MIN_FILTER, GL::NEAREST);
gl.texParameteri(GL::TEXTURE_2D, GL::TEXTURE_WRAP_S, GL::CLAMP_TO_EDGE);
gl.texParameteri(GL::TEXTURE_2D, GL::TEXTURE_WRAP_T, GL::CLAMP_TO_EDGE);
gl.texImage2D(GL::TEXTURE_2D, //
0, //
_this->webGLVersion() < 2.f ? GL::DEPTH_COMPONENT : GL::DEPTH_COMPONENT16, //
width, //
height, //
0, //
GL::DEPTH_COMPONENT, //
GL::UNSIGNED_SHORT, //
nullptr //
);
gl.framebufferTexture2D(GL::FRAMEBUFFER, //
GL::DEPTH_ATTACHMENT, //
GL::TEXTURE_2D, //
depthTexture->_webGLTexture.get(), //
0 //
);
depthTexture->_framebuffer = std::move(framebuffer);
depthTexture->baseWidth = width;
depthTexture->baseHeight = height;
depthTexture->width = width;
depthTexture->height = height;
depthTexture->isReady = true;
depthTexture->samples = 1;
depthTexture->generateMipMaps = generateMipMaps;
depthTexture->samplingMode = GL::NEAREST;
depthTexture->_generateDepthBuffer = generateDepthBuffer;
depthTexture->_generateStencilBuffer = generateStencilBuffer;
textures.emplace_back(depthTexture);
_this->_internalTexturesCache.emplace_back(depthTexture);
}
gl.drawBuffers(attachments);
_this->_bindUnboundFramebuffer(nullptr);
_this->resetTextureCache();
return textures;
}
unsigned int MultiRenderExtension::updateMultipleRenderTargetTextureSampleCount(
const std::vector<InternalTexturePtr>& textures, unsigned int samples)
{
if (_this->webGLVersion() < 2.f || textures.empty()) {
return 1;
}
if (textures[0]->samples == samples) {
return samples;
}
auto count = textures[0]->_attachments.size();
if (count == 0) {
return 1;
}
auto& gl = *_this->_gl;
samples = std::min(samples, _this->getCaps().maxMSAASamples);
// Dispose previous render buffers
if (textures[0]->_depthStencilBuffer) {
gl.deleteRenderbuffer(textures[0]->_depthStencilBuffer.get());
textures[0]->_depthStencilBuffer = nullptr;
}
if (textures[0]->_MSAAFramebuffer) {
gl.deleteFramebuffer(textures[0]->_MSAAFramebuffer.get());
textures[0]->_MSAAFramebuffer = nullptr;
}
for (size_t i = 0; i < count; i++) {
const auto& texture = textures[i];
if (texture->_MSAARenderBuffer) {
gl.deleteRenderbuffer(texture->_MSAARenderBuffer.get());
texture->_MSAARenderBuffer = nullptr;
}
}
if (samples > 1) {
auto framebuffer = gl.createFramebuffer();
if (!framebuffer) {
throw std::runtime_error("Unable to create multi sampled framebuffer");
}
_this->_bindUnboundFramebuffer(framebuffer);
auto depthStencilBuffer = _this->_setupFramebufferDepthAttachments(
textures[0]->_generateStencilBuffer, textures[0]->_generateDepthBuffer, textures[0]->width,
textures[0]->height, static_cast<int>(samples));
Uint32Array attachments;
for (size_t i = 0; i < count; ++i) {
auto iStr = std::to_string(i);
auto& texture = textures[i];
auto attachment = gl[_this->webGLVersion() > 1.f ? "COLOR_ATTACHMENT" + iStr :
"COLOR_ATTACHMENT" + iStr + "_WEBGL"];
auto colorRenderbuffer = gl.createRenderbuffer();
if (!colorRenderbuffer) {
throw std::runtime_error("Unable to create multi sampled framebuffer");
}
gl.bindRenderbuffer(GL::RENDERBUFFER, colorRenderbuffer.get());
gl.renderbufferStorageMultisample(GL::RENDERBUFFER, static_cast<int>(samples),
_this->_getRGBAMultiSampleBufferFormat(texture->type),
texture->width, texture->height);
gl.framebufferRenderbuffer(GL::FRAMEBUFFER, attachment, GL::RENDERBUFFER,
colorRenderbuffer.get());
texture->_MSAAFramebuffer = framebuffer;
texture->_MSAARenderBuffer = std::move(colorRenderbuffer);
texture->samples = samples;
texture->_depthStencilBuffer = std::move(depthStencilBuffer);
gl.bindRenderbuffer(GL::RENDERBUFFER, nullptr);
attachments.emplace_back(attachment);
}
gl.drawBuffers(attachments);
}
else {
_this->_bindUnboundFramebuffer(textures[0]->_framebuffer);
}
_this->_bindUnboundFramebuffer(nullptr);
return samples;
}
void MultiRenderExtension::bindAttachments(const std::vector<unsigned int>& attachments)
{
auto& gl = *_this->_gl;
gl.drawBuffers(attachments);
}
void MultiRenderExtension::restoreSingleAttachment()
{
bindAttachments({GL::BACK});
}
std::vector<unsigned int>
MultiRenderExtension::buildTextureLayout(const std::vector<bool>& textureStatus) const
{
auto& gl = *_this->_gl;
std::vector<unsigned int> result;
for (auto i = 0ull; i < textureStatus.size(); ++i) {
if (textureStatus[i]) {
result.emplace_back(gl["COLOR_ATTACHMENT" + std::to_string(i)]);
}
else {
result.emplace_back(GL::NONE);
}
}
return result;
}
} // end of namespace BABYLON
<commit_msg>Formatting and using hardware texture<commit_after>#include <babylon/engines/extensions/multi_render_extension.h>
#include <babylon/core/logging.h>
#include <babylon/engines/thin_engine.h>
#include <babylon/materials/textures/imulti_render_target_options.h>
#include <babylon/materials/textures/internal_texture.h>
#include <babylon/maths/isize.h>
namespace BABYLON {
MultiRenderExtension::MultiRenderExtension(ThinEngine* engine) : _this{engine}
{
}
MultiRenderExtension::~MultiRenderExtension() = default;
void MultiRenderExtension::unBindMultiColorAttachmentFramebuffer(
const std::vector<InternalTexturePtr>& textures, bool disableGenerateMipMaps,
const std::function<void()>& onBeforeUnbind)
{
_this->_currentRenderTarget = nullptr;
// If MSAA, we need to bitblt back to main texture
auto& gl = *_this->_gl;
auto& attachments = textures[0]->_attachments;
auto count = attachments.size();
if (textures[0]->_MSAAFramebuffer) {
gl.bindFramebuffer(GL::READ_FRAMEBUFFER, textures[0]->_MSAAFramebuffer.get());
gl.bindFramebuffer(GL::DRAW_FRAMEBUFFER, textures[0]->_framebuffer.get());
for (size_t i = 0; i < count; ++i) {
const auto iStr = std::to_string(i);
auto& texture = textures[i];
for (size_t j = 0; j < count; ++j) {
attachments[j] = GL::NONE;
}
attachments[i] = gl[_this->webGLVersion() > 1.f ? "COLOR_ATTACHMENT" + iStr :
"COLOR_ATTACHMENT" + iStr + "_WEBGL"];
gl.readBuffer(attachments[i]);
gl.drawBuffers(attachments);
gl.blitFramebuffer(0, 0, texture->width, texture->height, 0, 0, texture->width,
texture->height, GL::COLOR_BUFFER_BIT, GL::NEAREST);
}
for (size_t i = 0; i < count; i++) {
const auto iStr = std::to_string(i);
attachments[i] = gl[_this->webGLVersion() > 1.f ? "COLOR_ATTACHMENT" + iStr :
"COLOR_ATTACHMENT" + iStr + "_WEBGL"];
}
gl.drawBuffers(attachments);
}
for (size_t i = 0; i < count; ++i) {
const auto& texture = textures[i];
if (texture->generateMipMaps && !disableGenerateMipMaps && !texture->isCube) {
_this->_bindTextureDirectly(GL::TEXTURE_2D, texture);
gl.generateMipmap(GL::TEXTURE_2D);
_this->_bindTextureDirectly(GL::TEXTURE_2D, nullptr);
}
}
if (onBeforeUnbind) {
if (textures[0]->_MSAAFramebuffer) {
// Bind the correct framebuffer
_this->_bindUnboundFramebuffer(textures[0]->_framebuffer);
}
onBeforeUnbind();
}
_this->_bindUnboundFramebuffer(nullptr);
}
std::vector<InternalTexturePtr> MultiRenderExtension::createMultipleRenderTarget(
ISize size, const IMultiRenderTargetOptions& options, bool initializeBuffers)
{
auto generateMipMaps = options.generateMipMaps.value_or(false);
auto generateDepthBuffer = options.generateDepthBuffer.value_or(true);
auto generateStencilBuffer = options.generateStencilBuffer.value_or(false);
auto generateDepthTexture = options.generateDepthTexture.value_or(false);
auto textureCount = options.textureCount.value_or(1);
auto defaultType = Constants::TEXTURETYPE_UNSIGNED_INT;
auto defaultSamplingMode = Constants::TEXTURE_TRILINEAR_SAMPLINGMODE;
const auto& types = options.types;
const auto& samplingModes = options.samplingModes;
auto width = size.width;
auto height = size.height;
auto& gl = *_this->_gl;
// Create the framebuffer
auto framebuffer = gl.createFramebuffer();
_this->_bindUnboundFramebuffer(framebuffer);
std::vector<InternalTexturePtr> textures;
std::vector<GL::GLenum> attachments;
auto depthStencilBuffer = _this->_setupFramebufferDepthAttachments(
generateStencilBuffer, generateDepthBuffer, width, height);
for (unsigned int i = 0; i < textureCount; ++i) {
const auto iStr = std::to_string(i);
auto samplingMode = (i < samplingModes.size()) ? samplingModes[i] : defaultSamplingMode;
auto type = (i < types.size()) ? types[i] : defaultType;
if (type == Constants::TEXTURETYPE_FLOAT && !_this->_caps.textureFloatLinearFiltering) {
// if floating point linear (GL::FLOAT) then force to NEAREST_SAMPLINGMODE
samplingMode = Constants::TEXTURE_NEAREST_SAMPLINGMODE;
}
else if (type == Constants::TEXTURETYPE_HALF_FLOAT
&& !_this->_caps.textureHalfFloatLinearFiltering) {
// if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
samplingMode = Constants::TEXTURE_NEAREST_SAMPLINGMODE;
}
auto filters = _this->_getSamplingParameters(samplingMode, generateMipMaps);
if (type == Constants::TEXTURETYPE_FLOAT && !_this->_caps.textureFloat) {
type = Constants::TEXTURETYPE_UNSIGNED_INT;
BABYLON_LOG_WARN(
"MultiRenderExtension",
"Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type")
}
auto texture = InternalTexture::New(_this, InternalTextureSource::MultiRenderTarget);
auto attachment = gl[_this->webGLVersion() > 1.f ? "COLOR_ATTACHMENT" + iStr :
"COLOR_ATTACHMENT" + iStr + "_WEBGL"];
textures.emplace_back(texture);
attachments.emplace_back(attachment);
gl.activeTexture(gl["TEXTURE" + iStr]);
gl.bindTexture(GL::TEXTURE_2D, texture->_hardwareTexture ?
texture->_hardwareTexture->underlyingResource().get() :
nullptr);
gl.texParameteri(GL::TEXTURE_2D, GL::TEXTURE_MAG_FILTER, filters.mag);
gl.texParameteri(GL::TEXTURE_2D, GL::TEXTURE_MIN_FILTER, filters.min);
gl.texParameteri(GL::TEXTURE_2D, GL::TEXTURE_WRAP_S, GL::CLAMP_TO_EDGE);
gl.texParameteri(GL::TEXTURE_2D, GL::TEXTURE_WRAP_T, GL::CLAMP_TO_EDGE);
gl.texImage2D(GL::TEXTURE_2D, 0,
static_cast<int>(_this->_getRGBABufferInternalSizedFormat(type)), width, height,
0, GL::RGBA, _this->_getWebGLTextureType(type), nullptr);
gl.framebufferTexture2D(
GL::DRAW_FRAMEBUFFER, attachment, GL::TEXTURE_2D,
texture->_hardwareTexture ? texture->_hardwareTexture->underlyingResource().get() : nullptr,
0);
if (generateMipMaps) {
gl.generateMipmap(GL::TEXTURE_2D);
}
// Unbind
_this->_bindTextureDirectly(GL::TEXTURE_2D, nullptr);
texture->_framebuffer = std::move(framebuffer);
texture->_depthStencilBuffer = std::move(depthStencilBuffer);
texture->baseWidth = width;
texture->baseHeight = height;
texture->width = width;
texture->height = height;
texture->isReady = true;
texture->samples = 1;
texture->generateMipMaps = generateMipMaps;
texture->samplingMode = samplingMode;
texture->type = type;
texture->_generateDepthBuffer = generateDepthBuffer;
texture->_generateStencilBuffer = generateStencilBuffer;
texture->_attachments = attachments;
texture->_textureArray = textures;
_this->_internalTexturesCache.emplace_back(texture);
}
if (generateDepthTexture && _this->_caps.depthTextureExtension) {
// Depth texture
auto depthTexture = InternalTexture::New(_this, InternalTextureSource::MultiRenderTarget);
GL::IGLTexture* depthTextureHardwareTexture
= depthTexture->_hardwareTexture ?
depthTexture->_hardwareTexture->underlyingResource().get() :
nullptr;
gl.activeTexture(GL::TEXTURE0);
gl.bindTexture(GL::TEXTURE_2D, depthTextureHardwareTexture);
gl.texParameteri(GL::TEXTURE_2D, GL::TEXTURE_MAG_FILTER, GL::NEAREST);
gl.texParameteri(GL::TEXTURE_2D, GL::TEXTURE_MIN_FILTER, GL::NEAREST);
gl.texParameteri(GL::TEXTURE_2D, GL::TEXTURE_WRAP_S, GL::CLAMP_TO_EDGE);
gl.texParameteri(GL::TEXTURE_2D, GL::TEXTURE_WRAP_T, GL::CLAMP_TO_EDGE);
gl.texImage2D(GL::TEXTURE_2D, //
0, //
_this->webGLVersion() < 2.f ? GL::DEPTH_COMPONENT : GL::DEPTH_COMPONENT16, //
width, //
height, //
0, //
GL::DEPTH_COMPONENT, //
GL::UNSIGNED_SHORT, //
nullptr //
);
gl.framebufferTexture2D(GL::FRAMEBUFFER, //
GL::DEPTH_ATTACHMENT, //
GL::TEXTURE_2D, //
depthTextureHardwareTexture, //
0 //
);
depthTexture->_framebuffer = std::move(framebuffer);
depthTexture->baseWidth = width;
depthTexture->baseHeight = height;
depthTexture->width = width;
depthTexture->height = height;
depthTexture->isReady = true;
depthTexture->samples = 1;
depthTexture->generateMipMaps = generateMipMaps;
depthTexture->samplingMode = GL::NEAREST;
depthTexture->_generateDepthBuffer = generateDepthBuffer;
depthTexture->_generateStencilBuffer = generateStencilBuffer;
textures.emplace_back(depthTexture);
_this->_internalTexturesCache.emplace_back(depthTexture);
}
if (initializeBuffers) {
gl.drawBuffers(attachments);
}
_this->_bindUnboundFramebuffer(nullptr);
_this->resetTextureCache();
return textures;
}
unsigned int MultiRenderExtension::updateMultipleRenderTargetTextureSampleCount(
const std::vector<InternalTexturePtr>& textures, unsigned int samples, bool initializeBuffers)
{
if (_this->webGLVersion() < 2.f || textures.empty()) {
return 1;
}
if (textures[0]->samples == samples) {
return samples;
}
auto count = textures[0]->_attachments.size();
if (count == 0) {
return 1;
}
auto& gl = *_this->_gl;
samples = std::min(samples, _this->getCaps().maxMSAASamples);
// Dispose previous render buffers
if (textures[0]->_depthStencilBuffer) {
gl.deleteRenderbuffer(textures[0]->_depthStencilBuffer.get());
textures[0]->_depthStencilBuffer = nullptr;
}
if (textures[0]->_MSAAFramebuffer) {
gl.deleteFramebuffer(textures[0]->_MSAAFramebuffer.get());
textures[0]->_MSAAFramebuffer = nullptr;
}
for (size_t i = 0; i < count; i++) {
const auto& texture = textures[i];
if (texture->_MSAARenderBuffer) {
gl.deleteRenderbuffer(texture->_MSAARenderBuffer.get());
texture->_MSAARenderBuffer = nullptr;
}
}
if (samples > 1) {
auto framebuffer = gl.createFramebuffer();
if (!framebuffer) {
throw std::runtime_error("Unable to create multi sampled framebuffer");
}
_this->_bindUnboundFramebuffer(framebuffer);
auto depthStencilBuffer = _this->_setupFramebufferDepthAttachments(
textures[0]->_generateStencilBuffer, textures[0]->_generateDepthBuffer, textures[0]->width,
textures[0]->height, static_cast<int>(samples));
Uint32Array attachments;
for (size_t i = 0; i < count; ++i) {
auto iStr = std::to_string(i);
auto& texture = textures[i];
auto attachment = gl[_this->webGLVersion() > 1.f ? "COLOR_ATTACHMENT" + iStr :
"COLOR_ATTACHMENT" + iStr + "_WEBGL"];
auto colorRenderbuffer = gl.createRenderbuffer();
if (!colorRenderbuffer) {
throw std::runtime_error("Unable to create multi sampled framebuffer");
}
gl.bindRenderbuffer(GL::RENDERBUFFER, colorRenderbuffer.get());
gl.renderbufferStorageMultisample(GL::RENDERBUFFER, static_cast<int>(samples),
_this->_getRGBAMultiSampleBufferFormat(texture->type),
texture->width, texture->height);
gl.framebufferRenderbuffer(GL::FRAMEBUFFER, attachment, GL::RENDERBUFFER,
colorRenderbuffer.get());
texture->_MSAAFramebuffer = framebuffer;
texture->_MSAARenderBuffer = std::move(colorRenderbuffer);
texture->samples = samples;
texture->_depthStencilBuffer = std::move(depthStencilBuffer);
gl.bindRenderbuffer(GL::RENDERBUFFER, nullptr);
attachments.emplace_back(attachment);
}
if (initializeBuffers) {
gl.drawBuffers(attachments);
}
}
else {
_this->_bindUnboundFramebuffer(textures[0]->_framebuffer);
}
_this->_bindUnboundFramebuffer(nullptr);
return samples;
}
void MultiRenderExtension::bindAttachments(const std::vector<unsigned int>& attachments)
{
auto& gl = *_this->_gl;
gl.drawBuffers(attachments);
}
std::vector<unsigned int>
MultiRenderExtension::buildTextureLayout(const std::vector<bool>& textureStatus) const
{
auto& gl = *_this->_gl;
std::vector<unsigned int> result;
for (auto i = 0ull; i < textureStatus.size(); ++i) {
if (textureStatus[i]) {
result.emplace_back(gl["COLOR_ATTACHMENT" + std::to_string(i)]);
}
else {
result.emplace_back(GL::NONE);
}
}
return result;
}
void MultiRenderExtension::restoreSingleAttachment()
{
bindAttachments({GL::BACK});
}
void MultiRenderExtension::restoreSingleAttachmentForRenderTarget()
{
bindAttachments({GL::COLOR_ATTACHMENT0});
}
void MultiRenderExtension::clearAttachments(Uint32Array& attachments,
const std::optional<Color4>& colorMain,
const std::optional<Color4>& colorOthers,
bool clearDepth, bool clearStencil)
{
if (attachments.empty()) {
return;
}
auto& gl = *_this->_gl;
gl.drawBuffers({attachments[0]});
_this->clear(colorMain, colorMain.has_value(), clearDepth, clearStencil);
const auto saveVal = attachments[0];
attachments[0] = GL::NONE;
gl.drawBuffers(attachments);
_this->clear(colorOthers, colorOthers.has_value(), false, false);
attachments[0] = saveVal;
}
} // end of namespace BABYLON
<|endoftext|>
|
<commit_before>/* This file is part of libDAI - http://www.libdai.org/
*
* Copyright (c) 2006-2011, The libDAI 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 <dai/dai_config.h>
#ifdef DAI_WITH_BP
#include <iostream>
#include <sstream>
#include <map>
#include <set>
#include <algorithm>
#include <dai/bp.h>
#include <dai/util.h>
#include <dai/properties.h>
//#define DAI_VERBOSE
#ifdef DAI_VERBOSE
# define DAI_LOG(MESSAGE) do { std::cout << MESSAGE << std::endl; } while(0)
#else
# define DAI_LOG(MESSAGE)
#endif
namespace dai {
using namespace std;
void BP::setProperties( const PropertySet &opts ) {
DAI_ASSERT( opts.hasKey("tol") );
DAI_ASSERT( opts.hasKey("updates") );
props.tol = opts.getStringAs<Real>("tol");
if( opts.hasKey("maxiter") )
props.maxiter = opts.getStringAs<size_t>("maxiter");
else
props.maxiter = 10000;
if( opts.hasKey("maxtime") )
props.maxtime = opts.getStringAs<Real>("maxtime");
else
props.maxtime = INFINITY;
if( opts.hasKey("verbose") )
props.verbose = opts.getStringAs<size_t>("verbose");
else
props.verbose = 0;
if( opts.hasKey("damping") )
props.damping = opts.getStringAs<Real>("damping");
else
props.damping = 0.0;
}
PropertySet BP::getProperties() const {
PropertySet opts;
opts.set( "tol", props.tol );
opts.set( "maxiter", props.maxiter );
opts.set( "maxtime", props.maxtime );
opts.set( "verbose", props.verbose );
opts.set( "damping", props.damping );
return opts;
}
string BP::printProperties() const {
stringstream s( stringstream::out );
s << "[";
s << "tol=" << props.tol << ",";
s << "maxiter=" << props.maxiter << ",";
s << "maxtime=" << props.maxtime << ",";
s << "verbose=" << props.verbose << ",";
s << "damping=" << props.damping << "]";
return s.str();
}
void BP::construct() {
// create edge properties
_edges.clear();
_edges.reserve( nrVars() );
_oldProd.clear();
_edge2lutNew.clear();
_edge2lutNew.reserve( nrVars() );
for( size_t i = 0; i < nrVars(); ++i ) {
_edges.push_back( vector<EdgeProp>() );
_edges[i].reserve( nbV(i).size() );
_oldProd.push_back(vector<double>(var(i).states(), 1));
_edge2lutNew.push_back( vector<heap_data_handle>() );
_edge2lutNew[i].reserve( nbV(i).size() );
for( const Neighbor &I : nbV(i) ) {
EdgeProp newEP;
newEP.message = Prob( var(i).states() );
newEP.newMessage = Prob( var(i).states() );
newEP.index.reserve( factor(I).nrStates() );
for( IndexFor k( var(i), factor(I).vars() ); k.valid(); ++k )
newEP.index.push_back( k );
newEP.residual = 0.0;
_edges[i].push_back( newEP );
_edge2lutNew[i].push_back( _lutNew.push( make_pair( newEP.residual, make_pair( i, _edges[i].size() - 1 ))));
}
}
// create old beliefs
_oldBeliefsV.clear();
_oldBeliefsV.reserve( nrVars() );
for( size_t i = 0; i < nrVars(); ++i )
_oldBeliefsV.push_back( Factor( var(i) ) );
_oldBeliefsF.clear();
_oldBeliefsF.reserve( nrFactors() );
for( size_t I = 0; I < nrFactors(); ++I )
_oldBeliefsF.push_back( Factor( factor(I).vars() ) );
// create update sequence
_updateSeq.clear();
_updateSeq.reserve( nrEdges() );
for( size_t I = 0; I < nrFactors(); I++ )
for( const Neighbor &i : nbF(I) )
_updateSeq.push_back( Edge( i, i.dual ) );
}
void BP::init() {
Real c = 1.0;
for( size_t i = 0; i < nrVars(); ++i ) {
for( const Neighbor &I : nbV(i) ) {
message( i, I.iter ).fill( c );
newMessage( i, I.iter ).fill( c );
updateResidual( i, I.iter, 0.0 );
}
}
_iters = 0;
}
void BP::findMaxResidual( size_t &i, size_t &_I ) {
DAI_ASSERT( !_lutNew.empty() );
i = _lutNew.top().second.first;
_I = _lutNew.top().second.second;
}
// TODO: Optimize (in progress)
void BP::calcIncomingMessageProduct(Prob &prod, size_t I, bool without_i, size_t i) const {
// Calculate product of incoming messages and factor I
for(const Neighbor &j: nbF(I)) {
if( !(without_i && (j == i)) ) {
// TODO: the calculation in this loop got very cryptic.
// One might want to have some explanations at some point...
// The message that should not go into the product is the one from that
// node that that message will be sent to. Conveniently, the value is
// already available: j.dual.
size_t _I = j.dual;
// ind is the precalculated IndexFor(j,I) i.e. to x_I == k corresponds x_j == ind[k]
const ind_t &ind = index(j, _I);
for(size_t r = 0; r < prod.size(); ++r) {
// Let's divide by that message that should not go into the product.
Real prod_jk = _oldProd[j.node][ind[r]] / _edges[j][_I].message._p[ind[r]];
// And multiply it with the target.
prod._p[r] *= prod_jk;
}
}
}
}
void BP::calcNewMessage( size_t i, size_t _I) {
// load
size_t I = _G.nb1(i)[_I].node;
// The following applies only rarely (uV2New1: 50x, uNew1 and u1: 135x)
// TODO: investigate further, can this still be useful?
// UPDATE: image segmentation example doesn't converge if this "optimization"
// is removed. I don't fully get it though. NJU
if( factor(I).vars().size() == 1 ) // optimization
newMessage(i,_I) = factor(I).p();
else {
// calculate updated message I->i
// The capacity of _prod is not changed here. malloc/free will be called
// very rarely. However, this can be further improved, because
// _factors[I].p().size() cleanly toggles between 2 and 4:
// TODO: create two containers _prod4 and _prod2 and cleverly call
// calcNewMessage() with either one as argument.
if (_prod.size() != _factors[I].p().size())
_prod.resize(_factors[I].p().size());
std::copy(_factors[I].p().begin(), _factors[I].p().end(), _prod.begin());
calcIncomingMessageProduct(_prod, I, true, i);
DAI_LOG("calcNewMessage " << I << " <-> " << i);
// Marginalize onto i
Prob &marg = newMessage(i,_I);
std::fill(marg._p.begin(), marg._p.end(), 0.0);
// ind is the precalculated IndexFor(i,I) i.e. to x_I == k corresponds x_i == ind[k]
const ind_t ind = index(i,_I);
for( size_t r = 0; r < _prod.size(); ++r )
marg._p[ind[r]] = marg[ind[r]] + _prod[r];
marg.normalizeFast();
}
// Update the residual if necessary
updateResidual( i, _I , distFast( newMessage( i, _I ), message( i, _I ) ) );
}
// BP::run does not check for NANs for performance reasons
// Somehow NaNs do not often occur in BP...
Real BP::run() {
if( props.verbose >= 1 )
cerr << "Starting " << identify() << "...";
if( props.verbose >= 3)
cerr << endl;
double tic = toc();
// do several passes over the network until maximum number of iterations has
// been reached or until the maximum belief difference is smaller than tolerance
Real maxDiff = INFINITY;
for( ; _iters < props.maxiter && maxDiff > props.tol && (toc() - tic) < props.maxtime; _iters++ ) {
if( _iters == 0 ) {
// do the first pass
for( size_t i = 0; i < nrVars(); ++i )
for( const Neighbor &I : nbV(i) ) {
calcNewMessage( i, I.iter);
}
}
// Maximum-Residual BP [\ref EMK06]
for( size_t t = 0; t < _updateSeq.size(); ++t ) {
// update the message with the largest residual
size_t i, _I;
findMaxResidual( i, _I );
DAI_LOG("updating message from " << i << " to " << _I);
updateMessage( i, _I );
// I->i has been updated, which means that residuals for all
// J->j with J in nb[i]\I and j in nb[J]\i have to be updated
for( const Neighbor &J: nbV(i) ) {
if( J.iter != _I ) {
for( const Neighbor &j: nbF(J) ) {
size_t _J = j.dual;
if( j != i )
calcNewMessage( j, _J);
}
}
}
}
// calculate new beliefs and compare with old ones
maxDiff = -INFINITY;
for( size_t i = 0; i < nrVars(); ++i ) {
Factor b( beliefV(i) );
maxDiff = std::max( maxDiff, distFast( b.p(), _oldBeliefsV[i].p() ) );
_oldBeliefsV[i] = b;
}
for( size_t I = 0; I < nrFactors(); ++I ) {
Factor b( beliefF(I) );
maxDiff = std::max( maxDiff, distFast( b.p(), _oldBeliefsF[I].p() ) );
_oldBeliefsF[I] = b;
}
if( props.verbose >= 3 )
cerr << name() << "::run: maxdiff " << maxDiff << " after " << _iters+1 << " passes" << endl;
}
if( maxDiff > _maxdiff )
_maxdiff = maxDiff;
if( props.verbose >= 1 ) {
if( maxDiff > props.tol ) {
if( props.verbose == 1 )
cerr << endl;
cerr << name() << "::run: WARNING: not converged after " << _iters << " passes (" << toc() - tic << " seconds)...final maxdiff:" << maxDiff << endl;
} else {
if( props.verbose >= 3 )
cerr << name() << "::run: ";
cerr << "converged in " << _iters << " passes (" << toc() - tic << " seconds)." << endl;
}
}
return maxDiff;
}
void BP::calcBeliefV( size_t i, Prob &p ) const {
p = Prob( var(i).states(), 1.0);
for ( const Neighbor &I : nbV(i) )
p *= newMessage( i, I.iter );
}
Factor BP::beliefV( size_t i ) const {
Prob p;
calcBeliefV( i, p );
p.normalize();
return( Factor( var(i), p ) );
}
Factor BP::beliefF( size_t I ) const {
Factor Fprod( factor(I) );
Prob &p = Fprod.p();
calcBeliefF( I, p );
p.normalize();
return( Factor( factor(I).vars(), p ) );
}
vector<Factor> BP::beliefs() const {
vector<Factor> result;
for( size_t i = 0; i < nrVars(); ++i )
result.push_back( beliefV(i) );
for( size_t I = 0; I < nrFactors(); ++I )
result.push_back( beliefF(I) );
return result;
}
Factor BP::belief( const VarSet &ns ) const {
if( ns.size() == 0 )
return Factor();
else if( ns.size() == 1 )
return beliefV( findVar( *(ns.begin() ) ) );
else {
size_t I;
for( I = 0; I < nrFactors(); I++ )
if( factor(I).vars() >> ns )
break;
if( I == nrFactors() )
DAI_THROW(BELIEF_NOT_AVAILABLE);
return beliefF(I).marginal(ns);
}
}
Real BP::logZ() const {
Real sum = 0.0;
for( size_t i = 0; i < nrVars(); ++i )
sum += (1.0 - nbV(i).size()) * beliefV(i).entropy();
for( size_t I = 0; I < nrFactors(); ++I )
sum -= dist( beliefF(I), factor(I), DISTKL );
return sum;
}
void BP::init( const VarSet &ns ) {
for( VarSet::const_iterator n = ns.begin(); n != ns.end(); ++n ) {
size_t ni = findVar( *n );
for( const Neighbor &I : nbV( ni ) ) {
Real val = 1.0;
message( ni, I.iter ).fill( val );
newMessage( ni, I.iter ).fill( val );
updateResidual( ni, I.iter, 0.0 );
}
}
_iters = 0;
}
void BP::updateMessage( size_t i, size_t _I ) {
for (size_t j=0; j<_oldProd[i].size(); ++j) {
_oldProd[i][j] = _edges[i][_I].newMessage._p[j] * _oldProd[i][j] / _edges[i][_I].message._p[j];
}
if( recordSentMessages )
_sentMessages.push_back(make_pair(i,_I));
if( props.damping == 0.0 ) {
message(i,_I) = newMessage(i,_I);
updateResidual( i, _I, 0.0 );
} else {
message(i,_I) = (message(i,_I) ^ props.damping) * (newMessage(i,_I) ^ (1.0 - props.damping));
updateResidual( i, _I, distFast( newMessage(i,_I), message(i,_I) ) );
}
}
// TODO: Optimize: We are using a heap now but this is not faster then the multimap solution. So we might have to revert to it.
void BP::updateResidual( size_t i, size_t _I, Real r ) {
EdgeProp* pEdge = &_edges[i][_I];
pEdge->residual = r;
// rearrange look-up table (delete and reinsert new key)
_lutNew.update(_edge2lutNew[i][_I], make_pair( r, make_pair(i, _I) ));
}
} // end of namespace dai
#endif
<commit_msg>Access storage more directly. (No speedup measured)<commit_after>/* This file is part of libDAI - http://www.libdai.org/
*
* Copyright (c) 2006-2011, The libDAI 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 <dai/dai_config.h>
#ifdef DAI_WITH_BP
#include <iostream>
#include <sstream>
#include <map>
#include <set>
#include <algorithm>
#include <dai/bp.h>
#include <dai/util.h>
#include <dai/properties.h>
//#define DAI_VERBOSE
#ifdef DAI_VERBOSE
# define DAI_LOG(MESSAGE) do { std::cout << MESSAGE << std::endl; } while(0)
#else
# define DAI_LOG(MESSAGE)
#endif
namespace dai {
using namespace std;
void BP::setProperties( const PropertySet &opts ) {
DAI_ASSERT( opts.hasKey("tol") );
DAI_ASSERT( opts.hasKey("updates") );
props.tol = opts.getStringAs<Real>("tol");
if( opts.hasKey("maxiter") )
props.maxiter = opts.getStringAs<size_t>("maxiter");
else
props.maxiter = 10000;
if( opts.hasKey("maxtime") )
props.maxtime = opts.getStringAs<Real>("maxtime");
else
props.maxtime = INFINITY;
if( opts.hasKey("verbose") )
props.verbose = opts.getStringAs<size_t>("verbose");
else
props.verbose = 0;
if( opts.hasKey("damping") )
props.damping = opts.getStringAs<Real>("damping");
else
props.damping = 0.0;
}
PropertySet BP::getProperties() const {
PropertySet opts;
opts.set( "tol", props.tol );
opts.set( "maxiter", props.maxiter );
opts.set( "maxtime", props.maxtime );
opts.set( "verbose", props.verbose );
opts.set( "damping", props.damping );
return opts;
}
string BP::printProperties() const {
stringstream s( stringstream::out );
s << "[";
s << "tol=" << props.tol << ",";
s << "maxiter=" << props.maxiter << ",";
s << "maxtime=" << props.maxtime << ",";
s << "verbose=" << props.verbose << ",";
s << "damping=" << props.damping << "]";
return s.str();
}
void BP::construct() {
// create edge properties
_edges.clear();
_edges.reserve( nrVars() );
_oldProd.clear();
_edge2lutNew.clear();
_edge2lutNew.reserve( nrVars() );
for( size_t i = 0; i < nrVars(); ++i ) {
_edges.push_back( vector<EdgeProp>() );
_edges[i].reserve( nbV(i).size() );
_oldProd.push_back(vector<double>(var(i).states(), 1));
_edge2lutNew.push_back( vector<heap_data_handle>() );
_edge2lutNew[i].reserve( nbV(i).size() );
for( const Neighbor &I : nbV(i) ) {
EdgeProp newEP;
newEP.message = Prob( var(i).states() );
newEP.newMessage = Prob( var(i).states() );
newEP.index.reserve( factor(I).nrStates() );
for( IndexFor k( var(i), factor(I).vars() ); k.valid(); ++k )
newEP.index.push_back( k );
newEP.residual = 0.0;
_edges[i].push_back( newEP );
_edge2lutNew[i].push_back( _lutNew.push( make_pair( newEP.residual, make_pair( i, _edges[i].size() - 1 ))));
}
}
// create old beliefs
_oldBeliefsV.clear();
_oldBeliefsV.reserve( nrVars() );
for( size_t i = 0; i < nrVars(); ++i )
_oldBeliefsV.push_back( Factor( var(i) ) );
_oldBeliefsF.clear();
_oldBeliefsF.reserve( nrFactors() );
for( size_t I = 0; I < nrFactors(); ++I )
_oldBeliefsF.push_back( Factor( factor(I).vars() ) );
// create update sequence
_updateSeq.clear();
_updateSeq.reserve( nrEdges() );
for( size_t I = 0; I < nrFactors(); I++ )
for( const Neighbor &i : nbF(I) )
_updateSeq.push_back( Edge( i, i.dual ) );
}
void BP::init() {
Real c = 1.0;
for( size_t i = 0; i < nrVars(); ++i ) {
for( const Neighbor &I : nbV(i) ) {
message( i, I.iter ).fill( c );
newMessage( i, I.iter ).fill( c );
updateResidual( i, I.iter, 0.0 );
}
}
_iters = 0;
}
void BP::findMaxResidual( size_t &i, size_t &_I ) {
DAI_ASSERT( !_lutNew.empty() );
i = _lutNew.top().second.first;
_I = _lutNew.top().second.second;
}
// TODO: Optimize (in progress)
void BP::calcIncomingMessageProduct(Prob &prod, size_t I, bool without_i, size_t i) const {
// Calculate product of incoming messages and factor I
for(const Neighbor &j: nbF(I)) {
if( !(without_i && (j == i)) ) {
// TODO: the calculation in this loop got very cryptic.
// One might want to have some explanations at some point...
// The message that should not go into the product is the one from that
// node that that message will be sent to. Conveniently, the value is
// already available: j.dual.
size_t _I = j.dual;
// ind is the precalculated IndexFor(j,I) i.e. to x_I == k corresponds x_j == ind[k]
const ind_t &ind = index(j, _I);
for(size_t r = 0; r < prod.size(); ++r) {
// Let's divide by that message that should not go into the product.
Real prod_jk = _oldProd[j.node][ind[r]] / _edges[j][_I].message._p[ind[r]];
// And multiply it with the target.
prod._p[r] *= prod_jk;
}
}
}
}
void BP::calcNewMessage( size_t i, size_t _I) {
// load
size_t I = _G.nb1(i)[_I].node;
// The following applies only rarely (uV2New1: 50x, uNew1 and u1: 135x)
// TODO: investigate further, can this still be useful?
// UPDATE: image segmentation example doesn't converge if this "optimization"
// is removed. I don't fully get it though. NJU
if( _factors[I].vars().size() == 1 ) { // optimization
std::copy(_factors[I].p().begin(),
_factors[I].p().end(),
newMessage(i,_I)._p.begin());
}
else {
// calculate updated message I->i
// The capacity of _prod is not changed here. malloc/free will be called
// very rarely. However, this can be further improved, because
// _factors[I].p().size() cleanly toggles between 2 and 4:
// TODO: create two containers _prod4 and _prod2 and cleverly call
// calcNewMessage() with either one as argument.
if (_prod.size() != _factors[I].p().size())
_prod.resize(_factors[I].p().size());
std::copy(_factors[I].p().begin(), _factors[I].p().end(), _prod.begin());
calcIncomingMessageProduct(_prod, I, true, i);
DAI_LOG("calcNewMessage " << I << " <-> " << i);
// Marginalize onto i
Prob &marg = newMessage(i,_I);
std::fill(marg._p.begin(), marg._p.end(), 0.0);
// ind is the precalculated IndexFor(i,I) i.e. to x_I == k corresponds x_i == ind[k]
const ind_t ind = index(i,_I);
for( size_t r = 0; r < _prod.size(); ++r )
marg._p[ind[r]] = marg[ind[r]] + _prod[r];
marg.normalizeFast();
}
// Update the residual if necessary
updateResidual( i, _I , distFast( newMessage( i, _I ), message( i, _I ) ) );
}
// BP::run does not check for NANs for performance reasons
// Somehow NaNs do not often occur in BP...
Real BP::run() {
if( props.verbose >= 1 )
cerr << "Starting " << identify() << "...";
if( props.verbose >= 3)
cerr << endl;
double tic = toc();
// do several passes over the network until maximum number of iterations has
// been reached or until the maximum belief difference is smaller than tolerance
Real maxDiff = INFINITY;
for( ; _iters < props.maxiter && maxDiff > props.tol && (toc() - tic) < props.maxtime; _iters++ ) {
if( _iters == 0 ) {
// do the first pass
for( size_t i = 0; i < nrVars(); ++i )
for( const Neighbor &I : nbV(i) ) {
calcNewMessage( i, I.iter);
}
}
// Maximum-Residual BP [\ref EMK06]
for( size_t t = 0; t < _updateSeq.size(); ++t ) {
// update the message with the largest residual
size_t i, _I;
findMaxResidual( i, _I );
DAI_LOG("updating message from " << i << " to " << _I);
updateMessage( i, _I );
// I->i has been updated, which means that residuals for all
// J->j with J in nb[i]\I and j in nb[J]\i have to be updated
for( const Neighbor &J: nbV(i) ) {
if( J.iter != _I ) {
for( const Neighbor &j: nbF(J) ) {
size_t _J = j.dual;
if( j != i )
calcNewMessage( j, _J);
}
}
}
}
// calculate new beliefs and compare with old ones
maxDiff = -INFINITY;
for( size_t i = 0; i < nrVars(); ++i ) {
Factor b( beliefV(i) );
maxDiff = std::max( maxDiff, distFast( b.p(), _oldBeliefsV[i].p() ) );
_oldBeliefsV[i] = b;
}
for( size_t I = 0; I < nrFactors(); ++I ) {
Factor b( beliefF(I) );
maxDiff = std::max( maxDiff, distFast( b.p(), _oldBeliefsF[I].p() ) );
_oldBeliefsF[I] = b;
}
if( props.verbose >= 3 )
cerr << name() << "::run: maxdiff " << maxDiff << " after " << _iters+1 << " passes" << endl;
}
if( maxDiff > _maxdiff )
_maxdiff = maxDiff;
if( props.verbose >= 1 ) {
if( maxDiff > props.tol ) {
if( props.verbose == 1 )
cerr << endl;
cerr << name() << "::run: WARNING: not converged after " << _iters << " passes (" << toc() - tic << " seconds)...final maxdiff:" << maxDiff << endl;
} else {
if( props.verbose >= 3 )
cerr << name() << "::run: ";
cerr << "converged in " << _iters << " passes (" << toc() - tic << " seconds)." << endl;
}
}
return maxDiff;
}
void BP::calcBeliefV( size_t i, Prob &p ) const {
p = Prob( var(i).states(), 1.0);
for ( const Neighbor &I : nbV(i) )
p *= newMessage( i, I.iter );
}
Factor BP::beliefV( size_t i ) const {
Prob p;
calcBeliefV( i, p );
p.normalize();
return( Factor( var(i), p ) );
}
Factor BP::beliefF( size_t I ) const {
Factor Fprod( factor(I) );
Prob &p = Fprod.p();
calcBeliefF( I, p );
p.normalize();
return( Factor( factor(I).vars(), p ) );
}
vector<Factor> BP::beliefs() const {
vector<Factor> result;
for( size_t i = 0; i < nrVars(); ++i )
result.push_back( beliefV(i) );
for( size_t I = 0; I < nrFactors(); ++I )
result.push_back( beliefF(I) );
return result;
}
Factor BP::belief( const VarSet &ns ) const {
if( ns.size() == 0 )
return Factor();
else if( ns.size() == 1 )
return beliefV( findVar( *(ns.begin() ) ) );
else {
size_t I;
for( I = 0; I < nrFactors(); I++ )
if( factor(I).vars() >> ns )
break;
if( I == nrFactors() )
DAI_THROW(BELIEF_NOT_AVAILABLE);
return beliefF(I).marginal(ns);
}
}
Real BP::logZ() const {
Real sum = 0.0;
for( size_t i = 0; i < nrVars(); ++i )
sum += (1.0 - nbV(i).size()) * beliefV(i).entropy();
for( size_t I = 0; I < nrFactors(); ++I )
sum -= dist( beliefF(I), factor(I), DISTKL );
return sum;
}
void BP::init( const VarSet &ns ) {
for( VarSet::const_iterator n = ns.begin(); n != ns.end(); ++n ) {
size_t ni = findVar( *n );
for( const Neighbor &I : nbV( ni ) ) {
Real val = 1.0;
message( ni, I.iter ).fill( val );
newMessage( ni, I.iter ).fill( val );
updateResidual( ni, I.iter, 0.0 );
}
}
_iters = 0;
}
void BP::updateMessage( size_t i, size_t _I ) {
for (size_t j=0; j<_oldProd[i].size(); ++j) {
_oldProd[i][j] = _edges[i][_I].newMessage._p[j] * _oldProd[i][j] / _edges[i][_I].message._p[j];
}
if( recordSentMessages )
_sentMessages.push_back(make_pair(i,_I));
if( props.damping == 0.0 ) {
message(i,_I) = newMessage(i,_I);
updateResidual( i, _I, 0.0 );
} else {
message(i,_I) = (message(i,_I) ^ props.damping) * (newMessage(i,_I) ^ (1.0 - props.damping));
updateResidual( i, _I, distFast( newMessage(i,_I), message(i,_I) ) );
}
}
// TODO: Optimize: We are using a heap now but this is not faster then the multimap solution. So we might have to revert to it.
void BP::updateResidual( size_t i, size_t _I, Real r ) {
EdgeProp* pEdge = &_edges[i][_I];
pEdge->residual = r;
// rearrange look-up table (delete and reinsert new key)
_lutNew.update(_edge2lutNew[i][_I], make_pair( r, make_pair(i, _I) ));
}
} // end of namespace dai
#endif
<|endoftext|>
|
<commit_before>// This file is part of UDPipe <http://github.com/ufal/udpipe/>.
//
// Copyright 2016 Institute of Formal and Applied Linguistics, Faculty of
// Mathematics and Physics, Charles University in Prague, Czech Republic.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include <fstream>
#include <sstream>
#include "common.h"
#include "model/evaluator.h"
#include "model/model.h"
#include "model/pipeline.h"
#include "sentence/input_format.h"
#include "trainer/trainer.h"
#include "utils/getpara.h"
#include "utils/iostreams.h"
#include "utils/options.h"
#include "utils/process_args.h"
#include "version/version.h"
using namespace ufal::udpipe;
bool append_conllu(istream& is, vector<sentence>& sentences, string& error) {
unique_ptr<input_format> conllu_input(input_format::new_conllu_input_format());
string block;
while (conllu_input->read_block(is, block)) {
conllu_input->set_text(block);
while (sentences.emplace_back(), conllu_input->next_sentence(sentences.back(), error)) ;
sentences.pop_back();
if (!error.empty()) return false;
}
return true;
}
int main(int argc, char* argv[]) {
iostreams_init();
options::map options;
if (!options::parse({{"accuracy", options::value::none},
{"method", options::value{"morphodita_parsito"}},
{"heldout", options::value::any},
{"input", options::value::any},
{"outfile", options::value::any},
{"output", options::value::any},
{"parse", options::value::none},
{"parser", options::value::any},
{"tag", options::value::none},
{"tagger", options::value::any},
{"tokenize", options::value::none},
{"tokenizer", options::value::any},
{"train", options::value::none},
{"version", options::value::none},
{"help", options::value::none}}, argc, argv, options) ||
options.count("help") ||
(argc < 2 && !options.count("version")))
runtime_failure("Usage: " << argv[0] << " --train [training_options] model_file [input_files]\n"
" " << argv[0] << " [running_options] model_file [input_files]\n"
"Running options: --accuracy (measure accuracy only)\n"
" --input=[conllu|horizontal|vertical]\n"
" --outfile=output file template\n"
" --output=[conllu|matxin|horizontal|vertical]\n"
" --tokenize (perform tokenization)\n"
" --tokenizer=tokenizer options, implies --tokenize\n"
" --tag (perform tagging)\n"
" --tagger=tagger options, implies --tag\n"
" --parse (perform parsing)\n"
" --parser=parser options, implies --parse\n"
"Training options: --method=[morphodita_parsito] which method to use\n"
" --heldout=heldout data file name\n"
" --tokenizer=tokenizer options\n"
" --tagger=tagger options\n"
" --parser=parser options\n"
"Generic options: --version\n"
" --help");
if (options.count("version"))
return cout << version::version_and_copyright() << endl, 0;
if (options.count("train")) {
string error;
// Load training data
cerr << "Loading training data: " << flush;
vector<sentence> training;
for (int i = 2; i < argc; i++) {
ifstream input(argv[i]);
if (!input.is_open()) runtime_failure("Cannot open input file '" << argv[i] << "'!");
if (!append_conllu(input, training, error))
runtime_failure("Cannot load training data from file '" << argv[i] << "': " << error);
}
if (argc == 2 && !append_conllu(cin, training, error)) runtime_failure("Cannot load training data: " << error);
cerr << "done." << endl;
// Load heldout data
vector<sentence> heldout;
if (options.count("heldout")) {
ifstream input(options["heldout"]);
if (!input.is_open()) runtime_failure("Cannot open heldout data file '" << options["heldout"] << "'!");
if (!append_conllu(input, heldout, error))
runtime_failure("Cannot load heldout data from file '" << options["heldout"] << "': " << error);
}
// Open output file
ofstream model(argv[1], ofstream::binary);
if (!model.is_open()) runtime_failure("Cannot open model file '" << argv[1] << "' for writing.");
// Train the model
cerr << "Training the UDPipe model." << endl;
string method = options.count("method") ? options["method"] : "morphodita_parsito";
if (!trainer::train(method, training, heldout, options["tokenizer"], options["tagger"], options["parser"], model, error))
runtime_failure("An error occurred during model training: " << error);
cerr << "The trained UDPipe model was saved." << endl;
} else {
// Load the model if needed
unique_ptr<model> model;
if (options.count("tokenizer") || options.count("tokenize") ||
options.count("tagger") || options.count("tag") ||
options.count("parser") || options.count("parse")) {
cerr << "Loading UDPipe model: " << flush;
model.reset(model::load(argv[1]));
if (!model) runtime_failure("Cannot load UDPipe model '" << argv[1] << "'!");
cerr << "done." << endl;
}
if (options.count("accuracy")) {
if (options.count("input")) runtime_failure("The --input option is unsupported when --accuracy is used!");
if (options.count("output")) runtime_failure("The --output option is unsupported when --accuracy is used!");
// Prepare the evaluator
evaluator evaluator(model.get(), options.count("tokenizer") ? options["tokenizer"] : options.count("tokenize") ? pipeline::DEFAULT : pipeline::NONE,
options.count("tagger") ? options["tagger"] : options.count("tag") ? pipeline::DEFAULT : pipeline::NONE,
options.count("parser") ? options["parser"] : options.count("parse") ? pipeline::DEFAULT : pipeline::NONE);
// Process the data
process_args_with_output_template(2, argc, argv, options["outfile"], [&evaluator](istream& is, ostream& os) {
string error;
if (!evaluator.evaluate(is, os, error))
runtime_failure("An error occurred during UDPipe execution: " << error);
});
} else {
// Prepare the pipeline
pipeline pipeline(model.get(), options.count("tokenizer") ? "tokenizer=" + options["tokenizer"] : options.count("tokenize") ? "tokenizer" : options.count("input") ? options["input"] : "conllu",
options.count("tagger") ? options["tagger"] : options.count("tag") ? pipeline::DEFAULT : pipeline::NONE,
options.count("parser") ? options["parser"] : options.count("parse") ? pipeline::DEFAULT : pipeline::NONE,
options.count("output") ? options["output"] : "conllu");
// Process the data
process_args_with_output_template(2, argc, argv, options["outfile"], [&pipeline](istream& is, ostream& os) {
string error;
if (!pipeline.process(is, os, error))
runtime_failure("An error occurred during UDPipe execution: " << error);
});
}
}
return 0;
}
<commit_msg>Add --detokenize mode for UDPipe.<commit_after>// This file is part of UDPipe <http://github.com/ufal/udpipe/>.
//
// Copyright 2016 Institute of Formal and Applied Linguistics, Faculty of
// Mathematics and Physics, Charles University in Prague, Czech Republic.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include <fstream>
#include <sstream>
#include "common.h"
#include "model/evaluator.h"
#include "model/model.h"
#include "model/pipeline.h"
#include "sentence/input_format.h"
#include "sentence/output_format.h"
#include "tokenizer/detokenizer.h"
#include "trainer/trainer.h"
#include "utils/getpara.h"
#include "utils/iostreams.h"
#include "utils/options.h"
#include "utils/process_args.h"
#include "version/version.h"
using namespace ufal::udpipe;
bool append_conllu(istream& is, vector<sentence>& sentences, string& error) {
unique_ptr<input_format> conllu_input(input_format::new_conllu_input_format());
string block;
while (conllu_input->read_block(is, block)) {
conllu_input->set_text(block);
while (sentences.emplace_back(), conllu_input->next_sentence(sentences.back(), error)) ;
sentences.pop_back();
if (!error.empty()) return false;
}
return true;
}
int main(int argc, char* argv[]) {
iostreams_init();
options::map options;
if (!options::parse({{"accuracy", options::value::none},
{"detokenize", options::value::none},
{"method", options::value{"morphodita_parsito"}},
{"heldout", options::value::any},
{"input", options::value::any},
{"outfile", options::value::any},
{"output", options::value::any},
{"parse", options::value::none},
{"parser", options::value::any},
{"tag", options::value::none},
{"tagger", options::value::any},
{"tokenize", options::value::none},
{"tokenizer", options::value::any},
{"train", options::value::none},
{"version", options::value::none},
{"help", options::value::none}}, argc, argv, options) ||
options.count("help") ||
(argc < 2 && !options.count("version")))
runtime_failure("Usage: " << argv[0] << " [running_opts] model_file [input_files]\n"
" " << argv[0] << " --train [training_opts] model_file [input_files]\n"
" " << argv[0] << " --detokenize [detokenize_opts] raw_text_file [input_files]\n"
"Running opts: --accuracy (measure accuracy only)\n"
" --input=[conllu|horizontal|vertical]\n"
" --outfile=output file template\n"
" --output=[conllu|matxin|horizontal|vertical]\n"
" --tokenize (perform tokenization)\n"
" --tokenizer=tokenizer options, implies --tokenize\n"
" --tag (perform tagging)\n"
" --tagger=tagger options, implies --tag\n"
" --parse (perform parsing)\n"
" --parser=parser options, implies --parse\n"
"Training opts: --method=[morphodita_parsito] which method to use\n"
" --heldout=heldout data file name\n"
" --tokenizer=tokenizer options\n"
" --tagger=tagger options\n"
" --parser=parser options\n"
"Detokenize opts: --outfile=output file template\n"
"Generic opts: --version\n"
" --help");
if (options.count("version"))
return cout << version::version_and_copyright() << endl, 0;
// TRAINING
if (options.count("train")) {
string error;
// Load training data
cerr << "Loading training data: " << flush;
vector<sentence> training;
for (int i = 2; i < argc; i++) {
ifstream input(argv[i]);
if (!input.is_open()) runtime_failure("Cannot open input file '" << argv[i] << "'!");
if (!append_conllu(input, training, error))
runtime_failure("Cannot load training data from file '" << argv[i] << "': " << error);
}
if (argc == 2 && !append_conllu(cin, training, error)) runtime_failure("Cannot load training data: " << error);
cerr << "done." << endl;
// Load heldout data
vector<sentence> heldout;
if (options.count("heldout")) {
ifstream input(options["heldout"]);
if (!input.is_open()) runtime_failure("Cannot open heldout data file '" << options["heldout"] << "'!");
if (!append_conllu(input, heldout, error))
runtime_failure("Cannot load heldout data from file '" << options["heldout"] << "': " << error);
}
// Open output file
ofstream model(argv[1], ofstream::binary);
if (!model.is_open()) runtime_failure("Cannot open model file '" << argv[1] << "' for writing.");
// Train the model
cerr << "Training the UDPipe model." << endl;
string method = options.count("method") ? options["method"] : "morphodita_parsito";
if (!trainer::train(method, training, heldout, options["tokenizer"], options["tagger"], options["parser"], model, error))
runtime_failure("An error occurred during model training: " << error);
cerr << "The trained UDPipe model was saved." << endl;
} else
// DETOKENIZE
if (options.count("detokenize")) {
// Detokenize CoNLL-U files
ifstream raw_text_file(argv[1]);
if (!raw_text_file.is_open()) runtime_failure("Cannot load raw text from file '" << argv[1] << "'.");
string raw_text;
for (char c; raw_text_file.get(c); )
raw_text.push_back(c);
raw_text_file.close();
detokenizer detokenizer(raw_text);
process_args_with_output_template(2, argc, argv, options["outfile"], [&detokenizer](istream& is, ostream& os) {
unique_ptr<input_format> conllu_input(input_format::new_conllu_input_format());
unique_ptr<output_format> conllu_output(output_format::new_conllu_output_format());
sentence s;
string block, error;
while (conllu_input->read_block(is, block)) {
conllu_input->set_text(block);
while (conllu_input->next_sentence(s, error)) {
detokenizer.detokenize(s);
conllu_output->write_sentence(s, os);
}
if (!error.empty()) runtime_failure("An error occurred during UDPipe execution: " << error);
}
conllu_output->finish_document(os);
});
} else
// RUN
{
// Load the model if needed
unique_ptr<model> model;
if (options.count("tokenizer") || options.count("tokenize") ||
options.count("tagger") || options.count("tag") ||
options.count("parser") || options.count("parse")) {
cerr << "Loading UDPipe model: " << flush;
model.reset(model::load(argv[1]));
if (!model) runtime_failure("Cannot load UDPipe model '" << argv[1] << "'!");
cerr << "done." << endl;
}
if (options.count("accuracy")) {
if (options.count("input")) runtime_failure("The --input option is unsupported when --accuracy is used!");
if (options.count("output")) runtime_failure("The --output option is unsupported when --accuracy is used!");
// Prepare the evaluator
evaluator evaluator(model.get(), options.count("tokenizer") ? options["tokenizer"] : options.count("tokenize") ? pipeline::DEFAULT : pipeline::NONE,
options.count("tagger") ? options["tagger"] : options.count("tag") ? pipeline::DEFAULT : pipeline::NONE,
options.count("parser") ? options["parser"] : options.count("parse") ? pipeline::DEFAULT : pipeline::NONE);
// Process the data
process_args_with_output_template(2, argc, argv, options["outfile"], [&evaluator](istream& is, ostream& os) {
string error;
if (!evaluator.evaluate(is, os, error))
runtime_failure("An error occurred during UDPipe execution: " << error);
});
} else {
// Prepare the pipeline
pipeline pipeline(model.get(), options.count("tokenizer") ? "tokenizer=" + options["tokenizer"] : options.count("tokenize") ? "tokenizer" : options.count("input") ? options["input"] : "conllu",
options.count("tagger") ? options["tagger"] : options.count("tag") ? pipeline::DEFAULT : pipeline::NONE,
options.count("parser") ? options["parser"] : options.count("parse") ? pipeline::DEFAULT : pipeline::NONE,
options.count("output") ? options["output"] : "conllu");
// Process the data
process_args_with_output_template(2, argc, argv, options["outfile"], [&pipeline](istream& is, ostream& os) {
string error;
if (!pipeline.process(is, os, error))
runtime_failure("An error occurred during UDPipe execution: " << error);
});
}
}
return 0;
}
<|endoftext|>
|
<commit_before>#ifndef VSMC_RNG_SEED_HPP
#define VSMC_RNG_SEED_HPP
#include <vsmc/rng/common.hpp>
#include <ctime>
#include <cstdlib>
namespace vsmc { namespace rng {
class Seed
{
public :
typedef unsigned long result_type;
static Seed &create ()
{
static Seed seed;
return seed;
}
result_type get ()
{
if (seed_ >= std::numeric_limits<result_type>::max() - 1)
seed_ = 0;
return ++seed_;
}
void set (result_type seed)
{
seed_ = seed;
}
void skip (result_type steps)
{
if (seed_ >= std::numeric_limits<result_type>::max() - steps)
seed_ = steps;
else
seed_ += steps;
}
private :
result_type seed_;
Seed () : seed_(VSMC_RNG_SEED)
{
if (!seed_)
seed_ = std::rand();
}
Seed (const Seed &) {}
const Seed &operator= (const Seed &) {return *this;}
};
} } // namespace vsmc::rng
#endif // VSMC_RNG_SEED_HPP
<commit_msg>document Seed<commit_after>#ifndef VSMC_RNG_SEED_HPP
#define VSMC_RNG_SEED_HPP
#include <vsmc/rng/common.hpp>
#include <ctime>
#include <cstdlib>
namespace vsmc { namespace rng {
/// \brief Seed generator
/// \ingroup RNG
///
/// \details
/// A Seed object cannot be created, copied, or assigned to/from by user.
/// Instead, user can only get a reference to a \c static Seed object through
/// \c Seed::create(). It is intended to generate distinct seed for the
/// Counter-based random number generator provided by Random123 library. The
/// seed generated from the Seed object shall not be used by other Pseudo
/// random number generator. The seed sequence is just a sequence of \c
/// unsigned integers. On most platforms this means it can used to create
/// \f$2^32 - 1\f$ independent random streams when used with Random123. All
/// public options are of constant complexity. For Pseudo random number
/// generators, independent seeds would need much higher computational
/// complexity to generate.
///
/// \note Note that currently all interface of Seed are \b not thread-safe.
class Seed
{
public :
typedef unsigned result_type;
static Seed &create ()
{
static Seed seed;
return seed;
}
result_type get ()
{
if (seed_ >= std::numeric_limits<result_type>::max() - 1)
seed_ = 0;
return ++seed_;
}
void set (result_type seed)
{
seed_ = seed;
}
void skip (result_type steps)
{
if (seed_ >= std::numeric_limits<result_type>::max() - steps)
seed_ = steps;
else
seed_ += steps;
}
private :
result_type seed_;
Seed () : seed_(VSMC_RNG_SEED)
{
if (!seed_)
seed_ = std::rand();
}
Seed (const Seed &) {}
const Seed &operator= (const Seed &) {return *this;}
};
} } // namespace vsmc::rng
#endif // VSMC_RNG_SEED_HPP
<|endoftext|>
|
<commit_before>#include "binlog.h"
#include "util/log.h"
#include "util/strings.h"
#include <map>
/* Binlog */
Binlog::Binlog(uint64_t seq, char cmd, char type, const leveldb::Slice &key){
buf.append((char *)(&seq), sizeof(uint64_t));
buf.push_back(cmd);
buf.push_back(type);
buf.append(key.data(), key.size());
}
uint64_t Binlog::seq() const{
return *((uint64_t *)(buf.data()));
}
char Binlog::type() const{
return buf[sizeof(uint64_t)];
}
char Binlog::cmd() const{
return buf[sizeof(uint64_t) + 1];
}
const Bytes Binlog::key() const{
return Bytes(buf.data() + HEADER_LEN, buf.size() - HEADER_LEN);
}
int Binlog::load(const leveldb::Slice &s){
if(s.size() < HEADER_LEN){
return -1;
}
buf.assign(s.data(), s.size());
return 0;
}
std::string Binlog::dumps() const{
std::string str;
if(buf.size() < HEADER_LEN){
return str;
}
char buf[20];
snprintf(buf, sizeof(buf), "%llu ", this->seq());
str.append(buf);
switch(this->type()){
case BinlogType::NOOP:
str.append("noop ");
break;
case BinlogType::SYNC:
str.append("sync ");
break;
case BinlogType::MIRROR:
str.append("mirror ");
break;
case BinlogType::COPY:
str.append("copy ");
break;
}
switch(this->cmd()){
case BinlogCommand::NONE:
str.append("none ");
break;
case BinlogCommand::KSET:
str.append("set ");
break;
case BinlogCommand::KDEL:
str.append("del ");
break;
case BinlogCommand::HSET:
str.append("hset ");
break;
case BinlogCommand::HDEL:
str.append("hdel ");
break;
case BinlogCommand::ZSET:
str.append("zset ");
break;
case BinlogCommand::ZDEL:
str.append("zdel ");
break;
case BinlogCommand::BEGIN:
str.append("begin ");
break;
case BinlogCommand::END:
str.append("end ");
break;
}
Bytes b = this->key();
str.append(hexmem(b.data(), b.size()));
return str;
}
/* SyncLogQueue */
static inline std::string encode_seq_key(uint64_t seq){
seq = big_endian(seq);
std::string ret;
ret.push_back(DataType::SYNCLOG);
ret.append((char *)&seq, sizeof(seq));
return ret;
}
static inline uint64_t decode_seq_key(const leveldb::Slice &key){
uint64_t seq = 0;
if(key.size() == (sizeof(uint64_t) + 1) && key.data()[0] == DataType::SYNCLOG){
seq = *((uint64_t *)(key.data() + 1));
seq = big_endian(seq);
}
return seq;
}
BinlogQueue::BinlogQueue(leveldb::DB *db){
this->db = db;
this->min_seq = 0;
this->last_seq = 0;
this->tran_seq = 0;
this->capacity = LOG_QUEUE_SIZE;
Binlog log;
if(this->find_last(&log) == 1){
this->last_seq = log.seq();
}
if(this->find_next(1, &log) == 1){
this->min_seq = log.seq();
}
log_debug("capacity: %d, min: %llu, max: %llu,", capacity, min_seq, last_seq);
//this->merge();
/*
int noops = 0;
int total = 0;
uint64_t seq = this->min_seq;
while(this->find_next(seq, &log) == 1){
total ++;
seq = log.seq() + 1;
if(log.type() != BinlogType::NOOP){
std::string s = log.dumps();
//log_trace("%s", s.c_str());
noops ++;
}
}
log_debug("capacity: %d, min: %llu, max: %llu, noops: %d, total: %d",
capacity, min_seq, last_seq, noops, total);
*/
// start cleaning thread
thread_quit = false;
pthread_t tid;
int err = pthread_create(&tid, NULL, &BinlogQueue::log_clean_thread_func, this);
if(err != 0){
log_fatal("can't create thread: %s", strerror(err));
exit(0);
}
}
BinlogQueue::~BinlogQueue(){
thread_quit = true;
while(1){
if(thread_quit == false){
break;
}
usleep(100 * 1000);
}
log_debug("BinlogQueue finalized");
}
void BinlogQueue::begin(){
tran_seq = last_seq;
batch.Clear();
}
void BinlogQueue::rollback(){
tran_seq = 0;
}
leveldb::Status BinlogQueue::commit(){
leveldb::WriteOptions write_opts;
leveldb::Status s = db->Write(write_opts, &batch);
if(s.ok()){
last_seq = tran_seq;
tran_seq = 0;
}
return s;
}
void BinlogQueue::add(char type, char cmd, const leveldb::Slice &key){
tran_seq ++;
Binlog log(tran_seq, type, cmd, key);
batch.Put(encode_seq_key(tran_seq), log.repr());
}
void BinlogQueue::add(char type, char cmd, const std::string &key){
leveldb::Slice s(key);
this->add(type, cmd, s);
}
// leveldb put
void BinlogQueue::Put(const leveldb::Slice& key, const leveldb::Slice& value){
batch.Put(key, value);
}
// leveldb delete
void BinlogQueue::Delete(const leveldb::Slice& key){
batch.Delete(key);
}
int BinlogQueue::find_next(uint64_t next_seq, Binlog *log) const{
if(this->get(next_seq, log) == 1){
return 1;
}
uint64_t ret = 0;
std::string key_str = encode_seq_key(next_seq);
leveldb::ReadOptions iterate_options;
leveldb::Iterator *it = db->NewIterator(iterate_options);
it->Seek(key_str);
if(it->Valid()){
leveldb::Slice key = it->key();
if(decode_seq_key(key) != 0){
leveldb::Slice val = it->value();
if(log->load(val) == -1){
ret = -1;
}else{
ret = 1;
}
}
}
delete it;
return ret;
}
int BinlogQueue::find_last(Binlog *log) const{
uint64_t ret = 0;
std::string key_str = encode_seq_key(UINT64_MAX);
leveldb::ReadOptions iterate_options;
leveldb::Iterator *it = db->NewIterator(iterate_options);
it->Seek(key_str);
if(!it->Valid()){
// Iterator::prev requires Valid, so we seek to last
it->SeekToLast();
}
// UINT64_MAX is not used
if(it->Valid()){
it->Prev();
}
if(it->Valid()){
leveldb::Slice key = it->key();
if(decode_seq_key(key) != 0){
leveldb::Slice val = it->value();
if(log->load(val) == -1){
ret = -1;
}else{
ret = 1;
}
}
}
delete it;
return ret;
}
int BinlogQueue::get(uint64_t seq, Binlog *log) const{
std::string val;
leveldb::Status s = db->Get(leveldb::ReadOptions(), encode_seq_key(seq), &val);
if(s.ok()){
if(log->load(val) != -1){
return 1;
}
}
return 0;
}
int BinlogQueue::update(uint64_t seq, char type, char cmd, const std::string &key){
Binlog log(seq, type, cmd, key);
leveldb::Status s = db->Put(leveldb::WriteOptions(), encode_seq_key(seq), log.repr());
if(s.ok()){
return 0;
}
return -1;
}
int BinlogQueue::del(uint64_t seq){
leveldb::Status s = db->Delete(leveldb::WriteOptions(), encode_seq_key(seq));
if(!s.ok()){
return -1;
}
return 0;
}
int BinlogQueue::del_range(uint64_t start, uint64_t end){
while(start <= end){
leveldb::WriteBatch batch;
for(int count = 0; start <= end && count < 1000; start++, count++){
batch.Delete(encode_seq_key(start));
}
leveldb::Status s = db->Write(leveldb::WriteOptions(), &batch);
if(!s.ok()){
return -1;
}
}
return 0;
}
void* BinlogQueue::log_clean_thread_func(void *arg){
BinlogQueue *logs = (BinlogQueue *)arg;
while(!logs->thread_quit){
usleep(200 * 1000);
if(logs->last_seq - logs->min_seq < LOG_QUEUE_SIZE * 1.1){
continue;
}
uint64_t start = logs->min_seq;
uint64_t end = logs->last_seq - LOG_QUEUE_SIZE;
logs->del_range(start, end);
logs->min_seq = end + 1;
log_debug("clean %d logs[%llu ~ %llu], %d left, max: %llu",
end-start+1, start, end, logs->last_seq - logs->min_seq + 1, logs->last_seq);
}
log_debug("clean_thread quit");
logs->thread_quit = false;
return (void *)NULL;
}
// TESTING, slow, so not used
void BinlogQueue::merge(){
std::map<std::string, uint64_t> key_map;
uint64_t start = min_seq;
uint64_t end = last_seq;
int reduce_count = 0;
int total = 0;
total = end - start + 1;
log_trace("merge begin");
for(; start <= end; start++){
Binlog log;
if(this->get(start, &log) == 1){
if(log.type() == BinlogType::NOOP){
continue;
}
std::string key = log.key().String();
std::map<std::string, uint64_t>::iterator it = key_map.find(key);
if(it != key_map.end()){
uint64_t seq = it->second;
this->update(seq, BinlogType::NOOP, BinlogCommand::NONE, "");
//log_trace("merge update %llu to NOOP", seq);
reduce_count ++;
}
key_map[key] = log.seq();
}
}
log_trace("merge reduce %d of %d binlogs", reduce_count, total);
}
<commit_msg>change Binlog::Binlog argument names<commit_after>#include "binlog.h"
#include "util/log.h"
#include "util/strings.h"
#include <map>
/* Binlog */
Binlog::Binlog(uint64_t seq, char type, char cmd, const leveldb::Slice &key){
buf.append((char *)(&seq), sizeof(uint64_t));
buf.push_back(type);
buf.push_back(cmd);
buf.append(key.data(), key.size());
}
uint64_t Binlog::seq() const{
return *((uint64_t *)(buf.data()));
}
char Binlog::type() const{
return buf[sizeof(uint64_t)];
}
char Binlog::cmd() const{
return buf[sizeof(uint64_t) + 1];
}
const Bytes Binlog::key() const{
return Bytes(buf.data() + HEADER_LEN, buf.size() - HEADER_LEN);
}
int Binlog::load(const leveldb::Slice &s){
if(s.size() < HEADER_LEN){
return -1;
}
buf.assign(s.data(), s.size());
return 0;
}
std::string Binlog::dumps() const{
std::string str;
if(buf.size() < HEADER_LEN){
return str;
}
char buf[20];
snprintf(buf, sizeof(buf), "%llu ", this->seq());
str.append(buf);
switch(this->type()){
case BinlogType::NOOP:
str.append("noop ");
break;
case BinlogType::SYNC:
str.append("sync ");
break;
case BinlogType::MIRROR:
str.append("mirror ");
break;
case BinlogType::COPY:
str.append("copy ");
break;
}
switch(this->cmd()){
case BinlogCommand::NONE:
str.append("none ");
break;
case BinlogCommand::KSET:
str.append("set ");
break;
case BinlogCommand::KDEL:
str.append("del ");
break;
case BinlogCommand::HSET:
str.append("hset ");
break;
case BinlogCommand::HDEL:
str.append("hdel ");
break;
case BinlogCommand::ZSET:
str.append("zset ");
break;
case BinlogCommand::ZDEL:
str.append("zdel ");
break;
case BinlogCommand::BEGIN:
str.append("begin ");
break;
case BinlogCommand::END:
str.append("end ");
break;
}
Bytes b = this->key();
str.append(hexmem(b.data(), b.size()));
return str;
}
/* SyncLogQueue */
static inline std::string encode_seq_key(uint64_t seq){
seq = big_endian(seq);
std::string ret;
ret.push_back(DataType::SYNCLOG);
ret.append((char *)&seq, sizeof(seq));
return ret;
}
static inline uint64_t decode_seq_key(const leveldb::Slice &key){
uint64_t seq = 0;
if(key.size() == (sizeof(uint64_t) + 1) && key.data()[0] == DataType::SYNCLOG){
seq = *((uint64_t *)(key.data() + 1));
seq = big_endian(seq);
}
return seq;
}
BinlogQueue::BinlogQueue(leveldb::DB *db){
this->db = db;
this->min_seq = 0;
this->last_seq = 0;
this->tran_seq = 0;
this->capacity = LOG_QUEUE_SIZE;
Binlog log;
if(this->find_last(&log) == 1){
this->last_seq = log.seq();
}
if(this->find_next(1, &log) == 1){
this->min_seq = log.seq();
}
log_debug("capacity: %d, min: %llu, max: %llu,", capacity, min_seq, last_seq);
//this->merge();
/*
int noops = 0;
int total = 0;
uint64_t seq = this->min_seq;
while(this->find_next(seq, &log) == 1){
total ++;
seq = log.seq() + 1;
if(log.type() != BinlogType::NOOP){
std::string s = log.dumps();
//log_trace("%s", s.c_str());
noops ++;
}
}
log_debug("capacity: %d, min: %llu, max: %llu, noops: %d, total: %d",
capacity, min_seq, last_seq, noops, total);
*/
// start cleaning thread
thread_quit = false;
pthread_t tid;
int err = pthread_create(&tid, NULL, &BinlogQueue::log_clean_thread_func, this);
if(err != 0){
log_fatal("can't create thread: %s", strerror(err));
exit(0);
}
}
BinlogQueue::~BinlogQueue(){
thread_quit = true;
while(1){
if(thread_quit == false){
break;
}
usleep(100 * 1000);
}
log_debug("BinlogQueue finalized");
}
void BinlogQueue::begin(){
tran_seq = last_seq;
batch.Clear();
}
void BinlogQueue::rollback(){
tran_seq = 0;
}
leveldb::Status BinlogQueue::commit(){
leveldb::WriteOptions write_opts;
leveldb::Status s = db->Write(write_opts, &batch);
if(s.ok()){
last_seq = tran_seq;
tran_seq = 0;
}
return s;
}
void BinlogQueue::add(char type, char cmd, const leveldb::Slice &key){
tran_seq ++;
Binlog log(tran_seq, type, cmd, key);
batch.Put(encode_seq_key(tran_seq), log.repr());
}
void BinlogQueue::add(char type, char cmd, const std::string &key){
leveldb::Slice s(key);
this->add(type, cmd, s);
}
// leveldb put
void BinlogQueue::Put(const leveldb::Slice& key, const leveldb::Slice& value){
batch.Put(key, value);
}
// leveldb delete
void BinlogQueue::Delete(const leveldb::Slice& key){
batch.Delete(key);
}
int BinlogQueue::find_next(uint64_t next_seq, Binlog *log) const{
if(this->get(next_seq, log) == 1){
return 1;
}
uint64_t ret = 0;
std::string key_str = encode_seq_key(next_seq);
leveldb::ReadOptions iterate_options;
leveldb::Iterator *it = db->NewIterator(iterate_options);
it->Seek(key_str);
if(it->Valid()){
leveldb::Slice key = it->key();
if(decode_seq_key(key) != 0){
leveldb::Slice val = it->value();
if(log->load(val) == -1){
ret = -1;
}else{
ret = 1;
}
}
}
delete it;
return ret;
}
int BinlogQueue::find_last(Binlog *log) const{
uint64_t ret = 0;
std::string key_str = encode_seq_key(UINT64_MAX);
leveldb::ReadOptions iterate_options;
leveldb::Iterator *it = db->NewIterator(iterate_options);
it->Seek(key_str);
if(!it->Valid()){
// Iterator::prev requires Valid, so we seek to last
it->SeekToLast();
}
// UINT64_MAX is not used
if(it->Valid()){
it->Prev();
}
if(it->Valid()){
leveldb::Slice key = it->key();
if(decode_seq_key(key) != 0){
leveldb::Slice val = it->value();
if(log->load(val) == -1){
ret = -1;
}else{
ret = 1;
}
}
}
delete it;
return ret;
}
int BinlogQueue::get(uint64_t seq, Binlog *log) const{
std::string val;
leveldb::Status s = db->Get(leveldb::ReadOptions(), encode_seq_key(seq), &val);
if(s.ok()){
if(log->load(val) != -1){
return 1;
}
}
return 0;
}
int BinlogQueue::update(uint64_t seq, char type, char cmd, const std::string &key){
Binlog log(seq, type, cmd, key);
leveldb::Status s = db->Put(leveldb::WriteOptions(), encode_seq_key(seq), log.repr());
if(s.ok()){
return 0;
}
return -1;
}
int BinlogQueue::del(uint64_t seq){
leveldb::Status s = db->Delete(leveldb::WriteOptions(), encode_seq_key(seq));
if(!s.ok()){
return -1;
}
return 0;
}
int BinlogQueue::del_range(uint64_t start, uint64_t end){
while(start <= end){
leveldb::WriteBatch batch;
for(int count = 0; start <= end && count < 1000; start++, count++){
batch.Delete(encode_seq_key(start));
}
leveldb::Status s = db->Write(leveldb::WriteOptions(), &batch);
if(!s.ok()){
return -1;
}
}
return 0;
}
void* BinlogQueue::log_clean_thread_func(void *arg){
BinlogQueue *logs = (BinlogQueue *)arg;
while(!logs->thread_quit){
usleep(200 * 1000);
if(logs->last_seq - logs->min_seq < LOG_QUEUE_SIZE * 1.1){
continue;
}
uint64_t start = logs->min_seq;
uint64_t end = logs->last_seq - LOG_QUEUE_SIZE;
logs->del_range(start, end);
logs->min_seq = end + 1;
log_debug("clean %d logs[%llu ~ %llu], %d left, max: %llu",
end-start+1, start, end, logs->last_seq - logs->min_seq + 1, logs->last_seq);
}
log_debug("clean_thread quit");
logs->thread_quit = false;
return (void *)NULL;
}
// TESTING, slow, so not used
void BinlogQueue::merge(){
std::map<std::string, uint64_t> key_map;
uint64_t start = min_seq;
uint64_t end = last_seq;
int reduce_count = 0;
int total = 0;
total = end - start + 1;
log_trace("merge begin");
for(; start <= end; start++){
Binlog log;
if(this->get(start, &log) == 1){
if(log.type() == BinlogType::NOOP){
continue;
}
std::string key = log.key().String();
std::map<std::string, uint64_t>::iterator it = key_map.find(key);
if(it != key_map.end()){
uint64_t seq = it->second;
this->update(seq, BinlogType::NOOP, BinlogCommand::NONE, "");
//log_trace("merge update %llu to NOOP", seq);
reduce_count ++;
}
key_map[key] = log.seq();
}
}
log_trace("merge reduce %d of %d binlogs", reduce_count, total);
}
<|endoftext|>
|
<commit_before><commit_msg>Unit test for UNO field item implementation.<commit_after><|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
{
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;
}
<commit_msg>YAML CPP: Use function to determine key iterator<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
{
NameIterator relativeKeyIterator (Key const & key, Key const & parent)
{
auto parentIterator = parent.begin ();
auto keyIterator = key.begin ();
while (parentIterator != parent.end () && keyIterator != key.end ())
{
parentIterator++;
keyIterator++;
}
return keyIterator;
}
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)
{
NameIterator keyIterator = relativeKeyIterator (key, parent);
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>// Copyright 2012-2013 Samplecount S.L.
//
// 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.
#ifndef METHCLA_MEMORY_HPP_INCLUDED
#define METHCLA_MEMORY_HPP_INCLUDED
#include <boost/assert.hpp>
#include <cstddef>
#include <cstdint>
namespace Methcla { namespace Memory {
class Alignment
{
public:
Alignment(size_t alignment)
: m_alignment(alignment)
{
BOOST_ASSERT_MSG( (m_alignment & (m_alignment - 1)) == 0, "Alignment must be a power of two" );
BOOST_ASSERT_MSG( m_alignment >= sizeof(nullptr), "Alignment must be >= sizeof(nullptr)" );
}
Alignment(const Alignment&) = default;
operator size_t () const
{
return m_alignment;
}
template <typename T> bool isAligned(T size) const
{
return isAligned(m_alignment, size);
}
template <typename T> T align(T size) const
{
return align(m_alignment, size);
}
template <typename T> size_t padding(T size) const
{
return padding(m_alignment, size);
}
// Aligning pointers
template <typename T> bool isAligned(T* ptr) const
{
return isAligned(reinterpret_cast<uintptr_t>(ptr));
}
template <typename T> T* align(T* ptr) const
{
return reinterpret_cast<T*>(align(reinterpret_cast<uintptr_t>(ptr)));
}
template <typename T> size_t padding(T* ptr) const
{
return padding(reinterpret_cast<uintptr_t>(ptr));
}
// Static alignment functions
template <typename T> static bool isAligned(size_t alignment, T n)
{
return (n & ~(alignment-1)) == n;
}
template <typename T> static T align(size_t alignment, T n)
{
return (n + alignment) & ~(alignment-1);
}
template <typename T> static size_t padding(size_t alignment, T n)
{
return align(alignment, n) - n;
}
private:
size_t m_alignment;
};
//* Default alignment.
static const Alignment kDefaultAlignment(
#if defined(__ANDROID__)
alignof(max_align_t)
#else
alignof(std::max_align_t)
#endif
);
//* Alignment needed for data accessed by SIMD instructions.
static const Alignment kSIMDAlignment(16);
//* Allocate memory of `size` bytes.
//
// @throw std::invalid_argument
// @throw std::bad_alloc
void* alloc(size_t size);
//* Allocate aligned memory of `size` bytes.
//
// @throw std::invalid_argument
// @throw std::bad_alloc
void* allocAligned(Alignment align, size_t size);
//* Free memory allocated by this allocator.
void free(void* ptr) noexcept;
//* Allocate memory for `n` elements of type `T`.
//
// @throw std::invalid_argument
// @throw std::bad_alloc
template <typename T> T* allocOf(size_t n=1)
{
return static_cast<T*>(alloc(n * sizeof(T)));
}
//* Allocate aligned memory for `n` elements of type `T`.
//
// @throw std::invalid_argument
// @throw std::bad_alloc
template <typename T> T* allocAlignedOf(Alignment align, size_t n=1)
{
return static_cast<T*>(allocAligned(align, n * sizeof(T)));
}
} }
#endif // METHCLA_MEMORY_HPP_INCLUDED
<commit_msg>Ensure alignment is greater than sizeof(void*) in all cases<commit_after>// Copyright 2012-2013 Samplecount S.L.
//
// 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.
#ifndef METHCLA_MEMORY_HPP_INCLUDED
#define METHCLA_MEMORY_HPP_INCLUDED
#include <boost/assert.hpp>
#include <cstddef>
#include <cstdint>
namespace Methcla { namespace Memory {
class Alignment
{
public:
Alignment(size_t alignment)
: m_alignment(std::max(alignment, sizeof(void*)))
{
BOOST_ASSERT_MSG( (m_alignment & (m_alignment - 1)) == 0, "Alignment must be a power of two" );
}
Alignment(const Alignment&) = default;
operator size_t () const
{
return m_alignment;
}
template <typename T> bool isAligned(T size) const
{
return isAligned(m_alignment, size);
}
template <typename T> T align(T size) const
{
return align(m_alignment, size);
}
template <typename T> size_t padding(T size) const
{
return padding(m_alignment, size);
}
// Aligning pointers
template <typename T> bool isAligned(T* ptr) const
{
return isAligned(reinterpret_cast<uintptr_t>(ptr));
}
template <typename T> T* align(T* ptr) const
{
return reinterpret_cast<T*>(align(reinterpret_cast<uintptr_t>(ptr)));
}
template <typename T> size_t padding(T* ptr) const
{
return padding(reinterpret_cast<uintptr_t>(ptr));
}
// Static alignment functions
template <typename T> static bool isAligned(size_t alignment, T n)
{
return (n & ~(alignment-1)) == n;
}
template <typename T> static T align(size_t alignment, T n)
{
return (n + alignment) & ~(alignment-1);
}
template <typename T> static size_t padding(size_t alignment, T n)
{
return align(alignment, n) - n;
}
private:
size_t m_alignment;
};
//* Default alignment.
static const Alignment kDefaultAlignment(
#if defined(__ANDROID__)
alignof(max_align_t)
#else
alignof(std::max_align_t)
#endif
);
//* Alignment needed for data accessed by SIMD instructions.
static const Alignment kSIMDAlignment(16);
//* Allocate memory of `size` bytes.
//
// @throw std::invalid_argument
// @throw std::bad_alloc
void* alloc(size_t size);
//* Allocate aligned memory of `size` bytes.
//
// @throw std::invalid_argument
// @throw std::bad_alloc
void* allocAligned(Alignment align, size_t size);
//* Free memory allocated by this allocator.
void free(void* ptr) noexcept;
//* Allocate memory for `n` elements of type `T`.
//
// @throw std::invalid_argument
// @throw std::bad_alloc
template <typename T> T* allocOf(size_t n=1)
{
return static_cast<T*>(alloc(n * sizeof(T)));
}
//* Allocate aligned memory for `n` elements of type `T`.
//
// @throw std::invalid_argument
// @throw std::bad_alloc
template <typename T> T* allocAlignedOf(Alignment align, size_t n=1)
{
return static_cast<T*>(allocAligned(align, n * sizeof(T)));
}
} }
#endif // METHCLA_MEMORY_HPP_INCLUDED
<|endoftext|>
|
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2000 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Log$
* Revision 1.8 2000/06/16 20:25:23 rahulj
* Add the -v=always option to force validation checking. Need this
* option for running the conformance tests.
*
* Revision 1.7 2000/05/31 18:42:31 rahulj
* 'Auto' validation is the default processing mode.
*
* Revision 1.6 2000/03/03 01:29:29 roddey
* Added a scanReset()/parseReset() method to the scanner and
* parsers, to allow for reset after early exit from a progressive parse.
* Added calls to new Terminate() call to all of the samples. Improved
* documentation in SAX and DOM parsers.
*
* Revision 1.5 2000/03/02 19:53:39 roddey
* This checkin includes many changes done while waiting for the
* 1.1.0 code to be finished. I can't list them all here, but a list is
* available elsewhere.
*
* Revision 1.4 2000/02/11 02:32:46 abagchi
* Removed StrX::transcode
*
* Revision 1.3 2000/02/06 07:47:17 rahulj
* Year 2K copyright swat.
*
* Revision 1.2 1999/11/12 02:13:40 rahulj
* It now validates when the -v option is specified.
*
* Revision 1.1.1.1 1999/11/09 01:09:52 twl
* Initial checkin
*
* Revision 1.8 1999/11/08 20:43:34 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <util/PlatformUtils.hpp>
#include <sax/SAXException.hpp>
#include <sax/SAXParseException.hpp>
#include <parsers/DOMParser.hpp>
#include "DOMCount.hpp"
#include <string.h>
#include <stdlib.h>
// ---------------------------------------------------------------------------
// This is a simple program which invokes the DOMParser to build a DOM
// tree for the specified input file. It then walks the tree and counts
// the number of elements. The element count is then printed.
// ---------------------------------------------------------------------------
void usage()
{
cout << "\nUsage:\n"
" DOMCount [-v -n] {XML file}\n\n"
"This program invokes the XML4C DOM parser, builds\n"
"the DOM tree, and then prints the number of elements\n"
"found in the input XML file.\n\n"
"Options:\n"
" -v=xxx Validation scheme [always | never | auto*]\n"
" -n Enable namespace processing. Defaults to off.\n\n"
" * = Default if not provided explicitly\n\n"
<< endl;
}
int main(int argC, char* argV[])
{
// Initialize the XML4C system
try
{
XMLPlatformUtils::Initialize();
}
catch (const XMLException& toCatch)
{
cerr << "Error during initialization! :\n"
<< StrX(toCatch.getMessage()) << endl;
return 1;
}
// Check command line and extract arguments.
if (argC < 2)
{
usage();
return 1;
}
const char* xmlFile = 0;
DOMParser::ValSchemes valScheme = DOMParser::Val_Auto;
bool doNamespaces = false;
// See if non validating dom parser configuration is requested.
if ((argC == 2) && !strcmp(argV[1], "-?"))
{
usage();
return 2;
}
int argInd;
for (argInd = 1; argInd < argC; argInd++)
{
// Break out on first non-dash parameter
if (argV[argInd][0] != '-')
break;
if (!strncmp(argV[argInd], "-v=", 3)
|| !strncmp(argV[argInd], "-V=", 3))
{
const char* const parm = &argV[argInd][3];
if (!strcmp(parm, "never"))
valScheme = DOMParser::Val_Never;
else if (!strcmp(parm, "auto"))
valScheme = DOMParser::Val_Auto;
else if (!strcmp(parm, "always"))
valScheme = DOMParser::Val_Always;
else
{
cerr << "Unknown -v= value: " << parm << endl;
return 2;
}
}
else if (!strcmp(argV[argInd], "-n")
|| !strcmp(argV[argInd], "-N"))
{
doNamespaces = true;
}
else
{
cerr << "Unknown option '" << argV[argInd]
<< "', ignoring it\n" << endl;
}
}
//
// There should be only one and only one parameter left, and that
// should be the file name.
//
if (argInd != argC - 1)
{
usage();
return 1;
}
xmlFile = argV[argInd];
// Instantiate the DOM parser.
DOMParser parser;
parser.setValidationScheme(valScheme);
parser.setDoNamespaces(doNamespaces);
// And create our error handler and install it
DOMCount elementCounter;
parser.setErrorHandler(&elementCounter);
//
// Get the starting time and kick off the parse of the indicated
// file. Catch any exceptions that might propogate out of it.
//
unsigned long duration;
try
{
const unsigned long startMillis = XMLPlatformUtils::getCurrentMillis();
parser.parse(xmlFile);
const unsigned long endMillis = XMLPlatformUtils::getCurrentMillis();
duration = endMillis - startMillis;
}
catch (const XMLException& toCatch)
{
cerr << "\nError during parsing: '" << xmlFile << "'\n"
<< "Exception message is: \n"
<< StrX(toCatch.getMessage()) << "\n" << endl;
return -1;
}
//
// Extract the DOM tree, get the list of all the elements and report the
// length as the count of elements.
//
if (elementCounter.getSawErrors())
{
cout << "\nErrors occured, no output available\n" << endl;
}
else
{
DOM_Document doc = parser.getDocument();
unsigned int elementCount = doc.getElementsByTagName("*").getLength();
// Print out the stats that we collected and time taken.
cout << xmlFile << ": " << duration << " ms ("
<< elementCount << " elems)." << endl;
}
// And call the termination method
XMLPlatformUtils::Terminate();
return 0;
}
DOMCount::DOMCount() :
fSawErrors(false)
{
}
DOMCount::~DOMCount()
{
}
// ---------------------------------------------------------------------------
// DOMCountHandlers: Overrides of the SAX ErrorHandler interface
// ---------------------------------------------------------------------------
void DOMCount::error(const SAXParseException& e)
{
fSawErrors = true;
cerr << "\nError at file " << StrX(e.getSystemId())
<< ", line " << e.getLineNumber()
<< ", char " << e.getColumnNumber()
<< "\n Message: " << StrX(e.getMessage()) << endl;
}
void DOMCount::fatalError(const SAXParseException& e)
{
fSawErrors = true;
cerr << "\nFatal Error at file " << StrX(e.getSystemId())
<< ", line " << e.getLineNumber()
<< ", char " << e.getColumnNumber()
<< "\n Message: " << StrX(e.getMessage()) << endl;
}
void DOMCount::warning(const SAXParseException& e)
{
cerr << "\nWarning at file " << StrX(e.getSystemId())
<< ", line " << e.getLineNumber()
<< ", char " << e.getColumnNumber()
<< "\n Message: " << StrX(e.getMessage()) << endl;
}
void DOMCount::resetErrors()
{
}
<commit_msg>Modified to catch dom and general exceptions.<commit_after>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2000 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Id$
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <util/PlatformUtils.hpp>
#include <sax/SAXException.hpp>
#include <sax/SAXParseException.hpp>
#include <parsers/DOMParser.hpp>
#include <dom/DOM_DOMException.hpp>
#include "DOMCount.hpp"
#include <string.h>
#include <stdlib.h>
// ---------------------------------------------------------------------------
// This is a simple program which invokes the DOMParser to build a DOM
// tree for the specified input file. It then walks the tree and counts
// the number of elements. The element count is then printed.
// ---------------------------------------------------------------------------
void usage()
{
cout << "\nUsage:\n"
" DOMCount [-v -n] {XML file}\n\n"
"This program invokes the XML4C DOM parser, builds\n"
"the DOM tree, and then prints the number of elements\n"
"found in the input XML file.\n\n"
"Options:\n"
" -v=xxx Validation scheme [always | never | auto*]\n"
" -n Enable namespace processing. Defaults to off.\n\n"
" * = Default if not provided explicitly\n\n"
<< endl;
}
int main(int argC, char* argV[])
{
// Initialize the XML4C system
try
{
XMLPlatformUtils::Initialize();
}
catch (const XMLException& toCatch)
{
cerr << "Error during initialization! :\n"
<< StrX(toCatch.getMessage()) << endl;
return 1;
}
// Check command line and extract arguments.
if (argC < 2)
{
usage();
return 1;
}
const char* xmlFile = 0;
DOMParser::ValSchemes valScheme = DOMParser::Val_Auto;
bool doNamespaces = false;
// See if non validating dom parser configuration is requested.
if ((argC == 2) && !strcmp(argV[1], "-?"))
{
usage();
return 2;
}
int argInd;
for (argInd = 1; argInd < argC; argInd++)
{
// Break out on first non-dash parameter
if (argV[argInd][0] != '-')
break;
if (!strncmp(argV[argInd], "-v=", 3)
|| !strncmp(argV[argInd], "-V=", 3))
{
const char* const parm = &argV[argInd][3];
if (!strcmp(parm, "never"))
valScheme = DOMParser::Val_Never;
else if (!strcmp(parm, "auto"))
valScheme = DOMParser::Val_Auto;
else if (!strcmp(parm, "always"))
valScheme = DOMParser::Val_Always;
else
{
cerr << "Unknown -v= value: " << parm << endl;
return 2;
}
}
else if (!strcmp(argV[argInd], "-n")
|| !strcmp(argV[argInd], "-N"))
{
doNamespaces = true;
}
else
{
cerr << "Unknown option '" << argV[argInd]
<< "', ignoring it\n" << endl;
}
}
//
// There should be only one and only one parameter left, and that
// should be the file name.
//
if (argInd != argC - 1)
{
usage();
return 1;
}
xmlFile = argV[argInd];
// Instantiate the DOM parser.
DOMParser parser;
parser.setValidationScheme(valScheme);
parser.setDoNamespaces(doNamespaces);
// And create our error handler and install it
DOMCount elementCounter;
parser.setErrorHandler(&elementCounter);
//
// Get the starting time and kick off the parse of the indicated
// file. Catch any exceptions that might propogate out of it.
//
unsigned long duration;
try
{
const unsigned long startMillis = XMLPlatformUtils::getCurrentMillis();
parser.parse(xmlFile);
const unsigned long endMillis = XMLPlatformUtils::getCurrentMillis();
duration = endMillis - startMillis;
}
catch (const XMLException& toCatch)
{
cerr << "\nError during parsing: '" << xmlFile << "'\n"
<< "Exception message is: \n"
<< StrX(toCatch.getMessage()) << "\n" << endl;
return -1;
}
catch (const DOM_DOMException& toCatch)
{
cerr << "\nError during parsing: '" << xmlFile << "'\n"
<< "Exception message is: \n"
<< toCatch.msg.transcode() << "\n" << endl;
XMLPlatformUtils::Terminate();
return 4;
}
catch (...)
{
cerr << "\nUnexpected exception during parsing: '" << xmlFile << "'\n";
XMLPlatformUtils::Terminate();
return 4;
}
//
// Extract the DOM tree, get the list of all the elements and report the
// length as the count of elements.
//
if (elementCounter.getSawErrors())
{
cout << "\nErrors occured, no output available\n" << endl;
}
else
{
DOM_Document doc = parser.getDocument();
unsigned int elementCount = doc.getElementsByTagName("*").getLength();
// Print out the stats that we collected and time taken.
cout << xmlFile << ": " << duration << " ms ("
<< elementCount << " elems)." << endl;
}
// And call the termination method
XMLPlatformUtils::Terminate();
return 0;
}
DOMCount::DOMCount() :
fSawErrors(false)
{
}
DOMCount::~DOMCount()
{
}
// ---------------------------------------------------------------------------
// DOMCountHandlers: Overrides of the SAX ErrorHandler interface
// ---------------------------------------------------------------------------
void DOMCount::error(const SAXParseException& e)
{
fSawErrors = true;
cerr << "\nError at file " << StrX(e.getSystemId())
<< ", line " << e.getLineNumber()
<< ", char " << e.getColumnNumber()
<< "\n Message: " << StrX(e.getMessage()) << endl;
}
void DOMCount::fatalError(const SAXParseException& e)
{
fSawErrors = true;
cerr << "\nFatal Error at file " << StrX(e.getSystemId())
<< ", line " << e.getLineNumber()
<< ", char " << e.getColumnNumber()
<< "\n Message: " << StrX(e.getMessage()) << endl;
}
void DOMCount::warning(const SAXParseException& e)
{
cerr << "\nWarning at file " << StrX(e.getSystemId())
<< ", line " << e.getLineNumber()
<< ", char " << e.getColumnNumber()
<< "\n Message: " << StrX(e.getMessage()) << endl;
}
void DOMCount::resetErrors()
{
}
<|endoftext|>
|
<commit_before>#include <iostream> /* allows to perform standard input and output operations */
#include <fstream>
#include <stdio.h> /* Standard input/output definitions */
#include <stdint.h> /* Standard input/output definitions */
#include <stdlib.h> /* defines several general purpose functions */
//#include <string> /* String function definitions */
#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
//#include <errno.h> /* Error number definitions */
//#include <termios.h> /* POSIX terminal control definitions */
#include <ctype.h> /* isxxx() */
#include <ros/ros.h> /* ROS */
#include <geometry_msgs/Twist.h> /* ROS Twist message */
#include <base_controller/encoders.h> /* Custom message /encoders */
//const char* serialport="/dev/ttyAMA0"; /* defines used serialport */
//int serialport_bps=B38400; /* defines baudrate od serialport */
int32_t EncoderL; /* stores encoder value left read from md49 */
int32_t EncoderR; /* stores encoder value right read from md49 */
unsigned char speed_l=128, speed_r=128; /* speed to set for MD49 */
unsigned char last_speed_l=128, last_speed_r=128; /* speed to set for MD49 */
//bool cmd_vel_received=true;
double vr = 0.0;
double vl = 0.0;
double max_vr = 0.2;
double max_vl = 0.2;
double min_vr = 0.2;
double min_vl = 0.2;
double base_width = 0.4; /* Base width in meters */
unsigned char serialBuffer[18]; /* Serial buffer to store uart data */
void read_MD49_Data (void);
void set_MD49_speed (unsigned char speed_l, unsigned char speed_r);
char* itoa(int value, char* result, int base);
using namespace std;
void cmd_vel_callback(const geometry_msgs::Twist& vel_cmd){
if (vel_cmd.linear.x>0){
speed_l = 255;
speed_r = 255;
}
if (vel_cmd.linear.x<0){
speed_l = 0;
speed_r = 0;
}
if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){
speed_l = 128;
speed_r = 128;
}
if (vel_cmd.angular.z>0){
speed_l = 0;
speed_r = 255;
}
if (vel_cmd.angular.z<0){
speed_l = 255;
speed_r = 0;
}
if ((speed_l != last_speed_l) || (speed_r != last_speed_r)){
set_MD49_speed(speed_l,speed_r);
last_speed_l=speed_l;
last_speed_r=speed_r;
}
/*
//ANFANG Alternative
if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){vl=0;vr=0;}
else if(vel_cmd.linear.x == 0){
// turning
vr = vel_cmd.angular.z * base_width / 2.0;
vl = (-1) * vr;
}
else if(vel_cmd.angular.z == 0){
// forward / backward
vl = vr = vel_cmd.linear.x;
}
else{
// moving doing arcs
vl = vel_cmd.linear.x - vel_cmd.angular.z * base_width / 2.0;
if (vl > max_vl) {vl=max_vl;}
if (vl < min_vl) {vl=min_vl;}
vr = vel_cmd.linear.x + vel_cmd.angular.z * base_width / 2.0;
if (vr > max_vr) {vr=max_vr;}
if (vr < min_vr) {vr=min_vr;}
}
//ENDE Alternative
*/
}
int main( int argc, char* argv[] ){
ros::init(argc, argv, "base_controller" );
ros::NodeHandle n;
ros::Subscriber sub = n.subscribe("/cmd_vel", 10, cmd_vel_callback);
ros::Publisher encoders_pub = n.advertise<base_controller::encoders>("encoders",10);
// Set nodes looprate 5Hz
// ***********************
ros::Rate loop_rate(5);
ROS_INFO("base_controller running...");
while( n.ok() )
{
// Publish encoder values to topic /encoders (custom message)
// ********************************************************************
base_controller::encoders encoders;
encoders.encoder_l=EncoderL;
encoders.encoder_r=EncoderR;
encoders_pub.publish(encoders);
// Read encoder and other data from MD49
// *************************************
read_MD49_Data();
// Loop
// ****
//set_MD49_speed(speed_l,speed_r);
ros::spinOnce();
loop_rate.sleep();
}// end.mainloop
return 1;
} // end.main
void read_MD49_Data (void){
//serialBuffer[0] = 82; // 82=R Steuerbyte um alle Daten vom MD49 zu lesen
//writeBytes(fd, 1);
//Daten lesen und in Array schreiben
//readBytes(fd, 18);
string line;
ifstream myfile ("md49_data.txt");
if (myfile.is_open())
{
int i=0;
while ( getline (myfile,line) )
{
//cout << line << '\n';
char data[10];
std::copy(line.begin(), line.end(), data);
serialBuffer[i]=atoi(data);
i =i++;
}
myfile.close();
}
else cout << "Unable to open file";
/*
printf("\033[2J"); // clear the screen
printf("\033[H"); // position cursor at top-left corner
printf ("MD49-Data read from AVR-Master: \n");
printf("====================================================== \n");
printf("Encoder1 Byte1: %i ",serialBuffer[0]);
printf("Byte2: %i ",serialBuffer[1]);
printf("Byte3: % i ",serialBuffer[2]);
printf("Byte4: %i \n",serialBuffer[3]);
printf("Encoder2 Byte1: %i ",serialBuffer[4]);
printf("Byte2: %i ",serialBuffer[5]);
printf("Byte3: %i ",serialBuffer[6]);
printf("Byte4: %i \n",serialBuffer[7]);
printf("EncoderL: %i ",EncoderL);
printf("EncoderR: %i \n",EncoderR);
printf("====================================================== \n");
printf("Speed1: %i ",serialBuffer[8]);
printf("Speed2: %i \n",serialBuffer[9]);
printf("Volts: %i \n",serialBuffer[10]);
printf("Current1: %i ",serialBuffer[11]);
printf("Current2: %i \n",serialBuffer[12]);
printf("Error: %i \n",serialBuffer[13]);
printf("Acceleration: %i \n",serialBuffer[14]);
printf("Mode: %i \n",serialBuffer[15]);
printf("Regulator: %i \n",serialBuffer[16]);
printf("Timeout: %i \n",serialBuffer[17]);
*/
// printf("vl= %f \n", vl);
// printf("vr= %f \n", vr);
EncoderL = serialBuffer[0] << 24; // Put together first encoder value
EncoderL |= (serialBuffer[1] << 16);
EncoderL |= (serialBuffer[2] << 8);
EncoderL |= (serialBuffer[3]);
EncoderR = serialBuffer[4] << 24; // Put together second encoder value
EncoderR |= (serialBuffer[5] << 16);
EncoderR |= (serialBuffer[6] << 8);
EncoderR |= (serialBuffer[7]);
}
void set_MD49_speed (unsigned char speed_l, unsigned char speed_r){
char buffer[33];
ofstream myfile;
myfile.open ("md49_commands.txt");
//myfile << "Writing this to a file.\n";
if (speed_l==0){
myfile << "000";
myfile << "\n";
}
else if (speed_l<10){
myfile << "00";
myfile << itoa(speed_l,buffer,10);
}
else if (speed_l<100){
myfile << "0";
myfile << itoa(speed_l,buffer,10);
}
else{
myfile << itoa(speed_l,buffer,10);
}
myfile << "\n";
if (speed_r==0){
myfile << "000";
myfile << "\n";
}
else if (speed_r<10){
myfile << "00";
myfile << itoa(speed_r,buffer,10);
}
else if (speed_r<100){
myfile << "0";
myfile << itoa(speed_r,buffer,10);
}
else{
myfile << itoa(speed_r,buffer,10);
}
myfile << "\n";
myfile.close();
}
char* itoa(int value, char* result, int base) {
// check that the base if valid
if (base < 2 || base > 36) { *result = '\0'; return result; }
char* ptr = result, *ptr1 = result, tmp_char;
int tmp_value;
do {
tmp_value = value;
value /= base;
*ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)];
} while ( value );
// Apply negative sign
if (tmp_value < 0) *ptr++ = '-';
*ptr-- = '\0';
while(ptr1 < ptr) {
tmp_char = *ptr;
*ptr--= *ptr1;
*ptr1++ = tmp_char;
}
return result;
}
<commit_msg>Update code<commit_after>#include <iostream> /* allows to perform standard input and output operations */
#include <fstream>
#include <stdio.h> /* Standard input/output definitions */
#include <stdint.h> /* Standard input/output definitions */
#include <stdlib.h> /* defines several general purpose functions */
//#include <string> /* String function definitions */
#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
//#include <errno.h> /* Error number definitions */
//#include <termios.h> /* POSIX terminal control definitions */
#include <ctype.h> /* isxxx() */
#include <ros/ros.h> /* ROS */
#include <geometry_msgs/Twist.h> /* ROS Twist message */
#include <base_controller/encoders.h> /* Custom message /encoders */
//const char* serialport="/dev/ttyAMA0"; /* defines used serialport */
//int serialport_bps=B38400; /* defines baudrate od serialport */
int32_t EncoderL; /* stores encoder value left read from md49 */
int32_t EncoderR; /* stores encoder value right read from md49 */
unsigned char speed_l=128, speed_r=128; /* speed to set for MD49 */
unsigned char last_speed_l=128, last_speed_r=128; /* speed to set for MD49 */
//bool cmd_vel_received=true;
double vr = 0.0;
double vl = 0.0;
double max_vr = 0.2;
double max_vl = 0.2;
double min_vr = 0.2;
double min_vl = 0.2;
double base_width = 0.4; /* Base width in meters */
unsigned char serialBuffer[18]; /* Serial buffer to store uart data */
void read_MD49_Data (void);
void set_MD49_speed (unsigned char speed_l, unsigned char speed_r);
char* itoa(int value, char* result, int base);
using namespace std;
void cmd_vel_callback(const geometry_msgs::Twist& vel_cmd){
if (vel_cmd.linear.x>0){
speed_l = 255;
speed_r = 255;
}
if (vel_cmd.linear.x<0){
speed_l = 0;
speed_r = 0;
}
if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){
speed_l = 128;
speed_r = 128;
}
if (vel_cmd.angular.z>0){
speed_l = 0;
speed_r = 255;
}
if (vel_cmd.angular.z<0){
speed_l = 255;
speed_r = 0;
}
if ((speed_l != last_speed_l) || (speed_r != last_speed_r)){
set_MD49_speed(speed_l,speed_r);
last_speed_l=speed_l;
last_speed_r=speed_r;
}
/*
//ANFANG Alternative
if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){vl=0;vr=0;}
else if(vel_cmd.linear.x == 0){
// turning
vr = vel_cmd.angular.z * base_width / 2.0;
vl = (-1) * vr;
}
else if(vel_cmd.angular.z == 0){
// forward / backward
vl = vr = vel_cmd.linear.x;
}
else{
// moving doing arcs
vl = vel_cmd.linear.x - vel_cmd.angular.z * base_width / 2.0;
if (vl > max_vl) {vl=max_vl;}
if (vl < min_vl) {vl=min_vl;}
vr = vel_cmd.linear.x + vel_cmd.angular.z * base_width / 2.0;
if (vr > max_vr) {vr=max_vr;}
if (vr < min_vr) {vr=min_vr;}
}
//ENDE Alternative
*/
}
int main( int argc, char* argv[] ){
ros::init(argc, argv, "base_controller" );
ros::NodeHandle n;
ros::Subscriber sub = n.subscribe("/cmd_vel", 10, cmd_vel_callback);
ros::Publisher encoders_pub = n.advertise<base_controller::encoders>("encoders",10);
// Set nodes looprate 5Hz
// ***********************
ros::Rate loop_rate(5);
ROS_INFO("base_controller running...");
while( n.ok() )
{
// Publish encoder values to topic /encoders (custom message)
// ********************************************************************
base_controller::encoders encoders;
encoders.encoder_l=EncoderL;
encoders.encoder_r=EncoderR;
encoders_pub.publish(encoders);
// Read encoder and other data from MD49
// *************************************
read_MD49_Data();
// Loop
// ****
//set_MD49_speed(speed_l,speed_r);
ros::spinOnce();
loop_rate.sleep();
}// end.mainloop
return 1;
} // end.main
void read_MD49_Data (void){
//serialBuffer[0] = 82; // 82=R Steuerbyte um alle Daten vom MD49 zu lesen
//writeBytes(fd, 1);
//Daten lesen und in Array schreiben
//readBytes(fd, 18);
string line;
ifstream myfile ("md49_data.txt");
if (myfile.is_open())
{
int i=0;
while ( getline (myfile,line) )
{
//cout << line << '\n';
char data[10];
std::copy(line.begin(), line.end(), data);
serialBuffer[i]=atoi(data);
i =i++;
}
myfile.close();
}
else cout << "Unable to open file";
/*
printf("\033[2J"); // clear the screen
printf("\033[H"); // position cursor at top-left corner
printf ("MD49-Data read from AVR-Master: \n");
printf("====================================================== \n");
printf("Encoder1 Byte1: %i ",serialBuffer[0]);
printf("Byte2: %i ",serialBuffer[1]);
printf("Byte3: % i ",serialBuffer[2]);
printf("Byte4: %i \n",serialBuffer[3]);
printf("Encoder2 Byte1: %i ",serialBuffer[4]);
printf("Byte2: %i ",serialBuffer[5]);
printf("Byte3: %i ",serialBuffer[6]);
printf("Byte4: %i \n",serialBuffer[7]);
printf("EncoderL: %i ",EncoderL);
printf("EncoderR: %i \n",EncoderR);
printf("====================================================== \n");
printf("Speed1: %i ",serialBuffer[8]);
printf("Speed2: %i \n",serialBuffer[9]);
printf("Volts: %i \n",serialBuffer[10]);
printf("Current1: %i ",serialBuffer[11]);
printf("Current2: %i \n",serialBuffer[12]);
printf("Error: %i \n",serialBuffer[13]);
printf("Acceleration: %i \n",serialBuffer[14]);
printf("Mode: %i \n",serialBuffer[15]);
printf("Regulator: %i \n",serialBuffer[16]);
printf("Timeout: %i \n",serialBuffer[17]);
*/
// printf("vl= %f \n", vl);
// printf("vr= %f \n", vr);
EncoderL = serialBuffer[0] << 24; // Put together first encoder value
EncoderL |= (serialBuffer[1] << 16);
EncoderL |= (serialBuffer[2] << 8);
EncoderL |= (serialBuffer[3]);
EncoderR = serialBuffer[4] << 24; // Put together second encoder value
EncoderR |= (serialBuffer[5] << 16);
EncoderR |= (serialBuffer[6] << 8);
EncoderR |= (serialBuffer[7]);
}
void set_MD49_speed (unsigned char speed_l, unsigned char speed_r){
char buffer[33];
ofstream myfile;
myfile.open ("md49_commands.txt");
//myfile << "Writing this to a file.\n";
if (speed_l==0){
myfile << "000";
myfile << "\n";
}
else if (speed_l<10){
myfile << "00";
myfile << itoa(speed_l,buffer,10);
myfile << "\n";
}
else if (speed_l<100){
myfile << "0";
myfile << itoa(speed_l,buffer,10);
myfile << "\n";
}
else{
myfile << itoa(speed_l,buffer,10);
myfile << "\n";
}
if (speed_r==0){
myfile << "000";
myfile << "\n";
}
else if (speed_r<10){
myfile << "00";
myfile << itoa(speed_r,buffer,10);
myfile << "\n";
}
else if (speed_r<100){
myfile << "0";
myfile << itoa(speed_r,buffer,10);
myfile << "\n";
}
else{
myfile << itoa(speed_r,buffer,10);
myfile << "\n";
}
myfile.close();
}
char* itoa(int value, char* result, int base) {
// check that the base if valid
if (base < 2 || base > 36) { *result = '\0'; return result; }
char* ptr = result, *ptr1 = result, tmp_char;
int tmp_value;
do {
tmp_value = value;
value /= base;
*ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)];
} while ( value );
// Apply negative sign
if (tmp_value < 0) *ptr++ = '-';
*ptr-- = '\0';
while(ptr1 < ptr) {
tmp_char = *ptr;
*ptr--= *ptr1;
*ptr1++ = tmp_char;
}
return result;
}
<|endoftext|>
|
<commit_before>#include "brandes.h"
#include <queue>
#include <stack>
#include <algorithm>
#include <thread>
template<typename T>
void Brandes<T>::process(T vertex_id, std::unordered_map<T, fType> *BC_local)
{
std::stack<T> S;
std::unordered_map<T, std::vector<T> > P;
std::unordered_map<T, int> sigma;
std::unordered_map<T, int> d;
std::unordered_map<T, fType> delta;
for (T w : graph_.get_vertex_ids()) {
P[w] = std::vector<T>();
sigma[w] = 0;
d[w] = -1;
delta[w] = 0;
}
sigma[vertex_id] = 1;
d[vertex_id] = 0;
std::queue<T> Q;
Q.push(vertex_id);
while (!Q.empty()) {
T v = Q.front();
Q.pop();
S.push(v);
for (auto w : graph_.get_neighbors(v)) {
if (d[w] < 0) {
Q.push(w);
d[w] = d[v] + 1;
}
if (d[w] == d[v] + 1) {
sigma[w] += sigma[v];
P[w].emplace_back(v);
}
}
}
while (!S.empty()) {
T v = S.top(); S.pop();
for (T p : P[v]) {
double result = (fType(sigma[p]) / sigma[v]) * (1.0 + delta[v]);
delta[p] += result;
}
if (v != vertex_id) {
(*BC_local)[v] += delta[v];
}
}
}
template<typename T>
void Brandes<T>::run_worker(const std::vector<T> &jobs, std::atomic<int> *idx) {
std::unordered_map<T, fType> BC_local;
for (T w : graph_.get_vertex_ids()) {
BC_local[w] = 0;
}
while(true) {
int my_index = (*idx)--;
if (my_index < 0)
break;
process(jobs[my_index], &BC_local);
}
// Synchronized section
{
std::lock_guard<std::mutex> guard(bc_mutex_);
for (auto it : BC_local) {
BC_[it.first] += it.second;
}
}
}
template<typename T>
void Brandes<T>::run(const size_t thread_num) {
std::vector<std::thread> threads;
std::vector<T> jobs;
std::atomic<int> index;
// add jobs
for (auto id : graph_.get_vertex_ids())
jobs.emplace_back(id);
index.store(jobs.size() - 1);
// run threads
for (size_t i = 0; i < thread_num; i++)
threads.emplace_back(std::thread( [this, &jobs, &index] { run_worker(jobs, &index); }));
// wait for them to finish
for (auto& thread : threads)
thread.join();
}
template<typename T>
const std::vector<std::pair<T, typename Brandes<T>::fType>>
Brandes<T>::get_result_vector() const {
std::vector<std::pair<T, fType>> results;
results.reserve(BC_.size());
for (auto it : BC_) {
results.emplace_back( std::make_pair(it.first, it.second));
}
sort(begin(results), end(results));
return results;
}
<commit_msg>Modify algorithm to reduce number of threads<commit_after>#include "brandes.h"
#include <queue>
#include <stack>
#include <algorithm>
#include <thread>
template<typename T>
void Brandes<T>::process(T vertex_id, std::unordered_map<T, fType> *BC_local)
{
std::stack<T> S;
std::unordered_map<T, std::vector<T> > P;
std::unordered_map<T, int> sigma;
std::unordered_map<T, int> d;
std::unordered_map<T, fType> delta;
for (T w : graph_.get_vertex_ids()) {
P[w] = std::vector<T>();
sigma[w] = 0;
d[w] = -1;
delta[w] = 0;
}
sigma[vertex_id] = 1;
d[vertex_id] = 0;
std::queue<T> Q;
Q.push(vertex_id);
while (!Q.empty()) {
T v = Q.front();
Q.pop();
S.push(v);
for (auto w : graph_.get_neighbors(v)) {
if (d[w] < 0) {
Q.push(w);
d[w] = d[v] + 1;
}
if (d[w] == d[v] + 1) {
sigma[w] += sigma[v];
P[w].emplace_back(v);
}
}
}
while (!S.empty()) {
T v = S.top(); S.pop();
for (T p : P[v]) {
double result = (fType(sigma[p]) / sigma[v]) * (1.0 + delta[v]);
delta[p] += result;
}
if (v != vertex_id) {
(*BC_local)[v] += delta[v];
}
}
}
template<typename T>
void Brandes<T>::run_worker(const std::vector<T> &jobs, std::atomic<int> *idx) {
std::unordered_map<T, fType> BC_local;
for (T w : graph_.get_vertex_ids()) {
BC_local[w] = 0;
}
while(true) {
int my_index = (*idx)--;
if (my_index < 0)
break;
process(jobs[my_index], &BC_local);
}
// Synchronized section
{
std::lock_guard<std::mutex> guard(bc_mutex_);
for (auto it : BC_local) {
BC_[it.first] += it.second;
}
}
}
template<typename T>
void Brandes<T>::run(const size_t thread_num) {
std::vector<std::thread> threads;
std::vector<T> jobs;
std::atomic<int> index;
// add jobs
for (auto id : graph_.get_vertex_ids())
jobs.emplace_back(id);
index.store(jobs.size() - 1);
// run threads
for (size_t i = 0; i < thread_num-1; i++)
threads.emplace_back(std::thread( [this, &jobs, &index] { run_worker(jobs, &index); }));
run_worker(jobs, &index);
// wait for others to finish
for (auto& thread : threads)
thread.join();
}
template<typename T>
const std::vector<std::pair<T, typename Brandes<T>::fType>>
Brandes<T>::get_result_vector() const {
std::vector<std::pair<T, fType>> results;
results.reserve(BC_.size());
for (auto it : BC_) {
results.emplace_back( std::make_pair(it.first, it.second));
}
sort(begin(results), end(results));
return results;
}
<|endoftext|>
|
<commit_before>/*
* main.cpp -- This file is part of primesieve
*
* Copyright (C) 2011 Kim Walisch, <kim.walisch@gmail.com>
*
* 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 <QtGui/QApplication>
#include "PrimeSieveGUI.h"
#include "../soe/ParallelPrimeSieve.h"
#include <QSharedMemory>
#include <stdint.h>
#include <stdexcept>
#include <cstdlib>
#include <iostream>
/**
* The Qt GUI interface is launched if the user launches the
* application by mouse click, a ParallelPrimeSieve process is
* launched if exactly one argument (shared memory identifier) is
* provided.
* @see createProcesses(...)
* @param argv[1] Shared memory identifier
*/
int main(int argc, char *argv[]) {
// Qt GUI interface
if (argc != 2) {
QApplication a(argc, argv);
PrimeSieveGUI w;
w.show();
return a.exec();
}
// ParallelPrimeSieve process
else {
// open an existing and initialized shared memory
QSharedMemory sharedMemory(argv[1]);
if (!sharedMemory.attach()) {
std::cerr << "Unable to attach shared memory " << argv[1] << std::endl;
exit(EXIT_FAILURE);
}
// map the attached shared memory to the results structure
ParallelPrimeSieve::SharedMemoryPPS* sharedMemoryPPS =
static_cast<ParallelPrimeSieve::SharedMemoryPPS*> (sharedMemory.data());
try {
// create a new ParallelPrimeSieve object which is initialized
// with values from the shared memory (provided by the Qt GUI),
// upon completion ParallelPrimeSieve communicates its results
// back to the Qt GUI through the shared memory segment.
ParallelPrimeSieve primesieve;
primesieve.setSharedMemory(sharedMemoryPPS);
primesieve.sieve(sharedMemoryPPS->threads);
}
catch (std::exception& ex) {
sharedMemory.detach();
std::cerr << "ParallelPrimeSieve error: " << ex.what() << std::endl;
exit(EXIT_FAILURE);
}
sharedMemory.detach();
}
// exit success
return 0;
}
<commit_msg>fixed Mac OS X application startup bug<commit_after>/*
* main.cpp -- This file is part of primesieve
*
* Copyright (C) 2011 Kim Walisch, <kim.walisch@gmail.com>
*
* 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 <QtGui/QApplication>
#include "PrimeSieveGUI.h"
#include "../soe/ParallelPrimeSieve.h"
#include <QSharedMemory>
#include <stdint.h>
#include <stdexcept>
#include <cstdlib>
#include <iostream>
/**
* The primesieve GUI interface is launched if the user launches the
* application by mouse click, a PrimeSieveProcess is launched if
* "PrimeSieveProcess" and a shared memory identifier (process id) are
* provided as arguments.
* @see PrimeSieveProcess.cpp
* @param argv[1] ["PrimeSieveProcess"]
* @param argv[2] [Shared memory identifier]
*/
int main(int argc, char *argv[]) {
// PrimeSieveProcess
if (argc == 3 && QString(argv[1]).compare("PrimeSieveProcess") == 0) {
// open an existing and initialized shared memory
QSharedMemory sharedMemory(argv[2]);
if (!sharedMemory.attach()) {
std::cerr << "Unable to attach shared memory " << argv[2] << std::endl;
exit(EXIT_FAILURE);
}
// map the attached shared memory to the results structure
ParallelPrimeSieve::SharedMemoryPPS* sharedMemoryPPS =
static_cast<ParallelPrimeSieve::SharedMemoryPPS*> (sharedMemory.data());
try {
ParallelPrimeSieve primesieve;
// initialize the ParallelPrimeSieve object with values from the
// shared memory provided by the primesieve GUI
primesieve.setSharedMemory(sharedMemoryPPS);
// start sieving primes, the results are communicated back to
// the primesieve GUI via the shared memory
primesieve.sieve(sharedMemoryPPS->threads);
}
catch (std::exception& ex) {
sharedMemory.detach();
std::cerr << "ParallelPrimeSieve error: " << ex.what() << std::endl;
exit(EXIT_FAILURE);
}
sharedMemory.detach();
// exit success
return 0;
}
else { // Qt GUI interface
QApplication a(argc, argv);
PrimeSieveGUI w;
w.show();
return a.exec();
}
}
<|endoftext|>
|
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* LXQt - a lightweight, Qt based, desktop toolset
* https://lxqt.org
*
* Copyright: 2010-2011 Razor team
* Authors:
* Alexander Sokoloff <sokoloff.a@gmail.com>
*
* This program or library is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General
* Public License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*
* END_COMMON_COPYRIGHT_HEADER */
#include "xdgaction.h"
#include "xdgicon.h"
#include <QDebug>
#include <QCoreApplication>
XdgAction::XdgAction(QObject *parent):
QAction(parent)
{
}
XdgAction::XdgAction(const XdgDesktopFile& desktopFile, QObject *parent):
QAction(parent)
{
load(desktopFile);
}
XdgAction::XdgAction(const XdgDesktopFile* desktopFile, QObject *parent):
QAction(parent)
{
load(*desktopFile);
}
XdgAction::XdgAction(const QString& desktopFileName, QObject *parent):
QAction(parent)
{
XdgDesktopFile df;
df.load(desktopFileName);
load(df);
}
XdgAction::XdgAction(const XdgAction& other, QObject *parent):
QAction(parent)
{
load(other.mDesktopFile);
}
XdgAction::~XdgAction()
{
}
XdgAction& XdgAction::operator=(const XdgAction& other)
{
load(other.mDesktopFile);
return *this;
}
bool XdgAction::isValid() const
{
return mDesktopFile.isValid();
}
void XdgAction::load(const XdgDesktopFile& desktopFile)
{
mDesktopFile = desktopFile;
if (mDesktopFile.isValid())
{
// & is reserved for mnemonics
setText(mDesktopFile.name().replace(QLatin1Char('&'), QLatin1String("&&")));
setToolTip(mDesktopFile.comment());
connect(this, SIGNAL(triggered()), this, SLOT(runConmmand()));
QMetaObject::invokeMethod(this, "updateIcon", Qt::QueuedConnection);
}
else
{
setText(QString());
setToolTip(QString());
setIcon(QIcon());
}
}
void XdgAction::runConmmand() const
{
if (mDesktopFile.isValid())
mDesktopFile.startDetached();
}
void XdgAction::updateIcon()
{
setIcon(mDesktopFile.icon());
if (icon().isNull())
setIcon(XdgIcon::fromTheme(QLatin1String("application-x-executable")));
QCoreApplication::processEvents();
}
<commit_msg>xdgaction: Remove unneeded processEvents() call<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* LXQt - a lightweight, Qt based, desktop toolset
* https://lxqt.org
*
* Copyright: 2010-2011 Razor team
* Authors:
* Alexander Sokoloff <sokoloff.a@gmail.com>
*
* This program or library is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General
* Public License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*
* END_COMMON_COPYRIGHT_HEADER */
#include "xdgaction.h"
#include "xdgicon.h"
#include <QDebug>
#include <QCoreApplication>
XdgAction::XdgAction(QObject *parent):
QAction(parent)
{
}
XdgAction::XdgAction(const XdgDesktopFile& desktopFile, QObject *parent):
QAction(parent)
{
load(desktopFile);
}
XdgAction::XdgAction(const XdgDesktopFile* desktopFile, QObject *parent):
QAction(parent)
{
load(*desktopFile);
}
XdgAction::XdgAction(const QString& desktopFileName, QObject *parent):
QAction(parent)
{
XdgDesktopFile df;
df.load(desktopFileName);
load(df);
}
XdgAction::XdgAction(const XdgAction& other, QObject *parent):
QAction(parent)
{
load(other.mDesktopFile);
}
XdgAction::~XdgAction()
{
}
XdgAction& XdgAction::operator=(const XdgAction& other)
{
load(other.mDesktopFile);
return *this;
}
bool XdgAction::isValid() const
{
return mDesktopFile.isValid();
}
void XdgAction::load(const XdgDesktopFile& desktopFile)
{
mDesktopFile = desktopFile;
if (mDesktopFile.isValid())
{
// & is reserved for mnemonics
setText(mDesktopFile.name().replace(QLatin1Char('&'), QLatin1String("&&")));
setToolTip(mDesktopFile.comment());
connect(this, SIGNAL(triggered()), this, SLOT(runConmmand()));
QMetaObject::invokeMethod(this, "updateIcon", Qt::QueuedConnection);
}
else
{
setText(QString());
setToolTip(QString());
setIcon(QIcon());
}
}
void XdgAction::runConmmand() const
{
if (mDesktopFile.isValid())
mDesktopFile.startDetached();
}
void XdgAction::updateIcon()
{
setIcon(mDesktopFile.icon());
if (icon().isNull())
setIcon(XdgIcon::fromTheme(QLatin1String("application-x-executable")));
}
<|endoftext|>
|
<commit_before>/****************************************************************************
This file is part of the GLC-lib library.
Copyright (C) 2005-2006 Laurent Ribon (laumaya@users.sourceforge.net)
Version 0.9.6, packaged on June, 2006.
http://glc-lib.sourceforge.net
GLC-lib is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
GLC-lib 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 GLC-lib; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*****************************************************************************/
//! \file glc_factory.cpp implementation of the GLC_Factory class.
#include "glc_factory.h"
#include "glc_objtomesh2.h"
// init static member
GLC_Factory* GLC_Factory::m_pFactory= NULL;
//////////////////////////////////////////////////////////////////////
// static method
//////////////////////////////////////////////////////////////////////
// Return the unique instance of the factory
GLC_Factory* GLC_Factory::instance(QGLWidget *GLWidget)
{
if(m_pFactory == NULL)
{
m_pFactory= new GLC_Factory(GLWidget);
}
return m_pFactory;
}
//////////////////////////////////////////////////////////////////////
// Constructor destructor
//////////////////////////////////////////////////////////////////////
// Protected constructor
GLC_Factory::GLC_Factory(QGLWidget *GLWidget)
: m_pQGLWidget(GLWidget)
{
}
// Destructor
GLC_Factory::~GLC_Factory()
{
m_pFactory= NULL;
}
//////////////////////////////////////////////////////////////////////
// Create functions
//////////////////////////////////////////////////////////////////////
// Create an GLC_Point
GLC_Point* GLC_Factory::createPoint(const GLC_Vector4d &coord) const
{
return new GLC_Point(coord);
}
// Create an GLC_Point
GLC_Point* GLC_Factory::createPoint(double x, double y, double z) const
{
return new GLC_Point(x, y, z);
}
// Create an GLC_Circle
GLC_Circle* GLC_Factory::createCircle(double radius, double angle) const
{
return new GLC_Circle(radius, angle);
}
// Create an GLC_Circle by copying another GLC_Circle
GLC_Circle* GLC_Factory::createCircle(const GLC_Geometry* pCircle) const
{
const GLC_Circle* pTempCircle= dynamic_cast<const GLC_Circle*>(pCircle);
if (pTempCircle != NULL)
{
return new GLC_Circle(*pTempCircle);
}
else
{
return NULL;
}
}
// Create an GLC_Box
GLC_Box* GLC_Factory::createBox(double lx, double ly, double lz) const
{
return new GLC_Box(lx, ly, lz);
}
// Create an GLC_Box
GLC_Box* GLC_Factory::createBox(const GLC_BoundingBox& boundingBox) const
{
const double lx= boundingBox.getUpper().getX() - boundingBox.getLower().getX();
const double ly= boundingBox.getUpper().getY() - boundingBox.getLower().getY();
const double lz= boundingBox.getUpper().getZ() - boundingBox.getLower().getZ();
GLC_Box* pBox= new GLC_Box(lx, ly, lz);
pBox->translate(boundingBox.getLower().getX(), boundingBox.getLower().getY()
, boundingBox.getLower().getZ());
return pBox;
}
// Create an GLC_Cylinder
GLC_Cylinder* GLC_Factory::createCylinder(double radius, double length) const
{
return new GLC_Cylinder(radius, length);
}
// Create an GLC_Cylinder by copying another GLC_Cylinder
GLC_Cylinder* GLC_Factory::createCylinder(const GLC_Geometry* pCylinder) const
{
const GLC_Cylinder* pTempCylinder= dynamic_cast<const GLC_Cylinder*>(pCylinder);
if (pTempCylinder != NULL)
{
return new GLC_Cylinder(*pTempCylinder);
}
else
{
return NULL;
}
}
// Create an GLC_Mesh with a QFile
GLC_Mesh2* GLC_Factory::createMesh(QFile &file) const
{
GLC_ObjToMesh2 objToMesh(m_pQGLWidget);
connect(&objToMesh, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int)));
return objToMesh.CreateMeshFromObj(file);
}
// Create an GLC_Mesh by copying another mesh
GLC_Mesh2* GLC_Factory::createMesh(const GLC_Geometry* pMesh) const
{
const GLC_Mesh2* pTempMesh= dynamic_cast<const GLC_Mesh2*>(pMesh);
if (pTempMesh != NULL)
{
return new GLC_Mesh2(*pTempMesh);
}
else
{
return NULL;
}
}
// Create an GLC_Material
GLC_Material* GLC_Factory::createMaterial() const
{
return new GLC_Material();
}
// Create an GLC_Material
GLC_Material* GLC_Factory::createMaterial(const GLfloat *pAmbiantColor) const
{
return new GLC_Material("Material", pAmbiantColor);
}
// Create an GLC_Material
GLC_Material* GLC_Factory::createMaterial(const QColor &color) const
{
return new GLC_Material(color);
}
GLC_Material* GLC_Factory::createMaterial(GLC_Texture* pTexture) const
{
return new GLC_Material(pTexture, "TextureMaterial");
}
// create an material textured with a image file name
GLC_Material* GLC_Factory::createMaterial(const QString &textureFullFileName) const
{
GLC_Texture* pTexture= createTexture(textureFullFileName);
return createMaterial(pTexture);
}
// Create an GLC_Texture
GLC_Texture* GLC_Factory::createTexture(const QString &textureFullFileName) const
{
return new GLC_Texture(m_pQGLWidget, textureFullFileName);
}
<commit_msg>After replacing *GLfloat by QColor, pass a QColor object to the constructor of GLC_Object which need a color.<commit_after>/****************************************************************************
This file is part of the GLC-lib library.
Copyright (C) 2005-2006 Laurent Ribon (laumaya@users.sourceforge.net)
Version 0.9.6, packaged on June, 2006.
http://glc-lib.sourceforge.net
GLC-lib is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
GLC-lib 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 GLC-lib; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*****************************************************************************/
//! \file glc_factory.cpp implementation of the GLC_Factory class.
#include "glc_factory.h"
#include "glc_objtomesh2.h"
// init static member
GLC_Factory* GLC_Factory::m_pFactory= NULL;
//////////////////////////////////////////////////////////////////////
// static method
//////////////////////////////////////////////////////////////////////
// Return the unique instance of the factory
GLC_Factory* GLC_Factory::instance(QGLWidget *GLWidget)
{
if(m_pFactory == NULL)
{
m_pFactory= new GLC_Factory(GLWidget);
}
return m_pFactory;
}
//////////////////////////////////////////////////////////////////////
// Constructor destructor
//////////////////////////////////////////////////////////////////////
// Protected constructor
GLC_Factory::GLC_Factory(QGLWidget *GLWidget)
: m_pQGLWidget(GLWidget)
{
}
// Destructor
GLC_Factory::~GLC_Factory()
{
m_pFactory= NULL;
}
//////////////////////////////////////////////////////////////////////
// Create functions
//////////////////////////////////////////////////////////////////////
// Create an GLC_Point
GLC_Point* GLC_Factory::createPoint(const GLC_Vector4d &coord) const
{
return new GLC_Point(coord, Qt::white);
}
// Create an GLC_Point
GLC_Point* GLC_Factory::createPoint(double x, double y, double z) const
{
return new GLC_Point(x, y, z, Qt::white);
}
// Create an GLC_Circle
GLC_Circle* GLC_Factory::createCircle(double radius, double angle) const
{
return new GLC_Circle(radius, angle, Qt::white);
}
// Create an GLC_Circle by copying another GLC_Circle
GLC_Circle* GLC_Factory::createCircle(const GLC_Geometry* pCircle) const
{
const GLC_Circle* pTempCircle= dynamic_cast<const GLC_Circle*>(pCircle);
if (pTempCircle != NULL)
{
return new GLC_Circle(*pTempCircle);
}
else
{
return NULL;
}
}
// Create an GLC_Box
GLC_Box* GLC_Factory::createBox(double lx, double ly, double lz) const
{
return new GLC_Box(lx, ly, lz, Qt::white);
}
// Create an GLC_Box
GLC_Box* GLC_Factory::createBox(const GLC_BoundingBox& boundingBox) const
{
const double lx= boundingBox.getUpper().getX() - boundingBox.getLower().getX();
const double ly= boundingBox.getUpper().getY() - boundingBox.getLower().getY();
const double lz= boundingBox.getUpper().getZ() - boundingBox.getLower().getZ();
GLC_Box* pBox= new GLC_Box(lx, ly, lz, Qt::white);
pBox->translate(boundingBox.getLower().getX(), boundingBox.getLower().getY()
, boundingBox.getLower().getZ());
return pBox;
}
// Create an GLC_Cylinder
GLC_Cylinder* GLC_Factory::createCylinder(double radius, double length) const
{
return new GLC_Cylinder(radius, length, Qt::white);
}
// Create an GLC_Cylinder by copying another GLC_Cylinder
GLC_Cylinder* GLC_Factory::createCylinder(const GLC_Geometry* pCylinder) const
{
const GLC_Cylinder* pTempCylinder= dynamic_cast<const GLC_Cylinder*>(pCylinder);
if (pTempCylinder != NULL)
{
return new GLC_Cylinder(*pTempCylinder);
}
else
{
return NULL;
}
}
// Create an GLC_Mesh with a QFile
GLC_Mesh2* GLC_Factory::createMesh(QFile &file) const
{
GLC_ObjToMesh2 objToMesh(m_pQGLWidget);
connect(&objToMesh, SIGNAL(currentQuantum(int)), this, SIGNAL(currentQuantum(int)));
return objToMesh.CreateMeshFromObj(file);
}
// Create an GLC_Mesh by copying another mesh
GLC_Mesh2* GLC_Factory::createMesh(const GLC_Geometry* pMesh) const
{
const GLC_Mesh2* pTempMesh= dynamic_cast<const GLC_Mesh2*>(pMesh);
if (pTempMesh != NULL)
{
return new GLC_Mesh2(*pTempMesh);
}
else
{
return NULL;
}
}
// Create an GLC_Material
GLC_Material* GLC_Factory::createMaterial() const
{
return new GLC_Material();
}
// Create an GLC_Material
GLC_Material* GLC_Factory::createMaterial(const GLfloat *pAmbiantColor) const
{
return new GLC_Material("Material", pAmbiantColor);
}
// Create an GLC_Material
GLC_Material* GLC_Factory::createMaterial(const QColor &color) const
{
return new GLC_Material(color);
}
GLC_Material* GLC_Factory::createMaterial(GLC_Texture* pTexture) const
{
return new GLC_Material(pTexture, "TextureMaterial");
}
// create an material textured with a image file name
GLC_Material* GLC_Factory::createMaterial(const QString &textureFullFileName) const
{
GLC_Texture* pTexture= createTexture(textureFullFileName);
return createMaterial(pTexture);
}
// Create an GLC_Texture
GLC_Texture* GLC_Factory::createTexture(const QString &textureFullFileName) const
{
return new GLC_Texture(m_pQGLWidget, textureFullFileName);
}
<|endoftext|>
|
<commit_before>#include <cstdlib>
#include <cmath>
#include <fstream>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <algorithm>
#include <exception>
#include <sys/time.h>
#include "modules/htmTree.h"
#include "modules/kdTree.h"
#include "misc.h"
#include "feat.h"
#include "structs.h"
#include "collision.h"
#include "global.h"
//reduce redistributes, updates 07/02/15 rnc
int main(int argc, char **argv) {
//// Initializations ---------------------------------------------
srand48(1234); // Make sure we have reproducability
check_args(argc);
Time t, time; // t for global, time for local
init_time(t);
Feat F;
MTL M;
// Read parameters file //
F.readInputFile(argv[1]);
printFile(argv[1]);
// Read Secretfile
// Secret contains the identity of each target: QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF
Gals Secret;
printf("# Read %s galaxies from %s \n",f(F.Ngal).c_str(),F.Secretfile.c_str());
Secret=read_Secretfile(F.Secretfile,F);
std::vector<int> count;
count=count_galaxies(Secret);
printf(" Number of galaxies by type, QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF\n");
for(int i=0;i<8;i++){printf (" type %d number %d \n",i, count[i]);}
//read the three input files
MTL Targ=read_MTLfile(F.Targfile,F,0,0);
MTL SStars=read_MTLfile(F.SStarsfile,F,1,0);
MTL SkyF=read_MTLfile(F.SkyFfile,F,0,1);
//combine the three input files
M=Targ;
printf(" M size %d \n",M.size());
M.insert(M.end(),SStars.begin(),SStars.end());
printf(" M size %d \n",M.size());
M.insert(M.end(),SkyF.begin(),SkyF.end());
printf(" M size %d \n",M.size());
F.Ngal=M.size();
assign_priority_class(M);
//establish priority classes
std::vector <int> count_class(M.priority_list.size(),0);
for(int i;i<M.size();++i){
if(!M[i].SS&&!M[i].SF){
count_class[M[i].priority_class]+=1;
}
}
for(int i;i<M.priority_list.size();++i){
printf(" class %d number %d\n",i,count_class[i]);
}
//diagnostic
int count_ss=0;
int count_sf=0;
for(int g=0;g<M.size();++g){
if(M[g].SS) count_ss++;
if(M[g].SF) count_sf++;
}
printf(" number SS = %d number SF = %d\n",count_ss,count_sf);
PP pp;
pp.read_fiber_positions(F);
F.Nfiber = pp.fp.size()/2;
F.Npetal = max(pp.spectrom)+1;
F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500
pp.get_neighbors(F); pp.compute_fibsofsp(F);
//P is original list of plates
Plates P = read_plate_centers(F);
printf(" future plates %d\n",P.size());
F.Nplate=P.size();
printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str());
// Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions
F.cb = create_cb(); // cb=central body
F.fh = create_fh(); // fh=fiber holder
//// Collect available galaxies <-> tilefibers --------------------
// HTM Tree of galaxies
const double MinTreeSize = 0.01;
init_time_at(time,"# Start building HTM tree",t);
htmTree<struct target> T(M,MinTreeSize);
print_time(time,"# ... took :");//T.stats();
// For plates/fibers, collect available galaxies; done in parallel
collect_galaxies_for_all(M,T,P,pp,F);
// For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..]
collect_available_tilefibers(M,P,F);
//results_on_inputs("doc/figs/",G,P,F,true);
//// Assignment |||||||||||||||||||||||||||||||||||||||||||||||||||
printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber);
Assignment A(M,F);
print_time(t,"# Start assignment at : ");
// Make a plan ----------------------------------------------------
// Plans whole survey without sky fibers, standard stars
// assumes maximum number of observations needed for QSOs, LRGs
simple_assign(M,P,pp,F,A);
//check to see if any SS or SF are assigned
int SS_count=0;
int SF_count=0;
std::vector <int> class_count(3,0);
for( int j=0;j<F.Nplate;++j){
for (int k=0;k<F.Nfiber;++k){
if(A.TF[j][k]!=-1){
if(M[A.TF[j][k]].SS)SS_count++;
if(M[A.TF[j][k]].SF)SF_count++;
class_count[M[A.TF[j][k]].priority_class]++;
}
}
}
printf("after simple assign, SS assigned %d SF assigned %d\n",SS_count,SF_count);
printf(" class 0 %d class 1 %d class 2 %d\n", class_count[0],class_count[1],class_count[2]);
//check to see if there are tiles with no galaxies
//need to keep mapping of old tile list to new tile list
for (int j=0;j<F.Nplate ;++j){
bool not_done=true;
for(int k=0;k<F.Nfiber && not_done;++k){
if(A.TF[j][k]!=-1){
A.suborder.push_back(j);
not_done=false;
}
}
}
F.NUsedplate=A.suborder.size();
printf(" Plates after screening %d \n",F.NUsedplate);
//diagnostic
/*
for (int j=0;j<F.NUsedplate;++j){
int js=A.suborder[j];
printf(" js = %d available SF for fibers\n",js);
for (int k=0;k<10;++k){
printf(" %d ",P[js].SF_av_gal_fiber[k*500].size());
}
printf("\n petals");
for (int q=0;q<F.Npetal;++q){
printf(" %d",P[js].SF_av_gal[q].size());
}
printf("\n");
}
*/
//if(F.diagnose)diagnostic(M,G,F,A);
print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs
// Smooth out distribution of free fibers, and increase the number of assignments
for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A);// more iterations will improve performance slightly
for (int i=0; i<1; i++) {
improve(M,P,pp,F,A);
redistribute_tf(M,P,pp,F,A);
}
print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false);
//try assigning SF and SS before real time assignment
for (int j=0;j<F.NUsedplate;++j){
int js=A.suborder[j];
//printf(" before assign_sf_ss js= %d\n",js);
A.next_plate=js;
assign_sf_ss(js,M,P,pp,F,A); // Assign SS and SF for each tile
//printf("before assign_unused js= %d \n",js);
assign_unused(js,M,P,pp,F,A);
}
if(F.diagnose)diagnostic(M,Secret,F,A);
init_time_at(time,"# Begin real time assignment",t);
//Execute plan, updating targets at intervals
std::vector <int> update_intervals=F.pass_intervals;
update_intervals.push_back(F.NUsedplate);
for(int i=0;i<update_intervals.size()-1;++i){//go plate by used plate
printf(" before pass = %d at %d tiles\n",i,update_intervals[i]);
//display_results("doc/figs/",G,P,pp,F,A,true);
//plan whole survey from this point out
A.next_plate=F.pass_intervals[i];
for (int jj=F.pass_intervals[i]; jj<F.NUsedplate; jj++) {
int j = A.suborder[jj];
//printf(" next plate is %d \n",j);
assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF
assign_unused(j,M,P,pp,F,A);
//A.next_plate++;
}
//update target information for interval i
//A.next_plate=F.pass_intervals[i];
for (int jj=update_intervals[i]; jj<update_intervals[i+1]; jj++) {
//int j = A.suborder[A.next_plate];
//int js=A.suborder[jj];
// Update corrects all future occurrences of wrong QSOs etc and tries to observe something else
if (0<=jj-F.Analysis) update_plan_from_one_obs(jj,Secret,M,P,pp,F,A,F.Nplate-1); else printf("\n");
//A.next_plate++;
}
//if(A.next_plate<F.Nplate){
redistribute_tf(M,P,pp,F,A);
redistribute_tf(M,P,pp,F,A);
improve(M,P,pp,F,A);
redistribute_tf(M,P,pp,F,A);
//}
if(F.diagnose)diagnostic(M,Secret,F,A);
}
// check on SS and SF
for(int js=0;js<F.NUsedplate;++js){
printf("\n js = %d\n",js);
for (int p=0;p<F.Npetal;++p){
int count_SS=0;
int count_SF=0;
for (int k=0;k<F.Nfbp;++k){
int kk=pp.fibers_of_sp[p][k];
int g=A.TF[js][kk];
if(g!=-1 && M[g].SS)count_SS++;
if(g!=-1 && M[g].SF)count_SF++;
}
printf(" %d %d ",count_SS,count_SF);
}
printf("\n");
}
// Results -------------------------------------------------------
if (F.PrintAscii) for (int j=0; j<F.NUsedplate; j++){
write_FAtile_ascii(A.suborder[j],F.outDir,M,P,pp,F,A);
}
if (F.PrintFits) for (int j=0; j<F.NUsedplate; j++){
fa_write(A.suborder[j],F.outDir,M,P,pp,F,A); // Write output
}
display_results("doc/figs/",Secret,M,P,pp,F,A,true);
if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane
print_time(t,"# Finished !... in");
return(0);
}
<commit_msg>fix diagnostic for SS SF<commit_after>#include <cstdlib>
#include <cmath>
#include <fstream>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <algorithm>
#include <exception>
#include <sys/time.h>
#include "modules/htmTree.h"
#include "modules/kdTree.h"
#include "misc.h"
#include "feat.h"
#include "structs.h"
#include "collision.h"
#include "global.h"
//reduce redistributes, updates 07/02/15 rnc
int main(int argc, char **argv) {
//// Initializations ---------------------------------------------
srand48(1234); // Make sure we have reproducability
check_args(argc);
Time t, time; // t for global, time for local
init_time(t);
Feat F;
MTL M;
// Read parameters file //
F.readInputFile(argv[1]);
printFile(argv[1]);
// Read Secretfile
// Secret contains the identity of each target: QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF
Gals Secret;
printf("# Read %s galaxies from %s \n",f(F.Ngal).c_str(),F.Secretfile.c_str());
Secret=read_Secretfile(F.Secretfile,F);
std::vector<int> count;
count=count_galaxies(Secret);
printf(" Number of galaxies by type, QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF\n");
for(int i=0;i<8;i++){printf (" type %d number %d \n",i, count[i]);}
//read the three input files
MTL Targ=read_MTLfile(F.Targfile,F,0,0);
MTL SStars=read_MTLfile(F.SStarsfile,F,1,0);
MTL SkyF=read_MTLfile(F.SkyFfile,F,0,1);
//combine the three input files
M=Targ;
printf(" M size %d \n",M.size());
M.insert(M.end(),SStars.begin(),SStars.end());
printf(" M size %d \n",M.size());
M.insert(M.end(),SkyF.begin(),SkyF.end());
printf(" M size %d \n",M.size());
F.Ngal=M.size();
assign_priority_class(M);
//establish priority classes
std::vector <int> count_class(M.priority_list.size(),0);
for(int i;i<M.size();++i){
if(!M[i].SS&&!M[i].SF){
count_class[M[i].priority_class]+=1;
}
}
for(int i;i<M.priority_list.size();++i){
printf(" class %d number %d\n",i,count_class[i]);
}
//diagnostic
int count_ss=0;
int count_sf=0;
for(int g=0;g<M.size();++g){
if(M[g].SS) count_ss++;
if(M[g].SF) count_sf++;
}
printf(" number SS = %d number SF = %d\n",count_ss,count_sf);
PP pp;
pp.read_fiber_positions(F);
F.Nfiber = pp.fp.size()/2;
F.Npetal = max(pp.spectrom)+1;
F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500
pp.get_neighbors(F); pp.compute_fibsofsp(F);
//P is original list of plates
Plates P = read_plate_centers(F);
printf(" future plates %d\n",P.size());
F.Nplate=P.size();
printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str());
// Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions
F.cb = create_cb(); // cb=central body
F.fh = create_fh(); // fh=fiber holder
//// Collect available galaxies <-> tilefibers --------------------
// HTM Tree of galaxies
const double MinTreeSize = 0.01;
init_time_at(time,"# Start building HTM tree",t);
htmTree<struct target> T(M,MinTreeSize);
print_time(time,"# ... took :");//T.stats();
// For plates/fibers, collect available galaxies; done in parallel
collect_galaxies_for_all(M,T,P,pp,F);
// For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..]
collect_available_tilefibers(M,P,F);
//results_on_inputs("doc/figs/",G,P,F,true);
//// Assignment |||||||||||||||||||||||||||||||||||||||||||||||||||
printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber);
Assignment A(M,F);
print_time(t,"# Start assignment at : ");
// Make a plan ----------------------------------------------------
// Plans whole survey without sky fibers, standard stars
// assumes maximum number of observations needed for QSOs, LRGs
simple_assign(M,P,pp,F,A);
//check to see if any SS or SF are assigned
int SS_count=0;
int SF_count=0;
std::vector <int> class_count(3,0);
for( int j=0;j<F.Nplate;++j){
for (int k=0;k<F.Nfiber;++k){
if(A.TF[j][k]!=-1){
if(M[A.TF[j][k]].SS)SS_count++;
if(M[A.TF[j][k]].SF)SF_count++;
class_count[M[A.TF[j][k]].priority_class]++;
}
}
}
printf("after simple assign, SS assigned %d SF assigned %d\n",SS_count,SF_count);
printf(" class 0 %d class 1 %d class 2 %d\n", class_count[0],class_count[1],class_count[2]);
//check to see if there are tiles with no galaxies
//need to keep mapping of old tile list to new tile list
for (int j=0;j<F.Nplate ;++j){
bool not_done=true;
for(int k=0;k<F.Nfiber && not_done;++k){
if(A.TF[j][k]!=-1){
A.suborder.push_back(j);
not_done=false;
}
}
}
F.NUsedplate=A.suborder.size();
printf(" Plates after screening %d \n",F.NUsedplate);
//diagnostic
/*
for (int j=0;j<F.NUsedplate;++j){
int js=A.suborder[j];
printf(" js = %d available SF for fibers\n",js);
for (int k=0;k<10;++k){
printf(" %d ",P[js].SF_av_gal_fiber[k*500].size());
}
printf("\n petals");
for (int q=0;q<F.Npetal;++q){
printf(" %d",P[js].SF_av_gal[q].size());
}
printf("\n");
}
*/
//if(F.diagnose)diagnostic(M,G,F,A);
print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs
// Smooth out distribution of free fibers, and increase the number of assignments
for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A);// more iterations will improve performance slightly
for (int i=0; i<1; i++) {
improve(M,P,pp,F,A);
redistribute_tf(M,P,pp,F,A);
}
print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false);
//try assigning SF and SS before real time assignment
for (int j=0;j<F.NUsedplate;++j){
int js=A.suborder[j];
//printf(" before assign_sf_ss js= %d\n",js);
A.next_plate=js;
assign_sf_ss(js,M,P,pp,F,A); // Assign SS and SF for each tile
//printf("before assign_unused js= %d \n",js);
assign_unused(js,M,P,pp,F,A);
}
if(F.diagnose)diagnostic(M,Secret,F,A);
init_time_at(time,"# Begin real time assignment",t);
//Execute plan, updating targets at intervals
std::vector <int> update_intervals=F.pass_intervals;
update_intervals.push_back(F.NUsedplate);
for(int i=0;i<update_intervals.size()-1;++i){//go plate by used plate
printf(" before pass = %d at %d tiles\n",i,update_intervals[i]);
//display_results("doc/figs/",G,P,pp,F,A,true);
//plan whole survey from this point out
A.next_plate=F.pass_intervals[i];
for (int jj=F.pass_intervals[i]; jj<F.NUsedplate; jj++) {
int j = A.suborder[jj];
//printf(" next plate is %d \n",j);
assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF
assign_unused(j,M,P,pp,F,A);
//A.next_plate++;
}
//update target information for interval i
//A.next_plate=F.pass_intervals[i];
for (int jj=update_intervals[i]; jj<update_intervals[i+1]; jj++) {
//int j = A.suborder[A.next_plate];
//int js=A.suborder[jj];
// Update corrects all future occurrences of wrong QSOs etc and tries to observe something else
if (0<=jj-F.Analysis) update_plan_from_one_obs(jj,Secret,M,P,pp,F,A,F.Nplate-1); else printf("\n");
//A.next_plate++;
}
//if(A.next_plate<F.Nplate){
redistribute_tf(M,P,pp,F,A);
redistribute_tf(M,P,pp,F,A);
improve(M,P,pp,F,A);
redistribute_tf(M,P,pp,F,A);
//}
if(F.diagnose)diagnostic(M,Secret,F,A);
}
// check on SS and SF
for(int j=0;j<F.NUsedplate;++j){
int js=A.suborder[j];
printf("\n js = %d\n",js);
for (int p=0;p<F.Npetal;++p){
int count_SS=0;
int count_SF=0;
for (int k=0;k<F.Nfbp;++k){
int kk=pp.fibers_of_sp[p][k];
int g=A.TF[js][kk];
if(g!=-1 && M[g].SS)count_SS++;
if(g!=-1 && M[g].SF)count_SF++;
}
printf(" %d %d ",count_SS,count_SF);
}
printf("\n");
}
// Results -------------------------------------------------------
if (F.PrintAscii) for (int j=0; j<F.NUsedplate; j++){
write_FAtile_ascii(A.suborder[j],F.outDir,M,P,pp,F,A);
}
if (F.PrintFits) for (int j=0; j<F.NUsedplate; j++){
fa_write(A.suborder[j],F.outDir,M,P,pp,F,A); // Write output
}
display_results("doc/figs/",Secret,M,P,pp,F,A,true);
if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane
print_time(t,"# Finished !... in");
return(0);
}
<|endoftext|>
|
<commit_before>/*
* Open Source Movement Analysis Library
* Copyright (C) 2016, Moveck Solution 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(s) of the copyright holders nor the names
* of its contributors may be used to endorse or promote products
* derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "openma/io/handlerplugin.h"
#include "openma/io/device.h"
#include "openma/io/enums.h"
#include "openma/base/pluginmanager.h"
// #ifdef OPENMA_IO_STATIC_DEFINE
#include "../plugins/staticiopluginloader.h"
// #endif
namespace ma
{
namespace io
{
/**
* Convenient method to load handler plugins.
* Internally this method uses a static object. It will be populated the first time this function is used.
*/
const std::vector<HandlerPlugin*>& load_handler_plugins()
{
static PluginManager<HandlerPlugin> manager;
if (manager.plugins().empty())
{
// #ifndef OPENMA_IO_STATIC_DEFINE
// Dynamic loading
// {"trialformats","bodyformats"})
// #error Not yet implemented
// #else
// Static include
load_handler_plugins(&manager);
// #endif
}
return manager.plugins();
};
/**
* @class HandlerPlugin openma/io/handlerplugin.h
* @brief Interface to load handler(s) dynamically.
*
* A format is a string composed of two parts. Both separated by a dot. The left side of the dot is the name of company that developed the format (e.g.'codamotion'), while the right part is the (file) extension used for this format (e.g. mdf).
*
* @ingroup openma_io
*/
/**
* Default constructor
*/
HandlerPlugin::HandlerPlugin()
{};
/**
* Destructor (default)
*/
HandlerPlugin::~HandlerPlugin() = default;
/**
* @fn virtual std::vector<std::string> supportedFormats() const _OPENMA_NOEXCEPT = 0;
* Returns a list of supported format by this plugin.
*/
/**
* @fn virtual Capability HandlerPlugin::capabilities(const std::string& format) const _OPENMA_NOEXCEPT
* Returns the capabilities availble for a handler managed by this plugin. In case multiple handlers are managed by this plugin, you can use @a format to returns the corresponding capabilities. For example:
* @code{.unparsed}
* Capability MyHandler::capabilities(const std::string& format) const _OPENMA_NOEXCEPT
* {
* if (format.compare("openma.foo") == 0)
* eturn Capability::CanReadAndWrite;
* else if (format.compare("openma.bar") == 0)
* eturn Capability::CanRead;
* };
* @endcode
*/
/**
* @fn virtual Signature HandlerPlugin::detectSignature(const Device* const device, std::string* format) const _OPENMA_NOEXCEPT = 0;
* Detect the signature used fo one of the supported format. If the string @a format is not null, the detected format will be set. Because, the @a device is a const pointer, it is needed to use the method Device::peek() to extract content without modifying the device.
* In case no signature exists for the supported formats, this method shall return Signature::NotAvailable.
*/
/**
* Try to detect the extension used by one of the supported format in the string @a str.
* If the string @a format is not null, the detected format will be set inside.
* @note This detection method is not robust. If possible use the signature detection.
*/
bool HandlerPlugin::detectExtension(const std::string& str, std::string* format) const _OPENMA_NOEXCEPT
{
auto formats = this->supportedFormats();
auto idx = str.find_last_of('.');
if (idx != std::string::npos)
{
auto ext = str.substr(idx+1);
auto len = ext.length();
for (const auto& f: formats)
{
if (f.substr(f.length()-len,len).compare(ext) == 0)
{
if (format != nullptr)
*format = f;
return true;
}
}
}
return false;
};
/**
* @fn virtual Handler* HandlerPlugin::create(Device* device, const std::string& format) = 0;
* Create a new handler. The @a device is passed to the created handler. The usage of @a format can be twofold. First, it can be used to verify if the given format is supported by this plugin. Second, it will help to choose the good handler if multiple formats are managed by the plugin.
*/
};
};<commit_msg>Force the extension and format to be in lower case before the comparison.<commit_after>/*
* Open Source Movement Analysis Library
* Copyright (C) 2016, Moveck Solution 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(s) of the copyright holders nor the names
* of its contributors may be used to endorse or promote products
* derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "openma/io/handlerplugin.h"
#include "openma/io/device.h"
#include "openma/io/enums.h"
#include "openma/base/pluginmanager.h"
// #ifdef OPENMA_IO_STATIC_DEFINE
#include "../plugins/staticiopluginloader.h"
// #endif
#include <algorithm> // std::transform
namespace ma
{
namespace io
{
/**
* Convenient method to load handler plugins.
* Internally this method uses a static object. It will be populated the first time this function is used.
*/
const std::vector<HandlerPlugin*>& load_handler_plugins()
{
static PluginManager<HandlerPlugin> manager;
if (manager.plugins().empty())
{
// #ifndef OPENMA_IO_STATIC_DEFINE
// Dynamic loading
// {"trialformats","bodyformats"})
// #error Not yet implemented
// #else
// Static include
load_handler_plugins(&manager);
// #endif
}
return manager.plugins();
};
/**
* @class HandlerPlugin openma/io/handlerplugin.h
* @brief Interface to load handler(s) dynamically.
*
* A format is a string composed of two parts. Both separated by a dot. The left side of the dot is the name of company that developed the format (e.g.'codamotion'), while the right part is the (file) extension used for this format (e.g. mdf).
*
* @ingroup openma_io
*/
/**
* Default constructor
*/
HandlerPlugin::HandlerPlugin()
{};
/**
* Destructor (default)
*/
HandlerPlugin::~HandlerPlugin() = default;
/**
* @fn virtual std::vector<std::string> supportedFormats() const _OPENMA_NOEXCEPT = 0;
* Returns a list of supported format by this plugin.
*/
/**
* @fn virtual Capability HandlerPlugin::capabilities(const std::string& format) const _OPENMA_NOEXCEPT
* Returns the capabilities availble for a handler managed by this plugin. In case multiple handlers are managed by this plugin, you can use @a format to returns the corresponding capabilities. For example:
* @code{.unparsed}
* Capability MyHandler::capabilities(const std::string& format) const _OPENMA_NOEXCEPT
* {
* if (format.compare("openma.foo") == 0)
* return Capability::CanReadAndWrite;
* else if (format.compare("openma.bar") == 0)
* return Capability::CanRead;
* };
* @endcode
*/
/**
* @fn virtual Signature HandlerPlugin::detectSignature(const Device* const device, std::string* format) const _OPENMA_NOEXCEPT = 0;
* Detect the signature used fo one of the supported format. If the string @a format is not null, the detected format will be set. Because, the @a device is a const pointer, it is needed to use the method Device::peek() to extract content without modifying the device.
* In case no signature exists for the supported formats, this method shall return Signature::NotAvailable.
*/
/**
* Try to detect the extension used by one of the supported format in the string @a str.
* If the string @a format is not null, the detected format will be set inside.
* @note This detection method is not robust. If possible use the signature detection.
*/
bool HandlerPlugin::detectExtension(const std::string& str, std::string* format) const _OPENMA_NOEXCEPT
{
auto formats = this->supportedFormats();
auto idx = str.find_last_of('.');
if ((idx != std::string::npos) && (idx != (str.size()-1)))
{
auto ext = str.substr(idx+1);
std::transform(ext.begin(), ext.end(), ext.begin(), tolower);
auto len = ext.length();
for (const auto& f: formats)
{
auto subf = f.substr(f.length()-len,len);
std::transform(subf.begin(), subf.end(), subf.begin(), tolower);
if (subf.compare(ext) == 0)
{
if (format != nullptr)
*format = f;
return true;
}
}
}
return false;
};
/**
* @fn virtual Handler* HandlerPlugin::create(Device* device, const std::string& format) = 0;
* Create a new handler. The @a device is passed to the created handler. The usage of @a format can be twofold. First, it can be used to verify if the given format is supported by this plugin. Second, it will help to choose the good handler if multiple formats are managed by the plugin.
*/
};
};<|endoftext|>
|
<commit_before>#include <clpeak.h>
#define MSTRINGIFY(...) #__VA_ARGS__
static const char *stringifiedKernels =
#include "global_bandwidth_kernels.cl"
#include "compute_sp_kernels.cl"
#include "compute_hp_kernels.cl"
#include "compute_dp_kernels.cl"
#include "compute_integer_kernels.cl"
;
static const char *stringifiedKernelsNoInt =
#include "global_bandwidth_kernels.cl"
#include "compute_sp_kernels.cl"
#include "compute_hp_kernels.cl"
#include "compute_dp_kernels.cl"
;
#ifdef USE_STUB_OPENCL
// Prototype
extern "C" {
void stubOpenclReset();
}
#endif
clPeak::clPeak(): forcePlatform(false), forceDevice(false), useEventTimer(false),
isGlobalBW(true), isComputeSP(true), isComputeDP(true), isComputeInt(true),
isTransferBW(true), isKernelLatency(true),
specifiedPlatform(-1), specifiedDevice(-1)
{
}
clPeak::~clPeak()
{
if(log) delete log;
}
int clPeak::runAll()
{
try
{
#ifdef USE_STUB_OPENCL
stubOpenclReset();
#endif
vector<cl::Platform> platforms;
cl::Platform::get(&platforms);
log->xmlOpenTag("clpeak");
log->xmlAppendAttribs("os", OS_NAME);
for(int p=0; p < (int)platforms.size(); p++)
{
if(forcePlatform && (p != specifiedPlatform))
continue;
std::string platformName = platforms[p].getInfo<CL_PLATFORM_NAME>();
trimString(platformName);
log->print(NEWLINE "Platform: " + platformName + NEWLINE);
log->xmlOpenTag("platform");
log->xmlAppendAttribs("name", platformName);
bool isIntel = (platformName.find("Intel") != std::string::npos)? true: false;
bool isApple = (platformName.find("Apple") != std::string::npos)? true: false;
bool isSnapdragon = (platformName.find("Snapdragon") != std::string::npos) ? true : false;
cl_context_properties cps[3] = {
CL_CONTEXT_PLATFORM,
(cl_context_properties)(platforms[p])(),
0
};
// Use only gpus in snapdragon, it would crash otherwise!
cl_device_type device_type = (isSnapdragon)? CL_DEVICE_TYPE_GPU: CL_DEVICE_TYPE_ALL;
cl::Context ctx(device_type, cps);
vector<cl::Device> devices = ctx.getInfo<CL_CONTEXT_DEVICES>();
cl::Program prog;
// FIXME Disabling integer compute tests on intel platform
// Kernel build is taking much much longer time
// FIXME Disabling integer compute tests on apple platform
// Causes Segmentation fault: 11
if(isIntel || isApple)
{
cl::Program::Sources source(1, make_pair(stringifiedKernelsNoInt, (strlen(stringifiedKernelsNoInt)+1)));
isComputeInt = false;
prog = cl::Program(ctx, source);
}
else
{
cl::Program::Sources source(1, make_pair(stringifiedKernels, (strlen(stringifiedKernels)+1)));
prog = cl::Program(ctx, source);
}
for(int d=0; d < (int)devices.size(); d++)
{
if(forceDevice && (d != specifiedDevice))
continue;
device_info_t devInfo = getDeviceInfo(devices[d]);
log->print(TAB "Device: " + devInfo.deviceName + NEWLINE);
log->print(TAB TAB "Driver version : ");
log->print(devInfo.driverVersion); log->print(" (" OS_NAME ")" NEWLINE);
log->print(TAB TAB "Compute units : ");
log->print(devInfo.numCUs); log->print(NEWLINE);
log->print(TAB TAB "Clock frequency : ");
log->print(devInfo.maxClockFreq); log->print(" MHz" NEWLINE);
log->xmlOpenTag("device");
log->xmlAppendAttribs("name", devInfo.deviceName);
log->xmlAppendAttribs("driver_version", devInfo.driverVersion);
log->xmlAppendAttribs("compute_units", devInfo.numCUs);
log->xmlAppendAttribs("clock_frequency", devInfo.maxClockFreq);
log->xmlAppendAttribs("clock_frequency_unit", "MHz");
try
{
vector<cl::Device> dev = {devices[d]};
prog.build(dev, BUILD_OPTIONS);
}
catch (cl::Error &error)
{
log->print(TAB TAB "Build Log: " + prog.getBuildInfo<CL_PROGRAM_BUILD_LOG>(devices[d])
+ NEWLINE NEWLINE);
continue;
}
cl::CommandQueue queue = cl::CommandQueue(ctx, devices[d], CL_QUEUE_PROFILING_ENABLE);
runGlobalBandwidthTest(queue, prog, devInfo);
runComputeSP(queue, prog, devInfo);
runComputeHP(queue, prog, devInfo);
runComputeDP(queue, prog, devInfo);
runComputeInteger(queue, prog, devInfo);
runTransferBandwidthTest(queue, prog, devInfo);
runKernelLatency(queue, prog, devInfo);
log->print(NEWLINE);
log->xmlCloseTag(); // device
}
log->xmlCloseTag(); // platform
}
log->xmlCloseTag(); // clpeak
}
catch(cl::Error &error)
{
stringstream ss;
ss << error.what() << " (" << error.err() << ")" NEWLINE;
log->print(ss.str());
return -1;
}
return 0;
}
float clPeak::run_kernel(cl::CommandQueue &queue, cl::Kernel &kernel, cl::NDRange &globalSize, cl::NDRange &localSize, int iters)
{
float timed = 0;
// Dummy calls
queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize);
queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize);
queue.finish();
if(useEventTimer)
{
for(int i=0; i<iters; i++)
{
cl::Event timeEvent;
queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize, NULL, &timeEvent);
queue.finish();
timed += timeInUS(timeEvent);
}
} else // std timer
{
Timer timer;
timer.start();
for(int i=0; i<iters; i++)
{
queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize);
}
queue.finish();
timed = timer.stopAndTime();
}
return (timed / iters);
}
<commit_msg>Disable integer kernel in intel only on windows<commit_after>#include <clpeak.h>
#define MSTRINGIFY(...) #__VA_ARGS__
static const char *stringifiedKernels =
#include "global_bandwidth_kernels.cl"
#include "compute_sp_kernels.cl"
#include "compute_hp_kernels.cl"
#include "compute_dp_kernels.cl"
#include "compute_integer_kernels.cl"
;
static const char *stringifiedKernelsNoInt =
#include "global_bandwidth_kernels.cl"
#include "compute_sp_kernels.cl"
#include "compute_hp_kernels.cl"
#include "compute_dp_kernels.cl"
;
#ifdef USE_STUB_OPENCL
// Prototype
extern "C" {
void stubOpenclReset();
}
#endif
clPeak::clPeak(): forcePlatform(false), forceDevice(false), useEventTimer(false),
isGlobalBW(true), isComputeSP(true), isComputeDP(true), isComputeInt(true),
isTransferBW(true), isKernelLatency(true),
specifiedPlatform(-1), specifiedDevice(-1)
{
}
clPeak::~clPeak()
{
if(log) delete log;
}
int clPeak::runAll()
{
try
{
#ifdef USE_STUB_OPENCL
stubOpenclReset();
#endif
vector<cl::Platform> platforms;
cl::Platform::get(&platforms);
log->xmlOpenTag("clpeak");
log->xmlAppendAttribs("os", OS_NAME);
for(int p=0; p < (int)platforms.size(); p++)
{
if(forcePlatform && (p != specifiedPlatform))
continue;
std::string platformName = platforms[p].getInfo<CL_PLATFORM_NAME>();
trimString(platformName);
log->print(NEWLINE "Platform: " + platformName + NEWLINE);
log->xmlOpenTag("platform");
log->xmlAppendAttribs("name", platformName);
// Disable intel integer kernel only on windows
bool isIntel = false;
#if defined(_WIN32)
isIntel = (platformName.find("Intel") != std::string::npos)? true: false;
#endif
bool isApple = (platformName.find("Apple") != std::string::npos)? true: false;
bool isSnapdragon = (platformName.find("Snapdragon") != std::string::npos) ? true : false;
cl_context_properties cps[3] = {
CL_CONTEXT_PLATFORM,
(cl_context_properties)(platforms[p])(),
0
};
// Use only gpus in snapdragon, it would crash otherwise!
cl_device_type device_type = (isSnapdragon)? CL_DEVICE_TYPE_GPU: CL_DEVICE_TYPE_ALL;
cl::Context ctx(device_type, cps);
vector<cl::Device> devices = ctx.getInfo<CL_CONTEXT_DEVICES>();
cl::Program prog;
// FIXME Disabling integer compute tests on intel platform
// Kernel build is taking much much longer time
// FIXME Disabling integer compute tests on apple platform
// Causes Segmentation fault: 11
if(isIntel || isApple)
{
cl::Program::Sources source(1, make_pair(stringifiedKernelsNoInt, (strlen(stringifiedKernelsNoInt)+1)));
isComputeInt = false;
prog = cl::Program(ctx, source);
}
else
{
cl::Program::Sources source(1, make_pair(stringifiedKernels, (strlen(stringifiedKernels)+1)));
prog = cl::Program(ctx, source);
}
for(int d=0; d < (int)devices.size(); d++)
{
if(forceDevice && (d != specifiedDevice))
continue;
device_info_t devInfo = getDeviceInfo(devices[d]);
log->print(TAB "Device: " + devInfo.deviceName + NEWLINE);
log->print(TAB TAB "Driver version : ");
log->print(devInfo.driverVersion); log->print(" (" OS_NAME ")" NEWLINE);
log->print(TAB TAB "Compute units : ");
log->print(devInfo.numCUs); log->print(NEWLINE);
log->print(TAB TAB "Clock frequency : ");
log->print(devInfo.maxClockFreq); log->print(" MHz" NEWLINE);
log->xmlOpenTag("device");
log->xmlAppendAttribs("name", devInfo.deviceName);
log->xmlAppendAttribs("driver_version", devInfo.driverVersion);
log->xmlAppendAttribs("compute_units", devInfo.numCUs);
log->xmlAppendAttribs("clock_frequency", devInfo.maxClockFreq);
log->xmlAppendAttribs("clock_frequency_unit", "MHz");
try
{
vector<cl::Device> dev = {devices[d]};
prog.build(dev, BUILD_OPTIONS);
}
catch (cl::Error &error)
{
log->print(TAB TAB "Build Log: " + prog.getBuildInfo<CL_PROGRAM_BUILD_LOG>(devices[d])
+ NEWLINE NEWLINE);
continue;
}
cl::CommandQueue queue = cl::CommandQueue(ctx, devices[d], CL_QUEUE_PROFILING_ENABLE);
runGlobalBandwidthTest(queue, prog, devInfo);
runComputeSP(queue, prog, devInfo);
runComputeHP(queue, prog, devInfo);
runComputeDP(queue, prog, devInfo);
runComputeInteger(queue, prog, devInfo);
runTransferBandwidthTest(queue, prog, devInfo);
runKernelLatency(queue, prog, devInfo);
log->print(NEWLINE);
log->xmlCloseTag(); // device
}
log->xmlCloseTag(); // platform
}
log->xmlCloseTag(); // clpeak
}
catch(cl::Error &error)
{
stringstream ss;
ss << error.what() << " (" << error.err() << ")" NEWLINE;
log->print(ss.str());
return -1;
}
return 0;
}
float clPeak::run_kernel(cl::CommandQueue &queue, cl::Kernel &kernel, cl::NDRange &globalSize, cl::NDRange &localSize, int iters)
{
float timed = 0;
// Dummy calls
queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize);
queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize);
queue.finish();
if(useEventTimer)
{
for(int i=0; i<iters; i++)
{
cl::Event timeEvent;
queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize, NULL, &timeEvent);
queue.finish();
timed += timeInUS(timeEvent);
}
} else // std timer
{
Timer timer;
timer.start();
for(int i=0; i<iters; i++)
{
queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize);
}
queue.finish();
timed = timer.stopAndTime();
}
return (timed / iters);
}
<|endoftext|>
|
<commit_before>// Copyright 2012 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/v8.h"
#include "src/bootstrapper.h"
#include "src/codegen.h"
#include "src/compiler.h"
#include "src/cpu-profiler.h"
#include "src/debug.h"
#include "src/prettyprinter.h"
#include "src/rewriter.h"
#include "src/runtime.h"
namespace v8 {
namespace internal {
#if defined(_WIN64)
typedef double (*ModuloFunction)(double, double);
static ModuloFunction modulo_function = NULL;
// Defined in codegen-x64.cc.
ModuloFunction CreateModuloFunction();
void init_modulo_function() {
modulo_function = CreateModuloFunction();
}
double modulo(double x, double y) {
// Note: here we rely on dependent reads being ordered. This is true
// on all architectures we currently support.
return (*modulo_function)(x, y);
}
#elif defined(_WIN32)
double modulo(double x, double y) {
// Workaround MS fmod bugs. ECMA-262 says:
// dividend is finite and divisor is an infinity => result equals dividend
// dividend is a zero and divisor is nonzero finite => result equals dividend
if (!(std::isfinite(x) && (!std::isfinite(y) && !std::isnan(y))) &&
!(x == 0 && (y != 0 && std::isfinite(y)))) {
x = fmod(x, y);
}
return x;
}
#else // POSIX
double modulo(double x, double y) {
return std::fmod(x, y);
}
#endif // defined(_WIN64)
#define UNARY_MATH_FUNCTION(name, generator) \
static UnaryMathFunction fast_##name##_function = NULL; \
void init_fast_##name##_function() { \
fast_##name##_function = generator; \
} \
double fast_##name(double x) { \
return (*fast_##name##_function)(x); \
}
UNARY_MATH_FUNCTION(exp, CreateExpFunction())
UNARY_MATH_FUNCTION(sqrt, CreateSqrtFunction())
#undef UNARY_MATH_FUNCTION
void lazily_initialize_fast_exp() {
if (fast_exp_function == NULL) {
init_fast_exp_function();
}
}
#define __ ACCESS_MASM(masm_)
#ifdef DEBUG
Comment::Comment(MacroAssembler* masm, const char* msg)
: masm_(masm), msg_(msg) {
__ RecordComment(msg);
}
Comment::~Comment() {
if (msg_[0] == '[') __ RecordComment("]");
}
#endif // DEBUG
#undef __
void CodeGenerator::MakeCodePrologue(CompilationInfo* info, const char* kind) {
bool print_source = false;
bool print_ast = false;
const char* ftype;
if (info->isolate()->bootstrapper()->IsActive()) {
print_source = FLAG_print_builtin_source;
print_ast = FLAG_print_builtin_ast;
ftype = "builtin";
} else {
print_source = FLAG_print_source;
print_ast = FLAG_print_ast;
ftype = "user-defined";
}
if (FLAG_trace_codegen || print_source || print_ast) {
PrintF("[generating %s code for %s function: ", kind, ftype);
if (info->IsStub()) {
const char* name =
CodeStub::MajorName(info->code_stub()->MajorKey(), true);
PrintF("%s", name == NULL ? "<unknown>" : name);
} else {
PrintF("%s", info->function()->debug_name()->ToCString().get());
}
PrintF("]\n");
}
#ifdef DEBUG
if (!info->IsStub() && print_source) {
PrintF("--- Source from AST ---\n%s\n",
PrettyPrinter(info->zone()).PrintProgram(info->function()));
}
if (!info->IsStub() && print_ast) {
PrintF("--- AST ---\n%s\n",
AstPrinter(info->zone()).PrintProgram(info->function()));
}
#endif // DEBUG
}
Handle<Code> CodeGenerator::MakeCodeEpilogue(MacroAssembler* masm,
Code::Flags flags,
CompilationInfo* info) {
Isolate* isolate = info->isolate();
// Allocate and install the code.
CodeDesc desc;
bool is_crankshafted =
Code::ExtractKindFromFlags(flags) == Code::OPTIMIZED_FUNCTION ||
info->IsStub();
masm->GetCode(&desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, flags, masm->CodeObject(),
false, is_crankshafted,
info->prologue_offset(),
info->is_debug() && !is_crankshafted);
isolate->counters()->total_compiled_code_size()->Increment(
code->instruction_size());
isolate->heap()->IncrementCodeGeneratedBytes(is_crankshafted,
code->instruction_size());
return code;
}
void CodeGenerator::PrintCode(Handle<Code> code, CompilationInfo* info) {
#ifdef ENABLE_DISASSEMBLER
AllowDeferredHandleDereference allow_deference_for_print_code;
bool print_code = info->isolate()->bootstrapper()->IsActive()
? FLAG_print_builtin_code
: (FLAG_print_code ||
(info->IsStub() && FLAG_print_code_stubs) ||
(info->IsOptimizing() && FLAG_print_opt_code));
if (print_code) {
// Print the source code if available.
FunctionLiteral* function = info->function();
bool print_source = code->kind() == Code::OPTIMIZED_FUNCTION ||
code->kind() == Code::FUNCTION;
CodeTracer::Scope tracing_scope(info->isolate()->GetCodeTracer());
OFStream os(tracing_scope.file());
if (print_source) {
Handle<Script> script = info->script();
if (!script->IsUndefined() && !script->source()->IsUndefined()) {
os << "--- Raw source ---\n";
ConsStringIteratorOp op;
StringCharacterStream stream(String::cast(script->source()),
&op,
function->start_position());
// fun->end_position() points to the last character in the stream. We
// need to compensate by adding one to calculate the length.
int source_len =
function->end_position() - function->start_position() + 1;
for (int i = 0; i < source_len; i++) {
if (stream.HasMore()) {
os << AsReversiblyEscapedUC16(stream.GetNext());
}
}
os << "\n\n";
}
}
if (info->IsOptimizing()) {
if (FLAG_print_unopt_code) {
os << "--- Unoptimized code ---\n";
info->closure()->shared()->code()->Disassemble(
function->debug_name()->ToCString().get(), os);
}
os << "--- Optimized code ---\n"
<< "optimization_id = " << info->optimization_id() << "\n";
} else {
os << "--- Code ---\n";
}
if (print_source) {
os << "source_position = " << function->start_position() << "\n";
}
if (info->IsStub()) {
CodeStub::Major major_key = info->code_stub()->MajorKey();
code->Disassemble(CodeStub::MajorName(major_key, false), os);
} else {
code->Disassemble(function->debug_name()->ToCString().get(), os);
}
os << "--- End code ---\n";
}
#endif // ENABLE_DISASSEMBLER
}
bool CodeGenerator::RecordPositions(MacroAssembler* masm,
int pos,
bool right_here) {
if (pos != RelocInfo::kNoPosition) {
masm->positions_recorder()->RecordStatementPosition(pos);
masm->positions_recorder()->RecordPosition(pos);
if (right_here) {
return masm->positions_recorder()->WriteRecordedPositions();
}
}
return false;
}
} } // namespace v8::internal
<commit_msg>Allow trace-codegen to dereference handles.<commit_after>// Copyright 2012 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/v8.h"
#include "src/bootstrapper.h"
#include "src/codegen.h"
#include "src/compiler.h"
#include "src/cpu-profiler.h"
#include "src/debug.h"
#include "src/prettyprinter.h"
#include "src/rewriter.h"
#include "src/runtime.h"
namespace v8 {
namespace internal {
#if defined(_WIN64)
typedef double (*ModuloFunction)(double, double);
static ModuloFunction modulo_function = NULL;
// Defined in codegen-x64.cc.
ModuloFunction CreateModuloFunction();
void init_modulo_function() {
modulo_function = CreateModuloFunction();
}
double modulo(double x, double y) {
// Note: here we rely on dependent reads being ordered. This is true
// on all architectures we currently support.
return (*modulo_function)(x, y);
}
#elif defined(_WIN32)
double modulo(double x, double y) {
// Workaround MS fmod bugs. ECMA-262 says:
// dividend is finite and divisor is an infinity => result equals dividend
// dividend is a zero and divisor is nonzero finite => result equals dividend
if (!(std::isfinite(x) && (!std::isfinite(y) && !std::isnan(y))) &&
!(x == 0 && (y != 0 && std::isfinite(y)))) {
x = fmod(x, y);
}
return x;
}
#else // POSIX
double modulo(double x, double y) {
return std::fmod(x, y);
}
#endif // defined(_WIN64)
#define UNARY_MATH_FUNCTION(name, generator) \
static UnaryMathFunction fast_##name##_function = NULL; \
void init_fast_##name##_function() { \
fast_##name##_function = generator; \
} \
double fast_##name(double x) { \
return (*fast_##name##_function)(x); \
}
UNARY_MATH_FUNCTION(exp, CreateExpFunction())
UNARY_MATH_FUNCTION(sqrt, CreateSqrtFunction())
#undef UNARY_MATH_FUNCTION
void lazily_initialize_fast_exp() {
if (fast_exp_function == NULL) {
init_fast_exp_function();
}
}
#define __ ACCESS_MASM(masm_)
#ifdef DEBUG
Comment::Comment(MacroAssembler* masm, const char* msg)
: masm_(masm), msg_(msg) {
__ RecordComment(msg);
}
Comment::~Comment() {
if (msg_[0] == '[') __ RecordComment("]");
}
#endif // DEBUG
#undef __
void CodeGenerator::MakeCodePrologue(CompilationInfo* info, const char* kind) {
bool print_source = false;
bool print_ast = false;
const char* ftype;
if (info->isolate()->bootstrapper()->IsActive()) {
print_source = FLAG_print_builtin_source;
print_ast = FLAG_print_builtin_ast;
ftype = "builtin";
} else {
print_source = FLAG_print_source;
print_ast = FLAG_print_ast;
ftype = "user-defined";
}
if (FLAG_trace_codegen || print_source || print_ast) {
PrintF("[generating %s code for %s function: ", kind, ftype);
if (info->IsStub()) {
const char* name =
CodeStub::MajorName(info->code_stub()->MajorKey(), true);
PrintF("%s", name == NULL ? "<unknown>" : name);
} else {
AllowDeferredHandleDereference allow_deference_for_trace;
PrintF("%s", info->function()->debug_name()->ToCString().get());
}
PrintF("]\n");
}
#ifdef DEBUG
if (!info->IsStub() && print_source) {
PrintF("--- Source from AST ---\n%s\n",
PrettyPrinter(info->zone()).PrintProgram(info->function()));
}
if (!info->IsStub() && print_ast) {
PrintF("--- AST ---\n%s\n",
AstPrinter(info->zone()).PrintProgram(info->function()));
}
#endif // DEBUG
}
Handle<Code> CodeGenerator::MakeCodeEpilogue(MacroAssembler* masm,
Code::Flags flags,
CompilationInfo* info) {
Isolate* isolate = info->isolate();
// Allocate and install the code.
CodeDesc desc;
bool is_crankshafted =
Code::ExtractKindFromFlags(flags) == Code::OPTIMIZED_FUNCTION ||
info->IsStub();
masm->GetCode(&desc);
Handle<Code> code =
isolate->factory()->NewCode(desc, flags, masm->CodeObject(),
false, is_crankshafted,
info->prologue_offset(),
info->is_debug() && !is_crankshafted);
isolate->counters()->total_compiled_code_size()->Increment(
code->instruction_size());
isolate->heap()->IncrementCodeGeneratedBytes(is_crankshafted,
code->instruction_size());
return code;
}
void CodeGenerator::PrintCode(Handle<Code> code, CompilationInfo* info) {
#ifdef ENABLE_DISASSEMBLER
AllowDeferredHandleDereference allow_deference_for_print_code;
bool print_code = info->isolate()->bootstrapper()->IsActive()
? FLAG_print_builtin_code
: (FLAG_print_code ||
(info->IsStub() && FLAG_print_code_stubs) ||
(info->IsOptimizing() && FLAG_print_opt_code));
if (print_code) {
// Print the source code if available.
FunctionLiteral* function = info->function();
bool print_source = code->kind() == Code::OPTIMIZED_FUNCTION ||
code->kind() == Code::FUNCTION;
CodeTracer::Scope tracing_scope(info->isolate()->GetCodeTracer());
OFStream os(tracing_scope.file());
if (print_source) {
Handle<Script> script = info->script();
if (!script->IsUndefined() && !script->source()->IsUndefined()) {
os << "--- Raw source ---\n";
ConsStringIteratorOp op;
StringCharacterStream stream(String::cast(script->source()),
&op,
function->start_position());
// fun->end_position() points to the last character in the stream. We
// need to compensate by adding one to calculate the length.
int source_len =
function->end_position() - function->start_position() + 1;
for (int i = 0; i < source_len; i++) {
if (stream.HasMore()) {
os << AsReversiblyEscapedUC16(stream.GetNext());
}
}
os << "\n\n";
}
}
if (info->IsOptimizing()) {
if (FLAG_print_unopt_code) {
os << "--- Unoptimized code ---\n";
info->closure()->shared()->code()->Disassemble(
function->debug_name()->ToCString().get(), os);
}
os << "--- Optimized code ---\n"
<< "optimization_id = " << info->optimization_id() << "\n";
} else {
os << "--- Code ---\n";
}
if (print_source) {
os << "source_position = " << function->start_position() << "\n";
}
if (info->IsStub()) {
CodeStub::Major major_key = info->code_stub()->MajorKey();
code->Disassemble(CodeStub::MajorName(major_key, false), os);
} else {
code->Disassemble(function->debug_name()->ToCString().get(), os);
}
os << "--- End code ---\n";
}
#endif // ENABLE_DISASSEMBLER
}
bool CodeGenerator::RecordPositions(MacroAssembler* masm,
int pos,
bool right_here) {
if (pos != RelocInfo::kNoPosition) {
masm->positions_recorder()->RecordStatementPosition(pos);
masm->positions_recorder()->RecordPosition(pos);
if (right_here) {
return masm->positions_recorder()->WriteRecordedPositions();
}
}
return false;
}
} } // namespace v8::internal
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2018, NVIDIA CORPORATION.
*
* 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.
*/
/** ---------------------------------------------------------------------------*
* @brief Operations on GDF columns
*
* @file column.cpp
* ---------------------------------------------------------------------------**/
#include <gdf/gdf.h>
#include <gdf/utils.h>
#include <gdf/errorutils.h>
#include <cuda_runtime_api.h>
// forward decl -- see validops.cu
gdf_error gdf_mask_concat(gdf_valid_type *output_mask,
gdf_size_type output_column_length,
gdf_valid_type *masks_to_concat[],
gdf_size_type *column_lengths,
gdf_size_type num_columns);
/** ---------------------------------------------------------------------------*
* @brief Concatenates multiple gdf_columns into a single, contiguous column,
* including the validity bitmasks.
*
* Note that input columns with nullptr validity masks are treated as if all
* elements are valid.
*
* @param[out] output_column A column whose buffers are already allocated that
* will contain the concatenation of the input columns data and
* validity bitmasks
* @Param[in] columns_to_concat[] The columns to concatenate
* @Param[in] num_columns The number of columns to concatenate
*
* @return gdf_error GDF_SUCCESS upon completion; GDF_DATASET_EMPTY if any data
* pointer is NULL, GDF_COLUMN_SIZE_MISMATCH if the output column size
* != the total size of the input columns; GDF_DTYPE_MISMATCH if the
* input columns have different datatypes.
* ---------------------------------------------------------------------------**/
gdf_error gdf_column_concat(gdf_column *output_column, gdf_column *columns_to_concat[], int num_columns)
{
if (nullptr == columns_to_concat){
return GDF_DATASET_EMPTY;
}
if ((nullptr == columns_to_concat[0])
|| (nullptr == output_column)){
return GDF_DATASET_EMPTY;
}
const gdf_dtype column_type = columns_to_concat[0]->dtype;
if (column_type != output_column->dtype){
return GDF_DTYPE_MISMATCH;
}
gdf_size_type total_size = 0;
bool at_least_one_mask_present = false;
// Ensure all the columns are properly allocated
// and have matching types
for (int i = 0; i < num_columns; ++i) {
gdf_column* current_column = columns_to_concat[i];
if (nullptr == current_column) {
return GDF_DATASET_EMPTY;
}
if ((current_column->size > 0) && (nullptr == current_column->data))
{
return GDF_DATASET_EMPTY;
}
if (column_type != current_column->dtype) {
return GDF_DTYPE_MISMATCH;
}
total_size += current_column->size;
at_least_one_mask_present |= (columns_to_concat[i]->valid != 0);
}
// sum of the sizes of the input columns must equal output column size
if (output_column->size != total_size) {
return GDF_COLUMN_SIZE_MISMATCH;
}
int8_t* target = (int8_t*)(output_column->data);
output_column->null_count = 0;
// copy data
for (int i = 0; i < num_columns; ++i) {
gdf_size_type bytes = sizeof(column_type) * columns_to_concat[i]->size;
cudaMemcpy(target, columns_to_concat[i]->data, bytes, cudaMemcpyDeviceToDevice);
target += bytes;
output_column->null_count += columns_to_concat[i]->null_count;
}
if (at_least_one_mask_present) {
gdf_valid_type** masks;
gdf_size_type* column_lengths;
cudaMallocManaged((void**)&masks, sizeof(gdf_valid_type*)*num_columns);
cudaMallocManaged((void**)&column_lengths, sizeof(gdf_size_type)*num_columns);
for (int i = 0; i < num_columns; ++i) {
masks[i] = columns_to_concat[i]->valid;
column_lengths[i] = columns_to_concat[i]->size;
}
gdf_mask_concat(output_column->valid, output_column->size, masks, column_lengths, num_columns);
cudaFree(masks);
cudaFree(column_lengths);
}
else {
// no masks, so just fill output valid mask with all 1 bits
// TODO: async
cudaMemset(output_column->valid, 0xff, gdf_get_num_chars_bitmask(total_size) * sizeof(gdf_valid_type));
}
return GDF_SUCCESS;
}
/** ---------------------------------------------------------------------------*
* @brief Return the size of the gdf_column data type.
*
* @return gdf_size_type Size of the gdf_column data type.
*b ---------------------------------------------------------------------------**/
gdf_size_type gdf_column_sizeof() {
return sizeof(gdf_column);
}
/** ---------------------------------------------------------------------------*
* @brief Create a GDF column given data and validity bitmask pointers, size, and
* datatype
*
* @param[out] column The output column.
* @param[in] data Pointer to data.
* @param[in] valid Pointer to validity bitmask for the data.
* @param[in] size Number of rows in the column.
* @param[in] dtype Data type of the column.
* @return gdf_error Returns GDF_SUCCESS upon successful creation.
* ---------------------------------------------------------------------------**/
gdf_error gdf_column_view(gdf_column *column,
void *data,
gdf_valid_type *valid,
gdf_size_type size,
gdf_dtype dtype)
{
column->data = data;
column->valid = valid;
column->size = size;
column->dtype = dtype;
column->null_count = 0;
return GDF_SUCCESS;
}
/** ---------------------------------------------------------------------------*
* @brief Create a GDF column given data and validity bitmask pointers, size, and
* datatype, and count of null (non-valid) elements
*
* @param[out] column The output column.
* @param[in] data Pointer to data.
* @param[in] valid Pointer to validity bitmask for the data.
* @param[in] size Number of rows in the column.
* @param[in] dtype Data type of the column.
* @param[in] null_count The number of non-valid elements in the validity bitmask
* @return gdf_error Returns GDF_SUCCESS upon successful creation.
* ---------------------------------------------------------------------------**/
gdf_error gdf_column_view_augmented(gdf_column *column,
void *data,
gdf_valid_type *valid,
gdf_size_type size,
gdf_dtype dtype,
gdf_size_type null_count)
{
column->data = data;
column->valid = valid;
column->size = size;
column->dtype = dtype;
column->null_count = null_count;
return GDF_SUCCESS;
}
/** ---------------------------------------------------------------------------*
* @brief Free the CUDA device memory of a gdf_column
*
* @param[inout] column Data and validity bitmask pointers of this column will be freed
* @return gdf_error GDF_SUCCESS or GDF_ERROR if there is an error freeing the data
* ---------------------------------------------------------------------------**/
gdf_error gdf_column_free(gdf_column *column)
{
CUDA_TRY( cudaFree(column->data) );
CUDA_TRY( cudaFree(column->valid) );
return GDF_SUCCESS;
}
/** ---------------------------------------------------------------------------*
* @brief Get the byte width of a column
*
* @param[in] col The input column
* @param[out] width The data type size of col
* @return gdf_error GDF_SUCCESS, or GDF_UNSUPPORTED_DTYPE if col has an invalid
* datatype
* ---------------------------------------------------------------------------**/
gdf_error get_column_byte_width(gdf_column * col,
int * width)
{
switch(col->dtype) {
case GDF_INT8 :
*width = 1;
break;
case GDF_INT16 :
*width = 2;
break;
case GDF_INT32 :
*width = 4;
break;
case GDF_INT64 :
*width = 8;
break;
case GDF_FLOAT32 :
*width = 4;
break;
case GDF_FLOAT64 :
*width = 8;
break;
case GDF_DATE32 :
*width = 4;
break;
case GDF_DATE64 :
*width = 8;
break;
case GDF_TIMESTAMP :
*width = 8;
break;
default :
*width = -1;
return GDF_UNSUPPORTED_DTYPE;
}
return GDF_SUCCESS;
}
<commit_msg>Added notes on potential optimizations<commit_after>/*
* Copyright (c) 2018, NVIDIA CORPORATION.
*
* 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.
*/
/** ---------------------------------------------------------------------------*
* @brief Operations on GDF columns
*
* @file column.cpp
* ---------------------------------------------------------------------------**/
#include <gdf/gdf.h>
#include <gdf/utils.h>
#include <gdf/errorutils.h>
#include <cuda_runtime_api.h>
// forward decl -- see validops.cu
gdf_error gdf_mask_concat(gdf_valid_type *output_mask,
gdf_size_type output_column_length,
gdf_valid_type *masks_to_concat[],
gdf_size_type *column_lengths,
gdf_size_type num_columns);
/** ---------------------------------------------------------------------------*
* @brief Concatenates multiple gdf_columns into a single, contiguous column,
* including the validity bitmasks.
*
* Note that input columns with nullptr validity masks are treated as if all
* elements are valid.
*
* @param[out] output_column A column whose buffers are already allocated that
* will contain the concatenation of the input columns data and
* validity bitmasks
* @Param[in] columns_to_concat[] The columns to concatenate
* @Param[in] num_columns The number of columns to concatenate
*
* @return gdf_error GDF_SUCCESS upon completion; GDF_DATASET_EMPTY if any data
* pointer is NULL, GDF_COLUMN_SIZE_MISMATCH if the output column size
* != the total size of the input columns; GDF_DTYPE_MISMATCH if the
* input columns have different datatypes.
* ---------------------------------------------------------------------------**/
gdf_error gdf_column_concat(gdf_column *output_column, gdf_column *columns_to_concat[], int num_columns)
{
if (nullptr == columns_to_concat){
return GDF_DATASET_EMPTY;
}
if ((nullptr == columns_to_concat[0])
|| (nullptr == output_column)){
return GDF_DATASET_EMPTY;
}
const gdf_dtype column_type = columns_to_concat[0]->dtype;
if (column_type != output_column->dtype){
return GDF_DTYPE_MISMATCH;
}
gdf_size_type total_size = 0;
bool at_least_one_mask_present = false;
// Ensure all the columns are properly allocated
// and have matching types
for (int i = 0; i < num_columns; ++i) {
gdf_column* current_column = columns_to_concat[i];
if (nullptr == current_column) {
return GDF_DATASET_EMPTY;
}
if ((current_column->size > 0) && (nullptr == current_column->data))
{
return GDF_DATASET_EMPTY;
}
if (column_type != current_column->dtype) {
return GDF_DTYPE_MISMATCH;
}
total_size += current_column->size;
at_least_one_mask_present |= (columns_to_concat[i]->valid != 0);
}
// sum of the sizes of the input columns must equal output column size
if (output_column->size != total_size) {
return GDF_COLUMN_SIZE_MISMATCH;
}
int8_t* target = (int8_t*)(output_column->data);
output_column->null_count = 0;
// TODO optimizations if needed
// 1. Either
// a) use cudaMemcpyAsync to copy the data and overlap copies with gdf_mask_concat
// (this will require getting rid of the allocations below because they will
// implicitly sync the device), or
// b) use a kernel to copy the data from all columns in one go. This will likely not
// overlap with the gdf_mask_concat
// 2. Detect a zero total null count and skip gdf_mask_concat -- use cudaMemsetAsync
// copy data
for (int i = 0; i < num_columns; ++i) {
gdf_size_type bytes = sizeof(column_type) * columns_to_concat[i]->size;
cudaMemcpy(target, columns_to_concat[i]->data, bytes, cudaMemcpyDeviceToDevice);
target += bytes;
output_column->null_count += columns_to_concat[i]->null_count;
}
if (at_least_one_mask_present) {
gdf_valid_type** masks;
gdf_size_type* column_lengths;
cudaMallocManaged((void**)&masks, sizeof(gdf_valid_type*)*num_columns);
cudaMallocManaged((void**)&column_lengths, sizeof(gdf_size_type)*num_columns);
for (int i = 0; i < num_columns; ++i) {
masks[i] = columns_to_concat[i]->valid;
column_lengths[i] = columns_to_concat[i]->size;
}
gdf_mask_concat(output_column->valid, output_column->size, masks, column_lengths, num_columns);
cudaFree(masks);
cudaFree(column_lengths);
}
else {
// no masks, so just fill output valid mask with all 1 bits
// TODO: async
cudaMemset(output_column->valid, 0xff, gdf_get_num_chars_bitmask(total_size) * sizeof(gdf_valid_type));
}
return GDF_SUCCESS;
}
/** ---------------------------------------------------------------------------*
* @brief Return the size of the gdf_column data type.
*
* @return gdf_size_type Size of the gdf_column data type.
*b ---------------------------------------------------------------------------**/
gdf_size_type gdf_column_sizeof() {
return sizeof(gdf_column);
}
/** ---------------------------------------------------------------------------*
* @brief Create a GDF column given data and validity bitmask pointers, size, and
* datatype
*
* @param[out] column The output column.
* @param[in] data Pointer to data.
* @param[in] valid Pointer to validity bitmask for the data.
* @param[in] size Number of rows in the column.
* @param[in] dtype Data type of the column.
* @return gdf_error Returns GDF_SUCCESS upon successful creation.
* ---------------------------------------------------------------------------**/
gdf_error gdf_column_view(gdf_column *column,
void *data,
gdf_valid_type *valid,
gdf_size_type size,
gdf_dtype dtype)
{
column->data = data;
column->valid = valid;
column->size = size;
column->dtype = dtype;
column->null_count = 0;
return GDF_SUCCESS;
}
/** ---------------------------------------------------------------------------*
* @brief Create a GDF column given data and validity bitmask pointers, size, and
* datatype, and count of null (non-valid) elements
*
* @param[out] column The output column.
* @param[in] data Pointer to data.
* @param[in] valid Pointer to validity bitmask for the data.
* @param[in] size Number of rows in the column.
* @param[in] dtype Data type of the column.
* @param[in] null_count The number of non-valid elements in the validity bitmask
* @return gdf_error Returns GDF_SUCCESS upon successful creation.
* ---------------------------------------------------------------------------**/
gdf_error gdf_column_view_augmented(gdf_column *column,
void *data,
gdf_valid_type *valid,
gdf_size_type size,
gdf_dtype dtype,
gdf_size_type null_count)
{
column->data = data;
column->valid = valid;
column->size = size;
column->dtype = dtype;
column->null_count = null_count;
return GDF_SUCCESS;
}
/** ---------------------------------------------------------------------------*
* @brief Free the CUDA device memory of a gdf_column
*
* @param[inout] column Data and validity bitmask pointers of this column will be freed
* @return gdf_error GDF_SUCCESS or GDF_ERROR if there is an error freeing the data
* ---------------------------------------------------------------------------**/
gdf_error gdf_column_free(gdf_column *column)
{
CUDA_TRY( cudaFree(column->data) );
CUDA_TRY( cudaFree(column->valid) );
return GDF_SUCCESS;
}
/** ---------------------------------------------------------------------------*
* @brief Get the byte width of a column
*
* @param[in] col The input column
* @param[out] width The data type size of col
* @return gdf_error GDF_SUCCESS, or GDF_UNSUPPORTED_DTYPE if col has an invalid
* datatype
* ---------------------------------------------------------------------------**/
gdf_error get_column_byte_width(gdf_column * col,
int * width)
{
switch(col->dtype) {
case GDF_INT8 :
*width = 1;
break;
case GDF_INT16 :
*width = 2;
break;
case GDF_INT32 :
*width = 4;
break;
case GDF_INT64 :
*width = 8;
break;
case GDF_FLOAT32 :
*width = 4;
break;
case GDF_FLOAT64 :
*width = 8;
break;
case GDF_DATE32 :
*width = 4;
break;
case GDF_DATE64 :
*width = 8;
break;
case GDF_TIMESTAMP :
*width = 8;
break;
default :
*width = -1;
return GDF_UNSUPPORTED_DTYPE;
}
return GDF_SUCCESS;
}
<|endoftext|>
|
<commit_before>#include "common.h"
#include "Ruby.h"
#include "RubyObject.h"
#include "RubyModule.h"
#include <node.h>
#include <limits>
#include <iostream>
using namespace v8;
const int32_t MIN_INT32 = std::numeric_limits<int32_t>::min();
const int32_t MAX_INT32 = std::numeric_limits<int32_t>::max();
Handle<Value> rubyToV8(VALUE val)
{
NanEscapableScope();
log("Converting " << RSTRING_PTR(rb_funcall2(val, rb_intern("to_s"), 0, NULL)) << " to v8");
int type = TYPE(val);
switch (type) {
case T_NONE:
case T_NIL:
return NanEscapeScope(NanUndefined());
case T_FLOAT:
return NanEscapeScope(NanNew<Number>(RFLOAT_VALUE(val)));
case T_STRING:
return NanEscapeScope(NanNew<String>(RSTRING_PTR(val), RSTRING_LEN(val)));
case T_ARRAY: {
int len = RARRAY_LEN(val);
Local<Array> array = NanNew<Array>(len);
for (int i = 0; i < len; i++) {
array->Set(i, rubyToV8(rb_ary_entry(val, i)));
}
return NanEscapeScope(array);
}
case T_FIXNUM: {
long longVal = FIX2LONG(val);
if (longVal >= MIN_INT32 && longVal <= MAX_INT32) {
return NanEscapeScope(NanNew<Integer>(longVal));
}
else
return NanEscapeScope(NanNew<Number>(longVal));
}
case T_BIGNUM: {
double dblVal = rb_big2dbl(val);
// if (dblVal == HUGE_VAL || dblVal == -HUGE_VAL) {
// VALUE valStr = rb_big2str(val, 10);
// return NanEscapeScope(rubyToV8(valStr));
// }
// else
return NanEscapeScope(NanNew<Number>(dblVal));
}
case T_TRUE:
return NanEscapeScope(NanTrue());
case T_FALSE:
return NanEscapeScope(NanFalse());
case T_OBJECT:
case T_DATA: {
Local<Object> owner = RubyObject::RubyUnwrap(val);
if (owner.IsEmpty()) {
owner = NanNew<Object>();
Local<Object> ctor = RubyModule::ToV8(CLASS_OF(val));
owner->SetPrototype(ctor->Get(NanNew<String>("prototype")));
owner->Set(NanNew<String>("_rubyObj"), RubyObject::ToV8(val, owner));
}
return NanEscapeScope(owner);
}
case T_SYMBOL: {
VALUE str = rb_id2str(SYM2ID(val));
return NanEscapeScope(NanNew<String>(RSTRING_PTR(str), RSTRING_LEN(str)));
}
case T_MODULE:
case T_CLASS:
return NanEscapeScope(RubyModule::ToV8(val));
default:
std::cerr << "Unknown ruby type(" << type << "): " <<
rb_obj_classname(val) << std::endl;
return NanEscapeScope(NanUndefined());
}
}
VALUE v8ToRuby(Handle<Value> val)
{
NanScope();
log("Converting " << *String::Utf8Value(val) << " to ruby");
if (val->IsUndefined())
return Qnil;
else if (val->IsNull())
return Qnil;
else if (val->IsTrue())
return Qtrue;
else if (val->IsFalse())
return Qfalse;
else if (val->IsString()) {
// TODO: We should handle encoding here
Handle<String> str = val.As<String>();
VALUE rbStr = rb_str_new(NULL, str->Utf8Length());
str->WriteUtf8(RSTRING_PTR(rbStr));
return rbStr;
}
else if (val->IsArray()) {
Handle<Array> v8Arr = val.As<Array>();
VALUE rbArr = rb_ary_new2(v8Arr->Length());
for (uint32_t i = 0; i < v8Arr->Length(); i++) {
rb_ary_store(rbArr, i, v8ToRuby(v8Arr->Get(i)));
}
return rbArr;
}
else if (val->IsInt32())
return INT2NUM(val->Int32Value());
else if (val->IsUint32())
return UINT2NUM(val->Uint32Value());
else if (val->IsNumber())
return rb_float_new(val->NumberValue());
else if (val->IsFunction()) {
Local<Object> rubyClass =
val.As<Function>()->Get(NanNew<String>("_rubyClass")).As<Object>();
if (!rubyClass.IsEmpty() && rubyClass->IsObject() &&
rubyClass->InternalFieldCount() == 1) {
return VALUE(NanGetInternalFieldPointer(rubyClass, 0));
}
}
else if (val->IsObject()) {
VALUE rbObj = RubyObject::FromV8(val.As<Object>());
if (rbObj != Qnil)
return rbObj;
// TODO: Should we wrap objects here?
}
String::Utf8Value str(val->ToDetailString());
std::cerr << "Unknown v8 type: " << *str << std::endl;
return Qnil;
}
Handle<Value> rubyExToV8(VALUE ex)
{
NanEscapableScope();
assert(rb_obj_is_kind_of(ex, rb_eException) == Qtrue);
VALUE msg = rb_funcall(ex, rb_intern("message"), 0);
Local<String> msgStr = NanNew<String>(RSTRING_PTR(msg), RSTRING_LEN(msg));
Local<Value> v8Err;
VALUE klass = rb_class_of(ex);
if (klass == rb_eArgError ||
klass == rb_eLoadError)
v8Err = Exception::Error(msgStr);
else if (klass == rb_eNameError ||
klass == rb_eNoMethodError)
v8Err = Exception::ReferenceError(msgStr);
else if (klass == rb_eTypeError)
v8Err = Exception::TypeError(msgStr);
else if (klass == rb_eSyntaxError)
v8Err = Exception::SyntaxError(msgStr);
else {
std::cerr << "Unknown ruby exception: " <<
rb_obj_classname(ex) << std::endl;
v8Err = Exception::Error(msgStr);
}
VALUE backtrace = rb_funcall(ex, rb_intern("backtrace"), 0);
Local<Object> errObj = v8Err.As<Object>();
errObj->Set(NanNew<String>("rubyStack"), rubyToV8(backtrace));
return NanEscapeScope(v8Err);
}
VALUE RescueCB(VALUE data, VALUE ex)
{
VALUE *storedEx = reinterpret_cast<VALUE*>(data);
*storedEx = ex;
return Qnil;
}
VALUE CallV8FromRuby(const Handle<Object> recv,
const Handle<Function> callback,
int argc, const VALUE* argv)
{
NanScope();
std::vector<Handle<Value> > v8Args(argc);
for (int i = 0; i < argc; i++) {
v8Args[i] = rubyToV8(argv[i]);
}
Handle<Value> ret = NanMakeCallback(recv, callback, argc, &v8Args[0]);
return v8ToRuby(ret);
}
struct MethodCaller::Block
{
Block(Handle<Function> f)
{
NanAssignPersistent(func, f);
dataObj = Data_Wrap_Struct(Ruby::BLOCK_WRAPPER_CLASS, NULL, Free, this);
}
static VALUE Func(VALUE, VALUE data, int argc, const VALUE* rbArgv)
{
Block* block;
Data_Get_Struct(data, Block, block);
Local<Function> fn = NanNew<Function>(block->func);
// TODO: Should we store args.This() and call it as the receiver?
return CallV8FromRuby(NanGetCurrentContext()->Global(), fn,
argc, rbArgv);
}
static void Free(void* data)
{
Block* block = static_cast<Block*>(data);
NanDisposePersistent(block->func);
delete block;
}
Persistent<Function> func;
VALUE dataObj;
};
MethodCaller::MethodCaller(VALUE o, _NAN_METHOD_ARGS_TYPE args, int start):
obj(o), methodID(ID(EXTERNAL_UNWRAP(args.Data()))),
rubyArgs(args.Length()-start), block(NULL)
{
// TODO: Is this right? Is there a way to determine if a block is expected?
if (args.Length()-start > 0 && args[args.Length()-1]->IsFunction()) {
Local<Function> func = args[args.Length()-1].As<Function>();
if (!func->Has(NanNew<String>("_rubyClass"))) {
block = new Block(func);
rubyArgs.resize(rubyArgs.size()-1);
}
}
for (size_t i = 0; i < rubyArgs.size(); i++) {
rubyArgs[i] = v8ToRuby(args[i+start]);
}
}
VALUE MethodCaller::operator()() const
{
if (block == NULL) {
log("Calling method: " << rb_obj_classname(obj) << "." <<
rb_id2name(methodID) << " with " << rubyArgs.size() << " args");
return rb_funcall2(obj, methodID, rubyArgs.size(), (VALUE*)&rubyArgs[0]);
}
else {
log("Calling method: " << rb_obj_classname(obj) << "." <<
rb_id2name(methodID) << " with " << rubyArgs.size() <<
" args and a block");
// TODO: Probably not available in Ruby < 1.9
return rb_block_call(obj, methodID, rubyArgs.size(), (VALUE*)&rubyArgs[0],
RUBY_METHOD_FUNC(Block::Func), block->dataObj);
}
}
Handle<Value> CallRubyFromV8(VALUE recv, _NAN_METHOD_ARGS_TYPE args)
{
NanEscapableScope();
VALUE ex;
VALUE res = SafeRubyCall(MethodCaller(recv, args), ex);
if (ex != Qnil) {
NanThrowError(rubyExToV8(ex));
return NanEscapeScope(NanUndefined());
}
return NanEscapeScope(rubyToV8(res));
}
void DumpRubyArgs(int argc, VALUE* argv)
{
#ifdef _DEBUG
for (int i = 0; i < argc; i++) {
VALUE str = rb_funcall2(argv[i], rb_intern("to_s"), 0, NULL);
std::cout << i << ": " << StringValueCStr(str) << std::endl;
}
#endif
}
void DumpV8Props(Handle<Object> obj)
{
#ifdef _DEBUG
NanScope();
Local<Array> propNames = obj->GetPropertyNames();
for (uint32_t i = 0; i < propNames->Length(); i++) {
Local<Value> key = propNames->Get(i);
std::cout << *String::Utf8Value(key) << std::endl;
}
#endif
}
void DumpV8Args(_NAN_METHOD_ARGS_TYPE args)
{
#ifdef _DEBUG
NanScope();
for (int i = 0; i < args.Length(); i++) {
std::cout << i << ": " << *String::Utf8Value(args[i]) << std::endl;
}
#endif
}
<commit_msg>Fixed conversion of really big Bignums<commit_after>#include "common.h"
#include "Ruby.h"
#include "RubyObject.h"
#include "RubyModule.h"
#include <node.h>
#include <limits>
#include <iostream>
#include <math.h>
using namespace v8;
const int32_t MIN_INT32 = std::numeric_limits<int32_t>::min();
const int32_t MAX_INT32 = std::numeric_limits<int32_t>::max();
Handle<Value> rubyToV8(VALUE val)
{
NanEscapableScope();
log("Converting " << RSTRING_PTR(rb_funcall2(val, rb_intern("to_s"), 0, NULL)) << " to v8");
int type = TYPE(val);
switch (type) {
case T_NONE:
case T_NIL:
return NanEscapeScope(NanUndefined());
case T_FLOAT:
return NanEscapeScope(NanNew<Number>(RFLOAT_VALUE(val)));
case T_STRING:
return NanEscapeScope(NanNew<String>(RSTRING_PTR(val), RSTRING_LEN(val)));
case T_ARRAY: {
int len = RARRAY_LEN(val);
Local<Array> array = NanNew<Array>(len);
for (int i = 0; i < len; i++) {
array->Set(i, rubyToV8(rb_ary_entry(val, i)));
}
return NanEscapeScope(array);
}
case T_FIXNUM: {
long longVal = FIX2LONG(val);
if (longVal >= MIN_INT32 && longVal <= MAX_INT32) {
return NanEscapeScope(NanNew<Integer>(longVal));
}
else
return NanEscapeScope(NanNew<Number>(longVal));
}
case T_BIGNUM: {
double dblVal = rb_big2dbl(val);
if (dblVal == HUGE_VAL || dblVal == -HUGE_VAL) {
VALUE valStr = rb_big2str(val, 10);
return NanEscapeScope(rubyToV8(valStr));
}
else
return NanEscapeScope(NanNew<Number>(dblVal));
}
case T_TRUE:
return NanEscapeScope(NanTrue());
case T_FALSE:
return NanEscapeScope(NanFalse());
case T_OBJECT:
case T_DATA: {
Local<Object> owner = RubyObject::RubyUnwrap(val);
if (owner.IsEmpty()) {
owner = NanNew<Object>();
Local<Object> ctor = RubyModule::ToV8(CLASS_OF(val));
owner->SetPrototype(ctor->Get(NanNew<String>("prototype")));
owner->Set(NanNew<String>("_rubyObj"), RubyObject::ToV8(val, owner));
}
return NanEscapeScope(owner);
}
case T_SYMBOL: {
VALUE str = rb_id2str(SYM2ID(val));
return NanEscapeScope(NanNew<String>(RSTRING_PTR(str), RSTRING_LEN(str)));
}
case T_MODULE:
case T_CLASS:
return NanEscapeScope(RubyModule::ToV8(val));
default:
std::cerr << "Unknown ruby type(" << type << "): " <<
rb_obj_classname(val) << std::endl;
return NanEscapeScope(NanUndefined());
}
}
VALUE v8ToRuby(Handle<Value> val)
{
NanScope();
log("Converting " << *String::Utf8Value(val) << " to ruby");
if (val->IsUndefined())
return Qnil;
else if (val->IsNull())
return Qnil;
else if (val->IsTrue())
return Qtrue;
else if (val->IsFalse())
return Qfalse;
else if (val->IsString()) {
// TODO: We should handle encoding here
Handle<String> str = val.As<String>();
VALUE rbStr = rb_str_new(NULL, str->Utf8Length());
str->WriteUtf8(RSTRING_PTR(rbStr));
return rbStr;
}
else if (val->IsArray()) {
Handle<Array> v8Arr = val.As<Array>();
VALUE rbArr = rb_ary_new2(v8Arr->Length());
for (uint32_t i = 0; i < v8Arr->Length(); i++) {
rb_ary_store(rbArr, i, v8ToRuby(v8Arr->Get(i)));
}
return rbArr;
}
else if (val->IsInt32())
return INT2NUM(val->Int32Value());
else if (val->IsUint32())
return UINT2NUM(val->Uint32Value());
else if (val->IsNumber())
return rb_float_new(val->NumberValue());
else if (val->IsFunction()) {
Local<Object> rubyClass =
val.As<Function>()->Get(NanNew<String>("_rubyClass")).As<Object>();
if (!rubyClass.IsEmpty() && rubyClass->IsObject() &&
rubyClass->InternalFieldCount() == 1) {
return VALUE(NanGetInternalFieldPointer(rubyClass, 0));
}
}
else if (val->IsObject()) {
VALUE rbObj = RubyObject::FromV8(val.As<Object>());
if (rbObj != Qnil)
return rbObj;
// TODO: Should we wrap objects here?
}
String::Utf8Value str(val->ToDetailString());
std::cerr << "Unknown v8 type: " << *str << std::endl;
return Qnil;
}
Handle<Value> rubyExToV8(VALUE ex)
{
NanEscapableScope();
assert(rb_obj_is_kind_of(ex, rb_eException) == Qtrue);
VALUE msg = rb_funcall(ex, rb_intern("message"), 0);
Local<String> msgStr = NanNew<String>(RSTRING_PTR(msg), RSTRING_LEN(msg));
Local<Value> v8Err;
VALUE klass = rb_class_of(ex);
if (klass == rb_eArgError ||
klass == rb_eLoadError)
v8Err = Exception::Error(msgStr);
else if (klass == rb_eNameError ||
klass == rb_eNoMethodError)
v8Err = Exception::ReferenceError(msgStr);
else if (klass == rb_eTypeError)
v8Err = Exception::TypeError(msgStr);
else if (klass == rb_eSyntaxError)
v8Err = Exception::SyntaxError(msgStr);
else {
std::cerr << "Unknown ruby exception: " <<
rb_obj_classname(ex) << std::endl;
v8Err = Exception::Error(msgStr);
}
VALUE backtrace = rb_funcall(ex, rb_intern("backtrace"), 0);
Local<Object> errObj = v8Err.As<Object>();
errObj->Set(NanNew<String>("rubyStack"), rubyToV8(backtrace));
return NanEscapeScope(v8Err);
}
VALUE RescueCB(VALUE data, VALUE ex)
{
VALUE *storedEx = reinterpret_cast<VALUE*>(data);
*storedEx = ex;
return Qnil;
}
VALUE CallV8FromRuby(const Handle<Object> recv,
const Handle<Function> callback,
int argc, const VALUE* argv)
{
NanScope();
std::vector<Handle<Value> > v8Args(argc);
for (int i = 0; i < argc; i++) {
v8Args[i] = rubyToV8(argv[i]);
}
Handle<Value> ret = NanMakeCallback(recv, callback, argc, &v8Args[0]);
return v8ToRuby(ret);
}
struct MethodCaller::Block
{
Block(Handle<Function> f)
{
NanAssignPersistent(func, f);
dataObj = Data_Wrap_Struct(Ruby::BLOCK_WRAPPER_CLASS, NULL, Free, this);
}
static VALUE Func(VALUE, VALUE data, int argc, const VALUE* rbArgv)
{
Block* block;
Data_Get_Struct(data, Block, block);
Local<Function> fn = NanNew<Function>(block->func);
// TODO: Should we store args.This() and call it as the receiver?
return CallV8FromRuby(NanGetCurrentContext()->Global(), fn,
argc, rbArgv);
}
static void Free(void* data)
{
Block* block = static_cast<Block*>(data);
NanDisposePersistent(block->func);
delete block;
}
Persistent<Function> func;
VALUE dataObj;
};
MethodCaller::MethodCaller(VALUE o, _NAN_METHOD_ARGS_TYPE args, int start):
obj(o), methodID(ID(EXTERNAL_UNWRAP(args.Data()))),
rubyArgs(args.Length()-start), block(NULL)
{
// TODO: Is this right? Is there a way to determine if a block is expected?
if (args.Length()-start > 0 && args[args.Length()-1]->IsFunction()) {
Local<Function> func = args[args.Length()-1].As<Function>();
if (!func->Has(NanNew<String>("_rubyClass"))) {
block = new Block(func);
rubyArgs.resize(rubyArgs.size()-1);
}
}
for (size_t i = 0; i < rubyArgs.size(); i++) {
rubyArgs[i] = v8ToRuby(args[i+start]);
}
}
VALUE MethodCaller::operator()() const
{
if (block == NULL) {
log("Calling method: " << rb_obj_classname(obj) << "." <<
rb_id2name(methodID) << " with " << rubyArgs.size() << " args");
return rb_funcall2(obj, methodID, rubyArgs.size(), (VALUE*)&rubyArgs[0]);
}
else {
log("Calling method: " << rb_obj_classname(obj) << "." <<
rb_id2name(methodID) << " with " << rubyArgs.size() <<
" args and a block");
// TODO: Probably not available in Ruby < 1.9
return rb_block_call(obj, methodID, rubyArgs.size(), (VALUE*)&rubyArgs[0],
RUBY_METHOD_FUNC(Block::Func), block->dataObj);
}
}
Handle<Value> CallRubyFromV8(VALUE recv, _NAN_METHOD_ARGS_TYPE args)
{
NanEscapableScope();
VALUE ex;
VALUE res = SafeRubyCall(MethodCaller(recv, args), ex);
if (ex != Qnil) {
NanThrowError(rubyExToV8(ex));
return NanEscapeScope(NanUndefined());
}
return NanEscapeScope(rubyToV8(res));
}
void DumpRubyArgs(int argc, VALUE* argv)
{
#ifdef _DEBUG
for (int i = 0; i < argc; i++) {
VALUE str = rb_funcall2(argv[i], rb_intern("to_s"), 0, NULL);
std::cout << i << ": " << StringValueCStr(str) << std::endl;
}
#endif
}
void DumpV8Props(Handle<Object> obj)
{
#ifdef _DEBUG
NanScope();
Local<Array> propNames = obj->GetPropertyNames();
for (uint32_t i = 0; i < propNames->Length(); i++) {
Local<Value> key = propNames->Get(i);
std::cout << *String::Utf8Value(key) << std::endl;
}
#endif
}
void DumpV8Args(_NAN_METHOD_ARGS_TYPE args)
{
#ifdef _DEBUG
NanScope();
for (int i = 0; i < args.Length(); i++) {
std::cout << i << ": " << *String::Utf8Value(args[i]) << std::endl;
}
#endif
}
<|endoftext|>
|
<commit_before>/*-
* Copyright (C) 2008-2009 by Maxim Ignatenko
* gelraen.ua@gmail.com
*
* All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions *
* are met: *
* * Redistributions of source code must retain the above copyright *
* notice, this list of conditions and the following disclaimer. *
* * Redistributions in binary form must reproduce the above copyright *
* notice, this list of conditions and the following disclaimer in *
* the documentation and/or other materials provided with the *
* distribution. *
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS *
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT *
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR *
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT *
* 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. *
*
* $Id$
*/
#include "config.h"
#include "defs.h"
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
Config::Config()
: IRCConfig(), DCConfig()
{
m_loglevel=log::error + log::warning + log::notice;
m_bSyslog=0;
}
Config::Config(const IRCConfig& c1,const DCConfig& c2, const Config& conf)
: IRCConfig(c1), DCConfig(c2)
{
m_sLogFile=conf.m_sLogFile;
m_pidfile=conf.m_pidfile;
m_loglevel=conf.m_loglevel;
m_bSyslog=m_bSyslog;
}
Config::~Config()
{
}
struct confvar
{
string name;
char type; // 's','i'
int Config::* np;
string Config::* sp;
};
const confvar varlist[]={
{"irc_server", 's', NULL, &Config::m_irc_server},
{"irc_port", 'i', &Config::m_irc_port, NULL},
{"irc_nick", 's', NULL, &Config::m_irc_nick},
{"irc_username", 's', NULL, &Config::m_irc_username},
{"irc_password", 's', NULL, &Config::m_irc_password},
{"irc_realname", 's', NULL, &Config::m_irc_realname},
{"irc_channel", 's', NULL, &Config::m_irc_channel},
{"dc_server", 's', NULL, &Config::m_dc_server},
{"dc_port", 'i', &Config::m_dc_port, NULL},
{"dc_nick", 's', NULL, &Config::m_dc_nick},
{"dc_pass", 's', NULL, &Config::m_dc_pass},
{"dc_description", 's', NULL, &Config::m_dc_description},
{"dc_speed", 's', NULL, &Config::m_dc_speed},
{"dc_speed_val", 'i', &Config::m_dc_speed_val, NULL},
{"dc_email", 's', NULL, &Config::m_dc_email},
{"dc_share_size", 's', NULL, &Config::m_dc_share_size},
{"logfile", 's', NULL, &Config::m_sLogFile},
{"pidfile", 's', NULL, &Config::m_pidfile},
{"loglevel", 'i', &Config::m_loglevel, NULL},
{"use_syslog", 'i', &Config::m_bSyslog, NULL},
{"", '\0', NULL, NULL} // terminator
};
/*!
\fn Config::ReadFromFile(const string& sConfFile)
*/
bool Config::ReadFromFile(const string& sConfFile)
{
string str;
ifstream conf(sConfFile.c_str());
if (conf.bad()) return false;
while (!conf.eof())
{
getline(conf,str);
string::size_type pos=0;
str=trim(str);
if ((pos=str.find(';'))!=string::npos)
{
str.erase(pos); // erase all after ';'
}
if (str == ""||(pos=str.find("="))==string::npos)
continue;
vars[trim(str.substr(0, pos))] =
trim(trim(trim(str.substr(pos + 1)), '\''), '\"');
};
int i;
istringstream s;
for(i=0;varlist[i].type!='\0';i++)
{
if (vars.find(varlist[i].name)==vars.end()) continue;
switch (varlist[i].type)
{
case 's':
(this->*(varlist[i].sp))=vars[varlist[i].name];
break;
case 'i':
s.str(vars[varlist[i].name]);
s >> (this->*(varlist[i].np));
break;
}
}
return true;
}
/*!
\fn Config::getLogFile()
*/
const string& Config::getLogFile()
{
return m_sLogFile;
}
<commit_msg>Bugfixing<commit_after>/*-
* Copyright (C) 2008-2009 by Maxim Ignatenko
* gelraen.ua@gmail.com
*
* All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions *
* are met: *
* * Redistributions of source code must retain the above copyright *
* notice, this list of conditions and the following disclaimer. *
* * Redistributions in binary form must reproduce the above copyright *
* notice, this list of conditions and the following disclaimer in *
* the documentation and/or other materials provided with the *
* distribution. *
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS *
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT *
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR *
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT *
* 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. *
*
* $Id$
*/
#include "config.h"
#include "defs.h"
#include <fstream>
#include <string>
#include <sstream>
#include <cstdlib>
using namespace std;
Config::Config()
: IRCConfig(), DCConfig()
{
m_loglevel=log::error + log::warning + log::notice;
m_bSyslog=0;
}
Config::Config(const IRCConfig& c1,const DCConfig& c2, const Config& conf)
: IRCConfig(c1), DCConfig(c2)
{
m_sLogFile=conf.m_sLogFile;
m_pidfile=conf.m_pidfile;
m_loglevel=conf.m_loglevel;
m_bSyslog=m_bSyslog;
}
Config::~Config()
{
}
struct confvar
{
string name;
char type; // 's','i'
int Config::* np;
string Config::* sp;
};
const confvar varlist[]={
{"irc_server", 's', NULL, &Config::m_irc_server},
{"irc_port", 'i', &Config::m_irc_port, NULL},
{"irc_nick", 's', NULL, &Config::m_irc_nick},
{"irc_username", 's', NULL, &Config::m_irc_username},
{"irc_password", 's', NULL, &Config::m_irc_password},
{"irc_realname", 's', NULL, &Config::m_irc_realname},
{"irc_channel", 's', NULL, &Config::m_irc_channel},
{"dc_server", 's', NULL, &Config::m_dc_server},
{"dc_port", 'i', &Config::m_dc_port, NULL},
{"dc_nick", 's', NULL, &Config::m_dc_nick},
{"dc_pass", 's', NULL, &Config::m_dc_pass},
{"dc_description", 's', NULL, &Config::m_dc_description},
{"dc_speed", 's', NULL, &Config::m_dc_speed},
{"dc_speed_val", 'i', &Config::m_dc_speed_val, NULL},
{"dc_email", 's', NULL, &Config::m_dc_email},
{"dc_share_size", 's', NULL, &Config::m_dc_share_size},
{"logfile", 's', NULL, &Config::m_sLogFile},
{"pidfile", 's', NULL, &Config::m_pidfile},
{"loglevel", 'i', &Config::m_loglevel, NULL},
{"use_syslog", 'i', &Config::m_bSyslog, NULL},
{"", '\0', NULL, NULL} // terminator
};
/*!
\fn Config::ReadFromFile(const string& sConfFile)
*/
bool Config::ReadFromFile(const string& sConfFile)
{
string str;
ifstream conf(sConfFile.c_str());
if (conf.bad()) return false;
while (!conf.eof())
{
getline(conf,str);
string::size_type pos=0;
str=trim(str);
if ((pos=str.find(';'))!=string::npos)
{
str.erase(pos); // erase all after ';'
}
if (str == ""||(pos=str.find("="))==string::npos)
continue;
vars[trim(str.substr(0, pos))] =
trim(trim(trim(str.substr(pos + 1)), '\''), '\"');
};
int i;
for(i=0;varlist[i].type!='\0';i++)
{
if (vars.find(varlist[i].name)==vars.end()) continue;
switch (varlist[i].type)
{
case 's':
(this->*(varlist[i].sp))=vars[varlist[i].name];
break;
case 'i':
this->*(varlist[i].np)=(int)strtol(vars[varlist[i].name].c_str(),
(char **)NULL, 10);
break;
}
}
return true;
}
/*!
\fn Config::getLogFile()
*/
const string& Config::getLogFile()
{
return m_sLogFile;
}
<|endoftext|>
|
<commit_before>#ifndef AX_INPUT_OUTPUT_H
#define AX_INPUT_OUTPUT_H
#include <iostream>
#include "Expression.hpp"
namespace ax
{
template<class V,
typename std::enable_if<
is_VectorExpression<typename V::value_trait>::value
>::type*& = enabler>
std::ostream& operator<<(std::ostream& os, const V& vec)
{
for(auto i(0); i<V::size; ++i)
os << vec[i] << " ";
return os;
}
template<class V,
typename std::enable_if<
is_DynamicVectorExpression<typename V::value_trait>::value
>::type*& = enabler>
std::ostream& operator<<(std::ostream& os, const V& vec)
{
for(auto i(0); i<vec.size(); ++i)
os << vec[i] << " ";
return os;
}
template<class M,
typename std::enable_if<
is_MatrixExpression<typename M::value_trait>::value
>::type*& = enabler>
std::ostream& operator<<(std::ostream& os, const M& mat)
{
for(std::size_t i(0); i<M::row; ++i)
{
for(std::size_t j(0); j<M::col; ++j)
os << mat(i,j) << " ";
std::cout << std::endl;
}
return os;
}
template<class M,
typename std::enable_if<
is_DynamicMatrixExpression<typename M::value_trait>::value
>::type*& = enabler>
std::ostream& operator<<(std::ostream& os, const M& mat)
{
for(std::size_t i(0); i<mat.size_row(); ++i)
{
for(std::size_t j(0); j<mat.size_col(); ++j)
os << mat(i,j) << " ";
std::cout << std::endl;
}
return os;
}
}
#endif /*AX_INPUT_OUTPUT_H*/
<commit_msg>add VectorAVX output<commit_after>#ifndef AX_INPUT_OUTPUT_H
#define AX_INPUT_OUTPUT_H
#include <iostream>
#include <array>
#include "Expression.hpp"
namespace ax
{
template<class V,
typename std::enable_if<
is_VectorExpression<typename V::value_trait>::value
>::type*& = enabler>
std::ostream& operator<<(std::ostream& os, const V& vec)
{
for(auto i(0); i<V::size; ++i)
os << vec[i] << " ";
return os;
}
template<class V,
typename std::enable_if<
is_DynamicVectorExpression<typename V::value_trait>::value
>::type*& = enabler>
std::ostream& operator<<(std::ostream& os, const V& vec)
{
for(auto i(0); i<vec.size(); ++i)
os << vec[i] << " ";
return os;
}
template<class V,
typename std::enable_if<
is_AVXVectorExpression<typename V::value_trait>::value
>::type*& = enabler>
std::ostream& operator<<(std::ostream& os, const V& vec)
{
std::array<double, V::size> val = vec.get();
for(auto i(0); i<V::size; ++i)
os << val[i] << " ";
return os;
}
template<class M,
typename std::enable_if<
is_MatrixExpression<typename M::value_trait>::value
>::type*& = enabler>
std::ostream& operator<<(std::ostream& os, const M& mat)
{
for(std::size_t i(0); i<M::row; ++i)
{
for(std::size_t j(0); j<M::col; ++j)
os << mat(i,j) << " ";
std::cout << std::endl;
}
return os;
}
template<class M,
typename std::enable_if<
is_DynamicMatrixExpression<typename M::value_trait>::value
>::type*& = enabler>
std::ostream& operator<<(std::ostream& os, const M& mat)
{
for(std::size_t i(0); i<mat.size_row(); ++i)
{
for(std::size_t j(0); j<mat.size_col(); ++j)
os << mat(i,j) << " ";
std::cout << std::endl;
}
return os;
}
}
#endif /*AX_INPUT_OUTPUT_H*/
<|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: olestorage.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 "oox/helper/olestorage.hxx"
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/container/XNameContainer.hpp>
#include <com/sun/star/io/XInputStream.hpp>
#include <com/sun/star/io/XOutputStream.hpp>
#include "oox/helper/helper.hxx"
using ::rtl::OUString;
using ::com::sun::star::uno::Any;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::uno::Exception;
using ::com::sun::star::uno::UNO_QUERY;
using ::com::sun::star::uno::UNO_QUERY_THROW;
using ::com::sun::star::container::XNameAccess;
using ::com::sun::star::lang::XMultiServiceFactory;
using ::com::sun::star::beans::PropertyValue;
using ::com::sun::star::embed::XStorage;
using ::com::sun::star::io::XInputStream;
using ::com::sun::star::io::XOutputStream;
namespace oox {
// ============================================================================
OleStorage::OleStorage(
const Reference< XMultiServiceFactory >& rxFactory,
const Reference< XInputStream >& rxInStream,
bool bBaseStreamAccess ) :
StorageBase( rxInStream, bBaseStreamAccess )
{
OSL_ENSURE( rxFactory.is(), "OleStorage::OleStorage - missing service factory" );
// create base storage object
Sequence< Any > aArgs( 2 );
aArgs[ 0 ] <<= rxInStream;
aArgs[ 1 ] <<= true; // true = do not create a copy of the input stream
mxStorage.set( rxFactory->createInstanceWithArguments(
CREATE_OUSTRING( "com.sun.star.embed.OLESimpleStorage" ), aArgs ), UNO_QUERY );
mxElements.set( mxStorage, UNO_QUERY );
}
OleStorage::OleStorage(
const Reference< XMultiServiceFactory >& rxFactory,
const Reference< XOutputStream >& rxOutStream,
bool bBaseStreamAccess ) :
StorageBase( rxOutStream, bBaseStreamAccess )
{
OSL_ENSURE( rxFactory.is(), "OleStorage::OleStorage - missing service factory" );
(void)rxFactory; // prevent compiler warning
OSL_ENSURE( false, "OleStorage::OleStorage - not implemented" );
mxElements.set( mxStorage, UNO_QUERY );
}
OleStorage::OleStorage( const OleStorage& rParentStorage, const Reference< XNameAccess >& rxElementsAccess, const OUString& rElementName ) :
StorageBase( rParentStorage, rElementName ),
mxStorage( rParentStorage.mxStorage ),
mxElements( rxElementsAccess )
{
OSL_ENSURE( mxElements.is(), "OleStorage::OleStorage - missing elements access" );
}
OleStorage::~OleStorage()
{
}
// StorageBase interface ------------------------------------------------------
bool OleStorage::implIsStorage() const
{
if( mxStorage.is() && mxElements.is() ) try
{
/* If this is not a storage, hasElements() throws an exception. But we
do not return the result of hasElements(), because an empty storage
is a valid storage too. */
mxElements->hasElements();
return true;
}
catch( Exception& )
{
}
return false;
}
Reference< XStorage > OleStorage::implGetXStorage() const
{
OSL_ENSURE( false, "OleStorage::getXStorage - not implemented" );
return Reference< XStorage >();
}
void OleStorage::implGetElementNames( ::std::vector< OUString >& orElementNames ) const
{
Sequence< OUString > aNames;
if( mxStorage.is() ) try
{
aNames = mxElements->getElementNames();
if( aNames.getLength() > 0 )
orElementNames.insert( orElementNames.end(), aNames.getConstArray(), aNames.getConstArray() + aNames.getLength() );
}
catch( Exception& )
{
}
}
StorageRef OleStorage::implOpenSubStorage( const OUString& rElementName, bool bCreate )
{
OSL_ENSURE( !bCreate, "OleStorage::implOpenSubStorage - creating substorages not implemented" );
(void)bCreate; // prevent compiler warning
StorageRef xSubStorage;
if( mxElements.is() ) try
{
Reference< XNameAccess > xSubElements( mxElements->getByName( rElementName ), UNO_QUERY_THROW );
xSubStorage.reset( new OleStorage( *this, xSubElements, rElementName ) );
}
catch( Exception& )
{
}
return xSubStorage;
}
Reference< XInputStream > OleStorage::implOpenInputStream( const OUString& rElementName )
{
Reference< XInputStream > xInStream;
if( mxElements.is() ) try
{
xInStream.set( mxElements->getByName( rElementName ), UNO_QUERY );
}
catch( Exception& )
{
}
return xInStream;
}
Reference< XOutputStream > OleStorage::implOpenOutputStream( const OUString& rElementName )
{
Reference< XOutputStream > xOutStream;
if( mxElements.is() && (rElementName.getLength() > 0) ) try
{
(void)rElementName; // prevent compiler warning
OSL_ENSURE( false, "OleStorage::implOpenOutputStream - not implemented" );
}
catch( Exception& )
{
}
return xOutStream;
}
// ============================================================================
} // namespace oox
<commit_msg>INTEGRATION: CWS xmlfilter05 (1.2.18); FILE MERGED 2008/05/02 11:24:39 hbrinkm 1.2.18.2: RESYNC: (1.2-1.3); FILE MERGED 2008/04/17 09:45:46 dr 1.2.18.1: #i86546# #i86549# #i86560# support all file types and templates<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: olestorage.cxx,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.
*
************************************************************************/
#include "oox/helper/olestorage.hxx"
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/container/XNameContainer.hpp>
#include <com/sun/star/io/XInputStream.hpp>
#include <com/sun/star/io/XOutputStream.hpp>
#include "oox/helper/helper.hxx"
using ::rtl::OUString;
using ::com::sun::star::uno::Any;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::uno::Exception;
using ::com::sun::star::uno::UNO_QUERY;
using ::com::sun::star::uno::UNO_QUERY_THROW;
using ::com::sun::star::container::XNameAccess;
using ::com::sun::star::lang::XMultiServiceFactory;
using ::com::sun::star::beans::PropertyValue;
using ::com::sun::star::embed::XStorage;
using ::com::sun::star::io::XInputStream;
using ::com::sun::star::io::XOutputStream;
namespace oox {
// ============================================================================
OleStorage::OleStorage(
const Reference< XMultiServiceFactory >& rxFactory,
const Reference< XInputStream >& rxInStream,
bool bBaseStreamAccess ) :
StorageBase( rxInStream, bBaseStreamAccess )
{
OSL_ENSURE( rxFactory.is(), "OleStorage::OleStorage - missing service factory" );
// create base storage object
Sequence< Any > aArgs( 2 );
aArgs[ 0 ] <<= rxInStream;
aArgs[ 1 ] <<= true; // true = do not create a copy of the input stream
mxStorage.set( rxFactory->createInstanceWithArguments(
CREATE_OUSTRING( "com.sun.star.embed.OLESimpleStorage" ), aArgs ), UNO_QUERY );
mxElements.set( mxStorage, UNO_QUERY );
}
OleStorage::OleStorage(
const Reference< XMultiServiceFactory >& rxFactory,
const Reference< XOutputStream >& rxOutStream,
bool bBaseStreamAccess ) :
StorageBase( rxOutStream, bBaseStreamAccess )
{
OSL_ENSURE( rxFactory.is(), "OleStorage::OleStorage - missing service factory" );
(void)rxFactory; // prevent compiler warning
OSL_ENSURE( false, "OleStorage::OleStorage - not implemented" );
mxElements.set( mxStorage, UNO_QUERY );
}
OleStorage::OleStorage( const OleStorage& rParentStorage, const Reference< XNameAccess >& rxElementsAccess, const OUString& rElementName ) :
StorageBase( rParentStorage, rElementName ),
mxStorage( rParentStorage.mxStorage ),
mxElements( rxElementsAccess )
{
OSL_ENSURE( mxElements.is(), "OleStorage::OleStorage - missing elements access" );
}
OleStorage::~OleStorage()
{
}
// StorageBase interface ------------------------------------------------------
bool OleStorage::implIsStorage() const
{
if( mxStorage.is() && mxElements.is() ) try
{
/* If this is not a storage, hasElements() throws an exception. But we
do not return the result of hasElements(), because an empty storage
is a valid storage too. */
mxElements->hasElements();
return true;
}
catch( Exception& )
{
}
return false;
}
Reference< XStorage > OleStorage::implGetXStorage() const
{
OSL_ENSURE( false, "OleStorage::getXStorage - not implemented" );
return Reference< XStorage >();
}
void OleStorage::implGetElementNames( ::std::vector< OUString >& orElementNames ) const
{
Sequence< OUString > aNames;
if( mxElements.is() ) try
{
aNames = mxElements->getElementNames();
if( aNames.getLength() > 0 )
orElementNames.insert( orElementNames.end(), aNames.getConstArray(), aNames.getConstArray() + aNames.getLength() );
}
catch( Exception& )
{
}
}
StorageRef OleStorage::implOpenSubStorage( const OUString& rElementName, bool bCreate )
{
OSL_ENSURE( !bCreate, "OleStorage::implOpenSubStorage - creating substorages not implemented" );
(void)bCreate; // prevent compiler warning
StorageRef xSubStorage;
if( mxElements.is() ) try
{
Reference< XNameAccess > xSubElements( mxElements->getByName( rElementName ), UNO_QUERY_THROW );
xSubStorage.reset( new OleStorage( *this, xSubElements, rElementName ) );
}
catch( Exception& )
{
}
return xSubStorage;
}
Reference< XInputStream > OleStorage::implOpenInputStream( const OUString& rElementName )
{
Reference< XInputStream > xInStream;
if( mxElements.is() ) try
{
xInStream.set( mxElements->getByName( rElementName ), UNO_QUERY );
}
catch( Exception& )
{
}
return xInStream;
}
Reference< XOutputStream > OleStorage::implOpenOutputStream( const OUString& rElementName )
{
Reference< XOutputStream > xOutStream;
if( mxElements.is() && (rElementName.getLength() > 0) ) try
{
(void)rElementName; // prevent compiler warning
OSL_ENSURE( false, "OleStorage::implOpenOutputStream - not implemented" );
}
catch( Exception& )
{
}
return xOutStream;
}
// ============================================================================
} // namespace oox
<|endoftext|>
|
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "QmitkMorphologicalOperationsWidget.h"
#include <mitkProgressBar.h>
#include <mitkSliceNavigationController.h>
#include <QCheckBox>
static const char* const HelpText = "Select a segmentation above";
QmitkMorphologicalOperationsWidget::QmitkMorphologicalOperationsWidget(mitk::SliceNavigationController* timeNavigationController, QWidget* parent)
: QmitkSegmentationUtilityWidget(timeNavigationController, parent)
{
m_Controls.setupUi(this);
m_Controls.dataSelectionWidget->AddDataStorageComboBox(QmitkDataSelectionWidget::SegmentationPredicate);
m_Controls.dataSelectionWidget->SetHelpText(HelpText);
connect(m_Controls.btnClosing, SIGNAL(clicked()), this, SLOT(OnClosingButtonClicked()));
connect(m_Controls.btnOpening, SIGNAL(clicked()), this, SLOT(OnOpeningButtonClicked()));
connect(m_Controls.btnDilatation, SIGNAL(clicked()), this, SLOT(OnDilatationButtonClicked()));
connect(m_Controls.btnErosion, SIGNAL(clicked()), this, SLOT(OnErosionButtonClicked()));
connect(m_Controls.btnFillHoles, SIGNAL(clicked()), this, SLOT(OnFillHolesButtonClicked()));
connect(m_Controls.radioButtonMorphoCross, SIGNAL(clicked()), this, SLOT(OnRadioButtonsClicked()));
connect(m_Controls.radioButtonMorphoBall, SIGNAL(clicked()), this, SLOT(OnRadioButtonsClicked()));
connect(m_Controls.dataSelectionWidget, SIGNAL(SelectionChanged(unsigned int, const mitk::DataNode*)), this, SLOT(OnSelectionChanged(unsigned int, const mitk::DataNode*)));
if (m_Controls.dataSelectionWidget->GetSelection(0).IsNotNull())
this->OnSelectionChanged(0, m_Controls.dataSelectionWidget->GetSelection(0));
}
QmitkMorphologicalOperationsWidget::~QmitkMorphologicalOperationsWidget()
{
}
void QmitkMorphologicalOperationsWidget::OnSelectionChanged(unsigned int index, const mitk::DataNode* selection)
{
QmitkDataSelectionWidget* dataSelectionWidget = m_Controls.dataSelectionWidget;
mitk::DataNode::Pointer node = dataSelectionWidget->GetSelection(0);
if (node.IsNotNull())
{
m_Controls.dataSelectionWidget->SetHelpText("");
this->EnableButtons(true);
}
else
{
m_Controls.dataSelectionWidget->SetHelpText(HelpText);
this->EnableButtons(false);
}
}
void QmitkMorphologicalOperationsWidget::EnableButtons(bool enable)
{
m_Controls.btnClosing->setEnabled(enable);
m_Controls.btnDilatation->setEnabled(enable);
m_Controls.btnErosion->setEnabled(enable);
m_Controls.btnFillHoles->setEnabled(enable);
m_Controls.btnOpening->setEnabled(enable);
}
void QmitkMorphologicalOperationsWidget::OnRadioButtonsClicked()
{
bool enable = m_Controls.radioButtonMorphoBall->isChecked();
m_Controls.sliderMorphFactor->setEnabled(enable);
m_Controls.spinBoxMorphFactor->setEnabled(enable);
}
void QmitkMorphologicalOperationsWidget::OnClosingButtonClicked()
{
QApplication::setOverrideCursor(QCursor(Qt::BusyCursor));
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
QmitkDataSelectionWidget* dataSelectionWidget = m_Controls.dataSelectionWidget;
mitk::DataNode::Pointer node = dataSelectionWidget->GetSelection(0);
mitk::Image::Pointer image = static_cast<mitk::Image*>(node->GetData());
bool ball = m_Controls.radioButtonMorphoBall->isChecked();
mitk::MorphologicalOperations::StructuralElementType structuralElement = ball
? mitk::MorphologicalOperations::Ball
: mitk::MorphologicalOperations::Cross;
try
{
mitk::MorphologicalOperations::Closing(image, m_Controls.spinBoxMorphFactor->value(), structuralElement);
}
catch (const itk::ExceptionObject& exception)
{
MITK_WARN << "Exception caught: " << exception.GetDescription();
QApplication::restoreOverrideCursor();
return;
}
node->SetData(image);
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
QApplication::restoreOverrideCursor();
}
void QmitkMorphologicalOperationsWidget::OnOpeningButtonClicked()
{
QApplication::setOverrideCursor(QCursor(Qt::BusyCursor));
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
QmitkDataSelectionWidget* dataSelectionWidget = m_Controls.dataSelectionWidget;
mitk::DataNode::Pointer node = dataSelectionWidget->GetSelection(0);
mitk::Image::Pointer image = static_cast<mitk::Image*>(node->GetData());
bool ball = m_Controls.radioButtonMorphoBall->isChecked();
mitk::MorphologicalOperations::StructuralElementType structuralElement = ball
? mitk::MorphologicalOperations::Ball
: mitk::MorphologicalOperations::Cross;
try
{
mitk::MorphologicalOperations::Opening(image, m_Controls.spinBoxMorphFactor->value(), structuralElement);
}
catch (const itk::ExceptionObject& exception)
{
MITK_WARN << "Exception caught: " << exception.GetDescription();
QApplication::restoreOverrideCursor();
return;
}
node->SetData(image);
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
QApplication::restoreOverrideCursor();
}
void QmitkMorphologicalOperationsWidget::OnDilatationButtonClicked()
{
QApplication::setOverrideCursor(QCursor(Qt::BusyCursor));
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
QmitkDataSelectionWidget* dataSelectionWidget = m_Controls.dataSelectionWidget;
mitk::DataNode::Pointer node = dataSelectionWidget->GetSelection(0);
mitk::Image::Pointer image = static_cast<mitk::Image*>(node->GetData());
bool ball = m_Controls.radioButtonMorphoBall->isChecked();
mitk::MorphologicalOperations::StructuralElementType structuralElement = ball
? mitk::MorphologicalOperations::Ball
: mitk::MorphologicalOperations::Cross;
try
{
mitk::MorphologicalOperations::Dilate(image, m_Controls.spinBoxMorphFactor->value(), structuralElement);
}
catch (const itk::ExceptionObject& exception)
{
MITK_WARN << "Exception caught: " << exception.GetDescription();
QApplication::restoreOverrideCursor();
return;
}
node->SetData(image);
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
QApplication::restoreOverrideCursor();
}
void QmitkMorphologicalOperationsWidget::OnErosionButtonClicked()
{
QApplication::setOverrideCursor(QCursor(Qt::BusyCursor));
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
QmitkDataSelectionWidget* dataSelectionWidget = m_Controls.dataSelectionWidget;
mitk::DataNode::Pointer node = dataSelectionWidget->GetSelection(0);
mitk::Image::Pointer image = static_cast<mitk::Image*>(node->GetData());
bool ball = m_Controls.radioButtonMorphoBall->isChecked();
mitk::MorphologicalOperations::StructuralElementType structuralElement = ball
? mitk::MorphologicalOperations::Ball
: mitk::MorphologicalOperations::Cross;
try
{
mitk::MorphologicalOperations::Erode(image, m_Controls.spinBoxMorphFactor->value(), structuralElement);
}
catch (const itk::ExceptionObject& exception)
{
MITK_WARN << "Exception caught: " << exception.GetDescription();
QApplication::restoreOverrideCursor();
return;
}
node->SetData(image);
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
QApplication::restoreOverrideCursor();
}
void QmitkMorphologicalOperationsWidget::OnFillHolesButtonClicked()
{
QApplication::setOverrideCursor(QCursor(Qt::BusyCursor));
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
QmitkDataSelectionWidget* dataSelectionWidget = m_Controls.dataSelectionWidget;
mitk::DataNode::Pointer node = dataSelectionWidget->GetSelection(0);
mitk::Image::Pointer image = static_cast<mitk::Image*>(node->GetData());
try
{
mitk::MorphologicalOperations::FillHoles(image);
}
catch (const itk::ExceptionObject& exception)
{
MITK_WARN << "Exception caught: " << exception.GetDescription();
QApplication::restoreOverrideCursor();
return;
}
node->SetData(image);
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
QApplication::restoreOverrideCursor();
}
mitk::MorphologicalOperations::StructuralElementType QmitkMorphologicalOperationsWidget::CreateStructerElement_UI()
{
bool ball = m_Controls.radioButtonMorphoBall->isChecked();
int accum_flag = 0;
if(ball){
if(m_Controls.m_AxialCheckbox->isChecked()) accum_flag |= mitk::MorphologicalOperations::Ball_Axial;
if(m_Controls.m_SagitalCheckbox->isChecked()) accum_flag |= mitk::MorphologicalOperations::Ball_Sagital;
if(m_Controls.m_CornalCheckbox->isChecked()) accum_flag |= mitk::MorphologicalOperations::Ball_Coronal;
}else{
if(m_Controls.m_AxialCheckbox->isChecked()) accum_flag |= mitk::MorphologicalOperations::Cross_Axial;
if(m_Controls.m_SagitalCheckbox->isChecked()) accum_flag |= mitk::MorphologicalOperations::Cross_Sagital;
if(m_Controls.m_CornalCheckbox->isChecked()) accum_flag |= mitk::MorphologicalOperations::Cross_Coronal;
}
return (mitk::MorphologicalOperations::StructuralElementType)accum_flag;
}
<commit_msg>use the new added method<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "QmitkMorphologicalOperationsWidget.h"
#include <mitkProgressBar.h>
#include <mitkSliceNavigationController.h>
#include <QCheckBox>
static const char* const HelpText = "Select a segmentation above";
QmitkMorphologicalOperationsWidget::QmitkMorphologicalOperationsWidget(mitk::SliceNavigationController* timeNavigationController, QWidget* parent)
: QmitkSegmentationUtilityWidget(timeNavigationController, parent)
{
m_Controls.setupUi(this);
m_Controls.dataSelectionWidget->AddDataStorageComboBox(QmitkDataSelectionWidget::SegmentationPredicate);
m_Controls.dataSelectionWidget->SetHelpText(HelpText);
connect(m_Controls.btnClosing, SIGNAL(clicked()), this, SLOT(OnClosingButtonClicked()));
connect(m_Controls.btnOpening, SIGNAL(clicked()), this, SLOT(OnOpeningButtonClicked()));
connect(m_Controls.btnDilatation, SIGNAL(clicked()), this, SLOT(OnDilatationButtonClicked()));
connect(m_Controls.btnErosion, SIGNAL(clicked()), this, SLOT(OnErosionButtonClicked()));
connect(m_Controls.btnFillHoles, SIGNAL(clicked()), this, SLOT(OnFillHolesButtonClicked()));
connect(m_Controls.radioButtonMorphoCross, SIGNAL(clicked()), this, SLOT(OnRadioButtonsClicked()));
connect(m_Controls.radioButtonMorphoBall, SIGNAL(clicked()), this, SLOT(OnRadioButtonsClicked()));
connect(m_Controls.dataSelectionWidget, SIGNAL(SelectionChanged(unsigned int, const mitk::DataNode*)), this, SLOT(OnSelectionChanged(unsigned int, const mitk::DataNode*)));
if (m_Controls.dataSelectionWidget->GetSelection(0).IsNotNull())
this->OnSelectionChanged(0, m_Controls.dataSelectionWidget->GetSelection(0));
}
QmitkMorphologicalOperationsWidget::~QmitkMorphologicalOperationsWidget()
{
}
void QmitkMorphologicalOperationsWidget::OnSelectionChanged(unsigned int index, const mitk::DataNode* selection)
{
QmitkDataSelectionWidget* dataSelectionWidget = m_Controls.dataSelectionWidget;
mitk::DataNode::Pointer node = dataSelectionWidget->GetSelection(0);
if (node.IsNotNull())
{
m_Controls.dataSelectionWidget->SetHelpText("");
this->EnableButtons(true);
}
else
{
m_Controls.dataSelectionWidget->SetHelpText(HelpText);
this->EnableButtons(false);
}
}
void QmitkMorphologicalOperationsWidget::EnableButtons(bool enable)
{
m_Controls.btnClosing->setEnabled(enable);
m_Controls.btnDilatation->setEnabled(enable);
m_Controls.btnErosion->setEnabled(enable);
m_Controls.btnFillHoles->setEnabled(enable);
m_Controls.btnOpening->setEnabled(enable);
}
void QmitkMorphologicalOperationsWidget::OnRadioButtonsClicked()
{
bool enable = m_Controls.radioButtonMorphoBall->isChecked();
m_Controls.sliderMorphFactor->setEnabled(enable);
m_Controls.spinBoxMorphFactor->setEnabled(enable);
}
void QmitkMorphologicalOperationsWidget::OnClosingButtonClicked()
{
QApplication::setOverrideCursor(QCursor(Qt::BusyCursor));
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
QmitkDataSelectionWidget* dataSelectionWidget = m_Controls.dataSelectionWidget;
mitk::DataNode::Pointer node = dataSelectionWidget->GetSelection(0);
mitk::Image::Pointer image = static_cast<mitk::Image*>(node->GetData());
mitk::MorphologicalOperations::StructuralElementType structuralElement = CreateStructerElement_UI();
try
{
mitk::MorphologicalOperations::Closing(image, m_Controls.spinBoxMorphFactor->value(), structuralElement);
}
catch (const itk::ExceptionObject& exception)
{
MITK_WARN << "Exception caught: " << exception.GetDescription();
QApplication::restoreOverrideCursor();
return;
}
node->SetData(image);
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
QApplication::restoreOverrideCursor();
}
void QmitkMorphologicalOperationsWidget::OnOpeningButtonClicked()
{
QApplication::setOverrideCursor(QCursor(Qt::BusyCursor));
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
QmitkDataSelectionWidget* dataSelectionWidget = m_Controls.dataSelectionWidget;
mitk::DataNode::Pointer node = dataSelectionWidget->GetSelection(0);
mitk::Image::Pointer image = static_cast<mitk::Image*>(node->GetData());
mitk::MorphologicalOperations::StructuralElementType structuralElement = CreateStructerElement_UI();
try
{
mitk::MorphologicalOperations::Opening(image, m_Controls.spinBoxMorphFactor->value(), structuralElement);
}
catch (const itk::ExceptionObject& exception)
{
MITK_WARN << "Exception caught: " << exception.GetDescription();
QApplication::restoreOverrideCursor();
return;
}
node->SetData(image);
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
QApplication::restoreOverrideCursor();
}
void QmitkMorphologicalOperationsWidget::OnDilatationButtonClicked()
{
QApplication::setOverrideCursor(QCursor(Qt::BusyCursor));
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
QmitkDataSelectionWidget* dataSelectionWidget = m_Controls.dataSelectionWidget;
mitk::DataNode::Pointer node = dataSelectionWidget->GetSelection(0);
mitk::Image::Pointer image = static_cast<mitk::Image*>(node->GetData());
mitk::MorphologicalOperations::StructuralElementType structuralElement = this->CreateStructerElement_UI();
try
{
mitk::MorphologicalOperations::Dilate(image, m_Controls.spinBoxMorphFactor->value(), structuralElement);
}
catch (const itk::ExceptionObject& exception)
{
MITK_WARN << "Exception caught: " << exception.GetDescription();
QApplication::restoreOverrideCursor();
return;
}
node->SetData(image);
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
QApplication::restoreOverrideCursor();
}
void QmitkMorphologicalOperationsWidget::OnErosionButtonClicked()
{
QApplication::setOverrideCursor(QCursor(Qt::BusyCursor));
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
QmitkDataSelectionWidget* dataSelectionWidget = m_Controls.dataSelectionWidget;
mitk::DataNode::Pointer node = dataSelectionWidget->GetSelection(0);
mitk::Image::Pointer image = static_cast<mitk::Image*>(node->GetData());
mitk::MorphologicalOperations::StructuralElementType structuralElement = CreateStructerElement_UI();
try
{
mitk::MorphologicalOperations::Erode(image, m_Controls.spinBoxMorphFactor->value(), structuralElement);
}
catch (const itk::ExceptionObject& exception)
{
MITK_WARN << "Exception caught: " << exception.GetDescription();
QApplication::restoreOverrideCursor();
return;
}
node->SetData(image);
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
QApplication::restoreOverrideCursor();
}
void QmitkMorphologicalOperationsWidget::OnFillHolesButtonClicked()
{
QApplication::setOverrideCursor(QCursor(Qt::BusyCursor));
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
QmitkDataSelectionWidget* dataSelectionWidget = m_Controls.dataSelectionWidget;
mitk::DataNode::Pointer node = dataSelectionWidget->GetSelection(0);
mitk::Image::Pointer image = static_cast<mitk::Image*>(node->GetData());
try
{
mitk::MorphologicalOperations::FillHoles(image);
}
catch (const itk::ExceptionObject& exception)
{
MITK_WARN << "Exception caught: " << exception.GetDescription();
QApplication::restoreOverrideCursor();
return;
}
node->SetData(image);
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
QApplication::restoreOverrideCursor();
}
mitk::MorphologicalOperations::StructuralElementType QmitkMorphologicalOperationsWidget::CreateStructerElement_UI()
{
bool ball = m_Controls.radioButtonMorphoBall->isChecked();
int accum_flag = 0;
if(ball){
if(m_Controls.m_AxialCheckbox->isChecked()) accum_flag |= mitk::MorphologicalOperations::Ball_Axial;
if(m_Controls.m_SagitalCheckbox->isChecked()) accum_flag |= mitk::MorphologicalOperations::Ball_Sagital;
if(m_Controls.m_CornalCheckbox->isChecked()) accum_flag |= mitk::MorphologicalOperations::Ball_Coronal;
}else{
if(m_Controls.m_AxialCheckbox->isChecked()) accum_flag |= mitk::MorphologicalOperations::Cross_Axial;
if(m_Controls.m_SagitalCheckbox->isChecked()) accum_flag |= mitk::MorphologicalOperations::Cross_Sagital;
if(m_Controls.m_CornalCheckbox->isChecked()) accum_flag |= mitk::MorphologicalOperations::Cross_Coronal;
}
return (mitk::MorphologicalOperations::StructuralElementType)accum_flag;
}
<|endoftext|>
|
<commit_before>//=============================================================================================================
/**
* @file annotationview.cpp
* @author Lorenz Esch <lesch@mgh.harvard.edu>;
* Gabriel Motta <gbmotta@mgh.harvard.edu>
* @since 0.1.0
* @date March, 2020
*
* @section LICENSE
*
* Copyright (C) 2020, Christoph Dinh, Lorenz Esch, Gabriel Motta. 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 MNE-CPP authors 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.
*
*
* @brief Definition of the AnnotationView Class.
*
*/
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include "annotationview.h"
#include "ui_annotationview.h"
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================
#include <QDebug>
#include <QMap>
#include <QToolBar>
#include <QColorDialog>
#include <QFileDialog>
#include <QKeyEvent>
//=============================================================================================================
// Eigen INCLUDES
//=============================================================================================================
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================
AnnotationView::AnnotationView()
: ui(new Ui::EventWindowDockWidget)
, m_iCheckState(0)
, m_iLastSampClicked(0)
, m_pAnnModel(Q_NULLPTR)
, m_pColordialog(new QColorDialog(this))
{
ui->setupUi(this);
ui->m_comboBox_filterTypes->addItem("All");
ui->m_comboBox_filterTypes->addItem("0");
ui->m_comboBox_filterTypes->setCurrentText("All");
onDataChanged();
}
//=============================================================================================================
void AnnotationView::initMSVCSettings()
{
//Model
ui->m_tableView_eventTableView->setModel(m_pAnnModel.data());
connect(m_pAnnModel.data(),&ANSHAREDLIB::AnnotationModel::dataChanged,
this, &AnnotationView::onDataChanged, Qt::UniqueConnection);
//Delegate
m_pAnnDelegate = QSharedPointer<AnnotationDelegate>(new AnnotationDelegate(this));
ui->m_tableView_eventTableView->setItemDelegate(m_pAnnDelegate.data());
connect(m_pAnnDelegate.data(), &AnnotationDelegate::sampleValueChanged,
this, &AnnotationView::realTimeDataSample, Qt::UniqueConnection);
connect(m_pAnnDelegate.data(), &AnnotationDelegate::timeValueChanged,
this, &AnnotationView::realTimeDataTime, Qt::UniqueConnection);
ui->m_tableView_eventTableView->resizeColumnsToContents();
ui->m_tableView_eventTableView->adjustSize();
ui->m_tableView_eventTableView->setSelectionMode(QAbstractItemView::ExtendedSelection);
}
//=============================================================================================================
void AnnotationView::initGUIFunctionality()
{
//'Activate annotations' checkbox
connect(ui->m_checkBox_activateEvents, &QCheckBox::stateChanged,
this, &AnnotationView::onActiveEventsChecked, Qt::UniqueConnection);
//'Show selected annotation' checkbox
connect(ui->m_checkBox_showSelectedEventsOnly,&QCheckBox::stateChanged,
this, &AnnotationView::onSelectedEventsChecked, Qt::UniqueConnection);
connect(ui->m_tableView_eventTableView->selectionModel(), &QItemSelectionModel::selectionChanged,
this, &AnnotationView::onCurrentSelectedChanged, Qt::UniqueConnection);
//Annotation types combo box
//ui->m_comboBox_filterTypes->addItems(m_pAnnModel->getEventTypeList());
connect(ui->m_comboBox_filterTypes, &QComboBox::currentTextChanged,
m_pAnnModel.data(), &ANSHAREDLIB::AnnotationModel::setEventFilterType, Qt::UniqueConnection);
connect(m_pAnnModel.data(), &ANSHAREDLIB::AnnotationModel::updateEventTypes,
this, &AnnotationView::updateComboBox, Qt::UniqueConnection);
//'Remove annotations' button
QToolBar *toolBar = new QToolBar(this);
toolBar->setOrientation(Qt::Vertical);
toolBar->setMovable(false);
QAction* removeEvent = new QAction("Remove", this);
removeEvent->setStatusTip(tr("Remove an annotation from the list"));
toolBar->addAction(removeEvent);
connect(removeEvent, &QAction::triggered,
this, &AnnotationView::removeAnnotationfromModel, Qt::UniqueConnection);
ui->m_gridLayout_Main->addWidget(toolBar,1,1,1,1);
//Add type button
connect(ui->m_pushButton_addEventType, &QPushButton::clicked,
this, &AnnotationView::addNewAnnotationType, Qt::UniqueConnection);
connect(ui->m_pushButtonSave, &QPushButton::clicked,
this, &AnnotationView::onSaveButton, Qt::UniqueConnection);
//connect(ui->m_tableView_eventTableView.)
}
//=============================================================================================================
void AnnotationView::onActiveEventsChecked(int iCheckBoxState)
{
//qDebug() << "onActiveEventsChecked" << iCheckBoxState;
m_iCheckState = iCheckBoxState;
emit activeEventsChecked(m_iCheckState);
}
//=============================================================================================================
void AnnotationView::updateComboBox(const QString ¤tAnnotationType)
{
ui->m_comboBox_filterTypes->clear();
ui->m_comboBox_filterTypes->addItem("All");
ui->m_comboBox_filterTypes->addItems(m_pAnnModel->getEventTypeList());
// if(m_pAnnModel->getEventTypeList().contains(currentAnnotationType))
// ui->m_comboBox_filterTypes->setCurrentText(currentAnnotationType);
m_pAnnModel->setLastType(currentAnnotationType.toInt());
emit triggerRedraw();
}
//=============================================================================================================
void AnnotationView::addAnnotationToModel(const int iSample)
{
//qDebug() << "AnnotationView::addAnnotationToModel -- Here";
m_iLastSampClicked = iSample;
m_pAnnModel->setSamplePos(m_iLastSampClicked);
m_pAnnModel->insertRow(0, QModelIndex());
emit triggerRedraw();
}
//=============================================================================================================
void AnnotationView::setModel(QSharedPointer<ANSHAREDLIB::AnnotationModel> pAnnModel)
{
m_pAnnModel = pAnnModel;
initMSVCSettings();
initGUIFunctionality();
onDataChanged();
}
//=============================================================================================================
void AnnotationView::onDataChanged()
{
//qDebug() << "AnnotationView::onDataChanged";
ui->m_tableView_eventTableView->viewport()->update();
ui->m_tableView_eventTableView->viewport()->repaint();
emit triggerRedraw();
}
//=============================================================================================================
void AnnotationView::passFiffParams(int iFirst,int iLast,float fFreq)
{
m_pAnnModel->setFirstLastSample(iFirst, iLast);
m_pAnnModel->setSampleFreq(fFreq);
}
//=============================================================================================================
void AnnotationView::removeAnnotationfromModel()
{
QModelIndexList indexList = ui->m_tableView_eventTableView->selectionModel()->selectedIndexes();
for(int i = 0; i<indexList.size(); i++)
m_pAnnModel->removeRow(indexList.at(i).row() /*- i*/);
emit triggerRedraw();
}
//=============================================================================================================
void AnnotationView::addNewAnnotationType()
{
m_pAnnModel->addNewAnnotationType(QString().number(ui->m_spinBox_addEventType->value()), m_pColordialog->getColor(Qt::black, this));
//m_pAnnModel->setEventFilterType(QString().number(ui->m_spinBox_addEventType->value()));
emit triggerRedraw();
}
//=============================================================================================================
void AnnotationView::onSelectedEventsChecked(int iCheckBoxState)
{
m_iCheckSelectedState = iCheckBoxState;
m_pAnnModel->setShowSelected(m_iCheckSelectedState);
//qDebug() << ui->m_tableView_eventTableView->selectionModel()->currentIndex().row();
//ui->m_tableView_eventTableView->selectionModel()->sle
//m_pAnnModel
emit triggerRedraw();
}
//=============================================================================================================
void AnnotationView::disconnectFromModel()
{
disconnect(m_pAnnModel.data(),&ANSHAREDLIB::AnnotationModel::dataChanged,
this, &AnnotationView::onDataChanged);
disconnect(ui->m_checkBox_activateEvents, &QCheckBox::stateChanged,
this, &AnnotationView::onActiveEventsChecked);
disconnect(ui->m_checkBox_showSelectedEventsOnly,&QCheckBox::stateChanged,
this, &AnnotationView::onSelectedEventsChecked);
disconnect(ui->m_comboBox_filterTypes, &QComboBox::currentTextChanged,
m_pAnnModel.data(), &ANSHAREDLIB::AnnotationModel::setEventFilterType);
disconnect(m_pAnnModel.data(), &ANSHAREDLIB::AnnotationModel::updateEventTypes,
this, &AnnotationView::updateComboBox);
disconnect(ui->m_pushButton_addEventType, &QPushButton::clicked,
this, &AnnotationView::addNewAnnotationType);
}
//=============================================================================================================
void AnnotationView::onCurrentSelectedChanged()
{
m_pAnnModel->clearSelected();
//qDebug() << "AnnotationView::onCurrentSelectedChanged";
//qDebug() << ui->m_tableView_eventTableView->selectionModel()->currentIndex().row();
m_pAnnModel->setSelectedAnn(ui->m_tableView_eventTableView->selectionModel()->currentIndex().row());
// m_pAnnModel->setSelectedAnn(ui->m_tableView_eventTableView
// qDebug() << ui->m_tableView_eventTableView->selectionModel()->selectedIndexes();
for (int i = 0; i < ui->m_tableView_eventTableView->selectionModel()->selectedRows().size(); i++) {
// qDebug() << ui->m_tableView_eventTableView->selectionModel()->selectedRows().at(i).row();
m_pAnnModel->appendSelected(ui->m_tableView_eventTableView->selectionModel()->selectedRows().at(i).row());
}
}
//=============================================================================================================
void AnnotationView::onSaveButton()
{
#ifdef WASMBUILD
m_pAnnModel->saveToFile("");
#else
QString fileName = QFileDialog::getSaveFileName(Q_NULLPTR,
tr("Save Annotations"), "",
tr("Event file (*.eve);;All Files (*)"));
if (fileName.isEmpty()) {
return;
}
qInfo() << "AnnotationView::onSaveButton";
m_pAnnModel->saveToFile(fileName);
#endif
}
//=============================================================================================================
void AnnotationView::keyPressEvent(QKeyEvent* event)
{
if(event->key() == Qt::Key_Delete) {
//qDebug() << "[AnnotationView::keyPressEvent] -- Qt::Key_Delete";
this->removeAnnotationfromModel();
}
}
//=============================================================================================================
void AnnotationView::realTimeDataSample(int iValue)
{
m_pAnnModel->setSelectedAnn(ui->m_tableView_eventTableView->selectionModel()->currentIndex().row());
//qDebug() << "AnnotationView::realTimeData --" << iValue;
m_pAnnModel->updateFilteredSample(iValue);
this->onDataChanged();
}
//=============================================================================================================
void AnnotationView::realTimeDataTime(double dValue)
{
m_pAnnModel->setSelectedAnn(ui->m_tableView_eventTableView->selectionModel()->currentIndex().row());
//qDebug() << "AnnotationView::realTimeDataTime" << dValue;
dValue *= m_pAnnModel->getFreq();
//qDebug() << "AnnotationView::realTimeDataTime" << dValue;
int t_iSample = static_cast<int>(dValue);
m_pAnnModel->updateFilteredSample(t_iSample);
this->onDataChanged();
}
<commit_msg>ENH: fix deleting annotations when multiple selected<commit_after>//=============================================================================================================
/**
* @file annotationview.cpp
* @author Lorenz Esch <lesch@mgh.harvard.edu>;
* Gabriel Motta <gbmotta@mgh.harvard.edu>
* @since 0.1.0
* @date March, 2020
*
* @section LICENSE
*
* Copyright (C) 2020, Christoph Dinh, Lorenz Esch, Gabriel Motta. 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 MNE-CPP authors 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.
*
*
* @brief Definition of the AnnotationView Class.
*
*/
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include "annotationview.h"
#include "ui_annotationview.h"
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================
#include <QDebug>
#include <QMap>
#include <QToolBar>
#include <QColorDialog>
#include <QFileDialog>
#include <QKeyEvent>
//=============================================================================================================
// Eigen INCLUDES
//=============================================================================================================
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================
AnnotationView::AnnotationView()
: ui(new Ui::EventWindowDockWidget)
, m_iCheckState(0)
, m_iLastSampClicked(0)
, m_pAnnModel(Q_NULLPTR)
, m_pColordialog(new QColorDialog(this))
{
ui->setupUi(this);
ui->m_comboBox_filterTypes->addItem("All");
ui->m_comboBox_filterTypes->addItem("0");
ui->m_comboBox_filterTypes->setCurrentText("All");
onDataChanged();
}
//=============================================================================================================
void AnnotationView::initMSVCSettings()
{
//Model
ui->m_tableView_eventTableView->setModel(m_pAnnModel.data());
connect(m_pAnnModel.data(),&ANSHAREDLIB::AnnotationModel::dataChanged,
this, &AnnotationView::onDataChanged, Qt::UniqueConnection);
//Delegate
m_pAnnDelegate = QSharedPointer<AnnotationDelegate>(new AnnotationDelegate(this));
ui->m_tableView_eventTableView->setItemDelegate(m_pAnnDelegate.data());
connect(m_pAnnDelegate.data(), &AnnotationDelegate::sampleValueChanged,
this, &AnnotationView::realTimeDataSample, Qt::UniqueConnection);
connect(m_pAnnDelegate.data(), &AnnotationDelegate::timeValueChanged,
this, &AnnotationView::realTimeDataTime, Qt::UniqueConnection);
ui->m_tableView_eventTableView->resizeColumnsToContents();
ui->m_tableView_eventTableView->adjustSize();
ui->m_tableView_eventTableView->setSelectionMode(QAbstractItemView::ExtendedSelection);
}
//=============================================================================================================
void AnnotationView::initGUIFunctionality()
{
//'Activate annotations' checkbox
connect(ui->m_checkBox_activateEvents, &QCheckBox::stateChanged,
this, &AnnotationView::onActiveEventsChecked, Qt::UniqueConnection);
//'Show selected annotation' checkbox
connect(ui->m_checkBox_showSelectedEventsOnly,&QCheckBox::stateChanged,
this, &AnnotationView::onSelectedEventsChecked, Qt::UniqueConnection);
connect(ui->m_tableView_eventTableView->selectionModel(), &QItemSelectionModel::selectionChanged,
this, &AnnotationView::onCurrentSelectedChanged, Qt::UniqueConnection);
//Annotation types combo box
//ui->m_comboBox_filterTypes->addItems(m_pAnnModel->getEventTypeList());
connect(ui->m_comboBox_filterTypes, &QComboBox::currentTextChanged,
m_pAnnModel.data(), &ANSHAREDLIB::AnnotationModel::setEventFilterType, Qt::UniqueConnection);
connect(m_pAnnModel.data(), &ANSHAREDLIB::AnnotationModel::updateEventTypes,
this, &AnnotationView::updateComboBox, Qt::UniqueConnection);
//'Remove annotations' button
QToolBar *toolBar = new QToolBar(this);
toolBar->setOrientation(Qt::Vertical);
toolBar->setMovable(false);
QAction* removeEvent = new QAction("Remove", this);
removeEvent->setStatusTip(tr("Remove an annotation from the list"));
toolBar->addAction(removeEvent);
connect(removeEvent, &QAction::triggered,
this, &AnnotationView::removeAnnotationfromModel, Qt::UniqueConnection);
ui->m_gridLayout_Main->addWidget(toolBar,1,1,1,1);
//Add type button
connect(ui->m_pushButton_addEventType, &QPushButton::clicked,
this, &AnnotationView::addNewAnnotationType, Qt::UniqueConnection);
connect(ui->m_pushButtonSave, &QPushButton::clicked,
this, &AnnotationView::onSaveButton, Qt::UniqueConnection);
//connect(ui->m_tableView_eventTableView.)
}
//=============================================================================================================
void AnnotationView::onActiveEventsChecked(int iCheckBoxState)
{
//qDebug() << "onActiveEventsChecked" << iCheckBoxState;
m_iCheckState = iCheckBoxState;
emit activeEventsChecked(m_iCheckState);
}
//=============================================================================================================
void AnnotationView::updateComboBox(const QString ¤tAnnotationType)
{
ui->m_comboBox_filterTypes->clear();
ui->m_comboBox_filterTypes->addItem("All");
ui->m_comboBox_filterTypes->addItems(m_pAnnModel->getEventTypeList());
// if(m_pAnnModel->getEventTypeList().contains(currentAnnotationType))
// ui->m_comboBox_filterTypes->setCurrentText(currentAnnotationType);
m_pAnnModel->setLastType(currentAnnotationType.toInt());
emit triggerRedraw();
}
//=============================================================================================================
void AnnotationView::addAnnotationToModel(const int iSample)
{
//qDebug() << "AnnotationView::addAnnotationToModel -- Here";
m_iLastSampClicked = iSample;
m_pAnnModel->setSamplePos(m_iLastSampClicked);
m_pAnnModel->insertRow(0, QModelIndex());
emit triggerRedraw();
}
//=============================================================================================================
void AnnotationView::setModel(QSharedPointer<ANSHAREDLIB::AnnotationModel> pAnnModel)
{
m_pAnnModel = pAnnModel;
initMSVCSettings();
initGUIFunctionality();
onDataChanged();
}
//=============================================================================================================
void AnnotationView::onDataChanged()
{
//qDebug() << "AnnotationView::onDataChanged";
ui->m_tableView_eventTableView->viewport()->update();
ui->m_tableView_eventTableView->viewport()->repaint();
emit triggerRedraw();
}
//=============================================================================================================
void AnnotationView::passFiffParams(int iFirst,int iLast,float fFreq)
{
m_pAnnModel->setFirstLastSample(iFirst, iLast);
m_pAnnModel->setSampleFreq(fFreq);
}
//=============================================================================================================
void AnnotationView::removeAnnotationfromModel()
{
ui->m_tableView_eventTableView->setSelectionMode(QAbstractItemView::SingleSelection);
//QModelIndexList indexList = ui->m_tableView_eventTableView->selectionModel()->selectedIndexes();
QModelIndexList indexList = ui->m_tableView_eventTableView->selectionModel()->selectedRows();
qDebug() << indexList;
int iLastDeleted();
for(int i = 0; i<indexList.size(); i++) {
//qDebug() << "Index List" << indexList.at(i).row();
//qDebug() << "With Modifier" << indexList.at(i).row() - i;
m_pAnnModel->removeRow(indexList.at(i).row() - i);
}
emit triggerRedraw();
ui->m_tableView_eventTableView->setSelectionMode(QAbstractItemView::ExtendedSelection);
}
//=============================================================================================================
void AnnotationView::addNewAnnotationType()
{
m_pAnnModel->addNewAnnotationType(QString().number(ui->m_spinBox_addEventType->value()), m_pColordialog->getColor(Qt::black, this));
//m_pAnnModel->setEventFilterType(QString().number(ui->m_spinBox_addEventType->value()));
emit triggerRedraw();
}
//=============================================================================================================
void AnnotationView::onSelectedEventsChecked(int iCheckBoxState)
{
m_iCheckSelectedState = iCheckBoxState;
m_pAnnModel->setShowSelected(m_iCheckSelectedState);
//qDebug() << ui->m_tableView_eventTableView->selectionModel()->currentIndex().row();
//ui->m_tableView_eventTableView->selectionModel()->sle
//m_pAnnModel
emit triggerRedraw();
}
//=============================================================================================================
void AnnotationView::disconnectFromModel()
{
disconnect(m_pAnnModel.data(),&ANSHAREDLIB::AnnotationModel::dataChanged,
this, &AnnotationView::onDataChanged);
disconnect(ui->m_checkBox_activateEvents, &QCheckBox::stateChanged,
this, &AnnotationView::onActiveEventsChecked);
disconnect(ui->m_checkBox_showSelectedEventsOnly,&QCheckBox::stateChanged,
this, &AnnotationView::onSelectedEventsChecked);
disconnect(ui->m_comboBox_filterTypes, &QComboBox::currentTextChanged,
m_pAnnModel.data(), &ANSHAREDLIB::AnnotationModel::setEventFilterType);
disconnect(m_pAnnModel.data(), &ANSHAREDLIB::AnnotationModel::updateEventTypes,
this, &AnnotationView::updateComboBox);
disconnect(ui->m_pushButton_addEventType, &QPushButton::clicked,
this, &AnnotationView::addNewAnnotationType);
}
//=============================================================================================================
void AnnotationView::onCurrentSelectedChanged()
{
m_pAnnModel->clearSelected();
//qDebug() << "AnnotationView::onCurrentSelectedChanged";
//qDebug() << ui->m_tableView_eventTableView->selectionModel()->currentIndex().row();
m_pAnnModel->setSelectedAnn(ui->m_tableView_eventTableView->selectionModel()->currentIndex().row());
// m_pAnnModel->setSelectedAnn(ui->m_tableView_eventTableView
// qDebug() << ui->m_tableView_eventTableView->selectionModel()->selectedIndexes();
for (int i = 0; i < ui->m_tableView_eventTableView->selectionModel()->selectedRows().size(); i++) {
// qDebug() << ui->m_tableView_eventTableView->selectionModel()->selectedRows().at(i).row();
m_pAnnModel->appendSelected(ui->m_tableView_eventTableView->selectionModel()->selectedRows().at(i).row());
}
}
//=============================================================================================================
void AnnotationView::onSaveButton()
{
#ifdef WASMBUILD
m_pAnnModel->saveToFile("");
#else
QString fileName = QFileDialog::getSaveFileName(Q_NULLPTR,
tr("Save Annotations"), "",
tr("Event file (*.eve);;All Files (*)"));
if (fileName.isEmpty()) {
return;
}
qInfo() << "AnnotationView::onSaveButton";
m_pAnnModel->saveToFile(fileName);
#endif
}
//=============================================================================================================
void AnnotationView::keyPressEvent(QKeyEvent* event)
{
if(event->key() == Qt::Key_Delete) {
//qDebug() << "[AnnotationView::keyPressEvent] -- Qt::Key_Delete";
this->removeAnnotationfromModel();
}
}
//=============================================================================================================
void AnnotationView::realTimeDataSample(int iValue)
{
m_pAnnModel->setSelectedAnn(ui->m_tableView_eventTableView->selectionModel()->currentIndex().row());
//qDebug() << "AnnotationView::realTimeData --" << iValue;
m_pAnnModel->updateFilteredSample(iValue);
this->onDataChanged();
}
//=============================================================================================================
void AnnotationView::realTimeDataTime(double dValue)
{
m_pAnnModel->setSelectedAnn(ui->m_tableView_eventTableView->selectionModel()->currentIndex().row());
//qDebug() << "AnnotationView::realTimeDataTime" << dValue;
dValue *= m_pAnnModel->getFreq();
//qDebug() << "AnnotationView::realTimeDataTime" << dValue;
int t_iSample = static_cast<int>(dValue);
m_pAnnModel->updateFilteredSample(t_iSample);
this->onDataChanged();
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012-2016 Daniele Bartolini and individual contributors.
* License: https://github.com/taylor001/crown/blob/master/LICENSE
*/
#include "device.h"
#include "array.h"
#include "config.h"
#include "input_manager.h"
#include "log.h"
#include "lua_environment.h"
#include "material_manager.h"
#include "memory.h"
#include "os.h"
#include "resource_loader.h"
#include "resource_manager.h"
#include "resource_package.h"
#include "types.h"
#include "world.h"
#include "filesystem.h"
#include "path.h"
#include "disk_filesystem.h"
#include "physics.h"
#include "audio.h"
#include "profiler.h"
#include "console_server.h"
#include "input_device.h"
#include "sjson.h"
#include "map.h"
#include "vector3.h"
#if CROWN_PLATFORM_ANDROID
#include "apk_filesystem.h"
#endif // CROWN_PLATFORM_ANDROID
#define MAX_SUBSYSTEMS_HEAP 8 * 1024 * 1024
namespace crown
{
Device::Device(const DeviceOptions& opts)
: _allocator(default_allocator(), MAX_SUBSYSTEMS_HEAP)
, _width(0)
, _height(0)
, _mouse_curr_x(0)
, _mouse_curr_y(0)
, _mouse_last_x(0)
, _mouse_last_y(0)
, _is_init(false)
, _is_running(false)
, _is_paused(false)
, _frame_count(0)
, _last_time(0)
, _current_time(0)
, _last_delta_time(0.0f)
, _time_since_start(0.0)
, _device_options(opts)
, _bundle_filesystem(NULL)
, _boot_package_id(uint64_t(0))
, _boot_script_id(uint64_t(0))
, _boot_package(NULL)
, _lua_environment(NULL)
, _resource_loader(NULL)
, _resource_manager(NULL)
, _input_manager(NULL)
, _shader_manager(NULL)
, _material_manager(NULL)
, _unit_manager(NULL)
, _worlds(default_allocator())
, _bgfx_allocator(default_allocator())
{
}
void Device::init()
{
// Initialize
CE_LOGI("Initializing Crown Engine %s...", version());
profiler_globals::init();
#if CROWN_PLATFORM_ANDROID
_bundle_filesystem = CE_NEW(_allocator, ApkFilesystem)(const_cast<AAssetManager*>(_device_options.asset_manager()));
#else
_bundle_filesystem = CE_NEW(_allocator, DiskFilesystem)(_device_options.bundle_dir());
#endif // CROWN_PLATFORM_ANDROID
_resource_loader = CE_NEW(_allocator, ResourceLoader)(*_bundle_filesystem);
_resource_manager = CE_NEW(_allocator, ResourceManager)(*_resource_loader);
read_config();
bgfx::init(bgfx::RendererType::Count
, BGFX_PCI_ID_NONE
, 0
, &_bgfx_callback
, &_bgfx_allocator
);
_shader_manager = CE_NEW(_allocator, ShaderManager)(default_allocator());
_material_manager = CE_NEW(_allocator, MaterialManager)(default_allocator(), *_resource_manager);
_input_manager = CE_NEW(_allocator, InputManager)(default_allocator());
_unit_manager = CE_NEW(_allocator, UnitManager)(default_allocator());
audio_globals::init();
physics_globals::init();
_boot_package = create_resource_package(_boot_package_id);
_boot_package->load();
_boot_package->flush();
_lua_environment = CE_NEW(_allocator, LuaEnvironment)();
_lua_environment->load_libs();
_lua_environment->execute((LuaResource*)_resource_manager->get(SCRIPT_TYPE, _boot_script_id));
_lua_environment->call_global("init", 0);
_is_init = true;
_is_running = true;
_last_time = os::clocktime();
CE_LOGD("Engine initialized");
}
void Device::shutdown()
{
CE_ASSERT(_is_init, "Engine is not initialized");
_is_running = false;
_is_init = false;
_lua_environment->call_global("shutdown", 0);
CE_DELETE(_allocator, _lua_environment);
_boot_package->unload();
destroy_resource_package(*_boot_package);
physics_globals::shutdown();
audio_globals::shutdown();
CE_DELETE(_allocator, _unit_manager);
CE_DELETE(_allocator, _input_manager);
CE_DELETE(_allocator, _material_manager);
CE_DELETE(_allocator, _shader_manager);
CE_DELETE(_allocator, _resource_manager);
CE_DELETE(_allocator, _resource_loader);
CE_DELETE(_allocator, _bundle_filesystem);
bgfx::shutdown();
profiler_globals::shutdown();
_allocator.clear();
}
void Device::quit()
{
_is_running = false;
}
void Device::pause()
{
_is_paused = true;
CE_LOGI("Engine paused.");
}
void Device::unpause()
{
_is_paused = false;
CE_LOGI("Engine unpaused.");
}
void Device::resolution(uint16_t& width, uint16_t& height)
{
width = _width;
height = _height;
}
bool Device::is_running() const
{
return _is_running;
}
uint64_t Device::frame_count() const
{
return _frame_count;
}
float Device::last_delta_time() const
{
return _last_delta_time;
}
double Device::time_since_start() const
{
return _time_since_start;
}
void Device::update()
{
while (!process_events() && _is_running)
{
_current_time = os::clocktime();
const int64_t time = _current_time - _last_time;
_last_time = _current_time;
const double freq = (double) os::clockfrequency();
_last_delta_time = time * (1.0 / freq);
_time_since_start += _last_delta_time;
profiler_globals::clear();
console_server_globals::update();
RECORD_FLOAT("device.dt", _last_delta_time);
RECORD_FLOAT("device.fps", 1.0f/_last_delta_time);
if (!_is_paused)
{
_resource_manager->complete_requests();
_lua_environment->call_global("update", 1, ARGUMENT_FLOAT, last_delta_time());
_lua_environment->call_global("render", 1, ARGUMENT_FLOAT, last_delta_time());
}
_input_manager->update();
const bgfx::Stats* stats = bgfx::getStats();
RECORD_FLOAT("bgfx.gpu_time", double(stats->gpuTimeEnd - stats->gpuTimeBegin)*1000.0/stats->gpuTimerFreq);
RECORD_FLOAT("bgfx.cpu_time", double(stats->cpuTimeEnd - stats->cpuTimeBegin)*1000.0/stats->cpuTimerFreq);
bgfx::frame();
profiler_globals::flush();
_lua_environment->clear_temporaries();
_frame_count++;
}
}
void Device::render_world(World& world, CameraInstance camera)
{
world.render(camera);
}
World* Device::create_world()
{
World* w = CE_NEW(default_allocator(), World)(default_allocator()
, *_resource_manager
, *_lua_environment
, *_material_manager
, *_unit_manager
);
array::push_back(_worlds, w);
return w;
}
void Device::destroy_world(World& w)
{
for (uint32_t i = 0, n = array::size(_worlds); i < n; ++i)
{
if (&w == _worlds[i])
{
CE_DELETE(default_allocator(), &w);
_worlds[i] = _worlds[n - 1];
array::pop_back(_worlds);
return;
}
}
CE_ASSERT(false, "Bad world");
}
ResourcePackage* Device::create_resource_package(StringId64 id)
{
return CE_NEW(default_allocator(), ResourcePackage)(id, *_resource_manager);
}
void Device::destroy_resource_package(ResourcePackage& rp)
{
CE_DELETE(default_allocator(), &rp);
}
void Device::reload(StringId64 type, StringId64 name)
{
const void* old_resource = _resource_manager->get(type, name);
_resource_manager->reload(type, name);
const void* new_resource = _resource_manager->get(type, name);
if (type == SCRIPT_TYPE)
{
_lua_environment->execute((const LuaResource*)new_resource);
}
}
ResourceManager* Device::resource_manager()
{
return _resource_manager;
}
LuaEnvironment* Device::lua_environment()
{
return _lua_environment;
}
InputManager* Device::input_manager()
{
return _input_manager;
}
ShaderManager* Device::shader_manager()
{
return _shader_manager;
}
MaterialManager* Device::material_manager()
{
return _material_manager;
}
UnitManager* Device::unit_manager()
{
return _unit_manager;
}
bool Device::process_events()
{
OsEvent event;
bool exit = false;
InputManager* im = _input_manager;
const int16_t dt_x = _mouse_curr_x - _mouse_last_x;
const int16_t dt_y = _mouse_curr_y - _mouse_last_y;
im->mouse()->set_axis(MouseAxis::CURSOR_DELTA, vector3(dt_x, dt_y, 0.0f));
_mouse_last_x = _mouse_curr_x;
_mouse_last_y = _mouse_curr_y;
while(next_event(event))
{
if (event.type == OsEvent::NONE) continue;
switch (event.type)
{
case OsEvent::TOUCH:
{
const OsTouchEvent& ev = event.touch;
switch (ev.type)
{
case OsTouchEvent::POINTER:
im->touch()->set_button_state(ev.pointer_id, ev.pressed);
break;
case OsTouchEvent::MOVE:
im->touch()->set_axis(ev.pointer_id, vector3(ev.x, ev.y, 0.0f));
break;
default:
CE_FATAL("Unknown touch event type");
break;
}
break;
}
case OsEvent::MOUSE:
{
const OsMouseEvent& ev = event.mouse;
switch (ev.type)
{
case OsMouseEvent::BUTTON:
im->mouse()->set_button_state(ev.button, ev.pressed);
break;
case OsMouseEvent::MOVE:
_mouse_curr_x = ev.x;
_mouse_curr_y = ev.y;
im->mouse()->set_axis(MouseAxis::CURSOR, vector3(ev.x, ev.y, 0.0f));
break;
case OsMouseEvent::WHEEL:
im->mouse()->set_axis(MouseAxis::WHEEL, vector3(0.0f, ev.wheel, 0.0f));
break;
default:
CE_FATAL("Unknown mouse event type");
break;
}
break;
}
case OsEvent::KEYBOARD:
{
const OsKeyboardEvent& ev = event.keyboard;
im->keyboard()->set_button_state(ev.button, ev.pressed);
break;
}
case OsEvent::JOYPAD:
{
const OsJoypadEvent& ev = event.joypad;
switch (ev.type)
{
case OsJoypadEvent::CONNECTED:
im->joypad(ev.index)->set_connected(ev.connected);
break;
case OsJoypadEvent::BUTTON:
im->joypad(ev.index)->set_button_state(ev.button, ev.pressed);
break;
case OsJoypadEvent::AXIS:
im->joypad(ev.index)->set_axis(ev.button, vector3(ev.x, ev.y, ev.z));
break;
default:
CE_FATAL("Unknown joypad event");
break;
}
break;
}
case OsEvent::METRICS:
{
const OsMetricsEvent& ev = event.metrics;
_width = ev.width;
_height = ev.height;
bgfx::reset(ev.width, ev.height, BGFX_RESET_VSYNC);
break;
}
case OsEvent::EXIT:
{
exit = true;
break;
}
case OsEvent::PAUSE:
{
pause();
break;
}
case OsEvent::RESUME:
{
unpause();
break;
}
default:
{
CE_FATAL("Unknown Os Event");
break;
}
}
}
return exit;
}
void Device::read_config()
{
TempAllocator4096 ta;
DynamicString project_path(ta);
if (_device_options.project() != NULL)
{
project_path += _device_options.project();
project_path += '/';
}
project_path += CROWN_BOOT_CONFIG;
const StringId64 config_name(project_path.c_str());
_resource_manager->load(CONFIG_TYPE, config_name);
_resource_manager->flush();
const char* cfile = (const char*)_resource_manager->get(CONFIG_TYPE, config_name);
JsonObject config(ta);
sjson::parse(cfile, config);
_boot_script_id = sjson::parse_resource_id(config["boot_script"]);
_boot_package_id = sjson::parse_resource_id(config["boot_package"]);
_resource_manager->unload(CONFIG_TYPE, config_name);
}
char _buffer[sizeof(Device)];
Device* _device = NULL;
void init(const DeviceOptions& opts)
{
CE_ASSERT(_device == NULL, "Crown already initialized");
_device = new (_buffer) Device(opts);
_device->init();
}
void update()
{
_device->update();
}
void shutdown()
{
_device->shutdown();
_device->~Device();
_device = NULL;
}
Device* device()
{
return crown::_device;
}
} // namespace crown
<commit_msg>Cleanup<commit_after>/*
* Copyright (c) 2012-2016 Daniele Bartolini and individual contributors.
* License: https://github.com/taylor001/crown/blob/master/LICENSE
*/
#include "device.h"
#include "array.h"
#include "config.h"
#include "input_manager.h"
#include "log.h"
#include "lua_environment.h"
#include "material_manager.h"
#include "memory.h"
#include "os.h"
#include "resource_loader.h"
#include "resource_manager.h"
#include "resource_package.h"
#include "types.h"
#include "world.h"
#include "filesystem.h"
#include "path.h"
#include "disk_filesystem.h"
#include "physics.h"
#include "audio.h"
#include "profiler.h"
#include "console_server.h"
#include "input_device.h"
#include "sjson.h"
#include "map.h"
#include "vector3.h"
#if CROWN_PLATFORM_ANDROID
#include "apk_filesystem.h"
#endif // CROWN_PLATFORM_ANDROID
#define MAX_SUBSYSTEMS_HEAP 8 * 1024 * 1024
namespace crown
{
Device::Device(const DeviceOptions& opts)
: _allocator(default_allocator(), MAX_SUBSYSTEMS_HEAP)
, _width(0)
, _height(0)
, _mouse_curr_x(0)
, _mouse_curr_y(0)
, _mouse_last_x(0)
, _mouse_last_y(0)
, _is_init(false)
, _is_running(false)
, _is_paused(false)
, _frame_count(0)
, _last_time(0)
, _current_time(0)
, _last_delta_time(0.0f)
, _time_since_start(0.0)
, _device_options(opts)
, _bundle_filesystem(NULL)
, _boot_package_id(uint64_t(0))
, _boot_script_id(uint64_t(0))
, _boot_package(NULL)
, _lua_environment(NULL)
, _resource_loader(NULL)
, _resource_manager(NULL)
, _input_manager(NULL)
, _shader_manager(NULL)
, _material_manager(NULL)
, _unit_manager(NULL)
, _worlds(default_allocator())
, _bgfx_allocator(default_allocator())
{
}
void Device::init()
{
// Initialize
CE_LOGI("Initializing Crown Engine %s...", version());
profiler_globals::init();
#if CROWN_PLATFORM_ANDROID
_bundle_filesystem = CE_NEW(_allocator, ApkFilesystem)(const_cast<AAssetManager*>(_device_options.asset_manager()));
#else
_bundle_filesystem = CE_NEW(_allocator, DiskFilesystem)(_device_options.bundle_dir());
#endif // CROWN_PLATFORM_ANDROID
_resource_loader = CE_NEW(_allocator, ResourceLoader)(*_bundle_filesystem);
_resource_manager = CE_NEW(_allocator, ResourceManager)(*_resource_loader);
read_config();
bgfx::init(bgfx::RendererType::Count
, BGFX_PCI_ID_NONE
, 0
, &_bgfx_callback
, &_bgfx_allocator
);
_shader_manager = CE_NEW(_allocator, ShaderManager)(default_allocator());
_material_manager = CE_NEW(_allocator, MaterialManager)(default_allocator(), *_resource_manager);
_input_manager = CE_NEW(_allocator, InputManager)(default_allocator());
_unit_manager = CE_NEW(_allocator, UnitManager)(default_allocator());
_lua_environment = CE_NEW(_allocator, LuaEnvironment)();
audio_globals::init();
physics_globals::init();
_boot_package = create_resource_package(_boot_package_id);
_boot_package->load();
_boot_package->flush();
_lua_environment->load_libs();
_lua_environment->execute((LuaResource*)_resource_manager->get(SCRIPT_TYPE, _boot_script_id));
_lua_environment->call_global("init", 0);
_is_init = true;
_is_running = true;
_last_time = os::clocktime();
CE_LOGD("Engine initialized");
}
void Device::shutdown()
{
CE_ASSERT(_is_init, "Engine is not initialized");
_is_running = false;
_is_init = false;
_lua_environment->call_global("shutdown", 0);
_boot_package->unload();
destroy_resource_package(*_boot_package);
physics_globals::shutdown();
audio_globals::shutdown();
CE_DELETE(_allocator, _lua_environment);
CE_DELETE(_allocator, _unit_manager);
CE_DELETE(_allocator, _input_manager);
CE_DELETE(_allocator, _material_manager);
CE_DELETE(_allocator, _shader_manager);
CE_DELETE(_allocator, _resource_manager);
CE_DELETE(_allocator, _resource_loader);
CE_DELETE(_allocator, _bundle_filesystem);
bgfx::shutdown();
profiler_globals::shutdown();
_allocator.clear();
}
void Device::quit()
{
_is_running = false;
}
void Device::pause()
{
_is_paused = true;
CE_LOGI("Engine paused.");
}
void Device::unpause()
{
_is_paused = false;
CE_LOGI("Engine unpaused.");
}
void Device::resolution(uint16_t& width, uint16_t& height)
{
width = _width;
height = _height;
}
bool Device::is_running() const
{
return _is_running;
}
uint64_t Device::frame_count() const
{
return _frame_count;
}
float Device::last_delta_time() const
{
return _last_delta_time;
}
double Device::time_since_start() const
{
return _time_since_start;
}
void Device::update()
{
while (!process_events() && _is_running)
{
_current_time = os::clocktime();
const int64_t time = _current_time - _last_time;
_last_time = _current_time;
const double freq = (double) os::clockfrequency();
_last_delta_time = time * (1.0 / freq);
_time_since_start += _last_delta_time;
profiler_globals::clear();
console_server_globals::update();
RECORD_FLOAT("device.dt", _last_delta_time);
RECORD_FLOAT("device.fps", 1.0f/_last_delta_time);
if (!_is_paused)
{
_resource_manager->complete_requests();
_lua_environment->call_global("update", 1, ARGUMENT_FLOAT, last_delta_time());
_lua_environment->call_global("render", 1, ARGUMENT_FLOAT, last_delta_time());
}
_input_manager->update();
const bgfx::Stats* stats = bgfx::getStats();
RECORD_FLOAT("bgfx.gpu_time", double(stats->gpuTimeEnd - stats->gpuTimeBegin)*1000.0/stats->gpuTimerFreq);
RECORD_FLOAT("bgfx.cpu_time", double(stats->cpuTimeEnd - stats->cpuTimeBegin)*1000.0/stats->cpuTimerFreq);
bgfx::frame();
profiler_globals::flush();
_lua_environment->clear_temporaries();
_frame_count++;
}
}
void Device::render_world(World& world, CameraInstance camera)
{
world.render(camera);
}
World* Device::create_world()
{
World* w = CE_NEW(default_allocator(), World)(default_allocator()
, *_resource_manager
, *_lua_environment
, *_material_manager
, *_unit_manager
);
array::push_back(_worlds, w);
return w;
}
void Device::destroy_world(World& w)
{
for (uint32_t i = 0, n = array::size(_worlds); i < n; ++i)
{
if (&w == _worlds[i])
{
CE_DELETE(default_allocator(), &w);
_worlds[i] = _worlds[n - 1];
array::pop_back(_worlds);
return;
}
}
CE_ASSERT(false, "Bad world");
}
ResourcePackage* Device::create_resource_package(StringId64 id)
{
return CE_NEW(default_allocator(), ResourcePackage)(id, *_resource_manager);
}
void Device::destroy_resource_package(ResourcePackage& rp)
{
CE_DELETE(default_allocator(), &rp);
}
void Device::reload(StringId64 type, StringId64 name)
{
const void* old_resource = _resource_manager->get(type, name);
_resource_manager->reload(type, name);
const void* new_resource = _resource_manager->get(type, name);
if (type == SCRIPT_TYPE)
{
_lua_environment->execute((const LuaResource*)new_resource);
}
}
ResourceManager* Device::resource_manager()
{
return _resource_manager;
}
LuaEnvironment* Device::lua_environment()
{
return _lua_environment;
}
InputManager* Device::input_manager()
{
return _input_manager;
}
ShaderManager* Device::shader_manager()
{
return _shader_manager;
}
MaterialManager* Device::material_manager()
{
return _material_manager;
}
UnitManager* Device::unit_manager()
{
return _unit_manager;
}
bool Device::process_events()
{
OsEvent event;
bool exit = false;
InputManager* im = _input_manager;
const int16_t dt_x = _mouse_curr_x - _mouse_last_x;
const int16_t dt_y = _mouse_curr_y - _mouse_last_y;
im->mouse()->set_axis(MouseAxis::CURSOR_DELTA, vector3(dt_x, dt_y, 0.0f));
_mouse_last_x = _mouse_curr_x;
_mouse_last_y = _mouse_curr_y;
while(next_event(event))
{
if (event.type == OsEvent::NONE) continue;
switch (event.type)
{
case OsEvent::TOUCH:
{
const OsTouchEvent& ev = event.touch;
switch (ev.type)
{
case OsTouchEvent::POINTER:
im->touch()->set_button_state(ev.pointer_id, ev.pressed);
break;
case OsTouchEvent::MOVE:
im->touch()->set_axis(ev.pointer_id, vector3(ev.x, ev.y, 0.0f));
break;
default:
CE_FATAL("Unknown touch event type");
break;
}
break;
}
case OsEvent::MOUSE:
{
const OsMouseEvent& ev = event.mouse;
switch (ev.type)
{
case OsMouseEvent::BUTTON:
im->mouse()->set_button_state(ev.button, ev.pressed);
break;
case OsMouseEvent::MOVE:
_mouse_curr_x = ev.x;
_mouse_curr_y = ev.y;
im->mouse()->set_axis(MouseAxis::CURSOR, vector3(ev.x, ev.y, 0.0f));
break;
case OsMouseEvent::WHEEL:
im->mouse()->set_axis(MouseAxis::WHEEL, vector3(0.0f, ev.wheel, 0.0f));
break;
default:
CE_FATAL("Unknown mouse event type");
break;
}
break;
}
case OsEvent::KEYBOARD:
{
const OsKeyboardEvent& ev = event.keyboard;
im->keyboard()->set_button_state(ev.button, ev.pressed);
break;
}
case OsEvent::JOYPAD:
{
const OsJoypadEvent& ev = event.joypad;
switch (ev.type)
{
case OsJoypadEvent::CONNECTED:
im->joypad(ev.index)->set_connected(ev.connected);
break;
case OsJoypadEvent::BUTTON:
im->joypad(ev.index)->set_button_state(ev.button, ev.pressed);
break;
case OsJoypadEvent::AXIS:
im->joypad(ev.index)->set_axis(ev.button, vector3(ev.x, ev.y, ev.z));
break;
default:
CE_FATAL("Unknown joypad event");
break;
}
break;
}
case OsEvent::METRICS:
{
const OsMetricsEvent& ev = event.metrics;
_width = ev.width;
_height = ev.height;
bgfx::reset(ev.width, ev.height, BGFX_RESET_VSYNC);
break;
}
case OsEvent::EXIT:
{
exit = true;
break;
}
case OsEvent::PAUSE:
{
pause();
break;
}
case OsEvent::RESUME:
{
unpause();
break;
}
default:
{
CE_FATAL("Unknown Os Event");
break;
}
}
}
return exit;
}
void Device::read_config()
{
TempAllocator4096 ta;
DynamicString project_path(ta);
if (_device_options.project() != NULL)
{
project_path += _device_options.project();
project_path += '/';
}
project_path += CROWN_BOOT_CONFIG;
const StringId64 config_name(project_path.c_str());
_resource_manager->load(CONFIG_TYPE, config_name);
_resource_manager->flush();
const char* cfile = (const char*)_resource_manager->get(CONFIG_TYPE, config_name);
JsonObject config(ta);
sjson::parse(cfile, config);
_boot_script_id = sjson::parse_resource_id(config["boot_script"]);
_boot_package_id = sjson::parse_resource_id(config["boot_package"]);
_resource_manager->unload(CONFIG_TYPE, config_name);
}
char _buffer[sizeof(Device)];
Device* _device = NULL;
void init(const DeviceOptions& opts)
{
CE_ASSERT(_device == NULL, "Crown already initialized");
_device = new (_buffer) Device(opts);
_device->init();
}
void update()
{
_device->update();
}
void shutdown()
{
_device->shutdown();
_device->~Device();
_device = NULL;
}
Device* device()
{
return crown::_device;
}
} // namespace crown
<|endoftext|>
|
<commit_before>#include <iostream>
#include <stdio.h>
#include <dirent.h>
#include <vector>
#include <sys/stat.h>
#include <iomanip>
using namespace std;
void printPermissions(int protec) {
if (S_ISDIR(protec) != 0) cout << "d";
else cout << "-";
cout << ((protec & S_IRUSR)?"r":"-");
cout << ((protec & S_IWUSR)?"w":"-");
cout << ((protec & S_IXUSR)?"x":"-");
cout << ((protec & S_IRGRP)?"r":"-");
cout << ((protec & S_IWGRP)?"w":"-");
cout << ((protec & S_IXGRP)?"x":"-");
cout << ((protec & S_IROTH)?"r":"-");
cout << ((protec & S_IWOTH)?"w":"-");
cout << ((protec & S_IXOTH)?"x":"-");
}
void printInformation(struct stat s) {
cout << " " << setw(5) << s.st_nlink;
cout << " " << setw(10) << s.st_uid;
cout << " " << setw(10) << s.st_gid;
cout << " " << setw(10) << s.st_size;
cout << " " << setw(15) << s.st_mtime;
cout << " ";
}
void printStr(char *c) {
for (int i = 0; c[i] != '\0'; ++i) {
cout << c[i];
}
}
void changeColor(short background, int protec){
if(background == 1) cout << "\x1b[47m";
if(S_ISDIR(protec)) cout << "\x1b[34m";
else if(protec & S_IXUSR) cout << "\x1b[32m";
}
void resetColor(){
cout<<"\x1b[0m";
}
void print_time(vector<string> &v) {
int total = 0;
for (unsigned i = 0; i < v.size(); ++i) {
struct stat s;
if (stat(v.at(i).c_str(), &s) == -1) {
perror(string("There was an error with stat(" + v.at(i) + ")").c_str());
}
else {
total += s.st_blocks*512;
}
}
total = total != 0 ? total / 512: 0;
cout << "total " << total <<endl;
}
void print_aFlag(vector<string> &v, vector<string> &n) {
for (unsigned i = 0; i < v.size(); ++i) {
struct stat s;
if (stat(v.at(i).c_str(), &s) == -1) {
perror(string("There was an error with stat(" + v.at(i) + ")").c_str());
}
else {
if (v.at(i).find('.') == 0) {//axou ponto
changeColor(1, s.st_mode);
cout << n.at(i);
}
else {
changeColor(0, s.st_mode);
cout << n.at(i);
}
resetColor();
cout << " ";
}
}
}
void print_alFlag(vector<string> &v, vector<string> &n) {
for (unsigned i = 0; i < v.size(); ++i) {
struct stat s;
stat(v.at(i).c_str(), &s);
if (stat(v.at(i).c_str(), &s) == -1) {
perror(string("There was an error with stat(" + v.at(i) + ")").c_str());
}
else {
resetColor();
printPermissions(s.st_mode);
printInformation(s);
if (v.at(i).find('.') == 0) {//axou ponto
changeColor(1, s.st_mode);
cout << n.at(i);
}
else {
changeColor(0, s.st_mode);
cout << n.at(i);
}
resetColor();
cout << endl;
}
}
}
int main(int argc, char **argv)
{
//beggining of flags checking
char dir[] = ".";
if (argc == 1) {
argv[0] = dir;
}
else {
for(int i = 0; i < argc - 1; ++i) {
argv[i] = argv[i + 1];
}
argc--;
}
bool flag_a = false;
bool flag_l = false;
bool is_flag = false;
bool is_dir = false;
int dir_count = 0;
for (int i = 0; i < argc; ++i) {
is_flag = false;
if (argv[i][0] == '-') {
is_flag = true;
}
else {
is_dir = true;
argv[dir_count] = argv[i];
++dir_count;
}
for (int j = 1; argv[i][j] != '\0'; ++j) {
if (is_flag == true && is_dir == false) {
if(argv[i][j] == 'a') flag_a = true;
if(argv[i][j] == 'l') flag_l = true;
}
}
}
if (dir_count == 0) {
argv[0] = dir;
++dir_count;
}
//end of flags checking
vector <string> names;
vector <string> dirs;
for (int k = 0; k < dir_count; ++k) {
struct stat s;
if (stat(argv[k], &s) < 0) {
perror("stat");
cout << endl;
}
else {
DIR *dirp = opendir(argv[k]);
if (dirp == NULL) { //is not dir
resetColor();
perror("opendir");
cout << endl;
}
else {
dirent *direntp;
if (strcmp(argv[k], ".") != 0) {
resetColor();
printStr(argv[k]);//print folders name
cout << ":" << endl;
}
//creates list of name of files
while ((direntp = readdir(dirp))) {
if (direntp == NULL) {
perror("readdir");
cout << endl;
}
else {
if (strcmp(argv[k], ".") == 0) {
if (!flag_a) { //exclude hidden files from the list
if (direntp->d_name[0]!='.') {
string curr_str(direntp->d_name);
names.push_back(curr_str);
dirs.push_back(curr_str);
}
}
else { //list with --all files
string curr_str(direntp->d_name);
names.push_back(curr_str);
dirs.push_back(curr_str);
}
}
else {
if (!flag_a) { //exclude hidden files from the list
if (direntp->d_name[0]!='.') {
string curr_str = string(direntp->d_name);
string dir = "/" + string(curr_str);
names.push_back(string(curr_str));
dirs.push_back(argv[k] + dir);
}
}
else { //list with --all files
string curr_str = string(direntp->d_name);
string dir = "/" + string(curr_str);
names.push_back(string(curr_str));
dirs.push_back(argv[k] + dir);
}
}
}
}
if (!flag_l) { //flag a
resetColor();
print_aFlag(dirs, names);
resetColor();
}
else {// flag al or l, dependes on the contents of "names"
resetColor();
print_time(dirs);
print_alFlag(dirs, names);
resetColor();
}
if (closedir(dirp) == -1) perror("closedir");
cout << endl;
}
names.clear();
dirs.clear();
}
}
return 0;
}
<commit_msg>Update ls.cpp<commit_after>#include <iostream>
#include <stdio.h>
#include <dirent.h>
#include <vector>
#include <sys/stat.h>
#include <iomanip>
#include <string.h>
using namespace std;
void printPermissions(int protec) {
if (S_ISDIR(protec) != 0) cout << "d";
else if (S_ISLNK(protec) != 0) cout << "l";
else cout << "-";
cout << ((protec & S_IRUSR)?"r":"-");
cout << ((protec & S_IWUSR)?"w":"-");
cout << ((protec & S_IXUSR)?"x":"-");
cout << ((protec & S_IRGRP)?"r":"-");
cout << ((protec & S_IWGRP)?"w":"-");
cout << ((protec & S_IXGRP)?"x":"-");
cout << ((protec & S_IROTH)?"r":"-");
cout << ((protec & S_IWOTH)?"w":"-");
cout << ((protec & S_IXOTH)?"x":"-");
}
void printInformation(struct stat s) {
cout << "\t" << setw(5) << s.st_nlink;
cout << "\t" << setw(5) << s.st_uid;
cout << "\t" << setw(5) << s.st_gid;
cout << "\t" << setw(10) << s.st_size;
cout << "\t" << setw(15) << s.st_mtime;
cout << "\t";
}
void printStr(char *c) {
for (int i = 0; c[i] != '\0'; ++i) {
cout << c[i];
}
}
void changeColor(short background, int protec){
if(background == 1) cout << "\x1b[47m";
if(S_ISDIR(protec)) cout << "\x1b[34m";
else if(protec & S_IXUSR) cout << "\x1b[32m";
}
void resetColor(){
cout<<"\x1b[0m";
}
void print_time(vector<string> &v) {
int total = 0;
for (unsigned i = 0; i < v.size(); ++i) {
struct stat s;
if (lstat(v.at(i).c_str(), &s) == -1) {
perror(string("ERROR(" + v.at(i) + ")").c_str());
}
else {
total += s.st_blocks*512;
}
}
total = total != 0 ? total / 512: 0;
cout << "total " << total <<endl;
}
void print_aFlag(vector<string> &v, vector<string> &n) {
for (unsigned i = 0; i < v.size(); ++i) {
struct stat s;
if (lstat(v.at(i).c_str(), &s) == -1) {
perror(string("ERROR lstat(" + v.at(i) + ")").c_str());
}
else {
if (v.at(i).find('.') == 0) {//axou ponto
changeColor(1, s.st_mode);
cout << n.at(i);
}
else {
changeColor(0, s.st_mode);
cout << n.at(i);
}
resetColor();
cout << " ";
}
}
}
void print_alFlag(vector<string> &v, vector<string> &n) {
for (unsigned i = 0; i < v.size(); ++i) {
struct stat s;
stat(v.at(i).c_str(), &s);
if (lstat(v.at(i).c_str(), &s) == -1) {
perror(string("ERROR: lstat(" + v.at(i) + ")").c_str());
}
else {
resetColor();
printPermissions(s.st_mode);
printInformation(s);
if (v.at(i).find('.') == 0) {//axou ponto
changeColor(1, s.st_mode);
cout << n.at(i);
}
else {
changeColor(0, s.st_mode);
cout << n.at(i);
}
resetColor();
cout << endl;
}
}
}
int main(int argc, char **argv)
{
//beggining of flags checking
char dir[] = ".";
if (argc == 1) {
argv[0] = dir;
}
else {
for(int i = 0; i < argc - 1; ++i) {
argv[i] = argv[i + 1];
}
argc--;
}
bool flag_a = false;
bool flag_l = false;
bool is_flag = false;
bool is_dir = false;
int dir_count = 0;
for (int i = 0; i < argc; ++i) {
is_flag = false;
if (argv[i][0] == '-') {
is_flag = true;
}
else {
is_dir = true;
argv[dir_count] = argv[i];
++dir_count;
}
for (int j = 1; argv[i][j] != '\0'; ++j) {
if (is_flag == true && is_dir == false) {
if(argv[i][j] == 'a') flag_a = true;
if(argv[i][j] == 'l') flag_l = true;
}
}
}
if (dir_count == 0) {
argv[0] = dir;
++dir_count;
}
//end of flags checking
vector <string> names;
vector <string> dirs;
for (int k = 0; k < dir_count; ++k) {
struct stat s;
if (lstat(argv[k], &s) < 0) {
perror("lstat");
cout << endl;
}
else {
DIR *dirp = opendir(argv[k]);
if (dirp == NULL) { //is not dir
resetColor();
perror("opendir");
cout << endl;
}
else {
dirent *direntp;
if (strcmp(argv[k], ".") != 0) {
resetColor();
printStr(argv[k]);//print folders name
cout << ":" << endl;
}
//creates list of name of files
while ((direntp = readdir(dirp))) {
if (direntp == NULL) {
perror("readdir");
cout << endl;
}
else {
if (strcmp(argv[k], ".") == 0) {
if (!flag_a) { //exclude hidden files from the list
if (direntp->d_name[0]!='.') {
string curr_str(direntp->d_name);
names.push_back(curr_str);
dirs.push_back(curr_str);
}
}
else { //list with --all files
string curr_str(direntp->d_name);
names.push_back(curr_str);
dirs.push_back(curr_str);
}
}
else {
if (!flag_a) { //exclude hidden files from the list
if (direntp->d_name[0]!='.') {
string curr_str = string(direntp->d_name);
string dir = "/" + string(curr_str);
names.push_back(string(curr_str));
dirs.push_back(argv[k] + dir);
}
}
else { //list with --all files
string curr_str = string(direntp->d_name);
string dir = "/" + string(curr_str);
names.push_back(string(curr_str));
dirs.push_back(argv[k] + dir);
}
}
}
}
if (!flag_l) { //flag a
resetColor();
print_aFlag(dirs, names);
resetColor();
}
else {// flag al or l, dependes on the contents of "names"
resetColor();
print_time(dirs);
print_alFlag(dirs, names);
resetColor();
}
if (closedir(dirp) == -1) perror("closedir");
cout << endl;
}
names.clear();
dirs.clear();
}
}
return 0;
}
<|endoftext|>
|
<commit_before>#include "device.h"
#include "sysex/commands.h"
#include "sysex/deviceinfo.h"
#include "sysex/getcommands.h"
#include "sysex/infos.h"
#include "sysex/midi.h"
#include <array>
#include <cstring>
#include <iostream>
#include <sstream>
#include <unistd.h>
Device::Device(int inPortNumber, int outPortNumber, long serialNumber,
int productId) {
this->inPortNumber = inPortNumber;
this->outPortNumber = outPortNumber;
this->serialNumber = new MIDISysexValue(serialNumber, 5);
this->productId = new MIDISysexValue(productId, 2);
setupMidi();
}
#ifdef __MIO_SIMULATE__
Device::Device(int inPortNumber, int outPortNumber, long serialNumber,
int productId, std::string modelName, std::string deviceName) {
this->inPortNumber = inPortNumber;
this->outPortNumber = outPortNumber;
this->serialNumber = new MIDISysexValue(serialNumber);
this->productId = new MIDISysexValue(productId);
this->modelName = modelName;
this->deviceName = deviceName;
this->simulate = true;
}
#endif //__MIO_DEBUG__
Device::~Device() {
if (midiin) {
if (midiin->isPortOpen())
midiin->closePort();
delete midiin;
}
if (midiout) {
if (midiout->isPortOpen())
midiout->closePort();
delete midiout;
}
}
BYTE_VECTOR *Device::getManufacturerHeader() {
if (Device::manufacturerHeader == 0) {
manufacturerHeader = new BYTE_VECTOR();
manufacturerHeader->push_back(MANUFACTURER_SYSEX_ID[0]);
manufacturerHeader->push_back(MANUFACTURER_SYSEX_ID[1]);
manufacturerHeader->push_back(MANUFACTURER_SYSEX_ID[2]);
}
return manufacturerHeader;
}
BYTE_VECTOR *Device::getDeviceHeader() {
if (deviceHeader == 0) {
deviceHeader = new BYTE_VECTOR();
deviceHeader->reserve(productId->getByteValue()->size() +
serialNumber->getByteValue()->size());
deviceHeader->insert(deviceHeader->end(),
productId->getByteValue()->begin(),
productId->getByteValue()->end());
deviceHeader->insert(deviceHeader->end(),
serialNumber->getByteValue()->begin(),
serialNumber->getByteValue()->end());
}
return deviceHeader;
}
BYTE_VECTOR *Device::getFullHeader() {
if (fullHeader == 0) {
fullHeader = new BYTE_VECTOR();
fullHeader->reserve(Device::getManufacturerHeader()->size() +
getDeviceHeader()->size() + 1);
fullHeader->insert(fullHeader->end(),
Device::getManufacturerHeader()->begin(),
Device::getManufacturerHeader()->end());
fullHeader->push_back(Device::MESSAGE_CLASS);
fullHeader->insert(fullHeader->end(), getDeviceHeader()->begin(),
getDeviceHeader()->end());
}
return fullHeader;
}
void Device::setupMidi() {
std::stringstream name;
name << "MioConfig In " << serialNumber->getLongValue();
midiin = MIDI::createMidiIn(name.str());
midiin->openPort(inPortNumber);
name << "MioConfig Out " << serialNumber->getLongValue();
midiout = MIDI::createMidiOut(name.str());
midiout->openPort(outPortNumber);
}
void Device::sentSysex(BYTE_VECTOR *data) {
usleep(sysexWaitTime);
midiout->sendMessage(data);
}
BYTE_VECTOR *Device::retrieveSysex() {
usleep(sysexWaitTime);
BYTE_VECTOR *data = new BYTE_VECTOR();
midiin->getMessage(data);
if (checkSysex(data))
return data;
return 0;
}
bool Device::checkSysex(BYTE_VECTOR *data) {
BYTE_VECTOR *dataHeader =
new BYTE_VECTOR(data->begin() + 1, data->begin() + 12);
BYTE_VECTOR *localHeader = getFullHeader();
return MIDI::compareByteVector(dataHeader, localHeader);
}
void Device::queryDeviceInfo() {
#ifdef __MIO_SIMULATE__
if (!simulate) {
#endif
GetCommands *c = new GetCommands(this);
c->setDebug(true);
commands = (Commands *)c->query();
if (commands == 0) {
std::cerr << "can not query supported commands";
return;
}
if (commands->isCommandSupported(SysExMessage::GET_INFO_LIST)) {
Infos *i = new Infos(this);
i->execute();
Infos *ia = (Infos *)i->getAnswer();
}
DeviceInfo *di = new DeviceInfo(this);
di->execute();
DeviceInfo *dia = (DeviceInfo *)di->getAnswer();
deviceName = dia->getDataAsString();
di->setInfoItem(DeviceInfo::ACESSORY_NAME);
di->execute();
dia = (DeviceInfo *)di->getAnswer();
modelName = dia->getDataAsString();
di->setInfoItem(DeviceInfo::SERIAL_NUMBER);
di->execute();
dia = (DeviceInfo *)di->getAnswer();
serialNumberString = dia->getDataAsString();
#ifdef __MIO_SIMULATE__
}
#endif
}
BYTE_VECTOR *Device::nextTransactionId() {
if (transactionId > 16000)
transactionId = 0;
BYTE_VECTOR *v = MIDI::byteSplit(++transactionId, 2);
return v;
}
BYTE_VECTOR *Device::manufacturerHeader = 0;
<commit_msg>extended simulation<commit_after>#include "device.h"
#include "sysex/commands.h"
#include "sysex/deviceinfo.h"
#include "sysex/getcommands.h"
#include "sysex/infos.h"
#include "sysex/midi.h"
#include <array>
#include <cstring>
#include <iostream>
#include <sstream>
#include <unistd.h>
Device::Device(int inPortNumber, int outPortNumber, long serialNumber,
int productId) {
this->inPortNumber = inPortNumber;
this->outPortNumber = outPortNumber;
this->serialNumber = new MIDISysexValue(serialNumber, 5);
this->productId = new MIDISysexValue(productId, 2);
setupMidi();
}
#ifdef __MIO_SIMULATE__
Device::Device(int inPortNumber, int outPortNumber, long serialNumber,
int productId, std::string modelName, std::string deviceName) {
this->inPortNumber = inPortNumber;
this->outPortNumber = outPortNumber;
this->serialNumber = new MIDISysexValue(serialNumber, 5);
this->productId = new MIDISysexValue(productId, 2);
this->modelName = modelName;
this->deviceName = deviceName;
this->deviceIsSimulated = true;
}
#endif //__MIO_DEBUG__
Device::~Device() {
if (midiin) {
if (midiin->isPortOpen())
midiin->closePort();
delete midiin;
}
if (midiout) {
if (midiout->isPortOpen())
midiout->closePort();
delete midiout;
}
}
BYTE_VECTOR *Device::getManufacturerHeader() {
if (Device::manufacturerHeader == 0) {
manufacturerHeader = new BYTE_VECTOR();
manufacturerHeader->push_back(MANUFACTURER_SYSEX_ID[0]);
manufacturerHeader->push_back(MANUFACTURER_SYSEX_ID[1]);
manufacturerHeader->push_back(MANUFACTURER_SYSEX_ID[2]);
}
return manufacturerHeader;
}
BYTE_VECTOR *Device::getDeviceHeader() {
if (deviceHeader == 0) {
deviceHeader = new BYTE_VECTOR();
deviceHeader->reserve(productId->getByteValue()->size() +
serialNumber->getByteValue()->size());
deviceHeader->insert(deviceHeader->end(),
productId->getByteValue()->begin(),
productId->getByteValue()->end());
deviceHeader->insert(deviceHeader->end(),
serialNumber->getByteValue()->begin(),
serialNumber->getByteValue()->end());
}
return deviceHeader;
}
BYTE_VECTOR *Device::getFullHeader() {
if (fullHeader == 0) {
fullHeader = new BYTE_VECTOR();
fullHeader->reserve(Device::getManufacturerHeader()->size() +
getDeviceHeader()->size() + 1);
fullHeader->insert(fullHeader->end(),
Device::getManufacturerHeader()->begin(),
Device::getManufacturerHeader()->end());
fullHeader->push_back(Device::MESSAGE_CLASS);
fullHeader->insert(fullHeader->end(), getDeviceHeader()->begin(),
getDeviceHeader()->end());
}
return fullHeader;
}
void Device::setupMidi() {
std::stringstream name;
name << "MioConfig In " << serialNumber->getLongValue();
midiin = MIDI::createMidiIn(name.str());
midiin->openPort(inPortNumber);
name << "MioConfig Out " << serialNumber->getLongValue();
midiout = MIDI::createMidiOut(name.str());
midiout->openPort(outPortNumber);
}
void Device::sentSysex(BYTE_VECTOR *data) {
usleep(sysexWaitTime);
midiout->sendMessage(data);
}
BYTE_VECTOR *Device::retrieveSysex() {
usleep(sysexWaitTime);
BYTE_VECTOR *data = new BYTE_VECTOR();
midiin->getMessage(data);
if (checkSysex(data))
return data;
return 0;
}
bool Device::checkSysex(BYTE_VECTOR *data) {
BYTE_VECTOR *dataHeader =
new BYTE_VECTOR(data->begin() + 1, data->begin() + 12);
BYTE_VECTOR *localHeader = getFullHeader();
return MIDI::compareByteVector(dataHeader, localHeader);
}
void Device::queryDeviceInfo() {
GetCommands *c = new GetCommands(this);
c->setDebug(true);
#ifdef __MIO_SIMULATE__
BYTE_VECTOR *message = new BYTE_VECTOR({0xF0});
message->insert(message->end(), getFullHeader()->begin(),
getFullHeader()->end());
message->push_back(0x00);
message->push_back(0x01);
message->push_back(0x00);
message->push_back(SysExMessage::RET_COMMAND_LIST);
message->push_back(0x00);
message->push_back(0x06);
message->insert(message->end(), {0x05, 0x07, 0x08, 0x09, 0x0b, 0x0c});
commands = new Commands(SysExMessage::RET_COMMAND_LIST, message, this);
commands->parseAnswerData();
#else
commands = (Commands *)c->query();
#endif
if (commands == 0) {
std::cerr << "can not query supported commands";
return;
}
#if __MIO_SIMULATE__
if (!deviceIsSimulated) {
#endif //__MIO_SIMULATE
if (commands->isCommandSupported(SysExMessage::GET_INFO_LIST)) {
Infos *i = new Infos(this);
i->execute();
Infos *ia = (Infos *)i->getAnswer();
}
DeviceInfo *di = new DeviceInfo(this);
di->execute();
DeviceInfo *dia = (DeviceInfo *)di->getAnswer();
deviceName = dia->getDataAsString();
di->setInfoItem(DeviceInfo::ACESSORY_NAME);
di->execute();
dia = (DeviceInfo *)di->getAnswer();
modelName = dia->getDataAsString();
di->setInfoItem(DeviceInfo::SERIAL_NUMBER);
di->execute();
dia = (DeviceInfo *)di->getAnswer();
serialNumberString = dia->getDataAsString();
#ifdef __MIO_SIMULATE__
}
#endif //__MIO_SIMULATE__
}
BYTE_VECTOR *Device::nextTransactionId() {
if (transactionId > 16000)
transactionId = 0;
BYTE_VECTOR *v = MIDI::byteSplit(++transactionId, 2);
return v;
}
BYTE_VECTOR *Device::manufacturerHeader = 0;
<|endoftext|>
|
<commit_before>#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
bool Alphabetical(string c1, string c2)
{
for(int i = 0; i < c1.size(); i++)
{
c1.at(i) = tolower(c1.at(i));
}
for(int i = 0; i < c2.size(); i++)
{
c2.at(i) = tolower(c2.at(i));
}
return c1.compare(c2) < 0;
}
void print_files(vector<string> V)
{
for(int x = 0; x < V.size(); x++)
{
cout << V.at(x) << " ";
}
}
int main(int argc, char ** argv)
{
vector<string> file_store;
if(argc <= 1)
{
cout << "Nothing passed in to argv." << endl;
exit(1);
}
else
{
char* Sec_Arr = new char[2];
Sec_Arr[0] = '.';
strcpy(Sec_Arr,".");
argv[0] = Sec_Arr;
DIR *dirp;
if(NULL == (dirp = opendir(argv[0])))
{
perror("There was an error with opendir(). ");
exit(1);
}
struct dirent *filespecs;
errno = 0;
while(NULL != (filespecs = readdir(dirp)))
{
file_store.push_back(filespecs->d_name);
}
sort(file_store.begin(), file_store.end(), Alphabetical);
print_files(file_store);
if(errno != 0)
{
perror("There was an error with readdir(). ");
exit(1);
}
cout << endl;
if(-1 == closedir(dirp))
{
perror("There was an error with closedir(). ");
}
}
return 0;
}
<commit_msg>make ls-a work now<commit_after>#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
string convert_to_string(char *Data)
{
return string(Data);
}
bool Alphabetical(string c1, string c2)
{
for(int i = 0; i < c1.size(); i++)
{
c1.at(i) = tolower(c1.at(i));
}
for(int i = 0; i < c2.size(); i++)
{
c2.at(i) = tolower(c2.at(i));
}
return c1.compare(c2) < 0;
}
vector<int> flag_index; //global vector for checing which flags
vector<string> file_store;
string converted_string;
void type_of_flag(string s)
{
for(int x = 0; x < s.size(); x++) // 0 = "-" dash
{ // 1 = "a"
if(s.at(x) == '-') // 2 = "l"
{ // 3 = "R"
flag_index.push_back(0);
}
else if(s.at(x) == 'a')
{
flag_index.push_back(1);
}
else if(s.at(x) == 'l')
{
flag_index.push_back(2);
}
else if(s.at(x) == 'R')
{
flag_index.push_back(3);
}
else
{
flag_index.push_back(-1);
}
}
}
void print_files(vector<string> V)
{
for(int x = 0; x < V.size(); x++)
{
cout << V.at(x) << " ";
}
}
void execute(int arg, char ** agv)
{
DIR *dirp;
dirp = opendir(agv[0]);
if(NULL == dirp)
{
perror("opendir()");
exit(1);
}
struct dirent *filespecs;
while(NULL != (filespecs = readdir(dirp)))
{
file_store.push_back(filespecs->d_name);
}
sort(file_store.begin(), file_store.end(), Alphabetical);
print_files(file_store);
if(-1 == closedir(dirp))
{
perror("closedir");
exit(1);
}
}
int main(int argc, char ** argv)
{
bool A_check;
bool L_check;
bool R_check;
string flags; //holds all flags of user input
if(argc <= 1)
{
cout << "Nothing passed in to argv." << endl;
exit(1);
}
vector<char *> flags_finder;
for(int x = 1; x < argc; x++)
{
flags_finder.push_back(argv[x]);
}
char* Sec_Arr = new char[2];
Sec_Arr[0] = '.';
strcpy(Sec_Arr,".");
argv[0] = Sec_Arr;
for(int x = 1; x < argc; x++)
{
converted_string += convert_to_string(argv[x]);
converted_string += " ";
}
//cout << converted_string;
for(int x = 0; x < flags_finder.size(); x++)
{
converted_string += convert_to_string(flags_finder.at(x));
for(int i = 0; i < converted_string.size(); i++)
{
if(converted_string.at(i) == '-')
{
for(int v = 1; v < converted_string.size(); v++)
{
flags += converted_string.at(x);
}
}
}
}
for(int i = 0; i < flags.size(); i++)
{
if(flags.at(i) == 'a')
{
A_check = true;
}
else if(flags.at(i) == 'l')
{
L_check = true;
}
else if(flags.at(i) == 'R')
{
R_check == true;
}
}
if(A_check)
{
execute(argc, argv);
}
DIR *dirp;
if(NULL == (dirp = opendir(argv[0])))
{
perror("There was an error with opendir(). ");
exit(1);
}
struct dirent *filespecs;
errno = 0;
while(NULL != (filespecs = readdir(dirp)))
{
file_store.push_back(filespecs->d_name);
}
sort(file_store.begin(), file_store.end(), Alphabetical);
print_files(file_store);
if(errno != 0)
{
perror("There was an error with readdir(). ");
exit(1);
}
cout << endl;
if(-1 == closedir(dirp))
{
perror("There was an error with closedir(). ");
}
return 0;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <vector>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <cassert>
#include <pwd.h>
#include <grp.h>
#include <iomanip>
#include <errno.h>
#include <dirent.h>
#include <vector>
using namespace std;
#define GREEN "\033[32m" //Green color for executables
#define BLUE "\033[34m" //Blue color for directories
#define REG "\033[0m"//regular color
#define HIDDEN "\033[47m" //hidden files
struct stat stats;
DIR *directory;
struct dirent *dir;
void color(string files, struct stat name)
{
//Checking Hidden Directories
if(files.find(".") == 0 &&(name.st_mode&S_IFDIR))
{
cout << HIDDEN << BLUE;
cout << files << " ";
cout << REG;
}
//Checking Hidden Executables
else if(files.find(".") == 0 && (name.st_mode&S_IXUSR))
{
cout << HIDDEN << GREEN;
cout << files << " ";
cout << REG;
}
//Checking Hidden files only
else if(files.find(".") == 0)
{
cout << HIDDEN;
cout << files << " ";
cout << REG;
}
//Checking Directories
else if((name.st_mode & S_IFMT) == S_IFDIR)
{
cout << BLUE;
cout << files << " ";
cout << REG;
}
//Checking executables
else if(name.st_mode & S_IXUSR)
{
cout << GREEN;
cout << files << " ";
cout << REG;
}
//Checking regular files
else cout << files << REG << " " ;
}
void printvector(vector<string> v, string path)
{
for (unsigned int i = 0; i < v.size(); i++)
{
string tmp = path + "/" + v.at(i);
if (-1 == stat(tmp.c_str(), &stats))
perror("stat 1");
color(v.at(i), stats);
}
}
bool checkdir(string s)
{
if (-1 == stat(s.c_str(), &stats))
{
perror("fuck tyou");
exit(1);
}
else
{
if ((stats.st_mode & S_IFMT) == S_IFREG)
{
cout<< s << endl;
return true;
}
}
}
bool checkdirnoprint(string s)
{
if (-1 == stat(s.c_str(), &stats))
{
perror("fuck tyou");
exit(1);
}
else
{
if ((stats.st_mode & S_IFMT) == S_IFREG)
{
return true;
}
}
}
void printls(string s)
{
bool isdir = false;
isdir = checkdir(s);
if (isdir)
return;
vector<string> fag;
if (NULL == (directory = opendir(s.c_str())))
perror("hi :)");
errno = 0;
while (NULL != (dir = readdir(directory)))
{
string caa = dir->d_name;
if (caa.find(".") != 0)
fag.push_back(caa);
}
sort(fag.begin(), fag.end());
printvector(fag, s);
cout << endl;
}
void printals(string s)
{
bool isdir = false;
isdir = checkdir(s);
if (isdir)
return;
vector<string> fag;
if (NULL == (directory = opendir(s.c_str())))
perror("hi :)");
errno = 0;
while (NULL != (dir = readdir(directory)))
{
string caa = dir->d_name;
fag.push_back(caa);
}
sort(fag.begin(), fag.end());
printvector(fag, s);
cout << endl;
}
void total(vector <string> &file, string path)
{
int total=0;
for(int i=0; i<file.size(); i++)
{
struct stat size;
string temp=path+'/'+file[i];
if(stat(temp.c_str(),&size)==-1)
{
perror("stat error");
exit(1);
}
total += size.st_blocks/2;
cout << "total" << total << endl;
}
}
void lprint(struct stat name)
{
string s;
if(S_ISDIR(name.st_mode))
s += 'd';
else
{
if(S_ISLNK(name.st_mode))
s += 'l';
else
cout << '-';
}
if(name.st_mode & S_IRUSR)
cout << 'r';
else
cout << '-';
if(name.st_mode & S_IWUSR)
cout << 'w';
else
cout << '-';
if(name.st_mode & S_IXUSR)
cout << 'x';
else
cout << '-';
if(name.st_mode & S_IRGRP)
cout << 'r';
else
cout << '-';
if(name.st_mode & S_IWGRP)
cout << 'w';
else
cout << '-';
if(name.st_mode & S_IXGRP)
cout << 'x';
else
cout << '-';
if(name.st_mode & S_IROTH)
cout << 'r';
else
cout << '-';
if(name.st_mode & S_IWOTH)
cout << 'w';
else
cout << '-';
if(name.st_mode & S_IXOTH)
cout << 'x';
else
cout << '-';
cout << ' ' << name.st_nlink << ' ';
struct passwd* pw=getpwuid(name.st_uid);
if(!pw)
{
perror("Failed to get pwuid");
exit(1);
}
struct group* gp=getgrgid(name.st_gid);
if(!gp)
{
perror("Failed to get grgid");
}
cout << pw->pw_name << ' ';
cout << gp->gr_name << ' ';
cout << setw(5) << right;
cout << name.st_size << ' ';
//time last modified
char buff[80];
struct tm* time=localtime(&name.st_mtime);
if(!strftime(buff,80,"%b %d %H: %M",time))
{
perror("strftime function error");
exit(1);
}
cout << buff << ' ';
}
void printlls(string s)
{
bool isdir = false;
isdir = checkdir(s);
if (isdir)
return;
vector<string> fag;
if (NULL == (directory = opendir(s.c_str())))
perror("hi :)");
errno = 0;
while (NULL != (dir = readdir(directory)))
{
if (-1 == stat(dir->d_name, &stats))
{
perror("fuck tyou");
exit(1);
}
string tmp = dir->d_name;
if (tmp.find(".") != 0)
{
lprint(stats);
cout << " ";
color(dir->d_name, stats);
cout << endl;
}
}
}
void printlals(string s)
{
bool isdir = false;
isdir = checkdir(s);
if (isdir)
return;
vector<string> fag;
if (NULL == (directory = opendir(s.c_str())))
perror("hi :)");
errno = 0;
while (NULL != (dir = readdir(directory)))
{
if (-1 == stat(dir->d_name, &stats))
{
perror("fuck tyou");
exit(1);
}
lprint(stats);
cout << " ";
color(dir->d_name, stats);
cout << endl;
}
}
void printrls(string s)
{
cout << s << ":" << endl;
printls(s);
/*bool isdir = false;
*isdir = checkdir(s);
*if (isdir)
* return;
*vector<string> fag;
*if (NULL == (directory = opendir(s.c_str())))
* perror("hi :)");
*errno = 0;
*while (NULL != (dir = readdir(directory)))
*{
* string caa = dir->d_name;
* if (caa.find(".") != 0)
* fag.push_back(caa);
*
*}
*sort(fag.begin(), fag.end());
*printvector(fag);
*cout << endl;
*
*printrls();
*/
bool isdir = false;
isdir = checkdir(s);
if (isdir)
return;
if (NULL == (directory = opendir(s.c_str())))
perror("hi" ) ;
while (NULL != (dir = readdir(directory)))
{
string caa = dir->d_name;
if (caa.find(".") != 0)
{
if (not checkdirnoprint(s + "/" + caa)) //if not not dir or if it is a dir
{
printrls(s + "/" + caa);
}
}
}
}
int main(int argc, char* argv[])
{
bool checkflag=true;//checks for flags and files
bool a=false;//to see if ls contains -a or not
bool l=false;//to see if ls contains -l or not
bool R=false;//to see if ls contains -R or not
vector <string> in;
//checking for flags
for(int i=1; i<argc; i++)
{
if(checkflag)
if(argv[i][0]=='-')
for(int j=1; argv[i][j]!=0; j++)
{
if(argv[i][j]=='R')
R=true;
else if(argv[i][j]=='l')
l=true;
else if(argv[i][j]=='a')
a=true;
else
{
cerr << "Invalid flag! nigga " << argv[i][j] << endl;
exit(1);
}
}
else
in.push_back(argv[i]);
}
//checking for files now
for(int i=0; i<in.size(); i++)
{
struct stat file;
if(stat(in.at(i).c_str(),&file)==-1)
{
perror("stat");
exit(1);
}
if(!(file.st_mode & S_IFDIR))
{
color(in[0],file);
cout << endl;
}
}
if (!a && !R && !l)
{
for (int i = 0; i < in.size(); i++)
{
printls(in.at(i));
}
if (in.size() == 0)
printls(".");
}
if (a and !R and !l)
{
for (int i = 0; i < in.size(); i++)
{
printals(in.at(i));
}
if (in.size() == 0)
printals(".");
}
if (!a and !R and l)
{
sort(in.begin(), in.end());
for (int i = 0; i < in.size(); i++)
{
printlls(in.at(i));
}
if (in.size() == 0)
printlls(".");
}
if (a and !R and l)
{
sort(in.begin(), in.end());
for (int i = 0; i < in.size(); i++)
{
printlals(in.at(i));
}
if (in.size() == 0)
printlals(".");
}
if (not a and R and not l)
{
for (int i = 0; i < in.size(); i++)
{
printrls(in.at(i));
}
if (in.size() == 0)
printrls(".");
}
return 0;
}
<commit_msg>Update ls.cpp<commit_after>#include <iostream>
#include <vector>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <cassert>
#include <pwd.h>
#include <grp.h>
#include <iomanip>
#include <errno.h>
#include <dirent.h>
#include <vector>
using namespace std;
#define GREEN "\033[32m" //Green color for executables
#define BLUE "\033[34m" //Blue color for directories
#define REG "\033[0m"//regular color
#define HIDDEN "\033[47m" //hidden files
struct stat stats;
DIR *directory;
struct dirent *dir;
void color(string files, struct stat name)
{
//Checking Hidden Directories
if(files.find(".") == 0 &&(name.st_mode&S_IFDIR))
{
cout << HIDDEN << BLUE;
cout << files << " ";
cout << REG;
}
//Checking Hidden Executables
else if(files.find(".") == 0 && (name.st_mode&S_IXUSR))
{
cout << HIDDEN << GREEN;
cout << files << " ";
cout << REG;
}
//Checking Hidden files only
else if(files.find(".") == 0)
{
cout << HIDDEN;
cout << files << " ";
cout << REG;
}
//Checking Directories
else if((name.st_mode & S_IFMT) == S_IFDIR)
{
cout << BLUE;
cout << files << " ";
cout << REG;
}
//Checking executables
else if(name.st_mode & S_IXUSR)
{
cout << GREEN;
cout << files << " ";
cout << REG;
}
//Checking regular files
else cout << files << REG << " " ;
}
void printvector(vector<string> v, string path)
{
for (unsigned int i = 0; i < v.size(); i++)
{
string tmp = path + "/" + v.at(i);
if (-1 == stat(tmp.c_str(), &stats))
perror("stat 1");
color(v.at(i), stats);
}
}
bool checkdir(string s)
{
if (-1 == stat(s.c_str(), &stats))
{
perror("fuck tyou");
exit(1);
}
else
{
if ((stats.st_mode & S_IFMT) == S_IFREG)
{
cout<< s << endl;
return true;
}
}
}
bool checkdirnoprint(string s)
{
if (-1 == stat(s.c_str(), &stats))
{
perror("fuck tyou");
exit(1);
}
else
{
if ((stats.st_mode & S_IFMT) == S_IFREG)
{
return true;
}
}
}
void printls(string s)
{
bool isdir = false;
isdir = checkdir(s);
if (isdir)
return;
vector<string> fag;
if (NULL == (directory = opendir(s.c_str())))
perror("hi :)");
errno = 0;
while (NULL != (dir = readdir(directory)))
{
string caa = dir->d_name;
if (caa.find(".") != 0)
fag.push_back(caa);
}
sort(fag.begin(), fag.end());
printvector(fag, s);
cout << endl;
}
void printals(string s)
{
bool isdir = false;
isdir = checkdir(s);
if (isdir)
return;
vector<string> fag;
if (NULL == (directory = opendir(s.c_str())))
perror("hi :)");
errno = 0;
while (NULL != (dir = readdir(directory)))
{
string caa = dir->d_name;
fag.push_back(caa);
}
sort(fag.begin(), fag.end());
printvector(fag, s);
cout << endl;
}
void total(vector <string> &file, string path)
{
int total=0;
for(int i=0; i<file.size(); i++)
{
struct stat size;
string temp=path+'/'+file[i];
if(stat(temp.c_str(),&size)==-1)
{
perror("stat error");
exit(1);
}
total += size.st_blocks/2;
cout << "total" << total << endl;
}
}
void lprint(struct stat name)
{
string s;
if(S_ISDIR(name.st_mode))
s += 'd';
else
{
if(S_ISLNK(name.st_mode))
s += 'l';
else
cout << '-';
}
if(name.st_mode & S_IRUSR)
cout << 'r';
else
cout << '-';
if(name.st_mode & S_IWUSR)
cout << 'w';
else
cout << '-';
if(name.st_mode & S_IXUSR)
cout << 'x';
else
cout << '-';
if(name.st_mode & S_IRGRP)
cout << 'r';
else
cout << '-';
if(name.st_mode & S_IWGRP)
cout << 'w';
else
cout << '-';
if(name.st_mode & S_IXGRP)
cout << 'x';
else
cout << '-';
if(name.st_mode & S_IROTH)
cout << 'r';
else
cout << '-';
if(name.st_mode & S_IWOTH)
cout << 'w';
else
cout << '-';
if(name.st_mode & S_IXOTH)
cout << 'x';
else
cout << '-';
cout << ' ' << name.st_nlink << ' ';
struct passwd* pw=getpwuid(name.st_uid);
if(!pw)
{
perror("Failed to get pwuid");
exit(1);
}
struct group* gp=getgrgid(name.st_gid);
if(!gp)
{
perror("Failed to get grgid");
}
cout << pw->pw_name << ' ';
cout << gp->gr_name << ' ';
cout << setw(5) << right;
cout << name.st_size << ' ';
//time last modified
char buff[80];
struct tm* time=localtime(&name.st_mtime);
if(!strftime(buff,80,"%b %d %H: %M",time))
{
perror("strftime function error");
exit(1);
}
cout << buff << ' ';
}
void printlls(string s)
{
bool isdir = false;
isdir = checkdir(s);
if (isdir)
return;
vector<string> fag;
if (NULL == (directory = opendir(s.c_str())))
perror("hi :)");
errno = 0;
while (NULL != (dir = readdir(directory)))
{
if (-1 == stat(dir->d_name, &stats))
{
perror("fuck tyou");
exit(1);
}
string tmp = dir->d_name;
if (tmp.find(".") != 0)
{
lprint(stats);
cout << " ";
color(dir->d_name, stats);
cout << endl;
}
}
}
void printlals(string s)
{
bool isdir = false;
isdir = checkdir(s);
if (isdir)
return;
vector<string> fag;
if (NULL == (directory = opendir(s.c_str())))
perror("hi :)");
errno = 0;
while (NULL != (dir = readdir(directory)))
{
if (-1 == stat(dir->d_name, &stats))
{
perror("fuck tyou");
exit(1);
}
lprint(stats);
cout << " ";
color(dir->d_name, stats);
cout << endl;
}
}
void printrls(string s)
{
cout << s << ":" << endl;
printls(s);
/*bool isdir = false;
*isdir = checkdir(s);
*if (isdir)
* return;
*vector<string> fag;
*if (NULL == (directory = opendir(s.c_str())))
* perror("hi :)");
*errno = 0;
*while (NULL != (dir = readdir(directory)))
*{
* string caa = dir->d_name;
* if (caa.find(".") != 0)
* fag.push_back(caa);
*
*}
*sort(fag.begin(), fag.end());
*printvector(fag);
*cout << endl;
*
*printrls();
*/
bool isdir = false;
isdir = checkdir(s);
if (isdir)
return;
if (NULL == (directory = opendir(s.c_str())))
perror("hi" ) ;
while (NULL != (dir = readdir(directory)))
{
string caa = dir->d_name;
if (caa.find(".") != 0)
{
if (not checkdirnoprint(s + "/" + caa)) //if not not dir or if it is a dir
{
printrls(s + "/" + caa);
}
}
}
}
void printrals(string s)
{
cout << s << ":" << endl;
printals(s);
bool isdir = false;
isdir = checkdir(s);
if (isdir)
return;
if (NULL == (directory = opendir(s.c_str())))
perror("hi" ) ;
while (NULL != (dir = readdir(directory)))
{
string caa = dir->d_name;
if (caa != "." && caa != ".." )
{
if (not checkdirnoprint(s + "/" + caa)) //if not not dir or if it is a dir
{
printrals(s + "/" + caa);
}
}
}
}
void printralls(string s)
{
cout << s << ":" << endl;
printlals(s);
bool isdir = false;
isdir = checkdir(s);
if (isdir)
return;
if (NULL == (directory = opendir(s.c_str())))
perror("hi" ) ;
while (NULL != (dir = readdir(directory)))
{
string caa = dir->d_name;
if (caa != "." && caa != ".." )
{
if (not checkdirnoprint(s + "/" + caa)) //if not not dir or if it is a dir
{
printralls(s + "/" + caa);
}
}
}
}
void printrlls(string s)
{
cout << s << ":" << endl;
printlls(s);
/*bool isdir = false;
*isdir = checkdir(s);
*if (isdir)
* return;
*vector<string> fag;
*if (NULL == (directory = opendir(s.c_str())))
* perror("hi :)");
*errno = 0;
*while (NULL != (dir = readdir(directory)))
*{
* string caa = dir->d_name;
* if (caa.find(".") != 0)
* fag.push_back(caa);
*
*}
*sort(fag.begin(), fag.end());
*printvector(fag);
*cout << endl;
*
*printrls();
*/
bool isdir = false;
isdir = checkdir(s);
if (isdir)
return;
if (NULL == (directory = opendir(s.c_str())))
perror("hi" ) ;
while (NULL != (dir = readdir(directory)))
{
string caa = dir->d_name;
if (caa.find(".") != 0)
{
if (not checkdirnoprint(s + "/" + caa)) //if not not dir or if it is a dir
{
printrlls(s + "/" + caa);
}
}
}
}
int main(int argc, char* argv[])
{
bool checkflag=true;//checks for flags and files
bool a=false;//to see if ls contains -a or not
bool l=false;//to see if ls contains -l or not
bool R=false;//to see if ls contains -R or not
vector <string> in;
//checking for flags
for(int i=1; i<argc; i++)
{
if(checkflag)
if(argv[i][0]=='-')
for(int j=1; argv[i][j]!=0; j++)
{
if(argv[i][j]=='R')
R=true;
else if(argv[i][j]=='l')
l=true;
else if(argv[i][j]=='a')
a=true;
else
{
cerr << "Invalid flag! nigga " << argv[i][j] << endl;
exit(1);
}
}
else
in.push_back(argv[i]);
}
//checking for files now
for(int i=0; i<in.size(); i++)
{
struct stat file;
if(stat(in.at(i).c_str(),&file)==-1)
{
perror("stat");
exit(1);
}
if(!(file.st_mode & S_IFDIR))
{
color(in[0],file);
cout << endl;
}
}
if (!a && !R && !l)
{
for (int i = 0; i < in.size(); i++)
{
printls(in.at(i));
}
if (in.size() == 0)
printls(".");
}
if (a and !R and !l)
{
for (int i = 0; i < in.size(); i++)
{
printals(in.at(i));
}
if (in.size() == 0)
printals(".");
}
if (!a and !R and l)
{
sort(in.begin(), in.end());
for (int i = 0; i < in.size(); i++)
{
printlls(in.at(i));
}
if (in.size() == 0)
printlls(".");
}
if (a and !R and l)
{
sort(in.begin(), in.end());
for (int i = 0; i < in.size(); i++)
{
printlals(in.at(i));
}
if (in.size() == 0)
printlals(".");
}
if (not a and R and not l)
{
for (int i = 0; i < in.size(); i++)
{
printrls(in.at(i));
}
if (in.size() == 0)
printrls(".");
}
if (a and R and not l)
{
for (int i = 0; i < in.size(); i++)
{
printrals(in.at(i));
}
if (in.size() == 0)
printrals(".");
}
if (a and R and l)
{
for (int i = 0; i < in.size(); i++)
{
printralls(in.at(i));
}
if (in.size() == 0)
printralls(".");
}
if (not a and R and l)
{
for (int i = 0; i < in.size(); i++)
{
printrlls(in.at(i));
}
if (in.size() == 0)
printrlls(".");
}
return 0;
}
<|endoftext|>
|
<commit_before>#include "dialogs.h"
#include "juci.h"
#include "singletons.h"
namespace sigc {
#ifndef SIGC_FUNCTORS_DEDUCE_RESULT_TYPE_WITH_DECLTYPE
template <typename Functor>
struct functor_trait<Functor, false> {
typedef decltype (::sigc::mem_fun(std::declval<Functor&>(),
&Functor::operator())) _intermediate;
typedef typename _intermediate::result_type result_type;
typedef Functor functor_type;
};
#else
SIGC_FUNCTORS_DEDUCE_RESULT_TYPE_WITH_DECLTYPE
#endif
}
Dialog::Message::Message(const std::string &text): Gtk::Window(Gtk::WindowType::WINDOW_POPUP), label(text) {
auto font_desc=label.get_pango_context()->get_font_description();
font_desc.set_size(font_desc.get_size()*2);
label.create_pango_context();
label.get_pango_context()->set_font_description(font_desc);
add(label);
property_decorated()=false;
set_accept_focus(false);
set_skip_taskbar_hint(true);
auto g_application=g_application_get_default();
auto gio_application=Glib::wrap(g_application, true);
auto application=Glib::RefPtr<Application>::cast_static(gio_application);
set_transient_for(*application->window);
set_position(Gtk::WindowPosition::WIN_POS_CENTER_ON_PARENT);
label.signal_draw().connect([this](const Cairo::RefPtr<Cairo::Context>& cr) {
label_drawn=true;
return false;
});
show_all();
}
void Dialog::Message::wait_until_drawn() {
while(gtk_events_pending() || !label_drawn)
gtk_main_iteration();
}
std::string Dialog::gtk_dialog(const std::string &title,
const std::vector<std::pair<std::string, Gtk::ResponseType>> &buttons,
Gtk::FileChooserAction gtk_options,
const std::string &file_name) {
Gtk::FileChooserDialog dialog(title, gtk_options);
auto g_application=g_application_get_default(); //TODO: Post issue that Gio::Application::get_default should return pointer and not Glib::RefPtr
auto gio_application=Glib::wrap(g_application, true);
auto application=Glib::RefPtr<Application>::cast_static(gio_application);
dialog.set_transient_for(*application->window);
auto current_path=application->window->notebook.get_current_folder();
if(current_path.empty())
current_path=boost::filesystem::current_path();
gtk_file_chooser_set_current_folder((GtkFileChooser*)dialog.gobj(), current_path.string().c_str());
if (!file_name.empty())
gtk_file_chooser_set_filename((GtkFileChooser*)dialog.gobj(), file_name.c_str());
dialog.set_position(Gtk::WindowPosition::WIN_POS_CENTER_ALWAYS);
for (auto &button : buttons)
dialog.add_button(button.first, button.second);
return dialog.run() == Gtk::RESPONSE_OK ? dialog.get_filename() : "";
}
<commit_msg>Now sets font correctly.<commit_after>#include "dialogs.h"
#include "juci.h"
#include "singletons.h"
#include <cmath>
namespace sigc {
#ifndef SIGC_FUNCTORS_DEDUCE_RESULT_TYPE_WITH_DECLTYPE
template <typename Functor>
struct functor_trait<Functor, false> {
typedef decltype (::sigc::mem_fun(std::declval<Functor&>(),
&Functor::operator())) _intermediate;
typedef typename _intermediate::result_type result_type;
typedef Functor functor_type;
};
#else
SIGC_FUNCTORS_DEDUCE_RESULT_TYPE_WITH_DECLTYPE
#endif
}
Dialog::Message::Message(const std::string &text): Gtk::Window(Gtk::WindowType::WINDOW_POPUP), label(text) {
auto font_desc=label.get_pango_context()->get_font_description();
font_desc.set_size(static_cast<int>(round(static_cast<double>(font_desc.get_size())*1.25)));
label.override_font(font_desc);
add(label);
property_decorated()=false;
set_accept_focus(false);
set_skip_taskbar_hint(true);
auto g_application=g_application_get_default();
auto gio_application=Glib::wrap(g_application, true);
auto application=Glib::RefPtr<Application>::cast_static(gio_application);
set_transient_for(*application->window);
set_position(Gtk::WindowPosition::WIN_POS_CENTER_ON_PARENT);
label.signal_draw().connect([this](const Cairo::RefPtr<Cairo::Context>& cr) {
label_drawn=true;
return false;
});
show_all();
}
void Dialog::Message::wait_until_drawn() {
while(gtk_events_pending() || !label_drawn)
gtk_main_iteration();
}
std::string Dialog::gtk_dialog(const std::string &title,
const std::vector<std::pair<std::string, Gtk::ResponseType>> &buttons,
Gtk::FileChooserAction gtk_options,
const std::string &file_name) {
Gtk::FileChooserDialog dialog(title, gtk_options);
auto g_application=g_application_get_default(); //TODO: Post issue that Gio::Application::get_default should return pointer and not Glib::RefPtr
auto gio_application=Glib::wrap(g_application, true);
auto application=Glib::RefPtr<Application>::cast_static(gio_application);
dialog.set_transient_for(*application->window);
auto current_path=application->window->notebook.get_current_folder();
if(current_path.empty())
current_path=boost::filesystem::current_path();
gtk_file_chooser_set_current_folder((GtkFileChooser*)dialog.gobj(), current_path.string().c_str());
if (!file_name.empty())
gtk_file_chooser_set_filename((GtkFileChooser*)dialog.gobj(), file_name.c_str());
dialog.set_position(Gtk::WindowPosition::WIN_POS_CENTER_ALWAYS);
for (auto &button : buttons)
dialog.add_button(button.first, button.second);
return dialog.run() == Gtk::RESPONSE_OK ? dialog.get_filename() : "";
}
<|endoftext|>
|
<commit_before>/*
* fMBT, free Model Based Testing tool
* Copyright (c) 2012, Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU Lesser General Public License,
* version 2.1, as published by the Free Software Foundation.
*
* This program is distributed in the hope 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 alongwith
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
#include "conf.hh"
#include "endhook.hh"
#include <sstream>
#include <list>
#undef FACTORY_CREATOR_PARAMS
#undef FACTORY_CREATOR_PARAMS2
#undef FACTORY_CREATE_PARAMS
class Conf;
#define FACTORY_CREATOR_PARAMS Conf* _c, std::string params
#define FACTORY_CREATOR_PARAMS2 _c, params
#define FACTORY_CREATE_PARAMS Conf* _c, std::string name, std::string params
FACTORY_CREATE(EndHook)
FACTORY_DEFAULT_CREATOR(EndHook, EndHookExit, "exit")
FACTORY_DEFAULT_CREATOR(EndHook, EndHookInteractive, "interactive")
FACTORY_ATEXIT(EndHook)
FACTORY_CREATORS(EndHook)
FACTORY_ADD_FACTORY(EndHook)
void EndHookExit::run(){
c->exit_status=exit_status;
}
void EndHookInteractive::run() {
c->exit_interactive=true;
}
void hook_delete(EndHook* e)
{
if (e) {
delete e;
}
}
void stringify_hooks(std::ostringstream& t,
const std::list<EndHook*> hl,
const std::string name)
{
for(std::list<EndHook*>::const_iterator i=hl.begin();i!=hl.end();i++) {
std::string val=(*i)->stringify();
if (val!="") {
t << name << " = " << val << std::endl;
}
}
}
void hook_runner(EndHook* e) {
if (e)
e->run();
}
std::string EndHookExit::stringify() {
if (!status) return Writable::stringify();
return "exit("+to_string(exit_status)+")";
}
EndHook* new_endhook(Conf* c,const std::string& s)
{
std::string name,option;
param_cut(s,name,option);
EndHook* ret=EndHookFactory::create(c, name, option);
if (ret) {
return ret;
}
//Let's try old thing.
split(s, name, option);
ret=EndHookFactory::create(c, name, option);
if (ret) {
fprintf(stderr,"DEPRECATED END SYNTAX. %s\nNew syntax is %s(%s)\n",
s.c_str(),name.c_str(),option.c_str());
}
return ret;
}
<commit_msg>Don't print default endhooks<commit_after>/*
* fMBT, free Model Based Testing tool
* Copyright (c) 2012, Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU Lesser General Public License,
* version 2.1, as published by the Free Software Foundation.
*
* This program is distributed in the hope 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 alongwith
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
#include "conf.hh"
#include "endhook.hh"
#include <sstream>
#include <list>
#undef FACTORY_CREATOR_PARAMS
#undef FACTORY_CREATOR_PARAMS2
#undef FACTORY_CREATE_PARAMS
class Conf;
#define FACTORY_CREATOR_PARAMS Conf* _c, std::string params
#define FACTORY_CREATOR_PARAMS2 _c, params
#define FACTORY_CREATE_PARAMS Conf* _c, std::string name, std::string params
FACTORY_CREATE(EndHook)
FACTORY_DEFAULT_CREATOR(EndHook, EndHookExit, "exit")
FACTORY_DEFAULT_CREATOR(EndHook, EndHookInteractive, "interactive")
FACTORY_ATEXIT(EndHook)
FACTORY_CREATORS(EndHook)
FACTORY_ADD_FACTORY(EndHook)
void EndHookExit::run(){
c->exit_status=exit_status;
}
void EndHookInteractive::run() {
c->exit_interactive=true;
}
void hook_delete(EndHook* e)
{
if (e) {
delete e;
}
}
void stringify_hooks(std::ostringstream& t,
const std::list<EndHook*> hl,
const std::string name)
{
std::list<EndHook*>::const_iterator i=hl.begin();
for(i++;i!=hl.end();i++) {
std::string val=(*i)->stringify();
if (val!="") {
t << name << " = " << val << std::endl;
}
}
}
void hook_runner(EndHook* e) {
if (e)
e->run();
}
std::string EndHookExit::stringify() {
if (!status) return Writable::stringify();
return "exit("+to_string(exit_status)+")";
}
EndHook* new_endhook(Conf* c,const std::string& s)
{
std::string name,option;
param_cut(s,name,option);
EndHook* ret=EndHookFactory::create(c, name, option);
if (ret) {
return ret;
}
//Let's try old thing.
split(s, name, option);
ret=EndHookFactory::create(c, name, option);
if (ret) {
fprintf(stderr,"DEPRECATED END SYNTAX. %s\nNew syntax is %s(%s)\n",
s.c_str(),name.c_str(),option.c_str());
}
return ret;
}
<|endoftext|>
|
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2009 Torus Knot Software Ltd
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 "OgreStableHeaders.h"
#include "OgreInstancedEntity.h"
#include "OgreInstanceBatch.h"
#include "OgreSkeletonInstance.h"
#include "OgreAnimationState.h"
#include "OgreOptimisedUtil.h"
#include "OgreSceneNode.h"
#include "OgreStringConverter.h"
#include "OgreCamera.h"
#include "OgreException.h"
namespace Ogre
{
NameGenerator InstancedEntity::msNameGenerator("");
InstancedEntity::InstancedEntity( InstanceBatch *batchOwner, uint32 instanceID, InstancedEntity* sharedTransformEntity ) :
MovableObject(),
mInstanceId( instanceID ),
mInUse( false ),
mBatchOwner( batchOwner ),
mAnimationState( 0 ),
mSkeletonInstance( 0 ),
mBoneMatrices(0),
mBoneWorldMatrices(0),
mLastParentXform( Matrix4::ZERO ),
mFrameAnimationLastUpdated(std::numeric_limits<unsigned long>::max()),
mSharedTransformEntity( 0 ),
mTransformLookupNumber(instanceID)
{
//Use a static name generator to ensure this name stays unique (which may not happen
//otherwise due to reparenting when defragmenting)
mName = batchOwner->getName() + "/InstancedEntity_" + StringConverter::toString(mInstanceId) + "/"+
msNameGenerator.generate();
if (sharedTransformEntity)
{
sharedTransformEntity->shareTransformWith(this);
}
else
{
createSkeletonInstance();
}
}
InstancedEntity::~InstancedEntity()
{
unlinkTransform();
destroySkeletonInstance();
}
void InstancedEntity::shareTransformWith( InstancedEntity *slave )
{
if( !this->mBatchOwner->_getMeshRef()->hasSkeleton() ||
this->mBatchOwner->_getMeshRef()->getSkeleton().isNull() ||
!this->mBatchOwner->_supportsSkeletalAnimation() )
{
return;
}
if( this->mSharedTransformEntity )
{
OGRE_EXCEPT( Exception::ERR_INVALID_STATE, "Attempted to share '" + mName + "' transforms "
"with slave '" + slave->mName + "' but '" + mName +"' is "
"already sharing. Hierarchical sharing not allowed.",
"InstancedEntity::shareTransformWith" );
}
if( this->mBatchOwner->_getMeshRef()->getSkeleton() !=
slave->mBatchOwner->_getMeshRef()->getSkeleton() )
{
OGRE_EXCEPT( Exception::ERR_INVALID_STATE, "Sharing transforms requires both instanced"
" entities to have the same skeleton",
"InstancedEntity::shareTransformWith" );
}
slave->unlinkTransform();
slave->destroySkeletonInstance();
slave->mSkeletonInstance = this->mSkeletonInstance;
slave->mAnimationState = this->mAnimationState;
slave->mBoneMatrices = this->mBoneMatrices;
if (mBatchOwner->useBoneWorldMatrices())
{
slave->mBoneWorldMatrices = this->mBoneWorldMatrices;
}
slave->mSharedTransformEntity = this;
//The sharing partners are kept in the parent entity
this->mSharingPartners.push_back( slave );
slave->mBatchOwner->_markTransformSharingDirty();
}
//-----------------------------------------------------------------------
void InstancedEntity::stopSharingTransform()
{
if( mSharedTransformEntity )
{
unlinkTransform();
createSkeletonInstance();
}
else
{
//Tell the ones sharing skeleton with us to use their own
InstancedEntityVec::const_iterator itor = mSharingPartners.begin();
InstancedEntityVec::const_iterator end = mSharingPartners.end();
while( itor != end )
{
(*itor)->stopSharingTransform();
++itor;
}
mSharingPartners.clear();
}
}
//-----------------------------------------------------------------------
const String& InstancedEntity::getMovableType(void) const
{
static String sType = "InstancedEntity";
return sType;
}
//-----------------------------------------------------------------------
size_t InstancedEntity::getTransforms( Matrix4 *xform ) const
{
size_t retVal = 1;
//When not attached, returns zero matrix to avoid rendering this one, not identity
if( mParentNode && isVisible() )
{
if( !mSkeletonInstance )
{
*xform = mBatchOwner->useBoneWorldMatrices() ?
mParentNode->_getFullTransform() : Matrix4::IDENTITY;
}
else
{
Matrix4* matrices = mBatchOwner->useBoneWorldMatrices() ? mBoneWorldMatrices : mBoneMatrices;
const Mesh::IndexMap *indexMap = mBatchOwner->_getIndexToBoneMap();
Mesh::IndexMap::const_iterator itor = indexMap->begin();
Mesh::IndexMap::const_iterator end = indexMap->end();
while( itor != end )
*xform++ = matrices[*itor++];
retVal = indexMap->size();
}
}
else
{
if( mSkeletonInstance )
retVal = mSkeletonInstance->getNumBones();
std::fill_n( xform, retVal, Matrix4::ZERO );
}
return retVal;
}
//-----------------------------------------------------------------------
size_t InstancedEntity::getTransforms3x4( float *xform ) const
{
size_t retVal;
//When not attached, returns zero matrix to avoid rendering this one, not identity
if( mParentNode && isVisible() )
{
if( !mSkeletonInstance )
{
const Matrix4& mat = mBatchOwner->useBoneWorldMatrices() ?
mParentNode->_getFullTransform() : Matrix4::IDENTITY;
for( int i=0; i<3; ++i )
{
Real const *row = mat[i];
for( int j=0; j<4; ++j )
*xform++ = *row++;
}
retVal = 12;
}
else
{
Matrix4* matrices = mBatchOwner->useBoneWorldMatrices() ? mBoneWorldMatrices : mBoneMatrices;
const Mesh::IndexMap *indexMap = mBatchOwner->_getIndexToBoneMap();
Mesh::IndexMap::const_iterator itor = indexMap->begin();
Mesh::IndexMap::const_iterator end = indexMap->end();
while( itor != end )
{
const Matrix4 &mat = matrices[*itor++];
for( int i=0; i<3; ++i )
{
Real const *row = mat[i];
for( int j=0; j<4; ++j )
*xform++ = *row++;
}
}
retVal = indexMap->size() * 4 * 3;
}
}
else
{
if( mSkeletonInstance )
retVal = mSkeletonInstance->getNumBones() * 3 * 4;
else
retVal = 12;
std::fill_n( xform, retVal, 0.0f );
}
return retVal;
}
//-----------------------------------------------------------------------
bool InstancedEntity::findVisible( Camera *camera ) const
{
//Object is explicitly visible and attached to a Node
bool retVal = isVisible() & isInScene();
//Object's bounding box is viewed by the camera
const SceneNode *parentSceneNode = getParentSceneNode();
if( parentSceneNode && camera )
retVal &= camera->isVisible( parentSceneNode->_getWorldAABB() );
return retVal;
}
//-----------------------------------------------------------------------
void InstancedEntity::createSkeletonInstance()
{
//Is mesh skeletally animated?
if( mBatchOwner->_getMeshRef()->hasSkeleton() &&
!mBatchOwner->_getMeshRef()->getSkeleton().isNull() &&
mBatchOwner->_supportsSkeletalAnimation() )
{
mSkeletonInstance = OGRE_NEW SkeletonInstance( mBatchOwner->_getMeshRef()->getSkeleton() );
mSkeletonInstance->load();
mBoneMatrices = static_cast<Matrix4*>(OGRE_MALLOC_SIMD( sizeof(Matrix4) *
mSkeletonInstance->getNumBones(),
MEMCATEGORY_ANIMATION));
if (mBatchOwner->useBoneWorldMatrices())
{
mBoneWorldMatrices = static_cast<Matrix4*>(OGRE_MALLOC_SIMD( sizeof(Matrix4) *
mSkeletonInstance->getNumBones(),
MEMCATEGORY_ANIMATION));
}
mAnimationState = OGRE_NEW AnimationStateSet();
mBatchOwner->_getMeshRef()->_initAnimationState( mAnimationState );
}
}
//-----------------------------------------------------------------------
void InstancedEntity::destroySkeletonInstance()
{
if( mSkeletonInstance )
{
//Tell the ones sharing skeleton with us to use their own
//sharing partners will remove themselves from notifyUnlink
while( mSharingPartners.empty() == false )
{
mSharingPartners.front()->stopSharingTransform();
}
mSharingPartners.clear();
OGRE_DELETE mSkeletonInstance;
OGRE_DELETE mAnimationState;
OGRE_FREE_SIMD( mBoneMatrices, MEMCATEGORY_ANIMATION );
OGRE_FREE_SIMD( mBoneWorldMatrices, MEMCATEGORY_ANIMATION );
mSkeletonInstance = 0;
mAnimationState = 0;
mBoneMatrices = 0;
mBoneWorldMatrices = 0;
}
}
//-----------------------------------------------------------------------
void InstancedEntity::unlinkTransform()
{
if( mSharedTransformEntity )
{
//Tell our master we're no longer his slave
mSharedTransformEntity->notifyUnlink( this );
mBatchOwner->_markTransformSharingDirty();
mSkeletonInstance = 0;
mAnimationState = 0;
mBoneMatrices = 0;
mBoneWorldMatrices = 0;
mSharedTransformEntity = 0;
}
}
//-----------------------------------------------------------------------
void InstancedEntity::notifyUnlink( const InstancedEntity *slave )
{
//Find the slave and remove it
InstancedEntityVec::iterator itor = mSharingPartners.begin();
InstancedEntityVec::iterator end = mSharingPartners.end();
while( itor != end )
{
if( *itor == slave )
{
std::swap(*itor,mSharingPartners.back());
mSharingPartners.pop_back();
break;
}
++itor;
}
}
//-----------------------------------------------------------------------
const AxisAlignedBox& InstancedEntity::getBoundingBox(void) const
{
//TODO: Add attached objects (TagPoints) to the bbox
return mBatchOwner->_getMeshReference()->getBounds();
}
//-----------------------------------------------------------------------
Real InstancedEntity::getBoundingRadius(void) const
{
Real rad = mBatchOwner->_getMeshReference()->getBoundingSphereRadius();
// Scale by largest scale factor
if( mParentNode )
{
const Vector3& s = mParentNode->_getDerivedScale();
rad *= std::max( Math::Abs(s.x), std::max( Math::Abs(s.y), Math::Abs(s.z) ) );
}
return rad;
}
//-----------------------------------------------------------------------
Real InstancedEntity::getSquaredViewDepth( const Camera* cam ) const
{
Real retVal = std::numeric_limits<Real>::infinity();
if( mParentNode )
retVal = mParentNode->getSquaredViewDepth( cam );
return retVal;
}
//-----------------------------------------------------------------------
void InstancedEntity::_notifyMoved(void)
{
mBatchOwner->_boundsDirty();
MovableObject::_notifyMoved();
}
//-----------------------------------------------------------------------
void InstancedEntity::_notifyAttached( Node* parent, bool isTagPoint )
{
mBatchOwner->_boundsDirty();
MovableObject::_notifyAttached( parent, isTagPoint );
}
//-----------------------------------------------------------------------
AnimationState* InstancedEntity::getAnimationState(const String& name) const
{
if (!mAnimationState)
{
OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Entity is not animated",
"InstancedEntity::getAnimationState");
}
return mAnimationState->getAnimationState(name);
}
//-----------------------------------------------------------------------
AnimationStateSet* InstancedEntity::getAllAnimationStates(void) const
{
return mAnimationState;
}
//-----------------------------------------------------------------------
bool InstancedEntity::_updateAnimation(void)
{
if (mSharedTransformEntity)
{
return mSharedTransformEntity->_updateAnimation();
}
else
{
const bool animationDirty =
(mFrameAnimationLastUpdated != mAnimationState->getDirtyFrameNumber()) ||
(mSkeletonInstance->getManualBonesDirty());
if( animationDirty || mLastParentXform != _getParentNodeFullTransform() )
{
mSkeletonInstance->setAnimationState( *mAnimationState );
mSkeletonInstance->_getBoneMatrices( mBoneMatrices );
// Cache last parent transform for next frame use too.
mLastParentXform = _getParentNodeFullTransform();
if (mBatchOwner->useBoneWorldMatrices())
{
OptimisedUtil::getImplementation()->concatenateAffineMatrices(
mLastParentXform,
mBoneMatrices,
mBoneWorldMatrices,
mSkeletonInstance->getNumBones() );
}
mFrameAnimationLastUpdated = mAnimationState->getDirtyFrameNumber();
return true;
}
}
return false;
}
}
<commit_msg>Fixed writing of partial batches in instancing by writing the correct number of zero'ed matrices for non-visible or non-existent entities.<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2009 Torus Knot Software Ltd
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 "OgreStableHeaders.h"
#include "OgreInstancedEntity.h"
#include "OgreInstanceBatch.h"
#include "OgreSkeletonInstance.h"
#include "OgreAnimationState.h"
#include "OgreOptimisedUtil.h"
#include "OgreSceneNode.h"
#include "OgreStringConverter.h"
#include "OgreCamera.h"
#include "OgreException.h"
namespace Ogre
{
NameGenerator InstancedEntity::msNameGenerator("");
InstancedEntity::InstancedEntity( InstanceBatch *batchOwner, uint32 instanceID, InstancedEntity* sharedTransformEntity ) :
MovableObject(),
mInstanceId( instanceID ),
mInUse( false ),
mBatchOwner( batchOwner ),
mAnimationState( 0 ),
mSkeletonInstance( 0 ),
mBoneMatrices(0),
mBoneWorldMatrices(0),
mLastParentXform( Matrix4::ZERO ),
mFrameAnimationLastUpdated(std::numeric_limits<unsigned long>::max()),
mSharedTransformEntity( 0 ),
mTransformLookupNumber(instanceID)
{
//Use a static name generator to ensure this name stays unique (which may not happen
//otherwise due to reparenting when defragmenting)
mName = batchOwner->getName() + "/InstancedEntity_" + StringConverter::toString(mInstanceId) + "/"+
msNameGenerator.generate();
if (sharedTransformEntity)
{
sharedTransformEntity->shareTransformWith(this);
}
else
{
createSkeletonInstance();
}
}
InstancedEntity::~InstancedEntity()
{
unlinkTransform();
destroySkeletonInstance();
}
void InstancedEntity::shareTransformWith( InstancedEntity *slave )
{
if( !this->mBatchOwner->_getMeshRef()->hasSkeleton() ||
this->mBatchOwner->_getMeshRef()->getSkeleton().isNull() ||
!this->mBatchOwner->_supportsSkeletalAnimation() )
{
return;
}
if( this->mSharedTransformEntity )
{
OGRE_EXCEPT( Exception::ERR_INVALID_STATE, "Attempted to share '" + mName + "' transforms "
"with slave '" + slave->mName + "' but '" + mName +"' is "
"already sharing. Hierarchical sharing not allowed.",
"InstancedEntity::shareTransformWith" );
}
if( this->mBatchOwner->_getMeshRef()->getSkeleton() !=
slave->mBatchOwner->_getMeshRef()->getSkeleton() )
{
OGRE_EXCEPT( Exception::ERR_INVALID_STATE, "Sharing transforms requires both instanced"
" entities to have the same skeleton",
"InstancedEntity::shareTransformWith" );
}
slave->unlinkTransform();
slave->destroySkeletonInstance();
slave->mSkeletonInstance = this->mSkeletonInstance;
slave->mAnimationState = this->mAnimationState;
slave->mBoneMatrices = this->mBoneMatrices;
if (mBatchOwner->useBoneWorldMatrices())
{
slave->mBoneWorldMatrices = this->mBoneWorldMatrices;
}
slave->mSharedTransformEntity = this;
//The sharing partners are kept in the parent entity
this->mSharingPartners.push_back( slave );
slave->mBatchOwner->_markTransformSharingDirty();
}
//-----------------------------------------------------------------------
void InstancedEntity::stopSharingTransform()
{
if( mSharedTransformEntity )
{
unlinkTransform();
createSkeletonInstance();
}
else
{
//Tell the ones sharing skeleton with us to use their own
InstancedEntityVec::const_iterator itor = mSharingPartners.begin();
InstancedEntityVec::const_iterator end = mSharingPartners.end();
while( itor != end )
{
(*itor)->stopSharingTransform();
++itor;
}
mSharingPartners.clear();
}
}
//-----------------------------------------------------------------------
const String& InstancedEntity::getMovableType(void) const
{
static String sType = "InstancedEntity";
return sType;
}
//-----------------------------------------------------------------------
size_t InstancedEntity::getTransforms( Matrix4 *xform ) const
{
size_t retVal = 1;
//When not attached, returns zero matrix to avoid rendering this one, not identity
if( mParentNode && isVisible() )
{
if( !mSkeletonInstance )
{
*xform = mBatchOwner->useBoneWorldMatrices() ?
mParentNode->_getFullTransform() : Matrix4::IDENTITY;
}
else
{
Matrix4* matrices = mBatchOwner->useBoneWorldMatrices() ? mBoneWorldMatrices : mBoneMatrices;
const Mesh::IndexMap *indexMap = mBatchOwner->_getIndexToBoneMap();
Mesh::IndexMap::const_iterator itor = indexMap->begin();
Mesh::IndexMap::const_iterator end = indexMap->end();
while( itor != end )
*xform++ = matrices[*itor++];
retVal = indexMap->size();
}
}
else
{
if( mSkeletonInstance )
retVal = mBatchOwner->_getIndexToBoneMap()->size();
std::fill_n( xform, retVal, Matrix4::ZERO );
}
return retVal;
}
//-----------------------------------------------------------------------
size_t InstancedEntity::getTransforms3x4( float *xform ) const
{
size_t retVal;
//When not attached, returns zero matrix to avoid rendering this one, not identity
if( mParentNode && isVisible() )
{
if( !mSkeletonInstance )
{
const Matrix4& mat = mBatchOwner->useBoneWorldMatrices() ?
mParentNode->_getFullTransform() : Matrix4::IDENTITY;
for( int i=0; i<3; ++i )
{
Real const *row = mat[i];
for( int j=0; j<4; ++j )
*xform++ = *row++;
}
retVal = 12;
}
else
{
Matrix4* matrices = mBatchOwner->useBoneWorldMatrices() ? mBoneWorldMatrices : mBoneMatrices;
const Mesh::IndexMap *indexMap = mBatchOwner->_getIndexToBoneMap();
Mesh::IndexMap::const_iterator itor = indexMap->begin();
Mesh::IndexMap::const_iterator end = indexMap->end();
while( itor != end )
{
const Matrix4 &mat = matrices[*itor++];
for( int i=0; i<3; ++i )
{
Real const *row = mat[i];
for( int j=0; j<4; ++j )
*xform++ = *row++;
}
}
retVal = indexMap->size() * 4 * 3;
}
}
else
{
if( mSkeletonInstance )
retVal = mBatchOwner->_getIndexToBoneMap()->size() * 3 * 4;
else
retVal = 12;
std::fill_n( xform, retVal, 0.0f );
}
return retVal;
}
//-----------------------------------------------------------------------
bool InstancedEntity::findVisible( Camera *camera ) const
{
//Object is explicitly visible and attached to a Node
bool retVal = isVisible() & isInScene();
//Object's bounding box is viewed by the camera
const SceneNode *parentSceneNode = getParentSceneNode();
if( parentSceneNode && camera )
retVal &= camera->isVisible( parentSceneNode->_getWorldAABB() );
return retVal;
}
//-----------------------------------------------------------------------
void InstancedEntity::createSkeletonInstance()
{
//Is mesh skeletally animated?
if( mBatchOwner->_getMeshRef()->hasSkeleton() &&
!mBatchOwner->_getMeshRef()->getSkeleton().isNull() &&
mBatchOwner->_supportsSkeletalAnimation() )
{
mSkeletonInstance = OGRE_NEW SkeletonInstance( mBatchOwner->_getMeshRef()->getSkeleton() );
mSkeletonInstance->load();
mBoneMatrices = static_cast<Matrix4*>(OGRE_MALLOC_SIMD( sizeof(Matrix4) *
mSkeletonInstance->getNumBones(),
MEMCATEGORY_ANIMATION));
if (mBatchOwner->useBoneWorldMatrices())
{
mBoneWorldMatrices = static_cast<Matrix4*>(OGRE_MALLOC_SIMD( sizeof(Matrix4) *
mSkeletonInstance->getNumBones(),
MEMCATEGORY_ANIMATION));
}
mAnimationState = OGRE_NEW AnimationStateSet();
mBatchOwner->_getMeshRef()->_initAnimationState( mAnimationState );
}
}
//-----------------------------------------------------------------------
void InstancedEntity::destroySkeletonInstance()
{
if( mSkeletonInstance )
{
//Tell the ones sharing skeleton with us to use their own
//sharing partners will remove themselves from notifyUnlink
while( mSharingPartners.empty() == false )
{
mSharingPartners.front()->stopSharingTransform();
}
mSharingPartners.clear();
OGRE_DELETE mSkeletonInstance;
OGRE_DELETE mAnimationState;
OGRE_FREE_SIMD( mBoneMatrices, MEMCATEGORY_ANIMATION );
OGRE_FREE_SIMD( mBoneWorldMatrices, MEMCATEGORY_ANIMATION );
mSkeletonInstance = 0;
mAnimationState = 0;
mBoneMatrices = 0;
mBoneWorldMatrices = 0;
}
}
//-----------------------------------------------------------------------
void InstancedEntity::unlinkTransform()
{
if( mSharedTransformEntity )
{
//Tell our master we're no longer his slave
mSharedTransformEntity->notifyUnlink( this );
mBatchOwner->_markTransformSharingDirty();
mSkeletonInstance = 0;
mAnimationState = 0;
mBoneMatrices = 0;
mBoneWorldMatrices = 0;
mSharedTransformEntity = 0;
}
}
//-----------------------------------------------------------------------
void InstancedEntity::notifyUnlink( const InstancedEntity *slave )
{
//Find the slave and remove it
InstancedEntityVec::iterator itor = mSharingPartners.begin();
InstancedEntityVec::iterator end = mSharingPartners.end();
while( itor != end )
{
if( *itor == slave )
{
std::swap(*itor,mSharingPartners.back());
mSharingPartners.pop_back();
break;
}
++itor;
}
}
//-----------------------------------------------------------------------
const AxisAlignedBox& InstancedEntity::getBoundingBox(void) const
{
//TODO: Add attached objects (TagPoints) to the bbox
return mBatchOwner->_getMeshReference()->getBounds();
}
//-----------------------------------------------------------------------
Real InstancedEntity::getBoundingRadius(void) const
{
Real rad = mBatchOwner->_getMeshReference()->getBoundingSphereRadius();
// Scale by largest scale factor
if( mParentNode )
{
const Vector3& s = mParentNode->_getDerivedScale();
rad *= std::max( Math::Abs(s.x), std::max( Math::Abs(s.y), Math::Abs(s.z) ) );
}
return rad;
}
//-----------------------------------------------------------------------
Real InstancedEntity::getSquaredViewDepth( const Camera* cam ) const
{
Real retVal = std::numeric_limits<Real>::infinity();
if( mParentNode )
retVal = mParentNode->getSquaredViewDepth( cam );
return retVal;
}
//-----------------------------------------------------------------------
void InstancedEntity::_notifyMoved(void)
{
mBatchOwner->_boundsDirty();
MovableObject::_notifyMoved();
}
//-----------------------------------------------------------------------
void InstancedEntity::_notifyAttached( Node* parent, bool isTagPoint )
{
mBatchOwner->_boundsDirty();
MovableObject::_notifyAttached( parent, isTagPoint );
}
//-----------------------------------------------------------------------
AnimationState* InstancedEntity::getAnimationState(const String& name) const
{
if (!mAnimationState)
{
OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Entity is not animated",
"InstancedEntity::getAnimationState");
}
return mAnimationState->getAnimationState(name);
}
//-----------------------------------------------------------------------
AnimationStateSet* InstancedEntity::getAllAnimationStates(void) const
{
return mAnimationState;
}
//-----------------------------------------------------------------------
bool InstancedEntity::_updateAnimation(void)
{
if (mSharedTransformEntity)
{
return mSharedTransformEntity->_updateAnimation();
}
else
{
const bool animationDirty =
(mFrameAnimationLastUpdated != mAnimationState->getDirtyFrameNumber()) ||
(mSkeletonInstance->getManualBonesDirty());
if( animationDirty || mLastParentXform != _getParentNodeFullTransform() )
{
mSkeletonInstance->setAnimationState( *mAnimationState );
mSkeletonInstance->_getBoneMatrices( mBoneMatrices );
// Cache last parent transform for next frame use too.
mLastParentXform = _getParentNodeFullTransform();
if (mBatchOwner->useBoneWorldMatrices())
{
OptimisedUtil::getImplementation()->concatenateAffineMatrices(
mLastParentXform,
mBoneMatrices,
mBoneWorldMatrices,
mSkeletonInstance->getNumBones() );
}
mFrameAnimationLastUpdated = mAnimationState->getDirtyFrameNumber();
return true;
}
}
return false;
}
}
<|endoftext|>
|
<commit_before>/* mbed Microcontroller Library
* Copyright (c) 2006-2015 ARM Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "drivers/I2C.h"
#include "drivers/DigitalInOut.h"
#include "platform/mbed_wait_api.h"
#if DEVICE_I2C
#if DEVICE_I2C_ASYNCH
#include "platform/mbed_power_mgmt.h"
#endif
namespace mbed {
I2C *I2C::_owner = NULL;
SingletonPtr<PlatformMutex> I2C::_mutex;
I2C::I2C(PinName sda, PinName scl) :
#if DEVICE_I2C_ASYNCH
_irq(this), _usage(DMA_USAGE_NEVER), _deep_sleep_locked(false),
#endif
_i2c(), _hz(100000)
{
lock();
// The init function also set the frequency to 100000
_sda = sda;
_scl = scl;
recover(sda, scl);
i2c_init(&_i2c, _sda, _scl);
// Used to avoid unnecessary frequency updates
_owner = this;
unlock();
}
void I2C::frequency(int hz)
{
lock();
_hz = hz;
// We want to update the frequency even if we are already the bus owners
i2c_frequency(&_i2c, _hz);
// Updating the frequency of the bus we become the owners of it
_owner = this;
unlock();
}
void I2C::aquire()
{
lock();
if (_owner != this) {
i2c_frequency(&_i2c, _hz);
_owner = this;
}
unlock();
}
// write - Master Transmitter Mode
int I2C::write(int address, const char *data, int length, bool repeated)
{
lock();
aquire();
int stop = (repeated) ? 0 : 1;
int written = i2c_write(&_i2c, address, data, length, stop);
unlock();
return length != written;
}
int I2C::write(int data)
{
lock();
int ret = i2c_byte_write(&_i2c, data);
unlock();
return ret;
}
// read - Master Receiver Mode
int I2C::read(int address, char *data, int length, bool repeated)
{
lock();
aquire();
int stop = (repeated) ? 0 : 1;
int read = i2c_read(&_i2c, address, data, length, stop);
unlock();
return length != read;
}
int I2C::read(int ack)
{
lock();
int ret;
if (ack) {
ret = i2c_byte_read(&_i2c, 0);
} else {
ret = i2c_byte_read(&_i2c, 1);
}
unlock();
return ret;
}
void I2C::start(void)
{
lock();
i2c_start(&_i2c);
unlock();
}
void I2C::stop(void)
{
lock();
i2c_stop(&_i2c);
unlock();
}
void I2C::lock()
{
_mutex->lock();
}
void I2C::unlock()
{
_mutex->unlock();
}
int I2C::recover(PinName sda, PinName scl)
{
DigitalInOut pin_sda(sda, PIN_INPUT, PullNone, 1);
DigitalInOut pin_scl(scl, PIN_INPUT, PullNone, 1);
// Read and verify if recovery is required
if (pin_scl == 1) {
if (pin_sda == 1) {
// Return successfuly as SDA and SCL is high
return 0;
}
} else {
// Return as SCL is low and no access to become master.
return I2C_ERROR_BUS_BUSY;
}
// Send clock pulses, for device to recover 9
pin_scl.mode(PullNone);
pin_scl.output();
int count = 9;
while (count--) {
pin_scl.mode(PullNone);
pin_scl = 0;
wait_us(5);
pin_scl.mode(PullUp);
pin_scl = 1;
wait_us(5);
}
// Send Stop
pin_sda.output();
pin_sda = 0;
wait_us(5);
pin_scl = 1;
wait_us(5);
pin_sda = 1;
wait_us(5);
pin_sda.input();
pin_scl.input();
if ((pin_scl == 0) || (pin_sda == 0)) {
// Return as SCL is low and no access to become master.
return I2C_ERROR_BUS_BUSY;
}
return 0;
}
#if DEVICE_I2C_ASYNCH
int I2C::transfer(int address, const char *tx_buffer, int tx_length, char *rx_buffer, int rx_length, const event_callback_t &callback, int event, bool repeated)
{
lock();
if (i2c_active(&_i2c)) {
unlock();
return -1; // transaction ongoing
}
lock_deep_sleep();
aquire();
_callback = callback;
int stop = (repeated) ? 0 : 1;
_irq.callback(&I2C::irq_handler_asynch);
i2c_transfer_asynch(&_i2c, (void *)tx_buffer, tx_length, (void *)rx_buffer, rx_length, address, stop, _irq.entry(), event, _usage);
unlock();
return 0;
}
void I2C::abort_transfer(void)
{
lock();
i2c_abort_asynch(&_i2c);
unlock_deep_sleep();
unlock();
}
void I2C::irq_handler_asynch(void)
{
int event = i2c_irq_handler_asynch(&_i2c);
if (_callback && event) {
_callback.call(event);
}
if (event) {
unlock_deep_sleep();
}
}
void I2C::lock_deep_sleep()
{
if (_deep_sleep_locked == false) {
sleep_manager_lock_deep_sleep();
_deep_sleep_locked = true;
}
}
void I2C::unlock_deep_sleep()
{
if (_deep_sleep_locked == true) {
sleep_manager_unlock_deep_sleep();
_deep_sleep_locked = false;
}
}
#endif
} // namespace mbed
#endif
<commit_msg>Addressed review comments<commit_after>/* mbed Microcontroller Library
* Copyright (c) 2006-2015 ARM Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "drivers/I2C.h"
#include "drivers/DigitalInOut.h"
#include "platform/mbed_wait_api.h"
#if DEVICE_I2C
#if DEVICE_I2C_ASYNCH
#include "platform/mbed_power_mgmt.h"
#endif
namespace mbed {
I2C *I2C::_owner = NULL;
SingletonPtr<PlatformMutex> I2C::_mutex;
I2C::I2C(PinName sda, PinName scl) :
#if DEVICE_I2C_ASYNCH
_irq(this), _usage(DMA_USAGE_NEVER), _deep_sleep_locked(false),
#endif
_i2c(), _hz(100000)
{
lock();
// The init function also set the frequency to 100000
_sda = sda;
_scl = scl;
recover(sda, scl);
i2c_init(&_i2c, _sda, _scl);
// Used to avoid unnecessary frequency updates
_owner = this;
unlock();
}
void I2C::frequency(int hz)
{
lock();
_hz = hz;
// We want to update the frequency even if we are already the bus owners
i2c_frequency(&_i2c, _hz);
// Updating the frequency of the bus we become the owners of it
_owner = this;
unlock();
}
void I2C::aquire()
{
lock();
if (_owner != this) {
i2c_frequency(&_i2c, _hz);
_owner = this;
}
unlock();
}
// write - Master Transmitter Mode
int I2C::write(int address, const char *data, int length, bool repeated)
{
lock();
aquire();
int stop = (repeated) ? 0 : 1;
int written = i2c_write(&_i2c, address, data, length, stop);
unlock();
return length != written;
}
int I2C::write(int data)
{
lock();
int ret = i2c_byte_write(&_i2c, data);
unlock();
return ret;
}
// read - Master Receiver Mode
int I2C::read(int address, char *data, int length, bool repeated)
{
lock();
aquire();
int stop = (repeated) ? 0 : 1;
int read = i2c_read(&_i2c, address, data, length, stop);
unlock();
return length != read;
}
int I2C::read(int ack)
{
lock();
int ret;
if (ack) {
ret = i2c_byte_read(&_i2c, 0);
} else {
ret = i2c_byte_read(&_i2c, 1);
}
unlock();
return ret;
}
void I2C::start(void)
{
lock();
i2c_start(&_i2c);
unlock();
}
void I2C::stop(void)
{
lock();
i2c_stop(&_i2c);
unlock();
}
void I2C::lock()
{
_mutex->lock();
}
void I2C::unlock()
{
_mutex->unlock();
}
int I2C::recover(PinName sda, PinName scl)
{
DigitalInOut pin_sda(sda, PIN_INPUT, PullNone, 1);
DigitalInOut pin_scl(scl, PIN_INPUT, PullNone, 1);
// Return as SCL is low and no access to become master.
if (pin_scl == 0) {
return I2C_ERROR_BUS_BUSY;
}
// Return successfully as SDA and SCL is high
if (pin_sda == 1) {
return 0;
}
// Send clock pulses, for device to recover 9
pin_scl.mode(PullNone);
pin_scl.output();
for (int count = 0; count < 10; count++) {
pin_scl.mode(PullNone);
pin_scl = 0;
wait_us(5);
pin_scl.mode(PullUp);
pin_scl = 1;
wait_us(5);
}
// Send Stop
pin_sda.output();
pin_sda = 0;
wait_us(5);
pin_scl = 1;
wait_us(5);
pin_sda = 1;
wait_us(5);
pin_sda.input();
pin_scl.input();
if ((pin_scl == 0) || (pin_sda == 0)) {
// Return as SCL is low and no access to become master.
return I2C_ERROR_BUS_BUSY;
}
return 0;
}
#if DEVICE_I2C_ASYNCH
int I2C::transfer(int address, const char *tx_buffer, int tx_length, char *rx_buffer, int rx_length, const event_callback_t &callback, int event, bool repeated)
{
lock();
if (i2c_active(&_i2c)) {
unlock();
return -1; // transaction ongoing
}
lock_deep_sleep();
aquire();
_callback = callback;
int stop = (repeated) ? 0 : 1;
_irq.callback(&I2C::irq_handler_asynch);
i2c_transfer_asynch(&_i2c, (void *)tx_buffer, tx_length, (void *)rx_buffer, rx_length, address, stop, _irq.entry(), event, _usage);
unlock();
return 0;
}
void I2C::abort_transfer(void)
{
lock();
i2c_abort_asynch(&_i2c);
unlock_deep_sleep();
unlock();
}
void I2C::irq_handler_asynch(void)
{
int event = i2c_irq_handler_asynch(&_i2c);
if (_callback && event) {
_callback.call(event);
}
if (event) {
unlock_deep_sleep();
}
}
void I2C::lock_deep_sleep()
{
if (_deep_sleep_locked == false) {
sleep_manager_lock_deep_sleep();
_deep_sleep_locked = true;
}
}
void I2C::unlock_deep_sleep()
{
if (_deep_sleep_locked == true) {
sleep_manager_unlock_deep_sleep();
_deep_sleep_locked = false;
}
}
#endif
} // namespace mbed
#endif
<|endoftext|>
|
<commit_before>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// On Tizen installing applications requires super-user powers primarily because
// some pieces of information of the application are put on globally accessible
// locations. This helper will run with super-user powers (via suid) and will
// be called by Crosswalk (now running as a normal user) so all the activities
// that required 'root' access are done by a small code base.
#if defined(OS_TIZEN_MOBILE)
#include <pkgmgr/pkgmgr_parser.h>
#else
// So we can compile this on Linux Desktop
static int pkgmgr_parser_parse_manifest_for_installation(
const char* path, char *const tagv[]) {
return 0;
}
static int pkgmgr_parser_parse_manifest_for_uninstallation(
const char* path, char *const tagv[]) {
return 0;
}
#endif
#include "base/files/file_path.h"
#include "base/file_util.h"
namespace {
const base::FilePath kIconDir("/opt/share/icons/default/small/");
const base::FilePath kXmlDir("/opt/share/packages/");
const base::FilePath kXWalkLauncherBinary("/usr/bin/xwalk-launcher");
class FileDeleter {
public:
FileDeleter(const base::FilePath& path, bool recursive)
: path_(path),
recursive_(recursive) {}
~FileDeleter() {
if (path_.empty())
return;
base::DeleteFile(path_, recursive_);
}
void Dismiss() {
path_.clear();
}
private:
base::FilePath path_;
bool recursive_;
};
bool InstallApplication(const char* appid, const char* xmlpath,
const char* iconpath) {
base::FilePath icon_src(iconpath);
// icon_dst == /opt/share/icons/default/small/<appid>.png
// FIXME(vcgomes): Add support for more icon types
base::FilePath icon_dst = kIconDir.Append(std::string(appid) + ".png");
if (!base::CopyFile(icon_src, icon_dst)) {
fprintf(stdout, "Couldn't copy application icon to '%s'\n",
icon_dst.value().c_str());
return false;
}
FileDeleter icon_cleaner(icon_dst, false);
base::FilePath xml_src(xmlpath);
base::FilePath xml_dst = kXmlDir.Append(std::string(appid) + ".xml");
if (!base::CopyFile(xml_src, xml_dst)) {
fprintf(stdout, "Couldn't copy application XML metadata to '%s'\n",
xml_dst.value().c_str());
return false;
}
FileDeleter xml_cleaner(xml_dst, false);
if (pkgmgr_parser_parse_manifest_for_installation(xmlpath, NULL)) {
fprintf(stdout, "Couldn't parse manifest XML '%s'\n", xmlpath);
return false;
}
icon_cleaner.Dismiss();
xml_cleaner.Dismiss();
return true;
}
bool UninstallApplication(const char* appid) {
bool result = true;
char iconname[PATH_MAX];
// FIXME(vcgomes): Add support for more icon types
base::FilePath icon_dst = kIconDir.Append(std::string(appid) + ".png");
if (!base::DeleteFile(icon_dst, false)) {
fprintf(stdout, "Couldn't delete '%s'\n", icon_dst.value().c_str());
result = false;
}
base::FilePath xmlpath(kXmlDir);
xmlpath = xmlpath.Append(std::string(appid) + ".xml");
int ret = pkgmgr_parser_parse_manifest_for_uninstallation(
xmlpath.value().c_str(), NULL);
if (ret) {
fprintf(stdout, "Couldn't parse manifest XML '%s'\n",
xmlpath.value().c_str());
result = false;
}
if (!base::DeleteFile(xmlpath, false)) {
fprintf(stdout, "Couldn't delete '%s'\n", xmlpath.value().c_str());
result = false;
}
return result;
}
int usage(const char* program) {
fprintf(stdout, "%s - Crosswalk Tizen Application Installation helper\n\n",
basename(program));
fprintf(stdout, "Usage: \n"
"\t%s --install <appid> <xml> <icon>\n"
"\t%s --uninstall <appid>\n",
program, program);
return 1;
}
} // namespace
int main(int argc, char *argv[]) {
bool result = false;
if (argc <= 2)
return usage(argv[0]);
if (!strcmp(argv[1], "--install")) {
if (argc != 5)
return usage(argv[0]);
result = InstallApplication(argv[2], argv[3], argv[4]);
} else if (!strcmp(argv[1], "--uninstall")) {
if (argc != 3)
return usage(argv[0]);
result = UninstallApplication(argv[2]);
} else {
return usage(argv[0]);
}
// Convetion is to return 0 on success.
return result ? 0 : 1;
}
<commit_msg>[Application][Tizen] Change the effective UID of the application to 'root'<commit_after>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// On Tizen installing applications requires super-user powers primarily because
// some pieces of information of the application are put on globally accessible
// locations. This helper will run with super-user powers (via suid) and will
// be called by Crosswalk (now running as a normal user) so all the activities
// that required 'root' access are done by a small code base.
#if defined(OS_TIZEN_MOBILE)
#include <pkgmgr/pkgmgr_parser.h>
#else
// So we can compile this on Linux Desktop
static int pkgmgr_parser_parse_manifest_for_installation(
const char* path, char *const tagv[]) {
return 0;
}
static int pkgmgr_parser_parse_manifest_for_uninstallation(
const char* path, char *const tagv[]) {
return 0;
}
#endif
#include "base/files/file_path.h"
#include "base/file_util.h"
namespace {
const base::FilePath kIconDir("/opt/share/icons/default/small/");
const base::FilePath kXmlDir("/opt/share/packages/");
const base::FilePath kXWalkLauncherBinary("/usr/bin/xwalk-launcher");
class FileDeleter {
public:
FileDeleter(const base::FilePath& path, bool recursive)
: path_(path),
recursive_(recursive) {}
~FileDeleter() {
if (path_.empty())
return;
base::DeleteFile(path_, recursive_);
}
void Dismiss() {
path_.clear();
}
private:
base::FilePath path_;
bool recursive_;
};
bool InstallApplication(const char* appid, const char* xmlpath,
const char* iconpath) {
base::FilePath icon_src(iconpath);
// icon_dst == /opt/share/icons/default/small/<appid>.png
// FIXME(vcgomes): Add support for more icon types
base::FilePath icon_dst = kIconDir.Append(std::string(appid) + ".png");
if (!base::CopyFile(icon_src, icon_dst)) {
fprintf(stdout, "Couldn't copy application icon to '%s'\n",
icon_dst.value().c_str());
return false;
}
FileDeleter icon_cleaner(icon_dst, false);
base::FilePath xml_src(xmlpath);
base::FilePath xml_dst = kXmlDir.Append(std::string(appid) + ".xml");
if (!base::CopyFile(xml_src, xml_dst)) {
fprintf(stdout, "Couldn't copy application XML metadata to '%s'\n",
xml_dst.value().c_str());
return false;
}
FileDeleter xml_cleaner(xml_dst, false);
if (pkgmgr_parser_parse_manifest_for_installation(xmlpath, NULL)) {
fprintf(stdout, "Couldn't parse manifest XML '%s'\n", xmlpath);
return false;
}
icon_cleaner.Dismiss();
xml_cleaner.Dismiss();
return true;
}
bool UninstallApplication(const char* appid) {
bool result = true;
char iconname[PATH_MAX];
// FIXME(vcgomes): Add support for more icon types
base::FilePath icon_dst = kIconDir.Append(std::string(appid) + ".png");
if (!base::DeleteFile(icon_dst, false)) {
fprintf(stdout, "Couldn't delete '%s'\n", icon_dst.value().c_str());
result = false;
}
base::FilePath xmlpath(kXmlDir);
xmlpath = xmlpath.Append(std::string(appid) + ".xml");
int ret = pkgmgr_parser_parse_manifest_for_uninstallation(
xmlpath.value().c_str(), NULL);
if (ret) {
fprintf(stdout, "Couldn't parse manifest XML '%s'\n",
xmlpath.value().c_str());
result = false;
}
if (!base::DeleteFile(xmlpath, false)) {
fprintf(stdout, "Couldn't delete '%s'\n", xmlpath.value().c_str());
result = false;
}
return result;
}
int usage(const char* program) {
fprintf(stdout, "%s - Crosswalk Tizen Application Installation helper\n\n",
basename(program));
fprintf(stdout, "Usage: \n"
"\t%s --install <appid> <xml> <icon>\n"
"\t%s --uninstall <appid>\n",
program, program);
return 1;
}
} // namespace
int main(int argc, char *argv[]) {
bool result = false;
if (argc <= 2)
return usage(argv[0]);
// When installing an application on Tizen, the libraries used require
// some steps to be run as root (UID 0) and fail otherwise, so we force
// this tool to assume the root UID.
if (setuid(0)) {
fprintf(stderr, "Make sure '%s' is set-user-ID-root\n", argv[0]);
return 1;;
}
if (!strcmp(argv[1], "--install")) {
if (argc != 5)
return usage(argv[0]);
result = InstallApplication(argv[2], argv[3], argv[4]);
} else if (!strcmp(argv[1], "--uninstall")) {
if (argc != 3)
return usage(argv[0]);
result = UninstallApplication(argv[2]);
} else {
return usage(argv[0]);
}
// Convetion is to return 0 on success.
return result ? 0 : 1;
}
<|endoftext|>
|
<commit_before>#include "palabos3D.h"
#include "palabos3D.hh"
#include <vector>
#include <cmath>
using namespace plb;
using namespace plb::descriptors;
using namespace std;
typedef double T;
typedef Array<T,3> Velocity;
//#define DESCRIPTOR descriptors::D3Q27Descriptor
#define DESCRIPTOR MRTD3Q19Descriptor
typedef MRTdynamics<T,DESCRIPTOR> BackgroundDynamics;
typedef AnechoicMRTdynamics<T,DESCRIPTOR> AnechoicBackgroundDynamics;
// ---------------------------------------------
// Includes of acoustics resources
#include "acoustics/acoustics3D.h"
using namespace plb_acoustics_3D;
// ---------------------------------------------
const T rho0 = 1;
const T drho = rho0/10;
void writeGifs(MultiBlockLattice3D<T,DESCRIPTOR>& lattice, plint iter){
const plint nx = lattice.getNx();
const plint ny = lattice.getNy();
const plint nz = lattice.getNz();
const plint imSize = 600;
ImageWriter<T> imageWriter("leeloo");
Box3D slice(0, nx-1, 0, ny-1, nz/2, nz/2);
//imageWriter.writeGif(createFileName("u", iT, 6),
//*computeDensity(lattice), );
imageWriter.writeGif( createFileName("rho", iter, 6),
*computeDensity(lattice, slice),
(T) rho0 - drho/1000000, (T) rho0 + drho/1000000, imSize, imSize);
}
void writeVTK(MultiBlockLattice3D<T,DESCRIPTOR>& lattice, plint iter){
VtkImageOutput3D<T> vtkOut(createFileName("vtk", iter, 6), 1.);
vtkOut.writeData<float>(*computeDensity(lattice), "density", 1.);
vtkOut.writeData<3,float>(*computeVelocity(lattice), "velocity", 1.);
}
int main(int argc, char **argv){
plbInit(&argc, &argv);
std::string fNameOut = "tmp";
const plint nx = 150;
const plint ny = 100;
const plint nz = 100;
const T lattice_speed_sound = 1/sqrt(3);
const T omega = 1.985;
const plint maxT = 120000;
Array<T,3> u0(0, 0, 0);
global::directories().setOutputDir(fNameOut+"/");
// Setting anechoic dynamics like this way
MultiBlockLattice3D<T, DESCRIPTOR> lattice(nx, ny, nz, new AnechoicBackgroundDynamics(omega));
defineDynamics(lattice, lattice.getBoundingBox(), new BackgroundDynamics(omega));
pcout << "Creation of the lattice." << endl;
// Switch off periodicity.
lattice.periodicity().toggleAll(false);
pcout << "Initilization of rho and u." << endl;
initializeAtEquilibrium( lattice, lattice.getBoundingBox(), rho0 , u0 );
T rhoBar_target = 0;
const T mach_number = 0.2;
const T velocity_flow = mach_number*lattice_speed_sound;
Array<T,3> j_target(velocity_flow, 0, 0);
T size_anechoic_buffer = 20;
defineAnechoicMRTBoards(nx, ny, nz, lattice, size_anechoic_buffer,
omega, j_target, j_target, j_target, j_target, j_target, j_target,
rhoBar_target);
lattice.initialize();
pcout << std::endl << "Voxelizing the domain." << std::endl;
pcout << "Simulation begins" << endl;
plb_ofstream history_pressures("tmp/history_pressures.dat");
plb_ofstream history_velocities_x("tmp/history_velocities_x.dat");
plb_ofstream history_velocities_y("tmp/history_velocities_y.dat");
plb_ofstream history_velocities_z("tmp/history_velocities_z.dat");
for (plint iT=0; iT<maxT; ++iT){
if (iT == 0){
//T lattice_speed_sound = 1/sqrt(3);
//T rho_changing = 1. + drho*sin(2*M_PI*(lattice_speed_sound/20)*iT);
Box3D impulse(nx/2, nx/2, ny/2, ny/2, nz/2, nz/2);
initializeAtEquilibrium( lattice, impulse, rho0 + drho, u0);
}
if (iT % 10 == 0 && iT>0) {
pcout << "Iteration " << iT << endl;
//writeGifs(lattice,iT);
writeVTK(lattice, iT);
}
history_pressures << setprecision(10) << lattice.get(nx/2+30, ny/2+30, nz/2+30).computeDensity() - rho0 << endl;
Array<T,3> velocities;
lattice.get(nx/2+30, ny/2+30, nz/2+30).computeVelocity(velocities);
history_velocities_x << setprecision(10) << velocities[0]/lattice_speed_sound << endl;
history_velocities_y << setprecision(10) << velocities[1]/lattice_speed_sound << endl;
history_velocities_z << setprecision(10) << velocities[2]/lattice_speed_sound << endl;
lattice.collideAndStream();
}
pcout << "End of simulation at iteration " << endl;
}
<commit_msg>update duct radiation<commit_after>#include "palabos3D.h"
#include "palabos3D.hh"
#include <vector>
#include <cmath>
using namespace plb;
using namespace plb::descriptors;
using namespace std;
typedef double T;
typedef Array<T,3> Velocity;
//#define DESCRIPTOR descriptors::D3Q27Descriptor
#define DESCRIPTOR MRTD3Q19Descriptor
typedef MRTdynamics<T,DESCRIPTOR> BackgroundDynamics;
typedef AnechoicMRTdynamics<T,DESCRIPTOR> AnechoicBackgroundDynamics;
// ---------------------------------------------
// Includes of acoustics resources
#include "acoustics/acoustics3D.h"
using namespace plb_acoustics_3D;
// ---------------------------------------------
const T rho0 = 1;
const T drho = rho0/10;
void writeGifs(MultiBlockLattice3D<T,DESCRIPTOR>& lattice, plint iter){
const plint nx = lattice.getNx();
const plint ny = lattice.getNy();
const plint nz = lattice.getNz();
const plint imSize = 600;
ImageWriter<T> imageWriter("leeloo");
Box3D slice(0, nx-1, 0, ny-1, nz/2, nz/2);
//imageWriter.writeGif(createFileName("u", iT, 6),
//*computeDensity(lattice), );
imageWriter.writeGif( createFileName("rho", iter, 6),
*computeDensity(lattice, slice),
(T) rho0 - drho/1000000, (T) rho0 + drho/1000000, imSize, imSize);
}
void writeVTK(MultiBlockLattice3D<T,DESCRIPTOR>& lattice, plint iter){
VtkImageOutput3D<T> vtkOut(createFileName("vtk", iter, 6), 1.);
vtkOut.writeData<float>(*computeDensity(lattice), "density", 1.);
vtkOut.writeData<3,float>(*computeVelocity(lattice), "velocity", 1.);
}
int main(int argc, char **argv){
plbInit(&argc, &argv);
std::string fNameOut = "tmp";
const plint nx = 150;
const plint ny = 100;
const plint nz = 100;
const T lattice_speed_sound = 1/sqrt(3);
const T omega = 1.985;
const plint maxT = 120000;
Array<T,3> u0(0, 0, 0);
global::directories().setOutputDir(fNameOut+"/");
//Build geometry
// Create the cylinder surface as a set of triangles.
T radius = 20.;
Array<T,3> originalCenter(0, 0, 0);
TriangleSet<T> triangleSet;
triangleSet = constructSphere<T>(originalCenter, radius, (plint)40);
// tube to more efficient data structures that are internally used by palabos.
// The TriangleBoundary3D structure will be later used to assign proper boundary conditions.
plint borderWidth = 1; // Because the Guo boundary condition acts in a one-cell layer.
// Requirement: margin>=borderWidth.
plint margin = 1 + borderWidth; // Extra margin of allocated cells around the obstacle.
plint extraLayer = 0; // Make the bounding box larger; for visualization purposes
// only. For the simulation, it is OK to have extraLayer=0.
DEFscaledMesh<T> defMesh(triangleSet, 40, 1, margin, extraLayer);
pcout << "Valor do Dx: " << defMesh.getDx() << std::endl;
Array<T, 3> physical_position = defMesh.getPhysicalLocation();
pcout << "posicao fisica em x: " << physical_position[0] << std::endl;
pcout << "posicao fisica em y: " << physical_position[1] << std::endl;
pcout << "posicao fisica em z: " << physical_position[2] << std::endl;
Array< T, 3 > position_lattice(50, ny/2, nz/2);
defMesh.setPhysicalLocation(position_lattice);
Array<T, 3> physical_position_c = defMesh.getPhysicalLocation();
pcout << "posicao fisica em x_c: " << physical_position_c[0] << std::endl;
pcout << "posicao fisica em y_c: " << physical_position_c[1] << std::endl;
pcout << "posicao fisica em z_c: " << physical_position_c[2] << std::endl;
defMesh.getMesh().inflate();
TriangleBoundary3D<T> boundary(defMesh);
boundary.getMesh().writeBinarySTL("cylinder.stl");
pcout << "Number of triangles: " << boundary.getMesh().getNumTriangles() << std::endl;
// handled by the following voxelization process.
pcout << std::endl << "Voxelizing the domain." << std::endl;
const int flowType = voxelFlag::outside;
const plint extendedEnvelopeWidth = 2;
const plint blockSize = 20; // Zero means: no sparse representation.
// Because the Guo boundary condition needs 2-cell neighbor access.
VoxelizedDomain3D<T> voxelizedDomain (
boundary, flowType, extraLayer, borderWidth, extendedEnvelopeWidth, blockSize);
pcout << getMultiBlockInfo(voxelizedDomain.getVoxelMatrix()) << std::endl;
//-------------------------------------
//Set geometry in lattice
// The Guo off *lattice boundary condition is set up.
pcout << "Creating boundary condition." << std::endl;
BoundaryProfiles3D<T,Velocity> profiles;
bool useAllDirections = true; // Extrapolation scheme for the off *lattice boundary condition.
GuoOffLatticeModel3D<T,DESCRIPTOR>* model =
new GuoOffLatticeModel3D<T,DESCRIPTOR> (
new TriangleFlowShape3D<T,Array<T,3> > (
voxelizedDomain.getBoundary(), profiles),
flowType, useAllDirections );
bool useRegularized = true;
// Use an off *lattice boundary condition which is closer in spirit to
// regularized boundary conditions.
model->selectUseRegularizedModel(useRegularized);
// Setting anechoic dynamics like this way
MultiBlockLattice3D<T, DESCRIPTOR> lattice(nx, ny, nz, new AnechoicBackgroundDynamics(omega));
defineDynamics(lattice, lattice.getBoundingBox(), new BackgroundDynamics(omega));
OffLatticeBoundaryCondition3D<T,DESCRIPTOR,Velocity> boundaryCondition (
model, voxelizedDomain, lattice);
boundaryCondition.insert();
defineDynamics(lattice, voxelizedDomain.getVoxelMatrix(),
lattice.getBoundingBox(), new NoDynamics<T,DESCRIPTOR>(), voxelFlag::inside);
pcout << "Creation of the lattice." << endl;
// Switch off periodicity.
lattice.periodicity().toggleAll(false);
pcout << "Initilization of rho and u." << endl;
initializeAtEquilibrium( lattice, lattice.getBoundingBox(), rho0 , u0 );
T rhoBar_target = 0;
const T mach_number = 0.2;
const T velocity_flow = mach_number*lattice_speed_sound;
Array<T,3> j_target(velocity_flow, 0, 0);
T size_anechoic_buffer = 20;
/*defineAnechoicMRTBoards(nx, ny, nz, lattice, size_anechoic_buffer,
omega, j_target, j_target, j_target, j_target, j_target, j_target,
rhoBar_target);*/
lattice.initialize();
pcout << std::endl << "Voxelizing the domain." << std::endl;
pcout << "Simulation begins" << endl;
plb_ofstream history_pressures("tmp/history_pressures.dat");
plb_ofstream history_velocities_x("tmp/history_velocities_x.dat");
plb_ofstream history_velocities_y("tmp/history_velocities_y.dat");
plb_ofstream history_velocities_z("tmp/history_velocities_z.dat");
for (plint iT=0; iT<maxT; ++iT){
if (iT == 0){
//T lattice_speed_sound = 1/sqrt(3);
//T rho_changing = 1. + drho*sin(2*M_PI*(lattice_speed_sound/20)*iT);
Box3D impulse(nx/2, nx/2, ny/2, ny/2, nz/2, nz/2);
initializeAtEquilibrium( lattice, impulse, rho0 + drho, u0);
}
if (iT % 10 == 0 && iT>0) {
pcout << "Iteration " << iT << endl;
//writeGifs(lattice,iT);
writeVTK(lattice, iT);
}
history_pressures << setprecision(10) << lattice.get(nx/2+30, ny/2+30, nz/2+30).computeDensity() - rho0 << endl;
Array<T,3> velocities;
lattice.get(nx/2+30, ny/2+30, nz/2+30).computeVelocity(velocities);
history_velocities_x << setprecision(10) << velocities[0]/lattice_speed_sound << endl;
history_velocities_y << setprecision(10) << velocities[1]/lattice_speed_sound << endl;
history_velocities_z << setprecision(10) << velocities[2]/lattice_speed_sound << endl;
lattice.collideAndStream();
}
pcout << "End of simulation at iteration " << endl;
}
<|endoftext|>
|
<commit_before>#include "palabos3D.h"
#include "palabos3D.hh"
#include <vector>
#include <cmath>
using namespace plb;
using namespace plb::descriptors;
using namespace std;
typedef double T;
typedef Array<T,3> Velocity;
//#define DESCRIPTOR descriptors::D3Q27Descriptor
#define DESCRIPTOR MRTD3Q19Descriptor
typedef MRTdynamics<T,DESCRIPTOR> BackgroundDynamics;
typedef AnechoicMRTdynamics<T,DESCRIPTOR> AnechoicBackgroundDynamics;
// ---------------------------------------------
// Includes of acoustics resources
#include "acoustics/acoustics3D.h"
using namespace plb_acoustics_3D;
// ---------------------------------------------
const T rho0 = 1;
const T drho = rho0/10;
void writeGifs(MultiBlockLattice3D<T,DESCRIPTOR>& lattice, plint iter){
const plint nx = lattice.getNx();
const plint ny = lattice.getNy();
const plint nz = lattice.getNz();
const plint imSize = 600;
ImageWriter<T> imageWriter("leeloo");
Box3D slice(0, nx-1, 0, ny-1, nz/2, nz/2);
//imageWriter.writeGif(createFileName("u", iT, 6),
//*computeDensity(lattice), );
imageWriter.writeGif( createFileName("rho", iter, 6),
*computeDensity(lattice, slice),
(T) rho0 - drho/1000000, (T) rho0 + drho/1000000, imSize, imSize);
}
void writeVTK(MultiBlockLattice3D<T,DESCRIPTOR>& lattice, plint iter){
VtkImageOutput3D<T> vtkOut(createFileName("vtk", iter, 6), 1.);
vtkOut.writeData<float>(*computeDensity(lattice), "density", 1.);
vtkOut.writeData<3,float>(*computeVelocity(lattice), "velocity", 1.);
}
int main(int argc, char **argv){
plbInit(&argc, &argv);
std::string fNameOut = "tmp";
const plint nx = 350;
const plint ny = 160;
const plint nz = 160;
const T lattice_speed_sound = 1/sqrt(3);
const T cs2 = lattice_speed_sound*lattice_speed_sound;
const T omega = 1.985;
const plint maxT = 10000;
const plint maxT_final_source = maxT - 1000;
const T ka_max = 1.82;
const T ka_min = 0;
Array<T,3> u0(0, 0, 0);
global::directories().setOutputDir(fNameOut+"/");
//Build geometry
Array<T,3> centerLB(30, ny/2, nz/2);
//TriangleSet<T> triangleSet("Duto_Fechado.STL");
//Array<T,3> center(param.cx, param.cy, param.cz);
TriangleSet<T> triangleSet;
pcout << "construindo o duto" << std::endl;
/*
(Array<T,3> const& inletCenter, T externRadius, T internRadius,
T length, plint nAxial, plint nCirc)
*/
T thickness_duct = 4;
T radius = 20;
triangleSet = constructDuct(centerLB, radius + thickness_duct, radius
, (T) 250, (plint) 10, (plint) 50);
//triangleSet = constructSphere<T>(centerLB, (T) 10, (plint)40);
/*TriangleSet<T> triangleSet("duto_fechado.STL");
triangleSet.translate(centerLB);*/
// rotate: Z, X, Y in radians
//triangleSet.rotate((T) 0, (T) 0, (T) 0);
//triangleSet.scale((T) 3.95253e+2);
// tube to more efficient data structures that are internally used by palabos.
// The TriangleBoundary3D structure will be later used to assign proper boundary conditions.
plint borderWidth = 1; // Because the Guo boundary condition acts in a one-cell layer.
// Requirement: margin>=borderWidth.
plint margin = 1; // Extra margin of allocated cells around the obstacle.
plint extraLayer = 0; // Make the bounding box larger; for visualization purposes
// only. For the simulation, it is OK to have extraLayer=0.
plint xDirection = 0;
DEFscaledMesh<T> defMesh(triangleSet, 0, xDirection, margin, Dot3D(0, 0, 0));
defMesh.setDx((T) 1.);
pcout << "Valor do Dx: " << defMesh.getDx() << std::endl;
Array<T, 3> physical_position = defMesh.getPhysicalLocation();
pcout << "posicao fisica em x: " << physical_position[0] << std::endl;
pcout << "posicao fisica em y: " << physical_position[1] << std::endl;
pcout << "posicao fisica em z: " << physical_position[2] << std::endl;
//Array< T, 3 > position_lattice(50, ny/2, nz/2);
//defMesh.setPhysicalLocation(position_lattice);
Array<T, 3> physical_position_c = defMesh.getPhysicalLocation();
pcout << "posicao fisica em x_c: " << physical_position_c[0] << std::endl;
pcout << "posicao fisica em y_c: " << physical_position_c[1] << std::endl;
pcout << "posicao fisica em z_c: " << physical_position_c[2] << std::endl;
defMesh.getMesh().inflate();
TriangleBoundary3D<T> boundary(defMesh);
boundary.getMesh().writeBinarySTL("duct.stl");
pcout << "Number of triangles: " << boundary.getMesh().getNumTriangles() << std::endl;
// handled by the following voxelization process.
pcout << std::endl << "Voxelizing the domain." << std::endl;
const int flowType = voxelFlag::outside;
const plint extendedEnvelopeWidth = 2;
const plint blockSize = 0; // Zero means: no sparse representation.
// Because the Guo boundary condition needs 2-cell neighbor access.
Box3D full_domain(0, nx-1, 0, ny-1, 0, nz-1);
VoxelizedDomain3D<T> voxelizedDomain (
boundary, flowType, full_domain, borderWidth, extendedEnvelopeWidth, blockSize);
pcout << getMultiBlockInfo(voxelizedDomain.getVoxelMatrix()) << std::endl;
// Build lattice and set default dynamics
//-------------------------------------
MultiBlockLattice3D<T,DESCRIPTOR> *lattice =
new MultiBlockLattice3D<T,DESCRIPTOR>(voxelizedDomain.getVoxelMatrix());
// Setting anechoic dynamics like this way
defineDynamics(*lattice, lattice->getBoundingBox(),
new AnechoicBackgroundDynamics(omega));
defineDynamics(*lattice, lattice->getBoundingBox(),
new BackgroundDynamics(omega));
//-------------------------------------
//Set geometry in lattice
// The Guo off *lattice boundary condition is set up.
pcout << "Creating boundary condition." << std::endl;
BoundaryProfiles3D<T,Velocity> profiles;
//profiles.setWallProfile(new NoSlipProfile3D<T>);
bool useAllDirections = true; // Extrapolation scheme for the off *lattice boundary condition.
GuoOffLatticeModel3D<T,DESCRIPTOR>* model =
new GuoOffLatticeModel3D<T,DESCRIPTOR> (
new TriangleFlowShape3D<T,Array<T,3> > (
voxelizedDomain.getBoundary(), profiles),
flowType, useAllDirections );
bool useRegularized = true;
// Use an off *lattice boundary condition which is closer in spirit to
// regularized boundary conditions.
model->selectUseRegularizedModel(useRegularized);
// ---
OffLatticeBoundaryCondition3D<T,DESCRIPTOR,Velocity> boundaryCondition (
model, voxelizedDomain, *lattice);
boundaryCondition.insert();
defineDynamics(*lattice, voxelizedDomain.getVoxelMatrix(),
lattice->getBoundingBox(), new NoDynamics<T,DESCRIPTOR>(-999), voxelFlag::inside);
pcout << "Creation of the lattice." << endl;
// Switch off periodicity.
lattice->periodicity().toggleAll(false);
pcout << "Initilization of rho and u." << endl;
initializeAtEquilibrium( *lattice, lattice->getBoundingBox(), rho0 , u0 );
// Set anechoic condition on boundaries
T rhoBar_target = 0;
const T mach_number = 0.2;
const T velocity_flow = mach_number*lattice_speed_sound;
Array<T,3> j_target(0, 0, 0);
T size_anechoic_buffer = 30;
defineAnechoicMRTBoards(nx, ny, nz, *lattice, size_anechoic_buffer,
omega, j_target, j_target, j_target, j_target, j_target, j_target,
rhoBar_target);
lattice->initialize();
pcout << std::endl << "Voxelizing the domain." << std::endl;
pcout << "Simulation begins" << endl;
plb_ofstream history_pressures("tmp/history_pressures.dat");
plb_ofstream history_velocities_x("tmp/history_velocities_x.dat");
plb_ofstream history_velocities_y("tmp/history_velocities_y.dat");
plb_ofstream history_velocities_z("tmp/history_velocities_z.dat");
for (plint iT=0; iT<maxT; ++iT){
if (iT <= maxT_final_source){
//drho*sin(2*M_PI*(lattice_speed_sound/20)*iT);
//drho*cos((lattice_speed_sound/radius)*(ka_max*((maxT-iT)/maxT)));
T initial_frequency = ka_min*lattice_speed_sound/(2*M_PI*radius);
T frequency_max_lattice = ka_max*lattice_speed_sound/(2*M_PI*radius);
T variation_frequency = (frequency_max_lattice - initial_frequency)/maxT_final_source;
T frequency_function = initial_frequency*iT + (variation_frequency*iT*iT)/2;
T phase = 2*M_PI*frequency_function;
T chirp_hand = 1. + drho*sin(phase);
T rho_changing = 1. + drho*sin(2*M_PI*(lattice_speed_sound/20)*iT);
//Box3D impulse(nx/2 + 50, nx/2 + 50, ny/2 + 50, ny/2 + 50, nz/2 + 50, nz/2 + 50);
plint source_radius = radius;
Box3D test_source(centerLB[0] + 10, centerLB[0] + 15,
ny/2 - source_radius/sqrt(2),
ny/2 + source_radius/sqrt(2),
nz/2 - source_radius/sqrt(2),
nz/2 + source_radius/sqrt(2));
//Box3D impulse(centerLB[0] + 10, centerLB[0] + 10, ny/2, ny/2, nz/2, nz/2);
initializeAtEquilibrium( *lattice, test_source, chirp_hand, u0);
}else{
plint source_radius = radius;
Box3D test_source(centerLB[0] + 10, centerLB[0] + 15,
ny/2 - source_radius/sqrt(2),
ny/2 + source_radius/sqrt(2),
nz/2 - source_radius/sqrt(2),
nz/2 + source_radius/sqrt(2));
initializeAtEquilibrium( *lattice, test_source, rho0, u0);
}
if (iT % 10 == 0 && iT>0) {
pcout << "Iteration " << iT << endl;
//writeGifs(lattice,iT);
//writeVTK(*lattice, iT);
}
// extract values of pressure and velocities
Box3D surface_probe(6*radius, 6*radius, ny/2 - radius/sqrt(2),
ny/2 + radius/sqrt(2),
nz/2 - radius/sqrt(2),
nz/2 + radius/sqrt(2));
history_pressures << setprecision(10) << (computeAverageDensity(*lattice, surface_probe) - rho0)*cs2 << endl;
history_velocities_x << setprecision(10) <<
boundaryCondition.computeAverageVelocityComponent(surface_probe, 0)/lattice_speed_sound << endl;
history_velocities_y << setprecision(10) <<
boundaryCondition.computeAverageVelocityComponent(surface_probe, 1)/lattice_speed_sound << endl;
history_velocities_z << setprecision(10) <<
boundaryCondition.computeAverageVelocityComponent(surface_probe, 2)/lattice_speed_sound << endl;
lattice->collideAndStream();
}
pcout << "End of simulation at iteration " << endl;
}
<commit_msg>Duct size done<commit_after>#include "palabos3D.h"
#include "palabos3D.hh"
#include <vector>
#include <cmath>
using namespace plb;
using namespace plb::descriptors;
using namespace std;
typedef double T;
typedef Array<T,3> Velocity;
//#define DESCRIPTOR descriptors::D3Q27Descriptor
#define DESCRIPTOR MRTD3Q19Descriptor
typedef MRTdynamics<T,DESCRIPTOR> BackgroundDynamics;
typedef AnechoicMRTdynamics<T,DESCRIPTOR> AnechoicBackgroundDynamics;
// ---------------------------------------------
// Includes of acoustics resources
#include "acoustics/acoustics3D.h"
using namespace plb_acoustics_3D;
// ---------------------------------------------
const T rho0 = 1;
const T drho = rho0/10;
void writeGifs(MultiBlockLattice3D<T,DESCRIPTOR>& lattice, plint iter){
const plint nx = lattice.getNx();
const plint ny = lattice.getNy();
const plint nz = lattice.getNz();
const plint imSize = 600;
ImageWriter<T> imageWriter("leeloo");
Box3D slice(0, nx-1, 0, ny-1, nz/2, nz/2);
//imageWriter.writeGif(createFileName("u", iT, 6),
//*computeDensity(lattice), );
imageWriter.writeGif( createFileName("rho", iter, 6),
*computeDensity(lattice, slice),
(T) rho0 - drho/1000000, (T) rho0 + drho/1000000, imSize, imSize);
}
void writeVTK(MultiBlockLattice3D<T,DESCRIPTOR>& lattice, plint iter){
VtkImageOutput3D<T> vtkOut(createFileName("vtk", iter, 6), 1.);
vtkOut.writeData<float>(*computeDensity(lattice), "density", 1.);
vtkOut.writeData<3,float>(*computeVelocity(lattice), "velocity", 1.);
}
int main(int argc, char **argv){
plbInit(&argc, &argv);
std::string fNameOut = "tmp";
const T radius = 11;
const T diameter = 2*radius;
const plint nx = 23*diameter;
const plint ny = 20*diameter;
const plint nz = 20*diameter;
const T lattice_speed_sound = 1/sqrt(3);
const T cs2 = lattice_speed_sound*lattice_speed_sound;
const T omega = 1.985;
const plint maxT = 10000;
const plint maxT_final_source = maxT - 1000;
const T ka_max = 1.82;
const T ka_min = 0;
Array<T,3> u0(0, 0, 0);
global::directories().setOutputDir(fNameOut+"/");
//Build geometry
Array<T,3> centerLB(30, ny/2, nz/2);
//TriangleSet<T> triangleSet("Duto_Fechado.STL");
//Array<T,3> center(param.cx, param.cy, param.cz);
TriangleSet<T> triangleSet;
pcout << "construindo o duto" << std::endl;
/*
(Array<T,3> const& inletCenter, T externRadius, T internRadius,
T length, plint nAxial, plint nCirc)
*/
T thickness_duct = 4;
T size_duct = 11*diameter;
triangleSet = constructDuct(centerLB, radius + thickness_duct, radius
, (T) size_duct, (plint) 10, (plint) 50);
//triangleSet = constructSphere<T>(centerLB, (T) 10, (plint)40);
/*TriangleSet<T> triangleSet("duto_fechado.STL");
triangleSet.translate(centerLB);*/
// rotate: Z, X, Y in radians
//triangleSet.rotate((T) 0, (T) 0, (T) 0);
//triangleSet.scale((T) 3.95253e+2);
// tube to more efficient data structures that are internally used by palabos.
// The TriangleBoundary3D structure will be later used to assign proper boundary conditions.
plint borderWidth = 1; // Because the Guo boundary condition acts in a one-cell layer.
// Requirement: margin>=borderWidth.
plint margin = 1; // Extra margin of allocated cells around the obstacle.
plint extraLayer = 0; // Make the bounding box larger; for visualization purposes
// only. For the simulation, it is OK to have extraLayer=0.
plint xDirection = 0;
DEFscaledMesh<T> defMesh(triangleSet, 0, xDirection, margin, Dot3D(0, 0, 0));
defMesh.setDx((T) 1.);
pcout << "Valor do Dx: " << defMesh.getDx() << std::endl;
Array<T, 3> physical_position = defMesh.getPhysicalLocation();
pcout << "posicao fisica em x: " << physical_position[0] << std::endl;
pcout << "posicao fisica em y: " << physical_position[1] << std::endl;
pcout << "posicao fisica em z: " << physical_position[2] << std::endl;
//Array< T, 3 > position_lattice(50, ny/2, nz/2);
//defMesh.setPhysicalLocation(position_lattice);
Array<T, 3> physical_position_c = defMesh.getPhysicalLocation();
pcout << "posicao fisica em x_c: " << physical_position_c[0] << std::endl;
pcout << "posicao fisica em y_c: " << physical_position_c[1] << std::endl;
pcout << "posicao fisica em z_c: " << physical_position_c[2] << std::endl;
defMesh.getMesh().inflate();
TriangleBoundary3D<T> boundary(defMesh);
boundary.getMesh().writeBinarySTL("duct.stl");
pcout << "Number of triangles: " << boundary.getMesh().getNumTriangles() << std::endl;
// handled by the following voxelization process.
pcout << std::endl << "Voxelizing the domain." << std::endl;
const int flowType = voxelFlag::outside;
const plint extendedEnvelopeWidth = 2;
const plint blockSize = 0; // Zero means: no sparse representation.
// Because the Guo boundary condition needs 2-cell neighbor access.
Box3D full_domain(0, nx-1, 0, ny-1, 0, nz-1);
VoxelizedDomain3D<T> voxelizedDomain (
boundary, flowType, full_domain, borderWidth, extendedEnvelopeWidth, blockSize);
pcout << getMultiBlockInfo(voxelizedDomain.getVoxelMatrix()) << std::endl;
// Build lattice and set default dynamics
//-------------------------------------
MultiBlockLattice3D<T,DESCRIPTOR> *lattice =
new MultiBlockLattice3D<T,DESCRIPTOR>(voxelizedDomain.getVoxelMatrix());
// Setting anechoic dynamics like this way
defineDynamics(*lattice, lattice->getBoundingBox(),
new AnechoicBackgroundDynamics(omega));
defineDynamics(*lattice, lattice->getBoundingBox(),
new BackgroundDynamics(omega));
//-------------------------------------
//Set geometry in lattice
// The Guo off *lattice boundary condition is set up.
pcout << "Creating boundary condition." << std::endl;
BoundaryProfiles3D<T,Velocity> profiles;
//profiles.setWallProfile(new NoSlipProfile3D<T>);
bool useAllDirections = true; // Extrapolation scheme for the off *lattice boundary condition.
GuoOffLatticeModel3D<T,DESCRIPTOR>* model =
new GuoOffLatticeModel3D<T,DESCRIPTOR> (
new TriangleFlowShape3D<T,Array<T,3> > (
voxelizedDomain.getBoundary(), profiles),
flowType, useAllDirections );
bool useRegularized = true;
// Use an off *lattice boundary condition which is closer in spirit to
// regularized boundary conditions.
model->selectUseRegularizedModel(useRegularized);
// ---
OffLatticeBoundaryCondition3D<T,DESCRIPTOR,Velocity> boundaryCondition (
model, voxelizedDomain, *lattice);
boundaryCondition.insert();
defineDynamics(*lattice, voxelizedDomain.getVoxelMatrix(),
lattice->getBoundingBox(), new NoDynamics<T,DESCRIPTOR>(-999), voxelFlag::inside);
pcout << "Creation of the lattice." << endl;
// Switch off periodicity.
lattice->periodicity().toggleAll(false);
pcout << "Initilization of rho and u." << endl;
initializeAtEquilibrium( *lattice, lattice->getBoundingBox(), rho0 , u0 );
// Set anechoic condition on boundaries
T rhoBar_target = 0;
const T mach_number = 0.2;
const T velocity_flow = mach_number*lattice_speed_sound;
Array<T,3> j_target(0, 0, 0);
T size_anechoic_buffer = 30;
defineAnechoicMRTBoards(nx, ny, nz, *lattice, size_anechoic_buffer,
omega, j_target, j_target, j_target, j_target, j_target, j_target,
rhoBar_target);
lattice->initialize();
pcout << std::endl << "Voxelizing the domain." << std::endl;
pcout << "Simulation begins" << endl;
// Setting probes
plint position_x_3r = centerLB[0] + size_duct - 3*radius;
Box3D surface_probe_3r(position_x_3r, position_x_3r, ny/2 - radius/sqrt(2),
ny/2 + radius/sqrt(2),
nz/2 - radius/sqrt(2),
nz/2 + radius/sqrt(2));
plint position_x_4r = centerLB[0] + size_duct - 4*radius;
Box3D surface_probe_4r(position_x_4r, position_x_4r, ny/2 - radius/sqrt(2),
ny/2 + radius/sqrt(2),
nz/2 - radius/sqrt(2),
nz/2 + radius/sqrt(2));
plint position_x_6r = centerLB[0] + size_duct - 6*radius;
Box3D surface_probe_6r(position_x_6r, position_x_6r, ny/2 - radius/sqrt(2),
ny/2 + radius/sqrt(2),
nz/2 - radius/sqrt(2),
nz/2 + radius/sqrt(2));
plb_ofstream history_pressures_3r("tmp/history_pressures_3r.dat");
plb_ofstream history_pressures_4r("tmp/history_pressures_4r.dat");
plb_ofstream history_pressures_6r("tmp/history_pressures_6r.dat");
plb_ofstream history_velocities_3r("tmp/history_velocities_3r.dat");
plb_ofstream history_velocities_4r("tmp/history_velocities_4r.dat");
plb_ofstream history_velocities_6r("tmp/history_velocities_6r.dat");
for (plint iT=0; iT<maxT; ++iT){
if (iT <= maxT_final_source){
//drho*sin(2*M_PI*(lattice_speed_sound/20)*iT);
//drho*cos((lattice_speed_sound/radius)*(ka_max*((maxT-iT)/maxT)));
T initial_frequency = ka_min*lattice_speed_sound/(2*M_PI*radius);
T frequency_max_lattice = ka_max*lattice_speed_sound/(2*M_PI*radius);
T variation_frequency = (frequency_max_lattice - initial_frequency)/maxT_final_source;
T frequency_function = initial_frequency*iT + (variation_frequency*iT*iT)/2;
T phase = 2*M_PI*frequency_function;
T chirp_hand = 1. + drho*sin(phase);
T rho_changing = 1. + drho*sin(2*M_PI*(lattice_speed_sound/20)*iT);
//Box3D impulse(nx/2 + 50, nx/2 + 50, ny/2 + 50, ny/2 + 50, nz/2 + 50, nz/2 + 50);
plint source_radius = radius;
Box3D test_source(centerLB[0] + 10, centerLB[0] + 15,
ny/2 - source_radius/sqrt(2),
ny/2 + source_radius/sqrt(2),
nz/2 - source_radius/sqrt(2),
nz/2 + source_radius/sqrt(2));
//Box3D impulse(centerLB[0] + 10, centerLB[0] + 10, ny/2, ny/2, nz/2, nz/2);
initializeAtEquilibrium( *lattice, test_source, chirp_hand, u0);
}else{
plint source_radius = radius;
Box3D test_source(centerLB[0] + 10, centerLB[0] + 15,
ny/2 - source_radius/sqrt(2),
ny/2 + source_radius/sqrt(2),
nz/2 - source_radius/sqrt(2),
nz/2 + source_radius/sqrt(2));
initializeAtEquilibrium( *lattice, test_source, rho0, u0);
}
if (iT % 10 == 0 && iT>0) {
pcout << "Iteration " << iT << endl;
//writeGifs(lattice,iT);
writeVTK(*lattice, iT);
}
// extract values of pressure and velocities
history_pressures_3r << setprecision(10) << (computeAverageDensity(*lattice, surface_probe_3r) - rho0)*cs2 << endl;
history_pressures_4r << setprecision(10) << (computeAverageDensity(*lattice, surface_probe_4r) - rho0)*cs2 << endl;
history_pressures_6r << setprecision(10) << (computeAverageDensity(*lattice, surface_probe_6r) - rho0)*cs2 << endl;
history_velocities_3r << setprecision(10) <<
boundaryCondition.computeAverageVelocityComponent(surface_probe_3r, 0)/lattice_speed_sound << endl;
history_velocities_4r << setprecision(10) <<
boundaryCondition.computeAverageVelocityComponent(surface_probe_4r, 1)/lattice_speed_sound << endl;
history_velocities_6r << setprecision(10) <<
boundaryCondition.computeAverageVelocityComponent(surface_probe_6r, 2)/lattice_speed_sound << endl;
lattice->collideAndStream();
}
pcout << "End of simulation at iteration " << endl;
}
<|endoftext|>
|
<commit_before>/*
* mod_dup - duplicates apache requests
*
* Copyright (C) 2013 Orange
*
* 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 "mod_dup.hh"
#include "Utils.hh"
#include <boost/shared_ptr.hpp>
#include <http_config.h>
namespace DupModule {
/*
* Callback to iterate over the headers tables
* Pushes a copy of key => value in a list passed without typing as the first argument
*/
static int iterateOverHeadersCallBack(void *d, const char *key, const char *value) {
RequestInfo::tHeaders *headers = reinterpret_cast<RequestInfo::tHeaders *>(d);
headers->push_back(std::pair<std::string, std::string>(key, value));
return 1;
}
static void
prepareRequestInfo(DupConf *tConf, request_rec *pRequest, RequestInfo &r) {
// Copy headers in
apr_table_do(&iterateOverHeadersCallBack, &r.mHeadersIn, pRequest->headers_in, NULL);
// Add the elapsed time header
r.mHeadersOut.push_back(std::make_pair(std::string("ELAPSED_TIME_BY_DUP"), boost::lexical_cast<std::string>(r.getElapsedTimeMS())));
// Basic
r.mPoison = false;
r.mConfPath = tConf->dirName;
r.mPath = pRequest->uri;
r.mArgs = pRequest->args ? pRequest->args : "";
}
static void
printRequest(request_rec *pRequest, RequestInfo *pBH, DupConf *tConf) {
const char *reqId = apr_table_get(pRequest->headers_in, CommonModule::c_UNIQUE_ID);
Log::debug("### Pushing a request with ID: %s, body size:%ld", reqId, pBH->mBody.size());
Log::debug("### Uri:%s, dir name:%s", pRequest->uri, tConf->dirName);
Log::debug("### Request args: %s", pRequest->args);
}
apr_status_t
inputFilterHandler(ap_filter_t *pFilter, apr_bucket_brigade *pB, ap_input_mode_t pMode, apr_read_type_e pBlock, apr_off_t pReadbytes) {
request_rec *pRequest = pFilter->r;
if (!pRequest || !pRequest->per_dir_config) {
return ap_get_brigade(pFilter->next, pB, pMode, pBlock, pReadbytes);
}
struct DupConf *conf = reinterpret_cast<DupConf *>(ap_get_module_config(pRequest->per_dir_config, &dup_module));
if (!conf || !conf->dirName) {
// Not a location that we treat, we decline the request
return ap_get_brigade(pFilter->next, pB, pMode, pBlock, pReadbytes);
}
RequestInfo *info;
if (!pFilter->ctx) {
// Unique request id
std::string uid = CommonModule::getOrSetUniqueID(pRequest);
info = new RequestInfo(uid);
// Allocation on a shared pointer on the request pool
// We guarantee that whatever happens, the RequestInfo will be deleted
void *space = apr_palloc(pRequest->pool, sizeof(boost::shared_ptr<RequestInfo>));
new (space) boost::shared_ptr<RequestInfo>(info);
// Registering of the shared pointer destructor on the pool
apr_pool_cleanup_register(pRequest->pool, space, cleaner<boost::shared_ptr<RequestInfo> >,
apr_pool_cleanup_null);
// Backup in request context
ap_set_module_config(pRequest->request_config, &dup_module, (void *)space);
// Backup in filter context
pFilter->ctx = info;
info->mConfPath = conf->dirName;
info->mArgs = pRequest->args ? pRequest->args : "";
}
if (pFilter->ctx != (void *) -1) {
// Request not read yet
info = reinterpret_cast<RequestInfo *>(pFilter->ctx);
apr_status_t st = ap_get_brigade(pFilter->next, pB, pMode, pBlock, pReadbytes);
if (st != APR_SUCCESS) {
pFilter->ctx = (void *) -1;
return st;
}
// Concats the brigade content to the reqinfo
for (apr_bucket *b = APR_BRIGADE_FIRST(pB);
b != APR_BRIGADE_SENTINEL(pB);
b = APR_BUCKET_NEXT(b) ) {
// Metadata end of stream
if (APR_BUCKET_IS_EOS(b)) {
return APR_SUCCESS;
}
if (APR_BUCKET_IS_METADATA(b))
continue;
const char *data = 0;
apr_size_t len = 0;
apr_status_t rv = apr_bucket_read(b, &data, &len, APR_BLOCK_READ);
if (rv != APR_SUCCESS) {
Log::error(42, "Bucket read failed, skipping the rest of the body");
return rv;
}
if (len) {
info->mBody.append(data, len);
}
}
}
// Data is read
return APR_SUCCESS;
}
/**
* Output Body filter handler
* Writes the response body to the RequestInfo
* Unless not needed because we only duplicate request and no reponses
*/
apr_status_t
outputBodyFilterHandler(ap_filter_t *pFilter, apr_bucket_brigade *pBrigade) {
request_rec *pRequest = pFilter->r;
apr_status_t rv;
// Reject requests that do not meet our requirements
if ((pFilter->ctx == (void *) -1) || !pRequest || !pRequest->per_dir_config) {
rv = ap_pass_brigade(pFilter->next, pBrigade);
apr_brigade_cleanup(pBrigade);
return rv;
}
struct DupConf *tConf = reinterpret_cast<DupConf *>(ap_get_module_config(pRequest->per_dir_config, &dup_module));
if ((!tConf) || (!tConf->dirName) || (tConf->getHighestDuplicationType() == DuplicationType::NONE)) {
rv = ap_pass_brigade(pFilter->next, pBrigade);
apr_brigade_cleanup(pBrigade);
return rv;
}
boost::shared_ptr<RequestInfo> * reqInfo(reinterpret_cast<boost::shared_ptr<RequestInfo> *>(ap_get_module_config(pFilter->r->request_config, &dup_module)));
if (!reqInfo || !reqInfo->get()) {
pFilter->ctx = (void *) -1;
rv = ap_pass_brigade(pFilter->next, pBrigade);
apr_brigade_cleanup(pBrigade);
return rv;
}
RequestInfo * ri = reqInfo->get();
// Write the response body to the RequestInfo if found
apr_bucket *currentBucket;
for ( currentBucket = APR_BRIGADE_FIRST(pBrigade);
currentBucket != APR_BRIGADE_SENTINEL(pBrigade);
currentBucket = APR_BUCKET_NEXT(currentBucket) ) {
if (APR_BUCKET_IS_EOS(currentBucket)) {
ri->eos_seen(true);
pFilter->ctx = (void *) -1;
rv = ap_pass_brigade(pFilter->next, pBrigade);
apr_brigade_cleanup(pBrigade);
return rv;
}
if (APR_BUCKET_IS_METADATA(currentBucket))
continue;
// We need to get the highest one as we haven't matched which rule it is yet
if (tConf->getHighestDuplicationType() == DuplicationType::REQUEST_WITH_ANSWER) {
const char *data;
apr_size_t len;
rv = apr_bucket_read(currentBucket, &data, &len, APR_BLOCK_READ);
if ((rv == APR_SUCCESS) && data) {
// Appends the part read to the answer
ri->mAnswer.append(data, len);
}
}
}
rv = ap_pass_brigade(pFilter->next, pBrigade);
apr_brigade_cleanup(pBrigade);
return rv;
}
/**
* Output filter handler
* Retrieves in/out headers
* Pushes the RequestInfo object to the RequestProcessor
*/
apr_status_t
outputHeadersFilterHandler(ap_filter_t *pFilter, apr_bucket_brigade *pBrigade) {
apr_status_t rv;
if ( pFilter->ctx == (void *) -1 ) {
rv = ap_pass_brigade(pFilter->next, pBrigade);
apr_brigade_cleanup(pBrigade);
return rv;
}
request_rec *pRequest = pFilter->r;
// Reject requests that do not meet our requirements
if (!pRequest || !pRequest->per_dir_config) {
pFilter->ctx = (void *) -1;
rv = ap_pass_brigade(pFilter->next, pBrigade);
apr_brigade_cleanup(pBrigade);
return rv;
}
struct DupConf *tConf = reinterpret_cast<DupConf *>(ap_get_module_config(pRequest->per_dir_config, &dup_module));
if ((!tConf) || (!tConf->dirName) || (tConf->getHighestDuplicationType() == DuplicationType::NONE)) {
pFilter->ctx = (void *) -1;
rv = ap_pass_brigade(pFilter->next, pBrigade);
apr_brigade_cleanup(pBrigade);
return rv;
}
boost::shared_ptr<RequestInfo> * reqInfo(reinterpret_cast<boost::shared_ptr<RequestInfo> *>(ap_get_module_config(pFilter->r->request_config, &dup_module)));
if (!reqInfo || !reqInfo->get()) {
pFilter->ctx = (void *) -1;
rv = ap_pass_brigade(pFilter->next, pBrigade);
apr_brigade_cleanup(pBrigade);
return rv;
}
RequestInfo *ri = reqInfo->get();
// Copy headers out
apr_table_do(&iterateOverHeadersCallBack, &ri->mHeadersOut, pRequest->headers_out, NULL);
if (!ri->eos_seen()) {
rv = ap_pass_brigade(pFilter->next, pBrigade);
apr_brigade_cleanup(pBrigade);
return rv;
}
// Pushing the answer to the processor
prepareRequestInfo(tConf, pRequest, *ri);
if ( tConf->synchronous ) {
static __thread CURL * lCurl = NULL;
if ( ! lCurl ) {
lCurl = gProcessor->initCurl();
}
gProcessor->runOne(*ri, lCurl);
}
else {
gThreadPool->push(*reqInfo);
}
pFilter->ctx = (void *) -1;
printRequest(pRequest, ri, tConf);
rv = ap_pass_brigade(pFilter->next, pBrigade);
apr_brigade_cleanup(pBrigade);
return rv;
}
};
<commit_msg>fix for when outputFilter is called before inputFilter, which happens when response body is large (>=8k)<commit_after>/*
* mod_dup - duplicates apache requests
*
* Copyright (C) 2013 Orange
*
* 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 "mod_dup.hh"
#include "Utils.hh"
#include <boost/shared_ptr.hpp>
#include <http_config.h>
namespace DupModule {
/*
* Callback to iterate over the headers tables
* Pushes a copy of key => value in a list passed without typing as the first argument
*/
static int iterateOverHeadersCallBack(void *d, const char *key, const char *value) {
RequestInfo::tHeaders *headers = reinterpret_cast<RequestInfo::tHeaders *>(d);
headers->push_back(std::pair<std::string, std::string>(key, value));
return 1;
}
static void
prepareRequestInfo(DupConf *tConf, request_rec *pRequest, RequestInfo &r) {
// Copy headers in
apr_table_do(&iterateOverHeadersCallBack, &r.mHeadersIn, pRequest->headers_in, NULL);
// Add the elapsed time header
r.mHeadersOut.push_back(std::make_pair(std::string("ELAPSED_TIME_BY_DUP"), boost::lexical_cast<std::string>(r.getElapsedTimeMS())));
// Basic
r.mPoison = false;
r.mConfPath = tConf->dirName;
r.mPath = pRequest->uri;
r.mArgs = pRequest->args ? pRequest->args : "";
}
static void
printRequest(request_rec *pRequest, RequestInfo *pBH, DupConf *tConf) {
const char *reqId = apr_table_get(pRequest->headers_in, CommonModule::c_UNIQUE_ID);
Log::debug("### Pushing a request with ID: %s, body size:%ld", reqId, pBH->mBody.size());
Log::debug("### Uri:%s, dir name:%s", pRequest->uri, tConf->dirName);
Log::debug("### Request args: %s", pRequest->args);
}
apr_status_t
inputFilterHandler(ap_filter_t *pFilter, apr_bucket_brigade *pB, ap_input_mode_t pMode, apr_read_type_e pBlock, apr_off_t pReadbytes) {
request_rec *pRequest = pFilter->r;
if (!pRequest || !pRequest->per_dir_config) {
return ap_get_brigade(pFilter->next, pB, pMode, pBlock, pReadbytes);
}
struct DupConf *conf = reinterpret_cast<DupConf *>(ap_get_module_config(pRequest->per_dir_config, &dup_module));
if (!conf || !conf->dirName) {
// Not a location that we treat, we decline the request
return ap_get_brigade(pFilter->next, pB, pMode, pBlock, pReadbytes);
}
RequestInfo *info = NULL;
if (!pFilter->ctx) {
boost::shared_ptr<RequestInfo> * reqInfo(reinterpret_cast<boost::shared_ptr<RequestInfo> *>(ap_get_module_config(pFilter->r->request_config, &dup_module)));
if (!reqInfo || !reqInfo->get()) {
// Unique request id
std::string uid = CommonModule::getOrSetUniqueID(pRequest);
info = new RequestInfo(uid);
// Allocation on a shared pointer on the request pool
// We guarantee that whatever happens, the RequestInfo will be deleted
void *space = apr_palloc(pRequest->pool, sizeof(boost::shared_ptr<RequestInfo>));
reqInfo = new (space) boost::shared_ptr<RequestInfo>(info);
// Registering of the shared pointer destructor on the pool
apr_pool_cleanup_register(pRequest->pool, space, cleaner<boost::shared_ptr<RequestInfo> >,
apr_pool_cleanup_null);
// Backup in request context
ap_set_module_config(pRequest->request_config, &dup_module, (void *)space);
// Backup in filter context
info->mConfPath = conf->dirName;
info->mArgs = pRequest->args ? pRequest->args : "";
}
pFilter->ctx = reqInfo->get();
}
if (pFilter->ctx != (void *) -1) {
// Request not read yet
info = reinterpret_cast<RequestInfo *>(pFilter->ctx);
apr_status_t st = ap_get_brigade(pFilter->next, pB, pMode, pBlock, pReadbytes);
if (st != APR_SUCCESS) {
pFilter->ctx = (void *) -1;
return st;
}
// Concats the brigade content to the reqinfo
for (apr_bucket *b = APR_BRIGADE_FIRST(pB);
b != APR_BRIGADE_SENTINEL(pB);
b = APR_BUCKET_NEXT(b) ) {
// Metadata end of stream
if (APR_BUCKET_IS_EOS(b)) {
return APR_SUCCESS;
}
if (APR_BUCKET_IS_METADATA(b))
continue;
const char *data = 0;
apr_size_t len = 0;
apr_status_t rv = apr_bucket_read(b, &data, &len, APR_BLOCK_READ);
if (rv != APR_SUCCESS) {
Log::error(42, "Bucket read failed, skipping the rest of the body");
return rv;
}
if (len) {
info->mBody.append(data, len);
}
}
}
// Data is read
return APR_SUCCESS;
}
/**
* Output Body filter handler
* Writes the response body to the RequestInfo
* Unless not needed because we only duplicate request and no reponses
*/
apr_status_t
outputBodyFilterHandler(ap_filter_t *pFilter, apr_bucket_brigade *pBrigade) {
request_rec *pRequest = pFilter->r;
apr_status_t rv;
// Reject requests that do not meet our requirements
if ((pFilter->ctx == (void *) -1) || !pRequest || !pRequest->per_dir_config) {
rv = ap_pass_brigade(pFilter->next, pBrigade);
apr_brigade_cleanup(pBrigade);
return rv;
}
struct DupConf *tConf = reinterpret_cast<DupConf *>(ap_get_module_config(pRequest->per_dir_config, &dup_module));
if ((!tConf) || (!tConf->dirName) || (tConf->getHighestDuplicationType() == DuplicationType::NONE)) {
rv = ap_pass_brigade(pFilter->next, pBrigade);
apr_brigade_cleanup(pBrigade);
return rv;
}
RequestInfo * ri = NULL;
boost::shared_ptr<RequestInfo> * reqInfo(reinterpret_cast<boost::shared_ptr<RequestInfo> *>(ap_get_module_config(pFilter->r->request_config, &dup_module)));
if (!reqInfo || !reqInfo->get()) {
if (!pFilter->ctx) {
// Unique request id
std::string uid = CommonModule::getOrSetUniqueID(pRequest);
ri = new RequestInfo(uid);
// Allocation on a shared pointer on the request pool
// We guarantee that whatever happens, the RequestInfo will be deleted
void *space = apr_palloc(pRequest->pool, sizeof(boost::shared_ptr<RequestInfo>));
reqInfo = new (space) boost::shared_ptr<RequestInfo>(ri);
// Registering of the shared pointer destructor on the pool
apr_pool_cleanup_register(pRequest->pool, space, cleaner<boost::shared_ptr<RequestInfo> >,
apr_pool_cleanup_null);
// Backup in request context
ap_set_module_config(pRequest->request_config, &dup_module, (void *)space);
// Backup in filter context
pFilter->ctx = ri;
ri->mConfPath = tConf->dirName;
ri->mArgs = pRequest->args ? pRequest->args : "";
} else {
// Should not happen
pFilter->ctx = (void *) -1;
rv = ap_pass_brigade(pFilter->next, pBrigade);
apr_brigade_cleanup(pBrigade);
return rv;
}
} else {
ri = reqInfo->get();
}
// Write the response body to the RequestInfo if found
apr_bucket *currentBucket;
for ( currentBucket = APR_BRIGADE_FIRST(pBrigade);
currentBucket != APR_BRIGADE_SENTINEL(pBrigade);
currentBucket = APR_BUCKET_NEXT(currentBucket) ) {
if (APR_BUCKET_IS_EOS(currentBucket)) {
ri->eos_seen(true);
pFilter->ctx = (void *) -1;
rv = ap_pass_brigade(pFilter->next, pBrigade);
apr_brigade_cleanup(pBrigade);
return rv;
}
if (APR_BUCKET_IS_METADATA(currentBucket))
continue;
// We need to get the highest one as we haven't matched which rule it is yet
if (tConf->getHighestDuplicationType() == DuplicationType::REQUEST_WITH_ANSWER) {
const char *data;
apr_size_t len;
rv = apr_bucket_read(currentBucket, &data, &len, APR_BLOCK_READ);
if ((rv == APR_SUCCESS) && data) {
// Appends the part read to the answer
ri->mAnswer.append(data, len);
}
}
}
rv = ap_pass_brigade(pFilter->next, pBrigade);
apr_brigade_cleanup(pBrigade);
return rv;
}
/**
* Output filter handler
* Retrieves in/out headers
* Pushes the RequestInfo object to the RequestProcessor
*/
apr_status_t
outputHeadersFilterHandler(ap_filter_t *pFilter, apr_bucket_brigade *pBrigade) {
apr_status_t rv;
if ( pFilter->ctx == (void *) -1 ) {
rv = ap_pass_brigade(pFilter->next, pBrigade);
apr_brigade_cleanup(pBrigade);
return rv;
}
request_rec *pRequest = pFilter->r;
// Reject requests that do not meet our requirements
if (!pRequest || !pRequest->per_dir_config) {
pFilter->ctx = (void *) -1;
rv = ap_pass_brigade(pFilter->next, pBrigade);
apr_brigade_cleanup(pBrigade);
return rv;
}
struct DupConf *tConf = reinterpret_cast<DupConf *>(ap_get_module_config(pRequest->per_dir_config, &dup_module));
if ((!tConf) || (!tConf->dirName) || (tConf->getHighestDuplicationType() == DuplicationType::NONE)) {
pFilter->ctx = (void *) -1;
rv = ap_pass_brigade(pFilter->next, pBrigade);
apr_brigade_cleanup(pBrigade);
return rv;
}
RequestInfo * ri = NULL;
boost::shared_ptr<RequestInfo> * reqInfo(reinterpret_cast<boost::shared_ptr<RequestInfo> *>(ap_get_module_config(pFilter->r->request_config, &dup_module)));
if (!reqInfo || !reqInfo->get()) {
if (!pFilter->ctx) {
// Unique request id
std::string uid = CommonModule::getOrSetUniqueID(pRequest);
ri = new RequestInfo(uid);
// Allocation on a shared pointer on the request pool
// We guarantee that whatever happens, the RequestInfo will be deleted
void *space = apr_palloc(pRequest->pool, sizeof(boost::shared_ptr<RequestInfo>));
reqInfo = new (space) boost::shared_ptr<RequestInfo>(ri);
// Registering of the shared pointer destructor on the pool
apr_pool_cleanup_register(pRequest->pool, space, cleaner<boost::shared_ptr<RequestInfo> >,
apr_pool_cleanup_null);
// Backup in request context
ap_set_module_config(pRequest->request_config, &dup_module, (void *)space);
// Backup in filter context
pFilter->ctx = ri;
ri->mConfPath = tConf->dirName;
ri->mArgs = pRequest->args ? pRequest->args : "";
} else {
// Should not happen
pFilter->ctx = (void *) -1;
rv = ap_pass_brigade(pFilter->next, pBrigade);
apr_brigade_cleanup(pBrigade);
return rv;
}
} else {
ri = reqInfo->get();
}
// Copy headers out
apr_table_do(&iterateOverHeadersCallBack, &ri->mHeadersOut, pRequest->headers_out, NULL);
if (!ri->eos_seen()) {
rv = ap_pass_brigade(pFilter->next, pBrigade);
apr_brigade_cleanup(pBrigade);
return rv;
}
// Pushing the answer to the processor
prepareRequestInfo(tConf, pRequest, *ri);
if ( tConf->synchronous ) {
static __thread CURL * lCurl = NULL;
if ( ! lCurl ) {
lCurl = gProcessor->initCurl();
}
gProcessor->runOne(*ri, lCurl);
}
else {
gThreadPool->push(*reqInfo);
}
pFilter->ctx = (void *) -1;
printRequest(pRequest, ri, tConf);
rv = ap_pass_brigade(pFilter->next, pBrigade);
apr_brigade_cleanup(pBrigade);
return rv;
}
};
<|endoftext|>
|
<commit_before>/*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*
* helloADIOS1Writer_nompi.cpp : non mpi version of helloADIOS1Writer
*
* Created on: Jan 9, 2017
* Author: Norbert Podhorszki pnorbert@ornl.gov
*/
#include <iostream>
#include <vector>
#include <adios2.h>
int main(int argc, char *argv[])
{
/** Application variable */
std::vector<float> myFloats = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
const std::size_t Nx = myFloats.size();
try
{
/** ADIOS class factory of IO class objects, DebugON is recommended */
adios::ADIOS adios(MPI_COMM_WORLD, adios::DebugON);
/*** IO class object: settings and factory of Settings: Variables,
* Parameters, Transports, and Execution: Engines */
adios::IO &adios1IO = adios.DeclareIO("ADIOS1IO");
adios1IO.SetEngine("ADIOS1Writer");
adios1IO.AddTransport("file");
/** global array : name, { shape (total) }, { start (local) }, { count
* (local) }, all are constant dimensions */
adios::Variable<float> &bpFloats = adios1IO.DefineVariable<float>(
"bpFloats", {}, {}, {Nx}, adios::ConstantDims);
/** Engine derived class, spawned to start IO operations */
auto adios1Writer =
adios1IO.Open("myVector.bp", adios::OpenMode::Write);
if (!adios1Writer)
{
throw std::ios_base::failure(
"ERROR: hdf5Writer not created at Open\n");
}
/** Write variable for buffering */
adios1Writer->Write<float>(bpFloats, myFloats.data());
/** Create bp file, engine becomes unreachable after this*/
adios1Writer->Close();
}
catch (std::invalid_argument &e)
{
std::cout << "Invalid argument exception, STOPPING PROGRAM\n";
std::cout << e.what() << "\n";
}
catch (std::ios_base::failure &e)
{
std::cout << "System exception, STOPPING PROGRAM\n";
std::cout << e.what() << "\n";
}
catch (std::exception &e)
{
std::cout << "Exception, STOPPING PROGRAM\n";
std::cout << e.what() << "\n";
}
return 0;
}
<commit_msg>Williamfgc refactor examples basics (#10)<commit_after>/*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*
* helloADIOS1Writer_nompi.cpp : non mpi version of helloADIOS1Writer
*
* Created on: Jan 9, 2017
* Author: Norbert Podhorszki pnorbert@ornl.gov
*/
#include <iostream>
#include <vector>
#include <adios2.h>
int main(int argc, char *argv[])
{
/** Application variable */
std::vector<float> myFloats = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
const std::size_t Nx = myFloats.size();
try
{
/** ADIOS class factory of IO class objects, DebugON is recommended */
adios::ADIOS adios(adios::DebugON);
/*** IO class object: settings and factory of Settings: Variables,
* Parameters, Transports, and Execution: Engines */
adios::IO &adios1IO = adios.DeclareIO("ADIOS1IO");
adios1IO.SetEngine("ADIOS1Writer");
adios1IO.AddTransport("file");
/** global array : name, { shape (total) }, { start (local) }, { count
* (local) }, all are constant dimensions */
adios::Variable<float> &bpFloats = adios1IO.DefineVariable<float>(
"bpFloats", {}, {}, {Nx}, adios::ConstantDims);
/** Engine derived class, spawned to start IO operations */
auto adios1Writer =
adios1IO.Open("myVector.bp", adios::OpenMode::Write);
if (!adios1Writer)
{
throw std::ios_base::failure(
"ERROR: hdf5Writer not created at Open\n");
}
/** Write variable for buffering */
adios1Writer->Write<float>(bpFloats, myFloats.data());
/** Create bp file, engine becomes unreachable after this*/
adios1Writer->Close();
}
catch (std::invalid_argument &e)
{
std::cout << "Invalid argument exception, STOPPING PROGRAM\n";
std::cout << e.what() << "\n";
}
catch (std::ios_base::failure &e)
{
std::cout << "System exception, STOPPING PROGRAM\n";
std::cout << e.what() << "\n";
}
catch (std::exception &e)
{
std::cout << "Exception, STOPPING PROGRAM\n";
std::cout << e.what() << "\n";
}
return 0;
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <amr_single_step.h>
#include <fclaw2d_map.h>
#include <p4est_connectivity.h>
#include <amr_forestclaw.H>
#include <amr_utils.H>
#include <fclaw_options.h>
#include <fclaw2d_map_query.h>
#include <fc2d_clawpack46.H>
#include "sphere_user.H"
typedef struct user_options
{
int example;
int is_registered;
} user_options_t;
static void *
options_register_user (fclaw_app_t * app, void *package, sc_options_t * opt)
{
user_options_t* user = (user_options_t*) package;
sc_options_add_int (opt, 0, "example", &user->example, 0,
"[user] 1 for pillow grid, " \
"2 for cubed sphere ");
user->is_registered = 1;
return NULL;
}
static fclaw_exit_type_t
options_check_user (fclaw_app_t * app, void *package, void *registered)
{
user_options_t* user = (user_options_t*) package;
if (user->example < 1 || user->example > 2) {
fclaw_global_essentialf ("Option --user:example must be 1 or 2\n");
return FCLAW_EXIT_ERROR;
}
return FCLAW_NOEXIT;
}
static const fclaw_app_options_vtable_t options_vtable_user = {
options_register_user,
NULL, /* options_postprocess_user */
options_check_user,
NULL /* options_destroy_user */
};
void static
register_user_options (fclaw_app_t * app,
const char *configfile,
user_options_t* user)
{
FCLAW_ASSERT (app != NULL);
fclaw_app_options_register (app,"user", configfile, &options_vtable_user,
user);
}
static
void run_program(fclaw_app_t* app, amr_options_t* gparms,
fc2d_clawpack46_options_t* clawpack_options,
user_options_t* user)
{
sc_MPI_Comm mpicomm;
/* Mapped, multi-block domain */
p4est_connectivity_t *conn = NULL;
fclaw2d_domain_t *domain;
fclaw2d_map_context_t *cont = NULL;
/* Used locally */
double pi = M_PI;
double rotate[2];
mpicomm = fclaw_app_get_mpi_size_rank (app, NULL, NULL);
rotate[0] = pi*gparms->theta/180.0;
rotate[1] = pi*gparms->phi/180.0;
switch (user->example) {
case 1:
conn = p4est_connectivity_new_pillow();
cont = fclaw2d_map_new_pillowsphere(gparms->scale,gparms->shift,rotate);
break;
case 2:
conn = p4est_connectivity_new_cubed();
cont = fclaw2d_map_new_cubedsphere(gparms->scale,gparms->shift,rotate);
break;
default:
SC_ABORT_NOT_REACHED (); /* must be checked in torus_checkparms */
}
domain = fclaw2d_domain_new_conn_map (mpicomm, gparms->minlevel, conn, cont);
fclaw2d_domain_list_levels(domain, FCLAW_VERBOSITY_ESSENTIAL);
fclaw2d_domain_list_neighbors(domain, FCLAW_VERBOSITY_DEBUG);
/* ---------------------------------------------------------------
Set domain data.
--------------------------------------------------------------- */
init_domain_data(domain);
/* Store parameters */
set_domain_parms(domain,gparms);
fc2d_clawpack46_set_options (domain,clawpack_options);
/* Link solvers to the domain */
link_problem_setup(domain,sphere_problem_setup);
sphere_link_solvers(domain);
/* --------------------------------------------------
Initialize and run the simulation
-------------------------------------------------- */
amrinit(&domain);
amrrun(&domain);
amrreset(&domain);
/* --------------------------------------------------
Clean up the mapping context.
-------------------------------------------------- */
fclaw2d_map_destroy (cont);
}
int main (int argc, char **argv)
{
fclaw_app_t *app;
int first_arg;
fclaw_exit_type_t vexit;
/* Options */
sc_options_t *options;
amr_options_t samr_options, *gparms = &samr_options;
fc2d_clawpack46_options_t sclawpack_options, *clawpack_options = &sclawpack_options;
user_options_t suser_options, *user = &suser_options;
int retval;
/* Initialize application */
app = fclaw_app_new (&argc, &argv, user);
options = fclaw_app_get_options (app);
/* Register options for each package */
fclaw_options_register_general (app, "fclaw_options.ini", gparms);
fc2d_clawpack46_options_register (app, "fclaw_options.ini", clawpack_options);
register_user_options (app, "fclaw_options.ini", user);
/* Read configuration file(s) and command line, and process options */
retval = fclaw_options_read_from_file(options);
vexit = fclaw_app_options_parse (app, &first_arg,"fclaw_options.ini.used");
/* -------------------------------------------------------------
- Run program
------------------------------------------------------------- */
if (!retval & !vexit)
{
run_program(app, gparms, clawpack_options, user);
}
fclaw_app_destroy (app);
return 0;
}
<commit_msg>(sphere) Add new package handling features<commit_after>/*
Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <amr_single_step.h>
#include <fclaw2d_map.h>
#include <p4est_connectivity.h>
#include <amr_forestclaw.H>
#include <amr_utils.H>
#include <fclaw_options.h>
#include <fclaw2d_map_query.h>
#include <fclaw_package.h>
#include <fc2d_clawpack46.H>
#include "sphere_user.H"
typedef struct user_options
{
int example;
int is_registered;
} user_options_t;
static void *
options_register_user (fclaw_app_t * app, void *package, sc_options_t * opt)
{
user_options_t* user = (user_options_t*) package;
sc_options_add_int (opt, 0, "example", &user->example, 0,
"[user] 1 for pillow grid, " \
"2 for cubed sphere ");
user->is_registered = 1;
return NULL;
}
static fclaw_exit_type_t
options_check_user (fclaw_app_t * app, void *package, void *registered)
{
user_options_t* user = (user_options_t*) package;
if (user->example < 1 || user->example > 2) {
fclaw_global_essentialf ("Option --user:example must be 1 or 2\n");
return FCLAW_EXIT_ERROR;
}
return FCLAW_NOEXIT;
}
static const fclaw_app_options_vtable_t options_vtable_user = {
options_register_user,
NULL, /* options_postprocess_user */
options_check_user,
NULL /* options_destroy_user */
};
void static
register_user_options (fclaw_app_t * app,
const char *configfile,
user_options_t* user)
{
FCLAW_ASSERT (app != NULL);
fclaw_app_options_register (app,"user", configfile, &options_vtable_user,
user);
}
static
void run_program(fclaw_app_t* app, amr_options_t* gparms,
fc2d_clawpack46_options_t* clawpack_options,
user_options_t* user)
{
sc_MPI_Comm mpicomm;
/* Mapped, multi-block domain */
p4est_connectivity_t *conn = NULL;
fclaw2d_domain_t *domain;
fclaw2d_map_context_t *cont = NULL;
/* Used locally */
double pi = M_PI;
double rotate[2];
mpicomm = fclaw_app_get_mpi_size_rank (app, NULL, NULL);
rotate[0] = pi*gparms->theta/180.0;
rotate[1] = pi*gparms->phi/180.0;
switch (user->example) {
case 1:
conn = p4est_connectivity_new_pillow();
cont = fclaw2d_map_new_pillowsphere(gparms->scale,gparms->shift,rotate);
break;
case 2:
conn = p4est_connectivity_new_cubed();
cont = fclaw2d_map_new_cubedsphere(gparms->scale,gparms->shift,rotate);
break;
default:
SC_ABORT_NOT_REACHED (); /* must be checked in torus_checkparms */
}
domain = fclaw2d_domain_new_conn_map (mpicomm, gparms->minlevel, conn, cont);
fclaw2d_domain_list_levels(domain, FCLAW_VERBOSITY_ESSENTIAL);
fclaw2d_domain_list_neighbors(domain, FCLAW_VERBOSITY_DEBUG);
/* ---------------------------------------------------------------
Set domain data.
--------------------------------------------------------------- */
init_domain_data(domain);
/* Store parameters */
set_domain_parms(domain,gparms);
fc2d_clawpack46_set_options (domain,clawpack_options);
/* Link solvers to the domain */
link_problem_setup(domain,sphere_problem_setup);
sphere_link_solvers(domain);
/* --------------------------------------------------
Initialize and run the simulation
-------------------------------------------------- */
amrinit(&domain);
amrrun(&domain);
amrreset(&domain);
/* --------------------------------------------------
Clean up the mapping context.
-------------------------------------------------- */
fclaw2d_map_destroy (cont);
}
int main (int argc, char **argv)
{
fclaw_app_t *app;
int first_arg;
fclaw_exit_type_t vexit;
/* Options */
sc_options_t *options;
amr_options_t samr_options, *gparms = &samr_options;
fc2d_clawpack46_options_t sclawpack_options, *clawpack_options = &sclawpack_options;
user_options_t suser_options, *user = &suser_options;
int clawpack46_id;
fclaw_package_container_t* pkgs;
int retval;
/* Initialize application */
app = fclaw_app_new (&argc, &argv, user);
options = fclaw_app_get_options (app);
/* Register options for each package */
fclaw_options_register_general (app, "fclaw_options.ini", gparms);
fc2d_clawpack46_options_register (app, "fclaw_options.ini", clawpack_options);
register_user_options (app, "fclaw_options.ini", user);
/* Read configuration file(s) and command line, and process options */
retval = fclaw_options_read_from_file(options);
vexit = fclaw_app_options_parse (app, &first_arg,"fclaw_options.ini.used");
pkgs = fclaw_package_collection_init();
clawpack46_id = fc2d_clawpack46_package_register(pkgs,clawpack_options);
ClawPatch::package_container = *pkgs;
/* -------------------------------------------------------------
- Run program
------------------------------------------------------------- */
if (!retval & !vexit)
{
run_program(app, gparms, clawpack_options, user);
}
fclaw_package_collection_destroy(pkgs);
fclaw_app_destroy (app);
return 0;
}
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////
// This file is part of Grappa, a system for scaling irregular
// applications on commodity clusters.
// Copyright (C) 2010-2014 University of Washington and Battelle
// Memorial Institute. University of Washington authorizes use of this
// Grappa software.
// Grappa is free software: you can redistribute it and/or modify it
// under the terms of the Affero General Public License as published
// by Affero, Inc., either version 1 of the License, or (at your
// option) any later version.
// Grappa 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
// Affero General Public License for more details.
// You should have received a copy of the Affero General Public
// License along with this program. If not, you may obtain one from
// http://www.affero.org/oagpl.html.
////////////////////////////////////////////////////////////////////////
#include <Grappa.hpp>
using namespace Grappa;
using namespace std;
DEFINE_int64( n, 8, "Board size" );
GRAPPA_DEFINE_METRIC( SimpleMetric<double>, nqueens_runtime, 0.0 );
/*
* Each core maintains the number of solutions it has found + the board size
*/
int64_t nqSolutions;
int nqBoardSize;
GlobalCompletionEvent gce; // tasks synchronization
/*
* Checks whether it is safe to put a queen in row 'row' in the current
* column. Vector 'cols' has the row position for the queens in the previous
* columns.
*/
bool nqIsSafe(int row, vector<int> &cols)
{
int n = cols.size();
/* we check if putting a queen on row 'row' will cause any of the previous
* queens (in 'cols') to capture it.
*/
for (auto i=0; i<n; i++) {
if (row == cols[i] || abs(n-i) == abs(row-cols[i]))
return false; // captured - not safe
}
return true;
}
/*
* This is basically a brute force solution using recursion.
*
* Vector 'cols' stores, for each column, the row number of a queen. We start
* with an empty vector (i.e., placing queens on the first column), check if
* it is safe to place a queen on a specific row and recursively call nqSearch
* to check for the next column.
*/
void nqSearch(GlobalAddress< vector<int> > cols)
{
/* get the size of the vector */
int vsize = delegate::call(cols, [](vector<int> &v) { return v.size(); });
/* are we done yet? */
if (vsize == nqBoardSize) {
nqSolutions++;
return;
}
/* check whether it is safe to consider a queen for the next column */
for (int i=0; i<nqBoardSize; i++) {
/* safe? code is executed at the core that owns the vector */
bool safe = delegate::call(cols, [i](vector<int> &v) {
bool safe = nqIsSafe(i, v);
return safe;
});
/* if not safe we are done - otherwise create a new vector and do
* a recursive call to nqSearch */
if (safe) {
vector<int> *mv = new vector<int>(0);
/* copy the original vector to the new one we just created */
for (auto k=0; k<vsize; k++) {
mv->push_back(delegate::call(cols, [k](vector<int> &v) { return v[k]; }));
}
mv->push_back(i);
GlobalAddress< vector<int> > g_mv = make_global(mv);
/* spawn a recursive search */
spawn<unbound,&gce>([g_mv] { nqSearch(g_mv); });
}
}
/* delete original vector */
delegate::call(cols, [](vector<int> &v) { delete &v; });
}
int main(int argc, char * argv[]) {
init( &argc, &argv );
const int expectedSolutions[] =
{0, 1, 0, 0, 2, 10, 4, 40, 92, 352, 724, 2680, 14200, 73712, 365596, \
2279184, 14772512};
nqBoardSize = FLAGS_n;
nqSolutions = 0;
run([=]{
double start = walltime();
vector<int> *cols = new vector<int>(0);
GlobalAddress< vector<int> > g_cols = make_global(cols);
finish<&gce>([g_cols]{
nqSearch(g_cols);
});
int64_t total = reduce<int64_t,collective_add<int64_t>>(&nqSolutions);
nqueens_runtime = walltime() - start;
if (nqBoardSize <= 16) {
LOG(INFO) << "NQueens (" << nqBoardSize << ") = " << total << \
" (solution is " << (total == expectedSolutions[nqBoardSize] ? "correct)" : "wrong)");
}
else
LOG(INFO) << "NQueens (" << nqBoardSize << ") = " << total;
LOG(INFO) << "Elapsed time: " << nqueens_runtime.value() << " seconds";
});
finalize();
}
<commit_msg>Deleting a wrongly-added file =P<commit_after><|endoftext|>
|
<commit_before>/*
Copyright (C) 2016 Claude SIMON (http://zeusw.org/epeios/contact.html).
This file is part of 'eSketch' software.
'eSketch' is free software: you can redistribute it and/or modify it
under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
'eSketch' is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with 'eSketch'. If not, see <http://www.gnu.org/licenses/>.
*/
#include "sclxdhtml.h"
#include "sclmisc.h"
#include "frdrgstry.h"
#include "core.h"
const char *sclmisc::SCLMISCTargetName = BASE_NAME;
void sclxdhtml::SCLXDHTMLInitialization( xdhcmn::mode__ Mode )
{
qRH
sclfrntnd::rFeatures Features;
qRB
core::Core.Init( Mode );
if ( Mode == xdhcmn::mMultiUser ) {
Features.Init();
sclfrntnd::GuessBackendFeatures( Features );
core::Kernel().Init( Features, plgn::EmptyAbstracts );
}
qRR
qRT
qRE
}
xdhcmn::session_callback__ *sclxdhtml::SCLXDHTMLRetrieveCallback(
const char *Language,
xdhcmn::proxy_callback__ *ProxyCallback )
{
core::rSession *Session = new core::rSession;
if ( Session == NULL )
qRGnr();
Session->Init( core::Kernel(), Language, ProxyCallback );
switch ( core::Core.Mode() ) {
case xdhcmn::mMonoUser:
switch ( sclfrntnd::HandleProject() ) {
case sclfrntnd::phNone:
::prolog::SetLayout( *Session );
break;
case sclfrntnd::phLoad:
::login::SetLayout( *Session );
break;
case sclfrntnd::phLogin:
Session->SetBackendVisibility( sclxdhtml::bvHide );
::login::SetLayout( *Session );
break;
case sclfrntnd::phRun:
::main::SetLayout( *Session );
break;
default:
qRGnr();
break;
}
break;
case xdhcmn::mMultiUser:
// login::SetLayout( *Session );
break;
default:
qRGnr();
break;
}
return Session;
}
void sclxdhtml::SCLXDHTMLReleaseCallback( xdhcmn::session_callback__ *Callback )
{
if ( Callback == NULL )
qRGnr();
delete Callback;
}
<commit_msg>14/10/2016 11:03:12<commit_after>/*
Copyright (C) 2016 Claude SIMON (http://zeusw.org/epeios/contact.html).
This file is part of 'eSketch' software.
'eSketch' is free software: you can redistribute it and/or modify it
under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
'eSketch' is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with 'eSketch'. If not, see <http://www.gnu.org/licenses/>.
*/
#include "sclxdhtml.h"
#include "sclmisc.h"
#include "frdrgstry.h"
#include "core.h"
void sclxdhtml::SCLXDHTMLInitialization( xdhcmn::mode__ Mode )
{
qRH
sclfrntnd::rFeatures Features;
qRB
core::Core.Init( Mode );
if ( Mode == xdhcmn::mMultiUser ) {
Features.Init();
sclfrntnd::GuessBackendFeatures( Features );
core::Kernel().Init( Features, plgn::EmptyAbstracts );
}
qRR
qRT
qRE
}
xdhcmn::session_callback__ *sclxdhtml::SCLXDHTMLRetrieveCallback(
const char *Language,
xdhcmn::proxy_callback__ *ProxyCallback )
{
core::rSession *Session = new core::rSession;
if ( Session == NULL )
qRGnr();
Session->Init( core::Kernel(), Language, ProxyCallback );
switch ( core::Core.Mode() ) {
case xdhcmn::mMonoUser:
switch ( sclfrntnd::HandleProject() ) {
case sclfrntnd::phNone:
::prolog::SetLayout( *Session );
break;
case sclfrntnd::phLoad:
::login::SetLayout( *Session );
break;
case sclfrntnd::phLogin:
Session->SetBackendVisibility( sclxdhtml::bvHide );
::login::SetLayout( *Session );
break;
case sclfrntnd::phRun:
::main::SetLayout( *Session );
break;
default:
qRGnr();
break;
}
break;
case xdhcmn::mMultiUser:
// login::SetLayout( *Session );
break;
default:
qRGnr();
break;
}
return Session;
}
void sclxdhtml::SCLXDHTMLReleaseCallback( xdhcmn::session_callback__ *Callback )
{
if ( Callback == NULL )
qRGnr();
delete Callback;
}
const char *sclmisc::SCLMISCTargetName = BASE_NAME;
const char *sclmisc::SCLMISCProductName = SKTINF_MC_AFFIX;
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/enrollment/enterprise_enrollment_screen.h"
#include "base/bind.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/metrics/histogram.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/cros/cryptohome_library.h"
#include "chrome/browser/chromeos/login/authenticator.h"
#include "chrome/browser/chromeos/login/screen_observer.h"
#include "chrome/browser/policy/auto_enrollment_client.h"
#include "chrome/browser/policy/browser_policy_connector.h"
#include "chrome/browser/policy/cloud_policy_data_store.h"
#include "chrome/browser/policy/enterprise_metrics.h"
namespace chromeos {
namespace {
// Retry for InstallAttrs initialization every 500ms.
const int kLockRetryIntervalMs = 500;
} // namespace
EnterpriseEnrollmentScreen::EnterpriseEnrollmentScreen(
ScreenObserver* observer,
EnterpriseEnrollmentScreenActor* actor)
: WizardScreen(observer),
actor_(actor),
is_auto_enrollment_(false),
is_showing_(false),
ALLOW_THIS_IN_INITIALIZER_LIST(weak_ptr_factory_(this)) {
actor_->SetController(this);
// Init the TPM if it has not been done until now (in debug build we might
// have not done that yet).
chromeos::CryptohomeLibrary* cryptohome =
chromeos::CrosLibrary::Get()->GetCryptohomeLibrary();
if (cryptohome &&
cryptohome->TpmIsEnabled() &&
!cryptohome->TpmIsBeingOwned() &&
!cryptohome->TpmIsOwned()) {
cryptohome->TpmCanAttemptOwnership();
}
}
EnterpriseEnrollmentScreen::~EnterpriseEnrollmentScreen() {}
void EnterpriseEnrollmentScreen::SetParameters(bool is_auto_enrollment,
const std::string& user) {
is_auto_enrollment_ = is_auto_enrollment;
user_ = user.empty() ? user : Authenticator::Canonicalize(user);
}
void EnterpriseEnrollmentScreen::PrepareToShow() {
actor_->PrepareToShow();
}
void EnterpriseEnrollmentScreen::Show() {
is_showing_ = true;
actor_->Show();
}
void EnterpriseEnrollmentScreen::Hide() {
is_showing_ = false;
actor_->Hide();
}
void EnterpriseEnrollmentScreen::OnOAuthTokenAvailable(
const std::string& user,
const std::string& token) {
user_ = Authenticator::Canonicalize(user);
RegisterForDevicePolicy(token);
}
void EnterpriseEnrollmentScreen::OnConfirmationClosed(bool go_back_to_signin) {
get_screen_observer()->OnExit(go_back_to_signin ?
ScreenObserver::ENTERPRISE_ENROLLMENT_COMPLETED :
ScreenObserver::ENTERPRISE_AUTO_MAGIC_ENROLLMENT_COMPLETED);
}
bool EnterpriseEnrollmentScreen::IsAutoEnrollment(std::string* user) {
if (is_auto_enrollment_)
*user = user_;
return is_auto_enrollment_;
}
void EnterpriseEnrollmentScreen::OnPolicyStateChanged(
policy::CloudPolicySubsystem::PolicySubsystemState state,
policy::CloudPolicySubsystem::ErrorDetails error_details) {
if (is_showing_) {
switch (state) {
case policy::CloudPolicySubsystem::UNENROLLED:
switch (error_details) {
case policy::CloudPolicySubsystem::BAD_SERIAL_NUMBER:
actor_->ShowSerialNumberError();
break;
case policy::CloudPolicySubsystem::BAD_ENROLLMENT_MODE:
actor_->ShowEnrollmentModeError();
break;
default: // Still working...
return;
}
break;
case policy::CloudPolicySubsystem::BAD_GAIA_TOKEN:
case policy::CloudPolicySubsystem::LOCAL_ERROR:
actor_->ShowFatalEnrollmentError();
break;
case policy::CloudPolicySubsystem::UNMANAGED:
actor_->ShowAccountError();
break;
case policy::CloudPolicySubsystem::NETWORK_ERROR:
actor_->ShowNetworkEnrollmentError();
break;
case policy::CloudPolicySubsystem::TOKEN_FETCHED:
if (!is_auto_enrollment_ ||
g_browser_process->browser_policy_connector()->
GetDeviceCloudPolicyDataStore()->device_mode() ==
policy::DEVICE_MODE_ENTERPRISE) {
WriteInstallAttributesData();
return;
} else {
LOG(ERROR) << "Enrollment can not proceed because Auto-enrollment is "
<< "not supported for non-enterprise enrollment modes.";
policy::AutoEnrollmentClient::CancelAutoEnrollment();
is_auto_enrollment_ = false;
actor_->ShowAutoEnrollmentError();
// Set the error state to something distinguishable in the logs.
state = policy::CloudPolicySubsystem::LOCAL_ERROR;
error_details = policy::CloudPolicySubsystem::AUTO_ENROLLMENT_ERROR;
}
break;
case policy::CloudPolicySubsystem::SUCCESS:
// Success!
registrar_.reset();
actor_->ShowConfirmationScreen();
return;
}
// We have an error.
if (!is_auto_enrollment_) {
UMA_HISTOGRAM_ENUMERATION(policy::kMetricEnrollment,
policy::kMetricEnrollmentPolicyFailed,
policy::kMetricEnrollmentSize);
}
LOG(WARNING) << "Policy subsystem error during enrollment: " << state
<< " details: " << error_details;
}
// Stop the policy infrastructure.
registrar_.reset();
g_browser_process->browser_policy_connector()->ResetDevicePolicy();
}
void EnterpriseEnrollmentScreen::WriteInstallAttributesData() {
// Since this method is also called directly.
weak_ptr_factory_.InvalidateWeakPtrs();
switch (g_browser_process->browser_policy_connector()->LockDevice(user_)) {
case policy::EnterpriseInstallAttributes::LOCK_SUCCESS: {
// Proceed with policy fetch.
policy::BrowserPolicyConnector* connector =
g_browser_process->browser_policy_connector();
connector->FetchCloudPolicy();
return;
}
case policy::EnterpriseInstallAttributes::LOCK_NOT_READY: {
// InstallAttributes not ready yet, retry later.
LOG(WARNING) << "Install Attributes not ready yet will retry in "
<< kLockRetryIntervalMs << "ms.";
MessageLoop::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&EnterpriseEnrollmentScreen::WriteInstallAttributesData,
weak_ptr_factory_.GetWeakPtr()),
kLockRetryIntervalMs);
return;
}
case policy::EnterpriseInstallAttributes::LOCK_BACKEND_ERROR: {
actor_->ShowFatalEnrollmentError();
return;
}
case policy::EnterpriseInstallAttributes::LOCK_WRONG_USER: {
LOG(ERROR) << "Enrollment can not proceed because the InstallAttrs "
<< "has been locked already!";
actor_->ShowFatalEnrollmentError();
return;
}
}
NOTREACHED();
}
void EnterpriseEnrollmentScreen::RegisterForDevicePolicy(
const std::string& token) {
policy::BrowserPolicyConnector* connector =
g_browser_process->browser_policy_connector();
if (!connector->device_cloud_policy_subsystem()) {
LOG(ERROR) << "Cloud policy subsystem not initialized.";
} else if (connector->IsEnterpriseManaged()) {
LOG(ERROR) << "Device is already enterprise managed!";
} else if (connector->device_cloud_policy_subsystem()->state() ==
policy::CloudPolicySubsystem::SUCCESS) {
LOG(ERROR) << "A previous enrollment already succeeded!";
} else {
// Make sure the device policy subsystem is in a clean slate.
connector->ResetDevicePolicy();
connector->ScheduleServiceInitialization(0);
registrar_.reset(new policy::CloudPolicySubsystem::ObserverRegistrar(
connector->device_cloud_policy_subsystem(), this));
// Push the credentials to the policy infrastructure. It'll start enrollment
// and notify us of progress through CloudPolicySubsystem::Observer.
connector->RegisterForDevicePolicy(user_, token, is_auto_enrollment_);
return;
}
NOTREACHED();
if (is_showing_)
actor_->ShowFatalEnrollmentError();
}
} // namespace chromeos
<commit_msg>Restart the Chrome session after a successful KIOSK enrollment.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/enrollment/enterprise_enrollment_screen.h"
#include "base/bind.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/metrics/histogram.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/cros/cryptohome_library.h"
#include "chrome/browser/chromeos/dbus/dbus_thread_manager.h"
#include "chrome/browser/chromeos/dbus/session_manager_client.h"
#include "chrome/browser/chromeos/login/authenticator.h"
#include "chrome/browser/chromeos/login/screen_observer.h"
#include "chrome/browser/policy/auto_enrollment_client.h"
#include "chrome/browser/policy/browser_policy_connector.h"
#include "chrome/browser/policy/cloud_policy_data_store.h"
#include "chrome/browser/policy/enterprise_metrics.h"
namespace chromeos {
namespace {
// Retry for InstallAttrs initialization every 500ms.
const int kLockRetryIntervalMs = 500;
} // namespace
EnterpriseEnrollmentScreen::EnterpriseEnrollmentScreen(
ScreenObserver* observer,
EnterpriseEnrollmentScreenActor* actor)
: WizardScreen(observer),
actor_(actor),
is_auto_enrollment_(false),
is_showing_(false),
ALLOW_THIS_IN_INITIALIZER_LIST(weak_ptr_factory_(this)) {
actor_->SetController(this);
// Init the TPM if it has not been done until now (in debug build we might
// have not done that yet).
chromeos::CryptohomeLibrary* cryptohome =
chromeos::CrosLibrary::Get()->GetCryptohomeLibrary();
if (cryptohome &&
cryptohome->TpmIsEnabled() &&
!cryptohome->TpmIsBeingOwned() &&
!cryptohome->TpmIsOwned()) {
cryptohome->TpmCanAttemptOwnership();
}
}
EnterpriseEnrollmentScreen::~EnterpriseEnrollmentScreen() {}
void EnterpriseEnrollmentScreen::SetParameters(bool is_auto_enrollment,
const std::string& user) {
is_auto_enrollment_ = is_auto_enrollment;
user_ = user.empty() ? user : Authenticator::Canonicalize(user);
}
void EnterpriseEnrollmentScreen::PrepareToShow() {
actor_->PrepareToShow();
}
void EnterpriseEnrollmentScreen::Show() {
is_showing_ = true;
actor_->Show();
}
void EnterpriseEnrollmentScreen::Hide() {
is_showing_ = false;
actor_->Hide();
}
void EnterpriseEnrollmentScreen::OnOAuthTokenAvailable(
const std::string& user,
const std::string& token) {
user_ = Authenticator::Canonicalize(user);
RegisterForDevicePolicy(token);
}
void EnterpriseEnrollmentScreen::OnConfirmationClosed(bool go_back_to_signin) {
// If the machine has been put in KIOSK mode we have to restart the session
// here to go in the proper KIOSK mode login screen.
if (g_browser_process->browser_policy_connector()->
GetDeviceCloudPolicyDataStore()->device_mode() ==
policy::DEVICE_MODE_KIOSK) {
DBusThreadManager::Get()->GetSessionManagerClient()->StopSession();
return;
}
get_screen_observer()->OnExit(go_back_to_signin ?
ScreenObserver::ENTERPRISE_ENROLLMENT_COMPLETED :
ScreenObserver::ENTERPRISE_AUTO_MAGIC_ENROLLMENT_COMPLETED);
}
bool EnterpriseEnrollmentScreen::IsAutoEnrollment(std::string* user) {
if (is_auto_enrollment_)
*user = user_;
return is_auto_enrollment_;
}
void EnterpriseEnrollmentScreen::OnPolicyStateChanged(
policy::CloudPolicySubsystem::PolicySubsystemState state,
policy::CloudPolicySubsystem::ErrorDetails error_details) {
if (is_showing_) {
switch (state) {
case policy::CloudPolicySubsystem::UNENROLLED:
switch (error_details) {
case policy::CloudPolicySubsystem::BAD_SERIAL_NUMBER:
actor_->ShowSerialNumberError();
break;
case policy::CloudPolicySubsystem::BAD_ENROLLMENT_MODE:
actor_->ShowEnrollmentModeError();
break;
default: // Still working...
return;
}
break;
case policy::CloudPolicySubsystem::BAD_GAIA_TOKEN:
case policy::CloudPolicySubsystem::LOCAL_ERROR:
actor_->ShowFatalEnrollmentError();
break;
case policy::CloudPolicySubsystem::UNMANAGED:
actor_->ShowAccountError();
break;
case policy::CloudPolicySubsystem::NETWORK_ERROR:
actor_->ShowNetworkEnrollmentError();
break;
case policy::CloudPolicySubsystem::TOKEN_FETCHED:
if (!is_auto_enrollment_ ||
g_browser_process->browser_policy_connector()->
GetDeviceCloudPolicyDataStore()->device_mode() ==
policy::DEVICE_MODE_ENTERPRISE) {
WriteInstallAttributesData();
return;
} else {
LOG(ERROR) << "Enrollment can not proceed because Auto-enrollment is "
<< "not supported for non-enterprise enrollment modes.";
policy::AutoEnrollmentClient::CancelAutoEnrollment();
is_auto_enrollment_ = false;
actor_->ShowAutoEnrollmentError();
// Set the error state to something distinguishable in the logs.
state = policy::CloudPolicySubsystem::LOCAL_ERROR;
error_details = policy::CloudPolicySubsystem::AUTO_ENROLLMENT_ERROR;
}
break;
case policy::CloudPolicySubsystem::SUCCESS:
// Success!
registrar_.reset();
actor_->ShowConfirmationScreen();
return;
}
// We have an error.
if (!is_auto_enrollment_) {
UMA_HISTOGRAM_ENUMERATION(policy::kMetricEnrollment,
policy::kMetricEnrollmentPolicyFailed,
policy::kMetricEnrollmentSize);
}
LOG(WARNING) << "Policy subsystem error during enrollment: " << state
<< " details: " << error_details;
}
// Stop the policy infrastructure.
registrar_.reset();
g_browser_process->browser_policy_connector()->ResetDevicePolicy();
}
void EnterpriseEnrollmentScreen::WriteInstallAttributesData() {
// Since this method is also called directly.
weak_ptr_factory_.InvalidateWeakPtrs();
switch (g_browser_process->browser_policy_connector()->LockDevice(user_)) {
case policy::EnterpriseInstallAttributes::LOCK_SUCCESS: {
// Proceed with policy fetch.
policy::BrowserPolicyConnector* connector =
g_browser_process->browser_policy_connector();
connector->FetchCloudPolicy();
return;
}
case policy::EnterpriseInstallAttributes::LOCK_NOT_READY: {
// InstallAttributes not ready yet, retry later.
LOG(WARNING) << "Install Attributes not ready yet will retry in "
<< kLockRetryIntervalMs << "ms.";
MessageLoop::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&EnterpriseEnrollmentScreen::WriteInstallAttributesData,
weak_ptr_factory_.GetWeakPtr()),
kLockRetryIntervalMs);
return;
}
case policy::EnterpriseInstallAttributes::LOCK_BACKEND_ERROR: {
actor_->ShowFatalEnrollmentError();
return;
}
case policy::EnterpriseInstallAttributes::LOCK_WRONG_USER: {
LOG(ERROR) << "Enrollment can not proceed because the InstallAttrs "
<< "has been locked already!";
actor_->ShowFatalEnrollmentError();
return;
}
}
NOTREACHED();
}
void EnterpriseEnrollmentScreen::RegisterForDevicePolicy(
const std::string& token) {
policy::BrowserPolicyConnector* connector =
g_browser_process->browser_policy_connector();
if (!connector->device_cloud_policy_subsystem()) {
LOG(ERROR) << "Cloud policy subsystem not initialized.";
} else if (connector->IsEnterpriseManaged()) {
LOG(ERROR) << "Device is already enterprise managed!";
} else if (connector->device_cloud_policy_subsystem()->state() ==
policy::CloudPolicySubsystem::SUCCESS) {
LOG(ERROR) << "A previous enrollment already succeeded!";
} else {
// Make sure the device policy subsystem is in a clean slate.
connector->ResetDevicePolicy();
connector->ScheduleServiceInitialization(0);
registrar_.reset(new policy::CloudPolicySubsystem::ObserverRegistrar(
connector->device_cloud_policy_subsystem(), this));
// Push the credentials to the policy infrastructure. It'll start enrollment
// and notify us of progress through CloudPolicySubsystem::Observer.
connector->RegisterForDevicePolicy(user_, token, is_auto_enrollment_);
return;
}
NOTREACHED();
if (is_showing_)
actor_->ShowFatalEnrollmentError();
}
} // namespace chromeos
<|endoftext|>
|
<commit_before>/* This file is part of the KDE project.
Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies).
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 or 3 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, see <http://www.gnu.org/licenses/>.
*/
#include "backend.h"
#include "backendnode.h"
#include "audiooutput.h"
#include "effect.h"
#include "mediaobject.h"
#include "videowidget.h"
#include "volumeeffect.h"
//windows specific (DirectX Media Object)
#include <dmo.h>
#include <QtCore/QSettings>
#include <QtCore/QSet>
#include <QtCore/QVariant>
#include <QtCore/QtPlugin>
QT_BEGIN_NAMESPACE
Q_EXPORT_PLUGIN2(phonon_ds9, Phonon::DS9::Backend);
namespace Phonon
{
namespace DS9
{
bool Backend::AudioMoniker::operator==(const AudioMoniker &other)
{
return other->IsEqual(*this) == S_OK;
}
Backend::Backend(QObject *parent, const QVariantList &)
: QObject(parent)
{
::CoInitialize(0);
//registering meta types
qRegisterMetaType<HRESULT>("HRESULT");
qRegisterMetaType<QSet<Filter> >("QSet<Filter>");
qRegisterMetaType<Graph>("Graph");
}
Backend::~Backend()
{
m_audioOutputs.clear();
m_audioEffects.clear();
::CoUninitialize();
}
QObject *Backend::createObject(BackendInterface::Class c, QObject *parent, const QList<QVariant> &args)
{
switch (c)
{
case MediaObjectClass:
return new MediaObject(parent);
case AudioOutputClass:
return new AudioOutput(this, parent);
#ifndef QT_NO_PHONON_EFFECT
case EffectClass:
return new Effect(m_audioEffects[ args[0].toInt() ], parent);
#endif //QT_NO_PHONON_EFFECT
#ifndef QT_NO_PHONON_VIDEO
case VideoWidgetClass:
return new VideoWidget(qobject_cast<QWidget *>(parent));
#endif //QT_NO_PHONON_VIDEO
#ifndef QT_NO_PHONON_VOLUMEFADEREFFECT
case VolumeFaderEffectClass:
return new VolumeEffect(parent);
#endif //QT_NO_PHONON_VOLUMEFADEREFFECT
default:
return 0;
}
}
bool Backend::supportsVideo() const
{
#ifndef QT_NO_PHONON_VIDEO
return true;
#else
return false;
#endif //QT_NO_PHONON_VIDEO
}
QStringList Backend::availableMimeTypes() const
{
QSet<QString> ret;
const QStringList locations = QStringList() << QLatin1String("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Multimedia\\mplayer2\\mime types")
<< QLatin1String("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Multimedia\\wmplayer\\mime types");
Q_FOREACH(QString s, locations) {
QSettings settings(s, QSettings::NativeFormat);
ret += settings.childGroups().replaceInStrings("\\", "/").toSet();
}
QStringList list = ret.toList();
qSort(list);
return list;
}
Filter Backend::getAudioOutputFilter(int index) const
{
Filter ret;
if (index >= 0 && index < m_audioOutputs.count()) {
m_audioOutputs.at(index)->BindToObject(0, 0, IID_IBaseFilter, reinterpret_cast<void**>(&ret));
} else {
//just return the default audio renderer (not directsound)
ret = Filter(CLSID_AudioRender, IID_IBaseFilter);
}
return ret;
}
QList<int> Backend::objectDescriptionIndexes(Phonon::ObjectDescriptionType type) const
{
QList<int> ret;
switch(type)
{
case Phonon::AudioOutputDeviceType:
{
#ifdef Q_OS_WINCE
ret << 0; // only one audio device with index 0
#else
ComPointer<ICreateDevEnum> devEnum(CLSID_SystemDeviceEnum, IID_ICreateDevEnum);
if (!devEnum) {
return ret; //it is impossible to enumerate the devices
}
ComPointer<IEnumMoniker> enumMon;
HRESULT hr = devEnum->CreateClassEnumerator(CLSID_AudioRendererCategory, enumMon.pparam(), 0);
if (FAILED(hr)) {
break;
}
AudioMoniker mon;
//let's reorder the devices so that directshound appears first
int nbds = 0; //number of directsound devices
while (S_OK == enumMon->Next(1, mon.pparam(), 0)) {
LPOLESTR str = 0;
mon->GetDisplayName(0,0,&str);
const QString name = QString::fromUtf16((unsigned short*)str);
ComPointer<IMalloc> alloc;
::CoGetMalloc(1, alloc.pparam());
alloc->Free(str);
int insert_pos = 0;
if (!m_audioOutputs.contains(mon)) {
insert_pos = m_audioOutputs.count();
m_audioOutputs.append(mon);
} else {
insert_pos = m_audioOutputs.indexOf(mon);
}
if (name.contains(QLatin1String("DirectSound"))) {
ret.insert(nbds++, insert_pos);
} else {
ret.append(insert_pos);
}
}
#endif
break;
}
#ifndef QT_NO_PHONON_EFFECT
case Phonon::EffectType:
{
m_audioEffects.clear();
ComPointer<IEnumDMO> enumDMO;
HRESULT hr = ::DMOEnum(DMOCATEGORY_AUDIO_EFFECT, DMO_ENUMF_INCLUDE_KEYED, 0, 0, 0, 0, enumDMO.pparam());
if (SUCCEEDED(hr)) {
CLSID clsid;
while (S_OK == enumDMO->Next(1, &clsid, 0, 0)) {
ret += m_audioEffects.count();
m_audioEffects.append(clsid);
}
}
break;
}
break;
#endif //QT_NO_PHONON_EFFECT
default:
break;
}
return ret;
}
QHash<QByteArray, QVariant> Backend::objectDescriptionProperties(Phonon::ObjectDescriptionType type, int index) const
{
QHash<QByteArray, QVariant> ret;
switch (type)
{
case Phonon::AudioOutputDeviceType:
{
#ifdef Q_OS_WINCE
ret["name"] = QLatin1String("default audio device");
#else
const AudioMoniker &mon = m_audioOutputs[index];
LPOLESTR str = 0;
HRESULT hr = mon->GetDisplayName(0,0, &str);
if (SUCCEEDED(hr)) {
QString name = QString::fromUtf16((unsigned short*)str);
ComPointer<IMalloc> alloc;
::CoGetMalloc(1, alloc.pparam());
alloc->Free(str);
ret["name"] = name.mid(name.indexOf('\\') + 1);
}
#endif
}
break;
#ifndef QT_NO_PHONON_EFFECT
case Phonon::EffectType:
{
WCHAR name[80]; // 80 is clearly stated in the MSDN doc
HRESULT hr = ::DMOGetName(m_audioEffects[index], name);
if (SUCCEEDED(hr)) {
ret["name"] = QString::fromUtf16((unsigned short*)name);
}
}
break;
#endif //QT_NO_PHONON_EFFECT
default:
break;
}
return ret;
}
bool Backend::endConnectionChange(QSet<QObject *> objects)
{
//end of a transaction
HRESULT hr = E_FAIL;
if (!objects.isEmpty()) {
Q_FOREACH(QObject *o, objects) {
if (BackendNode *node = qobject_cast<BackendNode*>(o)) {
MediaObject *mo = node->mediaObject();
if (mo && m_graphState.contains(mo)) {
switch(m_graphState[mo])
{
case Phonon::ErrorState:
case Phonon::StoppedState:
case Phonon::LoadingState:
//nothing to do
break;
case Phonon::PausedState:
mo->pause();
break;
default:
mo->play();
break;
}
if (mo->state() != Phonon::ErrorState) {
hr = S_OK;
}
m_graphState.remove(mo);
}
}
}
}
return SUCCEEDED(hr);
}
bool Backend::startConnectionChange(QSet<QObject *> objects)
{
//start a transaction
QSet<MediaObject*> mediaObjects;
//let's save the state of the graph (before we stop it)
Q_FOREACH(QObject *o, objects) {
if (BackendNode *node = qobject_cast<BackendNode*>(o)) {
if (MediaObject *mo = node->mediaObject()) {
mediaObjects << mo;
}
}
}
Q_FOREACH(MediaObject *mo, mediaObjects) {
m_graphState[mo] = mo->state();
mo->ensureStopped(); //we have to stop the graph..
}
return !mediaObjects.isEmpty();
}
bool Backend::connectNodes(QObject *_source, QObject *_sink)
{
BackendNode *source = qobject_cast<BackendNode*>(_source);
if (!source) {
return false;
}
BackendNode *sink = qobject_cast<BackendNode*>(_sink);
if (!sink) {
return false;
}
//setting the graph if needed
if (source->mediaObject() == 0 && sink->mediaObject() == 0) {
//error: no graph selected
return false;
} else if (source->mediaObject() && source->mediaObject() != sink->mediaObject()) {
//this' graph becomes the common one
source->mediaObject()->grabNode(sink);
} else if (source->mediaObject() == 0) {
//sink's graph becomes the common one
sink->mediaObject()->grabNode(source);
}
return source->mediaObject()->connectNodes(source, sink);
}
bool Backend::disconnectNodes(QObject *_source, QObject *_sink)
{
BackendNode *source = qobject_cast<BackendNode*>(_source);
if (!source) {
return false;
}
BackendNode *sink = qobject_cast<BackendNode*>(_sink);
if (!sink) {
return false;
}
return source->mediaObject() == 0 ||
source->mediaObject()->disconnectNodes(source, sink);
}
}
}
QT_END_NAMESPACE
#include "moc_backend.cpp"
<commit_msg>make autotest path when reconnecting a path with the exact same source and sink.<commit_after>/* This file is part of the KDE project.
Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies).
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 or 3 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, see <http://www.gnu.org/licenses/>.
*/
#include "backend.h"
#include "backendnode.h"
#include "audiooutput.h"
#include "effect.h"
#include "mediaobject.h"
#include "videowidget.h"
#include "volumeeffect.h"
//windows specific (DirectX Media Object)
#include <dmo.h>
#include <QtCore/QSettings>
#include <QtCore/QSet>
#include <QtCore/QVariant>
#include <QtCore/QtPlugin>
QT_BEGIN_NAMESPACE
Q_EXPORT_PLUGIN2(phonon_ds9, Phonon::DS9::Backend);
namespace Phonon
{
namespace DS9
{
bool Backend::AudioMoniker::operator==(const AudioMoniker &other)
{
return other->IsEqual(*this) == S_OK;
}
Backend::Backend(QObject *parent, const QVariantList &)
: QObject(parent)
{
::CoInitialize(0);
//registering meta types
qRegisterMetaType<HRESULT>("HRESULT");
qRegisterMetaType<QSet<Filter> >("QSet<Filter>");
qRegisterMetaType<Graph>("Graph");
}
Backend::~Backend()
{
m_audioOutputs.clear();
m_audioEffects.clear();
::CoUninitialize();
}
QObject *Backend::createObject(BackendInterface::Class c, QObject *parent, const QList<QVariant> &args)
{
switch (c)
{
case MediaObjectClass:
return new MediaObject(parent);
case AudioOutputClass:
return new AudioOutput(this, parent);
#ifndef QT_NO_PHONON_EFFECT
case EffectClass:
return new Effect(m_audioEffects[ args[0].toInt() ], parent);
#endif //QT_NO_PHONON_EFFECT
#ifndef QT_NO_PHONON_VIDEO
case VideoWidgetClass:
return new VideoWidget(qobject_cast<QWidget *>(parent));
#endif //QT_NO_PHONON_VIDEO
#ifndef QT_NO_PHONON_VOLUMEFADEREFFECT
case VolumeFaderEffectClass:
return new VolumeEffect(parent);
#endif //QT_NO_PHONON_VOLUMEFADEREFFECT
default:
return 0;
}
}
bool Backend::supportsVideo() const
{
#ifndef QT_NO_PHONON_VIDEO
return true;
#else
return false;
#endif //QT_NO_PHONON_VIDEO
}
QStringList Backend::availableMimeTypes() const
{
QSet<QString> ret;
const QStringList locations = QStringList() << QLatin1String("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Multimedia\\mplayer2\\mime types")
<< QLatin1String("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Multimedia\\wmplayer\\mime types");
Q_FOREACH(QString s, locations) {
QSettings settings(s, QSettings::NativeFormat);
ret += settings.childGroups().replaceInStrings("\\", "/").toSet();
}
QStringList list = ret.toList();
qSort(list);
return list;
}
Filter Backend::getAudioOutputFilter(int index) const
{
Filter ret;
if (index >= 0 && index < m_audioOutputs.count()) {
m_audioOutputs.at(index)->BindToObject(0, 0, IID_IBaseFilter, reinterpret_cast<void**>(&ret));
} else {
//just return the default audio renderer (not directsound)
ret = Filter(CLSID_AudioRender, IID_IBaseFilter);
}
return ret;
}
QList<int> Backend::objectDescriptionIndexes(Phonon::ObjectDescriptionType type) const
{
QList<int> ret;
switch(type)
{
case Phonon::AudioOutputDeviceType:
{
#ifdef Q_OS_WINCE
ret << 0; // only one audio device with index 0
#else
ComPointer<ICreateDevEnum> devEnum(CLSID_SystemDeviceEnum, IID_ICreateDevEnum);
if (!devEnum) {
return ret; //it is impossible to enumerate the devices
}
ComPointer<IEnumMoniker> enumMon;
HRESULT hr = devEnum->CreateClassEnumerator(CLSID_AudioRendererCategory, enumMon.pparam(), 0);
if (FAILED(hr)) {
break;
}
AudioMoniker mon;
//let's reorder the devices so that directshound appears first
int nbds = 0; //number of directsound devices
while (S_OK == enumMon->Next(1, mon.pparam(), 0)) {
LPOLESTR str = 0;
mon->GetDisplayName(0,0,&str);
const QString name = QString::fromUtf16((unsigned short*)str);
ComPointer<IMalloc> alloc;
::CoGetMalloc(1, alloc.pparam());
alloc->Free(str);
int insert_pos = 0;
if (!m_audioOutputs.contains(mon)) {
insert_pos = m_audioOutputs.count();
m_audioOutputs.append(mon);
} else {
insert_pos = m_audioOutputs.indexOf(mon);
}
if (name.contains(QLatin1String("DirectSound"))) {
ret.insert(nbds++, insert_pos);
} else {
ret.append(insert_pos);
}
}
#endif
break;
}
#ifndef QT_NO_PHONON_EFFECT
case Phonon::EffectType:
{
m_audioEffects.clear();
ComPointer<IEnumDMO> enumDMO;
HRESULT hr = ::DMOEnum(DMOCATEGORY_AUDIO_EFFECT, DMO_ENUMF_INCLUDE_KEYED, 0, 0, 0, 0, enumDMO.pparam());
if (SUCCEEDED(hr)) {
CLSID clsid;
while (S_OK == enumDMO->Next(1, &clsid, 0, 0)) {
ret += m_audioEffects.count();
m_audioEffects.append(clsid);
}
}
break;
}
break;
#endif //QT_NO_PHONON_EFFECT
default:
break;
}
return ret;
}
QHash<QByteArray, QVariant> Backend::objectDescriptionProperties(Phonon::ObjectDescriptionType type, int index) const
{
QHash<QByteArray, QVariant> ret;
switch (type)
{
case Phonon::AudioOutputDeviceType:
{
#ifdef Q_OS_WINCE
ret["name"] = QLatin1String("default audio device");
#else
const AudioMoniker &mon = m_audioOutputs[index];
LPOLESTR str = 0;
HRESULT hr = mon->GetDisplayName(0,0, &str);
if (SUCCEEDED(hr)) {
QString name = QString::fromUtf16((unsigned short*)str);
ComPointer<IMalloc> alloc;
::CoGetMalloc(1, alloc.pparam());
alloc->Free(str);
ret["name"] = name.mid(name.indexOf('\\') + 1);
}
#endif
}
break;
#ifndef QT_NO_PHONON_EFFECT
case Phonon::EffectType:
{
WCHAR name[80]; // 80 is clearly stated in the MSDN doc
HRESULT hr = ::DMOGetName(m_audioEffects[index], name);
if (SUCCEEDED(hr)) {
ret["name"] = QString::fromUtf16((unsigned short*)name);
}
}
break;
#endif //QT_NO_PHONON_EFFECT
default:
break;
}
return ret;
}
bool Backend::endConnectionChange(QSet<QObject *> objects)
{
//end of a transaction
HRESULT hr = E_FAIL;
if (!objects.isEmpty()) {
Q_FOREACH(QObject *o, objects) {
if (BackendNode *node = qobject_cast<BackendNode*>(o)) {
MediaObject *mo = node->mediaObject();
if (mo && m_graphState.contains(mo)) {
switch(m_graphState[mo])
{
case Phonon::ErrorState:
case Phonon::StoppedState:
case Phonon::LoadingState:
//nothing to do
break;
case Phonon::PausedState:
mo->pause();
break;
default:
mo->play();
break;
}
if (mo->state() != Phonon::ErrorState) {
hr = S_OK;
}
m_graphState.remove(mo);
}
}
}
}
return SUCCEEDED(hr);
}
bool Backend::startConnectionChange(QSet<QObject *> objects)
{
//start a transaction
QSet<MediaObject*> mediaObjects;
//let's save the state of the graph (before we stop it)
Q_FOREACH(QObject *o, objects) {
if (BackendNode *node = qobject_cast<BackendNode*>(o)) {
if (MediaObject *mo = node->mediaObject()) {
mediaObjects << mo;
}
}
}
Q_FOREACH(MediaObject *mo, mediaObjects) {
m_graphState[mo] = mo->state();
mo->ensureStopped(); //we have to stop the graph..
}
return objects.isEmpty() || !mediaObjects.isEmpty();
}
bool Backend::connectNodes(QObject *_source, QObject *_sink)
{
BackendNode *source = qobject_cast<BackendNode*>(_source);
if (!source) {
return false;
}
BackendNode *sink = qobject_cast<BackendNode*>(_sink);
if (!sink) {
return false;
}
//setting the graph if needed
if (source->mediaObject() == 0 && sink->mediaObject() == 0) {
//error: no graph selected
return false;
} else if (source->mediaObject() && source->mediaObject() != sink->mediaObject()) {
//this' graph becomes the common one
source->mediaObject()->grabNode(sink);
} else if (source->mediaObject() == 0) {
//sink's graph becomes the common one
sink->mediaObject()->grabNode(source);
}
return source->mediaObject()->connectNodes(source, sink);
}
bool Backend::disconnectNodes(QObject *_source, QObject *_sink)
{
BackendNode *source = qobject_cast<BackendNode*>(_source);
if (!source) {
return false;
}
BackendNode *sink = qobject_cast<BackendNode*>(_sink);
if (!sink) {
return false;
}
return source->mediaObject() == 0 ||
source->mediaObject()->disconnectNodes(source, sink);
}
}
}
QT_END_NAMESPACE
#include "moc_backend.cpp"
<|endoftext|>
|
<commit_before>/*
* nextpnr -- Next Generation Place and Route
*
* Copyright (C) 2018 David Shah <david@symbioticeda.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include <algorithm>
#include <iomanip>
#include <queue>
#include "nextpnr.h"
#include "cells.h"
#include "globals.h"
#include "log.h"
#define fmt_str(x) (static_cast<const std::ostringstream &>(std::ostringstream() << x).str())
NEXTPNR_NAMESPACE_BEGIN
static std::string get_quad_name(GlobalQuadrant quad)
{
switch (quad) {
case QUAD_UL:
return "UL";
case QUAD_UR:
return "UR";
case QUAD_LL:
return "LL";
case QUAD_LR:
return "LR";
}
return "";
}
class Ecp5GlobalRouter
{
public:
Ecp5GlobalRouter(Context *ctx) : ctx(ctx){};
private:
bool is_clock_port(const PortRef &user)
{
if (user.cell->type == id_TRELLIS_SLICE && user.port == id_CLK)
return true;
return false;
}
std::vector<NetInfo *> get_clocks()
{
std::unordered_map<IdString, int> clockCount;
for (auto &net : ctx->nets) {
NetInfo *ni = net.second.get();
clockCount[ni->name] = 0;
for (const auto &user : ni->users) {
if (is_clock_port(user))
clockCount[ni->name]++;
}
//log_info("clkcount %s: %d\n", ni->name.c_str(ctx),clockCount[ni->name]);
}
std::vector<NetInfo *> clocks;
while (clocks.size() < 16) {
auto max = std::max_element(clockCount.begin(), clockCount.end(),
[](const decltype(clockCount)::value_type &a,
const decltype(clockCount)::value_type &b) { return a.second < b.second; });
if (max == clockCount.end() || max->second < 5)
break;
clocks.push_back(ctx->nets.at(max->first).get());
clockCount.erase(max->first);
}
return clocks;
}
PipId find_tap_pip(WireId tile_glb)
{
std::string wireName = ctx->getWireBasename(tile_glb).str(ctx);
std::string glbName = wireName.substr(2);
TapDirection td = ctx->globalInfoAtLoc(tile_glb.location).tap_dir;
WireId tap_wire;
Location tap_loc;
tap_loc.x = ctx->globalInfoAtLoc(tile_glb.location).tap_col;
tap_loc.y = tile_glb.location.y;
if (td == TAP_DIR_LEFT) {
tap_wire = ctx->getWireByLocAndBasename(tap_loc, "L_" + glbName);
} else {
tap_wire = ctx->getWireByLocAndBasename(tap_loc, "R_" + glbName);
}
return *(ctx->getPipsUphill(tap_wire).begin());
}
PipId find_spine_pip(WireId tap_wire)
{
std::string wireName = ctx->getWireBasename(tap_wire).str(ctx);
Location spine_loc;
spine_loc.x = ctx->globalInfoAtLoc(tap_wire.location).spine_col;
spine_loc.y = ctx->globalInfoAtLoc(tap_wire.location).spine_row;
WireId spine_wire = ctx->getWireByLocAndBasename(spine_loc, wireName);
return *(ctx->getPipsUphill(spine_wire).begin());
}
void route_logic_tile_global(NetInfo *net, int global_index, PortRef user)
{
WireId userWire = ctx->getBelPinWire(user.cell->bel, user.port);
WireId globalWire;
IdString global_name = ctx->id(fmt_str("G_HPBX" << std::setw(2) << std::setfill('0') << global_index << "00"));
std::queue<WireId> upstream;
std::unordered_map<WireId, PipId> backtrace;
upstream.push(userWire);
bool already_routed = false;
// Search back from the pin until we reach the global network
while (true) {
WireId next = upstream.front();
upstream.pop();
if (ctx->getBoundWireNet(next) == net) {
already_routed = true;
globalWire = next;
break;
}
if (ctx->getWireBasename(next) == global_name) {
globalWire = next;
break;
}
if (ctx->checkWireAvail(next)) {
for (auto pip : ctx->getPipsUphill(next)) {
WireId src = ctx->getPipSrcWire(pip);
backtrace[src] = pip;
upstream.push(src);
}
}
if (upstream.size() > 3000) {
log_error("failed to route HPBX%02d00 to %s.%s\n", global_index,
ctx->getBelName(user.cell->bel).c_str(ctx), user.port.c_str(ctx));
}
}
// Set all the pips we found along the way
WireId cursor = userWire;
while (true) {
auto fnd = backtrace.find(cursor);
if (fnd == backtrace.end())
break;
ctx->bindPip(fnd->second, net, STRENGTH_LOCKED);
cursor = ctx->getPipSrcWire(fnd->second);
}
// If the global network inside the tile isn't already set up,
// we also need to bind the buffers along the way
if (!already_routed) {
ctx->bindWire(cursor, net, STRENGTH_LOCKED);
PipId tap_pip = find_tap_pip(cursor);
NetInfo *tap_net = ctx->getBoundPipNet(tap_pip);
if (tap_net == nullptr) {
ctx->bindPip(tap_pip, net, STRENGTH_LOCKED);
PipId spine_pip = find_spine_pip(ctx->getPipSrcWire(tap_pip));
NetInfo *spine_net = ctx->getBoundPipNet(spine_pip);
if (spine_net == nullptr) {
ctx->bindPip(spine_pip, net, STRENGTH_LOCKED);
} else {
NPNR_ASSERT(spine_net == net);
}
} else {
NPNR_ASSERT(tap_net == net);
}
}
}
bool is_global_io(CellInfo *io, std::string &glb_name)
{
std::string func_name = ctx->getPioFunctionName(io->bel);
if (func_name.substr(0, 5) == "PCLKT") {
func_name.erase(func_name.find('_'), 1);
glb_name = "G_" + func_name;
return true;
}
return false;
}
WireId get_global_wire(GlobalQuadrant quad, int network)
{
return ctx->getWireByLocAndBasename(Location(0, 0), "G_" + get_quad_name(quad) + "PCLK" + std::to_string(network));
}
bool simple_router(NetInfo *net, WireId src, WireId dst, bool allow_fail = false)
{
std::queue<WireId> visit;
std::unordered_map<WireId, PipId> backtrace;
visit.push(src);
WireId cursor;
while (true) {
if (visit.empty() || visit.size() > 50000) {
if (allow_fail)
return false;
log_error("cannot route global from %s to %s.\n", ctx->getWireName(src).c_str(ctx),
ctx->getWireName(dst).c_str(ctx));
}
cursor = visit.back();
visit.pop();
NetInfo *bound = ctx->getBoundWireNet(cursor);
if (bound == net) {
break;
} else if (bound != nullptr) {
continue;
}
if (cursor == dst)
break;
for (auto dh : ctx->getPipsDownhill(cursor)) {
WireId pipDst = ctx->getPipDstWire(dh);
if (backtrace.count(pipDst))
continue;
backtrace[pipDst] = dh;
visit.push(pipDst);
}
}
while (true) {
auto fnd = backtrace.find(cursor);
if (fnd == backtrace.end())
break;
ctx->bindPip(fnd->second, net, STRENGTH_LOCKED);
cursor = ctx->getPipSrcWire(fnd->second);
}
return true;
}
bool route_onto_global(NetInfo *net, int network)
{
WireId glb_src;
NPNR_ASSERT(net->driver.cell->type == id_DCCA);
glb_src = ctx->getNetinfoSourceWire(net);
for (int quad = QUAD_UL; quad < QUAD_LR + 1; quad++) {
WireId glb_dst = get_global_wire(GlobalQuadrant(quad), network);
NPNR_ASSERT(glb_dst != WireId());
bool routed = simple_router(net, glb_src, glb_dst);
if (!routed)
return false;
}
return true;
}
// Attempt to place a DCC
void place_dcc(CellInfo *dcc) {
for (auto bel : ctx->getBels()) {
if (ctx->getBelType(bel) == id_DCCA && ctx->checkBelAvail(bel)) {
if (ctx->isValidBelForCell(dcc, bel)) {
ctx->bindBel(bel, dcc, STRENGTH_LOCKED);
return;
}
}
}
NPNR_ASSERT_FALSE("failed to place dcca");
}
// Insert a DCC into a net to promote it to a global
NetInfo *insert_dcc(NetInfo *net)
{
auto dcc = create_ecp5_cell(ctx, id_DCCA, "$gbuf$" + net->name.str(ctx));
std::unique_ptr<NetInfo> glbnet = std::unique_ptr<NetInfo>(new NetInfo);
glbnet->name = ctx->id("$glbnet$" + net->name.str(ctx));
glbnet->driver.cell = dcc.get();
glbnet->driver.port = id_CLKO;
for (auto user : net->users) {
user.cell->ports.at(user.port).net = glbnet.get();
}
net->users.clear();
dcc->ports[id_CLKI].net = net;
PortRef clki_pr;
clki_pr.port = id_CLKI;
clki_pr.cell = dcc.get();
net->users.push_back(clki_pr);
place_dcc(dcc.get());
ctx->cells[dcc->name] = std::move(dcc);
NetInfo *glbptr = glbnet.get();
ctx->nets[glbnet->name] = std::move(glbnet);
return glbptr;
}
Context *ctx;
public:
void promote_and_route_globals() {
log_info("Promoting and routing globals...");
auto clocks = get_clocks();
int glbid = 0;
for (auto clock : clocks) {
log_info(" promoting clock net %s to global %d\n", clock->name.c_str(ctx), glbid);
auto old_users = clock->users;
NetInfo *global = insert_dcc(clock);
bool routed = route_onto_global(global, glbid);
NPNR_ASSERT(routed);
for (const auto &user : global->users) {
route_logic_tile_global(global, glbid, user);
}
glbid++;
}
}
};
void route_ecp5_globals(Context *ctx) {
Ecp5GlobalRouter(ctx).promote_and_route_globals();
}
NEXTPNR_NAMESPACE_END
<commit_msg>ecp5: Fixing global router bugs<commit_after>/*
* nextpnr -- Next Generation Place and Route
*
* Copyright (C) 2018 David Shah <david@symbioticeda.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include <algorithm>
#include <iomanip>
#include <queue>
#include "nextpnr.h"
#include "cells.h"
#include "globals.h"
#include "log.h"
#define fmt_str(x) (static_cast<const std::ostringstream &>(std::ostringstream() << x).str())
NEXTPNR_NAMESPACE_BEGIN
static std::string get_quad_name(GlobalQuadrant quad)
{
switch (quad) {
case QUAD_UL:
return "UL";
case QUAD_UR:
return "UR";
case QUAD_LL:
return "LL";
case QUAD_LR:
return "LR";
}
return "";
}
class Ecp5GlobalRouter
{
public:
Ecp5GlobalRouter(Context *ctx) : ctx(ctx){};
private:
bool is_clock_port(const PortRef &user)
{
if (user.cell->type == id_TRELLIS_SLICE && user.port == id_CLK)
return true;
return false;
}
std::vector<NetInfo *> get_clocks()
{
std::unordered_map<IdString, int> clockCount;
for (auto &net : ctx->nets) {
NetInfo *ni = net.second.get();
clockCount[ni->name] = 0;
for (const auto &user : ni->users) {
if (is_clock_port(user))
clockCount[ni->name]++;
}
//log_info("clkcount %s: %d\n", ni->name.c_str(ctx),clockCount[ni->name]);
}
std::vector<NetInfo *> clocks;
while (clocks.size() < 16) {
auto max = std::max_element(clockCount.begin(), clockCount.end(),
[](const decltype(clockCount)::value_type &a,
const decltype(clockCount)::value_type &b) { return a.second < b.second; });
if (max == clockCount.end() || max->second < 5)
break;
clocks.push_back(ctx->nets.at(max->first).get());
clockCount.erase(max->first);
}
return clocks;
}
PipId find_tap_pip(WireId tile_glb)
{
std::string wireName = ctx->getWireBasename(tile_glb).str(ctx);
std::string glbName = wireName.substr(2);
TapDirection td = ctx->globalInfoAtLoc(tile_glb.location).tap_dir;
WireId tap_wire;
Location tap_loc;
tap_loc.x = ctx->globalInfoAtLoc(tile_glb.location).tap_col;
tap_loc.y = tile_glb.location.y;
if (td == TAP_DIR_LEFT) {
tap_wire = ctx->getWireByLocAndBasename(tap_loc, "L_" + glbName);
} else {
tap_wire = ctx->getWireByLocAndBasename(tap_loc, "R_" + glbName);
}
return *(ctx->getPipsUphill(tap_wire).begin());
}
PipId find_spine_pip(WireId tap_wire)
{
std::string wireName = ctx->getWireBasename(tap_wire).str(ctx);
Location spine_loc;
spine_loc.x = ctx->globalInfoAtLoc(tap_wire.location).spine_col;
spine_loc.y = ctx->globalInfoAtLoc(tap_wire.location).spine_row;
WireId spine_wire = ctx->getWireByLocAndBasename(spine_loc, wireName);
return *(ctx->getPipsUphill(spine_wire).begin());
}
void route_logic_tile_global(NetInfo *net, int global_index, PortRef user)
{
WireId userWire = ctx->getBelPinWire(user.cell->bel, user.port);
WireId globalWire;
IdString global_name = ctx->id(fmt_str("G_HPBX" << std::setw(2) << std::setfill('0') << global_index << "00"));
std::queue<WireId> upstream;
std::unordered_map<WireId, PipId> backtrace;
upstream.push(userWire);
bool already_routed = false;
// Search back from the pin until we reach the global network
while (true) {
WireId next = upstream.front();
upstream.pop();
if (ctx->getBoundWireNet(next) == net) {
already_routed = true;
globalWire = next;
break;
}
if (ctx->getWireBasename(next) == global_name) {
globalWire = next;
break;
}
if (ctx->checkWireAvail(next)) {
for (auto pip : ctx->getPipsUphill(next)) {
WireId src = ctx->getPipSrcWire(pip);
backtrace[src] = pip;
upstream.push(src);
}
}
if (upstream.size() > 3000) {
log_error("failed to route HPBX%02d00 to %s.%s\n", global_index,
ctx->getBelName(user.cell->bel).c_str(ctx), user.port.c_str(ctx));
}
}
// Set all the pips we found along the way
WireId cursor = userWire;
while (true) {
auto fnd = backtrace.find(cursor);
if (fnd == backtrace.end())
break;
ctx->bindPip(fnd->second, net, STRENGTH_LOCKED);
cursor = ctx->getPipSrcWire(fnd->second);
}
// If the global network inside the tile isn't already set up,
// we also need to bind the buffers along the way
if (!already_routed) {
ctx->bindWire(cursor, net, STRENGTH_LOCKED);
PipId tap_pip = find_tap_pip(cursor);
NetInfo *tap_net = ctx->getBoundPipNet(tap_pip);
if (tap_net == nullptr) {
ctx->bindPip(tap_pip, net, STRENGTH_LOCKED);
PipId spine_pip = find_spine_pip(ctx->getPipSrcWire(tap_pip));
NetInfo *spine_net = ctx->getBoundPipNet(spine_pip);
if (spine_net == nullptr) {
ctx->bindPip(spine_pip, net, STRENGTH_LOCKED);
} else {
NPNR_ASSERT(spine_net == net);
}
} else {
NPNR_ASSERT(tap_net == net);
}
}
}
bool is_global_io(CellInfo *io, std::string &glb_name)
{
std::string func_name = ctx->getPioFunctionName(io->bel);
if (func_name.substr(0, 5) == "PCLKT") {
func_name.erase(func_name.find('_'), 1);
glb_name = "G_" + func_name;
return true;
}
return false;
}
WireId get_global_wire(GlobalQuadrant quad, int network)
{
return ctx->getWireByLocAndBasename(Location(0, 0), "G_" + get_quad_name(quad) + "PCLK" + std::to_string(network));
}
bool simple_router(NetInfo *net, WireId src, WireId dst, bool allow_fail = false)
{
std::queue<WireId> visit;
std::unordered_map<WireId, PipId> backtrace;
visit.push(src);
WireId cursor;
while (true) {
if (visit.empty() || visit.size() > 50000) {
if (allow_fail)
return false;
log_error("cannot route global from %s to %s.\n", ctx->getWireName(src).c_str(ctx),
ctx->getWireName(dst).c_str(ctx));
}
cursor = visit.front();
visit.pop();
NetInfo *bound = ctx->getBoundWireNet(cursor);
if (ctx->verbose)
log_info(" exploring %s\n", ctx->getWireName(cursor).c_str(ctx));
if (bound == net) {
} else if (bound != nullptr) {
continue;
}
if (cursor == dst)
break;
for (auto dh : ctx->getPipsDownhill(cursor)) {
WireId pipDst = ctx->getPipDstWire(dh);
if (ctx->verbose)
log_info(" downhill -> %s\n", ctx->getWireName(pipDst).c_str(ctx));
if (backtrace.count(pipDst))
continue;
backtrace[pipDst] = dh;
visit.push(pipDst);
}
}
while (true) {
auto fnd = backtrace.find(cursor);
if (fnd == backtrace.end())
break;
NetInfo * bound = ctx->getBoundWireNet(cursor);
if (bound != nullptr) {
NPNR_ASSERT(bound == net);
break;
}
ctx->bindPip(fnd->second, net, STRENGTH_LOCKED);
cursor = ctx->getPipSrcWire(fnd->second);
}
if (ctx->getBoundWireNet(src) == nullptr)
ctx->bindWire(src, net, STRENGTH_LOCKED);
return true;
}
bool route_onto_global(NetInfo *net, int network)
{
WireId glb_src;
NPNR_ASSERT(net->driver.cell->type == id_DCCA);
glb_src = ctx->getNetinfoSourceWire(net);
for (int quad = QUAD_UL; quad < QUAD_LR + 1; quad++) {
WireId glb_dst = get_global_wire(GlobalQuadrant(quad), network);
NPNR_ASSERT(glb_dst != WireId());
bool routed = simple_router(net, glb_src, glb_dst);
if (!routed)
return false;
}
return true;
}
// Attempt to place a DCC
void place_dcc(CellInfo *dcc) {
for (auto bel : ctx->getBels()) {
if (ctx->getBelType(bel) == id_DCCA && ctx->checkBelAvail(bel)) {
if (ctx->isValidBelForCell(dcc, bel)) {
ctx->bindBel(bel, dcc, STRENGTH_LOCKED);
return;
}
}
}
NPNR_ASSERT_FALSE("failed to place dcca");
}
// Insert a DCC into a net to promote it to a global
NetInfo *insert_dcc(NetInfo *net)
{
auto dcc = create_ecp5_cell(ctx, id_DCCA, "$gbuf$" + net->name.str(ctx));
std::unique_ptr<NetInfo> glbnet = std::unique_ptr<NetInfo>(new NetInfo);
glbnet->name = ctx->id("$glbnet$" + net->name.str(ctx));
glbnet->driver.cell = dcc.get();
glbnet->driver.port = id_CLKO;
for (auto user : net->users) {
user.cell->ports.at(user.port).net = glbnet.get();
}
net->users.clear();
dcc->ports[id_CLKI].net = net;
PortRef clki_pr;
clki_pr.port = id_CLKI;
clki_pr.cell = dcc.get();
net->users.push_back(clki_pr);
place_dcc(dcc.get());
ctx->cells[dcc->name] = std::move(dcc);
NetInfo *glbptr = glbnet.get();
ctx->nets[glbnet->name] = std::move(glbnet);
return glbptr;
}
Context *ctx;
public:
void promote_and_route_globals() {
log_info("Promoting and routing globals...\n");
auto clocks = get_clocks();
int glbid = 0;
for (auto clock : clocks) {
log_info(" promoting clock net %s to global %d\n", clock->name.c_str(ctx), glbid);
auto old_users = clock->users;
NetInfo *global = insert_dcc(clock);
bool routed = route_onto_global(global, glbid);
NPNR_ASSERT(routed);
for (const auto &user : global->users) {
route_logic_tile_global(global, glbid, user);
}
glbid++;
}
}
};
void route_ecp5_globals(Context *ctx) {
Ecp5GlobalRouter(ctx).promote_and_route_globals();
}
NEXTPNR_NAMESPACE_END
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2016, Patricio Gonzalez Vivo
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "fbo.h"
#include <iostream>
Fbo::Fbo():m_id(0), m_old_fbo_id(0), m_texture(0), m_depth_buffer(0), m_depth_texture(0), m_type(COLOR_TEXTURE), m_width(0), m_height(0), m_allocated(false), m_binded(false), m_depth(false) {
}
Fbo::~Fbo() {
unbind();
if (m_allocated) {
glDeleteTextures(1, &m_texture);
glDeleteRenderbuffers(1, &m_depth_buffer);
glDeleteFramebuffers(1, &m_id);
m_allocated = false;
}
}
void Fbo::allocate(const uint _width, const uint _height, FboType _type) {
m_type = _type;
bool color_texture = true;
bool depth_texture = false;
switch(_type) {
case COLOR_TEXTURE:
m_depth = false;
color_texture = true;
depth_texture = false;
break;
case COLOR_TEXTURE_DEPTH_BUFFER:
m_depth = true;
color_texture = true;
depth_texture = false;
break;
case COLOR_DEPTH_TEXTURES:
m_depth = true;
color_texture = true;
depth_texture = true;
break;
case DEPTH_TEXTURE:
m_depth = true;
color_texture = false;
depth_texture = true;
break;
}
if (!m_allocated) {
// Create a frame buffer
glGenFramebuffers(1, &m_id);
if (color_texture) {
// Generate a texture to hold the colour buffer
glGenTextures(1, &m_texture);
}
if (m_depth) {
// Create a texture to hold the depth buffer
glGenRenderbuffers(1, &m_depth_buffer);
}
}
m_width = _width;
m_height = _height;
bind();
if (color_texture) {
// Color
glBindTexture(GL_TEXTURE_2D, m_texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_width, m_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
// glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_texture, 0);
}
// Depth Buffer
if (m_depth) {
glBindRenderbuffer(GL_RENDERBUFFER, m_depth_buffer);
#ifdef PLATFORM_RPI
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, m_width, m_height);
#else
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, m_width, m_height);
#endif
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_depth_buffer);
if (depth_texture) {
// Generate a texture to hold the depth buffer
if (m_depth_texture == 0) {
glGenTextures(1, &m_depth_texture);
}
glBindTexture(GL_TEXTURE_2D, m_depth_texture);
#ifdef PLATFORM_RPI
// glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, m_width, m_height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, m_width, m_height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, NULL);
#else
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, m_width, m_height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
#endif
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, m_depth_texture, 0);
}
}
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE) {
m_allocated = true;
}
else {
std::cout << "FBO: not complete" << std::endl;
}
unbind();
glBindTexture(GL_TEXTURE_2D, 0);
if (m_depth){
glBindRenderbuffer(GL_RENDERBUFFER, 0);
}
}
void Fbo::bind() {
if (!m_binded) {
glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint *)&m_old_fbo_id);
glBindTexture(GL_TEXTURE_2D, 0);
glEnable(GL_TEXTURE_2D);
glBindFramebuffer(GL_FRAMEBUFFER, m_id);
glViewport(0.0f, 0.0f, m_width, m_height);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
if (m_depth) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
} else {
glClear(GL_COLOR_BUFFER_BIT);
}
m_binded = true;
}
}
void Fbo::unbind() {
if (m_binded) {
glBindFramebuffer(GL_FRAMEBUFFER, m_old_fbo_id);
m_binded = false;
}
}
<commit_msg>non working<commit_after>/*
Copyright (c) 2016, Patricio Gonzalez Vivo
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "fbo.h"
#include <iostream>
Fbo::Fbo():m_id(0), m_old_fbo_id(0), m_texture(0), m_depth_buffer(0), m_depth_texture(0), m_type(COLOR_TEXTURE), m_width(0), m_height(0), m_allocated(false), m_binded(false), m_depth(false) {
}
Fbo::~Fbo() {
unbind();
if (m_allocated) {
glDeleteTextures(1, &m_texture);
glDeleteRenderbuffers(1, &m_depth_buffer);
glDeleteFramebuffers(1, &m_id);
m_allocated = false;
}
}
void Fbo::allocate(const uint _width, const uint _height, FboType _type) {
m_type = _type;
bool color_texture = true;
bool depth_texture = false;
switch(_type) {
case COLOR_TEXTURE:
m_depth = false;
color_texture = true;
depth_texture = false;
break;
case COLOR_TEXTURE_DEPTH_BUFFER:
m_depth = true;
color_texture = true;
depth_texture = false;
break;
case COLOR_DEPTH_TEXTURES:
m_depth = true;
color_texture = true;
depth_texture = true;
break;
case DEPTH_TEXTURE:
m_depth = true;
color_texture = false;
depth_texture = true;
break;
}
if (!m_allocated) {
// Create a frame buffer
glGenFramebuffers(1, &m_id);
if (color_texture) {
// Generate a texture to hold the colour buffer
glGenTextures(1, &m_texture);
}
if (m_depth) {
// Create a texture to hold the depth buffer
glGenRenderbuffers(1, &m_depth_buffer);
}
}
m_width = _width;
m_height = _height;
bind();
if (color_texture) {
// Color
glBindTexture(GL_TEXTURE_2D, m_texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_width, m_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
// glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_texture, 0);
}
// Depth Buffer
if (m_depth) {
glBindRenderbuffer(GL_RENDERBUFFER, m_depth_buffer);
#ifdef PLATFORM_RPI
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, m_width, m_height);
#else
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, m_width, m_height);
#endif
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_depth_buffer);
if (depth_texture) {
// Generate a texture to hold the depth buffer
if (m_depth_texture == 0) {
glGenTextures(1, &m_depth_texture);
}
glBindTexture(GL_TEXTURE_2D, m_depth_texture);
#ifdef PLATFORM_RPI
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, m_width, m_height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
// glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, m_width, m_height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL);
// glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, m_width, m_height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, NULL);
#else
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, m_width, m_height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
#endif
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, m_depth_texture, 0);
}
}
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE) {
m_allocated = true;
}
else {
std::cout << "FBO: not complete" << std::endl;
}
unbind();
glBindTexture(GL_TEXTURE_2D, 0);
if (m_depth){
glBindRenderbuffer(GL_RENDERBUFFER, 0);
}
}
void Fbo::bind() {
if (!m_binded) {
glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint *)&m_old_fbo_id);
glBindTexture(GL_TEXTURE_2D, 0);
glEnable(GL_TEXTURE_2D);
glBindFramebuffer(GL_FRAMEBUFFER, m_id);
glViewport(0.0f, 0.0f, m_width, m_height);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
if (m_depth) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
} else {
glClear(GL_COLOR_BUFFER_BIT);
}
m_binded = true;
}
}
void Fbo::unbind() {
if (m_binded) {
glBindFramebuffer(GL_FRAMEBUFFER, m_old_fbo_id);
m_binded = false;
}
}
<|endoftext|>
|
<commit_before>// cc_lang.cc see license.txt for copyright and terms of use
// code for cc_lang.h
#include "cc_lang.h" // this module
#include <string.h> // memset
void CCLang::ANSI_C()
{
// just in case I forget to initialize something....
memset(this, 0, sizeof(*this));
tagsAreTypes = false;
recognizeCppKeywords = false;
implicitFuncVariable = false;
gccFuncBehavior = GFB_none;
noInnerClasses = true;
uninitializedGlobalDataIsCommon = true;
emptyParamsMeansPureVarargFunc = false;
complainUponBadDeref = true;
strictArraySizeRequirements = false;
allowOverloading = false;
compoundSelfName = false;
allowCallToUndeclFunc = false;
allow_KR_ParamOmit = false;
allowImplicitInt = true;
allowDynamicallySizedArrays = false;
allowIncompleteEnums = false;
declareGNUBuiltins = false;
isCplusplus = false;
isC99 = false;
}
void CCLang::KandR_C()
{
ANSI_C();
emptyParamsMeansPureVarargFunc = true;
allowCallToUndeclFunc = true;
allow_KR_ParamOmit = true;
allowImplicitInt = true;
// our K&R is really GNU K&R ...
declareGNUBuiltins = true;
}
void CCLang::ANSI_C99()
{
ANSI_C();
implicitFuncVariable = true;
allowImplicitInt = false;
isC99 = true;
}
void CCLang::GNU_C()
{
ANSI_C99();
allowImplicitInt = true;
gccFuncBehavior = GFB_string;
allowDynamicallySizedArrays = true;
declareGNUBuiltins = true;
// I'm just guessing this is GNU only.... yep:
// http://gcc.gnu.org/onlinedocs/gcc-3.1/gcc/Incomplete-Enums.html
allowIncompleteEnums = true;
}
void CCLang::GNU_KandR_C()
{
KandR_C();
implicitFuncVariable = true;
gccFuncBehavior = GFB_string;
allowDynamicallySizedArrays = true;
// this seems wrong, but Oink's tests want it this way...
isC99 = true;
}
void CCLang::GNU2_KandR_C()
{
GNU_KandR_C();
// seems to not be true for gcc 2.96 at least
isC99 = false;
}
void CCLang::ANSI_Cplusplus()
{
tagsAreTypes = true;
recognizeCppKeywords = true;
implicitFuncVariable = false;
gccFuncBehavior = GFB_none;
noInnerClasses = false;
uninitializedGlobalDataIsCommon = false;
emptyParamsMeansPureVarargFunc = false;
// these aren't exactly ANSI C++; they might be "pragmatic C++"
// for the current state of the parser
complainUponBadDeref = false;
strictArraySizeRequirements = false;
allowOverloading = true;
compoundSelfName = true;
allowCallToUndeclFunc = false;
allow_KR_ParamOmit = false;
allowImplicitInt = false;
allowDynamicallySizedArrays = false;
allowIncompleteEnums = false;
declareGNUBuiltins = false;
isCplusplus = true;
isC99 = false;
}
void CCLang::GNU_Cplusplus()
{
ANSI_Cplusplus();
gccFuncBehavior = GFB_variable;
// is this really right? Oink tests it like it is ...
allowDynamicallySizedArrays = true;
declareGNUBuiltins = true;
}
// EOF
<commit_msg>GNU_KandR_C() now allows incomplete enums<commit_after>// cc_lang.cc see license.txt for copyright and terms of use
// code for cc_lang.h
#include "cc_lang.h" // this module
#include <string.h> // memset
void CCLang::ANSI_C()
{
// just in case I forget to initialize something....
memset(this, 0, sizeof(*this));
tagsAreTypes = false;
recognizeCppKeywords = false;
implicitFuncVariable = false;
gccFuncBehavior = GFB_none;
noInnerClasses = true;
uninitializedGlobalDataIsCommon = true;
emptyParamsMeansPureVarargFunc = false;
complainUponBadDeref = true;
strictArraySizeRequirements = false;
allowOverloading = false;
compoundSelfName = false;
allowCallToUndeclFunc = false;
allow_KR_ParamOmit = false;
allowImplicitInt = true;
allowDynamicallySizedArrays = false;
allowIncompleteEnums = false;
declareGNUBuiltins = false;
isCplusplus = false;
isC99 = false;
}
void CCLang::KandR_C()
{
ANSI_C();
emptyParamsMeansPureVarargFunc = true;
allowCallToUndeclFunc = true;
allow_KR_ParamOmit = true;
allowImplicitInt = true;
// our K&R is really GNU K&R ...
declareGNUBuiltins = true;
}
void CCLang::ANSI_C99()
{
ANSI_C();
implicitFuncVariable = true;
allowImplicitInt = false;
isC99 = true;
}
void CCLang::GNU_C()
{
ANSI_C99();
allowImplicitInt = true;
gccFuncBehavior = GFB_string;
allowDynamicallySizedArrays = true;
declareGNUBuiltins = true;
// I'm just guessing this is GNU only.... yep:
// http://gcc.gnu.org/onlinedocs/gcc-3.1/gcc/Incomplete-Enums.html
allowIncompleteEnums = true;
}
// dsw: FIX: Multiple inheritance problem: should this be an extension
// of GNU_C() or of KandR_C(). This shows up because in GNU_C() you
// set allowIncompleteEnums = true but here you don't.
void CCLang::GNU_KandR_C()
{
KandR_C();
implicitFuncVariable = true;
gccFuncBehavior = GFB_string;
allowDynamicallySizedArrays = true;
allowIncompleteEnums = true; // gnu according to Scott, above
// this seems wrong, but Oink's tests want it this way...
isC99 = true;
}
void CCLang::GNU2_KandR_C()
{
GNU_KandR_C();
// seems to not be true for gcc 2.96 at least
isC99 = false;
}
void CCLang::ANSI_Cplusplus()
{
tagsAreTypes = true;
recognizeCppKeywords = true;
implicitFuncVariable = false;
gccFuncBehavior = GFB_none;
noInnerClasses = false;
uninitializedGlobalDataIsCommon = false;
emptyParamsMeansPureVarargFunc = false;
// these aren't exactly ANSI C++; they might be "pragmatic C++"
// for the current state of the parser
complainUponBadDeref = false;
strictArraySizeRequirements = false;
allowOverloading = true;
compoundSelfName = true;
allowCallToUndeclFunc = false;
allow_KR_ParamOmit = false;
allowImplicitInt = false;
allowDynamicallySizedArrays = false;
allowIncompleteEnums = false;
declareGNUBuiltins = false;
isCplusplus = true;
isC99 = false;
}
void CCLang::GNU_Cplusplus()
{
ANSI_Cplusplus();
gccFuncBehavior = GFB_variable;
// is this really right? Oink tests it like it is ...
allowDynamicallySizedArrays = true;
declareGNUBuiltins = true;
}
// EOF
<|endoftext|>
|
<commit_before>#include "enumcreator.h"
#include "protocolparser.h"
#include <QStringList>
#include <math.h>
EnumCreator::EnumCreator(const QDomElement& e):
minbitwidth(0)
{
parse(e);
}
void EnumCreator::clear(void)
{
minbitwidth = 0;
name.clear();
comment.clear();
output.clear();
nameList.clear();
commentList.clear();
valueList.clear();
numberList.clear();
}
/*!
* Parse an Enum tag from the xml to create an enumeration.
* \param e is the Enum tag DOM element
* \return A string (including linefeeds) to declare the enumeration
*/
QString EnumCreator::parse(const QDomElement& e)
{
clear();
name = e.attribute("name");
comment = e.attribute("comment");
description = e.attribute("description");
//If the enum struct has the attribute 'hidden="true"', it won't be displayed in the documentation
hidden = ProtocolParser::isFieldSet(e,"hidden");
QDomNodeList list = e.elementsByTagName("Value");
// If we have no entries there is nothing to do
if(list.size() <= 0)
return output;
// Put the top level comment in
if(!comment.isEmpty())
{
output += "/*!\n";
output += ProtocolParser::outputLongComment(" *", comment) + "\n";
output += " */\n";
}
QStringList declarationList;
int maxLength = 0;
for(int i = 0; i < list.size(); i++)
{
QDomElement field = list.at(i).toElement();
if(field.isNull())
continue;
QString valueName = field.attribute("name");
if(valueName.isEmpty())
continue;
// Add it to our list
nameList.append(valueName);
// The declared value, which may be empty
QString value = field.attribute("value");
valueList.append(value);
// And don't forget the comment
commentList.append(ProtocolParser::getComment(field));
// Form the declaration string
QString declaration = " " + valueName;
if(!value.isEmpty())
declaration += " = " + value;
declarationList.append(declaration);
// Track the longest declaration
int length = declaration.length();
if(length > maxLength)
maxLength = length;
}// for all enum entries
// Figure out the number list we will use for markdown
computeNumberList();
// Account for 1 character we will add below
maxLength += 1;
// We want maxLength to be a multiple of 4
maxLength += 4 - (maxLength % 4);
// Declare the enumeration
output += "typedef enum\n";
output += "{\n";
for(int i = 0; i < declarationList.size(); i++)
{
// Output the enumerator name and separator
output += declarationList.at(i);
// Output a comma separator or space for the last item
if(i < (declarationList.size() - 1))
output += ",";
else
output += " ";
// Pad to maxLength
for(int j = declarationList.at(i).length(); j < maxLength; j++)
output += " ";
// Output the comment
output += "//!< " + commentList.at(i) + "\n";
}// for all enumerators
output += "}";
output += name;
output += ";\n";
return output;
}// EnumCreator::parse
/*!
* Go through the list of enum strings and attempt to determine the list of
* actual numbers that will be output in markdown. This is also how we
* determine the number of bits needed to encode. This is called by parse()
*/
void EnumCreator::computeNumberList(void)
{
// Attempt to get a list of numbers that represents the value of each enumeration
int maxValue = 1;
int value = -1;
QString baseString;
for(int i = 0; i < valueList.length(); i++)
{
// The string from the XML, which may be empty
QString stringValue = valueList.at(i);
// Clear any whitespace from it just to be sure
stringValue = stringValue.trimmed();
if(stringValue.isEmpty())
{
// Increment enumeration value by one
value++;
// Is this incremented value aboslute, or referenced to
// some other string we could not resolve?
if(baseString.isEmpty())
stringValue.setNum(value);
else
stringValue = baseString + " + " + QString().setNum(value);
}// if the xml was empty
else
{
bool ok;
if(stringValue.startsWith("0x"))
value = stringValue.toUInt(&ok, 16);
else if(stringValue.startsWith("0b"))
value = stringValue.toUInt(&ok, 2);
else
value = stringValue.toUInt(&ok, 10);
// If we didn't get a number, then this string has to be resolved
// by the compiler, all we can do is track offsets from it
if(!ok)
{
baseString = stringValue;
value = 0;
}
else
{
baseString.clear();
stringValue.setNum(value);
}
}// if we got a string from the xml
// keep track of maximum value
if(value > maxValue)
maxValue = value;
// Append to the number list
numberList.append(stringValue);
}// for the whole list of value strings
// Its possible we have no idea, so go with 8 bits in that case
if(maxValue > 0)
{
// Figure out the number of bits needed to encode the maximum value
minbitwidth = (int)ceil(log2(maxValue + 1));
}
else
minbitwidth = 8;
}// EnumCreator::computeNumberList
/*!
* Get the markdown output that documents this enumeration
* \param indent is the indent level for the markdown output
* \return the markdown output string
*
QString EnumCreator::getMarkdown(QString indent) const
{
QString output;
// Add one more space for visibility
output += indent + "* `" + name + "`";
if(!comment.isEmpty())
output += " : " + comment + ".";
output += "\n";
output += "\n";
indent += " ";
for(int i = 0; i < nameList.length(); i++)
{
output += indent;
// bulleted list with name and value in code
output += "* `" + nameList.at(i) + " = " + numberList.at(i) + "`";
if(!commentList.at(i).isEmpty())
output += " : " + commentList.at(i) + ".";
output += "\n";
output += "\n";
}
return output;
}// EnumCreator::getMarkdown*/
/*!
* Get the markdown output that documents this enumeration
* \param outline gives the outline number for this heading
* \param packetids is the list of packet identifiers, used to determine if a link should be added
* \return the markdown output string
*/
QString EnumCreator::getMarkdown(QString outline, const QStringList& packetids) const
{
QString output;
if(nameList.length() > 0)
{
QStringList codeNameList;
//If a longer description exists for this enum, display it in the documentation
if (!description.isEmpty()) {
output += "**Description:**\n";
output += description;
output += "\n";
}
// figure out the column spacing in the tables
int firstColumnSpacing = QString("Name").length();
int secondColumnSpacing = QString("Value").length();
int thirdColumnSpacing = QString("Description").length();
for(int i = 0; i < nameList.length(); i++)
{
bool link = false;
// Check to see if this enumeration is a packet identifier
for(int j = 0; j < packetids.size(); j++)
{
if(packetids.at(j) == nameList.at(i))
{
link = true;
break;
}
}
// Make name as code, with or without a link to an anchor elsewhere
if(link)
codeNameList.append("[`" + nameList.at(i) + "`](#" + nameList.at(i) + ")");
else
codeNameList.append("`" + nameList.at(i) + "`");
if(firstColumnSpacing < codeNameList.at(i).length())
firstColumnSpacing = codeNameList.at(i).length();
if(secondColumnSpacing < numberList.at(i).length())
secondColumnSpacing = numberList.at(i).length();
if(thirdColumnSpacing < commentList.at(i).length())
thirdColumnSpacing = commentList.at(i).length();
}
// The outline paragraph
if(!outline.isEmpty())
output += "## " + outline + ") " + name + "\n\n";
// Table caption, with an anchor for the enumeration name
if(comment.isEmpty())
output += "[<a name=\""+name+"\"></a>" + name + "]\n";
else
output += "[<a name=\""+name+"\"></a>" + name + ": " + comment + "]\n";
// Table header
output += "| ";
output += spacedString("Name", firstColumnSpacing);
output += " | ";
output += spacedString("Value", secondColumnSpacing);
output += " | ";
output += spacedString("Description", thirdColumnSpacing);
output += " |\n";
// Underscore the header
output += "| ";
for(int i = 0; i < firstColumnSpacing; i++)
output += "-";
output += " | :";
for(int i = 1; i < secondColumnSpacing-1; i++)
output += "-";
output += ": | ";
for(int i = 0; i < thirdColumnSpacing; i++)
output += "-";
output += " |\n";
// Now write out the outputs
for(int i = 0; i < codeNameList.length(); i++)
{
output += "| ";
output += spacedString(codeNameList.at(i), firstColumnSpacing);
output += " | ";
output += spacedString(numberList.at(i), secondColumnSpacing);
output += " | ";
output += spacedString(commentList.at(i), thirdColumnSpacing);
output += " |\n";
}
output += "\n";
}
return output;
}// EnumCreator::getMarkdown
/*!
* Replace any text that matches an enumeration name with the value of that enumeration
* \param text is modified to replace names with numbers
* \return a reference to text
*/
QString& EnumCreator::replaceEnumerationNameWithValue(QString& text) const
{
for(int i = 0; i < nameList.length(); i++)
{
// If we don't have a name there is no point
if(nameList.at(i).isEmpty())
continue;
// If we don't have a value there is no point
if(valueList.at(i) == numberList.at(i))
continue;
if(text.contains(nameList.at(i)))
{
text.replace(nameList.at(i), numberList.at(i));
}
}
return text;
}// EnumCreator::replaceEnumerationNameWithValue
/*!
* Determine if text is part of an enumeration. This will compare against all
* elements in this enumeration and return true if any of them match.
* \param text is the enumeration value string to compare.
* \return true if text is a value in this enumeration.
*/
bool EnumCreator::isEnumerationValue(const QString& text) const
{
for(int i = 0; i < nameList.length(); i++)
{
// If we don't have a name there is no point
if(nameList.at(i).isEmpty())
continue;
if(text.compare(nameList.at(i)) == 0)
return true;
}
return false;
}// EnumCreator::isEnumerationValue
/*!
* Output a spaced string
* \param text is the first part of the string
* \param spacing is the total length of the string. The output is padded with
* spaces to reach this length.
* \return The spaced string.
*/
QString spacedString(QString text, int spacing)
{
QString output = text;
while(output.length() < spacing)
output += " ";
return output;
}
<commit_msg>Fixed placement of enum description field in documentation<commit_after>#include "enumcreator.h"
#include "protocolparser.h"
#include <QStringList>
#include <math.h>
EnumCreator::EnumCreator(const QDomElement& e):
minbitwidth(0)
{
parse(e);
}
void EnumCreator::clear(void)
{
minbitwidth = 0;
name.clear();
comment.clear();
output.clear();
nameList.clear();
commentList.clear();
valueList.clear();
numberList.clear();
}
/*!
* Parse an Enum tag from the xml to create an enumeration.
* \param e is the Enum tag DOM element
* \return A string (including linefeeds) to declare the enumeration
*/
QString EnumCreator::parse(const QDomElement& e)
{
clear();
name = e.attribute("name");
comment = e.attribute("comment");
description = e.attribute("description");
//If the enum struct has the attribute 'hidden="true"', it won't be displayed in the documentation
hidden = ProtocolParser::isFieldSet(e,"hidden");
QDomNodeList list = e.elementsByTagName("Value");
// If we have no entries there is nothing to do
if(list.size() <= 0)
return output;
// Put the top level comment in
if(!comment.isEmpty())
{
output += "/*!\n";
output += ProtocolParser::outputLongComment(" *", comment) + "\n";
output += " */\n";
}
QStringList declarationList;
int maxLength = 0;
for(int i = 0; i < list.size(); i++)
{
QDomElement field = list.at(i).toElement();
if(field.isNull())
continue;
QString valueName = field.attribute("name");
if(valueName.isEmpty())
continue;
// Add it to our list
nameList.append(valueName);
// The declared value, which may be empty
QString value = field.attribute("value");
valueList.append(value);
// And don't forget the comment
commentList.append(ProtocolParser::getComment(field));
// Form the declaration string
QString declaration = " " + valueName;
if(!value.isEmpty())
declaration += " = " + value;
declarationList.append(declaration);
// Track the longest declaration
int length = declaration.length();
if(length > maxLength)
maxLength = length;
}// for all enum entries
// Figure out the number list we will use for markdown
computeNumberList();
// Account for 1 character we will add below
maxLength += 1;
// We want maxLength to be a multiple of 4
maxLength += 4 - (maxLength % 4);
// Declare the enumeration
output += "typedef enum\n";
output += "{\n";
for(int i = 0; i < declarationList.size(); i++)
{
// Output the enumerator name and separator
output += declarationList.at(i);
// Output a comma separator or space for the last item
if(i < (declarationList.size() - 1))
output += ",";
else
output += " ";
// Pad to maxLength
for(int j = declarationList.at(i).length(); j < maxLength; j++)
output += " ";
// Output the comment
output += "//!< " + commentList.at(i) + "\n";
}// for all enumerators
output += "}";
output += name;
output += ";\n";
return output;
}// EnumCreator::parse
/*!
* Go through the list of enum strings and attempt to determine the list of
* actual numbers that will be output in markdown. This is also how we
* determine the number of bits needed to encode. This is called by parse()
*/
void EnumCreator::computeNumberList(void)
{
// Attempt to get a list of numbers that represents the value of each enumeration
int maxValue = 1;
int value = -1;
QString baseString;
for(int i = 0; i < valueList.length(); i++)
{
// The string from the XML, which may be empty
QString stringValue = valueList.at(i);
// Clear any whitespace from it just to be sure
stringValue = stringValue.trimmed();
if(stringValue.isEmpty())
{
// Increment enumeration value by one
value++;
// Is this incremented value aboslute, or referenced to
// some other string we could not resolve?
if(baseString.isEmpty())
stringValue.setNum(value);
else
stringValue = baseString + " + " + QString().setNum(value);
}// if the xml was empty
else
{
bool ok;
if(stringValue.startsWith("0x"))
value = stringValue.toUInt(&ok, 16);
else if(stringValue.startsWith("0b"))
value = stringValue.toUInt(&ok, 2);
else
value = stringValue.toUInt(&ok, 10);
// If we didn't get a number, then this string has to be resolved
// by the compiler, all we can do is track offsets from it
if(!ok)
{
baseString = stringValue;
value = 0;
}
else
{
baseString.clear();
stringValue.setNum(value);
}
}// if we got a string from the xml
// keep track of maximum value
if(value > maxValue)
maxValue = value;
// Append to the number list
numberList.append(stringValue);
}// for the whole list of value strings
// Its possible we have no idea, so go with 8 bits in that case
if(maxValue > 0)
{
// Figure out the number of bits needed to encode the maximum value
minbitwidth = (int)ceil(log2(maxValue + 1));
}
else
minbitwidth = 8;
}// EnumCreator::computeNumberList
/*!
* Get the markdown output that documents this enumeration
* \param indent is the indent level for the markdown output
* \return the markdown output string
*
QString EnumCreator::getMarkdown(QString indent) const
{
QString output;
// Add one more space for visibility
output += indent + "* `" + name + "`";
if(!comment.isEmpty())
output += " : " + comment + ".";
output += "\n";
output += "\n";
indent += " ";
for(int i = 0; i < nameList.length(); i++)
{
output += indent;
// bulleted list with name and value in code
output += "* `" + nameList.at(i) + " = " + numberList.at(i) + "`";
if(!commentList.at(i).isEmpty())
output += " : " + commentList.at(i) + ".";
output += "\n";
output += "\n";
}
return output;
}// EnumCreator::getMarkdown*/
/*!
* Get the markdown output that documents this enumeration
* \param outline gives the outline number for this heading
* \param packetids is the list of packet identifiers, used to determine if a link should be added
* \return the markdown output string
*/
QString EnumCreator::getMarkdown(QString outline, const QStringList& packetids) const
{
QString output;
if(nameList.length() > 0)
{
QStringList codeNameList;
// figure out the column spacing in the tables
int firstColumnSpacing = QString("Name").length();
int secondColumnSpacing = QString("Value").length();
int thirdColumnSpacing = QString("Description").length();
for(int i = 0; i < nameList.length(); i++)
{
bool link = false;
// Check to see if this enumeration is a packet identifier
for(int j = 0; j < packetids.size(); j++)
{
if(packetids.at(j) == nameList.at(i))
{
link = true;
break;
}
}
// Make name as code, with or without a link to an anchor elsewhere
if(link)
codeNameList.append("[`" + nameList.at(i) + "`](#" + nameList.at(i) + ")");
else
codeNameList.append("`" + nameList.at(i) + "`");
if(firstColumnSpacing < codeNameList.at(i).length())
firstColumnSpacing = codeNameList.at(i).length();
if(secondColumnSpacing < numberList.at(i).length())
secondColumnSpacing = numberList.at(i).length();
if(thirdColumnSpacing < commentList.at(i).length())
thirdColumnSpacing = commentList.at(i).length();
}
// The outline paragraph
if(!outline.isEmpty())
output += "## " + outline + ") " + name + "\n\n";
//If a longer description exists for this enum, display it in the documentation
if (!description.isEmpty()) {
output += "**Description:**\n";
output += description;
output += "\n";
}
// Table caption, with an anchor for the enumeration name
if(comment.isEmpty())
output += "[<a name=\""+name+"\"></a>" + name + "]\n";
else
output += "[<a name=\""+name+"\"></a>" + name + ": " + comment + "]\n";
// Table header
output += "| ";
output += spacedString("Name", firstColumnSpacing);
output += " | ";
output += spacedString("Value", secondColumnSpacing);
output += " | ";
output += spacedString("Description", thirdColumnSpacing);
output += " |\n";
// Underscore the header
output += "| ";
for(int i = 0; i < firstColumnSpacing; i++)
output += "-";
output += " | :";
for(int i = 1; i < secondColumnSpacing-1; i++)
output += "-";
output += ": | ";
for(int i = 0; i < thirdColumnSpacing; i++)
output += "-";
output += " |\n";
// Now write out the outputs
for(int i = 0; i < codeNameList.length(); i++)
{
output += "| ";
output += spacedString(codeNameList.at(i), firstColumnSpacing);
output += " | ";
output += spacedString(numberList.at(i), secondColumnSpacing);
output += " | ";
output += spacedString(commentList.at(i), thirdColumnSpacing);
output += " |\n";
}
output += "\n";
}
return output;
}// EnumCreator::getMarkdown
/*!
* Replace any text that matches an enumeration name with the value of that enumeration
* \param text is modified to replace names with numbers
* \return a reference to text
*/
QString& EnumCreator::replaceEnumerationNameWithValue(QString& text) const
{
for(int i = 0; i < nameList.length(); i++)
{
// If we don't have a name there is no point
if(nameList.at(i).isEmpty())
continue;
// If we don't have a value there is no point
if(valueList.at(i) == numberList.at(i))
continue;
if(text.contains(nameList.at(i)))
{
text.replace(nameList.at(i), numberList.at(i));
}
}
return text;
}// EnumCreator::replaceEnumerationNameWithValue
/*!
* Determine if text is part of an enumeration. This will compare against all
* elements in this enumeration and return true if any of them match.
* \param text is the enumeration value string to compare.
* \return true if text is a value in this enumeration.
*/
bool EnumCreator::isEnumerationValue(const QString& text) const
{
for(int i = 0; i < nameList.length(); i++)
{
// If we don't have a name there is no point
if(nameList.at(i).isEmpty())
continue;
if(text.compare(nameList.at(i)) == 0)
return true;
}
return false;
}// EnumCreator::isEnumerationValue
/*!
* Output a spaced string
* \param text is the first part of the string
* \param spacing is the total length of the string. The output is padded with
* spaces to reach this length.
* \return The spaced string.
*/
QString spacedString(QString text, int spacing)
{
QString output = text;
while(output.length() < spacing)
output += " ";
return output;
}
<|endoftext|>
|
<commit_before>#include "insect.hpp"
#include "graph/graph.hpp"
#include <iostream>
void Insect::draw(sf::RenderTarget& target, Graph *g, sf::Sprite sprite) {
Branch *b = g->getBranch(path.getBranchID(currentBranch));
float cpos = pos;
float sign = 1.0f;
if (b->getSecondNode() == path.getNodeID(currentBranch)) {
cpos = 1-pos;
sign = -1.0f;
}
sf::Vector2f posVect = b->getSpline().evaluatePos(cpos);
sf::Vector2f speedVect = b->getSpline().evaluateSpeed(cpos) * sign;
angle = atan2(speedVect.y, speedVect.x);
sprite.setRotation(angle * 180.0f / 3.14159265f + 90.0f);
sprite.setPosition(posVect);
hitbox.setPosition(posVect);
target.draw(hitbox);
target.draw(sprite);
}
void Insect::move(float dt, Graph* g) {
float len = g->getBranch(path.getBranchID(currentBranch))->getLength();
pos += speed * dt / len;
if (pos > 1.0f) {
pos = 0.0f;
currentBranch += 1;
if (currentBranch == path.size())
{
currentBranch = 0;
reachedObjective = true;
}
}
}
Insect::type Insect::getType() {
return mType;
}
Insect::Insect(type mType, float fhitbox
,int currentBranch
, float pos, float speed, float angle, Node::ID obj, bool bo) : mType(mType)
, hitbox(fhitbox)
, currentBranch(currentBranch)
, pos(pos)
, speed(speed)
, angle(angle)
, objective(obj)
, reachedObjective(bo)
{
hitbox.setOrigin(fhitbox, fhitbox);
}
Aphid::Aphid(AphidBehaviour::ID b, Node spawn, Graph *g) : Insect(Insect::Aphid, 10, 0, 0.0f, 50.0f, 0.0f, spawn, false)
, behaviour(b, spawn, *g)
{
path = behaviour.getPath();
objective = behaviour.getObjective();
}
LadyBug::LadyBug(Insect::type type, Node spawn, Graph *g) : Insect(type, 12, 0, 0.0f, 50.f*1.5f, 0.0f, spawn, true)
{
path = AphidBehaviour(AphidBehaviour::Offensive, Node::ID(spawn), *g).getPath();
}
void LadyBug::RedefinePath(Path newPath, Graph &g) {
futurePath = newPath;
if (!futurePath.isCyclic(g))
futurePath.makeCyclic(g);
Node::ID nextNode = path.getNodeID(currentBranch);
if (currentBranch + 1 == path.size())
nextNode = path.getLastNodeID(g);
else
nextNode = path.getNodeID(currentBranch + 1);
float shortestDist = 1e16; //not pretty :s
std::set<Node::ID> nodes = newPath.getNodes(g);
for (auto &id : nodes) {
if (g.getDist(id, nextNode) < shortestDist) {
shortestDist = g.getDist(id, nextNode);
objective = id;
}
}
Node::ID prevNode = path.getNodeID(currentBranch);
Branch::ID currBranch = path.getBranchID(currentBranch);
path = g.getPath(nextNode, objective);
path.insertBranch(prevNode, currBranch);
reachedObjective = false;
}
void LadyBug::move(float dt, Graph* g) {
float len = g->getBranch(path.getBranchID(currentBranch))->getLength();
pos += speed * dt / len;
//im like not sure at all the objective stuff is safe
//get ready for segfaults <3
if (pos > 1.0f) {
pos = 0.0f;
currentBranch += 1;
if (currentBranch == path.size()) {
currentBranch = 0;
if (!reachedObjective) {
reachedObjective = true;
path = futurePath;
}
}
}
}
float Insect::getPos(Graph* g)
{
Branch *b = g->getBranch(path.getBranchID(currentBranch));
float cpos = 1-pos;
if (b->getSecondNode() == path.getNodeID(currentBranch))
{
cpos = pos;
}
return cpos;
}
<commit_msg>ladyBug spawn avec un path safe<commit_after>#include "insect.hpp"
#include "graph/graph.hpp"
#include <iostream>
void Insect::draw(sf::RenderTarget& target, Graph *g, sf::Sprite sprite) {
Branch *b = g->getBranch(path.getBranchID(currentBranch));
float cpos = pos;
float sign = 1.0f;
if (b->getSecondNode() == path.getNodeID(currentBranch)) {
cpos = 1-pos;
sign = -1.0f;
}
sf::Vector2f posVect = b->getSpline().evaluatePos(cpos);
sf::Vector2f speedVect = b->getSpline().evaluateSpeed(cpos) * sign;
angle = atan2(speedVect.y, speedVect.x);
sprite.setRotation(angle * 180.0f / 3.14159265f + 90.0f);
sprite.setPosition(posVect);
hitbox.setPosition(posVect);
target.draw(hitbox);
target.draw(sprite);
}
void Insect::move(float dt, Graph* g) {
float len = g->getBranch(path.getBranchID(currentBranch))->getLength();
pos += speed * dt / len;
if (pos > 1.0f) {
pos = 0.0f;
currentBranch += 1;
if (currentBranch == path.size())
{
currentBranch = 0;
reachedObjective = true;
}
}
}
Insect::type Insect::getType() {
return mType;
}
Insect::Insect(type mType, float fhitbox
,int currentBranch
, float pos, float speed, float angle, Node::ID obj, bool bo) : mType(mType)
, hitbox(fhitbox)
, currentBranch(currentBranch)
, pos(pos)
, speed(speed)
, angle(angle)
, objective(obj)
, reachedObjective(bo)
{
hitbox.setOrigin(fhitbox, fhitbox);
}
Aphid::Aphid(AphidBehaviour::ID b, Node spawn, Graph *g) : Insect(Insect::Aphid, 10, 0, 0.0f, 50.0f, 0.0f, spawn, false)
, behaviour(b, spawn, *g)
{
path = behaviour.getPath();
objective = behaviour.getObjective();
}
LadyBug::LadyBug(Insect::type type, Node spawn, Graph *g) : Insect(type, 12, 0, 0.0f, 50.f*1.5f, 0.0f, spawn, true)
{
Branch::ID spawnBranch = g->getNeighbours(spawn).begin()->second;
path.addBranch(spawn, spawnBranch);
path.addBranch((*g)[spawnBranch].getFirstNode(), spawnBranch);
}
void LadyBug::RedefinePath(Path newPath, Graph &g) {
futurePath = newPath;
if (!futurePath.isCyclic(g))
futurePath.makeCyclic(g);
Node::ID nextNode = path.getNodeID(currentBranch);
if (currentBranch + 1 == path.size())
nextNode = path.getLastNodeID(g);
else
nextNode = path.getNodeID(currentBranch + 1);
float shortestDist = 1e16; //not pretty :s
std::set<Node::ID> nodes = newPath.getNodes(g);
for (auto &id : nodes) {
if (g.getDist(id, nextNode) < shortestDist) {
shortestDist = g.getDist(id, nextNode);
objective = id;
}
}
Node::ID prevNode = path.getNodeID(currentBranch);
Branch::ID currBranch = path.getBranchID(currentBranch);
path = g.getPath(nextNode, objective);
path.insertBranch(prevNode, currBranch);
reachedObjective = false;
}
void LadyBug::move(float dt, Graph* g) {
float len = g->getBranch(path.getBranchID(currentBranch))->getLength();
pos += speed * dt / len;
//im like not sure at all the objective stuff is safe
//get ready for segfaults <3
if (pos > 1.0f) {
pos = 0.0f;
currentBranch += 1;
if (currentBranch == path.size()) {
currentBranch = 0;
if (!reachedObjective) {
reachedObjective = true;
path = futurePath;
}
}
}
}
float Insect::getPos(Graph* g)
{
Branch *b = g->getBranch(path.getBranchID(currentBranch));
float cpos = 1-pos;
if (b->getSecondNode() == path.getNodeID(currentBranch))
{
cpos = pos;
}
return cpos;
}
<|endoftext|>
|
<commit_before>#include <string.h>
#include <iostream>
#include <sstream>
#include <map>
#include <unistd.h>
#include <openssl/sha.h>
#include <openssl/hmac.h>
#include "base64.h"
#include <jansson.h>
#include "kraken.h"
#include "curl_fun.h"
// INFO workaround for std::to_string when not using c++11
namespace patch {
template < typename T > std::string to_string(const T& n) {
std::ostringstream stm;
stm << n;
return stm.str();
}
}
namespace Kraken {
static std::map<int, std::string> *id_to_transaction = new std::map<int, std::string>();
double getQuote(Parameters& params, bool isBid) {
bool GETRequest = false;
json_t* root = getJsonFromUrl(params, "https://api.kraken.com/0/public/Ticker", "pair=XXBTZUSD", GETRequest);
const char* quote;
double quoteValue;
if (isBid) {
quote = json_string_value(json_array_get(json_object_get(json_object_get(json_object_get(root, "result"), "XXBTZUSD"), "b"), 0));
} else {
quote = json_string_value(json_array_get(json_object_get(json_object_get(json_object_get(root, "result"), "XXBTZUSD"), "a"), 0));
}
if (quote != NULL) {
quoteValue = atof(quote);
} else {
quoteValue = 0.0;
}
json_decref(root);
return quoteValue;
}
double getAvail(Parameters& params, std::string currency) {
json_t* root = authRequest(params, "https://api.kraken.com", "/0/private/Balance");
json_t* result = json_object_get(root, "result");
if (json_object_size(result) == 0) {
return 0.0;
}
double available = 0.0;
if (currency.compare("usd") == 0) {
const char * avail_str = json_string_value(json_object_get(result, "ZUSD"));
available = avail_str ? atof(avail_str) : 0.0;
} else if (currency.compare("btc") == 0) {
const char * avail_str = json_string_value(json_object_get(result, "XXBT"));
available = avail_str ? atof(avail_str) : 0.0;
} else {
*params.logFile << "Currency not supported" << std::endl;
}
return available;
}
int sendLongOrder(Parameters& params, std::string direction, double quantity, double price) {
if (direction.compare("buy") != 0 && direction.compare("sell") != 0) {
*params.logFile << "Error: Neither \"buy\" nor \"sell\" selected" << std::endl;
return 0;
}
*params.logFile << "<Kraken> Trying to send a \"" << direction << "\" limit order: " << quantity << " @ $" << price << "..." << std::endl;
std::string pair = "XXBTZUSD";
std::string type = direction;
std::string ordertype = "limit";
std::string pricelimit = patch::to_string(price);
std::string volume = patch::to_string(quantity);
std::string options = "pair=" + pair + "&type=" + type + "&ordertype=" + ordertype + "&price=" + pricelimit + "&volume=" + volume;
json_t* res = authRequest(params, "https://api.kraken.com", "/0/private/AddOrder", options);
json_t* root = json_object_get(res, "result");
if (json_is_object(root) == 0) {
*params.logFile << json_dumps(res, 0) << std::endl;
exit(0);
}
std::string txid = json_string_value(json_array_get(json_object_get(root, "txid"), 0));
int max_id = id_to_transaction->size();
(*id_to_transaction)[max_id] = txid;
*params.logFile << "<Kraken> Done (transaction ID: " << txid << ")\n" << std::endl;
json_decref(root);
return max_id;
}
bool isOrderComplete(Parameters& params, int orderId) {
json_t* root = authRequest(params, "https://api.kraken.com", "/0/private/OpenOrders");
// no open order: return true
root = json_object_get(json_object_get(root, "result"), "open");
if (json_object_size(root) == 0) {
*params.logFile << "No order exists" << std::endl;
return true;
}
*params.logFile << json_dumps(root, 0) << std::endl;
std::string transaction_id = (*id_to_transaction)[orderId];
root = json_object_get(root, transaction_id.c_str());
// open orders exist but specific order not found: return true
if (json_object_size(root) == 0) {
*params.logFile << "Order " << transaction_id << " does not exist" << std::endl;
return true;
// open orders exist and specific order was found: return false
} else {
*params.logFile << "Order " << transaction_id << " still exists!" << std::endl;
return false;
}
}
double getActivePos(Parameters& params) {
return getAvail(params, "btc");
}
double getLimitPrice(Parameters& params, double volume, bool isBid) {
bool GETRequest = false;
json_t* root = json_object_get(json_object_get(getJsonFromUrl(params, "https://api.kraken.com/0/public/Depth", "pair=XXBTZUSD", GETRequest), "result"), "XXBTZUSD");
if (isBid) {
root = json_object_get(root, "bids");
} else {
root = json_object_get(root, "asks");
}
// loop on volume
double tmpVol = 0.0;
int i = 0;
// [[<price>, <volume>, <timestamp>], [<price>, <volume>, <timestamp>], ...]
while (tmpVol < volume) {
// volumes are added up until the requested volume is reached
tmpVol += atof(json_string_value(json_array_get(json_array_get(root, i), 1)));
i++;
}
double limPrice = 0.0;
limPrice = atof(json_string_value(json_array_get(json_array_get(root, i-1), 0)));
json_decref(root);
return limPrice;
}
json_t* authRequest(Parameters& params, std::string url, std::string request, std::string options) {
// create nonce and POST data
struct timeval tv;
gettimeofday(&tv, NULL);
unsigned long long nonce = (tv.tv_sec * 1000.0) + (tv.tv_usec * 0.001) + 0.5;
std::string post_data = "";
if (options.empty()) {
post_data = "nonce=" + patch::to_string(nonce);
} else {
post_data = "nonce=" + patch::to_string(nonce) + "&" + options;
}
// Message signature using HMAC-SHA512 of (URI path + SHA256(nonce + POST data))
// and base64 decoded secret API key
std::string payload_for_signature = patch::to_string(nonce) + post_data;
unsigned char digest[SHA256_DIGEST_LENGTH];
SHA256((unsigned char*)payload_for_signature.c_str(), strlen(payload_for_signature.c_str()), (unsigned char*)&digest);
int signature_data_length = request.length() + SHA256_DIGEST_LENGTH;
unsigned char signature_data[signature_data_length];
std::copy(request.begin(), request.end(), &signature_data[0]);
memcpy(&signature_data[request.length()], &digest, SHA256_DIGEST_LENGTH);
std::string decoded_key = base64_decode(params.krakenSecret);
unsigned char* hmac_digest;
hmac_digest = HMAC(EVP_sha512(), decoded_key.c_str(), decoded_key.length(), (unsigned char*)&signature_data, signature_data_length, NULL, NULL);
std::string api_sign_header = base64_encode(reinterpret_cast<const unsigned char*>(hmac_digest), SHA512_DIGEST_LENGTH);
// cURL header
struct curl_slist* headers = NULL;
std::string api = "API-KEY:" + std::string(params.krakenApi);
std::string api_sig = "API-Sign:" + api_sign_header;
headers = curl_slist_append(headers, api.c_str());
headers = curl_slist_append(headers, api_sig.c_str());
// cURL request
CURLcode resCurl;
if (params.curl) {
std::string readBuffer;
curl_easy_setopt(params.curl, CURLOPT_POST, 1L);
curl_easy_setopt(params.curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(params.curl, CURLOPT_POSTFIELDS, post_data.c_str());
curl_easy_setopt(params.curl, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(params.curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(params.curl, CURLOPT_WRITEDATA, &readBuffer);
curl_easy_setopt(params.curl, CURLOPT_URL, (url+request).c_str());
curl_easy_setopt(params.curl, CURLOPT_CONNECTTIMEOUT, 10L);
resCurl = curl_easy_perform(params.curl);
json_t* root;
json_error_t error;
while (resCurl != CURLE_OK) {
*params.logFile << "<Kraken> Error with cURL. Retry in 2 sec...\n" << std::endl;
sleep(2.0);
readBuffer = "";
resCurl = curl_easy_perform(params.curl);
}
root = json_loads(readBuffer.c_str(), 0, &error);
while (!root) {
*params.logFile << "<Kraken> Error with JSON:\n" << error.text << std::endl;
*params.logFile << "<Kraken> Buffer:\n" << readBuffer.c_str() << std::endl;
*params.logFile << "<Kraken> Retrying..." << std::endl;
sleep(2.0);
readBuffer = "";
resCurl = curl_easy_perform(params.curl);
while (resCurl != CURLE_OK) {
*params.logFile << "<Kraken> Error with cURL. Retry in 2 sec...\n" << std::endl;
sleep(2.0);
readBuffer = "";
resCurl = curl_easy_perform(params.curl);
}
root = json_loads(readBuffer.c_str(), 0, &error);
}
curl_slist_free_all(headers);
curl_easy_reset(params.curl);
return root;
} else {
*params.logFile << "<Kraken> Error with cURL init." << std::endl;
return NULL;
}
return NULL;
}
}
<commit_msg>Changed kraken.cpp to make less API calls. Should stop hitting API limit and lower bandwidth usage.<commit_after>#include <string.h>
#include <iostream>
#include <sstream>
#include <map>
#include <unistd.h>
#include <openssl/sha.h>
#include <openssl/hmac.h>
#include "base64.h"
#include <jansson.h>
#include "kraken.h"
#include "curl_fun.h"
// INFO workaround for std::to_string when not using c++11
namespace patch {
template < typename T > std::string to_string(const T& n) {
std::ostringstream stm;
stm << n;
return stm.str();
}
}
namespace Kraken {
json_t* krakenTicker;
bool krakenGotTicker = false;
json_t* krakenLimPrices;
bool krakenGotLimPrice = false;
static std::map<int, std::string> *id_to_transaction = new std::map<int, std::string>();
double getQuote(Parameters& params, bool isBid) {
bool GETRequest = false;
json_t* root;
if (krakenGotTicker) {
root = krakenTicker;
krakenGotTicker = false;
} else {
root = getJsonFromUrl(params, "https://api.kraken.com/0/public/Ticker", "pair=XXBTZUSD", GETRequest);
krakenGotTicker = true;
}
const char* quote;
double quoteValue;
if (isBid) {
quote = json_string_value(json_array_get(json_object_get(json_object_get(json_object_get(root, "result"), "XXBTZUSD"), "b"), 0));
} else {
quote = json_string_value(json_array_get(json_object_get(json_object_get(json_object_get(root, "result"), "XXBTZUSD"), "a"), 0));
}
if (quote != NULL) {
quoteValue = atof(quote);
} else {
quoteValue = 0.0;
}
json_decref(root);
return quoteValue;
}
double getAvail(Parameters& params, std::string currency) {
json_t* root = authRequest(params, "https://api.kraken.com", "/0/private/Balance");
json_t* result = json_object_get(root, "result");
if (json_object_size(result) == 0) {
return 0.0;
}
double available = 0.0;
if (currency.compare("usd") == 0) {
const char * avail_str = json_string_value(json_object_get(result, "ZUSD"));
available = avail_str ? atof(avail_str) : 0.0;
} else if (currency.compare("btc") == 0) {
const char * avail_str = json_string_value(json_object_get(result, "XXBT"));
available = avail_str ? atof(avail_str) : 0.0;
} else {
*params.logFile << "Currency not supported" << std::endl;
}
return available;
}
int sendLongOrder(Parameters& params, std::string direction, double quantity, double price) {
if (direction.compare("buy") != 0 && direction.compare("sell") != 0) {
*params.logFile << "Error: Neither \"buy\" nor \"sell\" selected" << std::endl;
return 0;
}
*params.logFile << "<Kraken> Trying to send a \"" << direction << "\" limit order: " << quantity << " @ $" << price << "..." << std::endl;
std::string pair = "XXBTZUSD";
std::string type = direction;
std::string ordertype = "limit";
std::string pricelimit = patch::to_string(price);
std::string volume = patch::to_string(quantity);
std::string options = "pair=" + pair + "&type=" + type + "&ordertype=" + ordertype + "&price=" + pricelimit + "&volume=" + volume;
json_t* res = authRequest(params, "https://api.kraken.com", "/0/private/AddOrder", options);
json_t* root = json_object_get(res, "result");
if (json_is_object(root) == 0) {
*params.logFile << json_dumps(res, 0) << std::endl;
exit(0);
}
std::string txid = json_string_value(json_array_get(json_object_get(root, "txid"), 0));
int max_id = id_to_transaction->size();
(*id_to_transaction)[max_id] = txid;
*params.logFile << "<Kraken> Done (transaction ID: " << txid << ")\n" << std::endl;
json_decref(root);
return max_id;
}
bool isOrderComplete(Parameters& params, int orderId) {
json_t* root = authRequest(params, "https://api.kraken.com", "/0/private/OpenOrders");
// no open order: return true
root = json_object_get(json_object_get(root, "result"), "open");
if (json_object_size(root) == 0) {
*params.logFile << "No order exists" << std::endl;
return true;
}
*params.logFile << json_dumps(root, 0) << std::endl;
std::string transaction_id = (*id_to_transaction)[orderId];
root = json_object_get(root, transaction_id.c_str());
// open orders exist but specific order not found: return true
if (json_object_size(root) == 0) {
*params.logFile << "Order " << transaction_id << " does not exist" << std::endl;
return true;
// open orders exist and specific order was found: return false
} else {
*params.logFile << "Order " << transaction_id << " still exists!" << std::endl;
return false;
}
}
double getActivePos(Parameters& params) {
return getAvail(params, "btc");
}
double getLimitPrice(Parameters& params, double volume, bool isBid) {
bool GETRequest = false;
json_t* root;
if (krakenGotLimPrice) {
root = krakenLimPrices;
krakenGotLimPrice = false;
} else {
root = json_object_get(json_object_get(getJsonFromUrl(params, "https://api.kraken.com/0/public/Depth", "pair=XXBTZUSD", GETRequest), "result"), "XXBTZUSD");
krakenGotLimPrice = true;
}
if (isBid) {
root = json_object_get(root, "bids");
} else {
root = json_object_get(root, "asks");
}
// loop on volume
double tmpVol = 0.0;
int i = 0;
// [[<price>, <volume>, <timestamp>], [<price>, <volume>, <timestamp>], ...]
while (tmpVol < volume) {
// volumes are added up until the requested volume is reached
tmpVol += atof(json_string_value(json_array_get(json_array_get(root, i), 1)));
i++;
}
double limPrice = 0.0;
limPrice = atof(json_string_value(json_array_get(json_array_get(root, i-1), 0)));
json_decref(root);
return limPrice;
}
json_t* authRequest(Parameters& params, std::string url, std::string request, std::string options) {
// create nonce and POST data
struct timeval tv;
gettimeofday(&tv, NULL);
unsigned long long nonce = (tv.tv_sec * 1000.0) + (tv.tv_usec * 0.001) + 0.5;
std::string post_data = "";
if (options.empty()) {
post_data = "nonce=" + patch::to_string(nonce);
} else {
post_data = "nonce=" + patch::to_string(nonce) + "&" + options;
}
// Message signature using HMAC-SHA512 of (URI path + SHA256(nonce + POST data))
// and base64 decoded secret API key
std::string payload_for_signature = patch::to_string(nonce) + post_data;
unsigned char digest[SHA256_DIGEST_LENGTH];
SHA256((unsigned char*)payload_for_signature.c_str(), strlen(payload_for_signature.c_str()), (unsigned char*)&digest);
int signature_data_length = request.length() + SHA256_DIGEST_LENGTH;
unsigned char signature_data[signature_data_length];
std::copy(request.begin(), request.end(), &signature_data[0]);
memcpy(&signature_data[request.length()], &digest, SHA256_DIGEST_LENGTH);
std::string decoded_key = base64_decode(params.krakenSecret);
unsigned char* hmac_digest;
hmac_digest = HMAC(EVP_sha512(), decoded_key.c_str(), decoded_key.length(), (unsigned char*)&signature_data, signature_data_length, NULL, NULL);
std::string api_sign_header = base64_encode(reinterpret_cast<const unsigned char*>(hmac_digest), SHA512_DIGEST_LENGTH);
// cURL header
struct curl_slist* headers = NULL;
std::string api = "API-KEY:" + std::string(params.krakenApi);
std::string api_sig = "API-Sign:" + api_sign_header;
headers = curl_slist_append(headers, api.c_str());
headers = curl_slist_append(headers, api_sig.c_str());
// cURL request
CURLcode resCurl;
if (params.curl) {
std::string readBuffer;
curl_easy_setopt(params.curl, CURLOPT_POST, 1L);
curl_easy_setopt(params.curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(params.curl, CURLOPT_POSTFIELDS, post_data.c_str());
curl_easy_setopt(params.curl, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(params.curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(params.curl, CURLOPT_WRITEDATA, &readBuffer);
curl_easy_setopt(params.curl, CURLOPT_URL, (url+request).c_str());
curl_easy_setopt(params.curl, CURLOPT_CONNECTTIMEOUT, 10L);
resCurl = curl_easy_perform(params.curl);
json_t* root;
json_error_t error;
while (resCurl != CURLE_OK) {
*params.logFile << "<Kraken> Error with cURL. Retry in 2 sec...\n" << std::endl;
sleep(2.0);
readBuffer = "";
resCurl = curl_easy_perform(params.curl);
}
root = json_loads(readBuffer.c_str(), 0, &error);
while (!root) {
*params.logFile << "<Kraken> Error with JSON:\n" << error.text << std::endl;
*params.logFile << "<Kraken> Buffer:\n" << readBuffer.c_str() << std::endl;
*params.logFile << "<Kraken> Retrying..." << std::endl;
sleep(2.0);
readBuffer = "";
resCurl = curl_easy_perform(params.curl);
while (resCurl != CURLE_OK) {
*params.logFile << "<Kraken> Error with cURL. Retry in 2 sec...\n" << std::endl;
sleep(2.0);
readBuffer = "";
resCurl = curl_easy_perform(params.curl);
}
root = json_loads(readBuffer.c_str(), 0, &error);
}
curl_slist_free_all(headers);
curl_easy_reset(params.curl);
return root;
} else {
*params.logFile << "<Kraken> Error with cURL init." << std::endl;
return NULL;
}
return NULL;
}
}
<|endoftext|>
|
<commit_before>#include <type_traits>
namespace Lambda {
using namespace std;
struct Functor {};
template<typename _Type>
struct IsBound {
static bool constexpr s_f = !is_base_of<
Functor,
typename remove_cv<
typename remove_reference<_Type>::type
>::type
>::value;
};
template<typename _Type>
inline _Type &&Pass(_Type &&rr) {
return rr;
}
template<unsigned int _i>
struct Bind :
public Functor
{
template<typename _First, typename... _Other>
inline static auto Apply(_First&&, _Other&&... rrOther) -> decltype(Bind<_i - 1>::Apply(rrOther...)) {
return Bind<_i - 1>::Apply(rrOther...);
}
template<typename... _Arguments>
inline auto operator () (_Arguments&&... rrArguments) -> decltype(Bind<_i>::Apply(rrArguments...)) {
return Bind<_i>::Apply(rrArguments...);
}
};
template<>
struct Bind<0> :
public Functor
{
template<typename _Type, typename... _Other>
inline static _Type &&Apply(_Type &&rr, _Other&&...) {
return rr;
}
template<typename _Type, typename... _Other>
inline _Type &&operator () (_Type &&rr, _Other&&...) {
return rr;
}
};
#define LAMBDA_PREFIX_UNARY_FUNCTOR_CLASS(Operator, Name) \
template<typename _Operand, bool _fBound = IsBound<_Operand>::s_f> \
struct Name; \
template<typename _Operand> \
struct Name<_Operand, false> : \
public Functor \
{ \
_Operand m_Operand; \
Name(_Operand &&a_rrOperand) \
: \
m_Operand(Pass(a_rrOperand)) {} \
template<typename... _Arguments> \
inline auto operator () (_Arguments&&... Arguments) -> decltype(Operator(m_Operand(Arguments...))) { \
return Operator(m_Operand(Arguments...)); \
} \
}; \
template<typename _Operand> \
struct Name<_Operand, true> : \
public Functor \
{ \
_Operand m_Operand; \
Name(_Operand &&a_rrOperand) \
: \
m_Operand(Pass(a_rrOperand)) {} \
template<typename... _Arguments> \
inline auto operator () (_Arguments&&...) -> decltype(Operator m_Operand) { \
return Operator m_Operand; \
} \
};
#define LAMBDA_POSTFIX_UNARY_FUNCTOR_CLASS(Operator, Name) \
template<typename _Operand, bool _fBound = IsBound<_Operand>::s_f> \
struct Name; \
template<typename _Operand> \
struct Name<_Operand, false> : \
public Functor \
{ \
_Operand m_Operand; \
Name(_Operand &&a_rrOperand) \
: \
m_Operand(Pass(a_rrOperand)) {} \
template<typename... _Arguments> \
inline auto operator () (_Arguments&&... Arguments) -> decltype((m_Operand(Arguments...)) Operator) { \
return (m_Operand(Arguments...)) Operator; \
} \
}; \
template<typename _Operand> \
struct Name<_Operand, true> : \
public Functor \
{ \
_Operand m_Operand; \
Name(_Operand &&a_rrOperand) \
: \
m_Operand(Pass(a_rrOperand)) {} \
template<typename... _Arguments> \
inline auto operator () (_Arguments&&...) -> decltype(m_Operand Operator) { \
return m_Operand Operator; \
} \
};
LAMBDA_PREFIX_UNARY_FUNCTOR_CLASS(+, UnaryPlus)
LAMBDA_PREFIX_UNARY_FUNCTOR_CLASS(-, UnaryMinus)
LAMBDA_PREFIX_UNARY_FUNCTOR_CLASS(!, LogicalNot)
LAMBDA_PREFIX_UNARY_FUNCTOR_CLASS(~, BitwiseNot)
LAMBDA_PREFIX_UNARY_FUNCTOR_CLASS(++, PreIncrement)
LAMBDA_PREFIX_UNARY_FUNCTOR_CLASS(--, PreDecrement)
LAMBDA_POSTFIX_UNARY_FUNCTOR_CLASS(++, PostIncrement)
LAMBDA_POSTFIX_UNARY_FUNCTOR_CLASS(--, PostDecrement)
#define LAMBDA_BINARY_FUNCTOR_CLASS(Operator, Name) \
template<typename _Left, typename _Right, bool _fLeftBound = IsBound<_Left>::s_f, bool _fRightBound = IsBound<_Right>::s_f> \
struct Name; \
template<typename _Left, typename _Right> \
struct Name<_Left, _Right, false, false> : \
public Functor \
{ \
_Left m_Left; \
_Right m_Right; \
Name(_Left &&a_rrLeft, _Right &&a_rrRight) \
: \
m_Left(Pass(a_rrLeft)), \
m_Right(Pass(a_rrRight)) {} \
template<typename... _Arguments> \
inline auto operator () (_Arguments&&... Arguments) -> decltype(m_Left(Arguments...) Operator m_Right(Arguments...)) { \
return m_Left(Arguments...) Operator m_Right(Arguments...); \
} \
}; \
template<typename _Left, typename _Right> \
struct Name<_Left, _Right, true, false> : \
public Functor \
{ \
_Left m_Left; \
_Right m_Right; \
Name(_Left &&a_rrLeft, _Right &&a_rrRight) \
: \
m_Left(Pass(a_rrLeft)), \
m_Right(Pass(a_rrRight)) {} \
template<typename... _Arguments> \
inline auto operator () (_Arguments&&... Arguments) -> decltype(m_Left Operator m_Right(Arguments...)) { \
return m_Left Operator m_Right(Arguments...); \
} \
}; \
template<typename _Left, typename _Right> \
struct Name<_Left, _Right, false, true> : \
public Functor \
{ \
_Left m_Left; \
_Right m_Right; \
Name(_Left &&a_rrLeft, _Right &&a_rrRight) \
: \
m_Left(Pass(a_rrLeft)), \
m_Right(Pass(a_rrRight)) {} \
template<typename... _Arguments> \
inline auto operator () (_Arguments&&... Arguments) -> decltype(m_Left(Arguments...) Operator m_Right) { \
return m_Left(Arguments...) Operator m_Right; \
} \
}; \
template<typename _Left, typename _Right> \
struct Name<_Left, _Right, true, true> : \
public Functor \
{ \
_Left m_Left; \
_Right m_Right; \
Name(_Left &&a_rrLeft, _Right &&a_rrRight) \
: \
m_Left(Pass(a_rrLeft)), \
m_Right(Pass(a_rrRight)) {} \
template<typename... _Arguments> \
inline auto operator () (_Arguments&&...) -> decltype(m_Left Operator m_Right) { \
return m_Left Operator m_Right; \
} \
};
LAMBDA_BINARY_FUNCTOR_CLASS(+, BinaryPlus)
LAMBDA_BINARY_FUNCTOR_CLASS(+=, CompoundPlus)
LAMBDA_BINARY_FUNCTOR_CLASS(-, BinaryMinus)
LAMBDA_BINARY_FUNCTOR_CLASS(-=, CompoundMinus)
LAMBDA_BINARY_FUNCTOR_CLASS(*, Multiply)
LAMBDA_BINARY_FUNCTOR_CLASS(*=, CompoundMultiply)
LAMBDA_BINARY_FUNCTOR_CLASS(/, Divide)
LAMBDA_BINARY_FUNCTOR_CLASS(/=, CompoundDivide)
LAMBDA_BINARY_FUNCTOR_CLASS(%, Modulus)
LAMBDA_BINARY_FUNCTOR_CLASS(%=, CompoundModulus)
LAMBDA_BINARY_FUNCTOR_CLASS(&, BitwiseAnd)
LAMBDA_BINARY_FUNCTOR_CLASS(|, BitwiseOr)
LAMBDA_BINARY_FUNCTOR_CLASS(^, BitwiseXor)
LAMBDA_BINARY_FUNCTOR_CLASS(&=, CompoundAnd)
LAMBDA_BINARY_FUNCTOR_CLASS(|=, CompoundOr)
LAMBDA_BINARY_FUNCTOR_CLASS(^=, CompoundXor)
LAMBDA_BINARY_FUNCTOR_CLASS(&&, LogicalAnd)
LAMBDA_BINARY_FUNCTOR_CLASS(||, LogicalOr)
LAMBDA_BINARY_FUNCTOR_CLASS(<<, LeftShift)
LAMBDA_BINARY_FUNCTOR_CLASS(<<=, CompoundLeftShift)
LAMBDA_BINARY_FUNCTOR_CLASS(>>, RightShift)
LAMBDA_BINARY_FUNCTOR_CLASS(>>=, CompoundRightShift)
//LAMBDA_BINARY_FUNCTOR_CLASS(=, Assignment)
LAMBDA_BINARY_FUNCTOR_CLASS(==, Equals)
LAMBDA_BINARY_FUNCTOR_CLASS(!=, NotEqual)
LAMBDA_BINARY_FUNCTOR_CLASS(<, LessThan)
LAMBDA_BINARY_FUNCTOR_CLASS(>, GreaterThan)
LAMBDA_BINARY_FUNCTOR_CLASS(<=, LessThanOrEqualTo)
LAMBDA_BINARY_FUNCTOR_CLASS(>=, GreaterThanOrEqualTo)
}
Lambda::Bind<0> _1;
Lambda::Bind<1> _2;
Lambda::Bind<2> _3;
Lambda::Bind<3> _4;
Lambda::Bind<4> _5;
Lambda::Bind<5> _6;
Lambda::Bind<6> _7;
Lambda::Bind<7> _8;
Lambda::Bind<8> _9;
Lambda::Bind<9> _10;
#define LAMBDA_PREFIX_UNARY_OPERATOR(Operator, FunctorClass) \
template<typename _Operand> \
inline Lambda::FunctorClass<_Operand> operator Operator (_Operand &&rrOperand) { \
return Lambda::FunctorClass<_Operand>((_Operand&&)rrOperand); \
}
LAMBDA_PREFIX_UNARY_OPERATOR(+, UnaryPlus)
LAMBDA_PREFIX_UNARY_OPERATOR(-, UnaryMinus)
LAMBDA_PREFIX_UNARY_OPERATOR(!, LogicalNot)
LAMBDA_PREFIX_UNARY_OPERATOR(~, BitwiseNot)
LAMBDA_PREFIX_UNARY_OPERATOR(++, PostIncrement)
LAMBDA_PREFIX_UNARY_OPERATOR(--, PostDecrement)
#define LAMBDA_BINARY_OPERATOR(Operator, FunctorClass) \
template<typename _Left, typename _Right> \
inline Lambda::FunctorClass<_Left, _Right> operator Operator (_Left &&rrLeft, _Right &&rrRight) { \
return Lambda::FunctorClass<_Left, _Right>((_Left&&)rrLeft, (_Right&&)rrRight); \
}
LAMBDA_BINARY_OPERATOR(+, BinaryPlus)
LAMBDA_BINARY_OPERATOR(+=, CompoundPlus)
LAMBDA_BINARY_OPERATOR(-, BinaryMinus)
LAMBDA_BINARY_OPERATOR(-=, CompoundMinus)
LAMBDA_BINARY_OPERATOR(*, Multiply)
LAMBDA_BINARY_OPERATOR(*=, CompoundMultiply)
LAMBDA_BINARY_OPERATOR(/, Divide)
LAMBDA_BINARY_OPERATOR(/=, CompoundDivide)
LAMBDA_BINARY_OPERATOR(%, Modulus)
LAMBDA_BINARY_OPERATOR(%=, CompoundModulus)
LAMBDA_BINARY_OPERATOR(&, BitwiseAnd)
LAMBDA_BINARY_OPERATOR(|, BitwiseOr)
LAMBDA_BINARY_OPERATOR(^, BitwiseXor)
LAMBDA_BINARY_OPERATOR(&=, CompoundAnd)
LAMBDA_BINARY_OPERATOR(|=, CompoundOr)
LAMBDA_BINARY_OPERATOR(^=, CompoundXor)
LAMBDA_BINARY_OPERATOR(&&, LogicalAnd)
LAMBDA_BINARY_OPERATOR(||, LogicalOr)
LAMBDA_BINARY_OPERATOR(<<, LeftShift)
LAMBDA_BINARY_OPERATOR(<<=, CompoundLeftShift)
LAMBDA_BINARY_OPERATOR(>>, RightShift)
LAMBDA_BINARY_OPERATOR(>>=, CompoundRightShift)
//LAMBDA_BINARY_OPERATOR(=, Assignment)
LAMBDA_BINARY_OPERATOR(==, Equals)
LAMBDA_BINARY_OPERATOR(!=, NotEqual)
LAMBDA_BINARY_OPERATOR(<, LessThan)
LAMBDA_BINARY_OPERATOR(>, GreaterThan)
LAMBDA_BINARY_OPERATOR(<=, LessThanOrEqualTo)
LAMBDA_BINARY_OPERATOR(>=, GreaterThanOrEqualTo)
<commit_msg>Bugfix.<commit_after>#include <type_traits>
namespace Lambda {
using namespace std;
struct Functor {};
template<typename _Type>
struct IsBound {
static bool constexpr s_f = !is_base_of<
Functor,
typename remove_cv<
typename remove_reference<_Type>::type
>::type
>::value;
};
template<typename _Type>
inline _Type &&Pass(_Type &&rr) {
return rr;
}
template<unsigned int _i>
struct Bind :
public Functor
{
template<typename _First, typename... _Other>
inline static auto Apply(_First&&, _Other&&... rrOther) -> decltype(Bind<_i - 1>::Apply(rrOther...)) {
return Bind<_i - 1>::Apply(rrOther...);
}
template<typename... _Arguments>
inline auto operator () (_Arguments&&... rrArguments) -> decltype(Bind<_i>::Apply(rrArguments...)) {
return Bind<_i>::Apply(rrArguments...);
}
};
template<>
struct Bind<0> :
public Functor
{
template<typename _Type, typename... _Other>
inline static _Type &&Apply(_Type &&rr, _Other&&...) {
return rr;
}
template<typename _Type, typename... _Other>
inline _Type &&operator () (_Type &&rr, _Other&&...) {
return rr;
}
};
#define LAMBDA_PREFIX_UNARY_FUNCTOR_CLASS(Operator, Name) \
template<typename _Operand, bool _fBound = IsBound<_Operand>::s_f> \
struct Name; \
template<typename _Operand> \
struct Name<_Operand, false> : \
public Functor \
{ \
_Operand m_Operand; \
Name(_Operand &&a_rrOperand) \
: \
m_Operand(Pass(a_rrOperand)) {} \
template<typename... _Arguments> \
inline auto operator () (_Arguments&&... Arguments) -> decltype(Operator(m_Operand(Arguments...))) { \
return Operator(m_Operand(Arguments...)); \
} \
}; \
template<typename _Operand> \
struct Name<_Operand, true> : \
public Functor \
{ \
_Operand m_Operand; \
Name(_Operand &&a_rrOperand) \
: \
m_Operand(Pass(a_rrOperand)) {} \
template<typename... _Arguments> \
inline auto operator () (_Arguments&&...) -> decltype(Operator m_Operand) { \
return Operator m_Operand; \
} \
};
#define LAMBDA_POSTFIX_UNARY_FUNCTOR_CLASS(Operator, Name) \
template<typename _Operand, bool _fBound = IsBound<_Operand>::s_f> \
struct Name; \
template<typename _Operand> \
struct Name<_Operand, false> : \
public Functor \
{ \
_Operand m_Operand; \
Name(_Operand &&a_rrOperand) \
: \
m_Operand(Pass(a_rrOperand)) {} \
template<typename... _Arguments> \
inline auto operator () (_Arguments&&... Arguments) -> decltype((m_Operand(Arguments...)) Operator) { \
return (m_Operand(Arguments...)) Operator; \
} \
}; \
template<typename _Operand> \
struct Name<_Operand, true> : \
public Functor \
{ \
_Operand m_Operand; \
Name(_Operand &&a_rrOperand) \
: \
m_Operand(Pass(a_rrOperand)) {} \
template<typename... _Arguments> \
inline auto operator () (_Arguments&&...) -> decltype(m_Operand Operator) { \
return m_Operand Operator; \
} \
};
LAMBDA_PREFIX_UNARY_FUNCTOR_CLASS(+, UnaryPlus)
LAMBDA_PREFIX_UNARY_FUNCTOR_CLASS(-, UnaryMinus)
LAMBDA_PREFIX_UNARY_FUNCTOR_CLASS(!, LogicalNot)
LAMBDA_PREFIX_UNARY_FUNCTOR_CLASS(~, BitwiseNot)
LAMBDA_PREFIX_UNARY_FUNCTOR_CLASS(++, PreIncrement)
LAMBDA_PREFIX_UNARY_FUNCTOR_CLASS(--, PreDecrement)
LAMBDA_POSTFIX_UNARY_FUNCTOR_CLASS(++, PostIncrement)
LAMBDA_POSTFIX_UNARY_FUNCTOR_CLASS(--, PostDecrement)
#define LAMBDA_BINARY_FUNCTOR_CLASS(Operator, Name) \
template<typename _Left, typename _Right, bool _fLeftBound = IsBound<_Left>::s_f, bool _fRightBound = IsBound<_Right>::s_f> \
struct Name; \
template<typename _Left, typename _Right> \
struct Name<_Left, _Right, false, false> : \
public Functor \
{ \
_Left m_Left; \
_Right m_Right; \
Name(_Left &&a_rrLeft, _Right &&a_rrRight) \
: \
m_Left(Pass(a_rrLeft)), \
m_Right(Pass(a_rrRight)) {} \
template<typename... _Arguments> \
inline auto operator () (_Arguments&&... Arguments) -> decltype(m_Left(Arguments...) Operator m_Right(Arguments...)) { \
return m_Left(Arguments...) Operator m_Right(Arguments...); \
} \
}; \
template<typename _Left, typename _Right> \
struct Name<_Left, _Right, true, false> : \
public Functor \
{ \
_Left m_Left; \
_Right m_Right; \
Name(_Left &&a_rrLeft, _Right &&a_rrRight) \
: \
m_Left(Pass(a_rrLeft)), \
m_Right(Pass(a_rrRight)) {} \
template<typename... _Arguments> \
inline auto operator () (_Arguments&&... Arguments) -> decltype(m_Left Operator m_Right(Arguments...)) { \
return m_Left Operator m_Right(Arguments...); \
} \
}; \
template<typename _Left, typename _Right> \
struct Name<_Left, _Right, false, true> : \
public Functor \
{ \
_Left m_Left; \
_Right m_Right; \
Name(_Left &&a_rrLeft, _Right &&a_rrRight) \
: \
m_Left(Pass(a_rrLeft)), \
m_Right(Pass(a_rrRight)) {} \
template<typename... _Arguments> \
inline auto operator () (_Arguments&&... Arguments) -> decltype(m_Left(Arguments...) Operator m_Right) { \
return m_Left(Arguments...) Operator m_Right; \
} \
}; \
template<typename _Left, typename _Right> \
struct Name<_Left, _Right, true, true> : \
public Functor \
{ \
_Left m_Left; \
_Right m_Right; \
Name(_Left &&a_rrLeft, _Right &&a_rrRight) \
: \
m_Left(Pass(a_rrLeft)), \
m_Right(Pass(a_rrRight)) {} \
template<typename... _Arguments> \
inline auto operator () (_Arguments&&...) -> decltype(m_Left Operator m_Right) { \
return m_Left Operator m_Right; \
} \
};
LAMBDA_BINARY_FUNCTOR_CLASS(+, BinaryPlus)
LAMBDA_BINARY_FUNCTOR_CLASS(+=, CompoundPlus)
LAMBDA_BINARY_FUNCTOR_CLASS(-, BinaryMinus)
LAMBDA_BINARY_FUNCTOR_CLASS(-=, CompoundMinus)
LAMBDA_BINARY_FUNCTOR_CLASS(*, Multiply)
LAMBDA_BINARY_FUNCTOR_CLASS(*=, CompoundMultiply)
LAMBDA_BINARY_FUNCTOR_CLASS(/, Divide)
LAMBDA_BINARY_FUNCTOR_CLASS(/=, CompoundDivide)
LAMBDA_BINARY_FUNCTOR_CLASS(%, Modulus)
LAMBDA_BINARY_FUNCTOR_CLASS(%=, CompoundModulus)
LAMBDA_BINARY_FUNCTOR_CLASS(&, BitwiseAnd)
LAMBDA_BINARY_FUNCTOR_CLASS(|, BitwiseOr)
LAMBDA_BINARY_FUNCTOR_CLASS(^, BitwiseXor)
LAMBDA_BINARY_FUNCTOR_CLASS(&=, CompoundAnd)
LAMBDA_BINARY_FUNCTOR_CLASS(|=, CompoundOr)
LAMBDA_BINARY_FUNCTOR_CLASS(^=, CompoundXor)
LAMBDA_BINARY_FUNCTOR_CLASS(&&, LogicalAnd)
LAMBDA_BINARY_FUNCTOR_CLASS(||, LogicalOr)
LAMBDA_BINARY_FUNCTOR_CLASS(<<, LeftShift)
LAMBDA_BINARY_FUNCTOR_CLASS(<<=, CompoundLeftShift)
LAMBDA_BINARY_FUNCTOR_CLASS(>>, RightShift)
LAMBDA_BINARY_FUNCTOR_CLASS(>>=, CompoundRightShift)
//LAMBDA_BINARY_FUNCTOR_CLASS(=, Assignment)
LAMBDA_BINARY_FUNCTOR_CLASS(==, Equals)
LAMBDA_BINARY_FUNCTOR_CLASS(!=, NotEqual)
LAMBDA_BINARY_FUNCTOR_CLASS(<, LessThan)
LAMBDA_BINARY_FUNCTOR_CLASS(>, GreaterThan)
LAMBDA_BINARY_FUNCTOR_CLASS(<=, LessThanOrEqualTo)
LAMBDA_BINARY_FUNCTOR_CLASS(>=, GreaterThanOrEqualTo)
}
Lambda::Bind<0> _1;
Lambda::Bind<1> _2;
Lambda::Bind<2> _3;
Lambda::Bind<3> _4;
Lambda::Bind<4> _5;
Lambda::Bind<5> _6;
Lambda::Bind<6> _7;
Lambda::Bind<7> _8;
Lambda::Bind<8> _9;
Lambda::Bind<9> _10;
#define LAMBDA_PREFIX_UNARY_OPERATOR(Operator, FunctorClass) \
template<typename _Operand> \
inline Lambda::FunctorClass<_Operand> operator Operator (_Operand &&rrOperand) { \
return Lambda::FunctorClass<_Operand>((_Operand&&)rrOperand); \
}
LAMBDA_PREFIX_UNARY_OPERATOR(+, UnaryPlus)
LAMBDA_PREFIX_UNARY_OPERATOR(-, UnaryMinus)
LAMBDA_PREFIX_UNARY_OPERATOR(!, LogicalNot)
LAMBDA_PREFIX_UNARY_OPERATOR(~, BitwiseNot)
LAMBDA_PREFIX_UNARY_OPERATOR(++, PreIncrement)
LAMBDA_PREFIX_UNARY_OPERATOR(--, PreDecrement)
#define LAMBDA_BINARY_OPERATOR(Operator, FunctorClass) \
template<typename _Left, typename _Right> \
inline Lambda::FunctorClass<_Left, _Right> operator Operator (_Left &&rrLeft, _Right &&rrRight) { \
return Lambda::FunctorClass<_Left, _Right>((_Left&&)rrLeft, (_Right&&)rrRight); \
}
LAMBDA_BINARY_OPERATOR(+, BinaryPlus)
LAMBDA_BINARY_OPERATOR(+=, CompoundPlus)
LAMBDA_BINARY_OPERATOR(-, BinaryMinus)
LAMBDA_BINARY_OPERATOR(-=, CompoundMinus)
LAMBDA_BINARY_OPERATOR(*, Multiply)
LAMBDA_BINARY_OPERATOR(*=, CompoundMultiply)
LAMBDA_BINARY_OPERATOR(/, Divide)
LAMBDA_BINARY_OPERATOR(/=, CompoundDivide)
LAMBDA_BINARY_OPERATOR(%, Modulus)
LAMBDA_BINARY_OPERATOR(%=, CompoundModulus)
LAMBDA_BINARY_OPERATOR(&, BitwiseAnd)
LAMBDA_BINARY_OPERATOR(|, BitwiseOr)
LAMBDA_BINARY_OPERATOR(^, BitwiseXor)
LAMBDA_BINARY_OPERATOR(&=, CompoundAnd)
LAMBDA_BINARY_OPERATOR(|=, CompoundOr)
LAMBDA_BINARY_OPERATOR(^=, CompoundXor)
LAMBDA_BINARY_OPERATOR(&&, LogicalAnd)
LAMBDA_BINARY_OPERATOR(||, LogicalOr)
LAMBDA_BINARY_OPERATOR(<<, LeftShift)
LAMBDA_BINARY_OPERATOR(<<=, CompoundLeftShift)
LAMBDA_BINARY_OPERATOR(>>, RightShift)
LAMBDA_BINARY_OPERATOR(>>=, CompoundRightShift)
//LAMBDA_BINARY_OPERATOR(=, Assignment)
LAMBDA_BINARY_OPERATOR(==, Equals)
LAMBDA_BINARY_OPERATOR(!=, NotEqual)
LAMBDA_BINARY_OPERATOR(<, LessThan)
LAMBDA_BINARY_OPERATOR(>, GreaterThan)
LAMBDA_BINARY_OPERATOR(<=, LessThanOrEqualTo)
LAMBDA_BINARY_OPERATOR(>=, GreaterThanOrEqualTo)
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkObjectMorphologyImageFilterTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.
=========================================================================*/
#include <stdlib.h>
#include <time.h>
#include <itkImage.h>
#include "itkDilateObjectMorphologyImageFilter.h"
#include "itkBinaryErodeImageFilter.h"
#include "itkBinaryDilateImageFilter.h"
#include "itkErodeObjectMorphologyImageFilter.h"
#include <itkBinaryBallStructuringElement.h>
#include <itkImageRegionIterator.h>
#include <itkExceptionObject.h>
int itkObjectMorphologyImageFilterTest(int, char* [] )
{
// Define the dimension of the images
const unsigned int myDimension = 3;
// Define the values of the input images
const unsigned short fgValue = 1;
const unsigned short bgValue = 0;
// Declare the types of the images
typedef itk::Image<unsigned short, myDimension> myImageType;
// Declare the type of the index to access images
typedef itk::Index<myDimension> myIndexType;
// Declare the type of the size
typedef itk::Size<myDimension> mySizeType;
// Declare the type of the Region
typedef itk::ImageRegion<myDimension> myRegionType;
// Create an image
myImageType::Pointer inputImage = myImageType::New();
// Define their size, and start index
mySizeType size;
size[0] = 20;
size[1] = 20;
size[2] = 20;
myIndexType index;
index[0] = 0;
index[1] = 0;
index[2] = 0;
myRegionType region;
region.SetIndex( index );
region.SetSize( size );
// Initialize Image
inputImage->SetRegions( region );
inputImage->Allocate();
// Declare Iterator types apropriated for each image
typedef itk::ImageRegionIterator<myImageType> myIteratorType;
// Initialize the content of Image
inputImage->FillBuffer(bgValue);
myImageType::IndexType ind;
ind[0] = 10;
ind[1] = 10;
ind[2] = 10;
inputImage->SetPixel(ind, fgValue);
ind[0] = 2;
ind[1] = 2;
ind[2] = 8;
inputImage->SetPixel(ind, fgValue);
ind[0] = 9;
ind[1] = 10;
ind[2] = 5;
inputImage->SetPixel(ind, fgValue);
ind[0] = 9;
ind[1] = 0;
ind[2] = 15;
inputImage->SetPixel(ind, fgValue);
ind[0] = 9;
ind[1] = 9;
ind[2] = 7;
inputImage->SetPixel(ind, fgValue);
ind[0] = 0;
ind[1] = 4;
ind[2] = 17;
inputImage->SetPixel(ind, fgValue);
// Declare the type for the structuring element
typedef itk::BinaryBallStructuringElement<unsigned short, myDimension>
myKernelType;
// Declare the type for the morphology Filter
typedef itk::DilateObjectMorphologyImageFilter<myImageType, myImageType,
myKernelType>
myDilateFilterType;
typedef itk::BinaryDilateImageFilter<myImageType, myImageType,
myKernelType>
binDilateFilterType;
typedef itk::ErodeObjectMorphologyImageFilter<myImageType, myImageType,
myKernelType>
myErodeFilterType;
typedef itk::BinaryErodeImageFilter<myImageType, myImageType,
myKernelType>
binErodeFilterType;
// Create the filter
myDilateFilterType::Pointer dilateFilter = myDilateFilterType::New();
myErodeFilterType::Pointer erodeFilter = myErodeFilterType::New();
binDilateFilterType::Pointer binDilateFilter = binDilateFilterType::New();
binErodeFilterType::Pointer binErodeFilter = binErodeFilterType::New();
// Create the structuring element
myKernelType ball;
myKernelType::SizeType ballSize;
ballSize[0] = 5;
ballSize[1] = 5;
ballSize[2] = 5;
ball.SetRadius(ballSize);
ball.CreateStructuringElement();
// Connect the input image
dilateFilter->SetInput( inputImage );
dilateFilter->SetKernel( ball );
dilateFilter->SetObjectValue( fgValue );
myImageType::Pointer outputImage = dilateFilter->GetOutput();
clock_t start, end;
double elapsedTime;
// Execute the filter
try
{
std::cout << "Object Dilate..." << std::endl;
start = clock();
dilateFilter->Update();
end = clock();
elapsedTime = (end - start) / (double) CLOCKS_PER_SEC;
// Print the content of the result image
std::cout << " Success: " << std::endl;
std::cout << " Time = " << elapsedTime << std::endl;
}
catch (itk::ExceptionObject& e)
{
std::cerr << "Exception caught during dilate filter Update\n" << e;
return -1;
}
binDilateFilter->SetInput( inputImage );
binDilateFilter->SetKernel( ball );
binDilateFilter->SetDilateValue( fgValue );
myImageType::Pointer outputBinImage = binDilateFilter->GetOutput();
try
{
std::cout << "Binary Dilate..." << std::endl;
start = clock();
binDilateFilter->Update();
end = clock();
elapsedTime = (end - start) / (double) CLOCKS_PER_SEC;
// Print the content of the result image
std::cout << " Success: " << std::endl;
std::cout << " Time = " << elapsedTime << std::endl;
}
catch (itk::ExceptionObject& e)
{
std::cerr << "Exception caught during dilate filter Update\n" << e;
return -1;
}
// Create an iterator for going through the image output
myIteratorType itObj(outputImage, outputImage->GetBufferedRegion());
myIteratorType itBin(outputBinImage, outputBinImage->GetBufferedRegion());
std::cout << "Test for Dilate equality..." << std::endl;
start = clock();
while( !itObj.IsAtEnd() && !itBin.IsAtEnd() )
{
if(itObj.Get() != itBin.Get())
{
std::cerr << "Error: Dilated images differ!" << std::endl;
return -1;
}
++itObj;
++itBin;
}
end = clock();
elapsedTime = (end - start) / (double) CLOCKS_PER_SEC;
std::cout << " Success: " << std::endl;
std::cout << " Time = " << elapsedTime << std::endl;
ballSize[0] = 1;
ballSize[1] = 1;
ballSize[2] = 1;
ball.SetRadius(ballSize);
ball.CreateStructuringElement();
// Connect the input image
erodeFilter->SetInput( outputImage );
erodeFilter->SetKernel( ball );
erodeFilter->SetObjectValue( fgValue );
erodeFilter->SetBackgroundValue( bgValue );
myImageType::Pointer output2Image = erodeFilter->GetOutput();
// Execute the filter
try
{
std::cout << "Object Erode..." << std::endl;
start = clock();
erodeFilter->Update();
end = clock();
elapsedTime = (end - start) / (double) CLOCKS_PER_SEC;
// Print the content of the result image
std::cout << " Success: " << std::endl;
std::cout << " Time = " << elapsedTime << std::endl;
}
catch (itk::ExceptionObject& e)
{
std::cerr << "Exception caught during erode filter Update\n" << e;
return -1;
}
binErodeFilter->SetInput( outputImage );
binErodeFilter->SetKernel( ball );
binErodeFilter->SetErodeValue( fgValue );
myImageType::Pointer outputBin2Image = binErodeFilter->GetOutput();
// Execute the filter
try
{
std::cout << "Binary Erode..." << std::endl;
start = clock();
binErodeFilter->Update();
end = clock();
elapsedTime = (end - start) / (double) CLOCKS_PER_SEC;
// Print the content of the result image
std::cout << " Success: " << std::endl;
std::cout << " Time = " << elapsedTime << std::endl;
}
catch (itk::ExceptionObject& e)
{
std::cerr << "Exception caught during erode filter Update\n" << e;
return -1;
}
// Create an iterator for going through the image output
myIteratorType it2Obj(output2Image, output2Image->GetBufferedRegion());
myIteratorType it2Bin(outputBin2Image, outputBin2Image->GetBufferedRegion());
std::cout << "Test for Erode equality..." << std::endl;
start = clock();
while( !it2Obj.IsAtEnd() )
{
if(it2Obj.Get() != it2Bin.Get())
{
std::cout << "As expected: Error: Eroded images differ!" << std::endl;
std::cout << " Please see documentation - ErodeObject and BinaryErode";
std::cout << std::endl << " produce different results" << std::endl;
break;
}
++it2Obj;
++it2Bin;
}
end = clock();
elapsedTime = (end - start) / (double) CLOCKS_PER_SEC;
std::cout << " Success: " << std::endl;
std::cout << " Time = " << elapsedTime << std::endl;
// All objects should be automatically destroyed at this point
return 0;
}
<commit_msg>ENH: Improved detail in error message - tracking IRIX64 error<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkObjectMorphologyImageFilterTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.
=========================================================================*/
#include <stdlib.h>
#include <time.h>
#include <itkImage.h>
#include <itkIndex.h>
#include "itkDilateObjectMorphologyImageFilter.h"
#include "itkBinaryErodeImageFilter.h"
#include "itkBinaryDilateImageFilter.h"
#include "itkErodeObjectMorphologyImageFilter.h"
#include <itkBinaryBallStructuringElement.h>
#include <itkImageRegionIterator.h>
#include <itkExceptionObject.h>
int itkObjectMorphologyImageFilterTest(int, char* [] )
{
// Define the dimension of the images
const unsigned int myDimension = 3;
// Define the values of the input images
const unsigned short fgValue = 1;
const unsigned short bgValue = 0;
// Declare the types of the images
typedef itk::Image<unsigned short, myDimension> myImageType;
// Declare the type of the index to access images
typedef itk::Index<myDimension> myIndexType;
// Declare the type of the size
typedef itk::Size<myDimension> mySizeType;
// Declare the type of the Region
typedef itk::ImageRegion<myDimension> myRegionType;
// Create an image
myImageType::Pointer inputImage = myImageType::New();
// Define their size, and start index
mySizeType size;
size[0] = 20;
size[1] = 20;
size[2] = 20;
myIndexType index;
index[0] = 0;
index[1] = 0;
index[2] = 0;
myRegionType region;
region.SetIndex( index );
region.SetSize( size );
// Initialize Image
inputImage->SetRegions( region );
inputImage->Allocate();
// Declare Iterator types apropriated for each image
typedef itk::ImageRegionIterator<myImageType> myIteratorType;
// Initialize the content of Image
inputImage->FillBuffer(bgValue);
myImageType::IndexType ind;
ind[0] = 10;
ind[1] = 10;
ind[2] = 10;
inputImage->SetPixel(ind, fgValue);
ind[0] = 2;
ind[1] = 2;
ind[2] = 8;
inputImage->SetPixel(ind, fgValue);
ind[0] = 9;
ind[1] = 10;
ind[2] = 5;
inputImage->SetPixel(ind, fgValue);
ind[0] = 9;
ind[1] = 0;
ind[2] = 15;
inputImage->SetPixel(ind, fgValue);
ind[0] = 9;
ind[1] = 9;
ind[2] = 7;
inputImage->SetPixel(ind, fgValue);
ind[0] = 0;
ind[1] = 4;
ind[2] = 17;
inputImage->SetPixel(ind, fgValue);
// Declare the type for the structuring element
typedef itk::BinaryBallStructuringElement<unsigned short, myDimension>
myKernelType;
// Declare the type for the morphology Filter
typedef itk::DilateObjectMorphologyImageFilter<myImageType, myImageType,
myKernelType>
myDilateFilterType;
typedef itk::BinaryDilateImageFilter<myImageType, myImageType,
myKernelType>
binDilateFilterType;
typedef itk::ErodeObjectMorphologyImageFilter<myImageType, myImageType,
myKernelType>
myErodeFilterType;
typedef itk::BinaryErodeImageFilter<myImageType, myImageType,
myKernelType>
binErodeFilterType;
// Create the filter
myDilateFilterType::Pointer dilateFilter = myDilateFilterType::New();
myErodeFilterType::Pointer erodeFilter = myErodeFilterType::New();
binDilateFilterType::Pointer binDilateFilter = binDilateFilterType::New();
binErodeFilterType::Pointer binErodeFilter = binErodeFilterType::New();
// Create the structuring element
myKernelType ball;
myKernelType::SizeType ballSize;
ballSize[0] = 5;
ballSize[1] = 4;
ballSize[2] = 3;
ball.SetRadius(ballSize);
ball.CreateStructuringElement();
// Connect the input image
dilateFilter->SetInput( inputImage );
dilateFilter->SetKernel( ball );
dilateFilter->SetObjectValue( fgValue );
myImageType::Pointer outputImage = dilateFilter->GetOutput();
clock_t start, end;
double elapsedTime;
// Execute the filter
try
{
std::cout << "Object Dilate..." << std::endl;
start = clock();
dilateFilter->Update();
end = clock();
elapsedTime = (end - start) / (double) CLOCKS_PER_SEC;
// Print the content of the result image
std::cout << " Success: " << std::endl;
std::cout << " Time = " << elapsedTime << std::endl;
}
catch (itk::ExceptionObject& e)
{
std::cerr << "Exception caught during dilate filter Update\n" << e;
return -1;
}
binDilateFilter->SetInput( inputImage );
binDilateFilter->SetKernel( ball );
binDilateFilter->SetDilateValue( fgValue );
myImageType::Pointer outputBinImage = binDilateFilter->GetOutput();
try
{
std::cout << "Binary Dilate..." << std::endl;
start = clock();
binDilateFilter->Update();
end = clock();
elapsedTime = (end - start) / (double) CLOCKS_PER_SEC;
// Print the content of the result image
std::cout << " Success: " << std::endl;
std::cout << " Time = " << elapsedTime << std::endl;
}
catch (itk::ExceptionObject& e)
{
std::cerr << "Exception caught during dilate filter Update\n" << e;
return -1;
}
// Create an iterator for going through the image output
myIteratorType itObj(outputImage, outputImage->GetBufferedRegion());
myIteratorType itBin(outputBinImage, outputBinImage->GetBufferedRegion());
std::cout << "Test for Dilate equality..." << std::endl;
start = clock();
itObj.GoToBegin();
itBin.GoToBegin();
int count = 0;
while( !itObj.IsAtEnd() && !itBin.IsAtEnd() )
{
if(itObj.Get() != itBin.Get())
{
std::cerr << "Error: Dilated images differ!" << std::endl;
std::cerr << " Slice = " << count/(size[1]*size[0]) << std::endl;
int x, y;
itk::Index<3> i;
i[2] = count/(size[1]*size[0]);
for(y=0; y<size[1]; y++)
{
i[1] = y;
for(x=0; x<size[0]; x++)
{
i[0] = x;
std::cerr << outputImage->GetPixel(i)
<< outputBinImage->GetPixel(i) << " ";
}
std::cerr << std::endl;
}
return -1;
}
++itObj;
++itBin;
++count;
}
end = clock();
elapsedTime = (end - start) / (double) CLOCKS_PER_SEC;
std::cout << " Success: " << std::endl;
std::cout << " Time = " << elapsedTime << std::endl;
ballSize[0] = 2;
ballSize[1] = 2;
ballSize[2] = 2;
ball.SetRadius(ballSize);
ball.CreateStructuringElement();
// Connect the input image
erodeFilter->SetInput( outputImage );
erodeFilter->SetKernel( ball );
erodeFilter->SetObjectValue( fgValue );
erodeFilter->SetBackgroundValue( bgValue );
myImageType::Pointer output2Image = erodeFilter->GetOutput();
// Execute the filter
try
{
std::cout << "Object Erode..." << std::endl;
start = clock();
erodeFilter->Update();
end = clock();
elapsedTime = (end - start) / (double) CLOCKS_PER_SEC;
// Print the content of the result image
std::cout << " Success: " << std::endl;
std::cout << " Time = " << elapsedTime << std::endl;
}
catch (itk::ExceptionObject& e)
{
std::cerr << "Exception caught during erode filter Update\n" << e;
return -1;
}
binErodeFilter->SetInput( outputImage );
binErodeFilter->SetKernel( ball );
binErodeFilter->SetErodeValue( fgValue );
myImageType::Pointer outputBin2Image = binErodeFilter->GetOutput();
// Execute the filter
try
{
std::cout << "Binary Erode..." << std::endl;
start = clock();
binErodeFilter->Update();
end = clock();
elapsedTime = (end - start) / (double) CLOCKS_PER_SEC;
// Print the content of the result image
std::cout << " Success: " << std::endl;
std::cout << " Time = " << elapsedTime << std::endl;
}
catch (itk::ExceptionObject& e)
{
std::cerr << "Exception caught during erode filter Update\n" << e;
return -1;
}
// Create an iterator for going through the image output
myIteratorType it2Obj(output2Image, output2Image->GetBufferedRegion());
myIteratorType it2Bin(outputBin2Image, outputBin2Image->GetBufferedRegion());
std::cout << "Test for Erode equality..." << std::endl;
start = clock();
count = 0;
while( !it2Obj.IsAtEnd() )
{
if(it2Obj.Get() != it2Bin.Get())
{
std::cout << "As expected: Error: Eroded images differ!" << std::endl;
std::cout << " Please see documentation - ErodeObject and BinaryErode";
std::cout << std::endl << " produce different results" << std::endl;
std::cout << " Slice = " << count/(size[1]*size[0]) << std::endl;
int x, y;
itk::Index<3> i;
i[2] = count/(size[1]*size[0]);
for(y=0; y<size[1]; y++)
{
i[1] = y;
for(x=0; x<size[0]; x++)
{
i[0] = x;
std::cout << output2Image->GetPixel(i)
<< outputBin2Image->GetPixel(i) << " ";
}
std::cout << std::endl;
}
break;
}
++it2Obj;
++it2Bin;
++count;
}
end = clock();
elapsedTime = (end - start) / (double) CLOCKS_PER_SEC;
std::cout << " Success: " << std::endl;
std::cout << " Time = " << elapsedTime << std::endl;
// All objects should be automatically destroyed at this point
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2014, Baidu.com, Inc. All Rights Reserved
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Author: yanshiguang02@baidu.com
#include "logging.h"
#include <assert.h>
#include <boost/bind.hpp>
#include <queue>
#include <set>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <syscall.h>
#include <sys/time.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include "mutex.h"
#include "thread.h"
#include "timer.h"
namespace baidu {
namespace common {
int g_log_level = INFO;
int64_t g_log_size = 0;
int32_t g_log_count = 0;
FILE* g_log_file = stdout;
std::string g_log_file_name;
FILE* g_warning_file = NULL;
int64_t g_total_size_limit = 0;
std::queue<std::string> g_log_queue;
int64_t current_total_size = 0;
bool GetNewLog(bool append) {
char buf[30];
struct timeval tv;
gettimeofday(&tv, NULL);
const time_t seconds = tv.tv_sec;
struct tm t;
localtime_r(&seconds, &t);
snprintf(buf, 30,
"%02d-%02d.%02d:%02d:%02d.%06d",
t.tm_mon + 1,
t.tm_mday,
t.tm_hour,
t.tm_min,
t.tm_sec,
static_cast<int>(tv.tv_usec));
std::string full_path(g_log_file_name + ".");
full_path.append(buf);
size_t idx = full_path.rfind('/');
if (idx == std::string::npos) {
idx = 0;
} else {
idx += 1;
}
const char* mode = append ? "ab" : "wb";
FILE* fp = fopen(full_path.c_str(), mode);
if (fp == NULL) {
return false;
}
if (g_log_file != stdout) {
fclose(g_log_file);
}
g_log_file = fp;
remove(g_log_file_name.c_str());
symlink(full_path.substr(idx).c_str(), g_log_file_name.c_str());
g_log_queue.push(full_path);
while ((g_log_count && static_cast<int64_t>(g_log_queue.size()) > g_log_count)
|| (g_total_size_limit && current_total_size > g_total_size_limit)) {
std::string to_del = g_log_queue.front();
struct stat sta;
if (-1 == lstat(to_del.c_str(), &sta)) {
return false;
}
remove(to_del.c_str());
current_total_size -= sta.st_size;
g_log_queue.pop();
}
return true;
}
void SetLogLevel(int level) {
g_log_level = level;
}
class AsyncLogger {
public:
AsyncLogger()
: jobs_(&mu_), done_(&mu_), stopped_(false), size_(0) {
thread_.Start(boost::bind(&AsyncLogger::AsyncWriter, this));
}
~AsyncLogger() {
stopped_ = true;
{
MutexLock lock(&mu_);
jobs_.Signal();
}
thread_.Join();
// close fd
}
void WriteLog(int log_level, const char* buffer, int32_t len) {
std::string* log_str = new std::string(buffer, len);
MutexLock lock(&mu_);
buffer_queue_.push(make_pair(log_level, log_str));
jobs_.Signal();
}
void AsyncWriter() {
MutexLock lock(&mu_);
while (1) {
int loglen = 0;
int wflen = 0;
while (!buffer_queue_.empty()) {
int log_level = buffer_queue_.front().first;
std::string* str = buffer_queue_.front().second;
buffer_queue_.pop();
if (g_log_file != stdout && g_log_size && str &&
static_cast<int64_t>(size_ + str->length()) > g_log_size) {
current_total_size += static_cast<int64_t>(size_ + str->length());
mu_.Unlock();
GetNewLog(false);
mu_.Lock();
size_ = 0;
}
mu_.Unlock();
if (str && !str->empty()) {
fwrite(str->data(), 1, str->size(), g_log_file);
loglen += str->size();
if (g_warning_file && log_level >= 8) {
fwrite(str->data(), 1, str->size(), g_warning_file);
wflen += str->size();
}
if (g_log_size) size_ += str->length();
}
delete str;
mu_.Lock();
}
if (loglen) fflush(g_log_file);
if (wflen) fflush(g_warning_file);
if (stopped_) {
break;
}
done_.Broadcast();
jobs_.Wait();
}
}
void Flush() {
MutexLock lock(&mu_);
buffer_queue_.push(std::make_pair(0, reinterpret_cast<std::string*>(NULL)));
jobs_.Signal();
done_.Wait();
}
private:
Mutex mu_;
CondVar jobs_;
CondVar done_;
bool stopped_;
int64_t size_;
Thread thread_;
std::queue<std::pair<int, std::string*> > buffer_queue_;
};
AsyncLogger g_logger;
bool SetWarningFile(const char* path, bool append) {
const char* mode = append ? "ab" : "wb";
FILE* fp = fopen(path, mode);
if (fp == NULL) {
return false;
}
if (g_warning_file) {
fclose(g_warning_file);
}
g_warning_file = fp;
return true;
}
bool RecoverHistory(const char* path) {
std::string log_path(path);
size_t idx = log_path.rfind('/');
std::string dir = "./";
std::string log(path);
if (idx != std::string::npos) {
dir = log_path.substr(0, idx + 1);
log = log_path.substr(idx + 1);
}
struct dirent *entry = NULL;
DIR *dir_ptr = opendir(dir.c_str());
if (dir_ptr == NULL) {
return false;
}
std::vector<std::string> loglist;
while (entry = readdir(dir_ptr)) {
if (std::string(entry->d_name).find(log) != std::string::npos) {
std::string file_name = dir + std::string(entry->d_name);
struct stat sta;
if (-1 == lstat(file_name.c_str(), &sta)) {
return false;
}
if (S_ISREG(sta.st_mode)) {
loglist.push_back(dir + std::string(entry->d_name));
current_total_size += sta.st_size;
}
}
}
closedir(dir_ptr);
std::sort(loglist.begin(), loglist.end());
for (std::vector<std::string>::iterator it = loglist.begin(); it != loglist.end();
++it) {
if (*it != g_log_queue.front()) {
g_log_queue.push(*it);
}
}
while ( (g_log_count && static_cast<int64_t>(g_log_queue.size()) > g_log_count)
|| (g_total_size_limit && current_total_size > g_total_size_limit)) {
std::string to_del = g_log_queue.front();
struct stat sta;
if (-1 == lstat(to_del.c_str(), &sta)) break;
current_total_size -= sta.st_size;
remove(to_del.c_str());
g_log_queue.pop();
}
return true;
}
bool SetLogFile(const char* path, bool append) {
g_log_file_name.assign(path);
return GetNewLog(append);
}
bool SetLogSize(int size) {
if (size < 0) {
return false;
}
g_log_size = static_cast<int64_t>(size) << 20;
return true;
}
bool SetLogCount(int count) {
if (count < 0 || g_total_size_limit != 0) {
return false;
}
g_log_count = count;
if (!RecoverHistory(g_log_file_name.c_str())) {
return false;
}
return true;
}
bool SetLogSizeLimit(int size) {
if (size < 0 || g_log_count != 0) {
return false;
}
g_total_size_limit = static_cast<int64_t>(size) << 20;
if (!RecoverHistory(g_log_file_name.c_str())) {
return false;
}
return true;
}
void Logv(int log_level, const char* format, va_list ap) {
static __thread uint64_t thread_id = 0;
if (thread_id == 0) {
thread_id = syscall(__NR_gettid);
}
// We try twice: the first time with a fixed-size stack allocated buffer,
// and the second time with a much larger dynamically allocated buffer.
char buffer[500];
for (int iter = 0; iter < 2; iter++) {
char* base;
int bufsize;
if (iter == 0) {
bufsize = sizeof(buffer);
base = buffer;
} else {
bufsize = 30000;
base = new char[bufsize];
}
char* p = base;
char* limit = base + bufsize;
int32_t rlen = timer::now_time_str(p, limit - p);
p += rlen;
p += snprintf(p, limit - p, " %lld ", static_cast<long long unsigned int>(thread_id));
// Print the message
if (p < limit) {
va_list backup_ap;
va_copy(backup_ap, ap);
p += vsnprintf(p, limit - p, format, backup_ap);
va_end(backup_ap);
}
// Truncate to available space if necessary
if (p >= limit) {
if (iter == 0) {
continue; // Try again with larger buffer
} else {
p = limit - 1;
}
}
// Add newline if necessary
if (p == base || p[-1] != '\n') {
*p++ = '\n';
}
assert(p <= limit);
//fwrite(base, 1, p - base, g_log_file);
//fflush(g_log_file);
//if (g_warning_file && log_level >= 8) {
// fwrite(base, 1, p - base, g_warning_file);
// fflush(g_warning_file);
//}
g_logger.WriteLog(log_level, base, p - base);
if (log_level == FATAL) {
g_logger.Flush();
}
if (base != buffer) {
delete[] base;
}
break;
}
}
void Log(int level, const char* fmt, ...) {
va_list ap;
va_start(ap, fmt);
if (level >= g_log_level) {
Logv(level, fmt, ap);
}
va_end(ap);
if (level == FATAL) {
abort();
}
}
LogStream::LogStream(int level) : level_(level) {}
LogStream::~LogStream() {
Log(level_, "%s", oss_.str().c_str());
}
} // namespace common
} // namespace baidu
/* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */
<commit_msg>use set instead of queue<commit_after>// Copyright (c) 2014, Baidu.com, Inc. All Rights Reserved
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Author: yanshiguang02@baidu.com
#include "logging.h"
#include <assert.h>
#include <boost/bind.hpp>
#include <queue>
#include <set>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <syscall.h>
#include <sys/time.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include "mutex.h"
#include "thread.h"
#include "timer.h"
namespace baidu {
namespace common {
int g_log_level = INFO;
int64_t g_log_size = 0;
int32_t g_log_count = 0;
FILE* g_log_file = stdout;
std::string g_log_file_name;
FILE* g_warning_file = NULL;
int64_t g_total_size_limit = 0;
std::set<std::string> g_log_set;
int64_t current_total_size = 0;
bool GetNewLog(bool append) {
char buf[30];
struct timeval tv;
gettimeofday(&tv, NULL);
const time_t seconds = tv.tv_sec;
struct tm t;
localtime_r(&seconds, &t);
snprintf(buf, 30,
"%02d-%02d.%02d:%02d:%02d.%06d",
t.tm_mon + 1,
t.tm_mday,
t.tm_hour,
t.tm_min,
t.tm_sec,
static_cast<int>(tv.tv_usec));
std::string full_path(g_log_file_name + ".");
full_path.append(buf);
size_t idx = full_path.rfind('/');
if (idx == std::string::npos) {
idx = 0;
} else {
idx += 1;
}
const char* mode = append ? "ab" : "wb";
FILE* fp = fopen(full_path.c_str(), mode);
if (fp == NULL) {
return false;
}
if (g_log_file != stdout) {
fclose(g_log_file);
}
g_log_file = fp;
remove(g_log_file_name.c_str());
symlink(full_path.substr(idx).c_str(), g_log_file_name.c_str());
g_log_set.insert(full_path);
while ((g_log_count && static_cast<int64_t>(g_log_set.size()) > g_log_count)
|| (g_total_size_limit && current_total_size > g_total_size_limit)) {
std::set<std::string>::iterator it = g_log_set.begin();
if (it != g_log_set.end()) {
struct stat sta;
if (-1 == lstat(it->c_str(), &sta)) {
return false;
}
remove(it->c_str());
current_total_size -= sta.st_size;
g_log_set.erase(it++);
}
}
return true;
}
void SetLogLevel(int level) {
g_log_level = level;
}
class AsyncLogger {
public:
AsyncLogger()
: jobs_(&mu_), done_(&mu_), stopped_(false), size_(0) {
thread_.Start(boost::bind(&AsyncLogger::AsyncWriter, this));
}
~AsyncLogger() {
stopped_ = true;
{
MutexLock lock(&mu_);
jobs_.Signal();
}
thread_.Join();
// close fd
}
void WriteLog(int log_level, const char* buffer, int32_t len) {
std::string* log_str = new std::string(buffer, len);
MutexLock lock(&mu_);
buffer_queue_.push(make_pair(log_level, log_str));
jobs_.Signal();
}
void AsyncWriter() {
MutexLock lock(&mu_);
while (1) {
int loglen = 0;
int wflen = 0;
while (!buffer_queue_.empty()) {
int log_level = buffer_queue_.front().first;
std::string* str = buffer_queue_.front().second;
buffer_queue_.pop();
if (g_log_file != stdout && g_log_size && str &&
static_cast<int64_t>(size_ + str->length()) > g_log_size) {
current_total_size += static_cast<int64_t>(size_ + str->length());
mu_.Unlock();
GetNewLog(false);
mu_.Lock();
size_ = 0;
}
mu_.Unlock();
if (str && !str->empty()) {
fwrite(str->data(), 1, str->size(), g_log_file);
loglen += str->size();
if (g_warning_file && log_level >= 8) {
fwrite(str->data(), 1, str->size(), g_warning_file);
wflen += str->size();
}
if (g_log_size) size_ += str->length();
}
delete str;
mu_.Lock();
}
if (loglen) fflush(g_log_file);
if (wflen) fflush(g_warning_file);
if (stopped_) {
break;
}
done_.Broadcast();
jobs_.Wait();
}
}
void Flush() {
MutexLock lock(&mu_);
buffer_queue_.push(std::make_pair(0, reinterpret_cast<std::string*>(NULL)));
jobs_.Signal();
done_.Wait();
}
private:
Mutex mu_;
CondVar jobs_;
CondVar done_;
bool stopped_;
int64_t size_;
Thread thread_;
std::queue<std::pair<int, std::string*> > buffer_queue_;
};
AsyncLogger g_logger;
bool SetWarningFile(const char* path, bool append) {
const char* mode = append ? "ab" : "wb";
FILE* fp = fopen(path, mode);
if (fp == NULL) {
return false;
}
if (g_warning_file) {
fclose(g_warning_file);
}
g_warning_file = fp;
return true;
}
bool RecoverHistory(const char* path) {
std::string log_path(path);
size_t idx = log_path.rfind('/');
std::string dir = "./";
std::string log(path);
if (idx != std::string::npos) {
dir = log_path.substr(0, idx + 1);
log = log_path.substr(idx + 1);
}
struct dirent *entry = NULL;
DIR *dir_ptr = opendir(dir.c_str());
if (dir_ptr == NULL) {
return false;
}
std::vector<std::string> loglist;
while (entry = readdir(dir_ptr)) {
if (std::string(entry->d_name).find(log) != std::string::npos) {
std::string file_name = dir + std::string(entry->d_name);
struct stat sta;
if (-1 == lstat(file_name.c_str(), &sta)) {
return false;
}
if (S_ISREG(sta.st_mode)) {
loglist.push_back(dir + std::string(entry->d_name));
current_total_size += sta.st_size;
}
}
}
closedir(dir_ptr);
std::sort(loglist.begin(), loglist.end());
for (std::vector<std::string>::iterator it = loglist.begin(); it != loglist.end();
++it) {
g_log_set.insert(*it);
}
while ( (g_log_count && static_cast<int64_t>(g_log_set.size()) > g_log_count)
|| (g_total_size_limit && current_total_size > g_total_size_limit)) {
std::set<std::string>::iterator it = g_log_set.begin();
if (it != g_log_set.end()) {
struct stat sta;
if (-1 == lstat(it->c_str(), &sta)) {
return false;
}
remove(it->c_str());
current_total_size -= sta.st_size;
g_log_set.erase(it++);
}
}
return true;
}
bool SetLogFile(const char* path, bool append) {
g_log_file_name.assign(path);
return GetNewLog(append);
}
bool SetLogSize(int size) {
if (size < 0) {
return false;
}
g_log_size = static_cast<int64_t>(size) << 20;
return true;
}
bool SetLogCount(int count) {
if (count < 0 || g_total_size_limit != 0) {
return false;
}
g_log_count = count;
if (!RecoverHistory(g_log_file_name.c_str())) {
return false;
}
return true;
}
bool SetLogSizeLimit(int size) {
if (size < 0 || g_log_count != 0) {
return false;
}
g_total_size_limit = static_cast<int64_t>(size) << 20;
if (!RecoverHistory(g_log_file_name.c_str())) {
return false;
}
return true;
}
void Logv(int log_level, const char* format, va_list ap) {
static __thread uint64_t thread_id = 0;
if (thread_id == 0) {
thread_id = syscall(__NR_gettid);
}
// We try twice: the first time with a fixed-size stack allocated buffer,
// and the second time with a much larger dynamically allocated buffer.
char buffer[500];
for (int iter = 0; iter < 2; iter++) {
char* base;
int bufsize;
if (iter == 0) {
bufsize = sizeof(buffer);
base = buffer;
} else {
bufsize = 30000;
base = new char[bufsize];
}
char* p = base;
char* limit = base + bufsize;
int32_t rlen = timer::now_time_str(p, limit - p);
p += rlen;
p += snprintf(p, limit - p, " %lld ", static_cast<long long unsigned int>(thread_id));
// Print the message
if (p < limit) {
va_list backup_ap;
va_copy(backup_ap, ap);
p += vsnprintf(p, limit - p, format, backup_ap);
va_end(backup_ap);
}
// Truncate to available space if necessary
if (p >= limit) {
if (iter == 0) {
continue; // Try again with larger buffer
} else {
p = limit - 1;
}
}
// Add newline if necessary
if (p == base || p[-1] != '\n') {
*p++ = '\n';
}
assert(p <= limit);
//fwrite(base, 1, p - base, g_log_file);
//fflush(g_log_file);
//if (g_warning_file && log_level >= 8) {
// fwrite(base, 1, p - base, g_warning_file);
// fflush(g_warning_file);
//}
g_logger.WriteLog(log_level, base, p - base);
if (log_level == FATAL) {
g_logger.Flush();
}
if (base != buffer) {
delete[] base;
}
break;
}
}
void Log(int level, const char* fmt, ...) {
va_list ap;
va_start(ap, fmt);
if (level >= g_log_level) {
Logv(level, fmt, ap);
}
va_end(ap);
if (level == FATAL) {
abort();
}
}
LogStream::LogStream(int level) : level_(level) {}
LogStream::~LogStream() {
Log(level_, "%s", oss_.str().c_str());
}
} // namespace common
} // namespace baidu
/* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */
<|endoftext|>
|
<commit_before>/**\file
* \brief Matrix-esque terminal animation
*
* \copyright
* Copyright (c) 2012-2013, ef.gy Project Members
* \copyright
* 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:
* \copyright
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* \copyright
* 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.
*
* \see Project Documentation: http://ef.gy/documentation/libefgy
* \see Project Source Code: http://git.becquerel.org/jyujin/libefgy.git
*/
#include <iostream>
#include <ef.gy/vt100.h>
#include <ef.gy/random.h>
#include <unistd.h>
#include <chrono>
using namespace efgy;
using namespace std::chrono;
terminal::vt100<> output;
random::mersenneTwister<> rng(1337);
system_clock::time_point now;
class matrixStream
{
public:
class cell
{
public:
cell(const unsigned long &pCharacter)
: character(pCharacter), created(now) {}
unsigned long character;
system_clock::time_point created;
};
matrixStream(const std::size_t &pLine, const std::size_t &pColumn)
: line(pLine), column(pColumn), last(now) {}
std::size_t line;
std::size_t column;
std::vector<cell> data;
system_clock::time_point last;
bool update (void)
{
if ((now - last) > std::chrono::microseconds(40))
{
last = now;
switch (rng() % 4)
{
case 0:
if (data.size() > 0)
{
data.erase(data.begin() + (rng() % data.size()));
}
else
{
data.push_back(cell(rng() % (1 << 7)));
}
break;
default:
data.push_back(cell(rng() % (1 << 7)));
}
}
std::array<std::size_t,2> s = output.size();
int i = line;
for (cell &d : data)
{
if (i >= s[1])
{
break;
}
output.target[i][column].content = d.character;
output.target[i][column].foregroundColour = (now - d.created) > std::chrono::microseconds(120) ? 2 : 7;
output.target[i][column].backgroundColour = 0;
i++;
}
return true;
}
};
int main (int argc, char **argv)
{
output.resize(output.getOSDimensions());
std::array<std::size_t,2> s = output.size();
int i;
std::vector<matrixStream> streams;
while (1)
{
i++;
now = system_clock::now();
if (i % 100 == 0)
{
std::size_t l = rng() % s[1];
std::size_t c = rng() % s[0];
streams.push_back(matrixStream(l, c));
}
if (streams.size() > 200)
{
streams.erase(streams.begin());
}
for (matrixStream &s : streams)
{
if (rng() % 10 == 0)
{
s.update();
}
}
std::cout << output.flush();
usleep(10);
}
for (std::string s = output.flush(); s != ""; s = output.flush())
{
std::cout << s;
i++;
}
std::cout << "\e[39;49;0m\n";
return 0;
}
<commit_msg>some improvements to the matrix animation<commit_after>/**\file
* \brief Matrix-esque terminal animation
*
* \copyright
* Copyright (c) 2012-2013, ef.gy Project Members
* \copyright
* 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:
* \copyright
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* \copyright
* 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.
*
* \see Project Documentation: http://ef.gy/documentation/libefgy
* \see Project Source Code: http://git.becquerel.org/jyujin/libefgy.git
*/
#include <iostream>
#include <ef.gy/vt100.h>
#include <ef.gy/random.h>
#include <unistd.h>
#include <chrono>
using namespace efgy;
using namespace std::chrono;
terminal::vt100<> output;
random::mersenneTwister<> rng(1337);
system_clock::time_point now;
class matrixStream
{
public:
class cell
{
public:
cell(const unsigned long &pCharacter)
: character(pCharacter), created(now) {}
unsigned long character;
system_clock::time_point created;
};
matrixStream(const std::size_t &pLine, const std::size_t &pColumn)
: line(pLine), column(pColumn), last(now), doDelete(false) {}
std::size_t line;
std::size_t column;
std::vector<cell> data;
system_clock::time_point last;
bool doDelete;
bool update (void)
{
if ((now - last) > std::chrono::milliseconds(10))
{
last = now;
switch (rng() % 3)
{
case 0:
if (data.size() > 0)
{
data.erase(data.begin() + (rng() % data.size()));
}
else
{
data.push_back(cell(rng() % (1 << 7)));
}
break;
default:
data.push_back(cell(rng() % (1 << 7)));
}
}
std::array<std::size_t,2> s = output.size();
if (data.size() > (s[1]/2))
{
if (line < s[1])
{
if (rng() % 5 == 0)
{
output.target[line][column].content = ' ';
line++;
}
}
else
{
doDelete = true;
}
data.erase(data.begin());
}
int i = line;
for (cell &d : data)
{
if (i >= s[1])
{
break;
}
output.target[i][column].content = d.character;
output.target[i][column].foregroundColour = (now - d.created) > std::chrono::milliseconds(120) ? 2 : 7;
output.target[i][column].backgroundColour = 0;
i++;
}
return true;
}
};
int main (int argc, char **argv)
{
output.resize(output.getOSDimensions());
std::array<std::size_t,2> s = output.size();
int i;
std::vector<matrixStream> streams;
while (1)
{
i++;
now = system_clock::now();
if (i % 50 == 0)
{
std::size_t l = rng() % (s[1] / 3);
std::size_t c = rng() % s[0];
streams.push_back(matrixStream(l, c));
}
if (streams.size() > 100)
{
streams.erase(streams.begin());
}
for (matrixStream &s : streams)
{
s.update();
}
for (unsigned int i = 0; i < streams.size(); i++)
{
if (streams[i].doDelete)
{
streams.erase(streams.begin() + i);
}
}
std::cout << output.flush();
usleep(50);
}
for (std::string s = output.flush(); s != ""; s = output.flush())
{
std::cout << s;
i++;
}
std::cout << "\e[39;49;0m\n";
return 0;
}
<|endoftext|>
|
<commit_before>/**\file
* \ingroup example-programmes
* \brief Matrix-esque terminal animation
*
* This is a terminal programme that uses libefgy's vt100 code to render a text
* version of the matrix 'scrolling streams of text' animation. It's really
* fairly simple but also kinda nice to see how the vt100 output is performing.
*
* \image html matrix.png "Screenshot of the programme running in Terminal.app"
*
* \copyright
* Copyright (c) 2012-2013, ef.gy Project Members
* \copyright
* 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:
* \copyright
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* \copyright
* 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.
*
* \see Project Documentation: http://ef.gy/documentation/libefgy
* \see Project Source Code: http://git.becquerel.org/jyujin/libefgy.git
*/
#include <iostream>
#include <ef.gy/vt100.h>
#include <ef.gy/random.h>
#include <chrono>
#include <csignal>
#include <cmath>
#include <sched.h>
using namespace efgy;
using namespace std::chrono;
terminal::vt100<> output;
random::mersenneTwister<> rng(1337);
system_clock::time_point now;
class matrixStream
{
public:
class cell
{
public:
cell(const unsigned long &pCharacter)
: character(pCharacter), created(now) {}
unsigned long character;
system_clock::time_point created;
};
matrixStream(const std::size_t &pLine, const std::size_t &pColumn)
: line(pLine), column(pColumn), last(now), doDelete(false) {}
std::size_t line;
std::size_t column;
std::vector<cell> data;
system_clock::time_point last;
bool doDelete;
bool update (void)
{
if ((now - last) > std::chrono::milliseconds(10))
{
last = now;
switch (rng() % 3)
{
case 0:
if (data.size() > 0)
{
data.erase(data.begin() + (rng() % data.size()));
break;
}
default:
data.push_back(cell(rng() % (1 << 7)));
}
}
std::array<std::size_t,2> s = output.size();
if (data.size() > (s[1]/2))
{
if (line < s[1])
{
if (rng() % 5 == 0)
{
output.target[line][column].content = ' ';
line++;
}
}
else
{
doDelete = true;
}
data.erase(data.begin());
}
int i = line;
for (cell &d : data)
{
if (i >= s[1])
{
break;
}
output.target[i][column].content = d.character;
output.target[i][column].foregroundColour = (now - d.created) > std::chrono::milliseconds(120) ? 2 : 7;
output.target[i][column].backgroundColour = 0;
i++;
}
return true;
}
};
void handle_interrupt(int signal)
{
exit(1);
}
terminal::cell<long> postProcess
(const terminal::terminal<long>&t,
const std::size_t &l,
const std::size_t &c)
{
terminal::cell<long> rv = t.target[l][c];
rv.content = rv.content == 0 ? ' ' : rv.content;
rv.foregroundColour = rv.foregroundColour == 7 ? 7 : 2;
rv.backgroundColour = 0;
return rv;
}
terminal::cell<long> postProcessPolar
(const terminal::terminal<long>&t,
const std::size_t &pl,
const std::size_t &pc)
{
double l = pl;
double c = pc;
std::array<std::size_t,2> s = t.size();
double hl = s[1]/2;
double hc = s[0]/2;
double loff = l - hl;
double coff = c - hc;
double r2 = loff*loff + coff*coff;
double r = std::sqrt(r2);
l = hl + loff + std::sin(r) * 1.0;
c = hc + coff + std::cos(r) * 1.0;
const std::size_t tl = (std::size_t)l < s[1] ? (std::size_t)l : (s[1] - 1);
const std::size_t tc = (std::size_t)c < s[0] ? (std::size_t)c : (s[0] - 1);
terminal::cell<long> rv = t.target[tl][tc];
terminal::cell<long> cv = t.current[tl][tc];
rv.content = rv.content == 0 ? (cv.content == 0 ? ' ' : cv.content) : rv.content;
rv.foregroundColour = rv.foregroundColour == 7 ? 7 : 2;
rv.backgroundColour = 0;
return rv;
}
int main (int argc, char **argv)
{
output.resize(output.getOSDimensions());
std::array<std::size_t,2> s = output.size();
std::size_t i;
std::vector<matrixStream> streams;
std::signal(SIGINT, handle_interrupt);
while (1)
{
i++;
now = system_clock::now();
if ((streams.size() <= 100) && (i % 50 == 0))
{
std::size_t l = rng() % (s[1] / 3);
std::size_t c = rng() % s[0];
streams.push_back(matrixStream(l, c));
}
for (matrixStream &s : streams)
{
s.update();
}
for (unsigned int i = 0; i < streams.size(); i++)
{
if (streams[i].doDelete)
{
streams.erase(streams.begin() + i);
}
}
if (output.flush(postProcess) == 0)
{
sched_yield();
}
}
while ((i = output.flush(postProcess)) > 0);
return 0;
}
<commit_msg>started documenting the matrix demo<commit_after>/**\file
* \ingroup example-programmes
* \brief Matrix-esque terminal animation
*
* This is a terminal programme that uses libefgy's vt100 code to render a text
* version of the matrix 'scrolling streams of text' animation. It's really
* fairly simple but also kinda nice to see how the vt100 output is performing.
*
* \image html matrix.png "Screenshot of the programme running in Terminal.app"
*
* \copyright
* Copyright (c) 2012-2013, ef.gy Project Members
* \copyright
* 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:
* \copyright
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* \copyright
* 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.
*
* \see Project Documentation: http://ef.gy/documentation/libefgy
* \see Project Source Code: http://git.becquerel.org/jyujin/libefgy.git
*/
#include <iostream>
#include <ef.gy/vt100.h>
#include <ef.gy/random.h>
#include <chrono>
#include <csignal>
#include <cmath>
#include <sched.h>
using namespace efgy;
using namespace std::chrono;
/**\brief Data and functions of the matrix example programme
*
* Contains global variables and classes used by the 'matrix' demo animation.
* This is a separate namespace to keep things all neat, clean and tidy.
*/
namespace thematrix
{
/**\brief VT100 output buffer
*
* Encapsulates stdio to automatically generate the terminal escape
* sequences to write things at specific positions with specific colours.
*/
terminal::vt100<> output;
/**\brief Random number generator
*
* A seeded instance of the mersenne twister RNG; used to position the
* streams and to add and remove glyphs randomly.
*/
random::mersenneTwister<> rng(1337);
/**\brief Current time
*
* The point in time when processing of the current streams started; used
* to determine when streams should be updated.
*/
system_clock::time_point now;
/**\brief A stream of data
*
* A 'stream' is what I dubbed the individual columns of text in the
* animation. These are generated randomly and they mutate randomly as
* well.
*/
class stream
{
public:
/**\brief A single glyph in a stream
*
* To create the animation, each of the glyphs in the output needs
* to be tagges with the time it was created, in order to know
* which colour to draw the glyph in.
*/
class cell
{
public:
cell(const unsigned long &pCharacter)
: character(pCharacter), created(now) {}
unsigned long character;
system_clock::time_point created;
};
stream(const std::size_t &pLine, const std::size_t &pColumn)
: line(pLine), column(pColumn), last(now), doDelete(false) {}
std::size_t line;
std::size_t column;
std::vector<cell> data;
system_clock::time_point last;
bool doDelete;
bool update (void)
{
if ((now - last) > std::chrono::milliseconds(10))
{
last = now;
switch (rng() % 3)
{
case 0:
if (data.size() > 0)
{
data.erase(data.begin() + (rng() % data.size()));
break;
}
default:
data.push_back(cell(rng() % (1 << 7)));
}
}
std::array<std::size_t,2> s = output.size();
if (data.size() > (s[1]/2))
{
if (line < s[1])
{
if (rng() % 5 == 0)
{
output.target[line][column].content = ' ';
line++;
}
}
else
{
doDelete = true;
}
data.erase(data.begin());
}
int i = line;
for (cell &d : data)
{
if (i >= s[1])
{
break;
}
output.target[i][column].content = d.character;
output.target[i][column].foregroundColour = (now - d.created) > std::chrono::milliseconds(120) ? 2 : 7;
output.target[i][column].backgroundColour = 0;
i++;
}
return true;
}
};
void handle_interrupt(int signal)
{
exit(1);
}
terminal::cell<long> postProcess
(const terminal::terminal<long>&t,
const std::size_t &l,
const std::size_t &c)
{
terminal::cell<long> rv = t.target[l][c];
rv.content = rv.content == 0 ? ' ' : rv.content;
rv.foregroundColour = rv.foregroundColour == 7 ? 7 : 2;
rv.backgroundColour = 0;
return rv;
}
terminal::cell<long> postProcessPolar
(const terminal::terminal<long>&t,
const std::size_t &pl,
const std::size_t &pc)
{
double l = pl;
double c = pc;
std::array<std::size_t,2> s = t.size();
double hl = s[1]/2;
double hc = s[0]/2;
double loff = l - hl;
double coff = c - hc;
double r2 = loff*loff + coff*coff;
double r = std::sqrt(r2);
l = hl + loff + std::sin(r) * 1.0;
c = hc + coff + std::cos(r) * 1.0;
const std::size_t tl = (std::size_t)l < s[1] ? (std::size_t)l : (s[1] - 1);
const std::size_t tc = (std::size_t)c < s[0] ? (std::size_t)c : (s[0] - 1);
terminal::cell<long> rv = t.target[tl][tc];
terminal::cell<long> cv = t.current[tl][tc];
rv.content = rv.content == 0 ? (cv.content == 0 ? ' ' : cv.content) : rv.content;
rv.foregroundColour = rv.foregroundColour == 7 ? 7 : 2;
rv.backgroundColour = 0;
return rv;
}
};
using namespace thematrix;
int main (int argc, char **argv)
{
output.resize(output.getOSDimensions());
std::array<std::size_t,2> s = output.size();
std::size_t i;
std::vector<stream> streams;
std::signal(SIGINT, handle_interrupt);
while (1)
{
i++;
now = system_clock::now();
if ((streams.size() <= 100) && (i % 50 == 0))
{
std::size_t l = rng() % (s[1] / 3);
std::size_t c = rng() % s[0];
streams.push_back(stream(l, c));
}
for (stream &s : streams)
{
s.update();
}
for (unsigned int i = 0; i < streams.size(); i++)
{
if (streams[i].doDelete)
{
streams.erase(streams.begin() + i);
}
}
if (output.flush(postProcess) == 0)
{
sched_yield();
}
}
while ((i = output.flush(postProcess)) > 0);
return 0;
}
<|endoftext|>
|
<commit_before>#include "OrientationSensorsWrapper.h"
#include "SDLogDriver.h"
#include "DualEncoderDriver.h"
#include "MotorDriver.h"
#include "PlanarAccelerationModule.h"
#include "TireContactModule.h"
#include "FrontLiftedDetection.h"
#include "constants.h"
#include <Wire.h>
#include <SD.h>
enum {
WAITING_FOR_COMMAND,
PREPARE_TO_FIGHT,
IN_COMBAT,
RECALIBRATE,
BRAINDEAD,
TEST
} robot_state = WAITING_FOR_COMMAND;
uint32_t prepare_micros;
void log_info()
{
log_data_pack.timestamp = millis();
log_data_pack.acc_x = position.getAccX();
log_data_pack.acc_y = position.getAccY();
log_data_pack.acc_z = position.getAccZ();
log_data_pack.gyro_x = position.getGyroX();
log_data_pack.gyro_y = position.getGyroY();
log_data_pack.gyro_z = position.getGyroZ();
log_data_pack.ahrs_x = position.getRoll();
log_data_pack.ahrs_y = position.getPitch();
log_data_pack.ahrs_z = position.getYaw();
log_data_pack.leftSpeed = leftEncoder.getSpeed();
log_data_pack.rightSpeed = rightEncoder.getSpeed();
logDataPack();
}
void setup()
{
Serial.begin(115200);
SD.begin(4);
initLogger();
initDualEncoders();
initMotors();
pinMode(LEFT_SENSOR_PIN, INPUT);
pinMode(RIGHT_SENSOR_PIN, INPUT);
Wire.begin();
Wire.setClock(400000);
position.init();
tiresContactInit(TIRE_LOST_OF_CONTACT_DEGREES);
initFrontLifted(FRONT_LIFTED_THRESHOLD);
}
void serialCommand()
{
static int left = 0;
static int right = 0;
if(Serial.available() == 0) return;
char cmd = Serial.read();
if(cmd == 'l')
{
left = 0;
if(Serial.available() > 0)
{
char dir = Serial.read();
while(Serial.available() > 0)
{
char digit = Serial.read();
left = left * 10 + (digit - '0');
}
if(dir == '-') left = -left;
}
setMotors(left, right);
}
else if(cmd == 'r')
{
right = 0;
if(Serial.available() > 0)
{
char dir = Serial.read();
while(Serial.available() > 0)
{
char digit = Serial.read();
right = right * 10 + (digit - '0');
}
if(dir == '-') right = -right;
}
setMotors(left, right);
}
else if(cmd == 'd')
{
dumpLog();
}
}
void readProximitySensors(int& left, int& right)
{
left = digitalRead(LEFT_SENSOR_PIN) ^ 1;
right = digitalRead(RIGHT_SENSOR_PIN) ^ 1;
}
void getCommand()
{
static int left = 0;
static int right = 0;
static int last_left = 0;
static int last_right = 0;
static int command_counter = 0;
readProximitySensors(left, right);
if(robot_state == WAITING_FOR_COMMAND)
{
if(right)
{
if(left > last_left)
{
++command_counter;
Serial.print("Command counter: ");
Serial.println(command_counter);
}
}
else if(right < last_right)
{
switch(command_counter)
{
case 0:
robot_state = PREPARE_TO_FIGHT;
prepare_micros = micros();
break;
case 1:
robot_state = RECALIBRATE;
position.calibrate();
plannarAcceleration.calibrate();
robot_state = WAITING_FOR_COMMAND;
break;
case 2:
robot_state = TEST;
setMotors(80, 80);
break;
}
command_counter = 0;
}
}
else if(left && right)
{
if(robot_state == PREPARE_TO_FIGHT)
robot_state = WAITING_FOR_COMMAND;
else
{
robot_state = BRAINDEAD;
setMotors(0, 0);
}
}
last_left = left;
last_right = right;
}
void loop()
{
static uint32_t last_sample_micros = 0;
static uint32_t last_log_micros = 0;
static uint32_t last_blink_micros = 0;
uint32_t current_micros = micros();
{ // blink control
uint32_t full_cycle;
uint32_t high_cycle;
if(robot_state == BRAINDEAD)
{
full_cycle = MICROS_PER_SECOND * 2;
high_cycle = MICROS_PER_SECOND;
}
else if(robot_state == PREPARE_TO_FIGHT)
{
full_cycle = MICROS_PER_SECOND / 10;
high_cycle = MICROS_PER_SECOND / 20;
}
else
{
full_cycle = MICROS_PER_SECOND / 2;
high_cycle = MICROS_PER_SECOND / 3;
}
if(current_micros - last_blink_micros >= full_cycle)
{
digitalWrite(LED_PIN, HIGH);
last_blink_micros = current_micros;
}
else if(current_micros - last_blink_micros >= high_cycle)
{
digitalWrite(LED_PIN, LOW);
}
}
if(robot_state == BRAINDEAD)
{
setMotors(0, 0);
return;
}
if(robot_state == PREPARE_TO_FIGHT)
{
if(current_micros - prepare_micros >= MICROS_PER_SECOND * 5)
{
robot_state = IN_COMBAT;
}
}
// Read sensors
if(current_micros - last_sample_micros >= MICROS_PER_SECOND / SAMPLE_FREQUENCY)
{
position.read_sensors();
getCommand();
last_sample_micros = current_micros;
}
// Log data
if(current_micros - last_log_micros >= MICROS_PER_SECOND / LOG_FREQUENCY)
{
log_info();
last_log_micros = current_micros;
Serial.print(getLeftTireContactState()); Serial.print(" ");
Serial.print(getRightTireContactState()); Serial.print(" ");
Serial.print(getFrontLiftedState()); Serial.println("");
}
serialCommand();
}
<commit_msg>Improve serial commands for motors<commit_after>#include "OrientationSensorsWrapper.h"
#include "SDLogDriver.h"
#include "DualEncoderDriver.h"
#include "MotorDriver.h"
#include "PlanarAccelerationModule.h"
#include "TireContactModule.h"
#include "FrontLiftedDetection.h"
#include "constants.h"
#include <Wire.h>
#include <SD.h>
enum {
WAITING_FOR_COMMAND,
PREPARE_TO_FIGHT,
IN_COMBAT,
RECALIBRATE,
BRAINDEAD,
TEST
} robot_state = WAITING_FOR_COMMAND;
uint32_t prepare_micros;
void log_info()
{
log_data_pack.timestamp = millis();
log_data_pack.acc_x = position.getAccX();
log_data_pack.acc_y = position.getAccY();
log_data_pack.acc_z = position.getAccZ();
log_data_pack.gyro_x = position.getGyroX();
log_data_pack.gyro_y = position.getGyroY();
log_data_pack.gyro_z = position.getGyroZ();
log_data_pack.ahrs_x = position.getRoll();
log_data_pack.ahrs_y = position.getPitch();
log_data_pack.ahrs_z = position.getYaw();
log_data_pack.leftSpeed = leftEncoder.getSpeed();
log_data_pack.rightSpeed = rightEncoder.getSpeed();
logDataPack();
}
void setup()
{
Serial.begin(115200);
SD.begin(4);
initLogger();
initDualEncoders();
initMotors();
pinMode(LEFT_SENSOR_PIN, INPUT);
pinMode(RIGHT_SENSOR_PIN, INPUT);
Wire.begin();
Wire.setClock(400000);
position.init();
tiresContactInit(TIRE_LOST_OF_CONTACT_DEGREES);
initFrontLifted(FRONT_LIFTED_THRESHOLD);
}
void serialCommand()
{
static int left = 0;
static int right = 0;
if(Serial.available() == 0) return;
char cmd = Serial.read();
if(cmd == 'l')
{
left = 0;
if(Serial.available() > 0)
{
int dir = 1;
if(Serial.peek() == '-')
{
dir = -1;
Serial.read();
}
while(Serial.available() > 0)
{
char digit = Serial.read();
left = left * 10 + (digit - '0');
}
left *= dir;
}
setMotors(left, right);
}
else if(cmd == 'r')
{
right = 0;
if(Serial.available() > 0)
{
int dir = 1;
if(Serial.peek() == '-')
{
dir = -1;
Serial.read();
}
while(Serial.available() > 0)
{
char digit = Serial.read();
right = right * 10 + (digit - '0');
}
right *= dir;
}
setMotors(left, right);
}
else if(cmd == 'd')
{
dumpLog();
}
}
void readProximitySensors(int& left, int& right)
{
left = digitalRead(LEFT_SENSOR_PIN) ^ 1;
right = digitalRead(RIGHT_SENSOR_PIN) ^ 1;
}
void getCommand()
{
static int left = 0;
static int right = 0;
static int last_left = 0;
static int last_right = 0;
static int command_counter = 0;
readProximitySensors(left, right);
if(robot_state == WAITING_FOR_COMMAND)
{
if(right)
{
if(left > last_left)
{
++command_counter;
Serial.print("Command counter: ");
Serial.println(command_counter);
}
}
else if(right < last_right)
{
switch(command_counter)
{
case 0:
robot_state = PREPARE_TO_FIGHT;
prepare_micros = micros();
break;
case 1:
robot_state = RECALIBRATE;
position.calibrate();
plannarAcceleration.calibrate();
robot_state = WAITING_FOR_COMMAND;
break;
case 2:
robot_state = TEST;
setMotors(80, 80);
break;
}
command_counter = 0;
}
}
else if(left && right)
{
if(robot_state == PREPARE_TO_FIGHT)
robot_state = WAITING_FOR_COMMAND;
else
{
robot_state = BRAINDEAD;
setMotors(0, 0);
}
}
last_left = left;
last_right = right;
}
void loop()
{
static uint32_t last_sample_micros = 0;
static uint32_t last_log_micros = 0;
static uint32_t last_blink_micros = 0;
uint32_t current_micros = micros();
{ // blink control
uint32_t full_cycle;
uint32_t high_cycle;
if(robot_state == BRAINDEAD)
{
full_cycle = MICROS_PER_SECOND * 2;
high_cycle = MICROS_PER_SECOND;
}
else if(robot_state == PREPARE_TO_FIGHT)
{
full_cycle = MICROS_PER_SECOND / 10;
high_cycle = MICROS_PER_SECOND / 20;
}
else
{
full_cycle = MICROS_PER_SECOND / 2;
high_cycle = MICROS_PER_SECOND / 3;
}
if(current_micros - last_blink_micros >= full_cycle)
{
digitalWrite(LED_PIN, HIGH);
last_blink_micros = current_micros;
}
else if(current_micros - last_blink_micros >= high_cycle)
{
digitalWrite(LED_PIN, LOW);
}
}
if(robot_state == BRAINDEAD)
{
setMotors(0, 0);
return;
}
if(robot_state == PREPARE_TO_FIGHT)
{
if(current_micros - prepare_micros >= MICROS_PER_SECOND * 5)
{
robot_state = IN_COMBAT;
}
}
// Read sensors
if(current_micros - last_sample_micros >= MICROS_PER_SECOND / SAMPLE_FREQUENCY)
{
position.read_sensors();
getCommand();
last_sample_micros = current_micros;
}
// Log data
if(current_micros - last_log_micros >= MICROS_PER_SECOND / LOG_FREQUENCY)
{
log_info();
last_log_micros = current_micros;
Serial.print(getLeftTireContactState()); Serial.print(" ");
Serial.print(getRightTireContactState()); Serial.print(" ");
Serial.print(getFrontLiftedState()); Serial.println("");
}
serialCommand();
}
<|endoftext|>
|
<commit_before>#include "packer.hpp"
namespace vg {
Packer::Packer(void) : xgidx(nullptr) { }
Packer::Packer(xg::XG* xidx, size_t binsz) : xgidx(xidx), bin_size(binsz) {
coverage_dynamic = gcsa::CounterArray(xgidx->seq_length, 8);
if (binsz) n_bins = xgidx->seq_length / bin_size + 1;
}
Packer::~Packer(void) {
close_edit_tmpfiles();
remove_edit_tmpfiles();
}
void Packer::load_from_file(const string& file_name) {
ifstream in(file_name);
load(in);
}
void Packer::save_to_file(const string& file_name) {
ofstream out(file_name);
serialize(out);
}
void Packer::load(istream& in) {
sdsl::read_member(bin_size, in);
sdsl::read_member(n_bins, in);
coverage_civ.load(in);
edit_csas.resize(n_bins);
for (size_t i = 0; i < n_bins; ++i) {
edit_csas[i].load(in);
}
// We can only load compacted.
is_compacted = true;
}
void Packer::merge_from_files(const vector<string>& file_names) {
#ifdef debug
cerr << "Merging " << file_names.size() << " pack files" << endl;
#endif
// load into our dynamic structures, then compact
bool first = true;
for (auto& file_name : file_names) {
Packer c;
ifstream f(file_name);
c.load(f);
// take bin size and counts from the first, assume they are all the same
if (first) {
bin_size = c.get_bin_size();
n_bins = c.get_n_bins();
ensure_edit_tmpfiles_open();
first = false;
} else {
assert(bin_size == c.get_bin_size());
assert(n_bins == c.get_n_bins());
}
c.write_edits(tmpfstreams);
collect_coverage(c);
}
}
void Packer::merge_from_dynamic(vector<Packer*>& packers) {
// load dynamic packs into our dynamic structures, then compact
bool first = true;
for (auto& p : packers) {
auto& c = *p;
c.close_edit_tmpfiles(); // flush and close temporaries
// take bin size and counts from the first, assume they are all the same
if (first) {
bin_size = c.get_bin_size();
n_bins = c.get_n_bins();
ensure_edit_tmpfiles_open();
first = false;
} else {
assert(bin_size == c.get_bin_size());
assert(n_bins == c.get_n_bins());
}
c.write_edits(tmpfstreams);
collect_coverage(c);
}
}
size_t Packer::get_bin_size(void) const {
return bin_size;
}
size_t Packer::get_n_bins(void) const {
return n_bins;
}
size_t Packer::bin_for_position(size_t i) const {
if (bin_size > 0) {
return i / bin_size;
} else {
return 0;
}
}
void Packer::write_edits(vector<ofstream*>& out) const {
for (size_t i = 0; i < n_bins; ++i) {
write_edits(*out[i], i);
}
}
void Packer::write_edits(ostream& out, size_t bin) const {
if (is_compacted) {
out << extract(edit_csas[bin], 0, edit_csas[bin].size()-2) << delim1; // chomp trailing null, add back delim
} else {
// uncompacted, so just cat the edit file for this bin onto out
if (edit_tmpfile_names.size()) {
ifstream edits(edit_tmpfile_names[bin], std::ios_base::binary);
out << edits.rdbuf() << delim1;
}
}
}
void Packer::collect_coverage(const Packer& c) {
// assume the same basis vector
assert(!is_compacted);
for (size_t i = 0; i < c.graph_length(); ++i) {
coverage_dynamic.increment(i, c.coverage_at_position(i));
}
}
size_t Packer::serialize(std::ostream& out,
sdsl::structure_tree_node* s,
std::string name) {
make_compact();
sdsl::structure_tree_node* child = sdsl::structure_tree::add_child(s, name, sdsl::util::class_name(*this));
size_t written = 0;
written += sdsl::write_member(bin_size, out, child, "bin_size_" + name);
written += sdsl::write_member(edit_csas.size(), out, child, "n_bins_" + name);
written += coverage_civ.serialize(out, child, "graph_coverage_" + name);
for (auto& edit_csa : edit_csas) {
written += edit_csa.serialize(out, child, "edit_csa_" + name);
}
sdsl::structure_tree::add_size(child, written);
return written;
}
void Packer::make_compact(void) {
// pack the dynamic countarry and edit coverage into the compact data structure
if (is_compacted) {
#ifdef debug
cerr << "Packer is already compact" << endl;
#endif
return;
} else {
#ifdef debug
cerr << "Need to make packer compact" << endl;
#endif
}
// sync edit file
close_edit_tmpfiles();
// temporaries for construction
size_t basis_length = coverage_dynamic.size();
int_vector<> coverage_iv;
util::assign(coverage_iv, int_vector<>(basis_length));
for (size_t i = 0; i < coverage_dynamic.size(); ++i) {
coverage_iv[i] = coverage_dynamic[i];
}
edit_csas.resize(edit_tmpfile_names.size());
util::assign(coverage_civ, coverage_iv);
construct_config::byte_algo_sa = SE_SAIS;
#pragma omp parallel for
for (size_t i = 0; i < edit_tmpfile_names.size(); ++i) {
construct(edit_csas[i], edit_tmpfile_names[i], 1);
}
// construct the record marker bitvector
remove_edit_tmpfiles();
is_compacted = true;
}
void Packer::make_dynamic(void) {
if (!is_compacted) return;
// unpack the compact represenation into the countarray
assert(false); // not implemented
is_compacted = false;
}
bool Packer::is_dynamic(void) {
return !is_compacted;
}
void Packer::ensure_edit_tmpfiles_open(void) {
if (tmpfstreams.empty()) {
string base = "vg-pack_";
string edit_tmpfile_name = tmpfilename(base);
std::remove(edit_tmpfile_name.c_str()); // remove this; we'll use it as a base name
// for as many bins as we have, make a temp file
tmpfstreams.resize(n_bins);
edit_tmpfile_names.resize(n_bins);
for (size_t i = 0; i < n_bins; ++i) {
edit_tmpfile_names[i] = edit_tmpfile_name+"_"+convert(i);
tmpfstreams[i] = new ofstream;
tmpfstreams[i]->open(edit_tmpfile_names[i], std::ios_base::binary);
assert(tmpfstreams[i]->is_open());
}
}
}
void Packer::close_edit_tmpfiles(void) {
if (!tmpfstreams.empty()) {
for (auto& tmpfstream : tmpfstreams) {
*tmpfstream << delim1; // pad
tmpfstream->close();
delete tmpfstream;
}
tmpfstreams.clear();
}
}
void Packer::remove_edit_tmpfiles(void) {
if (!edit_tmpfile_names.empty()) {
for (auto& name : edit_tmpfile_names) {
std::remove(name.c_str());
}
edit_tmpfile_names.clear();
}
}
void Packer::add(const Alignment& aln, bool record_edits) {
// open tmpfile if needed
ensure_edit_tmpfiles_open();
// count the nodes, edges, and edits
for (auto& mapping : aln.path().mapping()) {
if (!mapping.has_position()) {
#ifdef debug
cerr << "Mapping has no position" << endl;
#endif
continue;
}
size_t i = position_in_basis(mapping.position());
for (auto& edit : mapping.edit()) {
if (edit_is_match(edit)) {
#ifdef debug
cerr << "Recording a match" << endl;
#endif
if (mapping.position().is_reverse()) {
for (size_t j = 0; j < edit.from_length(); ++j) {
coverage_dynamic.increment(i-j);
}
} else {
for (size_t j = 0; j < edit.from_length(); ++j) {
coverage_dynamic.increment(i+j);
}
}
} else if (record_edits) {
// we represent things on the forward strand
string pos_repr = pos_key(i);
string edit_repr = edit_value(edit, mapping.position().is_reverse());
size_t bin = bin_for_position(i);
*tmpfstreams[bin] << pos_repr << edit_repr;
}
if (mapping.position().is_reverse()) {
i -= edit.from_length();
} else {
i += edit.from_length();
}
}
}
}
// find the position on the forward strand in the sequence vector
size_t Packer::position_in_basis(const Position& pos) const {
// get position on the forward strand
if (pos.is_reverse()) {
return (int64_t)xg_node_start(pos.node_id(), xgidx)
+ (int64_t)reverse(pos, xg_node_length(pos.node_id(), xgidx)).offset() - 1;
} else {
return (int64_t)xg_node_start(pos.node_id(), xgidx) + (int64_t)pos.offset();
}
}
string Packer::pos_key(size_t i) const {
Position pos;
size_t offset = 2;
pos.set_node_id(i+offset);
string pos_repr;
pos.SerializeToString(&pos_repr);
stringstream s;
s << delim1 << delim2 << delim1 << escape_delims(pos_repr);
return s.str();
}
string Packer::edit_value(const Edit& edit, bool revcomp) const {
string edit_repr;
if (revcomp) {
reverse_complement_edit(edit).SerializeToString(&edit_repr);
} else {
edit.SerializeToString(&edit_repr);
}
stringstream s;
s << delim1 << escape_delims(edit_repr);
return s.str();
}
string Packer::escape_delims(const string& s) const {
return escape_delim(escape_delim(s, delim1), delim2);
}
string Packer::unescape_delims(const string& s) const {
return unescape_delim(unescape_delim(s, delim1), delim2);
}
string Packer::escape_delim(const string& s, char d) const {
string escaped; escaped.reserve(s.size());
for (size_t i = 0; i < s.size(); ++i) {
char c = s[i];
escaped.push_back(c);
if (c == d) escaped.push_back(c);
}
return escaped;
}
string Packer::unescape_delim(const string& s, char d) const {
string unescaped; unescaped.reserve(s.size());
for (size_t i = 0; i < s.size()-1; ++i) {
char c = s[i];
char b = s[i+1];
if (c == d && b == d) {
unescaped.push_back(c);
} else {
unescaped.push_back(c);
if (i == s.size()-2) unescaped.push_back(b);
}
}
return unescaped;
}
size_t Packer::graph_length(void) const {
if (is_compacted) {
return coverage_civ.size();
} else {
return coverage_dynamic.size();
}
}
size_t Packer::coverage_at_position(size_t i) const {
if (is_compacted) {
return coverage_civ[i];
} else {
return coverage_dynamic[i];
}
}
vector<Edit> Packer::edits_at_position(size_t i) const {
vector<Edit> edits;
if (i == 0) return edits;
string key = pos_key(i);
size_t bin = bin_for_position(i);
auto& edit_csa = edit_csas[bin];
auto occs = locate(edit_csa, key);
for (size_t i = 0; i < occs.size(); ++i) {
// walk from after the key and delim1 to the next end-sep
size_t b = occs[i] + key.size() + 1;
size_t e = b;
// look for an odd number of delims
// run until we find a delim
while (true) {
while (extract(edit_csa, e, e)[0] != delim1) ++e;
// now we are matching the delim... count them
size_t f = e;
while (extract(edit_csa, f, f)[0] == delim1) ++f;
size_t c = f - e;
e = f; // set pointer to last delim
if (c % 2 != 0) {
break;
}
}
string value = unescape_delims(extract(edit_csa, b, e));
Edit edit;
edit.ParseFromString(value);
edits.push_back(edit);
}
return edits;
}
ostream& Packer::as_table(ostream& out, bool show_edits) {
#ifdef debug
cerr << "Packer table of " << coverage_civ.size() << " rows:" << endl;
#endif
out << "seq.pos" << "\t"
<< "node.id" << "\t"
<< "node.offset" << "\t"
<< "coverage";
if (show_edits) out << "\t" << "edits";
out << endl;
// write the coverage as a vector
for (size_t i = 0; i < coverage_civ.size(); ++i) {
id_t node_id = xgidx->node_at_seq_pos(i+1);
size_t offset = i - xgidx->node_start(node_id);
out << i << "\t" << node_id << "\t" << offset << "\t" << coverage_civ[i];
if (show_edits) {
out << "\t" << count(edit_csas[bin_for_position(i)], pos_key(i));
for (auto& edit : edits_at_position(i)) out << " " << pb2json(edit);
}
out << endl;
}
}
ostream& Packer::show_structure(ostream& out) {
out << coverage_civ << endl; // graph coverage (compacted coverage_dynamic)
for (auto& edit_csa : edit_csas) {
out << edit_csa << endl;
}
//out << " i SA ISA PSI LF BWT T[SA[i]..SA[i]-1]" << endl;
//csXprintf(cout, "%2I %2S %3s %3P %2p %3B %:3T", edit_csa);
return out;
}
}
<commit_msg>resolve #1510<commit_after>#include "packer.hpp"
namespace vg {
Packer::Packer(void) : xgidx(nullptr) { }
Packer::Packer(xg::XG* xidx, size_t binsz) : xgidx(xidx), bin_size(binsz) {
coverage_dynamic = gcsa::CounterArray(xgidx->seq_length, 8);
if (binsz) n_bins = xgidx->seq_length / bin_size + 1;
}
Packer::~Packer(void) {
close_edit_tmpfiles();
remove_edit_tmpfiles();
}
void Packer::load_from_file(const string& file_name) {
ifstream in(file_name);
load(in);
}
void Packer::save_to_file(const string& file_name) {
ofstream out(file_name);
serialize(out);
}
void Packer::load(istream& in) {
sdsl::read_member(bin_size, in);
sdsl::read_member(n_bins, in);
coverage_civ.load(in);
edit_csas.resize(n_bins);
for (size_t i = 0; i < n_bins; ++i) {
edit_csas[i].load(in);
}
// We can only load compacted.
is_compacted = true;
}
void Packer::merge_from_files(const vector<string>& file_names) {
#ifdef debug
cerr << "Merging " << file_names.size() << " pack files" << endl;
#endif
// load into our dynamic structures, then compact
bool first = true;
for (auto& file_name : file_names) {
Packer c;
ifstream f(file_name);
c.load(f);
// take bin size and counts from the first, assume they are all the same
if (first) {
bin_size = c.get_bin_size();
n_bins = c.get_n_bins();
ensure_edit_tmpfiles_open();
first = false;
} else {
assert(bin_size == c.get_bin_size());
assert(n_bins == c.get_n_bins());
}
c.write_edits(tmpfstreams);
collect_coverage(c);
}
}
void Packer::merge_from_dynamic(vector<Packer*>& packers) {
// load dynamic packs into our dynamic structures, then compact
bool first = true;
for (auto& p : packers) {
auto& c = *p;
c.close_edit_tmpfiles(); // flush and close temporaries
// take bin size and counts from the first, assume they are all the same
if (first) {
bin_size = c.get_bin_size();
n_bins = c.get_n_bins();
ensure_edit_tmpfiles_open();
first = false;
} else {
assert(bin_size == c.get_bin_size());
assert(n_bins == c.get_n_bins());
}
c.write_edits(tmpfstreams);
collect_coverage(c);
}
}
size_t Packer::get_bin_size(void) const {
return bin_size;
}
size_t Packer::get_n_bins(void) const {
return n_bins;
}
size_t Packer::bin_for_position(size_t i) const {
if (bin_size > 0) {
return i / bin_size;
} else {
return 0;
}
}
void Packer::write_edits(vector<ofstream*>& out) const {
for (size_t i = 0; i < n_bins; ++i) {
write_edits(*out[i], i);
}
}
void Packer::write_edits(ostream& out, size_t bin) const {
if (is_compacted) {
out << extract(edit_csas[bin], 0, edit_csas[bin].size()-2) << delim1; // chomp trailing null, add back delim
} else {
// uncompacted, so just cat the edit file for this bin onto out
if (edit_tmpfile_names.size()) {
ifstream edits(edit_tmpfile_names[bin], std::ios_base::binary);
out << edits.rdbuf() << delim1;
}
}
}
void Packer::collect_coverage(const Packer& c) {
// assume the same basis vector
assert(!is_compacted);
for (size_t i = 0; i < c.graph_length(); ++i) {
coverage_dynamic.increment(i, c.coverage_at_position(i));
}
}
size_t Packer::serialize(std::ostream& out,
sdsl::structure_tree_node* s,
std::string name) {
make_compact();
sdsl::structure_tree_node* child = sdsl::structure_tree::add_child(s, name, sdsl::util::class_name(*this));
size_t written = 0;
written += sdsl::write_member(bin_size, out, child, "bin_size_" + name);
written += sdsl::write_member(edit_csas.size(), out, child, "n_bins_" + name);
written += coverage_civ.serialize(out, child, "graph_coverage_" + name);
for (auto& edit_csa : edit_csas) {
written += edit_csa.serialize(out, child, "edit_csa_" + name);
}
sdsl::structure_tree::add_size(child, written);
return written;
}
void Packer::make_compact(void) {
// pack the dynamic countarry and edit coverage into the compact data structure
if (is_compacted) {
#ifdef debug
cerr << "Packer is already compact" << endl;
#endif
return;
} else {
#ifdef debug
cerr << "Need to make packer compact" << endl;
#endif
}
// sync edit file
close_edit_tmpfiles();
// temporaries for construction
size_t basis_length = coverage_dynamic.size();
int_vector<> coverage_iv;
util::assign(coverage_iv, int_vector<>(basis_length));
for (size_t i = 0; i < coverage_dynamic.size(); ++i) {
coverage_iv[i] = coverage_dynamic[i];
}
edit_csas.resize(edit_tmpfile_names.size());
util::assign(coverage_civ, coverage_iv);
construct_config::byte_algo_sa = SE_SAIS;
#pragma omp parallel for
for (size_t i = 0; i < edit_tmpfile_names.size(); ++i) {
construct(edit_csas[i], edit_tmpfile_names[i], 1);
}
// construct the record marker bitvector
remove_edit_tmpfiles();
is_compacted = true;
}
void Packer::make_dynamic(void) {
if (!is_compacted) return;
// unpack the compact represenation into the countarray
assert(false); // not implemented
is_compacted = false;
}
bool Packer::is_dynamic(void) {
return !is_compacted;
}
void Packer::ensure_edit_tmpfiles_open(void) {
if (tmpfstreams.empty()) {
string base = "vg-pack_";
string edit_tmpfile_name = tmpfilename(base);
std::remove(edit_tmpfile_name.c_str()); // remove this; we'll use it as a base name
// for as many bins as we have, make a temp file
tmpfstreams.resize(n_bins);
edit_tmpfile_names.resize(n_bins);
for (size_t i = 0; i < n_bins; ++i) {
edit_tmpfile_names[i] = edit_tmpfile_name+"_"+convert(i);
tmpfstreams[i] = new ofstream;
tmpfstreams[i]->open(edit_tmpfile_names[i], std::ios_base::binary);
assert(tmpfstreams[i]->is_open());
}
}
}
void Packer::close_edit_tmpfiles(void) {
if (!tmpfstreams.empty()) {
for (auto& tmpfstream : tmpfstreams) {
*tmpfstream << delim1; // pad
tmpfstream->close();
delete tmpfstream;
}
tmpfstreams.clear();
}
}
void Packer::remove_edit_tmpfiles(void) {
if (!edit_tmpfile_names.empty()) {
for (auto& name : edit_tmpfile_names) {
std::remove(name.c_str());
}
edit_tmpfile_names.clear();
}
}
void Packer::add(const Alignment& aln, bool record_edits) {
// open tmpfile if needed
ensure_edit_tmpfiles_open();
// count the nodes, edges, and edits
for (auto& mapping : aln.path().mapping()) {
if (!mapping.has_position()) {
#ifdef debug
cerr << "Mapping has no position" << endl;
#endif
continue;
}
// skip nodes outside of our graph, assuming this may be a subgraph
if (!xgidx->has_node(mapping.position().node_id())) {
continue;
}
size_t i = position_in_basis(mapping.position());
for (auto& edit : mapping.edit()) {
if (edit_is_match(edit)) {
#ifdef debug
cerr << "Recording a match" << endl;
#endif
if (mapping.position().is_reverse()) {
for (size_t j = 0; j < edit.from_length(); ++j) {
coverage_dynamic.increment(i-j);
}
} else {
for (size_t j = 0; j < edit.from_length(); ++j) {
coverage_dynamic.increment(i+j);
}
}
} else if (record_edits) {
// we represent things on the forward strand
string pos_repr = pos_key(i);
string edit_repr = edit_value(edit, mapping.position().is_reverse());
size_t bin = bin_for_position(i);
*tmpfstreams[bin] << pos_repr << edit_repr;
}
if (mapping.position().is_reverse()) {
i -= edit.from_length();
} else {
i += edit.from_length();
}
}
}
}
// find the position on the forward strand in the sequence vector
size_t Packer::position_in_basis(const Position& pos) const {
// get position on the forward strand
if (pos.is_reverse()) {
return (int64_t)xg_node_start(pos.node_id(), xgidx)
+ (int64_t)reverse(pos, xg_node_length(pos.node_id(), xgidx)).offset() - 1;
} else {
return (int64_t)xg_node_start(pos.node_id(), xgidx) + (int64_t)pos.offset();
}
}
string Packer::pos_key(size_t i) const {
Position pos;
size_t offset = 2;
pos.set_node_id(i+offset);
string pos_repr;
pos.SerializeToString(&pos_repr);
stringstream s;
s << delim1 << delim2 << delim1 << escape_delims(pos_repr);
return s.str();
}
string Packer::edit_value(const Edit& edit, bool revcomp) const {
string edit_repr;
if (revcomp) {
reverse_complement_edit(edit).SerializeToString(&edit_repr);
} else {
edit.SerializeToString(&edit_repr);
}
stringstream s;
s << delim1 << escape_delims(edit_repr);
return s.str();
}
string Packer::escape_delims(const string& s) const {
return escape_delim(escape_delim(s, delim1), delim2);
}
string Packer::unescape_delims(const string& s) const {
return unescape_delim(unescape_delim(s, delim1), delim2);
}
string Packer::escape_delim(const string& s, char d) const {
string escaped; escaped.reserve(s.size());
for (size_t i = 0; i < s.size(); ++i) {
char c = s[i];
escaped.push_back(c);
if (c == d) escaped.push_back(c);
}
return escaped;
}
string Packer::unescape_delim(const string& s, char d) const {
string unescaped; unescaped.reserve(s.size());
for (size_t i = 0; i < s.size()-1; ++i) {
char c = s[i];
char b = s[i+1];
if (c == d && b == d) {
unescaped.push_back(c);
} else {
unescaped.push_back(c);
if (i == s.size()-2) unescaped.push_back(b);
}
}
return unescaped;
}
size_t Packer::graph_length(void) const {
if (is_compacted) {
return coverage_civ.size();
} else {
return coverage_dynamic.size();
}
}
size_t Packer::coverage_at_position(size_t i) const {
if (is_compacted) {
return coverage_civ[i];
} else {
return coverage_dynamic[i];
}
}
vector<Edit> Packer::edits_at_position(size_t i) const {
vector<Edit> edits;
if (i == 0) return edits;
string key = pos_key(i);
size_t bin = bin_for_position(i);
auto& edit_csa = edit_csas[bin];
auto occs = locate(edit_csa, key);
for (size_t i = 0; i < occs.size(); ++i) {
// walk from after the key and delim1 to the next end-sep
size_t b = occs[i] + key.size() + 1;
size_t e = b;
// look for an odd number of delims
// run until we find a delim
while (true) {
while (extract(edit_csa, e, e)[0] != delim1) ++e;
// now we are matching the delim... count them
size_t f = e;
while (extract(edit_csa, f, f)[0] == delim1) ++f;
size_t c = f - e;
e = f; // set pointer to last delim
if (c % 2 != 0) {
break;
}
}
string value = unescape_delims(extract(edit_csa, b, e));
Edit edit;
edit.ParseFromString(value);
edits.push_back(edit);
}
return edits;
}
ostream& Packer::as_table(ostream& out, bool show_edits) {
#ifdef debug
cerr << "Packer table of " << coverage_civ.size() << " rows:" << endl;
#endif
out << "seq.pos" << "\t"
<< "node.id" << "\t"
<< "node.offset" << "\t"
<< "coverage";
if (show_edits) out << "\t" << "edits";
out << endl;
// write the coverage as a vector
for (size_t i = 0; i < coverage_civ.size(); ++i) {
id_t node_id = xgidx->node_at_seq_pos(i+1);
size_t offset = i - xgidx->node_start(node_id);
out << i << "\t" << node_id << "\t" << offset << "\t" << coverage_civ[i];
if (show_edits) {
out << "\t" << count(edit_csas[bin_for_position(i)], pos_key(i));
for (auto& edit : edits_at_position(i)) out << " " << pb2json(edit);
}
out << endl;
}
}
ostream& Packer::show_structure(ostream& out) {
out << coverage_civ << endl; // graph coverage (compacted coverage_dynamic)
for (auto& edit_csa : edit_csas) {
out << edit_csa << endl;
}
//out << " i SA ISA PSI LF BWT T[SA[i]..SA[i]-1]" << endl;
//csXprintf(cout, "%2I %2S %3s %3P %2p %3B %:3T", edit_csa);
return out;
}
}
<|endoftext|>
|
<commit_before>#include "../include/parser.h"
#include "../include/exceptions.h"
#define IGNORE_PARSE_ERROR(FUN, ARG)\
try \
{ \
return FUN(ARG); \
} \
catch (ParseError e) \
{ \
\
} \
inline char get_char(FileCursor& cursor)
{
char c = cursor.get();
if (cursor.eof())
throw ParseError();
return c;
}
// sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
// / "*" / "+" / "," / ";" / "="
FileCursor parse_sub_delims(FileCursor cursor)
{
char c = get_char(cursor);
if(c == '!' || c == '$' || c == '&' || c == '\'' || c == '(' || c == ')' ||
c == '*' || c == '+' || c == ',' || c == ';' || c == '=')
return cursor;
else
throw ParseError();
}
// gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"
FileCursor parse_gen_delims(FileCursor cursor)
{
char c = get_char(cursor);
if (c == ':' || c == '/' || c == '?' || c == '#' || c == '[' || c == ']' ||
c =='@')
return cursor;
else
throw ParseError();
}
// reserved = gen-delims / sub-delims
FileCursor parse_reserved(FileCursor cursor)
{
IGNORE_PARSE_ERROR(parse_gen_delims, cursor);
IGNORE_PARSE_ERROR(parse_sub_delims, cursor);
throw ParseError();
}
FileCursor parse_alpha(FileCursor cursor)
{
char c = get_char(cursor);
if(('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z'))
return cursor;
else
throw ParseError();
}
FileCursor parse_digit(FileCursor cursor)
{
char c = get_char(cursor);
if('0' <= c && c <= '9')
return cursor;
else
throw ParseError();
}
// unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
FileCursor parse_unreserved(FileCursor cursor)
{
IGNORE_PARSE_ERROR(parse_alpha, cursor);
IGNORE_PARSE_ERROR(parse_digit, cursor);
char c = get_char(cursor);
if (c == '-' || c == '.' || c == '_' || c == '~')
return cursor;
else
throw ParseError();
}
// hexdigit = DIGIT / 'A' - 'F' / 'a' - 'f'
FileCursor parse_hexdigit(FileCursor cursor)
{
IGNORE_PARSE_ERROR(parse_digit, cursor);
char c = get_char(cursor);
if(('A' <= c && c <= 'F') || ('a' <= c && c <= 'f'))
return cursor;
throw ParseError();
}
// pct-encoded = "%" HEXDIG HEXDIG
FileCursor parse_pct_encoded(FileCursor cursor)
{
char c = get_char(cursor);
if (c != '%')
throw ParseError();
parse_hexdigit(cursor);
return parse_hexdigit(cursor);
}
// pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
FileCursor parse_pchar(FileCursor cursor)
{
IGNORE_PARSE_ERROR(parse_unreserved, cursor);
IGNORE_PARSE_ERROR(parse_pct_encoded, cursor);
IGNORE_PARSE_ERROR(parse_sub_delims, cursor);
char c = get_char(cursor);
if(c == ':' || c == '@')
return cursor;
else
throw ParseError();
}
<commit_msg>Add parser functions.<commit_after>#include "../include/parser.h"
#include "../include/exceptions.h"
#define IGNORE_PARSE_ERROR(FUN, ARG)\
try \
{ \
return FUN(ARG); \
} \
catch (ParseError e) \
{ \
\
} \
#define REPEAT_IGNORING(FUN, ARG) \
while(true) \
{ \
try \
{ \
ARG = FUN(ARG); \
} \
catch(ParseError) \
{ \
return ARG; \
} \
} \
inline char get_char(FileCursor& cursor)
{
char c = cursor.get();
if (cursor.eof())
throw ParseError();
return c;
}
// sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
// / "*" / "+" / "," / ";" / "="
FileCursor parse_sub_delims(FileCursor cursor)
{
char c = get_char(cursor);
if(c == '!' || c == '$' || c == '&' || c == '\'' || c == '(' || c == ')' ||
c == '*' || c == '+' || c == ',' || c == ';' || c == '=')
return cursor;
else
throw ParseError();
}
// gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"
FileCursor parse_gen_delims(FileCursor cursor)
{
char c = get_char(cursor);
if (c == ':' || c == '/' || c == '?' || c == '#' || c == '[' || c == ']' ||
c =='@')
return cursor;
else
throw ParseError();
}
// reserved = gen-delims / sub-delims
FileCursor parse_reserved(FileCursor cursor)
{
IGNORE_PARSE_ERROR(parse_gen_delims, cursor);
IGNORE_PARSE_ERROR(parse_sub_delims, cursor);
throw ParseError();
}
FileCursor parse_alpha(FileCursor cursor)
{
char c = get_char(cursor);
if(('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z'))
return cursor;
else
throw ParseError();
}
FileCursor parse_digit(FileCursor cursor)
{
char c = get_char(cursor);
if('0' <= c && c <= '9')
return cursor;
else
throw ParseError();
}
// unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
FileCursor parse_unreserved(FileCursor cursor)
{
IGNORE_PARSE_ERROR(parse_alpha, cursor);
IGNORE_PARSE_ERROR(parse_digit, cursor);
char c = get_char(cursor);
if (c == '-' || c == '.' || c == '_' || c == '~')
return cursor;
else
throw ParseError();
}
// hexdigit = DIGIT / 'A' - 'F' / 'a' - 'f'
FileCursor parse_hexdigit(FileCursor cursor)
{
IGNORE_PARSE_ERROR(parse_digit, cursor);
char c = get_char(cursor);
if(('A' <= c && c <= 'F') || ('a' <= c && c <= 'f'))
return cursor;
throw ParseError();
}
// pct-encoded = "%" HEXDIG HEXDIG
FileCursor parse_pct_encoded(FileCursor cursor)
{
char c = get_char(cursor);
if (c != '%')
throw ParseError();
parse_hexdigit(cursor);
return parse_hexdigit(cursor);
}
// pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
FileCursor parse_pchar(FileCursor cursor)
{
IGNORE_PARSE_ERROR(parse_unreserved, cursor);
IGNORE_PARSE_ERROR(parse_pct_encoded, cursor);
IGNORE_PARSE_ERROR(parse_sub_delims, cursor);
char c = get_char(cursor);
if(c == ':' || c == '@')
return cursor;
else
throw ParseError();
}
//query_fragment_element = pchar / "/" / "?"
FileCursor parse_query_fragment_element(FileCursor cursor)
{
IGNORE_PARSE_ERROR(parse_pchar, cursor);
char c = get_char(cursor);
if(c == '/' || c == '?')
return cursor;
else
throw ParseError();
}
//query = *query_fragment_element
//fragment = *query_fragment_element
FileCursor parse_query_fragment(FileCursor cursor)
{
REPEAT_IGNORING(parse_query_fragment_element, cursor);
}
// segment_nz_nc_element = unreserved / pct-encoded / sub-delims / "@"
FileCursor parse_segment_nz_nc_element(FileCursor cursor)
{
IGNORE_PARSE_ERROR(parse_unreserved, cursor);
IGNORE_PARSE_ERROR(parse_pct_encoded, cursor);
IGNORE_PARSE_ERROR(parse_sub_delims, cursor);
char c = get_char(cursor);
if (c == '@')
return cursor;
else
throw ParseError();
}
// segment-nz-nc = 1*segment-nz-nc
FileCursor parse_segment_nz_nc(FileCursor cursor)
{
cursor = parse_segment_nz_nc_element(cursor);
REPEAT_IGNORING(parse_segment_nz_nc_element, cursor);
}
// segment = *pchar
FileCursor parse_segment(FileCursor cursor)
{
REPEAT_IGNORING(parse_pchar, cursor);
}
// segment-nz = 1*pchar
FileCursor parse_segment_nz(FileCursor cursor)
{
cursor = parse_pchar(cursor);
REPEAT_IGNORING(parse_pchar, cursor);
}
// slash_segment = '/' segment
FileCursor parse_slash_segment(FileCursor cursor)
{
char c = get_char(cursor);
if (c != '/')
throw ParseError();
else
IGNORE_PARSE_ERROR(parse_segment, cursor);
}
// path-abempty = *( "/" segment )
FileCursor parse_path_abempty(FileCursor cursor)
{
REPEAT_IGNORING(parse_slash_segment, cursor);
}
// path-absolute = "/" [ segment-nz *( "/" segment ) ]
FileCursor parse_path_absolute(FileCursor cursor)
{
char c = get_char(cursor);
if (c != '/')
throw ParseError();
else
{
try
{
FileCursor cursor2(parse_segment_nz(cursor));
REPEAT_IGNORING(parse_slash_segment, cursor2);
}
catch(ParseError)
{
return cursor;
}
}
}
// path-noscheme = segment-nz-nc *( "/" segment )
FileCursor parse_path_noscheme(FileCursor cursor)
{
FileCursor cursor2(parse_segment_nz_nc(cursor));
REPEAT_IGNORING(parse_slash_segment, cursor2);
}
// path-rootless = segment-nz *( "/" segment )
FileCursor parse_path_rootless(FileCursor cursor)
{
FileCursor cursor2(parse_segment_nz(cursor));
REPEAT_IGNORING(parse_slash_segment, cursor2);
}
// path-empty = 0<pchar>
FileCursor parse_path_empty(FileCursor cursor)
{
return cursor;
}
// path = path-abempty ; begins with "/" or is empty
// / path-absolute ; begins with "/" but not "//"
// / path-noscheme ; begins with a non-colon segment
// / path-rootless ; begins with a segment
// / path-empty ; zero characters
FileCursor parse_path(FileCursor cursor)
{
IGNORE_PARSE_ERROR(parse_path_abempty, cursor);
IGNORE_PARSE_ERROR(parse_path_absolute, cursor);
IGNORE_PARSE_ERROR(parse_path_noscheme, cursor);
IGNORE_PARSE_ERROR(parse_path_rootless, cursor);
IGNORE_PARSE_ERROR(parse_path_empty, cursor);
throw ParseError();
}
// 250_255 = "25" 0-5
FileCursor parse_250_255(FileCursor cursor)
{
char c = get_char(cursor);
if (c != '2')
throw ParseError();
c = get_char(cursor);
if (c != '5')
throw ParseError();
c = get_char(cursor);
if ('0' <= c && c <= '5')
return cursor;
else
throw ParseError();
}
// 200_249 = "2" 0-4 DIGIT
FileCursor parse_200_249(FileCursor cursor)
{
char c = get_char(cursor);
if (c != '2')
throw ParseError();
c = get_char(cursor);
if ('0' <= c && c <= '4')
{
return parse_digit(cursor);
}
else
throw ParseError();
}
// 100_199 = "1" DIGIT DIGIT
FileCursor parse_100_199(FileCursor cursor)
{
char c = get_char(cursor);
if(c != '1')
throw ParseError();
return parse_digit(parse_digit(cursor));
}
// 10_99 = 1-9 DIGIT
FileCursor parse_10_99(FileCursor cursor)
{
char c = get_char(cursor);
if ('1' <= c && c <= '9')
{
return parse_digit(cursor);
}
else
throw ParseError();
}
//dec-octet = DIGIT ; 0-9
// / 10_99 ; 10-99
// / 100_199 ; 100-199
// / 200_249 ; 200-249
// / 250_255 ; 250-255
FileCursor parse_dec_octet(FileCursor cursor)
{
IGNORE_PARSE_ERROR(parse_250_255, cursor);
IGNORE_PARSE_ERROR(parse_200_249, cursor);
IGNORE_PARSE_ERROR(parse_100_199, cursor);
IGNORE_PARSE_ERROR(parse_10_99, cursor);
IGNORE_PARSE_ERROR(parse_digit, cursor);
throw ParseError();
}
// reg_name_segment = *( unreserved / pct-encoded / sub-delims )
FileCursor parse_reg_name_segment(FileCursor cursor)
{
IGNORE_PARSE_ERROR(parse_unreserved, cursor);
IGNORE_PARSE_ERROR(parse_pct_encoded, cursor);
IGNORE_PARSE_ERROR(parse_sub_delims, cursor);
throw ParseError();
}
// reg_name = *(reg_name_segment)
FileCursor parse_reg_name(FileCursor cursor)
{
REPEAT_IGNORING(parse_reg_name_segment, cursor);
}
// IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet
FileCursor parse_ipv4address(FileCursor cursor)
{
for (int i=0; i<3; i++)
{
cursor = parse_dec_octet(cursor);
if (get_char(cursor) != '.')
throw ParseError();
}
return parse_dec_octet(cursor);
}
// h16 = 1*4HEXDIG
FileCursor parse_h16(FileCursor cursor)
{
cursor = parse_hexdigit(cursor);
for (int i=0; i<3; i++)
{
try
{
cursor = parse_hexdigit(cursor);
}
catch(ParseError)
{
return cursor;
}
}
return cursor;
}
// ls32 = ( h16 ":" h16 ) / IPv4address
FileCursor parse_ls32(FileCursor cursor)
{
IGNORE_PARSE_ERROR(parse_ipv4address, cursor);
cursor = parse_h16(cursor);
if (get_char(cursor) != ':')
throw ParseError();
return parse_h16(cursor);
}
// h16_colon = h16 ':'
FileCursor parse_h16_colon(FileCursor cursor)
{
cursor = parse_h16(cursor);
if(get_char(cursor) == ':')
return cursor;
else
throw ParseError();
}
FileCursor parse_n_h16_colon(FileCursor cursor, int n)
{
for (int i=0; i<n; i++)
{
cursor = parse_h16_colon(cursor);
}
return cursor;
}
FileCursor parse_lt_n_h16_colon(FileCursor cursor, int n)
{
for (int i=0; i<n; i++)
{
try
{
cursor = parse_h16_colon(cursor);
}
catch(ParseError)
{
return cursor;
}
}
return cursor;
}
// double_colon = ":" ":"
FileCursor parse_double_colon(FileCursor cursor)
{
if (get_char(cursor) != ':')
throw ParseError();
else
if (get_char(cursor) != ':')
throw ParseError();
else
return cursor;
}
// IPv6address1 = 6( h16 ":" ) ls32
// / "::" 5( h16 ":" ) ls32
// / [ h16 ] "::" 4( h16 ":" ) ls32
// / [ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32
// / [ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32
// / [ *3( h16 ":" ) h16 ] "::" h16 ":" ls32
// / [ *4( h16 ":" ) h16 ] "::" ls32
// / [ *5( h16 ":" ) h16 ] "::" h16
// / [ *6( h16 ":" ) h16 ] "::"
FileCursor parse_ipv6address_case(FileCursor cursor, int n)
{
if (n > 1)
{
try
{
cursor = parse_h16(parse_lt_n_h16_colon(cursor, n - 2));
}
catch(ParseError)
{
}
}
if (n > 0)
cursor = parse_double_colon(cursor);
if (6 - n > 0)
cursor = parse_n_h16_colon(cursor, 6 - n);
if (n < 7)
cursor = parse_ls32(cursor);
else if ( n == 7)
cursor = parse_h16(cursor);
return cursor;
}
FileCursor parse_ipv6address(FileCursor cursor)
{
for (int i=0; i<9; i++)
{
try
{
return parse_ipv6address_case(cursor, i);
}
catch(ParseError)
{
}
}
throw ParseError();
}
FileCursor parse_unreserved_subdelims_colon(FileCursor cursor)
{
IGNORE_PARSE_ERROR(parse_unreserved, cursor);
IGNORE_PARSE_ERROR(parse_sub_delims, cursor);
if(get_char(cursor) == ':')
return cursor;
else
throw ParseError();
}
FileCursor parse_at_least_one_unreserved_subdelims_colon(FileCursor cursor)
{
cursor = parse_unreserved_subdelims_colon(cursor);
REPEAT_IGNORING(parse_unreserved, cursor);
}
FileCursor parse_at_least_one_hexdigit(FileCursor cursor)
{
cursor = parse_hexdigit(cursor);
REPEAT_IGNORING(parse_hexdigit, cursor);
}
//IPvFuture = "v" 1*HEXDIG "." 1*( unreserved / sub-delims / ":" )
FileCursor parse_ipvfuture(FileCursor cursor)
{
if(get_char(cursor) != 'v')
throw ParseError();
cursor = parse_at_least_one_hexdigit(cursor);
if(get_char(cursor) != '.')
throw ParseError();
return parse_at_least_one_unreserved_subdelims_colon(cursor);
}
//ipv6address_ipfuture = IPv6address / IPvFuture
FileCursor parse_ipv6address_ipfuture(FileCursor cursor)
{
IGNORE_PARSE_ERROR(parse_ipv6address, cursor);
IGNORE_PARSE_ERROR(parse_ipvfuture, cursor);
throw ParseError();
}
// IP-literal = "[" ipv6address_ipfuture "]"
FileCursor parse_ip_literal(FileCursor cursor)
{
if(get_char(cursor) != '[')
throw ParseError();
cursor = parse_ipv6address_ipfuture(cursor);
if(get_char(cursor) == ']')
return cursor;
else
throw ParseError();
}
//port = *DIGIT
FileCursor parse_port(FileCursor cursor)
{
REPEAT_IGNORING(parse_digit, cursor);
}
//host = IP-literal / IPv4address / reg-name
FileCursor parse_host(FileCursor cursor)
{
IGNORE_PARSE_ERROR(parse_ip_literal, cursor);
IGNORE_PARSE_ERROR(parse_ipv4address, cursor);
IGNORE_PARSE_ERROR(parse_reg_name, cursor);
throw ParseError();
}
//userinfo_segment = unreserved / pct-encoded / sub-delims / ":"
FileCursor parse_userinfo_segment(FileCursor cursor)
{
IGNORE_PARSE_ERROR(parse_unreserved, cursor);
IGNORE_PARSE_ERROR(parse_pct_encoded, cursor);
IGNORE_PARSE_ERROR(parse_sub_delims, cursor);
if(get_char(cursor) == ':')
return cursor;
else
throw ParseError();
}
//userinfo = *user_info_segment
FileCursor parse_userinfo(FileCursor cursor)
{
REPEAT_IGNORING(parse_userinfo_segment, cursor);
}
//authority = [ userinfo "@" ] host [ ":" port ]
FileCursor parse_authority(FileCursor cursor)
{
try
{
FileCursor copy(parse_userinfo(cursor));
if(get_char(copy) != '@')
throw ParseError();
cursor = copy;
}
catch(ParseError)
{
}
cursor = parse_host(cursor);
try
{
FileCursor copy2(cursor);
if(get_char(copy2) != ':')
throw ParseError();
cursor = parse_port(copy2);
}
catch(ParseError)
{
}
return cursor;
}
//parse_hier_part_case = "//" authority path-abempty
FileCursor parse_hier_part_case(FileCursor cursor)
{
if (get_char(cursor) != '/')
throw ParseError();
if (get_char(cursor) != '/')
throw ParseError();
cursor = parse_authority(cursor);
return parse_path_abempty(cursor);
}
//hier-part = hier_part_case
// / path-absolute
// / path-rootless
// / path-empty
FileCursor parse_hier_part(FileCursor cursor)
{
IGNORE_PARSE_ERROR(parse_hier_part_case, cursor);
IGNORE_PARSE_ERROR(parse_path_absolute, cursor);
IGNORE_PARSE_ERROR(parse_path_rootless, cursor);
IGNORE_PARSE_ERROR(parse_path_empty, cursor);
throw ParseError();
}
// scheme_element = ALPHA / DIGIT / "+" / "-" / "."
FileCursor parse_scheme_element(FileCursor cursor)
{
IGNORE_PARSE_ERROR(parse_alpha, cursor);
IGNORE_PARSE_ERROR(parse_digit, cursor);
char c = get_char(cursor);
if (c == '+' || c == '-' || c == '.')
return cursor;
else
throw ParseError();
}
//scheme = ALPHA *scheme_element
FileCursor parse_scheme(FileCursor cursor)
{
cursor = parse_alpha(cursor);
REPEAT_IGNORING(parse_scheme_element, cursor);
}
//uri = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
FileCursor parse_uri(FileCursor cursor)
{
cursor = parse_scheme(cursor);
if(get_char(cursor) != ':')
throw ParseError();
cursor = parse_hier_part(cursor);
try
{
FileCursor copy(cursor);
if (get_char(copy) != '?')
throw ParseError();
cursor = parse_query_fragment(copy);
}
catch(ParseError)
{
}
try
{
FileCursor copy2(cursor);
if (get_char(copy2) != '#')
throw ParseError();
cursor = parse_query_fragment(cursor);
}
catch(ParseError)
{
}
return cursor;
}
<|endoftext|>
|
<commit_before>#include <exception>
#include <iostream>
#include <vector>
#include "execution_step.h"
#include "parser.h"
#define STATE_INIT 0
#define STATE_PIPE 1
std::vector<ExecutionStep*> parse_tokens(std::vector<std::string> tokens) throw (std::string) {
std::vector<ExecutionStep*> ret;
ExecutionStep* head = NULL;
ExecutionStep* prev = NULL;
int executionState = STATE_INIT;
std::vector<std::string> execTokens;
for (std::vector<std::string>::iterator it = tokens.begin(); it != tokens.end(); it++) {
std::string token = *it;
if (token == ";" || token == "\n") {
if (execTokens.size() == 0) {
continue;
}
ExecutionStep* end = new ExecutionStep(new Program(execTokens));
if (executionState == STATE_INIT) {
head = end;
} else if (executionState == STATE_PIPE) {
prev->setPipe(end);
}
ret.push_back(head);
executionState = STATE_INIT;
execTokens = std::vector<std::string>();
} else if (token == "|") {
ExecutionStep* step = new ExecutionStep(new Program(execTokens));
if (executionState == STATE_INIT) {
head = step;
}
if (head == NULL) {
throw std::string("Invalid pipe -- no step before specified.");
}
if (executionState == STATE_PIPE) {
prev->setPipe(step);
}
prev = step;
execTokens = std::vector<std::string>();
executionState = STATE_PIPE;
} else if (token == ">" || token == ">>") {
if (execTokens.size() == 0) {
throw std::string("No tokens.");
}
ExecutionStep* step = new ExecutionStep(new Program(execTokens));
if (executionState == STATE_INIT) {
head = step;
}
if (head == NULL) {
throw std::string("Invalid out redirect -- no step before specified.");
}
if (executionState == STATE_PIPE) {
prev->setPipe(step);
}
it++;
step->setOutfile(*it);
if (token == ">>") {
step->setOutappend(true);
}
execTokens = std::vector<std::string>();
prev = step;
executionState = STATE_PIPE;
} else {
execTokens.push_back(token);
}
}
if (execTokens.size() > 0) {
ExecutionStep* end = new ExecutionStep(new Program(execTokens));
if (executionState == STATE_INIT) {
head = end;
} else if (executionState == STATE_PIPE) {
prev->setPipe(end);
}
}
ret.push_back(head);
return ret;
}
<commit_msg>remove executionState<commit_after>#include <exception>
#include <iostream>
#include <vector>
#include "execution_step.h"
#include "parser.h"
std::vector<ExecutionStep*> parse_tokens(std::vector<std::string> tokens) throw (std::string) {
std::vector<ExecutionStep*> ret;
ExecutionStep* head = NULL;
ExecutionStep* prev = NULL;
ExecutionStep* cur = NULL;
std::vector<std::string> execTokens;
for (std::vector<std::string>::iterator it = tokens.begin(); it != tokens.end(); it++) {
std::string token = *it;
if (token == ";" || token == "\n") {
if (execTokens.size() != 0) {
cur = new ExecutionStep(new Program(execTokens));
if (prev != NULL) {
prev->setPipe(cur);
} else {
head = cur;
}
}
ret.push_back(head);
execTokens = std::vector<std::string>();
} else if (token == "|") {
if (cur == NULL) {
if (execTokens.size() == 0) {
throw std::string("No tokens.");
}
cur = new ExecutionStep(new Program(execTokens));
}
if (prev != NULL) {
prev->setPipe(cur);
} else {
head = cur;
}
prev = cur;
cur = NULL;
execTokens = std::vector<std::string>();
} else if (token == ">" || token == ">>") {
if (cur == NULL) {
if (execTokens.size() == 0) {
throw std::string("No tokens.");
}
cur = new ExecutionStep(new Program(execTokens));
}
it++;
cur->setOutfile(*it);
if (token == ">>") {
cur->setOutappend(true);
}
execTokens = std::vector<std::string>();
} else {
execTokens.push_back(token);
}
}
if (cur != NULL) {
if (prev != NULL) {
prev->setPipe(cur);
} else {
head = cur;
}
cur = NULL;
}
if (execTokens.size() > 0 && cur == NULL) {
cur = new ExecutionStep(new Program(execTokens));
if (prev != NULL) {
prev->setPipe(cur);
} else {
head = cur;
}
}
ret.push_back(head);
return ret;
}
<|endoftext|>
|
<commit_before>#include "parser.h"
using namespace std;
static void rndr_blockcode(struct buf *ob, struct buf *text, void *opaque);
static void rndr_blockquote(struct buf *ob, struct buf *text, void *opaque);
static void rndr_header(struct buf *ob, struct buf *text, int level, void *opaque);
static void rndr_list(struct buf *ob, struct buf *text, int flags, void *opaque);
static void rndr_listitem(struct buf *ob, struct buf *text, int flags, void *opaque);
static void rndr_paragraph(struct buf *ob, struct buf *text, void *opaque);
static int rndr_codespan(struct buf *ob, struct buf *text, void *opaque);
static int rndr_double_emphasis(struct buf *ob, struct buf *text, char c, void *opaque);
static int rndr_emphasis(struct buf *ob, struct buf *text, char c, void *opaque);
static int rndr_triple_emphasis(struct buf *ob, struct buf *text, char c, void *opaque);
static int rndr_linebreak(struct buf *ob, void *opaque);
static int rndr_link(struct buf *ob, struct buf *link, struct buf *title, struct buf *content, void *opaque);
static void rndr_normal_text(struct buf *ob, struct buf *text, void *opaque);
struct mkd_renderer mkd_callbacks = {
/* document-level callbacks */
NULL, // prolog
NULL, // epilogue
/* block-level callbacks */
rndr_blockcode, // block code
rndr_blockquote, // block quote
NULL, // block html
rndr_header, // header
NULL, // hrule
rndr_list, // list
rndr_listitem, // listitem
rndr_paragraph, // paragraph
NULL, // table
NULL, // table cell
NULL, // table row
/* span-level callbacks */
NULL, // autolink
rndr_codespan, // codespan
rndr_double_emphasis, // double emphasis
rndr_emphasis, // emphasis
NULL, // image
rndr_linebreak, // line break
rndr_link, // link
NULL, // raw html tag
rndr_triple_emphasis, // triple emphasis
/* low-level callbacks */
NULL, // entity
rndr_normal_text, // normal text
/* renderer data */
64, // max stack
"*_",
NULL // opaque
};
namespace Bypass {
const static std::string TWO_SPACES = " ";
Parser::Parser()
: elementSoup()
{
elementCount = 1;
}
Parser::~Parser() {
}
Document Parser::parse(const char* mkd) {
document = Document();
if (mkd) {
struct buf *ib, *ob;
ib = bufnew(INPUT_UNIT);
bufputs(ib, mkd);
ob = bufnew(OUTPUT_UNIT);
mkd_callbacks.opaque = this;
//parse and assemble document
markdown(ob, ib, &mkd_callbacks);
for (boost::unordered_map<std::string, Element>::iterator it = elementSoup.begin(); it != elementSoup.end(); ++it) {
document.append(it->second);
}
bufrelease(ib);
bufrelease(ob);
}
return document;
}
Document Parser::parse(const string& markdown) {
return parse(markdown.c_str());
}
// Block Element Callbacks
void Parser::handleBlock(Type type, struct buf *ob, struct buf *text) {
Element block;
block.setType(type);
std::string textString(text->data);
textString = textString.substr(0,text->size);
std::vector<std::string> strs;
boost::split(strs, textString, boost::is_any_of("|"));
for(vector<std::string>::iterator it = strs.begin(); it != strs.end(); it++) {
if (elementSoup.count(*it) > 0) {
block.append(elementSoup.at(*it));
elementSoup.erase(*it);
}
}
elementCount++;
std::ostringstream oss;
oss << elementCount;
elementSoup[oss.str()] = block;
oss << '|';
bufputs(ob, oss.str().c_str());
}
void Parser::parsedBlockcode(struct buf *ob, struct buf *text) {
}
void Parser::parsedBlockquote(struct buf *ob, struct buf *text) {
}
void Parser::parsedHeader(struct buf *ob, struct buf *text, int level) {
}
void Parser::parsedList(struct buf *ob, struct buf *text, int flags) {
}
void Parser::parsedListItem(struct buf *ob, struct buf *text, int flags) {
}
void Parser::parsedParagraph(struct buf *ob, struct buf *text) {
handleBlock(PARAGRAPH, ob, text);
}
// Span Element Callbacks
void Parser::handleSpan(Type type, struct buf *ob, struct buf *text, struct buf *extra) {
std::string textString(text->data);
textString = textString.substr(0, text->size);
std::vector<std::string> strs;
if (text)
boost::split(strs, textString, boost::is_any_of("|"));
if (strs.size() > 0) {
Element element = elementSoup.at(strs[0]);
element.setType(type);
elementSoup.erase(strs[0]);
elementSoup[strs[0]] = element;
bufputs(ob, textString.c_str());
}
else {
Element element;
element.setType(type);
createSpan(element, ob);
}
}
void Parser::createSpan(Element element, struct buf *ob) {
elementCount++;
std::ostringstream oss;
oss << elementCount;
elementSoup[oss.str()] = element;
oss << '|';
bufputs(ob, oss.str().c_str());
}
int Parser::parsedDoubleEmphasis(struct buf *ob, struct buf *text, char c) {
handleSpan(DOUBLE_EMPHASIS, ob, text);
return 1;
}
int Parser::parsedEmphasis(struct buf *ob, struct buf *text, char c) {
handleSpan(EMPHASIS, ob, text);
return 1;
}
int Parser::parsedTripleEmphasis(struct buf *ob, struct buf *text, char c) {
handleSpan(TRIPLE_EMPHASIS, ob, text);
return 1;
}
int Parser::parsedLink(struct buf *ob, struct buf *link, struct buf *title, struct buf *content) {
handleSpan(LINK, ob, content, link);
return 1;
}
int Parser::parsedCodeSpan(struct buf *ob, struct buf *text) {
if (text && text->size > 0) {
Element codeSpan;
codeSpan.setType(CODE_SPAN);
codeSpan.setText(std::string(text->data).substr(0, text->size));
pendingSpanElements.push_back(codeSpan);
}
return 1;
}
int Parser::parsedLinebreak(struct buf *ob) {
handleSpan(LINEBREAK, ob, NULL);
return 1;
}
// Low Level Callbacks
void Parser::parsedNormalText(struct buf *ob, struct buf *text) {
// The parser will spuriously emit a text callback for an empty string
// that butts up against a span-level element. This will ignore it.
if (text && text->size > 0) {
Element normalText;
normalText.setType(TEXT);
normalText.setText(std::string(text->data).substr(0, text->size));
createSpan(normalText, ob);
}
}
}
// Block Element callbacks
static void rndr_blockcode(struct buf *ob, struct buf *text, void *opaque) {
((Bypass::Parser*) opaque)->parsedBlockcode(ob, text);
}
static void rndr_blockquote(struct buf *ob, struct buf *text, void *opaque) {
((Bypass::Parser*) opaque)->parsedBlockquote(ob, text);
}
static void rndr_header(struct buf *ob, struct buf *text, int level, void *opaque) {
((Bypass::Parser*) opaque)->parsedHeader(ob, text, level);
}
static void rndr_list(struct buf *ob, struct buf *text, int flags, void *opaque) {
((Bypass::Parser*) opaque)->parsedList(ob, text, flags);
}
static void rndr_listitem(struct buf *ob, struct buf *text, int flags, void *opaque) {
((Bypass::Parser*) opaque)->parsedListItem(ob, text, flags);
}
static void rndr_paragraph(struct buf *ob, struct buf *text, void *opaque) {
((Bypass::Parser*) opaque)->parsedParagraph(ob, text);
}
// Span Element callbacks
static int rndr_codespan(struct buf *ob, struct buf *text, void *opaque) {
return ((Bypass::Parser*) opaque)->parsedCodeSpan(ob, text);
}
static int rndr_double_emphasis(struct buf *ob, struct buf *text, char c, void *opaque) {
return ((Bypass::Parser*) opaque)->parsedDoubleEmphasis(ob, text, c);
}
static int rndr_emphasis(struct buf *ob, struct buf *text, char c, void *opaque) {
return ((Bypass::Parser*) opaque)->parsedEmphasis(ob, text, c);
}
static int rndr_triple_emphasis(struct buf *ob, struct buf *text, char c, void *opaque) {
return ((Bypass::Parser*) opaque)->parsedTripleEmphasis(ob, text, c);
}
static int rndr_linebreak(struct buf *ob, void *opaque) {
return ((Bypass::Parser*) opaque)->parsedLinebreak(ob);
}
static int rndr_link(struct buf *ob, struct buf *link, struct buf *title, struct buf *content, void *opaque) {
return ((Bypass::Parser*) opaque)->parsedLink(ob, link, title, content);
}
// Low Level Callbacks
static void rndr_normal_text(struct buf *ob, struct buf *text, void *opaque) {
return ((Bypass::Parser*) opaque)->parsedNormalText(ob, text);
}
<commit_msg>Process more block elements<commit_after>#include "parser.h"
using namespace std;
static void rndr_blockcode(struct buf *ob, struct buf *text, void *opaque);
static void rndr_blockquote(struct buf *ob, struct buf *text, void *opaque);
static void rndr_header(struct buf *ob, struct buf *text, int level, void *opaque);
static void rndr_list(struct buf *ob, struct buf *text, int flags, void *opaque);
static void rndr_listitem(struct buf *ob, struct buf *text, int flags, void *opaque);
static void rndr_paragraph(struct buf *ob, struct buf *text, void *opaque);
static int rndr_codespan(struct buf *ob, struct buf *text, void *opaque);
static int rndr_double_emphasis(struct buf *ob, struct buf *text, char c, void *opaque);
static int rndr_emphasis(struct buf *ob, struct buf *text, char c, void *opaque);
static int rndr_triple_emphasis(struct buf *ob, struct buf *text, char c, void *opaque);
static int rndr_linebreak(struct buf *ob, void *opaque);
static int rndr_link(struct buf *ob, struct buf *link, struct buf *title, struct buf *content, void *opaque);
static void rndr_normal_text(struct buf *ob, struct buf *text, void *opaque);
struct mkd_renderer mkd_callbacks = {
/* document-level callbacks */
NULL, // prolog
NULL, // epilogue
/* block-level callbacks */
rndr_blockcode, // block code
rndr_blockquote, // block quote
NULL, // block html
rndr_header, // header
NULL, // hrule
rndr_list, // list
rndr_listitem, // listitem
rndr_paragraph, // paragraph
NULL, // table
NULL, // table cell
NULL, // table row
/* span-level callbacks */
NULL, // autolink
rndr_codespan, // codespan
rndr_double_emphasis, // double emphasis
rndr_emphasis, // emphasis
NULL, // image
rndr_linebreak, // line break
rndr_link, // link
NULL, // raw html tag
rndr_triple_emphasis, // triple emphasis
/* low-level callbacks */
NULL, // entity
rndr_normal_text, // normal text
/* renderer data */
64, // max stack
"*_",
NULL // opaque
};
namespace Bypass {
const static std::string TWO_SPACES = " ";
Parser::Parser()
: elementSoup()
{
elementCount = 1;
}
Parser::~Parser() {
}
Document Parser::parse(const char* mkd) {
document = Document();
if (mkd) {
struct buf *ib, *ob;
ib = bufnew(INPUT_UNIT);
bufputs(ib, mkd);
ob = bufnew(OUTPUT_UNIT);
mkd_callbacks.opaque = this;
//parse and assemble document
markdown(ob, ib, &mkd_callbacks);
for (boost::unordered_map<std::string, Element>::iterator it = elementSoup.begin(); it != elementSoup.end(); ++it) {
document.append(it->second);
}
bufrelease(ib);
bufrelease(ob);
}
return document;
}
Document Parser::parse(const string& markdown) {
return parse(markdown.c_str());
}
// Block Element Callbacks
void Parser::handleBlock(Type type, struct buf *ob, struct buf *text) {
Element block;
block.setType(type);
std::string textString(text->data);
textString = textString.substr(0,text->size);
std::vector<std::string> strs;
boost::split(strs, textString, boost::is_any_of("|"));
for(vector<std::string>::iterator it = strs.begin(); it != strs.end(); it++) {
if (elementSoup.count(*it) > 0) {
block.append(elementSoup.at(*it));
elementSoup.erase(*it);
}
}
elementCount++;
std::ostringstream oss;
oss << elementCount;
elementSoup[oss.str()] = block;
oss << '|';
bufputs(ob, oss.str().c_str());
}
void Parser::parsedBlockcode(struct buf *ob, struct buf *text) {
handleBlock(BLOCK_CODE, ob, text);
}
void Parser::parsedBlockquote(struct buf *ob, struct buf *text) {
handleBlock(BLOCK_QUOTE, ob, text);
}
void Parser::parsedHeader(struct buf *ob, struct buf *text, int level) {
handleBlock(HEADER, ob, text);
}
void Parser::parsedList(struct buf *ob, struct buf *text, int flags) {
handleBlock(LIST, ob, text);
}
void Parser::parsedListItem(struct buf *ob, struct buf *text, int flags) {
handleBlock(LIST_ITEM, ob, text);
}
void Parser::parsedParagraph(struct buf *ob, struct buf *text) {
handleBlock(PARAGRAPH, ob, text);
}
// Span Element Callbacks
void Parser::handleSpan(Type type, struct buf *ob, struct buf *text, struct buf *extra) {
std::string textString(text->data);
textString = textString.substr(0, text->size);
std::vector<std::string> strs;
if (text)
boost::split(strs, textString, boost::is_any_of("|"));
if (strs.size() > 0) {
Element element = elementSoup.at(strs[0]);
element.setType(type);
elementSoup.erase(strs[0]);
elementSoup[strs[0]] = element;
bufputs(ob, textString.c_str());
}
else {
Element element;
element.setType(type);
createSpan(element, ob);
}
}
void Parser::createSpan(Element element, struct buf *ob) {
elementCount++;
std::ostringstream oss;
oss << elementCount;
elementSoup[oss.str()] = element;
oss << '|';
bufputs(ob, oss.str().c_str());
}
int Parser::parsedDoubleEmphasis(struct buf *ob, struct buf *text, char c) {
handleSpan(DOUBLE_EMPHASIS, ob, text);
return 1;
}
int Parser::parsedEmphasis(struct buf *ob, struct buf *text, char c) {
handleSpan(EMPHASIS, ob, text);
return 1;
}
int Parser::parsedTripleEmphasis(struct buf *ob, struct buf *text, char c) {
handleSpan(TRIPLE_EMPHASIS, ob, text);
return 1;
}
int Parser::parsedLink(struct buf *ob, struct buf *link, struct buf *title, struct buf *content) {
handleSpan(LINK, ob, content, link);
return 1;
}
int Parser::parsedCodeSpan(struct buf *ob, struct buf *text) {
handleBlock(CODE_SPAN, ob, text);
return 1;
}
int Parser::parsedLinebreak(struct buf *ob) {
handleSpan(LINEBREAK, ob, NULL);
return 1;
}
// Low Level Callbacks
void Parser::parsedNormalText(struct buf *ob, struct buf *text) {
// The parser will spuriously emit a text callback for an empty string
// that butts up against a span-level element. This will ignore it.
if (text && text->size > 0) {
Element normalText;
normalText.setType(TEXT);
normalText.setText(std::string(text->data).substr(0, text->size));
createSpan(normalText, ob);
}
}
}
// Block Element callbacks
static void rndr_blockcode(struct buf *ob, struct buf *text, void *opaque) {
((Bypass::Parser*) opaque)->parsedBlockcode(ob, text);
}
static void rndr_blockquote(struct buf *ob, struct buf *text, void *opaque) {
((Bypass::Parser*) opaque)->parsedBlockquote(ob, text);
}
static void rndr_header(struct buf *ob, struct buf *text, int level, void *opaque) {
((Bypass::Parser*) opaque)->parsedHeader(ob, text, level);
}
static void rndr_list(struct buf *ob, struct buf *text, int flags, void *opaque) {
((Bypass::Parser*) opaque)->parsedList(ob, text, flags);
}
static void rndr_listitem(struct buf *ob, struct buf *text, int flags, void *opaque) {
((Bypass::Parser*) opaque)->parsedListItem(ob, text, flags);
}
static void rndr_paragraph(struct buf *ob, struct buf *text, void *opaque) {
((Bypass::Parser*) opaque)->parsedParagraph(ob, text);
}
// Span Element callbacks
static int rndr_codespan(struct buf *ob, struct buf *text, void *opaque) {
return ((Bypass::Parser*) opaque)->parsedCodeSpan(ob, text);
}
static int rndr_double_emphasis(struct buf *ob, struct buf *text, char c, void *opaque) {
return ((Bypass::Parser*) opaque)->parsedDoubleEmphasis(ob, text, c);
}
static int rndr_emphasis(struct buf *ob, struct buf *text, char c, void *opaque) {
return ((Bypass::Parser*) opaque)->parsedEmphasis(ob, text, c);
}
static int rndr_triple_emphasis(struct buf *ob, struct buf *text, char c, void *opaque) {
return ((Bypass::Parser*) opaque)->parsedTripleEmphasis(ob, text, c);
}
static int rndr_linebreak(struct buf *ob, void *opaque) {
return ((Bypass::Parser*) opaque)->parsedLinebreak(ob);
}
static int rndr_link(struct buf *ob, struct buf *link, struct buf *title, struct buf *content, void *opaque) {
return ((Bypass::Parser*) opaque)->parsedLink(ob, link, title, content);
}
// Low Level Callbacks
static void rndr_normal_text(struct buf *ob, struct buf *text, void *opaque) {
return ((Bypass::Parser*) opaque)->parsedNormalText(ob, text);
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <iostream>
#include "libtorrent/policy.hpp"
#include "libtorrent/torrent.hpp"
#include "libtorrent/socket.hpp"
#include "libtorrent/peer_connection.hpp"
namespace
{
enum
{
// we try to maintain 4 requested blocks in the download
// queue
request_queue = 16
};
using namespace libtorrent;
// TODO: replace these two functions with std::find_first_of
template<class It1, class It2>
bool has_intersection(It1 start1, It1 end1, It2 start2, It2 end2)
{
for (;start1 != end1; ++start1)
for (;start2 != end2; ++start2)
if (*start1 == *start2) return true;
return false;
}
piece_block find_first_common(const std::vector<piece_block>& queue,
const std::vector<piece_block>& busy)
{
for (std::vector<piece_block>::const_reverse_iterator i
= queue.rbegin();
i != queue.rend();
++i)
{
for (std::vector<piece_block>::const_iterator j
= busy.begin();
j != busy.end();
++j)
{
if ((*j) == (*i)) return *i;
}
}
assert(false);
}
void request_a_block(torrent& t, peer_connection& c)
{
int num_requests = request_queue - c.download_queue().size();
// if our request queue is already full, we
// don't have to make any new requests yet
if (num_requests <= 0) return;
piece_picker& p = t.picker();
std::vector<piece_block> interesting_pieces;
interesting_pieces.reserve(100);
// picks the interesting pieces from this peer
// the integer is the number of pieces that
// should be guaranteed to be available for download
// (if this number is too big, too many pieces are
// picked and cpu-time is wasted)
p.pick_pieces(c.get_bitfield(), interesting_pieces, num_requests);
// this vector is filled with the interestin pieces
// that some other peer is currently downloading
// we should then compare this peer's download speed
// with the other's, to see if we should abort another
// peer_connection in favour of this one
std::vector<piece_block> busy_pieces;
busy_pieces.reserve(10);
for (std::vector<piece_block>::iterator i = interesting_pieces.begin();
i != interesting_pieces.end();
++i)
{
if (p.is_downloading(*i))
{
busy_pieces.push_back(*i);
continue;
}
// ok, we found a piece that's not being downloaded
// by somebody else. request it from this peer
c.request_block(*i);
num_requests--;
if (num_requests <= 0) return;
}
if (busy_pieces.empty()) return;
// first look for blocks that are just queued
// and not actually sent to us yet
// (then we can cancel those and request them
// from this peer instead)
peer_connection* peer = 0;
float down_speed = 0.f;
// find the peer with the lowest download
// speed that also has a piece thatt this
// peer could send us
for (torrent::peer_iterator i = t.begin();
i != t.end();
++i)
{
const std::vector<piece_block>& queue = (*i)->download_queue();
if ((*i)->statistics().down_peak() > down_speed
&& has_intersection(busy_pieces.begin(),
busy_pieces.end(),
queue.begin(),
queue.end()))
{
peer = *i;
down_speed = (*i)->statistics().down_peak();
}
}
assert(peer != 0);
// this peer doesn't have a faster connection than the
// slowest peer. Don't take over any blocks
if (c.statistics().down_peak() <= down_speed) return;
// find a suitable block to take over from this peer
piece_block block = find_first_common(peer->download_queue(), busy_pieces);
peer->cancel_block(block);
c.request_block(block);
// the one we interrupted may need to request a new piece
request_a_block(t, *peer);
num_requests--;
}
}
namespace libtorrent
{
/*
TODO: make two proxy classes that filter out
all unneccesary members from torrent and peer_connection
to make it easier to use them in the policy
useful member functions:
void torrent::connect_to_peer(address, peer_id);
piece_picker& torrent::picker();
std::vector<peer_connection*>::const_iterator torrent::begin() const
std::vector<peer_connection*>::const_iterator torrent::end() const
void peer_connection::interested();
void peer_connection::not_interested();
void peer_connection::choke();
void peer_connection::unchoke();
void peer_connection::request_piece(int index);
const std::vector<int>& peer_connection::download_queue();
*/
policy::policy(torrent* t)
: m_num_peers(0)
, m_torrent(t)
{}
// this is called when a connection is made, before any
// handshake (it's possible to ban certain ip:s).
bool policy::accept_connection(const address& remote)
{
m_num_peers++;
return true;
}
void policy::peer_from_tracker(const address& remote, const peer_id& id)
{
try
{
m_torrent->connect_to_peer(remote, id);
m_num_peers++;
}
catch(network_error&) {}
}
// this is called when we are choked by a peer
// i.e. a peer lets us know that we will not receive
// anything for a while
void policy::choked(peer_connection& c)
{
c.choke();
}
void policy::piece_finished(peer_connection& c, int index, bool successfully_verified)
{
// TODO: if verification failed, mark the peers that were involved
// in some way
}
void policy::block_finished(peer_connection& c, piece_block b)
{
if (c.has_peer_choked()) return;
request_a_block(*m_torrent, c);
}
// this is called when we are unchoked by a peer
// i.e. a peer lets us know that we will receive
// data from now on
void policy::unchoked(peer_connection& c)
{
c.unchoke();
if (c.is_interesting()) request_a_block(*m_torrent, c);
}
void policy::interested(peer_connection& c)
{
c.unchoke();
}
void policy::not_interested(peer_connection& c)
{
}
void policy::connection_closed(const peer_connection& c)
{
}
void policy::peer_is_interesting(peer_connection& c)
{
c.interested();
if (c.has_peer_choked()) return;
request_a_block(*m_torrent, c);
}
}
<commit_msg>bugfix<commit_after>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <iostream>
#include "libtorrent/policy.hpp"
#include "libtorrent/torrent.hpp"
#include "libtorrent/socket.hpp"
#include "libtorrent/peer_connection.hpp"
namespace
{
enum
{
// we try to maintain 4 requested blocks in the download
// queue
request_queue = 16
};
using namespace libtorrent;
// TODO: replace these two functions with std::find_first_of
template<class It1, class It2>
bool has_intersection(It1 start1, It1 end1, It2 start2, It2 end2)
{
for (;start1 != end1; ++start1)
for (;start2 != end2; ++start2)
if (*start1 == *start2) return true;
return false;
}
piece_block find_first_common(const std::vector<piece_block>& queue,
const std::vector<piece_block>& busy)
{
for (std::vector<piece_block>::const_reverse_iterator i
= queue.rbegin();
i != queue.rend();
++i)
{
for (std::vector<piece_block>::const_iterator j
= busy.begin();
j != busy.end();
++j)
{
if ((*j) == (*i)) return *i;
}
}
assert(false);
}
void request_a_block(torrent& t, peer_connection& c)
{
int num_requests = request_queue - c.download_queue().size();
// if our request queue is already full, we
// don't have to make any new requests yet
if (num_requests <= 0) return;
piece_picker& p = t.picker();
std::vector<piece_block> interesting_pieces;
interesting_pieces.reserve(100);
// picks the interesting pieces from this peer
// the integer is the number of pieces that
// should be guaranteed to be available for download
// (if this number is too big, too many pieces are
// picked and cpu-time is wasted)
p.pick_pieces(c.get_bitfield(), interesting_pieces, num_requests);
// this vector is filled with the interestin pieces
// that some other peer is currently downloading
// we should then compare this peer's download speed
// with the other's, to see if we should abort another
// peer_connection in favour of this one
std::vector<piece_block> busy_pieces;
busy_pieces.reserve(10);
for (std::vector<piece_block>::iterator i = interesting_pieces.begin();
i != interesting_pieces.end();
++i)
{
if (p.is_downloading(*i))
{
busy_pieces.push_back(*i);
continue;
}
// ok, we found a piece that's not being downloaded
// by somebody else. request it from this peer
c.request_block(*i);
num_requests--;
if (num_requests <= 0) return;
}
if (busy_pieces.empty()) return;
// first look for blocks that are just queued
// and not actually sent to us yet
// (then we can cancel those and request them
// from this peer instead)
peer_connection* peer = 0;
float down_speed = -1.f;
// find the peer with the lowest download
// speed that also has a piece thatt this
// peer could send us
for (torrent::peer_iterator i = t.begin();
i != t.end();
++i)
{
const std::vector<piece_block>& queue = (*i)->download_queue();
if ((*i)->statistics().down_peak() > down_speed
&& has_intersection(busy_pieces.begin(),
busy_pieces.end(),
queue.begin(),
queue.end()))
{
peer = *i;
down_speed = (*i)->statistics().down_peak();
}
}
assert(peer != 0);
// this peer doesn't have a faster connection than the
// slowest peer. Don't take over any blocks
if (c.statistics().down_peak() <= down_speed) return;
// find a suitable block to take over from this peer
piece_block block = find_first_common(peer->download_queue(), busy_pieces);
peer->cancel_block(block);
c.request_block(block);
// the one we interrupted may need to request a new piece
request_a_block(t, *peer);
num_requests--;
}
}
namespace libtorrent
{
/*
TODO: make two proxy classes that filter out
all unneccesary members from torrent and peer_connection
to make it easier to use them in the policy
useful member functions:
void torrent::connect_to_peer(address, peer_id);
piece_picker& torrent::picker();
std::vector<peer_connection*>::const_iterator torrent::begin() const
std::vector<peer_connection*>::const_iterator torrent::end() const
void peer_connection::interested();
void peer_connection::not_interested();
void peer_connection::choke();
void peer_connection::unchoke();
void peer_connection::request_piece(int index);
const std::vector<int>& peer_connection::download_queue();
*/
policy::policy(torrent* t)
: m_num_peers(0)
, m_torrent(t)
{}
// this is called when a connection is made, before any
// handshake (it's possible to ban certain ip:s).
bool policy::accept_connection(const address& remote)
{
m_num_peers++;
return true;
}
void policy::peer_from_tracker(const address& remote, const peer_id& id)
{
try
{
m_torrent->connect_to_peer(remote, id);
m_num_peers++;
}
catch(network_error&) {}
}
// this is called when we are choked by a peer
// i.e. a peer lets us know that we will not receive
// anything for a while
void policy::choked(peer_connection& c)
{
c.choke();
}
void policy::piece_finished(peer_connection& c, int index, bool successfully_verified)
{
// TODO: if verification failed, mark the peers that were involved
// in some way
}
void policy::block_finished(peer_connection& c, piece_block b)
{
if (c.has_peer_choked()) return;
request_a_block(*m_torrent, c);
}
// this is called when we are unchoked by a peer
// i.e. a peer lets us know that we will receive
// data from now on
void policy::unchoked(peer_connection& c)
{
c.unchoke();
if (c.is_interesting()) request_a_block(*m_torrent, c);
}
void policy::interested(peer_connection& c)
{
c.unchoke();
}
void policy::not_interested(peer_connection& c)
{
}
void policy::connection_closed(const peer_connection& c)
{
}
void policy::peer_is_interesting(peer_connection& c)
{
c.interested();
if (c.has_peer_choked()) return;
request_a_block(*m_torrent, c);
}
}
<|endoftext|>
|
<commit_before>// -*- mode: c++, encoding: utf-8 -*-
/**
* tbrpg – Text based roll playing game
*
* Copyright © 2012 Mattias Andrée (maandree@kth.se)
*
* 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 <stdlib.h>
#include <iostream>
#include <vector>
#include "cleaner.hpp"
#include "prompter.hpp"
#include "Senario.hpp"
#include "CharacterCreator.hpp"
#include "GamePlay.hpp"
#include "BasicSenario.hpp"
/**
* Text based roll playing game
*
* DD2387 Program construction with C++
* Laboration 3
*
* @author Mattias Andrée <maandree@kth.se>
*/
namespace tbrpg
{
/**
* Create a party
*
* @param senario The game senario
* @param sheets Solts for the character sheets of the party
* @return Whether the party creation was completed
*/
bool createParty(const Senario& senario, std::vector<CharacterSheet*>* sheets);
/**
* Fixes character attributes and add them to the party member list
*
* @param senario The game senario
* @param sheets The character sheets of the party
*/
void fixCharacters(Senario& senario, std::vector<CharacterSheet*>* sheets);
/**
* This the main entry point of the program
*
* @param argc The number of elements in `argv`
* @param argv Command line arguments, including the execute file
* @return Exit value, 0 if successful
*/
int __main__(int argc, char** argv)
{
(void) argc;
(void) argv;
/** BEGIN initialise random **/
unsigned a, d;
asm("cpuid");
asm volatile("rdtsc" : "=a" (a), "=d" (d));
srand(((long long)a) | (((long long)d) << 32LL));
/** END initialise random **/
std::vector<std::string> senarioTitles = {BasicSenario::getTitle()};
long senarioIndex = promptDialogue(4, "Welcome to tbrpg!",
"Select a game senario." "\n"
"\n"
"Use the up and down arrow keys to nagivate," "\n"
"and press enter, spacebar or the right arrow" "\n"
"key to start the select senario. You can" "\n"
"also use the letter in front of the senario." "\n"
"\n"
"You should play with the manual by your side," "\n"
"run `info tbrpg` or open a graphical if you" "\n"
"have one installed, jfbview can view them in" "\n"
"the TTY." "\n"
"\n"
"If you want to exit, press <control>g." "\n",
senarioTitles, 0);
Senario* _senario = nullptr;
if (senarioIndex == 0)
_senario = new BasicSenario();
if (_senario == nullptr)
{
cleaner::getInstance().clean();
return 0;
}
cleaner::getInstance().enqueueDelete(_senario);
Senario& senario = *_senario;
std::vector<CharacterSheet*>* sheets = new std::vector<CharacterSheet*>(senario.rules.party_start_size);
if (createParty(senario, sheets) == false)
{
delete sheets;
cleaner::getInstance().clean();
return 0;
}
fixCharacters(senario, sheets);
delete sheets;
senario.partyFormed();
senario.start();
GamePlay game = GamePlay(senario);
while (game.next())
;
cleaner::getInstance().clean();
return 0;
}
/**
* Create a party
*
* @param senario The game senario
* @param sheets Solts for the character sheets of the party
* @return Whether the party creation was completed
*/
bool createParty(const Senario& senario, std::vector<CharacterSheet*>* sheets)
{
return promptSlots<CharacterSheet>("Create your party, you need at least one character.",
true, 1, sheets,
[&] () -> CharacterSheet* {
CharacterCreator cc = CharacterCreator(senario.rules);
return cc.create();
},
[] (CharacterSheet* sheet, bool selected) -> void {
if (sheet == nullptr)
std::cout << (selected ? "\033[01m(empty)\033[21m" : "(empty)");
else
{
std::cout << (selected ? "\033[01;3" : "\033[3") << (int)(sheet->colour) << "m";
std::cout << sheet->name << "\033[21;39m";
}
});
}
/**
* Fixes character attributes and add them to the party member list
*
* @param senario The game senario
* @param sheets The character sheets of the party
*/
void fixCharacters(Senario& senario, std::vector<CharacterSheet*>* sheets)
{
for (CharacterSheet* sheet : *sheets)
if (sheet != nullptr)
{
Character* character = new Character();
character->record = *sheet;
delete sheet;
character->protagonist = true;
character->hit_points = character->record.hit_points;
for (size_t i = 0, n = character->record.prestige.size(); i < n; i++)
if (character->record.prestige[i] >= PROTOTYPE(Warrior))
if (character->record.level[i] >= 7)
character->extra_attacks++;
cleaner::getInstance().enqueueDelete(character);
senario.party.characters.push_back(character);
}
}
}
/**
* This the main entry point of the program
*
* @param argc The number of elements in `argv`
* @param argv Command line arguments, including the execute file
* @return Exit value, 0 if successful
*/
int main(int argc, char** argv)
{
return tbrpg::__main__(argc, argv);
}
<commit_msg>extra_attacks should be half attacks<commit_after>// -*- mode: c++, encoding: utf-8 -*-
/**
* tbrpg – Text based roll playing game
*
* Copyright © 2012 Mattias Andrée (maandree@kth.se)
*
* 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 <stdlib.h>
#include <iostream>
#include <vector>
#include "cleaner.hpp"
#include "prompter.hpp"
#include "Senario.hpp"
#include "CharacterCreator.hpp"
#include "GamePlay.hpp"
#include "BasicSenario.hpp"
/**
* Text based roll playing game
*
* DD2387 Program construction with C++
* Laboration 3
*
* @author Mattias Andrée <maandree@kth.se>
*/
namespace tbrpg
{
/**
* Create a party
*
* @param senario The game senario
* @param sheets Solts for the character sheets of the party
* @return Whether the party creation was completed
*/
bool createParty(const Senario& senario, std::vector<CharacterSheet*>* sheets);
/**
* Fixes character attributes and add them to the party member list
*
* @param senario The game senario
* @param sheets The character sheets of the party
*/
void fixCharacters(Senario& senario, std::vector<CharacterSheet*>* sheets);
/**
* This the main entry point of the program
*
* @param argc The number of elements in `argv`
* @param argv Command line arguments, including the execute file
* @return Exit value, 0 if successful
*/
int __main__(int argc, char** argv)
{
(void) argc;
(void) argv;
/** BEGIN initialise random **/
unsigned a, d;
asm("cpuid");
asm volatile("rdtsc" : "=a" (a), "=d" (d));
srand(((long long)a) | (((long long)d) << 32LL));
/** END initialise random **/
std::vector<std::string> senarioTitles = {BasicSenario::getTitle()};
long senarioIndex = promptDialogue(4, "Welcome to tbrpg!",
"Select a game senario." "\n"
"\n"
"Use the up and down arrow keys to nagivate," "\n"
"and press enter, spacebar or the right arrow" "\n"
"key to start the select senario. You can" "\n"
"also use the letter in front of the senario." "\n"
"\n"
"You should play with the manual by your side," "\n"
"run `info tbrpg` or open a graphical if you" "\n"
"have one installed, jfbview can view them in" "\n"
"the TTY." "\n"
"\n"
"If you want to exit, press <control>g." "\n",
senarioTitles, 0);
Senario* _senario = nullptr;
if (senarioIndex == 0)
_senario = new BasicSenario();
if (_senario == nullptr)
{
cleaner::getInstance().clean();
return 0;
}
cleaner::getInstance().enqueueDelete(_senario);
Senario& senario = *_senario;
std::vector<CharacterSheet*>* sheets = new std::vector<CharacterSheet*>(senario.rules.party_start_size);
if (createParty(senario, sheets) == false)
{
delete sheets;
cleaner::getInstance().clean();
return 0;
}
fixCharacters(senario, sheets);
delete sheets;
senario.partyFormed();
senario.start();
GamePlay game = GamePlay(senario);
while (game.next())
;
cleaner::getInstance().clean();
return 0;
}
/**
* Create a party
*
* @param senario The game senario
* @param sheets Solts for the character sheets of the party
* @return Whether the party creation was completed
*/
bool createParty(const Senario& senario, std::vector<CharacterSheet*>* sheets)
{
return promptSlots<CharacterSheet>("Create your party, you need at least one character.",
true, 1, sheets,
[&] () -> CharacterSheet* {
CharacterCreator cc = CharacterCreator(senario.rules);
return cc.create();
},
[] (CharacterSheet* sheet, bool selected) -> void {
if (sheet == nullptr)
std::cout << (selected ? "\033[01m(empty)\033[21m" : "(empty)");
else
{
std::cout << (selected ? "\033[01;3" : "\033[3") << (int)(sheet->colour) << "m";
std::cout << sheet->name << "\033[21;39m";
}
});
}
/**
* Fixes character attributes and add them to the party member list
*
* @param senario The game senario
* @param sheets The character sheets of the party
*/
void fixCharacters(Senario& senario, std::vector<CharacterSheet*>* sheets)
{
for (CharacterSheet* sheet : *sheets)
if (sheet != nullptr)
{
Character* character = new Character();
character->record = *sheet;
delete sheet;
character->protagonist = true;
character->hit_points = character->record.hit_points;
for (size_t i = 0, n = character->record.prestige.size(); i < n; i++)
if (character->record.prestige[i] >= PROTOTYPE(Warrior))
if (character->record.level[i] >= 7)
character->extra_attacks += 2;
cleaner::getInstance().enqueueDelete(character);
senario.party.characters.push_back(character);
}
}
}
/**
* This the main entry point of the program
*
* @param argc The number of elements in `argv`
* @param argv Command line arguments, including the execute file
* @return Exit value, 0 if successful
*/
int main(int argc, char** argv)
{
return tbrpg::__main__(argc, argv);
}
<|endoftext|>
|
<commit_before>/*
* Pi 2 is connected to the ImP/IMU via UART, Camera via CSI, Burn Wire Relay
* via GPIO and Pi 1 via Ethernet and GPIO for LO, SOE and SODS signals.
*
* This program controls most of the main logic and for the PIOneERs mission
* on board REXUS.
*/
#include <stdio.h>
#include <cstdint>
#include <unistd.h> //For sleep
#include <stdlib.h>
#include <iostream>
#include <signal.h>
#include "pins2.h"
#include "camera/camera.h"
#include "UART/UART.h"
#include "Ethernet/Ethernet.h"
#include "comms/pipes.h"
#include "comms/protocol.h"
#include "comms/packet.h"
#include "timing/timer.h"
#include "logger/logger.h"
#include <wiringPi.h>
Logger Log("/Docs/Logs/raspi2");
bool flight_mode = false;
// Global variable for the Camera and IMU
PiCamera Cam;
// Setup for the UART communications
int baud = 230400;
ImP IMP(baud);
comms::Pipe ImP_stream;
// Ethernet communication setup and variables (we are acting as client)
int port_no = 31415; // Random unused port for communication
Raspi2 raspi2(port_no);
/**
* Checks whether input is activated
* @param pin: GPIO to be checked
* @return true or false
*/
bool poll_input(int pin) {
int count = 0;
for (int i = 0; i < 5; i++) {
count += digitalRead(pin);
delayMicroseconds(200);
}
return (count < 3) ? true : false;
}
void signal_handler(int s) {
Log("FATAL") << "Exiting program after signal " << s;
if (Cam.is_running()) {
Cam.stopVideo();
Log("INFO") << "Stopping camera process";
} else {
Log("ERROR") << "Camera process died prematurely or did not start";
}
if (raspi2.is_alive()) {
raspi2.end();
Log("INFO") << "Closed Ethernet communication";
} else {
Log("ERROR") << "Ethernet process died prematurely or did not start";
}
if (&ImP_stream != NULL) {
ImP_stream.close_pipes();
Log("INFO") << "Closed ImP communication";
} else {
Log("ERROR") << "ImP process died prematurely or did not start";
}
digitalWrite(BURNWIRE, 0);
// TODO copy data to a further backup directory
Log("INFO") << "Ending program, Pi rebooting";
system("sudo reboot");
exit(1); // This was an unexpected end so we will exit with an error!
}
int SODS_SIGNAL() {
/*
* When the 'Start of Data Storage' signal is received all data recording
* is stopped (IMU and Camera) and power to the camera is cut off to stop
* shorting due to melting on re-entry. All data is copied into a backup
* directory.
*/
Log("INFO") << "SODS signal received";
if (Cam.is_running()) {
Cam.stopVideo();
Log("INFO") << "Stopping camera process";
} else {
Log("ERROR") << "Camera process died prematurely or did not start";
}
if (raspi2.is_alive()) {
raspi2.end();
Log("INFO") << "Closed Ethernet communication";
} else {
Log("ERROR") << "Ethernet process died prematurely or did not start";
}
if (&ImP_stream != NULL) {
ImP_stream.close_pipes();
Log("INFO") << "Closed ImP communication";
} else {
Log("ERROR") << "ImP process died prematurely or did not start";
}
digitalWrite(BURNWIRE, 0);
digitalWrite(BURNWIRE, 0);
// TODO copy data to a further backup directory
Log("INFO") << "Ending program, Pi rebooting";
system("sudo reboot");
return 0;
}
int SOE_SIGNAL() {
/*
* When the 'Start of Experiment' signal is received the boom needs to be
* deployed and the ImP and IMU to start taking measurements. For boom
* deployment is there is no increase in the encoder count or ?? seconds
* have passed since start of deployment then it is assumed that either the
* boom has reached it's full length or something has gone wrong and the
* count of the encoder is sent to ground.
*/
Log("INFO") << "SOE signal received";
// Setup the ImP and start requesting data
ImP_stream = IMP.startDataCollection("Docs/Data/Pi2/test");
Log("INFO") << "Started data collection from ImP";
comms::Packet p; // Buffer for reading data from the IMU stream
// Trigger the burn wire for 10 seconds!
Log("INFO") << "Triggering burnwire";
digitalWrite(BURNWIRE, 1);
Timer tmr;
Log("INFO") << "Burn wire triggered" << std::endl;
while (tmr.elapsed() < 10000) {
// Get ImP data
int n = ImP_stream.binread(&p, sizeof (p));
if (n > 0) {
Log("DATA (ImP)") << p;
raspi2.sendPacket(p);
}
n = raspi2.recvPacket(p);
if (n > 0)
Log("DATA (PI1)") << p;
Timer::sleep_ms(10);
}
digitalWrite(BURNWIRE, 0);
Log("INFO") << "Burn wire off after " << tmr.elapsed() << " ms";
Log("INFO") << "Waiting for SODS";
// Wait for the next signal to continue the program
bool signal_received = false;
while (!signal_received) {
signal_received = poll_input(SODS);
// Read data from IMU_data_stream and echo it to Ethernet
int n = ImP_stream.binread(&p, sizeof (p));
if (n > 0) {
Log("DATA (ImP)") << p;
raspi2.sendPacket(p);
}
n = raspi2.recvPacket(p);
if (n > 0)
Log("DATA (PI1)") << p;
Timer::sleep_ms(10);
}
return SODS_SIGNAL();
}
int LO_SIGNAL() {
/*
* When the 'Lift Off' signal is received from the REXUS Module the cameras
* are set to start recording video and we then wait to receive the 'Start
* of Experiment' signal (when the nose-cone is ejected)
*/
Log("INFO") << "LO signal received";
Cam.startVideo("Docs/Video/rexus_video");
Log("INFO") << "Camera started recording video";
// Poll the SOE pin until signal is received
Log("INFO") << "Waiting for SOE";
bool signal_received = false;
while (!signal_received) {
Timer::sleep_ms(10);
signal_received = poll_input(SOE);
// TODO Implement communications with RXSM
}
return SOE_SIGNAL();
}
int main() {
/*
* This part of the program is run before the Lift-Off. In effect it
* continually listens for commands from the ground station and runs any
* required tests, regularly reporting status until the LO Signal is
* received.
*/
signal(SIGINT, signal_handler);
// Create necessary directories for saving files
system("mkdir -p Docs/Data/Pi1 Docs/Data/Pi2 Docs/Data/test Docs/Video Docs/Logs");
Log.start_log();
Log("INFO") << "Pi2 is alive";
wiringPiSetup();
// Setup main signal pins
pinMode(LO, INPUT);
pullUpDnControl(LO, PUD_UP);
pinMode(SOE, INPUT);
pullUpDnControl(SOE, PUD_UP);
pinMode(SODS, INPUT);
pullUpDnControl(SODS, PUD_UP);
pinMode(ALIVE, OUTPUT);
Log("INFO") << "Main signal pins setup";
// Setup pins and check whether we are in flight mode
pinMode(LAUNCH_MODE, INPUT);
pullUpDnControl(LAUNCH_MODE, PUD_UP);
flight_mode = digitalRead(LAUNCH_MODE);
Log("INFO") << (flight_mode ? "flight mode enabled" : "test mode enabled");
// Setup Burn Wire
pinMode(BURNWIRE, OUTPUT);
// Setup server and wait for client
digitalWrite(ALIVE, 1);
Log("INFO") << "Waiting for connection from client on port " << port_no;
try {
raspi2.run("Docs/Data/Pi1/backup.txt");
} catch (EthernetException e) {
Log("FATAL") << "Unable to connect to pi 1";
signal_handler(-5);
}
Log("INFO") << "Connection to Pi1 successfil";
Log("INFO") << "Waiting for LO signal";
// Check for LO signal.
std::string msg;
bool signal_received = false;
comms::Packet p;
comms::byte1_t id;
comms::byte2_t index;
char data[16];
while (!signal_received) {
Timer::sleep_ms(10);
signal_received = poll_input(LO);
// TODO Implement communications with Pi 1
int n = raspi2.recvPacket(p);
if (n > 0) {
Log("PI1") << p;
comms::Protocol::unpack(p, id, index, data);
if (id == 0b11000000) {
Log("RXSM") << "Received Command: " << data[0];
switch (data[0]) {
case 1: // restart
Log("INFO") << "Rebooting...";
system("sudo reboot now");
exit(0);
case 2: // shutdown
Log("INFO") << "Shutting down...";
system("sudo shutdown now");
exit(0);
case 3: // Toggle flight mode
Log("INFO") << "Toggling flight mode";
flight_mode = (flight_mode) ? false : true;
Log("INFO") << (flight_mode ? "flight mode enabled" : "test mode enabled");
if (flight_mode)
REXUS.sendMsg("WARNING: Flight mode enabled");
else
REXUS.sendMsg("Entering test mode");
break;
case 4: // Run all tests
tests::all_tests();
}
}
Log("DATA (PI1)") << "Unpacked\n\t\"" << std::string(data) << "\"";
//TODO handle incoming commands!
}
}
LO_SIGNAL();
system("sudo reboot");
return 0;
}
<commit_msg>Debugging raspi2<commit_after>/*
* Pi 2 is connected to the ImP/IMU via UART, Camera via CSI, Burn Wire Relay
* via GPIO and Pi 1 via Ethernet and GPIO for LO, SOE and SODS signals.
*
* This program controls most of the main logic and for the PIOneERs mission
* on board REXUS.
*/
#include <stdio.h>
#include <cstdint>
#include <unistd.h> //For sleep
#include <stdlib.h>
#include <iostream>
#include <signal.h>
#include "pins2.h"
#include "camera/camera.h"
#include "UART/UART.h"
#include "Ethernet/Ethernet.h"
#include "comms/pipes.h"
#include "comms/protocol.h"
#include "comms/packet.h"
#include "timing/timer.h"
#include "logger/logger.h"
#include "tests/tests.h"
#include <wiringPi.h>
Logger Log("/Docs/Logs/raspi2");
bool flight_mode = false;
// Global variable for the Camera and IMU
PiCamera Cam;
// Setup for the UART communications
int baud = 230400;
ImP IMP(baud);
comms::Pipe ImP_stream;
// Ethernet communication setup and variables (we are acting as client)
int port_no = 31415; // Random unused port for communication
Raspi2 raspi2(port_no);
/**
* Checks whether input is activated
* @param pin: GPIO to be checked
* @return true or false
*/
bool poll_input(int pin) {
int count = 0;
for (int i = 0; i < 5; i++) {
count += digitalRead(pin);
delayMicroseconds(200);
}
return (count < 3) ? true : false;
}
void signal_handler(int s) {
Log("FATAL") << "Exiting program after signal " << s;
if (Cam.is_running()) {
Cam.stopVideo();
Log("INFO") << "Stopping camera process";
} else {
Log("ERROR") << "Camera process died prematurely or did not start";
}
if (raspi2.is_alive()) {
raspi2.end();
Log("INFO") << "Closed Ethernet communication";
} else {
Log("ERROR") << "Ethernet process died prematurely or did not start";
}
if (&ImP_stream != NULL) {
ImP_stream.close_pipes();
Log("INFO") << "Closed ImP communication";
} else {
Log("ERROR") << "ImP process died prematurely or did not start";
}
digitalWrite(BURNWIRE, 0);
// TODO copy data to a further backup directory
Log("INFO") << "Ending program, Pi rebooting";
system("sudo reboot");
exit(1); // This was an unexpected end so we will exit with an error!
}
int SODS_SIGNAL() {
/*
* When the 'Start of Data Storage' signal is received all data recording
* is stopped (IMU and Camera) and power to the camera is cut off to stop
* shorting due to melting on re-entry. All data is copied into a backup
* directory.
*/
Log("INFO") << "SODS signal received";
if (Cam.is_running()) {
Cam.stopVideo();
Log("INFO") << "Stopping camera process";
} else {
Log("ERROR") << "Camera process died prematurely or did not start";
}
if (raspi2.is_alive()) {
raspi2.end();
Log("INFO") << "Closed Ethernet communication";
} else {
Log("ERROR") << "Ethernet process died prematurely or did not start";
}
if (&ImP_stream != NULL) {
ImP_stream.close_pipes();
Log("INFO") << "Closed ImP communication";
} else {
Log("ERROR") << "ImP process died prematurely or did not start";
}
digitalWrite(BURNWIRE, 0);
digitalWrite(BURNWIRE, 0);
// TODO copy data to a further backup directory
Log("INFO") << "Ending program, Pi rebooting";
system("sudo reboot");
return 0;
}
int SOE_SIGNAL() {
/*
* When the 'Start of Experiment' signal is received the boom needs to be
* deployed and the ImP and IMU to start taking measurements. For boom
* deployment is there is no increase in the encoder count or ?? seconds
* have passed since start of deployment then it is assumed that either the
* boom has reached it's full length or something has gone wrong and the
* count of the encoder is sent to ground.
*/
Log("INFO") << "SOE signal received";
// Setup the ImP and start requesting data
ImP_stream = IMP.startDataCollection("Docs/Data/Pi2/test");
Log("INFO") << "Started data collection from ImP";
comms::Packet p; // Buffer for reading data from the IMU stream
// Trigger the burn wire for 10 seconds!
Log("INFO") << "Triggering burnwire";
digitalWrite(BURNWIRE, 1);
Timer tmr;
Log("INFO") << "Burn wire triggered" << std::endl;
while (tmr.elapsed() < 10000) {
// Get ImP data
int n = ImP_stream.binread(&p, sizeof (p));
if (n > 0) {
Log("DATA (ImP)") << p;
raspi2.sendPacket(p);
}
n = raspi2.recvPacket(p);
if (n > 0)
Log("DATA (PI1)") << p;
Timer::sleep_ms(10);
}
digitalWrite(BURNWIRE, 0);
Log("INFO") << "Burn wire off after " << tmr.elapsed() << " ms";
Log("INFO") << "Waiting for SODS";
// Wait for the next signal to continue the program
bool signal_received = false;
while (!signal_received) {
signal_received = poll_input(SODS);
// Read data from IMU_data_stream and echo it to Ethernet
int n = ImP_stream.binread(&p, sizeof (p));
if (n > 0) {
Log("DATA (ImP)") << p;
raspi2.sendPacket(p);
}
n = raspi2.recvPacket(p);
if (n > 0)
Log("DATA (PI1)") << p;
Timer::sleep_ms(10);
}
return SODS_SIGNAL();
}
int LO_SIGNAL() {
/*
* When the 'Lift Off' signal is received from the REXUS Module the cameras
* are set to start recording video and we then wait to receive the 'Start
* of Experiment' signal (when the nose-cone is ejected)
*/
Log("INFO") << "LO signal received";
Cam.startVideo("Docs/Video/rexus_video");
Log("INFO") << "Camera started recording video";
// Poll the SOE pin until signal is received
Log("INFO") << "Waiting for SOE";
bool signal_received = false;
while (!signal_received) {
Timer::sleep_ms(10);
signal_received = poll_input(SOE);
// TODO Implement communications with RXSM
}
return SOE_SIGNAL();
}
int main() {
/*
* This part of the program is run before the Lift-Off. In effect it
* continually listens for commands from the ground station and runs any
* required tests, regularly reporting status until the LO Signal is
* received.
*/
signal(SIGINT, signal_handler);
// Create necessary directories for saving files
system("mkdir -p Docs/Data/Pi1 Docs/Data/Pi2 Docs/Data/test Docs/Video Docs/Logs");
Log.start_log();
Log("INFO") << "Pi2 is alive";
wiringPiSetup();
// Setup main signal pins
pinMode(LO, INPUT);
pullUpDnControl(LO, PUD_UP);
pinMode(SOE, INPUT);
pullUpDnControl(SOE, PUD_UP);
pinMode(SODS, INPUT);
pullUpDnControl(SODS, PUD_UP);
pinMode(ALIVE, OUTPUT);
Log("INFO") << "Main signal pins setup";
// Setup pins and check whether we are in flight mode
pinMode(LAUNCH_MODE, INPUT);
pullUpDnControl(LAUNCH_MODE, PUD_UP);
flight_mode = digitalRead(LAUNCH_MODE);
Log("INFO") << (flight_mode ? "flight mode enabled" : "test mode enabled");
// Setup Burn Wire
pinMode(BURNWIRE, OUTPUT);
// Setup server and wait for client
digitalWrite(ALIVE, 1);
Log("INFO") << "Waiting for connection from client on port " << port_no;
try {
raspi2.run("Docs/Data/Pi1/backup.txt");
} catch (EthernetException e) {
Log("FATAL") << "Unable to connect to pi 1";
signal_handler(-5);
}
Log("INFO") << "Connection to Pi1 successfil";
Log("INFO") << "Waiting for LO signal";
// Check for LO signal.
std::string msg;
bool signal_received = false;
comms::Packet p;
comms::byte1_t id;
comms::byte2_t index;
char data[16];
while (!signal_received) {
Timer::sleep_ms(10);
signal_received = poll_input(LO);
// TODO Implement communications with Pi 1
int n = raspi2.recvPacket(p);
if (n > 0) {
Log("PI1") << p;
comms::Protocol::unpack(p, id, index, data);
if (id == 0b11000000) {
Log("RXSM") << "Received Command: " << data[0];
switch (data[0]) {
case 1: // restart
Log("INFO") << "Rebooting...";
system("sudo reboot now");
exit(0);
case 2: // shutdown
Log("INFO") << "Shutting down...";
system("sudo shutdown now");
exit(0);
case 3: // Toggle flight mode
Log("INFO") << "Toggling flight mode";
flight_mode = (flight_mode) ? false : true;
Log("INFO") << (flight_mode ? "flight mode enabled" : "test mode enabled");
break;
case 4: // Run all tests
tests::all_tests();
}
}
Log("DATA (PI1)") << "Unpacked\n\t\"" << std::string(data) << "\"";
//TODO handle incoming commands!
}
}
LO_SIGNAL();
system("sudo reboot");
return 0;
}
<|endoftext|>
|
<commit_before>/***************************************
** Tsunagari Tile Engine **
** reader.cpp **
** Copyright 2011-2013 PariahSoft LLC **
***************************************/
// **********
// 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 <errno.h>
#include <stdlib.h>
#include <Gosu/Bitmap.hpp>
#include <Gosu/Image.hpp>
#include <Gosu/IO.hpp>
#include <map>
#include <physfs.h>
#include "cache-template.cpp"
#include "client-conf.h"
#include "formatter.h"
#include "log.h"
#include "python.h"
#include "python-bindings-template.cpp"
#include "reader.h"
#include "script.h"
#include "window.h"
#include "xml.h"
#define ASSERT(x) if (!(x)) { return false; }
typedef std::shared_ptr<xmlDtd> DTDRef;
typedef std::shared_ptr<std::string> StringRef;
// Caches that store processed, game-ready objects. Garbage collected.
Cache<ImageRef> images;
Cache<TiledImageRef> tiles;
Cache<SampleRef> sounds;
Cache<XMLRef> xmls;
Cache<StringRef> texts;
// DTDs don't expire. No garbage collection.
typedef std::map<std::string, DTDRef> DTDMap;
DTDMap dtds;
static std::string path(const std::string& entryName)
{
// XXX: archive might not be world
return conf.worldFilename + "/" + entryName;
}
template <class T>
static bool readFromDisk(const std::string& name, T& buf)
{
PHYSFS_sint64 size;
PHYSFS_File* zf;
if (!PHYSFS_exists(name.c_str())) {
Log::err("Reader", Formatter("%: file missing")
% path(name));
return false;
}
zf = PHYSFS_openRead(name.c_str());
if (!zf) {
Log::err("Reader", Formatter("%: error opening file: %")
% path(name) % PHYSFS_getLastError());
return false;
}
size = PHYSFS_fileLength(zf);
if (size == -1) {
Log::err("Reader", Formatter("%: could not determine file size: %")
% path(name) % PHYSFS_getLastError());
PHYSFS_close(zf);
return false;
}
if (size > std::numeric_limits<uint32_t>::max()) {
// FIXME: Technically, we just need to issue multiple calls to
// PHYSFS_read. Fix when needed.
Log::err("Reader", Formatter("%: file too long (>4GB)")
% path(name));
PHYSFS_close(zf);
return false;
}
buf.resize(size);
if (size == 0) {
PHYSFS_close(zf);
return true;
}
if (PHYSFS_read(zf, (char*)(buf.data()),
(PHYSFS_uint32)size, 1) != 1) {
Log::err("Reader", Formatter("%: error reading file: %")
% path(name) % PHYSFS_getLastError());
PHYSFS_close(zf);
return false;
}
PHYSFS_close(zf);
return true;
}
// FIXME: Should be moved to xml.cpp!!!!!!
static DTDRef parseDTD(const std::string& path)
{
xmlCharEncoding enc = XML_CHAR_ENCODING_NONE;
std::string bytes = Reader::readString(path);
if (bytes.empty())
return DTDRef();
xmlParserInputBuffer* input = xmlParserInputBufferCreateMem(
bytes.c_str(), (int)bytes.size(), enc);
if (!input)
return DTDRef();
xmlDtd* dtd = xmlIOParseDTD(NULL, input, enc);
if (!dtd)
return DTDRef();
return DTDRef(dtd, xmlFreeDtd);
}
// FIXME: Should be moved to xml.cpp!!!!!!
static bool preloadDTDs()
{
ASSERT(dtds["dtd/area.dtd"] = parseDTD("dtd/area.dtd"));
ASSERT(dtds["dtd/entity.dtd"] = parseDTD("dtd/entity.dtd"));
ASSERT(dtds["dtd/tsx.dtd"] = parseDTD("dtd/tsx.dtd"));
ASSERT(dtds["dtd/world.dtd"] = parseDTD("dtd/world.dtd"));
return true;
}
static xmlDtd* getDTD(const std::string& name)
{
DTDMap::iterator it = dtds.find(name);
return it == dtds.end() ? NULL : it->second.get();
}
static XMLDoc* readXMLDoc(const std::string& name,
const std::string& dtdPath)
{
std::string p = path(name);
std::string data = Reader::readString(name);
xmlDtd* dtd = getDTD(dtdPath);
if (!dtd || data.empty())
return NULL;
XMLDoc* doc = new XMLDoc;
if (!doc->init(p, data, dtd)) {
delete doc;
return NULL;
}
return doc;
}
static bool callInitpy(const std::string& archivePath)
{
ASSERT(Reader::prependPath(archivePath));
bool exists = Reader::resourceExists("__init__.py");
Log::info(archivePath,
std::string("__init__.py: ") +
(exists ? "found" : "not found"));
if (exists)
// FIXME: Python will cache the __init__ module with no path prefix
ASSERT(Script::create("__init__"));
ASSERT(Reader::rmPath(archivePath));
return true;
}
bool Reader::init(char* argv0)
{
ASSERT(PHYSFS_init(argv0) != 0);
// If any of our archives contain a file called "__init__.py", call it.
for (Conf::StringVector::const_iterator it = conf.dataPath.begin(); it != conf.dataPath.end(); it++) {
const std::string archive = *it;
ASSERT(callInitpy(archive));
}
ASSERT(callInitpy(BASE_ZIP_PATH));
ASSERT(prependPath(BASE_ZIP_PATH));
// DTDs must be loaded from BASE_ZIP. They cannot be allowed to be
// loaded from the world.
ASSERT(preloadDTDs());
ASSERT(prependPath(conf.worldFilename));
for (Conf::StringVector::const_iterator it = conf.dataPath.begin(); it != conf.dataPath.end(); it++) {
const std::string archive = *it;
ASSERT(prependPath(archive));
}
return true;
}
void Reader::deinit()
{
PHYSFS_deinit();
}
bool Reader::prependPath(const std::string& path)
{
int err = PHYSFS_mount(path.c_str(), NULL, 0);
if (err == 0) {
Log::fatal("Reader", Formatter("%: could not open archive: %")
% path % PHYSFS_getLastError());
return false;
}
pythonPrependPath(path);
return true;
}
bool Reader::appendPath(const std::string& path)
{
int err = PHYSFS_mount(path.c_str(), NULL, 1);
if (err == 0) {
Log::fatal("Reader", Formatter("%: could not open archive: %")
% path % PHYSFS_getLastError());
return false;
}
pythonRmPath(path);
return true;
}
bool Reader::rmPath(const std::string& path)
{
int err = PHYSFS_removeFromSearchPath(path.c_str());
if (err == 0) {
Log::err("Reader", Formatter("libphysfs: %: %")
% path % PHYSFS_getLastError());
return false;
}
return true;
}
bool Reader::resourceExists(const std::string& name)
{
return PHYSFS_exists(name.c_str());
}
bool Reader::directoryExists(const std::string& name)
{
return resourceExists(name) && PHYSFS_isDirectory(name.c_str());
}
bool Reader::fileExists(const std::string& name)
{
return resourceExists(name) && !PHYSFS_isDirectory(name.c_str());
}
Gosu::Buffer* Reader::readBuffer(const std::string& name)
{
Gosu::Buffer* buf = new Gosu::Buffer();
if (readFromDisk(name, *buf)) {
return buf;
}
else {
delete buf;
return NULL;
}
}
std::string Reader::readString(const std::string& name)
{
std::string str;
return readFromDisk(name, str) ? str : "";
}
ImageRef Reader::getImage(const std::string& name)
{
ImageRef existing = images.lifetimeRequest(name);
if (existing)
return existing;
std::unique_ptr<Gosu::Buffer> buffer(readBuffer(name));
if (!buffer)
return ImageRef();
ImageRef result(Image::create(buffer->data(), buffer->size()));
if (!result)
return ImageRef();
images.lifetimePut(name, result);
return result;
}
TiledImageRef Reader::getTiledImage(const std::string& name,
int w, int h)
{
TiledImageRef existing = tiles.momentaryRequest(name);
if (existing)
return existing;
std::unique_ptr<Gosu::Buffer> buffer(readBuffer(name));
if (!buffer)
return TiledImageRef();
TiledImageRef result(
TiledImage::create(buffer->data(), buffer->size(), w, h)
);
if (!result)
return TiledImageRef();
tiles.momentaryPut(name, result);
return result;
}
SampleRef Reader::getSample(const std::string& name)
{
if (!conf.audioEnabled)
return SampleRef();
SampleRef existing = sounds.lifetimeRequest(name);
if (existing)
return existing;
std::unique_ptr<Gosu::Buffer> buffer(readBuffer(name));
if (!buffer)
return SampleRef();
SampleRef result(new Sound(new Gosu::Sample(buffer->frontReader())));
sounds.lifetimePut(name, result);
return result;
}
XMLRef Reader::getXMLDoc(const std::string& name,
const std::string& dtdFile)
{
XMLRef existing = xmls.momentaryRequest(name);
if (existing)
return existing;
XMLRef result(readXMLDoc(name, dtdFile));
xmls.momentaryPut(name, result);
return result;
}
std::string Reader::getText(const std::string& name)
{
StringRef existing = texts.momentaryRequest(name);
if (existing)
return *existing.get();
StringRef result(new std::string(readString(name)));
texts.momentaryPut(name, result);
return *result.get();
}
void Reader::garbageCollect()
{
images.garbageCollect();
tiles.garbageCollect();
sounds.garbageCollect();
// songs.garbageCollect();
xmls.garbageCollect();
texts.garbageCollect();
}
void exportReader()
{
// FIXME: Broken with shift to singleton. No instantiated object to bind.
// Fix will require a stub object.
#if 0
using namespace boost::python;
class_<Reader>("Reader", no_init)
.def("resource_exists", &Reader::resourceExists)
.def("run_python_script", &Reader::runPythonScript)
.def("get_text", &Reader::getText);
pythonSetGlobal("Reader");
#endif
}
<commit_msg>reader.cpp: label global vars with 'static'<commit_after>/***************************************
** Tsunagari Tile Engine **
** reader.cpp **
** Copyright 2011-2013 PariahSoft LLC **
***************************************/
// **********
// 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 <errno.h>
#include <stdlib.h>
#include <Gosu/Bitmap.hpp>
#include <Gosu/Image.hpp>
#include <Gosu/IO.hpp>
#include <map>
#include <physfs.h>
#include "cache-template.cpp"
#include "client-conf.h"
#include "formatter.h"
#include "log.h"
#include "python.h"
#include "python-bindings-template.cpp"
#include "reader.h"
#include "script.h"
#include "window.h"
#include "xml.h"
#define ASSERT(x) if (!(x)) { return false; }
typedef std::shared_ptr<xmlDtd> DTDRef;
typedef std::shared_ptr<std::string> StringRef;
// Caches that store processed, game-ready objects. Garbage collected.
static Cache<ImageRef> images;
static Cache<TiledImageRef> tiles;
static Cache<SampleRef> sounds;
static Cache<XMLRef> xmls;
static Cache<StringRef> texts;
// DTDs don't expire. No garbage collection.
typedef std::map<std::string, DTDRef> DTDMap;
static DTDMap dtds;
static std::string path(const std::string& entryName)
{
// XXX: archive might not be world
return conf.worldFilename + "/" + entryName;
}
template <class T>
static bool readFromDisk(const std::string& name, T& buf)
{
PHYSFS_sint64 size;
PHYSFS_File* zf;
if (!PHYSFS_exists(name.c_str())) {
Log::err("Reader", Formatter("%: file missing")
% path(name));
return false;
}
zf = PHYSFS_openRead(name.c_str());
if (!zf) {
Log::err("Reader", Formatter("%: error opening file: %")
% path(name) % PHYSFS_getLastError());
return false;
}
size = PHYSFS_fileLength(zf);
if (size == -1) {
Log::err("Reader", Formatter("%: could not determine file size: %")
% path(name) % PHYSFS_getLastError());
PHYSFS_close(zf);
return false;
}
if (size > std::numeric_limits<uint32_t>::max()) {
// FIXME: Technically, we just need to issue multiple calls to
// PHYSFS_read. Fix when needed.
Log::err("Reader", Formatter("%: file too long (>4GB)")
% path(name));
PHYSFS_close(zf);
return false;
}
buf.resize(size);
if (size == 0) {
PHYSFS_close(zf);
return true;
}
if (PHYSFS_read(zf, (char*)(buf.data()),
(PHYSFS_uint32)size, 1) != 1) {
Log::err("Reader", Formatter("%: error reading file: %")
% path(name) % PHYSFS_getLastError());
PHYSFS_close(zf);
return false;
}
PHYSFS_close(zf);
return true;
}
// FIXME: Should be moved to xml.cpp!!!!!!
static DTDRef parseDTD(const std::string& path)
{
xmlCharEncoding enc = XML_CHAR_ENCODING_NONE;
std::string bytes = Reader::readString(path);
if (bytes.empty())
return DTDRef();
xmlParserInputBuffer* input = xmlParserInputBufferCreateMem(
bytes.c_str(), (int)bytes.size(), enc);
if (!input)
return DTDRef();
xmlDtd* dtd = xmlIOParseDTD(NULL, input, enc);
if (!dtd)
return DTDRef();
return DTDRef(dtd, xmlFreeDtd);
}
// FIXME: Should be moved to xml.cpp!!!!!!
static bool preloadDTDs()
{
ASSERT(dtds["dtd/area.dtd"] = parseDTD("dtd/area.dtd"));
ASSERT(dtds["dtd/entity.dtd"] = parseDTD("dtd/entity.dtd"));
ASSERT(dtds["dtd/tsx.dtd"] = parseDTD("dtd/tsx.dtd"));
ASSERT(dtds["dtd/world.dtd"] = parseDTD("dtd/world.dtd"));
return true;
}
static xmlDtd* getDTD(const std::string& name)
{
DTDMap::iterator it = dtds.find(name);
return it == dtds.end() ? NULL : it->second.get();
}
static XMLDoc* readXMLDoc(const std::string& name,
const std::string& dtdPath)
{
std::string p = path(name);
std::string data = Reader::readString(name);
xmlDtd* dtd = getDTD(dtdPath);
if (!dtd || data.empty())
return NULL;
XMLDoc* doc = new XMLDoc;
if (!doc->init(p, data, dtd)) {
delete doc;
return NULL;
}
return doc;
}
static bool callInitpy(const std::string& archivePath)
{
ASSERT(Reader::prependPath(archivePath));
bool exists = Reader::resourceExists("__init__.py");
Log::info(archivePath,
std::string("__init__.py: ") +
(exists ? "found" : "not found"));
if (exists)
// FIXME: Python will cache the __init__ module with no path prefix
ASSERT(Script::create("__init__"));
ASSERT(Reader::rmPath(archivePath));
return true;
}
bool Reader::init(char* argv0)
{
ASSERT(PHYSFS_init(argv0) != 0);
// If any of our archives contain a file called "__init__.py", call it.
for (Conf::StringVector::const_iterator it = conf.dataPath.begin(); it != conf.dataPath.end(); it++) {
const std::string archive = *it;
ASSERT(callInitpy(archive));
}
ASSERT(callInitpy(BASE_ZIP_PATH));
ASSERT(prependPath(BASE_ZIP_PATH));
// DTDs must be loaded from BASE_ZIP. They cannot be allowed to be
// loaded from the world.
ASSERT(preloadDTDs());
ASSERT(prependPath(conf.worldFilename));
for (Conf::StringVector::const_iterator it = conf.dataPath.begin(); it != conf.dataPath.end(); it++) {
const std::string archive = *it;
ASSERT(prependPath(archive));
}
return true;
}
void Reader::deinit()
{
PHYSFS_deinit();
}
bool Reader::prependPath(const std::string& path)
{
int err = PHYSFS_mount(path.c_str(), NULL, 0);
if (err == 0) {
Log::fatal("Reader", Formatter("%: could not open archive: %")
% path % PHYSFS_getLastError());
return false;
}
pythonPrependPath(path);
return true;
}
bool Reader::appendPath(const std::string& path)
{
int err = PHYSFS_mount(path.c_str(), NULL, 1);
if (err == 0) {
Log::fatal("Reader", Formatter("%: could not open archive: %")
% path % PHYSFS_getLastError());
return false;
}
pythonRmPath(path);
return true;
}
bool Reader::rmPath(const std::string& path)
{
int err = PHYSFS_removeFromSearchPath(path.c_str());
if (err == 0) {
Log::err("Reader", Formatter("libphysfs: %: %")
% path % PHYSFS_getLastError());
return false;
}
return true;
}
bool Reader::resourceExists(const std::string& name)
{
return PHYSFS_exists(name.c_str());
}
bool Reader::directoryExists(const std::string& name)
{
return resourceExists(name) && PHYSFS_isDirectory(name.c_str());
}
bool Reader::fileExists(const std::string& name)
{
return resourceExists(name) && !PHYSFS_isDirectory(name.c_str());
}
Gosu::Buffer* Reader::readBuffer(const std::string& name)
{
Gosu::Buffer* buf = new Gosu::Buffer();
if (readFromDisk(name, *buf)) {
return buf;
}
else {
delete buf;
return NULL;
}
}
std::string Reader::readString(const std::string& name)
{
std::string str;
return readFromDisk(name, str) ? str : "";
}
ImageRef Reader::getImage(const std::string& name)
{
ImageRef existing = images.lifetimeRequest(name);
if (existing)
return existing;
std::unique_ptr<Gosu::Buffer> buffer(readBuffer(name));
if (!buffer)
return ImageRef();
ImageRef result(Image::create(buffer->data(), buffer->size()));
if (!result)
return ImageRef();
images.lifetimePut(name, result);
return result;
}
TiledImageRef Reader::getTiledImage(const std::string& name,
int w, int h)
{
TiledImageRef existing = tiles.momentaryRequest(name);
if (existing)
return existing;
std::unique_ptr<Gosu::Buffer> buffer(readBuffer(name));
if (!buffer)
return TiledImageRef();
TiledImageRef result(
TiledImage::create(buffer->data(), buffer->size(), w, h)
);
if (!result)
return TiledImageRef();
tiles.momentaryPut(name, result);
return result;
}
SampleRef Reader::getSample(const std::string& name)
{
if (!conf.audioEnabled)
return SampleRef();
SampleRef existing = sounds.lifetimeRequest(name);
if (existing)
return existing;
std::unique_ptr<Gosu::Buffer> buffer(readBuffer(name));
if (!buffer)
return SampleRef();
SampleRef result(new Sound(new Gosu::Sample(buffer->frontReader())));
sounds.lifetimePut(name, result);
return result;
}
XMLRef Reader::getXMLDoc(const std::string& name,
const std::string& dtdFile)
{
XMLRef existing = xmls.momentaryRequest(name);
if (existing)
return existing;
XMLRef result(readXMLDoc(name, dtdFile));
xmls.momentaryPut(name, result);
return result;
}
std::string Reader::getText(const std::string& name)
{
StringRef existing = texts.momentaryRequest(name);
if (existing)
return *existing.get();
StringRef result(new std::string(readString(name)));
texts.momentaryPut(name, result);
return *result.get();
}
void Reader::garbageCollect()
{
images.garbageCollect();
tiles.garbageCollect();
sounds.garbageCollect();
// songs.garbageCollect();
xmls.garbageCollect();
texts.garbageCollect();
}
void exportReader()
{
// FIXME: Broken with shift to singleton. No instantiated object to bind.
// Fix will require a stub object.
#if 0
using namespace boost::python;
class_<Reader>("Reader", no_init)
.def("resource_exists", &Reader::resourceExists)
.def("run_python_script", &Reader::runPythonScript)
.def("get_text", &Reader::getText);
pythonSetGlobal("Reader");
#endif
}
<|endoftext|>
|
<commit_before>#include <queue>
#include <cstring>
#include <iostream>
#include <vector>
#include <string.h>
#include <unistd.h>
#include <boost/tokenizer.hpp>
#include <boost/algorithm/string.hpp>
#include <sys/utsname.h>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;
using namespace boost;
// Cases to test:
// cd Desktop&&ls -a
// cd Desktop&[ENTER] ls -a
// cd Desktop;ls -a
// cd Desktop;ls
// ls;ls;ls;ls
// cd Desktop & ls -a
// cd Desktop;
// ls;
// cd Desktop||ls -a;vim touch.cpp&&[ENTER] ls -a
// cd Desktop
// ; clear
// && ls
// || ls -a
// NOTE: cd will NOT be tested or used!
// Re-read specs if unsure!!
// prints user and machine info
void pcmd_prompt() {
string login(getlogin());
struct utsname hostname;
uname(&hostname);
string nodeName(hostname.nodename);
cout << login << "@" << nodeName << "$ ";
}
// parses input into queue for execution
void parse_into_queue(queue<string> &l, const string &s) {
char_separator<char> delim(" ", ";&|#") ;
tokenizer<char_separator<char>> mytok(s, delim);
for (auto i = mytok.begin(); i != mytok.end(); ++i) {
l.push(*i);
}
}
// for testing purposes
void print_queue (queue<string> q) {
if (q.empty()) {
return;
}
while (!q.empty()) {
cout << "[" << q.front() << "] ";
q.pop();
}
cout << endl;
}
// for testing purposes
void qinfo(queue<string> q) {
cout << "Size: " << q.size() << endl;
print_queue(q);
}
// reinitializes v with q until connector
void parse_connectors(vector<string> &v, queue<string> &q) {
while (!q.empty() && q.front() != "&" && q.front() != "|" && q.front() != ";" && q.front() != "#")
{
v.push_back(q.front());
q.pop();
}
}
bool cmd_exit(vector<string> &v) {
if (iequals(v.at(0), "exit")) {
return true;
}
return false;
}
void to_arr_cstring(vector<string> &s, vector<char*> &cs) {
for (auto i = 0; i != s.size(); ++i) {
cs[i] = &s[i][0];
}
}
// exec cmd and if success
bool begin_exec(vector<char*> &cs) {
int status;
int pid = fork();
if (pid < 0) { // error
perror("FORK");
_exit(-1);
}
else if (pid == 0) { // child
cout << "child process" << endl;
if (-1 == execvp(cs[0], cs.data())) {
perror("EXEC");
_exit(-1);
}
_exit(0);
}
else if (pid > 0) { // parent
if (-1 == wait(&status)) {
perror("WAIT");
}
if (status != 0) {
return false;
}
}
return true;
}
// checks connector logic
bool connect_success(bool status, queue<string> &q) {
if (!q.empty() && q.front() == "&") {
q.pop();
if (!q.empty() && q.front() == "&") {
q.pop();
if (!status) {
return false;
}
else {
return true;
}
}
else if (q.empty()) {
cout << "Syntax error: incorrect usage of \"&&\"" << endl;
return false;
}
else {
cout << "Syntax error: incorrect usage of \"&&\"" << endl;
return false;
}
}
else if (!q.empty() && q.front() == "|") {
q.pop();
if (!q.empty() && q.front() == "|") {
q.pop();
if (status) {
return false;
}
else {
return true;
}
}
else if (q.empty()) {
cout << "Syntax error: incorrect usage of \"||\"" << endl;
return false;
}
else {
cout << "Syntax error: incorrect usage of \"||\"" << endl;
return false;
}
}
else if (!q.empty() && q.front() == ";") {
q.pop();
return true;
}
else if (!q.empty() && q.front() == "#") {
return false;
}
else if (!q.empty()) {
cout << "Syntax error: " << q.front() << " is not a valid connector!" << endl;
return false;
}
else {
cout << "done" << endl;
return false;
}
}
int main(int argc, char* argv[]) {
while (1) {
string cmd_input;
queue<string> list;
pcmd_prompt();
getline(cin, cmd_input);
parse_into_queue(list, cmd_input);
vector<string> cmd;
while (!list.empty()) {
qinfo(list); // debugger
bool exec_success = false;
if (list.front() == "#") {
break;
}
parse_connectors(cmd, list);
if (cmd.size() == 0) {
cout << "Syntax error: formatting issue in command" << endl;
break;
}
else if (cmd_exit(cmd)) {
cout << "Exiting RShell" << endl;
return 0;
}
else {
vector<char*> cmd_cstring(cmd.size() + 1);
to_arr_cstring(cmd, cmd_cstring);
exec_success = begin_exec(cmd_cstring);
}
if (!connect_success(exec_success, list)) {
break;
}
cmd.clear();
}
}
return 0;
}
<commit_msg>segfault at pcmd_prompt when using script cmd<commit_after>#include <queue>
#include <cstring>
#include <iostream>
#include <vector>
#include <unistd.h>
#include <boost/tokenizer.hpp>
#include <boost/algorithm/string.hpp>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;
using namespace boost;
// Cases to test:
// cd Desktop&&ls -a
// cd Desktop&[ENTER] ls -a
// cd Desktop;ls -a
// cd Desktop;ls
// ls;ls;ls;ls
// cd Desktop & ls -a
// cd Desktop;
// ls;
// cd Desktop||ls -a;vim touch.cpp&&[ENTER] ls -a
// cd Desktop
// ; clear
// && ls
// || ls -a
// NOTE: cd will NOT be tested or used!
// Re-read specs if unsure!!
// prints user and machine info
void pcmd_prompt() {
string login;
login = getlogin();
if (login.empty()) {
perror("GETLOGIN");
}
char host_arr[1024];
host_arr[1023] = '\0';
if (gethostname(host_arr, 1023) == -1) {
perror("GETHOSTNAME");
}
cout << login << "@" << host_arr << "$ ";
}
// parses input into queue for execution
void parse_into_queue(queue<string> &l, const string &s) {
char_separator<char> delim(" ", ";&|#") ;
tokenizer<char_separator<char>> mytok(s, delim);
for (auto i = mytok.begin(); i != mytok.end(); ++i) {
l.push(*i);
}
}
// for testing purposes
void print_queue (queue<string> q) {
if (q.empty()) {
return;
}
while (!q.empty()) {
cout << "[" << q.front() << "] ";
q.pop();
}
cout << endl;
}
// for testing purposes
void qinfo(queue<string> &q) {
cout << "Size: " << q.size() << endl;
print_queue(q);
}
// reinitializes v with q until connector
void parse_connectors(vector<string> &v, queue<string> &q) {
while (!q.empty() && q.front() != "&" && q.front() != "|" && q.front() != ";" && q.front() != "#")
{
v.push_back(q.front());
q.pop();
}
}
bool cmd_exit(vector<string> &v) {
if (iequals(v.at(0), "exit")) {
return true;
}
return false;
}
void to_arr_cstring(vector<string> &s, vector<char*> &cs) {
for (auto i = 0; i != s.size(); ++i) {
cs[i] = &s[i][0];
}
}
// exec cmd and if success
bool begin_exec(vector<char*> &cs) {
int status;
int pid = fork();
if (pid < 0) { // error
perror("FORK");
_exit(-1);
}
else if (pid == 0) { // child
cout << "child process" << endl;
if (-1 == execvp(cs[0], cs.data())) {
perror("EXEC");
_exit(-1);
}
_exit(0);
}
else if (pid > 0) { // parent
if (-1 == wait(&status)) {
perror("WAIT");
}
if (status != 0) {
return false;
}
}
return true;
}
// checks connector logic
bool connect_success(bool status, queue<string> &q) {
if (!q.empty() && q.front() == "&") {
q.pop();
if (!q.empty() && q.front() == "&") {
q.pop();
if (!status) {
return false;
}
else {
return true;
}
}
else if (q.empty()) {
cout << "Syntax error: incorrect usage of \"&&\"" << endl;
return false;
}
else {
cout << "Syntax error: incorrect usage of \"&&\"" << endl;
return false;
}
}
else if (!q.empty() && q.front() == "|") {
q.pop();
if (!q.empty() && q.front() == "|") {
q.pop();
if (status) {
return false;
}
else {
return true;
}
}
else if (q.empty()) {
cout << "Syntax error: incorrect usage of \"||\"" << endl;
return false;
}
else {
cout << "Syntax error: incorrect usage of \"||\"" << endl;
return false;
}
}
else if (!q.empty() && q.front() == ";") {
q.pop();
return true;
}
else if (!q.empty() && q.front() == "#") {
return false;
}
else if (!q.empty()) {
cout << "Syntax error: " << q.front() << " is not a valid connector!" << endl;
return false;
}
else {
// cout << "done" << endl;
return false;
}
}
int main(){
while (1) {
string cmd_input;
queue<string> list;
pcmd_prompt();
getline(cin, cmd_input);
parse_into_queue(list, cmd_input);
vector<string> cmd;
while (!list.empty()) {
// qinfo(list); // debugger
bool exec_success = false;
if (list.front() == "#") {
break;
}
parse_connectors(cmd, list);
if (cmd.size() == 0) {
cout << "Syntax error: formatting issue in command" << endl;
break;
}
else if (cmd_exit(cmd)) {
cout << "Exiting RShell" << endl;
return 0;
}
else {
vector<char*> cmd_cstring(cmd.size() + 1);
to_arr_cstring(cmd, cmd_cstring);
exec_success = begin_exec(cmd_cstring);
}
if (!connect_success(exec_success, list)) {
break;
}
cmd.clear();
}
}
return 0;
}
<|endoftext|>
|
<commit_before>#include<iostream>
#include<sstream>
#include<stdio.h>
#include<boost/tokenizer.hpp>
#include<errno.h>
#include<string>
#include<string.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<sys/unistd.h>
using namespace std;
using namespace boost;
typedef tokenizer<char_separator<char> > Tok;
void readCommands(string str);
int conjunct(int n, stringstream& ss, const Tok::iterator &it);
void skipCommand(Tok::iterator &it, Tok &tokens);
void splitString(char** args, stringstream& ss, int n);
int main(){
cout << endl;
string str;
string usrname = getlogin();
char hostname[128];
int success = gethostname(hostname, sizeof hostname);
string userinfo = "";
if(usrname != "\0" && success == 0){
userinfo = usrname + "@" + hostname;
}
bool notExited = true;
while(notExited){
cout << userinfo << "$ ";
getline(cin, str);
readCommands(str);
}
return 0;
}
void readCommands(string str){
char_separator<char> sep("\" ", ";#|&");
Tok tokens(str, sep);
stringstream ss;
int n = 0;
for(Tok::iterator it = tokens.begin(); it != tokens.end(); it++){
if(*it == "#"){
conjunct(n, ss, it);
return;
}
else if(*it == ";"){
conjunct(n, ss, it);
n = 0;
it++;
if(it == tokens.end()) break;
}
else if(*it == "&"){
if(conjunct(n, ss, it) == -1){
skipCommand(it, tokens);
}
n = 0;
if(it == tokens.end()) break;
it++;
}
else if(*it == "|"){
if(conjunct(n, ss, it) != -1){
skipCommand(it, tokens);
}
n = 0;
if(it == tokens.end()) break;
it++;
}
if(*it != "&" && *it != "|"){
ss << *it;
ss << " ";
n++;
}
}
if(n > 0){
Tok::iterator it = tokens.begin();
conjunct(n, ss, it);
}
}
int conjunct(int n, stringstream& ss, const Tok::iterator &it){
if(n == 0 && *it != "#"){
cerr << "Bash: syntax error near unexpected token \'" << *it << "\'" << endl;
return -2;
}
else if(n == 0 && *it == "#") return 0;
char** args = new char*[n + 1];
splitString(args, ss, n);
int pid = fork();
if(pid == -1){
perror("There was an error with the fork().");
exit(1);
}
else if(pid == 0){
if(-1 == execvp((const char*) args[0], (char* const*) args)){
perror(args[0]);
exit(1);
}
}
else if(pid > 0){
if(-1 == wait(0)){
perror("There was an error with wait().");
return -1;
}
}
return 0;
}
void skipCommand(Tok::iterator &it, Tok &tokens){
while(it != tokens.end() && *it != ";"){
it++;
}
}
void splitString(char** args, stringstream& ss, int n){
string *str = new string[n];
for(int i = 0; i < n; i++){
ss >> str[i];
args[i] = (char*) str[i].c_str();
}
args[n] = NULL;
char exitC[] = "exit";
if(strcmp(args[0], exitC) == 0){
cout << endl;
exit(0);
}
delete[] str;
}
<commit_msg>updated rshell.cpp to delete dynamically allocated memory in conjunct() function<commit_after>#include<iostream>
#include<sstream>
#include<stdio.h>
#include<boost/tokenizer.hpp>
#include<errno.h>
#include<string>
#include<string.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<sys/unistd.h>
using namespace std;
using namespace boost;
typedef tokenizer<char_separator<char> > Tok;
void readCommands(string str);
int conjunct(int n, stringstream& ss, const Tok::iterator &it);
void skipCommand(Tok::iterator &it, Tok &tokens);
void splitString(char** args, stringstream& ss, int n);
int main(){
cout << endl;
string str;
string usrname = getlogin();
char hostname[128];
int success = gethostname(hostname, sizeof hostname);
string userinfo = "";
if(usrname != "\0" && success == 0){
userinfo = usrname + "@" + hostname;
}
bool notExited = true;
while(notExited){
cout << userinfo << "$ ";
getline(cin, str);
readCommands(str);
}
return 0;
}
void readCommands(string str){
char_separator<char> sep("\" ", ";#|&");
Tok tokens(str, sep);
stringstream ss;
int n = 0;
for(Tok::iterator it = tokens.begin(); it != tokens.end(); it++){
if(*it == "#"){
conjunct(n, ss, it);
return;
}
else if(*it == ";"){
conjunct(n, ss, it);
n = 0;
it++;
if(it == tokens.end()) break;
}
else if(*it == "&"){
if(conjunct(n, ss, it) == -1){
skipCommand(it, tokens);
}
n = 0;
if(it == tokens.end()) break;
it++;
}
else if(*it == "|"){
if(conjunct(n, ss, it) != -1){
skipCommand(it, tokens);
}
n = 0;
if(it == tokens.end()) break;
it++;
}
if(*it != "&" && *it != "|"){
ss << *it;
ss << " ";
n++;
}
}
if(n > 0){
Tok::iterator it = tokens.begin();
conjunct(n, ss, it);
}
}
int conjunct(int n, stringstream& ss, const Tok::iterator &it){
if(n == 0 && *it != "#"){
cerr << "Bash: syntax error near unexpected token \'" << *it << "\'" << endl;
return -2;
}
else if(n == 0 && *it == "#") return 0;
char** args = new char*[n + 1];
splitString(args, ss, n);
int pid = fork();
if(pid == -1){
perror("There was an error with the fork().");
exit(1);
}
else if(pid == 0){
if(-1 == execvp((const char*) args[0], (char* const*) args)){
perror(args[0]);
exit(1);
}
}
else if(pid > 0){
if(-1 == wait(0)){
perror("There was an error with wait().");
return -1;
}
}
delete[] args;
return 0;
}
void skipCommand(Tok::iterator &it, Tok &tokens){
while(it != tokens.end() && *it != ";"){
it++;
}
}
void splitString(char** args, stringstream& ss, int n){
string *str = new string[n];
for(int i = 0; i < n; i++){
ss >> str[i];
args[i] = (char*) str[i].c_str();
}
args[n] = NULL;
char exitC[] = "exit";
if(strcmp(args[0], exitC) == 0){
cout << endl;
exit(0);
}
delete[] str;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <errno.h>
#include <vector>
#include "comParse.h"
#include <cstring>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
using namespace boost;
using namespace std;
struct redirect;
bool redirection(char** argv, redirect& rdts, const int fd);
struct redirect {
bool doI_Rdct; // input redirect
int indexIR;
int savedSTDIN; // for duping STDIN and saving it
int rfd; // when opening new fd in 0 for reading
bool doO_Rdct; // output redirect
int indexOR;
int savedSTDOUT; // for duping STDOUT and saving it
int wofd; // when opening new fd in 1 for writing
bool doE_Rdct; // output redirect
int indexER;
int savedSTDERR; // for duping STDERR and saving it
int wefd; // when opening new fd in 2 for writing
vector<int*> currentFD;
redirect() {
doI_Rdct = false;
savedSTDIN = -1;
rfd = -1;
indexIR = -1;
doO_Rdct = false;
savedSTDOUT = -1;
wofd = -1;
indexOR = -1;
doE_Rdct = false;
savedSTDERR = -1;
wefd = -1;
indexER = -1;
}
void closeCurrFDs() {
if (!currentFD.empty()) {
for (vector<int*>::iterator it = currentFD.begin();
it != currentFD.end(); it++) {
if (-1 == close(*(*it))) {
perror("close");
exit(-1);
}
}
currentFD.clear();
}
}
~redirect() {
//closeCurrFDs();
}
};
int main() {
while (true) {
char** argv = NULL;
vector<char*> commands;
comParse comPr;
do {
cerr << "$ " << flush;
string input = "";
getline(cin, input); // Get command
commands = comPr.parseLine(input);
} while (commands.size() == 1); // if empty line, repeat req for command. sz 1 = just NULL delim.
argv = &commands[0];
redirect rdts;
for (unsigned int i = 0; i < commands.size() - 1; i++) { // NULL at end
if ( strcmp(commands.at(i), ";") == 0
|| strcmp(commands.at(i), "0<")) {
delete[] commands.at(i);
argv[i] = NULL;
break;
} else if (strcmp(commands.at(i), "<") == 0) {
delete[] commands.at(i);
argv[i] = NULL;
rdts.doI_Rdct = true;
rdts.indexIR = i;
} else if (strcmp(commands.at(i), ">") == 0
|| strcmp(commands.at(i), "1>") == 0) {
delete[] commands.at(i);
argv[i] = NULL;
rdts.doO_Rdct = true;
rdts.indexOR = i;
} else if (strcmp(commands.at(i), "2>") == 0) {
delete[] commands.at(i);
argv[i] = NULL;
rdts.doE_Rdct = true;
rdts.indexER = i;
}
}
/* Confusing as heck, let me explain!
* char const* means pointer to a constant char
* so char const* const means a const pointer to a const char
* and char const* const* means a const pointer to a const char pointer!
* (Read declarations from right to left to make it make sense -
* char const* = POINTER (*) to a CONST CHAR)
*/
//char const* const* c_arr = &commands[0]; // even if Not necessary: keep as really cool discovery!
bool doExec = true; // If false, do not fork and exec command
char ex[5] = "exit";
if (strcmp(argv[0], ex) == 0) {
comPr.deleteCStrings(commands); // Has heap allocated memory, always should be dealt with
return 0; // EXIT command
}
if (rdts.doI_Rdct) doExec = redirection(argv, rdts, STDIN_FILENO);
if (rdts.doO_Rdct) doExec = redirection(argv, rdts, STDOUT_FILENO);
if (rdts.doE_Rdct) doExec = redirection(argv, rdts, STDERR_FILENO);
if (doExec) {
int pid = fork();
if (pid == -1) { // Error in fork
perror("error in fork");
comPr.deleteCStrings(commands);
exit(-1);
} else if (pid == 0) { // Child Process
if (-1 == execvp(argv[0], argv)) {
// All children need to exit! (forgot this)
if (errno == EACCES) { // Access denied
perror(argv[0]);
exit(-1);
} else if (errno == ENOEXEC) { // Not Exec
perror(argv[0]);
exit(-1);
} else if (errno == ENOENT) { // Does not exist
perror(argv[0]);
exit(-1);
} else {
perror("error in execvp");
exit(-1);
}
}
} else if (pid > 0) { // parent!
if (-1 == wait(0))
perror("wait");
if (errno != 0 && errno != EACCES && errno != ENOEXEC && errno != ENOENT)
exit(-1);
}
}
if (rdts.doI_Rdct) {
if (-1 == dup2(rdts.savedSTDIN, rdts.rfd)) { // Restore stdin
perror("dup2-input");
exit(-1);
}
}
if (rdts.doO_Rdct) {
if (-1 == dup2(rdts.savedSTDOUT, rdts.wofd)) { // Restore stdout
perror("dup2-output");
exit(-1);
}
}
if (rdts.doE_Rdct) {
if (-1 == dup2(rdts.savedSTDERR, rdts.wefd)) { // Restore stdout
perror("dup2-stderr");
exit(-1);
}
}
comPr.deleteCStrings(commands);
//rdts.closeCurrFDs();
}
return 0;
}
// closes respective fd and opens file in its place
bool redirection(char** argv, redirect& rdts, const int fd) {
bool doRedir; // generalize between input, output, and errput, with pointers
int* savedFD;
int* newFD;
int* index;
int FLAG;
if (fd == STDIN_FILENO) {
doRedir = rdts.doI_Rdct;
savedFD = &(rdts.savedSTDIN);
newFD = &(rdts.rfd);
index = &(rdts.indexIR);
FLAG = O_RDONLY;
} else if (fd == STDOUT_FILENO) {
doRedir = rdts.doO_Rdct;
savedFD = &(rdts.savedSTDOUT);
newFD = &(rdts.wofd);
index = &(rdts.indexOR);
FLAG = O_WRONLY | O_CREAT | O_TRUNC;
} else if (fd == STDERR_FILENO) {
doRedir = rdts.doE_Rdct;
savedFD = &(rdts.savedSTDERR);
newFD = &(rdts.wefd);
index = &(rdts.indexER);
FLAG = O_WRONLY | O_CREAT | O_TRUNC;
} else {
cerr << "Redirection failed\n";
exit(-1);
}
if (doRedir) {
// dup the STDIN
if ( -1 == (*savedFD = dup(fd)) ) {
perror("dup-redirect" + fd);
exit(-1);
}
// close STDIN
if ( -1 == close(fd) ) {
perror("close-redirect" + fd);
exit(-1);
}
// open file
if ( -1 == (*newFD = open(argv[*index + 1], FLAG)) ) {
if (errno == EACCES || errno == ENOENT) { //FIXME
perror(argv[rdts.indexIR + 1]); // filename syntax
return false;
} else {
perror("open-redirect" + fd);
exit(-1);
}
}
// record which fd to close
rdts.currentFD.push_back(newFD);
}
return true;
}
<commit_msg>Fixed segfault. Now multi-bit and all 3 first redirects work\!<commit_after>#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <errno.h>
#include <vector>
#include "comParse.h"
#include <cstring>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
using namespace boost;
using namespace std;
struct redirect;
bool redirection(char** argv, redirect& rdts, const int fd);
struct redirect {
bool doI_Rdct; // input redirect
int indexIR;
int savedSTDIN; // for duping STDIN and saving it
int rfd; // when opening new fd in 0 for reading
bool doO_Rdct; // output redirect
int indexOR;
int savedSTDOUT; // for duping STDOUT and saving it
int wofd; // when opening new fd in 1 for writing
bool doE_Rdct; // output redirect
int indexER;
int savedSTDERR; // for duping STDERR and saving it
int wefd; // when opening new fd in 2 for writing
vector<int*> currentFD;
redirect() {
doI_Rdct = false;
savedSTDIN = -1;
rfd = -1;
indexIR = -1;
doO_Rdct = false;
savedSTDOUT = -1;
wofd = -1;
indexOR = -1;
doE_Rdct = false;
savedSTDERR = -1;
wefd = -1;
indexER = -1;
}
void closeCurrFDs() {
if (!currentFD.empty()) {
for (vector<int*>::iterator it = currentFD.begin();
it != currentFD.end(); it++) {
if (-1 == close(*(*it))) {
perror("close");
exit(-1);
}
}
currentFD.clear();
}
}
~redirect() {
//closeCurrFDs();
}
};
int main() {
while (true) {
char** argv = NULL;
vector<char*> commands;
comParse comPr;
do {
cerr << "$ " << flush;
string input = "";
getline(cin, input); // Get command
commands = comPr.parseLine(input);
} while (commands.size() == 1); // if empty line, repeat req for command. sz 1 = just NULL delim.
argv = &commands[0];
redirect rdts;
for (unsigned int i = 0; i < commands.size() - 1; i++) { // NULL at end
if ( strcmp(commands.at(i), ";") == 0) {
delete[] commands.at(i);
argv[i] = NULL;
break;
} else if (strcmp(commands.at(i), "<") == 0
|| strcmp(commands.at(i), "0<") == 0) {
delete[] commands.at(i);
argv[i] = NULL;
rdts.doI_Rdct = true;
rdts.indexIR = i;
} else if (strcmp(commands.at(i), ">") == 0
|| strcmp(commands.at(i), "1>") == 0) {
delete[] commands.at(i);
argv[i] = NULL;
rdts.doO_Rdct = true;
rdts.indexOR = i;
} else if (strcmp(commands.at(i), "2>") == 0) {
delete[] commands.at(i);
argv[i] = NULL;
rdts.doE_Rdct = true;
rdts.indexER = i;
}
}
/* Confusing as heck, let me explain!
* char const* means pointer to a constant char
* so char const* const means a const pointer to a const char
* and char const* const* means a const pointer to a const char pointer!
* (Read declarations from right to left to make it make sense -
* char const* = POINTER (*) to a CONST CHAR)
*/
//char const* const* c_arr = &commands[0]; // even if Not necessary: keep as really cool discovery!
bool doExec = true; // If false, do not fork and exec command
char ex[5] = "exit";
if (strcmp(argv[0], ex) == 0) {
comPr.deleteCStrings(commands); // Has heap allocated memory, always should be dealt with
return 0; // EXIT command
}
if (rdts.doI_Rdct) doExec = redirection(argv, rdts, STDIN_FILENO);
if (rdts.doO_Rdct) doExec = redirection(argv, rdts, STDOUT_FILENO);
if (rdts.doE_Rdct) doExec = redirection(argv, rdts, STDERR_FILENO);
if (doExec) {
int pid = fork();
if (pid == -1) { // Error in fork
perror("error in fork");
comPr.deleteCStrings(commands);
exit(-1);
} else if (pid == 0) { // Child Process
if (-1 == execvp(argv[0], argv)) {
// All children need to exit! (forgot this)
if (errno == EACCES) { // Access denied
perror(argv[0]);
exit(-1);
} else if (errno == ENOEXEC) { // Not Exec
perror(argv[0]);
exit(-1);
} else if (errno == ENOENT) { // Does not exist
perror(argv[0]);
exit(-1);
} else {
perror("error in execvp");
exit(-1);
}
}
} else if (pid > 0) { // parent!
if (-1 == wait(0))
perror("wait");
if (errno != 0 && errno != EACCES && errno != ENOEXEC && errno != ENOENT)
exit(-1);
}
}
if (rdts.doI_Rdct) {
if (-1 == dup2(rdts.savedSTDIN, rdts.rfd)) { // Restore stdin
perror("dup2-input");
exit(-1);
}
}
if (rdts.doO_Rdct) {
if (-1 == dup2(rdts.savedSTDOUT, rdts.wofd)) { // Restore stdout
perror("dup2-output");
exit(-1);
}
}
if (rdts.doE_Rdct) {
if (-1 == dup2(rdts.savedSTDERR, rdts.wefd)) { // Restore stdout
perror("dup2-stderr");
exit(-1);
}
}
comPr.deleteCStrings(commands);
//rdts.closeCurrFDs();
}
return 0;
}
// closes respective fd and opens file in its place
bool redirection(char** argv, redirect& rdts, const int fd) {
bool doRedir; // generalize between input, output, and errput, with pointers
int* savedFD;
int* newFD;
int* index;
int FLAG;
if (fd == STDIN_FILENO) {
doRedir = rdts.doI_Rdct;
savedFD = &(rdts.savedSTDIN);
newFD = &(rdts.rfd);
index = &(rdts.indexIR);
FLAG = O_RDONLY;
} else if (fd == STDOUT_FILENO) {
doRedir = rdts.doO_Rdct;
savedFD = &(rdts.savedSTDOUT);
newFD = &(rdts.wofd);
index = &(rdts.indexOR);
FLAG = O_WRONLY | O_CREAT | O_TRUNC;
} else if (fd == STDERR_FILENO) {
doRedir = rdts.doE_Rdct;
savedFD = &(rdts.savedSTDERR);
newFD = &(rdts.wefd);
index = &(rdts.indexER);
FLAG = O_WRONLY | O_CREAT | O_TRUNC;
} else {
cerr << "Redirection failed\n";
exit(-1);
}
if (doRedir) {
// dup the STDIN
if ( -1 == (*savedFD = dup(fd)) ) {
perror("dup-redirect" + fd);
exit(-1);
}
// close STDIN
if ( -1 == close(fd) ) {
perror("close-redirect" + fd);
exit(-1);
}
// open file
if ( -1 == (*newFD = open(argv[*index + 1], FLAG)) ) {
if (errno == EACCES || errno == ENOENT) { //FIXME
perror(argv[rdts.indexIR + 1]); // filename syntax
return false;
} else {
perror("open-redirect" + fd);
exit(-1);
}
}
// record which fd to close
rdts.currentFD.push_back(newFD);
}
return true;
}
<|endoftext|>
|
<commit_before>#include <boost/tokenizer.hpp>
#include <iostream>
#include <unistd.h>
#include <string.h>
#include <cstdlib>
#include <errno.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string>
#include <sstream>
#include <vector>
using namespace boost;
using namespace std;
int main()
{
string args;
while(1 != 2)
{
cout << "$ ";
getline(cin, args);
string exitf;
char *argv[9];
int i = 0;
vector<string> arg_s;
tokenizer<> tok(args);
for(tokenizer<>::iterator beg=tok.begin(); beg!=tok.end();++beg) {
if(*beg == "exit")
exitf = *beg;
arg_s.push_back(*beg);
argv[i] = new char[6];
strcpy(argv[i], const_cast<char*>(arg_s[i].c_str()));
++i;
}
argv[i] = NULL;
int pid = fork();
if(pid == -1) {
perror("fork");
exit(1);
}
if(pid == 0) {
int r = execvp(argv[0], argv);
if(r == -1) {
perror("execvp");
exit(1);
}
}
else {
if(-1 == waitpid(pid, &pid, 0)) {
perror("waitpid");
}
if(exitf == "exit")
exit(1);
}
// int pid = fork();
// if(pid == -1) {
// perror("fork");
// exit(1);
// }
// if(pid == 0)
// {
//char *argv2[4];
//argv2[0] = new char[6];
//strcpy(argv[0], "ls");
//argv2[1] = new char[6];
//strcpy(argv[1], "-a");
//argv2[2] = new char [6];
//strcpy(argv[2], "-l");
// int pid2 = fork();
// if(pid2 == -1) {
// perror("fork");
// exit(1);
// }
// if(pid2 == 0) {
/// if(execvp(argv[0], argv) == -1) {
// perror("execvp");
// exit(1);
// }
// }
// else {
// if(-1 == waitpid(pid2,&pid2,0 ))
// perror("waitpid");
// }
//
// if(execvp(argv[1], argv) == -1) {
// perror("execvp");
// exit(1);
// }
//
// cout << "after" << endl;
// }
// else {
// if(-1 == waitpid(pid, &pid, 0))
// perror("waitpid");
// }
}
return 0;
}
<commit_msg>rshell.cpp updated<commit_after>#include <boost/tokenizer.hpp>
#include <iostream>
#include <unistd.h>
#include <string.h>
#include <cstdlib>
#include <errno.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string>
#include <sstream>
#include <vector>
//using namespace boost;
using namespace std;
int main()
{
using namespace boost;
string args;
while(1 != 2)
{
cout << "$ ";
getline(cin, args);
char *argv[9];
int i = 0;
vector<string> arg_s;
tokenizer<> tok(args);
for(tokenizer<>::iterator beg=tok.begin(); beg!=tok.end();++beg) {
arg_s.push_back(*beg);
argv[i] = new char[6];
strcpy(argv[i], const_cast<char*>(arg_s[i].c_str()));
if(*beg == "exit")
exit(1);
++i;
}
argv[i] = NULL;
int pid = fork();
if(pid == -1) {
perror("fork");
exit(1);
}
if(pid == 0) {
int r = execvp(argv[0], argv);
if(r == -1) {
perror("execvp");
exit(1);
}
}
else {
if(-1 == waitpid(pid, &pid, 0)) {
perror("waitpid");
}
}
// int pid = fork();
// if(pid == -1) {
// perror("fork");
// exit(1);
// }
// if(pid == 0)
// {
//char *argv2[4];
//argv2[0] = new char[6];
//strcpy(argv[0], "ls");
//argv2[1] = new char[6];
//strcpy(argv[1], "-a");
//argv2[2] = new char [6];
//strcpy(argv[2], "-l");
// int pid2 = fork();
// if(pid2 == -1) {
// perror("fork");
// exit(1);
// }
// if(pid2 == 0) {
/// if(execvp(argv[0], argv) == -1) {
// perror("execvp");
// exit(1);
// }
// }
// else {
// if(-1 == waitpid(pid2,&pid2,0 ))
// perror("waitpid");
// }
//
// if(execvp(argv[1], argv) == -1) {
// perror("execvp");
// exit(1);
// }
//
// cout << "after" << endl;
// }
// else {
// if(-1 == waitpid(pid, &pid, 0))
// perror("waitpid");
// }
}
return 0;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <boost/tokenizer.hpp>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <errno.h>
#include <vector>
#include <cstring>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>
#include <list>
#include "comParse.h"
#include "redirect.h"
#include "digit.h"
using namespace boost;
using namespace std;
void input_sigHandler(int param) {
if (param == SIGINT) {
char currentDir[512];
if (NULL == (getcwd(currentDir, 512))) { // Currently outputs error that directory is too long. Don't like this FIXME
perror("getcwd");
currentDir[0] = '\0';
}
cout << '\n' << currentDir << " $ " << flush;
}
if (param == SIGTSTP) {}
}
void quit_sigHandler(int param) {
if (param == SIGINT) {
cout << endl;
}
}
int main() {
list<int> stoppedpids;
signal (SIGTSTP, input_sigHandler); // Ctrl C
while (true) {
signal(SIGINT, input_sigHandler);
char** argv = NULL;
vector<char*> commands;
comParse comPr;
char currentDir[512]; // Current Working Directory
if (NULL == (getcwd(currentDir, 512))) { // Currently outputs error that directory is too long. Don't like this FIXME
perror("getcwd");
currentDir[0] = '\0';
}
do {
cout << currentDir << " $ " << flush;
string input = "";
getline(cin, input); // Get command
commands = comPr.parseLine(input);
} while (commands.size() == 1); // if empty line, repeat req for command. sz 1 = just NULL delim.
bool doExec = true; // If false, do not fork and exec command
//MASSIVE SECTION OF CODE DEDICATED TO PARSING FOR SEMI, PIPES
//-------------------------------------------------------------------------
int timeout = 0;
vector<char*> realcom; // command + arguments - input redirection & semicolon
vector< vector<char*> > realcomsP;
vector<bool> isPipe;
bool setPipe = false; // pipe will only be made if needed
argv = &commands.at(0);
redirect rdts; // contains redirection flags and values
for (unsigned int i = 0; i < commands.size() - 1; i++) { // NULL at end
char* c = commands.at(i);
// if semicolon or pipe, split command into two
if ( strcmp(commands.at(i), ";") == 0) {
delete[] commands.at(i);
argv[i] = NULL;
timeout = 1;
realcom.push_back(NULL);
realcomsP.push_back(realcom);
realcom.clear();
isPipe.push_back(false);
} else if (strcmp(c, "|") == 0) {
delete[] commands.at(i);
argv[i] = NULL;
timeout = 1;
realcom.push_back(NULL);
realcomsP.push_back(realcom);
realcom.clear();
isPipe.push_back(true);
setPipe = true;
} else if (strchr(c, '<') != NULL) {
int fd = -1;
// FIXME: Currently assumes 1 digit fd. K for assignment.
// Convert char to int with - 48
if (isdigit(commands.at(i)[0])) fd = commands.at(i)[0] - 48; // num before operator
delete[] commands.at(i);
argv[i] = NULL;
timeout = 2; // do not push this or next arg
rdts.v_opfd.push_back( pair<int,int>(I_REDIRECT, fd) ); // op, fd
if ( !(i + 1 < commands.size()) ) { // next arg must exist (filename)
cerr << "rshell: syntax error at <\n";
doExec = false;
break;
}
rdts.v_ind.push_back(i + 1); // index
} else if (strchr(c, '>') != NULL) {
int fd = -1;
// FIXME: Currently assumes 1 digit fd. K for assignment.
// Convert char to int with - 48
if (isdigit(commands.at(i)[0])) fd = commands.at(i)[0] - 48; // num before operator
if (strstr(commands.at(i), ">>>") != NULL) {
cerr << "rshell: syntax error at >\n";
doExec = false;
break;
}
else if (strstr(commands.at(i), ">>") != NULL)
rdts.v_opfd.push_back( pair<int,int>(ORD_APPEND, fd) ); // op, fd
else {
rdts.v_opfd.push_back( pair<int,int>(O_REDIRECT, fd) ); // op, fd
// c = commands.at(i - 1);
// if (i - 1 < 0 || strcmp( c, ":" ) == 0) // should truncate file if :>
// realcom.pop_back();
}
delete[] commands.at(i);
argv[i] = NULL;
timeout = 2; // do not push this or next arg
if ( !(i + 1 < commands.size() - 1) ) { // next arg must exist (filename)
cerr << "rshell: syntax error at <";
exit(-1);
}
rdts.v_ind.push_back(i + 1); // index
}
if (timeout != 0) timeout--;
else realcom.push_back(commands.at(i));
}
realcom.push_back(NULL);
realcomsP.push_back(realcom);
isPipe.push_back(false);
// Test produces weird results but gdb says contents are correct...wth?
//for (unsigned int i = 0; i < realcomsP.size(); i++) {
// cerr << i << ": ";
// for (unsigned int j = 0; j < realcomsP.at(i).size(); j++) {
// cerr << realcomsP.at(1).at(j) << ' ';
// }
// cerr << endl;
//}
//exit(0);
/* Confusing as heck, let me explain!
* char const* means pointer to a constant char
* so char const* const means a const pointer to a const char
* and char const* const* means a const pointer to a const char pointer!
* (Read declarations from right to left to make it make sense -
* char const* = POINTER (*) to a CONST CHAR)
*/
//char const* const* c_arr = &commands[0]; // even if Not necessary: keep as really cool discovery!
if (doExec != false) doExec = setRdct(argv, rdts);
//if (rdts.doO_Rdct) doExec = redirection(argv, rdts, STDOUT_FILENO);
//if (rdts.doE_Rdct) doExec = redirection(argv, rdts, STDERR_FILENO);
char ex[5] = "exit";
int fdpipe[2];
int savefdpipe[2];
bool resetPipe = false;
if (setPipe) {
if (-1 == pipe(fdpipe)) {
perror("pipe");
exit(-1);
}
}
signal(SIGINT, quit_sigHandler);
for (unsigned int i = 0; doExec && i < realcomsP.size(); i++) {
argv = &realcomsP.at(i).at(0); // initialize to char**
if (strcmp(argv[0], ex) == 0) {
comPr.deleteCStrings(commands); // Has heap allocated memory, always should be dealt with
return 0; // EXIT command
}
int pid = fork();
if (pid == -1) { // Error in fork
perror("error in fork");
comPr.deleteCStrings(commands);
exit(-1);
} else if (pid == 0) { // child Process
signal(SIGINT, SIG_DFL);
signal(SIGTSTP, SIG_DFL);
if (0 == strcmp(argv[0], "cd")) exit(0); // cd: PARENT PROCESS
else if (0 == strcmp(argv[0], "fg")) { // fg
int stoppedID = stoppedpids.size() ? stoppedpids.size() : 1; // default, most recent or 1
int sizePids = stoppedpids.size();
if (realcomsP.at(i).size() >= 2) {
if (-1 != (stoppedID = toDigit(argv[1])) && sizePids >= stoppedID) {
list<int>::iterator it = stoppedpids.begin(); // List has no middle of list accessor
for (int i = 0; i < stoppedID; i++, it++);
int pidStopped = *it;
if (-1 == kill(pidStopped, SIGCONT))
perror("rshell: fg"); // No such job
} else cerr << "rshell: fg: " << argv[1] << ": no such job";
} else {
if (sizePids >= stoppedID) {
if (-1 == kill(stoppedpids.back(), SIGCONT)) {
string s = "rshell: fg";
s += argv[1];
perror(s.c_str()); // No such job
}
} else cerr << "rshell: fg: current: no such job";
}
}
// If piping, this command outputs to pipe
if (isPipe.at(i)) {
// move output's fd
if (-1 == (savefdpipe[1] = dup(STDOUT_FILENO))) {
perror("dup w/ pipe");
exit(-1);
}
// place pipe in output
if (-1 == dup2(fdpipe[1], STDOUT_FILENO)) {
perror("dup w/ pipe");
exit(-1);
}
}
char* cpathvar = getenv("PATH");
if (cpathvar == NULL) {
perror("getenv");
exit(-1);
}
string pathvar = cpathvar;
typedef boost::tokenizer<char_separator<char> > tokenizer;
char rm_delim[2] = {':', '\0'}; // null is delim, not char for filtering
char_separator<char> charSep(rm_delim); // should ignore only whitespace
tokenizer parse(pathvar, charSep);
errno = 0;
for (tokenizer::iterator it = parse.begin(); it != parse.end(); it++) {
string s = *it + "/";
s += argv[0];
if (-1 != execv(s.c_str(), argv)) {
break;
}
}
if (errno != 0) { // perror for execv
// All children need to exit! (forgot this)
if (errno == EACCES) { // Access denied
perror(argv[0]);
} else if (errno == ENOEXEC) { // Not Executable
perror(argv[0]);
} else if (errno == ENOENT) { // Does not exist
perror(argv[0]);
} else {
perror("error in execv");
}
exit(-1);
}
// if last command piped, next command's input is from pipe
if (isPipe.at(i)) {
// put output back in place
if (-1 == dup2(savefdpipe[1],STDOUT_FILENO)) {
perror("dup w/ pipe");
exit(-1);
}
// close newly dup'ed output
if (-1 == (close(savefdpipe[1]))) {
perror("close w/ pipe");
exit(-1);
}
// save input
if (-1 == (savefdpipe[0] = dup(STDIN_FILENO))) {
perror("dup w/ pipe");
exit(-1);
}
// put pipe into input
if (-1 == dup2(fdpipe[0],STDIN_FILENO)) {
perror("dup w/ pipe");
exit(-1);
}
resetPipe = true;
} else if (resetPipe) {
// put input back in place
if (-1 == dup2(savefdpipe[0],STDIN_FILENO)) {
perror("dup w/ pipe");
exit(-1);
}
// close newly dup'ed input
if (-1 == (close(savefdpipe[0]))) {
perror("dup w/ pipe");
exit(-1);
}
resetPipe = false;
}
exit(0);
} else if (pid > 0) { // parent!
int status;
// Ctrl Z: WUNTRACED is an option that lets the parent wait for processes that
// have stopped too, not just terminated.
// If stopped, add its pid to a queue of stopped pids and use kill(pid, SIGCONT)
// to continue it if user enters fg or bg (don't wait if bg, but keep process in queue)
if (-1 == waitpid(pid, &status, WUNTRACED))
perror("wait");
if (errno != 0 && errno != EACCES && errno != ENOEXEC && errno != ENOENT)
exit(-1);
if (0 == strcmp(argv[0], "cd")) { // cd: PARENT PROCESS
if (realcomsP.at(i).size() < 2 || -1 == chdir(argv[1])) // need a param (others ignored)
perror("rshell: cd");
}
if (WIFSTOPPED(status)) {
stoppedpids.push_back(pid);
cout << "[" << stoppedpids.size() << "]+ Stopped\t\t" << argv[0] << endl;
}
}
}
if (setPipe) {
for (int i = 0; i < 2; i++) {
if (-1 == close(fdpipe[i])) {
perror("close pipe");
exit(-1);
}
}
}
for (unsigned int i = 0; i < rdts.v_savedP.size(); i++) {
if (-1 == dup2(rdts.v_savedP.at(i), rdts.v_pfd.at(i))) { // Restore saved fds
perror("dup2");
exit(-1);
}
if (-1 == close(rdts.v_savedP.at(i))) { // Restore saved fds
perror("close");
exit(-1);
}
}
comPr.deleteCStrings(commands);
//rdts.closeCurrFDs();
}
return 0;
}
<commit_msg>Finished fg implementation<commit_after>#include <iostream>
#include <boost/tokenizer.hpp>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <errno.h>
#include <vector>
#include <cstring>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>
#include <list>
#include "comParse.h"
#include "redirect.h"
#include "digit.h"
using namespace boost;
using namespace std;
void input_sigHandler(int param) {
if (param == SIGINT) {
char currentDir[512];
if (NULL == (getcwd(currentDir, 512))) { // Currently outputs error that directory is too long. Don't like this FIXME
perror("getcwd");
currentDir[0] = '\0';
}
cout << '\n' << currentDir << " $ " << flush;
}
if (param == SIGTSTP) {}
}
void quit_sigHandler(int param) {
if (param == SIGINT) {
cout << endl;
}
}
int main() {
list<int> stopped_pids;
signal (SIGTSTP, input_sigHandler); // Ctrl C
while (true) {
signal(SIGINT, input_sigHandler);
char** argv = NULL;
vector<char*> commands;
comParse comPr;
char currentDir[512]; // Current Working Directory
if (NULL == (getcwd(currentDir, 512))) { // Currently outputs error that directory is too long. Don't like this FIXME
perror("getcwd");
currentDir[0] = '\0';
}
do {
cout << currentDir << " $ " << flush;
string input = "";
getline(cin, input); // Get command
commands = comPr.parseLine(input);
} while (commands.size() == 1); // if empty line, repeat req for command. sz 1 = just NULL delim.
bool doExec = true; // If false, do not fork and exec command
//MASSIVE SECTION OF CODE DEDICATED TO PARSING FOR SEMI, PIPES
//-------------------------------------------------------------------------
int timeout = 0;
vector<char*> realcom; // command + arguments - input redirection & semicolon
vector< vector<char*> > realcomsP;
vector<bool> isPipe;
bool setPipe = false; // pipe will only be made if needed
argv = &commands.at(0);
redirect rdts; // contains redirection flags and values
for (unsigned int i = 0; i < commands.size() - 1; i++) { // NULL at end
char* c = commands.at(i);
// if semicolon or pipe, split command into two
if ( strcmp(commands.at(i), ";") == 0) {
delete[] commands.at(i);
argv[i] = NULL;
timeout = 1;
realcom.push_back(NULL);
realcomsP.push_back(realcom);
realcom.clear();
isPipe.push_back(false);
} else if (strcmp(c, "|") == 0) {
delete[] commands.at(i);
argv[i] = NULL;
timeout = 1;
realcom.push_back(NULL);
realcomsP.push_back(realcom);
realcom.clear();
isPipe.push_back(true);
setPipe = true;
} else if (strchr(c, '<') != NULL) {
int fd = -1;
// FIXME: Currently assumes 1 digit fd. K for assignment.
// Convert char to int with - 48
if (isdigit(commands.at(i)[0])) fd = commands.at(i)[0] - 48; // num before operator
delete[] commands.at(i);
argv[i] = NULL;
timeout = 2; // do not push this or next arg
rdts.v_opfd.push_back( pair<int,int>(I_REDIRECT, fd) ); // op, fd
if ( !(i + 1 < commands.size()) ) { // next arg must exist (filename)
cerr << "rshell: syntax error at <\n";
doExec = false;
break;
}
rdts.v_ind.push_back(i + 1); // index
} else if (strchr(c, '>') != NULL) {
int fd = -1;
// FIXME: Currently assumes 1 digit fd. K for assignment.
// Convert char to int with - 48
if (isdigit(commands.at(i)[0])) fd = commands.at(i)[0] - 48; // num before operator
if (strstr(commands.at(i), ">>>") != NULL) {
cerr << "rshell: syntax error at >\n";
doExec = false;
break;
}
else if (strstr(commands.at(i), ">>") != NULL)
rdts.v_opfd.push_back( pair<int,int>(ORD_APPEND, fd) ); // op, fd
else {
rdts.v_opfd.push_back( pair<int,int>(O_REDIRECT, fd) ); // op, fd
// c = commands.at(i - 1);
// if (i - 1 < 0 || strcmp( c, ":" ) == 0) // should truncate file if :>
// realcom.pop_back();
}
delete[] commands.at(i);
argv[i] = NULL;
timeout = 2; // do not push this or next arg
if ( !(i + 1 < commands.size() - 1) ) { // next arg must exist (filename)
cerr << "rshell: syntax error at <";
exit(-1);
}
rdts.v_ind.push_back(i + 1); // index
}
if (timeout != 0) timeout--;
else realcom.push_back(commands.at(i));
}
realcom.push_back(NULL);
realcomsP.push_back(realcom);
isPipe.push_back(false);
// Test produces weird results but gdb says contents are correct...wth?
//for (unsigned int i = 0; i < realcomsP.size(); i++) {
// cerr << i << ": ";
// for (unsigned int j = 0; j < realcomsP.at(i).size(); j++) {
// cerr << realcomsP.at(1).at(j) << ' ';
// }
// cerr << endl;
//}
//exit(0);
/* Confusing as heck, let me explain!
* char const* means pointer to a constant char
* so char const* const means a const pointer to a const char
* and char const* const* means a const pointer to a const char pointer!
* (Read declarations from right to left to make it make sense -
* char const* = POINTER (*) to a CONST CHAR)
*/
//char const* const* c_arr = &commands[0]; // even if Not necessary: keep as really cool discovery!
if (doExec != false) doExec = setRdct(argv, rdts);
//if (rdts.doO_Rdct) doExec = redirection(argv, rdts, STDOUT_FILENO);
//if (rdts.doE_Rdct) doExec = redirection(argv, rdts, STDERR_FILENO);
char ex[5] = "exit";
int fdpipe[2];
int savefdpipe[2];
bool resetPipe = false;
if (setPipe) {
if (-1 == pipe(fdpipe)) {
perror("pipe");
exit(-1);
}
}
signal(SIGINT, quit_sigHandler);
for (unsigned int i = 0; doExec && i < realcomsP.size(); i++) {
argv = &realcomsP.at(i).at(0); // initialize to char**
if (strcmp(argv[0], ex) == 0) {
comPr.deleteCStrings(commands); // Has heap allocated memory, always should be dealt with
return 0; // EXIT command
}
int pid = fork();
if (pid == -1) { // Error in fork
perror("error in fork");
comPr.deleteCStrings(commands);
exit(-1);
} else if (pid == 0) { // child Process
// cd/fg (Do in parent process)
if (0 == strcmp(argv[0], "cd") || 0 == strcmp(argv[0], "fg")) exit(0);
// Default signals for ctrl z, ctrl c
signal(SIGINT, SIG_DFL);
signal(SIGTSTP, SIG_DFL);
// If piping, this command outputs to pipe
if (isPipe.at(i)) {
// move output's fd
if (-1 == (savefdpipe[1] = dup(STDOUT_FILENO))) {
perror("dup w/ pipe");
exit(-1);
}
// place pipe in output
if (-1 == dup2(fdpipe[1], STDOUT_FILENO)) {
perror("dup w/ pipe");
exit(-1);
}
}
char* cpathvar = getenv("PATH");
if (cpathvar == NULL) {
perror("getenv");
exit(-1);
}
string pathvar = cpathvar;
typedef boost::tokenizer<char_separator<char> > tokenizer;
char rm_delim[2] = {':', '\0'}; // null is delim, not char for filtering
char_separator<char> charSep(rm_delim); // should ignore only whitespace
tokenizer parse(pathvar, charSep);
errno = 0;
for (tokenizer::iterator it = parse.begin(); it != parse.end(); it++) {
string s = *it + "/";
s += argv[0];
if (-1 != execv(s.c_str(), argv)) {
break;
}
}
if (errno != 0) { // perror for execv
// All children need to exit! (forgot this)
if (errno == EACCES) { // Access denied
perror(argv[0]);
} else if (errno == ENOEXEC) { // Not Executable
perror(argv[0]);
} else if (errno == ENOENT) { // Does not exist
perror(argv[0]);
} else {
perror("error in execv");
}
exit(-1);
}
// if last command piped, next command's input is from pipe
if (isPipe.at(i)) {
// put output back in place
if (-1 == dup2(savefdpipe[1],STDOUT_FILENO)) {
perror("dup w/ pipe");
exit(-1);
}
// close newly dup'ed output
if (-1 == (close(savefdpipe[1]))) {
perror("close w/ pipe");
exit(-1);
}
// save input
if (-1 == (savefdpipe[0] = dup(STDIN_FILENO))) {
perror("dup w/ pipe");
exit(-1);
}
// put pipe into input
if (-1 == dup2(fdpipe[0],STDIN_FILENO)) {
perror("dup w/ pipe");
exit(-1);
}
resetPipe = true;
} else if (resetPipe) {
// put input back in place
if (-1 == dup2(savefdpipe[0],STDIN_FILENO)) {
perror("dup w/ pipe");
exit(-1);
}
// close newly dup'ed input
if (-1 == (close(savefdpipe[0]))) {
perror("dup w/ pipe");
exit(-1);
}
resetPipe = false;
}
exit(0);
} else if (pid > 0) { // parent!
int status;
// Ctrl Z: WUNTRACED is an option that lets the parent wait for processes that
// have stopped too, not just terminated.
// If stopped, add its pid to a queue of stopped pids and use kill(pid, SIGCONT)
// to continue it if user enters fg or bg (don't wait if bg, but keep process in queue)
if (-1 == waitpid(pid, &status, WUNTRACED))
perror("wait");
if (errno != 0 && errno != EACCES && errno != ENOEXEC && errno != ENOENT)
exit(-1);
if (WIFSTOPPED(status)) {
stopped_pids.push_back(pid);
cout << "[" << stopped_pids.size() << "]+ Stopped\t\t" << argv[0] << endl;
}
// cd
if (0 == strcmp(argv[0], "cd")) { // cd: PARENT PROCESS
if (realcomsP.at(i).size() < 2 || -1 == chdir(argv[1])) // need a param (others ignored)
perror("rshell: cd");
}
// fg
int waiting_pid = -1;
if (0 == strcmp(argv[0], "fg")) {
if (stopped_pids.empty()) {
cerr << "rshell: fg: " << argv[1] << ": no such job";
exit(-1);
}
int stoppedID = stopped_pids.size() ? stopped_pids.size() : 1; // default, most recent or 1
int sizePids = stopped_pids.size();
//cout << endl << "stoppedID = " << stoppedID << endl
// << "sizePids = " << sizePids << endl;
// If fg has argument (id of stopped process)
// vector composed of <fg> <arg> <null> (at least 3)
if (realcomsP.at(i).size() > 2) {
if (-1 != (stoppedID = toDigit(argv[1])) && sizePids >= stoppedID) {
// get element at stoppedID - 1
list<int>::iterator it = stopped_pids.begin();
for (int i = 0; i < stoppedID - 1; i++, it++);
int pidStopped = *it;
// continue process, wait
if (-1 != kill(pidStopped, SIGCONT)) {
waiting_pid = pidStopped;
stopped_pids.erase(it);
} else perror("rshell: fg"); // No such job
} else cerr << "rshell: fg: " << argv[1] << ": no such job";
}
// Default fg
else {
// continue process, wait
if (-1 != kill(stopped_pids.back(), SIGCONT)) {
waiting_pid = stopped_pids.back();
stopped_pids.pop_back();
} else {
string s = "rshell: fg";
s += argv[1];
perror(s.c_str()); // No such job
}
}
}
if (waiting_pid != -1) {
if (-1 == waitpid(waiting_pid, &status, WUNTRACED))
perror("wait");
if (WIFSTOPPED(status)) {
stopped_pids.push_back(pid);
cout << "[" << stopped_pids.size() << "]+ Stopped\t\t" << argv[0] << endl;
}
}
}
}
if (setPipe) {
for (int i = 0; i < 2; i++) {
if (-1 == close(fdpipe[i])) {
perror("close pipe");
exit(-1);
}
}
}
for (unsigned int i = 0; i < rdts.v_savedP.size(); i++) {
if (-1 == dup2(rdts.v_savedP.at(i), rdts.v_pfd.at(i))) { // Restore saved fds
perror("dup2");
exit(-1);
}
if (-1 == close(rdts.v_savedP.at(i))) { // Restore saved fds
perror("close");
exit(-1);
}
}
comPr.deleteCStrings(commands);
//rdts.closeCurrFDs();
}
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright 2015 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <algorithm>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <numeric>
#include <sched.h>
#include <string.h>
#include <sstream>
#include <sys/mman.h>
#include <sys/rusage.h>
#include <vector>
#include <rttest.h>
// Global variables
struct rttest_params _rttest_params;
struct rttest_sample_buffer _rttest_sample_buffer;
struct rttest_results _rttest_results;
static inline bool timespec_gt(const struct timespec *t1,
const struct timespec *t2)
{
if (t1->tv_sec > t2->tv_sec)
{
return true;
}
if (t1->tv_sec < t2->tv_sec)
{
return false;
}
return t1->tv_nsec > t2->tv_nsec;
}
static inline void normalize_timespec(struct timespec *t)
{
// TODO: maybe could use some work
while (t->tv_nsec >= NSEC_PER_SEC) {
t->tv_nsec -= NSEC_PER_SEC;
t->tv_sec++;
}
}
static inline void add_timespecs(const struct timespec *t1,
const struct timespec *t2,
struct timespec *dst)
{
dst->tv_sec = t1->tv_sec + t2->tv_sec;
dst->tv_nsec = t1->tv_nsec + t2->tv_nsec;
normalize_timespec(dst);
}
static inline bool subtract_timespecs(const struct timespec *t1,
const struct timespec *t2,
struct timespec *dst)
{
if (timespec_gt(t2, t1))
{
return subtract_timespecs(t2, t1, dst);
}
dst->tv_sec = t1->tv_sec - t2->tv_sec;
dst->tv_nsec = t1->tv_nsec - t2->tv_nsec;
normalize_timespec(dst);
return true;
}
static inline unsigned long timespec_to_long(const struct timespec *t)
{
return t->tv_sec * NSEC_PER_SEC + t->tv_nsec;
}
int rttest_record_missed_deadline(struct timespec *deadline,
struct timespec *result_time, int iteration)
{
struct timespec jitter;
subtract_timespecs(result_time, deadline, &jitter);
// Record jitter
if (iteration > _rttest_sample_buffer.buffer_size)
{
return -1;
}
_rttest_sample_buffer.missed_deadlines[iteration] = true;
_rttest_sample_buffer.latency_samples[iteration] = -timespec_to_long(&jitter);
return 0;
}
int rttest_record_jitter(struct timespec *deadline,
struct timespec *result_time, int iteration)
{
if (timespec_gt(result_time, deadline))
{
// missed a deadline
return rttest_record_missed_deadline(deadline, result_time, iteration);
}
struct timespec jitter;
subtract_timespecs(deadline, result_time, &jitter);
// Record jitter
if (iteration > _rttest_sample_buffer.buffer_size)
{
return -1;
}
_rttest_sample_buffer.missed_deadlines[iteration] = false;
_rttest_sample_buffer.latency_samples[iteration] = timespec_to_long(&jitter);
return 0;
}
int rttest_read_args(int argc, char** argv)
{
//parse arguments
}
int rttest_init(unsigned long iterations, struct timespec update_period,
size_t sched_policy, int sched_priority, int lock_memory, size_t stack_size,
int plot, int write, char *filename)
{
_rttest_params.iterations = iterations;
_rttest_params.update_period = update_period;
_rttest_params.sched_policy = sched_policy;
_rttest_params.sched_priority = sched_priority;
_rttest_params.lock_memory = lock_memory;
_rttest_params.stack_size = stack_size;
_rttest_params.plot = plot;
_rttest_params.write = write;
_rttest_params.filename = filename;
_rttest_sample_buffer.latency_samples =
(long *) std::malloc(iterations*sizeof(unsigned long));
memset(_rttest_sample_buffer.latency_samples, 0,
iterations*sizeof(long));
_rttest_sample_buffer.missed_deadlines =
(bool *) std::malloc(iterations*sizeof(bool));
memset(_rttest_sample_buffer.missed_deadlines, 0, iterations*sizeof(bool));
_rttest_sample_buffer.buffer_size = iterations;
}
int rttest_spin(void *(*user_function)(void *), void *args)
{
return rttest_spin_period(user_function, args, &_rttest_params.update_period,
_rttest_params.iterations);
}
int rttest_spin_period(void *(*user_function)(void *), void *args,
const struct timespec *update_period, const unsigned long iterations)
{
struct timespec wakeup_time, current_time;
clock_gettime(0, ¤t_time);
wakeup_time = current_time;
for (int i = 0; i < iterations; i++)
{
// Plan the next shot
add_timespecs(&wakeup_time, update_period, &wakeup_time);
clock_gettime(0, ¤t_time);
if (timespec_gt(¤t_time, &wakeup_time))
{
// Missed a deadline before we could sleep! Record it
rttest_record_missed_deadline(&wakeup_time, ¤t_time, i);
}
else
{
clock_nanosleep(0, TIMER_ABSTIME, &wakeup_time, NULL);
clock_gettime(0, ¤t_time);
rttest_record_jitter(&wakeup_time, ¤t_time, i);
}
user_function(args);
}
return 0;
}
int rttest_schedule_wakeup(void *(*user_function)(void *), void *args,
struct timespec absolute_wakeup)
{
struct timespec current_time;
clock_gettime(0, ¤t_time);
if (timespec_gt(¤t_time, &absolute_wakeup))
{
// Missed a deadline before we could sleep! Record it
rttest_record_missed_deadline(&absolute_wakeup, ¤t_time, -1);
}
else
{
clock_nanosleep(0, TIMER_ABSTIME, &absolute_wakeup, NULL);
clock_gettime(0, ¤t_time);
rttest_record_jitter(&absolute_wakeup, ¤t_time, -1);
}
user_function(args);
return 0;
}
int rttest_lock_memory()
{
return mlockall(MCL_CURRENT | MCL_FUTURE);
}
int rttest_prefault_stack_size(const size_t stack_size)
{
unsigned char stack[stack_size];
memset(stack, 0, stack_size);
// TODO: catch errors, maybe verify memset return value points to stack?
return 0;
}
int rttest_prefault_stack()
{
return rttest_prefault_stack_size(_rttest_params.stack_size);
}
int rttest_set_thread_default_priority()
{
return rttest_set_sched_priority(_rttest_params.sched_priority,
_rttest_params.sched_policy);
}
int rttest_set_sched_priority(size_t sched_priority, int policy)
{
struct sched_param param;
param.sched_priority = sched_priority;
// note that sched_setscheduler can set the priority of an arbitrary process
return sched_setscheduler(0, policy, ¶m);
}
int rttest_calculate_statistics(struct rttest_results *results)
{
if (results == NULL)
{
return -1;
}
std::vector<long> jitter_dataset;
jitter_dataset.assign(_rttest_sample_buffer.latency_samples,
_rttest_sample_buffer.latency_samples + _rttest_sample_buffer.buffer_size);
std::vector<long> latency_dataset(jitter_dataset.size());
std::copy_if(jitter_dataset.begin(), jitter_dataset.end(),
latency_dataset.begin(),
[](long sample){ return sample < 0; } );
std::vector<bool> missed_deadlines_data;
missed_deadlines_data.assign(_rttest_sample_buffer.missed_deadlines,
_rttest_sample_buffer.missed_deadlines + _rttest_sample_buffer.buffer_size);
results->min_latency = *std::min_element(latency_dataset.begin(), latency_dataset.end());
results->max_latency = *std::max_element(latency_dataset.begin(), latency_dataset.end());
results->mean_latency = std::accumulate(latency_dataset.begin(),
latency_dataset.end(), 0.0) / latency_dataset.size();
double sq_sum = std::inner_product(latency_dataset.begin(), latency_dataset.end(),
latency_dataset.begin(), 0.0);
results->latency_stddev =
std::sqrt(sq_sum / latency_dataset.size() - results->mean_latency * results->mean_latency);
results->min_jitter = *std::min_element(jitter_dataset.begin(), jitter_dataset.end());
results->max_jitter = *std::max_element(jitter_dataset.begin(), jitter_dataset.end());
results->mean_jitter = std::accumulate(jitter_dataset.begin(),
jitter_dataset.end(), 0.0) / jitter_dataset.size();
sq_sum = std::inner_product(jitter_dataset.begin(), jitter_dataset.end(),
jitter_dataset.begin(), 0.0);
results->jitter_stddev =
std::sqrt(sq_sum / jitter_dataset.size() - results->mean_jitter * results->mean_jitter);
results->missed_deadlines = std::count(missed_deadlines_data.begin(),
missed_deadlines_data.end(), true);
results->early_deadlines = missed_deadlines_data.size() - results->missed_deadlines;
return 0;
}
std::string rttest_results_to_string(struct rttest_results *results)
{
if (!results)
{
return "ERROR: rttest got NULL results string!";
}
std::stringstream sstring;
sstring << "rttest statistics:" << std::endl;
sstring << " - Missed deadlines: " << results->missed_deadlines << std::endl;
sstring << " - Early deadlines: " << results->early_deadlines << std::endl;
sstring << std::endl;
sstring << " Latency (time after deadline was missed):" << std::endl;
sstring << " - Min: " << results->min_latency << std::endl;
sstring << " - Max: " << results->max_latency << std::endl;
sstring << " - Mean: " << results->mean_latency << std::endl;
sstring << " - Standard deviation: " << results->latency_stddev << std::endl;
sstring << std::endl;
sstring << " Jitter (scheduling variation for early or missed deadlines):" << std::endl;
sstring << " - Min: " << results->min_jitter << std::endl;
sstring << " - Max: " << results->max_jitter << std::endl;
sstring << " - Mean: " << results->mean_jitter << std::endl;
sstring << " - Standard deviation: " << results->jitter_stddev << std::endl;
return sstring.str();
}
int rttest_finish()
{
// Print statistics to screen
rttest_calculate_statistics(&_rttest_results);
std::cout << rttest_results_to_string(&_rttest_results);
if (_rttest_sample_buffer.latency_samples != NULL)
{
free(_rttest_sample_buffer.latency_samples);
}
if (_rttest_sample_buffer.missed_deadlines != NULL)
{
free(_rttest_sample_buffer.missed_deadlines);
}
return 0;
}
int rttest_write_results()
{
// Format:
// iteration timestamp latency missed_deadline? (1/0)
if (!_rttest_params.write)
{
return -1;
}
if (_rttest_sample_buffer.latency_samples == NULL)
{
return -1;
}
if (_rttest_sample_buffer.missed_deadlines == NULL)
{
return -1;
}
return 0;
}
int rttest_plot()
{
if (!_rttest_params.plot)
{
return -1;
}
return 0;
}
<commit_msg>Implemented file writing<commit_after>// Copyright 2015 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <algorithm>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <numeric>
#include <fstream>
#include <sched.h>
#include <string.h>
#include <sstream>
#include <sys/mman.h>
#include <sys/rusage.h>
#include <vector>
#include <rttest.h>
// Global variables
struct rttest_params _rttest_params;
struct rttest_sample_buffer _rttest_sample_buffer;
struct rttest_results _rttest_results;
static inline bool timespec_gt(const struct timespec *t1,
const struct timespec *t2)
{
if (t1->tv_sec > t2->tv_sec)
{
return true;
}
if (t1->tv_sec < t2->tv_sec)
{
return false;
}
return t1->tv_nsec > t2->tv_nsec;
}
static inline void normalize_timespec(struct timespec *t)
{
// TODO: maybe could use some work
while (t->tv_nsec >= NSEC_PER_SEC) {
t->tv_nsec -= NSEC_PER_SEC;
t->tv_sec++;
}
}
static inline void add_timespecs(const struct timespec *t1,
const struct timespec *t2,
struct timespec *dst)
{
dst->tv_sec = t1->tv_sec + t2->tv_sec;
dst->tv_nsec = t1->tv_nsec + t2->tv_nsec;
normalize_timespec(dst);
}
static inline bool subtract_timespecs(const struct timespec *t1,
const struct timespec *t2,
struct timespec *dst)
{
if (timespec_gt(t2, t1))
{
return subtract_timespecs(t2, t1, dst);
}
dst->tv_sec = t1->tv_sec - t2->tv_sec;
dst->tv_nsec = t1->tv_nsec - t2->tv_nsec;
normalize_timespec(dst);
return true;
}
static inline unsigned long timespec_to_long(const struct timespec *t)
{
return t->tv_sec * NSEC_PER_SEC + t->tv_nsec;
}
int rttest_record_missed_deadline(struct timespec *deadline,
struct timespec *result_time, int iteration)
{
struct timespec jitter;
subtract_timespecs(result_time, deadline, &jitter);
// Record jitter
if (iteration > _rttest_sample_buffer.buffer_size)
{
return -1;
}
_rttest_sample_buffer.missed_deadlines[iteration] = true;
_rttest_sample_buffer.latency_samples[iteration] = -timespec_to_long(&jitter);
return 0;
}
int rttest_record_jitter(struct timespec *deadline,
struct timespec *result_time, int iteration)
{
if (timespec_gt(result_time, deadline))
{
// missed a deadline
return rttest_record_missed_deadline(deadline, result_time, iteration);
}
struct timespec jitter;
subtract_timespecs(deadline, result_time, &jitter);
// Record jitter
if (iteration > _rttest_sample_buffer.buffer_size)
{
return -1;
}
_rttest_sample_buffer.missed_deadlines[iteration] = false;
_rttest_sample_buffer.latency_samples[iteration] = timespec_to_long(&jitter);
return 0;
}
int rttest_read_args(int argc, char** argv)
{
//parse arguments
}
int rttest_init(unsigned long iterations, struct timespec update_period,
size_t sched_policy, int sched_priority, int lock_memory, size_t stack_size,
int plot, int write, char *filename)
{
_rttest_params.iterations = iterations;
_rttest_params.update_period = update_period;
_rttest_params.sched_policy = sched_policy;
_rttest_params.sched_priority = sched_priority;
_rttest_params.lock_memory = lock_memory;
_rttest_params.stack_size = stack_size;
_rttest_params.plot = plot;
_rttest_params.write = write;
_rttest_params.filename = filename;
_rttest_sample_buffer.latency_samples =
(long *) std::malloc(iterations*sizeof(unsigned long));
memset(_rttest_sample_buffer.latency_samples, 0,
iterations*sizeof(long));
_rttest_sample_buffer.missed_deadlines =
(bool *) std::malloc(iterations*sizeof(bool));
memset(_rttest_sample_buffer.missed_deadlines, 0, iterations*sizeof(bool));
_rttest_sample_buffer.buffer_size = iterations;
return 0;
}
int rttest_spin(void *(*user_function)(void *), void *args)
{
return rttest_spin_period(user_function, args, &_rttest_params.update_period,
_rttest_params.iterations);
}
int rttest_spin_period(void *(*user_function)(void *), void *args,
const struct timespec *update_period, const unsigned long iterations)
{
struct timespec wakeup_time, current_time;
clock_gettime(0, ¤t_time);
wakeup_time = current_time;
for (int i = 0; i < iterations; i++)
{
// Plan the next shot
add_timespecs(&wakeup_time, update_period, &wakeup_time);
clock_gettime(0, ¤t_time);
if (timespec_gt(¤t_time, &wakeup_time))
{
// Missed a deadline before we could sleep! Record it
rttest_record_missed_deadline(&wakeup_time, ¤t_time, i);
}
else
{
clock_nanosleep(0, TIMER_ABSTIME, &wakeup_time, NULL);
clock_gettime(0, ¤t_time);
rttest_record_jitter(&wakeup_time, ¤t_time, i);
}
user_function(args);
}
return 0;
}
int rttest_schedule_wakeup(void *(*user_function)(void *), void *args,
struct timespec absolute_wakeup)
{
struct timespec current_time;
clock_gettime(0, ¤t_time);
if (timespec_gt(¤t_time, &absolute_wakeup))
{
// Missed a deadline before we could sleep! Record it
rttest_record_missed_deadline(&absolute_wakeup, ¤t_time, -1);
}
else
{
clock_nanosleep(0, TIMER_ABSTIME, &absolute_wakeup, NULL);
clock_gettime(0, ¤t_time);
rttest_record_jitter(&absolute_wakeup, ¤t_time, -1);
}
user_function(args);
return 0;
}
int rttest_lock_memory()
{
return mlockall(MCL_CURRENT | MCL_FUTURE);
}
int rttest_prefault_stack_size(const size_t stack_size)
{
unsigned char stack[stack_size];
memset(stack, 0, stack_size);
// TODO: catch errors, maybe verify memset return value points to stack?
return 0;
}
int rttest_prefault_stack()
{
return rttest_prefault_stack_size(_rttest_params.stack_size);
}
int rttest_set_thread_default_priority()
{
return rttest_set_sched_priority(_rttest_params.sched_priority,
_rttest_params.sched_policy);
}
int rttest_set_sched_priority(size_t sched_priority, int policy)
{
struct sched_param param;
param.sched_priority = sched_priority;
// note that sched_setscheduler can set the priority of an arbitrary process
return sched_setscheduler(0, policy, ¶m);
}
int rttest_calculate_statistics(struct rttest_results *results)
{
if (results == NULL)
{
return -1;
}
std::vector<long> jitter_dataset;
jitter_dataset.assign(_rttest_sample_buffer.latency_samples,
_rttest_sample_buffer.latency_samples + _rttest_sample_buffer.buffer_size);
std::vector<long> latency_dataset(jitter_dataset.size());
std::copy_if(jitter_dataset.begin(), jitter_dataset.end(),
latency_dataset.begin(),
[](long sample){ return sample < 0; } );
std::vector<bool> missed_deadlines_data;
missed_deadlines_data.assign(_rttest_sample_buffer.missed_deadlines,
_rttest_sample_buffer.missed_deadlines + _rttest_sample_buffer.buffer_size);
results->min_latency = *std::min_element(latency_dataset.begin(), latency_dataset.end());
results->max_latency = *std::max_element(latency_dataset.begin(), latency_dataset.end());
results->mean_latency = std::accumulate(latency_dataset.begin(),
latency_dataset.end(), 0.0) / latency_dataset.size();
double sq_sum = std::inner_product(latency_dataset.begin(), latency_dataset.end(),
latency_dataset.begin(), 0.0);
results->latency_stddev =
std::sqrt(sq_sum / latency_dataset.size() - results->mean_latency * results->mean_latency);
results->min_jitter = *std::min_element(jitter_dataset.begin(), jitter_dataset.end());
results->max_jitter = *std::max_element(jitter_dataset.begin(), jitter_dataset.end());
results->mean_jitter = std::accumulate(jitter_dataset.begin(),
jitter_dataset.end(), 0.0) / jitter_dataset.size();
sq_sum = std::inner_product(jitter_dataset.begin(), jitter_dataset.end(),
jitter_dataset.begin(), 0.0);
results->jitter_stddev =
std::sqrt(sq_sum / jitter_dataset.size() - results->mean_jitter * results->mean_jitter);
results->missed_deadlines = std::count(missed_deadlines_data.begin(),
missed_deadlines_data.end(), true);
results->early_deadlines = missed_deadlines_data.size() - results->missed_deadlines;
return 0;
}
std::string rttest_results_to_string(struct rttest_results *results)
{
if (!results)
{
return "ERROR: rttest got NULL results string!";
}
std::stringstream sstring;
sstring << "rttest statistics:" << std::endl;
sstring << " - Missed deadlines: " << results->missed_deadlines << std::endl;
sstring << " - Early deadlines: " << results->early_deadlines << std::endl;
sstring << std::endl;
sstring << " Latency (time after deadline was missed):" << std::endl;
sstring << " - Min: " << results->min_latency << std::endl;
sstring << " - Max: " << results->max_latency << std::endl;
sstring << " - Mean: " << results->mean_latency << std::endl;
sstring << " - Standard deviation: " << results->latency_stddev << std::endl;
sstring << std::endl;
sstring << " Jitter (scheduling variation for early or missed deadlines):" << std::endl;
sstring << " - Min: " << results->min_jitter << std::endl;
sstring << " - Max: " << results->max_jitter << std::endl;
sstring << " - Mean: " << results->mean_jitter << std::endl;
sstring << " - Standard deviation: " << results->jitter_stddev << std::endl;
return sstring.str();
}
int rttest_finish()
{
// Print statistics to screen
rttest_calculate_statistics(&_rttest_results);
std::cout << rttest_results_to_string(&_rttest_results);
if (_rttest_sample_buffer.latency_samples != NULL)
{
free(_rttest_sample_buffer.latency_samples);
}
if (_rttest_sample_buffer.missed_deadlines != NULL)
{
free(_rttest_sample_buffer.missed_deadlines);
}
return 0;
}
int rttest_write_results()
{
if (!_rttest_params.write)
{
return -1;
}
if (_rttest_sample_buffer.latency_samples == NULL)
{
return -1;
}
if (_rttest_sample_buffer.missed_deadlines == NULL)
{
return -1;
}
std::ofstream fstream(_rttest_params.filename, std::ios::out);
if (!fstream.is_open())
{
return -1;
}
// Format:
// iteration timestamp (ns) latency missed_deadline? (1/0)
fstream << "iteration timestamp latency missed_deadline" << std::endl;
for (unsigned long i = 0; i < _rttest_sample_buffer.buffer_size; ++i)
{
fstream << i << " " << timespec_to_long(&_rttest_params.update_period) * i
<< " " << _rttest_sample_buffer.latency_samples[i] << " "
<< _rttest_sample_buffer.missed_deadlines[i] << std::endl;
}
fstream.close();
return 0;
}
int rttest_plot()
{
if (!_rttest_params.plot)
{
return -1;
}
return 0;
}
<|endoftext|>
|
<commit_before>/*****************************************************************************
* Copyright 2011 Sergey Shekyan
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* *****************************************************************************/
/*****
* Author: Sergey Shekyan sshekyan@qualys.com
*
* Slow HTTP attack vulnerability test tool
* http://code.google.com/p/slowhttptest/
*****/
#include <ctime>
#include <errno.h>
#include <execinfo.h>
#include <stdarg.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "slowlog.h"
namespace {
static FILE* log_file = NULL;
static FILE* csv_file = NULL;
static FILE* html_file = NULL;
int current_log_level;
void print_html_header() {
fprintf(html_file,
"<html>\r\n \
<head>\r\n \
<script type=\"text/javascript\" src=\"https://www.google.com/jsapi\"></script>\r\n \
<script type=\"text/javascript\">\r\n \
google.load(\"visualization\", \"1\", {packages:[\"corechart\"]});\r\n \
google.setOnLoadCallback(drawChart);\r\n \
function drawChart() {\r\n \
var data = new google.visualization.DataTable();\r\n \
data.addColumn('string', 'Seconds');\r\n \
data.addColumn('number', 'Error');\r\n \
data.addColumn('number', 'Closed');\r\n \
data.addColumn('number', 'Pending');\r\n \
data.addColumn('number', 'Connected');\r\n \
data.addRows([\r\n");
}
void print_html_footer() {
fprintf(html_file,
" ]);\r\n \
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));\r\n \
chart.draw(data, {width: 400, height: 240, title: 'Company Performance',\r\n \
hAxis: {title: 'Seconds', titleTextStyle: {color: '#FF0000'}},\r\n \
vAxis: {title: 'Connections', titleTextStyle: {color: '#FF0000'}}\r\n \
});\r\n \
}\r\n \
</script>\r\n \
</head>\r\n \
<body>\r\n \
<div id=\"chart_div\"></div>\r\n \
</body>\r\n \
</html>");
}
void dispose_of_log(int param) {
if (log_file && log_file != stdout) {
fclose(log_file);
}
if(csv_file) {
fclose(csv_file);
}
if(html_file) {
print_html_footer();
fflush(html_file);
fclose(html_file);
}
exit(1);
}
void print_call_stack() {
static void* buf[64];
const int depth = backtrace(buf, sizeof(buf)/sizeof(buf[0]));
backtrace_symbols_fd(buf, depth, fileno(stdout));
if (stdout != log_file) {
backtrace_symbols_fd(buf, depth, fileno(log_file));
}
}
}
namespace slowhttptest {
void slowlog_init(int debug_level, const char* file_name, bool need_stats) {
log_file = file_name == NULL ? stdout : fopen(file_name, "w");
if(!log_file) {
printf("Unable to open log file %s for writing: %s", file_name,
strerror(errno));
}
if(need_stats) {
time_t rawtime;
struct tm * timeinfo;
time(&rawtime);
timeinfo = localtime(&rawtime);
char csv_file_name[32] = {0};
char html_file_name[32] = {0};
strftime(csv_file_name, 22, "slow_%H%M%Y%m%d.csv", timeinfo);
strftime(html_file_name, 22, "slow_%H%M%Y%m%d.html", timeinfo);
csv_file = fopen(csv_file_name , "w");
if(!csv_file) {
printf("Unable to open csv file %s for writing: %s\n",
csv_file_name,
strerror(errno));
} else {
fprintf(csv_file, "Seconds,Error,Closed,Pending,Connected\n");
}
html_file = fopen(html_file_name , "w");
if(!html_file) {
printf("Unable to open html file %s for writing: %s\n",
html_file_name,
strerror(errno));
} else {
print_html_header();
}
}
signal(SIGINT, &dispose_of_log);
current_log_level = debug_level;
}
void check(bool f, const char* message) {
if (!f) {
fprintf(log_file, "%s\n", message);
fflush(log_file);
print_call_stack();
exit(1);
}
}
void log_fatal(const char* format, ...) {
const time_t now = time(NULL);
char ctimebuf[32];
const char* buf = ctime_r(&now, ctimebuf);
fprintf(log_file, "%-.24s FATAL:", buf);
va_list va;
va_start(va, format);
vfprintf(log_file, format, va);
va_end(va);
fflush(log_file);
print_call_stack();
exit(1);
}
void dump_csv(const char* format, ...) {
va_list va;
va_start(va, format);
vfprintf(csv_file, format, va);
fflush(csv_file);
va_end(va);
}
void dump_html(const char* format, ...) {
va_list va;
va_start(va, format);
vfprintf(html_file, format, va);
fflush(html_file);
va_end(va);
}
void slowlog(int lvl, const char* format, ...) {
if(lvl <= current_log_level) {
const time_t now = time(NULL);
char ctimebuf[32];
const char* buf = ctime_r(&now, ctimebuf);
fprintf(log_file, "%-.24s:", buf);
va_list va;
va_start(va, format);
vfprintf(log_file, format, va);
va_end(va);
}
}
} // namespace slowhttptest
<commit_msg>added atexit<commit_after>/*****************************************************************************
* Copyright 2011 Sergey Shekyan
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* *****************************************************************************/
/*****
* Author: Sergey Shekyan sshekyan@qualys.com
*
* Slow HTTP attack vulnerability test tool
* http://code.google.com/p/slowhttptest/
*****/
#include <ctime>
#include <errno.h>
#include <execinfo.h>
#include <stdarg.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "slowlog.h"
namespace {
static FILE* log_file = NULL;
static FILE* csv_file = NULL;
static FILE* html_file = NULL;
int current_log_level;
void print_html_header() {
fprintf(html_file,
"<html>\r\n \
<head>\r\n \
<script type=\"text/javascript\" src=\"https://www.google.com/jsapi\"></script>\r\n \
<script type=\"text/javascript\">\r\n \
google.load(\"visualization\", \"1\", {packages:[\"corechart\"]});\r\n \
google.setOnLoadCallback(drawChart);\r\n \
function drawChart() {\r\n \
var data = new google.visualization.DataTable();\r\n \
data.addColumn('string', 'Seconds');\r\n \
data.addColumn('number', 'Error');\r\n \
data.addColumn('number', 'Closed');\r\n \
data.addColumn('number', 'Pending');\r\n \
data.addColumn('number', 'Connected');\r\n \
data.addRows([\r\n");
}
void print_html_footer() {
fprintf(html_file,
" ]);\r\n \
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));\r\n \
chart.draw(data, {width: 400, height: 240, title: 'BLABLA, here goes test parameters',\r\n \
hAxis: {title: 'Seconds', titleTextStyle: {color: '#FF0000'}},\r\n \
vAxis: {title: 'Connections', titleTextStyle: {color: '#FF0000'}}\r\n \
});\r\n \
}\r\n \
</script>\r\n \
</head>\r\n \
<body>\r\n \
<div id=\"chart_div\"></div>\r\n \
</body>\r\n \
</html>");
}
void dispose_of_log(int param) {
if (log_file && log_file != stdout) {
fclose(log_file);
}
if(csv_file) {
fclose(csv_file);
}
if(html_file) {
print_html_footer();
fflush(html_file);
fclose(html_file);
}
exit(1);
}
void wrapper_dispose_of_log() {
dispose_of_log(0);
}
void print_call_stack() {
static void* buf[64];
const int depth = backtrace(buf, sizeof(buf)/sizeof(buf[0]));
backtrace_symbols_fd(buf, depth, fileno(stdout));
if (stdout != log_file) {
backtrace_symbols_fd(buf, depth, fileno(log_file));
}
}
}
namespace slowhttptest {
void slowlog_init(int debug_level, const char* file_name, bool need_stats) {
log_file = file_name == NULL ? stdout : fopen(file_name, "w");
if(!log_file) {
printf("Unable to open log file %s for writing: %s", file_name,
strerror(errno));
}
if(need_stats) {
time_t rawtime;
struct tm * timeinfo;
time(&rawtime);
timeinfo = localtime(&rawtime);
char csv_file_name[32] = {0};
char html_file_name[32] = {0};
strftime(csv_file_name, 22, "slow_%H%M%Y%m%d.csv", timeinfo);
strftime(html_file_name, 22, "slow_%H%M%Y%m%d.html", timeinfo);
csv_file = fopen(csv_file_name , "w");
if(!csv_file) {
printf("Unable to open csv file %s for writing: %s\n",
csv_file_name,
strerror(errno));
} else {
fprintf(csv_file, "Seconds,Error,Closed,Pending,Connected\n");
}
html_file = fopen(html_file_name , "w");
if(!html_file) {
printf("Unable to open html file %s for writing: %s\n",
html_file_name,
strerror(errno));
} else {
print_html_header();
}
}
atexit(&wrapper_dispose_of_log);
signal(SIGINT, &dispose_of_log);
current_log_level = debug_level;
}
void check(bool f, const char* message) {
if (!f) {
fprintf(log_file, "%s\n", message);
fflush(log_file);
print_call_stack();
exit(1);
}
}
void log_fatal(const char* format, ...) {
const time_t now = time(NULL);
char ctimebuf[32];
const char* buf = ctime_r(&now, ctimebuf);
fprintf(log_file, "%-.24s FATAL:", buf);
va_list va;
va_start(va, format);
vfprintf(log_file, format, va);
va_end(va);
fflush(log_file);
print_call_stack();
exit(1);
}
void dump_csv(const char* format, ...) {
va_list va;
va_start(va, format);
vfprintf(csv_file, format, va);
fflush(csv_file);
va_end(va);
}
void dump_html(const char* format, ...) {
va_list va;
va_start(va, format);
vfprintf(html_file, format, va);
fflush(html_file);
va_end(va);
}
void slowlog(int lvl, const char* format, ...) {
if(lvl <= current_log_level) {
const time_t now = time(NULL);
char ctimebuf[32];
const char* buf = ctime_r(&now, ctimebuf);
fprintf(log_file, "%-.24s:", buf);
va_list va;
va_start(va, format);
vfprintf(log_file, format, va);
va_end(va);
}
}
} // namespace slowhttptest
<|endoftext|>
|
<commit_before>/* socket.cpp -*- C++ -*-
Rémi Attab (remi.attab@gmail.com), 18 Nov 2013
FreeBSD-style copyright and disclaimer apply
Socket abstraction implementation
*/
#include "socket.h"
#include "utils.h"
#include "lockless/tls.h"
#include <array>
#include <string>
#include <cstring>
#include <cassert>
#include <netdb.h>
#include <ifaddrs.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <net/if.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
namespace slick {
/******************************************************************************/
/* ADDRESS */
/******************************************************************************/
Address::
Address(const std::string& hostPort)
{
size_t pos = hostPort.find(':');
assert(pos != std::string::npos);
host = hostPort.substr(0, pos);
port = stoi(hostPort.substr(pos + 1));
}
Address::
Address(struct sockaddr* addr)
{
socklen_t addrlen;
int family = addr->sa_family;
if (family == AF_INET) addrlen = sizeof(struct sockaddr_in);
else if (family == AF_INET6) addrlen = sizeof(struct sockaddr_in6);
else assert(false);
*this = Address(addr, addrlen);
}
Address::
Address(struct sockaddr* addr, socklen_t addrlen)
{
std::array<char, 256> host;
std::array<char, 256> service;
int res = getnameinfo(
addr, addrlen,
host.data(), host.size(),
service.data(), service.size(),
NI_NUMERICHOST | NI_NUMERICSERV);
SLICK_CHECK_ERRNO(!res, "Address.getnameinfo");
this->host = std::string(host.data());
this->port = atoi(service.data());
}
/******************************************************************************/
/* INTERFACE IT */
/******************************************************************************/
struct InterfaceIt
{
InterfaceIt(const char* host, Port port) :
first(nullptr), cur(nullptr)
{
struct addrinfo hints;
std::memset(&hints, 0, sizeof hints);
hints.ai_flags = !host ? AI_PASSIVE : 0;
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
assert(!host || port);
std::string portStr = std::to_string(port);
int ret = getaddrinfo(host, portStr.c_str(), &hints, &first);
if (ret) {
SLICK_CHECK_ERRNO(ret != EAI_SYSTEM, "InterfaceIt.getaddrinfo");
throw std::logic_error("error: " + std::to_string(ret));
}
cur = first;
}
~InterfaceIt()
{
if (first) freeaddrinfo(first);
}
explicit operator bool() const { return cur; }
void operator++ () { cur = cur->ai_next; }
void operator++ (int) { cur = cur->ai_next; }
const struct addrinfo& operator* () const { return *cur; }
const struct addrinfo* operator-> () const { return cur; }
private:
struct addrinfo* first;
struct addrinfo* cur;
};
/******************************************************************************/
/* SOCKET */
/******************************************************************************/
Socket::
Socket(Socket&& other) noexcept : fd_(other.fd_)
{
other.fd_ = -1;
}
Socket&
Socket::
operator=(Socket&& other) noexcept
{
if (this == &other) return *this;
fd_ = other.fd_;
other.fd_ = -1;
return *this;
}
Socket
Socket::
connect(const Address& addr)
{
Socket socket;
assert(addr);
for (InterfaceIt it(addr.chost(), addr.port); it; it++) {
int fd = ::socket(it->ai_family, it->ai_socktype | SOCK_NONBLOCK, it->ai_protocol);
if (fd < 0) continue;
FdGuard guard(fd);
int ret = ::connect(fd, it->ai_addr, it->ai_addrlen);
if (ret < 0 && errno != EINPROGRESS) continue;
socket.fd_ = guard.release();
break;
}
if (socket) socket.init();
return std::move(socket);
}
Socket
Socket::
connect(const std::vector<Address>& addrs)
{
for (const auto& addr : addrs) {
Socket socket = connect(addr);
if (socket) return std::move(socket);
}
return Socket();
}
Socket
Socket::
accept(int fd)
{
Socket socket;
socklen_t addrlen = 0;
struct sockaddr addr;
std::memset(&addr, 0, sizeof(addr));
socket.fd_ = accept4(fd, &addr, &addrlen, SOCK_NONBLOCK);
if (socket.fd_ < 0 && (errno == EAGAIN || errno == EWOULDBLOCK))
return std::move(socket);
SLICK_CHECK_ERRNO(socket.fd_ >= 0, "Socket.accept");
socket.init();
return std::move(socket);
}
void
Socket::
init()
{
int val = true;
int ret = setsockopt(fd_, IPPROTO_TCP, TCP_NODELAY, &val, sizeof val);
SLICK_CHECK_ERRNO(!ret, "Socket.setsockopt.TCP_NODELAY");
}
Socket::
~Socket()
{
if (fd_ < 0) return;
// There's no error checking because there's not much we can do if they fail
shutdown(fd_, SHUT_RDWR);
close(fd_);
}
int
Socket::
error() const
{
int error = 0;
socklen_t errlen = sizeof error;
int ret = getsockopt(fd_, SOL_SOCKET, SO_ERROR, &error, &errlen);
SLICK_CHECK_ERRNO(!ret, "Socket.getsockopt.error");
return error;
}
void
Socket::
throwError() const
{
int err = error();
if (err) throw std::runtime_error(checkErrnoString(err, "Socket.error"));
}
/******************************************************************************/
/* PASSIVE SOCKET */
/******************************************************************************/
PassiveSockets::
PassiveSockets(Port port, int flags)
{
for (InterfaceIt it(nullptr, port); it; it++) {
int fd = socket(it->ai_family, it->ai_socktype | flags, it->ai_protocol);
if (fd < 0) continue;
FdGuard guard(fd);
int ret = bind(fd, it->ai_addr, it->ai_addrlen);
if (ret < 0) continue;
ret = listen(fd, 1U << 8);
if (ret < 0) continue;
fds_.push_back(guard.release());
}
if (fds_.empty()) throw std::runtime_error("ERROR: no valid interface");
}
PassiveSockets::
~PassiveSockets()
{
for (int fd : fds_) close(fd);
}
/******************************************************************************/
/* NETWORK INTERFACES */
/******************************************************************************/
std::vector<Address>
networkInterfaces(bool excludeLoopback)
{
std::vector<Address> result;
unsigned include = IFF_UP | IFF_RUNNING;
unsigned exclude = excludeLoopback ? IFF_LOOPBACK : 0;
struct ifaddrs* it;
int ret = getifaddrs(&it);
SLICK_CHECK_ERRNO(!ret, "networkInterfaces.getifaddrs");
auto addrsGuard = guard([=] { freeifaddrs(it); });
for(; it; it = it->ifa_next) {
if (!it->ifa_addr) continue;
if (it->ifa_flags & exclude) continue;
if ((it->ifa_flags & include) != include) continue;
int family = it->ifa_addr->sa_family;
if (family != AF_INET && family != AF_INET6) continue;
result.emplace_back(it->ifa_addr);
}
return std::move(result);
}
} // slick
<commit_msg>Remove the flags from PassiveSockets (assume non-block always).<commit_after>/* socket.cpp -*- C++ -*-
Rémi Attab (remi.attab@gmail.com), 18 Nov 2013
FreeBSD-style copyright and disclaimer apply
Socket abstraction implementation
*/
#include "socket.h"
#include "utils.h"
#include "lockless/tls.h"
#include <array>
#include <string>
#include <cstring>
#include <cassert>
#include <netdb.h>
#include <ifaddrs.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <net/if.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
namespace slick {
/******************************************************************************/
/* ADDRESS */
/******************************************************************************/
Address::
Address(const std::string& hostPort)
{
size_t pos = hostPort.find(':');
assert(pos != std::string::npos);
host = hostPort.substr(0, pos);
port = stoi(hostPort.substr(pos + 1));
}
Address::
Address(struct sockaddr* addr)
{
socklen_t addrlen;
int family = addr->sa_family;
if (family == AF_INET) addrlen = sizeof(struct sockaddr_in);
else if (family == AF_INET6) addrlen = sizeof(struct sockaddr_in6);
else assert(false);
*this = Address(addr, addrlen);
}
Address::
Address(struct sockaddr* addr, socklen_t addrlen)
{
std::array<char, 256> host;
std::array<char, 256> service;
int res = getnameinfo(
addr, addrlen,
host.data(), host.size(),
service.data(), service.size(),
NI_NUMERICHOST | NI_NUMERICSERV);
SLICK_CHECK_ERRNO(!res, "Address.getnameinfo");
this->host = std::string(host.data());
this->port = atoi(service.data());
}
/******************************************************************************/
/* INTERFACE IT */
/******************************************************************************/
struct InterfaceIt
{
InterfaceIt(const char* host, Port port) :
first(nullptr), cur(nullptr)
{
struct addrinfo hints;
std::memset(&hints, 0, sizeof hints);
hints.ai_flags = !host ? AI_PASSIVE : 0;
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
assert(!host || port);
std::string portStr = std::to_string(port);
int ret = getaddrinfo(host, portStr.c_str(), &hints, &first);
if (ret) {
SLICK_CHECK_ERRNO(ret != EAI_SYSTEM, "InterfaceIt.getaddrinfo");
throw std::logic_error("error: " + std::to_string(ret));
}
cur = first;
}
~InterfaceIt()
{
if (first) freeaddrinfo(first);
}
explicit operator bool() const { return cur; }
void operator++ () { cur = cur->ai_next; }
void operator++ (int) { cur = cur->ai_next; }
const struct addrinfo& operator* () const { return *cur; }
const struct addrinfo* operator-> () const { return cur; }
private:
struct addrinfo* first;
struct addrinfo* cur;
};
/******************************************************************************/
/* SOCKET */
/******************************************************************************/
Socket::
Socket(Socket&& other) noexcept : fd_(other.fd_)
{
other.fd_ = -1;
}
Socket&
Socket::
operator=(Socket&& other) noexcept
{
if (this == &other) return *this;
fd_ = other.fd_;
other.fd_ = -1;
return *this;
}
Socket
Socket::
connect(const Address& addr)
{
Socket socket;
assert(addr);
for (InterfaceIt it(addr.chost(), addr.port); it; it++) {
int flags = SOCK_NONBLOCK;
int fd = ::socket(it->ai_family, it->ai_socktype | flags, it->ai_protocol);
if (fd < 0) continue;
FdGuard guard(fd);
int ret = ::connect(fd, it->ai_addr, it->ai_addrlen);
if (ret < 0 && errno != EINPROGRESS) continue;
socket.fd_ = guard.release();
break;
}
if (socket) socket.init();
return std::move(socket);
}
Socket
Socket::
connect(const std::vector<Address>& addrs)
{
for (const auto& addr : addrs) {
Socket socket = connect(addr);
if (socket) return std::move(socket);
}
return Socket();
}
Socket
Socket::
accept(int fd)
{
Socket socket;
socklen_t addrlen = 0;
struct sockaddr addr;
std::memset(&addr, 0, sizeof(addr));
socket.fd_ = accept4(fd, &addr, &addrlen, SOCK_NONBLOCK);
if (socket.fd_ < 0 && (errno == EAGAIN || errno == EWOULDBLOCK))
return std::move(socket);
SLICK_CHECK_ERRNO(socket.fd_ >= 0, "Socket.accept");
socket.init();
return std::move(socket);
}
void
Socket::
init()
{
int val = true;
int ret = setsockopt(fd_, IPPROTO_TCP, TCP_NODELAY, &val, sizeof val);
SLICK_CHECK_ERRNO(!ret, "Socket.setsockopt.TCP_NODELAY");
}
Socket::
~Socket()
{
if (fd_ < 0) return;
// There's no error checking because there's not much we can do if they fail
shutdown(fd_, SHUT_RDWR);
close(fd_);
}
int
Socket::
error() const
{
int error = 0;
socklen_t errlen = sizeof error;
int ret = getsockopt(fd_, SOL_SOCKET, SO_ERROR, &error, &errlen);
SLICK_CHECK_ERRNO(!ret, "Socket.getsockopt.error");
return error;
}
void
Socket::
throwError() const
{
int err = error();
if (err) throw std::runtime_error(checkErrnoString(err, "Socket.error"));
}
/******************************************************************************/
/* PASSIVE SOCKET */
/******************************************************************************/
PassiveSockets::
PassiveSockets(Port port)
{
for (InterfaceIt it(nullptr, port); it; it++) {
int flags = SOCK_NONBLOCK;
int fd = socket(it->ai_family, it->ai_socktype | flags, it->ai_protocol);
if (fd < 0) continue;
FdGuard guard(fd);
int ret = bind(fd, it->ai_addr, it->ai_addrlen);
if (ret < 0) continue;
ret = listen(fd, 1U << 8);
if (ret < 0) continue;
fds_.push_back(guard.release());
}
if (fds_.empty()) throw std::runtime_error("ERROR: no valid interface");
}
PassiveSockets::
~PassiveSockets()
{
for (int fd : fds_) close(fd);
}
/******************************************************************************/
/* NETWORK INTERFACES */
/******************************************************************************/
std::vector<Address>
networkInterfaces(bool excludeLoopback)
{
std::vector<Address> result;
unsigned include = IFF_UP | IFF_RUNNING;
unsigned exclude = excludeLoopback ? IFF_LOOPBACK : 0;
struct ifaddrs* it;
int ret = getifaddrs(&it);
SLICK_CHECK_ERRNO(!ret, "networkInterfaces.getifaddrs");
auto addrsGuard = guard([=] { freeifaddrs(it); });
for(; it; it = it->ifa_next) {
if (!it->ifa_addr) continue;
if (it->ifa_flags & exclude) continue;
if ((it->ifa_flags & include) != include) continue;
int family = it->ifa_addr->sa_family;
if (family != AF_INET && family != AF_INET6) continue;
result.emplace_back(it->ifa_addr);
}
return std::move(result);
}
} // slick
<|endoftext|>
|
<commit_before>#include <string>
#include <iostream>
#include <ctime>
#include <array>
#include <cmath>
#include "solver.h"
#include "message.h"
#include "key.h"
#include "language_data.h"
Solver::Solver(Message* message, Key &key) : message_(message), key_(key), bestKey_(nullptr),
tempTabu_(std::unordered_set<std::string>()),
optimalTabu_((std::unordered_set<std::string>()))
{
srand(time(nullptr));
}
void Solver::SetKey(Key &key)
{
key_ = key;
}
void Solver::Start()
{
int lastScore = CalculateScore(message_->DecryptInt(key_));
int bestScore = lastScore;
int currentBestScore = bestScore;
unsigned int iterations = 0;
const int maxTolerance = 40;
const int endIterationShuffles = 5;
const int tempClearProbability = 80;
int tolerance = 0;
int currentTolerance = 0;
bool improved = false;
int currentTabu = 0;
Key* bestKey = new Key(key_);
Key* currentBestKey = new Key(key_);
currentBestScore = bestScore = lastScore = CalculateScore(message_->DecryptInt(key_));
while (bestScore < 42000 && iterations < 80)
{
improved = false;
for (int p1 = 0; p1 < key_.GetLength(); p1++)
{
for (int p2 = 0; p2 < key_.GetLength(); p2++)
{
if (!key_.Swap(p1, p2)) continue;
int score = CalculateScore(message_->DecryptInt(key_));
if (tempTabu_.find(key_.AsPlainText()) != std::end(tempTabu_) ||
optimalTabu_.find(key_.AsPlainText()) != std::end(optimalTabu_))
{
//std::cout << "Blacklisted " << std::endl;
score = -10000;
}
else
{
score = CalculateScore(message_->DecryptInt(key_));
}
tempTabu_.insert(key_.AsPlainText());
if (maxTolerance)
{
tolerance = rand() % (maxTolerance - currentTolerance + 1);
}
if (score < lastScore - tolerance)
{
key_.Swap(p1, p2); //undo last swap
}
else
{
lastScore = score;
if (lastScore > bestScore)
{
improved = true;
bestScore = lastScore;
delete bestKey;
bestKey = new Key(key_);
//delete currentBestKey;
//currentBestKey = new Key(*key_);
}
if (score > currentBestScore)
{
currentBestScore = score;
delete currentBestKey;
currentBestKey = new Key(key_);
}
}
}
}
if (!improved)
{
if (++currentTolerance >= maxTolerance)
{
currentTolerance = 0;
}
currentTabu++;
if (currentTabu >= 300 /* max tabu */)
{
std::cout << "The plateau's clean, no dirt to be seen" << std::endl;
optimalTabu_.insert(currentBestKey->AsPlainText());
currentBestScore = -10000;
if (rand() % 2)
{
std::cout << "Restart w/ random key" << std::endl;
key_.RandomShuffle(100);
}
else
{
std::cout << "Back to best key" << std::endl;
key_ = *bestKey;
}
currentTabu = 0;
}
}
else
{
currentTolerance = 0;
currentTabu = 0;
}
key_.RandomShuffle(endIterationShuffles);
if (tempTabu_.find(key_.AsPlainText()) != std::end(tempTabu_) ||
optimalTabu_.find(key_.AsPlainText()) != std::end(optimalTabu_))
{
lastScore = -10000;
}
else
{
/*key_->SetMapSymbol('9', 8);
key_->SetMapSymbol('%', 11);
key_->SetMapSymbol('P', 8);
key_->SetMapSymbol('/', 10);
key_->SetMapSymbol('Z', 4);
key_->SetMapSymbol('U', 8);
key_->SetMapSymbol('B', 11);
key_->SetMapSymbol('k', 8);
key_->SetMapSymbol('O', 13);*/
lastScore = CalculateScore(message_->DecryptInt(key_));
}
if ((rand() % 100) < tempClearProbability) { //CLEAR_TABU_PROB
std::cout << "Clearing temp" << std::endl;
tempTabu_.clear();
}
tolerance = 0;
iterations++;
std::cout << "Iteration " << iterations - 1 << " done with score " << currentBestScore << ", best is " << bestScore << std::endl;
} //end of hill climber loop
bestKey_ = bestKey;
std::cout << iterations << " iterations completed" << std::endl;
std::cout << "Best key is " << bestKey->AsPlainText() << std::endl;
std::cout << "Best score is " << bestScore << std::endl;
std::cout << "And it decrypts to" << std::endl;
std::cout << message_->DecryptAsString(*bestKey_);
}
int Solver::CalculateScore(const std::vector<int>& plaintext)
{
unsigned int score = 0;
unsigned int biscore, triscore, tetrascore, pentascore;
biscore = triscore = tetrascore = pentascore = 0;
auto it = std::begin(plaintext);
//for (unsigned int i = 0; i < len - 1; i++)
size_t remaining = plaintext.size();
while (it != std::end(plaintext))
{
int gram = *(it++); //1st
auto it2 = it;
if (remaining > 1 || it2 != std::end(plaintext)) {
gram *= 26;
gram += *(it2++);
}
biscore += LanguageData::GetBigramFrequency(gram);
if (remaining > 2 || it2 != std::end(plaintext)) {
gram *= 26;
gram += *(it2++);
triscore += LanguageData::GetTri(gram);
}
if (remaining > 3 || it2 != std::end(plaintext)) {
gram *= 26;
gram += *(it2++);
tetrascore += LanguageData::GetTetra(gram);
}
if (remaining > 4 || it2 != std::end(plaintext)) {
gram *= 26;
gram += *(it2++);
pentascore += LanguageData::GetPenta(gram); //hehe, pentagram
}
remaining--;
}
//std::cout << "Scored " << pentascore << " " << (tetrascore >> 1) << " " << (triscore >> 2 ) << " " << (biscore >> 3) << std::endl;
score = pentascore + (tetrascore >> 1) + (triscore >> 2) + (biscore >> 3);
//score = pentascore + (tetrascore) + (triscore) + (biscore);
//update statistics
//This is a perfectly normal way to value-initialize an array in C++11
//GCC is sadly being too paranoid about this
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
std::array<int, 26> freqs {};
#pragma GCC diagnostic pop
int unique = 0;
for (size_t i = 0; i < plaintext.size(); i++)
{
int idx = plaintext[i];
if (!freqs[idx])
{
unique++;
}
freqs[idx]++;
}
double probMass = (double)plaintext.size() / unique;
double entropy = 0.0;
double entropyProb = 0.0;
double ioc = 0.0;
double chi2 = 0.0;
double chiTemp = 0.0;
for (int i = 0; i < 26; i++)
{
if (freqs[i] > 1)
{
ioc += freqs[i] * (freqs[i] - 1);
}
if (freqs[i])
{
entropyProb = (double)freqs[i] / plaintext.size();
entropy += entropyProb * (std::log(entropyProb) / std::log(2));
chiTemp = freqs[i] - probMass;
chiTemp *= chiTemp;
chiTemp /= probMass;
chi2 += chiTemp;
}
}
ioc /= plaintext.size() * (plaintext.size() - 1);
chi2 /= plaintext.size();
entropy *= -1;
double dioc = 0.0; //GetDIoC(plaintext);
double multiplier = 1.0;
multiplier *= 1.05 - (5 * std::abs(ioc - LanguageData::EnglishIoC));
//multiplier *= 1.05 - ((5 >> 1) * std::abs(dioc - LanguageData::EnglishDIoC));
multiplier *= 1.05 - (5 * std::abs(chi2 - LanguageData::EnglishChi2)) / 60.0;
multiplier *= 1.05 - (5 * std::abs(entropy - LanguageData::EnglishEntropy)) / 150.0;
return int(score * multiplier);
}
double Solver::GetDIoC(std::vector<int>& plaintext)
{
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
std::array<int, 676> freqs {};
#pragma GCC diagnostic pop
double dioc = 0;
int count = 0;
for (size_t i = 0; i < plaintext.size() - 1; i += 2)
{
int idx1 = plaintext[i];
int idx2 = plaintext[i + 1];
freqs[idx1 * 26 + idx2]++;
count++;
}
for (size_t i = 0; i < freqs.size(); i++)
{
if(freqs[i] > 1)
{
dioc += freqs[i] * (freqs[i] - 1);
}
}
dioc /= count * (count - 1);
std::cout << "DIOC count is " << count << std::endl;
return dioc;
}
void Solver::TestScore(std::string& plaintext)
{
//shut up
//std::cout << "Got " << CalculateScore(plaintext) << std::endl;
}
<commit_msg>Turning keys within the solver into references<commit_after>#include <string>
#include <iostream>
#include <ctime>
#include <array>
#include <cmath>
#include "solver.h"
#include "message.h"
#include "key.h"
#include "language_data.h"
Solver::Solver(Message* message, Key &key) : message_(message), key_(key), bestKey_(nullptr),
tempTabu_(std::unordered_set<std::string>()),
optimalTabu_((std::unordered_set<std::string>()))
{
srand(time(nullptr));
}
void Solver::SetKey(Key &key)
{
key_ = key;
}
void Solver::Start()
{
int lastScore = CalculateScore(message_->DecryptInt(key_));
int bestScore = lastScore;
int currentBestScore = bestScore;
unsigned int iterations = 0;
const int maxTolerance = 40;
const int endIterationShuffles = 5;
const int tempClearProbability = 80;
int tolerance = 0;
int currentTolerance = 0;
bool improved = false;
int currentTabu = 0;
Key bestKey(key_);
Key currentBestKey(key_);
currentBestScore = bestScore = lastScore = CalculateScore(message_->DecryptInt(key_));
while (bestScore < 42000 && iterations < 80)
{
improved = false;
for (int p1 = 0; p1 < key_.GetLength(); p1++)
{
for (int p2 = 0; p2 < key_.GetLength(); p2++)
{
if (!key_.Swap(p1, p2)) continue;
int score = CalculateScore(message_->DecryptInt(key_));
if (tempTabu_.find(key_.AsPlainText()) != std::end(tempTabu_) ||
optimalTabu_.find(key_.AsPlainText()) != std::end(optimalTabu_))
{
//std::cout << "Blacklisted " << std::endl;
score = -10000;
}
else
{
score = CalculateScore(message_->DecryptInt(key_));
}
tempTabu_.insert(key_.AsPlainText());
if (maxTolerance)
{
tolerance = rand() % (maxTolerance - currentTolerance + 1);
}
if (score < lastScore - tolerance)
{
key_.Swap(p1, p2); //undo last swap
}
else
{
lastScore = score;
if (lastScore > bestScore)
{
improved = true;
bestScore = lastScore;
bestKey = key_;
}
if (score > currentBestScore)
{
currentBestScore = score;
currentBestKey = key_;
}
}
}
}
if (!improved)
{
if (++currentTolerance >= maxTolerance)
{
currentTolerance = 0;
}
currentTabu++;
if (currentTabu >= 300 /* max tabu */)
{
std::cout << "The plateau's clean, no dirt to be seen" << std::endl;
optimalTabu_.insert(currentBestKey.AsPlainText());
currentBestScore = -10000;
if (rand() % 2)
{
std::cout << "Restart w/ random key" << std::endl;
key_.RandomShuffle(100);
}
else
{
std::cout << "Back to best key" << std::endl;
key_ = bestKey;
}
currentTabu = 0;
}
}
else
{
currentTolerance = 0;
currentTabu = 0;
}
key_.RandomShuffle(endIterationShuffles);
if (tempTabu_.find(key_.AsPlainText()) != std::end(tempTabu_) ||
optimalTabu_.find(key_.AsPlainText()) != std::end(optimalTabu_))
{
lastScore = -10000;
}
else
{
/*key_->SetMapSymbol('9', 8);
key_->SetMapSymbol('%', 11);
key_->SetMapSymbol('P', 8);
key_->SetMapSymbol('/', 10);
key_->SetMapSymbol('Z', 4);
key_->SetMapSymbol('U', 8);
key_->SetMapSymbol('B', 11);
key_->SetMapSymbol('k', 8);
key_->SetMapSymbol('O', 13);*/
lastScore = CalculateScore(message_->DecryptInt(key_));
}
if ((rand() % 100) < tempClearProbability) { //CLEAR_TABU_PROB
std::cout << "Clearing temp" << std::endl;
tempTabu_.clear();
}
tolerance = 0;
iterations++;
std::cout << "Iteration " << iterations - 1 << " done with score " << currentBestScore << ", best is " << bestScore << std::endl;
} //end of hill climber loop
std::cout << iterations << " iterations completed" << std::endl;
std::cout << "Best key is " << bestKey.AsPlainText() << std::endl;
std::cout << "Best score is " << bestScore << std::endl;
std::cout << "And it decrypts to" << std::endl;
std::cout << message_->DecryptAsString(bestKey);
}
int Solver::CalculateScore(const std::vector<int>& plaintext)
{
unsigned int score = 0;
unsigned int biscore, triscore, tetrascore, pentascore;
biscore = triscore = tetrascore = pentascore = 0;
auto it = std::begin(plaintext);
//for (unsigned int i = 0; i < len - 1; i++)
size_t remaining = plaintext.size();
while (it != std::end(plaintext))
{
int gram = *(it++); //1st
auto it2 = it;
if (remaining > 1 || it2 != std::end(plaintext)) {
gram *= 26;
gram += *(it2++);
}
biscore += LanguageData::GetBigramFrequency(gram);
if (remaining > 2 || it2 != std::end(plaintext)) {
gram *= 26;
gram += *(it2++);
triscore += LanguageData::GetTri(gram);
}
if (remaining > 3 || it2 != std::end(plaintext)) {
gram *= 26;
gram += *(it2++);
tetrascore += LanguageData::GetTetra(gram);
}
if (remaining > 4 || it2 != std::end(plaintext)) {
gram *= 26;
gram += *(it2++);
pentascore += LanguageData::GetPenta(gram); //hehe, pentagram
}
remaining--;
}
//std::cout << "Scored " << pentascore << " " << (tetrascore >> 1) << " " << (triscore >> 2 ) << " " << (biscore >> 3) << std::endl;
score = pentascore + (tetrascore >> 1) + (triscore >> 2) + (biscore >> 3);
//score = pentascore + (tetrascore) + (triscore) + (biscore);
//update statistics
//This is a perfectly normal way to value-initialize an array in C++11
//GCC is sadly being too paranoid about this
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
std::array<int, 26> freqs {};
#pragma GCC diagnostic pop
int unique = 0;
for (size_t i = 0; i < plaintext.size(); i++)
{
int idx = plaintext[i];
if (!freqs[idx])
{
unique++;
}
freqs[idx]++;
}
double probMass = (double)plaintext.size() / unique;
double entropy = 0.0;
double entropyProb = 0.0;
double ioc = 0.0;
double chi2 = 0.0;
double chiTemp = 0.0;
for (int i = 0; i < 26; i++)
{
if (freqs[i] > 1)
{
ioc += freqs[i] * (freqs[i] - 1);
}
if (freqs[i])
{
entropyProb = (double)freqs[i] / plaintext.size();
entropy += entropyProb * (std::log(entropyProb) / std::log(2));
chiTemp = freqs[i] - probMass;
chiTemp *= chiTemp;
chiTemp /= probMass;
chi2 += chiTemp;
}
}
ioc /= plaintext.size() * (plaintext.size() - 1);
chi2 /= plaintext.size();
entropy *= -1;
double dioc = 0.0; //GetDIoC(plaintext);
double multiplier = 1.0;
multiplier *= 1.05 - (5 * std::abs(ioc - LanguageData::EnglishIoC));
//multiplier *= 1.05 - ((5 >> 1) * std::abs(dioc - LanguageData::EnglishDIoC));
multiplier *= 1.05 - (5 * std::abs(chi2 - LanguageData::EnglishChi2)) / 60.0;
multiplier *= 1.05 - (5 * std::abs(entropy - LanguageData::EnglishEntropy)) / 150.0;
return int(score * multiplier);
}
double Solver::GetDIoC(std::vector<int>& plaintext)
{
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
std::array<int, 676> freqs {};
#pragma GCC diagnostic pop
double dioc = 0;
int count = 0;
for (size_t i = 0; i < plaintext.size() - 1; i += 2)
{
int idx1 = plaintext[i];
int idx2 = plaintext[i + 1];
freqs[idx1 * 26 + idx2]++;
count++;
}
for (size_t i = 0; i < freqs.size(); i++)
{
if(freqs[i] > 1)
{
dioc += freqs[i] * (freqs[i] - 1);
}
}
dioc /= count * (count - 1);
std::cout << "DIOC count is " << count << std::endl;
return dioc;
}
void Solver::TestScore(std::string& plaintext)
{
//shut up
//std::cout << "Got " << CalculateScore(plaintext) << std::endl;
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.