text
stringlengths 54
60.6k
|
---|
<commit_before>// Copyright (c) 2015, Ming Wen
#include "fys.hpp"
#include "json_handler.hpp"
using namespace std;
namespace fys {
void testBasicIO(string featuresFile)
{
std::cout << "==== Test Start: BasicIO ====" << std::endl;
JsonFeatures jf = JsonFeatures(featuresFile);
jf.readJsonFile();
std::cout << jf.getFileStr() << std::endl;
rapidjson::Document doc;
doc.Parse(jf.getFileStr().c_str());
if (doc.HasMember("detector") && doc["detector"].IsNull()) {
rapidjson::Value& detectorVal = doc["detector"];
detectorVal.SetString("SIFT");
}
rapidjson::StringBuffer buffer;
rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buffer);
doc.Accept(writer);
jf.updateStr(buffer);
std::cout << jf.getFileStr() << std::endl;
jf.writeJsonFile();
std::cout << "==== Test End: BasicIO ====" << std::endl;
}
void testGetSet(string imageFile)
{
std::cout << "==== Test Start: Getter and Setter ====" << std::endl;
JsonImages ji = JsonImages(imageFile);
ji.readJsonFile();
rapidjson::Document doc;
doc.Parse(ji.getFileStr().c_str());
// getIntVal
vector<string> path1 = vector<string>();
path1.push_back("train");
path1.push_back("0");
path1.push_back("size");
path1.push_back("nrows");
std::cout << "Number of rows in the image: " << ji.getIntVal(doc, path1) << std::endl;
// getDoubleVal & setDoubleVal
vector<string> path2 = vector<string>();
path2.push_back("train");
path2.push_back("0");
path2.push_back("objects");
path2.push_back("0");
path2.push_back("region");
path2.push_back("ymin");
std::cout << "Original: min y value of the object: " << ji.getDoubleVal(doc, path2) << std::endl;
ji.setDoubleVal(doc, path2, 10);
std::cout << "New: min y value of the object: " << ji.getDoubleVal(doc, path2) << std::endl;
// getStrVal & setStrVal
vector<string> path3 = vector<string>();
path3.push_back("train");
path3.push_back("0");
path3.push_back("filename");
std::cout << "Original: file name of image: " << ji.getStrVal(doc, path3) << std::endl;
ji.setStrVal(doc, path3, "ff.jpg");
std::cout << "New: file name of image: " << ji.getStrVal(doc, path3) << std::endl;
rapidjson::StringBuffer buffer;
rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buffer);
doc.Accept(writer);
std::cout << "Json string after change: " << ji.getDocStr(buffer) << std::endl;
std::cout << "==== Test End: Getter and Setter ====" << std::endl;
}
void testFeatureType(string featuresFile)
{
std::cout << "==== Test Start: Feature Types ====" << std::endl;
JsonFeatures jf = JsonFeatures(featuresFile);
jf.readJsonFile();
rapidjson::Document doc;
doc.Parse(jf.getFileStr().c_str());
std::cout << "Original: detector type: " << jf.getDetectorType(doc) << std::endl;
jf.setDetectorType(doc, "SURF");
std::cout << "New: detector type: " << jf.getDetectorType(doc) << std::endl;
rapidjson::StringBuffer buffer;
rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buffer);
doc.Accept(writer);
std::cout << "Json string after change: " << jf.getDocStr(buffer) << std::endl;
std::cout << "==== Test End: Feature Types ====" << std::endl;
}
void testImageProperties(string imagesFile)
{
std::cout << "==== Test Start: Number of Images ====" << std::endl;
JsonImages ji = JsonImages(imagesFile);
ji.readJsonFile();
rapidjson::Document doc;
doc.Parse(ji.getFileStr().c_str());
ImageSample stat = ji.getNumImage(doc);
std::cout << "Training set: " << stat.train << std::endl;
std::cout << "Validation set: " << stat.validate << std::endl;
std::cout << "Test set: " << stat.test << std::endl;
std::cout << "Total: " << stat.total << std::endl;
std::cout << std::endl;
std::cout << "File name of image 0: " << ji.getFileName(doc, TRAIN_TYPE, 0) << std::endl;
std::cout << "Folder name of image 0: " << ji.getFolderName(doc, TRAIN_TYPE, 0) << std::endl;
ImageSize is = ji.getImageSize(doc, TRAIN_TYPE, 0);
std::cout << "Rows: " << is.nrows << std::endl;
std::cout << "Columns: " << is.ncols << std::endl;
std::cout << "==== Test End: Number of Images ====" << std::endl;
}
} // namespace fys
<commit_msg>tested: getObjectList()<commit_after>// Copyright (c) 2015, Ming Wen
#include "fys.hpp"
#include "json_handler.hpp"
using namespace std;
namespace fys {
void testBasicIO(string featuresFile)
{
std::cout << "==== Test Start: BasicIO ====" << std::endl;
JsonFeatures jf = JsonFeatures(featuresFile);
jf.readJsonFile();
std::cout << jf.getFileStr() << std::endl;
rapidjson::Document doc;
doc.Parse(jf.getFileStr().c_str());
if (doc.HasMember("detector") && doc["detector"].IsNull()) {
rapidjson::Value& detectorVal = doc["detector"];
detectorVal.SetString("SIFT");
}
rapidjson::StringBuffer buffer;
rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buffer);
doc.Accept(writer);
jf.updateStr(buffer);
std::cout << jf.getFileStr() << std::endl;
jf.writeJsonFile();
std::cout << "==== Test End: BasicIO ====" << std::endl;
}
void testGetSet(string imageFile)
{
std::cout << "==== Test Start: Getter and Setter ====" << std::endl;
JsonImages ji = JsonImages(imageFile);
ji.readJsonFile();
rapidjson::Document doc;
doc.Parse(ji.getFileStr().c_str());
// getIntVal
vector<string> path1 = vector<string>();
path1.push_back("train");
path1.push_back("0");
path1.push_back("size");
path1.push_back("nrows");
std::cout << "Number of rows in the image: " << ji.getIntVal(doc, path1) << std::endl;
// getDoubleVal & setDoubleVal
vector<string> path2 = vector<string>();
path2.push_back("train");
path2.push_back("0");
path2.push_back("objects");
path2.push_back("0");
path2.push_back("region");
path2.push_back("ymin");
std::cout << "Original: min y value of the object: " << ji.getDoubleVal(doc, path2) << std::endl;
ji.setDoubleVal(doc, path2, 10);
std::cout << "New: min y value of the object: " << ji.getDoubleVal(doc, path2) << std::endl;
// getStrVal & setStrVal
vector<string> path3 = vector<string>();
path3.push_back("train");
path3.push_back("0");
path3.push_back("filename");
std::cout << "Original: file name of image: " << ji.getStrVal(doc, path3) << std::endl;
ji.setStrVal(doc, path3, "ff.jpg");
std::cout << "New: file name of image: " << ji.getStrVal(doc, path3) << std::endl;
rapidjson::StringBuffer buffer;
rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buffer);
doc.Accept(writer);
std::cout << "Json string after change: " << ji.getDocStr(buffer) << std::endl;
std::cout << "==== Test End: Getter and Setter ====" << std::endl;
}
void testFeatureType(string featuresFile)
{
std::cout << "==== Test Start: Feature Types ====" << std::endl;
JsonFeatures jf = JsonFeatures(featuresFile);
jf.readJsonFile();
rapidjson::Document doc;
doc.Parse(jf.getFileStr().c_str());
std::cout << "Original: detector type: " << jf.getDetectorType(doc) << std::endl;
jf.setDetectorType(doc, "SURF");
std::cout << "New: detector type: " << jf.getDetectorType(doc) << std::endl;
rapidjson::StringBuffer buffer;
rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buffer);
doc.Accept(writer);
std::cout << "Json string after change: " << jf.getDocStr(buffer) << std::endl;
std::cout << "==== Test End: Feature Types ====" << std::endl;
}
void testImageProperties(string imagesFile)
{
std::cout << "==== Test Start: Number of Images ====" << std::endl;
JsonImages ji = JsonImages(imagesFile);
ji.readJsonFile();
rapidjson::Document doc;
doc.Parse(ji.getFileStr().c_str());
ImageSample stat = ji.getNumImage(doc);
std::cout << "Training set: " << stat.train << std::endl;
std::cout << "Validation set: " << stat.validate << std::endl;
std::cout << "Test set: " << stat.test << std::endl;
std::cout << "Total: " << stat.total << std::endl;
std::cout << std::endl;
std::cout << "File name of image 0: " << ji.getFileName(doc, TRAIN_TYPE, 0) << std::endl;
std::cout << "Folder name of image 0: " << ji.getFolderName(doc, TRAIN_TYPE, 0) << std::endl;
ImageSize is = ji.getImageSize(doc, TRAIN_TYPE, 0);
std::cout << "Rows: " << is.nrows << std::endl;
std::cout << "Columns: " << is.ncols << std::endl;
vector<ImageObject> oblist = ji.getObjectList(doc, TRAIN_TYPE, 0);
std::cout << "Object name: " << oblist[0].name << std::endl;
std::cout << "Object ID: " << oblist[0].id << std::endl;
std::cout << "Object region: " << oblist[0].region.xmin << " " << oblist[0].region.xmax << " " \
<< oblist[0].region.ymin << " " << oblist[0].region.ymax << std::endl;
std::cout << "==== Test End: Number of Images ====" << std::endl;
}
} // namespace fys
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "cpu.h"
#include "cpu_instructions.h"
#include "mmu.h"
#include "ram.h"
#include "cartrige.h"
#include "interrupts.h"
#include "gpu.h"
#include "timer.h"
#include "joypad.h"
#include "apu.h"
#include "debugger.h"
struct TestReader final : public IMemory
{
u8 a;
public:
TestReader() : a() {}
u8 read_byte(u16 adress, u32 unused) override
{
return 0;
//return 0xFF;
}
void write_byte(u16 adress, u8 val, u32 unused) override
{
if (adress == 0xFF01)
a = val;
if (adress == 0xFF02 && val == 0x81)
printf("%c", a);
}
};
struct SpeedSwitch : public IMemory
{
bool double_speed = false;
bool switch_speed = false;
u8 read_byte(u16 adress, u32 unused) override
{
if (adress == 0xFF4D)
{
auto ret = change_bit(0xFF, double_speed, 7);
return change_bit(ret, switch_speed, 0);
}
else
return 0xFF;
}
void write_byte(u16 adress, u8 val, u32 key) override
{
if (adress == 0xFF4D)
{
if (key == 0xFFFFFFFF && val == 0xFF)
{
switch_speed = false;
double_speed = !double_speed;
}
else
switch_speed = check_bit(val, 0);
}
//else ignore
}
};
int main(int argc, char *argv[])
{
Interrupts ints;
Timer timer(ints);
MMU mmu;
Ram ram;
Cartrige cart;
TestReader tr; //testing
Joypad joypad;
CPU cpu(mmu);
Gpu gpu(ints);
APU apu;
SpeedSwitch speed;
Debugger debugger;
debugger.attach_mmu(make_function(&MMU::read_byte, &mmu), make_function(&MMU::write_byte, &mmu));
debugger.attach_gpu(gpu.get_debug_func());
cpu.attach_debugger(debugger.get_cpu());
mmu.attach_debug_callback(make_function(&Debugger::check_memory_access, &debugger));
SDL_Window* window = SDL_CreateWindow("Test",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
160 * 3,
144 * 3,
0);
SDL_Renderer* rend = SDL_CreateRenderer(window, -1, 0);
SDL_Texture* tex = SDL_CreateTexture(rend, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, 160, 144);
SDL_Event ev;
std::string file_name;
while (true)
{
std::cout << "Insert cartrige path:\n";
std::cin >> file_name;
if (cart.load_cartrige(file_name))
{
std::cout << "Cartrige loaded!\n";
break;
}
std::cout << "Failed to load cartrige!\n";
}
mmu.register_chunk(0, 0x7FFF, cart.get_memory_controller());
mmu.register_chunk(0x8000, 0x9FFF, &gpu); //vram
mmu.register_chunk(0xA000, 0xBFFF, cart.get_memory_controller());
mmu.register_chunk(0xC000, 0xFDFF, &ram);
mmu.register_chunk(0xFE00, 0xFE9F, &gpu); //oam tables
mmu.register_chunk(0xFF00, 0xFF00, &joypad);//input keys register
mmu.register_chunk(0xFF01, 0xFF02, &tr); //TEST READER!!!!
mmu.register_chunk(0xFF04, 0xFF07, &timer);//timer controls
mmu.register_chunk(0xFF0F, 0xFF0F, &ints);//interrupts flags
mmu.register_chunk(0xFF10, 0xFF3F, &apu); //APU registers + wave RAM
mmu.register_chunk(0xFF40, 0xFF4B, &gpu); //gpu control regs
mmu.register_chunk(0xFF4D, 0xFF4D, &speed); //CPU speed switch (CGB)
mmu.register_chunk(0xFF4F, 0xFF4F, &gpu); //gpu vram bank reg (CGB)
mmu.register_chunk(0xFF51, 0xFF55, &gpu); //gpu HDMA/GDMA regs (CGB)
mmu.register_chunk(0xFF68, 0xFF6B, &gpu); //gpu color BGP/OBP regs (CGB)
mmu.register_chunk(0xFF70, 0xFF70, &ram); //ram bank register (CGB)
mmu.register_chunk(0xFF80, 0xFFFE, &ram); //high ram
mmu.register_chunk(0xFFFF, 0xFFFF, &ints); //interrupts
gpu.attach_dma_ptrs(cart.get_dma_controller(), &ram);
bool enable_cgb = cart.is_cgb_ready();
cpu.enable_cgb_mode(enable_cgb);
gpu.enable_cgb_mode(enable_cgb);
ram.enable_cgb_mode(enable_cgb);
bool spin = true;
const u32 key_map[8] = { SDLK_RIGHT, SDLK_LEFT, SDLK_UP, SDLK_DOWN, SDLK_a, SDLK_b, SDLK_RETURN, SDLK_s };
while (spin)
{
while (SDL_PollEvent(&ev))
{
if (ev.type == SDL_KEYDOWN || ev.type == SDL_KEYUP)
{
u32 key_code = 0;
while (key_code < 8 && key_map[key_code] != ev.key.keysym.sym)
++key_code;
if (key_code < 8)
{
if (ev.type == SDL_KEYDOWN)
joypad.push_key(static_cast<KEYS>(key_code));
else
joypad.release_key(static_cast<KEYS>(key_code));
}
}
else if (ev.type == SDL_QUIT)
spin = false;
}
//auto start = std::chrono::high_resolution_clock::now();
while (!gpu.is_entering_vblank()) //TODO: if someone turn off lcd, this loop may spin forever
{
u32 sync_cycles = 0;
if (ints.is_any_raised())
{
cpu.unhalt();
if (cpu.is_interrupt_enabled())
sync_cycles = cpu.handle_interrupt(ints.get_first_raised());
}
debugger.step();
sync_cycles += cpu.step();
sync_cycles += gpu.step(sync_cycles);
apu.step(sync_cycles);
timer.step(sync_cycles);
gpu.set_speed(speed.double_speed);
apu.set_speed(speed.double_speed);
}
auto ptr = gpu.get_frame_buffer();
void* pixels = nullptr;
int pitch = 0;
SDL_LockTexture(tex, NULL, &pixels, &pitch);
std::memcpy(pixels, ptr, sizeof(u32) * 160 * 144);
SDL_UnlockTexture(tex);
SDL_RenderClear(rend);
SDL_RenderCopy(rend, tex, NULL, NULL);
SDL_RenderPresent(rend);
gpu.clear_frame_buffer();
debugger.after_vblank();
//auto end = std::chrono::high_resolution_clock::now();
//auto dur = (end - start).count();
/*if ((dur / 1000000) < 16)
SDL_Delay(16 - (dur / 1000000));*/
}
SDL_DestroyTexture(tex);
SDL_DestroyRenderer(rend);
SDL_DestroyWindow(window);
return 0;
}
<commit_msg>forgot to init SDL2<commit_after>#include "stdafx.h"
#include "cpu.h"
#include "cpu_instructions.h"
#include "mmu.h"
#include "ram.h"
#include "cartrige.h"
#include "interrupts.h"
#include "gpu.h"
#include "timer.h"
#include "joypad.h"
#include "apu.h"
#include "debugger.h"
struct TestReader final : public IMemory
{
u8 a;
public:
TestReader() : a() {}
u8 read_byte(u16 adress, u32 unused) override
{
return 0;
//return 0xFF;
}
void write_byte(u16 adress, u8 val, u32 unused) override
{
if (adress == 0xFF01)
a = val;
if (adress == 0xFF02 && val == 0x81)
printf("%c", a);
}
};
struct SpeedSwitch : public IMemory
{
bool double_speed = false;
bool switch_speed = false;
u8 read_byte(u16 adress, u32 unused) override
{
if (adress == 0xFF4D)
{
auto ret = change_bit(0xFF, double_speed, 7);
return change_bit(ret, switch_speed, 0);
}
else
return 0xFF;
}
void write_byte(u16 adress, u8 val, u32 key) override
{
if (adress == 0xFF4D)
{
if (key == 0xFFFFFFFF && val == 0xFF)
{
switch_speed = false;
double_speed = !double_speed;
}
else
switch_speed = check_bit(val, 0);
}
//else ignore
}
};
int main(int argc, char *argv[])
{
SDL_Init(SDL_INIT_VIDEO);
Interrupts ints;
Timer timer(ints);
MMU mmu;
Ram ram;
Cartrige cart;
TestReader tr; //testing
Joypad joypad;
CPU cpu(mmu);
Gpu gpu(ints);
APU apu;
SpeedSwitch speed;
Debugger debugger;
debugger.attach_mmu(make_function(&MMU::read_byte, &mmu), make_function(&MMU::write_byte, &mmu));
debugger.attach_gpu(gpu.get_debug_func());
cpu.attach_debugger(debugger.get_cpu());
mmu.attach_debug_callback(make_function(&Debugger::check_memory_access, &debugger));
SDL_Window* window = SDL_CreateWindow("Test",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
160 * 3,
144 * 3,
0);
SDL_Renderer* rend = SDL_CreateRenderer(window, -1, 0);
SDL_Texture* tex = SDL_CreateTexture(rend, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, 160, 144);
SDL_Event ev;
std::string file_name;
while (true)
{
std::cout << "Insert cartrige path:\n";
std::cin >> file_name;
if (cart.load_cartrige(file_name))
{
std::cout << "Cartrige loaded!\n";
break;
}
std::cout << "Failed to load cartrige!\n";
}
mmu.register_chunk(0, 0x7FFF, cart.get_memory_controller());
mmu.register_chunk(0x8000, 0x9FFF, &gpu); //vram
mmu.register_chunk(0xA000, 0xBFFF, cart.get_memory_controller());
mmu.register_chunk(0xC000, 0xFDFF, &ram);
mmu.register_chunk(0xFE00, 0xFE9F, &gpu); //oam tables
mmu.register_chunk(0xFF00, 0xFF00, &joypad);//input keys register
mmu.register_chunk(0xFF01, 0xFF02, &tr); //TEST READER!!!!
mmu.register_chunk(0xFF04, 0xFF07, &timer);//timer controls
mmu.register_chunk(0xFF0F, 0xFF0F, &ints);//interrupts flags
mmu.register_chunk(0xFF10, 0xFF3F, &apu); //APU registers + wave RAM
mmu.register_chunk(0xFF40, 0xFF4B, &gpu); //gpu control regs
mmu.register_chunk(0xFF4D, 0xFF4D, &speed); //CPU speed switch (CGB)
mmu.register_chunk(0xFF4F, 0xFF4F, &gpu); //gpu vram bank reg (CGB)
mmu.register_chunk(0xFF51, 0xFF55, &gpu); //gpu HDMA/GDMA regs (CGB)
mmu.register_chunk(0xFF68, 0xFF6B, &gpu); //gpu color BGP/OBP regs (CGB)
mmu.register_chunk(0xFF70, 0xFF70, &ram); //ram bank register (CGB)
mmu.register_chunk(0xFF80, 0xFFFE, &ram); //high ram
mmu.register_chunk(0xFFFF, 0xFFFF, &ints); //interrupts
gpu.attach_dma_ptrs(cart.get_dma_controller(), &ram);
bool enable_cgb = cart.is_cgb_ready();
cpu.enable_cgb_mode(enable_cgb);
gpu.enable_cgb_mode(enable_cgb);
ram.enable_cgb_mode(enable_cgb);
bool spin = true;
const u32 key_map[8] = { SDLK_RIGHT, SDLK_LEFT, SDLK_UP, SDLK_DOWN, SDLK_a, SDLK_b, SDLK_RETURN, SDLK_s };
while (spin)
{
while (SDL_PollEvent(&ev))
{
if (ev.type == SDL_KEYDOWN || ev.type == SDL_KEYUP)
{
u32 key_code = 0;
while (key_code < 8 && key_map[key_code] != ev.key.keysym.sym)
++key_code;
if (key_code < 8)
{
if (ev.type == SDL_KEYDOWN)
joypad.push_key(static_cast<KEYS>(key_code));
else
joypad.release_key(static_cast<KEYS>(key_code));
}
}
else if (ev.type == SDL_QUIT)
spin = false;
}
//auto start = std::chrono::high_resolution_clock::now();
while (!gpu.is_entering_vblank()) //TODO: if someone turn off lcd, this loop may spin forever
{
u32 sync_cycles = 0;
if (ints.is_any_raised())
{
cpu.unhalt();
if (cpu.is_interrupt_enabled())
sync_cycles = cpu.handle_interrupt(ints.get_first_raised());
}
debugger.step();
sync_cycles += cpu.step();
sync_cycles += gpu.step(sync_cycles);
apu.step(sync_cycles);
timer.step(sync_cycles);
gpu.set_speed(speed.double_speed);
apu.set_speed(speed.double_speed);
}
auto ptr = gpu.get_frame_buffer();
void* pixels = nullptr;
int pitch = 0;
SDL_LockTexture(tex, NULL, &pixels, &pitch);
std::memcpy(pixels, ptr, sizeof(u32) * 160 * 144);
SDL_UnlockTexture(tex);
SDL_RenderClear(rend);
SDL_RenderCopy(rend, tex, NULL, NULL);
SDL_RenderPresent(rend);
gpu.clear_frame_buffer();
debugger.after_vblank();
//auto end = std::chrono::high_resolution_clock::now();
//auto dur = (end - start).count();
/*if ((dur / 1000000) < 16)
SDL_Delay(16 - (dur / 1000000));*/
}
SDL_DestroyTexture(tex);
SDL_DestroyRenderer(rend);
SDL_DestroyWindow(window);
return 0;
}
<|endoftext|> |
<commit_before>/**
* Shader.cpp
* Contributors:
* * Arthur Sonzogni (author)
* Licence:
* * Public Domain
*/
#include "Shader.hpp"
#include <vector>
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <glm/gtc/type_ptr.hpp>
using namespace std;
using namespace glm;
// file reading
void getFileContents(const char *filename, vector<char>& buffer)
{
//debug("chargement du fichier : %s",filename);
ifstream file(filename, ios_base::binary);
if (file)
{
file.seekg(0, ios_base::end);
streamsize size = file.tellg();
if (size > 0)
{
file.seekg(0, ios_base::beg);
buffer.resize(static_cast<size_t>(size));
file.read(&buffer[0], size);
}
buffer.push_back('\0');
}
else
{
throw std::invalid_argument(string("The file ") + filename + " doesn't exists");
}
}
Shader::Shader(const std::string &filename, GLenum type)
{
// file loading
vector<char> fileContent;
getFileContents(filename.c_str(),fileContent);
// creation
handle = glCreateShader(type);
if(handle == 0)
throw std::runtime_error("[Error] Impossible to create a new Shader");
// code source assignation
const char* shaderText(&fileContent[0]);
glShaderSource(handle, 1, (const GLchar**)&shaderText, NULL);
// compilation
glCompileShader(handle);
// compilation check
GLint compile_status;
glGetShaderiv(handle, GL_COMPILE_STATUS, &compile_status);
if(compile_status != GL_TRUE)
{
/* error text retreiving*/
GLsizei logsize = 0;
glGetShaderiv(handle, GL_INFO_LOG_LENGTH, &logsize);
char* log = new char[logsize+1];
glGetShaderInfoLog(handle, logsize, &logsize, log);
//log[logsize]='\0';
cout<<"[Error] compilation error: "<<filename<<endl;
cout<<log<<endl;
exit(EXIT_FAILURE);
}
else
{
cout<<"[Info] Shader "<<filename<<" compiled successfully"<<endl;
}
}
GLuint Shader::getHandle() const
{
return handle;
}
Shader::~Shader()
{
}
ShaderProgram::ShaderProgram()
{
// programme creation
handle = glCreateProgram();
if (not handle)
throw std::runtime_error("Impossible to create a new shader program");
}
ShaderProgram::ShaderProgram(std::initializer_list<Shader> shaderList):
ShaderProgram()
{
for(auto& s : shaderList)
glAttachShader(handle,s.getHandle());
link();
}
void ShaderProgram::link()
{
glLinkProgram(handle);
GLint result;
glGetProgramiv(handle,GL_LINK_STATUS, &result);
if (result!=GL_TRUE)
{
cout<<"[Error] linkage error"<<endl;
/* error text retreiving*/
GLsizei logsize = 0;
glGetProgramiv(handle, GL_INFO_LOG_LENGTH, &logsize);
char* log = new char[logsize];
glGetProgramInfoLog(handle, logsize, &logsize, log);
//log[logsize]='\0';
cout<<log<<endl;
}
}
GLint ShaderProgram::uniform(const std::string &name)
{
auto it = uniforms.find(name);
if (it == uniforms.end())
{
// uniform that is not referenced
GLint r = glGetUniformLocation(handle, name.c_str());
if ( r == GL_INVALID_OPERATION || r < 0 )
cout<<"[Error] uniform "<<name<<" doesn't exist in program"<<endl;
// add it anyways
uniforms[name] = r;
return r;
}
else
return it->second;
}
GLint ShaderProgram::attribute(const std::string& name)
{
GLint attrib = glGetAttribLocation(handle, name.c_str());
if (attrib == GL_INVALID_OPERATION || attrib < 0 )
cout<<"[Error] Attribute "<<name<<" doesn't exist in program"<<endl;
return attrib;
}
void ShaderProgram::setAttribute(const std::string& name, GLint size, GLsizei stride, GLuint offset,
GLboolean normalize,
GLenum type)
{
GLint loc = attribute(name);
glEnableVertexAttribArray(loc);
glVertexAttribPointer(
loc,
size,
type,
normalize,
stride,
reinterpret_cast<void*>(offset)
);
}
void ShaderProgram::setAttribute(const std::string& name, GLint size, GLsizei stride, GLuint offset,
GLboolean normalize)
{
setAttribute(name,size,stride,offset,normalize,GL_FLOAT);
}
void ShaderProgram::setAttribute(const std::string& name, GLint size, GLsizei stride, GLuint offset,
GLenum type)
{
setAttribute(name,size,stride,offset,false,type);
}
void ShaderProgram::setAttribute(const std::string& name, GLint size, GLsizei stride, GLuint offset)
{
setAttribute(name,size,stride,offset,false,GL_FLOAT);
}
void ShaderProgram::setUniform(const std::string& name,float x,float y,float z)
{
glUniform3f(uniform(name), x, y, z);
}
void ShaderProgram::setUniform(const std::string& name, const vec3 & v)
{
glUniform3fv(uniform(name), 1, value_ptr(v));
}
void ShaderProgram::setUniform(const std::string& name, const dvec3 & v)
{
glUniform3dv(uniform(name), 1, value_ptr(v));
}
void ShaderProgram::setUniform(const std::string& name, const vec4 & v)
{
glUniform4fv(uniform(name), 1, value_ptr(v));
}
void ShaderProgram::setUniform(const std::string& name, const dvec4 & v)
{
glUniform4dv(uniform(name), 1, value_ptr(v));
}
void ShaderProgram::setUniform(const std::string& name, const dmat4 & m)
{
glUniformMatrix4dv(uniform(name), 1, GL_FALSE, value_ptr(m));
}
void ShaderProgram::setUniform(const std::string& name, const mat4 & m)
{
glUniformMatrix4fv(uniform(name), 1, GL_FALSE, value_ptr(m));
}
void ShaderProgram::setUniform(const std::string& name, const mat3 & m)
{
glUniformMatrix3fv(uniform(name), 1, GL_FALSE, value_ptr(m));
}
void ShaderProgram::setUniform(const std::string& name, float val )
{
glUniform1f(uniform(name), val);
}
void ShaderProgram::setUniform(const std::string& name, int val )
{
glUniform1i(uniform(name), val);
}
ShaderProgram::~ShaderProgram()
{
//glDeleteProgram(handle);
}
void ShaderProgram::use() const
{
glUseProgram(handle);
}
void ShaderProgram::unuse() const
{
glUseProgram(0);
}
GLuint ShaderProgram::getHandle() const
{
return handle;
}
<commit_msg>Fix missing header<commit_after>/**
* Shader.cpp
* Contributors:
* * Arthur Sonzogni (author)
* Licence:
* * Public Domain
*/
#include "Shader.hpp"
#include <vector>
#include <fstream>
#include <iostream>
#include <cstdlib>
#include <stdexcept>
#include <glm/gtc/type_ptr.hpp>
using namespace std;
using namespace glm;
// file reading
void getFileContents(const char *filename, vector<char>& buffer)
{
//debug("chargement du fichier : %s",filename);
ifstream file(filename, ios_base::binary);
if (file)
{
file.seekg(0, ios_base::end);
streamsize size = file.tellg();
if (size > 0)
{
file.seekg(0, ios_base::beg);
buffer.resize(static_cast<size_t>(size));
file.read(&buffer[0], size);
}
buffer.push_back('\0');
}
else
{
throw std::invalid_argument(string("The file ") + filename + " doesn't exists");
}
}
Shader::Shader(const std::string &filename, GLenum type)
{
// file loading
vector<char> fileContent;
getFileContents(filename.c_str(),fileContent);
// creation
handle = glCreateShader(type);
if(handle == 0)
throw std::runtime_error("[Error] Impossible to create a new Shader");
// code source assignation
const char* shaderText(&fileContent[0]);
glShaderSource(handle, 1, (const GLchar**)&shaderText, NULL);
// compilation
glCompileShader(handle);
// compilation check
GLint compile_status;
glGetShaderiv(handle, GL_COMPILE_STATUS, &compile_status);
if(compile_status != GL_TRUE)
{
/* error text retreiving*/
GLsizei logsize = 0;
glGetShaderiv(handle, GL_INFO_LOG_LENGTH, &logsize);
char* log = new char[logsize+1];
glGetShaderInfoLog(handle, logsize, &logsize, log);
//log[logsize]='\0';
cout<<"[Error] compilation error: "<<filename<<endl;
cout<<log<<endl;
exit(EXIT_FAILURE);
}
else
{
cout<<"[Info] Shader "<<filename<<" compiled successfully"<<endl;
}
}
GLuint Shader::getHandle() const
{
return handle;
}
Shader::~Shader()
{
}
ShaderProgram::ShaderProgram()
{
// programme creation
handle = glCreateProgram();
if (not handle)
throw std::runtime_error("Impossible to create a new shader program");
}
ShaderProgram::ShaderProgram(std::initializer_list<Shader> shaderList):
ShaderProgram()
{
for(auto& s : shaderList)
glAttachShader(handle,s.getHandle());
link();
}
void ShaderProgram::link()
{
glLinkProgram(handle);
GLint result;
glGetProgramiv(handle,GL_LINK_STATUS, &result);
if (result!=GL_TRUE)
{
cout<<"[Error] linkage error"<<endl;
/* error text retreiving*/
GLsizei logsize = 0;
glGetProgramiv(handle, GL_INFO_LOG_LENGTH, &logsize);
char* log = new char[logsize];
glGetProgramInfoLog(handle, logsize, &logsize, log);
//log[logsize]='\0';
cout<<log<<endl;
}
}
GLint ShaderProgram::uniform(const std::string &name)
{
auto it = uniforms.find(name);
if (it == uniforms.end())
{
// uniform that is not referenced
GLint r = glGetUniformLocation(handle, name.c_str());
if ( r == GL_INVALID_OPERATION || r < 0 )
cout<<"[Error] uniform "<<name<<" doesn't exist in program"<<endl;
// add it anyways
uniforms[name] = r;
return r;
}
else
return it->second;
}
GLint ShaderProgram::attribute(const std::string& name)
{
GLint attrib = glGetAttribLocation(handle, name.c_str());
if (attrib == GL_INVALID_OPERATION || attrib < 0 )
cout<<"[Error] Attribute "<<name<<" doesn't exist in program"<<endl;
return attrib;
}
void ShaderProgram::setAttribute(const std::string& name, GLint size, GLsizei stride, GLuint offset,
GLboolean normalize,
GLenum type)
{
GLint loc = attribute(name);
glEnableVertexAttribArray(loc);
glVertexAttribPointer(
loc,
size,
type,
normalize,
stride,
reinterpret_cast<void*>(offset)
);
}
void ShaderProgram::setAttribute(const std::string& name, GLint size, GLsizei stride, GLuint offset,
GLboolean normalize)
{
setAttribute(name,size,stride,offset,normalize,GL_FLOAT);
}
void ShaderProgram::setAttribute(const std::string& name, GLint size, GLsizei stride, GLuint offset,
GLenum type)
{
setAttribute(name,size,stride,offset,false,type);
}
void ShaderProgram::setAttribute(const std::string& name, GLint size, GLsizei stride, GLuint offset)
{
setAttribute(name,size,stride,offset,false,GL_FLOAT);
}
void ShaderProgram::setUniform(const std::string& name,float x,float y,float z)
{
glUniform3f(uniform(name), x, y, z);
}
void ShaderProgram::setUniform(const std::string& name, const vec3 & v)
{
glUniform3fv(uniform(name), 1, value_ptr(v));
}
void ShaderProgram::setUniform(const std::string& name, const dvec3 & v)
{
glUniform3dv(uniform(name), 1, value_ptr(v));
}
void ShaderProgram::setUniform(const std::string& name, const vec4 & v)
{
glUniform4fv(uniform(name), 1, value_ptr(v));
}
void ShaderProgram::setUniform(const std::string& name, const dvec4 & v)
{
glUniform4dv(uniform(name), 1, value_ptr(v));
}
void ShaderProgram::setUniform(const std::string& name, const dmat4 & m)
{
glUniformMatrix4dv(uniform(name), 1, GL_FALSE, value_ptr(m));
}
void ShaderProgram::setUniform(const std::string& name, const mat4 & m)
{
glUniformMatrix4fv(uniform(name), 1, GL_FALSE, value_ptr(m));
}
void ShaderProgram::setUniform(const std::string& name, const mat3 & m)
{
glUniformMatrix3fv(uniform(name), 1, GL_FALSE, value_ptr(m));
}
void ShaderProgram::setUniform(const std::string& name, float val )
{
glUniform1f(uniform(name), val);
}
void ShaderProgram::setUniform(const std::string& name, int val )
{
glUniform1i(uniform(name), val);
}
ShaderProgram::~ShaderProgram()
{
//glDeleteProgram(handle);
}
void ShaderProgram::use() const
{
glUseProgram(handle);
}
void ShaderProgram::unuse() const
{
glUseProgram(0);
}
GLuint ShaderProgram::getHandle() const
{
return handle;
}
<|endoftext|> |
<commit_before>#include "gui/coordinate.h"
#include "globals.h"
using namespace Gui;
static int getHorizontalAbsolute(double x){
const int center = Global::getScreenWidth()/2;
return (int)(center + (center * x));
}
static int getVerticalAbsolute(double y){
const int center = Global::getScreenHeight()/2;
return (int)(center + (center * y));
}
static double getHorizontalRelative(int x){
const int center = Global::getScreenWidth()/2;
if (x == center){
return 0;
} else if (x < center){
return -( (x/center) * .01);
} else if (x > center){
return ( ((x - center)/center) * .01);
}
return 0;
}
static double getVerticalRelative(int y){
const int center = Global::getScreenHeight()/2;
if (y == center){
return 0;
} else if (y < center){
return -( (y/center) * .01);
} else if (y > center){
return ( ((y - center)/center) * .01);
}
return 0;
}
AbsolutePoint::AbsolutePoint(){
}
AbsolutePoint::AbsolutePoint(int x, int y){
}
AbsolutePoint::~AbsolutePoint(){
}
int AbsolutePoint::getX(){
return x;
}
int AbsolutePoint::getY(){
return y;
}
RelativePoint::RelativePoint(){
}
RelativePoint::RelativePoint(double x, double y){
}
RelativePoint::~RelativePoint(){
}
int RelativePoint::getX(){
return getHorizontalAbsolute(x);
}
int RelativePoint::getY(){
return getVerticalAbsolute(y);
}
AbsolutePoint RelativePoint::getAbsolute(){
return AbsolutePoint(getHorizontalAbsolute(x),getVerticalAbsolute(y));
}
double RelativePoint::getRelativeX(){
return x;
}
double RelativePoint::getRelativeY(){
return y;
}
Coordinate::Coordinate(){
}
Coordinate::Coordinate(const AbsolutePoint &, const AbsolutePoint &){
}
Coordinate::Coordinate(const RelativePoint &, const RelativePoint &){
}
Coordinate::~Coordinate(){
}
void Coordinate::setZ(double z){
}
void Coordinate::setRadius(double radius){
}
int Coordinate::getX(){
return position.getX();
}
int Coordinate::getY(){
return position.getY();
}
int Coordinate::getWidth(){
return dimensions.getX();
}
int Coordinate::getHeight(){
return dimensions.getY();
}
<commit_msg>Clean up relative/absolute conversions<commit_after>#include "gui/coordinate.h"
#include "globals.h"
using namespace Gui;
static int relativeToAbsolute(double x, int center){
return (int)(center + (center * x));
}
static double absoluteToRelative(int x, int center){
return (x-center)/center;
}
AbsolutePoint::AbsolutePoint(){
}
AbsolutePoint::AbsolutePoint(int x, int y){
}
AbsolutePoint::~AbsolutePoint(){
}
int AbsolutePoint::getX(){
return x;
}
int AbsolutePoint::getY(){
return y;
}
RelativePoint::RelativePoint(){
}
RelativePoint::RelativePoint(double x, double y){
}
RelativePoint::~RelativePoint(){
}
int RelativePoint::getX(){
return relativeToAbsolute(x,Global::getScreenWidth()/2);
}
int RelativePoint::getY(){
return relativeToAbsolute(y,Global::getScreenHeight()/2);
}
AbsolutePoint RelativePoint::getAbsolute(){
return AbsolutePoint(relativeToAbsolute(x,Global::getScreenWidth()/2), relativeToAbsolute(y,Global::getScreenHeight()/2));
}
double RelativePoint::getRelativeX(){
return x;
}
double RelativePoint::getRelativeY(){
return y;
}
Coordinate::Coordinate(){
}
Coordinate::Coordinate(const AbsolutePoint &, const AbsolutePoint &){
}
Coordinate::Coordinate(const RelativePoint &, const RelativePoint &){
}
Coordinate::~Coordinate(){
}
void Coordinate::setZ(double z){
}
void Coordinate::setRadius(double radius){
}
int Coordinate::getX(){
return position.getX();
}
int Coordinate::getY(){
return position.getY();
}
int Coordinate::getWidth(){
return dimensions.getX();
}
int Coordinate::getHeight(){
return dimensions.getY();
}
<|endoftext|> |
<commit_before>#include "fallbackedgedb.h"
#include <fstream>
#include <limits>
using namespace annis;
using namespace std;
FallbackEdgeDB::FallbackEdgeDB(StringStorage &strings, const Component &component)
: strings(strings), component(component)
{
}
void FallbackEdgeDB::addEdge(const Edge &edge)
{
if(edge.source != edge.target)
{
edges.insert(edge);
}
}
void FallbackEdgeDB::addEdgeAnnotation(const Edge& edge, const Annotation &anno)
{
edgeAnnotations.insert2(edge, anno);
}
void FallbackEdgeDB::clear()
{
edges.clear();
edgeAnnotations.clear();
}
bool FallbackEdgeDB::isConnected(const Edge &edge, unsigned int minDistance, unsigned int maxDistance) const
{
typedef stx::btree_set<Edge>::const_iterator EdgeIt;
if(minDistance == 1 && maxDistance == 1)
{
EdgeIt it = edges.find(edge);
if(it != edges.end())
{
return true;
}
else
{
return false;
}
}
else
{
FallbackDFSIterator dfs(*this, edge.source, minDistance, maxDistance);
DFSIteratorResult result = dfs.nextDFS();
while(result.found)
{
if(result.node == edge.target)
{
return true;
}
result = dfs.nextDFS();
}
}
return false;
}
std::unique_ptr<EdgeIterator> FallbackEdgeDB::findConnected(nodeid_t sourceNode,
unsigned int minDistance,
unsigned int maxDistance) const
{
return std::unique_ptr<EdgeIterator>(
new FallbackDFSIterator(*this, sourceNode, minDistance, maxDistance));
}
int FallbackEdgeDB::distance(const Edge &edge) const
{
FallbackDFSIterator dfs(*this, edge.source, 0, uintmax);
DFSIteratorResult result = dfs.nextDFS();
while(result.found)
{
if(result.node == edge.target)
{
return result.distance;
}
result = dfs.nextDFS();
}
return -1;
}
std::vector<Annotation> FallbackEdgeDB::getEdgeAnnotations(const Edge& edge) const
{
typedef stx::btree_multimap<Edge, Annotation>::const_iterator ItType;
std::vector<Annotation> result;
std::pair<ItType, ItType> range =
edgeAnnotations.equal_range(edge);
for(ItType it=range.first; it != range.second; ++it)
{
result.push_back(it->second);
}
return result;
}
std::vector<nodeid_t> FallbackEdgeDB::getOutgoingEdges(nodeid_t node) const
{
typedef stx::btree_set<Edge>::const_iterator EdgeIt;
vector<nodeid_t> result;
EdgeIt lowerIt = edges.lower_bound(Init::initEdge(node, numeric_limits<uint32_t>::min()));
EdgeIt upperIt = edges.upper_bound(Init::initEdge(node, numeric_limits<uint32_t>::max()));
for(EdgeIt it = lowerIt; it != upperIt; it++)
{
result.push_back(it->target);
}
return result;
}
std::vector<nodeid_t> FallbackEdgeDB::getIncomingEdges(nodeid_t node) const
{
// this is a extremly slow approach, there should be more efficient methods for other
// edge databases
// TODO: we should also concider to add another index
std::vector<nodeid_t> result;
result.reserve(10);
for(auto& e : edges)
{
if(e.target == node)
{
result.push_back(e.source);
}
}
return result;
}
bool FallbackEdgeDB::load(std::string dirPath)
{
clear();
ifstream in;
in.open(dirPath + "/edges.btree");
edges.restore(in);
in.close();
in.open(dirPath + "/edgeAnnotations.btree");
edgeAnnotations.restore(in);
in.close();
return true;
}
bool FallbackEdgeDB::save(std::string dirPath)
{
ofstream out;
out.open(dirPath + "/edges.btree");
edges.dump(out);
out.close();
out.open(dirPath + "/edgeAnnotations.btree");
edgeAnnotations.dump(out);
out.close();
return true;
}
std::uint32_t FallbackEdgeDB::numberOfEdges() const
{
return edges.size();
}
std::uint32_t FallbackEdgeDB::numberOfEdgeAnnotations() const
{
return edgeAnnotations.size();
}
FallbackDFSIterator::FallbackDFSIterator(const FallbackEdgeDB &edb,
std::uint32_t startNode,
unsigned int minDistance,
unsigned int maxDistance)
: edb(edb), minDistance(minDistance), maxDistance(maxDistance), startNode(startNode)
{
initStack();
}
DFSIteratorResult FallbackDFSIterator::nextDFS()
{
DFSIteratorResult result;
result.found = false;
while(!result.found && !traversalStack.empty())
{
pair<uint32_t, unsigned int> stackEntry = traversalStack.top();
result.node = stackEntry.first;
result.distance = stackEntry.second;
traversalStack.pop();
if(result.distance >= minDistance && result.distance <= maxDistance)
{
// get the next node
result.found = true;
}
// add the remaining child nodes
if(result.distance < maxDistance)
{
// add the outgoing edges to the stack
auto outgoing = edb.getOutgoingEdges(result.node);
for(size_t idxOutgoing=0; idxOutgoing < outgoing.size(); idxOutgoing++)
{
if(visited.find(outgoing[idxOutgoing]) == visited.end())
{
traversalStack.push(pair<nodeid_t, unsigned int>(outgoing[idxOutgoing],
result.distance+1));
visited.insert(outgoing[idxOutgoing]);
}
}
}
}
return result;
}
std::pair<bool, nodeid_t> FallbackDFSIterator::next()
{
DFSIteratorResult result = nextDFS();
return std::pair<bool, nodeid_t>(result.found, result.node);
}
void FallbackDFSIterator::initStack()
{
// add the initial value to the stack
traversalStack.push(pair<uint32_t,unsigned int>(startNode, 0));
visited.insert(startNode);
}
void FallbackDFSIterator::reset()
{
// clear the stack
while(!traversalStack.empty())
{
traversalStack.pop();
}
visited.clear();
initStack();
}
<commit_msg>use iterator for looping over the outgoing edges<commit_after>#include "fallbackedgedb.h"
#include <fstream>
#include <limits>
using namespace annis;
using namespace std;
FallbackEdgeDB::FallbackEdgeDB(StringStorage &strings, const Component &component)
: strings(strings), component(component)
{
}
void FallbackEdgeDB::addEdge(const Edge &edge)
{
if(edge.source != edge.target)
{
edges.insert(edge);
}
}
void FallbackEdgeDB::addEdgeAnnotation(const Edge& edge, const Annotation &anno)
{
edgeAnnotations.insert2(edge, anno);
}
void FallbackEdgeDB::clear()
{
edges.clear();
edgeAnnotations.clear();
}
bool FallbackEdgeDB::isConnected(const Edge &edge, unsigned int minDistance, unsigned int maxDistance) const
{
typedef stx::btree_set<Edge>::const_iterator EdgeIt;
if(minDistance == 1 && maxDistance == 1)
{
EdgeIt it = edges.find(edge);
if(it != edges.end())
{
return true;
}
else
{
return false;
}
}
else
{
FallbackDFSIterator dfs(*this, edge.source, minDistance, maxDistance);
DFSIteratorResult result = dfs.nextDFS();
while(result.found)
{
if(result.node == edge.target)
{
return true;
}
result = dfs.nextDFS();
}
}
return false;
}
std::unique_ptr<EdgeIterator> FallbackEdgeDB::findConnected(nodeid_t sourceNode,
unsigned int minDistance,
unsigned int maxDistance) const
{
return std::unique_ptr<EdgeIterator>(
new FallbackDFSIterator(*this, sourceNode, minDistance, maxDistance));
}
int FallbackEdgeDB::distance(const Edge &edge) const
{
FallbackDFSIterator dfs(*this, edge.source, 0, uintmax);
DFSIteratorResult result = dfs.nextDFS();
while(result.found)
{
if(result.node == edge.target)
{
return result.distance;
}
result = dfs.nextDFS();
}
return -1;
}
std::vector<Annotation> FallbackEdgeDB::getEdgeAnnotations(const Edge& edge) const
{
typedef stx::btree_multimap<Edge, Annotation>::const_iterator ItType;
std::vector<Annotation> result;
std::pair<ItType, ItType> range =
edgeAnnotations.equal_range(edge);
for(ItType it=range.first; it != range.second; ++it)
{
result.push_back(it->second);
}
return result;
}
std::vector<nodeid_t> FallbackEdgeDB::getOutgoingEdges(nodeid_t node) const
{
typedef stx::btree_set<Edge>::const_iterator EdgeIt;
vector<nodeid_t> result;
EdgeIt lowerIt = edges.lower_bound(Init::initEdge(node, numeric_limits<uint32_t>::min()));
EdgeIt upperIt = edges.upper_bound(Init::initEdge(node, numeric_limits<uint32_t>::max()));
for(EdgeIt it = lowerIt; it != upperIt; it++)
{
result.push_back(it->target);
}
return result;
}
std::vector<nodeid_t> FallbackEdgeDB::getIncomingEdges(nodeid_t node) const
{
// this is a extremly slow approach, there should be more efficient methods for other
// edge databases
// TODO: we should also concider to add another index
std::vector<nodeid_t> result;
result.reserve(10);
for(auto& e : edges)
{
if(e.target == node)
{
result.push_back(e.source);
}
}
return result;
}
bool FallbackEdgeDB::load(std::string dirPath)
{
clear();
ifstream in;
in.open(dirPath + "/edges.btree");
edges.restore(in);
in.close();
in.open(dirPath + "/edgeAnnotations.btree");
edgeAnnotations.restore(in);
in.close();
return true;
}
bool FallbackEdgeDB::save(std::string dirPath)
{
ofstream out;
out.open(dirPath + "/edges.btree");
edges.dump(out);
out.close();
out.open(dirPath + "/edgeAnnotations.btree");
edgeAnnotations.dump(out);
out.close();
return true;
}
std::uint32_t FallbackEdgeDB::numberOfEdges() const
{
return edges.size();
}
std::uint32_t FallbackEdgeDB::numberOfEdgeAnnotations() const
{
return edgeAnnotations.size();
}
FallbackDFSIterator::FallbackDFSIterator(const FallbackEdgeDB &edb,
std::uint32_t startNode,
unsigned int minDistance,
unsigned int maxDistance)
: edb(edb), minDistance(minDistance), maxDistance(maxDistance), startNode(startNode)
{
initStack();
}
DFSIteratorResult FallbackDFSIterator::nextDFS()
{
DFSIteratorResult result;
result.found = false;
while(!result.found && !traversalStack.empty())
{
pair<uint32_t, unsigned int> stackEntry = traversalStack.top();
result.node = stackEntry.first;
result.distance = stackEntry.second;
traversalStack.pop();
if(result.distance >= minDistance && result.distance <= maxDistance)
{
// get the next node
result.found = true;
}
// add the remaining child nodes
if(result.distance < maxDistance)
{
// add the outgoing edges to the stack
auto outgoing = edb.getOutgoingEdges(result.node);
for(const auto& outNodeID : outgoing)
{
if(visited.find(outNodeID) == visited.end())
{
traversalStack.push(pair<nodeid_t, unsigned int>(outNodeID,
result.distance+1));
visited.insert(outNodeID);
}
}
}
}
return result;
}
std::pair<bool, nodeid_t> FallbackDFSIterator::next()
{
DFSIteratorResult result = nextDFS();
return std::pair<bool, nodeid_t>(result.found, result.node);
}
void FallbackDFSIterator::initStack()
{
// add the initial value to the stack
traversalStack.push(pair<uint32_t,unsigned int>(startNode, 0));
visited.insert(startNode);
}
void FallbackDFSIterator::reset()
{
// clear the stack
while(!traversalStack.empty())
{
traversalStack.pop();
}
visited.clear();
initStack();
}
<|endoftext|> |
<commit_before>//
// GLWarpShader.cpp
// gatherer
//
// Created by David Hirvonen on 8/28/15.
//
//
#include "graphics/GLWarpShader.h"
#include "graphics/RenderTexture.h"
#include "graphics/GLTexture.h"
#include "graphics/GLExtra.h"
_GATHERER_GRAPHICS_BEGIN
WarpShader::WarpShader(const cv::Size &size, const cv::Point2f &resolution)
: m_size(size)
, m_resolution(resolution)
{
compileShadersPlanar();
}
void WarpShader::compileShadersPlanar()
{
using gatherer::graphics::RenderTexture;
// vertex shader
const char *kPlanarVertexShaderString = R"(
attribute vec4 position;
attribute vec4 inputTextureCoordinate;
varying vec2 textureCoordinate;
uniform mat4 modelViewProjMatrix;
void main()
{
gl_Position = modelViewProjMatrix * position;
textureCoordinate = inputTextureCoordinate.xy;
})";
const char *kPlanarFragmentShaderString =
#if defined(GATHERER_OPENGL_ES)
"varying highp vec2 textureCoordinate;\n"
#else
"varying vec2 textureCoordinate;\n"
#endif
R"(
uniform sampler2D texture;
void main()
{
gl_FragColor = texture2D(texture, textureCoordinate);
})";
// m_frameVertices, i.e. (0, 0, w, h)
// m_textureCoordinates, i.e. (-1, -1, 1, 1)
const GLchar * vShaderStr[] = { kPlanarVertexShaderString };
const GLchar * fShaderStr[] = { kPlanarFragmentShaderString };
std::vector< std::pair<int, const char *> > attributes;
attributes.push_back( std::pair<int, const char*>(RenderTexture::ATTRIB_VERTEX, "position") );
attributes.push_back( std::pair<int, const char*>(RenderTexture::ATTRIB_TEXTUREPOSITION, "inputTextureCoordinate") );
m_pPlanarShaderProgram = std::make_unique<gatherer::graphics::shader_prog>(vShaderStr, fShaderStr, attributes);
m_PlanarUniformMVP = m_pPlanarShaderProgram->GetUniformLocation("modelViewProjMatrix");
m_PlanarUniformTexture = m_pPlanarShaderProgram->GetUniformLocation("texture");
gatherer::graphics::glErrorTest();
}
GLuint WarpShader::operator()(int texture)
{
const float w = m_size.width;
const float h = m_size.height;
// Transform to rectangle defined by (-1,-1) (+1,+1)
cv::Matx33f T(1,0,-w/2,0,1,-h/2,0,0,1);
cv::Matx33f S(2.0/w,0,0,0,2.0/h,0,0,0,1);
// Otionally add some effect:
const float theta = (m_count % 360) * M_PI / 180.f;
const float c = std::cos(theta);
const float s = std::sin(theta);
cv::Matx33f R(+c, -s, 0, +s, +c, 0, 0, 0, 1);
cv::Matx33f H = S * R * T;
(*this)(texture, H);
m_count ++;
return 0;
}
void WarpShader::operator()(int texture, const cv::Matx33f &H)
{
using gatherer::graphics::RenderTexture;
using gatherer::graphics::GLTexRect;
cv::Matx44f MVPt;
R3x3To4x4(H.t(), MVPt);
GLTexRect roi(m_size);
// {-1,-1}, {1,-1}, {-1,1}, {1,1}
auto vertices = roi.GetVertices();
auto coords = GLTexRect::GetTextureCoordinates();
std::vector<cv::Vec4f> vertices4d;
for(const auto &p : vertices)
vertices4d.emplace_back(p.x, (m_size.height - p.y), 0, 1);
// Note: We'll assume this is configured by the calling functions
// Note: for rendering to the display we need to factor in screen resolution
//glViewport(0, 0, int(m_resolution.x * m_size.width + 0.5f), int(m_resolution.y * m_size.height + 0.5f));
(*m_pPlanarShaderProgram)();
glUniformMatrix4fv(m_PlanarUniformMVP, 1, 0, (GLfloat *)&MVPt(0,0));
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT);
glBindTexture(GL_TEXTURE_2D, texture);
//std::cout << "glBindTexture " << int(glGetError()) << std::endl;
glVertexAttribPointer(RenderTexture::ATTRIB_VERTEX, 4, GL_FLOAT, 0, 0, &vertices4d[0][0]);
glEnableVertexAttribArray(RenderTexture::ATTRIB_VERTEX);
glVertexAttribPointer(RenderTexture::ATTRIB_TEXTUREPOSITION, 2, GL_FLOAT, 0, 0, &coords[0]);
glEnableVertexAttribArray(RenderTexture::ATTRIB_TEXTUREPOSITION);
//std::cout << "glVertex stuff " << int(glGetError()) << std::endl;
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
}
_GATHERER_GRAPHICS_END
<commit_msg>return to c++11 without c++14 make_unique TODO<commit_after>//
// GLWarpShader.cpp
// gatherer
//
// Created by David Hirvonen on 8/28/15.
//
//
#include "graphics/GLWarpShader.h"
#include "graphics/RenderTexture.h"
#include "graphics/GLTexture.h"
#include "graphics/GLExtra.h"
_GATHERER_GRAPHICS_BEGIN
WarpShader::WarpShader(const cv::Size &size, const cv::Point2f &resolution)
: m_size(size)
, m_resolution(resolution)
{
compileShadersPlanar();
}
void WarpShader::compileShadersPlanar()
{
using gatherer::graphics::RenderTexture;
// vertex shader
const char *kPlanarVertexShaderString = R"(
attribute vec4 position;
attribute vec4 inputTextureCoordinate;
varying vec2 textureCoordinate;
uniform mat4 modelViewProjMatrix;
void main()
{
gl_Position = modelViewProjMatrix * position;
textureCoordinate = inputTextureCoordinate.xy;
})";
const char *kPlanarFragmentShaderString =
#if defined(GATHERER_OPENGL_ES)
"varying highp vec2 textureCoordinate;\n"
#else
"varying vec2 textureCoordinate;\n"
#endif
R"(
uniform sampler2D texture;
void main()
{
gl_FragColor = texture2D(texture, textureCoordinate);
})";
// m_frameVertices, i.e. (0, 0, w, h)
// m_textureCoordinates, i.e. (-1, -1, 1, 1)
const GLchar * vShaderStr[] = { kPlanarVertexShaderString };
const GLchar * fShaderStr[] = { kPlanarFragmentShaderString };
std::vector< std::pair<int, const char *> > attributes;
attributes.push_back( std::pair<int, const char*>(RenderTexture::ATTRIB_VERTEX, "position") );
attributes.push_back( std::pair<int, const char*>(RenderTexture::ATTRIB_TEXTUREPOSITION, "inputTextureCoordinate") );
m_pPlanarShaderProgram = make_unique<gatherer::graphics::shader_prog>(vShaderStr, fShaderStr, attributes);
m_PlanarUniformMVP = m_pPlanarShaderProgram->GetUniformLocation("modelViewProjMatrix");
m_PlanarUniformTexture = m_pPlanarShaderProgram->GetUniformLocation("texture");
gatherer::graphics::glErrorTest();
}
GLuint WarpShader::operator()(int texture)
{
const float w = m_size.width;
const float h = m_size.height;
// Transform to rectangle defined by (-1,-1) (+1,+1)
cv::Matx33f T(1,0,-w/2,0,1,-h/2,0,0,1);
cv::Matx33f S(2.0/w,0,0,0,2.0/h,0,0,0,1);
// Otionally add some effect:
const float theta = (m_count % 360) * M_PI / 180.f;
const float c = std::cos(theta);
const float s = std::sin(theta);
cv::Matx33f R(+c, -s, 0, +s, +c, 0, 0, 0, 1);
cv::Matx33f H = S * R * T;
(*this)(texture, H);
m_count ++;
return 0;
}
void WarpShader::operator()(int texture, const cv::Matx33f &H)
{
using gatherer::graphics::RenderTexture;
using gatherer::graphics::GLTexRect;
cv::Matx44f MVPt;
R3x3To4x4(H.t(), MVPt);
GLTexRect roi(m_size);
// {-1,-1}, {1,-1}, {-1,1}, {1,1}
auto vertices = roi.GetVertices();
auto coords = GLTexRect::GetTextureCoordinates();
std::vector<cv::Vec4f> vertices4d;
for(const auto &p : vertices)
vertices4d.emplace_back(p.x, (m_size.height - p.y), 0, 1);
// Note: We'll assume this is configured by the calling functions
// Note: for rendering to the display we need to factor in screen resolution
//glViewport(0, 0, int(m_resolution.x * m_size.width + 0.5f), int(m_resolution.y * m_size.height + 0.5f));
(*m_pPlanarShaderProgram)();
glUniformMatrix4fv(m_PlanarUniformMVP, 1, 0, (GLfloat *)&MVPt(0,0));
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT);
glBindTexture(GL_TEXTURE_2D, texture);
//std::cout << "glBindTexture " << int(glGetError()) << std::endl;
glVertexAttribPointer(RenderTexture::ATTRIB_VERTEX, 4, GL_FLOAT, 0, 0, &vertices4d[0][0]);
glEnableVertexAttribArray(RenderTexture::ATTRIB_VERTEX);
glVertexAttribPointer(RenderTexture::ATTRIB_TEXTUREPOSITION, 2, GL_FLOAT, 0, 0, &coords[0]);
glEnableVertexAttribArray(RenderTexture::ATTRIB_TEXTUREPOSITION);
//std::cout << "glVertex stuff " << int(glGetError()) << std::endl;
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
}
_GATHERER_GRAPHICS_END
<|endoftext|> |
<commit_before>#include "util/bitmap.h"
#include "util/trans-bitmap.h"
#include "tabbed-box.h"
#include "menu/menu.h"
#include "util/font.h"
#include "gui/context-box.h"
using namespace Gui;
#if 0
/* FIXME add rounded tabs */
static void roundTab( const Bitmap & work, int radius, int x1, int y1, int x2, int y2, int color, bool bottom = true ){
const int width = x2 - x1;
const int height = y2 - y1;
radius = Mid(0, radius, Min((x1+width - x1)/2, (y1+height - y1)/2));
work.circleFill(x1+radius, y1+radius, radius, color);
work.circleFill((x1+width)-radius, y1+radius, radius, color);
work.circleFill(x1+radius, (y1+height)-radius, radius, color);
work.circleFill((x1+width)-radius, (y1+height)-radius, radius, color);
work.rectangleFill( x1+radius, y1, x2-radius, y1+radius, color);
work.rectangleFill( x1, y1+radius, x2, y2-radius, color);
work.rectangleFill( x1+radius, y2-radius, x2-radius, y2, color);
work.line(x1+radius, y1, x1+width-radius, y1, color);
work.line(x1+radius, y1+height, x1+width-radius,y1+height, color);
work.line(x1, y1+radius,x1, y1+height-radius, color);
work.line(x1+width, y1+radius,x1+width, y1+height-radius, color);
arc(work, x1+radius, y1+radius, S_PI-1.115, radius, color);
arc(work, x1+radius + (width - radius *2), y1+radius, -S_PI/2 +0.116, radius, color);
arc(work, x1+width-radius, y1+height-radius, -0.110, radius ,color);
arc(work, x1+radius, y1+height-radius, S_PI/2-0.119, radius, color);
}
#endif
Tab::Tab():
context(new ContextBox()),
active(false){
// Set alpha to 0 as we are not interested in the box
context->colors.borderAlpha = 0;
context->colors.bodyAlpha = 0;
}
Tab::~Tab(){
delete context;
}
TabbedBox::TabbedBox():
current(0),
fontWidth(24),
fontHeight(24),
inTab(false),
tabWidthMax(0),
tabFontColor(Bitmap::makeColor(255,255,255)),
currentTabFontColor(Bitmap::makeColor(0,0,255)){
activeTabFontColor = new Effects::Gradient(50, tabFontColor, currentTabFontColor);
}
TabbedBox::TabbedBox(const TabbedBox & b):
activeTabFontColor(NULL){
this->location = b.location;
this->workArea = b.workArea;
}
TabbedBox::~TabbedBox(){
for (std::vector<Gui::Tab *>::iterator i = tabs.begin(); i != tabs.end(); ++i){
Gui::Tab * tab = *i;
if (tab){
delete tab;
}
}
if (activeTabFontColor){
delete activeTabFontColor;
}
}
TabbedBox &TabbedBox::operator=( const TabbedBox ©){
location = copy.location;
workArea = copy.workArea;
return *this;
}
// Logic
void TabbedBox::act(){
if (!tabs.empty()){
const Font & vFont = Font::getFont(font, fontWidth, fontHeight);
//tabWidthMax = location.getWidth()/tabs.size();
const int width = vFont.textLength(tabs[current]->name.c_str()) + 5;
tabWidthMax = (location.getWidth() - width) / (tabs.size() - 1);
} else {
return;
}
if (!tabs[current]->active){
tabs[current]->active = true;
}
tabs[current]->context->act();
if (inTab){
if (activeTabFontColor){
activeTabFontColor->update();
}
}
}
// Render
void TabbedBox::render(const Bitmap & work){
const int tabHeight = fontHeight + 5;
// checkWorkArea();
Bitmap area(work, location.getX(), location.getY(), location.getWidth(), location.getHeight());
// Check if we are using a rounded box
if (location.getRadius() > 0){
//roundRectFill( *workArea, (int)location.getRadius(), 0, 0, location.getWidth()-1, location.getHeight()-1, colors.body );
//roundRect( *workArea, (int)location.getRadius(), 0, 0, location.getWidth()-1, location.getHeight()-1, colors.border );
} else {
area.translucent().rectangleFill(0, tabHeight+1, location.getWidth()-1, location.getHeight()-1, colors.body );
//area.translucent().rectangle(0, tabHeight, location.getWidth()-1, location.getHeight()-1, colors.border );
area.translucent().vLine(tabHeight,0,location.getHeight()-1,colors.border);
area.translucent().hLine(0,location.getHeight()-1,location.getWidth()-1,colors.border);
area.translucent().vLine(tabHeight,location.getWidth()-1,location.getHeight()-1,colors.border);
}
tabs[current]->context->render(area);
renderTabs(area);
/* FIXME: only render the background in translucent mode, the text should
* not be translucent
*/
// workArea->draw(location.getX(), location.getY(), work);
}
// Add tab
void TabbedBox::addTab(const std::string & name, const std::vector<ContextItem *> & list){
for (std::vector<Tab *>::iterator i = tabs.begin(); i != tabs.end(); ++i){
Tab * tab = *i;
if (tab->name == name){
return;
}
}
Tab * tab = new Tab();
tab->name = name;
tab->context->setList(list);
tab->context->setFont(font, fontWidth, fontHeight);
const int modifier = fontHeight * .35;
tab->context->location.setPosition(Gui::AbsolutePoint(0, fontHeight + modifier));
tab->context->location.setPosition2(Gui::AbsolutePoint(location.getWidth(), location.getHeight()- modifier));
tab->context->open();
tabs.push_back(tab);
}
void TabbedBox::moveTab(int direction){
tabs[current]->context->close();
tabs[current]->active = false;
current = (current + direction + tabs.size()) % tabs.size();
/*
if (current == 0){
current = tabs.size()-1;
} else {
current--;
}
*/
tabs[current]->context->open();
tabs[current]->active = true;
}
void TabbedBox::up(){
if (tabs.size() == 0){
return;
}
if (!inTab){
moveTab(-1);
} else {
tabs[current]->context->previous();
}
}
void TabbedBox::down(){
if (tabs.size() == 0){
return;
}
if (!inTab){
moveTab(1);
} else {
tabs[current]->context->next();
}
}
void TabbedBox::left(){
if (tabs.size() == 0){
return;
}
if (!inTab){
moveTab(-1);
} else {
tabs[current]->context->adjustLeft();
}
}
void TabbedBox::right(){
if (tabs.size() == 0){
return;
}
if (!inTab){
moveTab(1);
} else {
tabs[current]->context->adjustRight();
}
}
void TabbedBox::toggleTabSelect(){
inTab = !inTab;
}
unsigned int TabbedBox::getCurrentIndex() const {
if (tabs.size() == 0){
return 0;
}
return this->tabs[current]->context->getCurrentIndex();
}
void TabbedBox::setTabFontColor(int color){
tabFontColor = color;
if (activeTabFontColor){
delete activeTabFontColor;
}
activeTabFontColor = new Effects::Gradient(50, tabFontColor, currentTabFontColor);
}
void TabbedBox::setSelectedTabFontColor(int color){
currentTabFontColor = color;
if (activeTabFontColor){
delete activeTabFontColor;
}
activeTabFontColor = new Effects::Gradient(50, tabFontColor, currentTabFontColor);
}
void TabbedBox::renderTabs(const Bitmap & bmp){
const int tabHeight = fontHeight + 5;
const Font & vFont = Font::getFont(font, fontWidth, fontHeight);
int x = 0;
Bitmap::transBlender(0, 0, 0, colors.bodyAlpha);
for (std::vector<Gui::Tab *>::iterator i = tabs.begin(); i != tabs.end(); ++i){
Gui::Tab * tab = *i;
const int textWidth = vFont.textLength(tab->name.c_str()) + 5;
// for last tab
int modifier = 0;
// Check last tab so we can ensure proper sizing
if ( i == (tabs.begin() + tabs.size() -1)){
if ( ( (tabWidthMax * (tabs.size() - 1) ) + textWidth ) != (unsigned int)location.getWidth() ){
modifier = location.getWidth() - x - (tab->active ? textWidth : tabWidthMax);
}
}
if (tab->context->location.getRadius() > 0){
} else {
if (tab->active){
if (!inTab){
//bmp.translucent().rectangle(x, 0, x+textWidth + modifier - 1, tabHeight, colors.border);
bmp.translucent().vLine(0,x,tabHeight,colors.border);
bmp.translucent().hLine(x,0,x+textWidth+modifier-1,colors.border);
bmp.translucent().vLine(0,x+textWidth+modifier-1,tabHeight,colors.border);
bmp.translucent().rectangleFill( x+1, 1, x+textWidth + modifier - 2, tabHeight, colors.body);
bmp.setClipRect(x, 0, x+textWidth + modifier, tabHeight-1);
vFont.printf(x + (((textWidth + modifier)/2)-(((textWidth + modifier) - 5)/2)), 0, currentTabFontColor, bmp, tab->name, 0 );
} else {
//bmp.translucent().rectangle(x, 0, x+textWidth + modifier -1, tabHeight, colors.border);
bmp.translucent().vLine(0,x,tabHeight,colors.border);
bmp.translucent().hLine(x,0,x+textWidth+modifier-1,colors.border);
bmp.translucent().vLine(0,x+textWidth+modifier-1,tabHeight,colors.border);
bmp.translucent().rectangleFill( x+1, 1, x+textWidth-2 + modifier, tabHeight, colors.body );
bmp.setClipRect(x, 0, x+textWidth + modifier, tabHeight-1);
vFont.printf(x + (((textWidth + modifier)/2)-(((textWidth + modifier) - 5)/2)), 0, activeTabFontColor->current(), bmp, tab->name, 0 );
}
x+=textWidth + modifier;
} else {
const int heightMod = tabHeight * .15;
bmp.translucent().rectangle(x, 1 + heightMod, x+tabWidthMax + modifier -1, tabHeight, tabColors.border);
bmp.translucent().hLine(x,tabHeight,x+tabWidthMax+modifier-1,colors.border);
bmp.translucent().rectangleFill( x+1, 2 + heightMod, x+tabWidthMax + modifier -2, tabHeight-2, tabColors.body);
bmp.setClipRect(x+2, 6 + heightMod, x+tabWidthMax + modifier -3, tabHeight-1);
vFont.printf(x + (((tabWidthMax + modifier)/2)-((textWidth + modifier)/2)), 0, tabFontColor, bmp, tab->name, 0 );
x += tabWidthMax + modifier;
}
bmp.setClipRect(0, 0, bmp.getWidth(), bmp.getHeight());
}
}
}
<commit_msg>Cast to int.<commit_after>#include "util/bitmap.h"
#include "util/trans-bitmap.h"
#include "tabbed-box.h"
#include "menu/menu.h"
#include "util/font.h"
#include "gui/context-box.h"
using namespace Gui;
#if 0
/* FIXME add rounded tabs */
static void roundTab( const Bitmap & work, int radius, int x1, int y1, int x2, int y2, int color, bool bottom = true ){
const int width = x2 - x1;
const int height = y2 - y1;
radius = Mid(0, radius, Min((x1+width - x1)/2, (y1+height - y1)/2));
work.circleFill(x1+radius, y1+radius, radius, color);
work.circleFill((x1+width)-radius, y1+radius, radius, color);
work.circleFill(x1+radius, (y1+height)-radius, radius, color);
work.circleFill((x1+width)-radius, (y1+height)-radius, radius, color);
work.rectangleFill( x1+radius, y1, x2-radius, y1+radius, color);
work.rectangleFill( x1, y1+radius, x2, y2-radius, color);
work.rectangleFill( x1+radius, y2-radius, x2-radius, y2, color);
work.line(x1+radius, y1, x1+width-radius, y1, color);
work.line(x1+radius, y1+height, x1+width-radius,y1+height, color);
work.line(x1, y1+radius,x1, y1+height-radius, color);
work.line(x1+width, y1+radius,x1+width, y1+height-radius, color);
arc(work, x1+radius, y1+radius, S_PI-1.115, radius, color);
arc(work, x1+radius + (width - radius *2), y1+radius, -S_PI/2 +0.116, radius, color);
arc(work, x1+width-radius, y1+height-radius, -0.110, radius ,color);
arc(work, x1+radius, y1+height-radius, S_PI/2-0.119, radius, color);
}
#endif
Tab::Tab():
context(new ContextBox()),
active(false){
// Set alpha to 0 as we are not interested in the box
context->colors.borderAlpha = 0;
context->colors.bodyAlpha = 0;
}
Tab::~Tab(){
delete context;
}
TabbedBox::TabbedBox():
current(0),
fontWidth(24),
fontHeight(24),
inTab(false),
tabWidthMax(0),
tabFontColor(Bitmap::makeColor(255,255,255)),
currentTabFontColor(Bitmap::makeColor(0,0,255)){
activeTabFontColor = new Effects::Gradient(50, tabFontColor, currentTabFontColor);
}
TabbedBox::TabbedBox(const TabbedBox & b):
activeTabFontColor(NULL){
this->location = b.location;
this->workArea = b.workArea;
}
TabbedBox::~TabbedBox(){
for (std::vector<Gui::Tab *>::iterator i = tabs.begin(); i != tabs.end(); ++i){
Gui::Tab * tab = *i;
if (tab){
delete tab;
}
}
if (activeTabFontColor){
delete activeTabFontColor;
}
}
TabbedBox &TabbedBox::operator=( const TabbedBox ©){
location = copy.location;
workArea = copy.workArea;
return *this;
}
// Logic
void TabbedBox::act(){
if (!tabs.empty()){
const Font & vFont = Font::getFont(font, fontWidth, fontHeight);
//tabWidthMax = location.getWidth()/tabs.size();
const int width = vFont.textLength(tabs[current]->name.c_str()) + 5;
tabWidthMax = (location.getWidth() - width) / (tabs.size() - 1);
} else {
return;
}
if (!tabs[current]->active){
tabs[current]->active = true;
}
tabs[current]->context->act();
if (inTab){
if (activeTabFontColor){
activeTabFontColor->update();
}
}
}
// Render
void TabbedBox::render(const Bitmap & work){
const int tabHeight = fontHeight + 5;
// checkWorkArea();
Bitmap area(work, location.getX(), location.getY(), location.getWidth(), location.getHeight());
// Check if we are using a rounded box
if (location.getRadius() > 0){
//roundRectFill( *workArea, (int)location.getRadius(), 0, 0, location.getWidth()-1, location.getHeight()-1, colors.body );
//roundRect( *workArea, (int)location.getRadius(), 0, 0, location.getWidth()-1, location.getHeight()-1, colors.border );
} else {
area.translucent().rectangleFill(0, tabHeight+1, location.getWidth()-1, location.getHeight()-1, colors.body );
//area.translucent().rectangle(0, tabHeight, location.getWidth()-1, location.getHeight()-1, colors.border );
area.translucent().vLine(tabHeight,0,location.getHeight()-1,colors.border);
area.translucent().hLine(0,location.getHeight()-1,location.getWidth()-1,colors.border);
area.translucent().vLine(tabHeight,location.getWidth()-1,location.getHeight()-1,colors.border);
}
tabs[current]->context->render(area);
renderTabs(area);
/* FIXME: only render the background in translucent mode, the text should
* not be translucent
*/
// workArea->draw(location.getX(), location.getY(), work);
}
// Add tab
void TabbedBox::addTab(const std::string & name, const std::vector<ContextItem *> & list){
for (std::vector<Tab *>::iterator i = tabs.begin(); i != tabs.end(); ++i){
Tab * tab = *i;
if (tab->name == name){
return;
}
}
Tab * tab = new Tab();
tab->name = name;
tab->context->setList(list);
tab->context->setFont(font, fontWidth, fontHeight);
const int modifier = fontHeight * .35;
tab->context->location.setPosition(Gui::AbsolutePoint(0, fontHeight + modifier));
tab->context->location.setPosition2(Gui::AbsolutePoint(location.getWidth(), location.getHeight()- modifier));
tab->context->open();
tabs.push_back(tab);
}
void TabbedBox::moveTab(int direction){
tabs[current]->context->close();
tabs[current]->active = false;
current = ((int)current + direction + tabs.size()) % tabs.size();
/*
if (current == 0){
current = tabs.size()-1;
} else {
current--;
}
*/
tabs[current]->context->open();
tabs[current]->active = true;
}
void TabbedBox::up(){
if (tabs.size() == 0){
return;
}
if (!inTab){
moveTab(-1);
} else {
tabs[current]->context->previous();
}
}
void TabbedBox::down(){
if (tabs.size() == 0){
return;
}
if (!inTab){
moveTab(1);
} else {
tabs[current]->context->next();
}
}
void TabbedBox::left(){
if (tabs.size() == 0){
return;
}
if (!inTab){
moveTab(-1);
} else {
tabs[current]->context->adjustLeft();
}
}
void TabbedBox::right(){
if (tabs.size() == 0){
return;
}
if (!inTab){
moveTab(1);
} else {
tabs[current]->context->adjustRight();
}
}
void TabbedBox::toggleTabSelect(){
inTab = !inTab;
}
unsigned int TabbedBox::getCurrentIndex() const {
if (tabs.size() == 0){
return 0;
}
return this->tabs[current]->context->getCurrentIndex();
}
void TabbedBox::setTabFontColor(int color){
tabFontColor = color;
if (activeTabFontColor){
delete activeTabFontColor;
}
activeTabFontColor = new Effects::Gradient(50, tabFontColor, currentTabFontColor);
}
void TabbedBox::setSelectedTabFontColor(int color){
currentTabFontColor = color;
if (activeTabFontColor){
delete activeTabFontColor;
}
activeTabFontColor = new Effects::Gradient(50, tabFontColor, currentTabFontColor);
}
void TabbedBox::renderTabs(const Bitmap & bmp){
const int tabHeight = fontHeight + 5;
const Font & vFont = Font::getFont(font, fontWidth, fontHeight);
int x = 0;
Bitmap::transBlender(0, 0, 0, colors.bodyAlpha);
for (std::vector<Gui::Tab *>::iterator i = tabs.begin(); i != tabs.end(); ++i){
Gui::Tab * tab = *i;
const int textWidth = vFont.textLength(tab->name.c_str()) + 5;
// for last tab
int modifier = 0;
// Check last tab so we can ensure proper sizing
if ( i == (tabs.begin() + tabs.size() -1)){
if ( ( (tabWidthMax * (tabs.size() - 1) ) + textWidth ) != (unsigned int)location.getWidth() ){
modifier = location.getWidth() - x - (tab->active ? textWidth : tabWidthMax);
}
}
if (tab->context->location.getRadius() > 0){
} else {
if (tab->active){
if (!inTab){
//bmp.translucent().rectangle(x, 0, x+textWidth + modifier - 1, tabHeight, colors.border);
bmp.translucent().vLine(0,x,tabHeight,colors.border);
bmp.translucent().hLine(x,0,x+textWidth+modifier-1,colors.border);
bmp.translucent().vLine(0,x+textWidth+modifier-1,tabHeight,colors.border);
bmp.translucent().rectangleFill( x+1, 1, x+textWidth + modifier - 2, tabHeight, colors.body);
bmp.setClipRect(x, 0, x+textWidth + modifier, tabHeight-1);
vFont.printf(x + (((textWidth + modifier)/2)-(((textWidth + modifier) - 5)/2)), 0, currentTabFontColor, bmp, tab->name, 0 );
} else {
//bmp.translucent().rectangle(x, 0, x+textWidth + modifier -1, tabHeight, colors.border);
bmp.translucent().vLine(0,x,tabHeight,colors.border);
bmp.translucent().hLine(x,0,x+textWidth+modifier-1,colors.border);
bmp.translucent().vLine(0,x+textWidth+modifier-1,tabHeight,colors.border);
bmp.translucent().rectangleFill( x+1, 1, x+textWidth-2 + modifier, tabHeight, colors.body );
bmp.setClipRect(x, 0, x+textWidth + modifier, tabHeight-1);
vFont.printf(x + (((textWidth + modifier)/2)-(((textWidth + modifier) - 5)/2)), 0, activeTabFontColor->current(), bmp, tab->name, 0 );
}
x+=textWidth + modifier;
} else {
const int heightMod = tabHeight * .15;
bmp.translucent().rectangle(x, 1 + heightMod, x+tabWidthMax + modifier -1, tabHeight, tabColors.border);
bmp.translucent().hLine(x,tabHeight,x+tabWidthMax+modifier-1,colors.border);
bmp.translucent().rectangleFill( x+1, 2 + heightMod, x+tabWidthMax + modifier -2, tabHeight-2, tabColors.body);
bmp.setClipRect(x+2, 6 + heightMod, x+tabWidthMax + modifier -3, tabHeight-1);
vFont.printf(x + (((tabWidthMax + modifier)/2)-((textWidth + modifier)/2)), 0, tabFontColor, bmp, tab->name, 0 );
x += tabWidthMax + modifier;
}
bmp.setClipRect(0, 0, bmp.getWidth(), bmp.getHeight());
}
}
}
<|endoftext|> |
<commit_before>#include "client.h"
#include "gconsole.h"
#include "net_worm.h"
#include "particle.h"
#include "part_type.h"
#include "game/WormInputHandler.h"
#include "gusgame.h"
#include "network.h"
#include "player_options.h"
#include "encoding.h"
#include <memory>
#include "util/log.h"
#include "netstream.h"
Client::Client() : Net_Control(false)
{
Net_setControlID(0);
Net_setDebugName("Net_CLI");
}
void Client::Net_cbConnectResult(eNet_ConnectResult res) {
if(res != eNet_ConnAccepted) {
errors << "Client::Net_cbConnectResult: connection not accepted" << endl;
return;
}
console.addLogMsg("* CONNECTION ACCEPTED");
network.incConnCount();
// earlier, we did the mod/level loading here
// _reply contained two strings, containing level/mod name
sendConsistencyInfo();
Net_requestNetMode(NetConnID_server(), 1);
}
Client::~Client()
{
}
void Client::sendConsistencyInfo()
{
std::auto_ptr<Net_BitStream> req(new Net_BitStream);
req->addInt(Network::ConsistencyInfo, 8);
req->addInt(Network::protocolVersion, 32);
gusGame.addCRCs(req.get());
Net_sendData( network.getServerID(), req.release(), eNet_ReliableOrdered );
}
void Client::Net_cbConnectionClosed(Net_ConnID _id, eNet_CloseReason _reason, Net_BitStream &_reasondata)
{
network.decConnCount();
switch( _reason )
{
case eNet_ClosedDisconnect:
{
Network::DConnEvents dcEvent = static_cast<Network::DConnEvents>( _reasondata.getInt(8) );
switch( dcEvent )
{
case Network::ServerMapChange:
{
console.addLogMsg("* SERVER CHANGED MAP");
network.olxReconnect(150);
gusGame.reset(GusGame::ServerChangeMap);
}
break;
case Network::Quit:
{
console.addLogMsg("* CONNECTION CLOSED BY SERVER");
gusGame.reset(GusGame::ServerQuit);
}
break;
case Network::Kick:
{
console.addLogMsg("* YOU WERE KICKED");
gusGame.reset(GusGame::Kicked);
}
break;
case Network::IncompatibleData:
{
console.addLogMsg("* YOU HAVE INCOMPATIBLE DATA");
gusGame.reset(GusGame::IncompatibleData);
}
break;
case Network::IncompatibleProtocol:
{
console.addLogMsg("* THE HOST RUNS AN INCOMPATIBLE VERSION OF VERMES");
gusGame.reset(GusGame::IncompatibleProtocol);
}
break;
default:
{
console.addLogMsg("* CONNECTION CLOSED BY DUNNO WHAT :O");
gusGame.reset(GusGame::ServerQuit);
}
break;
}
}
break;
case eNet_ClosedTimeout:
console.addLogMsg("* CONNECTION TIMEDOUT");
gusGame.reset(GusGame::ServerQuit);
break;
case eNet_ClosedReconnect:
console.addLogMsg("* CONNECTION RECONNECTED");
break;
default:
break;
}
DLOG("A connection was closed");
}
void Client::Net_cbDataReceived( Net_ConnID id, Net_BitStream& data)
{
int event = Encoding::decode(data, Network::ClientEvents::Max);
switch(event)
{
case Network::ClientEvents::LuaEvents:
{
for(int t = Network::LuaEventGroup::GusGame;
t < Network::LuaEventGroup::Max; ++t)
{
int c = data.getInt(8);
for(int i = 0; i < c; ++i)
{
std::string name = data.getString();
network.indexLuaEvent((Network::LuaEventGroup::type)t, name);
}
}
}
break;
}
}
void Client::Net_cbNodeRequest_Dynamic( Net_ConnID _id, Net_ClassID _requested_class, Net_BitStream *_announcedata, eNet_NodeRole _role, Net_NodeID _net_id )
{
// check the requested class
if ( _requested_class == CWorm::classID )
{
if(_announcedata == NULL) {
warnings << "Net_cbNodeRequest_Dynamic for CWorm without announce data" << endl;
return;
}
int wormid = _announcedata->getInt(8);
if(wormid < 0 || wormid >= MAX_WORMS) {
warnings << "Net_cbNodeRequest_Dynamic for CWorm: wormid " << wormid << " invalid" << endl;
return;
}
notes << "Net_cbNodeRequest_Dynamic for worm " << wormid << ", nodeid " << _net_id << endl;
CWorm* worm = &cClient->getRemoteWorms()[wormid];
if(!worm->isUsed()) {
warnings << "Net_cbNodeRequest_Dynamic for CWorm: worm " << wormid << " is not used" << endl;
return;
}
worm->NetWorm_Init(false);
}else if ( _requested_class == CWormInputHandler::classID )
{
if(_announcedata == NULL) {
warnings << "Net_cbNodeRequest_Dynamic for CWormInputHandler without announce data" << endl;
return;
}
int wormid = _announcedata->getInt(8);
if(wormid < 0 || wormid >= MAX_WORMS) {
warnings << "Net_cbNodeRequest_Dynamic for CWormInputHandler: wormid " << wormid << " invalid" << endl;
return;
}
CWorm* worm = &cClient->getRemoteWorms()[wormid];
if(!worm->isUsed()) {
warnings << "Net_cbNodeRequest_Dynamic for CWormInputHandler: worm " << wormid << " is not used" << endl;
return;
}
notes << "Net_cbNodeRequest_Dynamic: new player (node " << _net_id << ") for worm " << wormid << ", set to " << ((_role == eNet_RoleOwner) ? "owner" : "proxy") << endl;
// Creates a player class depending on the role
CWormInputHandler* player = gusGame.addPlayer ( (_role == eNet_RoleOwner) ? GusGame::OWNER : GusGame::PROXY, worm );
player->assignNetworkRole(false);
if(worm->m_inputHandler) {
warnings << "Net_cbNodeRequest_Dynamic: worm " << worm->getName() << " has already the following input handler set: "; warnings.flush();
warnings << worm->m_inputHandler->name() << endl;
worm->m_inputHandler->quit();
worm->m_inputHandler = NULL;
}
worm->m_inputHandler = player;
cClient->SetupGameInputs(); // we must init the inputs for the new inputhandler
if(cClient->getGameReady()) {
if(cClient->getStatus() == NET_PLAYING) // playing
player->startGame();
// Dont do that right now, no wpn selection in gus
/* else
player->initWeaponSelection(); */
}
}else if( _requested_class == Particle::classID )
{
int typeIndex = Encoding::decode(*_announcedata, partTypeList.size());
CWormInputHandler* owner = gusGame.findPlayerWithID(_announcedata->getInt(32));
newParticle_requested(partTypeList[typeIndex], Vec(), Vec(), 1, owner, Angle());
}else
{
console.addLogMsg("* ERROR: INVALID DYNAMIC NODE REQUEST");
}
}
<commit_msg>init wpn selection for lx<commit_after>#include "client.h"
#include "gconsole.h"
#include "net_worm.h"
#include "particle.h"
#include "part_type.h"
#include "game/WormInputHandler.h"
#include "gusgame.h"
#include "network.h"
#include "player_options.h"
#include "encoding.h"
#include <memory>
#include "util/log.h"
#include "netstream.h"
#include "game/Game.h"
#include "CGameScript.h"
Client::Client() : Net_Control(false)
{
Net_setControlID(0);
Net_setDebugName("Net_CLI");
}
void Client::Net_cbConnectResult(eNet_ConnectResult res) {
if(res != eNet_ConnAccepted) {
errors << "Client::Net_cbConnectResult: connection not accepted" << endl;
return;
}
console.addLogMsg("* CONNECTION ACCEPTED");
network.incConnCount();
// earlier, we did the mod/level loading here
// _reply contained two strings, containing level/mod name
sendConsistencyInfo();
Net_requestNetMode(NetConnID_server(), 1);
}
Client::~Client()
{
}
void Client::sendConsistencyInfo()
{
std::auto_ptr<Net_BitStream> req(new Net_BitStream);
req->addInt(Network::ConsistencyInfo, 8);
req->addInt(Network::protocolVersion, 32);
gusGame.addCRCs(req.get());
Net_sendData( network.getServerID(), req.release(), eNet_ReliableOrdered );
}
void Client::Net_cbConnectionClosed(Net_ConnID _id, eNet_CloseReason _reason, Net_BitStream &_reasondata)
{
network.decConnCount();
switch( _reason )
{
case eNet_ClosedDisconnect:
{
Network::DConnEvents dcEvent = static_cast<Network::DConnEvents>( _reasondata.getInt(8) );
switch( dcEvent )
{
case Network::ServerMapChange:
{
console.addLogMsg("* SERVER CHANGED MAP");
network.olxReconnect(150);
gusGame.reset(GusGame::ServerChangeMap);
}
break;
case Network::Quit:
{
console.addLogMsg("* CONNECTION CLOSED BY SERVER");
gusGame.reset(GusGame::ServerQuit);
}
break;
case Network::Kick:
{
console.addLogMsg("* YOU WERE KICKED");
gusGame.reset(GusGame::Kicked);
}
break;
case Network::IncompatibleData:
{
console.addLogMsg("* YOU HAVE INCOMPATIBLE DATA");
gusGame.reset(GusGame::IncompatibleData);
}
break;
case Network::IncompatibleProtocol:
{
console.addLogMsg("* THE HOST RUNS AN INCOMPATIBLE VERSION OF VERMES");
gusGame.reset(GusGame::IncompatibleProtocol);
}
break;
default:
{
console.addLogMsg("* CONNECTION CLOSED BY DUNNO WHAT :O");
gusGame.reset(GusGame::ServerQuit);
}
break;
}
}
break;
case eNet_ClosedTimeout:
console.addLogMsg("* CONNECTION TIMEDOUT");
gusGame.reset(GusGame::ServerQuit);
break;
case eNet_ClosedReconnect:
console.addLogMsg("* CONNECTION RECONNECTED");
break;
default:
break;
}
DLOG("A connection was closed");
}
void Client::Net_cbDataReceived( Net_ConnID id, Net_BitStream& data)
{
int event = Encoding::decode(data, Network::ClientEvents::Max);
switch(event)
{
case Network::ClientEvents::LuaEvents:
{
for(int t = Network::LuaEventGroup::GusGame;
t < Network::LuaEventGroup::Max; ++t)
{
int c = data.getInt(8);
for(int i = 0; i < c; ++i)
{
std::string name = data.getString();
network.indexLuaEvent((Network::LuaEventGroup::type)t, name);
}
}
}
break;
}
}
void Client::Net_cbNodeRequest_Dynamic( Net_ConnID _id, Net_ClassID _requested_class, Net_BitStream *_announcedata, eNet_NodeRole _role, Net_NodeID _net_id )
{
// check the requested class
if ( _requested_class == CWorm::classID )
{
if(_announcedata == NULL) {
warnings << "Net_cbNodeRequest_Dynamic for CWorm without announce data" << endl;
return;
}
int wormid = _announcedata->getInt(8);
if(wormid < 0 || wormid >= MAX_WORMS) {
warnings << "Net_cbNodeRequest_Dynamic for CWorm: wormid " << wormid << " invalid" << endl;
return;
}
notes << "Net_cbNodeRequest_Dynamic for worm " << wormid << ", nodeid " << _net_id << endl;
CWorm* worm = &cClient->getRemoteWorms()[wormid];
if(!worm->isUsed()) {
warnings << "Net_cbNodeRequest_Dynamic for CWorm: worm " << wormid << " is not used" << endl;
return;
}
worm->NetWorm_Init(false);
}else if ( _requested_class == CWormInputHandler::classID )
{
if(_announcedata == NULL) {
warnings << "Net_cbNodeRequest_Dynamic for CWormInputHandler without announce data" << endl;
return;
}
int wormid = _announcedata->getInt(8);
if(wormid < 0 || wormid >= MAX_WORMS) {
warnings << "Net_cbNodeRequest_Dynamic for CWormInputHandler: wormid " << wormid << " invalid" << endl;
return;
}
CWorm* worm = &cClient->getRemoteWorms()[wormid];
if(!worm->isUsed()) {
warnings << "Net_cbNodeRequest_Dynamic for CWormInputHandler: worm " << wormid << " is not used" << endl;
return;
}
notes << "Net_cbNodeRequest_Dynamic: new player (node " << _net_id << ") for worm " << wormid << ", set to " << ((_role == eNet_RoleOwner) ? "owner" : "proxy") << endl;
// Creates a player class depending on the role
CWormInputHandler* player = gusGame.addPlayer ( (_role == eNet_RoleOwner) ? GusGame::OWNER : GusGame::PROXY, worm );
player->assignNetworkRole(false);
if(worm->m_inputHandler) {
warnings << "Net_cbNodeRequest_Dynamic: worm " << worm->getName() << " has already the following input handler set: "; warnings.flush();
warnings << worm->m_inputHandler->name() << endl;
worm->m_inputHandler->quit();
worm->m_inputHandler = NULL;
}
worm->m_inputHandler = player;
cClient->SetupGameInputs(); // we must init the inputs for the new inputhandler
if(cClient->getGameReady()) {
if(cClient->getStatus() == NET_PLAYING) // playing
player->startGame();
else if(!game.gameScript()->gusEngineUsed())
player->initWeaponSelection();
}
}else if( _requested_class == Particle::classID )
{
int typeIndex = Encoding::decode(*_announcedata, partTypeList.size());
CWormInputHandler* owner = gusGame.findPlayerWithID(_announcedata->getInt(32));
newParticle_requested(partTypeList[typeIndex], Vec(), Vec(), 1, owner, Angle());
}else
{
console.addLogMsg("* ERROR: INVALID DYNAMIC NODE REQUEST");
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2015 Daniel Selsam. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Daniel Selsam
*/
#include "kernel/instantiate.h"
#include "kernel/abstract.h"
#include "kernel/inductive/inductive.h"
#include "library/blast/blast.h"
#include "library/blast/action_result.h"
#include "library/blast/forward/forward_actions.h"
#include "library/blast/proof_expr.h"
#include "library/blast/choice_point.h"
#include "library/blast/hypothesis.h"
#include "library/blast/util.h"
#include "library/expr_lt.h"
#include "library/head_map.h"
namespace lean {
namespace blast {
action_result qfc_action(list<gexpr> const & lemmas) {
return action_result::failed();
}
}}
<commit_msg>fix(library/blast/forward/qcf): compilation warning<commit_after>/*
Copyright (c) 2015 Daniel Selsam. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Daniel Selsam
*/
#include "kernel/instantiate.h"
#include "kernel/abstract.h"
#include "kernel/inductive/inductive.h"
#include "library/blast/blast.h"
#include "library/blast/action_result.h"
#include "library/blast/forward/forward_actions.h"
#include "library/blast/proof_expr.h"
#include "library/blast/choice_point.h"
#include "library/blast/hypothesis.h"
#include "library/blast/util.h"
#include "library/expr_lt.h"
#include "library/head_map.h"
namespace lean {
namespace blast {
action_result qfc_action(list<gexpr> const &) {
return action_result::failed();
}
}}
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 "itkJSONImageIO.h"
#include "itkMetaDataObject.h"
#include "itkIOCommon.h"
#include "rapidjson/document.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/ostreamwrapper.h"
namespace itk
{
JSONImageIO
::JSONImageIO()
{
this->SetNumberOfDimensions(3);
this->AddSupportedWriteExtension(".json");
this->AddSupportedReadExtension(".json");
}
JSONImageIO
::~JSONImageIO()
{
}
bool
JSONImageIO
::SupportsDimension(unsigned long itkNotUsed(dimension))
{
return true;
}
void
JSONImageIO
::PrintSelf(std::ostream & os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
}
ImageIOBase::IOComponentType
JSONImageIO
::JSToITKComponentType(const std::string & jsComponentType)
{
if( jsComponentType == "int8_t" )
{
return CHAR;
}
else if( jsComponentType == "uint8_t" )
{
return UCHAR;
}
else if( jsComponentType == "int16_t" )
{
return SHORT;
}
else if( jsComponentType == "uint16_t" )
{
return USHORT;
}
else if( jsComponentType == "int32_t" )
{
return INT;
}
else if( jsComponentType == "uint32_t" )
{
return UINT;
}
else if( jsComponentType == "int64_t" )
{
return LONGLONG;
}
else if( jsComponentType == "uint64_t" )
{
return ULONGLONG;
}
else if( jsComponentType == "float" )
{
return FLOAT;
}
else if( jsComponentType == "double" )
{
return DOUBLE;
}
return UNKNOWNCOMPONENTTYPE;
}
std::string
JSONImageIO
::ITKToJSComponentType(const ImageIOBase::IOComponentType itkComponentType)
{
switch ( itkComponentType )
{
case CHAR:
return "int8_t";
case UCHAR:
return "uint8_t";
case SHORT:
return "int16_t";
case USHORT:
return "uint16_t";;
case INT:
return "int32_t";
case UINT:
return "uint32_t";;
case LONG:
return "int64_t";
case ULONG:
return "uint64_t";;
case LONGLONG:
return "int64_t";
case ULONGLONG:
return "uint64_t";
case FLOAT:
return "float";
case DOUBLE:
return "double";
default:
return "int8_t";
}
}
ImageIOBase::IOPixelType
JSONImageIO
::JSToITKPixelType( const int jsPixelType )
{
switch ( jsPixelType )
{
case 0:
return UNKNOWNPIXELTYPE;
case 1:
return SCALAR;
case 2:
return RGB;
case 3:
return RGBA;
case 4:
return OFFSET;
case 5:
return VECTOR;
case 6:
return POINT;
case 7:
return COVARIANTVECTOR;
case 8:
return SYMMETRICSECONDRANKTENSOR;
case 9:
return DIFFUSIONTENSOR3D;
case 10:
return COMPLEX;
case 11:
return FIXEDARRAY;
case 13:
return MATRIX;
}
return UNKNOWNPIXELTYPE;
}
int
JSONImageIO
::ITKToJSPixelType( const ImageIOBase::IOPixelType itkPixelType )
{
switch ( itkPixelType )
{
case UNKNOWNPIXELTYPE:
return 0;
case SCALAR:
return 1;
case RGB:
return 2;
case RGBA:
return 3;
case OFFSET:
return 4;
case VECTOR:
return 5;
case POINT:
return 6;
case COVARIANTVECTOR:
return 7;
case SYMMETRICSECONDRANKTENSOR:
return 7;
case DIFFUSIONTENSOR3D:
return 7;
case COMPLEX:
return 10;
case FIXEDARRAY:
return 11;
case MATRIX:
return 13;
}
return 0;
}
bool
JSONImageIO
::CanReadFile(const char *filename)
{
// Check the extension first to avoid opening files that do not
// look like nrrds. The file must have an appropriate extension to be
// recognized.
std::string fname = filename;
bool extensionFound = false;
std::string::size_type jsonPos = fname.rfind(".json");
if ( ( jsonPos != std::string::npos )
&& ( jsonPos == fname.length() - 5 ) )
{
extensionFound = true;
}
if ( !extensionFound )
{
itkDebugMacro(<< "The filename extension is not recognized");
return false;
}
std::ifstream inputStream;
try
{
this->OpenFileForReading( inputStream, fname, true );
}
catch( ExceptionObject & )
{
return false;
}
std::string str((std::istreambuf_iterator<char>(inputStream)),
std::istreambuf_iterator<char>());
rapidjson::Document document;
if( document.Parse( str.c_str() ).HasParseError() )
{
inputStream.close();
return false;
}
if( !document.HasMember("imageType") )
{
return false;
}
inputStream.close();
return true;
}
void
JSONImageIO
::ReadImageInformation()
{
this->SetByteOrderToLittleEndian();
std::ifstream inputStream;
this->OpenFileForReading( inputStream, this->GetFileName(), true );
rapidjson::Document document;
std::string str((std::istreambuf_iterator<char>(inputStream)),
std::istreambuf_iterator<char>());
if (document.Parse(str.c_str()).HasParseError())
{
itkExceptionMacro("Could not parse JSON");
return;
}
const rapidjson::Value & imageType = document["imageType"];
const int dimension = imageType["dimension"].GetInt();
this->SetNumberOfDimensions( dimension );
const std::string componentType( imageType["componentType"].GetString() );
const ImageIOBase::IOComponentType ioComponentType = this->JSToITKComponentType( componentType );
this->SetComponentType( ioComponentType );
const int pixelType( imageType["pixelType"].GetInt() );
const ImageIOBase::IOPixelType ioPixelType = this->JSToITKPixelType( pixelType );
this->SetPixelType( ioPixelType );
this->SetNumberOfComponents( imageType["components"].GetInt() );
const rapidjson::Value & origin = document["origin"];
int count = 0;
for( rapidjson::Value::ConstValueIterator itr = origin.Begin(); itr != origin.End(); ++itr )
{
this->SetOrigin( count, itr->GetDouble() );
++count;
}
const rapidjson::Value & spacing = document["spacing"];
count = 0;
for( rapidjson::Value::ConstValueIterator itr = spacing.Begin(); itr != spacing.End(); ++itr )
{
this->SetSpacing( count, itr->GetDouble() );
++count;
}
const rapidjson::Value & directionContainer = document["direction"];
const rapidjson::Value & direction = directionContainer["data"];
count = 0;
for( rapidjson::Value::ConstValueIterator itr = direction.Begin(); itr != direction.End(); )
{
std::vector< double > direction( dimension );
for( unsigned int ii = 0; ii < dimension; ++ii )
{
direction[ii] = itr->GetDouble();
++itr;
}
this->SetDirection( count, direction );
++count;
}
const rapidjson::Value & size = document["size"];
count = 0;
for( rapidjson::Value::ConstValueIterator itr = size.Begin(); itr != size.End(); ++itr )
{
this->SetDimensions( count, itr->GetInt() );
++count;
}
}
void
JSONImageIO
::Read( void *buffer )
{
std::ifstream inputStream;
this->OpenFileForReading( inputStream, this->GetFileName(), true );
std::string str((std::istreambuf_iterator<char>(inputStream)),
std::istreambuf_iterator<char>());
rapidjson::Document document;
if ( document.Parse( str.c_str() ).HasParseError())
{
itkExceptionMacro("Could not parse JSON");
return;
}
const std::string dataFile( document["data"].GetString() );
std::ifstream dataStream;
this->OpenFileForReading( dataStream, dataFile.c_str() );
const SizeValueType numberOfBytesToBeRead =
static_cast< SizeValueType >( this->GetImageSizeInBytes() );
if ( !this->ReadBufferAsBinary( dataStream, buffer, numberOfBytesToBeRead ) )
{
itkExceptionMacro(<< "Read failed: Wanted "
<< numberOfBytesToBeRead
<< " bytes, but read "
<< dataStream.gcount() << " bytes.");
}
}
bool
JSONImageIO
::CanWriteFile(const char *name)
{
std::string filename = name;
if( filename == "" )
{
return false;
}
bool extensionFound = false;
std::string::size_type jsonPos = filename.rfind(".json");
if ( ( jsonPos != std::string::npos )
&& ( jsonPos == filename.length() - 5 ) )
{
extensionFound = true;
}
if ( !extensionFound )
{
itkDebugMacro(<< "The filename extension is not recognized");
return false;
}
return true;
}
void
JSONImageIO
::WriteImageInformation()
{
rapidjson::Document document;
document.SetObject();
rapidjson::Document::AllocatorType& allocator = document.GetAllocator();
rapidjson::Value imageType;
imageType.SetObject();
const unsigned int dimension = this->GetNumberOfDimensions();
imageType.AddMember("dimension", rapidjson::Value(dimension).Move(), allocator );
const std::string componentString = this->ITKToJSComponentType( this->GetComponentType() );
rapidjson::Value componentType;
componentType.SetString( componentString.c_str(), allocator );
imageType.AddMember("componentType", componentType.Move(), allocator );
const int pixelType = this->ITKToJSPixelType( this->GetPixelType() );
imageType.AddMember("pixelType", rapidjson::Value(pixelType).Move(), allocator );
imageType.AddMember("components", rapidjson::Value( this->GetNumberOfComponents() ).Move(), allocator );
document.AddMember( "imageType", imageType.Move(), allocator );
rapidjson::Value origin(rapidjson::kArrayType);
for( unsigned int ii = 0; ii < dimension; ++ii )
{
origin.PushBack(rapidjson::Value().SetDouble(this->GetOrigin( ii )), allocator);
}
document.AddMember( "origin", origin.Move(), allocator );
rapidjson::Value spacing(rapidjson::kArrayType);
for( unsigned int ii = 0; ii < dimension; ++ii )
{
spacing.PushBack(rapidjson::Value().SetDouble(this->GetSpacing( ii )), allocator);
}
document.AddMember( "spacing", spacing.Move(), allocator );
rapidjson::Value direction(rapidjson::kArrayType);
for( unsigned int ii = 0; ii < dimension; ++ii )
{
const std::vector< double > dimensionDirection = this->GetDirection( ii );
for( unsigned int jj = 0; jj < dimension; ++jj )
{
direction.PushBack(rapidjson::Value().SetDouble( dimensionDirection[jj] ), allocator);
}
}
document.AddMember( "direction", direction.Move(), allocator );
rapidjson::Value size(rapidjson::kArrayType);
for( unsigned int ii = 0; ii < dimension; ++ii )
{
size.PushBack(rapidjson::Value().SetInt( this->GetDimensions( ii ) ), allocator);
}
document.AddMember( "size", size.Move(), allocator );
std::string dataFileString( std::string( this->GetFileName() ) + ".data" );
rapidjson::Value dataFile;
dataFile.SetString( dataFileString.c_str(), allocator );
document.AddMember( "data", dataFile, allocator );
std::ofstream outputStream;
this->OpenFileForWriting( outputStream, this->GetFileName(), true, true );
rapidjson::OStreamWrapper ostreamWrapper( outputStream );
rapidjson::PrettyWriter< rapidjson::OStreamWrapper > writer( ostreamWrapper );
document.Accept( writer );
outputStream.close();
}
void
JSONImageIO
::Write( const void *buffer )
{
this->WriteImageInformation();
const std::string fileName = std::string( this->GetFileName() ) + ".data";
std::ofstream outputStream;
this->OpenFileForWriting( outputStream, fileName, true, false );
const SizeValueType numberOfBytes = this->GetImageSizeInBytes();
outputStream.write(static_cast< const char * >( buffer ), numberOfBytes); \
}
} // end namespace itk
<commit_msg>style(itkJSONImageIO): Fix too many semi-colons KWStyle error<commit_after>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 "itkJSONImageIO.h"
#include "itkMetaDataObject.h"
#include "itkIOCommon.h"
#include "rapidjson/document.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/ostreamwrapper.h"
namespace itk
{
JSONImageIO
::JSONImageIO()
{
this->SetNumberOfDimensions(3);
this->AddSupportedWriteExtension(".json");
this->AddSupportedReadExtension(".json");
}
JSONImageIO
::~JSONImageIO()
{
}
bool
JSONImageIO
::SupportsDimension(unsigned long itkNotUsed(dimension))
{
return true;
}
void
JSONImageIO
::PrintSelf(std::ostream & os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
}
ImageIOBase::IOComponentType
JSONImageIO
::JSToITKComponentType(const std::string & jsComponentType)
{
if( jsComponentType == "int8_t" )
{
return CHAR;
}
else if( jsComponentType == "uint8_t" )
{
return UCHAR;
}
else if( jsComponentType == "int16_t" )
{
return SHORT;
}
else if( jsComponentType == "uint16_t" )
{
return USHORT;
}
else if( jsComponentType == "int32_t" )
{
return INT;
}
else if( jsComponentType == "uint32_t" )
{
return UINT;
}
else if( jsComponentType == "int64_t" )
{
return LONGLONG;
}
else if( jsComponentType == "uint64_t" )
{
return ULONGLONG;
}
else if( jsComponentType == "float" )
{
return FLOAT;
}
else if( jsComponentType == "double" )
{
return DOUBLE;
}
return UNKNOWNCOMPONENTTYPE;
}
std::string
JSONImageIO
::ITKToJSComponentType(const ImageIOBase::IOComponentType itkComponentType)
{
switch ( itkComponentType )
{
case CHAR:
return "int8_t";
case UCHAR:
return "uint8_t";
case SHORT:
return "int16_t";
case USHORT:
return "uint16_t";
case INT:
return "int32_t";
case UINT:
return "uint32_t";
case LONG:
return "int64_t";
case ULONG:
return "uint64_t";
case LONGLONG:
return "int64_t";
case ULONGLONG:
return "uint64_t";
case FLOAT:
return "float";
case DOUBLE:
return "double";
default:
return "int8_t";
}
}
ImageIOBase::IOPixelType
JSONImageIO
::JSToITKPixelType( const int jsPixelType )
{
switch ( jsPixelType )
{
case 0:
return UNKNOWNPIXELTYPE;
case 1:
return SCALAR;
case 2:
return RGB;
case 3:
return RGBA;
case 4:
return OFFSET;
case 5:
return VECTOR;
case 6:
return POINT;
case 7:
return COVARIANTVECTOR;
case 8:
return SYMMETRICSECONDRANKTENSOR;
case 9:
return DIFFUSIONTENSOR3D;
case 10:
return COMPLEX;
case 11:
return FIXEDARRAY;
case 13:
return MATRIX;
}
return UNKNOWNPIXELTYPE;
}
int
JSONImageIO
::ITKToJSPixelType( const ImageIOBase::IOPixelType itkPixelType )
{
switch ( itkPixelType )
{
case UNKNOWNPIXELTYPE:
return 0;
case SCALAR:
return 1;
case RGB:
return 2;
case RGBA:
return 3;
case OFFSET:
return 4;
case VECTOR:
return 5;
case POINT:
return 6;
case COVARIANTVECTOR:
return 7;
case SYMMETRICSECONDRANKTENSOR:
return 7;
case DIFFUSIONTENSOR3D:
return 7;
case COMPLEX:
return 10;
case FIXEDARRAY:
return 11;
case MATRIX:
return 13;
}
return 0;
}
bool
JSONImageIO
::CanReadFile(const char *filename)
{
// Check the extension first to avoid opening files that do not
// look like nrrds. The file must have an appropriate extension to be
// recognized.
std::string fname = filename;
bool extensionFound = false;
std::string::size_type jsonPos = fname.rfind(".json");
if ( ( jsonPos != std::string::npos )
&& ( jsonPos == fname.length() - 5 ) )
{
extensionFound = true;
}
if ( !extensionFound )
{
itkDebugMacro(<< "The filename extension is not recognized");
return false;
}
std::ifstream inputStream;
try
{
this->OpenFileForReading( inputStream, fname, true );
}
catch( ExceptionObject & )
{
return false;
}
std::string str((std::istreambuf_iterator<char>(inputStream)),
std::istreambuf_iterator<char>());
rapidjson::Document document;
if( document.Parse( str.c_str() ).HasParseError() )
{
inputStream.close();
return false;
}
if( !document.HasMember("imageType") )
{
return false;
}
inputStream.close();
return true;
}
void
JSONImageIO
::ReadImageInformation()
{
this->SetByteOrderToLittleEndian();
std::ifstream inputStream;
this->OpenFileForReading( inputStream, this->GetFileName(), true );
rapidjson::Document document;
std::string str((std::istreambuf_iterator<char>(inputStream)),
std::istreambuf_iterator<char>());
if (document.Parse(str.c_str()).HasParseError())
{
itkExceptionMacro("Could not parse JSON");
return;
}
const rapidjson::Value & imageType = document["imageType"];
const int dimension = imageType["dimension"].GetInt();
this->SetNumberOfDimensions( dimension );
const std::string componentType( imageType["componentType"].GetString() );
const ImageIOBase::IOComponentType ioComponentType = this->JSToITKComponentType( componentType );
this->SetComponentType( ioComponentType );
const int pixelType( imageType["pixelType"].GetInt() );
const ImageIOBase::IOPixelType ioPixelType = this->JSToITKPixelType( pixelType );
this->SetPixelType( ioPixelType );
this->SetNumberOfComponents( imageType["components"].GetInt() );
const rapidjson::Value & origin = document["origin"];
int count = 0;
for( rapidjson::Value::ConstValueIterator itr = origin.Begin(); itr != origin.End(); ++itr )
{
this->SetOrigin( count, itr->GetDouble() );
++count;
}
const rapidjson::Value & spacing = document["spacing"];
count = 0;
for( rapidjson::Value::ConstValueIterator itr = spacing.Begin(); itr != spacing.End(); ++itr )
{
this->SetSpacing( count, itr->GetDouble() );
++count;
}
const rapidjson::Value & directionContainer = document["direction"];
const rapidjson::Value & direction = directionContainer["data"];
count = 0;
for( rapidjson::Value::ConstValueIterator itr = direction.Begin(); itr != direction.End(); )
{
std::vector< double > direction( dimension );
for( unsigned int ii = 0; ii < dimension; ++ii )
{
direction[ii] = itr->GetDouble();
++itr;
}
this->SetDirection( count, direction );
++count;
}
const rapidjson::Value & size = document["size"];
count = 0;
for( rapidjson::Value::ConstValueIterator itr = size.Begin(); itr != size.End(); ++itr )
{
this->SetDimensions( count, itr->GetInt() );
++count;
}
}
void
JSONImageIO
::Read( void *buffer )
{
std::ifstream inputStream;
this->OpenFileForReading( inputStream, this->GetFileName(), true );
std::string str((std::istreambuf_iterator<char>(inputStream)),
std::istreambuf_iterator<char>());
rapidjson::Document document;
if ( document.Parse( str.c_str() ).HasParseError())
{
itkExceptionMacro("Could not parse JSON");
return;
}
const std::string dataFile( document["data"].GetString() );
std::ifstream dataStream;
this->OpenFileForReading( dataStream, dataFile.c_str() );
const SizeValueType numberOfBytesToBeRead =
static_cast< SizeValueType >( this->GetImageSizeInBytes() );
if ( !this->ReadBufferAsBinary( dataStream, buffer, numberOfBytesToBeRead ) )
{
itkExceptionMacro(<< "Read failed: Wanted "
<< numberOfBytesToBeRead
<< " bytes, but read "
<< dataStream.gcount() << " bytes.");
}
}
bool
JSONImageIO
::CanWriteFile(const char *name)
{
std::string filename = name;
if( filename == "" )
{
return false;
}
bool extensionFound = false;
std::string::size_type jsonPos = filename.rfind(".json");
if ( ( jsonPos != std::string::npos )
&& ( jsonPos == filename.length() - 5 ) )
{
extensionFound = true;
}
if ( !extensionFound )
{
itkDebugMacro(<< "The filename extension is not recognized");
return false;
}
return true;
}
void
JSONImageIO
::WriteImageInformation()
{
rapidjson::Document document;
document.SetObject();
rapidjson::Document::AllocatorType& allocator = document.GetAllocator();
rapidjson::Value imageType;
imageType.SetObject();
const unsigned int dimension = this->GetNumberOfDimensions();
imageType.AddMember("dimension", rapidjson::Value(dimension).Move(), allocator );
const std::string componentString = this->ITKToJSComponentType( this->GetComponentType() );
rapidjson::Value componentType;
componentType.SetString( componentString.c_str(), allocator );
imageType.AddMember("componentType", componentType.Move(), allocator );
const int pixelType = this->ITKToJSPixelType( this->GetPixelType() );
imageType.AddMember("pixelType", rapidjson::Value(pixelType).Move(), allocator );
imageType.AddMember("components", rapidjson::Value( this->GetNumberOfComponents() ).Move(), allocator );
document.AddMember( "imageType", imageType.Move(), allocator );
rapidjson::Value origin(rapidjson::kArrayType);
for( unsigned int ii = 0; ii < dimension; ++ii )
{
origin.PushBack(rapidjson::Value().SetDouble(this->GetOrigin( ii )), allocator);
}
document.AddMember( "origin", origin.Move(), allocator );
rapidjson::Value spacing(rapidjson::kArrayType);
for( unsigned int ii = 0; ii < dimension; ++ii )
{
spacing.PushBack(rapidjson::Value().SetDouble(this->GetSpacing( ii )), allocator);
}
document.AddMember( "spacing", spacing.Move(), allocator );
rapidjson::Value direction(rapidjson::kArrayType);
for( unsigned int ii = 0; ii < dimension; ++ii )
{
const std::vector< double > dimensionDirection = this->GetDirection( ii );
for( unsigned int jj = 0; jj < dimension; ++jj )
{
direction.PushBack(rapidjson::Value().SetDouble( dimensionDirection[jj] ), allocator);
}
}
document.AddMember( "direction", direction.Move(), allocator );
rapidjson::Value size(rapidjson::kArrayType);
for( unsigned int ii = 0; ii < dimension; ++ii )
{
size.PushBack(rapidjson::Value().SetInt( this->GetDimensions( ii ) ), allocator);
}
document.AddMember( "size", size.Move(), allocator );
std::string dataFileString( std::string( this->GetFileName() ) + ".data" );
rapidjson::Value dataFile;
dataFile.SetString( dataFileString.c_str(), allocator );
document.AddMember( "data", dataFile, allocator );
std::ofstream outputStream;
this->OpenFileForWriting( outputStream, this->GetFileName(), true, true );
rapidjson::OStreamWrapper ostreamWrapper( outputStream );
rapidjson::PrettyWriter< rapidjson::OStreamWrapper > writer( ostreamWrapper );
document.Accept( writer );
outputStream.close();
}
void
JSONImageIO
::Write( const void *buffer )
{
this->WriteImageInformation();
const std::string fileName = std::string( this->GetFileName() ) + ".data";
std::ofstream outputStream;
this->OpenFileForWriting( outputStream, fileName, true, false );
const SizeValueType numberOfBytes = this->GetImageSizeInBytes();
outputStream.write(static_cast< const char * >( buffer ), numberOfBytes); \
}
} // end namespace itk
<|endoftext|> |
<commit_before>#include "utils/tag-loader/tag-loader.h"
#include <QMessageBox>
#include <ui_tag-loader.h>
#include "helpers.h"
#include "models/profile.h"
#include "models/site.h"
#include "tags/tag-database.h"
#include "tools/tag-list-loader.h"
#define MIN_TAG_COUNT 20
TagLoader::TagLoader(Profile *profile, QWidget *parent)
: QDialog(parent), ui(new Ui::TagLoader), m_profile(profile), m_sites(profile->getSites())
{
ui->setupUi(this);
resetOptions();
ui->widgetProgress->hide();
resize(size().width(), 0);
}
TagLoader::~TagLoader()
{
delete ui;
}
void TagLoader::resetOptions()
{
m_options.clear();
QStringList keys;
for (auto it = m_sites.constBegin(); it != m_sites.constEnd(); ++it) {
Site *site = it.value();
if (TagListLoader::canLoadTags(site)) {
m_options.append(it.key());
keys.append(QString("%1 (%L2 tags)").arg(it.key()).arg(site->tagDatabase()->count()));
}
}
int index = ui->comboSource->currentIndex();
ui->comboSource->clear();
ui->comboSource->addItems(keys);
if (index >= 0) {
ui->comboSource->setCurrentIndex(index);
}
}
void TagLoader::cancel()
{
if (m_loader != nullptr) {
m_loader->cancel();
}
emit rejected();
close();
deleteLater();
}
void TagLoader::start()
{
Site *site = m_sites.value(m_options[ui->comboSource->currentIndex()]);
// Show progress bar
ui->buttonStart->setEnabled(false);
ui->progressBar->setValue(0);
ui->progressBar->setMinimum(0);
ui->progressBar->setMaximum(0);
ui->labelProgress->setText("");
ui->widgetProgress->show();
// Start loader
m_loader = new TagListLoader(m_profile, site, MIN_TAG_COUNT, this);
connect(m_loader, TagListLoader::progress, ui->labelProgress, &QLabel::setText);
connect(m_loader, TagListLoader::finished, this, &TagLoader::finishedLoading);
m_loader->start();
}
void TagLoader::finishedLoading()
{
// Hide progress bar
ui->buttonStart->setEnabled(true);
ui->widgetProgress->hide();
resize(size().width(), 0);
// Handle errors
if (!m_loader->error().isEmpty()) {
error(this, m_loader->error());
} else {
QMessageBox::information(this, tr("Finished"), tr("%n tag(s) loaded", "", m_loader->results().count()));
}
// Clean-up
m_loader->deleteLater();
m_loader = nullptr;
resetOptions();
}
<commit_msg>Fix pointer to method syntax in TagLoader class<commit_after>#include "utils/tag-loader/tag-loader.h"
#include <QMessageBox>
#include <ui_tag-loader.h>
#include "helpers.h"
#include "models/profile.h"
#include "models/site.h"
#include "tags/tag-database.h"
#include "tools/tag-list-loader.h"
#define MIN_TAG_COUNT 20
TagLoader::TagLoader(Profile *profile, QWidget *parent)
: QDialog(parent), ui(new Ui::TagLoader), m_profile(profile), m_sites(profile->getSites())
{
ui->setupUi(this);
resetOptions();
ui->widgetProgress->hide();
resize(size().width(), 0);
}
TagLoader::~TagLoader()
{
delete ui;
}
void TagLoader::resetOptions()
{
m_options.clear();
QStringList keys;
for (auto it = m_sites.constBegin(); it != m_sites.constEnd(); ++it) {
Site *site = it.value();
if (TagListLoader::canLoadTags(site)) {
m_options.append(it.key());
keys.append(QString("%1 (%L2 tags)").arg(it.key()).arg(site->tagDatabase()->count()));
}
}
int index = ui->comboSource->currentIndex();
ui->comboSource->clear();
ui->comboSource->addItems(keys);
if (index >= 0) {
ui->comboSource->setCurrentIndex(index);
}
}
void TagLoader::cancel()
{
if (m_loader != nullptr) {
m_loader->cancel();
}
emit rejected();
close();
deleteLater();
}
void TagLoader::start()
{
Site *site = m_sites.value(m_options[ui->comboSource->currentIndex()]);
// Show progress bar
ui->buttonStart->setEnabled(false);
ui->progressBar->setValue(0);
ui->progressBar->setMinimum(0);
ui->progressBar->setMaximum(0);
ui->labelProgress->setText("");
ui->widgetProgress->show();
// Start loader
m_loader = new TagListLoader(m_profile, site, MIN_TAG_COUNT, this);
connect(m_loader, &TagListLoader::progress, ui->labelProgress, &QLabel::setText);
connect(m_loader, &TagListLoader::finished, this, &TagLoader::finishedLoading);
m_loader->start();
}
void TagLoader::finishedLoading()
{
// Hide progress bar
ui->buttonStart->setEnabled(true);
ui->widgetProgress->hide();
resize(size().width(), 0);
// Handle errors
if (!m_loader->error().isEmpty()) {
error(this, m_loader->error());
} else {
QMessageBox::information(this, tr("Finished"), tr("%n tag(s) loaded", "", m_loader->results().count()));
}
// Clean-up
m_loader->deleteLater();
m_loader = nullptr;
resetOptions();
}
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/common/scominfo/p9_cu.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_cu.H
/// @brief P9 chip unit definitions
///
/// HWP HWP Owner: [email protected]
/// HWP FW Owner: [email protected]
/// HWP Team: Infrastructure
/// HWP Level: 1
/// HWP Consumed by: FSP/HB
///
#ifndef P9_CU_H
#define P9_CU_H
// includes
#include <stdint.h>
extern "C"
{
/// P9 chip unit type enumeration
typedef enum
{
P9C_CHIP, ///< Cumulus chip (included for future expansion)
P9N_CHIP, ///< Nimbus chip (included for future expansion)
PU_C_CHIPUNIT, ///< Core
PU_EQ_CHIPUNIT, ///< Quad
PU_EX_CHIPUNIT, ///< EX
PU_XBUS_CHIPUNIT, ///< XBUS
PU_OBUS_CHIPUNIT, ///< OBUS
PU_NV_CHIPUNIT, ///< NV Link Brick
PU_PEC_CHIPUNIT, ///< PCIe (PEC)
PU_PHB_CHIPUNIT, ///< PCIe (PHB)
PU_MI_CHIPUNIT, ///< MI (Cumulus only)
PU_DMI_CHIPUNIT, ///< DMI (Cumulus only)
PU_MCS_CHIPUNIT, ///< MCS (Nimbus only)
PU_MCA_CHIPUNIT, ///< MCA (Nimbus only)
PU_MCBIST_CHIPUNIT, ///< MCBIST (Nimbus only)
PU_OCC_CHIPUNIT, ///< OCC
PU_PERV_CHIPUNIT, ///< Pervasive
PU_PPE_CHIPUNIT, ///< PPE
PU_SBE_CHIPUNIT, ///< SBE
PU_CAPP_CHIPUNIT, ///< CAPP
NONE, ///< None/Invalid
PU_NVBUS_CHIPUNIT = PU_NV_CHIPUNIT ///< DO NOT USE! TEMPORARY FOR CI ONLY
} p9ChipUnits_t;
/// P9 chip unit pairing struct
struct p9_chipUnitPairing_t
{
/// @brief Default constructor
p9_chipUnitPairing_t()
: chipUnitType(NONE), chipUnitNum(0) {}
/// @brief Construct from type/instance number
p9_chipUnitPairing_t (p9ChipUnits_t type, uint32_t num)
: chipUnitType(type), chipUnitNum(num) {}
p9ChipUnits_t chipUnitType; ///< chip unit type
uint32_t chipUnitNum; ///< chip unit instance number
};
} // extern "C"
#endif /* P9_CU_H */
<commit_msg>Adding SCOM addr translation for PPE chip units<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/common/scominfo/p9_cu.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_cu.H
/// @brief P9 chip unit definitions
///
/// HWP HWP Owner: [email protected]
/// HWP FW Owner: [email protected]
/// HWP Team: Infrastructure
/// HWP Level: 2
/// HWP Consumed by: FSP/HB
///
#ifndef P9_CU_H
#define P9_CU_H
// includes
#include <stdint.h>
extern "C"
{
/// P9 chip unit type enumeration
typedef enum
{
P9C_CHIP, ///< Cumulus chip (included for future expansion)
P9N_CHIP, ///< Nimbus chip (included for future expansion)
PU_C_CHIPUNIT, ///< Core
PU_EQ_CHIPUNIT, ///< Quad
PU_EX_CHIPUNIT, ///< EX
PU_XBUS_CHIPUNIT, ///< XBUS
PU_OBUS_CHIPUNIT, ///< OBUS
PU_NV_CHIPUNIT, ///< NV Link Brick
PU_PEC_CHIPUNIT, ///< PCIe (PEC)
PU_PHB_CHIPUNIT, ///< PCIe (PHB)
PU_MI_CHIPUNIT, ///< MI (Cumulus only)
PU_DMI_CHIPUNIT, ///< DMI (Cumulus only)
PU_MCS_CHIPUNIT, ///< MCS (Nimbus only)
PU_MCA_CHIPUNIT, ///< MCA (Nimbus only)
PU_MCBIST_CHIPUNIT, ///< MCBIST (Nimbus only)
PU_PERV_CHIPUNIT, ///< Pervasive
PU_PPE_CHIPUNIT, ///< PPE
PU_SBE_CHIPUNIT, ///< SBE
PU_CAPP_CHIPUNIT, ///< CAPP
NONE, ///< None/Invalid
} p9ChipUnits_t;
/// P9 chip unit pairing struct
struct p9_chipUnitPairing_t
{
/// @brief Default constructor
p9_chipUnitPairing_t()
: chipUnitType(NONE), chipUnitNum(0) {}
/// @brief Construct from type/instance number
p9_chipUnitPairing_t (p9ChipUnits_t type, uint32_t num)
: chipUnitType(type), chipUnitNum(num) {}
p9ChipUnits_t chipUnitType; ///< chip unit type
uint32_t chipUnitNum; ///< chip unit instance number
};
/// P9 PPE Chip Unit Instance Number enumeration
/// PPE name Nimbus Cumulus
/// SBE 0 0
/// GPE0..3 10..13 10..13
/// CME0 20..25 20..25
/// CME1 30..35 30..35
/// IO PPE (xbus) 40 40
/// IO PPE (obus) 41,42 41,42
/// IO PPE (dmi) NA 43,44
/// Powerbus PPEs 50 50..52
typedef enum
{
PPE_SBE_CHIPUNIT_NUM = 0,
PPE_GPE0_CHIPUNIT_NUM = 10,
PPE_GPE3_CHIPUNIT_NUM = 13,
PPE_EQ0_CME0_CHIPUNIT_NUM = 20, // Quad0-CME0
PPE_EQ5_CME0_CHIPUNIT_NUM = 25, // Quad5-CME0
PPE_EQ0_CME1_CHIPUNIT_NUM = 30, // Quad0-CME1
PPE_EQ5_CME1_CHIPUNIT_NUM = 35, // Quad5-CME1
PPE_IO_XBUS_CHIPUNIT_NUM = 40,
PPE_IO_OB0_CHIPUNIT_NUM = 41,
PPE_IO_OB1_CHIPUNIT_NUM = 42,
PPE_IO1_DMI_CHIPUNIT_NUM = 44,
PPE_PB0_CHIPUNIT_NUM = 50,
PPE_PB2_CHIPUNIT_NUM = 52,
PPE_LAST_CHIPUNIT_NUM = PPE_PB2_CHIPUNIT_NUM,
} p9_ppe_chip_unit_instance_num_t;
} // extern "C"
#endif /* P9_CU_H */
<|endoftext|> |
<commit_before><commit_msg>Support profile_file_prefix in python binding (#5864)<commit_after><|endoftext|> |
<commit_before>/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkImageDecoder.h"
#include "SkImage_Base.h"
#include "SkBitmap.h"
#include "SkCanvas.h"
#include "SkData.h"
class SkImage_Codec : public SkImage_Base {
public:
static SkImage* NewEmpty();
SkImage_Codec(SkData* encodedData, int width, int height);
virtual ~SkImage_Codec();
virtual void onDraw(SkCanvas*, SkScalar, SkScalar, const SkPaint*) const SK_OVERRIDE;
virtual void onDrawRectToRect(SkCanvas*, const SkRect*, const SkRect&,
const SkPaint*) const SK_OVERRIDE;
virtual bool isOpaque() const SK_OVERRIDE;
private:
SkData* fEncodedData;
SkBitmap fBitmap;
typedef SkImage_Base INHERITED;
};
///////////////////////////////////////////////////////////////////////////////
SkImage_Codec::SkImage_Codec(SkData* data, int width, int height) : INHERITED(width, height) {
fEncodedData = data;
fEncodedData->ref();
}
SkImage_Codec::~SkImage_Codec() {
fEncodedData->unref();
}
void SkImage_Codec::onDraw(SkCanvas* canvas, SkScalar x, SkScalar y, const SkPaint* paint) const {
if (!fBitmap.pixelRef()) {
// todo: this needs to be thread-safe
SkBitmap* bitmap = const_cast<SkBitmap*>(&fBitmap);
if (!SkImageDecoder::DecodeMemory(fEncodedData->bytes(), fEncodedData->size(), bitmap)) {
return;
}
}
canvas->drawBitmap(fBitmap, x, y, paint);
}
void SkImage_Codec::onDrawRectToRect(SkCanvas* canvas, const SkRect* src, const SkRect& dst,
const SkPaint* paint) const {
if (!fBitmap.pixelRef()) {
// todo: this needs to be thread-safe
SkBitmap* bitmap = const_cast<SkBitmap*>(&fBitmap);
if (!SkImageDecoder::DecodeMemory(fEncodedData->bytes(), fEncodedData->size(), bitmap)) {
return;
}
}
canvas->drawBitmapRectToRect(fBitmap, src, dst, paint);
}
///////////////////////////////////////////////////////////////////////////////
SkImage* SkImage::NewEncodedData(SkData* data) {
if (NULL == data) {
return NULL;
}
SkBitmap bitmap;
if (!SkImageDecoder::DecodeMemory(data->bytes(), data->size(), &bitmap, kUnknown_SkColorType,
SkImageDecoder::kDecodeBounds_Mode)) {
return NULL;
}
return SkNEW_ARGS(SkImage_Codec, (data, bitmap.width(), bitmap.height()));
}
bool SkImage_Codec::isOpaque() const {
return fBitmap.isOpaque();
}
<commit_msg>Small refactoring in SkImage_Codec<commit_after>/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkImageDecoder.h"
#include "SkImage_Base.h"
#include "SkBitmap.h"
#include "SkCanvas.h"
#include "SkData.h"
class SkImage_Codec : public SkImage_Base {
public:
static SkImage* NewEmpty();
SkImage_Codec(SkData* encodedData, int width, int height);
virtual ~SkImage_Codec();
virtual void onDraw(SkCanvas*, SkScalar, SkScalar, const SkPaint*) const SK_OVERRIDE;
virtual void onDrawRectToRect(SkCanvas*, const SkRect*, const SkRect&,
const SkPaint*) const SK_OVERRIDE;
virtual bool isOpaque() const SK_OVERRIDE;
private:
bool ensureBitmapDecoded() const;
SkData* fEncodedData;
SkBitmap fBitmap;
typedef SkImage_Base INHERITED;
};
///////////////////////////////////////////////////////////////////////////////
SkImage_Codec::SkImage_Codec(SkData* data, int width, int height) : INHERITED(width, height) {
fEncodedData = data;
fEncodedData->ref();
}
SkImage_Codec::~SkImage_Codec() {
fEncodedData->unref();
}
bool SkImage_Codec::ensureBitmapDecoded() const {
if (!fBitmap.pixelRef()) {
// todo: this needs to be thread-safe
SkBitmap* bitmap = const_cast<SkBitmap*>(&fBitmap);
if (!SkImageDecoder::DecodeMemory(fEncodedData->bytes(), fEncodedData->size(), bitmap)) {
return false;
}
}
return true;
}
void SkImage_Codec::onDraw(SkCanvas* canvas, SkScalar x, SkScalar y, const SkPaint* paint) const {
if(!this->ensureBitmapDecoded()) {
return;
}
canvas->drawBitmap(fBitmap, x, y, paint);
}
void SkImage_Codec::onDrawRectToRect(SkCanvas* canvas, const SkRect* src, const SkRect& dst,
const SkPaint* paint) const {
if(!this->ensureBitmapDecoded()) {
return;
}
canvas->drawBitmapRectToRect(fBitmap, src, dst, paint);
}
///////////////////////////////////////////////////////////////////////////////
SkImage* SkImage::NewEncodedData(SkData* data) {
if (NULL == data) {
return NULL;
}
SkBitmap bitmap;
if (!SkImageDecoder::DecodeMemory(data->bytes(), data->size(), &bitmap, kUnknown_SkColorType,
SkImageDecoder::kDecodeBounds_Mode)) {
return NULL;
}
return SkNEW_ARGS(SkImage_Codec, (data, bitmap.width(), bitmap.height()));
}
bool SkImage_Codec::isOpaque() const {
return fBitmap.isOpaque();
}
<|endoftext|> |
<commit_before>/*
* Copyright 2007-2020 CM4all GmbH
* All rights reserved.
*
* author: Max Kellermann <[email protected]>
*
* 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
* FOUNDATION 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 "FileIstream.hxx"
#include "istream.hxx"
#include "New.hxx"
#include "Result.hxx"
#include "io/Buffered.hxx"
#include "io/Open.hxx"
#include "io/UniqueFileDescriptor.hxx"
#include "pool/pool.hxx"
#include "fb_pool.hxx"
#include "SliceFifoBuffer.hxx"
#include "system/Error.hxx"
#include "event/TimerEvent.hxx"
#include "util/RuntimeError.hxx"
#include <assert.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <limits.h>
/**
* If EAGAIN occurs (on NFS), we try again after 100ms. We can't
* check SocketEvent::READ, because the kernel always indicates VFS files as
* "readable without blocking".
*/
static constexpr Event::Duration file_retry_timeout = std::chrono::milliseconds(100);
class FileIstream final : public Istream {
FileDescriptor fd;
FdType fd_type;
/**
* A timer to retry reading after EAGAIN.
*/
TimerEvent retry_event;
off_t rest;
SliceFifoBuffer buffer;
const char *path;
public:
FileIstream(struct pool &p, EventLoop &event_loop,
UniqueFileDescriptor &&_fd, FdType _fd_type, off_t _length,
const char *_path) noexcept
:Istream(p),
fd(_fd.Steal()), fd_type(_fd_type),
retry_event(event_loop, BIND_THIS_METHOD(EventCallback)),
rest(_length),
path(_path) {}
~FileIstream() noexcept {
retry_event.Cancel();
}
private:
void CloseHandle() noexcept {
if (!fd.IsDefined())
return;
retry_event.Cancel();
fd.Close();
buffer.FreeIfDefined();
}
void Abort(std::exception_ptr ep) noexcept {
CloseHandle();
DestroyError(ep);
}
/**
* @return the number of bytes still in the buffer
*/
size_t SubmitBuffer() noexcept {
return ConsumeFromBuffer(buffer);
}
void EofDetected() noexcept {
assert(fd.IsDefined());
CloseHandle();
DestroyEof();
}
gcc_pure
size_t GetMaxRead() const noexcept {
if (rest != (off_t)-1 && rest < (off_t)INT_MAX)
return (size_t)rest;
else
return INT_MAX;
}
void TryData() noexcept;
void TryDirect() noexcept;
void TryRead() noexcept {
if (CheckDirect(fd_type))
TryDirect();
else
TryData();
}
void EventCallback() noexcept {
TryRead();
}
/* virtual methods from class Istream */
off_t _GetAvailable(bool partial) noexcept override;
off_t _Skip(gcc_unused off_t length) noexcept override;
void _Read() noexcept override {
retry_event.Cancel();
TryRead();
}
int _AsFd() noexcept override;
void _Close() noexcept override {
CloseHandle();
Destroy();
}
};
inline void
FileIstream::TryData() noexcept
{
size_t buffer_rest = 0;
if (buffer.IsNull()) {
if (rest != 0)
buffer.Allocate(fb_pool_get());
} else {
const size_t available = buffer.GetAvailable();
if (available > 0) {
buffer_rest = SubmitBuffer();
if (buffer_rest == available)
/* not a single byte was consumed: we may have been
closed, and we must bail out now */
return;
}
}
if (rest == 0) {
if (buffer_rest == 0)
EofDetected();
return;
}
ssize_t nbytes = read_to_buffer(fd.Get(), buffer, GetMaxRead());
if (nbytes == 0) {
if (rest == (off_t)-1) {
rest = 0;
if (buffer_rest == 0)
EofDetected();
} else {
Abort(std::make_exception_ptr(FormatRuntimeError("premature end of file in '%s'",
path)));
}
return;
} else if (nbytes == -1) {
Abort(std::make_exception_ptr(FormatErrno("Failed to read from '%s'",
path)));
return;
} else if (nbytes > 0 && rest != (off_t)-1) {
rest -= (off_t)nbytes;
assert(rest >= 0);
}
assert(!buffer.empty());
buffer_rest = SubmitBuffer();
if (buffer_rest == 0 && rest == 0)
EofDetected();
}
inline void
FileIstream::TryDirect() noexcept
{
/* first consume the rest of the buffer */
if (SubmitBuffer() > 0)
return;
if (rest == 0) {
EofDetected();
return;
}
ssize_t nbytes = InvokeDirect(fd_type, fd.Get(), GetMaxRead());
if (nbytes == ISTREAM_RESULT_CLOSED)
/* this stream was closed during the direct() callback */
return;
if (nbytes > 0 || nbytes == ISTREAM_RESULT_BLOCKING) {
/* -2 means the callback wasn't able to consume any data right
now */
if (nbytes > 0 && rest != (off_t)-1) {
rest -= (off_t)nbytes;
assert(rest >= 0);
if (rest == 0)
EofDetected();
}
} else if (nbytes == ISTREAM_RESULT_EOF) {
if (rest == (off_t)-1) {
EofDetected();
} else {
Abort(std::make_exception_ptr(FormatRuntimeError("premature end of file in '%s'",
path)));
}
} else if (errno == EAGAIN) {
/* this should only happen for splice(SPLICE_F_NONBLOCK) from
NFS files - unfortunately we cannot use SocketEvent::READ
here, so we just install a timer which retries after
100ms */
retry_event.Schedule(file_retry_timeout);
} else {
/* XXX */
Abort(std::make_exception_ptr(FormatErrno("Failed to read from '%s'",
path)));
}
}
/*
* istream implementation
*
*/
off_t
FileIstream::_GetAvailable(bool partial) noexcept
{
off_t available;
if (rest != (off_t)-1)
available = rest;
else if (!partial)
return (off_t)-1;
else
available = 0;
available += buffer.GetAvailable();
return available;
}
off_t
FileIstream::_Skip(off_t length) noexcept
{
retry_event.Cancel();
if (rest == (off_t)-1)
return (off_t)-1;
if (length == 0)
return 0;
const size_t buffer_available = buffer.GetAvailable();
if (length < off_t(buffer_available)) {
buffer.Consume(length);
Consumed(length);
return length;
}
length -= buffer_available;
buffer.Clear();
if (length >= rest) {
/* skip beyond EOF */
length = rest;
rest = 0;
} else {
/* seek the file descriptor */
if (fd.Skip(length) < 0)
return -1;
rest -= length;
}
off_t result = buffer_available + length;
Consumed(result);
return result;
}
int
FileIstream::_AsFd() noexcept
{
int result_fd = fd.Steal();
Destroy();
return result_fd;
}
/*
* constructor and public methods
*
*/
UnusedIstreamPtr
istream_file_fd_new(EventLoop &event_loop, struct pool &pool,
const char *path,
UniqueFileDescriptor fd, FdType fd_type, off_t length) noexcept
{
assert(fd.IsDefined());
assert(length >= -1);
return NewIstreamPtr<FileIstream>(pool, event_loop,
std::move(fd), fd_type,
length, path);
}
UnusedIstreamPtr
istream_file_new(EventLoop &event_loop, struct pool &pool,
const char *path)
{
auto fd = OpenReadOnly(path);
struct stat st;
if (fstat(fd.Get(), &st) < 0)
throw FormatErrno("Failed to stat %s", path);
off_t size = S_ISREG(st.st_mode) ? st.st_size : -1;
FdType fd_type = FdType::FD_FILE;
if (S_ISCHR(st.st_mode))
fd_type = FdType::FD_CHARDEV;
else if (S_ISFIFO(st.st_mode))
fd_type = FdType::FD_PIPE;
else if (S_ISSOCK(st.st_mode))
fd_type = FdType::FD_SOCKET;
return istream_file_fd_new(event_loop, pool, path,
std::move(fd), fd_type, size);
}
<commit_msg>istream/file: fold CloseHandle() into destructor<commit_after>/*
* Copyright 2007-2020 CM4all GmbH
* All rights reserved.
*
* author: Max Kellermann <[email protected]>
*
* 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
* FOUNDATION 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 "FileIstream.hxx"
#include "istream.hxx"
#include "New.hxx"
#include "Result.hxx"
#include "io/Buffered.hxx"
#include "io/Open.hxx"
#include "io/UniqueFileDescriptor.hxx"
#include "pool/pool.hxx"
#include "fb_pool.hxx"
#include "SliceFifoBuffer.hxx"
#include "system/Error.hxx"
#include "event/TimerEvent.hxx"
#include "util/RuntimeError.hxx"
#include <assert.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <limits.h>
/**
* If EAGAIN occurs (on NFS), we try again after 100ms. We can't
* check SocketEvent::READ, because the kernel always indicates VFS files as
* "readable without blocking".
*/
static constexpr Event::Duration file_retry_timeout = std::chrono::milliseconds(100);
class FileIstream final : public Istream {
FileDescriptor fd;
FdType fd_type;
/**
* A timer to retry reading after EAGAIN.
*/
TimerEvent retry_event;
off_t rest;
SliceFifoBuffer buffer;
const char *path;
public:
FileIstream(struct pool &p, EventLoop &event_loop,
UniqueFileDescriptor &&_fd, FdType _fd_type, off_t _length,
const char *_path) noexcept
:Istream(p),
fd(_fd.Steal()), fd_type(_fd_type),
retry_event(event_loop, BIND_THIS_METHOD(EventCallback)),
rest(_length),
path(_path) {}
~FileIstream() noexcept {
retry_event.Cancel();
if (fd.IsDefined())
fd.Close();
buffer.FreeIfDefined();
}
private:
void Abort(std::exception_ptr ep) noexcept {
DestroyError(ep);
}
/**
* @return the number of bytes still in the buffer
*/
size_t SubmitBuffer() noexcept {
return ConsumeFromBuffer(buffer);
}
void EofDetected() noexcept {
assert(fd.IsDefined());
DestroyEof();
}
gcc_pure
size_t GetMaxRead() const noexcept {
if (rest != (off_t)-1 && rest < (off_t)INT_MAX)
return (size_t)rest;
else
return INT_MAX;
}
void TryData() noexcept;
void TryDirect() noexcept;
void TryRead() noexcept {
if (CheckDirect(fd_type))
TryDirect();
else
TryData();
}
void EventCallback() noexcept {
TryRead();
}
/* virtual methods from class Istream */
off_t _GetAvailable(bool partial) noexcept override;
off_t _Skip(gcc_unused off_t length) noexcept override;
void _Read() noexcept override {
retry_event.Cancel();
TryRead();
}
int _AsFd() noexcept override;
void _Close() noexcept override {
Destroy();
}
};
inline void
FileIstream::TryData() noexcept
{
size_t buffer_rest = 0;
if (buffer.IsNull()) {
if (rest != 0)
buffer.Allocate(fb_pool_get());
} else {
const size_t available = buffer.GetAvailable();
if (available > 0) {
buffer_rest = SubmitBuffer();
if (buffer_rest == available)
/* not a single byte was consumed: we may have been
closed, and we must bail out now */
return;
}
}
if (rest == 0) {
if (buffer_rest == 0)
EofDetected();
return;
}
ssize_t nbytes = read_to_buffer(fd.Get(), buffer, GetMaxRead());
if (nbytes == 0) {
if (rest == (off_t)-1) {
rest = 0;
if (buffer_rest == 0)
EofDetected();
} else {
Abort(std::make_exception_ptr(FormatRuntimeError("premature end of file in '%s'",
path)));
}
return;
} else if (nbytes == -1) {
Abort(std::make_exception_ptr(FormatErrno("Failed to read from '%s'",
path)));
return;
} else if (nbytes > 0 && rest != (off_t)-1) {
rest -= (off_t)nbytes;
assert(rest >= 0);
}
assert(!buffer.empty());
buffer_rest = SubmitBuffer();
if (buffer_rest == 0 && rest == 0)
EofDetected();
}
inline void
FileIstream::TryDirect() noexcept
{
/* first consume the rest of the buffer */
if (SubmitBuffer() > 0)
return;
if (rest == 0) {
EofDetected();
return;
}
ssize_t nbytes = InvokeDirect(fd_type, fd.Get(), GetMaxRead());
if (nbytes == ISTREAM_RESULT_CLOSED)
/* this stream was closed during the direct() callback */
return;
if (nbytes > 0 || nbytes == ISTREAM_RESULT_BLOCKING) {
/* -2 means the callback wasn't able to consume any data right
now */
if (nbytes > 0 && rest != (off_t)-1) {
rest -= (off_t)nbytes;
assert(rest >= 0);
if (rest == 0)
EofDetected();
}
} else if (nbytes == ISTREAM_RESULT_EOF) {
if (rest == (off_t)-1) {
EofDetected();
} else {
Abort(std::make_exception_ptr(FormatRuntimeError("premature end of file in '%s'",
path)));
}
} else if (errno == EAGAIN) {
/* this should only happen for splice(SPLICE_F_NONBLOCK) from
NFS files - unfortunately we cannot use SocketEvent::READ
here, so we just install a timer which retries after
100ms */
retry_event.Schedule(file_retry_timeout);
} else {
/* XXX */
Abort(std::make_exception_ptr(FormatErrno("Failed to read from '%s'",
path)));
}
}
/*
* istream implementation
*
*/
off_t
FileIstream::_GetAvailable(bool partial) noexcept
{
off_t available;
if (rest != (off_t)-1)
available = rest;
else if (!partial)
return (off_t)-1;
else
available = 0;
available += buffer.GetAvailable();
return available;
}
off_t
FileIstream::_Skip(off_t length) noexcept
{
retry_event.Cancel();
if (rest == (off_t)-1)
return (off_t)-1;
if (length == 0)
return 0;
const size_t buffer_available = buffer.GetAvailable();
if (length < off_t(buffer_available)) {
buffer.Consume(length);
Consumed(length);
return length;
}
length -= buffer_available;
buffer.Clear();
if (length >= rest) {
/* skip beyond EOF */
length = rest;
rest = 0;
} else {
/* seek the file descriptor */
if (fd.Skip(length) < 0)
return -1;
rest -= length;
}
off_t result = buffer_available + length;
Consumed(result);
return result;
}
int
FileIstream::_AsFd() noexcept
{
int result_fd = fd.Steal();
Destroy();
return result_fd;
}
/*
* constructor and public methods
*
*/
UnusedIstreamPtr
istream_file_fd_new(EventLoop &event_loop, struct pool &pool,
const char *path,
UniqueFileDescriptor fd, FdType fd_type, off_t length) noexcept
{
assert(fd.IsDefined());
assert(length >= -1);
return NewIstreamPtr<FileIstream>(pool, event_loop,
std::move(fd), fd_type,
length, path);
}
UnusedIstreamPtr
istream_file_new(EventLoop &event_loop, struct pool &pool,
const char *path)
{
auto fd = OpenReadOnly(path);
struct stat st;
if (fstat(fd.Get(), &st) < 0)
throw FormatErrno("Failed to stat %s", path);
off_t size = S_ISREG(st.st_mode) ? st.st_size : -1;
FdType fd_type = FdType::FD_FILE;
if (S_ISCHR(st.st_mode))
fd_type = FdType::FD_CHARDEV;
else if (S_ISFIFO(st.st_mode))
fd_type = FdType::FD_PIPE;
else if (S_ISSOCK(st.st_mode))
fd_type = FdType::FD_SOCKET;
return istream_file_fd_new(event_loop, pool, path,
std::move(fd), fd_type, size);
}
<|endoftext|> |
<commit_before>/*
* This file is part of crash-reporter
*
* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
*
* Contact: Ville Ilvonen <[email protected]>
* Author: Riku Halonen <[email protected]>
*
* Copyright (C) 2013 Jolla Ltd.
* Contact: Jakub Adam <[email protected]>
*
* This program 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 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
// System includes.
#include <QAuthenticator>
#include <QJsonDocument>
#include <QJsonObject>
#include <QNetworkReply>
#include <QDebug>
#include <QFile>
#include <QFileInfo>
#include <QDir>
#include <QSslConfiguration>
#include <QNetworkProxy>
#include <QTime>
// User includes.
#include "creportercoreregistry.h"
#include "creporterhttpclient.h"
#include "creporterhttpclient_p.h"
#include "creporterapplicationsettings.h"
#include "creporterutils.h"
const char *clientstate_string[] = {"None", "Init", "Connecting", "Sending", "Aborting"};
// ******** Class CReporterHttpClientPrivate ********
// ======== MEMBER FUNCTIONS ========
// ----------------------------------------------------------------------------
// CReporterHttpClientPrivate::CReporterHttpClientPrivate
// ----------------------------------------------------------------------------
CReporterHttpClientPrivate::CReporterHttpClientPrivate() :
m_manager( 0 ),
m_reply( 0 )
{
m_clientState = CReporterHttpClient::None;
}
// ----------------------------------------------------------------------------
// CReporterHttpClientPrivate::~CReporterHttpClientPrivate
// ----------------------------------------------------------------------------
CReporterHttpClientPrivate::~CReporterHttpClientPrivate()
{
CReporterApplicationSettings::freeSingleton();
if (m_reply != 0) {
m_reply->abort();
m_reply = 0;
}
if (m_manager != 0) {
delete m_manager;
m_manager = 0;
}
}
// ----------------------------------------------------------------------------
// CReporterHttpClientPrivate::init
// ----------------------------------------------------------------------------
void CReporterHttpClientPrivate::init(bool deleteAfterSending)
{
qDebug() << __PRETTY_FUNCTION__ << "Initiating HTTP session.";
m_deleteFileFlag = deleteAfterSending;
m_userAborted = false;
m_httpError = false;
if (CReporterApplicationSettings::instance()->useProxy()) {
qDebug() << __PRETTY_FUNCTION__ << "Network proxy defined.";
QNetworkProxy proxy;
proxy.setType(QNetworkProxy::HttpProxy);
proxy.setHostName(CReporterApplicationSettings::instance()->proxyUrl());
proxy.setPort(CReporterApplicationSettings::instance()->proxyPort());
QNetworkProxy::setApplicationProxy(proxy);
}
if (m_manager == 0) {
m_manager = new QNetworkAccessManager(q_ptr);
Q_CHECK_PTR(m_manager);
connect(m_manager, SIGNAL(authenticationRequired(QNetworkReply*, QAuthenticator*)),
this, SLOT(handleAuthenticationRequired(QNetworkReply*, QAuthenticator*)));
}
stateChange(CReporterHttpClient::Init);
}
// ----------------------------------------------------------------------------
// CReporterHttpClientPrivate::createRequest
// ----------------------------------------------------------------------------
bool CReporterHttpClientPrivate::createRequest(const QString &file)
{
Q_ASSERT(m_manager != NULL);
qDebug() << __PRETTY_FUNCTION__ << "Create new request.";
if (m_clientState != CReporterHttpClient::Init) {
return false;
}
QNetworkRequest request;
QByteArray dataToSend;
// Set server URL and port.
QUrl url(CReporterApplicationSettings::instance()->serverUrl());
url.setPort(CReporterApplicationSettings::instance()->serverPort());
if (CReporterApplicationSettings::instance()->useSsl()) {
qDebug() << __PRETTY_FUNCTION__ << "SSL is enabled.";
QSslConfiguration ssl(QSslConfiguration::defaultConfiguration());
ssl.setPeerVerifyMode(QSslSocket::VerifyNone);
request.setSslConfiguration(ssl);
}
// Set file to be the current.
m_currentFile.setFile(file);
qDebug() << __PRETTY_FUNCTION__ << "File to upload:" << m_currentFile.absoluteFilePath();
qDebug() << __PRETTY_FUNCTION__ << "File size:" << m_currentFile.size() / 1024 << "kB's";
// For PUT, we need to append file name to the path.
QString serverPath = CReporterApplicationSettings::instance()->serverPath() +
"/" + m_currentFile.fileName();
url.setPath(serverPath);
url.setQuery("uuid=" + CReporterUtils::deviceUid() +
"&model=" + CReporterUtils::deviceModel());
request.setUrl(url);
qDebug() << __PRETTY_FUNCTION__ << "Upload URL:" << url.toString();
if (!createPutRequest(request, dataToSend)) {
qDebug() << __PRETTY_FUNCTION__ << "Failed to create network request.";
return false;
}
// Send request and connect signal/ slots.
m_reply = m_manager->put(request, dataToSend);
if (m_reply == 0) {
return false;
}
// Connect QNetworkReply signals.
connect(m_reply, SIGNAL(sslErrors(QList<QSslError>)),
this, SLOT(handleSslErrors(QList<QSslError>)));
connect(m_reply, SIGNAL(error(QNetworkReply::NetworkError)),
this, SLOT(handleError(QNetworkReply::NetworkError)));
connect(m_reply, SIGNAL(finished()), this, SLOT(handleFinished()));
stateChange(CReporterHttpClient::Connecting);
return true;
}
// ----------------------------------------------------------------------------
// CReporterHttpClientPrivate::cancel
// ----------------------------------------------------------------------------
void CReporterHttpClientPrivate::cancel()
{
qDebug() << __PRETTY_FUNCTION__ << "User aborted transaction.";
m_userAborted = true;
stateChange( CReporterHttpClient::Aborting );
if (m_reply != 0) {
qDebug() << __PRETTY_FUNCTION__ << "Canceling transaction.";
// Abort ongoing transactions.
m_reply->abort();
}
// Clean up.
handleFinished();
}
// ======== LOCAL FUNCTIONS ========
// ----------------------------------------------------------------------------
// CReporterHttpClientPrivate::handleAuthenticationRequired
// ----------------------------------------------------------------------------
void CReporterHttpClientPrivate::handleAuthenticationRequired(QNetworkReply *reply,
QAuthenticator *authenticator)
{
qDebug() << __PRETTY_FUNCTION__ << "Fill in the credentials.";
connect(reply, SIGNAL(uploadProgress(qint64,qint64)),
this, SLOT(handleUploadProgress(qint64,qint64)));
// Fill in the credentials.
authenticator->setUser(CReporterApplicationSettings::instance()->username());
authenticator->setPassword(CReporterApplicationSettings::instance()->password());
}
// ----------------------------------------------------------------------------
// CReporterHttpClientPrivate::handleSslErrors
// ----------------------------------------------------------------------------
void CReporterHttpClientPrivate::handleSslErrors(const QList<QSslError> &errors )
{
QString errorString;
foreach (const QSslError &error, errors) {
if ( !errorString.isEmpty() ) {
errorString += ", ";
}
errorString += error.errorString();
}
qDebug() << "One or more SSL errors occured:" << errorString;
// Ignore and continue connection.
m_reply->ignoreSslErrors();
}
// ----------------------------------------------------------------------------
// CReporterHttpClientPrivate::handleError
// ----------------------------------------------------------------------------
void CReporterHttpClientPrivate::handleError(QNetworkReply::NetworkError error)
{
if (m_reply && m_reply->error() != QNetworkReply::NoError) {
// Finished is emitted by QNetworkReply after this, inidicating that
// the connection is over.
qCritical() << __PRETTY_FUNCTION__ << "Upload failed.";
m_httpError = true;
QString errorString =m_reply->errorString();
qDebug() << __PRETTY_FUNCTION__ << "Error code:" << error << "," << errorString;
emit uploadError(m_currentFile.fileName(), errorString);
}
}
void CReporterHttpClientPrivate::parseReply()
{
if (!m_reply) {
qDebug() << "Server reply is NULL";
return;
}
if (!m_reply->open(QIODevice::ReadOnly)) {
qDebug() << "Couldn't open server reply for reading.";
return;
}
QJsonDocument reply = QJsonDocument::fromJson(m_reply->readAll());
if (reply.isNull() || !reply.isObject()) {
qDebug() << "Error parsing JSON server reply.";
return;
}
QJsonObject json = reply.object();
int submissionId = static_cast<int>(json.value("submission_id").toDouble(0));
if (submissionId == 0) {
qDebug() << "Failed to parse submission id from JSON.";
return;
}
QUrl submissionUrl(CReporterApplicationSettings::instance()->serverUrl());
submissionUrl.setPort(CReporterApplicationSettings::instance()->serverPort());
submissionUrl.setPath("/");
submissionUrl.setFragment(QString("submissions/%1").arg(submissionId));
QString corePath(CReporterCoreRegistry::instance()->getCoreLocationPaths().first());
QFile uploadlog(corePath + "/uploadlog");
if (!uploadlog.open(QIODevice::WriteOnly | QIODevice::Append)) {
qDebug() << "Couldn't open uploadlog for writing.";
return;
}
QTextStream stream(&uploadlog);
stream << m_currentFile.fileName() << ' ' << submissionUrl.toString() << '\n';
uploadlog.close();
}
// ----------------------------------------------------------------------------
// CReporterHttpClientPrivate::handleFinished
// ----------------------------------------------------------------------------
void CReporterHttpClientPrivate::handleFinished()
{
qDebug() << __PRETTY_FUNCTION__ << "Uploading file:" << m_currentFile.fileName() << "finished.";
if (!m_httpError && !m_userAborted) {
// Upload was successful.
parseReply();
if (m_deleteFileFlag) {
// Remove file if delete was requested.
CReporterUtils::removeFile(m_currentFile.absoluteFilePath());
}
}
// QNetworkreply objects are owned by QNetworkAccessManager and deleted along with it.
m_reply = 0;
stateChange(CReporterHttpClient::Init);
emit finished();
}
// ----------------------------------------------------------------------------
// CReporterHttpClientPrivate::handleUploadProgress
// ----------------------------------------------------------------------------
void CReporterHttpClientPrivate::handleUploadProgress(qint64 bytesSent, qint64 bytesTotal)
{
qDebug() << __PRETTY_FUNCTION__ << "Sent:" << bytesSent << "Total:" << bytesTotal;
if (m_userAborted || m_httpError) {
// Do not update, if aborted.
return;
}
if (m_clientState != CReporterHttpClient::Sending) {
stateChange(CReporterHttpClient::Sending);
}
int done = (int)((bytesSent * 100) / bytesTotal);
qDebug() << __PRETTY_FUNCTION__ << "Done:" << done << "%";
emit q_ptr->updateProgress(done);
}
// ----------------------------------------------------------------------------
// CReporterHttpClientPrivate::stateChange
// ----------------------------------------------------------------------------
void CReporterHttpClientPrivate::stateChange(CReporterHttpClient::State nextState)
{
qDebug() << __PRETTY_FUNCTION__ << "Current state:" << q_ptr->stateToString( m_clientState );
qDebug() << __PRETTY_FUNCTION__ << "New state:" << q_ptr->stateToString( nextState );
m_clientState = nextState;
emit stateChanged( m_clientState );
}
// ----------------------------------------------------------------------------
// CReporterHttpClientPrivate::createPutRequest
// ----------------------------------------------------------------------------
bool CReporterHttpClientPrivate::createPutRequest(QNetworkRequest &request,
QByteArray &dataToSend)
{
QFile file(m_currentFile.absoluteFilePath());
// Abort, if file doesn't exist or IO error.
if (!file.exists() || !file.open(QIODevice::ReadOnly)) {
return false;
}
// Append file.
dataToSend += file.readAll();
file.close();
// Construct HTTP Headers.
request.setRawHeader("User-Agent", "crash-reporter");
request.setRawHeader("Accept", "*/*");
request.setHeader(QNetworkRequest::ContentLengthHeader, dataToSend.size());
return true;
}
// ******** Class CReporterHttpClient ********
// ======== MEMBER FUNCTIONS ========
// ----------------------------------------------------------------------------
// CReporterHttpClient::CReporterHttpClient
// ----------------------------------------------------------------------------
CReporterHttpClient::CReporterHttpClient(QObject *parent) :
QObject(parent) ,
d_ptr(new CReporterHttpClientPrivate())
{
Q_D(CReporterHttpClient);
d->q_ptr = this;
connect( d, SIGNAL(stateChanged(CReporterHttpClient::State)),
this, SIGNAL(clientStateChanged(CReporterHttpClient::State)) );
connect( d, SIGNAL(uploadError(QString,QString)), this, SIGNAL(uploadError(QString,QString)) );
connect( d, SIGNAL(finished()), this, SIGNAL(finished()) );
}
// ----------------------------------------------------------------------------
// CReporterHttpClient::~CReporterHttpClient
// ----------------------------------------------------------------------------
CReporterHttpClient::~CReporterHttpClient()
{
qDebug() << __PRETTY_FUNCTION__ << "Client destroyed.";
delete d_ptr;
d_ptr = NULL;
}
// ----------------------------------------------------------------------------
// CReporterHttpClient::initSession
// ----------------------------------------------------------------------------
void CReporterHttpClient::initSession(bool deleteAfterSending)
{
Q_D(CReporterHttpClient);
d->init(deleteAfterSending);
}
// ----------------------------------------------------------------------------
// CReporterHttpClient::state
// ----------------------------------------------------------------------------
CReporterHttpClient::State CReporterHttpClient::state() const
{
return d_ptr->m_clientState;
}
// ----------------------------------------------------------------------------
// CReporterHttpClient::stateToString
// ----------------------------------------------------------------------------
QString CReporterHttpClient::stateToString(CReporterHttpClient::State state) const
{
return QString(clientstate_string[state]);
}
// ----------------------------------------------------------------------------
// CReporterHttpClient::upload
// ----------------------------------------------------------------------------
bool CReporterHttpClient::upload(const QString &file)
{
Q_D( CReporterHttpClient );
qDebug() << __PRETTY_FUNCTION__ << "Upload requested.";
return d->createRequest(file);
}
// ----------------------------------------------------------------------------
// CReporterHttpClient::cancel
// ----------------------------------------------------------------------------
void CReporterHttpClient::cancel()
{
Q_D(CReporterHttpClient);
qDebug() << __PRETTY_FUNCTION__ << "Cancel requested.";
d->cancel();
}
// End of file
<commit_msg>[httpclient] connect to QNetworkReply::uploadProgress() immediately<commit_after>/*
* This file is part of crash-reporter
*
* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
*
* Contact: Ville Ilvonen <[email protected]>
* Author: Riku Halonen <[email protected]>
*
* Copyright (C) 2013 Jolla Ltd.
* Contact: Jakub Adam <[email protected]>
*
* This program 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 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
// System includes.
#include <QAuthenticator>
#include <QJsonDocument>
#include <QJsonObject>
#include <QNetworkReply>
#include <QDebug>
#include <QFile>
#include <QFileInfo>
#include <QDir>
#include <QSslConfiguration>
#include <QNetworkProxy>
#include <QTime>
// User includes.
#include "creportercoreregistry.h"
#include "creporterhttpclient.h"
#include "creporterhttpclient_p.h"
#include "creporterapplicationsettings.h"
#include "creporterutils.h"
const char *clientstate_string[] = {"None", "Init", "Connecting", "Sending", "Aborting"};
// ******** Class CReporterHttpClientPrivate ********
// ======== MEMBER FUNCTIONS ========
// ----------------------------------------------------------------------------
// CReporterHttpClientPrivate::CReporterHttpClientPrivate
// ----------------------------------------------------------------------------
CReporterHttpClientPrivate::CReporterHttpClientPrivate() :
m_manager( 0 ),
m_reply( 0 )
{
m_clientState = CReporterHttpClient::None;
}
// ----------------------------------------------------------------------------
// CReporterHttpClientPrivate::~CReporterHttpClientPrivate
// ----------------------------------------------------------------------------
CReporterHttpClientPrivate::~CReporterHttpClientPrivate()
{
CReporterApplicationSettings::freeSingleton();
if (m_reply != 0) {
m_reply->abort();
m_reply = 0;
}
if (m_manager != 0) {
delete m_manager;
m_manager = 0;
}
}
// ----------------------------------------------------------------------------
// CReporterHttpClientPrivate::init
// ----------------------------------------------------------------------------
void CReporterHttpClientPrivate::init(bool deleteAfterSending)
{
qDebug() << __PRETTY_FUNCTION__ << "Initiating HTTP session.";
m_deleteFileFlag = deleteAfterSending;
m_userAborted = false;
m_httpError = false;
if (CReporterApplicationSettings::instance()->useProxy()) {
qDebug() << __PRETTY_FUNCTION__ << "Network proxy defined.";
QNetworkProxy proxy;
proxy.setType(QNetworkProxy::HttpProxy);
proxy.setHostName(CReporterApplicationSettings::instance()->proxyUrl());
proxy.setPort(CReporterApplicationSettings::instance()->proxyPort());
QNetworkProxy::setApplicationProxy(proxy);
}
if (m_manager == 0) {
m_manager = new QNetworkAccessManager(q_ptr);
Q_CHECK_PTR(m_manager);
connect(m_manager, SIGNAL(authenticationRequired(QNetworkReply*, QAuthenticator*)),
this, SLOT(handleAuthenticationRequired(QNetworkReply*, QAuthenticator*)));
}
stateChange(CReporterHttpClient::Init);
}
// ----------------------------------------------------------------------------
// CReporterHttpClientPrivate::createRequest
// ----------------------------------------------------------------------------
bool CReporterHttpClientPrivate::createRequest(const QString &file)
{
Q_ASSERT(m_manager != NULL);
qDebug() << __PRETTY_FUNCTION__ << "Create new request.";
if (m_clientState != CReporterHttpClient::Init) {
return false;
}
QNetworkRequest request;
QByteArray dataToSend;
// Set server URL and port.
QUrl url(CReporterApplicationSettings::instance()->serverUrl());
url.setPort(CReporterApplicationSettings::instance()->serverPort());
if (CReporterApplicationSettings::instance()->useSsl()) {
qDebug() << __PRETTY_FUNCTION__ << "SSL is enabled.";
QSslConfiguration ssl(QSslConfiguration::defaultConfiguration());
ssl.setPeerVerifyMode(QSslSocket::VerifyNone);
request.setSslConfiguration(ssl);
}
// Set file to be the current.
m_currentFile.setFile(file);
qDebug() << __PRETTY_FUNCTION__ << "File to upload:" << m_currentFile.absoluteFilePath();
qDebug() << __PRETTY_FUNCTION__ << "File size:" << m_currentFile.size() / 1024 << "kB's";
// For PUT, we need to append file name to the path.
QString serverPath = CReporterApplicationSettings::instance()->serverPath() +
"/" + m_currentFile.fileName();
url.setPath(serverPath);
url.setQuery("uuid=" + CReporterUtils::deviceUid() +
"&model=" + CReporterUtils::deviceModel());
request.setUrl(url);
qDebug() << __PRETTY_FUNCTION__ << "Upload URL:" << url.toString();
if (!createPutRequest(request, dataToSend)) {
qDebug() << __PRETTY_FUNCTION__ << "Failed to create network request.";
return false;
}
// Send request and connect signal/ slots.
m_reply = m_manager->put(request, dataToSend);
if (m_reply == 0) {
return false;
}
// Connect QNetworkReply signals.
connect(m_reply, SIGNAL(sslErrors(QList<QSslError>)),
this, SLOT(handleSslErrors(QList<QSslError>)));
connect(m_reply, SIGNAL(error(QNetworkReply::NetworkError)),
this, SLOT(handleError(QNetworkReply::NetworkError)));
connect(m_reply, SIGNAL(finished()), this, SLOT(handleFinished()));
connect(m_reply, &QNetworkReply::uploadProgress,
this, &CReporterHttpClientPrivate::handleUploadProgress);
stateChange(CReporterHttpClient::Connecting);
return true;
}
// ----------------------------------------------------------------------------
// CReporterHttpClientPrivate::cancel
// ----------------------------------------------------------------------------
void CReporterHttpClientPrivate::cancel()
{
qDebug() << __PRETTY_FUNCTION__ << "User aborted transaction.";
m_userAborted = true;
stateChange( CReporterHttpClient::Aborting );
if (m_reply != 0) {
qDebug() << __PRETTY_FUNCTION__ << "Canceling transaction.";
// Abort ongoing transactions.
m_reply->abort();
}
// Clean up.
handleFinished();
}
// ======== LOCAL FUNCTIONS ========
// ----------------------------------------------------------------------------
// CReporterHttpClientPrivate::handleAuthenticationRequired
// ----------------------------------------------------------------------------
void CReporterHttpClientPrivate::handleAuthenticationRequired(QNetworkReply *reply,
QAuthenticator *authenticator)
{
Q_UNUSED(reply)
qDebug() << __PRETTY_FUNCTION__ << "Fill in the credentials.";
// Fill in the credentials.
authenticator->setUser(CReporterApplicationSettings::instance()->username());
authenticator->setPassword(CReporterApplicationSettings::instance()->password());
}
// ----------------------------------------------------------------------------
// CReporterHttpClientPrivate::handleSslErrors
// ----------------------------------------------------------------------------
void CReporterHttpClientPrivate::handleSslErrors(const QList<QSslError> &errors )
{
QString errorString;
foreach (const QSslError &error, errors) {
if ( !errorString.isEmpty() ) {
errorString += ", ";
}
errorString += error.errorString();
}
qDebug() << "One or more SSL errors occured:" << errorString;
// Ignore and continue connection.
m_reply->ignoreSslErrors();
}
// ----------------------------------------------------------------------------
// CReporterHttpClientPrivate::handleError
// ----------------------------------------------------------------------------
void CReporterHttpClientPrivate::handleError(QNetworkReply::NetworkError error)
{
if (m_reply && m_reply->error() != QNetworkReply::NoError) {
// Finished is emitted by QNetworkReply after this, inidicating that
// the connection is over.
qCritical() << __PRETTY_FUNCTION__ << "Upload failed.";
m_httpError = true;
QString errorString =m_reply->errorString();
qDebug() << __PRETTY_FUNCTION__ << "Error code:" << error << "," << errorString;
emit uploadError(m_currentFile.fileName(), errorString);
}
}
void CReporterHttpClientPrivate::parseReply()
{
if (!m_reply) {
qDebug() << "Server reply is NULL";
return;
}
if (!m_reply->open(QIODevice::ReadOnly)) {
qDebug() << "Couldn't open server reply for reading.";
return;
}
QJsonDocument reply = QJsonDocument::fromJson(m_reply->readAll());
if (reply.isNull() || !reply.isObject()) {
qDebug() << "Error parsing JSON server reply.";
return;
}
QJsonObject json = reply.object();
int submissionId = static_cast<int>(json.value("submission_id").toDouble(0));
if (submissionId == 0) {
qDebug() << "Failed to parse submission id from JSON.";
return;
}
QUrl submissionUrl(CReporterApplicationSettings::instance()->serverUrl());
submissionUrl.setPort(CReporterApplicationSettings::instance()->serverPort());
submissionUrl.setPath("/");
submissionUrl.setFragment(QString("submissions/%1").arg(submissionId));
QString corePath(CReporterCoreRegistry::instance()->getCoreLocationPaths().first());
QFile uploadlog(corePath + "/uploadlog");
if (!uploadlog.open(QIODevice::WriteOnly | QIODevice::Append)) {
qDebug() << "Couldn't open uploadlog for writing.";
return;
}
QTextStream stream(&uploadlog);
stream << m_currentFile.fileName() << ' ' << submissionUrl.toString() << '\n';
uploadlog.close();
}
// ----------------------------------------------------------------------------
// CReporterHttpClientPrivate::handleFinished
// ----------------------------------------------------------------------------
void CReporterHttpClientPrivate::handleFinished()
{
qDebug() << __PRETTY_FUNCTION__ << "Uploading file:" << m_currentFile.fileName() << "finished.";
if (!m_httpError && !m_userAborted) {
// Upload was successful.
parseReply();
if (m_deleteFileFlag) {
// Remove file if delete was requested.
CReporterUtils::removeFile(m_currentFile.absoluteFilePath());
}
}
// QNetworkreply objects are owned by QNetworkAccessManager and deleted along with it.
m_reply = 0;
stateChange(CReporterHttpClient::Init);
emit finished();
}
// ----------------------------------------------------------------------------
// CReporterHttpClientPrivate::handleUploadProgress
// ----------------------------------------------------------------------------
void CReporterHttpClientPrivate::handleUploadProgress(qint64 bytesSent, qint64 bytesTotal)
{
qDebug() << __PRETTY_FUNCTION__ << "Sent:" << bytesSent << "Total:" << bytesTotal;
if (m_userAborted || m_httpError) {
// Do not update, if aborted.
return;
}
if (m_clientState != CReporterHttpClient::Sending) {
stateChange(CReporterHttpClient::Sending);
}
int done = (int)((bytesSent * 100) / bytesTotal);
qDebug() << __PRETTY_FUNCTION__ << "Done:" << done << "%";
emit q_ptr->updateProgress(done);
}
// ----------------------------------------------------------------------------
// CReporterHttpClientPrivate::stateChange
// ----------------------------------------------------------------------------
void CReporterHttpClientPrivate::stateChange(CReporterHttpClient::State nextState)
{
qDebug() << __PRETTY_FUNCTION__ << "Current state:" << q_ptr->stateToString( m_clientState );
qDebug() << __PRETTY_FUNCTION__ << "New state:" << q_ptr->stateToString( nextState );
m_clientState = nextState;
emit stateChanged( m_clientState );
}
// ----------------------------------------------------------------------------
// CReporterHttpClientPrivate::createPutRequest
// ----------------------------------------------------------------------------
bool CReporterHttpClientPrivate::createPutRequest(QNetworkRequest &request,
QByteArray &dataToSend)
{
QFile file(m_currentFile.absoluteFilePath());
// Abort, if file doesn't exist or IO error.
if (!file.exists() || !file.open(QIODevice::ReadOnly)) {
return false;
}
// Append file.
dataToSend += file.readAll();
file.close();
// Construct HTTP Headers.
request.setRawHeader("User-Agent", "crash-reporter");
request.setRawHeader("Accept", "*/*");
request.setHeader(QNetworkRequest::ContentLengthHeader, dataToSend.size());
return true;
}
// ******** Class CReporterHttpClient ********
// ======== MEMBER FUNCTIONS ========
// ----------------------------------------------------------------------------
// CReporterHttpClient::CReporterHttpClient
// ----------------------------------------------------------------------------
CReporterHttpClient::CReporterHttpClient(QObject *parent) :
QObject(parent) ,
d_ptr(new CReporterHttpClientPrivate())
{
Q_D(CReporterHttpClient);
d->q_ptr = this;
connect( d, SIGNAL(stateChanged(CReporterHttpClient::State)),
this, SIGNAL(clientStateChanged(CReporterHttpClient::State)) );
connect( d, SIGNAL(uploadError(QString,QString)), this, SIGNAL(uploadError(QString,QString)) );
connect( d, SIGNAL(finished()), this, SIGNAL(finished()) );
}
// ----------------------------------------------------------------------------
// CReporterHttpClient::~CReporterHttpClient
// ----------------------------------------------------------------------------
CReporterHttpClient::~CReporterHttpClient()
{
qDebug() << __PRETTY_FUNCTION__ << "Client destroyed.";
delete d_ptr;
d_ptr = NULL;
}
// ----------------------------------------------------------------------------
// CReporterHttpClient::initSession
// ----------------------------------------------------------------------------
void CReporterHttpClient::initSession(bool deleteAfterSending)
{
Q_D(CReporterHttpClient);
d->init(deleteAfterSending);
}
// ----------------------------------------------------------------------------
// CReporterHttpClient::state
// ----------------------------------------------------------------------------
CReporterHttpClient::State CReporterHttpClient::state() const
{
return d_ptr->m_clientState;
}
// ----------------------------------------------------------------------------
// CReporterHttpClient::stateToString
// ----------------------------------------------------------------------------
QString CReporterHttpClient::stateToString(CReporterHttpClient::State state) const
{
return QString(clientstate_string[state]);
}
// ----------------------------------------------------------------------------
// CReporterHttpClient::upload
// ----------------------------------------------------------------------------
bool CReporterHttpClient::upload(const QString &file)
{
Q_D( CReporterHttpClient );
qDebug() << __PRETTY_FUNCTION__ << "Upload requested.";
return d->createRequest(file);
}
// ----------------------------------------------------------------------------
// CReporterHttpClient::cancel
// ----------------------------------------------------------------------------
void CReporterHttpClient::cancel()
{
Q_D(CReporterHttpClient);
qDebug() << __PRETTY_FUNCTION__ << "Cancel requested.";
d->cancel();
}
// End of file
<|endoftext|> |
<commit_before>#include "Capture.h"
#include "Timer.h"
#include <iostream>
#include <time.h>
static const int cameraWidth = 848, cameraHeight = 480;
//static const int videoFileFPS = 60; // Set frame rate to 60 fps for ffmpeg.
static const int videoFileFPS = -1; // Let GStreamer control its own frame rate.
Capture::Capture(int device)
: cap(device)
, fps(-1)
, canDropFrame(true)
{
imageWidth = cameraWidth;
imageHeight = cameraHeight;
cap.set(cv::CAP_PROP_FRAME_WIDTH, cameraWidth);
cap.set(cv::CAP_PROP_FRAME_HEIGHT, cameraHeight);
}
Capture::Capture(const char* filename)
: cap(filename)
, fps(videoFileFPS)
, canDropFrame(false)
{
imageWidth = cap.get(cv::CAP_PROP_FRAME_WIDTH);
imageHeight = cap.get(cv::CAP_PROP_FRAME_HEIGHT);
}
void Capture::BackgroundLoop() {
cv::Mat image;
int frameCount = 0;
Timer timer;
timer.Start();
while (! imagesCaptured.quitting) {
if (! cap.read(image)) {break;}
if (canDropFrame && imagesCaptured.size >= imagesCaptured.Capacity()) {
std::cerr << "Capture dropped frame." << std::endl;
} else {
imagesCaptured.Enqueue(image);
++frameCount;
struct timespec sleep = {0, fps > 0 ? 1000 * timer.NextSleep(fps, frameCount) : 0};
if (sleep.tv_nsec > 0) {
nanosleep(&sleep, NULL);
}
}
}
timer.PrintTimeStats(frameCount);
}
static void* CaptureThread(void* cap) {
((Capture*)cap)->BackgroundLoop();
return 0;
}
void Capture::Start() {
pthread_create(&thread, NULL, CaptureThread, this);
}
void Capture::Stop() {
imagesCaptured.Quit();
pthread_join(thread, NULL);
}
<commit_msg>frame rate and image size<commit_after>#include "Capture.h"
#include "Timer.h"
#include <iostream>
#include <time.h>
static const int cameraWidth = 160, cameraHeight = 120;
static const float cameraFPS = -1.;
static const int videoFileFPS = -1;
Capture::Capture(int device)
: cap(device)
, fps(-1)
, canDropFrame(true)
{
#if 0
imageWidth = cap.get(cv::CAP_PROP_FRAME_WIDTH);
imageHeight = cap.get(cv::CAP_PROP_FRAME_HEIGHT);
std::cerr << "camera: " << imageWidth << " x " << imageHeight << std::endl;
#else
imageWidth = cameraWidth;
imageHeight = cameraHeight;
cap.set(cv::CAP_PROP_FRAME_WIDTH, cameraWidth);
cap.set(cv::CAP_PROP_FRAME_HEIGHT, cameraHeight);
#endif
if (cameraFPS > 0) {
cap.set(cv::CAP_PROP_FPS, cameraFPS);
}
}
Capture::Capture(const char* filename)
: cap(filename)
, fps(videoFileFPS)
, canDropFrame(false)
{
imageWidth = cap.get(cv::CAP_PROP_FRAME_WIDTH);
imageHeight = cap.get(cv::CAP_PROP_FRAME_HEIGHT);
}
void Capture::BackgroundLoop() {
cv::Mat image;
int frameCount = 0;
Timer timer;
timer.Start();
while (! imagesCaptured.quitting) {
if (! cap.read(image)) {break;}
if (canDropFrame && imagesCaptured.size >= imagesCaptured.Capacity()) {
std::cerr << "Capture dropped frame." << std::endl;
} else {
imagesCaptured.Enqueue(image);
++frameCount;
struct timespec sleep = {0, fps > 0 ? 1000 * timer.NextSleep(fps, frameCount) : 0};
if (sleep.tv_nsec > 0) {
nanosleep(&sleep, NULL);
}
}
}
timer.PrintTimeStats(frameCount);
}
static void* CaptureThread(void* cap) {
((Capture*)cap)->BackgroundLoop();
return 0;
}
void Capture::Start() {
pthread_create(&thread, NULL, CaptureThread, this);
}
void Capture::Stop() {
imagesCaptured.Quit();
pthread_join(thread, NULL);
}
<|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.
#ifndef RCLCPP__INTRA_PROCESS_MANAGER_IMPL_HPP_
#define RCLCPP__INTRA_PROCESS_MANAGER_IMPL_HPP_
#include <algorithm>
#include <array>
#include <atomic>
#include <cstring>
#include <functional>
#include <limits>
#include <map>
#include <memory>
#include <mutex>
#include <set>
#include <string>
#include <unordered_map>
#include <utility>
#include "rmw/validate_full_topic_name.h"
#include "rclcpp/macros.hpp"
#include "rclcpp/mapped_ring_buffer.hpp"
#include "rclcpp/publisher.hpp"
#include "rclcpp/subscription.hpp"
#include "rclcpp/visibility_control.hpp"
namespace rclcpp
{
namespace intra_process_manager
{
class IntraProcessManagerImplBase
{
public:
RCLCPP_SMART_PTR_DEFINITIONS_NOT_COPYABLE(IntraProcessManagerImplBase)
IntraProcessManagerImplBase() = default;
virtual ~IntraProcessManagerImplBase() = default;
virtual void
add_subscription(uint64_t id, SubscriptionBase::SharedPtr subscription) = 0;
virtual void
remove_subscription(uint64_t intra_process_subscription_id) = 0;
virtual void add_publisher(
uint64_t id,
PublisherBase::WeakPtr publisher,
mapped_ring_buffer::MappedRingBufferBase::SharedPtr mrb,
size_t size) = 0;
virtual void
remove_publisher(uint64_t intra_process_publisher_id) = 0;
virtual mapped_ring_buffer::MappedRingBufferBase::SharedPtr
get_publisher_info_for_id(
uint64_t intra_process_publisher_id,
uint64_t & message_seq) = 0;
virtual void
store_intra_process_message(uint64_t intra_process_publisher_id, uint64_t message_seq) = 0;
virtual mapped_ring_buffer::MappedRingBufferBase::SharedPtr
take_intra_process_message(
uint64_t intra_process_publisher_id,
uint64_t message_sequence_number,
uint64_t requesting_subscriptions_intra_process_id,
size_t & size) = 0;
virtual bool
matches_any_publishers(const rmw_gid_t * id) const = 0;
virtual size_t
get_subscription_count(uint64_t intra_process_publisher_id) const = 0;
private:
RCLCPP_DISABLE_COPY(IntraProcessManagerImplBase)
};
template<typename Allocator = std::allocator<void>>
class IntraProcessManagerImpl : public IntraProcessManagerImplBase
{
public:
IntraProcessManagerImpl() = default;
~IntraProcessManagerImpl() = default;
void
add_subscription(uint64_t id, SubscriptionBase::SharedPtr subscription)
{
subscriptions_[id] = subscription;
subscription_ids_by_topic_[fixed_size_string(subscription->get_topic_name())].insert(id);
}
void
remove_subscription(uint64_t intra_process_subscription_id)
{
subscriptions_.erase(intra_process_subscription_id);
for (auto & pair : subscription_ids_by_topic_) {
pair.second.erase(intra_process_subscription_id);
}
// Iterate over all publisher infos and all stored subscription id's and
// remove references to this subscription's id.
for (auto & publisher_pair : publishers_) {
for (auto & sub_pair : publisher_pair.second.target_subscriptions_by_message_sequence) {
sub_pair.second.erase(intra_process_subscription_id);
}
}
}
void add_publisher(
uint64_t id,
PublisherBase::WeakPtr publisher,
mapped_ring_buffer::MappedRingBufferBase::SharedPtr mrb,
size_t size)
{
publishers_[id].publisher = publisher;
// As long as the size of the ring buffer is less than the max sequence number, we're safe.
if (size > std::numeric_limits<uint64_t>::max()) {
throw std::invalid_argument("the calculated buffer size is too large");
}
publishers_[id].sequence_number.store(0);
publishers_[id].buffer = mrb;
publishers_[id].target_subscriptions_by_message_sequence.reserve(size);
}
void
remove_publisher(uint64_t intra_process_publisher_id)
{
publishers_.erase(intra_process_publisher_id);
}
// return message_seq and mrb
mapped_ring_buffer::MappedRingBufferBase::SharedPtr
get_publisher_info_for_id(
uint64_t intra_process_publisher_id,
uint64_t & message_seq)
{
std::lock_guard<std::mutex> lock(runtime_mutex_);
auto it = publishers_.find(intra_process_publisher_id);
if (it == publishers_.end()) {
throw std::runtime_error("get_publisher_info_for_id called with invalid publisher id");
}
PublisherInfo & info = it->second;
// Calculate the next message sequence number.
message_seq = info.sequence_number.fetch_add(1);
return info.buffer;
}
void
store_intra_process_message(uint64_t intra_process_publisher_id, uint64_t message_seq)
{
std::lock_guard<std::mutex> lock(runtime_mutex_);
auto it = publishers_.find(intra_process_publisher_id);
if (it == publishers_.end()) {
throw std::runtime_error("store_intra_process_message called with invalid publisher id");
}
PublisherInfo & info = it->second;
auto publisher = info.publisher.lock();
if (!publisher) {
throw std::runtime_error("publisher has unexpectedly gone out of scope");
}
// Figure out what subscriptions should receive the message.
auto & destined_subscriptions =
subscription_ids_by_topic_[fixed_size_string(publisher->get_topic_name())];
// Store the list for later comparison.
if (info.target_subscriptions_by_message_sequence.count(message_seq) == 0) {
info.target_subscriptions_by_message_sequence.emplace(
message_seq, AllocSet(std::less<uint64_t>(), uint64_allocator));
} else {
info.target_subscriptions_by_message_sequence[message_seq].clear();
}
std::copy(
destined_subscriptions.begin(), destined_subscriptions.end(),
// Memory allocation occurs in info.target_subscriptions_by_message_sequence[message_seq]
std::inserter(
info.target_subscriptions_by_message_sequence[message_seq],
// This ends up only being a hint to std::set, could also be .begin().
info.target_subscriptions_by_message_sequence[message_seq].end()
)
);
}
mapped_ring_buffer::MappedRingBufferBase::SharedPtr
take_intra_process_message(
uint64_t intra_process_publisher_id,
uint64_t message_sequence_number,
uint64_t requesting_subscriptions_intra_process_id,
size_t & size
)
{
std::lock_guard<std::mutex> lock(runtime_mutex_);
PublisherInfo * info;
{
auto it = publishers_.find(intra_process_publisher_id);
if (it == publishers_.end()) {
// Publisher is either invalid or no longer exists.
return 0;
}
info = &it->second;
}
// Figure out how many subscriptions are left.
AllocSet * target_subs;
{
auto it = info->target_subscriptions_by_message_sequence.find(message_sequence_number);
if (it == info->target_subscriptions_by_message_sequence.end()) {
// Message is no longer being stored by this publisher.
return 0;
}
target_subs = &it->second;
}
{
auto it = std::find(
target_subs->begin(), target_subs->end(),
requesting_subscriptions_intra_process_id);
if (it == target_subs->end()) {
// This publisher id/message seq pair was not intended for this subscription.
return 0;
}
target_subs->erase(it);
}
size = target_subs->size();
return info->buffer;
}
bool
matches_any_publishers(const rmw_gid_t * id) const
{
for (auto & publisher_pair : publishers_) {
auto publisher = publisher_pair.second.publisher.lock();
if (!publisher) {
continue;
}
if (*publisher.get() == id) {
return true;
}
}
return false;
}
size_t
get_subscription_count(uint64_t intra_process_publisher_id) const
{
auto publisher_it = publishers_.find(intra_process_publisher_id);
if (publisher_it == publishers_.end()) {
// Publisher is either invalid or no longer exists.
return 0;
}
auto publisher = publisher_it->second.publisher.lock();
if (!publisher) {
throw std::runtime_error("publisher has unexpectedly gone out of scope");
}
auto sub_map_it =
subscription_ids_by_topic_.find(fixed_size_string(publisher->get_topic_name()));
if (sub_map_it == subscription_ids_by_topic_.end()) {
// No intraprocess subscribers
return 0;
}
return sub_map_it->second.size();
}
private:
RCLCPP_DISABLE_COPY(IntraProcessManagerImpl)
using FixedSizeString = std::array<char, RMW_TOPIC_MAX_NAME_LENGTH + 1>;
FixedSizeString
fixed_size_string(const char * str) const
{
FixedSizeString ret;
std::strncpy(ret.data(), str, ret.size());
return ret;
}
template<typename T>
using RebindAlloc = typename std::allocator_traits<Allocator>::template rebind_alloc<T>;
RebindAlloc<uint64_t> uint64_allocator;
using AllocSet = std::set<uint64_t, std::less<uint64_t>, RebindAlloc<uint64_t>>;
using SubscriptionMap = std::unordered_map<
uint64_t, SubscriptionBase::WeakPtr,
std::hash<uint64_t>, std::equal_to<uint64_t>,
RebindAlloc<std::pair<const uint64_t, SubscriptionBase::WeakPtr>>>;
using IDTopicMap = std::map<
FixedSizeString,
AllocSet,
std::less<FixedSizeString>,
RebindAlloc<std::pair<const FixedSizeString, AllocSet>>>;
SubscriptionMap subscriptions_;
IDTopicMap subscription_ids_by_topic_;
struct PublisherInfo
{
RCLCPP_DISABLE_COPY(PublisherInfo)
PublisherInfo() = default;
PublisherBase::WeakPtr publisher;
std::atomic<uint64_t> sequence_number;
mapped_ring_buffer::MappedRingBufferBase::SharedPtr buffer;
using TargetSubscriptionsMap = std::unordered_map<
uint64_t, AllocSet,
std::hash<uint64_t>, std::equal_to<uint64_t>,
RebindAlloc<std::pair<const uint64_t, AllocSet>>>;
TargetSubscriptionsMap target_subscriptions_by_message_sequence;
};
using PublisherMap = std::unordered_map<
uint64_t, PublisherInfo,
std::hash<uint64_t>, std::equal_to<uint64_t>,
RebindAlloc<std::pair<const uint64_t, PublisherInfo>>>;
PublisherMap publishers_;
std::mutex runtime_mutex_;
};
RCLCPP_PUBLIC
IntraProcessManagerImplBase::SharedPtr
create_default_impl();
} // namespace intra_process_manager
} // namespace rclcpp
#endif // RCLCPP__INTRA_PROCESS_MANAGER_IMPL_HPP_
<commit_msg>Replaced strncpy with memcpy (#684)<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.
#ifndef RCLCPP__INTRA_PROCESS_MANAGER_IMPL_HPP_
#define RCLCPP__INTRA_PROCESS_MANAGER_IMPL_HPP_
#include <algorithm>
#include <array>
#include <atomic>
#include <cstring>
#include <functional>
#include <limits>
#include <map>
#include <memory>
#include <mutex>
#include <set>
#include <stdexcept>
#include <string>
#include <unordered_map>
#include <utility>
#include "rmw/validate_full_topic_name.h"
#include "rclcpp/macros.hpp"
#include "rclcpp/mapped_ring_buffer.hpp"
#include "rclcpp/publisher.hpp"
#include "rclcpp/subscription.hpp"
#include "rclcpp/visibility_control.hpp"
namespace rclcpp
{
namespace intra_process_manager
{
class IntraProcessManagerImplBase
{
public:
RCLCPP_SMART_PTR_DEFINITIONS_NOT_COPYABLE(IntraProcessManagerImplBase)
IntraProcessManagerImplBase() = default;
virtual ~IntraProcessManagerImplBase() = default;
virtual void
add_subscription(uint64_t id, SubscriptionBase::SharedPtr subscription) = 0;
virtual void
remove_subscription(uint64_t intra_process_subscription_id) = 0;
virtual void add_publisher(
uint64_t id,
PublisherBase::WeakPtr publisher,
mapped_ring_buffer::MappedRingBufferBase::SharedPtr mrb,
size_t size) = 0;
virtual void
remove_publisher(uint64_t intra_process_publisher_id) = 0;
virtual mapped_ring_buffer::MappedRingBufferBase::SharedPtr
get_publisher_info_for_id(
uint64_t intra_process_publisher_id,
uint64_t & message_seq) = 0;
virtual void
store_intra_process_message(uint64_t intra_process_publisher_id, uint64_t message_seq) = 0;
virtual mapped_ring_buffer::MappedRingBufferBase::SharedPtr
take_intra_process_message(
uint64_t intra_process_publisher_id,
uint64_t message_sequence_number,
uint64_t requesting_subscriptions_intra_process_id,
size_t & size) = 0;
virtual bool
matches_any_publishers(const rmw_gid_t * id) const = 0;
virtual size_t
get_subscription_count(uint64_t intra_process_publisher_id) const = 0;
private:
RCLCPP_DISABLE_COPY(IntraProcessManagerImplBase)
};
template<typename Allocator = std::allocator<void>>
class IntraProcessManagerImpl : public IntraProcessManagerImplBase
{
public:
IntraProcessManagerImpl() = default;
~IntraProcessManagerImpl() = default;
void
add_subscription(uint64_t id, SubscriptionBase::SharedPtr subscription)
{
subscriptions_[id] = subscription;
subscription_ids_by_topic_[fixed_size_string(subscription->get_topic_name())].insert(id);
}
void
remove_subscription(uint64_t intra_process_subscription_id)
{
subscriptions_.erase(intra_process_subscription_id);
for (auto & pair : subscription_ids_by_topic_) {
pair.second.erase(intra_process_subscription_id);
}
// Iterate over all publisher infos and all stored subscription id's and
// remove references to this subscription's id.
for (auto & publisher_pair : publishers_) {
for (auto & sub_pair : publisher_pair.second.target_subscriptions_by_message_sequence) {
sub_pair.second.erase(intra_process_subscription_id);
}
}
}
void add_publisher(
uint64_t id,
PublisherBase::WeakPtr publisher,
mapped_ring_buffer::MappedRingBufferBase::SharedPtr mrb,
size_t size)
{
publishers_[id].publisher = publisher;
// As long as the size of the ring buffer is less than the max sequence number, we're safe.
if (size > std::numeric_limits<uint64_t>::max()) {
throw std::invalid_argument("the calculated buffer size is too large");
}
publishers_[id].sequence_number.store(0);
publishers_[id].buffer = mrb;
publishers_[id].target_subscriptions_by_message_sequence.reserve(size);
}
void
remove_publisher(uint64_t intra_process_publisher_id)
{
publishers_.erase(intra_process_publisher_id);
}
// return message_seq and mrb
mapped_ring_buffer::MappedRingBufferBase::SharedPtr
get_publisher_info_for_id(
uint64_t intra_process_publisher_id,
uint64_t & message_seq)
{
std::lock_guard<std::mutex> lock(runtime_mutex_);
auto it = publishers_.find(intra_process_publisher_id);
if (it == publishers_.end()) {
throw std::runtime_error("get_publisher_info_for_id called with invalid publisher id");
}
PublisherInfo & info = it->second;
// Calculate the next message sequence number.
message_seq = info.sequence_number.fetch_add(1);
return info.buffer;
}
void
store_intra_process_message(uint64_t intra_process_publisher_id, uint64_t message_seq)
{
std::lock_guard<std::mutex> lock(runtime_mutex_);
auto it = publishers_.find(intra_process_publisher_id);
if (it == publishers_.end()) {
throw std::runtime_error("store_intra_process_message called with invalid publisher id");
}
PublisherInfo & info = it->second;
auto publisher = info.publisher.lock();
if (!publisher) {
throw std::runtime_error("publisher has unexpectedly gone out of scope");
}
// Figure out what subscriptions should receive the message.
auto & destined_subscriptions =
subscription_ids_by_topic_[fixed_size_string(publisher->get_topic_name())];
// Store the list for later comparison.
if (info.target_subscriptions_by_message_sequence.count(message_seq) == 0) {
info.target_subscriptions_by_message_sequence.emplace(
message_seq, AllocSet(std::less<uint64_t>(), uint64_allocator));
} else {
info.target_subscriptions_by_message_sequence[message_seq].clear();
}
std::copy(
destined_subscriptions.begin(), destined_subscriptions.end(),
// Memory allocation occurs in info.target_subscriptions_by_message_sequence[message_seq]
std::inserter(
info.target_subscriptions_by_message_sequence[message_seq],
// This ends up only being a hint to std::set, could also be .begin().
info.target_subscriptions_by_message_sequence[message_seq].end()
)
);
}
mapped_ring_buffer::MappedRingBufferBase::SharedPtr
take_intra_process_message(
uint64_t intra_process_publisher_id,
uint64_t message_sequence_number,
uint64_t requesting_subscriptions_intra_process_id,
size_t & size
)
{
std::lock_guard<std::mutex> lock(runtime_mutex_);
PublisherInfo * info;
{
auto it = publishers_.find(intra_process_publisher_id);
if (it == publishers_.end()) {
// Publisher is either invalid or no longer exists.
return 0;
}
info = &it->second;
}
// Figure out how many subscriptions are left.
AllocSet * target_subs;
{
auto it = info->target_subscriptions_by_message_sequence.find(message_sequence_number);
if (it == info->target_subscriptions_by_message_sequence.end()) {
// Message is no longer being stored by this publisher.
return 0;
}
target_subs = &it->second;
}
{
auto it = std::find(
target_subs->begin(), target_subs->end(),
requesting_subscriptions_intra_process_id);
if (it == target_subs->end()) {
// This publisher id/message seq pair was not intended for this subscription.
return 0;
}
target_subs->erase(it);
}
size = target_subs->size();
return info->buffer;
}
bool
matches_any_publishers(const rmw_gid_t * id) const
{
for (auto & publisher_pair : publishers_) {
auto publisher = publisher_pair.second.publisher.lock();
if (!publisher) {
continue;
}
if (*publisher.get() == id) {
return true;
}
}
return false;
}
size_t
get_subscription_count(uint64_t intra_process_publisher_id) const
{
auto publisher_it = publishers_.find(intra_process_publisher_id);
if (publisher_it == publishers_.end()) {
// Publisher is either invalid or no longer exists.
return 0;
}
auto publisher = publisher_it->second.publisher.lock();
if (!publisher) {
throw std::runtime_error("publisher has unexpectedly gone out of scope");
}
auto sub_map_it =
subscription_ids_by_topic_.find(fixed_size_string(publisher->get_topic_name()));
if (sub_map_it == subscription_ids_by_topic_.end()) {
// No intraprocess subscribers
return 0;
}
return sub_map_it->second.size();
}
private:
RCLCPP_DISABLE_COPY(IntraProcessManagerImpl)
using FixedSizeString = std::array<char, RMW_TOPIC_MAX_NAME_LENGTH + 1>;
FixedSizeString
fixed_size_string(const char * str) const
{
FixedSizeString ret;
size_t size = std::strlen(str) + 1;
if (size > ret.size()) {
throw std::runtime_error("failed to copy topic name");
}
std::memcpy(ret.data(), str, size);
return ret;
}
struct strcmp_wrapper
{
bool
operator()(const FixedSizeString lhs, const FixedSizeString rhs) const
{
return std::strcmp(lhs.data(), rhs.data()) < 0;
}
};
template<typename T>
using RebindAlloc = typename std::allocator_traits<Allocator>::template rebind_alloc<T>;
RebindAlloc<uint64_t> uint64_allocator;
using AllocSet = std::set<uint64_t, std::less<uint64_t>, RebindAlloc<uint64_t>>;
using SubscriptionMap = std::unordered_map<
uint64_t, SubscriptionBase::WeakPtr,
std::hash<uint64_t>, std::equal_to<uint64_t>,
RebindAlloc<std::pair<const uint64_t, SubscriptionBase::WeakPtr>>>;
using IDTopicMap = std::map<
FixedSizeString,
AllocSet,
strcmp_wrapper,
RebindAlloc<std::pair<const FixedSizeString, AllocSet>>>;
SubscriptionMap subscriptions_;
IDTopicMap subscription_ids_by_topic_;
struct PublisherInfo
{
RCLCPP_DISABLE_COPY(PublisherInfo)
PublisherInfo() = default;
PublisherBase::WeakPtr publisher;
std::atomic<uint64_t> sequence_number;
mapped_ring_buffer::MappedRingBufferBase::SharedPtr buffer;
using TargetSubscriptionsMap = std::unordered_map<
uint64_t, AllocSet,
std::hash<uint64_t>, std::equal_to<uint64_t>,
RebindAlloc<std::pair<const uint64_t, AllocSet>>>;
TargetSubscriptionsMap target_subscriptions_by_message_sequence;
};
using PublisherMap = std::unordered_map<
uint64_t, PublisherInfo,
std::hash<uint64_t>, std::equal_to<uint64_t>,
RebindAlloc<std::pair<const uint64_t, PublisherInfo>>>;
PublisherMap publishers_;
std::mutex runtime_mutex_;
};
RCLCPP_PUBLIC
IntraProcessManagerImplBase::SharedPtr
create_default_impl();
} // namespace intra_process_manager
} // namespace rclcpp
#endif // RCLCPP__INTRA_PROCESS_MANAGER_IMPL_HPP_
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2004-2009 See the AUTHORS file for details.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*/
#include "DCCSock.h"
#include "User.h"
#include "Utils.h"
CDCCSock::~CDCCSock() {
if ((m_pFile) && (!m_bNoDelFile)) {
m_pFile->Close();
delete m_pFile;
}
if (m_pUser) {
m_pUser->AddBytesRead(GetBytesRead());
m_pUser->AddBytesWritten(GetBytesWritten());
}
}
void CDCCSock::ReadData(const char* data, int len) {
if (!m_pFile) {
DEBUG("File not open! closing get.");
m_pUser->PutModule(m_sModuleName, ((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - File not open!");
Close();
}
// DCC specs says the receiving end sends the number of bytes it
// received so far as a 4 byte integer in network byte order, so we need
// uint32_t to do the job portably. This also means that the maximum
// file that we can transfer is 4 GiB big (see OpenFile()).
if (m_bSend) {
m_sSendBuf.append(data, len);
while (m_sSendBuf.size() >= 4) {
uint32_t iRemoteSoFar;
memcpy(&iRemoteSoFar, m_sSendBuf.data(), sizeof(iRemoteSoFar));
iRemoteSoFar = ntohl(iRemoteSoFar);
if ((iRemoteSoFar + 65536) >= m_uBytesSoFar) {
SendPacket();
}
m_sSendBuf.erase(0, 4);
}
} else {
m_pFile->Write(data, len);
m_uBytesSoFar += len;
uint32_t uSoFar = htonl(m_uBytesSoFar);
Write((char*) &uSoFar, sizeof(uSoFar));
if (m_uBytesSoFar >= m_uFileSize) {
Close();
}
}
}
void CDCCSock::ConnectionRefused() {
DEBUG(GetSockName() << " == ConnectionRefused()");
m_pUser->PutModule(m_sModuleName, ((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - Connection Refused.");
}
void CDCCSock::Timeout() {
DEBUG(GetSockName() << " == Timeout()");
m_pUser->PutModule(m_sModuleName, ((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - Timed Out.");
}
void CDCCSock::SockError(int iErrno) {
DEBUG(GetSockName() << " == SockError(" << iErrno << ")");
m_pUser->PutModule(m_sModuleName, ((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - Socket Error [" + CString(iErrno) + "]");
}
void CDCCSock::Connected() {
DEBUG(GetSockName() << " == Connected(" << GetRemoteIP() << ")");
m_pUser->PutModule(m_sModuleName, ((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - Transfer Started.");
if (m_bSend) {
SendPacket();
}
SetTimeout(120);
}
void CDCCSock::Disconnected() {
const CString sStart = ((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - ";
DEBUG(GetSockName() << " == Disconnected()");
if (m_uBytesSoFar > m_uFileSize) {
m_pUser->PutModule(m_sModuleName, sStart + "TooMuchData!");
} else if (m_uBytesSoFar == m_uFileSize) {
if (m_bSend) {
m_pUser->PutModule(m_sModuleName, sStart + "Completed! - Sent [" + m_sLocalFile +
"] at [" + CString((int) (GetAvgWrite() / 1024.0)) + " KiB/s ]");
} else {
m_pUser->PutModule(m_sModuleName, sStart + "Completed! - Saved to [" + m_sLocalFile +
"] at [" + CString((int) (GetAvgRead() / 1024.0)) + " KiB/s ]");
}
} else {
m_pUser->PutModule(m_sModuleName, sStart + "Incomplete!");
}
}
void CDCCSock::SendPacket() {
if (!m_pFile) {
m_pUser->PutModule(m_sModuleName, ((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - File closed prematurely.");
Close();
return;
}
char szBuf[4096];
int iLen = m_pFile->Read(szBuf, 4096);
if (iLen < 0) {
m_pUser->PutModule(m_sModuleName, ((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - Error reading from file.");
Close();
return;
}
if (iLen > 0) {
Write(szBuf, iLen);
m_uBytesSoFar += iLen;
}
}
Csock* CDCCSock::GetSockObj(const CString& sHost, unsigned short uPort) {
Close();
CDCCSock* pSock = new CDCCSock(m_pUser, m_sRemoteNick, m_sLocalFile, m_sModuleName, m_uFileSize, m_pFile);
pSock->SetSockName("DCC::SEND::" + m_sRemoteNick);
pSock->SetTimeout(120);
pSock->SetFileName(m_sFileName);
pSock->SetFileOffset(m_uBytesSoFar);
m_bNoDelFile = true;
return pSock;
}
CFile* CDCCSock::OpenFile(bool bWrite) {
if ((m_pFile) || (m_sLocalFile.empty())) {
m_pUser->PutModule(m_sModuleName, ((bWrite) ? "DCC <- [" : "DCC -> [") + m_sRemoteNick + "][" + m_sLocalFile + "] - Unable to open file.");
return NULL;
}
m_pFile = new CFile(m_sLocalFile);
if (bWrite) {
if (m_pFile->Exists()) {
delete m_pFile;
m_pFile = NULL;
m_pUser->PutModule(m_sModuleName, "DCC <- [" + m_sRemoteNick + "] - File already exists [" + m_sLocalFile + "]");
return NULL;
}
if (!m_pFile->Open(O_WRONLY | O_TRUNC | O_CREAT)) {
delete m_pFile;
m_pFile = NULL;
m_pUser->PutModule(m_sModuleName, "DCC <- [" + m_sRemoteNick + "] - Could not open file [" + m_sLocalFile + "]");
return NULL;
}
} else {
if (!m_pFile->IsReg()) {
delete m_pFile;
m_pFile = NULL;
m_pUser->PutModule(m_sModuleName, "DCC -> [" + m_sRemoteNick + "] - Not a file [" + m_sLocalFile + "]");
return NULL;
}
if (!m_pFile->Open()) {
delete m_pFile;
m_pFile = NULL;
m_pUser->PutModule(m_sModuleName, "DCC -> [" + m_sRemoteNick + "] - Could not open file [" + m_sLocalFile + "]");
return NULL;
}
// The DCC specs only allow file transfers with files smaller
// than 4GiB (see ReadData()).
off_t uFileSize = m_pFile->GetSize();
if (uFileSize > 0xffffffff) {
delete m_pFile;
m_pFile = NULL;
m_pUser->PutModule(m_sModuleName, "DCC -> [" + m_sRemoteNick + "] - File too large (>4 GiB) [" + m_sLocalFile + "]");
return NULL;
}
m_uFileSize = (unsigned long) uFileSize;
}
m_sFileName = m_pFile->GetShortName();
return m_pFile;
}
<commit_msg>DCCSock: Make sure we don't cache too much data in memory<commit_after>/*
* Copyright (C) 2004-2009 See the AUTHORS file for details.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*/
#include "DCCSock.h"
#include "User.h"
#include "Utils.h"
CDCCSock::~CDCCSock() {
if ((m_pFile) && (!m_bNoDelFile)) {
m_pFile->Close();
delete m_pFile;
}
if (m_pUser) {
m_pUser->AddBytesRead(GetBytesRead());
m_pUser->AddBytesWritten(GetBytesWritten());
}
}
void CDCCSock::ReadData(const char* data, int len) {
if (!m_pFile) {
DEBUG("File not open! closing get.");
m_pUser->PutModule(m_sModuleName, ((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - File not open!");
Close();
}
// DCC specs says the receiving end sends the number of bytes it
// received so far as a 4 byte integer in network byte order, so we need
// uint32_t to do the job portably. This also means that the maximum
// file that we can transfer is 4 GiB big (see OpenFile()).
if (m_bSend) {
m_sSendBuf.append(data, len);
while (m_sSendBuf.size() >= 4) {
uint32_t iRemoteSoFar;
memcpy(&iRemoteSoFar, m_sSendBuf.data(), sizeof(iRemoteSoFar));
iRemoteSoFar = ntohl(iRemoteSoFar);
if ((iRemoteSoFar + 65536) >= m_uBytesSoFar) {
SendPacket();
}
m_sSendBuf.erase(0, 4);
}
} else {
m_pFile->Write(data, len);
m_uBytesSoFar += len;
uint32_t uSoFar = htonl(m_uBytesSoFar);
Write((char*) &uSoFar, sizeof(uSoFar));
if (m_uBytesSoFar >= m_uFileSize) {
Close();
}
}
}
void CDCCSock::ConnectionRefused() {
DEBUG(GetSockName() << " == ConnectionRefused()");
m_pUser->PutModule(m_sModuleName, ((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - Connection Refused.");
}
void CDCCSock::Timeout() {
DEBUG(GetSockName() << " == Timeout()");
m_pUser->PutModule(m_sModuleName, ((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - Timed Out.");
}
void CDCCSock::SockError(int iErrno) {
DEBUG(GetSockName() << " == SockError(" << iErrno << ")");
m_pUser->PutModule(m_sModuleName, ((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - Socket Error [" + CString(iErrno) + "]");
}
void CDCCSock::Connected() {
DEBUG(GetSockName() << " == Connected(" << GetRemoteIP() << ")");
m_pUser->PutModule(m_sModuleName, ((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - Transfer Started.");
if (m_bSend) {
SendPacket();
}
SetTimeout(120);
}
void CDCCSock::Disconnected() {
const CString sStart = ((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - ";
DEBUG(GetSockName() << " == Disconnected()");
if (m_uBytesSoFar > m_uFileSize) {
m_pUser->PutModule(m_sModuleName, sStart + "TooMuchData!");
} else if (m_uBytesSoFar == m_uFileSize) {
if (m_bSend) {
m_pUser->PutModule(m_sModuleName, sStart + "Completed! - Sent [" + m_sLocalFile +
"] at [" + CString((int) (GetAvgWrite() / 1024.0)) + " KiB/s ]");
} else {
m_pUser->PutModule(m_sModuleName, sStart + "Completed! - Saved to [" + m_sLocalFile +
"] at [" + CString((int) (GetAvgRead() / 1024.0)) + " KiB/s ]");
}
} else {
m_pUser->PutModule(m_sModuleName, sStart + "Incomplete!");
}
}
void CDCCSock::SendPacket() {
if (!m_pFile) {
m_pUser->PutModule(m_sModuleName, ((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - File closed prematurely.");
Close();
return;
}
if (GetInternalWriteBuffer().size() > 1024 * 1024) {
// There is still enough data to be written, don't add more
// stuff to that buffer.
DEBUG("SendPacket(): Skipping send, buffer still full enough [" << GetInternalWriteBuffer().size() << "]["
<< m_sRemoteNick << "][" << m_sFileName << "]");
return;
}
char szBuf[4096];
int iLen = m_pFile->Read(szBuf, 4096);
if (iLen < 0) {
m_pUser->PutModule(m_sModuleName, ((m_bSend) ? "DCC -> [" : "DCC <- [") + m_sRemoteNick + "][" + m_sFileName + "] - Error reading from file.");
Close();
return;
}
if (iLen > 0) {
Write(szBuf, iLen);
m_uBytesSoFar += iLen;
}
}
Csock* CDCCSock::GetSockObj(const CString& sHost, unsigned short uPort) {
Close();
CDCCSock* pSock = new CDCCSock(m_pUser, m_sRemoteNick, m_sLocalFile, m_sModuleName, m_uFileSize, m_pFile);
pSock->SetSockName("DCC::SEND::" + m_sRemoteNick);
pSock->SetTimeout(120);
pSock->SetFileName(m_sFileName);
pSock->SetFileOffset(m_uBytesSoFar);
m_bNoDelFile = true;
return pSock;
}
CFile* CDCCSock::OpenFile(bool bWrite) {
if ((m_pFile) || (m_sLocalFile.empty())) {
m_pUser->PutModule(m_sModuleName, ((bWrite) ? "DCC <- [" : "DCC -> [") + m_sRemoteNick + "][" + m_sLocalFile + "] - Unable to open file.");
return NULL;
}
m_pFile = new CFile(m_sLocalFile);
if (bWrite) {
if (m_pFile->Exists()) {
delete m_pFile;
m_pFile = NULL;
m_pUser->PutModule(m_sModuleName, "DCC <- [" + m_sRemoteNick + "] - File already exists [" + m_sLocalFile + "]");
return NULL;
}
if (!m_pFile->Open(O_WRONLY | O_TRUNC | O_CREAT)) {
delete m_pFile;
m_pFile = NULL;
m_pUser->PutModule(m_sModuleName, "DCC <- [" + m_sRemoteNick + "] - Could not open file [" + m_sLocalFile + "]");
return NULL;
}
} else {
if (!m_pFile->IsReg()) {
delete m_pFile;
m_pFile = NULL;
m_pUser->PutModule(m_sModuleName, "DCC -> [" + m_sRemoteNick + "] - Not a file [" + m_sLocalFile + "]");
return NULL;
}
if (!m_pFile->Open()) {
delete m_pFile;
m_pFile = NULL;
m_pUser->PutModule(m_sModuleName, "DCC -> [" + m_sRemoteNick + "] - Could not open file [" + m_sLocalFile + "]");
return NULL;
}
// The DCC specs only allow file transfers with files smaller
// than 4GiB (see ReadData()).
off_t uFileSize = m_pFile->GetSize();
if (uFileSize > 0xffffffff) {
delete m_pFile;
m_pFile = NULL;
m_pUser->PutModule(m_sModuleName, "DCC -> [" + m_sRemoteNick + "] - File too large (>4 GiB) [" + m_sLocalFile + "]");
return NULL;
}
m_uFileSize = (unsigned long) uFileSize;
}
m_sFileName = m_pFile->GetShortName();
return m_pFile;
}
<|endoftext|> |
<commit_before>/*
* DataSet.cpp
*
* Copyright (c) 2012 Tsukasa OMOTO <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/* This file is available under an MIT license. */
#include "DataSet.hpp"
/**
* Constructor
*
* Load DataSet
*
* @param const char *dataset DataSet's filename
*/
DataSet::DataSet(const char *dataset)
:M(0), V(0), N(0)
{
loadDataSet(dataset);
}
/**
* Constructor
*
* Load DataSet and Vocabulary
*
* @param const char *dataset DataSet's filename
* @param const char *vocab Vocabulary's filename
*/
DataSet::DataSet(const char *dataset, const char *vocab)
:M(0), V(0), N(0)
{
loadDataSet(dataset);
loadVocabulary(vocab);
}
/**
* Load a file and Initialize variables
*
* @param const char *filename open *filename
*/
void DataSet::loadDataSet(const char *filename) {
std::ifstream fin(filename);
if (!fin) {
std::cerr << "Can't open the file: " << filename << std::endl;
exit(1);
}
// the 1st line : the number of docs
fin >> M;
docs.resize(M);
n_m.resize(M, 0);
// the 2nd line : the number of vocabulary
fin >> V;
// the 3rd line : the number of words
fin >> N;
// the following lines : docID vocab wordID count
int m, v, cnt;
while ( fin >> m >> v >> cnt ) {
for (int i = 0; i < cnt; i++) {
docs[m-1].push_back(v);
n_m[m-1]++;
}
}
fin.close();
}
/**
* Loac Vocabulary
*
* @param const char *filename open *filename
*/
void DataSet::loadVocabulary(const char *filename) {
std::ifstream fin(filename);
if (!fin) {
std::cerr << "Can't open the file: " << filename << std::endl;
exit(1);
}
std::string buff;
while ( fin >> buff ) {
vocab.push_back(buff);
}
fin.close();
}
<commit_msg>Fix comment.<commit_after>/*
* DataSet.cpp
*
* Copyright (c) 2012 Tsukasa OMOTO <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/* This file is available under an MIT license. */
#include "DataSet.hpp"
/**
* Constructor
*
* Load DataSet
*
* @param const char *dataset DataSet's filename
*/
DataSet::DataSet(const char *dataset)
:M(0), V(0), N(0)
{
loadDataSet(dataset);
}
/**
* Constructor
*
* Load DataSet and Vocabulary
*
* @param const char *dataset DataSet's filename
* @param const char *vocab Vocabulary's filename
*/
DataSet::DataSet(const char *dataset, const char *vocab)
:M(0), V(0), N(0)
{
loadDataSet(dataset);
loadVocabulary(vocab);
}
/**
* Load a file and Initialize variables
*
* @param const char *filename open *filename
*/
void DataSet::loadDataSet(const char *filename) {
std::ifstream fin(filename);
if (!fin) {
std::cerr << "Can't open the file: " << filename << std::endl;
exit(1);
}
// the 1st line : the number of docs
fin >> M;
docs.resize(M);
n_m.resize(M, 0);
// the 2nd line : the number of vocabulary
fin >> V;
// the 3rd line : the number of words
fin >> N;
// the following lines : docID wordID count
int m, v, cnt;
while ( fin >> m >> v >> cnt ) {
for (int i = 0; i < cnt; i++) {
docs[m-1].push_back(v);
n_m[m-1]++;
}
}
fin.close();
}
/**
* Loac Vocabulary
*
* @param const char *filename open *filename
*/
void DataSet::loadVocabulary(const char *filename) {
std::ifstream fin(filename);
if (!fin) {
std::cerr << "Can't open the file: " << filename << std::endl;
exit(1);
}
std::string buff;
while ( fin >> buff ) {
vocab.push_back(buff);
}
fin.close();
}
<|endoftext|> |
<commit_before>/*
Emon.cpp - Library for openenergymonitor
Created by Trystan Lea, April 27 2010
GNU GPL
*/
//#include "WProgram.h" un-comment for use on older versions of Arduino IDE
#include "EmonLib.h"
#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
//--------------------------------------------------------------------------------------
// Sets the pins to be used for voltage and current sensors
//--------------------------------------------------------------------------------------
void EnergyMonitor::voltage(int _inPinV, double _VCAL, double _PHASECAL)
{
inPinV = _inPinV;
VCAL = _VCAL;
PHASECAL = _PHASECAL;
}
void EnergyMonitor::current(int _inPinI, double _ICAL)
{
inPinI = _inPinI;
ICAL = _ICAL;
}
//--------------------------------------------------------------------------------------
// Sets the pins to be used for voltage and current sensors based on emontx pin map
//--------------------------------------------------------------------------------------
void EnergyMonitor::voltageTX(double _VCAL, double _PHASECAL)
{
inPinV = 2;
VCAL = _VCAL;
PHASECAL = _PHASECAL;
}
void EnergyMonitor::currentTX(int _channel, double _ICAL)
{
if (_channel == 1) inPinI = 3;
if (_channel == 2) inPinI = 0;
if (_channel == 3) inPinI = 1;
ICAL = _ICAL;
}
//--------------------------------------------------------------------------------------
// emon_calc procedure
// Calculates realPower,apparentPower,powerFactor,Vrms,Irms,kwh increment
// From a sample window of the mains AC voltage and current.
// The Sample window length is defined by the number of half wavelengths or crossings we choose to measure.
//--------------------------------------------------------------------------------------
void EnergyMonitor::calcVI(int crossings, int timeout)
{
int SUPPLYVOLTAGE = readVcc();
int crossCount = 0; //Used to measure number of times threshold is crossed.
int numberOfSamples = 0; //This is now incremented
//-------------------------------------------------------------------------------------------------------------------------
// 1) Waits for the waveform to be close to 'zero' (500 adc) part in sin curve.
//-------------------------------------------------------------------------------------------------------------------------
boolean st=false; //an indicator to exit the while loop
unsigned long start = millis(); //millis()-start makes sure it doesnt get stuck in the loop if there is an error.
while(st==false) //the while loop...
{
startV = analogRead(inPinV); //using the voltage waveform
if ((startV < 550) && (startV > 440)) st=true; //check its within range
if ((millis()-start)>timeout) st = true;
}
//-------------------------------------------------------------------------------------------------------------------------
// 2) Main measurment loop
//-------------------------------------------------------------------------------------------------------------------------
start = millis();
while ((crossCount < crossings) && ((millis()-start)<timeout))
{
numberOfSamples++; //Count number of times looped.
lastSampleV=sampleV; //Used for digital high pass filter
lastSampleI=sampleI; //Used for digital high pass filter
lastFilteredV = filteredV; //Used for offset removal
lastFilteredI = filteredI; //Used for offset removal
//-----------------------------------------------------------------------------
// A) Read in raw voltage and current samples
//-----------------------------------------------------------------------------
sampleV = analogRead(inPinV); //Read in raw voltage signal
sampleI = analogRead(inPinI); //Read in raw current signal
//-----------------------------------------------------------------------------
// B) Apply digital high pass filters to remove 2.5V DC offset (centered on 0V).
//-----------------------------------------------------------------------------
filteredV = 0.996*(lastFilteredV+sampleV-lastSampleV);
filteredI = 0.996*(lastFilteredI+sampleI-lastSampleI);
//-----------------------------------------------------------------------------
// C) Root-mean-square method voltage
//-----------------------------------------------------------------------------
sqV= filteredV * filteredV; //1) square voltage values
sumV += sqV; //2) sum
//-----------------------------------------------------------------------------
// D) Root-mean-square method current
//-----------------------------------------------------------------------------
sqI = filteredI * filteredI; //1) square current values
sumI += sqI; //2) sum
//-----------------------------------------------------------------------------
// E) Phase calibration
//-----------------------------------------------------------------------------
phaseShiftedV = lastFilteredV + PHASECAL * (filteredV - lastFilteredV);
//-----------------------------------------------------------------------------
// F) Instantaneous power calc
//-----------------------------------------------------------------------------
instP = phaseShiftedV * filteredI; //Instantaneous Power
sumP +=instP; //Sum
//-----------------------------------------------------------------------------
// G) Find the number of times the voltage has crossed the initial voltage
// - every 2 crosses we will have sampled 1 wavelength
// - so this method allows us to sample an integer number of half wavelengths which increases accuracy
//-----------------------------------------------------------------------------
lastVCross = checkVCross;
if (sampleV > startV) checkVCross = true;
else checkVCross = false;
if (numberOfSamples==1) lastVCross = checkVCross;
if (lastVCross != checkVCross) crossCount++;
}
//-------------------------------------------------------------------------------------------------------------------------
// 3) Post loop calculations
//-------------------------------------------------------------------------------------------------------------------------
//Calculation of the root of the mean of the voltage and current squared (rms)
//Calibration coeficients applied.
double V_RATIO = VCAL *((SUPPLYVOLTAGE/1000.0) / 1023.0);
Vrms = V_RATIO * sqrt(sumV / numberOfSamples);
double I_RATIO = ICAL *((SUPPLYVOLTAGE/1000.0) / 1023.0);
Irms = I_RATIO * sqrt(sumI / numberOfSamples);
//Calculation power values
realPower = V_RATIO * I_RATIO * sumP / numberOfSamples;
apparentPower = Vrms * Irms;
powerFactor=realPower / apparentPower;
//Reset accumulators
sumV = 0;
sumI = 0;
sumP = 0;
//--------------------------------------------------------------------------------------
}
//--------------------------------------------------------------------------------------
double EnergyMonitor::calcIrms(int NUMBER_OF_SAMPLES)
{
int SUPPLYVOLTAGE = readVcc();
for (int n = 0; n < NUMBER_OF_SAMPLES; n++)
{
lastSampleI = sampleI;
sampleI = analogRead(inPinI);
lastFilteredI = filteredI;
filteredI = 0.996*(lastFilteredI+sampleI-lastSampleI);
// Root-mean-square method current
// 1) square current values
sqI = filteredI * filteredI;
// 2) sum
sumI += sqI;
}
double I_RATIO = ICAL *((SUPPLYVOLTAGE/1000.0) / 1023.0);
Irms = I_RATIO * sqrt(sumI / NUMBER_OF_SAMPLES);
//Reset accumulators
sumI = 0;
//--------------------------------------------------------------------------------------
return Irms;
}
void EnergyMonitor::serialprint()
{
Serial.print(realPower);
Serial.print(' ');
Serial.print(apparentPower);
Serial.print(' ');
Serial.print(Vrms);
Serial.print(' ');
Serial.print(Irms);
Serial.print(' ');
Serial.print(powerFactor);
Serial.println(' ');
delay(100);
}
//thanks to http://hacking.majenko.co.uk/making-accurate-adc-readings-on-arduino
//and Jérôme who alerted us to http://provideyourown.com/2012/secret-arduino-voltmeter-measure-battery-voltage/
long EnergyMonitor::readVcc() {
long result;
#if defined(__AVR_ATmega168__) || defined(__AVR_ATmega328__)
ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
#elif defined(__AVR_ATmega32U4__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
ADMUX = _BV(REFS0) | _BV(MUX4) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
#elif defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
ADMUX = _BV(MUX5) | _BV(MUX0);
#elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
#endif
delay(2); // Wait for Vref to settle
ADCSRA |= _BV(ADSC); // Convert
while (bit_is_set(ADCSRA,ADSC));
result = ADCL;
result |= ADCH<<8;
result = 1126400L / result; //1100mV*1024 ADC steps http://openenergymonitor.org/emon/node/1186
return result;
}
<commit_msg>correct missing #elif define for ATtiny85<commit_after>/*
Emon.cpp - Library for openenergymonitor
Created by Trystan Lea, April 27 2010
GNU GPL
*/
//#include "WProgram.h" un-comment for use on older versions of Arduino IDE
#include "EmonLib.h"
#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
//--------------------------------------------------------------------------------------
// Sets the pins to be used for voltage and current sensors
//--------------------------------------------------------------------------------------
void EnergyMonitor::voltage(int _inPinV, double _VCAL, double _PHASECAL)
{
inPinV = _inPinV;
VCAL = _VCAL;
PHASECAL = _PHASECAL;
}
void EnergyMonitor::current(int _inPinI, double _ICAL)
{
inPinI = _inPinI;
ICAL = _ICAL;
}
//--------------------------------------------------------------------------------------
// Sets the pins to be used for voltage and current sensors based on emontx pin map
//--------------------------------------------------------------------------------------
void EnergyMonitor::voltageTX(double _VCAL, double _PHASECAL)
{
inPinV = 2;
VCAL = _VCAL;
PHASECAL = _PHASECAL;
}
void EnergyMonitor::currentTX(int _channel, double _ICAL)
{
if (_channel == 1) inPinI = 3;
if (_channel == 2) inPinI = 0;
if (_channel == 3) inPinI = 1;
ICAL = _ICAL;
}
//--------------------------------------------------------------------------------------
// emon_calc procedure
// Calculates realPower,apparentPower,powerFactor,Vrms,Irms,kwh increment
// From a sample window of the mains AC voltage and current.
// The Sample window length is defined by the number of half wavelengths or crossings we choose to measure.
//--------------------------------------------------------------------------------------
void EnergyMonitor::calcVI(int crossings, int timeout)
{
int SUPPLYVOLTAGE = readVcc();
int crossCount = 0; //Used to measure number of times threshold is crossed.
int numberOfSamples = 0; //This is now incremented
//-------------------------------------------------------------------------------------------------------------------------
// 1) Waits for the waveform to be close to 'zero' (500 adc) part in sin curve.
//-------------------------------------------------------------------------------------------------------------------------
boolean st=false; //an indicator to exit the while loop
unsigned long start = millis(); //millis()-start makes sure it doesnt get stuck in the loop if there is an error.
while(st==false) //the while loop...
{
startV = analogRead(inPinV); //using the voltage waveform
if ((startV < 550) && (startV > 440)) st=true; //check its within range
if ((millis()-start)>timeout) st = true;
}
//-------------------------------------------------------------------------------------------------------------------------
// 2) Main measurment loop
//-------------------------------------------------------------------------------------------------------------------------
start = millis();
while ((crossCount < crossings) && ((millis()-start)<timeout))
{
numberOfSamples++; //Count number of times looped.
lastSampleV=sampleV; //Used for digital high pass filter
lastSampleI=sampleI; //Used for digital high pass filter
lastFilteredV = filteredV; //Used for offset removal
lastFilteredI = filteredI; //Used for offset removal
//-----------------------------------------------------------------------------
// A) Read in raw voltage and current samples
//-----------------------------------------------------------------------------
sampleV = analogRead(inPinV); //Read in raw voltage signal
sampleI = analogRead(inPinI); //Read in raw current signal
//-----------------------------------------------------------------------------
// B) Apply digital high pass filters to remove 2.5V DC offset (centered on 0V).
//-----------------------------------------------------------------------------
filteredV = 0.996*(lastFilteredV+sampleV-lastSampleV);
filteredI = 0.996*(lastFilteredI+sampleI-lastSampleI);
//-----------------------------------------------------------------------------
// C) Root-mean-square method voltage
//-----------------------------------------------------------------------------
sqV= filteredV * filteredV; //1) square voltage values
sumV += sqV; //2) sum
//-----------------------------------------------------------------------------
// D) Root-mean-square method current
//-----------------------------------------------------------------------------
sqI = filteredI * filteredI; //1) square current values
sumI += sqI; //2) sum
//-----------------------------------------------------------------------------
// E) Phase calibration
//-----------------------------------------------------------------------------
phaseShiftedV = lastFilteredV + PHASECAL * (filteredV - lastFilteredV);
//-----------------------------------------------------------------------------
// F) Instantaneous power calc
//-----------------------------------------------------------------------------
instP = phaseShiftedV * filteredI; //Instantaneous Power
sumP +=instP; //Sum
//-----------------------------------------------------------------------------
// G) Find the number of times the voltage has crossed the initial voltage
// - every 2 crosses we will have sampled 1 wavelength
// - so this method allows us to sample an integer number of half wavelengths which increases accuracy
//-----------------------------------------------------------------------------
lastVCross = checkVCross;
if (sampleV > startV) checkVCross = true;
else checkVCross = false;
if (numberOfSamples==1) lastVCross = checkVCross;
if (lastVCross != checkVCross) crossCount++;
}
//-------------------------------------------------------------------------------------------------------------------------
// 3) Post loop calculations
//-------------------------------------------------------------------------------------------------------------------------
//Calculation of the root of the mean of the voltage and current squared (rms)
//Calibration coeficients applied.
double V_RATIO = VCAL *((SUPPLYVOLTAGE/1000.0) / 1023.0);
Vrms = V_RATIO * sqrt(sumV / numberOfSamples);
double I_RATIO = ICAL *((SUPPLYVOLTAGE/1000.0) / 1023.0);
Irms = I_RATIO * sqrt(sumI / numberOfSamples);
//Calculation power values
realPower = V_RATIO * I_RATIO * sumP / numberOfSamples;
apparentPower = Vrms * Irms;
powerFactor=realPower / apparentPower;
//Reset accumulators
sumV = 0;
sumI = 0;
sumP = 0;
//--------------------------------------------------------------------------------------
}
//--------------------------------------------------------------------------------------
double EnergyMonitor::calcIrms(int NUMBER_OF_SAMPLES)
{
int SUPPLYVOLTAGE = readVcc();
for (int n = 0; n < NUMBER_OF_SAMPLES; n++)
{
lastSampleI = sampleI;
sampleI = analogRead(inPinI);
lastFilteredI = filteredI;
filteredI = 0.996*(lastFilteredI+sampleI-lastSampleI);
// Root-mean-square method current
// 1) square current values
sqI = filteredI * filteredI;
// 2) sum
sumI += sqI;
}
double I_RATIO = ICAL *((SUPPLYVOLTAGE/1000.0) / 1023.0);
Irms = I_RATIO * sqrt(sumI / NUMBER_OF_SAMPLES);
//Reset accumulators
sumI = 0;
//--------------------------------------------------------------------------------------
return Irms;
}
void EnergyMonitor::serialprint()
{
Serial.print(realPower);
Serial.print(' ');
Serial.print(apparentPower);
Serial.print(' ');
Serial.print(Vrms);
Serial.print(' ');
Serial.print(Irms);
Serial.print(' ');
Serial.print(powerFactor);
Serial.println(' ');
delay(100);
}
//thanks to http://hacking.majenko.co.uk/making-accurate-adc-readings-on-arduino
//and Jérôme who alerted us to http://provideyourown.com/2012/secret-arduino-voltmeter-measure-battery-voltage/
long EnergyMonitor::readVcc() {
long result;
#if defined(__AVR_ATmega168__) || defined(__AVR_ATmega328__)
ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
#elif defined(__AVR_ATmega32U4__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
ADMUX = _BV(REFS0) | _BV(MUX4) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
#elif defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
ADMUX = _BV(MUX5) | _BV(MUX0);
#elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
ADMUX = _BV(MUX3) | _BV(MUX2);
#endif
delay(2); // Wait for Vref to settle
ADCSRA |= _BV(ADSC); // Convert
while (bit_is_set(ADCSRA,ADSC));
result = ADCL;
result |= ADCH<<8;
result = 1126400L / result; //1100mV*1024 ADC steps http://openenergymonitor.org/emon/node/1186
return result;
}
<|endoftext|> |
<commit_before>#include "FATData.h"
#include <fstream>
#include <iostream>
#include <sys/stat.h>
using namespace std;
FATData::FATData(const char* mount)
{
uint8_t* BPB = new uint8_t[BPB_SIZE];
unsigned int FATSz;
unsigned int ROOTSz;
ifstream imageFile(mount, ios::in | ios::binary);
imageFile.read((char*)BPB, BPB_SIZE);
bytesPerSector = bytesToUnsigned(&BPB[BPB_BYTES_PER_SEC_OFFSET], BPB_BYTES_PER_SEC_SIZE);
sectorsPerCluster = bytesToUnsigned(&BPB[BPB_SEC_PER_CLUS_OFFSET], BPB_SEC_PER_CLUS_SIZE);
reservedSectorCount = bytesToUnsigned(&BPB[BPB_RSVD_SEC_CNT_OFFSET], BPB_RSVD_SEC_CNT_SIZE);
rootEntityCount = bytesToUnsigned(&BPB[BPB_ROOT_ENT_CNT_OFFSET], BPB_ROOT_ENT_CNT_SIZE);
totalSectors16 = bytesToUnsigned(&BPB[BPB_TOT_SEC_16_OFFSET],BPB_TOT_SEC_16_SIZE);
FATSz16 = bytesToUnsigned(&BPB[BPB_FAT_SZ16_OFFSET], BPB_FAT_SZ16_SIZE);
totalSectors32 = bytesToUnsigned(&BPB[BPB_TOT_SEC_32_OFFSET],BPB_TOT_SEC_32_SIZE);
FATSz = BPB_NUM_FATS * FATSz16;
ROOTSz = rootEntityCount * ROOT_ENT_SZ;
FAT = new uint8_t[FATSz];
ROOT = new uint8_t[ROOTSz];
imageFile.read((char*)FAT, FATSz);
imageFile.read((char*)ROOT, ROOTSz);
imageFile.close();
delete BPB;
}//FATData constructor
FATData::~FATData()
{
}//FATData destructor
unsigned int FATData::getBytesPerSector()
{
return bytesPerSector;
}//unsigned int FATData::getBytesPerSector()
void FATData::fatls()
{
cout << " DATE | TIME | TYPE | SIZE | SFN | LFN\n";
}//void FATData::fatls()
//***************************************************************************//
// Begin Utility Functions for FATData //
//***************************************************************************//
unsigned int bytesToUnsigned(uint8_t* start, unsigned int size)
{
unsigned int accum = 0;
for (unsigned int i = 0 ; i < size ; i++)
{
accum += ((unsigned int)start[i]) << (8 * i);
}
return accum;
}//unsigned int bytesToUnsigned(uint8_t* start, size)
<commit_msg>divided by 512<commit_after>#include "FATData.h"
#include <fstream>
#include <iostream>
#include <sys/stat.h>
using namespace std;
FATData::FATData(const char* mount)
{
uint8_t* BPB = new uint8_t[BPB_SIZE];
unsigned int FATSz;
unsigned int ROOTSz;
ifstream imageFile(mount, ios::in | ios::binary);
imageFile.read((char*)BPB, BPB_SIZE);
bytesPerSector = bytesToUnsigned(&BPB[BPB_BYTES_PER_SEC_OFFSET], BPB_BYTES_PER_SEC_SIZE);
sectorsPerCluster = bytesToUnsigned(&BPB[BPB_SEC_PER_CLUS_OFFSET], BPB_SEC_PER_CLUS_SIZE);
reservedSectorCount = bytesToUnsigned(&BPB[BPB_RSVD_SEC_CNT_OFFSET], BPB_RSVD_SEC_CNT_SIZE);
rootEntityCount = bytesToUnsigned(&BPB[BPB_ROOT_ENT_CNT_OFFSET], BPB_ROOT_ENT_CNT_SIZE);
totalSectors16 = bytesToUnsigned(&BPB[BPB_TOT_SEC_16_OFFSET],BPB_TOT_SEC_16_SIZE);
FATSz16 = bytesToUnsigned(&BPB[BPB_FAT_SZ16_OFFSET], BPB_FAT_SZ16_SIZE);
totalSectors32 = bytesToUnsigned(&BPB[BPB_TOT_SEC_32_OFFSET],BPB_TOT_SEC_32_SIZE);
FATSz = BPB_NUM_FATS * FATSz16;
ROOTSz = rootEntityCount * ROOT_ENT_SZ / 512; //Dividing by 512 is black magic from a handout
FAT = new uint8_t[FATSz];
ROOT = new uint8_t[ROOTSz];
imageFile.read((char*)FAT, FATSz);
imageFile.read((char*)ROOT, ROOTSz);
imageFile.close();
delete BPB;
}//FATData constructor
FATData::~FATData()
{
}//FATData destructor
unsigned int FATData::getBytesPerSector()
{
return bytesPerSector;
}//unsigned int FATData::getBytesPerSector()
void FATData::fatls()
{
cout << " DATE | TIME | TYPE | SIZE | SFN | LFN\n";
}//void FATData::fatls()
//***************************************************************************//
// Begin Utility Functions for FATData //
//***************************************************************************//
unsigned int bytesToUnsigned(uint8_t* start, unsigned int size)
{
unsigned int accum = 0;
for (unsigned int i = 0 ; i < size ; i++)
{
accum += ((unsigned int)start[i]) << (8 * i);
}
return accum;
}//unsigned int bytesToUnsigned(uint8_t* start, size)
<|endoftext|> |
<commit_before>#include "player.h"
#include "json.h"
#include <iostream>
#include <cstdlib>
const char* Player::VERSION = "Default C++ player";
int Player::betRequest(json::Value game_state)
{
std::cerr<<json::Serialize(game_state)<<std::endl;
std::string s = json::Serialize(game_state);
std::string delimiter = "},{";
std::string token;
size_t pos = 0;
while ((pos = s.find(delimiter)) != std::string::npos) {
token = s.substr(0,pos);
std::cerr << token << std::endl;
s.erase(0, pos + delimiter.length());
}
return 100;
}
void Player::showdown(json::Value game_state)
{
}
<commit_msg>add try catch<commit_after>#include "player.h"
#include "json.h"
#include <iostream>
#include <cstdlib>
const char* Player::VERSION = "Default C++ player";
int Player::betRequest(json::Value game_state)
{
try {
std::cerr<<json::Serialize(game_state)<<std::endl;
std::string s = json::Serialize(game_state);
std::string delimiter = "},{";
std::string token;
size_t pos = 0;
while ((pos = s.find(delimiter)) != std::string::npos) {
token = s.substr(0,pos);
std::cerr << token << std::endl;
s.erase(0, pos + delimiter.length());
}
return 100;
} catch(const std::exception& e) {
// in case it crashes
return 100;
}
}
void Player::showdown(json::Value game_state)
{
}
<|endoftext|> |
<commit_before>#include "Clipper.h"
#include <algorithm>
#include <functional>
// Calculates the intersection point of a line segment lb->la which crosses the
// plane with normal 'n'.
static bool RayPlaneIntersection(const FLOATVECTOR3 &la,
const FLOATVECTOR3 &lb,
const FLOATVECTOR3 &n, const float D,
FLOATVECTOR3 &hit)
{
const float denom = n ^ (la - lb);
if(EpsilonEqual(denom, 0.0f)) {
return false;
}
const float t = ((n ^ la) + D) / denom;
hit = la + (t*(lb - la));
return true;
}
// Splits a triangle along a plane with the given normal.
// Assumes: plane's D == 0.
// triangle does span the plane.
void SplitTriangle(FLOATVECTOR3 a,
FLOATVECTOR3 b,
FLOATVECTOR3 c,
float fa,
float fb,
float fc,
const FLOATVECTOR3 &normal,
const float D,
std::vector<FLOATVECTOR3>& out,
std::vector<FLOATVECTOR3>& newVerts)
{
// rotation / mirroring.
// c
// o Push `c' to be alone on one side of the plane, making
// / \ `a' and `b' on the other. Later we'll be able to
// plane --------- assume that there will be an intersection with the
// / \ clip plane along the lines `ac' and `bc'. This
// o-------o reduces the number of cases below.
// a b
// if fa*fc is non-negative, both have the same sign -- and thus are on the
// same side of the plane.
if(fa*fc >= 0) {
std::swap(fb, fc);
std::swap(b, c);
std::swap(fa, fb);
std::swap(a, b);
} else if(fb*fc >= 0) {
std::swap(fa, fc);
std::swap(a, c);
std::swap(fa, fb);
std::swap(a, b);
}
// Find the intersection points.
FLOATVECTOR3 A, B;
RayPlaneIntersection(a,c, normal,D, A);
RayPlaneIntersection(b,c, normal,D, B);
if(fc >= 0) {
out.push_back(a); out.push_back(b); out.push_back(A);
out.push_back(b); out.push_back(B); out.push_back(A);
} else {
out.push_back(A); out.push_back(B); out.push_back(c);
}
newVerts.push_back(A);
newVerts.push_back(B);
}
std::vector<FLOATVECTOR3> Clipper::TriPlane(std::vector<FLOATVECTOR3>& posData, const FLOATVECTOR3 &normal, const float D) {
std::vector<FLOATVECTOR3> newVertices;
std::vector<FLOATVECTOR3> out;
if (posData.size() % 3 != 0) return newVertices;
for(auto iter = posData.begin(); iter < (posData.end()-2); iter += 3) {
const FLOATVECTOR3 &a = (*iter);
const FLOATVECTOR3 &b = (*(iter+1));
const FLOATVECTOR3 &c = (*(iter+2));
float fa = (normal ^ a) + D;
float fb = (normal ^ b) + D;
float fc = (normal ^ c) + D;
if(fabs(fa) < (2 * std::numeric_limits<float>::epsilon())) { fa = 0; }
if(fabs(fb) < (2 * std::numeric_limits<float>::epsilon())) { fb = 0; }
if(fabs(fc) < (2 * std::numeric_limits<float>::epsilon())) { fc = 0; }
if(fa >= 0 && fb >= 0 && fc >= 0) { // trivial reject
// discard -- i.e. do nothing / ignore tri.
continue;
} else if(fa <= 0 && fb <= 0 && fc <= 0) { // trivial accept
out.push_back(a);
out.push_back(b);
out.push_back(c);
} else { // triangle spans plane -- must be split.
std::vector<FLOATVECTOR3> tris, newVerts;
SplitTriangle(a,b,c, fa,fb,fc,normal,D, tris, newVerts);
// append triangles and vertices to lists
out.insert(out.end(), tris.begin(), tris. end());
newVertices.insert(newVertices.end(), newVerts.begin(), newVerts. end());
}
}
posData = out;
return newVertices;
}
struct {
bool operator() (const FLOATVECTOR3& i, const FLOATVECTOR3& j) {
return i.x < j.x || (i.x == j.x && i.y < j.y) || (i.x == j.x && i.y == j.y && i.z < j.z);
}
} CompSorter;
static bool AngleSorter(const FLOATVECTOR3& i, const FLOATVECTOR3& j, const FLOATVECTOR3& center, const FLOATVECTOR3& refVec, const FLOATVECTOR3& normal) {
FLOATVECTOR3 vecI = (i-center).normalized();
float cosI = refVec ^ vecI;
float sinI = (vecI % refVec)^ normal;
FLOATVECTOR3 vecJ = (j-center).normalized();
float cosJ = refVec ^ vecJ;
float sinJ = (vecJ % refVec) ^ normal;
float acI = atan2(sinI, cosI);
float acJ = atan2(sinJ, cosJ);
return acI > acJ;
}
void Clipper::BoxPlane(std::vector<FLOATVECTOR3>& posData, const FLOATVECTOR3 &normal, const float D) {
std::vector<FLOATVECTOR3> newVertices = Clipper::TriPlane(posData, normal, D);
if (newVertices.size() < 3) return;
// remove duplicate vertices
std::sort(newVertices.begin(), newVertices.end(), CompSorter);
newVertices.erase(std::unique(newVertices.begin(), newVertices.end()), newVertices.end());
// sort counter clockwise
using namespace std::placeholders;
FLOATVECTOR3 center;
for (auto vertex = newVertices.begin();vertex<newVertices.end();++vertex) {
center += *vertex;
}
center /= float(newVertices.size());
std::sort(newVertices.begin(), newVertices.end(), std::bind(AngleSorter, _1, _2, center, (newVertices[0]-center).normalized(), normal ));
// create a triangle fan with the newly created vertices to close the polytope
for (auto vertex = newVertices.begin()+2;vertex<newVertices.end();++vertex) {
posData.push_back(newVertices[0]);
posData.push_back(*(vertex-1));
posData.push_back(*(vertex));
}
}
/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2012 Interactive Visualization and Data Analysis Group.
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.
*/
<commit_msg>Fix sorting code.<commit_after>#include "Clipper.h"
#include <algorithm>
#include <functional>
// Calculates the intersection point of a line segment lb->la which crosses the
// plane with normal 'n'.
static bool RayPlaneIntersection(const FLOATVECTOR3 &la,
const FLOATVECTOR3 &lb,
const FLOATVECTOR3 &n, const float D,
FLOATVECTOR3 &hit)
{
const float denom = n ^ (la - lb);
if(EpsilonEqual(denom, 0.0f)) {
return false;
}
const float t = ((n ^ la) + D) / denom;
hit = la + (t*(lb - la));
return true;
}
// Splits a triangle along a plane with the given normal.
// Assumes: plane's D == 0.
// triangle does span the plane.
void SplitTriangle(FLOATVECTOR3 a,
FLOATVECTOR3 b,
FLOATVECTOR3 c,
float fa,
float fb,
float fc,
const FLOATVECTOR3 &normal,
const float D,
std::vector<FLOATVECTOR3>& out,
std::vector<FLOATVECTOR3>& newVerts)
{
// rotation / mirroring.
// c
// o Push `c' to be alone on one side of the plane, making
// / \ `a' and `b' on the other. Later we'll be able to
// plane --------- assume that there will be an intersection with the
// / \ clip plane along the lines `ac' and `bc'. This
// o-------o reduces the number of cases below.
// a b
// if fa*fc is non-negative, both have the same sign -- and thus are on the
// same side of the plane.
if(fa*fc >= 0) {
std::swap(fb, fc);
std::swap(b, c);
std::swap(fa, fb);
std::swap(a, b);
} else if(fb*fc >= 0) {
std::swap(fa, fc);
std::swap(a, c);
std::swap(fa, fb);
std::swap(a, b);
}
// Find the intersection points.
FLOATVECTOR3 A, B;
RayPlaneIntersection(a,c, normal,D, A);
RayPlaneIntersection(b,c, normal,D, B);
if(fc >= 0) {
out.push_back(a); out.push_back(b); out.push_back(A);
out.push_back(b); out.push_back(B); out.push_back(A);
} else {
out.push_back(A); out.push_back(B); out.push_back(c);
}
newVerts.push_back(A);
newVerts.push_back(B);
}
std::vector<FLOATVECTOR3> Clipper::TriPlane(std::vector<FLOATVECTOR3>& posData, const FLOATVECTOR3 &normal, const float D) {
std::vector<FLOATVECTOR3> newVertices;
std::vector<FLOATVECTOR3> out;
if (posData.size() % 3 != 0) return newVertices;
for(auto iter = posData.begin(); iter < (posData.end()-2); iter += 3) {
const FLOATVECTOR3 &a = (*iter);
const FLOATVECTOR3 &b = (*(iter+1));
const FLOATVECTOR3 &c = (*(iter+2));
float fa = (normal ^ a) + D;
float fb = (normal ^ b) + D;
float fc = (normal ^ c) + D;
if(fabs(fa) < (2 * std::numeric_limits<float>::epsilon())) { fa = 0; }
if(fabs(fb) < (2 * std::numeric_limits<float>::epsilon())) { fb = 0; }
if(fabs(fc) < (2 * std::numeric_limits<float>::epsilon())) { fc = 0; }
if(fa >= 0 && fb >= 0 && fc >= 0) { // trivial reject
// discard -- i.e. do nothing / ignore tri.
continue;
} else if(fa <= 0 && fb <= 0 && fc <= 0) { // trivial accept
out.push_back(a);
out.push_back(b);
out.push_back(c);
} else { // triangle spans plane -- must be split.
std::vector<FLOATVECTOR3> tris, newVerts;
SplitTriangle(a,b,c, fa,fb,fc,normal,D, tris, newVerts);
// append triangles and vertices to lists
out.insert(out.end(), tris.begin(), tris. end());
newVertices.insert(newVertices.end(), newVerts.begin(), newVerts. end());
}
}
posData = out;
return newVertices;
}
struct CompSorter {
bool operator() (const FLOATVECTOR3& i, const FLOATVECTOR3& j) const {
return i.x < j.x || (i.x == j.x && i.y < j.y) ||
(i.x == j.x && i.y == j.y && i.z < j.z);
}
};
static bool AngleSorter(const FLOATVECTOR3& i, const FLOATVECTOR3& j, const FLOATVECTOR3& center, const FLOATVECTOR3& refVec, const FLOATVECTOR3& normal) {
FLOATVECTOR3 vecI = (i-center).normalized();
float cosI = refVec ^ vecI;
float sinI = (vecI % refVec)^ normal;
FLOATVECTOR3 vecJ = (j-center).normalized();
float cosJ = refVec ^ vecJ;
float sinJ = (vecJ % refVec) ^ normal;
float acI = atan2(sinI, cosI);
float acJ = atan2(sinJ, cosJ);
return acI > acJ;
}
void Clipper::BoxPlane(std::vector<FLOATVECTOR3>& posData, const FLOATVECTOR3 &normal, const float D) {
std::vector<FLOATVECTOR3> newVertices = Clipper::TriPlane(posData, normal, D);
if (newVertices.size() < 3) return;
// remove duplicate vertices
std::sort(newVertices.begin(), newVertices.end(), CompSorter());
newVertices.erase(std::unique(newVertices.begin(), newVertices.end()),
newVertices.end());
// sort counter clockwise
using namespace std::placeholders;
FLOATVECTOR3 center;
for (auto vertex = newVertices.begin();vertex<newVertices.end();++vertex) {
center += *vertex;
}
center /= float(newVertices.size());
std::sort(newVertices.begin(), newVertices.end(), std::bind(AngleSorter, _1, _2, center, (newVertices[0]-center).normalized(), normal ));
// create a triangle fan with the newly created vertices to close the polytope
for (auto vertex = newVertices.begin()+2;vertex<newVertices.end();++vertex) {
posData.push_back(newVertices[0]);
posData.push_back(*(vertex-1));
posData.push_back(*(vertex));
}
}
/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2012 Interactive Visualization and Data Analysis Group.
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.
*/
<|endoftext|> |
<commit_before>#include <DO/Sara/Core/Math/UnivariatePolynomial.hpp>
#include <DO/Sara/Core/Math/NewtonRaphson.hpp>
#include <complex>
#include <ctime>
#include <memory>
namespace DO { namespace Sara {
auto compute_moduli_lower_bound(const UnivariatePolynomial<double>& P)
-> double
{
auto Q = P;
Q[0] = -std::abs(Q[0] / Q[Q.degree()]);
for (int i = 1; i <= Q.degree(); ++i)
Q[i] = std::abs(Q[i] / Q[Q.degree()]);
auto x = 1.;
auto newton_raphson = NewtonRaphson<double>{Q};
x = newton_raphson(x, 50);
return x;
}
auto K1_no_shift_polynomial(const UnivariatePolynomial<double>& K0,
const UnivariatePolynomial<double>& P)
-> UnivariatePolynomial<double>
{
// See stage 1 formula: no-shift process (page 556).
auto K1 = (K0 - (K0(0) / P(0)) * P) / Z;
return K1.first;
}
auto K1_fixed_shift_polynomial(const UnivariatePolynomial<double>& K0,
const UnivariatePolynomial<double>& P,
const UnivariatePolynomial<double>& sigma,
const std::complex<double>& s1,
const std::complex<double>& s2)
-> UnivariatePolynomial<double>
{
return K0[Z] + P[Z]
}
auto K0_(const UnivariatePolynomial<double>& P)
-> UnivariatePolynomial<double>
{
// Write the scaled recurrence formula (page 563).
const auto n = P.degree();
auto K0 = UnivariatePolynomial<double>{n - 1};
for (int i = 0; i < n; ++i)
K0[n - 1 - i] = ((n - i) * P[n - i]) / n;
return K0;
}
auto K1_stage1(const UnivariatePolynomial<double>& K0,
const UnivariatePolynomial<double>& P)
-> UnivariatePolynomial<double>
{
// See stage 1 formula: no-shift process (page 556).
auto K1 = (K0 - (K0(0) / P(0)) * P) / Z;
return K1.first;
}
auto K1_stage2(const UnivariatePolynomial<double>& K0,
const UnivariatePolynomial<double>& P,
const UnivariatePolynomial<double>& sigma,
const std::complex<double>& s1, const std::complex<double>& s2)
-> UnivariatePolynomial<double>
{
return {};
}
//auto K1_stage2(const UnivariatePolynomial<double>& K0,
// const UnivariatePolynomial<double>& P,
// const UnivariatePolynomial<double>& sigma,
// const std::complex<double>& s1, const std::complex<double>& s2)
// -> std::array<double, 6>
//{
// // See stage 2 formula (9.7) (page 563).
// Matrix4cd M;
// Vector4cd y;
// M << 1, -s2, 0, 0,
// 0, 0, 1, -1,
// 1, -s1, 0, 0,
// 0, 0, 1, -s1;
// y << P(s1), P(s2), K0(s1), K0(s2);
// Vector4cd x = M.colPivHouseholderQr().solve(y);
// const auto a = std::real(x[0]);
// const auto b = std::real(x[1]);
// const auto c = std::real(x[2]);
// const auto d = std::real(x[3]);
// const auto u = - std::real(s1 + s2);
// const auto v = - std::real(s1 * s2);
// return {a, b, c, d, u, v};
//}
//auto stage2(const UnivariatePolynomial<double>& K0_,
// const UnivariatePolynomial<double>& P,
// int L = 20) -> double
//{
// const auto beta = compute_moduli_lower_bound(P);
// const auto s1 = beta; //* std::exp(i*rand());
// const auto s2 = std::conj(s1); //* std::exp(i*rand());
// const auto sigma = sigma_(s1);
// auto K0 = K0_;
// auto K1 = K1_stage2(P, K0, sigma, s1, std::conj(s1));
// auto K2 = K1_stage2(P, K1, sigma, s1, std::conj(s1));
// auto K3 = K1_stage2(P, K2, sigma, s1, std::conj(s1));
// auto K4 = K1_stage2(P, K3, sigma, s1, std::conj(s1));
// auto u = std::real(s1 + s2);
// auto t0 = s1 - (a0 - b0 * s2) / (c0 - d0 * s2);
// auto t1 = s1 - (a1 - b1 * s2) / (c1 - d1 * s2);
// auto t2 = s1 - (a2 - b2 * s2) / (c2 - d2 * s2);
// for (int i = 0; i < L; ++i)
// {
// K0 = K1;
// K1 = K2;
// K2 = K1_stage2(P, K1, sigma, s1, std::conj(s1));
// t0 = t1;
// t1 = t2;
// t2 = s1 - P(s1) / K2(s1);
// auto sigma_0 = sigma(K0, K1, K2, s1, s2);
// auto sigma_1 = sigma(K1, K2, K3, s1, s2);
// auto sigma_2 = sigma(K2, K3, K4, s1, s2);
// const auto v0 = sigma_0[0];
// const auto v1 = sigma_1[0];
// const auto v2 = sigma_2[0];
// // Convergence to rho_1?
// if (std::abs(t1 - t0) <= 0.5 * t0 && std::abs(t2 - t1) <= 0.5 * t1)
// return t2;
// // Convergence of sigma(z) to (z - rho_1) * (z - rho_2)?
// if (std::abs(v1 - v0) <= 0.5 * v0 && std::abs(v2 - v1) <= 0.5 * v1)
// return t2;
// }
// return std::numeric_limits<double>::infinity();
//}
//auto stage3(const UnivariatePolynomial<double>& K0_,
// const UnivariatePolynomial<double>& P,
// int L = 20) -> double
//{
// const auto beta = compute_moduli_lower_bound(P);
// const auto s1 = beta; //* std::exp(i*rand());
// const auto s2 = std::conj(s1); //* std::exp(i*rand());
// const auto sigma = sigma_(s1);
// auto K0 = K0_;
// auto K1 = K1_stage2(P, K0, sigma, s1, std::conj(s1));
// auto K2 = K1_stage2(P, K1, sigma, s1, std::conj(s1));
// auto K3 = K1_stage2(P, K2, sigma, s1, std::conj(s1));
// auto K4 = K1_stage2(P, K3, sigma, s1, std::conj(s1));
// auto u = std::real(s1 + s2);
// auto t0 = s1 - (a0 - b0 * s2) / (c0 - d0 * s2);
// auto t1 = s1 - (a1 - b1 * s2) / (c1 - d1 * s2);
// auto t2 = s1 - (a2 - b2 * s2) / (c2 - d2 * s2);
// for (int i = 0; i < L; ++i)
// {
// K0 = K1;
// K1 = K2;
// K2 = K1_stage2(P, K1, sigma, s1, std::conj(s1));
// t0 = t1;
// t1 = t2;
// t2 = s1 - P(s1) / K2(s1);
// auto sigma_0 = sigma(K0, K1, K2, s1, s2);
// auto sigma_1 = sigma(K1, K2, K3, s1, s2);
// auto sigma_2 = sigma(K2, K3, K4, s1, s2);
// const auto v0 = sigma_0[0];
// const auto v1 = sigma_1[0];
// const auto v2 = sigma_2[0];
// // Convergence to rho_1?
// if (std::abs(t1 - t0) <= 0.5 * t0 && std::abs(t2 - t1) <= 0.5 * t1)
// return t2;
// // Convergence of sigma(z) to (z - rho_1) * (z - rho_2)?
// if (std::abs(v1 - v0) <= 0.5 * v0 && std::abs(v2 - v1) <= 0.5 * v1)
// return t2;
// }
// return std::numeric_limits<double>::infinity();
//}
//auto sigma_lambda(const UnivariatePolynomial<double>& K0,
// const UnivariatePolynomial<double>& K1,
// const UnivariatePolynomial<double>& K2,
// const std::complex<double>& s1,
// const std::complex<double>& s2)
// -> UnivariatePolynomial<double>
//{
// // Use a, b, c, d, u, v.
// auto K0_s1 = c0 - d0 * s2, K0_s2 = c0 - d0 * s1;
// auto K1_s1 = c1 - d1 * s2, K1_s2 = c1 - d1 * s1;
// auto K2_s1 = c2 - d2 * s2, K2_s2 = c2 - d2 * s1;
// const auto det = K1_s1 * K2_s2 - K1_s2 * K2_s1;
// const auto m0 = K1_s1 * K2_s2 - K1_s2 * K2_s2;
// const auto m1 = K0_s2 * K2_s1 - K0_s1 * K2_s2;
// const auto m2 = K0_s1 * K1_s2 - K0_s2 * K1_s1;
// const auto sigma = (m0 * Z.pow<std::complex<double>>(2) + m1 * Z + m2) / det;
// return sigma;
//}
//sigma_lambda(
//auto stage3(const UnivariatePolynomial<double>& K0,
// const UnivariatePolynomial<double>& sigma0,
// const UnivariatePolynomial<double>& P) -> void
//{
//}
//auto sigma_(const std::complex<double>& s1) -> UnivariatePolynomial<double>
//{
// auto res = UnivariatePolynomial<double>{};
// auto res_c = (Z - s1) * (Z - std::conj(s1));
// res._coeff.resize(res_c._coeff.size());
// for (auto i = 0u; i < res_c._coeff.size(); ++i)
// res[i] = std::real(res_c[i]);
// return res;
//}
} /* namespace Sara */
} /* namespace DO */
<commit_msg>WIP: save work.<commit_after>#include <DO/Sara/Core/EigenExtension.hpp>
#include <DO/Sara/Core/Math/NewtonRaphson.hpp>
#include <DO/Sara/Core/Math/UnivariatePolynomial.hpp>
#include <complex>
#include <ctime>
#include <memory>
namespace DO { namespace Sara {
auto compute_moduli_lower_bound(const UnivariatePolynomial<double>& P)
-> double
{
auto Q = P;
Q[0] = -std::abs(Q[0] / Q[Q.degree()]);
for (int i = 1; i <= Q.degree(); ++i)
Q[i] = std::abs(Q[i] / Q[Q.degree()]);
auto x = 1.;
auto newton_raphson = NewtonRaphson<double>{Q};
x = newton_raphson(x, 50);
return x;
}
// Sigma is a real polynomial. So (s1, s2) is a pair of identical real numbers
// or a conjugate complex pair.
auto sigma_generic_formula(const std::complex<double>& s1)
-> UnivariatePolynomial<double>
{
const auto a = std::real(s1);
const auto b = std::imag(s1);
return Z.pow<double>(2) - 2 * a * Z + (a * a + b * b);
}
// See formula (2.2) at page 547.
// Don't use because overflow and underflow problems would occur (page 563).
auto K1_generic_recurrence_formula(const UnivariatePolynomial<double>& K0,
const UnivariatePolynomial<double>& P,
const UnivariatePolynomial<double>& sigma,
const std::complex<double>& s1)
-> UnivariatePolynomial<double>
{
const auto s2 = std::conj(s1);
Matrix2cd a, b, c;
a << P(s1), P(s2), //
K0(s1), K0(s2);
b << K0(s1), K0(s2), //
s1 * P(s1), s2 * P(s2);
c << s1 * P(s1), s2 * P(s2), //
P(s1), P(s2);
const auto m = std::real(a.determinant() / c.determinant());
const auto n = std::real(b.determinant() / c.determinant());
return ((K0 + (m * Z + n)*P) / sigma).first;
}
// See formula (2.7) at page 548.
auto
sigma_formula_from_shift_polynomials(const UnivariatePolynomial<double>& K0,
const UnivariatePolynomial<double>& K1,
const UnivariatePolynomial<double>& K2,
const std::complex<double>& s1)
-> UnivariatePolynomial<double>
{
const auto s2 = std::conj(s1);
const auto a2 = std::real(K1(s1) * K2(s2) - K1(s2) * K2(s1));
const auto a1 = std::real(K0(s2) * K2(s1) - K0(s1) * K2(s2));
const auto a0 = std::real(K0(s1) * K1(s2) - K0(s2) * K1(s1));
// return (a2 * Z.pow(2) + a1 * Z + a0) / a2;
return Z.pow<double>(2) + (a1 / a2) * Z + (a0 / a2);
}
// See formula at "Stage 1: no-shift process" at page 556.
auto K1_no_shift_polynomial(const UnivariatePolynomial<double>& K0,
const UnivariatePolynomial<double>& P)
-> UnivariatePolynomial<double>
{
auto K1 = (K0 - (K0(0) / P(0)) * P) / Z;
return K1.first;
}
// This is the scaled recurrence formula (page 563).
auto K0_polynomial(const UnivariatePolynomial<double>& P)
-> UnivariatePolynomial<double>
{
return derivative(P) / P.degree();
}
// Return linear polynomial remainder of division of:
// - P / sigma
// - K0 / sigma
//
// Used for stage 2 (fixed-shift process).
// TODO: For stage 2, P(s1) and P(s2) are evaluated only once.
//
// Used for stage 3 (variable-shift process).
// TODO: s1 and s2 are updated every time.
auto calculate_remainders(const UnivariatePolynomial<double>& P,
const UnivariatePolynomial<double>& K0,
const UnivariatePolynomial<double>& sigma,
const std::complex<double>& s1)
-> std::pair<UnivariatePolynomial<double>, UnivariatePolynomial<double>>
{
const auto s2 = std::conj(s1);
// See stage 2 formula (9.7) (page 563).
Matrix4cd M;
Vector4cd y;
M << 1, -s2, 0, 0,
0, 0, 1, -1,
1, -s1, 0, 0,
0, 0, 1, -s1;
y << P(s1), P(s2), K0(s1), K0(s2);
Vector4cd x = M.colPivHouseholderQr().solve(y);
const auto a = std::real(x[0]);
const auto b = std::real(x[1]);
const auto c = std::real(x[2]);
const auto d = std::real(x[3]);
const auto u = - std::real(s1 + s2);
const auto P_remainder = b * (Z + u) + a;
const auto K0_remainder = d * (Z + u) + c;
return {P_remainder, K0_remainder};
}
//auto stage2(const UnivariatePolynomial<double>& K0_,
// const UnivariatePolynomial<double>& P,
// int L = 20) -> double
//{
// const auto beta = compute_moduli_lower_bound(P);
// const auto s1 = beta; //* std::exp(i*rand());
// const auto s2 = std::conj(s1); //* std::exp(i*rand());
// const auto sigma = sigma_(s1);
// auto K0 = K0_;
// auto K1 = K1_stage2(P, K0, sigma, s1, std::conj(s1));
// auto K2 = K1_stage2(P, K1, sigma, s1, std::conj(s1));
// auto K3 = K1_stage2(P, K2, sigma, s1, std::conj(s1));
// auto K4 = K1_stage2(P, K3, sigma, s1, std::conj(s1));
// auto u = std::real(s1 + s2);
// auto t0 = s1 - (a0 - b0 * s2) / (c0 - d0 * s2);
// auto t1 = s1 - (a1 - b1 * s2) / (c1 - d1 * s2);
// auto t2 = s1 - (a2 - b2 * s2) / (c2 - d2 * s2);
// for (int i = 0; i < L; ++i)
// {
// K0 = K1;
// K1 = K2;
// K2 = K1_stage2(P, K1, sigma, s1, std::conj(s1));
// t0 = t1;
// t1 = t2;
// t2 = s1 - P(s1) / K2(s1);
// auto sigma_0 = sigma(K0, K1, K2, s1, s2);
// auto sigma_1 = sigma(K1, K2, K3, s1, s2);
// auto sigma_2 = sigma(K2, K3, K4, s1, s2);
// const auto v0 = sigma_0[0];
// const auto v1 = sigma_1[0];
// const auto v2 = sigma_2[0];
// // Convergence to rho_1?
// if (std::abs(t1 - t0) <= 0.5 * t0 && std::abs(t2 - t1) <= 0.5 * t1)
// return t2;
// // Convergence of sigma(z) to (z - rho_1) * (z - rho_2)?
// if (std::abs(v1 - v0) <= 0.5 * v0 && std::abs(v2 - v1) <= 0.5 * v1)
// return t2;
// }
// return std::numeric_limits<double>::infinity();
//}
//auto stage3(const UnivariatePolynomial<double>& K0_,
// const UnivariatePolynomial<double>& P,
// int L = 20) -> double
//{
// const auto beta = compute_moduli_lower_bound(P);
// const auto s1 = beta; //* std::exp(i*rand());
// const auto s2 = std::conj(s1); //* std::exp(i*rand());
// const auto sigma = sigma_(s1);
// auto K0 = K0_;
// auto K1 = K1_stage2(P, K0, sigma, s1, std::conj(s1));
// auto K2 = K1_stage2(P, K1, sigma, s1, std::conj(s1));
// auto K3 = K1_stage2(P, K2, sigma, s1, std::conj(s1));
// auto K4 = K1_stage2(P, K3, sigma, s1, std::conj(s1));
// auto u = std::real(s1 + s2);
// auto t0 = s1 - (a0 - b0 * s2) / (c0 - d0 * s2);
// auto t1 = s1 - (a1 - b1 * s2) / (c1 - d1 * s2);
// auto t2 = s1 - (a2 - b2 * s2) / (c2 - d2 * s2);
// for (int i = 0; i < L; ++i)
// {
// K0 = K1;
// K1 = K2;
// K2 = K1_stage2(P, K1, sigma, s1, std::conj(s1));
// t0 = t1;
// t1 = t2;
// t2 = s1 - P(s1) / K2(s1);
// auto sigma_0 = sigma(K0, K1, K2, s1, s2);
// auto sigma_1 = sigma(K1, K2, K3, s1, s2);
// auto sigma_2 = sigma(K2, K3, K4, s1, s2);
// const auto v0 = sigma_0[0];
// const auto v1 = sigma_1[0];
// const auto v2 = sigma_2[0];
// // Convergence to rho_1?
// if (std::abs(t1 - t0) <= 0.5 * t0 && std::abs(t2 - t1) <= 0.5 * t1)
// return t2;
// // Convergence of sigma(z) to (z - rho_1) * (z - rho_2)?
// if (std::abs(v1 - v0) <= 0.5 * v0 && std::abs(v2 - v1) <= 0.5 * v1)
// return t2;
// }
// return std::numeric_limits<double>::infinity();
//}
//auto sigma_lambda(const UnivariatePolynomial<double>& K0,
// const UnivariatePolynomial<double>& K1,
// const UnivariatePolynomial<double>& K2,
// const std::complex<double>& s1,
// const std::complex<double>& s2)
// -> UnivariatePolynomial<double>
//{
// // Use a, b, c, d, u, v.
// auto K0_s1 = c0 - d0 * s2, K0_s2 = c0 - d0 * s1;
// auto K1_s1 = c1 - d1 * s2, K1_s2 = c1 - d1 * s1;
// auto K2_s1 = c2 - d2 * s2, K2_s2 = c2 - d2 * s1;
// const auto det = K1_s1 * K2_s2 - K1_s2 * K2_s1;
// const auto m0 = K1_s1 * K2_s2 - K1_s2 * K2_s2;
// const auto m1 = K0_s2 * K2_s1 - K0_s1 * K2_s2;
// const auto m2 = K0_s1 * K1_s2 - K0_s2 * K1_s1;
// const auto sigma = (m0 * Z.pow<std::complex<double>>(2) + m1 * Z + m2) / det;
// return sigma;
//}
//sigma_lambda(
//auto stage3(const UnivariatePolynomial<double>& K0,
// const UnivariatePolynomial<double>& sigma0,
// const UnivariatePolynomial<double>& P) -> void
//{
//}
//auto sigma_(const std::complex<double>& s1) -> UnivariatePolynomial<double>
//{
// auto res = UnivariatePolynomial<double>{};
// auto res_c = (Z - s1) * (Z - std::conj(s1));
// res._coeff.resize(res_c._coeff.size());
// for (auto i = 0u; i < res_c._coeff.size(); ++i)
// res[i] = std::real(res_c[i]);
// return res;
//}
} /* namespace Sara */
} /* namespace DO */
<|endoftext|> |
<commit_before>// Copyright (c) 2012, Sergey Zolotarev
// 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.
//
// 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 <cstddef>
#include <map>
#include "jit.h"
#include "jump-x86.h"
#include "plugin.h"
#include "pluginversion.h"
using namespace jit;
typedef void (*logprintf_t)(const char *format, ...);
static logprintf_t logprintf;
typedef std::map<AMX*, JIT*> JITMap;
static JITMap jit_map;
static JIT *GetJIT(AMX *amx) {
JITMap::const_iterator it = jit_map.find(amx);
if (it == jit_map.end()) {
JIT *jit = new JIT(amx);
jit_map.insert(std::make_pair(amx, jit));
return jit;
} else {
return it->second;
}
}
static void DeleteJIT(AMX *amx) {
JITMap::iterator it = jit_map.find(amx);
if (it != jit_map.end()) {
delete it->second;
jit_map.erase(it);
}
}
static int AMXAPI amx_GetAddr_JIT(AMX *amx, cell amx_addr, cell **phys_addr) {
AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx->base);
*phys_addr = reinterpret_cast<cell*>(amx->base + hdr->dat + amx_addr);
return AMX_ERR_NONE;
}
static int AMXAPI amx_Exec_JIT(AMX *amx, cell *retval, int index) {
if (index != AMX_EXEC_CONT) {
return GetJIT(amx)->CallPublicFunction(index, retval);
}
return AMX_ERR_NONE;
}
PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {
return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES;
}
PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) {
logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF];
new JumpX86(((void**)ppData[PLUGIN_DATA_AMX_EXPORTS])[PLUGIN_AMX_EXPORT_Exec], (void*)amx_Exec_JIT);
new JumpX86(((void**)ppData[PLUGIN_DATA_AMX_EXPORTS])[PLUGIN_AMX_EXPORT_GetAddr], (void*)amx_GetAddr_JIT);
logprintf(" JIT plugin v%s is OK.", PLUGIN_VERSION_STRING);
return true;
}
PLUGIN_EXPORT void PLUGIN_CALL Unload() {
// nothing
}
PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) {
return AMX_ERR_NONE;
}
PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) {
DeleteJIT(amx);
return AMX_ERR_NONE;
}
<commit_msg>Delete all JIT instances in Unload()<commit_after>// Copyright (c) 2012, Sergey Zolotarev
// 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.
//
// 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 <cstddef>
#include <map>
#include "jit.h"
#include "jump-x86.h"
#include "plugin.h"
#include "pluginversion.h"
using namespace jit;
typedef void (*logprintf_t)(const char *format, ...);
static logprintf_t logprintf;
typedef std::map<AMX*, JIT*> JITMap;
static JITMap jit_map;
static JIT *GetJIT(AMX *amx) {
JITMap::const_iterator it = jit_map.find(amx);
if (it == jit_map.end()) {
JIT *jit = new JIT(amx);
jit_map.insert(std::make_pair(amx, jit));
return jit;
} else {
return it->second;
}
}
static void DeleteJIT(AMX *amx) {
JITMap::iterator it = jit_map.find(amx);
if (it != jit_map.end()) {
delete it->second;
jit_map.erase(it);
}
}
static int AMXAPI amx_GetAddr_JIT(AMX *amx, cell amx_addr, cell **phys_addr) {
AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx->base);
*phys_addr = reinterpret_cast<cell*>(amx->base + hdr->dat + amx_addr);
return AMX_ERR_NONE;
}
static int AMXAPI amx_Exec_JIT(AMX *amx, cell *retval, int index) {
if (index != AMX_EXEC_CONT) {
return GetJIT(amx)->CallPublicFunction(index, retval);
}
return AMX_ERR_NONE;
}
PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {
return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES;
}
PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) {
logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF];
new JumpX86(((void**)ppData[PLUGIN_DATA_AMX_EXPORTS])[PLUGIN_AMX_EXPORT_Exec], (void*)amx_Exec_JIT);
new JumpX86(((void**)ppData[PLUGIN_DATA_AMX_EXPORTS])[PLUGIN_AMX_EXPORT_GetAddr], (void*)amx_GetAddr_JIT);
logprintf(" JIT plugin v%s is OK.", PLUGIN_VERSION_STRING);
return true;
}
PLUGIN_EXPORT void PLUGIN_CALL Unload() {
for (JITMap::iterator it = jit_map.begin(); it != jit_map.end(); ++it) {
delete it->second;
}
}
PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) {
return AMX_ERR_NONE;
}
PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) {
DeleteJIT(amx);
return AMX_ERR_NONE;
}
<|endoftext|> |
<commit_before>/*
* PCD8544 - Interface with Philips PCD8544 (or compatible) LCDs.
*
* Copyright (c) 2010 Carlos Rodrigues <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "PCD8544.h"
#if ARDUINO < 100
#include <WProgram.h>
#else
#include <Arduino.h>
#endif
#include <avr/pgmspace.h>
#define PCD8544_CMD LOW
#define PCD8544_DATA HIGH
/*
* If this was a ".h", it would get added to sketches when using
* the "Sketch -> Import Library..." menu on the Arduino IDE...
*/
#include "charset.cpp"
PCD8544::PCD8544(unsigned char sclk, unsigned char sdin,
unsigned char dc, unsigned char reset,
unsigned char sce):
pin_sclk(sclk),
pin_sdin(sdin),
pin_dc(dc),
pin_reset(reset),
pin_sce(sce)
{}
void PCD8544::begin(unsigned char width, unsigned char height, unsigned char model)
{
this->width = width;
this->height = height;
// Only two chip variants are currently known/supported...
this->model = (model == CHIP_ST7576) ? CHIP_ST7576 : CHIP_PCD8544;
this->column = 0;
this->line = 0;
// Sanitize the custom glyphs...
memset(this->custom, 0, sizeof(this->custom));
// All pins are outputs (these displays cannot be read)...
pinMode(this->pin_sclk, OUTPUT);
pinMode(this->pin_sdin, OUTPUT);
pinMode(this->pin_dc, OUTPUT);
pinMode(this->pin_reset, OUTPUT);
pinMode(this->pin_sce, OUTPUT);
// Reset the controller state...
digitalWrite(this->pin_reset, HIGH);
digitalWrite(this->pin_sce, HIGH);
digitalWrite(this->pin_reset, LOW);
delay(100);
digitalWrite(this->pin_reset, HIGH);
// Set the LCD parameters...
this->send(PCD8544_CMD, 0x21); // extended instruction set control (H=1)
this->send(PCD8544_CMD, 0x13); // bias system (1:48)
if (this->model == CHIP_ST7576) {
this->send(PCD8544_CMD, 0xe0); // higher Vop, too faint at default
this->send(PCD8544_CMD, 0x05); // partial display mode
} else {
this->send(PCD8544_CMD, 0xc2); // default Vop (3.06 + 66 * 0.06 = 7V)
}
this->send(PCD8544_CMD, 0x20); // extended instruction set control (H=0)
this->send(PCD8544_CMD, 0x09); // all display segments on
// Clear RAM contents...
this->clear();
// Activate LCD...
this->send(PCD8544_CMD, 0x08); // display blank
this->send(PCD8544_CMD, 0x0c); // normal mode (0x0d = inverse mode)
delay(100);
// Place the cursor at the origin...
this->send(PCD8544_CMD, 0x80);
this->send(PCD8544_CMD, 0x40);
}
void PCD8544::stop()
{
this->clear();
this->setPower(false);
}
void PCD8544::clear()
{
this->setCursor(0, 0);
for (unsigned short i = 0; i < this->width * (this->height/8); i++) {
this->send(PCD8544_DATA, 0x00);
}
this->setCursor(0, 0);
}
void PCD8544::clearLine()
{
this->setCursor(0, this->line);
for (unsigned char i = 0; i < this->width; i++) {
this->send(PCD8544_DATA, 0x00);
}
this->setCursor(0, this->line);
}
void PCD8544::setPower(bool on)
{
this->send(PCD8544_CMD, on ? 0x20 : 0x24);
}
inline void PCD8544::display()
{
this->setPower(true);
}
inline void PCD8544::noDisplay()
{
this->setPower(false);
}
void PCD8544::setInverse(bool inverse)
{
this->send(PCD8544_CMD, inverse ? 0x0d : 0x0c);
}
void PCD8544::setContrast(unsigned char level)
{
// The PCD8544 datasheet specifies a maximum Vop of 8.5V for safe
// operation in low temperatures, which limits the contrast level.
if (this->model == CHIP_PCD8544 && level > 90) {
level = 90; // Vop = 3.06 + 90 * 0.06 = 8.46V
}
// The ST7576 datasheet specifies a minimum Vop of 4V.
if (this->model == CHIP_ST7576 && level < 36) {
level = 36; // Vop = 2.94 + 36 * 0.06 = 4.02V
}
this->send(PCD8544_CMD, 0x21); // extended instruction set control (H=1)
this->send(PCD8544_CMD, 0x80 | (level & 0x7f));
this->send(PCD8544_CMD, 0x20); // extended instruction set control (H=0)
}
void PCD8544::home()
{
this->setCursor(0, this->line);
}
void PCD8544::setCursor(unsigned char column, unsigned char line)
{
this->column = (column % this->width);
this->line = (line % (this->height/9 + 1));
this->send(PCD8544_CMD, 0x80 | this->column);
this->send(PCD8544_CMD, 0x40 | this->line);
}
void PCD8544::createChar(unsigned char chr, const unsigned char *glyph)
{
// ASCII 0-31 only...
if (chr >= ' ') {
return;
}
this->custom[chr] = glyph;
}
#if ARDUINO < 100
void PCD8544::write(uint8_t chr)
#else
size_t PCD8544::write(uint8_t chr)
#endif
{
// ASCII 7-bit only...
if (chr >= 0x80) {
#if ARDUINO < 100
return;
#else
return 0;
#endif
}
const unsigned char *glyph;
unsigned char pgm_buffer[5];
if (chr >= ' ') {
// Regular ASCII characters are kept in flash to save RAM...
memcpy_P(pgm_buffer, &charset[chr - ' '], sizeof(pgm_buffer));
glyph = pgm_buffer;
} else {
// Custom glyphs, on the other hand, are stored in RAM...
if (this->custom[chr]) {
glyph = this->custom[chr];
} else {
// Default to a space character if unset...
memcpy_P(pgm_buffer, &charset[0], sizeof(pgm_buffer));
glyph = pgm_buffer;
}
}
// Output one column at a time...
for (unsigned char i = 0; i < 5; i++) {
this->send(PCD8544_DATA, glyph[i]);
}
// One column between characters...
this->send(PCD8544_DATA, 0x00);
// Update the cursor position...
this->column = (this->column + 6) % this->width;
if (this->column == 0) {
this->line = (this->line + 1) % (this->height/9 + 1);
}
#if ARDUINO >= 100
return 1;
#endif
}
void PCD8544::drawBitmap(const unsigned char *data, unsigned char columns, unsigned char lines)
{
unsigned char scolumn = this->column;
unsigned char sline = this->line;
// The bitmap will be clipped at the right/bottom edge of the display...
unsigned char mx = (scolumn + columns > this->width) ? (this->width - scolumn) : columns;
unsigned char my = (sline + lines > this->height/8) ? (this->height/8 - sline) : lines;
for (unsigned char y = 0; y < my; y++) {
this->setCursor(scolumn, sline + y);
for (unsigned char x = 0; x < mx; x++) {
this->send(PCD8544_DATA, data[y * columns + x]);
}
}
// Leave the cursor in a consistent position...
this->setCursor(scolumn + columns, sline);
}
void PCD8544::drawColumn(unsigned char lines, unsigned char value)
{
unsigned char scolumn = this->column;
unsigned char sline = this->line;
// Keep "value" within range...
if (value > lines*8) {
value = lines*8;
}
// Find the line where "value" resides...
unsigned char mark = (lines*8 - 1 - value)/8;
// Clear the lines above the mark...
for (unsigned char line = 0; line < mark; line++) {
this->setCursor(scolumn, sline + line);
this->send(PCD8544_DATA, 0x00);
}
// Compute the byte to draw at the "mark" line...
unsigned char b = 0xff;
for (unsigned char i = 0; i < lines*8 - mark*8 - value; i++) {
b <<= 1;
}
this->setCursor(scolumn, sline + mark);
this->send(PCD8544_DATA, b);
// Fill the lines below the mark...
for (unsigned char line = mark + 1; line < lines; line++) {
this->setCursor(scolumn, sline + line);
this->send(PCD8544_DATA, 0xff);
}
// Leave the cursor in a consistent position...
this->setCursor(scolumn + 1, sline);
}
void PCD8544::send(unsigned char type, unsigned char data)
{
digitalWrite(this->pin_dc, type);
digitalWrite(this->pin_sce, LOW);
shiftOut(this->pin_sdin, this->pin_sclk, MSBFIRST, data);
digitalWrite(this->pin_sce, HIGH);
}
/* vim: set expandtab ts=4 sw=4: */
<commit_msg>Correct comment for the ST7576 Vop equation.<commit_after>/*
* PCD8544 - Interface with Philips PCD8544 (or compatible) LCDs.
*
* Copyright (c) 2010 Carlos Rodrigues <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "PCD8544.h"
#if ARDUINO < 100
#include <WProgram.h>
#else
#include <Arduino.h>
#endif
#include <avr/pgmspace.h>
#define PCD8544_CMD LOW
#define PCD8544_DATA HIGH
/*
* If this was a ".h", it would get added to sketches when using
* the "Sketch -> Import Library..." menu on the Arduino IDE...
*/
#include "charset.cpp"
PCD8544::PCD8544(unsigned char sclk, unsigned char sdin,
unsigned char dc, unsigned char reset,
unsigned char sce):
pin_sclk(sclk),
pin_sdin(sdin),
pin_dc(dc),
pin_reset(reset),
pin_sce(sce)
{}
void PCD8544::begin(unsigned char width, unsigned char height, unsigned char model)
{
this->width = width;
this->height = height;
// Only two chip variants are currently known/supported...
this->model = (model == CHIP_ST7576) ? CHIP_ST7576 : CHIP_PCD8544;
this->column = 0;
this->line = 0;
// Sanitize the custom glyphs...
memset(this->custom, 0, sizeof(this->custom));
// All pins are outputs (these displays cannot be read)...
pinMode(this->pin_sclk, OUTPUT);
pinMode(this->pin_sdin, OUTPUT);
pinMode(this->pin_dc, OUTPUT);
pinMode(this->pin_reset, OUTPUT);
pinMode(this->pin_sce, OUTPUT);
// Reset the controller state...
digitalWrite(this->pin_reset, HIGH);
digitalWrite(this->pin_sce, HIGH);
digitalWrite(this->pin_reset, LOW);
delay(100);
digitalWrite(this->pin_reset, HIGH);
// Set the LCD parameters...
this->send(PCD8544_CMD, 0x21); // extended instruction set control (H=1)
this->send(PCD8544_CMD, 0x13); // bias system (1:48)
if (this->model == CHIP_ST7576) {
this->send(PCD8544_CMD, 0xe0); // higher Vop, too faint at default
this->send(PCD8544_CMD, 0x05); // partial display mode
} else {
this->send(PCD8544_CMD, 0xc2); // default Vop (3.06 + 66 * 0.06 = 7V)
}
this->send(PCD8544_CMD, 0x20); // extended instruction set control (H=0)
this->send(PCD8544_CMD, 0x09); // all display segments on
// Clear RAM contents...
this->clear();
// Activate LCD...
this->send(PCD8544_CMD, 0x08); // display blank
this->send(PCD8544_CMD, 0x0c); // normal mode (0x0d = inverse mode)
delay(100);
// Place the cursor at the origin...
this->send(PCD8544_CMD, 0x80);
this->send(PCD8544_CMD, 0x40);
}
void PCD8544::stop()
{
this->clear();
this->setPower(false);
}
void PCD8544::clear()
{
this->setCursor(0, 0);
for (unsigned short i = 0; i < this->width * (this->height/8); i++) {
this->send(PCD8544_DATA, 0x00);
}
this->setCursor(0, 0);
}
void PCD8544::clearLine()
{
this->setCursor(0, this->line);
for (unsigned char i = 0; i < this->width; i++) {
this->send(PCD8544_DATA, 0x00);
}
this->setCursor(0, this->line);
}
void PCD8544::setPower(bool on)
{
this->send(PCD8544_CMD, on ? 0x20 : 0x24);
}
inline void PCD8544::display()
{
this->setPower(true);
}
inline void PCD8544::noDisplay()
{
this->setPower(false);
}
void PCD8544::setInverse(bool inverse)
{
this->send(PCD8544_CMD, inverse ? 0x0d : 0x0c);
}
void PCD8544::setContrast(unsigned char level)
{
// The PCD8544 datasheet specifies a maximum Vop of 8.5V for safe
// operation in low temperatures, which limits the contrast level.
if (this->model == CHIP_PCD8544 && level > 90) {
level = 90; // Vop = 3.06 + 90 * 0.06 = 8.46V
}
// The ST7576 datasheet specifies a minimum Vop of 4V.
if (this->model == CHIP_ST7576 && level < 36) {
level = 36; // Vop = 2.94 + 36 * 0.03 = 4.02V
}
this->send(PCD8544_CMD, 0x21); // extended instruction set control (H=1)
this->send(PCD8544_CMD, 0x80 | (level & 0x7f));
this->send(PCD8544_CMD, 0x20); // extended instruction set control (H=0)
}
void PCD8544::home()
{
this->setCursor(0, this->line);
}
void PCD8544::setCursor(unsigned char column, unsigned char line)
{
this->column = (column % this->width);
this->line = (line % (this->height/9 + 1));
this->send(PCD8544_CMD, 0x80 | this->column);
this->send(PCD8544_CMD, 0x40 | this->line);
}
void PCD8544::createChar(unsigned char chr, const unsigned char *glyph)
{
// ASCII 0-31 only...
if (chr >= ' ') {
return;
}
this->custom[chr] = glyph;
}
#if ARDUINO < 100
void PCD8544::write(uint8_t chr)
#else
size_t PCD8544::write(uint8_t chr)
#endif
{
// ASCII 7-bit only...
if (chr >= 0x80) {
#if ARDUINO < 100
return;
#else
return 0;
#endif
}
const unsigned char *glyph;
unsigned char pgm_buffer[5];
if (chr >= ' ') {
// Regular ASCII characters are kept in flash to save RAM...
memcpy_P(pgm_buffer, &charset[chr - ' '], sizeof(pgm_buffer));
glyph = pgm_buffer;
} else {
// Custom glyphs, on the other hand, are stored in RAM...
if (this->custom[chr]) {
glyph = this->custom[chr];
} else {
// Default to a space character if unset...
memcpy_P(pgm_buffer, &charset[0], sizeof(pgm_buffer));
glyph = pgm_buffer;
}
}
// Output one column at a time...
for (unsigned char i = 0; i < 5; i++) {
this->send(PCD8544_DATA, glyph[i]);
}
// One column between characters...
this->send(PCD8544_DATA, 0x00);
// Update the cursor position...
this->column = (this->column + 6) % this->width;
if (this->column == 0) {
this->line = (this->line + 1) % (this->height/9 + 1);
}
#if ARDUINO >= 100
return 1;
#endif
}
void PCD8544::drawBitmap(const unsigned char *data, unsigned char columns, unsigned char lines)
{
unsigned char scolumn = this->column;
unsigned char sline = this->line;
// The bitmap will be clipped at the right/bottom edge of the display...
unsigned char mx = (scolumn + columns > this->width) ? (this->width - scolumn) : columns;
unsigned char my = (sline + lines > this->height/8) ? (this->height/8 - sline) : lines;
for (unsigned char y = 0; y < my; y++) {
this->setCursor(scolumn, sline + y);
for (unsigned char x = 0; x < mx; x++) {
this->send(PCD8544_DATA, data[y * columns + x]);
}
}
// Leave the cursor in a consistent position...
this->setCursor(scolumn + columns, sline);
}
void PCD8544::drawColumn(unsigned char lines, unsigned char value)
{
unsigned char scolumn = this->column;
unsigned char sline = this->line;
// Keep "value" within range...
if (value > lines*8) {
value = lines*8;
}
// Find the line where "value" resides...
unsigned char mark = (lines*8 - 1 - value)/8;
// Clear the lines above the mark...
for (unsigned char line = 0; line < mark; line++) {
this->setCursor(scolumn, sline + line);
this->send(PCD8544_DATA, 0x00);
}
// Compute the byte to draw at the "mark" line...
unsigned char b = 0xff;
for (unsigned char i = 0; i < lines*8 - mark*8 - value; i++) {
b <<= 1;
}
this->setCursor(scolumn, sline + mark);
this->send(PCD8544_DATA, b);
// Fill the lines below the mark...
for (unsigned char line = mark + 1; line < lines; line++) {
this->setCursor(scolumn, sline + line);
this->send(PCD8544_DATA, 0xff);
}
// Leave the cursor in a consistent position...
this->setCursor(scolumn + 1, sline);
}
void PCD8544::send(unsigned char type, unsigned char data)
{
digitalWrite(this->pin_dc, type);
digitalWrite(this->pin_sce, LOW);
shiftOut(this->pin_sdin, this->pin_sclk, MSBFIRST, data);
digitalWrite(this->pin_sce, HIGH);
}
/* vim: set expandtab ts=4 sw=4: */
<|endoftext|> |
<commit_before>/*
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include <utility>
#include <vector>
#include "util/interrupt.h"
#include "kernel/metavar.h"
#include "kernel/free_vars.h"
#include "kernel/justification.h"
#include "kernel/instantiate.h"
#include "kernel/find_fn.h"
#include "kernel/expr_maps.h"
#include "kernel/level.h"
#include "kernel/cache_stack.h"
#include "kernel/expr_cache.h"
#ifndef LEAN_INSTANTIATE_METAVARS_CACHE_CAPACITY
#define LEAN_INSTANTIATE_METAVARS_CACHE_CAPACITY 1024*8
#endif
namespace lean {
substitution::substitution() {}
bool substitution::is_expr_assigned(name const & m) const {
return m_expr_subst.contains(m);
}
auto substitution::get_expr_assignment(name const & m) const -> opt_expr_jst {
auto it = m_expr_subst.find(m);
if (it)
return opt_expr_jst(mk_pair(*it, get_expr_jst(m)));
else
return opt_expr_jst();
}
bool substitution::is_level_assigned(name const & m) const {
return m_level_subst.contains(m);
}
auto substitution::get_level_assignment(name const & m) const -> opt_level_jst {
auto it = m_level_subst.find(m);
if (it)
return opt_level_jst(mk_pair(*it, get_level_jst(m)));
else
return opt_level_jst();
}
optional<expr> substitution::get_expr(name const & m) const {
auto it = m_expr_subst.find(m);
return it ? some_expr(*it) : none_expr();
}
optional<level> substitution::get_level(name const & m) const {
auto it = m_level_subst.find(m);
return it ? some_level(*it) : none_level();
}
void substitution::assign(name const & m, expr const & t, justification const & j) {
lean_assert(closed(t));
m_expr_subst.insert(m, t);
m_occs_map.erase(m);
if (!j.is_none())
m_expr_jsts.insert(m, j);
}
void substitution::assign(name const & m, level const & l, justification const & j) {
m_level_subst.insert(m, l);
if (!j.is_none())
m_level_jsts.insert(m, j);
}
pair<level, justification> substitution::instantiate_metavars(level const & l, bool use_jst) {
if (!has_meta(l))
return mk_pair(l, justification());
justification j;
auto save_jst = [&](justification const & j2) { j = mk_composite1(j, j2); };
level r = replace(l, [&](level const & l) {
if (!has_meta(l)) {
return some_level(l);
} else if (is_meta(l)) {
auto p1 = get_assignment(l);
if (p1) {
auto p2 = instantiate_metavars(p1->first, use_jst);
if (use_jst) {
justification new_jst = mk_composite1(p1->second, p2.second);
assign(meta_id(l), p2.first, new_jst);
save_jst(new_jst);
} else {
assign(meta_id(l), p2.first);
}
return some_level(p2.first);
}
}
return none_level();
});
return mk_pair(r, j);
}
typedef expr_cache instantiate_metavars_cache;
MK_CACHE_STACK(instantiate_metavars_cache, LEAN_INSTANTIATE_METAVARS_CACHE_CAPACITY)
class instantiate_metavars_fn {
protected:
typedef instantiate_metavars_cache_ref cache_ref;
substitution & m_subst;
cache_ref m_cache;
justification m_jst;
bool m_use_jst;
// if m_inst_local_types, then instantiate metavariables nested in the types of local constants and metavariables.
bool m_inst_local_types;
void save_jst(justification const & j) { m_jst = mk_composite1(m_jst, j); }
level visit_level(level const & l) {
auto p1 = m_subst.instantiate_metavars(l, m_use_jst);
if (m_use_jst)
save_jst(p1.second);
return p1.first;
}
levels visit_levels(levels const & ls) {
return map_reuse(ls,
[&](level const & l) { return visit_level(l); },
[](level const & l1, level const & l2) { return is_eqp(l1, l2); });
}
expr visit_sort(expr const & s) {
return update_sort(s, visit_level(sort_level(s)));
}
expr visit_constant(expr const & c) {
return update_constant(c, visit_levels(const_levels(c)));
}
expr visit_meta(expr const & m) {
name const & m_name = mlocal_name(m);
auto p1 = m_subst.get_expr_assignment(m_name);
if (p1) {
if (!has_metavar(p1->first)) {
if (m_use_jst)
save_jst(p1->second);
return p1->first;
} else if (m_use_jst) {
auto p2 = m_subst.instantiate_metavars(p1->first);
justification new_jst = mk_composite1(p1->second, p2.second);
m_subst.assign(m_name, p2.first, new_jst);
save_jst(new_jst);
return p2.first;
} else {
auto p2 = m_subst.instantiate_metavars(p1->first);
m_subst.assign(m_name, p2.first, mk_composite1(p1->second, p2.second));
return p2.first;
}
} else {
if (m_inst_local_types)
return update_mlocal(m, visit(mlocal_type(m)));
else
return m;
}
}
expr visit_app(expr const & e) {
buffer<expr> args;
expr const & f = get_app_rev_args(e, args);
if (is_metavar(f)) {
if (auto p1 = m_subst.get_expr_assignment(mlocal_name(f))) {
if (m_use_jst)
save_jst(p1->second);
expr new_app = apply_beta(p1->first, args.size(), args.data());
return visit(new_app);
}
}
expr new_f = visit(f);
buffer<expr> new_args;
bool modified = !is_eqp(new_f, f);
for (expr const & arg : args) {
expr new_arg = visit(arg);
if (!is_eqp(arg, new_arg))
modified = true;
new_args.push_back(new_arg);
}
if (!modified)
return e;
else
return mk_rev_app(new_f, new_args);
}
expr save_result(expr const & e, expr && r) {
m_cache->insert(e, r);
return r;
}
expr visit_macro(expr const & e) {
lean_assert(is_macro(e));
buffer<expr> new_args;
for (unsigned i = 0; i < macro_num_args(e); i++)
new_args.push_back(visit(macro_arg(e, i)));
return update_macro(e, new_args.size(), new_args.data());
}
expr visit_binding(expr const & e) {
lean_assert(is_binding(e));
expr new_d = visit(binding_domain(e));
expr new_b = visit(binding_body(e));
return update_binding(e, new_d, new_b);
}
expr visit(expr const & e) {
if (!has_metavar(e))
return e;
check_system("instantiate metavars");
if (auto it = m_cache->find(e))
return *it;
switch (e.kind()) {
case expr_kind::Sort: return save_result(e, visit_sort(e));
case expr_kind::Var: lean_unreachable();
case expr_kind::Local:
if (m_inst_local_types)
return save_result(e, update_mlocal(e, visit(mlocal_type(e))));
else
return e;
case expr_kind::Constant: return save_result(e, visit_constant(e));
case expr_kind::Macro: return save_result(e, visit_macro(e));
case expr_kind::Meta: return save_result(e, visit_meta(e));
case expr_kind::App: return save_result(e, visit_app(e));
case expr_kind::Lambda:
case expr_kind::Pi: return save_result(e, visit_binding(e));
}
lean_unreachable();
}
public:
instantiate_metavars_fn(substitution & s, bool use_jst, bool inst_local_types):
m_subst(s), m_use_jst(use_jst), m_inst_local_types(inst_local_types) {}
justification const & get_justification() const { return m_jst; }
expr operator()(expr const & e) { return visit(e); }
};
pair<expr, justification> substitution::instantiate_metavars_core(expr const & e, bool inst_local_types) {
if (!has_metavar(e)) {
return mk_pair(e, justification());
} else {
instantiate_metavars_fn fn(*this, true, inst_local_types);
expr r = fn(e);
return mk_pair(r, fn.get_justification());
}
}
expr substitution::instantiate_metavars_wo_jst(expr const & e, bool inst_local_types) {
return instantiate_metavars_fn(*this, false, inst_local_types)(e);
}
static name_set merge(name_set s1, name_set const & s2) {
s2.for_each([&](name const & n) { s1.insert(n); });
return s1;
}
static bool all_unassigned(substitution const & subst, name_set const & s) {
return !s.find_if([&](name const & m) { return subst.is_expr_assigned(m); });
}
name_set substitution::get_occs(name const & m, name_set & fresh) {
lean_assert(is_expr_assigned(m));
check_system("substitution occurs check");
if (fresh.contains(m)) {
return *m_occs_map.find(m);
} else if (name_set const * it = m_occs_map.find(m)) {
name_set curr_occs = *it;
if (all_unassigned(*this, curr_occs)) {
return curr_occs;
}
name_set new_occs;
curr_occs.for_each([&](name const & n) {
if (is_expr_assigned(n)) {
new_occs = merge(new_occs, get_occs(n, fresh));
} else {
// we need to update
new_occs.insert(n);
}
});
m_occs_map.insert(m, new_occs);
fresh.insert(m);
return new_occs;
} else {
expr e = *get_expr(m);
name_set occs;
::lean::for_each(e, [&](expr const & e, unsigned) {
if (!has_expr_metavar(e)) return false;
if (is_local(e)) return false; // do not process type
if (is_metavar(e)) {
name const & n = mlocal_name(e);
if (is_expr_assigned(n)) {
occs = merge(occs, get_occs(n, fresh));
} else {
occs.insert(n);
}
return false;
}
return true;
});
m_occs_map.insert(m, occs);
fresh.insert(m);
return occs;
}
}
bool substitution::occurs_expr(name const & m, expr const & e) {
if (!has_expr_metavar(e))
return false;
name_set fresh;
bool found = false;
for_each(e, [&](expr const & e, unsigned) {
if (found || !has_expr_metavar(e)) return false;
if (is_metavar(e)) {
name const & n = mlocal_name(e);
if (is_expr_assigned(n)) {
if (get_occs(n, fresh).contains(m))
found = true;
} else if (n == m) {
found = true;
}
return false; // do not visit type
}
if (is_local(e)) return false; // do not visit type
return true;
});
return found;
}
}
<commit_msg>fix(kernel/metavar): improve error messages by propagating the tag when we execute instantiate_all<commit_after>/*
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include <utility>
#include <vector>
#include "util/interrupt.h"
#include "kernel/metavar.h"
#include "kernel/free_vars.h"
#include "kernel/justification.h"
#include "kernel/instantiate.h"
#include "kernel/find_fn.h"
#include "kernel/expr_maps.h"
#include "kernel/level.h"
#include "kernel/cache_stack.h"
#include "kernel/expr_cache.h"
#ifndef LEAN_INSTANTIATE_METAVARS_CACHE_CAPACITY
#define LEAN_INSTANTIATE_METAVARS_CACHE_CAPACITY 1024*8
#endif
namespace lean {
substitution::substitution() {}
bool substitution::is_expr_assigned(name const & m) const {
return m_expr_subst.contains(m);
}
auto substitution::get_expr_assignment(name const & m) const -> opt_expr_jst {
auto it = m_expr_subst.find(m);
if (it)
return opt_expr_jst(mk_pair(*it, get_expr_jst(m)));
else
return opt_expr_jst();
}
bool substitution::is_level_assigned(name const & m) const {
return m_level_subst.contains(m);
}
auto substitution::get_level_assignment(name const & m) const -> opt_level_jst {
auto it = m_level_subst.find(m);
if (it)
return opt_level_jst(mk_pair(*it, get_level_jst(m)));
else
return opt_level_jst();
}
optional<expr> substitution::get_expr(name const & m) const {
auto it = m_expr_subst.find(m);
return it ? some_expr(*it) : none_expr();
}
optional<level> substitution::get_level(name const & m) const {
auto it = m_level_subst.find(m);
return it ? some_level(*it) : none_level();
}
void substitution::assign(name const & m, expr const & t, justification const & j) {
lean_assert(closed(t));
m_expr_subst.insert(m, t);
m_occs_map.erase(m);
if (!j.is_none())
m_expr_jsts.insert(m, j);
}
void substitution::assign(name const & m, level const & l, justification const & j) {
m_level_subst.insert(m, l);
if (!j.is_none())
m_level_jsts.insert(m, j);
}
pair<level, justification> substitution::instantiate_metavars(level const & l, bool use_jst) {
if (!has_meta(l))
return mk_pair(l, justification());
justification j;
auto save_jst = [&](justification const & j2) { j = mk_composite1(j, j2); };
level r = replace(l, [&](level const & l) {
if (!has_meta(l)) {
return some_level(l);
} else if (is_meta(l)) {
auto p1 = get_assignment(l);
if (p1) {
auto p2 = instantiate_metavars(p1->first, use_jst);
if (use_jst) {
justification new_jst = mk_composite1(p1->second, p2.second);
assign(meta_id(l), p2.first, new_jst);
save_jst(new_jst);
} else {
assign(meta_id(l), p2.first);
}
return some_level(p2.first);
}
}
return none_level();
});
return mk_pair(r, j);
}
typedef expr_cache instantiate_metavars_cache;
MK_CACHE_STACK(instantiate_metavars_cache, LEAN_INSTANTIATE_METAVARS_CACHE_CAPACITY)
class instantiate_metavars_fn {
protected:
typedef instantiate_metavars_cache_ref cache_ref;
substitution & m_subst;
cache_ref m_cache;
justification m_jst;
bool m_use_jst;
// if m_inst_local_types, then instantiate metavariables nested in the types of local constants and metavariables.
bool m_inst_local_types;
void save_jst(justification const & j) { m_jst = mk_composite1(m_jst, j); }
level visit_level(level const & l) {
auto p1 = m_subst.instantiate_metavars(l, m_use_jst);
if (m_use_jst)
save_jst(p1.second);
return p1.first;
}
levels visit_levels(levels const & ls) {
return map_reuse(ls,
[&](level const & l) { return visit_level(l); },
[](level const & l1, level const & l2) { return is_eqp(l1, l2); });
}
expr visit_sort(expr const & s) {
return update_sort(s, visit_level(sort_level(s)));
}
expr visit_constant(expr const & c) {
return update_constant(c, visit_levels(const_levels(c)));
}
expr visit_meta(expr const & m) {
name const & m_name = mlocal_name(m);
auto p1 = m_subst.get_expr_assignment(m_name);
if (p1) {
if (!has_metavar(p1->first)) {
if (m_use_jst)
save_jst(p1->second);
return p1->first;
} else if (m_use_jst) {
auto p2 = m_subst.instantiate_metavars(p1->first);
justification new_jst = mk_composite1(p1->second, p2.second);
m_subst.assign(m_name, p2.first, new_jst);
save_jst(new_jst);
return p2.first;
} else {
auto p2 = m_subst.instantiate_metavars(p1->first);
m_subst.assign(m_name, p2.first, mk_composite1(p1->second, p2.second));
return p2.first;
}
} else {
if (m_inst_local_types)
return update_mlocal(m, visit(mlocal_type(m)));
else
return m;
}
}
expr visit_app(expr const & e) {
buffer<expr> args;
expr const & f = get_app_rev_args(e, args);
if (is_metavar(f)) {
if (auto p1 = m_subst.get_expr_assignment(mlocal_name(f))) {
if (m_use_jst)
save_jst(p1->second);
expr new_app = apply_beta(p1->first, args.size(), args.data());
return visit(new_app);
}
}
expr new_f = visit(f);
buffer<expr> new_args;
bool modified = !is_eqp(new_f, f);
for (expr const & arg : args) {
expr new_arg = visit(arg);
if (!is_eqp(arg, new_arg))
modified = true;
new_args.push_back(new_arg);
}
if (!modified)
return e;
else
return mk_rev_app(new_f, new_args, e.get_tag());
}
expr save_result(expr const & e, expr && r) {
m_cache->insert(e, r);
return r;
}
expr visit_macro(expr const & e) {
lean_assert(is_macro(e));
buffer<expr> new_args;
for (unsigned i = 0; i < macro_num_args(e); i++)
new_args.push_back(visit(macro_arg(e, i)));
return update_macro(e, new_args.size(), new_args.data());
}
expr visit_binding(expr const & e) {
lean_assert(is_binding(e));
expr new_d = visit(binding_domain(e));
expr new_b = visit(binding_body(e));
return update_binding(e, new_d, new_b);
}
expr visit(expr const & e) {
if (!has_metavar(e))
return e;
check_system("instantiate metavars");
if (auto it = m_cache->find(e))
return *it;
switch (e.kind()) {
case expr_kind::Sort: return save_result(e, visit_sort(e));
case expr_kind::Var: lean_unreachable();
case expr_kind::Local:
if (m_inst_local_types)
return save_result(e, update_mlocal(e, visit(mlocal_type(e))));
else
return e;
case expr_kind::Constant: return save_result(e, visit_constant(e));
case expr_kind::Macro: return save_result(e, visit_macro(e));
case expr_kind::Meta: return save_result(e, visit_meta(e));
case expr_kind::App: return save_result(e, visit_app(e));
case expr_kind::Lambda:
case expr_kind::Pi: return save_result(e, visit_binding(e));
}
lean_unreachable();
}
public:
instantiate_metavars_fn(substitution & s, bool use_jst, bool inst_local_types):
m_subst(s), m_use_jst(use_jst), m_inst_local_types(inst_local_types) {}
justification const & get_justification() const { return m_jst; }
expr operator()(expr const & e) { return visit(e); }
};
pair<expr, justification> substitution::instantiate_metavars_core(expr const & e, bool inst_local_types) {
if (!has_metavar(e)) {
return mk_pair(e, justification());
} else {
instantiate_metavars_fn fn(*this, true, inst_local_types);
expr r = fn(e);
return mk_pair(r, fn.get_justification());
}
}
expr substitution::instantiate_metavars_wo_jst(expr const & e, bool inst_local_types) {
return instantiate_metavars_fn(*this, false, inst_local_types)(e);
}
static name_set merge(name_set s1, name_set const & s2) {
s2.for_each([&](name const & n) { s1.insert(n); });
return s1;
}
static bool all_unassigned(substitution const & subst, name_set const & s) {
return !s.find_if([&](name const & m) { return subst.is_expr_assigned(m); });
}
name_set substitution::get_occs(name const & m, name_set & fresh) {
lean_assert(is_expr_assigned(m));
check_system("substitution occurs check");
if (fresh.contains(m)) {
return *m_occs_map.find(m);
} else if (name_set const * it = m_occs_map.find(m)) {
name_set curr_occs = *it;
if (all_unassigned(*this, curr_occs)) {
return curr_occs;
}
name_set new_occs;
curr_occs.for_each([&](name const & n) {
if (is_expr_assigned(n)) {
new_occs = merge(new_occs, get_occs(n, fresh));
} else {
// we need to update
new_occs.insert(n);
}
});
m_occs_map.insert(m, new_occs);
fresh.insert(m);
return new_occs;
} else {
expr e = *get_expr(m);
name_set occs;
::lean::for_each(e, [&](expr const & e, unsigned) {
if (!has_expr_metavar(e)) return false;
if (is_local(e)) return false; // do not process type
if (is_metavar(e)) {
name const & n = mlocal_name(e);
if (is_expr_assigned(n)) {
occs = merge(occs, get_occs(n, fresh));
} else {
occs.insert(n);
}
return false;
}
return true;
});
m_occs_map.insert(m, occs);
fresh.insert(m);
return occs;
}
}
bool substitution::occurs_expr(name const & m, expr const & e) {
if (!has_expr_metavar(e))
return false;
name_set fresh;
bool found = false;
for_each(e, [&](expr const & e, unsigned) {
if (found || !has_expr_metavar(e)) return false;
if (is_metavar(e)) {
name const & n = mlocal_name(e);
if (is_expr_assigned(n)) {
if (get_occs(n, fresh).contains(m))
found = true;
} else if (n == m) {
found = true;
}
return false; // do not visit type
}
if (is_local(e)) return false; // do not visit type
return true;
});
return found;
}
}
<|endoftext|> |
<commit_before>#include "kraken_headers.hpp"
#include "krakendb.hpp"
#include "quickfile.hpp"
#include <sys/stat.h>
#include <sys/mman.h>
#include <errno.h>
#include <string.h>
#include <stdarg.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
// #define TEST_TAXA
using namespace std;
using namespace kraken;
static const char * INDEX = "database.idx";
static const char * DB = "database.kdb";
static const uint64_t NT_MASK = uint64_t(3) << 62;
char* kmerInterpreter(uint64_t kmer, uint8_t k) {
char* res = new char[k];
kmer <<= (sizeof(kmer) * 8) - (k * 2);
for(int i=0; i<k; i++) {
switch ((kmer & NT_MASK) >> 62) {
case 0:
res[i] = 'A';
break;
case 1:
res[i] = 'C';
break;
case 2:
res[i] = 'G';
break;
case 3:
res[i] = 'T';
break;
}
kmer <<= 2;
}
return res;
}
void test_taxa(KrakenDB db, uint64_t kmer, uint32_t taxid,
uint64_t val_len, ofstream err_file)
{
uint64_t last_bin_key = 0;
int64_t min_pos = 1;
int64_t max_pos = 0;
uint32_t taxid_e = 0;
uint32_t* kmer_pos = db.kmer_query(kmer,&last_bin_key,
&min_pos,&max_pos,true);
memcpy(&taxid_e, kmer_pos, val_len);
err_file << "exp:\t" << taxid_e << endl;
err_file << "act:\t" << taxid << endl;
}
int main() {
#ifdef TEST_TAXA
ofstream err_file;
err_file.open("trans_kra.log");
#endif
QuickFile idx_file(INDEX);
KrakenDBIndex idx(idx_file.ptr());
idx_file.load_file();
QuickFile db_file(DB);
KrakenDB db(db_file.ptr());
db.set_index(&idx);
db_file.load_file();
// Return pointer to start of pairs
char* pairs = db.get_pair_ptr();
// how many bits are in each key?
uint64_t key_bits = db.get_key_bits();
// how many bytes does each key occupy?
uint64_t key_len = db.get_key_len();
// how many bytes does each value occupy?
uint64_t val_len = db.get_val_len();
// how many key/value pairs are there?
uint64_t key_ct = db.get_key_ct();
// how many bytes does each pair occupy?
uint64_t pair_size = db.pair_size();
uint64_t* offsets = idx.get_array();
uint64_t nt = idx.indexed_nt();
uint64_t n_bins = (1ull << (2 * nt)) + 1;
uint64_t bin_len = 64*key_ct/n_bins;
uint64_t mask = (1ull << key_bits) -1;
char* bin = (char*) malloc(bin_len*pair_size);
uint64_t* kmers = (uint64_t*) calloc(bin_len, sizeof(uint64_t));
uint32_t* taxa = (uint32_t*) calloc(bin_len, sizeof(uint32_t));
uint64_t* temp_kmers;
uint32_t* temp_taxa;
uint64_t start = 0, stop = 0, len = 0;
uint64_t kmer_id = 1;
for(uint64_t* temp_offsets = offsets+1;
temp_offsets < offsets+300; temp_offsets++)
{
temp_kmers = kmers;
temp_taxa = taxa;
start = stop;
stop = *temp_offsets;
len = stop - start;
if (start < stop) {
if (len > bin_len) {
bin_len = 2*len;
bin = (char*) realloc(bin, bin_len*pair_size);
kmers = (uint64_t*) realloc(kmers, bin_len*sizeof(uint64_t));
taxa = (uint32_t*) realloc(taxa, bin_len*sizeof(uint32_t));
temp_kmers = kmers;
temp_taxa = taxa;
}
memcpy(bin, pairs + (start * pair_size), len * pair_size);
for(char* next_pair = bin;
next_pair < bin + (len*pair_size);
next_pair += pair_size)
{
memcpy(temp_kmers, next_pair, key_len);
memcpy(temp_taxa, next_pair+key_len, val_len);
*temp_kmers &= mask;
#ifdef TEST_TAXA
test_taxa(db, *temp_kmers, *temp_taxa, val_len, err_file);
#endif
temp_kmers++;
temp_taxa++;
}
for(temp_kmers = kmers, temp_taxa = taxa;
temp_kmers < kmers + len;
temp_kmers++, temp_taxa++)
{
cout << ">kmer|" << kmer_id++ << "|taxid|" << *temp_taxa << endl;
cout << kmerInterpreter(*temp_kmers, key_bits/2) << endl << endl;
}
}
}
free(bin);
free(kmers);
free(taxa);
return 0;
}
<commit_msg>Typo<commit_after>#include "kraken_headers.hpp"
#include "krakendb.hpp"
#include "quickfile.hpp"
#include <sys/stat.h>
#include <sys/mman.h>
#include <errno.h>
#include <string.h>
#include <stdarg.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
// #define TEST_TAXA
using namespace std;
using namespace kraken;
static const char * INDEX = "database.idx";
static const char * DB = "database.kdb";
static const uint64_t NT_MASK = uint64_t(3) << 62;
char* kmerInterpreter(uint64_t kmer, uint8_t k) {
char* res = new char[k];
kmer <<= (sizeof(kmer) * 8) - (k * 2);
for(int i=0; i<k; i++) {
switch ((kmer & NT_MASK) >> 62) {
case 0:
res[i] = 'A';
break;
case 1:
res[i] = 'C';
break;
case 2:
res[i] = 'G';
break;
case 3:
res[i] = 'T';
break;
}
kmer <<= 2;
}
return res;
}
void test_taxa(KrakenDB db, uint64_t kmer, uint32_t taxid,
uint64_t val_len, ofstream err_file)
{
uint64_t last_bin_key = 0;
int64_t min_pos = 1;
int64_t max_pos = 0;
uint32_t taxid_e = 0;
uint32_t* kmer_pos = db.kmer_query(kmer,&last_bin_key,
&min_pos,&max_pos,true);
memcpy(&taxid_e, kmer_pos, val_len);
err_file << "exp:\t" << taxid_e << endl;
err_file << "act:\t" << taxid << endl;
}
int main() {
#ifdef TEST_TAXA
ofstream err_file;
err_file.open("trans_kra.log");
#endif
QuickFile idx_file(INDEX);
KrakenDBIndex idx(idx_file.ptr());
idx_file.load_file();
QuickFile db_file(DB);
KrakenDB db(db_file.ptr());
db.set_index(&idx);
db_file.load_file();
// Return pointer to start of pairs
char* pairs = db.get_pair_ptr();
// how many bits are in each key?
uint64_t key_bits = db.get_key_bits();
// how many bytes does each key occupy?
uint64_t key_len = db.get_key_len();
// how many bytes does each value occupy?
uint64_t val_len = db.get_val_len();
// how many key/value pairs are there?
uint64_t key_ct = db.get_key_ct();
// how many bytes does each pair occupy?
uint64_t pair_size = db.pair_size();
uint64_t* offsets = idx.get_array();
uint64_t nt = idx.indexed_nt();
uint64_t n_bins = (1ull << (2 * nt)) + 1;
uint64_t bin_len = 64*key_ct/n_bins;
uint64_t mask = (1ull << key_bits) -1;
char* bin = (char*) malloc(bin_len*pair_size);
uint64_t* kmers = (uint64_t*) calloc(bin_len, sizeof(uint64_t));
uint32_t* taxa = (uint32_t*) calloc(bin_len, sizeof(uint32_t));
uint64_t* temp_kmers;
uint32_t* temp_taxa;
uint64_t start = 0, stop = 0, len = 0;
uint64_t kmer_id = 1;
for(uint64_t* temp_offsets = offsets+1;
temp_offsets < n_bins; temp_offsets++)
{
temp_kmers = kmers;
temp_taxa = taxa;
start = stop;
stop = *temp_offsets;
len = stop - start;
if (start < stop) {
if (len > bin_len) {
bin_len = 2*len;
bin = (char*) realloc(bin, bin_len*pair_size);
kmers = (uint64_t*) realloc(kmers, bin_len*sizeof(uint64_t));
taxa = (uint32_t*) realloc(taxa, bin_len*sizeof(uint32_t));
temp_kmers = kmers;
temp_taxa = taxa;
}
memcpy(bin, pairs + (start * pair_size), len * pair_size);
for(char* next_pair = bin;
next_pair < bin + (len*pair_size);
next_pair += pair_size)
{
memcpy(temp_kmers, next_pair, key_len);
memcpy(temp_taxa, next_pair+key_len, val_len);
*temp_kmers &= mask;
#ifdef TEST_TAXA
test_taxa(db, *temp_kmers, *temp_taxa, val_len, err_file);
#endif
temp_kmers++;
temp_taxa++;
}
for(temp_kmers = kmers, temp_taxa = taxa;
temp_kmers < kmers + len;
temp_kmers++, temp_taxa++)
{
cout << ">kmer|" << kmer_id++ << "|taxid|" << *temp_taxa << endl;
cout << kmerInterpreter(*temp_kmers, key_bits/2) << endl << endl;
}
}
}
free(bin);
free(kmers);
free(taxa);
return 0;
}
<|endoftext|> |
<commit_before>//
// This file is part of the Marble Desktop Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2006-2007 Torsten Rahn <[email protected]>"
// Copyright 2007 Inge Wallin <[email protected]>"
//
#include "Quaternion.h"
#include <cmath>
#include <QtCore/QString>
#include <QtCore/QDebug>
#define quatNorm (v[Q_W] * v[Q_W] + v[Q_X] * v[Q_X] + v[Q_Y] * v[Q_Y] + v[Q_Z] * v[Q_Z])
Quaternion::Quaternion()
{
// like in libeigen we keep the quaternion uninitialized
// set( 1.0, 0.0, 0.0, 0.0 );
}
Quaternion::Quaternion(double w, double x, double y, double z)
{
set( w, x, y, z );
}
Quaternion::Quaternion(double alpha, double beta)
{
v[Q_W] = 0.0;
const double cosBeta = cos(beta);
v[Q_X] = -cosBeta * sin(alpha);
v[Q_Y] = -sin(beta);
v[Q_Z] = cosBeta * cos(alpha);
}
void Quaternion::normalize()
{
scalar( 1.0 / sqrt(quatNorm) );
}
void Quaternion::scalar(double mult)
{
v[Q_W] *= mult;
v[Q_X] *= mult;
v[Q_Y] *= mult;
v[Q_Z] *= mult;
}
Quaternion Quaternion::inverse() const
{
Quaternion inverse( v[Q_W], -v[Q_X], -v[Q_Y], -v[Q_Z] );
inverse.normalize();
return inverse;
}
void Quaternion::createFromEuler(double pitch, double yaw, double roll)
{
double cX, cY, cZ, sX, sY, sZ, cYcZ, sYsZ, sYcZ, cYsZ;
pitch *= 0.5;
yaw *= 0.5;
roll *= 0.5;
cX = cos(pitch);
cY = cos(yaw);
cZ = cos(roll);
sX = sin(pitch);
sY = sin(yaw);
sZ = sin(roll);
cYcZ = cY * cZ;
sYsZ = sY * sZ;
sYcZ = sY * cZ;
cYsZ = cY * sZ;
v[Q_W] = cX * cYcZ + sX * sYsZ;
v[Q_X] = sX * cYcZ - cX * sYsZ;
v[Q_Y] = cX * sYcZ + sX * cYsZ;
v[Q_Z] = cX * cYsZ - sX * sYcZ;
}
double Quaternion::pitch() const
{
return atan2(2.0*(v[Q_W]*v[Q_X]+v[Q_Y]*v[Q_Z]),(1-2*(v[Q_X]*v[Q_X]+v[Q_Y]*v[Q_Y])));
// return atan(2.0*(v[Q_W]*v[Q_X]+v[Q_Y]*v[Q_Z])/(1-2*(v[Q_X]*v[Q_X]+v[Q_Y]*v[Q_Y])));
}
double Quaternion::yaw() const
{
return asin(2.0*(v[Q_W]*v[Q_Y]-v[Q_Z]*v[Q_X]));
}
double Quaternion::roll() const
{
return atan2(2.0*(v[Q_W]*v[Q_Z]+v[Q_X]*v[Q_Y]),(1-2*(v[Q_Y]*v[Q_Y]+v[Q_Z]*v[Q_Z])));
// return atan(2.0*(v[Q_W]*v[Q_Z]+v[Q_X]*v[Q_Y])/(1-2*(v[Q_Y]*v[Q_Y]+v[Q_Z]*v[Q_Z])));
}
void Quaternion::display() const
{
QString quatdisplay = QString("Quaternion: w= %1, x= %2, y= %3, z= %4, |q|= %5" )
.arg(v[Q_W]).arg(v[Q_X]).arg(v[Q_Y]).arg(v[Q_Z]).arg(quatNorm);
qDebug() << quatdisplay;
}
void Quaternion::operator*=(const Quaternion &q)
{
double x, y, z, w;
w = v[Q_W] * q.v[Q_W] - v[Q_X] * q.v[Q_X] - v[Q_Y] * q.v[Q_Y] - v[Q_Z] * q.v[Q_Z];
x = v[Q_W] * q.v[Q_X] + v[Q_X] * q.v[Q_W] + v[Q_Y] * q.v[Q_Z] - v[Q_Z] * q.v[Q_Y];
y = v[Q_W] * q.v[Q_Y] - v[Q_X] * q.v[Q_Z] + v[Q_Y] * q.v[Q_W] + v[Q_Z] * q.v[Q_X];
z = v[Q_W] * q.v[Q_Z] + v[Q_X] * q.v[Q_Y] - v[Q_Y] * q.v[Q_X] + v[Q_Z] * q.v[Q_W];
set( w, x, y, z );
}
bool Quaternion::operator==(const Quaternion &q) const
{
return ( v[Q_W] == q.v[Q_W]
&& v[Q_X] == q.v[Q_X]
&& v[Q_Y] == q.v[Q_Y]
&& v[Q_Z] == q.v[Q_Z] );
}
Quaternion Quaternion::operator*(const Quaternion &q) const
{
double w, x, y, z;
w = v[Q_W] * q.v[Q_W] - v[Q_X] * q.v[Q_X] - v[Q_Y] * q.v[Q_Y] - v[Q_Z] * q.v[Q_Z];
x = v[Q_W] * q.v[Q_X] + v[Q_X] * q.v[Q_W] + v[Q_Y] * q.v[Q_Z] - v[Q_Z] * q.v[Q_Y];
y = v[Q_W] * q.v[Q_Y] - v[Q_X] * q.v[Q_Z] + v[Q_Y] * q.v[Q_W] + v[Q_Z] * q.v[Q_X];
z = v[Q_W] * q.v[Q_Z] + v[Q_X] * q.v[Q_Y] - v[Q_Y] * q.v[Q_X] + v[Q_Z] * q.v[Q_W];
return Quaternion( w, x, y, z );
}
void Quaternion::rotateAroundAxis(const Quaternion &q)
{
double w, x, y, z;
w = + v[Q_X] * q.v[Q_X] + v[Q_Y] * q.v[Q_Y] + v[Q_Z] * q.v[Q_Z];
x = + v[Q_X] * q.v[Q_W] - v[Q_Y] * q.v[Q_Z] + v[Q_Z] * q.v[Q_Y];
y = + v[Q_X] * q.v[Q_Z] + v[Q_Y] * q.v[Q_W] - v[Q_Z] * q.v[Q_X];
z = - v[Q_X] * q.v[Q_Y] + v[Q_Y] * q.v[Q_X] + v[Q_Z] * q.v[Q_W];
v[Q_W] = q.v[Q_W] * w - q.v[Q_X] * x - q.v[Q_Y] * y - q.v[Q_Z] * z;
v[Q_X] = q.v[Q_W] * x + q.v[Q_X] * w + q.v[Q_Y] * z - q.v[Q_Z] * y;
v[Q_Y] = q.v[Q_W] * y - q.v[Q_X] * z + q.v[Q_Y] * w + q.v[Q_Z] * x;
v[Q_Z] = q.v[Q_W] * z + q.v[Q_X] * y - q.v[Q_Y] * x + q.v[Q_Z] * w;
}
void Quaternion::slerp(const Quaternion q1, const Quaternion q2, double t)
{
double p1, p2;
double cosAlpha = ( q1.v[Q_X]*q2.v[Q_X] + q1.v[Q_Y]*q2.v[Q_Y]
+ q1.v[Q_Z]*q2.v[Q_Z] + q1.v[Q_W]*q2.v[Q_W] );
double alpha = acos(cosAlpha);
double sinAlpha = sin(alpha);
if( sinAlpha > 0.0 ) {
p1 = sin( (1.0-t)*alpha ) / sinAlpha;
p2 = sin( t*alpha ) / sinAlpha;
} else {
// both Quaternions are equal
p1 = 1.0;
p2 = 0.0;
}
v[Q_X] = p1*q1.v[Q_X] + p2*q2.v[Q_X];
v[Q_Y] = p1*q1.v[Q_Y] + p2*q2.v[Q_Y];
v[Q_Z] = p1*q1.v[Q_Z] + p2*q2.v[Q_Z];
v[Q_W] = p1*q1.v[Q_W] + p2*q2.v[Q_W];
}
void Quaternion::getSpherical(double &alpha, double &beta) const
{
double y = v[Q_Y];
if ( y > 1.0 )
y = 1.0;
else if ( y < -1.0 )
y = -1.0;
beta = -asin( y );
if(v[Q_X] * v[Q_X] + v[Q_Z] * v[Q_Z] > 0.00005)
alpha = -atan2(v[Q_X], v[Q_Z]);
else
alpha = 0.0;
}
void Quaternion::toMatrix(matrix &m) const
{
double xy = v[Q_X] * v[Q_Y], xz = v[Q_X] * v[Q_Z];
double yy = v[Q_Y] * v[Q_Y], yw = v[Q_Y] * v[Q_W];
double zw = v[Q_Z] * v[Q_W], zz = v[Q_Z] * v[Q_Z];
m[0][0] = 1.0 - 2.0 * (yy + zz);
m[0][1] = 2.0 * (xy + zw);
m[0][2] = 2.0 * (xz - yw);
m[0][3] = 0.0;
double xx = v[Q_X] * v[Q_X], xw = v[Q_X] * v[Q_W], yz = v[Q_Y] * v[Q_Z];
m[1][0] = 2.0 * (xy - zw);
m[1][1] = 1.0 - 2.0 * (xx + zz);
m[1][2] = 2.0 * (yz + xw);
m[1][3] = 0.0;
m[2][0] = 2.0 * (xz + yw);
m[2][1] = 2.0 * (yz - xw);
m[2][2] = 1.0 - 2.0 * (xx + yy);
m[2][3] = 0.0;
}
void Quaternion::rotateAroundAxis(const matrix &m)
{
double x, y, z;
x = m[0][0] * v[Q_X] + m[1][0] * v[Q_Y] + m[2][0] * v[Q_Z];
y = m[0][1] * v[Q_X] + m[1][1] * v[Q_Y] + m[2][1] * v[Q_Z];
z = m[0][2] * v[Q_X] + m[1][2] * v[Q_Y] + m[2][2] * v[Q_Z];
v[Q_W] = 1.0; v[Q_X] = x; v[Q_Y] = y; v[Q_Z] = z;
}
<commit_msg>fix wrong indentation mistakenly introduced by tackat<commit_after>//
// This file is part of the Marble Desktop Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2006-2007 Torsten Rahn <[email protected]>"
// Copyright 2007 Inge Wallin <[email protected]>"
//
#include "Quaternion.h"
#include <cmath>
#include <QtCore/QString>
#include <QtCore/QDebug>
#define quatNorm (v[Q_W] * v[Q_W] + v[Q_X] * v[Q_X] + v[Q_Y] * v[Q_Y] + v[Q_Z] * v[Q_Z])
Quaternion::Quaternion()
{
// like in libeigen we keep the quaternion uninitialized
// set( 1.0, 0.0, 0.0, 0.0 );
}
Quaternion::Quaternion(double w, double x, double y, double z)
{
set( w, x, y, z );
}
Quaternion::Quaternion(double alpha, double beta)
{
v[Q_W] = 0.0;
const double cosBeta = cos(beta);
v[Q_X] = -cosBeta * sin(alpha);
v[Q_Y] = -sin(beta);
v[Q_Z] = cosBeta * cos(alpha);
}
void Quaternion::normalize()
{
scalar( 1.0 / sqrt(quatNorm) );
}
void Quaternion::scalar(double mult)
{
v[Q_W] *= mult;
v[Q_X] *= mult;
v[Q_Y] *= mult;
v[Q_Z] *= mult;
}
Quaternion Quaternion::inverse() const
{
Quaternion inverse( v[Q_W], -v[Q_X], -v[Q_Y], -v[Q_Z] );
inverse.normalize();
return inverse;
}
void Quaternion::createFromEuler(double pitch, double yaw, double roll)
{
double cX, cY, cZ, sX, sY, sZ, cYcZ, sYsZ, sYcZ, cYsZ;
pitch *= 0.5;
yaw *= 0.5;
roll *= 0.5;
cX = cos(pitch);
cY = cos(yaw);
cZ = cos(roll);
sX = sin(pitch);
sY = sin(yaw);
sZ = sin(roll);
cYcZ = cY * cZ;
sYsZ = sY * sZ;
sYcZ = sY * cZ;
cYsZ = cY * sZ;
v[Q_W] = cX * cYcZ + sX * sYsZ;
v[Q_X] = sX * cYcZ - cX * sYsZ;
v[Q_Y] = cX * sYcZ + sX * cYsZ;
v[Q_Z] = cX * cYsZ - sX * sYcZ;
}
double Quaternion::pitch() const
{
return atan2(2.0*(v[Q_W]*v[Q_X]+v[Q_Y]*v[Q_Z]),(1-2*(v[Q_X]*v[Q_X]+v[Q_Y]*v[Q_Y])));
// return atan(2.0*(v[Q_W]*v[Q_X]+v[Q_Y]*v[Q_Z])/(1-2*(v[Q_X]*v[Q_X]+v[Q_Y]*v[Q_Y])));
}
double Quaternion::yaw() const
{
return asin(2.0*(v[Q_W]*v[Q_Y]-v[Q_Z]*v[Q_X]));
}
double Quaternion::roll() const
{
return atan2(2.0*(v[Q_W]*v[Q_Z]+v[Q_X]*v[Q_Y]),(1-2*(v[Q_Y]*v[Q_Y]+v[Q_Z]*v[Q_Z])));
// return atan(2.0*(v[Q_W]*v[Q_Z]+v[Q_X]*v[Q_Y])/(1-2*(v[Q_Y]*v[Q_Y]+v[Q_Z]*v[Q_Z])));
}
void Quaternion::display() const
{
QString quatdisplay = QString("Quaternion: w= %1, x= %2, y= %3, z= %4, |q|= %5" )
.arg(v[Q_W]).arg(v[Q_X]).arg(v[Q_Y]).arg(v[Q_Z]).arg(quatNorm);
qDebug() << quatdisplay;
}
void Quaternion::operator*=(const Quaternion &q)
{
double x, y, z, w;
w = v[Q_W] * q.v[Q_W] - v[Q_X] * q.v[Q_X] - v[Q_Y] * q.v[Q_Y] - v[Q_Z] * q.v[Q_Z];
x = v[Q_W] * q.v[Q_X] + v[Q_X] * q.v[Q_W] + v[Q_Y] * q.v[Q_Z] - v[Q_Z] * q.v[Q_Y];
y = v[Q_W] * q.v[Q_Y] - v[Q_X] * q.v[Q_Z] + v[Q_Y] * q.v[Q_W] + v[Q_Z] * q.v[Q_X];
z = v[Q_W] * q.v[Q_Z] + v[Q_X] * q.v[Q_Y] - v[Q_Y] * q.v[Q_X] + v[Q_Z] * q.v[Q_W];
set( w, x, y, z );
}
bool Quaternion::operator==(const Quaternion &q) const
{
return ( v[Q_W] == q.v[Q_W]
&& v[Q_X] == q.v[Q_X]
&& v[Q_Y] == q.v[Q_Y]
&& v[Q_Z] == q.v[Q_Z] );
}
Quaternion Quaternion::operator*(const Quaternion &q) const
{
double w, x, y, z;
w = v[Q_W] * q.v[Q_W] - v[Q_X] * q.v[Q_X] - v[Q_Y] * q.v[Q_Y] - v[Q_Z] * q.v[Q_Z];
x = v[Q_W] * q.v[Q_X] + v[Q_X] * q.v[Q_W] + v[Q_Y] * q.v[Q_Z] - v[Q_Z] * q.v[Q_Y];
y = v[Q_W] * q.v[Q_Y] - v[Q_X] * q.v[Q_Z] + v[Q_Y] * q.v[Q_W] + v[Q_Z] * q.v[Q_X];
z = v[Q_W] * q.v[Q_Z] + v[Q_X] * q.v[Q_Y] - v[Q_Y] * q.v[Q_X] + v[Q_Z] * q.v[Q_W];
return Quaternion( w, x, y, z );
}
void Quaternion::rotateAroundAxis(const Quaternion &q)
{
double w, x, y, z;
w = + v[Q_X] * q.v[Q_X] + v[Q_Y] * q.v[Q_Y] + v[Q_Z] * q.v[Q_Z];
x = + v[Q_X] * q.v[Q_W] - v[Q_Y] * q.v[Q_Z] + v[Q_Z] * q.v[Q_Y];
y = + v[Q_X] * q.v[Q_Z] + v[Q_Y] * q.v[Q_W] - v[Q_Z] * q.v[Q_X];
z = - v[Q_X] * q.v[Q_Y] + v[Q_Y] * q.v[Q_X] + v[Q_Z] * q.v[Q_W];
v[Q_W] = q.v[Q_W] * w - q.v[Q_X] * x - q.v[Q_Y] * y - q.v[Q_Z] * z;
v[Q_X] = q.v[Q_W] * x + q.v[Q_X] * w + q.v[Q_Y] * z - q.v[Q_Z] * y;
v[Q_Y] = q.v[Q_W] * y - q.v[Q_X] * z + q.v[Q_Y] * w + q.v[Q_Z] * x;
v[Q_Z] = q.v[Q_W] * z + q.v[Q_X] * y - q.v[Q_Y] * x + q.v[Q_Z] * w;
}
void Quaternion::slerp(const Quaternion q1, const Quaternion q2, double t)
{
double p1, p2;
double cosAlpha = ( q1.v[Q_X]*q2.v[Q_X] + q1.v[Q_Y]*q2.v[Q_Y]
+ q1.v[Q_Z]*q2.v[Q_Z] + q1.v[Q_W]*q2.v[Q_W] );
double alpha = acos(cosAlpha);
double sinAlpha = sin(alpha);
if( sinAlpha > 0.0 ) {
p1 = sin( (1.0-t)*alpha ) / sinAlpha;
p2 = sin( t*alpha ) / sinAlpha;
} else {
// both Quaternions are equal
p1 = 1.0;
p2 = 0.0;
}
v[Q_X] = p1*q1.v[Q_X] + p2*q2.v[Q_X];
v[Q_Y] = p1*q1.v[Q_Y] + p2*q2.v[Q_Y];
v[Q_Z] = p1*q1.v[Q_Z] + p2*q2.v[Q_Z];
v[Q_W] = p1*q1.v[Q_W] + p2*q2.v[Q_W];
}
void Quaternion::getSpherical(double &alpha, double &beta) const
{
double y = v[Q_Y];
if ( y > 1.0 )
y = 1.0;
else if ( y < -1.0 )
y = -1.0;
beta = -asin( y );
if(v[Q_X] * v[Q_X] + v[Q_Z] * v[Q_Z] > 0.00005)
alpha = -atan2(v[Q_X], v[Q_Z]);
else
alpha = 0.0;
}
void Quaternion::toMatrix(matrix &m) const
{
double xy = v[Q_X] * v[Q_Y], xz = v[Q_X] * v[Q_Z];
double yy = v[Q_Y] * v[Q_Y], yw = v[Q_Y] * v[Q_W];
double zw = v[Q_Z] * v[Q_W], zz = v[Q_Z] * v[Q_Z];
m[0][0] = 1.0 - 2.0 * (yy + zz);
m[0][1] = 2.0 * (xy + zw);
m[0][2] = 2.0 * (xz - yw);
m[0][3] = 0.0;
double xx = v[Q_X] * v[Q_X], xw = v[Q_X] * v[Q_W], yz = v[Q_Y] * v[Q_Z];
m[1][0] = 2.0 * (xy - zw);
m[1][1] = 1.0 - 2.0 * (xx + zz);
m[1][2] = 2.0 * (yz + xw);
m[1][3] = 0.0;
m[2][0] = 2.0 * (xz + yw);
m[2][1] = 2.0 * (yz - xw);
m[2][2] = 1.0 - 2.0 * (xx + yy);
m[2][3] = 0.0;
}
void Quaternion::rotateAroundAxis(const matrix &m)
{
double x, y, z;
x = m[0][0] * v[Q_X] + m[1][0] * v[Q_Y] + m[2][0] * v[Q_Z];
y = m[0][1] * v[Q_X] + m[1][1] * v[Q_Y] + m[2][1] * v[Q_Z];
z = m[0][2] * v[Q_X] + m[1][2] * v[Q_Y] + m[2][2] * v[Q_Z];
v[Q_W] = 1.0; v[Q_X] = x; v[Q_Y] = y; v[Q_Z] = z;
}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* This file is part of the libkeynote project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <cassert>
#include "KNCollectorBase.h"
#include "KNDictionary.h"
#include "KNText.h"
namespace libkeynote
{
KNCollectorBase::KNCollectorBase(KNDictionary &dict)
: m_dict(dict)
, m_objectsStack()
, m_currentGeometry()
, m_currentText()
, m_collecting(false)
, m_layerOpened(false)
, m_groupLevel(0)
{
}
KNCollectorBase::~KNCollectorBase()
{
assert(!m_collecting);
assert(m_objectsStack.empty());
}
void KNCollectorBase::collectCharacterStyle(const ID_t &id, const KNStylePtr_t &style)
{
if (m_collecting)
m_dict.characterStyles[id] = style;
}
void KNCollectorBase::collectGraphicStyle(const ID_t &id, const KNStylePtr_t &style)
{
if (m_collecting)
m_dict.graphicStyles[id] = style;
}
void KNCollectorBase::collectHeadlineStyle(const ID_t &id, const KNStylePtr_t &style)
{
if (m_collecting)
m_dict.headlineStyles[id] = style;
}
void KNCollectorBase::collectLayoutStyle(const ID_t &id, const KNStylePtr_t &style)
{
if (m_collecting)
m_dict.layoutStyles[id] = style;
}
void KNCollectorBase::collectParagraphStyle(const ID_t &id, const KNStylePtr_t &style)
{
if (m_collecting)
m_dict.paragraphStyles[id] = style;
}
void KNCollectorBase::collectGeometry(const ID_t &, const KNGeometryPtr_t &geometry)
{
if (m_collecting)
m_currentGeometry = geometry;
}
void KNCollectorBase::collectGroup(const ID_t &, const KNGroupPtr_t &group)
{
if (m_collecting)
{
assert(!m_objectsStack.empty());
group->objects = m_objectsStack.top();
m_objectsStack.pop();
assert(!m_objectsStack.empty());
m_objectsStack.top().push_back(makeObject(group));
}
}
void KNCollectorBase::collectImage(const ID_t &id, const KNImagePtr_t &image)
{
if (m_collecting)
{
assert(!m_objectsStack.empty());
image->geometry = m_currentGeometry;
m_currentGeometry.reset();
m_dict.images[id] = image;
m_objectsStack.top().push_back(makeObject(image));
}
}
void KNCollectorBase::collectLine(const ID_t &, const KNLinePtr_t &line)
{
if (m_collecting)
{
assert(!m_objectsStack.empty());
line->geometry = m_currentGeometry;
m_currentGeometry.reset();
m_objectsStack.top().push_back(makeObject(line));
}
}
void KNCollectorBase::collectMedia(const ID_t &, const KNMediaPtr_t &media)
{
if (m_collecting)
{
assert(!m_objectsStack.empty());
media->geometry = m_currentGeometry;
m_currentGeometry.reset();
m_objectsStack.top().push_back(makeObject(media));
}
}
void KNCollectorBase::collectPath(const ID_t &, const KNPathPtr_t &path)
{
if (m_collecting)
{
assert(!m_objectsStack.empty());
path->setGeometry(m_currentGeometry);
m_currentGeometry.reset();
m_objectsStack.top().push_back(makeObject(path));
}
}
void KNCollectorBase::collectLayer(const ID_t &, bool)
{
if (m_collecting)
{
assert(m_layerOpened);
assert(!m_objectsStack.empty());
m_currentLayer.reset(new KNLayer());
m_currentLayer->objects = m_objectsStack.top();
m_objectsStack.pop();
}
}
void KNCollectorBase::collectText(const std::string &text, const ID_t &style)
{
if (m_collecting)
{
assert(bool(m_currentText));
m_currentText->insertText(text, m_dict.characterStyles[style]);
}
}
void KNCollectorBase::collectTab()
{
if (m_collecting)
{
assert(bool(m_currentText));
m_currentText->insertTab();
}
}
void KNCollectorBase::collectLineBreak()
{
if (m_collecting)
{
assert(bool(m_currentText));
m_currentText->insertLineBreak();
}
}
void KNCollectorBase::collectSlideText(const ID_t &id, const bool title)
{
if (m_collecting)
{
assert(!m_objectsStack.empty());
KNTextBodyPtr_t textBody(new KNTextBody(title));
textBody->geometry = m_currentGeometry;
textBody->text = m_currentText;
if (title)
m_dict.titlePlaceholders[id] = textBody;
else
m_dict.bodyPlaceholders[id] = textBody;
m_objectsStack.top().push_back(makeObject(textBody));
m_currentGeometry.reset();
m_currentText.reset();
}
}
void KNCollectorBase::startLayer()
{
if (m_collecting)
{
assert(!m_layerOpened);
assert(m_objectsStack.empty());
assert(!m_currentLayer);
m_objectsStack.push(KNObjectList_t());
m_layerOpened = true;
assert(!m_objectsStack.empty());
}
}
void KNCollectorBase::endLayer()
{
if (m_collecting)
{
assert(m_layerOpened);
// object stack is already cleared by collectLayer()
assert(m_objectsStack.empty());
m_currentLayer.reset();
m_layerOpened = false;
assert(m_objectsStack.empty());
}
}
void KNCollectorBase::startGroup()
{
if (m_collecting)
{
assert(m_layerOpened);
assert(!m_objectsStack.empty());
m_objectsStack.push(KNObjectList_t());
++m_groupLevel;
}
}
void KNCollectorBase::endGroup()
{
if (m_collecting)
{
assert(m_layerOpened);
assert(!m_objectsStack.empty());
assert(m_groupLevel > 0);
--m_groupLevel;
// stack is popped in collectGroup already
}
}
void KNCollectorBase::startParagraph(const ID_t &style)
{
if (m_collecting)
{
assert(bool(m_currentText));
m_currentText->openParagraph(m_dict.paragraphStyles[style]);
}
}
void KNCollectorBase::endParagraph()
{
if (m_collecting)
{
assert(bool(m_currentText));
m_currentText->closeParagraph();
}
}
void KNCollectorBase::startTextLayout(const ID_t &style)
{
if (m_collecting)
{
assert(!m_currentText);
m_currentText.reset(new KNText());
const KNStylePtr_t layoutStyle = m_dict.layoutStyles[style];
m_currentText->setLayoutStyle(layoutStyle);
}
}
void KNCollectorBase::endTextLayout()
{
if (m_collecting)
{
assert(bool(m_currentText));
m_currentText.reset();
}
}
bool KNCollectorBase::getCollecting() const
{
return m_collecting;
}
void KNCollectorBase::setCollecting(bool collecting)
{
m_collecting = collecting;
}
const KNLayerPtr_t &KNCollectorBase::getLayer() const
{
return m_currentLayer;
}
} // namespace libkeynote
/* vim:set shiftwidth=2 softtabstop=2 expandtab: */
<commit_msg>do not process text placeholders for now<commit_after>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* This file is part of the libkeynote project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <cassert>
#include "KNCollectorBase.h"
#include "KNDictionary.h"
#include "KNText.h"
namespace libkeynote
{
KNCollectorBase::KNCollectorBase(KNDictionary &dict)
: m_dict(dict)
, m_objectsStack()
, m_currentGeometry()
, m_currentText()
, m_collecting(false)
, m_layerOpened(false)
, m_groupLevel(0)
{
}
KNCollectorBase::~KNCollectorBase()
{
assert(!m_collecting);
assert(m_objectsStack.empty());
}
void KNCollectorBase::collectCharacterStyle(const ID_t &id, const KNStylePtr_t &style)
{
if (m_collecting)
m_dict.characterStyles[id] = style;
}
void KNCollectorBase::collectGraphicStyle(const ID_t &id, const KNStylePtr_t &style)
{
if (m_collecting)
m_dict.graphicStyles[id] = style;
}
void KNCollectorBase::collectHeadlineStyle(const ID_t &id, const KNStylePtr_t &style)
{
if (m_collecting)
m_dict.headlineStyles[id] = style;
}
void KNCollectorBase::collectLayoutStyle(const ID_t &id, const KNStylePtr_t &style)
{
if (m_collecting)
m_dict.layoutStyles[id] = style;
}
void KNCollectorBase::collectParagraphStyle(const ID_t &id, const KNStylePtr_t &style)
{
if (m_collecting)
m_dict.paragraphStyles[id] = style;
}
void KNCollectorBase::collectGeometry(const ID_t &, const KNGeometryPtr_t &geometry)
{
if (m_collecting)
m_currentGeometry = geometry;
}
void KNCollectorBase::collectGroup(const ID_t &, const KNGroupPtr_t &group)
{
if (m_collecting)
{
assert(!m_objectsStack.empty());
group->objects = m_objectsStack.top();
m_objectsStack.pop();
assert(!m_objectsStack.empty());
m_objectsStack.top().push_back(makeObject(group));
}
}
void KNCollectorBase::collectImage(const ID_t &id, const KNImagePtr_t &image)
{
if (m_collecting)
{
assert(!m_objectsStack.empty());
image->geometry = m_currentGeometry;
m_currentGeometry.reset();
m_dict.images[id] = image;
m_objectsStack.top().push_back(makeObject(image));
}
}
void KNCollectorBase::collectLine(const ID_t &, const KNLinePtr_t &line)
{
if (m_collecting)
{
assert(!m_objectsStack.empty());
line->geometry = m_currentGeometry;
m_currentGeometry.reset();
m_objectsStack.top().push_back(makeObject(line));
}
}
void KNCollectorBase::collectMedia(const ID_t &, const KNMediaPtr_t &media)
{
if (m_collecting)
{
assert(!m_objectsStack.empty());
media->geometry = m_currentGeometry;
m_currentGeometry.reset();
m_objectsStack.top().push_back(makeObject(media));
}
}
void KNCollectorBase::collectPath(const ID_t &, const KNPathPtr_t &path)
{
if (m_collecting)
{
assert(!m_objectsStack.empty());
path->setGeometry(m_currentGeometry);
m_currentGeometry.reset();
m_objectsStack.top().push_back(makeObject(path));
}
}
void KNCollectorBase::collectLayer(const ID_t &, bool)
{
if (m_collecting)
{
assert(m_layerOpened);
assert(!m_objectsStack.empty());
m_currentLayer.reset(new KNLayer());
m_currentLayer->objects = m_objectsStack.top();
m_objectsStack.pop();
}
}
void KNCollectorBase::collectText(const std::string &text, const ID_t &style)
{
if (m_collecting)
{
assert(bool(m_currentText));
m_currentText->insertText(text, m_dict.characterStyles[style]);
}
}
void KNCollectorBase::collectTab()
{
if (m_collecting)
{
assert(bool(m_currentText));
m_currentText->insertTab();
}
}
void KNCollectorBase::collectLineBreak()
{
if (m_collecting)
{
assert(bool(m_currentText));
m_currentText->insertLineBreak();
}
}
void KNCollectorBase::collectSlideText(const ID_t &id, const bool title)
{
if (m_collecting)
{
// assert(!m_objectsStack.empty());
KNTextBodyPtr_t textBody(new KNTextBody(title));
textBody->geometry = m_currentGeometry;
textBody->text = m_currentText;
if (title)
m_dict.titlePlaceholders[id] = textBody;
else
m_dict.bodyPlaceholders[id] = textBody;
// m_objectsStack.top().push_back(makeObject(textBody));
m_currentGeometry.reset();
m_currentText.reset();
}
}
void KNCollectorBase::startLayer()
{
if (m_collecting)
{
assert(!m_layerOpened);
assert(m_objectsStack.empty());
assert(!m_currentLayer);
m_objectsStack.push(KNObjectList_t());
m_layerOpened = true;
assert(!m_objectsStack.empty());
}
}
void KNCollectorBase::endLayer()
{
if (m_collecting)
{
assert(m_layerOpened);
// object stack is already cleared by collectLayer()
assert(m_objectsStack.empty());
m_currentLayer.reset();
m_layerOpened = false;
assert(m_objectsStack.empty());
}
}
void KNCollectorBase::startGroup()
{
if (m_collecting)
{
assert(m_layerOpened);
assert(!m_objectsStack.empty());
m_objectsStack.push(KNObjectList_t());
++m_groupLevel;
}
}
void KNCollectorBase::endGroup()
{
if (m_collecting)
{
assert(m_layerOpened);
assert(!m_objectsStack.empty());
assert(m_groupLevel > 0);
--m_groupLevel;
// stack is popped in collectGroup already
}
}
void KNCollectorBase::startParagraph(const ID_t &style)
{
if (m_collecting)
{
assert(bool(m_currentText));
m_currentText->openParagraph(m_dict.paragraphStyles[style]);
}
}
void KNCollectorBase::endParagraph()
{
if (m_collecting)
{
assert(bool(m_currentText));
m_currentText->closeParagraph();
}
}
void KNCollectorBase::startTextLayout(const ID_t &style)
{
if (m_collecting)
{
assert(!m_currentText);
m_currentText.reset(new KNText());
const KNStylePtr_t layoutStyle = m_dict.layoutStyles[style];
m_currentText->setLayoutStyle(layoutStyle);
}
}
void KNCollectorBase::endTextLayout()
{
if (m_collecting)
{
assert(bool(m_currentText));
m_currentText.reset();
}
}
bool KNCollectorBase::getCollecting() const
{
return m_collecting;
}
void KNCollectorBase::setCollecting(bool collecting)
{
m_collecting = collecting;
}
const KNLayerPtr_t &KNCollectorBase::getLayer() const
{
return m_currentLayer;
}
} // namespace libkeynote
/* vim:set shiftwidth=2 softtabstop=2 expandtab: */
<|endoftext|> |
<commit_before>/*
*
* Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Orion Context Broker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* fermin at tid dot es
*
* Author: Fermin Galan
*/
#include <semaphore.h>
#include <errno.h>
#include "logMsg/logMsg.h"
#include "logMsg/traceLevels.h"
#include "common/sem.h"
/* ****************************************************************************
*
* Globals -
*/
static sem_t reqSem;
static sem_t mongoSem;
/* ****************************************************************************
*
* semInit -
*
* parameter #1: 0 - the semaphore is to be shared between threads,
* parameter #2: 1 - initially the semaphore is free
*
* RETURN VALUE (of sem_init)
* 0 on success,
* -1 on failure
*
*/
int semInit(int shared, int takenInitially)
{
if (sem_init(&reqSem, shared, takenInitially) == -1)
LM_RE(1, ("Error initializing 'req' semaphore: %s\n", strerror(errno)));
if (sem_init(&mongoSem, shared, takenInitially) == -1)
LM_RE(2, ("Error initializing 'mongo' semaphore: %s\n", strerror(errno)));
LM_T(LmtReqSem, ("Initialized 'req' semaphore"));
LM_T(LmtMongoSem, ("Initialized 'mongo' semaphore"));
return 0;
}
/* ****************************************************************************
*
* reqSemTake -
*/
int reqSemTake(const char* who, const char* what)
{
int x;
LM_T(LmtReqSem, ("%s taking the 'req' semaphore for '%s'", who, what));
x = sem_wait(&reqSem);
LM_T(LmtReqSem, ("%s has the 'req' semaphore", who));
return x;
}
/* ****************************************************************************
*
* mongoSemTake -
*/
int mongoSemTake(const char* who, const char* what)
{
int x;
LM_T(LmtMongoSem, ("%s taking the 'mongo' semaphore for '%s'", who, what));
x = sem_wait(&mongoSem);
LM_T(LmtMongoSem, ("%s has the 'mongo' semaphore", who));
return x;
}
/* ****************************************************************************
*
* reqSemGive -
*/
int reqSemGive(const char* who, const char* what)
{
if (what != NULL)
LM_T(LmtReqSem, ("%s gives the 'req' semaphore for '%s'", who, what));
else
LM_T(LmtReqSem, ("%s gives the 'req' semaphore", who));
return sem_post(&reqSem);
}
/* ****************************************************************************
*
* mongoSemGive -
*/
int mongoSemGive(const char* who, const char* what)
{
if (what != NULL)
LM_T(LmtMongoSem, ("%s gives the 'mongo' semaphore for '%s'", who, what));
else
LM_T(LmtMongoSem, ("%s gives the 'mongo' semaphore", who));
return sem_post(&mongoSem);
}
<commit_msg>x -> r in sem.cpp<commit_after>/*
*
* Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Orion Context Broker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* fermin at tid dot es
*
* Author: Fermin Galan
*/
#include <semaphore.h>
#include <errno.h>
#include "logMsg/logMsg.h"
#include "logMsg/traceLevels.h"
#include "common/sem.h"
/* ****************************************************************************
*
* Globals -
*/
static sem_t reqSem;
static sem_t mongoSem;
/* ****************************************************************************
*
* semInit -
*
* parameter #1: 0 - the semaphore is to be shared between threads,
* parameter #2: 1 - initially the semaphore is free
*
* RETURN VALUE (of sem_init)
* 0 on success,
* -1 on failure
*
*/
int semInit(int shared, int takenInitially)
{
if (sem_init(&reqSem, shared, takenInitially) == -1)
LM_RE(1, ("Error initializing 'req' semaphore: %s\n", strerror(errno)));
if (sem_init(&mongoSem, shared, takenInitially) == -1)
LM_RE(2, ("Error initializing 'mongo' semaphore: %s\n", strerror(errno)));
LM_T(LmtReqSem, ("Initialized 'req' semaphore"));
LM_T(LmtMongoSem, ("Initialized 'mongo' semaphore"));
return 0;
}
/* ****************************************************************************
*
* reqSemTake -
*/
int reqSemTake(const char* who, const char* what)
{
int r;
LM_T(LmtReqSem, ("%s taking the 'req' semaphore for '%s'", who, what));
r = sem_wait(&reqSem);
LM_T(LmtReqSem, ("%s has the 'req' semaphore", who));
return r;
}
/* ****************************************************************************
*
* mongoSemTake -
*/
int mongoSemTake(const char* who, const char* what)
{
int r;
LM_T(LmtMongoSem, ("%s taking the 'mongo' semaphore for '%s'", who, what));
r = sem_wait(&mongoSem);
LM_T(LmtMongoSem, ("%s has the 'mongo' semaphore", who));
return r;
}
/* ****************************************************************************
*
* reqSemGive -
*/
int reqSemGive(const char* who, const char* what)
{
if (what != NULL)
LM_T(LmtReqSem, ("%s gives the 'req' semaphore for '%s'", who, what));
else
LM_T(LmtReqSem, ("%s gives the 'req' semaphore", who));
return sem_post(&reqSem);
}
/* ****************************************************************************
*
* mongoSemGive -
*/
int mongoSemGive(const char* who, const char* what)
{
if (what != NULL)
LM_T(LmtMongoSem, ("%s gives the 'mongo' semaphore for '%s'", who, what));
else
LM_T(LmtMongoSem, ("%s gives the 'mongo' semaphore", who));
return sem_post(&mongoSem);
}
<|endoftext|> |
<commit_before>//
// Copyright (c) 2002-2012 The ANGLE 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.
//
// Surface.cpp: Implements the egl::Surface class, representing a drawing surface
// such as the client area of a window, including any back buffers.
// Implements EGLSurface and related functionality. [EGL 1.4] section 2.2 page 3.
#include <tchar.h>
#include <algorithm>
#include "libEGL/Surface.h"
#include "common/debug.h"
#include "libGLESv2/Texture.h"
#include "libGLESv2/renderer/SwapChain.h"
#include "libGLESv2/main.h"
#include "libEGL/main.h"
#include "libEGL/Display.h"
#if defined(ANGLE_PLATFORM_WINRT)
#include "common/winrtutils.h"
#include <wrl/client.h>
#include <wrl\implements.h>
#include <wrl\module.h>
#include <wrl\event.h>
#include <wrl\wrappers\corewrappers.h>
#include <windows.applicationmodel.core.h>
using namespace ABI::Windows::UI::Core;
#endif // #if defined(ANGLE_PLATFORM_WINRT)
namespace egl
{
Surface::Surface(Display *display, const Config *config, EGLNativeWindowType window, EGLint postSubBufferSupported)
: mDisplay(display), mConfig(config), mWindow(window), mPostSubBufferSupported(postSubBufferSupported)
{
mRenderer = mDisplay->getRenderer();
mSwapChain = NULL;
mShareHandle = NULL;
mTexture = NULL;
mTextureFormat = EGL_NO_TEXTURE;
mTextureTarget = EGL_NO_TEXTURE;
mPixelAspectRatio = (EGLint)(1.0 * EGL_DISPLAY_SCALING); // FIXME: Determine actual pixel aspect ratio
mRenderBuffer = EGL_BACK_BUFFER;
mSwapBehavior = EGL_BUFFER_PRESERVED;
mSwapInterval = -1;
mWidth = -1;
mHeight = -1;
setSwapInterval(1);
subclassWindow();
}
Surface::Surface(Display *display, const Config *config, HANDLE shareHandle, EGLint width, EGLint height, EGLenum textureFormat, EGLenum textureType)
: mDisplay(display), mWindow(NULL), mConfig(config), mShareHandle(shareHandle), mWidth(width), mHeight(height), mPostSubBufferSupported(EGL_FALSE)
{
mRenderer = mDisplay->getRenderer();
mSwapChain = NULL;
mWindowSubclassed = false;
mTexture = NULL;
mTextureFormat = textureFormat;
mTextureTarget = textureType;
mPixelAspectRatio = (EGLint)(1.0 * EGL_DISPLAY_SCALING); // FIXME: Determine actual pixel aspect ratio
mRenderBuffer = EGL_BACK_BUFFER;
mSwapBehavior = EGL_BUFFER_PRESERVED;
mSwapInterval = -1;
setSwapInterval(1);
}
Surface::~Surface()
{
unsubclassWindow();
release();
}
bool Surface::initialize()
{
if (!resetSwapChain())
return false;
return true;
}
void Surface::release()
{
delete mSwapChain;
mSwapChain = NULL;
if (mTexture)
{
mTexture->releaseTexImage();
mTexture = NULL;
}
}
bool Surface::resetSwapChain()
{
ASSERT(!mSwapChain);
int width;
int height;
if (mWindow)
{
#if defined(ANGLE_PLATFORM_WINRT)
winrt::getCurrentWindowDimensions(width, height);
#else
RECT windowRect;
if (!GetClientRect(getWindowHandle(), &windowRect))
{
ASSERT(false);
ERR("Could not retrieve the window dimensions");
return error(EGL_BAD_SURFACE, false);
}
width = windowRect.right - windowRect.left;
height = windowRect.bottom - windowRect.top;
#endif // #if defined(ANGLE_PLATFORM_WINRT)
}
else
{
// non-window surface - size is determined at creation
width = mWidth;
height = mHeight;
}
mSwapChain = mRenderer->createSwapChain(mWindow, mShareHandle,
mConfig->mRenderTargetFormat,
mConfig->mDepthStencilFormat);
if (!mSwapChain)
{
return error(EGL_BAD_ALLOC, false);
}
if (!resetSwapChain(width, height))
{
delete mSwapChain;
mSwapChain = NULL;
return false;
}
return true;
}
bool Surface::resizeSwapChain(int backbufferWidth, int backbufferHeight)
{
ASSERT(backbufferWidth >= 0 && backbufferHeight >= 0);
ASSERT(mSwapChain);
EGLint status = mSwapChain->resize(backbufferWidth, backbufferHeight);
if (status == EGL_CONTEXT_LOST)
{
mDisplay->notifyDeviceLost();
return false;
}
else if (status != EGL_SUCCESS)
{
return error(status, false);
}
mWidth = backbufferWidth;
mHeight = backbufferHeight;
return true;
}
bool Surface::resetSwapChain(int backbufferWidth, int backbufferHeight)
{
ASSERT(backbufferWidth >= 0 && backbufferHeight >= 0);
ASSERT(mSwapChain);
EGLint status = mSwapChain->reset(backbufferWidth, backbufferHeight, mSwapInterval);
if (status == EGL_CONTEXT_LOST)
{
mRenderer->notifyDeviceLost();
return false;
}
else if (status != EGL_SUCCESS)
{
return error(status, false);
}
mWidth = backbufferWidth;
mHeight = backbufferHeight;
mSwapIntervalDirty = false;
return true;
}
bool Surface::swapRect(EGLint x, EGLint y, EGLint width, EGLint height)
{
if (!mSwapChain)
{
return true;
}
if (x + width > mWidth)
{
width = mWidth - x;
}
if (y + height > mHeight)
{
height = mHeight - y;
}
if (width == 0 || height == 0)
{
return true;
}
EGLint status = mSwapChain->swapRect(x, y, width, height);
if (status == EGL_CONTEXT_LOST)
{
mRenderer->notifyDeviceLost();
return false;
}
else if (status != EGL_SUCCESS)
{
return error(status, false);
}
checkForOutOfDateSwapChain();
return true;
}
EGLNativeWindowType Surface::getWindowHandle()
{
return mWindow;
}
#define kSurfaceProperty _TEXT("Egl::SurfaceOwner")
#define kParentWndProc _TEXT("Egl::SurfaceParentWndProc")
#if !defined(ANGLE_PLATFORM_WINRT)
static LRESULT CALLBACK SurfaceWindowProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam)
{
if (message == WM_SIZE)
{
Surface* surf = reinterpret_cast<Surface*>(GetProp(hwnd, kSurfaceProperty));
if(surf)
{
surf->checkForOutOfDateSwapChain();
}
}
WNDPROC prevWndFunc = reinterpret_cast<WNDPROC >(GetProp(hwnd, kParentWndProc));
return CallWindowProc(prevWndFunc, hwnd, message, wparam, lparam);
}
#endif // #if !defined(ANGLE_PLATFORM_WINRT)
void Surface::subclassWindow()
{
if (!mWindow)
{
return;
}
#if !defined(ANGLE_PLATFORM_WINRT)
DWORD processId;
DWORD threadId = GetWindowThreadProcessId(mWindow, &processId);
if (processId != GetCurrentProcessId() || threadId != GetCurrentThreadId())
{
return;
}
SetLastError(0);
LONG_PTR oldWndProc = SetWindowLongPtr(mWindow, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(SurfaceWindowProc));
if(oldWndProc == 0 && GetLastError() != ERROR_SUCCESS)
{
mWindowSubclassed = false;
return;
}
SetProp(mWindow, kSurfaceProperty, reinterpret_cast<HANDLE>(this));
SetProp(mWindow, kParentWndProc, reinterpret_cast<HANDLE>(oldWndProc));
#endif // #if !defined(ANGLE_PLATFORM_WINRT)
mWindowSubclassed = true;
}
void Surface::unsubclassWindow()
{
if(!mWindowSubclassed)
{
return;
}
#if !defined(ANGLE_PLATFORM_WINRT)
// un-subclass
LONG_PTR parentWndFunc = reinterpret_cast<LONG_PTR>(GetProp(mWindow, kParentWndProc));
// Check the windowproc is still SurfaceWindowProc.
// If this assert fails, then it is likely the application has subclassed the
// hwnd as well and did not unsubclass before destroying its EGL context. The
// application should be modified to either subclass before initializing the
// EGL context, or to unsubclass before destroying the EGL context.
if(parentWndFunc)
{
LONG_PTR prevWndFunc = SetWindowLongPtr(mWindow, GWLP_WNDPROC, parentWndFunc);
ASSERT(prevWndFunc == reinterpret_cast<LONG_PTR>(SurfaceWindowProc));
}
RemoveProp(mWindow, kSurfaceProperty);
RemoveProp(mWindow, kParentWndProc);
#endif // #if !defined(ANGLE_PLATFORM_WINRT)
mWindowSubclassed = false;
}
bool Surface::checkForOutOfDateSwapChain()
{
#if defined(ANGLE_PLATFORM_WINRT)
int clientWidth = 0;
int clientHeight = 0;
winrt::getCurrentWindowDimensions(clientWidth,clientHeight);
#else
RECT client;
if (!GetClientRect(getWindowHandle(), &client))
{
ASSERT(false);
return false;
}
// Grow the buffer now, if the window has grown. We need to grow now to avoid losing information.
int clientWidth = client.right - client.left;
int clientHeight = client.bottom - client.top;
#endif // #if defined(ANGLE_PLATFORM_WINRT)
bool sizeDirty = clientWidth != getWidth() || clientHeight != getHeight();
if (mSwapIntervalDirty)
{
resetSwapChain(clientWidth, clientHeight);
}
else if (sizeDirty)
{
resizeSwapChain(clientWidth, clientHeight);
}
if (mSwapIntervalDirty || sizeDirty)
{
if (static_cast<egl::Surface*>(getCurrentDrawSurface()) == this)
{
glMakeCurrent(glGetCurrentContext(), static_cast<egl::Display*>(getCurrentDisplay()), this);
}
return true;
}
return false;
}
bool Surface::swap()
{
return swapRect(0, 0, mWidth, mHeight);
}
bool Surface::postSubBuffer(EGLint x, EGLint y, EGLint width, EGLint height)
{
if (!mPostSubBufferSupported)
{
// Spec is not clear about how this should be handled.
return true;
}
return swapRect(x, y, width, height);
}
EGLint Surface::getWidth() const
{
return mWidth;
}
EGLint Surface::getHeight() const
{
return mHeight;
}
EGLint Surface::isPostSubBufferSupported() const
{
return mPostSubBufferSupported;
}
rx::SwapChain *Surface::getSwapChain() const
{
return mSwapChain;
}
void Surface::setSwapInterval(EGLint interval)
{
if (mSwapInterval == interval)
{
return;
}
mSwapInterval = interval;
mSwapInterval = std::max(mSwapInterval, mRenderer->getMinSwapInterval());
mSwapInterval = std::min(mSwapInterval, mRenderer->getMaxSwapInterval());
mSwapIntervalDirty = true;
}
EGLenum Surface::getTextureFormat() const
{
return mTextureFormat;
}
EGLenum Surface::getTextureTarget() const
{
return mTextureTarget;
}
void Surface::setBoundTexture(gl::Texture2D *texture)
{
mTexture = texture;
}
gl::Texture2D *Surface::getBoundTexture() const
{
return mTexture;
}
EGLenum Surface::getFormat() const
{
return mConfig->mRenderTargetFormat;
}
}
<commit_msg>removed unnecessary winrt includes<commit_after>//
// Copyright (c) 2002-2012 The ANGLE 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.
//
// Surface.cpp: Implements the egl::Surface class, representing a drawing surface
// such as the client area of a window, including any back buffers.
// Implements EGLSurface and related functionality. [EGL 1.4] section 2.2 page 3.
#include <tchar.h>
#include <algorithm>
#include "libEGL/Surface.h"
#include "common/debug.h"
#include "libGLESv2/Texture.h"
#include "libGLESv2/renderer/SwapChain.h"
#include "libGLESv2/main.h"
#include "libEGL/main.h"
#include "libEGL/Display.h"
#if defined(ANGLE_PLATFORM_WINRT)
#include "common/winrtutils.h"
#endif // #if defined(ANGLE_PLATFORM_WINRT)
namespace egl
{
Surface::Surface(Display *display, const Config *config, EGLNativeWindowType window, EGLint postSubBufferSupported)
: mDisplay(display), mConfig(config), mWindow(window), mPostSubBufferSupported(postSubBufferSupported)
{
mRenderer = mDisplay->getRenderer();
mSwapChain = NULL;
mShareHandle = NULL;
mTexture = NULL;
mTextureFormat = EGL_NO_TEXTURE;
mTextureTarget = EGL_NO_TEXTURE;
mPixelAspectRatio = (EGLint)(1.0 * EGL_DISPLAY_SCALING); // FIXME: Determine actual pixel aspect ratio
mRenderBuffer = EGL_BACK_BUFFER;
mSwapBehavior = EGL_BUFFER_PRESERVED;
mSwapInterval = -1;
mWidth = -1;
mHeight = -1;
setSwapInterval(1);
subclassWindow();
}
Surface::Surface(Display *display, const Config *config, HANDLE shareHandle, EGLint width, EGLint height, EGLenum textureFormat, EGLenum textureType)
: mDisplay(display), mWindow(NULL), mConfig(config), mShareHandle(shareHandle), mWidth(width), mHeight(height), mPostSubBufferSupported(EGL_FALSE)
{
mRenderer = mDisplay->getRenderer();
mSwapChain = NULL;
mWindowSubclassed = false;
mTexture = NULL;
mTextureFormat = textureFormat;
mTextureTarget = textureType;
mPixelAspectRatio = (EGLint)(1.0 * EGL_DISPLAY_SCALING); // FIXME: Determine actual pixel aspect ratio
mRenderBuffer = EGL_BACK_BUFFER;
mSwapBehavior = EGL_BUFFER_PRESERVED;
mSwapInterval = -1;
setSwapInterval(1);
}
Surface::~Surface()
{
unsubclassWindow();
release();
}
bool Surface::initialize()
{
if (!resetSwapChain())
return false;
return true;
}
void Surface::release()
{
delete mSwapChain;
mSwapChain = NULL;
if (mTexture)
{
mTexture->releaseTexImage();
mTexture = NULL;
}
}
bool Surface::resetSwapChain()
{
ASSERT(!mSwapChain);
int width;
int height;
if (mWindow)
{
#if defined(ANGLE_PLATFORM_WINRT)
winrt::getCurrentWindowDimensions(width, height);
#else
RECT windowRect;
if (!GetClientRect(getWindowHandle(), &windowRect))
{
ASSERT(false);
ERR("Could not retrieve the window dimensions");
return error(EGL_BAD_SURFACE, false);
}
width = windowRect.right - windowRect.left;
height = windowRect.bottom - windowRect.top;
#endif // #if defined(ANGLE_PLATFORM_WINRT)
}
else
{
// non-window surface - size is determined at creation
width = mWidth;
height = mHeight;
}
mSwapChain = mRenderer->createSwapChain(mWindow, mShareHandle,
mConfig->mRenderTargetFormat,
mConfig->mDepthStencilFormat);
if (!mSwapChain)
{
return error(EGL_BAD_ALLOC, false);
}
if (!resetSwapChain(width, height))
{
delete mSwapChain;
mSwapChain = NULL;
return false;
}
return true;
}
bool Surface::resizeSwapChain(int backbufferWidth, int backbufferHeight)
{
ASSERT(backbufferWidth >= 0 && backbufferHeight >= 0);
ASSERT(mSwapChain);
EGLint status = mSwapChain->resize(backbufferWidth, backbufferHeight);
if (status == EGL_CONTEXT_LOST)
{
mDisplay->notifyDeviceLost();
return false;
}
else if (status != EGL_SUCCESS)
{
return error(status, false);
}
mWidth = backbufferWidth;
mHeight = backbufferHeight;
return true;
}
bool Surface::resetSwapChain(int backbufferWidth, int backbufferHeight)
{
ASSERT(backbufferWidth >= 0 && backbufferHeight >= 0);
ASSERT(mSwapChain);
EGLint status = mSwapChain->reset(backbufferWidth, backbufferHeight, mSwapInterval);
if (status == EGL_CONTEXT_LOST)
{
mRenderer->notifyDeviceLost();
return false;
}
else if (status != EGL_SUCCESS)
{
return error(status, false);
}
mWidth = backbufferWidth;
mHeight = backbufferHeight;
mSwapIntervalDirty = false;
return true;
}
bool Surface::swapRect(EGLint x, EGLint y, EGLint width, EGLint height)
{
if (!mSwapChain)
{
return true;
}
if (x + width > mWidth)
{
width = mWidth - x;
}
if (y + height > mHeight)
{
height = mHeight - y;
}
if (width == 0 || height == 0)
{
return true;
}
EGLint status = mSwapChain->swapRect(x, y, width, height);
if (status == EGL_CONTEXT_LOST)
{
mRenderer->notifyDeviceLost();
return false;
}
else if (status != EGL_SUCCESS)
{
return error(status, false);
}
checkForOutOfDateSwapChain();
return true;
}
EGLNativeWindowType Surface::getWindowHandle()
{
return mWindow;
}
#define kSurfaceProperty _TEXT("Egl::SurfaceOwner")
#define kParentWndProc _TEXT("Egl::SurfaceParentWndProc")
#if !defined(ANGLE_PLATFORM_WINRT)
static LRESULT CALLBACK SurfaceWindowProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam)
{
if (message == WM_SIZE)
{
Surface* surf = reinterpret_cast<Surface*>(GetProp(hwnd, kSurfaceProperty));
if(surf)
{
surf->checkForOutOfDateSwapChain();
}
}
WNDPROC prevWndFunc = reinterpret_cast<WNDPROC >(GetProp(hwnd, kParentWndProc));
return CallWindowProc(prevWndFunc, hwnd, message, wparam, lparam);
}
#endif // #if !defined(ANGLE_PLATFORM_WINRT)
void Surface::subclassWindow()
{
if (!mWindow)
{
return;
}
#if !defined(ANGLE_PLATFORM_WINRT)
DWORD processId;
DWORD threadId = GetWindowThreadProcessId(mWindow, &processId);
if (processId != GetCurrentProcessId() || threadId != GetCurrentThreadId())
{
return;
}
SetLastError(0);
LONG_PTR oldWndProc = SetWindowLongPtr(mWindow, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(SurfaceWindowProc));
if(oldWndProc == 0 && GetLastError() != ERROR_SUCCESS)
{
mWindowSubclassed = false;
return;
}
SetProp(mWindow, kSurfaceProperty, reinterpret_cast<HANDLE>(this));
SetProp(mWindow, kParentWndProc, reinterpret_cast<HANDLE>(oldWndProc));
#endif // #if !defined(ANGLE_PLATFORM_WINRT)
mWindowSubclassed = true;
}
void Surface::unsubclassWindow()
{
if(!mWindowSubclassed)
{
return;
}
#if !defined(ANGLE_PLATFORM_WINRT)
// un-subclass
LONG_PTR parentWndFunc = reinterpret_cast<LONG_PTR>(GetProp(mWindow, kParentWndProc));
// Check the windowproc is still SurfaceWindowProc.
// If this assert fails, then it is likely the application has subclassed the
// hwnd as well and did not unsubclass before destroying its EGL context. The
// application should be modified to either subclass before initializing the
// EGL context, or to unsubclass before destroying the EGL context.
if(parentWndFunc)
{
LONG_PTR prevWndFunc = SetWindowLongPtr(mWindow, GWLP_WNDPROC, parentWndFunc);
ASSERT(prevWndFunc == reinterpret_cast<LONG_PTR>(SurfaceWindowProc));
}
RemoveProp(mWindow, kSurfaceProperty);
RemoveProp(mWindow, kParentWndProc);
#endif // #if !defined(ANGLE_PLATFORM_WINRT)
mWindowSubclassed = false;
}
bool Surface::checkForOutOfDateSwapChain()
{
#if defined(ANGLE_PLATFORM_WINRT)
int clientWidth = 0;
int clientHeight = 0;
winrt::getCurrentWindowDimensions(clientWidth,clientHeight);
#else
RECT client;
if (!GetClientRect(getWindowHandle(), &client))
{
ASSERT(false);
return false;
}
// Grow the buffer now, if the window has grown. We need to grow now to avoid losing information.
int clientWidth = client.right - client.left;
int clientHeight = client.bottom - client.top;
#endif // #if defined(ANGLE_PLATFORM_WINRT)
bool sizeDirty = clientWidth != getWidth() || clientHeight != getHeight();
if (mSwapIntervalDirty)
{
resetSwapChain(clientWidth, clientHeight);
}
else if (sizeDirty)
{
resizeSwapChain(clientWidth, clientHeight);
}
if (mSwapIntervalDirty || sizeDirty)
{
if (static_cast<egl::Surface*>(getCurrentDrawSurface()) == this)
{
glMakeCurrent(glGetCurrentContext(), static_cast<egl::Display*>(getCurrentDisplay()), this);
}
return true;
}
return false;
}
bool Surface::swap()
{
return swapRect(0, 0, mWidth, mHeight);
}
bool Surface::postSubBuffer(EGLint x, EGLint y, EGLint width, EGLint height)
{
if (!mPostSubBufferSupported)
{
// Spec is not clear about how this should be handled.
return true;
}
return swapRect(x, y, width, height);
}
EGLint Surface::getWidth() const
{
return mWidth;
}
EGLint Surface::getHeight() const
{
return mHeight;
}
EGLint Surface::isPostSubBufferSupported() const
{
return mPostSubBufferSupported;
}
rx::SwapChain *Surface::getSwapChain() const
{
return mSwapChain;
}
void Surface::setSwapInterval(EGLint interval)
{
if (mSwapInterval == interval)
{
return;
}
mSwapInterval = interval;
mSwapInterval = std::max(mSwapInterval, mRenderer->getMinSwapInterval());
mSwapInterval = std::min(mSwapInterval, mRenderer->getMaxSwapInterval());
mSwapIntervalDirty = true;
}
EGLenum Surface::getTextureFormat() const
{
return mTextureFormat;
}
EGLenum Surface::getTextureTarget() const
{
return mTextureTarget;
}
void Surface::setBoundTexture(gl::Texture2D *texture)
{
mTexture = texture;
}
gl::Texture2D *Surface::getBoundTexture() const
{
return mTexture;
}
EGLenum Surface::getFormat() const
{
return mConfig->mRenderTargetFormat;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2009-2011 The VOTCA Development Team (http://www.votca.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <algorithm>
#include <votca/csg/topology.h>
#include <votca/csg/exclusionlist.h>
namespace votca { namespace csg {
void ExclusionList::Clear(void)
{
list< exclusion_t *>::iterator iter;
for(iter=_exclusions.begin();iter!=_exclusions.end();++iter)
delete *iter;
_exclusions.clear();
}
void ExclusionList::CreateExclusions(Topology *top) {
InteractionContainer &ic = top->BondedInteractions();
InteractionContainer::iterator ia;
for (ia = ic.begin(); ia != ic.end(); ++ia) {
int beads_in_int = (*ia)->BeadCount();
list<Bead *> l;
for (int ibead = 0; ibead < beads_in_int; ibead ++) {
int ii = (*ia)->getBeadId(ibead);
l.push_back(top->getBead(ii));
}
ExcludeList(l);
}
}
bool ExclusionList::IsExcluded(Bead *bead1, Bead *bead2) {
exclusion_t *excl;
if(bead1->getMolecule() == bead2->getMolecule()) return false;
if (bead2 < bead1) swap(bead1, bead2);
if ((excl = GetExclusions(bead1))) {
if(find(excl->_exclude.begin(), excl->_exclude.end(), bead2)
!= excl->_exclude.end()) return true;
}
return false;
}
std::ostream &operator<<(std::ostream &out, ExclusionList& exl)
{
list<ExclusionList::exclusion_t*>::iterator ex;
for(ex=exl._exclusions.begin();ex!=exl._exclusions.end();++ex) {
list<Bead *>::iterator i;
out << (int)((*ex)->_atom->getId()) + 1;
for(i=(*ex)->_exclude.begin(); i!=(*ex)->_exclude.end(); ++i) {
out << " " << ((*i)->getId()+1);
}
out << endl;
}
return out;
}
}}
<commit_msg>fixed Victor's new exclusion list scheme (fixes issue #165)<commit_after>/*
* Copyright 2009-2011 The VOTCA Development Team (http://www.votca.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <algorithm>
#include <votca/csg/topology.h>
#include <votca/csg/exclusionlist.h>
namespace votca { namespace csg {
void ExclusionList::Clear(void)
{
list< exclusion_t *>::iterator iter;
for(iter=_exclusions.begin();iter!=_exclusions.end();++iter)
delete *iter;
_exclusions.clear();
}
void ExclusionList::CreateExclusions(Topology *top) {
InteractionContainer &ic = top->BondedInteractions();
InteractionContainer::iterator ia;
for (ia = ic.begin(); ia != ic.end(); ++ia) {
int beads_in_int = (*ia)->BeadCount();
list<Bead *> l;
for (int ibead = 0; ibead < beads_in_int; ibead ++) {
int ii = (*ia)->getBeadId(ibead);
l.push_back(top->getBead(ii));
}
ExcludeList(l);
}
}
bool ExclusionList::IsExcluded(Bead *bead1, Bead *bead2) {
exclusion_t *excl;
if(bead1->getMolecule() != bead2->getMolecule()) return false;
if (bead2 < bead1) swap(bead1, bead2);
if ((excl = GetExclusions(bead1))) {
if(find(excl->_exclude.begin(), excl->_exclude.end(), bead2)
!= excl->_exclude.end()) return true;
}
return false;
}
std::ostream &operator<<(std::ostream &out, ExclusionList& exl)
{
list<ExclusionList::exclusion_t*>::iterator ex;
for(ex=exl._exclusions.begin();ex!=exl._exclusions.end();++ex) {
list<Bead *>::iterator i;
out << (int)((*ex)->_atom->getId()) + 1;
for(i=(*ex)->_exclude.begin(); i!=(*ex)->_exclude.end(); ++i) {
out << " " << ((*i)->getId()+1);
}
out << endl;
}
return out;
}
}}
<|endoftext|> |
<commit_before>/* This file is part of Ingen.
* Copyright (C) 2007 Dave Robillard <http://drobilla.net>
*
* Ingen 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.
*
* Ingen 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 details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <cassert>
#include <raul/Atom.hpp>
#include "interface/EngineInterface.hpp"
#include "client/PatchModel.hpp"
#include "client/NodeModel.hpp"
#include "App.hpp"
#include "NodeModule.hpp"
#include "PatchCanvas.hpp"
#include "Port.hpp"
#include "GladeFactory.hpp"
#include "RenameWindow.hpp"
#include "PatchWindow.hpp"
#include "WindowFactory.hpp"
#include "SubpatchModule.hpp"
#include "NodeControlWindow.hpp"
namespace Ingen {
namespace GUI {
NodeModule::NodeModule(boost::shared_ptr<PatchCanvas> canvas, SharedPtr<NodeModel> node)
: FlowCanvas::Module(canvas, node->path().name())
, _node(node)
, _slv2_ui(NULL)
, _gui(NULL)
, _gui_item(NULL)
{
assert(_node);
node->signal_new_port.connect(sigc::bind(sigc::mem_fun(this, &NodeModule::add_port), true));
node->signal_removed_port.connect(sigc::mem_fun(this, &NodeModule::remove_port));
node->signal_metadata.connect(sigc::mem_fun(this, &NodeModule::set_metadata));
node->signal_polyphonic.connect(sigc::mem_fun(this, &NodeModule::set_stacked_border));
node->signal_renamed.connect(sigc::mem_fun(this, &NodeModule::rename));
set_stacked_border(node->polyphonic());
}
NodeModule::~NodeModule()
{
NodeControlWindow* win = App::instance().window_factory()->control_window(_node);
if (win) {
// Should remove from window factory via signal
delete win;
}
}
void
NodeModule::create_menu()
{
Glib::RefPtr<Gnome::Glade::Xml> xml = GladeFactory::new_glade_reference();
xml->get_widget_derived("object_menu", _menu);
_menu->init(_node);
_menu->signal_embed_gui.connect(sigc::mem_fun(this, &NodeModule::embed_gui));
set_menu(_menu);
}
boost::shared_ptr<NodeModule>
NodeModule::create(boost::shared_ptr<PatchCanvas> canvas, SharedPtr<NodeModel> node)
{
boost::shared_ptr<NodeModule> ret;
SharedPtr<PatchModel> patch = PtrCast<PatchModel>(node);
if (patch)
ret = boost::shared_ptr<NodeModule>(new SubpatchModule(canvas, patch));
else
ret = boost::shared_ptr<NodeModule>(new NodeModule(canvas, node));
for (MetadataMap::const_iterator m = node->metadata().begin(); m != node->metadata().end(); ++m)
ret->set_metadata(m->first, m->second);
uint32_t index = 0;
for (PortModelList::const_iterator p = node->ports().begin(); p != node->ports().end(); ++p) {
ret->add_port(*p, false);
(*p)->signal_control.connect(sigc::bind<0>(
sigc::mem_fun(ret.get(), &NodeModule::control_change), index));
++index;
}
ret->resize();
return ret;
}
void
NodeModule::control_change(uint32_t index, float control)
{
if (_slv2_ui) {
const LV2UI_Descriptor* ui_descriptor = slv2_ui_instance_get_descriptor(_slv2_ui);
LV2UI_Handle ui_handle = slv2_ui_instance_get_handle(_slv2_ui);
ui_descriptor->port_event(ui_handle, index, 4, &control);
}
}
void
NodeModule::embed_gui(bool embed)
{
if (embed) {
// FIXME: leaks?
GtkWidget* c_widget = NULL;
Gtk::Bin* container = NULL;
if (!_gui_item) {
cerr << "Embedding LV2 GUI" << endl;
_slv2_ui = _node->plugin()->ui(App::instance().engine().get(), _node.get());
if (_slv2_ui) {
cerr << "Found UI" << endl;
c_widget = (GtkWidget*)slv2_ui_instance_get_widget(_slv2_ui);
_gui = Glib::wrap(c_widget);
assert(_gui);
//container = new Gtk::Alignment(); // transparent bg but uber slow
container = new Gtk::EventBox();
container->add(*_gui);
container->show_all();
/*Gdk::Color color;
color.set_red((_color & 0xFF000000) >> 24);
color.set_green((_color & 0x00FF0000) >> 16);
color.set_blue((_color & 0xFF000000) >> 8);
container->modify_bg(Gtk::STATE_NORMAL, color);
container->modify_bg(Gtk::STATE_ACTIVE, color);
container->modify_bg(Gtk::STATE_PRELIGHT, color);
container->modify_bg(Gtk::STATE_SELECTED, color);*/
const double y = 4 + _canvas_title.property_text_height();
_gui_item = new Gnome::Canvas::Widget(*this, 2.0, y, *container);
}
}
if (_gui_item) {
assert(_gui);
cerr << "Created canvas item" << endl;
_gui->show_all();
_gui_item->show();
GtkRequisition r;
gtk_widget_size_request(c_widget, &r);
gui_size_request(&r);
_gui_item->raise_to_top();
_gui->signal_size_request().connect(sigc::mem_fun(this, &NodeModule::gui_size_request));
for (PortModelList::const_iterator p = _node->ports().begin(); p != _node->ports().end(); ++p)
if ((*p)->is_control() && (*p)->is_output())
App::instance().engine()->enable_port_broadcasting((*p)->path());
} else {
cerr << "*** Failed to create canvas item" << endl;
}
} else {
if (_gui_item) {
delete _gui_item;
_gui_item = NULL;
}
if (_gui) {
delete _gui;
_gui = NULL;
}
//slv2_ui_instance_free(_slv2_ui); // FIXME: leak
_slv2_ui = NULL;
_ports_y_offset = 0;
_width = 0; // resize() takes care of it..
for (PortModelList::const_iterator p = _node->ports().begin(); p != _node->ports().end(); ++p)
if ((*p)->is_control() && (*p)->is_output())
App::instance().engine()->disable_port_broadcasting((*p)->path());
}
resize();
}
void
NodeModule::gui_size_request(Gtk::Requisition* r)
{
if (r->width + 4 > _width)
set_width(r->width + 4);
_gui_item->property_width() = _width - 4;
_gui_item->property_height() = r->height;
_ports_y_offset = r->height + 2;
resize();
}
void
NodeModule::rename()
{
set_name(_node->path().name());
}
void
NodeModule::add_port(SharedPtr<PortModel> port, bool resize_to_fit)
{
Module::add_port(boost::shared_ptr<Port>(new Port(
PtrCast<NodeModule>(shared_from_this()), port)));
if (resize_to_fit)
resize();
}
void
NodeModule::remove_port(SharedPtr<PortModel> port)
{
SharedPtr<FlowCanvas::Port> p = Module::remove_port(port->path().name());
p.reset();
}
void
NodeModule::show_control_window()
{
#ifdef HAVE_SLV2
if (_node->plugin()->type() == PluginModel::LV2) {
// FIXME: check type
SLV2UIInstance ui = _node->plugin()->ui(App::instance().engine().get(), _node.get());
if (ui) {
cerr << "Showing LV2 GUI" << endl;
// FIXME: leak
GtkWidget* c_widget = (GtkWidget*)slv2_ui_instance_get_widget(ui);
Gtk::Widget* widget = Glib::wrap(c_widget);
Gtk::Window* win = new Gtk::Window();
win->add(*widget);
widget->show_all();
win->present();
} else {
cerr << "No LV2 GUI, showing builtin controls" << endl;
App::instance().window_factory()->present_controls(_node);
}
} else {
App::instance().window_factory()->present_controls(_node);
}
#else
App::instance().window_factory()->present_controls(_node);
#endif
}
void
NodeModule::store_location()
{
const float x = static_cast<float>(property_x());
const float y = static_cast<float>(property_y());
const Atom& existing_x = _node->get_metadata("ingenuity:canvas-x");
const Atom& existing_y = _node->get_metadata("ingenuity:canvas-y");
if (existing_x.type() != Atom::FLOAT || existing_y.type() != Atom::FLOAT
|| existing_x.get_float() != x || existing_y.get_float() != y) {
App::instance().engine()->set_metadata(_node->path(), "ingenuity:canvas-x", Atom(x));
App::instance().engine()->set_metadata(_node->path(), "ingenuity:canvas-y", Atom(y));
}
}
void
NodeModule::set_metadata(const string& key, const Atom& value)
{
if (key == "ingenuity:canvas-x" && value.type() == Atom::FLOAT)
move_to(value.get_float(), property_y());
else if (key == "ingenuity:canvas-y" && value.type() == Atom::FLOAT)
move_to(property_x(), value.get_float());
}
} // namespace GUI
} // namespace Ingen
<commit_msg>Fix unembedding/reembedding of LV2 GUIs.<commit_after>/* This file is part of Ingen.
* Copyright (C) 2007 Dave Robillard <http://drobilla.net>
*
* Ingen 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.
*
* Ingen 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 details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <cassert>
#include <raul/Atom.hpp>
#include "interface/EngineInterface.hpp"
#include "client/PatchModel.hpp"
#include "client/NodeModel.hpp"
#include "App.hpp"
#include "NodeModule.hpp"
#include "PatchCanvas.hpp"
#include "Port.hpp"
#include "GladeFactory.hpp"
#include "RenameWindow.hpp"
#include "PatchWindow.hpp"
#include "WindowFactory.hpp"
#include "SubpatchModule.hpp"
#include "NodeControlWindow.hpp"
namespace Ingen {
namespace GUI {
NodeModule::NodeModule(boost::shared_ptr<PatchCanvas> canvas, SharedPtr<NodeModel> node)
: FlowCanvas::Module(canvas, node->path().name())
, _node(node)
, _slv2_ui(NULL)
, _gui(NULL)
, _gui_item(NULL)
{
assert(_node);
node->signal_new_port.connect(sigc::bind(sigc::mem_fun(this, &NodeModule::add_port), true));
node->signal_removed_port.connect(sigc::mem_fun(this, &NodeModule::remove_port));
node->signal_metadata.connect(sigc::mem_fun(this, &NodeModule::set_metadata));
node->signal_polyphonic.connect(sigc::mem_fun(this, &NodeModule::set_stacked_border));
node->signal_renamed.connect(sigc::mem_fun(this, &NodeModule::rename));
set_stacked_border(node->polyphonic());
}
NodeModule::~NodeModule()
{
NodeControlWindow* win = App::instance().window_factory()->control_window(_node);
if (win) {
// Should remove from window factory via signal
delete win;
}
}
void
NodeModule::create_menu()
{
Glib::RefPtr<Gnome::Glade::Xml> xml = GladeFactory::new_glade_reference();
xml->get_widget_derived("object_menu", _menu);
_menu->init(_node);
_menu->signal_embed_gui.connect(sigc::mem_fun(this, &NodeModule::embed_gui));
set_menu(_menu);
}
boost::shared_ptr<NodeModule>
NodeModule::create(boost::shared_ptr<PatchCanvas> canvas, SharedPtr<NodeModel> node)
{
boost::shared_ptr<NodeModule> ret;
SharedPtr<PatchModel> patch = PtrCast<PatchModel>(node);
if (patch)
ret = boost::shared_ptr<NodeModule>(new SubpatchModule(canvas, patch));
else
ret = boost::shared_ptr<NodeModule>(new NodeModule(canvas, node));
for (MetadataMap::const_iterator m = node->metadata().begin(); m != node->metadata().end(); ++m)
ret->set_metadata(m->first, m->second);
uint32_t index = 0;
for (PortModelList::const_iterator p = node->ports().begin(); p != node->ports().end(); ++p) {
ret->add_port(*p, false);
(*p)->signal_control.connect(sigc::bind<0>(
sigc::mem_fun(ret.get(), &NodeModule::control_change), index));
++index;
}
ret->resize();
return ret;
}
void
NodeModule::control_change(uint32_t index, float control)
{
if (_slv2_ui) {
const LV2UI_Descriptor* ui_descriptor = slv2_ui_instance_get_descriptor(_slv2_ui);
LV2UI_Handle ui_handle = slv2_ui_instance_get_handle(_slv2_ui);
ui_descriptor->port_event(ui_handle, index, 4, &control);
}
}
void
NodeModule::embed_gui(bool embed)
{
if (embed) {
// FIXME: leaks?
GtkWidget* c_widget = NULL;
Gtk::Bin* container = NULL;
if (!_gui_item) {
cerr << "Embedding LV2 GUI" << endl;
_slv2_ui = _node->plugin()->ui(App::instance().engine().get(), _node.get());
if (_slv2_ui) {
cerr << "Found UI" << endl;
c_widget = (GtkWidget*)slv2_ui_instance_get_widget(_slv2_ui);
_gui = Glib::wrap(c_widget);
assert(_gui);
//container = new Gtk::Alignment(); // transparent bg but uber slow
container = new Gtk::EventBox();
container->add(*_gui);
container->show_all();
/*Gdk::Color color;
color.set_red((_color & 0xFF000000) >> 24);
color.set_green((_color & 0x00FF0000) >> 16);
color.set_blue((_color & 0xFF000000) >> 8);
container->modify_bg(Gtk::STATE_NORMAL, color);
container->modify_bg(Gtk::STATE_ACTIVE, color);
container->modify_bg(Gtk::STATE_PRELIGHT, color);
container->modify_bg(Gtk::STATE_SELECTED, color);*/
const double y = 4 + _canvas_title.property_text_height();
_gui_item = new Gnome::Canvas::Widget(*this, 2.0, y, *container);
}
}
if (_gui_item) {
assert(_gui);
cerr << "Created canvas item" << endl;
_gui->show_all();
_gui_item->show();
GtkRequisition r;
gtk_widget_size_request(c_widget, &r);
gui_size_request(&r);
_gui_item->raise_to_top();
_gui->signal_size_request().connect(sigc::mem_fun(this, &NodeModule::gui_size_request));
for (PortModelList::const_iterator p = _node->ports().begin(); p != _node->ports().end(); ++p)
if ((*p)->is_control() && (*p)->is_output())
App::instance().engine()->enable_port_broadcasting((*p)->path());
} else {
cerr << "*** Failed to create canvas item" << endl;
}
} else {
if (_gui_item) {
delete _gui_item;
_gui_item = NULL;
}
slv2_ui_instance_free(_slv2_ui);
_slv2_ui = NULL;
_gui = NULL;
_ports_y_offset = 0;
_width = 0; // resize() takes care of it..
for (PortModelList::const_iterator p = _node->ports().begin(); p != _node->ports().end(); ++p)
if ((*p)->is_control() && (*p)->is_output())
App::instance().engine()->disable_port_broadcasting((*p)->path());
}
resize();
}
void
NodeModule::gui_size_request(Gtk::Requisition* r)
{
if (r->width + 4 > _width)
set_width(r->width + 4);
_gui_item->property_width() = _width - 4;
_gui_item->property_height() = r->height;
_ports_y_offset = r->height + 2;
resize();
}
void
NodeModule::rename()
{
set_name(_node->path().name());
}
void
NodeModule::add_port(SharedPtr<PortModel> port, bool resize_to_fit)
{
Module::add_port(boost::shared_ptr<Port>(new Port(
PtrCast<NodeModule>(shared_from_this()), port)));
if (resize_to_fit)
resize();
}
void
NodeModule::remove_port(SharedPtr<PortModel> port)
{
SharedPtr<FlowCanvas::Port> p = Module::remove_port(port->path().name());
p.reset();
}
void
NodeModule::show_control_window()
{
#ifdef HAVE_SLV2
if (_node->plugin()->type() == PluginModel::LV2) {
// FIXME: check type
SLV2UIInstance ui = _node->plugin()->ui(App::instance().engine().get(), _node.get());
if (ui) {
cerr << "Showing LV2 GUI" << endl;
// FIXME: leak
GtkWidget* c_widget = (GtkWidget*)slv2_ui_instance_get_widget(ui);
Gtk::Widget* widget = Glib::wrap(c_widget);
Gtk::Window* win = new Gtk::Window();
win->add(*widget);
widget->show_all();
win->present();
} else {
cerr << "No LV2 GUI, showing builtin controls" << endl;
App::instance().window_factory()->present_controls(_node);
}
} else {
App::instance().window_factory()->present_controls(_node);
}
#else
App::instance().window_factory()->present_controls(_node);
#endif
}
void
NodeModule::store_location()
{
const float x = static_cast<float>(property_x());
const float y = static_cast<float>(property_y());
const Atom& existing_x = _node->get_metadata("ingenuity:canvas-x");
const Atom& existing_y = _node->get_metadata("ingenuity:canvas-y");
if (existing_x.type() != Atom::FLOAT || existing_y.type() != Atom::FLOAT
|| existing_x.get_float() != x || existing_y.get_float() != y) {
App::instance().engine()->set_metadata(_node->path(), "ingenuity:canvas-x", Atom(x));
App::instance().engine()->set_metadata(_node->path(), "ingenuity:canvas-y", Atom(y));
}
}
void
NodeModule::set_metadata(const string& key, const Atom& value)
{
if (key == "ingenuity:canvas-x" && value.type() == Atom::FLOAT)
move_to(value.get_float(), property_y());
else if (key == "ingenuity:canvas-y" && value.type() == Atom::FLOAT)
move_to(property_x(), value.get_float());
}
} // namespace GUI
} // namespace Ingen
<|endoftext|> |
<commit_before>#include "libircppclient.hpp"
#include "util.hpp"
#include <string>
#include <iostream>
#include <thread>
#include <stdexcept>
namespace irc {
client::client(const config &conf)
: conf_(conf), con_(conf_.ssl)
{
std::string ret = validate_conf(conf);
if (!ret.empty())
throw std::invalid_argument("Configuration error: " + ret);
con_.set_addr(conf.address);
con_.set_port(conf.port);
/*
* "Bind" the external read handlers from connection to
* read_handler() here. Otherwise, you'd need to fiddle
* with connection.hpp inclusion.
*/
con_.set_ext_read_handler([this](const std::experimental::string_view &content) {
this->read_handler(content);
});
}
std::string client::validate_conf(const config &c)
{
/* Address checking. */
if (c.address.empty()) {
return "the address is empty.";
} else {
std::string ret = util::valid_addr(c.address);
if (!ret.empty())
return "invalid address, reason: " + ret;
}
/* Port checking. */
if (c.port.empty())
return "port is empty.";
else if (!util::is_integer(c.port))
return "port contains one of more non-integers.";
return "";
}
void client::initialize()
{
con_.write("NICK " + conf_.nick);
con_.write("USER " + conf_.user + " 0 * :" + conf_.user);
}
void client::start()
{
con_.connect();
/*
* These writes will be put in the io_service's
* queue until a complete connection has been made.
*/
initialize();
con_.run();
}
void client::stop()
{
/*
* Haven't I forgotten something?
* Some async function that needs terminating, maybe?
*/
con_.stop_ping();
con_.stop();
}
void client::read_handler(const std::experimental::string_view &content)
{
for (read_handler_t &func: read_handlers_) {
func(content);
}
}
void client::add_read_handler(std::function<void(const std::experimental::string_view &)> func)
{
read_handlers_.emplace_back(func);
}
void client::raw_cmd(const std::experimental::string_view &content)
{
if (content.empty())
throw std::invalid_argument("content is empty.");
con_.write(content.data());
}
/* ns irc */
}
<commit_msg>remove unecessary whitespace<commit_after>#include "libircppclient.hpp"
#include "util.hpp"
#include <string>
#include <iostream>
#include <thread>
#include <stdexcept>
#include <cassert>
namespace irc {
client::client(const config &conf)
: conf_(conf), con_(conf_.ssl)
{
std::string ret = validate_conf(conf);
if (!ret.empty())
throw std::invalid_argument("Configuration error: " + ret);
con_.set_addr(conf.address);
con_.set_port(conf.port);
/*
* "Bind" the external read handlers from connection to
* read_handler() here. Otherwise, you'd need to fiddle
* with connection.hpp inclusion.
*/
con_.set_ext_read_handler([this](const std::experimental::string_view &content) {
this->read_handler(content);
});
}
std::string client::validate_conf(const config &c)
{
/* Address checking. */
if (c.address.empty()) {
return "the address is empty.";
} else {
std::string ret = util::valid_addr(c.address);
if (!ret.empty())
return "invalid address, reason: " + ret;
}
/* Port checking. */
if (c.port.empty())
return "port is empty.";
else if (!util::is_integer(c.port))
return "port contains one of more non-integers.";
return "";
}
void client::initialize()
{
con_.write("NICK " + conf_.nick);
con_.write("USER " + conf_.user + " 0 * :" + conf_.user);
}
void client::start()
{
con_.connect();
/*
* These writes will be put in the io_service's
* queue until a complete connection has been made.
*/
initialize();
con_.run();
}
void client::stop()
{
/*
* Haven't I forgotten something?
* Some async function that needs terminating, maybe?
*/
con_.stop_ping();
con_.stop();
}
void client::read_handler(const std::experimental::string_view &content)
{
for (read_handler_t &func: read_handlers_) {
func(content);
}
}
void client::add_read_handler(std::function<void(const std::experimental::string_view &)> func)
{
read_handlers_.emplace_back(func);
}
void client::raw_cmd(const std::experimental::string_view &content)
{
if (content.empty())
throw std::invalid_argument("content is empty.");
con_.write(content.data());
}
/* ns irc */
}
<|endoftext|> |
<commit_before>/*
SjASMPlus Z80 Cross Compiler
This is modified sources of SjASM by Aprisobal - [email protected]
Copyright (c) 2005 Sjoerd Mastijn
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the
use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim
that you wrote the original software. If you use this software in a product,
an acknowledgment in the product documentation would be appreciated but is
not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
// support.cpp
#include "sjdefs.h"
#ifdef UNDER_CE
#endif
// http://legacy.imatix.com/html/sfl/sfl282.htm
char* strpad(char* string, char ch, aint length) {
aint cursize;
cursize = strlen (string); /* Get current length of string */
while (cursize < length) /* Pad until at desired length */
string [cursize++] = ch;
string [cursize++] = '\0'; /* Add terminating null */
return (string); /* and return to caller */
}
#if !defined (_MSC_VER) || defined (UNDER_CE)
void GetCurrentDirectory(int whatever, char* pad) {
pad[0] = 0;
}
int SearchPath(char* oudzp, char* filename, char* whatever, int maxlen, char* nieuwzp, char** ach) {
FILE* fp;
char* p, * f;
if (filename[0] == '/') {
STRCPY(nieuwzp, maxlen, filename);
} else {
STRCPY(nieuwzp, maxlen, oudzp);
if (*nieuwzp && nieuwzp[strlen(nieuwzp)] != '/') {
STRCAT(nieuwzp, maxlen, "/");
}
STRCAT(nieuwzp, maxlen, filename);
}
if (ach) {
p = f = nieuwzp;
while (*p) {
if (*p == '/') {
f = p + 1;
} ++p;
}
*ach = f;
}
if (FOPEN_ISOK(fp, nieuwzp, "r")) {
fclose(fp);
return 1;
}
return 0;
}
char* strset(char* str, char val) {
//non-aligned
char* pByte = str;
while (((uintptr_t) pByte) & 3) {
if (*pByte) {
*pByte++ = val;
} else {
return str;
}
}
//4-byte aligned
unsigned long* pBlock = (unsigned long*) pByte;
unsigned long a;
unsigned long dwVal = val | val << 8 | val << 16 | val << 24;
for (; ;) {
a = *pBlock;
a &= 0x7f7f7f7f;
a -= 0x01010101;
if (a & 0x80808080) {
break;
} else {
*pBlock++ = dwVal;
}
}
//non-aligned
pByte = (char*) pBlock;
while (*pByte) {
*pByte++ = val;
}
return str;
}
#ifndef WIN32
long GetTickCount() {
struct timeval tv1[1];
gettimeofday(tv1, 0);
return tv1->tv_usec / 1000;
}
#endif
#endif
#ifdef USE_LUA
void LuaShellExec(char *command) {
#ifdef UNDER_CE
//_wsystem(_towchar(command));
SHELLEXECUTEINFO info;
info.cbSize = sizeof(SHELLEXECUTEINFO);
info.fMask = NULL;
info.hwnd = NULL;
info.lpVerb = NULL;
info.lpFile = _totchar(command);
info.lpParameters = NULL;
info.lpDirectory = NULL;
info.nShow = SW_MAXIMIZE;
info.hInstApp = NULL;
ShellExecuteEx(&info);
#else
#ifdef WIN32
WinExec(command, SW_SHOWNORMAL);
#else
int ret = system(command);
if ( ret == -1 ) {
Error("[LUASHELEXEC] Unable to start child process for command", command, CATCHALL);
}
#endif
#endif
}
#endif //USE_LUA
//eof support.cpp
<commit_msg>uintptr_t definition fixed for older compilers.<commit_after>/*
SjASMPlus Z80 Cross Compiler
This is modified sources of SjASM by Aprisobal - [email protected]
Copyright (c) 2005 Sjoerd Mastijn
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the
use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim
that you wrote the original software. If you use this software in a product,
an acknowledgment in the product documentation would be appreciated but is
not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
// support.cpp
#include "sjdefs.h"
#ifdef UNDER_CE
#endif
// http://legacy.imatix.com/html/sfl/sfl282.htm
char* strpad(char* string, char ch, aint length) {
aint cursize;
cursize = strlen (string); /* Get current length of string */
while (cursize < length) /* Pad until at desired length */
string [cursize++] = ch;
string [cursize++] = '\0'; /* Add terminating null */
return (string); /* and return to caller */
}
#if !defined (_MSC_VER) || defined (UNDER_CE)
void GetCurrentDirectory(int whatever, char* pad) {
pad[0] = 0;
}
int SearchPath(char* oudzp, char* filename, char* whatever, int maxlen, char* nieuwzp, char** ach) {
FILE* fp;
char* p, * f;
if (filename[0] == '/') {
STRCPY(nieuwzp, maxlen, filename);
} else {
STRCPY(nieuwzp, maxlen, oudzp);
if (*nieuwzp && nieuwzp[strlen(nieuwzp)] != '/') {
STRCAT(nieuwzp, maxlen, "/");
}
STRCAT(nieuwzp, maxlen, filename);
}
if (ach) {
p = f = nieuwzp;
while (*p) {
if (*p == '/') {
f = p + 1;
} ++p;
}
*ach = f;
}
if (FOPEN_ISOK(fp, nieuwzp, "r")) {
fclose(fp);
return 1;
}
return 0;
}
char* strset(char* str, char val) {
//non-aligned
char* pByte = str;
// mborik: fix for older compilers
#ifdef _UINTPTR_T_DEFINED
while (((uintptr_t) pByte) & 3) {
#else
while (((unsigned long) pByte) & 3) {
#endif
if (*pByte) {
*pByte++ = val;
} else {
return str;
}
}
//4-byte aligned
unsigned long* pBlock = (unsigned long*) pByte;
unsigned long a;
unsigned long dwVal = val | val << 8 | val << 16 | val << 24;
for (; ;) {
a = *pBlock;
a &= 0x7f7f7f7f;
a -= 0x01010101;
if (a & 0x80808080) {
break;
} else {
*pBlock++ = dwVal;
}
}
//non-aligned
pByte = (char*) pBlock;
while (*pByte) {
*pByte++ = val;
}
return str;
}
#ifndef WIN32
long GetTickCount() {
struct timeval tv1[1];
gettimeofday(tv1, 0);
return tv1->tv_usec / 1000;
}
#endif
#endif
#ifdef USE_LUA
void LuaShellExec(char *command) {
#ifdef UNDER_CE
//_wsystem(_towchar(command));
SHELLEXECUTEINFO info;
info.cbSize = sizeof(SHELLEXECUTEINFO);
info.fMask = NULL;
info.hwnd = NULL;
info.lpVerb = NULL;
info.lpFile = _totchar(command);
info.lpParameters = NULL;
info.lpDirectory = NULL;
info.nShow = SW_MAXIMIZE;
info.hInstApp = NULL;
ShellExecuteEx(&info);
#else
#ifdef WIN32
WinExec(command, SW_SHOWNORMAL);
#else
int ret = system(command);
if ( ret == -1 ) {
Error("[LUASHELEXEC] Unable to start child process for command", command, CATCHALL);
}
#endif
#endif
}
#endif //USE_LUA
//eof support.cpp
<|endoftext|> |
<commit_before>#include "susi/DuktapeEngine.h"
std::string Susi::Duktape::susiJS = R"SUSIJS(
var susi = {
_consumerCallbacks: [],
_processorCallbacks: [],
_processorTopicCounter: {},
_consumerTopicCounter: {},
_publishCallbacks: {},
_processorProcesses: {},
_processed: [],
registerConsumer: function(topic,callback) {
var id = this._genID();
this._consumerCallbacks.push({topic: topic, callback: callback, id: id});
var count = this._consumerTopicCounter[topic] || 0;
count++;
this._consumerTopicCounter[topic] = count;
if(count === 1){
_registerConsumer(topic);
}
return id;
},
registerProcessor: function(topic,callback) {
var id = this._genID();
this._processorCallbacks.push({topic: topic, callback: callback, id: id});
var count = this._processorTopicCounter[topic] || 0;
count++;
this._processorTopicCounter[topic] = count;
if(count == 1){
_registerProcessor(topic);
}
return id;
},
unregisterConsumer: function(id){
for(var i=0;i<this._consumerCallbacks;i++){
if(this._consumerCallbacks[i].id === id){
var topic = this._consumerCallbacks[i].topic;
this._consumerCallbacks.splice(i,1);
var count = this._consumerTopicCounter[topic];
count--;
if(count === 0){
delete(this._consumerTopicCounter[topic]);
_unregisterConsumer(topic);
}else{
this._consumerTopicCounter[topic] = count;
}
return true;
}
}
return false;
},
unregisterProcessor: function(id){
for(var i=0;i<this._processorCallbacks;i++){
if(this._processorCallbacks[i].id === id){
var topic = this._processorCallbacks[i].topic;
this._processorCallbacks.splice(i,1);
var count = this._processorTopicCounter[topic];
count--;
if(count === 0){
delete(this._processorTopicCounter[topic]);
_unregisterProcessor(topic);
}else{
this._processorTopicCounter[topic] = count;
}
return true;
}
}
return false;
},
publish: function(event,callback) {
if(event.id === undefined){
event.id = ''+this._genID();
}
if(callback !== undefined) {
this._publishCallbacks[event.id] = callback;
}
_publish(JSON.stringify(event));
},
ack: function(event){
var process = this._processorProcesses[event.id];
if(process.next >= process.processors.length){
delete this._processorProcesses[event.id];
_ack(JSON.stringify(event));
}else{
process.next++;
process.processors[process.next-1](event);
}
},
dismiss: function(event){
delete(this._processorProcesses[event.id]);
_dismiss(JSON.stringify(event));
},
//used by js to interact with c++ part
_processConsumerEvent: function(event){
event = JSON.parse(event);
for(var i=0;i<this._consumerCallbacks.length;i++){
if(event.topic.match(this._consumerCallbacks[i].topic)){
this._consumerCallbacks[i].callback(event);
}
}
},
_processProcessorEvent: function(event){
event = JSON.parse(event);
if(this._processed.indexOf(event.id) !== -1){
_ack(JSON.stringify(event));
return;
}
this._processed.push(event.id);
if(this._processed.length > 64){
this._processed.splice(0,1);
}
Duktape.fin(event,function(event){
susi.ack(event);
});
var process = {
processors: [],
next: 0
};
for (var i = 0; i<this._processorCallbacks.length; i++) {
if(event.topic.match(this._processorCallbacks[i].topic)){
process.processors.push(this._processorCallbacks[i].callback);
}
}
this._processorProcesses[event.id] = process;
this.ack(event);
Duktape.gc();
},
_processAck: function(event){
event = JSON.parse(event);
var cb = this._publishCallbacks[event.id];
if(cb !== undefined) {
cb(event);
delete this._publishCallbacks[event.id];
}
},
_genID: function(){
return Math.floor(Math.random()*1000000000000);
}
};
//called by c++ part
function _processConsumerEvent(event,topic){
susi._processConsumerEvent(event,topic);
}
function _processProcessorEvent(event,topic){
susi._processProcessorEvent(event,topic)
}
function _processAck(event){
susi._processAck(event);
}
var duktapeLogger = new Duktape.Logger('susi-js');
duktapeLogger.l = 0;
var console = {
_prepareArguments: function(args){
var newArgs = [];
for(var i=0;i<args.length;i++){
if(typeof args[i] === 'object'){
newArgs.push(Duktape.enc('jx',args[i]));
}else{
newArgs.push(args[i]);
}
}
return newArgs;
},
_getLine: function(){
var e = new Error(arguments);
return e.stack.split('\n')[3].trim().split(' ')[1];
},
log: function(){
duktapeLogger.info.apply(duktapeLogger,this._prepareArguments(arguments));
},
debug: function(){
duktapeLogger.n = 'susi-js: '+this._getLine();
duktapeLogger.debug.apply(duktapeLogger,this._prepareArguments(arguments));
duktapeLogger.n = 'susi-js';
},
error: function(){
duktapeLogger.n = 'susi-js: '+this._getLine();
duktapeLogger.error.apply(duktapeLogger,this._prepareArguments(arguments));
duktapeLogger.n = 'susi-js';
}
};
var TimeoutManager = {
timeoutFunctions: [],
add: function(cb, millis){
this.timeoutFunctions.push({
deadline: Date.now()+millis,
cb: cb
});
},
check: function(){
var now = Date.now();
for(var i=this.timeoutFunctions.length-1;i>=0;i--){
if(this.timeoutFunctions[i].deadline <= now){
this.timeoutFunctions[i].cb();
this.timeoutFunctions.splice(i,1);
}
}
}
};
function setTimeout(cb,millis){
TimeoutManager.add(cb,millis);
_setTimeout(millis);
}
function _checkTimeouts(){
TimeoutManager.check();
}
)SUSIJS";
<commit_msg>fixed double consumers in complex setups, needs further investigation;<commit_after>#include "susi/DuktapeEngine.h"
std::string Susi::Duktape::susiJS = R"SUSIJS(
var susi = {
_consumerCallbacks: [],
_processorCallbacks: [],
_processorTopicCounter: {},
_consumerTopicCounter: {},
_publishCallbacks: {},
_processorProcesses: {},
_processed: [],
_processedConsumer: [],
registerConsumer: function(topic,callback) {
var id = this._genID();
this._consumerCallbacks.push({topic: topic, callback: callback, id: id});
var count = this._consumerTopicCounter[topic] || 0;
count++;
this._consumerTopicCounter[topic] = count;
if(count === 1){
_registerConsumer(topic);
}
return id;
},
registerProcessor: function(topic,callback) {
var id = this._genID();
this._processorCallbacks.push({topic: topic, callback: callback, id: id});
var count = this._processorTopicCounter[topic] || 0;
count++;
this._processorTopicCounter[topic] = count;
if(count == 1){
_registerProcessor(topic);
}
return id;
},
unregisterConsumer: function(id){
for(var i=0;i<this._consumerCallbacks;i++){
if(this._consumerCallbacks[i].id === id){
var topic = this._consumerCallbacks[i].topic;
this._consumerCallbacks.splice(i,1);
var count = this._consumerTopicCounter[topic];
count--;
if(count === 0){
delete(this._consumerTopicCounter[topic]);
_unregisterConsumer(topic);
}else{
this._consumerTopicCounter[topic] = count;
}
return true;
}
}
return false;
},
unregisterProcessor: function(id){
for(var i=0;i<this._processorCallbacks;i++){
if(this._processorCallbacks[i].id === id){
var topic = this._processorCallbacks[i].topic;
this._processorCallbacks.splice(i,1);
var count = this._processorTopicCounter[topic];
count--;
if(count === 0){
delete(this._processorTopicCounter[topic]);
_unregisterProcessor(topic);
}else{
this._processorTopicCounter[topic] = count;
}
return true;
}
}
return false;
},
publish: function(event,callback) {
if(event.id === undefined){
event.id = ''+this._genID();
}
if(callback !== undefined) {
this._publishCallbacks[event.id] = callback;
}
_publish(JSON.stringify(event));
},
ack: function(event){
var process = this._processorProcesses[event.id];
if(process.next >= process.processors.length){
delete this._processorProcesses[event.id];
_ack(JSON.stringify(event));
}else{
process.next++;
process.processors[process.next-1](event);
}
},
dismiss: function(event){
delete(this._processorProcesses[event.id]);
_dismiss(JSON.stringify(event));
},
//used by js to interact with c++ part
_processConsumerEvent: function(event){
event = JSON.parse(event);
if(this._processedConsumer.indexOf(event.id) !== -1){
_ack(JSON.stringify(event));
return;
}
this._processedConsumer.push(event.id);
if(this._processedConsumer.length > 64){
this._processedConsumer.splice(0,1);
}
for(var i=0;i<this._consumerCallbacks.length;i++){
if(event.topic.match(this._consumerCallbacks[i].topic)){
this._consumerCallbacks[i].callback(event);
}
}
},
_processProcessorEvent: function(event){
event = JSON.parse(event);
if(this._processed.indexOf(event.id) !== -1){
_ack(JSON.stringify(event));
return;
}
this._processed.push(event.id);
if(this._processed.length > 64){
this._processed.splice(0,1);
}
Duktape.fin(event,function(event){
susi.ack(event);
});
var process = {
processors: [],
next: 0
};
for (var i = 0; i<this._processorCallbacks.length; i++) {
if(event.topic.match(this._processorCallbacks[i].topic)){
process.processors.push(this._processorCallbacks[i].callback);
}
}
this._processorProcesses[event.id] = process;
this.ack(event);
Duktape.gc();
},
_processAck: function(event){
event = JSON.parse(event);
var cb = this._publishCallbacks[event.id];
if(cb !== undefined) {
cb(event);
delete this._publishCallbacks[event.id];
}
},
_genID: function(){
return Math.floor(Math.random()*1000000000000);
}
};
//called by c++ part
function _processConsumerEvent(event,topic){
susi._processConsumerEvent(event,topic);
}
function _processProcessorEvent(event,topic){
susi._processProcessorEvent(event,topic)
}
function _processAck(event){
susi._processAck(event);
}
var duktapeLogger = new Duktape.Logger('susi-js');
duktapeLogger.l = 0;
var console = {
_prepareArguments: function(args){
var newArgs = [];
for(var i=0;i<args.length;i++){
if(typeof args[i] === 'object'){
newArgs.push(Duktape.enc('jx',args[i]));
}else{
newArgs.push(args[i]);
}
}
return newArgs;
},
_getLine: function(){
var e = new Error(arguments);
return e.stack.split('\n')[3].trim().split(' ')[1];
},
log: function(){
duktapeLogger.info.apply(duktapeLogger,this._prepareArguments(arguments));
},
debug: function(){
duktapeLogger.n = 'susi-js: '+this._getLine();
duktapeLogger.debug.apply(duktapeLogger,this._prepareArguments(arguments));
duktapeLogger.n = 'susi-js';
},
error: function(){
duktapeLogger.n = 'susi-js: '+this._getLine();
duktapeLogger.error.apply(duktapeLogger,this._prepareArguments(arguments));
duktapeLogger.n = 'susi-js';
}
};
var TimeoutManager = {
timeoutFunctions: [],
add: function(cb, millis){
this.timeoutFunctions.push({
deadline: Date.now()+millis,
cb: cb
});
},
check: function(){
var now = Date.now();
for(var i=this.timeoutFunctions.length-1;i>=0;i--){
if(this.timeoutFunctions[i].deadline <= now){
this.timeoutFunctions[i].cb();
this.timeoutFunctions.splice(i,1);
}
}
}
};
function setTimeout(cb,millis){
TimeoutManager.add(cb,millis);
_setTimeout(millis);
}
function _checkTimeouts(){
TimeoutManager.check();
}
)SUSIJS";
<|endoftext|> |
<commit_before>#include <Windows.h>
#include <stdint.h> // Types indpendents de la plateforme
#include <Xinput.h> // Pour la gestion des entres (manette...)
// Pour bien comprendre la diffrence de fonctionnement des variables statiques en C en fonction du scope
#define internal static // fonctions non visible depuis l'extrieur de ce fichier
#define local_persist static // variable visibles juste dans le scope o elle dfinie
#define global_variable static // variable visible dans tous le fichiers (globale)
// Quelques dfinitions de types d'entiers pour ne pas tre dpendant de la plateforme
typedef unsigned char uint8;
typedef uint8_t uint8; // comme un unsigned char, un 8 bits
typedef int16_t uint16;
typedef int32_t uint32;
typedef int64_t uint64;
// Struct qui reprsente un backbuffer qui nous permet de dessiner
struct win32_offscreen_buffer {
BITMAPINFO Info;
void *Memory;
int Width;
int Height;
int BytesPerPixel;
int Pitch; // Pitch reprsente la taille d'une ligne en octets
};
// variables globales pour le moment, on grera autrement plus tard
global_variable bool GlobalRunning;
global_variable win32_offscreen_buffer GlobalBackBuffer;
// Struct qui reprsente des dimensions
struct win32_window_dimension
{
int Width;
int Height;
};
// Permet de renvoyer les dimensions actuelles de la fentre
internal win32_window_dimension
Win32GetWindowDimension(HWND Window) {
win32_window_dimension Result;
RECT ClientRect;
GetClientRect(Window, &ClientRect);
Result.Width = ClientRect.right - ClientRect.left;
Result.Height = ClientRect.bottom - ClientRect.top;
return(Result);
}
// Ici on dfinit des pointeurs vers les fonctions de Xinput
// Cette technique traditionnelle permet d'utiliser des fonctions
// Sans linker directement la lib, et permet aussi de tester si la lib est prsente
// On utilise alors des macros pour dfinir la signature des fonctions
// Ici on dfinit deux fonctions qui vont se subsituer aux vraies si la lib n'est pas trouve
// D'abord pour XInputGetState
#define X_INPUT_GET_STATE(name) DWORD WINAPI name(DWORD dwUserIndex, XINPUT_STATE *pState)
typedef X_INPUT_GET_STATE(x_input_get_state);
X_INPUT_GET_STATE(XInputGetStateStub) {
return(0);
}
global_variable x_input_get_state *XInputGetState_ = XInputGetStateStub;
#define XInputGetState XInputGetState_
// De mme pour XInputSetState
#define X_INPUT_SET_STATE(name) DWORD WINAPI name(DWORD dwUserIndex, XINPUT_VIBRATION *pVibration)
typedef X_INPUT_SET_STATE(x_input_set_state);
X_INPUT_SET_STATE(XInputSetStateStub) {
return(0);
}
global_variable x_input_set_state *XInputSetState_ = XInputSetStateStub;
#define XInputSetState XInputSetState_
// On va alors
internal void
Win32LoadXInput(void) {
HMODULE XInputLibrary = LoadLibrary("xinput1_3.dll"); // on essaye une version un peu plus ancienne qui sera prsente sur plus de machines
if (XInputLibrary)
{
XInputGetState_ = (x_input_get_state*)GetProcAddress(XInputLibrary, "XInputGetState");
XInputSetState_ = (x_input_set_state*)GetProcAddress(XInputLibrary, "XInputSetState");
}
}
/* Fonction qui va dessiner dans le backbuffer un gradient de couleur trange */
internal void
RenderWeirdGradient(win32_offscreen_buffer *Buffer, int XOffset, int YOffset)
{
uint8 *Row = (uint8 *)Buffer->Memory; // on va se dplacer dans la mmoire par pas de 8 bits
for (int Y = 0; Y < Buffer->Height; ++Y)
{
uint32 *Pixel = (uint32 *)Row; // Pixel par pixel, on commence par le premier de la ligne
for (int X = 0; X < Buffer->Width; ++X)
{
/*
Pixels en little endian architecture
0 1 2 3 ...
Pixels en mmoire : 00 00 00 00 ...
Couleur BB GG RR XX
en hexa: 0xXXRRGGBB
*/
uint8 Blue = (X + XOffset);
uint8 Green = (Y + YOffset);
uint8 Red = (X + Y);
// *Pixel = 0xFF00FF00;
*Pixel++ = ((Red << 16) | (Green << 8) | Blue); // ce qui quivaut en hexa 0x00BBGG00
}
Row += Buffer->Pitch; // Ligne suivante
}
}
/**
* Fonction qui permet de dfinir et de rinitialiser un backbuffer en fonction de ses dimensions
* DIB: Device Independent Bitmap
**/
internal void
Win32ResizeDIBSection(win32_offscreen_buffer *Buffer, int Width, int Height)
{
if (Buffer->Memory)
{
VirtualFree(Buffer->Memory, 0, MEM_RELEASE); // cf. VirtualProtect, utile pour debug
}
Buffer->Width = Width;
Buffer->Height = Height;
Buffer->BytesPerPixel = 4;
Buffer->Info.bmiHeader.biSize = sizeof(Buffer->Info.bmiHeader);
Buffer->Info.bmiHeader.biWidth = Buffer->Width;
Buffer->Info.bmiHeader.biHeight = -Buffer->Height; // Attention au sens des coordonnes, du bas vers le haut (d'o le moins)
Buffer->Info.bmiHeader.biPlanes = 1;
Buffer->Info.bmiHeader.biBitCount = 32;
Buffer->Info.bmiHeader.biCompression = BI_RGB;
int BitmapMemorySize = (Buffer->Width * Buffer->Height) * Buffer->BytesPerPixel;
Buffer->Memory = VirtualAlloc(0, BitmapMemorySize, MEM_COMMIT, PAGE_READWRITE); // cf. aussi HeapAlloc
Buffer->Pitch = Width * Buffer->BytesPerPixel;
}
/**
* Ici au dbut on passait ClientRect par rfrence avec un pointeur (*ClientRect)
* cependant comme la structure est petite le passer par valeur est suffisant
**/
internal void
Win32DisplayBufferInWindow(
HDC DeviceContext,
int WindowWidth,
int WindowHeight,
win32_offscreen_buffer *Buffer)
{
StretchDIBits( // copie d'un rectangle vers un autre (scaling si ncessaire, bit oprations...)
DeviceContext,
0, 0, WindowWidth, WindowHeight,
0, 0, Buffer->Width, Buffer->Height,
Buffer->Memory,
&Buffer->Info,
DIB_RGB_COLORS,
SRCCOPY // BitBlt: bit-block transfer of the color data => voir les autres modes dans la MSDN
);
}
/**
* Callback de la fentre principale qui va traiter les messages renvoys par Windows
**/
internal LRESULT CALLBACK
Win32MainWindowCallback(
HWND Window,
UINT Message,
WPARAM WParam,
LPARAM LParam)
{
LRESULT Result = 0;
switch(Message)
{
case WM_SIZE:
{
OutputDebugStringA("WM_SIZE\n");
}
break;
case WM_DESTROY:
{
// PostQuitMessage(0); // Va permettre de sortir de la boucle infinie en dessous
GlobalRunning = false;
OutputDebugStringA("WM_DESTROY\n");
}
break;
case WM_CLOSE:
{
// DestroyWindow(Window);
GlobalRunning = false;
OutputDebugStringA("WM_CLOSE\n");
}
break;
case WM_ACTIVATEAPP:
{
OutputDebugStringA("WM_ACTIVATEAPP\n");
}
break;
case WM_PAINT:
{
PAINTSTRUCT Paint;
HDC DeviceContext = BeginPaint(Window, &Paint);
win32_window_dimension Dimension = Win32GetWindowDimension(Window);
Win32DisplayBufferInWindow(DeviceContext, Dimension.Width, Dimension.Height, &GlobalBackBuffer);
EndPaint(Window, &Paint);
}
break;
default:
{
// OutputDebugStringA("default\n");
Result = DefWindowProc(Window, Message, WParam, LParam);
}
break;
}
return(Result);
}
/**
* Main du programme qui va initialiser la fentre et grer la boucle principale : attente des messages,
* gestion de la manette et du clavier, dessin...
**/
int CALLBACK
WinMain(
HINSTANCE Instance,
HINSTANCE PrevInstance,
LPSTR CommandLine,
int ShowCode)
{
// On essaye de charger les fonctions de la dll qui gre les manettes
Win32LoadXInput();
// Cration de la fentre principale
WNDCLASSA WindowClass = {}; // initialisation par dfaut, ANSI version de WNDCLASSA
Win32ResizeDIBSection(&GlobalBackBuffer, 800, 600);
// On ne configure que les membres que l'on veut
WindowClass.style = CS_HREDRAW|CS_VREDRAW|CS_OWNDC; // indique que l'on veut rafraichir la fentre entire lors d'un resize (horizontal et vertical)
WindowClass.lpfnWndProc = Win32MainWindowCallback;
WindowClass.hInstance = Instance;
// WindowClass.hIcon;
WindowClass.lpszClassName = "FaitmainHerosWindowClass"; // nom pour retrouver la fentre
// Ouverture de la fentre
if (RegisterClassA(&WindowClass))
{
HWND Window = CreateWindowExA( // ANSI version de CreateWindowEx
0, // dwExStyle : options de la fentre
WindowClass.lpszClassName,
"FaitmainHeros",
WS_OVERLAPPEDWINDOW|WS_VISIBLE, //dwStyle : overlapped window, visible par dfaut
CW_USEDEFAULT, // X
CW_USEDEFAULT, // Y
CW_USEDEFAULT, // nWidth
CW_USEDEFAULT, // nHeight
0, // hWndParent : 0 pour dire que c'est une fentre top
0, // hMenu : 0 pour dire pas de menu
Instance,
0 // Pas de passage de paramtres la fentre
);
if (Window)
{
// Comme on a spcifi CS_OWNDC on peut initialiser un seul HDC
// et s'en servir indfiniment car on ne le partage pas
HDC DeviceContext = GetDC(Window);
int XOffset = 0;
int YOffset = 0;
GlobalRunning = true;
while (GlobalRunning) // boucle infinie pour traiter tous les messages
{
MSG Message;
while(PeekMessageA(&Message, 0, 0, 0, PM_REMOVE)) // On utilise PeekMessage au lieu de GetMessage qui est bloquant
{
if (Message.message == WM_QUIT) GlobalRunning = false;
TranslateMessage(&Message); // On demande Windows de traiter le message
DispatchMessage(&Message); // Envoie le message au main WindowCallback, que l'on a dfini et dclar au dessus
}
// Gestion des entres, pour le moment on gre a chaque image, il faudra peut-tre le faire plus frquemment
// surtout si le nombre d'images par seconde chute
for (DWORD ControllerIndex = 0; ControllerIndex < XUSER_MAX_COUNT; ++ControllerIndex)
{
XINPUT_STATE ControllerState;
if (XInputGetState(ControllerIndex, &ControllerState) == ERROR_SUCCESS)
{
// Le controller est branch
XINPUT_GAMEPAD *Pad = &ControllerState.Gamepad;
bool Up = (Pad->wButtons & XINPUT_GAMEPAD_DPAD_UP);
bool Down = (Pad->wButtons & XINPUT_GAMEPAD_DPAD_DOWN);
bool Left = (Pad->wButtons & XINPUT_GAMEPAD_DPAD_LEFT);
bool Right = (Pad->wButtons & XINPUT_GAMEPAD_DPAD_RIGHT);
bool Start = (Pad->wButtons & XINPUT_GAMEPAD_START);
bool Back = (Pad->wButtons & XINPUT_GAMEPAD_BACK);
bool LeftShoulder = (Pad->wButtons & XINPUT_GAMEPAD_LEFT_SHOULDER);
bool RightShoulder = (Pad->wButtons & XINPUT_GAMEPAD_RIGHT_SHOULDER);
bool AButton = (Pad->wButtons & XINPUT_GAMEPAD_A);
bool BButton = (Pad->wButtons & XINPUT_GAMEPAD_B);
bool XButton = (Pad->wButtons & XINPUT_GAMEPAD_X);
bool YButton = (Pad->wButtons & XINPUT_GAMEPAD_Y);
uint16 StickX = Pad->sThumbLX;
uint16 StickY = Pad->sThumbLY;
// Test d'utilisation de la manette
if (Up) YOffset += 2;
if (Down) YOffset -= 2;
if (Right) XOffset -= 4;
// Vibration de la manette
XINPUT_VIBRATION Vibration;
if (Left)
{
Vibration.wLeftMotorSpeed = 60000;
Vibration.wRightMotorSpeed = 60000;
}
else
{
Vibration.wLeftMotorSpeed = 0;
Vibration.wRightMotorSpeed = 0;
}
XInputSetState(0, &Vibration);
}
else
{
// Le controlleur n'est pas branch
}
}
// Grce PeekMessage on a tout le temps CPU que l'on veut et on peut dessiner ici
RenderWeirdGradient(&GlobalBackBuffer, XOffset, YOffset);
++XOffset;
// On doit alors crire dans la fentre chaque fois que l'on veut rendre
// On en fera une fonction propre
win32_window_dimension Dimension = Win32GetWindowDimension(Window);
Win32DisplayBufferInWindow(
DeviceContext,
Dimension.Width, Dimension.Height,
&GlobalBackBuffer);
ReleaseDC(Window, DeviceContext);
// Pour animer diffremment le gradient
++XOffset;
}
}
else
{
OutputDebugStringA("Error: CreateWindowEx\n");
}
}
else
{
OutputDebugStringA("Error: RegisterClass\n");
}
return(0);
};<commit_msg>Début de gestion du clavier<commit_after>#include <Windows.h>
#include <stdint.h> // Types indpendents de la plateforme
#include <Xinput.h> // Pour la gestion des entres (manette...)
// Pour bien comprendre la diffrence de fonctionnement des variables statiques en C en fonction du scope
#define internal static // fonctions non visible depuis l'extrieur de ce fichier
#define local_persist static // variable visibles juste dans le scope o elle dfinie
#define global_variable static // variable visible dans tous le fichiers (globale)
// Quelques dfinitions de types d'entiers pour ne pas tre dpendant de la plateforme
typedef unsigned char uint8;
typedef uint8_t uint8; // comme un unsigned char, un 8 bits
typedef int16_t uint16;
typedef int32_t uint32;
typedef int64_t uint64;
// Struct qui reprsente un backbuffer qui nous permet de dessiner
struct win32_offscreen_buffer {
BITMAPINFO Info;
void *Memory;
int Width;
int Height;
int BytesPerPixel;
int Pitch; // Pitch reprsente la taille d'une ligne en octets
};
// variables globales pour le moment, on grera autrement plus tard
global_variable bool GlobalRunning;
global_variable win32_offscreen_buffer GlobalBackBuffer;
// Struct qui reprsente des dimensions
struct win32_window_dimension
{
int Width;
int Height;
};
// Permet de renvoyer les dimensions actuelles de la fentre
internal win32_window_dimension
Win32GetWindowDimension(HWND Window) {
win32_window_dimension Result;
RECT ClientRect;
GetClientRect(Window, &ClientRect);
Result.Width = ClientRect.right - ClientRect.left;
Result.Height = ClientRect.bottom - ClientRect.top;
return(Result);
}
// Ici on dfinit des pointeurs vers les fonctions de Xinput
// Cette technique traditionnelle permet d'utiliser des fonctions
// Sans linker directement la lib, et permet aussi de tester si la lib est prsente
// On utilise alors des macros pour dfinir la signature des fonctions
// Ici on dfinit deux fonctions qui vont se subsituer aux vraies si la lib n'est pas trouve
// D'abord pour XInputGetState
#define X_INPUT_GET_STATE(name) DWORD WINAPI name(DWORD dwUserIndex, XINPUT_STATE *pState)
typedef X_INPUT_GET_STATE(x_input_get_state);
X_INPUT_GET_STATE(XInputGetStateStub) {
return(0);
}
global_variable x_input_get_state *XInputGetState_ = XInputGetStateStub;
#define XInputGetState XInputGetState_
// De mme pour XInputSetState
#define X_INPUT_SET_STATE(name) DWORD WINAPI name(DWORD dwUserIndex, XINPUT_VIBRATION *pVibration)
typedef X_INPUT_SET_STATE(x_input_set_state);
X_INPUT_SET_STATE(XInputSetStateStub) {
return(0);
}
global_variable x_input_set_state *XInputSetState_ = XInputSetStateStub;
#define XInputSetState XInputSetState_
// On va alors
internal void
Win32LoadXInput(void) {
HMODULE XInputLibrary = LoadLibrary("xinput1_3.dll"); // on essaye une version un peu plus ancienne qui sera prsente sur plus de machines
if (XInputLibrary)
{
XInputGetState_ = (x_input_get_state*)GetProcAddress(XInputLibrary, "XInputGetState");
XInputSetState_ = (x_input_set_state*)GetProcAddress(XInputLibrary, "XInputSetState");
}
}
/* Fonction qui va dessiner dans le backbuffer un gradient de couleur trange */
internal void
RenderWeirdGradient(win32_offscreen_buffer *Buffer, int XOffset, int YOffset)
{
uint8 *Row = (uint8 *)Buffer->Memory; // on va se dplacer dans la mmoire par pas de 8 bits
for (int Y = 0; Y < Buffer->Height; ++Y)
{
uint32 *Pixel = (uint32 *)Row; // Pixel par pixel, on commence par le premier de la ligne
for (int X = 0; X < Buffer->Width; ++X)
{
/*
Pixels en little endian architecture
0 1 2 3 ...
Pixels en mmoire : 00 00 00 00 ...
Couleur BB GG RR XX
en hexa: 0xXXRRGGBB
*/
uint8 Blue = (X + XOffset);
uint8 Green = (Y + YOffset);
uint8 Red = (X + Y);
// *Pixel = 0xFF00FF00;
*Pixel++ = ((Red << 16) | (Green << 8) | Blue); // ce qui quivaut en hexa 0x00BBGG00
}
Row += Buffer->Pitch; // Ligne suivante
}
}
/**
* Fonction qui permet de dfinir et de rinitialiser un backbuffer en fonction de ses dimensions
* DIB: Device Independent Bitmap
**/
internal void
Win32ResizeDIBSection(win32_offscreen_buffer *Buffer, int Width, int Height)
{
if (Buffer->Memory)
{
VirtualFree(Buffer->Memory, 0, MEM_RELEASE); // cf. VirtualProtect, utile pour debug
}
Buffer->Width = Width;
Buffer->Height = Height;
Buffer->BytesPerPixel = 4;
Buffer->Info.bmiHeader.biSize = sizeof(Buffer->Info.bmiHeader);
Buffer->Info.bmiHeader.biWidth = Buffer->Width;
Buffer->Info.bmiHeader.biHeight = -Buffer->Height; // Attention au sens des coordonnes, du bas vers le haut (d'o le moins)
Buffer->Info.bmiHeader.biPlanes = 1;
Buffer->Info.bmiHeader.biBitCount = 32;
Buffer->Info.bmiHeader.biCompression = BI_RGB;
int BitmapMemorySize = (Buffer->Width * Buffer->Height) * Buffer->BytesPerPixel;
Buffer->Memory = VirtualAlloc(0, BitmapMemorySize, MEM_COMMIT, PAGE_READWRITE); // cf. aussi HeapAlloc
Buffer->Pitch = Width * Buffer->BytesPerPixel;
}
/**
* Ici au dbut on passait ClientRect par rfrence avec un pointeur (*ClientRect)
* cependant comme la structure est petite le passer par valeur est suffisant
**/
internal void
Win32DisplayBufferInWindow(
HDC DeviceContext,
int WindowWidth,
int WindowHeight,
win32_offscreen_buffer *Buffer)
{
StretchDIBits( // copie d'un rectangle vers un autre (scaling si ncessaire, bit oprations...)
DeviceContext,
0, 0, WindowWidth, WindowHeight,
0, 0, Buffer->Width, Buffer->Height,
Buffer->Memory,
&Buffer->Info,
DIB_RGB_COLORS,
SRCCOPY // BitBlt: bit-block transfer of the color data => voir les autres modes dans la MSDN
);
}
/**
* Callback de la fentre principale qui va traiter les messages renvoys par Windows
**/
internal LRESULT CALLBACK
Win32MainWindowCallback(
HWND Window,
UINT Message,
WPARAM WParam,
LPARAM LParam)
{
LRESULT Result = 0;
switch(Message)
{
case WM_SIZE:
{
OutputDebugStringA("WM_SIZE\n");
}
break;
case WM_DESTROY:
{
// PostQuitMessage(0); // Va permettre de sortir de la boucle infinie en dessous
GlobalRunning = false;
OutputDebugStringA("WM_DESTROY\n");
}
break;
case WM_CLOSE:
{
// DestroyWindow(Window);
GlobalRunning = false;
OutputDebugStringA("WM_CLOSE\n");
}
break;
case WM_ACTIVATEAPP:
{
OutputDebugStringA("WM_ACTIVATEAPP\n");
}
break;
case WM_SYSKEYDOWN:
case WM_SYSKEYUP:
case WM_KEYDOWN:
case WM_KEYUP:
{
uint32 VKCode = WParam;
if (VKCode == 'Z')
{
OutputDebugStringA("Z\n");
}
else if (VKCode == 'S')
{
OutputDebugStringA("S\n");
}
else if (VKCode == 'Q')
{
OutputDebugStringA("Q\n");
}
else if (VKCode == 'D')
{
OutputDebugStringA("D\n");
}
else if (VKCode == VK_UP)
{
OutputDebugStringA("UP\n");
}
else if (VKCode == VK_DOWN)
{
OutputDebugStringA("DOWN\n");
}
else if (VKCode == VK_LEFT)
{
OutputDebugStringA("LEFT\n");
}
else if (VKCode == VK_RIGHT)
{
OutputDebugStringA("RIGHT\n");
}
else if (VKCode == VK_ESCAPE)
{
OutputDebugStringA("ESCAPE\n");
}
else if (VKCode == VK_SPACE)
{
OutputDebugStringA("SPACE\n");
}
}
break;
case WM_PAINT:
{
PAINTSTRUCT Paint;
HDC DeviceContext = BeginPaint(Window, &Paint);
win32_window_dimension Dimension = Win32GetWindowDimension(Window);
Win32DisplayBufferInWindow(DeviceContext, Dimension.Width, Dimension.Height, &GlobalBackBuffer);
EndPaint(Window, &Paint);
}
break;
default:
{
// OutputDebugStringA("default\n");
Result = DefWindowProc(Window, Message, WParam, LParam);
}
break;
}
return(Result);
}
/**
* Main du programme qui va initialiser la fentre et grer la boucle principale : attente des messages,
* gestion de la manette et du clavier, dessin...
**/
int CALLBACK
WinMain(
HINSTANCE Instance,
HINSTANCE PrevInstance,
LPSTR CommandLine,
int ShowCode)
{
// On essaye de charger les fonctions de la dll qui gre les manettes
Win32LoadXInput();
// Cration de la fentre principale
WNDCLASSA WindowClass = {}; // initialisation par dfaut, ANSI version de WNDCLASSA
Win32ResizeDIBSection(&GlobalBackBuffer, 800, 600);
// On ne configure que les membres que l'on veut
WindowClass.style = CS_HREDRAW|CS_VREDRAW|CS_OWNDC; // indique que l'on veut rafraichir la fentre entire lors d'un resize (horizontal et vertical)
WindowClass.lpfnWndProc = Win32MainWindowCallback;
WindowClass.hInstance = Instance;
// WindowClass.hIcon;
WindowClass.lpszClassName = "FaitmainHerosWindowClass"; // nom pour retrouver la fentre
// Ouverture de la fentre
if (RegisterClassA(&WindowClass))
{
HWND Window = CreateWindowExA( // ANSI version de CreateWindowEx
0, // dwExStyle : options de la fentre
WindowClass.lpszClassName,
"FaitmainHeros",
WS_OVERLAPPEDWINDOW|WS_VISIBLE, //dwStyle : overlapped window, visible par dfaut
CW_USEDEFAULT, // X
CW_USEDEFAULT, // Y
CW_USEDEFAULT, // nWidth
CW_USEDEFAULT, // nHeight
0, // hWndParent : 0 pour dire que c'est une fentre top
0, // hMenu : 0 pour dire pas de menu
Instance,
0 // Pas de passage de paramtres la fentre
);
if (Window)
{
// Comme on a spcifi CS_OWNDC on peut initialiser un seul HDC
// et s'en servir indfiniment car on ne le partage pas
HDC DeviceContext = GetDC(Window);
int XOffset = 0;
int YOffset = 0;
GlobalRunning = true;
while (GlobalRunning) // boucle infinie pour traiter tous les messages
{
MSG Message;
while(PeekMessageA(&Message, 0, 0, 0, PM_REMOVE)) // On utilise PeekMessage au lieu de GetMessage qui est bloquant
{
if (Message.message == WM_QUIT) GlobalRunning = false;
TranslateMessage(&Message); // On demande Windows de traiter le message
DispatchMessage(&Message); // Envoie le message au main WindowCallback, que l'on a dfini et dclar au dessus
}
// Gestion des entres, pour le moment on gre a chaque image, il faudra peut-tre le faire plus frquemment
// surtout si le nombre d'images par seconde chute
for (DWORD ControllerIndex = 0; ControllerIndex < XUSER_MAX_COUNT; ++ControllerIndex)
{
XINPUT_STATE ControllerState;
if (XInputGetState(ControllerIndex, &ControllerState) == ERROR_SUCCESS)
{
// Le controller est branch
XINPUT_GAMEPAD *Pad = &ControllerState.Gamepad;
bool Up = (Pad->wButtons & XINPUT_GAMEPAD_DPAD_UP);
bool Down = (Pad->wButtons & XINPUT_GAMEPAD_DPAD_DOWN);
bool Left = (Pad->wButtons & XINPUT_GAMEPAD_DPAD_LEFT);
bool Right = (Pad->wButtons & XINPUT_GAMEPAD_DPAD_RIGHT);
bool Start = (Pad->wButtons & XINPUT_GAMEPAD_START);
bool Back = (Pad->wButtons & XINPUT_GAMEPAD_BACK);
bool LeftShoulder = (Pad->wButtons & XINPUT_GAMEPAD_LEFT_SHOULDER);
bool RightShoulder = (Pad->wButtons & XINPUT_GAMEPAD_RIGHT_SHOULDER);
bool AButton = (Pad->wButtons & XINPUT_GAMEPAD_A);
bool BButton = (Pad->wButtons & XINPUT_GAMEPAD_B);
bool XButton = (Pad->wButtons & XINPUT_GAMEPAD_X);
bool YButton = (Pad->wButtons & XINPUT_GAMEPAD_Y);
uint16 StickX = Pad->sThumbLX;
uint16 StickY = Pad->sThumbLY;
// Test d'utilisation de la manette
if (Up) YOffset += 2;
if (Down) YOffset -= 2;
if (Right) XOffset -= 4;
// Vibration de la manette
XINPUT_VIBRATION Vibration;
if (Left)
{
Vibration.wLeftMotorSpeed = 60000;
Vibration.wRightMotorSpeed = 60000;
}
else
{
Vibration.wLeftMotorSpeed = 0;
Vibration.wRightMotorSpeed = 0;
}
XInputSetState(0, &Vibration);
}
else
{
// Le controlleur n'est pas branch
}
}
// Grce PeekMessage on a tout le temps CPU que l'on veut et on peut dessiner ici
RenderWeirdGradient(&GlobalBackBuffer, XOffset, YOffset);
++XOffset;
// On doit alors crire dans la fentre chaque fois que l'on veut rendre
// On en fera une fonction propre
win32_window_dimension Dimension = Win32GetWindowDimension(Window);
Win32DisplayBufferInWindow(
DeviceContext,
Dimension.Width, Dimension.Height,
&GlobalBackBuffer);
ReleaseDC(Window, DeviceContext);
// Pour animer diffremment le gradient
++XOffset;
}
}
else
{
OutputDebugStringA("Error: CreateWindowEx\n");
}
}
else
{
OutputDebugStringA("Error: RegisterClass\n");
}
return(0);
};<|endoftext|> |
<commit_before>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
*
* Condor Software Copyright Notice
* Copyright (C) 1990-2006, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* This source code is covered by the Condor Public License, which can
* be found in the accompanying LICENSE.TXT file, or online at
* www.condorproject.org.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* AND THE UNIVERSITY OF WISCONSIN-MADISON "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY, OF SATISFACTORY QUALITY, AND FITNESS
* FOR A PARTICULAR PURPOSE OR USE ARE DISCLAIMED. THE COPYRIGHT
* HOLDERS AND CONTRIBUTORS AND THE UNIVERSITY OF WISCONSIN-MADISON
* MAKE NO MAKE NO REPRESENTATION THAT THE SOFTWARE, MODIFICATIONS,
* ENHANCEMENTS OR DERIVATIVE WORKS THEREOF, WILL NOT INFRINGE ANY
* PATENT, COPYRIGHT, TRADEMARK, TRADE SECRET OR OTHER PROPRIETARY
* RIGHT.
*
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/
#define _CONDOR_ALLOW_OPEN 1 // because this is used in the test suite
/* the below is defined in test suite programs that use these files. */
#ifndef NO_CONDOR_COMMON
#include "condor_common.h"
#endif
#include "memory_file.h"
#include "condor_fix_iostream.h"
static const int DEFAULT_BUFFER_SIZE=1024;
static const int COMPARE_BUFFER_SIZE=10000;
memory_file::memory_file()
{
buffer = new char[DEFAULT_BUFFER_SIZE];
bufsize = DEFAULT_BUFFER_SIZE;
memset(buffer, 0, bufsize);
pointer = filesize = 0;
}
memory_file::~memory_file()
{
if( buffer ) delete [] buffer;
}
/*
Compare this memory_file against a real file.
Return the number of errors found.
*/
int memory_file::compare( char *filename )
{
int errors=0;
off_t position=0, chunksize=0;
char cbuffer[COMPARE_BUFFER_SIZE];
int fd = open(filename,O_RDONLY);
if( fd==-1 ) {
cerr << "Couldn't open " << filename << endl;
return 100;
}
while(1) {
chunksize = ::read(fd,cbuffer,COMPARE_BUFFER_SIZE);
if(chunksize<=0) break;
errors += count_errors( cbuffer, &buffer[position], chunksize, position );
position += chunksize;
if( errors>10 ) {
cout << "Too many errors, stopping.\n";
break;
}
}
if(position!=filesize) {
cout << "SIZE ERROR:\nFile was " << position
<< " bytes, but mem was " << filesize
<< " bytes.\n";
errors++;
}
::close(fd);
return errors;
}
/*
Move the current seek pointer to a new position, as lseek(2).
Return the new pointer, or -1 in case of an error.
*/
off_t memory_file::seek( off_t offset, int whence )
{
off_t newpointer;
switch(whence) {
case SEEK_SET:
newpointer = offset;
break;
case SEEK_CUR:
newpointer = pointer+offset;
break;
case SEEK_END:
newpointer = filesize+offset;
break;
}
if( newpointer<0 ) {
return -1;
} else {
pointer = newpointer;
}
return pointer;
}
/*
Read from the simulated file, as read(2).
Returns the number of bytes read, or an error.
*/
ssize_t memory_file::read( char *data, size_t length )
{
if( (data==0) || (length<0) || (pointer<0) ) return -1;
if( pointer>=filesize ) return 0;
if(length==0) return 0;
if((pointer+(off_t)length)>filesize) length = filesize-pointer;
memcpy(data,&buffer[pointer],length);
pointer += length;
return length;
}
/*
Write to the simulated file, as write(2).
Returns the number of bytes written, or an error.
*/
ssize_t memory_file::write( char *data, size_t length )
{
if( (data==0) || (length<0) || (pointer<0) ) return -1;
if(length==0) return 0;
ensure(pointer+length);
memcpy(&buffer[pointer],data,length);
pointer+=length;
if( pointer>filesize ) filesize=pointer;
return length;
}
/*
Expand the buffer so that it can hold up to needed.
To minimize memory allocations, the buffer size is
increased by powers of two.
*/
void memory_file::ensure( int needed )
{
if( needed>bufsize ) {
int newsize = bufsize;
while(newsize<needed) newsize*=2;
char *newbuffer = new char[newsize];
memcpy(newbuffer,buffer,bufsize);
memset(&newbuffer[bufsize], 0, newsize-bufsize);
delete [] buffer;
buffer = newbuffer;
bufsize = newsize;
}
}
/*
Count the number of discrepancies between two buffers and
return that number. Display any errors along the way.
*/
int count_errors( char *b1, char *b2, int length, int offset )
{
int errors=0;
for( int i=0; i<length; i++ ) {
if( b1[i]!=b2[i] ) {
if(!errors) cout << "FOUND ERROR:\npos\ta\tb\n";
errors++;
cout << (i+offset) << '\t' << (int)b1[i] << '\t' << (int)b2[i] << endl;
if( errors>50 ) {
cout << "Too many errors, stopping." << endl;
return 50;
}
}
}
return errors;
}
<commit_msg>remove warning<commit_after>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**
*
* Condor Software Copyright Notice
* Copyright (C) 1990-2006, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* This source code is covered by the Condor Public License, which can
* be found in the accompanying LICENSE.TXT file, or online at
* www.condorproject.org.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* AND THE UNIVERSITY OF WISCONSIN-MADISON "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY, OF SATISFACTORY QUALITY, AND FITNESS
* FOR A PARTICULAR PURPOSE OR USE ARE DISCLAIMED. THE COPYRIGHT
* HOLDERS AND CONTRIBUTORS AND THE UNIVERSITY OF WISCONSIN-MADISON
* MAKE NO MAKE NO REPRESENTATION THAT THE SOFTWARE, MODIFICATIONS,
* ENHANCEMENTS OR DERIVATIVE WORKS THEREOF, WILL NOT INFRINGE ANY
* PATENT, COPYRIGHT, TRADEMARK, TRADE SECRET OR OTHER PROPRIETARY
* RIGHT.
*
****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/
#define _CONDOR_ALLOW_OPEN 1 // because this is used in the test suite
/* the below is defined in test suite programs that use these files. */
#ifndef NO_CONDOR_COMMON
#include "condor_common.h"
#endif
#include "memory_file.h"
#include "condor_fix_iostream.h"
static const int DEFAULT_BUFFER_SIZE=1024;
static const int COMPARE_BUFFER_SIZE=10000;
memory_file::memory_file()
{
buffer = new char[DEFAULT_BUFFER_SIZE];
bufsize = DEFAULT_BUFFER_SIZE;
memset(buffer, 0, bufsize);
pointer = filesize = 0;
}
memory_file::~memory_file()
{
if( buffer ) delete [] buffer;
}
/*
Compare this memory_file against a real file.
Return the number of errors found.
*/
int memory_file::compare( char *filename )
{
int errors=0;
off_t position=0, chunksize=0;
char cbuffer[COMPARE_BUFFER_SIZE];
int fd = open(filename,O_RDONLY);
if( fd==-1 ) {
cerr << "Couldn't open " << filename << endl;
return 100;
}
while(1) {
chunksize = ::read(fd,cbuffer,COMPARE_BUFFER_SIZE);
if(chunksize<=0) break;
errors += count_errors( cbuffer, &buffer[position], chunksize, position );
position += chunksize;
if( errors>10 ) {
cout << "Too many errors, stopping.\n";
break;
}
}
if(position!=filesize) {
cout << "SIZE ERROR:\nFile was " << position
<< " bytes, but mem was " << filesize
<< " bytes.\n";
errors++;
}
::close(fd);
return errors;
}
/*
Move the current seek pointer to a new position, as lseek(2).
Return the new pointer, or -1 in case of an error.
*/
off_t memory_file::seek( off_t offset, int whence )
{
off_t newpointer;
switch(whence) {
case SEEK_SET:
newpointer = offset;
break;
case SEEK_CUR:
newpointer = pointer+offset;
break;
case SEEK_END:
newpointer = filesize+offset;
break;
}
if( newpointer<0 ) {
return -1;
} else {
pointer = newpointer;
}
return pointer;
}
/*
Read from the simulated file, as read(2).
Returns the number of bytes read, or an error.
*/
ssize_t memory_file::read( char *data, size_t length )
{
if( (data==0) || (pointer<0) ) return -1;
if( pointer>=filesize ) return 0;
if(length==0) return 0;
if((pointer+(off_t)length)>filesize) length = filesize-pointer;
memcpy(data,&buffer[pointer],length);
pointer += length;
return length;
}
/*
Write to the simulated file, as write(2).
Returns the number of bytes written, or an error.
*/
ssize_t memory_file::write( char *data, size_t length )
{
if( (data==0) || (pointer<0) ) return -1;
if(length==0) return 0;
ensure(pointer+length);
memcpy(&buffer[pointer],data,length);
pointer+=length;
if( pointer>filesize ) filesize=pointer;
return length;
}
/*
Expand the buffer so that it can hold up to needed.
To minimize memory allocations, the buffer size is
increased by powers of two.
*/
void memory_file::ensure( int needed )
{
if( needed>bufsize ) {
int newsize = bufsize;
while(newsize<needed) newsize*=2;
char *newbuffer = new char[newsize];
memcpy(newbuffer,buffer,bufsize);
memset(&newbuffer[bufsize], 0, newsize-bufsize);
delete [] buffer;
buffer = newbuffer;
bufsize = newsize;
}
}
/*
Count the number of discrepancies between two buffers and
return that number. Display any errors along the way.
*/
int count_errors( char *b1, char *b2, int length, int offset )
{
int errors=0;
for( int i=0; i<length; i++ ) {
if( b1[i]!=b2[i] ) {
if(!errors) cout << "FOUND ERROR:\npos\ta\tb\n";
errors++;
cout << (i+offset) << '\t' << (int)b1[i] << '\t' << (int)b2[i] << endl;
if( errors>50 ) {
cout << "Too many errors, stopping." << endl;
return 50;
}
}
}
return errors;
}
<|endoftext|> |
<commit_before>#include "texture.h"
#include "platform.h"
#include "util/geom.h"
#include "gl/renderState.h"
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#include <cstring> // for memset
namespace Tangram {
int Texture::s_validGeneration = 0;
Texture::Texture(unsigned int _width, unsigned int _height, TextureOptions _options, bool _generateMipmaps)
: m_options(_options), m_generateMipmaps(_generateMipmaps) {
m_glHandle = 0;
m_dirty = false;
m_shouldResize = false;
m_target = GL_TEXTURE_2D;
m_generation = -1;
resize(_width, _height);
}
Texture::Texture(const std::string& _file, TextureOptions _options, bool _generateMipmaps)
: Texture(0, 0, _options, _generateMipmaps) {
unsigned int size;
unsigned char* data = bytesFromResource(_file.c_str(), &size);
unsigned char* pixels;
int width, height, comp;
pixels = stbi_load_from_memory(data, size, &width, &height, &comp, STBI_rgb_alpha);
resize(width, height);
setData(reinterpret_cast<GLuint*>(pixels), width * height);
update(0);
free(data);
stbi_image_free(pixels);
}
Texture::~Texture() {
if (m_glHandle) {
glDeleteTextures(1, &m_glHandle);
// if the texture is bound, and deleted, the binding defaults to 0 according to the OpenGL
// spec, in this case we need to force the currently bound texture to 0 in the render states
if (RenderState::texture.compare(m_target, m_glHandle)) {
RenderState::texture.init(m_target, 0, false);
}
}
}
void Texture::setData(const GLuint* _data, unsigned int _dataSize) {
if (m_data.size() > 0) { m_data.clear(); }
m_data.insert(m_data.begin(), _data, _data + _dataSize);
m_dirty = true;
}
void Texture::setSubData(const GLuint* _subData, unsigned int _xoff, unsigned int _yoff, unsigned int _width,
unsigned int _height) {
// update m_data with subdata
size_t bpp = bytesPerPixel();
size_t divisor = sizeof(GLuint) / bpp;
for (size_t j = 0; j < _height; j++) {
size_t dpos = ((j + _yoff) * m_width + _xoff) / divisor;
size_t spos = (j * _width) / divisor;
std::memcpy(&m_data[dpos], &_subData[spos], _width * bpp);
}
m_subData.push_back({{_subData, _subData + (_width * _height) / divisor}, _xoff, _yoff, _width, _height});
m_dirty = true;
}
void Texture::bind(GLuint _unit) {
RenderState::textureUnit(_unit);
RenderState::texture(m_target, m_glHandle);
}
void Texture::generate(GLuint _textureUnit) {
glGenTextures(1, &m_glHandle);
bind(_textureUnit);
if (m_generateMipmaps) {
GLenum mipmapFlags = GL_LINEAR_MIPMAP_LINEAR | GL_LINEAR_MIPMAP_NEAREST | GL_NEAREST_MIPMAP_LINEAR | GL_NEAREST_MIPMAP_NEAREST;
if (m_options.m_filtering.m_min & mipmapFlags) {
logMsg("Warning: wrong options provided for the usage of mipmap generation\n");
}
}
glTexParameteri(m_target, GL_TEXTURE_MIN_FILTER, m_options.m_filtering.m_min);
glTexParameteri(m_target, GL_TEXTURE_MAG_FILTER, m_options.m_filtering.m_mag);
glTexParameteri(m_target, GL_TEXTURE_WRAP_S, m_options.m_wrapping.m_wraps);
glTexParameteri(m_target, GL_TEXTURE_WRAP_T, m_options.m_wrapping.m_wrapt);
m_generation = s_validGeneration;
}
void Texture::checkValidity() {
if (m_generation != s_validGeneration) {
m_dirty = true;
m_shouldResize = true;
m_glHandle = 0;
}
}
void Texture::update(GLuint _textureUnit) {
checkValidity();
if (!m_dirty) { return; }
if (m_glHandle == 0) { // texture hasn't been initialized yet, generate it
generate(_textureUnit);
if (m_data.size() == 0) { m_data.assign(m_width * m_height, 0); }
} else {
bind(_textureUnit);
}
GLuint* data = m_data.size() > 0 ? m_data.data() : nullptr;
// resize or push data
if (m_shouldResize) {
glTexImage2D(m_target, 0, m_options.m_internalFormat, m_width, m_height, 0, m_options.m_format, GL_UNSIGNED_BYTE, data);
if (data && m_generateMipmaps) {
// generate the mipmaps for this texture
glGenerateMipmap(m_target);
}
m_shouldResize = false;
}
// process queued sub data updates
while (m_subData.size() > 0) {
TextureSubData& subData = m_subData.front();
glTexSubImage2D(m_target, 0, subData.m_xoff, subData.m_yoff, subData.m_width, subData.m_height,
m_options.m_format, GL_UNSIGNED_BYTE, subData.m_data.data());
m_subData.pop();
}
m_dirty = false;
}
void Texture::resize(const unsigned int _width, const unsigned int _height) {
m_width = _width;
m_height = _height;
m_shouldResize = true;
m_dirty = true;
}
size_t Texture::bytesPerPixel() {
switch (m_options.m_internalFormat) {
case GL_ALPHA:
case GL_LUMINANCE:
return 1;
case GL_LUMINANCE_ALPHA:
return 2;
case GL_RGB:
return 3;
default:
return 4;
}
}
void Texture::invalidateAllTextures() {
++s_validGeneration;
}
}
<commit_msg>fix: initialization of Texture m_data<commit_after>#include "texture.h"
#include "platform.h"
#include "util/geom.h"
#include "gl/renderState.h"
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#include <cstring> // for memset
namespace Tangram {
int Texture::s_validGeneration = 0;
Texture::Texture(unsigned int _width, unsigned int _height, TextureOptions _options, bool _generateMipmaps)
: m_options(_options), m_generateMipmaps(_generateMipmaps) {
m_glHandle = 0;
m_dirty = false;
m_shouldResize = false;
m_target = GL_TEXTURE_2D;
m_generation = -1;
resize(_width, _height);
}
Texture::Texture(const std::string& _file, TextureOptions _options, bool _generateMipmaps)
: Texture(0, 0, _options, _generateMipmaps) {
unsigned int size;
unsigned char* data = bytesFromResource(_file.c_str(), &size);
unsigned char* pixels;
int width, height, comp;
pixels = stbi_load_from_memory(data, size, &width, &height, &comp, STBI_rgb_alpha);
resize(width, height);
setData(reinterpret_cast<GLuint*>(pixels), width * height);
update(0);
free(data);
stbi_image_free(pixels);
}
Texture::~Texture() {
if (m_glHandle) {
glDeleteTextures(1, &m_glHandle);
// if the texture is bound, and deleted, the binding defaults to 0 according to the OpenGL
// spec, in this case we need to force the currently bound texture to 0 in the render states
if (RenderState::texture.compare(m_target, m_glHandle)) {
RenderState::texture.init(m_target, 0, false);
}
}
}
void Texture::setData(const GLuint* _data, unsigned int _dataSize) {
if (m_data.size() > 0) { m_data.clear(); }
m_data.insert(m_data.begin(), _data, _data + _dataSize);
m_dirty = true;
}
void Texture::setSubData(const GLuint* _subData, unsigned int _xoff, unsigned int _yoff, unsigned int _width,
unsigned int _height) {
size_t bpp = bytesPerPixel();
size_t divisor = sizeof(GLuint) / bpp;
// Init m_data if update() was not called after resize()
if (m_data.size() != (m_width * m_height) / divisor) {
m_data.resize((m_width * m_height) / divisor);
}
// update m_data with subdata
for (size_t j = 0; j < _height; j++) {
size_t dpos = ((j + _yoff) * m_width + _xoff) / divisor;
size_t spos = (j * _width) / divisor;
std::memcpy(&m_data[dpos], &_subData[spos], _width * bpp);
}
m_subData.push_back({{_subData, _subData + (_width * _height) / divisor}, _xoff, _yoff, _width, _height});
m_dirty = true;
}
void Texture::bind(GLuint _unit) {
RenderState::textureUnit(_unit);
RenderState::texture(m_target, m_glHandle);
}
void Texture::generate(GLuint _textureUnit) {
glGenTextures(1, &m_glHandle);
bind(_textureUnit);
if (m_generateMipmaps) {
GLenum mipmapFlags = GL_LINEAR_MIPMAP_LINEAR | GL_LINEAR_MIPMAP_NEAREST | GL_NEAREST_MIPMAP_LINEAR | GL_NEAREST_MIPMAP_NEAREST;
if (m_options.m_filtering.m_min & mipmapFlags) {
logMsg("Warning: wrong options provided for the usage of mipmap generation\n");
}
}
glTexParameteri(m_target, GL_TEXTURE_MIN_FILTER, m_options.m_filtering.m_min);
glTexParameteri(m_target, GL_TEXTURE_MAG_FILTER, m_options.m_filtering.m_mag);
glTexParameteri(m_target, GL_TEXTURE_WRAP_S, m_options.m_wrapping.m_wraps);
glTexParameteri(m_target, GL_TEXTURE_WRAP_T, m_options.m_wrapping.m_wrapt);
m_generation = s_validGeneration;
}
void Texture::checkValidity() {
if (m_generation != s_validGeneration) {
m_dirty = true;
m_shouldResize = true;
m_glHandle = 0;
}
}
void Texture::update(GLuint _textureUnit) {
checkValidity();
if (!m_dirty) { return; }
if (m_glHandle == 0) { // texture hasn't been initialized yet, generate it
generate(_textureUnit);
if (m_data.size() == 0) {
size_t divisor = sizeof(GLuint) / bytesPerPixel();
m_data.resize((m_width * m_height) / divisor, 0);
}
} else {
bind(_textureUnit);
}
GLuint* data = m_data.size() > 0 ? m_data.data() : nullptr;
// resize or push data
if (m_shouldResize) {
glTexImage2D(m_target, 0, m_options.m_internalFormat, m_width, m_height, 0, m_options.m_format, GL_UNSIGNED_BYTE, data);
if (data && m_generateMipmaps) {
// generate the mipmaps for this texture
glGenerateMipmap(m_target);
}
m_shouldResize = false;
}
// process queued sub data updates
while (m_subData.size() > 0) {
TextureSubData& subData = m_subData.front();
glTexSubImage2D(m_target, 0, subData.m_xoff, subData.m_yoff, subData.m_width, subData.m_height,
m_options.m_format, GL_UNSIGNED_BYTE, subData.m_data.data());
m_subData.pop();
}
m_dirty = false;
}
void Texture::resize(const unsigned int _width, const unsigned int _height) {
m_width = _width;
m_height = _height;
m_shouldResize = true;
m_dirty = true;
}
size_t Texture::bytesPerPixel() {
switch (m_options.m_internalFormat) {
case GL_ALPHA:
case GL_LUMINANCE:
return 1;
case GL_LUMINANCE_ALPHA:
return 2;
case GL_RGB:
return 3;
default:
return 4;
}
}
void Texture::invalidateAllTextures() {
++s_validGeneration;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2016 Florent Revest <[email protected]>
* All rights reserved.
*
* You may use this file under the terms of BSD license as follows:
*
* 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 HOLDERS 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 "flatmeshnode.h"
#include <math.h>
#include <QScreen>
#include <QElapsedTimer>
/* Used to compute a triangle color from its distance to the center */
static inline QColor interpolateColors(const QColor& color1, const QColor& color2, qreal ratio)
{
/* Linear scale is too harsh, this looks better. This is not supposed to be called very often */
ratio = pow(ratio, 1.7);
if (ratio>1) ratio=1;
int r = color1.red()*(1-ratio) + color2.red()*ratio;
int g = color1.green()*(1-ratio) + color2.green()*ratio;
int b = color1.blue()*(1-ratio) + color2.blue()*ratio;
return QColor(r, g, b);
}
FlatMeshNode::FlatMeshNode(QQuickWindow *window, QRectF boundingRect)
: QSGSimpleRectNode(boundingRect, Qt::transparent),
m_animationState(0), m_window(window)
{
connect(window, SIGNAL(afterRendering()), this, SLOT(maybeAnimate()));
connect(window, SIGNAL(widthChanged(int)), this, SLOT(generateGrid()));
connect(window, SIGNAL(heightChanged(int)), this, SLOT(generateGrid()));
srand(time(NULL));
generateGrid();
for(int y = 0; y < NUM_POINTS_Y-1; y++) {
for(int x = 0; x < NUM_POINTS_X-1; x++) {
for(int n = 0; n < 2; n++) {
QSGGeometryNode *triangle = new QSGGeometryNode();
QSGFlatColorMaterial *color = new QSGFlatColorMaterial;
triangle->setOpaqueMaterial(color);
QSGGeometry *geometry = new QSGGeometry(QSGGeometry::defaultAttributes_Point2D(), 3);
triangle->setGeometry(geometry);
appendChildNode(triangle);
}
}
}
}
void FlatMeshNode::updateColors()
{
int centerX = m_unitWidth*((NUM_POINTS_X-2)/2);
int centerY = m_unitHeight*((NUM_POINTS_Y-2)/2);
int radius = rect().width()*0.6;
QSGGeometryNode *triangle = static_cast<QSGGeometryNode *>(firstChild());
for(int y = 0; y < NUM_POINTS_Y-1; y++) {
for(int x = 0; x < NUM_POINTS_X-1; x++) {
for(int n = 0; n < 2; n++) {
QSGFlatColorMaterial *color = static_cast<QSGFlatColorMaterial *>(triangle->opaqueMaterial());
color->setColor(interpolateColors(m_centerColor, m_outerColor,
sqrt(pow(m_points[y*NUM_POINTS_Y+x].centerX-centerX, 2) + pow(m_points[y*NUM_POINTS_Y+x].centerY-centerY, 2))/radius));
triangle->setOpaqueMaterial(color);
triangle->markDirty(QSGNode::DirtyMaterial);
triangle = static_cast<QSGGeometryNode *>(triangle->nextSibling());
}
}
}
}
void FlatMeshNode::setCenterColor(QColor c)
{
if (c == m_centerColor)
return;
m_centerColor = c;
updateColors();
}
void FlatMeshNode::setOuterColor(QColor c)
{
if (c == m_outerColor)
return;
m_outerColor = c;
updateColors();
}
/* When the size changes, regenerate a grid of points that serves as a base for further operations */
void FlatMeshNode::generateGrid()
{
m_unitWidth = rect().width()/(NUM_POINTS_X-2);
m_unitHeight = rect().height()/(NUM_POINTS_Y-2);
for(int y = 0; y < NUM_POINTS_Y; y++) {
for(int x = 0; x < NUM_POINTS_X; x++) {
Point *point = &m_points[y*NUM_POINTS_Y+x];
point->centerX = m_unitWidth*x;
point->centerY = m_unitHeight*y;
if(x != 0 && x != (NUM_POINTS_X-1)) {
point->animOriginX = point->centerX + rand()%m_unitWidth - m_unitWidth/2;
point->animEndX = point->centerX + rand()%m_unitWidth - m_unitWidth/2;
}
else
point->animEndX = point->animOriginX = point->centerX;
if(y != 0 && y != (NUM_POINTS_Y-1)) {
point->animOriginY = point->centerY + rand()%m_unitHeight - m_unitHeight/2;
point->animEndY = point->centerY + rand()%m_unitHeight - m_unitHeight/2;
}
else
point->animEndY = point->animOriginY = point->centerY;
}
}
}
void FlatMeshNode::setAnimated(bool animated)
{
m_animated = animated;
}
void FlatMeshNode::maybeAnimate()
{
static QElapsedTimer t;
if(!t.isValid()) t.start();
if (m_animated && t.elapsed() >= 100) {
t.restart();
m_animationState += 0.03;
/* Interpolate all points positions according to the animationState */
for(int i = 0; i < NUM_POINTS_X*NUM_POINTS_Y; i++) {
Point *p = &m_points[i];
p->currentPos.x = p->animOriginX + (p->animEndX-p->animOriginX)*m_animationState;
p->currentPos.y = p->animOriginY + (p->animEndY-p->animOriginY)*m_animationState;
}
/* Update all triangles' geometries according to the new points position */
QSGGeometryNode *triangle = static_cast<QSGGeometryNode *>(firstChild());
for(int i = 0; i < NUM_POINTS_X*NUM_POINTS_Y; i++) {
if(m_points[i].centerX != m_unitWidth*(NUM_POINTS_X-1) && m_points[i].centerY != m_unitHeight*(NUM_POINTS_Y-1)) {
int random = rand()%2;
for(int n = 0; n < 2; n++) {
QSGGeometry::Point2D *v = triangle->geometry()->vertexDataAsPoint2D();
if(random==0) {
if(n==0) {
v[0] = m_points[i].currentPos;
v[1] = m_points[i+NUM_POINTS_X].currentPos;
v[2] = m_points[i+NUM_POINTS_X+1].currentPos;
} else if(n==1) {
v[0] = m_points[i].currentPos;
v[1] = m_points[i+1].currentPos;
v[2] = m_points[i+NUM_POINTS_X+1].currentPos;
}
} else {
if(n==0) {
v[0] = m_points[i].currentPos;
v[1] = m_points[i+NUM_POINTS_X].currentPos;
v[2] = m_points[i+1].currentPos;
} else if(n==1) {
v[0] = m_points[i+NUM_POINTS_X].currentPos;
v[1] = m_points[i+1].currentPos;
v[2] = m_points[i+NUM_POINTS_X+1].currentPos;
}
}
triangle->markDirty(QSGNode::DirtyGeometry);
triangle = static_cast<QSGGeometryNode *>(triangle->nextSibling());
}
}
}
/* Regenerate a set of animation end points when the animation is finished */
if(m_animationState >= 1.0) {
m_animationState = 0.0;
for(int y = 0; y < NUM_POINTS_Y; y++) {
for(int x = 0; x < NUM_POINTS_X; x++) {
Point *point = &m_points[y*NUM_POINTS_Y+x];
if(x != 0 && x != (NUM_POINTS_X-1)) {
point->animOriginX = point->animEndX;
point->animEndX = point->centerX + rand()%m_unitWidth - m_unitWidth/2;
}
if(y != 0 && y != (NUM_POINTS_Y-1)) {
point->animOriginY = point->animEndY;
point->animEndY = point->centerY + rand()%m_unitHeight - m_unitHeight/2;
}
}
}
}
}
}
<commit_msg>FlatMeshNode: don't skip first frame<commit_after>/*
* Copyright (C) 2016 Florent Revest <[email protected]>
* All rights reserved.
*
* You may use this file under the terms of BSD license as follows:
*
* 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 HOLDERS 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 "flatmeshnode.h"
#include <math.h>
#include <QScreen>
#include <QElapsedTimer>
/* Used to compute a triangle color from its distance to the center */
static inline QColor interpolateColors(const QColor& color1, const QColor& color2, qreal ratio)
{
/* Linear scale is too harsh, this looks better. This is not supposed to be called very often */
ratio = pow(ratio, 1.7);
if (ratio>1) ratio=1;
int r = color1.red()*(1-ratio) + color2.red()*ratio;
int g = color1.green()*(1-ratio) + color2.green()*ratio;
int b = color1.blue()*(1-ratio) + color2.blue()*ratio;
return QColor(r, g, b);
}
FlatMeshNode::FlatMeshNode(QQuickWindow *window, QRectF boundingRect)
: QSGSimpleRectNode(boundingRect, Qt::transparent),
m_animationState(0), m_window(window)
{
connect(window, SIGNAL(afterRendering()), this, SLOT(maybeAnimate()));
connect(window, SIGNAL(widthChanged(int)), this, SLOT(generateGrid()));
connect(window, SIGNAL(heightChanged(int)), this, SLOT(generateGrid()));
srand(time(NULL));
generateGrid();
for(int y = 0; y < NUM_POINTS_Y-1; y++) {
for(int x = 0; x < NUM_POINTS_X-1; x++) {
for(int n = 0; n < 2; n++) {
QSGGeometryNode *triangle = new QSGGeometryNode();
QSGFlatColorMaterial *color = new QSGFlatColorMaterial;
triangle->setOpaqueMaterial(color);
QSGGeometry *geometry = new QSGGeometry(QSGGeometry::defaultAttributes_Point2D(), 3);
triangle->setGeometry(geometry);
appendChildNode(triangle);
}
}
}
}
void FlatMeshNode::updateColors()
{
int centerX = m_unitWidth*((NUM_POINTS_X-2)/2);
int centerY = m_unitHeight*((NUM_POINTS_Y-2)/2);
int radius = rect().width()*0.6;
QSGGeometryNode *triangle = static_cast<QSGGeometryNode *>(firstChild());
for(int y = 0; y < NUM_POINTS_Y-1; y++) {
for(int x = 0; x < NUM_POINTS_X-1; x++) {
for(int n = 0; n < 2; n++) {
QSGFlatColorMaterial *color = static_cast<QSGFlatColorMaterial *>(triangle->opaqueMaterial());
color->setColor(interpolateColors(m_centerColor, m_outerColor,
sqrt(pow(m_points[y*NUM_POINTS_Y+x].centerX-centerX, 2) + pow(m_points[y*NUM_POINTS_Y+x].centerY-centerY, 2))/radius));
triangle->setOpaqueMaterial(color);
triangle->markDirty(QSGNode::DirtyMaterial);
triangle = static_cast<QSGGeometryNode *>(triangle->nextSibling());
}
}
}
}
void FlatMeshNode::setCenterColor(QColor c)
{
if (c == m_centerColor)
return;
m_centerColor = c;
updateColors();
}
void FlatMeshNode::setOuterColor(QColor c)
{
if (c == m_outerColor)
return;
m_outerColor = c;
updateColors();
}
/* When the size changes, regenerate a grid of points that serves as a base for further operations */
void FlatMeshNode::generateGrid()
{
m_unitWidth = rect().width()/(NUM_POINTS_X-2);
m_unitHeight = rect().height()/(NUM_POINTS_Y-2);
for(int y = 0; y < NUM_POINTS_Y; y++) {
for(int x = 0; x < NUM_POINTS_X; x++) {
Point *point = &m_points[y*NUM_POINTS_Y+x];
point->centerX = m_unitWidth*x;
point->centerY = m_unitHeight*y;
if(x != 0 && x != (NUM_POINTS_X-1)) {
point->animOriginX = point->centerX + rand()%m_unitWidth - m_unitWidth/2;
point->animEndX = point->centerX + rand()%m_unitWidth - m_unitWidth/2;
}
else
point->animEndX = point->animOriginX = point->centerX;
if(y != 0 && y != (NUM_POINTS_Y-1)) {
point->animOriginY = point->centerY + rand()%m_unitHeight - m_unitHeight/2;
point->animEndY = point->centerY + rand()%m_unitHeight - m_unitHeight/2;
}
else
point->animEndY = point->animOriginY = point->centerY;
}
}
}
void FlatMeshNode::setAnimated(bool animated)
{
m_animated = animated;
}
void FlatMeshNode::maybeAnimate()
{
static QElapsedTimer t;
bool firstFrame = false;
if(!t.isValid()) {
t.start();
firstFrame = true;
}
if (firstFrame || (m_animated && t.restart() >= 100)) {
m_animationState += 0.03;
/* Interpolate all points positions according to the animationState */
for(int i = 0; i < NUM_POINTS_X*NUM_POINTS_Y; i++) {
Point *p = &m_points[i];
p->currentPos.x = p->animOriginX + (p->animEndX-p->animOriginX)*m_animationState;
p->currentPos.y = p->animOriginY + (p->animEndY-p->animOriginY)*m_animationState;
}
/* Update all triangles' geometries according to the new points position */
qreal lastCenterX = m_unitWidth*(NUM_POINTS_X-1);
qreal lastcenterY = m_unitHeight*(NUM_POINTS_Y-1);
QSGGeometryNode *triangle = static_cast<QSGGeometryNode *>(firstChild());
for(int i = 0; i < NUM_POINTS_X*NUM_POINTS_Y; i++) {
if(m_points[i].centerX != lastCenterX && m_points[i].centerY != lastcenterY) {
int random = rand()%2;
for(int n = 0; n < 2; n++) {
QSGGeometry::Point2D *v = triangle->geometry()->vertexDataAsPoint2D();
if(random) {
if(n) {
v[0] = m_points[i].currentPos;
v[1] = m_points[i+NUM_POINTS_X].currentPos;
v[2] = m_points[i+NUM_POINTS_X+1].currentPos;
} else {
v[0] = m_points[i].currentPos;
v[1] = m_points[i+1].currentPos;
v[2] = m_points[i+NUM_POINTS_X+1].currentPos;
}
} else {
if(n) {
v[0] = m_points[i].currentPos;
v[1] = m_points[i+NUM_POINTS_X].currentPos;
v[2] = m_points[i+1].currentPos;
} else {
v[0] = m_points[i+NUM_POINTS_X].currentPos;
v[1] = m_points[i+1].currentPos;
v[2] = m_points[i+NUM_POINTS_X+1].currentPos;
}
}
triangle->markDirty(QSGNode::DirtyGeometry);
triangle = static_cast<QSGGeometryNode *>(triangle->nextSibling());
}
}
}
/* Regenerate a set of animation end points when the animation is finished */
if(m_animationState >= 1.0) {
m_animationState = 0.0;
for(int y = 0; y < NUM_POINTS_Y; y++) {
for(int x = 0; x < NUM_POINTS_X; x++) {
Point *point = &m_points[y*NUM_POINTS_Y+x];
if(x != 0 && x != (NUM_POINTS_X-1)) {
point->animOriginX = point->animEndX;
point->animEndX = point->centerX + rand()%m_unitWidth - m_unitWidth/2;
}
if(y != 0 && y != (NUM_POINTS_Y-1)) {
point->animOriginY = point->animEndY;
point->animEndY = point->centerY + rand()%m_unitHeight - m_unitHeight/2;
}
}
}
}
}
}
<|endoftext|> |
<commit_before>/**
Copyright (c) 2017, Philip Deegan.
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 Philip Deegan 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 "maiken.hpp"
#ifdef _MKN_WITH_MKN_RAM_
#include "maiken/github.hpp"
bool maiken::Application::get_binaries() {
size_t suxcess = 0;
kul::Dir outD(inst ? inst.real() : buildDir());
const auto files = kul::String::SPLIT(this->binary(), " ");
for (const std::string &file : files) {
std::string fn = file.substr(file.rfind("/") + 1);
kul::https::Get(file)
.withHeaders({{"User-Agent", "Mozilla not a virus"},
{"Accept", "application/octet-stream"},
{"Content-Disposition", "attachment; filename=" + fn}})
.withResponse([&](const kul::http::Response &r) {
if (r.status() == 200) {
kul::File dl(fn);
if (dl.is()) {
suxcess++;
dl.mv(outD);
}
}
})
.send();
}
return suxcess == files.size();
}
#endif
namespace maiken {
class ObjectMerger {
public:
static void into(const Application &root) {
kul::Dir robj(root.buildDir().join("obj"));
for (auto a : root.dependencies()) {
kul::Dir obj(a->buildDir().join("obj"));
if (obj)
for (auto f : obj.files()) f.cp(robj);
}
}
};
} // namespace maiken
void maiken::Application::process() KTHROW(kul::Exception) {
const kul::hash::set::String &cmds(CommandStateMachine::INSTANCE().commands());
const auto gEnvVars = maiken::AppVars::INSTANCE().envVars();
for(auto const& ev : gEnvVars) KLOG(INF) << ev.first << " : " << ev.second;
kul::os::PushDir pushd(this->project().dir());
auto loadModules = [&](Application &app) {
#ifndef _MKN_DISABLE_MODULES_
for (auto mod = app.modDeps.begin(); mod != app.modDeps.end(); ++mod) {
app.mods.push_back(ModuleLoader::LOAD(**mod));
}
for (auto &modLoader : app.mods) modLoader->module()->init(app, app.modInit(modLoader->app()));
#endif //_MKN_DISABLE_MODULES_
};
auto proc = [&](Application &app, bool work) {
kul::env::CWD(app.project().dir());
if (work) {
if (!app.buildDir()) app.buildDir().mk();
if (BuildRecorder::INSTANCE().has(app.buildDir().real())) return;
BuildRecorder::INSTANCE().add(app.buildDir().real());
}
kul::Dir mkn(app.buildDir().join(".mkn"));
std::vector<std::pair<std::string, std::string>> oldEvs;
for (const auto &ev : app.envVars()) {
const std::string v = kul::env::GET(ev.name());
oldEvs.push_back(std::pair<std::string, std::string>(ev.name(), v));
kul::env::SET(ev.name(), ev.toString().c_str());
maiken::AppVars::INSTANCE().envVar(ev.name(), ev.toString());
}
if (cmds.count(STR_CLEAN) && app.buildDir().is()) {
app.buildDir().rm();
mkn.rm();
}
if (cmds.count(STR_MERGE) && app.ro) ObjectMerger::into(app);
#ifdef _MKN_WITH_MKN_RAM_
if (work && !app.bin.empty() && app.get_binaries()) work = false; // doesn't work yet
#endif
app.loadTimeStamps();
kul::hash::set::String objects;
if (cmds.count(STR_BUILD) || cmds.count(STR_COMPILE)) {
for (auto &modLoader : app.mods)
modLoader->module()->compile(app, app.modCompile(modLoader->app()));
if (work) app.compile(objects);
}
if (cmds.count(STR_BUILD) || cmds.count(STR_LINK)) {
if (work)
for (auto &modLoader : app.mods)
modLoader->module()->link(app, app.modLink(modLoader->app()));
if ((cmds.count(STR_MERGE) && app.ro) || !cmds.count(STR_MERGE)) {
app.findObjects(objects);
app.link(objects);
}
}
for (const auto &oldEv : oldEvs) kul::env::SET(oldEv.first.c_str(), oldEv.second.c_str());
for (const auto e : gEnvVars) maiken::AppVars::INSTANCE().envVar(e.first, e.second);
};
auto _mods = ModuleMinimiser::modules(*this);
for (auto &mod : ModuleMinimiser::modules(*this)) {
bool build = mod.second->is_build_required();
bool is_build_stale = mod.second->is_build_stale();
if (!build && (is_build_stale && !maiken::AppVars::INSTANCE().quiet())) {
std::stringstream ss;
ss << "The project @ " << mod.second->project().dir() << " appears to be stale" << std::endl;
ss << "\tWould you like to build it (Y/n) - this message can be removed "
"with -q"
<< std::endl;
build = kul::String::BOOL(kul::cli::receive(ss.str()));
}
if (build) {
CommandStateMachine::INSTANCE().main(0);
for (auto &m : _mods) m.second->process();
CommandStateMachine::INSTANCE().main(1);
}
}
for (auto app = this->deps.rbegin(); app != this->deps.rend(); ++app) loadModules(**app);
loadModules(*this);
for (auto app = this->deps.rbegin(); app != this->deps.rend(); ++app) {
if ((*app)->ig) continue;
if ((*app)->lang.empty()) (*app)->resolveLang();
(*app)->main.clear();
proc(**app, !(*app)->srcs.empty());
}
if (!this->ig) proc(*this, (!this->srcs.empty() || !this->main.empty()));
if (cmds.count(STR_TEST)) {
for (auto &modLoader : mods) modLoader->module()->test(*this, this->modTest(modLoader->app()));
test();
}
if (cmds.count(STR_PACK)) {
pack();
for (auto &modLoader : mods) modLoader->module()->pack(*this, this->modPack(modLoader->app()));
}
if (CommandStateMachine::INSTANCE().main() && (cmds.count(STR_RUN) || cmds.count(STR_DBG)))
run(cmds.count(STR_DBG));
CommandStateMachine::INSTANCE().reset();
AppVars::INSTANCE().show(0);
}
<commit_msg>rm var print<commit_after>/**
Copyright (c) 2017, Philip Deegan.
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 Philip Deegan 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 "maiken.hpp"
#ifdef _MKN_WITH_MKN_RAM_
#include "maiken/github.hpp"
bool maiken::Application::get_binaries() {
size_t suxcess = 0;
kul::Dir outD(inst ? inst.real() : buildDir());
const auto files = kul::String::SPLIT(this->binary(), " ");
for (const std::string &file : files) {
std::string fn = file.substr(file.rfind("/") + 1);
kul::https::Get(file)
.withHeaders({{"User-Agent", "Mozilla not a virus"},
{"Accept", "application/octet-stream"},
{"Content-Disposition", "attachment; filename=" + fn}})
.withResponse([&](const kul::http::Response &r) {
if (r.status() == 200) {
kul::File dl(fn);
if (dl.is()) {
suxcess++;
dl.mv(outD);
}
}
})
.send();
}
return suxcess == files.size();
}
#endif
namespace maiken {
class ObjectMerger {
public:
static void into(const Application &root) {
kul::Dir robj(root.buildDir().join("obj"));
for (auto a : root.dependencies()) {
kul::Dir obj(a->buildDir().join("obj"));
if (obj)
for (auto f : obj.files()) f.cp(robj);
}
}
};
} // namespace maiken
void maiken::Application::process() KTHROW(kul::Exception) {
auto const& cmds = CommandStateMachine::INSTANCE().commands();
auto const& gEnvVars = maiken::AppVars::INSTANCE().envVars();
kul::os::PushDir pushd(this->project().dir());
auto loadModules = [&](Application &app) {
#ifndef _MKN_DISABLE_MODULES_
for (auto mod = app.modDeps.begin(); mod != app.modDeps.end(); ++mod) {
app.mods.push_back(ModuleLoader::LOAD(**mod));
}
for (auto &modLoader : app.mods) modLoader->module()->init(app, app.modInit(modLoader->app()));
#endif //_MKN_DISABLE_MODULES_
};
auto proc = [&](Application &app, bool work) {
kul::env::CWD(app.project().dir());
if (work) {
if (!app.buildDir()) app.buildDir().mk();
if (BuildRecorder::INSTANCE().has(app.buildDir().real())) return;
BuildRecorder::INSTANCE().add(app.buildDir().real());
}
kul::Dir mkn(app.buildDir().join(".mkn"));
std::vector<std::pair<std::string, std::string>> oldEvs;
for (const auto &ev : app.envVars()) {
const std::string v = kul::env::GET(ev.name());
oldEvs.push_back(std::pair<std::string, std::string>(ev.name(), v));
kul::env::SET(ev.name(), ev.toString().c_str());
maiken::AppVars::INSTANCE().envVar(ev.name(), ev.toString());
}
if (cmds.count(STR_CLEAN) && app.buildDir().is()) {
app.buildDir().rm();
mkn.rm();
}
if (cmds.count(STR_MERGE) && app.ro) ObjectMerger::into(app);
#ifdef _MKN_WITH_MKN_RAM_
if (work && !app.bin.empty() && app.get_binaries()) work = false; // doesn't work yet
#endif
app.loadTimeStamps();
kul::hash::set::String objects;
if (cmds.count(STR_BUILD) || cmds.count(STR_COMPILE)) {
for (auto &modLoader : app.mods)
modLoader->module()->compile(app, app.modCompile(modLoader->app()));
if (work) app.compile(objects);
}
if (cmds.count(STR_BUILD) || cmds.count(STR_LINK)) {
if (work)
for (auto &modLoader : app.mods)
modLoader->module()->link(app, app.modLink(modLoader->app()));
if ((cmds.count(STR_MERGE) && app.ro) || !cmds.count(STR_MERGE)) {
app.findObjects(objects);
app.link(objects);
}
}
for (const auto &oldEv : oldEvs) kul::env::SET(oldEv.first.c_str(), oldEv.second.c_str());
for (const auto e : gEnvVars) maiken::AppVars::INSTANCE().envVar(e.first, e.second);
};
auto _mods = ModuleMinimiser::modules(*this);
for (auto &mod : ModuleMinimiser::modules(*this)) {
bool build = mod.second->is_build_required();
bool is_build_stale = mod.second->is_build_stale();
if (!build && (is_build_stale && !maiken::AppVars::INSTANCE().quiet())) {
std::stringstream ss;
ss << "The project @ " << mod.second->project().dir() << " appears to be stale" << std::endl;
ss << "\tWould you like to build it (Y/n) - this message can be removed "
"with -q"
<< std::endl;
build = kul::String::BOOL(kul::cli::receive(ss.str()));
}
if (build) {
CommandStateMachine::INSTANCE().main(0);
for (auto &m : _mods) m.second->process();
CommandStateMachine::INSTANCE().main(1);
}
}
for (auto app = this->deps.rbegin(); app != this->deps.rend(); ++app) loadModules(**app);
loadModules(*this);
for (auto app = this->deps.rbegin(); app != this->deps.rend(); ++app) {
if ((*app)->ig) continue;
if ((*app)->lang.empty()) (*app)->resolveLang();
(*app)->main.clear();
proc(**app, !(*app)->srcs.empty());
}
if (!this->ig) proc(*this, (!this->srcs.empty() || !this->main.empty()));
if (cmds.count(STR_TEST)) {
for (auto &modLoader : mods) modLoader->module()->test(*this, this->modTest(modLoader->app()));
test();
}
if (cmds.count(STR_PACK)) {
pack();
for (auto &modLoader : mods) modLoader->module()->pack(*this, this->modPack(modLoader->app()));
}
if (CommandStateMachine::INSTANCE().main() && (cmds.count(STR_RUN) || cmds.count(STR_DBG)))
run(cmds.count(STR_DBG));
CommandStateMachine::INSTANCE().reset();
AppVars::INSTANCE().show(0);
}
<|endoftext|> |
<commit_before>#include <cerrno>
#include <cstring>
#include <ctime>
#include <iostream>
#include <pqxx/connection>
#include <pqxx/transaction>
#include <pqxx/transactor>
#include <pqxx/trigger>
#include <pqxx/result>
using namespace PGSTD;
using namespace pqxx;
// Example program for libpqxx. Send notification to self.
//
// Usage: test004 [connect-string]
//
// Where connect-string is a set of connection options in Postgresql's
// PQconnectdb() format, eg. "dbname=template1" to select from a database
// called template1, or "host=foo.bar.net user=smith" to connect to a
// backend running on host foo.bar.net, logging in as user smith.
namespace
{
int Backend_PID = 0;
// Sample implementation of trigger handler
class TestTrig : public trigger
{
bool m_Done;
public:
explicit TestTrig(connection_base &C) : trigger(C, "trig"), m_Done(false) {}
virtual void operator()(int be_pid)
{
m_Done = true;
if (be_pid != Backend_PID)
throw logic_error("Expected notification from backend process " +
to_string(Backend_PID) +
", but got one from " +
to_string(be_pid));
cout << "Received notification: " << name() << " pid=" << be_pid << endl;
}
bool Done() const { return m_Done; }
};
// A transactor to trigger our trigger handler
class Notify : public transactor<>
{
string m_Trigger;
public:
explicit Notify(string TrigName) :
transactor<>("Notifier"), m_Trigger(TrigName) { }
void operator()(argument_type &T)
{
T.exec("NOTIFY \"" + m_Trigger + "\"");
Backend_PID = T.conn().backendpid();
}
void OnAbort(const char Reason[]) throw ()
{
try
{
cerr << "Notify failed!" << endl;
if (Reason) cerr << "Reason: " << Reason << endl;
}
catch (const exception &)
{
}
}
};
} // namespace
int main(int, char *argv[])
{
try
{
connection C(argv[1]);
cout << "Adding trigger..." << endl;
TestTrig Trig(C);
cout << "Sending notification..." << endl;
C.perform(Notify(Trig.name()));
int notifs = 0;
for (int i=0; (i < 20) && !Trig.Done(); ++i)
{
if (notifs)
throw logic_error("Got " + to_string(notifs) +
" unexpected notification(s)!");
pqxx::internal::sleep_seconds(1);
notifs = C.get_notifs();
cout << ".";
}
cout << endl;
if (!Trig.Done())
{
cout << "No notification received!" << endl;
return 1;
}
if (notifs != 1)
throw logic_error("Expected 1 notification, got " + to_string(notifs));
}
catch (const sql_error &e)
{
// If we're interested in the text of a failed query, we can write separate
// exception handling code for this type of exception
cerr << "SQL error: " << e.what() << endl
<< "Query was: '" << e.query() << "'" << endl;
return 1;
}
catch (const exception &e)
{
// All exceptions thrown by libpqxx are derived from std::exception
cerr << "Exception: " << e.what() << endl;
return 2;
}
catch (...)
{
// This is really unexpected (see above)
cerr << "Unhandled exception" << endl;
return 100;
}
return 0;
}
<commit_msg>Added comment<commit_after>#include <cerrno>
#include <cstring>
#include <ctime>
#include <iostream>
#include <pqxx/connection>
#include <pqxx/transaction>
#include <pqxx/transactor>
#include <pqxx/trigger>
#include <pqxx/result>
using namespace PGSTD;
using namespace pqxx;
// Example program for libpqxx. Send notification to self.
//
// Usage: test004 [connect-string]
//
// Where connect-string is a set of connection options in Postgresql's
// PQconnectdb() format, eg. "dbname=template1" to select from a database
// called template1, or "host=foo.bar.net user=smith" to connect to a
// backend running on host foo.bar.net, logging in as user smith.
namespace
{
int Backend_PID = 0;
// Sample implementation of trigger handler
class TestTrig : public trigger
{
bool m_Done;
public:
explicit TestTrig(connection_base &C) : trigger(C, "trig"), m_Done(false) {}
virtual void operator()(int be_pid)
{
m_Done = true;
if (be_pid != Backend_PID)
throw logic_error("Expected notification from backend process " +
to_string(Backend_PID) +
", but got one from " +
to_string(be_pid));
cout << "Received notification: " << name() << " pid=" << be_pid << endl;
}
bool Done() const { return m_Done; }
};
// A transactor to trigger our trigger handler
class Notify : public transactor<>
{
string m_Trigger;
public:
explicit Notify(string TrigName) :
transactor<>("Notifier"), m_Trigger(TrigName) { }
void operator()(argument_type &T)
{
T.exec("NOTIFY \"" + m_Trigger + "\"");
Backend_PID = T.conn().backendpid();
}
void OnAbort(const char Reason[]) throw ()
{
try
{
cerr << "Notify failed!" << endl;
if (Reason) cerr << "Reason: " << Reason << endl;
}
catch (const exception &)
{
}
}
};
} // namespace
int main(int, char *argv[])
{
try
{
connection C(argv[1]);
cout << "Adding trigger..." << endl;
TestTrig Trig(C);
cout << "Sending notification..." << endl;
C.perform(Notify(Trig.name()));
int notifs = 0;
for (int i=0; (i < 20) && !Trig.Done(); ++i)
{
if (notifs)
throw logic_error("Got " + to_string(notifs) +
" unexpected notification(s)!");
// Sleep one second using a libpqxx-internal function. Kids, don't try
// this at home! The pqxx::internal namespace is not for third-party use
// and may change radically at any time.
pqxx::internal::sleep_seconds(1);
notifs = C.get_notifs();
cout << ".";
}
cout << endl;
if (!Trig.Done())
{
cout << "No notification received!" << endl;
return 1;
}
if (notifs != 1)
throw logic_error("Expected 1 notification, got " + to_string(notifs));
}
catch (const sql_error &e)
{
// If we're interested in the text of a failed query, we can write separate
// exception handling code for this type of exception
cerr << "SQL error: " << e.what() << endl
<< "Query was: '" << e.query() << "'" << endl;
return 1;
}
catch (const exception &e)
{
// All exceptions thrown by libpqxx are derived from std::exception
cerr << "Exception: " << e.what() << endl;
return 2;
}
catch (...)
{
// This is really unexpected (see above)
cerr << "Unhandled exception" << endl;
return 100;
}
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>Always check return of stat #6345<commit_after><|endoftext|> |
<commit_before>/*
* Copyright 2012 Adam Murdoch
*
* 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.
*/
/*
* POSIX platform functions.
*/
#ifndef _WIN32
#include "native.h"
#include "generic.h"
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/utsname.h>
JNIEXPORT void JNICALL
Java_net_rubygrapefruit_platform_internal_jni_NativeLibraryFunctions_getSystemInfo(JNIEnv *env, jclass target, jobject info, jobject result) {
jclass infoClass = env->GetObjectClass(info);
struct utsname machine_info;
if (uname(&machine_info) != 0) {
mark_failed_with_errno(env, "could not query machine details", result);
return;
}
jfieldID osNameField = env->GetFieldID(infoClass, "osName", "Ljava/lang/String;");
env->SetObjectField(info, osNameField, char_to_java(env, machine_info.sysname, result));
jfieldID osVersionField = env->GetFieldID(infoClass, "osVersion", "Ljava/lang/String;");
env->SetObjectField(info, osVersionField, char_to_java(env, machine_info.release, result));
jfieldID machineArchitectureField = env->GetFieldID(infoClass, "machineArchitecture", "Ljava/lang/String;");
env->SetObjectField(info, machineArchitectureField, char_to_java(env, machine_info.machine, result));
}
JNIEXPORT void JNICALL
Java_net_rubygrapefruit_platform_internal_jni_PosixTypeFunctions_getNativeTypeInfo(JNIEnv *env, jclass target, jobject info) {
jclass infoClass = env->GetObjectClass(info);
env->SetIntField(info, env->GetFieldID(infoClass, "int_bytes", "I"), sizeof(int));
env->SetIntField(info, env->GetFieldID(infoClass, "u_long_bytes", "I"), sizeof(u_long));
env->SetIntField(info, env->GetFieldID(infoClass, "size_t_bytes", "I"), sizeof(size_t));
env->SetIntField(info, env->GetFieldID(infoClass, "uid_t_bytes", "I"), sizeof(uid_t));
env->SetIntField(info, env->GetFieldID(infoClass, "gid_t_bytes", "I"), sizeof(gid_t));
env->SetIntField(info, env->GetFieldID(infoClass, "off_t_bytes", "I"), sizeof(off_t));
}
/*
* File functions
*/
JNIEXPORT void JNICALL
Java_net_rubygrapefruit_platform_internal_jni_PosixFileFunctions_chmod(JNIEnv *env, jclass target, jstring path, jint mode, jobject result) {
char* pathStr = java_to_char(env, path, result);
if (pathStr == NULL) {
return;
}
int retval = chmod(pathStr, mode);
free(pathStr);
if (retval != 0) {
mark_failed_with_errno(env, "could not chmod file", result);
}
}
jlong timestamp(struct timespec t) {
return t.tv_sec * 1000 + t.tv_nsec / 1000;
}
JNIEXPORT void JNICALL
Java_net_rubygrapefruit_platform_internal_jni_PosixFileFunctions_stat(JNIEnv *env, jclass target, jstring path, jobject dest, jobject result) {
struct stat fileInfo;
char* pathStr = java_to_char(env, path, result);
if (pathStr == NULL) {
return;
}
int retval = lstat(pathStr, &fileInfo);
free(pathStr);
if (retval != 0 && errno != ENOENT) {
mark_failed_with_errno(env, "could not stat file", result);
return;
}
jclass destClass = env->GetObjectClass(dest);
jfieldID modeField = env->GetFieldID(destClass, "mode", "I");
jfieldID typeField = env->GetFieldID(destClass, "type", "I");
jfieldID sizeField = env->GetFieldID(destClass, "size", "J");
jfieldID uidField = env->GetFieldID(destClass, "uid", "I");
jfieldID gidField = env->GetFieldID(destClass, "gid", "I");
jfieldID blockSizeField = env->GetFieldID(destClass, "blockSize", "J");
jfieldID accessTimeField = env->GetFieldID(destClass, "accessTime", "J");
jfieldID modificationTimeField = env->GetFieldID(destClass, "modificationTime", "J");
jfieldID statusChangeTime = env->GetFieldID(destClass, "statusChangeTime", "J");
if (retval != 0) {
env->SetIntField(dest, typeField, FILE_TYPE_MISSING);
} else {
env->SetIntField(dest, modeField, 0777 & fileInfo.st_mode);
int type;
switch (fileInfo.st_mode & S_IFMT) {
case S_IFREG:
type = FILE_TYPE_FILE;
break;
case S_IFDIR:
type = FILE_TYPE_DIRECTORY;
break;
case S_IFLNK:
type = FILE_TYPE_SYMLINK;
break;
default:
type= FILE_TYPE_OTHER;
}
env->SetIntField(dest, typeField, type);
env->SetIntField(dest, uidField, fileInfo.st_uid);
env->SetIntField(dest, gidField, fileInfo.st_gid);
if (type == FILE_TYPE_FILE) {
env->SetLongField(dest, sizeField, fileInfo.st_size);
}
env->SetLongField(dest, blockSizeField, fileInfo.st_blksize);
#ifdef __linux__
env->SetLongField(dest, accessTimeField, fileInfo.st_atime * 1000);
env->SetLongField(dest, modificationTimeField, fileInfo.st_mtime * 1000);
env->SetLongField(dest, statusChangeTime, fileInfo.st_ctime * 1000);
#else
env->SetLongField(dest, accessTimeField, timestamp(fileInfo.st_atimespec));
env->SetLongField(dest, modificationTimeField, timestamp(fileInfo.st_mtimespec));
env->SetLongField(dest, statusChangeTime, timestamp(fileInfo.st_ctimespec));
#endif
}
}
JNIEXPORT void JNICALL
Java_net_rubygrapefruit_platform_internal_jni_PosixFileFunctions_symlink(JNIEnv *env, jclass target, jstring path, jstring contents, jobject result) {
char* pathStr = java_to_char(env, path, result);
if (pathStr == NULL) {
return;
}
char* contentStr = java_to_char(env, contents, result);
if (contentStr == NULL) {
free(pathStr);
return;
}
int retval = symlink(contentStr, pathStr);
free(contentStr);
free(pathStr);
if (retval != 0) {
mark_failed_with_errno(env, "could not symlink", result);
}
}
JNIEXPORT jstring JNICALL
Java_net_rubygrapefruit_platform_internal_jni_PosixFileFunctions_readlink(JNIEnv *env, jclass target, jstring path, jobject result) {
struct stat link_info;
char* pathStr = java_to_char(env, path, result);
if (pathStr == NULL) {
return NULL;
}
int retval = lstat(pathStr, &link_info);
if (retval != 0) {
free(pathStr);
mark_failed_with_errno(env, "could not lstat file", result);
return NULL;
}
char* contents = (char*)malloc(link_info.st_size + 1);
if (contents == NULL) {
free(pathStr);
mark_failed_with_message(env, "could not create array", result);
return NULL;
}
retval = readlink(pathStr, contents, link_info.st_size);
free(pathStr);
if (retval < 0) {
free(contents);
mark_failed_with_errno(env, "could not readlink", result);
return NULL;
}
contents[link_info.st_size] = 0;
jstring contents_str = char_to_java(env, contents, result);
free(contents);
return contents_str;
}
/*
* Process functions
*/
JNIEXPORT jint JNICALL
Java_net_rubygrapefruit_platform_internal_jni_PosixProcessFunctions_getPid(JNIEnv *env, jclass target) {
return getpid();
}
JNIEXPORT jstring JNICALL
Java_net_rubygrapefruit_platform_internal_jni_PosixProcessFunctions_getWorkingDirectory(JNIEnv *env, jclass target, jobject result) {
char* path = getcwd(NULL, 0);
if (path == NULL) {
mark_failed_with_errno(env, "could not getcwd()", result);
return NULL;
}
jstring dir = char_to_java(env, path, result);
free(path);
return dir;
}
JNIEXPORT void JNICALL
Java_net_rubygrapefruit_platform_internal_jni_PosixProcessFunctions_setWorkingDirectory(JNIEnv *env, jclass target, jstring dir, jobject result) {
char* path = java_to_char(env, dir, result);
if (path == NULL) {
return;
}
if (chdir(path) != 0) {
mark_failed_with_errno(env, "could not setcwd()", result);
}
free(path);
}
JNIEXPORT jstring JNICALL
Java_net_rubygrapefruit_platform_internal_jni_PosixProcessFunctions_getEnvironmentVariable(JNIEnv *env, jclass target, jstring var, jobject result) {
char* varStr = java_to_char(env, var, result);
char* valueStr = getenv(varStr);
free(varStr);
if (valueStr == NULL) {
return NULL;
}
return char_to_java(env, valueStr, result);
}
JNIEXPORT void JNICALL
Java_net_rubygrapefruit_platform_internal_jni_PosixProcessFunctions_setEnvironmentVariable(JNIEnv *env, jclass target, jstring var, jstring value, jobject result) {
char* varStr = java_to_char(env, var, result);
if (value == NULL) {
if (setenv(varStr, "", 1) != 0) {
mark_failed_with_errno(env, "could not putenv()", result);
}
} else {
char* valueStr = java_to_char(env, value, result);
if (setenv(varStr, valueStr, 1) != 0) {
mark_failed_with_errno(env, "could not putenv()", result);
}
free(valueStr);
}
free(varStr);
}
/*
* Terminal functions
*/
JNIEXPORT jboolean JNICALL
Java_net_rubygrapefruit_platform_internal_jni_PosixTerminalFunctions_isatty(JNIEnv *env, jclass target, jint output) {
struct stat fileInfo;
int result;
switch (output) {
case 0:
case 1:
return isatty(output+1) ? JNI_TRUE : JNI_FALSE;
default:
return JNI_FALSE;
}
}
JNIEXPORT void JNICALL
Java_net_rubygrapefruit_platform_internal_jni_PosixTerminalFunctions_getTerminalSize(JNIEnv *env, jclass target, jint output, jobject dimension, jobject result) {
struct winsize screen_size;
int retval = ioctl(output+1, TIOCGWINSZ, &screen_size);
if (retval != 0) {
mark_failed_with_errno(env, "could not fetch terminal size", result);
return;
}
jclass dimensionClass = env->GetObjectClass(dimension);
jfieldID widthField = env->GetFieldID(dimensionClass, "cols", "I");
env->SetIntField(dimension, widthField, screen_size.ws_col);
jfieldID heightField = env->GetFieldID(dimensionClass, "rows", "I");
env->SetIntField(dimension, heightField, screen_size.ws_row);
}
#endif
<commit_msg>Fixed times reported for `FileInfo` on 32bit linux.<commit_after>/*
* Copyright 2012 Adam Murdoch
*
* 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.
*/
/*
* POSIX platform functions.
*/
#ifndef _WIN32
#include "native.h"
#include "generic.h"
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/utsname.h>
JNIEXPORT void JNICALL
Java_net_rubygrapefruit_platform_internal_jni_NativeLibraryFunctions_getSystemInfo(JNIEnv *env, jclass target, jobject info, jobject result) {
jclass infoClass = env->GetObjectClass(info);
struct utsname machine_info;
if (uname(&machine_info) != 0) {
mark_failed_with_errno(env, "could not query machine details", result);
return;
}
jfieldID osNameField = env->GetFieldID(infoClass, "osName", "Ljava/lang/String;");
env->SetObjectField(info, osNameField, char_to_java(env, machine_info.sysname, result));
jfieldID osVersionField = env->GetFieldID(infoClass, "osVersion", "Ljava/lang/String;");
env->SetObjectField(info, osVersionField, char_to_java(env, machine_info.release, result));
jfieldID machineArchitectureField = env->GetFieldID(infoClass, "machineArchitecture", "Ljava/lang/String;");
env->SetObjectField(info, machineArchitectureField, char_to_java(env, machine_info.machine, result));
}
JNIEXPORT void JNICALL
Java_net_rubygrapefruit_platform_internal_jni_PosixTypeFunctions_getNativeTypeInfo(JNIEnv *env, jclass target, jobject info) {
jclass infoClass = env->GetObjectClass(info);
env->SetIntField(info, env->GetFieldID(infoClass, "int_bytes", "I"), sizeof(int));
env->SetIntField(info, env->GetFieldID(infoClass, "u_long_bytes", "I"), sizeof(u_long));
env->SetIntField(info, env->GetFieldID(infoClass, "size_t_bytes", "I"), sizeof(size_t));
env->SetIntField(info, env->GetFieldID(infoClass, "uid_t_bytes", "I"), sizeof(uid_t));
env->SetIntField(info, env->GetFieldID(infoClass, "gid_t_bytes", "I"), sizeof(gid_t));
env->SetIntField(info, env->GetFieldID(infoClass, "off_t_bytes", "I"), sizeof(off_t));
}
/*
* File functions
*/
JNIEXPORT void JNICALL
Java_net_rubygrapefruit_platform_internal_jni_PosixFileFunctions_chmod(JNIEnv *env, jclass target, jstring path, jint mode, jobject result) {
char* pathStr = java_to_char(env, path, result);
if (pathStr == NULL) {
return;
}
int retval = chmod(pathStr, mode);
free(pathStr);
if (retval != 0) {
mark_failed_with_errno(env, "could not chmod file", result);
}
}
jlong timestamp(struct timespec t) {
return (jlong)(t.tv_sec) * 1000 + (jlong)(t.tv_nsec) / 1000;
}
JNIEXPORT void JNICALL
Java_net_rubygrapefruit_platform_internal_jni_PosixFileFunctions_stat(JNIEnv *env, jclass target, jstring path, jobject dest, jobject result) {
struct stat fileInfo;
char* pathStr = java_to_char(env, path, result);
if (pathStr == NULL) {
return;
}
int retval = lstat(pathStr, &fileInfo);
free(pathStr);
if (retval != 0 && errno != ENOENT) {
mark_failed_with_errno(env, "could not stat file", result);
return;
}
jclass destClass = env->GetObjectClass(dest);
jfieldID modeField = env->GetFieldID(destClass, "mode", "I");
jfieldID typeField = env->GetFieldID(destClass, "type", "I");
jfieldID sizeField = env->GetFieldID(destClass, "size", "J");
jfieldID uidField = env->GetFieldID(destClass, "uid", "I");
jfieldID gidField = env->GetFieldID(destClass, "gid", "I");
jfieldID blockSizeField = env->GetFieldID(destClass, "blockSize", "J");
jfieldID accessTimeField = env->GetFieldID(destClass, "accessTime", "J");
jfieldID modificationTimeField = env->GetFieldID(destClass, "modificationTime", "J");
jfieldID statusChangeTime = env->GetFieldID(destClass, "statusChangeTime", "J");
if (retval != 0) {
env->SetIntField(dest, typeField, FILE_TYPE_MISSING);
} else {
env->SetIntField(dest, modeField, 0777 & fileInfo.st_mode);
int type;
switch (fileInfo.st_mode & S_IFMT) {
case S_IFREG:
type = FILE_TYPE_FILE;
break;
case S_IFDIR:
type = FILE_TYPE_DIRECTORY;
break;
case S_IFLNK:
type = FILE_TYPE_SYMLINK;
break;
default:
type= FILE_TYPE_OTHER;
}
env->SetIntField(dest, typeField, type);
env->SetIntField(dest, uidField, fileInfo.st_uid);
env->SetIntField(dest, gidField, fileInfo.st_gid);
if (type == FILE_TYPE_FILE) {
env->SetLongField(dest, sizeField, fileInfo.st_size);
}
env->SetLongField(dest, blockSizeField, fileInfo.st_blksize);
#ifdef __linux__
env->SetLongField(dest, accessTimeField, timestamp(fileInfo.st_atim));
env->SetLongField(dest, modificationTimeField, timestamp(fileInfo.st_mtim));
env->SetLongField(dest, statusChangeTime, timestamp(fileInfo.st_ctim));
#else
env->SetLongField(dest, accessTimeField, timestamp(fileInfo.st_atimespec));
env->SetLongField(dest, modificationTimeField, timestamp(fileInfo.st_mtimespec));
env->SetLongField(dest, statusChangeTime, timestamp(fileInfo.st_ctimespec));
#endif
}
}
JNIEXPORT void JNICALL
Java_net_rubygrapefruit_platform_internal_jni_PosixFileFunctions_symlink(JNIEnv *env, jclass target, jstring path, jstring contents, jobject result) {
char* pathStr = java_to_char(env, path, result);
if (pathStr == NULL) {
return;
}
char* contentStr = java_to_char(env, contents, result);
if (contentStr == NULL) {
free(pathStr);
return;
}
int retval = symlink(contentStr, pathStr);
free(contentStr);
free(pathStr);
if (retval != 0) {
mark_failed_with_errno(env, "could not symlink", result);
}
}
JNIEXPORT jstring JNICALL
Java_net_rubygrapefruit_platform_internal_jni_PosixFileFunctions_readlink(JNIEnv *env, jclass target, jstring path, jobject result) {
struct stat link_info;
char* pathStr = java_to_char(env, path, result);
if (pathStr == NULL) {
return NULL;
}
int retval = lstat(pathStr, &link_info);
if (retval != 0) {
free(pathStr);
mark_failed_with_errno(env, "could not lstat file", result);
return NULL;
}
char* contents = (char*)malloc(link_info.st_size + 1);
if (contents == NULL) {
free(pathStr);
mark_failed_with_message(env, "could not create array", result);
return NULL;
}
retval = readlink(pathStr, contents, link_info.st_size);
free(pathStr);
if (retval < 0) {
free(contents);
mark_failed_with_errno(env, "could not readlink", result);
return NULL;
}
contents[link_info.st_size] = 0;
jstring contents_str = char_to_java(env, contents, result);
free(contents);
return contents_str;
}
/*
* Process functions
*/
JNIEXPORT jint JNICALL
Java_net_rubygrapefruit_platform_internal_jni_PosixProcessFunctions_getPid(JNIEnv *env, jclass target) {
return getpid();
}
JNIEXPORT jstring JNICALL
Java_net_rubygrapefruit_platform_internal_jni_PosixProcessFunctions_getWorkingDirectory(JNIEnv *env, jclass target, jobject result) {
char* path = getcwd(NULL, 0);
if (path == NULL) {
mark_failed_with_errno(env, "could not getcwd()", result);
return NULL;
}
jstring dir = char_to_java(env, path, result);
free(path);
return dir;
}
JNIEXPORT void JNICALL
Java_net_rubygrapefruit_platform_internal_jni_PosixProcessFunctions_setWorkingDirectory(JNIEnv *env, jclass target, jstring dir, jobject result) {
char* path = java_to_char(env, dir, result);
if (path == NULL) {
return;
}
if (chdir(path) != 0) {
mark_failed_with_errno(env, "could not setcwd()", result);
}
free(path);
}
JNIEXPORT jstring JNICALL
Java_net_rubygrapefruit_platform_internal_jni_PosixProcessFunctions_getEnvironmentVariable(JNIEnv *env, jclass target, jstring var, jobject result) {
char* varStr = java_to_char(env, var, result);
char* valueStr = getenv(varStr);
free(varStr);
if (valueStr == NULL) {
return NULL;
}
return char_to_java(env, valueStr, result);
}
JNIEXPORT void JNICALL
Java_net_rubygrapefruit_platform_internal_jni_PosixProcessFunctions_setEnvironmentVariable(JNIEnv *env, jclass target, jstring var, jstring value, jobject result) {
char* varStr = java_to_char(env, var, result);
if (value == NULL) {
if (setenv(varStr, "", 1) != 0) {
mark_failed_with_errno(env, "could not putenv()", result);
}
} else {
char* valueStr = java_to_char(env, value, result);
if (setenv(varStr, valueStr, 1) != 0) {
mark_failed_with_errno(env, "could not putenv()", result);
}
free(valueStr);
}
free(varStr);
}
/*
* Terminal functions
*/
JNIEXPORT jboolean JNICALL
Java_net_rubygrapefruit_platform_internal_jni_PosixTerminalFunctions_isatty(JNIEnv *env, jclass target, jint output) {
struct stat fileInfo;
int result;
switch (output) {
case 0:
case 1:
return isatty(output+1) ? JNI_TRUE : JNI_FALSE;
default:
return JNI_FALSE;
}
}
JNIEXPORT void JNICALL
Java_net_rubygrapefruit_platform_internal_jni_PosixTerminalFunctions_getTerminalSize(JNIEnv *env, jclass target, jint output, jobject dimension, jobject result) {
struct winsize screen_size;
int retval = ioctl(output+1, TIOCGWINSZ, &screen_size);
if (retval != 0) {
mark_failed_with_errno(env, "could not fetch terminal size", result);
return;
}
jclass dimensionClass = env->GetObjectClass(dimension);
jfieldID widthField = env->GetFieldID(dimensionClass, "cols", "I");
env->SetIntField(dimension, widthField, screen_size.ws_col);
jfieldID heightField = env->GetFieldID(dimensionClass, "rows", "I");
env->SetIntField(dimension, heightField, screen_size.ws_row);
}
#endif
<|endoftext|> |
<commit_before>//! @file getcpinfo.cpp
//! @author Aaron Ktaz <[email protected]>
//! @brief Implements GetCpInfoW Win32 API
#include <errno.h>
#include <string>
#include <langinfo.h>
#include "getcpinfo.h"
//! @brief GetCPInfoW retrieves the name of the code page associated with
//! the current thread.
//!
//! GetCpInfoW the Unicode variation. See [MSDN documentation].
//!
//! @param[in] codepage
//! @parblock
//! An UINT Identifier for the code page for which to retrieve information.
//! See Code Page Identifiers for details
//! 65001 in the number for UTF8. It is the only valid inpur parameter
//!because Linux and Unix only use UTF8 for codepage
//!
//! @endparblock
//!
//! @param[out] cpinfo
//! @parblock
//! Pointer to a CPINFO structure that receives information about the code page
//!
//! LPCPINFO is a pointer to the structure _cpinfo used to contain the information
//! about a code page
//!
//! _cpinfo is a struct that comprises
//!
//! UINT MaxCharSize;
//! Maximum length, in bytes, of a character in the code page.
//! The length can be 1 for a single-byte character set (SBCS),
//! 2 for a double-byte character set (DBCS), or a value larger
//! than 2 for other character set types. The function cannot
//! use the size to distinguish an SBCS or a DBCS from other
//! character sets because of other factors, for example,
//! the use of ISCII or ISO-2022-xx code pages.
//!
//! BYTE DefaultChar[const_cpinfo::MAX_DEFAULTCHAR];
//! Default character used when translating character
//! strings to the specific code page. This character is used by
//! the WideCharToMultiByte function if an explicit default
//! character is not specified. The default is usually the "?"
//! character for the code page
//!
//! BYTE LeadByte[const_cpinfo::MAX_LEADBYTES];
//! A fixed-length array of lead byte ranges, for which the number
//! of lead byte ranges is variable. If the code page has no lead
//! bytes, every element of the array is set to NULL. If the code
//! page has lead bytes, the array specifies a starting value and
//! an ending value for each range. Ranges are inclusive, and the
//! maximum number of ranges for any code page is five. The array
//! uses two bytes to describe each range, with two null bytes as
//! a terminator after the last range.
//!
//! MAX_DEFAULTCHAR is an int of size 2
//! MAX_LEADBYTES is an int of size 12
//!
//!
//! @exception errno Passes these errors via errno to GetLastError:
//! - ERROR_INVALID_PARAMETER: parameter is not valid
//!
//! @retval TRUE If the function succeeds, the return value is a nonzero
//! value, and cpinfo is population with information about the code page
//!
//! @retval FALSE If the function fails, the return value is zero. To get
//! extended error information, call GetLastError.
//!
//! [MSDN documentation]:https://msdn.microsoft.com/en-us/library/windows/desktop/dd318078%28v=vs.85%29.aspx
//! [_cpinfo]: https://msdn.microsoft.com/en-us/library/windows/desktop/dd317780%28v=vs.85%29.aspx
//! [CodePageIdentifiers] https://msdn.microsoft.com/en-us/library/windows/desktop/dd317756%28v=vs.85%29.aspx
BOOL GetCPInfoW(UINT codepage, CPINFO* cpinfo)
{
errno = FALSE;
// Select locale from environment
setlocale(LC_ALL, "");
// Check that locale is UTF-8
if (nl_langinfo(CODESET) != std::string("UTF-8"))
{
errno = ERROR_BAD_ENVIRONMENT;
return FALSE;
}
// 65001 is the code page for UTF8, Linux and Unix default it UTF8
if (codepage != const_cpinfo::UTF8)
{
//If other value is used return error because Linux and Unix only used UTF-8 for codepage
errno = ERROR_INVALID_PARAMETER;
return FALSE;
}
// UTF-8 uses the default char for DefaultChar[0] which is '?'
cpinfo->DefaultChar[0] = '?';
cpinfo->DefaultChar[1] = '0';
cpinfo->MaxCharSize = 4;
for (int i = 0; i < const_cpinfo::MAX_LEADBYTES; i++ )
{
// UTF-8 uses the default has no LeadByte as result LeadByte is '0'
cpinfo->LeadByte[i] = '0';
}
return TRUE;
}
<commit_msg>Changes to documentation<commit_after>//! @file getcpinfo.cpp
//! @author Aaron Ktaz <[email protected]>
//! @brief Implements GetCpInfoW Win32 API
#include <errno.h>
#include <string>
#include <langinfo.h>
#include "getcpinfo.h"
//! @brief GetCPInfoW retrieves the name of the code page associated with
//! the current thread.
//!
//! GetCpInfoW the Unicode variation. See [MSDN documentation].
//!
//! @param[in] codepage
//! @parblock
//! An UINT Identifier for the code page for which to retrieve information.
//! See Code Page Identifiers for details
//! 65001 in the number for UTF8. It is the only valid input parameter
//!because Linux and Unix only use UTF8 for codepage
//!
//! @endparblock
//!
//! @param[out] cpinfo
//! @parblock
//! Pointer to a CPINFO structure that receives information about the code page
//!
//! LPCPINFO is a pointer to the structure _cpinfo used to contain the information
//! about a code page
//!
//!
//! typedef struct _cpinfo {
//! UINT MaxCharSize;
//! BYTE DefaultChar[MAX_DEFAULTCHAR];
//! BYTE LeadByte[MAX_LEADBYTES];
//! } CPINFO, *LPCPINFO;
//!
//! _cpinfo is a struct that comprises
//!
//! UINT MaxCharSize;
//! Maximum length, in bytes, of a character in the code page.
//! The length can be 1 for a single-byte character set (SBCS),
//! 2 for a double-byte character set (DBCS), or a value larger
//! than 2 for other character set types. The function cannot
//! use the size to distinguish an SBCS or a DBCS from other
//! character sets because of other factors, for example,
//! the use of ISCII or ISO-2022-xx code pages.
//!
//! BYTE DefaultChar[const_cpinfo::MAX_DEFAULTCHAR];
//! Default character used when translating character
//! strings to the specific code page. This character is used by
//! the WideCharToMultiByte function if an explicit default
//! character is not specified. The default is usually the "?"
//! character for the code page
//!
//! BYTE LeadByte[const_cpinfo::MAX_LEADBYTES];
//! A fixed-length array of lead byte ranges, for which the number
//! of lead byte ranges is variable. If the code page has no lead
//! bytes, every element of the array is set to NULL. If the code
//! page has lead bytes, the array specifies a starting value and
//! an ending value for each range. Ranges are inclusive, and the
//! maximum number of ranges for any code page is five. The array
//! uses two bytes to describe each range, with two null bytes as
//! a terminator after the last range.
//!
//! MAX_DEFAULTCHAR is an int of size 2
//! MAX_LEADBYTES is an int of size 12
//!
//!
//! @exception errno Passes these errors via errno to GetLastError:
//! - ERROR_INVALID_PARAMETER: parameter is not valid
//!
//! @retval TRUE If the function succeeds, the return value is a nonzero
//! value, and cpinfo is population with information about the code page
//!
//! @retval FALSE If the function fails, the return value is zero. To get
//! extended error information, call GetLastError.
//!
//! [MSDN documentation]:https://msdn.microsoft.com/en-us/library/windows/desktop/dd318078%28v=vs.85%29.aspx
//! [_cpinfo]: https://msdn.microsoft.com/en-us/library/windows/desktop/dd317780(v=vs.85).aspx
//! [CodePageIdentifiers] https://msdn.microsoft.com/en-us/library/windows/desktop/dd317756(v=vs.85).aspx
BOOL GetCPInfoW(UINT codepage, CPINFO* cpinfo)
{
errno = FALSE;
// Select locale from environment
setlocale(LC_ALL, "");
// Check that locale is UTF-8
if (nl_langinfo(CODESET) != std::string("UTF-8"))
{
errno = ERROR_BAD_ENVIRONMENT;
return FALSE;
}
if (codepage != const_cpinfo::UTF8)
{
//If other value is used return error because Linux and Unix only used UTF-8 for codepage
errno = ERROR_INVALID_PARAMETER;
return FALSE;
}
// UTF-8 uses the default char for DefaultChar[0] which is '?'
cpinfo->DefaultChar[0] = '?';
cpinfo->DefaultChar[1] = '0';
cpinfo->MaxCharSize = 4;
for (int i = 0; i < const_cpinfo::MAX_LEADBYTES; i++ )
{
// UTF-8 uses the default has no LeadByte as result LeadByte is '0'
cpinfo->LeadByte[i] = '0';
}
return TRUE;
}
<|endoftext|> |
<commit_before>// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "manifest_parser.h"
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include "graph.h"
#include "state.h"
#include "util.h"
#include "version.h"
ManifestParser::ManifestParser(State* state, FileReader* file_reader,
ManifestParserOptions options)
: Parser(state, file_reader),
options_(options), quiet_(false) {
env_ = &state->bindings_;
}
bool ManifestParser::Parse(const string& filename, const string& input,
string* err) {
lexer_.Start(filename, input);
for (;;) {
Lexer::Token token = lexer_.ReadToken();
switch (token) {
case Lexer::POOL:
if (!ParsePool(err))
return false;
break;
case Lexer::BUILD:
if (!ParseEdge(err))
return false;
break;
case Lexer::RULE:
if (!ParseRule(err))
return false;
break;
case Lexer::DEFAULT:
if (!ParseDefault(err))
return false;
break;
case Lexer::IDENT: {
lexer_.UnreadToken();
string name;
EvalString let_value;
if (!ParseLet(&name, &let_value, err))
return false;
string value = let_value.Evaluate(env_);
// Check ninja_required_version immediately so we can exit
// before encountering any syntactic surprises.
if (name == "ninja_required_version")
CheckNinjaVersion(value);
env_->AddBinding(name, value);
break;
}
case Lexer::INCLUDE:
if (!ParseFileInclude(false, err))
return false;
break;
case Lexer::SUBNINJA:
if (!ParseFileInclude(true, err))
return false;
break;
case Lexer::ERROR: {
return lexer_.Error(lexer_.DescribeLastError(), err);
}
case Lexer::TEOF:
return true;
case Lexer::NEWLINE:
break;
default:
return lexer_.Error(string("unexpected ") + Lexer::TokenName(token),
err);
}
}
return false; // not reached
}
bool ManifestParser::ParsePool(string* err) {
string name;
if (!lexer_.ReadIdent(&name))
return lexer_.Error("expected pool name", err);
if (!ExpectToken(Lexer::NEWLINE, err))
return false;
if (state_->LookupPool(name) != NULL)
return lexer_.Error("duplicate pool '" + name + "'", err);
int depth = -1;
while (lexer_.PeekToken(Lexer::INDENT)) {
string key;
EvalString value;
if (!ParseLet(&key, &value, err))
return false;
if (key == "depth") {
string depth_string = value.Evaluate(env_);
depth = atol(depth_string.c_str());
if (depth < 0)
return lexer_.Error("invalid pool depth", err);
} else {
return lexer_.Error("unexpected variable '" + key + "'", err);
}
}
if (depth < 0)
return lexer_.Error("expected 'depth =' line", err);
state_->AddPool(new Pool(name, depth));
return true;
}
bool ManifestParser::ParseRule(string* err) {
string name;
if (!lexer_.ReadIdent(&name))
return lexer_.Error("expected rule name", err);
if (!ExpectToken(Lexer::NEWLINE, err))
return false;
if (env_->LookupRuleCurrentScope(name) != NULL)
return lexer_.Error("duplicate rule '" + name + "'", err);
Rule* rule = new Rule(name); // XXX scoped_ptr
while (lexer_.PeekToken(Lexer::INDENT)) {
string key;
EvalString value;
if (!ParseLet(&key, &value, err))
return false;
if (Rule::IsReservedBinding(key)) {
rule->AddBinding(key, value);
} else {
// Die on other keyvals for now; revisit if we want to add a
// scope here.
return lexer_.Error("unexpected variable '" + key + "'", err);
}
}
if (rule->bindings_["rspfile"].empty() !=
rule->bindings_["rspfile_content"].empty()) {
return lexer_.Error("rspfile and rspfile_content need to be "
"both specified", err);
}
if (rule->bindings_["command"].empty())
return lexer_.Error("expected 'command =' line", err);
env_->AddRule(rule);
return true;
}
bool ManifestParser::ParseLet(string* key, EvalString* value, string* err) {
if (!lexer_.ReadIdent(key))
return lexer_.Error("expected variable name", err);
if (!ExpectToken(Lexer::EQUALS, err))
return false;
if (!lexer_.ReadVarValue(value, err))
return false;
return true;
}
bool ManifestParser::ParseDefault(string* err) {
EvalString eval;
if (!lexer_.ReadPath(&eval, err))
return false;
if (eval.empty())
return lexer_.Error("expected target name", err);
do {
string path = eval.Evaluate(env_);
string path_err;
uint64_t slash_bits; // Unused because this only does lookup.
if (!CanonicalizePath(&path, &slash_bits, &path_err))
return lexer_.Error(path_err, err);
if (!state_->AddDefault(path, &path_err))
return lexer_.Error(path_err, err);
eval.Clear();
if (!lexer_.ReadPath(&eval, err))
return false;
} while (!eval.empty());
if (!ExpectToken(Lexer::NEWLINE, err))
return false;
return true;
}
bool ManifestParser::ParseEdge(string* err) {
vector<EvalString> ins, outs;
{
EvalString out;
if (!lexer_.ReadPath(&out, err))
return false;
while (!out.empty()) {
outs.push_back(out);
out.Clear();
if (!lexer_.ReadPath(&out, err))
return false;
}
}
// Add all implicit outs, counting how many as we go.
int implicit_outs = 0;
if (lexer_.PeekToken(Lexer::PIPE)) {
for (;;) {
EvalString out;
if (!lexer_.ReadPath(&out, err))
return err;
if (out.empty())
break;
outs.push_back(out);
++implicit_outs;
}
}
if (outs.empty())
return lexer_.Error("expected path", err);
if (!ExpectToken(Lexer::COLON, err))
return false;
string rule_name;
if (!lexer_.ReadIdent(&rule_name))
return lexer_.Error("expected build command name", err);
const Rule* rule = env_->LookupRule(rule_name);
if (!rule)
return lexer_.Error("unknown build rule '" + rule_name + "'", err);
for (;;) {
// XXX should we require one path here?
EvalString in;
if (!lexer_.ReadPath(&in, err))
return false;
if (in.empty())
break;
ins.push_back(in);
}
// Add all implicit deps, counting how many as we go.
int implicit = 0;
if (lexer_.PeekToken(Lexer::PIPE)) {
for (;;) {
EvalString in;
if (!lexer_.ReadPath(&in, err))
return err;
if (in.empty())
break;
ins.push_back(in);
++implicit;
}
}
// Add all order-only deps, counting how many as we go.
int order_only = 0;
if (lexer_.PeekToken(Lexer::PIPE2)) {
for (;;) {
EvalString in;
if (!lexer_.ReadPath(&in, err))
return false;
if (in.empty())
break;
ins.push_back(in);
++order_only;
}
}
if (!ExpectToken(Lexer::NEWLINE, err))
return false;
// Bindings on edges are rare, so allocate per-edge envs only when needed.
bool has_indent_token = lexer_.PeekToken(Lexer::INDENT);
BindingEnv* env = has_indent_token ? new BindingEnv(env_) : env_;
while (has_indent_token) {
string key;
EvalString val;
if (!ParseLet(&key, &val, err))
return false;
env->AddBinding(key, val.Evaluate(env_));
has_indent_token = lexer_.PeekToken(Lexer::INDENT);
}
Edge* edge = state_->AddEdge(rule);
edge->env_ = env;
string pool_name = edge->GetBinding("pool");
if (!pool_name.empty()) {
Pool* pool = state_->LookupPool(pool_name);
if (pool == NULL)
return lexer_.Error("unknown pool name '" + pool_name + "'", err);
edge->pool_ = pool;
}
edge->outputs_.reserve(outs.size());
for (size_t i = 0, e = outs.size(); i != e; ++i) {
string path = outs[i].Evaluate(env);
string path_err;
uint64_t slash_bits;
if (!CanonicalizePath(&path, &slash_bits, &path_err))
return lexer_.Error(path_err, err);
if (!state_->AddOut(edge, path, slash_bits)) {
if (options_.dupe_edge_action_ == kDupeEdgeActionError) {
lexer_.Error("multiple rules generate " + path + " [-w dupbuild=err]",
err);
return false;
} else {
if (!quiet_) {
Warning("multiple rules generate %s. "
"builds involving this target will not be correct; "
"continuing anyway [-w dupbuild=warn]",
path.c_str());
}
if (e - i <= static_cast<size_t>(implicit_outs))
--implicit_outs;
}
}
}
if (edge->outputs_.empty()) {
// All outputs of the edge are already created by other edges. Don't add
// this edge. Do this check before input nodes are connected to the edge.
state_->edges_.pop_back();
delete edge;
return true;
}
edge->implicit_outs_ = implicit_outs;
edge->inputs_.reserve(ins.size());
for (vector<EvalString>::iterator i = ins.begin(); i != ins.end(); ++i) {
string path = i->Evaluate(env);
string path_err;
uint64_t slash_bits;
if (!CanonicalizePath(&path, &slash_bits, &path_err))
return lexer_.Error(path_err, err);
state_->AddIn(edge, path, slash_bits);
}
edge->implicit_deps_ = implicit;
edge->order_only_deps_ = order_only;
if (options_.phony_cycle_action_ == kPhonyCycleActionWarn &&
edge->maybe_phonycycle_diagnostic()) {
// CMake 2.8.12.x and 3.0.x incorrectly write phony build statements
// that reference themselves. Ninja used to tolerate these in the
// build graph but that has since been fixed. Filter them out to
// support users of those old CMake versions.
Node* out = edge->outputs_[0];
vector<Node*>::iterator new_end =
remove(edge->inputs_.begin(), edge->inputs_.end(), out);
if (new_end != edge->inputs_.end()) {
edge->inputs_.erase(new_end, edge->inputs_.end());
if (!quiet_) {
Warning("phony target '%s' names itself as an input; "
"ignoring [-w phonycycle=warn]",
out->path().c_str());
}
}
}
// Multiple outputs aren't (yet?) supported with depslog.
string deps_type = edge->GetBinding("deps");
if (!deps_type.empty() && edge->outputs_.size() > 1) {
return lexer_.Error("multiple outputs aren't (yet?) supported by depslog; "
"bring this up on the mailing list if it affects you",
err);
}
// Lookup, validate, and save any dyndep binding. It will be used later
// to load generated dependency information dynamically, but it must
// be one of our manifest-specified inputs.
string dyndep = edge->GetUnescapedDyndep();
if (!dyndep.empty()) {
uint64_t slash_bits;
if (!CanonicalizePath(&dyndep, &slash_bits, err))
return false;
edge->dyndep_ = state_->GetNode(dyndep, slash_bits);
edge->dyndep_->set_dyndep_pending(true);
vector<Node*>::iterator dgi =
std::find(edge->inputs_.begin(), edge->inputs_.end(), edge->dyndep_);
if (dgi == edge->inputs_.end()) {
return lexer_.Error("dyndep '" + dyndep + "' is not an input", err);
}
}
return true;
}
bool ManifestParser::ParseFileInclude(bool new_scope, string* err) {
EvalString eval;
if (!lexer_.ReadPath(&eval, err))
return false;
string path = eval.Evaluate(env_);
ManifestParser subparser(state_, file_reader_, options_);
if (new_scope) {
subparser.env_ = new BindingEnv(env_);
} else {
subparser.env_ = env_;
}
if (!subparser.Load(path, err, &lexer_))
return false;
if (!ExpectToken(Lexer::NEWLINE, err))
return false;
return true;
}
<commit_msg>Fix minor typo of return value<commit_after>// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "manifest_parser.h"
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include "graph.h"
#include "state.h"
#include "util.h"
#include "version.h"
ManifestParser::ManifestParser(State* state, FileReader* file_reader,
ManifestParserOptions options)
: Parser(state, file_reader),
options_(options), quiet_(false) {
env_ = &state->bindings_;
}
bool ManifestParser::Parse(const string& filename, const string& input,
string* err) {
lexer_.Start(filename, input);
for (;;) {
Lexer::Token token = lexer_.ReadToken();
switch (token) {
case Lexer::POOL:
if (!ParsePool(err))
return false;
break;
case Lexer::BUILD:
if (!ParseEdge(err))
return false;
break;
case Lexer::RULE:
if (!ParseRule(err))
return false;
break;
case Lexer::DEFAULT:
if (!ParseDefault(err))
return false;
break;
case Lexer::IDENT: {
lexer_.UnreadToken();
string name;
EvalString let_value;
if (!ParseLet(&name, &let_value, err))
return false;
string value = let_value.Evaluate(env_);
// Check ninja_required_version immediately so we can exit
// before encountering any syntactic surprises.
if (name == "ninja_required_version")
CheckNinjaVersion(value);
env_->AddBinding(name, value);
break;
}
case Lexer::INCLUDE:
if (!ParseFileInclude(false, err))
return false;
break;
case Lexer::SUBNINJA:
if (!ParseFileInclude(true, err))
return false;
break;
case Lexer::ERROR: {
return lexer_.Error(lexer_.DescribeLastError(), err);
}
case Lexer::TEOF:
return true;
case Lexer::NEWLINE:
break;
default:
return lexer_.Error(string("unexpected ") + Lexer::TokenName(token),
err);
}
}
return false; // not reached
}
bool ManifestParser::ParsePool(string* err) {
string name;
if (!lexer_.ReadIdent(&name))
return lexer_.Error("expected pool name", err);
if (!ExpectToken(Lexer::NEWLINE, err))
return false;
if (state_->LookupPool(name) != NULL)
return lexer_.Error("duplicate pool '" + name + "'", err);
int depth = -1;
while (lexer_.PeekToken(Lexer::INDENT)) {
string key;
EvalString value;
if (!ParseLet(&key, &value, err))
return false;
if (key == "depth") {
string depth_string = value.Evaluate(env_);
depth = atol(depth_string.c_str());
if (depth < 0)
return lexer_.Error("invalid pool depth", err);
} else {
return lexer_.Error("unexpected variable '" + key + "'", err);
}
}
if (depth < 0)
return lexer_.Error("expected 'depth =' line", err);
state_->AddPool(new Pool(name, depth));
return true;
}
bool ManifestParser::ParseRule(string* err) {
string name;
if (!lexer_.ReadIdent(&name))
return lexer_.Error("expected rule name", err);
if (!ExpectToken(Lexer::NEWLINE, err))
return false;
if (env_->LookupRuleCurrentScope(name) != NULL)
return lexer_.Error("duplicate rule '" + name + "'", err);
Rule* rule = new Rule(name); // XXX scoped_ptr
while (lexer_.PeekToken(Lexer::INDENT)) {
string key;
EvalString value;
if (!ParseLet(&key, &value, err))
return false;
if (Rule::IsReservedBinding(key)) {
rule->AddBinding(key, value);
} else {
// Die on other keyvals for now; revisit if we want to add a
// scope here.
return lexer_.Error("unexpected variable '" + key + "'", err);
}
}
if (rule->bindings_["rspfile"].empty() !=
rule->bindings_["rspfile_content"].empty()) {
return lexer_.Error("rspfile and rspfile_content need to be "
"both specified", err);
}
if (rule->bindings_["command"].empty())
return lexer_.Error("expected 'command =' line", err);
env_->AddRule(rule);
return true;
}
bool ManifestParser::ParseLet(string* key, EvalString* value, string* err) {
if (!lexer_.ReadIdent(key))
return lexer_.Error("expected variable name", err);
if (!ExpectToken(Lexer::EQUALS, err))
return false;
if (!lexer_.ReadVarValue(value, err))
return false;
return true;
}
bool ManifestParser::ParseDefault(string* err) {
EvalString eval;
if (!lexer_.ReadPath(&eval, err))
return false;
if (eval.empty())
return lexer_.Error("expected target name", err);
do {
string path = eval.Evaluate(env_);
string path_err;
uint64_t slash_bits; // Unused because this only does lookup.
if (!CanonicalizePath(&path, &slash_bits, &path_err))
return lexer_.Error(path_err, err);
if (!state_->AddDefault(path, &path_err))
return lexer_.Error(path_err, err);
eval.Clear();
if (!lexer_.ReadPath(&eval, err))
return false;
} while (!eval.empty());
if (!ExpectToken(Lexer::NEWLINE, err))
return false;
return true;
}
bool ManifestParser::ParseEdge(string* err) {
vector<EvalString> ins, outs;
{
EvalString out;
if (!lexer_.ReadPath(&out, err))
return false;
while (!out.empty()) {
outs.push_back(out);
out.Clear();
if (!lexer_.ReadPath(&out, err))
return false;
}
}
// Add all implicit outs, counting how many as we go.
int implicit_outs = 0;
if (lexer_.PeekToken(Lexer::PIPE)) {
for (;;) {
EvalString out;
if (!lexer_.ReadPath(&out, err))
return false;
if (out.empty())
break;
outs.push_back(out);
++implicit_outs;
}
}
if (outs.empty())
return lexer_.Error("expected path", err);
if (!ExpectToken(Lexer::COLON, err))
return false;
string rule_name;
if (!lexer_.ReadIdent(&rule_name))
return lexer_.Error("expected build command name", err);
const Rule* rule = env_->LookupRule(rule_name);
if (!rule)
return lexer_.Error("unknown build rule '" + rule_name + "'", err);
for (;;) {
// XXX should we require one path here?
EvalString in;
if (!lexer_.ReadPath(&in, err))
return false;
if (in.empty())
break;
ins.push_back(in);
}
// Add all implicit deps, counting how many as we go.
int implicit = 0;
if (lexer_.PeekToken(Lexer::PIPE)) {
for (;;) {
EvalString in;
if (!lexer_.ReadPath(&in, err))
return false;
if (in.empty())
break;
ins.push_back(in);
++implicit;
}
}
// Add all order-only deps, counting how many as we go.
int order_only = 0;
if (lexer_.PeekToken(Lexer::PIPE2)) {
for (;;) {
EvalString in;
if (!lexer_.ReadPath(&in, err))
return false;
if (in.empty())
break;
ins.push_back(in);
++order_only;
}
}
if (!ExpectToken(Lexer::NEWLINE, err))
return false;
// Bindings on edges are rare, so allocate per-edge envs only when needed.
bool has_indent_token = lexer_.PeekToken(Lexer::INDENT);
BindingEnv* env = has_indent_token ? new BindingEnv(env_) : env_;
while (has_indent_token) {
string key;
EvalString val;
if (!ParseLet(&key, &val, err))
return false;
env->AddBinding(key, val.Evaluate(env_));
has_indent_token = lexer_.PeekToken(Lexer::INDENT);
}
Edge* edge = state_->AddEdge(rule);
edge->env_ = env;
string pool_name = edge->GetBinding("pool");
if (!pool_name.empty()) {
Pool* pool = state_->LookupPool(pool_name);
if (pool == NULL)
return lexer_.Error("unknown pool name '" + pool_name + "'", err);
edge->pool_ = pool;
}
edge->outputs_.reserve(outs.size());
for (size_t i = 0, e = outs.size(); i != e; ++i) {
string path = outs[i].Evaluate(env);
string path_err;
uint64_t slash_bits;
if (!CanonicalizePath(&path, &slash_bits, &path_err))
return lexer_.Error(path_err, err);
if (!state_->AddOut(edge, path, slash_bits)) {
if (options_.dupe_edge_action_ == kDupeEdgeActionError) {
lexer_.Error("multiple rules generate " + path + " [-w dupbuild=err]",
err);
return false;
} else {
if (!quiet_) {
Warning("multiple rules generate %s. "
"builds involving this target will not be correct; "
"continuing anyway [-w dupbuild=warn]",
path.c_str());
}
if (e - i <= static_cast<size_t>(implicit_outs))
--implicit_outs;
}
}
}
if (edge->outputs_.empty()) {
// All outputs of the edge are already created by other edges. Don't add
// this edge. Do this check before input nodes are connected to the edge.
state_->edges_.pop_back();
delete edge;
return true;
}
edge->implicit_outs_ = implicit_outs;
edge->inputs_.reserve(ins.size());
for (vector<EvalString>::iterator i = ins.begin(); i != ins.end(); ++i) {
string path = i->Evaluate(env);
string path_err;
uint64_t slash_bits;
if (!CanonicalizePath(&path, &slash_bits, &path_err))
return lexer_.Error(path_err, err);
state_->AddIn(edge, path, slash_bits);
}
edge->implicit_deps_ = implicit;
edge->order_only_deps_ = order_only;
if (options_.phony_cycle_action_ == kPhonyCycleActionWarn &&
edge->maybe_phonycycle_diagnostic()) {
// CMake 2.8.12.x and 3.0.x incorrectly write phony build statements
// that reference themselves. Ninja used to tolerate these in the
// build graph but that has since been fixed. Filter them out to
// support users of those old CMake versions.
Node* out = edge->outputs_[0];
vector<Node*>::iterator new_end =
remove(edge->inputs_.begin(), edge->inputs_.end(), out);
if (new_end != edge->inputs_.end()) {
edge->inputs_.erase(new_end, edge->inputs_.end());
if (!quiet_) {
Warning("phony target '%s' names itself as an input; "
"ignoring [-w phonycycle=warn]",
out->path().c_str());
}
}
}
// Multiple outputs aren't (yet?) supported with depslog.
string deps_type = edge->GetBinding("deps");
if (!deps_type.empty() && edge->outputs_.size() > 1) {
return lexer_.Error("multiple outputs aren't (yet?) supported by depslog; "
"bring this up on the mailing list if it affects you",
err);
}
// Lookup, validate, and save any dyndep binding. It will be used later
// to load generated dependency information dynamically, but it must
// be one of our manifest-specified inputs.
string dyndep = edge->GetUnescapedDyndep();
if (!dyndep.empty()) {
uint64_t slash_bits;
if (!CanonicalizePath(&dyndep, &slash_bits, err))
return false;
edge->dyndep_ = state_->GetNode(dyndep, slash_bits);
edge->dyndep_->set_dyndep_pending(true);
vector<Node*>::iterator dgi =
std::find(edge->inputs_.begin(), edge->inputs_.end(), edge->dyndep_);
if (dgi == edge->inputs_.end()) {
return lexer_.Error("dyndep '" + dyndep + "' is not an input", err);
}
}
return true;
}
bool ManifestParser::ParseFileInclude(bool new_scope, string* err) {
EvalString eval;
if (!lexer_.ReadPath(&eval, err))
return false;
string path = eval.Evaluate(env_);
ManifestParser subparser(state_, file_reader_, options_);
if (new_scope) {
subparser.env_ = new BindingEnv(env_);
} else {
subparser.env_ = env_;
}
if (!subparser.Load(path, err, &lexer_))
return false;
if (!ExpectToken(Lexer::NEWLINE, err))
return false;
return true;
}
<|endoftext|> |
<commit_before>#include "math_container.h"
using std::complex;
/******************************************************/
/*solve the equation cosh(x)=exp(y), input y, return x*/
/******************************************************/
complex<double> coshx_eq_expy(double y)
{
complex<double> ey={exp(y),0};
complex<double> gamma=log(ey-sqrt(ey*ey-1.0));
//Since gamma is pure real or pure imaginary, set it:
if( abs( gamma.real() ) < abs( gamma.imag() ) ) gamma=complex<double>( 0, gamma.imag() );
else gamma=complex<double>( gamma.real(), 0 );
return gamma;
}
<commit_msg>Use namespace std, if we do not set this there is a bug?.<commit_after>#include "math_container.h"
using namespace std;
/******************************************************/
/*solve the equation cosh(x)=exp(y), input y, return x*/
/******************************************************/
complex<double> coshx_eq_expy(double y)
{
complex<double> ey={exp(y),0};
complex<double> gamma=log(ey-sqrt(ey*ey-1.0));
//Since gamma is pure real or pure imaginary, set it:
if( abs( gamma.real() ) < abs( gamma.imag() ) ) gamma=complex<double>( 0, gamma.imag() );
else gamma=complex<double>( gamma.real(), 0 );
return gamma;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2012 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Andreas Hansson
*/
#include "mem/addr_mapper.hh"
AddrMapper::AddrMapper(const AddrMapperParams* p)
: MemObject(p),
masterPort(name() + "-master", *this),
slavePort(name() + "-slave", *this)
{
}
void
AddrMapper::init()
{
if (!slavePort.isConnected() || !masterPort.isConnected())
fatal("Address mapper is not connected on both sides.\n");
if ((slavePort.peerBlockSize() != masterPort.peerBlockSize()) &&
slavePort.peerBlockSize() && masterPort.peerBlockSize())
fatal("Slave port size %d, master port size %d \n "
"don't have the same block size... Not supported.\n",
slavePort.peerBlockSize(), masterPort.peerBlockSize());
}
BaseMasterPort&
AddrMapper::getMasterPort(const std::string& if_name, PortID idx)
{
if (if_name == "master") {
return masterPort;
} else {
return MemObject::getMasterPort(if_name, idx);
}
}
BaseSlavePort&
AddrMapper::getSlavePort(const std::string& if_name, PortID idx)
{
if (if_name == "slave") {
return slavePort;
} else {
return MemObject::getSlavePort(if_name, idx);
}
}
void
AddrMapper::recvFunctional(PacketPtr pkt)
{
Addr orig_addr = pkt->getAddr();
pkt->setAddr(remapAddr(orig_addr));
masterPort.sendFunctional(pkt);
pkt->setAddr(orig_addr);
}
void
AddrMapper::recvFunctionalSnoop(PacketPtr pkt)
{
Addr orig_addr = pkt->getAddr();
pkt->setAddr(remapAddr(orig_addr));
slavePort.sendFunctionalSnoop(pkt);
pkt->setAddr(orig_addr);
}
Tick
AddrMapper::recvAtomic(PacketPtr pkt)
{
Addr orig_addr = pkt->getAddr();
pkt->setAddr(remapAddr(orig_addr));
Tick ret_tick = masterPort.sendAtomic(pkt);
pkt->setAddr(orig_addr);
return ret_tick;
}
Tick
AddrMapper::recvAtomicSnoop(PacketPtr pkt)
{
Addr orig_addr = pkt->getAddr();
pkt->setAddr(remapAddr(orig_addr));
Tick ret_tick = slavePort.sendAtomicSnoop(pkt);
pkt->setAddr(orig_addr);
return ret_tick;
}
bool
AddrMapper::recvTimingReq(PacketPtr pkt)
{
Addr orig_addr = pkt->getAddr();
bool needsResponse = pkt->needsResponse();
bool memInhibitAsserted = pkt->memInhibitAsserted();
Packet::SenderState* senderState = pkt->senderState;
if (needsResponse && !memInhibitAsserted) {
pkt->senderState = new AddrMapperSenderState(senderState, orig_addr);
}
pkt->setAddr(remapAddr(orig_addr));
// Attempt to send the packet (always succeeds for inhibited
// packets)
bool successful = masterPort.sendTimingReq(pkt);
// If not successful, restore the sender state
if (!successful && needsResponse) {
delete pkt->senderState;
pkt->senderState = senderState;
}
return successful;
}
bool
AddrMapper::recvTimingResp(PacketPtr pkt)
{
AddrMapperSenderState* receivedState =
dynamic_cast<AddrMapperSenderState*>(pkt->senderState);
// Restore initial sender state
if (receivedState == NULL)
panic("AddrMapper %s got a response without sender state\n",
name());
Addr remapped_addr = pkt->getAddr();
// Restore the state and address
pkt->senderState = receivedState->origSenderState;
pkt->setAddr(receivedState->origAddr);
// Attempt to send the packet
bool successful = slavePort.sendTimingResp(pkt);
// If packet successfully sent, delete the sender state, otherwise
// restore state
if (successful) {
delete receivedState;
} else {
// Don't delete anything and let the packet look like we did
// not touch it
pkt->senderState = receivedState;
pkt->setAddr(remapped_addr);
}
return successful;
}
void
AddrMapper::recvTimingSnoopReq(PacketPtr pkt)
{
slavePort.sendTimingSnoopReq(pkt);
}
bool
AddrMapper::recvTimingSnoopResp(PacketPtr pkt)
{
return masterPort.sendTimingSnoopResp(pkt);
}
bool
AddrMapper::isSnooping() const
{
if (slavePort.isSnooping())
fatal("AddrMapper doesn't support remapping of snooping requests\n");
return false;
}
unsigned
AddrMapper::deviceBlockSizeMaster()
{
return slavePort.peerBlockSize();
}
unsigned
AddrMapper::deviceBlockSizeSlave()
{
return masterPort.peerBlockSize();
}
void
AddrMapper::recvRetryMaster()
{
slavePort.sendRetry();
}
void
AddrMapper::recvRetrySlave()
{
masterPort.sendRetry();
}
void
AddrMapper::recvRangeChange()
{
slavePort.sendRangeChange();
}
RangeAddrMapper::RangeAddrMapper(const RangeAddrMapperParams* p) :
AddrMapper(p),
originalRanges(p->original_ranges),
remappedRanges(p->remapped_ranges)
{
if (originalRanges.size() != remappedRanges.size())
fatal("AddrMapper: original and shadowed range list must "
"be same size\n");
for (size_t x = 0; x < originalRanges.size(); x++) {
if (originalRanges[x].size() != remappedRanges[x].size())
fatal("AddrMapper: original and shadowed range list elements"
" aren't all of the same size\n");
}
}
RangeAddrMapper*
RangeAddrMapperParams::create()
{
return new RangeAddrMapper(this);
}
Addr
RangeAddrMapper::remapAddr(Addr addr) const
{
for (int i = 0; i < originalRanges.size(); ++i) {
if (originalRanges[i].contains(addr)) {
Addr offset = addr - originalRanges[i].start();
return offset + remappedRanges[i].start();
}
}
return addr;
}
AddrRangeList
RangeAddrMapper::getAddrRanges() const
{
AddrRangeList ranges;
AddrRangeList actualRanges = masterPort.getAddrRanges();
for (AddrRangeIter r = actualRanges.begin(); r != actualRanges.end(); ++r) {
AddrRange range = *r;
for (int j = 0; j < originalRanges.size(); ++j) {
if (range.intersects(originalRanges[j]))
fatal("Cannot remap range that intersects the original"
" ranges but are not a subset.\n");
if (range.isSubset(originalRanges[j])) {
// range is a subset
Addr offset = range.start() - originalRanges[j].start();
Addr start = range.start() - offset;
ranges.push_back(AddrRange(start, start + range.size() - 1));
} else {
ranges.push_back(range);
}
}
}
return ranges;
}
<commit_msg>mem: Skip address mapper range checks to allow more flexibility<commit_after>/*
* Copyright (c) 2012 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Andreas Hansson
*/
#include "mem/addr_mapper.hh"
AddrMapper::AddrMapper(const AddrMapperParams* p)
: MemObject(p),
masterPort(name() + "-master", *this),
slavePort(name() + "-slave", *this)
{
}
void
AddrMapper::init()
{
if (!slavePort.isConnected() || !masterPort.isConnected())
fatal("Address mapper is not connected on both sides.\n");
if ((slavePort.peerBlockSize() != masterPort.peerBlockSize()) &&
slavePort.peerBlockSize() && masterPort.peerBlockSize())
fatal("Slave port size %d, master port size %d \n "
"don't have the same block size... Not supported.\n",
slavePort.peerBlockSize(), masterPort.peerBlockSize());
}
BaseMasterPort&
AddrMapper::getMasterPort(const std::string& if_name, PortID idx)
{
if (if_name == "master") {
return masterPort;
} else {
return MemObject::getMasterPort(if_name, idx);
}
}
BaseSlavePort&
AddrMapper::getSlavePort(const std::string& if_name, PortID idx)
{
if (if_name == "slave") {
return slavePort;
} else {
return MemObject::getSlavePort(if_name, idx);
}
}
void
AddrMapper::recvFunctional(PacketPtr pkt)
{
Addr orig_addr = pkt->getAddr();
pkt->setAddr(remapAddr(orig_addr));
masterPort.sendFunctional(pkt);
pkt->setAddr(orig_addr);
}
void
AddrMapper::recvFunctionalSnoop(PacketPtr pkt)
{
Addr orig_addr = pkt->getAddr();
pkt->setAddr(remapAddr(orig_addr));
slavePort.sendFunctionalSnoop(pkt);
pkt->setAddr(orig_addr);
}
Tick
AddrMapper::recvAtomic(PacketPtr pkt)
{
Addr orig_addr = pkt->getAddr();
pkt->setAddr(remapAddr(orig_addr));
Tick ret_tick = masterPort.sendAtomic(pkt);
pkt->setAddr(orig_addr);
return ret_tick;
}
Tick
AddrMapper::recvAtomicSnoop(PacketPtr pkt)
{
Addr orig_addr = pkt->getAddr();
pkt->setAddr(remapAddr(orig_addr));
Tick ret_tick = slavePort.sendAtomicSnoop(pkt);
pkt->setAddr(orig_addr);
return ret_tick;
}
bool
AddrMapper::recvTimingReq(PacketPtr pkt)
{
Addr orig_addr = pkt->getAddr();
bool needsResponse = pkt->needsResponse();
bool memInhibitAsserted = pkt->memInhibitAsserted();
Packet::SenderState* senderState = pkt->senderState;
if (needsResponse && !memInhibitAsserted) {
pkt->senderState = new AddrMapperSenderState(senderState, orig_addr);
}
pkt->setAddr(remapAddr(orig_addr));
// Attempt to send the packet (always succeeds for inhibited
// packets)
bool successful = masterPort.sendTimingReq(pkt);
// If not successful, restore the sender state
if (!successful && needsResponse) {
delete pkt->senderState;
pkt->senderState = senderState;
}
return successful;
}
bool
AddrMapper::recvTimingResp(PacketPtr pkt)
{
AddrMapperSenderState* receivedState =
dynamic_cast<AddrMapperSenderState*>(pkt->senderState);
// Restore initial sender state
if (receivedState == NULL)
panic("AddrMapper %s got a response without sender state\n",
name());
Addr remapped_addr = pkt->getAddr();
// Restore the state and address
pkt->senderState = receivedState->origSenderState;
pkt->setAddr(receivedState->origAddr);
// Attempt to send the packet
bool successful = slavePort.sendTimingResp(pkt);
// If packet successfully sent, delete the sender state, otherwise
// restore state
if (successful) {
delete receivedState;
} else {
// Don't delete anything and let the packet look like we did
// not touch it
pkt->senderState = receivedState;
pkt->setAddr(remapped_addr);
}
return successful;
}
void
AddrMapper::recvTimingSnoopReq(PacketPtr pkt)
{
slavePort.sendTimingSnoopReq(pkt);
}
bool
AddrMapper::recvTimingSnoopResp(PacketPtr pkt)
{
return masterPort.sendTimingSnoopResp(pkt);
}
bool
AddrMapper::isSnooping() const
{
if (slavePort.isSnooping())
fatal("AddrMapper doesn't support remapping of snooping requests\n");
return false;
}
unsigned
AddrMapper::deviceBlockSizeMaster()
{
return slavePort.peerBlockSize();
}
unsigned
AddrMapper::deviceBlockSizeSlave()
{
return masterPort.peerBlockSize();
}
void
AddrMapper::recvRetryMaster()
{
slavePort.sendRetry();
}
void
AddrMapper::recvRetrySlave()
{
masterPort.sendRetry();
}
void
AddrMapper::recvRangeChange()
{
slavePort.sendRangeChange();
}
RangeAddrMapper::RangeAddrMapper(const RangeAddrMapperParams* p) :
AddrMapper(p),
originalRanges(p->original_ranges),
remappedRanges(p->remapped_ranges)
{
if (originalRanges.size() != remappedRanges.size())
fatal("AddrMapper: original and shadowed range list must "
"be same size\n");
for (size_t x = 0; x < originalRanges.size(); x++) {
if (originalRanges[x].size() != remappedRanges[x].size())
fatal("AddrMapper: original and shadowed range list elements"
" aren't all of the same size\n");
}
}
RangeAddrMapper*
RangeAddrMapperParams::create()
{
return new RangeAddrMapper(this);
}
Addr
RangeAddrMapper::remapAddr(Addr addr) const
{
for (int i = 0; i < originalRanges.size(); ++i) {
if (originalRanges[i].contains(addr)) {
Addr offset = addr - originalRanges[i].start();
return offset + remappedRanges[i].start();
}
}
return addr;
}
AddrRangeList
RangeAddrMapper::getAddrRanges() const
{
// Simply return the original ranges as given by the parameters
AddrRangeList ranges(originalRanges.begin(), originalRanges.end());
return ranges;
}
<|endoftext|> |
<commit_before>#include <algorithm>
#include <string>
#include <vector>
#include <boost/optional.hpp>
#include <locale>
#include "../../../src/prompt.hh"
#include "../../../src/configuration.hh"
#include "../../../src/to_str.hh"
#include "../../../src/show_message.hh"
#include "../../../src/visual.hh"
#include "move.hh"
void mvline(contents& contents, boost::optional<int> line) {
if(line) {
contents.x = 0;
int cont = line.get();
if(cont < 0) {
show_message("Can't move to a negative line!");
contents.y = 0;
return;
}
contents.y = cont;
if(cont >= contents.cont.size()) {
contents.y = contents.cont.size() - 1;
show_message("Can't move past end of buffer!");
}
} else {
while(true) {
std::string str = prompt("Goto line: ");
try {
int res = std::stoi(str);
mvline(contents, res);
return;
} catch(std::invalid_argument) {
continue;
}
}
}
}
void mv(contents& contents, unsigned long _y, unsigned long _x) {
contents.y = _y;
contents.x = _x;
if((long) contents.y < 0) contents.y = 0;
if(contents.y >= contents.cont.size())
contents.y = contents.cont.size() - 1;
if((long) contents.x < 0) contents.x = 0;
if(contents.x >= contents.cont[contents.y].size())
contents.x = contents.cont[contents.y].size() - 1;
}
void mvrel(contents& contents, long y, long x) {
if(y < 0) mvu(contents,-y);
else mvd(contents, y);
if(x < 0) mvb(contents,-x);
else mvf(contents, x);
}
void mvcol(contents& contents, boost::optional<int> col) {
if(col) {
unsigned int len = contents.cont[contents.y].length();
if(len >= col.get()) {
contents.x = col.get();
contents.waiting_for_desired = false;
} else {
show_message((std::string("Can't move to column: ")
+ int_to_str(col.get())).c_str());
}
} else {
while(true) {
std::string str = prompt("Goto column: ");
try {
int res = std::stoi(str);
mvcol(contents, res);
return;
} catch(std::invalid_argument) {
continue;
}
}
}
}
void mvsot(contents& contents, boost::optional<int> op) {
mvsol(contents, op);
const std::string& str = contents.cont[contents.y];
for(unsigned int i = 0; i < str.length(); i++) {
if(str[i] == ' ' || str[i] == '\t')
mvf(contents, op);
else break;
}
}
void mveol(contents& contents, boost::optional<int>) {
mvcol(contents,contents.cont[contents.y].length() - 1);
}
void mvsol(contents& contents, boost::optional<int>) {
mvcol(contents,0);
}
void mvsop(contents& contents, boost::optional<int>) {
contents.y = 0;
contents.x = 0;
contents.waiting_for_desired = false;
contents.y_offset = 0;
}
void mveop(contents& contents, boost::optional<int>) {
contents.y = contents.cont.size() - 1;
contents.x = 0;
contents.y_offset = contents.y - contents.max_y + 2;
contents.waiting_for_desired = false;
}
void mvd(contents& contents, boost::optional<int> op) {
int times = op ? op.get() : 1;
if(contents.y + times < 0 || contents.y + times >= contents.cont.size()) {
show_message("Can't move to that location (start/end of buffer)");
return;
}
int vis = to_visual(contents.cont[contents.y],contents.x);
contents.y += times;
unsigned int len = contents.cont[contents.y].length();
if(contents.waiting_for_desired) {
if((int)contents.x < 0) {
contents.x = len - 1;
unsigned int vis = from_visual(contents.cont[contents.y],
contents.desired_x);
if(vis < contents.x) {
contents.x = vis;
contents.waiting_for_desired = false;
}
} else if(contents.x >= len) {
contents.x = len - 1;
} else if((contents.desired_x > contents.x
&& contents.desired_x < len)
|| contents.desired_x == 0) {
// x desired len
contents.x = contents.desired_x;
contents.waiting_for_desired = false;
} else {
// x len desired
contents.x = len - 1;
}
} else if(len <= contents.x && len > 0) {
contents.waiting_for_desired = true;
contents.desired_x = contents.x;
contents.x = len - 1;
} else {
int des = contents.x;
contents.x = from_visual(contents.cont[contents.y],vis);
if(len == 0) {
contents.waiting_for_desired = true;
contents.desired_x = des;
}
}
contents.x = (long) contents.x >= 0 ? contents.x : 0;
if(contents.y - contents.y_offset >= contents.max_y)
contents.y_offset = contents.y - contents.y_offset + 1;
if(contents.y < contents.y_offset)
contents.y_offset = contents.y;
}
void mvu(contents& contents, boost::optional<int> op) {
if(op) mvd(contents,-op.get());
else mvd(contents,-1);
}
inline static bool isDeliminator(char ch) {
return std::find(DELIMINATORS.begin(), DELIMINATORS.end(), ch)
!= DELIMINATORS.end();
}
inline static bool isWhitespace(char ch) {
static const std::locale loc;
return std::isspace(ch, loc);
}
void mvfw(contents& contents, boost::optional<int> op) {
if(op && op.get() < 0) return mvbw(contents, op.get() * -1);
int num = op ? op.get() : 1;
if(num == 0 || num == -0) return;
if(num < 0) return mvbw(contents, -op.get());
//if deliminator then move forward until not deliminator then move over whitespace
//else move foward until (whitespace -> move till not whitespace) or (deliminator -> stop)
#define boundsCheck if(contents.y >= contents.cont.size() || \
(contents.y == contents.cont.size() - 1 && \
contents.x >= contents.cont[contents.y].size())) return;
#define ch contents.cont[contents.y][contents.x]
if(isDeliminator(ch)) {
do {
mvf(contents);
boundsCheck;
} while(isDeliminator(ch));
while(isWhitespace(ch)) {
mvf(contents);
boundsCheck;
}
} else {
while(!isDeliminator(ch) and !isWhitespace(ch)) {
mvf(contents);
boundsCheck;
}
if(isWhitespace(ch)) {
while(isWhitespace(ch)) {
mvf(contents);
boundsCheck;
}
} else {
while(isDeliminator(ch)) {
mvf(contents);
boundsCheck;
}
}
}
#undef boundsCheck
if(num > 0) mvfw(contents,num - 1);
}
void mvfeow(contents& contents, boost::optional<int> op) {
//move at least one forward
//move over non deliminators
//move over deliminators
}
void mvbw(contents& contents, boost::optional<int> op) {
//move back one then
//if delimitor then move back until no delimitor
//else if whitespace then move back until not whitespace then
// move back consistently over delimitors or word chars
//else /*word char*/ move back until not word char or
// whitespace
//move forward one
}
inline static unsigned int fixLen(unsigned int len) {
return len ? len : 1;
}
void mvf(contents& contents, boost::optional<int> op) {
int times = op ? op.get() : 1;
long newx = contents.x + times;
try {
while(fixLen(contents.cont.at(contents.y).length()) <= newx) {
newx -= fixLen(contents.cont[contents.y].length());
contents.y++;
}
} catch(...) { }
if(contents.y >= contents.cont.size()) contents.y = contents.cont.size()-1;
if(contents.x < 0) contents.x = 0;
else contents.x = newx;
contents.waiting_for_desired = false;
}
void mvb(contents& contents, boost::optional<int> op) {
int times = op ? op.get() : 1;
if(contents.y == 0 && contents.x == 0) return;
long newx = contents.x - times;
try {
while(newx < 0) {
contents.y--;
newx += fixLen(contents.cont.at(contents.y).length());
}
} catch(...) { }
if(newx < 0) contents.x = 0;
else contents.x = newx;
contents.waiting_for_desired = false;
}
<commit_msg>Align text for ``move.cc``<commit_after>#include <algorithm>
#include <string>
#include <vector>
#include <boost/optional.hpp>
#include <locale>
#include "../../../src/prompt.hh"
#include "../../../src/configuration.hh"
#include "../../../src/to_str.hh"
#include "../../../src/show_message.hh"
#include "../../../src/visual.hh"
#include "move.hh"
void mvline(contents& contents, boost::optional<int> line) {
if(line) {
contents.x = 0;
int cont = line.get();
if(cont < 0) {
show_message("Can't move to a negative line!");
contents.y = 0;
return;
}
contents.y = cont;
if(cont >= contents.cont.size()) {
contents.y = contents.cont.size() - 1;
show_message("Can't move past end of buffer!");
}
} else {
while(true) {
std::string str = prompt("Goto line: ");
try {
int res = std::stoi(str);
mvline(contents, res);
return;
} catch(std::invalid_argument) {
continue;
}
}
}
}
void mv(contents& contents, unsigned long _y, unsigned long _x) {
contents.y = _y;
contents.x = _x;
if((long) contents.y < 0) contents.y = 0;
if(contents.y >= contents.cont.size())
contents.y = contents.cont.size() - 1;
if((long) contents.x < 0) contents.x = 0;
if(contents.x >= contents.cont[contents.y].size())
contents.x = contents.cont[contents.y].size() - 1;
}
void mvrel(contents& contents, long y, long x) {
if(y < 0) mvu(contents,-y);
else mvd(contents, y);
if(x < 0) mvb(contents,-x);
else mvf(contents, x);
}
void mvcol(contents& contents, boost::optional<int> col) {
if(col) {
unsigned int len = contents.cont[contents.y].length();
if(len >= col.get()) {
contents.x = col.get();
contents.waiting_for_desired = false;
} else {
show_message((std::string("Can't move to column: ")
+ int_to_str(col.get())).c_str());
}
} else {
while(true) {
std::string str = prompt("Goto column: ");
try {
int res = std::stoi(str);
mvcol(contents, res);
return;
} catch(std::invalid_argument) {
continue;
}
}
}
}
void mvsot(contents& contents, boost::optional<int> op) {
mvsol(contents, op);
const std::string& str = contents.cont[contents.y];
for(unsigned int i = 0; i < str.length(); i++) {
if(str[i] == ' ' || str[i] == '\t')
mvf(contents, op);
else break;
}
}
void mveol(contents& contents, boost::optional<int>) {
mvcol(contents,contents.cont[contents.y].length() - 1);
}
void mvsol(contents& contents, boost::optional<int>) {
mvcol(contents,0);
}
void mvsop(contents& contents, boost::optional<int>) {
contents.y = 0;
contents.x = 0;
contents.waiting_for_desired = false;
contents.y_offset = 0;
}
void mveop(contents& contents, boost::optional<int>) {
contents.y = contents.cont.size() - 1;
contents.x = 0;
contents.y_offset = contents.y - contents.max_y + 2;
contents.waiting_for_desired = false;
}
void mvd(contents& contents, boost::optional<int> op) {
int times = op ? op.get() : 1;
if(contents.y + times < 0 || contents.y + times >= contents.cont.size()) {
show_message("Can't move to that location (start/end of buffer)");
return;
}
int vis = to_visual(contents.cont[contents.y],contents.x);
contents.y += times;
unsigned int len = contents.cont[contents.y].length();
if(contents.waiting_for_desired) {
if((int)contents.x < 0) {
contents.x = len - 1;
unsigned int vis = from_visual(contents.cont[contents.y],
contents.desired_x);
if(vis < contents.x) {
contents.x = vis;
contents.waiting_for_desired = false;
}
} else if(contents.x >= len) {
contents.x = len - 1;
} else if((contents.desired_x > contents.x
&& contents.desired_x < len)
|| contents.desired_x == 0) {
// x desired len
contents.x = contents.desired_x;
contents.waiting_for_desired = false;
} else {
// x len desired
contents.x = len - 1;
}
} else if(len <= contents.x && len > 0) {
contents.waiting_for_desired = true;
contents.desired_x = contents.x;
contents.x = len - 1;
} else {
int des = contents.x;
contents.x = from_visual(contents.cont[contents.y],vis);
if(len == 0) {
contents.waiting_for_desired = true;
contents.desired_x = des;
}
}
contents.x = (long) contents.x >= 0 ? contents.x : 0;
if(contents.y - contents.y_offset >= contents.max_y)
contents.y_offset = contents.y - contents.y_offset + 1;
if(contents.y < contents.y_offset)
contents.y_offset = contents.y;
}
void mvu(contents& contents, boost::optional<int> op) {
if(op) mvd(contents,-op.get());
else mvd(contents,-1);
}
inline static bool isDeliminator(char ch) {
return std::find(DELIMINATORS.begin(), DELIMINATORS.end(), ch)
!= DELIMINATORS.end();
}
inline static bool isWhitespace(char ch) {
static const std::locale loc;
return std::isspace(ch, loc);
}
void mvfw(contents& contents, boost::optional<int> op) {
if(op && op.get() < 0) return mvbw(contents, op.get() * -1);
int num = op ? op.get() : 1;
if(num == 0 || num == -0) return;
if(num < 0) return mvbw(contents, -op.get());
//if deliminator then move forward until not deliminator then move over whitespace
//else move foward until (whitespace -> move till not whitespace) or (deliminator -> stop)
#define boundsCheck if(contents.y >= contents.cont.size() || \
(contents.y == contents.cont.size() - 1 && \
contents.x >= contents.cont[contents.y].size())) return;
#define ch contents.cont[contents.y][contents.x]
if(isDeliminator(ch)) {
do {
mvf(contents);
boundsCheck;
} while(isDeliminator(ch));
while(isWhitespace(ch)) {
mvf(contents);
boundsCheck;
}
} else {
while(!isDeliminator(ch) and !isWhitespace(ch)) {
mvf(contents);
boundsCheck;
}
if(isWhitespace(ch)) {
while(isWhitespace(ch)) {
mvf(contents);
boundsCheck;
}
} else {
while(isDeliminator(ch)) {
mvf(contents);
boundsCheck;
}
}
}
#undef boundsCheck
if(num > 0) mvfw(contents,num - 1);
}
void mvfeow(contents& contents, boost::optional<int> op) {
//move at least one forward
//move over non deliminators
//move over deliminators
}
void mvbw(contents& contents, boost::optional<int> op) {
//move back one then
//if delimitor then move back until no delimitor
//else if whitespace then move back until not whitespace then
// move back consistently over delimitors or word chars
//else /*word char*/ move back until not word char or
// whitespace
//move forward one
}
inline static unsigned int fixLen(unsigned int len) {
return len ? len : 1;
}
void mvf(contents& contents, boost::optional<int> op) {
int times = op ? op.get() : 1;
long newx = contents.x + times;
try {
while(fixLen(contents.cont.at(contents.y).length()) <= newx) {
newx -= fixLen(contents.cont[contents.y].length());
contents.y++;
}
} catch(...) { }
if(contents.y >= contents.cont.size()) contents.y = contents.cont.size() - 1;
if(contents.x < 0) contents.x = 0;
else contents.x = newx;
contents.waiting_for_desired = false;
}
void mvb(contents& contents, boost::optional<int> op) {
int times = op ? op.get() : 1;
if(contents.y == 0 && contents.x == 0) return;
long newx = contents.x - times;
try {
while(newx < 0) {
contents.y--;
newx += fixLen(contents.cont.at(contents.y).length());
}
} catch(...) { }
if(newx < 0) contents.x = 0;
else contents.x = newx;
contents.waiting_for_desired = false;
}
<|endoftext|> |
<commit_before>/**
* @file UvUtils.cpp
* @brief uvpp miscellaneous utilities.
* @author zer0
* @date 2017-05-27
*/
#include <libtbag/uvpp/UvUtils.hpp>
#include <libtbag/string/StringUtils.hpp>
#include <libtbag/log/Log.hpp>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <uv.h>
// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------
namespace uvpp {
char ** setupArgs(int argc, char ** argv)
{
return ::uv_setup_args(argc, argv);
}
std::string getProcessTitle()
{
std::size_t const BUFFER_SIZE = 256;
char buffer[BUFFER_SIZE] = {0,};
// If buffer is NULL or size is zero, UV_EINVAL is returned.
// If size cannot accommodate the process title and terminating NULL character,
// the function returns UV_ENOBUFS.
int const CODE = ::uv_get_process_title(buffer, BUFFER_SIZE);
if (CODE != 0) {
tDLogE("getProcessTitle() {} error", getUvErrorName(CODE));
return std::string();
}
return std::string(buffer);
}
void setProcessTitle(std::string const & title)
{
// On platforms with a fixed size buffer for the process title
// the contents of title will be copied to the buffer
// and truncated if larger than the available space.
// Other platforms will return UV_ENOMEM if they cannot allocate
// enough space to duplicate the contents of title.
int const CODE = ::uv_set_process_title(title.c_str());
if (CODE != 0) {
tDLogE("setProcessTitle() {} error", getUvErrorName(CODE));
}
}
std::size_t getResidentSetMemory()
{
std::size_t rss = 0;
int const CODE = ::uv_resident_set_memory(&rss);
if (CODE != 0) {
tDLogE("getResidentSetMemory() {} error", getUvErrorName(CODE));
}
return rss;
}
double getUptime()
{
double uptime = 0.0f;
int const CODE = ::uv_uptime(&uptime);
if (CODE != 0) {
tDLogE("getUptime() {} error", getUvErrorName(CODE));
}
return uptime;
}
ResourceUsage getResourceUsage()
{
uv_rusage_t rusage = {0,};
int const CODE = ::uv_getrusage(&rusage);
if (CODE != 0) {
tDLogE("getResourceUsage() {} error", getUvErrorName(CODE));
}
ResourceUsage result;
result.utime.sec = rusage.ru_utime.tv_sec;
result.utime.usec = rusage.ru_utime.tv_usec;
result.stime.sec = rusage.ru_stime.tv_sec;
result.stime.usec = rusage.ru_stime.tv_usec;
result.maxrss = rusage.ru_maxrss;
result.ixrss = rusage.ru_ixrss;
result.idrss = rusage.ru_idrss;
result.isrss = rusage.ru_isrss;
result.minflt = rusage.ru_minflt;
result.majflt = rusage.ru_majflt;
result.nswap = rusage.ru_nswap;
result.inblock = rusage.ru_inblock;
result.oublock = rusage.ru_oublock;
result.msgsnd = rusage.ru_msgsnd;
result.msgrcv = rusage.ru_msgrcv;
result.nsignals = rusage.ru_nsignals;
result.nvcsw = rusage.ru_nvcsw;
result.nivcsw = rusage.ru_nivcsw;
return result;
}
std::vector<CpuInfo> getCpuInfos()
{
uv_cpu_info_t * infos = nullptr;
int count = 0;
// Gets information about the CPUs on the system.
// The cpu_infos array will have count elements and needs to be freed with uv_free_cpu_info().
int const CODE = ::uv_cpu_info(&infos, &count);
if (convertUvErrorToErrWithLogging("getCpuInfos()", CODE) != E_SUCCESS) {
return std::vector<CpuInfo>();
}
assert(count > 0);
std::vector<CpuInfo> result(static_cast<std::size_t>(count));
uv_cpu_info_t * cursor = infos;
for (int i = 0; i < count; ++i, ++cursor) {
result[i].model.assign(cursor->model);
result[i].speed = cursor->speed;
result[i].times.user = cursor->cpu_times.user;
result[i].times.nice = cursor->cpu_times.nice;
result[i].times.sys = cursor->cpu_times.sys ;
result[i].times.idle = cursor->cpu_times.idle;
result[i].times.irq = cursor->cpu_times.irq ;
}
// Frees the cpu_infos array previously allocated with uv_cpu_info().
::uv_free_cpu_info(infos, count);
return result;
}
std::vector<InterfaceAddress> getInterfaceAddresses()
{
uv_interface_address_t * infos = nullptr;
int count = 0;
// Gets address information about the network interfaces on the system.
// An array of count elements is allocated and returned in addresses.
// It must be freed by the user, calling uv_free_interface_addresses().
int const CODE = uv_interface_addresses(&infos, &count);
if (convertUvErrorToErrWithLogging("getInterfaceAddresses()", CODE) != E_SUCCESS) {
return std::vector<InterfaceAddress>();
}
assert(count >= 0);
std::vector<InterfaceAddress> result(static_cast<std::size_t>(count));
uv_interface_address_t * cursor = infos;
for (int i = 0; i < count; ++i, ++cursor) {
result[i].name.assign(cursor->name);
static_assert(PHYSICAL_ADDRESS_SIZE == sizeof(cursor->phys_addr),
"The sizes of PHYSICAL_ADDRESS_SIZE and uv_interface_address_s.phys_addr should be the same.");
for (int pi = 0; pi < result[i].physical_address.max_size(); ++pi) {
result[i].physical_address[pi] = cursor->phys_addr[pi];
}
result[i].is_internal = (cursor->is_internal != 0 ? true : false);
static_assert(sizeof(result[i].address) == sizeof(cursor->address),
"The sizes of InterfaceAddress.address and uv_interface_address_s.address should be the same.");
static_assert(sizeof(result[i].netmask) == sizeof(cursor->netmask),
"The sizes of InterfaceAddress.netmask and uv_interface_address_s.netmask should be the same.");
static_assert(sizeof(SocketAddress) == sizeof(cursor->address) && sizeof(SocketAddress) == sizeof(cursor->netmask),
"The sizes of SocketAddress and address and netmask should be the same.");
::memcpy(&result[i].address, &cursor->address, sizeof(cursor->address));
::memcpy(&result[i].netmask, &cursor->netmask, sizeof(cursor->netmask));
assert(result[i].address.in4.sin_family == result[i].address.in6.sin6_family);
assert(result[i].netmask.in4.sin_family == result[i].netmask.in6.sin6_family);
}
// Free an array of uv_interface_address_t which was returned by uv_interface_addresses().
::uv_free_interface_addresses(infos, count);
return result;
}
std::string convertPhysicalToString(PhysicalAddress const & physical)
{
std::vector<uint8_t> const BUFFER(physical.begin(), physical.end());
return string::convertByteVectorToHexString(BUFFER, std::string(), std::string(":"));
}
void changeDirectory(std::string const & dir)
{
int const CODE = ::uv_chdir(dir.c_str());
if (CODE != 0) {
tDLogE("changeDirectory() {} error", getUvErrorName(CODE));
}
}
std::vector<double> getLoadAverage()
{
std::size_t const SIZE = 3;
double avg[SIZE] = {0,};
::uv_loadavg(avg);
return std::vector<double>({avg[0], avg[1], avg[2]});
}
Password getPassword()
{
// The populated data includes the username, euid, gid, shell, and home directory.
// On non-Windows systems, all data comes from getpwuid_r(3).
// On Windows, uid and gid are set to -1 and have no meaning, and shell is NULL.
// After successfully calling this function,
// the memory allocated to pwd needs to be freed with uv_os_free_passwd().
uv_passwd_t pwd = {0,};
int const CODE = ::uv_os_get_passwd(&pwd);
if (CODE != 0) {
tDLogE("getPassword() {} error", getUvErrorName(CODE));
return Password{};
}
Password result;
if (pwd.username != nullptr) {
result.username.assign(pwd.username);
}
if (pwd.shell != nullptr) {
result.shell.assign(pwd.shell);
}
if (pwd.homedir != nullptr) {
result.homedir.assign(pwd.homedir);
}
result.uid = pwd.uid;
result.gid = pwd.gid;
// Frees the pwd memory previously allocated with uv_os_get_passwd().
::uv_os_free_passwd(&pwd);
return result;
}
uint64_t getTotalMemory()
{
return ::uv_get_total_memory();
}
uint64_t getHighResolutionTime()
{
// It is relative to an arbitrary time in the past.
// It is not related to the time of day and therefore not subject to clock drift.
// The primary use is for measuring performance between intervals.
//
// Not every platform can support nanosecond resolution;
// however, this value will always be in nanoseconds.
return ::uv_hrtime();
}
Err getEnv(std::string const & name, std::string & value)
{
char * env_value = ::getenv(name.c_str());
if (env_value != nullptr) {
value = std::string(env_value);
return E_SUCCESS;
}
return E_ENFOUND;
}
Err setEnv(std::string const & name, std::string const & value)
{
tDLogE("setEnv() Function not implemented.");
return E_ENOSYS;
}
Err unsetEnv(std::string const & name)
{
tDLogE("unsetEnv() Function not implemented.");
return E_ENOSYS;
}
std::string getHostName()
{
tDLogE("getHostName() Function not implemented.");
return std::string();
}
} // namespace uvpp
// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------
<commit_msg>Implementation of environment variables related features in the UvUtils package.<commit_after>/**
* @file UvUtils.cpp
* @brief uvpp miscellaneous utilities.
* @author zer0
* @date 2017-05-27
*/
#include <libtbag/uvpp/UvUtils.hpp>
#include <libtbag/string/StringUtils.hpp>
#include <libtbag/log/Log.hpp>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <uv.h>
// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------
namespace uvpp {
char ** setupArgs(int argc, char ** argv)
{
return ::uv_setup_args(argc, argv);
}
std::string getProcessTitle()
{
std::size_t const BUFFER_SIZE = 256;
char buffer[BUFFER_SIZE] = {0,};
// If buffer is NULL or size is zero, UV_EINVAL is returned.
// If size cannot accommodate the process title and terminating NULL character,
// the function returns UV_ENOBUFS.
int const CODE = ::uv_get_process_title(buffer, BUFFER_SIZE);
if (CODE != 0) {
tDLogE("getProcessTitle() {} error", getUvErrorName(CODE));
return std::string();
}
return std::string(buffer);
}
void setProcessTitle(std::string const & title)
{
// On platforms with a fixed size buffer for the process title
// the contents of title will be copied to the buffer
// and truncated if larger than the available space.
// Other platforms will return UV_ENOMEM if they cannot allocate
// enough space to duplicate the contents of title.
int const CODE = ::uv_set_process_title(title.c_str());
if (CODE != 0) {
tDLogE("setProcessTitle() {} error", getUvErrorName(CODE));
}
}
std::size_t getResidentSetMemory()
{
std::size_t rss = 0;
int const CODE = ::uv_resident_set_memory(&rss);
if (CODE != 0) {
tDLogE("getResidentSetMemory() {} error", getUvErrorName(CODE));
}
return rss;
}
double getUptime()
{
double uptime = 0.0f;
int const CODE = ::uv_uptime(&uptime);
if (CODE != 0) {
tDLogE("getUptime() {} error", getUvErrorName(CODE));
}
return uptime;
}
ResourceUsage getResourceUsage()
{
uv_rusage_t rusage = {0,};
int const CODE = ::uv_getrusage(&rusage);
if (CODE != 0) {
tDLogE("getResourceUsage() {} error", getUvErrorName(CODE));
}
ResourceUsage result;
result.utime.sec = rusage.ru_utime.tv_sec;
result.utime.usec = rusage.ru_utime.tv_usec;
result.stime.sec = rusage.ru_stime.tv_sec;
result.stime.usec = rusage.ru_stime.tv_usec;
result.maxrss = rusage.ru_maxrss;
result.ixrss = rusage.ru_ixrss;
result.idrss = rusage.ru_idrss;
result.isrss = rusage.ru_isrss;
result.minflt = rusage.ru_minflt;
result.majflt = rusage.ru_majflt;
result.nswap = rusage.ru_nswap;
result.inblock = rusage.ru_inblock;
result.oublock = rusage.ru_oublock;
result.msgsnd = rusage.ru_msgsnd;
result.msgrcv = rusage.ru_msgrcv;
result.nsignals = rusage.ru_nsignals;
result.nvcsw = rusage.ru_nvcsw;
result.nivcsw = rusage.ru_nivcsw;
return result;
}
std::vector<CpuInfo> getCpuInfos()
{
uv_cpu_info_t * infos = nullptr;
int count = 0;
// Gets information about the CPUs on the system.
// The cpu_infos array will have count elements and needs to be freed with uv_free_cpu_info().
int const CODE = ::uv_cpu_info(&infos, &count);
if (convertUvErrorToErrWithLogging("getCpuInfos()", CODE) != E_SUCCESS) {
return std::vector<CpuInfo>();
}
assert(count > 0);
std::vector<CpuInfo> result(static_cast<std::size_t>(count));
uv_cpu_info_t * cursor = infos;
for (int i = 0; i < count; ++i, ++cursor) {
result[i].model.assign(cursor->model);
result[i].speed = cursor->speed;
result[i].times.user = cursor->cpu_times.user;
result[i].times.nice = cursor->cpu_times.nice;
result[i].times.sys = cursor->cpu_times.sys ;
result[i].times.idle = cursor->cpu_times.idle;
result[i].times.irq = cursor->cpu_times.irq ;
}
// Frees the cpu_infos array previously allocated with uv_cpu_info().
::uv_free_cpu_info(infos, count);
return result;
}
std::vector<InterfaceAddress> getInterfaceAddresses()
{
uv_interface_address_t * infos = nullptr;
int count = 0;
// Gets address information about the network interfaces on the system.
// An array of count elements is allocated and returned in addresses.
// It must be freed by the user, calling uv_free_interface_addresses().
int const CODE = uv_interface_addresses(&infos, &count);
if (convertUvErrorToErrWithLogging("getInterfaceAddresses()", CODE) != E_SUCCESS) {
return std::vector<InterfaceAddress>();
}
assert(count >= 0);
std::vector<InterfaceAddress> result(static_cast<std::size_t>(count));
uv_interface_address_t * cursor = infos;
for (int i = 0; i < count; ++i, ++cursor) {
result[i].name.assign(cursor->name);
static_assert(PHYSICAL_ADDRESS_SIZE == sizeof(cursor->phys_addr),
"The sizes of PHYSICAL_ADDRESS_SIZE and uv_interface_address_s.phys_addr should be the same.");
for (int pi = 0; pi < result[i].physical_address.max_size(); ++pi) {
result[i].physical_address[pi] = cursor->phys_addr[pi];
}
result[i].is_internal = (cursor->is_internal != 0 ? true : false);
static_assert(sizeof(result[i].address) == sizeof(cursor->address),
"The sizes of InterfaceAddress.address and uv_interface_address_s.address should be the same.");
static_assert(sizeof(result[i].netmask) == sizeof(cursor->netmask),
"The sizes of InterfaceAddress.netmask and uv_interface_address_s.netmask should be the same.");
static_assert(sizeof(SocketAddress) == sizeof(cursor->address) && sizeof(SocketAddress) == sizeof(cursor->netmask),
"The sizes of SocketAddress and address and netmask should be the same.");
::memcpy(&result[i].address, &cursor->address, sizeof(cursor->address));
::memcpy(&result[i].netmask, &cursor->netmask, sizeof(cursor->netmask));
assert(result[i].address.in4.sin_family == result[i].address.in6.sin6_family);
assert(result[i].netmask.in4.sin_family == result[i].netmask.in6.sin6_family);
}
// Free an array of uv_interface_address_t which was returned by uv_interface_addresses().
::uv_free_interface_addresses(infos, count);
return result;
}
std::string convertPhysicalToString(PhysicalAddress const & physical)
{
std::vector<uint8_t> const BUFFER(physical.begin(), physical.end());
return libtbag::string::convertByteVectorToHexString(BUFFER, std::string(), std::string(":"));
}
void changeDirectory(std::string const & dir)
{
int const CODE = ::uv_chdir(dir.c_str());
if (CODE != 0) {
tDLogE("changeDirectory() {} error", getUvErrorName(CODE));
}
}
std::vector<double> getLoadAverage()
{
std::size_t const SIZE = 3;
double avg[SIZE] = {0,};
::uv_loadavg(avg);
return std::vector<double>({avg[0], avg[1], avg[2]});
}
Password getPassword()
{
// The populated data includes the username, euid, gid, shell, and home directory.
// On non-Windows systems, all data comes from getpwuid_r(3).
// On Windows, uid and gid are set to -1 and have no meaning, and shell is NULL.
// After successfully calling this function,
// the memory allocated to pwd needs to be freed with uv_os_free_passwd().
uv_passwd_t pwd = {0,};
int const CODE = ::uv_os_get_passwd(&pwd);
if (CODE != 0) {
tDLogE("getPassword() {} error", getUvErrorName(CODE));
return Password{};
}
Password result;
if (pwd.username != nullptr) {
result.username.assign(pwd.username);
}
if (pwd.shell != nullptr) {
result.shell.assign(pwd.shell);
}
if (pwd.homedir != nullptr) {
result.homedir.assign(pwd.homedir);
}
result.uid = pwd.uid;
result.gid = pwd.gid;
// Frees the pwd memory previously allocated with uv_os_get_passwd().
::uv_os_free_passwd(&pwd);
return result;
}
uint64_t getTotalMemory()
{
return ::uv_get_total_memory();
}
uint64_t getHighResolutionTime()
{
// It is relative to an arbitrary time in the past.
// It is not related to the time of day and therefore not subject to clock drift.
// The primary use is for measuring performance between intervals.
//
// Not every platform can support nanosecond resolution;
// however, this value will always be in nanoseconds.
return ::uv_hrtime();
}
Err getEnv(std::string const & name, std::string & value)
{
#if (UV_VERSION_MAJOR >= 1) && (UV_VERSION_MINOR >= 12)
std::size_t size = 0;
int code = ::uv_os_getenv(name.c_str(), nullptr, &size);
if (code != UV_ENOBUFS) {
return libtbag::convertUvErrorToErr(code);
}
assert(size >= 1);
assert(code == UV_ENOBUFS);
std::vector<char> buffer(size);
code = ::uv_os_getenv(name.c_str(), &value[0], &size);
if (code == 0) {
value = std::string(&buffer[0]);
return E_SUCCESS;
}
return libtbag::convertUvErrorToErr(code);
#else
char * env_value = ::getenv(name.c_str());
if (env_value != nullptr) {
value = std::string(env_value);
return E_SUCCESS;
}
return E_ENFOUND;
#endif
}
Err setEnv(std::string const & name, std::string const & value)
{
#if (UV_VERSION_MAJOR >= 1) && (UV_VERSION_MINOR >= 12)
return libtbag::convertUvErrorToErr(::uv_os_setenv(name.c_str(), value.c_str()));
#else
tDLogE("setEnv() Function not implemented.");
return E_ENOSYS;
#endif
}
Err unsetEnv(std::string const & name)
{
#if (UV_VERSION_MAJOR >= 1) && (UV_VERSION_MINOR >= 12)
return libtbag::convertUvErrorToErr(::uv_os_unsetenv(name.c_str()));
#else
tDLogE("unsetEnv() Function not implemented.");
return E_ENOSYS;
#endif
}
std::string getHostName()
{
#if (UV_VERSION_MAJOR >= 1) && (UV_VERSION_MINOR >= 16)
char buffer[UV_MAXHOSTNAMESIZE] = {0,};
std::size_t size = UV_MAXHOSTNAMESIZE;
int const CODE = ::uv_os_gethostname(buffer, &size);
if (CODE == 0) {
return std::string(&buffer[0]);
}
return std::string();
#elif (UV_VERSION_MAJOR >= 1) && (UV_VERSION_MINOR >= 12)
std::size_t size = 0;
int code = ::uv_os_gethostname(nullptr, &size);
if (code != UV_ENOBUFS) {
return std::string();
}
assert(size >= 1);
assert(code == UV_ENOBUFS);
std::vector<char> buffer(size);
code = ::uv_os_gethostname(&buffer[0], &size);
if (code == 0) {
return std::string(&buffer[0]);
}
return std::string();
#else
tDLogE("getHostName() Function not implemented.");
return std::string();
#endif
}
} // namespace uvpp
// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------
<|endoftext|> |
<commit_before>#include "mutation.h"
#include "editdistance.h"
#include <iostream>
#include <fstream>
#include "util.h"
#include <string.h>
#include "builtinmutation.h"
#include <sstream>
#include "globalsettings.h"
Mutation::Mutation(string name, string left, string center, string right){
//we shift some bases from left and right to center to require 100% match of these bases
mShift = 2;
mLeft = left.substr(0, left.length()-mShift);
mCenter = left.substr(left.length()-mShift, mShift) + center + right.substr(0, mShift);
mRight = right.substr(mShift, right.length()-mShift);
mPattern = left + center + right;
mName = name;
}
Match* Mutation::searchInRead(Read* r, int distanceReq, int qualReq){
char phredQualReq= (char)(qualReq + 33);
int readLen = r->mSeq.length();
int lLen = mLeft.length();
int cLen = mCenter.length();
int rLen = mRight.length();
int pLen = mPattern.length();
string seq = r->mSeq.mStr;
const char* seqData = seq.c_str();
const char* centerData = mCenter.c_str();
const char* patternData = mPattern.c_str();
const char* qualData = r->mQuality.c_str();
// we should ignore the mutations in the exact edge since there usualy exists errors
const int margin = 0;
for(int start = margin; start + cLen + margin <= readLen; start++){
int lComp = min(start, lLen);
// check string identity in a fast way
bool identical = true;
for (int i=0;i<cLen;i++){
if (seqData[start + i] != centerData[i]){
identical = false;
break;
}
}
if(!identical)
continue;
// check quality in a fast way
bool qualityPassed = true;
for (int i=mShift; i<cLen-mShift; i++){
if (qualData[start + i] < phredQualReq){
qualityPassed = false;
break;
}
}
if(!qualityPassed)
continue;
int edLen = min(pLen - (lLen - lComp), readLen - (start - lComp));
// too short
if(edLen < 15)
continue;
int ed = edit_distance(seqData + start - lComp, edLen, patternData + lLen - lComp, edLen);
if ( ed <= distanceReq){
return new Match(r, start, ed);
}
}
return NULL;
}
vector<Mutation> Mutation::parseCsv(string filename) {
ifstream file;
file.open(filename.c_str(), ifstream::in);
const int maxLine = 1000;
char line[maxLine];
vector<Mutation> mutations;
while(file.getline(line, maxLine)){
// trim \n, \r or \r\n in the tail
int readed = strlen(line);
if(readed >=2 ){
if(line[readed-1] == '\n' || line[readed-1] == '\r'){
line[readed-1] = '\0';
if(line[readed-2] == '\r')
line[readed-2] = '\0';
}
}
string linestr(line);
vector<string> splitted;
split(linestr, splitted, ",");
// a valid line need 4 columns: name, left, center, right
if(splitted.size()<4)
continue;
// comment line
if(starts_with(splitted[0], "#"))
continue;
string name = trim(splitted[0]);
string left = trim(splitted[1]);
string center = trim(splitted[2]);
string right = trim(splitted[3]);
Mutation mut(name, left, center, right);
if(left.length()<10){
cerr << "WARNING: skip following mutation since its left part < 10bp"<<endl<<"\t";
mut.print();
}
else if(right.length()<10){
cerr << "WARNING: skip following mutation since its right part < 10bp"<<endl<<"\t";
mut.print();
}
else if(left.length() + center.length() + right.length() < 30){
cerr << "WARNING: skip following mutation since its (left+center+right) < 30bp"<<endl<<"\t";
mut.print();
}
else {
mutations.push_back(mut);
}
}
file.close();
if(mutations.size() <= 0){
cerr<<"No mutation will be scanned"<<endl;
}
return mutations;
}
vector<Mutation> Mutation::parseBuiltIn() {
vector<Mutation> mutations;
vector<string> lines;
split(BUILT_IN_MUTATIONS, lines, "\n");
for(int i=0;i<lines.size();i++){
string linestr = lines[i];
vector<string> splitted;
split(linestr, splitted, ",");
// a valid line need 4 columns: name, left, center, right
if(splitted.size()<4)
continue;
// comment line
if(starts_with(splitted[0], "#"))
continue;
string name = trim(splitted[0]);
string left = trim(splitted[1]);
string center = trim(splitted[2]);
string right = trim(splitted[3]);
Mutation mut(name, left, center, right);
mutations.push_back(mut);
}
if(mutations.size() <= 0){
cerr<<"No mutation will be scanned"<<endl;
}
return mutations;
}
vector<Mutation> Mutation::parseVcf(string vcfFile, string refFile) {
vector<Mutation> mutations;
VcfReader vr(vcfFile);
vr.readAll();
vector<Variant> variants = vr.variants();
bool markedOnly = GlobalSettings::markedOnlyForVCF;
const int vcfMax = 100;
if(variants.size() > vcfMax && markedOnly==false){
cerr<<"Your VCF has more than "<<vcfMax<<" records, this will make MutScan take too long to complete the scan." << endl;
cerr<<"Please use a smaller VCF"<<endl;
cerr<<"Or use --mark option, and mark the wanted VCF records with FILTER column as M"<<endl;
cerr<<"Example (note the M in the FILTER column):"<<endl;
cerr<<"#CHROM POS ID REF ALT QUAL FILTER INFO"<<endl;
cerr<<"1 69224 COSM3677745 A C . M This record will be scanned"<<endl;
cerr<<"1 880950 COSM3493111 G A . . This record will be skipped"<<endl;
cerr<<endl;
exit(-1);
}
FastaReader fr(refFile);
fr.readAll();
map<string, string> ref = fr.contigs();
for(int i=0;i<variants.size();i++) {
Variant& v = variants[i];
// skip the unmasked if markedOnly flag is set true
if(markedOnly && (v.filter!="m" && v.filter!="M"))
continue;
string chrom = v.chrom;
if(!starts_with(chrom, "chr"))
chrom = "chr" + chrom;
// the contig is not in reference
if(ref.count(chrom) == 0)
continue;
// the variant is out of this contig, or in the front or tail
// note that VCF is 1-based, and string is 0-based
if(v.pos > ref[chrom].length() + 25 + 1 || v.pos < 25 + 1)
continue;
string gene = v.gene();
string aa = v.aaChange();
string cds = v.cdsChange();
stringstream ss;
if(gene!="")
ss<<gene<<"_";
if(aa!="")
ss<<aa<<"_";
if(cds!="")
ss<<cds<<"_";
ss<<chrom<<"_"<<v.pos<<"_"<<v.ref<<">"<<v.alt;
string name = ss.str();
string left = ref[chrom].substr(v.pos-25-1, 25);
string center = v.alt;
string right = ref[chrom].substr(v.pos+v.ref.length()-1, 25);
Mutation mut(name, left, center, right);
cerr << name << ", " << left << ", " << center << ", " << right << endl;
mutations.push_back(mut);
}
if(mutations.size() <= 0){
cerr<<"No mutation will be scanned"<<endl;
if(markedOnly){
cerr<<"You are using --mark option, you should mark the wanted VCF records with FILTER as M"<<endl;
cerr<<"Example (note the M in the FILTER column):"<<endl;
cerr<<"#CHROM POS ID REF ALT QUAL FILTER INFO"<<endl;
cerr<<"1 69224 COSM3677745 A C . M This record will be scanned"<<endl;
cerr<<"1 880950 COSM3493111 G A . . This record will be skipped"<<endl;
} else {
cerr<<"Your VCF contains no valid records"<<endl;
}
cerr<<endl;
exit(-1);
}
return mutations;
}
void Mutation::print(){
cout<<mName<<" "<<mLeft<<" "<<mCenter<<" "<<mRight<<endl;
}
void Mutation::printHtml(ofstream& file){
file<<mName<<" "<<mLeft<<" "<<mCenter<<" "<<mRight;
}
<commit_msg>support with or without chr in VCF<commit_after>#include "mutation.h"
#include "editdistance.h"
#include <iostream>
#include <fstream>
#include "util.h"
#include <string.h>
#include "builtinmutation.h"
#include <sstream>
#include "globalsettings.h"
Mutation::Mutation(string name, string left, string center, string right){
//we shift some bases from left and right to center to require 100% match of these bases
mShift = 2;
mLeft = left.substr(0, left.length()-mShift);
mCenter = left.substr(left.length()-mShift, mShift) + center + right.substr(0, mShift);
mRight = right.substr(mShift, right.length()-mShift);
mPattern = left + center + right;
mName = name;
}
Match* Mutation::searchInRead(Read* r, int distanceReq, int qualReq){
char phredQualReq= (char)(qualReq + 33);
int readLen = r->mSeq.length();
int lLen = mLeft.length();
int cLen = mCenter.length();
int rLen = mRight.length();
int pLen = mPattern.length();
string seq = r->mSeq.mStr;
const char* seqData = seq.c_str();
const char* centerData = mCenter.c_str();
const char* patternData = mPattern.c_str();
const char* qualData = r->mQuality.c_str();
// we should ignore the mutations in the exact edge since there usualy exists errors
const int margin = 0;
for(int start = margin; start + cLen + margin <= readLen; start++){
int lComp = min(start, lLen);
// check string identity in a fast way
bool identical = true;
for (int i=0;i<cLen;i++){
if (seqData[start + i] != centerData[i]){
identical = false;
break;
}
}
if(!identical)
continue;
// check quality in a fast way
bool qualityPassed = true;
for (int i=mShift; i<cLen-mShift; i++){
if (qualData[start + i] < phredQualReq){
qualityPassed = false;
break;
}
}
if(!qualityPassed)
continue;
int edLen = min(pLen - (lLen - lComp), readLen - (start - lComp));
// too short
if(edLen < 15)
continue;
int ed = edit_distance(seqData + start - lComp, edLen, patternData + lLen - lComp, edLen);
if ( ed <= distanceReq){
return new Match(r, start, ed);
}
}
return NULL;
}
vector<Mutation> Mutation::parseCsv(string filename) {
ifstream file;
file.open(filename.c_str(), ifstream::in);
const int maxLine = 1000;
char line[maxLine];
vector<Mutation> mutations;
while(file.getline(line, maxLine)){
// trim \n, \r or \r\n in the tail
int readed = strlen(line);
if(readed >=2 ){
if(line[readed-1] == '\n' || line[readed-1] == '\r'){
line[readed-1] = '\0';
if(line[readed-2] == '\r')
line[readed-2] = '\0';
}
}
string linestr(line);
vector<string> splitted;
split(linestr, splitted, ",");
// a valid line need 4 columns: name, left, center, right
if(splitted.size()<4)
continue;
// comment line
if(starts_with(splitted[0], "#"))
continue;
string name = trim(splitted[0]);
string left = trim(splitted[1]);
string center = trim(splitted[2]);
string right = trim(splitted[3]);
Mutation mut(name, left, center, right);
if(left.length()<10){
cerr << "WARNING: skip following mutation since its left part < 10bp"<<endl<<"\t";
mut.print();
}
else if(right.length()<10){
cerr << "WARNING: skip following mutation since its right part < 10bp"<<endl<<"\t";
mut.print();
}
else if(left.length() + center.length() + right.length() < 30){
cerr << "WARNING: skip following mutation since its (left+center+right) < 30bp"<<endl<<"\t";
mut.print();
}
else {
mutations.push_back(mut);
}
}
file.close();
if(mutations.size() <= 0){
cerr<<"No mutation will be scanned"<<endl;
}
return mutations;
}
vector<Mutation> Mutation::parseBuiltIn() {
vector<Mutation> mutations;
vector<string> lines;
split(BUILT_IN_MUTATIONS, lines, "\n");
for(int i=0;i<lines.size();i++){
string linestr = lines[i];
vector<string> splitted;
split(linestr, splitted, ",");
// a valid line need 4 columns: name, left, center, right
if(splitted.size()<4)
continue;
// comment line
if(starts_with(splitted[0], "#"))
continue;
string name = trim(splitted[0]);
string left = trim(splitted[1]);
string center = trim(splitted[2]);
string right = trim(splitted[3]);
Mutation mut(name, left, center, right);
mutations.push_back(mut);
}
if(mutations.size() <= 0){
cerr<<"No mutation will be scanned"<<endl;
}
return mutations;
}
vector<Mutation> Mutation::parseVcf(string vcfFile, string refFile) {
vector<Mutation> mutations;
VcfReader vr(vcfFile);
vr.readAll();
vector<Variant> variants = vr.variants();
bool markedOnly = GlobalSettings::markedOnlyForVCF;
const int vcfMax = 100;
if(variants.size() > vcfMax && markedOnly==false){
cerr<<"Your VCF has more than "<<vcfMax<<" records, this will make MutScan take too long to complete the scan." << endl;
cerr<<"Please use a smaller VCF"<<endl;
cerr<<"Or use --mark option, and mark the wanted VCF records with FILTER column as M"<<endl;
cerr<<"Example (note the M in the FILTER column):"<<endl;
cerr<<"#CHROM POS ID REF ALT QUAL FILTER INFO"<<endl;
cerr<<"1 69224 COSM3677745 A C . M This record will be scanned"<<endl;
cerr<<"1 880950 COSM3493111 G A . . This record will be skipped"<<endl;
cerr<<endl;
exit(-1);
}
FastaReader fr(refFile);
fr.readAll();
map<string, string> ref = fr.contigs();
for(int i=0;i<variants.size();i++) {
Variant& v = variants[i];
// skip the unmasked if markedOnly flag is set true
if(markedOnly && (v.filter!="m" && v.filter!="M"))
continue;
string chrom = v.chrom;
// the contig is not in reference
if(ref.count(chrom) == 0){
// add or remove chr to match the reference
if(!starts_with(chrom, "chr"))
chrom = "chr" + chrom;
else
chrom = chrom.substr(3, chrom.length()-3);
if(ref.count(chrom) == 0)
continue;
}
// the variant is out of this contig, or in the front or tail
// note that VCF is 1-based, and string is 0-based
if(v.pos > ref[chrom].length() + 25 + 1 || v.pos < 25 + 1)
continue;
string gene = v.gene();
string aa = v.aaChange();
string cds = v.cdsChange();
stringstream ss;
if(gene!="")
ss<<gene<<"_";
if(aa!="")
ss<<aa<<"_";
if(cds!="")
ss<<cds<<"_";
ss<<chrom<<"_"<<v.pos<<"_"<<v.ref<<">"<<v.alt;
string name = ss.str();
string left = ref[chrom].substr(v.pos-25-1, 25);
string center = v.alt;
string right = ref[chrom].substr(v.pos+v.ref.length()-1, 25);
Mutation mut(name, left, center, right);
cerr << name << ", " << left << ", " << center << ", " << right << endl;
mutations.push_back(mut);
}
if(mutations.size() <= 0){
cerr<<"No mutation will be scanned"<<endl;
if(markedOnly){
cerr<<"You are using --mark option, you should mark the wanted VCF records with FILTER as M"<<endl;
cerr<<"Example (note the M in the FILTER column):"<<endl;
cerr<<"#CHROM POS ID REF ALT QUAL FILTER INFO"<<endl;
cerr<<"1 69224 COSM3677745 A C . M This record will be scanned"<<endl;
cerr<<"1 880950 COSM3493111 G A . . This record will be skipped"<<endl;
} else {
cerr<<"Your VCF contains no valid records"<<endl;
}
cerr<<endl;
exit(-1);
}
return mutations;
}
void Mutation::print(){
cout<<mName<<" "<<mLeft<<" "<<mCenter<<" "<<mRight<<endl;
}
void Mutation::printHtml(ofstream& file){
file<<mName<<" "<<mLeft<<" "<<mCenter<<" "<<mRight;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2016 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
// MVF-Core common objects and functions
#include "mvf-core.h"
#include "init.h"
#include "util.h"
#include "chainparams.h"
#include "validationinterface.h"
#include <iostream>
#include <fstream>
#include <boost/filesystem.hpp>
using namespace std;
// version string identifying the consensus-relevant algorithmic changes
// so that a user can quickly see if MVF fork clients are compatible
// for test purposes (since they may diverge during development/testing).
// A new value must be chosen whenever there are changes to consensus
// relevant functionality (excepting things which are parameterized).
// Values are surnames chosen from the name list of space travelers at
// https://en.wikipedia.org/wiki/List_of_space_travelers_by_name
std::string post_fork_consensus_id = "AKIYAMA";
// actual fork height, taking into account user configuration parameters (MVHF-CORE-DES-TRIG-4)
int FinalActivateForkHeight = 0;
// actual fork id, taking into account user configuration parameters (MVHF-CORE-DES-CSIG-1)
int FinalForkId = 0;
// track whether HF has been activated before in previous run (MVHF-CORE-DES-TRIG-5)
// is set at startup based on btcfork.conf presence
bool wasMVFHardForkPreviouslyActivated = false;
// track whether HF is active (MVHF-CORE-DES-TRIG-5)
bool isMVFHardForkActive = false;
// track whether auto wallet backup might still need to be done
// this is set to true at startup if client detects fork already triggered
// otherwise when the backup is made. (MVHF-CORE-DES-WABU-1)
bool fAutoBackupDone = false;
// default suffix to append to wallet filename for auto backup (MVHF-CORE-DES-WABU-1)
std::string autoWalletBackupSuffix = "[email protected]";
/** Add MVF-specific command line options (MVHF-CORE-DES-TRIG-8) */
std::string ForkCmdLineHelp()
{
std::string strUsage;
strUsage += HelpMessageGroup(_("Bitcoin MVF-Core Options:"));
// automatic wallet backup parameters (MVHF-CORE-DES-WABU-1)
strUsage += HelpMessageOpt("-autobackupwalletpath=<path>", _("Automatically backup the wallet to the autobackupwalletfile path after the block specified becomes the best block (-autobackupblock). Default: Enabled"));
strUsage += HelpMessageOpt("-autobackupblock=<n>", _("Specify the block number that triggers the automatic wallet backup. Default: forkheight-1"));
// fork height parameter (MVHF-CORE-DES-TRIG-1)
strUsage += HelpMessageOpt("-forkheight=<n>", strprintf(_("Block height at which to fork on active network (integer). Defaults (also minimums): mainnet:%u,testnet=%u,regtest=%u"), (unsigned)HARDFORK_HEIGHT_MAINNET, (unsigned)HARDFORK_HEIGHT_TESTNET, (unsigned)HARDFORK_HEIGHT_REGTEST));
// fork id (MVHF-CORE-DES-CSIG-1)
strUsage += HelpMessageOpt("-forkid=<n>", strprintf(_("Fork id to use for signature change. Value must be between 0 and %d. Default is 0x%06x (%u)"), (unsigned)MAX_HARDFORK_SIGHASH_ID, (unsigned)HARDFORK_SIGHASH_ID, (unsigned)HARDFORK_SIGHASH_ID));
return strUsage;
}
/** Performs fork-related setup / validation actions when the program starts */
void ForkSetup(const CChainParams& chainparams)
{
int defaultForkHeightForNetwork = 0;
std:string activeNetworkID = chainparams.NetworkIDString();
LogPrintf("%s: MVF: doing setup\n", __func__);
LogPrintf("%s: MVF: consensus version = %s\n", __func__, post_fork_consensus_id);
LogPrintf("%s: MVF: active network = %s\n", __func__, activeNetworkID);
// determine minimum fork height according to network
// (these are set to the same as the default fork heights for now, but could be made different)
if (activeNetworkID == CBaseChainParams::MAIN)
defaultForkHeightForNetwork = HARDFORK_HEIGHT_MAINNET;
else if (activeNetworkID == CBaseChainParams::TESTNET)
defaultForkHeightForNetwork = HARDFORK_HEIGHT_TESTNET;
else if (activeNetworkID == CBaseChainParams::REGTEST)
defaultForkHeightForNetwork = HARDFORK_HEIGHT_REGTEST;
else
throw std::runtime_error(strprintf("%s: Unknown chain %s.", __func__, activeNetworkID));
FinalActivateForkHeight = GetArg("-forkheight", defaultForkHeightForNetwork);
FinalForkId = GetArg("-forkid", HARDFORK_SIGHASH_ID);
// check fork id for validity (MVHF-CORE-DES-CSIG-2)
if (FinalForkId == 0) {
LogPrintf("MVF: Warning: fork id = 0 will result in vulnerability to replay attacks\n");
}
else {
if (FinalForkId < 0 || FinalForkId > MAX_HARDFORK_SIGHASH_ID) {
LogPrintf("MVF: Error: specified fork id (%d) is not in range 0..%u\n", FinalForkId, (unsigned)MAX_HARDFORK_SIGHASH_ID);
StartShutdown();
}
}
if (GetBoolArg("-segwitfork", DEFAULT_TRIGGER_ON_SEGWIT))
LogPrintf("%s: MVF: Segregated Witness trigger is ENABLED\n", __func__);
else
LogPrintf("%s: MVF: Segregated Witness trigger is DISABLED\n", __func__);
LogPrintf("%s: MVF: active fork height = %d\n", __func__, FinalActivateForkHeight);
LogPrintf("%s: MVF: active fork id = 0x%06x (%d)\n", __func__, FinalForkId, FinalForkId);
if (GetBoolArg("-force-retarget", DEFAULT_FORCE_RETARGET))
LogPrintf("%s: MVF: force-retarget is ENABLED\n", __func__);
else
LogPrintf("%s: MVF: force-retarget is DISABLED\n", __func__);
LogPrintf("%s: MVF: auto backup block = %d\n", __func__, GetArg("-autobackupblock", FinalActivateForkHeight - 1));
// check if btcfork.conf exists (MVHF-CORE-DES-TRIG-10)
boost::filesystem::path pathBTCforkConfigFile(BTCFORK_CONF_FILENAME);
if (!pathBTCforkConfigFile.is_complete())
pathBTCforkConfigFile = GetDataDir(false) / pathBTCforkConfigFile;
if (boost::filesystem::exists(pathBTCforkConfigFile)) {
LogPrintf("%s: MVF: found marker config file at %s - client has already forked before\n", __func__, pathBTCforkConfigFile.string().c_str());
wasMVFHardForkPreviouslyActivated = true;
}
else {
LogPrintf("%s: MVF: no marker config file at %s - client has not forked yet\n", __func__, pathBTCforkConfigFile.string().c_str());
wasMVFHardForkPreviouslyActivated = false;
}
// we should always set the activation flag to false during setup
isMVFHardForkActive = false;
}
/** Actions when the fork triggers (MVHF-CORE-DES-TRIG-6) */
// doBackup parameter default is true
void ActivateFork(int actualForkHeight, bool doBackup)
{
LogPrintf("%s: MVF: checking whether to perform fork activation\n", __func__);
if (!isMVFHardForkActive && !wasMVFHardForkPreviouslyActivated) // sanity check to protect the one-off actions
{
LogPrintf("%s: MVF: performing fork activation actions\n", __func__);
// set so that we capture the actual height at which it forked
// because this can be different from user-specified configuration
// (e.g. soft-fork activated)
FinalActivateForkHeight = actualForkHeight;
boost::filesystem::path pathBTCforkConfigFile(BTCFORK_CONF_FILENAME);
if (!pathBTCforkConfigFile.is_complete())
pathBTCforkConfigFile = GetDataDir(false) / pathBTCforkConfigFile;
LogPrintf("%s: MVF: checking for existence of %s\n", __func__, pathBTCforkConfigFile.string().c_str());
// remove btcfork.conf if it already exists - it shall be overwritten
if (boost::filesystem::exists(pathBTCforkConfigFile)) {
LogPrintf("%s: MVF: removing %s\n", __func__, pathBTCforkConfigFile.string().c_str());
try {
boost::filesystem::remove(pathBTCforkConfigFile);
} catch (const boost::filesystem::filesystem_error& e) {
LogPrintf("%s: Unable to remove pidfile: %s\n", __func__, e.what());
}
}
// try to write the btcfork.conf (MVHF-CORE-DES-TRIG-10)
LogPrintf("%s: MVF: writing %s\n", __func__, pathBTCforkConfigFile.string().c_str());
std::ofstream btcforkfile(pathBTCforkConfigFile.string().c_str(), std::ios::out);
btcforkfile << "forkheight=" << FinalActivateForkHeight << "\n";
btcforkfile << "forkid=" << FinalForkId << "\n";
LogPrintf("%s: MVF: active fork height = %d\n", __func__, FinalActivateForkHeight);
LogPrintf("%s: MVF: active fork id = 0x%06x (%d)\n", __func__, FinalForkId, FinalForkId);
// MVF-Core begin MVHF-CORE-DES-WABU-3
// check if we need to do wallet auto backup at fork block
// this is in case of soft-fork triggered activation
// MVF-Core TODO: reduce code duplication between this block and main.cpp:UpdateTip()
if (doBackup && !fAutoBackupDone)
{
std::string strWalletBackupFile = GetArg("-autobackupwalletpath", "");
int BackupBlock = actualForkHeight;
//LogPrintf("MVF DEBUG: autobackupwalletpath=%s\n",strWalletBackupFile);
//LogPrintf("MVF DEBUG: autobackupblock=%d\n",BackupBlock);
if (GetBoolArg("-disablewallet", false))
{
LogPrintf("MVF: -disablewallet and -autobackupwalletpath conflict so automatic backup disabled.");
fAutoBackupDone = true;
}
else {
// Auto Backup defined, but no need to check block height since
// this is fork activation time and we still have not backed up
// so just get on with it
if (GetMainSignals().BackupWalletAuto(strWalletBackupFile, BackupBlock))
fAutoBackupDone = true;
else {
// shutdown in case of wallet backup failure (MVHF-CORE-DES-WABU-5)
// MVF-Core TODO: investigate if this is safe in terms of wallet flushing/closing or if more needs to be done
btcforkfile << "error: unable to perform automatic backup - exiting" << "\n";
btcforkfile.close();
throw std::runtime_error("CWallet::BackupWalletAuto() : Auto wallet backup failed!");
}
}
btcforkfile << "autobackupblock=" << FinalActivateForkHeight << "\n";
LogPrintf("%s: MVF: soft-forked auto backup block = %d\n", __func__, FinalActivateForkHeight);
}
else {
// auto backup was already made pre-fork - emit parameters
btcforkfile << "autobackupblock=" << GetArg("-autobackupblock", FinalActivateForkHeight - 1) << "\n";
LogPrintf("%s: MVF: height-based auto backup block = %d\n", __func__, GetArg("-autobackupblock", FinalActivateForkHeight - 1));
}
// close fork parameter file
btcforkfile.close();
}
// set the flag so that other code knows HF is active
LogPrintf("%s: MVF: enabling isMVFHardForkActive\n", __func__);
isMVFHardForkActive = true;
}
/** Actions when the fork is deactivated in reorg (MVHF-CORE-DES-TRIG-7) */
void DeactivateFork(void)
{
LogPrintf("%s: MVF: checking whether to perform fork deactivation\n", __func__);
if (isMVFHardForkActive)
{
LogPrintf("%s: MVF: performing fork deactivation actions\n", __func__);
}
LogPrintf("%s: MVF: disabling isMVFHardForkActive\n", __func__);
isMVFHardForkActive = false;
}
<commit_msg>change log output for consensus id<commit_after>// Copyright (c) 2016 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
// MVF-Core common objects and functions
#include "mvf-core.h"
#include "init.h"
#include "util.h"
#include "chainparams.h"
#include "validationinterface.h"
#include <iostream>
#include <fstream>
#include <boost/filesystem.hpp>
using namespace std;
// version string identifying the consensus-relevant algorithmic changes
// so that a user can quickly see if MVF fork clients are compatible
// for test purposes (since they may diverge during development/testing).
// A new value must be chosen whenever there are changes to consensus
// relevant functionality (excepting things which are parameterized).
// Values are surnames chosen from the name list of space travelers at
// https://en.wikipedia.org/wiki/List_of_space_travelers_by_name
std::string post_fork_consensus_id = "AKIYAMA";
// actual fork height, taking into account user configuration parameters (MVHF-CORE-DES-TRIG-4)
int FinalActivateForkHeight = 0;
// actual fork id, taking into account user configuration parameters (MVHF-CORE-DES-CSIG-1)
int FinalForkId = 0;
// track whether HF has been activated before in previous run (MVHF-CORE-DES-TRIG-5)
// is set at startup based on btcfork.conf presence
bool wasMVFHardForkPreviouslyActivated = false;
// track whether HF is active (MVHF-CORE-DES-TRIG-5)
bool isMVFHardForkActive = false;
// track whether auto wallet backup might still need to be done
// this is set to true at startup if client detects fork already triggered
// otherwise when the backup is made. (MVHF-CORE-DES-WABU-1)
bool fAutoBackupDone = false;
// default suffix to append to wallet filename for auto backup (MVHF-CORE-DES-WABU-1)
std::string autoWalletBackupSuffix = "[email protected]";
/** Add MVF-specific command line options (MVHF-CORE-DES-TRIG-8) */
std::string ForkCmdLineHelp()
{
std::string strUsage;
strUsage += HelpMessageGroup(_("Bitcoin MVF-Core Options:"));
// automatic wallet backup parameters (MVHF-CORE-DES-WABU-1)
strUsage += HelpMessageOpt("-autobackupwalletpath=<path>", _("Automatically backup the wallet to the autobackupwalletfile path after the block specified becomes the best block (-autobackupblock). Default: Enabled"));
strUsage += HelpMessageOpt("-autobackupblock=<n>", _("Specify the block number that triggers the automatic wallet backup. Default: forkheight-1"));
// fork height parameter (MVHF-CORE-DES-TRIG-1)
strUsage += HelpMessageOpt("-forkheight=<n>", strprintf(_("Block height at which to fork on active network (integer). Defaults (also minimums): mainnet:%u,testnet=%u,regtest=%u"), (unsigned)HARDFORK_HEIGHT_MAINNET, (unsigned)HARDFORK_HEIGHT_TESTNET, (unsigned)HARDFORK_HEIGHT_REGTEST));
// fork id (MVHF-CORE-DES-CSIG-1)
strUsage += HelpMessageOpt("-forkid=<n>", strprintf(_("Fork id to use for signature change. Value must be between 0 and %d. Default is 0x%06x (%u)"), (unsigned)MAX_HARDFORK_SIGHASH_ID, (unsigned)HARDFORK_SIGHASH_ID, (unsigned)HARDFORK_SIGHASH_ID));
return strUsage;
}
/** Performs fork-related setup / validation actions when the program starts */
void ForkSetup(const CChainParams& chainparams)
{
int defaultForkHeightForNetwork = 0;
std:string activeNetworkID = chainparams.NetworkIDString();
LogPrintf("%s: MVF: doing setup\n", __func__);
LogPrintf("%s: MVF: fork consensus code = %s\n", __func__, post_fork_consensus_id);
LogPrintf("%s: MVF: active network = %s\n", __func__, activeNetworkID);
// determine minimum fork height according to network
// (these are set to the same as the default fork heights for now, but could be made different)
if (activeNetworkID == CBaseChainParams::MAIN)
defaultForkHeightForNetwork = HARDFORK_HEIGHT_MAINNET;
else if (activeNetworkID == CBaseChainParams::TESTNET)
defaultForkHeightForNetwork = HARDFORK_HEIGHT_TESTNET;
else if (activeNetworkID == CBaseChainParams::REGTEST)
defaultForkHeightForNetwork = HARDFORK_HEIGHT_REGTEST;
else
throw std::runtime_error(strprintf("%s: Unknown chain %s.", __func__, activeNetworkID));
FinalActivateForkHeight = GetArg("-forkheight", defaultForkHeightForNetwork);
FinalForkId = GetArg("-forkid", HARDFORK_SIGHASH_ID);
// check fork id for validity (MVHF-CORE-DES-CSIG-2)
if (FinalForkId == 0) {
LogPrintf("MVF: Warning: fork id = 0 will result in vulnerability to replay attacks\n");
}
else {
if (FinalForkId < 0 || FinalForkId > MAX_HARDFORK_SIGHASH_ID) {
LogPrintf("MVF: Error: specified fork id (%d) is not in range 0..%u\n", FinalForkId, (unsigned)MAX_HARDFORK_SIGHASH_ID);
StartShutdown();
}
}
if (GetBoolArg("-segwitfork", DEFAULT_TRIGGER_ON_SEGWIT))
LogPrintf("%s: MVF: Segregated Witness trigger is ENABLED\n", __func__);
else
LogPrintf("%s: MVF: Segregated Witness trigger is DISABLED\n", __func__);
LogPrintf("%s: MVF: active fork height = %d\n", __func__, FinalActivateForkHeight);
LogPrintf("%s: MVF: active fork id = 0x%06x (%d)\n", __func__, FinalForkId, FinalForkId);
if (GetBoolArg("-force-retarget", DEFAULT_FORCE_RETARGET))
LogPrintf("%s: MVF: force-retarget is ENABLED\n", __func__);
else
LogPrintf("%s: MVF: force-retarget is DISABLED\n", __func__);
LogPrintf("%s: MVF: auto backup block = %d\n", __func__, GetArg("-autobackupblock", FinalActivateForkHeight - 1));
// check if btcfork.conf exists (MVHF-CORE-DES-TRIG-10)
boost::filesystem::path pathBTCforkConfigFile(BTCFORK_CONF_FILENAME);
if (!pathBTCforkConfigFile.is_complete())
pathBTCforkConfigFile = GetDataDir(false) / pathBTCforkConfigFile;
if (boost::filesystem::exists(pathBTCforkConfigFile)) {
LogPrintf("%s: MVF: found marker config file at %s - client has already forked before\n", __func__, pathBTCforkConfigFile.string().c_str());
wasMVFHardForkPreviouslyActivated = true;
}
else {
LogPrintf("%s: MVF: no marker config file at %s - client has not forked yet\n", __func__, pathBTCforkConfigFile.string().c_str());
wasMVFHardForkPreviouslyActivated = false;
}
// we should always set the activation flag to false during setup
isMVFHardForkActive = false;
}
/** Actions when the fork triggers (MVHF-CORE-DES-TRIG-6) */
// doBackup parameter default is true
void ActivateFork(int actualForkHeight, bool doBackup)
{
LogPrintf("%s: MVF: checking whether to perform fork activation\n", __func__);
if (!isMVFHardForkActive && !wasMVFHardForkPreviouslyActivated) // sanity check to protect the one-off actions
{
LogPrintf("%s: MVF: performing fork activation actions\n", __func__);
// set so that we capture the actual height at which it forked
// because this can be different from user-specified configuration
// (e.g. soft-fork activated)
FinalActivateForkHeight = actualForkHeight;
boost::filesystem::path pathBTCforkConfigFile(BTCFORK_CONF_FILENAME);
if (!pathBTCforkConfigFile.is_complete())
pathBTCforkConfigFile = GetDataDir(false) / pathBTCforkConfigFile;
LogPrintf("%s: MVF: checking for existence of %s\n", __func__, pathBTCforkConfigFile.string().c_str());
// remove btcfork.conf if it already exists - it shall be overwritten
if (boost::filesystem::exists(pathBTCforkConfigFile)) {
LogPrintf("%s: MVF: removing %s\n", __func__, pathBTCforkConfigFile.string().c_str());
try {
boost::filesystem::remove(pathBTCforkConfigFile);
} catch (const boost::filesystem::filesystem_error& e) {
LogPrintf("%s: Unable to remove pidfile: %s\n", __func__, e.what());
}
}
// try to write the btcfork.conf (MVHF-CORE-DES-TRIG-10)
LogPrintf("%s: MVF: writing %s\n", __func__, pathBTCforkConfigFile.string().c_str());
std::ofstream btcforkfile(pathBTCforkConfigFile.string().c_str(), std::ios::out);
btcforkfile << "forkheight=" << FinalActivateForkHeight << "\n";
btcforkfile << "forkid=" << FinalForkId << "\n";
LogPrintf("%s: MVF: active fork height = %d\n", __func__, FinalActivateForkHeight);
LogPrintf("%s: MVF: active fork id = 0x%06x (%d)\n", __func__, FinalForkId, FinalForkId);
// MVF-Core begin MVHF-CORE-DES-WABU-3
// check if we need to do wallet auto backup at fork block
// this is in case of soft-fork triggered activation
// MVF-Core TODO: reduce code duplication between this block and main.cpp:UpdateTip()
if (doBackup && !fAutoBackupDone)
{
std::string strWalletBackupFile = GetArg("-autobackupwalletpath", "");
int BackupBlock = actualForkHeight;
//LogPrintf("MVF DEBUG: autobackupwalletpath=%s\n",strWalletBackupFile);
//LogPrintf("MVF DEBUG: autobackupblock=%d\n",BackupBlock);
if (GetBoolArg("-disablewallet", false))
{
LogPrintf("MVF: -disablewallet and -autobackupwalletpath conflict so automatic backup disabled.");
fAutoBackupDone = true;
}
else {
// Auto Backup defined, but no need to check block height since
// this is fork activation time and we still have not backed up
// so just get on with it
if (GetMainSignals().BackupWalletAuto(strWalletBackupFile, BackupBlock))
fAutoBackupDone = true;
else {
// shutdown in case of wallet backup failure (MVHF-CORE-DES-WABU-5)
// MVF-Core TODO: investigate if this is safe in terms of wallet flushing/closing or if more needs to be done
btcforkfile << "error: unable to perform automatic backup - exiting" << "\n";
btcforkfile.close();
throw std::runtime_error("CWallet::BackupWalletAuto() : Auto wallet backup failed!");
}
}
btcforkfile << "autobackupblock=" << FinalActivateForkHeight << "\n";
LogPrintf("%s: MVF: soft-forked auto backup block = %d\n", __func__, FinalActivateForkHeight);
}
else {
// auto backup was already made pre-fork - emit parameters
btcforkfile << "autobackupblock=" << GetArg("-autobackupblock", FinalActivateForkHeight - 1) << "\n";
LogPrintf("%s: MVF: height-based auto backup block = %d\n", __func__, GetArg("-autobackupblock", FinalActivateForkHeight - 1));
}
// close fork parameter file
btcforkfile.close();
}
// set the flag so that other code knows HF is active
LogPrintf("%s: MVF: enabling isMVFHardForkActive\n", __func__);
isMVFHardForkActive = true;
}
/** Actions when the fork is deactivated in reorg (MVHF-CORE-DES-TRIG-7) */
void DeactivateFork(void)
{
LogPrintf("%s: MVF: checking whether to perform fork deactivation\n", __func__);
if (isMVFHardForkActive)
{
LogPrintf("%s: MVF: performing fork deactivation actions\n", __func__);
}
LogPrintf("%s: MVF: disabling isMVFHardForkActive\n", __func__);
isMVFHardForkActive = false;
}
<|endoftext|> |
<commit_before>//#define BOOST_ASIO_ENABLE_HANDLER_TRACKING
#include <iostream>
#include <fstream>
#include <string>
#include <tuple>
#include <chrono>
#include <functional>
#include <stdexcept>
#include <unistd.h>
#include <getopt.h>
#include <syslog.h>
#include <boost/asio.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/transform_width.hpp>
namespace asio = boost::asio;
namespace fs = boost::filesystem;
using namespace std::placeholders;
enum class default_params : unsigned int {
interval_sec = 60 * 60
};
struct mydnsjpd_opt {
std::string config_file;
std::string username, passwd;
bool verbose = false, become_daemon = false, effect_immediately = false;
unsigned int interval = static_cast<unsigned int>(default_params::interval_sec);
};
void usage(std::string const& prog_name)
{
std::cout
<< "Usage: " << prog_name << " [OPTION]... -f conf_file" << std::endl
<< "Options:" << std::endl
<< " -d\t\tbecome a daemon" << std::endl
<< " -f\t\tuse specified file as a config file" << std::endl
<< " -v\t\tenable verbose output" << std::endl
<< " -h\t\tdisplay this help and exit" << std::endl;
}
void die(std::string const& prog_name, int exit_code)
{
usage(prog_name);
std::exit(exit_code);
}
// config file format:
// USERNAME=user
// PASSWORD=password
// INTERVAL=sec
void read_config_file(mydnsjpd_opt& opt)
{
std::ifstream ifs(opt.config_file);
if (!ifs)
throw std::runtime_error(opt.config_file + ": Could not open or no such file");
for (std::string line; std::getline(ifs, line); ) {
if (line.empty() || line[0] == '#')
continue;
auto equ_pos = line.find_first_of('=');
if (equ_pos == std::string::npos || equ_pos + 1 == line.length())
throw std::runtime_error(opt.config_file + ": Syntax error: \'" + line + '\'');
std::string varname = line.substr(0, equ_pos), content = line.substr(equ_pos + 1);
if (varname == "USERNAME")
opt.username = std::move(content);
else if (varname == "PASSWORD")
opt.passwd = std::move(content);
else if (varname == "INTERVAL")
opt.interval = static_cast<unsigned int>(std::atoi(content.c_str()));
else if (varname == "EFFECT_IMMEDIATELY")
opt.effect_immediately = (content == "YES" || content == "yes");
else
throw std::runtime_error(opt.config_file + ": Invalid variable \'" + varname + '\'');
}
}
void parse_cmd_line(int argc, char **argv, mydnsjpd_opt& opt)
{
for (int c; (c = ::getopt(argc, argv, "df:vh")) != -1;) {
switch (c) {
case 'd':
opt.become_daemon = true;
break;
case 'f':
opt.config_file.assign(optarg);
break;
case 'v':
opt.verbose = true;
break;
case 'h':
die(argv[0], EXIT_SUCCESS);
break;
default:
die(argv[0], EXIT_FAILURE);
}
}
if (opt.config_file.empty())
throw std::runtime_error("Invalid config file");
opt.config_file = fs::absolute(opt.config_file).native();
read_config_file(opt);
if (opt.username.empty() || opt.passwd.empty())
throw std::runtime_error("Username or password not specified");
}
void base64_encode(std::string const& from, std::string& to)
{
using namespace boost::archive::iterators;
typedef base64_from_binary<transform_width<decltype(from.begin()), 6, 8 >> base64_iterator;
to.clear();
std::copy(
base64_iterator(BOOST_MAKE_PFTO_WRAPPER(from.begin())),
base64_iterator(BOOST_MAKE_PFTO_WRAPPER(from.end())),
std::back_inserter(to)
);
}
std::tuple<std::string, int, std::string> mydnsjp_update(mydnsjpd_opt const& opt)
{
std::string basic_auth_str;
base64_encode(opt.username + ':' + opt.passwd, basic_auth_str);
boost::asio::ip::tcp::iostream s;
s.expires_from_now(boost::posix_time::seconds(2));
s.connect("www.mydns.jp", "80");
if (!s)
throw std::runtime_error(s.error().message());
s << "GET /login.html HTTP/1.1\r\n"
<< "Host: www.mydns.jp\r\n"
<< "Connection: close\r\n"
<< "Authorization: Basic " << basic_auth_str << "\r\n"
<< "\r\n" << std::flush;
if (!s)
throw std::runtime_error("unable to send the HTTP request");
std::string http_version, http_status, status_msg;
s >> http_version >> http_status;
std::getline(s, status_msg);
if (!s)
throw std::runtime_error("unable to receive the HTTP response");
if (opt.verbose && !opt.become_daemon)
std::copy(
std::istreambuf_iterator<char>(s.rdbuf()),
std::istreambuf_iterator<char>(),
std::ostreambuf_iterator<char>(std::cout.rdbuf())
);
return std::make_tuple(http_version, std::atoi(http_status.c_str()), status_msg.substr(1));
}
class mydnsjpd {
public:
typedef asio::basic_waitable_timer<std::chrono::steady_clock> steady_timer;
mydnsjpd(asio::io_service& io, mydnsjpd_opt& opt)
: io_(io), timer_(io), sigset_(io, SIGHUP, SIGINT, SIGTERM), opt_(opt)
{
io_.notify_fork(asio::io_service::fork_prepare);
if (::daemon(0, 0) < 0)
die("daemon(): " + std::string(std::strerror(errno)), EXIT_FAILURE);
io_.notify_fork(asio::io_service::fork_child);
start_service();
::openlog("mydnsjpd", LOG_CONS | LOG_PID, LOG_DAEMON);
::syslog(LOG_INFO, "daemon started masterID=%s,interval(sec)=%d", opt_.username.c_str(), opt_.interval);
}
~mydnsjpd()
{
::syslog(LOG_INFO, "daemon now finished");
::closelog();
}
private:
void start_service()
{
start_timer();
start_signal_handling();
}
void start_timer()
{
timer_.expires_from_now(std::chrono::seconds(opt_.interval));
timer_.async_wait(std::bind(&mydnsjpd::timer_handler, this, _1));
}
void start_signal_handling()
{
sigset_.async_wait(std::bind(&mydnsjpd::sighandler, this, _1, _2));
}
void timer_handler(boost::system::error_code const& err)
{
if (err) {
if (!(opt_.effect_immediately && err == asio::error::operation_aborted))
::syslog(LOG_ERR, "Error: timer handler: %s", err.message().c_str());
} else try {
auto ret = mydnsjp_update(opt_);
::syslog(std::get<1>(ret) == 200 ? LOG_NOTICE : LOG_ERR,
"status=%d msg=%s", std::get<1>(ret), std::get<2>(ret).c_str());
} catch (std::exception& e) {
::syslog(LOG_ERR, "Exception: timer handler: %s", e.what());
}
start_timer();
}
void sighandler(boost::system::error_code const& err, int signum)
{
if (err)
::syslog(LOG_ERR, "Error: signal hander: %s", err.message().c_str());
else if (signum == SIGHUP) try {
read_config_file(opt_);
if (opt_.effect_immediately)
timer_.cancel();
::syslog(LOG_INFO, "Reload config: masterID=%s,interval(sec)=%d", opt_.username.c_str(), opt_.interval);
} catch (std::exception& e) {
::syslog(LOG_ERR, "Exception: signal handler: %s", e.what());
} else if (signum == SIGINT || signum == SIGTERM) {
::syslog(LOG_NOTICE, "Received SIGINT or SIGTERM, now stopping operations");
io_.stop();
}
start_signal_handling();
}
asio::io_service& io_;
steady_timer timer_;
asio::signal_set sigset_;
mydnsjpd_opt& opt_;
};
void io_service_run(asio::io_service& io_service)
{
for (;;) {
try {
io_service.run();
break;
} catch (std::exception& e) {
::syslog(LOG_ERR, "Exception: catched by io_service_run(): %s", e.what());
}
}
}
int main(int argc, char **argv)
{
int exit_code = EXIT_SUCCESS;
try {
if (argc < 2)
throw std::runtime_error("Too few arguments, use -h option to display usage");
mydnsjpd_opt opt;
parse_cmd_line(argc, argv, opt);
if (opt.become_daemon) {
asio::io_service io_service;
mydnsjpd daemon(io_service, opt);
io_service_run(io_service);
} else {
auto ret = mydnsjp_update(opt);
int return_code = std::get<1>(ret);
if (return_code != 200)
throw std::runtime_error(std::to_string(return_code) + " / " + std::get<2>(ret));
std::cout << "status=" << return_code << " msg=" << std::get<2>(ret) << std::endl;
}
} catch (std::exception& e) {
std::cerr << "Exception: " << e.what() << std::endl;
exit_code = EXIT_FAILURE;
}
return exit_code;
}
<commit_msg>mydnsjpd.cpp: add comments to src file<commit_after>//#define BOOST_ASIO_ENABLE_HANDLER_TRACKING
#include <iostream>
#include <fstream>
#include <string>
#include <tuple>
#include <chrono>
#include <functional>
#include <stdexcept>
#include <unistd.h>
#include <getopt.h>
#include <syslog.h>
#include <boost/asio.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/transform_width.hpp>
namespace asio = boost::asio;
namespace fs = boost::filesystem;
using namespace std::placeholders;
enum class default_params : unsigned int {
interval_sec = 60 * 60
};
// mydnsjpd option structure
struct mydnsjpd_opt {
std::string config_file;
std::string username, passwd;
bool verbose = false, become_daemon = false, effect_immediately = false;
unsigned int interval = static_cast<unsigned int>(default_params::interval_sec);
};
void usage(std::string const& prog_name)
{
std::cout
<< "Usage: " << prog_name << " [OPTION]... -f conf_file" << std::endl
<< "Options:" << std::endl
<< " -d\t\tbecome a daemon" << std::endl
<< " -f\t\tuse specified file as a config file" << std::endl
<< " -v\t\tenable verbose output" << std::endl
<< " -h\t\tdisplay this help and exit" << std::endl;
}
void die(std::string const& prog_name, int exit_code)
{
usage(prog_name);
std::exit(exit_code);
}
// config file format:
// USERNAME=user
// PASSWORD=password
// INTERVAL=sec
void read_config_file(mydnsjpd_opt& opt)
{
std::ifstream ifs(opt.config_file);
if (!ifs)
throw std::runtime_error(opt.config_file + ": Could not open or no such file");
for (std::string line; std::getline(ifs, line); ) {
if (line.empty() || line[0] == '#')
continue;
auto equ_pos = line.find_first_of('=');
if (equ_pos == std::string::npos || equ_pos + 1 == line.length())
throw std::runtime_error(opt.config_file + ": Syntax error: \'" + line + '\'');
std::string varname = line.substr(0, equ_pos), content = line.substr(equ_pos + 1);
if (varname == "USERNAME")
opt.username = std::move(content);
else if (varname == "PASSWORD")
opt.passwd = std::move(content);
else if (varname == "INTERVAL")
opt.interval = static_cast<unsigned int>(std::atoi(content.c_str()));
else if (varname == "EFFECT_IMMEDIATELY")
opt.effect_immediately = (content == "YES" || content == "yes");
else
throw std::runtime_error(opt.config_file + ": Invalid variable \'" + varname + '\'');
}
}
void parse_cmd_line(int argc, char **argv, mydnsjpd_opt& opt)
{
for (int c; (c = ::getopt(argc, argv, "df:vh")) != -1;) {
switch (c) {
case 'd':
opt.become_daemon = true;
break;
case 'f':
opt.config_file.assign(optarg);
break;
case 'v':
opt.verbose = true;
break;
case 'h':
die(argv[0], EXIT_SUCCESS);
break;
default:
die(argv[0], EXIT_FAILURE);
}
}
if (opt.config_file.empty())
throw std::runtime_error("Invalid config file");
opt.config_file = fs::absolute(opt.config_file).native();
read_config_file(opt);
if (opt.username.empty() || opt.passwd.empty())
throw std::runtime_error("Username or password not specified");
}
void base64_encode(std::string const& from, std::string& to)
{
using namespace boost::archive::iterators;
typedef base64_from_binary<transform_width<decltype(from.begin()), 6, 8 >> base64_iterator;
to.clear();
std::copy(
base64_iterator(BOOST_MAKE_PFTO_WRAPPER(from.begin())),
base64_iterator(BOOST_MAKE_PFTO_WRAPPER(from.end())),
std::back_inserter(to)
);
}
// mydnsjpd core updating function
std::tuple<std::string, int, std::string> mydnsjp_update(mydnsjpd_opt const& opt)
{
std::string basic_auth_str;
base64_encode(opt.username + ':' + opt.passwd, basic_auth_str);
boost::asio::ip::tcp::iostream s;
s.expires_from_now(boost::posix_time::seconds(2));
s.connect("www.mydns.jp", "80");
if (!s)
throw std::runtime_error(s.error().message());
s << "GET /login.html HTTP/1.1\r\n"
<< "Host: www.mydns.jp\r\n"
<< "Connection: close\r\n"
<< "Authorization: Basic " << basic_auth_str << "\r\n"
<< "\r\n" << std::flush;
if (!s)
throw std::runtime_error("unable to send the HTTP request");
std::string http_version, http_status, status_msg;
s >> http_version >> http_status;
std::getline(s, status_msg);
if (!s)
throw std::runtime_error("unable to receive the HTTP response");
if (opt.verbose && !opt.become_daemon)
std::copy(
std::istreambuf_iterator<char>(s.rdbuf()),
std::istreambuf_iterator<char>(),
std::ostreambuf_iterator<char>(std::cout.rdbuf())
);
return std::make_tuple(http_version, std::atoi(http_status.c_str()), status_msg.substr(1));
}
//
// mydnsjpd core daemon class
//
class mydnsjpd {
public:
typedef asio::basic_waitable_timer<std::chrono::steady_clock> steady_timer;
mydnsjpd(asio::io_service& io, mydnsjpd_opt& opt)
: io_(io), timer_(io), sigset_(io, SIGHUP, SIGINT, SIGTERM), opt_(opt)
{
io_.notify_fork(asio::io_service::fork_prepare);
if (::daemon(0, 0) < 0)
die("daemon(): " + std::string(std::strerror(errno)), EXIT_FAILURE);
io_.notify_fork(asio::io_service::fork_child);
start_service();
::openlog("mydnsjpd", LOG_CONS | LOG_PID, LOG_DAEMON);
::syslog(LOG_INFO, "daemon started masterID=%s,interval(sec)=%d", opt_.username.c_str(), opt_.interval);
}
~mydnsjpd()
{
::syslog(LOG_INFO, "daemon now finished");
::closelog();
}
private:
void start_service()
{
start_timer();
start_signal_handling();
}
void start_timer()
{
timer_.expires_from_now(std::chrono::seconds(opt_.interval));
timer_.async_wait(std::bind(&mydnsjpd::timer_handler, this, _1));
}
void start_signal_handling()
{
sigset_.async_wait(std::bind(&mydnsjpd::sighandler, this, _1, _2));
}
void timer_handler(boost::system::error_code const& err)
{
if (err) {
if (!(opt_.effect_immediately && err == asio::error::operation_aborted))
::syslog(LOG_ERR, "Error: timer handler: %s", err.message().c_str());
} else try {
auto ret = mydnsjp_update(opt_);
::syslog(std::get<1>(ret) == 200 ? LOG_NOTICE : LOG_ERR,
"status=%d msg=%s", std::get<1>(ret), std::get<2>(ret).c_str());
} catch (std::exception& e) {
::syslog(LOG_ERR, "Exception: timer handler: %s", e.what());
}
start_timer();
}
void sighandler(boost::system::error_code const& err, int signum)
{
if (err)
::syslog(LOG_ERR, "Error: signal hander: %s", err.message().c_str());
else if (signum == SIGHUP) try {
read_config_file(opt_);
if (opt_.effect_immediately)
timer_.cancel();
::syslog(LOG_INFO, "Reload config: masterID=%s,interval(sec)=%d", opt_.username.c_str(), opt_.interval);
} catch (std::exception& e) {
::syslog(LOG_ERR, "Exception: signal handler: %s", e.what());
} else if (signum == SIGINT || signum == SIGTERM) {
::syslog(LOG_NOTICE, "Received SIGINT or SIGTERM, now stopping operations");
io_.stop();
}
start_signal_handling();
}
asio::io_service& io_;
steady_timer timer_;
asio::signal_set sigset_;
mydnsjpd_opt& opt_;
};
// Do io_service::run() properly including exception handling
void io_service_run(asio::io_service& io_service)
{
for (;;) {
try {
io_service.run();
break;
} catch (std::exception& e) {
::syslog(LOG_ERR, "Exception: catched by io_service_run(): %s", e.what());
} catch (...) {
::syslog(LOG_ERR, "FATAL error: unknown exception cathced, exiting...");
break;
}
}
}
int main(int argc, char **argv)
{
int exit_code = EXIT_SUCCESS;
try {
if (argc < 2)
throw std::runtime_error("Too few arguments, use -h option to display usage");
mydnsjpd_opt opt;
parse_cmd_line(argc, argv, opt);
if (opt.become_daemon) {
// Now we are becoming a daemon
asio::io_service io_service;
mydnsjpd daemon(io_service, opt);
io_service_run(io_service);
} else {
// Or perform one-shot updating
auto ret = mydnsjp_update(opt);
int return_code = std::get<1>(ret);
if (return_code != 200)
throw std::runtime_error(std::to_string(return_code) + " / " + std::get<2>(ret));
std::cout << "status=" << return_code << " msg=" << std::get<2>(ret) << std::endl;
}
} catch (std::exception& e) {
std::cerr << "Exception: " << e.what() << std::endl;
exit_code = EXIT_FAILURE;
}
return exit_code;
}
<|endoftext|> |
<commit_before>#pragma once
/*
* Some parts are from upb - a minimalist implementation of protocol buffers.
*
* Copyright (c) 2008-2011 Google Inc. See LICENSE for details.
* Author: Josh Haberman <[email protected]>
*/
#include <stdint.h>
#include <stdexcept>
#include <string>
#include <cassert>
#undef LIKELY
#undef UNLIKELY
#if defined(__GNUC__) && __GNUC__ >= 4
#define LIKELY(x) (__builtin_expect((x), 1))
#define UNLIKELY(x) (__builtin_expect((x), 0))
#else
#define LIKELY(x) (x)
#define UNLIKELY(x) (x)
#endif
namespace protobuf {
#define FORCEINLINE inline __attribute__((always_inline))
#define NOINLINE __attribute__((noinline))
#define PBF_INLINE FORCEINLINE
struct message {
PBF_INLINE message(const char *data, uint32_t length);
PBF_INLINE bool next();
PBF_INLINE uint64_t varint();
PBF_INLINE uint64_t varint2();
PBF_INLINE int64_t svarint();
PBF_INLINE std::string string();
PBF_INLINE float float32();
PBF_INLINE double float64();
PBF_INLINE int64_t int64();
PBF_INLINE bool boolean();
PBF_INLINE void skip();
PBF_INLINE void skipValue(uint32_t val);
PBF_INLINE void skipBytes(uint32_t bytes);
const char *data;
const char *end;
uint64_t value;
uint32_t tag;
};
message::message(const char * _data, uint32_t length)
: data(_data),
end(data + length)
{
}
bool message::next()
{
if (data < end) {
value = varint();
tag = value >> 3;
return true;
}
return false;
}
uint64_t message::varint()
{
int8_t byte = 0x80;
uint64_t result = 0;
int bitpos;
for (bitpos = 0; bitpos < 70 && (byte & 0x80); bitpos += 7) {
if (data >= end) {
throw std::runtime_error("unterminated varint, unexpected end of buffer");
}
result |= ((uint64_t)(byte = *data) & 0x7F) << bitpos;
data++;
}
if (bitpos == 70 && (byte & 0x80)) {
throw std::runtime_error("unterminated varint (too long)");
}
return result;
}
static const int8_t kMaxVarintLength64 = 10;
uint64_t message::varint2() {
const int8_t* begin = reinterpret_cast<const int8_t*>(data);
const int8_t* iend = reinterpret_cast<const int8_t*>(end);
const int8_t* p = begin;
uint64_t val = 0;
if (LIKELY(iend - begin >= kMaxVarintLength64)) { // fast path
int64_t b;
do {
b = *p++; val = (b & 0x7f) ; if (b >= 0) break;
b = *p++; val |= (b & 0x7f) << 7; if (b >= 0) break;
b = *p++; val |= (b & 0x7f) << 14; if (b >= 0) break;
b = *p++; val |= (b & 0x7f) << 21; if (b >= 0) break;
b = *p++; val |= (b & 0x7f) << 28; if (b >= 0) break;
b = *p++; val |= (b & 0x7f) << 35; if (b >= 0) break;
b = *p++; val |= (b & 0x7f) << 42; if (b >= 0) break;
b = *p++; val |= (b & 0x7f) << 49; if (b >= 0) break;
b = *p++; val |= (b & 0x7f) << 56; if (b >= 0) break;
b = *p++; val |= (b & 0x7f) << 63; if (b >= 0) break;
throw std::invalid_argument("Invalid varint value"); // too big
} while (false);
} else {
int shift = 0;
while (p != iend && *p < 0) {
val |= static_cast<uint64_t>(*p++ & 0x7f) << shift;
shift += 7;
}
if (p == iend) throw std::invalid_argument("Invalid varint value");
val |= static_cast<uint64_t>(*p++) << shift;
}
data = reinterpret_cast<const char *>(p);
return val;
}
int64_t message::svarint()
{
uint64_t n = varint();
return (n >> 1) ^ -(int64_t)(n & 1);
}
std::string message::string()
{
uint32_t bytes = varint();
const char *string = (const char *)data;
skipBytes(bytes);
return std::string(string, bytes);
}
float message::float32()
{
skipBytes(4);
float result;
memcpy(&result, data - 4, 4);
return result;
}
double message::float64()
{
skipBytes(8);
double result;
memcpy(&result, data - 8, 8);
return result;
}
int64_t message::int64()
{
return (int64_t)varint();
}
bool message::boolean()
{
skipBytes(1);
return *(bool *)(data - 1);
}
void message::skip()
{
skipValue(value);
}
void message::skipValue(uint32_t val)
{
switch (val & 0x7) {
case 0: // varint
varint();
break;
case 1: // 64 bit
skipBytes(8);
break;
case 2: // string/message
skipBytes(varint());
break;
case 5: // 32 bit
skipBytes(4);
break;
default:
char msg[80];
snprintf(msg, 80, "cannot skip unknown type %d", val & 0x7);
throw std::runtime_error(msg);
}
}
void message::skipBytes(uint32_t bytes)
{
data += bytes;
if (data > end) {
throw std::runtime_error("unexpected end of buffer");
}
}
}
<commit_msg>fix tabs that snuck into c code<commit_after>#pragma once
/*
* Some parts are from upb - a minimalist implementation of protocol buffers.
*
* Copyright (c) 2008-2011 Google Inc. See LICENSE for details.
* Author: Josh Haberman <[email protected]>
*/
#include <stdint.h>
#include <stdexcept>
#include <string>
#include <cassert>
#undef LIKELY
#undef UNLIKELY
#if defined(__GNUC__) && __GNUC__ >= 4
#define LIKELY(x) (__builtin_expect((x), 1))
#define UNLIKELY(x) (__builtin_expect((x), 0))
#else
#define LIKELY(x) (x)
#define UNLIKELY(x) (x)
#endif
namespace protobuf {
#define FORCEINLINE inline __attribute__((always_inline))
#define NOINLINE __attribute__((noinline))
#define PBF_INLINE FORCEINLINE
struct message {
PBF_INLINE message(const char *data, uint32_t length);
PBF_INLINE bool next();
PBF_INLINE uint64_t varint();
PBF_INLINE uint64_t varint2();
PBF_INLINE int64_t svarint();
PBF_INLINE std::string string();
PBF_INLINE float float32();
PBF_INLINE double float64();
PBF_INLINE int64_t int64();
PBF_INLINE bool boolean();
PBF_INLINE void skip();
PBF_INLINE void skipValue(uint32_t val);
PBF_INLINE void skipBytes(uint32_t bytes);
const char *data;
const char *end;
uint64_t value;
uint32_t tag;
};
message::message(const char * _data, uint32_t length)
: data(_data),
end(data + length)
{
}
bool message::next()
{
if (data < end) {
value = varint();
tag = value >> 3;
return true;
}
return false;
}
uint64_t message::varint()
{
int8_t byte = 0x80;
uint64_t result = 0;
int bitpos;
for (bitpos = 0; bitpos < 70 && (byte & 0x80); bitpos += 7) {
if (data >= end) {
throw std::runtime_error("unterminated varint, unexpected end of buffer");
}
result |= ((uint64_t)(byte = *data) & 0x7F) << bitpos;
data++;
}
if (bitpos == 70 && (byte & 0x80)) {
throw std::runtime_error("unterminated varint (too long)");
}
return result;
}
static const int8_t kMaxVarintLength64 = 10;
uint64_t message::varint2() {
const int8_t* begin = reinterpret_cast<const int8_t*>(data);
const int8_t* iend = reinterpret_cast<const int8_t*>(end);
const int8_t* p = begin;
uint64_t val = 0;
if (LIKELY(iend - begin >= kMaxVarintLength64)) { // fast path
int64_t b;
do {
b = *p++; val = (b & 0x7f) ; if (b >= 0) break;
b = *p++; val |= (b & 0x7f) << 7; if (b >= 0) break;
b = *p++; val |= (b & 0x7f) << 14; if (b >= 0) break;
b = *p++; val |= (b & 0x7f) << 21; if (b >= 0) break;
b = *p++; val |= (b & 0x7f) << 28; if (b >= 0) break;
b = *p++; val |= (b & 0x7f) << 35; if (b >= 0) break;
b = *p++; val |= (b & 0x7f) << 42; if (b >= 0) break;
b = *p++; val |= (b & 0x7f) << 49; if (b >= 0) break;
b = *p++; val |= (b & 0x7f) << 56; if (b >= 0) break;
b = *p++; val |= (b & 0x7f) << 63; if (b >= 0) break;
throw std::invalid_argument("Invalid varint value"); // too big
} while (false);
} else {
int shift = 0;
while (p != iend && *p < 0) {
val |= static_cast<uint64_t>(*p++ & 0x7f) << shift;
shift += 7;
}
if (p == iend) throw std::invalid_argument("Invalid varint value");
val |= static_cast<uint64_t>(*p++) << shift;
}
data = reinterpret_cast<const char *>(p);
return val;
}
int64_t message::svarint()
{
uint64_t n = varint();
return (n >> 1) ^ -(int64_t)(n & 1);
}
std::string message::string()
{
uint32_t bytes = varint();
const char *string = (const char *)data;
skipBytes(bytes);
return std::string(string, bytes);
}
float message::float32()
{
skipBytes(4);
float result;
memcpy(&result, data - 4, 4);
return result;
}
double message::float64()
{
skipBytes(8);
double result;
memcpy(&result, data - 8, 8);
return result;
}
int64_t message::int64()
{
return (int64_t)varint();
}
bool message::boolean()
{
skipBytes(1);
return *(bool *)(data - 1);
}
void message::skip()
{
skipValue(value);
}
void message::skipValue(uint32_t val)
{
switch (val & 0x7) {
case 0: // varint
varint();
break;
case 1: // 64 bit
skipBytes(8);
break;
case 2: // string/message
skipBytes(varint());
break;
case 5: // 32 bit
skipBytes(4);
break;
default:
char msg[80];
snprintf(msg, 80, "cannot skip unknown type %d", val & 0x7);
throw std::runtime_error(msg);
}
}
void message::skipBytes(uint32_t bytes)
{
data += bytes;
if (data > end) {
throw std::runtime_error("unexpected end of buffer");
}
}
}
<|endoftext|> |
<commit_before>/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2011-2013 Couchbase, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "internal.h"
#include "packetutils.h"
#include "bucketconfig/clconfig.h"
#include "vbucket/aliases.h"
#include "sllist-inl.h"
#define LOGARGS(instance, lvl) (instance)->settings, "newconfig", LCB_LOG_##lvl, __FILE__, __LINE__
#define LOG(instance, lvlbase, msg) lcb_log(instance->settings, "newconfig", LCB_LOG_##lvlbase, __FILE__, __LINE__, msg)
#define SERVER_FMT "%s:%s (%p)"
#define SERVER_ARGS(s) (s)->get_host().host, (s)->get_host().port, (void *)s
typedef struct lcb_GUESSVB_st {
time_t last_update; /**< Last time this vBucket was heuristically set */
char newix; /**< New index, heuristically determined */
char oldix; /**< Original index, according to map */
char used; /**< Flag indicating whether or not this entry has been used */
} lcb_GUESSVB;
/* Ignore configuration updates for heuristically guessed vBuckets for a
* maximum amount of [n] seconds */
#define MAX_KEEP_GUESS 20
static int
should_keep_guess(lcb_GUESSVB *guess, lcbvb_VBUCKET *vb)
{
if (guess->newix == guess->oldix) {
/* Heuristic position is the same as starting position */
return 0;
}
if (vb->servers[0] != guess->oldix) {
/* Previous master changed */
return 0;
}
if (time(NULL) - guess->last_update > MAX_KEEP_GUESS) {
/* Last usage too old */
return 0;
}
return 1;
}
void
lcb_vbguess_newconfig(lcb_t instance, lcbvb_CONFIG *cfg, lcb_GUESSVB *guesses)
{
unsigned ii;
if (!guesses) {
return;
}
for (ii = 0; ii < cfg->nvb; ii++) {
lcb_GUESSVB *guess = guesses + ii;
lcbvb_VBUCKET *vb = cfg->vbuckets + ii;
if (!guess->used) {
continue;
}
/* IF: Heuristically learned a new index, _and_ the old index (which is
* known to be bad) is the same index stated by the new config */
if (should_keep_guess(guess, vb)) {
lcb_log(LOGARGS(instance, TRACE), "Keeping heuristically guessed index. VBID=%d. Current=%d. Old=%d.", ii, guess->newix, guess->oldix);
vb->servers[0] = guess->newix;
} else {
/* We don't reassign to the guess structure here. The idea is that
* we will simply use the new config. If this gives us problems, the
* config will re-learn again. */
lcb_log(LOGARGS(instance, TRACE), "Ignoring heuristically guessed index. VBID=%d. Current=%d. Old=%d. New=%d", ii, guess->newix, guess->oldix, vb->servers[0]);
guess->used = 0;
}
}
}
int
lcb_vbguess_remap(lcb_t instance, int vbid, int bad)
{
if (LCBT_SETTING(instance, vb_noguess)) {
int newix = lcbvb_nmv_remap_ex(LCBT_VBCONFIG(instance), vbid, bad, 0);
if (newix > -1 && newix != bad) {
lcb_log(LOGARGS(instance, TRACE), "Got new index from ffmap. VBID=%d. Old=%d. New=%d", vbid, bad, newix);
}
return newix;
} else {
lcb_GUESSVB *guesses = instance->vbguess;
lcb_GUESSVB *guess = guesses + vbid;
int newix = lcbvb_nmv_remap_ex(LCBT_VBCONFIG(instance), vbid, bad, 1);
if (!guesses) {
guesses = instance->vbguess = reinterpret_cast<lcb_GUESSVB*>(calloc(
LCBT_VBCONFIG(instance)->nvb, sizeof *guesses));
}
if (newix > -1 && newix != bad) {
guess->newix = newix;
guess->oldix = bad;
guess->used = 1;
guess->last_update = time(NULL);
lcb_log(LOGARGS(instance, TRACE), "Guessed new heuristic index VBID=%d. Old=%d. New=%d", vbid, bad, newix);
}
return newix;
}
}
/**
* Finds the index of an older server using the current config.
*
* This function is used to help reuse the server structures for memcached
* packets.
*
* @param oldconfig The old configuration. This is the configuration the
* old server is bound to
* @param newconfig The new configuration. This will be inspected for new
* nodes which may have been added, and ones which may have been removed.
* @param server The server to match
* @return The new index, or -1 if the current server is not present in the new
* config.
*/
static int
find_new_data_index(lcbvb_CONFIG *oldconfig, lcbvb_CONFIG* newconfig,
lcb::Server *server)
{
const char *old_datahost = lcbvb_get_hostport(oldconfig,
server->get_index(), LCBVB_SVCTYPE_DATA, LCBVB_SVCMODE_PLAIN);
if (!old_datahost) {
/* Old server had no data service */
return -1;
}
for (size_t ii = 0; ii < LCBVB_NSERVERS(newconfig); ii++) {
const char *new_datahost = lcbvb_get_hostport(newconfig, ii,
LCBVB_SVCTYPE_DATA, LCBVB_SVCMODE_PLAIN);
if (new_datahost && strcmp(new_datahost, old_datahost) == 0) {
return ii;
}
}
return -1;
}
static void
log_vbdiff(lcb_t instance, lcbvb_CONFIGDIFF *diff)
{
lcb_log(LOGARGS(instance, INFO), "Config Diff: [ vBuckets Modified=%d ], [Sequence Changed=%d]", diff->n_vb_changes, diff->sequence_changed);
if (diff->servers_added) {
for (char **curserver = diff->servers_added; *curserver; curserver++) {
lcb_log(LOGARGS(instance, INFO), "Detected server %s added", *curserver);
}
}
if (diff->servers_removed) {
for (char **curserver = diff->servers_removed; *curserver; curserver++) {
lcb_log(LOGARGS(instance, INFO), "Detected server %s removed", *curserver);
}
}
}
/**
* This callback is invoked for packet relocation twice. It tries to relocate
* commands to their destination server. Some commands may not be relocated
* either because they have no explicit "Relocation Information" (i.e. no
* specific vbucket) or because the command is tied to a specific server (i.e.
* CMD_STAT).
*
* Note that `KEEP_PACKET` here doesn't mean to "Save" the packet, but rather
* to keep the packet in the current queue (so that if the server ends up
* being removed, the command will fail); rather than being relocated to
* another server.
*/
static int
iterwipe_cb(mc_CMDQUEUE *cq, mc_PIPELINE *oldpl, mc_PACKET *oldpkt, void *)
{
protocol_binary_request_header hdr;
lcb::Server *srv = static_cast<lcb::Server *>(oldpl);
int newix;
mcreq_read_hdr(oldpkt, &hdr);
if (!lcb_should_retry(srv->get_settings(), oldpkt, LCB_MAX_ERROR)) {
return MCREQ_KEEP_PACKET;
}
if (LCBVB_DISTTYPE(cq->config) == LCBVB_DIST_VBUCKET) {
newix = lcbvb_vbmaster(cq->config, ntohs(hdr.request.vbucket));
} else {
const void *key = NULL;
lcb_SIZE nkey = 0;
int tmpid;
/* XXX: We ignore hashkey. This is going away soon, and is probably
* better than simply failing the items. */
mcreq_get_key(oldpkt, &key, &nkey);
lcbvb_map_key(cq->config, key, nkey, &tmpid, &newix);
}
if (newix < 0 || newix > (int)cq->npipelines-1) {
return MCREQ_KEEP_PACKET;
}
mc_PIPELINE *newpl = cq->pipelines[newix];
if (newpl == oldpl || newpl == NULL) {
return MCREQ_KEEP_PACKET;
}
lcb_log(LOGARGS((lcb_t)cq->cqdata, DEBUG), "Remapped packet %p (SEQ=%u) from " SERVER_FMT " to " SERVER_FMT,
(void*)oldpkt, oldpkt->opaque, SERVER_ARGS((lcb::Server*)oldpl), SERVER_ARGS((lcb::Server*)newpl));
/** Otherwise, copy over the packet and find the new vBucket to map to */
mc_PACKET *newpkt = mcreq_renew_packet(oldpkt);
newpkt->flags &= ~MCREQ_STATE_FLAGS;
mcreq_reenqueue_packet(newpl, newpkt);
mcreq_packet_handled(oldpl, oldpkt);
return MCREQ_REMOVE_PACKET;
}
static void
replace_config(lcb_t instance, lcbvb_CONFIG *oldconfig, lcbvb_CONFIG *newconfig)
{
mc_CMDQUEUE *cq = &instance->cmdq;
mc_PIPELINE **ppold, **ppnew;
unsigned ii, nold, nnew;
assert(LCBT_VBCONFIG(instance) == newconfig);
nnew = LCBVB_NSERVERS(newconfig);
ppnew = reinterpret_cast<mc_PIPELINE**>(calloc(nnew, sizeof(*ppnew)));
ppold = mcreq_queue_take_pipelines(cq, &nold);
/**
* Determine which existing servers are still part of the new cluster config
* and place it inside the new list.
*/
for (ii = 0; ii < nold; ii++) {
lcb::Server *cur = static_cast<lcb::Server *>(ppold[ii]);
int newix = find_new_data_index(oldconfig, newconfig, cur);
if (newix > -1) {
cur->set_new_index(newix);
ppnew[newix] = cur;
ppold[ii] = NULL;
lcb_log(LOGARGS(instance, INFO), "Reusing server " SERVER_FMT ". OldIndex=%d. NewIndex=%d", SERVER_ARGS(cur), ii, newix);
}
}
/**
* Once we've moved the kept servers to the new list, allocate new lcb::Server
* structures for slots that don't have an existing lcb::Server. We must do
* this before add_pipelines() is called, so that there are no holes inside
* ppnew
*/
for (ii = 0; ii < nnew; ii++) {
if (!ppnew[ii]) {
ppnew[ii] = new lcb::Server(instance, ii);
}
}
/**
* Once we have all the server structures in place for the new config,
* transfer the new config along with the new list over to the CQ structure.
*/
mcreq_queue_add_pipelines(cq, ppnew, nnew, newconfig);
for (ii = 0; ii < nnew; ii++) {
mcreq_iterwipe(cq, ppnew[ii], iterwipe_cb, NULL);
}
/**
* Go through all the servers that are to be removed and relocate commands
* from their queues into the new queues
*/
for (ii = 0; ii < nold; ii++) {
if (!ppold[ii]) {
continue;
}
mcreq_iterwipe(cq, ppold[ii], iterwipe_cb, NULL);
static_cast<lcb::Server*>(ppold[ii])->purge(LCB_MAP_CHANGED);
static_cast<lcb::Server*>(ppold[ii])->close();
}
for (ii = 0; ii < nnew; ii++) {
if (static_cast<lcb::Server*>(ppnew[ii])->has_pending()) {
ppnew[ii]->flush_start(ppnew[ii]);
}
}
free(ppnew);
free(ppold);
}
void lcb_update_vbconfig(lcb_t instance, lcb_pCONFIGINFO config)
{
lcb_configuration_t change_status;
lcb::clconfig::ConfigInfo *old_config = instance->cur_configinfo;
mc_CMDQUEUE *q = &instance->cmdq;
instance->cur_configinfo = config;
config->incref();
q->config = instance->cur_configinfo->vbc;
q->cqdata = instance;
if (old_config) {
lcbvb_CONFIGDIFF *diff = lcbvb_compare(old_config->vbc, config->vbc);
if (diff) {
log_vbdiff(instance, diff);
lcbvb_free_diff(diff);
}
/* Apply the vb guesses */
lcb_vbguess_newconfig(instance, config->vbc, instance->vbguess);
replace_config(instance, old_config->vbc, config->vbc);
old_config->decref();
change_status = LCB_CONFIGURATION_CHANGED;
} else {
size_t nservers = VB_NSERVERS(config->vbc);
std::vector<mc_PIPELINE*> servers;
for (size_t ii = 0; ii < nservers; ii++) {
servers.push_back(new lcb::Server(instance, ii));
}
mcreq_queue_add_pipelines(q, &servers[0], nservers, config->vbc);
change_status = LCB_CONFIGURATION_NEW;
}
/* Update the list of nodes here for server list */
instance->ht_nodes->clear();
for (size_t ii = 0; ii < LCBVB_NSERVERS(config->vbc); ++ii) {
const char *hp = lcbvb_get_hostport(config->vbc, ii,
LCBVB_SVCTYPE_MGMT, LCBVB_SVCMODE_PLAIN);
if (hp) {
instance->ht_nodes->add(hp, LCB_CONFIG_HTTP_PORT);
}
}
instance->callbacks.configuration(instance, change_status);
lcb_maybe_breakout(instance);
}
<commit_msg>CCBC-854: init vbguess array before entry lookup<commit_after>/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2011-2013 Couchbase, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "internal.h"
#include "packetutils.h"
#include "bucketconfig/clconfig.h"
#include "vbucket/aliases.h"
#include "sllist-inl.h"
#define LOGARGS(instance, lvl) (instance)->settings, "newconfig", LCB_LOG_##lvl, __FILE__, __LINE__
#define LOG(instance, lvlbase, msg) lcb_log(instance->settings, "newconfig", LCB_LOG_##lvlbase, __FILE__, __LINE__, msg)
#define SERVER_FMT "%s:%s (%p)"
#define SERVER_ARGS(s) (s)->get_host().host, (s)->get_host().port, (void *)s
typedef struct lcb_GUESSVB_st {
time_t last_update; /**< Last time this vBucket was heuristically set */
char newix; /**< New index, heuristically determined */
char oldix; /**< Original index, according to map */
char used; /**< Flag indicating whether or not this entry has been used */
} lcb_GUESSVB;
/* Ignore configuration updates for heuristically guessed vBuckets for a
* maximum amount of [n] seconds */
#define MAX_KEEP_GUESS 20
static int
should_keep_guess(lcb_GUESSVB *guess, lcbvb_VBUCKET *vb)
{
if (guess->newix == guess->oldix) {
/* Heuristic position is the same as starting position */
return 0;
}
if (vb->servers[0] != guess->oldix) {
/* Previous master changed */
return 0;
}
if (time(NULL) - guess->last_update > MAX_KEEP_GUESS) {
/* Last usage too old */
return 0;
}
return 1;
}
void
lcb_vbguess_newconfig(lcb_t instance, lcbvb_CONFIG *cfg, lcb_GUESSVB *guesses)
{
unsigned ii;
if (!guesses) {
return;
}
for (ii = 0; ii < cfg->nvb; ii++) {
lcb_GUESSVB *guess = guesses + ii;
lcbvb_VBUCKET *vb = cfg->vbuckets + ii;
if (!guess->used) {
continue;
}
/* IF: Heuristically learned a new index, _and_ the old index (which is
* known to be bad) is the same index stated by the new config */
if (should_keep_guess(guess, vb)) {
lcb_log(LOGARGS(instance, TRACE), "Keeping heuristically guessed index. VBID=%d. Current=%d. Old=%d.", ii, guess->newix, guess->oldix);
vb->servers[0] = guess->newix;
} else {
/* We don't reassign to the guess structure here. The idea is that
* we will simply use the new config. If this gives us problems, the
* config will re-learn again. */
lcb_log(LOGARGS(instance, TRACE), "Ignoring heuristically guessed index. VBID=%d. Current=%d. Old=%d. New=%d", ii, guess->newix, guess->oldix, vb->servers[0]);
guess->used = 0;
}
}
}
int
lcb_vbguess_remap(lcb_t instance, int vbid, int bad)
{
if (LCBT_SETTING(instance, vb_noguess)) {
int newix = lcbvb_nmv_remap_ex(LCBT_VBCONFIG(instance), vbid, bad, 0);
if (newix > -1 && newix != bad) {
lcb_log(LOGARGS(instance, TRACE), "Got new index from ffmap. VBID=%d. Old=%d. New=%d", vbid, bad, newix);
}
return newix;
} else {
lcb_GUESSVB *guesses = instance->vbguess;
if (!guesses) {
guesses = instance->vbguess =
reinterpret_cast< lcb_GUESSVB * >(calloc(LCBT_VBCONFIG(instance)->nvb, sizeof(lcb_GUESSVB)));
}
lcb_GUESSVB *guess = guesses + vbid;
int newix = lcbvb_nmv_remap_ex(LCBT_VBCONFIG(instance), vbid, bad, 1);
if (newix > -1 && newix != bad) {
guess->newix = newix;
guess->oldix = bad;
guess->used = 1;
guess->last_update = time(NULL);
lcb_log(LOGARGS(instance, TRACE), "Guessed new heuristic index VBID=%d. Old=%d. New=%d", vbid, bad, newix);
}
return newix;
}
}
/**
* Finds the index of an older server using the current config.
*
* This function is used to help reuse the server structures for memcached
* packets.
*
* @param oldconfig The old configuration. This is the configuration the
* old server is bound to
* @param newconfig The new configuration. This will be inspected for new
* nodes which may have been added, and ones which may have been removed.
* @param server The server to match
* @return The new index, or -1 if the current server is not present in the new
* config.
*/
static int
find_new_data_index(lcbvb_CONFIG *oldconfig, lcbvb_CONFIG* newconfig,
lcb::Server *server)
{
const char *old_datahost = lcbvb_get_hostport(oldconfig,
server->get_index(), LCBVB_SVCTYPE_DATA, LCBVB_SVCMODE_PLAIN);
if (!old_datahost) {
/* Old server had no data service */
return -1;
}
for (size_t ii = 0; ii < LCBVB_NSERVERS(newconfig); ii++) {
const char *new_datahost = lcbvb_get_hostport(newconfig, ii,
LCBVB_SVCTYPE_DATA, LCBVB_SVCMODE_PLAIN);
if (new_datahost && strcmp(new_datahost, old_datahost) == 0) {
return ii;
}
}
return -1;
}
static void
log_vbdiff(lcb_t instance, lcbvb_CONFIGDIFF *diff)
{
lcb_log(LOGARGS(instance, INFO), "Config Diff: [ vBuckets Modified=%d ], [Sequence Changed=%d]", diff->n_vb_changes, diff->sequence_changed);
if (diff->servers_added) {
for (char **curserver = diff->servers_added; *curserver; curserver++) {
lcb_log(LOGARGS(instance, INFO), "Detected server %s added", *curserver);
}
}
if (diff->servers_removed) {
for (char **curserver = diff->servers_removed; *curserver; curserver++) {
lcb_log(LOGARGS(instance, INFO), "Detected server %s removed", *curserver);
}
}
}
/**
* This callback is invoked for packet relocation twice. It tries to relocate
* commands to their destination server. Some commands may not be relocated
* either because they have no explicit "Relocation Information" (i.e. no
* specific vbucket) or because the command is tied to a specific server (i.e.
* CMD_STAT).
*
* Note that `KEEP_PACKET` here doesn't mean to "Save" the packet, but rather
* to keep the packet in the current queue (so that if the server ends up
* being removed, the command will fail); rather than being relocated to
* another server.
*/
static int
iterwipe_cb(mc_CMDQUEUE *cq, mc_PIPELINE *oldpl, mc_PACKET *oldpkt, void *)
{
protocol_binary_request_header hdr;
lcb::Server *srv = static_cast<lcb::Server *>(oldpl);
int newix;
mcreq_read_hdr(oldpkt, &hdr);
if (!lcb_should_retry(srv->get_settings(), oldpkt, LCB_MAX_ERROR)) {
return MCREQ_KEEP_PACKET;
}
if (LCBVB_DISTTYPE(cq->config) == LCBVB_DIST_VBUCKET) {
newix = lcbvb_vbmaster(cq->config, ntohs(hdr.request.vbucket));
} else {
const void *key = NULL;
lcb_SIZE nkey = 0;
int tmpid;
/* XXX: We ignore hashkey. This is going away soon, and is probably
* better than simply failing the items. */
mcreq_get_key(oldpkt, &key, &nkey);
lcbvb_map_key(cq->config, key, nkey, &tmpid, &newix);
}
if (newix < 0 || newix > (int)cq->npipelines-1) {
return MCREQ_KEEP_PACKET;
}
mc_PIPELINE *newpl = cq->pipelines[newix];
if (newpl == oldpl || newpl == NULL) {
return MCREQ_KEEP_PACKET;
}
lcb_log(LOGARGS((lcb_t)cq->cqdata, DEBUG), "Remapped packet %p (SEQ=%u) from " SERVER_FMT " to " SERVER_FMT,
(void*)oldpkt, oldpkt->opaque, SERVER_ARGS((lcb::Server*)oldpl), SERVER_ARGS((lcb::Server*)newpl));
/** Otherwise, copy over the packet and find the new vBucket to map to */
mc_PACKET *newpkt = mcreq_renew_packet(oldpkt);
newpkt->flags &= ~MCREQ_STATE_FLAGS;
mcreq_reenqueue_packet(newpl, newpkt);
mcreq_packet_handled(oldpl, oldpkt);
return MCREQ_REMOVE_PACKET;
}
static void
replace_config(lcb_t instance, lcbvb_CONFIG *oldconfig, lcbvb_CONFIG *newconfig)
{
mc_CMDQUEUE *cq = &instance->cmdq;
mc_PIPELINE **ppold, **ppnew;
unsigned ii, nold, nnew;
assert(LCBT_VBCONFIG(instance) == newconfig);
nnew = LCBVB_NSERVERS(newconfig);
ppnew = reinterpret_cast<mc_PIPELINE**>(calloc(nnew, sizeof(*ppnew)));
ppold = mcreq_queue_take_pipelines(cq, &nold);
/**
* Determine which existing servers are still part of the new cluster config
* and place it inside the new list.
*/
for (ii = 0; ii < nold; ii++) {
lcb::Server *cur = static_cast<lcb::Server *>(ppold[ii]);
int newix = find_new_data_index(oldconfig, newconfig, cur);
if (newix > -1) {
cur->set_new_index(newix);
ppnew[newix] = cur;
ppold[ii] = NULL;
lcb_log(LOGARGS(instance, INFO), "Reusing server " SERVER_FMT ". OldIndex=%d. NewIndex=%d", SERVER_ARGS(cur), ii, newix);
}
}
/**
* Once we've moved the kept servers to the new list, allocate new lcb::Server
* structures for slots that don't have an existing lcb::Server. We must do
* this before add_pipelines() is called, so that there are no holes inside
* ppnew
*/
for (ii = 0; ii < nnew; ii++) {
if (!ppnew[ii]) {
ppnew[ii] = new lcb::Server(instance, ii);
}
}
/**
* Once we have all the server structures in place for the new config,
* transfer the new config along with the new list over to the CQ structure.
*/
mcreq_queue_add_pipelines(cq, ppnew, nnew, newconfig);
for (ii = 0; ii < nnew; ii++) {
mcreq_iterwipe(cq, ppnew[ii], iterwipe_cb, NULL);
}
/**
* Go through all the servers that are to be removed and relocate commands
* from their queues into the new queues
*/
for (ii = 0; ii < nold; ii++) {
if (!ppold[ii]) {
continue;
}
mcreq_iterwipe(cq, ppold[ii], iterwipe_cb, NULL);
static_cast<lcb::Server*>(ppold[ii])->purge(LCB_MAP_CHANGED);
static_cast<lcb::Server*>(ppold[ii])->close();
}
for (ii = 0; ii < nnew; ii++) {
if (static_cast<lcb::Server*>(ppnew[ii])->has_pending()) {
ppnew[ii]->flush_start(ppnew[ii]);
}
}
free(ppnew);
free(ppold);
}
void lcb_update_vbconfig(lcb_t instance, lcb_pCONFIGINFO config)
{
lcb_configuration_t change_status;
lcb::clconfig::ConfigInfo *old_config = instance->cur_configinfo;
mc_CMDQUEUE *q = &instance->cmdq;
instance->cur_configinfo = config;
config->incref();
q->config = instance->cur_configinfo->vbc;
q->cqdata = instance;
if (old_config) {
lcbvb_CONFIGDIFF *diff = lcbvb_compare(old_config->vbc, config->vbc);
if (diff) {
log_vbdiff(instance, diff);
lcbvb_free_diff(diff);
}
/* Apply the vb guesses */
lcb_vbguess_newconfig(instance, config->vbc, instance->vbguess);
replace_config(instance, old_config->vbc, config->vbc);
old_config->decref();
change_status = LCB_CONFIGURATION_CHANGED;
} else {
size_t nservers = VB_NSERVERS(config->vbc);
std::vector<mc_PIPELINE*> servers;
for (size_t ii = 0; ii < nservers; ii++) {
servers.push_back(new lcb::Server(instance, ii));
}
mcreq_queue_add_pipelines(q, &servers[0], nservers, config->vbc);
change_status = LCB_CONFIGURATION_NEW;
}
/* Update the list of nodes here for server list */
instance->ht_nodes->clear();
for (size_t ii = 0; ii < LCBVB_NSERVERS(config->vbc); ++ii) {
const char *hp = lcbvb_get_hostport(config->vbc, ii,
LCBVB_SVCTYPE_MGMT, LCBVB_SVCMODE_PLAIN);
if (hp) {
instance->ht_nodes->add(hp, LCB_CONFIG_HTTP_PORT);
}
}
instance->callbacks.configuration(instance, change_status);
lcb_maybe_breakout(instance);
}
<|endoftext|> |
<commit_before>#include <mos/gfx/assets.hpp>
#include <cstring>
#include <filesystem/path.h>
#include <fstream>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/euler_angles.hpp>
#include <glm/gtx/io.hpp>
#include <glm/gtx/matrix_decompose.hpp>
#include <mos/util.hpp>
#include <iostream>
namespace mos {
namespace gfx {
using namespace nlohmann;
Assets::Assets(const std::string directory) : directory_(directory) {}
Assets::~Assets() {}
Model Assets::model_value(const std::string &base_path, const json &value) {
auto name = value.value("name", "");
auto mesh_name = std::string("");
if (!value["mesh"].is_null()) {
mesh_name = value.value("mesh", "");
}
std::string material_name = "";
if (!value["material"].is_null()) {
material_name = value.value("material", "");
}
auto transform = jsonarray_to_mat4(value["transform"]);
auto created_model = Model(
name, mesh(base_path + mesh_name),
transform,
material(base_path + material_name));
for (auto &m : value["children"]) {
std::string t = m;
created_model.models.push_back(model(base_path + t));
}
return created_model;
}
Model Assets::model(const std::string &path) {
std::cout << "Loading : " << path << std::endl;
filesystem::path fpath = path;
auto doc = json::parse(mos::text(directory_ + path));
return model_value(fpath.parent_path().empty() ? "" : fpath.parent_path().str() + "/", doc);
}
Animation Assets::animation(const std::string &path) {
auto doc = json::parse(mos::text(directory_ + path));
auto frame_rate = doc["frame_rate"];
std::map<unsigned int, std::shared_ptr<Mesh const>> keyframes;
for (auto &keyframe : doc["keyframes"]) {
auto key = keyframe["key"];
auto mesh_path = keyframe["mesh"];
keyframes.insert({key, mesh(mesh_path)});
}
Animation animation(keyframes, frame_rate);
return animation;
}
std::shared_ptr<Mesh> Assets::mesh(const std::string &path) {
if (meshes_.find(path) == meshes_.end()) {
meshes_.insert(MeshPair(path, Mesh::load(directory_ + path)));
}
return meshes_.at(path);
}
std::shared_ptr<Texture2D>
Assets::texture(const std::string &path,
const bool color_data,
const bool mipmaps,
const Texture2D::Wrap &wrap) {
if (!path.empty()) {
if (textures_.find(path) == textures_.end()) {
textures_.insert(TexturePair(path, Texture2D::load(directory_ + path, color_data, mipmaps, wrap)));
}
return textures_.at(path);
} else {
return std::shared_ptr<Texture2D>(nullptr);
}
}
Material Assets::material(const std::string &path) {
if (path.empty()) {
return Material();
} else {
filesystem::path fpath = path;
auto base_path = fpath.parent_path().empty() ? "" : fpath.parent_path().str() + "/";
if (fpath.extension() == "material") {
auto value = json::parse(mos::text(directory_ + fpath.str()));
auto read_texture = [&](const std::string &name, const bool color_data = true) {
std::string file_name = "";
if (!value[name].is_null()) {
file_name = value[name];
}
auto tex = file_name.empty() ? texture("") : texture(base_path + file_name, color_data);
return tex;
};
auto albedo_map = read_texture("albedo_map");
auto emission_map = read_texture("emission_map");
auto normal_map = read_texture("normal_map");
if (normal_map) {
if (normal_map->format == Texture::Format::SRGB){
normal_map->format = Texture::Format::RGB;
}
else if (normal_map->format == Texture::Format::SRGBA){
normal_map->format = Texture::Format::RGBA;
}
//normal_map->format = normal_map->format == Texture::Format::SRGB ? Texture::Format::RGB : Texture::Format::RGBA;
}
auto metallic_map = read_texture("metallic_map");
auto roughness_map = read_texture("roughness_map");
auto ambient_occlusion_map = read_texture("ambient_occlusion_map");
auto diffuse = glm::vec3(value["albedo"][0], value["albedo"][1], value["albedo"][2]);
auto opacity = value["opacity"];
auto roughness = value["roughness"];
auto metallic = value["metallic"];
auto emission = glm::vec3(value["emission"][0], value["emission"][1], value["emission"][2]);
auto ambient_occlusion = value["ambient_occlusion"];
return Material(albedo_map,
emission_map,
normal_map,
metallic_map,
roughness_map,
ambient_occlusion_map,
diffuse,
opacity,
roughness,
metallic,
emission);
} else {
throw std::runtime_error(path.substr(path.find_last_of(".")) +
" file format is not supported.");
}
}
}
Light Assets::light(const std::string &path) {
if (path.empty()) {
return Light();
} else {
filesystem::path fpath = path;
auto base_path = fpath.parent_path().empty() ? "" : fpath.parent_path().str() + "/";
if (fpath.extension() == "light") {
auto value = json::parse(mos::text(directory_ + fpath.str()));
auto transform = jsonarray_to_mat4(value["transform"]);
auto position = glm::vec3(transform[3]);
auto center = position + glm::vec3(transform * glm::vec4(0.0f, 0.0f, -1.0f, 0.0f));
std::string t = value["light"];
auto data_value = json::parse(mos::text(directory_ + t));
auto color = glm::vec3(data_value["color"][0],
data_value["color"][1],
data_value["color"][2]);
auto strength = data_value["strength"];
auto size = data_value["size"];
auto blend = value["blend"];
return Light(position,
center,
size,
color,
strength);
} else {
throw std::runtime_error(path.substr(path.find_last_of(".")) +
" file format is not supported.");
}
}
}
EnvironmentLight Assets::environment_light(const std::string &path) {
filesystem::path fpath = path;
auto base_path = fpath.parent_path().empty() ? "" : fpath.parent_path().str() + "/";
if (fpath.extension() == "environment_light") {
auto value = json::parse(mos::text(directory_ + fpath.str()));
auto transform = jsonarray_to_mat4(value["transform"]);
auto position = glm::vec3(transform[3]);
glm::vec3 scale;
glm::quat rotation;
glm::vec3 translation;
glm::vec3 skew;
glm::vec4 perspective;
glm::decompose(transform, scale, rotation, translation, skew, perspective);
auto extent = float(value["extent"]) * scale;
auto strength = value.value("strength", 1.0f);
auto resolution = value.value("resolution", 128.0f);
return EnvironmentLight(position,
extent,
strength,
glm::uvec2(resolution));
} else {
throw std::runtime_error(path.substr(path.find_last_of(".")) +
" file format is not supported.");
}
}
void Assets::clear_unused() {
for (auto it = textures_.begin(); it != textures_.end();) {
if (it->second.use_count() <= 1) {
textures_.erase(it++);
} else {
++it;
}
}
for (auto it = meshes_.begin(); it != meshes_.end();) {
if (it->second.use_count() <= 1) {
meshes_.erase(it++);
} else {
++it;
}
}
}
}
}
<commit_msg>Formatting<commit_after>#include <mos/gfx/assets.hpp>
#include <cstring>
#include <filesystem/path.h>
#include <fstream>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/euler_angles.hpp>
#include <glm/gtx/io.hpp>
#include <glm/gtx/matrix_decompose.hpp>
#include <mos/util.hpp>
#include <iostream>
namespace mos {
namespace gfx {
using namespace nlohmann;
Assets::Assets(const std::string directory) : directory_(directory) {}
Assets::~Assets() {}
Model Assets::model_value(const std::string &base_path, const json &value) {
auto name = value.value("name", "");
auto mesh_name = std::string("");
if (!value["mesh"].is_null()) {
mesh_name = value.value("mesh", "");
}
std::string material_name = "";
if (!value["material"].is_null()) {
material_name = value.value("material", "");
}
auto transform = jsonarray_to_mat4(value["transform"]);
auto created_model = Model(
name, mesh(base_path + mesh_name),
transform,
material(base_path + material_name));
for (auto &m : value["children"]) {
std::string t = m;
created_model.models.push_back(model(base_path + t));
}
return created_model;
}
Model Assets::model(const std::string &path) {
std::cout << "Loading: " << path << std::endl;
filesystem::path fpath = path;
auto doc = json::parse(mos::text(directory_ + path));
return model_value(fpath.parent_path().empty() ? "" : fpath.parent_path().str() + "/", doc);
}
Animation Assets::animation(const std::string &path) {
auto doc = json::parse(mos::text(directory_ + path));
auto frame_rate = doc["frame_rate"];
std::map<unsigned int, std::shared_ptr<Mesh const>> keyframes;
for (auto &keyframe : doc["keyframes"]) {
auto key = keyframe["key"];
auto mesh_path = keyframe["mesh"];
keyframes.insert({key, mesh(mesh_path)});
}
Animation animation(keyframes, frame_rate);
return animation;
}
std::shared_ptr<Mesh> Assets::mesh(const std::string &path) {
if (meshes_.find(path) == meshes_.end()) {
meshes_.insert(MeshPair(path, Mesh::load(directory_ + path)));
}
return meshes_.at(path);
}
std::shared_ptr<Texture2D>
Assets::texture(const std::string &path,
const bool color_data,
const bool mipmaps,
const Texture2D::Wrap &wrap) {
if (!path.empty()) {
if (textures_.find(path) == textures_.end()) {
textures_.insert(TexturePair(path, Texture2D::load(directory_ + path, color_data, mipmaps, wrap)));
}
return textures_.at(path);
} else {
return std::shared_ptr<Texture2D>(nullptr);
}
}
Material Assets::material(const std::string &path) {
if (path.empty()) {
return Material();
} else {
filesystem::path fpath = path;
auto base_path = fpath.parent_path().empty() ? "" : fpath.parent_path().str() + "/";
if (fpath.extension() == "material") {
auto value = json::parse(mos::text(directory_ + fpath.str()));
auto read_texture = [&](const std::string &name, const bool color_data = true) {
std::string file_name = "";
if (!value[name].is_null()) {
file_name = value[name];
}
auto tex = file_name.empty() ? texture("") : texture(base_path + file_name, color_data);
return tex;
};
auto albedo_map = read_texture("albedo_map");
auto emission_map = read_texture("emission_map");
auto normal_map = read_texture("normal_map");
if (normal_map) {
if (normal_map->format == Texture::Format::SRGB){
normal_map->format = Texture::Format::RGB;
}
else if (normal_map->format == Texture::Format::SRGBA){
normal_map->format = Texture::Format::RGBA;
}
//normal_map->format = normal_map->format == Texture::Format::SRGB ? Texture::Format::RGB : Texture::Format::RGBA;
}
auto metallic_map = read_texture("metallic_map");
auto roughness_map = read_texture("roughness_map");
auto ambient_occlusion_map = read_texture("ambient_occlusion_map");
auto diffuse = glm::vec3(value["albedo"][0], value["albedo"][1], value["albedo"][2]);
auto opacity = value["opacity"];
auto roughness = value["roughness"];
auto metallic = value["metallic"];
auto emission = glm::vec3(value["emission"][0], value["emission"][1], value["emission"][2]);
auto ambient_occlusion = value["ambient_occlusion"];
return Material(albedo_map,
emission_map,
normal_map,
metallic_map,
roughness_map,
ambient_occlusion_map,
diffuse,
opacity,
roughness,
metallic,
emission);
} else {
throw std::runtime_error(path.substr(path.find_last_of(".")) +
" file format is not supported.");
}
}
}
Light Assets::light(const std::string &path) {
if (path.empty()) {
return Light();
} else {
filesystem::path fpath = path;
auto base_path = fpath.parent_path().empty() ? "" : fpath.parent_path().str() + "/";
if (fpath.extension() == "light") {
auto value = json::parse(mos::text(directory_ + fpath.str()));
auto transform = jsonarray_to_mat4(value["transform"]);
auto position = glm::vec3(transform[3]);
auto center = position + glm::vec3(transform * glm::vec4(0.0f, 0.0f, -1.0f, 0.0f));
std::string t = value["light"];
auto data_value = json::parse(mos::text(directory_ + t));
auto color = glm::vec3(data_value["color"][0],
data_value["color"][1],
data_value["color"][2]);
auto strength = data_value["strength"];
auto size = data_value["size"];
auto blend = value["blend"];
return Light(position,
center,
size,
color,
strength);
} else {
throw std::runtime_error(path.substr(path.find_last_of(".")) +
" file format is not supported.");
}
}
}
EnvironmentLight Assets::environment_light(const std::string &path) {
filesystem::path fpath = path;
auto base_path = fpath.parent_path().empty() ? "" : fpath.parent_path().str() + "/";
if (fpath.extension() == "environment_light") {
auto value = json::parse(mos::text(directory_ + fpath.str()));
auto transform = jsonarray_to_mat4(value["transform"]);
auto position = glm::vec3(transform[3]);
glm::vec3 scale;
glm::quat rotation;
glm::vec3 translation;
glm::vec3 skew;
glm::vec4 perspective;
glm::decompose(transform, scale, rotation, translation, skew, perspective);
auto extent = float(value["extent"]) * scale;
auto strength = value.value("strength", 1.0f);
auto resolution = value.value("resolution", 128.0f);
return EnvironmentLight(position,
extent,
strength,
glm::uvec2(resolution));
} else {
throw std::runtime_error(path.substr(path.find_last_of(".")) +
" file format is not supported.");
}
}
void Assets::clear_unused() {
for (auto it = textures_.begin(); it != textures_.end();) {
if (it->second.use_count() <= 1) {
textures_.erase(it++);
} else {
++it;
}
}
for (auto it = meshes_.begin(); it != meshes_.end();) {
if (it->second.use_count() <= 1) {
meshes_.erase(it++);
} else {
++it;
}
}
}
}
}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "Texture.h"
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
using namespace glm;
namespace softlit
{
Image::Image(const std::string & fileName)
{
m_data = stbi_load(fileName.c_str(), &m_width, &m_height, &m_numChannels, 0);
}
Image::~Image()
{
stbi_image_free(m_data);
m_data = nullptr;
}
Texture::Texture(const Image& image)
: m_image(image)
{
}
Texture::~Texture()
{
}
template<>
glm::vec4 Texture::Sample<TextureSampler::SAMPLE_RGBA>(const glm::vec2& uv) const
{
DBG_ASSERT(m_image.m_numChannels == 4);
//TODO: FILTER!!!
uint32_t idxS = (uint32_t)glm::floor(uv.s * m_image.m_width);
uint32_t idxT = (uint32_t)glm::floor(uv.t * m_image.m_height);
uint32_t idx = (idxT * m_image.m_width + idxS) * m_image.m_numChannels;
float g = (float)(m_image.m_data[idx++]);
float b = (float)(m_image.m_data[idx++]);
float r = (float)(m_image.m_data[idx++]);
float a = (float)(m_image.m_data[idx++]);
return glm::vec4(r, g, b, a) * g_texColDiv;
}
template<>
glm::vec3 Texture::Sample<TextureSampler::SAMPLE_RGB>(const glm::vec2& uv) const
{
DBG_ASSERT(m_image.m_numChannels == 3);
//TODO: FILTER!!!
uint32_t idxS = (uint32_t)glm::floor(uv.s * m_image.m_width);
uint32_t idxT = (uint32_t)glm::floor(uv.t * m_image.m_height);
uint32_t idx = (idxT * m_image.m_width + idxS) * m_image.m_numChannels;
float r = (float)(m_image.m_data[idx++]);
float g = (float)(m_image.m_data[idx++]);
float b = (float)(m_image.m_data[idx++]);
return glm::vec3(r, g, b) * g_texColDiv;
}
}<commit_msg>Fix wrong order in RGBA texel fetch<commit_after>#include "stdafx.h"
#include "Texture.h"
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
using namespace glm;
namespace softlit
{
Image::Image(const std::string & fileName)
{
m_data = stbi_load(fileName.c_str(), &m_width, &m_height, &m_numChannels, 0);
}
Image::~Image()
{
stbi_image_free(m_data);
m_data = nullptr;
}
Texture::Texture(const Image& image)
: m_image(image)
{
}
Texture::~Texture()
{
}
template<>
glm::vec4 Texture::Sample<TextureSampler::SAMPLE_RGBA>(const glm::vec2& uv) const
{
DBG_ASSERT(m_image.m_numChannels == 4);
//TODO: FILTER!!!
uint32_t idxS = (uint32_t)glm::floor(uv.s * m_image.m_width);
uint32_t idxT = (uint32_t)glm::floor(uv.t * m_image.m_height);
uint32_t idx = (idxT * m_image.m_width + idxS) * m_image.m_numChannels;
float r = (float)(m_image.m_data[idx++]);
float g = (float)(m_image.m_data[idx++]);
float b = (float)(m_image.m_data[idx++]);
float a = (float)(m_image.m_data[idx++]);
return glm::vec4(r, g, b, a) * g_texColDiv;
}
template<>
glm::vec3 Texture::Sample<TextureSampler::SAMPLE_RGB>(const glm::vec2& uv) const
{
DBG_ASSERT(m_image.m_numChannels == 3);
//TODO: FILTER!!!
uint32_t idxS = (uint32_t)glm::floor(uv.s * m_image.m_width);
uint32_t idxT = (uint32_t)glm::floor(uv.t * m_image.m_height);
uint32_t idx = (idxT * m_image.m_width + idxS) * m_image.m_numChannels;
float r = (float)(m_image.m_data[idx++]);
float g = (float)(m_image.m_data[idx++]);
float b = (float)(m_image.m_data[idx++]);
return glm::vec3(r, g, b) * g_texColDiv;
}
}<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <limits>
#include "consoleui.h"
using namespace std;
const char TAB = '\t';
ConsoleUI::ConsoleUI()
{
WelcomeMenu();
}
void ConsoleUI::WelcomeMenu()
{
cout << endl;
cout << endl;
cout << TAB << "----------------------------------------------------------------------------" << endl;
cout << TAB << TAB << TAB << " Welcome! This program will store or show" << endl;
cout << TAB << TAB << TAB << " famous computer scientists. " << endl;
cout << TAB << "----------------------------------------------------------------------------" << endl;
cout << endl;
}
void ConsoleUI::features()
{
cout << TAB << "----------------------------------------------------------------------------" << endl;
cout << TAB << " ___ ___ __________ ____ ___ ___ ___" << endl;
cout << TAB << " / \\\\ / \\\\ | ______|| | \\\\ | || | || | ||" << endl;
cout << TAB << " / \\\\ / \\\\ | ||__ | \\\\| || | || | ||" << endl;
cout << TAB << " / /\\ \\\\/ /\\ \\\\ | ___|| | |\\ \\| || | || | ||" << endl;
cout << TAB << " / // \\ // \\ \\\\ | ||_____ | ||\\ || | \\\\_/ ||" << endl;
cout << TAB << "/__// \\___// \\__\\\\|_________|| |__|| \\___|| \\________//" << endl;
cout << TAB << "----------------------------------------------------------------------------" << endl;
cout << TAB << "The list below shows you all possible features on what you can do." << endl;
cout << endl;
cout << TAB << "press H to show all options" << endl; //eitthvað svona er sniðgt;
cout << TAB << "Press 1 to create a new scientist." << endl;
cout << TAB << "Press 2 to list all scientists." << endl;
cout << TAB << "Press 3 to search for a scientist." << endl;
cout << TAB << "Press 4 to get the database stats" << endl;
cout << TAB << "Press Q to quit the program." << endl;
cout << TAB << "----------------------------------------------------------------------------" << endl;
cout << endl;
}
void ConsoleUI::readScientists()
{
Scientist temp;
string tempName;
cout << TAB << "Please enter a name: ";
getline(cin, tempName);
do
{
if(tempName.empty())
{
cout << TAB << "You cannot enter an empty name. Please try again: ";
ws(cin);
getline(cin, tempName);
}
}
while(tempName.empty());
temp.setName(tempName);
bool validGender = false;
string tempGender;
string gender;
cout << TAB << "Please enter the gender(M for male, F for female): ";
while(validGender == false)
{
ws(cin);
getline(cin, gender);
if(gender != "M" && gender != "m" && gender != "F" && gender != "f")
{
cout << TAB << gender << " is not a valid option" << endl;
cout << TAB <<"Please enter a valid option: ";
}
if(gender == "M"||gender== "m")
{
tempGender = "Male";
temp.setGender(tempGender);
validGender = true;
}
else if(gender == "F" || gender == "f")
{
tempGender = "Female";
temp.setGender(tempGender);
validGender = true;
}
}
int tempDateOfBirth = 2017;
int tempDateOfDeath = -1;
cout << TAB << "Please enter a year of birth: ";
cin >> tempDateOfBirth;
do
{
if(tempDateOfBirth > 2016)
{
cout << TAB << "Invalid date. Please try again: ";
cin >> tempDateOfBirth;
}
else if(tempDateOfBirth < 0)
{
cout << TAB << "A person cannot have a negative date of birth. Please try again: ";
cin >> tempDateOfBirth;
}
}while(tempDateOfBirth > 2016 || tempDateOfBirth < 0);
do
{
if(!cin)
{
while((!cin))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << TAB << "That is not a date, please try again: ";
cin >> tempDateOfBirth;
}
}
}while(tempDateOfBirth > 2016 && tempDateOfBirth < 0);
temp.setDateOfBirth(tempDateOfBirth);
cout << TAB << "Please enter a year of death(Enter 0 if the scientist is still alive): ";
cin >> tempDateOfDeath;
do
{
if(!cin)
{
while((!cin))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << TAB << "Invalid date, that is not a year, try again: " << endl;
cout << TAB << "Please enter a year of death(Enter 0 if the scientist is still alive): ";
cin >> tempDateOfDeath;
}
}
else if(((tempDateOfDeath < tempDateOfBirth)&&(tempDateOfDeath != 0)) || (tempDateOfDeath > 2017))
{
cout << TAB << "Not possible. A person cannot die before it is born, try again: ";
cin >> tempDateOfDeath;
cout << TAB << "Please enter a year of death(Enter 0 if the scientist is still alive): ";
cin.clear();
cin >> tempDateOfDeath;
}
}
while((tempDateOfDeath < tempDateOfBirth)&&(tempDateOfDeath != 0));
do
{
if(tempDateOfDeath > 2016)
{
cout << TAB << "Not possible. A person cannot die beyond the current year, try again: ";
cin >> tempDateOfDeath;
}
}while((tempDateOfDeath < tempDateOfBirth)&&(tempDateOfDeath != 0));
temp.setDateOfDeath(tempDateOfDeath);
cout << endl;
char cont;
cout << TAB << "Do you want to add another scientist? Press Y/y for yes or N/n for no: ";
cin >> cont;
if(cont == 'y' || cont == 'Y')
{
readScientists();
}
else
{
features();
}
service.create(temp);
}
void ConsoleUI::display(vector<Scientist> scientists)
{
cout << "\t Information about all listed scientists" << endl;
cout << "\t___________________________________________________________________________" << endl;
for(size_t i = 0; i < scientists.size(); i++)
{
int tempAge;
if (scientists[i].getDateOfDeath() != 0)
{
tempAge = scientists[i].getDateOfDeath() - scientists[i].getDateOfBirth();
}
else
{
tempAge = 2016 - scientists[i].getDateOfBirth();
}
cout << "\t |Name: " << scientists[i].getName() << endl;
cout << "\t |Gender: " << scientists[i].getGender() << endl;
cout << "\t |Born: " << scientists[i].getDateOfBirth() << endl;
if(scientists[i].getDateOfDeath() == 0)
{
cout << "\t |Age: " << tempAge << endl;
cout << "\t |Still alive " << endl;
}
else
{
cout << "\t |Died: " << scientists[i].getDateOfDeath() << endl;
cout << "\t |Died at the age of " << tempAge << endl;
}
cout << TAB << "----------------------------------------------------------------------------" << endl;
}
}
void ConsoleUI::displayListOfScientistsAlpha()
{
vector<Scientist> scientists = service.getScientistsAlpha();
display(scientists);
}
void ConsoleUI::displayListOfScientistsYoung()
{
vector<Scientist> scientists = service.getScientistsYoung();
display(scientists);
}
void ConsoleUI::displayListOfScientistsOld()
{
vector<Scientist> scientists = service.getScientistsOld();
display(scientists);
}
void ConsoleUI::searchName()
{
string name;
cout << TAB << "Enter the name of the scientist you want to find: ";
cin.ignore();
getline(cin, name);
vector<Scientist> temp = service.searchName(name);
if(temp.size() == 0)
{
cout << TAB << "There is no scientist with the name " << name << " in our data, please try again: " << endl;
}
else
{
display(temp);
}
}
void ConsoleUI::searchDateOfBirth()
{
int year = 0;
cout << TAB << "Enter the scientists year of birth: ";
cin >> year;
vector<Scientist> temp = service.searchDateOfBirth(year);
if(temp.size() == 0)
{
cout << TAB << "There is no scientist in our database with that date of birth, please try again: " << endl;
}
else
{
display(temp);
}
}
void ConsoleUI::searchGender()
{
char gender;
cout << TAB << "Please enter a gender(M for male, F for female): " << endl;
cout << TAB;
cin >> gender;
vector<Scientist> temp = service.searchGender(gender);
if(temp.size() == 0)
{
if(gender == 'M' || gender == 'm')
{
cout << TAB << "There are no male scientists. " << endl;
}
if(gender == 'F' || gender == 'f')
{
cout << TAB << "There are no female scientists. " << endl;
}
}
else
{
display(temp);
}
}
void ConsoleUI::searchRandomScientist()
{
vector<Scientist> temp = service.searchRandom();
display(temp);
}
void ConsoleUI::stats()
{
size_t dead;
vector<Scientist> males = service.searchGender('M');
vector<Scientist> females = service.searchGender('F');
vector<Scientist> alive = service.searchDateOfDeath(0);
vector<Scientist> total = service.getScientists();
dead = total.size() - alive.size();
cout << TAB << "---------------------------" << endl;
cout << TAB << "The database consists of:" << endl;
cout << TAB << males.size() << " male scientists" << endl;
cout << TAB << females.size() << " female scientists" << endl;
cout << TAB << alive.size() << " alive scientists" << endl;
cout << TAB << dead << " dead scientists" << endl;
cout << TAB << "----------------------------" << endl << endl;
}
void ConsoleUI::listOrSortScientist()
{
string CHOICE = "/0";
while(CHOICE[0] != 'q' && CHOICE[0] != 'Q')
{
vector<Scientist> temp = service.getScientists();
cout << TAB << "Please choose a feature: ";
ws(cin);
getline(cin, CHOICE);
if(CHOICE.length() > 1)
{
cout << TAB << "invalid input" << endl;
}
else
{
if(CHOICE[0] == 'h' || CHOICE[0] == 'H')
{
features();
}
else if(CHOICE[0] == '1')
{
cout << endl;
cout << TAB << ">>> Reading Scientists <<<" << endl << endl;
readScientists();
}
else if(CHOICE[0] == '2')
{
char sort;
cout << endl;
cout << TAB << "How should the list be sorted?" << endl;
cout << TAB << "Press 1 for alphabetical order." << endl;
cout << TAB << "Press 2 to sort from youngest to oldest." << endl;
cout << TAB << "Press 3 to sort from oldest to youngest." << endl;
cout << TAB << "Press any other number to go BACK to the menu." << endl;
cout << TAB << "" << endl;
cout << TAB << "----------------------------------------------------------------------------" << endl;
cout << TAB;
cin >> sort;
if(sort == '1')
{
displayListOfScientistsAlpha();
}
else if(sort == '2')
{
displayListOfScientistsYoung();
}
else if(sort == '3')
{
displayListOfScientistsOld();
}
else
{
features();
}
}
else if(CHOICE[0] == '3')
{
char searchOptions;
cout << endl;
cout << TAB << "What do you want to search for?" << endl;
cout << TAB << "Press 1 to search for a scientist witch a specific name." << endl;
cout << TAB << "Press 2 to search for all scientists born in a specific year." << endl;
cout << TAB << "Press 3 to search for all scientists with a specific gender." << endl;
cout << TAB << "Press 4 to search for a random Scientist." << endl;
cout << TAB << "Press any other number to go BACK to the menu." << endl;
cout << TAB << "" << endl;
cout << TAB << "----------------------------------------------------------------------------" << endl;
cout << TAB;
cin >> searchOptions;
if(searchOptions == '1')
{
searchName();
}
else if(searchOptions == '2')
{
searchDateOfBirth();
}
else if(searchOptions == '3')
{
searchGender();
}
else if(searchOptions == '4')
{
searchRandomScientist();
}
else
{
features();
}
}
else if(CHOICE[0] == '4')
{
stats();
}
else if(CHOICE[0] == 'q' || CHOICE[0] == 'Q')
{
break;
}
else
{
cout << TAB << "invalid input" << endl;
}
}
}
}
<commit_msg>Final<commit_after>#include <iostream>
#include <string>
#include <limits>
#include "consoleui.h"
using namespace std;
const char TAB = '\t';
ConsoleUI::ConsoleUI()
{
WelcomeMenu();
}
void ConsoleUI::WelcomeMenu()
{
cout << endl;
cout << endl;
cout << TAB << "----------------------------------------------------------------------------" << endl;
cout << TAB << TAB << TAB << " Welcome! This program will store or show" << endl;
cout << TAB << TAB << TAB << " famous computer scientists. " << endl;
cout << TAB << "----------------------------------------------------------------------------" << endl;
cout << endl;
}
void ConsoleUI::features()
{
cout << TAB << "----------------------------------------------------------------------------" << endl;
cout << TAB << " ___ ___ __________ ____ ___ ___ ___" << endl;
cout << TAB << " / \\\\ / \\\\ | ______|| | \\\\ | || | || | ||" << endl;
cout << TAB << " / \\\\ / \\\\ | ||__ | \\\\| || | || | ||" << endl;
cout << TAB << " / /\\ \\\\/ /\\ \\\\ | ___|| | |\\ \\| || | || | ||" << endl;
cout << TAB << " / // \\ // \\ \\\\ | ||_____ | ||\\ || | \\\\_/ ||" << endl;
cout << TAB << "/__// \\___// \\__\\\\|_________|| |__|| \\___|| \\________//" << endl;
cout << TAB << "----------------------------------------------------------------------------" << endl;
cout << TAB << "The list below shows you all possible features on what you can do." << endl;
cout << endl;
cout << TAB << "press H to show all options" << endl; //eitthvað svona er sniðgt;
cout << TAB << "Press 1 to create a new scientist." << endl;
cout << TAB << "Press 2 to list all scientists." << endl;
cout << TAB << "Press 3 to search for a scientist." << endl;
cout << TAB << "Press 4 to get the database stats" << endl;
cout << TAB << "Press Q to quit the program." << endl;
cout << TAB << "----------------------------------------------------------------------------" << endl;
cout << endl;
}
void ConsoleUI::readScientists()
{
Scientist temp;
string tempName;
cout << TAB << "Please enter a name: ";
getline(cin, tempName);
do
{
if(tempName.empty())
{
cout << TAB << "You cannot enter an empty name. Please try again: ";
ws(cin);
getline(cin, tempName);
}
}
while(tempName.empty());
temp.setName(tempName);
bool validGender = false;
string tempGender;
string gender;
cout << TAB << "Please enter the gender(M for male, F for female): ";
while(validGender == false)
{
ws(cin);
getline(cin, gender);
if(gender != "M" && gender != "m" && gender != "F" && gender != "f")
{
cout << TAB << gender << " is not a valid option" << endl;
cout << TAB <<"Please enter a valid option: ";
}
if(gender == "M"||gender== "m")
{
tempGender = "Male";
temp.setGender(tempGender);
validGender = true;
}
else if(gender == "F" || gender == "f")
{
tempGender = "Female";
temp.setGender(tempGender);
validGender = true;
}
}
int tempDateOfBirth = 2017;
int tempDateOfDeath = -1;
cout << TAB << "Please enter a year of birth: ";
cin >> tempDateOfBirth;
do
{
if(tempDateOfBirth > 2016)
{
cout << TAB << "Invalid date. Please try again: ";
cin >> tempDateOfBirth;
}
else if(tempDateOfBirth < 0)
{
cout << TAB << "A person cannot have a negative date of birth. Please try again: ";
cin >> tempDateOfBirth;
}
}while(tempDateOfBirth > 2016 || tempDateOfBirth < 0);
do
{
if(tempDateOfBirth > 2016)
{
cout << TAB << "Invalid date. Please try again: ";
cin >> tempDateOfBirth;
}
else if(tempDateOfBirth < 0)
{
cout << TAB << "A person cannot have a negative date of birth. Please try again: ";
cin >> tempDateOfBirth;
}
}while(tempDateOfBirth > 2016 || tempDateOfBirth < 0);
do
{
if(!cin)
{
while((!cin))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << TAB << "That is not a date, please try again: ";
cin >> tempDateOfBirth;
}
}
}while(tempDateOfBirth > 2016 && tempDateOfBirth < 0);
temp.setDateOfBirth(tempDateOfBirth);
cout << TAB << "Please enter a year of death(Enter 0 if the scientist is still alive): ";
cin >> tempDateOfDeath;
do
{
if(!cin)
{
while((!cin))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << TAB << "Invalid date, that is not a year, try again: ";
cin >> tempDateOfDeath;
}
}
else if((tempDateOfDeath < tempDateOfBirth)&&(tempDateOfDeath != 0) && (tempDateOfDeath < 2017))
{
cout << TAB << "Not possible. A person cannot die before it is born, try again: ";
cin >> tempDateOfDeath;
cin.clear();
}
}
while((tempDateOfDeath < tempDateOfBirth)&&(tempDateOfDeath != 0));
do
{
if(tempDateOfDeath > 2016)
{
cout << TAB << "Not possible. A person cannot die beyond the current year, try again: ";
cin >> tempDateOfDeath;
}
}while((tempDateOfDeath < tempDateOfBirth)&&(tempDateOfDeath != 0));
temp.setDateOfDeath(tempDateOfDeath);
cout << endl;
char cont;
cout << TAB << "Do you want to add another scientist? Press Y/y for yes or N/n for no: ";
cin >> cont;
if(cont == 'y' || cont == 'Y')
{
readScientists();
}
else
{
features();
}
service.create(temp);
}
void ConsoleUI::display(vector<Scientist> scientists)
{
cout << "\t Information about all listed scientists" << endl;
cout << "\t___________________________________________________________________________" << endl;
for(size_t i = 0; i < scientists.size(); i++)
{
int tempAge;
if (scientists[i].getDateOfDeath() != 0)
{
tempAge = scientists[i].getDateOfDeath() - scientists[i].getDateOfBirth();
}
else
{
tempAge = 2016 - scientists[i].getDateOfBirth();
}
cout << "\t |Name: " << scientists[i].getName() << endl;
cout << "\t |Gender: " << scientists[i].getGender() << endl;
cout << "\t |Born: " << scientists[i].getDateOfBirth() << endl;
if(scientists[i].getDateOfDeath() == 0)
{
cout << "\t |Age: " << tempAge << endl;
cout << "\t |Still alive " << endl;
}
else
{
cout << "\t |Died: " << scientists[i].getDateOfDeath() << endl;
cout << "\t |Died at the age of " << tempAge << endl;
}
cout << TAB << "----------------------------------------------------------------------------" << endl;
}
}
void ConsoleUI::displayListOfScientistsAlpha()
{
vector<Scientist> scientists = service.getScientistsAlpha();
display(scientists);
}
void ConsoleUI::displayListOfScientistsYoung()
{
vector<Scientist> scientists = service.getScientistsYoung();
display(scientists);
}
void ConsoleUI::displayListOfScientistsOld()
{
vector<Scientist> scientists = service.getScientistsOld();
display(scientists);
}
void ConsoleUI::searchName()
{
string name;
cout << TAB << "Enter the name of the scientist you want to find: ";
cin.ignore();
getline(cin, name);
vector<Scientist> temp = service.searchName(name);
if(temp.size() == 0)
{
cout << TAB << "There is no scientist with the name " << name << " in our data, please try again: " << endl;
}
else
{
display(temp);
}
}
void ConsoleUI::searchDateOfBirth()
{
int year = 0;
cout << TAB << "Enter the scientists year of birth: ";
cin >> year;
vector<Scientist> temp = service.searchDateOfBirth(year);
if(temp.size() == 0)
{
cout << TAB << "There is no scientist in our database with that date of birth, please try again: " << endl;
}
else
{
display(temp);
}
}
void ConsoleUI::searchGender()
{
char gender;
cout << TAB << "Please enter a gender(M for male, F for female): " << endl;
cout << TAB;
cin >> gender;
vector<Scientist> temp = service.searchGender(gender);
if(temp.size() == 0)
{
if(gender == 'M' || gender == 'm')
{
cout << TAB << "There are no male scientists. " << endl;
}
if(gender == 'F' || gender == 'f')
{
cout << TAB << "There are no female scientists. " << endl;
}
}
else
{
display(temp);
}
}
void ConsoleUI::searchRandomScientist()
{
vector<Scientist> temp = service.searchRandom();
display(temp);
}
void ConsoleUI::stats()
{
size_t dead;
vector<Scientist> males = service.searchGender('M');
vector<Scientist> females = service.searchGender('F');
vector<Scientist> alive = service.searchDateOfDeath(0);
vector<Scientist> total = service.getScientists();
dead = total.size() - alive.size();
cout << TAB << "---------------------------" << endl;
cout << TAB << "The database consists of:" << endl;
cout << TAB << males.size() << " male scientists" << endl;
cout << TAB << females.size() << " female scientists" << endl;
cout << TAB << alive.size() << " alive scientists" << endl;
cout << TAB << dead << " dead scientists" << endl;
cout << TAB << "----------------------------" << endl << endl;
}
void ConsoleUI::listOrSortScientist()
{
string CHOICE = "/0";
while(CHOICE[0] != 'q' && CHOICE[0] != 'Q')
{
vector<Scientist> temp = service.getScientists();
cout << TAB << "Please choose a feature: ";
ws(cin);
getline(cin, CHOICE);
if(CHOICE.length() > 1)
{
cout << TAB << "invalid input" << endl;
}
else
{
if(CHOICE[0] == 'h' || CHOICE[0] == 'H')
{
features();
}
else if(CHOICE[0] == '1')
{
cout << endl;
cout << TAB << ">>> Reading Scientists <<<" << endl << endl;
readScientists();
}
else if(CHOICE[0] == '2')
{
char sort;
cout << endl;
cout << TAB << "How should the list be sorted?" << endl;
cout << TAB << "Press 1 for alphabetical order." << endl;
cout << TAB << "Press 2 to sort from youngest to oldest." << endl;
cout << TAB << "Press 3 to sort from oldest to youngest." << endl;
cout << TAB << "Press any other number to go BACK to the menu." << endl;
cout << TAB << "" << endl;
cout << TAB << "----------------------------------------------------------------------------" << endl;
cout << TAB;
cin >> sort;
if(sort == '1')
{
displayListOfScientistsAlpha();
}
else if(sort == '2')
{
displayListOfScientistsYoung();
}
else if(sort == '3')
{
displayListOfScientistsOld();
}
else
{
features();
}
}
else if(CHOICE[0] == '3')
{
char searchOptions;
cout << endl;
cout << TAB << "What do you want to search for?" << endl;
cout << TAB << "Press 1 to search for a scientist witch a specific name." << endl;
cout << TAB << "Press 2 to search for all scientists born in a specific year." << endl;
cout << TAB << "Press 3 to search for all scientists with a specific gender." << endl;
cout << TAB << "Press 4 to search for a random Scientist." << endl;
cout << TAB << "Press any other number to go BACK to the menu." << endl;
cout << TAB << "" << endl;
cout << TAB << "----------------------------------------------------------------------------" << endl;
cout << TAB;
cin >> searchOptions;
if(searchOptions == '1')
{
searchName();
}
else if(searchOptions == '2')
{
searchDateOfBirth();
}
else if(searchOptions == '3')
{
searchGender();
}
else if(searchOptions == '4')
{
searchRandomScientist();
}
else
{
features();
}
}
else if(CHOICE[0] == '4')
{
stats();
}
else if(CHOICE[0] == 'q' || CHOICE[0] == 'Q')
{
break;
}
else
{
cout << TAB << "invalid input" << endl;
}
}
}
}
<|endoftext|> |
<commit_before><commit_msg>Add unit test to check for zero length dir in FTP PWD response. <commit_after><|endoftext|> |
<commit_before>/// HEADER
#include "dynamic_transform.h"
/// COMPONENT
#include <csapex_transform/transform_message.h>
#include <csapex_transform/time_stamp_message.h>
#include "listener.h"
/// PROJECT
#include <csapex/msg/output.h>
#include <csapex/msg/input.h>
#include <utils_param/parameter_factory.h>
#include <csapex/model/node_modifier.h>
#include <csapex/utility/register_apex_plugin.h>
/// SYSTEM
#include <tf/transform_datatypes.h>
CSAPEX_REGISTER_CLASS(csapex::DynamicTransform, csapex::Node)
using namespace csapex;
DynamicTransform::DynamicTransform()
: init_(false)
{
}
void DynamicTransform::setupParameters()
{
std::vector<std::string> topics;
addParameter(param::ParameterFactory::declareParameterStringSet("from", topics), boost::bind(&DynamicTransform::update, this));
addParameter(param::ParameterFactory::declareParameterStringSet("to", topics), boost::bind(&DynamicTransform::update, this));
addParameter(param::ParameterFactory::declareTrigger("refresh"), boost::bind(&DynamicTransform::refresh, this));
addParameter(param::ParameterFactory::declareTrigger("reset tf"), boost::bind(&DynamicTransform::resetTf, this));
from_p = boost::dynamic_pointer_cast<param::SetParameter>(getParameter("from"));
to_p = boost::dynamic_pointer_cast<param::SetParameter>(getParameter("to"));
}
void DynamicTransform::process()
{
if(!init_) {
refresh();
}
setError(false);
bool update = false;
bool use_in_frame = frame_in_from_->hasMessage();
from_p->setEnabled(!use_in_frame);
if(use_in_frame) {
std::string from = frame_in_from_->getMessage<connection_types::GenericValueMessage<std::string> >()->value;
if(readParameter<std::string>("from") != from) {
setParameter("from", from);
update = true;
}
}
bool use_to_frame = frame_in_to_->hasMessage();
to_p->setEnabled(!use_to_frame);
if(use_to_frame) {
std::string to = frame_in_to_->getMessage<connection_types::GenericValueMessage<std::string> >()->value;
if(readParameter<std::string>("to") != to) {
setParameter("to", to);
update = true;
}
}
if(update) {
refresh();
}
if(time_in_->hasMessage()) {
connection_types::TimeStampMessage::Ptr time_msg = time_in_->getMessage<connection_types::TimeStampMessage>();
publishTransform(time_msg->value);
} else {
publishTransform(ros::Time(0));
}
}
void DynamicTransform::publishTransform(const ros::Time& time)
{
if(!init_) {
refresh();
}
tf::StampedTransform t;
if(getParameter("from")->is<void>()) {
throw std::runtime_error("from is not a string");
}
if(getParameter("to")->is<void>()) {
throw std::runtime_error("to is not a string");
}
std::string to = readParameter<std::string>("to");
std::string from = readParameter<std::string>("from");
try {
LockedListener l = Listener::getLocked();
if(l.l) {
l.l->tfl->lookupTransform(to, from, time, t);
setError(false);
} else {
return;
}
} catch(const tf2::TransformException& e) {
setError(true, e.what(), EL_WARNING);
return;
}
connection_types::TransformMessage::Ptr msg(new connection_types::TransformMessage);
msg->value = t;
msg->frame_id = from;
msg->child_frame = to;
output_->publish(msg);
connection_types::GenericValueMessage<std::string>::Ptr frame(new connection_types::GenericValueMessage<std::string>);
frame->value = readParameter<std::string>("to");
output_frame_->publish(frame);
}
void DynamicTransform::setup()
{
time_in_ = modifier_->addOptionalInput<connection_types::TimeStampMessage>("Time");
frame_in_from_ = modifier_->addOptionalInput<connection_types::GenericValueMessage<std::string> >("Origin Frame");
frame_in_to_ = modifier_->addOptionalInput<connection_types::GenericValueMessage<std::string> >("Target Frame");
output_ = modifier_->addOutput<connection_types::TransformMessage>("Transform");
output_frame_ = modifier_->addOutput<connection_types::GenericValueMessage<std::string> >("Target Frame");
}
void DynamicTransform::resetTf()
{
LockedListener l = Listener::getLocked();
if(l.l) {
l.l->reset();
}
}
void DynamicTransform::refresh()
{
std::vector<std::string> frames;
std::string to, from;
if(getParameter("from")->is<std::string>()) {
to = to_p->as<std::string>();
}
if(getParameter("to")->is<std::string>()) {
from = from_p->as<std::string>();
}
LockedListener l = Listener::getLocked();
l.l->tfl->waitForTransform(from, to, ros::Time(0), ros::Duration(1.0));
if(l.l) {
std::vector<std::string> f;
l.l->tfl->getFrameStrings(f);
for(std::size_t i = 0; i < f.size(); ++i) {
frames.push_back(std::string("/") + f[i]);
}
} else {
return;
}
if(std::find(frames.begin(), frames.end(), from) == frames.end()) {
frames.push_back(from);
}
if(std::find(frames.begin(), frames.end(), to) == frames.end()) {
frames.push_back(to);
}
from_p->setSet(frames);
to_p->setSet(frames);
init_ = true;
}
void DynamicTransform::update()
{
}
<commit_msg>segfault fixed when no ros connection<commit_after>/// HEADER
#include "dynamic_transform.h"
/// COMPONENT
#include <csapex_transform/transform_message.h>
#include <csapex_transform/time_stamp_message.h>
#include "listener.h"
/// PROJECT
#include <csapex/msg/output.h>
#include <csapex/msg/input.h>
#include <utils_param/parameter_factory.h>
#include <csapex/model/node_modifier.h>
#include <csapex/utility/register_apex_plugin.h>
/// SYSTEM
#include <tf/transform_datatypes.h>
CSAPEX_REGISTER_CLASS(csapex::DynamicTransform, csapex::Node)
using namespace csapex;
DynamicTransform::DynamicTransform()
: init_(false)
{
}
void DynamicTransform::setupParameters()
{
std::vector<std::string> topics;
addParameter(param::ParameterFactory::declareParameterStringSet("from", topics), boost::bind(&DynamicTransform::update, this));
addParameter(param::ParameterFactory::declareParameterStringSet("to", topics), boost::bind(&DynamicTransform::update, this));
addParameter(param::ParameterFactory::declareTrigger("refresh"), boost::bind(&DynamicTransform::refresh, this));
addParameter(param::ParameterFactory::declareTrigger("reset tf"), boost::bind(&DynamicTransform::resetTf, this));
from_p = boost::dynamic_pointer_cast<param::SetParameter>(getParameter("from"));
to_p = boost::dynamic_pointer_cast<param::SetParameter>(getParameter("to"));
}
void DynamicTransform::process()
{
if(!init_) {
refresh();
}
setError(false);
bool update = false;
bool use_in_frame = frame_in_from_->hasMessage();
from_p->setEnabled(!use_in_frame);
if(use_in_frame) {
std::string from = frame_in_from_->getMessage<connection_types::GenericValueMessage<std::string> >()->value;
if(readParameter<std::string>("from") != from) {
setParameter("from", from);
update = true;
}
}
bool use_to_frame = frame_in_to_->hasMessage();
to_p->setEnabled(!use_to_frame);
if(use_to_frame) {
std::string to = frame_in_to_->getMessage<connection_types::GenericValueMessage<std::string> >()->value;
if(readParameter<std::string>("to") != to) {
setParameter("to", to);
update = true;
}
}
if(update) {
refresh();
}
if(time_in_->hasMessage()) {
connection_types::TimeStampMessage::Ptr time_msg = time_in_->getMessage<connection_types::TimeStampMessage>();
publishTransform(time_msg->value);
} else {
publishTransform(ros::Time(0));
}
}
void DynamicTransform::publishTransform(const ros::Time& time)
{
if(!init_) {
refresh();
}
tf::StampedTransform t;
if(getParameter("from")->is<void>()) {
throw std::runtime_error("from is not a string");
}
if(getParameter("to")->is<void>()) {
throw std::runtime_error("to is not a string");
}
std::string to = readParameter<std::string>("to");
std::string from = readParameter<std::string>("from");
try {
LockedListener l = Listener::getLocked();
if(l.l) {
l.l->tfl->lookupTransform(to, from, time, t);
setError(false);
} else {
return;
}
} catch(const tf2::TransformException& e) {
setError(true, e.what(), EL_WARNING);
return;
}
connection_types::TransformMessage::Ptr msg(new connection_types::TransformMessage);
msg->value = t;
msg->frame_id = from;
msg->child_frame = to;
output_->publish(msg);
connection_types::GenericValueMessage<std::string>::Ptr frame(new connection_types::GenericValueMessage<std::string>);
frame->value = readParameter<std::string>("to");
output_frame_->publish(frame);
}
void DynamicTransform::setup()
{
time_in_ = modifier_->addOptionalInput<connection_types::TimeStampMessage>("Time");
frame_in_from_ = modifier_->addOptionalInput<connection_types::GenericValueMessage<std::string> >("Origin Frame");
frame_in_to_ = modifier_->addOptionalInput<connection_types::GenericValueMessage<std::string> >("Target Frame");
output_ = modifier_->addOutput<connection_types::TransformMessage>("Transform");
output_frame_ = modifier_->addOutput<connection_types::GenericValueMessage<std::string> >("Target Frame");
}
void DynamicTransform::resetTf()
{
LockedListener l = Listener::getLocked();
if(l.l) {
l.l->reset();
}
}
void DynamicTransform::refresh()
{
std::vector<std::string> frames;
std::string to, from;
if(getParameter("from")->is<std::string>()) {
to = to_p->as<std::string>();
}
if(getParameter("to")->is<std::string>()) {
from = from_p->as<std::string>();
}
LockedListener l = Listener::getLocked();
if(!l.l) {
return;
}
l.l->tfl->waitForTransform(from, to, ros::Time(0), ros::Duration(1.0));
if(l.l) {
std::vector<std::string> f;
l.l->tfl->getFrameStrings(f);
for(std::size_t i = 0; i < f.size(); ++i) {
frames.push_back(std::string("/") + f[i]);
}
} else {
return;
}
if(std::find(frames.begin(), frames.end(), from) == frames.end()) {
frames.push_back(from);
}
if(std::find(frames.begin(), frames.end(), to) == frames.end()) {
frames.push_back(to);
}
from_p->setSet(frames);
to_p->setSet(frames);
init_ = true;
}
void DynamicTransform::update()
{
}
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
///////////////////////////////////////////////////////////////////////////////
// //
// Base Class for Detector specific Trigger // //
// //
// //
// //
// //
// //
///////////////////////////////////////////////////////////////////////////////
#include <Riostream.h>
#include <TNamed.h>
#include <TString.h>
#include <TObjArray.h>
#include <TRandom.h>
#include "AliLog.h"
#include "AliRun.h"
#include "AliRunLoader.h"
#include "AliTriggerInput.h"
#include "AliTriggerDetector.h"
ClassImp( AliTriggerDetector )
//_____________________________________________________________________________
AliTriggerDetector::AliTriggerDetector() :
TNamed(),
fMask(0),
fInputs()
{
// Default constructor
}
//_____________________________________________________________________________
AliTriggerDetector::AliTriggerDetector(const AliTriggerDetector & de ):
TNamed(de),
fMask(de.fMask),
fInputs(de.fInputs)
{
// Copy constructor
}
//_____________________________________________________________________________
AliTriggerDetector::~AliTriggerDetector()
{
// Destructor
// Delete only inputs that are not
// associated to the CTP
Int_t ninputs = fInputs.GetEntriesFast();
for(Int_t i = 0; i < ninputs; i++) {
AliTriggerInput *inp = (AliTriggerInput *)fInputs.At(i);
if (inp->GetSignature() == -1 &&
inp->GetMask() == 0)
delete fInputs.RemoveAt(i);
}
}
//_____________________________________________________________________________
void AliTriggerDetector::CreateInputs(const TObjArray &inputs)
{
// Define the inputs to the Central Trigger Processor
// This is a dummy version
// Check if we have to create the inputs first
if( fInputs.GetEntriesFast() == 0 ) {
// Create the inputs that the detector can provide
CreateInputs();
}
TString name = GetName();
// Pointer to the available inputs provided by the detector
TObjArray* availInputs = &fInputs;
Int_t ninputs = inputs.GetEntriesFast();
for( Int_t j=0; j<ninputs; j++ ) {
AliTriggerInput *inp = (AliTriggerInput*)inputs.At(j);
if ( name.CompareTo(inp->GetModule().Data()) ) continue;
TObject *tempObj = availInputs->FindObject(inp->GetInputName().Data());
if ( tempObj ) {
Int_t tempIndex = availInputs->IndexOf(tempObj);
delete availInputs->Remove(tempObj);
fInputs.AddAt( inp, tempIndex );
inp->Enable();
AliInfo(Form("Trigger input (%s) is found in the CTP configuration. Therefore it is enabled for trigger detector (%s)",
inp->GetInputName().Data(),name.Data()));
}
else {
AliWarning(Form("Trigger Input (%s) is not implemented for the trigger detector (%s) ! It will be disabled !",
inp->GetInputName().Data(),name.Data()));
}
}
for( Int_t j=0; j<fInputs.GetEntriesFast(); j++ ) {
AliTriggerInput *inp = (AliTriggerInput *)fInputs.At(j);
if (inp->GetSignature() == -1 &&
inp->GetMask() == 0)
inp->Enable();
AliInfo(Form("Trigger input (%s) was not found in the CTP configuration. Therefore it will be run in a stand-alone mode",
inp->GetInputName().Data()));
}
fInputs.SetOwner(kFALSE);
}
//_____________________________________________________________________________
void AliTriggerDetector::CreateInputs()
{
// Define the inputs to the Central Trigger Processor
// This is a dummy version
// Do not create inputs again!!
if( fInputs.GetEntriesFast() > 0 ) return;
fInputs.AddLast( new AliTriggerInput( "TEST1_L0", "TEST", 0 ) );
fInputs.AddLast( new AliTriggerInput( "TEST2_L0", "TEST", 0 ) );
fInputs.AddLast( new AliTriggerInput( "TEST3_L0", "TEST", 0 ) );
}
//_____________________________________________________________________________
void AliTriggerDetector::Trigger()
{
// This is a dummy version set all inputs in a random way
AliWarning( Form( "Triggering dummy detector %s", GetName() ) );
// ********** Get Digits for the current event **********
AliRunLoader* runLoader = gAlice->GetRunLoader();
AliInfo( Form( "Event %d", runLoader->GetEventNumber() ) );
TString loadername = GetName();
loadername.Append( "Loader" );
AliLoader * loader = runLoader->GetLoader( loadername.Data() );
if( loader ) {
loader->LoadDigits( "READ" );
TTree* digits = loader->TreeD();
// Do something with the digits !!!
if( digits ) {
// digits->Print();
}
loader->UnloadDigits();
}
// ******************************************************
// set all inputs in a random way
Int_t nInputs = fInputs.GetEntriesFast();
for( Int_t j=0; j<nInputs; j++ ) {
AliTriggerInput* in = (AliTriggerInput*)fInputs.At( j );
if( gRandom->Rndm() > 0.5 ) {
in->Set();
fMask |= in->GetValue();
}
}
}
//_____________________________________________________________________________
void AliTriggerDetector::SetInput( TString& name )
{
// Set Input by name
SetInput( name.Data() );
}
//_____________________________________________________________________________
void AliTriggerDetector::SetInput( const char * name )
{
// Set Input by name
AliTriggerInput* in = ((AliTriggerInput*)fInputs.FindObject( name ));
if( in ) {
in->Set();
fMask |= in->GetValue();
} else
AliError( Form( "There is not input named %s", name ) );
}
//_____________________________________________________________________________
void AliTriggerDetector::Print( const Option_t* opt ) const
{
// Print
cout << "Trigger Detector : " << GetName() << endl;
cout << " Trigger Class Mask: 0x" << hex << GetMask() << dec << endl;
Int_t nInputs = fInputs.GetEntriesFast();
for( Int_t j=0; j<nInputs; j++ ) {
AliTriggerInput* in = (AliTriggerInput*)fInputs.At( j );
in->Print( opt );
}
}
<commit_msg>Bug fix. Missing {} that was causing a false information message that the trigger input will be running in a stand-alone mode. Thanks to Philippe for noticing the problem<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
///////////////////////////////////////////////////////////////////////////////
// //
// Base Class for Detector specific Trigger // //
// //
// //
// //
// //
// //
///////////////////////////////////////////////////////////////////////////////
#include <Riostream.h>
#include <TNamed.h>
#include <TString.h>
#include <TObjArray.h>
#include <TRandom.h>
#include "AliLog.h"
#include "AliRun.h"
#include "AliRunLoader.h"
#include "AliTriggerInput.h"
#include "AliTriggerDetector.h"
ClassImp( AliTriggerDetector )
//_____________________________________________________________________________
AliTriggerDetector::AliTriggerDetector() :
TNamed(),
fMask(0),
fInputs()
{
// Default constructor
}
//_____________________________________________________________________________
AliTriggerDetector::AliTriggerDetector(const AliTriggerDetector & de ):
TNamed(de),
fMask(de.fMask),
fInputs(de.fInputs)
{
// Copy constructor
}
//_____________________________________________________________________________
AliTriggerDetector::~AliTriggerDetector()
{
// Destructor
// Delete only inputs that are not
// associated to the CTP
Int_t ninputs = fInputs.GetEntriesFast();
for(Int_t i = 0; i < ninputs; i++) {
AliTriggerInput *inp = (AliTriggerInput *)fInputs.At(i);
if (inp->GetSignature() == -1 &&
inp->GetMask() == 0)
delete fInputs.RemoveAt(i);
}
}
//_____________________________________________________________________________
void AliTriggerDetector::CreateInputs(const TObjArray &inputs)
{
// Define the inputs to the Central Trigger Processor
// This is a dummy version
// Check if we have to create the inputs first
if( fInputs.GetEntriesFast() == 0 ) {
// Create the inputs that the detector can provide
CreateInputs();
}
TString name = GetName();
// Pointer to the available inputs provided by the detector
TObjArray* availInputs = &fInputs;
Int_t ninputs = inputs.GetEntriesFast();
for( Int_t j=0; j<ninputs; j++ ) {
AliTriggerInput *inp = (AliTriggerInput*)inputs.At(j);
if ( name.CompareTo(inp->GetModule().Data()) ) continue;
TObject *tempObj = availInputs->FindObject(inp->GetInputName().Data());
if ( tempObj ) {
Int_t tempIndex = availInputs->IndexOf(tempObj);
delete availInputs->Remove(tempObj);
fInputs.AddAt( inp, tempIndex );
inp->Enable();
AliInfo(Form("Trigger input (%s) is found in the CTP configuration. Therefore it is enabled for trigger detector (%s)",
inp->GetInputName().Data(),name.Data()));
}
else {
AliWarning(Form("Trigger Input (%s) is not implemented for the trigger detector (%s) ! It will be disabled !",
inp->GetInputName().Data(),name.Data()));
}
}
for( Int_t j=0; j<fInputs.GetEntriesFast(); j++ ) {
AliTriggerInput *inp = (AliTriggerInput *)fInputs.At(j);
if (inp->GetSignature() == -1 &&
inp->GetMask() == 0) {
inp->Enable();
AliInfo(Form("Trigger input (%s) was not found in the CTP configuration. Therefore it will be run in a stand-alone mode",
inp->GetInputName().Data()));
}
}
fInputs.SetOwner(kFALSE);
}
//_____________________________________________________________________________
void AliTriggerDetector::CreateInputs()
{
// Define the inputs to the Central Trigger Processor
// This is a dummy version
// Do not create inputs again!!
if( fInputs.GetEntriesFast() > 0 ) return;
fInputs.AddLast( new AliTriggerInput( "TEST1_L0", "TEST", 0 ) );
fInputs.AddLast( new AliTriggerInput( "TEST2_L0", "TEST", 0 ) );
fInputs.AddLast( new AliTriggerInput( "TEST3_L0", "TEST", 0 ) );
}
//_____________________________________________________________________________
void AliTriggerDetector::Trigger()
{
// This is a dummy version set all inputs in a random way
AliWarning( Form( "Triggering dummy detector %s", GetName() ) );
// ********** Get Digits for the current event **********
AliRunLoader* runLoader = gAlice->GetRunLoader();
AliInfo( Form( "Event %d", runLoader->GetEventNumber() ) );
TString loadername = GetName();
loadername.Append( "Loader" );
AliLoader * loader = runLoader->GetLoader( loadername.Data() );
if( loader ) {
loader->LoadDigits( "READ" );
TTree* digits = loader->TreeD();
// Do something with the digits !!!
if( digits ) {
// digits->Print();
}
loader->UnloadDigits();
}
// ******************************************************
// set all inputs in a random way
Int_t nInputs = fInputs.GetEntriesFast();
for( Int_t j=0; j<nInputs; j++ ) {
AliTriggerInput* in = (AliTriggerInput*)fInputs.At( j );
if( gRandom->Rndm() > 0.5 ) {
in->Set();
fMask |= in->GetValue();
}
}
}
//_____________________________________________________________________________
void AliTriggerDetector::SetInput( TString& name )
{
// Set Input by name
SetInput( name.Data() );
}
//_____________________________________________________________________________
void AliTriggerDetector::SetInput( const char * name )
{
// Set Input by name
AliTriggerInput* in = ((AliTriggerInput*)fInputs.FindObject( name ));
if( in ) {
in->Set();
fMask |= in->GetValue();
} else
AliError( Form( "There is not input named %s", name ) );
}
//_____________________________________________________________________________
void AliTriggerDetector::Print( const Option_t* opt ) const
{
// Print
cout << "Trigger Detector : " << GetName() << endl;
cout << " Trigger Class Mask: 0x" << hex << GetMask() << dec << endl;
Int_t nInputs = fInputs.GetEntriesFast();
for( Int_t j=0; j<nInputs; j++ ) {
AliTriggerInput* in = (AliTriggerInput*)fInputs.At( j );
in->Print( opt );
}
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include "paddle/fluid/framework/data_layout_transform.h"
#include "paddle/fluid/framework/feed_fetch_type.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/platform/device_context.h"
#include "paddle/fluid/platform/profiler.h"
namespace paddle {
namespace operators {
// FIXME(yuyang18): Should we assume the fetch operator always generate
// CPU outputs?
static void DataCopy(const framework::LoDTensor &src_item,
const std::string &fetch_var_name,
framework::LoDTensor *dst_item) {
if (src_item.IsInitialized() && src_item.numel() > 0) {
#ifdef PADDLE_WITH_MKLDNN
// Conversion from MKL-DNN to Paddle
if (src_item.layout() == framework::DataLayout::kMKLDNN) {
framework::Tensor out;
// Convert to desired Paddle layout, apart from grads of filter
// as params are not a subject to paddle's data_format
framework::innerTransDataLayoutFromMKLDNN(
src_item.layout(), fetch_var_name == framework::GradVarName("Filter")
? framework::DataLayout::kNCHW
: paddle::platform::MKLDNNDeviceContext::tls()
.get_cur_paddle_data_layout(),
src_item, &out, platform::CPUPlace());
TensorCopySync(out, platform::CPUPlace(), dst_item);
} else {
TensorCopySync(src_item, platform::CPUPlace(), dst_item);
}
#else
#ifdef PADDLE_WITH_ASCEND_CL
if (platform::is_npu_place(src_item.place())) {
platform::DeviceContextPool::Instance().Get(src_item.place())->Wait();
}
#endif
TensorCopySync(src_item, platform::CPUPlace(), dst_item);
#endif
} else {
// Not copy, if the src tensor is empty.
dst_item->clear();
dst_item->Resize({0});
}
dst_item->set_lod(src_item.lod());
}
class FetchOp : public framework::OperatorBase {
public:
FetchOp(const std::string &type, const framework::VariableNameMap &inputs,
const framework::VariableNameMap &outputs,
const framework::AttributeMap &attrs)
: OperatorBase(type, inputs, outputs, attrs) {}
private:
void RunImpl(const framework::Scope &scope,
const platform::Place &place) const override {
OP_INOUT_CHECK(HasInputs("X"), "Input", "X", "Fetch");
OP_INOUT_CHECK(HasOutputs("Out"), "Output", "Out", "Fetch");
auto fetch_var_name = Input("X");
auto *fetch_var = scope.FindVar(fetch_var_name);
PADDLE_ENFORCE_NOT_NULL(
fetch_var,
platform::errors::NotFound(
"Input variable(%s) cannot be found in scope for operator 'Fetch'."
"Confirm that you have used the fetch `Variable` format "
"instead of the string literal('%s') in `fetch_list` "
"parameter when using `executor.run` method. In other "
"words, the format of "
"`executor.run(fetch_list=[fetch_var])`(fetch_var is a "
"Variable) is recommended.",
fetch_var_name, fetch_var_name));
auto out_name = Output("Out");
auto *out_var = scope.FindVar(out_name);
PADDLE_ENFORCE_NOT_NULL(out_var, platform::errors::NotFound(
"Output variable(%s) cannot be found "
"in scope for operator 'Fetch'.",
out_name));
int col = Attr<int>("col");
PADDLE_ENFORCE_GE(
col, 0, platform::errors::InvalidArgument(
"Expected the column index (the attribute 'col' of "
"operator 'Fetch') of current fetching variable to be "
"no less than 0. But received column index = %d.",
col));
VLOG(3) << "Fetch variable " << fetch_var_name << " to variable "
<< out_name << "'s " << col << " column.";
auto *fetch_list = out_var->GetMutable<framework::FetchList>();
if (static_cast<size_t>(col) >= fetch_list->size()) {
fetch_list->resize(col + 1);
}
if (fetch_var->IsType<framework::LoDTensor>()) {
auto &src_item = fetch_var->Get<framework::LoDTensor>();
auto *dst_item = &(BOOST_GET(framework::LoDTensor, fetch_list->at(col)));
DataCopy(src_item, fetch_var_name, dst_item);
} else {
auto &src_item = fetch_var->Get<framework::LoDTensorArray>();
framework::LoDTensorArray tmp(src_item.size());
fetch_list->at(col) = tmp;
auto &dst_item =
BOOST_GET(framework::LoDTensorArray, fetch_list->at(col));
for (size_t i = 0; i < src_item.size(); ++i) {
DataCopy(src_item[i], fetch_var_name, &dst_item[i]);
}
}
}
};
class FetchOpInfoMaker : public framework::OpProtoAndCheckerMaker {
public:
void Make() override {
AddInput("X",
"(LoDTensor) The resulted LoDTensor which is expected to return "
"to users.");
AddOutput("Out",
"(vector<LoDTensor>) A fetching list of LoDTensor which may have "
"different dimension, shape and data type.");
AddAttr<int>("col", "(int) The column index of fetching object.");
AddComment(R"DOC(
Fetch Operator.
It should not be configured by users directly.
)DOC");
}
};
} // namespace operators
} // namespace paddle
REGISTER_OPERATOR(
fetch, paddle::operators::FetchOp,
paddle::framework::EmptyGradOpMaker<paddle::framework::OpDesc>,
paddle::framework::EmptyGradOpMaker<paddle::imperative::OpBase>,
paddle::operators::FetchOpInfoMaker);
<commit_msg>[NPU] remove duplicated stream sync in fetch op (#33819)<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include "paddle/fluid/framework/data_layout_transform.h"
#include "paddle/fluid/framework/feed_fetch_type.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/platform/device_context.h"
#include "paddle/fluid/platform/profiler.h"
namespace paddle {
namespace operators {
// FIXME(yuyang18): Should we assume the fetch operator always generate
// CPU outputs?
static void DataCopy(const framework::LoDTensor &src_item,
const std::string &fetch_var_name,
framework::LoDTensor *dst_item) {
if (src_item.IsInitialized() && src_item.numel() > 0) {
#ifdef PADDLE_WITH_MKLDNN
// Conversion from MKL-DNN to Paddle
if (src_item.layout() == framework::DataLayout::kMKLDNN) {
framework::Tensor out;
// Convert to desired Paddle layout, apart from grads of filter
// as params are not a subject to paddle's data_format
framework::innerTransDataLayoutFromMKLDNN(
src_item.layout(), fetch_var_name == framework::GradVarName("Filter")
? framework::DataLayout::kNCHW
: paddle::platform::MKLDNNDeviceContext::tls()
.get_cur_paddle_data_layout(),
src_item, &out, platform::CPUPlace());
TensorCopySync(out, platform::CPUPlace(), dst_item);
} else {
TensorCopySync(src_item, platform::CPUPlace(), dst_item);
}
#else
TensorCopySync(src_item, platform::CPUPlace(), dst_item);
#endif
} else {
// Not copy, if the src tensor is empty.
dst_item->clear();
dst_item->Resize({0});
}
dst_item->set_lod(src_item.lod());
}
class FetchOp : public framework::OperatorBase {
public:
FetchOp(const std::string &type, const framework::VariableNameMap &inputs,
const framework::VariableNameMap &outputs,
const framework::AttributeMap &attrs)
: OperatorBase(type, inputs, outputs, attrs) {}
private:
void RunImpl(const framework::Scope &scope,
const platform::Place &place) const override {
OP_INOUT_CHECK(HasInputs("X"), "Input", "X", "Fetch");
OP_INOUT_CHECK(HasOutputs("Out"), "Output", "Out", "Fetch");
auto fetch_var_name = Input("X");
auto *fetch_var = scope.FindVar(fetch_var_name);
PADDLE_ENFORCE_NOT_NULL(
fetch_var,
platform::errors::NotFound(
"Input variable(%s) cannot be found in scope for operator 'Fetch'."
"Confirm that you have used the fetch `Variable` format "
"instead of the string literal('%s') in `fetch_list` "
"parameter when using `executor.run` method. In other "
"words, the format of "
"`executor.run(fetch_list=[fetch_var])`(fetch_var is a "
"Variable) is recommended.",
fetch_var_name, fetch_var_name));
auto out_name = Output("Out");
auto *out_var = scope.FindVar(out_name);
PADDLE_ENFORCE_NOT_NULL(out_var, platform::errors::NotFound(
"Output variable(%s) cannot be found "
"in scope for operator 'Fetch'.",
out_name));
int col = Attr<int>("col");
PADDLE_ENFORCE_GE(
col, 0, platform::errors::InvalidArgument(
"Expected the column index (the attribute 'col' of "
"operator 'Fetch') of current fetching variable to be "
"no less than 0. But received column index = %d.",
col));
VLOG(3) << "Fetch variable " << fetch_var_name << " to variable "
<< out_name << "'s " << col << " column.";
auto *fetch_list = out_var->GetMutable<framework::FetchList>();
if (static_cast<size_t>(col) >= fetch_list->size()) {
fetch_list->resize(col + 1);
}
if (fetch_var->IsType<framework::LoDTensor>()) {
auto &src_item = fetch_var->Get<framework::LoDTensor>();
auto *dst_item = &(BOOST_GET(framework::LoDTensor, fetch_list->at(col)));
DataCopy(src_item, fetch_var_name, dst_item);
} else {
auto &src_item = fetch_var->Get<framework::LoDTensorArray>();
framework::LoDTensorArray tmp(src_item.size());
fetch_list->at(col) = tmp;
auto &dst_item =
BOOST_GET(framework::LoDTensorArray, fetch_list->at(col));
for (size_t i = 0; i < src_item.size(); ++i) {
DataCopy(src_item[i], fetch_var_name, &dst_item[i]);
}
}
}
};
class FetchOpInfoMaker : public framework::OpProtoAndCheckerMaker {
public:
void Make() override {
AddInput("X",
"(LoDTensor) The resulted LoDTensor which is expected to return "
"to users.");
AddOutput("Out",
"(vector<LoDTensor>) A fetching list of LoDTensor which may have "
"different dimension, shape and data type.");
AddAttr<int>("col", "(int) The column index of fetching object.");
AddComment(R"DOC(
Fetch Operator.
It should not be configured by users directly.
)DOC");
}
};
} // namespace operators
} // namespace paddle
REGISTER_OPERATOR(
fetch, paddle::operators::FetchOp,
paddle::framework::EmptyGradOpMaker<paddle::framework::OpDesc>,
paddle::framework::EmptyGradOpMaker<paddle::imperative::OpBase>,
paddle::operators::FetchOpInfoMaker);
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: htmlfile.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: vg $ $Date: 2005-03-23 09:05:00 $
*
* 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): _______________________________________
*
*
************************************************************************/
#include <precomp.h>
#include <toolkit/htmlfile.hxx>
// NOT FULLY DECLARED SERVICES
#include <cosv/file.hxx>
#include <udm/html/htmlitem.hxx>
using namespace csi;
using csi::xml::AnAttribute;
DocuFile_Html::DocuFile_Html()
: sFilePath(),
sTitle(),
sLocation(),
sStyle(),
sCssFile(),
sCopyright(),
aBodyData()
{
}
void
DocuFile_Html::SetLocation( const csv::ploc::Path & i_rFilePath )
{
StreamLock sPath(1000);
i_rFilePath.Get( sPath() );
sFilePath = sPath().c_str();
}
void
DocuFile_Html::SetTitle( const char * i_sTitle )
{
sTitle = i_sTitle;
}
void
DocuFile_Html::SetInlineStyle( const char * i_sStyle )
{
sStyle = i_sStyle;
}
void
DocuFile_Html::SetRelativeCssPath( const char * i_sCssFile_relativePath )
{
sCssFile = i_sCssFile_relativePath;
}
void
DocuFile_Html::SetCopyright( const char * i_sCopyright )
{
sCopyright = i_sCopyright;
}
void
DocuFile_Html::EmptyBody()
{
aBodyData.SetContent(0);
aBodyData
>> *new html::Label( "_top_" )
<< " ";
}
bool
DocuFile_Html::CreateFile()
{
csv::File aFile(sFilePath, csv::CFM_CREATE);
if (NOT aFile.open())
{
Cerr() << "Can't create file " << sFilePath << "." << Endl();
return false;
}
WriteHeader(aFile);
WriteBody(aFile);
// Write end
static const char sCompletion[] = "\n</html>\n";
aFile.write( sCompletion );
aFile.close();
Cout() << '.' << Flush();
return true;
}
void
DocuFile_Html::WriteHeader( csv::File & io_aFile )
{
static const char s1[] =
"<html>\n<head>\n<title>";
static const char s2[] =
"</title>\n"
"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n";
io_aFile.write( s1 );
io_aFile.write( sTitle );
io_aFile.write( s2 );
if (NOT sCssFile.empty())
{
static const char s3[] =
"<link rel=\"stylesheet\" type=\"text/css\" href=\"";
static const char s4[] =
"\">\n";
io_aFile.write(s3);
io_aFile.write(sCssFile);
io_aFile.write(s4);
}
if (NOT sStyle.empty())
{
static const char s5[] =
"<style>";
static const char s6[] =
"</style>\n";
io_aFile.write(s5);
io_aFile.write(sStyle);
io_aFile.write(s6);
}
static const char s7[] =
"</head>\n";
io_aFile.write(s7);
}
void
DocuFile_Html::WriteBody( csv::File & io_aFile )
{
aBodyData
>> *new html::Link( "#_top_" )
<< "Top of Page";
if ( sCopyright.length() > 0 )
{
aBodyData
<< new xml::XmlCode("<hr size=\"3\">");
aBodyData
>> *new html::Paragraph
<< new html::ClassAttr( "copyright" )
<< new xml::AnAttribute( "align", "center" )
<< new xml::XmlCode(sCopyright);
}
aBodyData.WriteOut(io_aFile);
}
<commit_msg>INTEGRATION: CWS adc12p (1.3.6); FILE MERGED 2005/07/27 11:21:25 np 1.3.6.1: #i52495#<commit_after>/*************************************************************************
*
* $RCSfile: htmlfile.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2005-08-05 14:26:23 $
*
* 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): _______________________________________
*
*
************************************************************************/
#include <precomp.h>
#include <toolkit/htmlfile.hxx>
// NOT FULLY DECLARED SERVICES
#include <cosv/file.hxx>
#include <udm/html/htmlitem.hxx>
using namespace csi;
using csi::xml::AnAttribute;
DocuFile_Html::DocuFile_Html()
: sFilePath(),
sTitle(),
sLocation(),
sStyle(),
sCssFile(),
sCopyright(),
aBodyData(),
aBuffer(60000) // Grows dynamically, when necessary.
{
}
void
DocuFile_Html::SetLocation( const csv::ploc::Path & i_rFilePath )
{
StreamLock sPath(1000);
i_rFilePath.Get( sPath() );
sFilePath = sPath().c_str();
}
void
DocuFile_Html::SetTitle( const char * i_sTitle )
{
sTitle = i_sTitle;
}
void
DocuFile_Html::SetInlineStyle( const char * i_sStyle )
{
sStyle = i_sStyle;
}
void
DocuFile_Html::SetRelativeCssPath( const char * i_sCssFile_relativePath )
{
sCssFile = i_sCssFile_relativePath;
}
void
DocuFile_Html::SetCopyright( const char * i_sCopyright )
{
sCopyright = i_sCopyright;
}
void
DocuFile_Html::EmptyBody()
{
aBodyData.SetContent(0);
aBodyData
>> *new html::Label( "_top_" )
<< " ";
}
bool
DocuFile_Html::CreateFile()
{
csv::File aFile(sFilePath, csv::CFM_CREATE);
if (NOT aFile.open())
{
Cerr() << "Can't create file " << sFilePath << "." << Endl();
return false;
}
WriteHeader(aFile);
WriteBody(aFile);
// Write end
static const char sCompletion[] = "\n</html>\n";
aFile.write( sCompletion );
aFile.close();
Cout() << '.' << Flush();
return true;
}
void
DocuFile_Html::WriteHeader( csv::File & io_aFile )
{
aBuffer.reset();
static const char s1[] =
"<html>\n<head>\n<title>";
static const char s2[] =
"</title>\n"
"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n";
aBuffer.write( s1 );
aBuffer.write( sTitle );
aBuffer.write( s2 );
if (NOT sCssFile.empty())
{
static const char s3[] =
"<link rel=\"stylesheet\" type=\"text/css\" href=\"";
static const char s4[] =
"\">\n";
aBuffer.write(s3);
aBuffer.write(sCssFile);
aBuffer.write(s4);
}
if (NOT sStyle.empty())
{
static const char s5[] =
"<style>";
static const char s6[] =
"</style>\n";
aBuffer.write(s5);
aBuffer.write(sStyle);
aBuffer.write(s6);
}
static const char s7[] =
"</head>\n";
aBuffer.write(s7);
io_aFile.write(aBuffer.c_str(), aBuffer.size());
}
void
DocuFile_Html::WriteBody( csv::File & io_aFile )
{
aBuffer.reset();
aBodyData
>> *new html::Link( "#_top_" )
<< "Top of Page";
if ( sCopyright.length() > 0 )
{
aBodyData
<< new xml::XmlCode("<hr size=\"3\">");
aBodyData
>> *new html::Paragraph
<< new html::ClassAttr( "copyright" )
<< new xml::AnAttribute( "align", "center" )
<< new xml::XmlCode(sCopyright);
}
aBodyData.WriteOut(aBuffer);
io_aFile.write(aBuffer.c_str(), aBuffer.size());
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: postuninstall.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: vg $ $Date: 2008-03-18 12:54:23 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#define _WIN32_WINDOWS 0x0410
#ifdef _MSC_VER
#pragma warning(push, 1) /* disable warnings within system headers */
#endif
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <msiquery.h>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include <malloc.h>
#ifdef UNICODE
#define _UNICODE
#define _tstring wstring
#else
#define _tstring string
#endif
#include <tchar.h>
#include <string>
#include <io.h>
static std::_tstring GetMsiProperty( MSIHANDLE handle, const std::_tstring& sProperty )
{
std::_tstring result;
TCHAR szDummy[1] = TEXT("");
DWORD nChars = 0;
if ( MsiGetProperty( handle, sProperty.c_str(), szDummy, &nChars ) == ERROR_MORE_DATA )
{
DWORD nBytes = ++nChars * sizeof(TCHAR);
LPTSTR buffer = reinterpret_cast<LPTSTR>(_alloca(nBytes));
ZeroMemory( buffer, nBytes );
MsiGetProperty(handle, sProperty.c_str(), buffer, &nChars);
result = buffer;
}
return result;
}
static BOOL ExecuteCommand( LPCTSTR lpCommand, BOOL bSync )
{
BOOL fSuccess = FALSE;
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
fSuccess = CreateProcess(
NULL,
(LPTSTR)lpCommand,
NULL,
NULL,
FALSE,
0,
NULL,
NULL,
&si,
&pi
);
if ( fSuccess )
{
if ( bSync )
WaitForSingleObject( pi.hProcess, INFINITE );
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
}
return fSuccess;
}
extern "C" UINT __stdcall ExecutePostUninstallScript( MSIHANDLE handle )
{
TCHAR szValue[8192];
DWORD nValueSize = sizeof(szValue);
HKEY hKey;
std::_tstring sInstDir;
std::_tstring sProductKey = GetMsiProperty( handle, TEXT("FINDPRODUCT") );
// MessageBox( NULL, sProductKey.c_str(), "Titel", MB_OK );
if ( ERROR_SUCCESS == RegOpenKey( HKEY_CURRENT_USER, sProductKey.c_str(), &hKey ) )
{
if ( ERROR_SUCCESS == RegQueryValueEx( hKey, TEXT("OFFICEINSTALLLOCATION"), NULL, NULL, (LPBYTE)szValue, &nValueSize ) )
{
sInstDir = szValue;
}
RegCloseKey( hKey );
}
else if ( ERROR_SUCCESS == RegOpenKey( HKEY_LOCAL_MACHINE, sProductKey.c_str(), &hKey ) )
{
if ( ERROR_SUCCESS == RegQueryValueEx( hKey, TEXT("OFFICEINSTALLLOCATION"), NULL, NULL, (LPBYTE)szValue, &nValueSize ) )
{
sInstDir = szValue;
}
RegCloseKey( hKey );
}
else
return ERROR_SUCCESS;
std::_tstring sInfFile = sInstDir + TEXT("program\\postuninstall.inf");
std::_tstring sCommand = _T("RUNDLL32.EXE ");
// MessageBox( NULL, sInfFile.c_str(), "Titel", MB_OK );
if ( (LONG)GetVersion() < 0 )
sCommand += _T("setupx.dll");
else
sCommand += _T("setupapi.dll");
sCommand += _T(",InstallHinfSection PostUninstall 132 ");
sCommand += sInfFile;
if ( 0 == _taccess( sInfFile.c_str(), 2 ) )
ExecuteCommand( sCommand.c_str(), TRUE );
DeleteFile( sInfFile.c_str() );
return ERROR_SUCCESS;
}
<commit_msg>INTEGRATION: CWS changefileheader (1.8.4); FILE MERGED 2008/03/31 16:08:01 rt 1.8.4.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: postuninstall.cxx,v $
* $Revision: 1.9 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#define _WIN32_WINDOWS 0x0410
#ifdef _MSC_VER
#pragma warning(push, 1) /* disable warnings within system headers */
#endif
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <msiquery.h>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include <malloc.h>
#ifdef UNICODE
#define _UNICODE
#define _tstring wstring
#else
#define _tstring string
#endif
#include <tchar.h>
#include <string>
#include <io.h>
static std::_tstring GetMsiProperty( MSIHANDLE handle, const std::_tstring& sProperty )
{
std::_tstring result;
TCHAR szDummy[1] = TEXT("");
DWORD nChars = 0;
if ( MsiGetProperty( handle, sProperty.c_str(), szDummy, &nChars ) == ERROR_MORE_DATA )
{
DWORD nBytes = ++nChars * sizeof(TCHAR);
LPTSTR buffer = reinterpret_cast<LPTSTR>(_alloca(nBytes));
ZeroMemory( buffer, nBytes );
MsiGetProperty(handle, sProperty.c_str(), buffer, &nChars);
result = buffer;
}
return result;
}
static BOOL ExecuteCommand( LPCTSTR lpCommand, BOOL bSync )
{
BOOL fSuccess = FALSE;
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
fSuccess = CreateProcess(
NULL,
(LPTSTR)lpCommand,
NULL,
NULL,
FALSE,
0,
NULL,
NULL,
&si,
&pi
);
if ( fSuccess )
{
if ( bSync )
WaitForSingleObject( pi.hProcess, INFINITE );
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
}
return fSuccess;
}
extern "C" UINT __stdcall ExecutePostUninstallScript( MSIHANDLE handle )
{
TCHAR szValue[8192];
DWORD nValueSize = sizeof(szValue);
HKEY hKey;
std::_tstring sInstDir;
std::_tstring sProductKey = GetMsiProperty( handle, TEXT("FINDPRODUCT") );
// MessageBox( NULL, sProductKey.c_str(), "Titel", MB_OK );
if ( ERROR_SUCCESS == RegOpenKey( HKEY_CURRENT_USER, sProductKey.c_str(), &hKey ) )
{
if ( ERROR_SUCCESS == RegQueryValueEx( hKey, TEXT("OFFICEINSTALLLOCATION"), NULL, NULL, (LPBYTE)szValue, &nValueSize ) )
{
sInstDir = szValue;
}
RegCloseKey( hKey );
}
else if ( ERROR_SUCCESS == RegOpenKey( HKEY_LOCAL_MACHINE, sProductKey.c_str(), &hKey ) )
{
if ( ERROR_SUCCESS == RegQueryValueEx( hKey, TEXT("OFFICEINSTALLLOCATION"), NULL, NULL, (LPBYTE)szValue, &nValueSize ) )
{
sInstDir = szValue;
}
RegCloseKey( hKey );
}
else
return ERROR_SUCCESS;
std::_tstring sInfFile = sInstDir + TEXT("program\\postuninstall.inf");
std::_tstring sCommand = _T("RUNDLL32.EXE ");
// MessageBox( NULL, sInfFile.c_str(), "Titel", MB_OK );
if ( (LONG)GetVersion() < 0 )
sCommand += _T("setupx.dll");
else
sCommand += _T("setupapi.dll");
sCommand += _T(",InstallHinfSection PostUninstall 132 ");
sCommand += sInfFile;
if ( 0 == _taccess( sInfFile.c_str(), 2 ) )
ExecuteCommand( sCommand.c_str(), TRUE );
DeleteFile( sInfFile.c_str() );
return ERROR_SUCCESS;
}
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2010 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
*
*****************************************************************************/
//$Id$
#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
#include <mapnik/raster_colorizer.hpp>
using mapnik::raster_colorizer;
using mapnik::raster_colorizer_ptr;
using mapnik::color_band;
using mapnik::color_bands;
namespace {
void append_band1(raster_colorizer_ptr & rc, color_band b)
{
rc->append_band(b);
}
void append_band2(raster_colorizer_ptr & rc, color_band b, unsigned m)
{
rc->append_band(b, m);
}
void append_band3(raster_colorizer_ptr & rc, float v, color c)
{
rc->append_band(v, c);
}
void append_band4(raster_colorizer_ptr & rc, float v, color c, unsigned m)
{
rc->append_band(v, c, m);
}
color_bands const& get_color_bands(raster_colorizer_ptr & rc)
{
return rc->get_color_bands();
}
}
void export_raster_colorizer()
{
using namespace boost::python;
class_<raster_colorizer,raster_colorizer_ptr>("RasterColorizer", init<>("Deafult ctor."))
.add_property("bands",make_function
(get_color_bands,
return_value_policy<reference_existing_object>()))
.def("append_band", append_band1, "TODO: Write docs")
.def("append_band", append_band2, "TODO: Write docs")
.def("append_band", append_band3, "TODO: Write docs")
.def("append_band", append_band4, "TODO: Write docs")
.def("get_color", &raster_colorizer::get_color, "TODO: Write docs")
;
class_<color_bands>("ColorBands",init<>("Default ctor."))
.def(vector_indexing_suite<color_bands>())
;
class_<color_band>("ColorBand",
init<float,color const&>("Deafult ctor."))
.add_property("color", make_function
(&color_band::get_color,
return_value_policy<reference_existing_object>()))
.add_property("value", &color_band::get_value)
.def(self == self)
.def("__str__",&color_band::to_string)
;
}
<commit_msg>+ add using mapnik::color<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2010 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
*
*****************************************************************************/
//$Id$
#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
#include <mapnik/raster_colorizer.hpp>
using mapnik::raster_colorizer;
using mapnik::raster_colorizer_ptr;
using mapnik::color_band;
using mapnik::color_bands;
using mapnik::color;
namespace {
void append_band1(raster_colorizer_ptr & rc, color_band b)
{
rc->append_band(b);
}
void append_band2(raster_colorizer_ptr & rc, color_band b, unsigned m)
{
rc->append_band(b, m);
}
void append_band3(raster_colorizer_ptr & rc, float v, color c)
{
rc->append_band(v, c);
}
void append_band4(raster_colorizer_ptr & rc, float v, color c, unsigned m)
{
rc->append_band(v, c, m);
}
color_bands const& get_color_bands(raster_colorizer_ptr & rc)
{
return rc->get_color_bands();
}
}
void export_raster_colorizer()
{
using namespace boost::python;
class_<raster_colorizer,raster_colorizer_ptr>("RasterColorizer", init<>("Deafult ctor."))
.add_property("bands",make_function
(get_color_bands,
return_value_policy<reference_existing_object>()))
.def("append_band", append_band1, "TODO: Write docs")
.def("append_band", append_band2, "TODO: Write docs")
.def("append_band", append_band3, "TODO: Write docs")
.def("append_band", append_band4, "TODO: Write docs")
.def("get_color", &raster_colorizer::get_color, "TODO: Write docs")
;
class_<color_bands>("ColorBands",init<>("Default ctor."))
.def(vector_indexing_suite<color_bands>())
;
class_<color_band>("ColorBand",
init<float,color const&>("Deafult ctor."))
.add_property("color", make_function
(&color_band::get_color,
return_value_policy<reference_existing_object>()))
.add_property("value", &color_band::get_value)
.def(self == self)
.def("__str__",&color_band::to_string)
;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: Class.cxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: obo $ $Date: 2006-09-17 02:44:59 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_connectivity.hxx"
#ifndef _CONNECTIVITY_JAVA_LANG_CLASS_HXX_
#include "java/lang/Class.hxx"
#endif
#ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_
#include "java/tools.hxx"
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
using namespace connectivity;
//**************************************************************
//************ Class: java.lang.Class
//**************************************************************
jclass java_lang_Class::theClass = 0;
java_lang_Class::~java_lang_Class()
{}
jclass java_lang_Class::getMyClass()
{
// die Klasse muss nur einmal geholt werden, daher statisch
if( !theClass ){
SDBThreadAttach t;
if( !t.pEnv ) return (jclass)NULL;
jclass tempClass = t.pEnv->FindClass("java/lang/Class"); OSL_ENSURE(tempClass,"Java : FindClass nicht erfolgreich!");
jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass );
t.pEnv->DeleteLocalRef( tempClass );
saveClassRef( globClass );
}
return theClass;
}
void java_lang_Class::saveClassRef( jclass pClass )
{
if( pClass==NULL )
return;
// der uebergebe Klassen-Handle ist schon global, daher einfach speichern
theClass = pClass;
}
java_lang_Class * java_lang_Class::forName( const ::rtl::OUString& _par0 )
{
jobject out(NULL);
SDBThreadAttach t;
if( t.pEnv )
{
::rtl::OString sClassName = ::rtl::OUStringToOString(_par0, RTL_TEXTENCODING_JAVA_UTF8);
sClassName = sClassName.replace('.','/');
out = t.pEnv->FindClass(sClassName);
ThrowSQLException(t.pEnv,0);
} //t.pEnv
// ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
return out==0 ? NULL : new java_lang_Class( t.pEnv, out );
}
sal_Bool java_lang_Class::isAssignableFrom( java_lang_Class * _par0 )
{
jboolean out(0);
SDBThreadAttach t;
if( t.pEnv ){
// temporaere Variable initialisieren
static const char * cSignature = "(Ljava/lang/Class;)Z";
static const char * cMethodName = "isAssignableFrom";
// Java-Call absetzen
static jmethodID mID = NULL;
if ( !mID )
mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
if( mID ){
jvalue args[1];
// Parameter konvertieren
args[0].l = _par0 != NULL ? ((java_lang_Object *)_par0)->getJavaObject() : NULL;
out = t.pEnv->CallBooleanMethod( object, mID, args[0].l );
ThrowSQLException(t.pEnv,0);
// und aufraeumen
} //mID
} //t.pEnv
return out;
}
java_lang_Object * java_lang_Class::newInstance()
{
jobject out(NULL);
SDBThreadAttach t;
if( t.pEnv ){
// temporaere Variable initialisieren
static const char * cSignature = "()Ljava/lang/Object;";
static const char * cMethodName = "newInstance";
// Java-Call absetzen
static jmethodID mID = NULL;
if ( !mID )
mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
if( mID ){
out = t.pEnv->CallObjectMethod( object, mID);
ThrowSQLException(t.pEnv,0);
} //mID
} //t.pEnv
// ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
return out==0 ? NULL : new java_lang_Object( t.pEnv, out );
}
jobject java_lang_Class::newInstanceObject()
{
jobject out(NULL);
SDBThreadAttach t;
if( t.pEnv )
{
// temporaere Variable initialisieren
static const char * cSignature = "()Ljava/lang/Object;";
static const char * cMethodName = "newInstance";
// Java-Call absetzen
static jmethodID mID = NULL;
if ( !mID )
mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
if( mID ){
out = t.pEnv->CallObjectMethod( object, mID);
ThrowSQLException(t.pEnv,0);
} //mID
} //t.pEnv
// ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
return out;
}
::rtl::OUString java_lang_Class::getName()
{
SDBThreadAttach t;
::rtl::OUString aStr;
if( t.pEnv ){
// temporaere Variable initialisieren
static const char * cSignature = "()Ljava/lang/String;";
static const char * cMethodName = "getName";
// Java-Call absetzen
static jmethodID mID = NULL;
if ( !mID )
mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
if( mID ){
jstring out = (jstring)t.pEnv->CallObjectMethod( object, mID);
ThrowSQLException(t.pEnv,0);
aStr = JavaString2String(t.pEnv, (jstring)out );
} //mID
} //t.pEnv
// ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
return aStr;
}
<commit_msg>INTEGRATION: CWS changefileheader (1.13.216); FILE MERGED 2008/04/01 15:08:50 thb 1.13.216.3: #i85898# Stripping all external header guards 2008/04/01 10:53:04 thb 1.13.216.2: #i85898# Stripping all external header guards 2008/03/28 15:23:41 rt 1.13.216.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: Class.cxx,v $
* $Revision: 1.14 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_connectivity.hxx"
#include "java/lang/Class.hxx"
#include "java/tools.hxx"
#include <rtl/ustring.hxx>
using namespace connectivity;
//**************************************************************
//************ Class: java.lang.Class
//**************************************************************
jclass java_lang_Class::theClass = 0;
java_lang_Class::~java_lang_Class()
{}
jclass java_lang_Class::getMyClass()
{
// die Klasse muss nur einmal geholt werden, daher statisch
if( !theClass ){
SDBThreadAttach t;
if( !t.pEnv ) return (jclass)NULL;
jclass tempClass = t.pEnv->FindClass("java/lang/Class"); OSL_ENSURE(tempClass,"Java : FindClass nicht erfolgreich!");
jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass );
t.pEnv->DeleteLocalRef( tempClass );
saveClassRef( globClass );
}
return theClass;
}
void java_lang_Class::saveClassRef( jclass pClass )
{
if( pClass==NULL )
return;
// der uebergebe Klassen-Handle ist schon global, daher einfach speichern
theClass = pClass;
}
java_lang_Class * java_lang_Class::forName( const ::rtl::OUString& _par0 )
{
jobject out(NULL);
SDBThreadAttach t;
if( t.pEnv )
{
::rtl::OString sClassName = ::rtl::OUStringToOString(_par0, RTL_TEXTENCODING_JAVA_UTF8);
sClassName = sClassName.replace('.','/');
out = t.pEnv->FindClass(sClassName);
ThrowSQLException(t.pEnv,0);
} //t.pEnv
// ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
return out==0 ? NULL : new java_lang_Class( t.pEnv, out );
}
sal_Bool java_lang_Class::isAssignableFrom( java_lang_Class * _par0 )
{
jboolean out(0);
SDBThreadAttach t;
if( t.pEnv ){
// temporaere Variable initialisieren
static const char * cSignature = "(Ljava/lang/Class;)Z";
static const char * cMethodName = "isAssignableFrom";
// Java-Call absetzen
static jmethodID mID = NULL;
if ( !mID )
mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
if( mID ){
jvalue args[1];
// Parameter konvertieren
args[0].l = _par0 != NULL ? ((java_lang_Object *)_par0)->getJavaObject() : NULL;
out = t.pEnv->CallBooleanMethod( object, mID, args[0].l );
ThrowSQLException(t.pEnv,0);
// und aufraeumen
} //mID
} //t.pEnv
return out;
}
java_lang_Object * java_lang_Class::newInstance()
{
jobject out(NULL);
SDBThreadAttach t;
if( t.pEnv ){
// temporaere Variable initialisieren
static const char * cSignature = "()Ljava/lang/Object;";
static const char * cMethodName = "newInstance";
// Java-Call absetzen
static jmethodID mID = NULL;
if ( !mID )
mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
if( mID ){
out = t.pEnv->CallObjectMethod( object, mID);
ThrowSQLException(t.pEnv,0);
} //mID
} //t.pEnv
// ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
return out==0 ? NULL : new java_lang_Object( t.pEnv, out );
}
jobject java_lang_Class::newInstanceObject()
{
jobject out(NULL);
SDBThreadAttach t;
if( t.pEnv )
{
// temporaere Variable initialisieren
static const char * cSignature = "()Ljava/lang/Object;";
static const char * cMethodName = "newInstance";
// Java-Call absetzen
static jmethodID mID = NULL;
if ( !mID )
mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
if( mID ){
out = t.pEnv->CallObjectMethod( object, mID);
ThrowSQLException(t.pEnv,0);
} //mID
} //t.pEnv
// ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
return out;
}
::rtl::OUString java_lang_Class::getName()
{
SDBThreadAttach t;
::rtl::OUString aStr;
if( t.pEnv ){
// temporaere Variable initialisieren
static const char * cSignature = "()Ljava/lang/String;";
static const char * cMethodName = "getName";
// Java-Call absetzen
static jmethodID mID = NULL;
if ( !mID )
mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
if( mID ){
jstring out = (jstring)t.pEnv->CallObjectMethod( object, mID);
ThrowSQLException(t.pEnv,0);
aStr = JavaString2String(t.pEnv, (jstring)out );
} //mID
} //t.pEnv
// ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
return aStr;
}
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2008, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include <cassert>
#include "boost/format.hpp"
#include "IECoreGL/ToGLMeshConverter.h"
#include "IECoreGL/MeshPrimitive.h"
#include "IECore/MeshPrimitive.h"
#include "IECore/TriangulateOp.h"
#include "IECore/MeshNormalsOp.h"
#include "IECore/DespatchTypedData.h"
#include "IECore/MessageHandler.h"
using namespace IECoreGL;
class ToGLMeshConverter::ToFaceVaryingConverter
{
public:
typedef IECore::DataPtr ReturnType;
ToFaceVaryingConverter( IECore::ConstIntVectorDataPtr vertIds ) : m_vertIds( vertIds )
{
assert( m_vertIds );
}
template<typename T>
IECore::DataPtr operator()( typename T::Ptr inData )
{
assert( inData );
const typename T::Ptr outData = new T();
outData->writable().resize( m_vertIds->readable().size() );
typename T::ValueType::iterator outIt = outData->writable().begin();
for ( typename T::ValueType::size_type i = 0; i < m_vertIds->readable().size(); i++ )
{
*outIt++ = inData->readable()[ m_vertIds->readable()[ i ] ];
}
return outData;
}
IECore::ConstIntVectorDataPtr m_vertIds;
};
ToGLMeshConverter::ToGLMeshConverter( IECore::ConstMeshPrimitivePtr toConvert )
: ToGLConverter( staticTypeName(), "Converts IECore::MeshPrimitive objects to IECoreGL::MeshPrimitive objects.", IECore::MeshPrimitiveTypeId )
{
srcParameter()->setValue( boost::const_pointer_cast<IECore::MeshPrimitive>( toConvert ) );
}
ToGLMeshConverter::~ToGLMeshConverter()
{
}
IECore::RunTimeTypedPtr ToGLMeshConverter::doConversion( IECore::ConstObjectPtr src, IECore::ConstCompoundObjectPtr operands ) const
{
IECore::MeshPrimitivePtr mesh = boost::static_pointer_cast<IECore::MeshPrimitive>( src->copy() ); // safe because the parameter validated it for us
IECore::TriangulateOpPtr op = new IECore::TriangulateOp();
op->inputParameter()->setValue( mesh );
op->throwExceptionsParameter()->setTypedValue( false ); // it's better to see something than nothing
mesh = IECore::runTimeCast< IECore::MeshPrimitive > ( op->operate() );
assert( mesh );
IECore::ConstV3fVectorDataPtr p = 0;
IECore::PrimitiveVariableMap::const_iterator pIt = mesh->variables.find( "P" );
if( pIt!=mesh->variables.end() )
{
if( pIt->second.interpolation==IECore::PrimitiveVariable::Vertex )
{
p = IECore::runTimeCast<const IECore::V3fVectorData>( pIt->second.data );
}
}
if( !p )
{
throw IECore::Exception( "Must specify primitive variable \"P\", of type V3fVectorData and interpolation type Vertex." );
}
IECore::ConstV3fVectorDataPtr n = 0;
IECore::PrimitiveVariableMap::const_iterator nIt = mesh->variables.find( "N" );
if( nIt != mesh->variables.end() )
{
if( nIt->second.interpolation==IECore::PrimitiveVariable::Vertex || nIt->second.interpolation==IECore::PrimitiveVariable::Varying || nIt->second.interpolation==IECore::PrimitiveVariable::FaceVarying )
{
n = IECore::runTimeCast<const IECore::V3fVectorData>( nIt->second.data );
}
if( !n )
{
throw IECore::Exception( "Must specify primitive variable \"N\", of type V3fVectorData" );
}
}
else
{
IECore::MeshNormalsOpPtr normOp = new IECore::MeshNormalsOp();
normOp->inputParameter()->setValue( mesh );
mesh = IECore::runTimeCast< IECore::MeshPrimitive > ( normOp->operate() );
assert( mesh );
nIt = mesh->variables.find( "N" );
assert( nIt != mesh->variables.end() );
n = IECore::runTimeCast<const IECore::V3fVectorData>( nIt->second.data );
}
assert( n );
MeshPrimitivePtr glMesh = new MeshPrimitive( mesh->vertexIds(), p );
ToFaceVaryingConverter primVarConverter( mesh->vertexIds() );
for ( IECore::PrimitiveVariableMap::iterator pIt = mesh->variables.begin(); pIt != mesh->variables.end(); ++pIt )
{
if ( pIt->second.data )
{
if ( pIt->second.interpolation==IECore::PrimitiveVariable::Vertex || pIt->second.interpolation==IECore::PrimitiveVariable::Varying )
{
IECore::DataPtr newData = IECore::despatchTypedData< ToFaceVaryingConverter, IECore::TypeTraits::IsVectorTypedData >( pIt->second.data, primVarConverter );
pIt->second.interpolation = IECore::PrimitiveVariable::FaceVarying;
glMesh->addVertexAttribute( pIt->first, newData );
}
else if ( pIt->second.interpolation==IECore::PrimitiveVariable::FaceVarying )
{
glMesh->addVertexAttribute( pIt->first, pIt->second.data );
}
}
else
{
IECore::msg( IECore::Msg::Warning, "ToGLMeshConverter", boost::format( "No data given for primvar \"%s\"" ) % pIt->first );
}
}
IECore::PrimitiveVariableMap::const_iterator sIt = mesh->variables.find( "s" );
IECore::PrimitiveVariableMap::const_iterator tIt = mesh->variables.find( "t" );
if ( sIt != mesh->variables.end() && tIt != mesh->variables.end() )
{
if ( sIt->second.interpolation == IECore::PrimitiveVariable::FaceVarying
&& tIt->second.interpolation == IECore::PrimitiveVariable::FaceVarying )
{
IECore::ConstFloatVectorDataPtr s = IECore::runTimeCast< const IECore::FloatVectorData >( sIt->second.data );
IECore::ConstFloatVectorDataPtr t = IECore::runTimeCast< const IECore::FloatVectorData >( tIt->second.data );
if ( s && t )
{
/// Should hold true if primvarsAreValid
assert( s->readable().size() == t->readable().size() );
IECore::V2fVectorDataPtr stData = new IECore::V2fVectorData();
stData->writable().resize( s->readable().size() );
for ( unsigned i = 0; i < s->readable().size(); i++ )
{
stData->writable()[i] = Imath::V2f( s->readable()[i], t->readable()[i] );
}
glMesh->addVertexAttribute( "st", stData );
}
else
{
IECore::msg( IECore::Msg::Warning, "ToGLMeshConverter", "If specified, primitive variables \"s\" and \"t\" must be of type FloatVectorData and interpolation type FaceVarying." );
}
}
else
{
IECore::msg( IECore::Msg::Warning, "ToGLMeshConverter", "If specified, primitive variables \"s\" and \"t\" must be of type FloatVectorData and interpolation type FaceVarying." );
}
}
else if ( sIt != mesh->variables.end() || tIt != mesh->variables.end() )
{
IECore::msg( IECore::Msg::Warning, "ToGLMeshConverter", "Primitive variable \"s\" or \"t\" found, but not both." );
}
return glMesh;
}
<commit_msg>Fixed a bug which meant that vertex s,t primvars would add invalid data to the gl mesh. They are now converted to facevarying and added.<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2008, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include <cassert>
#include "boost/format.hpp"
#include "IECoreGL/ToGLMeshConverter.h"
#include "IECoreGL/MeshPrimitive.h"
#include "IECore/MeshPrimitive.h"
#include "IECore/TriangulateOp.h"
#include "IECore/MeshNormalsOp.h"
#include "IECore/DespatchTypedData.h"
#include "IECore/MessageHandler.h"
using namespace IECoreGL;
/// \todo This should be in a standalone Op, and should cope with more than just Vertex interpolated input.
class ToGLMeshConverter::ToFaceVaryingConverter
{
public:
typedef IECore::DataPtr ReturnType;
ToFaceVaryingConverter( IECore::ConstIntVectorDataPtr vertIds ) : m_vertIds( vertIds )
{
assert( m_vertIds );
}
template<typename T>
IECore::DataPtr operator()( typename T::Ptr inData )
{
assert( inData );
const typename T::Ptr outData = new T();
outData->writable().resize( m_vertIds->readable().size() );
typename T::ValueType::iterator outIt = outData->writable().begin();
for ( typename T::ValueType::size_type i = 0; i < m_vertIds->readable().size(); i++ )
{
*outIt++ = inData->readable()[ m_vertIds->readable()[ i ] ];
}
return outData;
}
IECore::ConstIntVectorDataPtr m_vertIds;
};
ToGLMeshConverter::ToGLMeshConverter( IECore::ConstMeshPrimitivePtr toConvert )
: ToGLConverter( staticTypeName(), "Converts IECore::MeshPrimitive objects to IECoreGL::MeshPrimitive objects.", IECore::MeshPrimitiveTypeId )
{
srcParameter()->setValue( boost::const_pointer_cast<IECore::MeshPrimitive>( toConvert ) );
}
ToGLMeshConverter::~ToGLMeshConverter()
{
}
IECore::RunTimeTypedPtr ToGLMeshConverter::doConversion( IECore::ConstObjectPtr src, IECore::ConstCompoundObjectPtr operands ) const
{
IECore::MeshPrimitivePtr mesh = boost::static_pointer_cast<IECore::MeshPrimitive>( src->copy() ); // safe because the parameter validated it for us
IECore::TriangulateOpPtr op = new IECore::TriangulateOp();
op->inputParameter()->setValue( mesh );
op->throwExceptionsParameter()->setTypedValue( false ); // it's better to see something than nothing
mesh = IECore::runTimeCast< IECore::MeshPrimitive > ( op->operate() );
assert( mesh );
IECore::ConstV3fVectorDataPtr p = 0;
IECore::PrimitiveVariableMap::const_iterator pIt = mesh->variables.find( "P" );
if( pIt!=mesh->variables.end() )
{
if( pIt->second.interpolation==IECore::PrimitiveVariable::Vertex )
{
p = IECore::runTimeCast<const IECore::V3fVectorData>( pIt->second.data );
}
}
if( !p )
{
throw IECore::Exception( "Must specify primitive variable \"P\", of type V3fVectorData and interpolation type Vertex." );
}
IECore::ConstV3fVectorDataPtr n = 0;
IECore::PrimitiveVariableMap::const_iterator nIt = mesh->variables.find( "N" );
if( nIt != mesh->variables.end() )
{
if( nIt->second.interpolation==IECore::PrimitiveVariable::Vertex || nIt->second.interpolation==IECore::PrimitiveVariable::Varying || nIt->second.interpolation==IECore::PrimitiveVariable::FaceVarying )
{
n = IECore::runTimeCast<const IECore::V3fVectorData>( nIt->second.data );
}
if( !n )
{
throw IECore::Exception( "Must specify primitive variable \"N\", of type V3fVectorData" );
}
}
else
{
IECore::MeshNormalsOpPtr normOp = new IECore::MeshNormalsOp();
normOp->inputParameter()->setValue( mesh );
mesh = IECore::runTimeCast< IECore::MeshPrimitive > ( normOp->operate() );
assert( mesh );
nIt = mesh->variables.find( "N" );
assert( nIt != mesh->variables.end() );
n = IECore::runTimeCast<const IECore::V3fVectorData>( nIt->second.data );
}
assert( n );
MeshPrimitivePtr glMesh = new MeshPrimitive( mesh->vertexIds(), p );
ToFaceVaryingConverter primVarConverter( mesh->vertexIds() );
for ( IECore::PrimitiveVariableMap::iterator pIt = mesh->variables.begin(); pIt != mesh->variables.end(); ++pIt )
{
if ( pIt->second.data )
{
if ( pIt->second.interpolation==IECore::PrimitiveVariable::Vertex || pIt->second.interpolation==IECore::PrimitiveVariable::Varying )
{
// convert to facevarying
IECore::DataPtr newData = IECore::despatchTypedData< ToFaceVaryingConverter, IECore::TypeTraits::IsVectorTypedData >( pIt->second.data, primVarConverter );
glMesh->addVertexAttribute( pIt->first, newData );
// modify the primvar we converted in case it is "s" or "t", then we don't have to do another conversion below.
pIt->second.interpolation = IECore::PrimitiveVariable::FaceVarying;
pIt->second.data = newData;
}
else if ( pIt->second.interpolation==IECore::PrimitiveVariable::FaceVarying )
{
glMesh->addVertexAttribute( pIt->first, pIt->second.data );
}
}
else
{
IECore::msg( IECore::Msg::Warning, "ToGLMeshConverter", boost::format( "No data given for primvar \"%s\"" ) % pIt->first );
}
}
IECore::PrimitiveVariableMap::const_iterator sIt = mesh->variables.find( "s" );
IECore::PrimitiveVariableMap::const_iterator tIt = mesh->variables.find( "t" );
if ( sIt != mesh->variables.end() && tIt != mesh->variables.end() )
{
if ( sIt->second.interpolation == IECore::PrimitiveVariable::FaceVarying
&& tIt->second.interpolation == IECore::PrimitiveVariable::FaceVarying )
{
IECore::ConstFloatVectorDataPtr s = IECore::runTimeCast< const IECore::FloatVectorData >( sIt->second.data );
IECore::ConstFloatVectorDataPtr t = IECore::runTimeCast< const IECore::FloatVectorData >( tIt->second.data );
if ( s && t )
{
/// Should hold true if primvarsAreValid
assert( s->readable().size() == t->readable().size() );
IECore::V2fVectorDataPtr stData = new IECore::V2fVectorData();
stData->writable().resize( s->readable().size() );
for ( unsigned i = 0; i < s->readable().size(); i++ )
{
stData->writable()[i] = Imath::V2f( s->readable()[i], t->readable()[i] );
}
glMesh->addVertexAttribute( "st", stData );
}
else
{
IECore::msg( IECore::Msg::Warning, "ToGLMeshConverter", "If specified, primitive variables \"s\" and \"t\" must be of type FloatVectorData and interpolation type FaceVarying." );
}
}
else
{
IECore::msg( IECore::Msg::Warning, "ToGLMeshConverter", "If specified, primitive variables \"s\" and \"t\" must be of type FloatVectorData and interpolation type FaceVarying." );
}
}
else if ( sIt != mesh->variables.end() || tIt != mesh->variables.end() )
{
IECore::msg( IECore::Msg::Warning, "ToGLMeshConverter", "Primitive variable \"s\" or \"t\" found, but not both." );
}
return glMesh;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2011 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkBlurImageFilter.h"
#include "SkColorPriv.h"
SkBlurImageFilter::SkBlurImageFilter(SkFlattenableReadBuffer& buffer)
: INHERITED(buffer) {
fSigma.fWidth = buffer.readScalar();
fSigma.fHeight = buffer.readScalar();
}
SkBlurImageFilter::SkBlurImageFilter(SkScalar sigmaX, SkScalar sigmaY)
: fSigma(SkSize::Make(sigmaX, sigmaY)) {
SkASSERT(sigmaX >= 0 && sigmaY >= 0);
}
bool SkBlurImageFilter::asABlur(SkSize* sigma) const {
*sigma = fSigma;
return true;
}
void SkBlurImageFilter::flatten(SkFlattenableWriteBuffer& buffer) {
this->INHERITED::flatten(buffer);
buffer.writeScalar(fSigma.fWidth);
buffer.writeScalar(fSigma.fHeight);
}
static void boxBlurX(const SkBitmap& src, SkBitmap* dst, int kernelSize,
int leftOffset, int rightOffset)
{
int width = src.width(), height = src.height();
int rightBorder = SkMin32(rightOffset + 1, width);
for (int y = 0; y < height; ++y) {
int sumA = 0, sumR = 0, sumG = 0, sumB = 0;
SkPMColor* p = src.getAddr32(0, y);
for (int i = 0; i < rightBorder; ++i) {
sumA += SkGetPackedA32(*p);
sumR += SkGetPackedR32(*p);
sumG += SkGetPackedG32(*p);
sumB += SkGetPackedB32(*p);
p++;
}
const SkColor* sptr = src.getAddr32(0, y);
SkColor* dptr = dst->getAddr32(0, y);
for (int x = 0; x < width; ++x) {
*dptr = SkPackARGB32(sumA / kernelSize,
sumR / kernelSize,
sumG / kernelSize,
sumB / kernelSize);
if (x >= leftOffset) {
SkColor l = *(sptr - leftOffset);
sumA -= SkGetPackedA32(l);
sumR -= SkGetPackedR32(l);
sumG -= SkGetPackedG32(l);
sumB -= SkGetPackedB32(l);
}
if (x + rightOffset + 1 < width) {
SkColor r = *(sptr + rightOffset + 1);
sumA += SkGetPackedA32(r);
sumR += SkGetPackedR32(r);
sumG += SkGetPackedG32(r);
sumB += SkGetPackedB32(r);
}
sptr++;
dptr++;
}
}
}
static void boxBlurY(const SkBitmap& src, SkBitmap* dst, int kernelSize,
int topOffset, int bottomOffset)
{
int width = src.width(), height = src.height();
int bottomBorder = SkMin32(bottomOffset + 1, height);
int srcStride = src.rowBytesAsPixels();
int dstStride = dst->rowBytesAsPixels();
for (int x = 0; x < width; ++x) {
int sumA = 0, sumR = 0, sumG = 0, sumB = 0;
SkColor* p = src.getAddr32(x, 0);
for (int i = 0; i < bottomBorder; ++i) {
sumA += SkGetPackedA32(*p);
sumR += SkGetPackedR32(*p);
sumG += SkGetPackedG32(*p);
sumB += SkGetPackedB32(*p);
p += srcStride;
}
const SkColor* sptr = src.getAddr32(x, 0);
SkColor* dptr = dst->getAddr32(x, 0);
for (int y = 0; y < height; ++y) {
*dptr = SkPackARGB32(sumA / kernelSize,
sumR / kernelSize,
sumG / kernelSize,
sumB / kernelSize);
if (y >= topOffset) {
SkColor l = *(sptr - topOffset * srcStride);
sumA -= SkGetPackedA32(l);
sumR -= SkGetPackedR32(l);
sumG -= SkGetPackedG32(l);
sumB -= SkGetPackedB32(l);
}
if (y + bottomOffset + 1 < height) {
SkColor r = *(sptr + (bottomOffset + 1) * srcStride);
sumA += SkGetPackedA32(r);
sumR += SkGetPackedR32(r);
sumG += SkGetPackedG32(r);
sumB += SkGetPackedB32(r);
}
sptr += srcStride;
dptr += dstStride;
}
}
}
static void getBox3Params(SkScalar s, int *kernelSize, int* kernelSize3, int *lowOffset, int *highOffset)
{
int d = static_cast<int>(floorf(SkScalarToFloat(s) * 3.0f * sqrtf(2.0f * M_PI) / 4.0f + 0.5f));
*kernelSize = d;
if (d % 2 == 1) {
*lowOffset = *highOffset = (d - 1) / 2;
*kernelSize3 = d;
} else {
*highOffset = d / 2;
*lowOffset = *highOffset - 1;
*kernelSize3 = d + 1;
}
}
bool SkBlurImageFilter::onFilterImage(const SkBitmap& src, const SkMatrix&,
SkBitmap* dst, SkIPoint*) {
if (src.config() != SkBitmap::kARGB_8888_Config) {
return false;
}
dst->setConfig(src.config(), src.width(), src.height());
dst->allocPixels();
int kernelSizeX, kernelSizeX3, lowOffsetX, highOffsetX;
int kernelSizeY, kernelSizeY3, lowOffsetY, highOffsetY;
getBox3Params(fSigma.width(), &kernelSizeX, &kernelSizeX3, &lowOffsetX, &highOffsetX);
getBox3Params(fSigma.height(), &kernelSizeY, &kernelSizeY3, &lowOffsetY, &highOffsetY);
if (kernelSizeX < 0 || kernelSizeY < 0) {
return false;
}
if (kernelSizeX == 0 && kernelSizeY == 0) {
src.copyTo(dst, dst->config());
return true;
}
SkBitmap temp;
temp.setConfig(dst->config(), dst->width(), dst->height());
if (!temp.allocPixels()) {
return false;
}
if (kernelSizeX > 0 && kernelSizeY > 0) {
boxBlurX(src, &temp, kernelSizeX, lowOffsetX, highOffsetX);
boxBlurY(temp, dst, kernelSizeY, lowOffsetY, highOffsetY);
boxBlurX(*dst, &temp, kernelSizeX, highOffsetX, lowOffsetX);
boxBlurY(temp, dst, kernelSizeY, highOffsetY, lowOffsetY);
boxBlurX(*dst, &temp, kernelSizeX3, highOffsetX, highOffsetX);
boxBlurY(temp, dst, kernelSizeY3, highOffsetY, highOffsetY);
} else if (kernelSizeX > 0) {
boxBlurX(src, dst, kernelSizeX, lowOffsetX, highOffsetX);
boxBlurX(*dst, &temp, kernelSizeX, highOffsetX, lowOffsetX);
boxBlurX(temp, dst, kernelSizeX3, highOffsetX, highOffsetX);
} else if (kernelSizeY > 0) {
boxBlurY(src, dst, kernelSizeY, lowOffsetY, highOffsetY);
boxBlurY(*dst, &temp, kernelSizeY, highOffsetY, lowOffsetY);
boxBlurY(temp, dst, kernelSizeY3, highOffsetY, highOffsetY);
}
return true;
}
SK_DEFINE_FLATTENABLE_REGISTRAR(SkBlurImageFilter)
<commit_msg>Unreviewed. Fixing the Windows build, due to a non definition of M_PI.<commit_after>/*
* Copyright 2011 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkBlurImageFilter.h"
#include "SkColorPriv.h"
SkBlurImageFilter::SkBlurImageFilter(SkFlattenableReadBuffer& buffer)
: INHERITED(buffer) {
fSigma.fWidth = buffer.readScalar();
fSigma.fHeight = buffer.readScalar();
}
SkBlurImageFilter::SkBlurImageFilter(SkScalar sigmaX, SkScalar sigmaY)
: fSigma(SkSize::Make(sigmaX, sigmaY)) {
SkASSERT(sigmaX >= 0 && sigmaY >= 0);
}
bool SkBlurImageFilter::asABlur(SkSize* sigma) const {
*sigma = fSigma;
return true;
}
void SkBlurImageFilter::flatten(SkFlattenableWriteBuffer& buffer) {
this->INHERITED::flatten(buffer);
buffer.writeScalar(fSigma.fWidth);
buffer.writeScalar(fSigma.fHeight);
}
static void boxBlurX(const SkBitmap& src, SkBitmap* dst, int kernelSize,
int leftOffset, int rightOffset)
{
int width = src.width(), height = src.height();
int rightBorder = SkMin32(rightOffset + 1, width);
for (int y = 0; y < height; ++y) {
int sumA = 0, sumR = 0, sumG = 0, sumB = 0;
SkPMColor* p = src.getAddr32(0, y);
for (int i = 0; i < rightBorder; ++i) {
sumA += SkGetPackedA32(*p);
sumR += SkGetPackedR32(*p);
sumG += SkGetPackedG32(*p);
sumB += SkGetPackedB32(*p);
p++;
}
const SkColor* sptr = src.getAddr32(0, y);
SkColor* dptr = dst->getAddr32(0, y);
for (int x = 0; x < width; ++x) {
*dptr = SkPackARGB32(sumA / kernelSize,
sumR / kernelSize,
sumG / kernelSize,
sumB / kernelSize);
if (x >= leftOffset) {
SkColor l = *(sptr - leftOffset);
sumA -= SkGetPackedA32(l);
sumR -= SkGetPackedR32(l);
sumG -= SkGetPackedG32(l);
sumB -= SkGetPackedB32(l);
}
if (x + rightOffset + 1 < width) {
SkColor r = *(sptr + rightOffset + 1);
sumA += SkGetPackedA32(r);
sumR += SkGetPackedR32(r);
sumG += SkGetPackedG32(r);
sumB += SkGetPackedB32(r);
}
sptr++;
dptr++;
}
}
}
static void boxBlurY(const SkBitmap& src, SkBitmap* dst, int kernelSize,
int topOffset, int bottomOffset)
{
int width = src.width(), height = src.height();
int bottomBorder = SkMin32(bottomOffset + 1, height);
int srcStride = src.rowBytesAsPixels();
int dstStride = dst->rowBytesAsPixels();
for (int x = 0; x < width; ++x) {
int sumA = 0, sumR = 0, sumG = 0, sumB = 0;
SkColor* p = src.getAddr32(x, 0);
for (int i = 0; i < bottomBorder; ++i) {
sumA += SkGetPackedA32(*p);
sumR += SkGetPackedR32(*p);
sumG += SkGetPackedG32(*p);
sumB += SkGetPackedB32(*p);
p += srcStride;
}
const SkColor* sptr = src.getAddr32(x, 0);
SkColor* dptr = dst->getAddr32(x, 0);
for (int y = 0; y < height; ++y) {
*dptr = SkPackARGB32(sumA / kernelSize,
sumR / kernelSize,
sumG / kernelSize,
sumB / kernelSize);
if (y >= topOffset) {
SkColor l = *(sptr - topOffset * srcStride);
sumA -= SkGetPackedA32(l);
sumR -= SkGetPackedR32(l);
sumG -= SkGetPackedG32(l);
sumB -= SkGetPackedB32(l);
}
if (y + bottomOffset + 1 < height) {
SkColor r = *(sptr + (bottomOffset + 1) * srcStride);
sumA += SkGetPackedA32(r);
sumR += SkGetPackedR32(r);
sumG += SkGetPackedG32(r);
sumB += SkGetPackedB32(r);
}
sptr += srcStride;
dptr += dstStride;
}
}
}
static void getBox3Params(SkScalar s, int *kernelSize, int* kernelSize3, int *lowOffset, int *highOffset)
{
float pi = SkScalarToFloat(SK_ScalarPI);
int d = static_cast<int>(floorf(SkScalarToFloat(s) * 3.0f * sqrtf(2.0f * pi) / 4.0f + 0.5f));
*kernelSize = d;
if (d % 2 == 1) {
*lowOffset = *highOffset = (d - 1) / 2;
*kernelSize3 = d;
} else {
*highOffset = d / 2;
*lowOffset = *highOffset - 1;
*kernelSize3 = d + 1;
}
}
bool SkBlurImageFilter::onFilterImage(const SkBitmap& src, const SkMatrix&,
SkBitmap* dst, SkIPoint*) {
if (src.config() != SkBitmap::kARGB_8888_Config) {
return false;
}
dst->setConfig(src.config(), src.width(), src.height());
dst->allocPixels();
int kernelSizeX, kernelSizeX3, lowOffsetX, highOffsetX;
int kernelSizeY, kernelSizeY3, lowOffsetY, highOffsetY;
getBox3Params(fSigma.width(), &kernelSizeX, &kernelSizeX3, &lowOffsetX, &highOffsetX);
getBox3Params(fSigma.height(), &kernelSizeY, &kernelSizeY3, &lowOffsetY, &highOffsetY);
if (kernelSizeX < 0 || kernelSizeY < 0) {
return false;
}
if (kernelSizeX == 0 && kernelSizeY == 0) {
src.copyTo(dst, dst->config());
return true;
}
SkBitmap temp;
temp.setConfig(dst->config(), dst->width(), dst->height());
if (!temp.allocPixels()) {
return false;
}
if (kernelSizeX > 0 && kernelSizeY > 0) {
boxBlurX(src, &temp, kernelSizeX, lowOffsetX, highOffsetX);
boxBlurY(temp, dst, kernelSizeY, lowOffsetY, highOffsetY);
boxBlurX(*dst, &temp, kernelSizeX, highOffsetX, lowOffsetX);
boxBlurY(temp, dst, kernelSizeY, highOffsetY, lowOffsetY);
boxBlurX(*dst, &temp, kernelSizeX3, highOffsetX, highOffsetX);
boxBlurY(temp, dst, kernelSizeY3, highOffsetY, highOffsetY);
} else if (kernelSizeX > 0) {
boxBlurX(src, dst, kernelSizeX, lowOffsetX, highOffsetX);
boxBlurX(*dst, &temp, kernelSizeX, highOffsetX, lowOffsetX);
boxBlurX(temp, dst, kernelSizeX3, highOffsetX, highOffsetX);
} else if (kernelSizeY > 0) {
boxBlurY(src, dst, kernelSizeY, lowOffsetY, highOffsetY);
boxBlurY(*dst, &temp, kernelSizeY, highOffsetY, lowOffsetY);
boxBlurY(temp, dst, kernelSizeY3, highOffsetY, highOffsetY);
}
return true;
}
SK_DEFINE_FLATTENABLE_REGISTRAR(SkBlurImageFilter)
<|endoftext|> |
<commit_before>// Copyright (c) 2019 The Zcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "../property.h"
#include "../sigmadb.h"
#include "../sigmaprimitives.h"
#include "../wallet.h"
#include "../walletmodels.h"
#include "../../wallet/wallet.h"
#include "../../wallet/walletexcept.h"
#include "../../wallet/test/wallet_test_fixture.h"
#include <boost/optional/optional_io.hpp>
#include <boost/test/unit_test.hpp>
#include <iterator>
#include <ostream>
#include <stdexcept>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
namespace std {
template<class Char, class Traits, unsigned Size>
basic_ostream<Char, Traits>& operator<<(basic_ostream<Char, Traits>& os, const base_blob<Size>& v)
{
return os << v.GetHex();
}
} // namespace std
namespace elysium {
struct WalletTestingSetup : ::WalletTestingSetup
{
WalletTestingSetup()
{
sigmaDb = new SigmaDatabase(pathTemp / "elysium_sigma_tests", true, 10);
wallet = new Wallet(pwalletMain->strWalletFile);
wallet->ReloadMasterKey();
}
~WalletTestingSetup()
{
delete wallet; wallet = nullptr;
delete sigmaDb; sigmaDb = nullptr;
}
SigmaMint CreateSigmaMint(PropertyId property, SigmaDenomination denomination)
{
auto id = wallet->CreateSigmaMint(property, denomination);
return wallet->GetSigmaMint(id);
}
};
BOOST_FIXTURE_TEST_SUITE(elysium_wallet_tests, WalletTestingSetup)
BOOST_AUTO_TEST_CASE(sigma_mint_create_one)
{
auto id = wallet->CreateSigmaMint(1, 2);
auto mint = wallet->GetSigmaMint(id);
BOOST_CHECK(id.pubKey.IsValid());
BOOST_CHECK_EQUAL(1, id.property);
BOOST_CHECK_EQUAL(2, id.denomination);
BOOST_CHECK_EQUAL(id.property, mint.property);
BOOST_CHECK_EQUAL(id.denomination, mint.denomination);
BOOST_CHECK(!mint.IsSpent());
BOOST_CHECK_EQUAL(mint.chainState, SigmaMintChainState());
auto priv = wallet->GetKey(mint);
SigmaPublicKey pub(priv, DefaultSigmaParams);
BOOST_CHECK_EQUAL(id.pubKey, pub);
auto another = CreateSigmaMint(1, 2);
BOOST_CHECK_NE(another, mint);
}
BOOST_AUTO_TEST_CASE(sigma_mint_create_multi)
{
std::vector<SigmaDenomination> denominations = {0, 1, 0, 2};
std::vector<SigmaMintId> ids(5);
std::unordered_set<SigmaMint> mints;
auto next = wallet->CreateSigmaMints(1, denominations.begin(), denominations.end(), ids.begin());
BOOST_CHECK_EQUAL(std::distance(ids.begin(), next), 4);
BOOST_CHECK_EQUAL(ids[0].denomination, 0);
BOOST_CHECK_EQUAL(ids[1].denomination, 1);
BOOST_CHECK_EQUAL(ids[2].denomination, 0);
BOOST_CHECK_EQUAL(ids[3].denomination, 2);
for (auto it = ids.begin(); it != next; it++) {
auto& id = *it;
auto mint = wallet->GetSigmaMint(id);
BOOST_CHECK_EQUAL(id.property, 1);
BOOST_CHECK_EQUAL(mint.property, id.property);
BOOST_CHECK_EQUAL(id.denomination, mint.denomination);
BOOST_CHECK(id.pubKey.IsValid());
BOOST_CHECK_NE(id.pubKey, SigmaPublicKey());
BOOST_CHECK(!mint.IsSpent());
BOOST_CHECK_EQUAL(mint.chainState, SigmaMintChainState());
BOOST_CHECK(mints.insert(std::move(mint)).second);
auto priv = wallet->GetKey(mint);
SigmaPublicKey pub(priv, DefaultSigmaParams);
BOOST_CHECK_EQUAL(pub, id.pubKey);
}
}
BOOST_AUTO_TEST_CASE(sigma_spend_create_no_spendable_mint)
{
// No any mints.
BOOST_CHECK_THROW(wallet->CreateSigmaSpendV1(3, 0, false), InsufficientFunds);
// Different denomination and property type.
auto mintId = wallet->CreateSigmaMint(3, 0);
BOOST_CHECK_THROW(wallet->CreateSigmaSpendV1(3, 1, false), InsufficientFunds);
BOOST_CHECK_THROW(wallet->CreateSigmaSpendV1(4, 0, false), InsufficientFunds);
// Pending mint.
BOOST_CHECK_THROW(wallet->CreateSigmaSpendV1(3, 0, false), InsufficientFunds);
// Already spent.
sigmaDb->RecordMint(3, 0, mintId.pubKey, 100);
wallet->SetSigmaMintUsedTransaction(mintId, uint256S("890e968f9b65dbacd576100c9b1c446f06471ed27df845ab7a24931cb640b388"));
BOOST_CHECK_THROW(wallet->CreateSigmaSpendV1(3, 0, false), InsufficientFunds);
}
BOOST_AUTO_TEST_CASE(sigma_spend_create_with_spendable_mints)
{
// Create first full group and one mint in a next group.
auto expectedMintId = wallet->CreateSigmaMint(3, 0);
sigmaDb->RecordMint(3, 0, expectedMintId.pubKey, 100);
for (unsigned i = 1; i <= sigmaDb->groupSize; i++) {
auto mintid = wallet->CreateSigmaMint(3, 0);
sigmaDb->RecordMint(3, 0, mintid.pubKey, 100 + i);
}
auto spend = wallet->CreateSigmaSpendV1(3, 0, false);
BOOST_CHECK_EQUAL(spend.mint, expectedMintId);
BOOST_CHECK_EQUAL(spend.group, 0);
BOOST_CHECK_EQUAL(spend.groupSize, sigmaDb->groupSize);
}
BOOST_AUTO_TEST_CASE(sigma_spend_create_not_enough_anonimity)
{
auto mintId = wallet->CreateSigmaMint(3, 0);
sigmaDb->RecordMint(3, 0, mintId.pubKey, 100);
BOOST_CHECK_EXCEPTION(wallet->CreateSigmaSpendV1(3, 0, false), WalletError, [] (const WalletError& e) {
return e.what() == std::string("Amount of coins in anonimity set is not enough to spend");
});
}
BOOST_AUTO_TEST_CASE(sigma_mint_listing_all)
{
// Create mints.
std::unordered_set<SigmaMintId> ids;
ids.insert(wallet->CreateSigmaMint(1, 0));
ids.insert(wallet->CreateSigmaMint(2, 0));
ids.insert(wallet->CreateSigmaMint(1, 1));
ids.insert(wallet->CreateSigmaMint(2, 0));
BOOST_CHECK_EQUAL(ids.size(), 4);
// List mints.
std::unordered_map<SigmaMintId, SigmaMint> mints;
wallet->ListSigmaMintsV1(std::inserter(mints, mints.begin()));
BOOST_CHECK_EQUAL(mints.size(), ids.size());
for (auto& mint : mints) {
auto it = ids.find(mint.first);
BOOST_CHECK(it != ids.end());
BOOST_CHECK_EQUAL(mint.second, wallet->GetSigmaMint(*it));
ids.erase(it);
}
BOOST_CHECK_EQUAL(ids.size(), 0);
}
BOOST_AUTO_TEST_CASE(sigma_mint_check_existence)
{
auto owned = wallet->CreateSigmaMint(1, 1);
SigmaPrivateKey priv;
SigmaPublicKey pub;
priv.Generate();
pub.Generate(priv, DefaultSigmaParams);
SigmaMintId other(1, 1, pub);
BOOST_CHECK_EQUAL(wallet->HasSigmaMint(owned), true);
BOOST_CHECK_EQUAL(wallet->HasSigmaMint(other), false);
}
BOOST_AUTO_TEST_CASE(sigma_mint_get)
{
// Get existence.
auto owned = wallet->CreateSigmaMint(1, 1);
auto mint = wallet->GetSigmaMint(owned);
SigmaPublicKey pub(wallet->GetKey(mint), DefaultSigmaParams);
BOOST_CHECK_EQUAL(owned, SigmaMintId(mint.property, mint.denomination, pub));
// Get non-existence.
SigmaPrivateKey otherPriv;
SigmaPublicKey otherPub;
otherPriv.Generate();
otherPub.Generate(otherPriv, DefaultSigmaParams);
SigmaMintId other(1, 1, otherPub);
BOOST_CHECK_THROW(wallet->GetSigmaMint(other), std::runtime_error);
}
BOOST_AUTO_TEST_CASE(sigma_mint_set_used)
{
auto tx = uint256S("64c4c22a45ad449be61c52a431d11e81f7fd0ee2f2235bf02944fb0b3dd07adb");
auto id = wallet->CreateSigmaMint(1, 1);
SigmaMint mint;
wallet->SetSigmaMintUsedTransaction(id, tx);
mint = wallet->GetSigmaMint(id);
BOOST_CHECK_EQUAL(mint.spendTx, tx);
wallet->SetSigmaMintUsedTransaction(id, uint256());
mint = wallet->GetSigmaMint(id);
BOOST_CHECK(!mint.IsSpent());
}
BOOST_AUTO_TEST_CASE(sigma_mint_chainstate_owned)
{
auto id = wallet->CreateSigmaMint(1, 0);
SigmaMintGroup group;
SigmaMintIndex index;
SigmaMint mint;
// Add.
std::tie(group, index) = sigmaDb->RecordMint(1, 0, id.pubKey, 100);
mint = wallet->GetSigmaMint(id);
BOOST_CHECK_EQUAL(mint.chainState.block, 100);
BOOST_CHECK_EQUAL(mint.chainState.group, group);
BOOST_CHECK_EQUAL(mint.chainState.index, index);
// Remove.
sigmaDb->DeleteAll(100);
mint = wallet->GetSigmaMint(id);
BOOST_CHECK_EQUAL(mint.chainState, SigmaMintChainState());
}
BOOST_AUTO_TEST_CASE(sigma_mint_chainstate_not_owned)
{
// Add our mint first so we can test if the other mint does not alter our mint state.
auto id = wallet->CreateSigmaMint(1, 0);
SigmaMintGroup group;
SigmaMintIndex index;
std::tie(group, index) = sigmaDb->RecordMint(1, 0, id.pubKey, 100);
// Add other mint.
SigmaPrivateKey otherPriv;
SigmaPublicKey otherPub;
otherPriv.Generate();
otherPub.Generate(otherPriv, DefaultSigmaParams);
sigmaDb->RecordMint(1, 0, otherPub, 101);
// Our chain state should not updated.
SigmaMint mint;
mint = wallet->GetSigmaMint(id);
BOOST_CHECK_EQUAL(mint.chainState.block, 100);
BOOST_CHECK_EQUAL(mint.chainState.group, group);
BOOST_CHECK_EQUAL(mint.chainState.index, index);
// Other mint should not added to our wallet.
BOOST_CHECK_THROW(
wallet->GetSigmaMint(SigmaMintId(1, 0, otherPub)),
std::runtime_error
);
// Remove other mint and our chain state should not updated.
sigmaDb->DeleteAll(101);
mint = wallet->GetSigmaMint(id);
BOOST_CHECK_EQUAL(mint.chainState.block, 100);
BOOST_CHECK_EQUAL(mint.chainState.group, group);
BOOST_CHECK_EQUAL(mint.chainState.index, index);
}
BOOST_AUTO_TEST_SUITE_END()
}
<commit_msg>Fix invalid assertion<commit_after>// Copyright (c) 2019 The Zcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "../property.h"
#include "../sigmadb.h"
#include "../sigmaprimitives.h"
#include "../wallet.h"
#include "../walletmodels.h"
#include "../../wallet/wallet.h"
#include "../../wallet/walletexcept.h"
#include "../../wallet/test/wallet_test_fixture.h"
#include <boost/optional/optional_io.hpp>
#include <boost/test/unit_test.hpp>
#include <iterator>
#include <ostream>
#include <stdexcept>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
namespace std {
template<class Char, class Traits, unsigned Size>
basic_ostream<Char, Traits>& operator<<(basic_ostream<Char, Traits>& os, const base_blob<Size>& v)
{
return os << v.GetHex();
}
} // namespace std
namespace elysium {
struct WalletTestingSetup : ::WalletTestingSetup
{
WalletTestingSetup()
{
sigmaDb = new SigmaDatabase(pathTemp / "elysium_sigma_tests", true, 10);
wallet = new Wallet(pwalletMain->strWalletFile);
wallet->ReloadMasterKey();
}
~WalletTestingSetup()
{
delete wallet; wallet = nullptr;
delete sigmaDb; sigmaDb = nullptr;
}
SigmaMint CreateSigmaMint(PropertyId property, SigmaDenomination denomination)
{
auto id = wallet->CreateSigmaMint(property, denomination);
return wallet->GetSigmaMint(id);
}
};
BOOST_FIXTURE_TEST_SUITE(elysium_wallet_tests, WalletTestingSetup)
BOOST_AUTO_TEST_CASE(sigma_mint_create_one)
{
auto id = wallet->CreateSigmaMint(1, 2);
auto mint = wallet->GetSigmaMint(id);
BOOST_CHECK(id.pubKey.IsValid());
BOOST_CHECK_EQUAL(1, id.property);
BOOST_CHECK_EQUAL(2, id.denomination);
BOOST_CHECK_EQUAL(id.property, mint.property);
BOOST_CHECK_EQUAL(id.denomination, mint.denomination);
BOOST_CHECK(!mint.IsSpent());
BOOST_CHECK_EQUAL(mint.chainState, SigmaMintChainState());
auto priv = wallet->GetKey(mint);
SigmaPublicKey pub(priv, DefaultSigmaParams);
BOOST_CHECK_EQUAL(id.pubKey, pub);
auto another = CreateSigmaMint(1, 2);
BOOST_CHECK_NE(another, mint);
}
BOOST_AUTO_TEST_CASE(sigma_mint_create_multi)
{
std::vector<SigmaDenomination> denominations = {0, 1, 0, 2};
std::vector<SigmaMintId> ids(5);
std::unordered_set<SigmaMint> mints;
auto next = wallet->CreateSigmaMints(1, denominations.begin(), denominations.end(), ids.begin());
BOOST_CHECK_EQUAL(std::distance(ids.begin(), next), 4);
BOOST_CHECK_EQUAL(ids[0].denomination, 0);
BOOST_CHECK_EQUAL(ids[1].denomination, 1);
BOOST_CHECK_EQUAL(ids[2].denomination, 0);
BOOST_CHECK_EQUAL(ids[3].denomination, 2);
for (auto it = ids.begin(); it != next; it++) {
auto& id = *it;
auto mint = wallet->GetSigmaMint(id);
BOOST_CHECK_EQUAL(id.property, 1);
BOOST_CHECK_EQUAL(mint.property, id.property);
BOOST_CHECK_EQUAL(id.denomination, mint.denomination);
BOOST_CHECK(id.pubKey.IsValid());
BOOST_CHECK_NE(id.pubKey, SigmaPublicKey());
BOOST_CHECK(!mint.IsSpent());
BOOST_CHECK_EQUAL(mint.chainState, SigmaMintChainState());
BOOST_CHECK(mints.insert(std::move(mint)).second);
auto priv = wallet->GetKey(mint);
SigmaPublicKey pub(priv, DefaultSigmaParams);
BOOST_CHECK_EQUAL(pub, id.pubKey);
}
}
BOOST_AUTO_TEST_CASE(sigma_spend_create_no_spendable_mint)
{
// No any mints.
BOOST_CHECK_THROW(wallet->CreateSigmaSpendV1(3, 0, false), InsufficientFunds);
// Different denomination and property type.
auto mintId = wallet->CreateSigmaMint(3, 0);
BOOST_CHECK_THROW(wallet->CreateSigmaSpendV1(3, 1, false), InsufficientFunds);
BOOST_CHECK_THROW(wallet->CreateSigmaSpendV1(4, 0, false), InsufficientFunds);
// Pending mint.
BOOST_CHECK_THROW(wallet->CreateSigmaSpendV1(3, 0, false), InsufficientFunds);
// Already spent.
sigmaDb->RecordMint(3, 0, mintId.pubKey, 100);
wallet->SetSigmaMintUsedTransaction(mintId, uint256S("890e968f9b65dbacd576100c9b1c446f06471ed27df845ab7a24931cb640b388"));
BOOST_CHECK_THROW(wallet->CreateSigmaSpendV1(3, 0, false), InsufficientFunds);
}
BOOST_AUTO_TEST_CASE(sigma_spend_create_with_spendable_mints)
{
// Create first full group and one mint in a next group.
auto expectedMintId = wallet->CreateSigmaMint(3, 0);
sigmaDb->RecordMint(3, 0, expectedMintId.pubKey, 100);
for (unsigned i = 1; i <= sigmaDb->groupSize; i++) {
auto mintid = wallet->CreateSigmaMint(3, 0);
sigmaDb->RecordMint(3, 0, mintid.pubKey, 100 + i);
}
auto spend = wallet->CreateSigmaSpendV1(3, 0, false);
BOOST_CHECK_EQUAL(spend.mint, expectedMintId);
BOOST_CHECK_EQUAL(spend.group, 0);
BOOST_CHECK_EQUAL(spend.groupSize, sigmaDb->groupSize);
}
BOOST_AUTO_TEST_CASE(sigma_spend_create_not_enough_anonimity)
{
auto mintId = wallet->CreateSigmaMint(3, 0);
sigmaDb->RecordMint(3, 0, mintId.pubKey, 100);
BOOST_CHECK_EXCEPTION(wallet->CreateSigmaSpendV1(3, 0, false), WalletError, [] (const WalletError& e) {
return e.what() == std::string("Amount of coins in anonimity set is not enough to spend");
});
}
BOOST_AUTO_TEST_CASE(sigma_mint_listing_all)
{
// Create mints.
std::unordered_set<SigmaMintId> ids;
ids.insert(wallet->CreateSigmaMint(1, 0));
ids.insert(wallet->CreateSigmaMint(2, 0));
ids.insert(wallet->CreateSigmaMint(1, 1));
ids.insert(wallet->CreateSigmaMint(2, 0));
BOOST_CHECK_EQUAL(ids.size(), 4);
// List mints.
std::unordered_map<SigmaMintId, SigmaMint> mints;
wallet->ListSigmaMintsV1(std::inserter(mints, mints.begin()));
BOOST_CHECK_EQUAL(mints.size(), ids.size());
for (auto& mint : mints) {
auto it = ids.find(mint.first);
BOOST_CHECK(it != ids.end());
BOOST_CHECK_EQUAL(mint.second, wallet->GetSigmaMint(*it));
ids.erase(it);
}
BOOST_CHECK_EQUAL(ids.size(), 0);
}
BOOST_AUTO_TEST_CASE(sigma_mint_check_existence)
{
auto owned = wallet->CreateSigmaMint(1, 1);
SigmaPrivateKey priv;
SigmaPublicKey pub;
priv.Generate();
pub.Generate(priv, DefaultSigmaParams);
SigmaMintId other(1, 1, pub);
BOOST_CHECK_EQUAL(wallet->HasSigmaMint(owned), true);
BOOST_CHECK_EQUAL(wallet->HasSigmaMint(other), false);
}
BOOST_AUTO_TEST_CASE(sigma_mint_get)
{
// Get existence.
auto owned = wallet->CreateSigmaMint(1, 1);
auto mint = wallet->GetSigmaMint(owned);
SigmaPublicKey pub(wallet->GetKey(mint), DefaultSigmaParams);
BOOST_CHECK_EQUAL(owned, SigmaMintId(mint.property, mint.denomination, pub));
// Get non-existence.
SigmaPrivateKey otherPriv;
SigmaPublicKey otherPub;
otherPriv.Generate();
otherPub.Generate(otherPriv, DefaultSigmaParams);
SigmaMintId other(1, 1, otherPub);
BOOST_CHECK_THROW(wallet->GetSigmaMint(other), std::invalid_argument);
}
BOOST_AUTO_TEST_CASE(sigma_mint_set_used)
{
auto tx = uint256S("64c4c22a45ad449be61c52a431d11e81f7fd0ee2f2235bf02944fb0b3dd07adb");
auto id = wallet->CreateSigmaMint(1, 1);
SigmaMint mint;
wallet->SetSigmaMintUsedTransaction(id, tx);
mint = wallet->GetSigmaMint(id);
BOOST_CHECK_EQUAL(mint.spendTx, tx);
wallet->SetSigmaMintUsedTransaction(id, uint256());
mint = wallet->GetSigmaMint(id);
BOOST_CHECK(!mint.IsSpent());
}
BOOST_AUTO_TEST_CASE(sigma_mint_chainstate_owned)
{
auto id = wallet->CreateSigmaMint(1, 0);
SigmaMintGroup group;
SigmaMintIndex index;
SigmaMint mint;
// Add.
std::tie(group, index) = sigmaDb->RecordMint(1, 0, id.pubKey, 100);
mint = wallet->GetSigmaMint(id);
BOOST_CHECK_EQUAL(mint.chainState.block, 100);
BOOST_CHECK_EQUAL(mint.chainState.group, group);
BOOST_CHECK_EQUAL(mint.chainState.index, index);
// Remove.
sigmaDb->DeleteAll(100);
mint = wallet->GetSigmaMint(id);
BOOST_CHECK_EQUAL(mint.chainState, SigmaMintChainState());
}
BOOST_AUTO_TEST_CASE(sigma_mint_chainstate_not_owned)
{
// Add our mint first so we can test if the other mint does not alter our mint state.
auto id = wallet->CreateSigmaMint(1, 0);
SigmaMintGroup group;
SigmaMintIndex index;
std::tie(group, index) = sigmaDb->RecordMint(1, 0, id.pubKey, 100);
// Add other mint.
SigmaPrivateKey otherPriv;
SigmaPublicKey otherPub;
otherPriv.Generate();
otherPub.Generate(otherPriv, DefaultSigmaParams);
sigmaDb->RecordMint(1, 0, otherPub, 101);
// Our chain state should not updated.
SigmaMint mint;
mint = wallet->GetSigmaMint(id);
BOOST_CHECK_EQUAL(mint.chainState.block, 100);
BOOST_CHECK_EQUAL(mint.chainState.group, group);
BOOST_CHECK_EQUAL(mint.chainState.index, index);
// Other mint should not added to our wallet.
BOOST_CHECK_THROW(
wallet->GetSigmaMint(SigmaMintId(1, 0, otherPub)),
std::invalid_argument
);
// Remove other mint and our chain state should not updated.
sigmaDb->DeleteAll(101);
mint = wallet->GetSigmaMint(id);
BOOST_CHECK_EQUAL(mint.chainState.block, 100);
BOOST_CHECK_EQUAL(mint.chainState.group, group);
BOOST_CHECK_EQUAL(mint.chainState.index, index);
}
BOOST_AUTO_TEST_SUITE_END()
}
<|endoftext|> |
<commit_before>/*
MIT License
Copyright (c) 2018 namreeb http://github.com/namreeb [email protected]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#pragma comment(lib, "asmjit.lib")
#pragma comment(lib, "udis86.lib")
#include "InitializeHooks.hpp"
#include <hadesmem/patcher.hpp>
#include <cstdint>
namespace
{
enum class Version
{
Classic = 0,
TBC,
WotLK,
Cata32,
Cata64,
Total
};
enum class Offset
{
CVar__Set = 0,
RealmListCVar,
Initialize,
Login,
FoV,
Total
};
PVOID GetAddress(Version version, Offset offset)
{
static constexpr std::uint32_t offsets[static_cast<int>(Version::Total)][static_cast<int>(Offset::Total)] =
{
// Classic
{
0x23DF50,
0x82812C,
0x2AD0,
0x6AFB0,
0x4089B4
},
// TBC
{
0x23F6C0,
0x943330,
0x77AC0,
0x6E560,
0x4B5A04
},
// WotLK
{
0x3668C0,
0x879D00,
0xE5940,
0xD8A30,
0x5E8D88
},
// Cata32
{
0x2553B0,
0x9BE800,
0x40F8F0,
0x400240,
0x00, // not supported. let me know if anyone actually wants this
},
// Cata64
{
0x2F61D0,
0xCA4328,
0x51C0F0,
0x514100,
0x00, // not supported. let me know if anyone actually wants this
}
};
auto const baseAddress = reinterpret_cast<std::uint8_t *>(::GetModuleHandle(nullptr));
return baseAddress + offsets[static_cast<int>(version)][static_cast<int>(offset)];
}
}
namespace Classic
{
class CVar {};
using SetT = bool(__thiscall CVar::*)(const char *, char, char, char, char);
using InitializeT = void (__cdecl *)();
using LoginT = void(__fastcall *)(char *, char *);
void InitializeHook(hadesmem::PatchDetourBase *detour, GameSettings *settings)
{
auto const initialize = detour->GetTrampolineT<InitializeT>();
initialize();
auto const cvar = *reinterpret_cast<CVar **>(GetAddress(Version::Classic, Offset::RealmListCVar));
auto const set = hadesmem::detail::AliasCast<SetT>(GetAddress(Version::Classic, Offset::CVar__Set));
(cvar->*set)(settings->AuthServer, 1, 0, 1, 0);
detour->Remove();
if (settings->CredentialsSet)
{
auto const login = hadesmem::detail::AliasCast<LoginT>(GetAddress(Version::Classic, Offset::Login));
login(settings->Username, settings->Password);
}
settings->LoadComplete = true;
}
void ApplyClientInitHook(GameSettings *settings)
{
auto const proc = hadesmem::Process(::GetCurrentProcessId());
auto const initializeOrig = hadesmem::detail::AliasCast<InitializeT>(GetAddress(Version::Classic, Offset::Initialize));
auto initializeDetour = new hadesmem::PatchDetour<InitializeT>(proc, initializeOrig,
[settings] (hadesmem::PatchDetourBase *detour)
{
InitializeHook(detour, settings);
});
initializeDetour->Apply();
if (settings->FoVSet)
{
auto const pFov = GetAddress(Version::Classic, Offset::FoV);
std::vector<std::uint8_t> patchData(sizeof(settings->FoV));
memcpy(&patchData[0], &settings->FoV, sizeof(settings->FoV));
auto patch = new hadesmem::PatchRaw(proc, pFov, patchData);
patch->Apply();
}
}
}
namespace TBC
{
class CVar {};
using SetT = bool(__thiscall CVar::*)(const char *, char, char, char, char);
using InitializeT = void(__cdecl*)();
using LoginT = void(__cdecl *)(char *, char *);
void InitializeHook(hadesmem::PatchDetourBase *detour, GameSettings *settings)
{
auto const initialize = detour->GetTrampolineT<InitializeT>();
initialize();
auto const cvar = *reinterpret_cast<CVar **>(GetAddress(Version::TBC, Offset::RealmListCVar));
auto const set = hadesmem::detail::AliasCast<SetT>(GetAddress(Version::TBC, Offset::CVar__Set));
(cvar->*set)(settings->AuthServer, 1, 0, 1, 0);
detour->Remove();
if (settings->CredentialsSet)
{
auto const login = hadesmem::detail::AliasCast<LoginT>(GetAddress(Version::TBC, Offset::Login));
login(settings->Username, settings->Password);
}
settings->LoadComplete = true;
}
void ApplyClientInitHook(GameSettings *settings)
{
auto const proc = hadesmem::Process(::GetCurrentProcessId());
auto const initializeOrig = hadesmem::detail::AliasCast<InitializeT>(GetAddress(Version::TBC, Offset::Initialize));
auto initializeDetour = new hadesmem::PatchDetour<InitializeT>(proc, initializeOrig,
[settings] (hadesmem::PatchDetourBase *detour)
{
InitializeHook(detour, settings);
});
initializeDetour->Apply();
if (settings->FoVSet)
{
auto const pFov = GetAddress(Version::TBC, Offset::FoV);
std::vector<std::uint8_t> patchData(sizeof(settings->FoV));
memcpy(&patchData[0], &settings->FoV, sizeof(settings->FoV));
auto patch = new hadesmem::PatchRaw(proc, pFov, patchData);
patch->Apply();
}
}
}
namespace WOTLK
{
class CVar {};
using SetT = bool(__thiscall CVar::*)(const char *, char, char, char, char);
using InitializeT = void (*)();
using LoginT = void(__cdecl *)(char *, char *);
void InitializeHook(hadesmem::PatchDetourBase *detour, GameSettings *settings)
{
auto const initialize = detour->GetTrampolineT<InitializeT>();
initialize();
auto const cvar = *reinterpret_cast<CVar **>(GetAddress(Version::WotLK, Offset::RealmListCVar));
auto const set = hadesmem::detail::AliasCast<SetT>(GetAddress(Version::WotLK, Offset::CVar__Set));
(cvar->*set)(settings->AuthServer, 1, 0, 1, 0);
detour->Remove();
if (settings->CredentialsSet)
{
auto const login = hadesmem::detail::AliasCast<LoginT>(GetAddress(Version::WotLK, Offset::Login));
login(settings->Username, settings->Password);
}
settings->LoadComplete = true;
}
void ApplyClientInitHook(GameSettings *settings)
{
auto const proc = hadesmem::Process(::GetCurrentProcessId());
auto const initializeOrig = hadesmem::detail::AliasCast<InitializeT>(GetAddress(Version::WotLK, Offset::Initialize));
auto initializeDetour = new hadesmem::PatchDetour<InitializeT>(proc, initializeOrig,
[settings] (hadesmem::PatchDetourBase *detour)
{
InitializeHook(detour, settings);
});
initializeDetour->Apply();
if (settings->FoVSet)
{
auto const pFov = GetAddress(Version::WotLK, Offset::FoV);
std::vector<std::uint8_t> patchData(sizeof(settings->FoV));
memcpy(&patchData[0], &settings->FoV, sizeof(settings->FoV));
auto patch = new hadesmem::PatchRaw(proc, pFov, patchData);
patch->Apply();
}
}
}
namespace Cata32
{
class CVar {};
using SetT = bool(__thiscall CVar::*)(const char *, char, char, char, char);
using InitializeT = void(__cdecl *)();
using LoginT = void(__cdecl *)(char *, char *);
void InitializeHook(hadesmem::PatchDetourBase *detour, GameSettings *settings)
{
auto const initialize = detour->GetTrampolineT<InitializeT>();
initialize();
auto const cvar = *reinterpret_cast<CVar **>(GetAddress(Version::Cata32, Offset::RealmListCVar));
auto const set = hadesmem::detail::AliasCast<SetT>(GetAddress(Version::Cata32, Offset::CVar__Set));
(cvar->*set)(settings->AuthServer, 1, 0, 1, 0);
detour->Remove();
if (settings->CredentialsSet)
{
auto const login = hadesmem::detail::AliasCast<LoginT>(GetAddress(Version::Cata32, Offset::Login));
login(settings->Username, settings->Password);
}
settings->LoadComplete = true;
}
void ApplyClientInitHook(GameSettings *settings)
{
auto const proc = hadesmem::Process(::GetCurrentProcessId());
auto const initializeOrig = hadesmem::detail::AliasCast<InitializeT>(GetAddress(Version::Cata32, Offset::Initialize));
auto initializeDetour = new hadesmem::PatchDetour<InitializeT>(proc, initializeOrig,
[settings](hadesmem::PatchDetourBase *detour)
{
InitializeHook(detour, settings);
});
initializeDetour->Apply();
}
}
namespace Cata64
{
class CVar {};
using SetT = bool(__fastcall CVar::*)(const char *, char, char, char, char);
using InitializeT = int (__stdcall *)();
using LoginT = void(__fastcall *)(char *, char *);
int InitializeHook(hadesmem::PatchDetourBase *detour, GameSettings *settings)
{
auto const initialize = detour->GetTrampolineT<InitializeT>();
auto const ret = initialize();
auto const cvar = *reinterpret_cast<CVar **>(GetAddress(Version::Cata64, Offset::RealmListCVar));
auto const set = hadesmem::detail::AliasCast<SetT>(GetAddress(Version::Cata64, Offset::CVar__Set));
(cvar->*set)(settings->AuthServer, 1, 0, 1, 0);
detour->Remove();
if (settings->CredentialsSet)
{
auto const login = hadesmem::detail::AliasCast<LoginT>(GetAddress(Version::Cata64, Offset::Login));
login(settings->Username, settings->Password);
}
settings->LoadComplete = true;
return ret;
}
void ApplyClientInitHook(GameSettings *settings)
{
auto const proc = hadesmem::Process(::GetCurrentProcessId());
auto const initializeOrig = hadesmem::detail::AliasCast<InitializeT>(GetAddress(Version::Cata64, Offset::Initialize));
auto initializeDetour = new hadesmem::PatchDetour<InitializeT>(proc, initializeOrig,
[settings] (hadesmem::PatchDetourBase *detour)
{
return InitializeHook(detour, settings);
});
initializeDetour->Apply();
}
}<commit_msg>Update automatic login to only proceed once the alert url is rendered, when present. This should fix issue #10.<commit_after>/*
MIT License
Copyright (c) 2018 namreeb http://github.com/namreeb [email protected]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#pragma comment(lib, "asmjit.lib")
#pragma comment(lib, "udis86.lib")
#include "InitializeHooks.hpp"
#include <hadesmem/patcher.hpp>
#include <cstdint>
namespace
{
enum class Version
{
Classic = 0,
TBC,
WotLK,
Cata32,
Cata64,
Total
};
enum class Offset
{
CVar__Set = 0,
RealmListCVar,
Idle,
CGlueMgr__m_pendingServerAlert,
Login,
FoV,
Total
};
PVOID GetAddress(Version version, Offset offset)
{
static constexpr std::uint32_t offsets[static_cast<int>(Version::Total)][static_cast<int>(Offset::Total)] =
{
// Classic
{
0x23DF50,
0x82812C,
0x6B930,
0x741E28,
0x6AFB0,
0x4089B4
},
// TBC
{
0x23F6C0,
0x943330,
0x70160,
0x807DB8,
0x6E560,
0x4B5A04
},
// WotLK
{
0x3668C0,
0x879D00,
0xDAB40,
0x76AF88,
0xD8A30,
0x5E8D88
},
// Cata32
{
0x2553B0,
0x9BE800,
0x405310,
0xABBF04,
0x400240,
0x00, // not supported. let me know if anyone actually wants this
},
// Cata64
{
0x2F61D0,
0xCA4328,
0x51A7C0,
0xDACCA8,
0x514100,
0x00, // not supported. let me know if anyone actually wants this
}
};
auto const baseAddress = reinterpret_cast<std::uint8_t *>(::GetModuleHandle(nullptr));
return baseAddress + offsets[static_cast<int>(version)][static_cast<int>(offset)];
}
}
namespace Classic
{
class CVar {};
using SetT = bool(__thiscall CVar::*)(const char *, char, char, char, char);
using IdleT = int(__cdecl *)();
using LoginT = void(__fastcall *)(char *, char *);
int IdleHook(hadesmem::PatchDetourBase *detour, GameSettings *settings)
{
auto const idle = detour->GetTrampolineT<IdleT>();
auto const ret = idle();
// if we are no longer waiting for the server alert, proceed with configuration
if (!*reinterpret_cast<std::uint32_t *>(GetAddress(Version::Classic, Offset::CGlueMgr__m_pendingServerAlert)))
{
auto const cvar = *reinterpret_cast<CVar **>(GetAddress(Version::Classic, Offset::RealmListCVar));
auto const set = hadesmem::detail::AliasCast<SetT>(GetAddress(Version::Classic, Offset::CVar__Set));
(cvar->*set)(settings->AuthServer, 1, 0, 1, 0);
detour->Remove();
if (settings->CredentialsSet)
{
auto const login = hadesmem::detail::AliasCast<LoginT>(GetAddress(Version::Classic, Offset::Login));
login(settings->Username, settings->Password);
}
settings->LoadComplete = true;
}
return ret;
}
void ApplyClientInitHook(GameSettings *settings)
{
// just to make sure the value is initialized
*reinterpret_cast<std::uint32_t *>(GetAddress(Version::Classic, Offset::CGlueMgr__m_pendingServerAlert)) = 1;
auto const proc = hadesmem::Process(::GetCurrentProcessId());
auto const idleOrig = hadesmem::detail::AliasCast<IdleT>(GetAddress(Version::Classic, Offset::Idle));
auto idleDetour = new hadesmem::PatchDetour<IdleT>(proc, idleOrig,
[settings] (hadesmem::PatchDetourBase *detour)
{
return IdleHook(detour, settings);
});
idleDetour->Apply();
if (settings->FoVSet)
{
auto const pFov = GetAddress(Version::Classic, Offset::FoV);
std::vector<std::uint8_t> patchData(sizeof(settings->FoV));
memcpy(&patchData[0], &settings->FoV, sizeof(settings->FoV));
auto patch = new hadesmem::PatchRaw(proc, pFov, patchData);
patch->Apply();
}
}
}
namespace TBC
{
class CVar {};
using SetT = bool(__thiscall CVar::*)(const char *, char, char, char, char);
using IdleT = int (__cdecl*)();
using LoginT = void(__cdecl *)(char *, char *);
int IdleHook(hadesmem::PatchDetourBase *detour, GameSettings *settings)
{
auto const idle = detour->GetTrampolineT<IdleT>();
auto const ret = idle();
// if we are no longer waiting for the server alert, proceed with configuration
if (!*reinterpret_cast<std::uint32_t *>(GetAddress(Version::TBC, Offset::CGlueMgr__m_pendingServerAlert)))
{
auto const cvar = *reinterpret_cast<CVar **>(GetAddress(Version::TBC, Offset::RealmListCVar));
auto const set = hadesmem::detail::AliasCast<SetT>(GetAddress(Version::TBC, Offset::CVar__Set));
(cvar->*set)(settings->AuthServer, 1, 0, 1, 0);
detour->Remove();
if (settings->CredentialsSet)
{
auto const login = hadesmem::detail::AliasCast<LoginT>(GetAddress(Version::TBC, Offset::Login));
login(settings->Username, settings->Password);
}
settings->LoadComplete = true;
}
return ret;
}
void ApplyClientInitHook(GameSettings *settings)
{
// just to make sure the value is initialized
*reinterpret_cast<std::uint32_t *>(GetAddress(Version::TBC, Offset::CGlueMgr__m_pendingServerAlert)) = 1;
auto const proc = hadesmem::Process(::GetCurrentProcessId());
auto const idleOrig = hadesmem::detail::AliasCast<IdleT>(GetAddress(Version::TBC, Offset::Idle));
auto idleDetour = new hadesmem::PatchDetour<IdleT>(proc, idleOrig,
[settings] (hadesmem::PatchDetourBase *detour)
{
return IdleHook(detour, settings);
});
idleDetour->Apply();
if (settings->FoVSet)
{
auto const pFov = GetAddress(Version::TBC, Offset::FoV);
std::vector<std::uint8_t> patchData(sizeof(settings->FoV));
memcpy(&patchData[0], &settings->FoV, sizeof(settings->FoV));
auto patch = new hadesmem::PatchRaw(proc, pFov, patchData);
patch->Apply();
}
}
}
namespace WOTLK
{
class CVar {};
using SetT = bool(__thiscall CVar::*)(const char *, char, char, char, char);
using IdleT = int (__cdecl *)();
using LoginT = void(__cdecl *)(char *, char *);
int IdleHook(hadesmem::PatchDetourBase *detour, GameSettings *settings)
{
auto const idle = detour->GetTrampolineT<IdleT>();
auto const ret = idle();
// if we are no longer waiting for the server alert, proceed with configuration
if (!*reinterpret_cast<std::uint32_t *>(GetAddress(Version::WotLK, Offset::CGlueMgr__m_pendingServerAlert)))
{
auto const cvar = *reinterpret_cast<CVar **>(GetAddress(Version::WotLK, Offset::RealmListCVar));
auto const set = hadesmem::detail::AliasCast<SetT>(GetAddress(Version::WotLK, Offset::CVar__Set));
(cvar->*set)(settings->AuthServer, 1, 0, 1, 0);
detour->Remove();
if (settings->CredentialsSet)
{
auto const login = hadesmem::detail::AliasCast<LoginT>(GetAddress(Version::WotLK, Offset::Login));
login(settings->Username, settings->Password);
}
settings->LoadComplete = true;
}
return ret;
}
void ApplyClientInitHook(GameSettings *settings)
{
// just to make sure the value is initialized
*reinterpret_cast<std::uint32_t *>(GetAddress(Version::WotLK, Offset::CGlueMgr__m_pendingServerAlert)) = 1;
auto const proc = hadesmem::Process(::GetCurrentProcessId());
auto const idleOrig = hadesmem::detail::AliasCast<IdleT>(GetAddress(Version::WotLK, Offset::Idle));
auto idleDetour = new hadesmem::PatchDetour<IdleT>(proc, idleOrig,
[settings] (hadesmem::PatchDetourBase *detour)
{
return IdleHook(detour, settings);
});
idleDetour->Apply();
if (settings->FoVSet)
{
auto const pFov = GetAddress(Version::WotLK, Offset::FoV);
std::vector<std::uint8_t> patchData(sizeof(settings->FoV));
memcpy(&patchData[0], &settings->FoV, sizeof(settings->FoV));
auto patch = new hadesmem::PatchRaw(proc, pFov, patchData);
patch->Apply();
}
}
}
namespace Cata32
{
class CVar {};
using SetT = bool(__thiscall CVar::*)(const char *, char, char, char, char);
using IdleT = int(__cdecl *)();
using LoginT = void(__cdecl *)(char *, char *);
int IdleHook(hadesmem::PatchDetourBase *detour, GameSettings *settings)
{
auto const idle = detour->GetTrampolineT<IdleT>();
auto const ret = idle();
// if we are no longer waiting for the server alert, proceed with configuration
if (!*reinterpret_cast<std::uint32_t *>(GetAddress(Version::Cata32, Offset::CGlueMgr__m_pendingServerAlert)))
{
auto const cvar = *reinterpret_cast<CVar **>(GetAddress(Version::Cata32, Offset::RealmListCVar));
auto const set = hadesmem::detail::AliasCast<SetT>(GetAddress(Version::Cata32, Offset::CVar__Set));
(cvar->*set)(settings->AuthServer, 1, 0, 1, 0);
detour->Remove();
if (settings->CredentialsSet)
{
auto const login = hadesmem::detail::AliasCast<LoginT>(GetAddress(Version::Cata32, Offset::Login));
login(settings->Username, settings->Password);
}
settings->LoadComplete = true;
}
return ret;
}
void ApplyClientInitHook(GameSettings *settings)
{
// just to make sure the value is initialized
*reinterpret_cast<std::uint32_t *>(GetAddress(Version::Cata32, Offset::CGlueMgr__m_pendingServerAlert)) = 1;
auto const proc = hadesmem::Process(::GetCurrentProcessId());
auto const idleOrig = hadesmem::detail::AliasCast<IdleT>(GetAddress(Version::Cata32, Offset::Idle));
auto idleDetour = new hadesmem::PatchDetour<IdleT>(proc, idleOrig,
[settings](hadesmem::PatchDetourBase *detour)
{
return IdleHook(detour, settings);
});
idleDetour->Apply();
}
}
namespace Cata64
{
class CVar {};
using SetT = bool(__fastcall CVar::*)(const char *, char, char, char, char);
using IdleT = int (__stdcall *)();
using LoginT = void(__fastcall *)(char *, char *);
int IdleHook(hadesmem::PatchDetourBase *detour, GameSettings *settings)
{
auto const idle = detour->GetTrampolineT<IdleT>();
auto const ret = idle();
// if we are no longer waiting for the server alert, proceed with configuration
if (!*reinterpret_cast<std::uint32_t *>(GetAddress(Version::Cata64, Offset::CGlueMgr__m_pendingServerAlert)))
{
auto const cvar = *reinterpret_cast<CVar **>(GetAddress(Version::Cata64, Offset::RealmListCVar));
auto const set = hadesmem::detail::AliasCast<SetT>(GetAddress(Version::Cata64, Offset::CVar__Set));
(cvar->*set)(settings->AuthServer, 1, 0, 1, 0);
detour->Remove();
if (settings->CredentialsSet)
{
auto const login = hadesmem::detail::AliasCast<LoginT>(GetAddress(Version::Cata64, Offset::Login));
login(settings->Username, settings->Password);
}
settings->LoadComplete = true;
}
return ret;
}
void ApplyClientInitHook(GameSettings *settings)
{
// just to make sure the value is initialized
*reinterpret_cast<std::uint32_t *>(GetAddress(Version::Cata64, Offset::CGlueMgr__m_pendingServerAlert)) = 1;
auto const proc = hadesmem::Process(::GetCurrentProcessId());
auto const idleOrig = hadesmem::detail::AliasCast<IdleT>(GetAddress(Version::Cata64, Offset::Idle));
auto idleDetour = new hadesmem::PatchDetour<IdleT>(proc, idleOrig,
[settings] (hadesmem::PatchDetourBase *detour)
{
return IdleHook(detour, settings);
});
idleDetour->Apply();
}
}<|endoftext|> |
<commit_before>#pragma once
#include <Gamma/Envelope.h>
#include <Gamma/Filter.h>
#include <Gamma/Oscillator.h>
#include <Gamma/Noise.h>
#include "util/dsp/overdrive.hpp"
#include "core/voices/voice_manager.hpp"
#include "goss.hpp"
//TODO: draw model
namespace otto::engines::goss {
struct Voice : voices::VoiceBase<Voice> {
Voice(Audio& a) noexcept;
float operator()() noexcept;
void on_note_on(float) noexcept;
void on_note_off() noexcept;
/// Use actions from base class
using VoiceBase::action;
void action(itc::prop_change<&Props::click>, float c) noexcept;
void action(itc::prop_change<&Props::model>, int m) noexcept;
void action(voices::attack_tag::action, float a) noexcept
{
env_.attack(a * a * 8.f + 0.01f);
}
void action(voices::decay_tag::action, float d) noexcept
{
env_.decay(d * d * 4.f + 0.01f);
}
void action(voices::sustain_tag::action, float s) noexcept
{
env_.sustain(s);
}
void action(voices::release_tag::action, float r) noexcept
{
env_.release(r * r * 8.f + 0.01f);
}
private:
Audio& audio;
/// Does not allocate tables. Reads from models in Audio.
gam::Osc<> voice_player;
gam::Osc<> percussion_player;
gam::NoiseBrown<> noise;
gam::AD<> perc_env{0.01, 0.08};
gam::ADSR<> env_ = {0.1f, 0.1f, 0.7f, 2.0f, 1.f, -4.f};
};
struct Audio {
Audio() noexcept;
void action(Actions::rotation_variable, std::atomic<float>&) noexcept;
void action(itc::prop_change<&Props::drive>, float d) noexcept;
void action(itc::prop_change<&Props::leslie>, float l) noexcept;
template<typename Tag, typename... Args>
auto action(itc::Action<Tag, Args...> a, Args... args) noexcept
-> std::enable_if_t<itc::ActionReciever::is<voices::VoiceManager<Voice, 6>, itc::Action<Tag, Args...>>>
{
voice_mgr_.action(a, args...);
}
float operator()() noexcept;
audio::ProcessData<1> process(audio::ProcessData<1>) noexcept;
private:
friend Voice;
std::atomic<float>* shared_rotation = nullptr;
void generate_model(gam::Osc<>&, model_type);
std::array<gam::Osc<>, number_of_models> models;
gam::Osc<> percussion = {1, 0, 2048};
float gain = 0.f;
float output_scaling = 0.f;
float leslie = 0.f;
float leslie_speed_hi = 0.f;
float leslie_speed_lo = 0.f;
float leslie_amount_hi = 0.f;
float leslie_amount_lo = 0.f;
gam::LFO<> leslie_filter_hi;
gam::LFO<> leslie_filter_lo;
gam::LFO<> pitch_modulation_hi;
gam::AccumPhase<> rotation;
gam::Biquad<> lpf;
gam::Biquad<> hpf;
util::dsp::HammondPreamp overdrive;
voices::VoiceManager<Voice, 6> voice_mgr_ = {*this};
};
} // namespace otto::engines::goss
<commit_msg>Goss: removing deprecated overdrive<commit_after>#pragma once
#include <Gamma/Envelope.h>
#include <Gamma/Filter.h>
#include <Gamma/Oscillator.h>
#include <Gamma/Noise.h>
#include "util/dsp/overdrive.hpp"
#include "core/voices/voice_manager.hpp"
#include "goss.hpp"
//TODO: draw model
namespace otto::engines::goss {
struct Voice : voices::VoiceBase<Voice> {
Voice(Audio& a) noexcept;
float operator()() noexcept;
void on_note_on(float) noexcept;
void on_note_off() noexcept;
/// Use actions from base class
using VoiceBase::action;
void action(itc::prop_change<&Props::click>, float c) noexcept;
void action(itc::prop_change<&Props::model>, int m) noexcept;
void action(voices::attack_tag::action, float a) noexcept
{
env_.attack(a * a * 8.f + 0.01f);
}
void action(voices::decay_tag::action, float d) noexcept
{
env_.decay(d * d * 4.f + 0.01f);
}
void action(voices::sustain_tag::action, float s) noexcept
{
env_.sustain(s);
}
void action(voices::release_tag::action, float r) noexcept
{
env_.release(r * r * 8.f + 0.01f);
}
private:
Audio& audio;
/// Does not allocate tables. Reads from models in Audio.
gam::Osc<> voice_player;
gam::Osc<> percussion_player;
gam::NoiseBrown<> noise;
gam::AD<> perc_env{0.01, 0.08};
gam::ADSR<> env_ = {0.1f, 0.1f, 0.7f, 2.0f, 1.f, -4.f};
};
struct Audio {
Audio() noexcept;
void action(Actions::rotation_variable, std::atomic<float>&) noexcept;
void action(itc::prop_change<&Props::drive>, float d) noexcept;
void action(itc::prop_change<&Props::leslie>, float l) noexcept;
template<typename Tag, typename... Args>
auto action(itc::Action<Tag, Args...> a, Args... args) noexcept
-> std::enable_if_t<itc::ActionReciever::is<voices::VoiceManager<Voice, 6>, itc::Action<Tag, Args...>>>
{
voice_mgr_.action(a, args...);
}
float operator()() noexcept;
audio::ProcessData<1> process(audio::ProcessData<1>) noexcept;
private:
friend Voice;
std::atomic<float>* shared_rotation = nullptr;
void generate_model(gam::Osc<>&, model_type);
std::array<gam::Osc<>, number_of_models> models;
gam::Osc<> percussion = {1, 0, 2048};
float gain = 0.f;
float output_scaling = 0.f;
float leslie = 0.f;
float leslie_speed_hi = 0.f;
float leslie_speed_lo = 0.f;
float leslie_amount_hi = 0.f;
float leslie_amount_lo = 0.f;
gam::LFO<> leslie_filter_hi;
gam::LFO<> leslie_filter_lo;
gam::LFO<> pitch_modulation_hi;
gam::AccumPhase<> rotation;
gam::Biquad<> lpf;
gam::Biquad<> hpf;
voices::VoiceManager<Voice, 6> voice_mgr_ = {*this};
};
} // namespace otto::engines::goss
<|endoftext|> |
<commit_before>#include "estimator/world_estimator.hpp"
#include <cstdio>
#include "hal.h"
#include "unit_config.hpp"
WorldEstimator::WorldEstimator(
LocationEstimator& locEstimator,
AttitudeEstimator& attEstimator,
Communicator& communicator)
: locEstimator(locEstimator),
attEstimator(attEstimator),
worldMessageStream(communicator, 10) {
}
WorldEstimate WorldEstimator::update(const SensorMeasurements& meas) {
// TODO: get GPS data
WorldEstimate estimate {
.loc = locEstimator.update(meas),
.att = attEstimator.update(meas)
};
if(worldMessageStream.ready()) {
// protocol::message::log_message_t m;
// sprintf(m.data, "world estimate test");
//
// worldMessageStream.publish(m);
}
return estimate;
}
<commit_msg>Reduce debug rate.<commit_after>#include "estimator/world_estimator.hpp"
#include <cstdio>
#include "hal.h"
#include "unit_config.hpp"
WorldEstimator::WorldEstimator(
LocationEstimator& locEstimator,
AttitudeEstimator& attEstimator,
Communicator& communicator)
: locEstimator(locEstimator),
attEstimator(attEstimator),
worldMessageStream(communicator, 1) {
}
WorldEstimate WorldEstimator::update(const SensorMeasurements& meas) {
// TODO: get GPS data
WorldEstimate estimate {
.loc = locEstimator.update(meas),
.att = attEstimator.update(meas)
};
if(worldMessageStream.ready() && meas.gps) {
// protocol::message::log_message_t m;
// sprintf(m.data, "gps: %d %d", (int) (*meas.gps).lat * 1000, (int) (*meas.gps).lon * 1000);
//
// worldMessageStream.publish(m);
}
return estimate;
}
<|endoftext|> |
<commit_before>//
// Created by Kevin on 15/10/2016.
//
#include <stdexcept>
#include "GPU/GPU.h"
using namespace std;
using namespace Gameboy::GPU;
using namespace Gameboy::General;
GPU::GPU(Gameboy::CPU::IInterruptible &p_interruptible, IReadable& p_readableMemoryMappedIO, IVideoOutputDevice& p_outputDevice)
: interruptible (p_interruptible),
readableMemoryMappedIO (p_readableMemoryMappedIO),
outputDevice (p_outputDevice),
frameBuffer (WIDTH * HEIGHT),
clock (),
gpuReg (),
colors {COLOUR0, COLOUR1, COLOUR2, COLOUR3},
windowYPosition (),
lastWindowYPosition ()
{
gpuReg[OffSTAT] = OAMUsed;
videoRam.initialise(Memory::MemoryType(8192));
spriteRam.initialise(Memory::MemoryType(160));
}
void GPU::next(uint32_t ticks) {
if (!isLcdOn()) {
return;
}
clock += ticks;
Mode mode = getMode();
switch (mode) {
case HBlank:
if (clock >= 204) {
// next mode is either mode 1 - VBlank or mode 2 - OAMUsed
clock -= 204;
incrementLY();
if (gpuReg[OffLY] == HEIGHT) {
outputDevice.render(frameBuffer.data());
setMode(VBlank);
// Frame is ready, commit it
} else {
setMode(OAMUsed);
}
}
break;
case VBlank:
if (clock >= 456) {
clock -= 456;
incrementLY();
if (gpuReg[OffLY] == 0) {
windowYPosition = gpuReg[OffWY];
lastWindowYPosition = 0;
setMode(OAMUsed);
}
}
break;
case OAMUsed:
if (clock >= 80) {
// next mode is mode 3 - no interrupts to raise
clock -= 80;
setMode(OAMVRamUsed);
}
break;
case OAMVRamUsed:
if (clock >= 172) {
// render scanLine
renderScanLine();
// next mode is mode 0 - HBlank
clock -= 172;
setMode(HBlank);
}
break;
}
}
// LCDC
bool GPU::isLcdOn() const {
return (gpuReg[OffLCDC] & (1 << 7)) != 0;
}
uint16_t GPU::getWindowTileMapOffset() const {
return static_cast<uint16_t>((gpuReg[OffLCDC] & (1 << 6)) ? 0x9C00 : 0x9800) - VideoRam;
}
bool GPU::isWindowDisplayOn() const {
return (gpuReg[OffLCDC] & (1 << 5)) != 0;
}
uint16_t GPU::getBgWindowTileDataOffset() const {
// When 9000, signed addressing is used
return static_cast<uint16_t>((gpuReg[OffLCDC] & (1 << 4)) ? 0x8000 : 0x9000) - VideoRam;
}
uint16_t GPU::getBgTileMapOffset() const {
return static_cast<uint16_t>((gpuReg[OffLCDC] & (1 << 3)) ? 0x9C00 : 0x9800) - VideoRam;
}
uint8_t GPU::getSpriteHeight() const {
return static_cast<uint8_t>((gpuReg[OffLCDC] & (1 << 2)) ? 16 : 8);
}
bool GPU::isSpriteDisplayOn() const {
return (gpuReg[OffLCDC] & (1 << 1)) != 0;
}
bool GPU::isBgDisplayOn() const {
return (gpuReg[OffLCDC] & (1 << 0)) != 0;
}
// STAT
void GPU::setMode(Mode mode) {
gpuReg[OffSTAT] &= 0xFC;
gpuReg[OffSTAT] |= mode;
if ((mode != OAMVRamUsed) && (gpuReg[OffSTAT] & (1 << (3 + mode)))) {
interruptible.requestInterrupt(StatIrq);
}
if (mode == VBlank) {
interruptible.requestInterrupt(VBlankIrq);
}
}
void GPU::incrementLY() {
if (++gpuReg[OffLY] == 154) {
gpuReg[OffLY] = 0;
}
// check coincidence flag
if (gpuReg[OffLY] == gpuReg[OffLYC]) {
gpuReg[OffSTAT] |= (1 << 2);
// Check and raise coincidence interrupt
if (gpuReg[OffSTAT] & (1 << 6)) {
interruptible.requestInterrupt(StatIrq);
}
} else {
gpuReg[OffSTAT] &= ~(1 << 2);
}
}
Mode GPU::getMode() const {
return static_cast<Mode>(gpuReg[OffSTAT] & 0x03);
}
uint8_t GPU::read(uint16_t address) const {
if (address >= VideoRam && address < RamBankN) {
// VRam
if (isLcdOn() && (getMode() == Mode::OAMVRamUsed)) {
throw runtime_error ("Cannot read from VRAM, it is in use by the GPU");
}
return videoRam.readExt(address - VideoRam);
} else if (address >= SpriteRam && address < UnusableIO1) {
// Sprite Ram
if (isLcdOn() && (getMode() & 0x02)) {
throw runtime_error ("Cannot read from Sprite Ram, it is in use by the GPU");
}
return spriteRam.readExt(address - SpriteRam);
} else if (address >= LCDC && address <= WX) {
// Registers
return gpuReg[address - LCDC];
}
throw runtime_error ("GPU read out of range: " + to_string(address));
}
void GPU::write(uint16_t address, uint8_t datum) {
if (address >= VideoRam && address < RamBankN) {
// VRam
if (isLcdOn() && (getMode() == Mode::OAMVRamUsed)) {
throw runtime_error ("Cannot write to VRAM, it is in use by the GPU");
}
return videoRam.writeExt(address - VideoRam, datum);
} else if (address >= SpriteRam && address < UnusableIO1) {
// Sprite Ram
if (isLcdOn() && (getMode() & 0x02)) {
throw runtime_error ("Cannot write to Sprite Ram, it is in use by the GPU");
}
return spriteRam.writeExt(address - SpriteRam, datum);
} else if (address >= LCDC && address <= WX) {
// Registers
const RegisterOffset offset = static_cast<RegisterOffset>(address - LCDC);
switch (offset) {
case OffLCDC: // 0xFF40
gpuReg[offset] = datum;
break;
case OffSTAT: // 0xFF41
gpuReg[offset] &= 0x03;
gpuReg[offset] |= datum & 0xFC;
break;
case OffSCY: // 0xFF42
case OffSCX: // 0xFF43
gpuReg[offset] = datum;
break;
case OffLY: // 0xFF44
throw runtime_error("Attempted write to LY Register, datum:" + to_string(static_cast<uint32_t>(datum)));
case OffLYC: // 0xFF45
gpuReg[offset] = datum;
break;
case OffDMA: // 0xFF46
// Perform DMA transfer
{
const uint16_t baseAddress = static_cast<uint16_t>(datum) << 8;
for (uint8_t i = 0; i < (UnusableIO1 - SpriteRam); ++i) {
//write(SpriteRam + i, readableMemoryMappedIO.read(baseAddress + i));
// Rough implementation, need to emulate more
// TODO: This takes 671 ticks, data wriging should be probably emulated
// during this course of time. Or at the very least, lock the whole memory map
// except High Ram.
spriteRam.writeExt(i, readableMemoryMappedIO.read(baseAddress + i));
}
}
break;
case OffBGP: // 0xFF47
case OffOBP0: // 0xFF48
case OffOBP1: // 0xFF49
case OffWY: // 0xFF4A
case OffWX: // 0xFF4B
gpuReg[offset] = datum;
break;
}
return;
}
throw runtime_error ("GPU write out of range: " + to_string(address) + ", datum: " + to_string(static_cast<uint32_t>(datum)));
}
void GPU::renderScanLine() {
const bool bgEnabled = isBgDisplayOn();
const bool windowEnabled = isWindowDisplayOn()
&& (/*gpuReg[OffWY]*/ windowYPosition <= gpuReg[OffLY])
&& (gpuReg[OffWX] <= 166);
// TODO: Check if keeping value as unsigned becomes a problem with comparisons
const int16_t alteredWX = static_cast<int16_t>(gpuReg[OffWX] - 7);
// Data offset for both background and window
const uint16_t dataOffset = getBgWindowTileDataOffset();
const bool negativeAddressing = dataOffset != 0;
// Get the background and Window Map
const uint16_t backgroundMapOffset = getBgTileMapOffset();
const uint16_t windowMapOffset = getWindowTileMapOffset();
// Render Background and Window
for (uint8_t x = 0; x < WIDTH; ++x) {
// Determine whether to draw using window or background
uint16_t mapOffset;
// Pixel offsets
uint8_t xOffset;
uint8_t yOffset;
// In below comparison, x and alteredWX are both promoted to 'int'
if (windowEnabled && (x >= alteredWX) && (x <= alteredWX)) {
// Use window
mapOffset = windowMapOffset;
// Both values are promoted to 'int' before subtraction takes place
xOffset = static_cast<uint8_t>(x - alteredWX);
// Handle case where window is interrupted and resumed at a later line
// This value is updated to WY upon exiting VBLANK
yOffset = lastWindowYPosition++;
} else if (bgEnabled) {
// Use background
mapOffset = backgroundMapOffset;
xOffset = gpuReg[OffSCX] + x;
yOffset = gpuReg[OffSCY] + gpuReg[OffLY];
} else {
// Commit to frame buffer the colour 0 - White
frameBuffer[gpuReg[OffLY] * WIDTH + x] = colors[0];
continue;
}
// Tile offsets - Divide by 8 since tiles are 8x8 and division will transform
// view from pixel coordinates to tile coordinates
const uint8_t yTileOffset = yOffset >> 3; // Divide by 8
// Select one of the 8 rows found in the tile
const uint8_t tileLineIndex = yOffset & static_cast<uint8_t>(0x07);
// Divide by 8 to transform from pixel coordinates to tile coordinates
const uint8_t xTileOffset = xOffset >> 3;
// Get tile number from tile map - multiply yTileOffset by 32 as there are 32 tiles within one row
const uint8_t tileNumber = videoRam.readExt(mapOffset +
// & ~0x400 is the same as % 1024
static_cast<size_t>(((yTileOffset << 5) + xTileOffset) & ~0x400));
// Get tile address from the tile index, this address is used to compose the final address
// to read data from the tile data region
const uint16_t tileAddress =
dataOffset + (negativeAddressing ? (static_cast<int8_t>(tileNumber) << 4) : tileNumber << 4);
// Tile x-Pixel Index
const uint8_t tileXPixelIndex = xOffset & static_cast<uint8_t>(0x07);
// Get 2-bit value - multiply tileLineIndex by two as each line is composed of 2-bytes
const uint16_t finalAddress = tileAddress + (tileLineIndex << 1);
uint8_t pixelValue = static_cast<uint8_t>((videoRam.readExt(finalAddress + 1) &
(1 << (7 - tileXPixelIndex))) ? 2 : 0);
pixelValue |= (videoRam.readExt(finalAddress) >> (7 - tileXPixelIndex)) & 1;
// Get palette colour value
const uint8_t colorIndexValue = static_cast<uint8_t>((gpuReg[OffBGP] >> (pixelValue << 1)) & 0x03);
// Commit to frame buffer
frameBuffer[gpuReg[OffLY] * WIDTH + x] = colors[colorIndexValue];
}
if (isSpriteDisplayOn()) {
/*uint8_t spritesAdded = 0;
struct {
uint8_t index;
int16_t x;
} spritesToRender[10];*/
const uint8_t spriteHeight = getSpriteHeight();
// Render Sprites (max 10 per line)
for (uint8_t sprite = 0; sprite < 40; ++sprite) {
// Determine the ten highest priority sprites to survive
// Check whether it is part of this scan-line
const int16_t spriteY1 = static_cast<int16_t>(spriteRam.readExt((sprite << 2)) - 16);
const int16_t spriteY2 = spriteY1 + spriteHeight;
if (gpuReg[OffLY] >= spriteY1 && gpuReg[OffLY] <= spriteY2) {
// Get the x-coordinates
const uint8_t spriteX2 = spriteRam.readExt((sprite << 2) + 1);
const int16_t spriteX1 = static_cast<int16_t>(spriteX2 - 8);
// Check if in screen coordinates
if (spriteX1 >= WIDTH || static_cast<int16_t>(spriteX2) < 0) {
continue;
}
/*
// Check whether this sprite has priority over the other sprites
bool collision = false;
for (size_t i = 0; (!collision) && (i < spritesAdded); ++i) {
// Check if we collide, then check if we have priority
if ((spriteX1 <= spritesToRender[i].x) && (spritesToRender[i].x - spriteX1) < 8) {
spritesToRender[i].x = spriteX1;
spritesToRender[i].index = sprite;
collision = true;
}
}
// We did not collide, add if possible
if (!collision && (spritesAdded < 10)) {
spritesToRender[spritesAdded].x = spriteX1;
spritesToRender[spritesAdded].index = sprite;
++spritesAdded;
}
*/
}
}
}
}
<commit_msg>Add first working version of sprites<commit_after>//
// Created by Kevin on 15/10/2016.
//
#include <stdexcept>
#include "GPU/GPU.h"
using namespace std;
using namespace Gameboy::GPU;
using namespace Gameboy::General;
GPU::GPU(Gameboy::CPU::IInterruptible &p_interruptible, IReadable& p_readableMemoryMappedIO, IVideoOutputDevice& p_outputDevice)
: interruptible (p_interruptible),
readableMemoryMappedIO (p_readableMemoryMappedIO),
outputDevice (p_outputDevice),
frameBuffer (WIDTH * HEIGHT),
clock (),
gpuReg (),
colors {COLOUR0, COLOUR1, COLOUR2, COLOUR3},
windowYPosition (),
lastWindowYPosition ()
{
gpuReg[OffSTAT] = OAMUsed;
videoRam.initialise(Memory::MemoryType(8192));
spriteRam.initialise(Memory::MemoryType(160));
}
void GPU::next(uint32_t ticks) {
if (!isLcdOn()) {
return;
}
clock += ticks;
Mode mode = getMode();
switch (mode) {
case HBlank:
if (clock >= 204) {
// next mode is either mode 1 - VBlank or mode 2 - OAMUsed
clock -= 204;
incrementLY();
if (gpuReg[OffLY] == HEIGHT) {
outputDevice.render(frameBuffer.data());
setMode(VBlank);
// Frame is ready, commit it
} else {
setMode(OAMUsed);
}
}
break;
case VBlank:
if (clock >= 456) {
clock -= 456;
incrementLY();
if (gpuReg[OffLY] == 0) {
windowYPosition = gpuReg[OffWY];
lastWindowYPosition = 0;
setMode(OAMUsed);
}
}
break;
case OAMUsed:
if (clock >= 80) {
// next mode is mode 3 - no interrupts to raise
clock -= 80;
setMode(OAMVRamUsed);
}
break;
case OAMVRamUsed:
if (clock >= 172) {
// render scanLine
renderScanLine();
// next mode is mode 0 - HBlank
clock -= 172;
setMode(HBlank);
}
break;
}
}
// LCDC
bool GPU::isLcdOn() const {
return (gpuReg[OffLCDC] & (1 << 7)) != 0;
}
uint16_t GPU::getWindowTileMapOffset() const {
return static_cast<uint16_t>((gpuReg[OffLCDC] & (1 << 6)) ? 0x9C00 : 0x9800) - VideoRam;
}
bool GPU::isWindowDisplayOn() const {
return (gpuReg[OffLCDC] & (1 << 5)) != 0;
}
uint16_t GPU::getBgWindowTileDataOffset() const {
// When 9000, signed addressing is used
return static_cast<uint16_t>((gpuReg[OffLCDC] & (1 << 4)) ? 0x8000 : 0x9000) - VideoRam;
}
uint16_t GPU::getBgTileMapOffset() const {
return static_cast<uint16_t>((gpuReg[OffLCDC] & (1 << 3)) ? 0x9C00 : 0x9800) - VideoRam;
}
uint8_t GPU::getSpriteHeight() const {
return static_cast<uint8_t>((gpuReg[OffLCDC] & (1 << 2)) ? 16 : 8);
}
bool GPU::isSpriteDisplayOn() const {
return (gpuReg[OffLCDC] & (1 << 1)) != 0;
}
bool GPU::isBgDisplayOn() const {
return (gpuReg[OffLCDC] & (1 << 0)) != 0;
}
// STAT
void GPU::setMode(Mode mode) {
gpuReg[OffSTAT] &= 0xFC;
gpuReg[OffSTAT] |= mode;
if ((mode != OAMVRamUsed) && (gpuReg[OffSTAT] & (1 << (3 + mode)))) {
interruptible.requestInterrupt(StatIrq);
}
if (mode == VBlank) {
interruptible.requestInterrupt(VBlankIrq);
}
}
void GPU::incrementLY() {
if (++gpuReg[OffLY] == 154) {
gpuReg[OffLY] = 0;
}
// check coincidence flag
if (gpuReg[OffLY] == gpuReg[OffLYC]) {
gpuReg[OffSTAT] |= (1 << 2);
// Check and raise coincidence interrupt
if (gpuReg[OffSTAT] & (1 << 6)) {
interruptible.requestInterrupt(StatIrq);
}
} else {
gpuReg[OffSTAT] &= ~(1 << 2);
}
}
Mode GPU::getMode() const {
return static_cast<Mode>(gpuReg[OffSTAT] & 0x03);
}
uint8_t GPU::read(uint16_t address) const {
if (address >= VideoRam && address < RamBankN) {
// VRam
if (isLcdOn() && (getMode() == Mode::OAMVRamUsed)) {
throw runtime_error ("Cannot read from VRAM, it is in use by the GPU");
}
return videoRam.readExt(address - VideoRam);
} else if (address >= SpriteRam && address < UnusableIO1) {
// Sprite Ram
if (isLcdOn() && (getMode() & 0x02)) {
throw runtime_error ("Cannot read from Sprite Ram, it is in use by the GPU");
}
return spriteRam.readExt(address - SpriteRam);
} else if (address >= LCDC && address <= WX) {
// Registers
return gpuReg[address - LCDC];
}
throw runtime_error ("GPU read out of range: " + to_string(address));
}
void GPU::write(uint16_t address, uint8_t datum) {
if (address >= VideoRam && address < RamBankN) {
// VRam
if (isLcdOn() && (getMode() == Mode::OAMVRamUsed)) {
throw runtime_error ("Cannot write to VRAM, it is in use by the GPU");
}
return videoRam.writeExt(address - VideoRam, datum);
} else if (address >= SpriteRam && address < UnusableIO1) {
// Sprite Ram
if (isLcdOn() && (getMode() & 0x02)) {
throw runtime_error ("Cannot write to Sprite Ram, it is in use by the GPU");
}
return spriteRam.writeExt(address - SpriteRam, datum);
} else if (address >= LCDC && address <= WX) {
// Registers
const RegisterOffset offset = static_cast<RegisterOffset>(address - LCDC);
switch (offset) {
case OffLCDC: // 0xFF40
gpuReg[offset] = datum;
break;
case OffSTAT: // 0xFF41
gpuReg[offset] &= 0x03;
gpuReg[offset] |= datum & 0xFC;
break;
case OffSCY: // 0xFF42
case OffSCX: // 0xFF43
gpuReg[offset] = datum;
break;
case OffLY: // 0xFF44
throw runtime_error("Attempted write to LY Register, datum:" + to_string(static_cast<uint32_t>(datum)));
case OffLYC: // 0xFF45
gpuReg[offset] = datum;
break;
case OffDMA: // 0xFF46
// Perform DMA transfer
{
const uint16_t baseAddress = static_cast<uint16_t>(datum) << 8;
for (uint8_t i = 0; i < (UnusableIO1 - SpriteRam); ++i) {
//write(SpriteRam + i, readableMemoryMappedIO.read(baseAddress + i));
// Rough implementation, need to emulate more
// TODO: This takes 671 ticks, data wriging should be probably emulated
// during this course of time. Or at the very least, lock the whole memory map
// except High Ram.
spriteRam.writeExt(i, readableMemoryMappedIO.read(baseAddress + i));
}
}
break;
case OffBGP: // 0xFF47
case OffOBP0: // 0xFF48
case OffOBP1: // 0xFF49
case OffWY: // 0xFF4A
case OffWX: // 0xFF4B
gpuReg[offset] = datum;
break;
}
return;
}
throw runtime_error ("GPU write out of range: " + to_string(address) + ", datum: " + to_string(static_cast<uint32_t>(datum)));
}
void GPU::renderScanLine() {
const bool bgEnabled = isBgDisplayOn();
const bool windowEnabled = isWindowDisplayOn()
&& (/*gpuReg[OffWY]*/ windowYPosition <= gpuReg[OffLY])
&& (gpuReg[OffWX] <= 166);
// TODO: Check if keeping value as unsigned becomes a problem with comparisons
const int16_t alteredWX = static_cast<int16_t>(gpuReg[OffWX] - 7);
// Data offset for both background and window
const uint16_t dataOffset = getBgWindowTileDataOffset();
const bool negativeAddressing = dataOffset != 0;
// Get the background and Window Map
const uint16_t backgroundMapOffset = getBgTileMapOffset();
const uint16_t windowMapOffset = getWindowTileMapOffset();
// Render Background and Window
for (uint8_t x = 0; x < WIDTH; ++x) {
// Determine whether to draw using window or background
uint16_t mapOffset;
// Pixel offsets
uint8_t xOffset;
uint8_t yOffset;
// In below comparison, x and alteredWX are both promoted to 'int'
if (windowEnabled && (x >= alteredWX) /*&& (x <= (alteredWX + WIDTH))*/) {
// Use window
mapOffset = windowMapOffset;
// Both values are promoted to 'int' before subtraction takes place
xOffset = static_cast<uint8_t>(x - alteredWX);
// Handle case where window is interrupted and resumed at a later line
// This value is updated to WY upon exiting VBLANK
yOffset = lastWindowYPosition;
} else if (bgEnabled) {
// Use background
mapOffset = backgroundMapOffset;
xOffset = gpuReg[OffSCX] + x;
yOffset = gpuReg[OffSCY] + gpuReg[OffLY];
} else {
// Commit to frame buffer the colour 0 - White
frameBuffer[gpuReg[OffLY] * WIDTH + x] = colors[0];
continue;
}
// Tile offsets - Divide by 8 since tiles are 8x8 and division will transform
// view from pixel coordinates to tile coordinates
const uint8_t yTileOffset = yOffset >> 3; // Divide by 8
// Select one of the 8 rows found in the tile
const uint8_t tileLineIndex = yOffset & static_cast<uint8_t>(0x07);
// Divide by 8 to transform from pixel coordinates to tile coordinates
const uint8_t xTileOffset = xOffset >> 3;
// Get tile number from tile map - multiply yTileOffset by 32 as there are 32 tiles within one row
const uint8_t tileNumber = videoRam.readExt(mapOffset +
// & ~0x400 is the same as % 1024
static_cast<size_t>(((yTileOffset << 5) + xTileOffset) & ~0x400));
// Get tile address from the tile index, this address is used to compose the final address
// to read data from the tile data region
const uint16_t tileAddress =
dataOffset + (negativeAddressing ? (static_cast<int8_t>(tileNumber) << 4) : tileNumber << 4);
// Tile x-Pixel Index
const uint8_t tileXPixelIndex = xOffset & static_cast<uint8_t>(0x07);
// Get 2-bit value - multiply tileLineIndex by two as each line is composed of 2-bytes
const uint16_t finalAddress = tileAddress + (tileLineIndex << 1);
uint8_t pixelValue = static_cast<uint8_t>((videoRam.readExt(finalAddress + 1) &
(1 << (7 - tileXPixelIndex))) ? 2 : 0);
pixelValue |= (videoRam.readExt(finalAddress) >> (7 - tileXPixelIndex)) & 1;
// Get palette colour value
const uint8_t colorIndexValue = static_cast<uint8_t>((gpuReg[OffBGP] >> (pixelValue << 1)) & 0x03);
// Commit to frame buffer
frameBuffer[gpuReg[OffLY] * WIDTH + x] = colors[colorIndexValue];
}
if (windowEnabled) {
++lastWindowYPosition;
}
if (isSpriteDisplayOn()) {
/*uint8_t spritesAdded = 0;
struct {
uint8_t index;
int16_t x;
} spritesToRender[10];*/
const uint8_t spriteHeight = getSpriteHeight();
// Render Sprites (max 10 per line)
for (uint8_t sprite = 0; sprite < 40; ++sprite) {
// Determine the ten highest priority sprites to survive
// Check whether it is part of this scan-line
const int16_t spriteY1 = static_cast<int16_t>(spriteRam.readExt((sprite << 2)) - 16);
const int16_t spriteY2 = spriteY1 + spriteHeight - 1;
if (gpuReg[OffLY] >= spriteY1 && gpuReg[OffLY] <= spriteY2) {
// Get the x-coordinates
const uint8_t spriteX2 = spriteRam.readExt((sprite << 2) + 1);
const int16_t spriteX1 = static_cast<int16_t>(spriteX2 - 8);
// Check if in screen coordinates
if (spriteX1 >= WIDTH || static_cast<int16_t>(spriteX2) < 0) {
continue;
}
/*
// Check whether this sprite has priority over the other sprites
bool collision = false;
for (size_t i = 0; (!collision) && (i < spritesAdded); ++i) {
// Check if we collide, then check if we have priority
if ((spriteX1 <= spritesToRender[i].x) && (spritesToRender[i].x - spriteX1) < 8) {
spritesToRender[i].x = spriteX1;
spritesToRender[i].index = sprite;
collision = true;
}
}
// We did not collide, add if possible
if (!collision && (spritesAdded < 10)) {
spritesToRender[spritesAdded].x = spriteX1;
spritesToRender[spritesAdded].index = sprite;
++spritesAdded;
}
*/
// For the time being, assume no hardware limit and no priority checks
// and just draw
// Get tile number from tile map - multiply yTileOffset by 32 as there are 32 tiles within one row
const uint8_t patternNumber = spriteRam.readExt((sprite << 2) + 2) & (spriteHeight == 16 ? 0xFE : 0xFF);
const uint8_t options = spriteRam.readExt((sprite << 2) + 3);
const bool hasPriority = (options & (1 << 7)) == 0;
const bool yFlip = (options & (1 << 6)) != 0;
const bool xFlip = (options & (1 << 5)) != 0;
const uint8_t palette = (options & (1 << 4)) != 0 ? gpuReg[OffOBP1] : gpuReg[OffOBP0];
// Select correct y-row depending on y-flip
const uint8_t lineNumber = static_cast<uint8_t>(yFlip ? spriteY1 - gpuReg[OffLY] : spriteY2 - gpuReg[OffLY]);
// Read the whole line
// Get 2-bit value - multiply tileLineIndex by two as each line is composed of 2-bytes
const uint16_t finalAddress = (patternNumber << 4) + (lineNumber << 1);
// render
for (int8_t i = 0; i < 8; ++i) {
int8_t x = xFlip ? 7 - i : i;
uint8_t pixelValue = static_cast<uint8_t>((videoRam.readExt(finalAddress + 1) &
(1 << (7 - x))) ? 2 : 0);
pixelValue |= (videoRam.readExt(finalAddress) >> (7 - x)) & 1;
// Get palette colour value
const uint8_t color = static_cast<uint8_t>((palette >> (pixelValue << 1)) & 0x03);
//
int16_t spriteXPixel = spriteX1 + i;
if (spriteXPixel >= 0 && spriteXPixel < WIDTH
&& (color != colors[COLOUR0])
&& (hasPriority || frameBuffer[gpuReg[OffLY] * WIDTH + spriteXPixel] == colors[COLOUR0])) {
frameBuffer[gpuReg[OffLY] * WIDTH + spriteXPixel] = colors[color];
}
}
}
}
}
}
<|endoftext|> |
<commit_before>#include <Wire.h> // I2C用
#include <ADXL345.h> // 加速度センサ用
#include <TimerOne.h> //timer1 //timer0はdelay、timer2はtoneで使われてる(´・ω・`)
// #include "dtmtdatas.h"
#include "Helper2_protected.h"
#include "LED.h"
Accel accel;
// val の値を min と max の値に収まるようにする
// val < min :=> min
// min <= val <= max :=> val
// max < val :=> max
float clamp(float val, float min, float max) {
if (val < min) { return min; }
if (max < val) { return max; }
return val;
}
// I2C
// 直接接続だと 0x53, そうでないと 0x1D
#define ADXL345_ID 0x53
// 加速度センサ
ADXL345 adxl;
Accel accel;
LEDClass led1 = LEDClass(0);
LEDClass led2 = LEDClass(1);
void initialize() {
accel = Accel();
AN_LED.begin();
// ピン初期化
// pinMode(2,OUTPUT);
// digitalWrite(2,LOW);
// 加速度センサ初期化
sendi2c(ADXL345_ID, 0x2C, 0b00001100); //3200Hz書き出し
sendi2c(ADXL345_ID, 0x31, 0b00001000); //fullresmode
initializeAccelerometer();
// タイマー1
//割り込み周期[usec]//887@16MH動作//8Mhz動作なら単純に考えて倍
Timer1.initialize(800);
// Timer1.initialize(6000);
Timer1.attachInterrupt(interrupt); //割り込みする関数
// debug用
// Serial.begin(9600);
// Serial.println("started");
delay(1000);//初期状態確認用
}
void updateData() {
int count = 20, sumx = 0, sumy = 0, sumz = 0;
int rawx = 0, rawy = 0, rawz = 0;
// 水準器
for(int i=0; i<count; i++){
adxl.readAccel(&rawx, &rawy, &rawz);
sumx += rawx;
sumy += rawy;
sumz += rawz;
}
// // sum(x, y, z) は -10240 - 10240 をとる?
// // 1G で x, y: 4900, z: 4500 ぐらいの値をとる => 正規化して -1.0 - 1.0 に縮める
// // by kyontan
// // NOTE: 割る値 は適宜調整してください
float x = clamp(-sumx / 4900.0, -1.0, 1.0);
float y = clamp(-sumy / 4900.0, -1.0, 1.0);
float z = clamp(-sumz / 4500.0, -1.0, 1.0);
accel.x = x;
accel.y = y;
accel.z = z;
};
// loop() の中で呼ばれる
void wait(int16_t msec) {
uint32_t start = millis();
while ((millis() - start) < msec) {
updateData();
}
};
// timer1割り込みで走る関数
void interrupt() {
// LEDの点滅とかはここでしても良いかも?
};
// I2C通信
void sendi2c(int8_t id, int8_t reg, int8_t data) {
Wire.beginTransmission(id); // Adxl345 のアドレス: 0x1D
Wire.write(reg);
Wire.write(data);
Wire.endTransmission();
};
void initializeAccelerometer() {
adxl.powerOn();
adxl.setRangeSetting(2); //測定範囲
// 動作した or してないの閾値を設定 (0-255)
adxl.setActivityThreshold(75); //値:*62.5[mg]
adxl.setInactivityThreshold(75); //値:*62.5[mg]
adxl.setTimeInactivity(10); //非動作の判定までに要する時間//値:*5[ms]
// 動作したかを監視する軸の設定 (1 == on; 0 == off)
//各軸の判定の論理和
adxl.setActivityX(1);
adxl.setActivityY(1);
adxl.setActivityZ(1);
// 動作してないを監視する軸の設定 (1 == on; 0 == off)
//各軸の判定の論理積
adxl.setInactivityX(1);
adxl.setInactivityY(1);
adxl.setInactivityZ(1);
// タップされたことを検視する軸の設定 (1 == on; 0 == off)
adxl.setTapDetectionOnX(0);
adxl.setTapDetectionOnY(0);
adxl.setTapDetectionOnZ(0);
// タップ,ダブルタップに関数る閾値の設定 (0-255)
adxl.setTapThreshold(80); //値:*62.5[mg]
adxl.setTapDuration(15); //値:*625[μs]
adxl.setDoubleTapLatency(80); //値:*1.25[ms]
adxl.setDoubleTapWindow(200); //値:*1.25[ms]
// 自由落下に関する閾値の設定 (0-255)
//閾値と時間の論理積
adxl.setFreeFallThreshold(0x09); //閾値//(0x05 - 0x09) 推薦 - 値:*62.5[mg]
adxl.setFreeFallDuration(0x0A); //時間//(0x14 - 0.46) 推薦 - 値:*5[ms]
//setting all interupts to take place on int pin 1
//I had issues with int pin 2, was unable to reset it
adxl.setInterruptMapping( ADXL345_INT_SINGLE_TAP_BIT, ADXL345_INT1_PIN );
adxl.setInterruptMapping( ADXL345_INT_DOUBLE_TAP_BIT, ADXL345_INT1_PIN );
adxl.setInterruptMapping( ADXL345_INT_FREE_FALL_BIT, ADXL345_INT1_PIN );
adxl.setInterruptMapping( ADXL345_INT_ACTIVITY_BIT, ADXL345_INT1_PIN );
adxl.setInterruptMapping( ADXL345_INT_INACTIVITY_BIT, ADXL345_INT1_PIN );
//register interupt actions - 1 == on; 0 == off
adxl.setInterrupt( ADXL345_INT_SINGLE_TAP_BIT, 0);
adxl.setInterrupt( ADXL345_INT_DOUBLE_TAP_BIT, 0);
adxl.setInterrupt( ADXL345_INT_FREE_FALL_BIT, 0);
adxl.setInterrupt( ADXL345_INT_ACTIVITY_BIT, 0);
adxl.setInterrupt( ADXL345_INT_INACTIVITY_BIT, 0);
}
<commit_msg>コンパイル通ります<commit_after>#include <Wire.h> // I2C用
#include <ADXL345.h> // 加速度センサ用
#include <TimerOne.h> //timer1 //timer0はdelay、timer2はtoneで使われてる(´・ω・`)
// #include "dtmtdatas.h"
#include "Helper2_protected.h"
#include "LED.h"
// val の値を min と max の値に収まるようにする
// val < min :=> min
// min <= val <= max :=> val
// max < val :=> max
float clamp(float val, float min, float max) {
if (val < min) { return min; }
if (max < val) { return max; }
return val;
}
// I2C
// 直接接続だと 0x53, そうでないと 0x1D
#define ADXL345_ID 0x53
// 加速度センサ
ADXL345 adxl;
Accel accel;
LEDClass led1 = LEDClass(0);
LEDClass led2 = LEDClass(1);
void initialize() {
accel = Accel();
AN_LED.begin();
// ピン初期化
// pinMode(2,OUTPUT);
// digitalWrite(2,LOW);
// 加速度センサ初期化
sendi2c(ADXL345_ID, 0x2C, 0b00001100); //3200Hz書き出し
sendi2c(ADXL345_ID, 0x31, 0b00001000); //fullresmode
initializeAccelerometer();
// タイマー1
//割り込み周期[usec]//887@16MH動作//8Mhz動作なら単純に考えて倍
Timer1.initialize(800);
// Timer1.initialize(6000);
Timer1.attachInterrupt(interrupt); //割り込みする関数
// debug用
// Serial.begin(9600);
// Serial.println("started");
delay(1000);//初期状態確認用
}
void updateData() {
int count = 20, sumx = 0, sumy = 0, sumz = 0;
int rawx = 0, rawy = 0, rawz = 0;
// 水準器
for(int i=0; i<count; i++){
adxl.readAccel(&rawx, &rawy, &rawz);
sumx += rawx;
sumy += rawy;
sumz += rawz;
}
// // sum(x, y, z) は -10240 - 10240 をとる?
// // 1G で x, y: 4900, z: 4500 ぐらいの値をとる => 正規化して -1.0 - 1.0 に縮める
// // by kyontan
// // NOTE: 割る値 は適宜調整してください
float x = clamp(-sumx / 4900.0, -1.0, 1.0);
float y = clamp(-sumy / 4900.0, -1.0, 1.0);
float z = clamp(-sumz / 4500.0, -1.0, 1.0);
accel.x = x;
accel.y = y;
accel.z = z;
};
// loop() の中で呼ばれる
void wait(int16_t msec) {
uint32_t start = millis();
while ((millis() - start) < msec) {
updateData();
}
};
// timer1割り込みで走る関数
void interrupt() {
// LEDの点滅とかはここでしても良いかも?
};
// I2C通信
void sendi2c(int8_t id, int8_t reg, int8_t data) {
Wire.beginTransmission(id); // Adxl345 のアドレス: 0x1D
Wire.write(reg);
Wire.write(data);
Wire.endTransmission();
};
void initializeAccelerometer() {
adxl.powerOn();
adxl.setRangeSetting(2); //測定範囲
// 動作した or してないの閾値を設定 (0-255)
adxl.setActivityThreshold(75); //値:*62.5[mg]
adxl.setInactivityThreshold(75); //値:*62.5[mg]
adxl.setTimeInactivity(10); //非動作の判定までに要する時間//値:*5[ms]
// 動作したかを監視する軸の設定 (1 == on; 0 == off)
//各軸の判定の論理和
adxl.setActivityX(1);
adxl.setActivityY(1);
adxl.setActivityZ(1);
// 動作してないを監視する軸の設定 (1 == on; 0 == off)
//各軸の判定の論理積
adxl.setInactivityX(1);
adxl.setInactivityY(1);
adxl.setInactivityZ(1);
// タップされたことを検視する軸の設定 (1 == on; 0 == off)
adxl.setTapDetectionOnX(0);
adxl.setTapDetectionOnY(0);
adxl.setTapDetectionOnZ(0);
// タップ,ダブルタップに関数る閾値の設定 (0-255)
adxl.setTapThreshold(80); //値:*62.5[mg]
adxl.setTapDuration(15); //値:*625[μs]
adxl.setDoubleTapLatency(80); //値:*1.25[ms]
adxl.setDoubleTapWindow(200); //値:*1.25[ms]
// 自由落下に関する閾値の設定 (0-255)
//閾値と時間の論理積
adxl.setFreeFallThreshold(0x09); //閾値//(0x05 - 0x09) 推薦 - 値:*62.5[mg]
adxl.setFreeFallDuration(0x0A); //時間//(0x14 - 0.46) 推薦 - 値:*5[ms]
//setting all interupts to take place on int pin 1
//I had issues with int pin 2, was unable to reset it
adxl.setInterruptMapping( ADXL345_INT_SINGLE_TAP_BIT, ADXL345_INT1_PIN );
adxl.setInterruptMapping( ADXL345_INT_DOUBLE_TAP_BIT, ADXL345_INT1_PIN );
adxl.setInterruptMapping( ADXL345_INT_FREE_FALL_BIT, ADXL345_INT1_PIN );
adxl.setInterruptMapping( ADXL345_INT_ACTIVITY_BIT, ADXL345_INT1_PIN );
adxl.setInterruptMapping( ADXL345_INT_INACTIVITY_BIT, ADXL345_INT1_PIN );
//register interupt actions - 1 == on; 0 == off
adxl.setInterrupt( ADXL345_INT_SINGLE_TAP_BIT, 0);
adxl.setInterrupt( ADXL345_INT_DOUBLE_TAP_BIT, 0);
adxl.setInterrupt( ADXL345_INT_FREE_FALL_BIT, 0);
adxl.setInterrupt( ADXL345_INT_ACTIVITY_BIT, 0);
adxl.setInterrupt( ADXL345_INT_INACTIVITY_BIT, 0);
}
<|endoftext|> |
<commit_before>/// \file RNTuple.cxx
/// \ingroup NTuple ROOT7
/// \author Jakob Blomer <[email protected]>
/// \date 2018-10-04
/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback
/// is welcome!
/*************************************************************************
* Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include <ROOT/RNTuple.hxx>
#include <ROOT/RFieldVisitor.hxx>
#include <ROOT/RNTupleModel.hxx>
#include <ROOT/RPageSourceFriends.hxx>
#include <ROOT/RPageStorage.hxx>
#include <ROOT/RPageSinkBuf.hxx>
#include <ROOT/RPageStorageFile.hxx>
#ifdef R__USE_IMT
#include <ROOT/TTaskGroup.hxx>
#endif
#include <TError.h>
#include <TROOT.h> // for IsImplicitMTEnabled()
#include <algorithm>
#include <exception>
#include <functional>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <unordered_map>
#include <utility>
#ifdef R__USE_IMT
ROOT::Experimental::RNTupleImtTaskScheduler::RNTupleImtTaskScheduler()
{
Reset();
}
void ROOT::Experimental::RNTupleImtTaskScheduler::Reset()
{
fTaskGroup = std::make_unique<TTaskGroup>();
}
void ROOT::Experimental::RNTupleImtTaskScheduler::AddTask(const std::function<void(void)> &taskFunc)
{
fTaskGroup->Run(taskFunc);
}
void ROOT::Experimental::RNTupleImtTaskScheduler::Wait()
{
fTaskGroup->Wait();
}
#endif
//------------------------------------------------------------------------------
void ROOT::Experimental::RNTupleReader::ConnectModel(const RNTupleModel &model) {
const auto &desc = fSource->GetDescriptor();
model.GetFieldZero()->SetOnDiskId(desc.GetFieldZeroId());
for (auto &field : *model.GetFieldZero()) {
// If the model has been created from the descritor, the on-disk IDs are already set.
// User-provided models instead need to find their corresponding IDs in the descriptor.
if (field.GetOnDiskId() == kInvalidDescriptorId) {
field.SetOnDiskId(desc.FindFieldId(field.GetName(), field.GetParent()->GetOnDiskId()));
}
field.ConnectPageSource(*fSource);
}
}
void ROOT::Experimental::RNTupleReader::InitPageSource()
{
#ifdef R__USE_IMT
if (IsImplicitMTEnabled()) {
fUnzipTasks = std::make_unique<RNTupleImtTaskScheduler>();
fSource->SetTaskScheduler(fUnzipTasks.get());
}
#endif
fSource->Attach();
fMetrics.ObserveMetrics(fSource->GetMetrics());
}
ROOT::Experimental::RNTupleReader::RNTupleReader(
std::unique_ptr<ROOT::Experimental::RNTupleModel> model,
std::unique_ptr<ROOT::Experimental::Detail::RPageSource> source)
: fSource(std::move(source))
, fModel(std::move(model))
, fMetrics("RNTupleReader")
{
if (!fSource) {
throw RException(R__FAIL("null source"));
}
if (!fModel) {
throw RException(R__FAIL("null model"));
}
InitPageSource();
ConnectModel(*fModel);
}
ROOT::Experimental::RNTupleReader::RNTupleReader(std::unique_ptr<ROOT::Experimental::Detail::RPageSource> source)
: fSource(std::move(source))
, fModel(nullptr)
, fMetrics("RNTupleReader")
{
if (!fSource) {
throw RException(R__FAIL("null source"));
}
InitPageSource();
}
ROOT::Experimental::RNTupleReader::~RNTupleReader() = default;
std::unique_ptr<ROOT::Experimental::RNTupleReader> ROOT::Experimental::RNTupleReader::Open(
std::unique_ptr<RNTupleModel> model,
std::string_view ntupleName,
std::string_view storage,
const RNTupleReadOptions &options)
{
return std::make_unique<RNTupleReader>(std::move(model), Detail::RPageSource::Create(ntupleName, storage, options));
}
std::unique_ptr<ROOT::Experimental::RNTupleReader> ROOT::Experimental::RNTupleReader::Open(
std::string_view ntupleName,
std::string_view storage,
const RNTupleReadOptions &options)
{
return std::make_unique<RNTupleReader>(Detail::RPageSource::Create(ntupleName, storage, options));
}
std::unique_ptr<ROOT::Experimental::RNTupleReader> ROOT::Experimental::RNTupleReader::OpenFriends(
std::span<ROpenSpec> ntuples)
{
std::vector<std::unique_ptr<Detail::RPageSource>> sources;
for (const auto &n : ntuples) {
sources.emplace_back(Detail::RPageSource::Create(n.fNTupleName, n.fStorage, n.fOptions));
}
return std::make_unique<RNTupleReader>(std::make_unique<Detail::RPageSourceFriends>("_friends", sources));
}
ROOT::Experimental::RNTupleModel *ROOT::Experimental::RNTupleReader::GetModel()
{
if (!fModel) {
fModel = fSource->GetDescriptor().GenerateModel();
ConnectModel(*fModel);
}
return fModel.get();
}
void ROOT::Experimental::RNTupleReader::PrintInfo(const ENTupleInfo what, std::ostream &output)
{
// TODO(lesimon): In a later version, these variables may be defined by the user or the ideal width may be read out from the terminal.
char frameSymbol = '*';
int width = 80;
/*
if (width < 30) {
output << "The width is too small! Should be at least 30." << std::endl;
return;
}
*/
std::string name = fSource->GetDescriptor().GetName();
switch (what) {
case ENTupleInfo::kSummary: {
for (int i = 0; i < (width/2 + width%2 - 4); ++i)
output << frameSymbol;
output << " NTUPLE ";
for (int i = 0; i < (width/2 - 4); ++i)
output << frameSymbol;
output << std::endl;
// FitString defined in RFieldVisitor.cxx
output << frameSymbol << " N-Tuple : " << RNTupleFormatter::FitString(name, width-13) << frameSymbol << std::endl; // prints line with name of ntuple
output << frameSymbol << " Entries : " << RNTupleFormatter::FitString(std::to_string(GetNEntries()), width - 13) << frameSymbol << std::endl; // prints line with number of entries
// Traverses through all fields to gather information needed for printing.
RPrepareVisitor prepVisitor;
// Traverses through all fields to do the actual printing.
RPrintSchemaVisitor printVisitor(output);
// Note that we do not need to connect the model, we are only looking at its tree of fields
auto fullModel = fSource->GetDescriptor().GenerateModel();
fullModel->GetFieldZero()->AcceptVisitor(prepVisitor);
printVisitor.SetFrameSymbol(frameSymbol);
printVisitor.SetWidth(width);
printVisitor.SetDeepestLevel(prepVisitor.GetDeepestLevel());
printVisitor.SetNumFields(prepVisitor.GetNumFields());
for (int i = 0; i < width; ++i)
output << frameSymbol;
output << std::endl;
fullModel->GetFieldZero()->AcceptVisitor(printVisitor);
for (int i = 0; i < width; ++i)
output << frameSymbol;
output << std::endl;
break;
}
case ENTupleInfo::kStorageDetails:
fSource->GetDescriptor().PrintInfo(output);
break;
case ENTupleInfo::kMetrics:
fMetrics.Print(output);
break;
default:
// Unhandled case, internal error
R__ASSERT(false);
}
}
ROOT::Experimental::RNTupleReader *ROOT::Experimental::RNTupleReader::GetDisplayReader()
{
if (!fDisplayReader)
fDisplayReader = Clone();
return fDisplayReader.get();
}
void ROOT::Experimental::RNTupleReader::Show(NTupleSize_t index, const ENTupleShowFormat format, std::ostream &output)
{
RNTupleReader *reader = this;
REntry *entry = nullptr;
// Don't accidentally trigger loading of the entire model
if (fModel)
entry = fModel->GetDefaultEntry();
switch(format) {
case ENTupleShowFormat::kCompleteJSON:
reader = GetDisplayReader();
entry = reader->GetModel()->GetDefaultEntry();
// Fall through
case ENTupleShowFormat::kCurrentModelJSON:
if (!entry) {
output << "{}" << std::endl;
break;
}
reader->LoadEntry(index);
output << "{";
for (auto iValue = entry->begin(); iValue != entry->end(); ) {
output << std::endl;
RPrintValueVisitor visitor(*iValue, output, 1 /* level */);
iValue->GetField()->AcceptVisitor(visitor);
if (++iValue == entry->end()) {
output << std::endl;
break;
} else {
output << ",";
}
}
output << "}" << std::endl;
break;
default:
// Unhandled case, internal error
R__ASSERT(false);
}
}
//------------------------------------------------------------------------------
ROOT::Experimental::RNTupleWriter::RNTupleWriter(
std::unique_ptr<ROOT::Experimental::RNTupleModel> model,
std::unique_ptr<ROOT::Experimental::Detail::RPageSink> sink)
: fSink(std::move(sink))
, fModel(std::move(model))
, fMetrics("RNTupleWriter")
{
if (!fModel) {
throw RException(R__FAIL("null model"));
}
if (!fSink) {
throw RException(R__FAIL("null sink"));
}
#ifdef R__USE_IMT
if (IsImplicitMTEnabled()) {
fZipTasks = std::make_unique<RNTupleImtTaskScheduler>();
fSink->SetTaskScheduler(fZipTasks.get());
}
#endif
fSink->Create(*fModel.get());
fMetrics.ObserveMetrics(fSink->GetMetrics());
const auto &writeOpts = fSink->GetWriteOptions();
fMaxUnzippedClusterSize = writeOpts.GetMaxUnzippedClusterSize();
// First estimate is a factor 2 compression if compression is used at all
const int scale = writeOpts.GetCompression() ? 2 : 1;
fUnzippedClusterSizeEst = scale * writeOpts.GetApproxZippedClusterSize();
}
ROOT::Experimental::RNTupleWriter::~RNTupleWriter()
{
CommitCluster();
fSink->CommitDataset();
}
std::unique_ptr<ROOT::Experimental::RNTupleWriter> ROOT::Experimental::RNTupleWriter::Recreate(
std::unique_ptr<RNTupleModel> model,
std::string_view ntupleName,
std::string_view storage,
const RNTupleWriteOptions &options)
{
return std::make_unique<RNTupleWriter>(std::move(model), Detail::RPageSink::Create(ntupleName, storage, options));
}
std::unique_ptr<ROOT::Experimental::RNTupleWriter> ROOT::Experimental::RNTupleWriter::Append(
std::unique_ptr<RNTupleModel> model,
std::string_view ntupleName,
TFile &file,
const RNTupleWriteOptions &options)
{
auto sink = std::make_unique<Detail::RPageSinkFile>(ntupleName, file, options);
if (options.GetUseBufferedWrite()) {
auto bufferedSink = std::make_unique<Detail::RPageSinkBuf>(std::move(sink));
return std::make_unique<RNTupleWriter>(std::move(model), std::move(bufferedSink));
}
return std::make_unique<RNTupleWriter>(std::move(model), std::move(sink));
}
void ROOT::Experimental::RNTupleWriter::CommitCluster()
{
if (fNEntries == fLastCommitted) return;
for (auto& field : *fModel->GetFieldZero()) {
field.Flush();
field.CommitCluster();
}
const float nbytes = fSink->CommitCluster(fNEntries);
// Cap the compression factor at 1000 to prevent overflow of fMinUnzippedClusterSizeEst
float compressionFactor = std::min(1000.f, static_cast<float>(fUnzippedClusterSize) / nbytes);
fUnzippedClusterSizeEst =
compressionFactor * static_cast<float>(fSink->GetWriteOptions().GetApproxZippedClusterSize());
fLastCommitted = fNEntries;
fUnzippedClusterSize = 0;
}
//------------------------------------------------------------------------------
ROOT::Experimental::RCollectionNTupleWriter::RCollectionNTupleWriter(std::unique_ptr<REntry> defaultEntry)
: fOffset(0), fDefaultEntry(std::move(defaultEntry))
{
}
<commit_msg>[ntuple] Clarify constness of local variable<commit_after>/// \file RNTuple.cxx
/// \ingroup NTuple ROOT7
/// \author Jakob Blomer <[email protected]>
/// \date 2018-10-04
/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback
/// is welcome!
/*************************************************************************
* Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include <ROOT/RNTuple.hxx>
#include <ROOT/RFieldVisitor.hxx>
#include <ROOT/RNTupleModel.hxx>
#include <ROOT/RPageSourceFriends.hxx>
#include <ROOT/RPageStorage.hxx>
#include <ROOT/RPageSinkBuf.hxx>
#include <ROOT/RPageStorageFile.hxx>
#ifdef R__USE_IMT
#include <ROOT/TTaskGroup.hxx>
#endif
#include <TError.h>
#include <TROOT.h> // for IsImplicitMTEnabled()
#include <algorithm>
#include <exception>
#include <functional>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <unordered_map>
#include <utility>
#ifdef R__USE_IMT
ROOT::Experimental::RNTupleImtTaskScheduler::RNTupleImtTaskScheduler()
{
Reset();
}
void ROOT::Experimental::RNTupleImtTaskScheduler::Reset()
{
fTaskGroup = std::make_unique<TTaskGroup>();
}
void ROOT::Experimental::RNTupleImtTaskScheduler::AddTask(const std::function<void(void)> &taskFunc)
{
fTaskGroup->Run(taskFunc);
}
void ROOT::Experimental::RNTupleImtTaskScheduler::Wait()
{
fTaskGroup->Wait();
}
#endif
//------------------------------------------------------------------------------
void ROOT::Experimental::RNTupleReader::ConnectModel(const RNTupleModel &model) {
const auto &desc = fSource->GetDescriptor();
model.GetFieldZero()->SetOnDiskId(desc.GetFieldZeroId());
for (auto &field : *model.GetFieldZero()) {
// If the model has been created from the descritor, the on-disk IDs are already set.
// User-provided models instead need to find their corresponding IDs in the descriptor.
if (field.GetOnDiskId() == kInvalidDescriptorId) {
field.SetOnDiskId(desc.FindFieldId(field.GetName(), field.GetParent()->GetOnDiskId()));
}
field.ConnectPageSource(*fSource);
}
}
void ROOT::Experimental::RNTupleReader::InitPageSource()
{
#ifdef R__USE_IMT
if (IsImplicitMTEnabled()) {
fUnzipTasks = std::make_unique<RNTupleImtTaskScheduler>();
fSource->SetTaskScheduler(fUnzipTasks.get());
}
#endif
fSource->Attach();
fMetrics.ObserveMetrics(fSource->GetMetrics());
}
ROOT::Experimental::RNTupleReader::RNTupleReader(
std::unique_ptr<ROOT::Experimental::RNTupleModel> model,
std::unique_ptr<ROOT::Experimental::Detail::RPageSource> source)
: fSource(std::move(source))
, fModel(std::move(model))
, fMetrics("RNTupleReader")
{
if (!fSource) {
throw RException(R__FAIL("null source"));
}
if (!fModel) {
throw RException(R__FAIL("null model"));
}
InitPageSource();
ConnectModel(*fModel);
}
ROOT::Experimental::RNTupleReader::RNTupleReader(std::unique_ptr<ROOT::Experimental::Detail::RPageSource> source)
: fSource(std::move(source))
, fModel(nullptr)
, fMetrics("RNTupleReader")
{
if (!fSource) {
throw RException(R__FAIL("null source"));
}
InitPageSource();
}
ROOT::Experimental::RNTupleReader::~RNTupleReader() = default;
std::unique_ptr<ROOT::Experimental::RNTupleReader> ROOT::Experimental::RNTupleReader::Open(
std::unique_ptr<RNTupleModel> model,
std::string_view ntupleName,
std::string_view storage,
const RNTupleReadOptions &options)
{
return std::make_unique<RNTupleReader>(std::move(model), Detail::RPageSource::Create(ntupleName, storage, options));
}
std::unique_ptr<ROOT::Experimental::RNTupleReader> ROOT::Experimental::RNTupleReader::Open(
std::string_view ntupleName,
std::string_view storage,
const RNTupleReadOptions &options)
{
return std::make_unique<RNTupleReader>(Detail::RPageSource::Create(ntupleName, storage, options));
}
std::unique_ptr<ROOT::Experimental::RNTupleReader> ROOT::Experimental::RNTupleReader::OpenFriends(
std::span<ROpenSpec> ntuples)
{
std::vector<std::unique_ptr<Detail::RPageSource>> sources;
for (const auto &n : ntuples) {
sources.emplace_back(Detail::RPageSource::Create(n.fNTupleName, n.fStorage, n.fOptions));
}
return std::make_unique<RNTupleReader>(std::make_unique<Detail::RPageSourceFriends>("_friends", sources));
}
ROOT::Experimental::RNTupleModel *ROOT::Experimental::RNTupleReader::GetModel()
{
if (!fModel) {
fModel = fSource->GetDescriptor().GenerateModel();
ConnectModel(*fModel);
}
return fModel.get();
}
void ROOT::Experimental::RNTupleReader::PrintInfo(const ENTupleInfo what, std::ostream &output)
{
// TODO(lesimon): In a later version, these variables may be defined by the user or the ideal width may be read out from the terminal.
char frameSymbol = '*';
int width = 80;
/*
if (width < 30) {
output << "The width is too small! Should be at least 30." << std::endl;
return;
}
*/
std::string name = fSource->GetDescriptor().GetName();
switch (what) {
case ENTupleInfo::kSummary: {
for (int i = 0; i < (width/2 + width%2 - 4); ++i)
output << frameSymbol;
output << " NTUPLE ";
for (int i = 0; i < (width/2 - 4); ++i)
output << frameSymbol;
output << std::endl;
// FitString defined in RFieldVisitor.cxx
output << frameSymbol << " N-Tuple : " << RNTupleFormatter::FitString(name, width-13) << frameSymbol << std::endl; // prints line with name of ntuple
output << frameSymbol << " Entries : " << RNTupleFormatter::FitString(std::to_string(GetNEntries()), width - 13) << frameSymbol << std::endl; // prints line with number of entries
// Traverses through all fields to gather information needed for printing.
RPrepareVisitor prepVisitor;
// Traverses through all fields to do the actual printing.
RPrintSchemaVisitor printVisitor(output);
// Note that we do not need to connect the model, we are only looking at its tree of fields
auto fullModel = fSource->GetDescriptor().GenerateModel();
fullModel->GetFieldZero()->AcceptVisitor(prepVisitor);
printVisitor.SetFrameSymbol(frameSymbol);
printVisitor.SetWidth(width);
printVisitor.SetDeepestLevel(prepVisitor.GetDeepestLevel());
printVisitor.SetNumFields(prepVisitor.GetNumFields());
for (int i = 0; i < width; ++i)
output << frameSymbol;
output << std::endl;
fullModel->GetFieldZero()->AcceptVisitor(printVisitor);
for (int i = 0; i < width; ++i)
output << frameSymbol;
output << std::endl;
break;
}
case ENTupleInfo::kStorageDetails:
fSource->GetDescriptor().PrintInfo(output);
break;
case ENTupleInfo::kMetrics:
fMetrics.Print(output);
break;
default:
// Unhandled case, internal error
R__ASSERT(false);
}
}
ROOT::Experimental::RNTupleReader *ROOT::Experimental::RNTupleReader::GetDisplayReader()
{
if (!fDisplayReader)
fDisplayReader = Clone();
return fDisplayReader.get();
}
void ROOT::Experimental::RNTupleReader::Show(NTupleSize_t index, const ENTupleShowFormat format, std::ostream &output)
{
RNTupleReader *reader = this;
REntry *entry = nullptr;
// Don't accidentally trigger loading of the entire model
if (fModel)
entry = fModel->GetDefaultEntry();
switch(format) {
case ENTupleShowFormat::kCompleteJSON:
reader = GetDisplayReader();
entry = reader->GetModel()->GetDefaultEntry();
// Fall through
case ENTupleShowFormat::kCurrentModelJSON:
if (!entry) {
output << "{}" << std::endl;
break;
}
reader->LoadEntry(index);
output << "{";
for (auto iValue = entry->begin(); iValue != entry->end(); ) {
output << std::endl;
RPrintValueVisitor visitor(*iValue, output, 1 /* level */);
iValue->GetField()->AcceptVisitor(visitor);
if (++iValue == entry->end()) {
output << std::endl;
break;
} else {
output << ",";
}
}
output << "}" << std::endl;
break;
default:
// Unhandled case, internal error
R__ASSERT(false);
}
}
//------------------------------------------------------------------------------
ROOT::Experimental::RNTupleWriter::RNTupleWriter(
std::unique_ptr<ROOT::Experimental::RNTupleModel> model,
std::unique_ptr<ROOT::Experimental::Detail::RPageSink> sink)
: fSink(std::move(sink))
, fModel(std::move(model))
, fMetrics("RNTupleWriter")
{
if (!fModel) {
throw RException(R__FAIL("null model"));
}
if (!fSink) {
throw RException(R__FAIL("null sink"));
}
#ifdef R__USE_IMT
if (IsImplicitMTEnabled()) {
fZipTasks = std::make_unique<RNTupleImtTaskScheduler>();
fSink->SetTaskScheduler(fZipTasks.get());
}
#endif
fSink->Create(*fModel.get());
fMetrics.ObserveMetrics(fSink->GetMetrics());
const auto &writeOpts = fSink->GetWriteOptions();
fMaxUnzippedClusterSize = writeOpts.GetMaxUnzippedClusterSize();
// First estimate is a factor 2 compression if compression is used at all
const int scale = writeOpts.GetCompression() ? 2 : 1;
fUnzippedClusterSizeEst = scale * writeOpts.GetApproxZippedClusterSize();
}
ROOT::Experimental::RNTupleWriter::~RNTupleWriter()
{
CommitCluster();
fSink->CommitDataset();
}
std::unique_ptr<ROOT::Experimental::RNTupleWriter> ROOT::Experimental::RNTupleWriter::Recreate(
std::unique_ptr<RNTupleModel> model,
std::string_view ntupleName,
std::string_view storage,
const RNTupleWriteOptions &options)
{
return std::make_unique<RNTupleWriter>(std::move(model), Detail::RPageSink::Create(ntupleName, storage, options));
}
std::unique_ptr<ROOT::Experimental::RNTupleWriter> ROOT::Experimental::RNTupleWriter::Append(
std::unique_ptr<RNTupleModel> model,
std::string_view ntupleName,
TFile &file,
const RNTupleWriteOptions &options)
{
auto sink = std::make_unique<Detail::RPageSinkFile>(ntupleName, file, options);
if (options.GetUseBufferedWrite()) {
auto bufferedSink = std::make_unique<Detail::RPageSinkBuf>(std::move(sink));
return std::make_unique<RNTupleWriter>(std::move(model), std::move(bufferedSink));
}
return std::make_unique<RNTupleWriter>(std::move(model), std::move(sink));
}
void ROOT::Experimental::RNTupleWriter::CommitCluster()
{
if (fNEntries == fLastCommitted) return;
for (auto& field : *fModel->GetFieldZero()) {
field.Flush();
field.CommitCluster();
}
const float nbytes = fSink->CommitCluster(fNEntries);
// Cap the compression factor at 1000 to prevent overflow of fMinUnzippedClusterSizeEst
const float compressionFactor = std::min(1000.f, static_cast<float>(fUnzippedClusterSize) / nbytes);
fUnzippedClusterSizeEst =
compressionFactor * static_cast<float>(fSink->GetWriteOptions().GetApproxZippedClusterSize());
fLastCommitted = fNEntries;
fUnzippedClusterSize = 0;
}
//------------------------------------------------------------------------------
ROOT::Experimental::RCollectionNTupleWriter::RCollectionNTupleWriter(std::unique_ptr<REntry> defaultEntry)
: fOffset(0), fDefaultEntry(std::move(defaultEntry))
{
}
<|endoftext|> |
<commit_before>#include "TFile.h"
#include "TTree.h"
#include "TTreeReader.h"
#include "TTreeReaderArray.h"
#include "gtest/gtest.h"
#include <fstream>
TEST(TTreeReaderArray, MultiReaders) {
// See https://root.cern.ch/phpBB3/viewtopic.php?f=3&t=22790
TTree* tree = new TTree("TTreeReaderArrayTree", "In-memory test tree");
double Double[6] = {42.f, 43.f, 44.f, 45.f, 46.f, 47.f};
tree->Branch("D", &Double, "D[4]/D");
tree->Fill();
tree->Fill();
tree->Fill();
TTreeReader TR(tree);
TTreeReaderArray<double> trDouble0(TR, "D");
TTreeReaderArray<double> trDouble1(TR, "D");
TTreeReaderArray<double> trDouble2(TR, "D");
TTreeReaderArray<double> trDouble3(TR, "D");
TTreeReaderArray<double> trDouble4(TR, "D");
TTreeReaderArray<double> trDouble5(TR, "D");
TR.SetEntry(1);
EXPECT_EQ(4u, trDouble0.GetSize());
EXPECT_EQ(4u, trDouble1.GetSize());
EXPECT_EQ(4u, trDouble2.GetSize());
EXPECT_EQ(4u, trDouble3.GetSize());
EXPECT_EQ(4u, trDouble4.GetSize());
EXPECT_EQ(4u, trDouble5.GetSize());
for (int i = 0; i < 4; ++i) {
EXPECT_DOUBLE_EQ(Double[i], trDouble0[i]);
EXPECT_DOUBLE_EQ(Double[i], trDouble1[i]);
EXPECT_DOUBLE_EQ(Double[i], trDouble2[i]);
EXPECT_DOUBLE_EQ(Double[i], trDouble3[i]);
EXPECT_DOUBLE_EQ(Double[i], trDouble4[i]);
EXPECT_DOUBLE_EQ(Double[i], trDouble5[i]);
}
}
<commit_msg>Test TTreeReaderArray reading vector (not reproducing ROOT-8747).<commit_after>#include "TFile.h"
#include "TTree.h"
#include "TTreeReader.h"
#include "TTreeReaderArray.h"
#include "gtest/gtest.h"
#include <fstream>
TEST(TTreeReaderArray, Vector) {
TTree* tree = new TTree("TTreeReaderArrayTree", "In-memory test tree");
std::vector<float> vecf{17.f, 18.f, 19.f, 20.f, 21.f};
tree->Branch("vec", &vecf);
tree->Fill();
tree->Fill();
tree->Fill();
TTreeReader tr(tree);
TTreeReaderArray<double> vec(tr, "vec");
EXPECT_EQ(5u, vec.GetSize());
EXPECT_DOUBLE_EQ(19., vec[2]);
EXPECT_DOUBLE_EQ(17., vec[0]);
}
TEST(TTreeReaderArray, MultiReaders) {
// See https://root.cern.ch/phpBB3/viewtopic.php?f=3&t=22790
TTree* tree = new TTree("TTreeReaderArrayTree", "In-memory test tree");
double Double[6] = {42.f, 43.f, 44.f, 45.f, 46.f, 47.f};
tree->Branch("D", &Double, "D[4]/D");
tree->Fill();
tree->Fill();
tree->Fill();
TTreeReader TR(tree);
TTreeReaderArray<double> trDouble0(TR, "D");
TTreeReaderArray<double> trDouble1(TR, "D");
TTreeReaderArray<double> trDouble2(TR, "D");
TTreeReaderArray<double> trDouble3(TR, "D");
TTreeReaderArray<double> trDouble4(TR, "D");
TTreeReaderArray<double> trDouble5(TR, "D");
TR.SetEntry(1);
EXPECT_EQ(4u, trDouble0.GetSize());
EXPECT_EQ(4u, trDouble1.GetSize());
EXPECT_EQ(4u, trDouble2.GetSize());
EXPECT_EQ(4u, trDouble3.GetSize());
EXPECT_EQ(4u, trDouble4.GetSize());
EXPECT_EQ(4u, trDouble5.GetSize());
for (int i = 0; i < 4; ++i) {
EXPECT_DOUBLE_EQ(Double[i], trDouble0[i]);
EXPECT_DOUBLE_EQ(Double[i], trDouble1[i]);
EXPECT_DOUBLE_EQ(Double[i], trDouble2[i]);
EXPECT_DOUBLE_EQ(Double[i], trDouble3[i]);
EXPECT_DOUBLE_EQ(Double[i], trDouble4[i]);
EXPECT_DOUBLE_EQ(Double[i], trDouble5[i]);
}
}
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
///////////////////////////////////////////////////////////////////////////////
// //
// class for ZDC calibration -> values for pedestal subtraction //
// //
///////////////////////////////////////////////////////////////////////////////
#include "AliZDCPedestals.h"
ClassImp(AliZDCPedestals)
//________________________________________________________________
AliZDCPedestals::AliZDCPedestals():
TNamed()
{
Reset();
}
//________________________________________________________________
AliZDCPedestals::AliZDCPedestals(const char* name):
TNamed()
{
// Constructor
TString namst = "Calib_";
namst += name;
SetName(namst.Data());
SetTitle(namst.Data());
Reset();
for(Int_t i=0; i<48; i++){
fMeanPedestal[i] = 0.;
fMeanPedWidth[i] = 0.;
fOOTPedestal[i] = 0.;
fOOTPedWidth[i] = 0.;
for(Int_t j=0; j<2; j++) fPedCorrCoeff[j][i] = 0.;
}
}
//________________________________________________________________
AliZDCPedestals::AliZDCPedestals(const AliZDCPedestals& calibda) :
TNamed(calibda)
{
// Copy constructor
SetName(calibda.GetName());
SetTitle(calibda.GetName());
Reset();
for(int t=0; t<48; t++){
fMeanPedestal[t] = calibda.GetMeanPed(t);
fMeanPedWidth[t] = calibda.GetMeanPedWidth(t);
fOOTPedestal[t] = calibda.GetOOTPed(t);
fOOTPedWidth[t] = calibda.GetOOTPedWidth(t);
fPedCorrCoeff[0][t] = calibda.GetPedCorrCoeff0(t);
fPedCorrCoeff[1][t] = calibda.GetPedCorrCoeff1(t);
}
}
//________________________________________________________________
AliZDCPedestals &AliZDCPedestals::operator =(const AliZDCPedestals& calibda)
{
// assignment operator
SetName(calibda.GetName());
SetTitle(calibda.GetName());
Reset();
for(int t=0; t<48; t++){
fMeanPedestal[t] = calibda.GetMeanPed(t);
fMeanPedWidth[t] = calibda.GetMeanPedWidth(t);
fOOTPedestal[t] = calibda.GetOOTPed(t);
fOOTPedWidth[t] = calibda.GetOOTPedWidth(t);
fPedCorrCoeff[0][t] = calibda.GetPedCorrCoeff0(t);
fPedCorrCoeff[1][t] = calibda.GetPedCorrCoeff1(t);
}
return *this;
}
//________________________________________________________________
AliZDCPedestals::~AliZDCPedestals()
{
}
//________________________________________________________________
void AliZDCPedestals::Reset()
{
// Reset
memset(fMeanPedestal,0,48*sizeof(Float_t));
memset(fMeanPedWidth,0,48*sizeof(Float_t));
memset(fOOTPedestal,0,48*sizeof(Float_t));
memset(fOOTPedWidth,0,48*sizeof(Float_t));
}
//________________________________________________________________
void AliZDCPedestals::Print(Option_t *) const
{
// Printing of calibration object
printf("\n ####### In-time pedestal values (mean value, sigma) ####### \n");
for(int t=0; t<48; t++)
printf("\t ADC%d (%.1f, %.1f)\n",t,fMeanPedestal[t],fMeanPedWidth[t]);
//
printf("\n\n ####### Out-of-time pedestal values (mean value, sigma) ####### \n");
for(int t=0; t<48; t++)
printf("\t ADC-OoT%d (%.1f, %.1f)\n",t,fOOTPedestal[t],fOOTPedWidth[t]);
}
//________________________________________________________________
void AliZDCPedestals::SetMeanPed(Float_t* MeanPed)
{
if(MeanPed) for(int t=0; t<48; t++) fMeanPedestal[t] = MeanPed[t];
else for(int t=0; t<48; t++) fMeanPedestal[t] = 0.;
}
//________________________________________________________________
void AliZDCPedestals::SetMeanPedWidth(Float_t* MeanPedWidth)
{
if(MeanPedWidth) for(int t=0; t<48; t++) fMeanPedWidth[t] = MeanPedWidth[t];
else for(int t=0; t<48; t++) fMeanPedWidth[t] = 0.;
}
//________________________________________________________________
void AliZDCPedestals::SetOOTPed(Float_t* OOTPed)
{
if(OOTPed) for(int t=0; t<48; t++) fOOTPedestal[t] = OOTPed[t];
else for(int t=0; t<48; t++) fOOTPedestal[t] = 0.;
}
//________________________________________________________________
void AliZDCPedestals::SetOOTPedWidth(Float_t* OOTPedWidth)
{
if(OOTPedWidth) for(int t=0; t<48; t++) fOOTPedWidth[t] = OOTPedWidth[t];
else for(int t=0; t<48; t++) fOOTPedWidth[t] = 0.;
}
//________________________________________________________________
void AliZDCPedestals:: SetPedCorrCoeff(Float_t* PedCorrCoeff)
{
// Set coefficients for pedestal correlations
if(PedCorrCoeff){
for(Int_t j=0; j<2; j++){
for(int t=0; t<48; t++)
fPedCorrCoeff[j][t] = PedCorrCoeff[t];
}
}
else{
for(Int_t j=0; j<2; j++){
for(int t=0; t<48; t++)
fPedCorrCoeff[j][t] = 0.;
}
}
}
//________________________________________________________________
void AliZDCPedestals:: SetPedCorrCoeff(Float_t* PedCorrCoeff0, Float_t* PedCorrCoeff1)
{
// Set coefficients for pedestal correlations
if(PedCorrCoeff0 && PedCorrCoeff1){
for(int t=0; t<48; t++){
fPedCorrCoeff[0][t] = PedCorrCoeff0[t];
fPedCorrCoeff[0][t] = PedCorrCoeff1[t];
}
}
else{
for(int t=0; t<48; t++){
fPedCorrCoeff[0][t] = 0.;
fPedCorrCoeff[1][t] = 0.;
}
}
}
<commit_msg>Cut and paste error corrected<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
///////////////////////////////////////////////////////////////////////////////
// //
// class for ZDC calibration -> values for pedestal subtraction //
// //
///////////////////////////////////////////////////////////////////////////////
#include "AliZDCPedestals.h"
ClassImp(AliZDCPedestals)
//________________________________________________________________
AliZDCPedestals::AliZDCPedestals():
TNamed()
{
Reset();
}
//________________________________________________________________
AliZDCPedestals::AliZDCPedestals(const char* name):
TNamed()
{
// Constructor
TString namst = "Calib_";
namst += name;
SetName(namst.Data());
SetTitle(namst.Data());
Reset();
for(Int_t i=0; i<48; i++){
fMeanPedestal[i] = 0.;
fMeanPedWidth[i] = 0.;
fOOTPedestal[i] = 0.;
fOOTPedWidth[i] = 0.;
for(Int_t j=0; j<2; j++) fPedCorrCoeff[j][i] = 0.;
}
}
//________________________________________________________________
AliZDCPedestals::AliZDCPedestals(const AliZDCPedestals& calibda) :
TNamed(calibda)
{
// Copy constructor
SetName(calibda.GetName());
SetTitle(calibda.GetName());
Reset();
for(int t=0; t<48; t++){
fMeanPedestal[t] = calibda.GetMeanPed(t);
fMeanPedWidth[t] = calibda.GetMeanPedWidth(t);
fOOTPedestal[t] = calibda.GetOOTPed(t);
fOOTPedWidth[t] = calibda.GetOOTPedWidth(t);
fPedCorrCoeff[0][t] = calibda.GetPedCorrCoeff0(t);
fPedCorrCoeff[1][t] = calibda.GetPedCorrCoeff1(t);
}
}
//________________________________________________________________
AliZDCPedestals &AliZDCPedestals::operator =(const AliZDCPedestals& calibda)
{
// assignment operator
SetName(calibda.GetName());
SetTitle(calibda.GetName());
Reset();
for(int t=0; t<48; t++){
fMeanPedestal[t] = calibda.GetMeanPed(t);
fMeanPedWidth[t] = calibda.GetMeanPedWidth(t);
fOOTPedestal[t] = calibda.GetOOTPed(t);
fOOTPedWidth[t] = calibda.GetOOTPedWidth(t);
fPedCorrCoeff[0][t] = calibda.GetPedCorrCoeff0(t);
fPedCorrCoeff[1][t] = calibda.GetPedCorrCoeff1(t);
}
return *this;
}
//________________________________________________________________
AliZDCPedestals::~AliZDCPedestals()
{
}
//________________________________________________________________
void AliZDCPedestals::Reset()
{
// Reset
memset(fMeanPedestal,0,48*sizeof(Float_t));
memset(fMeanPedWidth,0,48*sizeof(Float_t));
memset(fOOTPedestal,0,48*sizeof(Float_t));
memset(fOOTPedWidth,0,48*sizeof(Float_t));
}
//________________________________________________________________
void AliZDCPedestals::Print(Option_t *) const
{
// Printing of calibration object
printf("\n ####### In-time pedestal values (mean value, sigma) ####### \n");
for(int t=0; t<48; t++)
printf("\t ADC%d (%.1f, %.1f)\n",t,fMeanPedestal[t],fMeanPedWidth[t]);
//
printf("\n\n ####### Out-of-time pedestal values (mean value, sigma) ####### \n");
for(int t=0; t<48; t++)
printf("\t ADC-OoT%d (%.1f, %.1f)\n",t,fOOTPedestal[t],fOOTPedWidth[t]);
}
//________________________________________________________________
void AliZDCPedestals::SetMeanPed(Float_t* MeanPed)
{
if(MeanPed) for(int t=0; t<48; t++) fMeanPedestal[t] = MeanPed[t];
else for(int t=0; t<48; t++) fMeanPedestal[t] = 0.;
}
//________________________________________________________________
void AliZDCPedestals::SetMeanPedWidth(Float_t* MeanPedWidth)
{
if(MeanPedWidth) for(int t=0; t<48; t++) fMeanPedWidth[t] = MeanPedWidth[t];
else for(int t=0; t<48; t++) fMeanPedWidth[t] = 0.;
}
//________________________________________________________________
void AliZDCPedestals::SetOOTPed(Float_t* OOTPed)
{
if(OOTPed) for(int t=0; t<48; t++) fOOTPedestal[t] = OOTPed[t];
else for(int t=0; t<48; t++) fOOTPedestal[t] = 0.;
}
//________________________________________________________________
void AliZDCPedestals::SetOOTPedWidth(Float_t* OOTPedWidth)
{
if(OOTPedWidth) for(int t=0; t<48; t++) fOOTPedWidth[t] = OOTPedWidth[t];
else for(int t=0; t<48; t++) fOOTPedWidth[t] = 0.;
}
//________________________________________________________________
void AliZDCPedestals:: SetPedCorrCoeff(Float_t* PedCorrCoeff)
{
// Set coefficients for pedestal correlations
if(PedCorrCoeff){
for(Int_t j=0; j<2; j++){
for(int t=0; t<48; t++)
fPedCorrCoeff[j][t] = PedCorrCoeff[t];
}
}
else{
for(Int_t j=0; j<2; j++){
for(int t=0; t<48; t++)
fPedCorrCoeff[j][t] = 0.;
}
}
}
//________________________________________________________________
void AliZDCPedestals:: SetPedCorrCoeff(Float_t* PedCorrCoeff0, Float_t* PedCorrCoeff1)
{
// Set coefficients for pedestal correlations
if(PedCorrCoeff0 && PedCorrCoeff1){
for(int t=0; t<48; t++){
fPedCorrCoeff[0][t] = PedCorrCoeff0[t];
fPedCorrCoeff[1][t] = PedCorrCoeff1[t];
}
}
else{
for(int t=0; t<48; t++){
fPedCorrCoeff[0][t] = 0.;
fPedCorrCoeff[1][t] = 0.;
}
}
}
<|endoftext|> |
<commit_before>/******************************************************************************\
* File: lexers.cpp
* Purpose: Implementation of wxExLexers classes
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 2008-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/config.h>
#include <wx/stdpaths.h>
#include <wx/tokenzr.h>
#include <wx/stc/stc.h>
#include <wx/textfile.h>
#include <wx/extension/lexers.h>
#include <wx/extension/frd.h>
#include <wx/extension/util.h> // for wxExMatchesOneOf
wxExLexers* wxExLexers::m_Self = NULL;
wxExLexers::wxExLexers(const wxFileName& filename)
: m_FileName(filename)
{
}
const wxString wxExLexers::BuildWildCards(const wxFileName& filename) const
{
const wxString allfiles_wildcard =
_("All Files") + wxString::Format(" (%s)|%s",
wxFileSelectorDefaultWildcardStr,
wxFileSelectorDefaultWildcardStr);
wxString wildcards = allfiles_wildcard;
// Build the wildcard string using all available lexers.
for (
std::vector<wxExLexer>::const_iterator it = m_Lexers.begin();
it != m_Lexers.end();
++it)
{
if (!it->GetAssociations().empty())
{
const wxString wildcard =
it->GetScintillaLexer() +
" (" + it->GetAssociations() + ") |" +
it->GetAssociations();
if (wxExMatchesOneOf(filename, it->GetAssociations()))
{
wildcards = wildcard + "|" + wildcards;
}
else
{
wildcards = wildcards + "|" + wildcard;
}
}
}
return wildcards;
}
const wxExLexer wxExLexers::FindByFileName(const wxFileName& filename) const
{
if (!filename.IsOk())
{
return wxExLexer();
}
for (
std::vector<wxExLexer>::const_iterator it = m_Lexers.begin();
it != m_Lexers.end();
++it)
{
if (wxExMatchesOneOf(filename, it->GetAssociations()))
{
return *it;
}
}
return wxExLexer();
}
const wxExLexer wxExLexers::FindByName(
const wxString& name,
bool fail_if_not_found) const
{
for (
std::vector<wxExLexer>::const_iterator it = m_Lexers.begin();
it != m_Lexers.end();
++it)
{
if (name == it->GetScintillaLexer())
{
return *it;
}
}
if (!m_Lexers.empty() && fail_if_not_found)
{
wxFAIL;
}
return wxExLexer();
}
const wxExLexer wxExLexers::FindByText(const wxString& text) const
{
// Add automatic lexers if text starts with some special tokens.
const wxString text_lowercase = text.Lower();
if (text_lowercase.StartsWith("#") ||
// .po files that do not have comment headers, start with msgid, so set them
text_lowercase.StartsWith("msgid"))
{
return FindByName("bash", false); // don't show error
}
else if (text_lowercase.StartsWith("<html>") ||
text_lowercase.StartsWith("<?php"))
{
return FindByName("hypertext", false); // don't show error
}
else if (text_lowercase.StartsWith("<?xml"))
{
return FindByName("xml", false); // don't show error
}
// cpp files like #include <map> really do not have a .h extension (e.g. /usr/include/c++/3.3.5/map)
// so add here.
else if (text_lowercase.StartsWith("//"))
{
return FindByName("cpp", false); // don't show error
}
return wxExLexer();
}
wxExLexers* wxExLexers::Get(bool createOnDemand)
{
if (m_Self == NULL && createOnDemand)
{
m_Self = new wxExLexers(wxFileName(
#ifdef wxExUSE_PORTABLE
wxPathOnly(wxStandardPaths::Get().GetExecutablePath())
#else
wxStandardPaths::Get().GetUserDataDir()
#endif
+ wxFileName::GetPathSeparator() + "lexers.xml")
);
m_Self->Read();
}
return m_Self;
}
const wxString wxExLexers::GetLexerAssociations() const
{
wxExFindReplaceData* frd = wxExFindReplaceData::Get();
wxASSERT(frd != NULL);
wxString text;
for (
std::vector<wxExLexer>::const_iterator it = m_Lexers.begin();
it != m_Lexers.end();
++it)
{
if (!it->GetAssociations().empty())
{
if (!text.empty())
{
text += frd->GetFieldSeparator();
}
text += it->GetAssociations();
}
}
return text;
}
const wxString wxExLexers::ParseTagColourings(const wxXmlNode* node) const
{
wxString text;
wxXmlNode* child = node->GetChildren();
while (child)
{
if (child->GetName() == "colouring")
{
text +=
child->GetAttribute("no", "0") + "=" +
child->GetNodeContent().Strip(wxString::both) + wxTextFile::GetEOL();
}
else if (child->GetName() == "comment")
{
// Ignore comments.
}
else
{
wxLogError("Undefined colourings tag: %s on: %d",
child->GetName().c_str(), child->GetLineNumber());
}
child = child->GetNext();
}
return text;
}
void wxExLexers::ParseTagGlobal(const wxXmlNode* node)
{
wxXmlNode* child = node->GetChildren();
while (child)
{
if (child->GetName() == "comment")
{
// Ignore comments.
}
else if (child->GetName() == "hex")
{
m_StylesHex.push_back(
child->GetAttribute("no", "0") + "=" +
child->GetNodeContent().Strip(wxString::both));
}
else if (child->GetName() == "indicator")
{
m_Indicators.insert(std::make_pair(
atoi(child->GetAttribute("no", "0").c_str()),
atoi(child->GetNodeContent().Strip(wxString::both).c_str())));
}
else if (child->GetName() == "marker")
{
const wxExMarker marker(ParseTagMarker(
child->GetAttribute("no", "0"),
child->GetNodeContent().Strip(wxString::both)));
if (marker.GetMarkerNumber() < wxSTC_STYLE_MAX &&
marker.GetMarkerSymbol() < wxSTC_STYLE_MAX)
{
m_Markers.push_back(marker);
}
else
{
wxLogError("Illegal marker number: %d or symbol: %d on: %d",
marker.GetMarkerNumber(),
marker.GetMarkerSymbol(),
child->GetLineNumber());
}
}
else if (child->GetName() == "style")
{
m_Styles.push_back(
child->GetAttribute("no", "0") + "=" +
child->GetNodeContent().Strip(wxString::both));
}
else
{
wxLogError("Undefined global tag: %s on: %d",
child->GetName().c_str(), child->GetLineNumber());
}
child = child->GetNext();
}
}
const wxExLexer wxExLexers::ParseTagLexer(const wxXmlNode* node) const
{
wxExLexer lexer;
lexer.m_ScintillaLexer = node->GetAttribute("name", "");
lexer.m_Associations = node->GetAttribute("extensions", "");
wxXmlNode *child = node->GetChildren();
while (child)
{
if (child->GetName() == "colourings")
{
lexer.m_Colourings = ParseTagColourings(child);
}
else if (child->GetName() == "keywords")
{
if (!lexer.SetKeywords(child->GetNodeContent().Strip(wxString::both)))
{
wxLogError("Keywords could not be set on: %d", child->GetLineNumber());
}
}
else if (child->GetName() == "properties")
{
lexer.m_Properties = ParseTagProperties(child);
}
else if (child->GetName() == "comments")
{
lexer.m_CommentBegin = child->GetAttribute("begin1", "");
lexer.m_CommentEnd = child->GetAttribute("end1", "");
lexer.m_CommentBegin2 = child->GetAttribute("begin2", "");
lexer.m_CommentEnd2 = child->GetAttribute("end2", "");
}
else if (child->GetName() == "comment")
{
// Ignore comments.
}
else
{
wxLogError("Undefined lexer tag: %s on: %d",
child->GetName().c_str(), child->GetLineNumber());
}
child = child->GetNext();
}
return lexer;
}
const wxExMarker wxExLexers::ParseTagMarker(
const wxString& number,
const wxString& props) const
{
wxStringTokenizer prop_fields(props, ",");
const wxString symbol = prop_fields.GetNextToken();
wxColour foreground;
wxColour background;
if (prop_fields.HasMoreTokens())
{
foreground = prop_fields.GetNextToken();
if (prop_fields.HasMoreTokens())
{
background = prop_fields.GetNextToken();
}
}
const int no = atoi(number.c_str());
const int symbol_no = atoi(symbol.c_str());
if (no <= wxSTC_MARKER_MAX && symbol_no <= wxSTC_MARKER_MAX)
{
return wxExMarker(no, symbol_no, foreground, background);
}
else
{
wxLogError("Illegal marker number: %d or symbol: %d", no, symbol_no);
return wxExMarker(0, 0, foreground, background);
}
}
const wxString wxExLexers::ParseTagProperties(const wxXmlNode* node) const
{
wxString text;
wxXmlNode *child = node->GetChildren();
while (child)
{
if (child->GetName() == "property")
{
text +=
child->GetAttribute("name", "0") + "=" +
child->GetNodeContent().Strip(wxString::both) + wxTextFile::GetEOL();
}
else if (child->GetName() == "comment")
{
// Ignore comments.
}
else
{
wxLogError("Undefined properties tag: %s on %d",
child->GetName().c_str(), child->GetLineNumber());
}
child = child->GetNext();
}
return text;
}
void wxExLexers::Read()
{
// This test is to prevent showing an error if the lexers file does not exist,
// as this is not required.
if (!m_FileName.FileExists())
{
return;
}
wxXmlDocument doc;
if (!doc.Load(m_FileName.GetFullPath()))
{
return;
}
// Initialize members.
m_Indicators.clear();
m_Lexers.clear();
m_Markers.clear();
m_Styles.clear();
m_StylesHex.clear();
wxXmlNode* child = doc.GetRoot()->GetChildren();
while (child)
{
if (child->GetName() == "global")
{
ParseTagGlobal(child);
}
else if (child->GetName() == "lexer")
{
const wxExLexer& lexer = ParseTagLexer(child);
if (!lexer.GetScintillaLexer().empty())
{
if (lexer.GetScintillaLexer() == "hypertext")
{
// As our lexers.xml files cannot use xml comments,
// add them here.
wxExLexer l(lexer);
l.m_CommentBegin = "<!--";
l.m_CommentEnd = "-->";
m_Lexers.push_back(l);
}
else
{
m_Lexers.push_back(lexer);
}
}
}
child = child->GetNext();
}
// Initialize the config if it is constructed.
wxConfigBase* config = wxConfigBase::Get(false);
if (config != NULL)
{
if (!wxConfigBase::Get()->Exists(_("In files")))
{
wxConfigBase::Get()->Write(_("In files"), GetLexerAssociations());
}
if (!wxConfigBase::Get()->Exists(_("Add what")))
{
wxConfigBase::Get()->Write(_("Add what"), GetLexerAssociations());
}
}
}
wxExLexers* wxExLexers::Set(wxExLexers* lexers)
{
wxExLexers* old = m_Self;
m_Self = lexers;
return old;
}
bool wxExLexers::ShowDialog(
wxWindow* parent,
wxExLexer& lexer,
const wxString& caption) const
{
wxArrayString aChoices;
int choice = -1;
int index = 0;
for (
std::vector<wxExLexer>::const_iterator it = m_Lexers.begin();
it != m_Lexers.end();
++it)
{
aChoices.Add(it->GetScintillaLexer());
if (lexer.GetScintillaLexer() == it->GetScintillaLexer())
{
choice = index;
}
index++;
}
// Add the <none> lexer (index is already incremented).
const wxString no_lexer = _("<none>");
aChoices.Add(no_lexer);
// And set the choice if we do not have a lexer.
if (lexer.GetScintillaLexer().empty())
{
choice = index;
}
wxSingleChoiceDialog dlg(parent, _("Input") + ":", caption, aChoices);
if (choice != -1)
{
dlg.SetSelection(choice);
}
if (dlg.ShowModal() == wxID_CANCEL)
{
return false;
}
const wxString sel = dlg.GetStringSelection();
if (sel == no_lexer)
{
lexer = wxExLexer();
}
else
{
lexer = FindByName(sel);
}
return true;
}
<commit_msg>no need to test for null config<commit_after>/******************************************************************************\
* File: lexers.cpp
* Purpose: Implementation of wxExLexers classes
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 2008-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/config.h>
#include <wx/stdpaths.h>
#include <wx/tokenzr.h>
#include <wx/stc/stc.h>
#include <wx/textfile.h>
#include <wx/extension/lexers.h>
#include <wx/extension/frd.h>
#include <wx/extension/util.h> // for wxExMatchesOneOf
wxExLexers* wxExLexers::m_Self = NULL;
wxExLexers::wxExLexers(const wxFileName& filename)
: m_FileName(filename)
{
}
const wxString wxExLexers::BuildWildCards(const wxFileName& filename) const
{
const wxString allfiles_wildcard =
_("All Files") + wxString::Format(" (%s)|%s",
wxFileSelectorDefaultWildcardStr,
wxFileSelectorDefaultWildcardStr);
wxString wildcards = allfiles_wildcard;
// Build the wildcard string using all available lexers.
for (
std::vector<wxExLexer>::const_iterator it = m_Lexers.begin();
it != m_Lexers.end();
++it)
{
if (!it->GetAssociations().empty())
{
const wxString wildcard =
it->GetScintillaLexer() +
" (" + it->GetAssociations() + ") |" +
it->GetAssociations();
if (wxExMatchesOneOf(filename, it->GetAssociations()))
{
wildcards = wildcard + "|" + wildcards;
}
else
{
wildcards = wildcards + "|" + wildcard;
}
}
}
return wildcards;
}
const wxExLexer wxExLexers::FindByFileName(const wxFileName& filename) const
{
if (!filename.IsOk())
{
return wxExLexer();
}
for (
std::vector<wxExLexer>::const_iterator it = m_Lexers.begin();
it != m_Lexers.end();
++it)
{
if (wxExMatchesOneOf(filename, it->GetAssociations()))
{
return *it;
}
}
return wxExLexer();
}
const wxExLexer wxExLexers::FindByName(
const wxString& name,
bool fail_if_not_found) const
{
for (
std::vector<wxExLexer>::const_iterator it = m_Lexers.begin();
it != m_Lexers.end();
++it)
{
if (name == it->GetScintillaLexer())
{
return *it;
}
}
if (!m_Lexers.empty() && fail_if_not_found)
{
wxFAIL;
}
return wxExLexer();
}
const wxExLexer wxExLexers::FindByText(const wxString& text) const
{
// Add automatic lexers if text starts with some special tokens.
const wxString text_lowercase = text.Lower();
if (text_lowercase.StartsWith("#") ||
// .po files that do not have comment headers, start with msgid, so set them
text_lowercase.StartsWith("msgid"))
{
return FindByName("bash", false); // don't show error
}
else if (text_lowercase.StartsWith("<html>") ||
text_lowercase.StartsWith("<?php"))
{
return FindByName("hypertext", false); // don't show error
}
else if (text_lowercase.StartsWith("<?xml"))
{
return FindByName("xml", false); // don't show error
}
// cpp files like #include <map> really do not have a .h extension (e.g. /usr/include/c++/3.3.5/map)
// so add here.
else if (text_lowercase.StartsWith("//"))
{
return FindByName("cpp", false); // don't show error
}
return wxExLexer();
}
wxExLexers* wxExLexers::Get(bool createOnDemand)
{
if (m_Self == NULL && createOnDemand)
{
m_Self = new wxExLexers(wxFileName(
#ifdef wxExUSE_PORTABLE
wxPathOnly(wxStandardPaths::Get().GetExecutablePath())
#else
wxStandardPaths::Get().GetUserDataDir()
#endif
+ wxFileName::GetPathSeparator() + "lexers.xml")
);
m_Self->Read();
}
return m_Self;
}
const wxString wxExLexers::GetLexerAssociations() const
{
wxExFindReplaceData* frd = wxExFindReplaceData::Get();
wxASSERT(frd != NULL);
wxString text;
for (
std::vector<wxExLexer>::const_iterator it = m_Lexers.begin();
it != m_Lexers.end();
++it)
{
if (!it->GetAssociations().empty())
{
if (!text.empty())
{
text += frd->GetFieldSeparator();
}
text += it->GetAssociations();
}
}
return text;
}
const wxString wxExLexers::ParseTagColourings(const wxXmlNode* node) const
{
wxString text;
wxXmlNode* child = node->GetChildren();
while (child)
{
if (child->GetName() == "colouring")
{
text +=
child->GetAttribute("no", "0") + "=" +
child->GetNodeContent().Strip(wxString::both) + wxTextFile::GetEOL();
}
else if (child->GetName() == "comment")
{
// Ignore comments.
}
else
{
wxLogError("Undefined colourings tag: %s on: %d",
child->GetName().c_str(), child->GetLineNumber());
}
child = child->GetNext();
}
return text;
}
void wxExLexers::ParseTagGlobal(const wxXmlNode* node)
{
wxXmlNode* child = node->GetChildren();
while (child)
{
if (child->GetName() == "comment")
{
// Ignore comments.
}
else if (child->GetName() == "hex")
{
m_StylesHex.push_back(
child->GetAttribute("no", "0") + "=" +
child->GetNodeContent().Strip(wxString::both));
}
else if (child->GetName() == "indicator")
{
m_Indicators.insert(std::make_pair(
atoi(child->GetAttribute("no", "0").c_str()),
atoi(child->GetNodeContent().Strip(wxString::both).c_str())));
}
else if (child->GetName() == "marker")
{
const wxExMarker marker(ParseTagMarker(
child->GetAttribute("no", "0"),
child->GetNodeContent().Strip(wxString::both)));
if (marker.GetMarkerNumber() < wxSTC_STYLE_MAX &&
marker.GetMarkerSymbol() < wxSTC_STYLE_MAX)
{
m_Markers.push_back(marker);
}
else
{
wxLogError("Illegal marker number: %d or symbol: %d on: %d",
marker.GetMarkerNumber(),
marker.GetMarkerSymbol(),
child->GetLineNumber());
}
}
else if (child->GetName() == "style")
{
m_Styles.push_back(
child->GetAttribute("no", "0") + "=" +
child->GetNodeContent().Strip(wxString::both));
}
else
{
wxLogError("Undefined global tag: %s on: %d",
child->GetName().c_str(), child->GetLineNumber());
}
child = child->GetNext();
}
}
const wxExLexer wxExLexers::ParseTagLexer(const wxXmlNode* node) const
{
wxExLexer lexer;
lexer.m_ScintillaLexer = node->GetAttribute("name", "");
lexer.m_Associations = node->GetAttribute("extensions", "");
wxXmlNode *child = node->GetChildren();
while (child)
{
if (child->GetName() == "colourings")
{
lexer.m_Colourings = ParseTagColourings(child);
}
else if (child->GetName() == "keywords")
{
if (!lexer.SetKeywords(child->GetNodeContent().Strip(wxString::both)))
{
wxLogError("Keywords could not be set on: %d", child->GetLineNumber());
}
}
else if (child->GetName() == "properties")
{
lexer.m_Properties = ParseTagProperties(child);
}
else if (child->GetName() == "comments")
{
lexer.m_CommentBegin = child->GetAttribute("begin1", "");
lexer.m_CommentEnd = child->GetAttribute("end1", "");
lexer.m_CommentBegin2 = child->GetAttribute("begin2", "");
lexer.m_CommentEnd2 = child->GetAttribute("end2", "");
}
else if (child->GetName() == "comment")
{
// Ignore comments.
}
else
{
wxLogError("Undefined lexer tag: %s on: %d",
child->GetName().c_str(), child->GetLineNumber());
}
child = child->GetNext();
}
return lexer;
}
const wxExMarker wxExLexers::ParseTagMarker(
const wxString& number,
const wxString& props) const
{
wxStringTokenizer prop_fields(props, ",");
const wxString symbol = prop_fields.GetNextToken();
wxColour foreground;
wxColour background;
if (prop_fields.HasMoreTokens())
{
foreground = prop_fields.GetNextToken();
if (prop_fields.HasMoreTokens())
{
background = prop_fields.GetNextToken();
}
}
const int no = atoi(number.c_str());
const int symbol_no = atoi(symbol.c_str());
if (no <= wxSTC_MARKER_MAX && symbol_no <= wxSTC_MARKER_MAX)
{
return wxExMarker(no, symbol_no, foreground, background);
}
else
{
wxLogError("Illegal marker number: %d or symbol: %d", no, symbol_no);
return wxExMarker(0, 0, foreground, background);
}
}
const wxString wxExLexers::ParseTagProperties(const wxXmlNode* node) const
{
wxString text;
wxXmlNode *child = node->GetChildren();
while (child)
{
if (child->GetName() == "property")
{
text +=
child->GetAttribute("name", "0") + "=" +
child->GetNodeContent().Strip(wxString::both) + wxTextFile::GetEOL();
}
else if (child->GetName() == "comment")
{
// Ignore comments.
}
else
{
wxLogError("Undefined properties tag: %s on %d",
child->GetName().c_str(), child->GetLineNumber());
}
child = child->GetNext();
}
return text;
}
void wxExLexers::Read()
{
// This test is to prevent showing an error if the lexers file does not exist,
// as this is not required.
if (!m_FileName.FileExists())
{
return;
}
wxXmlDocument doc;
if (!doc.Load(m_FileName.GetFullPath()))
{
return;
}
// Initialize members.
m_Indicators.clear();
m_Lexers.clear();
m_Markers.clear();
m_Styles.clear();
m_StylesHex.clear();
wxXmlNode* child = doc.GetRoot()->GetChildren();
while (child)
{
if (child->GetName() == "global")
{
ParseTagGlobal(child);
}
else if (child->GetName() == "lexer")
{
const wxExLexer& lexer = ParseTagLexer(child);
if (!lexer.GetScintillaLexer().empty())
{
if (lexer.GetScintillaLexer() == "hypertext")
{
// As our lexers.xml files cannot use xml comments,
// add them here.
wxExLexer l(lexer);
l.m_CommentBegin = "<!--";
l.m_CommentEnd = "-->";
m_Lexers.push_back(l);
}
else
{
m_Lexers.push_back(lexer);
}
}
}
child = child->GetNext();
}
if (!wxConfigBase::Get()->Exists(_("In files")))
{
wxConfigBase::Get()->Write(_("In files"), GetLexerAssociations());
}
if (!wxConfigBase::Get()->Exists(_("Add what")))
{
wxConfigBase::Get()->Write(_("Add what"), GetLexerAssociations());
}
}
wxExLexers* wxExLexers::Set(wxExLexers* lexers)
{
wxExLexers* old = m_Self;
m_Self = lexers;
return old;
}
bool wxExLexers::ShowDialog(
wxWindow* parent,
wxExLexer& lexer,
const wxString& caption) const
{
wxArrayString aChoices;
int choice = -1;
int index = 0;
for (
std::vector<wxExLexer>::const_iterator it = m_Lexers.begin();
it != m_Lexers.end();
++it)
{
aChoices.Add(it->GetScintillaLexer());
if (lexer.GetScintillaLexer() == it->GetScintillaLexer())
{
choice = index;
}
index++;
}
// Add the <none> lexer (index is already incremented).
const wxString no_lexer = _("<none>");
aChoices.Add(no_lexer);
// And set the choice if we do not have a lexer.
if (lexer.GetScintillaLexer().empty())
{
choice = index;
}
wxSingleChoiceDialog dlg(parent, _("Input") + ":", caption, aChoices);
if (choice != -1)
{
dlg.SetSelection(choice);
}
if (dlg.ShowModal() == wxID_CANCEL)
{
return false;
}
const wxString sel = dlg.GetStringSelection();
if (sel == no_lexer)
{
lexer = wxExLexer();
}
else
{
lexer = FindByName(sel);
}
return true;
}
<|endoftext|> |
<commit_before>/******************************************************************************\
* File: lexers.cpp
* Purpose: Implementation of wxExLexers classes
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 2008-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/config.h>
#include <wx/tokenzr.h>
#include <wx/stc/stc.h>
#include <wx/textfile.h>
#include <wx/extension/lexers.h>
#include <wx/extension/util.h> // for wxExMatchesOneOf
wxExLexers::wxExLexers(const wxFileName& filename)
: m_FileName(filename)
{
}
const wxString wxExLexers::BuildWildCards(const wxFileName& filename) const
{
const wxString allfiles_wildcard =
_("All Files") + wxString::Format(" (%s)|%s",
wxFileSelectorDefaultWildcardStr,
wxFileSelectorDefaultWildcardStr);
wxString wildcards = allfiles_wildcard;
// Build the wildcard string using all available lexers.
for (
std::vector<wxExLexer>::const_iterator it = m_Lexers.begin();
it != m_Lexers.end();
++it)
{
if (!it->GetAssociations().empty())
{
const wxString wildcard =
it->GetScintillaLexer() +
" (" + it->GetAssociations() + ") |" +
it->GetAssociations();
if (wxExMatchesOneOf(filename, it->GetAssociations()))
{
wildcards = wildcard + "|" + wildcards;
}
else
{
wildcards = wildcards + "|" + wildcard;
}
}
}
return wildcards;
}
const wxExLexer wxExLexers::FindByFileName(const wxFileName& filename) const
{
if (!filename.IsOk())
{
return wxExLexer();
}
for (
std::vector<wxExLexer>::const_iterator it = m_Lexers.begin();
it != m_Lexers.end();
++it)
{
if (wxExMatchesOneOf(filename, it->GetAssociations()))
{
return *it;
}
}
return wxExLexer();
}
const wxExLexer wxExLexers::FindByName(
const wxString& name,
bool fail_if_not_found) const
{
for (
std::vector<wxExLexer>::const_iterator it = m_Lexers.begin();
it != m_Lexers.end();
++it)
{
if (name == it->GetScintillaLexer())
{
return *it;
}
}
if (!m_Lexers.empty() && fail_if_not_found)
{
wxFAIL;
}
return wxExLexer();
}
const wxExLexer wxExLexers::FindByText(const wxString& text) const
{
// Add automatic lexers if text starts with some special tokens.
const wxString text_lowercase = text.Lower();
if (text_lowercase.StartsWith("#") ||
// .po files that do not have comment headers, start with msgid, so set them
text_lowercase.StartsWith("msgid"))
{
return FindByName("bash", false); // don't show error
}
else if (text_lowercase.StartsWith("<html>") ||
text_lowercase.StartsWith("<?php"))
{
return FindByName("hypertext", false); // don't show error
}
else if (text_lowercase.StartsWith("<?xml"))
{
return FindByName("xml", false); // don't show error
}
// cpp files like #include <map> really do not have a .h extension (e.g. /usr/include/c++/3.3.5/map)
// so add here.
else if (text_lowercase.StartsWith("//"))
{
return FindByName("cpp", false); // don't show error
}
return wxExLexer();
}
const wxString wxExLexers::GetLexerAssociations() const
{
wxString text;
for (
std::vector<wxExLexer>::const_iterator it = m_Lexers.begin();
it != m_Lexers.end();
++it)
{
if (!it->GetAssociations().empty())
{
if (!text.empty())
{
text += ",";
}
text += it->GetAssociations();
}
}
return text;
}
const wxString wxExLexers::ParseTagColourings(const wxXmlNode* node) const
{
wxString text;
wxXmlNode* child = node->GetChildren();
while (child)
{
if (child->GetName() == "colouring")
{
text +=
child->GetAttribute("no", "0") + "=" +
child->GetNodeContent().Strip(wxString::both) + wxTextFile::GetEOL();
}
else if (child->GetName() == "comment")
{
// Ignore comments.
}
else
{
wxLogError("Undefined colourings tag: %s on: %d",
child->GetName().c_str(), child->GetLineNumber());
}
child = child->GetNext();
}
return text;
}
void wxExLexers::ParseTagGlobal(const wxXmlNode* node)
{
wxXmlNode* child = node->GetChildren();
while (child)
{
if (child->GetName() == "comment")
{
// Ignore comments.
}
else if (child->GetName() == "hex")
{
m_StylesHex.push_back(
child->GetAttribute("no", "0") + "=" +
child->GetNodeContent().Strip(wxString::both));
}
else if (child->GetName() == "indicator")
{
m_Indicators.insert(std::make_pair(
atoi(child->GetAttribute("no", "0").c_str()),
atoi(child->GetNodeContent().Strip(wxString::both).c_str())));
}
else if (child->GetName() == "marker")
{
const wxExMarker marker(ParseTagMarker(
child->GetAttribute("no", "0"),
child->GetNodeContent().Strip(wxString::both)));
if (marker.GetMarkerNumber() < wxSTC_STYLE_MAX &&
marker.GetMarkerSymbol() < wxSTC_STYLE_MAX)
{
m_Markers.push_back(marker);
}
else
{
wxLogError("Illegal marker number: %d or symbol: %d on: %d",
marker.GetMarkerNumber(),
marker.GetMarkerSymbol(),
child->GetLineNumber());
}
}
else if (child->GetName() == "style")
{
m_Styles.push_back(
child->GetAttribute("no", "0") + "=" +
child->GetNodeContent().Strip(wxString::both));
}
else
{
wxLogError("Undefined global tag: %s on: %d",
child->GetName().c_str(), child->GetLineNumber());
}
child = child->GetNext();
}
}
const wxExLexer wxExLexers::ParseTagLexer(const wxXmlNode* node) const
{
wxExLexer lexer;
lexer.m_ScintillaLexer = node->GetAttribute("name", "");
lexer.m_Associations = node->GetAttribute("extensions", "");
wxXmlNode *child = node->GetChildren();
while (child)
{
if (child->GetName() == "colourings")
{
lexer.m_Colourings = ParseTagColourings(child);
}
else if (child->GetName() == "keywords")
{
if (!lexer.SetKeywords(child->GetNodeContent().Strip(wxString::both)))
{
wxLogError("Keywords could not be set on: %d", child->GetLineNumber());
}
}
else if (child->GetName() == "properties")
{
lexer.m_Properties = ParseTagProperties(child);
}
else if (child->GetName() == "comments")
{
lexer.m_CommentBegin = child->GetAttribute("begin1", "");
lexer.m_CommentEnd = child->GetAttribute("end1", "");
lexer.m_CommentBegin2 = child->GetAttribute("begin2", "");
lexer.m_CommentEnd2 = child->GetAttribute("end2", "");
}
else if (child->GetName() == "comment")
{
// Ignore comments.
}
else
{
wxLogError("Undefined lexer tag: %s on: %d",
child->GetName().c_str(), child->GetLineNumber());
}
child = child->GetNext();
}
return lexer;
}
const wxExMarker wxExLexers::ParseTagMarker(
const wxString& number,
const wxString& props) const
{
wxStringTokenizer prop_fields(props, ",");
const wxString symbol = prop_fields.GetNextToken();
wxColour foreground;
wxColour background;
if (prop_fields.HasMoreTokens())
{
foreground = prop_fields.GetNextToken();
if (prop_fields.HasMoreTokens())
{
background = prop_fields.GetNextToken();
}
}
const int no = atoi(number.c_str());
const int symbol_no = atoi(symbol.c_str());
if (no <= wxSTC_MARKER_MAX && symbol_no <= wxSTC_MARKER_MAX)
{
return wxExMarker(no, symbol_no, foreground, background);
}
else
{
wxLogError("Illegal marker number: %d or symbol: %d", no, symbol_no);
return wxExMarker(0, 0, foreground, background);
}
}
const wxString wxExLexers::ParseTagProperties(const wxXmlNode* node) const
{
wxString text;
wxXmlNode *child = node->GetChildren();
while (child)
{
if (child->GetName() == "property")
{
text +=
child->GetAttribute("name", "0") + "=" +
child->GetNodeContent().Strip(wxString::both) + wxTextFile::GetEOL();
}
else if (child->GetName() == "comment")
{
// Ignore comments.
}
else
{
wxLogError("Undefined properties tag: %s on %d",
child->GetName().c_str(), child->GetLineNumber());
}
child = child->GetNext();
}
return text;
}
bool wxExLexers::Read()
{
wxXmlDocument doc;
// This test is to prevent showing an error if the lexers files does not exist,
// as this is not required.
if (!m_FileName.FileExists())
{
return false;
}
else if (!doc.Load(m_FileName.GetFullPath()))
{
return false;
}
// Initialize members.
m_Indicators.clear();
m_Lexers.clear();
m_Markers.clear();
m_Styles.clear();
m_StylesHex.clear();
wxXmlNode* child = doc.GetRoot()->GetChildren();
while (child)
{
if (child->GetName() == "global")
{
ParseTagGlobal(child);
}
else if (child->GetName() == "lexer")
{
const wxExLexer& lexer = ParseTagLexer(child);
if (!lexer.GetScintillaLexer().empty())
{
if (lexer.GetScintillaLexer() == "hypertext")
{
// As our lexers.xml files cannot use xml comments,
// add them here.
wxExLexer l(lexer);
l.m_CommentBegin = "<!--";
l.m_CommentEnd = "-->";
m_Lexers.push_back(l);
}
else
{
m_Lexers.push_back(lexer);
}
}
}
child = child->GetNext();
}
// Initialize the config.
if (!wxConfigBase::Get()->Exists(_("In files")))
{
wxConfigBase::Get()->Write(_("In files"), GetLexerAssociations());
}
if (!wxConfigBase::Get()->Exists(_("Add what")))
{
wxConfigBase::Get()->Read(_("Add what"), GetLexerAssociations());
}
return true;
}
bool wxExLexers::ShowDialog(
wxWindow* parent,
wxExLexer& lexer,
const wxString& caption) const
{
wxArrayString aChoices;
int choice = -1;
int index = 0;
for (
std::vector<wxExLexer>::const_iterator it = m_Lexers.begin();
it != m_Lexers.end();
++it)
{
aChoices.Add(it->GetScintillaLexer());
if (lexer.GetScintillaLexer() == it->GetScintillaLexer())
{
choice = index;
}
index++;
}
// Add the <none> lexer (index is already incremented).
const wxString no_lexer = _("<none>");
aChoices.Add(no_lexer);
// And set the choice if we do not have a lexer.
if (lexer.GetScintillaLexer().empty())
{
choice = index;
}
wxSingleChoiceDialog dlg(parent, _("Input") + ":", caption, aChoices);
if (choice != -1)
{
dlg.SetSelection(choice);
}
if (dlg.ShowModal() == wxID_CANCEL)
{
return false;
}
const wxString sel = dlg.GetStringSelection();
if (sel == no_lexer)
{
lexer = wxExLexer();
}
else
{
lexer = FindByName(sel);
}
return true;
}
<commit_msg>a small fix<commit_after>/******************************************************************************\
* File: lexers.cpp
* Purpose: Implementation of wxExLexers classes
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 2008-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/config.h>
#include <wx/tokenzr.h>
#include <wx/stc/stc.h>
#include <wx/textfile.h>
#include <wx/extension/lexers.h>
#include <wx/extension/util.h> // for wxExMatchesOneOf
wxExLexers::wxExLexers(const wxFileName& filename)
: m_FileName(filename)
{
}
const wxString wxExLexers::BuildWildCards(const wxFileName& filename) const
{
const wxString allfiles_wildcard =
_("All Files") + wxString::Format(" (%s)|%s",
wxFileSelectorDefaultWildcardStr,
wxFileSelectorDefaultWildcardStr);
wxString wildcards = allfiles_wildcard;
// Build the wildcard string using all available lexers.
for (
std::vector<wxExLexer>::const_iterator it = m_Lexers.begin();
it != m_Lexers.end();
++it)
{
if (!it->GetAssociations().empty())
{
const wxString wildcard =
it->GetScintillaLexer() +
" (" + it->GetAssociations() + ") |" +
it->GetAssociations();
if (wxExMatchesOneOf(filename, it->GetAssociations()))
{
wildcards = wildcard + "|" + wildcards;
}
else
{
wildcards = wildcards + "|" + wildcard;
}
}
}
return wildcards;
}
const wxExLexer wxExLexers::FindByFileName(const wxFileName& filename) const
{
if (!filename.IsOk())
{
return wxExLexer();
}
for (
std::vector<wxExLexer>::const_iterator it = m_Lexers.begin();
it != m_Lexers.end();
++it)
{
if (wxExMatchesOneOf(filename, it->GetAssociations()))
{
return *it;
}
}
return wxExLexer();
}
const wxExLexer wxExLexers::FindByName(
const wxString& name,
bool fail_if_not_found) const
{
for (
std::vector<wxExLexer>::const_iterator it = m_Lexers.begin();
it != m_Lexers.end();
++it)
{
if (name == it->GetScintillaLexer())
{
return *it;
}
}
if (!m_Lexers.empty() && fail_if_not_found)
{
wxFAIL;
}
return wxExLexer();
}
const wxExLexer wxExLexers::FindByText(const wxString& text) const
{
// Add automatic lexers if text starts with some special tokens.
const wxString text_lowercase = text.Lower();
if (text_lowercase.StartsWith("#") ||
// .po files that do not have comment headers, start with msgid, so set them
text_lowercase.StartsWith("msgid"))
{
return FindByName("bash", false); // don't show error
}
else if (text_lowercase.StartsWith("<html>") ||
text_lowercase.StartsWith("<?php"))
{
return FindByName("hypertext", false); // don't show error
}
else if (text_lowercase.StartsWith("<?xml"))
{
return FindByName("xml", false); // don't show error
}
// cpp files like #include <map> really do not have a .h extension (e.g. /usr/include/c++/3.3.5/map)
// so add here.
else if (text_lowercase.StartsWith("//"))
{
return FindByName("cpp", false); // don't show error
}
return wxExLexer();
}
const wxString wxExLexers::GetLexerAssociations() const
{
wxString text;
for (
std::vector<wxExLexer>::const_iterator it = m_Lexers.begin();
it != m_Lexers.end();
++it)
{
if (!it->GetAssociations().empty())
{
if (!text.empty())
{
text += ",";
}
text += it->GetAssociations();
}
}
return text;
}
const wxString wxExLexers::ParseTagColourings(const wxXmlNode* node) const
{
wxString text;
wxXmlNode* child = node->GetChildren();
while (child)
{
if (child->GetName() == "colouring")
{
text +=
child->GetAttribute("no", "0") + "=" +
child->GetNodeContent().Strip(wxString::both) + wxTextFile::GetEOL();
}
else if (child->GetName() == "comment")
{
// Ignore comments.
}
else
{
wxLogError("Undefined colourings tag: %s on: %d",
child->GetName().c_str(), child->GetLineNumber());
}
child = child->GetNext();
}
return text;
}
void wxExLexers::ParseTagGlobal(const wxXmlNode* node)
{
wxXmlNode* child = node->GetChildren();
while (child)
{
if (child->GetName() == "comment")
{
// Ignore comments.
}
else if (child->GetName() == "hex")
{
m_StylesHex.push_back(
child->GetAttribute("no", "0") + "=" +
child->GetNodeContent().Strip(wxString::both));
}
else if (child->GetName() == "indicator")
{
m_Indicators.insert(std::make_pair(
atoi(child->GetAttribute("no", "0").c_str()),
atoi(child->GetNodeContent().Strip(wxString::both).c_str())));
}
else if (child->GetName() == "marker")
{
const wxExMarker marker(ParseTagMarker(
child->GetAttribute("no", "0"),
child->GetNodeContent().Strip(wxString::both)));
if (marker.GetMarkerNumber() < wxSTC_STYLE_MAX &&
marker.GetMarkerSymbol() < wxSTC_STYLE_MAX)
{
m_Markers.push_back(marker);
}
else
{
wxLogError("Illegal marker number: %d or symbol: %d on: %d",
marker.GetMarkerNumber(),
marker.GetMarkerSymbol(),
child->GetLineNumber());
}
}
else if (child->GetName() == "style")
{
m_Styles.push_back(
child->GetAttribute("no", "0") + "=" +
child->GetNodeContent().Strip(wxString::both));
}
else
{
wxLogError("Undefined global tag: %s on: %d",
child->GetName().c_str(), child->GetLineNumber());
}
child = child->GetNext();
}
}
const wxExLexer wxExLexers::ParseTagLexer(const wxXmlNode* node) const
{
wxExLexer lexer;
lexer.m_ScintillaLexer = node->GetAttribute("name", "");
lexer.m_Associations = node->GetAttribute("extensions", "");
wxXmlNode *child = node->GetChildren();
while (child)
{
if (child->GetName() == "colourings")
{
lexer.m_Colourings = ParseTagColourings(child);
}
else if (child->GetName() == "keywords")
{
if (!lexer.SetKeywords(child->GetNodeContent().Strip(wxString::both)))
{
wxLogError("Keywords could not be set on: %d", child->GetLineNumber());
}
}
else if (child->GetName() == "properties")
{
lexer.m_Properties = ParseTagProperties(child);
}
else if (child->GetName() == "comments")
{
lexer.m_CommentBegin = child->GetAttribute("begin1", "");
lexer.m_CommentEnd = child->GetAttribute("end1", "");
lexer.m_CommentBegin2 = child->GetAttribute("begin2", "");
lexer.m_CommentEnd2 = child->GetAttribute("end2", "");
}
else if (child->GetName() == "comment")
{
// Ignore comments.
}
else
{
wxLogError("Undefined lexer tag: %s on: %d",
child->GetName().c_str(), child->GetLineNumber());
}
child = child->GetNext();
}
return lexer;
}
const wxExMarker wxExLexers::ParseTagMarker(
const wxString& number,
const wxString& props) const
{
wxStringTokenizer prop_fields(props, ",");
const wxString symbol = prop_fields.GetNextToken();
wxColour foreground;
wxColour background;
if (prop_fields.HasMoreTokens())
{
foreground = prop_fields.GetNextToken();
if (prop_fields.HasMoreTokens())
{
background = prop_fields.GetNextToken();
}
}
const int no = atoi(number.c_str());
const int symbol_no = atoi(symbol.c_str());
if (no <= wxSTC_MARKER_MAX && symbol_no <= wxSTC_MARKER_MAX)
{
return wxExMarker(no, symbol_no, foreground, background);
}
else
{
wxLogError("Illegal marker number: %d or symbol: %d", no, symbol_no);
return wxExMarker(0, 0, foreground, background);
}
}
const wxString wxExLexers::ParseTagProperties(const wxXmlNode* node) const
{
wxString text;
wxXmlNode *child = node->GetChildren();
while (child)
{
if (child->GetName() == "property")
{
text +=
child->GetAttribute("name", "0") + "=" +
child->GetNodeContent().Strip(wxString::both) + wxTextFile::GetEOL();
}
else if (child->GetName() == "comment")
{
// Ignore comments.
}
else
{
wxLogError("Undefined properties tag: %s on %d",
child->GetName().c_str(), child->GetLineNumber());
}
child = child->GetNext();
}
return text;
}
bool wxExLexers::Read()
{
// This test is to prevent showing an error if the lexers files does not exist,
// as this is not required.
if (!m_FileName.FileExists())
{
return false;
}
wxXmlDocument doc;
if (!doc.Load(m_FileName.GetFullPath()))
{
return false;
}
// Initialize members.
m_Indicators.clear();
m_Lexers.clear();
m_Markers.clear();
m_Styles.clear();
m_StylesHex.clear();
wxXmlNode* child = doc.GetRoot()->GetChildren();
while (child)
{
if (child->GetName() == "global")
{
ParseTagGlobal(child);
}
else if (child->GetName() == "lexer")
{
const wxExLexer& lexer = ParseTagLexer(child);
if (!lexer.GetScintillaLexer().empty())
{
if (lexer.GetScintillaLexer() == "hypertext")
{
// As our lexers.xml files cannot use xml comments,
// add them here.
wxExLexer l(lexer);
l.m_CommentBegin = "<!--";
l.m_CommentEnd = "-->";
m_Lexers.push_back(l);
}
else
{
m_Lexers.push_back(lexer);
}
}
}
child = child->GetNext();
}
// Initialize the config.
if (!wxConfigBase::Get()->Exists(_("In files")))
{
wxConfigBase::Get()->Write(_("In files"), GetLexerAssociations());
}
if (!wxConfigBase::Get()->Exists(_("Add what")))
{
wxConfigBase::Get()->Read(_("Add what"), GetLexerAssociations());
}
return true;
}
bool wxExLexers::ShowDialog(
wxWindow* parent,
wxExLexer& lexer,
const wxString& caption) const
{
wxArrayString aChoices;
int choice = -1;
int index = 0;
for (
std::vector<wxExLexer>::const_iterator it = m_Lexers.begin();
it != m_Lexers.end();
++it)
{
aChoices.Add(it->GetScintillaLexer());
if (lexer.GetScintillaLexer() == it->GetScintillaLexer())
{
choice = index;
}
index++;
}
// Add the <none> lexer (index is already incremented).
const wxString no_lexer = _("<none>");
aChoices.Add(no_lexer);
// And set the choice if we do not have a lexer.
if (lexer.GetScintillaLexer().empty())
{
choice = index;
}
wxSingleChoiceDialog dlg(parent, _("Input") + ":", caption, aChoices);
if (choice != -1)
{
dlg.SetSelection(choice);
}
if (dlg.ShowModal() == wxID_CANCEL)
{
return false;
}
const wxString sel = dlg.GetStringSelection();
if (sel == no_lexer)
{
lexer = wxExLexer();
}
else
{
lexer = FindByName(sel);
}
return true;
}
<|endoftext|> |
<commit_before>/*
===========================================================================
Daemon BSD Source Code
Copyright (c) 2013-2014, Daemon Developers
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 Daemon developers 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 DAEMON DEVELOPERS 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 "Common.h"
#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#include <signal.h>
#ifdef __native_client__
#include <nacl/nacl_exception.h>
#else
#include <dlfcn.h>
#endif
#endif
namespace Sys {
#ifdef _WIN32
SteadyClock::time_point SteadyClock::now() NOEXCEPT
{
// Determine performance counter frequency
static double nanosec_per_tic = 0.0;
if (nanosec_per_tic == 0.0) {
LARGE_INTEGER freq;
QueryPerformanceFrequency(&freq);
nanosec_per_tic = 1000000000.0 / freq.QuadPart;
}
LARGE_INTEGER time;
QueryPerformanceCounter(&time);
return time_point(duration(rep(nanosec_per_tic * time.QuadPart)));
}
#endif
void SleepFor(SteadyClock::duration time)
{
#ifdef _WIN32
static ULONG maxRes = 0;
static NTSTATUS(WINAPI *pNtSetTimerResolution) (ULONG resolution, BOOLEAN set_resolution, ULONG* current_resolution);
static NTSTATUS(WINAPI *pNtDelayExecution) (BOOLEAN alertable, const LARGE_INTEGER* timeout);
if (maxRes == 0) {
// Load ntdll.dll functions
std::string errorString;
DynamicLib ntdll = DynamicLib::Open("ntdll.dll", errorString);
if (!ntdll)
Sys::Error("Failed to load ntdll.dll: %s", errorString);
auto pNtQueryTimerResolution = ntdll.LoadSym<NTSTATUS WINAPI(ULONG*, ULONG*, ULONG*)>("NtQueryTimerResolution", errorString);
if (!pNtQueryTimerResolution)
Sys::Error("Failed to load NtQueryTimerResolution from ntdll.dll: %s", errorString);
pNtSetTimerResolution = ntdll.LoadSym<NTSTATUS WINAPI(ULONG, BOOLEAN, ULONG*)>("NtSetTimerResolution", errorString);
if (!pNtSetTimerResolution)
Sys::Error("Failed to load NtSetTimerResolution from ntdll.dll: %s", errorString);
pNtDelayExecution = ntdll.LoadSym<NTSTATUS WINAPI(BOOLEAN, const LARGE_INTEGER*)>("NtDelayExecution", errorString);
if (!pNtDelayExecution)
Sys::Error("Failed to load NtDelayExecution from ntdll.dll: %s", errorString);
// Determine the maximum available timer resolution
ULONG minRes, curRes;
if (pNtQueryTimerResolution(&minRes, &maxRes, &curRes) != 0)
maxRes = 10000; // Default to 1ms
}
// Increase the system timer resolution for the duration of the sleep
ULONG curRes;
pNtSetTimerResolution(maxRes, TRUE, &curRes);
// Convert to NT units of 100ns
typedef std::chrono::duration<int64_t, std::ratio<1, 10000000>> NTDuration;
auto ntTime = std::chrono::duration_cast<NTDuration>(time);
// Store the delay as a negative number to indicate a relative sleep
LARGE_INTEGER duration;
duration.QuadPart = -ntTime.count();
pNtDelayExecution(FALSE, &duration);
// Restore timer resolution after sleeping
pNtSetTimerResolution(maxRes, FALSE, &curRes);
#else
std::this_thread::sleep_for(time);
#endif
}
SteadyClock::time_point SleepUntil(SteadyClock::time_point time)
{
// Early exit if we are already past the deadline
auto now = SteadyClock::now();
if (now >= time) {
// We were already past our deadline, which means that the previous frame
// ran for too long. Use the current time as the base for the next frame.
return now;
}
// Perform the actual sleep
SleepFor(time - now);
// We may have overslept, so use the target time rather than the
// current time as the base for the next frame. That way we ensure
// that the frame rate remains consistent.
return time;
}
void Drop(Str::StringRef message)
{
// Transform into a fatal error if too many errors are generated in quick
// succession.
static Sys::SteadyClock::time_point lastError;
Sys::SteadyClock::time_point now = Sys::SteadyClock::now();
static int errorCount = 0;
if (now - lastError < std::chrono::milliseconds(100)) {
if (++errorCount > 3)
Sys::Error(message);
} else
errorCount = 0;
lastError = now;
throw DropErr(message.c_str());
}
#ifdef _WIN32
std::string Win32StrError(uint32_t error)
{
std::string out;
char* message;
if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM, nullptr, error, MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT), reinterpret_cast<char *>(&message), 0, nullptr)) {
out = message;
// FormatMessage adds ".\r\n" to messages, but we don't want those
if (out.back() == '\n')
out.pop_back();
if (out.back() == '\r')
out.pop_back();
if (out.back() == '.')
out.pop_back();
LocalFree(message);
} else
out = Str::Format("Unknown error 0x%08lx", error);
return out;
}
#endif
// Setup crash handling
#ifdef _WIN32
static const char *WindowsExceptionString(DWORD code)
{
switch (code) {
case EXCEPTION_ACCESS_VIOLATION:
return "Access violation";
case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
return "Array bounds exceeded";
case EXCEPTION_BREAKPOINT:
return "Breakpoint was encountered";
case EXCEPTION_DATATYPE_MISALIGNMENT:
return "Datatype misalignment";
case EXCEPTION_FLT_DENORMAL_OPERAND:
return "Float: Denormal operand";
case EXCEPTION_FLT_DIVIDE_BY_ZERO:
return "Float: Divide by zero";
case EXCEPTION_FLT_INEXACT_RESULT:
return "Float: Inexact result";
case EXCEPTION_FLT_INVALID_OPERATION:
return "Float: Invalid operation";
case EXCEPTION_FLT_OVERFLOW:
return "Float: Overflow";
case EXCEPTION_FLT_STACK_CHECK:
return "Float: Stack check";
case EXCEPTION_FLT_UNDERFLOW:
return "Float: Underflow";
case EXCEPTION_ILLEGAL_INSTRUCTION:
return "Illegal instruction";
case EXCEPTION_IN_PAGE_ERROR:
return "Page error";
case EXCEPTION_INT_DIVIDE_BY_ZERO:
return "Integer: Divide by zero";
case EXCEPTION_INT_OVERFLOW:
return "Integer: Overflow";
case EXCEPTION_INVALID_DISPOSITION:
return "Invalid disposition";
case EXCEPTION_NONCONTINUABLE_EXCEPTION:
return "Noncontinuable exception";
case EXCEPTION_PRIV_INSTRUCTION:
return "Privileged instruction";
case EXCEPTION_SINGLE_STEP:
return "Single step";
case EXCEPTION_STACK_OVERFLOW:
return "Stack overflow";
default:
return "Unknown exception";
}
}
static LONG WINAPI CrashHandler(PEXCEPTION_POINTERS ExceptionInfo)
{
// Reset handler so that any future errors cause a crash
SetUnhandledExceptionFilter(nullptr);
// TODO: backtrace
Sys::Error("Crashed with exception 0x%lx: %s", ExceptionInfo->ExceptionRecord->ExceptionCode, WindowsExceptionString(ExceptionInfo->ExceptionRecord->ExceptionCode));
return EXCEPTION_CONTINUE_EXECUTION;
}
void SetupCrashHandler()
{
SetUnhandledExceptionFilter(CrashHandler);
}
#elif defined(__native_client__)
static void CrashHandler(struct NaClExceptionContext *)
{
// TODO: backtrace
Sys::Error("Crashed with NaCl exception");
}
void SetupCrashHandler()
{
nacl_exception_set_handler(CrashHandler);
}
#else
static void CrashHandler(int sig)
{
// TODO: backtrace
Sys::Error("Crashed with signal %d: %s", sig, strsignal(sig));
}
void SetupCrashHandler()
{
struct sigaction sa;
sa.sa_flags = SA_RESETHAND | SA_NODEFER;
sa.sa_handler = CrashHandler;
sigemptyset(&sa.sa_mask);
for (int sig: {SIGILL, SIGFPE, SIGSEGV, SIGABRT, SIGBUS, SIGTRAP})
sigaction(sig, &sa, nullptr);
}
#endif
#ifndef __native_client__
void DynamicLib::Close()
{
if (!handle)
return;
#ifdef _WIN32
FreeLibrary(static_cast<HMODULE>(handle));
#else
dlclose(handle);
#endif
handle = nullptr;
}
DynamicLib DynamicLib::Open(Str::StringRef filename, std::string& errorString)
{
#ifdef _WIN32
void* handle = LoadLibraryW(Str::UTF8To16(filename).c_str());
if (!handle)
errorString = Win32StrError(GetLastError());
#else
// Handle relative paths correctly
const char* dlopenFilename = filename.c_str();
std::string relativePath;
if (filename.find('/') == std::string::npos) {
relativePath = "./" + filename;
dlopenFilename = relativePath.c_str();
}
void* handle = dlopen(dlopenFilename, RTLD_NOW);
if (!handle)
errorString = dlerror();
#endif
DynamicLib out;
out.handle = handle;
return out;
}
intptr_t DynamicLib::InternalLoadSym(Str::StringRef sym, std::string& errorString)
{
#ifdef _WIN32
intptr_t p = reinterpret_cast<intptr_t>(GetProcAddress(static_cast<HMODULE>(handle), sym.c_str()));
if (!p)
errorString = Win32StrError(GetLastError());
return p;
#else
intptr_t p = reinterpret_cast<intptr_t>(dlsym(handle, sym.c_str()));
if (!p)
errorString = dlerror();
return p;
#endif
}
#endif // __native_client__
bool processTerminating = false;
void OSExit(int exitCode) {
processTerminating = true;
exit(exitCode);
}
bool IsProcessTerminating() {
return processTerminating;
}
void GenRandomBytes(void* dest, size_t size)
{
#ifdef _WIN32
HCRYPTPROV prov;
if (!CryptAcquireContext(&prov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
Sys::Error("CryptAcquireContext failed: %s", Win32StrError(GetLastError()));
if (!CryptGenRandom(prov, size, (BYTE*)dest))
Sys::Error("CryptGenRandom failed: %s", Win32StrError(GetLastError()));
CryptReleaseContext(prov, 0);
#else
try {
FS::RawPath::OpenRead("/dev/urandom").Read(dest, size);
} catch (std::system_error& err) {
Sys::Error("Failed to generate random bytes: %s", err.what());
}
#endif
}
} // namespace Sys
// Global operator new/delete override to not throw an exception when out of
// memory. Instead, it is preferable to simply crash with an error.
void* operator new(size_t n)
{
void* p = malloc(n);
if (!p)
Sys::Error("Out of memory");
return p;
}
void operator delete(void* p) NOEXCEPT
{
if (!Sys::processTerminating) {
free(p);
}
}
<commit_msg>Implement Sys::GenRandomBytes for NaCl<commit_after>/*
===========================================================================
Daemon BSD Source Code
Copyright (c) 2013-2014, Daemon Developers
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 Daemon developers 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 DAEMON DEVELOPERS 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 "Common.h"
#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#include <signal.h>
#ifdef __native_client__
#include <nacl/nacl_exception.h>
#include <nacl/nacl_random.h>
#else
#include <dlfcn.h>
#endif
#endif
namespace Sys {
#ifdef _WIN32
SteadyClock::time_point SteadyClock::now() NOEXCEPT
{
// Determine performance counter frequency
static double nanosec_per_tic = 0.0;
if (nanosec_per_tic == 0.0) {
LARGE_INTEGER freq;
QueryPerformanceFrequency(&freq);
nanosec_per_tic = 1000000000.0 / freq.QuadPart;
}
LARGE_INTEGER time;
QueryPerformanceCounter(&time);
return time_point(duration(rep(nanosec_per_tic * time.QuadPart)));
}
#endif
void SleepFor(SteadyClock::duration time)
{
#ifdef _WIN32
static ULONG maxRes = 0;
static NTSTATUS(WINAPI *pNtSetTimerResolution) (ULONG resolution, BOOLEAN set_resolution, ULONG* current_resolution);
static NTSTATUS(WINAPI *pNtDelayExecution) (BOOLEAN alertable, const LARGE_INTEGER* timeout);
if (maxRes == 0) {
// Load ntdll.dll functions
std::string errorString;
DynamicLib ntdll = DynamicLib::Open("ntdll.dll", errorString);
if (!ntdll)
Sys::Error("Failed to load ntdll.dll: %s", errorString);
auto pNtQueryTimerResolution = ntdll.LoadSym<NTSTATUS WINAPI(ULONG*, ULONG*, ULONG*)>("NtQueryTimerResolution", errorString);
if (!pNtQueryTimerResolution)
Sys::Error("Failed to load NtQueryTimerResolution from ntdll.dll: %s", errorString);
pNtSetTimerResolution = ntdll.LoadSym<NTSTATUS WINAPI(ULONG, BOOLEAN, ULONG*)>("NtSetTimerResolution", errorString);
if (!pNtSetTimerResolution)
Sys::Error("Failed to load NtSetTimerResolution from ntdll.dll: %s", errorString);
pNtDelayExecution = ntdll.LoadSym<NTSTATUS WINAPI(BOOLEAN, const LARGE_INTEGER*)>("NtDelayExecution", errorString);
if (!pNtDelayExecution)
Sys::Error("Failed to load NtDelayExecution from ntdll.dll: %s", errorString);
// Determine the maximum available timer resolution
ULONG minRes, curRes;
if (pNtQueryTimerResolution(&minRes, &maxRes, &curRes) != 0)
maxRes = 10000; // Default to 1ms
}
// Increase the system timer resolution for the duration of the sleep
ULONG curRes;
pNtSetTimerResolution(maxRes, TRUE, &curRes);
// Convert to NT units of 100ns
typedef std::chrono::duration<int64_t, std::ratio<1, 10000000>> NTDuration;
auto ntTime = std::chrono::duration_cast<NTDuration>(time);
// Store the delay as a negative number to indicate a relative sleep
LARGE_INTEGER duration;
duration.QuadPart = -ntTime.count();
pNtDelayExecution(FALSE, &duration);
// Restore timer resolution after sleeping
pNtSetTimerResolution(maxRes, FALSE, &curRes);
#else
std::this_thread::sleep_for(time);
#endif
}
SteadyClock::time_point SleepUntil(SteadyClock::time_point time)
{
// Early exit if we are already past the deadline
auto now = SteadyClock::now();
if (now >= time) {
// We were already past our deadline, which means that the previous frame
// ran for too long. Use the current time as the base for the next frame.
return now;
}
// Perform the actual sleep
SleepFor(time - now);
// We may have overslept, so use the target time rather than the
// current time as the base for the next frame. That way we ensure
// that the frame rate remains consistent.
return time;
}
void Drop(Str::StringRef message)
{
// Transform into a fatal error if too many errors are generated in quick
// succession.
static Sys::SteadyClock::time_point lastError;
Sys::SteadyClock::time_point now = Sys::SteadyClock::now();
static int errorCount = 0;
if (now - lastError < std::chrono::milliseconds(100)) {
if (++errorCount > 3)
Sys::Error(message);
} else
errorCount = 0;
lastError = now;
throw DropErr(message.c_str());
}
#ifdef _WIN32
std::string Win32StrError(uint32_t error)
{
std::string out;
char* message;
if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM, nullptr, error, MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT), reinterpret_cast<char *>(&message), 0, nullptr)) {
out = message;
// FormatMessage adds ".\r\n" to messages, but we don't want those
if (out.back() == '\n')
out.pop_back();
if (out.back() == '\r')
out.pop_back();
if (out.back() == '.')
out.pop_back();
LocalFree(message);
} else
out = Str::Format("Unknown error 0x%08lx", error);
return out;
}
#endif
// Setup crash handling
#ifdef _WIN32
static const char *WindowsExceptionString(DWORD code)
{
switch (code) {
case EXCEPTION_ACCESS_VIOLATION:
return "Access violation";
case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
return "Array bounds exceeded";
case EXCEPTION_BREAKPOINT:
return "Breakpoint was encountered";
case EXCEPTION_DATATYPE_MISALIGNMENT:
return "Datatype misalignment";
case EXCEPTION_FLT_DENORMAL_OPERAND:
return "Float: Denormal operand";
case EXCEPTION_FLT_DIVIDE_BY_ZERO:
return "Float: Divide by zero";
case EXCEPTION_FLT_INEXACT_RESULT:
return "Float: Inexact result";
case EXCEPTION_FLT_INVALID_OPERATION:
return "Float: Invalid operation";
case EXCEPTION_FLT_OVERFLOW:
return "Float: Overflow";
case EXCEPTION_FLT_STACK_CHECK:
return "Float: Stack check";
case EXCEPTION_FLT_UNDERFLOW:
return "Float: Underflow";
case EXCEPTION_ILLEGAL_INSTRUCTION:
return "Illegal instruction";
case EXCEPTION_IN_PAGE_ERROR:
return "Page error";
case EXCEPTION_INT_DIVIDE_BY_ZERO:
return "Integer: Divide by zero";
case EXCEPTION_INT_OVERFLOW:
return "Integer: Overflow";
case EXCEPTION_INVALID_DISPOSITION:
return "Invalid disposition";
case EXCEPTION_NONCONTINUABLE_EXCEPTION:
return "Noncontinuable exception";
case EXCEPTION_PRIV_INSTRUCTION:
return "Privileged instruction";
case EXCEPTION_SINGLE_STEP:
return "Single step";
case EXCEPTION_STACK_OVERFLOW:
return "Stack overflow";
default:
return "Unknown exception";
}
}
static LONG WINAPI CrashHandler(PEXCEPTION_POINTERS ExceptionInfo)
{
// Reset handler so that any future errors cause a crash
SetUnhandledExceptionFilter(nullptr);
// TODO: backtrace
Sys::Error("Crashed with exception 0x%lx: %s", ExceptionInfo->ExceptionRecord->ExceptionCode, WindowsExceptionString(ExceptionInfo->ExceptionRecord->ExceptionCode));
return EXCEPTION_CONTINUE_EXECUTION;
}
void SetupCrashHandler()
{
SetUnhandledExceptionFilter(CrashHandler);
}
#elif defined(__native_client__)
static void CrashHandler(struct NaClExceptionContext *)
{
// TODO: backtrace
Sys::Error("Crashed with NaCl exception");
}
void SetupCrashHandler()
{
nacl_exception_set_handler(CrashHandler);
}
#else
static void CrashHandler(int sig)
{
// TODO: backtrace
Sys::Error("Crashed with signal %d: %s", sig, strsignal(sig));
}
void SetupCrashHandler()
{
struct sigaction sa;
sa.sa_flags = SA_RESETHAND | SA_NODEFER;
sa.sa_handler = CrashHandler;
sigemptyset(&sa.sa_mask);
for (int sig: {SIGILL, SIGFPE, SIGSEGV, SIGABRT, SIGBUS, SIGTRAP})
sigaction(sig, &sa, nullptr);
}
#endif
#ifndef __native_client__
void DynamicLib::Close()
{
if (!handle)
return;
#ifdef _WIN32
FreeLibrary(static_cast<HMODULE>(handle));
#else
dlclose(handle);
#endif
handle = nullptr;
}
DynamicLib DynamicLib::Open(Str::StringRef filename, std::string& errorString)
{
#ifdef _WIN32
void* handle = LoadLibraryW(Str::UTF8To16(filename).c_str());
if (!handle)
errorString = Win32StrError(GetLastError());
#else
// Handle relative paths correctly
const char* dlopenFilename = filename.c_str();
std::string relativePath;
if (filename.find('/') == std::string::npos) {
relativePath = "./" + filename;
dlopenFilename = relativePath.c_str();
}
void* handle = dlopen(dlopenFilename, RTLD_NOW);
if (!handle)
errorString = dlerror();
#endif
DynamicLib out;
out.handle = handle;
return out;
}
intptr_t DynamicLib::InternalLoadSym(Str::StringRef sym, std::string& errorString)
{
#ifdef _WIN32
intptr_t p = reinterpret_cast<intptr_t>(GetProcAddress(static_cast<HMODULE>(handle), sym.c_str()));
if (!p)
errorString = Win32StrError(GetLastError());
return p;
#else
intptr_t p = reinterpret_cast<intptr_t>(dlsym(handle, sym.c_str()));
if (!p)
errorString = dlerror();
return p;
#endif
}
#endif // __native_client__
bool processTerminating = false;
void OSExit(int exitCode) {
processTerminating = true;
exit(exitCode);
}
bool IsProcessTerminating() {
return processTerminating;
}
void GenRandomBytes(void* dest, size_t size)
{
#ifdef _WIN32
HCRYPTPROV prov;
if (!CryptAcquireContext(&prov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
Sys::Error("CryptAcquireContext failed: %s", Win32StrError(GetLastError()));
if (!CryptGenRandom(prov, size, (BYTE*)dest))
Sys::Error("CryptGenRandom failed: %s", Win32StrError(GetLastError()));
CryptReleaseContext(prov, 0);
#elif defined(__native_client__)
size_t bytes_written;
if (nacl_secure_random(dest, size, &bytes_written) != 0 || bytes_written != size)
Sys::Error("nacl_secure_random failed");
#else
try {
FS::RawPath::OpenRead("/dev/urandom").Read(dest, size);
} catch (std::system_error& err) {
Sys::Error("Failed to generate random bytes: %s", err.what());
}
#endif
}
} // namespace Sys
// Global operator new/delete override to not throw an exception when out of
// memory. Instead, it is preferable to simply crash with an error.
void* operator new(size_t n)
{
void* p = malloc(n);
if (!p)
Sys::Error("Out of memory");
return p;
}
void operator delete(void* p) NOEXCEPT
{
if (!Sys::processTerminating) {
free(p);
}
}
<|endoftext|> |
<commit_before>#include <mill/math/Vector.hpp>
#include <mill/util/logger.hpp>
#include "mode_calc_help.hpp"
#include "mode_calc_rmsd.hpp"
#include "mode_calc_wham.hpp"
#include "mode_calc_dist.hpp"
#include "mode_calc_angle.hpp"
#include "mode_calc_aabb.hpp"
#include "mode_calc_obb.hpp"
#include "mode_calc_center.hpp"
namespace mill
{
const char* mode_calc_help_usage() noexcept
{
return "usage: mill calc [command] [parameters...]\n\n"
" avaiable commands\n"
" - rmsd\n"
" : calculate RMSD between a reference and frames in trajectory\n"
" - wham\n"
" : reconstruct free energy surface by WHAM\n"
" - dist\n"
" : calculate distance from traj file\n"
" - angle\n"
" : calculate angle from traj file\n"
" - aabb\n"
" : construct AABB\n"
" - obb\n"
" : construct OBB using covariances\n"
" - center\n"
" : calculate geometric center\n"
" - help\n"
" : print detailed explanation of each command\n";
}
//! this function forwards the arguments to different modes.
int mode_calc_help(std::deque<std::string_view> args)
{
using namespace std::literals::string_view_literals;
if(args.empty())
{
log::info(mode_calc_help_usage());
return 0;
}
const auto command = args.front();
if(command == "rmsd")
{
return mode_calc_rmsd({"help"sv});
}
else if(command == "dist")
{
return mode_calc_dist({"help"sv});
}
else if(command == "angle")
{
return mode_calc_angle({"help"sv});
}
else if(command == "wham")
{
return mode_calc_wham({"help"sv});
}
else if(command == "obb")
{
return mode_calc_obb({"help"sv});
}
else if(command == "aabb")
{
return mode_calc_aabb({"help"sv});
}
else if(command == "center")
{
return mode_calc_center({"help"sv});
}
else if(command == "help")
{
log::info(mode_calc_help_usage());
return 0;
}
else
{
log::error("mill calc help: unknown command : ", command);
log::error(mode_calc_help_usage());
return 1;
}
}
} // mill
<commit_msg>:children_crossing: add autocorrelation to calc help<commit_after>#include <mill/math/Vector.hpp>
#include <mill/util/logger.hpp>
#include "mode_calc_help.hpp"
#include "mode_calc_rmsd.hpp"
#include "mode_calc_wham.hpp"
#include "mode_calc_dist.hpp"
#include "mode_calc_angle.hpp"
#include "mode_calc_aabb.hpp"
#include "mode_calc_obb.hpp"
#include "mode_calc_center.hpp"
#include "mode_calc_autocorrelation.hpp"
namespace mill
{
const char* mode_calc_help_usage() noexcept
{
return "usage: mill calc [command] [parameters...]\n\n"
" avaiable commands\n"
" - rmsd\n"
" : calculate RMSD between a reference and frames in trajectory\n"
" - wham\n"
" : reconstruct free energy surface by WHAM\n"
" - dist\n"
" : calculate distance from traj file\n"
" - angle\n"
" : calculate angle from traj file\n"
" - aabb\n"
" : construct AABB\n"
" - obb\n"
" : construct OBB using covariances\n"
" - center\n"
" : calculate geometric center\n"
" - autocorrelation\n"
" : calculate autocorrelation of data\n"
" - help\n"
" : print detailed explanation of each command\n";
}
//! this function forwards the arguments to different modes.
int mode_calc_help(std::deque<std::string_view> args)
{
using namespace std::literals::string_view_literals;
if(args.empty())
{
log::info(mode_calc_help_usage());
return 0;
}
const auto command = args.front();
if(command == "rmsd")
{
return mode_calc_rmsd({"help"sv});
}
else if(command == "dist")
{
return mode_calc_dist({"help"sv});
}
else if(command == "angle")
{
return mode_calc_angle({"help"sv});
}
else if(command == "wham")
{
return mode_calc_wham({"help"sv});
}
else if(command == "obb")
{
return mode_calc_obb({"help"sv});
}
else if(command == "aabb")
{
return mode_calc_aabb({"help"sv});
}
else if(command == "center")
{
return mode_calc_center({"help"sv});
}
else if(command == "autocorrelation")
{
return mode_calc_autocorrelation({"help"sv});
}
else if(command == "help")
{
log::info(mode_calc_help_usage());
return 0;
}
else
{
log::error("mill calc help: unknown command : ", command);
log::error(mode_calc_help_usage());
return 1;
}
}
} // mill
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: core_resource.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: fs $ $Date: 2001-04-26 11:18:22 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _DBA_CORE_RESOURCE_HXX_
#define _DBA_CORE_RESOURCE_HXX_
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
class SimpleResMgr;
//.........................................................................
namespace dbaccess
{
#define DBACORE_RESSTRING(id) ResourceManager::loadString(id)
//==================================================================
//= ResourceManager
//= handling ressources within the DBA-Core library
//==================================================================
class ResourceManager
{
static SimpleResMgr* m_pImpl;
private:
// no instantiation allowed
ResourceManager() { }
~ResourceManager() { }
// we'll instantiate one static member of the following class, which, in it's dtor,
// ensures that m_pImpl will be deleted
class EnsureDelete
{
public:
EnsureDelete() { }
~EnsureDelete();
};
friend class EnsureDelete;
protected:
static void ensureImplExists();
public:
/** loads the string with the specified resource id from the FormLayer resource file
*/
static ::rtl::OUString loadString(sal_uInt16 _nResId);
};
//.........................................................................
}
//.........................................................................
#endif // _DBA_CORE_RESOURCE_HXX_
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.504); FILE MERGED 2005/09/05 17:32:29 rt 1.2.504.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: core_resource.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 13:36:10 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _DBA_CORE_RESOURCE_HXX_
#define _DBA_CORE_RESOURCE_HXX_
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
class SimpleResMgr;
//.........................................................................
namespace dbaccess
{
#define DBACORE_RESSTRING(id) ResourceManager::loadString(id)
//==================================================================
//= ResourceManager
//= handling ressources within the DBA-Core library
//==================================================================
class ResourceManager
{
static SimpleResMgr* m_pImpl;
private:
// no instantiation allowed
ResourceManager() { }
~ResourceManager() { }
// we'll instantiate one static member of the following class, which, in it's dtor,
// ensures that m_pImpl will be deleted
class EnsureDelete
{
public:
EnsureDelete() { }
~EnsureDelete();
};
friend class EnsureDelete;
protected:
static void ensureImplExists();
public:
/** loads the string with the specified resource id from the FormLayer resource file
*/
static ::rtl::OUString loadString(sal_uInt16 _nResId);
};
//.........................................................................
}
//.........................................................................
#endif // _DBA_CORE_RESOURCE_HXX_
<|endoftext|> |
<commit_before>#include <chrono>
#include <derecho/sst/multicast_sst.hpp>
#include <iostream>
#include <memory>
#include <thread>
#include <vector>
#include "aggregate_bandwidth.hpp"
#include "initialize.h"
#include "log_results.hpp"
using namespace std;
using namespace sst;
volatile bool done = false;
struct exp_results {
uint32_t num_nodes;
int num_senders_selector;
uint max_msg_size;
double sum_message_rate;
void print(std::ofstream& fout) {
fout << num_nodes << " " << num_senders_selector << " "
<< max_msg_size << " " << sum_message_rate << endl;
}
};
#ifndef NDEBUG
#define DEBUG_MSG(str) \
do { \
std::cout << str << std::endl; \
} while(false)
#else
#define DEBUG_MSG(str) \
do { \
} while(false)
#endif
int main(int argc, char* argv[]) {
constexpr uint max_msg_size = 1;
const unsigned int num_messages = 1000000;
if(argc < 4) {
cout << "Insufficient number of command line arguments" << endl;
cout << "Usage: " << argv[0] << " <num_nodes> <window_size><num_senders_selector (0 - all senders, 1 - half senders, 2 - one sender)>" << endl;
cout << "Thank you" << endl;
exit(1);
}
uint32_t num_nodes = atoi(argv[1]);
uint32_t window_size = atoi(argv[2]);
int num_senders_selector = atoi(argv[3]);
const uint32_t node_id = derecho::getConfUInt32(CONF_DERECHO_LOCAL_ID);
const std::map<uint32_t, std::pair<ip_addr_t, uint16_t>> ip_addrs_and_ports = initialize(num_nodes);
// initialize the rdma resources
#ifdef USE_VERBS_API
verbs_initialize(ip_addrs_and_ports, ip_addrs_and_ports, node_id);
#else
lf_initialize(ip_addrs_and_ports, node_id);
#endif
std::vector<uint32_t> members;
for(const auto& p : ip_addrs_and_ports) {
members.push_back(p.first);
}
uint32_t num_senders = num_nodes, row_offset = 0;
if(num_senders_selector == 0) {
} else if(num_senders_selector == 1) {
num_senders = num_nodes / 2;
row_offset = (num_nodes + 1) / 2;
} else {
num_senders = 1;
row_offset = num_nodes - 1;
}
std::shared_ptr<multicast_sst> sst = make_shared<multicast_sst>(
sst::SSTParams(members, node_id),
window_size,
num_senders, max_msg_size);
uint32_t node_rank = sst->get_local_index();
auto check_failures_loop = [&sst]() {
pthread_setname_np(pthread_self(), "check_failures");
while(true) {
std::this_thread::sleep_for(chrono::microseconds(1000));
if(sst) {
sst->put_with_completion((char*)std::addressof(sst->heartbeat[0]) - sst->getBaseAddress(), sizeof(bool));
}
}
};
thread failures_thread = std::thread(check_failures_loop);
vector<bool> completed(num_senders, false);
uint num_finished = 0;
auto sst_receive_handler = [&num_finished, num_senders_selector, &num_nodes, &num_messages, &completed](
uint32_t sender_rank, uint64_t index,
volatile char* msg, uint32_t size) {
if(index == num_messages - 1) {
completed[sender_rank] = true;
num_finished++;
}
if(num_finished == num_nodes || (num_senders_selector == 1 && num_finished == num_nodes / 2) || (num_senders_selector == 2 && num_finished == 1)) {
done = true;
}
};
auto receiver_pred = [&](const multicast_sst& sst) {
return true;
};
vector<int64_t> last_max_num_received(num_senders, -1);
auto receiver_trig = [&completed, last_max_num_received, window_size, num_nodes, node_rank, sst_receive_handler,
row_offset, num_senders](multicast_sst& sst) mutable {
while(true) {
for(uint j = 0; j < num_senders; ++j) {
auto num_received = sst.num_received_sst[node_rank][j] + 1;
uint32_t slot = num_received % window_size;
if((int64_t&)sst.slots[row_offset + j][(max_msg_size + 2 * sizeof(uint64_t)) * (slot + 1) - sizeof(uint64_t)] == (num_received / window_size + 1)) {
sst_receive_handler(j, num_received,
&sst.slots[row_offset + j][(max_msg_size + 2 * sizeof(uint64_t)) * slot],
sst.slots[row_offset + j][(max_msg_size + 2 * sizeof(uint64_t)) * (slot + 1) - 2 * sizeof(uint64_t)]);
sst.num_received_sst[node_rank][j]++;
}
}
bool time_to_push = true;
for(uint j = 0; j < num_senders; ++j) {
if(completed[j]) {
continue;
}
if(sst.num_received_sst[node_rank][j] - last_max_num_received[j] <= window_size / 2) {
time_to_push = false;
}
}
if(time_to_push) {
break;
}
}
sst.put(sst.num_received_sst.get_base() - sst.getBaseAddress(),
sizeof(sst.num_received_sst[0][0]) * num_senders);
for(uint j = 0; j < num_senders; ++j) {
last_max_num_received[j] = sst.num_received_sst[node_rank][j];
}
};
// inserting later
vector<uint32_t> indices(num_nodes);
iota(indices.begin(), indices.end(), 0);
std::vector<int> is_sender(num_nodes, 1);
if(num_senders_selector == 0) {
} else if(num_senders_selector == 1) {
for(uint i = 0; i <= (num_nodes - 1) / 2; ++i) {
is_sender[i] = 0;
}
} else {
for(uint i = 0; i < num_nodes - 1; ++i) {
is_sender[i] = 0;
}
}
sst::multicast_group<multicast_sst> g(sst, indices, window_size, max_msg_size, is_sender);
DEBUG_MSG("Group created");
// now
sst->predicates.insert(receiver_pred, receiver_trig,
sst::PredicateType::RECURRENT);
// uint count = 0;
struct timespec start_time, end_time;
// start timer
clock_gettime(CLOCK_REALTIME, &start_time);
if(node_rank == num_nodes - 1 || num_senders_selector == 0 || (node_rank > (num_nodes - 1) / 2 && num_senders_selector == 1)) {
for(uint i = 0; i < num_messages; ++i) {
volatile char* buf;
while((buf = g.get_buffer(max_msg_size)) == NULL) {
// ++count;
}
// for(uint i = 0; i < size; ++i) {
// buf[i] = 'a' + rand() % 26;
// }
g.send();
}
}
// cout << "Done sending" << endl;
while(!done) {
}
// end timer
clock_gettime(CLOCK_REALTIME, &end_time);
double my_time = ((end_time.tv_sec * 1e9 + end_time.tv_nsec) - (start_time.tv_sec * 1e9 + start_time.tv_nsec));
double message_rate = (num_messages * 1e9) / my_time;
;
if(num_senders_selector == 0) {
message_rate *= num_nodes;
} else if(num_senders_selector == 1) {
message_rate *= num_nodes / 2;
}
double sum_message_rate = aggregate_bandwidth(members, node_rank, message_rate);
log_results(exp_results{num_nodes, num_senders_selector, max_msg_size, sum_message_rate},
"data_multicast");
sst->sync_with_members();
}
<commit_msg>adapt multicast_throughput for libfabric too.<commit_after>#include <chrono>
#include <derecho/sst/multicast_sst.hpp>
#include <iostream>
#include <memory>
#include <thread>
#include <vector>
#include "aggregate_bandwidth.hpp"
#include "initialize.h"
#include "log_results.hpp"
using namespace std;
using namespace sst;
volatile bool done = false;
struct exp_results {
uint32_t num_nodes;
int num_senders_selector;
uint max_msg_size;
double sum_message_rate;
void print(std::ofstream& fout) {
fout << num_nodes << " " << num_senders_selector << " "
<< max_msg_size << " " << sum_message_rate << endl;
}
};
#ifndef NDEBUG
#define DEBUG_MSG(str) \
do { \
std::cout << str << std::endl; \
} while(false)
#else
#define DEBUG_MSG(str) \
do { \
} while(false)
#endif
int main(int argc, char* argv[]) {
constexpr uint max_msg_size = 1;
const unsigned int num_messages = 1000000;
if(argc < 4) {
cout << "Insufficient number of command line arguments" << endl;
cout << "Usage: " << argv[0] << " <num_nodes> <window_size><num_senders_selector (0 - all senders, 1 - half senders, 2 - one sender)>" << endl;
cout << "Thank you" << endl;
exit(1);
}
uint32_t num_nodes = atoi(argv[1]);
uint32_t window_size = atoi(argv[2]);
int num_senders_selector = atoi(argv[3]);
const uint32_t node_id = derecho::getConfUInt32(CONF_DERECHO_LOCAL_ID);
const std::map<uint32_t, std::pair<ip_addr_t, uint16_t>> ip_addrs_and_ports = initialize(num_nodes);
// initialize the rdma resources
#ifdef USE_VERBS_API
verbs_initialize(ip_addrs_and_ports, ip_addrs_and_ports, node_id);
#else
lf_initialize(ip_addrs_and_ports, ip_addrs_and_ports, node_id);
#endif
std::vector<uint32_t> members;
for(const auto& p : ip_addrs_and_ports) {
members.push_back(p.first);
}
uint32_t num_senders = num_nodes, row_offset = 0;
if(num_senders_selector == 0) {
} else if(num_senders_selector == 1) {
num_senders = num_nodes / 2;
row_offset = (num_nodes + 1) / 2;
} else {
num_senders = 1;
row_offset = num_nodes - 1;
}
std::shared_ptr<multicast_sst> sst = make_shared<multicast_sst>(
sst::SSTParams(members, node_id),
window_size,
num_senders, max_msg_size);
uint32_t node_rank = sst->get_local_index();
auto check_failures_loop = [&sst]() {
pthread_setname_np(pthread_self(), "check_failures");
while(true) {
std::this_thread::sleep_for(chrono::microseconds(1000));
if(sst) {
sst->put_with_completion((char*)std::addressof(sst->heartbeat[0]) - sst->getBaseAddress(), sizeof(bool));
}
}
};
thread failures_thread = std::thread(check_failures_loop);
vector<bool> completed(num_senders, false);
uint num_finished = 0;
auto sst_receive_handler = [&num_finished, num_senders_selector, &num_nodes, &num_messages, &completed](
uint32_t sender_rank, uint64_t index,
volatile char* msg, uint32_t size) {
if(index == num_messages - 1) {
completed[sender_rank] = true;
num_finished++;
}
if(num_finished == num_nodes || (num_senders_selector == 1 && num_finished == num_nodes / 2) || (num_senders_selector == 2 && num_finished == 1)) {
done = true;
}
};
auto receiver_pred = [&](const multicast_sst& sst) {
return true;
};
vector<int64_t> last_max_num_received(num_senders, -1);
auto receiver_trig = [&completed, last_max_num_received, window_size, num_nodes, node_rank, sst_receive_handler,
row_offset, num_senders](multicast_sst& sst) mutable {
while(true) {
for(uint j = 0; j < num_senders; ++j) {
auto num_received = sst.num_received_sst[node_rank][j] + 1;
uint32_t slot = num_received % window_size;
if((int64_t&)sst.slots[row_offset + j][(max_msg_size + 2 * sizeof(uint64_t)) * (slot + 1) - sizeof(uint64_t)] == (num_received / window_size + 1)) {
sst_receive_handler(j, num_received,
&sst.slots[row_offset + j][(max_msg_size + 2 * sizeof(uint64_t)) * slot],
sst.slots[row_offset + j][(max_msg_size + 2 * sizeof(uint64_t)) * (slot + 1) - 2 * sizeof(uint64_t)]);
sst.num_received_sst[node_rank][j]++;
}
}
bool time_to_push = true;
for(uint j = 0; j < num_senders; ++j) {
if(completed[j]) {
continue;
}
if(sst.num_received_sst[node_rank][j] - last_max_num_received[j] <= window_size / 2) {
time_to_push = false;
}
}
if(time_to_push) {
break;
}
}
sst.put(sst.num_received_sst.get_base() - sst.getBaseAddress(),
sizeof(sst.num_received_sst[0][0]) * num_senders);
for(uint j = 0; j < num_senders; ++j) {
last_max_num_received[j] = sst.num_received_sst[node_rank][j];
}
};
// inserting later
vector<uint32_t> indices(num_nodes);
iota(indices.begin(), indices.end(), 0);
std::vector<int> is_sender(num_nodes, 1);
if(num_senders_selector == 0) {
} else if(num_senders_selector == 1) {
for(uint i = 0; i <= (num_nodes - 1) / 2; ++i) {
is_sender[i] = 0;
}
} else {
for(uint i = 0; i < num_nodes - 1; ++i) {
is_sender[i] = 0;
}
}
sst::multicast_group<multicast_sst> g(sst, indices, window_size, max_msg_size, is_sender);
DEBUG_MSG("Group created");
// now
sst->predicates.insert(receiver_pred, receiver_trig,
sst::PredicateType::RECURRENT);
// uint count = 0;
struct timespec start_time, end_time;
// start timer
clock_gettime(CLOCK_REALTIME, &start_time);
if(node_rank == num_nodes - 1 || num_senders_selector == 0 || (node_rank > (num_nodes - 1) / 2 && num_senders_selector == 1)) {
for(uint i = 0; i < num_messages; ++i) {
volatile char* buf;
while((buf = g.get_buffer(max_msg_size)) == NULL) {
// ++count;
}
// for(uint i = 0; i < size; ++i) {
// buf[i] = 'a' + rand() % 26;
// }
g.send();
}
}
// cout << "Done sending" << endl;
while(!done) {
}
// end timer
clock_gettime(CLOCK_REALTIME, &end_time);
double my_time = ((end_time.tv_sec * 1e9 + end_time.tv_nsec) - (start_time.tv_sec * 1e9 + start_time.tv_nsec));
double message_rate = (num_messages * 1e9) / my_time;
;
if(num_senders_selector == 0) {
message_rate *= num_nodes;
} else if(num_senders_selector == 1) {
message_rate *= num_nodes / 2;
}
double sum_message_rate = aggregate_bandwidth(members, node_rank, message_rate);
log_results(exp_results{num_nodes, num_senders_selector, max_msg_size, sum_message_rate},
"data_multicast");
sst->sync_with_members();
}
<|endoftext|> |
<commit_before>/**
* Touhou Community Reliant Automatic Patcher
* Main DLL
*
* ----
*
* Repository handling.
*/
#include "thcrap.h"
#include "thcrap_update_wrapper.h"
#include <algorithm>
TH_CALLER_FREE char *RepoGetLocalFN(const char *id)
{
return strdup_cat("repos/", id, "/repo.js");
}
repo_t *RepoLoadJson(json_t *repo_js)
{
if (!json_is_object(repo_js)) {
return nullptr;
}
repo_t *repo = (repo_t*)malloc(sizeof(repo_t));
repo->id = json_object_get_string_copy(repo_js, "id");
repo->title = json_object_get_string_copy(repo_js, "title");
repo->contact = json_object_get_string_copy(repo_js, "contact");
repo->servers = json_object_get_string_array_copy(repo_js, "servers");
repo->neighbors = json_object_get_string_array_copy(repo_js, "neighbors");
json_t *patches = json_object_get(repo_js, "patches");
if (json_is_object(patches)) {
if (size_t patch_count = json_object_size(patches)) {
repo->patches = new repo_patch_t[patch_count + 1];
repo->patches[patch_count].patch_id = NULL;
const char* patch_id;
json_t* patch_title;
repo_patch_t* patch = repo->patches;
json_object_foreach(patches, patch_id, patch_title) {
patch->patch_id = strdup(patch_id);
patch->title = json_string_copy(patch_title);
++patch;
}
}
}
else {
repo->patches = NULL;
}
return repo;
}
bool RepoWrite(const repo_t *repo)
{
if (!repo || !repo->id) {
return false;
}
json_t* repo_js = json_object();
// Prepare json file
json_object_set_new(repo_js, "id", json_string(repo->id));
if (repo->title) {
json_object_set_new(repo_js, "title", json_string(repo->title));
}
if (repo->contact) {
json_object_set_new(repo_js, "contact", json_string(repo->contact));
}
if (repo->servers) {
json_t *servers = json_array();
for (size_t i = 0; repo->servers[i]; i++) {
json_array_append_new(servers, json_string(repo->servers[i]));
}
json_object_set_new(repo_js, "servers", servers);
}
if (repo->neighbors) {
json_t *neighbors = json_array();
for (size_t i = 0; repo->neighbors[i]; i++) {
json_array_append_new(neighbors, json_string(repo->neighbors[i]));
}
json_object_set_new(repo_js, "neighbors", neighbors);
}
if (repo->patches) {
json_t *patches = json_object();
for (size_t i = 0; repo->patches[i].patch_id; i++) {
json_object_set_new(patches, repo->patches[i].patch_id, json_string(repo->patches[i].title));
}
json_object_set_new(repo_js, "patches", patches);
}
// Write json file
char *repo_fn_local = RepoGetLocalFN(repo->id);
auto repo_path = std::filesystem::u8path(repo_fn_local);
auto repo_dir = repo_path;
repo_dir.remove_filename();
free(repo_fn_local);
std::filesystem::create_directories(repo_dir);
int ret = json_dump_file(repo_js, repo_path.u8string().c_str(), JSON_INDENT(4)) == 0;
json_decref(repo_js);
return ret;
}
void RepoFree(repo_t *repo)
{
if (repo) {
free(repo->id);
free(repo->title);
free(repo->contact);
if (repo->servers) {
for (size_t i = 0; repo->servers[i]; i++) {
free(repo->servers[i]);
}
free(repo->servers);
}
if (repo->neighbors) {
for (size_t i = 0; repo->neighbors[i]; i++) {
free(repo->neighbors[i]);
}
free(repo->neighbors);
}
if (repo->patches) {
for (size_t i = 0; repo->patches[i].patch_id; i++) {
free(repo->patches[i].patch_id);
free(repo->patches[i].title);
}
delete[] repo->patches;
}
free(repo);
}
}
repo_t *RepoLocalNext(HANDLE *hFind)
{
json_t *repo_js = NULL;
WIN32_FIND_DATAA w32fd;
BOOL find_ret = 0;
if(*hFind == NULL) {
// Too bad we can't do "*/repo.js" or something similar.
*hFind = FindFirstFile("repos/*", &w32fd);
if(*hFind == INVALID_HANDLE_VALUE) {
return NULL;
}
} else {
find_ret = W32_ERR_WRAP(FindNextFile(*hFind, &w32fd));
}
while(!find_ret) {
if(
(w32fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
&& strcmp(w32fd.cFileName, ".")
&& strcmp(w32fd.cFileName, "..")
) {
char *repo_local_fn = RepoGetLocalFN(w32fd.cFileName);
repo_js = json_load_file_report(repo_local_fn);
free(repo_local_fn);
if(repo_js) {
repo_t *repo = RepoLoadJson(repo_js);
json_decref(repo_js);
return repo;
}
}
find_ret = W32_ERR_WRAP(FindNextFile(*hFind, &w32fd));
};
FindClose(*hFind);
return NULL;
}
repo_t **RepoLoad(void)
{
HANDLE hFind = nullptr;
std::vector<repo_t*> repo_vector;
while (repo_t* repo = RepoLocalNext(&hFind)) {
repo_vector.push_back(repo);
}
if (repo_vector.empty()) {
return nullptr;
}
std::sort(repo_vector.begin(), repo_vector.end(), [](repo_t *a, repo_t *b) {
return strcmp(a->id, b->id) < 0;
});
size_t repo_count = repo_vector.size();
repo_t **repo_array = (repo_t**)malloc(sizeof(repo_t*) * (repo_count + 1));
repo_array[repo_count] = nullptr;
memcpy(repo_array, repo_vector.data(), sizeof(repo_t*) * repo_count);
return repo_array;
}
<commit_msg>thcrap: handle exception in RepoWrire<commit_after>/**
* Touhou Community Reliant Automatic Patcher
* Main DLL
*
* ----
*
* Repository handling.
*/
#include "thcrap.h"
#include "thcrap_update_wrapper.h"
#include <algorithm>
TH_CALLER_FREE char *RepoGetLocalFN(const char *id)
{
return strdup_cat("repos/", id, "/repo.js");
}
repo_t *RepoLoadJson(json_t *repo_js)
{
if (!json_is_object(repo_js)) {
return nullptr;
}
repo_t *repo = (repo_t*)malloc(sizeof(repo_t));
repo->id = json_object_get_string_copy(repo_js, "id");
repo->title = json_object_get_string_copy(repo_js, "title");
repo->contact = json_object_get_string_copy(repo_js, "contact");
repo->servers = json_object_get_string_array_copy(repo_js, "servers");
repo->neighbors = json_object_get_string_array_copy(repo_js, "neighbors");
json_t *patches = json_object_get(repo_js, "patches");
if (json_is_object(patches)) {
if (size_t patch_count = json_object_size(patches)) {
repo->patches = new repo_patch_t[patch_count + 1];
repo->patches[patch_count].patch_id = NULL;
const char* patch_id;
json_t* patch_title;
repo_patch_t* patch = repo->patches;
json_object_foreach(patches, patch_id, patch_title) {
patch->patch_id = strdup(patch_id);
patch->title = json_string_copy(patch_title);
++patch;
}
}
}
else {
repo->patches = NULL;
}
return repo;
}
bool RepoWrite(const repo_t *repo)
{
if (!repo || !repo->id) {
return false;
}
json_t* repo_js = json_object();
// Prepare json file
json_object_set_new(repo_js, "id", json_string(repo->id));
if (repo->title) {
json_object_set_new(repo_js, "title", json_string(repo->title));
}
if (repo->contact) {
json_object_set_new(repo_js, "contact", json_string(repo->contact));
}
if (repo->servers) {
json_t *servers = json_array();
for (size_t i = 0; repo->servers[i]; i++) {
json_array_append_new(servers, json_string(repo->servers[i]));
}
json_object_set_new(repo_js, "servers", servers);
}
if (repo->neighbors) {
json_t *neighbors = json_array();
for (size_t i = 0; repo->neighbors[i]; i++) {
json_array_append_new(neighbors, json_string(repo->neighbors[i]));
}
json_object_set_new(repo_js, "neighbors", neighbors);
}
if (repo->patches) {
json_t *patches = json_object();
for (size_t i = 0; repo->patches[i].patch_id; i++) {
json_object_set_new(patches, repo->patches[i].patch_id, json_string(repo->patches[i].title));
}
json_object_set_new(repo_js, "patches", patches);
}
// Write json file
char *repo_fn_local = RepoGetLocalFN(repo->id);
auto repo_path = std::filesystem::u8path(repo_fn_local);
auto repo_dir = repo_path;
repo_dir.remove_filename();
free(repo_fn_local);
try {
std::filesystem::create_directories(repo_dir);
}
catch (std::filesystem::filesystem_error e) {
log_printf("Failed to create repo folder %s.\nError %d: %s\n", repo_dir.u8string(), e.code().value(), e.what());
return false;
}
int ret = json_dump_file(repo_js, repo_path.u8string().c_str(), JSON_INDENT(4)) == 0;
json_decref(repo_js);
return ret;
}
void RepoFree(repo_t *repo)
{
if (repo) {
free(repo->id);
free(repo->title);
free(repo->contact);
if (repo->servers) {
for (size_t i = 0; repo->servers[i]; i++) {
free(repo->servers[i]);
}
free(repo->servers);
}
if (repo->neighbors) {
for (size_t i = 0; repo->neighbors[i]; i++) {
free(repo->neighbors[i]);
}
free(repo->neighbors);
}
if (repo->patches) {
for (size_t i = 0; repo->patches[i].patch_id; i++) {
free(repo->patches[i].patch_id);
free(repo->patches[i].title);
}
delete[] repo->patches;
}
free(repo);
}
}
repo_t *RepoLocalNext(HANDLE *hFind)
{
json_t *repo_js = NULL;
WIN32_FIND_DATAA w32fd;
BOOL find_ret = 0;
if(*hFind == NULL) {
// Too bad we can't do "*/repo.js" or something similar.
*hFind = FindFirstFile("repos/*", &w32fd);
if(*hFind == INVALID_HANDLE_VALUE) {
return NULL;
}
} else {
find_ret = W32_ERR_WRAP(FindNextFile(*hFind, &w32fd));
}
while(!find_ret) {
if(
(w32fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
&& strcmp(w32fd.cFileName, ".")
&& strcmp(w32fd.cFileName, "..")
) {
char *repo_local_fn = RepoGetLocalFN(w32fd.cFileName);
repo_js = json_load_file_report(repo_local_fn);
free(repo_local_fn);
if(repo_js) {
repo_t *repo = RepoLoadJson(repo_js);
json_decref(repo_js);
return repo;
}
}
find_ret = W32_ERR_WRAP(FindNextFile(*hFind, &w32fd));
};
FindClose(*hFind);
return NULL;
}
repo_t **RepoLoad(void)
{
HANDLE hFind = nullptr;
std::vector<repo_t*> repo_vector;
while (repo_t* repo = RepoLocalNext(&hFind)) {
repo_vector.push_back(repo);
}
if (repo_vector.empty()) {
return nullptr;
}
std::sort(repo_vector.begin(), repo_vector.end(), [](repo_t *a, repo_t *b) {
return strcmp(a->id, b->id) < 0;
});
size_t repo_count = repo_vector.size();
repo_t **repo_array = (repo_t**)malloc(sizeof(repo_t*) * (repo_count + 1));
repo_array[repo_count] = nullptr;
memcpy(repo_array, repo_vector.data(), sizeof(repo_t*) * repo_count);
return repo_array;
}
<|endoftext|> |
<commit_before>//---------------------------------------------------------------------------
// $Id$
// Version: $Name$
//
// Copyright (C) 2006 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------------------------------------------------------
#include <base/exceptions.h>
#include <base/memory_consumption.h>
#include <dofs/dof_objects.h>
#include <dofs/dof_handler.h>
#include <fe/fe.h>
namespace internal
{
namespace DoFHandler
{
template<int dim>
unsigned int
DoFObjects<dim>::memory_consumption () const
{
return (MemoryConsumption::memory_consumption (dofs));
}
template <int dim>
template <int spacedim>
inline
unsigned int
DoFObjects<dim>::n_active_fe_indices (const ::DoFHandler<spacedim> &,
const unsigned) const
{
return 1;
}
template <int dim>
template <int spacedim>
inline
bool
DoFObjects<dim>::fe_index_is_active (const ::DoFHandler<spacedim> &,
const unsigned int,
const unsigned int fe_index) const
{
Assert (fe_index == 0,
ExcMessage ("Only zero fe_index values are allowed for "
"non-hp DoFHandlers."));
return true;
}
template <int dim>
template <int spacedim>
unsigned int
DoFObjects<dim>::
get_dof_index (const ::DoFHandler<spacedim> &dof_handler,
const unsigned int obj_index,
const unsigned int fe_index,
const unsigned int local_index) const
{
unsigned int dofs_per_obj;
switch (dim)
{
case 1 :
dofs_per_obj = dof_handler.get_fe().dofs_per_line;
break;
case 2 :
dofs_per_obj = dof_handler.get_fe().dofs_per_quad;
break;
case 3 :
dofs_per_obj = dof_handler.get_fe().dofs_per_hex;
}
Assert (fe_index == ::DoFHandler<spacedim>::default_fe_index,
ExcMessage ("Only the default FE index is allowed for non-hp DoFHandler objects"));
Assert (local_index<dofs_per_obj,
ExcIndexRange (local_index, 0, dofs_per_obj));
Assert (obj_index * dofs_per_obj+local_index
<
dofs.size(),
ExcInternalError());
return dofs[obj_index * dofs_per_obj + local_index];
}
template <int dim>
template <int spacedim>
void
DoFObjects<dim>::
set_dof_index (const ::DoFHandler<spacedim> &dof_handler,
const unsigned int obj_index,
const unsigned int fe_index,
const unsigned int local_index,
const unsigned int global_index)
{
unsigned int dofs_per_obj;
switch (dim)
{
case 1 :
dofs_per_obj = dof_handler.get_fe().dofs_per_line;
break;
case 2 :
dofs_per_obj = dof_handler.get_fe().dofs_per_quad;
break;
case 3 :
dofs_per_obj = dof_handler.get_fe().dofs_per_hex;
}
Assert (fe_index == ::DoFHandler<spacedim>::default_fe_index,
ExcMessage ("Only the default FE index is allowed for non-hp DoFHandler objects"));
Assert (local_index<dofs_per_obj,
ExcIndexRange (local_index, 0, dof_handler.get_fe().dofs_per_line));
Assert (obj_index * dofs_per_obj+local_index
<
dofs.size(),
ExcInternalError());
dofs[obj_index * dofs_per_obj + local_index] = global_index;
}
// explicit instantiations
template
unsigned int
DoFObjects<1>::
memory_consumption () const;
template
unsigned int
DoFObjects<1>::
get_dof_index (const ::DoFHandler<deal_II_dimension> &dof_handler,
const unsigned int obj_index,
const unsigned int fe_index,
const unsigned int local_index) const;
template
void
DoFObjects<1>::
set_dof_index (const ::DoFHandler<deal_II_dimension> &dof_handler,
const unsigned int obj_index,
const unsigned int fe_index,
const unsigned int local_index,
const unsigned int global_index);
template
unsigned int
DoFObjects<1>::
n_active_fe_indices (const ::DoFHandler<deal_II_dimension> &,
const unsigned) const;
template
bool
DoFObjects<1>::
fe_index_is_active (const ::DoFHandler<deal_II_dimension> &,
const unsigned int,
const unsigned int fe_index) const;
#if deal_II_dimension >= 2
template
unsigned int
DoFObjects<2>::
memory_consumption () const;
template
unsigned int
DoFObjects<2>::
get_dof_index (const ::DoFHandler<deal_II_dimension> &dof_handler,
const unsigned int obj_index,
const unsigned int fe_index,
const unsigned int local_index) const;
template
void
DoFObjects<2>::
set_dof_index (const ::DoFHandler<deal_II_dimension> &dof_handler,
const unsigned int obj_index,
const unsigned int fe_index,
const unsigned int local_index,
const unsigned int global_index);
template
unsigned int
DoFObjects<2>::
n_active_fe_indices (const ::DoFHandler<deal_II_dimension> &,
const unsigned) const;
template
bool
DoFObjects<2>::
fe_index_is_active (const ::DoFHandler<deal_II_dimension> &,
const unsigned int,
const unsigned int fe_index) const;
#endif
#if deal_II_dimension >= 3
template
unsigned int
DoFObjects<3>::
memory_consumption () const;
template
unsigned int
DoFObjects<3>::
get_dof_index (const ::DoFHandler<deal_II_dimension> &dof_handler,
const unsigned int obj_index,
const unsigned int fe_index,
const unsigned int local_index) const;
template
void
DoFObjects<3>::
set_dof_index (const ::DoFHandler<deal_II_dimension> &dof_handler,
const unsigned int obj_index,
const unsigned int fe_index,
const unsigned int local_index,
const unsigned int global_index);
template
unsigned int
DoFObjects<3>::
n_active_fe_indices (const ::DoFHandler<deal_II_dimension> &,
const unsigned) const;
template
bool
DoFObjects<3>::
fe_index_is_active (const ::DoFHandler<deal_II_dimension> &,
const unsigned int,
const unsigned int fe_index) const;
#endif
}
}
<commit_msg>Remove inlines to avoid icc8's undefined reference to DoFObjects::n_active_fe_indices. Clean up.<commit_after>//---------------------------------------------------------------------------
// $Id$
// Version: $Name$
//
// Copyright (C) 2006 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------------------------------------------------------
#include <base/exceptions.h>
#include <base/memory_consumption.h>
#include <dofs/dof_objects.h>
#include <dofs/dof_handler.h>
#include <fe/fe.h>
namespace internal
{
namespace DoFHandler
{
template<int dim>
unsigned int
DoFObjects<dim>::memory_consumption () const
{
return (MemoryConsumption::memory_consumption (dofs));
}
template <int dim>
template <int spacedim>
unsigned int
DoFObjects<dim>::n_active_fe_indices (const ::DoFHandler<spacedim> &,
const unsigned) const
{
return 1;
}
template <int dim>
template <int spacedim>
bool
DoFObjects<dim>::fe_index_is_active (const ::DoFHandler<spacedim> &,
const unsigned int,
const unsigned int fe_index) const
{
Assert (fe_index == 0,
ExcMessage ("Only zero fe_index values are allowed for "
"non-hp DoFHandlers."));
return true;
}
template <int dim>
template <int spacedim>
unsigned int
DoFObjects<dim>::
get_dof_index (const ::DoFHandler<spacedim> &dof_handler,
const unsigned int obj_index,
const unsigned int fe_index,
const unsigned int local_index) const
{
unsigned int dofs_per_obj;
switch (dim)
{
case 1 :
dofs_per_obj = dof_handler.get_fe().dofs_per_line;
break;
case 2 :
dofs_per_obj = dof_handler.get_fe().dofs_per_quad;
break;
case 3 :
dofs_per_obj = dof_handler.get_fe().dofs_per_hex;
}
Assert (fe_index == ::DoFHandler<spacedim>::default_fe_index,
ExcMessage ("Only the default FE index is allowed for non-hp DoFHandler objects"));
Assert (local_index<dofs_per_obj,
ExcIndexRange (local_index, 0, dofs_per_obj));
Assert (obj_index * dofs_per_obj+local_index
<
dofs.size(),
ExcInternalError());
return dofs[obj_index * dofs_per_obj + local_index];
}
template <int dim>
template <int spacedim>
void
DoFObjects<dim>::
set_dof_index (const ::DoFHandler<spacedim> &dof_handler,
const unsigned int obj_index,
const unsigned int fe_index,
const unsigned int local_index,
const unsigned int global_index)
{
unsigned int dofs_per_obj;
switch (dim)
{
case 1 :
dofs_per_obj = dof_handler.get_fe().dofs_per_line;
break;
case 2 :
dofs_per_obj = dof_handler.get_fe().dofs_per_quad;
break;
case 3 :
dofs_per_obj = dof_handler.get_fe().dofs_per_hex;
}
Assert (fe_index == ::DoFHandler<spacedim>::default_fe_index,
ExcMessage ("Only the default FE index is allowed for non-hp DoFHandler objects"));
Assert (local_index<dofs_per_obj,
ExcIndexRange (local_index, 0, dof_handler.get_fe().dofs_per_line));
Assert (obj_index * dofs_per_obj+local_index
<
dofs.size(),
ExcInternalError());
dofs[obj_index * dofs_per_obj + local_index] = global_index;
}
// explicit instantiations
template class DoFObjects<1>;
template
unsigned int
DoFObjects<1>::
get_dof_index (const ::DoFHandler<deal_II_dimension> &dof_handler,
const unsigned int obj_index,
const unsigned int fe_index,
const unsigned int local_index) const;
template
void
DoFObjects<1>::
set_dof_index (const ::DoFHandler<deal_II_dimension> &dof_handler,
const unsigned int obj_index,
const unsigned int fe_index,
const unsigned int local_index,
const unsigned int global_index);
template
unsigned int
DoFObjects<1>::
n_active_fe_indices (const ::DoFHandler<deal_II_dimension> &,
const unsigned) const;
template
bool
DoFObjects<1>::
fe_index_is_active (const ::DoFHandler<deal_II_dimension> &,
const unsigned int,
const unsigned int fe_index) const;
#if deal_II_dimension >= 2
template class DoFObjects<2>;
template
unsigned int
DoFObjects<2>::
get_dof_index (const ::DoFHandler<deal_II_dimension> &dof_handler,
const unsigned int obj_index,
const unsigned int fe_index,
const unsigned int local_index) const;
template
void
DoFObjects<2>::
set_dof_index (const ::DoFHandler<deal_II_dimension> &dof_handler,
const unsigned int obj_index,
const unsigned int fe_index,
const unsigned int local_index,
const unsigned int global_index);
template
unsigned int
DoFObjects<2>::
n_active_fe_indices (const ::DoFHandler<deal_II_dimension> &,
const unsigned) const;
template
bool
DoFObjects<2>::
fe_index_is_active (const ::DoFHandler<deal_II_dimension> &,
const unsigned int,
const unsigned int fe_index) const;
#endif
#if deal_II_dimension >= 3
template class DoFObjects<3>;
template
unsigned int
DoFObjects<3>::
get_dof_index (const ::DoFHandler<deal_II_dimension> &dof_handler,
const unsigned int obj_index,
const unsigned int fe_index,
const unsigned int local_index) const;
template
void
DoFObjects<3>::
set_dof_index (const ::DoFHandler<deal_II_dimension> &dof_handler,
const unsigned int obj_index,
const unsigned int fe_index,
const unsigned int local_index,
const unsigned int global_index);
template
unsigned int
DoFObjects<3>::
n_active_fe_indices (const ::DoFHandler<deal_II_dimension> &,
const unsigned) const;
template
bool
DoFObjects<3>::
fe_index_is_active (const ::DoFHandler<deal_II_dimension> &,
const unsigned int,
const unsigned int fe_index) const;
#endif
}
}
<|endoftext|> |
<commit_before><include stdio.h>
project element static[object(slider) {
slider.static.Movable.object(for {user::prefs} meta::element)
} if [[element.slider: IOerror(pre: set, re-set: center)].post:'./makefile'];
<commit_msg>Update file property.cpp<commit_after><include stdio.h>
project element static[object(slider) {
slider.static.Movable.object(for {user::prefs} meta::element)
} if [[element.slider: IOerror(pre: set, re-set: center)].post:'./makefile'];
else [[ property.element(construct::meta, _init_, propert: null, event: (ev:EventArgs()))
]]
<|endoftext|> |
<commit_before>#pragma once
#ifndef SOLVER_LBFGS_ATLAS_HPP
#define SOLVER_LBFGS_ATLAS_HPP
#include <utility/Constants.hpp>
// #include <utility/Exception.hpp>
#include <engine/Backend_par.hpp>
#include <algorithm>
using namespace Utility;
template <> inline
void Method_Solver<Solver::LBFGS_Atlas>::Initialize ()
{
this->n_lbfgs_memory = 3; // how many updates the solver tracks to estimate the hessian
this->atlas_updates = std::vector<field<vector2field>>( this->noi, field<vector2field>( this->n_lbfgs_memory, vector2field(this->nos, { 0,0 } ) ));
this->grad_atlas_updates = std::vector<field<vector2field>>( this->noi, field<vector2field>( this->n_lbfgs_memory, vector2field(this->nos, { 0,0 } ) ));
this->rho = scalarfield( this->n_lbfgs_memory, 0 );
this->alpha = scalarfield( this->n_lbfgs_memory, 0 );
this->forces = std::vector<vectorfield>( this->noi, vectorfield( this->nos, { 0,0,0 } ) );
this->forces_virtual = std::vector<vectorfield>( this->noi, vectorfield( this->nos, { 0,0,0 } ) );
this->atlas_coords3 = std::vector<scalarfield>( this->noi, scalarfield(this->nos, 1) );
this->atlas_directions = std::vector<vector2field>( this->noi, vector2field( this->nos, { 0,0 } ) );
this->atlas_residuals = std::vector<vector2field>( this->noi, vector2field( this->nos, { 0,0 } ) );
this->atlas_residuals_last = std::vector<vector2field>( this->noi, vector2field( this->nos, { 0,0 } ) );
this->atlas_q_vec = std::vector<vector2field>( this->noi, vector2field( this->nos, { 0,0 } ) );
this->maxmove = 0.05;
this->local_iter = 0;
for (int img=0; img<this->noi; img++)
{
// Choose atlas3 coordinates
for(int i=0; i<this->nos; i++)
{
this->atlas_coords3[img][i] = (*this->configurations[img])[i][2] > 0 ? 1.0 : -1.0;
// Solver_Kernels::ncg_spins_to_atlas( *this->configurations[i], this->atlas_coords[i], this->atlas_coords3[i] );
}
}
}
/*
Stereographic coordinate system implemented according to an idea of F. Rybakov
TODO: reference painless conjugate gradients
See also Jorge Nocedal and Stephen J. Wright 'Numerical Optimization' Second Edition, 2006 (p. 121)
*/
template <> inline
void Method_Solver<Solver::LBFGS_Atlas>::Iteration()
{
int noi = configurations.size();
int nos = (*configurations[0]).size();
// Current force
this->Calculate_Force( this->configurations, this->forces );
for( int img=0; img<this->noi; img++ )
{
auto& image = *this->configurations[img];
auto& grad_ref = this->atlas_residuals[img];
auto fv = this->forces_virtual[img].data();
auto f = this->forces[img].data();
auto s = image.data();
Backend::par::apply( this->nos, [f,fv,s] SPIRIT_LAMBDA (int idx) {
fv[idx] = s[idx].cross(f[idx]);
} );
Solver_Kernels::atlas_calc_gradients(grad_ref, image, this->forces[img], this->atlas_coords3[img]);
}
// Calculate search direction
Solver_Kernels::lbfgs_get_searchdir(this->local_iter,
this->rho, this->alpha, this->atlas_q_vec,
this->atlas_directions, this->atlas_updates,
this->grad_atlas_updates, this->atlas_residuals, this->atlas_residuals_last,
this->n_lbfgs_memory, maxmove);
scalar a_norm_rms = 0;
// Scale by averaging
for(int img=0; img<noi; img++)
{
a_norm_rms = std::max(a_norm_rms, sqrt( Backend::par::reduce(this->atlas_directions[img], [] SPIRIT_LAMBDA (const Vector2 & v){ return v.squaredNorm(); }) / nos ));
}
scalar scaling = (a_norm_rms > maxmove) ? maxmove/a_norm_rms : 1.0;
for(int img=0; img<noi; img++)
{
auto d = atlas_directions[img].data();
Backend::par::apply(nos, [scaling, d] SPIRIT_LAMBDA (int idx){
d[idx] *= scaling;
});
}
// Rotate spins
Solver_Kernels::atlas_rotate( this->configurations, this->atlas_coords3, this->atlas_directions );
if(Solver_Kernels::ncg_atlas_check_coordinates(this->configurations, this->atlas_coords3, -0.6))
{
Solver_Kernels::lbfgs_atlas_transform_direction(this->configurations, this->atlas_coords3, this->atlas_updates, this->grad_atlas_updates, this->atlas_directions, this->atlas_residuals_last, this->rho);
}
}
template <> inline
std::string Method_Solver<Solver::LBFGS_Atlas>::SolverName()
{
return "LBFGS_Atlas";
}
template <> inline
std::string Method_Solver<Solver::LBFGS_Atlas>::SolverFullName()
{
return "Limited memory Broyden-Fletcher-Goldfarb-Shanno using stereographic atlas";
}
#endif<commit_msg>Core: Fixed compilation error when using float + CPU<commit_after>#pragma once
#ifndef SOLVER_LBFGS_ATLAS_HPP
#define SOLVER_LBFGS_ATLAS_HPP
#include <utility/Constants.hpp>
// #include <utility/Exception.hpp>
#include <engine/Backend_par.hpp>
#include <algorithm>
using namespace Utility;
template <> inline
void Method_Solver<Solver::LBFGS_Atlas>::Initialize ()
{
this->n_lbfgs_memory = 3; // how many updates the solver tracks to estimate the hessian
this->atlas_updates = std::vector<field<vector2field>>( this->noi, field<vector2field>( this->n_lbfgs_memory, vector2field(this->nos, { 0,0 } ) ));
this->grad_atlas_updates = std::vector<field<vector2field>>( this->noi, field<vector2field>( this->n_lbfgs_memory, vector2field(this->nos, { 0,0 } ) ));
this->rho = scalarfield( this->n_lbfgs_memory, 0 );
this->alpha = scalarfield( this->n_lbfgs_memory, 0 );
this->forces = std::vector<vectorfield>( this->noi, vectorfield( this->nos, { 0,0,0 } ) );
this->forces_virtual = std::vector<vectorfield>( this->noi, vectorfield( this->nos, { 0,0,0 } ) );
this->atlas_coords3 = std::vector<scalarfield>( this->noi, scalarfield(this->nos, 1) );
this->atlas_directions = std::vector<vector2field>( this->noi, vector2field( this->nos, { 0,0 } ) );
this->atlas_residuals = std::vector<vector2field>( this->noi, vector2field( this->nos, { 0,0 } ) );
this->atlas_residuals_last = std::vector<vector2field>( this->noi, vector2field( this->nos, { 0,0 } ) );
this->atlas_q_vec = std::vector<vector2field>( this->noi, vector2field( this->nos, { 0,0 } ) );
this->maxmove = 0.05;
this->local_iter = 0;
for (int img=0; img<this->noi; img++)
{
// Choose atlas3 coordinates
for(int i=0; i<this->nos; i++)
{
this->atlas_coords3[img][i] = (*this->configurations[img])[i][2] > 0 ? 1.0 : -1.0;
// Solver_Kernels::ncg_spins_to_atlas( *this->configurations[i], this->atlas_coords[i], this->atlas_coords3[i] );
}
}
}
/*
Stereographic coordinate system implemented according to an idea of F. Rybakov
TODO: reference painless conjugate gradients
See also Jorge Nocedal and Stephen J. Wright 'Numerical Optimization' Second Edition, 2006 (p. 121)
*/
template <> inline
void Method_Solver<Solver::LBFGS_Atlas>::Iteration()
{
int noi = configurations.size();
int nos = (*configurations[0]).size();
// Current force
this->Calculate_Force( this->configurations, this->forces );
for( int img=0; img<this->noi; img++ )
{
auto& image = *this->configurations[img];
auto& grad_ref = this->atlas_residuals[img];
auto fv = this->forces_virtual[img].data();
auto f = this->forces[img].data();
auto s = image.data();
Backend::par::apply( this->nos, [f,fv,s] SPIRIT_LAMBDA (int idx) {
fv[idx] = s[idx].cross(f[idx]);
} );
Solver_Kernels::atlas_calc_gradients(grad_ref, image, this->forces[img], this->atlas_coords3[img]);
}
// Calculate search direction
Solver_Kernels::lbfgs_get_searchdir(this->local_iter,
this->rho, this->alpha, this->atlas_q_vec,
this->atlas_directions, this->atlas_updates,
this->grad_atlas_updates, this->atlas_residuals, this->atlas_residuals_last,
this->n_lbfgs_memory, maxmove);
scalar a_norm_rms = 0;
// Scale by averaging
for(int img=0; img<noi; img++)
{
a_norm_rms = std::max(a_norm_rms, scalar( sqrt( Backend::par::reduce(this->atlas_directions[img], [] SPIRIT_LAMBDA (const Vector2 & v){ return v.squaredNorm(); }) / nos )));
}
scalar scaling = (a_norm_rms > maxmove) ? maxmove/a_norm_rms : 1.0;
for(int img=0; img<noi; img++)
{
auto d = atlas_directions[img].data();
Backend::par::apply(nos, [scaling, d] SPIRIT_LAMBDA (int idx){
d[idx] *= scaling;
});
}
// Rotate spins
Solver_Kernels::atlas_rotate( this->configurations, this->atlas_coords3, this->atlas_directions );
if(Solver_Kernels::ncg_atlas_check_coordinates(this->configurations, this->atlas_coords3, -0.6))
{
Solver_Kernels::lbfgs_atlas_transform_direction(this->configurations, this->atlas_coords3, this->atlas_updates, this->grad_atlas_updates, this->atlas_directions, this->atlas_residuals_last, this->rho);
}
}
template <> inline
std::string Method_Solver<Solver::LBFGS_Atlas>::SolverName()
{
return "LBFGS_Atlas";
}
template <> inline
std::string Method_Solver<Solver::LBFGS_Atlas>::SolverFullName()
{
return "Limited memory Broyden-Fletcher-Goldfarb-Shanno using stereographic atlas";
}
#endif<|endoftext|> |
<commit_before>#include "problem.h"
#include "factor.h"
#include <time.h>
double prediction_time = 0.0;
extern Stats* stats;
bool debug = false;
void exit_with_help(){
cerr << "Usage: ./predict (options) [testfile] [model]" << endl;
cerr << "options:" << endl;
cerr << "-s solver: (default 0)" << endl;
cerr << " 0 -- Viterbi(chain)" << endl;
cerr << " 1 -- sparseLP" << endl;
cerr << " 2 -- GDMM" << endl;
cerr << "-p problem_type: " << endl;
cerr << " chain -- sequence labeling problem" << endl;
cerr << " network -- network matching problem" << endl;
cerr << " uai -- uai format problem" << endl;
cerr << "-e eta: GDMM step size" << endl;
cerr << "-o rho: coefficient/weight of message" << endl;
cerr << "-m max_iter: max number of iterations" << endl;
exit(0);
}
void parse_cmd_line(int argc, char** argv, Param* param){
int i;
vector<string> args;
for (i = 1; i < argc; i++){
string arg(argv[i]);
//cerr << "arg[i]:" << arg << "|" << endl;
args.push_back(arg);
}
for(i=0;i<args.size();i++){
string arg = args[i];
if (arg == "-debug"){
debug = true;
continue;
}
if( arg[0] != '-' )
break;
if( ++i >= args.size() )
exit_with_help();
string arg2 = args[i];
if (arg == "--printmodel"){
param->print_to_loguai2 = true;
param->loguai2fname = arg2;
continue;
}
switch(arg[1]){
case 's': param->solver = stoi(arg2);
break;
case 'e': param->eta = stof(arg2);
break;
case 'o': param->rho = stof(arg2);
break;
case 'm': param->max_iter = stoi(arg2);
break;
case 'p': param->problem_type = string(arg2);
break;
default:
cerr << "unknown option: " << arg << " " << arg2 << endl;
exit(0);
}
}
if(i>=args.size())
exit_with_help();
param->testFname = argv[i+1];
i++;
if( i<args.size() )
param->modelFname = argv[i+1];
else{
param->modelFname = new char[FNAME_LEN];
strcpy(param->modelFname,"model");
}
}
double struct_predict(Problem* prob, Param* param){
Float hit = 0.0;
Float N = 0.0;
int n = 0;
stats = new Stats();
int K = prob->K;
cout << "constructing factors...";
vector<UniFactor*> x;
for (int i = 0; i < K; i++){
UniFactor* x_i = new UniFactor(K, prob->node_score_vecs[i], param);
x.push_back(x_i);
}
vector<UniFactor*> xt;
for (int i = 0; i < K; i++){
UniFactor* xt_i = new UniFactor(K, prob->node_score_vecs[K+i], param);
xt.push_back(xt_i);
}
cout << "done" << endl;
//////////////////////////////////////
// get row solutions
/////////////////////////////////////
//ifstream fin("data/rowsol");
//int* rowsol = new int[K];
//int* colsol = new int[K];
//int max_top = 0;
//Float row_cost = 0.0;
//Float col_cost = 0.0;
//Float avg_top = 0.0;
/*for( int k = 0; k < K; k++){
fin >> colsol[k];
colsol[k]--;
rowsol[colsol[k]] = k;
for(int i = 0; i < K; i++){
if (x[colsol[k]]->sorted_index[i].second == k){
if (max_top < i){
max_top = i;
}
avg_top += i;
row_cost += x[colsol[k]]->sorted_index[i].first;
break;
}
}
for(int i = 0; i < K; i++){
if (xt[k]->sorted_index[i].second == colsol[k]){
if (max_top < i){
max_top = i;
}
avg_top += i;
col_cost += xt[k]->sorted_index[i].first;
break;
}
}
}*/
//cout << "row_cost=" << row_cost << ", col_cost=" << col_cost << endl;
//cout << "max_top="<< max_top << ", avg_top=" << avg_top/(2*K)<< endl;
int iter = 0;
Float rho = param->rho;
int* indices = new int[K*2];
for (int i = 0; i < K*2; i++){
indices[i] = i;
}
bool* taken = new bool[K];
Float best_decoded = 1e100;
while (iter++ < param->max_iter){
stats->maintain_time -= get_current_time();
//random_shuffle(indices, indices+K*2);
stats->maintain_time += get_current_time();
Float act_size_sum = 0;
Float ever_nnz_size_sum = 0;
Float recall_rate = 0.0;
for (int k = 0; k < K*2; k++){
if (k % 2 == 0){
int i = k/2;
UniFactor* node = x[i];
//if (node->inside[rowsol[i]]){
// recall_rate += 1.0;
//} else {
// node->act_set.push_back(rowsol[i]);
// node->inside[rowsol[i]] = true;
//}
//add a new coordinate into active set
node->search();
//given active set, solve subproblem
node->subsolve();
act_size_sum += node->act_set.size();
ever_nnz_size_sum += node->ever_nnz_msg.size();
stats->maintain_time -= get_current_time();
Float* msg = node->msg;
Float* y = node->y;
for (vector<int>::iterator it = node->act_set.begin(); it != node->act_set.end(); it++){
int j = *it;
xt[j]->msg[i] = -msg[j];
if (abs(msg[j]) > 1e-12){
xt[j]->add_ever_nnz(i);
}
}
stats->maintain_time += get_current_time();
} else {
int j = k/2;
UniFactor* node = xt[j];
//if (node->inside[colsol[j]]){
// recall_rate += 1.0;
//} else {
// node->act_set.push_back(colsol[j]);
// node->inside[colsol[j]] = true;
//}
node->search();
node->subsolve();
act_size_sum += node->act_set.size();
ever_nnz_size_sum += node->ever_nnz_msg.size();
stats->maintain_time -= get_current_time();
Float* msg = node->msg;
Float* y = node->y;
for (vector<int>::iterator it = node->act_set.begin(); it != node->act_set.end(); it++){
int i = *it;
x[i]->msg[j] = -msg[i];
if (abs(msg[i]) > 1e-12){
x[i]->add_ever_nnz(j);
}
}
stats->maintain_time += get_current_time();
}
}
// msg[i] = (x[i][j] - xt[j][i] + mu[i][j])
// msg[i] = (x[i][j] - xt[j][i] + mu[i][j])
stats->maintain_time -= get_current_time();
for (int i = 0; i < K; i++){
for (vector<int>::iterator it = x[i]->act_set.begin(); it != x[i]->act_set.end(); it++){
int j = *it;
Float delta = x[i]->y[j];
x[i]->msg[j] += delta;
xt[j]->msg[i] -= delta;
if (abs(x[i]->msg[j]) > 1e-12){
x[i]->add_ever_nnz(j);
xt[j]->add_ever_nnz(i);
}
}
}
for (int j = 0; j < K; j++){
for (vector<int>::iterator it = xt[j]->act_set.begin(); it != xt[j]->act_set.end(); it++){
int i = *it;
Float delta = -xt[j]->y[i];
x[i]->msg[j] += delta;
xt[j]->msg[i] -= delta;
if (abs(x[i]->msg[j]) > 1e-12){
x[i]->add_ever_nnz(j);
xt[j]->add_ever_nnz(i);
}
}
}
Float cost = 0.0, infea = 0.0;
for (int i = 0; i < K; i++){
for (vector<int>::iterator it = x[i]->act_set.begin(); it != x[i]->act_set.end(); it++){
int j = *it;
cost += x[i]->y[j] * x[i]->c[j];
infea += abs(xt[j]->y[i] - x[i]->y[j]);
//cout << x[i]->y[j] << "\t";
}
}
for (int j = 0; j < K; j++){
for (vector<int>::iterator it = xt[j]->act_set.begin(); it != xt[j]->act_set.end(); it++){
int i = *it;
cost += xt[j]->y[i] * xt[j]->c[i];
infea += abs(xt[j]->y[i] - x[i]->y[j]);
//cout << xt[j]->y[i] << "\t";
}
//cout << endl;
}
if (iter % 1 == 0){
memset(taken, false, sizeof(bool)*K);
Float decoded = 0.0;
random_shuffle(indices, indices+K*2);
for (int k = 0; k < K*2; k++){
if (indices[k] >= K){
continue;
}
int i = indices[k];
Float max_y = 0.0;
int index = -1;
for (vector<int>::iterator it = x[i]->act_set.begin(); it != x[i]->act_set.end(); it++){
int j = *it;
if (!taken[j] && (x[i]->y[j] > max_y)){
max_y = x[i]->y[j];
index = j;
}
}
if (index == -1){
for (int j = 0; j < K; j++){
if (!taken[j]){
index = j;
break;
}
}
}
taken[index] = true;
decoded += x[i]->c[index];
}
if (decoded < best_decoded){
best_decoded = decoded;
}
}
stats->maintain_time += get_current_time();
//cout << endl;
cout << "iter=" << iter;
cout << ", recall_rate=" << recall_rate/(2*K);
cout << ", act_size=" << act_size_sum/(2*K);
cout << ", ever_nnz_size=" << ever_nnz_size_sum/(2*K);
cout << ", cost=" << cost/2.0 << ", infea=" << infea << ", best_decoded=" << best_decoded;
cout << ", search=" << stats->uni_search_time;
cout << ", subsolve=" << stats->uni_subsolve_time;
cout << ", maintain=" << stats->maintain_time;
cout << endl;
if (infea < 1e-5){
break;
}
}
delete taken;
return 0;
}
int main(int argc, char** argv){
if (argc < 2){
exit_with_help();
}
prediction_time = -get_current_time();
srand(time(NULL));
Param* param = new Param();
parse_cmd_line(argc, argv, param);
Problem* prob = NULL;
if (param->problem_type=="bipartite"){
prob = new BipartiteMatchingProblem(param);
prob->construct_data();
int K = ((BipartiteMatchingProblem*)prob)->K;
cerr << "prob.K=" << K << endl;
}
if (prob == NULL){
cerr << "Need to specific problem type!" << endl;
}
cerr << "param.rho=" << param->rho << endl;
cerr << "param.eta=" << param->eta << endl;
/*
double t1 = get_current_time();
vector<Float*> cc;
for (int i = 0; i < 200; i++){
Float* temp_float = new Float[4];
cc.push_back(temp_float);
}
for (int tt = 0; tt < 3000*1000; tt++)
for (int i = 0; i < 200; i++){
Float* cl = cc[rand()%200];
Float* cr = cc[rand()%200];
for (int j = 0; j < 4; j++)
cl[j] = cr[j];
}
cerr << get_current_time() - t1 << endl;
*/
if (param->solver == 2){
cerr << "Acc=" << struct_predict(prob, param) << endl;
}
prediction_time += get_current_time();
cerr << "prediction time=" << prediction_time << endl;
return 0;
}
<commit_msg>add some comment.<commit_after>#include "problem.h"
#include "factor.h"
#include <time.h>
double prediction_time = 0.0;
extern Stats* stats;
bool debug = false;
void exit_with_help(){
cerr << "Usage: ./predict (options) [testfile] [model]" << endl;
cerr << "options:" << endl;
cerr << "-s solver: (default 0)" << endl;
cerr << " 0 -- Viterbi(chain)" << endl;
cerr << " 1 -- sparseLP" << endl;
cerr << " 2 -- GDMM" << endl;
cerr << "-p problem_type: " << endl;
cerr << " chain -- sequence labeling problem" << endl;
cerr << " network -- network matching problem" << endl;
cerr << " uai -- uai format problem" << endl;
cerr << "-e eta: GDMM step size" << endl;
cerr << "-o rho: coefficient/weight of message" << endl;
cerr << "-m max_iter: max number of iterations" << endl;
exit(0);
}
void parse_cmd_line(int argc, char** argv, Param* param){
int i;
vector<string> args;
for (i = 1; i < argc; i++){
string arg(argv[i]);
//cerr << "arg[i]:" << arg << "|" << endl;
args.push_back(arg);
}
for(i=0;i<args.size();i++){
string arg = args[i];
if (arg == "-debug"){
debug = true;
continue;
}
if( arg[0] != '-' )
break;
if( ++i >= args.size() )
exit_with_help();
string arg2 = args[i];
if (arg == "--printmodel"){
param->print_to_loguai2 = true;
param->loguai2fname = arg2;
continue;
}
switch(arg[1]){
case 's': param->solver = stoi(arg2);
break;
case 'e': param->eta = stof(arg2);
break;
case 'o': param->rho = stof(arg2);
break;
case 'm': param->max_iter = stoi(arg2);
break;
case 'p': param->problem_type = string(arg2);
break;
default:
cerr << "unknown option: " << arg << " " << arg2 << endl;
exit(0);
}
}
if(i>=args.size())
exit_with_help();
param->testFname = argv[i+1];
i++;
if( i<args.size() )
param->modelFname = argv[i+1];
else{
param->modelFname = new char[FNAME_LEN];
strcpy(param->modelFname,"model");
}
}
double struct_predict(Problem* prob, Param* param){
Float hit = 0.0;
Float N = 0.0;
int n = 0;
stats = new Stats();
int K = prob->K;
cout << "constructing factors...";
vector<UniFactor*> x; //x is the permutation matrix sliced depend on rows.
for (int i = 0; i < K; i++){
UniFactor* x_i = new UniFactor(K, prob->node_score_vecs[i], param);
x.push_back(x_i);
}
vector<UniFactor*> xt;
for (int i = 0; i < K; i++){
UniFactor* xt_i = new UniFactor(K, prob->node_score_vecs[K+i], param);
xt.push_back(xt_i);
}
cout << "done" << endl;
//////////////////////////////////////
// get row solutions
/////////////////////////////////////
//ifstream fin("data/rowsol");
//int* rowsol = new int[K];
//int* colsol = new int[K];
//int max_top = 0;
//Float row_cost = 0.0;
//Float col_cost = 0.0;
//Float avg_top = 0.0;
/*for( int k = 0; k < K; k++){
fin >> colsol[k];
colsol[k]--;
rowsol[colsol[k]] = k;
for(int i = 0; i < K; i++){
if (x[colsol[k]]->sorted_index[i].second == k){
if (max_top < i){
max_top = i;
}
avg_top += i;
row_cost += x[colsol[k]]->sorted_index[i].first;
break;
}
}
for(int i = 0; i < K; i++){
if (xt[k]->sorted_index[i].second == colsol[k]){
if (max_top < i){
max_top = i;
}
avg_top += i;
col_cost += xt[k]->sorted_index[i].first;
break;
}
}
}*/
//cout << "row_cost=" << row_cost << ", col_cost=" << col_cost << endl;
//cout << "max_top="<< max_top << ", avg_top=" << avg_top/(2*K)<< endl;
int iter = 0;
Float rho = param->rho;
int* indices = new int[K*2];
for (int i = 0; i < K*2; i++){
indices[i] = i;
}
bool* taken = new bool[K];
Float best_decoded = 1e100;
while (iter++ < param->max_iter){
stats->maintain_time -= get_current_time();
//random_shuffle(indices, indices+K*2);
stats->maintain_time += get_current_time();
Float act_size_sum = 0;
Float ever_nnz_size_sum = 0;
Float recall_rate = 0.0;
for (int k = 0; k < K*2; k++){
if (k % 2 == 0){
int i = k/2;
UniFactor* node = x[i];
//if (node->inside[rowsol[i]]){
// recall_rate += 1.0;
//} else {
// node->act_set.push_back(rowsol[i]);
// node->inside[rowsol[i]] = true;
//}
//add a new coordinate into active set
node->search();
//given active set, solve subproblem
node->subsolve();
act_size_sum += node->act_set.size();
ever_nnz_size_sum += node->ever_nnz_msg.size();
stats->maintain_time -= get_current_time();
Float* msg = node->msg;
Float* y = node->y;
for (vector<int>::iterator it = node->act_set.begin(); it != node->act_set.end(); it++){
int j = *it;
xt[j]->msg[i] = -msg[j];
if (abs(msg[j]) > 1e-12){
xt[j]->add_ever_nnz(i);
}
}
stats->maintain_time += get_current_time();
} else {
int j = k/2;
UniFactor* node = xt[j];
//if (node->inside[colsol[j]]){
// recall_rate += 1.0;
//} else {
// node->act_set.push_back(colsol[j]);
// node->inside[colsol[j]] = true;
//}
node->search();
node->subsolve();
act_size_sum += node->act_set.size();
ever_nnz_size_sum += node->ever_nnz_msg.size();
stats->maintain_time -= get_current_time();
Float* msg = node->msg;
Float* y = node->y;
for (vector<int>::iterator it = node->act_set.begin(); it != node->act_set.end(); it++){
int i = *it;
x[i]->msg[j] = -msg[i];
if (abs(msg[i]) > 1e-12){
x[i]->add_ever_nnz(j);
}
}
stats->maintain_time += get_current_time();
}
}
// msg[i] = (x[i][j] - xt[j][i] + mu[i][j])
// msg[i] = (x[i][j] - xt[j][i] + mu[i][j])
stats->maintain_time -= get_current_time();
for (int i = 0; i < K; i++){
for (vector<int>::iterator it = x[i]->act_set.begin(); it != x[i]->act_set.end(); it++){
int j = *it;
Float delta = x[i]->y[j];
x[i]->msg[j] += delta;
xt[j]->msg[i] -= delta;
if (abs(x[i]->msg[j]) > 1e-12){
x[i]->add_ever_nnz(j);
xt[j]->add_ever_nnz(i);
}
}
}
for (int j = 0; j < K; j++){
for (vector<int>::iterator it = xt[j]->act_set.begin(); it != xt[j]->act_set.end(); it++){
int i = *it;
Float delta = -xt[j]->y[i];
x[i]->msg[j] += delta;
xt[j]->msg[i] -= delta;
if (abs(x[i]->msg[j]) > 1e-12){
x[i]->add_ever_nnz(j);
xt[j]->add_ever_nnz(i);
}
}
}
Float cost = 0.0, infea = 0.0;
for (int i = 0; i < K; i++){
for (vector<int>::iterator it = x[i]->act_set.begin(); it != x[i]->act_set.end(); it++){
int j = *it;
cost += x[i]->y[j] * x[i]->c[j];
infea += abs(xt[j]->y[i] - x[i]->y[j]);
//cout << x[i]->y[j] << "\t";
}
}
for (int j = 0; j < K; j++){
for (vector<int>::iterator it = xt[j]->act_set.begin(); it != xt[j]->act_set.end(); it++){
int i = *it;
cost += xt[j]->y[i] * xt[j]->c[i];
infea += abs(xt[j]->y[i] - x[i]->y[j]);
//cout << xt[j]->y[i] << "\t";
}
//cout << endl;
}
if (iter % 1 == 0){
memset(taken, false, sizeof(bool)*K);
Float decoded = 0.0;
random_shuffle(indices, indices+K*2);
for (int k = 0; k < K*2; k++){
if (indices[k] >= K){
continue;
}
int i = indices[k];
Float max_y = 0.0;
int index = -1;
for (vector<int>::iterator it = x[i]->act_set.begin(); it != x[i]->act_set.end(); it++){
int j = *it;
if (!taken[j] && (x[i]->y[j] > max_y)){
max_y = x[i]->y[j];
index = j;
}
}
if (index == -1){
for (int j = 0; j < K; j++){
if (!taken[j]){
index = j;
break;
}
}
}
taken[index] = true;
decoded += x[i]->c[index];
}
if (decoded < best_decoded){
best_decoded = decoded;
}
}
stats->maintain_time += get_current_time();
//cout << endl;
cout << "iter=" << iter;
cout << ", recall_rate=" << recall_rate/(2*K);
cout << ", act_size=" << act_size_sum/(2*K);
cout << ", ever_nnz_size=" << ever_nnz_size_sum/(2*K);
cout << ", cost=" << cost/2.0 << ", infea=" << infea << ", best_decoded=" << best_decoded;
cout << ", search=" << stats->uni_search_time;
cout << ", subsolve=" << stats->uni_subsolve_time;
cout << ", maintain=" << stats->maintain_time;
cout << endl;
if (infea < 1e-5){
break;
}
}
delete taken;
return 0;
}
int main(int argc, char** argv){
if (argc < 2){
exit_with_help();
}
prediction_time = -get_current_time();
srand(time(NULL));
Param* param = new Param();
parse_cmd_line(argc, argv, param);
Problem* prob = NULL;
if (param->problem_type=="bipartite"){
prob = new BipartiteMatchingProblem(param);
prob->construct_data();
int K = ((BipartiteMatchingProblem*)prob)->K;
cerr << "prob.K=" << K << endl;
}
if (prob == NULL){
cerr << "Need to specific problem type!" << endl;
}
cerr << "param.rho=" << param->rho << endl;
cerr << "param.eta=" << param->eta << endl;
/*
double t1 = get_current_time();
vector<Float*> cc;
for (int i = 0; i < 200; i++){
Float* temp_float = new Float[4];
cc.push_back(temp_float);
}
for (int tt = 0; tt < 3000*1000; tt++)
for (int i = 0; i < 200; i++){
Float* cl = cc[rand()%200];
Float* cr = cc[rand()%200];
for (int j = 0; j < 4; j++)
cl[j] = cr[j];
}
cerr << get_current_time() - t1 << endl;
*/
if (param->solver == 2){
cerr << "Acc=" << struct_predict(prob, param) << endl;
}
prediction_time += get_current_time();
cerr << "prediction time=" << prediction_time << endl;
return 0;
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright (C) 2016-2017 Kitsune Ral <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "printer.h"
#include "exception.h"
#include <algorithm>
#include <locale>
enum {
CannotReadTemplateFile = PrinterCodes, CannotWriteToFile,
};
using namespace std;
using namespace kainjow::mustache;
Printer::Printer(context_type&& context, const vector<string>& templateFileNames,
const string& inputBasePath, string outputBasePath,
const string& outFilesListPath)
: _context(context), _outputBasePath(std::move(outputBasePath))
{
// Enriching the context with "My Mustache library"
_context.set("@filePartial", lambda2 {
[inputBasePath, this](const string& s, const renderer& render) {
ifstream ifs { inputBasePath + s };
if (!ifs.good())
{
ifs.open(inputBasePath + s + ".mustache");
if (!ifs.good())
{
cerr << "Failed to open file for a partial: "
<< inputBasePath + s << endl;
// FIXME: Figure a better error reporting mechanism
return "/* Failed to open " + inputBasePath + s + " */";
}
}
string embeddedTemplate;
getline(ifs, embeddedTemplate, '\0'); // Won't work on files with NULs
return render(embeddedTemplate, false);
}
});
_context.set("@cap", lambda2 {
[](const string& s, const renderer& render)
{
return capitalizedCopy(render(s, false));
}
});
_context.set("@toupper", lambda2 {
[](string s, const renderer& render) {
s = render(s, false);
transform(s.begin(), s.end(), s.begin(),
[] (char c) { return toupper(c, locale::classic()); });
return s;
}
});
_context.set("@tolower", lambda2 {
[](string s, const renderer& render) {
s = render(s, false);
transform(s.begin(), s.end(), s.begin(),
[] (char c) { return tolower(c, locale::classic()); });
return s;
}
});
for (const auto& templateFileName: templateFileNames)
{
auto templateFilePath = inputBasePath + templateFileName;
cout << "Opening " << templateFilePath << endl;
ifstream ifs { templateFilePath };
if (!ifs.good())
{
cerr << "Failed to open " << templateFilePath << std::endl;
fail(CannotReadTemplateFile);
}
string templateContents;
if (!getline(ifs, templateContents, '\0')) // Won't work on files with NULs
{
cerr << "Failed to read from " << templateFilePath << std::endl;
fail(CannotReadTemplateFile);
}
mustache fileTemplate { templateContents };
fileTemplate.set_custom_escape([](const string& s) { return s; });
_templates.emplace_back(dropSuffix(templateFileName, ".mustache"),
std::move(fileTemplate));
}
if (!outFilesListPath.empty())
{
cout << "Opening " << _outputBasePath << outFilesListPath << endl;
_outFilesList.open(_outputBasePath + outFilesListPath);
if (!_outFilesList)
cerr << "No out files list set or cannot write to the file" << endl;
}
}
template <typename ObjT>
inline void setList(ObjT* object, const string& name, list&& list)
{
(*object)[name + '?'] = !list.empty();
if (!list.empty())
{
using namespace placeholders;
for_each(list.begin(), list.end() - 1,
bind(&data::set, _1, "hasMore", true));
list.back().set("last?", true);
}
(*object)[name] = list;
}
string renderType(const TypeUsage& tu)
{
if (tu.innerTypes.empty())
return tu.name;
// Template type
mustache m { tu.name };
object mInnerTypes;
int i = 0;
for (const auto& t: tu.innerTypes)
mInnerTypes.emplace(to_string(++i), renderType(t)); // {{1}}, {{2}} and so on
return m.render(mInnerTypes);
}
void dumpFieldAttrs(const VarDecl& param, object& fieldDef)
{
fieldDef["required?"] = param.required;
fieldDef["required"] = param.required; // Swagger compatibility
fieldDef["defaultValue"] = param.defaultValue;
for (const auto& attr: param.type.attributes)
fieldDef.emplace(attr);
for (const auto& listAttr: param.type.lists)
{
list mAttrValue;
for (const auto& i: listAttr.second)
mAttrValue.emplace_back(i);
fieldDef.emplace(listAttr.first, move(mAttrValue));
}
}
vector<string> Printer::print(const Model& model) const
{
auto context = _context;
context.set("filenameBase", model.filename);
{
// Imports
list mImports;
for (const auto& import: model.imports)
mImports.emplace_back(import);
setList(&context, "imports", std::move(mImports));
}
{
// Data definitions
list mTypes;
for (const auto& type: model.types)
{
object mType { { "classname", type.first } };
list mFields;
for (const auto& f: type.second.fields)
{
object fieldDef { { "name", f.name }
, { "datatype", renderType(f.type) } };
dumpFieldAttrs(f, fieldDef);
mFields.emplace_back(move(fieldDef));
}
setList(&mType, "vars", move(mFields));
mTypes.emplace_back(object { { "model", move(mType) } });
}
if (!mTypes.empty())
context.set("models", mTypes);
}
{
// Operations
list mClasses;
for (const auto& callClass: model.callClasses)
{
for (const auto& call: callClass.callOverloads)
{
object mClass { { "operationId", call.name }
, { "camelCaseOperationId", camelCase(call.name) }
, { "httpMethod", call.verb }
, { "path", call.path }
, { "skipAuth", !call.needsSecurity }
};
list mPathParts;
for (const auto& pp: call.pathParts)
mPathParts.emplace_back(object { { "part", pp } });
setList(&mClass, "pathParts", move(mPathParts));
for (const auto& pp: {
make_pair("pathParams", call.pathParams),
make_pair("queryParams", call.queryParams),
make_pair("headerParams", call.headerParams),
make_pair("bodyParams", call.bodyParams),
make_pair("allParams", call.collateParams())
})
{
list mParams;
for (const auto& param: pp.second)
{
object mParam { { "dataType", renderType(param.type) }
, { "baseName", param.name }
, { "paramName", param.name }
};
dumpFieldAttrs(param, mParam);
mParams.emplace_back(move(mParam));
}
setList(&mClass, pp.first, move(mParams));
}
{
list mResponses;
for (const auto& response: call.responses)
{
object mResponse { { "code", response.code }
, { "normalResponse?",
response.code == "200" }
};
list mProperties;
for (const auto& p: response.properties)
{
object mProperty { { "dataType", renderType(p.type) }
, { "paramName", p.name }
};
dumpFieldAttrs(p, mProperty);
mProperties.emplace_back(move(mProperty));
}
setList(&mResponse, "properties", move(mProperties));
mResponses.emplace_back(move(mResponse));
}
setList(&mClass, "responses", move(mResponses));
}
mClasses.emplace_back(move(mClass));
}
}
if (!mClasses.empty())
context.set("operations",
object { { "className", "NOT_IMPLEMENTED" }
, { "operation", mClasses }
});
context.set("basePathWithoutHost", model.basePath);
context.set("basePath", model.hostAddress + model.basePath);
}
vector<string> fileNames;
for (auto fileTemplate: _templates)
{
ostringstream fileNameStr;
fileNameStr << _outputBasePath << model.fileDir;
fileTemplate.first.render({ "base", model.filename }, fileNameStr);
if (!fileTemplate.first.error_message().empty())
{
cerr << "When rendering the filename:" << endl
<< fileTemplate.first.error_message() << endl;
continue; // FIXME: should be fail()
}
auto fileName = fileNameStr.str();
cout << "Printing " << fileName << endl;
ofstream ofs { fileName };
if (!ofs.good())
{
cerr << "Couldn't open " << fileName << " for writing" << endl;
fail(CannotWriteToFile);
}
fileTemplate.second.set_custom_escape([](const string& s) { return s; });
fileTemplate.second.render(context, ofs);
if (fileTemplate.second.error_message().empty())
_outFilesList << fileName << endl;
else
cerr << "When rendering the file:" << endl
<< fileTemplate.second.error_message() << endl;
fileNames.emplace_back(std::move(fileName));
}
return fileNames;
}
<commit_msg>Export the list of parent types to templates<commit_after>/******************************************************************************
* Copyright (C) 2016-2017 Kitsune Ral <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "printer.h"
#include "exception.h"
#include <algorithm>
#include <locale>
enum {
CannotReadTemplateFile = PrinterCodes, CannotWriteToFile,
};
using namespace std;
using namespace kainjow::mustache;
Printer::Printer(context_type&& context, const vector<string>& templateFileNames,
const string& inputBasePath, string outputBasePath,
const string& outFilesListPath)
: _context(context), _outputBasePath(std::move(outputBasePath))
{
// Enriching the context with "My Mustache library"
_context.set("@filePartial", lambda2 {
[inputBasePath, this](const string& s, const renderer& render) {
ifstream ifs { inputBasePath + s };
if (!ifs.good())
{
ifs.open(inputBasePath + s + ".mustache");
if (!ifs.good())
{
cerr << "Failed to open file for a partial: "
<< inputBasePath + s << endl;
// FIXME: Figure a better error reporting mechanism
return "/* Failed to open " + inputBasePath + s + " */";
}
}
string embeddedTemplate;
getline(ifs, embeddedTemplate, '\0'); // Won't work on files with NULs
return render(embeddedTemplate, false);
}
});
_context.set("@cap", lambda2 {
[](const string& s, const renderer& render)
{
return capitalizedCopy(render(s, false));
}
});
_context.set("@toupper", lambda2 {
[](string s, const renderer& render) {
s = render(s, false);
transform(s.begin(), s.end(), s.begin(),
[] (char c) { return toupper(c, locale::classic()); });
return s;
}
});
_context.set("@tolower", lambda2 {
[](string s, const renderer& render) {
s = render(s, false);
transform(s.begin(), s.end(), s.begin(),
[] (char c) { return tolower(c, locale::classic()); });
return s;
}
});
for (const auto& templateFileName: templateFileNames)
{
auto templateFilePath = inputBasePath + templateFileName;
cout << "Opening " << templateFilePath << endl;
ifstream ifs { templateFilePath };
if (!ifs.good())
{
cerr << "Failed to open " << templateFilePath << std::endl;
fail(CannotReadTemplateFile);
}
string templateContents;
if (!getline(ifs, templateContents, '\0')) // Won't work on files with NULs
{
cerr << "Failed to read from " << templateFilePath << std::endl;
fail(CannotReadTemplateFile);
}
mustache fileTemplate { templateContents };
fileTemplate.set_custom_escape([](const string& s) { return s; });
_templates.emplace_back(dropSuffix(templateFileName, ".mustache"),
std::move(fileTemplate));
}
if (!outFilesListPath.empty())
{
cout << "Opening " << _outputBasePath << outFilesListPath << endl;
_outFilesList.open(_outputBasePath + outFilesListPath);
if (!_outFilesList)
cerr << "No out files list set or cannot write to the file" << endl;
}
}
template <typename ObjT>
inline void setList(ObjT* object, const string& name, list&& list)
{
(*object)[name + '?'] = !list.empty();
if (!list.empty())
{
using namespace placeholders;
for_each(list.begin(), list.end() - 1,
bind(&data::set, _1, "hasMore", true));
list.back().set("last?", true);
}
(*object)[name] = list;
}
string renderType(const TypeUsage& tu)
{
if (tu.innerTypes.empty())
return tu.name;
// Template type
mustache m { tu.name };
object mInnerTypes;
int i = 0;
for (const auto& t: tu.innerTypes)
mInnerTypes.emplace(to_string(++i), renderType(t)); // {{1}}, {{2}} and so on
return m.render(mInnerTypes);
}
void dumpFieldAttrs(const VarDecl& param, object& fieldDef)
{
fieldDef["required?"] = param.required;
fieldDef["required"] = param.required; // Swagger compatibility
fieldDef["defaultValue"] = param.defaultValue;
for (const auto& attr: param.type.attributes)
fieldDef.emplace(attr);
for (const auto& listAttr: param.type.lists)
{
list mAttrValue;
for (const auto& i: listAttr.second)
mAttrValue.emplace_back(i);
fieldDef.emplace(listAttr.first, move(mAttrValue));
}
}
vector<string> Printer::print(const Model& model) const
{
auto context = _context;
context.set("filenameBase", model.filename);
{
// Imports
list mImports;
for (const auto& import: model.imports)
mImports.emplace_back(import);
setList(&context, "imports", std::move(mImports));
}
{
// Data definitions
list mTypes;
for (const auto& type: model.types)
{
object mType { { "classname", type.first } };
{
list mParents;
for (const auto& t: type.second.parentTypes)
mParents.emplace_back(renderType(t));
setList(&mType, "parents", move(mParents));
}
{
list mFields;
for (const auto& f: type.second.fields)
{
object fieldDef { { "name", f.name },
{ "datatype", renderType(f.type) } };
dumpFieldAttrs(f, fieldDef);
mFields.emplace_back(move(fieldDef));
}
setList(&mType, "vars", move(mFields));
}
mTypes.emplace_back(object { { "model", move(mType) } });
}
if (!mTypes.empty())
context.set("models", mTypes);
}
{
// Operations
list mClasses;
for (const auto& callClass: model.callClasses)
{
for (const auto& call: callClass.callOverloads)
{
object mClass { { "operationId", call.name }
, { "camelCaseOperationId", camelCase(call.name) }
, { "httpMethod", call.verb }
, { "path", call.path }
, { "skipAuth", !call.needsSecurity }
};
list mPathParts;
for (const auto& pp: call.pathParts)
mPathParts.emplace_back(object { { "part", pp } });
setList(&mClass, "pathParts", move(mPathParts));
for (const auto& pp: {
make_pair("pathParams", call.pathParams),
make_pair("queryParams", call.queryParams),
make_pair("headerParams", call.headerParams),
make_pair("bodyParams", call.bodyParams),
make_pair("allParams", call.collateParams())
})
{
list mParams;
for (const auto& param: pp.second)
{
object mParam { { "dataType", renderType(param.type) }
, { "baseName", param.name }
, { "paramName", param.name }
};
dumpFieldAttrs(param, mParam);
mParams.emplace_back(move(mParam));
}
setList(&mClass, pp.first, move(mParams));
}
{
list mResponses;
for (const auto& response: call.responses)
{
object mResponse { { "code", response.code }
, { "normalResponse?",
response.code == "200" }
};
list mProperties;
for (const auto& p: response.properties)
{
object mProperty { { "dataType", renderType(p.type) }
, { "paramName", p.name }
};
dumpFieldAttrs(p, mProperty);
mProperties.emplace_back(move(mProperty));
}
setList(&mResponse, "properties", move(mProperties));
mResponses.emplace_back(move(mResponse));
}
setList(&mClass, "responses", move(mResponses));
}
mClasses.emplace_back(move(mClass));
}
}
if (!mClasses.empty())
context.set("operations",
object { { "className", "NOT_IMPLEMENTED" }
, { "operation", mClasses }
});
context.set("basePathWithoutHost", model.basePath);
context.set("basePath", model.hostAddress + model.basePath);
}
vector<string> fileNames;
for (auto fileTemplate: _templates)
{
ostringstream fileNameStr;
fileNameStr << _outputBasePath << model.fileDir;
fileTemplate.first.render({ "base", model.filename }, fileNameStr);
if (!fileTemplate.first.error_message().empty())
{
cerr << "When rendering the filename:" << endl
<< fileTemplate.first.error_message() << endl;
continue; // FIXME: should be fail()
}
auto fileName = fileNameStr.str();
cout << "Printing " << fileName << endl;
ofstream ofs { fileName };
if (!ofs.good())
{
cerr << "Couldn't open " << fileName << " for writing" << endl;
fail(CannotWriteToFile);
}
fileTemplate.second.set_custom_escape([](const string& s) { return s; });
fileTemplate.second.render(context, ofs);
if (fileTemplate.second.error_message().empty())
_outFilesList << fileName << endl;
else
cerr << "When rendering the file:" << endl
<< fileTemplate.second.error_message() << endl;
fileNames.emplace_back(std::move(fileName));
}
return fileNames;
}
<|endoftext|> |
<commit_before>//
// Copyright (c) 2014 CNRS
// Authors: Florent Lamiraux
//
// This file is part of hpp-core
// hpp-core is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-core is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core If not, see
// <http://www.gnu.org/licenses/>.
#include <hpp/util/debug.hh>
#include <hpp/pinocchio/configuration.hh>
#include <hpp/core/constraint-set.hh>
#include <hpp/core/config-projector.hh>
namespace hpp {
namespace core {
HPP_PREDEF_CLASS (ConfigProjectorTrivial);
typedef boost::shared_ptr <ConfigProjectorTrivial>
ConfigProjectorTrivialPtr_t;
class ConfigProjectorTrivial : public ConfigProjector
{
public:
static ConfigProjectorTrivialPtr_t create (const DevicePtr_t& robot)
{
ConfigProjectorTrivial* ptr = new ConfigProjectorTrivial (robot);
ConfigProjectorTrivialPtr_t shPtr (ptr);
ptr->init (shPtr);
return shPtr;
}
ConfigProjectorTrivial (const DevicePtr_t& robot)
: ConfigProjector (robot, "trivial ConfigProjector", 0, 0)
{
}
// Do not copy, return shared pointer to this.
virtual ConstraintPtr_t copy () const
{
return weak_.lock ();
}
bool impl_compute (ConfigurationOut_t configuration)
{
computeLockedDofs (configuration);
return true;
}
void projectOnKernel (ConfigurationIn_t,
ConfigurationIn_t, ConfigurationOut_t)
{}
/// Check whether a configuration statisfies the constraint.
virtual bool isSatisfied (ConfigurationIn_t)
{
return true;
}
virtual bool isSatisfied (ConfigurationIn_t, vector_t& error)
{
error.resize (0);
return true;
}
void init (ConfigProjectorTrivialPtr_t weak)
{
ConfigProjector::init (weak);
weak_ = weak;
}
ConfigProjectorTrivialWkPtr_t weak_;
}; // class ConfigProjectorTrivial
bool ConstraintSet::impl_compute (ConfigurationOut_t configuration)
{
for (Constraints_t::iterator itConstraint = constraints_.begin ();
itConstraint != constraints_.end (); ++itConstraint) {
if (!(*itConstraint)->impl_compute (configuration)) return false;
}
return true;
}
ConstraintPtr_t ConstraintSet::copy () const
{
return createCopy (weak_.lock ());
}
ConstraintSet::ConstraintSet (const DevicePtr_t& robot,
const std::string& name) :
Constraint (name), constraints_ ()
{
constraints_.push_back (ConfigProjectorTrivial::create (robot));
trivialOrNotConfigProjectorIt_ = constraints_.begin ();
configProjectorIt_ = constraints_.end ();
}
ConstraintSet::ConstraintSet (const ConstraintSet& other) :
Constraint (other), constraints_ ()
{
for (Constraints_t::const_iterator it = other.constraints_.begin ();
it != other.constraints_.end (); ++it) {
constraints_.push_back ((*it)->copy ());
}
configProjectorIt_ = constraints_.begin ();
Constraints_t::const_iterator b = other.constraints_.begin();
Constraints_t::const_iterator it = other.configProjectorIt_;
std::advance (configProjectorIt_, std::distance (b, it));
trivialOrNotConfigProjectorIt_ = constraints_.begin ();
b = other.constraints_.begin();
it = other.configProjectorIt_;
std::advance (trivialOrNotConfigProjectorIt_, std::distance (b, it));
}
void ConstraintSet::removeFirstElement ()
{
constraints_.pop_front ();
}
ConfigProjectorPtr_t ConstraintSet::configProjector () const
{
if (configProjectorIt_ != constraints_.end ())
return HPP_STATIC_PTR_CAST (ConfigProjector, *configProjectorIt_);
else return ConfigProjectorPtr_t ();
}
bool ConstraintSet::isSatisfied (ConfigurationIn_t configuration)
{
for (Constraints_t::iterator itConstraint = constraints_.begin ();
itConstraint != constraints_.end (); ++itConstraint) {
if (!(*itConstraint)->isSatisfied (configuration)) {
return false;
}
}
return true;
}
bool ConstraintSet::isSatisfied (ConfigurationIn_t configuration,
vector_t& error)
{
bool result = true;
error.resize (0);
vector_t localError;
for (Constraints_t::iterator itConstraint = constraints_.begin ();
itConstraint != constraints_.end (); ++itConstraint) {
if (!(*itConstraint)->isSatisfied (configuration, localError)) {
error.conservativeResize (error.size () + localError.size ());
error.tail (localError.size ()) = localError;
result = false;
}
}
return result;
}
size_type ConstraintSet::numberNonLockedDof () const
{
return HPP_STATIC_PTR_CAST (ConfigProjector, *trivialOrNotConfigProjectorIt_)
->numberNonLockedDof ();
}
void ConstraintSet::compressVector (vectorIn_t normal,
vectorOut_t small) const
{
HPP_STATIC_PTR_CAST (ConfigProjector, *trivialOrNotConfigProjectorIt_)->compressVector (normal, small);
}
void ConstraintSet::uncompressVector (vectorIn_t small,
vectorOut_t normal) const
{
HPP_STATIC_PTR_CAST (ConfigProjector, *trivialOrNotConfigProjectorIt_)->uncompressVector (small, normal);
}
void ConstraintSet::compressMatrix (matrixIn_t normal, matrixOut_t small,
bool rows) const
{
HPP_STATIC_PTR_CAST (ConfigProjector, *trivialOrNotConfigProjectorIt_)->compressMatrix (normal, small, rows);
}
void ConstraintSet::uncompressMatrix (matrixIn_t small,
matrixOut_t normal,
bool rows) const
{
HPP_STATIC_PTR_CAST (ConfigProjector, *trivialOrNotConfigProjectorIt_)->uncompressMatrix (small, normal, rows);
}
} // namespace core
} // namespace core
<commit_msg>Fix ConstraintSet::isSatisfied<commit_after>//
// Copyright (c) 2014 CNRS
// Authors: Florent Lamiraux
//
// This file is part of hpp-core
// hpp-core is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-core is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core If not, see
// <http://www.gnu.org/licenses/>.
#include <hpp/util/debug.hh>
#include <hpp/pinocchio/configuration.hh>
#include <hpp/core/constraint-set.hh>
#include <hpp/core/config-projector.hh>
namespace hpp {
namespace core {
HPP_PREDEF_CLASS (ConfigProjectorTrivial);
typedef boost::shared_ptr <ConfigProjectorTrivial>
ConfigProjectorTrivialPtr_t;
class ConfigProjectorTrivial : public ConfigProjector
{
public:
static ConfigProjectorTrivialPtr_t create (const DevicePtr_t& robot)
{
ConfigProjectorTrivial* ptr = new ConfigProjectorTrivial (robot);
ConfigProjectorTrivialPtr_t shPtr (ptr);
ptr->init (shPtr);
return shPtr;
}
ConfigProjectorTrivial (const DevicePtr_t& robot)
: ConfigProjector (robot, "trivial ConfigProjector", 0, 0)
{
}
// Do not copy, return shared pointer to this.
virtual ConstraintPtr_t copy () const
{
return weak_.lock ();
}
bool impl_compute (ConfigurationOut_t configuration)
{
computeLockedDofs (configuration);
return true;
}
void projectOnKernel (ConfigurationIn_t,
ConfigurationIn_t, ConfigurationOut_t)
{}
/// Check whether a configuration statisfies the constraint.
virtual bool isSatisfied (ConfigurationIn_t)
{
return true;
}
virtual bool isSatisfied (ConfigurationIn_t, vector_t& error)
{
error.resize (0);
return true;
}
void init (ConfigProjectorTrivialPtr_t weak)
{
ConfigProjector::init (weak);
weak_ = weak;
}
ConfigProjectorTrivialWkPtr_t weak_;
}; // class ConfigProjectorTrivial
bool ConstraintSet::impl_compute (ConfigurationOut_t configuration)
{
for (Constraints_t::iterator itConstraint = constraints_.begin ();
itConstraint != constraints_.end (); ++itConstraint) {
if (!(*itConstraint)->impl_compute (configuration)) return false;
}
return true;
}
ConstraintPtr_t ConstraintSet::copy () const
{
return createCopy (weak_.lock ());
}
ConstraintSet::ConstraintSet (const DevicePtr_t& robot,
const std::string& name) :
Constraint (name), constraints_ ()
{
constraints_.push_back (ConfigProjectorTrivial::create (robot));
trivialOrNotConfigProjectorIt_ = constraints_.begin ();
configProjectorIt_ = constraints_.end ();
}
ConstraintSet::ConstraintSet (const ConstraintSet& other) :
Constraint (other), constraints_ ()
{
for (Constraints_t::const_iterator it = other.constraints_.begin ();
it != other.constraints_.end (); ++it) {
constraints_.push_back ((*it)->copy ());
}
configProjectorIt_ = constraints_.begin ();
Constraints_t::const_iterator b = other.constraints_.begin();
Constraints_t::const_iterator it = other.configProjectorIt_;
std::advance (configProjectorIt_, std::distance (b, it));
trivialOrNotConfigProjectorIt_ = constraints_.begin ();
b = other.constraints_.begin();
it = other.configProjectorIt_;
std::advance (trivialOrNotConfigProjectorIt_, std::distance (b, it));
}
void ConstraintSet::removeFirstElement ()
{
constraints_.pop_front ();
}
ConfigProjectorPtr_t ConstraintSet::configProjector () const
{
if (configProjectorIt_ != constraints_.end ())
return HPP_STATIC_PTR_CAST (ConfigProjector, *configProjectorIt_);
else return ConfigProjectorPtr_t ();
}
bool ConstraintSet::isSatisfied (ConfigurationIn_t configuration)
{
for (Constraints_t::iterator itConstraint = constraints_.begin ();
itConstraint != constraints_.end (); ++itConstraint) {
if (!(*itConstraint)->isSatisfied (configuration)) {
return false;
}
}
return true;
}
bool ConstraintSet::isSatisfied (ConfigurationIn_t configuration,
vector_t& error)
{
bool result = true;
error.resize (0);
vector_t localError;
for (Constraints_t::iterator itConstraint = constraints_.begin ();
itConstraint != constraints_.end (); ++itConstraint) {
if (!(*itConstraint)->isSatisfied (configuration, localError)) {
result = false;
}
error.conservativeResize (error.size () + localError.size ());
error.tail (localError.size ()) = localError;
}
return result;
}
size_type ConstraintSet::numberNonLockedDof () const
{
return HPP_STATIC_PTR_CAST (ConfigProjector, *trivialOrNotConfigProjectorIt_)
->numberNonLockedDof ();
}
void ConstraintSet::compressVector (vectorIn_t normal,
vectorOut_t small) const
{
HPP_STATIC_PTR_CAST (ConfigProjector, *trivialOrNotConfigProjectorIt_)->compressVector (normal, small);
}
void ConstraintSet::uncompressVector (vectorIn_t small,
vectorOut_t normal) const
{
HPP_STATIC_PTR_CAST (ConfigProjector, *trivialOrNotConfigProjectorIt_)->uncompressVector (small, normal);
}
void ConstraintSet::compressMatrix (matrixIn_t normal, matrixOut_t small,
bool rows) const
{
HPP_STATIC_PTR_CAST (ConfigProjector, *trivialOrNotConfigProjectorIt_)->compressMatrix (normal, small, rows);
}
void ConstraintSet::uncompressMatrix (matrixIn_t small,
matrixOut_t normal,
bool rows) const
{
HPP_STATIC_PTR_CAST (ConfigProjector, *trivialOrNotConfigProjectorIt_)->uncompressMatrix (small, normal, rows);
}
} // namespace core
} // namespace core
<|endoftext|> |
<commit_before>/*
Copyright 2016 Colin Girling
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 OCL_GUARD_TEST_TESTSTRING_HPP
#define OCL_GUARD_TEST_TESTSTRING_HPP
#include "TestMemoryUtility.hpp"
#include "TestStringUtility.hpp"
#include <cstddef>
#include <cstdlib>
#include <cstring>
namespace ocl
{
/*
* String class for test harness, with an interface complete enough for general usage.
*/
class TestString
{
public:
typedef TestStringUtility::size_type size_type;
/// size_type has the potential of being signed or unsigned,
/// so ensure signed/unsigned mismatch compiler warnings are suppressed.
static size_type const size_type_default = static_cast<size_type>(0);
public:
TestString(char const* str = NULL)
: m_length(size_type_default)
, m_string(NULL)
{
if (str != NULL)
TestStringUtility::UnsafeAllocateCopy(m_string, m_length, str);
}
TestString(char ch, size_type len)
: m_length(len)
, m_string(NULL)
{
if (len > size_type_default)
{
TestStringUtility::Allocate(m_string, len);
if (m_string != NULL)
TestStringUtility::UnsafeFill(m_string, ch, len);
else
m_length = size_type_default;
}
}
TestString(TestString const& str)
: m_length(size_type_default)
, m_string(NULL)
{
TestStringUtility::SafeAllocateCopy(m_string, m_length, str.m_string, str.m_length);
}
~TestString()
{
TestStringUtility::FastFree(m_string);
}
TestString& operator =(char const* str)
{
if ((str != NULL) && (*str != '\0'))
TestStringUtility::SafeReallocCopy(m_string, m_length, str);
else
Clear();
return *this;
}
TestString& operator =(TestString const& str)
{
if ((str.m_string != NULL) &&
(*str.m_string != '\0') &&
(str.m_length > size_type_default))
{
TestStringUtility::SafeReallocCopy(m_string,
m_length,
str.m_string,
str.m_length);
}
else
Clear();
return *this;
}
TestString& operator +=(char const* str)
{
Append(str);
return *this;
}
TestString& operator +=(TestString const& str)
{
Append(str);
return *this;
}
char operator [](size_type index) const
{
return ((m_string != NULL) && (index < m_length)) ? m_string[index] : '\0';
}
char& operator [](size_type index)
{
static char spare = '\0';
return ((m_string != NULL) && (index < m_length)) ? m_string[index] : spare;
}
operator char const*() const throw()
{
return Ptr();
}
bool operator ==(char const* str) const
{
if (m_string == NULL)
return (str == NULL) || (*str == '\0');
return ::strcmp(m_string, str) == 0;
}
bool operator ==(TestString const& str) const
{
if (m_string == NULL)
return str.m_string == NULL;
return ::strcmp(m_string, str.Ptr()) == 0;
}
public:
char const* Ptr() const throw()
{
return m_string != NULL ? m_string : "";
}
size_type GetLength() const throw()
{
return m_length;
}
bool IsEmpty() const throw()
{
return m_string == NULL;
}
void Clear()
{
TestStringUtility::FastFree(m_string);
m_string = NULL;
m_length = size_type_default;
}
bool Find(char ch, size_type& pos, size_type start = size_type_default) const
{
if (m_string != NULL)
return TestStringUtility::UnsafeFind(m_string, ch, pos, start);
return false;
}
/// Extract a partial string, and optionally remove the partial string
/// from this string.
void GetSubString(TestString& sub_str,
size_type start,
size_type count,
bool remove = false)
{
sub_str.Clear();
TestStringUtility::SafeReallocCopy(sub_str.m_string,
sub_str.m_length,
m_string + start,
count);
if (remove)
{
if (sub_str.m_length < m_length)
{
size_type chars_remaining = m_length - sub_str.m_length;
::memmove(m_string, m_string + sub_str.m_length, chars_remaining);
*(m_string + chars_remaining) = '\0';
m_length = chars_remaining;
}
else
Clear();
}
}
/// Replace the current sting with str.
void Assign(char const* str)
{
TestStringUtility::SafeReallocCopy(m_string, m_length, str);
}
/// Replace the current sting with str.
void Assign(TestString const& str)
{
TestStringUtility::SafeReallocCopy(m_string, m_length, str.m_string);
}
/// Move str into this string.
void Move(char*& str, size_type len)
{
TestStringUtility::FastFree(m_string);
m_string = str;
m_length = len;
str = NULL;
}
void Prepend(char const* str)
{
if ((str != NULL) && (*str != '\0'))
{
TestStringUtility::SafeReallocAppend(m_string,
m_length,
str,
privateSafeLength(str),
m_string,
m_length);
}
}
void Append(char const* str)
{
if ((str != NULL) && (*str != '\0'))
{
TestStringUtility::SafeReallocAppend(m_string,
m_length,
m_string,
m_length,
str,
privateSafeLength(str));
}
}
void Append(char const* str, size_type count)
{
if ((str != NULL) && (*str != '\0') &&
(count > size_type_default))
{
TestStringUtility::SafeReallocAppend(m_string,
m_length,
m_string,
m_length,
str,
count);
}
}
void Append(TestString const& str)
{
if ((str.m_string != NULL) &&
(*str.m_string != '\0') &&
(str.m_length > size_type_default))
{
TestStringUtility::SafeReallocAppend(m_string,
m_length,
m_string,
m_length,
str.m_string,
str.m_length);
}
}
/// Append a boolean converted to a "true" ot "false" string.
void Append(bool value)
{
char const* str = value ? "true" : "false";
Append(str);
}
/// Append a single character.
void Append(char value)
{
char str[2];
str[0] = value;
str[1] = '\0';
Append(str);
}
/// Append number of characters.
void Append(char value, size_type count)
{
if (count > size_type_default)
{
char* str = NULL;
TestStringUtility::Allocate(str, count);
if (str != NULL)
{
char* start = str;
for (char* str_end = str + count; str < str_end; ++str)
*str = value;
Append(start, count);
TestStringUtility::FastFree(start);
}
else
Append(value);
}
}
/// Append number of characters then a string value.
void Append(char ch, size_type count, char const* value, size_type len)
{
if (count > size_type_default)
{
char* str = NULL;
TestStringUtility::Allocate(str, count + len);
if (str != NULL)
{
char* start = str;
for (char* str_end = str + count; str < str_end; ++str)
*str = ch;
::memcpy(str, value, len + 1);
Append(start, count + len);
TestStringUtility::FastFree(start);
}
else
Append(ch);
}
else
Append(value, len);
}
void Append(signed char value, size_type pad = size_type_default)
{
privateAppendValue(value, pad);
}
void Append(unsigned char value, size_type pad = size_type_default)
{
privateAppendValue(value, pad);
}
void Append(signed short value, size_type pad = size_type_default)
{
privateAppendValue(value, pad);
}
void Append(unsigned short value, size_type pad = size_type_default)
{
privateAppendValue(value, pad);
}
void Append(signed int value, size_type pad = size_type_default)
{
privateAppendValue(value, pad);
}
void Append(unsigned int value, size_type pad = size_type_default)
{
privateAppendValue(value, pad);
}
void Append(signed long value, size_type pad = size_type_default)
{
privateAppendValue(value, pad);
}
void Append(unsigned long value, size_type pad = size_type_default)
{
privateAppendValue(value, pad);
}
private:
template<typename T>
void privateAppendValue(T value, size_type pad)
{
size_type length = size_type_default;
char* str = TestStringUtility::GetString(value, length);
if (str != NULL)
{
if (IsEmpty() && (pad == size_type_default))
Move(str, length);
else
{
if (pad > length)
Append('0', pad - length, str, length);
else
Append(str, length);
TestStringUtility::FastFree(str);
}
}
}
size_type privateSafeLength(char const* str)
{
return TestStringUtility::SafeLength(str);
}
private:
size_type m_length;
char* m_string;
};
} // namespace ocl
#endif // OCL_GUARD_TEST_TESTSTRING_HPP
<commit_msg>Fixed bug with GetSubString being able to go past end of buffer in TestString class.<commit_after>/*
Copyright 2016 Colin Girling
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 OCL_GUARD_TEST_TESTSTRING_HPP
#define OCL_GUARD_TEST_TESTSTRING_HPP
#include "TestMemoryUtility.hpp"
#include "TestStringUtility.hpp"
#include <cstddef>
#include <cstdlib>
#include <cstring>
namespace ocl
{
/*
* String class for test harness, with an interface complete enough for general usage.
*/
class TestString
{
public:
typedef TestStringUtility::size_type size_type;
/// size_type has the potential of being signed or unsigned,
/// so ensure signed/unsigned mismatch compiler warnings are suppressed.
static size_type const size_type_default = static_cast<size_type>(0);
public:
TestString(char const* str = NULL)
: m_length(size_type_default)
, m_string(NULL)
{
if (str != NULL)
TestStringUtility::UnsafeAllocateCopy(m_string, m_length, str);
}
TestString(char ch, size_type len)
: m_length(len)
, m_string(NULL)
{
if (len > size_type_default)
{
TestStringUtility::Allocate(m_string, len);
if (m_string != NULL)
TestStringUtility::UnsafeFill(m_string, ch, len);
else
m_length = size_type_default;
}
}
TestString(TestString const& str)
: m_length(size_type_default)
, m_string(NULL)
{
TestStringUtility::SafeAllocateCopy(m_string, m_length, str.m_string, str.m_length);
}
~TestString()
{
TestStringUtility::FastFree(m_string);
}
TestString& operator =(char const* str)
{
if ((str != NULL) && (*str != '\0'))
TestStringUtility::SafeReallocCopy(m_string, m_length, str);
else
Clear();
return *this;
}
TestString& operator =(TestString const& str)
{
if ((str.m_string != NULL) &&
(*str.m_string != '\0') &&
(str.m_length > size_type_default))
{
TestStringUtility::SafeReallocCopy(m_string,
m_length,
str.m_string,
str.m_length);
}
else
Clear();
return *this;
}
TestString& operator +=(char const* str)
{
Append(str);
return *this;
}
TestString& operator +=(TestString const& str)
{
Append(str);
return *this;
}
char operator [](size_type index) const
{
return ((m_string != NULL) && (index < m_length)) ? m_string[index] : '\0';
}
char& operator [](size_type index)
{
static char spare = '\0';
return ((m_string != NULL) && (index < m_length)) ? m_string[index] : spare;
}
operator char const*() const throw()
{
return Ptr();
}
bool operator ==(char const* str) const
{
if (m_string == NULL)
return (str == NULL) || (*str == '\0');
return ::strcmp(m_string, str) == 0;
}
bool operator ==(TestString const& str) const
{
if (m_string == NULL)
return str.m_string == NULL;
return ::strcmp(m_string, str.Ptr()) == 0;
}
public:
char const* Ptr() const throw()
{
return m_string != NULL ? m_string : "";
}
size_type GetLength() const throw()
{
return m_length;
}
bool IsEmpty() const throw()
{
return m_string == NULL;
}
void Clear()
{
TestStringUtility::FastFree(m_string);
m_string = NULL;
m_length = size_type_default;
}
bool Find(char ch, size_type& pos, size_type start = size_type_default) const
{
if (m_string != NULL)
return TestStringUtility::UnsafeFind(m_string, ch, pos, start);
return false;
}
/// Extract a partial string, and optionally remove the partial string
/// from this string.
void GetSubString(TestString& sub_str,
size_type start,
size_type count,
bool remove = false)
{
sub_str.Clear();
if (start + count <= m_length)
{
TestStringUtility::SafeReallocCopy(sub_str.m_string,
sub_str.m_length,
m_string + start,
count);
if (remove)
{
if (sub_str.m_length < m_length)
{
size_type chars_remaining = m_length - sub_str.m_length;
::memmove(m_string, m_string + sub_str.m_length, chars_remaining);
*(m_string + chars_remaining) = '\0';
m_length = chars_remaining;
}
else
Clear();
}
}
}
/// Replace the current sting with str.
void Assign(char const* str)
{
TestStringUtility::SafeReallocCopy(m_string, m_length, str);
}
/// Replace the current sting with str.
void Assign(TestString const& str)
{
TestStringUtility::SafeReallocCopy(m_string, m_length, str.m_string);
}
/// Move str into this string.
void Move(char*& str, size_type len)
{
TestStringUtility::FastFree(m_string);
m_string = str;
m_length = len;
str = NULL;
}
void Prepend(char const* str)
{
if ((str != NULL) && (*str != '\0'))
{
TestStringUtility::SafeReallocAppend(m_string,
m_length,
str,
privateSafeLength(str),
m_string,
m_length);
}
}
void Append(char const* str)
{
if ((str != NULL) && (*str != '\0'))
{
TestStringUtility::SafeReallocAppend(m_string,
m_length,
m_string,
m_length,
str,
privateSafeLength(str));
}
}
void Append(char const* str, size_type count)
{
if ((str != NULL) && (*str != '\0') &&
(count > size_type_default))
{
TestStringUtility::SafeReallocAppend(m_string,
m_length,
m_string,
m_length,
str,
count);
}
}
void Append(TestString const& str)
{
if ((str.m_string != NULL) &&
(*str.m_string != '\0') &&
(str.m_length > size_type_default))
{
TestStringUtility::SafeReallocAppend(m_string,
m_length,
m_string,
m_length,
str.m_string,
str.m_length);
}
}
/// Append a boolean converted to a "true" ot "false" string.
void Append(bool value)
{
char const* str = value ? "true" : "false";
Append(str);
}
/// Append a single character.
void Append(char value)
{
char str[2];
str[0] = value;
str[1] = '\0';
Append(str);
}
/// Append number of characters.
void Append(char value, size_type count)
{
if (count > size_type_default)
{
char* str = NULL;
TestStringUtility::Allocate(str, count);
if (str != NULL)
{
char* start = str;
for (char* str_end = str + count; str < str_end; ++str)
*str = value;
Append(start, count);
TestStringUtility::FastFree(start);
}
else
Append(value);
}
}
/// Append number of characters then a string value.
void Append(char ch, size_type count, char const* value, size_type len)
{
if (count > size_type_default)
{
char* str = NULL;
TestStringUtility::Allocate(str, count + len);
if (str != NULL)
{
char* start = str;
for (char* str_end = str + count; str < str_end; ++str)
*str = ch;
::memcpy(str, value, len + 1);
Append(start, count + len);
TestStringUtility::FastFree(start);
}
else
Append(ch);
}
else
Append(value, len);
}
void Append(signed char value, size_type pad = size_type_default)
{
privateAppendValue(value, pad);
}
void Append(unsigned char value, size_type pad = size_type_default)
{
privateAppendValue(value, pad);
}
void Append(signed short value, size_type pad = size_type_default)
{
privateAppendValue(value, pad);
}
void Append(unsigned short value, size_type pad = size_type_default)
{
privateAppendValue(value, pad);
}
void Append(signed int value, size_type pad = size_type_default)
{
privateAppendValue(value, pad);
}
void Append(unsigned int value, size_type pad = size_type_default)
{
privateAppendValue(value, pad);
}
void Append(signed long value, size_type pad = size_type_default)
{
privateAppendValue(value, pad);
}
void Append(unsigned long value, size_type pad = size_type_default)
{
privateAppendValue(value, pad);
}
private:
template<typename T>
void privateAppendValue(T value, size_type pad)
{
size_type length = size_type_default;
char* str = TestStringUtility::GetString(value, length);
if (str != NULL)
{
if (IsEmpty() && (pad == size_type_default))
Move(str, length);
else
{
if (pad > length)
Append('0', pad - length, str, length);
else
Append(str, length);
TestStringUtility::FastFree(str);
}
}
}
size_type privateSafeLength(char const* str)
{
return TestStringUtility::SafeLength(str);
}
private:
size_type m_length;
char* m_string;
};
} // namespace ocl
#endif // OCL_GUARD_TEST_TESTSTRING_HPP
<|endoftext|> |
<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra. Eigen itself is part of the KDE project.
//
// Copyright (C) 2006-2008 Benoit Jacob <[email protected]>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, 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.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#include "main.h"
template<typename MatrixType> void basicStuff(const MatrixType& m)
{
typedef typename MatrixType::Scalar Scalar;
typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType;
int rows = m.rows();
int cols = m.cols();
// this test relies a lot on Random.h, and there's not much more that we can do
// to test it, hence I consider that we will have tested Random.h
MatrixType m1 = MatrixType::Random(rows, cols),
m2 = MatrixType::Random(rows, cols),
m3(rows, cols),
mzero = MatrixType::Zero(rows, cols),
identity = Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime>
::Identity(rows, rows),
square = Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime>::Random(rows, rows);
VectorType v1 = VectorType::Random(rows),
v2 = VectorType::Random(rows),
vzero = VectorType::Zero(rows);
Scalar x = ei_random<Scalar>();
int r = ei_random<int>(0, rows-1),
c = ei_random<int>(0, cols-1);
m1.coeffRef(r,c) = x;
VERIFY_IS_APPROX(x, m1.coeff(r,c));
m1(r,c) = x;
VERIFY_IS_APPROX(x, m1(r,c));
v1.coeffRef(r) = x;
VERIFY_IS_APPROX(x, v1.coeff(r));
v1(r) = x;
VERIFY_IS_APPROX(x, v1(r));
v1[r] = x;
VERIFY_IS_APPROX(x, v1[r]);
VERIFY_IS_APPROX( v1, v1);
VERIFY_IS_NOT_APPROX( v1, 2*v1);
VERIFY_IS_MUCH_SMALLER_THAN( vzero, v1);
if(NumTraits<Scalar>::HasFloatingPoint)
VERIFY_IS_MUCH_SMALLER_THAN( vzero, v1.norm());
VERIFY_IS_NOT_MUCH_SMALLER_THAN(v1, v1);
VERIFY_IS_APPROX( vzero, v1-v1);
VERIFY_IS_APPROX( m1, m1);
VERIFY_IS_NOT_APPROX( m1, 2*m1);
VERIFY_IS_MUCH_SMALLER_THAN( mzero, m1);
VERIFY_IS_NOT_MUCH_SMALLER_THAN(m1, m1);
VERIFY_IS_APPROX( mzero, m1-m1);
// always test operator() on each read-only expression class,
// in order to check const-qualifiers.
// indeed, if an expression class (here Zero) is meant to be read-only,
// hence has no _write() method, the corresponding MatrixBase method (here zero())
// should return a const-qualified object so that it is the const-qualified
// operator() that gets called, which in turn calls _read().
VERIFY_IS_MUCH_SMALLER_THAN(MatrixType::Zero(rows,cols)(r,c), static_cast<Scalar>(1));
// now test copying a row-vector into a (column-)vector and conversely.
square.col(r) = square.row(r).eval();
Matrix<Scalar, 1, MatrixType::RowsAtCompileTime> rv(rows);
Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> cv(rows);
rv = square.row(r);
cv = square.col(r);
VERIFY_IS_APPROX(rv, cv.transpose());
if(cols!=1 && rows!=1 && MatrixType::SizeAtCompileTime!=Dynamic)
{
VERIFY_RAISES_ASSERT(m1 = (m2.block(0,0, rows-1, cols-1)));
}
VERIFY_IS_APPROX(m3 = m1,m1);
MatrixType m4;
VERIFY_IS_APPROX(m4 = m1,m1);
// test swap
m3 = m1;
m1.swap(m2);
VERIFY_IS_APPROX(m3, m2);
if(rows*cols>=3)
{
VERIFY_IS_NOT_APPROX(m3, m1);
}
}
void casting()
{
Matrix4f m = Matrix4f::Random(), m2;
Matrix4d n = m.cast<double>();
VERIFY(m.isApprox(n.cast<float>()));
m2 = m.cast<float>(); // check the specialization when NewType == Type
VERIFY(m.isApprox(m2));
}
void test_basicstuff()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST( basicStuff(Matrix<float, 1, 1>()) );
CALL_SUBTEST( basicStuff(Matrix4d()) );
CALL_SUBTEST( basicStuff(MatrixXcf(3, 3)) );
CALL_SUBTEST( basicStuff(MatrixXi(8, 12)) );
CALL_SUBTEST( basicStuff(MatrixXcd(20, 20)) );
CALL_SUBTEST( basicStuff(Matrix<float, 100, 100>()) );
CALL_SUBTEST( basicStuff(Matrix<long double,Dynamic,Dynamic>(10,10)) );
}
}
<commit_msg>gni, forgot to call the new subtest<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra. Eigen itself is part of the KDE project.
//
// Copyright (C) 2006-2008 Benoit Jacob <[email protected]>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, 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.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#include "main.h"
template<typename MatrixType> void basicStuff(const MatrixType& m)
{
typedef typename MatrixType::Scalar Scalar;
typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType;
int rows = m.rows();
int cols = m.cols();
// this test relies a lot on Random.h, and there's not much more that we can do
// to test it, hence I consider that we will have tested Random.h
MatrixType m1 = MatrixType::Random(rows, cols),
m2 = MatrixType::Random(rows, cols),
m3(rows, cols),
mzero = MatrixType::Zero(rows, cols),
identity = Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime>
::Identity(rows, rows),
square = Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime>::Random(rows, rows);
VectorType v1 = VectorType::Random(rows),
v2 = VectorType::Random(rows),
vzero = VectorType::Zero(rows);
Scalar x = ei_random<Scalar>();
int r = ei_random<int>(0, rows-1),
c = ei_random<int>(0, cols-1);
m1.coeffRef(r,c) = x;
VERIFY_IS_APPROX(x, m1.coeff(r,c));
m1(r,c) = x;
VERIFY_IS_APPROX(x, m1(r,c));
v1.coeffRef(r) = x;
VERIFY_IS_APPROX(x, v1.coeff(r));
v1(r) = x;
VERIFY_IS_APPROX(x, v1(r));
v1[r] = x;
VERIFY_IS_APPROX(x, v1[r]);
VERIFY_IS_APPROX( v1, v1);
VERIFY_IS_NOT_APPROX( v1, 2*v1);
VERIFY_IS_MUCH_SMALLER_THAN( vzero, v1);
if(NumTraits<Scalar>::HasFloatingPoint)
VERIFY_IS_MUCH_SMALLER_THAN( vzero, v1.norm());
VERIFY_IS_NOT_MUCH_SMALLER_THAN(v1, v1);
VERIFY_IS_APPROX( vzero, v1-v1);
VERIFY_IS_APPROX( m1, m1);
VERIFY_IS_NOT_APPROX( m1, 2*m1);
VERIFY_IS_MUCH_SMALLER_THAN( mzero, m1);
VERIFY_IS_NOT_MUCH_SMALLER_THAN(m1, m1);
VERIFY_IS_APPROX( mzero, m1-m1);
// always test operator() on each read-only expression class,
// in order to check const-qualifiers.
// indeed, if an expression class (here Zero) is meant to be read-only,
// hence has no _write() method, the corresponding MatrixBase method (here zero())
// should return a const-qualified object so that it is the const-qualified
// operator() that gets called, which in turn calls _read().
VERIFY_IS_MUCH_SMALLER_THAN(MatrixType::Zero(rows,cols)(r,c), static_cast<Scalar>(1));
// now test copying a row-vector into a (column-)vector and conversely.
square.col(r) = square.row(r).eval();
Matrix<Scalar, 1, MatrixType::RowsAtCompileTime> rv(rows);
Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> cv(rows);
rv = square.row(r);
cv = square.col(r);
VERIFY_IS_APPROX(rv, cv.transpose());
if(cols!=1 && rows!=1 && MatrixType::SizeAtCompileTime!=Dynamic)
{
VERIFY_RAISES_ASSERT(m1 = (m2.block(0,0, rows-1, cols-1)));
}
VERIFY_IS_APPROX(m3 = m1,m1);
MatrixType m4;
VERIFY_IS_APPROX(m4 = m1,m1);
// test swap
m3 = m1;
m1.swap(m2);
VERIFY_IS_APPROX(m3, m2);
if(rows*cols>=3)
{
VERIFY_IS_NOT_APPROX(m3, m1);
}
}
void casting()
{
Matrix4f m = Matrix4f::Random(), m2;
Matrix4d n = m.cast<double>();
VERIFY(m.isApprox(n.cast<float>()));
m2 = m.cast<float>(); // check the specialization when NewType == Type
VERIFY(m.isApprox(m2));
}
void test_basicstuff()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST( basicStuff(Matrix<float, 1, 1>()) );
CALL_SUBTEST( basicStuff(Matrix4d()) );
CALL_SUBTEST( basicStuff(MatrixXcf(3, 3)) );
CALL_SUBTEST( basicStuff(MatrixXi(8, 12)) );
CALL_SUBTEST( basicStuff(MatrixXcd(20, 20)) );
CALL_SUBTEST( basicStuff(Matrix<float, 100, 100>()) );
CALL_SUBTEST( basicStuff(Matrix<long double,Dynamic,Dynamic>(10,10)) );
}
CALL_SUBTEST(casting());
}
<|endoftext|> |
<commit_before>#include <list>
#include <algorithm>
#include "rtmidi/RtMidi.h"
#include "core.hpp"
#include "MidiIO.hpp"
#include "dsp/digital.hpp"
/*
* MIDIToCVInterface converts midi note on/off events, velocity , channel aftertouch, pitch wheel and mod wheel to
* CV
*/
struct MIDIToCVInterface : MidiIO, Module {
enum ParamIds {
RESET_PARAM,
NUM_PARAMS
};
enum InputIds {
NUM_INPUTS
};
enum OutputIds {
PITCH_OUTPUT = 0,
GATE_OUTPUT,
VELOCITY_OUTPUT,
MOD_OUTPUT,
PITCHWHEEL_OUTPUT,
CHANNEL_AFTERTOUCH_OUTPUT,
NUM_OUTPUTS
};
enum LightIds {
RESET_LIGHT,
NUM_LIGHTS
};
std::list<int> notes;
bool pedal = false;
int note = 60; // C4, most modules should use 261.626 Hz
int mod = 0;
int vel = 0;
int afterTouch = 0;
int pitchWheel = 64;
bool retrigger = false;
bool retriggered = false;
SchmittTrigger resetTrigger;
MIDIToCVInterface() : MidiIO(), Module(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS) {
}
~MIDIToCVInterface() {
};
void step();
void pressNote(int note);
void releaseNote(int note);
void processMidi(std::vector<unsigned char> msg);
json_t *toJson() {
json_t *rootJ = json_object();
addBaseJson(rootJ);
return rootJ;
}
void fromJson(json_t *rootJ) {
baseFromJson(rootJ);
}
void reset() {
resetMidi();
}
void resetMidi();
};
void MIDIToCVInterface::resetMidi() {
mod = 0;
pitchWheel = 64;
afterTouch = 0;
vel = 0;
outputs[GATE_OUTPUT].value = 0.0;
notes.clear();
}
void MIDIToCVInterface::step() {
if (isPortOpen()) {
std::vector<unsigned char> message;
// midiIn->getMessage returns empty vector if there are no messages in the queue
getMessage(&message);
while (message.size() > 0) {
processMidi(message);
getMessage(&message);
}
}
outputs[PITCH_OUTPUT].value = ((note - 60)) / 12.0;
bool gate = pedal || !notes.empty();
if (retrigger && retriggered) {
gate = false;
retriggered = false;
}
if (resetTrigger.process(params[RESET_PARAM].value)) {
resetMidi();
return;
}
lights[RESET_LIGHT].value -= lights[RESET_LIGHT].value / 0.55 / engineGetSampleRate(); // fade out light
outputs[GATE_OUTPUT].value = gate ? 10.0 : 0.0;
outputs[MOD_OUTPUT].value = mod / 127.0 * 10.0;
outputs[PITCHWHEEL_OUTPUT].value = (pitchWheel - 64) / 64.0 * 10.0;
outputs[CHANNEL_AFTERTOUCH_OUTPUT].value = afterTouch / 127.0 * 10.0;
outputs[VELOCITY_OUTPUT].value = vel / 127.0 * 10.0;
}
void MIDIToCVInterface::pressNote(int note) {
// Remove existing similar note
auto it = std::find(notes.begin(), notes.end(), note);
if (it != notes.end())
notes.erase(it);
// Push note
notes.push_back(note);
this->note = note;
retriggered = true;
}
void MIDIToCVInterface::releaseNote(int note) {
// Remove the note
auto it = std::find(notes.begin(), notes.end(), note);
if (it != notes.end())
notes.erase(it);
if (pedal) {
// Don't release if pedal is held
} else if (!notes.empty()) {
// Play previous note
auto it2 = notes.end();
it2--;
this->note = *it2;
retriggered = true;
}
}
void MIDIToCVInterface::processMidi(std::vector<unsigned char> msg) {
int channel = msg[0] & 0xf;
int status = (msg[0] >> 4) & 0xf;
int data1 = msg[1];
int data2 = msg[2];
//fprintf(stderr, "channel %d status %d data1 %d data2 %d\n", channel, status, data1,data2);
// Filter channels
if (this->channel >= 0 && this->channel != channel)
return;
switch (status) {
// note off
case 0x8: {
releaseNote(data1);
}
break;
case 0x9: // note on
if (data2 > 0) {
pressNote(data1);
this->vel = data2;
} else {
// For some reason, some keyboards send a "note on" event with a velocity of 0 to signal that the key has been released.
releaseNote(data1);
}
break;
case 0xb: // cc
switch (data1) {
case 0x01: // mod
this->mod = data2;
break;
case 0x40: // sustain
pedal = (data2 >= 64);
releaseNote(-1);
break;
}
break;
case 0xe: // pitch wheel
this->pitchWheel = data2;
break;
case 0xd: // channel aftertouch
this->afterTouch = data1;
break;
}
}
MidiToCVWidget::MidiToCVWidget() {
MIDIToCVInterface *module = new MIDIToCVInterface();
setModule(module);
box.size = Vec(15 * 9, 380);
{
Panel *panel = new LightPanel();
panel->box.size = box.size;
addChild(panel);
}
float margin = 5;
float labelHeight = 15;
float yPos = margin;
float yGap = 35;
addChild(createScrew<ScrewSilver>(Vec(15, 0)));
addChild(createScrew<ScrewSilver>(Vec(box.size.x - 30, 0)));
addChild(createScrew<ScrewSilver>(Vec(15, 365)));
addChild(createScrew<ScrewSilver>(Vec(box.size.x - 30, 365)));
{
Label *label = new Label();
label->box.pos = Vec(box.size.x - margin - 7 * 15, margin);
label->text = "MIDI to CV";
addChild(label);
yPos = labelHeight * 2;
}
addParam(createParam<LEDButton>(Vec(7 * 15, labelHeight), module, MIDIToCVInterface::RESET_PARAM, 0.0, 1.0, 0.0));
addChild(createLight<SmallLight<RedLight>>(Vec(7 * 15 + 5, labelHeight + 5), module, MIDIToCVInterface::RESET_LIGHT));
{
Label *label = new Label();
label->box.pos = Vec(margin, yPos);
label->text = "MIDI Interface";
addChild(label);
yPos += labelHeight + margin;
MidiChoice *midiChoice = new MidiChoice();
midiChoice->midiModule = dynamic_cast<MidiIO *>(module);
midiChoice->box.pos = Vec(margin, yPos);
midiChoice->box.size.x = box.size.x - 10;
addChild(midiChoice);
yPos += midiChoice->box.size.y + margin;
}
{
Label *label = new Label();
label->box.pos = Vec(margin, yPos);
label->text = "Channel";
addChild(label);
yPos += labelHeight + margin;
ChannelChoice *channelChoice = new ChannelChoice();
channelChoice->midiModule = dynamic_cast<MidiIO *>(module);
channelChoice->box.pos = Vec(margin, yPos);
channelChoice->box.size.x = box.size.x - 10;
addChild(channelChoice);
yPos += channelChoice->box.size.y + margin + 15;
}
std::string labels[MIDIToCVInterface::NUM_OUTPUTS] = {"1V/oct", "Gate", "Velocity", "Mod Wheel", "Pitch Wheel",
"Aftertouch"};
for (int i = 0; i < MIDIToCVInterface::NUM_OUTPUTS; i++) {
Label *label = new Label();
label->box.pos = Vec(margin, yPos);
label->text = labels[i];
addChild(label);
addOutput(createOutput<PJ3410Port>(Vec(15 * 6, yPos - 5), module, i));
yPos += yGap + margin;
}
}
void MidiToCVWidget::step() {
ModuleWidget::step();
}
<commit_msg>Add Smoothing to Pitch wheel and mod wheel and fix pedal handling for Midi-to-CV<commit_after>#include <list>
#include <algorithm>
#include "rtmidi/RtMidi.h"
#include "core.hpp"
#include "MidiIO.hpp"
#include "dsp/digital.hpp"
/*
* MIDIToCVInterface converts midi note on/off events, velocity , channel aftertouch, pitch wheel and mod wheel to
* CV
*/
struct MidiValue {
int val = 0; // Controller value
TransitionSmoother tSmooth;
bool changed = false; // Value has been changed by midi message (only if it is in sync!)
};
struct MIDIToCVInterface : MidiIO, Module {
enum ParamIds {
RESET_PARAM,
NUM_PARAMS
};
enum InputIds {
NUM_INPUTS
};
enum OutputIds {
PITCH_OUTPUT = 0,
GATE_OUTPUT,
VELOCITY_OUTPUT,
MOD_OUTPUT,
PITCHWHEEL_OUTPUT,
CHANNEL_AFTERTOUCH_OUTPUT,
NUM_OUTPUTS
};
enum LightIds {
RESET_LIGHT,
NUM_LIGHTS
};
std::list<int> notes;
bool pedal = false;
int note = 60; // C4, most modules should use 261.626 Hz
int vel = 0;
MidiValue mod;
MidiValue afterTouch;
MidiValue pitchWheel;
bool gate = false;
SchmittTrigger resetTrigger;
MIDIToCVInterface() : MidiIO(), Module(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS) {
pitchWheel.val = 64;
pitchWheel.tSmooth.set(0, 0);
}
~MIDIToCVInterface() {
};
void step();
void pressNote(int note);
void releaseNote(int note);
void processMidi(std::vector<unsigned char> msg);
json_t *toJson() {
json_t *rootJ = json_object();
addBaseJson(rootJ);
return rootJ;
}
void fromJson(json_t *rootJ) {
baseFromJson(rootJ);
}
void reset() {
resetMidi();
}
void resetMidi();
};
void MIDIToCVInterface::resetMidi() {
mod.val = 0;
mod.tSmooth.set(0, 0);
pitchWheel.val = 64;
pitchWheel.tSmooth.set(0, 0);
afterTouch.val = 0;
afterTouch.tSmooth.set(0, 0);
vel = 0;
gate = false;
notes.clear();
}
void MIDIToCVInterface::step() {
if (isPortOpen()) {
std::vector<unsigned char> message;
// midiIn->getMessage returns empty vector if there are no messages in the queue
getMessage(&message);
while (message.size() > 0) {
processMidi(message);
getMessage(&message);
}
}
outputs[PITCH_OUTPUT].value = ((note - 60)) / 12.0;
if (resetTrigger.process(params[RESET_PARAM].value)) {
resetMidi();
return;
}
lights[RESET_LIGHT].value -= lights[RESET_LIGHT].value / 0.55 / engineGetSampleRate(); // fade out light
outputs[GATE_OUTPUT].value = gate ? 10.0 : 0.0;
outputs[VELOCITY_OUTPUT].value = vel / 127.0 * 10.0;
int steps = int(engineGetSampleRate() / 32);
if (mod.changed) {
mod.tSmooth.set(outputs[MOD_OUTPUT].value, (mod.val / 127.0 * 10.0), steps);
mod.changed = false;
}
outputs[MOD_OUTPUT].value = mod.tSmooth.next();
if (pitchWheel.changed) {
pitchWheel.tSmooth.set(outputs[PITCHWHEEL_OUTPUT].value, (pitchWheel.val - 64) / 64.0 * 10.0, steps);
pitchWheel.changed = false;
}
outputs[PITCHWHEEL_OUTPUT].value = pitchWheel.tSmooth.next();
/* NOTE: I'll leave out value smoothing for after touch for now. I currently don't
* have an after touch capable device around and I assume it would require different
* smoothing*/
outputs[CHANNEL_AFTERTOUCH_OUTPUT].value = afterTouch.val / 127.0 * 10.0;
}
void MIDIToCVInterface::pressNote(int note) {
// Remove existing similar note
auto it = std::find(notes.begin(), notes.end(), note);
if (it != notes.end())
notes.erase(it);
// Push note
notes.push_back(note);
this->note = note;
gate = true;
}
void MIDIToCVInterface::releaseNote(int note) {
// Remove the note
auto it = std::find(notes.begin(), notes.end(), note);
if (it != notes.end())
notes.erase(it);
if (pedal) {
// Don't release if pedal is held
gate = true;
} else if (!notes.empty()) {
// Play previous note
auto it2 = notes.end();
it2--;
this->note = *it2;
gate = true;
} else {
gate = false;
}
}
void MIDIToCVInterface::processMidi(std::vector<unsigned char> msg) {
int channel = msg[0] & 0xf;
int status = (msg[0] >> 4) & 0xf;
int data1 = msg[1];
int data2 = msg[2];
fprintf(stderr, "channel %d status %d data1 %d data2 %d\n", channel, status, data1, data2);
// Filter channels
if (this->channel >= 0 && this->channel != channel)
return;
switch (status) {
// note off
case 0x8: {
releaseNote(data1);
}
break;
case 0x9: // note on
if (data2 > 0) {
pressNote(data1);
this->vel = data2;
} else {
// For some reason, some keyboards send a "note on" event with a velocity of 0 to signal that the key has been released.
releaseNote(data1);
}
break;
case 0xb: // cc
switch (data1) {
case 0x01: // mod
mod.val = data2;
mod.changed = true;
break;
case 0x40: // sustain
pedal = (data2 >= 64);
if (!pedal) {
releaseNote(-1);
}
break;
}
break;
case 0xe: // pitch wheel
pitchWheel.val = data2;
pitchWheel.changed = true;
break;
case 0xd: // channel aftertouch
afterTouch.val = data1;
afterTouch.changed = true;
break;
}
}
MidiToCVWidget::MidiToCVWidget() {
MIDIToCVInterface *module = new MIDIToCVInterface();
setModule(module);
box.size = Vec(15 * 9, 380);
{
Panel *panel = new LightPanel();
panel->box.size = box.size;
addChild(panel);
}
float margin = 5;
float labelHeight = 15;
float yPos = margin;
float yGap = 35;
addChild(createScrew<ScrewSilver>(Vec(15, 0)));
addChild(createScrew<ScrewSilver>(Vec(box.size.x - 30, 0)));
addChild(createScrew<ScrewSilver>(Vec(15, 365)));
addChild(createScrew<ScrewSilver>(Vec(box.size.x - 30, 365)));
{
Label *label = new Label();
label->box.pos = Vec(box.size.x - margin - 7 * 15, margin);
label->text = "MIDI to CV";
addChild(label);
yPos = labelHeight * 2;
}
addParam(createParam<LEDButton>(Vec(7 * 15, labelHeight), module, MIDIToCVInterface::RESET_PARAM, 0.0, 1.0, 0.0));
addChild(createLight<SmallLight<RedLight>>(Vec(7 * 15 + 5, labelHeight + 5), module,
MIDIToCVInterface::RESET_LIGHT));
{
Label *label = new Label();
label->box.pos = Vec(margin, yPos);
label->text = "MIDI Interface";
addChild(label);
yPos += labelHeight + margin;
MidiChoice *midiChoice = new MidiChoice();
midiChoice->midiModule = dynamic_cast<MidiIO *>(module);
midiChoice->box.pos = Vec(margin, yPos);
midiChoice->box.size.x = box.size.x - 10;
addChild(midiChoice);
yPos += midiChoice->box.size.y + margin;
}
{
Label *label = new Label();
label->box.pos = Vec(margin, yPos);
label->text = "Channel";
addChild(label);
yPos += labelHeight + margin;
ChannelChoice *channelChoice = new ChannelChoice();
channelChoice->midiModule = dynamic_cast<MidiIO *>(module);
channelChoice->box.pos = Vec(margin, yPos);
channelChoice->box.size.x = box.size.x - 10;
addChild(channelChoice);
yPos += channelChoice->box.size.y + margin + 15;
}
std::string labels[MIDIToCVInterface::NUM_OUTPUTS] = {"1V/oct", "Gate", "Velocity", "Mod Wheel", "Pitch Wheel",
"Aftertouch"};
for (int i = 0; i < MIDIToCVInterface::NUM_OUTPUTS; i++) {
Label *label = new Label();
label->box.pos = Vec(margin, yPos);
label->text = labels[i];
addChild(label);
addOutput(createOutput<PJ3410Port>(Vec(15 * 6, yPos - 5), module, i));
yPos += yGap + margin;
}
}
void MidiToCVWidget::step() {
ModuleWidget::step();
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011-2013 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 "intro.h"
#include "ui_intro.h"
#include "util.h"
#include <QFileDialog>
#include <QSettings>
#include <QMessageBox>
#include <boost/filesystem.hpp>
/* Minimum free space (in bytes) needed for data directory */
static const uint64 GB_BYTES = 1000000000LL;
static const uint64 BLOCK_CHAIN_SIZE = 10LL * GB_BYTES;
/* Check free space asynchronously to prevent hanging the UI thread.
Up to one request to check a path is in flight to this thread; when the check()
function runs, the current path is requested from the associated Intro object.
The reply is sent back through a signal.
This ensures that no queue of checking requests is built up while the user is
still entering the path, and that always the most recently entered path is checked as
soon as the thread becomes available.
*/
class FreespaceChecker : public QObject
{
Q_OBJECT
public:
FreespaceChecker(Intro *intro);
enum Status {
ST_OK,
ST_ERROR
};
public slots:
void check();
signals:
void reply(int status, const QString &message, quint64 available);
private:
Intro *intro;
};
#include "intro.moc"
FreespaceChecker::FreespaceChecker(Intro *intro)
{
this->intro = intro;
}
void FreespaceChecker::check()
{
namespace fs = boost::filesystem;
QString dataDirStr = intro->getPathToCheck();
fs::path dataDir = fs::path(dataDirStr.toStdString());
uint64 freeBytesAvailable = 0;
int replyStatus = ST_OK;
QString replyMessage = tr("A new data directory will be created.");
/* Find first parent that exists, so that fs::space does not fail */
fs::path parentDir = dataDir;
fs::path parentDirOld = fs::path();
while(parentDir.has_parent_path() && !fs::exists(parentDir))
{
parentDir = parentDir.parent_path();
/* Check if we make any progress, break if not to prevent an infinite loop here */
if (parentDirOld == parentDir)
break;
parentDirOld = parentDir;
}
try {
freeBytesAvailable = fs::space(parentDir).available;
if(fs::exists(dataDir))
{
if(fs::is_directory(dataDir))
{
QString separator = "<code>" + QDir::toNativeSeparators("/") + tr("name") + "</code>";
replyStatus = ST_OK;
replyMessage = tr("Directory already exists. Add %1 if you intend to create a new directory here.").arg(separator);
} else {
replyStatus = ST_ERROR;
replyMessage = tr("Path already exists, and is not a directory.");
}
}
} catch(fs::filesystem_error &e)
{
/* Parent directory does not exist or is not accessible */
replyStatus = ST_ERROR;
replyMessage = tr("Cannot create data directory here.");
}
emit reply(replyStatus, replyMessage, freeBytesAvailable);
}
Intro::Intro(QWidget *parent) :
QDialog(parent),
ui(new Ui::Intro),
thread(0),
signalled(false)
{
ui->setupUi(this);
ui->sizeWarningLabel->setText(ui->sizeWarningLabel->text().arg(BLOCK_CHAIN_SIZE/GB_BYTES));
startThread();
}
Intro::~Intro()
{
delete ui;
/* Ensure thread is finished before it is deleted */
emit stopThread();
thread->wait();
}
QString Intro::getDataDirectory()
{
return ui->dataDirectory->text();
}
void Intro::setDataDirectory(const QString &dataDir)
{
ui->dataDirectory->setText(dataDir);
if(dataDir == getDefaultDataDirectory())
{
ui->dataDirDefault->setChecked(true);
ui->dataDirectory->setEnabled(false);
ui->ellipsisButton->setEnabled(false);
} else {
ui->dataDirCustom->setChecked(true);
ui->dataDirectory->setEnabled(true);
ui->ellipsisButton->setEnabled(true);
}
}
QString Intro::getDefaultDataDirectory()
{
return QString::fromStdString(GetDefaultDataDir().string());
}
void Intro::pickDataDirectory(bool fIsTestnet)
{
namespace fs = boost::filesystem;;
QSettings settings;
/* If data directory provided on command line, no need to look at settings
or show a picking dialog */
if(!GetArg("-datadir", "").empty())
return;
/* 1) Default data directory for operating system */
QString dataDir = getDefaultDataDirectory();
/* 2) Allow QSettings to override default dir */
dataDir = settings.value("strDataDir", dataDir).toString();
if(!fs::exists(dataDir.toStdString()) || GetBoolArg("-choosedatadir", false))
{
/* If current default data directory does not exist, let the user choose one */
Intro intro;
intro.setDataDirectory(dataDir);
if (!fIsTestnet)
intro.setWindowIcon(QIcon(":icons/bitcoin"));
else
intro.setWindowIcon(QIcon(":icons/bitcoin_testnet"));
while(true)
{
if(!intro.exec())
{
/* Cancel clicked */
exit(0);
}
dataDir = intro.getDataDirectory();
try {
fs::create_directory(dataDir.toStdString());
break;
} catch(fs::filesystem_error &e) {
QMessageBox::critical(0, QObject::tr("Bitcoin"),
QObject::tr("Error: Specified data directory \"%1\" can not be created.").arg(dataDir));
/* fall through, back to choosing screen */
}
}
settings.setValue("strDataDir", dataDir);
}
SoftSetArg("-datadir", dataDir.toStdString());
}
void Intro::setStatus(int status, const QString &message, quint64 bytesAvailable)
{
switch(status)
{
case FreespaceChecker::ST_OK:
ui->errorMessage->setText(message);
ui->errorMessage->setStyleSheet("");
break;
case FreespaceChecker::ST_ERROR:
ui->errorMessage->setText(tr("Error") + ": " + message);
ui->errorMessage->setStyleSheet("QLabel { color: #800000 }");
break;
}
/* Indicate number of bytes available */
if(status == FreespaceChecker::ST_ERROR)
{
ui->freeSpace->setText("");
} else {
QString freeString = QString::number(bytesAvailable/GB_BYTES) + tr("GB of free space available");
if(bytesAvailable < BLOCK_CHAIN_SIZE)
{
freeString += " " + tr("(of %1GB needed)").arg(BLOCK_CHAIN_SIZE/GB_BYTES);
ui->freeSpace->setStyleSheet("QLabel { color: #800000 }");
} else {
ui->freeSpace->setStyleSheet("");
}
ui->freeSpace->setText(freeString + ".");
}
/* Don't allow confirm in ERROR state */
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(status != FreespaceChecker::ST_ERROR);
}
void Intro::on_dataDirectory_textChanged(const QString &dataDirStr)
{
/* Disable OK button until check result comes in */
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
checkPath(dataDirStr);
}
void Intro::on_ellipsisButton_clicked()
{
QString dir = QFileDialog::getExistingDirectory(0, "Choose data directory", ui->dataDirectory->text());
if(!dir.isEmpty())
ui->dataDirectory->setText(dir);
}
void Intro::on_dataDirDefault_clicked()
{
setDataDirectory(getDefaultDataDirectory());
}
void Intro::on_dataDirCustom_clicked()
{
ui->dataDirectory->setEnabled(true);
ui->ellipsisButton->setEnabled(true);
}
void Intro::startThread()
{
thread = new QThread(this);
FreespaceChecker *executor = new FreespaceChecker(this);
executor->moveToThread(thread);
connect(executor, SIGNAL(reply(int,QString,quint64)), this, SLOT(setStatus(int,QString,quint64)));
connect(this, SIGNAL(requestCheck()), executor, SLOT(check()));
/* make sure executor object is deleted in its own thread */
connect(this, SIGNAL(stopThread()), executor, SLOT(deleteLater()));
connect(this, SIGNAL(stopThread()), thread, SLOT(quit()));
thread->start();
}
void Intro::checkPath(const QString &dataDir)
{
mutex.lock();
pathToCheck = dataDir;
if(!signalled)
{
signalled = true;
emit requestCheck();
}
mutex.unlock();
}
QString Intro::getPathToCheck()
{
QString retval;
mutex.lock();
retval = pathToCheck;
signalled = false; /* new request can be queued now */
mutex.unlock();
return retval;
}
<commit_msg>[Qt] use tr() instead of QObject::tr() in intro.cpp<commit_after>// Copyright (c) 2011-2013 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 "intro.h"
#include "ui_intro.h"
#include "util.h"
#include <QFileDialog>
#include <QSettings>
#include <QMessageBox>
#include <boost/filesystem.hpp>
/* Minimum free space (in bytes) needed for data directory */
static const uint64 GB_BYTES = 1000000000LL;
static const uint64 BLOCK_CHAIN_SIZE = 10LL * GB_BYTES;
/* Check free space asynchronously to prevent hanging the UI thread.
Up to one request to check a path is in flight to this thread; when the check()
function runs, the current path is requested from the associated Intro object.
The reply is sent back through a signal.
This ensures that no queue of checking requests is built up while the user is
still entering the path, and that always the most recently entered path is checked as
soon as the thread becomes available.
*/
class FreespaceChecker : public QObject
{
Q_OBJECT
public:
FreespaceChecker(Intro *intro);
enum Status {
ST_OK,
ST_ERROR
};
public slots:
void check();
signals:
void reply(int status, const QString &message, quint64 available);
private:
Intro *intro;
};
#include "intro.moc"
FreespaceChecker::FreespaceChecker(Intro *intro)
{
this->intro = intro;
}
void FreespaceChecker::check()
{
namespace fs = boost::filesystem;
QString dataDirStr = intro->getPathToCheck();
fs::path dataDir = fs::path(dataDirStr.toStdString());
uint64 freeBytesAvailable = 0;
int replyStatus = ST_OK;
QString replyMessage = tr("A new data directory will be created.");
/* Find first parent that exists, so that fs::space does not fail */
fs::path parentDir = dataDir;
fs::path parentDirOld = fs::path();
while(parentDir.has_parent_path() && !fs::exists(parentDir))
{
parentDir = parentDir.parent_path();
/* Check if we make any progress, break if not to prevent an infinite loop here */
if (parentDirOld == parentDir)
break;
parentDirOld = parentDir;
}
try {
freeBytesAvailable = fs::space(parentDir).available;
if(fs::exists(dataDir))
{
if(fs::is_directory(dataDir))
{
QString separator = "<code>" + QDir::toNativeSeparators("/") + tr("name") + "</code>";
replyStatus = ST_OK;
replyMessage = tr("Directory already exists. Add %1 if you intend to create a new directory here.").arg(separator);
} else {
replyStatus = ST_ERROR;
replyMessage = tr("Path already exists, and is not a directory.");
}
}
} catch(fs::filesystem_error &e)
{
/* Parent directory does not exist or is not accessible */
replyStatus = ST_ERROR;
replyMessage = tr("Cannot create data directory here.");
}
emit reply(replyStatus, replyMessage, freeBytesAvailable);
}
Intro::Intro(QWidget *parent) :
QDialog(parent),
ui(new Ui::Intro),
thread(0),
signalled(false)
{
ui->setupUi(this);
ui->sizeWarningLabel->setText(ui->sizeWarningLabel->text().arg(BLOCK_CHAIN_SIZE/GB_BYTES));
startThread();
}
Intro::~Intro()
{
delete ui;
/* Ensure thread is finished before it is deleted */
emit stopThread();
thread->wait();
}
QString Intro::getDataDirectory()
{
return ui->dataDirectory->text();
}
void Intro::setDataDirectory(const QString &dataDir)
{
ui->dataDirectory->setText(dataDir);
if(dataDir == getDefaultDataDirectory())
{
ui->dataDirDefault->setChecked(true);
ui->dataDirectory->setEnabled(false);
ui->ellipsisButton->setEnabled(false);
} else {
ui->dataDirCustom->setChecked(true);
ui->dataDirectory->setEnabled(true);
ui->ellipsisButton->setEnabled(true);
}
}
QString Intro::getDefaultDataDirectory()
{
return QString::fromStdString(GetDefaultDataDir().string());
}
void Intro::pickDataDirectory(bool fIsTestnet)
{
namespace fs = boost::filesystem;;
QSettings settings;
/* If data directory provided on command line, no need to look at settings
or show a picking dialog */
if(!GetArg("-datadir", "").empty())
return;
/* 1) Default data directory for operating system */
QString dataDir = getDefaultDataDirectory();
/* 2) Allow QSettings to override default dir */
dataDir = settings.value("strDataDir", dataDir).toString();
if(!fs::exists(dataDir.toStdString()) || GetBoolArg("-choosedatadir", false))
{
/* If current default data directory does not exist, let the user choose one */
Intro intro;
intro.setDataDirectory(dataDir);
if (!fIsTestnet)
intro.setWindowIcon(QIcon(":icons/bitcoin"));
else
intro.setWindowIcon(QIcon(":icons/bitcoin_testnet"));
while(true)
{
if(!intro.exec())
{
/* Cancel clicked */
exit(0);
}
dataDir = intro.getDataDirectory();
try {
fs::create_directory(dataDir.toStdString());
break;
} catch(fs::filesystem_error &e) {
QMessageBox::critical(0, tr("Bitcoin"),
tr("Error: Specified data directory \"%1\" can not be created.").arg(dataDir));
/* fall through, back to choosing screen */
}
}
settings.setValue("strDataDir", dataDir);
}
SoftSetArg("-datadir", dataDir.toStdString());
}
void Intro::setStatus(int status, const QString &message, quint64 bytesAvailable)
{
switch(status)
{
case FreespaceChecker::ST_OK:
ui->errorMessage->setText(message);
ui->errorMessage->setStyleSheet("");
break;
case FreespaceChecker::ST_ERROR:
ui->errorMessage->setText(tr("Error") + ": " + message);
ui->errorMessage->setStyleSheet("QLabel { color: #800000 }");
break;
}
/* Indicate number of bytes available */
if(status == FreespaceChecker::ST_ERROR)
{
ui->freeSpace->setText("");
} else {
QString freeString = QString::number(bytesAvailable/GB_BYTES) + tr("GB of free space available");
if(bytesAvailable < BLOCK_CHAIN_SIZE)
{
freeString += " " + tr("(of %1GB needed)").arg(BLOCK_CHAIN_SIZE/GB_BYTES);
ui->freeSpace->setStyleSheet("QLabel { color: #800000 }");
} else {
ui->freeSpace->setStyleSheet("");
}
ui->freeSpace->setText(freeString + ".");
}
/* Don't allow confirm in ERROR state */
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(status != FreespaceChecker::ST_ERROR);
}
void Intro::on_dataDirectory_textChanged(const QString &dataDirStr)
{
/* Disable OK button until check result comes in */
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
checkPath(dataDirStr);
}
void Intro::on_ellipsisButton_clicked()
{
QString dir = QFileDialog::getExistingDirectory(0, "Choose data directory", ui->dataDirectory->text());
if(!dir.isEmpty())
ui->dataDirectory->setText(dir);
}
void Intro::on_dataDirDefault_clicked()
{
setDataDirectory(getDefaultDataDirectory());
}
void Intro::on_dataDirCustom_clicked()
{
ui->dataDirectory->setEnabled(true);
ui->ellipsisButton->setEnabled(true);
}
void Intro::startThread()
{
thread = new QThread(this);
FreespaceChecker *executor = new FreespaceChecker(this);
executor->moveToThread(thread);
connect(executor, SIGNAL(reply(int,QString,quint64)), this, SLOT(setStatus(int,QString,quint64)));
connect(this, SIGNAL(requestCheck()), executor, SLOT(check()));
/* make sure executor object is deleted in its own thread */
connect(this, SIGNAL(stopThread()), executor, SLOT(deleteLater()));
connect(this, SIGNAL(stopThread()), thread, SLOT(quit()));
thread->start();
}
void Intro::checkPath(const QString &dataDir)
{
mutex.lock();
pathToCheck = dataDir;
if(!signalled)
{
signalled = true;
emit requestCheck();
}
mutex.unlock();
}
QString Intro::getPathToCheck()
{
QString retval;
mutex.lock();
retval = pathToCheck;
signalled = false; /* new request can be queued now */
mutex.unlock();
return retval;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011-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 "intro.h"
#include "ui_intro.h"
#include "util.h"
#include <boost/filesystem.hpp>
#include <QFileDialog>
#include <QSettings>
#include <QMessageBox>
/* Minimum free space (in bytes) needed for data directory */
static const uint64_t GB_BYTES = 1000000000LL;
static const uint64_t BLOCK_CHAIN_SIZE = 10LL * GB_BYTES;
/* Check free space asynchronously to prevent hanging the UI thread.
Up to one request to check a path is in flight to this thread; when the check()
function runs, the current path is requested from the associated Intro object.
The reply is sent back through a signal.
This ensures that no queue of checking requests is built up while the user is
still entering the path, and that always the most recently entered path is checked as
soon as the thread becomes available.
*/
class FreespaceChecker : public QObject
{
Q_OBJECT
public:
FreespaceChecker(Intro *intro);
enum Status {
ST_OK,
ST_ERROR
};
public slots:
void check();
signals:
void reply(int status, const QString &message, quint64 available);
private:
Intro *intro;
};
#include "intro.moc"
FreespaceChecker::FreespaceChecker(Intro *intro)
{
this->intro = intro;
}
void FreespaceChecker::check()
{
namespace fs = boost::filesystem;
QString dataDirStr = intro->getPathToCheck();
fs::path dataDir = fs::path(dataDirStr.toStdString());
uint64_t freeBytesAvailable = 0;
int replyStatus = ST_OK;
QString replyMessage = tr("A new data directory will be created.");
/* Find first parent that exists, so that fs::space does not fail */
fs::path parentDir = dataDir;
fs::path parentDirOld = fs::path();
while(parentDir.has_parent_path() && !fs::exists(parentDir))
{
parentDir = parentDir.parent_path();
/* Check if we make any progress, break if not to prevent an infinite loop here */
if (parentDirOld == parentDir)
break;
parentDirOld = parentDir;
}
try {
freeBytesAvailable = fs::space(parentDir).available;
if(fs::exists(dataDir))
{
if(fs::is_directory(dataDir))
{
QString separator = "<code>" + QDir::toNativeSeparators("/") + tr("name") + "</code>";
replyStatus = ST_OK;
replyMessage = tr("Directory already exists. Add %1 if you intend to create a new directory here.").arg(separator);
} else {
replyStatus = ST_ERROR;
replyMessage = tr("Path already exists, and is not a directory.");
}
}
} catch(fs::filesystem_error &e)
{
/* Parent directory does not exist or is not accessible */
replyStatus = ST_ERROR;
replyMessage = tr("Cannot create data directory here.");
}
emit reply(replyStatus, replyMessage, freeBytesAvailable);
}
Intro::Intro(QWidget *parent) :
QDialog(parent),
ui(new Ui::Intro),
thread(0),
signalled(false)
{
ui->setupUi(this);
ui->sizeWarningLabel->setText(ui->sizeWarningLabel->text().arg(BLOCK_CHAIN_SIZE/GB_BYTES));
startThread();
}
Intro::~Intro()
{
delete ui;
/* Ensure thread is finished before it is deleted */
emit stopThread();
thread->wait();
}
QString Intro::getDataDirectory()
{
return ui->dataDirectory->text();
}
void Intro::setDataDirectory(const QString &dataDir)
{
ui->dataDirectory->setText(dataDir);
if(dataDir == getDefaultDataDirectory())
{
ui->dataDirDefault->setChecked(true);
ui->dataDirectory->setEnabled(false);
ui->ellipsisButton->setEnabled(false);
} else {
ui->dataDirCustom->setChecked(true);
ui->dataDirectory->setEnabled(true);
ui->ellipsisButton->setEnabled(true);
}
}
QString Intro::getDefaultDataDirectory()
{
return QString::fromStdString(GetDefaultDataDir().string());
}
void Intro::pickDataDirectory(bool fIsTestnet)
{
namespace fs = boost::filesystem;
QSettings settings;
/* If data directory provided on command line, no need to look at settings
or show a picking dialog */
if(!GetArg("-datadir", "").empty())
return;
/* 1) Default data directory for operating system */
QString dataDir = getDefaultDataDirectory();
/* 2) Allow QSettings to override default dir */
dataDir = settings.value("strDataDir", dataDir).toString();
if(!fs::exists(dataDir.toStdString()) || GetBoolArg("-choosedatadir", false))
{
/* If current default data directory does not exist, let the user choose one */
Intro intro;
intro.setDataDirectory(dataDir);
if (!fIsTestnet)
intro.setWindowIcon(QIcon(":icons/bitcoin"));
else
intro.setWindowIcon(QIcon(":icons/bitcoin_testnet"));
while(true)
{
if(!intro.exec())
{
/* Cancel clicked */
exit(0);
}
dataDir = intro.getDataDirectory();
try {
fs::create_directory(dataDir.toStdString());
break;
} catch(fs::filesystem_error &e) {
QMessageBox::critical(0, tr("Bitcoin"),
tr("Error: Specified data directory \"%1\" can not be created.").arg(dataDir));
/* fall through, back to choosing screen */
}
}
settings.setValue("strDataDir", dataDir);
}
SoftSetArg("-datadir", dataDir.toStdString());
}
void Intro::setStatus(int status, const QString &message, quint64 bytesAvailable)
{
switch(status)
{
case FreespaceChecker::ST_OK:
ui->errorMessage->setText(message);
ui->errorMessage->setStyleSheet("");
break;
case FreespaceChecker::ST_ERROR:
ui->errorMessage->setText(tr("Error") + ": " + message);
ui->errorMessage->setStyleSheet("QLabel { color: #800000 }");
break;
}
/* Indicate number of bytes available */
if(status == FreespaceChecker::ST_ERROR)
{
ui->freeSpace->setText("");
} else {
QString freeString = QString::number(bytesAvailable/GB_BYTES) + tr("GB of free space available");
if(bytesAvailable < BLOCK_CHAIN_SIZE)
{
freeString += " " + tr("(of %1GB needed)").arg(BLOCK_CHAIN_SIZE/GB_BYTES);
ui->freeSpace->setStyleSheet("QLabel { color: #800000 }");
} else {
ui->freeSpace->setStyleSheet("");
}
ui->freeSpace->setText(freeString + ".");
}
/* Don't allow confirm in ERROR state */
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(status != FreespaceChecker::ST_ERROR);
}
void Intro::on_dataDirectory_textChanged(const QString &dataDirStr)
{
/* Disable OK button until check result comes in */
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
checkPath(dataDirStr);
}
void Intro::on_ellipsisButton_clicked()
{
QString dir = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(0, "Choose data directory", ui->dataDirectory->text()));
if(!dir.isEmpty())
ui->dataDirectory->setText(dir);
}
void Intro::on_dataDirDefault_clicked()
{
setDataDirectory(getDefaultDataDirectory());
}
void Intro::on_dataDirCustom_clicked()
{
ui->dataDirectory->setEnabled(true);
ui->ellipsisButton->setEnabled(true);
}
void Intro::startThread()
{
thread = new QThread(this);
FreespaceChecker *executor = new FreespaceChecker(this);
executor->moveToThread(thread);
connect(executor, SIGNAL(reply(int,QString,quint64)), this, SLOT(setStatus(int,QString,quint64)));
connect(this, SIGNAL(requestCheck()), executor, SLOT(check()));
/* make sure executor object is deleted in its own thread */
connect(this, SIGNAL(stopThread()), executor, SLOT(deleteLater()));
connect(this, SIGNAL(stopThread()), thread, SLOT(quit()));
thread->start();
}
void Intro::checkPath(const QString &dataDir)
{
mutex.lock();
pathToCheck = dataDir;
if(!signalled)
{
signalled = true;
emit requestCheck();
}
mutex.unlock();
}
QString Intro::getPathToCheck()
{
QString retval;
mutex.lock();
retval = pathToCheck;
signalled = false; /* new request can be queued now */
mutex.unlock();
return retval;
}
<commit_msg>qt: Adjust BLOCK_CHAIN_SIZE to 20GB<commit_after>// Copyright (c) 2011-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 "intro.h"
#include "ui_intro.h"
#include "util.h"
#include <boost/filesystem.hpp>
#include <QFileDialog>
#include <QSettings>
#include <QMessageBox>
/* Minimum free space (in bytes) needed for data directory */
static const uint64_t GB_BYTES = 1000000000LL;
static const uint64_t BLOCK_CHAIN_SIZE = 20LL * GB_BYTES;
/* Check free space asynchronously to prevent hanging the UI thread.
Up to one request to check a path is in flight to this thread; when the check()
function runs, the current path is requested from the associated Intro object.
The reply is sent back through a signal.
This ensures that no queue of checking requests is built up while the user is
still entering the path, and that always the most recently entered path is checked as
soon as the thread becomes available.
*/
class FreespaceChecker : public QObject
{
Q_OBJECT
public:
FreespaceChecker(Intro *intro);
enum Status {
ST_OK,
ST_ERROR
};
public slots:
void check();
signals:
void reply(int status, const QString &message, quint64 available);
private:
Intro *intro;
};
#include "intro.moc"
FreespaceChecker::FreespaceChecker(Intro *intro)
{
this->intro = intro;
}
void FreespaceChecker::check()
{
namespace fs = boost::filesystem;
QString dataDirStr = intro->getPathToCheck();
fs::path dataDir = fs::path(dataDirStr.toStdString());
uint64_t freeBytesAvailable = 0;
int replyStatus = ST_OK;
QString replyMessage = tr("A new data directory will be created.");
/* Find first parent that exists, so that fs::space does not fail */
fs::path parentDir = dataDir;
fs::path parentDirOld = fs::path();
while(parentDir.has_parent_path() && !fs::exists(parentDir))
{
parentDir = parentDir.parent_path();
/* Check if we make any progress, break if not to prevent an infinite loop here */
if (parentDirOld == parentDir)
break;
parentDirOld = parentDir;
}
try {
freeBytesAvailable = fs::space(parentDir).available;
if(fs::exists(dataDir))
{
if(fs::is_directory(dataDir))
{
QString separator = "<code>" + QDir::toNativeSeparators("/") + tr("name") + "</code>";
replyStatus = ST_OK;
replyMessage = tr("Directory already exists. Add %1 if you intend to create a new directory here.").arg(separator);
} else {
replyStatus = ST_ERROR;
replyMessage = tr("Path already exists, and is not a directory.");
}
}
} catch(fs::filesystem_error &e)
{
/* Parent directory does not exist or is not accessible */
replyStatus = ST_ERROR;
replyMessage = tr("Cannot create data directory here.");
}
emit reply(replyStatus, replyMessage, freeBytesAvailable);
}
Intro::Intro(QWidget *parent) :
QDialog(parent),
ui(new Ui::Intro),
thread(0),
signalled(false)
{
ui->setupUi(this);
ui->sizeWarningLabel->setText(ui->sizeWarningLabel->text().arg(BLOCK_CHAIN_SIZE/GB_BYTES));
startThread();
}
Intro::~Intro()
{
delete ui;
/* Ensure thread is finished before it is deleted */
emit stopThread();
thread->wait();
}
QString Intro::getDataDirectory()
{
return ui->dataDirectory->text();
}
void Intro::setDataDirectory(const QString &dataDir)
{
ui->dataDirectory->setText(dataDir);
if(dataDir == getDefaultDataDirectory())
{
ui->dataDirDefault->setChecked(true);
ui->dataDirectory->setEnabled(false);
ui->ellipsisButton->setEnabled(false);
} else {
ui->dataDirCustom->setChecked(true);
ui->dataDirectory->setEnabled(true);
ui->ellipsisButton->setEnabled(true);
}
}
QString Intro::getDefaultDataDirectory()
{
return QString::fromStdString(GetDefaultDataDir().string());
}
void Intro::pickDataDirectory(bool fIsTestnet)
{
namespace fs = boost::filesystem;
QSettings settings;
/* If data directory provided on command line, no need to look at settings
or show a picking dialog */
if(!GetArg("-datadir", "").empty())
return;
/* 1) Default data directory for operating system */
QString dataDir = getDefaultDataDirectory();
/* 2) Allow QSettings to override default dir */
dataDir = settings.value("strDataDir", dataDir).toString();
if(!fs::exists(dataDir.toStdString()) || GetBoolArg("-choosedatadir", false))
{
/* If current default data directory does not exist, let the user choose one */
Intro intro;
intro.setDataDirectory(dataDir);
if (!fIsTestnet)
intro.setWindowIcon(QIcon(":icons/bitcoin"));
else
intro.setWindowIcon(QIcon(":icons/bitcoin_testnet"));
while(true)
{
if(!intro.exec())
{
/* Cancel clicked */
exit(0);
}
dataDir = intro.getDataDirectory();
try {
fs::create_directory(dataDir.toStdString());
break;
} catch(fs::filesystem_error &e) {
QMessageBox::critical(0, tr("Bitcoin"),
tr("Error: Specified data directory \"%1\" can not be created.").arg(dataDir));
/* fall through, back to choosing screen */
}
}
settings.setValue("strDataDir", dataDir);
}
SoftSetArg("-datadir", dataDir.toStdString());
}
void Intro::setStatus(int status, const QString &message, quint64 bytesAvailable)
{
switch(status)
{
case FreespaceChecker::ST_OK:
ui->errorMessage->setText(message);
ui->errorMessage->setStyleSheet("");
break;
case FreespaceChecker::ST_ERROR:
ui->errorMessage->setText(tr("Error") + ": " + message);
ui->errorMessage->setStyleSheet("QLabel { color: #800000 }");
break;
}
/* Indicate number of bytes available */
if(status == FreespaceChecker::ST_ERROR)
{
ui->freeSpace->setText("");
} else {
QString freeString = QString::number(bytesAvailable/GB_BYTES) + tr("GB of free space available");
if(bytesAvailable < BLOCK_CHAIN_SIZE)
{
freeString += " " + tr("(of %1GB needed)").arg(BLOCK_CHAIN_SIZE/GB_BYTES);
ui->freeSpace->setStyleSheet("QLabel { color: #800000 }");
} else {
ui->freeSpace->setStyleSheet("");
}
ui->freeSpace->setText(freeString + ".");
}
/* Don't allow confirm in ERROR state */
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(status != FreespaceChecker::ST_ERROR);
}
void Intro::on_dataDirectory_textChanged(const QString &dataDirStr)
{
/* Disable OK button until check result comes in */
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
checkPath(dataDirStr);
}
void Intro::on_ellipsisButton_clicked()
{
QString dir = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(0, "Choose data directory", ui->dataDirectory->text()));
if(!dir.isEmpty())
ui->dataDirectory->setText(dir);
}
void Intro::on_dataDirDefault_clicked()
{
setDataDirectory(getDefaultDataDirectory());
}
void Intro::on_dataDirCustom_clicked()
{
ui->dataDirectory->setEnabled(true);
ui->ellipsisButton->setEnabled(true);
}
void Intro::startThread()
{
thread = new QThread(this);
FreespaceChecker *executor = new FreespaceChecker(this);
executor->moveToThread(thread);
connect(executor, SIGNAL(reply(int,QString,quint64)), this, SLOT(setStatus(int,QString,quint64)));
connect(this, SIGNAL(requestCheck()), executor, SLOT(check()));
/* make sure executor object is deleted in its own thread */
connect(this, SIGNAL(stopThread()), executor, SLOT(deleteLater()));
connect(this, SIGNAL(stopThread()), thread, SLOT(quit()));
thread->start();
}
void Intro::checkPath(const QString &dataDir)
{
mutex.lock();
pathToCheck = dataDir;
if(!signalled)
{
signalled = true;
emit requestCheck();
}
mutex.unlock();
}
QString Intro::getPathToCheck()
{
QString retval;
mutex.lock();
retval = pathToCheck;
signalled = false; /* new request can be queued now */
mutex.unlock();
return retval;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif
#include <fs.h>
#include <qt/intro.h>
#include <qt/forms/ui_intro.h>
#include <qt/guiutil.h>
#include <interfaces/node.h>
#include <util.h>
#include <QFileDialog>
#include <QSettings>
#include <QMessageBox>
#include <cmath>
static const uint64_t GB_BYTES = 1000000000LL;
/* Minimum free space (in GB) needed for data directory */
constexpr uint64_t BLOCK_CHAIN_SIZE = 18;
/* Minimum free space (in GB) needed for data directory when pruned; Does not include prune target */
static const uint64_t CHAIN_STATE_SIZE = 3;
/* Total required space (in GB) depending on user choice (prune, not prune) */
static uint64_t requiredSpace;
/* Check free space asynchronously to prevent hanging the UI thread.
Up to one request to check a path is in flight to this thread; when the check()
function runs, the current path is requested from the associated Intro object.
The reply is sent back through a signal.
This ensures that no queue of checking requests is built up while the user is
still entering the path, and that always the most recently entered path is checked as
soon as the thread becomes available.
*/
class FreespaceChecker : public QObject
{
Q_OBJECT
public:
explicit FreespaceChecker(Intro *intro);
enum Status {
ST_OK,
ST_ERROR
};
public Q_SLOTS:
void check();
Q_SIGNALS:
void reply(int status, const QString &message, quint64 available);
private:
Intro *intro;
};
#include <qt/intro.moc>
FreespaceChecker::FreespaceChecker(Intro *_intro)
{
this->intro = _intro;
}
void FreespaceChecker::check()
{
QString dataDirStr = intro->getPathToCheck();
fs::path dataDir = GUIUtil::qstringToBoostPath(dataDirStr);
uint64_t freeBytesAvailable = 0;
int replyStatus = ST_OK;
QString replyMessage = tr("A new data directory will be created.");
/* Find first parent that exists, so that fs::space does not fail */
fs::path parentDir = dataDir;
fs::path parentDirOld = fs::path();
while(parentDir.has_parent_path() && !fs::exists(parentDir))
{
parentDir = parentDir.parent_path();
/* Check if we make any progress, break if not to prevent an infinite loop here */
if (parentDirOld == parentDir)
break;
parentDirOld = parentDir;
}
try {
freeBytesAvailable = fs::space(parentDir).available;
if(fs::exists(dataDir))
{
if(fs::is_directory(dataDir))
{
QString separator = "<code>" + QDir::toNativeSeparators("/") + tr("name") + "</code>";
replyStatus = ST_OK;
replyMessage = tr("Directory already exists. Add %1 if you intend to create a new directory here.").arg(separator);
} else {
replyStatus = ST_ERROR;
replyMessage = tr("Path already exists, and is not a directory.");
}
}
} catch (const fs::filesystem_error&)
{
/* Parent directory does not exist or is not accessible */
replyStatus = ST_ERROR;
replyMessage = tr("Cannot create data directory here.");
}
Q_EMIT reply(replyStatus, replyMessage, freeBytesAvailable);
}
Intro::Intro(QWidget *parent) :
QDialog(parent),
ui(new Ui::Intro),
thread(0),
signalled(false)
{
ui->setupUi(this);
ui->welcomeLabel->setText(ui->welcomeLabel->text().arg(tr(PACKAGE_NAME)));
ui->storageLabel->setText(ui->storageLabel->text().arg(tr(PACKAGE_NAME)));
ui->lblExplanation1->setText(ui->lblExplanation1->text()
.arg(tr(PACKAGE_NAME))
.arg(BLOCK_CHAIN_SIZE)
.arg(2009)
.arg(tr("Litecoin"))
);
ui->lblExplanation2->setText(ui->lblExplanation2->text().arg(tr(PACKAGE_NAME)));
uint64_t pruneTarget = std::max<int64_t>(0, gArgs.GetArg("-prune", 0));
requiredSpace = BLOCK_CHAIN_SIZE;
QString storageRequiresMsg = tr("At least %1 GB of data will be stored in this directory, and it will grow over time.");
if (pruneTarget) {
uint64_t prunedGBs = std::ceil(pruneTarget * 1024 * 1024.0 / GB_BYTES);
if (prunedGBs <= requiredSpace) {
requiredSpace = prunedGBs;
storageRequiresMsg = tr("Approximately %1 GB of data will be stored in this directory.");
}
ui->lblExplanation3->setVisible(true);
} else {
ui->lblExplanation3->setVisible(false);
}
requiredSpace += CHAIN_STATE_SIZE;
ui->sizeWarningLabel->setText(
tr("%1 will download and store a copy of the Litecoin block chain.").arg(tr(PACKAGE_NAME)) + " " +
storageRequiresMsg.arg(requiredSpace) + " " +
tr("The wallet will also be stored in this directory.")
);
startThread();
}
Intro::~Intro()
{
delete ui;
/* Ensure thread is finished before it is deleted */
Q_EMIT stopThread();
thread->wait();
}
QString Intro::getDataDirectory()
{
return ui->dataDirectory->text();
}
void Intro::setDataDirectory(const QString &dataDir)
{
ui->dataDirectory->setText(dataDir);
if(dataDir == getDefaultDataDirectory())
{
ui->dataDirDefault->setChecked(true);
ui->dataDirectory->setEnabled(false);
ui->ellipsisButton->setEnabled(false);
} else {
ui->dataDirCustom->setChecked(true);
ui->dataDirectory->setEnabled(true);
ui->ellipsisButton->setEnabled(true);
}
}
QString Intro::getDefaultDataDirectory()
{
return GUIUtil::boostPathToQString(GetDefaultDataDir());
}
bool Intro::pickDataDirectory(interfaces::Node& node)
{
QSettings settings;
/* If data directory provided on command line, no need to look at settings
or show a picking dialog */
if(!gArgs.GetArg("-datadir", "").empty())
return true;
/* 1) Default data directory for operating system */
QString dataDir = getDefaultDataDirectory();
/* 2) Allow QSettings to override default dir */
dataDir = settings.value("strDataDir", dataDir).toString();
if(!fs::exists(GUIUtil::qstringToBoostPath(dataDir)) || gArgs.GetBoolArg("-choosedatadir", DEFAULT_CHOOSE_DATADIR) || settings.value("fReset", false).toBool() || gArgs.GetBoolArg("-resetguisettings", false))
{
/* If current default data directory does not exist, let the user choose one */
Intro intro;
intro.setDataDirectory(dataDir);
intro.setWindowIcon(QIcon(":icons/bitcoin"));
while(true)
{
if(!intro.exec())
{
/* Cancel clicked */
return false;
}
dataDir = intro.getDataDirectory();
try {
if (TryCreateDirectories(GUIUtil::qstringToBoostPath(dataDir))) {
// If a new data directory has been created, make wallets subdirectory too
TryCreateDirectories(GUIUtil::qstringToBoostPath(dataDir) / "wallets");
}
break;
} catch (const fs::filesystem_error&) {
QMessageBox::critical(0, tr(PACKAGE_NAME),
tr("Error: Specified data directory \"%1\" cannot be created.").arg(dataDir));
/* fall through, back to choosing screen */
}
}
settings.setValue("strDataDir", dataDir);
settings.setValue("fReset", false);
}
/* Only override -datadir if different from the default, to make it possible to
* override -datadir in the bitcoin.conf file in the default data directory
* (to be consistent with bitcoind behavior)
*/
if(dataDir != getDefaultDataDirectory()) {
node.softSetArg("-datadir", GUIUtil::qstringToBoostPath(dataDir).string()); // use OS locale for path setting
}
return true;
}
void Intro::setStatus(int status, const QString &message, quint64 bytesAvailable)
{
switch(status)
{
case FreespaceChecker::ST_OK:
ui->errorMessage->setText(message);
ui->errorMessage->setStyleSheet("");
break;
case FreespaceChecker::ST_ERROR:
ui->errorMessage->setText(tr("Error") + ": " + message);
ui->errorMessage->setStyleSheet("QLabel { color: #800000 }");
break;
}
/* Indicate number of bytes available */
if(status == FreespaceChecker::ST_ERROR)
{
ui->freeSpace->setText("");
} else {
QString freeString = tr("%n GB of free space available", "", bytesAvailable/GB_BYTES);
if(bytesAvailable < requiredSpace * GB_BYTES)
{
freeString += " " + tr("(of %n GB needed)", "", requiredSpace);
ui->freeSpace->setStyleSheet("QLabel { color: #800000 }");
} else {
ui->freeSpace->setStyleSheet("");
}
ui->freeSpace->setText(freeString + ".");
}
/* Don't allow confirm in ERROR state */
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(status != FreespaceChecker::ST_ERROR);
}
void Intro::on_dataDirectory_textChanged(const QString &dataDirStr)
{
/* Disable OK button until check result comes in */
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
checkPath(dataDirStr);
}
void Intro::on_ellipsisButton_clicked()
{
QString dir = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(0, "Choose data directory", ui->dataDirectory->text()));
if(!dir.isEmpty())
ui->dataDirectory->setText(dir);
}
void Intro::on_dataDirDefault_clicked()
{
setDataDirectory(getDefaultDataDirectory());
}
void Intro::on_dataDirCustom_clicked()
{
ui->dataDirectory->setEnabled(true);
ui->ellipsisButton->setEnabled(true);
}
void Intro::startThread()
{
thread = new QThread(this);
FreespaceChecker *executor = new FreespaceChecker(this);
executor->moveToThread(thread);
connect(executor, SIGNAL(reply(int,QString,quint64)), this, SLOT(setStatus(int,QString,quint64)));
connect(this, SIGNAL(requestCheck()), executor, SLOT(check()));
/* make sure executor object is deleted in its own thread */
connect(this, SIGNAL(stopThread()), executor, SLOT(deleteLater()));
connect(this, SIGNAL(stopThread()), thread, SLOT(quit()));
thread->start();
}
void Intro::checkPath(const QString &dataDir)
{
mutex.lock();
pathToCheck = dataDir;
if(!signalled)
{
signalled = true;
Q_EMIT requestCheck();
}
mutex.unlock();
}
QString Intro::getPathToCheck()
{
QString retval;
mutex.lock();
retval = pathToCheck;
signalled = false; /* new request can be queued now */
mutex.unlock();
return retval;
}
<commit_msg>Litecoin: Update blockchain size<commit_after>// Copyright (c) 2011-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif
#include <fs.h>
#include <qt/intro.h>
#include <qt/forms/ui_intro.h>
#include <qt/guiutil.h>
#include <interfaces/node.h>
#include <util.h>
#include <QFileDialog>
#include <QSettings>
#include <QMessageBox>
#include <cmath>
static const uint64_t GB_BYTES = 1000000000LL;
/* Minimum free space (in GB) needed for data directory */
constexpr uint64_t BLOCK_CHAIN_SIZE = 20;
/* Minimum free space (in GB) needed for data directory when pruned; Does not include prune target */
static const uint64_t CHAIN_STATE_SIZE = 3;
/* Total required space (in GB) depending on user choice (prune, not prune) */
static uint64_t requiredSpace;
/* Check free space asynchronously to prevent hanging the UI thread.
Up to one request to check a path is in flight to this thread; when the check()
function runs, the current path is requested from the associated Intro object.
The reply is sent back through a signal.
This ensures that no queue of checking requests is built up while the user is
still entering the path, and that always the most recently entered path is checked as
soon as the thread becomes available.
*/
class FreespaceChecker : public QObject
{
Q_OBJECT
public:
explicit FreespaceChecker(Intro *intro);
enum Status {
ST_OK,
ST_ERROR
};
public Q_SLOTS:
void check();
Q_SIGNALS:
void reply(int status, const QString &message, quint64 available);
private:
Intro *intro;
};
#include <qt/intro.moc>
FreespaceChecker::FreespaceChecker(Intro *_intro)
{
this->intro = _intro;
}
void FreespaceChecker::check()
{
QString dataDirStr = intro->getPathToCheck();
fs::path dataDir = GUIUtil::qstringToBoostPath(dataDirStr);
uint64_t freeBytesAvailable = 0;
int replyStatus = ST_OK;
QString replyMessage = tr("A new data directory will be created.");
/* Find first parent that exists, so that fs::space does not fail */
fs::path parentDir = dataDir;
fs::path parentDirOld = fs::path();
while(parentDir.has_parent_path() && !fs::exists(parentDir))
{
parentDir = parentDir.parent_path();
/* Check if we make any progress, break if not to prevent an infinite loop here */
if (parentDirOld == parentDir)
break;
parentDirOld = parentDir;
}
try {
freeBytesAvailable = fs::space(parentDir).available;
if(fs::exists(dataDir))
{
if(fs::is_directory(dataDir))
{
QString separator = "<code>" + QDir::toNativeSeparators("/") + tr("name") + "</code>";
replyStatus = ST_OK;
replyMessage = tr("Directory already exists. Add %1 if you intend to create a new directory here.").arg(separator);
} else {
replyStatus = ST_ERROR;
replyMessage = tr("Path already exists, and is not a directory.");
}
}
} catch (const fs::filesystem_error&)
{
/* Parent directory does not exist or is not accessible */
replyStatus = ST_ERROR;
replyMessage = tr("Cannot create data directory here.");
}
Q_EMIT reply(replyStatus, replyMessage, freeBytesAvailable);
}
Intro::Intro(QWidget *parent) :
QDialog(parent),
ui(new Ui::Intro),
thread(0),
signalled(false)
{
ui->setupUi(this);
ui->welcomeLabel->setText(ui->welcomeLabel->text().arg(tr(PACKAGE_NAME)));
ui->storageLabel->setText(ui->storageLabel->text().arg(tr(PACKAGE_NAME)));
ui->lblExplanation1->setText(ui->lblExplanation1->text()
.arg(tr(PACKAGE_NAME))
.arg(BLOCK_CHAIN_SIZE)
.arg(2009)
.arg(tr("Litecoin"))
);
ui->lblExplanation2->setText(ui->lblExplanation2->text().arg(tr(PACKAGE_NAME)));
uint64_t pruneTarget = std::max<int64_t>(0, gArgs.GetArg("-prune", 0));
requiredSpace = BLOCK_CHAIN_SIZE;
QString storageRequiresMsg = tr("At least %1 GB of data will be stored in this directory, and it will grow over time.");
if (pruneTarget) {
uint64_t prunedGBs = std::ceil(pruneTarget * 1024 * 1024.0 / GB_BYTES);
if (prunedGBs <= requiredSpace) {
requiredSpace = prunedGBs;
storageRequiresMsg = tr("Approximately %1 GB of data will be stored in this directory.");
}
ui->lblExplanation3->setVisible(true);
} else {
ui->lblExplanation3->setVisible(false);
}
requiredSpace += CHAIN_STATE_SIZE;
ui->sizeWarningLabel->setText(
tr("%1 will download and store a copy of the Litecoin block chain.").arg(tr(PACKAGE_NAME)) + " " +
storageRequiresMsg.arg(requiredSpace) + " " +
tr("The wallet will also be stored in this directory.")
);
startThread();
}
Intro::~Intro()
{
delete ui;
/* Ensure thread is finished before it is deleted */
Q_EMIT stopThread();
thread->wait();
}
QString Intro::getDataDirectory()
{
return ui->dataDirectory->text();
}
void Intro::setDataDirectory(const QString &dataDir)
{
ui->dataDirectory->setText(dataDir);
if(dataDir == getDefaultDataDirectory())
{
ui->dataDirDefault->setChecked(true);
ui->dataDirectory->setEnabled(false);
ui->ellipsisButton->setEnabled(false);
} else {
ui->dataDirCustom->setChecked(true);
ui->dataDirectory->setEnabled(true);
ui->ellipsisButton->setEnabled(true);
}
}
QString Intro::getDefaultDataDirectory()
{
return GUIUtil::boostPathToQString(GetDefaultDataDir());
}
bool Intro::pickDataDirectory(interfaces::Node& node)
{
QSettings settings;
/* If data directory provided on command line, no need to look at settings
or show a picking dialog */
if(!gArgs.GetArg("-datadir", "").empty())
return true;
/* 1) Default data directory for operating system */
QString dataDir = getDefaultDataDirectory();
/* 2) Allow QSettings to override default dir */
dataDir = settings.value("strDataDir", dataDir).toString();
if(!fs::exists(GUIUtil::qstringToBoostPath(dataDir)) || gArgs.GetBoolArg("-choosedatadir", DEFAULT_CHOOSE_DATADIR) || settings.value("fReset", false).toBool() || gArgs.GetBoolArg("-resetguisettings", false))
{
/* If current default data directory does not exist, let the user choose one */
Intro intro;
intro.setDataDirectory(dataDir);
intro.setWindowIcon(QIcon(":icons/bitcoin"));
while(true)
{
if(!intro.exec())
{
/* Cancel clicked */
return false;
}
dataDir = intro.getDataDirectory();
try {
if (TryCreateDirectories(GUIUtil::qstringToBoostPath(dataDir))) {
// If a new data directory has been created, make wallets subdirectory too
TryCreateDirectories(GUIUtil::qstringToBoostPath(dataDir) / "wallets");
}
break;
} catch (const fs::filesystem_error&) {
QMessageBox::critical(0, tr(PACKAGE_NAME),
tr("Error: Specified data directory \"%1\" cannot be created.").arg(dataDir));
/* fall through, back to choosing screen */
}
}
settings.setValue("strDataDir", dataDir);
settings.setValue("fReset", false);
}
/* Only override -datadir if different from the default, to make it possible to
* override -datadir in the bitcoin.conf file in the default data directory
* (to be consistent with bitcoind behavior)
*/
if(dataDir != getDefaultDataDirectory()) {
node.softSetArg("-datadir", GUIUtil::qstringToBoostPath(dataDir).string()); // use OS locale for path setting
}
return true;
}
void Intro::setStatus(int status, const QString &message, quint64 bytesAvailable)
{
switch(status)
{
case FreespaceChecker::ST_OK:
ui->errorMessage->setText(message);
ui->errorMessage->setStyleSheet("");
break;
case FreespaceChecker::ST_ERROR:
ui->errorMessage->setText(tr("Error") + ": " + message);
ui->errorMessage->setStyleSheet("QLabel { color: #800000 }");
break;
}
/* Indicate number of bytes available */
if(status == FreespaceChecker::ST_ERROR)
{
ui->freeSpace->setText("");
} else {
QString freeString = tr("%n GB of free space available", "", bytesAvailable/GB_BYTES);
if(bytesAvailable < requiredSpace * GB_BYTES)
{
freeString += " " + tr("(of %n GB needed)", "", requiredSpace);
ui->freeSpace->setStyleSheet("QLabel { color: #800000 }");
} else {
ui->freeSpace->setStyleSheet("");
}
ui->freeSpace->setText(freeString + ".");
}
/* Don't allow confirm in ERROR state */
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(status != FreespaceChecker::ST_ERROR);
}
void Intro::on_dataDirectory_textChanged(const QString &dataDirStr)
{
/* Disable OK button until check result comes in */
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
checkPath(dataDirStr);
}
void Intro::on_ellipsisButton_clicked()
{
QString dir = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(0, "Choose data directory", ui->dataDirectory->text()));
if(!dir.isEmpty())
ui->dataDirectory->setText(dir);
}
void Intro::on_dataDirDefault_clicked()
{
setDataDirectory(getDefaultDataDirectory());
}
void Intro::on_dataDirCustom_clicked()
{
ui->dataDirectory->setEnabled(true);
ui->ellipsisButton->setEnabled(true);
}
void Intro::startThread()
{
thread = new QThread(this);
FreespaceChecker *executor = new FreespaceChecker(this);
executor->moveToThread(thread);
connect(executor, SIGNAL(reply(int,QString,quint64)), this, SLOT(setStatus(int,QString,quint64)));
connect(this, SIGNAL(requestCheck()), executor, SLOT(check()));
/* make sure executor object is deleted in its own thread */
connect(this, SIGNAL(stopThread()), executor, SLOT(deleteLater()));
connect(this, SIGNAL(stopThread()), thread, SLOT(quit()));
thread->start();
}
void Intro::checkPath(const QString &dataDir)
{
mutex.lock();
pathToCheck = dataDir;
if(!signalled)
{
signalled = true;
Q_EMIT requestCheck();
}
mutex.unlock();
}
QString Intro::getPathToCheck()
{
QString retval;
mutex.lock();
retval = pathToCheck;
signalled = false; /* new request can be queued now */
mutex.unlock();
return retval;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2016, The Bifrost Authors. All rights reserved.
* Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of The Bifrost 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 ``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 <bifrost/quantize.h>
#include "utils.hpp"
#include <limits>
#include <cmath>
using std::max;
using std::min;
// Note: maxval is always the max representable integer value
// E.g., 8-bit => 127 (signed), 255 (unsigned)
// minval is either -maxval (signed) or 0 (unsigned)
// The min representable value of signed integers is not used
// E.g., int8_t => -128 is not used
template<typename T>
inline T maxval(T x=T()) { return std::numeric_limits<T>::max(); }
template<typename T>
inline typename std::enable_if<!std::is_signed<T>::value,T>::type
minval(T x=T()) { return T(0); }
template<typename T>
inline typename std::enable_if< std::is_signed<T>::value,T>::type
minval(T x=T()) { return -maxval<T>(); }
template<typename I, typename F>
inline F clip(F x) {
return min(max(x,F(minval<I>())),F(maxval<I>()));
}
template<typename IType, typename SType, typename OType>
inline void quantize(IType ival, SType scale, OType& oval) {
//std::cout << (int)minval<OType>() << ", " << (int)maxval<OType>() << std::endl;
//std::cout << scale << std::endl;
//std::cout << ival
// << " --> " << ival*scale
// << " --> " << clip<OType>(ival*scale)
// << " --> " << rint(clip<OType>(ival*scale))
// << " --> " << (int)OType(rint(clip<OType>(ival*scale)))
// << std::endl;
oval = OType(rint(clip<OType>(ival*scale)));
}
template<typename IType, typename SType, typename OType>
struct QuantizeFunctor {
SType scale;
bool byteswap_in;
bool byteswap_out;
QuantizeFunctor(SType scale_, bool byteswap_in_, bool byteswap_out_)
: scale(scale_),
byteswap_in(byteswap_in_),
byteswap_out(byteswap_out_) {}
void operator()(IType ival, OType& oval) const {
if( byteswap_in ) {
byteswap(ival, &ival);
}
quantize(ival, scale, oval);
if( byteswap_out ) {
byteswap(oval, &oval);
}
}
};
template<typename T, typename U, typename Func, typename Size>
void foreach_simple_cpu(T const* in,
U* out,
Size nelement,
Func func) {
for( Size i=0; i<nelement; ++i ) {
func(in[i], out[i]);
//std::cout << std::hex << (int)in[i] << " --> " << (int)out[i] << std::endl;
}
}
BFstatus bfQuantize(BFarray const* in,
BFarray const* out,
double scale) {
BF_ASSERT(in, BF_STATUS_INVALID_POINTER);
BF_ASSERT(out, BF_STATUS_INVALID_POINTER);
BF_ASSERT(!out->immutable, BF_STATUS_INVALID_POINTER);
BF_ASSERT(shapes_equal(in, out), BF_STATUS_INVALID_SHAPE);
BF_ASSERT(BF_DTYPE_IS_COMPLEX( in->dtype) ==
BF_DTYPE_IS_COMPLEX(out->dtype),
BF_STATUS_INVALID_DTYPE);
BF_ASSERT(BF_DTYPE_IS_COMPLEX(in->dtype) || !in->conjugated,
BF_STATUS_INVALID_DTYPE);
BF_ASSERT(BF_DTYPE_IS_COMPLEX(out->dtype) || !in->conjugated,
BF_STATUS_INVALID_DTYPE);
// TODO: Support conjugation
BF_ASSERT((!BF_DTYPE_IS_COMPLEX(in->dtype)) ||
(in->conjugated == out->conjugated),
BF_STATUS_UNSUPPORTED);
// TODO: Support padded arrays
BF_ASSERT(is_contiguous(in), BF_STATUS_UNSUPPORTED_STRIDE);
BF_ASSERT(is_contiguous(out), BF_STATUS_UNSUPPORTED_STRIDE);
// TODO: Support CUDA space
BF_ASSERT(space_accessible_from(in->space, BF_SPACE_SYSTEM),
BF_STATUS_UNSUPPORTED_SPACE);
BF_ASSERT(space_accessible_from(out->space, BF_SPACE_SYSTEM),
BF_STATUS_UNSUPPORTED_SPACE);
size_t nelement = num_contiguous_elements(in);
bool byteswap_in = ( in->big_endian != is_big_endian());
bool byteswap_out = (out->big_endian != is_big_endian());
#define CALL_FOREACH_SIMPLE_CPU_QUANTIZE(itype,stype,otype) \
foreach_simple_cpu((itype*)in->data, \
(otype*)out->data, \
nelement, \
QuantizeFunctor<itype,stype,otype> \
(scale,byteswap_in,byteswap_out))
// **TODO: Need CF32 --> CI* separately to support conjugation
if( in->dtype == BF_DTYPE_F32 || in->dtype == BF_DTYPE_CF32 ) {
// TODO: Support T-->T with endian conversion (like quantize but with identity func instead)
switch( out->dtype ) {
case BF_DTYPE_CI8: nelement *= 2;
case BF_DTYPE_I8: {
CALL_FOREACH_SIMPLE_CPU_QUANTIZE(float,float,int8_t); break;
}
case BF_DTYPE_CI16: nelement *= 2;
case BF_DTYPE_I16: {
CALL_FOREACH_SIMPLE_CPU_QUANTIZE(float,float,int16_t); break;
}
case BF_DTYPE_CI32: nelement *= 2;
case BF_DTYPE_I32: {
CALL_FOREACH_SIMPLE_CPU_QUANTIZE(float,double,int32_t); break;
}
case BF_DTYPE_U8: {
CALL_FOREACH_SIMPLE_CPU_QUANTIZE(float,float,uint8_t); break;
}
case BF_DTYPE_U16: {
CALL_FOREACH_SIMPLE_CPU_QUANTIZE(float,float,uint16_t); break;
}
case BF_DTYPE_U32: {
CALL_FOREACH_SIMPLE_CPU_QUANTIZE(float,double,uint32_t); break;
}
default: BF_FAIL("Supported bfQuantize output dtype", BF_STATUS_UNSUPPORTED_DTYPE);
}
} else {
BF_FAIL("Supported bfQuantize input dtype", BF_STATUS_UNSUPPORTED_DTYPE);
}
#undef CALL_FOREACH_SIMPLE_CPU_QUANTIZE
return BF_STATUS_SUCCESS;
}
<commit_msg>Added support for quantizing to CI4/I4.<commit_after>/*
* Copyright (c) 2016, The Bifrost Authors. All rights reserved.
* Copyright (c) 2016, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of The Bifrost 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 ``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 <bifrost/quantize.h>
#include "utils.hpp"
#include <limits>
#include <cmath>
#include <iostream>
using std::max;
using std::min;
// Note: maxval is always the max representable integer value
// E.g., 8-bit => 127 (signed), 255 (unsigned)
// minval is either -maxval (signed) or 0 (unsigned)
// The min representable value of signed integers is not used
// E.g., int8_t => -128 is not used
template<typename T>
inline T maxval(T x=T()) { return std::numeric_limits<T>::max(); }
template<typename T>
inline typename std::enable_if<!std::is_signed<T>::value,T>::type
minval(T x=T()) { return T(0); }
template<typename T>
inline typename std::enable_if< std::is_signed<T>::value,T>::type
minval(T x=T()) { return -maxval<T>(); }
template<typename I, typename F>
inline F clip(F x) {
return min(max(x,F(minval<I>())),F(maxval<I>()));
}
inline int8_t clip_4bit(int8_t x) {
return min(max(x,int8_t(-7)),int8_t(7));
}
template<typename IType, typename SType, typename OType>
inline void quantize(IType ival, SType scale, OType& oval) {
//std::cout << (int)minval<OType>() << ", " << (int)maxval<OType>() << std::endl;
//std::cout << scale << std::endl;
//std::cout << ival
// << " --> " << ival*scale
// << " --> " << clip<OType>(ival*scale)
// << " --> " << rint(clip<OType>(ival*scale))
// << " --> " << (int)OType(rint(clip<OType>(ival*scale)))
// << std::endl;
oval = OType(rint(clip<OType>(ival*scale)));
}
template<typename IType, typename SType, typename OType>
struct QuantizeFunctor {
SType scale;
bool byteswap_in;
bool byteswap_out;
QuantizeFunctor(SType scale_, bool byteswap_in_, bool byteswap_out_)
: scale(scale_),
byteswap_in(byteswap_in_),
byteswap_out(byteswap_out_) {}
void operator()(IType ival, OType& oval) const {
if( byteswap_in ) {
byteswap(ival, &ival);
}
quantize(ival, scale, oval);
if( byteswap_out ) {
byteswap(oval, &oval);
}
}
};
template<typename T, typename U, typename Func, typename Size>
void foreach_simple_cpu(T const* in,
U* out,
Size nelement,
Func func) {
for( Size i=0; i<nelement; ++i ) {
func(in[i], out[i]);
//std::cout << std::hex << (int)in[i] << " --> " << (int)out[i] << std::endl;
}
}
template<typename T, typename Func, typename Size>
void foreach_simple_cpu_4bit(T const* in,
int8_t* out,
Size nelement,
Func func) {
T tempR;
T tempI;
int8_t tempO;
for( Size i=0; i<nelement; i+=2 ) {
tempR = in[i+0];
tempI = in[i+1];
if(func.byteswap_in) {
byteswap(tempR, &tempR);
byteswap(tempI, &tempI);
}
//std::cout << tempR << ", " << tempI << " --> " << rint(clip_4bit(tempR)) << ", " << rint(clip_4bit(tempI)) << '\n';
tempO = (((int8_t(rint(clip_4bit(tempR)))*16) ) & 0xF0) | \
(((int8_t(rint(clip_4bit(tempI)))*16) >> 4) & 0x0F);
if(func.byteswap_out) {
byteswap(tempO, &tempO);
}
out[i/2] = tempO;
}
}
BFstatus bfQuantize(BFarray const* in,
BFarray const* out,
double scale) {
BF_ASSERT(in, BF_STATUS_INVALID_POINTER);
BF_ASSERT(out, BF_STATUS_INVALID_POINTER);
BF_ASSERT(!out->immutable, BF_STATUS_INVALID_POINTER);
BF_ASSERT(shapes_equal(in, out), BF_STATUS_INVALID_SHAPE);
BF_ASSERT(BF_DTYPE_IS_COMPLEX( in->dtype) ==
BF_DTYPE_IS_COMPLEX(out->dtype),
BF_STATUS_INVALID_DTYPE);
BF_ASSERT(BF_DTYPE_IS_COMPLEX(in->dtype) || !in->conjugated,
BF_STATUS_INVALID_DTYPE);
BF_ASSERT(BF_DTYPE_IS_COMPLEX(out->dtype) || !in->conjugated,
BF_STATUS_INVALID_DTYPE);
// TODO: Support conjugation
BF_ASSERT((!BF_DTYPE_IS_COMPLEX(in->dtype)) ||
(in->conjugated == out->conjugated),
BF_STATUS_UNSUPPORTED);
// TODO: Support padded arrays
BF_ASSERT(is_contiguous(in), BF_STATUS_UNSUPPORTED_STRIDE);
BF_ASSERT(is_contiguous(out), BF_STATUS_UNSUPPORTED_STRIDE);
// TODO: Support CUDA space
BF_ASSERT(space_accessible_from(in->space, BF_SPACE_SYSTEM),
BF_STATUS_UNSUPPORTED_SPACE);
BF_ASSERT(space_accessible_from(out->space, BF_SPACE_SYSTEM),
BF_STATUS_UNSUPPORTED_SPACE);
size_t nelement = num_contiguous_elements(in);
bool byteswap_in = ( in->big_endian != is_big_endian());
bool byteswap_out = (out->big_endian != is_big_endian());
if( out->dtype == BF_DTYPE_I4 ){
BF_ASSERT(nelement%2 == 0, BF_STATUS_UNSUPPORTED_STRIDE);
}
#define CALL_FOREACH_SIMPLE_CPU_QUANTIZE(itype,stype,otype) \
foreach_simple_cpu((itype*)in->data, \
(otype*)out->data, \
nelement, \
QuantizeFunctor<itype,stype,otype> \
(scale,byteswap_in,byteswap_out))
// **TODO: Need CF32 --> CI* separately to support conjugation
if( in->dtype == BF_DTYPE_F32 || in->dtype == BF_DTYPE_CF32 ) {
// TODO: Support T-->T with endian conversion (like quantize but with identity func instead)
switch( out->dtype ) {
case BF_DTYPE_CI4: nelement *= 2;
case BF_DTYPE_I4: {
foreach_simple_cpu_4bit((float*)in->data, \
(int8_t*)out->data, \
nelement, \
QuantizeFunctor<float,float,uint8_t> \
(scale,byteswap_in,byteswap_out)); break;
}
case BF_DTYPE_CI8: nelement *= 2;
case BF_DTYPE_I8: {
CALL_FOREACH_SIMPLE_CPU_QUANTIZE(float,float,int8_t); break;
}
case BF_DTYPE_CI16: nelement *= 2;
case BF_DTYPE_I16: {
CALL_FOREACH_SIMPLE_CPU_QUANTIZE(float,float,int16_t); break;
}
case BF_DTYPE_CI32: nelement *= 2;
case BF_DTYPE_I32: {
CALL_FOREACH_SIMPLE_CPU_QUANTIZE(float,double,int32_t); break;
}
case BF_DTYPE_U8: {
CALL_FOREACH_SIMPLE_CPU_QUANTIZE(float,float,uint8_t); break;
}
case BF_DTYPE_U16: {
CALL_FOREACH_SIMPLE_CPU_QUANTIZE(float,float,uint16_t); break;
}
case BF_DTYPE_U32: {
CALL_FOREACH_SIMPLE_CPU_QUANTIZE(float,double,uint32_t); break;
}
default: BF_FAIL("Supported bfQuantize output dtype", BF_STATUS_UNSUPPORTED_DTYPE);
}
} else {
BF_FAIL("Supported bfQuantize input dtype", BF_STATUS_UNSUPPORTED_DTYPE);
}
#undef CALL_FOREACH_SIMPLE_CPU_QUANTIZE
return BF_STATUS_SUCCESS;
}
<|endoftext|> |
<commit_before>#include "random_lcg.h"
#include <cmath>
// Starting seed
int64_t seed = 1;
// LCG parameters
const uint64_t prn_mult = 2806196910506780709LL; // multiplication factor, g
const uint64_t prn_add = 1; // additive factor, c
const uint64_t prn_mod = 0x8000000000000000; // 2^63
const uint64_t prn_mask = 0x7fffffffffffffff; // 2^63 - 1
const uint64_t prn_stride = 152917LL; // stride between particles
const double prn_norm = pow(2, -63); // 2^-63
// Module constants
const int N_STREAMS = 5;
const int STREAM_TRACKING = 0;
const int STREAM_TALLIES = 1;
const int STREAM_SOURCE = 2;
const int STREAM_URR_PTABLE = 3;
const int STREAM_VOLUME = 4;
// Current PRNG state
uint64_t prn_seed[N_STREAMS]; // current seed
int stream; // current RNG stream
#pragma omp threadprivate(prn_seed, stream)
//==============================================================================
// PRN
//==============================================================================
extern "C" double
prn()
{
// This algorithm uses bit-masking to find the next integer(8) value to be
// used to calculate the random number.
prn_seed[stream] = (prn_mult*prn_seed[stream] + prn_add) & prn_mask;
// Once the integer is calculated, we just need to divide by 2**m,
// represented here as multiplying by a pre-calculated factor
return prn_seed[stream] * prn_norm;
}
//==============================================================================
// FUTURE_PRN
//==============================================================================
extern "C" double
future_prn(uint64_t n)
{
return future_seed(n, prn_seed[stream]) * prn_norm;
}
//==============================================================================
// SET_PARTICLE_SEED
//==============================================================================
extern "C" void
set_particle_seed(uint64_t id)
{
for (int i = 0; i < N_STREAMS; i++) {
prn_seed[i] = future_seed(id * prn_stride, seed + i);
}
}
//==============================================================================
// ADVANCE_PRN_SEED
//==============================================================================
extern "C" void
advance_prn_seed(uint64_t n)
{
prn_seed[stream] = future_seed(n, prn_seed[stream]);
}
//==============================================================================
// FUTURE_SEED
//==============================================================================
extern "C" uint64_t
future_seed(uint64_t n, uint64_t seed)
{
// In cases where we want to skip backwards, we add the period of the random
// number generator until the number of PRNs to skip is positive since
// skipping ahead that much is the same as skipping backwards by the original
// amount.
uint64_t nskip = n;
while (nskip > prn_mod) nskip += prn_mod;
// Make sure nskip is less than 2^M.
nskip &= prn_mask;
// The algorithm here to determine the parameters used to skip ahead is
// described in F. Brown, "Random Number Generation with Arbitrary Stride,"
// Trans. Am. Nucl. Soc. (Nov. 1994). This algorithm is able to skip ahead in
// O(log2(N)) operations instead of O(N). Basically, it computes parameters G
// and C which can then be used to find x_N = G*x_0 + C mod 2^M.
// Initialize constants
uint64_t g = prn_mult;
uint64_t c = prn_add;
uint64_t g_new = 1;
uint64_t c_new = 0;
while (nskip > 0) {
// Check if the least significant bit is 1.
if (nskip & 1) {
g_new = (g_new * g) & prn_mask;
c_new = (c_new * g + c) & prn_mask;
}
c = ((g + 1) * c) & prn_mask;
g = (g * g) & prn_mask;
// Move bits right, dropping least significant bit.
nskip >>= 1;
}
// With G and C, we can now find the new seed.
return (g_new * seed + c_new) & prn_mask;
}
//==============================================================================
// PRN_SET_STREAM
//==============================================================================
extern "C" void
prn_set_stream(int i)
{
stream = i - 1;
}
//==============================================================================
// API FUNCTIONS
//==============================================================================
extern "C" int
openmc_set_seed(uint64_t new_seed)
{
seed = new_seed;
#pragma omp parallel
for (int i = 0; i < N_STREAMS; i++) {
prn_seed[i] = seed + i;
}
stream = STREAM_TRACKING;
#pragma end omp parallel
return 0;
}
<commit_msg>Simplify RNG<commit_after>#include "random_lcg.h"
#include <cmath>
// Starting seed
int64_t seed = 1;
// LCG parameters
const uint64_t prn_mult = 2806196910506780709LL; // multiplication factor, g
const uint64_t prn_add = 1; // additive factor, c
const uint64_t prn_mod = 0x8000000000000000; // 2^63
const uint64_t prn_mask = 0x7fffffffffffffff; // 2^63 - 1
const uint64_t prn_stride = 152917LL; // stride between particles
const double prn_norm = pow(2, -63); // 2^-63
// Module constants
const int N_STREAMS = 5;
const int STREAM_TRACKING = 0;
const int STREAM_TALLIES = 1;
const int STREAM_SOURCE = 2;
const int STREAM_URR_PTABLE = 3;
const int STREAM_VOLUME = 4;
// Current PRNG state
uint64_t prn_seed[N_STREAMS]; // current seed
int stream; // current RNG stream
#pragma omp threadprivate(prn_seed, stream)
//==============================================================================
// PRN
//==============================================================================
extern "C" double
prn()
{
// This algorithm uses bit-masking to find the next integer(8) value to be
// used to calculate the random number.
prn_seed[stream] = (prn_mult*prn_seed[stream] + prn_add) & prn_mask;
// Once the integer is calculated, we just need to divide by 2**m,
// represented here as multiplying by a pre-calculated factor
return prn_seed[stream] * prn_norm;
}
//==============================================================================
// FUTURE_PRN
//==============================================================================
extern "C" double
future_prn(uint64_t n)
{
return future_seed(n, prn_seed[stream]) * prn_norm;
}
//==============================================================================
// SET_PARTICLE_SEED
//==============================================================================
extern "C" void
set_particle_seed(uint64_t id)
{
for (int i = 0; i < N_STREAMS; i++) {
prn_seed[i] = future_seed(id * prn_stride, seed + i);
}
}
//==============================================================================
// ADVANCE_PRN_SEED
//==============================================================================
extern "C" void
advance_prn_seed(uint64_t n)
{
prn_seed[stream] = future_seed(n, prn_seed[stream]);
}
//==============================================================================
// FUTURE_SEED
//==============================================================================
extern "C" uint64_t
future_seed(uint64_t n, uint64_t seed)
{
// Make sure nskip is less than 2^M.
n &= prn_mask;
// The algorithm here to determine the parameters used to skip ahead is
// described in F. Brown, "Random Number Generation with Arbitrary Stride,"
// Trans. Am. Nucl. Soc. (Nov. 1994). This algorithm is able to skip ahead in
// O(log2(N)) operations instead of O(N). Basically, it computes parameters G
// and C which can then be used to find x_N = G*x_0 + C mod 2^M.
// Initialize constants
uint64_t g = prn_mult;
uint64_t c = prn_add;
uint64_t g_new = 1;
uint64_t c_new = 0;
while (n > 0) {
// Check if the least significant bit is 1.
if (n & 1) {
g_new = g_new * g;
c_new = c_new * g + c;
}
c = (g + 1) * c;
g = g * g;
// Move bits right, dropping least significant bit.
n >>= 1;
}
// With G and C, we can now find the new seed.
return (g_new * seed + c_new) & prn_mask;
}
//==============================================================================
// PRN_SET_STREAM
//==============================================================================
extern "C" void
prn_set_stream(int i)
{
stream = i - 1;
}
//==============================================================================
// API FUNCTIONS
//==============================================================================
extern "C" int
openmc_set_seed(uint64_t new_seed)
{
seed = new_seed;
#pragma omp parallel
for (int i = 0; i < N_STREAMS; i++) {
prn_seed[i] = seed + i;
}
stream = STREAM_TRACKING;
#pragma end omp parallel
return 0;
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.