text
stringlengths
54
60.6k
<commit_before>#include "General.h" #include <shellapi.h> #include "../3RVX/LanguageTranslator.h" #include "../3RVX/Logger.h" #include "../3RVX/Settings.h" #include "../3RVX/SkinInfo.h" #include "resource.h" const wchar_t General::REGKEY_NAME[] = L"3RVX"; const wchar_t General::REGKEY_RUN[] = L"Software\\Microsoft\\Windows\\CurrentVersion\\Run"; void General::Initialize() { INIT_CONTROL(GRP_BEHAVIOR, GroupBox, _behaviorGroup); INIT_CONTROL(CHK_STARTUP, Checkbox, _startup); INIT_CONTROL(CHK_NOTIFY, Checkbox, _notifyIcon); INIT_CONTROL(CHK_SOUNDS, Checkbox, _sounds); INIT_CONTROL(GRP_SKIN, GroupBox, _skinGroup); INIT_CONTROL(CMB_SKIN, ComboBox, _skin); _skin.OnSelectionChange = [this]() { LoadSkinInfo(_skin.Selection()); return true; }; INIT_CONTROL(LBL_AUTHOR, Label, _author); INIT_CONTROL(BTN_WEBSITE, Button, _website); _website.OnClick = [this]() { if (_url != L"") { ShellExecute(NULL, L"open", _url.c_str(), NULL, NULL, SW_SHOWNORMAL); } return true; }; INIT_CONTROL(GRP_LANGUAGE, GroupBox, _languageGroup); INIT_CONTROL(CMB_LANG, ComboBox, _language); _language.OnSelectionChange = [this]() { // Handle language selection change return true; }; } void General::LoadSettings() { Settings *settings = Settings::Instance(); LanguageTranslator *lt = settings->Translator(); _startup.Checked(RunOnStartup()); _notifyIcon.Checked(settings->NotifyIconEnabled()); _sounds.Checked(settings->SoundEffectsEnabled()); /* Determine which skins are available */ std::list<std::wstring> skins = FindSkins(Settings::SkinDir().c_str()); for (std::wstring skin : skins) { _skin.AddItem(skin); } /* Update the combo box with the current skin */ std::wstring current = settings->CurrentSkin(); int idx = _skin.Select(current); if (idx == CB_ERR) { _skin.Select(Settings::DefaultSkin); } LoadSkinInfo(current); /* Populate the language box */ std::list<std::wstring> languages = FindLanguages( settings->LanguagesDir().c_str()); for (std::wstring language : languages) { _language.AddItem(language); } std::wstring currentLang = settings->LanguageName(); _language.Select(currentLang); } void General::SaveSettings() { if (_hWnd == NULL) { return; } CLOG(L"Saving: General"); Settings *settings = Settings::Instance(); RunOnStartup(_startup.Checked()); settings->NotifyIconEnabled(_notifyIcon.Checked()); settings->SoundEffectsEnabled(_sounds.Checked()); settings->CurrentSkin(_skin.Selection()); } bool General::RunOnStartup() { long res; HKEY key = NULL; bool run = false; res = RegOpenKeyEx(HKEY_CURRENT_USER, REGKEY_RUN, NULL, KEY_READ, &key); if (res == ERROR_SUCCESS) { res = RegQueryValueEx(key, REGKEY_NAME, NULL, NULL, NULL, NULL); run = (res == ERROR_SUCCESS); RegCloseKey(key); } return run; } bool General::RunOnStartup(bool enable) { long res; HKEY key = NULL; bool ok = false; std::wstring path = Settings::AppDir() + L"\\3RVX.exe"; res = RegOpenKeyEx(HKEY_CURRENT_USER, REGKEY_RUN, NULL, KEY_ALL_ACCESS, &key); if (res == ERROR_SUCCESS) { if (enable) { res = RegSetValueEx(key, REGKEY_NAME, NULL, REG_SZ, (LPBYTE) path.c_str(), (path.size() + 1) * sizeof(TCHAR)); ok = (res == ERROR_SUCCESS); } else { res = RegDeleteValue(key, REGKEY_NAME); ok = (res == ERROR_SUCCESS); } RegCloseKey(key); } return ok; } std::list<std::wstring> General::FindSkins(std::wstring dir) { std::list<std::wstring> skins; WIN32_FIND_DATA ffd; HANDLE hFind; CLOG(L"Finding skins in: %s", dir.c_str()); dir += L"\\*"; hFind = FindFirstFile(dir.c_str(), &ffd); if (hFind == INVALID_HANDLE_VALUE) { CLOG(L"FindFirstFile() failed"); return skins; } do { std::wstring fName(ffd.cFileName); if (fName.at(0) == L'.') { continue; } QCLOG(L"%s", fName.c_str()); skins.push_back(fName); } while (FindNextFile(hFind, &ffd)); FindClose(hFind); return skins; } void General::LoadSkinInfo(std::wstring skinName) { std::wstring skinXML = Settings::Instance()->SkinXML(skinName); SkinInfo s(skinXML); std::wstring authorText(L"Author: {1}"); std::wstring transAuthor = Settings::Instance()->Translator() ->TranslateAndReplace(authorText, s.Author()); _author.Text(transAuthor); std::wstring url = s.URL(); if (url == L"") { _website.Disable(); } else { _url = s.URL(); _website.Enable(); } } std::list<std::wstring> General::FindLanguages(std::wstring dir) { std::list<std::wstring> languages; WIN32_FIND_DATA ffd; HANDLE hFind; CLOG(L"Finding language translations in: %s", dir.c_str()); dir += L"\\*.xml"; hFind = FindFirstFile(dir.c_str(), &ffd); if (hFind == INVALID_HANDLE_VALUE) { CLOG(L"FindFirstFile() failed"); return languages; } do { std::wstring fName(ffd.cFileName); if (fName.at(0) == L'.') { continue; } if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { continue; } QCLOG(L"%s", fName.c_str()); languages.push_back(fName); } while (FindNextFile(hFind, &ffd)); FindClose(hFind); return languages; }<commit_msg>Update for new translation params<commit_after>#include "General.h" #include <shellapi.h> #include "../3RVX/LanguageTranslator.h" #include "../3RVX/Logger.h" #include "../3RVX/Settings.h" #include "../3RVX/SkinInfo.h" #include "resource.h" const wchar_t General::REGKEY_NAME[] = L"3RVX"; const wchar_t General::REGKEY_RUN[] = L"Software\\Microsoft\\Windows\\CurrentVersion\\Run"; void General::Initialize() { INIT_CONTROL(GRP_BEHAVIOR, GroupBox, _behaviorGroup); INIT_CONTROL(CHK_STARTUP, Checkbox, _startup); INIT_CONTROL(CHK_NOTIFY, Checkbox, _notifyIcon); INIT_CONTROL(CHK_SOUNDS, Checkbox, _sounds); INIT_CONTROL(GRP_SKIN, GroupBox, _skinGroup); INIT_CONTROL(CMB_SKIN, ComboBox, _skin); _skin.OnSelectionChange = [this]() { LoadSkinInfo(_skin.Selection()); return true; }; INIT_CONTROL(LBL_AUTHOR, Label, _author); INIT_CONTROL(BTN_WEBSITE, Button, _website); _website.OnClick = [this]() { if (_url != L"") { ShellExecute(NULL, L"open", _url.c_str(), NULL, NULL, SW_SHOWNORMAL); } return true; }; INIT_CONTROL(GRP_LANGUAGE, GroupBox, _languageGroup); INIT_CONTROL(CMB_LANG, ComboBox, _language); _language.OnSelectionChange = [this]() { // Handle language selection change return true; }; } void General::LoadSettings() { Settings *settings = Settings::Instance(); LanguageTranslator *lt = settings->Translator(); _startup.Checked(RunOnStartup()); _notifyIcon.Checked(settings->NotifyIconEnabled()); _sounds.Checked(settings->SoundEffectsEnabled()); /* Determine which skins are available */ std::list<std::wstring> skins = FindSkins(Settings::SkinDir().c_str()); for (std::wstring skin : skins) { _skin.AddItem(skin); } /* Update the combo box with the current skin */ std::wstring current = settings->CurrentSkin(); int idx = _skin.Select(current); if (idx == CB_ERR) { _skin.Select(Settings::DefaultSkin); } LoadSkinInfo(current); /* Populate the language box */ std::list<std::wstring> languages = FindLanguages( settings->LanguagesDir().c_str()); for (std::wstring language : languages) { _language.AddItem(language); } std::wstring currentLang = settings->LanguageName(); _language.Select(currentLang); } void General::SaveSettings() { if (_hWnd == NULL) { return; } CLOG(L"Saving: General"); Settings *settings = Settings::Instance(); RunOnStartup(_startup.Checked()); settings->NotifyIconEnabled(_notifyIcon.Checked()); settings->SoundEffectsEnabled(_sounds.Checked()); settings->CurrentSkin(_skin.Selection()); } bool General::RunOnStartup() { long res; HKEY key = NULL; bool run = false; res = RegOpenKeyEx(HKEY_CURRENT_USER, REGKEY_RUN, NULL, KEY_READ, &key); if (res == ERROR_SUCCESS) { res = RegQueryValueEx(key, REGKEY_NAME, NULL, NULL, NULL, NULL); run = (res == ERROR_SUCCESS); RegCloseKey(key); } return run; } bool General::RunOnStartup(bool enable) { long res; HKEY key = NULL; bool ok = false; std::wstring path = Settings::AppDir() + L"\\3RVX.exe"; res = RegOpenKeyEx(HKEY_CURRENT_USER, REGKEY_RUN, NULL, KEY_ALL_ACCESS, &key); if (res == ERROR_SUCCESS) { if (enable) { res = RegSetValueEx(key, REGKEY_NAME, NULL, REG_SZ, (LPBYTE) path.c_str(), (path.size() + 1) * sizeof(TCHAR)); ok = (res == ERROR_SUCCESS); } else { res = RegDeleteValue(key, REGKEY_NAME); ok = (res == ERROR_SUCCESS); } RegCloseKey(key); } return ok; } std::list<std::wstring> General::FindSkins(std::wstring dir) { std::list<std::wstring> skins; WIN32_FIND_DATA ffd; HANDLE hFind; CLOG(L"Finding skins in: %s", dir.c_str()); dir += L"\\*"; hFind = FindFirstFile(dir.c_str(), &ffd); if (hFind == INVALID_HANDLE_VALUE) { CLOG(L"FindFirstFile() failed"); return skins; } do { std::wstring fName(ffd.cFileName); if (fName.at(0) == L'.') { continue; } QCLOG(L"%s", fName.c_str()); skins.push_back(fName); } while (FindNextFile(hFind, &ffd)); FindClose(hFind); return skins; } void General::LoadSkinInfo(std::wstring skinName) { std::wstring skinXML = Settings::Instance()->SkinXML(skinName); SkinInfo s(skinXML); std::wstring transAuthor = Settings::Instance()->Translator()->TranslateAndReplace( L"Author: {1}", s.Author()); _author.Text(transAuthor); std::wstring url = s.URL(); if (url == L"") { _website.Disable(); } else { _url = s.URL(); _website.Enable(); } } std::list<std::wstring> General::FindLanguages(std::wstring dir) { std::list<std::wstring> languages; WIN32_FIND_DATA ffd; HANDLE hFind; CLOG(L"Finding language translations in: %s", dir.c_str()); dir += L"\\*.xml"; hFind = FindFirstFile(dir.c_str(), &ffd); if (hFind == INVALID_HANDLE_VALUE) { CLOG(L"FindFirstFile() failed"); return languages; } do { std::wstring fName(ffd.cFileName); if (fName.at(0) == L'.') { continue; } if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { continue; } QCLOG(L"%s", fName.c_str()); languages.push_back(fName); } while (FindNextFile(hFind, &ffd)); FindClose(hFind); return languages; }<|endoftext|>
<commit_before> #include "registerAddr.hpp" #include "Gpu.hpp" #include "OpenGLWindow.hpp" #include "Memory.hpp" Gpu Gpu::_gpuInstance = Gpu(); Gpu &Gpu::Instance() { return Gpu::_gpuInstance; } Gpu::Gpu() : _clock(0), _mode(OAM_READ), _window(nullptr), _memory(Memory::Instance()) { _activeTile = 0; // TODO: CHECK how to get it } Gpu::~Gpu() { } #define TILES0_ADDR 0x8000 // Go to 0x8FFF / 0->255 #define TILES1_ADDR 0x8800 // Go to 0x97FF / -128->127 #define TILE_W 8 // bits #define TILE_PIXEL_SIZE 2 // bits on Gb #define BYTE_SIZE 8 // byte size 0000 0000 ;) #define PIXEL_BY_BYTE (BYTE_SIZE / TILE_PIXEL_SIZE) #define TILE_LINE_SIZE (TILE_W / PIXEL_BY_BYTE) #define MAP_W 32 #define MAP0_ADDR 0x9800 // 32*32 tile #define MAP1_ADDR 0x9C00 // 32*32 tile #include <iostream> unsigned int Gpu::scanPixel(uint8_t line, unsigned int x) { unsigned int pixel = 0xFFFFFF; unsigned int tileMapAddr = _activeTile ? MAP1_ADDR : MAP0_ADDR; unsigned int tileSetAddr = _activeTile ? TILES1_ADDR : TILES0_ADDR; unsigned int tileId = _memory.read_byte(tileMapAddr + (line / MAP_W) + x); // TODO: use scroll X / Y here unsigned int tileAddr = tileSetAddr + tileId; unsigned int sy = line % TILE_W; unsigned int sx = x % TILE_W; uint8_t sdata = _memory.read_byte(tileAddr + (sy * TILE_LINE_SIZE) + (x / PIXEL_BY_BYTE)); unsigned int colorId = (sdata >> (2 * (x % PIXEL_BY_BYTE))) & 0x3; switch (colorId) { case 0: pixel = 0x00FFFFFF; break ; case 1: pixel = 0x00C0C0C0; break ; case 2: pixel = 0x00606060; break ; case 3: pixel = 0x00000000; break; default: pixel = 0x00FF0000; // TODO: impossible case ! break ; } return pixel; } void Gpu::scanActLine() { uint16_t addrLine; unsigned int pixel; uint8_t line = _memory.read_byte(REGISTER_LY); for (int x = 0 ; x < WIN_WIDTH ; ++x) { addrLine = line * WIN_WIDTH + x; pixel = scanPixel(line, x); _window->drawPixel(addrLine, pixel); } } void Gpu::step() { uint8_t line = _memory.read_byte(REGISTER_LY); switch (_mode) { case OAM_READ: if (_clock >= 80) { _clock = 0; _mode = VRAM_READ; } break ; case VRAM_READ: if (_clock >= 172) { _clock = 0; _mode = HBLANK; scanActLine(); } break ; case HBLANK: if (_clock >= 204) { _clock = 0; _memory.write_byte(REGISTER_LY, ++line); if (line == 143) { _mode = VBLANK; _window->renderLater(); } else { _mode = OAM_READ; } } break ; case VBLANK: if (_clock >= 456) { _clock = 0; _memory.write_byte(REGISTER_LY, ++line); if (line > 153) { _mode = OAM_READ; _memory.write_byte(REGISTER_LY, 0); } } break ; default: break ; } } void Gpu::init() { _mode = OAM_READ; _clock = 0; _window = OpenGLWindow::Instance(); _window->initialize(); } void Gpu::accClock(unsigned int clock) { _clock += clock; } <commit_msg>better thing is happening<commit_after> #include "registerAddr.hpp" #include "Gpu.hpp" #include "OpenGLWindow.hpp" #include "Memory.hpp" Gpu Gpu::_gpuInstance = Gpu(); Gpu &Gpu::Instance() { return Gpu::_gpuInstance; } Gpu::Gpu() : _clock(0), _mode(OAM_READ), _window(nullptr), _memory(Memory::Instance()) { _activeTile = 0; // TODO: CHECK how to get it } Gpu::~Gpu() { } #define TILES0_ADDR 0x8000 // Go to 0x8FFF / 0->255 #define TILES1_ADDR 0x8800 // Go to 0x97FF / -128->127 #define TILE_W 8 // bits #define TILE_PIXEL_SIZE 2 // bits on Gb #define BYTE_SIZE 8 // byte size 0000 0000 ;) #define PIXEL_BY_BYTE (BYTE_SIZE / TILE_PIXEL_SIZE) #define TILE_LINE_SIZE (TILE_W / PIXEL_BY_BYTE) #define MAP_W 32 #define MAP0_ADDR 0x9800 // 32*32 tile #define MAP1_ADDR 0x9C00 // 32*32 tile #include <iostream> unsigned int Gpu::scanPixel(uint8_t line, unsigned int x) { unsigned int pixel = 0xFFFFFF; unsigned int tileMapAddr = _activeTile ? MAP1_ADDR : MAP0_ADDR; unsigned int tileSetAddr = _activeTile ? TILES1_ADDR : TILES0_ADDR; unsigned int tileId = _memory.read_byte(tileMapAddr + (line / MAP_W) + x); // TODO: use scroll X / Y here unsigned int tileAddr = tileSetAddr + tileId; unsigned int sy = line % TILE_W; unsigned int sx = x % TILE_W; uint8_t sdata = _memory.read_byte(tileAddr + (sy * TILE_LINE_SIZE) + (sx / PIXEL_BY_BYTE)); unsigned int colorId = (sdata >> (2 * (x % PIXEL_BY_BYTE))) & 0x3; switch (colorId) { case 0: pixel = 0x00FFFFFF; break ; case 1: pixel = 0x00C0C0C0; break ; case 2: pixel = 0x00606060; break ; case 3: pixel = 0x00000000; break; default: pixel = 0x00FF0000; // TODO: impossible case ! break ; } return pixel; } void Gpu::scanActLine() { uint16_t addrLine; unsigned int pixel; uint8_t line = _memory.read_byte(REGISTER_LY); for (int x = 0 ; x < WIN_WIDTH ; ++x) { addrLine = line * WIN_WIDTH + x; pixel = scanPixel(line, x); _window->drawPixel(addrLine, pixel); } } void Gpu::step() { uint8_t line = _memory.read_byte(REGISTER_LY); switch (_mode) { case OAM_READ: if (_clock >= 80) { _clock = 0; _mode = VRAM_READ; } break ; case VRAM_READ: if (_clock >= 172) { _clock = 0; _mode = HBLANK; scanActLine(); } break ; case HBLANK: if (_clock >= 204) { _clock = 0; _memory.write_byte(REGISTER_LY, ++line); if (line == 143) { _mode = VBLANK; _window->renderLater(); } else { _mode = OAM_READ; } } break ; case VBLANK: if (_clock >= 456) { _clock = 0; _memory.write_byte(REGISTER_LY, ++line); if (line > 153) { _mode = OAM_READ; _memory.write_byte(REGISTER_LY, 0); } } break ; default: break ; } } void Gpu::init() { _mode = OAM_READ; _clock = 0; _window = OpenGLWindow::Instance(); _window->initialize(); } void Gpu::accClock(unsigned int clock) { _clock += clock; } <|endoftext|>
<commit_before>#include <fstream> #include <iostream> #include "Rom.hpp" Rom Rom::_instance = Rom(); Rom::Rom(void) { this->_eram = NULL; this->_rom = NULL; } Rom::~Rom(void) { if (this->_rom != NULL) delete[] this->_rom; if (this->_eram != NULL) delete[] this->_eram; } Rom &Rom::Instance(void) { return Rom::_instance; } void Rom::init(void) { uint8_t flag_cgb; flag_cgb = (this->_rom[0x0143] & 0xFF); if (flag_cgb == 0x00 || flag_cgb == 0x80) this->_info.type = GB; else if (flag_cgb == 0xC0) this->_info.type = GBC; this->_info.cartridge = this->_rom[0x0147]; this->_info.romSize = this->_rom[0x0148]; this->_info.eramSize = this->_rom[0x0149]; this->_nbanks = getBankRom(this->_info.romSize); this->_nrambanks = getBankEram(this->_info.eramSize); if (this->_nrambanks > 0) this->_eram = new uint8_t [this->_nrambanks * 8192]; this->_bank = 0; this->_u_bank = 0; this->_rambank = 0; this->_write_protect = 0; } int Rom::load(const char *file) { std::ifstream romFile; uint32_t rom_size; if (this->_rom != NULL) delete[] this->_rom; if (this->_eram != NULL) delete[] this->_eram; this->_rom = NULL; this->_eram = NULL; romFile.open(file, std::ios::in | std::ios::ate | std::ios::binary); if (romFile.is_open()) { rom_size = romFile.tellg(); this->_rom = new char [rom_size]; romFile.seekg(0, std::ios::beg); romFile.read(this->_rom, rom_size); romFile.close(); this->init(); return 0; } return 1; } uint8_t Rom::read(uint16_t addr) { if (this->_rom == NULL) return -1; if (addr < 0x4000) return this->_rom[addr]; else if (addr < 0x8000) return this->_rom[addr + ((this->_bank + (this->_u_bank * 0x20)) * 0x4000)]; else if (addr >= 0xA000 && addr < 0xC000) return this->_eram[addr + (this->_rambank * 0x2000)]; return 0; } void Rom::write(uint16_t addr, uint8_t val) { switch (addr & 0xF000){ case 0x0000: case 0x1000: // RAMCS if (val == 0x00 || val == 0x0A) this->_write_protect = val; break; case 0x2000: case 0x3000: // Rom bank code if (this->_tbank) { // eram if (val == 0x01 || val <= 0x1f) this->_rambank = val; } else { // rom if (val == 0x01 || val <= 0x1f) this->_bank = val; } break; case 0x4000: case 0x5000: // Upper Rom bank code if (val <= 0x03) { if (this->_tbank == 0) this->_u_bank = val; } break; case 0x6000: case 0x7000: // Rom/Ram change if (val == 0x00 || val == 0x01) this->_tbank = val; break; case 0xA000: case 0xB000: // ERAM if (this->_write_protect == 0x0A) this->_eram[addr + (this->_rambank * 0x2000)] = val; break; } } void Rom::reset(void) { } irom Rom::getType(void) { return this->_info; } uint8_t Rom::getBankRom(uint8_t octet) { if (octet == 1) return 4; else if (octet == 2) return 8; else if (octet == 3) return 16; else if (octet == 4) return 32; else if (octet == 5) return 64; else if (octet == 6) return 128; else if (octet == 52) return 72; else if (octet == 53) return 80; else if (octet == 54) return 96; return 2; } uint8_t Rom::getBankEram(uint8_t octet) { if (octet == 1 || octet == 2) return 1; else if (octet == 3) return 4; else if (octet == 4) return 16; return 0; } bool Rom::isLoaded(void) { if (this->_rom == NULL) return false; return true; } <commit_msg>Write Rom protect if val == 0<commit_after>#include <fstream> #include <iostream> #include "Rom.hpp" Rom Rom::_instance = Rom(); Rom::Rom(void) { this->_eram = NULL; this->_rom = NULL; } Rom::~Rom(void) { if (this->_rom != NULL) delete[] this->_rom; if (this->_eram != NULL) delete[] this->_eram; } Rom &Rom::Instance(void) { return Rom::_instance; } void Rom::init(void) { uint8_t flag_cgb; flag_cgb = (this->_rom[0x0143] & 0xFF); if (flag_cgb == 0x00 || flag_cgb == 0x80) this->_info.type = GB; else if (flag_cgb == 0xC0) this->_info.type = GBC; this->_info.cartridge = this->_rom[0x0147]; this->_info.romSize = this->_rom[0x0148]; this->_info.eramSize = this->_rom[0x0149]; this->_nbanks = getBankRom(this->_info.romSize); this->_nrambanks = getBankEram(this->_info.eramSize); if (this->_nrambanks > 0) this->_eram = new uint8_t [this->_nrambanks * 8192]; this->_bank = 0; this->_u_bank = 0; this->_rambank = 0; this->_write_protect = 0; } int Rom::load(const char *file) { std::ifstream romFile; uint32_t rom_size; if (this->_rom != NULL) delete[] this->_rom; if (this->_eram != NULL) delete[] this->_eram; this->_rom = NULL; this->_eram = NULL; romFile.open(file, std::ios::in | std::ios::ate | std::ios::binary); if (romFile.is_open()) { rom_size = romFile.tellg(); this->_rom = new char [rom_size]; romFile.seekg(0, std::ios::beg); romFile.read(this->_rom, rom_size); romFile.close(); this->init(); return 0; } return 1; } uint8_t Rom::read(uint16_t addr) { if (this->_rom == NULL) return -1; if (addr < 0x4000) return this->_rom[addr]; else if (addr < 0x8000) return this->_rom[addr + ((this->_bank + (this->_u_bank * 0x20)) * 0x4000)]; else if (addr >= 0xA000 && addr < 0xC000) return this->_eram[addr + (this->_rambank * 0x2000)]; return 0; } void Rom::write(uint16_t addr, uint8_t val) { switch (addr & 0xF000){ case 0x0000: case 0x1000: // RAMCS if (val == 0x00 || val == 0x0A) this->_write_protect = val; break; case 0x2000: case 0x3000: // Rom bank code if (this->_tbank) { // eram if (val >= 0x01 && val <= 0x1f) this->_rambank = val; } else { // rom if (val >= 0x01 && val <= 0x1f) this->_bank = val; } break; case 0x4000: case 0x5000: // Upper Rom bank code if (val <= 0x03) { if (this->_tbank == 0) this->_u_bank = val; } break; case 0x6000: case 0x7000: // Rom/Ram change if (val == 0x00 || val == 0x01) this->_tbank = val; break; case 0xA000: case 0xB000: // ERAM if (this->_write_protect == 0x0A) this->_eram[addr + (this->_rambank * 0x2000)] = val; break; } } void Rom::reset(void) { } irom Rom::getType(void) { return this->_info; } uint8_t Rom::getBankRom(uint8_t octet) { if (octet == 1) return 4; else if (octet == 2) return 8; else if (octet == 3) return 16; else if (octet == 4) return 32; else if (octet == 5) return 64; else if (octet == 6) return 128; else if (octet == 52) return 72; else if (octet == 53) return 80; else if (octet == 54) return 96; return 2; } uint8_t Rom::getBankEram(uint8_t octet) { if (octet == 1 || octet == 2) return 1; else if (octet == 3) return 4; else if (octet == 4) return 16; return 0; } bool Rom::isLoaded(void) { if (this->_rom == NULL) return false; return true; } <|endoftext|>
<commit_before><commit_msg>new DnD implementations - now DnD tables/queries in the explorer pane / moved some implementations to dsbrowserDnD.cxx<commit_after><|endoftext|>
<commit_before>#include "PowerUI.h" #include "ui_PowerUI.h" PowerUI::PowerUI(QWidget *parent) : QWidget(parent), ui(new Ui::PowerUI) { ui->setupUi(this); } PowerUI::~PowerUI() { delete ui; } QPushButton& PowerUI::connectButton() { return *ui->connectButton; } QLabel& PowerUI::setConnectionStatus() { return *ui->connectionStatus; } QLineEdit& PowerUI::getSerialPortName() { return *ui->serialPortName; } QLineEdit& PowerUI::getBaudRate() { return *ui->baudrate; } QTextEdit& PowerUI::setDebugLog() { return *ui->connectionOutput; } QLabel& PowerUI::setSetSpeed() { return *ui->setSpeed; } QLabel& PowerUI::setSetCurrent() { return *ui->setCurrent; } QLabel& PowerUI::setActualSpeed() { return *ui->actualSpeed; } QLabel& PowerUI::setBusVoltage() { return *ui->busVoltage; } // QLabel& PowerUI::setArrayCurrentIn() // { // return *ui->arrayCurrentIn; // } // QLabel& PowerUI::setArrayCurrentOut() // { // return *ui->arrayCurrentOut; // } // QLabel& PowerUI::setNetCurrent() // { // return *ui->netCurrent; // } QLabel& PowerUI::setBatteryCMU1Temp() { return *ui->batteryCMU1Temp; } QLabel& PowerUI::setBatteryCMU1Cell1Voltage() { return *ui->batteryCMU1Cell1Voltage; } QLabel& PowerUI::setBatteryCMU1Cell2Voltage() { return *ui->batteryCMU1Cell2Voltage; } QLabel& PowerUI::setBatteryCMU1Cell3Voltage() { return *ui->batteryCMU1Cell3Voltage; } QLabel& PowerUI::setBatteryCMU1Cell4Voltage() { return *ui->batteryCMU1Cell4Voltage; } QLabel& PowerUI::setBatteryCMU1Cell5Voltage() { return *ui->batteryCMU1Cell5Voltage; } QLabel& PowerUI::setBatteryCMU1Cell6Voltage() { return *ui->batteryCMU1Cell6Voltage; } QLabel& PowerUI::setBatteryCMU1Cell7Voltage() { return *ui->batteryCMU1Cell7Voltage; } QLabel& PowerUI::setBatteryCMU1Cell8Voltage() { return *ui->batteryCMU1Cell8Voltage; } QLabel& PowerUI::setBatteryCMU2Temp() { return *ui->batteryCMU2Temp; } QLabel& PowerUI::setBatteryCMU2Cell1Voltage() { return *ui->batteryCMU2Cell1Voltage; } QLabel& PowerUI::setBatteryCMU2Cell2Voltage() { return *ui->batteryCMU2Cell2Voltage; } QLabel& PowerUI::setBatteryCMU2Cell3Voltage() { return *ui->batteryCMU2Cell3Voltage; } QLabel& PowerUI::setBatteryCMU2Cell4Voltage() { return *ui->batteryCMU2Cell4Voltage; } QLabel& PowerUI::setBatteryCMU2Cell5Voltage() { return *ui->batteryCMU2Cell5Voltage; } QLabel& PowerUI::setBatteryCMU2Cell6Voltage() { return *ui->batteryCMU2Cell6Voltage; } QLabel& PowerUI::setBatteryCMU2Cell7Voltage() { return *ui->batteryCMU2Cell7Voltage; } QLabel& PowerUI::setBatteryCMU2Cell8Voltage() { return *ui->batteryCMU2Cell8Voltage; } QLabel& PowerUI::setBatteryCMU3Temp() { return *ui->batteryCMU3Temp; } QLabel& PowerUI::setBatteryCMU3Cell1Voltage() { return *ui->batteryCMU3Cell1Voltage; } QLabel& PowerUI::setBatteryCMU3Cell2Voltage() { return *ui->batteryCMU3Cell2Voltage; } QLabel& PowerUI::setBatteryCMU3Cell3Voltage() { return *ui->batteryCMU3Cell3Voltage; } QLabel& PowerUI::setBatteryCMU3Cell4Voltage() { return *ui->batteryCMU3Cell4Voltage; } QLabel& PowerUI::setBatteryCMU3Cell5Voltage() { return *ui->batteryCMU3Cell5Voltage; } QLabel& PowerUI::setBatteryCMU3Cell6Voltage() { return *ui->batteryCMU3Cell6Voltage; } QLabel& PowerUI::setBatteryCMU3Cell7Voltage() { return *ui->batteryCMU3Cell7Voltage; } QLabel& PowerUI::setBatteryCMU3Cell8Voltage() { return *ui->batteryCMU3Cell8Voltage; } QLabel& PowerUI::setBatteryCMU4Temp() { return *ui->batteryCMU4Temp; } QLabel& PowerUI::setBatteryCMU4Cell1Voltage() { return *ui->batteryCMU4Cell1Voltage; } QLabel& PowerUI::setBatteryCMU4Cell2Voltage() { return *ui->batteryCMU4Cell2Voltage; } QLabel& PowerUI::setBatteryCMU4Cell3Voltage() { return *ui->batteryCMU4Cell3Voltage; } QLabel& PowerUI::setBatteryCMU4Cell4Voltage() { return *ui->batteryCMU4Cell4Voltage; } QLabel& PowerUI::setBatteryCMU4Cell5Voltage() { return *ui->batteryCMU4Cell5Voltage; } QLabel& PowerUI::setBatteryCMU4Cell6Voltage() { return *ui->batteryCMU4Cell6Voltage; } QLabel& PowerUI::setBatteryCMU4Cell7Voltage() { return *ui->batteryCMU4Cell7Voltage; } QLabel& PowerUI::setBatteryCMU4Cell8Voltage() { return *ui->batteryCMU4Cell8Voltage; } <commit_msg>program opens p in fullscreen now<commit_after>#include "PowerUI.h" #include "ui_PowerUI.h" PowerUI::PowerUI(QWidget *parent) : QWidget(parent), ui(new Ui::PowerUI) { ui->setupUi(this); showFullScreen(); } PowerUI::~PowerUI() { delete ui; } QPushButton& PowerUI::connectButton() { return *ui->connectButton; } QLabel& PowerUI::setConnectionStatus() { return *ui->connectionStatus; } QLineEdit& PowerUI::getSerialPortName() { return *ui->serialPortName; } QLineEdit& PowerUI::getBaudRate() { return *ui->baudrate; } QTextEdit& PowerUI::setDebugLog() { return *ui->connectionOutput; } QLabel& PowerUI::setSetSpeed() { return *ui->setSpeed; } QLabel& PowerUI::setSetCurrent() { return *ui->setCurrent; } QLabel& PowerUI::setActualSpeed() { return *ui->actualSpeed; } QLabel& PowerUI::setBusVoltage() { return *ui->busVoltage; } // QLabel& PowerUI::setArrayCurrentIn() // { // return *ui->arrayCurrentIn; // } // QLabel& PowerUI::setArrayCurrentOut() // { // return *ui->arrayCurrentOut; // } // QLabel& PowerUI::setNetCurrent() // { // return *ui->netCurrent; // } QLabel& PowerUI::setBatteryCMU1Temp() { return *ui->batteryCMU1Temp; } QLabel& PowerUI::setBatteryCMU1Cell1Voltage() { return *ui->batteryCMU1Cell1Voltage; } QLabel& PowerUI::setBatteryCMU1Cell2Voltage() { return *ui->batteryCMU1Cell2Voltage; } QLabel& PowerUI::setBatteryCMU1Cell3Voltage() { return *ui->batteryCMU1Cell3Voltage; } QLabel& PowerUI::setBatteryCMU1Cell4Voltage() { return *ui->batteryCMU1Cell4Voltage; } QLabel& PowerUI::setBatteryCMU1Cell5Voltage() { return *ui->batteryCMU1Cell5Voltage; } QLabel& PowerUI::setBatteryCMU1Cell6Voltage() { return *ui->batteryCMU1Cell6Voltage; } QLabel& PowerUI::setBatteryCMU1Cell7Voltage() { return *ui->batteryCMU1Cell7Voltage; } QLabel& PowerUI::setBatteryCMU1Cell8Voltage() { return *ui->batteryCMU1Cell8Voltage; } QLabel& PowerUI::setBatteryCMU2Temp() { return *ui->batteryCMU2Temp; } QLabel& PowerUI::setBatteryCMU2Cell1Voltage() { return *ui->batteryCMU2Cell1Voltage; } QLabel& PowerUI::setBatteryCMU2Cell2Voltage() { return *ui->batteryCMU2Cell2Voltage; } QLabel& PowerUI::setBatteryCMU2Cell3Voltage() { return *ui->batteryCMU2Cell3Voltage; } QLabel& PowerUI::setBatteryCMU2Cell4Voltage() { return *ui->batteryCMU2Cell4Voltage; } QLabel& PowerUI::setBatteryCMU2Cell5Voltage() { return *ui->batteryCMU2Cell5Voltage; } QLabel& PowerUI::setBatteryCMU2Cell6Voltage() { return *ui->batteryCMU2Cell6Voltage; } QLabel& PowerUI::setBatteryCMU2Cell7Voltage() { return *ui->batteryCMU2Cell7Voltage; } QLabel& PowerUI::setBatteryCMU2Cell8Voltage() { return *ui->batteryCMU2Cell8Voltage; } QLabel& PowerUI::setBatteryCMU3Temp() { return *ui->batteryCMU3Temp; } QLabel& PowerUI::setBatteryCMU3Cell1Voltage() { return *ui->batteryCMU3Cell1Voltage; } QLabel& PowerUI::setBatteryCMU3Cell2Voltage() { return *ui->batteryCMU3Cell2Voltage; } QLabel& PowerUI::setBatteryCMU3Cell3Voltage() { return *ui->batteryCMU3Cell3Voltage; } QLabel& PowerUI::setBatteryCMU3Cell4Voltage() { return *ui->batteryCMU3Cell4Voltage; } QLabel& PowerUI::setBatteryCMU3Cell5Voltage() { return *ui->batteryCMU3Cell5Voltage; } QLabel& PowerUI::setBatteryCMU3Cell6Voltage() { return *ui->batteryCMU3Cell6Voltage; } QLabel& PowerUI::setBatteryCMU3Cell7Voltage() { return *ui->batteryCMU3Cell7Voltage; } QLabel& PowerUI::setBatteryCMU3Cell8Voltage() { return *ui->batteryCMU3Cell8Voltage; } QLabel& PowerUI::setBatteryCMU4Temp() { return *ui->batteryCMU4Temp; } QLabel& PowerUI::setBatteryCMU4Cell1Voltage() { return *ui->batteryCMU4Cell1Voltage; } QLabel& PowerUI::setBatteryCMU4Cell2Voltage() { return *ui->batteryCMU4Cell2Voltage; } QLabel& PowerUI::setBatteryCMU4Cell3Voltage() { return *ui->batteryCMU4Cell3Voltage; } QLabel& PowerUI::setBatteryCMU4Cell4Voltage() { return *ui->batteryCMU4Cell4Voltage; } QLabel& PowerUI::setBatteryCMU4Cell5Voltage() { return *ui->batteryCMU4Cell5Voltage; } QLabel& PowerUI::setBatteryCMU4Cell6Voltage() { return *ui->batteryCMU4Cell6Voltage; } QLabel& PowerUI::setBatteryCMU4Cell7Voltage() { return *ui->batteryCMU4Cell7Voltage; } QLabel& PowerUI::setBatteryCMU4Cell8Voltage() { return *ui->batteryCMU4Cell8Voltage; } <|endoftext|>
<commit_before>#include "Character.h" Character::Character(): m_spriteCharater(new sf::Sprite()),m_textureCharacter(new sf::Texture()) { m_textureCharacter->loadFromFile("Build/Ressources/sprites/spooky/sprite.png"); m_spriteCharater->setTexture(*m_textureCharacter); m_spriteCharater->setTextureRect(sf::IntRect(0, 0, 32, 32)); m_spriteCharater->setPosition(sf::Vector2f(1, 1.)); } Character::~Character() { } void Character::setAngle(int alpha) { m_angleShot += alpha; } sf::Vector2f Character::getDirection() { return sf::Vector2f(cos(m_angleShot), sin(m_angleShot)); } void Character::jump() { return; } void Character::draw(sf::RenderWindow *window) const { if (m_currentAnimation == StateAnimation::Left){ m_spriteCharater->setTextureRect(sf::IntRect(0, 0, 32, 32)); //m_currentAnimation = StateAnimation::Midle; } window->draw(*m_spriteCharater); }<commit_msg>Jump Implementation<commit_after>#include "Character.h" Character::Character(): m_spriteCharater(new sf::Sprite()), m_textureCharacter(new sf::Texture()) { m_textureCharacter->loadFromFile("Build/Ressources/sprites/spooky/sprite.png"); m_spriteCharater->setTexture(*m_textureCharacter); m_spriteCharater->setTextureRect(sf::IntRect(0, 0, 32, 32)); m_position = sf::Vector2f(1, 1.); m_spriteCharater->setPosition(sf::Vector2f(1, 1.)); } Character::~Character() {} void Character::setAngle(int alpha) { m_angleShot += alpha; } sf::Vector2f Character::getDirection() { return sf::Vector2f(cos(m_angleShot), sin(m_angleShot)); } void Character::jump() { //TO DO while(!obstacles) { this->m_position = m_spriteCharater->getPosition() + this->getDirection()*m_velocity; m_spriteCharater->move(this->getDirection()*m_velocity); } return; } void Character::draw(sf::RenderWindow *window) const { if (m_currentAnimation == StateAnimation::Left){ m_spriteCharater->setTextureRect(sf::IntRect(0, 0, 32, 32)); //m_currentAnimation = StateAnimation::Midle; } window->draw(*m_spriteCharater); }<|endoftext|>
<commit_before>#include "Character.h" Character::Character(): m_spriteCharater(new sf::Sprite()), m_textureCharacter(new sf::Texture()) { m_textureCharacter->loadFromFile("Build/Ressources/sprites/spooky/sprite.png"); m_spriteCharater->setTexture(*m_textureCharacter); m_spriteCharater->setTextureRect(sf::IntRect(0, 0, 32, 32)); m_position = sf::Vector2f(1, 1.); m_spriteCharater->setPosition(sf::Vector2f(1, 1.)); } Character::~Character() {} void Character::setAngle(int alpha) { m_angleShot += alpha; } sf::Vector2f Character::getDirection() { return sf::Vector2f(cos(m_angleShot), sin(m_angleShot)); } void Character::jump() { //TO DO //while(!obstacles) { this->m_position = m_spriteCharater->getPosition() + this->getDirection()*m_velocity; m_spriteCharater->move(this->getDirection()*m_velocity); } return; } void Character::draw(sf::RenderWindow *window) const { window->draw(*m_spriteCharater); } void Character::update(){ if (m_currentAnimation == StateAnimation::Left){ m_spriteCharater->setTextureRect(sf::IntRect(32, 0, 32, 32)); m_currentAnimation } else if (m_currentAnimation == StateAnimation::Midle){ m_spriteCharater->setTextureRect(sf::IntRect(32, 32, 32, 32)); } else if (m_currentAnimation == StateAnimation::Right){ m_spriteCharater->setTextureRect(sf::IntRect(32, 64, 32, 32)); } } <commit_msg> sprite character drawed<commit_after>#include "Character.h" Character::Character(): m_spriteCharater(new sf::Sprite()), m_textureCharacter(new sf::Texture()) { m_textureCharacter->loadFromFile("Build/Ressources/sprites/spooky/sprite.png"); m_spriteCharater->setTexture(*m_textureCharacter); m_spriteCharater->setTextureRect(sf::IntRect(0, 0, 32, 32)); m_position = sf::Vector2f(1, 1.); m_spriteCharater->setPosition(sf::Vector2f(1, 1.)); } Character::~Character() {} void Character::setAngle(int alpha) { m_angleShot += alpha; } sf::Vector2f Character::getDirection() { return sf::Vector2f(cos(m_angleShot), sin(m_angleShot)); } void Character::jump() { //TO DO //while(!obstacles) { this->m_position = m_spriteCharater->getPosition() + this->getDirection()*m_velocity; m_spriteCharater->move(this->getDirection()*m_velocity); } return; } void Character::draw(sf::RenderWindow *window) const { window->draw(*m_spriteCharater); } void Character::update(){ if (m_currentAnimation == StateAnimation::Left){ m_spriteCharater->setTextureRect(sf::IntRect(32, 0, 32, 32)); m_currentAnimation = StateAnimation::Midle; } else if (m_currentAnimation == StateAnimation::Midle){ m_spriteCharater->setTextureRect(sf::IntRect(32, 32, 32, 32)); m_currentAnimation = StateAnimation::Midle; } else if (m_currentAnimation == StateAnimation::Right){ m_spriteCharater->setTextureRect(sf::IntRect(32, 64, 32, 32)); m_currentAnimation = StateAnimation::Left; } } <|endoftext|>
<commit_before>/* * qiaffine.cpp * * Copyright (c) 2015 Tobias Wood. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * */ #include <iostream> #include "itkMetaDataObject.h" #include "QI/Util.h" #include "QI/IO.h" #include "QI/Args.h" /* * Declare args here so things like verbose can be global */ args::ArgumentParser parser("Converts images between formats\nhttp://github.com/spinicist/QUIT"); args::Positional<std::string> input_file(parser, "INPUT", "Input file, must include extension."); args::Positional<std::string> output_arg(parser, "OUTPUT", "Output file, must include extension. If the rename flag is used, only the extension is used."); args::HelpFlag help(parser, "HELP", "Show this help menu", {'h', "help"}); args::Flag verbose(parser, "VERBOSE", "Print more information", {'v', "verbose"}); args::ValueFlagList<std::string> rename_args(parser, "RENAME", "Rename using specified header fields (can be multiple).", {'r', "rename"}); args::ValueFlag<std::string> prefix(parser, "PREFIX", "Add a prefix to output filename.", {'p', "prefix"}); /* * Templated functions to avoid macros */ template<typename TImage> void Convert(const std::string &input, const std::string &output) { auto image = QI::ReadImage<TImage>(input); QI::WriteImage<TImage>(image, output); } template<int D, typename T> void ConvertPixel(const std::string &input, const std::string &output, const itk::ImageIOBase::IOPixelType &pix) { switch (pix) { case itk::ImageIOBase::SCALAR: Convert<itk::Image<T, D>>(input, output); break; case itk::ImageIOBase::COMPLEX: Convert<itk::Image<std::complex<T>, D>>(input, output); break; default: QI_FAIL("Unsupported pixel type in image " << input); } } template<int D> void ConvertComponent(const std::string &input, const std::string &output, const itk::ImageIOBase::IOComponentType &component, const itk::ImageIOBase::IOPixelType &pix) { switch (component) { case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE: QI_FAIL("Unknown component type in image " << input); case itk::ImageIOBase::UCHAR: ConvertPixel<D, unsigned char>(input, output, pix); break; case itk::ImageIOBase::CHAR: ConvertPixel<D, char>(input, output, pix); break; case itk::ImageIOBase::USHORT: ConvertPixel<D, unsigned short>(input, output, pix); break; case itk::ImageIOBase::SHORT: ConvertPixel<D, short>(input, output, pix); break; case itk::ImageIOBase::UINT: ConvertPixel<D, unsigned int>(input, output, pix); break; case itk::ImageIOBase::INT: ConvertPixel<D, int>(input, output, pix); break; case itk::ImageIOBase::ULONG: ConvertPixel<D, unsigned long>(input, output, pix); break; case itk::ImageIOBase::LONG: ConvertPixel<D, long>(input, output, pix); break; case itk::ImageIOBase::FLOAT: ConvertPixel<D, float>(input, output, pix); break; case itk::ImageIOBase::DOUBLE: ConvertPixel<D, double>(input, output, pix); break; } } void ConvertDims(const std::string &input, const std::string &output, const int D, const itk::ImageIOBase::IOComponentType &component, const itk::ImageIOBase::IOPixelType &pix) { switch (D) { case 2: ConvertComponent<2>(input, output, component, pix); break; case 3: ConvertComponent<3>(input, output, component, pix); break; case 4: ConvertComponent<4>(input, output, component, pix); break; default: QI_FAIL("Unsupported dimension: " << D); } } /* * Helper function to work out the name of the output file */ std::string RenameFromHeader(const itk::MetaDataDictionary &header) { bool append_delim = false; std::string output; for (const auto rename_field: args::get(rename_args)) { std::vector<std::string> string_array_value; std::string string_value; double double_value; if (!header.HasKey(rename_field)) { if (verbose) std::cout << "Rename field '" << rename_field << "' not found in header. Ignoring" << std::endl; continue; } if (append_delim) { output.append("_"); } else { append_delim = true; } if (ExposeMetaData(header, rename_field, string_array_value)) { output.append(string_array_value[0]); } else if (ExposeMetaData(header, rename_field, string_value)) { output.append(string_value); } else if (ExposeMetaData(header, rename_field, double_value)) { std::ostringstream formatted; formatted << double_value; output.append(formatted.str()); } else { QI_EXCEPTION("Could not determine type of rename header field:" << rename_field); } } return output; } int main(int argc, char **argv) { QI::ParseArgs(parser, argc, argv); const std::string input = QI::CheckPos(input_file); itk::ImageIOBase::Pointer header = itk::ImageIOFactory::CreateImageIO(input.c_str(), itk::ImageIOFactory::ReadMode); if (!header) QI_FAIL("Could not open: " << input); header->SetFileName(input); header->ReadImageInformation(); /* Deal with renaming */ std::string output_path = prefix.Get(); if (rename_args) { output_path += RenameFromHeader(header->GetMetaDataDictionary()); output_path += QI::GetExt(QI::CheckPos(output_arg)); } else { output_path += QI::CheckPos(output_arg); } std::cout << output_path << std::endl; auto dims = header->GetNumberOfDimensions(); auto pixel_type = header->GetPixelType(); auto component_type = header->GetComponentType(); ConvertDims(input, output_path, dims, component_type, pixel_type); return EXIT_SUCCESS; } <commit_msg>ENH: Sanitise filename strings<commit_after>/* * qiaffine.cpp * * Copyright (c) 2015 Tobias Wood. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * */ #include <iostream> #include <algorithm> #include "itkMetaDataObject.h" #include "QI/Util.h" #include "QI/IO.h" #include "QI/Args.h" /* * Declare args here so things like verbose can be global */ args::ArgumentParser parser("Converts images between formats\nhttp://github.com/spinicist/QUIT"); args::Positional<std::string> input_file(parser, "INPUT", "Input file, must include extension."); args::Positional<std::string> output_arg(parser, "OUTPUT", "Output file, must include extension. If the rename flag is used, only the extension is used."); args::HelpFlag help(parser, "HELP", "Show this help menu", {'h', "help"}); args::Flag verbose(parser, "VERBOSE", "Print more information", {'v', "verbose"}); args::ValueFlagList<std::string> rename_args(parser, "RENAME", "Rename using specified header fields (can be multiple).", {'r', "rename"}); args::ValueFlag<std::string> prefix(parser, "PREFIX", "Add a prefix to output filename.", {'p', "prefix"}); /* * Templated functions to avoid macros */ template<typename TImage> void Convert(const std::string &input, const std::string &output) { auto image = QI::ReadImage<TImage>(input); QI::WriteImage<TImage>(image, output); } template<int D, typename T> void ConvertPixel(const std::string &input, const std::string &output, const itk::ImageIOBase::IOPixelType &pix) { switch (pix) { case itk::ImageIOBase::SCALAR: Convert<itk::Image<T, D>>(input, output); break; case itk::ImageIOBase::COMPLEX: Convert<itk::Image<std::complex<T>, D>>(input, output); break; default: QI_FAIL("Unsupported pixel type in image " << input); } } template<int D> void ConvertComponent(const std::string &input, const std::string &output, const itk::ImageIOBase::IOComponentType &component, const itk::ImageIOBase::IOPixelType &pix) { switch (component) { case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE: QI_FAIL("Unknown component type in image " << input); case itk::ImageIOBase::UCHAR: ConvertPixel<D, unsigned char>(input, output, pix); break; case itk::ImageIOBase::CHAR: ConvertPixel<D, char>(input, output, pix); break; case itk::ImageIOBase::USHORT: ConvertPixel<D, unsigned short>(input, output, pix); break; case itk::ImageIOBase::SHORT: ConvertPixel<D, short>(input, output, pix); break; case itk::ImageIOBase::UINT: ConvertPixel<D, unsigned int>(input, output, pix); break; case itk::ImageIOBase::INT: ConvertPixel<D, int>(input, output, pix); break; case itk::ImageIOBase::ULONG: ConvertPixel<D, unsigned long>(input, output, pix); break; case itk::ImageIOBase::LONG: ConvertPixel<D, long>(input, output, pix); break; case itk::ImageIOBase::FLOAT: ConvertPixel<D, float>(input, output, pix); break; case itk::ImageIOBase::DOUBLE: ConvertPixel<D, double>(input, output, pix); break; } } void ConvertDims(const std::string &input, const std::string &output, const int D, const itk::ImageIOBase::IOComponentType &component, const itk::ImageIOBase::IOPixelType &pix) { switch (D) { case 2: ConvertComponent<2>(input, output, component, pix); break; case 3: ConvertComponent<3>(input, output, component, pix); break; case 4: ConvertComponent<4>(input, output, component, pix); break; default: QI_FAIL("Unsupported dimension: " << D); } } /* * Helper function to sanitise meta-data to be suitable for a filename */ std::string SanitiseString(const std::string &s) { const std::string forbidden = " \\/:?\"<>|*+-="; std::string out(s.size(), ' '); std::transform(s.begin(), s.end(), out.begin(), [&forbidden](char c) { return forbidden.find(c) != std::string::npos ? '_' : c; }); return out; } /* * Helper function to work out the name of the output file */ std::string RenameFromHeader(const itk::MetaDataDictionary &header) { bool append_delim = false; std::string output; for (const auto rename_field: args::get(rename_args)) { std::vector<std::string> string_array_value; std::string string_value; double double_value; if (!header.HasKey(rename_field)) { if (verbose) std::cout << "Rename field '" << rename_field << "' not found in header. Ignoring" << std::endl; continue; } if (append_delim) { output.append("_"); } else { append_delim = true; } if (ExposeMetaData(header, rename_field, string_array_value)) { output.append(SanitiseString(string_array_value[0])); } else if (ExposeMetaData(header, rename_field, string_value)) { output.append(SanitiseString(string_value)); } else if (ExposeMetaData(header, rename_field, double_value)) { std::ostringstream formatted; formatted << double_value; output.append(formatted.str()); } else { QI_EXCEPTION("Could not determine type of rename header field:" << rename_field); } } return output; } int main(int argc, char **argv) { QI::ParseArgs(parser, argc, argv); const std::string input = QI::CheckPos(input_file); itk::ImageIOBase::Pointer header = itk::ImageIOFactory::CreateImageIO(input.c_str(), itk::ImageIOFactory::ReadMode); if (!header) QI_FAIL("Could not open: " << input); header->SetFileName(input); header->ReadImageInformation(); /* Deal with renaming */ std::string output_path = prefix.Get(); if (rename_args) { output_path += RenameFromHeader(header->GetMetaDataDictionary()); output_path += QI::GetExt(QI::CheckPos(output_arg)); } else { output_path += QI::CheckPos(output_arg); } std::cout << output_path << std::endl; auto dims = header->GetNumberOfDimensions(); auto pixel_type = header->GetPixelType(); auto component_type = header->GetComponentType(); ConvertDims(input, output_path, dims, component_type, pixel_type); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* * qikfilter.cpp * * Copyright (c) 2015 Tobias Wood. * * 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 <memory> #include <getopt.h> #include <iostream> #include <sstream> #include "Eigen/Dense" #include "itkImageSource.h" #include "itkConstNeighborhoodIterator.h" #include "itkImageRegionIteratorWithIndex.h" #include "itkMultiplyImageFilter.h" #include "itkDivideImageFilter.h" #include "itkComplexToComplexFFTImageFilter.h" #include "itkInverseFFTImageFilter.h" #include "itkFFTShiftImageFilter.h" #include "itkComplexToModulusImageFilter.h" #include "itkFFTPadImageFilter.h" #include "itkConstantPadImageFilter.h" #include "itkExtractImageFilter.h" #include "itkPasteImageFilter.h" #include "itkCastImageFilter.h" #include "QI/Types.h" #include "QI/Util.h" #include "QI/Kernels.h" #include "QI/IO.h" using namespace std; using namespace Eigen; namespace itk { template<typename TImage> class KernelSource : public ImageSource<TImage> { public: typedef TImage ImageType; typedef KernelSource Self; typedef ImageSource<ImageType> Superclass; typedef SmartPointer<Self> Pointer; typedef typename ImageType::RegionType RegionType; typedef typename ImageType::IndexType IndexType; typedef typename ImageType::SizeType SizeType; typedef typename ImageType::SpacingType SpacingType; typedef typename ImageType::DirectionType DirectionType; typedef typename ImageType::PointType PointType; protected: KernelSource(){} ~KernelSource(){} RegionType m_Region; SpacingType m_Spacing; DirectionType m_Direction; PointType m_Origin; std::vector<std::shared_ptr<QI::FilterKernel>> m_kernels; public: itkNewMacro(Self); itkTypeMacro(Self, ImageSource); void SetKernels(const std::vector<std::shared_ptr<QI::FilterKernel>> &k) { m_kernels = k; } itkSetMacro(Region, RegionType); itkSetMacro(Spacing, SpacingType); itkSetMacro(Direction, DirectionType); itkSetMacro(Origin, PointType); protected: virtual void GenerateOutputInformation() ITK_OVERRIDE { auto output = this->GetOutput(0); output->SetLargestPossibleRegion(m_Region); output->SetSpacing(m_Spacing); output->SetDirection(m_Direction); output->SetOrigin(m_Origin); } virtual void ThreadedGenerateData(const RegionType &region, ThreadIdType threadId) ITK_OVERRIDE { const auto startIndex = m_Region.GetIndex(); const Eigen::Array3d sz{m_Region.GetSize()[0], m_Region.GetSize()[1], m_Region.GetSize()[2]}; const Eigen::Array3d hsz = sz / 2; const Eigen::Array3d sp{m_Spacing[0], m_Spacing[1], m_Spacing[2]}; itk::ImageRegionIterator<ImageType> outIt(this->GetOutput(), m_Region); outIt.GoToBegin(); while(!outIt.IsAtEnd()) { const auto I = outIt.GetIndex() - startIndex; // Might be padded to a negative start const double x = fmod(static_cast<double>(I[0]) + hsz[0], sz[0]) - hsz[0]; const double y = fmod(static_cast<double>(I[1]) + hsz[1], sz[1]) - hsz[1]; const double z = fmod(static_cast<double>(I[2]) + hsz[2], sz[2]) - hsz[2]; const Eigen::Array3d p{x, y, z}; typename ImageType::PixelType val = 1; for (const auto &kernel : m_kernels) { val *= kernel->value(p, hsz, sp); } outIt.Set(val); ++outIt; } } private: KernelSource(const Self &); void operator=(const Self &); }; } // End namespace itk //****************************************************************************** // Main //****************************************************************************** const string usage { "Usage is: qikfilter [options] input \n\ \n\ Filter images in k-Space\n\ \n\ Options:\n\ --help, -h : Print this message.\n\ --verbose, -v : Print more information.\n\ --out, -o path : Specify an output filename (default image base).\n\ --filter, -f F : Choose a filter (see below).\n\ --zeropad, -z Z : Zero-pad by Z voxels.\n\ --save_kernel, -k : Save all pipeline steps.\n\ --complex_in : Read complex data.\n\ --complex_out : Output complex data.\n\ --threads, -T N : Use N threads (default=hardware limit).\n\ \n\ Valid filters are:\n\ Tukey,a,q - Tukey filter with parameters a & q\n\ Hamming,a,b - Hamming filter with parameters a & b\n\ Gauss,a - Gaussian with width a (in k-space)\n" }; int main(int argc, char **argv) { Eigen::initParallel(); //****************************************************************************** // Arguments / Usage //****************************************************************************** bool verbose = false, save_kernel = false; int complex_in = false, complex_out = false, zero_padding = 0; std::vector<shared_ptr<QI::FilterKernel>> kernels; string out_name; const struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"verbose", no_argument, 0, 'v'}, {"out", required_argument, 0, 'o'}, {"filter", required_argument, 0, 'f'}, {"zeropad", required_argument, 0, 'z'}, {"save_kernel", no_argument, 0, 'k'}, {"complex_in", no_argument, &complex_in, true}, {"complex_out", no_argument, &complex_out, true}, {"threads", required_argument, 0, 'T'}, {0, 0, 0, 0} }; const char *short_options = "hvo:m:e:z:kT:"; int indexptr = 0, c; while ((c = getopt_long(argc, argv, short_options, long_options, &indexptr)) != -1) { switch (c) { case 'v': verbose = true; break; case 'o': out_name = optarg; if (verbose) cout << "Output filename will be: " << out_name << endl; break; case 'f': { stringstream f(optarg); kernels.push_back(QI::ReadKernel(f)); if (verbose) cout << "Read kernel: " << *kernels.back() << endl; } break; case 'z': zero_padding = atoi(optarg); break; case 'k': save_kernel = true; break; case 'T': itk::MultiThreader::SetGlobalMaximumNumberOfThreads(atoi(optarg)); break; case 'h': cout << QI::GetVersion() << endl << usage << endl; return EXIT_SUCCESS; case 0: break; // Just a flag case '?': // getopt will print an error message return EXIT_FAILURE; default: cout << "Unhandled option " << string(1, c) << endl; return EXIT_FAILURE; } } if ((argc - optind) != 1) { cout << "Incorrect number of arguments." << endl << usage << endl; return EXIT_FAILURE; } string in_name(argv[optind++]); QI::SeriesXF::Pointer vols; if (complex_in) { if (verbose) cout << "Reading complex file: " << in_name << endl; vols = QI::ReadImage<QI::SeriesXF>(in_name); } else { if (verbose) cout << "Reading real file: " << in_name << endl; QI::SeriesF::Pointer rvols = QI::ReadImage<QI::SeriesF>(in_name); auto cast = itk::CastImageFilter<QI::SeriesF, QI::SeriesXF>::New(); cast->SetInput(rvols); cast->Update(); vols = cast->GetOutput(); vols->DisconnectPipeline(); } /* * Main calculation starts hear. * First a lot of typedefs. */ typedef itk::ExtractImageFilter<QI::SeriesXF, QI::VolumeXD> TExtract; typedef itk::TileImageFilter<QI::VolumeXF, QI::SeriesXF> TTile; typedef itk::CastImageFilter<QI::VolumeXD, QI::VolumeXF> TCast; typedef itk::ConstantPadImageFilter<QI::VolumeXD, QI::VolumeXD> TZeroPad; typedef itk::FFTPadImageFilter<QI::VolumeXD> TFFTPad; typedef itk::ComplexToComplexFFTImageFilter<QI::VolumeXD> TFFT; typedef itk::MultiplyImageFilter<QI::VolumeXD, QI::VolumeD, QI::VolumeXD> TMult; typedef itk::KernelSource<QI::VolumeD> TKernel; typedef itk::ExtractImageFilter<QI::VolumeXD, QI::VolumeXF> TUnpad; auto region = vols->GetLargestPossibleRegion(); const size_t nvols = region.GetSize()[3]; // Save for the loop region.GetModifiableSize()[3] = 0; QI::VolumeXD::RegionType unpad_region; for (int i = 0; i < 3; i++) { unpad_region.GetModifiableSize()[i] = region.GetSize()[i]; } itk::FixedArray<unsigned int, 4> layout; layout[0] = layout[1] = layout[2] = 1; layout[3] = nvols; auto extract = TExtract::New(); auto zero_pad = TZeroPad::New(); auto fft_pad = TFFTPad::New(); auto forward = TFFT::New(); auto tkernel = TKernel::New(); auto mult = TMult::New(); // inverse is declared in the loop due to a weird bug auto unpadder = TUnpad::New(); auto tile = TTile::New(); extract->SetInput(vols); extract->SetDirectionCollapseToSubmatrix(); if (zero_padding > 0) { QI::VolumeXD::SizeType padding; padding.Fill(zero_padding); zero_pad->SetInput(extract->GetOutput()); zero_pad->SetPadLowerBound(padding); zero_pad->SetPadUpperBound(padding); zero_pad->SetConstant(0); fft_pad->SetInput(zero_pad->GetOutput()); } else { fft_pad->SetInput(extract->GetOutput()); } fft_pad->SetSizeGreatestPrimeFactor(5); // This is the largest the VNL FFT supports forward->SetInput(fft_pad->GetOutput()); if (kernels.size() == 0) { kernels.push_back(std::make_shared<QI::TukeyKernel>()); } tkernel->SetKernels(kernels); mult->SetInput1(forward->GetOutput()); mult->SetInput2(tkernel->GetOutput()); unpadder->SetDirectionCollapseToSubmatrix(); unpadder->SetExtractionRegion(unpad_region); tile->SetLayout(layout); for (int i = 0; i < nvols; i++) { region.GetModifiableIndex()[3] = i; if (verbose) cout << "Processing volume " << i << endl; extract->SetExtractionRegion(region); extract->Update(); fft_pad->Update(); if (i == 0) { // For first image we need to update the kernel tkernel->SetRegion(fft_pad->GetOutput()->GetLargestPossibleRegion()); tkernel->SetSpacing(fft_pad->GetOutput()->GetSpacing()); tkernel->SetOrigin(fft_pad->GetOutput()->GetOrigin()); tkernel->SetDirection(fft_pad->GetOutput()->GetDirection()); tkernel->Update(); if (verbose) std::cout << "Built kernel" << std::endl; } mult->Update(); auto inverse = TFFT::New(); inverse->SetTransformDirection(TFFT::INVERSE); inverse->SetInput(mult->GetOutput()); unpadder->SetInput(inverse->GetOutput()); inverse->Update(); // Need a separate update to avoid region bug unpadder->Update(); QI::VolumeXF::Pointer v = unpadder->GetOutput(); tile->SetInput(i, v); v->DisconnectPipeline(); } if (verbose) cout << "Finished." << endl; tile->Update(); auto dir = vols->GetDirection(); auto spc = vols->GetSpacing(); vols = tile->GetOutput(); vols->SetDirection(dir); vols->SetSpacing(spc); vols->DisconnectPipeline(); if (out_name == "") out_name = in_name.substr(0, in_name.find(".")); const std::string out_path = out_name + "_filtered" + QI::OutExt(); if (complex_out) { if (verbose) cout << "Saving complex output file: " << out_path << endl; QI::WriteImage(vols, out_path); } else { if (verbose) cout << "Saving real output file: " << out_path << endl; QI::WriteMagnitudeImage(vols, out_path); } if (save_kernel) { const string kernel_path = out_name + "_kernel" + QI::OutExt(); if (verbose) cout << "Saving filter kernel to: " << kernel_path << endl; QI::WriteImage(tkernel->GetOutput(), kernel_path); } return EXIT_SUCCESS; } <commit_msg>BUG: Fixed narrowing warning.<commit_after>/* * qikfilter.cpp * * Copyright (c) 2015 Tobias Wood. * * 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 <memory> #include <getopt.h> #include <iostream> #include <sstream> #include "Eigen/Dense" #include "itkImageSource.h" #include "itkConstNeighborhoodIterator.h" #include "itkImageRegionIteratorWithIndex.h" #include "itkMultiplyImageFilter.h" #include "itkDivideImageFilter.h" #include "itkComplexToComplexFFTImageFilter.h" #include "itkInverseFFTImageFilter.h" #include "itkFFTShiftImageFilter.h" #include "itkComplexToModulusImageFilter.h" #include "itkFFTPadImageFilter.h" #include "itkConstantPadImageFilter.h" #include "itkExtractImageFilter.h" #include "itkPasteImageFilter.h" #include "itkCastImageFilter.h" #include "QI/Types.h" #include "QI/Util.h" #include "QI/Kernels.h" #include "QI/IO.h" using namespace std; using namespace Eigen; namespace itk { template<typename TImage> class KernelSource : public ImageSource<TImage> { public: typedef TImage ImageType; typedef KernelSource Self; typedef ImageSource<ImageType> Superclass; typedef SmartPointer<Self> Pointer; typedef typename ImageType::RegionType RegionType; typedef typename ImageType::IndexType IndexType; typedef typename ImageType::SizeType SizeType; typedef typename ImageType::SpacingType SpacingType; typedef typename ImageType::DirectionType DirectionType; typedef typename ImageType::PointType PointType; protected: KernelSource(){} ~KernelSource(){} RegionType m_Region; SpacingType m_Spacing; DirectionType m_Direction; PointType m_Origin; std::vector<std::shared_ptr<QI::FilterKernel>> m_kernels; public: itkNewMacro(Self); itkTypeMacro(Self, ImageSource); void SetKernels(const std::vector<std::shared_ptr<QI::FilterKernel>> &k) { m_kernels = k; } itkSetMacro(Region, RegionType); itkSetMacro(Spacing, SpacingType); itkSetMacro(Direction, DirectionType); itkSetMacro(Origin, PointType); protected: virtual void GenerateOutputInformation() ITK_OVERRIDE { auto output = this->GetOutput(0); output->SetLargestPossibleRegion(m_Region); output->SetSpacing(m_Spacing); output->SetDirection(m_Direction); output->SetOrigin(m_Origin); } virtual void ThreadedGenerateData(const RegionType &region, ThreadIdType threadId) ITK_OVERRIDE { const auto startIndex = m_Region.GetIndex(); const Eigen::Array3d sz{static_cast<double>(m_Region.GetSize()[0]), static_cast<double>(m_Region.GetSize()[1]), static_cast<double>(m_Region.GetSize()[2])}; const Eigen::Array3d hsz = sz / 2; const Eigen::Array3d sp{m_Spacing[0], m_Spacing[1], m_Spacing[2]}; itk::ImageRegionIterator<ImageType> outIt(this->GetOutput(), m_Region); outIt.GoToBegin(); while(!outIt.IsAtEnd()) { const auto I = outIt.GetIndex() - startIndex; // Might be padded to a negative start const double x = fmod(static_cast<double>(I[0]) + hsz[0], sz[0]) - hsz[0]; const double y = fmod(static_cast<double>(I[1]) + hsz[1], sz[1]) - hsz[1]; const double z = fmod(static_cast<double>(I[2]) + hsz[2], sz[2]) - hsz[2]; const Eigen::Array3d p{x, y, z}; typename ImageType::PixelType val = 1; for (const auto &kernel : m_kernels) { val *= kernel->value(p, hsz, sp); } outIt.Set(val); ++outIt; } } private: KernelSource(const Self &); void operator=(const Self &); }; } // End namespace itk //****************************************************************************** // Main //****************************************************************************** const string usage { "Usage is: qikfilter [options] input \n\ \n\ Filter images in k-Space\n\ \n\ Options:\n\ --help, -h : Print this message.\n\ --verbose, -v : Print more information.\n\ --out, -o path : Specify an output filename (default image base).\n\ --filter, -f F : Choose a filter (see below).\n\ --zeropad, -z Z : Zero-pad by Z voxels.\n\ --save_kernel, -k : Save all pipeline steps.\n\ --complex_in : Read complex data.\n\ --complex_out : Output complex data.\n\ --threads, -T N : Use N threads (default=hardware limit).\n\ \n\ Valid filters are:\n\ Tukey,a,q - Tukey filter with parameters a & q\n\ Hamming,a,b - Hamming filter with parameters a & b\n\ Gauss,a - Gaussian with width a (in k-space)\n" }; int main(int argc, char **argv) { Eigen::initParallel(); //****************************************************************************** // Arguments / Usage //****************************************************************************** bool verbose = false, save_kernel = false; int complex_in = false, complex_out = false, zero_padding = 0; std::vector<shared_ptr<QI::FilterKernel>> kernels; string out_name; const struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"verbose", no_argument, 0, 'v'}, {"out", required_argument, 0, 'o'}, {"filter", required_argument, 0, 'f'}, {"zeropad", required_argument, 0, 'z'}, {"save_kernel", no_argument, 0, 'k'}, {"complex_in", no_argument, &complex_in, true}, {"complex_out", no_argument, &complex_out, true}, {"threads", required_argument, 0, 'T'}, {0, 0, 0, 0} }; const char *short_options = "hvo:m:e:z:kT:"; int indexptr = 0, c; while ((c = getopt_long(argc, argv, short_options, long_options, &indexptr)) != -1) { switch (c) { case 'v': verbose = true; break; case 'o': out_name = optarg; if (verbose) cout << "Output filename will be: " << out_name << endl; break; case 'f': { stringstream f(optarg); kernels.push_back(QI::ReadKernel(f)); if (verbose) cout << "Read kernel: " << *kernels.back() << endl; } break; case 'z': zero_padding = atoi(optarg); break; case 'k': save_kernel = true; break; case 'T': itk::MultiThreader::SetGlobalMaximumNumberOfThreads(atoi(optarg)); break; case 'h': cout << QI::GetVersion() << endl << usage << endl; return EXIT_SUCCESS; case 0: break; // Just a flag case '?': // getopt will print an error message return EXIT_FAILURE; default: cout << "Unhandled option " << string(1, c) << endl; return EXIT_FAILURE; } } if ((argc - optind) != 1) { cout << "Incorrect number of arguments." << endl << usage << endl; return EXIT_FAILURE; } string in_name(argv[optind++]); QI::SeriesXF::Pointer vols; if (complex_in) { if (verbose) cout << "Reading complex file: " << in_name << endl; vols = QI::ReadImage<QI::SeriesXF>(in_name); } else { if (verbose) cout << "Reading real file: " << in_name << endl; QI::SeriesF::Pointer rvols = QI::ReadImage<QI::SeriesF>(in_name); auto cast = itk::CastImageFilter<QI::SeriesF, QI::SeriesXF>::New(); cast->SetInput(rvols); cast->Update(); vols = cast->GetOutput(); vols->DisconnectPipeline(); } /* * Main calculation starts hear. * First a lot of typedefs. */ typedef itk::ExtractImageFilter<QI::SeriesXF, QI::VolumeXD> TExtract; typedef itk::TileImageFilter<QI::VolumeXF, QI::SeriesXF> TTile; typedef itk::CastImageFilter<QI::VolumeXD, QI::VolumeXF> TCast; typedef itk::ConstantPadImageFilter<QI::VolumeXD, QI::VolumeXD> TZeroPad; typedef itk::FFTPadImageFilter<QI::VolumeXD> TFFTPad; typedef itk::ComplexToComplexFFTImageFilter<QI::VolumeXD> TFFT; typedef itk::MultiplyImageFilter<QI::VolumeXD, QI::VolumeD, QI::VolumeXD> TMult; typedef itk::KernelSource<QI::VolumeD> TKernel; typedef itk::ExtractImageFilter<QI::VolumeXD, QI::VolumeXF> TUnpad; auto region = vols->GetLargestPossibleRegion(); const size_t nvols = region.GetSize()[3]; // Save for the loop region.GetModifiableSize()[3] = 0; QI::VolumeXD::RegionType unpad_region; for (int i = 0; i < 3; i++) { unpad_region.GetModifiableSize()[i] = region.GetSize()[i]; } itk::FixedArray<unsigned int, 4> layout; layout[0] = layout[1] = layout[2] = 1; layout[3] = nvols; auto extract = TExtract::New(); auto zero_pad = TZeroPad::New(); auto fft_pad = TFFTPad::New(); auto forward = TFFT::New(); auto tkernel = TKernel::New(); auto mult = TMult::New(); // inverse is declared in the loop due to a weird bug auto unpadder = TUnpad::New(); auto tile = TTile::New(); extract->SetInput(vols); extract->SetDirectionCollapseToSubmatrix(); if (zero_padding > 0) { QI::VolumeXD::SizeType padding; padding.Fill(zero_padding); zero_pad->SetInput(extract->GetOutput()); zero_pad->SetPadLowerBound(padding); zero_pad->SetPadUpperBound(padding); zero_pad->SetConstant(0); fft_pad->SetInput(zero_pad->GetOutput()); } else { fft_pad->SetInput(extract->GetOutput()); } fft_pad->SetSizeGreatestPrimeFactor(5); // This is the largest the VNL FFT supports forward->SetInput(fft_pad->GetOutput()); if (kernels.size() == 0) { kernels.push_back(std::make_shared<QI::TukeyKernel>()); } tkernel->SetKernels(kernels); mult->SetInput1(forward->GetOutput()); mult->SetInput2(tkernel->GetOutput()); unpadder->SetDirectionCollapseToSubmatrix(); unpadder->SetExtractionRegion(unpad_region); tile->SetLayout(layout); for (int i = 0; i < nvols; i++) { region.GetModifiableIndex()[3] = i; if (verbose) cout << "Processing volume " << i << endl; extract->SetExtractionRegion(region); extract->Update(); fft_pad->Update(); if (i == 0) { // For first image we need to update the kernel tkernel->SetRegion(fft_pad->GetOutput()->GetLargestPossibleRegion()); tkernel->SetSpacing(fft_pad->GetOutput()->GetSpacing()); tkernel->SetOrigin(fft_pad->GetOutput()->GetOrigin()); tkernel->SetDirection(fft_pad->GetOutput()->GetDirection()); tkernel->Update(); if (verbose) std::cout << "Built kernel" << std::endl; } mult->Update(); auto inverse = TFFT::New(); inverse->SetTransformDirection(TFFT::INVERSE); inverse->SetInput(mult->GetOutput()); unpadder->SetInput(inverse->GetOutput()); inverse->Update(); // Need a separate update to avoid region bug unpadder->Update(); QI::VolumeXF::Pointer v = unpadder->GetOutput(); tile->SetInput(i, v); v->DisconnectPipeline(); } if (verbose) cout << "Finished." << endl; tile->Update(); auto dir = vols->GetDirection(); auto spc = vols->GetSpacing(); vols = tile->GetOutput(); vols->SetDirection(dir); vols->SetSpacing(spc); vols->DisconnectPipeline(); if (out_name == "") out_name = in_name.substr(0, in_name.find(".")); const std::string out_path = out_name + "_filtered" + QI::OutExt(); if (complex_out) { if (verbose) cout << "Saving complex output file: " << out_path << endl; QI::WriteImage(vols, out_path); } else { if (verbose) cout << "Saving real output file: " << out_path << endl; QI::WriteMagnitudeImage(vols, out_path); } if (save_kernel) { const string kernel_path = out_name + "_kernel" + QI::OutExt(); if (verbose) cout << "Saving filter kernel to: " << kernel_path << endl; QI::WriteImage(tkernel->GetOutput(), kernel_path); } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* * qikfilter.cpp * * Copyright (c) 2015 Tobias Wood. * * 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 <memory> #include <getopt.h> #include <iostream> #include <sstream> #include "Eigen/Dense" #include "itkImageSource.h" #include "itkConstNeighborhoodIterator.h" #include "itkImageRegionIteratorWithIndex.h" #include "itkMultiplyImageFilter.h" #include "itkDivideImageFilter.h" #include "itkComplexToComplexFFTImageFilter.h" #include "itkInverseFFTImageFilter.h" #include "itkFFTShiftImageFilter.h" #include "itkComplexToModulusImageFilter.h" #include "itkFFTPadImageFilter.h" #include "itkConstantPadImageFilter.h" #include "itkExtractImageFilter.h" #include "itkPasteImageFilter.h" #include "itkCastImageFilter.h" #include "QI/Types.h" #include "QI/Util.h" #include "QI/Kernels.h" #include "QI/IO.h" using namespace std; using namespace Eigen; namespace itk { template<typename TImage> class KernelSource : public ImageSource<TImage> { public: typedef TImage ImageType; typedef KernelSource Self; typedef ImageSource<ImageType> Superclass; typedef SmartPointer<Self> Pointer; typedef typename ImageType::RegionType RegionType; typedef typename ImageType::IndexType IndexType; typedef typename ImageType::SizeType SizeType; typedef typename ImageType::SpacingType SpacingType; typedef typename ImageType::DirectionType DirectionType; typedef typename ImageType::PointType PointType; protected: KernelSource(){} ~KernelSource(){} RegionType m_Region; SpacingType m_Spacing; DirectionType m_Direction; PointType m_Origin; std::vector<std::shared_ptr<QI::FilterKernel>> m_kernels; public: itkNewMacro(Self); itkTypeMacro(Self, ImageSource); void SetKernels(const std::vector<std::shared_ptr<QI::FilterKernel>> &k) { m_kernels = k; } itkSetMacro(Region, RegionType); itkSetMacro(Spacing, SpacingType); itkSetMacro(Direction, DirectionType); itkSetMacro(Origin, PointType); protected: virtual void GenerateOutputInformation() ITK_OVERRIDE { auto output = this->GetOutput(0); output->SetLargestPossibleRegion(m_Region); output->SetSpacing(m_Spacing); output->SetDirection(m_Direction); output->SetOrigin(m_Origin); } virtual void ThreadedGenerateData(const RegionType &region, ThreadIdType threadId) ITK_OVERRIDE { const auto startIndex = m_Region.GetIndex(); const Eigen::Array3d sz{static_cast<double>(m_Region.GetSize()[0]), static_cast<double>(m_Region.GetSize()[1]), static_cast<double>(m_Region.GetSize()[2])}; const Eigen::Array3d hsz = sz / 2; const Eigen::Array3d sp{m_Spacing[0], m_Spacing[1], m_Spacing[2]}; itk::ImageRegionIterator<ImageType> outIt(this->GetOutput(), m_Region); outIt.GoToBegin(); while(!outIt.IsAtEnd()) { const auto I = outIt.GetIndex() - startIndex; // Might be padded to a negative start const double x = fmod(static_cast<double>(I[0]) + hsz[0], sz[0]) - hsz[0]; const double y = fmod(static_cast<double>(I[1]) + hsz[1], sz[1]) - hsz[1]; const double z = fmod(static_cast<double>(I[2]) + hsz[2], sz[2]) - hsz[2]; const Eigen::Array3d p{x, y, z}; typename ImageType::PixelType val = 1; for (const auto &kernel : m_kernels) { val *= kernel->value(p, hsz, sp); } outIt.Set(val); ++outIt; } } private: KernelSource(const Self &); void operator=(const Self &); }; } // End namespace itk //****************************************************************************** // Main //****************************************************************************** const string usage { "Usage is: qikfilter [options] input \n\ \n\ Filter images in k-Space\n\ \n\ Options:\n\ --help, -h : Print this message.\n\ --verbose, -v : Print more information.\n\ --out, -o path : Specify an output filename (default image base).\n\ --filter, -f F : Choose a filter (see below).\n\ --zeropad, -z Z : Zero-pad by Z voxels.\n\ --save_kernel, -k : Save all pipeline steps.\n\ --complex_in : Read complex data.\n\ --complex_out : Output complex data.\n\ --threads, -T N : Use N threads (default=hardware limit).\n\ \n\ Valid filters are:\n\ Tukey,a,q - Tukey filter with parameters a & q\n\ Hamming,a,b - Hamming filter with parameters a & b\n\ Gauss,a - Gaussian with width a (in k-space)\n" }; int main(int argc, char **argv) { Eigen::initParallel(); //****************************************************************************** // Arguments / Usage //****************************************************************************** bool verbose = false, save_kernel = false; int complex_in = false, complex_out = false, zero_padding = 0; std::vector<shared_ptr<QI::FilterKernel>> kernels; string out_name; const struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"verbose", no_argument, 0, 'v'}, {"out", required_argument, 0, 'o'}, {"filter", required_argument, 0, 'f'}, {"zeropad", required_argument, 0, 'z'}, {"save_kernel", no_argument, 0, 'k'}, {"complex_in", no_argument, &complex_in, true}, {"complex_out", no_argument, &complex_out, true}, {"threads", required_argument, 0, 'T'}, {0, 0, 0, 0} }; const char *short_options = "hvo:m:e:z:kT:"; int indexptr = 0, c; while ((c = getopt_long(argc, argv, short_options, long_options, &indexptr)) != -1) { switch (c) { case 'v': verbose = true; break; case 'o': out_name = optarg; if (verbose) cout << "Output filename will be: " << out_name << endl; break; case 'f': { stringstream f(optarg); kernels.push_back(QI::ReadKernel(f)); if (verbose) cout << "Read kernel: " << *kernels.back() << endl; } break; case 'z': zero_padding = atoi(optarg); break; case 'k': save_kernel = true; break; case 'T': itk::MultiThreader::SetGlobalMaximumNumberOfThreads(atoi(optarg)); break; case 'h': cout << QI::GetVersion() << endl << usage << endl; return EXIT_SUCCESS; case 0: break; // Just a flag case '?': // getopt will print an error message return EXIT_FAILURE; default: cout << "Unhandled option " << string(1, c) << endl; return EXIT_FAILURE; } } if ((argc - optind) != 1) { cout << "Incorrect number of arguments." << endl << usage << endl; return EXIT_FAILURE; } string in_name(argv[optind++]); QI::SeriesXF::Pointer vols; if (complex_in) { if (verbose) cout << "Reading complex file: " << in_name << endl; vols = QI::ReadImage<QI::SeriesXF>(in_name); } else { if (verbose) cout << "Reading real file: " << in_name << endl; QI::SeriesF::Pointer rvols = QI::ReadImage<QI::SeriesF>(in_name); auto cast = itk::CastImageFilter<QI::SeriesF, QI::SeriesXF>::New(); cast->SetInput(rvols); cast->Update(); vols = cast->GetOutput(); vols->DisconnectPipeline(); } /* * Main calculation starts hear. * First a lot of typedefs. */ typedef itk::ExtractImageFilter<QI::SeriesXF, QI::VolumeXD> TExtract; typedef itk::TileImageFilter<QI::VolumeXF, QI::SeriesXF> TTile; typedef itk::CastImageFilter<QI::VolumeXD, QI::VolumeXF> TCast; typedef itk::ConstantPadImageFilter<QI::VolumeXD, QI::VolumeXD> TZeroPad; typedef itk::FFTPadImageFilter<QI::VolumeXD> TFFTPad; typedef itk::ComplexToComplexFFTImageFilter<QI::VolumeXD> TFFT; typedef itk::MultiplyImageFilter<QI::VolumeXD, QI::VolumeD, QI::VolumeXD> TMult; typedef itk::KernelSource<QI::VolumeD> TKernel; typedef itk::ExtractImageFilter<QI::VolumeXD, QI::VolumeXF> TUnpad; auto region = vols->GetLargestPossibleRegion(); const size_t nvols = region.GetSize()[3]; // Save for the loop region.GetModifiableSize()[3] = 0; QI::VolumeXD::RegionType unpad_region; for (int i = 0; i < 3; i++) { unpad_region.GetModifiableSize()[i] = region.GetSize()[i]; } itk::FixedArray<unsigned int, 4> layout; layout[0] = layout[1] = layout[2] = 1; layout[3] = nvols; auto extract = TExtract::New(); auto zero_pad = TZeroPad::New(); auto fft_pad = TFFTPad::New(); auto forward = TFFT::New(); auto tkernel = TKernel::New(); auto mult = TMult::New(); // inverse is declared in the loop due to a weird bug auto unpadder = TUnpad::New(); auto tile = TTile::New(); extract->SetInput(vols); extract->SetDirectionCollapseToSubmatrix(); if (zero_padding > 0) { QI::VolumeXD::SizeType padding; padding.Fill(zero_padding); zero_pad->SetInput(extract->GetOutput()); zero_pad->SetPadLowerBound(padding); zero_pad->SetPadUpperBound(padding); zero_pad->SetConstant(0); fft_pad->SetInput(zero_pad->GetOutput()); } else { fft_pad->SetInput(extract->GetOutput()); } fft_pad->SetSizeGreatestPrimeFactor(5); // This is the largest the VNL FFT supports forward->SetInput(fft_pad->GetOutput()); if (kernels.size() == 0) { kernels.push_back(std::make_shared<QI::TukeyKernel>()); } tkernel->SetKernels(kernels); mult->SetInput1(forward->GetOutput()); mult->SetInput2(tkernel->GetOutput()); unpadder->SetDirectionCollapseToSubmatrix(); unpadder->SetExtractionRegion(unpad_region); tile->SetLayout(layout); for (int i = 0; i < nvols; i++) { region.GetModifiableIndex()[3] = i; if (verbose) cout << "Processing volume " << i << endl; extract->SetExtractionRegion(region); extract->Update(); fft_pad->Update(); if (i == 0) { // For first image we need to update the kernel tkernel->SetRegion(fft_pad->GetOutput()->GetLargestPossibleRegion()); tkernel->SetSpacing(fft_pad->GetOutput()->GetSpacing()); tkernel->SetOrigin(fft_pad->GetOutput()->GetOrigin()); tkernel->SetDirection(fft_pad->GetOutput()->GetDirection()); tkernel->Update(); if (verbose) std::cout << "Built kernel" << std::endl; } mult->Update(); auto inverse = TFFT::New(); inverse->SetTransformDirection(TFFT::INVERSE); inverse->SetInput(mult->GetOutput()); unpadder->SetInput(inverse->GetOutput()); inverse->Update(); // Need a separate update to avoid region bug unpadder->Update(); QI::VolumeXF::Pointer v = unpadder->GetOutput(); tile->SetInput(i, v); v->DisconnectPipeline(); } if (verbose) cout << "Finished." << endl; tile->Update(); auto dir = vols->GetDirection(); auto spc = vols->GetSpacing(); vols = tile->GetOutput(); vols->SetDirection(dir); vols->SetSpacing(spc); vols->DisconnectPipeline(); if (out_name == "") out_name = in_name.substr(0, in_name.find(".")); const std::string out_path = out_name + "_filtered" + QI::OutExt(); if (complex_out) { if (verbose) cout << "Saving complex output file: " << out_path << endl; QI::WriteImage(vols, out_path); } else { if (verbose) cout << "Saving real output file: " << out_path << endl; QI::WriteMagnitudeImage(vols, out_path); } if (save_kernel) { const string kernel_path = out_name + "_kernel" + QI::OutExt(); if (verbose) cout << "Saving filter kernel to: " << kernel_path << endl; QI::WriteImage(tkernel->GetOutput(), kernel_path); } return EXIT_SUCCESS; } <commit_msg>ENH: Now can do one filter per volume.<commit_after>/* * qikfilter.cpp * * Copyright (c) 2015 Tobias Wood. * * 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 <memory> #include <iostream> #include <sstream> #include "Eigen/Dense" #include "itkImageSource.h" #include "itkConstNeighborhoodIterator.h" #include "itkImageRegionIteratorWithIndex.h" #include "itkMultiplyImageFilter.h" #include "itkDivideImageFilter.h" #include "itkComplexToComplexFFTImageFilter.h" #include "itkInverseFFTImageFilter.h" #include "itkFFTShiftImageFilter.h" #include "itkComplexToModulusImageFilter.h" #include "itkFFTPadImageFilter.h" #include "itkConstantPadImageFilter.h" #include "itkExtractImageFilter.h" #include "itkPasteImageFilter.h" #include "itkCastImageFilter.h" #include "QI/Types.h" #include "QI/Util.h" #include "QI/Kernels.h" #include "QI/IO.h" #include "QI/Args.h" using namespace std; using namespace Eigen; namespace itk { template<typename TImage> class KernelSource : public ImageSource<TImage> { public: typedef TImage ImageType; typedef KernelSource Self; typedef ImageSource<ImageType> Superclass; typedef SmartPointer<Self> Pointer; typedef typename ImageType::RegionType RegionType; typedef typename ImageType::IndexType IndexType; typedef typename ImageType::SizeType SizeType; typedef typename ImageType::SpacingType SpacingType; typedef typename ImageType::DirectionType DirectionType; typedef typename ImageType::PointType PointType; protected: KernelSource(){} ~KernelSource(){} RegionType m_Region; SpacingType m_Spacing; DirectionType m_Direction; PointType m_Origin; std::vector<std::shared_ptr<QI::FilterKernel>> m_kernels; public: itkNewMacro(Self); itkTypeMacro(Self, ImageSource); void SetKernel(const std::shared_ptr<QI::FilterKernel> &k) { m_kernels.clear(); m_kernels.push_back(k); this->Modified(); } void SetKernels(const std::vector<std::shared_ptr<QI::FilterKernel>> &k) { m_kernels = k; this->Modified(); } itkSetMacro(Region, RegionType); itkSetMacro(Spacing, SpacingType); itkSetMacro(Direction, DirectionType); itkSetMacro(Origin, PointType); protected: virtual void GenerateOutputInformation() ITK_OVERRIDE { auto output = this->GetOutput(0); output->SetLargestPossibleRegion(m_Region); output->SetSpacing(m_Spacing); output->SetDirection(m_Direction); output->SetOrigin(m_Origin); } virtual void ThreadedGenerateData(const RegionType &region, ThreadIdType threadId) ITK_OVERRIDE { const auto startIndex = m_Region.GetIndex(); const Eigen::Array3d sz{static_cast<double>(m_Region.GetSize()[0]), static_cast<double>(m_Region.GetSize()[1]), static_cast<double>(m_Region.GetSize()[2])}; const Eigen::Array3d hsz = sz / 2; const Eigen::Array3d sp{m_Spacing[0], m_Spacing[1], m_Spacing[2]}; itk::ImageRegionIterator<ImageType> outIt(this->GetOutput(), m_Region); outIt.GoToBegin(); while(!outIt.IsAtEnd()) { const auto I = outIt.GetIndex() - startIndex; // Might be padded to a negative start const double x = fmod(static_cast<double>(I[0]) + hsz[0], sz[0]) - hsz[0]; const double y = fmod(static_cast<double>(I[1]) + hsz[1], sz[1]) - hsz[1]; const double z = fmod(static_cast<double>(I[2]) + hsz[2], sz[2]) - hsz[2]; const Eigen::Array3d p{x, y, z}; typename ImageType::PixelType val = 1; for (const auto &kernel : m_kernels) { val *= kernel->value(p, hsz, sp); } outIt.Set(val); ++outIt; } } private: KernelSource(const Self &); void operator=(const Self &); }; } // End namespace itk //****************************************************************************** // Main //****************************************************************************** const string usage { "Usage is: qikfilter [options] input \n\ \n\ Filter images in k-Space\n\ \n\ Options:\n\ --help, -h : Print this message.\n\ --verbose, -v : Print more information.\n\ --out, -o path : Specify an output filename (default image base).\n\ --filter, -f F : Choose a filter (see below).\n\ --zeropad, -z Z : Zero-pad by Z voxels.\n\ --save_kernel, -k : Save all pipeline steps.\n\ --complex_in : Read complex data.\n\ --complex_out : Output complex data.\n\ --threads, -T N : Use N threads (default=hardware limit).\n\ \n\ Valid filters are:\n\ Tukey,a,q - Tukey filter with parameters a & q\n\ Hamming,a,b - Hamming filter with parameters a & b\n\ Gauss,a - Gaussian with width a (in k-space)\n" }; int main(int argc, char **argv) { Eigen::initParallel(); args::ArgumentParser parser("Filters/smooths images in k-space\nhttp://github.com/spinicist/QUIT", "Va"); args::Positional<std::string> in_path(parser, "INPUT", "Input file."); args::HelpFlag help(parser, "HELP", "Show this help menu", {'h', "help"}); args::Flag verbose(parser, "VERBOSE", "Print more information", {'v', "verbose"}); args::ValueFlag<int> threads(parser, "THREADS", "Use N threads (default=4, 0=hardware limit)", {'T', "threads"}, 4); args::ValueFlag<std::string> out_prefix(parser, "OUTPREFIX", "Add a prefix to output filenames", {'o', "out"}); args::ValueFlag<int> zero_padding(parser, "ZEROPAD", "Zero-pad volume by N voxels in each direction", {'z', "zero_pad"}, 0); args::Flag complex_in(parser, "COMPLEX_IN", "Input data is complex", {"complex_in"}); args::Flag complex_out(parser, "COMPLEX_OUT", "Write complex output", {"complex_out"}); args::Flag save_kernel(parser, "KERNEL", "Save kernels as images", {"save_kernel"}); args::Flag filter_per_volume(parser, "FILTER_PER_VOL", "Instead of concatenating multiple filters, use one per volume", {"filter_per_volume"}); args::ValueFlagList<std::string> filters(parser, "FILTER", "Specify a filter to use (can be multiple)", {'f', "filter"}); QI::ParseArgs(parser, argc, argv); itk::MultiThreader::SetGlobalDefaultNumberOfThreads(threads.Get()); std::vector<shared_ptr<QI::FilterKernel>> kernels; if (filters) { for (const auto &f: filters.Get()) { kernels.push_back(QI::ReadKernel(f)); } } else { kernels.push_back(std::make_shared<QI::TukeyKernel>()); } QI::SeriesXF::Pointer vols; if (complex_in) { if (verbose) cout << "Reading complex file: " << QI::CheckPos(in_path) << endl; vols = QI::ReadImage<QI::SeriesXF>(QI::CheckPos(in_path)); } else { if (verbose) cout << "Reading real file: " << QI::CheckPos(in_path) << endl; QI::SeriesF::Pointer rvols = QI::ReadImage<QI::SeriesF>(QI::CheckPos(in_path)); auto cast = itk::CastImageFilter<QI::SeriesF, QI::SeriesXF>::New(); cast->SetInput(rvols); cast->Update(); vols = cast->GetOutput(); vols->DisconnectPipeline(); } /* * Main calculation starts hear. * First a lot of typedefs. */ typedef itk::ExtractImageFilter<QI::SeriesXF, QI::VolumeXD> TExtract; typedef itk::TileImageFilter<QI::VolumeXF, QI::SeriesXF> TTile; typedef itk::CastImageFilter<QI::VolumeXD, QI::VolumeXF> TCast; typedef itk::ConstantPadImageFilter<QI::VolumeXD, QI::VolumeXD> TZeroPad; typedef itk::FFTPadImageFilter<QI::VolumeXD> TFFTPad; typedef itk::ComplexToComplexFFTImageFilter<QI::VolumeXD> TFFT; typedef itk::MultiplyImageFilter<QI::VolumeXD, QI::VolumeD, QI::VolumeXD> TMult; typedef itk::KernelSource<QI::VolumeD> TKernel; typedef itk::ExtractImageFilter<QI::VolumeXD, QI::VolumeXF> TUnpad; auto region = vols->GetLargestPossibleRegion(); const size_t nvols = region.GetSize()[3]; // Save for the loop if (filter_per_volume && nvols != kernels.size()) { std::cerr << "Number of volumes and kernels do not match for filter_per_volume option" << std::endl; return EXIT_FAILURE; } region.GetModifiableSize()[3] = 0; QI::VolumeXD::RegionType unpad_region; for (int i = 0; i < 3; i++) { unpad_region.GetModifiableSize()[i] = region.GetSize()[i]; } itk::FixedArray<unsigned int, 4> layout; layout[0] = layout[1] = layout[2] = 1; layout[3] = nvols; auto extract = TExtract::New(); auto zero_pad = TZeroPad::New(); auto fft_pad = TFFTPad::New(); auto forward = TFFT::New(); auto tkernel = TKernel::New(); auto mult = TMult::New(); // inverse is declared in the loop due to a weird bug auto unpadder = TUnpad::New(); auto tile = TTile::New(); extract->SetInput(vols); extract->SetDirectionCollapseToSubmatrix(); if (zero_padding > 0) { QI::VolumeXD::SizeType padding; padding.Fill(zero_padding); zero_pad->SetInput(extract->GetOutput()); zero_pad->SetPadLowerBound(padding); zero_pad->SetPadUpperBound(padding); zero_pad->SetConstant(0); fft_pad->SetInput(zero_pad->GetOutput()); } else { fft_pad->SetInput(extract->GetOutput()); } fft_pad->SetSizeGreatestPrimeFactor(5); // This is the largest the VNL FFT supports forward->SetInput(fft_pad->GetOutput()); if (!filter_per_volume) { tkernel->SetKernels(kernels); for (const auto &k : kernels) { if (verbose) std::cout << "Adding kernel: " << *k << std::endl; } } mult->SetInput1(forward->GetOutput()); mult->SetInput2(tkernel->GetOutput()); unpadder->SetDirectionCollapseToSubmatrix(); unpadder->SetExtractionRegion(unpad_region); tile->SetLayout(layout); for (int i = 0; i < nvols; i++) { region.GetModifiableIndex()[3] = i; if (verbose) cout << "Processing volume " << i << endl; extract->SetExtractionRegion(region); extract->Update(); fft_pad->Update(); if (i == 0) { // For first image we need to update the kernel tkernel->SetRegion(fft_pad->GetOutput()->GetLargestPossibleRegion()); tkernel->SetSpacing(fft_pad->GetOutput()->GetSpacing()); tkernel->SetOrigin(fft_pad->GetOutput()->GetOrigin()); tkernel->SetDirection(fft_pad->GetOutput()->GetDirection()); } if (filter_per_volume) { tkernel->SetKernel(kernels.at(i)); if (verbose) std::cout << "Setting kernel to: " << *kernels.at(i) << std::endl; } tkernel->Update(); mult->Update(); auto inverse = TFFT::New(); inverse->SetTransformDirection(TFFT::INVERSE); inverse->SetInput(mult->GetOutput()); unpadder->SetInput(inverse->GetOutput()); inverse->Update(); // Need a separate update to avoid region bug unpadder->Update(); QI::VolumeXF::Pointer v = unpadder->GetOutput(); tile->SetInput(i, v); v->DisconnectPipeline(); } if (verbose) cout << "Finished." << endl; tile->Update(); auto dir = vols->GetDirection(); auto spc = vols->GetSpacing(); vols = tile->GetOutput(); vols->SetDirection(dir); vols->SetSpacing(spc); vols->DisconnectPipeline(); std::string out_base = out_prefix.Get() + QI::Basename(in_path.Get()); const std::string out_path = out_base + "_filtered" + QI::OutExt(); if (complex_out) { if (verbose) cout << "Saving complex output file: " << out_path << endl; QI::WriteImage(vols, out_path); } else { if (verbose) cout << "Saving real output file: " << out_path << endl; QI::WriteMagnitudeImage(vols, out_path); } if (save_kernel) { const string kernel_path = out_base + "_kernel" + QI::OutExt(); if (verbose) cout << "Saving filter kernel to: " << kernel_path << endl; QI::WriteImage(tkernel->GetOutput(), kernel_path); } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>void MakeT0RecoParam(Int_t startRun = 0, Int_t endRun = AliCDBRunRange::Infinity(), AliRecoParam::EventSpecie_t defaultParam = AliRecoParam::kHighMult) { // Create T0 Calibration Object for Ideal calibration and // write it on CDB AliCDBManager *man = AliCDBManager::Instance(); man->SetDefaultStorage("local://$ALICE_ROOT/OCDB"); man->SetRun(startRun); TObjArray *recoParamArray = new TObjArray(); AliT0RecoParam* t0RecoParam; t0RecoParam = AliT0RecoParam::GetHighFluxParam(); t0RecoParam->SetEventSpecie(AliRecoParam::kHighMult); // t0RecoParam->Dump(); cout<<" t0RecoParam->GetEventSpecie "<< t0RecoParam->GetEventSpecie()<<endl; // t0RecoParam->Dump(); // t0RecoParam->PrintParameters(); recoParamArray->AddLast(t0RecoParam); t0RecoParam = AliT0RecoParam::GetLowFluxParam(); t0RecoParam->SetEventSpecie(AliRecoParam::kLowMult); cout<<" t0RecoParam->GetEventSpecie "<< t0RecoParam->GetEventSpecie()<<endl; // t0RecoParam->Dump(); // t0RecoParam->PrintParameters(); recoParamArray->AddLast(t0RecoParam); t0RecoParam = AliT0RecoParam::GetLaserTestParam(); t0RecoParam->SetEventSpecie(AliRecoParam::kCalib); // t0RecoParam->Dump(); cout<<" t0RecoParam->GetEventSpecie "<< t0RecoParam->GetEventSpecie()<<endl; // t0RecoParam->Dump(); // t0RecoParam->PrintParameters(); recoParamArray->AddLast(t0RecoParam); // Set the default Bool_t defaultIsSet = kFALSE; cout<<"recoParamArray->GetEntriesFast() "<<recoParamArray.GetEntriesFast()<<endl; TIter next(recoParamArray.MakeIterator()); while ( (param = static_cast<AliT0RecoParam*>(next())) ) { if (!param) continue; if (defaultParam == param->GetEventSpecie()) { cout<<" Specie "<<param->GetEventSpecie()<<endl; param->SetEventSpecie(param->GetEventSpecie()); param->SetAsDefault(); defaultIsSet = kTRUE; } param->Print("FULL"); } AliCDBMetaData *md= new AliCDBMetaData(); md->SetResponsible("Alla"); md->SetComment("Reconstruction parameters T0"); md->SetAliRootVersion(gSystem->Getenv("ARVERSION")); md->SetBeamPeriod(0); AliCDBId id("T0/Calib/RecoParam",startRun,endRun); man->GetDefaultStorage()->Put(recoParamArray,id, md); } <commit_msg>macros to produce new T0 Reco Param<commit_after>void MakeT0RecoParam(Int_t startRun = 0, Int_t endRun = AliCDBRunRange::Infinity(), AliRecoParam::EventSpecie_t defaultParam = AliRecoParam::kHighMult) { // Create T0 Calibration Object for Ideal calibration and // write it on CDB AliCDBManager *man = AliCDBManager::Instance(); man->SetDefaultStorage("local://$ALICE_ROOT/OCDB"); man->SetRun(startRun); TObjArray *recoParamArray = new TObjArray(); AliT0RecoParam* t0RecoParam; t0RecoParam = AliT0RecoParam::GetHighFluxParam(); t0RecoParam->SetEventSpecie(AliRecoParam::kHighMult); // t0RecoParam->Dump(); cout<<" t0RecoParam->GetEventSpecie "<< t0RecoParam->GetEventSpecie()<<endl; // t0RecoParam->Dump(); t0RecoParam->PrintParameters(); recoParamArray->AddLast(t0RecoParam); t0RecoParam = AliT0RecoParam::GetLowFluxParam(); t0RecoParam->SetEventSpecie(AliRecoParam::kLowMult); cout<<" t0RecoParam->GetEventSpecie "<< t0RecoParam->GetEventSpecie()<<endl; t0RecoParam->SetLow(10,-1000); t0RecoParam->PrintParameters(); recoParamArray->AddLast(t0RecoParam); t0RecoParam = AliT0RecoParam::GetLaserTestParam(); t0RecoParam->SetEventSpecie(AliRecoParam::kCalib); // t0RecoParam->Dump(); cout<<" t0RecoParam->GetEventSpecie "<< t0RecoParam->GetEventSpecie()<<endl; for (Int_t i=98; i<149; i++) { t0RecoParam->SetLow(i,-1000); t0RecoParam->SetHigh(i,1000); } // t0RecoParam->Dump(); t0RecoParam->SetRefPoint(1); t0RecoParam->PrintParameters(); recoParamArray->AddLast(t0RecoParam); // Set the default Bool_t defaultIsSet = kFALSE; // cout<<"recoParamArray->GetEntriesFast() "<<recoParamArray.GetEntriesFast()<<endl; TIter next(recoParamArray->MakeIterator()); while ( (param = static_cast<AliT0RecoParam*>(next())) ) { if (!param) continue; if (defaultParam == param->GetEventSpecie()) { cout<<" Specie "<<param->GetEventSpecie()<<endl; param->SetEventSpecie(param->GetEventSpecie()); param->SetAsDefault(); defaultIsSet = kTRUE; } param->Print("FULL"); } AliCDBMetaData *md= new AliCDBMetaData(); md->SetResponsible("Alla"); md->SetComment("Reconstruction parameters T0"); md->SetAliRootVersion(gSystem->Getenv("ARVERSION")); md->SetBeamPeriod(0); AliCDBId id("T0/Calib/RecoParam",startRun,endRun); man->GetDefaultStorage()->Put(recoParamArray,id, md); } <|endoftext|>
<commit_before>#include <map> #include "Tests.h" void veroRestApiTest() { // rest authenticate bool ret = restAuthenticate(KServerAddr, KPort, KUserName, KPassword); if (!ret) { report(); } // rest projects std::map<string, string> projectMap; restListProjects(KServerAddr, KPort, KUserName, KPassword, projectMap); for (std::map<string, string>::iterator i = projectMap.begin(); i != projectMap.end(); i++) { cout << "Project = " << (*i).first << endl; } // rest meta std::unique_ptr<MetadataResponse> metaResponse = restGetMeta(KServerAddr, KPort, KUserName, KPassword, KDefaultProject); } void veroMakeUriTest() { char project[100]; strcpy(project, "yulins_project"); makeSlug(project); cout << "\n"; cout << "Project make slug = " << project << "\n"; std::wstringstream metaUri = makeMetaUri(project); std::wstringstream queryUri = makeQueryUri(project); std::unique_ptr<char[]> metaUriPtr = wchar2char(metaUri.str().c_str()); std::unique_ptr<char[]> queryUriPtr = wchar2char(queryUri.str().c_str()); cout << "Meta uri = " << metaUriPtr.get() << "\n"; cout << "Query uri = " << queryUriPtr.get() << "\n"; } <commit_msg>Test rest query.<commit_after>#include <map> #include "Tests.h" void veroRestApiTest() { // rest authenticate bool ret = restAuthenticate(KServerAddr, KPort, KUserName, KPassword); if (!ret) { report(); } // rest projects std::map<string, string> projectMap; restListProjects(KServerAddr, KPort, KUserName, KPassword, projectMap); for (std::map<string, string>::iterator i = projectMap.begin(); i != projectMap.end(); i++) { cout << "Project = " << (*i).first << endl; } // rest meta std::unique_ptr<MetadataResponse> metaResponse = restGetMeta(KServerAddr, KPort, KUserName, KPassword, KDefaultProject); // rest query { std::unique_ptr<SQLResponse> y = restQuery(L"select Year", KServerAddr, KPort, KUserName, KPassword, KDefaultProject); if ((int)y->results.size() != 1) { report(); } } } void veroMakeUriTest() { char project[100]; strcpy(project, "yulins_project"); makeSlug(project); cout << "\n"; cout << "Project make slug = " << project << "\n"; std::wstringstream metaUri = makeMetaUri(project); std::wstringstream queryUri = makeQueryUri(project); std::unique_ptr<char[]> metaUriPtr = wchar2char(metaUri.str().c_str()); std::unique_ptr<char[]> queryUriPtr = wchar2char(queryUri.str().c_str()); cout << "Meta uri = " << metaUriPtr.get() << "\n"; cout << "Query uri = " << queryUriPtr.get() << "\n"; } <|endoftext|>
<commit_before>///////////////////////////////////////////////////////////////////////// // $Id$ ///////////////////////////////////////////////////////////////////////// // // Copyright (C) 2002 MandrakeSoft S.A. // // MandrakeSoft S.A. // 43, rue d'Aboukir // 75002 Paris - France // http://www.linux-mandrake.com/ // http://www.mandrakesoft.com/ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // External circuit for MSDOS compatible FPU exceptions // // Define BX_PLUGGABLE in files that can be compiled into plugins. For // platforms that require a special tag on exported symbols, BX_PLUGGABLE // is used to know when we are exporting symbols and when we are importing. #define BX_PLUGGABLE #include "bochs.h" #define LOG_THIS theExternalFpuIrq-> bx_extfpuirq_c *theExternalFpuIrq = NULL; int libextfpuirq_LTX_plugin_init(plugin_t *plugin, plugintype_t type, int argc, char *argv[]) { theExternalFpuIrq = new bx_extfpuirq_c (); bx_devices.pluginPci2IsaBridge = theExternalFpuIrq; BX_REGISTER_DEVICE_DEVMODEL(plugin, type, theExternalFpuIrq, BX_PLUGIN_EXTFPUIRQ); return(0); // Success } void libextfpuirq_LTX_plugin_fini(void) { } bx_extfpuirq_c::bx_extfpuirq_c(void) { put("EFIRQ"); settype(EXTFPUIRQLOG); } bx_extfpuirq_c::~bx_extfpuirq_c(void) { // nothing for now BX_DEBUG(("Exit.")); } void bx_extfpuirq_c::init(void) { // called once when bochs initializes DEV_register_iowrite_handler(this, write_handler, 0x00F0, "External FPU IRQ", 7); DEV_register_irq(13, "External FPU IRQ"); } void bx_extfpuirq_c::reset(unsigned type) { // We should handle IGNNE here DEV_pic_lower_irq(13); } // static IO port write callback handler // redirects to non-static class handler to avoid virtual functions void bx_extfpuirq_c::write_handler(void *this_ptr, Bit32u address, Bit32u value, unsigned io_len) { #if !BX_USE_EFI_SMF bx_extfpuirq_c *class_ptr = (bx_extfpuirq_c *) this_ptr; class_ptr->write(address, value, io_len); } void bx_extfpuirq_c::write(Bit32u address, Bit32u value, unsigned io_len) { #else UNUSED(this_ptr); #endif // !BX_USE_EFI_SMF // We should handle IGNNE here DEV_pic_lower_irq(13); } <commit_msg>- device plugin name fixed<commit_after>///////////////////////////////////////////////////////////////////////// // $Id$ ///////////////////////////////////////////////////////////////////////// // // Copyright (C) 2002 MandrakeSoft S.A. // // MandrakeSoft S.A. // 43, rue d'Aboukir // 75002 Paris - France // http://www.linux-mandrake.com/ // http://www.mandrakesoft.com/ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // External circuit for MSDOS compatible FPU exceptions // // Define BX_PLUGGABLE in files that can be compiled into plugins. For // platforms that require a special tag on exported symbols, BX_PLUGGABLE // is used to know when we are exporting symbols and when we are importing. #define BX_PLUGGABLE #include "bochs.h" #define LOG_THIS theExternalFpuIrq-> bx_extfpuirq_c *theExternalFpuIrq = NULL; int libextfpuirq_LTX_plugin_init(plugin_t *plugin, plugintype_t type, int argc, char *argv[]) { theExternalFpuIrq = new bx_extfpuirq_c (); bx_devices.pluginExtFpuIrq = theExternalFpuIrq; BX_REGISTER_DEVICE_DEVMODEL(plugin, type, theExternalFpuIrq, BX_PLUGIN_EXTFPUIRQ); return(0); // Success } void libextfpuirq_LTX_plugin_fini(void) { } bx_extfpuirq_c::bx_extfpuirq_c(void) { put("EFIRQ"); settype(EXTFPUIRQLOG); } bx_extfpuirq_c::~bx_extfpuirq_c(void) { // nothing for now BX_DEBUG(("Exit.")); } void bx_extfpuirq_c::init(void) { // called once when bochs initializes DEV_register_iowrite_handler(this, write_handler, 0x00F0, "External FPU IRQ", 7); DEV_register_irq(13, "External FPU IRQ"); } void bx_extfpuirq_c::reset(unsigned type) { // We should handle IGNNE here DEV_pic_lower_irq(13); } // static IO port write callback handler // redirects to non-static class handler to avoid virtual functions void bx_extfpuirq_c::write_handler(void *this_ptr, Bit32u address, Bit32u value, unsigned io_len) { #if !BX_USE_EFI_SMF bx_extfpuirq_c *class_ptr = (bx_extfpuirq_c *) this_ptr; class_ptr->write(address, value, io_len); } void bx_extfpuirq_c::write(Bit32u address, Bit32u value, unsigned io_len) { #else UNUSED(this_ptr); #endif // !BX_USE_EFI_SMF // We should handle IGNNE here DEV_pic_lower_irq(13); } <|endoftext|>
<commit_before><commit_msg>12455 - Bars<commit_after><|endoftext|>
<commit_before>#include "crypto.h" #include <stdio.h> #include <stdlib.h> #include <cstdlib> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <iostream> #include <fstream> #include <string> #include <cstring> #include "sha256.h" const int PACKET_DATA_LENGTH = 32; //bytes const int PACKET_CHECKSUM_LENGTH = 32; const int PACKET_LENGTH = PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH; char* OTP(unsigned long long* index, const unsigned long long amount); char* xorCharArray(const char* first, const char* second, unsigned long long length); unsigned long long unsignedLongLongRand(); char* longToCharArray(unsigned long long num, int size); unsigned long long charArrayToLong(const char* data, int size); bool charArrayEquals(const char* data1, const char* data2, int size); char* concat(const char* left, const char* right, int sizel, int sizer); char* sha_256(char* buf); // send command ssize_t cwrite(int fd, const void *buf, size_t len) { //long indexOfPad = random integer from 0 to size of OTP in bytes unsigned long long* indexOfPad = &unsignedLongLongRand(); //char* nonce = longToCharArray(&indexOfPad, PACKET_LENGTH); char* nonce = longToCharArray(*indexOfPad, PACKET_LENGTH); //send nonce to reciever int n; n = write(fd, nonce, PACKET_LENGTH); if (n < 0) { return -1; } //1 //char* myChecksum = xor(OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH), OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH)); char* myChecksum = xorCharArray(OTP(&indexOfPad,PACKET_LENGTH), OTP(&indexOfPad, PACKET_LENGTH)); //2 //byte* response = response from receiver char buffer[PACKET_LENGTH]; n = read(fd, buffer, PACKET_LENGTH); if (n < 0) { //error n = write(fd, "NO", PACKET_LENGTH); if (n < 0) { return -1; } return -1; } else if (n == 0) { //error - no message n = write(fd, "NO", PACKET_LENGTH); if (n < 0) { return -1; } return -1; } else if(!charArrayEquals(buffer, myChecksum, PACKET_LENGTH)) { //myChecksum != response return -1; } //send ok to reciever n = write(fd, "OK", PACKET_LENGTH); if (n < 0) { return -1; } //2.1 //2.2 //for(int bufferIndex = 0; bufferIndex < len; bufferIndex += PACKET_DATA_LENGTH) { for(int bufferIndex = 0; bufferIndex < len; bufferIndex += PACKET_DATA_LENGTH) { //char* toSend = buf[bufferIndex]; char* toSend = buf[bufferIndex]; //char* key = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH); char* key = OTP(indexOfPad, PACKET_LENGTH); //char* mac = sha-256(concat(toSend, key)); char* mac = sha_256(concat(toSend, key, PACKET_DATA_LENGTH, PACKET_CHECKSUM_LENGTH)); //char* message = concat(toSend, mac); char* message = concat(toSend, mac, PACKET_DATA_LENGTH, PACKET_CHECKSUM_LENGTH); //char* pad = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH); char* pad = OTP(indexOfPad, PACKET_LENGTH); //send xor(message, pad) to reciever n = write(fd, xorCharArray(message, pad), PACKET_LENGTH); if (n < 0) { delete[] key; return -1; } delete[] key; //3 } } // recv command ssize_t cread(int fd, void *buf, size_t len) { //1 //wait for nonce from sender char buffer[PACKET_LENGTH]; int n; n = read(fd, buffer, PACKET_LENGTH); if (n < 0) { //error return -1; } else if (n == 0) { //error - no message return -1; } //long indexOfPad; //indexOfPad = charArrayToLong(message recieved from sender); unsigned long long indexOfPad = charArrayToLong(buffer, PACKET_LENGTH); //byte* message = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH); char* message = OTP(&indexOfPad, PACKET_LENGTH); //byte* pad = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH); char* pad = OTP(&indexOfPad, PACKET_LENGTH); //byte* reply = xor(message, pad); char* reply = xorCharArray(message, pad, PACKET_LENGTH); //send reply to sender n = write(fd, reply, PACKET_LENGTH); if (n < 0) { return -1; } //2 //2.1 //recieve ok, if not retry, abort, ignore? n = read(fd, buffer, PACKET_LENGTH); if (n < 0) { //error return -1; } else if (n == 0) { //error - no message return -1; } else if(std::strcmp(buffer, "OK") != 0) { //error - not ok return -1; } //2.2 //int amount_recv = 0; int amount_recv = 0; //while(more to recieve or amount_recv + PACKET_DATA_LENGTH < len) { while(amount_recv + PACKET_DATA_LENGTH < len) { //3 //byte data[PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH] = message recieved from sender char data[PACKET_LENGTH]; amount_recv += read(fd, data, PACKET_LENGTH); //byte* key = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH); char* key = OTP(&indexOfPad, PACKET_LENGTH); //pad = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH); char* pad = OTP(&indexOfPad, PACKET_LENGTH); //byte* messsage = xor(data, pad); char* message = xorCharArray(data, pad, PACKET_LENGTH); //byte* checksum = data + PACKET_DATA_LENGTH; checksum is last part after the data char* checksum = message + PACKET_DATA_LENGTH; //byte* mac = sha-256(concat(messsage, key)); recompute mac //std::string msgStr(message); //std::string keyStr(key); char* mac = sha_256(concat(message, key, PACKET_DATA_LENGTH, PACKET_CHECKSUM_LENGTH)); if(!charArrayEquals(checksum, mac, PACKET_LENGTH)) { //checksum != mac delete[] mac; return -1; } //copy message into buffer for(int i = 0; i < PACKET_DATA_LENGTH; i++) { buf[i] = message[i]; } buf += PACKET_DATA_LENGTH; delete[] mac; } return amount_recv; } char* OTP(unsigned long long* index, const unsigned long long amount) { std::ifstream pad; pad.open("otp.key"); pad.seekg(*index); char* result = new char[amount]; pad.read(result, amount); pad.close(); *index += amount; return result; //byte pad[amount]; allocate amount bytes to return //seek to index in OTP //for(long i = 0; i < amount; i++) //pad[i] = readByte(); read in each byte from the file //*index += amount; increment index so we don't use the same pad twice //return pad; } char* xorCharArray(const char* first, const char* second, unsigned long long length) { //byte result[length]; char* result = new char[length]; //for(long i = 0; i < length; i++) { for(unsigned long long i = 0; i < length; i++) { result[i] = first[i] ^ second[i]; } return result; } unsigned long long unsignedLongLongRand() { unsigned long long rand1 = abs(rand()); unsigned long long rand2 = abs(rand()); rand1 <<= (sizeof(int)*8); unsigned long long randULL = (rand1 | rand2); return randULL; } char* longToCharArray(unsigned long long num, int size) { return reinterpret_cast<char*>(num); } unsigned long long charArrayToLong(const char* data, int size){ return reinterpret_cast<unsigned long long>(data); } bool charArrayEquals(const char* data1, const char* data2, int size) { for(int i = 0; i < size; i++) { if(data1[i] != data2[i]) return false; } return true; } char* concat(const char* left, const char* right, int sizel, int sizer) { char* result = new char[sizel + sizer]; for(int i = 0; i < sizel; i++) { result[i] = left[i]; } for(int i = 0; i < sizer; i++) { result[sizel + i] = right[i]; } return result; //std::string msgStr(left); //std::string keyStr(right); //return &(left + right)[0]; } char* sha_256(char* buf) { return &sha256(buf)[0]; } <commit_msg>fixed pointer<commit_after>#include "crypto.h" #include <stdio.h> #include <stdlib.h> #include <cstdlib> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <iostream> #include <fstream> #include <string> #include <cstring> #include "sha256.h" const int PACKET_DATA_LENGTH = 32; //bytes const int PACKET_CHECKSUM_LENGTH = 32; const int PACKET_LENGTH = PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH; char* OTP(unsigned long long* index, const unsigned long long amount); char* xorCharArray(const char* first, const char* second, unsigned long long length); unsigned long long unsignedLongLongRand(); char* longToCharArray(unsigned long long num, int size); unsigned long long charArrayToLong(const char* data, int size); bool charArrayEquals(const char* data1, const char* data2, int size); char* concat(const char* left, const char* right, int sizel, int sizer); char* sha_256(char* buf); // send command ssize_t cwrite(int fd, const void *buf, size_t len) { //long indexOfPad = random integer from 0 to size of OTP in bytes unsigned long long* indexOfPad = new unsigned long long; *indexOfPad = unsignedLongLongRand(); //char* nonce = longToCharArray(&indexOfPad, PACKET_LENGTH); char* nonce = longToCharArray(*indexOfPad, PACKET_LENGTH); //send nonce to reciever int n; n = write(fd, nonce, PACKET_LENGTH); if (n < 0) { return -1; } //1 //char* myChecksum = xor(OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH), OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH)); char* myChecksum = xorCharArray(OTP(&indexOfPad,PACKET_LENGTH), OTP(&indexOfPad, PACKET_LENGTH)); //2 //byte* response = response from receiver char buffer[PACKET_LENGTH]; n = read(fd, buffer, PACKET_LENGTH); if (n < 0) { //error n = write(fd, "NO", PACKET_LENGTH); if (n < 0) { return -1; } return -1; } else if (n == 0) { //error - no message n = write(fd, "NO", PACKET_LENGTH); if (n < 0) { return -1; } return -1; } else if(!charArrayEquals(buffer, myChecksum, PACKET_LENGTH)) { //myChecksum != response return -1; } //send ok to reciever n = write(fd, "OK", PACKET_LENGTH); if (n < 0) { return -1; } //2.1 //2.2 //for(int bufferIndex = 0; bufferIndex < len; bufferIndex += PACKET_DATA_LENGTH) { for(int bufferIndex = 0; bufferIndex < len; bufferIndex += PACKET_DATA_LENGTH) { //char* toSend = buf[bufferIndex]; char* toSend = buf[bufferIndex]; //char* key = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH); char* key = OTP(indexOfPad, PACKET_LENGTH); //char* mac = sha-256(concat(toSend, key)); char* mac = sha_256(concat(toSend, key, PACKET_DATA_LENGTH, PACKET_CHECKSUM_LENGTH)); //char* message = concat(toSend, mac); char* message = concat(toSend, mac, PACKET_DATA_LENGTH, PACKET_CHECKSUM_LENGTH); //char* pad = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH); char* pad = OTP(indexOfPad, PACKET_LENGTH); //send xor(message, pad) to reciever n = write(fd, xorCharArray(message, pad), PACKET_LENGTH); if (n < 0) { delete[] key; return -1; } delete[] key; //3 } } // recv command ssize_t cread(int fd, void *buf, size_t len) { //1 //wait for nonce from sender char buffer[PACKET_LENGTH]; int n; n = read(fd, buffer, PACKET_LENGTH); if (n < 0) { //error return -1; } else if (n == 0) { //error - no message return -1; } //long indexOfPad; //indexOfPad = charArrayToLong(message recieved from sender); unsigned long long indexOfPad = charArrayToLong(buffer, PACKET_LENGTH); //byte* message = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH); char* message = OTP(&indexOfPad, PACKET_LENGTH); //byte* pad = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH); char* pad = OTP(&indexOfPad, PACKET_LENGTH); //byte* reply = xor(message, pad); char* reply = xorCharArray(message, pad, PACKET_LENGTH); //send reply to sender n = write(fd, reply, PACKET_LENGTH); if (n < 0) { return -1; } //2 //2.1 //recieve ok, if not retry, abort, ignore? n = read(fd, buffer, PACKET_LENGTH); if (n < 0) { //error return -1; } else if (n == 0) { //error - no message return -1; } else if(std::strcmp(buffer, "OK") != 0) { //error - not ok return -1; } //2.2 //int amount_recv = 0; int amount_recv = 0; //while(more to recieve or amount_recv + PACKET_DATA_LENGTH < len) { while(amount_recv + PACKET_DATA_LENGTH < len) { //3 //byte data[PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH] = message recieved from sender char data[PACKET_LENGTH]; amount_recv += read(fd, data, PACKET_LENGTH); //byte* key = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH); char* key = OTP(&indexOfPad, PACKET_LENGTH); //pad = OTP(&indexOfPad, PACKET_DATA_LENGTH + PACKET_CHECKSUM_LENGTH); char* pad = OTP(&indexOfPad, PACKET_LENGTH); //byte* messsage = xor(data, pad); char* message = xorCharArray(data, pad, PACKET_LENGTH); //byte* checksum = data + PACKET_DATA_LENGTH; checksum is last part after the data char* checksum = message + PACKET_DATA_LENGTH; //byte* mac = sha-256(concat(messsage, key)); recompute mac //std::string msgStr(message); //std::string keyStr(key); char* mac = sha_256(concat(message, key, PACKET_DATA_LENGTH, PACKET_CHECKSUM_LENGTH)); if(!charArrayEquals(checksum, mac, PACKET_LENGTH)) { //checksum != mac delete[] mac; return -1; } //copy message into buffer for(int i = 0; i < PACKET_DATA_LENGTH; i++) { buf[i] = message[i]; } buf += PACKET_DATA_LENGTH; delete[] mac; } return amount_recv; } char* OTP(unsigned long long* index, const unsigned long long amount) { std::ifstream pad; pad.open("otp.key"); pad.seekg(*index); char* result = new char[amount]; pad.read(result, amount); pad.close(); *index += amount; return result; //byte pad[amount]; allocate amount bytes to return //seek to index in OTP //for(long i = 0; i < amount; i++) //pad[i] = readByte(); read in each byte from the file //*index += amount; increment index so we don't use the same pad twice //return pad; } char* xorCharArray(const char* first, const char* second, unsigned long long length) { //byte result[length]; char* result = new char[length]; //for(long i = 0; i < length; i++) { for(unsigned long long i = 0; i < length; i++) { result[i] = first[i] ^ second[i]; } return result; } unsigned long long unsignedLongLongRand() { unsigned long long rand1 = abs(rand()); unsigned long long rand2 = abs(rand()); rand1 <<= (sizeof(int)*8); unsigned long long randULL = (rand1 | rand2); return randULL; } char* longToCharArray(unsigned long long num, int size) { return reinterpret_cast<char*>(num); } unsigned long long charArrayToLong(const char* data, int size){ return reinterpret_cast<unsigned long long>(data); } bool charArrayEquals(const char* data1, const char* data2, int size) { for(int i = 0; i < size; i++) { if(data1[i] != data2[i]) return false; } return true; } char* concat(const char* left, const char* right, int sizel, int sizer) { char* result = new char[sizel + sizer]; for(int i = 0; i < sizel; i++) { result[i] = left[i]; } for(int i = 0; i < sizer; i++) { result[sizel + i] = right[i]; } return result; //std::string msgStr(left); //std::string keyStr(right); //return &(left + right)[0]; } char* sha_256(char* buf) { return &sha256(buf)[0]; } <|endoftext|>
<commit_before>/* * article.cpp * * Copyright (c) 2001, 2002, 2003, 2004 Frerich Raabe <raabe@kde.org> * * 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. For licensing and distribution details, check the * accompanying file 'COPYING'. */ #include "article.h" #include "tools_p.h" #include <kdebug.h> #include <krfcdate.h> #include <kurl.h> #include <kurllabel.h> #include <kmdcodec.h> #include <qdatetime.h> #include <qdom.h> using namespace RSS; KMD5 md5Machine; struct Article::Private : public Shared { QString title; KURL link; QString description; QDateTime pubDate; QString guid; bool guidIsPermaLink; MetaInfoMap meta; KURL commentsLink; int numComments; }; Article::Article() : d(new Private) { } Article::Article(const Article &other) : d(0) { *this = other; } Article::Article(const QDomNode &node, Format format) : d(new Private) { QString elemText; d->numComments=0; if (!(elemText = extractNode(node, QString::fromLatin1("title"))).isNull()) d->title = elemText; if (format==AtomFeed) { QDomNode n; for (n = node.firstChild(); !n.isNull(); n = n.nextSibling()) { const QDomElement e = n.toElement(); if ( (e.tagName()==QString::fromLatin1("link")) && (e.attribute(QString::fromLatin1("rel"))==QString::fromLatin1("alternate"))) { d->link=n.toElement().attribute(QString::fromLatin1("href")); break; } } } else { if (!(elemText = extractNode(node, QString::fromLatin1("link"))).isNull()) d->link = elemText; } // prefer content/content:encoded over summary/description for feeds that provide it QString tagName=(format==AtomFeed)? QString::fromLatin1("content"): QString::fromLatin1("content:encoded"); if (!(elemText = extractNode(node, tagName, false)).isNull()) d->description = elemText; if (d->description.isEmpty()) { if (!(elemText = extractNode(node, QString::fromLatin1("body"), false)).isNull()) d->description = elemText; if (d->description.isEmpty()) // 3rd try: see http://www.intertwingly.net/blog/1299.html { if (!(elemText = extractNode(node, QString::fromLatin1((format==AtomFeed)? "summary" : "description"), false)).isNull()) d->description = elemText; } } if (!(elemText = extractNode(node, QString::fromLatin1((format==AtomFeed)? "created": "pubDate"))).isNull()) { time_t _time; if (format==AtomFeed) _time = parseISO8601Date(elemText); else _time = KRFCDate::parseDate(elemText); // 0 means invalid, not epoch (it returns epoch+1 when it parsed epoch, see the KRFCDate::parseDate() docs) kdDebug() << "parsed: " << _time << endl; if (_time != 0) d->pubDate.setTime_t(_time); } if (!(elemText = extractNode(node, QString::fromLatin1("dc:date"))).isNull()) { time_t _time = parseISO8601Date(elemText); // 0 means invalid, not epoch (it returns epoch+1 when it parsed epoch, see the KRFCDate::parseDate() docs) kdDebug() << "parsed: " << _time << endl; if (_time != 0) d->pubDate.setTime_t(_time); } if (!(elemText = extractNode(node, QString::fromLatin1("wfw:comment"))).isNull()) { d->commentsLink = elemText; } if (!(elemText = extractNode(node, QString::fromLatin1("slash:comments"))).isNull()) { d->numComments = elemText.toInt(); } tagName=(format==AtomFeed)? QString::fromLatin1("id"): QString::fromLatin1("guid"); QDomNode n = node.namedItem(tagName); if (!n.isNull()) { d->guidIsPermaLink = (format==AtomFeed)? false : true; if (n.toElement().attribute(QString::fromLatin1("isPermaLink"), "true") == "false") d->guidIsPermaLink = false; if (!(elemText = extractNode(node, tagName)).isNull()) d->guid = elemText; } if(d->guid.isEmpty()) { d->guidIsPermaLink = false; md5Machine.reset(); QDomNode n(node); md5Machine.update(d->title.utf8()); md5Machine.update(d->description.utf8()); d->guid = QString(md5Machine.hexDigest().data()); } for (QDomNode i = node.firstChild(); !i.isNull(); i = i.nextSibling()) { if (i.isElement() && i.toElement().tagName() == QString::fromLatin1("metaInfo:meta")) { QString type = i.toElement().attribute(QString::fromLatin1("type")); d->meta[type] = i.toElement().text(); } } } Article::~Article() { if (d->deref()) delete d; } QString Article::title() const { return d->title; } const KURL &Article::link() const { return d->link; } QString Article::description() const { return d->description; } QString Article::guid() const { return d->guid; } bool Article::guidIsPermaLink() const { return d->guidIsPermaLink; } const QDateTime &Article::pubDate() const { return d->pubDate; } const KURL &Article::commentsLink() const { return d->commentsLink; } int Article::comments() const { return d->numComments; } QString Article::meta(const QString &key) const { return d->meta[key]; } KURLLabel *Article::widget(QWidget *parent, const char *name) const { KURLLabel *label = new KURLLabel(d->link.url(), d->title, parent, name); label->setUseTips(true); if (!d->description.isNull()) label->setTipText(d->description); return label; } Article &Article::operator=(const Article &other) { if (this != &other) { other.d->ref(); if (d && d->deref()) delete d; d = other.d; } return *this; } bool Article::operator==(const Article &other) const { return d->guid == other.guid(); } // vim:noet:ts=4 <commit_msg>remove kdebug() calls<commit_after>/* * article.cpp * * Copyright (c) 2001, 2002, 2003, 2004 Frerich Raabe <raabe@kde.org> * * 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. For licensing and distribution details, check the * accompanying file 'COPYING'. */ #include "article.h" #include "tools_p.h" #include <kdebug.h> #include <krfcdate.h> #include <kurl.h> #include <kurllabel.h> #include <kmdcodec.h> #include <qdatetime.h> #include <qdom.h> using namespace RSS; KMD5 md5Machine; struct Article::Private : public Shared { QString title; KURL link; QString description; QDateTime pubDate; QString guid; bool guidIsPermaLink; MetaInfoMap meta; KURL commentsLink; int numComments; }; Article::Article() : d(new Private) { } Article::Article(const Article &other) : d(0) { *this = other; } Article::Article(const QDomNode &node, Format format) : d(new Private) { QString elemText; d->numComments=0; if (!(elemText = extractNode(node, QString::fromLatin1("title"))).isNull()) d->title = elemText; if (format==AtomFeed) { QDomNode n; for (n = node.firstChild(); !n.isNull(); n = n.nextSibling()) { const QDomElement e = n.toElement(); if ( (e.tagName()==QString::fromLatin1("link")) && (e.attribute(QString::fromLatin1("rel"))==QString::fromLatin1("alternate"))) { d->link=n.toElement().attribute(QString::fromLatin1("href")); break; } } } else { if (!(elemText = extractNode(node, QString::fromLatin1("link"))).isNull()) d->link = elemText; } // prefer content/content:encoded over summary/description for feeds that provide it QString tagName=(format==AtomFeed)? QString::fromLatin1("content"): QString::fromLatin1("content:encoded"); if (!(elemText = extractNode(node, tagName, false)).isNull()) d->description = elemText; if (d->description.isEmpty()) { if (!(elemText = extractNode(node, QString::fromLatin1("body"), false)).isNull()) d->description = elemText; if (d->description.isEmpty()) // 3rd try: see http://www.intertwingly.net/blog/1299.html { if (!(elemText = extractNode(node, QString::fromLatin1((format==AtomFeed)? "summary" : "description"), false)).isNull()) d->description = elemText; } } if (!(elemText = extractNode(node, QString::fromLatin1((format==AtomFeed)? "created": "pubDate"))).isNull()) { time_t _time; if (format==AtomFeed) _time = parseISO8601Date(elemText); else _time = KRFCDate::parseDate(elemText); // 0 means invalid, not epoch (it returns epoch+1 when it parsed epoch, see the KRFCDate::parseDate() docs) if (_time != 0) d->pubDate.setTime_t(_time); } if (!(elemText = extractNode(node, QString::fromLatin1("dc:date"))).isNull()) { time_t _time = parseISO8601Date(elemText); // 0 means invalid, not epoch (it returns epoch+1 when it parsed epoch, see the KRFCDate::parseDate() docs) if (_time != 0) d->pubDate.setTime_t(_time); } if (!(elemText = extractNode(node, QString::fromLatin1("wfw:comment"))).isNull()) { d->commentsLink = elemText; } if (!(elemText = extractNode(node, QString::fromLatin1("slash:comments"))).isNull()) { d->numComments = elemText.toInt(); } tagName=(format==AtomFeed)? QString::fromLatin1("id"): QString::fromLatin1("guid"); QDomNode n = node.namedItem(tagName); if (!n.isNull()) { d->guidIsPermaLink = (format==AtomFeed)? false : true; if (n.toElement().attribute(QString::fromLatin1("isPermaLink"), "true") == "false") d->guidIsPermaLink = false; if (!(elemText = extractNode(node, tagName)).isNull()) d->guid = elemText; } if(d->guid.isEmpty()) { d->guidIsPermaLink = false; md5Machine.reset(); QDomNode n(node); md5Machine.update(d->title.utf8()); md5Machine.update(d->description.utf8()); d->guid = QString(md5Machine.hexDigest().data()); } for (QDomNode i = node.firstChild(); !i.isNull(); i = i.nextSibling()) { if (i.isElement() && i.toElement().tagName() == QString::fromLatin1("metaInfo:meta")) { QString type = i.toElement().attribute(QString::fromLatin1("type")); d->meta[type] = i.toElement().text(); } } } Article::~Article() { if (d->deref()) delete d; } QString Article::title() const { return d->title; } const KURL &Article::link() const { return d->link; } QString Article::description() const { return d->description; } QString Article::guid() const { return d->guid; } bool Article::guidIsPermaLink() const { return d->guidIsPermaLink; } const QDateTime &Article::pubDate() const { return d->pubDate; } const KURL &Article::commentsLink() const { return d->commentsLink; } int Article::comments() const { return d->numComments; } QString Article::meta(const QString &key) const { return d->meta[key]; } KURLLabel *Article::widget(QWidget *parent, const char *name) const { KURLLabel *label = new KURLLabel(d->link.url(), d->title, parent, name); label->setUseTips(true); if (!d->description.isNull()) label->setTipText(d->description); return label; } Article &Article::operator=(const Article &other) { if (this != &other) { other.d->ref(); if (d && d->deref()) delete d; d = other.d; } return *this; } bool Article::operator==(const Article &other) const { return d->guid == other.guid(); } // vim:noet:ts=4 <|endoftext|>
<commit_before>/* Copyright (c) 2015 In Cheol, Kang * * 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 "eznetpp.h" #include "net/tcp/tcp_acceptor.h" #include "net/tcp/tcp_socket.h" #include "sys/io_manager.h" eznetpp::sys::io_manager g_io_mgr(4); void sig_handler(int signum) { printf("hello signal handler\n"); g_io_mgr.stop(); } class tcp_echosvr_session : public eznetpp::event::tcp_socket_event_handler { public: tcp_echosvr_session(eznetpp::net::tcp::tcp_socket* sock) { _socket = sock; } virtual ~tcp_echosvr_session() = default; public: // override void on_recv(const std::string& msg, int len) { printf("received %d bytes\n", len); _socket->send_bytes(msg); } void on_send(unsigned int len) { printf("sent %d bytes\n", len); } void on_close(int err_no) { printf("closed the session(%d)\n", err_no); } // do not need void on_connect(int err_no) {}; private: eznetpp::net::tcp::tcp_socket* _socket; }; class tcp_echo_server : public eznetpp::event::tcp_acceptor_event_handler { public: tcp_echo_server(eznetpp::sys::io_manager* io_mgr) { _io_mgr = io_mgr; } virtual ~tcp_echo_server() = default; int open(int port, int backlog) { int ret = _acceptor.open(port, backlog); if (ret) { printf("%s\n", eznetpp::errcode::errno_to_str(ret).c_str()); return -1; } _io_mgr->register_socket_event_handler(&_acceptor, this); return 0; } // override void on_accept(eznetpp::net::tcp::tcp_socket* sock, int err_no) { _io_mgr->register_socket_event_handler(sock, new tcp_echosvr_session(sock)); } void on_close(int err_no) { printf("closed the acceptor(%d)\n", err_no); } private: eznetpp::sys::io_manager* _io_mgr = nullptr; eznetpp::net::tcp::tcp_acceptor _acceptor; }; int main(void) { if (signal(SIGINT, sig_handler) == SIG_ERR) printf("can't catch SIGINT\n"); signal(SIGABRT, sig_handler); signal(SIGTERM, sig_handler); signal(SIGKILL, sig_handler); g_io_mgr.init(); tcp_echo_server server(&g_io_mgr); server.open(56789, 5); g_io_mgr.loop(); return 0; } <commit_msg>delete some debug logs<commit_after>/* Copyright (c) 2015 In Cheol, Kang * * 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 "eznetpp.h" #include "net/tcp/tcp_acceptor.h" #include "net/tcp/tcp_socket.h" #include "sys/io_manager.h" eznetpp::sys::io_manager g_io_mgr(4); void sig_handler(int signum) { g_io_mgr.stop(); } class tcp_echosvr_session : public eznetpp::event::tcp_socket_event_handler { public: tcp_echosvr_session(eznetpp::net::tcp::tcp_socket* sock) { _socket = sock; } virtual ~tcp_echosvr_session() = default; public: // override void on_recv(const std::string& msg, int len) { printf("received %d bytes\n", len); _socket->send_bytes(msg); } void on_send(unsigned int len) { printf("sent %d bytes\n", len); } void on_close(int err_no) { printf("closed the session(%d)\n", err_no); } // do not need void on_connect(int err_no) {}; private: eznetpp::net::tcp::tcp_socket* _socket; }; class tcp_echo_server : public eznetpp::event::tcp_acceptor_event_handler { public: tcp_echo_server(eznetpp::sys::io_manager* io_mgr) { _io_mgr = io_mgr; } virtual ~tcp_echo_server() = default; int open(int port, int backlog) { int ret = _acceptor.open(port, backlog); if (ret) { printf("%s\n", eznetpp::errcode::errno_to_str(ret).c_str()); return -1; } _io_mgr->register_socket_event_handler(&_acceptor, this); return 0; } // override void on_accept(eznetpp::net::tcp::tcp_socket* sock, int err_no) { _io_mgr->register_socket_event_handler(sock, new tcp_echosvr_session(sock)); } void on_close(int err_no) { printf("closed the acceptor(%d)\n", err_no); } private: eznetpp::sys::io_manager* _io_mgr = nullptr; eznetpp::net::tcp::tcp_acceptor _acceptor; }; int main(void) { signal(SIGINT, sig_handler); g_io_mgr.init(); tcp_echo_server server(&g_io_mgr); server.open(56789, 5); g_io_mgr.loop(); return 0; } <|endoftext|>
<commit_before>/* @ 0xCCCCCCCC */ #include "kbase/logging.h" #include <cstdio> #include <ctime> #include <iomanip> #include <thread> #include <Windows.h> #include "kbase/scoped_handle.h" namespace { using kbase::LogSeverity; using kbase::LogItemOptions; using kbase::LoggingDestination; using kbase::OldFileDisposalOption; using kbase::PathChar; using kbase::PathString; using kbase::ScopedSysHandle; const char* kLogSeverityNames[] {"INFO", "WARNING", "ERROR", "FATAL"}; const LogSeverity kAlwaysPrintErrorMinLevel = LogSeverity::LOG_ERROR; LogSeverity g_min_severity_level = LogSeverity::LOG_INFO; LogItemOptions g_log_item_options = LogItemOptions::ENABLE_TIMESTAMP; LoggingDestination g_logging_dest = LoggingDestination::LOG_TO_FILE; OldFileDisposalOption g_old_file_option = OldFileDisposalOption::APPEND_TO_OLD_LOG_FILE; PathString g_log_file_path; ScopedSysHandle g_log_file; const PathChar kLogFileName[] = L"_debug_message.log"; template<typename E> constexpr auto ToUnderlying(E e) { return static_cast<std::underlying_type_t<E>>(e); } // Ouputs timestamp in the form like "20160126 09:14:38,456". void OutputNowTimestamp(std::ostream& stream) { namespace chrono = std::chrono; // Because c-style date&time utilities don't support microsecond precison, // we have to handle it on our own. auto time_now = chrono::system_clock::now(); auto duration_in_ms = chrono::duration_cast<chrono::milliseconds>(time_now.time_since_epoch()); auto ms_part = duration_in_ms - chrono::duration_cast<chrono::seconds>(duration_in_ms); tm local_time_now; time_t raw_time = chrono::system_clock::to_time_t(time_now); _localtime64_s(&local_time_now, &raw_time); stream << std::put_time(&local_time_now, "%Y%m%d %H:%M:%S,") << std::setfill('0') << std::setw(3) << ms_part.count(); } template<typename charT> const charT* ExtractFileName(const charT* file_path) { const charT* p = file_path; const charT* last_pos = nullptr; for (; *p != '\0'; ++p) { if (*p == '/' || *p == '\\') { last_pos = p; } } return last_pos ? last_pos + 1 : file_path; } // Returns the default path for log file. // We use the same path as the EXE file. PathString GetDefaultLogFilePath() { const size_t kMaxPath = MAX_PATH + 1; PathChar exe_path[kMaxPath]; GetModuleFileNameW(nullptr, exe_path, kMaxPath); const PathChar kExeExt[] = L".exe"; PathString default_path(exe_path); auto dot_pos = default_path.rfind(kExeExt); default_path.replace(dot_pos, _countof(kExeExt) - 1, kLogFileName); return default_path; } // Returns the fallback path for the log file. // We use the path in current directory as the fallback path, when using the // default path is not possible. PathString GetFallbackLogFilePath() { const size_t kMaxPath = MAX_PATH + 1; PathChar cur_path[kMaxPath]; GetCurrentDirectoryW(kMaxPath, cur_path); PathString fallback_path(cur_path); fallback_path.append(L"\\").append(ExtractFileName(g_log_file_path.c_str())); return fallback_path; } // Once this function succeed, `g_log_file` refers to a valid and writable file. // Returns true, if we initialized the log file successfully, false otherwise. bool InitLogFile() { if (g_log_file_path.empty()) { g_log_file_path = GetDefaultLogFilePath(); } if (g_old_file_option == OldFileDisposalOption::DELETE_OLD_LOG_FILE) { DeleteFileW(g_log_file_path.c_str()); } // Surprisingly, we need neither a local nor a global lock here, on Windows. // Because if we opened a file with `FILE_APPEND_DATA` flag only, the system // will ensure that each appending is atomic. // See https://msdn.microsoft.com/en-us/library/windows/hardware/ff548289(v=vs.85).aspx. g_log_file.Reset(CreateFileW(g_log_file_path.c_str(), FILE_APPEND_DATA, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr)); if (!g_log_file) { g_log_file_path = GetFallbackLogFilePath(); g_log_file.Reset(CreateFileW(g_log_file_path.c_str(), FILE_APPEND_DATA, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr)); } return static_cast<bool>(g_log_file); } } // namespace namespace kbase { namespace internal { LogSeverity GetMinSeverityLevel() { return g_min_severity_level; } } // namespace internal LoggingSettings::LoggingSettings() : min_severity_level(LogSeverity::LOG_INFO), log_item_options(LogItemOptions::ENABLE_TIMESTAMP), logging_destination(LoggingDestination::LOG_TO_FILE), old_file_disposal_option(OldFileDisposalOption::APPEND_TO_OLD_LOG_FILE) {} void ConfigureLoggingSettings(const LoggingSettings& settings) { g_min_severity_level = settings.min_severity_level; g_log_item_options = settings.log_item_options; g_logging_dest = settings.logging_destination; g_old_file_option = settings.old_file_disposal_option; if (!(g_logging_dest & LoggingDestination::LOG_TO_FILE)) { return; } if (!settings.log_file_path.empty()) { g_log_file_path = settings.log_file_path; } // TODO: consider assert the result value on DEBUG mode. InitLogFile(); } LogMessage::LogMessage(const char* file, int line, LogSeverity severity) : file_(file), line_(line), severity_(severity) { InitMessageHeader(); } LogMessage::~LogMessage() { if (severity_ == LogSeverity::LOG_FATAL) { // TODO: logging stack trace. } stream_ << std::endl; std::string msg = stream_.str(); if (g_logging_dest & LoggingDestination::LOG_TO_SYSTEM_DEBUG_LOG) { OutputDebugStringA(msg.c_str()); // Also writes to standard error stream. fwrite(msg.data(), sizeof(char), msg.length(), stderr); fflush(stderr); } else if (severity_ >= kAlwaysPrintErrorMinLevel) { fwrite(msg.data(), sizeof(char), msg.length(), stderr); fflush(stderr); } // If unfortunately, we failed to initialize the log file, just skip the writting. if (g_logging_dest & LoggingDestination::LOG_TO_FILE) { if (g_log_file) { DWORD bytes_written = 0; WriteFile(g_log_file, msg.data(), static_cast<DWORD>(msg.length() * sizeof(char)), &bytes_written, nullptr); } } } void LogMessage::InitMessageHeader() { stream_ << "["; if (g_log_item_options & LogItemOptions::ENABLE_TIMESTAMP) { OutputNowTimestamp(stream_); } if (g_log_item_options & LogItemOptions::ENABLE_PROCESS_ID) { stream_ << " " << GetCurrentProcessId(); } if (g_log_item_options & LogItemOptions::ENABLE_THREAD_ID) { stream_ << " " << std::this_thread::get_id(); } stream_ << " " << kLogSeverityNames[ToUnderlying(severity_)] << " " << ExtractFileName(file_) << " " << '(' << line_ << ")]"; } } // namespace kbase<commit_msg>Style: Slight format changed for log message header; Ensure-Check logging file was created successfully<commit_after>/* @ 0xCCCCCCCC */ #include "kbase/logging.h" #include <cstdio> #include <ctime> #include <iomanip> #include <thread> #include <Windows.h> #include "kbase/error_exception_util.h" #include "kbase/scoped_handle.h" #include "kbase/stack_walker.h" namespace { using kbase::LogSeverity; using kbase::LogItemOptions; using kbase::LoggingDestination; using kbase::OldFileDisposalOption; using kbase::PathChar; using kbase::PathString; using kbase::ScopedSysHandle; const char* kLogSeverityNames[] {"INFO", "WARNING", "ERROR", "FATAL"}; const LogSeverity kAlwaysPrintErrorMinLevel = LogSeverity::LOG_ERROR; LogSeverity g_min_severity_level = LogSeverity::LOG_INFO; LogItemOptions g_log_item_options = LogItemOptions::ENABLE_TIMESTAMP; LoggingDestination g_logging_dest = LoggingDestination::LOG_TO_FILE; OldFileDisposalOption g_old_file_option = OldFileDisposalOption::APPEND_TO_OLD_LOG_FILE; PathString g_log_file_path; ScopedSysHandle g_log_file; const PathChar kLogFileName[] = L"_debug_message.log"; template<typename E> constexpr auto ToUnderlying(E e) { return static_cast<std::underlying_type_t<E>>(e); } // Ouputs timestamp in the form like "20160126 09:14:38,456". void OutputNowTimestamp(std::ostream& stream) { namespace chrono = std::chrono; // Because c-style date&time utilities don't support microsecond precison, // we have to handle it on our own. auto time_now = chrono::system_clock::now(); auto duration_in_ms = chrono::duration_cast<chrono::milliseconds>(time_now.time_since_epoch()); auto ms_part = duration_in_ms - chrono::duration_cast<chrono::seconds>(duration_in_ms); tm local_time_now; time_t raw_time = chrono::system_clock::to_time_t(time_now); _localtime64_s(&local_time_now, &raw_time); stream << std::put_time(&local_time_now, "%Y%m%d %H:%M:%S,") << std::setfill('0') << std::setw(3) << ms_part.count(); } template<typename charT> const charT* ExtractFileName(const charT* file_path) { const charT* p = file_path; const charT* last_pos = nullptr; for (; *p != '\0'; ++p) { if (*p == '/' || *p == '\\') { last_pos = p; } } return last_pos ? last_pos + 1 : file_path; } // Returns the default path for log file. // We use the same path as the EXE file. PathString GetDefaultLogFilePath() { const size_t kMaxPath = MAX_PATH + 1; PathChar exe_path[kMaxPath]; GetModuleFileNameW(nullptr, exe_path, kMaxPath); const PathChar kExeExt[] = L".exe"; PathString default_path(exe_path); auto dot_pos = default_path.rfind(kExeExt); default_path.replace(dot_pos, _countof(kExeExt) - 1, kLogFileName); return default_path; } // Returns the fallback path for the log file. // We use the path in current directory as the fallback path, when using the // default path is not possible. PathString GetFallbackLogFilePath() { const size_t kMaxPath = MAX_PATH + 1; PathChar cur_path[kMaxPath]; GetCurrentDirectoryW(kMaxPath, cur_path); PathString fallback_path(cur_path); fallback_path.append(L"\\").append(ExtractFileName(g_log_file_path.c_str())); return fallback_path; } // Once this function succeed, `g_log_file` refers to a valid and writable file. // Returns true, if we initialized the log file successfully, false otherwise. bool InitLogFile() { if (g_log_file_path.empty()) { g_log_file_path = GetDefaultLogFilePath(); } if (g_old_file_option == OldFileDisposalOption::DELETE_OLD_LOG_FILE) { DeleteFileW(g_log_file_path.c_str()); } // Surprisingly, we need neither a local nor a global lock here, on Windows. // Because if we opened a file with `FILE_APPEND_DATA` flag only, the system // will ensure that each appending is atomic. // See https://msdn.microsoft.com/en-us/library/windows/hardware/ff548289(v=vs.85).aspx. g_log_file.Reset(CreateFileW(g_log_file_path.c_str(), FILE_APPEND_DATA, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr)); if (!g_log_file) { g_log_file_path = GetFallbackLogFilePath(); g_log_file.Reset(CreateFileW(g_log_file_path.c_str(), FILE_APPEND_DATA, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr)); } return static_cast<bool>(g_log_file); } } // namespace namespace kbase { namespace internal { LogSeverity GetMinSeverityLevel() { return g_min_severity_level; } } // namespace internal LoggingSettings::LoggingSettings() : min_severity_level(LogSeverity::LOG_INFO), log_item_options(LogItemOptions::ENABLE_TIMESTAMP), logging_destination(LoggingDestination::LOG_TO_FILE), old_file_disposal_option(OldFileDisposalOption::APPEND_TO_OLD_LOG_FILE) {} void ConfigureLoggingSettings(const LoggingSettings& settings) { g_min_severity_level = settings.min_severity_level; g_log_item_options = settings.log_item_options; g_logging_dest = settings.logging_destination; g_old_file_option = settings.old_file_disposal_option; if (!(g_logging_dest & LoggingDestination::LOG_TO_FILE)) { return; } if (!settings.log_file_path.empty()) { g_log_file_path = settings.log_file_path; } auto rv = InitLogFile(); ENSURE(CHECK, rv)(LastError()).Require(); } LogMessage::LogMessage(const char* file, int line, LogSeverity severity) : file_(file), line_(line), severity_(severity) { InitMessageHeader(); } LogMessage::~LogMessage() { if (severity_ == LogSeverity::LOG_FATAL) { stream_ << "\n"; StackWalker walker; walker.DumpCallStack(stream_); } stream_ << std::endl; std::string msg = stream_.str(); if (g_logging_dest & LoggingDestination::LOG_TO_SYSTEM_DEBUG_LOG) { OutputDebugStringA(msg.c_str()); // Also writes to standard error stream. fwrite(msg.data(), sizeof(char), msg.length(), stderr); fflush(stderr); } else if (severity_ >= kAlwaysPrintErrorMinLevel) { fwrite(msg.data(), sizeof(char), msg.length(), stderr); fflush(stderr); } // If unfortunately, we failed to initialize the log file, just skip the writting. if ((g_logging_dest & LoggingDestination::LOG_TO_FILE) && g_log_file) { DWORD bytes_written = 0; WriteFile(g_log_file, msg.data(), static_cast<DWORD>(msg.length() * sizeof(char)), &bytes_written, nullptr); } } void LogMessage::InitMessageHeader() { stream_ << "["; if (g_log_item_options & LogItemOptions::ENABLE_TIMESTAMP) { OutputNowTimestamp(stream_); } if (g_log_item_options & LogItemOptions::ENABLE_PROCESS_ID) { stream_ << " " << GetCurrentProcessId(); } if (g_log_item_options & LogItemOptions::ENABLE_THREAD_ID) { stream_ << " " << std::this_thread::get_id(); } stream_ << " " << kLogSeverityNames[ToUnderlying(severity_)] << " " << ExtractFileName(file_) << '(' << line_ << ")]"; } } // namespace kbase<|endoftext|>
<commit_before>/* * Copyright (c) 2018 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "api/transport/goog_cc_factory.h" #include <utility> #include "absl/memory/memory.h" #include "modules/congestion_controller/goog_cc/goog_cc_network_control.h" namespace webrtc { GoogCcNetworkControllerFactory::GoogCcNetworkControllerFactory( RtcEventLog* event_log) : event_log_(event_log) {} GoogCcNetworkControllerFactory::GoogCcNetworkControllerFactory( NetworkStatePredictorFactoryInterface* network_state_predictor_factory) { factory_config_.network_state_predictor_factory = network_state_predictor_factory; } GoogCcNetworkControllerFactory::GoogCcNetworkControllerFactory( GoogCcFactoryConfig config) : factory_config_(std::move(config)) {} std::unique_ptr<NetworkControllerInterface> GoogCcNetworkControllerFactory::Create(NetworkControllerConfig config) { if (event_log_) config.event_log = event_log_; GoogCcConfig goog_cc_config; goog_cc_config.feedback_only = factory_config_.feedback_only; if (factory_config_.network_state_estimator_factory) { RTC_DCHECK(config.key_value_config); goog_cc_config.network_state_estimator = factory_config_.network_state_estimator_factory->Create( config.key_value_config); } if (factory_config_.network_state_predictor_factory) { goog_cc_config.network_state_predictor = factory_config_.network_state_predictor_factory ->CreateNetworkStatePredictor(); } return absl::make_unique<GoogCcNetworkController>(config, std::move(goog_cc_config)); } TimeDelta GoogCcNetworkControllerFactory::GetProcessInterval() const { const int64_t kUpdateIntervalMs = 25; return TimeDelta::ms(kUpdateIntervalMs); } GoogCcFeedbackNetworkControllerFactory::GoogCcFeedbackNetworkControllerFactory( RtcEventLog* event_log) : GoogCcNetworkControllerFactory(event_log) { factory_config_.feedback_only = true; } } // namespace webrtc <commit_msg>Makes send side network estimation opt-in.<commit_after>/* * Copyright (c) 2018 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "api/transport/goog_cc_factory.h" #include <utility> #include "absl/memory/memory.h" #include "modules/congestion_controller/goog_cc/goog_cc_network_control.h" namespace webrtc { GoogCcNetworkControllerFactory::GoogCcNetworkControllerFactory( RtcEventLog* event_log) : event_log_(event_log) {} GoogCcNetworkControllerFactory::GoogCcNetworkControllerFactory( NetworkStatePredictorFactoryInterface* network_state_predictor_factory) { factory_config_.network_state_predictor_factory = network_state_predictor_factory; } GoogCcNetworkControllerFactory::GoogCcNetworkControllerFactory( GoogCcFactoryConfig config) : factory_config_(std::move(config)) {} std::unique_ptr<NetworkControllerInterface> GoogCcNetworkControllerFactory::Create(NetworkControllerConfig config) { if (event_log_) config.event_log = event_log_; GoogCcConfig goog_cc_config; goog_cc_config.feedback_only = factory_config_.feedback_only; if (factory_config_.network_state_estimator_factory) { RTC_DCHECK(config.key_value_config); if (config.key_value_config->Lookup("WebRTC-SendSideEstimation") .find("Enabled") == 0) { goog_cc_config.network_state_estimator = factory_config_.network_state_estimator_factory->Create( config.key_value_config); } } if (factory_config_.network_state_predictor_factory) { goog_cc_config.network_state_predictor = factory_config_.network_state_predictor_factory ->CreateNetworkStatePredictor(); } return absl::make_unique<GoogCcNetworkController>(config, std::move(goog_cc_config)); } TimeDelta GoogCcNetworkControllerFactory::GetProcessInterval() const { const int64_t kUpdateIntervalMs = 25; return TimeDelta::ms(kUpdateIntervalMs); } GoogCcFeedbackNetworkControllerFactory::GoogCcFeedbackNetworkControllerFactory( RtcEventLog* event_log) : GoogCcNetworkControllerFactory(event_log) { factory_config_.feedback_only = true; } } // namespace webrtc <|endoftext|>
<commit_before>/************************************************************************** * * Copyright 2011 Jose Fonseca * All Rights Reserved. * * 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 <string.h> #include "image.hpp" #include "retrace.hpp" #include "glproc.hpp" #include "glstate.hpp" #include "glretrace.hpp" namespace glretrace { bool double_buffer = false; bool insideGlBeginEnd = false; Trace::Parser parser; glws::WindowSystem *ws = NULL; glws::Visual *visual = NULL; glws::Drawable *drawable = NULL; glws::Context *context = NULL; unsigned frame = 0; long long startTime = 0; bool wait = false; bool benchmark = false; const char *compare_prefix = NULL; const char *snapshot_prefix = NULL; enum frequency snapshot_frequency = FREQUENCY_NEVER; unsigned dump_state = ~0; void checkGlError(Trace::Call &call) { GLenum error = glGetError(); if (error == GL_NO_ERROR) { return; } if (retrace::verbosity == 0) { std::cout << call; std::cout.flush(); } std::cerr << call.no << ": "; std::cerr << "warning: glGetError("; std::cerr << call.name(); std::cerr << ") = "; switch (error) { case GL_INVALID_ENUM: std::cerr << "GL_INVALID_ENUM"; break; case GL_INVALID_VALUE: std::cerr << "GL_INVALID_VALUE"; break; case GL_INVALID_OPERATION: std::cerr << "GL_INVALID_OPERATION"; break; case GL_STACK_OVERFLOW: std::cerr << "GL_STACK_OVERFLOW"; break; case GL_STACK_UNDERFLOW: std::cerr << "GL_STACK_UNDERFLOW"; break; case GL_OUT_OF_MEMORY: std::cerr << "GL_OUT_OF_MEMORY"; break; case GL_INVALID_FRAMEBUFFER_OPERATION: std::cerr << "GL_INVALID_FRAMEBUFFER_OPERATION"; break; case GL_TABLE_TOO_LARGE: std::cerr << "GL_TABLE_TOO_LARGE"; break; default: std::cerr << error; break; } std::cerr << "\n"; } void snapshot(unsigned call_no) { if (!drawable || (!snapshot_prefix && !compare_prefix)) { return; } Image::Image *ref = NULL; if (compare_prefix) { char filename[PATH_MAX]; snprintf(filename, sizeof filename, "%s%010u.png", compare_prefix, call_no); ref = Image::readPNG(filename); if (!ref) { return; } if (retrace::verbosity >= 0) { std::cout << "Read " << filename << "\n"; } } Image::Image *src = glstate::getDrawBufferImage(GL_RGBA); if (!src) { return; } if (snapshot_prefix) { char filename[PATH_MAX]; snprintf(filename, sizeof filename, "%s%010u.png", snapshot_prefix, call_no); if (src->writePNG(filename) && retrace::verbosity >= 0) { std::cout << "Wrote " << filename << "\n"; } } if (ref) { std::cout << "Snapshot " << call_no << " average precision of " << src->compare(*ref) << " bits\n"; delete ref; } delete src; } void frame_complete(unsigned call_no) { ++frame; if (snapshot_frequency == FREQUENCY_FRAME || snapshot_frequency == FREQUENCY_FRAMEBUFFER) { snapshot(call_no); } } static void display(void) { Trace::Call *call; while ((call = parser.parse_call())) { const char *name = call->name(); if (retrace::verbosity >= 1) { std::cout << *call; std::cout.flush(); } if (name[0] == 'C' && name[1] == 'G' && name[2] == 'L') { glretrace::retrace_call_cgl(*call); } else if (name[0] == 'w' && name[1] == 'g' && name[2] == 'l') { glretrace::retrace_call_wgl(*call); } else if (name[0] == 'g' && name[1] == 'l' && name[2] == 'X') { glretrace::retrace_call_glx(*call); } else { retrace::retrace_call(*call); } if (!insideGlBeginEnd && drawable && context && call->no >= dump_state) { glstate::dumpCurrentContext(std::cout); exit(0); } delete call; } // Reached the end of trace glFlush(); long long endTime = OS::GetTime(); float timeInterval = (endTime - startTime) * 1.0E-6; if (retrace::verbosity >= -1) { std::cout << "Rendered " << frame << " frames" " in " << timeInterval << " secs," " average of " << (frame/timeInterval) << " fps\n"; } if (wait) { while (ws->processEvents()) {} } else { exit(0); } } static void usage(void) { std::cout << "Usage: glretrace [OPTION] TRACE\n" "Replay TRACE.\n" "\n" " -b benchmark mode (no error checking or warning messages)\n" " -c PREFIX compare against snapshots\n" " -db use a double buffer visual (default)\n" " -sb use a single buffer visual\n" " -s PREFIX take snapshots\n" " -S FREQUENCY snapshot frequency: frame (default), framebuffer, or draw\n" " -v verbose output\n" " -D CALLNO dump state at specific call no\n" " -w wait on final frame\n"; } extern "C" int main(int argc, char **argv) { int i; for (i = 1; i < argc; ++i) { const char *arg = argv[i]; if (arg[0] != '-') { break; } if (!strcmp(arg, "--")) { break; } else if (!strcmp(arg, "-b")) { benchmark = true; retrace::verbosity = -1; } else if (!strcmp(arg, "-c")) { compare_prefix = argv[++i]; } else if (!strcmp(arg, "-D")) { dump_state = atoi(argv[++i]); retrace::verbosity = -2; } else if (!strcmp(arg, "-db")) { double_buffer = true; } else if (!strcmp(arg, "-sb")) { double_buffer = false; } else if (!strcmp(arg, "--help")) { usage(); return 0; } else if (!strcmp(arg, "-s")) { snapshot_prefix = argv[++i]; if (snapshot_frequency == FREQUENCY_NEVER) { snapshot_frequency = FREQUENCY_FRAME; } } else if (!strcmp(arg, "-S")) { arg = argv[++i]; if (!strcmp(arg, "frame")) { snapshot_frequency = FREQUENCY_FRAME; } else if (!strcmp(arg, "framebuffer")) { snapshot_frequency = FREQUENCY_FRAMEBUFFER; } else if (!strcmp(arg, "draw")) { snapshot_frequency = FREQUENCY_DRAW; } else { std::cerr << "error: unknown frequency " << arg << "\n"; usage(); return 1; } if (snapshot_prefix == NULL) { snapshot_prefix = ""; } } else if (!strcmp(arg, "-v")) { ++retrace::verbosity; } else if (!strcmp(arg, "-w")) { wait = true; } else { std::cerr << "error: unknown option " << arg << "\n"; usage(); return 1; } } ws = glws::createNativeWindowSystem(); visual = ws->createVisual(double_buffer); for ( ; i < argc; ++i) { if (parser.open(argv[i])) { startTime = OS::GetTime(); display(); parser.close(); } } return 0; } } /* namespace glretrace */ <commit_msg>Actually set double buffer as default...<commit_after>/************************************************************************** * * Copyright 2011 Jose Fonseca * All Rights Reserved. * * 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 <string.h> #include "image.hpp" #include "retrace.hpp" #include "glproc.hpp" #include "glstate.hpp" #include "glretrace.hpp" namespace glretrace { bool double_buffer = true; bool insideGlBeginEnd = false; Trace::Parser parser; glws::WindowSystem *ws = NULL; glws::Visual *visual = NULL; glws::Drawable *drawable = NULL; glws::Context *context = NULL; unsigned frame = 0; long long startTime = 0; bool wait = false; bool benchmark = false; const char *compare_prefix = NULL; const char *snapshot_prefix = NULL; enum frequency snapshot_frequency = FREQUENCY_NEVER; unsigned dump_state = ~0; void checkGlError(Trace::Call &call) { GLenum error = glGetError(); if (error == GL_NO_ERROR) { return; } if (retrace::verbosity == 0) { std::cout << call; std::cout.flush(); } std::cerr << call.no << ": "; std::cerr << "warning: glGetError("; std::cerr << call.name(); std::cerr << ") = "; switch (error) { case GL_INVALID_ENUM: std::cerr << "GL_INVALID_ENUM"; break; case GL_INVALID_VALUE: std::cerr << "GL_INVALID_VALUE"; break; case GL_INVALID_OPERATION: std::cerr << "GL_INVALID_OPERATION"; break; case GL_STACK_OVERFLOW: std::cerr << "GL_STACK_OVERFLOW"; break; case GL_STACK_UNDERFLOW: std::cerr << "GL_STACK_UNDERFLOW"; break; case GL_OUT_OF_MEMORY: std::cerr << "GL_OUT_OF_MEMORY"; break; case GL_INVALID_FRAMEBUFFER_OPERATION: std::cerr << "GL_INVALID_FRAMEBUFFER_OPERATION"; break; case GL_TABLE_TOO_LARGE: std::cerr << "GL_TABLE_TOO_LARGE"; break; default: std::cerr << error; break; } std::cerr << "\n"; } void snapshot(unsigned call_no) { if (!drawable || (!snapshot_prefix && !compare_prefix)) { return; } Image::Image *ref = NULL; if (compare_prefix) { char filename[PATH_MAX]; snprintf(filename, sizeof filename, "%s%010u.png", compare_prefix, call_no); ref = Image::readPNG(filename); if (!ref) { return; } if (retrace::verbosity >= 0) { std::cout << "Read " << filename << "\n"; } } Image::Image *src = glstate::getDrawBufferImage(GL_RGBA); if (!src) { return; } if (snapshot_prefix) { char filename[PATH_MAX]; snprintf(filename, sizeof filename, "%s%010u.png", snapshot_prefix, call_no); if (src->writePNG(filename) && retrace::verbosity >= 0) { std::cout << "Wrote " << filename << "\n"; } } if (ref) { std::cout << "Snapshot " << call_no << " average precision of " << src->compare(*ref) << " bits\n"; delete ref; } delete src; } void frame_complete(unsigned call_no) { ++frame; if (snapshot_frequency == FREQUENCY_FRAME || snapshot_frequency == FREQUENCY_FRAMEBUFFER) { snapshot(call_no); } } static void display(void) { Trace::Call *call; while ((call = parser.parse_call())) { const char *name = call->name(); if (retrace::verbosity >= 1) { std::cout << *call; std::cout.flush(); } if (name[0] == 'C' && name[1] == 'G' && name[2] == 'L') { glretrace::retrace_call_cgl(*call); } else if (name[0] == 'w' && name[1] == 'g' && name[2] == 'l') { glretrace::retrace_call_wgl(*call); } else if (name[0] == 'g' && name[1] == 'l' && name[2] == 'X') { glretrace::retrace_call_glx(*call); } else { retrace::retrace_call(*call); } if (!insideGlBeginEnd && drawable && context && call->no >= dump_state) { glstate::dumpCurrentContext(std::cout); exit(0); } delete call; } // Reached the end of trace glFlush(); long long endTime = OS::GetTime(); float timeInterval = (endTime - startTime) * 1.0E-6; if (retrace::verbosity >= -1) { std::cout << "Rendered " << frame << " frames" " in " << timeInterval << " secs," " average of " << (frame/timeInterval) << " fps\n"; } if (wait) { while (ws->processEvents()) {} } else { exit(0); } } static void usage(void) { std::cout << "Usage: glretrace [OPTION] TRACE\n" "Replay TRACE.\n" "\n" " -b benchmark mode (no error checking or warning messages)\n" " -c PREFIX compare against snapshots\n" " -db use a double buffer visual (default)\n" " -sb use a single buffer visual\n" " -s PREFIX take snapshots\n" " -S FREQUENCY snapshot frequency: frame (default), framebuffer, or draw\n" " -v verbose output\n" " -D CALLNO dump state at specific call no\n" " -w wait on final frame\n"; } extern "C" int main(int argc, char **argv) { int i; for (i = 1; i < argc; ++i) { const char *arg = argv[i]; if (arg[0] != '-') { break; } if (!strcmp(arg, "--")) { break; } else if (!strcmp(arg, "-b")) { benchmark = true; retrace::verbosity = -1; } else if (!strcmp(arg, "-c")) { compare_prefix = argv[++i]; } else if (!strcmp(arg, "-D")) { dump_state = atoi(argv[++i]); retrace::verbosity = -2; } else if (!strcmp(arg, "-db")) { double_buffer = true; } else if (!strcmp(arg, "-sb")) { double_buffer = false; } else if (!strcmp(arg, "--help")) { usage(); return 0; } else if (!strcmp(arg, "-s")) { snapshot_prefix = argv[++i]; if (snapshot_frequency == FREQUENCY_NEVER) { snapshot_frequency = FREQUENCY_FRAME; } } else if (!strcmp(arg, "-S")) { arg = argv[++i]; if (!strcmp(arg, "frame")) { snapshot_frequency = FREQUENCY_FRAME; } else if (!strcmp(arg, "framebuffer")) { snapshot_frequency = FREQUENCY_FRAMEBUFFER; } else if (!strcmp(arg, "draw")) { snapshot_frequency = FREQUENCY_DRAW; } else { std::cerr << "error: unknown frequency " << arg << "\n"; usage(); return 1; } if (snapshot_prefix == NULL) { snapshot_prefix = ""; } } else if (!strcmp(arg, "-v")) { ++retrace::verbosity; } else if (!strcmp(arg, "-w")) { wait = true; } else { std::cerr << "error: unknown option " << arg << "\n"; usage(); return 1; } } ws = glws::createNativeWindowSystem(); visual = ws->createVisual(double_buffer); for ( ; i < argc; ++i) { if (parser.open(argv[i])) { startTime = OS::GetTime(); display(); parser.close(); } } return 0; } } /* namespace glretrace */ <|endoftext|>
<commit_before>/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm/gm.h" #include "include/core/SkCanvas.h" #include "include/core/SkClipOp.h" #include "include/core/SkColor.h" #include "include/core/SkFont.h" #include "include/core/SkFontTypes.h" #include "include/core/SkPaint.h" #include "include/core/SkPath.h" #include "include/core/SkRect.h" #include "include/core/SkScalar.h" #include "include/core/SkSize.h" #include "include/core/SkString.h" #include "include/core/SkTypeface.h" #include "include/core/SkTypes.h" #include "include/effects/SkGradientShader.h" #include "src/core/SkClipOpPriv.h" #include "tools/Resources.h" #include "tools/ToolUtils.h" #include <string.h> namespace skiagm { constexpr SkColor gPathColor = SK_ColorBLACK; constexpr SkColor gClipAColor = SK_ColorBLUE; constexpr SkColor gClipBColor = SK_ColorRED; class ComplexClipGM : public GM { public: ComplexClipGM(bool aaclip, bool saveLayer, bool invertDraw) : fDoAAClip(aaclip) , fDoSaveLayer(saveLayer) , fInvertDraw(invertDraw) { this->setBGColor(0xFFDEDFDE); } protected: SkString onShortName() override { SkString str; str.printf("complexclip_%s%s%s", fDoAAClip ? "aa" : "bw", fDoSaveLayer ? "_layer" : "", fInvertDraw ? "_invert" : ""); return str; } SkISize onISize() override { return SkISize::Make(970, 780); } void onDraw(SkCanvas* canvas) override { SkPath path; path.moveTo(0, 50) .quadTo(0, 0, 50, 0) .lineTo(175, 0) .quadTo(200, 0, 200, 25) .lineTo(200, 150) .quadTo(200, 200, 150, 200) .lineTo(0, 200) .close() .moveTo(50, 50) .lineTo(150, 50) .lineTo(150, 125) .quadTo(150, 150, 125, 150) .lineTo(50, 150) .close(); if (fInvertDraw) { path.setFillType(SkPathFillType::kInverseEvenOdd); } else { path.setFillType(SkPathFillType::kEvenOdd); } SkPaint pathPaint; pathPaint.setAntiAlias(true); pathPaint.setColor(gPathColor); SkPath clipA; clipA.addPoly({{10, 20}, {165, 22}, {70, 105}, {165, 177}, {-5, 180}}, false).close(); SkPath clipB; clipB.addPoly({{40, 10}, {190, 15}, {195, 190}, {40, 185}, {155, 100}}, false).close(); SkFont font(ToolUtils::create_portable_typeface(), 20); constexpr struct { SkClipOp fOp; const char* fName; } gOps[] = { //extra spaces in names for measureText {kIntersect_SkClipOp, "Isect "}, {kDifference_SkClipOp, "Diff " }, {kUnion_SkClipOp, "Union "}, {kXOR_SkClipOp, "Xor " }, {kReverseDifference_SkClipOp, "RDiff "} }; canvas->translate(20, 20); canvas->scale(3 * SK_Scalar1 / 4, 3 * SK_Scalar1 / 4); if (fDoSaveLayer) { // We want the layer to appear symmetric relative to actual // device boundaries so we need to "undo" the effect of the // scale and translate SkRect bounds = SkRect::MakeLTRB( 4.0f/3.0f * -20, 4.0f/3.0f * -20, 4.0f/3.0f * (this->getISize().fWidth - 20), 4.0f/3.0f * (this->getISize().fHeight - 20)); bounds.inset(100, 100); SkPaint boundPaint; boundPaint.setColor(SK_ColorRED); boundPaint.setStyle(SkPaint::kStroke_Style); canvas->drawRect(bounds, boundPaint); canvas->clipRect(bounds); canvas->saveLayer(&bounds, nullptr); } for (int invBits = 0; invBits < 4; ++invBits) { canvas->save(); for (size_t op = 0; op < SK_ARRAY_COUNT(gOps); ++op) { this->drawHairlines(canvas, path, clipA, clipB); bool doInvA = SkToBool(invBits & 1); bool doInvB = SkToBool(invBits & 2); canvas->save(); // set clip clipA.setFillType(doInvA ? SkPathFillType::kInverseEvenOdd : SkPathFillType::kEvenOdd); clipB.setFillType(doInvB ? SkPathFillType::kInverseEvenOdd : SkPathFillType::kEvenOdd); canvas->clipPath(clipA, fDoAAClip); canvas->clipPath(clipB, gOps[op].fOp, fDoAAClip); // In the inverse case we need to prevent the draw from covering the whole // canvas. if (fInvertDraw) { SkRect rectClip = clipA.getBounds(); rectClip.join(path.getBounds()); rectClip.join(path.getBounds()); rectClip.outset(5, 5); canvas->clipRect(rectClip); } // draw path clipped canvas->drawPath(path, pathPaint); canvas->restore(); SkPaint paint; SkScalar txtX = 45; paint.setColor(gClipAColor); const char* aTxt = doInvA ? "InvA " : "A "; canvas->drawSimpleText(aTxt, strlen(aTxt), SkTextEncoding::kUTF8, txtX, 220, font, paint); txtX += font.measureText(aTxt, strlen(aTxt), SkTextEncoding::kUTF8); paint.setColor(SK_ColorBLACK); canvas->drawSimpleText(gOps[op].fName, strlen(gOps[op].fName), SkTextEncoding::kUTF8, txtX, 220, font, paint); txtX += font.measureText(gOps[op].fName, strlen(gOps[op].fName), SkTextEncoding::kUTF8); paint.setColor(gClipBColor); const char* bTxt = doInvB ? "InvB " : "B "; canvas->drawSimpleText(bTxt, strlen(bTxt), SkTextEncoding::kUTF8, txtX, 220, font, paint); canvas->translate(250,0); } canvas->restore(); canvas->translate(0, 250); } if (fDoSaveLayer) { canvas->restore(); } } private: void drawHairlines(SkCanvas* canvas, const SkPath& path, const SkPath& clipA, const SkPath& clipB) { SkPaint paint; paint.setAntiAlias(true); paint.setStyle(SkPaint::kStroke_Style); const SkAlpha fade = 0x33; // draw path in hairline paint.setColor(gPathColor); paint.setAlpha(fade); canvas->drawPath(path, paint); // draw clips in hair line paint.setColor(gClipAColor); paint.setAlpha(fade); canvas->drawPath(clipA, paint); paint.setColor(gClipBColor); paint.setAlpha(fade); canvas->drawPath(clipB, paint); } bool fDoAAClip; bool fDoSaveLayer; bool fInvertDraw; typedef GM INHERITED; }; ////////////////////////////////////////////////////////////////////////////// DEF_GM(return new ComplexClipGM(false, false, false);) DEF_GM(return new ComplexClipGM(false, false, true);) DEF_GM(return new ComplexClipGM(false, true, false);) DEF_GM(return new ComplexClipGM(false, true, true);) DEF_GM(return new ComplexClipGM(true, false, false);) DEF_GM(return new ComplexClipGM(true, false, true);) DEF_GM(return new ComplexClipGM(true, true, false);) DEF_GM(return new ComplexClipGM(true, true, true);) } DEF_SIMPLE_GM(clip_shader, canvas, 840, 650) { auto img = GetResourceAsImage("images/yellow_rose.png"); auto sh = img->makeShader(); SkRect r = SkRect::MakeIWH(img->width(), img->height()); SkPaint p; canvas->translate(10, 10); canvas->drawImage(img, 0, 0, nullptr); canvas->save(); canvas->translate(img->width() + 10, 0); canvas->clipShader(sh, SkClipOp::kIntersect); p.setColor(SK_ColorRED); canvas->drawRect(r, p); canvas->restore(); canvas->save(); canvas->translate(0, img->height() + 10); canvas->clipShader(sh, SkClipOp::kDifference); p.setColor(SK_ColorGREEN); canvas->drawRect(r, p); canvas->restore(); canvas->save(); canvas->translate(img->width() + 10, img->height() + 10); canvas->clipShader(sh, SkClipOp::kIntersect); canvas->save(); SkMatrix lm = SkMatrix::Scale(1.0f/5, 1.0f/5); canvas->clipShader(img->makeShader(SkTileMode::kRepeat, SkTileMode::kRepeat, &lm)); canvas->drawImage(img, 0, 0, nullptr); canvas->restore(); canvas->restore(); } DEF_SIMPLE_GM(clip_shader_layer, canvas, 430, 320) { auto img = GetResourceAsImage("images/yellow_rose.png"); auto sh = img->makeShader(); SkRect r = SkRect::MakeIWH(img->width(), img->height()); canvas->translate(10, 10); // now add the cool clip canvas->clipRect(r); canvas->clipShader(sh); // now draw a layer with the same image, and watch it get restored w/ the clip canvas->saveLayer(&r, nullptr); canvas->drawColor(0xFFFF0000); canvas->restore(); } DEF_SIMPLE_GM(clip_shader_nested, canvas, 256, 256) { float w = 64.f; float h = 64.f; const SkColor gradColors[] = {SK_ColorBLACK, SkColorSetARGB(128, 128, 128, 128)}; auto s = SkGradientShader::MakeRadial({0.5f * w, 0.5f * h}, 0.1f * w, gradColors, nullptr, 2, SkTileMode::kRepeat, 0, nullptr); SkPaint p; // A large black rect affected by two gradient clips canvas->save(); canvas->clipShader(s); canvas->scale(2.f, 2.f); canvas->clipShader(s); canvas->drawRect(SkRect::MakeWH(w, h), p); canvas->restore(); canvas->translate(0.f, 2.f * h); // A small red rect, with no clipping canvas->save(); p.setColor(SK_ColorRED); canvas->drawRect(SkRect::MakeWH(w, h), p); canvas->restore(); } <commit_msg>Add clipShader with perspective GM<commit_after>/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm/gm.h" #include "include/core/SkCanvas.h" #include "include/core/SkClipOp.h" #include "include/core/SkColor.h" #include "include/core/SkFont.h" #include "include/core/SkFontTypes.h" #include "include/core/SkPaint.h" #include "include/core/SkPath.h" #include "include/core/SkRect.h" #include "include/core/SkScalar.h" #include "include/core/SkSize.h" #include "include/core/SkString.h" #include "include/core/SkTypeface.h" #include "include/core/SkTypes.h" #include "include/effects/SkGradientShader.h" #include "src/core/SkClipOpPriv.h" #include "tools/Resources.h" #include "tools/ToolUtils.h" #include <string.h> namespace skiagm { constexpr SkColor gPathColor = SK_ColorBLACK; constexpr SkColor gClipAColor = SK_ColorBLUE; constexpr SkColor gClipBColor = SK_ColorRED; class ComplexClipGM : public GM { public: ComplexClipGM(bool aaclip, bool saveLayer, bool invertDraw) : fDoAAClip(aaclip) , fDoSaveLayer(saveLayer) , fInvertDraw(invertDraw) { this->setBGColor(0xFFDEDFDE); } protected: SkString onShortName() override { SkString str; str.printf("complexclip_%s%s%s", fDoAAClip ? "aa" : "bw", fDoSaveLayer ? "_layer" : "", fInvertDraw ? "_invert" : ""); return str; } SkISize onISize() override { return SkISize::Make(970, 780); } void onDraw(SkCanvas* canvas) override { SkPath path; path.moveTo(0, 50) .quadTo(0, 0, 50, 0) .lineTo(175, 0) .quadTo(200, 0, 200, 25) .lineTo(200, 150) .quadTo(200, 200, 150, 200) .lineTo(0, 200) .close() .moveTo(50, 50) .lineTo(150, 50) .lineTo(150, 125) .quadTo(150, 150, 125, 150) .lineTo(50, 150) .close(); if (fInvertDraw) { path.setFillType(SkPathFillType::kInverseEvenOdd); } else { path.setFillType(SkPathFillType::kEvenOdd); } SkPaint pathPaint; pathPaint.setAntiAlias(true); pathPaint.setColor(gPathColor); SkPath clipA; clipA.addPoly({{10, 20}, {165, 22}, {70, 105}, {165, 177}, {-5, 180}}, false).close(); SkPath clipB; clipB.addPoly({{40, 10}, {190, 15}, {195, 190}, {40, 185}, {155, 100}}, false).close(); SkFont font(ToolUtils::create_portable_typeface(), 20); constexpr struct { SkClipOp fOp; const char* fName; } gOps[] = { //extra spaces in names for measureText {kIntersect_SkClipOp, "Isect "}, {kDifference_SkClipOp, "Diff " }, {kUnion_SkClipOp, "Union "}, {kXOR_SkClipOp, "Xor " }, {kReverseDifference_SkClipOp, "RDiff "} }; canvas->translate(20, 20); canvas->scale(3 * SK_Scalar1 / 4, 3 * SK_Scalar1 / 4); if (fDoSaveLayer) { // We want the layer to appear symmetric relative to actual // device boundaries so we need to "undo" the effect of the // scale and translate SkRect bounds = SkRect::MakeLTRB( 4.0f/3.0f * -20, 4.0f/3.0f * -20, 4.0f/3.0f * (this->getISize().fWidth - 20), 4.0f/3.0f * (this->getISize().fHeight - 20)); bounds.inset(100, 100); SkPaint boundPaint; boundPaint.setColor(SK_ColorRED); boundPaint.setStyle(SkPaint::kStroke_Style); canvas->drawRect(bounds, boundPaint); canvas->clipRect(bounds); canvas->saveLayer(&bounds, nullptr); } for (int invBits = 0; invBits < 4; ++invBits) { canvas->save(); for (size_t op = 0; op < SK_ARRAY_COUNT(gOps); ++op) { this->drawHairlines(canvas, path, clipA, clipB); bool doInvA = SkToBool(invBits & 1); bool doInvB = SkToBool(invBits & 2); canvas->save(); // set clip clipA.setFillType(doInvA ? SkPathFillType::kInverseEvenOdd : SkPathFillType::kEvenOdd); clipB.setFillType(doInvB ? SkPathFillType::kInverseEvenOdd : SkPathFillType::kEvenOdd); canvas->clipPath(clipA, fDoAAClip); canvas->clipPath(clipB, gOps[op].fOp, fDoAAClip); // In the inverse case we need to prevent the draw from covering the whole // canvas. if (fInvertDraw) { SkRect rectClip = clipA.getBounds(); rectClip.join(path.getBounds()); rectClip.join(path.getBounds()); rectClip.outset(5, 5); canvas->clipRect(rectClip); } // draw path clipped canvas->drawPath(path, pathPaint); canvas->restore(); SkPaint paint; SkScalar txtX = 45; paint.setColor(gClipAColor); const char* aTxt = doInvA ? "InvA " : "A "; canvas->drawSimpleText(aTxt, strlen(aTxt), SkTextEncoding::kUTF8, txtX, 220, font, paint); txtX += font.measureText(aTxt, strlen(aTxt), SkTextEncoding::kUTF8); paint.setColor(SK_ColorBLACK); canvas->drawSimpleText(gOps[op].fName, strlen(gOps[op].fName), SkTextEncoding::kUTF8, txtX, 220, font, paint); txtX += font.measureText(gOps[op].fName, strlen(gOps[op].fName), SkTextEncoding::kUTF8); paint.setColor(gClipBColor); const char* bTxt = doInvB ? "InvB " : "B "; canvas->drawSimpleText(bTxt, strlen(bTxt), SkTextEncoding::kUTF8, txtX, 220, font, paint); canvas->translate(250,0); } canvas->restore(); canvas->translate(0, 250); } if (fDoSaveLayer) { canvas->restore(); } } private: void drawHairlines(SkCanvas* canvas, const SkPath& path, const SkPath& clipA, const SkPath& clipB) { SkPaint paint; paint.setAntiAlias(true); paint.setStyle(SkPaint::kStroke_Style); const SkAlpha fade = 0x33; // draw path in hairline paint.setColor(gPathColor); paint.setAlpha(fade); canvas->drawPath(path, paint); // draw clips in hair line paint.setColor(gClipAColor); paint.setAlpha(fade); canvas->drawPath(clipA, paint); paint.setColor(gClipBColor); paint.setAlpha(fade); canvas->drawPath(clipB, paint); } bool fDoAAClip; bool fDoSaveLayer; bool fInvertDraw; typedef GM INHERITED; }; ////////////////////////////////////////////////////////////////////////////// DEF_GM(return new ComplexClipGM(false, false, false);) DEF_GM(return new ComplexClipGM(false, false, true);) DEF_GM(return new ComplexClipGM(false, true, false);) DEF_GM(return new ComplexClipGM(false, true, true);) DEF_GM(return new ComplexClipGM(true, false, false);) DEF_GM(return new ComplexClipGM(true, false, true);) DEF_GM(return new ComplexClipGM(true, true, false);) DEF_GM(return new ComplexClipGM(true, true, true);) } DEF_SIMPLE_GM(clip_shader, canvas, 840, 650) { auto img = GetResourceAsImage("images/yellow_rose.png"); auto sh = img->makeShader(); SkRect r = SkRect::MakeIWH(img->width(), img->height()); SkPaint p; canvas->translate(10, 10); canvas->drawImage(img, 0, 0, nullptr); canvas->save(); canvas->translate(img->width() + 10, 0); canvas->clipShader(sh, SkClipOp::kIntersect); p.setColor(SK_ColorRED); canvas->drawRect(r, p); canvas->restore(); canvas->save(); canvas->translate(0, img->height() + 10); canvas->clipShader(sh, SkClipOp::kDifference); p.setColor(SK_ColorGREEN); canvas->drawRect(r, p); canvas->restore(); canvas->save(); canvas->translate(img->width() + 10, img->height() + 10); canvas->clipShader(sh, SkClipOp::kIntersect); canvas->save(); SkMatrix lm = SkMatrix::Scale(1.0f/5, 1.0f/5); canvas->clipShader(img->makeShader(SkTileMode::kRepeat, SkTileMode::kRepeat, &lm)); canvas->drawImage(img, 0, 0, nullptr); canvas->restore(); canvas->restore(); } DEF_SIMPLE_GM(clip_shader_layer, canvas, 430, 320) { auto img = GetResourceAsImage("images/yellow_rose.png"); auto sh = img->makeShader(); SkRect r = SkRect::MakeIWH(img->width(), img->height()); canvas->translate(10, 10); // now add the cool clip canvas->clipRect(r); canvas->clipShader(sh); // now draw a layer with the same image, and watch it get restored w/ the clip canvas->saveLayer(&r, nullptr); canvas->drawColor(0xFFFF0000); canvas->restore(); } DEF_SIMPLE_GM(clip_shader_nested, canvas, 256, 256) { float w = 64.f; float h = 64.f; const SkColor gradColors[] = {SK_ColorBLACK, SkColorSetARGB(128, 128, 128, 128)}; auto s = SkGradientShader::MakeRadial({0.5f * w, 0.5f * h}, 0.1f * w, gradColors, nullptr, 2, SkTileMode::kRepeat, 0, nullptr); SkPaint p; // A large black rect affected by two gradient clips canvas->save(); canvas->clipShader(s); canvas->scale(2.f, 2.f); canvas->clipShader(s); canvas->drawRect(SkRect::MakeWH(w, h), p); canvas->restore(); canvas->translate(0.f, 2.f * h); // A small red rect, with no clipping canvas->save(); p.setColor(SK_ColorRED); canvas->drawRect(SkRect::MakeWH(w, h), p); canvas->restore(); } namespace { // Where is canvas->concat(persp) called relative to the clipShader calls. enum ConcatPerspective { kConcatBeforeClips, kConcatAfterClips, kConcatBetweenClips }; // Order in which clipShader(image) and clipShader(gradient) are specified; only meaningful // when CanvasPerspective is kConcatBetweenClips. enum ClipOrder { kClipImageFirst, kClipGradientFirst, kDoesntMatter = kClipImageFirst }; // Which shaders have perspective applied as a local matrix. enum LocalMatrix { kNoLocalMat, kImageWithLocalMat, kGradientWithLocalMat, kBothWithLocalMat }; struct Config { ConcatPerspective fConcat; ClipOrder fOrder; LocalMatrix fLM; }; static void draw_banner(SkCanvas* canvas, Config config) { SkString banner; banner.append("Persp: "); if (config.fConcat == kConcatBeforeClips || config.fLM == kBothWithLocalMat) { banner.append("Both Clips"); } else { SkASSERT((config.fConcat == kConcatBetweenClips && config.fLM == kNoLocalMat) || (config.fConcat == kConcatAfterClips && (config.fLM == kImageWithLocalMat || config.fLM == kGradientWithLocalMat))); if ((config.fConcat == kConcatBetweenClips && config.fOrder == kClipImageFirst) || config.fLM == kGradientWithLocalMat) { banner.append("Gradient"); } else { SkASSERT(config.fOrder == kClipGradientFirst || config.fLM == kImageWithLocalMat); banner.append("Image"); } } if (config.fLM != kNoLocalMat) { banner.append(" (w/ LM, should equal top row)"); } static const SkFont kFont(ToolUtils::create_portable_typeface(), 12); canvas->drawString(banner.c_str(), 20.f, -30.f, kFont, SkPaint()); }; } // anonymous DEF_SIMPLE_GM(clip_shader_persp, canvas, 1370, 1030) { // Each draw has a clipShader(image-shader), a clipShader(gradient-shader), a concat(persp-mat), // and each shader may or may not be wrapped with a perspective local matrix. // Pairs of configs that should match in appearance where first config doesn't use a local // matrix (top row of GM) and the second does (bottom row of GM). Config matches[][2] = { // Everything has perspective {{kConcatBeforeClips, kDoesntMatter, kNoLocalMat}, {kConcatAfterClips, kDoesntMatter, kBothWithLocalMat}}, // Image shader has perspective {{kConcatBetweenClips, kClipGradientFirst, kNoLocalMat}, {kConcatAfterClips, kDoesntMatter, kImageWithLocalMat}}, // Gradient shader has perspective {{kConcatBetweenClips, kClipImageFirst, kNoLocalMat}, {kConcatAfterClips, kDoesntMatter, kGradientWithLocalMat}} }; // The image that is drawn auto img = GetResourceAsImage("images/yellow_rose.png"); // Scale factor always applied to the image shader so that it tiles SkMatrix scale = SkMatrix::Scale(1.f / 4.f, 1.f / 4.f); // The perspective matrix applied wherever needed SkPoint src[4]; SkRect::Make(img->dimensions()).toQuad(src); SkPoint dst[4] = {{0, 80.f}, {img->width() + 28.f, -100.f}, {img->width() - 28.f, img->height() + 100.f}, {0.f, img->height() - 80.f}}; SkMatrix persp; SkAssertResult(persp.setPolyToPoly(src, dst, 4)); SkMatrix perspScale = SkMatrix::Concat(persp, scale); auto drawConfig = [&](Config config) { canvas->save(); draw_banner(canvas, config); // Make clipShaders (possibly with local matrices) bool gradLM = config.fLM == kGradientWithLocalMat || config.fLM == kBothWithLocalMat; const SkColor gradColors[] = {SK_ColorBLACK, SkColorSetARGB(128, 128, 128, 128)}; auto gradShader = SkGradientShader::MakeRadial({0.5f * img->width(), 0.5f * img->height()}, 0.1f * img->width(), gradColors, nullptr, 2, SkTileMode::kRepeat, 0, gradLM ? &persp : nullptr); bool imageLM = config.fLM == kImageWithLocalMat || config.fLM == kBothWithLocalMat; auto imgShader = img->makeShader(SkTileMode::kRepeat, SkTileMode::kRepeat, imageLM ? perspScale : scale); // Perspective before any clipShader if (config.fConcat == kConcatBeforeClips) { canvas->concat(persp); } // First clipshader canvas->clipShader(config.fOrder == kClipImageFirst ? imgShader : gradShader); // Perspective between clipShader if (config.fConcat == kConcatBetweenClips) { canvas->concat(persp); } // Second clipShader canvas->clipShader(config.fOrder == kClipImageFirst ? gradShader : imgShader); // Perspective after clipShader if (config.fConcat == kConcatAfterClips) { canvas->concat(persp); } // Actual draw and clip boundary are the same for all configs canvas->clipRect(SkRect::MakeIWH(img->width(), img->height())); canvas->clear(SK_ColorBLACK); canvas->drawImage(img, 0, 0); canvas->restore(); }; SkIRect grid = persp.mapRect(SkRect::Make(img->dimensions())).roundOut(); grid.fLeft -= 20; // manual adjust to look nicer canvas->translate(10.f, 10.f); for (size_t i = 0; i < SK_ARRAY_COUNT(matches); ++i) { canvas->save(); canvas->translate(-grid.fLeft, -grid.fTop); drawConfig(matches[i][0]); canvas->translate(0.f, grid.height()); drawConfig(matches[i][1]); canvas->restore(); canvas->translate(grid.width(), 0.f); } } <|endoftext|>
<commit_before>/* * Copyright 2013 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkPerlinNoiseShader.h" namespace skiagm { class PerlinNoiseGM : public GM { public: PerlinNoiseGM() { this->setBGColor(0xFF000000); fSize = SkISize::Make(80, 80); } protected: virtual SkString onShortName() { return SkString("perlinnoise"); } virtual SkISize onISize() { return make_isize(500, 400); } void drawClippedRect(SkCanvas* canvas, int x, int y, const SkPaint& paint) { canvas->save(); canvas->clipRect(SkRect::MakeXYWH(SkIntToScalar(x), SkIntToScalar(y), SkIntToScalar(fSize.width()), SkIntToScalar(fSize.height()))); SkRect r = SkRect::MakeXYWH(x, y, SkIntToScalar(fSize.width()), SkIntToScalar(fSize.height())); canvas->drawRect(r, paint); canvas->restore(); } void test(SkCanvas* canvas, int x, int y, SkPerlinNoiseShader::Type type, float baseFrequencyX, float baseFrequencyY, int numOctaves, float seed, bool stitchTiles) { SkShader* shader = (type == SkPerlinNoiseShader::kFractalNoise_Type) ? SkPerlinNoiseShader::CreateFractalNoise(baseFrequencyX, baseFrequencyY, numOctaves, seed, stitchTiles ? &fSize : NULL) : SkPerlinNoiseShader::CreateTubulence(baseFrequencyX, baseFrequencyY, numOctaves, seed, stitchTiles ? &fSize : NULL); SkPaint paint; paint.setShader(shader)->unref(); drawClippedRect(canvas, x, y, paint); } virtual void onDraw(SkCanvas* canvas) { canvas->clear(0x00000000); test(canvas, 0, 0, SkPerlinNoiseShader::kFractalNoise_Type, 0.1f, 0.1f, 2, 0, false); test(canvas, 100, 0, SkPerlinNoiseShader::kFractalNoise_Type, 0.4f, 0.2f, 3, 0, true); test(canvas, 200, 0, SkPerlinNoiseShader::kFractalNoise_Type, 0.3f, 0.6f, 4, 0, false); test(canvas, 300, 0, SkPerlinNoiseShader::kFractalNoise_Type, 0.2f, 0.4f, 5, 0, true); test(canvas, 400, 0, SkPerlinNoiseShader::kFractalNoise_Type, 0.5f, 0.8f, 6, 0, false); test(canvas, 0, 100, SkPerlinNoiseShader::kTurbulence_Type, 0.1f, 0.1f, 2, 0, true); test(canvas, 100, 100, SkPerlinNoiseShader::kTurbulence_Type, 0.4f, 0.2f, 3, 0, false); test(canvas, 200, 100, SkPerlinNoiseShader::kTurbulence_Type, 0.3f, 0.6f, 4, 0, true); test(canvas, 300, 100, SkPerlinNoiseShader::kTurbulence_Type, 0.2f, 0.4f, 5, 0, false); test(canvas, 400, 100, SkPerlinNoiseShader::kTurbulence_Type, 0.5f, 0.8f, 6, 0, true); test(canvas, 0, 200, SkPerlinNoiseShader::kFractalNoise_Type, 0.1f, 0.1f, 3, 1, false); test(canvas, 100, 200, SkPerlinNoiseShader::kFractalNoise_Type, 0.1f, 0.1f, 3, 2, false); test(canvas, 200, 200, SkPerlinNoiseShader::kFractalNoise_Type, 0.1f, 0.1f, 3, 3, false); test(canvas, 300, 200, SkPerlinNoiseShader::kFractalNoise_Type, 0.1f, 0.1f, 3, 4, false); test(canvas, 400, 200, SkPerlinNoiseShader::kFractalNoise_Type, 0.1f, 0.1f, 3, 5, false); canvas->scale(SkFloatToScalar(0.75f), SkFloatToScalar(1.0f)); test(canvas, 0, 300, SkPerlinNoiseShader::kFractalNoise_Type, 0.1f, 0.1f, 2, 0, false); test(canvas, 100, 300, SkPerlinNoiseShader::kFractalNoise_Type, 0.4f, 0.2f, 3, 0, true); test(canvas, 200, 300, SkPerlinNoiseShader::kFractalNoise_Type, 0.3f, 0.6f, 4, 0, false); test(canvas, 300, 300, SkPerlinNoiseShader::kFractalNoise_Type, 0.2f, 0.4f, 5, 0, true); test(canvas, 400, 300, SkPerlinNoiseShader::kFractalNoise_Type, 0.5f, 0.8f, 6, 0, false); } private: typedef GM INHERITED; SkISize fSize; }; ////////////////////////////////////////////////////////////////////////////// static GM* MyFactory(void*) { return new PerlinNoiseGM; } static GMRegistry reg(MyFactory); } <commit_msg>Unreviewed build fix<commit_after>/* * Copyright 2013 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkPerlinNoiseShader.h" namespace skiagm { class PerlinNoiseGM : public GM { public: PerlinNoiseGM() { this->setBGColor(0xFF000000); fSize = SkISize::Make(80, 80); } protected: virtual SkString onShortName() { return SkString("perlinnoise"); } virtual SkISize onISize() { return make_isize(500, 400); } void drawClippedRect(SkCanvas* canvas, int x, int y, const SkPaint& paint) { canvas->save(); canvas->clipRect(SkRect::MakeXYWH(SkIntToScalar(x), SkIntToScalar(y), SkIntToScalar(fSize.width()), SkIntToScalar(fSize.height()))); SkRect r = SkRect::MakeXYWH(SkIntToScalar(x), SkIntToScalar(y), SkIntToScalar(fSize.width()), SkIntToScalar(fSize.height())); canvas->drawRect(r, paint); canvas->restore(); } void test(SkCanvas* canvas, int x, int y, SkPerlinNoiseShader::Type type, float baseFrequencyX, float baseFrequencyY, int numOctaves, float seed, bool stitchTiles) { SkShader* shader = (type == SkPerlinNoiseShader::kFractalNoise_Type) ? SkPerlinNoiseShader::CreateFractalNoise(baseFrequencyX, baseFrequencyY, numOctaves, seed, stitchTiles ? &fSize : NULL) : SkPerlinNoiseShader::CreateTubulence(baseFrequencyX, baseFrequencyY, numOctaves, seed, stitchTiles ? &fSize : NULL); SkPaint paint; paint.setShader(shader)->unref(); drawClippedRect(canvas, x, y, paint); } virtual void onDraw(SkCanvas* canvas) { canvas->clear(0x00000000); test(canvas, 0, 0, SkPerlinNoiseShader::kFractalNoise_Type, 0.1f, 0.1f, 2, 0, false); test(canvas, 100, 0, SkPerlinNoiseShader::kFractalNoise_Type, 0.4f, 0.2f, 3, 0, true); test(canvas, 200, 0, SkPerlinNoiseShader::kFractalNoise_Type, 0.3f, 0.6f, 4, 0, false); test(canvas, 300, 0, SkPerlinNoiseShader::kFractalNoise_Type, 0.2f, 0.4f, 5, 0, true); test(canvas, 400, 0, SkPerlinNoiseShader::kFractalNoise_Type, 0.5f, 0.8f, 6, 0, false); test(canvas, 0, 100, SkPerlinNoiseShader::kTurbulence_Type, 0.1f, 0.1f, 2, 0, true); test(canvas, 100, 100, SkPerlinNoiseShader::kTurbulence_Type, 0.4f, 0.2f, 3, 0, false); test(canvas, 200, 100, SkPerlinNoiseShader::kTurbulence_Type, 0.3f, 0.6f, 4, 0, true); test(canvas, 300, 100, SkPerlinNoiseShader::kTurbulence_Type, 0.2f, 0.4f, 5, 0, false); test(canvas, 400, 100, SkPerlinNoiseShader::kTurbulence_Type, 0.5f, 0.8f, 6, 0, true); test(canvas, 0, 200, SkPerlinNoiseShader::kFractalNoise_Type, 0.1f, 0.1f, 3, 1, false); test(canvas, 100, 200, SkPerlinNoiseShader::kFractalNoise_Type, 0.1f, 0.1f, 3, 2, false); test(canvas, 200, 200, SkPerlinNoiseShader::kFractalNoise_Type, 0.1f, 0.1f, 3, 3, false); test(canvas, 300, 200, SkPerlinNoiseShader::kFractalNoise_Type, 0.1f, 0.1f, 3, 4, false); test(canvas, 400, 200, SkPerlinNoiseShader::kFractalNoise_Type, 0.1f, 0.1f, 3, 5, false); canvas->scale(SkFloatToScalar(0.75f), SkFloatToScalar(1.0f)); test(canvas, 0, 300, SkPerlinNoiseShader::kFractalNoise_Type, 0.1f, 0.1f, 2, 0, false); test(canvas, 100, 300, SkPerlinNoiseShader::kFractalNoise_Type, 0.4f, 0.2f, 3, 0, true); test(canvas, 200, 300, SkPerlinNoiseShader::kFractalNoise_Type, 0.3f, 0.6f, 4, 0, false); test(canvas, 300, 300, SkPerlinNoiseShader::kFractalNoise_Type, 0.2f, 0.4f, 5, 0, true); test(canvas, 400, 300, SkPerlinNoiseShader::kFractalNoise_Type, 0.5f, 0.8f, 6, 0, false); } private: typedef GM INHERITED; SkISize fSize; }; ////////////////////////////////////////////////////////////////////////////// static GM* MyFactory(void*) { return new PerlinNoiseGM; } static GMRegistry reg(MyFactory); } <|endoftext|>
<commit_before>#include "pe/FileHdrWrapper.h" #include "pe/PEFile.h" #include <time.h> #include <QDateTime> namespace util { QString getDateString(const quint64 timestamp) { const time_t rawtime = (const time_t)timestamp; QString format = "dddd, dd.MM.yyyy hh:mm:ss"; QDateTime date1(QDateTime(QDateTime::fromTime_t(rawtime))); return date1.toUTC().toString(format) + " UTC"; } }; std::map<DWORD, QString> FileHdrWrapper::s_fHdrCharact; std::map<DWORD, QString> FileHdrWrapper::s_machine; void FileHdrWrapper::initCharact() { if (s_fHdrCharact.size() != 0) { return; //already initialized } s_fHdrCharact[F_RELOCS_STRIPPED] = "Relocation info stripped from file."; s_fHdrCharact[F_EXECUTABLE_IMAGE] = "File is executable (i.e. no unresolved externel references)."; s_fHdrCharact[F_LINE_NUMS_STRIPPED] = "Line nunbers stripped from file."; s_fHdrCharact[F_LOCAL_SYMS_STRIPPED] = "Local symbols stripped from file."; s_fHdrCharact[F_AGGRESIVE_WS_TRIM] = "Agressively trim working set"; s_fHdrCharact[F_LARGE_ADDRESS_AWARE] = "App can handle >2gb addresses"; s_fHdrCharact[F_BYTES_REVERSED_LO] = "Bytes of machine word are reversed."; s_fHdrCharact[F_MACHINE_32BIT] = "32 bit word machine."; s_fHdrCharact[F_DEBUG_STRIPPED] = "Debugging info stripped from file in .DBG file"; s_fHdrCharact[F_REMOVABLE_RUN_FROM_SWAP] = "If Image is on removable media, copy and run from the swap file."; s_fHdrCharact[F_NET_RUN_FROM_SWAP] = "If Image is on Net, copy and run from the swap file."; s_fHdrCharact[F_SYSTEM] = "System File."; s_fHdrCharact[F_DLL] = "File is a DLL."; s_fHdrCharact[F_UP_SYSTEM_ONLY] = "File should only be run on a UP machine"; s_fHdrCharact[F_BYTES_REVERSED_HI] = "Bytes of machine word are reversed."; } std::vector<DWORD> FileHdrWrapper::splitCharact(DWORD characteristics) { if (s_fHdrCharact.size() == 0) initCharact(); std::vector<DWORD> chSet; for (std::map<DWORD, QString>::iterator iter = s_fHdrCharact.begin(); iter != s_fHdrCharact.end(); ++iter) { if (characteristics & iter->first) { chSet.push_back(iter->first); } } return chSet; } QString FileHdrWrapper::translateCharacteristics(DWORD charact) { if (s_fHdrCharact.size() == 0) initCharact(); if (s_fHdrCharact.find(charact) == s_fHdrCharact.end()) return ""; return s_fHdrCharact[charact]; } void FileHdrWrapper::initMachine() { s_machine[M_UNKNOWN] = "s_machine unknown"; s_machine[M_I386] = "Intel 386"; s_machine[M_R3000] = "MIPS little-endian, 0x160 big-endian"; s_machine[M_R4000] = "MIPS little-endian"; s_machine[M_R10000] = "MIPS little-endian"; s_machine[M_WCEMIPSV2] = " MIPS little-endian WCE v2"; s_machine[M_ALPHA] = "Alpha_AXP"; s_machine[M_SH3] = "SH3 little-endian"; s_machine[M_SH3DSP] = "SH3DSP"; s_machine[M_SH3E] = "SH3E little-endian"; s_machine[M_SH4] = "SH4 little-endian"; s_machine[M_SH5] = "SH5"; s_machine[M_ARM] = "ARM Little-Endian"; s_machine[M_THUMB] = "Thumb"; s_machine[M_AM33] = "AM33"; s_machine[M_POWERPC] = "IBM PowerPC Little-Endian"; s_machine[M_POWERPCFP] = "PowerRPCFP"; s_machine[M_IA64] = "Intel 64"; s_machine[M_MIPS16] = "MIPS"; s_machine[M_ALPHA64] = "ALPHA64"; s_machine[M_MIPSFPU] = "MIPS"; s_machine[M_MIPSFPU16] = "MIPS"; s_machine[M_AXP64] = "M_ALPHA64"; s_machine[M_TRICORE] = " Infineon"; s_machine[M_CEF] = "CEF"; s_machine[M_EBC] = "EFI Byte Code"; s_machine[M_AMD64] = "AMD64 (K8)"; s_machine[M_M32R] = "M32R little-endian"; s_machine[M_CEE] = "CEE"; } QString FileHdrWrapper::translateMachine(DWORD val) { if (s_machine.size() == 0) initMachine(); if (s_machine.find(val) == s_machine.end()) return ""; return s_machine[val]; } void* FileHdrWrapper::getPtr() { if (this->hdr) { // use cached if exists return (void*) hdr; } if (m_PE == NULL) return NULL; offset_t myOff = m_PE->peFileHdrOffset(); IMAGE_FILE_HEADER* hdr = (IMAGE_FILE_HEADER*) m_Exe->getContentAt(myOff, sizeof(IMAGE_FILE_HEADER)); if (!hdr) return NULL; //error return (void*) hdr; } void* FileHdrWrapper::getFieldPtr(size_t fieldId, size_t subField) { IMAGE_FILE_HEADER * hdr = reinterpret_cast<IMAGE_FILE_HEADER*>(getPtr()); if (!hdr) return NULL; IMAGE_FILE_HEADER &fileHeader = (*hdr); switch (fieldId) { case MACHINE: return (void*) &fileHeader.Machine; case SEC_NUM: return (void*) &fileHeader.NumberOfSections; case TIMESTAMP: return (void*) &fileHeader.TimeDateStamp; case SYMBOL_PTR: return (void*) &fileHeader.PointerToSymbolTable; case SYMBOL_NUM: return (void*) &fileHeader.NumberOfSymbols; case OPTHDR_SIZE: return (void*) &fileHeader.SizeOfOptionalHeader; case CHARACT: return (void*) &fileHeader.Characteristics; } return (void*) &fileHeader; } QString FileHdrWrapper::getFieldName(size_t fieldId) { switch (fieldId) { case MACHINE: return("Machine"); case SEC_NUM: return ("Sections Count"); case TIMESTAMP: return("Time Date Stamp"); case SYMBOL_PTR: return("Ptr to Symbol Table"); case SYMBOL_NUM: return("Num. of Symbols"); case OPTHDR_SIZE: return("Size of OptionalHeader"); case CHARACT: return("Characteristics"); } return ""; } Executable::addr_type FileHdrWrapper::containsAddrType(size_t fieldId, size_t subField) { return Executable::NOT_ADDR; } QString FileHdrWrapper::translateFieldContent(size_t fieldId) { IMAGE_FILE_HEADER * hdr = reinterpret_cast<IMAGE_FILE_HEADER*>(getPtr()); if (!hdr) return ""; IMAGE_FILE_HEADER &fileHeader = (*hdr); switch (fieldId) { case MACHINE: return FileHdrWrapper::translateMachine(fileHeader.Machine); case TIMESTAMP: return util::getDateString(fileHeader.TimeDateStamp); } return ""; } <commit_msg>fixed spelling mistakes in file characteristics<commit_after>#include "pe/FileHdrWrapper.h" #include "pe/PEFile.h" #include <time.h> #include <QDateTime> namespace util { QString getDateString(const quint64 timestamp) { const time_t rawtime = (const time_t)timestamp; QString format = "dddd, dd.MM.yyyy hh:mm:ss"; QDateTime date1(QDateTime(QDateTime::fromTime_t(rawtime))); return date1.toUTC().toString(format) + " UTC"; } }; std::map<DWORD, QString> FileHdrWrapper::s_fHdrCharact; std::map<DWORD, QString> FileHdrWrapper::s_machine; void FileHdrWrapper::initCharact() { if (s_fHdrCharact.size() != 0) { return; //already initialized } s_fHdrCharact[F_RELOCS_STRIPPED] = "Relocation info stripped from file."; s_fHdrCharact[F_EXECUTABLE_IMAGE] = "File is executable (i.e. no unresolved external references)."; s_fHdrCharact[F_LINE_NUMS_STRIPPED] = "Line numbers stripped from file."; s_fHdrCharact[F_LOCAL_SYMS_STRIPPED] = "Local symbols stripped from file."; s_fHdrCharact[F_AGGRESIVE_WS_TRIM] = "Aggressively trim working set"; s_fHdrCharact[F_LARGE_ADDRESS_AWARE] = "App can handle >2gb addresses"; s_fHdrCharact[F_BYTES_REVERSED_LO] = "Bytes of machine word are reversed."; s_fHdrCharact[F_MACHINE_32BIT] = "32 bit word machine."; s_fHdrCharact[F_DEBUG_STRIPPED] = "Debugging info stripped from file in .DBG file"; s_fHdrCharact[F_REMOVABLE_RUN_FROM_SWAP] = "If Image is on removable media, copy and run from the swap file."; s_fHdrCharact[F_NET_RUN_FROM_SWAP] = "If Image is on Net, copy and run from the swap file."; s_fHdrCharact[F_SYSTEM] = "System File."; s_fHdrCharact[F_DLL] = "File is a DLL."; s_fHdrCharact[F_UP_SYSTEM_ONLY] = "File should only be run on a UP machine"; s_fHdrCharact[F_BYTES_REVERSED_HI] = "Bytes of machine word are reversed."; } std::vector<DWORD> FileHdrWrapper::splitCharact(DWORD characteristics) { if (s_fHdrCharact.size() == 0) initCharact(); std::vector<DWORD> chSet; for (std::map<DWORD, QString>::iterator iter = s_fHdrCharact.begin(); iter != s_fHdrCharact.end(); ++iter) { if (characteristics & iter->first) { chSet.push_back(iter->first); } } return chSet; } QString FileHdrWrapper::translateCharacteristics(DWORD charact) { if (s_fHdrCharact.size() == 0) initCharact(); if (s_fHdrCharact.find(charact) == s_fHdrCharact.end()) return ""; return s_fHdrCharact[charact]; } void FileHdrWrapper::initMachine() { s_machine[M_UNKNOWN] = "s_machine unknown"; s_machine[M_I386] = "Intel 386"; s_machine[M_R3000] = "MIPS little-endian, 0x160 big-endian"; s_machine[M_R4000] = "MIPS little-endian"; s_machine[M_R10000] = "MIPS little-endian"; s_machine[M_WCEMIPSV2] = " MIPS little-endian WCE v2"; s_machine[M_ALPHA] = "Alpha_AXP"; s_machine[M_SH3] = "SH3 little-endian"; s_machine[M_SH3DSP] = "SH3DSP"; s_machine[M_SH3E] = "SH3E little-endian"; s_machine[M_SH4] = "SH4 little-endian"; s_machine[M_SH5] = "SH5"; s_machine[M_ARM] = "ARM Little-Endian"; s_machine[M_THUMB] = "Thumb"; s_machine[M_AM33] = "AM33"; s_machine[M_POWERPC] = "IBM PowerPC Little-Endian"; s_machine[M_POWERPCFP] = "PowerRPCFP"; s_machine[M_IA64] = "Intel 64"; s_machine[M_MIPS16] = "MIPS"; s_machine[M_ALPHA64] = "ALPHA64"; s_machine[M_MIPSFPU] = "MIPS"; s_machine[M_MIPSFPU16] = "MIPS"; s_machine[M_AXP64] = "M_ALPHA64"; s_machine[M_TRICORE] = " Infineon"; s_machine[M_CEF] = "CEF"; s_machine[M_EBC] = "EFI Byte Code"; s_machine[M_AMD64] = "AMD64 (K8)"; s_machine[M_M32R] = "M32R little-endian"; s_machine[M_CEE] = "CEE"; } QString FileHdrWrapper::translateMachine(DWORD val) { if (s_machine.size() == 0) initMachine(); if (s_machine.find(val) == s_machine.end()) return ""; return s_machine[val]; } void* FileHdrWrapper::getPtr() { if (this->hdr) { // use cached if exists return (void*) hdr; } if (m_PE == NULL) return NULL; offset_t myOff = m_PE->peFileHdrOffset(); IMAGE_FILE_HEADER* hdr = (IMAGE_FILE_HEADER*) m_Exe->getContentAt(myOff, sizeof(IMAGE_FILE_HEADER)); if (!hdr) return NULL; //error return (void*) hdr; } void* FileHdrWrapper::getFieldPtr(size_t fieldId, size_t subField) { IMAGE_FILE_HEADER * hdr = reinterpret_cast<IMAGE_FILE_HEADER*>(getPtr()); if (!hdr) return NULL; IMAGE_FILE_HEADER &fileHeader = (*hdr); switch (fieldId) { case MACHINE: return (void*) &fileHeader.Machine; case SEC_NUM: return (void*) &fileHeader.NumberOfSections; case TIMESTAMP: return (void*) &fileHeader.TimeDateStamp; case SYMBOL_PTR: return (void*) &fileHeader.PointerToSymbolTable; case SYMBOL_NUM: return (void*) &fileHeader.NumberOfSymbols; case OPTHDR_SIZE: return (void*) &fileHeader.SizeOfOptionalHeader; case CHARACT: return (void*) &fileHeader.Characteristics; } return (void*) &fileHeader; } QString FileHdrWrapper::getFieldName(size_t fieldId) { switch (fieldId) { case MACHINE: return("Machine"); case SEC_NUM: return ("Sections Count"); case TIMESTAMP: return("Time Date Stamp"); case SYMBOL_PTR: return("Ptr to Symbol Table"); case SYMBOL_NUM: return("Num. of Symbols"); case OPTHDR_SIZE: return("Size of OptionalHeader"); case CHARACT: return("Characteristics"); } return ""; } Executable::addr_type FileHdrWrapper::containsAddrType(size_t fieldId, size_t subField) { return Executable::NOT_ADDR; } QString FileHdrWrapper::translateFieldContent(size_t fieldId) { IMAGE_FILE_HEADER * hdr = reinterpret_cast<IMAGE_FILE_HEADER*>(getPtr()); if (!hdr) return ""; IMAGE_FILE_HEADER &fileHeader = (*hdr); switch (fieldId) { case MACHINE: return FileHdrWrapper::translateMachine(fileHeader.Machine); case TIMESTAMP: return util::getDateString(fileHeader.TimeDateStamp); } return ""; } <|endoftext|>
<commit_before>/** * Copyright (c) 2004 Carsten Burghardt <burghardt@kde.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 2 of the License * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * In addition, as a special exception, the copyright holders give * permission to link the code of this program with any edition of * the Qt library by Trolltech AS, Norway (or with modified versions * of Qt that use the same license as Qt), and distribute linked * combinations including the two. You must obey the GNU General * Public License in all respects for all of the code used other than * Qt. If you modify this file, you may extend this exception to * your version of the file, but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from * your version. */ #include "listjob.h" #include "kmfolderimap.h" #include "kmfoldercachedimap.h" #include "kmacctimap.h" #include "kmacctcachedimap.h" #include "folderstorage.h" #include "kmfolder.h" #include "progressmanager.h" using KPIM::ProgressManager; #include <kdebug.h> #include <kurl.h> #include <kio/scheduler.h> #include <kio/job.h> #include <kio/global.h> #include <klocale.h> using namespace KMail; ListJob::ListJob( FolderStorage* storage, ImapAccountBase* account, ImapAccountBase::ListType type, bool secondStep, bool complete, bool hasInbox, const QString& path, KPIM::ProgressItem* item ) : FolderJob( 0, tOther, (storage ? storage->folder() : 0) ), mStorage( storage ), mAccount( account ), mType( type ), mHasInbox( hasInbox ), mSecondStep( secondStep ), mComplete( complete ), mHonorLocalSubscription( false ), mPath( path ), mParentProgressItem( item ) { } ListJob::~ListJob() { kdDebug(5006 ) << k_funcinfo << kdBacktrace() << endl; } void ListJob::execute() { if ( mAccount->makeConnection() == ImapAccountBase::Error ) { kdWarning(5006) << "ListJob - got no connection" << endl; deleteLater(); return; } else if ( mAccount->makeConnection() == ImapAccountBase::Connecting ) { // We'll wait for the connectionResult signal from the account. kdDebug(5006) << "ListJob - waiting for connection" << endl; connect( mAccount, SIGNAL( connectionResult(int, const QString&) ), this, SLOT( slotConnectionResult(int, const QString&) ) ); return; } // this is needed until we have a common base class for d(imap) if ( mPath.isEmpty() ) { if ( mStorage && mStorage->folderType() == KMFolderTypeImap ) { mPath = static_cast<KMFolderImap*>(mStorage)->imapPath(); } else if ( mStorage && mStorage->folderType() == KMFolderTypeCachedImap ) { mPath = static_cast<KMFolderCachedImap*>(mStorage)->imapPath(); } else { kdError(5006) << "ListJob - no valid path and no folder given" << endl; deleteLater(); return; } } // create jobData ImapAccountBase::jobData jd; jd.total = 1; jd.done = 0; jd.cancellable = true; jd.createInbox = ( mSecondStep && !mHasInbox ) ? true : false; jd.parent = mDestFolder; jd.onlySubscribed = ( mType != ImapAccountBase::List ); jd.path = mPath; QString status = mDestFolder ? mDestFolder->prettyURL() : QString::null; if ( mParentProgressItem ) { jd.progressItem = ProgressManager::createProgressItem( mParentProgressItem, "ListDir" + ProgressManager::getUniqueID(), status, i18n("retrieving folders"), false, mAccount->useSSL() || mAccount->useTLS() ); mParentProgressItem->setStatus( status ); } // this is needed if you have a prefix // as the INBOX is located in your root ("/") and needs a special listing jd.inboxOnly = !mSecondStep && mAccount->prefix() != "/" && mPath == mAccount->prefix() && !mHasInbox; // make the URL QString ltype = "LIST"; if ( mType == ImapAccountBase::ListSubscribed ) ltype = "LSUB"; else if ( mType == ImapAccountBase::ListSubscribedNoCheck ) ltype = "LSUBNOCHECK"; KURL url = mAccount->getUrl(); url.setPath( ( jd.inboxOnly ? QString("/") : mPath ) + ";TYPE=" + ltype + ( mComplete ? ";SECTION=COMPLETE" : QString::null) ); // go KIO::SimpleJob *job = KIO::listDir( url, false ); KIO::Scheduler::assignJobToSlave( mAccount->slave(), job ); mAccount->insertJob( job, jd ); connect( job, SIGNAL(result(KIO::Job *)), this, SLOT(slotListResult(KIO::Job *)) ); connect( job, SIGNAL(entries(KIO::Job *, const KIO::UDSEntryList &)), this, SLOT(slotListEntries(KIO::Job *, const KIO::UDSEntryList &)) ); } void ListJob::slotConnectionResult( int errorCode, const QString& errorMsg ) { Q_UNUSED( errorMsg ); if ( !errorCode ) execute(); else { if ( mParentProgressItem ) mParentProgressItem->setComplete(); deleteLater(); } } void ListJob::slotListResult( KIO::Job* job ) { ImapAccountBase::JobIterator it = mAccount->findJob( job ); if ( it == mAccount->jobsEnd() ) { deleteLater(); return; } if ( job->error() ) { mAccount->handleJobError( job, i18n( "Error while listing folder %1: " ).arg((*it).path), true ); } else { // transport the information, include the jobData emit receivedFolders( mSubfolderNames, mSubfolderPaths, mSubfolderMimeTypes, mSubfolderAttributes, *it ); mAccount->removeJob( it ); } deleteLater(); } void ListJob::slotListEntries( KIO::Job* job, const KIO::UDSEntryList& uds ) { ImapAccountBase::JobIterator it = mAccount->findJob( job ); if ( it == mAccount->jobsEnd() ) { deleteLater(); return; } if( (*it).progressItem ) (*it).progressItem->setProgress( 50 ); QString name; KURL url; QString mimeType; QString attributes; for ( KIO::UDSEntryList::ConstIterator udsIt = uds.begin(); udsIt != uds.end(); udsIt++ ) { mimeType = QString::null; attributes = QString::null; for ( KIO::UDSEntry::ConstIterator eIt = (*udsIt).begin(); eIt != (*udsIt).end(); eIt++ ) { // get the needed information if ( (*eIt).m_uds == KIO::UDS_NAME ) name = (*eIt).m_str; else if ( (*eIt).m_uds == KIO::UDS_URL ) url = KURL((*eIt).m_str, 106); // utf-8 else if ( (*eIt).m_uds == KIO::UDS_MIME_TYPE ) mimeType = (*eIt).m_str; else if ( (*eIt).m_uds == KIO::UDS_EXTRA ) attributes = (*eIt).m_str; } if ( (mimeType == "inode/directory" || mimeType == "message/digest" || mimeType == "message/directory") && name != ".." && (mAccount->hiddenFolders() || name.at(0) != '.') && (!(*it).inboxOnly || name.upper() == "INBOX") ) { if ( ((*it).inboxOnly || url.path() == "/INBOX/") && name.upper() == "INBOX" && !mHasInbox ) { // our INBOX (*it).createInbox = true; } if ( mHonorLocalSubscription && mAccount->onlyLocallySubscribedFolders() && !mAccount->locallySubscribedTo( url.path() ) ) { continue; } // Some servers send _lots_ of duplicates // This check is too slow for huge lists if ( mSubfolderPaths.count() > 100 || mSubfolderPaths.findIndex(url.path()) == -1 ) { mSubfolderNames.append( name ); mSubfolderPaths.append( url.path() ); mSubfolderMimeTypes.append( mimeType ); mSubfolderAttributes.append( attributes ); } } } } void KMail::ListJob::setHonorLocalSubscription( bool value ) { mHonorLocalSubscription = value; } bool KMail::ListJob::honorLocalSubscription() const { return mHonorLocalSubscription; } #include "listjob.moc" <commit_msg>REmove chatty debug.<commit_after>/** * Copyright (c) 2004 Carsten Burghardt <burghardt@kde.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 2 of the License * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * In addition, as a special exception, the copyright holders give * permission to link the code of this program with any edition of * the Qt library by Trolltech AS, Norway (or with modified versions * of Qt that use the same license as Qt), and distribute linked * combinations including the two. You must obey the GNU General * Public License in all respects for all of the code used other than * Qt. If you modify this file, you may extend this exception to * your version of the file, but you are not obligated to do so. If * you do not wish to do so, delete this exception statement from * your version. */ #include "listjob.h" #include "kmfolderimap.h" #include "kmfoldercachedimap.h" #include "kmacctimap.h" #include "kmacctcachedimap.h" #include "folderstorage.h" #include "kmfolder.h" #include "progressmanager.h" using KPIM::ProgressManager; #include <kdebug.h> #include <kurl.h> #include <kio/scheduler.h> #include <kio/job.h> #include <kio/global.h> #include <klocale.h> using namespace KMail; ListJob::ListJob( FolderStorage* storage, ImapAccountBase* account, ImapAccountBase::ListType type, bool secondStep, bool complete, bool hasInbox, const QString& path, KPIM::ProgressItem* item ) : FolderJob( 0, tOther, (storage ? storage->folder() : 0) ), mStorage( storage ), mAccount( account ), mType( type ), mHasInbox( hasInbox ), mSecondStep( secondStep ), mComplete( complete ), mHonorLocalSubscription( false ), mPath( path ), mParentProgressItem( item ) { } ListJob::~ListJob() { // kdDebug(5006 ) << k_funcinfo << kdBacktrace() << endl; } void ListJob::execute() { if ( mAccount->makeConnection() == ImapAccountBase::Error ) { kdWarning(5006) << "ListJob - got no connection" << endl; deleteLater(); return; } else if ( mAccount->makeConnection() == ImapAccountBase::Connecting ) { // We'll wait for the connectionResult signal from the account. kdDebug(5006) << "ListJob - waiting for connection" << endl; connect( mAccount, SIGNAL( connectionResult(int, const QString&) ), this, SLOT( slotConnectionResult(int, const QString&) ) ); return; } // this is needed until we have a common base class for d(imap) if ( mPath.isEmpty() ) { if ( mStorage && mStorage->folderType() == KMFolderTypeImap ) { mPath = static_cast<KMFolderImap*>(mStorage)->imapPath(); } else if ( mStorage && mStorage->folderType() == KMFolderTypeCachedImap ) { mPath = static_cast<KMFolderCachedImap*>(mStorage)->imapPath(); } else { kdError(5006) << "ListJob - no valid path and no folder given" << endl; deleteLater(); return; } } // create jobData ImapAccountBase::jobData jd; jd.total = 1; jd.done = 0; jd.cancellable = true; jd.createInbox = ( mSecondStep && !mHasInbox ) ? true : false; jd.parent = mDestFolder; jd.onlySubscribed = ( mType != ImapAccountBase::List ); jd.path = mPath; QString status = mDestFolder ? mDestFolder->prettyURL() : QString::null; if ( mParentProgressItem ) { jd.progressItem = ProgressManager::createProgressItem( mParentProgressItem, "ListDir" + ProgressManager::getUniqueID(), status, i18n("retrieving folders"), false, mAccount->useSSL() || mAccount->useTLS() ); mParentProgressItem->setStatus( status ); } // this is needed if you have a prefix // as the INBOX is located in your root ("/") and needs a special listing jd.inboxOnly = !mSecondStep && mAccount->prefix() != "/" && mPath == mAccount->prefix() && !mHasInbox; // make the URL QString ltype = "LIST"; if ( mType == ImapAccountBase::ListSubscribed ) ltype = "LSUB"; else if ( mType == ImapAccountBase::ListSubscribedNoCheck ) ltype = "LSUBNOCHECK"; KURL url = mAccount->getUrl(); url.setPath( ( jd.inboxOnly ? QString("/") : mPath ) + ";TYPE=" + ltype + ( mComplete ? ";SECTION=COMPLETE" : QString::null) ); // go KIO::SimpleJob *job = KIO::listDir( url, false ); KIO::Scheduler::assignJobToSlave( mAccount->slave(), job ); mAccount->insertJob( job, jd ); connect( job, SIGNAL(result(KIO::Job *)), this, SLOT(slotListResult(KIO::Job *)) ); connect( job, SIGNAL(entries(KIO::Job *, const KIO::UDSEntryList &)), this, SLOT(slotListEntries(KIO::Job *, const KIO::UDSEntryList &)) ); } void ListJob::slotConnectionResult( int errorCode, const QString& errorMsg ) { Q_UNUSED( errorMsg ); if ( !errorCode ) execute(); else { if ( mParentProgressItem ) mParentProgressItem->setComplete(); deleteLater(); } } void ListJob::slotListResult( KIO::Job* job ) { ImapAccountBase::JobIterator it = mAccount->findJob( job ); if ( it == mAccount->jobsEnd() ) { deleteLater(); return; } if ( job->error() ) { mAccount->handleJobError( job, i18n( "Error while listing folder %1: " ).arg((*it).path), true ); } else { // transport the information, include the jobData emit receivedFolders( mSubfolderNames, mSubfolderPaths, mSubfolderMimeTypes, mSubfolderAttributes, *it ); mAccount->removeJob( it ); } deleteLater(); } void ListJob::slotListEntries( KIO::Job* job, const KIO::UDSEntryList& uds ) { ImapAccountBase::JobIterator it = mAccount->findJob( job ); if ( it == mAccount->jobsEnd() ) { deleteLater(); return; } if( (*it).progressItem ) (*it).progressItem->setProgress( 50 ); QString name; KURL url; QString mimeType; QString attributes; for ( KIO::UDSEntryList::ConstIterator udsIt = uds.begin(); udsIt != uds.end(); udsIt++ ) { mimeType = QString::null; attributes = QString::null; for ( KIO::UDSEntry::ConstIterator eIt = (*udsIt).begin(); eIt != (*udsIt).end(); eIt++ ) { // get the needed information if ( (*eIt).m_uds == KIO::UDS_NAME ) name = (*eIt).m_str; else if ( (*eIt).m_uds == KIO::UDS_URL ) url = KURL((*eIt).m_str, 106); // utf-8 else if ( (*eIt).m_uds == KIO::UDS_MIME_TYPE ) mimeType = (*eIt).m_str; else if ( (*eIt).m_uds == KIO::UDS_EXTRA ) attributes = (*eIt).m_str; } if ( (mimeType == "inode/directory" || mimeType == "message/digest" || mimeType == "message/directory") && name != ".." && (mAccount->hiddenFolders() || name.at(0) != '.') && (!(*it).inboxOnly || name.upper() == "INBOX") ) { if ( ((*it).inboxOnly || url.path() == "/INBOX/") && name.upper() == "INBOX" && !mHasInbox ) { // our INBOX (*it).createInbox = true; } if ( mHonorLocalSubscription && mAccount->onlyLocallySubscribedFolders() && !mAccount->locallySubscribedTo( url.path() ) ) { continue; } // Some servers send _lots_ of duplicates // This check is too slow for huge lists if ( mSubfolderPaths.count() > 100 || mSubfolderPaths.findIndex(url.path()) == -1 ) { mSubfolderNames.append( name ); mSubfolderPaths.append( url.path() ); mSubfolderMimeTypes.append( mimeType ); mSubfolderAttributes.append( attributes ); } } } } void KMail::ListJob::setHonorLocalSubscription( bool value ) { mHonorLocalSubscription = value; } bool KMail::ListJob::honorLocalSubscription() const { return mHonorLocalSubscription; } #include "listjob.moc" <|endoftext|>
<commit_before>#include "source_map.hpp" #ifndef SASS_CONTEXT #include "context.hpp" #endif #include <string> #include <sstream> #include <cstddef> #include <iomanip> namespace Sass { using std::ptrdiff_t; SourceMap::SourceMap(const string& file) : current_position(Position(1, 1)), file(file) { } // taken from http://stackoverflow.com/a/7725289/1550314 std::string encodeJsonString(const std::string& input) { std::ostringstream ss; for (std::string::const_iterator iter = input.begin(); iter != input.end(); iter++) { switch (*iter) { case '\\': ss << "\\\\"; break; case '"': ss << "\\\""; break; case '\b': ss << "\\b"; break; case '\f': ss << "\\f"; break; case '\n': ss << "\\n"; break; case '\r': ss << "\\r"; break; case '\t': ss << "\\t"; break; // is a legal escape in JSON case '/': ss << "\\/"; break; default: ss << *iter; break; } } return ss.str(); } string SourceMap::generate_source_map() { string result = "{\n"; result += " \"version\": 3,\n"; result += " \"file\": \"" + encodeJsonString(file) + "\",\n"; result += " \"sources\": ["; for (size_t i = 0; i < files.size(); ++i) { result+="\"" + encodeJsonString(files[i]) + "\","; } if (!files.empty()) result.erase(result.length() - 1); result += "],\n"; result += " \"names\": [],\n"; result += " \"mappings\": \"" + serialize_mappings() + "\"\n"; result += "}"; return result; } string SourceMap::serialize_mappings() { string result = ""; size_t previous_generated_line = 0; size_t previous_generated_column = 0; size_t previous_original_line = 0; size_t previous_original_column = 0; size_t previous_original_file = 0; for (size_t i = 0; i < mappings.size(); ++i) { const size_t generated_line = mappings[i].generated_position.line - 1; const size_t generated_column = mappings[i].generated_position.column - 1; const size_t original_line = mappings[i].original_position.line - 1; const size_t original_column = mappings[i].original_position.column - 1; const size_t original_file = mappings[i].original_position.file - 1; if (generated_line != previous_generated_line) { previous_generated_column = 0; while (generated_line != previous_generated_line) { result += ";"; previous_generated_line += 1; } } else { if (i > 0) result += ","; } // generated column result += base64vlq.encode(static_cast<int>(generated_column) - static_cast<int>(previous_generated_column)); previous_generated_column = generated_column; // file result += base64vlq.encode(static_cast<int>(original_file) - static_cast<int>(previous_original_file)); previous_original_file = original_file; // source line result += base64vlq.encode(static_cast<int>(original_line) - static_cast<int>(previous_original_line)); previous_original_line = original_line; // source column result += base64vlq.encode(static_cast<int>(original_column) - static_cast<int>(previous_original_column)); previous_original_column = original_column; } return result; } void SourceMap::remove_line() { current_position.line -= 1; current_position.column = 1; } void SourceMap::update_column(const string& str) { const ptrdiff_t new_line_count = std::count(str.begin(), str.end(), '\n'); current_position.line += new_line_count; if (new_line_count >= 1) { current_position.column = str.size() - str.find_last_of('\n'); } else { current_position.column += str.size(); } } void SourceMap::add_mapping(AST_Node* node) { mappings.push_back(Mapping(node->position(), current_position)); } } <commit_msg>Fixes source map generating (#586)<commit_after>#include "source_map.hpp" #ifndef SASS_CONTEXT #include "context.hpp" #endif #include <string> #include <sstream> #include <cstddef> #include <iomanip> namespace Sass { using std::ptrdiff_t; SourceMap::SourceMap(const string& file) : current_position(Position(1, 1)), file(file) { } // taken from http://stackoverflow.com/a/7725289/1550314 std::string encodeJsonString(const std::string& input) { std::ostringstream ss; for (std::string::const_iterator iter = input.begin(); iter != input.end(); iter++) { switch (*iter) { case '\\': ss << "\\\\"; break; case '"': ss << "\\\""; break; case '\b': ss << "\\b"; break; case '\f': ss << "\\f"; break; case '\n': ss << "\\n"; break; case '\r': ss << "\\r"; break; case '\t': ss << "\\t"; break; // is a legal escape in JSON case '/': ss << "\\/"; break; default: ss << *iter; break; } } return ss.str(); } string SourceMap::generate_source_map() { string result = "{\n"; result += " \"version\": 3,\n"; result += " \"file\": \"" + encodeJsonString(file) + "\",\n"; result += " \"sources\": ["; for (size_t i = 0; i < files.size(); ++i) { result+="\"" + encodeJsonString(files[i]) + "\","; } if (!files.empty()) result.erase(result.length() - 1); result += "],\n"; result += " \"names\": [],\n"; result += " \"mappings\": \"" + serialize_mappings() + "\"\n"; result += "}"; return result; } string SourceMap::serialize_mappings() { string result = ""; size_t previous_generated_line = 0; size_t previous_generated_column = 0; size_t previous_original_line = 0; size_t previous_original_column = 0; size_t previous_original_file = 0; for (size_t i = 0; i < mappings.size(); ++i) { const size_t generated_line = mappings[i].generated_position.line - 1; const size_t generated_column = mappings[i].generated_position.column - 1; const size_t original_line = mappings[i].original_position.line - 1; const size_t original_column = mappings[i].original_position.column - 1; const size_t original_file = mappings[i].original_position.file - 1; if (generated_line != previous_generated_line) { previous_generated_column = 0; if (generated_line > previous_generated_line) { result += std::string(generated_line - previous_generated_line, ';'); previous_generated_line = generated_line; } } else if (i > 0) { result += ","; } // generated column result += base64vlq.encode(static_cast<int>(generated_column) - static_cast<int>(previous_generated_column)); previous_generated_column = generated_column; // file result += base64vlq.encode(static_cast<int>(original_file) - static_cast<int>(previous_original_file)); previous_original_file = original_file; // source line result += base64vlq.encode(static_cast<int>(original_line) - static_cast<int>(previous_original_line)); previous_original_line = original_line; // source column result += base64vlq.encode(static_cast<int>(original_column) - static_cast<int>(previous_original_column)); previous_original_column = original_column; } return result; } void SourceMap::remove_line() { // prevent removing non existing lines if (current_position.line > 1) { current_position.line -= 1; current_position.column = 1; } } void SourceMap::update_column(const string& str) { const ptrdiff_t new_line_count = std::count(str.begin(), str.end(), '\n'); current_position.line += new_line_count; if (new_line_count > 0) { current_position.column = str.size() - str.find_last_of('\n'); } else { current_position.column += str.size(); } } void SourceMap::add_mapping(AST_Node* node) { mappings.push_back(Mapping(node->position(), current_position)); } } <|endoftext|>
<commit_before>#include "photoeffects.hpp" using namespace cv; int warmify(cv::InputArray src, cv::OutputArray dst, uchar delta) { CV_Assert(src.type() == CV_8UC3); Mat imgSrc = src.getMat(); CV_Assert(imgSrc.data); dst.create(src.size(), CV_8UC3); Mat imgDst = dst.getMat(); Vec3b intensity, intensityNew; for (int i = 0; i < imgSrc.rows; i++) { for (int j = 0; j < imgSrc.cols; j++) { intensity = imgSrc.at<Vec3b>(i, j); intensityNew[0] = intensity[0]; uchar g = (intensity[1] + delta) >> 8; uchar r = (intensity[2] + delta) >> 8; intensityNew[1] = g * 255 + (1 - g) * intensity[1] + (1 - g) * delta; intensityNew[2] = r * 255 + (1 - r) * intensity[2] + (1 - r) * delta; imgDst.at<Vec3b>(i, j) = intensityNew; } } return 0; } <commit_msg>warmify.cpp changed by using OpenCV methods<commit_after>#include "photoeffects.hpp" using namespace cv; int warmify(cv::InputArray src, cv::OutputArray dst, uchar delta) { CV_Assert(src.type() == CV_8UC3); Mat imgSrc = src.getMat(); CV_Assert(imgSrc.data); dst.create(src.size(), CV_8UC3); Mat imgDst = dst.getMat(); Mat warmifyMat(src.size(), CV_8UC3, Scalar(0, delta, delta)); imgDst = imgSrc + warmifyMat; return 0; }<|endoftext|>
<commit_before>/** Copyright 2017 Daniel Garcia Vaglio degv364@gmail.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **/ //We must know the size during compilation time, to avoid using dynamic allocation #define SAMPLES_PER_SECOND 5 #define MEAN_SECONDS 5 #define MAX_SAMPLES (SAMPLES_PER_SECOND*(MEAN_SECONDS+1)) #define MEAN_SAMPLES (SAMPLES_PER_SECOND * MEAN_SECONDS) #ifndef HI_DEF #define HI_DEF typedef enum hi_return_e{ HI_RETURN_OK, HI_RETURN_FAIL, HI_RETURN_CRITICAL, HI_RETURN_BAD_PARAM } hi_return_e; #endif <commit_msg>state and events definition<commit_after>/** Copyright 2017 Daniel Garcia Vaglio degv364@gmail.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **/ //We must know the size during compilation time, to avoid using dynamic allocation #define SAMPLES_PER_SECOND 5 #define MEAN_SECONDS 5 #define MAX_SAMPLES (SAMPLES_PER_SECOND*(MEAN_SECONDS+1)) #define MEAN_SAMPLES (SAMPLES_PER_SECOND * MEAN_SECONDS) #ifndef HI_DEF #define HI_DEF // Return values typedef enum hi_return_e{ HI_RETURN_OK = 0, // Execution succesful HI_RETURN_FAIL, // Execution failed HI_RETURN_CRITICAL, // Critical fail HI_RETURN_BAD_PARAM // Execution failed due to invalid parameters } hi_return_e; // States typedef enum hi_state_e{ HI_STATE_NONE = 0, // No state HI_STATE_INIT, // Initialize peripherals HI_STATE_ALIVE_SEQ, // Functioning confirmation HI_STATE_ON, // Lamp ON HI_STATE_OFF, // Lamp OFF HI_STATE_DEINIT, // Deinitialize HI_STATE_FAIL, // Failure ocured, handle it HI_STATE_MANUAL_CONTROL, // Manual button state HI_NOSTATE_LAST // For range validation } hi_state_e; // External events, triggers for state transition typedef enum hi_ext_event_e{ HI_EXT_EVENT_NONE = 0, //NO event HI_EXT_EVENT_BOOT, //Boot HI_EXT_EVENT_LIGHTS_ON, //External lights on HI_EXT_EVENT_LIGHTS_OFF, //External lights off HI_EXT_EVENT_SOUND_LOW, // External sound is below treshhold HI_EXT_EVENT_SOUND_HIGH, //External sound increased HI_EXT_EVENT_CONTROL_REQ, // User pusehd button, manual control request HI_NO_EXT_EVENT_LAST // For range validation } hi_ext_event_e; #endif <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief RX programmer クラス @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2016, 2018 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "rx63t_protocol.hpp" #include "rx24t_protocol.hpp" #include "rx64m_protocol.hpp" #include "rx65x_protocol.hpp" #include <boost/format.hpp> #include <boost/variant.hpp> namespace rx { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief rx_prog クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// class prog { bool verbose_; typedef utils::rs232c_io RS232C; RS232C rs232c_; using protocol_type = boost::variant<rx63t::protocol, rx24t::protocol, rx64m::protocol, rx65x::protocol>; protocol_type protocol_; std::string out_section_(uint32_t n, uint32_t num) const { return (boost::format("#%02d/%02d: ") % n % num).str(); } struct bind_visitor { using result_type = bool; const std::string& path_; uint32_t brate_; const rx::protocol::rx_t& rx_; bind_visitor(const std::string& path, uint32_t brate, const rx::protocol::rx_t& rx) : path_(path), brate_(brate), rx_(rx) { } template <class T> bool operator()(T& x) { return x.bind(path_, brate_, rx_); } }; struct erase_page_visitor { using result_type = bool; uint32_t adr_; erase_page_visitor(uint32_t adr) : adr_(adr) { } template <class T> bool operator()(T& x) { return x.erase_page(adr_); } }; struct read_page_visitor { using result_type = bool; uint32_t adr_; uint8_t* dst_; read_page_visitor(uint32_t adr, uint8_t* dst) : adr_(adr), dst_(dst) { } template <class T> bool operator()(T& x) { return x.read_page(adr_, dst_); } }; struct select_write_visitor { using result_type = bool; bool data_; select_write_visitor(bool data) : data_(data) { } template <class T> bool operator()(T& x) { return x.select_write_area(data_); } }; struct write_visitor { using result_type = bool; uint32_t adr_; const uint8_t* src_; write_visitor(uint32_t adr, const uint8_t* src) : adr_(adr), src_(src) { } template <class T> bool operator()(T& x) { return x.write_page(adr_, src_); } }; struct end_visitor { using result_type = void; template <class T> void operator()(T& x) { x.end(); } }; public: //-------------------------------------------------------------// /*! @brief コンストラクター */ //-------------------------------------------------------------// prog(bool verbose = false) : verbose_(verbose) { } //-------------------------------------------------------------// /*! @brief 接続速度を変更する @param[in] path シリアル・デバイス・パス @param[in] brate ボーレート @param[in] rx CPU 設定 @return エラー無ければ「true」 */ //-------------------------------------------------------------// bool start(const std::string& path, uint32_t brate, const rx::protocol::rx_t& rx) { if(rx.cpu_type_ == "RX63T") { protocol_ = rx63t::protocol(); } else if(rx.cpu_type_ == "RX24T") { protocol_ = rx24t::protocol(); } else if(rx.cpu_type_ == "RX64M" || rx.cpu_type_ == "RX71M") { protocol_ = rx64m::protocol(); } else if(rx.cpu_type_ == "RX651" || rx.cpu_type_ == "RX65N") { protocol_ = rx65x::protocol(); } else { std::cerr << "CPU type missmatch: '" << rx.cpu_type_ << "'" << std::endl; return false; } { // 開始 bind_visitor vis(path, brate, rx); if(!boost::apply_visitor(vis, protocol_)) { end(); return false; } } return true; } //-------------------------------------------------------------// /*! @brief ページ消去 @param[in] adr 開始アドレス @return 成功なら「true」 */ //-------------------------------------------------------------// bool erase_page(uint32_t adr) { erase_page_visitor vis(adr); if(!boost::apply_visitor(vis, protocol_)) { end(); std::cerr << std::endl << boost::format("Erase page error: %08X") % adr << std::endl; return false; } return true; } //-------------------------------------------------------------// /*! @brief リード・ページ(256バイト) @param[in] adr 開始アドレス @param[out] dst 書き込みアドレス @return 成功なら「true」 */ //-------------------------------------------------------------// bool read_page(uint32_t adr, uint8_t* dst) { read_page_visitor vis(adr, dst); if(!boost::apply_visitor(vis, protocol_)) { end(); std::cerr << "Read page error." << std::endl; return false; } return true; } //-------------------------------------------------------------// /*! @brief ベリファイ・ページ(256バイト) @param[in] adr 開始アドレス @param[in] src 書き込みアドレス @return 成功なら「true」 */ //-------------------------------------------------------------// bool verify_page(uint32_t adr, const uint8_t* src) { uint8_t dev[256]; if(!read_page(adr, &dev[0])) { return false; } uint32_t errcnt = 0; for(uint32_t i = 0; i < 256; ++i) { auto m = *src++; if(dev[i] != m) { ++errcnt; if(verbose_) { std::cerr << (boost::format("0x%08X: D(%02X) to M(%02X)") % adr % static_cast<uint32_t>(dev[i]) % static_cast<uint32_t>(m)) << std::endl; } } ++adr; } if(errcnt > 0) { std::cerr << "Verify page error: " << errcnt << std::endl; return false; } return true; } //-------------------------------------------------------------// /*! @brief ライト開始 @param[in] data 「true」ならデータ領域 @return 成功なら「true」 */ //-------------------------------------------------------------// bool start_write(bool data) { select_write_visitor vis(data); if(!boost::apply_visitor(vis, protocol_)) { end(); std::cerr << "Write start error.(first)" << std::endl; return false; } return true; } //-------------------------------------------------------------// /*! @brief ライト(256バイト) @param[in] adr 開始アドレス @param[in] src 書き込みアドレス @return 成功なら「true」 */ //-------------------------------------------------------------// bool write(uint32_t adr, const uint8_t* src) { write_visitor vis(adr, src); if(!boost::apply_visitor(vis, protocol_)) { end(); std::cerr << "Write body error." << std::endl; return false; } return true; } //-------------------------------------------------------------// /*! @brief ライト終了 @return 成功なら「true」 */ //-------------------------------------------------------------// bool final_write() { write_visitor vis(0xffffffff, nullptr); if(!boost::apply_visitor(vis, protocol_)) { end(); std::cerr << "Write final error. (fin)" << std::endl; return false; } return true; } //-------------------------------------------------------------// /*! @brief 終了 */ //-------------------------------------------------------------// void end() { end_visitor vis; boost::apply_visitor(vis, protocol_); } }; } <commit_msg>update: RX66T protocol<commit_after>#pragma once //=====================================================================// /*! @file @brief RX programmer クラス @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2016, 2018 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "rx63t_protocol.hpp" #include "rx24t_protocol.hpp" #include "rx64m_protocol.hpp" #include "rx65x_protocol.hpp" #include "rx66t_protocol.hpp" #include <boost/format.hpp> #include <boost/variant.hpp> namespace rx { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief rx_prog クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// class prog { bool verbose_; typedef utils::rs232c_io RS232C; RS232C rs232c_; using protocol_type = boost::variant<rx63t::protocol, rx24t::protocol, rx64m::protocol, rx65x::protocol, rx66t::protocol>; protocol_type protocol_; std::string out_section_(uint32_t n, uint32_t num) const { return (boost::format("#%02d/%02d: ") % n % num).str(); } struct bind_visitor { using result_type = bool; const std::string& path_; uint32_t brate_; const rx::protocol::rx_t& rx_; bind_visitor(const std::string& path, uint32_t brate, const rx::protocol::rx_t& rx) : path_(path), brate_(brate), rx_(rx) { } template <class T> bool operator()(T& x) { return x.bind(path_, brate_, rx_); } }; struct erase_page_visitor { using result_type = bool; uint32_t adr_; erase_page_visitor(uint32_t adr) : adr_(adr) { } template <class T> bool operator()(T& x) { return x.erase_page(adr_); } }; struct read_page_visitor { using result_type = bool; uint32_t adr_; uint8_t* dst_; read_page_visitor(uint32_t adr, uint8_t* dst) : adr_(adr), dst_(dst) { } template <class T> bool operator()(T& x) { return x.read_page(adr_, dst_); } }; struct select_write_visitor { using result_type = bool; bool data_; select_write_visitor(bool data) : data_(data) { } template <class T> bool operator()(T& x) { return x.select_write_area(data_); } }; struct write_visitor { using result_type = bool; uint32_t adr_; const uint8_t* src_; write_visitor(uint32_t adr, const uint8_t* src) : adr_(adr), src_(src) { } template <class T> bool operator()(T& x) { return x.write_page(adr_, src_); } }; struct end_visitor { using result_type = void; template <class T> void operator()(T& x) { x.end(); } }; public: //-------------------------------------------------------------// /*! @brief コンストラクター */ //-------------------------------------------------------------// prog(bool verbose = false) : verbose_(verbose) { } //-------------------------------------------------------------// /*! @brief 接続速度を変更する @param[in] path シリアル・デバイス・パス @param[in] brate ボーレート @param[in] rx CPU 設定 @return エラー無ければ「true」 */ //-------------------------------------------------------------// bool start(const std::string& path, uint32_t brate, const rx::protocol::rx_t& rx) { if(rx.cpu_type_ == "RX63T") { protocol_ = rx63t::protocol(); } else if(rx.cpu_type_ == "RX24T") { protocol_ = rx24t::protocol(); } else if(rx.cpu_type_ == "RX64M" || rx.cpu_type_ == "RX71M") { protocol_ = rx64m::protocol(); } else if(rx.cpu_type_ == "RX651" || rx.cpu_type_ == "RX65N") { protocol_ = rx65x::protocol(); } else if(rx.cpu_type_ == "RX66T") { protocol_ = rx66t::protocol(); } else { std::cerr << "CPU type missmatch: '" << rx.cpu_type_ << "'" << std::endl; return false; } { // 開始 bind_visitor vis(path, brate, rx); if(!boost::apply_visitor(vis, protocol_)) { end(); return false; } } return true; } //-------------------------------------------------------------// /*! @brief ページ消去 @param[in] adr 開始アドレス @return 成功なら「true」 */ //-------------------------------------------------------------// bool erase_page(uint32_t adr) { erase_page_visitor vis(adr); if(!boost::apply_visitor(vis, protocol_)) { end(); std::cerr << std::endl << boost::format("Erase page error: %08X") % adr << std::endl; return false; } return true; } //-------------------------------------------------------------// /*! @brief リード・ページ(256バイト) @param[in] adr 開始アドレス @param[out] dst 書き込みアドレス @return 成功なら「true」 */ //-------------------------------------------------------------// bool read_page(uint32_t adr, uint8_t* dst) { read_page_visitor vis(adr, dst); if(!boost::apply_visitor(vis, protocol_)) { end(); std::cerr << "Read page error." << std::endl; return false; } return true; } //-------------------------------------------------------------// /*! @brief ベリファイ・ページ(256バイト) @param[in] adr 開始アドレス @param[in] src 書き込みアドレス @return 成功なら「true」 */ //-------------------------------------------------------------// bool verify_page(uint32_t adr, const uint8_t* src) { uint8_t dev[256]; if(!read_page(adr, &dev[0])) { return false; } uint32_t errcnt = 0; for(uint32_t i = 0; i < 256; ++i) { auto m = *src++; if(dev[i] != m) { ++errcnt; if(verbose_) { std::cerr << (boost::format("0x%08X: D(%02X) to M(%02X)") % adr % static_cast<uint32_t>(dev[i]) % static_cast<uint32_t>(m)) << std::endl; } } ++adr; } if(errcnt > 0) { std::cerr << "Verify page error: " << errcnt << std::endl; return false; } return true; } //-------------------------------------------------------------// /*! @brief ライト開始 @param[in] data 「true」ならデータ領域 @return 成功なら「true」 */ //-------------------------------------------------------------// bool start_write(bool data) { select_write_visitor vis(data); if(!boost::apply_visitor(vis, protocol_)) { end(); std::cerr << "Write start error.(first)" << std::endl; return false; } return true; } //-------------------------------------------------------------// /*! @brief ライト(256バイト) @param[in] adr 開始アドレス @param[in] src 書き込みアドレス @return 成功なら「true」 */ //-------------------------------------------------------------// bool write(uint32_t adr, const uint8_t* src) { write_visitor vis(adr, src); if(!boost::apply_visitor(vis, protocol_)) { end(); std::cerr << "Write body error." << std::endl; return false; } return true; } //-------------------------------------------------------------// /*! @brief ライト終了 @return 成功なら「true」 */ //-------------------------------------------------------------// bool final_write() { write_visitor vis(0xffffffff, nullptr); if(!boost::apply_visitor(vis, protocol_)) { end(); std::cerr << "Write final error. (fin)" << std::endl; return false; } return true; } //-------------------------------------------------------------// /*! @brief 終了 */ //-------------------------------------------------------------// void end() { end_visitor vis; boost::apply_visitor(vis, protocol_); } }; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: optutil.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: ihi $ $Date: 2006-08-04 12:11:15 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SC_OPTUTIL_HXX #define SC_OPTUTIL_HXX #ifndef _UTL_CONFIGITEM_HXX_ #include <unotools/configitem.hxx> #endif #ifndef _LINK_HXX #include <tools/link.hxx> #endif class ScOptionsUtil { public: static BOOL IsMetricSystem(); }; // ConfigItem for classes that use items from several sub trees class ScLinkConfigItem : public utl::ConfigItem { Link aCommitLink; public: ScLinkConfigItem( const rtl::OUString rSubTree ); ScLinkConfigItem( const rtl::OUString rSubTree, sal_Int16 nMode ); void SetCommitLink( const Link& rLink ); virtual void Notify( const com::sun::star::uno::Sequence<rtl::OUString>& aPropertyNames ); virtual void Commit(); void SetModified() { ConfigItem::SetModified(); } com::sun::star::uno::Sequence< com::sun::star::uno::Any> GetProperties(const com::sun::star::uno::Sequence< rtl::OUString >& rNames) { return ConfigItem::GetProperties( rNames ); } sal_Bool PutProperties( const com::sun::star::uno::Sequence< rtl::OUString >& rNames, const com::sun::star::uno::Sequence< com::sun::star::uno::Any>& rValues) { return ConfigItem::PutProperties( rNames, rValues ); } sal_Bool EnableNotification(com::sun::star::uno::Sequence< rtl::OUString >& rNames) { return ConfigItem::EnableNotification( rNames ); } com::sun::star::uno::Sequence< rtl::OUString > GetNodeNames(rtl::OUString& rNode) { return ConfigItem::GetNodeNames( rNode ); } }; #endif <commit_msg>INTEGRATION: CWS calcwarnings (1.3.88); FILE MERGED 2006/12/13 19:18:20 nn 1.3.88.1: #i69284# warning-free: core, unxsols4<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: optutil.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: vg $ $Date: 2007-02-27 11:57:02 $ * * 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 SC_OPTUTIL_HXX #define SC_OPTUTIL_HXX #ifndef _UTL_CONFIGITEM_HXX_ #include <unotools/configitem.hxx> #endif #ifndef _LINK_HXX #include <tools/link.hxx> #endif class ScOptionsUtil { public: static BOOL IsMetricSystem(); }; // ConfigItem for classes that use items from several sub trees class ScLinkConfigItem : public utl::ConfigItem { Link aCommitLink; public: ScLinkConfigItem( const rtl::OUString rSubTree ); ScLinkConfigItem( const rtl::OUString rSubTree, sal_Int16 nMode ); void SetCommitLink( const Link& rLink ); virtual void Notify( const com::sun::star::uno::Sequence<rtl::OUString>& aPropertyNames ); virtual void Commit(); void SetModified() { ConfigItem::SetModified(); } com::sun::star::uno::Sequence< com::sun::star::uno::Any> GetProperties(const com::sun::star::uno::Sequence< rtl::OUString >& rNames) { return ConfigItem::GetProperties( rNames ); } sal_Bool PutProperties( const com::sun::star::uno::Sequence< rtl::OUString >& rNames, const com::sun::star::uno::Sequence< com::sun::star::uno::Any>& rValues) { return ConfigItem::PutProperties( rNames, rValues ); } using ConfigItem::EnableNotification; using ConfigItem::GetNodeNames; // sal_Bool EnableNotification(com::sun::star::uno::Sequence< rtl::OUString >& rNames) // { return ConfigItem::EnableNotification( rNames ); } // com::sun::star::uno::Sequence< rtl::OUString > GetNodeNames(rtl::OUString& rNode) // { return ConfigItem::GetNodeNames( rNode ); } }; #endif <|endoftext|>
<commit_before>//--------------------------------------------------------------------*- C++ -*- // CLING - the C++ LLVM-based InterpreterG :) // author: Axel Naumann <axel@cern.ch> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "IncrementalExecutor.h" #include "IncrementalJIT.h" #include "Threading.h" #include "cling/Interpreter/Value.h" #include "cling/Interpreter/Transaction.h" #include "cling/Utils/AST.h" #include "clang/Basic/Diagnostic.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/PassManager.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/Triple.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/DynamicLibrary.h" #include "llvm/Support/Host.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Target/TargetMachine.h" #ifdef LLVM_ON_WIN32 extern "C" char *__unDName(char *demangled, const char *mangled, int out_len, void * (* pAlloc )(size_t), void (* pFree )(void *), unsigned short int flags); #else #include <cxxabi.h> #endif using namespace llvm; namespace cling { IncrementalExecutor::IncrementalExecutor(clang::DiagnosticsEngine& diags): m_CurrentAtExitModule(0) #if 0 : m_Diags(diags) #endif { // MSVC doesn't support m_AtExitFuncsSpinLock=ATOMIC_FLAG_INIT; in the class definition std::atomic_flag_clear( &m_AtExitFuncsSpinLock ); // No need to protect this access of m_AtExitFuncs, since nobody // can use this object yet. m_AtExitFuncs.reserve(256); m_JIT.reset(new IncrementalJIT(*this, std::move(CreateHostTargetMachine()))); } // Keep in source: ~unique_ptr<ClingJIT> needs ClingJIT IncrementalExecutor::~IncrementalExecutor() {} std::unique_ptr<TargetMachine> IncrementalExecutor::CreateHostTargetMachine() const { // TODO: make this configurable. Triple TheTriple(sys::getProcessTriple()); std::string Error; const Target *TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), Error); if (!TheTarget) { llvm::errs() << "cling::IncrementalExecutor: unable to find target:\n" << Error; } std::string MCPU; std::string FeaturesStr; TargetOptions Options = TargetOptions(); Options.NoFramePointerElim = 1; Options.JITEmitDebugInfo = 1; Reloc::Model RelocModel = Reloc::Default; CodeModel::Model CMModel = CodeModel::JITDefault; CodeGenOpt::Level OptLevel = CodeGenOpt::Less; std::unique_ptr<TargetMachine> TM; TM.reset(TheTarget->createTargetMachine(TheTriple.getTriple(), MCPU, FeaturesStr, Options, RelocModel, CMModel, OptLevel)); return std::move(TM); } void IncrementalExecutor::shuttingDown() { // No need to protect this access, since hopefully there is no concurrent // shutdown request. for (size_t I = 0, N = m_AtExitFuncs.size(); I < N; ++I) { const CXAAtExitElement& AEE = m_AtExitFuncs[N - I - 1]; (*AEE.m_Func)(AEE.m_Arg); } } void IncrementalExecutor::AddAtExitFunc(void (*func) (void*), void* arg) { // Register a CXAAtExit function cling::internal::SpinLockGuard slg(m_AtExitFuncsSpinLock); m_AtExitFuncs.push_back(CXAAtExitElement(func, arg, m_CurrentAtExitModule)); } void unresolvedSymbol() { // throw exception? llvm::errs() << "IncrementalExecutor: calling unresolved symbol, " "see previous error message!\n"; } void* IncrementalExecutor::HandleMissingFunction(const std::string& mangled_name) { // Not found in the map, add the symbol in the list of unresolved symbols if (m_unresolvedSymbols.insert(mangled_name).second) { //llvm::errs() << "IncrementalExecutor: use of undefined symbol '" // << mangled_name << "'!\n"; } // Avoid "ISO C++ forbids casting between pointer-to-function and // pointer-to-object": return (void*)reinterpret_cast<size_t>(unresolvedSymbol); } void* IncrementalExecutor::NotifyLazyFunctionCreators(const std::string& mangled_name) { for (std::vector<LazyFunctionCreatorFunc_t>::iterator it = m_lazyFuncCreator.begin(), et = m_lazyFuncCreator.end(); it != et; ++it) { void* ret = (void*)((LazyFunctionCreatorFunc_t)*it)(mangled_name); if (ret) return ret; } return HandleMissingFunction(mangled_name); } #if 0 // FIXME: employ to empty module dependencies *within* the *current* module. static void freeCallersOfUnresolvedSymbols(llvm::SmallVectorImpl<llvm::Function*>& funcsToFree, llvm::ExecutionEngine* engine) { llvm::SmallPtrSet<llvm::Function*, 40> funcsToFreeUnique; for (size_t i = 0; i < funcsToFree.size(); ++i) { llvm::Function* func = funcsToFree[i]; assert(func && "Cannot free NULL function"); if (funcsToFreeUnique.insert(func).second) { for (llvm::Value::use_iterator IU = func->use_begin(), EU = func->use_end(); IU != EU; ++IU) { llvm::Instruction* instUser = llvm::dyn_cast<llvm::Instruction>(*IU); if (!instUser) continue; if (!instUser->getParent()) continue; if (llvm::Function* userFunc = instUser->getParent()->getParent()) funcsToFree.push_back(userFunc); } } } for (llvm::SmallPtrSet<llvm::Function*, 40>::iterator I = funcsToFreeUnique.begin(), E = funcsToFreeUnique.end(); I != E; ++I) { // This should force the JIT to recompile the function. But the stubs stay, // and the JIT reuses the stubs now pointing nowhere, i.e. without updating // the machine code address. Fix the JIT, or hope that MCJIT helps. //engine->freeMachineCodeForFunction(*I); engine->updateGlobalMapping(*I, 0); } } #endif IncrementalExecutor::ExecutionResult IncrementalExecutor::runStaticInitializersOnce(const Transaction& T) { llvm::Module* m = T.getModule(); assert(m && "Module must not be null"); // Set m_CurrentAtExitModule to the Module, unset to 0 once done. struct AtExitModuleSetterRAII { llvm::Module*& m_AEM; AtExitModuleSetterRAII(llvm::Module* M, llvm::Module*& AEM): m_AEM(AEM) { AEM = M; } ~AtExitModuleSetterRAII() { m_AEM = 0; } } DSOHandleSetter(m, m_CurrentAtExitModule); // We don't care whether something was unresolved before. m_unresolvedSymbols.clear(); // check if there is any unresolved symbol in the list if (diagnoseUnresolvedSymbols("static initializers")) return kExeUnresolvedSymbols; llvm::GlobalVariable* GV = m->getGlobalVariable("llvm.global_ctors", true); // Nothing to do is good, too. if (!GV) return kExeSuccess; // Close similarity to // m_engine->runStaticConstructorsDestructors(false) aka // llvm::ExecutionEngine::runStaticConstructorsDestructors() // is intentional; we do an extra pass to check whether the JIT // managed to collect all the symbols needed by the niitializers. // Should be an array of '{ i32, void ()* }' structs. The first value is // the init priority, which we ignore. llvm::ConstantArray *InitList = llvm::dyn_cast<llvm::ConstantArray>(GV->getInitializer()); // We need to delete it here just in case we have recursive inits, otherwise // it will call inits multiple times. GV->eraseFromParent(); if (InitList == 0) return kExeSuccess; SmallVector<Function*, 2> initFuncs; for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) { llvm::ConstantStruct *CS = llvm::dyn_cast<llvm::ConstantStruct>(InitList->getOperand(i)); if (CS == 0) continue; llvm::Constant *FP = CS->getOperand(1); if (FP->isNullValue()) continue; // Found a sentinal value, ignore. // Strip off constant expression casts. if (llvm::ConstantExpr *CE = llvm::dyn_cast<llvm::ConstantExpr>(FP)) if (CE->isCast()) FP = CE->getOperand(0); // Execute the ctor/dtor function! if (llvm::Function *F = llvm::dyn_cast<llvm::Function>(FP)) { executeInit(F->getName()); initFuncs.push_back(F); if (F->getName().startswith("_GLOBAL__sub_I__")) { BasicBlock& BB = F->getEntryBlock(); for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I) if (CallInst* call = dyn_cast<CallInst>(I)) initFuncs.push_back(call->getCalledFunction()); } } } for (SmallVector<Function*,2>::iterator I = initFuncs.begin(), E = initFuncs.end(); I != E; ++I) { // Cleanup also the dangling init functions. They are in the form: // define internal void @_GLOBAL__I_aN() section "..."{ // entry: // call void @__cxx_global_var_init(N-1)() // call void @__cxx_global_var_initM() // ret void // } // // define internal void @__cxx_global_var_init(N-1)() section "..." { // entry: // call void @_ZN7MyClassC1Ev(%struct.MyClass* @n) // ret void // } // Erase __cxx_global_var_init(N-1)() first. (*I)->removeDeadConstantUsers(); (*I)->eraseFromParent(); } return kExeSuccess; } void IncrementalExecutor::runAndRemoveStaticDestructors(Transaction* T) { assert(T && "Must be set"); // Collect all the dtors bound to this transaction. AtExitFunctions boundToT; { cling::internal::SpinLockGuard slg(m_AtExitFuncsSpinLock); for (AtExitFunctions::iterator I = m_AtExitFuncs.begin(); I != m_AtExitFuncs.end();) if (I->m_FromM == T->getModule()) { boundToT.push_back(*I); I = m_AtExitFuncs.erase(I); } else ++I; } // end of spin lock lifetime block. // 'Unload' the cxa_atexit entities. for (AtExitFunctions::reverse_iterator I = boundToT.rbegin(), E = boundToT.rend(); I != E; ++I) { const CXAAtExitElement& AEE = *I; (*AEE.m_Func)(AEE.m_Arg); } } void IncrementalExecutor::installLazyFunctionCreator(LazyFunctionCreatorFunc_t fp) { m_lazyFuncCreator.push_back(fp); } bool IncrementalExecutor::addSymbol(const char* symbolName, void* symbolAddress) { void* actualAddress = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(symbolName); if (actualAddress) return false; llvm::sys::DynamicLibrary::AddSymbol(symbolName, symbolAddress); return true; } void* IncrementalExecutor::getAddressOfGlobal(llvm::StringRef symbolName, bool* fromJIT /*=0*/) { // Return a symbol's address, and whether it was jitted. void* address = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(symbolName); // It's not from the JIT if it's in a dylib. if (fromJIT) *fromJIT = !address; if (!address) return (void*)m_JIT->getSymbolAddress(symbolName); return address; } void* IncrementalExecutor::getPointerToGlobalFromJIT(const llvm::GlobalValue& GV) { // Get the function / variable pointer referenced by GV. // We don't care whether something was unresolved before. m_unresolvedSymbols.clear(); void* addr = (void*)m_JIT->getSymbolAddress(GV.getName()); if (diagnoseUnresolvedSymbols(GV.getName(), "symbol")) return 0; return addr; } bool IncrementalExecutor::diagnoseUnresolvedSymbols(llvm::StringRef trigger, llvm::StringRef title) { if (m_unresolvedSymbols.empty()) return false; llvm::SmallVector<llvm::Function*, 128> funcsToFree; for (std::set<std::string>::const_iterator i = m_unresolvedSymbols.begin(), e = m_unresolvedSymbols.end(); i != e; ++i) { #if 0 // FIXME: This causes a lot of test failures, for some reason it causes // the call to HandleMissingFunction to be elided. unsigned diagID = m_Diags.getCustomDiagID(clang::DiagnosticsEngine::Error, "%0 unresolved while jitting %1"); (void)diagID; //m_Diags.Report(diagID) << *i << funcname; // TODO: demangle the names. #endif llvm::errs() << "IncrementalExecutor::executeFunction: symbol '" << *i << "' unresolved while linking "; if (trigger.find(utils::Synthesize::UniquePrefix) != llvm::StringRef::npos) llvm::errs() << "[cling interface function]"; else { if (!title.empty()) llvm::errs() << title << " '"; llvm::errs() << trigger; if (!title.empty()) llvm::errs() << "'"; } llvm::errs() << "!\n"; // Be helpful, demangle! std::string demangledName; { #ifndef LLVM_ON_WIN32 int status = 0; char *demang = abi::__cxa_demangle(i->c_str(), 0, 0, &status); if (status == 0) demangledName = demang; free(demang); #else if (char* demang = __unDName(0, i->c_str(), 0, malloc, free, 0)) { demangledName = demang; free(demang); } #endif } if (!demangledName.empty()) { llvm::errs() << "You are probably missing the definition of " << demangledName << "\n" << "Maybe you need to load the corresponding shared library?\n"; } //llvm::Function *ff = m_engine->FindFunctionNamed(i->c_str()); // i could also reference a global variable, in which case ff == 0. //if (ff) // funcsToFree.push_back(ff); } //freeCallersOfUnresolvedSymbols(funcsToFree, m_engine.get()); m_unresolvedSymbols.clear(); return true; } }// end namespace cling <commit_msg>Fix object format on Windows (thanks Axel for the hint!)<commit_after>//--------------------------------------------------------------------*- C++ -*- // CLING - the C++ LLVM-based InterpreterG :) // author: Axel Naumann <axel@cern.ch> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "IncrementalExecutor.h" #include "IncrementalJIT.h" #include "Threading.h" #include "cling/Interpreter/Value.h" #include "cling/Interpreter/Transaction.h" #include "cling/Utils/AST.h" #include "clang/Basic/Diagnostic.h" #include "llvm/IR/Constants.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/PassManager.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/Triple.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/DynamicLibrary.h" #include "llvm/Support/Host.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Target/TargetMachine.h" #ifdef LLVM_ON_WIN32 extern "C" char *__unDName(char *demangled, const char *mangled, int out_len, void * (* pAlloc )(size_t), void (* pFree )(void *), unsigned short int flags); #else #include <cxxabi.h> #endif using namespace llvm; namespace cling { IncrementalExecutor::IncrementalExecutor(clang::DiagnosticsEngine& diags): m_CurrentAtExitModule(0) #if 0 : m_Diags(diags) #endif { // MSVC doesn't support m_AtExitFuncsSpinLock=ATOMIC_FLAG_INIT; in the class definition std::atomic_flag_clear( &m_AtExitFuncsSpinLock ); // No need to protect this access of m_AtExitFuncs, since nobody // can use this object yet. m_AtExitFuncs.reserve(256); m_JIT.reset(new IncrementalJIT(*this, std::move(CreateHostTargetMachine()))); } // Keep in source: ~unique_ptr<ClingJIT> needs ClingJIT IncrementalExecutor::~IncrementalExecutor() {} std::unique_ptr<TargetMachine> IncrementalExecutor::CreateHostTargetMachine() const { // TODO: make this configurable. Triple TheTriple(sys::getProcessTriple()); #ifdef _WIN32 /* * MCJIT works on Windows, but currently only through ELF object format. */ TheTriple.setObjectFormat(llvm::Triple::ELF); #endif std::string Error; const Target *TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), Error); if (!TheTarget) { llvm::errs() << "cling::IncrementalExecutor: unable to find target:\n" << Error; } std::string MCPU; std::string FeaturesStr; TargetOptions Options = TargetOptions(); Options.NoFramePointerElim = 1; Options.JITEmitDebugInfo = 1; Reloc::Model RelocModel = Reloc::Default; CodeModel::Model CMModel = CodeModel::JITDefault; CodeGenOpt::Level OptLevel = CodeGenOpt::Less; std::unique_ptr<TargetMachine> TM; TM.reset(TheTarget->createTargetMachine(TheTriple.getTriple(), MCPU, FeaturesStr, Options, RelocModel, CMModel, OptLevel)); return std::move(TM); } void IncrementalExecutor::shuttingDown() { // No need to protect this access, since hopefully there is no concurrent // shutdown request. for (size_t I = 0, N = m_AtExitFuncs.size(); I < N; ++I) { const CXAAtExitElement& AEE = m_AtExitFuncs[N - I - 1]; (*AEE.m_Func)(AEE.m_Arg); } } void IncrementalExecutor::AddAtExitFunc(void (*func) (void*), void* arg) { // Register a CXAAtExit function cling::internal::SpinLockGuard slg(m_AtExitFuncsSpinLock); m_AtExitFuncs.push_back(CXAAtExitElement(func, arg, m_CurrentAtExitModule)); } void unresolvedSymbol() { // throw exception? llvm::errs() << "IncrementalExecutor: calling unresolved symbol, " "see previous error message!\n"; } void* IncrementalExecutor::HandleMissingFunction(const std::string& mangled_name) { // Not found in the map, add the symbol in the list of unresolved symbols if (m_unresolvedSymbols.insert(mangled_name).second) { //llvm::errs() << "IncrementalExecutor: use of undefined symbol '" // << mangled_name << "'!\n"; } // Avoid "ISO C++ forbids casting between pointer-to-function and // pointer-to-object": return (void*)reinterpret_cast<size_t>(unresolvedSymbol); } void* IncrementalExecutor::NotifyLazyFunctionCreators(const std::string& mangled_name) { for (std::vector<LazyFunctionCreatorFunc_t>::iterator it = m_lazyFuncCreator.begin(), et = m_lazyFuncCreator.end(); it != et; ++it) { void* ret = (void*)((LazyFunctionCreatorFunc_t)*it)(mangled_name); if (ret) return ret; } return HandleMissingFunction(mangled_name); } #if 0 // FIXME: employ to empty module dependencies *within* the *current* module. static void freeCallersOfUnresolvedSymbols(llvm::SmallVectorImpl<llvm::Function*>& funcsToFree, llvm::ExecutionEngine* engine) { llvm::SmallPtrSet<llvm::Function*, 40> funcsToFreeUnique; for (size_t i = 0; i < funcsToFree.size(); ++i) { llvm::Function* func = funcsToFree[i]; assert(func && "Cannot free NULL function"); if (funcsToFreeUnique.insert(func).second) { for (llvm::Value::use_iterator IU = func->use_begin(), EU = func->use_end(); IU != EU; ++IU) { llvm::Instruction* instUser = llvm::dyn_cast<llvm::Instruction>(*IU); if (!instUser) continue; if (!instUser->getParent()) continue; if (llvm::Function* userFunc = instUser->getParent()->getParent()) funcsToFree.push_back(userFunc); } } } for (llvm::SmallPtrSet<llvm::Function*, 40>::iterator I = funcsToFreeUnique.begin(), E = funcsToFreeUnique.end(); I != E; ++I) { // This should force the JIT to recompile the function. But the stubs stay, // and the JIT reuses the stubs now pointing nowhere, i.e. without updating // the machine code address. Fix the JIT, or hope that MCJIT helps. //engine->freeMachineCodeForFunction(*I); engine->updateGlobalMapping(*I, 0); } } #endif IncrementalExecutor::ExecutionResult IncrementalExecutor::runStaticInitializersOnce(const Transaction& T) { llvm::Module* m = T.getModule(); assert(m && "Module must not be null"); // Set m_CurrentAtExitModule to the Module, unset to 0 once done. struct AtExitModuleSetterRAII { llvm::Module*& m_AEM; AtExitModuleSetterRAII(llvm::Module* M, llvm::Module*& AEM): m_AEM(AEM) { AEM = M; } ~AtExitModuleSetterRAII() { m_AEM = 0; } } DSOHandleSetter(m, m_CurrentAtExitModule); // We don't care whether something was unresolved before. m_unresolvedSymbols.clear(); // check if there is any unresolved symbol in the list if (diagnoseUnresolvedSymbols("static initializers")) return kExeUnresolvedSymbols; llvm::GlobalVariable* GV = m->getGlobalVariable("llvm.global_ctors", true); // Nothing to do is good, too. if (!GV) return kExeSuccess; // Close similarity to // m_engine->runStaticConstructorsDestructors(false) aka // llvm::ExecutionEngine::runStaticConstructorsDestructors() // is intentional; we do an extra pass to check whether the JIT // managed to collect all the symbols needed by the niitializers. // Should be an array of '{ i32, void ()* }' structs. The first value is // the init priority, which we ignore. llvm::ConstantArray *InitList = llvm::dyn_cast<llvm::ConstantArray>(GV->getInitializer()); // We need to delete it here just in case we have recursive inits, otherwise // it will call inits multiple times. GV->eraseFromParent(); if (InitList == 0) return kExeSuccess; SmallVector<Function*, 2> initFuncs; for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) { llvm::ConstantStruct *CS = llvm::dyn_cast<llvm::ConstantStruct>(InitList->getOperand(i)); if (CS == 0) continue; llvm::Constant *FP = CS->getOperand(1); if (FP->isNullValue()) continue; // Found a sentinal value, ignore. // Strip off constant expression casts. if (llvm::ConstantExpr *CE = llvm::dyn_cast<llvm::ConstantExpr>(FP)) if (CE->isCast()) FP = CE->getOperand(0); // Execute the ctor/dtor function! if (llvm::Function *F = llvm::dyn_cast<llvm::Function>(FP)) { executeInit(F->getName()); initFuncs.push_back(F); if (F->getName().startswith("_GLOBAL__sub_I__")) { BasicBlock& BB = F->getEntryBlock(); for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I) if (CallInst* call = dyn_cast<CallInst>(I)) initFuncs.push_back(call->getCalledFunction()); } } } for (SmallVector<Function*,2>::iterator I = initFuncs.begin(), E = initFuncs.end(); I != E; ++I) { // Cleanup also the dangling init functions. They are in the form: // define internal void @_GLOBAL__I_aN() section "..."{ // entry: // call void @__cxx_global_var_init(N-1)() // call void @__cxx_global_var_initM() // ret void // } // // define internal void @__cxx_global_var_init(N-1)() section "..." { // entry: // call void @_ZN7MyClassC1Ev(%struct.MyClass* @n) // ret void // } // Erase __cxx_global_var_init(N-1)() first. (*I)->removeDeadConstantUsers(); (*I)->eraseFromParent(); } return kExeSuccess; } void IncrementalExecutor::runAndRemoveStaticDestructors(Transaction* T) { assert(T && "Must be set"); // Collect all the dtors bound to this transaction. AtExitFunctions boundToT; { cling::internal::SpinLockGuard slg(m_AtExitFuncsSpinLock); for (AtExitFunctions::iterator I = m_AtExitFuncs.begin(); I != m_AtExitFuncs.end();) if (I->m_FromM == T->getModule()) { boundToT.push_back(*I); I = m_AtExitFuncs.erase(I); } else ++I; } // end of spin lock lifetime block. // 'Unload' the cxa_atexit entities. for (AtExitFunctions::reverse_iterator I = boundToT.rbegin(), E = boundToT.rend(); I != E; ++I) { const CXAAtExitElement& AEE = *I; (*AEE.m_Func)(AEE.m_Arg); } } void IncrementalExecutor::installLazyFunctionCreator(LazyFunctionCreatorFunc_t fp) { m_lazyFuncCreator.push_back(fp); } bool IncrementalExecutor::addSymbol(const char* symbolName, void* symbolAddress) { void* actualAddress = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(symbolName); if (actualAddress) return false; llvm::sys::DynamicLibrary::AddSymbol(symbolName, symbolAddress); return true; } void* IncrementalExecutor::getAddressOfGlobal(llvm::StringRef symbolName, bool* fromJIT /*=0*/) { // Return a symbol's address, and whether it was jitted. void* address = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(symbolName); // It's not from the JIT if it's in a dylib. if (fromJIT) *fromJIT = !address; if (!address) return (void*)m_JIT->getSymbolAddress(symbolName); return address; } void* IncrementalExecutor::getPointerToGlobalFromJIT(const llvm::GlobalValue& GV) { // Get the function / variable pointer referenced by GV. // We don't care whether something was unresolved before. m_unresolvedSymbols.clear(); void* addr = (void*)m_JIT->getSymbolAddress(GV.getName()); if (diagnoseUnresolvedSymbols(GV.getName(), "symbol")) return 0; return addr; } bool IncrementalExecutor::diagnoseUnresolvedSymbols(llvm::StringRef trigger, llvm::StringRef title) { if (m_unresolvedSymbols.empty()) return false; llvm::SmallVector<llvm::Function*, 128> funcsToFree; for (std::set<std::string>::const_iterator i = m_unresolvedSymbols.begin(), e = m_unresolvedSymbols.end(); i != e; ++i) { #if 0 // FIXME: This causes a lot of test failures, for some reason it causes // the call to HandleMissingFunction to be elided. unsigned diagID = m_Diags.getCustomDiagID(clang::DiagnosticsEngine::Error, "%0 unresolved while jitting %1"); (void)diagID; //m_Diags.Report(diagID) << *i << funcname; // TODO: demangle the names. #endif llvm::errs() << "IncrementalExecutor::executeFunction: symbol '" << *i << "' unresolved while linking "; if (trigger.find(utils::Synthesize::UniquePrefix) != llvm::StringRef::npos) llvm::errs() << "[cling interface function]"; else { if (!title.empty()) llvm::errs() << title << " '"; llvm::errs() << trigger; if (!title.empty()) llvm::errs() << "'"; } llvm::errs() << "!\n"; // Be helpful, demangle! std::string demangledName; { #ifndef LLVM_ON_WIN32 int status = 0; char *demang = abi::__cxa_demangle(i->c_str(), 0, 0, &status); if (status == 0) demangledName = demang; free(demang); #else if (char* demang = __unDName(0, i->c_str(), 0, malloc, free, 0)) { demangledName = demang; free(demang); } #endif } if (!demangledName.empty()) { llvm::errs() << "You are probably missing the definition of " << demangledName << "\n" << "Maybe you need to load the corresponding shared library?\n"; } //llvm::Function *ff = m_engine->FindFunctionNamed(i->c_str()); // i could also reference a global variable, in which case ff == 0. //if (ff) // funcsToFree.push_back(ff); } //freeCallersOfUnresolvedSymbols(funcsToFree, m_engine.get()); m_unresolvedSymbols.clear(); return true; } }// end namespace cling <|endoftext|>
<commit_before>/** * Copyright (C) 2005-2007 Christoph Rupp (chris@crupp.de). * All rights reserved. See file LICENSE for licence and copyright * information. * * unit tests for endian.h * */ #include <cppunit/extensions/HelperMacros.h> #include <ham/hamsterdb.h> #include "../src/os.h" #if WIN32 # include <windows.h> #else # include <unistd.h> #endif static void my_errhandler(const char *message) { (void)message; } class OsTest : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(OsTest); CPPUNIT_TEST (openCloseTest); CPPUNIT_TEST (openReadOnlyCloseTest); CPPUNIT_TEST (negativeOpenCloseTest); CPPUNIT_TEST (createCloseTest); CPPUNIT_TEST (createCloseOverwriteTest); CPPUNIT_TEST (closeTest); CPPUNIT_TEST (openExclusiveTest); CPPUNIT_TEST (readWriteTest); CPPUNIT_TEST (pagesizeTest); CPPUNIT_TEST (mmapTest); CPPUNIT_TEST (multipleMmapTest); CPPUNIT_TEST (negativeMmapTest); CPPUNIT_TEST (seekTellTest); CPPUNIT_TEST (negativeSeekTest); CPPUNIT_TEST (truncateTest); CPPUNIT_TEST (largefileTest); CPPUNIT_TEST_SUITE_END(); public: void setUp() { ham_set_errhandler(my_errhandler); } void tearDown() { #if WIN32 (void)DeleteFileA((LPCSTR)".test"); #else (void)unlink(".test"); #endif } void openCloseTest() { ham_status_t st; ham_fd_t fd; st=os_open("Makefile", 0, &fd); CPPUNIT_ASSERT(st==0); st=os_close(fd, 0); CPPUNIT_ASSERT(st==0); } void openReadOnlyCloseTest() { ham_status_t st; ham_fd_t fd; const char *p="# XXXXXXXXX ERROR\n"; st=os_open("Makefile", HAM_READ_ONLY, &fd); CPPUNIT_ASSERT(st==0); st=os_pwrite(fd, 0, p, (ham_size_t)strlen(p)); CPPUNIT_ASSERT(st==HAM_IO_ERROR); st=os_close(fd, 0); CPPUNIT_ASSERT(st==0); } void negativeOpenCloseTest() { ham_status_t st; ham_fd_t fd; st=os_open("__98324kasdlf.blöd", 0, &fd); CPPUNIT_ASSERT(st==HAM_FILE_NOT_FOUND); } void createCloseTest() { ham_status_t st; ham_fd_t fd; st=os_create(".test", 0, 0664, &fd); CPPUNIT_ASSERT_EQUAL(0, st); st=os_close(fd, 0); CPPUNIT_ASSERT_EQUAL(0, st); } void createCloseOverwriteTest() { ham_fd_t fd; ham_offset_t filesize; for (int i=0; i<3; i++) { CPPUNIT_ASSERT(os_create(".test", 0, 0664, &fd)==HAM_SUCCESS); CPPUNIT_ASSERT(os_seek(fd, 0, HAM_OS_SEEK_END)==HAM_SUCCESS); CPPUNIT_ASSERT(os_tell(fd, &filesize)==HAM_SUCCESS); CPPUNIT_ASSERT(filesize==0); CPPUNIT_ASSERT(os_truncate(fd, 1024)==HAM_SUCCESS); CPPUNIT_ASSERT(os_seek(fd, 0, HAM_OS_SEEK_END)==HAM_SUCCESS); CPPUNIT_ASSERT(os_tell(fd, &filesize)==HAM_SUCCESS); CPPUNIT_ASSERT(filesize==1024); CPPUNIT_ASSERT(os_close(fd, 0)==HAM_SUCCESS); } } void closeTest() { #ifndef WIN32 // crashs in ntdll.dll ham_status_t st; st=os_close((ham_fd_t)0x12345, 0); CPPUNIT_ASSERT(st==HAM_IO_ERROR); #endif } void openExclusiveTest() { ham_fd_t fd, fd2; CPPUNIT_ASSERT_EQUAL(0, os_create(".test", HAM_LOCK_EXCLUSIVE, 0664, &fd)); CPPUNIT_ASSERT_EQUAL(0, os_close(fd, HAM_LOCK_EXCLUSIVE)); CPPUNIT_ASSERT_EQUAL(0, os_open(".test", HAM_LOCK_EXCLUSIVE, &fd)); CPPUNIT_ASSERT_EQUAL(HAM_WOULD_BLOCK, os_open(".test", HAM_LOCK_EXCLUSIVE, &fd2)); CPPUNIT_ASSERT_EQUAL(0, os_close(fd, HAM_LOCK_EXCLUSIVE)); CPPUNIT_ASSERT_EQUAL(0, os_open(".test", HAM_LOCK_EXCLUSIVE, &fd2)); CPPUNIT_ASSERT_EQUAL(0, os_close(fd2, HAM_LOCK_EXCLUSIVE)); CPPUNIT_ASSERT_EQUAL(0, os_open(".test", 0, &fd2)); CPPUNIT_ASSERT_EQUAL(0, os_close(fd2, 0)); } void readWriteTest() { int i; ham_status_t st; ham_fd_t fd; char buffer[128], orig[128]; st=os_create(".test", 0, 0664, &fd); CPPUNIT_ASSERT(st==0); for (i=0; i<10; i++) { memset(buffer, i, sizeof(buffer)); st=os_pwrite(fd, i*sizeof(buffer), buffer, sizeof(buffer)); CPPUNIT_ASSERT(st==0); } for (i=0; i<10; i++) { memset(orig, i, sizeof(orig)); memset(buffer, 0, sizeof(buffer)); st=os_pread(fd, i*sizeof(buffer), buffer, sizeof(buffer)); CPPUNIT_ASSERT(st==0); CPPUNIT_ASSERT(0==memcmp(buffer, orig, sizeof(buffer))); } st=os_close(fd, 0); CPPUNIT_ASSERT(st==0); } void pagesizeTest() { ham_size_t ps=os_get_pagesize(); CPPUNIT_ASSERT(ps!=0); CPPUNIT_ASSERT(ps%1024==0); } void mmapTest() { int i; ham_status_t st; ham_fd_t fd, mmaph; ham_size_t ps=os_get_pagesize(); ham_u8_t *p1, *p2; p1=(ham_u8_t *)malloc(ps); st=os_create(".test", 0, 0664, &fd); CPPUNIT_ASSERT(st==0); for (i=0; i<10; i++) { memset(p1, i, ps); st=os_pwrite(fd, i*ps, p1, ps); CPPUNIT_ASSERT(st==0); } for (i=0; i<10; i++) { memset(p1, i, ps); st=os_mmap(fd, &mmaph, i*ps, ps, &p2); CPPUNIT_ASSERT(st==0); CPPUNIT_ASSERT(0==memcmp(p1, p2, ps)); st=os_munmap(&mmaph, p2, ps); CPPUNIT_ASSERT(st==0); } st=os_close(fd, 0); CPPUNIT_ASSERT(st==0); free(p1); } void multipleMmapTest() { int i; ham_status_t st; ham_fd_t fd, mmaph; ham_size_t ps=os_get_pagesize(); ham_u8_t *p1, *p2; ham_offset_t addr=0, size; st=os_create(".test", 0, 0664, &fd); CPPUNIT_ASSERT(st==0); for (i=0; i<5; i++) { size=ps*(i+1); p1=(ham_u8_t *)malloc((size_t)size); memset(p1, i, (size_t)size); st=os_pwrite(fd, addr, p1, (ham_size_t)size); CPPUNIT_ASSERT(st==0); free(p1); addr+=size; } addr=0; for (i=0; i<5; i++) { size=ps*(i+1); p1=(ham_u8_t *)malloc((size_t)size); memset(p1, i, (size_t)size); st=os_mmap(fd, &mmaph, addr, (ham_size_t)size, &p2); CPPUNIT_ASSERT(st==0); CPPUNIT_ASSERT(0==memcmp(p1, p2, (size_t)size)); st=os_munmap(&mmaph, p2, (ham_size_t)size); CPPUNIT_ASSERT(st==0); free(p1); addr+=size; } st=os_close(fd, 0); CPPUNIT_ASSERT(st==0); } void negativeMmapTest() { ham_status_t st; ham_fd_t fd, mmaph; ham_u8_t *page; st=os_create(".test", 0, 0664, &fd); CPPUNIT_ASSERT(st==0); st=os_mmap(fd, &mmaph, 33, 66, &page); // bad address && page size! CPPUNIT_ASSERT(st==HAM_IO_ERROR); st=os_close(fd, 0); CPPUNIT_ASSERT(st==0); } void seekTellTest() { int i; ham_status_t st; ham_fd_t fd; ham_offset_t tell; st=os_create(".test", 0, 0664, &fd); CPPUNIT_ASSERT(st==0); for (i=0; i<10; i++) { st=os_seek(fd, i, HAM_OS_SEEK_SET); CPPUNIT_ASSERT(st==0); st=os_tell(fd, &tell); CPPUNIT_ASSERT(st==0); CPPUNIT_ASSERT(tell==(ham_offset_t)i); } st=os_close(fd, 0); CPPUNIT_ASSERT(st==0); } void negativeSeekTest() { ham_status_t st; st=os_seek((ham_fd_t)0x12345, 0, HAM_OS_SEEK_SET); CPPUNIT_ASSERT(st==HAM_IO_ERROR); } void truncateTest() { int i; ham_status_t st; ham_fd_t fd; ham_offset_t fsize; st=os_create(".test", 0, 0664, &fd); CPPUNIT_ASSERT(st==0); for (i=0; i<10; i++) { st=os_truncate(fd, i*128); CPPUNIT_ASSERT(st==0); st=os_get_filesize(fd, &fsize); CPPUNIT_ASSERT(st==0); CPPUNIT_ASSERT(fsize==(ham_offset_t)(i*128)); } st=os_close(fd, 0); CPPUNIT_ASSERT(st==0); } void largefileTest() { int i; ham_status_t st; ham_fd_t fd; ham_u8_t kb[1024]; ham_offset_t tell; memset(kb, 0, sizeof(kb)); st=os_create(".test", 0, 0664, &fd); CPPUNIT_ASSERT(st==0); for (i=0; i<4*1024; i++) { st=os_pwrite(fd, i*sizeof(kb), kb, sizeof(kb)); CPPUNIT_ASSERT(st==0); } st=os_close(fd, 0); CPPUNIT_ASSERT(st==0); st=os_open(".test", 0, &fd); CPPUNIT_ASSERT(st==0); st=os_seek(fd, 0, HAM_OS_SEEK_END); CPPUNIT_ASSERT(st==0); st=os_tell(fd, &tell); CPPUNIT_ASSERT(st==0); CPPUNIT_ASSERT(tell==(ham_offset_t)1024*1024*4); st=os_close(fd, 0); CPPUNIT_ASSERT(st==0); } }; CPPUNIT_TEST_SUITE_REGISTRATION(OsTest); <commit_msg>disable EXCLUSIVE-test on cygwin<commit_after>/** * Copyright (C) 2005-2007 Christoph Rupp (chris@crupp.de). * All rights reserved. See file LICENSE for licence and copyright * information. * * unit tests for endian.h * */ #include <cppunit/extensions/HelperMacros.h> #include <ham/hamsterdb.h> #include "../src/os.h" #if WIN32 # include <windows.h> #else # include <unistd.h> #endif static void my_errhandler(const char *message) { (void)message; } class OsTest : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(OsTest); CPPUNIT_TEST (openCloseTest); CPPUNIT_TEST (openReadOnlyCloseTest); CPPUNIT_TEST (negativeOpenCloseTest); CPPUNIT_TEST (createCloseTest); CPPUNIT_TEST (createCloseOverwriteTest); CPPUNIT_TEST (closeTest); CPPUNIT_TEST (openExclusiveTest); CPPUNIT_TEST (readWriteTest); CPPUNIT_TEST (pagesizeTest); CPPUNIT_TEST (mmapTest); CPPUNIT_TEST (multipleMmapTest); CPPUNIT_TEST (negativeMmapTest); CPPUNIT_TEST (seekTellTest); CPPUNIT_TEST (negativeSeekTest); CPPUNIT_TEST (truncateTest); CPPUNIT_TEST (largefileTest); CPPUNIT_TEST_SUITE_END(); public: void setUp() { ham_set_errhandler(my_errhandler); } void tearDown() { #if WIN32 (void)DeleteFileA((LPCSTR)".test"); #else (void)unlink(".test"); #endif } void openCloseTest() { ham_status_t st; ham_fd_t fd; st=os_open("Makefile", 0, &fd); CPPUNIT_ASSERT(st==0); st=os_close(fd, 0); CPPUNIT_ASSERT(st==0); } void openReadOnlyCloseTest() { ham_status_t st; ham_fd_t fd; const char *p="# XXXXXXXXX ERROR\n"; st=os_open("Makefile", HAM_READ_ONLY, &fd); CPPUNIT_ASSERT(st==0); st=os_pwrite(fd, 0, p, (ham_size_t)strlen(p)); CPPUNIT_ASSERT(st==HAM_IO_ERROR); st=os_close(fd, 0); CPPUNIT_ASSERT(st==0); } void negativeOpenCloseTest() { ham_status_t st; ham_fd_t fd; st=os_open("__98324kasdlf.blöd", 0, &fd); CPPUNIT_ASSERT(st==HAM_FILE_NOT_FOUND); } void createCloseTest() { ham_status_t st; ham_fd_t fd; st=os_create(".test", 0, 0664, &fd); CPPUNIT_ASSERT_EQUAL(0, st); st=os_close(fd, 0); CPPUNIT_ASSERT_EQUAL(0, st); } void createCloseOverwriteTest() { ham_fd_t fd; ham_offset_t filesize; for (int i=0; i<3; i++) { CPPUNIT_ASSERT(os_create(".test", 0, 0664, &fd)==HAM_SUCCESS); CPPUNIT_ASSERT(os_seek(fd, 0, HAM_OS_SEEK_END)==HAM_SUCCESS); CPPUNIT_ASSERT(os_tell(fd, &filesize)==HAM_SUCCESS); CPPUNIT_ASSERT(filesize==0); CPPUNIT_ASSERT(os_truncate(fd, 1024)==HAM_SUCCESS); CPPUNIT_ASSERT(os_seek(fd, 0, HAM_OS_SEEK_END)==HAM_SUCCESS); CPPUNIT_ASSERT(os_tell(fd, &filesize)==HAM_SUCCESS); CPPUNIT_ASSERT(filesize==1024); CPPUNIT_ASSERT(os_close(fd, 0)==HAM_SUCCESS); } } void closeTest() { #ifndef WIN32 // crashs in ntdll.dll ham_status_t st; st=os_close((ham_fd_t)0x12345, 0); CPPUNIT_ASSERT(st==HAM_IO_ERROR); #endif } void openExclusiveTest() { /* fails on cygwin - cygwin bug? */ #ifndef __CYGWIN__ ham_fd_t fd, fd2; CPPUNIT_ASSERT_EQUAL(0, os_create(".test", HAM_LOCK_EXCLUSIVE, 0664, &fd)); CPPUNIT_ASSERT_EQUAL(0, os_close(fd, HAM_LOCK_EXCLUSIVE)); CPPUNIT_ASSERT_EQUAL(0, os_open(".test", HAM_LOCK_EXCLUSIVE, &fd)); CPPUNIT_ASSERT_EQUAL(HAM_WOULD_BLOCK, os_open(".test", HAM_LOCK_EXCLUSIVE, &fd2)); CPPUNIT_ASSERT_EQUAL(0, os_close(fd, HAM_LOCK_EXCLUSIVE)); CPPUNIT_ASSERT_EQUAL(0, os_open(".test", HAM_LOCK_EXCLUSIVE, &fd2)); CPPUNIT_ASSERT_EQUAL(0, os_close(fd2, HAM_LOCK_EXCLUSIVE)); CPPUNIT_ASSERT_EQUAL(0, os_open(".test", 0, &fd2)); CPPUNIT_ASSERT_EQUAL(0, os_close(fd2, 0)); #endif } void readWriteTest() { int i; ham_status_t st; ham_fd_t fd; char buffer[128], orig[128]; st=os_create(".test", 0, 0664, &fd); CPPUNIT_ASSERT(st==0); for (i=0; i<10; i++) { memset(buffer, i, sizeof(buffer)); st=os_pwrite(fd, i*sizeof(buffer), buffer, sizeof(buffer)); CPPUNIT_ASSERT(st==0); } for (i=0; i<10; i++) { memset(orig, i, sizeof(orig)); memset(buffer, 0, sizeof(buffer)); st=os_pread(fd, i*sizeof(buffer), buffer, sizeof(buffer)); CPPUNIT_ASSERT(st==0); CPPUNIT_ASSERT(0==memcmp(buffer, orig, sizeof(buffer))); } st=os_close(fd, 0); CPPUNIT_ASSERT(st==0); } void pagesizeTest() { ham_size_t ps=os_get_pagesize(); CPPUNIT_ASSERT(ps!=0); CPPUNIT_ASSERT(ps%1024==0); } void mmapTest() { int i; ham_status_t st; ham_fd_t fd, mmaph; ham_size_t ps=os_get_pagesize(); ham_u8_t *p1, *p2; p1=(ham_u8_t *)malloc(ps); st=os_create(".test", 0, 0664, &fd); CPPUNIT_ASSERT(st==0); for (i=0; i<10; i++) { memset(p1, i, ps); st=os_pwrite(fd, i*ps, p1, ps); CPPUNIT_ASSERT(st==0); } for (i=0; i<10; i++) { memset(p1, i, ps); st=os_mmap(fd, &mmaph, i*ps, ps, &p2); CPPUNIT_ASSERT(st==0); CPPUNIT_ASSERT(0==memcmp(p1, p2, ps)); st=os_munmap(&mmaph, p2, ps); CPPUNIT_ASSERT(st==0); } st=os_close(fd, 0); CPPUNIT_ASSERT(st==0); free(p1); } void multipleMmapTest() { int i; ham_status_t st; ham_fd_t fd, mmaph; ham_size_t ps=os_get_pagesize(); ham_u8_t *p1, *p2; ham_offset_t addr=0, size; st=os_create(".test", 0, 0664, &fd); CPPUNIT_ASSERT(st==0); for (i=0; i<5; i++) { size=ps*(i+1); p1=(ham_u8_t *)malloc((size_t)size); memset(p1, i, (size_t)size); st=os_pwrite(fd, addr, p1, (ham_size_t)size); CPPUNIT_ASSERT(st==0); free(p1); addr+=size; } addr=0; for (i=0; i<5; i++) { size=ps*(i+1); p1=(ham_u8_t *)malloc((size_t)size); memset(p1, i, (size_t)size); st=os_mmap(fd, &mmaph, addr, (ham_size_t)size, &p2); CPPUNIT_ASSERT(st==0); CPPUNIT_ASSERT(0==memcmp(p1, p2, (size_t)size)); st=os_munmap(&mmaph, p2, (ham_size_t)size); CPPUNIT_ASSERT(st==0); free(p1); addr+=size; } st=os_close(fd, 0); CPPUNIT_ASSERT(st==0); } void negativeMmapTest() { ham_status_t st; ham_fd_t fd, mmaph; ham_u8_t *page; st=os_create(".test", 0, 0664, &fd); CPPUNIT_ASSERT(st==0); st=os_mmap(fd, &mmaph, 33, 66, &page); // bad address && page size! CPPUNIT_ASSERT(st==HAM_IO_ERROR); st=os_close(fd, 0); CPPUNIT_ASSERT(st==0); } void seekTellTest() { int i; ham_status_t st; ham_fd_t fd; ham_offset_t tell; st=os_create(".test", 0, 0664, &fd); CPPUNIT_ASSERT(st==0); for (i=0; i<10; i++) { st=os_seek(fd, i, HAM_OS_SEEK_SET); CPPUNIT_ASSERT(st==0); st=os_tell(fd, &tell); CPPUNIT_ASSERT(st==0); CPPUNIT_ASSERT(tell==(ham_offset_t)i); } st=os_close(fd, 0); CPPUNIT_ASSERT(st==0); } void negativeSeekTest() { ham_status_t st; st=os_seek((ham_fd_t)0x12345, 0, HAM_OS_SEEK_SET); CPPUNIT_ASSERT(st==HAM_IO_ERROR); } void truncateTest() { int i; ham_status_t st; ham_fd_t fd; ham_offset_t fsize; st=os_create(".test", 0, 0664, &fd); CPPUNIT_ASSERT(st==0); for (i=0; i<10; i++) { st=os_truncate(fd, i*128); CPPUNIT_ASSERT(st==0); st=os_get_filesize(fd, &fsize); CPPUNIT_ASSERT(st==0); CPPUNIT_ASSERT(fsize==(ham_offset_t)(i*128)); } st=os_close(fd, 0); CPPUNIT_ASSERT(st==0); } void largefileTest() { int i; ham_status_t st; ham_fd_t fd; ham_u8_t kb[1024]; ham_offset_t tell; memset(kb, 0, sizeof(kb)); st=os_create(".test", 0, 0664, &fd); CPPUNIT_ASSERT(st==0); for (i=0; i<4*1024; i++) { st=os_pwrite(fd, i*sizeof(kb), kb, sizeof(kb)); CPPUNIT_ASSERT(st==0); } st=os_close(fd, 0); CPPUNIT_ASSERT(st==0); st=os_open(".test", 0, &fd); CPPUNIT_ASSERT(st==0); st=os_seek(fd, 0, HAM_OS_SEEK_END); CPPUNIT_ASSERT(st==0); st=os_tell(fd, &tell); CPPUNIT_ASSERT(st==0); CPPUNIT_ASSERT(tell==(ham_offset_t)1024*1024*4); st=os_close(fd, 0); CPPUNIT_ASSERT(st==0); } }; CPPUNIT_TEST_SUITE_REGISTRATION(OsTest); <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif // Software Guide : BeginLatex // // Let's assume that you have a KML file (hence in geographical coordinate) // that you would like to superpose to some image with a specific map projection. // Of course, you could use the handy ogr2ogr tool to do that, but it won't // integrate so seamlessly into your OTB application. // // You can also supposed that the image on which you want to superpose the data // is not in a specific map projection but a raw image from a specific sensor. // Thanks to OTB, the same code below will be able to do the appropriate // conversion. // // This example demonstrates the use of the // \doxygen{otb}{VectorDataProjectionFilter}. // // Software Guide : EndLatex #include "otbVectorDataProjectionFilter.h" #include "otbVectorData.h" #include "otbVectorDataFileReader.h" #include "otbVectorDataFileWriter.h" #include "otbImage.h" #include "otbImageFileReader.h" int main( int argc, char* argv[] ) { if(argc < 3 ) { std::cout << argv[0] <<" <input vector filename> <input image name> <output vector filename> " << std::endl; return EXIT_FAILURE; } // Software Guide : BeginLatex // // Declare the vector data type that you would like to use in your application // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::VectorData<double > InputVectorDataType; typedef otb::VectorData<double > OutputVectorDataType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Declare and instanciate the vector data reader: // \doxygen{otb}{VectorDataFileReader}. The call to the // \code{UpdateOutputInformation()} method fill up the header information. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::VectorDataFileReader<InputVectorDataType> VectorDataFileReaderType; VectorDataFileReaderType::Pointer reader = VectorDataFileReaderType::New(); reader->SetFileName(argv[1]); reader->UpdateOutputInformation(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We need the image only to retrieve its projection information, i.e. map projection // or sensor model parameters. Hence, the image pixels won't be read, only the header // information using the \code{UpdateOutputInformation()} method. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::Image<unsigned short int, 2> ImageType; typedef otb::ImageFileReader<ImageType> ImageReaderType; ImageReaderType::Pointer imageReader = ImageReaderType::New(); imageReader->SetFileName(argv[2]); imageReader->UpdateOutputInformation(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The \doxygen{otb}{VectorDataProjectionFilter} will do the work of converting the vector // data coordinates. It is usually a good idea to use it when you design applications // reading or saving vector data. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::VectorDataProjectionFilter<InputVectorDataType,OutputVectorDataType> VectorDataFilterType; VectorDataFilterType::Pointer vectorDataProjection = VectorDataFilterType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Information concerning the original projection of the vector data will be automatically // retrieved from the metadata. Nothing else is needed from you: // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet vectorDataProjection->SetInput(reader->GetOutput()); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Information concerning the target projection are retrieved directly from // the image: // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet vectorDataProjection->SetOutputKeywordList(imageReader->GetOutput()->GetImageKeywordlist()); vectorDataProjection->SetOutputOrigin(imageReader->GetOutput()->GetOrigin()); vectorDataProjection->SetOutputSpacing(imageReader->GetOutput()->GetSpacing()); vectorDataProjection->SetOutputProjectionRef(imageReader->GetOutput()->GetProjectionRef()); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Finally, the result is saved into a new vector file // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::VectorDataFileWriter<OutputVectorDataType> VectorDataFileWriterType; VectorDataFileWriterType::Pointer writer = VectorDataFileWriterType::New(); writer->SetFileName(argv[3]); writer->SetInput(vectorDataProjection->GetOutput()); writer->Update(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // It is worth noting that none of this code is specific to the vector data format. Whether // you pass a shapefile, or a KML file, the correct driver will be automatically instanciated. // // Software Guide : EndLatex return EXIT_SUCCESS; } <commit_msg>DOC: minor formatting of VectorDataProjectionExample<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif // Software Guide : BeginLatex // // Let's assume that you have a KML file (hence in geographical coordinates) // that you would like to superpose to some image with a specific map projection. // Of course, you could use the handy ogr2ogr tool to do that, but it won't // integrate so seamlessly into your OTB application. // // You can also suppose that the image on which you want to superpose // the data is not in a specific map projection but a raw image from a // particular sensor. Thanks to OTB, the same code below will be able // to do the appropriate conversion. // // This example demonstrates the use of the // \doxygen{otb}{VectorDataProjectionFilter}. // // Software Guide : EndLatex #include "otbVectorDataProjectionFilter.h" #include "otbVectorData.h" #include "otbVectorDataFileReader.h" #include "otbVectorDataFileWriter.h" #include "otbImage.h" #include "otbImageFileReader.h" int main( int argc, char* argv[] ) { if(argc < 3 ) { std::cout << argv[0] <<" <input vector filename> <input image name> <output vector filename> " << std::endl; return EXIT_FAILURE; } // Software Guide : BeginLatex // // Declare the vector data type that you would like to use in your // application. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::VectorData<double > InputVectorDataType; typedef otb::VectorData<double > OutputVectorDataType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Declare and instantiate the vector data reader: // \doxygen{otb}{VectorDataFileReader}. The call to the // \code{UpdateOutputInformation()} method fill up the header information. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::VectorDataFileReader<InputVectorDataType> VectorDataFileReaderType; VectorDataFileReaderType::Pointer reader = VectorDataFileReaderType::New(); reader->SetFileName(argv[1]); reader->UpdateOutputInformation(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We need the image only to retrieve its projection information, // i.e. map projection or sensor model parameters. Hence, the image // pixels won't be read, only the header information using the // \code{UpdateOutputInformation()} method. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::Image<unsigned short int, 2> ImageType; typedef otb::ImageFileReader<ImageType> ImageReaderType; ImageReaderType::Pointer imageReader = ImageReaderType::New(); imageReader->SetFileName(argv[2]); imageReader->UpdateOutputInformation(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The \doxygen{otb}{VectorDataProjectionFilter} will do the work of // converting the vector data coordinates. It is usually a good idea // to use it when you design applications reading or saving vector // data. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::VectorDataProjectionFilter<InputVectorDataType, OutputVectorDataType> VectorDataFilterType; VectorDataFilterType::Pointer vectorDataProjection = VectorDataFilterType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Information concerning the original projection of the vector data // will be automatically retrieved from the metadata. Nothing else // is needed from you: // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet vectorDataProjection->SetInput(reader->GetOutput()); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Information about the target projection is retrieved directly from // the image: // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet vectorDataProjection->SetOutputKeywordList( imageReader->GetOutput()->GetImageKeywordlist()); vectorDataProjection->SetOutputOrigin( imageReader->GetOutput()->GetOrigin()); vectorDataProjection->SetOutputSpacing( imageReader->GetOutput()->GetSpacing()); vectorDataProjection->SetOutputProjectionRef( imageReader->GetOutput()->GetProjectionRef()); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Finally, the result is saved into a new vector file. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::VectorDataFileWriter<OutputVectorDataType> VectorDataFileWriterType; VectorDataFileWriterType::Pointer writer = VectorDataFileWriterType::New(); writer->SetFileName(argv[3]); writer->SetInput(vectorDataProjection->GetOutput()); writer->Update(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // It is worth noting that none of this code is specific to the // vector data format. Whether you pass a shapefile, or a KML file, // the correct driver will be automatically instantiated. // // Software Guide : EndLatex return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include "Camera.h" #include "util.h" #include <cassert> using namespace nt; Camera::Camera(Player* t) : moveWithTarget(true), rotateWithTarget(true), rotateTarget(false), zoomSpeed(5), zSpeed(0.009), xSpeed(0.007), target(t), targetDistance(100), maxDistance(800) { setXRotation(0); setYRotation(0); setZRotation(0); setTarget(target); } void Camera::setTarget(Player* mob) { assert(target != 0); mob->alpha = target->alpha; target->alpha = target->defaultAlpha; target = mob; alignWithTarget(); } // target rotates to face away from camera void Camera::alignTarget() { target->xRot = getXRotation(); target->yRot = getYRotation(); target->zRot = getZRotation(); } // camera rotates to face at back of target void Camera::alignWithTarget() { setXRotation(target->xRot); setYRotation(target->yRot); setZRotation(target->zRot); } void Camera::setTargetDistance(float distance) { if (distance < 0) { distance = 0;} if (distance > maxDistance) {distance = maxDistance;} targetDistance = distance; target->alpha = targetDistance / 100; } void Camera::applySettings() const { float toDegrees = 180 / M_PI; // distance the camera from the target glTranslatef( 0.0f,0.0f, -targetDistance); glRotatef(-xRot * toDegrees, 1.0, 0.0, 0.0); glRotatef(-yRot * toDegrees, 0.0, 1.0, 0.0); glRotatef(-zRot * toDegrees, 0.0, 0.0, 1.0); // keeps the target in the center of the screen glTranslatef( -target->pos.x(), -target->pos.y(), -target->pos.z() ); } void Camera::setXRotation(float angle) { angle += M_PI_2; normalizeAngle(angle); // keep us from flipping upside down if ( angle > 3 * M_PI_2 ) { angle = 2 * M_PI; } else if ( angle > M_PI ) {angle = M_PI;} xRot = angle; } void Camera::setYRotation(float angle) { normalizeAngle(angle); yRot = angle; } void Camera::setZRotation(float angle) { normalizeAngle(angle); zRot = angle; } <commit_msg>Correct some whitespace<commit_after>#include "Camera.h" #include "util.h" #include <cassert> using namespace nt; Camera::Camera(Player* t) : moveWithTarget(true), rotateWithTarget(true), rotateTarget(false), zoomSpeed(5), zSpeed(0.009), xSpeed(0.007), target(t), targetDistance(100), maxDistance(800) { setXRotation(0); setYRotation(0); setZRotation(0); setTarget(target); } void Camera::setTarget(Player* mob) { assert(target != 0); mob->alpha = target->alpha; target->alpha = target->defaultAlpha; target = mob; alignWithTarget(); } // target rotates to face away from camera void Camera::alignTarget() { target->xRot = getXRotation(); target->yRot = getYRotation(); target->zRot = getZRotation(); } // camera rotates to face at back of target void Camera::alignWithTarget() { setXRotation(target->xRot); setYRotation(target->yRot); setZRotation(target->zRot); } void Camera::setTargetDistance(float distance) { if (distance < 0) { distance = 0;} if (distance > maxDistance) {distance = maxDistance;} targetDistance = distance; target->alpha = targetDistance / 100; } void Camera::applySettings() const { float toDegrees = 180 / M_PI; // distance the camera from the target glTranslatef( 0.0f,0.0f, -targetDistance); glRotatef(-xRot * toDegrees, 1.0, 0.0, 0.0); glRotatef(-yRot * toDegrees, 0.0, 1.0, 0.0); glRotatef(-zRot * toDegrees, 0.0, 0.0, 1.0); // keeps the target in the center of the screen glTranslatef( -target->pos.x(), -target->pos.y(), -target->pos.z() ); } void Camera::setXRotation(float angle) { angle += M_PI_2; normalizeAngle(angle); // keep us from flipping upside down if ( angle > 3 * M_PI_2 ) { angle = 2 * M_PI; } else if ( angle > M_PI ) {angle = M_PI;} xRot = angle; } void Camera::setYRotation(float angle) { normalizeAngle(angle); yRot = angle; } void Camera::setZRotation(float angle) { normalizeAngle(angle); zRot = angle; } <|endoftext|>
<commit_before>//============================================================================= // ■ CommandList.cpp //----------------------------------------------------------------------------- // VMDE中渲染指令列表。 //============================================================================= #include "global.hpp" static uint32_t CL_GDrawable_render(uint8_t* input) { GDrawable* ptr = *((GDrawable**) input); ptr->render(); return 0x0; } static uint32_t CL_GDrawable_renderOnce(uint8_t* input) { GDrawable* ptr = *((GDrawable**) input); ptr->renderOnce(); return 0x0; } static uint32_t CL_GDrawable_batch(uint8_t* input) { GDrawable** ind = (GDrawable**) input; while (*ind != NULL) { GDrawable* ptr = *ind; ptr->render(); ind ++; } return 0x0; } static uint32_t CL_GDrawable_batchOnce(uint8_t* input) { GDrawable** ind = (GDrawable**) input; while (*ind != NULL) { GDrawable* ptr = *ind; log("Batch %d", ptr->data.VAO); ptr->renderOnce(); ind ++; } return 0x0; } static ASM76::BIOS_call func_list[] = { #define add(x) &CL_##x, #include "CommandList.hpp" #undef add }; static int function_count = ARRAY_SIZE(func_list) + 1; ASM76::BIOS* CmdList::bios; void CmdList::global_init() { bios = new ASM76::BIOS(function_count); memcpy(bios->function_table, func_list, sizeof(func_list)); } CmdList::CmdList(ASM76::Program p) { vm = new ASM76::VM(p); vm->firmware = bios; } void CmdList::call() { vm->execute_from(0x0, false); } CmdList::~CmdList() { XE(delete, vm); } <commit_msg>Remove a refreshing log call<commit_after>//============================================================================= // ■ CommandList.cpp //----------------------------------------------------------------------------- // VMDE中渲染指令列表。 //============================================================================= #include "global.hpp" static uint32_t CL_GDrawable_render(uint8_t* input) { GDrawable* ptr = *((GDrawable**) input); ptr->render(); return 0x0; } static uint32_t CL_GDrawable_renderOnce(uint8_t* input) { GDrawable* ptr = *((GDrawable**) input); ptr->renderOnce(); return 0x0; } static uint32_t CL_GDrawable_batch(uint8_t* input) { GDrawable** ind = (GDrawable**) input; while (*ind != NULL) { GDrawable* ptr = *ind; ptr->render(); ind ++; } return 0x0; } static uint32_t CL_GDrawable_batchOnce(uint8_t* input) { GDrawable** ind = (GDrawable**) input; while (*ind != NULL) { GDrawable* ptr = *ind; ptr->renderOnce(); ind ++; } return 0x0; } static ASM76::BIOS_call func_list[] = { #define add(x) &CL_##x, #include "CommandList.hpp" #undef add }; static int function_count = ARRAY_SIZE(func_list) + 1; ASM76::BIOS* CmdList::bios; void CmdList::global_init() { bios = new ASM76::BIOS(function_count); memcpy(bios->function_table, func_list, sizeof(func_list)); } CmdList::CmdList(ASM76::Program p) { vm = new ASM76::VM(p); vm->firmware = bios; } void CmdList::call() { vm->execute_from(0x0, false); } CmdList::~CmdList() { XE(delete, vm); } <|endoftext|>
<commit_before><commit_msg> o RooLinkedList<commit_after><|endoftext|>
<commit_before>// // Copyright (c) 2017 The nanoFramework project contributors // Portions Copyright (c) Microsoft Corporation. All rights reserved. // See LICENSE file in the project root for full license information. // #include "nf_rt_native.h" static const CLR_RT_MethodHandler method_lookup[] = { Library_nf_rt_native_nanoFramework_Runtime_Native_SystemInfo::GetSystemVersion___STATIC__VOID__BYREF_I4__BYREF_I4__BYREF_I4__BYREF_I4, NULL, Library_nf_rt_native_nanoFramework_Runtime_Native_SystemInfo::get_OEMString___STATIC__STRING, Library_nf_rt_native_nanoFramework_Runtime_Native_SystemInfo::get_OEM___STATIC__U1, Library_nf_rt_native_nanoFramework_Runtime_Native_SystemInfo::get_Model___STATIC__U1, Library_nf_rt_native_nanoFramework_Runtime_Native_SystemInfo::get_SKU___STATIC__U2, NULL, Library_nf_rt_native_nanoFramework_Runtime_Native_SystemInfo::GetNativeFloatingPointSupport___STATIC__U1, NULL, NULL, Library_nf_rt_native_nanoFramework_Runtime_Native_Debug::GC___STATIC__U4__BOOLEAN, Library_nf_rt_native_nanoFramework_Runtime_Native_Debug::EnableGCMessages___STATIC__VOID__BOOLEAN, NULL, NULL, NULL, Library_nf_rt_native_nanoFramework_Runtime_Native_ExecutionConstraint::Install___STATIC__VOID__I4__I4, NULL, NULL, NULL, NULL, NULL, Library_nf_rt_native_nanoFramework_Runtime_Native_Power::NativeReboot___STATIC__VOID, NULL, NULL, NULL, NULL, Library_nf_rt_native_nanoFramework_Runtime_Native_ResourceUtility::GetObject___STATIC__OBJECT__mscorlibSystemResourcesResourceManager__mscorlibSystemEnum, Library_nf_rt_native_nanoFramework_Runtime_Native_ResourceUtility::GetObject___STATIC__OBJECT__mscorlibSystemResourcesResourceManager__mscorlibSystemEnum__I4__I4, NULL, NULL, NULL, Library_nf_rt_native_nanoFramework_Runtime_Native_Rtc::Native_RTC_SetSystemTime___STATIC__BOOLEAN__I4__U1__U1__U1__U1__U1__U1, }; const CLR_RT_NativeAssemblyData g_CLR_AssemblyNative_nanoFramework_Runtime_Native = { "nanoFramework.Runtime.Native", 0xFE14C7A7, method_lookup, { 1, 0, 2, 12 } }; <commit_msg>Update nanoFramework.Runtime.Native version to 1.0.2-preview-016 ***NO_CI***<commit_after>// // Copyright (c) 2017 The nanoFramework project contributors // Portions Copyright (c) Microsoft Corporation. All rights reserved. // See LICENSE file in the project root for full license information. // #include "nf_rt_native.h" static const CLR_RT_MethodHandler method_lookup[] = { Library_nf_rt_native_nanoFramework_Runtime_Native_SystemInfo::GetSystemVersion___STATIC__VOID__BYREF_I4__BYREF_I4__BYREF_I4__BYREF_I4, NULL, Library_nf_rt_native_nanoFramework_Runtime_Native_SystemInfo::get_OEMString___STATIC__STRING, Library_nf_rt_native_nanoFramework_Runtime_Native_SystemInfo::get_OEM___STATIC__U1, Library_nf_rt_native_nanoFramework_Runtime_Native_SystemInfo::get_Model___STATIC__U1, Library_nf_rt_native_nanoFramework_Runtime_Native_SystemInfo::get_SKU___STATIC__U2, NULL, Library_nf_rt_native_nanoFramework_Runtime_Native_SystemInfo::GetNativeFloatingPointSupport___STATIC__U1, NULL, NULL, Library_nf_rt_native_nanoFramework_Runtime_Native_Debug::GC___STATIC__U4__BOOLEAN, Library_nf_rt_native_nanoFramework_Runtime_Native_Debug::EnableGCMessages___STATIC__VOID__BOOLEAN, NULL, NULL, NULL, Library_nf_rt_native_nanoFramework_Runtime_Native_ExecutionConstraint::Install___STATIC__VOID__I4__I4, NULL, NULL, NULL, NULL, NULL, Library_nf_rt_native_nanoFramework_Runtime_Native_Power::NativeReboot___STATIC__VOID, NULL, NULL, NULL, NULL, Library_nf_rt_native_nanoFramework_Runtime_Native_ResourceUtility::GetObject___STATIC__OBJECT__mscorlibSystemResourcesResourceManager__mscorlibSystemEnum, Library_nf_rt_native_nanoFramework_Runtime_Native_ResourceUtility::GetObject___STATIC__OBJECT__mscorlibSystemResourcesResourceManager__mscorlibSystemEnum__I4__I4, NULL, NULL, NULL, Library_nf_rt_native_nanoFramework_Runtime_Native_Rtc::Native_RTC_SetSystemTime___STATIC__BOOLEAN__I4__U1__U1__U1__U1__U1__U1, }; const CLR_RT_NativeAssemblyData g_CLR_AssemblyNative_nanoFramework_Runtime_Native = { "nanoFramework.Runtime.Native", 0xFE14C7A7, method_lookup, { 1, 0, 2, 16 } }; <|endoftext|>
<commit_before>#include "GLUtil.h" #include "ConsoleOutput.h" #include "ImageFileUtils.h" #include <fstream> #include <sstream> #include <vector> namespace { std::function<GLUtil::GLDebugMessageCallbackFunc> g_debugMessageCallback; void GLAPIENTRY GLDebugMessageCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const GLvoid* userParam) { assert(g_debugMessageCallback != nullptr); g_debugMessageCallback({source, type, id, severity, length, message, userParam}); } std::optional<std::string> FileToString(const char* file) { std::ifstream is(file); if (!is) return {}; std::stringstream buffer; buffer << is.rdbuf(); return buffer.str(); } } // namespace void GLUtil::SetDebugMessageCallback(std::function<void(const GLDebugMessageInfo&)> callback) { g_debugMessageCallback = std::move(callback); if (g_debugMessageCallback) { if (glDebugMessageCallback) { glEnable(GL_DEBUG_OUTPUT); glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); glDebugMessageCallback(&GLDebugMessageCallback, nullptr); GLenum disableSources[] = { // GL_DEBUG_SOURCE_API, // GL_DEBUG_SOURCE_WINDOW_SYSTEM, GL_DEBUG_SOURCE_SHADER_COMPILER, // GL_DEBUG_SOURCE_THIRD_PARTY, // GL_DEBUG_SOURCE_APPLICATION, // GL_DEBUG_SOURCE_OTHER }; GLenum disableTypes[] = { // GL_DEBUG_TYPE_ERROR, // GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR, // GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR, // GL_DEBUG_TYPE_PORTABILITY, // GL_DEBUG_TYPE_PERFORMANCE, GL_DEBUG_TYPE_PUSH_GROUP, GL_DEBUG_TYPE_POP_GROUP, // GL_DEBUG_TYPE_MARKER, // GL_DEBUG_TYPE_OTHER }; // Enable all by default glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_TRUE); // Disable specific disableSources for (auto source : disableSources) { glDebugMessageControl(source, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_FALSE); } // Disable specific types for (auto type : disableTypes) { glDebugMessageControl(GL_DONT_CARE, type, GL_DONT_CARE, 0, nullptr, GL_FALSE); } } else { Errorf("GL Debug not supported.\n"); } } else { glDisable(GL_DEBUG_OUTPUT_SYNCHRONOUS); glDisable(GL_DEBUG_OUTPUT); } } void GLUtil::AllocateTexture(GLuint textureId, GLsizei width, GLsizei height, GLint internalFormat, std::optional<GLint> filtering, std::optional<PixelData> pixelData) { auto pd = pixelData.value_or(GLUtil::PixelData{nullptr, GL_RGBA, GL_UNSIGNED_BYTE}); glBindTexture(GL_TEXTURE_2D, textureId); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, width, height, 0, pd.format, pd.type, pd.pixels); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filtering.value_or(DEFAULT_FILTERING)); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filtering.value_or(DEFAULT_FILTERING)); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } bool GLUtil::LoadPngTexture(GLuint textureId, const char* file, std::optional<GLint> filtering) { auto imgData = ImageFileUtils::loadPngImage(file); if (!imgData) { return false; } AllocateTexture( textureId, imgData->width, imgData->height, imgData->hasAlpha ? GL_RGBA : GL_RGB, filtering, PixelData{imgData->data.get(), static_cast<GLenum>(imgData->hasAlpha ? GL_RGBA : GL_RGB), GL_UNSIGNED_BYTE}); return true; } GLuint GLUtil::LoadShadersFromFiles(const char* vertShaderFile, const char* fragShaderFile) { auto vertShaderCode = FileToString(vertShaderFile); if (!vertShaderCode) { Errorf("Failed to open %s\n", vertShaderFile); return 0; } auto fragShaderCode = FileToString(fragShaderFile); if (!fragShaderCode) { Errorf("Failed to open %s\n", fragShaderFile); return 0; } return LoadShaders(vertShaderCode->c_str(), fragShaderCode->c_str()); } GLuint GLUtil::LoadShaders(const char* vertShaderCode, const char* fragShaderCode) { auto CheckStatus = [](GLuint id, GLenum pname) { assert(pname == GL_COMPILE_STATUS || pname == GL_LINK_STATUS); GLint result = GL_FALSE; int infoLogLength{}; glGetShaderiv(id, pname, &result); glGetShaderiv(id, GL_INFO_LOG_LENGTH, &infoLogLength); if (infoLogLength > 0) { std::vector<char> info(infoLogLength + 1); if (pname == GL_COMPILE_STATUS) glGetShaderInfoLog(id, infoLogLength, NULL, info.data()); else glGetProgramInfoLog(id, infoLogLength, NULL, info.data()); Errorf("%s", info.data()); } return true; }; auto CompileShader = [CheckStatus](GLuint shaderId, const char* shaderCode) { // Printf("Compiling shader : %s\n", shaderFile); auto sourcePtr = shaderCode; glShaderSource(shaderId, 1, &sourcePtr, NULL); glCompileShader(shaderId); return CheckStatus(shaderId, GL_COMPILE_STATUS); }; auto LinkProgram = [CheckStatus](GLuint programId) { // Printf("Linking program\n"); glLinkProgram(programId); return CheckStatus(programId, GL_LINK_STATUS); }; GLuint vertShaderId = glCreateShader(GL_VERTEX_SHADER); if (!CompileShader(vertShaderId, vertShaderCode)) return 0; GLuint fragShaderId = glCreateShader(GL_FRAGMENT_SHADER); if (!CompileShader(fragShaderId, fragShaderCode)) return 0; GLuint programId = glCreateProgram(); glAttachShader(programId, vertShaderId); glAttachShader(programId, fragShaderId); if (!LinkProgram(programId)) return 0; glDetachShader(programId, vertShaderId); glDetachShader(programId, fragShaderId); glDeleteShader(vertShaderId); glDeleteShader(fragShaderId); return programId; } <commit_msg>GLUtil: fix invalid check for compile status on shader linking<commit_after>#include "GLUtil.h" #include "ConsoleOutput.h" #include "ImageFileUtils.h" #include <fstream> #include <sstream> #include <vector> namespace { std::function<GLUtil::GLDebugMessageCallbackFunc> g_debugMessageCallback; void GLAPIENTRY GLDebugMessageCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const GLvoid* userParam) { assert(g_debugMessageCallback != nullptr); g_debugMessageCallback({source, type, id, severity, length, message, userParam}); } std::optional<std::string> FileToString(const char* file) { std::ifstream is(file); if (!is) return {}; std::stringstream buffer; buffer << is.rdbuf(); return buffer.str(); } } // namespace void GLUtil::SetDebugMessageCallback(std::function<void(const GLDebugMessageInfo&)> callback) { g_debugMessageCallback = std::move(callback); if (g_debugMessageCallback) { if (glDebugMessageCallback) { glEnable(GL_DEBUG_OUTPUT); glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); glDebugMessageCallback(&GLDebugMessageCallback, nullptr); GLenum disableSources[] = { // GL_DEBUG_SOURCE_API, // GL_DEBUG_SOURCE_WINDOW_SYSTEM, GL_DEBUG_SOURCE_SHADER_COMPILER, // GL_DEBUG_SOURCE_THIRD_PARTY, // GL_DEBUG_SOURCE_APPLICATION, // GL_DEBUG_SOURCE_OTHER }; GLenum disableTypes[] = { // GL_DEBUG_TYPE_ERROR, // GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR, // GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR, // GL_DEBUG_TYPE_PORTABILITY, // GL_DEBUG_TYPE_PERFORMANCE, GL_DEBUG_TYPE_PUSH_GROUP, GL_DEBUG_TYPE_POP_GROUP, // GL_DEBUG_TYPE_MARKER, // GL_DEBUG_TYPE_OTHER }; // Enable all by default glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_TRUE); // Disable specific disableSources for (auto source : disableSources) { glDebugMessageControl(source, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_FALSE); } // Disable specific types for (auto type : disableTypes) { glDebugMessageControl(GL_DONT_CARE, type, GL_DONT_CARE, 0, nullptr, GL_FALSE); } } else { Errorf("GL Debug not supported.\n"); } } else { glDisable(GL_DEBUG_OUTPUT_SYNCHRONOUS); glDisable(GL_DEBUG_OUTPUT); } } void GLUtil::AllocateTexture(GLuint textureId, GLsizei width, GLsizei height, GLint internalFormat, std::optional<GLint> filtering, std::optional<PixelData> pixelData) { auto pd = pixelData.value_or(GLUtil::PixelData{nullptr, GL_RGBA, GL_UNSIGNED_BYTE}); glBindTexture(GL_TEXTURE_2D, textureId); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, width, height, 0, pd.format, pd.type, pd.pixels); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filtering.value_or(DEFAULT_FILTERING)); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filtering.value_or(DEFAULT_FILTERING)); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } bool GLUtil::LoadPngTexture(GLuint textureId, const char* file, std::optional<GLint> filtering) { auto imgData = ImageFileUtils::loadPngImage(file); if (!imgData) { return false; } AllocateTexture( textureId, imgData->width, imgData->height, imgData->hasAlpha ? GL_RGBA : GL_RGB, filtering, PixelData{imgData->data.get(), static_cast<GLenum>(imgData->hasAlpha ? GL_RGBA : GL_RGB), GL_UNSIGNED_BYTE}); return true; } GLuint GLUtil::LoadShadersFromFiles(const char* vertShaderFile, const char* fragShaderFile) { auto vertShaderCode = FileToString(vertShaderFile); if (!vertShaderCode) { Errorf("Failed to open %s\n", vertShaderFile); return 0; } auto fragShaderCode = FileToString(fragShaderFile); if (!fragShaderCode) { Errorf("Failed to open %s\n", fragShaderFile); return 0; } return LoadShaders(vertShaderCode->c_str(), fragShaderCode->c_str()); } GLuint GLUtil::LoadShaders(const char* vertShaderCode, const char* fragShaderCode) { auto CheckCompileStatus = [](GLuint id, GLenum pname) { assert(pname == GL_COMPILE_STATUS); GLint result = GL_FALSE; int infoLogLength{}; glGetShaderiv(id, pname, &result); glGetShaderiv(id, GL_INFO_LOG_LENGTH, &infoLogLength); if (infoLogLength > 0) { std::vector<char> info(infoLogLength + 1); if (pname == GL_COMPILE_STATUS) glGetShaderInfoLog(id, infoLogLength, NULL, info.data()); else glGetProgramInfoLog(id, infoLogLength, NULL, info.data()); Errorf("%s", info.data()); } return true; }; auto CompileShader = [CheckCompileStatus](GLuint shaderId, const char* shaderCode) { // Printf("Compiling shader : %s\n", shaderFile); auto sourcePtr = shaderCode; glShaderSource(shaderId, 1, &sourcePtr, NULL); glCompileShader(shaderId); return CheckCompileStatus(shaderId, GL_COMPILE_STATUS); }; auto LinkProgram = [](GLuint programId) { // Printf("Linking program\n"); glLinkProgram(programId); return true; //@TODO: check if valid }; GLuint vertShaderId = glCreateShader(GL_VERTEX_SHADER); if (!CompileShader(vertShaderId, vertShaderCode)) return 0; GLuint fragShaderId = glCreateShader(GL_FRAGMENT_SHADER); if (!CompileShader(fragShaderId, fragShaderCode)) return 0; GLuint programId = glCreateProgram(); glAttachShader(programId, vertShaderId); glAttachShader(programId, fragShaderId); if (!LinkProgram(programId)) return 0; glDetachShader(programId, vertShaderId); glDetachShader(programId, fragShaderId); glDeleteShader(vertShaderId); glDeleteShader(fragShaderId); return programId; } <|endoftext|>
<commit_before>/* * Copyright (c) 2015, 2016, Intel Corporation * * 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 Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 LOG OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef POLICY_HPP_INCLUDE #define POLICY_HPP_INCLUDE #include <vector> #include <map> #include <float.h> #include "geopm_message.h" #include "PolicyFlags.hpp" namespace geopm { class RegionPolicy; class Policy { public: Policy(int num_domain); virtual ~Policy(); int num_domain(void); void region_id(std::vector<uint64_t> &region_id); void update(uint64_t region_id, int domain_idx, double target); void update(uint64_t region_id, const std::vector<double> &target); void mode(int new_mode); void policy_flags(unsigned long new_flags); void target(uint64_t region_id, std::vector<double> &target); void target(uint64_t region_id, int domain, double &target); /// @brief Get the policy power mode /// @return geopm_policy_mode_e power mode int mode(void) const; /// @brief Get the policy frequency /// @return frequency in MHz int frequency_mhz(void) const; /// @brief Get the policy TDP percentage /// @return TDP (thermal design power) percentage between 0-100 int tdp_percent(void) const; /// @brief Get the policy affinity. This is the cores that we /// will dynamically control. One of /// GEOPM_FLAGS_SMALL_CPU_TOPOLOGY_COMPACT or /// GEOPM_FLAGS_SMALL_CPU_TOPOLOGY_COMPACT. /// @return enum power affinity int affinity(void) const; /// @brief Get the policy power goal, One of /// GEOPM_POLICY_GOAL_CPU_EFFICIENCY, /// GEOPM_POLICY_GOAL_NETWORK_EFFICIENCY, or /// GEOPM_POLICY_GOAL_MEMORY_EFFICIENCY /// @return enum power goal int goal(void) const; /// @brief Get the number of 'big' cores /// @return number of cores where we will run /// unconstrained power. int num_max_perf(void) const; void target_updated(uint64_t region_id, std::map<int, double> &target); // map from domain index to updated target value void target_valid(uint64_t region_id, std::map<int, double> &target); void policy_message(uint64_t region_id, const struct geopm_policy_message_s &parent_msg, std::vector<struct geopm_policy_message_s> &child_msg); /// @brief Set the convergence state. /// Called by the decision algorithm when it has determined /// whether or not the power policy enforcement has converged /// to an acceptance state. void is_converged(uint64_t region_id, bool converged_state); /// @brief Have we converged for this region. /// Set by he decision algorithm when it has determined /// that the power policy enforcement has converged to an /// acceptance state. /// @return true if converged else false. bool is_converged(uint64_t region_id); protected: PolicyFlags m_policy_flags; RegionPolicy *region_policy(uint64_t region_id); int m_num_domain; int m_mode; int m_num_sample; std::map<uint64_t, RegionPolicy *> m_region_policy; }; } #endif <commit_msg>Added a couple of doxygen comments for Policy.<commit_after>/* * Copyright (c) 2015, 2016, Intel Corporation * * 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 Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 LOG OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef POLICY_HPP_INCLUDE #define POLICY_HPP_INCLUDE #include <vector> #include <map> #include <float.h> #include "geopm_message.h" #include "PolicyFlags.hpp" namespace geopm { class RegionPolicy; /// @brief Class defines the per-domain power settings and policy state. class Policy { public: /// @brief Policy constructor. /// @param [in] num_domain number of control domains the policy regulates. Policy(int num_domain); /// @brief Policy destructor, virtual virtual ~Policy(); /// @brief Get number of control domains for the policy. /// @returns number of domains under control. int num_domain(void); void region_id(std::vector<uint64_t> &region_id); void update(uint64_t region_id, int domain_idx, double target); void update(uint64_t region_id, const std::vector<double> &target); void mode(int new_mode); void policy_flags(unsigned long new_flags); void target(uint64_t region_id, std::vector<double> &target); void target(uint64_t region_id, int domain, double &target); /// @brief Get the policy power mode /// @return geopm_policy_mode_e power mode int mode(void) const; /// @brief Get the policy frequency /// @return frequency in MHz int frequency_mhz(void) const; /// @brief Get the policy TDP percentage /// @return TDP (thermal design power) percentage between 0-100 int tdp_percent(void) const; /// @brief Get the policy affinity. This is the cores that we /// will dynamically control. One of /// GEOPM_FLAGS_SMALL_CPU_TOPOLOGY_COMPACT or /// GEOPM_FLAGS_SMALL_CPU_TOPOLOGY_COMPACT. /// @return enum power affinity int affinity(void) const; /// @brief Get the policy power goal, One of /// GEOPM_POLICY_GOAL_CPU_EFFICIENCY, /// GEOPM_POLICY_GOAL_NETWORK_EFFICIENCY, or /// GEOPM_POLICY_GOAL_MEMORY_EFFICIENCY /// @return enum power goal int goal(void) const; /// @brief Get the number of 'big' cores /// @return number of cores where we will run /// unconstrained power. int num_max_perf(void) const; void target_updated(uint64_t region_id, std::map<int, double> &target); // map from domain index to updated target value void target_valid(uint64_t region_id, std::map<int, double> &target); void policy_message(uint64_t region_id, const struct geopm_policy_message_s &parent_msg, std::vector<struct geopm_policy_message_s> &child_msg); /// @brief Set the convergence state. /// Called by the decision algorithm when it has determined /// whether or not the power policy enforcement has converged /// to an acceptance state. void is_converged(uint64_t region_id, bool converged_state); /// @brief Have we converged for this region. /// Set by he decision algorithm when it has determined /// that the power policy enforcement has converged to an /// acceptance state. /// @return true if converged else false. bool is_converged(uint64_t region_id); protected: PolicyFlags m_policy_flags; RegionPolicy *region_policy(uint64_t region_id); int m_num_domain; int m_mode; int m_num_sample; std::map<uint64_t, RegionPolicy *> m_region_policy; }; } #endif <|endoftext|>
<commit_before> #include "EntityData.hh" #include "Core/Engine.hh" #include "Components/Component.hh" #include "Entity.hh" #include <limits> #include <Core/AScene.hh> EntityData::EntityData(std::weak_ptr<AScene> scene) : _scene(scene), _flags(0), _localTranslation(0), _localRotation(0), _localScale(0), _globalTranslation(0), _globalRotation(0), _globalScale(0), _parent(Entity(std::numeric_limits<unsigned int>::max(), nullptr)) { removeFlags(ACTIVE); } EntityData::~EntityData() { _components.clear(); } EntityData::EntityData(EntityData &&o) { _handle = std::move(o._handle); _scene = std::move(o._scene); _flags = std::move(o._flags); _localTransform = std::move(o._localTransform); _globalTransform = std::move(o._globalTransform); _localRotation = std::move(o._localRotation); _localScale = std::move(o._localScale); _localTranslation = std::move(o._localTranslation); _globalRotation = std::move(o._globalRotation); _globalScale = std::move(o._globalScale); _globalTranslation = std::move(o._globalTranslation); _components = std::move(o._components); _code = std::move(o._code); _childs = std::move(o._childs); _parent = std::move(o._parent); } Entity &EntityData::getHandle() { return _handle; } std::shared_ptr<AScene> EntityData::getScene() const { return _scene.lock(); } void EntityData::setHandle(Entity &handle) { _handle = handle; } glm::mat4 const &EntityData::getLocalTransform() { return (_localTransform); } void EntityData::setLocalTransform(const glm::mat4 &t, bool forceMovedFlag) { _flags |= HAS_MOVED; _localTransform = t; computeTransformAndUpdateGraphnode(); if (forceMovedFlag) _flags |= HAS_MOVED; } glm::mat4 const &EntityData::getGlobalTransform() const { return (_globalTransform); } void EntityData::computeGlobalTransform(glm::mat4 const &fatherTransform) { _globalTransform = fatherTransform * _localTransform; _flags ^= HAS_MOVED; } void EntityData::computeGlobalTransform(const Entity &parent) { if (!parent.get()) return; _globalTransform = parent.get()->getGlobalTransform() * _localTransform; _flags ^= HAS_MOVED; } void EntityData::translate(const glm::vec3 &v) { _localTranslation += v; _flags |= HAS_MOVED; computeTransformAndUpdateGraphnode(); } void EntityData::setTranslation(const glm::vec3 &v) { _localTranslation = v; _flags |= HAS_MOVED; computeTransformAndUpdateGraphnode(); } glm::vec3 const &EntityData::getTranslation() const { return _localTranslation; } void EntityData::rotate(const glm::vec3 &v) { _localRotation += v; _flags |= HAS_MOVED; computeTransformAndUpdateGraphnode(); } void EntityData::setRotation(const glm::vec3 &v) { _localRotation = v; _flags |= HAS_MOVED; computeTransformAndUpdateGraphnode(); } glm::vec3 const &EntityData::getRotation() const { return _localRotation; } void EntityData::scale(const glm::vec3 &v) { _localScale += v; _flags |= HAS_MOVED; computeTransformAndUpdateGraphnode(); } void EntityData::setScale(const glm::vec3 &v) { _localScale = v; _flags |= HAS_MOVED; computeTransformAndUpdateGraphnode(); } glm::vec3 const &EntityData::getScale() const { return _localScale; } void EntityData::computeTransformAndUpdateGraphnode() { if (!_parent.get()) { computeGlobalTransform(glm::mat4(1)); } else { computeGlobalTransform(_parent); } for (auto e : _childs) { e->computeTransformAndUpdateGraphnode(); } } size_t EntityData::getFlags() const { return (_flags); } void EntityData::setFlags(size_t flags) { _flags = flags; } void EntityData::addFlags(size_t flags) { _flags |= flags; } void EntityData::removeFlags(size_t flags) { flags &= _flags; _flags ^= flags; } Barcode &EntityData::getCode() { return _code; } void EntityData::addTag(unsigned short tag) { assert(tag < MAX_TAG_NUMBER && "Tags limit is 31"); _code.add(tag); _scene.lock()->informFilters(true, tag, std::move(_handle)); } void EntityData::removeTag(unsigned short tag) { assert(tag < MAX_TAG_NUMBER && "Tags limit is 31"); _code.remove(tag); _scene.lock()->informFilters(false, tag, std::move(_handle)); } bool EntityData::isTagged(unsigned short tag) const { assert(tag < MAX_TAG_NUMBER && "Tags limit is 31"); return _code.isSet(tag); } bool EntityData::isTagged(Barcode &code) { // TODO get the size of the code and assert if > 31 return _code.match(code); } void EntityData::reset() { _flags = 0; _localTranslation = glm::vec3(0); _localRotation = glm::vec3(0); _localScale = glm::vec3(0); _globalTranslation = glm::vec3(0); _globalRotation = glm::vec3(0); _globalScale = glm::vec3(0); _globalTransform = glm::mat4(1); _localTransform = glm::mat4(1); _code.reset(); auto scene = _scene.lock(); for (std::size_t i = 0; i < MAX_TAG_NUMBER; ++i) { if (scene) scene->informFilters(false, i, std::move(_handle)); } for (std::size_t i = 0; i < _components.size(); ++i) { std::size_t id = i + MAX_TAG_NUMBER; if (_components[i].get()) { if (scene) scene->informFilters(false, id, std::move(_handle)); _components[i]->reset(); } _components[i].reset(); } removeParent(); for (auto e : _childs) e->removeParent(false); _childs.clear(); } //////////////// // // Graphnode const Entity &EntityData::getParent() const { return _parent; } void EntityData::removeChild(Entity &child, bool notify) { _childs.erase(child); if (notify) { child->removeParent(false); } } void EntityData::setParent(Entity &parent, bool notify) { if (_parent.get()) { _parent->removeChild(_handle, false); } if (notify) parent->addChild(_handle, false); computeTransformAndUpdateGraphnode(); _parent = parent; } void EntityData::addChild(Entity &child, bool notify) { _childs.insert(child); if (notify) { child->setParent(_handle, false); } } void EntityData::removeParent(bool notify) { if (notify && _parent.get()) { _parent->removeChild(_handle); } _parent = Entity(std::numeric_limits<unsigned int>::max(), nullptr); computeTransformAndUpdateGraphnode(); } std::set<Entity>::iterator EntityData::getChildsBegin() { return std::begin(_childs); } std::set<Entity>::iterator EntityData::getChildsEnd() { return std::end(_childs); } <commit_msg>Some warning fixed<commit_after> #include "EntityData.hh" #include "Core/Engine.hh" #include "Components/Component.hh" #include "Entity.hh" #include <limits> #include <Core/AScene.hh> EntityData::EntityData(std::weak_ptr<AScene> scene) : _scene(scene), _flags(0), _localTranslation(0), _localRotation(0), _localScale(0), _globalTranslation(0), _globalRotation(0), _globalScale(0), _parent(Entity(std::numeric_limits<unsigned int>::max(), nullptr)) { removeFlags(ACTIVE); } EntityData::~EntityData() { _components.clear(); } EntityData::EntityData(EntityData &&o) { _handle = std::move(o._handle); _scene = std::move(o._scene); _flags = std::move(o._flags); _localTransform = std::move(o._localTransform); _globalTransform = std::move(o._globalTransform); _localRotation = std::move(o._localRotation); _localScale = std::move(o._localScale); _localTranslation = std::move(o._localTranslation); _globalRotation = std::move(o._globalRotation); _globalScale = std::move(o._globalScale); _globalTranslation = std::move(o._globalTranslation); _components = std::move(o._components); _code = std::move(o._code); _childs = std::move(o._childs); _parent = std::move(o._parent); } Entity &EntityData::getHandle() { return _handle; } std::shared_ptr<AScene> EntityData::getScene() const { return _scene.lock(); } void EntityData::setHandle(Entity &handle) { _handle = handle; } glm::mat4 const &EntityData::getLocalTransform() { return (_localTransform); } void EntityData::setLocalTransform(const glm::mat4 &t, bool forceMovedFlag) { _flags |= HAS_MOVED; _localTransform = t; computeTransformAndUpdateGraphnode(); if (forceMovedFlag) _flags |= HAS_MOVED; } glm::mat4 const &EntityData::getGlobalTransform() const { return (_globalTransform); } void EntityData::computeGlobalTransform(glm::mat4 const &fatherTransform) { _globalTransform = fatherTransform * _localTransform; _flags ^= HAS_MOVED; } void EntityData::computeGlobalTransform(const Entity &parent) { if (!parent.get()) return; _globalTransform = parent.get()->getGlobalTransform() * _localTransform; _flags ^= HAS_MOVED; } void EntityData::translate(const glm::vec3 &v) { _localTranslation += v; _flags |= HAS_MOVED; computeTransformAndUpdateGraphnode(); } void EntityData::setTranslation(const glm::vec3 &v) { _localTranslation = v; _flags |= HAS_MOVED; computeTransformAndUpdateGraphnode(); } glm::vec3 const &EntityData::getTranslation() const { return _localTranslation; } void EntityData::rotate(const glm::vec3 &v) { _localRotation += v; _flags |= HAS_MOVED; computeTransformAndUpdateGraphnode(); } void EntityData::setRotation(const glm::vec3 &v) { _localRotation = v; _flags |= HAS_MOVED; computeTransformAndUpdateGraphnode(); } glm::vec3 const &EntityData::getRotation() const { return _localRotation; } void EntityData::scale(const glm::vec3 &v) { _localScale += v; _flags |= HAS_MOVED; computeTransformAndUpdateGraphnode(); } void EntityData::setScale(const glm::vec3 &v) { _localScale = v; _flags |= HAS_MOVED; computeTransformAndUpdateGraphnode(); } glm::vec3 const &EntityData::getScale() const { return _localScale; } void EntityData::computeTransformAndUpdateGraphnode() { if (!_parent.get()) { computeGlobalTransform(glm::mat4(1)); } else { computeGlobalTransform(_parent); } for (auto e : _childs) { e->computeTransformAndUpdateGraphnode(); } } size_t EntityData::getFlags() const { return (_flags); } void EntityData::setFlags(size_t flags) { _flags = flags; } void EntityData::addFlags(size_t flags) { _flags |= flags; } void EntityData::removeFlags(size_t flags) { flags &= _flags; _flags ^= flags; } Barcode &EntityData::getCode() { return _code; } void EntityData::addTag(unsigned short tag) { assert(tag < MAX_TAG_NUMBER && "Tags limit is 31"); _code.add(tag); _scene.lock()->informFilters(true, tag, std::move(_handle)); } void EntityData::removeTag(unsigned short tag) { assert(tag < MAX_TAG_NUMBER && "Tags limit is 31"); _code.remove(tag); _scene.lock()->informFilters(false, tag, std::move(_handle)); } bool EntityData::isTagged(unsigned short tag) const { assert(tag < MAX_TAG_NUMBER && "Tags limit is 31"); return _code.isSet(tag); } bool EntityData::isTagged(Barcode &code) { // TODO get the size of the code and assert if > 31 return _code.match(code); } void EntityData::reset() { _flags = 0; _localTranslation = glm::vec3(0); _localRotation = glm::vec3(0); _localScale = glm::vec3(0); _globalTranslation = glm::vec3(0); _globalRotation = glm::vec3(0); _globalScale = glm::vec3(0); _globalTransform = glm::mat4(1); _localTransform = glm::mat4(1); _code.reset(); auto scene = _scene.lock(); for (std::size_t i = 0; i < MAX_TAG_NUMBER; ++i) { if (scene) scene->informFilters(false, static_cast<unsigned short>(i), std::move(_handle)); } for (std::size_t i = 0; i < _components.size(); ++i) { std::size_t id = i + MAX_TAG_NUMBER; if (_components[i].get()) { if (scene) scene->informFilters(false, static_cast<unsigned short>(id), std::move(_handle)); _components[i]->reset(); } _components[i].reset(); } removeParent(); for (auto e : _childs) e->removeParent(false); _childs.clear(); } //////////////// // // Graphnode const Entity &EntityData::getParent() const { return _parent; } void EntityData::removeChild(Entity &child, bool notify) { _childs.erase(child); if (notify) { child->removeParent(false); } } void EntityData::setParent(Entity &parent, bool notify) { if (_parent.get()) { _parent->removeChild(_handle, false); } if (notify) parent->addChild(_handle, false); computeTransformAndUpdateGraphnode(); _parent = parent; } void EntityData::addChild(Entity &child, bool notify) { _childs.insert(child); if (notify) { child->setParent(_handle, false); } } void EntityData::removeParent(bool notify) { if (notify && _parent.get()) { _parent->removeChild(_handle); } _parent = Entity(std::numeric_limits<unsigned int>::max(), nullptr); computeTransformAndUpdateGraphnode(); } std::set<Entity>::iterator EntityData::getChildsBegin() { return std::begin(_childs); } std::set<Entity>::iterator EntityData::getChildsEnd() { return std::end(_childs); } <|endoftext|>
<commit_before>// binding.cc #include <node.h> #include "../deps/murmurhash.c/murmurhash.h" namespace murmurhashlib { using v8::FunctionCallbackInfo; using v8::Isolate; using v8::Value; using v8::Object; using v8::Local; using v8::Exception; using v8::String; void Murmurhash(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); // We check arguments in murmurhash.js; no need here String::Utf8Value key(args[0]->ToString()); uint32_t seed = args[1]->Int32Value(); uint32_t hash = murmurhash(*key, key.length(), seed); args.GetReturnValue().Set(hash); } void Initialize(Local<Object> exports) { NODE_SET_METHOD(exports, "hash", Murmurhash); } NODE_MODULE(murmurhash, Initialize) } <commit_msg>remove unnecessary isolate<commit_after>// binding.cc #include <node.h> #include "../deps/murmurhash.c/murmurhash.h" namespace murmurhashlib { using v8::FunctionCallbackInfo; using v8::Isolate; using v8::Value; using v8::Object; using v8::Local; using v8::Exception; using v8::String; void Murmurhash(const FunctionCallbackInfo<Value>& args) { // We check arguments in murmurhash.js; no need here String::Utf8Value key(args[0]->ToString()); uint32_t seed = args[1]->Int32Value(); uint32_t hash = murmurhash(*key, key.length(), seed); args.GetReturnValue().Set(hash); } void Initialize(Local<Object> exports) { NODE_SET_METHOD(exports, "hash", Murmurhash); } NODE_MODULE(murmurhash, Initialize) } <|endoftext|>
<commit_before>/* * GuildTerminalImplementation.cpp * * Created on: May 9, 2010 * Author: crush */ #include "server/zone/objects/tangible/terminal/guild/GuildTerminal.h" #include "server/zone/ZoneServer.h" #include "server/zone/objects/creature/CreatureObject.h" #include "server/zone/objects/player/PlayerObject.h" #include "server/zone/packets/object/ObjectMenuResponse.h" #include "server/zone/objects/guild/GuildObject.h" #include "server/zone/managers/guild/GuildManager.h" #include "server/zone/managers/player/PlayerManager.h" #include "server/zone/objects/building/BuildingObject.h" void GuildTerminalImplementation::fillObjectMenuResponse(ObjectMenuResponse* menuResponse, CreatureObject* player) { if (guildObject == NULL) { ManagedReference<BuildingObject*> building = cast<BuildingObject*>( getParentRecursively(SceneObjectType::BUILDING).get().get()); if (building != NULL && building->isOwnerOf(player)) { if (!player->isInGuild()) { menuResponse->addRadialMenuItem(185, 3, "@guild:menu_create"); //Create Guild return; } //If the owner is already in a guild, and this guild terminal doesn't have a guild assigned yet, //then use the owner's guild. guildObject = player->getGuildObject(); } else { //They don't have permission to create a guild. return; } } uint64 playerID = player->getObjectID(); //Only members have access. if (!guildObject->hasMember(playerID) && !player->getPlayerObject()->isPrivileged()) return; //Guild exists -> display these functions. menuResponse->addRadialMenuItem(193, 3, "@guild:menu_guild_management"); //Guild Management menuResponse->addRadialMenuItemToRadialID(193, 186, 3, "@guild:menu_info"); //Guild Information menuResponse->addRadialMenuItemToRadialID(193, 189, 3, "@guild:menu_enemies"); //Guild Enemies if ( guildObject->getGuildLeaderID() == playerID ) menuResponse->addRadialMenuItemToRadialID(193, 195, 3, "@guild:accept_hall"); // Accept if (guildObject->hasDisbandPermission(playerID)) menuResponse->addRadialMenuItemToRadialID(193, 191, 3, "@guild:menu_disband"); //Disband Guild if (guildObject->hasNamePermission(playerID) || player->getPlayerObject()->isPrivileged()) menuResponse->addRadialMenuItemToRadialID(193, 192, 3, "@guild:menu_namechange"); //Change Guild Name menuResponse->addRadialMenuItemToRadialID(193, 68, 3, "@guild:menu_enable_elections"); //Enable/Disable Elections menuResponse->addRadialMenuItem(194, 3, "@guild:menu_member_management"); //Member Management menuResponse->addRadialMenuItemToRadialID(194, 187, 3, "@guild:menu_members"); //Guild Members if (guildObject->getSponsoredPlayerCount() > 0) menuResponse->addRadialMenuItemToRadialID(194, 188, 3, "@guild:menu_sponsored"); //Sponsored for Membership menuResponse->addRadialMenuItemToRadialID(194, 190, 3, "@guild:menu_sponsor"); //Sponsor for Membership if (guildObject->getGuildLeaderID() == playerID || player->getPlayerObject()->isPrivileged()) menuResponse->addRadialMenuItemToRadialID(194, 69, 3, "@guild:menu_leader_change"); //Transfer PA Leadership return; } int GuildTerminalImplementation::handleObjectMenuSelect(CreatureObject* player, byte selectedID) { Locker _lock(_this.get()); ManagedReference<GuildManager*> guildManager = server->getZoneServer()->getGuildManager(); if (guildManager == NULL) return TerminalImplementation::handleObjectMenuSelect(player, selectedID); switch (selectedID) { case 69: guildManager->sendGuildTransferTo(player, _this.get()); break; case 185: guildManager->sendGuildCreateNameTo(player, _this.get()); break; case 189: guildManager->sendGuildWarStatusTo(player, guildObject, _this.get()); break; case 193: case 186: guildManager->sendGuildInformationTo(player, guildObject, _this.get()); break; case 191: guildManager->sendGuildDisbandConfirmTo(player, guildObject, _this.get()); break; case 194: case 187: guildManager->sendGuildMemberListTo(player, guildObject, _this.get()); break; case 188: guildManager->sendGuildSponsoredListTo(player, guildObject, _this.get()); break; case 190: guildManager->sendGuildSponsorTo(player, guildObject, _this.get()); break; case 192: guildManager->sendGuildChangeNameTo(player, guildObject, _this.get()); break; case 195: guildManager->sendAcceptLotsTo(player, _this.get()); break; default: TerminalImplementation::handleObjectMenuSelect(player, selectedID); } return 0; } <commit_msg>[Fixed] Mantis #5343<commit_after>/* * GuildTerminalImplementation.cpp * * Created on: May 9, 2010 * Author: crush */ #include "server/zone/objects/tangible/terminal/guild/GuildTerminal.h" #include "server/zone/ZoneServer.h" #include "server/zone/objects/creature/CreatureObject.h" #include "server/zone/objects/player/PlayerObject.h" #include "server/zone/packets/object/ObjectMenuResponse.h" #include "server/zone/objects/guild/GuildObject.h" #include "server/zone/managers/guild/GuildManager.h" #include "server/zone/managers/player/PlayerManager.h" #include "server/zone/objects/building/BuildingObject.h" void GuildTerminalImplementation::fillObjectMenuResponse(ObjectMenuResponse* menuResponse, CreatureObject* player) { if (guildObject == NULL) { ManagedReference<BuildingObject*> building = cast<BuildingObject*>( getParentRecursively(SceneObjectType::BUILDING).get().get()); if (building != NULL && building->isOwnerOf(player)) { if (!player->isInGuild()) { menuResponse->addRadialMenuItem(185, 3, "@guild:menu_create"); //Create Guild return; } //If the owner is already in a guild, and this guild terminal doesn't have a guild assigned yet, //then use the owner's guild. guildObject = player->getGuildObject(); } else { //They don't have permission to create a guild. return; } } uint64 playerID = player->getObjectID(); //Only members have access. if (!guildObject->hasMember(playerID) && !player->getPlayerObject()->isPrivileged()) return; //Guild exists -> display these functions. menuResponse->addRadialMenuItem(193, 3, "@guild:menu_guild_management"); //Guild Management menuResponse->addRadialMenuItemToRadialID(193, 186, 3, "@guild:menu_info"); //Guild Information menuResponse->addRadialMenuItemToRadialID(193, 189, 3, "@guild:menu_enemies"); //Guild Enemies if ( guildObject->getGuildLeaderID() == playerID ) menuResponse->addRadialMenuItemToRadialID(193, 195, 3, "@guild:accept_hall"); // Accept if (guildObject->hasDisbandPermission(playerID)) menuResponse->addRadialMenuItemToRadialID(193, 191, 3, "@guild:menu_disband"); //Disband Guild if (guildObject->hasNamePermission(playerID) || player->getPlayerObject()->isPrivileged()) menuResponse->addRadialMenuItemToRadialID(193, 192, 3, "@guild:menu_namechange"); //Change Guild Name menuResponse->addRadialMenuItemToRadialID(193, 68, 3, "@guild:menu_enable_elections"); //Enable/Disable Elections menuResponse->addRadialMenuItem(194, 3, "@guild:menu_member_management"); //Member Management menuResponse->addRadialMenuItemToRadialID(194, 187, 3, "@guild:menu_members"); //Guild Members if (guildObject->getSponsoredPlayerCount() > 0) menuResponse->addRadialMenuItemToRadialID(194, 188, 3, "@guild:menu_sponsored"); //Sponsored for Membership menuResponse->addRadialMenuItemToRadialID(194, 190, 3, "@guild:menu_sponsor"); //Sponsor for Membership if (guildObject->getGuildLeaderID() == playerID || player->getPlayerObject()->isPrivileged()) menuResponse->addRadialMenuItemToRadialID(194, 69, 3, "@guild:menu_leader_change"); //Transfer PA Leadership return; } int GuildTerminalImplementation::handleObjectMenuSelect(CreatureObject* player, byte selectedID) { Locker _lock(_this.get()); ManagedReference<GuildManager*> guildManager = server->getZoneServer()->getGuildManager(); if (guildManager == NULL) return TerminalImplementation::handleObjectMenuSelect(player, selectedID); uint64 playerID = player->getObjectID(); switch (selectedID) { case 69: if (guildObject->getGuildLeaderID() == playerID || player->getPlayerObject()->isPrivileged()) { guildManager->sendGuildTransferTo(player, _this.get()); } break; case 185: guildManager->sendGuildCreateNameTo(player, _this.get()); break; case 189: guildManager->sendGuildWarStatusTo(player, guildObject, _this.get()); break; case 193: case 186: guildManager->sendGuildInformationTo(player, guildObject, _this.get()); break; case 191: guildManager->sendGuildDisbandConfirmTo(player, guildObject, _this.get()); break; case 194: case 187: guildManager->sendGuildMemberListTo(player, guildObject, _this.get()); break; case 188: guildManager->sendGuildSponsoredListTo(player, guildObject, _this.get()); break; case 190: guildManager->sendGuildSponsorTo(player, guildObject, _this.get()); break; case 192: guildManager->sendGuildChangeNameTo(player, guildObject, _this.get()); break; case 195: if ( guildObject->getGuildLeaderID() == playerID ) { guildManager->sendAcceptLotsTo(player, _this.get()); } break; default: TerminalImplementation::handleObjectMenuSelect(player, selectedID); } return 0; } <|endoftext|>
<commit_before>#ifndef _SDD_ORDER_ORDER_HH_ #define _SDD_ORDER_ORDER_HH_ #include <initializer_list> #include <memory> #include <vector> #include <boost/optional.hpp> #include "sdd/conf/variable_traits.hh" namespace sdd { namespace order { /// @cond INTERNAL_DOC /*-------------------------------------------------------------------------------------------*/ // Forward declaration of an order's node. template <typename C> struct node; /*-------------------------------------------------------------------------------------------*/ /// @brief Represent an order of identifiers. template <typename C> using order_ptr_type = std::shared_ptr<node<C>>; /*-------------------------------------------------------------------------------------------*/ /// @brief An element of a linked list of nodes, associating a (library) variable to an (user) /// identifier. /// /// We create our own type rather than using std::list. This is beacause we don't want the user /// to add identifier to an order which has already been added as a nested order. template <typename C> struct node { /// @brief A variable type. typedef typename C::Variable variable_type; /// @brief An identifier type. typedef typename C::Identifier identifier_type; /// @brief The library variable. /// /// A variable is automatically assigned to an identifier by the library. const variable_type variable; /// @brief The user identifier. /// /// When nullptr, it's an artificial node. That is, a node generated by the library. const std::unique_ptr<identifier_type> identifier; /// @brief The nested order. /// /// If empty, the node is a flat node. const order_ptr_type<C> nested; /// @brief The node's next variable. const order_ptr_type<C> next; /// @brief Constructor. node( const variable_type& var, std::unique_ptr<identifier_type>&& id , order_ptr_type<C> nst, order_ptr_type<C> nxt) : variable(var) , identifier(std::move(id)) , nested(nst) , next(nxt) { } }; /// @endcond /*-------------------------------------------------------------------------------------------*/ /// @brief Represent an order of identifiers. template <typename C> class order { public: /// @brief The type of a variable. typedef typename C::Variable variable_type; /// @brief The type of an identifier. typedef typename C::Identifier identifier_type; /// @cond INTERNAL_DOC private: /// @brief The concrete order. order_ptr_type<C> order_ptr_; public: /// @brief Constructor. order(const order_ptr_type<C>& ptr) : order_ptr_(ptr) { } /// @brief Get the concrete order. const order_ptr_type<C>& ptr() const noexcept { return order_ptr_; } /// @endcond /// @brief Default constructor. order() : order_ptr_(nullptr) { } /// @brief Constructor from a list of identifiers. template <typename InputIterator> order(InputIterator begin, InputIterator end) : order() { std::vector<identifier_type> tmp(begin, end); for (auto rcit = tmp.crbegin(); rcit != tmp.crend(); ++rcit) { add(*rcit); } } /// @brief Constructor from a list of identifiers. order(std::initializer_list<identifier_type> list) : order(list.begin(), list.end()) { } /// @brief Copy operator. order& operator=(const order& other) { order_ptr_ = other.order_ptr_; return *this; } /// @brief Tell if this order is empty. /// /// It's unsafe to call any other method, except add(), if this order is empty. bool empty() const noexcept { return not order_ptr_; } /// @brief Get the variable of this order's head. const variable_type& variable() const noexcept { return order_ptr_->variable; } /// @brief Get the idetifier of this order's head. const identifier_type& identifier() const noexcept { return *order_ptr_->identifier; } /// @brief Get this order's head's next order. order next() const noexcept { return order(order_ptr_->next); } /// @brief Get this order's head's nested order. order nested() const noexcept { return order(order_ptr_->nested); } /// @brief Get the variable of an identifier const variable_type& identifier_variable(const identifier_type& id) const { std::function<boost::optional<variable_type>(const order_ptr_type<C>&)> helper; helper = [&helper, &id](const order_ptr_type<C>& ptr) -> boost::optional<variable_type> { if (not ptr) { return boost::optional<variable_type>(); } if (ptr->identifier and id == *ptr->identifier) { return ptr->variable; } if (ptr->nested) { const auto res = helper(ptr->nested); if (res) { return res; } } return helper(ptr->next); }; const auto res = helper(order_ptr_); if (res) { return *res; } else { throw std::runtime_error("Identifier not found."); } } order& add(const identifier_type& id) { return add(id, nullptr); } order& add(const identifier_type& id, const order& nested) { return add(id, nested.order_ptr_); } private: order& add(const identifier_type& id, order_ptr_type<C> nested_ptr) { const variable_type var = empty() ? conf::variable_traits<variable_type>::first() : conf::variable_traits<variable_type>::next(variable()); typedef std::unique_ptr<identifier_type> optional_id_type; order_ptr_ = std::make_shared<node<C>>( var , optional_id_type(new identifier_type(id)) , nested_ptr , order_ptr_); return *this; } }; /*-------------------------------------------------------------------------------------------*/ /// @related order template <typename C> std::ostream& operator<<(std::ostream& os, const order<C>& o) { if (not o.empty()) { os << o.identifier(); if (not o.nested().empty()) { os << " | (" << o.nested() << ")"; } if (not o.next().empty()) { os << " >> " << o.next(); } } return os; } /*-------------------------------------------------------------------------------------------*/ }} // namespace sdd::order #endif // _SDD_ORDER_ORDER_HH_ <commit_msg>Comments.<commit_after>#ifndef _SDD_ORDER_ORDER_HH_ #define _SDD_ORDER_ORDER_HH_ #include <initializer_list> #include <iostream> #include <memory> // shared_ptr, unique_ptr #include <vector> #include <boost/optional.hpp> #include "sdd/conf/variable_traits.hh" namespace sdd { namespace order { /// @cond INTERNAL_DOC /*-------------------------------------------------------------------------------------------*/ // Forward declaration of an order's node. template <typename C> struct node; /*-------------------------------------------------------------------------------------------*/ /// @brief Represent an order of identifiers. template <typename C> using order_ptr_type = std::shared_ptr<node<C>>; /*-------------------------------------------------------------------------------------------*/ /// @brief An element of a linked list of nodes, associating a (library) variable to an (user) /// identifier. /// /// We create our own type rather than using std::list. This is beacause we don't want the user /// to add identifier to an order which has already been added as a nested order. template <typename C> struct node { /// @brief A variable type. typedef typename C::Variable variable_type; /// @brief An identifier type. typedef typename C::Identifier identifier_type; /// @brief The library variable. /// /// A variable is automatically assigned to an identifier by the library. const variable_type variable; /// @brief The user identifier. /// /// When nullptr, it's an artificial node. That is, a node generated by the library. const std::unique_ptr<identifier_type> identifier; /// @brief The nested order. /// /// If nullptr, this node is a flat node. const order_ptr_type<C> nested; /// @brief The node's next variable. /// /// If nullptr, this node is the last one. const order_ptr_type<C> next; /// @brief Constructor. node( const variable_type& var, std::unique_ptr<identifier_type>&& id , order_ptr_type<C> nst, order_ptr_type<C> nxt) : variable(var) , identifier(std::move(id)) , nested(nst) , next(nxt) { } }; /// @endcond /*-------------------------------------------------------------------------------------------*/ /// @brief Represent an order of identifiers. template <typename C> class order { public: /// @brief The type of a variable. typedef typename C::Variable variable_type; /// @brief The type of an identifier. typedef typename C::Identifier identifier_type; /// @cond INTERNAL_DOC private: /// @brief The concrete order. order_ptr_type<C> order_ptr_; public: /// @brief Constructor. order(const order_ptr_type<C>& ptr) : order_ptr_(ptr) { } /// @brief Get the concrete order. const order_ptr_type<C>& ptr() const noexcept { return order_ptr_; } /// @endcond /// @brief Default constructor. order() : order_ptr_(nullptr) { } /// @brief Constructor from a list of identifiers. template <typename InputIterator> order(InputIterator begin, InputIterator end) : order() { std::vector<identifier_type> tmp(begin, end); for (auto rcit = tmp.crbegin(); rcit != tmp.crend(); ++rcit) { add(*rcit); } } /// @brief Constructor from a list of identifiers. order(std::initializer_list<identifier_type> list) : order(list.begin(), list.end()) { } /// @brief Copy operator. order& operator=(const order& other) { order_ptr_ = other.order_ptr_; return *this; } /// @brief Tell if this order is empty. /// /// It's unsafe to call any other method, except add(), if this order is empty. bool empty() const noexcept { return not order_ptr_; } /// @brief Get the variable of this order's head. const variable_type& variable() const noexcept { return order_ptr_->variable; } /// @brief Get the idetifier of this order's head. const identifier_type& identifier() const noexcept { return *order_ptr_->identifier; } /// @brief Get this order's head's next order. order next() const noexcept { return order(order_ptr_->next); } /// @brief Get this order's head's nested order. order nested() const noexcept { return order(order_ptr_->nested); } /// @brief Get the variable of an identifier const variable_type& identifier_variable(const identifier_type& id) const { std::function<boost::optional<variable_type>(const order_ptr_type<C>&)> helper; helper = [&helper, &id](const order_ptr_type<C>& ptr) -> boost::optional<variable_type> { if (not ptr) { return boost::optional<variable_type>(); } if (ptr->identifier and id == *ptr->identifier) { return ptr->variable; } if (ptr->nested) { const auto res = helper(ptr->nested); if (res) { return res; } } return helper(ptr->next); }; const auto res = helper(order_ptr_); if (res) { return *res; } else { throw std::runtime_error("Identifier not found."); } } order& add(const identifier_type& id) { return add(id, nullptr); } order& add(const identifier_type& id, const order& nested) { return add(id, nested.order_ptr_); } private: order& add(const identifier_type& id, order_ptr_type<C> nested_ptr) { const variable_type var = empty() ? conf::variable_traits<variable_type>::first() : conf::variable_traits<variable_type>::next(variable()); typedef std::unique_ptr<identifier_type> optional_id_type; order_ptr_ = std::make_shared<node<C>>( var , optional_id_type(new identifier_type(id)) , nested_ptr , order_ptr_); return *this; } }; /*-------------------------------------------------------------------------------------------*/ /// @related order template <typename C> std::ostream& operator<<(std::ostream& os, const order<C>& o) { if (not o.empty()) { os << o.identifier(); if (not o.nested().empty()) { os << " | (" << o.nested() << ")"; } if (not o.next().empty()) { os << " >> " << o.next(); } } return os; } /*-------------------------------------------------------------------------------------------*/ }} // namespace sdd::order #endif // _SDD_ORDER_ORDER_HH_ <|endoftext|>
<commit_before>#include "../search/search.hpp" #include "../structs/binheap.hpp" #include "../utils/pool.hpp" #include <limits> #include <vector> #include <cmath> void dfrowhdr(FILE *, const char *name, int ncols, ...); void dfrow(FILE *, const char *name, const char *colfmt, ...); void fatal(const char*, ...); template <class D> struct Arastar : public SearchAlgorithm<D> { typedef typename D::State State; typedef typename D::PackedState PackedState; typedef typename D::Cost Cost; typedef typename D::Oper Oper; struct Node : SearchNode<D> { Cost h; double fprime; static bool pred(Node *a, Node *b) { if (a->fprime == b->fprime) return a->g > b->g; return a->fprime < b->fprime; } }; struct Incons { Incons(unsigned long szhint) : mem(szhint) { } void init(D &d) { mem.init(d); } void add(Node *n, unsigned long h) { if (mem.find(n->packed, h) != NULL) return; mem.add(n); incons.push_back(n); } std::vector<Node*> &nodes(void) { return incons; } void clear(void) { mem.clear(); incons.clear(); } private: ClosedList<SearchNode<D>, SearchNode<D>, D> mem; std::vector<Node*> incons; }; Arastar(int argc, const char *argv[]) : SearchAlgorithm<D>(argc, argv), closed(30000001), incons(30000001) { wt0 = dwt = -1; for (int i = 0; i < argc; i++) { if (i < argc - 1 && strcmp(argv[i], "-wt0") == 0) wt0 = strtod(argv[++i], NULL); else if (i < argc - 1 && strcmp(argv[i], "-dwt") == 0) dwt = strtod(argv[++i], NULL); } if (wt0 < 1) fatal("Must specify initial weight ≥ 1 using -wt0"); if (dwt <= 0) fatal("Must specify weight decrement > 0 using -dwt"); wt = wt0; nodes = new Pool<Node>(); } ~Arastar(void) { delete nodes; } void search(D &d, typename D::State &s0) { this->start(); closed.init(d); incons.init(d); dfrowhdr(stdout, "sol", 6, "num", "nodes expanded", "nodes generated", "weight", "solution bound", "solution cost", "wall time"); Node *n0 = init(d, s0); closed.add(n0); open.push(n0); unsigned long n = 0; do { if (improve(d)) { n++; double epsprime = wt == 1.0 ? 1.0 : findbound(); if (wt < epsprime) epsprime = wt; dfrow(stdout, "sol", "uuugggg", n, this->res.expd, this->res.gend, wt, epsprime, (double) this->res.cost, walltime() - this->res.wallstrt); } if (wt <= 1.0) break; wt = wt - dwt > 1.0 ? wt - dwt : 1.0; if (wt < 1.0 + sqrt(std::numeric_limits<double>::epsilon())) wt = 1.0; updateopen(); closed.clear(); } while(!this->limit() && !open.empty()); this->finish(); } virtual void reset(void) { SearchAlgorithm<D>::reset(); wt = wt0; open.clear(); closed.clear(); incons.clear(); delete nodes; nodes = new Pool<Node>(); } virtual void output(FILE *out) { SearchAlgorithm<D>::output(out); closed.prstats(stdout, "closed "); dfpair(stdout, "open list type", "%s", "binary heap"); dfpair(stdout, "node size", "%u", sizeof(Node)); dfpair(stdout, "initial weight", "%g", wt0); dfpair(stdout, "weight decrement", "%g", dwt); } private: bool improve(D &d) { bool goal = false; while (!this->limit() && goodnodes()) { Node *n = *open.pop(); State buf, &state = d.unpack(buf, n->packed); if (d.isgoal(state)) { this->res.goal(d, n); goal = true; } expand(d, n, state); } return goal; } bool goodnodes() { return !open.empty() && (this->res.cost == Cost(-1) || (double) this->res.cost > (*open.front())->fprime); } // Find the tightest bound for the current incumbent. double findbound(void) { assert (this->res.cost != Cost(-1)); double cost = this->res.cost; double min = std::numeric_limits<double>::infinity(); std::vector<Node*> &inodes = incons.nodes(); for (long i = 0; i < (long) inodes.size(); i++) { Node *n = inodes[i]; double f = n->g + n->h; if (f >= cost) { inodes[i] = inodes[inodes.size()-1]; inodes.pop_back(); i--; continue; } if (f < min) min = f; } std::vector<Node*> &onodes = open.data(); for (long i = 0; i < (long) onodes.size(); i++) { Node *n = onodes[i]; double f = n->g + n->h; if (f >= cost) { onodes[i] = onodes[onodes.size()-1]; onodes.pop_back(); i--; continue; } if (f < min) min = f; } return cost / min; } // Update the open list: update f' values and add INCONS // and re-heapify. void updateopen(void) { std::vector<Node*> &nodes = incons.nodes(); for (unsigned long i = 0; i < nodes.size(); i++) { Node *n = nodes[i]; n->fprime = (double) n->g + wt * n->h; } for (long i = 0; i < open.size(); i++) { Node *n = open.at(i); n->fprime = (double) n->g + wt * n->h; } open.append(incons.nodes()); // reinits heap property incons.clear(); } void expand(D &d, Node *n, State &state) { this->res.expd++; for (unsigned int i = 0; i < d.nops(state); i++) { Oper op = d.nthop(state, i); if (op == n->pop) continue; this->res.gend++; considerkid(d, n, state, op); } } void considerkid(D &d, Node *parent, State &state, Oper op) { Node *kid = nodes->construct(); typename D::Transition tr(d, state, op); kid->g = parent->g + tr.cost; d.pack(kid->packed, tr.state); unsigned long hash = kid->packed.hash(); Node *dup = static_cast<Node*>(closed.find(kid->packed, hash)); if (dup) { this->res.dups++; if (kid->g >= dup->g) { nodes->destruct(kid); return; } this->res.reopnd++; dup->fprime = dup->fprime - dup->g + kid->g; dup->update(kid->g, parent, op, tr.revop); if (dup->openind < 0) incons.add(dup, hash); else open.update(dup->openind); nodes->destruct(kid); } else { kid->h = d.h(tr.state); kid->fprime = (double) kid->g + wt * kid->h; kid->update(kid->g, parent, op, tr.revop); closed.add(kid, hash); open.push(kid); } } Node *init(D &d, State &s0) { Node *n0 = nodes->construct(); d.pack(n0->packed, s0); n0->g = Cost(0); n0->h = d.h(s0); n0->fprime = wt * n0->h; n0->op = n0->pop = D::Nop; n0->parent = NULL; return n0; } double wt0, dwt, wt; BinHeap<Node, Node*> open; ClosedList<SearchNode<D>, SearchNode<D>, D> closed; Incons incons; Pool<Node> *nodes; }; <commit_msg>arastar: output the wall time column header.<commit_after>#include "../search/search.hpp" #include "../structs/binheap.hpp" #include "../utils/pool.hpp" #include <limits> #include <vector> #include <cmath> void dfrowhdr(FILE *, const char *name, int ncols, ...); void dfrow(FILE *, const char *name, const char *colfmt, ...); void fatal(const char*, ...); template <class D> struct Arastar : public SearchAlgorithm<D> { typedef typename D::State State; typedef typename D::PackedState PackedState; typedef typename D::Cost Cost; typedef typename D::Oper Oper; struct Node : SearchNode<D> { Cost h; double fprime; static bool pred(Node *a, Node *b) { if (a->fprime == b->fprime) return a->g > b->g; return a->fprime < b->fprime; } }; struct Incons { Incons(unsigned long szhint) : mem(szhint) { } void init(D &d) { mem.init(d); } void add(Node *n, unsigned long h) { if (mem.find(n->packed, h) != NULL) return; mem.add(n); incons.push_back(n); } std::vector<Node*> &nodes(void) { return incons; } void clear(void) { mem.clear(); incons.clear(); } private: ClosedList<SearchNode<D>, SearchNode<D>, D> mem; std::vector<Node*> incons; }; Arastar(int argc, const char *argv[]) : SearchAlgorithm<D>(argc, argv), closed(30000001), incons(30000001) { wt0 = dwt = -1; for (int i = 0; i < argc; i++) { if (i < argc - 1 && strcmp(argv[i], "-wt0") == 0) wt0 = strtod(argv[++i], NULL); else if (i < argc - 1 && strcmp(argv[i], "-dwt") == 0) dwt = strtod(argv[++i], NULL); } if (wt0 < 1) fatal("Must specify initial weight ≥ 1 using -wt0"); if (dwt <= 0) fatal("Must specify weight decrement > 0 using -dwt"); wt = wt0; nodes = new Pool<Node>(); } ~Arastar(void) { delete nodes; } void search(D &d, typename D::State &s0) { this->start(); closed.init(d); incons.init(d); dfrowhdr(stdout, "sol", 7, "num", "nodes expanded", "nodes generated", "weight", "solution bound", "solution cost", "wall time"); Node *n0 = init(d, s0); closed.add(n0); open.push(n0); unsigned long n = 0; do { if (improve(d)) { n++; double epsprime = wt == 1.0 ? 1.0 : findbound(); if (wt < epsprime) epsprime = wt; dfrow(stdout, "sol", "uuugggg", n, this->res.expd, this->res.gend, wt, epsprime, (double) this->res.cost, walltime() - this->res.wallstrt); } if (wt <= 1.0) break; wt = wt - dwt > 1.0 ? wt - dwt : 1.0; if (wt < 1.0 + sqrt(std::numeric_limits<double>::epsilon())) wt = 1.0; updateopen(); closed.clear(); } while(!this->limit() && !open.empty()); this->finish(); } virtual void reset(void) { SearchAlgorithm<D>::reset(); wt = wt0; open.clear(); closed.clear(); incons.clear(); delete nodes; nodes = new Pool<Node>(); } virtual void output(FILE *out) { SearchAlgorithm<D>::output(out); closed.prstats(stdout, "closed "); dfpair(stdout, "open list type", "%s", "binary heap"); dfpair(stdout, "node size", "%u", sizeof(Node)); dfpair(stdout, "initial weight", "%g", wt0); dfpair(stdout, "weight decrement", "%g", dwt); } private: bool improve(D &d) { bool goal = false; while (!this->limit() && goodnodes()) { Node *n = *open.pop(); State buf, &state = d.unpack(buf, n->packed); if (d.isgoal(state)) { this->res.goal(d, n); goal = true; } expand(d, n, state); } return goal; } bool goodnodes() { return !open.empty() && (this->res.cost == Cost(-1) || (double) this->res.cost > (*open.front())->fprime); } // Find the tightest bound for the current incumbent. double findbound(void) { assert (this->res.cost != Cost(-1)); double cost = this->res.cost; double min = std::numeric_limits<double>::infinity(); std::vector<Node*> &inodes = incons.nodes(); for (long i = 0; i < (long) inodes.size(); i++) { Node *n = inodes[i]; double f = n->g + n->h; if (f >= cost) { inodes[i] = inodes[inodes.size()-1]; inodes.pop_back(); i--; continue; } if (f < min) min = f; } std::vector<Node*> &onodes = open.data(); for (long i = 0; i < (long) onodes.size(); i++) { Node *n = onodes[i]; double f = n->g + n->h; if (f >= cost) { onodes[i] = onodes[onodes.size()-1]; onodes.pop_back(); i--; continue; } if (f < min) min = f; } return cost / min; } // Update the open list: update f' values and add INCONS // and re-heapify. void updateopen(void) { std::vector<Node*> &nodes = incons.nodes(); for (unsigned long i = 0; i < nodes.size(); i++) { Node *n = nodes[i]; n->fprime = (double) n->g + wt * n->h; } for (long i = 0; i < open.size(); i++) { Node *n = open.at(i); n->fprime = (double) n->g + wt * n->h; } open.append(incons.nodes()); // reinits heap property incons.clear(); } void expand(D &d, Node *n, State &state) { this->res.expd++; for (unsigned int i = 0; i < d.nops(state); i++) { Oper op = d.nthop(state, i); if (op == n->pop) continue; this->res.gend++; considerkid(d, n, state, op); } } void considerkid(D &d, Node *parent, State &state, Oper op) { Node *kid = nodes->construct(); typename D::Transition tr(d, state, op); kid->g = parent->g + tr.cost; d.pack(kid->packed, tr.state); unsigned long hash = kid->packed.hash(); Node *dup = static_cast<Node*>(closed.find(kid->packed, hash)); if (dup) { this->res.dups++; if (kid->g >= dup->g) { nodes->destruct(kid); return; } this->res.reopnd++; dup->fprime = dup->fprime - dup->g + kid->g; dup->update(kid->g, parent, op, tr.revop); if (dup->openind < 0) incons.add(dup, hash); else open.update(dup->openind); nodes->destruct(kid); } else { kid->h = d.h(tr.state); kid->fprime = (double) kid->g + wt * kid->h; kid->update(kid->g, parent, op, tr.revop); closed.add(kid, hash); open.push(kid); } } Node *init(D &d, State &s0) { Node *n0 = nodes->construct(); d.pack(n0->packed, s0); n0->g = Cost(0); n0->h = d.h(s0); n0->fprime = wt * n0->h; n0->op = n0->pop = D::Nop; n0->parent = NULL; return n0; } double wt0, dwt, wt; BinHeap<Node, Node*> open; ClosedList<SearchNode<D>, SearchNode<D>, D> closed; Incons incons; Pool<Node> *nodes; }; <|endoftext|>
<commit_before>/* * Copyright (c) 2014-2022 Patrizio Bekerle -- <patrizio@bekerle.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 2 of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * */ #include "qplaintexteditsearchwidget.h" #include <QDebug> #include <QEvent> #include <QKeyEvent> #include "ui_qplaintexteditsearchwidget.h" QPlainTextEditSearchWidget::QPlainTextEditSearchWidget(QPlainTextEdit *parent) : QWidget(parent), ui(new Ui::QPlainTextEditSearchWidget), selectionColor(0, 180, 0, 100) { ui->setupUi(this); _textEdit = parent; _darkMode = false; hide(); ui->searchCountLabel->setStyleSheet(QStringLiteral("* {color: grey}")); // hiding will leave a open space in the horizontal layout ui->searchCountLabel->setEnabled(false); _currentSearchResult = 0; _searchResultCount = 0; connect(ui->closeButton, &QPushButton::clicked, this, &QPlainTextEditSearchWidget::deactivate); connect(ui->searchLineEdit, &QLineEdit::textChanged, this, &QPlainTextEditSearchWidget::searchLineEditTextChanged); connect(ui->searchDownButton, &QPushButton::clicked, this, &QPlainTextEditSearchWidget::doSearchDown); connect(ui->searchUpButton, &QPushButton::clicked, this, &QPlainTextEditSearchWidget::doSearchUp); connect(ui->replaceToggleButton, &QPushButton::toggled, this, &QPlainTextEditSearchWidget::setReplaceMode); connect(ui->replaceButton, &QPushButton::clicked, this, &QPlainTextEditSearchWidget::doReplace); connect(ui->replaceAllButton, &QPushButton::clicked, this, &QPlainTextEditSearchWidget::doReplaceAll); connect(&_debounceTimer, &QTimer::timeout, this, &QPlainTextEditSearchWidget::performSearch); installEventFilter(this); ui->searchLineEdit->installEventFilter(this); ui->replaceLineEdit->installEventFilter(this); #ifdef Q_OS_MAC // set the spacing to 8 for OS X layout()->setSpacing(8); ui->buttonFrame->layout()->setSpacing(9); // set the margin to 0 for the top buttons for OS X QString buttonStyle = "QPushButton {margin: 0}"; ui->closeButton->setStyleSheet(buttonStyle); ui->searchDownButton->setStyleSheet(buttonStyle); ui->searchUpButton->setStyleSheet(buttonStyle); ui->replaceToggleButton->setStyleSheet(buttonStyle); ui->matchCaseSensitiveButton->setStyleSheet(buttonStyle); #endif } QPlainTextEditSearchWidget::~QPlainTextEditSearchWidget() { delete ui; } void QPlainTextEditSearchWidget::activate() { activate(true); } void QPlainTextEditSearchWidget::activateReplace() { // replacing is prohibited if the text edit is readonly if (_textEdit->isReadOnly()) { return; } ui->searchLineEdit->setText(_textEdit->textCursor().selectedText()); ui->searchLineEdit->selectAll(); activate(); setReplaceMode(true); } void QPlainTextEditSearchWidget::deactivate() { stopDebounce(); hide(); // Clear the search extra selections when closing the search bar clearSearchExtraSelections(); _textEdit->setFocus(); } void QPlainTextEditSearchWidget::setReplaceMode(bool enabled) { ui->replaceToggleButton->setChecked(enabled); ui->replaceLabel->setVisible(enabled); ui->replaceLineEdit->setVisible(enabled); ui->modeLabel->setVisible(enabled); ui->buttonFrame->setVisible(enabled); ui->matchCaseSensitiveButton->setVisible(enabled); } bool QPlainTextEditSearchWidget::eventFilter(QObject *obj, QEvent *event) { if (event->type() == QEvent::KeyPress) { auto *keyEvent = static_cast<QKeyEvent *>(event); if (keyEvent->key() == Qt::Key_Escape) { deactivate(); return true; } else if (!_debounceTimer.isActive() && (keyEvent->modifiers().testFlag(Qt::ShiftModifier) && (keyEvent->key() == Qt::Key_Return)) || (keyEvent->key() == Qt::Key_Up)) { doSearchUp(); return true; } else if (!_debounceTimer.isActive() && ((keyEvent->key() == Qt::Key_Return) || (keyEvent->key() == Qt::Key_Down))) { doSearchDown(); return true; } else if (!_debounceTimer.isActive() && keyEvent->key() == Qt::Key_F3) { doSearch(!keyEvent->modifiers().testFlag(Qt::ShiftModifier)); return true; } // if ((obj == ui->replaceLineEdit) && (keyEvent->key() == // Qt::Key_Tab) // && ui->replaceToggleButton->isChecked()) { // ui->replaceLineEdit->setFocus(); // } return false; } return QWidget::eventFilter(obj, event); } void QPlainTextEditSearchWidget::searchLineEditTextChanged( const QString &arg1) { _searchTerm = arg1; if (_debounceTimer.interval() != 0 && !_searchTerm.isEmpty()) { _debounceTimer.start(); ui->searchDownButton->setEnabled(false); ui->searchUpButton->setEnabled(false); } else { performSearch(); } } void QPlainTextEditSearchWidget::performSearch() { const int searchMode = ui->modeComboBox->currentIndex(); if (searchMode == RegularExpressionMode) { // Prevent stuck application when the user enters just start or end markers static const QRegularExpression regExp(R"(^[\^\$]+$)"); if (regExp.match(_searchTerm).hasMatch()) { clearSearchExtraSelections(); if (_debounceTimer.isActive()) { stopDebounce(); } return; } } doSearchCount(); updateSearchExtraSelections(); doSearchDown(); } void QPlainTextEditSearchWidget::clearSearchExtraSelections() { _searchExtraSelections.clear(); setSearchExtraSelections(); } void QPlainTextEditSearchWidget::updateSearchExtraSelections() { _searchExtraSelections.clear(); const auto textCursor = _textEdit->textCursor(); _textEdit->moveCursor(QTextCursor::Start); const QColor color = selectionColor; QTextCharFormat extraFmt; extraFmt.setBackground(color); while (doSearch(true, false, false)) { QTextEdit::ExtraSelection extra = QTextEdit::ExtraSelection(); extra.format = extraFmt; extra.cursor = _textEdit->textCursor(); _searchExtraSelections.append(extra); } _textEdit->setTextCursor(textCursor); this->setSearchExtraSelections(); } void QPlainTextEditSearchWidget::setSearchExtraSelections() const { this->_textEdit->setExtraSelections(this->_searchExtraSelections); } void QPlainTextEditSearchWidget::stopDebounce() { _debounceTimer.stop(); ui->searchDownButton->setEnabled(true); ui->searchUpButton->setEnabled(true); } void QPlainTextEditSearchWidget::doSearchUp() { doSearch(false); } void QPlainTextEditSearchWidget::doSearchDown() { doSearch(true); } bool QPlainTextEditSearchWidget::doReplace(bool forAll) { if (_textEdit->isReadOnly()) { return false; } QTextCursor cursor = _textEdit->textCursor(); if (!forAll && cursor.selectedText().isEmpty()) { return false; } const int searchMode = ui->modeComboBox->currentIndex(); if (searchMode == RegularExpressionMode) { QString text = cursor.selectedText(); text.replace(QRegularExpression(ui->searchLineEdit->text()), ui->replaceLineEdit->text()); cursor.insertText(text); } else { cursor.insertText(ui->replaceLineEdit->text()); } if (!forAll) { const int position = cursor.position(); if (!doSearch(true)) { // restore the last cursor position if text wasn't found any more cursor.setPosition(position); _textEdit->setTextCursor(cursor); } } return true; } void QPlainTextEditSearchWidget::doReplaceAll() { if (_textEdit->isReadOnly()) { return; } // start at the top _textEdit->moveCursor(QTextCursor::Start); // replace until everything to the bottom is replaced while (doSearch(true, false) && doReplace(true)) { } } /** * @brief Searches for text in the text edit * @returns true if found */ bool QPlainTextEditSearchWidget::doSearch(bool searchDown, bool allowRestartAtTop, bool updateUI) { if (_debounceTimer.isActive()) { stopDebounce(); } const QString text = ui->searchLineEdit->text(); if (text.isEmpty()) { if (updateUI) { ui->searchLineEdit->setStyleSheet(QLatin1String("")); } return false; } const int searchMode = ui->modeComboBox->currentIndex(); const bool caseSensitive = ui->matchCaseSensitiveButton->isChecked(); QFlags<QTextDocument::FindFlag> options = searchDown ? QTextDocument::FindFlag(0) : QTextDocument::FindBackward; if (searchMode == WholeWordsMode) { options |= QTextDocument::FindWholeWords; } if (caseSensitive) { options |= QTextDocument::FindCaseSensitively; } // block signal to reduce too many signals being fired and too many updates _textEdit->blockSignals(true); bool found = searchMode == RegularExpressionMode ? #if (QT_VERSION >= QT_VERSION_CHECK(5, 13, 0)) _textEdit->find( QRegularExpression( text, caseSensitive ? QRegularExpression::NoPatternOption : QRegularExpression::CaseInsensitiveOption), options) : #else _textEdit->find(QRegExp(text, caseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive), options) : #endif _textEdit->find(text, options); _textEdit->blockSignals(false); if (found) { const int result = searchDown ? ++_currentSearchResult : --_currentSearchResult; _currentSearchResult = std::min(result, _searchResultCount); updateSearchCountLabelText(); } // start at the top (or bottom) if not found if (!found && allowRestartAtTop) { _textEdit->moveCursor(searchDown ? QTextCursor::Start : QTextCursor::End); found = searchMode == RegularExpressionMode ? #if (QT_VERSION >= QT_VERSION_CHECK(5, 13, 0)) _textEdit->find( QRegularExpression( text, caseSensitive ? QRegularExpression::NoPatternOption : QRegularExpression::CaseInsensitiveOption), options) : #else _textEdit->find( QRegExp(text, caseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive), options) : #endif _textEdit->find(text, options); if (found && updateUI) { _currentSearchResult = searchDown ? 1 : _searchResultCount; updateSearchCountLabelText(); } } if (updateUI) { const QRect rect = _textEdit->cursorRect(); QMargins margins = _textEdit->layout()->contentsMargins(); const int searchWidgetHotArea = _textEdit->height() - this->height(); const int marginBottom = (rect.y() > searchWidgetHotArea) ? (this->height() + 10) : 0; // move the search box a bit up if we would block the search result if (margins.bottom() != marginBottom) { margins.setBottom(marginBottom); _textEdit->layout()->setContentsMargins(margins); } // add a background color according if we found the text or not const QString bgColorCode = _darkMode ? (found ? QStringLiteral("#135a13") : QStringLiteral("#8d2b36")) : found ? QStringLiteral("#D5FAE2") : QStringLiteral("#FAE9EB"); const QString fgColorCode = _darkMode ? QStringLiteral("#cccccc") : QStringLiteral("#404040"); ui->searchLineEdit->setStyleSheet( QStringLiteral("* { background: ") + bgColorCode + QStringLiteral("; color: ") + fgColorCode + QStringLiteral("; }")); // restore the search extra selections after the find command this->setSearchExtraSelections(); } return found; } /** * @brief Counts the search results */ void QPlainTextEditSearchWidget::doSearchCount() { // Note that we are moving the anchor, so the search will start from the top // again! Alternative: Restore cursor position afterwards, but then we will // not know // at what _currentSearchResult we currently are _textEdit->moveCursor(QTextCursor::Start, QTextCursor::MoveAnchor); bool found; _searchResultCount = 0; _currentSearchResult = 0; do { found = doSearch(true, false, false); if (found) { _searchResultCount++; } } while (found); updateSearchCountLabelText(); } void QPlainTextEditSearchWidget::setDarkMode(bool enabled) { _darkMode = enabled; } void QPlainTextEditSearchWidget::setSearchText(const QString &searchText) { ui->searchLineEdit->setText(searchText); } void QPlainTextEditSearchWidget::setSearchMode(SearchMode searchMode) { ui->modeComboBox->setCurrentIndex(searchMode); } void QPlainTextEditSearchWidget::setDebounceDelay(uint debounceDelay) { _debounceTimer.setInterval(static_cast<int>(debounceDelay)); } void QPlainTextEditSearchWidget::activate(bool focus) { setReplaceMode(ui->modeComboBox->currentIndex() != SearchMode::PlainTextMode); show(); // preset the selected text as search text if there is any and there is no // other search text const QString selectedText = _textEdit->textCursor().selectedText(); if (!selectedText.isEmpty() && ui->searchLineEdit->text().isEmpty()) { ui->searchLineEdit->setText(selectedText); } if (focus) { ui->searchLineEdit->setFocus(); } ui->searchLineEdit->selectAll(); updateSearchExtraSelections(); doSearchDown(); } void QPlainTextEditSearchWidget::reset() { ui->searchLineEdit->clear(); setSearchMode(SearchMode::PlainTextMode); setReplaceMode(false); ui->searchCountLabel->setEnabled(false); } void QPlainTextEditSearchWidget::updateSearchCountLabelText() { ui->searchCountLabel->setEnabled(true); ui->searchCountLabel->setText(QString("%1/%2").arg( _currentSearchResult == 0 ? QChar('-') : QString::number(_currentSearchResult), _searchResultCount == 0 ? QChar('-') : QString::number(_searchResultCount))); } void QPlainTextEditSearchWidget::setSearchSelectionColor(const QColor &color) { selectionColor = color; } void QPlainTextEditSearchWidget::on_modeComboBox_currentIndexChanged( int index) { Q_UNUSED(index) doSearchCount(); doSearchDown(); } void QPlainTextEditSearchWidget::on_matchCaseSensitiveButton_toggled( bool checked) { Q_UNUSED(checked) doSearchCount(); doSearchDown(); } <commit_msg>Fix warning<commit_after>/* * Copyright (c) 2014-2022 Patrizio Bekerle -- <patrizio@bekerle.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 2 of the License. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * */ #include "qplaintexteditsearchwidget.h" #include <QDebug> #include <QEvent> #include <QKeyEvent> #include "ui_qplaintexteditsearchwidget.h" QPlainTextEditSearchWidget::QPlainTextEditSearchWidget(QPlainTextEdit *parent) : QWidget(parent), ui(new Ui::QPlainTextEditSearchWidget), selectionColor(0, 180, 0, 100) { ui->setupUi(this); _textEdit = parent; _darkMode = false; hide(); ui->searchCountLabel->setStyleSheet(QStringLiteral("* {color: grey}")); // hiding will leave a open space in the horizontal layout ui->searchCountLabel->setEnabled(false); _currentSearchResult = 0; _searchResultCount = 0; connect(ui->closeButton, &QPushButton::clicked, this, &QPlainTextEditSearchWidget::deactivate); connect(ui->searchLineEdit, &QLineEdit::textChanged, this, &QPlainTextEditSearchWidget::searchLineEditTextChanged); connect(ui->searchDownButton, &QPushButton::clicked, this, &QPlainTextEditSearchWidget::doSearchDown); connect(ui->searchUpButton, &QPushButton::clicked, this, &QPlainTextEditSearchWidget::doSearchUp); connect(ui->replaceToggleButton, &QPushButton::toggled, this, &QPlainTextEditSearchWidget::setReplaceMode); connect(ui->replaceButton, &QPushButton::clicked, this, &QPlainTextEditSearchWidget::doReplace); connect(ui->replaceAllButton, &QPushButton::clicked, this, &QPlainTextEditSearchWidget::doReplaceAll); connect(&_debounceTimer, &QTimer::timeout, this, &QPlainTextEditSearchWidget::performSearch); installEventFilter(this); ui->searchLineEdit->installEventFilter(this); ui->replaceLineEdit->installEventFilter(this); #ifdef Q_OS_MAC // set the spacing to 8 for OS X layout()->setSpacing(8); ui->buttonFrame->layout()->setSpacing(9); // set the margin to 0 for the top buttons for OS X QString buttonStyle = "QPushButton {margin: 0}"; ui->closeButton->setStyleSheet(buttonStyle); ui->searchDownButton->setStyleSheet(buttonStyle); ui->searchUpButton->setStyleSheet(buttonStyle); ui->replaceToggleButton->setStyleSheet(buttonStyle); ui->matchCaseSensitiveButton->setStyleSheet(buttonStyle); #endif } QPlainTextEditSearchWidget::~QPlainTextEditSearchWidget() { delete ui; } void QPlainTextEditSearchWidget::activate() { activate(true); } void QPlainTextEditSearchWidget::activateReplace() { // replacing is prohibited if the text edit is readonly if (_textEdit->isReadOnly()) { return; } ui->searchLineEdit->setText(_textEdit->textCursor().selectedText()); ui->searchLineEdit->selectAll(); activate(); setReplaceMode(true); } void QPlainTextEditSearchWidget::deactivate() { stopDebounce(); hide(); // Clear the search extra selections when closing the search bar clearSearchExtraSelections(); _textEdit->setFocus(); } void QPlainTextEditSearchWidget::setReplaceMode(bool enabled) { ui->replaceToggleButton->setChecked(enabled); ui->replaceLabel->setVisible(enabled); ui->replaceLineEdit->setVisible(enabled); ui->modeLabel->setVisible(enabled); ui->buttonFrame->setVisible(enabled); ui->matchCaseSensitiveButton->setVisible(enabled); } bool QPlainTextEditSearchWidget::eventFilter(QObject *obj, QEvent *event) { if (event->type() == QEvent::KeyPress) { auto *keyEvent = static_cast<QKeyEvent *>(event); if (keyEvent->key() == Qt::Key_Escape) { deactivate(); return true; } else if (!(_debounceTimer.isActive() && keyEvent->modifiers().testFlag(Qt::ShiftModifier) && (keyEvent->key() == Qt::Key_Return)) || (keyEvent->key() == Qt::Key_Up)) { doSearchUp(); return true; } else if (!_debounceTimer.isActive() && ((keyEvent->key() == Qt::Key_Return) || (keyEvent->key() == Qt::Key_Down))) { doSearchDown(); return true; } else if (!_debounceTimer.isActive() && keyEvent->key() == Qt::Key_F3) { doSearch(!keyEvent->modifiers().testFlag(Qt::ShiftModifier)); return true; } // if ((obj == ui->replaceLineEdit) && (keyEvent->key() == // Qt::Key_Tab) // && ui->replaceToggleButton->isChecked()) { // ui->replaceLineEdit->setFocus(); // } return false; } return QWidget::eventFilter(obj, event); } void QPlainTextEditSearchWidget::searchLineEditTextChanged( const QString &arg1) { _searchTerm = arg1; if (_debounceTimer.interval() != 0 && !_searchTerm.isEmpty()) { _debounceTimer.start(); ui->searchDownButton->setEnabled(false); ui->searchUpButton->setEnabled(false); } else { performSearch(); } } void QPlainTextEditSearchWidget::performSearch() { const int searchMode = ui->modeComboBox->currentIndex(); if (searchMode == RegularExpressionMode) { // Prevent stuck application when the user enters just start or end markers static const QRegularExpression regExp(R"(^[\^\$]+$)"); if (regExp.match(_searchTerm).hasMatch()) { clearSearchExtraSelections(); if (_debounceTimer.isActive()) { stopDebounce(); } return; } } doSearchCount(); updateSearchExtraSelections(); doSearchDown(); } void QPlainTextEditSearchWidget::clearSearchExtraSelections() { _searchExtraSelections.clear(); setSearchExtraSelections(); } void QPlainTextEditSearchWidget::updateSearchExtraSelections() { _searchExtraSelections.clear(); const auto textCursor = _textEdit->textCursor(); _textEdit->moveCursor(QTextCursor::Start); const QColor color = selectionColor; QTextCharFormat extraFmt; extraFmt.setBackground(color); while (doSearch(true, false, false)) { QTextEdit::ExtraSelection extra = QTextEdit::ExtraSelection(); extra.format = extraFmt; extra.cursor = _textEdit->textCursor(); _searchExtraSelections.append(extra); } _textEdit->setTextCursor(textCursor); this->setSearchExtraSelections(); } void QPlainTextEditSearchWidget::setSearchExtraSelections() const { this->_textEdit->setExtraSelections(this->_searchExtraSelections); } void QPlainTextEditSearchWidget::stopDebounce() { _debounceTimer.stop(); ui->searchDownButton->setEnabled(true); ui->searchUpButton->setEnabled(true); } void QPlainTextEditSearchWidget::doSearchUp() { doSearch(false); } void QPlainTextEditSearchWidget::doSearchDown() { doSearch(true); } bool QPlainTextEditSearchWidget::doReplace(bool forAll) { if (_textEdit->isReadOnly()) { return false; } QTextCursor cursor = _textEdit->textCursor(); if (!forAll && cursor.selectedText().isEmpty()) { return false; } const int searchMode = ui->modeComboBox->currentIndex(); if (searchMode == RegularExpressionMode) { QString text = cursor.selectedText(); text.replace(QRegularExpression(ui->searchLineEdit->text()), ui->replaceLineEdit->text()); cursor.insertText(text); } else { cursor.insertText(ui->replaceLineEdit->text()); } if (!forAll) { const int position = cursor.position(); if (!doSearch(true)) { // restore the last cursor position if text wasn't found any more cursor.setPosition(position); _textEdit->setTextCursor(cursor); } } return true; } void QPlainTextEditSearchWidget::doReplaceAll() { if (_textEdit->isReadOnly()) { return; } // start at the top _textEdit->moveCursor(QTextCursor::Start); // replace until everything to the bottom is replaced while (doSearch(true, false) && doReplace(true)) { } } /** * @brief Searches for text in the text edit * @returns true if found */ bool QPlainTextEditSearchWidget::doSearch(bool searchDown, bool allowRestartAtTop, bool updateUI) { if (_debounceTimer.isActive()) { stopDebounce(); } const QString text = ui->searchLineEdit->text(); if (text.isEmpty()) { if (updateUI) { ui->searchLineEdit->setStyleSheet(QLatin1String("")); } return false; } const int searchMode = ui->modeComboBox->currentIndex(); const bool caseSensitive = ui->matchCaseSensitiveButton->isChecked(); QFlags<QTextDocument::FindFlag> options = searchDown ? QTextDocument::FindFlag(0) : QTextDocument::FindBackward; if (searchMode == WholeWordsMode) { options |= QTextDocument::FindWholeWords; } if (caseSensitive) { options |= QTextDocument::FindCaseSensitively; } // block signal to reduce too many signals being fired and too many updates _textEdit->blockSignals(true); bool found = searchMode == RegularExpressionMode ? #if (QT_VERSION >= QT_VERSION_CHECK(5, 13, 0)) _textEdit->find( QRegularExpression( text, caseSensitive ? QRegularExpression::NoPatternOption : QRegularExpression::CaseInsensitiveOption), options) : #else _textEdit->find(QRegExp(text, caseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive), options) : #endif _textEdit->find(text, options); _textEdit->blockSignals(false); if (found) { const int result = searchDown ? ++_currentSearchResult : --_currentSearchResult; _currentSearchResult = std::min(result, _searchResultCount); updateSearchCountLabelText(); } // start at the top (or bottom) if not found if (!found && allowRestartAtTop) { _textEdit->moveCursor(searchDown ? QTextCursor::Start : QTextCursor::End); found = searchMode == RegularExpressionMode ? #if (QT_VERSION >= QT_VERSION_CHECK(5, 13, 0)) _textEdit->find( QRegularExpression( text, caseSensitive ? QRegularExpression::NoPatternOption : QRegularExpression::CaseInsensitiveOption), options) : #else _textEdit->find( QRegExp(text, caseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive), options) : #endif _textEdit->find(text, options); if (found && updateUI) { _currentSearchResult = searchDown ? 1 : _searchResultCount; updateSearchCountLabelText(); } } if (updateUI) { const QRect rect = _textEdit->cursorRect(); QMargins margins = _textEdit->layout()->contentsMargins(); const int searchWidgetHotArea = _textEdit->height() - this->height(); const int marginBottom = (rect.y() > searchWidgetHotArea) ? (this->height() + 10) : 0; // move the search box a bit up if we would block the search result if (margins.bottom() != marginBottom) { margins.setBottom(marginBottom); _textEdit->layout()->setContentsMargins(margins); } // add a background color according if we found the text or not const QString bgColorCode = _darkMode ? (found ? QStringLiteral("#135a13") : QStringLiteral("#8d2b36")) : found ? QStringLiteral("#D5FAE2") : QStringLiteral("#FAE9EB"); const QString fgColorCode = _darkMode ? QStringLiteral("#cccccc") : QStringLiteral("#404040"); ui->searchLineEdit->setStyleSheet( QStringLiteral("* { background: ") + bgColorCode + QStringLiteral("; color: ") + fgColorCode + QStringLiteral("; }")); // restore the search extra selections after the find command this->setSearchExtraSelections(); } return found; } /** * @brief Counts the search results */ void QPlainTextEditSearchWidget::doSearchCount() { // Note that we are moving the anchor, so the search will start from the top // again! Alternative: Restore cursor position afterwards, but then we will // not know // at what _currentSearchResult we currently are _textEdit->moveCursor(QTextCursor::Start, QTextCursor::MoveAnchor); bool found; _searchResultCount = 0; _currentSearchResult = 0; do { found = doSearch(true, false, false); if (found) { _searchResultCount++; } } while (found); updateSearchCountLabelText(); } void QPlainTextEditSearchWidget::setDarkMode(bool enabled) { _darkMode = enabled; } void QPlainTextEditSearchWidget::setSearchText(const QString &searchText) { ui->searchLineEdit->setText(searchText); } void QPlainTextEditSearchWidget::setSearchMode(SearchMode searchMode) { ui->modeComboBox->setCurrentIndex(searchMode); } void QPlainTextEditSearchWidget::setDebounceDelay(uint debounceDelay) { _debounceTimer.setInterval(static_cast<int>(debounceDelay)); } void QPlainTextEditSearchWidget::activate(bool focus) { setReplaceMode(ui->modeComboBox->currentIndex() != SearchMode::PlainTextMode); show(); // preset the selected text as search text if there is any and there is no // other search text const QString selectedText = _textEdit->textCursor().selectedText(); if (!selectedText.isEmpty() && ui->searchLineEdit->text().isEmpty()) { ui->searchLineEdit->setText(selectedText); } if (focus) { ui->searchLineEdit->setFocus(); } ui->searchLineEdit->selectAll(); updateSearchExtraSelections(); doSearchDown(); } void QPlainTextEditSearchWidget::reset() { ui->searchLineEdit->clear(); setSearchMode(SearchMode::PlainTextMode); setReplaceMode(false); ui->searchCountLabel->setEnabled(false); } void QPlainTextEditSearchWidget::updateSearchCountLabelText() { ui->searchCountLabel->setEnabled(true); ui->searchCountLabel->setText(QString("%1/%2").arg( _currentSearchResult == 0 ? QChar('-') : QString::number(_currentSearchResult), _searchResultCount == 0 ? QChar('-') : QString::number(_searchResultCount))); } void QPlainTextEditSearchWidget::setSearchSelectionColor(const QColor &color) { selectionColor = color; } void QPlainTextEditSearchWidget::on_modeComboBox_currentIndexChanged( int index) { Q_UNUSED(index) doSearchCount(); doSearchDown(); } void QPlainTextEditSearchWidget::on_matchCaseSensitiveButton_toggled( bool checked) { Q_UNUSED(checked) doSearchCount(); doSearchDown(); } <|endoftext|>
<commit_before>#include "geometry.h" using namespace mathUtils; bool Geometry::eq(QPointF const &point1, QPointF const &point2, qreal eps) { return Math::eq(point1.x(), point2.x(), eps) && Math::eq(point1.y(), point2.y(), eps); } qreal Geometry::scalarProduct(QVector2D const &vector1, QVector2D const &vector2) { return vector1.x() * vector2.x() + vector1.y() * vector2.y(); } qreal Geometry::vectorProduct(QVector2D const &vector1, QVector2D const &vector2) { return vector1.x() * vector2.y() - vector1.y() * vector2.x(); } QVector2D Geometry::projection(QVector2D const &projected, QVector2D const &target) { QVector2D const normalizedTarget = target.normalized(); // Scalar product is a projection lenght return normalizedTarget * scalarProduct(normalizedTarget, projected); } QPointF Geometry::normalPoint(QLineF const &line, QPointF const &point) { qreal const x1 = line.p1().x(); qreal const y1 = line.p1().y(); qreal const x2 = line.p2().x(); qreal const y2 = line.p2().y(); qreal const x3 = point.x(); qreal const y3 = point.y(); if (x1 == x2) { return QPointF(x2, y3); } qreal const x = (x1 * Math::sqr(y2 - y1) + x3 * Math::sqr(x2 - x1) + (x2 - x1) * (y2 - y1) * (y3 - y1)) / (Math::sqr(y2 - y1) + Math::sqr(x2 - x1)); qreal const y = ((y2 - y1) * (x - x1) / (x2 - x1)) + y1; return QPointF(x, y); } QLineF Geometry::normalLine(QLineF const &line, QPointF const &point) { return QLineF(point, normalPoint(line, point)); } qreal Geometry::distance(QLineF const &line, QPointF const &point) { return normalLine(line, point).length(); } qreal Geometry::distance(QPointF const &point1, QPointF const &point2) { return sqrt(Math::sqr(point1.x() - point2.x()) + Math::sqr(point1.y() - point2.y())); } bool Geometry::intersects(QLineF const &line, QPainterPath const &path) { QPainterPath linePath(line.p1()); linePath.lineTo(line.p2()); return path.intersects(linePath); } QVector2D Geometry::directionVector(qreal angleInDegrees) { return directionVectorRad(angleInDegrees * pi / 180); } QVector2D Geometry::directionVectorRad(qreal angleInRadians) { return QVector2D(cos(angleInRadians), sin(angleInRadians)); } qreal Geometry::tangentLineAt(QPainterPath const &path, QPointF const &point) { qreal const percentage = percentageAt(path, point); return path.angleAtPercent(percentage); } qreal Geometry::percentageAt(QPainterPath const &path, QPointF const &point) { // Approximating percentage iteratively. First iterating by delta=1 percent increment, searching for // the closest point on path. Then repeating with found closest percentage value but with delta=0.1 and so on int const approximationLevel = 4; qreal result = 0.5; qreal delta = 0.01; for (int approximationIteration = 0; approximationIteration < approximationLevel; ++approximationIteration) { qreal minimalPercentage, minimalDistance = 10e10; for (int i = -50; i <= 50; ++i) { qreal const percentage = result + delta * i; QPointF const pointAtPercentage = percentage >= 0 && percentage <= 1 ? path.pointAtPercent(percentage) : QPointF(10e5, 10e5); qreal const distanceAtPercentage = distance(pointAtPercentage, point); if (distanceAtPercentage < minimalDistance) { minimalDistance = distanceAtPercentage; minimalPercentage = percentage; } } result = minimalPercentage; delta /= 10; } return result; } QList<QPointF> Geometry::pathToPoints(QPainterPath const &path) { qreal const polygonIsPointCondition = 0.001; QList<QPolygonF> polygons = path.toFillPolygons(); QList<QPointF> result; foreach (QPolygonF const &polygon, polygons) { if (square(polygon) < polygonIsPointCondition) { result << polygon[0]; } else { return QList<QPointF>(); } } return result; } qreal Geometry::square(QPolygonF const &polygon) { qreal result = 0; for (int i = 0; i < polygon.size(); ++i) { QPointF const p1 = i ? polygon[i-1] : polygon.back(); QPointF const p2 = polygon[i]; result += (p1.x() - p2.x()) * (p1.y() + p2.y()); } return fabs(result) / 2; } QLineF Geometry::veryLongLine(QPointF const &pointOnLine, QVector2D const &directionVector) { qreal const halfLength = 10000; return QLineF(pointOnLine + halfLength * directionVector.toPointF() , pointOnLine - halfLength * directionVector.toPointF()); } QList<QPointF> Geometry::intersection(QLineF const &line, QPainterPath const &path, qreal eps) { QList<QPointF> result; QPointF startPoint; QPointF endPoint; for (int i = 0; i < path.elementCount(); ++i) { QPainterPath::Element const element = path.elementAt(i); // Checking that element belongs to the wall path if (element.isMoveTo()) { endPoint = QPointF(element.x, element.y); continue; } startPoint = endPoint; endPoint = QPointF(element.x, element.y); QLineF currentLine(startPoint, endPoint); QPointF intersectionPoint; // TODO: consider curve cases if (line.intersect(currentLine, &intersectionPoint) != QLineF::NoIntersection && belongs(intersectionPoint, currentLine, eps)) { result << intersectionPoint; } } return result; } QPointF Geometry::closestPointTo(QList<QPointF> const &points, QPointF const &point) { qreal minDistance = 10e10; QPointF closestPoint; foreach (QPointF const &currentPoint, points) { qreal const currentDistance = distance(currentPoint, point); if (currentDistance < minDistance) { closestPoint = currentPoint; minDistance = currentDistance; } } return closestPoint; } bool Geometry::belongs(QPointF const &point, QLineF const &segment, qreal eps) { if (!Math::between(segment.x1(), segment.x2(), point.x(), eps) || !Math::between(segment.y1(), segment.y2(), point.y(), eps)) { return false; } if (eq(point, segment.p1(), eps) || eq(point, segment.p2(), eps)) { return true; } if (Math::eq(segment.x1(), segment.x2(), eps)) { return Math::eq(point.x(), segment.x1(), eps); } return Math::eq(QLineF(segment.p1(), point).angle(), QLineF(point, segment.p2()).angle(), eps); } bool Geometry::belongs(QPointF const &point, QPainterPath const &path, qreal eps) { QPointF startPoint; QPointF endPoint; for (int i = 0; i < path.elementCount(); ++i) { QPainterPath::Element const element = path.elementAt(i); // Checking that element belongs to the wall path if (element.isMoveTo()) { endPoint = QPointF(element.x, element.y); continue; } startPoint = endPoint; endPoint = QPointF(element.x, element.y); // TODO: consider curve cases if (belongs(point, QLineF(startPoint, endPoint)), eps) { return true; } } return false; } bool Geometry::belongs(QLineF const &line, QPainterPath const &path, qreal eps) { int const pointsToCheck = 5; QVector2D const shift = QVector2D(line.p2() - line.p1()) / (pointsToCheck - 1); for (int i = 0; i < pointsToCheck; ++i) { if (!belongs(line.p1() + i * shift.toPointF(), path), eps) { return false; } } return true; } <commit_msg>Fixed uninitialized variable warning<commit_after>#include "geometry.h" using namespace mathUtils; bool Geometry::eq(QPointF const &point1, QPointF const &point2, qreal eps) { return Math::eq(point1.x(), point2.x(), eps) && Math::eq(point1.y(), point2.y(), eps); } qreal Geometry::scalarProduct(QVector2D const &vector1, QVector2D const &vector2) { return vector1.x() * vector2.x() + vector1.y() * vector2.y(); } qreal Geometry::vectorProduct(QVector2D const &vector1, QVector2D const &vector2) { return vector1.x() * vector2.y() - vector1.y() * vector2.x(); } QVector2D Geometry::projection(QVector2D const &projected, QVector2D const &target) { QVector2D const normalizedTarget = target.normalized(); // Scalar product is a projection lenght return normalizedTarget * scalarProduct(normalizedTarget, projected); } QPointF Geometry::normalPoint(QLineF const &line, QPointF const &point) { qreal const x1 = line.p1().x(); qreal const y1 = line.p1().y(); qreal const x2 = line.p2().x(); qreal const y2 = line.p2().y(); qreal const x3 = point.x(); qreal const y3 = point.y(); if (x1 == x2) { return QPointF(x2, y3); } qreal const x = (x1 * Math::sqr(y2 - y1) + x3 * Math::sqr(x2 - x1) + (x2 - x1) * (y2 - y1) * (y3 - y1)) / (Math::sqr(y2 - y1) + Math::sqr(x2 - x1)); qreal const y = ((y2 - y1) * (x - x1) / (x2 - x1)) + y1; return QPointF(x, y); } QLineF Geometry::normalLine(QLineF const &line, QPointF const &point) { return QLineF(point, normalPoint(line, point)); } qreal Geometry::distance(QLineF const &line, QPointF const &point) { return normalLine(line, point).length(); } qreal Geometry::distance(QPointF const &point1, QPointF const &point2) { return sqrt(Math::sqr(point1.x() - point2.x()) + Math::sqr(point1.y() - point2.y())); } bool Geometry::intersects(QLineF const &line, QPainterPath const &path) { QPainterPath linePath(line.p1()); linePath.lineTo(line.p2()); return path.intersects(linePath); } QVector2D Geometry::directionVector(qreal angleInDegrees) { return directionVectorRad(angleInDegrees * pi / 180); } QVector2D Geometry::directionVectorRad(qreal angleInRadians) { return QVector2D(cos(angleInRadians), sin(angleInRadians)); } qreal Geometry::tangentLineAt(QPainterPath const &path, QPointF const &point) { qreal const percentage = percentageAt(path, point); return path.angleAtPercent(percentage); } qreal Geometry::percentageAt(QPainterPath const &path, QPointF const &point) { // Approximating percentage iteratively. First iterating by delta=1 percent increment, searching for // the closest point on path. Then repeating with found closest percentage value but with delta=0.1 and so on int const approximationLevel = 4; qreal result = 0.5; qreal delta = 0.01; for (int approximationIteration = 0; approximationIteration < approximationLevel; ++approximationIteration) { qreal minimalPercentage = 100; qreal minimalDistance = 10e10; for (int i = -50; i <= 50; ++i) { qreal const percentage = result + delta * i; QPointF const pointAtPercentage = percentage >= 0 && percentage <= 1 ? path.pointAtPercent(percentage) : QPointF(10e5, 10e5); qreal const distanceAtPercentage = distance(pointAtPercentage, point); if (distanceAtPercentage < minimalDistance) { minimalDistance = distanceAtPercentage; minimalPercentage = percentage; } } result = minimalPercentage; delta /= 10; } return result; } QList<QPointF> Geometry::pathToPoints(QPainterPath const &path) { qreal const polygonIsPointCondition = 0.001; QList<QPolygonF> polygons = path.toFillPolygons(); QList<QPointF> result; foreach (QPolygonF const &polygon, polygons) { if (square(polygon) < polygonIsPointCondition) { result << polygon[0]; } else { return QList<QPointF>(); } } return result; } qreal Geometry::square(QPolygonF const &polygon) { qreal result = 0; for (int i = 0; i < polygon.size(); ++i) { QPointF const p1 = i ? polygon[i-1] : polygon.back(); QPointF const p2 = polygon[i]; result += (p1.x() - p2.x()) * (p1.y() + p2.y()); } return fabs(result) / 2; } QLineF Geometry::veryLongLine(QPointF const &pointOnLine, QVector2D const &directionVector) { qreal const halfLength = 10000; return QLineF(pointOnLine + halfLength * directionVector.toPointF() , pointOnLine - halfLength * directionVector.toPointF()); } QList<QPointF> Geometry::intersection(QLineF const &line, QPainterPath const &path, qreal eps) { QList<QPointF> result; QPointF startPoint; QPointF endPoint; for (int i = 0; i < path.elementCount(); ++i) { QPainterPath::Element const element = path.elementAt(i); // Checking that element belongs to the wall path if (element.isMoveTo()) { endPoint = QPointF(element.x, element.y); continue; } startPoint = endPoint; endPoint = QPointF(element.x, element.y); QLineF currentLine(startPoint, endPoint); QPointF intersectionPoint; // TODO: consider curve cases if (line.intersect(currentLine, &intersectionPoint) != QLineF::NoIntersection && belongs(intersectionPoint, currentLine, eps)) { result << intersectionPoint; } } return result; } QPointF Geometry::closestPointTo(QList<QPointF> const &points, QPointF const &point) { qreal minDistance = 10e10; QPointF closestPoint; foreach (QPointF const &currentPoint, points) { qreal const currentDistance = distance(currentPoint, point); if (currentDistance < minDistance) { closestPoint = currentPoint; minDistance = currentDistance; } } return closestPoint; } bool Geometry::belongs(QPointF const &point, QLineF const &segment, qreal eps) { if (!Math::between(segment.x1(), segment.x2(), point.x(), eps) || !Math::between(segment.y1(), segment.y2(), point.y(), eps)) { return false; } if (eq(point, segment.p1(), eps) || eq(point, segment.p2(), eps)) { return true; } if (Math::eq(segment.x1(), segment.x2(), eps)) { return Math::eq(point.x(), segment.x1(), eps); } return Math::eq(QLineF(segment.p1(), point).angle(), QLineF(point, segment.p2()).angle(), eps); } bool Geometry::belongs(QPointF const &point, QPainterPath const &path, qreal eps) { QPointF startPoint; QPointF endPoint; for (int i = 0; i < path.elementCount(); ++i) { QPainterPath::Element const element = path.elementAt(i); // Checking that element belongs to the wall path if (element.isMoveTo()) { endPoint = QPointF(element.x, element.y); continue; } startPoint = endPoint; endPoint = QPointF(element.x, element.y); // TODO: consider curve cases if (belongs(point, QLineF(startPoint, endPoint)), eps) { return true; } } return false; } bool Geometry::belongs(QLineF const &line, QPainterPath const &path, qreal eps) { int const pointsToCheck = 5; QVector2D const shift = QVector2D(line.p2() - line.p1()) / (pointsToCheck - 1); for (int i = 0; i < pointsToCheck; ++i) { if (!belongs(line.p1() + i * shift.toPointF(), path), eps) { return false; } } return true; } <|endoftext|>
<commit_before>#include <gtest/gtest.h> using namespace testing; TEST(MyTest, MyTest) { EXPECT_EQ(1,1); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }<commit_msg>Added line-end at the end of the file.<commit_after>#include <gtest/gtest.h> using namespace testing; TEST(MyTest, MyTest) { EXPECT_EQ(1,1); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before><commit_msg>[sfm] default destructor<commit_after><|endoftext|>
<commit_before><commit_msg>Major cleanup<commit_after><|endoftext|>
<commit_before>#ifndef __elxKNNGraphAlphaMutualInformationMetric_HXX__ #define __elxKNNGraphAlphaMutualInformationMetric_HXX__ #include "elxKNNGraphAlphaMutualInformationMetric.h" #include "itkImageFileReader.h" #include "itkBSplineInterpolateImageFunction.h" #include <string> namespace elastix { using namespace itk; /** * ******************* Initialize *********************** */ template <class TElastix> void KNNGraphAlphaMutualInformationMetric<TElastix> ::Initialize(void) throw (ExceptionObject) { TimerPointer timer = TimerType::New(); timer->StartTimer(); this->Superclass1::Initialize(); timer->StopTimer(); elxout << "Initialization of KNNGraphAlphaMutualInformation metric took: " << static_cast<long>( timer->GetElapsedClockSec() * 1000 ) << " ms." << std::endl; } // end Initialize() /** * ***************** BeforeRegistration *********************** */ template <class TElastix> void KNNGraphAlphaMutualInformationMetric<TElastix> ::BeforeRegistration(void) { /** Get and set alpha, from alpha - MI. */ double alpha = 0.5; this->m_Configuration->ReadParameter( alpha, "Alpha", 0 ); this->SetAlpha( alpha ); } // end BeforeRegistration() /** * ***************** BeforeEachResolution *********************** */ template <class TElastix> void KNNGraphAlphaMutualInformationMetric<TElastix> ::BeforeEachResolution(void) { /** Get the current resolution level. */ unsigned int level = ( this->m_Registration->GetAsITKBaseType() )->GetCurrentLevel(); /** Get the parameters for the KNN binary tree. */ /** Get the tree type. */ std::string treeType = "KDTree"; this->m_Configuration->ReadParameter( treeType, "TreeType", 0 ); this->m_Configuration->ReadParameter( treeType, "TreeType", level, true ); bool silentBS = false; bool silentSplit = false; bool silentShrink = false; if ( treeType == "KDTree" ) { silentShrink = true; } else if ( treeType == "BruteForceTree" ) { silentBS = true; silentSplit = true; silentShrink = true; } /** Get the bucket size. */ unsigned int bucketSize = 50; this->m_Configuration->ReadParameter( bucketSize, "BucketSize", 0, silentBS ); this->m_Configuration->ReadParameter( bucketSize, "BucketSize", level, true ); /** Get the splitting rule for all trees. */ std::string splittingRule = "ANN_KD_SL_MIDPT"; this->m_Configuration->ReadParameter( splittingRule, "SplittingRule", 0, silentSplit ); this->m_Configuration->ReadParameter( splittingRule, "SplittingRule", level, true ); /** Get the splitting rule for the fixed tree. */ std::string fixedSplittingRule = "ANN_KD_SL_MIDPT"; this->m_Configuration->ReadParameter( fixedSplittingRule, "FixedSplittingRule", 0, silentSplit ); this->m_Configuration->ReadParameter( fixedSplittingRule, "FixedSplittingRule", level, true ); /** Get the splitting rule for the moving tree. */ std::string movingSplittingRule = "ANN_KD_SL_MIDPT"; this->m_Configuration->ReadParameter( movingSplittingRule, "MovingSplittingRule", 0, silentSplit ); this->m_Configuration->ReadParameter( movingSplittingRule, "MovingSplittingRule", level, true ); /** Get the splitting rule for the joint tree. */ std::string jointSplittingRule = "ANN_KD_SL_MIDPT"; this->m_Configuration->ReadParameter( jointSplittingRule, "JointSplittingRule", 0, silentSplit ); this->m_Configuration->ReadParameter( jointSplittingRule, "JointSplittingRule", level, true ); /** Get the shrinking rule for all trees. */ std::string shrinkingRule = "ANN_BD_SIMPLE"; this->m_Configuration->ReadParameter( shrinkingRule, "ShrinkingRule", 0, silentShrink ); this->m_Configuration->ReadParameter( shrinkingRule, "ShrinkingRule", level, true ); /** Get the shrinking rule for the fixed tree. */ std::string fixedShrinkingRule = "ANN_BD_SIMPLE"; this->m_Configuration->ReadParameter( fixedShrinkingRule, "FixedShrinkingRule", 0, silentShrink ); this->m_Configuration->ReadParameter( fixedShrinkingRule, "FixedShrinkingRule", level, true ); /** Get the shrinking rule for the moving tree. */ std::string movingShrinkingRule = "ANN_BD_SIMPLE"; this->m_Configuration->ReadParameter( movingShrinkingRule, "MovingShrinkingRule", 0, silentShrink ); this->m_Configuration->ReadParameter( movingShrinkingRule, "MovingShrinkingRule", level, true ); /** Get the shrinking rule for the joint tree. */ std::string jointShrinkingRule = "ANN_BD_SIMPLE"; this->m_Configuration->ReadParameter( jointShrinkingRule, "JointShrinkingRule", 0, silentShrink ); this->m_Configuration->ReadParameter( jointShrinkingRule, "JointShrinkingRule", level, true ); /** Set the tree. */ if ( treeType == "KDTree" ) { /** If "SplittingRule" is given then all splitting rules are the same. */ std::string tmp; if ( !this->m_Configuration->ReadParameter( tmp, "SplittingRule", 0, true ) ) { this->SetANNkDTree( bucketSize, splittingRule ); } else { this->SetANNkDTree( bucketSize, fixedSplittingRule, movingSplittingRule, jointSplittingRule ); } } else if ( treeType == "BDTree" ) { /** If "SplittingRule" is given then all splitting rules are the same. */ std::string tmp; if ( !this->m_Configuration->ReadParameter( tmp, "SplittingRule", 0, true ) ) { /** If "ShrinkingRule" is given then all shrinking rules are the same. */ if ( !this->m_Configuration->ReadParameter( tmp, "ShrinkingRule", 0, true ) ) { this->SetANNbdTree( bucketSize, splittingRule, shrinkingRule ); } else { this->SetANNbdTree( bucketSize, splittingRule, splittingRule, splittingRule, fixedShrinkingRule, movingShrinkingRule, jointShrinkingRule ); } } else { /** If "ShrinkingRule" is given then all shrinking rules are the same. */ if ( !this->m_Configuration->ReadParameter( tmp, "ShrinkingRule", 0, true ) ) { this->SetANNbdTree( bucketSize, fixedSplittingRule, movingSplittingRule, jointSplittingRule, shrinkingRule, shrinkingRule, shrinkingRule ); } else { this->SetANNbdTree( bucketSize, fixedSplittingRule, movingSplittingRule, jointSplittingRule, fixedShrinkingRule, movingShrinkingRule, jointShrinkingRule ); } } } else if ( treeType == "BruteForceTree" ) { this->SetANNBruteForceTree(); } else { itkExceptionMacro( << "ERROR: there is no tree type \"" << treeType << "\" implemented." ); } /** Get the parameters for the search tree. */ /** Get the tree search type. */ std::string treeSearchType = "Standard"; this->m_Configuration->ReadParameter( treeSearchType, "TreeSearchType", 0 ); this->m_Configuration->ReadParameter( treeSearchType, "TreeSearchType", level, true ); bool silentSR = true; if ( treeSearchType == "FixedRadius" ) { silentSR = false; } /** Get the k nearest neighbours. */ unsigned int kNearestNeighbours = 20; this->m_Configuration->ReadParameter( kNearestNeighbours, "KNearestNeighbours", 0 ); this->m_Configuration->ReadParameter( kNearestNeighbours, "KNearestNeighbours", level, true ); /** Get the error bound. */ double errorBound = 0.0; this->m_Configuration->ReadParameter( errorBound, "ErrorBound", 0 ); this->m_Configuration->ReadParameter( errorBound, "ErrorBound", level, true ); /** Get the squared search radius. */ double squaredSearchRadius = 0.0; this->m_Configuration->ReadParameter( squaredSearchRadius, "SquaredSearchRadius", 0, silentSR ); this->m_Configuration->ReadParameter( squaredSearchRadius, "SquaredSearchRadius", level, true ); /** Set the tree searcher. */ if ( treeSearchType == "Standard" ) { this->SetANNStandardTreeSearch( kNearestNeighbours, errorBound ); } else if ( treeSearchType == "FixedRadius" ) { this->SetANNFixedRadiusTreeSearch( kNearestNeighbours, errorBound, squaredSearchRadius ); } else if ( treeSearchType == "Priority" ) { this->SetANNPriorityTreeSearch( kNearestNeighbours, errorBound ); } else { itkExceptionMacro( << "ERROR: there is no tree searcher type \"" << treeSearchType << "\" implemented." ); } } // end BeforeEachResolution() } // end namespace elastix #endif // end #ifndef __elxKNNGraphAlphaMutualInformationMetric_HXX__ <commit_msg>MS:<commit_after>#ifndef __elxKNNGraphAlphaMutualInformationMetric_HXX__ #define __elxKNNGraphAlphaMutualInformationMetric_HXX__ #include "elxKNNGraphAlphaMutualInformationMetric.h" #include "itkImageFileReader.h" #include "itkBSplineInterpolateImageFunction.h" #include <string> namespace elastix { using namespace itk; /** * ******************* Initialize *********************** */ template <class TElastix> void KNNGraphAlphaMutualInformationMetric<TElastix> ::Initialize(void) throw (ExceptionObject) { TimerPointer timer = TimerType::New(); timer->StartTimer(); this->Superclass1::Initialize(); timer->StopTimer(); elxout << "Initialization of KNNGraphAlphaMutualInformation metric took: " << static_cast<long>( timer->GetElapsedClockSec() * 1000 ) << " ms." << std::endl; } // end Initialize() /** * ***************** BeforeRegistration *********************** */ template <class TElastix> void KNNGraphAlphaMutualInformationMetric<TElastix> ::BeforeRegistration(void) { /** Get and set alpha, from alpha - MI. */ double alpha = 0.5; this->m_Configuration->ReadParameter( alpha, "Alpha", 0 ); this->SetAlpha( alpha ); } // end BeforeRegistration() /** * ***************** BeforeEachResolution *********************** */ template <class TElastix> void KNNGraphAlphaMutualInformationMetric<TElastix> ::BeforeEachResolution(void) { /** Get the current resolution level. */ unsigned int level = ( this->m_Registration->GetAsITKBaseType() )->GetCurrentLevel(); /** Get the parameters for the KNN binary tree. */ /** Get the tree type. */ std::string treeType = "KDTree"; this->m_Configuration->ReadParameter( treeType, "TreeType", 0 ); this->m_Configuration->ReadParameter( treeType, "TreeType", level, true ); bool silentBS = false; bool silentSplit = false; bool silentShrink = false; if ( treeType == "KDTree" ) { silentShrink = true; } else if ( treeType == "BruteForceTree" ) { silentBS = true; silentSplit = true; silentShrink = true; } /** Get the bucket size. */ unsigned int bucketSize = 50; this->m_Configuration->ReadParameter( bucketSize, "BucketSize", 0, silentBS ); this->m_Configuration->ReadParameter( bucketSize, "BucketSize", level, true ); /** Get the splitting rule for all trees. */ bool returnValue = false; std::string splittingRule = "ANN_KD_SL_MIDPT"; returnValue = this->m_Configuration->ReadParameter( splittingRule, "SplittingRule", 0, silentSplit ); this->m_Configuration->ReadParameter( splittingRule, "SplittingRule", level, true ); /** Get the splitting rule for the fixed tree. */ std::string fixedSplittingRule = splittingRule; this->m_Configuration->ReadParameter( fixedSplittingRule, "FixedSplittingRule", 0, silentSplit | !returnValue ); this->m_Configuration->ReadParameter( fixedSplittingRule, "FixedSplittingRule", level, true ); /** Get the splitting rule for the moving tree. */ std::string movingSplittingRule = splittingRule; this->m_Configuration->ReadParameter( movingSplittingRule, "MovingSplittingRule", 0, silentSplit | !returnValue ); this->m_Configuration->ReadParameter( movingSplittingRule, "MovingSplittingRule", level, true ); /** Get the splitting rule for the joint tree. */ std::string jointSplittingRule = splittingRule; this->m_Configuration->ReadParameter( jointSplittingRule, "JointSplittingRule", 0, silentSplit | !returnValue ); this->m_Configuration->ReadParameter( jointSplittingRule, "JointSplittingRule", level, true ); /** Get the shrinking rule for all trees. */ returnValue = false; std::string shrinkingRule = "ANN_BD_SIMPLE"; returnValue = this->m_Configuration->ReadParameter( shrinkingRule, "ShrinkingRule", 0, silentShrink ); this->m_Configuration->ReadParameter( shrinkingRule, "ShrinkingRule", level, true ); /** Get the shrinking rule for the fixed tree. */ std::string fixedShrinkingRule = shrinkingRule; this->m_Configuration->ReadParameter( fixedShrinkingRule, "FixedShrinkingRule", 0, silentShrink | !returnValue ); this->m_Configuration->ReadParameter( fixedShrinkingRule, "FixedShrinkingRule", level, true ); /** Get the shrinking rule for the moving tree. */ std::string movingShrinkingRule = shrinkingRule; this->m_Configuration->ReadParameter( movingShrinkingRule, "MovingShrinkingRule", 0, silentShrink | !returnValue ); this->m_Configuration->ReadParameter( movingShrinkingRule, "MovingShrinkingRule", level, true ); /** Get the shrinking rule for the joint tree. */ std::string jointShrinkingRule = shrinkingRule; this->m_Configuration->ReadParameter( jointShrinkingRule, "JointShrinkingRule", 0, silentShrink | !returnValue ); this->m_Configuration->ReadParameter( jointShrinkingRule, "JointShrinkingRule", level, true ); /** Set the tree. */ if ( treeType == "KDTree" ) { this->SetANNkDTree( bucketSize, fixedSplittingRule, movingSplittingRule, jointSplittingRule ); } else if ( treeType == "BDTree" ) { this->SetANNbdTree( bucketSize, fixedSplittingRule, movingSplittingRule, jointSplittingRule, fixedShrinkingRule, movingShrinkingRule, jointShrinkingRule ); } else if ( treeType == "BruteForceTree" ) { this->SetANNBruteForceTree(); } else { itkExceptionMacro( << "ERROR: there is no tree type \"" << treeType << "\" implemented." ); } /** Get the parameters for the search tree. */ /** Get the tree search type. */ std::string treeSearchType = "Standard"; this->m_Configuration->ReadParameter( treeSearchType, "TreeSearchType", 0 ); this->m_Configuration->ReadParameter( treeSearchType, "TreeSearchType", level, true ); bool silentSR = true; if ( treeSearchType == "FixedRadius" ) { silentSR = false; } /** Get the k nearest neighbours. */ unsigned int kNearestNeighbours = 20; this->m_Configuration->ReadParameter( kNearestNeighbours, "KNearestNeighbours", 0 ); this->m_Configuration->ReadParameter( kNearestNeighbours, "KNearestNeighbours", level, true ); /** Get the error bound. */ double errorBound = 0.0; this->m_Configuration->ReadParameter( errorBound, "ErrorBound", 0 ); this->m_Configuration->ReadParameter( errorBound, "ErrorBound", level, true ); /** Get the squared search radius. */ double squaredSearchRadius = 0.0; this->m_Configuration->ReadParameter( squaredSearchRadius, "SquaredSearchRadius", 0, silentSR ); this->m_Configuration->ReadParameter( squaredSearchRadius, "SquaredSearchRadius", level, true ); /** Set the tree searcher. */ if ( treeSearchType == "Standard" ) { this->SetANNStandardTreeSearch( kNearestNeighbours, errorBound ); } else if ( treeSearchType == "FixedRadius" ) { this->SetANNFixedRadiusTreeSearch( kNearestNeighbours, errorBound, squaredSearchRadius ); } else if ( treeSearchType == "Priority" ) { this->SetANNPriorityTreeSearch( kNearestNeighbours, errorBound ); } else { itkExceptionMacro( << "ERROR: there is no tree searcher type \"" << treeSearchType << "\" implemented." ); } } // end BeforeEachResolution() } // end namespace elastix #endif // end #ifndef __elxKNNGraphAlphaMutualInformationMetric_HXX__ <|endoftext|>
<commit_before>#include <stdio.h> #include <cmath> #include <stdlib.h> #include <stdbool.h> #include <signal.h> #include <unistd.h> #include <assert.h> #include <math.h> #include <poll.h> #include <sys/mman.h> #include "common/util.h" #include "common/swaglog.h" #include "common/visionimg.h" #include "common/utilpp.h" #include "ui.hpp" #include "paint.hpp" int write_param_float(float param, const char* param_name, bool persistent_param) { char s[16]; int size = snprintf(s, sizeof(s), "%f", param); return Params(persistent_param).write_db_value(param_name, s, size < sizeof(s) ? size : sizeof(s)); } void ui_init(UIState *s) { s->sm = new SubMaster({"modelV2", "controlsState", "uiLayoutState", "liveCalibration", "radarState", "thermal", "frame", "health", "carParams", "ubloxGnss", "driverState", "dMonitoringState", "sensorEvents"}); s->started = false; s->status = STATUS_OFFROAD; s->scene.satelliteCount = -1; s->fb = framebuffer_init("ui", 0, true, &s->fb_w, &s->fb_h); assert(s->fb); ui_nvg_init(s); } static void ui_init_vision(UIState *s) { // Invisible until we receive a calibration message. s->scene.world_objects_visible = false; for (int i = 0; i < UI_BUF_COUNT; i++) { if (s->khr[i] != 0) { visionimg_destroy_gl(s->khr[i], s->priv_hnds[i]); glDeleteTextures(1, &s->frame_texs[i]); } VisionImg img = { .fd = s->stream.bufs[i].fd, .format = VISIONIMG_FORMAT_RGB24, .width = s->stream.bufs_info.width, .height = s->stream.bufs_info.height, .stride = s->stream.bufs_info.stride, .bpp = 3, .size = s->stream.bufs_info.buf_len, }; #ifndef QCOM s->priv_hnds[i] = s->stream.bufs[i].addr; #endif s->frame_texs[i] = visionimg_to_gl(&img, &s->khr[i], &s->priv_hnds[i]); glBindTexture(GL_TEXTURE_2D, s->frame_texs[i]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); // BGR glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, GL_BLUE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_GREEN); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_RED); } assert(glGetError() == GL_NO_ERROR); } void ui_update_vision(UIState *s) { if (!s->vision_connected && s->started) { const VisionStreamType type = s->scene.frontview ? VISION_STREAM_RGB_FRONT : VISION_STREAM_RGB_BACK; int err = visionstream_init(&s->stream, type, true, nullptr); if (err == 0) { ui_init_vision(s); s->vision_connected = true; } } if (s->vision_connected) { if (!s->started) goto destroy; // poll for a new frame struct pollfd fds[1] = {{ .fd = s->stream.ipc_fd, .events = POLLOUT, }}; int ret = poll(fds, 1, 100); if (ret > 0) { if (!visionstream_get(&s->stream, nullptr)) goto destroy; } } return; destroy: visionstream_destroy(&s->stream); s->vision_connected = false; } void update_sockets(UIState *s) { UIScene &scene = s->scene; SubMaster &sm = *(s->sm); if (sm.update(0) == 0){ return; } if (s->started && sm.updated("controlsState")) { auto event = sm["controlsState"]; scene.controls_state = event.getControlsState(); // TODO: the alert stuff shouldn't be handled here auto alert_sound = scene.controls_state.getAlertSound(); if (scene.alert_type.compare(scene.controls_state.getAlertType()) != 0) { if (alert_sound == AudibleAlert::NONE) { s->sound->stop(); } else { s->sound->play(alert_sound); } } scene.alert_text1 = scene.controls_state.getAlertText1(); scene.alert_text2 = scene.controls_state.getAlertText2(); scene.alert_size = scene.controls_state.getAlertSize(); scene.alert_type = scene.controls_state.getAlertType(); auto alertStatus = scene.controls_state.getAlertStatus(); if (alertStatus == cereal::ControlsState::AlertStatus::USER_PROMPT) { s->status = STATUS_WARNING; } else if (alertStatus == cereal::ControlsState::AlertStatus::CRITICAL) { s->status = STATUS_ALERT; } else { s->status = scene.controls_state.getEnabled() ? STATUS_ENGAGED : STATUS_DISENGAGED; } float alert_blinkingrate = scene.controls_state.getAlertBlinkingRate(); if (alert_blinkingrate > 0.) { if (s->alert_blinked) { if (s->alert_blinking_alpha > 0.0 && s->alert_blinking_alpha < 1.0) { s->alert_blinking_alpha += (0.05*alert_blinkingrate); } else { s->alert_blinked = false; } } else { if (s->alert_blinking_alpha > 0.25) { s->alert_blinking_alpha -= (0.05*alert_blinkingrate); } else { s->alert_blinking_alpha += 0.25; s->alert_blinked = true; } } } } if (sm.updated("radarState")) { auto data = sm["radarState"].getRadarState(); scene.lead_data[0] = data.getLeadOne(); scene.lead_data[1] = data.getLeadTwo(); } if (sm.updated("liveCalibration")) { scene.world_objects_visible = true; auto extrinsicl = sm["liveCalibration"].getLiveCalibration().getExtrinsicMatrix(); for (int i = 0; i < 3 * 4; i++) { scene.extrinsic_matrix.v[i] = extrinsicl[i]; } } if (sm.updated("modelV2")) { scene.model = sm["modelV2"].getModelV2(); scene.max_distance = fmin(scene.model.getPosition().getX()[TRAJECTORY_SIZE - 1], MAX_DRAW_DISTANCE); for (int ll_idx = 0; ll_idx < 4; ll_idx++) { if (scene.model.getLaneLineProbs().size() > ll_idx) { scene.lane_line_probs[ll_idx] = scene.model.getLaneLineProbs()[ll_idx]; } else { scene.lane_line_probs[ll_idx] = 0.0; } } for (int re_idx = 0; re_idx < 2; re_idx++) { if (scene.model.getRoadEdgeStds().size() > re_idx) { scene.road_edge_stds[re_idx] = scene.model.getRoadEdgeStds()[re_idx]; } else { scene.road_edge_stds[re_idx] = 1.0; } } } if (sm.updated("uiLayoutState")) { auto data = sm["uiLayoutState"].getUiLayoutState(); s->active_app = data.getActiveApp(); scene.uilayout_sidebarcollapsed = data.getSidebarCollapsed(); } if (sm.updated("thermal")) { scene.thermal = sm["thermal"].getThermal(); } if (sm.updated("ubloxGnss")) { auto data = sm["ubloxGnss"].getUbloxGnss(); if (data.which() == cereal::UbloxGnss::MEASUREMENT_REPORT) { scene.satelliteCount = data.getMeasurementReport().getNumMeas(); } } if (sm.updated("health")) { auto health = sm["health"].getHealth(); scene.hwType = health.getHwType(); s->ignition = health.getIgnitionLine() || health.getIgnitionCan(); } else if ((s->sm->frame - s->sm->rcv_frame("health")) > 5*UI_FREQ) { scene.hwType = cereal::HealthData::HwType::UNKNOWN; } if (sm.updated("carParams")) { s->longitudinal_control = sm["carParams"].getCarParams().getOpenpilotLongitudinalControl(); } if (sm.updated("driverState")) { scene.driver_state = sm["driverState"].getDriverState(); } if (sm.updated("dMonitoringState")) { scene.dmonitoring_state = sm["dMonitoringState"].getDMonitoringState(); scene.is_rhd = scene.dmonitoring_state.getIsRHD(); scene.frontview = scene.dmonitoring_state.getIsPreview(); } else if ((sm.frame - sm.rcv_frame("dMonitoringState")) > UI_FREQ/2) { scene.frontview = false; } if (sm.updated("sensorEvents")) { for (auto sensor : sm["sensorEvents"].getSensorEvents()) { if (sensor.which() == cereal::SensorEventData::LIGHT) { s->light_sensor = sensor.getLight(); } else if (!s->started && sensor.which() == cereal::SensorEventData::ACCELERATION) { s->accel_sensor = sensor.getAcceleration().getV()[2]; } else if (!s->started && sensor.which() == cereal::SensorEventData::GYRO_UNCALIBRATED) { s->gyro_sensor = sensor.getGyroUncalibrated().getV()[1]; } } } s->started = scene.thermal.getStarted() || scene.frontview; } static void ui_read_params(UIState *s) { const uint64_t frame = s->sm->frame; if (frame % (5*UI_FREQ) == 0) { read_param(&s->is_metric, "IsMetric"); } else if (frame % (6*UI_FREQ) == 0) { uint64_t last_athena_ping = 0; int param_read = read_param(&last_athena_ping, "LastAthenaPingTime"); if (param_read != 0) { // Failed to read param s->scene.athenaStatus = NET_DISCONNECTED; } else if (nanos_since_boot() - last_athena_ping < 70e9) { s->scene.athenaStatus = NET_CONNECTED; } else { s->scene.athenaStatus = NET_ERROR; } } } void ui_update(UIState *s) { ui_read_params(s); update_sockets(s); ui_update_vision(s); // Handle onroad/offroad transition if (!s->started && s->status != STATUS_OFFROAD) { s->status = STATUS_OFFROAD; s->active_app = cereal::UiLayoutState::App::HOME; s->scene.uilayout_sidebarcollapsed = false; s->sound->stop(); } else if (s->started && s->status == STATUS_OFFROAD) { s->status = STATUS_DISENGAGED; s->started_frame = s->sm->frame; s->active_app = cereal::UiLayoutState::App::NONE; s->scene.uilayout_sidebarcollapsed = true; s->alert_blinked = false; s->alert_blinking_alpha = 1.0; s->scene.alert_size = cereal::ControlsState::AlertSize::NONE; } // Handle controls/fcamera timeout if (s->started && !s->scene.frontview && ((s->sm)->frame - s->started_frame) > 10*UI_FREQ) { if ((s->sm)->rcv_frame("controlsState") < s->started_frame) { // car is started, but controlsState hasn't been seen at all s->scene.alert_text1 = "openpilot Unavailable"; s->scene.alert_text2 = "Waiting for controls to start"; s->scene.alert_size = cereal::ControlsState::AlertSize::MID; } else if (((s->sm)->frame - (s->sm)->rcv_frame("controlsState")) > 5*UI_FREQ) { // car is started, but controls is lagging or died if (s->scene.alert_text2 != "Controls Unresponsive" && s->scene.alert_text1 != "Camera Malfunction") { s->sound->play(AudibleAlert::CHIME_WARNING_REPEAT); LOGE("Controls unresponsive"); } s->scene.alert_text1 = "TAKE CONTROL IMMEDIATELY"; s->scene.alert_text2 = "Controls Unresponsive"; s->scene.alert_size = cereal::ControlsState::AlertSize::FULL; s->status = STATUS_ALERT; } const uint64_t frame_pkt = (s->sm)->rcv_frame("frame"); const uint64_t frame_delayed = (s->sm)->frame - frame_pkt; const uint64_t since_started = (s->sm)->frame - s->started_frame; if ((frame_pkt > s->started_frame || since_started > 15*UI_FREQ) && frame_delayed > 5*UI_FREQ) { // controls is fine, but rear camera is lagging or died s->scene.alert_text1 = "Camera Malfunction"; s->scene.alert_text2 = "Contact Support"; s->scene.alert_size = cereal::ControlsState::AlertSize::FULL; s->status = STATUS_DISENGAGED; s->sound->stop(); } } } <commit_msg>don't check dMonitorState's frame if frontview is false (#19584)<commit_after>#include <stdio.h> #include <cmath> #include <stdlib.h> #include <stdbool.h> #include <signal.h> #include <unistd.h> #include <assert.h> #include <math.h> #include <poll.h> #include <sys/mman.h> #include "common/util.h" #include "common/swaglog.h" #include "common/visionimg.h" #include "common/utilpp.h" #include "ui.hpp" #include "paint.hpp" int write_param_float(float param, const char* param_name, bool persistent_param) { char s[16]; int size = snprintf(s, sizeof(s), "%f", param); return Params(persistent_param).write_db_value(param_name, s, size < sizeof(s) ? size : sizeof(s)); } void ui_init(UIState *s) { s->sm = new SubMaster({"modelV2", "controlsState", "uiLayoutState", "liveCalibration", "radarState", "thermal", "frame", "health", "carParams", "ubloxGnss", "driverState", "dMonitoringState", "sensorEvents"}); s->started = false; s->status = STATUS_OFFROAD; s->scene.satelliteCount = -1; s->fb = framebuffer_init("ui", 0, true, &s->fb_w, &s->fb_h); assert(s->fb); ui_nvg_init(s); } static void ui_init_vision(UIState *s) { // Invisible until we receive a calibration message. s->scene.world_objects_visible = false; for (int i = 0; i < UI_BUF_COUNT; i++) { if (s->khr[i] != 0) { visionimg_destroy_gl(s->khr[i], s->priv_hnds[i]); glDeleteTextures(1, &s->frame_texs[i]); } VisionImg img = { .fd = s->stream.bufs[i].fd, .format = VISIONIMG_FORMAT_RGB24, .width = s->stream.bufs_info.width, .height = s->stream.bufs_info.height, .stride = s->stream.bufs_info.stride, .bpp = 3, .size = s->stream.bufs_info.buf_len, }; #ifndef QCOM s->priv_hnds[i] = s->stream.bufs[i].addr; #endif s->frame_texs[i] = visionimg_to_gl(&img, &s->khr[i], &s->priv_hnds[i]); glBindTexture(GL_TEXTURE_2D, s->frame_texs[i]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); // BGR glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, GL_BLUE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_GREEN); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_RED); } assert(glGetError() == GL_NO_ERROR); } void ui_update_vision(UIState *s) { if (!s->vision_connected && s->started) { const VisionStreamType type = s->scene.frontview ? VISION_STREAM_RGB_FRONT : VISION_STREAM_RGB_BACK; int err = visionstream_init(&s->stream, type, true, nullptr); if (err == 0) { ui_init_vision(s); s->vision_connected = true; } } if (s->vision_connected) { if (!s->started) goto destroy; // poll for a new frame struct pollfd fds[1] = {{ .fd = s->stream.ipc_fd, .events = POLLOUT, }}; int ret = poll(fds, 1, 100); if (ret > 0) { if (!visionstream_get(&s->stream, nullptr)) goto destroy; } } return; destroy: visionstream_destroy(&s->stream); s->vision_connected = false; } void update_sockets(UIState *s) { UIScene &scene = s->scene; SubMaster &sm = *(s->sm); if (sm.update(0) == 0){ return; } if (s->started && sm.updated("controlsState")) { auto event = sm["controlsState"]; scene.controls_state = event.getControlsState(); // TODO: the alert stuff shouldn't be handled here auto alert_sound = scene.controls_state.getAlertSound(); if (scene.alert_type.compare(scene.controls_state.getAlertType()) != 0) { if (alert_sound == AudibleAlert::NONE) { s->sound->stop(); } else { s->sound->play(alert_sound); } } scene.alert_text1 = scene.controls_state.getAlertText1(); scene.alert_text2 = scene.controls_state.getAlertText2(); scene.alert_size = scene.controls_state.getAlertSize(); scene.alert_type = scene.controls_state.getAlertType(); auto alertStatus = scene.controls_state.getAlertStatus(); if (alertStatus == cereal::ControlsState::AlertStatus::USER_PROMPT) { s->status = STATUS_WARNING; } else if (alertStatus == cereal::ControlsState::AlertStatus::CRITICAL) { s->status = STATUS_ALERT; } else { s->status = scene.controls_state.getEnabled() ? STATUS_ENGAGED : STATUS_DISENGAGED; } float alert_blinkingrate = scene.controls_state.getAlertBlinkingRate(); if (alert_blinkingrate > 0.) { if (s->alert_blinked) { if (s->alert_blinking_alpha > 0.0 && s->alert_blinking_alpha < 1.0) { s->alert_blinking_alpha += (0.05*alert_blinkingrate); } else { s->alert_blinked = false; } } else { if (s->alert_blinking_alpha > 0.25) { s->alert_blinking_alpha -= (0.05*alert_blinkingrate); } else { s->alert_blinking_alpha += 0.25; s->alert_blinked = true; } } } } if (sm.updated("radarState")) { auto data = sm["radarState"].getRadarState(); scene.lead_data[0] = data.getLeadOne(); scene.lead_data[1] = data.getLeadTwo(); } if (sm.updated("liveCalibration")) { scene.world_objects_visible = true; auto extrinsicl = sm["liveCalibration"].getLiveCalibration().getExtrinsicMatrix(); for (int i = 0; i < 3 * 4; i++) { scene.extrinsic_matrix.v[i] = extrinsicl[i]; } } if (sm.updated("modelV2")) { scene.model = sm["modelV2"].getModelV2(); scene.max_distance = fmin(scene.model.getPosition().getX()[TRAJECTORY_SIZE - 1], MAX_DRAW_DISTANCE); for (int ll_idx = 0; ll_idx < 4; ll_idx++) { if (scene.model.getLaneLineProbs().size() > ll_idx) { scene.lane_line_probs[ll_idx] = scene.model.getLaneLineProbs()[ll_idx]; } else { scene.lane_line_probs[ll_idx] = 0.0; } } for (int re_idx = 0; re_idx < 2; re_idx++) { if (scene.model.getRoadEdgeStds().size() > re_idx) { scene.road_edge_stds[re_idx] = scene.model.getRoadEdgeStds()[re_idx]; } else { scene.road_edge_stds[re_idx] = 1.0; } } } if (sm.updated("uiLayoutState")) { auto data = sm["uiLayoutState"].getUiLayoutState(); s->active_app = data.getActiveApp(); scene.uilayout_sidebarcollapsed = data.getSidebarCollapsed(); } if (sm.updated("thermal")) { scene.thermal = sm["thermal"].getThermal(); } if (sm.updated("ubloxGnss")) { auto data = sm["ubloxGnss"].getUbloxGnss(); if (data.which() == cereal::UbloxGnss::MEASUREMENT_REPORT) { scene.satelliteCount = data.getMeasurementReport().getNumMeas(); } } if (sm.updated("health")) { auto health = sm["health"].getHealth(); scene.hwType = health.getHwType(); s->ignition = health.getIgnitionLine() || health.getIgnitionCan(); } else if ((s->sm->frame - s->sm->rcv_frame("health")) > 5*UI_FREQ) { scene.hwType = cereal::HealthData::HwType::UNKNOWN; } if (sm.updated("carParams")) { s->longitudinal_control = sm["carParams"].getCarParams().getOpenpilotLongitudinalControl(); } if (sm.updated("driverState")) { scene.driver_state = sm["driverState"].getDriverState(); } if (sm.updated("dMonitoringState")) { scene.dmonitoring_state = sm["dMonitoringState"].getDMonitoringState(); scene.is_rhd = scene.dmonitoring_state.getIsRHD(); scene.frontview = scene.dmonitoring_state.getIsPreview(); } else if (scene.frontview && (sm.frame - sm.rcv_frame("dMonitoringState")) > UI_FREQ/2) { scene.frontview = false; } if (sm.updated("sensorEvents")) { for (auto sensor : sm["sensorEvents"].getSensorEvents()) { if (sensor.which() == cereal::SensorEventData::LIGHT) { s->light_sensor = sensor.getLight(); } else if (!s->started && sensor.which() == cereal::SensorEventData::ACCELERATION) { s->accel_sensor = sensor.getAcceleration().getV()[2]; } else if (!s->started && sensor.which() == cereal::SensorEventData::GYRO_UNCALIBRATED) { s->gyro_sensor = sensor.getGyroUncalibrated().getV()[1]; } } } s->started = scene.thermal.getStarted() || scene.frontview; } static void ui_read_params(UIState *s) { const uint64_t frame = s->sm->frame; if (frame % (5*UI_FREQ) == 0) { read_param(&s->is_metric, "IsMetric"); } else if (frame % (6*UI_FREQ) == 0) { uint64_t last_athena_ping = 0; int param_read = read_param(&last_athena_ping, "LastAthenaPingTime"); if (param_read != 0) { // Failed to read param s->scene.athenaStatus = NET_DISCONNECTED; } else if (nanos_since_boot() - last_athena_ping < 70e9) { s->scene.athenaStatus = NET_CONNECTED; } else { s->scene.athenaStatus = NET_ERROR; } } } void ui_update(UIState *s) { ui_read_params(s); update_sockets(s); ui_update_vision(s); // Handle onroad/offroad transition if (!s->started && s->status != STATUS_OFFROAD) { s->status = STATUS_OFFROAD; s->active_app = cereal::UiLayoutState::App::HOME; s->scene.uilayout_sidebarcollapsed = false; s->sound->stop(); } else if (s->started && s->status == STATUS_OFFROAD) { s->status = STATUS_DISENGAGED; s->started_frame = s->sm->frame; s->active_app = cereal::UiLayoutState::App::NONE; s->scene.uilayout_sidebarcollapsed = true; s->alert_blinked = false; s->alert_blinking_alpha = 1.0; s->scene.alert_size = cereal::ControlsState::AlertSize::NONE; } // Handle controls/fcamera timeout if (s->started && !s->scene.frontview && ((s->sm)->frame - s->started_frame) > 10*UI_FREQ) { if ((s->sm)->rcv_frame("controlsState") < s->started_frame) { // car is started, but controlsState hasn't been seen at all s->scene.alert_text1 = "openpilot Unavailable"; s->scene.alert_text2 = "Waiting for controls to start"; s->scene.alert_size = cereal::ControlsState::AlertSize::MID; } else if (((s->sm)->frame - (s->sm)->rcv_frame("controlsState")) > 5*UI_FREQ) { // car is started, but controls is lagging or died if (s->scene.alert_text2 != "Controls Unresponsive" && s->scene.alert_text1 != "Camera Malfunction") { s->sound->play(AudibleAlert::CHIME_WARNING_REPEAT); LOGE("Controls unresponsive"); } s->scene.alert_text1 = "TAKE CONTROL IMMEDIATELY"; s->scene.alert_text2 = "Controls Unresponsive"; s->scene.alert_size = cereal::ControlsState::AlertSize::FULL; s->status = STATUS_ALERT; } const uint64_t frame_pkt = (s->sm)->rcv_frame("frame"); const uint64_t frame_delayed = (s->sm)->frame - frame_pkt; const uint64_t since_started = (s->sm)->frame - s->started_frame; if ((frame_pkt > s->started_frame || since_started > 15*UI_FREQ) && frame_delayed > 5*UI_FREQ) { // controls is fine, but rear camera is lagging or died s->scene.alert_text1 = "Camera Malfunction"; s->scene.alert_text2 = "Contact Support"; s->scene.alert_size = cereal::ControlsState::AlertSize::FULL; s->status = STATUS_DISENGAGED; s->sound->stop(); } } } <|endoftext|>
<commit_before>/* * Copyright © 2012 Intel Corporation * * 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, see <http://www.gnu.org/licenses/>. * * Author: Benjamin Segovia <benjamin.segovia@intel.com> */ /** * \file utest.cpp * \author Benjamin Segovia <benjamin.segovia@intel.com> */ #include "utest.hpp" #include "utest_helper.hpp" #include <vector> #include <string> #include <iostream> #include <sys/ioctl.h> #include <unistd.h> #include <cstring> #include <stdlib.h> #include <csignal> #include <algorithm> #include <random> #include <chrono> #include <iterator> #include <semaphore.h> #include <unistd.h> struct signalMap { const char* signalName; int signalNum; }; using namespace std; sem_t tag; vector<UTest> *UTest::utestList = NULL; vector<int> v; // Initialize and declare statistics struct RStatistics UTest::retStatistics; void releaseUTestList(void) { delete UTest::utestList; } void runSummaryAtExit(void) { // If case crashes, count it as fail, and accumulate finishrun if(UTest::retStatistics.finishrun != UTest::utestList->size()) { UTest::retStatistics.finishrun++; // UTest::retStatistics.failCount++; } printf("\nsummary:\n----------\n"); printf(" total: %zu\n",UTest::utestList->size()); printf(" run: %zu\n",UTest::retStatistics.actualrun); printf(" pass: %zu\n",UTest::retStatistics.passCount); printf(" fail: %zu\n",UTest::retStatistics.failCount); printf(" pass rate: %f\n", (UTest::retStatistics.actualrun)?((float)UTest::retStatistics.passCount/(float)UTest::retStatistics.actualrun):(float)0); releaseUTestList(); } void signalHandler( int signum ) { const char* name = ""; signalMap arr[] = { {"SIGILL", SIGILL}, {"SIGFPE", SIGFPE}, {"SIGABRT", SIGABRT}, {"SIGBUS", SIGBUS}, {"SIGSEGV", SIGSEGV}, {"SIGHUP", SIGHUP}, {"SIGINT", SIGINT}, {"SIGQUIT", SIGQUIT}, {"SIGTERM", SIGTERM}, {NULL, -1} }; for(int i=0; arr[i].signalNum != -1 && arr[i].signalName != NULL; i++) { if(arr[i].signalNum == signum) name = arr[i].signalName; } printf(" Interrupt signal (%s) received.", name); UTest::retStatistics.failCount++; exit(signum); } void catch_signal(void){ struct sigaction sa; int sigs[] = { SIGILL, SIGFPE, SIGABRT, SIGBUS, SIGSEGV, SIGHUP, SIGINT, SIGQUIT, SIGTERM }; sa.sa_handler = signalHandler; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESETHAND; for(unsigned int i = 0; i < sizeof(sigs)/sizeof(sigs[0]); ++i) { if (sigaction(sigs[i], &sa, NULL) == -1) perror("Could not set signal handler"); } } void *multithread(void * arg) { int SerialNumber; //size_t PhtreadNumber = (size_t)arg; while(! v.empty()){ sem_wait(&tag); SerialNumber = v.back(); v.pop_back(); sem_post(&tag); const UTest &utest = (*UTest::utestList)[SerialNumber]; // printf("thread%lu %d, utests.name is %s\n",PhtreadNumber, SerialNumber,utest.name); UTest::do_run(utest); cl_kernel_destroy(true); cl_buffer_destroy(); } return 0; } UTest::UTest(Function fn, const char *name, bool isBenchMark, bool haveIssue, bool needDestroyProgram) : fn(fn), name(name), isBenchMark(isBenchMark), haveIssue(haveIssue), needDestroyProgram(needDestroyProgram) { if (utestList == NULL) { utestList = new vector<UTest>; catch_signal(); atexit(runSummaryAtExit); } utestList->push_back(*this); } static bool strequal(const char *s1, const char *s2) { if (strcmp(s1, s2) == 0) return true; return false; } void UTest::do_run(struct UTest utest){ // Print function name printf("%s()", utest.name); fflush(stdout); retStatistics.actualrun++; // Run one case in utestList, print result [SUCCESS] or [FAILED] (utest.fn)(); } void UTest::run(const char *name) { if (name == NULL) return; if (utestList == NULL) return; for (; retStatistics.finishrun < utestList->size(); ++retStatistics.finishrun) { const UTest &utest = (*utestList)[retStatistics.finishrun]; if (utest.name == NULL || utest.fn == NULL ) continue; if (strequal(utest.name, name)) { do_run(utest); cl_kernel_destroy(true); cl_buffer_destroy(); } } } void UTest::runMultiThread(const char *number) { if (number == NULL) return; if (utestList == NULL) return; unsigned long i, num; sem_init(&tag, 0, 1); num = atoi(number); unsigned long max_num = sysconf(_SC_NPROCESSORS_ONLN); if(num < 1 || num > max_num){ printf("the value range of multi-thread is [1 - %lu]",max_num); return; } for(i = 0; i < utestList->size(); ++i) v.push_back (i); unsigned seed = chrono::system_clock::now ().time_since_epoch ().count (); shuffle (v.begin (), v.end (), std::default_random_engine (seed)); pthread_t pthread_arry[num]; for(i=0; i<num;i++) pthread_create(&pthread_arry[i], NULL, multithread, (void *)i); for(i=0; i<num;i++) pthread_join(pthread_arry[i], NULL); sem_destroy(&tag); } void UTest::runAll(void) { if (utestList == NULL) return; for (; retStatistics.finishrun < utestList->size(); ++retStatistics.finishrun) { const UTest &utest = (*utestList)[retStatistics.finishrun]; if (utest.fn == NULL) continue; do_run(utest); cl_kernel_destroy(utest.needDestroyProgram); cl_buffer_destroy(); } } void UTest::runAllNoIssue(void) { if (utestList == NULL) return; for (; retStatistics.finishrun < utestList->size(); ++retStatistics.finishrun) { const UTest &utest = (*utestList)[retStatistics.finishrun]; if (utest.fn == NULL || utest.haveIssue || utest.isBenchMark) continue; do_run(utest); cl_kernel_destroy(utest.needDestroyProgram); cl_buffer_destroy(); } } void UTest::runAllBenchMark(void) { if (utestList == NULL) return; for (; retStatistics.finishrun < utestList->size(); ++retStatistics.finishrun) { const UTest &utest = (*utestList)[retStatistics.finishrun]; if (utest.fn == NULL || utest.haveIssue || !utest.isBenchMark) continue; do_run(utest); cl_kernel_destroy(utest.needDestroyProgram); cl_buffer_destroy(); } } void UTest::listAllCases() { if (utestList == NULL) return; for (size_t i = 0; i < utestList->size(); ++i) { const UTest &utest = (*utestList)[i]; if (utest.fn == NULL) continue; std::cout << utest.name << std::endl; } } <commit_msg>Utest: Add check for utest multithread run<commit_after>/* * Copyright © 2012 Intel Corporation * * 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, see <http://www.gnu.org/licenses/>. * * Author: Benjamin Segovia <benjamin.segovia@intel.com> */ /** * \file utest.cpp * \author Benjamin Segovia <benjamin.segovia@intel.com> */ #include "utest.hpp" #include "utest_helper.hpp" #include <vector> #include <string> #include <iostream> #include <sys/ioctl.h> #include <unistd.h> #include <cstring> #include <stdlib.h> #include <csignal> #include <algorithm> #include <random> #include <chrono> #include <iterator> #include <semaphore.h> #include <unistd.h> struct signalMap { const char* signalName; int signalNum; }; using namespace std; sem_t tag; vector<UTest> *UTest::utestList = NULL; vector<int> v; // Initialize and declare statistics struct RStatistics UTest::retStatistics; void releaseUTestList(void) { delete UTest::utestList; } void runSummaryAtExit(void) { // If case crashes, count it as fail, and accumulate finishrun if(UTest::retStatistics.finishrun != UTest::utestList->size()) { UTest::retStatistics.finishrun++; // UTest::retStatistics.failCount++; } printf("\nsummary:\n----------\n"); printf(" total: %zu\n",UTest::utestList->size()); printf(" run: %zu\n",UTest::retStatistics.actualrun); printf(" pass: %zu\n",UTest::retStatistics.passCount); printf(" fail: %zu\n",UTest::retStatistics.failCount); printf(" pass rate: %f\n", (UTest::retStatistics.actualrun)?((float)UTest::retStatistics.passCount/(float)UTest::retStatistics.actualrun):(float)0); releaseUTestList(); } void signalHandler( int signum ) { const char* name = ""; signalMap arr[] = { {"SIGILL", SIGILL}, {"SIGFPE", SIGFPE}, {"SIGABRT", SIGABRT}, {"SIGBUS", SIGBUS}, {"SIGSEGV", SIGSEGV}, {"SIGHUP", SIGHUP}, {"SIGINT", SIGINT}, {"SIGQUIT", SIGQUIT}, {"SIGTERM", SIGTERM}, {NULL, -1} }; for(int i=0; arr[i].signalNum != -1 && arr[i].signalName != NULL; i++) { if(arr[i].signalNum == signum) name = arr[i].signalName; } printf(" Interrupt signal (%s) received.", name); UTest::retStatistics.failCount++; exit(signum); } void catch_signal(void){ struct sigaction sa; int sigs[] = { SIGILL, SIGFPE, SIGABRT, SIGBUS, SIGSEGV, SIGHUP, SIGINT, SIGQUIT, SIGTERM }; sa.sa_handler = signalHandler; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESETHAND; for(unsigned int i = 0; i < sizeof(sigs)/sizeof(sigs[0]); ++i) { if (sigaction(sigs[i], &sa, NULL) == -1) perror("Could not set signal handler"); } } void *multithread(void * arg) { int SerialNumber; //size_t PhtreadNumber = (size_t)arg; while(! v.empty()){ sem_wait(&tag); SerialNumber = v.back(); v.pop_back(); sem_post(&tag); const UTest &utest = (*UTest::utestList)[SerialNumber]; if (utest.fn == NULL || utest.haveIssue || utest.isBenchMark) continue; // printf("thread%lu %d, utests.name is %s\n",PhtreadNumber, SerialNumber,utest.name); UTest::do_run(utest); cl_kernel_destroy(true); cl_buffer_destroy(); } return 0; } UTest::UTest(Function fn, const char *name, bool isBenchMark, bool haveIssue, bool needDestroyProgram) : fn(fn), name(name), isBenchMark(isBenchMark), haveIssue(haveIssue), needDestroyProgram(needDestroyProgram) { if (utestList == NULL) { utestList = new vector<UTest>; catch_signal(); atexit(runSummaryAtExit); } utestList->push_back(*this); } static bool strequal(const char *s1, const char *s2) { if (strcmp(s1, s2) == 0) return true; return false; } void UTest::do_run(struct UTest utest){ // Print function name printf("%s()", utest.name); fflush(stdout); retStatistics.actualrun++; // Run one case in utestList, print result [SUCCESS] or [FAILED] (utest.fn)(); } void UTest::run(const char *name) { if (name == NULL) return; if (utestList == NULL) return; for (; retStatistics.finishrun < utestList->size(); ++retStatistics.finishrun) { const UTest &utest = (*utestList)[retStatistics.finishrun]; if (utest.name == NULL || utest.fn == NULL ) continue; if (strequal(utest.name, name)) { do_run(utest); cl_kernel_destroy(true); cl_buffer_destroy(); } } } void UTest::runMultiThread(const char *number) { if (number == NULL) return; if (utestList == NULL) return; unsigned long i, num; sem_init(&tag, 0, 1); num = atoi(number); unsigned long max_num = sysconf(_SC_NPROCESSORS_ONLN); if(num < 1 || num > max_num){ printf("the value range of multi-thread is [1 - %lu]",max_num); return; } for(i = 0; i < utestList->size(); ++i) v.push_back (i); unsigned seed = chrono::system_clock::now ().time_since_epoch ().count (); shuffle (v.begin (), v.end (), std::default_random_engine (seed)); pthread_t pthread_arry[num]; for(i=0; i<num;i++) pthread_create(&pthread_arry[i], NULL, multithread, (void *)i); for(i=0; i<num;i++) pthread_join(pthread_arry[i], NULL); sem_destroy(&tag); } void UTest::runAll(void) { if (utestList == NULL) return; for (; retStatistics.finishrun < utestList->size(); ++retStatistics.finishrun) { const UTest &utest = (*utestList)[retStatistics.finishrun]; if (utest.fn == NULL) continue; do_run(utest); cl_kernel_destroy(utest.needDestroyProgram); cl_buffer_destroy(); } } void UTest::runAllNoIssue(void) { if (utestList == NULL) return; for (; retStatistics.finishrun < utestList->size(); ++retStatistics.finishrun) { const UTest &utest = (*utestList)[retStatistics.finishrun]; if (utest.fn == NULL || utest.haveIssue || utest.isBenchMark) continue; do_run(utest); cl_kernel_destroy(utest.needDestroyProgram); cl_buffer_destroy(); } } void UTest::runAllBenchMark(void) { if (utestList == NULL) return; for (; retStatistics.finishrun < utestList->size(); ++retStatistics.finishrun) { const UTest &utest = (*utestList)[retStatistics.finishrun]; if (utest.fn == NULL || utest.haveIssue || !utest.isBenchMark) continue; do_run(utest); cl_kernel_destroy(utest.needDestroyProgram); cl_buffer_destroy(); } } void UTest::listAllCases() { if (utestList == NULL) return; for (size_t i = 0; i < utestList->size(); ++i) { const UTest &utest = (*utestList)[i]; if (utest.fn == NULL) continue; std::cout << utest.name << std::endl; } } <|endoftext|>
<commit_before>#include <sstream> #include "Partitioning.h" using namespace std; double RepairDocumentPartition::getScore(ostream& os) { double term; double sum(0); double totalFragSize(0); for (unordered_map<string, FragInfo>::iterator it = uniqueFrags.begin(); it != uniqueFrags.end(); it++) { term = it->second.count * it->second.fragSize; sum += term; totalFragSize += it->second.fragSize; } if (uniqueFrags.size() == 0) return 0.0; double avgFragSize = totalFragSize / uniqueFrags.size(); return sum / (uniqueFrags.size() * avgFragSize); } SortedByOffsetNodeSet RepairDocumentPartition::getNodesNthLevelDown(RepairTreeNode* root, unsigned numLevelsDown, SortedByOffsetNodeSet& nodes) { if (!root) return nodes; if (numLevelsDown < 1) return nodes; if (numLevelsDown == 1) { if (root->getLeftChild() && root->getRightChild()) { nodes.insert(root->getLeftChild()); nodes.insert(root->getRightChild()); } return nodes; } if (root->getLeftChild() && root->getRightChild()) { this->getNodesNthLevelDown(root->getLeftChild(), numLevelsDown - 1, nodes); this->getNodesNthLevelDown(root->getRightChild(), numLevelsDown - 1, nodes); } return nodes; } int RepairDocumentPartition::getAssociationLocation(unsigned symbol) { if (memoizedAssociationLocations.count(symbol)) return memoizedAssociationLocations[symbol]; // It wasn't saved, so search for it, and save it for next time int loc = binarySearch(symbol, associations, 0, associations.size()); memoizedAssociationLocations[symbol] = loc; return loc; } double RepairDocumentPartition::getSubsetScore(SortedByOffsetNodeSet subset) { /* AVG */ // unsigned sum(0); // for (SortedByOffsetNodeSet::iterator it = subset.begin(); it != subset.end(); it++) // { // RepairTreeNode* currNode = *it; // unsigned currScore = 1; // int loc = getAssociationLocation(currNode->getSymbol()); // if (loc != -1) // { // Association a = associations[loc]; // currScore = currNode->getSize() * a.getFreq(); // } // sum += currScore; // } // if (subset.size() == 0 || sum == 0) return 0.0; // return ((double) sum) / ((double)subset.size()); /* MAX */ double currMax(0); for (SortedByOffsetNodeSet::iterator it = subset.begin(); it != subset.end(); it++) { RepairTreeNode* currNode = *it; double currScore = 1.0; int loc = getAssociationLocation(currNode->getSymbol()); if (loc != -1) { Association a = associations[loc]; currScore = currNode->getSize() * a.getFreq(); } if (currScore > currMax) { currMax = currScore; } } if (subset.size() == 0 || currMax == 0) return 0.0; return currMax; } SortedByOffsetNodeSet RepairDocumentPartition::getBestSubset(RepairTreeNode* node) { SortedByOffsetNodeSet nodes = SortedByOffsetNodeSet(); if (!node) return nodes; double myScore = 1.0; int loc = getAssociationLocation(node->getSymbol()); if (loc != -1) { Association a = associations[loc]; myScore = node->getSize() * a.getFreq(); } // node is a terminal if (!node->getLeftChild()) { nodes.insert(node); return nodes; } RepairTreeNode* leftChild = node->getLeftChild(); RepairTreeNode* rightChild = node->getRightChild(); SortedByOffsetNodeSet leftSubset = getBestSubset(leftChild); SortedByOffsetNodeSet rightSubset = getBestSubset(rightChild); double leftScore = getSubsetScore(leftSubset); double rightScore = getSubsetScore(rightSubset); // TODO try changing to max(leftScore, rightScore) double childrenScore = fragmentationCoefficient * (leftScore + rightScore); // Coefficient for fragmenting if (myScore >= childrenScore) { nodes.insert(node); return nodes; } nodes.insert(leftSubset.begin(), leftSubset.end()); nodes.insert(rightSubset.begin(), rightSubset.end()); return nodes; } unsigned RepairDocumentPartition::getPartitioningOneVersion(RepairTreeNode* root, unsigned numLevelsDown, unsigned* bounds, unsigned minFragSize, unsigned versionSize) { SortedByOffsetNodeSet nodes = SortedByOffsetNodeSet(); switch (this->method) { case RepairDocumentPartition::NAIVE: nodes = getNodesNthLevelDown(root, numLevelsDown, nodes); break; case RepairDocumentPartition::GREEDY: nodes = getBestSubset(root); break; // default is naive default: nodes = getNodesNthLevelDown(root, numLevelsDown, nodes); break; } unsigned prevVal(0); // the previous node's index in the file unsigned currVal(0); // the current node's index in the file unsigned diff(0); // the difference between consecutive indexes (a large value signifies a good fragment) unsigned numFrags(0); // the number of fragments (gets incremented in the following loop) RepairTreeNode* previous(NULL); // We know the first fragment is always at the beginning of the file, and we'll skip the first node in the loop below bounds[0] = 0; ++numFrags; // cerr << "Version Start" << endl; for (auto it = nodes.begin(); it != nodes.end(); ++it) { RepairTreeNode* current = *it; // cerr << "Symbol: " << current->getSymbol() << endl; // cerr << current->getOffset() << ","; if (!previous) { previous = current; continue; } prevVal = previous->getOffset(); currVal = current->getOffset(); diff = currVal - prevVal; if (diff >= minFragSize) { // These offsets are already sorted (see the comparator at the top) bounds[numFrags] = current->getOffset(); numFrags++; } // Update previous to point to this node now that we're done with it previous = current; } // cerr << endl << endl; // system("pause"); // Calculate the last diff so that the last fragment obeys the minFragSize rule if (nodes.size() >= 1) { unsigned lastDiff = versionSize - bounds[numFrags - 1]; if (lastDiff >= minFragSize) { // Our last fragment is ok, just add the position at the end of the file bounds[numFrags] = versionSize; numFrags++; } else { // Our last fragment is too small, replace the last offset we had with the position at the end of the file bounds[numFrags - 1] = versionSize; } } // TODO Handle this if (numFrags > MAX_NUM_FRAGMENTS_PER_VERSION) { // Fail or try a partitioning that won't fragment so much } return numFrags; } void RepairDocumentPartition::setPartitioningsAllVersions(unsigned numLevelsDown, unsigned minFragSize) { unsigned versionOffset(0); // after the loop, is set to the total number of fragments (also the size of the starts array) unsigned numFragments(0); // will be reused in the loop for the number of fragments in each version RepairTreeNode* rootForThisVersion = NULL; // Iterate over all versions for (unsigned i = 0; i < this->versionData.size(); i++) { rootForThisVersion = this->versionData[i].getRootNode(); // Do the partitioning for one version, and store the number of fragments numFragments = getPartitioningOneVersion(rootForThisVersion, numLevelsDown, &(this->offsets[versionOffset]), minFragSize, versionData[i].getVersionSize()); versionOffset += numFragments; this->versionSizes[i] = numFragments; } } void RepairDocumentPartition::setFragmentInfo(const vector<vector<unsigned> >& versions, ostream& os, bool print) { os << "*** Fragments ***" << endl; unsigned start, end, theID, fragSize; string word; vector<unsigned> wordIDs; MD5 md5; char* concatOfWordIDs; unsigned totalCountFragments(0); // Iterate over versions for (unsigned v = 0; v < versions.size(); v++) { wordIDs = versions[v]; // all the word IDs for version v this->fragments.push_back(vector<FragInfo >()); if (print) os << "Version " << v << endl; // One version: iterate over the words in that version for (unsigned i = 0; i < this->versionSizes[v] - 1; i++) { start = this->offsets[totalCountFragments + i]; end = this->offsets[totalCountFragments + i + 1]; fragSize = end - start; if (print) os << "Fragment " << i << ": "; stringstream ss; for (unsigned j = start; j < end; j++) { theID = wordIDs[j]; // Need a delimiter to ensure uniqueness (1,2,3 is different from 12,3) ss << theID << ","; } // Store the concatenation of the IDs for this fragment concatOfWordIDs = new char[MAX_FRAG_LENGTH]; strcpy(concatOfWordIDs, ss.str().c_str()); // Calculate the hash of the fragment string hash; // = new char[128]; // md5 produces 128 bit output hash = md5.digestString(concatOfWordIDs); this->fragments[v].push_back(FragInfo(0, 0, fragSize, hash)); ss.str(""); if (print) os << "hash (" << hash << ")" << endl; delete [] concatOfWordIDs; concatOfWordIDs = NULL; } totalCountFragments += this->versionSizes[v]; if (print) os << endl; } } void RepairDocumentPartition::updateUniqueFragmentHashMap() { unordered_map<string, FragInfo>::iterator it; for (size_t i = 0; i < this->fragments.size(); i++) { for (size_t j = 0; j < this->fragments[i].size(); j++) { FragInfo frag = this->fragments[i][j]; string myHash = frag.hash; unsigned theID; if (this->uniqueFrags.count(myHash)) { // Found it, so use its ID theID = this->uniqueFrags[myHash].id; this->uniqueFrags[myHash].count++; } else { // Didn't find it, give it an ID theID = nextFragID(); frag.id = theID; frag.count = 1; this->uniqueFrags[myHash] = frag; } } } } void RepairDocumentPartition::writeResults(const vector<vector<unsigned> >& versions, unordered_map<unsigned, string>& IDsToWords, const string& outFilename, bool printFragments, bool printAssociations) { ofstream os(outFilename.c_str()); os << "Results of re-pair partitioning..." << endl << endl; os << "*** Fragment boundaries ***" << endl; unsigned totalCountFragments(0); unsigned diff(0); unsigned numVersions = versions.size(); for (unsigned v = 0; v < numVersions; v++) { unsigned numFragsInVersion = versionSizes[v]; if (numFragsInVersion < 1) { continue; } os << "Version " << v << endl; for (unsigned i = 0; i < numFragsInVersion - 1; i++) { if (i < numFragsInVersion - 1) { unsigned currOffset = offsets[totalCountFragments + i]; unsigned nextOffset = offsets[totalCountFragments + i + 1]; diff = nextOffset - currOffset; } else { diff = 0; } os << "Fragment " << i << ": " << offsets[totalCountFragments + i] << "-" << offsets[totalCountFragments + i + 1] << " (frag size: " << diff << ")" << endl; } totalCountFragments += numFragsInVersion; os << endl; } // os << "Number of fragment boundaries: " << starts.size() << endl; // os << "Number of fragments: " << (starts.size() - 1) << endl << endl; this->setFragmentInfo(versions, os, printFragments); // Assign fragment IDs and stick them in a hashmap unordered_map<string, FragInfo> uniqueFrags; this->updateUniqueFragmentHashMap(); // Now decide on the score for this partitioning double score = this->getScore(os); os << "Score: " << score << endl; }<commit_msg>make default alg greedy, we never really use naive<commit_after>#include <sstream> #include "Partitioning.h" using namespace std; double RepairDocumentPartition::getScore(ostream& os) { double term; double sum(0); double totalFragSize(0); for (unordered_map<string, FragInfo>::iterator it = uniqueFrags.begin(); it != uniqueFrags.end(); it++) { term = it->second.count * it->second.fragSize; sum += term; totalFragSize += it->second.fragSize; } if (uniqueFrags.size() == 0) return 0.0; double avgFragSize = totalFragSize / uniqueFrags.size(); return sum / (uniqueFrags.size() * avgFragSize); } SortedByOffsetNodeSet RepairDocumentPartition::getNodesNthLevelDown(RepairTreeNode* root, unsigned numLevelsDown, SortedByOffsetNodeSet& nodes) { if (!root) return nodes; if (numLevelsDown < 1) return nodes; if (numLevelsDown == 1) { if (root->getLeftChild() && root->getRightChild()) { nodes.insert(root->getLeftChild()); nodes.insert(root->getRightChild()); } return nodes; } if (root->getLeftChild() && root->getRightChild()) { this->getNodesNthLevelDown(root->getLeftChild(), numLevelsDown - 1, nodes); this->getNodesNthLevelDown(root->getRightChild(), numLevelsDown - 1, nodes); } return nodes; } int RepairDocumentPartition::getAssociationLocation(unsigned symbol) { if (memoizedAssociationLocations.count(symbol)) return memoizedAssociationLocations[symbol]; // It wasn't saved, so search for it, and save it for next time int loc = binarySearch(symbol, associations, 0, associations.size()); memoizedAssociationLocations[symbol] = loc; return loc; } double RepairDocumentPartition::getSubsetScore(SortedByOffsetNodeSet subset) { /* AVG */ // unsigned sum(0); // for (SortedByOffsetNodeSet::iterator it = subset.begin(); it != subset.end(); it++) // { // RepairTreeNode* currNode = *it; // unsigned currScore = 1; // int loc = getAssociationLocation(currNode->getSymbol()); // if (loc != -1) // { // Association a = associations[loc]; // currScore = currNode->getSize() * a.getFreq(); // } // sum += currScore; // } // if (subset.size() == 0 || sum == 0) return 0.0; // return ((double) sum) / ((double)subset.size()); /* MAX */ double currMax(0); for (SortedByOffsetNodeSet::iterator it = subset.begin(); it != subset.end(); it++) { RepairTreeNode* currNode = *it; double currScore = 1.0; int loc = getAssociationLocation(currNode->getSymbol()); if (loc != -1) { Association a = associations[loc]; currScore = currNode->getSize() * a.getFreq(); } if (currScore > currMax) { currMax = currScore; } } if (subset.size() == 0 || currMax == 0) return 0.0; return currMax; } SortedByOffsetNodeSet RepairDocumentPartition::getBestSubset(RepairTreeNode* node) { SortedByOffsetNodeSet nodes = SortedByOffsetNodeSet(); if (!node) return nodes; double myScore = 1.0; int loc = getAssociationLocation(node->getSymbol()); if (loc != -1) { Association a = associations[loc]; myScore = node->getSize() * a.getFreq(); } // node is a terminal if (!node->getLeftChild()) { nodes.insert(node); return nodes; } RepairTreeNode* leftChild = node->getLeftChild(); RepairTreeNode* rightChild = node->getRightChild(); SortedByOffsetNodeSet leftSubset = getBestSubset(leftChild); SortedByOffsetNodeSet rightSubset = getBestSubset(rightChild); double leftScore = getSubsetScore(leftSubset); double rightScore = getSubsetScore(rightSubset); // TODO try changing to max(leftScore, rightScore) double childrenScore = fragmentationCoefficient * (leftScore + rightScore); // Coefficient for fragmenting if (myScore >= childrenScore) { nodes.insert(node); return nodes; } nodes.insert(leftSubset.begin(), leftSubset.end()); nodes.insert(rightSubset.begin(), rightSubset.end()); return nodes; } unsigned RepairDocumentPartition::getPartitioningOneVersion(RepairTreeNode* root, unsigned numLevelsDown, unsigned* bounds, unsigned minFragSize, unsigned versionSize) { SortedByOffsetNodeSet nodes = SortedByOffsetNodeSet(); switch (this->method) { case RepairDocumentPartition::NAIVE: nodes = getNodesNthLevelDown(root, numLevelsDown, nodes); break; case RepairDocumentPartition::GREEDY: nodes = getBestSubset(root); break; // default is greedy default: nodes = getBestSubset(root); break; } unsigned prevVal(0); // the previous node's index in the file unsigned currVal(0); // the current node's index in the file unsigned diff(0); // the difference between consecutive indexes (a large value signifies a good fragment) unsigned numFrags(0); // the number of fragments (gets incremented in the following loop) RepairTreeNode* previous(NULL); // We know the first fragment is always at the beginning of the file, and we'll skip the first node in the loop below bounds[0] = 0; ++numFrags; // cerr << "Version Start" << endl; for (auto it = nodes.begin(); it != nodes.end(); ++it) { RepairTreeNode* current = *it; // cerr << "Symbol: " << current->getSymbol() << endl; // cerr << current->getOffset() << ","; if (!previous) { previous = current; continue; } prevVal = previous->getOffset(); currVal = current->getOffset(); diff = currVal - prevVal; if (diff >= minFragSize) { // These offsets are already sorted (see the comparator at the top) bounds[numFrags] = current->getOffset(); numFrags++; } // Update previous to point to this node now that we're done with it previous = current; } // cerr << endl << endl; // system("pause"); // Calculate the last diff so that the last fragment obeys the minFragSize rule if (nodes.size() >= 1) { unsigned lastDiff = versionSize - bounds[numFrags - 1]; if (lastDiff >= minFragSize) { // Our last fragment is ok, just add the position at the end of the file bounds[numFrags] = versionSize; numFrags++; } else { // Our last fragment is too small, replace the last offset we had with the position at the end of the file bounds[numFrags - 1] = versionSize; } } // TODO Handle this if (numFrags > MAX_NUM_FRAGMENTS_PER_VERSION) { // Fail or try a partitioning that won't fragment so much } return numFrags; } void RepairDocumentPartition::setPartitioningsAllVersions(unsigned numLevelsDown, unsigned minFragSize) { unsigned versionOffset(0); // after the loop, is set to the total number of fragments (also the size of the starts array) unsigned numFragments(0); // will be reused in the loop for the number of fragments in each version RepairTreeNode* rootForThisVersion = NULL; // Iterate over all versions for (unsigned i = 0; i < this->versionData.size(); i++) { rootForThisVersion = this->versionData[i].getRootNode(); // Do the partitioning for one version, and store the number of fragments numFragments = getPartitioningOneVersion(rootForThisVersion, numLevelsDown, &(this->offsets[versionOffset]), minFragSize, versionData[i].getVersionSize()); versionOffset += numFragments; this->versionSizes[i] = numFragments; } } void RepairDocumentPartition::setFragmentInfo(const vector<vector<unsigned> >& versions, ostream& os, bool print) { os << "*** Fragments ***" << endl; unsigned start, end, theID, fragSize; string word; vector<unsigned> wordIDs; MD5 md5; char* concatOfWordIDs; unsigned totalCountFragments(0); // Iterate over versions for (unsigned v = 0; v < versions.size(); v++) { wordIDs = versions[v]; // all the word IDs for version v this->fragments.push_back(vector<FragInfo >()); if (print) os << "Version " << v << endl; // One version: iterate over the words in that version for (unsigned i = 0; i < this->versionSizes[v] - 1; i++) { start = this->offsets[totalCountFragments + i]; end = this->offsets[totalCountFragments + i + 1]; fragSize = end - start; if (print) os << "Fragment " << i << ": "; stringstream ss; for (unsigned j = start; j < end; j++) { theID = wordIDs[j]; // Need a delimiter to ensure uniqueness (1,2,3 is different from 12,3) ss << theID << ","; } // Store the concatenation of the IDs for this fragment concatOfWordIDs = new char[MAX_FRAG_LENGTH]; strcpy(concatOfWordIDs, ss.str().c_str()); // Calculate the hash of the fragment string hash; // = new char[128]; // md5 produces 128 bit output hash = md5.digestString(concatOfWordIDs); this->fragments[v].push_back(FragInfo(0, 0, fragSize, hash)); ss.str(""); if (print) os << "hash (" << hash << ")" << endl; delete [] concatOfWordIDs; concatOfWordIDs = NULL; } totalCountFragments += this->versionSizes[v]; if (print) os << endl; } } void RepairDocumentPartition::updateUniqueFragmentHashMap() { unordered_map<string, FragInfo>::iterator it; for (size_t i = 0; i < this->fragments.size(); i++) { for (size_t j = 0; j < this->fragments[i].size(); j++) { FragInfo frag = this->fragments[i][j]; string myHash = frag.hash; unsigned theID; if (this->uniqueFrags.count(myHash)) { // Found it, so use its ID theID = this->uniqueFrags[myHash].id; this->uniqueFrags[myHash].count++; } else { // Didn't find it, give it an ID theID = nextFragID(); frag.id = theID; frag.count = 1; this->uniqueFrags[myHash] = frag; } } } } void RepairDocumentPartition::writeResults(const vector<vector<unsigned> >& versions, unordered_map<unsigned, string>& IDsToWords, const string& outFilename, bool printFragments, bool printAssociations) { ofstream os(outFilename.c_str()); os << "Results of re-pair partitioning..." << endl << endl; os << "*** Fragment boundaries ***" << endl; unsigned totalCountFragments(0); unsigned diff(0); unsigned numVersions = versions.size(); for (unsigned v = 0; v < numVersions; v++) { unsigned numFragsInVersion = versionSizes[v]; if (numFragsInVersion < 1) { continue; } os << "Version " << v << endl; for (unsigned i = 0; i < numFragsInVersion - 1; i++) { if (i < numFragsInVersion - 1) { unsigned currOffset = offsets[totalCountFragments + i]; unsigned nextOffset = offsets[totalCountFragments + i + 1]; diff = nextOffset - currOffset; } else { diff = 0; } os << "Fragment " << i << ": " << offsets[totalCountFragments + i] << "-" << offsets[totalCountFragments + i + 1] << " (frag size: " << diff << ")" << endl; } totalCountFragments += numFragsInVersion; os << endl; } // os << "Number of fragment boundaries: " << starts.size() << endl; // os << "Number of fragments: " << (starts.size() - 1) << endl << endl; this->setFragmentInfo(versions, os, printFragments); // Assign fragment IDs and stick them in a hashmap unordered_map<string, FragInfo> uniqueFrags; this->updateUniqueFragmentHashMap(); // Now decide on the score for this partitioning double score = this->getScore(os); os << "Score: " << score << endl; }<|endoftext|>
<commit_before>#include <iostream> #include <string> #include <boost/program_options.hpp> namespace po = boost::program_options; using namespace std; /* Usage: hadoop fs [generic options] [-appendToFile <localsrc> ... <dst>] [-cat [-ignoreCrc] <src> ...] [-checksum <src> ...] [-chgrp [-R] GROUP PATH...] [-chmod [-R] <MODE[,MODE]... | OCTALMODE> PATH...] [-chown [-R] [OWNER][:[GROUP]] PATH...] [-copyFromLocal [-f] [-p] <localsrc> ... <dst>] [-copyToLocal [-p] [-ignoreCrc] [-crc] <src> ... <localdst>] [-count [-q] <path> ...] [-cp [-f] [-p] <src> ... <dst>] [-createSnapshot <snapshotDir> [<snapshotName>]] [-deleteSnapshot <snapshotDir> <snapshotName>] [-df [-h] [<path> ...]] [-du [-s] [-h] <path> ...] [-expunge] [-get [-p] [-ignoreCrc] [-crc] <src> ... <localdst>] [-getfacl [-R] <path>] [-getmerge [-nl] <src> <localdst>] [-help [cmd ...]] [-ls [-d] [-h] [-R] [<path> ...]] [-mkdir [-p] <path> ...] [-moveFromLocal <localsrc> ... <dst>] [-moveToLocal <src> <localdst>] [-mv <src> ... <dst>] [-put [-f] [-p] <localsrc> ... <dst>] [-renameSnapshot <snapshotDir> <oldName> <newName>] [-rm [-f] [-r|-R] [-skipTrash] <src> ...] [-rmdir [--ignore-fail-on-non-empty] <dir> ...] [-setfacl [-R] [{-b|-k} {-m|-x <acl_spec>} <path>]|[--set <acl_spec> <path>]] [-setrep [-R] [-w] <rep> <path> ...] [-stat [format] <path> ...] [-tail [-f] <file>] [-test -[defsz] <path>] [-text [-ignoreCrc] <src> ...] [-touchz <path> ...] [-usage [cmd ...]] */ static const string constStrDecs = "Usage: mdfs.client [generic options]\n" " [-appendToFile <localsrc> ... <dst>]\n" " [-cat [-ignoreCrc] <src> ...]\n" " [-checksum <src> ...]\n" " [-chgrp [-R] GROUP PATH...]\n" " [-chmod [-R] <MODE[,MODE]... | OCTALMODE> PATH...]\n" " [-chown [-R] [OWNER][:[GROUP]] PATH...]\n" " [-copyFromLocal [-f] [-p] <localsrc> ... <dst>]\n" " [-copyToLocal [-p] [-ignoreCrc] [-crc] <src> ... <localdst>]\n" " [-count [-q] <path> ...]\n" " [-cp [-f] [-p] <src> ... <dst>]\n" " [-createSnapshot <snapshotDir> [<snapshotName>]]\n" " [-deleteSnapshot <snapshotDir> <snapshotName>]\n" " [-df [-h] [<path> ...]]\n" " [-du [-s] [-h] <path> ...]\n" " [-expunge]\n" " [-get [-p] [-ignoreCrc] [-crc] <src> ... <localdst>]\n" " [-getfacl [-R] <path>]\n" " [-getmerge [-nl] <src> <localdst>]\n" " [-help [cmd ...]]\n" " [-ls [-d] [-h] [-R] [<path> ...]]\n" " [-mkdir [-p] <path> ...]\n" " [-moveFromLocal <localsrc> ... <dst>]\n" " [-moveToLocal <src> <localdst>]\n" " [-mv <src> ... <dst>]\n" " [-put [-f] [-p] <localsrc> ... <dst>]\n" " [-renameSnapshot <snapshotDir> <oldName> <newName>]\n" " [-rm [-f] [-r|-R] [-skipTrash] <src> ...]\n" " [-rmdir [--ignore-fail-on-non-empty] <dir> ...]\n" " [-setfacl [-R] [{-b|-k} {-m|-x <acl_spec>} <path>]|[--set <acl_spec> <path>]]\n" " [-setrep [-R] [-w] <rep> <path> ...]\n" " [-stat [format] <path> ...]\n" " [-tail [-f] <file>]\n" " [-test -[defsz] <path>]\n" " [-text [-ignoreCrc] <src> ...]\n" " [-touchz <path> ...]\n" " [-usage [cmd ...]]\n" ; int main(int ac,char*av[]) { po::options_description opt(constStrDecs); opt.add_options() ("help,h" , "") (",appendToFile" , po::value<string>() ," <localsrc> ... <dst>") ; po::variables_map vm; try { po::store(po::parse_command_line(ac, av, opt), vm); } catch(const po::error_with_option_name& e) { std::cout << e.what() << std::endl; } po::notify(vm); if (vm.count("help") || !vm.count("op")) { std::cout << opt << std::endl; } else { try { const std::string op = vm["op"].as<std::string>(); const int lhs = vm["lhs"].as<int>(); const int rhs = vm["rhs"].as<int>(); if (op == "add") { std::cout << lhs + rhs << std::endl; } if (op == "sub") { std::cout << lhs - rhs << std::endl; } } catch(const boost::bad_any_cast& e) { std::cout << e.what() << std::endl; } } return 0; } <commit_msg>add options<commit_after>#include <iostream> #include <string> #include <boost/program_options.hpp> namespace po = boost::program_options; using namespace std; /* Usage: hadoop fs [generic options] [-appendToFile <localsrc> ... <dst>] [-cat [-ignoreCrc] <src> ...] [-checksum <src> ...] [-chgrp [-R] GROUP PATH...] [-chmod [-R] <MODE[,MODE]... | OCTALMODE> PATH...] [-chown [-R] [OWNER][:[GROUP]] PATH...] [-copyFromLocal [-f] [-p] <localsrc> ... <dst>] [-copyToLocal [-p] [-ignoreCrc] [-crc] <src> ... <localdst>] [-count [-q] <path> ...] [-cp [-f] [-p] <src> ... <dst>] [-createSnapshot <snapshotDir> [<snapshotName>]] [-deleteSnapshot <snapshotDir> <snapshotName>] [-df [-h] [<path> ...]] [-du [-s] [-h] <path> ...] [-expunge] [-get [-p] [-ignoreCrc] [-crc] <src> ... <localdst>] [-getfacl [-R] <path>] [-getmerge [-nl] <src> <localdst>] [-help [cmd ...]] [-ls [-d] [-h] [-R] [<path> ...]] [-mkdir [-p] <path> ...] [-moveFromLocal <localsrc> ... <dst>] [-moveToLocal <src> <localdst>] [-mv <src> ... <dst>] [-put [-f] [-p] <localsrc> ... <dst>] [-renameSnapshot <snapshotDir> <oldName> <newName>] [-rm [-f] [-r|-R] [-skipTrash] <src> ...] [-rmdir [--ignore-fail-on-non-empty] <dir> ...] [-setfacl [-R] [{-b|-k} {-m|-x <acl_spec>} <path>]|[--set <acl_spec> <path>]] [-setrep [-R] [-w] <rep> <path> ...] [-stat [format] <path> ...] [-tail [-f] <file>] [-test -[defsz] <path>] [-text [-ignoreCrc] <src> ...] [-touchz <path> ...] [-usage [cmd ...]] */ static const string constStrDecs = "Usage: mdfs.client \n" " [-appendToFile <localsrc> ... <dst>]\n" " [-cat [-ignoreCrc] <src> ...]\n" " [-checksum <src> ...]\n" " [-chgrp [-R] GROUP PATH...]\n" " [-chmod [-R] <MODE[,MODE]... | OCTALMODE> PATH...]\n" " [-chown [-R] [OWNER][:[GROUP]] PATH...]\n" " [-copyFromLocal [-f] [-p] <localsrc> ... <dst>]\n" " [-copyToLocal [-p] [-ignoreCrc] [-crc] <src> ... <localdst>]\n" " [-count [-q] <path> ...]\n" " [-cp [-f] [-p] <src> ... <dst>]\n" " [-createSnapshot <snapshotDir> [<snapshotName>]]\n" " [-deleteSnapshot <snapshotDir> <snapshotName>]\n" " [-df [-h] [<path> ...]]\n" " [-du [-s] [-h] <path> ...]\n" " [-expunge]\n" " [-get [-p] [-ignoreCrc] [-crc] <src> ... <localdst>]\n" " [-getfacl [-R] <path>]\n" " [-getmerge [-nl] <src> <localdst>]\n" " [-help [cmd ...]]\n" " [-ls [-d] [-h] [-R] [<path> ...]]\n" " [-mkdir [-p] <path> ...]\n" " [-moveFromLocal <localsrc> ... <dst>]\n" " [-moveToLocal <src> <localdst>]\n" " [-mv <src> ... <dst>]\n" " [-put [-f] [-p] <localsrc> ... <dst>]\n" " [-renameSnapshot <snapshotDir> <oldName> <newName>]\n" " [-rm [-f] [-r|-R] [-skipTrash] <src> ...]\n" " [-rmdir [--ignore-fail-on-non-empty] <dir> ...]\n" " [-setfacl [-R] [{-b|-k} {-m|-x <acl_spec>} <path>]|[--set <acl_spec> <path>]]\n" " [-setrep [-R] [-w] <rep> <path> ...]\n" " [-stat [format] <path> ...]\n" " [-tail [-f] <file>]\n" " [-test -[defsz] <path>]\n" " [-text [-ignoreCrc] <src> ...]\n" " [-touchz <path> ...]\n" " [-usage [cmd ...]]\n" ; int main(int ac,char*av[]) { po::options_description opt(constStrDecs); opt.add_options() ("help,h" , "") (",appendToFile" , po::value<string>() ," <localsrc> ... <dst>") ; po::variables_map vm; try { po::store(po::parse_command_line(ac, av, opt), vm); } catch(const po::error_with_option_name& e) { std::cout << e.what() << std::endl; } po::notify(vm); if (vm.count("help") || !vm.count("op")) { std::cout << opt << std::endl; } else { try { const std::string op = vm["op"].as<std::string>(); const int lhs = vm["lhs"].as<int>(); const int rhs = vm["rhs"].as<int>(); if (op == "add") { std::cout << lhs + rhs << std::endl; } if (op == "sub") { std::cout << lhs - rhs << std::endl; } } catch(const boost::bad_any_cast& e) { std::cout << e.what() << std::endl; } } return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: ScriptInfoImpl.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: dsherwin $ $Date: 2002-10-17 14:58: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): _______________________________________ * * ************************************************************************/ #ifndef _SCRIPTING_STORAGE_SCRIPTINFOIMPL_HXX_ #define _SCRIPTING_STORAGE_SCRIPTINFOIMPL_HXX_ #include <vector> #include <map> #include <cppu/macros.hxx> #include <rtl/ustring.hxx> typedef ::std::pair< ::rtl::OUString, ::rtl::OUString > str_pair; typedef ::std::map< ::rtl::OUString, str_pair, ::std::equal_to< ::rtl::OUString > > strpair_map; typedef ::std::vector< str_pair > langdepprops_vec; typedef ::std::map< ::rtl::OUString, strpair_map, ::std::equal_to< ::rtl::OUString > > filesets_map; namespace scripting_impl { struct ScriptInfoImpl { inline ScriptInfoImpl::ScriptInfoImpl() SAL_THROW( () ) : language() , locales() , functionname() , logicalname() , languagedepprops() , filesets() { } inline ScriptInfoImpl::ScriptInfoImpl( const ::rtl::OUString& __language, const strpair_map& __locales, const ::rtl::OUString& __functionname, const ::rtl::OUString& __logicalname, const langdepprops_vec& __languagedepprops, const filesets_map& __filesets ) SAL_THROW( () ) : language( __language ) , locales( __locales ) , functionname( __functionname ) , logicalname( __logicalname ) , languagedepprops( __languagedepprops ) , filesets( __filesets ) { } ::rtl::OUString language; strpair_map locales; ::rtl::OUString functionname; ::rtl::OUString logicalname; langdepprops_vec languagedepprops; filesets_map filesets; }; } // namespace scripting_impl #endif // _SCRIPTING_STORAGE_SCRIPTINFOIMPL_HXX_ <commit_msg>Changed to represent new DTD<commit_after>/************************************************************************* * * $RCSfile: ScriptInfoImpl.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: dsherwin $ $Date: 2002-10-18 13:24: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): _______________________________________ * * ************************************************************************/ #ifndef _SCRIPTING_STORAGE_SCRIPTINFOIMPL_HXX_ #define _SCRIPTING_STORAGE_SCRIPTINFOIMPL_HXX_ #include <vector> #include <map> #include <cppu/macros.hxx> #include <rtl/ustring.hxx> typedef ::std::pair< ::rtl::OUString, ::rtl::OUString > str_pair; typedef ::std::map< ::rtl::OUString, str_pair, ::std::equal_to< ::rtl::OUString > > strpair_map; typedef ::std::vector< str_pair > props_vec; typedef ::std::map< ::rtl::OUString, ::std::pair< props_vec, strpair_map >, ::std::equal_to< ::rtl::OUString > > filesets_map; namespace scripting_impl { struct ScriptInfoImpl { inline ScriptInfoImpl::ScriptInfoImpl() SAL_THROW( () ) : parcelURI() , language() , locales() , functionname() , logicalname() , languagedepprops() , filesets() { } inline ScriptInfoImpl::ScriptInfoImpl( const ::rtl::OUString __parcelURI, const ::rtl::OUString& __language, const strpair_map& __locales, const ::rtl::OUString& __functionname, const ::rtl::OUString& __logicalname, const langdepprops_vec& __languagedepprops, const filesets_map& __filesets ) SAL_THROW( () ) : parcelURI( __parcelURI ) , language( __language ) , locales( __locales ) , functionname( __functionname ) , logicalname( __logicalname ) , languagedepprops( __languagedepprops ) , filesets( __filesets ) { } ::rtl::OUString parcelURI; ::rtl::OUString language; strpair_map locales; ::rtl::OUString functionname; ::rtl::OUString logicalname; props_vec languagedepprops; filesets_map filesets; }; } // namespace scripting_impl #endif // _SCRIPTING_STORAGE_SCRIPTINFOIMPL_HXX_ <|endoftext|>
<commit_before>#include "util/file_piece.hh" #include "util/exception.hh" #include "util/file.hh" #include "util/mmap.hh" #ifdef WIN32 #include <io.h> #endif // WIN32 #include <iostream> #include <string> #include <limits> #include <assert.h> #include <ctype.h> #include <fcntl.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> namespace util { ParseNumberException::ParseNumberException(StringPiece value) throw() { *this << "Could not parse \"" << value << "\" into a number"; } #ifdef HAVE_ZLIB GZException::GZException(gzFile file) { int num; *this << gzerror((gzFile)file, &num) << " from zlib"; #endif // HAVE_ZLIB } #endif // HAVE_ZLIB // Sigh this is the only way I could come up with to do a _const_ bool. It has ' ', '\f', '\n', '\r', '\t', and '\v' (same as isspace on C locale). const bool kSpaces[256] = {0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; FilePiece::FilePiece(const char *name, std::ostream *show_progress, std::size_t min_buffer) : file_(OpenReadOrThrow(name)), total_size_(SizeFile(file_.get())), page_(SizePage()), progress_(total_size_ == kBadSize ? NULL : show_progress, std::string("Reading ") + name, total_size_) { Initialize(name, show_progress, min_buffer); } FilePiece::FilePiece(int fd, const char *name, std::ostream *show_progress, std::size_t min_buffer) : file_(fd), total_size_(SizeFile(file_.get())), page_(SizePage()), progress_(total_size_ == kBadSize ? NULL : show_progress, std::string("Reading ") + name, total_size_) { Initialize(name, show_progress, min_buffer); } FilePiece::~FilePiece() { #ifdef HAVE_ZLIB if (gz_file_) { // zlib took ownership file_.release(); int ret; if (Z_OK != (ret = gzclose((gzFile)gz_file_))) { std::cerr << "could not close file " << file_name_ << " using zlib" << std::endl; abort(); } } #endif } StringPiece FilePiece::ReadLine(char delim) { std::size_t skip = 0; while (true) { for (const char *i = position_ + skip; i < position_end_; ++i) { if (*i == delim) { StringPiece ret(position_, i - position_); position_ = i + 1; return ret; } } if (at_end_) { if (position_ == position_end_) Shift(); return Consume(position_end_); } skip = position_end_ - position_; Shift(); } } float FilePiece::ReadFloat() { return ReadNumber<float>(); } double FilePiece::ReadDouble() { return ReadNumber<double>(); } long int FilePiece::ReadLong() { return ReadNumber<long int>(); } unsigned long int FilePiece::ReadULong() { return ReadNumber<unsigned long int>(); } void FilePiece::Initialize(const char *name, std::ostream *show_progress, std::size_t min_buffer) { #ifdef HAVE_ZLIB gz_file_ = NULL; #endif file_name_ = name; default_map_size_ = page_ * std::max<std::size_t>((min_buffer / page_ + 1), 2); position_ = NULL; position_end_ = NULL; mapped_offset_ = 0; at_end_ = false; if (total_size_ == kBadSize) { // So the assertion passes. fallback_to_read_ = false; if (show_progress) *show_progress << "File " << name << " isn't normal. Using slower read() instead of mmap(). No progress bar." << std::endl; TransitionToRead(); } else { fallback_to_read_ = false; } Shift(); // gzip detect. if ((position_end_ - position_) > 2 && *position_ == 0x1f && static_cast<unsigned char>(*(position_ + 1)) == 0x8b) { #ifndef HAVE_ZLIB UTIL_THROW(GZException, "Looks like a gzip file but support was not compiled in."); #endif if (!fallback_to_read_) { at_end_ = false; TransitionToRead(); } } } namespace { void ParseNumber(const char *begin, char *&end, float &out) { #if defined(sun) || defined(WIN32) out = static_cast<float>(strtod(begin, &end)); #else out = strtof(begin, &end); #endif } void ParseNumber(const char *begin, char *&end, double &out) { out = strtod(begin, &end); } void ParseNumber(const char *begin, char *&end, long int &out) { out = strtol(begin, &end, 10); } void ParseNumber(const char *begin, char *&end, unsigned long int &out) { out = strtoul(begin, &end, 10); } } // namespace template <class T> T FilePiece::ReadNumber() { SkipSpaces(); while (last_space_ < position_) { if (at_end_) { // Hallucinate a null off the end of the file. std::string buffer(position_, position_end_); char *end; T ret; ParseNumber(buffer.c_str(), end, ret); if (buffer.c_str() == end) throw ParseNumberException(buffer); position_ += end - buffer.c_str(); return ret; } Shift(); } char *end; T ret; ParseNumber(position_, end, ret); if (end == position_) throw ParseNumberException(ReadDelimited()); position_ = end; return ret; } const char *FilePiece::FindDelimiterOrEOF(const bool *delim) { std::size_t skip = 0; while (true) { for (const char *i = position_ + skip; i < position_end_; ++i) { if (delim[static_cast<unsigned char>(*i)]) return i; } if (at_end_) { if (position_ == position_end_) Shift(); return position_end_; } skip = position_end_ - position_; Shift(); } } void FilePiece::Shift() { if (at_end_) { progress_.Finished(); throw EndOfFileException(); } uint64_t desired_begin = position_ - data_.begin() + mapped_offset_; if (!fallback_to_read_) MMapShift(desired_begin); // Notice an mmap failure might set the fallback. if (fallback_to_read_) ReadShift(); for (last_space_ = position_end_ - 1; last_space_ >= position_; --last_space_) { if (isspace(*last_space_)) break; } } void FilePiece::MMapShift(uint64_t desired_begin) { // Use mmap. uint64_t ignore = desired_begin % page_; // Duplicate request for Shift means give more data. if (position_ == data_.begin() + ignore) { default_map_size_ *= 2; } // Local version so that in case of failure it doesn't overwrite the class variable. uint64_t mapped_offset = desired_begin - ignore; uint64_t mapped_size; if (default_map_size_ >= static_cast<std::size_t>(total_size_ - mapped_offset)) { at_end_ = true; mapped_size = total_size_ - mapped_offset; } else { mapped_size = default_map_size_; } // Forcibly clear the existing mmap first. data_.reset(); try { MapRead(POPULATE_OR_LAZY, *file_, mapped_offset, mapped_size, data_); } catch (const util::ErrnoException &e) { if (desired_begin) { SeekOrThrow(*file_, desired_begin); } // The mmap was scheduled to end the file, but now we're going to read it. at_end_ = false; TransitionToRead(); return; } mapped_offset_ = mapped_offset; position_ = data_.begin() + ignore; position_end_ = data_.begin() + mapped_size; progress_.Set(desired_begin); } void FilePiece::TransitionToRead() { assert(!fallback_to_read_); fallback_to_read_ = true; data_.reset(); data_.reset(malloc(default_map_size_), default_map_size_, scoped_memory::MALLOC_ALLOCATED); UTIL_THROW_IF(!data_.get(), ErrnoException, "malloc failed for " << default_map_size_); position_ = data_.begin(); position_end_ = position_; #ifdef HAVE_ZLIB assert(!gz_file_); gz_file_ = gzdopen(file_.get(), "r"); UTIL_THROW_IF(!gz_file_, GZException, "zlib failed to open " << file_name_); #endif } #ifdef WIN32 typedef int ssize_t; #endif void FilePiece::ReadShift() { assert(fallback_to_read_); // Bytes [data_.begin(), position_) have been consumed. // Bytes [position_, position_end_) have been read into the buffer. // Start at the beginning of the buffer if there's nothing useful in it. if (position_ == position_end_) { mapped_offset_ += (position_end_ - data_.begin()); position_ = data_.begin(); position_end_ = position_; } std::size_t already_read = position_end_ - data_.begin(); if (already_read == default_map_size_) { if (position_ == data_.begin()) { // Buffer too small. std::size_t valid_length = position_end_ - position_; default_map_size_ *= 2; data_.call_realloc(default_map_size_); UTIL_THROW_IF(!data_.get(), ErrnoException, "realloc failed for " << default_map_size_); position_ = data_.begin(); position_end_ = position_ + valid_length; } else { size_t moving = position_end_ - position_; memmove(data_.get(), position_, moving); position_ = data_.begin(); position_end_ = position_ + moving; already_read = moving; } } ssize_t read_return; #ifdef HAVE_ZLIB read_return = gzread((gzFile)gz_file_, static_cast<char*>(data_.get()) + already_read, default_map_size_ - already_read); if (read_return == -1) throw GZException(gz_file_); if (total_size_ != kBadSize) { // Just get the position, don't actually seek. Apparently this is how you do it. . . off_t ret = lseek(file_.get(), 0, SEEK_CUR); if (ret != -1) progress_.Set(ret); } #else read_return = read(file_.get(), static_cast<char*>(data_.get()) + already_read, default_map_size_ - already_read); UTIL_THROW_IF(read_return == -1, ErrnoException, "read failed"); progress_.Set(mapped_offset_); #endif if (read_return == 0) { at_end_ = true; } position_end_ += read_return; } } // namespace util <commit_msg>Fixed merge problem.<commit_after>#include "util/file_piece.hh" #include "util/exception.hh" #include "util/file.hh" #include "util/mmap.hh" #ifdef WIN32 #include <io.h> #endif // WIN32 #include <iostream> #include <string> #include <limits> #include <assert.h> #include <ctype.h> #include <fcntl.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> namespace util { ParseNumberException::ParseNumberException(StringPiece value) throw() { *this << "Could not parse \"" << value << "\" into a number"; } #ifdef HAVE_ZLIB GZException::GZException(gzFile file) { int num; *this << gzerror((gzFile)file, &num) << " from zlib"; } #endif // HAVE_ZLIB // Sigh this is the only way I could come up with to do a _const_ bool. It has ' ', '\f', '\n', '\r', '\t', and '\v' (same as isspace on C locale). const bool kSpaces[256] = {0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; FilePiece::FilePiece(const char *name, std::ostream *show_progress, std::size_t min_buffer) : file_(OpenReadOrThrow(name)), total_size_(SizeFile(file_.get())), page_(SizePage()), progress_(total_size_ == kBadSize ? NULL : show_progress, std::string("Reading ") + name, total_size_) { Initialize(name, show_progress, min_buffer); } FilePiece::FilePiece(int fd, const char *name, std::ostream *show_progress, std::size_t min_buffer) : file_(fd), total_size_(SizeFile(file_.get())), page_(SizePage()), progress_(total_size_ == kBadSize ? NULL : show_progress, std::string("Reading ") + name, total_size_) { Initialize(name, show_progress, min_buffer); } FilePiece::~FilePiece() { #ifdef HAVE_ZLIB if (gz_file_) { // zlib took ownership file_.release(); int ret; if (Z_OK != (ret = gzclose((gzFile)gz_file_))) { std::cerr << "could not close file " << file_name_ << " using zlib" << std::endl; abort(); } } #endif } StringPiece FilePiece::ReadLine(char delim) { std::size_t skip = 0; while (true) { for (const char *i = position_ + skip; i < position_end_; ++i) { if (*i == delim) { StringPiece ret(position_, i - position_); position_ = i + 1; return ret; } } if (at_end_) { if (position_ == position_end_) Shift(); return Consume(position_end_); } skip = position_end_ - position_; Shift(); } } float FilePiece::ReadFloat() { return ReadNumber<float>(); } double FilePiece::ReadDouble() { return ReadNumber<double>(); } long int FilePiece::ReadLong() { return ReadNumber<long int>(); } unsigned long int FilePiece::ReadULong() { return ReadNumber<unsigned long int>(); } void FilePiece::Initialize(const char *name, std::ostream *show_progress, std::size_t min_buffer) { #ifdef HAVE_ZLIB gz_file_ = NULL; #endif file_name_ = name; default_map_size_ = page_ * std::max<std::size_t>((min_buffer / page_ + 1), 2); position_ = NULL; position_end_ = NULL; mapped_offset_ = 0; at_end_ = false; if (total_size_ == kBadSize) { // So the assertion passes. fallback_to_read_ = false; if (show_progress) *show_progress << "File " << name << " isn't normal. Using slower read() instead of mmap(). No progress bar." << std::endl; TransitionToRead(); } else { fallback_to_read_ = false; } Shift(); // gzip detect. if ((position_end_ - position_) > 2 && *position_ == 0x1f && static_cast<unsigned char>(*(position_ + 1)) == 0x8b) { #ifndef HAVE_ZLIB UTIL_THROW(GZException, "Looks like a gzip file but support was not compiled in."); #endif if (!fallback_to_read_) { at_end_ = false; TransitionToRead(); } } } namespace { void ParseNumber(const char *begin, char *&end, float &out) { #if defined(sun) || defined(WIN32) out = static_cast<float>(strtod(begin, &end)); #else out = strtof(begin, &end); #endif } void ParseNumber(const char *begin, char *&end, double &out) { out = strtod(begin, &end); } void ParseNumber(const char *begin, char *&end, long int &out) { out = strtol(begin, &end, 10); } void ParseNumber(const char *begin, char *&end, unsigned long int &out) { out = strtoul(begin, &end, 10); } } // namespace template <class T> T FilePiece::ReadNumber() { SkipSpaces(); while (last_space_ < position_) { if (at_end_) { // Hallucinate a null off the end of the file. std::string buffer(position_, position_end_); char *end; T ret; ParseNumber(buffer.c_str(), end, ret); if (buffer.c_str() == end) throw ParseNumberException(buffer); position_ += end - buffer.c_str(); return ret; } Shift(); } char *end; T ret; ParseNumber(position_, end, ret); if (end == position_) throw ParseNumberException(ReadDelimited()); position_ = end; return ret; } const char *FilePiece::FindDelimiterOrEOF(const bool *delim) { std::size_t skip = 0; while (true) { for (const char *i = position_ + skip; i < position_end_; ++i) { if (delim[static_cast<unsigned char>(*i)]) return i; } if (at_end_) { if (position_ == position_end_) Shift(); return position_end_; } skip = position_end_ - position_; Shift(); } } void FilePiece::Shift() { if (at_end_) { progress_.Finished(); throw EndOfFileException(); } uint64_t desired_begin = position_ - data_.begin() + mapped_offset_; if (!fallback_to_read_) MMapShift(desired_begin); // Notice an mmap failure might set the fallback. if (fallback_to_read_) ReadShift(); for (last_space_ = position_end_ - 1; last_space_ >= position_; --last_space_) { if (isspace(*last_space_)) break; } } void FilePiece::MMapShift(uint64_t desired_begin) { // Use mmap. uint64_t ignore = desired_begin % page_; // Duplicate request for Shift means give more data. if (position_ == data_.begin() + ignore) { default_map_size_ *= 2; } // Local version so that in case of failure it doesn't overwrite the class variable. uint64_t mapped_offset = desired_begin - ignore; uint64_t mapped_size; if (default_map_size_ >= static_cast<std::size_t>(total_size_ - mapped_offset)) { at_end_ = true; mapped_size = total_size_ - mapped_offset; } else { mapped_size = default_map_size_; } // Forcibly clear the existing mmap first. data_.reset(); try { MapRead(POPULATE_OR_LAZY, *file_, mapped_offset, mapped_size, data_); } catch (const util::ErrnoException &e) { if (desired_begin) { SeekOrThrow(*file_, desired_begin); } // The mmap was scheduled to end the file, but now we're going to read it. at_end_ = false; TransitionToRead(); return; } mapped_offset_ = mapped_offset; position_ = data_.begin() + ignore; position_end_ = data_.begin() + mapped_size; progress_.Set(desired_begin); } void FilePiece::TransitionToRead() { assert(!fallback_to_read_); fallback_to_read_ = true; data_.reset(); data_.reset(malloc(default_map_size_), default_map_size_, scoped_memory::MALLOC_ALLOCATED); UTIL_THROW_IF(!data_.get(), ErrnoException, "malloc failed for " << default_map_size_); position_ = data_.begin(); position_end_ = position_; #ifdef HAVE_ZLIB assert(!gz_file_); gz_file_ = gzdopen(file_.get(), "r"); UTIL_THROW_IF(!gz_file_, GZException, "zlib failed to open " << file_name_); #endif } #ifdef WIN32 typedef int ssize_t; #endif void FilePiece::ReadShift() { assert(fallback_to_read_); // Bytes [data_.begin(), position_) have been consumed. // Bytes [position_, position_end_) have been read into the buffer. // Start at the beginning of the buffer if there's nothing useful in it. if (position_ == position_end_) { mapped_offset_ += (position_end_ - data_.begin()); position_ = data_.begin(); position_end_ = position_; } std::size_t already_read = position_end_ - data_.begin(); if (already_read == default_map_size_) { if (position_ == data_.begin()) { // Buffer too small. std::size_t valid_length = position_end_ - position_; default_map_size_ *= 2; data_.call_realloc(default_map_size_); UTIL_THROW_IF(!data_.get(), ErrnoException, "realloc failed for " << default_map_size_); position_ = data_.begin(); position_end_ = position_ + valid_length; } else { size_t moving = position_end_ - position_; memmove(data_.get(), position_, moving); position_ = data_.begin(); position_end_ = position_ + moving; already_read = moving; } } ssize_t read_return; #ifdef HAVE_ZLIB read_return = gzread((gzFile)gz_file_, static_cast<char*>(data_.get()) + already_read, default_map_size_ - already_read); if (read_return == -1) throw GZException(gz_file_); if (total_size_ != kBadSize) { // Just get the position, don't actually seek. Apparently this is how you do it. . . off_t ret = lseek(file_.get(), 0, SEEK_CUR); if (ret != -1) progress_.Set(ret); } #else read_return = read(file_.get(), static_cast<char*>(data_.get()) + already_read, default_map_size_ - already_read); UTIL_THROW_IF(read_return == -1, ErrnoException, "read failed"); progress_.Set(mapped_offset_); #endif if (read_return == 0) { at_end_ = true; } position_end_ += read_return; } } // namespace util <|endoftext|>
<commit_before>/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * ola-throughput.cpp * Send a bunch of frames quickly to load test the server. * Copyright (C) 2005-2010 Simon Newton */ #include <errno.h> #include <getopt.h> #include <stdlib.h> #include <ola/DmxBuffer.h> #include <ola/Logging.h> #include <ola/StreamingClient.h> #include <ola/StringUtils.h> #include <iostream> #include <string> using std::cout; using std::endl; using std::string; using ola::StreamingClient; typedef struct { unsigned int universe; unsigned int sleep_time; bool help; } options; /* * parse our cmd line options */ void ParseOptions(int argc, char *argv[], options *opts) { static struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"sleep", required_argument, 0, 's'}, {"universe", required_argument, 0, 'u'}, {0, 0, 0, 0} }; opts->sleep_time = 40000; opts->universe = 1; opts->help = false; int c; int option_index = 0; while (1) { c = getopt_long(argc, argv, "hs:u:", long_options, &option_index); if (c == -1) break; switch (c) { case 0: break; case 'h': opts->help = true; break; case 's': opts->sleep_time = atoi(optarg); break; case 'u': opts->universe = atoi(optarg); break; case '?': break; default: break; } } } /* * Display the help message */ void DisplayHelpAndExit(char arg[]) { cout << "Usage: " << arg << " --dmx <dmx_data> --universe <universe_id>\n" "\n" "Send DMX512 data to OLA. If dmx data isn't provided we read from stdin.\n" "\n" " -h, --help Display this help message and exit.\n" " -s, --sleep <time_in_uS> Time to sleep between frames.\n" " -u, --universe <universe_id> Id of universe to send data for.\n" << endl; exit(1); } /* * Main */ int main(int argc, char *argv[]) { ola::InitLogging(ola::OLA_LOG_WARN, ola::OLA_LOG_STDERR); StreamingClient ola_client; options opts; ParseOptions(argc, argv, &opts); if (opts.help) DisplayHelpAndExit(argv[0]); if (!ola_client.Setup()) { OLA_FATAL << "Setup failed"; exit(1); } while (1) { usleep(opts.sleep_time); ola::DmxBuffer buffer; buffer.Blackout(); if (!ola_client.SendDmx(opts.universe, buffer)) { cout << "Send DMX failed" << endl; return false; } } return 0; } <commit_msg>* Switch ola-throughput to use the flags module<commit_after>/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * ola-throughput.cpp * Send a bunch of frames quickly to load test the server. * Copyright (C) 2005-2010 Simon Newton */ #include <errno.h> #include <stdlib.h> #include <ola/base/Flags.h> #include <ola/base/Init.h> #include <ola/DmxBuffer.h> #include <ola/Logging.h> #include <ola/StreamingClient.h> #include <ola/StringUtils.h> #include <iostream> #include <string> using std::cout; using std::endl; using std::string; using ola::StreamingClient; DEFINE_s_uint32(universe, u, 1, "The universe to send data on"); DEFINE_s_uint32(sleep, s, 40000, "Time between DMX updates in micro-seconds"); /* * Main */ int main(int argc, char *argv[]) { ola::AppInit(argc, argv); ola::SetHelpString("[options]", "Send DMX512 data to OLA."); ola::ParseFlags(&argc, argv); ola::InitLoggingFromFlags(); StreamingClient ola_client; if (!ola_client.Setup()) { OLA_FATAL << "Setup failed"; exit(1); } ola::DmxBuffer buffer; buffer.Blackout(); while (1) { usleep(FLAGS_sleep); if (!ola_client.SendDmx(FLAGS_universe, buffer)) { cout << "Send DMX failed" << endl; return false; } } return 0; } <|endoftext|>
<commit_before>#include <QApplication> #include <QTranslator> #include <QLocale> #include <QDebug> #include <QTimer> #include <QDir> #include "qlcconfig.h" #include "launcher.h" void loadTranslation(const QString& locale, QApplication& app) { QString file(QString("launcher_%1").arg(locale)); QString path = QLCFile::systemDirectory(TRANSLATIONDIR).path(); QTranslator* translator = new QTranslator(&app); if (translator->load(file, path) == true) { qDebug() << "Using translation for" << locale; app.installTranslator(translator); } else { qDebug() << "Unable to find translation for" << locale << "in" << path; } } int main(int argc, char** argv) { QApplication app(argc, argv); /* Load plugins from within the bundle ONLY */ QDir dir(QApplication::applicationDirPath()); dir.cdUp(); dir.cd("PlugIns"); QApplication::setLibraryPaths(QStringList(dir.absolutePath())); loadTranslation(QLocale::system().name(), app); Launcher launcher; app.installEventFilter(&launcher); // If launcher is started by the system after user has activated // either a .qxf or .qxw file, we don't need to show the dialog // at all. Since this "mime-open" comes as an event, we won't know // about it until app.exec() has been called. So, give some grace // time before actually showing the launcher dialog, in case the // event arrives and we can destroy the dialog before actually // showing it. QTimer::singleShot(100, &launcher, SLOT(show())); return app.exec(); } <commit_msg>Revert loader/main.cpp change not building on OSX<commit_after>#include <QApplication> #include <QTranslator> #include <QLocale> #include <QDebug> #include <QTimer> #include <QDir> #include "qlcconfig.h" #include "launcher.h" void loadTranslation(const QString& locale, QApplication& app) { QString file(QString("launcher_%1").arg(locale)); #if defined(__APPLE__) || defined(Q_OS_MAC) QString path(QString("%1/../%2").arg(QApplication::applicationDirPath()) .arg(TRANSLATIONDIR)); #else QString path(TRANSLATIONDIR); #endif QTranslator* translator = new QTranslator(&app); if (translator->load(file, path) == true) { qDebug() << "Using translation for" << locale; app.installTranslator(translator); } else { qDebug() << "Unable to find translation for" << locale << "in" << path; } } int main(int argc, char** argv) { QApplication app(argc, argv); /* Load plugins from within the bundle ONLY */ QDir dir(QApplication::applicationDirPath()); dir.cdUp(); dir.cd("PlugIns"); QApplication::setLibraryPaths(QStringList(dir.absolutePath())); loadTranslation(QLocale::system().name(), app); Launcher launcher; app.installEventFilter(&launcher); // If launcher is started by the system after user has activated // either a .qxf or .qxw file, we don't need to show the dialog // at all. Since this "mime-open" comes as an event, we won't know // about it until app.exec() has been called. So, give some grace // time before actually showing the launcher dialog, in case the // event arrives and we can destroy the dialog before actually // showing it. QTimer::singleShot(100, &launcher, SLOT(show())); return app.exec(); } <|endoftext|>
<commit_before>#include "argumentlist.h" #include "epolleventdispatcher.h" #include "itransceiverclient.h" #include "localsocket.h" #include "message.h" #include "transceiver.h" #include <iostream> using namespace std; void fillHelloMessage(Message *hello) { hello->setType(Message::MethodCallMessage); hello->setDestination(string("org.freedesktop.DBus")); hello->setInterface(string("org.freedesktop.DBus")); hello->setPath(string("/org/freedesktop/DBus")); hello->setMethod(string("Hello")); } class ReplyPrinter : public ITransceiverClient { // reimplemented from ITransceiverClient virtual void messageReceived(Message *m); }; void ReplyPrinter::messageReceived(Message *m) { cout << "\nReceived:\n" << m->prettyPrint(); delete m; } int main(int argc, char *argv[]) { EpollEventDispatcher dispatcher; Transceiver transceiver(&dispatcher); ReplyPrinter receiver; transceiver.setClient(&receiver); { Message hello(1); fillHelloMessage(&hello); cout << "Sending:\n" << hello.prettyPrint() << '\n'; transceiver.sendAsync(&hello); Message spyEnable(2); spyEnable.setType(Message::MethodCallMessage); spyEnable.setDestination(string("org.freedesktop.DBus")); spyEnable.setInterface(string("org.freedesktop.DBus")); spyEnable.setPath(string("/org/freedesktop/DBus")); spyEnable.setMethod(string("AddMatch")); ArgumentList argList; ArgumentList::WriteCursor writer = argList.beginWrite(); writer.writeString(cstring("eavesdrop=true,type='method_call'")); writer.finish(); spyEnable.setArgumentList(argList); transceiver.sendAsync(&spyEnable); while (true) { dispatcher.poll(); } } return 0; } <commit_msg>Eavesdrop on *all* message types.<commit_after>#include "argumentlist.h" #include "epolleventdispatcher.h" #include "itransceiverclient.h" #include "localsocket.h" #include "message.h" #include "transceiver.h" #include <iostream> #include <string> using namespace std; void fillHelloMessage(Message *hello) { hello->setType(Message::MethodCallMessage); hello->setDestination(string("org.freedesktop.DBus")); hello->setInterface(string("org.freedesktop.DBus")); hello->setPath(string("/org/freedesktop/DBus")); hello->setMethod(string("Hello")); } void fillEavesdropMessage(Message *spyEnable, const char *messageType) { spyEnable->setType(Message::MethodCallMessage); spyEnable->setDestination(string("org.freedesktop.DBus")); spyEnable->setInterface(string("org.freedesktop.DBus")); spyEnable->setPath(string("/org/freedesktop/DBus")); spyEnable->setMethod(string("AddMatch")); ArgumentList argList; ArgumentList::WriteCursor writer = argList.beginWrite(); std::string str = "eavesdrop=true,type="; str += messageType; writer.writeString(cstring(str.c_str())); writer.finish(); spyEnable->setArgumentList(argList); } class ReplyPrinter : public ITransceiverClient { // reimplemented from ITransceiverClient virtual void messageReceived(Message *m); }; void ReplyPrinter::messageReceived(Message *m) { cout << '\n' << m->prettyPrint(); delete m; } int main(int argc, char *argv[]) { EpollEventDispatcher dispatcher; Transceiver transceiver(&dispatcher); int serial = 1; ReplyPrinter receiver; transceiver.setClient(&receiver); { Message *hello = new Message(serial++); fillHelloMessage(hello); transceiver.sendAsync(hello); static const int messageTypeCount = 4; const char *messageType[messageTypeCount] = { "signal", "method_call", "method_return", "error" }; for (int i = 0; i < messageTypeCount; i++) { Message *spyEnable = new Message(serial++); fillEavesdropMessage(spyEnable, messageType[i]); transceiver.sendAsync(spyEnable); } } while (true) { dispatcher.poll(); } return 0; } <|endoftext|>
<commit_before>#include "engine.h" #include "random.h" #include "gameEntity.h" #include "Updatable.h" #include "collisionable.h" #ifdef DEBUG #include <typeinfo> int DEBUG_PobjCount; PObject* DEBUG_PobjListStart; #endif #ifdef ENABLE_CRASH_LOGGER #ifdef __WIN32__ //Exception handler for mingw, from https://github.com/jrfonseca/drmingw #include <exchndl.h> #endif//__WIN32__ #endif//ENABLE_CRASH_LOGGER Engine* engine; Engine::Engine() { engine = this; #ifdef ENABLE_CRASH_LOGGER #ifdef __WIN32__ ExcHndlInit(); #endif//__WIN32__ #endif//ENABLE_CRASH_LOGGER initRandom(); windowManager = nullptr; CollisionManager::initialize(); InputHandler::initialize(); gameSpeed = 1.0; running = true; elapsedTime = 0.0; soundManager = new SoundManager(); } Engine::~Engine() { if (windowManager) windowManager->close(); delete soundManager; soundManager = nullptr; } void Engine::registerObject(string name, P<PObject> obj) { objectMap[name] = obj; } P<PObject> Engine::getObject(string name) { if (!objectMap[name]) return NULL; return objectMap[name]; } void Engine::runMainLoop() { windowManager = dynamic_cast<WindowManager*>(*getObject("windowManager")); if (!windowManager) { sf::Clock frameTimeClock; while(running) { float delta = frameTimeClock.getElapsedTime().asSeconds(); frameTimeClock.restart(); if (delta > 0.5) delta = 0.5; if (delta < 0.001) delta = 0.001; delta *= gameSpeed; entityList.update(); foreach(Updatable, u, updatableList) u->update(delta); elapsedTime += delta; CollisionManager::handleCollisions(delta); ScriptObject::clearDestroyedObjects(); soundManager->updateTick(); sf::sleep(sf::seconds(1.0/60.0 - delta)); //if (elapsedTime > 2.0) // break; } }else{ sf::Clock frameTimeClock; #ifdef DEBUG sf::Clock debugOutputClock; #endif last_key_press = sf::Keyboard::Unknown; while(running && windowManager->window.isOpen()) { InputHandler::mouse_wheel_delta = 0; // Handle events sf::Event event; while (windowManager->window.pollEvent(event)) { handleEvent(event); } if (last_key_press != sf::Keyboard::Unknown) { InputHandler::fireKeyEvent(last_key_press, -1); last_key_press = sf::Keyboard::Unknown; } #ifdef DEBUG if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape) && windowManager->hasFocus()) running = false; if (debugOutputClock.getElapsedTime().asSeconds() > 1.0) { printf("Object count: %4d %4d %4d\n", DEBUG_PobjCount, updatableList.size(), entityList.size()); debugOutputClock.restart(); } #endif float delta = frameTimeClock.restart().asSeconds(); if (delta > 0.5) delta = 0.5; if (delta < 0.001) delta = 0.001; delta *= gameSpeed; #ifdef DEBUG if (sf::Keyboard::isKeyPressed(sf::Keyboard::Tab)) delta /= 5.0; if (sf::Keyboard::isKeyPressed(sf::Keyboard::Tilde)) delta *= 5.0; #endif EngineTiming engine_timing; sf::Clock engine_timing_clock; InputHandler::update(); entityList.update(); foreach(Updatable, u, updatableList) u->update(delta); elapsedTime += delta; engine_timing.update = engine_timing_clock.restart().asSeconds(); CollisionManager::handleCollisions(delta); engine_timing.collision = engine_timing_clock.restart().asSeconds(); ScriptObject::clearDestroyedObjects(); soundManager->updateTick(); // Clear the window windowManager->render(); engine_timing.render = engine_timing_clock.restart().asSeconds(); engine_timing.server_update = 0.0f; if (game_server) engine_timing.server_update = game_server->getUpdateTime(); last_engine_timing = engine_timing; } soundManager->stopMusic(); } } void Engine::handleEvent(sf::Event& event) { // Window closed: exit if ((event.type == sf::Event::Closed)) running = false; if (event.type == sf::Event::GainedFocus) windowManager->windowHasFocus = true; if (event.type == sf::Event::LostFocus) windowManager->windowHasFocus = false; #ifdef DEBUG if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::L)) { int n = 0; printf("---------------------\n"); for(PObject* obj = DEBUG_PobjListStart; obj; obj = obj->DEBUG_PobjListNext) printf("%c%4d: %4d: %s\n", obj->isDestroyed() ? '>' : ' ', n++, obj->getRefCount(), typeid(*obj).name()); printf("---------------------\n"); } #endif if (event.type == sf::Event::KeyPressed) { InputHandler::keyboard_button_down[event.key.code] = true; last_key_press = event.key.code; } if (event.type == sf::Event::KeyReleased) InputHandler::keyboard_button_down[event.key.code] = false; if (event.type == sf::Event::TextEntered && event.text.unicode > 31 && event.text.unicode < 128) { if (last_key_press != sf::Keyboard::Unknown) { InputHandler::fireKeyEvent(last_key_press, event.text.unicode); last_key_press = sf::Keyboard::Unknown; } } if (event.type == sf::Event::MouseWheelMoved) InputHandler::mouse_wheel_delta += event.mouseWheel.delta; if (event.type == sf::Event::MouseButtonPressed) InputHandler::mouse_button_down[event.mouseButton.button] = true; if (event.type == sf::Event::MouseButtonReleased) InputHandler::mouse_button_down[event.mouseButton.button] = false; if (event.type == sf::Event::Resized) windowManager->setupView(); #ifdef __ANDROID__ //Focus lost and focus gained events are used when the application window is created and destroyed. if (event.type == sf::Event::LostFocus) running = false; //The MouseEntered and MouseLeft events are received when the activity needs to pause or resume. if (event.type == sf::Event::MouseLeft) { //Pause is when a small popup is on top of the window. So keep running. while(windowManager->window.isOpen() && windowManager->window.waitEvent(event)) { if (event.type != sf::Event::MouseLeft) handleEvent(event); if (event.type == sf::Event::MouseEntered) break; } } #endif//__ANDROID__ } void Engine::setGameSpeed(float speed) { gameSpeed = speed; } float Engine::getGameSpeed() { return gameSpeed; } float Engine::getElapsedTime() { return elapsedTime; } Engine::EngineTiming Engine::getEngineTiming() { return last_engine_timing; } void Engine::shutdown() { running = false; } <commit_msg>retab. fix unknown keystroke underflow<commit_after>#include "engine.h" #include "random.h" #include "gameEntity.h" #include "Updatable.h" #include "collisionable.h" #ifdef DEBUG #include <typeinfo> int DEBUG_PobjCount; PObject* DEBUG_PobjListStart; #endif #ifdef ENABLE_CRASH_LOGGER #ifdef __WIN32__ //Exception handler for mingw, from https://github.com/jrfonseca/drmingw #include <exchndl.h> #endif//__WIN32__ #endif//ENABLE_CRASH_LOGGER Engine* engine; Engine::Engine() { engine = this; #ifdef ENABLE_CRASH_LOGGER #ifdef __WIN32__ ExcHndlInit(); #endif//__WIN32__ #endif//ENABLE_CRASH_LOGGER initRandom(); windowManager = nullptr; CollisionManager::initialize(); InputHandler::initialize(); gameSpeed = 1.0; running = true; elapsedTime = 0.0; soundManager = new SoundManager(); } Engine::~Engine() { if (windowManager) windowManager->close(); delete soundManager; soundManager = nullptr; } void Engine::registerObject(string name, P<PObject> obj) { objectMap[name] = obj; } P<PObject> Engine::getObject(string name) { if (!objectMap[name]) return NULL; return objectMap[name]; } void Engine::runMainLoop() { windowManager = dynamic_cast<WindowManager*>(*getObject("windowManager")); if (!windowManager) { sf::Clock frameTimeClock; while(running) { float delta = frameTimeClock.getElapsedTime().asSeconds(); frameTimeClock.restart(); if (delta > 0.5) delta = 0.5; if (delta < 0.001) delta = 0.001; delta *= gameSpeed; entityList.update(); foreach(Updatable, u, updatableList) u->update(delta); elapsedTime += delta; CollisionManager::handleCollisions(delta); ScriptObject::clearDestroyedObjects(); soundManager->updateTick(); sf::sleep(sf::seconds(1.0/60.0 - delta)); //if (elapsedTime > 2.0) // break; } }else{ sf::Clock frameTimeClock; #ifdef DEBUG sf::Clock debugOutputClock; #endif last_key_press = sf::Keyboard::Unknown; while(running && windowManager->window.isOpen()) { InputHandler::mouse_wheel_delta = 0; // Handle events sf::Event event; while (windowManager->window.pollEvent(event)) { handleEvent(event); } if (last_key_press != sf::Keyboard::Unknown) { InputHandler::fireKeyEvent(last_key_press, -1); last_key_press = sf::Keyboard::Unknown; } #ifdef DEBUG if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape) && windowManager->hasFocus()) running = false; if (debugOutputClock.getElapsedTime().asSeconds() > 1.0) { printf("Object count: %4d %4d %4d\n", DEBUG_PobjCount, updatableList.size(), entityList.size()); debugOutputClock.restart(); } #endif float delta = frameTimeClock.restart().asSeconds(); if (delta > 0.5) delta = 0.5; if (delta < 0.001) delta = 0.001; delta *= gameSpeed; #ifdef DEBUG if (sf::Keyboard::isKeyPressed(sf::Keyboard::Tab)) delta /= 5.0; if (sf::Keyboard::isKeyPressed(sf::Keyboard::Tilde)) delta *= 5.0; #endif EngineTiming engine_timing; sf::Clock engine_timing_clock; InputHandler::update(); entityList.update(); foreach(Updatable, u, updatableList) u->update(delta); elapsedTime += delta; engine_timing.update = engine_timing_clock.restart().asSeconds(); CollisionManager::handleCollisions(delta); engine_timing.collision = engine_timing_clock.restart().asSeconds(); ScriptObject::clearDestroyedObjects(); soundManager->updateTick(); // Clear the window windowManager->render(); engine_timing.render = engine_timing_clock.restart().asSeconds(); engine_timing.server_update = 0.0f; if (game_server) engine_timing.server_update = game_server->getUpdateTime(); last_engine_timing = engine_timing; } soundManager->stopMusic(); } } void Engine::handleEvent(sf::Event& event) { // Window closed: exit if ((event.type == sf::Event::Closed)) running = false; if (event.type == sf::Event::GainedFocus) windowManager->windowHasFocus = true; if (event.type == sf::Event::LostFocus) windowManager->windowHasFocus = false; #ifdef DEBUG if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::L)) { int n = 0; printf("---------------------\n"); for(PObject* obj = DEBUG_PobjListStart; obj; obj = obj->DEBUG_PobjListNext) printf("%c%4d: %4d: %s\n", obj->isDestroyed() ? '>' : ' ', n++, obj->getRefCount(), typeid(*obj).name()); printf("---------------------\n"); } #endif if (event.type == sf::Event::KeyPressed) { if (event.key.code != sf::Keyboard::Unknown) InputHandler::keyboard_button_down[event.key.code] = true; #ifdef DEBUG else printf("Unknown key code pressed"); #endif last_key_press = event.key.code; } if (event.type == sf::Event::KeyReleased) { if (event.key.code != sf::Keyboard::Unknown) InputHandler::keyboard_button_down[event.key.code] = false; #ifdef DEBUG else printf("Unknown key code released"); #endif } if (event.type == sf::Event::TextEntered && event.text.unicode > 31 && event.text.unicode < 128) { if (last_key_press != sf::Keyboard::Unknown) { InputHandler::fireKeyEvent(last_key_press, event.text.unicode); last_key_press = sf::Keyboard::Unknown; } } if (event.type == sf::Event::MouseWheelMoved) InputHandler::mouse_wheel_delta += event.mouseWheel.delta; if (event.type == sf::Event::MouseButtonPressed) InputHandler::mouse_button_down[event.mouseButton.button] = true; if (event.type == sf::Event::MouseButtonReleased) InputHandler::mouse_button_down[event.mouseButton.button] = false; if (event.type == sf::Event::Resized) windowManager->setupView(); #ifdef __ANDROID__ //Focus lost and focus gained events are used when the application window is created and destroyed. if (event.type == sf::Event::LostFocus) running = false; //The MouseEntered and MouseLeft events are received when the activity needs to pause or resume. if (event.type == sf::Event::MouseLeft) { //Pause is when a small popup is on top of the window. So keep running. while(windowManager->window.isOpen() && windowManager->window.waitEvent(event)) { if (event.type != sf::Event::MouseLeft) handleEvent(event); if (event.type == sf::Event::MouseEntered) break; } } #endif//__ANDROID__ } void Engine::setGameSpeed(float speed) { gameSpeed = speed; } float Engine::getGameSpeed() { return gameSpeed; } float Engine::getElapsedTime() { return elapsedTime; } Engine::EngineTiming Engine::getEngineTiming() { return last_engine_timing; } void Engine::shutdown() { running = false; } <|endoftext|>
<commit_before>#include <iostream> #include "N-Queens.h" #include "StringMatching.h" int main(int _Argc, char ** _Argv) { NQueens queen(10); std::string pattern, text; std::cout << "Inserire stringa testo: "; std::cin >> text; std::cout << "Inserire stringa pattern: "; std::cin >> pattern; std::cout << "Occorrenza trovata in posizione : " << CompareStrings(pattern, text) << std::endl; if (queen.Start()) queen.Print(); else std::cout << "Configurazione non valida "; std::cout << std::endl; std::cout << "Premere un tasto per continuare "; std::cin.sync(); std::cin.ignore(); return 0; }<commit_msg>Testing new stuff.<commit_after>#include <iostream> #include "N-Queens.h" #include "StringMatching.h" #include "Knapsack.h" int main(int _Argc, char ** _Argv) { Knapsack knsack(3); NQueens queen(10); std::string pattern, text; knsack.AddItem(*(new IData(6, 2))); knsack.AddItem(*(new IData(4, 1))); knsack.AddItem(*(new IData(7, 3))); knsack.KnapsackGreedy(5); std::cout << "//STRING MATCHING//" << std::endl << std::endl; std::cout << "Inserire stringa testo: "; std::cin >> text; std::cout << "Inserire stringa pattern: "; std::cin >> pattern; std::cout << "Occorrenza trovata in posizione : " << CompareStrings(pattern, text) << std::endl << std::endl; std::cout << "//N-QUEEN RESOLVER//" << std::endl << std::endl; if (queen.Start()) queen.Print(); else std::cout << "Configurazione non valida "; std::cout << std::endl; std::cout << "Premere un tasto per continuare "; std::cin.sync(); std::cin.ignore(); return 0; }<|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice 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 <algorithm> #include <vector> #include <com/sun/star/frame/Desktop.hpp> #include <comphelper/processfactory.hxx> #include <comphelper/documentinfo.hxx> #include <comphelper/mediadescriptor.hxx> #include <rtl/string.hxx> #include <rtl/strbuf.hxx> #include "Communicator.hxx" #include "Listener.hxx" #include "Receiver.hxx" #include "RemoteServer.hxx" using namespace sd; using namespace std; using namespace com::sun::star; using namespace osl; Communicator::Communicator( IBluetoothSocket *pSocket ): Thread( "CommunicatorThread" ), mpSocket( pSocket ), pTransmitter( 0 ), mListener( 0 ) { } Communicator::~Communicator() { } /// Close the underlying socket from another thread to force /// an early exit / termination void Communicator::forceClose() { if( mpSocket ) mpSocket->close(); } // Run as a thread void Communicator::execute() { pTransmitter = new Transmitter( mpSocket ); pTransmitter->create(); pTransmitter->addMessage( "LO_SERVER_SERVER_PAIRED\n\n", Transmitter::PRIORITY_HIGH ); Receiver aReceiver( pTransmitter ); try { uno::Reference< frame::XDesktop2 > xFramesSupplier = frame::Desktop::create( ::comphelper::getProcessComponentContext() ); uno::Reference< frame::XFrame > xFrame ( xFramesSupplier->getActiveFrame(), uno::UNO_QUERY ); uno::Reference<presentation::XPresentationSupplier> xPS; if( xFrame.is() ) xPS = uno::Reference<presentation::XPresentationSupplier>( xFrame->getController()->getModel(), uno::UNO_QUERY ); uno::Reference<presentation::XPresentation2> xPresentation; if( xPS.is() ) xPresentation = uno::Reference<presentation::XPresentation2>( xPS->getPresentation(), uno::UNO_QUERY ); if ( xPresentation.is() && xPresentation->isRunning() ) { presentationStarted( xPresentation->getController() ); } else { pTransmitter->addMessage( "slideshow_finished\n\n", Transmitter::PRIORITY_HIGH ); } OStringBuffer aBuffer; aBuffer.append( "slideshow_info\n" ) .append( OUStringToOString( ::comphelper::DocumentInfo::getDocumentTitle( xFrame->getController()->getModel() ), RTL_TEXTENCODING_UTF8 ) ) .append("\n\n"); pTransmitter->addMessage( aBuffer.makeStringAndClear(), Transmitter::PRIORITY_LOW ); } catch (uno::RuntimeException &) { } sal_uInt64 aRet; vector<OString> aCommand; while ( true ) { OString aLine; aRet = mpSocket->readLine( aLine ); if ( aRet == 0 ) { break; // I.e. transmission finished. } if ( aLine.getLength() ) { aCommand.push_back( aLine ); } else { aReceiver.pushCommand( aCommand ); aCommand.clear(); } } SAL_INFO ("sdremote", "Exiting transmission loop\n"); disposeListener(); pTransmitter->notifyFinished(); pTransmitter->join(); pTransmitter = NULL; delete mpSocket; RemoteServer::removeCommunicator( this ); } void Communicator::informListenerDestroyed() { if ( pTransmitter ) pTransmitter->addMessage( "slideshow_finished\n\n", Transmitter::PRIORITY_HIGH ); mListener.clear(); } void Communicator::presentationStarted( const css::uno::Reference< css::presentation::XSlideShowController > &rController ) { if ( pTransmitter ) { mListener = rtl::Reference<Listener>( new Listener( this, pTransmitter ) ); mListener->init( rController ); } } void Communicator::disposeListener() { if ( mListener.is() ) { mListener->disposing(); mListener = NULL; } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Add sending server information after pairing.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice 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 <algorithm> #include <vector> #include <com/sun/star/frame/Desktop.hpp> #include <comphelper/processfactory.hxx> #include <comphelper/documentinfo.hxx> #include <comphelper/mediadescriptor.hxx> #include <config_version.h> #include <rtl/string.hxx> #include <rtl/strbuf.hxx> #include "Communicator.hxx" #include "Listener.hxx" #include "Receiver.hxx" #include "RemoteServer.hxx" using namespace sd; using namespace std; using namespace com::sun::star; using namespace osl; Communicator::Communicator( IBluetoothSocket *pSocket ): Thread( "CommunicatorThread" ), mpSocket( pSocket ), pTransmitter( 0 ), mListener( 0 ) { } Communicator::~Communicator() { } /// Close the underlying socket from another thread to force /// an early exit / termination void Communicator::forceClose() { if( mpSocket ) mpSocket->close(); } // Run as a thread void Communicator::execute() { pTransmitter = new Transmitter( mpSocket ); pTransmitter->create(); pTransmitter->addMessage( "LO_SERVER_SERVER_PAIRED\n\n", Transmitter::PRIORITY_HIGH ); OStringBuffer aServerInformationBuffer; aServerInformationBuffer .append( "LO_SERVER_INFO\n" ) .append( OUStringToOString( OUString::createFromAscii( LIBO_VERSION_DOTTED ), RTL_TEXTENCODING_UTF8 ) ) .append("\n\n"); pTransmitter->addMessage( aServerInformationBuffer.makeStringAndClear(), Transmitter::PRIORITY_HIGH ); Receiver aReceiver( pTransmitter ); try { uno::Reference< frame::XDesktop2 > xFramesSupplier = frame::Desktop::create( ::comphelper::getProcessComponentContext() ); uno::Reference< frame::XFrame > xFrame ( xFramesSupplier->getActiveFrame(), uno::UNO_QUERY ); uno::Reference<presentation::XPresentationSupplier> xPS; if( xFrame.is() ) xPS = uno::Reference<presentation::XPresentationSupplier>( xFrame->getController()->getModel(), uno::UNO_QUERY ); uno::Reference<presentation::XPresentation2> xPresentation; if( xPS.is() ) xPresentation = uno::Reference<presentation::XPresentation2>( xPS->getPresentation(), uno::UNO_QUERY ); if ( xPresentation.is() && xPresentation->isRunning() ) { presentationStarted( xPresentation->getController() ); } else { pTransmitter->addMessage( "slideshow_finished\n\n", Transmitter::PRIORITY_HIGH ); } OStringBuffer aBuffer; aBuffer .append( "slideshow_info\n" ) .append( OUStringToOString( ::comphelper::DocumentInfo::getDocumentTitle( xFrame->getController()->getModel() ), RTL_TEXTENCODING_UTF8 ) ) .append("\n\n"); pTransmitter->addMessage( aBuffer.makeStringAndClear(), Transmitter::PRIORITY_LOW ); } catch (uno::RuntimeException &) { } sal_uInt64 aRet; vector<OString> aCommand; while ( true ) { OString aLine; aRet = mpSocket->readLine( aLine ); if ( aRet == 0 ) { break; // I.e. transmission finished. } if ( aLine.getLength() ) { aCommand.push_back( aLine ); } else { aReceiver.pushCommand( aCommand ); aCommand.clear(); } } SAL_INFO ("sdremote", "Exiting transmission loop\n"); disposeListener(); pTransmitter->notifyFinished(); pTransmitter->join(); pTransmitter = NULL; delete mpSocket; RemoteServer::removeCommunicator( this ); } void Communicator::informListenerDestroyed() { if ( pTransmitter ) pTransmitter->addMessage( "slideshow_finished\n\n", Transmitter::PRIORITY_HIGH ); mListener.clear(); } void Communicator::presentationStarted( const css::uno::Reference< css::presentation::XSlideShowController > &rController ) { if ( pTransmitter ) { mListener = rtl::Reference<Listener>( new Listener( this, pTransmitter ) ); mListener->init( rController ); } } void Communicator::disposeListener() { if ( mListener.is() ) { mListener->disposing(); mListener = NULL; } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/* * Copyright (C) 2015-present ScyllaDB */ /* * SPDX-License-Identifier: AGPL-3.0-or-later */ #pragma once #include <boost/circular_buffer.hpp> #include "latency.hh" #include <cmath> #include <seastar/core/timer.hh> #include <iosfwd> #include "seastarx.hh" namespace utils { /** * An exponentially-weighted moving average. */ class moving_average { double _alpha = 0; bool _initialized = false; latency_counter::duration _tick_interval; uint64_t _count = 0; double _rate = 0; public: moving_average(latency_counter::duration interval, latency_counter::duration tick_interval) : _tick_interval(tick_interval) { _alpha = 1 - std::exp(-std::chrono::duration_cast<std::chrono::seconds>(tick_interval).count()/ static_cast<double>(std::chrono::duration_cast<std::chrono::seconds>(interval).count())); } void add(uint64_t val = 1) { _count += val; } void update() { double instant_rate = _count / static_cast<double>(std::chrono::duration_cast<std::chrono::seconds>(_tick_interval).count()); if (_initialized) { _rate += (_alpha * (instant_rate - _rate)); } else { _rate = instant_rate; _initialized = true; } _count = 0; } bool is_initilized() const { return _initialized; } double rate() const { if (is_initilized()) { return _rate; } return 0; } }; template <typename Unit> class basic_ihistogram { public: using duration_unit = Unit; // count holds all the events int64_t count; // total holds only the events we sample int64_t total; int64_t min; int64_t max; int64_t sum; int64_t started; double mean; double variance; int64_t sample_mask; boost::circular_buffer<int64_t> sample; basic_ihistogram(size_t size = 1024, int64_t _sample_mask = 0x80) : count(0), total(0), min(0), max(0), sum(0), started(0), mean(0), variance(0), sample_mask(_sample_mask), sample( size) { } template <typename Rep, typename Ratio> void mark(std::chrono::duration<Rep, Ratio> dur) { auto value = std::chrono::duration_cast<Unit>(dur).count(); if (total == 0 || value < min) { min = value; } if (total == 0 || value > max) { max = value; } if (total == 0) { mean = value; variance = 0; } else { double old_m = mean; double old_s = variance; mean = ((double)(sum + value)) / (total + 1); variance = old_s + ((value - old_m) * (value - mean)); } sum += value; total++; count++; sample.push_back(value); } void mark(latency_counter& lc) { if (lc.is_start()) { mark(lc.stop().latency()); } else { count++; } } /** * Return true if the current event should be sample. * In the typical case, there is no need to use this method * Call set_latency, that would start a latency object if needed. */ bool should_sample() const { return total == 0 || (started & sample_mask); } /** * Set the latency according to the sample rate. */ basic_ihistogram& set_latency(latency_counter& lc) { if (should_sample()) { lc.start(); } started++; return *this; } /** * Allow to use the histogram as a counter * Increment the total number of events without * sampling the value. */ basic_ihistogram& inc() { count++; return *this; } int64_t pending() const { return started - count; } inline double pow2(double a) { return a * a; } basic_ihistogram& operator +=(const basic_ihistogram& o) { if (count == 0) { *this = o; } else if (o.count > 0) { if (min > o.min) { min = o.min; } if (max < o.max) { max = o.max; } double ncount = count + o.count; sum += o.sum; double a = count / ncount; double b = o.count / ncount; double m = a * mean + b * o.mean; variance = (variance + pow2(m - mean)) * a + (o.variance + pow2(o.mean - mean)) * b; mean = m; count += o.count; total += o.total; for (auto i : o.sample) { sample.push_back(i); } } return *this; } int64_t estimated_sum() const { return mean * count; } template <typename U> friend basic_ihistogram<U> operator +(basic_ihistogram<U> a, const basic_ihistogram<U>& b); }; template <typename Unit> inline basic_ihistogram<Unit> operator +(basic_ihistogram<Unit> a, const basic_ihistogram<Unit>& b) { a += b; return a; } using ihistogram = basic_ihistogram<std::chrono::microseconds>; struct rate_moving_average { uint64_t count = 0; double rates[3] = {0}; double mean_rate = 0; rate_moving_average& operator +=(const rate_moving_average& o) { count += o.count; mean_rate += o.mean_rate; for (int i=0; i<3; i++) { rates[i] += o.rates[i]; } return *this; } friend rate_moving_average operator+ (rate_moving_average a, const rate_moving_average& b); }; inline rate_moving_average operator+ (rate_moving_average a, const rate_moving_average& b) { a += b; return a; } class timed_rate_moving_average { static constexpr latency_counter::duration tick_interval() { return std::chrono::seconds(10); } moving_average rates[3] = {{std::chrono::minutes(1), tick_interval()}, {std::chrono::minutes(5), tick_interval()}, {std::chrono::minutes(15), tick_interval()}}; latency_counter::time_point start_time; timer<> _timer; public: // _count is public so the collectd will be able to use it. // for all other cases use the count() method uint64_t _count = 0; timed_rate_moving_average() : start_time(latency_counter::now()), _timer([this] { update(); }) { _timer.arm_periodic(tick_interval()); } void mark(uint64_t n = 1) { _count += n; for (int i = 0; i < 3; i++) { rates[i].add(n); } } rate_moving_average rate() const { rate_moving_average res; double elapsed = std::chrono::duration_cast<std::chrono::seconds>(latency_counter::now() - start_time).count(); // We condition also in elapsed because it can happen that the call // for the rate calculation was performed too early and will not yield // meaningful results (i.e mean_rate is infinity) so the best thing is // to return 0 as it best reflects the state. if ((_count > 0) && (elapsed >= 1.0)) [[likely]] { res.mean_rate = (_count / elapsed); } else { res.mean_rate = 0; } res.count = _count; for (int i = 0; i < 3; i++) { res.rates[i] = rates[i].rate(); } return res; } void update() { for (int i = 0; i < 3; i++) { rates[i].update(); } } uint64_t count() const { return _count; } }; struct rate_moving_average_and_histogram { ihistogram hist; rate_moving_average rate; rate_moving_average_and_histogram& operator +=(const rate_moving_average_and_histogram& o) { hist += o.hist; rate += o.rate; return *this; } friend rate_moving_average_and_histogram operator +(rate_moving_average_and_histogram a, const rate_moving_average_and_histogram& b); }; inline rate_moving_average_and_histogram operator +(rate_moving_average_and_histogram a, const rate_moving_average_and_histogram& b) { a += b; return a; } /** * A timer metric which aggregates timing durations and provides duration statistics, plus * throughput statistics via meter */ class timed_rate_moving_average_and_histogram { public: ihistogram hist; timed_rate_moving_average met; timed_rate_moving_average_and_histogram() = default; timed_rate_moving_average_and_histogram(timed_rate_moving_average_and_histogram&&) = default; timed_rate_moving_average_and_histogram(const timed_rate_moving_average_and_histogram&) = default; timed_rate_moving_average_and_histogram(size_t size, int64_t _sample_mask = 0x80) : hist(size, _sample_mask) {} timed_rate_moving_average_and_histogram& operator=(const timed_rate_moving_average_and_histogram&) = default; template <typename Rep, typename Ratio> void mark(std::chrono::duration<Rep, Ratio> dur) { if (std::chrono::duration_cast<ihistogram::duration_unit>(dur).count() >= 0) { hist.mark(dur); met.mark(); } } void mark(latency_counter& lc) { hist.mark(lc); met.mark(); } void set_latency(latency_counter& lc) { hist.set_latency(lc); } rate_moving_average_and_histogram rate() const { rate_moving_average_and_histogram res; res.hist = hist; res.rate = met.rate(); return res; } }; } <commit_msg>utils/histogram.hh: should_sample should use a bitmask<commit_after>/* * Copyright (C) 2015-present ScyllaDB */ /* * SPDX-License-Identifier: AGPL-3.0-or-later */ #pragma once #include <boost/circular_buffer.hpp> #include "latency.hh" #include <cmath> #include <seastar/core/timer.hh> #include <iosfwd> #include "seastarx.hh" namespace utils { /** * An exponentially-weighted moving average. */ class moving_average { double _alpha = 0; bool _initialized = false; latency_counter::duration _tick_interval; uint64_t _count = 0; double _rate = 0; public: moving_average(latency_counter::duration interval, latency_counter::duration tick_interval) : _tick_interval(tick_interval) { _alpha = 1 - std::exp(-std::chrono::duration_cast<std::chrono::seconds>(tick_interval).count()/ static_cast<double>(std::chrono::duration_cast<std::chrono::seconds>(interval).count())); } void add(uint64_t val = 1) { _count += val; } void update() { double instant_rate = _count / static_cast<double>(std::chrono::duration_cast<std::chrono::seconds>(_tick_interval).count()); if (_initialized) { _rate += (_alpha * (instant_rate - _rate)); } else { _rate = instant_rate; _initialized = true; } _count = 0; } bool is_initilized() const { return _initialized; } double rate() const { if (is_initilized()) { return _rate; } return 0; } }; template <typename Unit> class basic_ihistogram { public: using duration_unit = Unit; // count holds all the events int64_t count; // total holds only the events we sample int64_t total; int64_t min; int64_t max; int64_t sum; int64_t started; double mean; double variance; int64_t sample_mask; boost::circular_buffer<int64_t> sample; basic_ihistogram(size_t size = 1024, int64_t _sample_mask = 0x80) : count(0), total(0), min(0), max(0), sum(0), started(0), mean(0), variance(0), sample_mask(_sample_mask), sample( size) { } template <typename Rep, typename Ratio> void mark(std::chrono::duration<Rep, Ratio> dur) { auto value = std::chrono::duration_cast<Unit>(dur).count(); if (total == 0 || value < min) { min = value; } if (total == 0 || value > max) { max = value; } if (total == 0) { mean = value; variance = 0; } else { double old_m = mean; double old_s = variance; mean = ((double)(sum + value)) / (total + 1); variance = old_s + ((value - old_m) * (value - mean)); } sum += value; total++; count++; sample.push_back(value); } void mark(latency_counter& lc) { if (lc.is_start()) { mark(lc.stop().latency()); } else { count++; } } /** * Return true if the current event should be sample. * In the typical case, there is no need to use this method * Call set_latency, that would start a latency object if needed. * * Typically, sample_mask is of the form of 2^n-1 which would * mean that we sample one of 2^n, but setting sample_mask to zero * would mean we would always sample. */ bool should_sample() const noexcept { return total == 0 || ((started & sample_mask) == sample_mask); } /** * Set the latency according to the sample rate. */ basic_ihistogram& set_latency(latency_counter& lc) { if (should_sample()) { lc.start(); } started++; return *this; } /** * Allow to use the histogram as a counter * Increment the total number of events without * sampling the value. */ basic_ihistogram& inc() { count++; return *this; } int64_t pending() const { return started - count; } inline double pow2(double a) { return a * a; } basic_ihistogram& operator +=(const basic_ihistogram& o) { if (count == 0) { *this = o; } else if (o.count > 0) { if (min > o.min) { min = o.min; } if (max < o.max) { max = o.max; } double ncount = count + o.count; sum += o.sum; double a = count / ncount; double b = o.count / ncount; double m = a * mean + b * o.mean; variance = (variance + pow2(m - mean)) * a + (o.variance + pow2(o.mean - mean)) * b; mean = m; count += o.count; total += o.total; for (auto i : o.sample) { sample.push_back(i); } } return *this; } int64_t estimated_sum() const { return mean * count; } template <typename U> friend basic_ihistogram<U> operator +(basic_ihistogram<U> a, const basic_ihistogram<U>& b); }; template <typename Unit> inline basic_ihistogram<Unit> operator +(basic_ihistogram<Unit> a, const basic_ihistogram<Unit>& b) { a += b; return a; } using ihistogram = basic_ihistogram<std::chrono::microseconds>; struct rate_moving_average { uint64_t count = 0; double rates[3] = {0}; double mean_rate = 0; rate_moving_average& operator +=(const rate_moving_average& o) { count += o.count; mean_rate += o.mean_rate; for (int i=0; i<3; i++) { rates[i] += o.rates[i]; } return *this; } friend rate_moving_average operator+ (rate_moving_average a, const rate_moving_average& b); }; inline rate_moving_average operator+ (rate_moving_average a, const rate_moving_average& b) { a += b; return a; } class timed_rate_moving_average { static constexpr latency_counter::duration tick_interval() { return std::chrono::seconds(10); } moving_average rates[3] = {{std::chrono::minutes(1), tick_interval()}, {std::chrono::minutes(5), tick_interval()}, {std::chrono::minutes(15), tick_interval()}}; latency_counter::time_point start_time; timer<> _timer; public: // _count is public so the collectd will be able to use it. // for all other cases use the count() method uint64_t _count = 0; timed_rate_moving_average() : start_time(latency_counter::now()), _timer([this] { update(); }) { _timer.arm_periodic(tick_interval()); } void mark(uint64_t n = 1) { _count += n; for (int i = 0; i < 3; i++) { rates[i].add(n); } } rate_moving_average rate() const { rate_moving_average res; double elapsed = std::chrono::duration_cast<std::chrono::seconds>(latency_counter::now() - start_time).count(); // We condition also in elapsed because it can happen that the call // for the rate calculation was performed too early and will not yield // meaningful results (i.e mean_rate is infinity) so the best thing is // to return 0 as it best reflects the state. if ((_count > 0) && (elapsed >= 1.0)) [[likely]] { res.mean_rate = (_count / elapsed); } else { res.mean_rate = 0; } res.count = _count; for (int i = 0; i < 3; i++) { res.rates[i] = rates[i].rate(); } return res; } void update() { for (int i = 0; i < 3; i++) { rates[i].update(); } } uint64_t count() const { return _count; } }; struct rate_moving_average_and_histogram { ihistogram hist; rate_moving_average rate; rate_moving_average_and_histogram& operator +=(const rate_moving_average_and_histogram& o) { hist += o.hist; rate += o.rate; return *this; } friend rate_moving_average_and_histogram operator +(rate_moving_average_and_histogram a, const rate_moving_average_and_histogram& b); }; inline rate_moving_average_and_histogram operator +(rate_moving_average_and_histogram a, const rate_moving_average_and_histogram& b) { a += b; return a; } /** * A timer metric which aggregates timing durations and provides duration statistics, plus * throughput statistics via meter */ class timed_rate_moving_average_and_histogram { public: ihistogram hist; timed_rate_moving_average met; timed_rate_moving_average_and_histogram() = default; timed_rate_moving_average_and_histogram(timed_rate_moving_average_and_histogram&&) = default; timed_rate_moving_average_and_histogram(const timed_rate_moving_average_and_histogram&) = default; timed_rate_moving_average_and_histogram(size_t size, int64_t _sample_mask = 0x80) : hist(size, _sample_mask) {} timed_rate_moving_average_and_histogram& operator=(const timed_rate_moving_average_and_histogram&) = default; template <typename Rep, typename Ratio> void mark(std::chrono::duration<Rep, Ratio> dur) { if (std::chrono::duration_cast<ihistogram::duration_unit>(dur).count() >= 0) { hist.mark(dur); met.mark(); } } void mark(latency_counter& lc) { hist.mark(lc); met.mark(); } void set_latency(latency_counter& lc) { hist.set_latency(lc); } rate_moving_average_and_histogram rate() const { rate_moving_average_and_histogram res; res.hist = hist; res.rate = met.rate(); return res; } }; } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/hwpf/fapi2/src/fapi2_utils.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,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 utils.C * @brief Implements fapi2 utilities */ #include <fapi2_attribute_service.H> #include <attribute_ids.H> #include <return_code.H> #include <plat_trace.H> #include <target.H> namespace fapi2 { ReturnCode queryChipEcAndName( const Target < fapi2::TARGET_TYPE_ALL>& i_target, fapi2::ATTR_NAME_Type& o_chipName, fapi2::ATTR_EC_Type& o_chipEc ) { ReturnCode l_rc = FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, i_target, o_chipName); if ( l_rc != FAPI2_RC_SUCCESS ) { FAPI_ERR("queryChipEcFeature: error getting chip name"); } else { l_rc = FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, i_target, o_chipEc); if ( l_rc != FAPI2_RC_SUCCESS ) { FAPI_ERR("queryChipEcFeature: error getting chip ec"); } } return l_rc; } }; <commit_msg>Modify the getFfdc routine to consider the SBE proc<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/hwpf/fapi2/src/fapi2_utils.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,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 utils.C * @brief Implements fapi2 utilities */ #include <fapi2_attribute_service.H> #include <attribute_ids.H> #include <return_code.H> #include <plat_trace.H> #include <target.H> namespace fapi2 { ReturnCode queryChipEcAndName( const Target < fapi2::TARGET_TYPE_ALL>& i_target, fapi2::ATTR_NAME_Type& o_chipName, fapi2::ATTR_EC_Type& o_chipEc ) { ReturnCode l_rc = FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, i_target, o_chipName); if ( l_rc != FAPI2_RC_SUCCESS ) { FAPI_ERR("queryChipEcFeature: error getting chip name"); } else { l_rc = FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, i_target, o_chipEc); if ( l_rc != FAPI2_RC_SUCCESS ) { FAPI_ERR("queryChipEcFeature: error getting chip ec"); } } return l_rc; } // convert sbe instance of target to a fapi position uint16_t convertSbeTargInstanceToFapiPos(fapi2::TargetType i_targType, fapi2::Target<TARGET_TYPE_PROC_CHIP>& i_proc, uint16_t i_instance) { // Compute this target's FAPI_POS value. We first take the parent's // FAPI_POS and multiply by the max number of targets of this type that // the parent's type can have. This yields the lower bound of this // target's FAPI_POS. Then we add in the relative position of this // target with respect to the parent. Typically this is done by passing // in the chip unit, in which case (such as for cores) it can be much // greater than the architecture limit ratio (there can be cores with // chip units of 0..23, but only 2 cores per ex), so to normalize we // have to take the value mod the architecture limit. Note that this // scheme only holds up because every parent also had the same type of // calculation to compute its own FAPI_POS. uint16_t max_targets = 0; uint16_t fapi_pos = INVALID_FAPI_POS; ATTR_FAPI_POS_Type l_procPosition = 0; FAPI_ATTR_GET(fapi2::ATTR_FAPI_POS, i_proc, l_procPosition); switch( i_targType ) { case TARGET_TYPE_EQ: { max_targets = MAX_EQ_PER_PROC; break; } case TARGET_TYPE_CORE: { max_targets = MAX_CORE_PER_PROC; break; } case TARGET_TYPE_EX: { max_targets = MAX_EX_PER_PROC; break; } case TARGET_TYPE_MCS: { max_targets = MAX_MCS_PER_PROC; break; } case TARGET_TYPE_MCA: { max_targets = MAX_MCA_PER_PROC; break; } case TARGET_TYPE_MC: { max_targets = MAX_MC_PER_PROC; break; } case TARGET_TYPE_MI: { max_targets = MAX_MI_PER_PROC; break; } case TARGET_TYPE_PHB: { max_targets = MAX_PHB_PER_PROC; break; } case TARGET_TYPE_MCBIST: { max_targets = MAX_MCBIST_PER_PROC; break; } case TARGET_TYPE_PERV: { max_targets = MAX_PERV_PER_PROC; break; } default: max_targets = INVALID_TARGET_COUNT; break; } if( max_targets == INVALID_TARGET_COUNT ) { FAPI_ERR("Unable to determine the target count " "for target type = 0x%x and instance 0x%d " "associated with proc position %d", i_targType, i_instance, l_procPosition); } else { fapi_pos = max_targets * l_procPosition + (i_instance % max_targets); } return fapi_pos; } }; <|endoftext|>
<commit_before><commit_msg>mwg/std/tuple (rvalue_reference_wrapper): Add move assignment operator for vc2010.<commit_after><|endoftext|>
<commit_before>#include <b9.hpp> #include <b9/core.hpp> #include <b9/hash.hpp> #include <b9/jit.hpp> #include <b9/loader.hpp> #include "Jit.hpp" #include <sys/time.h> #include <cassert> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <sstream> #include <string> namespace b9 { void ExecutionContext::push(StackElement value) { *(stackPointer_++) = value; } StackElement ExecutionContext::pop() { return *(--stackPointer_); } void ExecutionContext::functionCall(Parameter value) { auto f = virtualMachine_->getFunction((std::size_t)value); auto result = interpret(f); push(result); } void ExecutionContext::primitiveCall(Parameter value) { PrimitiveFunction *primitive = virtualMachine_->getPrimitive(value); (*primitive)(this); } void ExecutionContext::pushFromVar(StackElement *args, Parameter offset) { push(args[offset]); } void ExecutionContext::pushIntoVar(StackElement *args, Parameter offset) { args[offset] = pop(); } void ExecutionContext::drop() { pop(); } void ExecutionContext::intPushConstant(Parameter value) { push(value); } void ExecutionContext::strPushConstant(Parameter value) { push((StackElement)virtualMachine_->getString(value)); } Parameter ExecutionContext::intJmpEq(Parameter delta) { StackElement right = pop(); StackElement left = pop(); if (left == right) { return delta; } return 0; } Parameter ExecutionContext::intJmpNeq(Parameter delta) { StackElement right = pop(); StackElement left = pop(); if (left != right) { return delta; } return 0; } Parameter ExecutionContext::intJmpGt(Parameter delta) { StackElement right = pop(); StackElement left = pop(); if (left > right) { return delta; } return 0; } Parameter ExecutionContext::intJmpGe(Parameter delta) { StackElement right = pop(); StackElement left = pop(); if (left >= right) { return delta; } return 0; } Parameter ExecutionContext::intJmpLt(Parameter delta) { StackElement right = pop(); StackElement left = pop(); if (left < right) { return delta; } return 0; } Parameter ExecutionContext::intJmpLe(Parameter delta) { StackElement right = pop(); StackElement left = pop(); if (left <= right) { return delta; } return 0; } void ExecutionContext::intAdd() { StackElement right = pop(); StackElement left = pop(); StackElement result = left + right; push(result); } void ExecutionContext::intSub() { StackElement right = pop(); StackElement left = pop(); StackElement result = left - right; push(result); } /// ExecutionContext bool VirtualMachine::initialize() { if (cfg_.verbose) std::cout << "VM initializing...\n"; if (cfg_.jit) { if (initializeJit()) { compiler_ = std::make_shared<Compiler>(this, cfg_); if (cfg_.verbose) std::cout << "JIT successfully initialized\n"; return true; } if (cfg_.verbose) std::cout << "JIT failed to initialize\n"; return false; } return true; } bool VirtualMachine::shutdown() { if (cfg_.verbose) std::cout << "VM shutting down...\n"; if (cfg_.jit) { shutdownJit(); } return true; } void VirtualMachine::load(std::shared_ptr<const Module> module) { module_ = module; } /// ByteCode Interpreter #if 0 StackElement interpret_0(ExecutionContext *context, Instruction *program) { return context->interpret(program); } StackElement interpret_1(ExecutionContext *context, Instruction *program, StackElement p1) { context->push(p1); return context->interpret(program); } StackElement interpret_2(ExecutionContext *context, Instruction *program, StackElement p1, StackElement p2) { context->push(p1); context->push(p2); return context->interpret(program); } StackElement interpret_3(ExecutionContext *context, Instruction *program, StackElement p1, StackElement p2, StackElement p3) { context->push(p1); context->push(p2); context->push(p3); return context->interpret(program); } #endif // 0 StackElement ExecutionContext::interpret(const FunctionSpec *function) { const Instruction *instructionPointer = function->address; StackElement *args = stackPointer_ - function->nargs; stackPointer_ += function->nregs; while (*instructionPointer != NO_MORE_BYTECODES) { // b9PrintStack(context); // std::cerr << "instruction call " << std::hex << (int) // ByteCodes::toByte(Instructions::getByteCode(*instructionPointer)) << // std::endl; switch (Instructions::getByteCode(*instructionPointer)) { case ByteCode::INT_PUSH_CONSTANT: intPushConstant(Instructions::getParameter(*instructionPointer)); break; case ByteCode::STR_PUSH_CONSTANT: strPushConstant(Instructions::getParameter(*instructionPointer)); break; case ByteCode::DROP: drop(); break; case ByteCode::INT_ADD: intAdd(); break; case ByteCode::INT_SUB: intSub(); break; case ByteCode::JMP: instructionPointer += Instructions::getParameter(*instructionPointer); break; case ByteCode::INT_JMP_EQ: instructionPointer += intJmpEq(Instructions::getParameter(*instructionPointer)); break; case ByteCode::INT_JMP_NEQ: instructionPointer += intJmpNeq(Instructions::getParameter(*instructionPointer)); break; case ByteCode::INT_JMP_GT: instructionPointer += intJmpGt(Instructions::getParameter(*instructionPointer)); break; case ByteCode::INT_JMP_GE: instructionPointer += intJmpGe(Instructions::getParameter(*instructionPointer)); break; case ByteCode::INT_JMP_LT: instructionPointer += intJmpLt(Instructions::getParameter(*instructionPointer)); break; case ByteCode::INT_JMP_LE: instructionPointer += intJmpLe(Instructions::getParameter(*instructionPointer)); break; case ByteCode::FUNCTION_CALL: functionCall(Instructions::getParameter(*instructionPointer)); break; case ByteCode::PUSH_FROM_VAR: pushFromVar(args, Instructions::getParameter(*instructionPointer)); break; case ByteCode::POP_INTO_VAR: // TODO bad name, push or pop? pushIntoVar(args, Instructions::getParameter(*instructionPointer)); break; case ByteCode::FUNCTION_RETURN: { StackElement result = *(stackPointer_ - 1); stackPointer_ = args; return result; break; } case ByteCode::PRIMITIVE_CALL: primitiveCall(Instructions::getParameter(*instructionPointer)); break; default: assert(false); break; } instructionPointer++; } return *(stackPointer_ - 1); } void *VirtualMachine::getJitAddress(std::size_t functionIndex) { if (functionIndex > compiledFunctions_.size()) { return nullptr; } return compiledFunctions_[functionIndex]; } void VirtualMachine::setJitAddress(std::size_t functionIndex, void *value) { compiledFunctions_[functionIndex] = value; } PrimitiveFunction *VirtualMachine::getPrimitive(std::size_t index) { return module_->primitives[index]; } const FunctionSpec *VirtualMachine::getFunction(std::size_t index) { return &module_->functions[index]; } const char *VirtualMachine::getString(int index) { return module_->strings[index]; } std::size_t VirtualMachine::getFunctionCount() { return module_->functions.size(); } // void removeGeneratedCode(ExecutionContext *context, int functionIndex) { // context->functions[functionIndex].jitAddress = 0; // setJitAddressSlot(context->functions[functionIndex].program, 0); // } // void removeAllGeneratedCode(ExecutionContext *context) { // int functionIndex = 0; // while (context->functions[functionIndex].name != NO_MORE_FUNCTIONS) { // removeGeneratedCode(context, functionIndex); // functionIndex++; // } // } void VirtualMachine::generateAllCode() { std::size_t i = 0; for (auto &functionSpec : module_->functions) { auto func = compiler_->generateCode(functionSpec); setJitAddress(i, func); } } void ExecutionContext::reset() { stackPointer_ = stack_; programCounter_ = 0; } StackElement VirtualMachine::run(const std::string &name, const std::vector<StackElement> &usrArgs) { return run(module_->findFunction(name), usrArgs); } StackElement VirtualMachine::run(const std::size_t functionIndex, const std::vector<StackElement> &usrArgs) { auto function = getFunction(functionIndex); auto argsCount = function->nargs; if (cfg_.verbose) std::cout << "function: " << functionIndex << " nargs: " << argsCount << std::endl; if (function->nargs != usrArgs.size()) { std::stringstream ss; ss << function->name << " - Got " << usrArgs.size() << " arguments, expected " << function->nargs; std::string message = ss.str(); throw BadFunctionCallException{message}; } // push user defined arguments to send to the program for (std::size_t i = 0; i < function->nargs; i++) { auto idx = function->nargs - i - 1; auto arg = usrArgs[idx]; std::cout << "Pushing arg[" << idx << "] = " << arg << std::endl; executionContext_.push(arg); } auto address = getJitAddress(functionIndex); if (cfg_.jit && address == nullptr) { address = compiler_->generateCode(*function); setJitAddress(functionIndex, address); } if (address) { if (cfg_.debug) std::cout << "Calling JIT address at " << address << std::endl; StackElement result = 0; if (cfg_.passParam) { switch (argsCount) { case 0: { JIT_0_args jitedcode = (JIT_0_args)address; result = (*jitedcode)(); } break; case 1: { JIT_1_args jitedcode = (JIT_1_args)address; StackElement p1 = executionContext_.pop(); result = (*jitedcode)(p1); } break; case 2: { JIT_2_args jitedcode = (JIT_2_args)address; StackElement p2 = executionContext_.pop(); StackElement p1 = executionContext_.pop(); result = (*jitedcode)(p1, p2); } break; case 3: { JIT_3_args jitedcode = (JIT_3_args)address; StackElement p3 = executionContext_.pop(); StackElement p2 = executionContext_.pop(); StackElement p1 = executionContext_.pop(); result = (*jitedcode)(p1, p2, p3); } break; default: printf("Need to add handlers for more parameters\n"); break; } } else { // Call the Jit'ed function, passing the parameters on the // ExecutionContext stack. // TODO: should call vm.run here? Interpret jitedcode = (Interpret)address; result = (*jitedcode)(&executionContext_, function->address); } return result; } std::cout << "Interpreting...\n" << std::endl; // interpret the method otherwise executionContext_.reset(); StackElement result = executionContext_.interpret(function); executionContext_.reset(); return result; } const char *b9ByteCodeName(ByteCode bc) { if (bc == ByteCode::DROP) return "DROP"; if (bc == ByteCode::DUPLICATE) return "DUPLICATE"; if (bc == ByteCode::FUNCTION_RETURN) return "FUNCTION_RETURN"; if (bc == ByteCode::FUNCTION_CALL) return "FUNCTION_CALL"; if (bc == ByteCode::PRIMITIVE_CALL) return "PRIMITIVE_CALL"; if (bc == ByteCode::JMP) return "JMP"; if (bc == ByteCode::PUSH_FROM_VAR) return "PUSH_FROM_VAR"; if (bc == ByteCode::POP_INTO_VAR) return "POP_INTO_VAR"; if (bc == ByteCode::INT_PUSH_CONSTANT) return "INT_PUSH_CONSTANT"; if (bc == ByteCode::INT_SUB) return "INT_SUB"; if (bc == ByteCode::INT_ADD) return "INT_ADD"; if (bc == ByteCode::INT_JMP_EQ) return "INT_JMP_EQ"; if (bc == ByteCode::INT_JMP_NEQ) return "INT_JMP_NEQ"; if (bc == ByteCode::INT_JMP_GT) return "INT_JMP_GT"; if (bc == ByteCode::INT_JMP_GE) return "INT_JMP_GE"; if (bc == ByteCode::INT_JMP_LT) return "INT_JMP_LT"; if (bc == ByteCode::INT_JMP_LE) return "INT_JMP_LE"; if (bc == ByteCode::STR_PUSH_CONSTANT) return "STR_PUSH_CONSTANT"; if (bc == ByteCode::STR_JMP_EQ) return "STR_JMP_EQ"; if (bc == ByteCode::STR_JMP_NEQ) return "STR_JMP_NEQ"; return "UNKNOWN BYTECODE"; } // // Base9 Primitives // extern "C" void b9_prim_print_number(ExecutionContext *context) { StackElement number = context->pop(); std::cout << number << " "; context->push(0); } extern "C" void b9_prim_print_string(ExecutionContext *context) { char *string = (char *)keyToChar(context->pop()); puts(string); context->push(0); } extern "C" void b9_prim_hash_table_allocate(ExecutionContext *context) { pHeap p = hashTable_allocate(8); // if (context->debug >= 1) { // printf("IN hashTableAllocate %p\n", p); // } context->push((StackElement)p); } extern "C" void b9_prim_hash_table_put(ExecutionContext *context) { StackElement v = context->pop(); StackElement k = context->pop(); StackElement ht = context->pop(); // if (context->debug >= 1) { // printf("IN hashTablePut %p %p(%s) %p(%s) \n", ht, k, k, v, v); // } context->push((StackElement)hashTable_put(context, (pHeap)ht, (hashTableKey)k, (hashTableKey)v)); } extern "C" void b9_prim_hash_table_get(ExecutionContext *context) { StackElement k = context->pop(); StackElement ht = context->pop(); context->push( (StackElement)hashTable_get(context, (pHeap)ht, (hashTableKey)k)); } } // namespace b9 <commit_msg>Change bounds check<commit_after>#include <b9.hpp> #include <b9/core.hpp> #include <b9/hash.hpp> #include <b9/jit.hpp> #include <b9/loader.hpp> #include "Jit.hpp" #include <sys/time.h> #include <cassert> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <sstream> #include <string> namespace b9 { void ExecutionContext::push(StackElement value) { *(stackPointer_++) = value; } StackElement ExecutionContext::pop() { return *(--stackPointer_); } void ExecutionContext::functionCall(Parameter value) { auto f = virtualMachine_->getFunction((std::size_t)value); auto result = interpret(f); push(result); } void ExecutionContext::primitiveCall(Parameter value) { PrimitiveFunction *primitive = virtualMachine_->getPrimitive(value); (*primitive)(this); } void ExecutionContext::pushFromVar(StackElement *args, Parameter offset) { push(args[offset]); } void ExecutionContext::pushIntoVar(StackElement *args, Parameter offset) { args[offset] = pop(); } void ExecutionContext::drop() { pop(); } void ExecutionContext::intPushConstant(Parameter value) { push(value); } void ExecutionContext::strPushConstant(Parameter value) { push((StackElement)virtualMachine_->getString(value)); } Parameter ExecutionContext::intJmpEq(Parameter delta) { StackElement right = pop(); StackElement left = pop(); if (left == right) { return delta; } return 0; } Parameter ExecutionContext::intJmpNeq(Parameter delta) { StackElement right = pop(); StackElement left = pop(); if (left != right) { return delta; } return 0; } Parameter ExecutionContext::intJmpGt(Parameter delta) { StackElement right = pop(); StackElement left = pop(); if (left > right) { return delta; } return 0; } Parameter ExecutionContext::intJmpGe(Parameter delta) { StackElement right = pop(); StackElement left = pop(); if (left >= right) { return delta; } return 0; } Parameter ExecutionContext::intJmpLt(Parameter delta) { StackElement right = pop(); StackElement left = pop(); if (left < right) { return delta; } return 0; } Parameter ExecutionContext::intJmpLe(Parameter delta) { StackElement right = pop(); StackElement left = pop(); if (left <= right) { return delta; } return 0; } void ExecutionContext::intAdd() { StackElement right = pop(); StackElement left = pop(); StackElement result = left + right; push(result); } void ExecutionContext::intSub() { StackElement right = pop(); StackElement left = pop(); StackElement result = left - right; push(result); } /// ExecutionContext bool VirtualMachine::initialize() { if (cfg_.verbose) std::cout << "VM initializing...\n"; if (cfg_.jit) { if (initializeJit()) { compiler_ = std::make_shared<Compiler>(this, cfg_); if (cfg_.verbose) std::cout << "JIT successfully initialized\n"; return true; } if (cfg_.verbose) std::cout << "JIT failed to initialize\n"; return false; } return true; } bool VirtualMachine::shutdown() { if (cfg_.verbose) std::cout << "VM shutting down...\n"; if (cfg_.jit) { shutdownJit(); } return true; } void VirtualMachine::load(std::shared_ptr<const Module> module) { module_ = module; } /// ByteCode Interpreter #if 0 StackElement interpret_0(ExecutionContext *context, Instruction *program) { return context->interpret(program); } StackElement interpret_1(ExecutionContext *context, Instruction *program, StackElement p1) { context->push(p1); return context->interpret(program); } StackElement interpret_2(ExecutionContext *context, Instruction *program, StackElement p1, StackElement p2) { context->push(p1); context->push(p2); return context->interpret(program); } StackElement interpret_3(ExecutionContext *context, Instruction *program, StackElement p1, StackElement p2, StackElement p3) { context->push(p1); context->push(p2); context->push(p3); return context->interpret(program); } #endif // 0 StackElement ExecutionContext::interpret(const FunctionSpec *function) { const Instruction *instructionPointer = function->address; StackElement *args = stackPointer_ - function->nargs; stackPointer_ += function->nregs; while (*instructionPointer != NO_MORE_BYTECODES) { // b9PrintStack(context); // std::cerr << "instruction call " << std::hex << (int) // ByteCodes::toByte(Instructions::getByteCode(*instructionPointer)) << // std::endl; switch (Instructions::getByteCode(*instructionPointer)) { case ByteCode::INT_PUSH_CONSTANT: intPushConstant(Instructions::getParameter(*instructionPointer)); break; case ByteCode::STR_PUSH_CONSTANT: strPushConstant(Instructions::getParameter(*instructionPointer)); break; case ByteCode::DROP: drop(); break; case ByteCode::INT_ADD: intAdd(); break; case ByteCode::INT_SUB: intSub(); break; case ByteCode::JMP: instructionPointer += Instructions::getParameter(*instructionPointer); break; case ByteCode::INT_JMP_EQ: instructionPointer += intJmpEq(Instructions::getParameter(*instructionPointer)); break; case ByteCode::INT_JMP_NEQ: instructionPointer += intJmpNeq(Instructions::getParameter(*instructionPointer)); break; case ByteCode::INT_JMP_GT: instructionPointer += intJmpGt(Instructions::getParameter(*instructionPointer)); break; case ByteCode::INT_JMP_GE: instructionPointer += intJmpGe(Instructions::getParameter(*instructionPointer)); break; case ByteCode::INT_JMP_LT: instructionPointer += intJmpLt(Instructions::getParameter(*instructionPointer)); break; case ByteCode::INT_JMP_LE: instructionPointer += intJmpLe(Instructions::getParameter(*instructionPointer)); break; case ByteCode::FUNCTION_CALL: functionCall(Instructions::getParameter(*instructionPointer)); break; case ByteCode::PUSH_FROM_VAR: pushFromVar(args, Instructions::getParameter(*instructionPointer)); break; case ByteCode::POP_INTO_VAR: // TODO bad name, push or pop? pushIntoVar(args, Instructions::getParameter(*instructionPointer)); break; case ByteCode::FUNCTION_RETURN: { StackElement result = *(stackPointer_ - 1); stackPointer_ = args; return result; break; } case ByteCode::PRIMITIVE_CALL: primitiveCall(Instructions::getParameter(*instructionPointer)); break; default: assert(false); break; } instructionPointer++; } return *(stackPointer_ - 1); } void *VirtualMachine::getJitAddress(std::size_t functionIndex) { if (functionIndex >= compiledFunctions_.size()) { return nullptr; } return compiledFunctions_[functionIndex]; } void VirtualMachine::setJitAddress(std::size_t functionIndex, void *value) { compiledFunctions_[functionIndex] = value; } PrimitiveFunction *VirtualMachine::getPrimitive(std::size_t index) { return module_->primitives[index]; } const FunctionSpec *VirtualMachine::getFunction(std::size_t index) { return &module_->functions[index]; } const char *VirtualMachine::getString(int index) { return module_->strings[index]; } std::size_t VirtualMachine::getFunctionCount() { return module_->functions.size(); } // void removeGeneratedCode(ExecutionContext *context, int functionIndex) { // context->functions[functionIndex].jitAddress = 0; // setJitAddressSlot(context->functions[functionIndex].program, 0); // } // void removeAllGeneratedCode(ExecutionContext *context) { // int functionIndex = 0; // while (context->functions[functionIndex].name != NO_MORE_FUNCTIONS) { // removeGeneratedCode(context, functionIndex); // functionIndex++; // } // } void VirtualMachine::generateAllCode() { std::size_t i = 0; for (auto &functionSpec : module_->functions) { auto func = compiler_->generateCode(functionSpec); setJitAddress(i, func); } } void ExecutionContext::reset() { stackPointer_ = stack_; programCounter_ = 0; } StackElement VirtualMachine::run(const std::string &name, const std::vector<StackElement> &usrArgs) { return run(module_->findFunction(name), usrArgs); } StackElement VirtualMachine::run(const std::size_t functionIndex, const std::vector<StackElement> &usrArgs) { auto function = getFunction(functionIndex); auto argsCount = function->nargs; if (cfg_.verbose) std::cout << "function: " << functionIndex << " nargs: " << argsCount << std::endl; if (function->nargs != usrArgs.size()) { std::stringstream ss; ss << function->name << " - Got " << usrArgs.size() << " arguments, expected " << function->nargs; std::string message = ss.str(); throw BadFunctionCallException{message}; } // push user defined arguments to send to the program for (std::size_t i = 0; i < function->nargs; i++) { auto idx = function->nargs - i - 1; auto arg = usrArgs[idx]; std::cout << "Pushing arg[" << idx << "] = " << arg << std::endl; executionContext_.push(arg); } auto address = getJitAddress(functionIndex); if (cfg_.jit && address == nullptr) { address = compiler_->generateCode(*function); setJitAddress(functionIndex, address); } if (address) { if (cfg_.debug) std::cout << "Calling JIT address at " << address << std::endl; StackElement result = 0; if (cfg_.passParam) { switch (argsCount) { case 0: { JIT_0_args jitedcode = (JIT_0_args)address; result = (*jitedcode)(); } break; case 1: { JIT_1_args jitedcode = (JIT_1_args)address; StackElement p1 = executionContext_.pop(); result = (*jitedcode)(p1); } break; case 2: { JIT_2_args jitedcode = (JIT_2_args)address; StackElement p2 = executionContext_.pop(); StackElement p1 = executionContext_.pop(); result = (*jitedcode)(p1, p2); } break; case 3: { JIT_3_args jitedcode = (JIT_3_args)address; StackElement p3 = executionContext_.pop(); StackElement p2 = executionContext_.pop(); StackElement p1 = executionContext_.pop(); result = (*jitedcode)(p1, p2, p3); } break; default: printf("Need to add handlers for more parameters\n"); break; } } else { // Call the Jit'ed function, passing the parameters on the // ExecutionContext stack. // TODO: should call vm.run here? Interpret jitedcode = (Interpret)address; result = (*jitedcode)(&executionContext_, function->address); } return result; } std::cout << "Interpreting...\n" << std::endl; // interpret the method otherwise executionContext_.reset(); StackElement result = executionContext_.interpret(function); executionContext_.reset(); return result; } const char *b9ByteCodeName(ByteCode bc) { if (bc == ByteCode::DROP) return "DROP"; if (bc == ByteCode::DUPLICATE) return "DUPLICATE"; if (bc == ByteCode::FUNCTION_RETURN) return "FUNCTION_RETURN"; if (bc == ByteCode::FUNCTION_CALL) return "FUNCTION_CALL"; if (bc == ByteCode::PRIMITIVE_CALL) return "PRIMITIVE_CALL"; if (bc == ByteCode::JMP) return "JMP"; if (bc == ByteCode::PUSH_FROM_VAR) return "PUSH_FROM_VAR"; if (bc == ByteCode::POP_INTO_VAR) return "POP_INTO_VAR"; if (bc == ByteCode::INT_PUSH_CONSTANT) return "INT_PUSH_CONSTANT"; if (bc == ByteCode::INT_SUB) return "INT_SUB"; if (bc == ByteCode::INT_ADD) return "INT_ADD"; if (bc == ByteCode::INT_JMP_EQ) return "INT_JMP_EQ"; if (bc == ByteCode::INT_JMP_NEQ) return "INT_JMP_NEQ"; if (bc == ByteCode::INT_JMP_GT) return "INT_JMP_GT"; if (bc == ByteCode::INT_JMP_GE) return "INT_JMP_GE"; if (bc == ByteCode::INT_JMP_LT) return "INT_JMP_LT"; if (bc == ByteCode::INT_JMP_LE) return "INT_JMP_LE"; if (bc == ByteCode::STR_PUSH_CONSTANT) return "STR_PUSH_CONSTANT"; if (bc == ByteCode::STR_JMP_EQ) return "STR_JMP_EQ"; if (bc == ByteCode::STR_JMP_NEQ) return "STR_JMP_NEQ"; return "UNKNOWN BYTECODE"; } // // Base9 Primitives // extern "C" void b9_prim_print_number(ExecutionContext *context) { StackElement number = context->pop(); std::cout << number << " "; context->push(0); } extern "C" void b9_prim_print_string(ExecutionContext *context) { char *string = (char *)keyToChar(context->pop()); puts(string); context->push(0); } extern "C" void b9_prim_hash_table_allocate(ExecutionContext *context) { pHeap p = hashTable_allocate(8); // if (context->debug >= 1) { // printf("IN hashTableAllocate %p\n", p); // } context->push((StackElement)p); } extern "C" void b9_prim_hash_table_put(ExecutionContext *context) { StackElement v = context->pop(); StackElement k = context->pop(); StackElement ht = context->pop(); // if (context->debug >= 1) { // printf("IN hashTablePut %p %p(%s) %p(%s) \n", ht, k, k, v, v); // } context->push((StackElement)hashTable_put(context, (pHeap)ht, (hashTableKey)k, (hashTableKey)v)); } extern "C" void b9_prim_hash_table_get(ExecutionContext *context) { StackElement k = context->pop(); StackElement ht = context->pop(); context->push( (StackElement)hashTable_get(context, (pHeap)ht, (hashTableKey)k)); } } // namespace b9 <|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cms.h> //////////////////////////////////////////////////////////////////////////////// void cms_initialize() { } //////////////////////////////////////////////////////////////////////////////// void cms_terminate() { } <commit_msg>Add the code to init the ActiveMQ-CPP library and shut it down when finished.<commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cms.h> #include <activemq/library/ActiveMQCPP.h> //////////////////////////////////////////////////////////////////////////////// void cms_initialize() { activemq::library::ActiveMQCPP::initializeLibrary(); } //////////////////////////////////////////////////////////////////////////////// void cms_terminate() { activemq::library::ActiveMQCPP::shutdownLibrary(); } <|endoftext|>
<commit_before>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 3486 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>SWDEV-2 - Change OpenCL version number from 3486 to 3487<commit_after>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 3487 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 3373 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>SWDEV-2 - Change OpenCL version number from 3373 to 3374<commit_after>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 3374 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>/* Copyright (c) 2010-present Advanced Micro Devices, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 3289 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>SWDEV-2 - Change OpenCL version number from 3289 to 3290<commit_after>/* Copyright (c) 2010-present Advanced Micro Devices, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 3290 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 3433 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>SWDEV-2 - Change OpenCL version number from 3433 to 3434<commit_after>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 3434 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>/* Copyright (c) 2010-present Advanced Micro Devices, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 3191 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <commit_msg>SWDEV-2 - Change OpenCL version number from 3191 to 3192<commit_after>/* Copyright (c) 2010-present Advanced Micro Devices, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef VERSIONS_HPP_ #define VERSIONS_HPP_ #include "utils/macros.hpp" #ifndef AMD_PLATFORM_NAME #define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing" #endif // AMD_PLATFORM_NAME #ifndef AMD_PLATFORM_BUILD_NUMBER #define AMD_PLATFORM_BUILD_NUMBER 3192 #endif // AMD_PLATFORM_BUILD_NUMBER #ifndef AMD_PLATFORM_REVISION_NUMBER #define AMD_PLATFORM_REVISION_NUMBER 0 #endif // AMD_PLATFORM_REVISION_NUMBER #ifndef AMD_PLATFORM_RELEASE_INFO #define AMD_PLATFORM_RELEASE_INFO #endif // AMD_PLATFORM_RELEASE_INFO #define AMD_BUILD_STRING \ XSTR(AMD_PLATFORM_BUILD_NUMBER) \ "." XSTR(AMD_PLATFORM_REVISION_NUMBER) #ifndef AMD_PLATFORM_INFO #define AMD_PLATFORM_INFO \ "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \ "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")" #endif // ATI_PLATFORM_INFO #endif // VERSIONS_HPP_ <|endoftext|>
<commit_before>/* * Mnemonizer.cpp * Object to convert random ipv4 and ipv6 to a mnemonic. * The gist of the algorithm works like this: * Checks if the ip is valid ipv4 or ipv6 * Adds a static salt to the string * Hashes the ip and the salt with SHA1 * Splits the hash into 4 parts * Gets one of the mnemonicStart and one of the mneomicends for each part * * To use it: * First require it: * require('./path/mnemonics.node'); * then create an object with a salt like this: * var mnem = new mnemonics.mnemonizer("This is an example salt[0._\Acd2*+ç_SAs]"); * The salt is reccommended to be SALTLENGTH long * Then you can call Apply_mnemonic with any ip * mnem.Apply_mnemonic("192.168.1.1"); * This will return * The mnemonic if the argument passed is a valid ip * NULL if the ip was invalid or there was some incorrect parameter, and an error message will be printed */ #include "mnemonizer.h" #include <sstream> //String stream #include <cstdlib> //strtol #include <cmath> //floor #include <openssl/sha.h> using namespace v8; const std::string MNEMONICSTARTS[] = {"", "k", "s", "t", "d", "n", "h", "b", "p", "m", "f", "r", "g", "z", "l", "ch"}; const std::string MNEMONICENDS[] = {"a", "i", "u", "e", "o", "a", "i", "u", "e", "o", "ya", "yi", "yu", "ye", "yo", "'"}; const char* const HEXS = "0123456789ABCDEF"; const int SALTLENGTH = 40; //feel free to change this if you know a better length void mnemonizer::Init(Handle<Object> exports) { NanScope(); Local<FunctionTemplate> tpl = NanNew<FunctionTemplate>(New); tpl->SetClassName(NanNew("mnemonizer")); tpl->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(tpl,"Apply_mnemonic",Apply_mnemonic); NanAssignPersistent(constructor,tpl->GetFunction()); exports->Set(NanNew("mnemonizer"),tpl->GetFunction()); } NAN_METHOD(mnemonizer::New){ NanScope(); if(args.IsConstructCall()){ mnemonizer* obj; if(!args[0]->IsString()){ printf("mnemonizer: Warning, invalid Salt, no salt will we used (non secure)\n"); obj= new mnemonizer(std::string("")); }else{ String::Utf8Value saltUTF(args[0]); obj = new mnemonizer(std::string(*saltUTF)); } obj->Wrap(args.This()); NanReturnValue(args.This()); }else { Local<Function> cons = NanNew<Function>(constructor); NanReturnValue(cons->NewInstance()); } } Persistent<Function> mnemonizer::constructor; mnemonizer::mnemonizer(std::string salt) { if(salt.length()<SALTLENGTH) printf("mnemonizer: Warning, salt should be larger, at least %d characters\n",SALTLENGTH); this->salt=salt; } mnemonizer::~mnemonizer() { } bool mnemonizer::isIpv4(std::string ip){ if(*ip.rbegin()=='.') return false; std::stringstream ipStream(ip); std::string part; int count =0; char *end; while(std::getline(ipStream,part,'.')){ if(count>3 || part.empty()) return false; int val = strtol(part.c_str(),&end,10); if(*end!= '\0' ||val<0 || val>255) return false; count++; } return true; } bool mnemonizer::isIpv6(std::string ip){ if(*ip.rbegin()==':') return false; std::stringstream ipStream(ip); std::string part; bool gap = false; int count =0; char *end; while(std::getline(ipStream,part,':')){ if(part.empty()){ if(gap) //If we already have a gap don't accept this one return false; gap = true; } int val = strtol(part.c_str(),&end,16); if(*end!= '\0' || val>0xFFFF) return false; count++; } if(!gap && count!=8) return false; return true; } std::string mnemonizer::hashToMem(unsigned char* hash){ std::string result; result.reserve(10); for(int i=0;i<4;i++){ std::string part = ucharToHex(hash+(i*5),10); unsigned int val = strtoul(part.c_str(),NULL,16); result.append( MNEMONICSTARTS[(int)floor((val%256)/16)]+ MNEMONICENDS[val%16] ); } return result; } std::string mnemonizer::ucharToHex(unsigned char* hashpart,int length_hex){ std::string out; out.reserve(length_hex); for(int i=0;i <length_hex/2;i++) { unsigned char c = hashpart[i]; out.push_back(HEXS[c>>4]); out.push_back(HEXS[c&15]); } return out; } NAN_METHOD(mnemonizer::Apply_mnemonic){ NanScope(); mnemonizer* obj = ObjectWrap::Unwrap<mnemonizer>(args.Holder()); if(!args[0]->IsString()) printf("mnemonizer: Wrong argument passed to Apply_mnemonic(Should be an String)\n"); String::Utf8Value ipUTF(args[0]); std::string ip= std::string(*ipUTF); if(obj->isIpv4(ip) || obj->isIpv6(ip)){ unsigned char out[SHA_DIGEST_LENGTH]; ip.append(obj->salt); SHA1((unsigned char*)ip.c_str(),ip.length(),out); NanReturnValue(NanNew<String>(obj->hashToMem(out))); } NanReturnValue(NanNull()); }<commit_msg>Fix ipv6 starting or ending with ::<commit_after>/* * Mnemonizer.cpp * Object to convert random ipv4 and ipv6 to a mnemonic. * The gist of the algorithm works like this: * Checks if the ip is valid ipv4 or ipv6 * Adds a static salt to the string * Hashes the ip and the salt with SHA1 * Splits the hash into 4 parts * Gets one of the mnemonicStart and one of the mneomicends for each part * * To use it: * First require it: * require('./path/mnemonics.node'); * then create an object with a salt like this: * var mnem = new mnemonics.mnemonizer("This is an example salt[0._\Acd2*+ç_SAs]"); * The salt is reccommended to be SALTLENGTH long * Then you can call Apply_mnemonic with any ip * mnem.Apply_mnemonic("192.168.1.1"); * This will return * The mnemonic if the argument passed is a valid ip * NULL if the ip was invalid or there was some incorrect parameter, and an error message will be printed */ #include "mnemonizer.h" #include <sstream> //String stream #include <cstdlib> //strtol #include <cmath> //floor #include <openssl/sha.h> using namespace v8; const std::string MNEMONICSTARTS[] = {"", "k", "s", "t", "d", "n", "h", "b", "p", "m", "f", "r", "g", "z", "l", "ch"}; const std::string MNEMONICENDS[] = {"a", "i", "u", "e", "o", "a", "i", "u", "e", "o", "ya", "yi", "yu", "ye", "yo", "'"}; const char* const HEXS = "0123456789ABCDEF"; const int SALTLENGTH = 40; //feel free to change this if you know a better length void mnemonizer::Init(Handle<Object> exports) { NanScope(); Local<FunctionTemplate> tpl = NanNew<FunctionTemplate>(New); tpl->SetClassName(NanNew("mnemonizer")); tpl->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(tpl,"Apply_mnemonic",Apply_mnemonic); NanAssignPersistent(constructor,tpl->GetFunction()); exports->Set(NanNew("mnemonizer"),tpl->GetFunction()); } NAN_METHOD(mnemonizer::New){ NanScope(); if(args.IsConstructCall()){ mnemonizer* obj; if(!args[0]->IsString()){ printf("mnemonizer: Warning, invalid Salt, no salt will we used (non secure)\n"); obj= new mnemonizer(std::string("")); }else{ String::Utf8Value saltUTF(args[0]); obj = new mnemonizer(std::string(*saltUTF)); } obj->Wrap(args.This()); NanReturnValue(args.This()); }else { Local<Function> cons = NanNew<Function>(constructor); NanReturnValue(cons->NewInstance()); } } Persistent<Function> mnemonizer::constructor; mnemonizer::mnemonizer(std::string salt) { if(salt.length()<SALTLENGTH) printf("mnemonizer: Warning, salt should be larger, at least %d characters\n",SALTLENGTH); this->salt=salt; } mnemonizer::~mnemonizer() { } bool mnemonizer::isIpv4(std::string ip){ if(*ip.rbegin()=='.') return false; std::stringstream ipStream(ip); std::string part; int count =0; char *end; while(std::getline(ipStream,part,'.')){ if(count>3 || part.empty()) return false; int val = strtol(part.c_str(),&end,10); if(*end!= '\0' ||val<0 || val>255) return false; count++; } return true; } bool mnemonizer::isIpv6(std::string ip){ std::string::reverse_iterator lastC=ip.rbegin(); if(ip.length()<2 ||(lastC[0]==':' && lastC[1]!=':')) //ends with :: return false; bool gap = false; std::string::iterator firstC = ip.begin(); if(firstC[0]==':' && firstC[1]==':'){ //starts with :: gap=true; ip.erase(0,2); } std::stringstream ipStream(ip); std::string part; int count =0; char *end; while(std::getline(ipStream,part,':')){ if(part.empty()){ if(gap) //If we already have a gap don't accept this one return false; gap = true; } int val = strtol(part.c_str(),&end,16); if(*end!= '\0' || val>0xFFFF) return false; count++; } if(!gap && count!=8) return false; return true; } std::string mnemonizer::hashToMem(unsigned char* hash){ std::string result; result.reserve(10); for(int i=0;i<4;i++){ std::string part = ucharToHex(hash+(i*5),10); unsigned int val = strtoul(part.c_str(),NULL,16); result.append( MNEMONICSTARTS[(int)floor((val%256)/16)]+ MNEMONICENDS[val%16] ); } return result; } std::string mnemonizer::ucharToHex(unsigned char* hashpart,int length_hex){ std::string out; out.reserve(length_hex); for(int i=0;i <length_hex/2;i++) { unsigned char c = hashpart[i]; out.push_back(HEXS[c>>4]); out.push_back(HEXS[c&15]); } return out; } NAN_METHOD(mnemonizer::Apply_mnemonic){ NanScope(); mnemonizer* obj = ObjectWrap::Unwrap<mnemonizer>(args.Holder()); if(!args[0]->IsString()) printf("mnemonizer: Wrong argument passed to Apply_mnemonic(Should be an String)\n"); String::Utf8Value ipUTF(args[0]); std::string ip= std::string(*ipUTF); if(obj->isIpv4(ip) || obj->isIpv6(ip)){ unsigned char out[SHA_DIGEST_LENGTH]; ip.append(obj->salt); SHA1((unsigned char*)ip.c_str(),ip.length(),out); NanReturnValue(NanNew<String>(obj->hashToMem(out))); } NanReturnValue(NanNull()); }<|endoftext|>
<commit_before>// // TestUtilities.cpp // FxDSP // // Created by Hamilton Kibbe on 5/3/15. // Copyright (c) 2015 Hamilton Kibbe. All rights reserved. // #include "Utilities.h" #include <math.h> #include <gtest/gtest.h> #define EPSILON (0.00001) TEST(Utilities, TestAmpDbConversion) { float amps[5] = {1.0, 0.5, 0.25, 0.125, 0.0625}; float dbs[5] = {0.0,-6.0206003,-12.041201,-18.061801,-24.082401}; for (unsigned i = 0; i < 5; ++i) { ASSERT_NEAR(dbs[i], AmpToDb(amps[i]), EPSILON); ASSERT_NEAR(amps[i], DbToAmp(dbs[i]), EPSILON); } } TEST(Utilities, TestClamp) { float in[10] = {-10.0, -2.0, -1.1, -1.0, -0.5, 0.5, 1.0, 1.1, 2.0, 10.0}; float ex[10] = {-1.0, -1.0, -1.0, -1.0, -0.5, 0.5, 1.0, 1.0, 1.0, 1.0}; for (unsigned i = 0; i < 10; ++i) { ASSERT_FLOAT_EQ(ex[i], f_clamp(in[i], -1.0, 1.0)); } } TEST(Utilities, TestFastPow2) { float in[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; for (unsigned i = 0; i < 10; ++i) { ASSERT_FLOAT_EQ(powf(2.0, in[i]), f_pow2(in[i])); } } TEST(Utilities, log2) { double in[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; for (unsigned i = 0; i < 10; ++i) { ASSERT_DOUBLE_EQ(log(in[i])/log(2.), log2(in[i])); } } TEST(Utilities, TestMaxAndMin) { float a[10] = {0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0}; float b[10] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0}; for (unsigned i = 0; i < 10; ++i) { ASSERT_FLOAT_EQ(a[i], f_min(a[i], b[i])); ASSERT_FLOAT_EQ(b[i], f_max(a[i], b[i])); } } TEST(Utilities, TestFastExp) { float in[10] = {0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}; for (unsigned i = 0; i < 10; ++i) { ASSERT_NEAR(expf(in[i]), f_exp(in[i]), 0.001); } } TEST(Utilities, TestFastExpD) { double in[10] = {0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}; for (unsigned i = 0; i < 10; ++i) { ASSERT_NEAR(exp(in[i]), f_expD(in[i]), 0.000001); } } TEST(Utilities, TestNextPow2) { int in[11] = {-2, 2, 3, 6, 12, 30, 33, 127, 129, 500, 1000}; int expect[11] = {0, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024}; for (unsigned i = 0; i < 10; ++i) { ASSERT_EQ(expect[i], next_pow2(in[i])); } } TEST(Utilities, TestPolarRectangularConversion) { double mag[10] = {0.0, 0.1, 0.2, 0.3, 0.4, -0.5, -0.6, -0.7, -0.8, -0.9}; double phase[10] = {0.9, 0.8, 0.7, -0.6, -0.5, -0.4, -0.3, -0.2, 0.1, 0.0}; float real[10]; float im[10]; double realD[10]; double imD[10]; for (unsigned i = 0; i < 10; ++i) { PolarToRect((float)mag[i], (float)phase[i], real+i, im+i); PolarToRectD(mag[i], phase[i], realD+i, imD + i); } for (unsigned i = 0; i < 10; ++i) { ASSERT_FLOAT_EQ(mag[i] * cosf(phase[i]), real[i]); ASSERT_FLOAT_EQ(mag[i] * sinf(phase[i]), im[i]); ASSERT_DOUBLE_EQ(mag[i] * cos(phase[i]), realD[i]); ASSERT_DOUBLE_EQ(mag[i] * sin(phase[i]), imD[i]); } } TEST(Utilities, TestRectangularPolarConversion) { double re[6] = {-1.0, -0.5, -0.25, 0.25, 0.5, 1.0}; double im[6] = {-1.0, -0.5, -0.25, 0.25, 0.5, 1.0}; float mag; float phase; double magD; double phaseD; //Try points in all 4 quadrants for (unsigned i = 0; i < 6; ++i) { for (unsigned j = 0; j < 6; ++j) { RectToPolar((float)re[i], (float)im[j], &mag, &phase); RectToPolarD(re[i], im[j], &magD, &phaseD); double exp_mag = sqrt(re[i]*re[i] + im[j]*im[j]); double exp_phase = atan(im[j]/re[i]); if (exp_phase < 0) exp_phase += M_PI; ASSERT_FLOAT_EQ((float)exp_mag, mag); ASSERT_FLOAT_EQ((float)exp_phase, phase); ASSERT_DOUBLE_EQ(exp_mag, magD); ASSERT_DOUBLE_EQ(exp_phase, phaseD); } } } TEST(Utilities, TestFastTanh) { float in[10] = {-1.0, -0.5, -0.25, -0.125, -0.0625, 0.0625, 0.125, 0.25, 0.5, 1.0}; for (unsigned i = 0; i < 10; ++i) { ASSERT_NEAR(tanhf(in[i]), f_tanh(in[i]), 0.0005); } } TEST(Utilities, TestInt16ToFloat) { ASSERT_FLOAT_EQ(1.0, int16ToFloat(32767)); } TEST(Utilities, TesFloatToInt16) { ASSERT_EQ(32767, floatToInt16(1.0)); } TEST(Utilities, TestDbAmpConversion) { ASSERT_FLOAT_EQ(0.0, DbToAmp(-99.0)); ASSERT_FLOAT_EQ(1.0, DbToAmp(0.0)); }<commit_msg>tests<commit_after>// // TestUtilities.cpp // FxDSP // // Created by Hamilton Kibbe on 5/3/15. // Copyright (c) 2015 Hamilton Kibbe. All rights reserved. // #include "Utilities.h" #include <math.h> #include <gtest/gtest.h> #define EPSILON (0.00001) TEST(Utilities, TestAmpDbConversion) { float amps[5] = {1.0, 0.5, 0.25, 0.125, 0.0625}; float dbs[5] = {0.0,-6.0206003,-12.041201,-18.061801,-24.082401}; for (unsigned i = 0; i < 5; ++i) { ASSERT_NEAR(dbs[i], AmpToDb(amps[i]), EPSILON); ASSERT_NEAR(amps[i], DbToAmp(dbs[i]), EPSILON); } } TEST(Utilities, TestClamp) { float in[10] = {-10.0, -2.0, -1.1, -1.0, -0.5, 0.5, 1.0, 1.1, 2.0, 10.0}; float ex[10] = {-1.0, -1.0, -1.0, -1.0, -0.5, 0.5, 1.0, 1.0, 1.0, 1.0}; for (unsigned i = 0; i < 10; ++i) { ASSERT_FLOAT_EQ(ex[i], f_clamp(in[i], -1.0, 1.0)); } } TEST(Utilities, TestFastPow2) { float in[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; for (unsigned i = 0; i < 10; ++i) { ASSERT_FLOAT_EQ(powf(2.0, in[i]), f_pow2(in[i])); } } TEST(Utilities, log2) { double in[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; for (unsigned i = 0; i < 10; ++i) { ASSERT_DOUBLE_EQ(log(in[i])/log(2.), log2(in[i])); } } TEST(Utilities, TestMaxAndMin) { float a[10] = {0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0}; float b[10] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0}; for (unsigned i = 0; i < 10; ++i) { ASSERT_FLOAT_EQ(a[i], f_min(a[i], b[i])); ASSERT_FLOAT_EQ(b[i], f_max(a[i], b[i])); } } TEST(Utilities, TestFastExp) { float in[10] = {0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}; for (unsigned i = 0; i < 10; ++i) { ASSERT_NEAR(expf(in[i]), f_exp(in[i]), 0.001); } } TEST(Utilities, TestFastExpD) { double in[10] = {0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}; for (unsigned i = 0; i < 10; ++i) { ASSERT_NEAR(exp(in[i]), f_expD(in[i]), 0.000001); } } TEST(Utilities, TestNextPow2) { int in[11] = {-2, 2, 3, 6, 12, 30, 33, 127, 129, 500, 1000}; int expect[11] = {0, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024}; for (unsigned i = 0; i < 10; ++i) { ASSERT_EQ(expect[i], next_pow2(in[i])); } } TEST(Utilities, TestPolarRectangularConversion) { double mag[10] = {0.0, 0.1, 0.2, 0.3, 0.4, -0.5, -0.6, -0.7, -0.8, -0.9}; double phase[10] = {0.9, 0.8, 0.7, -0.6, -0.5, -0.4, -0.3, -0.2, 0.1, 0.0}; float real[10]; float im[10]; double realD[10]; double imD[10]; for (unsigned i = 0; i < 10; ++i) { PolarToRect((float)mag[i], (float)phase[i], real+i, im+i); PolarToRectD(mag[i], phase[i], realD+i, imD + i); } for (unsigned i = 0; i < 10; ++i) { ASSERT_FLOAT_EQ(mag[i] * cosf(phase[i]), real[i]); ASSERT_FLOAT_EQ(mag[i] * sinf(phase[i]), im[i]); ASSERT_DOUBLE_EQ(mag[i] * cos(phase[i]), realD[i]); ASSERT_DOUBLE_EQ(mag[i] * sin(phase[i]), imD[i]); } } TEST(Utilities, TestRectangularPolarConversion) { double re[6] = {-1.0, -0.5, -0.25, 0.25, 0.5, 1.0}; double im[6] = {-1.0, -0.5, -0.25, 0.25, 0.5, 1.0}; float mag; float phase; double magD; double phaseD; //Try points in all 4 quadrants for (unsigned i = 0; i < 6; ++i) { for (unsigned j = 0; j < 6; ++j) { RectToPolar((float)re[i], (float)im[j], &mag, &phase); RectToPolarD(re[i], im[j], &magD, &phaseD); double exp_mag = sqrt(re[i]*re[i] + im[j]*im[j]); double exp_phase = atan(im[j]/re[i]); if (exp_phase < 0) exp_phase += M_PI; ASSERT_FLOAT_EQ((float)exp_mag, mag); ASSERT_FLOAT_EQ((float)exp_phase, phase); ASSERT_DOUBLE_EQ(exp_mag, magD); ASSERT_DOUBLE_EQ(exp_phase, phaseD); } } } TEST(Utilities, TestFastTanh) { float in[10] = {-1.0, -0.5, -0.25, -0.125, -0.0625, 0.0625, 0.125, 0.25, 0.5, 1.0}; for (unsigned i = 0; i < 10; ++i) { ASSERT_NEAR(tanhf(in[i]), f_tanh(in[i]), 0.0005); } } TEST(Utilities, TestInt16ToFloat) { ASSERT_FLOAT_EQ(1.0, int16ToFloat(32767)); } TEST(Utilities, TesFloatToInt16) { ASSERT_EQ(32767, floatToInt16(1.0)); } TEST(Utilities, TestDbAmpConversion) { ASSERT_FLOAT_EQ(0.0, DbToAmp(-99.0)); ASSERT_FLOAT_EQ(1.0, DbToAmp(0.0)); } TEST(Utilities, TestDbAmpConversionDouble) { ASSERT_DOUBLE_EQ(0.0, DbToAmpD(-99.0)); ASSERT_DOUBLE_EQ(1.0, DbToAmpD(0.0)); }<|endoftext|>
<commit_before>#include "leveldb_ext.h" static void PyLevelDB_set_error(leveldb::Status& status) { extern PyObject* leveldb_exception; PyErr_SetString(leveldb_exception, status.ToString().c_str()); } const char leveldb_repair_db_doc[] = "leveldb.RepairDB(db_dir)\n" ; PyObject* leveldb_repair_db(PyObject* self, PyObject* args) { const char* db_dir = 0; if (!PyArg_ParseTuple(args, "s", &db_dir)) return 0; std::string _db_dir(db_dir); leveldb::Status status; leveldb::Options options; Py_BEGIN_ALLOW_THREADS status = leveldb::RepairDB(_db_dir.c_str(), options); Py_END_ALLOW_THREADS if (!status.ok()) { PyLevelDB_set_error(status); return 0; } Py_INCREF(Py_None); return Py_None; } static void PyLevelDB_dealloc(PyLevelDB* self) { if (self->db) { Py_BEGIN_ALLOW_THREADS delete self->db; Py_END_ALLOW_THREADS self->db = 0; } Py_TYPE(self)->tp_free(self); } static PyObject* PyLevelDB_new(PyTypeObject* type, PyObject* args, PyObject* kwds) { PyLevelDB* self = (PyLevelDB*)type->tp_alloc(type, 0); if (self) { self->db = 0; } return (PyObject*)self; } static PyObject* PyLevelDB_Put(PyLevelDB* self, PyObject* args, PyObject* kwds) { PyObject* sync = Py_False; Py_buffer key, value; static char* kwargs[] = {"key", "value", "sync", 0}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "s*s*|O!", kwargs, &key, &value, &PyBool_Type, &sync)) return 0; leveldb::Slice key_slice((const char*)key.buf, (size_t)key.len); leveldb::Slice value_slice((const char*)value.buf, (size_t)value.len); leveldb::WriteOptions options; options.sync = (sync == Py_True) ? true : false; leveldb::Status status; Py_BEGIN_ALLOW_THREADS status = self->db->Put(options, key_slice, value_slice); Py_END_ALLOW_THREADS PyBuffer_Release(&key); PyBuffer_Release(&value); if (!status.ok()) { PyLevelDB_set_error(status); return 0; } Py_INCREF(Py_None); return Py_None; } static PyObject* PyLevelDB_Get(PyLevelDB* self, PyObject* args, PyObject* kwds) { PyObject* verify_checksums = Py_False; PyObject* fill_cache = Py_True; Py_buffer key; static char* kwargs[] = {"key", "verify_checksums", "fill_cache", 0}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "s*|O!O!", kwargs, &key, &PyBool_Type, &verify_checksums, &PyBool_Type, &fill_cache)) return 0; leveldb::Slice key_slice((const char*)key.buf, (size_t)key.len); leveldb::ReadOptions options; options.verify_checksums = (verify_checksums == Py_True) ? true : false; options.fill_cache = (fill_cache == Py_True) ? true : false; leveldb::Status status; std::string value; Py_BEGIN_ALLOW_THREADS status = self->db->Get(options, key_slice, &value); Py_END_ALLOW_THREADS PyBuffer_Release(&key); if (status.IsNotFound()) { PyErr_SetNone(PyExc_KeyError); return 0; } if (!status.ok()) { PyLevelDB_set_error(status); return 0; } return PyString_FromStringAndSize(value.c_str(), value.length()); } static PyMethodDef PyLevelDB_methods[] = { {"Put", (PyCFunction)PyLevelDB_Put, METH_KEYWORDS, "add a key/value pair to database, with an optional synchronous disk write" }, {"Get", (PyCFunction)PyLevelDB_Get, METH_KEYWORDS, "get a value from the database" }, {NULL} }; static int PyLevelDB_init(PyLevelDB* self, PyObject* args, PyObject* kwds) { if (self->db) { Py_BEGIN_ALLOW_THREADS delete self->db; Py_END_ALLOW_THREADS self->db = 0; } const char* db_dir = 0; PyObject* create_if_missing = Py_True; static char* kwargs[] = {"filename", "create_if_missing", 0}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|O!", kwargs, &db_dir, &PyBool_Type, &create_if_missing)) return -1; leveldb::Options options; options.create_if_missing = (create_if_missing == Py_True) ? true : false; leveldb::Status status; // copy string parameter, since we might lose when we release the GIL std::string _db_dir(db_dir); Py_BEGIN_ALLOW_THREADS status = leveldb::DB::Open(options, _db_dir, &self->db); Py_END_ALLOW_THREADS if (!status.ok()) { PyLevelDB_set_error(status); return -1; } return 0; } PyTypeObject PyLevelDBType = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ "leveldb.LevelDB", /*tp_name*/ sizeof(PyLevelDB), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)PyLevelDB_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ "PyLevelDB wrapper", /*tp_doc */ 0, /*tp_traverse */ 0, /*tp_clear */ 0, /*tp_richcompare */ 0, /*tp_weaklistoffset */ 0, /*tp_iter */ 0, /*tp_iternext */ PyLevelDB_methods, /*tp_methods */ 0, /*tp_members */ 0, /*tp_getset */ 0, /*tp_base */ 0, /*tp_dict */ 0, /*tp_descr_get */ 0, /*tp_descr_set */ 0, /*tp_dictoffset */ (initproc)PyLevelDB_init, /*tp_init */ 0, /*tp_alloc */ PyLevelDB_new, /*tp_new */ }; <commit_msg>a lot more options for db open<commit_after>#include "leveldb_ext.h" static void PyLevelDB_set_error(leveldb::Status& status) { extern PyObject* leveldb_exception; PyErr_SetString(leveldb_exception, status.ToString().c_str()); } const char leveldb_repair_db_doc[] = "leveldb.RepairDB(db_dir)\n" ; PyObject* leveldb_repair_db(PyObject* self, PyObject* args) { const char* db_dir = 0; if (!PyArg_ParseTuple(args, "s", &db_dir)) return 0; std::string _db_dir(db_dir); leveldb::Status status; leveldb::Options options; Py_BEGIN_ALLOW_THREADS status = leveldb::RepairDB(_db_dir.c_str(), options); Py_END_ALLOW_THREADS if (!status.ok()) { PyLevelDB_set_error(status); return 0; } Py_INCREF(Py_None); return Py_None; } static void PyLevelDB_dealloc(PyLevelDB* self) { if (self->db) { Py_BEGIN_ALLOW_THREADS delete self->db; Py_END_ALLOW_THREADS self->db = 0; } Py_TYPE(self)->tp_free(self); } static PyObject* PyLevelDB_new(PyTypeObject* type, PyObject* args, PyObject* kwds) { PyLevelDB* self = (PyLevelDB*)type->tp_alloc(type, 0); if (self) { self->db = 0; } return (PyObject*)self; } static PyObject* PyLevelDB_Put(PyLevelDB* self, PyObject* args, PyObject* kwds) { PyObject* sync = Py_False; Py_buffer key, value; static char* kwargs[] = {"key", "value", "sync", 0}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "s*s*|O!", kwargs, &key, &value, &PyBool_Type, &sync)) return 0; leveldb::Slice key_slice((const char*)key.buf, (size_t)key.len); leveldb::Slice value_slice((const char*)value.buf, (size_t)value.len); leveldb::WriteOptions options; options.sync = (sync == Py_True) ? true : false; leveldb::Status status; Py_BEGIN_ALLOW_THREADS status = self->db->Put(options, key_slice, value_slice); Py_END_ALLOW_THREADS PyBuffer_Release(&key); PyBuffer_Release(&value); if (!status.ok()) { PyLevelDB_set_error(status); return 0; } Py_INCREF(Py_None); return Py_None; } static PyObject* PyLevelDB_Get(PyLevelDB* self, PyObject* args, PyObject* kwds) { PyObject* verify_checksums = Py_False; PyObject* fill_cache = Py_True; Py_buffer key; static char* kwargs[] = {"key", "verify_checksums", "fill_cache", 0}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "s*|O!O!", kwargs, &key, &PyBool_Type, &verify_checksums, &PyBool_Type, &fill_cache)) return 0; leveldb::Slice key_slice((const char*)key.buf, (size_t)key.len); leveldb::ReadOptions options; options.verify_checksums = (verify_checksums == Py_True) ? true : false; options.fill_cache = (fill_cache == Py_True) ? true : false; leveldb::Status status; std::string value; Py_BEGIN_ALLOW_THREADS status = self->db->Get(options, key_slice, &value); Py_END_ALLOW_THREADS PyBuffer_Release(&key); if (status.IsNotFound()) { PyErr_SetNone(PyExc_KeyError); return 0; } if (!status.ok()) { PyLevelDB_set_error(status); return 0; } return PyString_FromStringAndSize(value.c_str(), value.length()); } static PyObject* PyLevelDB_Delete(PyLevelDB* self, PyObject* args, PyObject* kwds) { PyObject* sync = Py_False; Py_buffer key; static char* kwargs[] = {"key", "sync", 0}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "s*|O!", kwargs, &key, &PyBool_Type, &sync)) return 0; leveldb::Slice key_slice((const char*)key.buf, (size_t)key.len); leveldb::WriteOptions options; options.sync = (sync == Py_True) ? true : false; leveldb::Status status; Py_BEGIN_ALLOW_THREADS status = self->db->Delete(options, key_slice); Py_END_ALLOW_THREADS PyBuffer_Release(&key); if (!status.ok()) { PyLevelDB_set_error(status); return 0; } Py_INCREF(Py_None); return Py_None; } static PyMethodDef PyLevelDB_methods[] = { {"Put", (PyCFunction)PyLevelDB_Put, METH_KEYWORDS, "add a key/value pair to database, with an optional synchronous disk write" }, {"Get", (PyCFunction)PyLevelDB_Get, METH_KEYWORDS, "get a value from the database" }, {"Delete", (PyCFunction)PyLevelDB_Delete, METH_KEYWORDS, "delete a value in the database" }, {NULL} }; static int PyLevelDB_init(PyLevelDB* self, PyObject* args, PyObject* kwds) { if (self->db) { Py_BEGIN_ALLOW_THREADS delete self->db; Py_END_ALLOW_THREADS self->db = 0; } const char* db_dir = 0; PyObject* create_if_missing = Py_True; PyObject* error_if_exists = Py_False; PyObject* paranoid_checks = Py_False; int write_buffer_size = 4<<20; int block_size = 4096; int max_open_files = 1000; int block_restart_interval = 16; static char* kwargs[] = {"filename", "create_if_missing", "error_if_exists", "paranoid_checks", "write_buffer_size", "block_size", "max_open_files", "block_restart_interval", 0}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|O!O!O!iiii", kwargs, &db_dir, &PyBool_Type, &create_if_missing, &PyBool_Type, &error_if_exists, &PyBool_Type, &paranoid_checks, &write_buffer_size, &block_size, &max_open_files, &block_restart_interval)) return -1; if (write_buffer_size < 0 || block_size < 0 || max_open_files < 0 || block_restart_interval < 0) { PyErr_SetString(PyExc_ValueError, "negative write_buffer_size/block_size/max_open_files/block_restart_interval"); return -1; } leveldb::Options options; options.create_if_missing = (create_if_missing == Py_True) ? true : false; options.error_if_exists = (error_if_exists == Py_True) ? true : false; options.paranoid_checks = (paranoid_checks == Py_True) ? true : false; options.write_buffer_size = write_buffer_size; options.block_size = block_size; options.max_open_files = max_open_files; options.block_restart_interval = block_restart_interval; options.compression = leveldb::kSnappyCompression; leveldb::Status status; // copy string parameter, since we might lose when we release the GIL std::string _db_dir(db_dir); Py_BEGIN_ALLOW_THREADS status = leveldb::DB::Open(options, _db_dir, &self->db); Py_END_ALLOW_THREADS if (!status.ok()) { PyLevelDB_set_error(status); return -1; } return 0; } PyTypeObject PyLevelDBType = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ "leveldb.LevelDB", /*tp_name*/ sizeof(PyLevelDB), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)PyLevelDB_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ "PyLevelDB wrapper", /*tp_doc */ 0, /*tp_traverse */ 0, /*tp_clear */ 0, /*tp_richcompare */ 0, /*tp_weaklistoffset */ 0, /*tp_iter */ 0, /*tp_iternext */ PyLevelDB_methods, /*tp_methods */ 0, /*tp_members */ 0, /*tp_getset */ 0, /*tp_base */ 0, /*tp_dict */ 0, /*tp_descr_get */ 0, /*tp_descr_set */ 0, /*tp_dictoffset */ (initproc)PyLevelDB_init, /*tp_init */ 0, /*tp_alloc */ PyLevelDB_new, /*tp_new */ }; <|endoftext|>
<commit_before>#include "stdafx.hpp" #include <float.h> #include <CppUnitTest.h> #include <functional> #include "Geometry/Grassmann.hpp" #include "Geometry/R3Element.hpp" #include "Quantities/Astronomy.hpp" #include "Quantities/BIPM.hpp" #include "Quantities/Constants.hpp" #include "Quantities/Dimensionless.hpp" #include "Quantities/ElementaryFunctions.hpp" #include "Quantities/Quantities.hpp" #include "Quantities/SI.hpp" #include "Quantities/UK.hpp" #include "TestUtilities/Algebra.hpp" #include "TestUtilities/ExplicitOperators.hpp" #include "TestUtilities/GeometryComparisons.hpp" #include "TestUtilities/QuantityComparisons.hpp" #include "TestUtilities/TestUtilities.hpp" namespace principia { namespace geometry { using namespace astronomy; using namespace bipm; using namespace constants; using namespace Microsoft::VisualStudio::CppUnitTestFramework; using namespace quantities; using namespace si; using namespace test_utilities; using namespace uk; TEST_CLASS(GrassmannTests) { public: struct World; R3Element<Length> const null_displacement_ = R3Element<Length>(0 * Metre, 0 * Metre, 0 * Metre); R3Element<Length> const u_ = R3Element<Length>(3 * Metre, -42 * Metre, 0 * Metre); R3Element<Length> const v_ = R3Element<Length>(-π * Metre, -e * Metre, -1 * Metre); R3Element<Length> const w_ = R3Element<Length>(2 * Metre, 2 * Metre, 2 * Metre); R3Element<Length> const a_ = R3Element<Length>(1 * Inch, 2 * Foot, 3 * admiralty::Fathom); template<typename LScalar, typename RScalar, typename Frame, int Rank> static Product<LScalar, RScalar> MultivectorInnerProduct( Multivector<LScalar, Frame, Rank> const& left, Multivector<RScalar, Frame, Rank> const& right) { return InnerProduct(left, right); } template<typename LScalar, typename RScalar, typename Frame, int LRank, int RRank> static Multivector<Product<LScalar, RScalar>, Frame, LRank + RRank> Multivectorwedge( Multivector<LScalar, Frame, LRank> const& left, Multivector<RScalar, Frame, RRank> const& right) { return Wedge(left, right); } TEST_METHOD(SpecialOrthogonalLieAlgebra) { TestLieBracket(Commutator<Dimensionless, Dimensionless, World>, Bivector<Dimensionless, World>(u_ / Foot), Bivector<Dimensionless, World>(v_ / Metre), Bivector<Dimensionless, World>(w_ / Rod), Bivector<Dimensionless, World>(a_ / Furlong), Dimensionless(0.42), 128 * DBL_EPSILON); } TEST_METHOD(MixedScalarMultiplication) { TestBilinearMap( Times<Vector<Speed, World>, Inverse<Time>, Vector<Length, World>>, 1 / Second, 1 / JulianYear, Vector<Length, World>(u_), Vector<Length, World>(v_), Dimensionless(42), 2 * DBL_EPSILON); TestBilinearMap( Times<Vector<Speed, World>, Vector<Length, World>, Inverse<Time>>, Vector<Length, World>(w_), Vector<Length, World>(a_), -1 / Day, SpeedOfLight / Parsec, Dimensionless(-π), DBL_EPSILON); Inverse<Time> t = -3 / Second; AssertEqual(t * Vector<Length, World>(u_), Vector<Length, World>(u_) * t); AssertEqual((Vector<Length, World>(v_) * t) / t, Vector<Length, World>(v_)); } TEST_METHOD(VectorSpaces) { TestInnerProductSpace(MultivectorInnerProduct<Length, Length, World, 1>, Vector<Length, World>(null_displacement_), Vector<Length, World>(u_), Vector<Length, World>(v_), Vector<Length, World>(w_), Vector<Length, World>(a_), Dimensionless(0), Dimensionless(1), Sqrt(163), -Sqrt(2), 12 * DBL_EPSILON); TestInnerProductSpace(MultivectorInnerProduct<Length, Length, World, 2>, Bivector<Length, World>(null_displacement_), Bivector<Length, World>(u_), Bivector<Length, World>(v_), Bivector<Length, World>(w_), Bivector<Length, World>(a_), Dimensionless(0), Dimensionless(1), Sqrt(163), -Sqrt(2), 12 * DBL_EPSILON); TestInnerProductSpace(MultivectorInnerProduct<Length, Length, World, 3>, Trivector<Length, World>(null_displacement_.x), Trivector<Length, World>(u_.y), Trivector<Length, World>(v_.z), Trivector<Length, World>(w_.x), Trivector<Length, World>(a_.y), Dimensionless(0), Dimensionless(1), Sqrt(163), -Sqrt(2)); TestInnerProductSpace(MultivectorInnerProduct<Dimensionless, Dimensionless, World, 1>, Vector<Dimensionless, World>(null_displacement_ / Metre), Vector<Dimensionless, World>(u_ / Metre), Vector<Dimensionless, World>(v_ / Metre), Vector<Dimensionless, World>(w_ / Metre), Vector<Dimensionless, World>(a_ / Metre), Dimensionless(0), Dimensionless(1), Sqrt(163), -Sqrt(2), 12 * DBL_EPSILON); TestInnerProductSpace(MultivectorInnerProduct<Dimensionless, Dimensionless, World, 2>, Bivector<Dimensionless, World>(null_displacement_ / Metre), Bivector<Dimensionless, World>(u_ / Metre), Bivector<Dimensionless, World>(v_ / Metre), Bivector<Dimensionless, World>(w_ / Metre), Bivector<Dimensionless, World>(a_ / Metre), Dimensionless(0), Dimensionless(1), Sqrt(163), -Sqrt(2), 12 * DBL_EPSILON); TestInnerProductSpace(MultivectorInnerProduct<Dimensionless, Dimensionless, World, 3>, Trivector<Dimensionless, World>(null_displacement_.x / Metre), Trivector<Dimensionless, World>(u_.y / Metre), Trivector<Dimensionless, World>(v_.z / Metre), Trivector<Dimensionless, World>(w_.x / Metre), Trivector<Dimensionless, World>(a_.y / Metre), Dimensionless(0), Dimensionless(1), Sqrt(163), -Sqrt(2)); } TEST_METHOD(GrassmannAlgebra) { TestAlternatingBilinearMap( Multivectorwedge<Dimensionless, Dimensionless, World, 1, 1>, Vector<Dimensionless, World>(u_ / Metre), Vector<Dimensionless, World>(v_ / Metre), Vector<Dimensionless, World>(w_ / Metre), Vector<Dimensionless, World>(a_ / Metre), Dimensionless(6 * 9)); } }; } // namespace geometry } // namespace principia <commit_msg>We actually test something here now, so there's a tolerance.<commit_after>#include "stdafx.hpp" #include <float.h> #include <CppUnitTest.h> #include <functional> #include "Geometry/Grassmann.hpp" #include "Geometry/R3Element.hpp" #include "Quantities/Astronomy.hpp" #include "Quantities/BIPM.hpp" #include "Quantities/Constants.hpp" #include "Quantities/Dimensionless.hpp" #include "Quantities/ElementaryFunctions.hpp" #include "Quantities/Quantities.hpp" #include "Quantities/SI.hpp" #include "Quantities/UK.hpp" #include "TestUtilities/Algebra.hpp" #include "TestUtilities/ExplicitOperators.hpp" #include "TestUtilities/GeometryComparisons.hpp" #include "TestUtilities/QuantityComparisons.hpp" #include "TestUtilities/TestUtilities.hpp" namespace principia { namespace geometry { using namespace astronomy; using namespace bipm; using namespace constants; using namespace Microsoft::VisualStudio::CppUnitTestFramework; using namespace quantities; using namespace si; using namespace test_utilities; using namespace uk; TEST_CLASS(GrassmannTests) { public: struct World; R3Element<Length> const null_displacement_ = R3Element<Length>(0 * Metre, 0 * Metre, 0 * Metre); R3Element<Length> const u_ = R3Element<Length>(3 * Metre, -42 * Metre, 0 * Metre); R3Element<Length> const v_ = R3Element<Length>(-π * Metre, -e * Metre, -1 * Metre); R3Element<Length> const w_ = R3Element<Length>(2 * Metre, 2 * Metre, 2 * Metre); R3Element<Length> const a_ = R3Element<Length>(1 * Inch, 2 * Foot, 3 * admiralty::Fathom); template<typename LScalar, typename RScalar, typename Frame, int Rank> static Product<LScalar, RScalar> MultivectorInnerProduct( Multivector<LScalar, Frame, Rank> const& left, Multivector<RScalar, Frame, Rank> const& right) { return InnerProduct(left, right); } template<typename LScalar, typename RScalar, typename Frame, int LRank, int RRank> static Multivector<Product<LScalar, RScalar>, Frame, LRank + RRank> Multivectorwedge( Multivector<LScalar, Frame, LRank> const& left, Multivector<RScalar, Frame, RRank> const& right) { return Wedge(left, right); } TEST_METHOD(SpecialOrthogonalLieAlgebra) { TestLieBracket(Commutator<Dimensionless, Dimensionless, World>, Bivector<Dimensionless, World>(u_ / Foot), Bivector<Dimensionless, World>(v_ / Metre), Bivector<Dimensionless, World>(w_ / Rod), Bivector<Dimensionless, World>(a_ / Furlong), Dimensionless(0.42), 128 * DBL_EPSILON); } TEST_METHOD(MixedScalarMultiplication) { TestBilinearMap( Times<Vector<Speed, World>, Inverse<Time>, Vector<Length, World>>, 1 / Second, 1 / JulianYear, Vector<Length, World>(u_), Vector<Length, World>(v_), Dimensionless(42), 2 * DBL_EPSILON); TestBilinearMap( Times<Vector<Speed, World>, Vector<Length, World>, Inverse<Time>>, Vector<Length, World>(w_), Vector<Length, World>(a_), -1 / Day, SpeedOfLight / Parsec, Dimensionless(-π), DBL_EPSILON); Inverse<Time> t = -3 / Second; AssertEqual(t * Vector<Length, World>(u_), Vector<Length, World>(u_) * t); AssertEqual((Vector<Length, World>(v_) * t) / t, Vector<Length, World>(v_)); } TEST_METHOD(VectorSpaces) { TestInnerProductSpace(MultivectorInnerProduct<Length, Length, World, 1>, Vector<Length, World>(null_displacement_), Vector<Length, World>(u_), Vector<Length, World>(v_), Vector<Length, World>(w_), Vector<Length, World>(a_), Dimensionless(0), Dimensionless(1), Sqrt(163), -Sqrt(2), 12 * DBL_EPSILON); TestInnerProductSpace(MultivectorInnerProduct<Length, Length, World, 2>, Bivector<Length, World>(null_displacement_), Bivector<Length, World>(u_), Bivector<Length, World>(v_), Bivector<Length, World>(w_), Bivector<Length, World>(a_), Dimensionless(0), Dimensionless(1), Sqrt(163), -Sqrt(2), 12 * DBL_EPSILON); TestInnerProductSpace(MultivectorInnerProduct<Length, Length, World, 3>, Trivector<Length, World>(null_displacement_.x), Trivector<Length, World>(u_.y), Trivector<Length, World>(v_.z), Trivector<Length, World>(w_.x), Trivector<Length, World>(a_.y), Dimensionless(0), Dimensionless(1), Sqrt(163), -Sqrt(2)); TestInnerProductSpace(MultivectorInnerProduct<Dimensionless, Dimensionless, World, 1>, Vector<Dimensionless, World>(null_displacement_ / Metre), Vector<Dimensionless, World>(u_ / Metre), Vector<Dimensionless, World>(v_ / Metre), Vector<Dimensionless, World>(w_ / Metre), Vector<Dimensionless, World>(a_ / Metre), Dimensionless(0), Dimensionless(1), Sqrt(163), -Sqrt(2), 12 * DBL_EPSILON); TestInnerProductSpace(MultivectorInnerProduct<Dimensionless, Dimensionless, World, 2>, Bivector<Dimensionless, World>(null_displacement_ / Metre), Bivector<Dimensionless, World>(u_ / Metre), Bivector<Dimensionless, World>(v_ / Metre), Bivector<Dimensionless, World>(w_ / Metre), Bivector<Dimensionless, World>(a_ / Metre), Dimensionless(0), Dimensionless(1), Sqrt(163), -Sqrt(2), 12 * DBL_EPSILON); TestInnerProductSpace(MultivectorInnerProduct<Dimensionless, Dimensionless, World, 3>, Trivector<Dimensionless, World>(null_displacement_.x / Metre), Trivector<Dimensionless, World>(u_.y / Metre), Trivector<Dimensionless, World>(v_.z / Metre), Trivector<Dimensionless, World>(w_.x / Metre), Trivector<Dimensionless, World>(a_.y / Metre), Dimensionless(0), Dimensionless(1), Sqrt(163), -Sqrt(2)); } TEST_METHOD(GrassmannAlgebra) { TestAlternatingBilinearMap( Multivectorwedge<Dimensionless, Dimensionless, World, 1, 1>, Vector<Dimensionless, World>(u_ / Metre), Vector<Dimensionless, World>(v_ / Metre), Vector<Dimensionless, World>(w_ / Metre), Vector<Dimensionless, World>(a_ / Metre), Dimensionless(6 * 9), 2 * DBL_EPSILON); } }; } // namespace geometry } // namespace principia <|endoftext|>
<commit_before>/* * Copyright 2015 Milian Wolff <mail@milianw.de> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "flamegraph.h" #include <cmath> #include <QVBoxLayout> #include <QGraphicsScene> #include <QStyleOption> #include <QGraphicsView> #include <QGraphicsRectItem> #include <QWheelEvent> #include <QEvent> #include <QToolTip> #include <QDebug> #include <QAction> #include <ThreadWeaver/ThreadWeaver> #include <KLocalizedString> #include <KColorScheme> class FrameGraphicsItem : public QGraphicsRectItem { public: FrameGraphicsItem(const quint64 cost, const QString& function, FrameGraphicsItem* parent = nullptr); quint64 cost() const; void setCost(quint64 cost); QString function() const; void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = nullptr) override; protected: void hoverEnterEvent(QGraphicsSceneHoverEvent *event) override; void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override; void showToolTip() const; private: quint64 m_cost; QString m_function; bool m_isHovered; }; Q_DECLARE_METATYPE(FrameGraphicsItem*); FrameGraphicsItem::FrameGraphicsItem(const quint64 cost, const QString& function, FrameGraphicsItem* parent) : QGraphicsRectItem(parent) , m_cost(cost) , m_function(function) , m_isHovered(false) { setFlag(QGraphicsItem::ItemIsSelectable); setAcceptHoverEvents(true); } quint64 FrameGraphicsItem::cost() const { return m_cost; } void FrameGraphicsItem::setCost(quint64 cost) { m_cost = cost; } QString FrameGraphicsItem::function() const { return m_function; } void FrameGraphicsItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* /*widget*/) { if (isSelected() || m_isHovered) { auto selectedColor = brush().color(); selectedColor.setAlpha(255); painter->fillRect(rect(), selectedColor); } else { painter->fillRect(rect(), brush()); } const QPen oldPen = painter->pen(); auto pen = oldPen; pen.setColor(brush().color()); if (isSelected()) { pen.setWidth(2); } painter->setPen(pen); painter->drawRect(rect()); painter->setPen(oldPen); const int margin = 4; const int width = rect().width() - 2 * margin; if (width < option->fontMetrics.averageCharWidth() * 6) { // text is too wide for the current LOD, don't paint it return; } const int height = rect().height(); painter->drawText(margin + rect().x(), rect().y(), width, height, Qt::AlignVCenter | Qt::AlignLeft | Qt::TextSingleLine, option->fontMetrics.elidedText(m_function, Qt::ElideRight, width)); } void FrameGraphicsItem::hoverEnterEvent(QGraphicsSceneHoverEvent *event) { QGraphicsRectItem::hoverEnterEvent(event); m_isHovered = true; showToolTip(); } void FrameGraphicsItem::showToolTip() const { // we build the tooltip text on demand, which is much faster than doing that for potentially thousands of items when we load the data QToolTip::showText(QCursor::pos(), i18nc("%1: number of allocations, %2: function label", "%1 allocations in %2 and below.", m_cost, m_function)); } void FrameGraphicsItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) { QGraphicsRectItem::hoverLeaveEvent(event); m_isHovered = false; if (auto parent = static_cast<FrameGraphicsItem*>(parentItem())) { parent->showToolTip(); } } namespace { /** * Generate a brush from the "mem" color space used in upstream FlameGraph.pl */ QBrush brush() { // intern the brushes, to reuse them across items which can be thousands // otherwise we'd end up with dozens of allocations and higher memory consumption static QVector<QBrush> brushes; if (brushes.isEmpty()) { std::generate_n(std::back_inserter(brushes), 100, [] () { return QColor(0, 190 + 50 * qreal(rand()) / RAND_MAX, 210 * qreal(rand()) / RAND_MAX, 125); }); } return brushes.at(rand() % brushes.size()); } /** * Layout the flame graph and hide tiny items. */ void layoutItems(FrameGraphicsItem *parent) { const auto& parentRect = parent->rect(); const auto pos = parentRect.topLeft(); const qreal maxWidth = parentRect.width(); const qreal h = parentRect.height(); const qreal y_margin = 2.; const qreal y = pos.y() - h - y_margin; qreal x = pos.x(); foreach (auto child, parent->childItems()) { auto frameChild = static_cast<FrameGraphicsItem*>(child); const qreal w = maxWidth * double(frameChild->cost()) / parent->cost(); frameChild->setVisible(w > 1); frameChild->setRect(QRectF(x, y, w, h)); layoutItems(frameChild); x += w; } } FrameGraphicsItem* findItemByFunction(const QList<QGraphicsItem*>& items, const QString& function) { foreach (auto item_, items) { auto item = static_cast<FrameGraphicsItem*>(item_); if (item->function() == function) { return item; } } return nullptr; } /** * Convert the top-down graph into a tree of FrameGraphicsItem. */ void toGraphicsItems(const QVector<RowData>& data, FrameGraphicsItem *parent) { foreach (const auto& row, data) { auto item = findItemByFunction(parent->childItems(), row.location->function); if (!item) { item = new FrameGraphicsItem(row.allocations, row.location->function, parent); item->setPen(parent->pen()); item->setBrush(brush()); } else { item->setCost(item->cost() + row.allocations); } toGraphicsItems(row.children, item); } } FrameGraphicsItem* parseData(const QVector<RowData>& topDownData) { double totalCost = 0; foreach(const auto& frame, topDownData) { totalCost += frame.allocations; } KColorScheme scheme(QPalette::Active); const QPen pen(scheme.foreground().color()); auto rootItem = new FrameGraphicsItem(totalCost, i18n("%1 allocations in total", totalCost)); rootItem->setBrush(scheme.background()); rootItem->setPen(pen); toGraphicsItems(topDownData, rootItem); return rootItem; } } FlameGraph::FlameGraph(QWidget* parent, Qt::WindowFlags flags) : QWidget(parent, flags) , m_scene(new QGraphicsScene(this)) , m_view(new QGraphicsView(this)) , m_rootItem(nullptr) , m_selectedItem(nullptr) , m_minRootWidth(0) { qRegisterMetaType<FrameGraphicsItem*>(); setLayout(new QVBoxLayout); m_scene->setItemIndexMethod(QGraphicsScene::NoIndex); m_view->setScene(m_scene); m_view->viewport()->installEventFilter(this); m_view->viewport()->setMouseTracking(true); m_view->setFont(QFont(QStringLiteral("monospace"))); m_view->setContextMenuPolicy(Qt::ActionsContextMenu); auto bottomUpViewAction = new QAction(i18n("Bottom-Down View"), this); bottomUpViewAction->setCheckable(true); connect(bottomUpViewAction, &QAction::toggled, this, [this, bottomUpViewAction] { m_showBottomUpData = bottomUpViewAction->isChecked(); showData(); }); m_view->addAction(bottomUpViewAction); layout()->addWidget(m_view); } FlameGraph::~FlameGraph() = default; bool FlameGraph::eventFilter(QObject* object, QEvent* event) { bool ret = QObject::eventFilter(object, event); if (event->type() == QEvent::MouseButtonRelease) { QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event); if (mouseEvent->button() == Qt::LeftButton) { selectItem(static_cast<FrameGraphicsItem*>(m_view->itemAt(mouseEvent->pos()))); } } else if (event->type() == QEvent::Resize || event->type() == QEvent::Show) { if (!m_rootItem) { showData(); } else { selectItem(m_selectedItem); } } else if (event->type() == QEvent::Hide) { setData(nullptr); } return ret; } void FlameGraph::setTopDownData(const TreeData& topDownData) { m_topDownData = topDownData; if (isVisible()) { showData(); } } void FlameGraph::setBottomUpData(const TreeData& bottomUpData) { m_bottomUpData = bottomUpData; } void FlameGraph::showData() { setData(nullptr); using namespace ThreadWeaver; auto data = m_showBottomUpData ? m_bottomUpData : m_topDownData; stream() << make_job([data, this]() { auto parsedData = parseData(data); QMetaObject::invokeMethod(this, "setData", Qt::QueuedConnection, Q_ARG(FrameGraphicsItem*, parsedData)); }); } void FlameGraph::setData(FrameGraphicsItem* rootItem) { m_scene->clear(); m_rootItem = rootItem; m_selectedItem = rootItem; if (!rootItem) { auto text = m_scene->addText(i18n("generating flame graph...")); m_view->centerOn(text); return; } // layouting needs a root item with a given height, the rest will be overwritten later rootItem->setRect(0, 0, 800, m_view->fontMetrics().height() + 4); m_scene->addItem(rootItem); if (isVisible()) { selectItem(m_rootItem); } } void FlameGraph::selectItem(FrameGraphicsItem* item) { if (!item) { return; } // scale item and its parents to the maximum available width // also hide all siblings of the parent items const auto rootWidth = m_view->viewport()->width() - 40; auto parent = item; while (parent) { auto rect = parent->rect(); rect.setLeft(0); rect.setWidth(rootWidth); parent->setRect(rect); if (parent->parentItem()) { foreach (auto sibling, parent->parentItem()->childItems()) { sibling->setVisible(sibling == parent); } } parent = static_cast<FrameGraphicsItem*>(parent->parentItem()); } // then layout all items below the selected on layoutItems(item); // and make sure it's visible m_view->centerOn(item); m_selectedItem = item; } <commit_msg>Don't descend into children of invisible flamegraph items.<commit_after>/* * Copyright 2015 Milian Wolff <mail@milianw.de> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "flamegraph.h" #include <cmath> #include <QVBoxLayout> #include <QGraphicsScene> #include <QStyleOption> #include <QGraphicsView> #include <QGraphicsRectItem> #include <QWheelEvent> #include <QEvent> #include <QToolTip> #include <QDebug> #include <QAction> #include <ThreadWeaver/ThreadWeaver> #include <KLocalizedString> #include <KColorScheme> class FrameGraphicsItem : public QGraphicsRectItem { public: FrameGraphicsItem(const quint64 cost, const QString& function, FrameGraphicsItem* parent = nullptr); quint64 cost() const; void setCost(quint64 cost); QString function() const; void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = nullptr) override; protected: void hoverEnterEvent(QGraphicsSceneHoverEvent *event) override; void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override; void showToolTip() const; private: quint64 m_cost; QString m_function; bool m_isHovered; }; Q_DECLARE_METATYPE(FrameGraphicsItem*); FrameGraphicsItem::FrameGraphicsItem(const quint64 cost, const QString& function, FrameGraphicsItem* parent) : QGraphicsRectItem(parent) , m_cost(cost) , m_function(function) , m_isHovered(false) { setFlag(QGraphicsItem::ItemIsSelectable); setAcceptHoverEvents(true); } quint64 FrameGraphicsItem::cost() const { return m_cost; } void FrameGraphicsItem::setCost(quint64 cost) { m_cost = cost; } QString FrameGraphicsItem::function() const { return m_function; } void FrameGraphicsItem::paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* /*widget*/) { if (isSelected() || m_isHovered) { auto selectedColor = brush().color(); selectedColor.setAlpha(255); painter->fillRect(rect(), selectedColor); } else { painter->fillRect(rect(), brush()); } const QPen oldPen = painter->pen(); auto pen = oldPen; pen.setColor(brush().color()); if (isSelected()) { pen.setWidth(2); } painter->setPen(pen); painter->drawRect(rect()); painter->setPen(oldPen); const int margin = 4; const int width = rect().width() - 2 * margin; if (width < option->fontMetrics.averageCharWidth() * 6) { // text is too wide for the current LOD, don't paint it return; } const int height = rect().height(); painter->drawText(margin + rect().x(), rect().y(), width, height, Qt::AlignVCenter | Qt::AlignLeft | Qt::TextSingleLine, option->fontMetrics.elidedText(m_function, Qt::ElideRight, width)); } void FrameGraphicsItem::hoverEnterEvent(QGraphicsSceneHoverEvent *event) { QGraphicsRectItem::hoverEnterEvent(event); m_isHovered = true; showToolTip(); } void FrameGraphicsItem::showToolTip() const { // we build the tooltip text on demand, which is much faster than doing that for potentially thousands of items when we load the data QToolTip::showText(QCursor::pos(), i18nc("%1: number of allocations, %2: function label", "%1 allocations in %2 and below.", m_cost, m_function)); } void FrameGraphicsItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) { QGraphicsRectItem::hoverLeaveEvent(event); m_isHovered = false; if (auto parent = static_cast<FrameGraphicsItem*>(parentItem())) { parent->showToolTip(); } } namespace { /** * Generate a brush from the "mem" color space used in upstream FlameGraph.pl */ QBrush brush() { // intern the brushes, to reuse them across items which can be thousands // otherwise we'd end up with dozens of allocations and higher memory consumption static QVector<QBrush> brushes; if (brushes.isEmpty()) { std::generate_n(std::back_inserter(brushes), 100, [] () { return QColor(0, 190 + 50 * qreal(rand()) / RAND_MAX, 210 * qreal(rand()) / RAND_MAX, 125); }); } return brushes.at(rand() % brushes.size()); } /** * Layout the flame graph and hide tiny items. */ void layoutItems(FrameGraphicsItem *parent) { const auto& parentRect = parent->rect(); const auto pos = parentRect.topLeft(); const qreal maxWidth = parentRect.width(); const qreal h = parentRect.height(); const qreal y_margin = 2.; const qreal y = pos.y() - h - y_margin; qreal x = pos.x(); foreach (auto child, parent->childItems()) { auto frameChild = static_cast<FrameGraphicsItem*>(child); const qreal w = maxWidth * double(frameChild->cost()) / parent->cost(); frameChild->setVisible(w > 1); if (frameChild->isVisible()) { frameChild->setRect(QRectF(x, y, w, h)); layoutItems(frameChild); x += w; } } } FrameGraphicsItem* findItemByFunction(const QList<QGraphicsItem*>& items, const QString& function) { foreach (auto item_, items) { auto item = static_cast<FrameGraphicsItem*>(item_); if (item->function() == function) { return item; } } return nullptr; } /** * Convert the top-down graph into a tree of FrameGraphicsItem. */ void toGraphicsItems(const QVector<RowData>& data, FrameGraphicsItem *parent) { foreach (const auto& row, data) { auto item = findItemByFunction(parent->childItems(), row.location->function); if (!item) { item = new FrameGraphicsItem(row.allocations, row.location->function, parent); item->setPen(parent->pen()); item->setBrush(brush()); } else { item->setCost(item->cost() + row.allocations); } toGraphicsItems(row.children, item); } } FrameGraphicsItem* parseData(const QVector<RowData>& topDownData) { double totalCost = 0; foreach(const auto& frame, topDownData) { totalCost += frame.allocations; } KColorScheme scheme(QPalette::Active); const QPen pen(scheme.foreground().color()); auto rootItem = new FrameGraphicsItem(totalCost, i18n("%1 allocations in total", totalCost)); rootItem->setBrush(scheme.background()); rootItem->setPen(pen); toGraphicsItems(topDownData, rootItem); return rootItem; } } FlameGraph::FlameGraph(QWidget* parent, Qt::WindowFlags flags) : QWidget(parent, flags) , m_scene(new QGraphicsScene(this)) , m_view(new QGraphicsView(this)) , m_rootItem(nullptr) , m_selectedItem(nullptr) , m_minRootWidth(0) { qRegisterMetaType<FrameGraphicsItem*>(); setLayout(new QVBoxLayout); m_scene->setItemIndexMethod(QGraphicsScene::NoIndex); m_view->setScene(m_scene); m_view->viewport()->installEventFilter(this); m_view->viewport()->setMouseTracking(true); m_view->setFont(QFont(QStringLiteral("monospace"))); m_view->setContextMenuPolicy(Qt::ActionsContextMenu); auto bottomUpViewAction = new QAction(i18n("Bottom-Down View"), this); bottomUpViewAction->setCheckable(true); connect(bottomUpViewAction, &QAction::toggled, this, [this, bottomUpViewAction] { m_showBottomUpData = bottomUpViewAction->isChecked(); showData(); }); m_view->addAction(bottomUpViewAction); layout()->addWidget(m_view); } FlameGraph::~FlameGraph() = default; bool FlameGraph::eventFilter(QObject* object, QEvent* event) { bool ret = QObject::eventFilter(object, event); if (event->type() == QEvent::MouseButtonRelease) { QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event); if (mouseEvent->button() == Qt::LeftButton) { selectItem(static_cast<FrameGraphicsItem*>(m_view->itemAt(mouseEvent->pos()))); } } else if (event->type() == QEvent::Resize || event->type() == QEvent::Show) { if (!m_rootItem) { showData(); } else { selectItem(m_selectedItem); } } else if (event->type() == QEvent::Hide) { setData(nullptr); } return ret; } void FlameGraph::setTopDownData(const TreeData& topDownData) { m_topDownData = topDownData; if (isVisible()) { showData(); } } void FlameGraph::setBottomUpData(const TreeData& bottomUpData) { m_bottomUpData = bottomUpData; } void FlameGraph::showData() { setData(nullptr); using namespace ThreadWeaver; auto data = m_showBottomUpData ? m_bottomUpData : m_topDownData; stream() << make_job([data, this]() { auto parsedData = parseData(data); QMetaObject::invokeMethod(this, "setData", Qt::QueuedConnection, Q_ARG(FrameGraphicsItem*, parsedData)); }); } void FlameGraph::setData(FrameGraphicsItem* rootItem) { m_scene->clear(); m_rootItem = rootItem; m_selectedItem = rootItem; if (!rootItem) { auto text = m_scene->addText(i18n("generating flame graph...")); m_view->centerOn(text); return; } // layouting needs a root item with a given height, the rest will be overwritten later rootItem->setRect(0, 0, 800, m_view->fontMetrics().height() + 4); m_scene->addItem(rootItem); if (isVisible()) { selectItem(m_rootItem); } } void FlameGraph::selectItem(FrameGraphicsItem* item) { if (!item) { return; } // scale item and its parents to the maximum available width // also hide all siblings of the parent items const auto rootWidth = m_view->viewport()->width() - 40; auto parent = item; while (parent) { auto rect = parent->rect(); rect.setLeft(0); rect.setWidth(rootWidth); parent->setRect(rect); if (parent->parentItem()) { foreach (auto sibling, parent->parentItem()->childItems()) { sibling->setVisible(sibling == parent); } } parent = static_cast<FrameGraphicsItem*>(parent->parentItem()); } // then layout all items below the selected on layoutItems(item); // and make sure it's visible m_view->centerOn(item); m_selectedItem = item; } <|endoftext|>
<commit_before>#include "datarecorder.h" #include <Framework/dataloghelper.h> #include "robotmodule.h" DataRecorder::DataRecorder(RobotModule& module) : module(module) { logger = Log4Qt::Logger::logger("DataRecorder"); connect(&module, SIGNAL(dataChanged(RobotModule*)), this, SLOT(newDataReceived(RobotModule*))); connect(&module, SIGNAL(healthStatusChanged(RobotModule*)), this, SLOT(newDataReceived(RobotModule*))); stream = NULL; file = new QFile(DataLogHelper::getLogDir()+module.getId()+".csv"); fileCount = 0; } void DataRecorder::stopRecording() { this->disconnect(); this->close(); } bool DataRecorder::isChanged(QStringList a, QStringList b) { if (a.size() != b.size()) return true; for(int i=0; i<a.size(); i++) { if (a[i] != b[i]) return true; } return false; } void DataRecorder::open() { QStringList dataKeysNew = module.getDataCopy().keys(); dataKeysNew.sort(); QStringList settingsKeysNew = module.getSettingKeys(); settingsKeysNew.sort(); bool listsChanged = isChanged(dataKeys, dataKeysNew) || isChanged(settingsKeys, settingsKeysNew); if (file->isOpen() && listsChanged) { this->close(); fileCount++; file = new QFile(DataLogHelper::getLogDir()+module.getId()+"_"+QString::number(fileCount)+".csv"); } if (!file->isOpen()) { if (file->exists()) logger->error("File "+ file->fileName()+ " already exists, although it shouldn't!"); // this file should always be a new one. but be sure that no data // is lost, just append everything. if (file->open(QFile::WriteOnly | QIODevice::Append)) { stream = new QTextStream(file); } else { logger->error("Could not open file "+file->fileName()); return; } dataKeys = module.getDataCopy().keys(); dataKeys.sort(); settingsKeys = module.getSettingKeys(); settingsKeys.sort(); *stream << ";time,healthStatus"; foreach (QString key, settingsKeys) { *stream << "," << key; } foreach (QString key, dataKeys) { *stream << "," << key; } *stream << "\r\n"; stream->flush(); } } void DataRecorder::newDataReceived(RobotModule *module) { open(); if (!file->isOpen()) { return; } QDateTime now = QDateTime::currentDateTime(); *stream << now.toTime_t() << "." << now.toString("z") << ","; *stream << module->getHealthStatus().isHealthOk(); // TODO: write health status to different logfile QMap<QString,QVariant> settingsMap; settingsMap = module->getSettingsCopy(); foreach (QString key, settingsKeys) { QVariant value =settingsMap.value(key); if (value.convert(QVariant::Double)) { *stream << "," << value.toDouble(); continue; } value = settingsMap.value(key); if (value.convert(QVariant::Bool)) { *stream << "," << value.toBool(); continue; } } foreach (QString key, dataKeys) { QVariant value = module->getDataValue(key); if (value.convert(QVariant::Double)) { *stream << "," << value.toDouble(); continue; } value = module->getDataValue(key); if (value.convert(QVariant::String) && value.toString() != "false" && value.toString() != "true") { *stream << ",\"" << value.toString() << "\""; continue; } value = module->getDataValue(key); if (value.convert(QVariant::Bool)) { *stream << "," << value.toBool(); continue; } } *stream << "\r\n"; // the app may crash... stream->flush(); } void DataRecorder::close() { logger->debug("Closing data log file for "+module.getId()); if (stream != NULL) { delete stream; stream = NULL; } if (file != NULL) { delete file; file = NULL; } } <commit_msg>fix segfault during closeing<commit_after>#include "datarecorder.h" #include <Framework/dataloghelper.h> #include "robotmodule.h" DataRecorder::DataRecorder(RobotModule& module) : module(module) { logger = Log4Qt::Logger::logger("DataRecorder"); connect(&module, SIGNAL(dataChanged(RobotModule*)), this, SLOT(newDataReceived(RobotModule*))); connect(&module, SIGNAL(healthStatusChanged(RobotModule*)), this, SLOT(newDataReceived(RobotModule*))); stream = NULL; file = new QFile(DataLogHelper::getLogDir()+module.getId()+".csv"); fileCount = 0; } void DataRecorder::stopRecording() { this->disconnect(); this->close(); } bool DataRecorder::isChanged(QStringList a, QStringList b) { if (a.size() != b.size()) return true; for(int i=0; i<a.size(); i++) { if (a[i] != b[i]) return true; } return false; } void DataRecorder::open() { QStringList dataKeysNew = module.getDataCopy().keys(); dataKeysNew.sort(); QStringList settingsKeysNew = module.getSettingKeys(); settingsKeysNew.sort(); bool listsChanged = isChanged(dataKeys, dataKeysNew) || isChanged(settingsKeys, settingsKeysNew); if (file == NULL || (file->isOpen() && listsChanged)) { this->close(); fileCount++; file = new QFile(DataLogHelper::getLogDir()+module.getId()+"_"+QString::number(fileCount)+".csv"); } if (!file->isOpen()) { if (file->exists()) logger->error("File "+ file->fileName()+ " already exists, although it shouldn't!"); // this file should always be a new one. but be sure that no data // is lost, just append everything. if (file->open(QFile::WriteOnly | QIODevice::Append)) { stream = new QTextStream(file); } else { logger->error("Could not open file "+file->fileName()); return; } dataKeys = module.getDataCopy().keys(); dataKeys.sort(); settingsKeys = module.getSettingKeys(); settingsKeys.sort(); *stream << ";time,healthStatus"; foreach (QString key, settingsKeys) { *stream << "," << key; } foreach (QString key, dataKeys) { *stream << "," << key; } *stream << "\r\n"; stream->flush(); } } void DataRecorder::newDataReceived(RobotModule *module) { open(); if (!file->isOpen()) { return; } QDateTime now = QDateTime::currentDateTime(); *stream << now.toTime_t() << "." << now.toString("z") << ","; *stream << module->getHealthStatus().isHealthOk(); // TODO: write health status to different logfile QMap<QString,QVariant> settingsMap; settingsMap = module->getSettingsCopy(); foreach (QString key, settingsKeys) { QVariant value =settingsMap.value(key); if (value.convert(QVariant::Double)) { *stream << "," << value.toDouble(); continue; } value = settingsMap.value(key); if (value.convert(QVariant::Bool)) { *stream << "," << value.toBool(); continue; } } foreach (QString key, dataKeys) { QVariant value = module->getDataValue(key); if (value.convert(QVariant::Double)) { *stream << "," << value.toDouble(); continue; } value = module->getDataValue(key); if (value.convert(QVariant::String) && value.toString() != "false" && value.toString() != "true") { *stream << ",\"" << value.toString() << "\""; continue; } value = module->getDataValue(key); if (value.convert(QVariant::Bool)) { *stream << "," << value.toBool(); continue; } } *stream << "\r\n"; // the app may crash... stream->flush(); } void DataRecorder::close() { logger->debug("Closing data log file for "+module.getId()); if (stream != NULL) { delete stream; stream = NULL; } if (file != NULL) { delete file; file = NULL; } } <|endoftext|>
<commit_before>#include "mainwindow.h" #include "ui_mainwindow.h" #include "playerinfoview.h" #include "jcz/tilefactory.h" #include <QActionGroup> #include <QSettings> #include "player/randomplayer.h" #include "player/montecarloplayer.h" #include "player/montecarloplayer2.h" #include "player/mctsplayer.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); auto actionGroup = new QActionGroup(this); actionGroup->addAction(ui->actionRandom_Tiles); actionGroup->addAction(ui->actionChoose_Tiles); boardUi = new BoardGraphicsScene(&tileFactory, &imgFactory, ui->boardView); game = new Game(&rntp); boardUi->setGame(game); ui->boardView->setScene(boardUi); connect(boardUi, SIGNAL(sceneRectChanged(QRectF)), this, SLOT(recenter(QRectF))); readSettings(); Player * p1 = &RandomPlayer::instance; Player * p2 = new MonteCarloPlayer<>(&tileFactory); Player * p4 = new MonteCarloPlayer<Utilities::SimpleUtility>(&tileFactory); Player * p5 = new MonteCarloPlayer2<>(&tileFactory); Player * p3 = new MCTSPlayer<>(&tileFactory); game->addWatchingPlayer(this); // game->addPlayer(p1); // game->addPlayer(p1); // game->addPlayer(p1); // game->addPlayer(p1); // game->addPlayer(p1); // game->addPlayer(p1); game->addPlayer(p2); // game->addPlayer(p3); // game->addPlayer(p4); game->addPlayer(p5); // game->addPlayer(this); game->newGame(Tile::BaseGame, &tileFactory); new std::thread( [this]() { while (!game->isFinished()) { // Util::sleep(150); game->step(); } } ); // timer = new QTimer(this); // connect(timer, SIGNAL(timeout()), this, SLOT(timeout())); // timer->setInterval(500); // timer->setSingleShot(false); // timer->start(); } MainWindow::~MainWindow() { delete ui; } void MainWindow::newGame(int player, const Game * game) { boardUi->newGame(player, game); if (isSetUp) return; isSetUp = true; qDeleteAll(playerInfos); playerInfos.clear(); QVBoxLayout * l = ui->playerInfoLayout; for (uint i = 0; i < game->getPlayerCount(); ++i) { PlayerInfoView * pi = new PlayerInfoView(i, game, &imgFactory); l->insertWidget(i, pi); connect(this, SIGNAL(updateNeeded()), pi, SLOT(updateView())); playerInfos.push_back(pi); } ui->remainingTiles->setUp(game, &imgFactory); connect(this, SIGNAL(updateNeeded()), ui->remainingTiles, SLOT(updateView())); QSettings settings; settings.beginGroup("games"); int size = settings.beginReadArray("game"); settings.endArray(); settings.beginWriteArray("game"); settings.setArrayIndex(size); settings.setValue("appRevision", APP_REVISION_STR); settings.setValue("qtCompileVersion", QT_VERSION_STR); settings.setValue("qtRuntimeVersionn", qVersion()); settings.beginWriteArray("players"); auto const & players = game->getPlayers(); for (size_t i = 0; i < players.size(); ++i) { settings.setArrayIndex((int)i); settings.setValue("type", players[i]->getTypeName()); } settings.endArray(); settings.endArray(); settings.endGroup(); } void MainWindow::playerMoved(int player, const Tile * tile, const MoveHistoryEntry & move) { emit updateNeeded(); boardUi->playerMoved(player, tile, move); QSettings settings; settings.beginGroup("games"); int size = settings.beginReadArray("game"); settings.endArray(); //game settings.beginWriteArray("game"); settings.setArrayIndex(size-1); int moveSize = settings.beginReadArray("moves"); settings.endArray(); //moves auto const & history = game->getMoveHistory(); settings.beginWriteArray("moves"); for (size_t i = moveSize; i < history.size(); ++i) { settings.setArrayIndex((int)i); MoveHistoryEntry const & m = history[i]; settings.setValue("tile", m.tile); settings.setValue("x", m.move.tileMove.x); settings.setValue("y", m.move.tileMove.x); settings.setValue("orientation", m.move.tileMove.orientation); settings.setValue("meeple", m.move.meepleMove.nodeIndex); } settings.endArray(); //moves settings.endArray(); //game settings.endGroup(); //games } TileMove MainWindow::getTileMove(int player, const Tile * tile, const MoveHistoryEntry & move, const TileMovesType & placements) { return boardUi->getTileMove(player, tile, move, placements); } MeepleMove MainWindow::getMeepleMove(int player, const Tile * tile, const MoveHistoryEntry & move, const MeepleMovesType & possible) { return boardUi->getMeepleMove(player, tile, move, possible); } void MainWindow::endGame() { isSetUp = false; emit updateNeeded(); boardUi->endGame(); QSettings settings; settings.beginGroup("games"); int size = settings.beginReadArray("game"); settings.endArray(); settings.beginWriteArray("game"); settings.setArrayIndex(size-1); settings.beginWriteArray("result"); int playerCount = game->getPlayerCount(); for (int i = 0; i < playerCount; ++i) { settings.setArrayIndex(i); settings.setValue("score", game->getPlayerScore(i)); } settings.endArray(); settings.endArray(); settings.endGroup(); } void MainWindow::closeEvent(QCloseEvent * event) { QSettings settings; settings.beginGroup("mainWindow"); settings.setValue("geometry", saveGeometry()); settings.setValue("windowState", saveState()); QMainWindow::closeEvent(event); settings.endGroup(); } void MainWindow::readSettings() { QSettings settings; settings.beginGroup("mainWindow"); restoreGeometry(settings.value("geometry").toByteArray()); restoreState(settings.value("windowState").toByteArray()); quint64 id = 0; if (settings.contains("appId")) { id = settings.value("appId").value<quint64>(); } else { std::uniform_int_distribution<quint64> distribution; std::default_random_engine generator(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::high_resolution_clock::now().time_since_epoch()).count()); for (int i = 0; i < 5000; ++i) distribution(generator); for (quint64 i = 0, end = distribution(generator); i < end; ++i) distribution(generator); for (uint i = 0; i <= sizeof(id) * 8; ++i) id = (id << 8) ^ distribution(generator); settings.setValue("appId", id); } settings.endGroup(); } void MainWindow::timeout() { game->step(); if (game->isFinished()) timer->stop(); } void MainWindow::recenter(QRectF rect) { ui->boardView->centerOn(rect.center()); } void MainWindow::on_actionRandom_Tiles_toggled(bool checked) { if (checked) game->setNextTileProvider(&rntp); } void MainWindow::on_actionChoose_Tiles_toggled(bool checked) { if (checked) game->setNextTileProvider(ui->remainingTiles); } <commit_msg>Fixed slow startup<commit_after>#include "mainwindow.h" #include "ui_mainwindow.h" #include "playerinfoview.h" #include "jcz/tilefactory.h" #include <QActionGroup> #include <QSettings> #include "player/randomplayer.h" #include "player/montecarloplayer.h" #include "player/montecarloplayer2.h" #include "player/mctsplayer.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); auto actionGroup = new QActionGroup(this); actionGroup->addAction(ui->actionRandom_Tiles); actionGroup->addAction(ui->actionChoose_Tiles); boardUi = new BoardGraphicsScene(&tileFactory, &imgFactory, ui->boardView); game = new Game(&rntp); boardUi->setGame(game); ui->boardView->setScene(boardUi); connect(boardUi, SIGNAL(sceneRectChanged(QRectF)), this, SLOT(recenter(QRectF))); readSettings(); Player * p1 = &RandomPlayer::instance; Player * p2 = new MonteCarloPlayer<>(&tileFactory); Player * p4 = new MonteCarloPlayer<Utilities::SimpleUtility>(&tileFactory); Player * p5 = new MonteCarloPlayer2<>(&tileFactory); Player * p3 = new MCTSPlayer<>(&tileFactory); game->addWatchingPlayer(this); // game->addPlayer(p1); // game->addPlayer(p1); // game->addPlayer(p1); // game->addPlayer(p1); // game->addPlayer(p1); // game->addPlayer(p1); game->addPlayer(p2); // game->addPlayer(p3); // game->addPlayer(p4); game->addPlayer(p5); // game->addPlayer(this); game->newGame(Tile::BaseGame, &tileFactory); new std::thread( [this]() { while (!game->isFinished()) { // Util::sleep(150); game->step(); } } ); // timer = new QTimer(this); // connect(timer, SIGNAL(timeout()), this, SLOT(timeout())); // timer->setInterval(500); // timer->setSingleShot(false); // timer->start(); } MainWindow::~MainWindow() { delete ui; } void MainWindow::newGame(int player, const Game * game) { boardUi->newGame(player, game); if (isSetUp) return; isSetUp = true; qDeleteAll(playerInfos); playerInfos.clear(); QVBoxLayout * l = ui->playerInfoLayout; for (uint i = 0; i < game->getPlayerCount(); ++i) { PlayerInfoView * pi = new PlayerInfoView(i, game, &imgFactory); l->insertWidget(i, pi); connect(this, SIGNAL(updateNeeded()), pi, SLOT(updateView())); playerInfos.push_back(pi); } ui->remainingTiles->setUp(game, &imgFactory); connect(this, SIGNAL(updateNeeded()), ui->remainingTiles, SLOT(updateView())); QSettings settings; settings.beginGroup("games"); int size = settings.beginReadArray("game"); settings.endArray(); settings.beginWriteArray("game"); settings.setArrayIndex(size); settings.setValue("appRevision", APP_REVISION_STR); settings.setValue("qtCompileVersion", QT_VERSION_STR); settings.setValue("qtRuntimeVersionn", qVersion()); settings.beginWriteArray("players"); auto const & players = game->getPlayers(); for (size_t i = 0; i < players.size(); ++i) { settings.setArrayIndex((int)i); settings.setValue("type", players[i]->getTypeName()); } settings.endArray(); settings.endArray(); settings.endGroup(); } void MainWindow::playerMoved(int player, const Tile * tile, const MoveHistoryEntry & move) { emit updateNeeded(); boardUi->playerMoved(player, tile, move); QSettings settings; settings.beginGroup("games"); int size = settings.beginReadArray("game"); settings.endArray(); //game settings.beginWriteArray("game"); settings.setArrayIndex(size-1); int moveSize = settings.beginReadArray("moves"); settings.endArray(); //moves auto const & history = game->getMoveHistory(); settings.beginWriteArray("moves"); for (size_t i = moveSize; i < history.size(); ++i) { settings.setArrayIndex((int)i); MoveHistoryEntry const & m = history[i]; settings.setValue("tile", m.tile); settings.setValue("x", m.move.tileMove.x); settings.setValue("y", m.move.tileMove.x); settings.setValue("orientation", m.move.tileMove.orientation); settings.setValue("meeple", m.move.meepleMove.nodeIndex); } settings.endArray(); //moves settings.endArray(); //game settings.endGroup(); //games } TileMove MainWindow::getTileMove(int player, const Tile * tile, const MoveHistoryEntry & move, const TileMovesType & placements) { return boardUi->getTileMove(player, tile, move, placements); } MeepleMove MainWindow::getMeepleMove(int player, const Tile * tile, const MoveHistoryEntry & move, const MeepleMovesType & possible) { return boardUi->getMeepleMove(player, tile, move, possible); } void MainWindow::endGame() { isSetUp = false; emit updateNeeded(); boardUi->endGame(); QSettings settings; settings.beginGroup("games"); int size = settings.beginReadArray("game"); settings.endArray(); settings.beginWriteArray("game"); settings.setArrayIndex(size-1); settings.beginWriteArray("result"); int playerCount = game->getPlayerCount(); for (int i = 0; i < playerCount; ++i) { settings.setArrayIndex(i); settings.setValue("score", game->getPlayerScore(i)); } settings.endArray(); settings.endArray(); settings.endGroup(); } void MainWindow::closeEvent(QCloseEvent * event) { QSettings settings; settings.beginGroup("mainWindow"); settings.setValue("geometry", saveGeometry()); settings.setValue("windowState", saveState()); QMainWindow::closeEvent(event); settings.endGroup(); } void MainWindow::readSettings() { QSettings settings; settings.beginGroup("mainWindow"); restoreGeometry(settings.value("geometry").toByteArray()); restoreState(settings.value("windowState").toByteArray()); quint64 id = 0; if (settings.contains("appId")) { id = settings.value("appId").value<quint64>(); } else { std::uniform_int_distribution<quint64> distribution; std::default_random_engine generator(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::high_resolution_clock::now().time_since_epoch()).count()); for (int i = 0; i < 5000; ++i) distribution(generator); for (quint64 i = 0, end = distribution(generator) % 1000000; i < end; ++i) distribution(generator); for (uint i = 0; i <= sizeof(id) * 8; ++i) id = (id << 8) ^ distribution(generator); settings.setValue("appId", id); } settings.endGroup(); } void MainWindow::timeout() { game->step(); if (game->isFinished()) timer->stop(); } void MainWindow::recenter(QRectF rect) { ui->boardView->centerOn(rect.center()); } void MainWindow::on_actionRandom_Tiles_toggled(bool checked) { if (checked) game->setNextTileProvider(&rntp); } void MainWindow::on_actionChoose_Tiles_toggled(bool checked) { if (checked) game->setNextTileProvider(ui->remainingTiles); } <|endoftext|>
<commit_before>/* * --------------------------------------------------------------------- * Numenta Platform for Intelligent Computing (NuPIC) * Copyright (C) 2013, Numenta, Inc. Unless you have purchased from * Numenta, Inc. a separate commercial license for this software code, the * following terms and conditions apply: * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see http://www.gnu.org/licenses. * * http://numenta.org/licenses/ * --------------------------------------------------------------------- */ /** @file * Templates implementation for class Grouper */ #ifndef NTA_ZETA1_GROUPER_T_HPP #define NTA_ZETA1_GROUPER_T_HPP #ifdef NUPIC2 #error "Zeta1Grouper is used only by Zeta1Node, which is not part of NuPIC 2" #endif //---------------------------------------------------------------------- namespace nta { //-------------------------------------------------------------------------------- /** * begin2 is not used: we do not output anything in learning mode. */ template <typename InIter, typename OutIter> void Zeta1Grouper::learn(InIter begin1, OutIter, size_type baby_idx) { size_type winnerIndex = size_type(*begin1); tam_.learn(winnerIndex, baby_idx); } //-------------------------------------------------------------------------------- /** * x is the output of the coincidence detector * * If using Time Based Inference ('tbi' set in the constructor), then the inference output * is computed by treating the Time Adjacency Matrix (tam) as a set of cell weights between * "cells" in each group. The intent here is to have the inference output for each group * increase in certainty as we see successive coincidence inputs that are in that group. * * For the TBI computation, each group is assigned 1 cell per coincidence in the * group. Each cell's output is updated after each time step based on the following * equation: * N / \ * cellOut (t) = bottomUp * ( SUM | cellWeight * cellOut (t-1) | + A0 ) * j j i=0 \ ij i / * * The net inference output for each group is then the max of all the cell outputs for * that group. * * Each group has it's own cellWeight matrix, which is produced by extracting the entries * from the TAM corresponding to the coincidences in that group, and then normalizing down * the columns so that the sum of the weights in each column is 1. * * The cellOuts for each group are kept unique from each other - when we have overlapping * groups for example, cell 0's output in group A will not necessarily be the same value * as cell 0's output in group B - this is because we only consider the contribution * from other cells *in the same group* when we peform the above cellOut computation. * * The A0 contribution can be considered as the likelihood that this cell is a start of * the group, or rather, it is the sum contribution from all the cells in the other * groups. Without this factor of course, none of the cell outputs would ever be non-zero. * In the end, the exact value chosen for A0 is immaterial since we are only looking at * the relative output strengths of each group. * * cellOut is a joint pdf over groups and coincidences. */ template <typename InIter, typename OutIter> void Zeta1Grouper::tbiInfer(InIter x, InIter x_end, OutIter y, TBICellOutputsVec::iterator cellOuts) { using namespace std; { // Pre-conditions NTA_ASSERT(!tbiCellWeights_.empty()) << "Grouper::tbiInfer: Cell weights not initialized"; } // End pre-conditions const value_type A0 = (value_type) 0.1; // Compute TBI output. OutIter y_begin = y; TBICellWeightsVec::iterator w = tbiCellWeights_.begin(); Groups::const_iterator g = groups_.begin(), g_end = groups_.end(); size_type g_idx = 0; for (; g != g_end; ++g, ++w, ++cellOuts, ++y, ++g_idx) { // Compute the product of the cellWeights and the current // cell outputs. // w has size g->size X g->size // *cellOuts has size g->size (vector) // tbiBuffer_ is sized to be the size of the largest group // (only the first g->size positions are used here) w->rightVecProd(*cellOuts, tbiBuffer_); // Add A0 to each cell output and multiply by the bottom up input AGroup::const_iterator s = g->begin(), s_end = g->end(); TBICellOutputs::iterator cell = cellOuts->begin(); TBICellOutputs::const_iterator b = tbiBuffer_.begin(); value_type maxCellOut = 0.0; // In case HOT is used, we need to convert the HOT state // index to its original coincidence. If HOT is not used, // getHOTCoincidence reduces to identity. for (; s != s_end; ++s, ++b, ++cell) { size_type c = tam_.getHOTCoincidence(*s); *cell = (*b + A0) * (*(x + c)); maxCellOut = max(*cell, maxCellOut); } *y = maxCellOut; } if(rescaleTBI_) { // Scale the group outputs so that the max is the same as the max of the inputs. // This preserves the relative strength between the group output and blank score // computed by the spatial pooler. value_type maxInValue = * std::max_element(x, x_end); if (maxInValue > (value_type) 0) normalize_max(y_begin, y_begin + groups_.size(), maxInValue); } } //-------------------------------------------------------------------------------- template <typename InIter, typename OutIter> void Zeta1Grouper::infer(InIter x, InIter x_end, OutIter y, size_type tbi_idx) { switch (mode_) { case maxProp: // For each row, find the max corresponding to a non-zero weights_.vecMaxAtNZ(x, y); break; case sumProp: weights_.rightVecProd(x, y); break; case tbi: { if (tbiCellWeights_.empty()) tbi_create_(); tbiInfer(x, x_end, y, tbiCellOutputs_[tbi_idx].begin()); } break; } // switch mode } //-------------------------------------------------------------------------------- } // end namespace nta #endif // NTA_ZETA1_GROUPER_T_HPP <commit_msg>remove Zeta1Grouper header, not used in NUPIC2<commit_after><|endoftext|>
<commit_before>#include "mainwindow.h" #include "ui_mainwindow.h" #include <QMessageBox> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) {} void MainWindow::setIP(QHostAddress myIP, QHostAddress partnerIP) { ui->setupUi(this); ui->ErrorLabel->setText("No error :)"); //Camera and image processer settings CaptureCamera.open(0); if(CaptureCamera.isOpened() == false) { ui->ErrorLabel->setText("Camera Error"); std::cerr<< "Camera open error" <<std::endl; } CamSize = OriginalImageMat.size(); Processer = new ImageProcesser(CamSize); ProcessTimer = new QTimer(this); connect(ProcessTimer, SIGNAL(timeout()), this, SLOT(processVideoAndUpdateQUI())); ProcessTimer->start(100); //tested with QElapsedTimer, 50 was too low... it generated runtime between 60-90 msec //with this we have ~12 msec :) //Add the graphics to graphicsview scene = new QGraphicsScene(0,0,Settings::SCREEN_WIDTH,Settings::SCREEN_HEIGHT,ui->graphicsView); ui->graphicsView->setScene(scene); //Other initializations myRoad = new Road(); lives = Settings::STARTLIFE; ui->MyLifeLCD->display(lives); distance = 0; QObject::connect(myRoad, SIGNAL(sendLifeNumber(int)), this, SLOT(receiveLifeNumber(int))); QObject::connect(myRoad, SIGNAL(sendDistanceNumber(int)), this, SLOT(receiveDistanceNumber(int))); QObject::connect(myRoad, SIGNAL(stopGame()), this, SLOT(lose())); scene->addItem(myRoad); //Start the game QObject::connect(&timer, SIGNAL(timeout()), scene, SLOT(advance())); MyIpAddr=myIP; ui->MyIP->setText("My IP: " + MyIpAddr.toString()); PartnerIpAddr=partnerIP; ui->PartnerIP->setText("Partner IP: " + PartnerIpAddr.toString()); n = new Network(); n->setIp(MyIpAddr,PartnerIpAddr); n->startBinding(); QObject::connect(n, SIGNAL(receivedImage(QImage)), this, SLOT(receiveNetworkImage(QImage))); gameStarted = false; this->show(); } void MainWindow::receiveLifeNumber(int i) { lives = i; if(lives>=0) ui->MyLifeLCD->display(lives); } void MainWindow::receiveDistanceNumber(int i) { distance = i; ui->MyDistLCD->display(distance); } void MainWindow::lose(){ timer.stop(); QMessageBox::StandardButton reply; reply = QMessageBox::question(this, "Rematch", "Would you like to restart the game?", QMessageBox::Yes|QMessageBox::No); if (reply == QMessageBox::Yes) { restart(); } else { closeVideoStream(); close(); exit(0); } } void MainWindow::processVideoAndUpdateQUI() { ProcUpdateElapsedTime.start(); CaptureCamera.read(OriginalImageMat); if (OriginalImageMat.empty()) return; cv::resize(OriginalImageMat, ResizedImageMat, cv::Size(352,220), 0, 0, cv::INTER_CUBIC); //resizing the image to fit in the UI cv::flip(ResizedImageMat, ResizedImageMat, 1); //eliminating the mirror effect //Add the picture to the processer int move = Processer->getMove(ResizedImageMat); //std::cout << "move: " << move <<std::endl; //Move the car if(prevmove == 0) { myRoad->moveCar(move); } prevmove = move; cv::cvtColor(ResizedImageMat, ResizedImageMat, CV_BGR2RGB); //converting the image to RGB cv::rectangle(ResizedImageMat,cv::Rect(0, 0, 100, 130),cv::Scalar(200)); cv::rectangle(ResizedImageMat,cv::Rect(250,0,102,130),cv::Scalar(200)); QImage OriginalImage((uchar*)ResizedImageMat.data, ResizedImageMat.cols, ResizedImageMat.rows, ResizedImageMat.step, QImage::Format_RGB888); //Creating the QImage for the label NetworkSendImage = OriginalImage; NetworkSendImage = NetworkSendImage.scaledToHeight(165); ui->MyVideoLabel->setPixmap(QPixmap::fromImage(OriginalImage)); //Sending number of lives and distance embedded in the image NetworkSendImage.setText("lives", QString::number(lives)); NetworkSendImage.setText("distance", QString::number(distance)); n->sendData(NetworkSendImage); //sending the image over the network if(lives >=0) { lose(); } // std::cerr << "processVideoAndUpdateQUI() elapsed time: " << ProcUpdateElapsedTime.elapsed() << " msec" << std::endl << std::endl; } //Public slot that receives the image from the networking thread void MainWindow::receiveNetworkImage(QImage q) { if (!gameStarted) { //Start the game timer.start(Settings::FREQUENCY); gameStarted = true; } ui->NetworkCamVideo->setPixmap(QPixmap::fromImage(q)); //putting the received image to the gui std::cout << "network lives: " << q.text("lives").toInt() << std::endl; if(q.text("lives").toInt()>=0) ui->NetworkLifeLCD->display(q.text("lives")); else{ NetworkSendImage.setText("lives", QString::number(-1)); NetworkSendImage.setText("distance", QString::number(distance)); n->sendData(NetworkSendImage); lose(); } //else timer.stop(); ui->NetworkDistLCD->display(q.text("distance")); } MainWindow::~MainWindow() { delete ui; delete ProcessTimer; delete Processer; delete n; delete scene; delete myCar; delete myRoad; } void MainWindow::closeVideoStream() { ProcessTimer->stop(); //std::cout << "Video process timer stopped" <<std::endl; CaptureCamera.release(); //std::cout << "Camera released" <<std::endl; } void MainWindow::restart() { delete myRoad; myRoad = new Road(); lives = Settings::STARTLIFE; ui->MyLifeLCD->display(lives); distance = 0; ui->MyDistLCD->display(distance); scene->addItem(myRoad); timer.start(Settings::FREQUENCY); } // Kezeli a billentyűlenyomást void MainWindow::keyPressEvent(QKeyEvent *event){ switch (event->key()) { case Qt::Key_Right: myRoad->moveCar(1); //turn right; break; case Qt::Key_Left: myRoad->moveCar(-1); //turn left; break; case Qt::Key_Escape: closeVideoStream(); close(); exit(0); break; default: break; } } <commit_msg>typo fixed<commit_after>#include "mainwindow.h" #include "ui_mainwindow.h" #include <QMessageBox> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) {} void MainWindow::setIP(QHostAddress myIP, QHostAddress partnerIP) { ui->setupUi(this); ui->ErrorLabel->setText("No error :)"); //Camera and image processer settings CaptureCamera.open(0); if(CaptureCamera.isOpened() == false) { ui->ErrorLabel->setText("Camera Error"); std::cerr<< "Camera open error" <<std::endl; } CamSize = OriginalImageMat.size(); Processer = new ImageProcesser(CamSize); ProcessTimer = new QTimer(this); connect(ProcessTimer, SIGNAL(timeout()), this, SLOT(processVideoAndUpdateQUI())); ProcessTimer->start(100); //tested with QElapsedTimer, 50 was too low... it generated runtime between 60-90 msec //with this we have ~12 msec :) //Add the graphics to graphicsview scene = new QGraphicsScene(0,0,Settings::SCREEN_WIDTH,Settings::SCREEN_HEIGHT,ui->graphicsView); ui->graphicsView->setScene(scene); //Other initializations myRoad = new Road(); lives = Settings::STARTLIFE; ui->MyLifeLCD->display(lives); distance = 0; QObject::connect(myRoad, SIGNAL(sendLifeNumber(int)), this, SLOT(receiveLifeNumber(int))); QObject::connect(myRoad, SIGNAL(sendDistanceNumber(int)), this, SLOT(receiveDistanceNumber(int))); QObject::connect(myRoad, SIGNAL(stopGame()), this, SLOT(lose())); scene->addItem(myRoad); //Start the game QObject::connect(&timer, SIGNAL(timeout()), scene, SLOT(advance())); MyIpAddr=myIP; ui->MyIP->setText("My IP: " + MyIpAddr.toString()); PartnerIpAddr=partnerIP; ui->PartnerIP->setText("Partner IP: " + PartnerIpAddr.toString()); n = new Network(); n->setIp(MyIpAddr,PartnerIpAddr); n->startBinding(); QObject::connect(n, SIGNAL(receivedImage(QImage)), this, SLOT(receiveNetworkImage(QImage))); gameStarted = false; this->show(); } void MainWindow::receiveLifeNumber(int i) { lives = i; if(lives>=0) ui->MyLifeLCD->display(lives); } void MainWindow::receiveDistanceNumber(int i) { distance = i; ui->MyDistLCD->display(distance); } void MainWindow::lose(){ timer.stop(); QMessageBox::StandardButton reply; reply = QMessageBox::question(this, "Rematch", "Would you like to restart the game?", QMessageBox::Yes|QMessageBox::No); if (reply == QMessageBox::Yes) { restart(); } else { closeVideoStream(); close(); exit(0); } } void MainWindow::processVideoAndUpdateQUI() { ProcUpdateElapsedTime.start(); CaptureCamera.read(OriginalImageMat); if (OriginalImageMat.empty()) return; cv::resize(OriginalImageMat, ResizedImageMat, cv::Size(352,220), 0, 0, cv::INTER_CUBIC); //resizing the image to fit in the UI cv::flip(ResizedImageMat, ResizedImageMat, 1); //eliminating the mirror effect //Add the picture to the processer int move = Processer->getMove(ResizedImageMat); //std::cout << "move: " << move <<std::endl; //Move the car if(prevmove == 0) { myRoad->moveCar(move); } prevmove = move; cv::cvtColor(ResizedImageMat, ResizedImageMat, CV_BGR2RGB); //converting the image to RGB cv::rectangle(ResizedImageMat,cv::Rect(0, 0, 100, 130),cv::Scalar(200)); cv::rectangle(ResizedImageMat,cv::Rect(250,0,102,130),cv::Scalar(200)); QImage OriginalImage((uchar*)ResizedImageMat.data, ResizedImageMat.cols, ResizedImageMat.rows, ResizedImageMat.step, QImage::Format_RGB888); //Creating the QImage for the label NetworkSendImage = OriginalImage; NetworkSendImage = NetworkSendImage.scaledToHeight(165); ui->MyVideoLabel->setPixmap(QPixmap::fromImage(OriginalImage)); //Sending number of lives and distance embedded in the image NetworkSendImage.setText("lives", QString::number(lives)); NetworkSendImage.setText("distance", QString::number(distance)); n->sendData(NetworkSendImage); //sending the image over the network if(lives < 0) { lose(); } // std::cerr << "processVideoAndUpdateQUI() elapsed time: " << ProcUpdateElapsedTime.elapsed() << " msec" << std::endl << std::endl; } //Public slot that receives the image from the networking thread void MainWindow::receiveNetworkImage(QImage q) { if (!gameStarted) { //Start the game timer.start(Settings::FREQUENCY); gameStarted = true; } ui->NetworkCamVideo->setPixmap(QPixmap::fromImage(q)); //putting the received image to the gui std::cout << "network lives: " << q.text("lives").toInt() << std::endl; if(q.text("lives").toInt()>=0) ui->NetworkLifeLCD->display(q.text("lives")); else{ lose(); } //else timer.stop(); ui->NetworkDistLCD->display(q.text("distance")); } MainWindow::~MainWindow() { delete ui; delete ProcessTimer; delete Processer; delete n; delete scene; delete myCar; delete myRoad; } void MainWindow::closeVideoStream() { ProcessTimer->stop(); //std::cout << "Video process timer stopped" <<std::endl; CaptureCamera.release(); //std::cout << "Camera released" <<std::endl; } void MainWindow::restart() { delete myRoad; myRoad = new Road(); lives = Settings::STARTLIFE; ui->MyLifeLCD->display(lives); distance = 0; ui->MyDistLCD->display(distance); scene->addItem(myRoad); timer.start(Settings::FREQUENCY); } // Kezeli a billentyűlenyomást void MainWindow::keyPressEvent(QKeyEvent *event){ switch (event->key()) { case Qt::Key_Right: myRoad->moveCar(1); //turn right; break; case Qt::Key_Left: myRoad->moveCar(-1); //turn left; break; case Qt::Key_Escape: closeVideoStream(); close(); exit(0); break; default: break; } } <|endoftext|>
<commit_before>/*----------------------------------------------------------------------------- This source file is a part of Hopsan Copyright (c) 2009 to present year, Hopsan Group This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. For license details and information about the Hopsan Group see the files GPLv3 and HOPSANGROUP in the Hopsan source code root directory For author and contributor information see the AUTHORS file -----------------------------------------------------------------------------*/ #ifndef OPTIMIZATIONTESTFUNCTION6D_HPP_INCLUDED #define OPTIMIZATIONTESTFUNCTION6D_HPP_INCLUDED #include "ComponentEssentials.h" #include "ComponentUtilities/AuxiliarySimulationFunctions.h" #include <math.h> namespace hopsan { class OptimizationTestFunction6D : public ComponentSignal { private: double *mpX1, *mpX2, *mpX3, *mpX4, *mpX5, *mpX6, *mpOut; int mFunc; public: static Component *Creator() { return new OptimizationTestFunction6D(); } void configure() { // Add ports to the component addInputVariable("x1", "", "", 0.0, &mpX1); addInputVariable("x2", "", "", 0.0, &mpX2); addInputVariable("x3", "", "", 0.0, &mpX3); addInputVariable("x4", "", "", 0.0, &mpX4); addInputVariable("x5", "", "", 0.0, &mpX5); addInputVariable("x6", "", "", 0.0, &mpX6); addOutputVariable("out", "", "", 0.0, &mpOut); std::vector<HString> functions; functions.push_back("Rosenbrock Function"); functions.push_back("Sphere Function"); functions.push_back("Styblinski-Tang Function"); addConditionalConstant("function", "Test Function", functions, mFunc); } void initialize() { simulateOneTimestep(); } void simulateOneTimestep() { double x1 = (*mpX1); double x2 = (*mpX2); double x3 = (*mpX3); double x4 = (*mpX4); double x5 = (*mpX5); double x6 = (*mpX6); switch(mFunc) { case 0: (*mpOut) = rosenbrock(x1,x2,x3,x4,x5,x6); break; case 1: (*mpOut) = sphere(x1,x2,x3,x4,x5,x6); break; case 2: (*mpOut) = styblinskiTang(x1,x2,x3,x4,x5,x6); break; default: (*mpOut) = 0; break; } } inline double rosenbrock(const double x1, const double x2, const double x3, const double x4, const double x5, const double x6) const { return (1.0-x1)*(1.0-x1) + 100.0*(x2-x1*x1)*(x2-x1*x1) + (1.0-x2)*(1.0-x2) + 100.0*(x3-x2*x2)*(x3-x2*x2) + (1.0-x3)*(1.0-x3) + 100.0*(x4-x3*x3)*(x4-x3*x3) + (1.0-x4)*(1.0-x4) + 100.0*(x5-x4*x4)*(x5-x4*x4) + (1.0-x5)*(1.0-x5) + 100.0*(1-x5*x5)*(1-x5*x5); } inline double sphere(const double x1, const double x2, const double x3, const double x4, const double x5, const double x6) const { return x1*x1+x2*x2+x3*x3+x4*x4+x5*x5+x6*x6; } inline double styblinskiTang(const double x1, const double x2, const double x3, const double x4, const double x5, const double x6) const { return (x1*x1*x1*x1-16.0*x1*x1+5.0*x1 + x2*x2*x2*x2-16.0*x2*x2+5.0*x2 + x3*x3*x3*x3-16.0*x3*x3+5.0*x3 + x4*x4*x4*x4-16.0*x4*x4+5.0*x4 + x5*x5*x5*x5-16.0*x5*x5+5.0*x5 + x6*x6*x6*x6-16.0*x6*x6+5.0*x6)/2.0; } }; } #endif //OPTIMIZATIONTESTFUNCTION6D_HPP_INCLUDED <commit_msg>Fixed error in Rosenbrock test function 6D.<commit_after>/*----------------------------------------------------------------------------- This source file is a part of Hopsan Copyright (c) 2009 to present year, Hopsan Group This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. For license details and information about the Hopsan Group see the files GPLv3 and HOPSANGROUP in the Hopsan source code root directory For author and contributor information see the AUTHORS file -----------------------------------------------------------------------------*/ #ifndef OPTIMIZATIONTESTFUNCTION6D_HPP_INCLUDED #define OPTIMIZATIONTESTFUNCTION6D_HPP_INCLUDED #include "ComponentEssentials.h" #include "ComponentUtilities/AuxiliarySimulationFunctions.h" #include <math.h> namespace hopsan { class OptimizationTestFunction6D : public ComponentSignal { private: double *mpX1, *mpX2, *mpX3, *mpX4, *mpX5, *mpX6, *mpOut; int mFunc; public: static Component *Creator() { return new OptimizationTestFunction6D(); } void configure() { // Add ports to the component addInputVariable("x1", "", "", 0.0, &mpX1); addInputVariable("x2", "", "", 0.0, &mpX2); addInputVariable("x3", "", "", 0.0, &mpX3); addInputVariable("x4", "", "", 0.0, &mpX4); addInputVariable("x5", "", "", 0.0, &mpX5); addInputVariable("x6", "", "", 0.0, &mpX6); addOutputVariable("out", "", "", 0.0, &mpOut); std::vector<HString> functions; functions.push_back("Rosenbrock Function"); functions.push_back("Sphere Function"); functions.push_back("Styblinski-Tang Function"); addConditionalConstant("function", "Test Function", functions, mFunc); } void initialize() { simulateOneTimestep(); } void simulateOneTimestep() { double x1 = (*mpX1); double x2 = (*mpX2); double x3 = (*mpX3); double x4 = (*mpX4); double x5 = (*mpX5); double x6 = (*mpX6); switch(mFunc) { case 0: (*mpOut) = rosenbrock(x1,x2,x3,x4,x5,x6); break; case 1: (*mpOut) = sphere(x1,x2,x3,x4,x5,x6); break; case 2: (*mpOut) = styblinskiTang(x1,x2,x3,x4,x5,x6); break; default: (*mpOut) = 0; break; } } inline double rosenbrock(const double x1, const double x2, const double x3, const double x4, const double x5, const double x6) const { return (1.0-x1)*(1.0-x1) + 100.0*(x2-x1*x1)*(x2-x1*x1) + (1.0-x2)*(1.0-x2) + 100.0*(x3-x2*x2)*(x3-x2*x2) + (1.0-x3)*(1.0-x3) + 100.0*(x4-x3*x3)*(x4-x3*x3) + (1.0-x4)*(1.0-x4) + 100.0*(x5-x4*x4)*(x5-x4*x4) + (1.0-x5)*(1.0-x5) + 100.0*(x6-x5*x5)*(x6-x5*x5); } inline double sphere(const double x1, const double x2, const double x3, const double x4, const double x5, const double x6) const { return x1*x1+x2*x2+x3*x3+x4*x4+x5*x5+x6*x6; } inline double styblinskiTang(const double x1, const double x2, const double x3, const double x4, const double x5, const double x6) const { return (x1*x1*x1*x1-16.0*x1*x1+5.0*x1 + x2*x2*x2*x2-16.0*x2*x2+5.0*x2 + x3*x3*x3*x3-16.0*x3*x3+5.0*x3 + x4*x4*x4*x4-16.0*x4*x4+5.0*x4 + x5*x5*x5*x5-16.0*x5*x5+5.0*x5 + x6*x6*x6*x6-16.0*x6*x6+5.0*x6)/2.0; } }; } #endif //OPTIMIZATIONTESTFUNCTION6D_HPP_INCLUDED <|endoftext|>
<commit_before>/*********************************************************************** KNotes support for OpenSync kdepim-sync plugin Copyright (C) 2004 Conectiva S. A. 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; 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 OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS SOFTWARE IS DISCLAIMED. *************************************************************************/ /** @file * * @autor Eduardo Pereira Habkost <ehabkost@conectiva.com.br> * * This module implements the access to the KDE 3.2 Notes, that are * stored on KGlobal::dirs()->saveLocation( "data" , "knotes/" ) + "notes.ics" * * TODO: Check how notes are stored on KDE 3.3/3.4, and use the right interface. * (http://www.opensync.org/ticket/34) */ #include <libkcal/calendarlocal.h> #include <libkcal/icalformat.h> #include <kglobal.h> #include <kstandarddirs.h> #include <kio/netaccess.h> #include <klocale.h> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include "knotes.h" extern "C" { #include <opensync/opensync-xml.h> } KNotesDataSource::KNotesDataSource(OSyncMember *m, OSyncHashTable *h) :member(m), hashtable(h) { } bool KNotesDataSource::connect(OSyncContext *ctx) { // Terminate knotes because we will change its data // Yes, it is _very_ ugly //FIXME: use dcop programming interface, not the commandline utility if (!system("dcop knotes MainApplication-Interface quit")) /* Restart knotes later */ knotesWasRunning = true; else knotesWasRunning = false; calendar = new KCal::CalendarLocal; if (!calendar) { osync_context_report_error(ctx, OSYNC_ERROR_INITIALIZATION, "Couldn't allocate calendar object"); } if (!calendar->load(KGlobal::dirs()->saveLocation( "data" , "knotes/" ) + "notes.ics")) { osync_context_report_error(ctx, OSYNC_ERROR_FILE_NOT_FOUND, "Couldn't load notes"); } return true; } /** Quick hack to avoid using KIO::NetAccess (that needs a KApplication instance */ static bool copy_file(const char *from, const char *to) { int f1 = open(from, O_RDONLY); if (f1 < 0) return false; int f2 = open(to, O_WRONLY); if (f2 < 0) { close(f1); return false; } char buf[1024]; int ret; bool result = true; for (;;) { ret = read(f1, buf, 1024); if (ret == 0) break; if (ret < 0) { if (errno == EINTR) continue; result = false; break; } int wret = write(f2, buf, ret); if (wret < ret) { result = false; break; } } close(f1); close(f2); return result; } bool KNotesDataSource::saveNotes(OSyncContext *ctx) { // shamelessly copied from KNotes source code QString file = KGlobal::dirs()->saveLocation( "data" , "knotes/" ) + "notes.ics"; QString backup = file + "~"; // if the backup fails don't even try to save the current notes // (might just destroy the file that's already there) if ( !copy_file(file, backup) ) { osync_context_report_error(ctx, OSYNC_ERROR_IO_ERROR, i18n("Unable to save the notes backup to " "%1! Check that there is sufficient " "disk space!").arg( backup ) ); return false; } else if ( !calendar->save( file, new KCal::ICalFormat() ) ) { osync_context_report_error(ctx, OSYNC_ERROR_IO_ERROR, i18n("Unable to save the notes to %1! " "Check that there is sufficient disk space." "There should be a backup in %2 " "though.").arg( file ).arg( backup ) ); return false; } return true; } bool KNotesDataSource::disconnect(OSyncContext *ctx) { if (!saveNotes(ctx)) return false; delete calendar; calendar = NULL; // FIXME: ugly, but necessary if (knotesWasRunning) system("knotes"); return true; } static QString calc_hash(const KCal::Journal *note) { QDateTime d = note->lastModified(); if (!d.isValid()) d = QDateTime::currentDateTime(); /*FIXME: not i18ned string */ return d.toString(); } bool KNotesDataSource::get_changeinfo(OSyncContext *ctx) { KCal::Journal::List notes = calendar->journals(); for (KCal::Journal::List::ConstIterator i = notes.begin(); i != notes.end(); i++) { osync_debug("knotes", 4, "Note summary: %s", (const char*)(*i)->summary().local8Bit()); osync_debug("knotes", 4, "Note contents:\n%s\n====", (const char*)(*i)->description().local8Bit()); QString uid = (*i)->uid(); QString hash = calc_hash(*i); // Create osxml doc containing the note xmlDoc *doc = xmlNewDoc((const xmlChar*)"1.0"); xmlNode *root = osxml_node_add_root(doc, "note"); OSyncXMLEncoding enc; enc.encoding = OSXML_8BIT; enc.charset = OSXML_UTF8; // Set the right attributes xmlNode *sum = xmlNewChild(root, NULL, (const xmlChar*)"", NULL); QCString utf8str = (*i)->summary().utf8(); osxml_node_set(sum, "Summary", utf8str, enc); xmlNode *body = xmlNewChild(root, NULL, (const xmlChar*)"", NULL); utf8str = (*i)->description().utf8(); osxml_node_set(body, "Body", utf8str, enc); // initialize the change object OSyncChange *chg = osync_change_new(); osync_change_set_uid(chg, uid.local8Bit()); osync_change_set_member(chg, member); // object type and format osync_change_set_objtype_string(chg, "note"); osync_change_set_objformat_string(chg, "xml-note"); osync_change_set_data(chg, (char*)doc, sizeof(doc), 1); //XXX: workaround to a bug on osync_change_multiply_master: // convert it to vnote OSyncFormatEnv *env = osync_member_get_format_env(member); OSyncError *e = NULL; if (!osync_change_convert_fmtname(env, chg, "vnote11", &e)) { osync_context_report_error(ctx, OSYNC_ERROR_CONVERT, "Error converting data to vnote: %s", osync_error_print(&e)); return false; } // Use the hash table to check if the object // needs to be reported osync_change_set_hash(chg, hash.data()); if (osync_hashtable_detect_change(hashtable, chg)) { osync_context_report_change(ctx, chg); osync_hashtable_update_hash(hashtable, chg); } } return true; } void KNotesDataSource::get_data(OSyncContext *ctx, OSyncChange *) { osync_context_report_error(ctx, OSYNC_ERROR_NOT_SUPPORTED, "Not implemented yet"); } bool KNotesDataSource::__access(OSyncContext *ctx, OSyncChange *chg) { OSyncChangeType type = osync_change_get_changetype(chg); QString uid = osync_change_get_uid(chg); if (type != CHANGE_DELETED) { // Get osxml data xmlDoc *doc = (xmlDoc*)osync_change_get_data(chg); xmlNode *root = osxml_node_get_root(doc, "note", NULL); if (!root) { osync_context_report_error(ctx, OSYNC_ERROR_CONVERT, "Invalid data"); return false; } QString summary = osxml_find_node(root, "Summary"); QString body = osxml_find_node(root, "Body"); KCal::Journal *j = calendar->journal(uid); if (type == CHANGE_MODIFIED && !j) type = CHANGE_ADDED; QString hash, uid; // end of the ugly-format parsing switch (type) { case CHANGE_ADDED: j = new KCal::Journal; j->setUid(uid); j->setSummary(summary); j->setDescription(body); hash = calc_hash(j); calendar->addJournal(j); uid = j->uid(); osync_change_set_uid(chg, uid); osync_change_set_hash(chg, hash); break; case CHANGE_MODIFIED: j->setSummary(summary); j->setDescription(body); hash = calc_hash(j); osync_change_set_hash(chg, hash); break; default: osync_context_report_error(ctx, OSYNC_ERROR_NOT_SUPPORTED, "Invalid change type"); return false; } } else { KCal::Journal *j = calendar->journal(uid); if (j) { calendar->deleteJournal(j); } } return true; } bool KNotesDataSource::access(OSyncContext *ctx, OSyncChange *chg) { if (!__access(ctx, chg)) return false; osync_context_report_success(ctx); return true; } bool KNotesDataSource::commit_change(OSyncContext *ctx, OSyncChange *chg) { if (!__access(ctx, chg)) return false; osync_hashtable_update_hash(hashtable, chg); osync_context_report_success(ctx); return true; } <commit_msg>Report errors properly. It was crashing if an error occured on when loading the notes<commit_after>/*********************************************************************** KNotes support for OpenSync kdepim-sync plugin Copyright (C) 2004 Conectiva S. A. 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; 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 OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS SOFTWARE IS DISCLAIMED. *************************************************************************/ /** @file * * @autor Eduardo Pereira Habkost <ehabkost@conectiva.com.br> * * This module implements the access to the KDE 3.2 Notes, that are * stored on KGlobal::dirs()->saveLocation( "data" , "knotes/" ) + "notes.ics" * * TODO: Check how notes are stored on KDE 3.3/3.4, and use the right interface. * (http://www.opensync.org/ticket/34) */ #include <libkcal/calendarlocal.h> #include <libkcal/icalformat.h> #include <kglobal.h> #include <kstandarddirs.h> #include <kio/netaccess.h> #include <klocale.h> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include "knotes.h" extern "C" { #include <opensync/opensync-xml.h> } KNotesDataSource::KNotesDataSource(OSyncMember *m, OSyncHashTable *h) :member(m), hashtable(h) { } bool KNotesDataSource::connect(OSyncContext *ctx) { // Terminate knotes because we will change its data // Yes, it is _very_ ugly //FIXME: use dcop programming interface, not the commandline utility if (!system("dcop knotes MainApplication-Interface quit")) /* Restart knotes later */ knotesWasRunning = true; else knotesWasRunning = false; calendar = new KCal::CalendarLocal; if (!calendar) { osync_context_report_error(ctx, OSYNC_ERROR_INITIALIZATION, "Couldn't allocate calendar object"); return false; } if (!calendar->load(KGlobal::dirs()->saveLocation( "data" , "knotes/" ) + "notes.ics")) { osync_context_report_error(ctx, OSYNC_ERROR_FILE_NOT_FOUND, "Couldn't load notes"); return false; } return true; } /** Quick hack to avoid using KIO::NetAccess (that needs a KApplication instance */ static bool copy_file(const char *from, const char *to) { int f1 = open(from, O_RDONLY); if (f1 < 0) return false; int f2 = open(to, O_WRONLY); if (f2 < 0) { close(f1); return false; } char buf[1024]; int ret; bool result = true; for (;;) { ret = read(f1, buf, 1024); if (ret == 0) break; if (ret < 0) { if (errno == EINTR) continue; result = false; break; } int wret = write(f2, buf, ret); if (wret < ret) { result = false; break; } } close(f1); close(f2); return result; } bool KNotesDataSource::saveNotes(OSyncContext *ctx) { // shamelessly copied from KNotes source code QString file = KGlobal::dirs()->saveLocation( "data" , "knotes/" ) + "notes.ics"; QString backup = file + "~"; // if the backup fails don't even try to save the current notes // (might just destroy the file that's already there) if ( !copy_file(file, backup) ) { osync_context_report_error(ctx, OSYNC_ERROR_IO_ERROR, i18n("Unable to save the notes backup to " "%1! Check that there is sufficient " "disk space!").arg( backup ) ); return false; } else if ( !calendar->save( file, new KCal::ICalFormat() ) ) { osync_context_report_error(ctx, OSYNC_ERROR_IO_ERROR, i18n("Unable to save the notes to %1! " "Check that there is sufficient disk space." "There should be a backup in %2 " "though.").arg( file ).arg( backup ) ); return false; } return true; } bool KNotesDataSource::disconnect(OSyncContext *ctx) { if (!saveNotes(ctx)) return false; delete calendar; calendar = NULL; // FIXME: ugly, but necessary if (knotesWasRunning) system("knotes"); return true; } static QString calc_hash(const KCal::Journal *note) { QDateTime d = note->lastModified(); if (!d.isValid()) d = QDateTime::currentDateTime(); /*FIXME: not i18ned string */ return d.toString(); } bool KNotesDataSource::get_changeinfo(OSyncContext *ctx) { KCal::Journal::List notes = calendar->journals(); for (KCal::Journal::List::ConstIterator i = notes.begin(); i != notes.end(); i++) { osync_debug("knotes", 4, "Note summary: %s", (const char*)(*i)->summary().local8Bit()); osync_debug("knotes", 4, "Note contents:\n%s\n====", (const char*)(*i)->description().local8Bit()); QString uid = (*i)->uid(); QString hash = calc_hash(*i); // Create osxml doc containing the note xmlDoc *doc = xmlNewDoc((const xmlChar*)"1.0"); xmlNode *root = osxml_node_add_root(doc, "note"); OSyncXMLEncoding enc; enc.encoding = OSXML_8BIT; enc.charset = OSXML_UTF8; // Set the right attributes xmlNode *sum = xmlNewChild(root, NULL, (const xmlChar*)"", NULL); QCString utf8str = (*i)->summary().utf8(); osxml_node_set(sum, "Summary", utf8str, enc); xmlNode *body = xmlNewChild(root, NULL, (const xmlChar*)"", NULL); utf8str = (*i)->description().utf8(); osxml_node_set(body, "Body", utf8str, enc); // initialize the change object OSyncChange *chg = osync_change_new(); osync_change_set_uid(chg, uid.local8Bit()); osync_change_set_member(chg, member); // object type and format osync_change_set_objtype_string(chg, "note"); osync_change_set_objformat_string(chg, "xml-note"); osync_change_set_data(chg, (char*)doc, sizeof(doc), 1); //XXX: workaround to a bug on osync_change_multiply_master: // convert it to vnote OSyncFormatEnv *env = osync_member_get_format_env(member); OSyncError *e = NULL; if (!osync_change_convert_fmtname(env, chg, "vnote11", &e)) { osync_context_report_error(ctx, OSYNC_ERROR_CONVERT, "Error converting data to vnote: %s", osync_error_print(&e)); return false; } // Use the hash table to check if the object // needs to be reported osync_change_set_hash(chg, hash.data()); if (osync_hashtable_detect_change(hashtable, chg)) { osync_context_report_change(ctx, chg); osync_hashtable_update_hash(hashtable, chg); } } return true; } void KNotesDataSource::get_data(OSyncContext *ctx, OSyncChange *) { osync_context_report_error(ctx, OSYNC_ERROR_NOT_SUPPORTED, "Not implemented yet"); } bool KNotesDataSource::__access(OSyncContext *ctx, OSyncChange *chg) { OSyncChangeType type = osync_change_get_changetype(chg); QString uid = osync_change_get_uid(chg); if (type != CHANGE_DELETED) { // Get osxml data xmlDoc *doc = (xmlDoc*)osync_change_get_data(chg); xmlNode *root = osxml_node_get_root(doc, "note", NULL); if (!root) { osync_context_report_error(ctx, OSYNC_ERROR_CONVERT, "Invalid data"); return false; } QString summary = osxml_find_node(root, "Summary"); QString body = osxml_find_node(root, "Body"); KCal::Journal *j = calendar->journal(uid); if (type == CHANGE_MODIFIED && !j) type = CHANGE_ADDED; QString hash, uid; // end of the ugly-format parsing switch (type) { case CHANGE_ADDED: j = new KCal::Journal; j->setUid(uid); j->setSummary(summary); j->setDescription(body); hash = calc_hash(j); calendar->addJournal(j); uid = j->uid(); osync_change_set_uid(chg, uid); osync_change_set_hash(chg, hash); break; case CHANGE_MODIFIED: j->setSummary(summary); j->setDescription(body); hash = calc_hash(j); osync_change_set_hash(chg, hash); break; default: osync_context_report_error(ctx, OSYNC_ERROR_NOT_SUPPORTED, "Invalid change type"); return false; } } else { KCal::Journal *j = calendar->journal(uid); if (j) { calendar->deleteJournal(j); } } return true; } bool KNotesDataSource::access(OSyncContext *ctx, OSyncChange *chg) { if (!__access(ctx, chg)) return false; osync_context_report_success(ctx); return true; } bool KNotesDataSource::commit_change(OSyncContext *ctx, OSyncChange *chg) { if (!__access(ctx, chg)) return false; osync_hashtable_update_hash(hashtable, chg); osync_context_report_success(ctx); return true; } <|endoftext|>
<commit_before>/* * Copyright (c) 2015 <name of copyright holder> * Author: Srijan R Shetty <srijan.shetty+code@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // Include the VPTree library #include "vptree.h" // STL #include <queue> // Stream processing #include <iostream> #include <fstream> // Limits of numbers #include <limits> using namespace std; using namespace VPTree; // Print the tree recursively void printRecursive(const Node *root) { // Prettify std::cout << std::endl << std::endl; // To store the previous Level std::queue< std::pair<const Node*, char> > previousLevel; previousLevel.push(std::make_pair(root, 'N')); // To store the leaves std::queue< std::pair<DBObject, char> > leaves; while (!previousLevel.empty()) { std::queue< std::pair<const Node*, char> > nextLevel; while (!previousLevel.empty()) { // Get the front and pop const Node *iterator = previousLevel.front().first; char type = previousLevel.front().second; previousLevel.pop(); // If it a seperator, print and move ahead if (type == '|') { std::cout << " || "; continue; } // Print the MBR iterator->getObjectPoint().print(); if (!iterator->isLeaf()) { // Push the leftSubtree if (iterator->leftNode != nullptr) { nextLevel.push(std::make_pair(iterator->leftNode, 'N')); // Insert a marker to indicate end of child nextLevel.push(std::make_pair(nullptr, '|')); } // Push the rightSubtree if (iterator->rightNode != nullptr) { nextLevel.push(std::make_pair(iterator->rightNode, 'N')); // Insert a marker to indicate end of child nextLevel.push(std::make_pair(nullptr, '|')); } } else { // Add all child points to the leaf for (auto child: iterator->objectCache) { // leaves.push(std::make_pair(child, 'L')); } // marker for end of leaf // leaves.push(std::make_pair(DBObject(), '|')); } // Delete allocated memory delete iterator; } // Seperate different levels std::cout << std::endl << std::endl; previousLevel = nextLevel; } // Print all the leaves while (!leaves.empty()) { // Get the front and pop DBObject obj = leaves.front().first; char type = leaves.front().second; leaves.pop(); // If it a seperator, print and move ahead if (type == '|') { std::cout << " || "; continue; } // Print the MBR obj.print(); std::cout << " | "; } // Prettify std::cout << std::endl << std::endl; } // Build the tree from reading the DATAFILE void buildTree(Node *root) { ifstream ifile; ifile.open(DATAFILE, ios::in); // Items to read from the file vector <double> point; double coordinate; string dataString; long long objectID; while (!ifile.eof()) { // Get the point point.clear(); for (long i = 0; i < DIMENSIONS; ++i) { ifile >> coordinate; point.push_back(coordinate); } // Get the objectID and the dataString ifile >> objectID >> dataString; // Some quirk which needs to be handled if (ifile.eof()) { break; } if (objectID % 10000 == 0) { cout << endl << "Inserting " << objectID << " "; } // Insert the object into file root->insert(DBObject(objectID, dataString, point)); } // Close the file ifile.close(); } void processQuery(Node *root) { ifstream ifile; ifile.open(QUERYFILE, ios::in); long query; // Loop over the entire file while (ifile >> query) { // Get the point from the file vector <double> coordinates; double coordinate; for (long i = 0; i < DIMENSIONS; ++i) { ifile >> coordinate; coordinates.push_back(coordinate); } Point point(coordinates); #ifdef OUTPUT cout << endl << query << " "; point.print(); #endif if (query == 1) { // Get the range double range; ifile >> range; #ifdef OUTPUT cout << " " << range << endl; #endif #ifdef TIME cout << query << " "; auto start = std::chrono::high_resolution_clock::now(); #endif // rangeSearch root->rangeSearch(point, range * 1.0); #ifdef TIME auto elapsed = std::chrono::high_resolution_clock::now() - start; long long microseconds = std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count(); cout << microseconds << endl; #endif } else if (query == 2) { // Get the number of points long k; ifile >> k; #ifdef OUTPUT cout << " " << k << endl; #endif #ifdef TIME cout << query << " "; auto start = std::chrono::high_resolution_clock::now(); #endif // kNNSearch // root->kNNSearch(point, k); #ifdef TIME auto elapsed = std::chrono::high_resolution_clock::now() - start; long long microseconds = std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count(); cout << microseconds << endl; #endif } } // Close the file ifile.close(); } int main() { // Test the insertion routine vector<double> p1 = {0.0, 0.0}; DBObject obj(0, "srijan", p1); Node *VPRoot = new Node(numeric_limits<double>::max(), obj); buildTree(VPRoot); // printRecursive(VPRoot); VPRoot->print(); cout << endl << endl; vector<double> p2 = {0.0, 0.0}; VPRoot->kNNSearch(p2, 9); return 0; } <commit_msg>fixed printRecursive<commit_after>/* * Copyright (c) 2015 <name of copyright holder> * Author: Srijan R Shetty <srijan.shetty+code@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // Include the VPTree library #include "vptree.h" // STL #include <queue> // Stream processing #include <iostream> #include <fstream> // Limits of numbers #include <limits> using namespace std; using namespace VPTree; // Print the tree recursively void printRecursive(const Node *root) { // Prettify std::cout << std::endl << std::endl; // To store the previous Level std::queue< std::pair<const Node*, char> > previousLevel; previousLevel.push(std::make_pair(root, 'N')); // To store the leaves std::queue< std::pair<DBObject, char> > leaves; while (!previousLevel.empty()) { std::queue< std::pair<const Node*, char> > nextLevel; while (!previousLevel.empty()) { // Get the front and pop const Node *iterator = previousLevel.front().first; char type = previousLevel.front().second; previousLevel.pop(); // If it a seperator, print and move ahead if (type == '|') { std::cout << " || "; continue; } // Print the MBR iterator->getObjectPoint().print(); if (!iterator->isLeaf()) { // Push the leftSubtree if (iterator->leftNode != nullptr) { nextLevel.push(std::make_pair(iterator->leftNode, 'N')); // Insert a marker to indicate end of child nextLevel.push(std::make_pair(nullptr, '|')); } // Push the rightSubtree if (iterator->rightNode != nullptr) { nextLevel.push(std::make_pair(iterator->rightNode, 'N')); // Insert a marker to indicate end of child nextLevel.push(std::make_pair(nullptr, '|')); } } else { // Add all child points to the leaf for (auto child: iterator->objectCache) { leaves.push(std::make_pair(child, 'L')); } // marker for end of leaf leaves.push(std::make_pair(DBObject(), '|')); } } // Seperate different levels std::cout << std::endl << std::endl; previousLevel = nextLevel; } // Print all the leaves while (!leaves.empty()) { // Get the front and pop DBObject obj = leaves.front().first; char type = leaves.front().second; leaves.pop(); // If it a seperator, print and move ahead if (type == '|') { std::cout << " || "; continue; } // Print the MBR obj.print(); std::cout << " | "; } // Prettify std::cout << std::endl << std::endl; } // Build the tree from reading the DATAFILE void buildTree(Node *root) { ifstream ifile; ifile.open(DATAFILE, ios::in); // Items to read from the file vector <double> point; double coordinate; string dataString; long long objectID; while (!ifile.eof()) { // Get the point point.clear(); for (long i = 0; i < DIMENSIONS; ++i) { ifile >> coordinate; point.push_back(coordinate); } // Get the objectID and the dataString ifile >> objectID >> dataString; // Some quirk which needs to be handled if (ifile.eof()) { break; } if (objectID % 10000 == 0) { cout << endl << "Inserting " << objectID << " "; } // Insert the object into file root->insert(DBObject(objectID, dataString, point)); } // Close the file ifile.close(); } void processQuery(Node *root) { ifstream ifile; ifile.open(QUERYFILE, ios::in); long query; // Loop over the entire file while (ifile >> query) { // Get the point from the file vector <double> coordinates; double coordinate; for (long i = 0; i < DIMENSIONS; ++i) { ifile >> coordinate; coordinates.push_back(coordinate); } Point point(coordinates); #ifdef OUTPUT cout << endl << query << " "; point.print(); #endif if (query == 1) { // Get the range double range; ifile >> range; #ifdef OUTPUT cout << " " << range << endl; #endif #ifdef TIME cout << query << " "; auto start = std::chrono::high_resolution_clock::now(); #endif // rangeSearch root->rangeSearch(point, range * 1.0); #ifdef TIME auto elapsed = std::chrono::high_resolution_clock::now() - start; long long microseconds = std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count(); cout << microseconds << endl; #endif } else if (query == 2) { // Get the number of points long k; ifile >> k; #ifdef OUTPUT cout << " " << k << endl; #endif #ifdef TIME cout << query << " "; auto start = std::chrono::high_resolution_clock::now(); #endif // kNNSearch // root->kNNSearch(point, k); #ifdef TIME auto elapsed = std::chrono::high_resolution_clock::now() - start; long long microseconds = std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count(); cout << microseconds << endl; #endif } } // Close the file ifile.close(); } int main() { // Test the insertion routine vector<double> p1 = {0.0, 0.0}; DBObject obj(0, "srijan", p1); Node *VPRoot = new Node(numeric_limits<double>::max(), obj); buildTree(VPRoot); printRecursive(VPRoot); vector<double> p2 = {0.0, 0.0}; VPRoot->kNNSearch(p2, 9); return 0; } <|endoftext|>
<commit_before>/* * ===================================================================================== * * Filename: encore.cpp * * Description: Encore - A computational framework for analysis of GWAS and other * biological data * * Includes epistasis interaction analysis (reGAIN), eigenvector * centrality SNP ranking (SNPrank), and feature selection using the * Evaporative Cooling machine learning tool. Encore also utilizes * plink for its ubiquitous data formats and wide array of GWAS * functionality. * * Created: 02/01/2012 * * Author: Nick Davis, nick-davis@utulsa.edu * * ===================================================================================== */ #include <fstream> #include <iostream> #include <string> #include <boost/program_options.hpp> #include <boost/program_options/positional_options.hpp> #include <boost/filesystem.hpp> #include <boost/algorithm/string.hpp> #include "ec/EvaporativeCooling.h" #include "plink/plinklibhandler.h" #include "plink/plink.h" #include "plink/options.h" #include "plink/helper.h" #include "snprank.h" #include "regain.h" using namespace boost; namespace po = boost::program_options; /******************************** * required plink data structures *******************************/ // plink object Plink* PP; int main(int argc, char* argv[]) { // command line variables // data files string infile = ""; string outfile_pref = "encore"; string covarfile = ""; string phenofile = ""; string extrfile = ""; //snprank double gamma = 0.85; // reGAIN double sif_thresh = 0.05; double fdr = 0.5; // EC string ec_algo = "all"; string ec_sm = "gm"; po::options_description desc("Encore - a tool for analysis of GWAS and other " "biological data.\nUsage: encore -i snpdata.ped [mode] -o output-prefix"); desc.add_options() ("input-file,i", po::value<string>(&infile), "Input GWAS file (.bed or .ped) or GAIN/reGAIN matrix (tab- or comma-separated)" ) ("output-prefix,o", po::value<string>(&outfile_pref), "Prefix to use for all output files" ) ("snprank,s", "Perform SNPrank analysis *mode*" ) ("gamma,g", po::value<double>(&gamma)->default_value(0.85, "0.85"), "Damping factor (default is 0.85)" ) ("regain,r", "Calculate regression GAIN *mode*" ) ("compress-matrices", "Write binary (compressed) reGAIN matrices" ) ("sif-threshold", po::value<double>(&sif_thresh)->default_value(0.05, "0.05"), "Numerical cutoff for SIF file interaction scores" ) ("fdr-prune", "FDR prune reGAIN interaction terms" ) ("fdr", po::value<double>(&fdr)->default_value(0.5, "0.5"), "FDR value for BH method" ) ("ec,e", "Perform Evaporative Cooling (EC) analysis *mode*" ) ("ec-algorithm", po::value<string>(&ec_algo), "EC ML algorithm (all|rf|rj)" ) ("ec-snp-metric", po::value<string>(&ec_sm), "EC SNP metric (gm|am)" ) ("extract", po::value<string>(&extrfile), "Extract list of SNPs from specified file" ) ("covar", po::value<string>(&covarfile), "Include covariate file in analysis" ) ("pheno", po::value<string>(&phenofile), "Include alternate phenotype file in analysis" ) ("assoc", "Run Case/control, QT association tests *mode*" ) ("linear", "Run linear regression model *mode*" ) ("ld-prune,l", "Linkage disequilibrium (LD) pruning *mode*" ) ("help,h", "display this help screen" ) ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); /******************************** * Help *******************************/ if (vm.count("help")) { cout << desc << endl; return 1; } /********************************* * Validate only one mode passed ********************************/ int modes = 0; for (po::variables_map::iterator iter = vm.begin(); iter != vm.end(); ++iter) { if (iter->first == "snprank" || iter->first == "regain" || iter->first == "ec" || iter->first == "assoc" || iter->first == "linear" || iter->first == "ld-prune") { modes++; } } if (modes > 1) { cerr << "Error: Only one mode may be specified" << endl << endl << desc << endl; return 1; } /******************************** * Input file *******************************/ // require input file if (!vm.count("input-file")) { cerr << "Error: Must specify input file" << endl << endl << desc << endl; return 1; } // ensure SNP/reGAIN file exists else if (!boost::filesystem::exists(infile)) { cerr << "Error: Input file " << infile << " does not exist" << endl; return 1; } // Plink input file else if (infile.find(".bed") != string::npos || infile.find(".ped") != string::npos) { // set file root vector<string> fileparts; split(fileparts, infile, is_any_of(".")); par::fileroot = ""; // handle files with multiple .s in the name for (int i =0; i < fileparts.size() - 1; i++) { par::fileroot += fileparts[i]; if (fileparts.size() > 2 && i < fileparts.size() - 2) par::fileroot += "."; } // set Plink's output file prefix par::output_file_name = outfile_pref; // initialize requisite Plink data structures initPlink(); // read SNP file in PLINK // binary file if (infile.find(".bed") != string::npos) readPlBinFile(); // plaintext file else if (infile.find(".ped") != string::npos) readPlFile(); // additional PLINK setup initPlStats(); } /******************************** * Covar file *******************************/ if (vm.count("covar")){ // validate that covar file is used with proper modes if (!(vm.count("regain") || vm.count("linear"))) { cerr << "Error: Covariate file may only be used with --regain or --linear" << endl << desc << endl; return 1; } // ensure covariate file exists else if (!boost::filesystem::exists(covarfile)) { cerr << "Error: Covariate file " << covarfile << " does not exist" << endl; return 1; } // read covariate file using PLINK else { par::covar_file = true; par::clist = true; par::clist_filename = covarfile; if(!PP->readCovListFile()){ cerr << "Error: Problem reading the covariates" << endl; return 1; } } } /******************************** * Pheno file *******************************/ if (vm.count("pheno")) { // alternate phenotype validation if (vm.count("snprank")) { cerr << "Error: Alternate phenotype file cannot be used with "\ "--snprank" << endl << desc << endl; return 1; } // ensure alternate phenotype file exists else if (!boost::filesystem::exists(phenofile)) { cerr << "Error: Alernate phenotype file " << phenofile << " does not exist" << endl; return 1; } // read alternate phenotype file using PLINK else { par::pheno_file = true; par::pheno_filename = phenofile; if(!PP->readPhenoFile()) cerr << "Error: Problem reading the alternate phenotype file" << endl; } } /******************************** * Extract file *******************************/ if (vm.count("extract")) { // extract validation if (vm.count("snprank") || vm.count("ec") || vm.count("ldprune")) { cerr << "Error: Extract file cannot be used with "\ "--snprank, --ec, or --ldprune" << endl << desc << endl; return 1; } // ensure extract file exists else if (!boost::filesystem::exists(extrfile)) { cerr << "Error: Extract file " << extrfile << " does not exist" << endl; return 1; } // read extract file SNPs using PLINK else { par::extract_set = true; par::extract_file = extrfile; PP->extractExcludeSet(false); } } /********************************* * Validate mode sub-options ********************************/ if ((gamma != 0.85) && !vm.count("snprank")) { cerr << "Error: --gamma must be used with --snprank" << endl << endl << desc << endl; return 1; } if ((sif_thresh != 0.05) && !vm.count("regain")) { cerr << "Error: --sif-threshold must be used with --regain" << endl << endl << desc << endl; return 1; } if (vm.count("fdr-prune") && !vm.count("regain")) { cerr << "Error: --fdr-prune must be used with --regain" << endl << endl << desc << endl; return 1; } if ((fdr != 0.5) && !vm.count("regain")) { cerr << "Error: --fdr must be used with --regain" << endl << endl << desc << endl; return 1; } if (vm.count("ec-algorithm") && !vm.count("ec")) { cerr << "Error: ec-algorithm must be used with --ec" << endl << endl << desc << endl; return 1; } if (vm.count("ec-snp-metric") && !vm.count("ec")) { cerr << "Error: ec-snp-metric must be used with --ec" << endl << endl << desc << endl; return 1; } /********************************* * Check primary mode of operation ********************************/ // SNPrank if (vm.count("snprank")) { SNPrank* sr = new SNPrank(infile); cout << "Writing SNPrank results to [ " << outfile_pref << ".snprank ]" << endl; sr->snprank(sr->getHeader(), sr->getData(), gamma, outfile_pref + ".snprank"); delete sr; } // reGAIN else if (vm.count("regain")) { if (!vm.count("extract")) cout << "Warning: It is recommended to use an --extract file of SNPs with "\ "--regain" << endl; // SNP major mode or individual major mode? if(par::fast_epistasis) { if(!par::SNP_major) PP->Ind2SNP(); } else { if(par::SNP_major) PP->SNP2Ind(); } bool fdrprune = vm.count("fdr-prune"); Regain* r = new Regain(vm.count("compress-matrices"), sif_thresh, fdrprune); r->run(); if (fdrprune){ r->writeRegain(); r->fdrPrune(fdr); } r->writeRegain(fdrprune); r->writePvals(); delete r; } // Evaporative Cooling (EC) else if (vm.count("ec")) { // EC options map map<string,string> opts; // required options for EC opts.insert(pair<string,string>("ec-num-target", "0")); opts.insert(pair<string,string>("snp-data", infile)); opts.insert(pair<string,string>("out-files-prefix", outfile_pref)); // defaults for ID matching string numericfile = ""; vector<string> ind_ids; vector<string> numeric_ids; vector<string> pheno_ids; bool datasetLoaded = false; // validate algorithm if (ec_algo != "all" && ec_algo != "rj" && ec_algo != "rf") cerr << "Error: EC algorithm must be one of: (all|rj|rf)" << endl; else opts.insert(pair<string,string>("ec-algorithm-steps", ec_algo)); // validate metric if (ec_sm != "gm" && ec_sm != "am") cerr << "Error: EC SNP metric must be one of: (gm|am)" << endl; else opts.insert(pair<string,string>("snp-metric", ec_sm)); // find IDs for loading from the dataset if(!GetMatchingIds(numericfile, phenofile, numeric_ids, pheno_ids, ind_ids)) cerr << "Error: could not get matching IDs from numeric " << "and/or phenotype files" << endl; // initialize dataset by extension Dataset* ds = 0; ds = ChooseSnpsDatasetByExtension(infile); bool loaded = ds->LoadDataset(infile, "", phenofile, ind_ids); if (!loaded) cerr << "Error: Failure to load dataset for analysis" << endl; // file data stats ds->PrintStats(); // create ec object and run EvaporativeCooling* ec = new EvaporativeCooling(ds, opts, SNP_ONLY_ANALYSIS); if(!ec->ComputeECScores()) cerr << "Error: Failed to calculate EC scores" << endl; // write results to file cout << "Writing EC results to [ " << outfile_pref << ".ec ]" << endl; ec->WriteAttributeScores(outfile_pref); delete ds; delete ec; } // Case/Control, QT association test OR linear model else if (vm.count("assoc")) { if (vm.count("linear")) par::assoc_glm = true; par::assoc_test = true; PP->calcAssociationWithPermutation(*PP->pperm); } // LD-based pruning else if (vm.count("ldprune")) { par::prune_ld = true; par::prune_ld_pairwise = true; par::prune_ld_win = 50; par::prune_ld_step = 5; par::prune_ld_vif = 0.5; PP->pruneLD(); } else { cerr << "Error: Invalid command mode, must be one of:" << endl << " --snprank, --regain, --ec, --assoc, --linear, --ldprune" << endl << endl << desc << endl; // Plink exit shutdown(); return 1; } // Plink exit shutdown(); return 0; } <commit_msg>Remove redundant text in gamma description<commit_after>/* * ===================================================================================== * * Filename: encore.cpp * * Description: Encore - A computational framework for analysis of GWAS and other * biological data * * Includes epistasis interaction analysis (reGAIN), eigenvector * centrality SNP ranking (SNPrank), and feature selection using the * Evaporative Cooling machine learning tool. Encore also utilizes * plink for its ubiquitous data formats and wide array of GWAS * functionality. * * Created: 02/01/2012 * * Author: Nick Davis, nick-davis@utulsa.edu * * ===================================================================================== */ #include <fstream> #include <iostream> #include <string> #include <boost/program_options.hpp> #include <boost/program_options/positional_options.hpp> #include <boost/filesystem.hpp> #include <boost/algorithm/string.hpp> #include "ec/EvaporativeCooling.h" #include "plink/plinklibhandler.h" #include "plink/plink.h" #include "plink/options.h" #include "plink/helper.h" #include "snprank.h" #include "regain.h" using namespace boost; namespace po = boost::program_options; /******************************** * required plink data structures *******************************/ // plink object Plink* PP; int main(int argc, char* argv[]) { // command line variables // data files string infile = ""; string outfile_pref = "encore"; string covarfile = ""; string phenofile = ""; string extrfile = ""; //snprank double gamma = 0.85; // reGAIN double sif_thresh = 0.05; double fdr = 0.5; // EC string ec_algo = "all"; string ec_sm = "gm"; po::options_description desc("Encore - a tool for analysis of GWAS and other " "biological data.\nUsage: encore -i snpdata.ped [mode] -o output-prefix"); desc.add_options() ("input-file,i", po::value<string>(&infile), "Input GWAS file (.bed or .ped) or GAIN/reGAIN matrix (tab- or comma-separated)" ) ("output-prefix,o", po::value<string>(&outfile_pref), "Prefix to use for all output files" ) ("snprank,s", "Perform SNPrank analysis *mode*" ) ("gamma,g", po::value<double>(&gamma)->default_value(0.85, "0.85"), "Damping factor" ) ("regain,r", "Calculate regression GAIN *mode*" ) ("compress-matrices", "Write binary (compressed) reGAIN matrices" ) ("sif-threshold", po::value<double>(&sif_thresh)->default_value(0.05, "0.05"), "Numerical cutoff for SIF file interaction scores" ) ("fdr-prune", "FDR prune reGAIN interaction terms" ) ("fdr", po::value<double>(&fdr)->default_value(0.5, "0.5"), "FDR value for BH method" ) ("ec,e", "Perform Evaporative Cooling (EC) analysis *mode*" ) ("ec-algorithm", po::value<string>(&ec_algo), "EC ML algorithm (all|rf|rj)" ) ("ec-snp-metric", po::value<string>(&ec_sm), "EC SNP metric (gm|am)" ) ("extract", po::value<string>(&extrfile), "Extract list of SNPs from specified file" ) ("covar", po::value<string>(&covarfile), "Include covariate file in analysis" ) ("pheno", po::value<string>(&phenofile), "Include alternate phenotype file in analysis" ) ("assoc", "Run Case/control, QT association tests *mode*" ) ("linear", "Run linear regression model *mode*" ) ("ld-prune,l", "Linkage disequilibrium (LD) pruning *mode*" ) ("help,h", "display this help screen" ) ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); /******************************** * Help *******************************/ if (vm.count("help")) { cout << desc << endl; return 1; } /********************************* * Validate only one mode passed ********************************/ int modes = 0; for (po::variables_map::iterator iter = vm.begin(); iter != vm.end(); ++iter) { if (iter->first == "snprank" || iter->first == "regain" || iter->first == "ec" || iter->first == "assoc" || iter->first == "linear" || iter->first == "ld-prune") { modes++; } } if (modes > 1) { cerr << "Error: Only one mode may be specified" << endl << endl << desc << endl; return 1; } /******************************** * Input file *******************************/ // require input file if (!vm.count("input-file")) { cerr << "Error: Must specify input file" << endl << endl << desc << endl; return 1; } // ensure SNP/reGAIN file exists else if (!boost::filesystem::exists(infile)) { cerr << "Error: Input file " << infile << " does not exist" << endl; return 1; } // Plink input file else if (infile.find(".bed") != string::npos || infile.find(".ped") != string::npos) { // set file root vector<string> fileparts; split(fileparts, infile, is_any_of(".")); par::fileroot = ""; // handle files with multiple .s in the name for (int i =0; i < fileparts.size() - 1; i++) { par::fileroot += fileparts[i]; if (fileparts.size() > 2 && i < fileparts.size() - 2) par::fileroot += "."; } // set Plink's output file prefix par::output_file_name = outfile_pref; // initialize requisite Plink data structures initPlink(); // read SNP file in PLINK // binary file if (infile.find(".bed") != string::npos) readPlBinFile(); // plaintext file else if (infile.find(".ped") != string::npos) readPlFile(); // additional PLINK setup initPlStats(); } /******************************** * Covar file *******************************/ if (vm.count("covar")){ // validate that covar file is used with proper modes if (!(vm.count("regain") || vm.count("linear"))) { cerr << "Error: Covariate file may only be used with --regain or --linear" << endl << desc << endl; return 1; } // ensure covariate file exists else if (!boost::filesystem::exists(covarfile)) { cerr << "Error: Covariate file " << covarfile << " does not exist" << endl; return 1; } // read covariate file using PLINK else { par::covar_file = true; par::clist = true; par::clist_filename = covarfile; if(!PP->readCovListFile()){ cerr << "Error: Problem reading the covariates" << endl; return 1; } } } /******************************** * Pheno file *******************************/ if (vm.count("pheno")) { // alternate phenotype validation if (vm.count("snprank")) { cerr << "Error: Alternate phenotype file cannot be used with "\ "--snprank" << endl << desc << endl; return 1; } // ensure alternate phenotype file exists else if (!boost::filesystem::exists(phenofile)) { cerr << "Error: Alernate phenotype file " << phenofile << " does not exist" << endl; return 1; } // read alternate phenotype file using PLINK else { par::pheno_file = true; par::pheno_filename = phenofile; if(!PP->readPhenoFile()) cerr << "Error: Problem reading the alternate phenotype file" << endl; } } /******************************** * Extract file *******************************/ if (vm.count("extract")) { // extract validation if (vm.count("snprank") || vm.count("ec") || vm.count("ldprune")) { cerr << "Error: Extract file cannot be used with "\ "--snprank, --ec, or --ldprune" << endl << desc << endl; return 1; } // ensure extract file exists else if (!boost::filesystem::exists(extrfile)) { cerr << "Error: Extract file " << extrfile << " does not exist" << endl; return 1; } // read extract file SNPs using PLINK else { par::extract_set = true; par::extract_file = extrfile; PP->extractExcludeSet(false); } } /********************************* * Validate mode sub-options ********************************/ if ((gamma != 0.85) && !vm.count("snprank")) { cerr << "Error: --gamma must be used with --snprank" << endl << endl << desc << endl; return 1; } if ((sif_thresh != 0.05) && !vm.count("regain")) { cerr << "Error: --sif-threshold must be used with --regain" << endl << endl << desc << endl; return 1; } if (vm.count("fdr-prune") && !vm.count("regain")) { cerr << "Error: --fdr-prune must be used with --regain" << endl << endl << desc << endl; return 1; } if ((fdr != 0.5) && !vm.count("regain")) { cerr << "Error: --fdr must be used with --regain" << endl << endl << desc << endl; return 1; } if (vm.count("ec-algorithm") && !vm.count("ec")) { cerr << "Error: ec-algorithm must be used with --ec" << endl << endl << desc << endl; return 1; } if (vm.count("ec-snp-metric") && !vm.count("ec")) { cerr << "Error: ec-snp-metric must be used with --ec" << endl << endl << desc << endl; return 1; } /********************************* * Check primary mode of operation ********************************/ // SNPrank if (vm.count("snprank")) { SNPrank* sr = new SNPrank(infile); cout << "Writing SNPrank results to [ " << outfile_pref << ".snprank ]" << endl; sr->snprank(sr->getHeader(), sr->getData(), gamma, outfile_pref + ".snprank"); delete sr; } // reGAIN else if (vm.count("regain")) { if (!vm.count("extract")) cout << "Warning: It is recommended to use an --extract file of SNPs with "\ "--regain" << endl; // SNP major mode or individual major mode? if(par::fast_epistasis) { if(!par::SNP_major) PP->Ind2SNP(); } else { if(par::SNP_major) PP->SNP2Ind(); } bool fdrprune = vm.count("fdr-prune"); Regain* r = new Regain(vm.count("compress-matrices"), sif_thresh, fdrprune); r->run(); if (fdrprune){ r->writeRegain(); r->fdrPrune(fdr); } r->writeRegain(fdrprune); r->writePvals(); delete r; } // Evaporative Cooling (EC) else if (vm.count("ec")) { // EC options map map<string,string> opts; // required options for EC opts.insert(pair<string,string>("ec-num-target", "0")); opts.insert(pair<string,string>("snp-data", infile)); opts.insert(pair<string,string>("out-files-prefix", outfile_pref)); // defaults for ID matching string numericfile = ""; vector<string> ind_ids; vector<string> numeric_ids; vector<string> pheno_ids; bool datasetLoaded = false; // validate algorithm if (ec_algo != "all" && ec_algo != "rj" && ec_algo != "rf") cerr << "Error: EC algorithm must be one of: (all|rj|rf)" << endl; else opts.insert(pair<string,string>("ec-algorithm-steps", ec_algo)); // validate metric if (ec_sm != "gm" && ec_sm != "am") cerr << "Error: EC SNP metric must be one of: (gm|am)" << endl; else opts.insert(pair<string,string>("snp-metric", ec_sm)); // find IDs for loading from the dataset if(!GetMatchingIds(numericfile, phenofile, numeric_ids, pheno_ids, ind_ids)) cerr << "Error: could not get matching IDs from numeric " << "and/or phenotype files" << endl; // initialize dataset by extension Dataset* ds = 0; ds = ChooseSnpsDatasetByExtension(infile); bool loaded = ds->LoadDataset(infile, "", phenofile, ind_ids); if (!loaded) cerr << "Error: Failure to load dataset for analysis" << endl; // file data stats ds->PrintStats(); // create ec object and run EvaporativeCooling* ec = new EvaporativeCooling(ds, opts, SNP_ONLY_ANALYSIS); if(!ec->ComputeECScores()) cerr << "Error: Failed to calculate EC scores" << endl; // write results to file cout << "Writing EC results to [ " << outfile_pref << ".ec ]" << endl; ec->WriteAttributeScores(outfile_pref); delete ds; delete ec; } // Case/Control, QT association test OR linear model else if (vm.count("assoc")) { if (vm.count("linear")) par::assoc_glm = true; par::assoc_test = true; PP->calcAssociationWithPermutation(*PP->pperm); } // LD-based pruning else if (vm.count("ldprune")) { par::prune_ld = true; par::prune_ld_pairwise = true; par::prune_ld_win = 50; par::prune_ld_step = 5; par::prune_ld_vif = 0.5; PP->pruneLD(); } else { cerr << "Error: Invalid command mode, must be one of:" << endl << " --snprank, --regain, --ec, --assoc, --linear, --ldprune" << endl << endl << desc << endl; // Plink exit shutdown(); return 1; } // Plink exit shutdown(); return 0; } <|endoftext|>
<commit_before>#include "AlembicXform.h" #include "MetaData.h" #include <maya/MFnTransform.h> namespace AbcA = ::Alembic::AbcCoreAbstract::ALEMBIC_VERSION_NS; using namespace AbcA; AlembicXform::AlembicXform(const MObject & in_Ref, AlembicWriteJob * in_Job) : AlembicObject(in_Ref, in_Job) { MFnDependencyNode node(in_Ref); MString name = truncateName(node.name())+"Xfo"; mObject = Alembic::AbcGeom::OXform(GetParentObject(),name.asChar(),GetJob()->GetAnimatedTs()); mSchema = mObject.getSchema(); } AlembicXform::~AlembicXform() { mObject.reset(); mSchema.reset(); } MStatus AlembicXform::Save(double time) { // access the xform MFnTransform node(GetRef()); // save the metadata SaveMetaData(this); // check if we have the global cache option bool globalCache = GetJob()->GetOption(L"exportInGlobalSpace").asInt() > 0; if(globalCache) { if(mNumSamples > 0) return MStatus::kSuccess; // store identity matrix mSample.setTranslation(Imath::V3d(0.0,0.0,0.0)); mSample.setRotation(Imath::V3d(1.0,0.0,0.0),0.0); mSample.setScale(Imath::V3d(1.0,1.0,1.0)); } else { MTransformationMatrix xf = node.transformation(); MMatrix matrix = xf.asMatrix(); Alembic::Abc::M44d abcMatrix; matrix.get(abcMatrix.x); mSample.setMatrix(abcMatrix); mSample.setInheritsXforms(true); } // save the sample mSchema.set(mSample); mNumSamples++; return MStatus::kSuccess; } void AlembicXformNode::PreDestruction() { mSchema.reset(); delRefArchive(mFileName); mFileName.clear(); } AlembicXformNode::~AlembicXformNode() { PreDestruction(); } MObject AlembicXformNode::mTimeAttr; MObject AlembicXformNode::mFileNameAttr; MObject AlembicXformNode::mIdentifierAttr; MObject AlembicXformNode::mOutTranslateXAttr; MObject AlembicXformNode::mOutTranslateYAttr; MObject AlembicXformNode::mOutTranslateZAttr; MObject AlembicXformNode::mOutTranslateAttr; MObject AlembicXformNode::mOutRotateXAttr; MObject AlembicXformNode::mOutRotateYAttr; MObject AlembicXformNode::mOutRotateZAttr; MObject AlembicXformNode::mOutRotateAttr; MObject AlembicXformNode::mOutScaleXAttr; MObject AlembicXformNode::mOutScaleYAttr; MObject AlembicXformNode::mOutScaleZAttr; MObject AlembicXformNode::mOutScaleAttr; MStatus AlembicXformNode::initialize() { MStatus status; MFnUnitAttribute uAttr; MFnTypedAttribute tAttr; MFnNumericAttribute nAttr; MFnGenericAttribute gAttr; MFnStringData emptyStringData; MObject emptyStringObject = emptyStringData.create(""); // input time mTimeAttr = uAttr.create("inTime", "tm", MFnUnitAttribute::kTime, 0.0); status = uAttr.setStorable(true); status = uAttr.setKeyable(true); status = addAttribute(mTimeAttr); // input file name mFileNameAttr = tAttr.create("fileName", "fn", MFnData::kString, emptyStringObject); status = tAttr.setStorable(true); status = tAttr.setUsedAsFilename(true); status = tAttr.setKeyable(false); status = addAttribute(mFileNameAttr); // input identifier mIdentifierAttr = tAttr.create("identifier", "it", MFnData::kString, emptyStringObject); status = tAttr.setStorable(true); status = tAttr.setKeyable(false); status = addAttribute(mIdentifierAttr); // output translateX mOutTranslateXAttr = nAttr.create("translateX", "tx", MFnNumericData::kDouble, 0.0); status = nAttr.setStorable(false); status = nAttr.setWritable(false); status = nAttr.setKeyable(false); status = nAttr.setHidden(false); // output translateY mOutTranslateYAttr = nAttr.create("translateY", "ty", MFnNumericData::kDouble, 0.0); status = nAttr.setStorable(false); status = nAttr.setWritable(false); status = nAttr.setKeyable(false); status = nAttr.setHidden(false); // output translateY mOutTranslateZAttr = nAttr.create("translateZ", "tz", MFnNumericData::kDouble, 0.0); status = nAttr.setStorable(false); status = nAttr.setWritable(false); status = nAttr.setKeyable(false); status = nAttr.setHidden(false); // output translate compound mOutTranslateAttr = nAttr.create( "translate", "t", mOutTranslateXAttr, mOutTranslateYAttr, mOutTranslateZAttr); status = nAttr.setStorable(false); status = nAttr.setWritable(false); status = nAttr.setKeyable(false); status = nAttr.setHidden(false); status = addAttribute(mOutTranslateAttr); // output rotatex mOutRotateXAttr = uAttr.create("rotateX", "rx", MFnUnitAttribute::kAngle, 0.0); status = uAttr.setStorable(false); status = uAttr.setWritable(false); status = uAttr.setKeyable(false); status = uAttr.setHidden(false); // output rotatexy mOutRotateYAttr = uAttr.create("rotateY", "ry", MFnUnitAttribute::kAngle, 0.0); status = uAttr.setStorable(false); status = uAttr.setWritable(false); status = uAttr.setKeyable(false); status = uAttr.setHidden(false); // output rotatez mOutRotateZAttr = uAttr.create("rotateZ", "rz", MFnUnitAttribute::kAngle, 0.0); status = uAttr.setStorable(false); status = uAttr.setWritable(false); status = uAttr.setKeyable(false); status = uAttr.setHidden(false); // output translate compound mOutRotateAttr = nAttr.create( "rotate", "r", mOutRotateXAttr, mOutRotateYAttr, mOutRotateZAttr); status = nAttr.setStorable(false); status = nAttr.setWritable(false); status = nAttr.setKeyable(false); status = nAttr.setHidden(false); status = addAttribute(mOutRotateAttr); // output scalex mOutScaleXAttr = nAttr.create("scaleX", "sx", MFnNumericData::kDouble, 1.0); status = nAttr.setStorable(false); status = nAttr.setWritable(false); status = nAttr.setKeyable(false); status = nAttr.setHidden(false); // output scaley mOutScaleYAttr = nAttr.create("scaleY", "sy", MFnNumericData::kDouble, 1.0); status = nAttr.setStorable(false); status = nAttr.setWritable(false); status = nAttr.setKeyable(false); status = nAttr.setHidden(false); // output scalez mOutScaleZAttr = nAttr.create("scaleZ", "sz", MFnNumericData::kDouble, 1.0); status = nAttr.setStorable(false); status = nAttr.setWritable(false); status = nAttr.setKeyable(false); status = nAttr.setHidden(false); // output translate compound mOutScaleAttr = nAttr.create( "scale", "s", mOutScaleXAttr, mOutScaleYAttr, mOutScaleZAttr); status = nAttr.setStorable(false); status = nAttr.setWritable(false); status = nAttr.setKeyable(false); status = nAttr.setHidden(false); status = addAttribute(mOutScaleAttr); // create a mapping status = attributeAffects(mTimeAttr, mOutTranslateXAttr); status = attributeAffects(mFileNameAttr, mOutTranslateXAttr); status = attributeAffects(mIdentifierAttr, mOutTranslateXAttr); status = attributeAffects(mTimeAttr, mOutTranslateYAttr); status = attributeAffects(mFileNameAttr, mOutTranslateYAttr); status = attributeAffects(mIdentifierAttr, mOutTranslateYAttr); status = attributeAffects(mTimeAttr, mOutTranslateZAttr); status = attributeAffects(mFileNameAttr, mOutTranslateZAttr); status = attributeAffects(mIdentifierAttr, mOutTranslateZAttr); status = attributeAffects(mTimeAttr, mOutRotateXAttr); status = attributeAffects(mFileNameAttr, mOutRotateXAttr); status = attributeAffects(mIdentifierAttr, mOutRotateXAttr); status = attributeAffects(mTimeAttr, mOutRotateYAttr); status = attributeAffects(mFileNameAttr, mOutRotateYAttr); status = attributeAffects(mIdentifierAttr, mOutRotateYAttr); status = attributeAffects(mTimeAttr, mOutRotateZAttr); status = attributeAffects(mFileNameAttr, mOutRotateZAttr); status = attributeAffects(mIdentifierAttr, mOutRotateZAttr); status = attributeAffects(mTimeAttr, mOutScaleXAttr); status = attributeAffects(mFileNameAttr, mOutScaleXAttr); status = attributeAffects(mIdentifierAttr, mOutScaleXAttr); status = attributeAffects(mTimeAttr, mOutScaleYAttr); status = attributeAffects(mFileNameAttr, mOutScaleYAttr); status = attributeAffects(mIdentifierAttr, mOutScaleYAttr); status = attributeAffects(mTimeAttr, mOutScaleZAttr); status = attributeAffects(mFileNameAttr, mOutScaleZAttr); status = attributeAffects(mIdentifierAttr, mOutScaleZAttr); return status; } MStatus AlembicXformNode::compute(const MPlug & plug, MDataBlock & dataBlock) { MStatus status; // update the frame number to be imported double inputTime = dataBlock.inputValue(mTimeAttr).asTime().as(MTime::kSeconds); MString & fileName = dataBlock.inputValue(mFileNameAttr).asString(); MString & identifier = dataBlock.inputValue(mIdentifierAttr).asString(); // check if we have the file if(fileName != mFileName || identifier != mIdentifier) { mSchema.reset(); if(fileName != mFileName) { delRefArchive(mFileName); mFileName = fileName; addRefArchive(mFileName); } mIdentifier = identifier; // get the object from the archive Alembic::Abc::IObject iObj = getObjectFromArchive(mFileName,identifier); if(!iObj.valid()) { MGlobal::displayWarning("[ExocortexAlembic] Identifier '"+identifier+"' not found in archive '"+mFileName+"'."); return MStatus::kFailure; } Alembic::AbcGeom::IXform obj(iObj,Alembic::Abc::kWrapExisting); if(!obj.valid()) { MGlobal::displayWarning("[ExocortexAlembic] Identifier '"+identifier+"' in archive '"+mFileName+"' is not a Xform."); return MStatus::kFailure; } mSchema = obj.getSchema(); if(!mSchema.valid()) return MStatus::kFailure; Alembic::AbcGeom::XformSample sample; mLastFloor = 0; mTimes.clear(); mMatrices.clear(); for(size_t i=0;i<mSchema.getNumSamples();i++) { mTimes.push_back((double)mSchema.getTimeSampling()->getStoredTimes()[i]); mSchema.get(sample,i); mMatrices.push_back(sample.getMatrix()); } } if(mTimes.size() == 0) return MStatus::kFailure; // find the index size_t index = mLastFloor; while(inputTime > mTimes[index] && index < mTimes.size()-1) index++; while(inputTime < mTimes[index] && index > 0) index--; Alembic::Abc::M44d matrix; if(fabs(inputTime - mTimes[index]) < 0.001 || index == mTimes.size()-1) { matrix = mMatrices[index]; } else { double blend = (inputTime - mTimes[index]) / (mTimes[index+1] - mTimes[index]); matrix = (1.0f - blend) * mMatrices[index] + blend * mMatrices[index+1]; } mLastFloor = index; // get the maya matrix MMatrix m(matrix.x); MTransformationMatrix transform(m); // decompose it MVector translation = transform.translation(MSpace::kTransform); double rotation[3]; MTransformationMatrix::RotationOrder order; transform.getRotation(rotation,order); double scale[3]; transform.getScale(scale,MSpace::kTransform); // output all channels dataBlock.outputValue(mOutTranslateXAttr).setDouble(translation.x); dataBlock.outputValue(mOutTranslateYAttr).setDouble(translation.y); dataBlock.outputValue(mOutTranslateZAttr).setDouble(translation.z); dataBlock.outputValue(mOutRotateXAttr).setMAngle(MAngle(rotation[0],MAngle::kRadians)); dataBlock.outputValue(mOutRotateYAttr).setMAngle(MAngle(rotation[1],MAngle::kRadians)); dataBlock.outputValue(mOutRotateZAttr).setMAngle(MAngle(rotation[2],MAngle::kRadians)); dataBlock.outputValue(mOutScaleXAttr).setDouble(scale[0]); dataBlock.outputValue(mOutScaleYAttr).setDouble(scale[1]); dataBlock.outputValue(mOutScaleZAttr).setDouble(scale[2]); return status; } <commit_msg>#50: alembic octopus crashes maya<commit_after>#include "AlembicXform.h" #include "MetaData.h" #include <maya/MFnTransform.h> namespace AbcA = ::Alembic::AbcCoreAbstract::ALEMBIC_VERSION_NS; using namespace AbcA; AlembicXform::AlembicXform(const MObject & in_Ref, AlembicWriteJob * in_Job) : AlembicObject(in_Ref, in_Job) { MFnDependencyNode node(in_Ref); MString name = truncateName(node.name())+"Xfo"; mObject = Alembic::AbcGeom::OXform(GetParentObject(),name.asChar(),GetJob()->GetAnimatedTs()); mSchema = mObject.getSchema(); } AlembicXform::~AlembicXform() { mObject.reset(); mSchema.reset(); } MStatus AlembicXform::Save(double time) { // access the xform MFnTransform node(GetRef()); // save the metadata SaveMetaData(this); // check if we have the global cache option bool globalCache = GetJob()->GetOption(L"exportInGlobalSpace").asInt() > 0; if(globalCache) { if(mNumSamples > 0) return MStatus::kSuccess; // store identity matrix mSample.setTranslation(Imath::V3d(0.0,0.0,0.0)); mSample.setRotation(Imath::V3d(1.0,0.0,0.0),0.0); mSample.setScale(Imath::V3d(1.0,1.0,1.0)); } else { MTransformationMatrix xf = node.transformation(); MMatrix matrix = xf.asMatrix(); Alembic::Abc::M44d abcMatrix; matrix.get(abcMatrix.x); mSample.setMatrix(abcMatrix); mSample.setInheritsXforms(true); } // save the sample mSchema.set(mSample); mNumSamples++; return MStatus::kSuccess; } void AlembicXformNode::PreDestruction() { mSchema.reset(); delRefArchive(mFileName); mFileName.clear(); } AlembicXformNode::~AlembicXformNode() { PreDestruction(); } MObject AlembicXformNode::mTimeAttr; MObject AlembicXformNode::mFileNameAttr; MObject AlembicXformNode::mIdentifierAttr; MObject AlembicXformNode::mOutTranslateXAttr; MObject AlembicXformNode::mOutTranslateYAttr; MObject AlembicXformNode::mOutTranslateZAttr; MObject AlembicXformNode::mOutTranslateAttr; MObject AlembicXformNode::mOutRotateXAttr; MObject AlembicXformNode::mOutRotateYAttr; MObject AlembicXformNode::mOutRotateZAttr; MObject AlembicXformNode::mOutRotateAttr; MObject AlembicXformNode::mOutScaleXAttr; MObject AlembicXformNode::mOutScaleYAttr; MObject AlembicXformNode::mOutScaleZAttr; MObject AlembicXformNode::mOutScaleAttr; MStatus AlembicXformNode::initialize() { MStatus status; MFnUnitAttribute uAttr; MFnTypedAttribute tAttr; MFnNumericAttribute nAttr; MFnGenericAttribute gAttr; MFnStringData emptyStringData; MObject emptyStringObject = emptyStringData.create(""); // input time mTimeAttr = uAttr.create("inTime", "tm", MFnUnitAttribute::kTime, 0.0); status = uAttr.setStorable(true); status = uAttr.setKeyable(true); status = addAttribute(mTimeAttr); // input file name mFileNameAttr = tAttr.create("fileName", "fn", MFnData::kString, emptyStringObject); status = tAttr.setStorable(true); status = tAttr.setUsedAsFilename(true); status = tAttr.setKeyable(false); status = addAttribute(mFileNameAttr); // input identifier mIdentifierAttr = tAttr.create("identifier", "it", MFnData::kString, emptyStringObject); status = tAttr.setStorable(true); status = tAttr.setKeyable(false); status = addAttribute(mIdentifierAttr); // output translateX mOutTranslateXAttr = nAttr.create("translateX", "tx", MFnNumericData::kDouble, 0.0); status = nAttr.setStorable(false); status = nAttr.setWritable(false); status = nAttr.setKeyable(false); status = nAttr.setHidden(false); // output translateY mOutTranslateYAttr = nAttr.create("translateY", "ty", MFnNumericData::kDouble, 0.0); status = nAttr.setStorable(false); status = nAttr.setWritable(false); status = nAttr.setKeyable(false); status = nAttr.setHidden(false); // output translateY mOutTranslateZAttr = nAttr.create("translateZ", "tz", MFnNumericData::kDouble, 0.0); status = nAttr.setStorable(false); status = nAttr.setWritable(false); status = nAttr.setKeyable(false); status = nAttr.setHidden(false); // output translate compound mOutTranslateAttr = nAttr.create( "translate", "t", mOutTranslateXAttr, mOutTranslateYAttr, mOutTranslateZAttr); status = nAttr.setStorable(false); status = nAttr.setWritable(false); status = nAttr.setKeyable(false); status = nAttr.setHidden(false); status = addAttribute(mOutTranslateAttr); // output rotatex mOutRotateXAttr = uAttr.create("rotateX", "rx", MFnUnitAttribute::kAngle, 0.0); status = uAttr.setStorable(false); status = uAttr.setWritable(false); status = uAttr.setKeyable(false); status = uAttr.setHidden(false); // output rotatexy mOutRotateYAttr = uAttr.create("rotateY", "ry", MFnUnitAttribute::kAngle, 0.0); status = uAttr.setStorable(false); status = uAttr.setWritable(false); status = uAttr.setKeyable(false); status = uAttr.setHidden(false); // output rotatez mOutRotateZAttr = uAttr.create("rotateZ", "rz", MFnUnitAttribute::kAngle, 0.0); status = uAttr.setStorable(false); status = uAttr.setWritable(false); status = uAttr.setKeyable(false); status = uAttr.setHidden(false); // output translate compound mOutRotateAttr = nAttr.create( "rotate", "r", mOutRotateXAttr, mOutRotateYAttr, mOutRotateZAttr); status = nAttr.setStorable(false); status = nAttr.setWritable(false); status = nAttr.setKeyable(false); status = nAttr.setHidden(false); status = addAttribute(mOutRotateAttr); // output scalex mOutScaleXAttr = nAttr.create("scaleX", "sx", MFnNumericData::kDouble, 1.0); status = nAttr.setStorable(false); status = nAttr.setWritable(false); status = nAttr.setKeyable(false); status = nAttr.setHidden(false); // output scaley mOutScaleYAttr = nAttr.create("scaleY", "sy", MFnNumericData::kDouble, 1.0); status = nAttr.setStorable(false); status = nAttr.setWritable(false); status = nAttr.setKeyable(false); status = nAttr.setHidden(false); // output scalez mOutScaleZAttr = nAttr.create("scaleZ", "sz", MFnNumericData::kDouble, 1.0); status = nAttr.setStorable(false); status = nAttr.setWritable(false); status = nAttr.setKeyable(false); status = nAttr.setHidden(false); // output translate compound mOutScaleAttr = nAttr.create( "scale", "s", mOutScaleXAttr, mOutScaleYAttr, mOutScaleZAttr); status = nAttr.setStorable(false); status = nAttr.setWritable(false); status = nAttr.setKeyable(false); status = nAttr.setHidden(false); status = addAttribute(mOutScaleAttr); // create a mapping status = attributeAffects(mTimeAttr, mOutTranslateXAttr); status = attributeAffects(mFileNameAttr, mOutTranslateXAttr); status = attributeAffects(mIdentifierAttr, mOutTranslateXAttr); status = attributeAffects(mTimeAttr, mOutTranslateYAttr); status = attributeAffects(mFileNameAttr, mOutTranslateYAttr); status = attributeAffects(mIdentifierAttr, mOutTranslateYAttr); status = attributeAffects(mTimeAttr, mOutTranslateZAttr); status = attributeAffects(mFileNameAttr, mOutTranslateZAttr); status = attributeAffects(mIdentifierAttr, mOutTranslateZAttr); status = attributeAffects(mTimeAttr, mOutRotateXAttr); status = attributeAffects(mFileNameAttr, mOutRotateXAttr); status = attributeAffects(mIdentifierAttr, mOutRotateXAttr); status = attributeAffects(mTimeAttr, mOutRotateYAttr); status = attributeAffects(mFileNameAttr, mOutRotateYAttr); status = attributeAffects(mIdentifierAttr, mOutRotateYAttr); status = attributeAffects(mTimeAttr, mOutRotateZAttr); status = attributeAffects(mFileNameAttr, mOutRotateZAttr); status = attributeAffects(mIdentifierAttr, mOutRotateZAttr); status = attributeAffects(mTimeAttr, mOutScaleXAttr); status = attributeAffects(mFileNameAttr, mOutScaleXAttr); status = attributeAffects(mIdentifierAttr, mOutScaleXAttr); status = attributeAffects(mTimeAttr, mOutScaleYAttr); status = attributeAffects(mFileNameAttr, mOutScaleYAttr); status = attributeAffects(mIdentifierAttr, mOutScaleYAttr); status = attributeAffects(mTimeAttr, mOutScaleZAttr); status = attributeAffects(mFileNameAttr, mOutScaleZAttr); status = attributeAffects(mIdentifierAttr, mOutScaleZAttr); return status; } MStatus AlembicXformNode::compute(const MPlug & plug, MDataBlock & dataBlock) { MStatus status; // update the frame number to be imported double inputTime = dataBlock.inputValue(mTimeAttr).asTime().as(MTime::kSeconds); MString & fileName = dataBlock.inputValue(mFileNameAttr).asString(); MString & identifier = dataBlock.inputValue(mIdentifierAttr).asString(); // check if we have the file if(fileName != mFileName || identifier != mIdentifier) { mSchema.reset(); if(fileName != mFileName) { delRefArchive(mFileName); mFileName = fileName; addRefArchive(mFileName); } mIdentifier = identifier; // get the object from the archive Alembic::Abc::IObject iObj = getObjectFromArchive(mFileName,identifier); if(!iObj.valid()) { MGlobal::displayWarning("[ExocortexAlembic] Identifier '"+identifier+"' not found in archive '"+mFileName+"'."); return MStatus::kFailure; } Alembic::AbcGeom::IXform obj(iObj,Alembic::Abc::kWrapExisting); if(!obj.valid()) { MGlobal::displayWarning("[ExocortexAlembic] Identifier '"+identifier+"' in archive '"+mFileName+"' is not a Xform."); return MStatus::kFailure; } mSchema = obj.getSchema(); if(!mSchema.valid()) return MStatus::kFailure; Alembic::AbcGeom::XformSample sample; mLastFloor = 0; mTimes.clear(); mMatrices.clear(); for(size_t i=0;i<mSchema.getNumSamples();i++) { if(mSchema.getTimeSampling()->getNumStoredTimes() <= i) break; mTimes.push_back((double)mSchema.getTimeSampling()->getStoredTimes()[i]); mSchema.get(sample,i); mMatrices.push_back(sample.getMatrix()); } } if(mTimes.size() == 0) return MStatus::kFailure; // find the index size_t index = mLastFloor; while(inputTime > mTimes[index] && index < mTimes.size()-1) index++; while(inputTime < mTimes[index] && index > 0) index--; Alembic::Abc::M44d matrix; if(fabs(inputTime - mTimes[index]) < 0.001 || index == mTimes.size()-1) { matrix = mMatrices[index]; } else { double blend = (inputTime - mTimes[index]) / (mTimes[index+1] - mTimes[index]); matrix = (1.0f - blend) * mMatrices[index] + blend * mMatrices[index+1]; } mLastFloor = index; // get the maya matrix MMatrix m(matrix.x); MTransformationMatrix transform(m); // decompose it MVector translation = transform.translation(MSpace::kTransform); double rotation[3]; MTransformationMatrix::RotationOrder order; transform.getRotation(rotation,order); double scale[3]; transform.getScale(scale,MSpace::kTransform); // output all channels dataBlock.outputValue(mOutTranslateXAttr).setDouble(translation.x); dataBlock.outputValue(mOutTranslateYAttr).setDouble(translation.y); dataBlock.outputValue(mOutTranslateZAttr).setDouble(translation.z); dataBlock.outputValue(mOutRotateXAttr).setMAngle(MAngle(rotation[0],MAngle::kRadians)); dataBlock.outputValue(mOutRotateYAttr).setMAngle(MAngle(rotation[1],MAngle::kRadians)); dataBlock.outputValue(mOutRotateZAttr).setMAngle(MAngle(rotation[2],MAngle::kRadians)); dataBlock.outputValue(mOutScaleXAttr).setDouble(scale[0]); dataBlock.outputValue(mOutScaleYAttr).setDouble(scale[1]); dataBlock.outputValue(mOutScaleZAttr).setDouble(scale[2]); return status; } <|endoftext|>
<commit_before>#include "AlembicXform.h" #include <xsi_application.h> #include <xsi_kinematics.h> #include <xsi_kinematicstate.h> #include <xsi_x3dobject.h> #include <xsi_math.h> #include <xsi_context.h> #include <xsi_operatorcontext.h> #include <xsi_customoperator.h> #include <xsi_factory.h> #include <xsi_parameter.h> #include <xsi_ppglayout.h> #include <xsi_ppgitem.h> #include <xsi_model.h> using namespace XSI; using namespace MATH; namespace AbcA = ::Alembic::AbcCoreAbstract::ALEMBIC_VERSION_NS; using namespace AbcA; void SaveXformSample(XSI::CRef kinestateRef, Alembic::AbcGeom::OXformSchema & schema, Alembic::AbcGeom::XformSample & sample, double time, bool xformCache) { KinematicState kineState(kinestateRef); // check if the transform is animated if(schema.getNumSamples() > 0) { X3DObject parent(kineState.GetParent3DObject()); if(!isRefAnimated(kineState.GetParent3DObject().GetRef(),xformCache)) return; } CTransformation global = kineState.GetTransform(time); if(!xformCache) { CTransformation model; kineState.GetParent3DObject().GetModel().GetKinematics().GetGlobal().GetTransform(time); global = MapWorldPoseToObjectSpace(model,global); } // store the transform CVector3 trans = global.GetTranslation(); CVector3 axis; double angle = global.GetRotationAxisAngle(axis); CVector3 scale = global.GetScaling(); sample.setTranslation(Imath::V3d(trans.GetX(),trans.GetY(),trans.GetZ())); sample.setRotation(Imath::V3d(axis.GetX(),axis.GetY(),axis.GetZ()),RadiansToDegrees(angle)); sample.setScale(Imath::V3d(scale.GetX(),scale.GetY(),scale.GetZ())); // save the sample schema.set(sample); } XSIPLUGINCALLBACK CStatus alembic_xform_Define( CRef& in_ctxt ) { return alembicOp_Define(in_ctxt); } XSIPLUGINCALLBACK CStatus alembic_xform_DefineLayout( CRef& in_ctxt ) { return alembicOp_DefineLayout(in_ctxt); } XSIPLUGINCALLBACK CStatus alembic_xform_Update( CRef& in_ctxt ) { OperatorContext ctxt( in_ctxt ); if((bool)ctxt.GetParameterValue(L"muted")) return CStatus::OK; CString path = ctxt.GetParameterValue(L"path"); CString identifier = ctxt.GetParameterValue(L"identifier"); Alembic::AbcGeom::IObject iObj = getObjectFromArchive(path,identifier); if(!iObj.valid()) return CStatus::OK; Alembic::AbcGeom::IXform obj(iObj,Alembic::Abc::kWrapExisting); if(!obj.valid()) return CStatus::OK; SampleInfo sampleInfo = getSampleInfo( ctxt.GetParameterValue(L"time"), obj.getSchema().getTimeSampling(), obj.getSchema().getNumSamples() ); Alembic::AbcGeom::XformSample sample; obj.getSchema().get(sample,sampleInfo.floorIndex); Alembic::Abc::M44d matrix = sample.getMatrix(); // blend if(sampleInfo.alpha != 0.0) { obj.getSchema().get(sample,sampleInfo.ceilIndex); Alembic::Abc::M44d ceilMatrix = sample.getMatrix(); matrix = (1.0 - sampleInfo.alpha) * matrix + sampleInfo.alpha * ceilMatrix; } CMatrix4 xsiMatrix; xsiMatrix.Set( matrix.getValue()[0],matrix.getValue()[1],matrix.getValue()[2],matrix.getValue()[3], matrix.getValue()[4],matrix.getValue()[5],matrix.getValue()[6],matrix.getValue()[7], matrix.getValue()[8],matrix.getValue()[9],matrix.getValue()[10],matrix.getValue()[11], matrix.getValue()[12],matrix.getValue()[13],matrix.getValue()[14],matrix.getValue()[15]); CTransformation xsiTransform; xsiTransform.SetMatrix4(xsiMatrix); KinematicState state(ctxt.GetOutputTarget()); state.PutTransform(xsiTransform); return CStatus::OK; } XSIPLUGINCALLBACK CStatus alembic_xform_Term(CRef & in_ctxt) { Context ctxt( in_ctxt ); CustomOperator op(ctxt.GetSource()); delRefArchive(op.GetParameterValue(L"path").GetAsText()); return CStatus::OK; } XSIPLUGINCALLBACK CStatus alembic_visibility_Define( CRef& in_ctxt ) { return alembicOp_Define(in_ctxt); } XSIPLUGINCALLBACK CStatus alembic_visibility_DefineLayout( CRef& in_ctxt ) { return alembicOp_DefineLayout(in_ctxt); } XSIPLUGINCALLBACK CStatus alembic_visibility_Update( CRef& in_ctxt ) { OperatorContext ctxt( in_ctxt ); if((bool)ctxt.GetParameterValue(L"muted")) return CStatus::OK; CString path = ctxt.GetParameterValue(L"path"); CString identifier = ctxt.GetParameterValue(L"identifier"); Alembic::AbcGeom::IObject obj = getObjectFromArchive(path,identifier); if(!obj.valid()) return CStatus::OK; Alembic::AbcGeom::IVisibilityProperty visibilityProperty = Alembic::AbcGeom::GetVisibilityProperty(obj); if(!visibilityProperty.valid()) return CStatus::OK; SampleInfo sampleInfo = getSampleInfo( ctxt.GetParameterValue(L"time"), getTimeSamplingFromObject(obj), visibilityProperty.getNumSamples() ); int8_t rawVisibilityValue = visibilityProperty.getValue ( sampleInfo.floorIndex ); Alembic::AbcGeom::ObjectVisibility visibilityValue = Alembic::AbcGeom::ObjectVisibility ( rawVisibilityValue ); Property prop(ctxt.GetOutputTarget()); switch(visibilityValue) { case Alembic::AbcGeom::kVisibilityVisible: { prop.PutParameterValue(L"viewvis",true); prop.PutParameterValue(L"rendvis",true); break; } case Alembic::AbcGeom::kVisibilityHidden: { prop.PutParameterValue(L"viewvis",false); prop.PutParameterValue(L"rendvis",false); break; } default: { break; } } return CStatus::OK; } XSIPLUGINCALLBACK CStatus alembic_visibility_Term(CRef & in_ctxt) { return alembicOp_Term(in_ctxt); } <commit_msg>transforms: internal cache to increase performance<commit_after>#include "AlembicXform.h" #include <xsi_application.h> #include <xsi_kinematics.h> #include <xsi_kinematicstate.h> #include <xsi_x3dobject.h> #include <xsi_math.h> #include <xsi_context.h> #include <xsi_operatorcontext.h> #include <xsi_customoperator.h> #include <xsi_factory.h> #include <xsi_parameter.h> #include <xsi_ppglayout.h> #include <xsi_ppgitem.h> #include <xsi_model.h> using namespace XSI; using namespace MATH; namespace AbcA = ::Alembic::AbcCoreAbstract::ALEMBIC_VERSION_NS; using namespace AbcA; void SaveXformSample(XSI::CRef kinestateRef, Alembic::AbcGeom::OXformSchema & schema, Alembic::AbcGeom::XformSample & sample, double time, bool xformCache) { KinematicState kineState(kinestateRef); // check if the transform is animated if(schema.getNumSamples() > 0) { X3DObject parent(kineState.GetParent3DObject()); if(!isRefAnimated(kineState.GetParent3DObject().GetRef(),xformCache)) return; } CTransformation global = kineState.GetTransform(time); if(!xformCache) { CTransformation model; kineState.GetParent3DObject().GetModel().GetKinematics().GetGlobal().GetTransform(time); global = MapWorldPoseToObjectSpace(model,global); } // store the transform CVector3 trans = global.GetTranslation(); CVector3 axis; double angle = global.GetRotationAxisAngle(axis); CVector3 scale = global.GetScaling(); sample.setTranslation(Imath::V3d(trans.GetX(),trans.GetY(),trans.GetZ())); sample.setRotation(Imath::V3d(axis.GetX(),axis.GetY(),axis.GetZ()),RadiansToDegrees(angle)); sample.setScale(Imath::V3d(scale.GetX(),scale.GetY(),scale.GetZ())); // save the sample schema.set(sample); } XSIPLUGINCALLBACK CStatus alembic_xform_Define( CRef& in_ctxt ) { return alembicOp_Define(in_ctxt); } XSIPLUGINCALLBACK CStatus alembic_xform_DefineLayout( CRef& in_ctxt ) { return alembicOp_DefineLayout(in_ctxt); } struct alembic_xform_UD { std::vector<double> times; size_t lastFloor; std::vector<Alembic::Abc::M44d> matrices; }; XSIPLUGINCALLBACK CStatus alembic_xform_Update( CRef& in_ctxt ) { OperatorContext ctxt( in_ctxt ); if((bool)ctxt.GetParameterValue(L"muted")) return CStatus::OK; CValue udVal = ctxt.GetUserData(); alembic_xform_UD * p = (alembic_xform_UD*)(CValue::siPtrType)udVal; if(p == NULL) { CString path = ctxt.GetParameterValue(L"path"); CString identifier = ctxt.GetParameterValue(L"identifier"); Alembic::AbcGeom::IObject iObj = getObjectFromArchive(path,identifier); if(!iObj.valid()) return CStatus::OK; Alembic::AbcGeom::IXform obj(iObj,Alembic::Abc::kWrapExisting); if(!obj.valid()) return CStatus::OK; p = new alembic_xform_UD(); p->lastFloor = 0; Alembic::AbcGeom::XformSample sample; for(size_t i=0;i<obj.getSchema().getNumSamples();i++) { p->times.push_back((double)obj.getSchema().getTimeSampling()->getStoredTimes()[i]); obj.getSchema().get(sample,i); p->matrices.push_back(sample.getMatrix()); } CValue val = (CValue::siPtrType) p; ctxt.PutUserData( val ) ; } double time = ctxt.GetParameterValue(L"time"); // find the index size_t index = p->lastFloor; while(time > p->times[index] && index < p->times.size()-1) index++; while(time < p->times[index] && index > 0) index--; Alembic::Abc::M44d matrix; if(fabs(time - p->times[index]) < 0.001 || index == p->times.size()-1) { matrix = p->matrices[index]; } else { double blend = (time - p->times[index]) / (p->times[index+1] - p->times[index]); matrix = (1.0f - blend) * p->matrices[index] + blend * p->matrices[index+1]; } p->lastFloor = index; CMatrix4 xsiMatrix; xsiMatrix.Set( matrix.getValue()[0],matrix.getValue()[1],matrix.getValue()[2],matrix.getValue()[3], matrix.getValue()[4],matrix.getValue()[5],matrix.getValue()[6],matrix.getValue()[7], matrix.getValue()[8],matrix.getValue()[9],matrix.getValue()[10],matrix.getValue()[11], matrix.getValue()[12],matrix.getValue()[13],matrix.getValue()[14],matrix.getValue()[15]); CTransformation xsiTransform; xsiTransform.SetMatrix4(xsiMatrix); KinematicState state(ctxt.GetOutputTarget()); state.PutTransform(xsiTransform); return CStatus::OK; } XSIPLUGINCALLBACK CStatus alembic_xform_Term(CRef & in_ctxt) { Context ctxt( in_ctxt ); CustomOperator op(ctxt.GetSource()); delRefArchive(op.GetParameterValue(L"path").GetAsText()); CValue udVal = ctxt.GetUserData(); alembic_xform_UD * p = (alembic_xform_UD*)(CValue::siPtrType)udVal; if(p!=NULL) { delete(p); p = NULL; } return CStatus::OK; } XSIPLUGINCALLBACK CStatus alembic_visibility_Define( CRef& in_ctxt ) { return alembicOp_Define(in_ctxt); } XSIPLUGINCALLBACK CStatus alembic_visibility_DefineLayout( CRef& in_ctxt ) { return alembicOp_DefineLayout(in_ctxt); } XSIPLUGINCALLBACK CStatus alembic_visibility_Update( CRef& in_ctxt ) { OperatorContext ctxt( in_ctxt ); if((bool)ctxt.GetParameterValue(L"muted")) return CStatus::OK; CString path = ctxt.GetParameterValue(L"path"); CString identifier = ctxt.GetParameterValue(L"identifier"); Alembic::AbcGeom::IObject obj = getObjectFromArchive(path,identifier); if(!obj.valid()) return CStatus::OK; Alembic::AbcGeom::IVisibilityProperty visibilityProperty = Alembic::AbcGeom::GetVisibilityProperty(obj); if(!visibilityProperty.valid()) return CStatus::OK; SampleInfo sampleInfo = getSampleInfo( ctxt.GetParameterValue(L"time"), getTimeSamplingFromObject(obj), visibilityProperty.getNumSamples() ); int8_t rawVisibilityValue = visibilityProperty.getValue ( sampleInfo.floorIndex ); Alembic::AbcGeom::ObjectVisibility visibilityValue = Alembic::AbcGeom::ObjectVisibility ( rawVisibilityValue ); Property prop(ctxt.GetOutputTarget()); switch(visibilityValue) { case Alembic::AbcGeom::kVisibilityVisible: { prop.PutParameterValue(L"viewvis",true); prop.PutParameterValue(L"rendvis",true); break; } case Alembic::AbcGeom::kVisibilityHidden: { prop.PutParameterValue(L"viewvis",false); prop.PutParameterValue(L"rendvis",false); break; } default: { break; } } return CStatus::OK; } XSIPLUGINCALLBACK CStatus alembic_visibility_Term(CRef & in_ctxt) { return alembicOp_Term(in_ctxt); } <|endoftext|>
<commit_before>/* medMainWindow.cpp --- * * Author: Julien Wintz * Copyright (C) 2008 - Julien Wintz, Inria. * Created: Fri Sep 18 12:48:07 2009 (+0200) * Version: $Id$ * Last-Updated: Tue Oct 20 09:57:15 2009 (+0200) * By: Julien Wintz * Update #: 114 */ /* Commentary: * */ /* Change log: * */ #include "medBrowserArea.h" #include "medMainWindow.h" #include "medViewerArea.h" #include "medWelcomeArea.h" #include <dtkScript/dtkScriptInterpreter.h> #include <dtkScript/dtkScriptInterpreterPool.h> #include <dtkScript/dtkScriptInterpreterPython.h> #include <dtkScript/dtkScriptInterpreterTcl.h> #include <dtkCore/dtkAbstractViewFactory.h> #include <dtkCore/dtkAbstractView.h> #include <dtkCore/dtkAbstractDataFactory.h> #include <dtkCore/dtkAbstractData.h> #include <dtkCore/dtkAbstractDataReader.h> #include <medSql/medDatabaseController.h> #include <medSql/medDatabaseView.h> #include <medSql/medDatabaseModel.h> #include <medSql/medDatabaseItem.h> #include <QtGui> class medMainWindowPrivate { public: QStackedWidget *stack; medWelcomeArea *welcomeArea; medBrowserArea *browserArea; medViewerArea *viewerArea; QToolBar *toolBar; QAction *switchToWelcomeAreaAction; QAction *switchToBrowserAreaAction; QAction *switchToViewerAreaAction; }; extern "C" int init_core(void); // -- Initialization core layer python wrapped functions extern "C" int Core_Init(Tcl_Interp *interp); // -- Initialization core layer tcl wrapped functions medMainWindow::medMainWindow(QWidget *parent) : QMainWindow(parent), d(new medMainWindowPrivate) { // Setting up database connection if(!medDatabaseController::instance()->createConnection()) qDebug() << "Unable to create a connection to the database"; // Setting up widgets d->welcomeArea = new medWelcomeArea(this); d->browserArea = new medBrowserArea(this); d->viewerArea = new medViewerArea(this); d->stack = new QStackedWidget(this); d->stack->addWidget(d->welcomeArea); d->stack->addWidget(d->browserArea); d->stack->addWidget(d->viewerArea); d->switchToWelcomeAreaAction = new QAction(this); d->switchToBrowserAreaAction = new QAction(this); d->switchToViewerAreaAction = new QAction(this); #if defined(Q_WS_MAC) d->switchToWelcomeAreaAction->setShortcut(Qt::MetaModifier + Qt::Key_1); d->switchToBrowserAreaAction->setShortcut(Qt::MetaModifier + Qt::Key_2); d->switchToViewerAreaAction->setShortcut(Qt::MetaModifier + Qt::Key_3); #else d->switchToWelcomeAreaAction->setShortcut(Qt::ControlModifier + Qt::Key_1); d->switchToBrowserAreaAction->setShortcut(Qt::ControlModifier + Qt::Key_2); d->switchToViewerAreaAction->setShortcut(Qt::ControlModifier + Qt::Key_3); #endif if(!(qApp->arguments().contains("--fullscreen"))) { d->switchToWelcomeAreaAction->setEnabled(false); d->switchToWelcomeAreaAction->setText("Welcome"); d->switchToWelcomeAreaAction->setToolTip("Switch to the welcome area (Ctrl+1)"); d->switchToWelcomeAreaAction->setIcon(QIcon(":/icons/widget.tiff")); d->switchToBrowserAreaAction->setEnabled(true); d->switchToBrowserAreaAction->setText("Browser"); d->switchToBrowserAreaAction->setToolTip("Switch to the borwser area (Ctrl+2)"); d->switchToBrowserAreaAction->setIcon(QIcon(":/icons/widget.tiff")); d->switchToViewerAreaAction->setEnabled(true); d->switchToViewerAreaAction->setText("Viewer"); d->switchToViewerAreaAction->setToolTip("Switch to the viewer area (Ctrl+3)"); d->switchToViewerAreaAction->setIcon(QIcon(":/icons/widget.tiff")); d->toolBar = this->addToolBar("Areas"); #ifdef Q_WS_MAC d->toolBar->setStyle(QStyleFactory::create("macintosh")); d->toolBar->setStyleSheet("*:enabled { color: black; } *:disabled { color: gray; }"); #endif d->toolBar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); d->toolBar->setIconSize(QSize(32, 32)); d->toolBar->addAction(d->switchToWelcomeAreaAction); d->toolBar->addAction(d->switchToBrowserAreaAction); d->toolBar->addAction(d->switchToViewerAreaAction); this->setUnifiedTitleAndToolBarOnMac(true); } connect(d->switchToWelcomeAreaAction, SIGNAL(triggered()), this, SLOT(switchToWelcomeArea())); connect(d->switchToBrowserAreaAction, SIGNAL(triggered()), this, SLOT(switchToBrowserArea())); connect(d->switchToViewerAreaAction, SIGNAL(triggered()), this, SLOT(switchToViewerArea())); connect(d->browserArea->view(), SIGNAL(patientDoubleClicked(const QModelIndex&)), this, SLOT(onPatientDoubleClicked (const QModelIndex&))); connect(d->browserArea->view(), SIGNAL(studyDoubleClicked(const QModelIndex&)), this, SLOT(onStudyDoubleClicked (const QModelIndex&))); connect(d->browserArea->view(), SIGNAL(seriesDoubleClicked(const QModelIndex&)), this, SLOT(onSeriesDoubleClicked (const QModelIndex&))); connect(d->viewerArea, SIGNAL(seriesSelected(int)), this, SLOT(onSeriesSelected(int))); this->addAction(d->switchToWelcomeAreaAction); this->addAction(d->switchToBrowserAreaAction); this->addAction(d->switchToViewerAreaAction); this->setWindowTitle("Medular"); this->setCentralWidget(d->stack); this->readSettings(); // Setting up core python module dtkScriptInterpreterPythonModuleManager::instance()->registerInitializer(&init_core); dtkScriptInterpreterPythonModuleManager::instance()->registerCommand( "import core" ); dtkScriptInterpreterPythonModuleManager::instance()->registerCommand( "dataFactory = core.dtkAbstractDataFactory.instance()" ); dtkScriptInterpreterPythonModuleManager::instance()->registerCommand( "processFactory = core.dtkAbstractProcessFactory.instance()" ); dtkScriptInterpreterPythonModuleManager::instance()->registerCommand( "viewFactory = core.dtkAbstractViewFactory.instance()" ); dtkScriptInterpreterPythonModuleManager::instance()->registerCommand( "pluginManager = core.dtkPluginManager.instance()" ); dtkScriptInterpreterPythonModuleManager::instance()->registerCommand( "deviceFactory = core.dtkAbstractDeviceFactory.instance()" ); // Setting up core tcl module dtkScriptInterpreterTclModuleManager::instance()->registerInitializer(&Core_Init); dtkScriptInterpreterTclModuleManager::instance()->registerCommand( "set dataFactory [dtkAbstractDataFactory_instance]" ); dtkScriptInterpreterTclModuleManager::instance()->registerCommand( "set processFactory [dtkAbstractProcessFactory_instance]" ); dtkScriptInterpreterTclModuleManager::instance()->registerCommand( "set viewFactory [dtkAbstractViewFactory_instance]" ); dtkScriptInterpreterTclModuleManager::instance()->registerCommand( "set pluginManager [dtkPluginManager_instance]" ); } medMainWindow::~medMainWindow(void) { delete d; d = NULL; } void medMainWindow::readSettings(void) { QSettings settings("inria", "medular"); settings.beginGroup("medular"); QPoint pos = settings.value("pos", QPoint(200, 200)).toPoint(); QSize size = settings.value("size", QSize(600, 400)).toSize(); move(pos); resize(size); settings.endGroup(); } void medMainWindow::writeSettings(void) { QSettings settings("inria", "medular"); settings.beginGroup("medular"); settings.setValue("pos", pos()); settings.setValue("size", size()); settings.endGroup(); } void medMainWindow::switchToWelcomeArea(void) { d->stack->setCurrentWidget(d->welcomeArea); d->switchToWelcomeAreaAction->setEnabled(false); d->switchToBrowserAreaAction->setEnabled(true); d->switchToViewerAreaAction->setEnabled(true); } void medMainWindow::switchToBrowserArea(void) { d->stack->setCurrentWidget(d->browserArea); d->switchToWelcomeAreaAction->setEnabled(true); d->switchToBrowserAreaAction->setEnabled(false); d->switchToViewerAreaAction->setEnabled(true); } void medMainWindow::switchToViewerArea(void) { d->stack->setCurrentWidget(d->viewerArea); d->switchToWelcomeAreaAction->setEnabled(true); d->switchToBrowserAreaAction->setEnabled(true); d->switchToViewerAreaAction->setEnabled(false); } void medMainWindow::onPatientDoubleClicked(const QModelIndex &index) { if (!index.isValid()) return; d->viewerArea->setPatientIndex(index.row()+1); switchToViewerArea(); } void medMainWindow::onStudyDoubleClicked(const QModelIndex &index) { if (!index.isValid()) return; QModelIndex patientIndex = index.parent(); if (!patientIndex.isValid()) return; d->viewerArea->setPatientIndex(patientIndex.row()+1); d->viewerArea->setStudyIndex(index.row()+1); switchToViewerArea(); } void medMainWindow::onSeriesDoubleClicked(const QModelIndex &index) { if (!index.isValid()) return; QModelIndex studyIndex = index.parent(); if (!studyIndex.isValid()) return; QModelIndex patientIndex = studyIndex.parent(); if (!patientIndex.isValid()) return; d->viewerArea->setPatientIndex(patientIndex.row()+1); d->viewerArea->setStudyIndex(studyIndex.row()+1); d->viewerArea->setSeriesIndex(index.row()+1); switchToViewerArea(); } void medMainWindow::closeEvent(QCloseEvent *event) { this->writeSettings(); delete medDatabaseController::instance(); } <commit_msg>Cleaning signal connections<commit_after>/* medMainWindow.cpp --- * * Author: Julien Wintz * Copyright (C) 2008 - Julien Wintz, Inria. * Created: Fri Sep 18 12:48:07 2009 (+0200) * Version: $Id$ * Last-Updated: Tue Oct 20 10:14:22 2009 (+0200) * By: Julien Wintz * Update #: 115 */ /* Commentary: * */ /* Change log: * */ #include "medBrowserArea.h" #include "medMainWindow.h" #include "medViewerArea.h" #include "medWelcomeArea.h" #include <dtkScript/dtkScriptInterpreter.h> #include <dtkScript/dtkScriptInterpreterPool.h> #include <dtkScript/dtkScriptInterpreterPython.h> #include <dtkScript/dtkScriptInterpreterTcl.h> #include <dtkCore/dtkAbstractViewFactory.h> #include <dtkCore/dtkAbstractView.h> #include <dtkCore/dtkAbstractDataFactory.h> #include <dtkCore/dtkAbstractData.h> #include <dtkCore/dtkAbstractDataReader.h> #include <medSql/medDatabaseController.h> #include <medSql/medDatabaseView.h> #include <medSql/medDatabaseModel.h> #include <medSql/medDatabaseItem.h> #include <QtGui> class medMainWindowPrivate { public: QStackedWidget *stack; medWelcomeArea *welcomeArea; medBrowserArea *browserArea; medViewerArea *viewerArea; QToolBar *toolBar; QAction *switchToWelcomeAreaAction; QAction *switchToBrowserAreaAction; QAction *switchToViewerAreaAction; }; extern "C" int init_core(void); // -- Initialization core layer python wrapped functions extern "C" int Core_Init(Tcl_Interp *interp); // -- Initialization core layer tcl wrapped functions medMainWindow::medMainWindow(QWidget *parent) : QMainWindow(parent), d(new medMainWindowPrivate) { // Setting up database connection if(!medDatabaseController::instance()->createConnection()) qDebug() << "Unable to create a connection to the database"; // Setting up widgets d->welcomeArea = new medWelcomeArea(this); d->browserArea = new medBrowserArea(this); d->viewerArea = new medViewerArea(this); d->stack = new QStackedWidget(this); d->stack->addWidget(d->welcomeArea); d->stack->addWidget(d->browserArea); d->stack->addWidget(d->viewerArea); d->switchToWelcomeAreaAction = new QAction(this); d->switchToBrowserAreaAction = new QAction(this); d->switchToViewerAreaAction = new QAction(this); #if defined(Q_WS_MAC) d->switchToWelcomeAreaAction->setShortcut(Qt::MetaModifier + Qt::Key_1); d->switchToBrowserAreaAction->setShortcut(Qt::MetaModifier + Qt::Key_2); d->switchToViewerAreaAction->setShortcut(Qt::MetaModifier + Qt::Key_3); #else d->switchToWelcomeAreaAction->setShortcut(Qt::ControlModifier + Qt::Key_1); d->switchToBrowserAreaAction->setShortcut(Qt::ControlModifier + Qt::Key_2); d->switchToViewerAreaAction->setShortcut(Qt::ControlModifier + Qt::Key_3); #endif if(!(qApp->arguments().contains("--fullscreen"))) { d->switchToWelcomeAreaAction->setEnabled(false); d->switchToWelcomeAreaAction->setText("Welcome"); d->switchToWelcomeAreaAction->setToolTip("Switch to the welcome area (Ctrl+1)"); d->switchToWelcomeAreaAction->setIcon(QIcon(":/icons/widget.tiff")); d->switchToBrowserAreaAction->setEnabled(true); d->switchToBrowserAreaAction->setText("Browser"); d->switchToBrowserAreaAction->setToolTip("Switch to the borwser area (Ctrl+2)"); d->switchToBrowserAreaAction->setIcon(QIcon(":/icons/widget.tiff")); d->switchToViewerAreaAction->setEnabled(true); d->switchToViewerAreaAction->setText("Viewer"); d->switchToViewerAreaAction->setToolTip("Switch to the viewer area (Ctrl+3)"); d->switchToViewerAreaAction->setIcon(QIcon(":/icons/widget.tiff")); d->toolBar = this->addToolBar("Areas"); #ifdef Q_WS_MAC d->toolBar->setStyle(QStyleFactory::create("macintosh")); d->toolBar->setStyleSheet("*:enabled { color: black; } *:disabled { color: gray; }"); #endif d->toolBar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); d->toolBar->setIconSize(QSize(32, 32)); d->toolBar->addAction(d->switchToWelcomeAreaAction); d->toolBar->addAction(d->switchToBrowserAreaAction); d->toolBar->addAction(d->switchToViewerAreaAction); this->setUnifiedTitleAndToolBarOnMac(true); } connect(d->switchToWelcomeAreaAction, SIGNAL(triggered()), this, SLOT(switchToWelcomeArea())); connect(d->switchToBrowserAreaAction, SIGNAL(triggered()), this, SLOT(switchToBrowserArea())); connect(d->switchToViewerAreaAction, SIGNAL(triggered()), this, SLOT(switchToViewerArea())); connect(d->browserArea->view(), SIGNAL(patientDoubleClicked(const QModelIndex&)), this, SLOT(onPatientDoubleClicked (const QModelIndex&))); connect(d->browserArea->view(), SIGNAL(studyDoubleClicked(const QModelIndex&)), this, SLOT(onStudyDoubleClicked (const QModelIndex&))); connect(d->browserArea->view(), SIGNAL(seriesDoubleClicked(const QModelIndex&)), this, SLOT(onSeriesDoubleClicked (const QModelIndex&))); this->addAction(d->switchToWelcomeAreaAction); this->addAction(d->switchToBrowserAreaAction); this->addAction(d->switchToViewerAreaAction); this->setWindowTitle("Medular"); this->setCentralWidget(d->stack); this->readSettings(); // Setting up core python module dtkScriptInterpreterPythonModuleManager::instance()->registerInitializer(&init_core); dtkScriptInterpreterPythonModuleManager::instance()->registerCommand( "import core" ); dtkScriptInterpreterPythonModuleManager::instance()->registerCommand( "dataFactory = core.dtkAbstractDataFactory.instance()" ); dtkScriptInterpreterPythonModuleManager::instance()->registerCommand( "processFactory = core.dtkAbstractProcessFactory.instance()" ); dtkScriptInterpreterPythonModuleManager::instance()->registerCommand( "viewFactory = core.dtkAbstractViewFactory.instance()" ); dtkScriptInterpreterPythonModuleManager::instance()->registerCommand( "pluginManager = core.dtkPluginManager.instance()" ); dtkScriptInterpreterPythonModuleManager::instance()->registerCommand( "deviceFactory = core.dtkAbstractDeviceFactory.instance()" ); // Setting up core tcl module dtkScriptInterpreterTclModuleManager::instance()->registerInitializer(&Core_Init); dtkScriptInterpreterTclModuleManager::instance()->registerCommand( "set dataFactory [dtkAbstractDataFactory_instance]" ); dtkScriptInterpreterTclModuleManager::instance()->registerCommand( "set processFactory [dtkAbstractProcessFactory_instance]" ); dtkScriptInterpreterTclModuleManager::instance()->registerCommand( "set viewFactory [dtkAbstractViewFactory_instance]" ); dtkScriptInterpreterTclModuleManager::instance()->registerCommand( "set pluginManager [dtkPluginManager_instance]" ); } medMainWindow::~medMainWindow(void) { delete d; d = NULL; } void medMainWindow::readSettings(void) { QSettings settings("inria", "medular"); settings.beginGroup("medular"); QPoint pos = settings.value("pos", QPoint(200, 200)).toPoint(); QSize size = settings.value("size", QSize(600, 400)).toSize(); move(pos); resize(size); settings.endGroup(); } void medMainWindow::writeSettings(void) { QSettings settings("inria", "medular"); settings.beginGroup("medular"); settings.setValue("pos", pos()); settings.setValue("size", size()); settings.endGroup(); } void medMainWindow::switchToWelcomeArea(void) { d->stack->setCurrentWidget(d->welcomeArea); d->switchToWelcomeAreaAction->setEnabled(false); d->switchToBrowserAreaAction->setEnabled(true); d->switchToViewerAreaAction->setEnabled(true); } void medMainWindow::switchToBrowserArea(void) { d->stack->setCurrentWidget(d->browserArea); d->switchToWelcomeAreaAction->setEnabled(true); d->switchToBrowserAreaAction->setEnabled(false); d->switchToViewerAreaAction->setEnabled(true); } void medMainWindow::switchToViewerArea(void) { d->stack->setCurrentWidget(d->viewerArea); d->switchToWelcomeAreaAction->setEnabled(true); d->switchToBrowserAreaAction->setEnabled(true); d->switchToViewerAreaAction->setEnabled(false); } void medMainWindow::onPatientDoubleClicked(const QModelIndex &index) { if (!index.isValid()) return; d->viewerArea->setPatientIndex(index.row()+1); switchToViewerArea(); } void medMainWindow::onStudyDoubleClicked(const QModelIndex &index) { if (!index.isValid()) return; QModelIndex patientIndex = index.parent(); if (!patientIndex.isValid()) return; d->viewerArea->setPatientIndex(patientIndex.row()+1); d->viewerArea->setStudyIndex(index.row()+1); switchToViewerArea(); } void medMainWindow::onSeriesDoubleClicked(const QModelIndex &index) { if (!index.isValid()) return; QModelIndex studyIndex = index.parent(); if (!studyIndex.isValid()) return; QModelIndex patientIndex = studyIndex.parent(); if (!patientIndex.isValid()) return; d->viewerArea->setPatientIndex(patientIndex.row()+1); d->viewerArea->setStudyIndex(studyIndex.row()+1); d->viewerArea->setSeriesIndex(index.row()+1); switchToViewerArea(); } void medMainWindow::closeEvent(QCloseEvent *event) { this->writeSettings(); delete medDatabaseController::instance(); } <|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. * **************************************************************************/ /* $Log$ */ //-*-C++-*- //_________________________________________________________________________ // Base Class of Cluster (empty cxx needed by Root) //*-- Author : Yves Schutz SUBATECH ////////////////////////////////////////////////////////////////////////////// // --- ROOT system --- #include "TObjArray.h" // --- Standard library --- // --- AliRoot header files --- #include "AliRecPoint.h" ClassImp(AliRecPoint) //____________________________________________________________________________ AliRecPoint::AliRecPoint() { // ctor fAmp = 0.0 ; fLocPos.SetXYZ(0., 0., 0.) ; fLocPosM = new TMatrix(3,3) ; fMaxDigit = 100 ; fMulDigit = 0 ; fDigitsList = new int[fMaxDigit]; ; fMaxTrack = 5 ; fMulTrack = 0 ; fTracksList = new int[fMaxTrack]; ; } //____________________________________________________________________________ AliRecPoint::~AliRecPoint() { // dtor delete fLocPosM ; if ( fDigitsList ) delete fDigitsList ; if ( fTracksList ) delete fTracksList ; } //____________________________________________________________________________ void AliRecPoint::AddDigit(AliDigitNew & digit) { // adds a digit to the digits list // and accumulates the total amplitude and the multiplicity if ( fMulDigit >= fMaxDigit ) { // increase the size of the list int * tempo = new ( int[fMaxDigit*=2] ) ; Int_t index ; for ( index = 0 ; index < fMulDigit ; index++ ) tempo[index] = fDigitsList[index] ; delete fDigitsList ; fDigitsList = tempo ; } fDigitsList[fMulDigit++]= (int) &digit ; fAmp += digit.GetAmp() ; } //____________________________________________________________________________ // void AliRecPoint::AddTrack(AliTrack & track) // { // // adds a digit to the digits list // // and accumulates the total amplitude and the multiplicity // if ( fMulTrack >= fMaxTrack ) { // increase the size of the list // int * tempo = new int[fMaxTrack*=2] ; // Int_t index ; // for ( index = 0 ; index < fMulTrack ; index++ ) // tempo[index] = fTracksList[index] ; // delete fTracksList ; // fTracksList = tempo ; // } // fTracksList[fMulTrack++]= (int) &Track ; // } //____________________________________________________________________________ void AliRecPoint::GetCovarianceMatrix(TMatrix & mat) { // returns the covariant matrix for the local position mat = *fLocPosM ; } //____________________________________________________________________________ void AliRecPoint::GetLocalPosition(TVector3 & pos) { // returns the position of the cluster in the local reference system of the sub-detector pos = fLocPos; } //____________________________________________________________________________ void AliRecPoint::GetGlobalPosition(TVector3 & gpos, TMatrix & gmat) { // returns the position of the cluster in the global reference system of ALICE // and the uncertainty on this position fGeom->GetGlobal(this, gpos, gmat) ; } //______________________________________________________________________________ void AliRecPoint::Streamer(TBuffer &R__b) { // Stream an object of class AliRecPoint. if (R__b.IsReading()) { Version_t R__v = R__b.ReadVersion(); if (R__v) { } TObject::Streamer(R__b); R__b >> fAmp; R__b.ReadArray(fDigitsList); R__b >> fGeom; fLocPos.Streamer(R__b); R__b >> fLocPosM; R__b >> fMulDigit; R__b >> fMulTrack; R__b.ReadArray(fTracksList); } else { R__b.WriteVersion(AliRecPoint::IsA()); TObject::Streamer(R__b); R__b << fAmp; R__b.WriteArray(fDigitsList, fMaxDigit); R__b << fGeom; fLocPos.Streamer(R__b); R__b << fLocPosM; R__b << fMulDigit; R__b << fMulTrack; R__b.WriteArray(fTracksList, fMaxTrack); } } <commit_msg>Corrections - a bug in the streamer (wrong size of the arrays) - replace Read/WriteArray by Read/WriteFastArray (suggestion R.Brun)<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. * **************************************************************************/ /* $Log$ Revision 1.1 1999/12/17 09:01:14 fca Y.Schutz new classes for reconstruction */ //-*-C++-*- //_________________________________________________________________________ // Base Class of Cluster (empty cxx needed by Root) //*-- Author : Yves Schutz SUBATECH ////////////////////////////////////////////////////////////////////////////// // --- ROOT system --- #include "TObjArray.h" // --- Standard library --- // --- AliRoot header files --- #include "AliRecPoint.h" ClassImp(AliRecPoint) //____________________________________________________________________________ AliRecPoint::AliRecPoint() { // ctor fAmp = 0.0 ; fLocPos.SetXYZ(0., 0., 0.) ; fLocPosM = new TMatrix(3,3) ; fMaxDigit = 100 ; fMulDigit = 0 ; fDigitsList = new int[fMaxDigit]; ; fMaxTrack = 5 ; fMulTrack = 0 ; fTracksList = new int[fMaxTrack]; ; } //____________________________________________________________________________ AliRecPoint::~AliRecPoint() { // dtor delete fLocPosM ; if ( fDigitsList ) delete fDigitsList ; if ( fTracksList ) delete fTracksList ; } //____________________________________________________________________________ void AliRecPoint::AddDigit(AliDigitNew & digit) { // adds a digit to the digits list // and accumulates the total amplitude and the multiplicity if ( fMulDigit >= fMaxDigit ) { // increase the size of the list int * tempo = new ( int[fMaxDigit*=2] ) ; Int_t index ; for ( index = 0 ; index < fMulDigit ; index++ ) tempo[index] = fDigitsList[index] ; delete fDigitsList ; fDigitsList = tempo ; } fDigitsList[fMulDigit++]= (int) &digit ; fAmp += digit.GetAmp() ; } //____________________________________________________________________________ // void AliRecPoint::AddTrack(AliTrack & track) // { // // adds a digit to the digits list // // and accumulates the total amplitude and the multiplicity // if ( fMulTrack >= fMaxTrack ) { // increase the size of the list // int * tempo = new int[fMaxTrack*=2] ; // Int_t index ; // for ( index = 0 ; index < fMulTrack ; index++ ) // tempo[index] = fTracksList[index] ; // delete fTracksList ; // fTracksList = tempo ; // } // fTracksList[fMulTrack++]= (int) &Track ; // } //____________________________________________________________________________ void AliRecPoint::GetCovarianceMatrix(TMatrix & mat) { // returns the covariant matrix for the local position mat = *fLocPosM ; } //____________________________________________________________________________ void AliRecPoint::GetLocalPosition(TVector3 & pos) { // returns the position of the cluster in the local reference system of the sub-detector pos = fLocPos; } //____________________________________________________________________________ void AliRecPoint::GetGlobalPosition(TVector3 & gpos, TMatrix & gmat) { // returns the position of the cluster in the global reference system of ALICE // and the uncertainty on this position fGeom->GetGlobal(this, gpos, gmat) ; } //______________________________________________________________________________ void AliRecPoint::Streamer(TBuffer &R__b) { // Stream an object of class AliRecPoint. if (R__b.IsReading()) { Version_t R__v = R__b.ReadVersion(); if (R__v) { } TObject::Streamer(R__b); R__b >> fAmp; R__b >> fMulDigit; fDigitsList = new Int_t[fMulDigit] ; R__b.ReadFastArray(fDigitsList, fMulDigit); R__b >> fGeom; fLocPos.Streamer(R__b); R__b >> fLocPosM; R__b >> fMulTrack; fTracksList = new Int_t[fMulTrack] ; R__b.ReadFastArray(fTracksList, fMulTrack); } else { R__b.WriteVersion(AliRecPoint::IsA()); TObject::Streamer(R__b); R__b << fAmp; R__b << fMulDigit; R__b.WriteFastArray(fDigitsList, fMulDigit); R__b << fGeom; fLocPos.Streamer(R__b); R__b << fLocPosM; R__b << fMulTrack; R__b.WriteFastArray(fTracksList, fMulTrack); } } <|endoftext|>
<commit_before>// Copyright (c) 2009-2017 The Bitcoin Core developers // Copyright (c) 2017 The PIVX 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/pivx-config.h" #endif #include <cstddef> #include <cstdint> #if defined(HAVE_SYS_SELECT_H) #include <sys/select.h> #endif // Prior to GLIBC_2.14, memcpy was aliased to memmove. extern "C" void* memmove(void* a, const void* b, size_t c); extern "C" void* memcpy(void* a, const void* b, size_t c) { return memmove(a, b, c); } extern "C" void __chk_fail(void) __attribute__((__noreturn__)); extern "C" FDELT_TYPE __fdelt_warn(FDELT_TYPE a) { if (a >= FD_SETSIZE) __chk_fail(); return a / __NFDBITS; } extern "C" FDELT_TYPE __fdelt_chk(FDELT_TYPE) __attribute__((weak, alias("__fdelt_warn"))); #if defined(__i386__) || defined(__arm__) extern "C" int64_t __udivmoddi4(uint64_t u, uint64_t v, uint64_t* rp); extern "C" int64_t __wrap___divmoddi4(int64_t u, int64_t v, int64_t* rp) { int32_t c1 = 0, c2 = 0; int64_t uu = u, vv = v; int64_t w; int64_t r; if (uu < 0) { c1 = ~c1, c2 = ~c2, uu = -uu; } if (vv < 0) { c1 = ~c1, vv = -vv; } w = __udivmoddi4(uu, vv, (uint64_t*)&r); if (c1) w = -w; if (c2) r = -r; *rp = r; return w; } #endif extern "C" float log2f_old(float x); #ifdef __i386__ __asm(".symver log2f_old,log2f@GLIBC_2.1"); #elif defined(__amd64__) __asm(".symver log2f_old,log2f@GLIBC_2.2.5"); #elif defined(__arm__) __asm(".symver log2f_old,log2f@GLIBC_2.4"); #elif defined(__aarch64__) __asm(".symver log2f_old,log2f@GLIBC_2.17"); #endif extern "C" float __wrap_log2f(float x) { return log2f_old(x); } <commit_msg>Update glibc_compat.cpp with risc<commit_after>// Copyright (c) 2009-2017 The Bitcoin Core developers // Copyright (c) 2017 The PIVX 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/pivx-config.h" #endif #include <cstddef> #include <cstdint> #if defined(HAVE_SYS_SELECT_H) #include <sys/select.h> #endif // Prior to GLIBC_2.14, memcpy was aliased to memmove. extern "C" void* memmove(void* a, const void* b, size_t c); extern "C" void* memcpy(void* a, const void* b, size_t c) { return memmove(a, b, c); } extern "C" void __chk_fail(void) __attribute__((__noreturn__)); extern "C" FDELT_TYPE __fdelt_warn(FDELT_TYPE a) { if (a >= FD_SETSIZE) __chk_fail(); return a / __NFDBITS; } extern "C" FDELT_TYPE __fdelt_chk(FDELT_TYPE) __attribute__((weak, alias("__fdelt_warn"))); #if defined(__i386__) || defined(__arm__) extern "C" int64_t __udivmoddi4(uint64_t u, uint64_t v, uint64_t* rp); extern "C" int64_t __wrap___divmoddi4(int64_t u, int64_t v, int64_t* rp) { int32_t c1 = 0, c2 = 0; int64_t uu = u, vv = v; int64_t w; int64_t r; if (uu < 0) { c1 = ~c1, c2 = ~c2, uu = -uu; } if (vv < 0) { c1 = ~c1, vv = -vv; } w = __udivmoddi4(uu, vv, (uint64_t*)&r); if (c1) w = -w; if (c2) r = -r; *rp = r; return w; } #endif extern "C" float log2f_old(float x); #ifdef __i386__ __asm(".symver log2f_old,log2f@GLIBC_2.1"); #elif defined(__amd64__) __asm(".symver log2f_old,log2f@GLIBC_2.2.5"); #elif defined(__arm__) __asm(".symver log2f_old,log2f@GLIBC_2.4"); #elif defined(__aarch64__) __asm(".symver log2f_old,log2f@GLIBC_2.17"); #elif defined(__riscv) __asm(".symver log2f_old,log2f@GLIBC_2.27"); #endif extern "C" float __wrap_log2f(float x) { return log2f_old(x); } <|endoftext|>
<commit_before>// Copyright 2014 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/compiler/js-inlining.h" #include "src/ast.h" #include "src/ast-numbering.h" #include "src/compiler/all-nodes.h" #include "src/compiler/ast-graph-builder.h" #include "src/compiler/common-operator.h" #include "src/compiler/js-operator.h" #include "src/compiler/node-matchers.h" #include "src/compiler/node-properties.h" #include "src/compiler/operator-properties.h" #include "src/full-codegen.h" #include "src/parser.h" #include "src/rewriter.h" #include "src/scopes.h" namespace v8 { namespace internal { namespace compiler { #define TRACE(...) \ do { \ if (FLAG_trace_turbo_inlining) PrintF(__VA_ARGS__); \ } while (false) // Provides convenience accessors for calls to JS functions. class JSCallFunctionAccessor { public: explicit JSCallFunctionAccessor(Node* call) : call_(call) { DCHECK_EQ(IrOpcode::kJSCallFunction, call->opcode()); } Node* jsfunction() { return call_->InputAt(0); } Node* receiver() { return call_->InputAt(1); } Node* formal_argument(size_t index) { DCHECK(index < formal_arguments()); return call_->InputAt(static_cast<int>(2 + index)); } size_t formal_arguments() { // {value_inputs} includes jsfunction and receiver. size_t value_inputs = call_->op()->ValueInputCount(); DCHECK_GE(call_->InputCount(), 2); return value_inputs - 2; } Node* frame_state() { return NodeProperties::GetFrameStateInput(call_, 0); } private: Node* call_; }; class CopyVisitor { public: CopyVisitor(Graph* source_graph, Graph* target_graph, Zone* temp_zone) : sentinel_op_(IrOpcode::kDead, Operator::kNoProperties, "Sentinel", 0, 0, 0, 0, 0, 0), sentinel_(target_graph->NewNode(&sentinel_op_)), copies_(source_graph->NodeCount(), sentinel_, temp_zone), source_graph_(source_graph), target_graph_(target_graph), temp_zone_(temp_zone) {} Node* GetCopy(Node* orig) { return copies_[orig->id()]; } void CopyGraph() { NodeVector inputs(temp_zone_); // TODO(bmeurer): AllNodes should be turned into something like // Graph::CollectNodesReachableFromEnd() and the gray set stuff should be // removed since it's only needed by the visualizer. AllNodes all(temp_zone_, source_graph_); // Copy all nodes reachable from end. for (Node* orig : all.live) { Node* copy = GetCopy(orig); if (copy != sentinel_) { // Mapping already exists. continue; } // Copy the node. inputs.clear(); for (Node* input : orig->inputs()) inputs.push_back(copies_[input->id()]); copy = target_graph_->NewNode(orig->op(), orig->InputCount(), inputs.empty() ? nullptr : &inputs[0]); copies_[orig->id()] = copy; } // For missing inputs. for (Node* orig : all.live) { Node* copy = copies_[orig->id()]; for (int i = 0; i < copy->InputCount(); ++i) { Node* input = copy->InputAt(i); if (input == sentinel_) { copy->ReplaceInput(i, GetCopy(orig->InputAt(i))); } } } } const NodeVector& copies() const { return copies_; } private: Operator const sentinel_op_; Node* const sentinel_; NodeVector copies_; Graph* const source_graph_; Graph* const target_graph_; Zone* const temp_zone_; }; Reduction JSInliner::InlineCall(Node* call, Node* frame_state, Node* start, Node* end) { // The scheduler is smart enough to place our code; we just ensure {control} // becomes the control input of the start of the inlinee, and {effect} becomes // the effect input of the start of the inlinee. Node* control = NodeProperties::GetControlInput(call); Node* effect = NodeProperties::GetEffectInput(call); // Context is last argument. int const inlinee_context_index = static_cast<int>(start->op()->ValueOutputCount()) - 1; // {inliner_inputs} counts JSFunction, Receiver, arguments, but not // context, effect, control. int inliner_inputs = call->op()->ValueInputCount(); // Iterate over all uses of the start node. for (Edge edge : start->use_edges()) { Node* use = edge.from(); switch (use->opcode()) { case IrOpcode::kParameter: { int index = 1 + ParameterIndexOf(use->op()); if (index < inliner_inputs && index < inlinee_context_index) { // There is an input from the call, and the index is a value // projection but not the context, so rewire the input. ReplaceWithValue(use, call->InputAt(index)); } else if (index == inlinee_context_index) { // TODO(turbofan): We always context specialize inlinees currently, so // we should never get here. UNREACHABLE(); } else if (index < inlinee_context_index) { // Call has fewer arguments than required, fill with undefined. ReplaceWithValue(use, jsgraph_->UndefinedConstant()); } else { // We got too many arguments, discard for now. // TODO(sigurds): Fix to treat arguments array correctly. } break; } default: if (NodeProperties::IsEffectEdge(edge)) { edge.UpdateTo(effect); } else if (NodeProperties::IsControlEdge(edge)) { edge.UpdateTo(control); } else if (NodeProperties::IsFrameStateEdge(edge)) { edge.UpdateTo(frame_state); } else { UNREACHABLE(); } break; } } NodeVector values(local_zone_); NodeVector effects(local_zone_); NodeVector controls(local_zone_); for (Node* const input : end->inputs()) { switch (input->opcode()) { case IrOpcode::kReturn: values.push_back(NodeProperties::GetValueInput(input, 0)); effects.push_back(NodeProperties::GetEffectInput(input)); controls.push_back(NodeProperties::GetControlInput(input)); break; case IrOpcode::kDeoptimize: case IrOpcode::kTerminate: case IrOpcode::kThrow: jsgraph_->graph()->end()->AppendInput(jsgraph_->zone(), input); jsgraph_->graph()->end()->set_op( jsgraph_->common()->End(jsgraph_->graph()->end()->InputCount())); break; default: UNREACHABLE(); break; } } DCHECK_NE(0u, values.size()); DCHECK_EQ(values.size(), effects.size()); DCHECK_EQ(values.size(), controls.size()); int const input_count = static_cast<int>(controls.size()); Node* control_output = jsgraph_->graph()->NewNode( jsgraph_->common()->Merge(input_count), input_count, &controls.front()); values.push_back(control_output); effects.push_back(control_output); Node* value_output = jsgraph_->graph()->NewNode( jsgraph_->common()->Phi(kMachAnyTagged, input_count), static_cast<int>(values.size()), &values.front()); Node* effect_output = jsgraph_->graph()->NewNode( jsgraph_->common()->EffectPhi(input_count), static_cast<int>(effects.size()), &effects.front()); ReplaceWithValue(call, value_output, effect_output, control_output); return Changed(value_output); } Node* JSInliner::CreateArgumentsAdaptorFrameState( JSCallFunctionAccessor* call, Handle<SharedFunctionInfo> shared_info, Zone* temp_zone) { const FrameStateFunctionInfo* state_info = jsgraph_->common()->CreateFrameStateFunctionInfo( FrameStateType::kArgumentsAdaptor, static_cast<int>(call->formal_arguments()) + 1, 0, shared_info); const Operator* op = jsgraph_->common()->FrameState( BailoutId(-1), OutputFrameStateCombine::Ignore(), state_info); const Operator* op0 = jsgraph_->common()->StateValues(0); Node* node0 = jsgraph_->graph()->NewNode(op0); NodeVector params(temp_zone); params.push_back(call->receiver()); for (size_t argument = 0; argument != call->formal_arguments(); ++argument) { params.push_back(call->formal_argument(argument)); } const Operator* op_param = jsgraph_->common()->StateValues(static_cast<int>(params.size())); Node* params_node = jsgraph_->graph()->NewNode( op_param, static_cast<int>(params.size()), &params.front()); return jsgraph_->graph()->NewNode(op, params_node, node0, node0, jsgraph_->UndefinedConstant(), call->jsfunction(), call->frame_state()); } Reduction JSInliner::Reduce(Node* node) { if (node->opcode() != IrOpcode::kJSCallFunction) return NoChange(); JSCallFunctionAccessor call(node); HeapObjectMatcher match(call.jsfunction()); if (!match.HasValue()) return NoChange(); if (!match.Value().handle()->IsJSFunction()) return NoChange(); Handle<JSFunction> function = Handle<JSFunction>::cast(match.Value().handle()); if (mode_ == kRestrictedInlining && !function->shared()->force_inline()) { return NoChange(); } // TODO(turbofan): TranslatedState::GetAdaptedArguments() currently relies on // not inlining recursive functions. We might want to relax that at some // point. for (Node* frame_state = call.frame_state(); frame_state->opcode() == IrOpcode::kFrameState; frame_state = frame_state->InputAt(kFrameStateOuterStateInput)) { FrameStateInfo const& info = OpParameter<FrameStateInfo>(frame_state); Handle<SharedFunctionInfo> shared_info; if (info.shared_info().ToHandle(&shared_info) && *shared_info == function->shared()) { TRACE("Not inlining %s into %s because call is recursive\n", function->shared()->DebugName()->ToCString().get(), info_->shared_info()->DebugName()->ToCString().get()); return NoChange(); } } Zone zone; ParseInfo parse_info(&zone, function); CompilationInfo info(&parse_info); if (info_->is_deoptimization_enabled()) info.MarkAsDeoptimizationEnabled(); if (!Compiler::ParseAndAnalyze(info.parse_info())) return NoChange(); if (!Compiler::EnsureDeoptimizationSupport(&info)) return NoChange(); if (info.scope()->arguments() != NULL && is_sloppy(info.language_mode())) { // For now do not inline functions that use their arguments array. TRACE("Not Inlining %s into %s because inlinee uses arguments array\n", function->shared()->DebugName()->ToCString().get(), info_->shared_info()->DebugName()->ToCString().get()); return NoChange(); } TRACE("Inlining %s into %s\n", function->shared()->DebugName()->ToCString().get(), info_->shared_info()->DebugName()->ToCString().get()); Graph graph(info.zone()); JSGraph jsgraph(info.isolate(), &graph, jsgraph_->common(), jsgraph_->javascript(), jsgraph_->machine()); // The inlinee specializes to the context from the JSFunction object. // TODO(turbofan): We might want to load the context from the JSFunction at // runtime in case we only know the SharedFunctionInfo once we have dynamic // type feedback in the compiler. AstGraphBuilder graph_builder(local_zone_, &info, &jsgraph); graph_builder.CreateGraph(true, false); CopyVisitor visitor(&graph, jsgraph_->graph(), info.zone()); visitor.CopyGraph(); Node* start = visitor.GetCopy(graph.start()); Node* end = visitor.GetCopy(graph.end()); Node* frame_state = call.frame_state(); size_t const inlinee_formal_parameters = start->op()->ValueOutputCount() - 3; // Insert argument adaptor frame if required. if (call.formal_arguments() != inlinee_formal_parameters) { // In strong mode, in case of too few arguments we need to throw a // TypeError so we must not inline this call. if (is_strong(info.language_mode()) && call.formal_arguments() < inlinee_formal_parameters) { return NoChange(); } frame_state = CreateArgumentsAdaptorFrameState(&call, info.shared_info(), info.zone()); } // Remember that we inlined this function. info_->AddInlinedFunction(info.shared_info()); return InlineCall(node, frame_state, start, end); } } // namespace compiler } // namespace internal } // namespace v8 <commit_msg>[turbofan] Disallow cross native context inlining.<commit_after>// Copyright 2014 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/compiler/js-inlining.h" #include "src/ast.h" #include "src/ast-numbering.h" #include "src/compiler/all-nodes.h" #include "src/compiler/ast-graph-builder.h" #include "src/compiler/common-operator.h" #include "src/compiler/js-operator.h" #include "src/compiler/node-matchers.h" #include "src/compiler/node-properties.h" #include "src/compiler/operator-properties.h" #include "src/full-codegen.h" #include "src/parser.h" #include "src/rewriter.h" #include "src/scopes.h" namespace v8 { namespace internal { namespace compiler { #define TRACE(...) \ do { \ if (FLAG_trace_turbo_inlining) PrintF(__VA_ARGS__); \ } while (false) // Provides convenience accessors for calls to JS functions. class JSCallFunctionAccessor { public: explicit JSCallFunctionAccessor(Node* call) : call_(call) { DCHECK_EQ(IrOpcode::kJSCallFunction, call->opcode()); } Node* jsfunction() { return call_->InputAt(0); } Node* receiver() { return call_->InputAt(1); } Node* formal_argument(size_t index) { DCHECK(index < formal_arguments()); return call_->InputAt(static_cast<int>(2 + index)); } size_t formal_arguments() { // {value_inputs} includes jsfunction and receiver. size_t value_inputs = call_->op()->ValueInputCount(); DCHECK_GE(call_->InputCount(), 2); return value_inputs - 2; } Node* frame_state() { return NodeProperties::GetFrameStateInput(call_, 0); } private: Node* call_; }; class CopyVisitor { public: CopyVisitor(Graph* source_graph, Graph* target_graph, Zone* temp_zone) : sentinel_op_(IrOpcode::kDead, Operator::kNoProperties, "Sentinel", 0, 0, 0, 0, 0, 0), sentinel_(target_graph->NewNode(&sentinel_op_)), copies_(source_graph->NodeCount(), sentinel_, temp_zone), source_graph_(source_graph), target_graph_(target_graph), temp_zone_(temp_zone) {} Node* GetCopy(Node* orig) { return copies_[orig->id()]; } void CopyGraph() { NodeVector inputs(temp_zone_); // TODO(bmeurer): AllNodes should be turned into something like // Graph::CollectNodesReachableFromEnd() and the gray set stuff should be // removed since it's only needed by the visualizer. AllNodes all(temp_zone_, source_graph_); // Copy all nodes reachable from end. for (Node* orig : all.live) { Node* copy = GetCopy(orig); if (copy != sentinel_) { // Mapping already exists. continue; } // Copy the node. inputs.clear(); for (Node* input : orig->inputs()) inputs.push_back(copies_[input->id()]); copy = target_graph_->NewNode(orig->op(), orig->InputCount(), inputs.empty() ? nullptr : &inputs[0]); copies_[orig->id()] = copy; } // For missing inputs. for (Node* orig : all.live) { Node* copy = copies_[orig->id()]; for (int i = 0; i < copy->InputCount(); ++i) { Node* input = copy->InputAt(i); if (input == sentinel_) { copy->ReplaceInput(i, GetCopy(orig->InputAt(i))); } } } } const NodeVector& copies() const { return copies_; } private: Operator const sentinel_op_; Node* const sentinel_; NodeVector copies_; Graph* const source_graph_; Graph* const target_graph_; Zone* const temp_zone_; }; Reduction JSInliner::InlineCall(Node* call, Node* frame_state, Node* start, Node* end) { // The scheduler is smart enough to place our code; we just ensure {control} // becomes the control input of the start of the inlinee, and {effect} becomes // the effect input of the start of the inlinee. Node* control = NodeProperties::GetControlInput(call); Node* effect = NodeProperties::GetEffectInput(call); // Context is last argument. int const inlinee_context_index = static_cast<int>(start->op()->ValueOutputCount()) - 1; // {inliner_inputs} counts JSFunction, Receiver, arguments, but not // context, effect, control. int inliner_inputs = call->op()->ValueInputCount(); // Iterate over all uses of the start node. for (Edge edge : start->use_edges()) { Node* use = edge.from(); switch (use->opcode()) { case IrOpcode::kParameter: { int index = 1 + ParameterIndexOf(use->op()); if (index < inliner_inputs && index < inlinee_context_index) { // There is an input from the call, and the index is a value // projection but not the context, so rewire the input. ReplaceWithValue(use, call->InputAt(index)); } else if (index == inlinee_context_index) { // TODO(turbofan): We always context specialize inlinees currently, so // we should never get here. UNREACHABLE(); } else if (index < inlinee_context_index) { // Call has fewer arguments than required, fill with undefined. ReplaceWithValue(use, jsgraph_->UndefinedConstant()); } else { // We got too many arguments, discard for now. // TODO(sigurds): Fix to treat arguments array correctly. } break; } default: if (NodeProperties::IsEffectEdge(edge)) { edge.UpdateTo(effect); } else if (NodeProperties::IsControlEdge(edge)) { edge.UpdateTo(control); } else if (NodeProperties::IsFrameStateEdge(edge)) { edge.UpdateTo(frame_state); } else { UNREACHABLE(); } break; } } NodeVector values(local_zone_); NodeVector effects(local_zone_); NodeVector controls(local_zone_); for (Node* const input : end->inputs()) { switch (input->opcode()) { case IrOpcode::kReturn: values.push_back(NodeProperties::GetValueInput(input, 0)); effects.push_back(NodeProperties::GetEffectInput(input)); controls.push_back(NodeProperties::GetControlInput(input)); break; case IrOpcode::kDeoptimize: case IrOpcode::kTerminate: case IrOpcode::kThrow: jsgraph_->graph()->end()->AppendInput(jsgraph_->zone(), input); jsgraph_->graph()->end()->set_op( jsgraph_->common()->End(jsgraph_->graph()->end()->InputCount())); break; default: UNREACHABLE(); break; } } DCHECK_NE(0u, values.size()); DCHECK_EQ(values.size(), effects.size()); DCHECK_EQ(values.size(), controls.size()); int const input_count = static_cast<int>(controls.size()); Node* control_output = jsgraph_->graph()->NewNode( jsgraph_->common()->Merge(input_count), input_count, &controls.front()); values.push_back(control_output); effects.push_back(control_output); Node* value_output = jsgraph_->graph()->NewNode( jsgraph_->common()->Phi(kMachAnyTagged, input_count), static_cast<int>(values.size()), &values.front()); Node* effect_output = jsgraph_->graph()->NewNode( jsgraph_->common()->EffectPhi(input_count), static_cast<int>(effects.size()), &effects.front()); ReplaceWithValue(call, value_output, effect_output, control_output); return Changed(value_output); } Node* JSInliner::CreateArgumentsAdaptorFrameState( JSCallFunctionAccessor* call, Handle<SharedFunctionInfo> shared_info, Zone* temp_zone) { const FrameStateFunctionInfo* state_info = jsgraph_->common()->CreateFrameStateFunctionInfo( FrameStateType::kArgumentsAdaptor, static_cast<int>(call->formal_arguments()) + 1, 0, shared_info); const Operator* op = jsgraph_->common()->FrameState( BailoutId(-1), OutputFrameStateCombine::Ignore(), state_info); const Operator* op0 = jsgraph_->common()->StateValues(0); Node* node0 = jsgraph_->graph()->NewNode(op0); NodeVector params(temp_zone); params.push_back(call->receiver()); for (size_t argument = 0; argument != call->formal_arguments(); ++argument) { params.push_back(call->formal_argument(argument)); } const Operator* op_param = jsgraph_->common()->StateValues(static_cast<int>(params.size())); Node* params_node = jsgraph_->graph()->NewNode( op_param, static_cast<int>(params.size()), &params.front()); return jsgraph_->graph()->NewNode(op, params_node, node0, node0, jsgraph_->UndefinedConstant(), call->jsfunction(), call->frame_state()); } Reduction JSInliner::Reduce(Node* node) { if (node->opcode() != IrOpcode::kJSCallFunction) return NoChange(); JSCallFunctionAccessor call(node); HeapObjectMatcher match(call.jsfunction()); if (!match.HasValue()) return NoChange(); if (!match.Value().handle()->IsJSFunction()) return NoChange(); Handle<JSFunction> function = Handle<JSFunction>::cast(match.Value().handle()); if (mode_ == kRestrictedInlining && !function->shared()->force_inline()) { return NoChange(); } // Disallow cross native-context inlining for now. This means that all parts // of the resulting code will operate on the same global object. // This also prevents cross context leaks for asm.js code, where we could // inline functions from a different context and hold on to that context (and // closure) from the code object. // TODO(turbofan): We might want to revisit this restriction later when we // have a need for this, and we know how to model different native contexts // in the same graph in a compositional way. if (function->context()->native_context() != info_->context()->native_context()) { TRACE("Not inlining %s into %s because of different native contexts\n", function->shared()->DebugName()->ToCString().get(), info_->shared_info()->DebugName()->ToCString().get()); return NoChange(); } // TODO(turbofan): TranslatedState::GetAdaptedArguments() currently relies on // not inlining recursive functions. We might want to relax that at some // point. for (Node* frame_state = call.frame_state(); frame_state->opcode() == IrOpcode::kFrameState; frame_state = frame_state->InputAt(kFrameStateOuterStateInput)) { FrameStateInfo const& info = OpParameter<FrameStateInfo>(frame_state); Handle<SharedFunctionInfo> shared_info; if (info.shared_info().ToHandle(&shared_info) && *shared_info == function->shared()) { TRACE("Not inlining %s into %s because call is recursive\n", function->shared()->DebugName()->ToCString().get(), info_->shared_info()->DebugName()->ToCString().get()); return NoChange(); } } Zone zone; ParseInfo parse_info(&zone, function); CompilationInfo info(&parse_info); if (info_->is_deoptimization_enabled()) info.MarkAsDeoptimizationEnabled(); if (!Compiler::ParseAndAnalyze(info.parse_info())) return NoChange(); if (!Compiler::EnsureDeoptimizationSupport(&info)) return NoChange(); if (info.scope()->arguments() != NULL && is_sloppy(info.language_mode())) { // For now do not inline functions that use their arguments array. TRACE("Not inlining %s into %s because inlinee uses arguments array\n", function->shared()->DebugName()->ToCString().get(), info_->shared_info()->DebugName()->ToCString().get()); return NoChange(); } TRACE("Inlining %s into %s\n", function->shared()->DebugName()->ToCString().get(), info_->shared_info()->DebugName()->ToCString().get()); Graph graph(info.zone()); JSGraph jsgraph(info.isolate(), &graph, jsgraph_->common(), jsgraph_->javascript(), jsgraph_->machine()); // The inlinee specializes to the context from the JSFunction object. // TODO(turbofan): We might want to load the context from the JSFunction at // runtime in case we only know the SharedFunctionInfo once we have dynamic // type feedback in the compiler. AstGraphBuilder graph_builder(local_zone_, &info, &jsgraph); graph_builder.CreateGraph(true, false); CopyVisitor visitor(&graph, jsgraph_->graph(), info.zone()); visitor.CopyGraph(); Node* start = visitor.GetCopy(graph.start()); Node* end = visitor.GetCopy(graph.end()); Node* frame_state = call.frame_state(); size_t const inlinee_formal_parameters = start->op()->ValueOutputCount() - 3; // Insert argument adaptor frame if required. if (call.formal_arguments() != inlinee_formal_parameters) { // In strong mode, in case of too few arguments we need to throw a // TypeError so we must not inline this call. if (is_strong(info.language_mode()) && call.formal_arguments() < inlinee_formal_parameters) { return NoChange(); } frame_state = CreateArgumentsAdaptorFrameState(&call, info.shared_info(), info.zone()); } // Remember that we inlined this function. info_->AddInlinedFunction(info.shared_info()); return InlineCall(node, frame_state, start, end); } } // namespace compiler } // namespace internal } // namespace v8 <|endoftext|>
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. 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 <gtest/gtest.h> #include "FunctionTest.h" namespace paddle { TEST(BlockExpandForward, real) { for (size_t batchSize : {5, 32}) { for (size_t channels : {1, 5, 32}) { for (size_t inputHeight : {5, 33, 100}) { for (size_t inputWidth : {5, 32, 96}) { for (size_t block : {1, 3, 5}) { for (size_t stride : {1, 2}) { for (size_t padding : {0, 1}) { // init Test object std::vector<size_t> strides = {stride, stride}; std::vector<size_t> paddings = {padding, padding}; std::vector<size_t> blocks = {block, block}; CpuGpuFuncCompare test("BlockExpand", FuncConfig() .set("strides", strides) .set("paddings", paddings) .set("blocks", blocks)); size_t outputHeight = 1 + (inputHeight + 2 * padding - block + stride - 1) / stride; size_t outputWidth = 1 + (inputWidth + 2 * padding - block + stride - 1) / stride; TensorShape inputShape = TensorShape({batchSize, channels, inputHeight, inputWidth}); TensorShape outputShape = TensorShape({batchSize, outputHeight * outputWidth, channels * block * block}); test.addInputs(BufferArg(VALUE_TYPE_FLOAT, inputShape)); test.addOutputs(BufferArg(VALUE_TYPE_FLOAT, outputShape)); // run Function test.run(); } } } } } } } } TEST(BlockExpandBackward, real) { for (size_t batchSize : {5, 32}) { for (size_t channels : {1, 5, 32}) { for (size_t inputHeight : {5, 33, 100}) { for (size_t inputWidth : {5, 32, 96}) { for (size_t block : {1, 3, 5}) { for (size_t stride : {1, 2}) { for (size_t padding : {0, 1}) { // init Test object std::vector<size_t> strides = {stride, stride}; std::vector<size_t> paddings = {padding, padding}; std::vector<size_t> blocks = {block, block}; CpuGpuFuncCompare test("BlockExpandGrad", FuncConfig() .set("strides", strides) .set("paddings", paddings) .set("blocks", blocks)); size_t outputHeight = 1 + (inputHeight + 2 * padding - block + stride - 1) / stride; size_t outputWidth = 1 + (inputWidth + 2 * padding - block + stride - 1) / stride; TensorShape inputShape = TensorShape({batchSize, channels, inputHeight, inputWidth}); TensorShape outputShape = TensorShape({batchSize, outputHeight * outputWidth, channels * block * block}); test.addInputs(BufferArg(VALUE_TYPE_FLOAT, outputShape)); test.addOutputs(BufferArg(VALUE_TYPE_FLOAT, inputShape), ADD_TO); // run Function test.run(); } } } } } } } } } // namespace paddle <commit_msg>Simplify BlockExpandOpTest.<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. 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 <gtest/gtest.h> #include "FunctionTest.h" namespace paddle { TEST(BlockExpandForward, real) { for (size_t batchSize : {5}) { for (size_t channels : {1, 5}) { for (size_t inputHeight : {5, 33}) { for (size_t inputWidth : {5, 32}) { for (size_t block : {1, 3, 5}) { for (size_t stride : {1, 2}) { for (size_t padding : {0, 1}) { // init Test object std::vector<size_t> strides = {stride, stride}; std::vector<size_t> paddings = {padding, padding}; std::vector<size_t> blocks = {block, block}; CpuGpuFuncCompare test("BlockExpand", FuncConfig() .set("strides", strides) .set("paddings", paddings) .set("blocks", blocks)); size_t outputHeight = 1 + (inputHeight + 2 * padding - block + stride - 1) / stride; size_t outputWidth = 1 + (inputWidth + 2 * padding - block + stride - 1) / stride; TensorShape inputShape = TensorShape({batchSize, channels, inputHeight, inputWidth}); TensorShape outputShape = TensorShape({batchSize, outputHeight * outputWidth, channels * block * block}); test.addInputs(BufferArg(VALUE_TYPE_FLOAT, inputShape)); test.addOutputs(BufferArg(VALUE_TYPE_FLOAT, outputShape)); // run Function test.run(); } } } } } } } } TEST(BlockExpandBackward, real) { for (size_t batchSize : {5}) { for (size_t channels : {1, 5}) { for (size_t inputHeight : {5, 33}) { for (size_t inputWidth : {5, 32}) { for (size_t block : {1, 3, 5}) { for (size_t stride : {1, 2}) { for (size_t padding : {0, 1}) { // init Test object std::vector<size_t> strides = {stride, stride}; std::vector<size_t> paddings = {padding, padding}; std::vector<size_t> blocks = {block, block}; CpuGpuFuncCompare test("BlockExpandGrad", FuncConfig() .set("strides", strides) .set("paddings", paddings) .set("blocks", blocks)); size_t outputHeight = 1 + (inputHeight + 2 * padding - block + stride - 1) / stride; size_t outputWidth = 1 + (inputWidth + 2 * padding - block + stride - 1) / stride; TensorShape inputShape = TensorShape({batchSize, channels, inputHeight, inputWidth}); TensorShape outputShape = TensorShape({batchSize, outputHeight * outputWidth, channels * block * block}); test.addInputs(BufferArg(VALUE_TYPE_FLOAT, outputShape)); test.addOutputs(BufferArg(VALUE_TYPE_FLOAT, inputShape), ADD_TO); // run Function test.run(); } } } } } } } } } // namespace paddle <|endoftext|>
<commit_before>/** * PANDA 3D SOFTWARE * Copyright (c) Carnegie Mellon University. All rights reserved. * * All use of this software is subject to the terms of the revised BSD * license. You should have received a copy of this license along * with this source code in a file named "LICENSE." * * @file datagramInputFile.cxx * @author drose * @date 2000-10-30 */ #include "datagramInputFile.h" #include "temporaryFile.h" #include "numeric_types.h" #include "datagramIterator.h" #include "profileTimer.h" #include "config_util.h" #include "config_express.h" #include "virtualFileSystem.h" #include "streamReader.h" #include "thread.h" /** * Opens the indicated filename for reading. Returns true on success, false * on failure. */ bool DatagramInputFile:: open(const FileReference *file) { close(); _file = file; _filename = _file->get_filename(); // DatagramInputFiles are always binary. _filename.set_binary(); VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); _vfile = vfs->get_file(_filename); if (_vfile == (VirtualFile *)NULL) { // No such file. return false; } _timestamp = _vfile->get_timestamp(); _in = _vfile->open_read_file(true); _owns_in = (_in != (istream *)NULL); return _owns_in && !_in->fail(); } /** * Starts reading from the indicated stream. Returns true on success, false * on failure. The DatagramInputFile does not take ownership of the stream; * you are responsible for closing or deleting it when you are done. */ bool DatagramInputFile:: open(istream &in, const Filename &filename) { close(); _in = &in; _owns_in = false; _filename = filename; _timestamp = 0; if (!filename.empty()) { _file = new FileReference(filename); } return !_in->fail(); } /** * Closes the file. This is also implicitly done when the DatagramInputFile * destructs. */ void DatagramInputFile:: close() { _vfile.clear(); if (_owns_in) { VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); vfs->close_read_file(_in); } _in = (istream *)NULL; _owns_in = false; _file.clear(); _filename = Filename(); _timestamp = 0; _read_first_datagram = false; _error = false; } /** * Reads a sequence of bytes from the beginning of the datagram file. This * may be called any number of times after the file has been opened and before * the first datagram is read. It may not be called once the first datagram * has been read. */ bool DatagramInputFile:: read_header(string &header, size_t num_bytes) { nassertr(!_read_first_datagram, false); nassertr(_in != (istream *)NULL, false); char *buffer = (char *)alloca(num_bytes); nassertr(buffer != (char *)NULL, false); _in->read(buffer, num_bytes); if (_in->fail() || _in->eof()) { return false; } header = string(buffer, num_bytes); Thread::consider_yield(); return true; } /** * Reads the next datagram from the file. Returns true on success, false if * there is an error or end of file. */ bool DatagramInputFile:: get_datagram(Datagram &data) { nassertr(_in != (istream *)NULL, false); _read_first_datagram = true; // First, get the size of the upcoming datagram. StreamReader reader(_in, false); uint32_t num_bytes_32 = reader.get_uint32(); if (_in->fail() || _in->eof()) { return false; } if (num_bytes_32 == 0) { // A special case for a zero-length datagram: no need to try to read any // data. data.clear(); return true; } streamsize num_bytes = (streamsize)num_bytes_32; if (num_bytes_32 == (uint32_t)-1) { // Another special case for a value larger than 32 bits. num_bytes = reader.get_uint64(); } // Make sure we have a reasonable datagram size for putting into memory. nassertr(num_bytes == (size_t)num_bytes, false); // Now, read the datagram itself. // If the number of bytes is large, we will need to allocate a temporary // buffer from the heap. Otherwise, we can get away with allocating it on // the stack, via alloca(). if (num_bytes > 65536) { char *buffer = (char *)PANDA_MALLOC_ARRAY(num_bytes); nassertr(buffer != (char *)NULL, false); _in->read(buffer, num_bytes); if (_in->fail() || _in->eof()) { _error = true; PANDA_FREE_ARRAY(buffer); return false; } data = Datagram(buffer, num_bytes); PANDA_FREE_ARRAY(buffer); } else { char *buffer = (char *)alloca(num_bytes); nassertr(buffer != (char *)NULL, false); _in->read(buffer, num_bytes); if (_in->fail() || _in->eof()) { _error = true; return false; } data = Datagram(buffer, num_bytes); } Thread::consider_yield(); return true; } /** * Skips over the next datagram without extracting it, but saves the relevant * file information in the SubfileInfo object so that its data may be read * later. For non-file-based datagram generators, this may mean creating a * temporary file and copying the contents of the datagram to disk. * * Returns true on success, false on failure or if this method is * unimplemented. */ bool DatagramInputFile:: save_datagram(SubfileInfo &info) { nassertr(_in != (istream *)NULL, false); _read_first_datagram = true; // First, get the size of the upcoming datagram. StreamReader reader(_in, false); size_t num_bytes_32 = reader.get_uint32(); if (_in->fail() || _in->eof()) { return false; } streamsize num_bytes = (streamsize)num_bytes_32; if (num_bytes_32 == (uint32_t)-1) { // Another special case for a value larger than 32 bits. num_bytes = reader.get_uint64(); } // If this stream is file-based, we can just point the SubfileInfo directly // into this file. if (_file != (FileReference *)NULL) { info = SubfileInfo(_file, _in->tellg(), num_bytes); _in->seekg(num_bytes, ios::cur); return true; } // Otherwise, we have to dump the data into a temporary file. PT(TemporaryFile) tfile = new TemporaryFile(Filename::temporary("", "")); pofstream out; Filename filename = tfile->get_filename(); filename.set_binary(); if (!filename.open_write(out)) { util_cat.error() << "Couldn't write to " << tfile->get_filename() << "\n"; return false; } if (util_cat.is_debug()) { util_cat.debug() << "Copying " << num_bytes << " bytes to " << tfile->get_filename() << "\n"; } streamsize num_remaining = num_bytes; static const size_t buffer_size = 4096; char buffer[buffer_size]; _in->read(buffer, min((streamsize)buffer_size, num_remaining)); streamsize count = _in->gcount(); while (count != 0) { out.write(buffer, count); if (out.fail()) { util_cat.error() << "Couldn't write " << num_bytes << " bytes to " << tfile->get_filename() << "\n"; return false; } num_remaining -= count; if (num_remaining == 0) { break; } _in->read(buffer, min((streamsize)buffer_size, num_remaining)); count = _in->gcount(); } if (num_remaining != 0) { util_cat.error() << "Truncated data stream.\n"; return false; } info = SubfileInfo(tfile, 0, num_bytes); return true; } /** * Returns true if the file has reached the end-of-file. This test may only * be made after a call to read_header() or get_datagram() has failed. */ bool DatagramInputFile:: is_eof() { return _in != (istream *)NULL ? _in->eof() : true; } /** * Returns true if the file has reached an error condition. */ bool DatagramInputFile:: is_error() { if (_in == (istream *)NULL) { return true; } if (_in->fail()) { _error = true; } return _error; } /** * Returns the filename that provides the source for these datagrams, if any, * or empty string if the datagrams do not originate from a file on disk. */ const Filename &DatagramInputFile:: get_filename() { return _filename; } /** * Returns the on-disk timestamp of the file that was read, at the time it was * opened, if that is available, or 0 if it is not. */ time_t DatagramInputFile:: get_timestamp() const { return _timestamp; } /** * Returns the FileReference that provides the source for these datagrams, if * any, or NULL if the datagrams do not originate from a file on disk. */ const FileReference *DatagramInputFile:: get_file() { return _file; } /** * Returns the VirtualFile that provides the source for these datagrams, if * any, or NULL if the datagrams do not originate from a VirtualFile. */ VirtualFile *DatagramInputFile:: get_vfile() { return _vfile; } /** * Returns the current file position within the data stream, if any, or 0 if * the file position is not meaningful or cannot be determined. * * For DatagramInputFiles that return a meaningful file position, this will be * pointing to the first byte following the datagram returned after a call to * get_datagram(). */ streampos DatagramInputFile:: get_file_pos() { if (_in == (istream *)NULL) { return 0; } return _in->tellg(); } <commit_msg>putil: Optimize DatagramInputFile::get_datagram<commit_after>/** * PANDA 3D SOFTWARE * Copyright (c) Carnegie Mellon University. All rights reserved. * * All use of this software is subject to the terms of the revised BSD * license. You should have received a copy of this license along * with this source code in a file named "LICENSE." * * @file datagramInputFile.cxx * @author drose * @date 2000-10-30 */ #include "datagramInputFile.h" #include "temporaryFile.h" #include "numeric_types.h" #include "datagramIterator.h" #include "profileTimer.h" #include "config_util.h" #include "config_express.h" #include "virtualFileSystem.h" #include "streamReader.h" #include "thread.h" /** * Opens the indicated filename for reading. Returns true on success, false * on failure. */ bool DatagramInputFile:: open(const FileReference *file) { close(); _file = file; _filename = _file->get_filename(); // DatagramInputFiles are always binary. _filename.set_binary(); VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); _vfile = vfs->get_file(_filename); if (_vfile == (VirtualFile *)NULL) { // No such file. return false; } _timestamp = _vfile->get_timestamp(); _in = _vfile->open_read_file(true); _owns_in = (_in != (istream *)NULL); return _owns_in && !_in->fail(); } /** * Starts reading from the indicated stream. Returns true on success, false * on failure. The DatagramInputFile does not take ownership of the stream; * you are responsible for closing or deleting it when you are done. */ bool DatagramInputFile:: open(istream &in, const Filename &filename) { close(); _in = &in; _owns_in = false; _filename = filename; _timestamp = 0; if (!filename.empty()) { _file = new FileReference(filename); } return !_in->fail(); } /** * Closes the file. This is also implicitly done when the DatagramInputFile * destructs. */ void DatagramInputFile:: close() { _vfile.clear(); if (_owns_in) { VirtualFileSystem *vfs = VirtualFileSystem::get_global_ptr(); vfs->close_read_file(_in); } _in = (istream *)NULL; _owns_in = false; _file.clear(); _filename = Filename(); _timestamp = 0; _read_first_datagram = false; _error = false; } /** * Reads a sequence of bytes from the beginning of the datagram file. This * may be called any number of times after the file has been opened and before * the first datagram is read. It may not be called once the first datagram * has been read. */ bool DatagramInputFile:: read_header(string &header, size_t num_bytes) { nassertr(!_read_first_datagram, false); nassertr(_in != (istream *)NULL, false); char *buffer = (char *)alloca(num_bytes); nassertr(buffer != (char *)NULL, false); _in->read(buffer, num_bytes); if (_in->fail() || _in->eof()) { return false; } header = string(buffer, num_bytes); Thread::consider_yield(); return true; } /** * Reads the next datagram from the file. Returns true on success, false if * there is an error or end of file. */ bool DatagramInputFile:: get_datagram(Datagram &data) { nassertr(_in != (istream *)NULL, false); _read_first_datagram = true; // First, get the size of the upcoming datagram. StreamReader reader(_in, false); uint32_t num_bytes_32 = reader.get_uint32(); if (_in->fail() || _in->eof()) { return false; } if (num_bytes_32 == 0) { // A special case for a zero-length datagram: no need to try to read any // data. data.clear(); return true; } streamsize num_bytes = (streamsize)num_bytes_32; if (num_bytes_32 == (uint32_t)-1) { // Another special case for a value larger than 32 bits. num_bytes = reader.get_uint64(); } // Make sure we have a reasonable datagram size for putting into memory. nassertr(num_bytes == (size_t)num_bytes, false); // Now, read the datagram itself. We construct an empty datagram, use // pad_bytes to make it big enough, and read *directly* into the datagram's // internal buffer. Doing this saves us a copy operation. data = Datagram(); streamsize bytes_read = 0; while (bytes_read < num_bytes) { streamsize bytes_left = num_bytes - bytes_read; // Hold up a second - datagrams >4MB are pretty large by bam/network // standards. Let's take it 4MB at a time just in case the length is // corrupt, so we don't allocate potentially a few GBs of RAM only to // find a truncated file. bytes_left = min(bytes_left, (streamsize)4*1024*1024); PTA_uchar buffer = data.modify_array(); buffer.resize(buffer.size() + bytes_left); unsigned char *ptr = &buffer.p()[bytes_read]; _in->read((char *)ptr, bytes_left); if (_in->fail() || _in->eof()) { _error = true; return false; } bytes_read += bytes_left; } Thread::consider_yield(); return true; } /** * Skips over the next datagram without extracting it, but saves the relevant * file information in the SubfileInfo object so that its data may be read * later. For non-file-based datagram generators, this may mean creating a * temporary file and copying the contents of the datagram to disk. * * Returns true on success, false on failure or if this method is * unimplemented. */ bool DatagramInputFile:: save_datagram(SubfileInfo &info) { nassertr(_in != (istream *)NULL, false); _read_first_datagram = true; // First, get the size of the upcoming datagram. StreamReader reader(_in, false); size_t num_bytes_32 = reader.get_uint32(); if (_in->fail() || _in->eof()) { return false; } streamsize num_bytes = (streamsize)num_bytes_32; if (num_bytes_32 == (uint32_t)-1) { // Another special case for a value larger than 32 bits. num_bytes = reader.get_uint64(); } // If this stream is file-based, we can just point the SubfileInfo directly // into this file. if (_file != (FileReference *)NULL) { info = SubfileInfo(_file, _in->tellg(), num_bytes); _in->seekg(num_bytes, ios::cur); return true; } // Otherwise, we have to dump the data into a temporary file. PT(TemporaryFile) tfile = new TemporaryFile(Filename::temporary("", "")); pofstream out; Filename filename = tfile->get_filename(); filename.set_binary(); if (!filename.open_write(out)) { util_cat.error() << "Couldn't write to " << tfile->get_filename() << "\n"; return false; } if (util_cat.is_debug()) { util_cat.debug() << "Copying " << num_bytes << " bytes to " << tfile->get_filename() << "\n"; } streamsize num_remaining = num_bytes; static const size_t buffer_size = 4096; char buffer[buffer_size]; _in->read(buffer, min((streamsize)buffer_size, num_remaining)); streamsize count = _in->gcount(); while (count != 0) { out.write(buffer, count); if (out.fail()) { util_cat.error() << "Couldn't write " << num_bytes << " bytes to " << tfile->get_filename() << "\n"; return false; } num_remaining -= count; if (num_remaining == 0) { break; } _in->read(buffer, min((streamsize)buffer_size, num_remaining)); count = _in->gcount(); } if (num_remaining != 0) { util_cat.error() << "Truncated data stream.\n"; return false; } info = SubfileInfo(tfile, 0, num_bytes); return true; } /** * Returns true if the file has reached the end-of-file. This test may only * be made after a call to read_header() or get_datagram() has failed. */ bool DatagramInputFile:: is_eof() { return _in != (istream *)NULL ? _in->eof() : true; } /** * Returns true if the file has reached an error condition. */ bool DatagramInputFile:: is_error() { if (_in == (istream *)NULL) { return true; } if (_in->fail()) { _error = true; } return _error; } /** * Returns the filename that provides the source for these datagrams, if any, * or empty string if the datagrams do not originate from a file on disk. */ const Filename &DatagramInputFile:: get_filename() { return _filename; } /** * Returns the on-disk timestamp of the file that was read, at the time it was * opened, if that is available, or 0 if it is not. */ time_t DatagramInputFile:: get_timestamp() const { return _timestamp; } /** * Returns the FileReference that provides the source for these datagrams, if * any, or NULL if the datagrams do not originate from a file on disk. */ const FileReference *DatagramInputFile:: get_file() { return _file; } /** * Returns the VirtualFile that provides the source for these datagrams, if * any, or NULL if the datagrams do not originate from a VirtualFile. */ VirtualFile *DatagramInputFile:: get_vfile() { return _vfile; } /** * Returns the current file position within the data stream, if any, or 0 if * the file position is not meaningful or cannot be determined. * * For DatagramInputFiles that return a meaningful file position, this will be * pointing to the first byte following the datagram returned after a call to * get_datagram(). */ streampos DatagramInputFile:: get_file_pos() { if (_in == (istream *)NULL) { return 0; } return _in->tellg(); } <|endoftext|>
<commit_before>#include "stdafx.h" #include "texture_atlas.h" #include "texture.h" #include "utilities/utilities.h" #include "utilities/cjson_utils.hpp" using namespace std; using namespace glm; namespace asdf { using namespace util; namespace data { texture_atlas_t::texture_atlas_t(std::string const& json_filepath) { import_from_json(json_filepath); } // Designed to import from TexturePacker, because that's a good a standard as any void texture_atlas_t::import_from_json(std::string const& filepath) { string json_str = read_text_file(filepath); cJSON* root = cJSON_Parse(json_str.c_str()); ASSERT(root, "Error loading imported textures json file"); auto meta_json = cJSON_GetObjectItem(root, "meta"); auto atlas_texture_filename = cJSON_GetObjectItem(meta_json, "image")->valuestring; //atlas texture is in the same folder, so just chop off the data filename from its path and append the texture filename std::string atlas_texture_filepath; auto last_slash_index = filepath.find_last_of("/\\"); if(last_slash_index == std::string::npos) { atlas_texture_filepath = atlas_texture_filename ; } else { atlas_texture_filepath = filepath.substr(0, last_slash_index) + "/" + atlas_texture_filename; } atlas_texture = make_shared<texture_t>(atlas_texture_filepath); auto frames_json = cJSON_GetObjectItem(root, "frames"); //array of entries ('frames') size_t len = cJSON_GetArraySize(frames_json); for(size_t i = 0; i < len; ++i) { auto entry_json = cJSON_GetArrayItem(frames_json, i); auto frame_json = cJSON_GetObjectItem(entry_json, "frame"); entry_t entry{string(cJSON_GetObjectItem(entry_json, "filename")->valuestring) , uvec2(cJSON_GetObjectItem(frame_json, "x")->valueint, cJSON_GetObjectItem(frame_json, "y")->valueint) , uvec2(cJSON_GetObjectItem(frame_json, "w")->valueint, cJSON_GetObjectItem(frame_json, "h")->valueint) }; } cJSON_Delete(root); } } }<commit_msg>texture atlas actually pushes a loaded entry instead of just ignoring it<commit_after>#include "stdafx.h" #include "texture_atlas.h" #include "texture.h" #include "utilities/utilities.h" #include "utilities/cjson_utils.hpp" using namespace std; using namespace glm; namespace asdf { using namespace util; namespace data { texture_atlas_t::texture_atlas_t(std::string const& json_filepath) { import_from_json(json_filepath); } // Designed to import from TexturePacker, because that's a good a standard as any void texture_atlas_t::import_from_json(std::string const& filepath) { string json_str = read_text_file(filepath); cJSON* root = cJSON_Parse(json_str.c_str()); ASSERT(root, "Error loading imported textures json file"); auto meta_json = cJSON_GetObjectItem(root, "meta"); auto atlas_texture_filename = cJSON_GetObjectItem(meta_json, "image")->valuestring; //atlas texture is in the same folder, so just chop off the data filename from its path and append the texture filename std::string atlas_texture_filepath; auto last_slash_index = filepath.find_last_of("/\\"); if(last_slash_index == std::string::npos) { atlas_texture_filepath = atlas_texture_filename ; } else { atlas_texture_filepath = filepath.substr(0, last_slash_index) + "/" + atlas_texture_filename; } atlas_texture = make_shared<texture_t>(atlas_texture_filepath); auto frames_json = cJSON_GetObjectItem(root, "frames"); //array of entries ('frames') size_t len = cJSON_GetArraySize(frames_json); for(size_t i = 0; i < len; ++i) { auto entry_json = cJSON_GetArrayItem(frames_json, i); auto frame_json = cJSON_GetObjectItem(entry_json, "frame"); entry_t entry{string(cJSON_GetObjectItem(entry_json, "filename")->valuestring) , uvec2(cJSON_GetObjectItem(frame_json, "x")->valueint, cJSON_GetObjectItem(frame_json, "y")->valueint) , uvec2(cJSON_GetObjectItem(frame_json, "w")->valueint, cJSON_GetObjectItem(frame_json, "h")->valueint) }; atlas_entries.push_back(std::move(entry)); } cJSON_Delete(root); } } }<|endoftext|>
<commit_before>#ifdef STAN_OPENCL #include <stan/math/prim/mat.hpp> #include <stan/math/prim/arr.hpp> #include <gtest/gtest.h> TEST(ErrorHandlingOpenCL, checkThrows) { const char* function = "test_func"; const char* msg = "test"; EXPECT_THROW(stan::math::throw_openCL(function, msg), std::domain_error); } #else TEST(ErrorHandlingOpenCL, checkThrowsDummy) { int a; EXPECT_NO_THROW(a = 1); } #endif <commit_msg>forgot to add gtest header to check_opencl test<commit_after>#ifdef STAN_OPENCL #include <stan/math/prim/mat.hpp> #include <stan/math/prim/arr.hpp> #include <gtest/gtest.h> TEST(ErrorHandlingOpenCL, checkThrows) { const char* function = "test_func"; const char* msg = "test"; EXPECT_THROW(stan::math::throw_openCL(function, msg), std::domain_error); } #else #include <gtest/gtest.h> TEST(ErrorHandlingOpenCL, checkThrowsDummy) { int a; EXPECT_NO_THROW(a = 1); } #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: hfi_method.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2004-07-12 15:26:58 $ * * 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 "hfi_method.hxx" // NOT FULLY DEFINED SERVICES #include <ary/idl/i_exception.hxx> #include <ary/idl/i_param.hxx> #include <toolkit/hf_docentry.hxx> #include <toolkit/hf_funcdecl.hxx> #include "hfi_doc.hxx" #include "hfi_globalindex.hxx" #include "hfi_typetext.hxx" HF_IdlMethod::HF_IdlMethod( Environment & io_rEnv, Xml::Element & o_cell) : HtmlFactory_Idl(io_rEnv,&o_cell) { } HF_IdlMethod::~HF_IdlMethod() { } void HF_IdlMethod::Produce_byData( const String & i_sName, type_id i_nReturnType, param_list & i_rParams, type_list & i_rExceptions, bool i_bOneway, bool i_bEllipse, const client & i_ce ) const { CurOut() >> *new Html::Label(i_sName) << new Html::ClassAttr(C_sMemberTitle) << i_sName; enter_ContentCell(); write_Declaration( i_sName, i_nReturnType, i_rParams, i_rExceptions, i_bOneway, i_bEllipse ); CurOut() << new Html::HorizontalLine; write_Docu(CurOut(), i_ce); leave_ContentCell(); } void HF_IdlMethod::write_Declaration( const String & i_sName, type_id i_nReturnType, param_list & i_rParams, type_list & i_rExceptions, bool i_bOneway, bool i_bEllipse ) const { HF_FunctionDeclaration aDecl(CurOut()) ; Xml::Element & front = aDecl.Add_ReturnLine(); // Front: if (i_bOneway) front << "[oneway] "; if (i_nReturnType.IsValid()) { // Normal function, but not constructors: HF_IdlTypeText aReturn(Env(), front,true); aReturn.Produce_byData(i_nReturnType); front << new Html::LineBreak; } front >> *new Html::Bold << i_sName; // Main line: Xml::Element & types = aDecl.Types(); Xml::Element & names = aDecl.Names(); bool bParams = i_rParams.operator bool(); if (bParams) { front << "("; HF_IdlTypeText aType( Env(), types, true ); write_Param( aType, names, (*i_rParams) ); for (++i_rParams; i_rParams; ++i_rParams) { types << new Html::LineBreak; names << "," << new Html::LineBreak; write_Param( aType, names, (*i_rParams) ); } // end for if (i_bEllipse) { names << " ..."; } names << " )"; } else front << "()"; if ( i_rExceptions.operator bool() ) { Xml::Element & rExcOut = aDecl.Add_RaisesLine("raises", NOT bParams); HF_IdlTypeText aExc(Env(), rExcOut, true); aExc.Produce_byData(*i_rExceptions); for (++i_rExceptions; i_rExceptions; ++i_rExceptions) { rExcOut << "," << new Html::LineBreak; aExc.Produce_byData(*i_rExceptions); } // end for rExcOut << " );"; } else { if (bParams) aDecl.Names() << ";"; else aDecl.Front() << ";"; } } void HF_IdlMethod::write_Param( HF_IdlTypeText & o_type, Xml::Element & o_names, const ary::idl::Parameter & i_param ) const { switch ( i_param.Direction() ) { case ary::idl::param_in: o_type.CurOut() << "[in] "; break; case ary::idl::param_out: o_type.CurOut() << "[out] "; break; case ary::idl::param_inout: o_type.CurOut() << "[inout] "; break; } // end switch o_type.Produce_byData( i_param.Type() ); o_names << i_param.Name(); } const String sContentBorder("0"); const String sContentWidth("96%"); const String sContentPadding("5"); const String sContentSpacing("0"); const String sBgWhite("#ffffff"); const String sCenter("center"); void HF_IdlMethod::enter_ContentCell() const { Xml::Element & rContentCell = CurOut() >> *new Html::Table( sContentBorder, sContentWidth, sContentPadding, sContentSpacing ) << new Html::BgColorAttr(sBgWhite) << new Html::AlignAttr(sCenter) >> *new Html::TableRow >> *new Html::TableCell; Out().Enter(rContentCell); } void HF_IdlMethod::leave_ContentCell() const { Out().Leave(); } <commit_msg>INTEGRATION: CWS adc9 (1.3.6); FILE MERGED 2004/11/09 17:20:00 np 1.3.6.1: #112290#<commit_after>/************************************************************************* * * $RCSfile: hfi_method.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2004-11-15 13:33:33 $ * * 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 "hfi_method.hxx" // NOT FULLY DEFINED SERVICES #include <ary/idl/i_exception.hxx> #include <ary/idl/i_param.hxx> #include <toolkit/hf_docentry.hxx> #include <toolkit/hf_funcdecl.hxx> #include "hfi_doc.hxx" #include "hfi_globalindex.hxx" #include "hfi_typetext.hxx" HF_IdlMethod::HF_IdlMethod( Environment & io_rEnv, Xml::Element & o_cell) : HtmlFactory_Idl(io_rEnv,&o_cell) { } HF_IdlMethod::~HF_IdlMethod() { } void HF_IdlMethod::Produce_byData( const String & i_sName, type_id i_nReturnType, param_list & i_rParams, type_list & i_rExceptions, bool i_bOneway, bool i_bEllipse, const client & i_ce ) const { CurOut() >> *new Html::Label(i_sName) << new Html::ClassAttr(C_sMemberTitle) << i_sName; enter_ContentCell(); write_Declaration( i_sName, i_nReturnType, i_rParams, i_rExceptions, i_bOneway, i_bEllipse ); CurOut() << new Html::HorizontalLine; write_Docu(CurOut(), i_ce); leave_ContentCell(); } #if 0 // old void HF_IdlMethod::write_Declaration( const String & i_sName, type_id i_nReturnType, param_list & i_rParams, type_list & i_rExceptions, bool i_bOneway, bool i_bEllipse ) const { HF_FunctionDeclaration aDecl(CurOut()) ; Xml::Element & front = aDecl.Add_ReturnLine(); // Front: if (i_bOneway) front << "[oneway] "; if (i_nReturnType.IsValid()) { // Normal function, but not constructors: HF_IdlTypeText aReturn(Env(), front, true); aReturn.Produce_byData(i_nReturnType); front << new Html::LineBreak; } front >> *new Html::Bold << i_sName; // Main line: Xml::Element & types = aDecl.Types(); Xml::Element & names = aDecl.Names(); bool bParams = i_rParams.operator bool(); if (bParams) { front << "("; HF_IdlTypeText aType( Env(), types, true ); write_Param( aType, names, (*i_rParams) ); for (++i_rParams; i_rParams; ++i_rParams) { types << new Html::LineBreak; names << "," << new Html::LineBreak; write_Param( aType, names, (*i_rParams) ); } // end for if (i_bEllipse) { names << " ..."; } names << " )"; } else front << "()"; if ( i_rExceptions.operator bool() ) { Xml::Element & rExcOut = aDecl.Add_RaisesLine("raises", NOT bParams); HF_IdlTypeText aExc(Env(), rExcOut, true); aExc.Produce_byData(*i_rExceptions); for (++i_rExceptions; i_rExceptions; ++i_rExceptions) { rExcOut << "," << new Html::LineBreak; aExc.Produce_byData(*i_rExceptions); } // end for rExcOut << " );"; } else { if (bParams) aDecl.Names() << ";"; else aDecl.Front() << ";"; } } #endif // 0 old void HF_IdlMethod::write_Declaration( const String & i_sName, type_id i_nReturnType, param_list & i_rParams, type_list & i_rExceptions, bool i_bOneway, bool i_bEllipse ) const { HF_FunctionDeclaration aDecl(CurOut(), "raises") ; Xml::Element & rReturnLine = aDecl.ReturnCell(); // Return line: if (i_bOneway) rReturnLine << "[oneway] "; if (i_nReturnType.IsValid()) { // Normal function, but not constructors: HF_IdlTypeText aReturn(Env(), rReturnLine, true); aReturn.Produce_byData(i_nReturnType); } // Main line: Xml::Element & rNameCell = aDecl.NameCell(); rNameCell >> *new Html::Bold << i_sName; Xml::Element * pParamEnd = 0; bool bParams = i_rParams.operator bool(); if (bParams) { rNameCell << "("; pParamEnd = write_Param( aDecl, *i_rParams ); for (++i_rParams; i_rParams; ++i_rParams) { *pParamEnd << ","; pParamEnd = write_Param( aDecl, *i_rParams ); } // end for if (i_bEllipse) { Xml::Element & rParamType = aDecl.NewParamTypeCell(); rParamType << " ..."; pParamEnd = &rParamType; } *pParamEnd << " )"; } else { rNameCell << "()"; } if ( i_rExceptions.operator bool() ) { Xml::Element & rExcOut = aDecl.ExceptionCell(); HF_IdlTypeText aExc(Env(), rExcOut, true); aExc.Produce_byData(*i_rExceptions); for (++i_rExceptions; i_rExceptions; ++i_rExceptions) { rExcOut << "," << new Html::LineBreak; aExc.Produce_byData(*i_rExceptions); } // end for rExcOut << " );"; } else if (bParams) { *pParamEnd << ";"; } else { rNameCell << ";"; } } #if 0 // old void HF_IdlMethod::write_Param( HF_IdlTypeText & o_type, Xml::Element & o_names, const ary::idl::Parameter & i_param ) const { switch ( i_param.Direction() ) { case ary::idl::param_in: o_type.CurOut() << "[in] "; break; case ary::idl::param_out: o_type.CurOut() << "[out] "; break; case ary::idl::param_inout: o_type.CurOut() << "[inout] "; break; } // end switch o_type.Produce_byData( i_param.Type() ); o_names << i_param.Name(); } #endif // 0 old Xml::Element * HF_IdlMethod::write_Param( HF_FunctionDeclaration & o_decl, const ary::idl::Parameter & i_param ) const { Xml::Element & rTypeCell = o_decl.NewParamTypeCell(); Xml::Element & rNameCell = o_decl.ParamNameCell(); switch ( i_param.Direction() ) { case ary::idl::param_in: rTypeCell << "[in] "; break; case ary::idl::param_out: rTypeCell << "[out] "; break; case ary::idl::param_inout: rTypeCell << "[inout] "; break; } // end switch HF_IdlTypeText aTypeWriter(Env(), rTypeCell, true); aTypeWriter.Produce_byData( i_param.Type() ); rNameCell << i_param.Name(); return &rNameCell; } const String sContentBorder("0"); const String sContentWidth("96%"); const String sContentPadding("5"); const String sContentSpacing("0"); const String sBgWhite("#ffffff"); const String sCenter("center"); void HF_IdlMethod::enter_ContentCell() const { Xml::Element & rContentCell = CurOut() >> *new Html::Table( sContentBorder, sContentWidth, sContentPadding, sContentSpacing ) << new Html::BgColorAttr(sBgWhite) << new Html::AlignAttr(sCenter) >> *new Html::TableRow >> *new Html::TableCell; Out().Enter(rContentCell); } void HF_IdlMethod::leave_ContentCell() const { Out().Leave(); } <|endoftext|>
<commit_before>// Copyright (C) 2017 Elviss Strazdins // This file is part of the Ouzel engine. #include <cassert> #include "TTFont.hpp" #include "core/Engine.hpp" #include "files/FileSystem.hpp" #include "utils/Log.hpp" #include "utils/Utils.hpp" #define STB_TRUETYPE_IMPLEMENTATION #include "../../external/stb/stb_truetype.h" namespace ouzel { TTFont::TTFont(): Font() { } TTFont::TTFont(const std::string & filename, uint16_t pt, bool mipmaps, UTFChars flag) { if (!parseFont(filename, pt, mipmaps, flag)) { Log(Log::Level::ERR) << "Failed to parse font " << filename; } kernCount = static_cast<uint16_t>(kern.size()); } void TTFont::getVertices(const std::string& text, const Color& color, const Vector2& anchor, const Vector2& scale, std::vector<uint16_t>& indices, std::vector<graphics::VertexPCT>& vertices, std::shared_ptr<graphics::Texture>& texture) { Vector2 position; std::vector<uint32_t> utf32Text = utf8to32(text); indices.clear(); vertices.clear(); indices.reserve(utf32Text.size() * 6); vertices.reserve(utf32Text.size() * 4); Vector2 textCoords[4]; size_t firstChar = 0; for (auto i = utf32Text.begin(); i != utf32Text.end(); ++i) { std::unordered_map<uint32_t, CharDescriptor>::iterator iter = chars.find(*i); if (iter != chars.end()) { const CharDescriptor& f = iter->second; uint16_t startIndex = static_cast<uint16_t>(vertices.size()); indices.push_back(startIndex + 0); indices.push_back(startIndex + 1); indices.push_back(startIndex + 2); indices.push_back(startIndex + 1); indices.push_back(startIndex + 3); indices.push_back(startIndex + 2); Vector2 leftTop(f.x / static_cast<float>(width), f.y / static_cast<float>(height)); Vector2 rightBottom((f.x + f.width) / static_cast<float>(width), (f.y + f.height) / static_cast<float>(height)); textCoords[0] = Vector2(leftTop.v[0], rightBottom.v[1]); textCoords[1] = Vector2(rightBottom.v[0], rightBottom.v[1]); textCoords[2] = Vector2(leftTop.v[0], leftTop.v[1]); textCoords[3] = Vector2(rightBottom.v[0], leftTop.v[1]); vertices.push_back(graphics::VertexPCT(Vector3(position.v[0] + f.xOffset, -position.v[1] - f.yOffset - f.height, 0.0f), color, textCoords[0])); vertices.push_back(graphics::VertexPCT(Vector3(position.v[0] + f.xOffset + f.width, -position.v[1] - f.yOffset - f.height, 0.0f), color, textCoords[1])); vertices.push_back(graphics::VertexPCT(Vector3(position.v[0] + f.xOffset, -position.v[1] - f.yOffset, 0.0f), color, textCoords[2])); vertices.push_back(graphics::VertexPCT(Vector3(position.v[0] + f.xOffset + f.width, -position.v[1] - f.yOffset, 0.0f), color, textCoords[3])); if ((i + 1) != utf32Text.end()) { position.v[0] += static_cast<float>(getKerningPair(*i, *(i + 1))); } position.v[0] += f.xAdvance; } if (*i == static_cast<uint32_t>('\n') || // line feed (i + 1) == utf32Text.end()) // end of string { float lineWidth = position.v[0]; position.v[0] = 0.0f; position.v[1] += lineHeight; for (size_t c = firstChar; c < vertices.size(); ++c) { vertices[c].position.v[0] -= lineWidth * anchor.v[0]; } firstChar = vertices.size(); } } float textHeight = position.v[1]; for (size_t c = 0; c < vertices.size(); ++c) { vertices[c].position.v[1] += textHeight * (1.0f - anchor.v[1]); vertices[c].position.v[0] *= scale.v[0]; vertices[c].position.v[1] *= scale.v[1]; } texture = fontTexture; } int16_t TTFont::getKerningPair(uint32_t first, uint32_t second) { auto i = kern.find(std::make_pair(first, second)); if (i != kern.end()) { return i->second; } return 0; } float TTFont::getStringWidth(const std::string& text) { float total = 0.0f; std::vector<uint32_t> utf32Text = utf8to32(text); for (auto i = utf32Text.begin(); i != utf32Text.end(); ++i) { std::unordered_map<uint32_t, CharDescriptor>::iterator iter = chars.find(*i); if (iter != chars.end()) { const CharDescriptor& f = iter->second; total += f.xAdvance; } } return total; } bool TTFont::parseFont(const std::string & filename, uint16_t pt, bool mipmaps, UTFChars flag) { stbtt_fontinfo font; std::vector<unsigned char> data; std::string f = ouzel::sharedEngine->getFileSystem()->getPath(filename); ouzel::sharedEngine->getFileSystem()->readFile(f, data); if (!stbtt_InitFont(&font, data.data(), stbtt_GetFontOffsetForIndex(data.data(), 0))) { Log(Log::Level::ERR) << "Failed to load font"; return false; } float s = stbtt_ScaleForPixelHeight(&font, pt); int w, h, xoff, yoff; height = 0; width = 0; std::vector<uint16_t> glyphs; std::map<uint32_t, std::pair<Size2, std::vector<uint8_t>> > glyphToBitmapData; if (flag && UTFChars::ASCII) { for (uint16_t i = 32; i < 127; i++) { glyphs.push_back(i); } } if (flag && UTFChars::ASCIIPLUS) { for (uint16_t i = 128; i < 256; i++) { glyphs.push_back(i); } } for (uint16_t c : glyphs) { unsigned char* bitmap = stbtt_GetCodepointBitmap(&font, s, s, c, &w, &h, &xoff, &yoff); if (bitmap) { for (uint16_t j : glyphs) { int kx = stbtt_GetCodepointKernAdvance(&font, j, c); if (kx == 0) continue; kern.emplace(std::pair<uint32_t, uint32_t>(j, c), static_cast<int16_t>(kx * s)); } int advance, leftBearing; stbtt_GetCodepointHMetrics(&font, c, &advance, &leftBearing); CharDescriptor nd; nd.xAdvance = static_cast<int16_t>(advance * s); nd.height = static_cast<int16_t>(h); nd.width = static_cast<int16_t>(w); nd.xOffset = static_cast<int16_t>(leftBearing * s); nd.yOffset = static_cast<int16_t>(h - abs(yoff)); std::vector<uint8_t> currentBuffer(static_cast<size_t>(h * w)); std::copy(&bitmap[0], &bitmap[h * w], currentBuffer.begin()); glyphToBitmapData.emplace(c, std::make_pair(Size2(static_cast<float>(w), static_cast<float>(h)), currentBuffer)); chars.emplace(c, nd); height = height < static_cast<uint16_t>(h) ? static_cast<uint16_t>(h) : height; width += static_cast<uint16_t>(w); } } std::vector<std::vector<uint8_t> > scanlines(height); int x = 0; for (const auto &c : glyphToBitmapData) { uint16_t charHeight = static_cast<uint16_t>(c.second.first.height()); uint16_t charWidth = static_cast<uint16_t>(c.second.first.width()); chars.at(c.first).x = static_cast<int16_t>(x); chars.at(c.first).y = 0; x += charWidth; uint16_t extraRows = height - charHeight; chars.at(c.first).yOffset += extraRows; size_t extraSpaceSize = extraRows * charWidth; unsigned int charSize = charHeight * charWidth; std::vector<uint8_t> newCharBuffer(extraSpaceSize + charSize, 0x00); std::copy(c.second.second.begin(), c.second.second.begin() + charSize, newCharBuffer.data()); assert(newCharBuffer.size() == height * charWidth); for (uint16_t i = 0; i < height; i++) { size_t scanlinesPreSize = scanlines[i].size(); scanlines[i].resize(scanlinesPreSize + charWidth); uint8_t* bufferStart = newCharBuffer.data() + static_cast<int>(charWidth * i); std::copy(bufferStart, bufferStart + charWidth, scanlines[i].data() + scanlinesPreSize); } } std::vector<uint8_t> textureData(scanlines[0].size() * height * 4); for (uint16_t i = 0; i < height; i++) { for (uint32_t j = 0; j < scanlines[0].size(); j++) { uint8_t b = scanlines[i][j]; textureData[(i * scanlines[0].size() + j) * 4 + 0] = 255; textureData[(i * scanlines[0].size() + j) * 4 + 1] = 255; textureData[(i * scanlines[0].size() + j) * 4 + 2] = 255; textureData[(i * scanlines[0].size() + j) * 4 + 3] = b; } } fontTexture = std::make_shared<graphics::Texture>(); fontTexture->init(textureData, Size2(width, height), 0, mipmaps ? 0 : 1); pages = 1; lineHeight = pt; kernCount = static_cast<uint16_t>(kern.size()); base = 0; return true; } } <commit_msg>Remove unneeded spaces<commit_after>// Copyright (C) 2017 Elviss Strazdins // This file is part of the Ouzel engine. #include <cassert> #include "TTFont.hpp" #include "core/Engine.hpp" #include "files/FileSystem.hpp" #include "utils/Log.hpp" #include "utils/Utils.hpp" #define STB_TRUETYPE_IMPLEMENTATION #include "../../external/stb/stb_truetype.h" namespace ouzel { TTFont::TTFont(): Font() { } TTFont::TTFont(const std::string & filename, uint16_t pt, bool mipmaps, UTFChars flag) { if (!parseFont(filename, pt, mipmaps, flag)) { Log(Log::Level::ERR) << "Failed to parse font " << filename; } kernCount = static_cast<uint16_t>(kern.size()); } void TTFont::getVertices(const std::string& text, const Color& color, const Vector2& anchor, const Vector2& scale, std::vector<uint16_t>& indices, std::vector<graphics::VertexPCT>& vertices, std::shared_ptr<graphics::Texture>& texture) { Vector2 position; std::vector<uint32_t> utf32Text = utf8to32(text); indices.clear(); vertices.clear(); indices.reserve(utf32Text.size() * 6); vertices.reserve(utf32Text.size() * 4); Vector2 textCoords[4]; size_t firstChar = 0; for (auto i = utf32Text.begin(); i != utf32Text.end(); ++i) { std::unordered_map<uint32_t, CharDescriptor>::iterator iter = chars.find(*i); if (iter != chars.end()) { const CharDescriptor& f = iter->second; uint16_t startIndex = static_cast<uint16_t>(vertices.size()); indices.push_back(startIndex + 0); indices.push_back(startIndex + 1); indices.push_back(startIndex + 2); indices.push_back(startIndex + 1); indices.push_back(startIndex + 3); indices.push_back(startIndex + 2); Vector2 leftTop(f.x / static_cast<float>(width), f.y / static_cast<float>(height)); Vector2 rightBottom((f.x + f.width) / static_cast<float>(width), (f.y + f.height) / static_cast<float>(height)); textCoords[0] = Vector2(leftTop.v[0], rightBottom.v[1]); textCoords[1] = Vector2(rightBottom.v[0], rightBottom.v[1]); textCoords[2] = Vector2(leftTop.v[0], leftTop.v[1]); textCoords[3] = Vector2(rightBottom.v[0], leftTop.v[1]); vertices.push_back(graphics::VertexPCT(Vector3(position.v[0] + f.xOffset, -position.v[1] - f.yOffset - f.height, 0.0f), color, textCoords[0])); vertices.push_back(graphics::VertexPCT(Vector3(position.v[0] + f.xOffset + f.width, -position.v[1] - f.yOffset - f.height, 0.0f), color, textCoords[1])); vertices.push_back(graphics::VertexPCT(Vector3(position.v[0] + f.xOffset, -position.v[1] - f.yOffset, 0.0f), color, textCoords[2])); vertices.push_back(graphics::VertexPCT(Vector3(position.v[0] + f.xOffset + f.width, -position.v[1] - f.yOffset, 0.0f), color, textCoords[3])); if ((i + 1) != utf32Text.end()) { position.v[0] += static_cast<float>(getKerningPair(*i, *(i + 1))); } position.v[0] += f.xAdvance; } if (*i == static_cast<uint32_t>('\n') || // line feed (i + 1) == utf32Text.end()) // end of string { float lineWidth = position.v[0]; position.v[0] = 0.0f; position.v[1] += lineHeight; for (size_t c = firstChar; c < vertices.size(); ++c) { vertices[c].position.v[0] -= lineWidth * anchor.v[0]; } firstChar = vertices.size(); } } float textHeight = position.v[1]; for (size_t c = 0; c < vertices.size(); ++c) { vertices[c].position.v[1] += textHeight * (1.0f - anchor.v[1]); vertices[c].position.v[0] *= scale.v[0]; vertices[c].position.v[1] *= scale.v[1]; } texture = fontTexture; } int16_t TTFont::getKerningPair(uint32_t first, uint32_t second) { auto i = kern.find(std::make_pair(first, second)); if (i != kern.end()) { return i->second; } return 0; } float TTFont::getStringWidth(const std::string& text) { float total = 0.0f; std::vector<uint32_t> utf32Text = utf8to32(text); for (auto i = utf32Text.begin(); i != utf32Text.end(); ++i) { std::unordered_map<uint32_t, CharDescriptor>::iterator iter = chars.find(*i); if (iter != chars.end()) { const CharDescriptor& f = iter->second; total += f.xAdvance; } } return total; } bool TTFont::parseFont(const std::string & filename, uint16_t pt, bool mipmaps, UTFChars flag) { stbtt_fontinfo font; std::vector<unsigned char> data; std::string f = ouzel::sharedEngine->getFileSystem()->getPath(filename); ouzel::sharedEngine->getFileSystem()->readFile(f, data); if (!stbtt_InitFont(&font, data.data(), stbtt_GetFontOffsetForIndex(data.data(), 0))) { Log(Log::Level::ERR) << "Failed to load font"; return false; } float s = stbtt_ScaleForPixelHeight(&font, pt); int w, h, xoff, yoff; height = 0; width = 0; std::vector<uint16_t> glyphs; std::map<uint32_t, std::pair<Size2, std::vector<uint8_t>>> glyphToBitmapData; if (flag && UTFChars::ASCII) { for (uint16_t i = 32; i < 127; i++) { glyphs.push_back(i); } } if (flag && UTFChars::ASCIIPLUS) { for (uint16_t i = 128; i < 256; i++) { glyphs.push_back(i); } } for (uint16_t c : glyphs) { unsigned char* bitmap = stbtt_GetCodepointBitmap(&font, s, s, c, &w, &h, &xoff, &yoff); if (bitmap) { for (uint16_t j : glyphs) { int kx = stbtt_GetCodepointKernAdvance(&font, j, c); if (kx == 0) continue; kern.emplace(std::pair<uint32_t, uint32_t>(j, c), static_cast<int16_t>(kx * s)); } int advance, leftBearing; stbtt_GetCodepointHMetrics(&font, c, &advance, &leftBearing); CharDescriptor nd; nd.xAdvance = static_cast<int16_t>(advance * s); nd.height = static_cast<int16_t>(h); nd.width = static_cast<int16_t>(w); nd.xOffset = static_cast<int16_t>(leftBearing * s); nd.yOffset = static_cast<int16_t>(h - abs(yoff)); std::vector<uint8_t> currentBuffer(static_cast<size_t>(h * w)); std::copy(&bitmap[0], &bitmap[h * w], currentBuffer.begin()); glyphToBitmapData.emplace(c, std::make_pair(Size2(static_cast<float>(w), static_cast<float>(h)), currentBuffer)); chars.emplace(c, nd); height = height < static_cast<uint16_t>(h) ? static_cast<uint16_t>(h) : height; width += static_cast<uint16_t>(w); } } std::vector<std::vector<uint8_t>> scanlines(height); int x = 0; for (const auto &c : glyphToBitmapData) { uint16_t charHeight = static_cast<uint16_t>(c.second.first.height()); uint16_t charWidth = static_cast<uint16_t>(c.second.first.width()); chars.at(c.first).x = static_cast<int16_t>(x); chars.at(c.first).y = 0; x += charWidth; uint16_t extraRows = height - charHeight; chars.at(c.first).yOffset += extraRows; size_t extraSpaceSize = extraRows * charWidth; unsigned int charSize = charHeight * charWidth; std::vector<uint8_t> newCharBuffer(extraSpaceSize + charSize, 0x00); std::copy(c.second.second.begin(), c.second.second.begin() + charSize, newCharBuffer.data()); assert(newCharBuffer.size() == height * charWidth); for (uint16_t i = 0; i < height; i++) { size_t scanlinesPreSize = scanlines[i].size(); scanlines[i].resize(scanlinesPreSize + charWidth); uint8_t* bufferStart = newCharBuffer.data() + static_cast<int>(charWidth * i); std::copy(bufferStart, bufferStart + charWidth, scanlines[i].data() + scanlinesPreSize); } } std::vector<uint8_t> textureData(scanlines[0].size() * height * 4); for (uint16_t i = 0; i < height; i++) { for (uint32_t j = 0; j < scanlines[0].size(); j++) { uint8_t b = scanlines[i][j]; textureData[(i * scanlines[0].size() + j) * 4 + 0] = 255; textureData[(i * scanlines[0].size() + j) * 4 + 1] = 255; textureData[(i * scanlines[0].size() + j) * 4 + 2] = 255; textureData[(i * scanlines[0].size() + j) * 4 + 3] = b; } } fontTexture = std::make_shared<graphics::Texture>(); fontTexture->init(textureData, Size2(width, height), 0, mipmaps ? 0 : 1); pages = 1; lineHeight = pt; kernCount = static_cast<uint16_t>(kern.size()); base = 0; return true; } } <|endoftext|>
<commit_before>// // Copyright © 2017 Arm Ltd. All rights reserved. // SPDX-License-Identifier: MIT // #include "../InferenceTest.hpp" #include "../ImagePreprocessor.hpp" #include "armnnTfParser/ITfParser.hpp" int main(int argc, char* argv[]) { int retVal = EXIT_FAILURE; try { // Coverity fix: The following code may throw an exception of type std::length_error. std::vector<ImageSet> imageSet = { { "Dog.jpg", 208 }, // Top five predictions in tensorflow: // ----------------------------------- // 208:golden retriever 0.57466376 // 209:Labrador retriever 0.30202731 // 853:tennis ball 0.0060001756 // 223:kuvasz 0.0053707925 // 160:Rhodesian ridgeback 0.0018179063 { "Cat.jpg", 283 }, // Top five predictions in tensorflow: // ----------------------------------- // 283:tiger cat 0.4667799 // 282:tabby, tabby cat 0.32511184 // 286:Egyptian cat 0.1038616 // 288:lynx, catamount 0.0017019814 // 284:Persian cat 0.0011340436 { "shark.jpg", 3 }, // Top five predictions in tensorflow: // ----------------------------------- // 3:great white shark, white shark, ... 0.98808634 // 148:grey whale, gray whale, ... 0.00070245547 // 234:Bouvier des Flandres, ... 0.00024639888 // 149:killer whale, killer, ... 0.00014115588 // 95:hummingbird 0.00011129203 }; armnn::TensorShape inputTensorShape({ 1, 299, 299, 3 }); using DataType = float; using DatabaseType = ImagePreprocessor<float>; using ParserType = armnnTfParser::ITfParser; using ModelType = InferenceModel<ParserType, DataType>; // Coverity fix: InferenceTestMain() may throw uncaught exceptions. retVal = armnn::test::ClassifierInferenceTestMain<DatabaseType, ParserType>( argc, argv, "inception_v3_2016_08_28_frozen_transformed.pb", true, "input", "InceptionV3/Predictions/Reshape_1", { 0, 1, 2, }, [&imageSet](const char* dataDir, const ModelType&) { return DatabaseType(dataDir, 299, 299, imageSet); }, &inputTensorShape); } catch (const std::exception& e) { // Coverity fix: BOOST_LOG_TRIVIAL (typically used to report errors) may throw an // exception of type std::length_error. // Using stderr instead in this context as there is no point in nesting try-catch blocks here. std::cerr << "WARNING: TfInceptionV3-Armnn: An error has occurred when running " "the classifier inference tests: " << e.what() << std::endl; } return retVal; } <commit_msg>Updated the inception_v3 model taken from official Tf<commit_after>// // Copyright © 2017 Arm Ltd. All rights reserved. // SPDX-License-Identifier: MIT // #include "../InferenceTest.hpp" #include "../ImagePreprocessor.hpp" #include "armnnTfParser/ITfParser.hpp" int main(int argc, char* argv[]) { int retVal = EXIT_FAILURE; try { // Coverity fix: The following code may throw an exception of type std::length_error. std::vector<ImageSet> imageSet = { { "Dog.jpg", 208 }, // Top five predictions in tensorflow: // ----------------------------------- // 208:golden retriever 0.57466376 // 209:Labrador retriever 0.30202731 // 853:tennis ball 0.0060001756 // 223:kuvasz 0.0053707925 // 160:Rhodesian ridgeback 0.0018179063 { "Cat.jpg", 283 }, // Top five predictions in tensorflow: // ----------------------------------- // 283:tiger cat 0.4667799 // 282:tabby, tabby cat 0.32511184 // 286:Egyptian cat 0.1038616 // 288:lynx, catamount 0.0017019814 // 284:Persian cat 0.0011340436 { "shark.jpg", 3 }, // Top five predictions in tensorflow: // ----------------------------------- // 3:great white shark, white shark, ... 0.98808634 // 148:grey whale, gray whale, ... 0.00070245547 // 234:Bouvier des Flandres, ... 0.00024639888 // 149:killer whale, killer, ... 0.00014115588 // 95:hummingbird 0.00011129203 }; armnn::TensorShape inputTensorShape({ 1, 299, 299, 3 }); using DataType = float; using DatabaseType = ImagePreprocessor<float>; using ParserType = armnnTfParser::ITfParser; using ModelType = InferenceModel<ParserType, DataType>; // Coverity fix: InferenceTestMain() may throw uncaught exceptions. retVal = armnn::test::ClassifierInferenceTestMain<DatabaseType, ParserType>( argc, argv, "inception_v3_2016_08_28_frozen.pb", true, "input", "InceptionV3/Predictions/Reshape_1", { 0, 1, 2, }, [&imageSet](const char* dataDir, const ModelType&) { return DatabaseType(dataDir, 299, 299, imageSet); }, &inputTensorShape); } catch (const std::exception& e) { // Coverity fix: BOOST_LOG_TRIVIAL (typically used to report errors) may throw an // exception of type std::length_error. // Using stderr instead in this context as there is no point in nesting try-catch blocks here. std::cerr << "WARNING: TfInceptionV3-Armnn: An error has occurred when running " "the classifier inference tests: " << e.what() << std::endl; } return retVal; } <|endoftext|>
<commit_before>void mkhtml (char *macro=0, Int_t force=0) { // to run this macro, you must have the correct .rootrc file // in your galice directory. // The gAlice classes summary documentation go to directory html // The gAlice classes source documentation go to directory html/src // The example macros documentation go to directory html/examples // gROOT->LoadMacro("loadlibs.C"); // loadlibs(); THtml html; TStopwatch timer; timer.Start(); if(macro) { gROOT->LoadMacro(macro); html.Convert(macro,"Example Macro"); } else { gSystem->Load("liblhapdf.so"); // Parton density functions gSystem->Load("libEGPythia6.so"); // TGenerator interface gSystem->Load("libpythia6.so"); // Pythia gSystem->Load("libAliPythia6.so"); // ALICE specific implementations gSystem->Load("libRALICE.so"); html.MakeAll(force,"[A-Z]*"); } timer.Stop(); timer.Print(); } <commit_msg>Loading analysis libraries<commit_after>void mkhtml (char *macro=0, Int_t force=0) { // to run this macro, you must have the correct .rootrc file // in your galice directory. // The gAlice classes summary documentation go to directory html // The gAlice classes source documentation go to directory html/src // The example macros documentation go to directory html/examples // gROOT->LoadMacro("loadlibs.C"); // loadlibs(); THtml html; html.SetProductName("AliRoot"); TStopwatch timer; timer.Start(); if(macro) { gROOT->LoadMacro(macro); html.Convert(macro,"Example Macro"); } else { gSystem->Load("liblhapdf.so"); // Parton density functions gSystem->Load("libEGPythia6.so"); // TGenerator interface gSystem->Load("libpythia6.so"); // Pythia gSystem->Load("libAliPythia6.so"); // ALICE specific implementations gSystem->Load("libRALICE.so"); gSystem->Load("libANALYSIS.so"); gSystem->Load("libANALYSISalice.so"); gSystem->Load("libANALYSISRL.so"); gSystem->Load("libPWG0base.so"); gSystem->Load("libPWG0dep.so"); gSystem->Load("libPWG0selectors.so"); gSystem->Load("libTENDER.so"); gSystem->Load("libPWG1.so"); gSystem->Load("libCORRFW.so"); gSystem->Load("libPWG2.so"); gSystem->Load("libPWG2AOD.so"); gSystem->Load("libPWG2ebye.so"); gSystem->Load("libPWG2evchar.so"); gSystem->Load("libPWG2femtoscopy.so"); gSystem->Load("libPWG2femtoscopyUser.so"); gSystem->Load("libPWG2flowCommon.so"); gSystem->Load("libPWG2flowTasks.so"); gSystem->Load("libPWG2forward.so"); gSystem->Load("libPWG2kink.so"); gSystem->Load("libPWG2resonances.so"); gSystem->Load("libPWG2spectra.so"); gSystem->Load("libPWG2unicor.so"); gSystem->Load("libPWG3base.so"); gSystem->Load("libPWG3hfe.so"); gSystem->Load("libPWG3muondep.so"); gSystem->Load("libPWG3muon.so"); gSystem->Load("libPWG3.so"); gSystem->Load("libPWG3vertexingHF.so"); gSystem->Load("libPWG3vertexingOld.so"); gSystem->Load("libJETAN.so"); gSystem->Load("libPWG4CaloCalib.so"); gSystem->Load("libPWG4GammaConv.so"); gSystem->Load("libPWG4JetTasks.so"); gSystem->Load("libPWG4omega3pi.so"); gSystem->Load("libPWG4PartCorrBase.so"); gSystem->Load("libPWG4PartCorrDep.so"); html.MakeAll(force,"[A-Z]*"); } timer.Stop(); timer.Print(); } <|endoftext|>
<commit_before>/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "perfetto/base/logging.h" #include "perfetto/trace_processor/trace_processor.h" #include "perfetto/trace_processor/raw_query.pb.h" namespace perfetto { namespace trace_processor { void FuzzTraceProcessor(const uint8_t* data, size_t size); void FuzzTraceProcessor(const uint8_t* data, size_t size) { std::unique_ptr<TraceProcessor> processor = TraceProcessor::CreateInstance(Config()); std::unique_ptr<uint8_t[]> buf(new uint8_t[size]); memcpy(buf.get(), data, size); if (!processor->Parse(std::move(buf), size)) return; processor->NotifyEndOfFile(); } } // namespace trace_processor } // namespace perfetto extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size); extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { perfetto::trace_processor::FuzzTraceProcessor(data, size); return 0; } <commit_msg>trace_processor: fix fuzzing target am: 3f4671995b<commit_after>/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "perfetto/base/logging.h" #include "perfetto/trace_processor/trace_processor.h" #include "perfetto/trace_processor/raw_query.pb.h" namespace perfetto { namespace trace_processor { void FuzzTraceProcessor(const uint8_t* data, size_t size); void FuzzTraceProcessor(const uint8_t* data, size_t size) { std::unique_ptr<TraceProcessor> processor = TraceProcessor::CreateInstance(Config()); std::unique_ptr<uint8_t[]> buf(new uint8_t[size]); memcpy(buf.get(), data, size); util::Status status = processor->Parse(std::move(buf), size); if (!status.ok()) return; processor->NotifyEndOfFile(); } } // namespace trace_processor } // namespace perfetto extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size); extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { perfetto::trace_processor::FuzzTraceProcessor(data, size); return 0; } <|endoftext|>
<commit_before>/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "include/core/SkBitmap.h" #include "include/core/SkMatrix.h" #include "include/private/SkTemplates.h" #include "src/core/SkArenaAlloc.h" #include "src/core/SkBitmapCache.h" #include "src/core/SkBitmapController.h" #include "src/core/SkMatrixPriv.h" #include "src/core/SkMipMap.h" #include "src/image/SkImage_Base.h" /////////////////////////////////////////////////////////////////////////////////////////////////// SkBitmapController::State* SkBitmapController::RequestBitmap(const SkImage_Base* image, const SkMatrix& inv, SkFilterQuality quality, SkArenaAlloc* alloc) { auto* state = alloc->make<SkBitmapController::State>(image, inv, quality); return state->pixmap().addr() ? state : nullptr; } bool SkBitmapController::State::processHighRequest(const SkImage_Base* image) { if (fQuality != kHigh_SkFilterQuality) { return false; } fQuality = kMedium_SkFilterQuality; #ifdef SK_SUPPORT_LEGACY_BICUBIC_FILTERING SkScalar invScaleX = fInvMatrix.getScaleX(); SkScalar invScaleY = fInvMatrix.getScaleY(); if (fInvMatrix.getType() & SkMatrix::kAffine_Mask) { SkSize scale; if (!fInvMatrix.decomposeScale(&scale)) { return false; } invScaleX = scale.width(); invScaleY = scale.height(); } invScaleX = SkScalarAbs(invScaleX); invScaleY = SkScalarAbs(invScaleY); if (invScaleX >= 1 - SK_ScalarNearlyZero || invScaleY >= 1 - SK_ScalarNearlyZero) { // we're down-scaling so abort HQ return false; } #else if (SkMatrixPriv::AdjustHighQualityFilterLevel(fInvMatrix, true) != kHigh_SkFilterQuality) { return false; } #endif // Confirmed that we can use HQ (w/ rasterpipeline) fQuality = kHigh_SkFilterQuality; (void)image->getROPixels(&fResultBitmap); return true; } /* * Modulo internal errors, this should always succeed *if* the matrix is downscaling * (in this case, we have the inverse, so it succeeds if fInvMatrix is upscaling) */ bool SkBitmapController::State::processMediumRequest(const SkImage_Base* image) { SkASSERT(fQuality <= kMedium_SkFilterQuality); if (fQuality != kMedium_SkFilterQuality) { return false; } // Our default return state is to downgrade the request to Low, w/ or w/o setting fBitmap // to a valid bitmap. fQuality = kLow_SkFilterQuality; SkSize invScaleSize; if (!fInvMatrix.decomposeScale(&invScaleSize, nullptr)) { return false; } if (invScaleSize.width() > SK_Scalar1 || invScaleSize.height() > SK_Scalar1) { fCurrMip.reset(SkMipMapCache::FindAndRef(SkBitmapCacheDesc::Make(image))); if (nullptr == fCurrMip.get()) { fCurrMip.reset(SkMipMapCache::AddAndRef(image)); if (nullptr == fCurrMip.get()) { return false; } } // diagnostic for a crasher... SkASSERT_RELEASE(fCurrMip->data()); const SkSize scale = SkSize::Make(SkScalarInvert(invScaleSize.width()), SkScalarInvert(invScaleSize.height())); SkMipMap::Level level; if (fCurrMip->extractLevel(scale, &level)) { const SkSize& invScaleFixup = level.fScale; fInvMatrix.postScale(invScaleFixup.width(), invScaleFixup.height()); // todo: if we could wrap the fCurrMip in a pixelref, then we could just install // that here, and not need to explicitly track it ourselves. return fResultBitmap.installPixels(level.fPixmap); } else { // failed to extract, so release the mipmap fCurrMip.reset(nullptr); } } return false; } SkBitmapController::State::State(const SkImage_Base* image, const SkMatrix& inv, SkFilterQuality qual) { fInvMatrix = inv; fQuality = qual; if (this->processHighRequest(image) || this->processMediumRequest(image)) { SkASSERT(fResultBitmap.getPixels()); } else { (void)image->getROPixels(&fResultBitmap); } // fResultBitmap.getPixels() may be null, but our caller knows to check fPixmap.addr() // and will destroy us if it is nullptr. fPixmap.reset(fResultBitmap.info(), fResultBitmap.getPixels(), fResultBitmap.rowBytes()); } <commit_msg>Roll external/skia ced601b40b37..dc85d3cb67d5 (1 commits)<commit_after>/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "include/core/SkBitmap.h" #include "include/core/SkMatrix.h" #include "include/private/SkTemplates.h" #include "src/core/SkArenaAlloc.h" #include "src/core/SkBitmapCache.h" #include "src/core/SkBitmapController.h" #include "src/core/SkMatrixPriv.h" #include "src/core/SkMipMap.h" #include "src/image/SkImage_Base.h" /////////////////////////////////////////////////////////////////////////////////////////////////// SkBitmapController::State* SkBitmapController::RequestBitmap(const SkImage_Base* image, const SkMatrix& inv, SkFilterQuality quality, SkArenaAlloc* alloc) { auto* state = alloc->make<SkBitmapController::State>(image, inv, quality); return state->pixmap().addr() ? state : nullptr; } bool SkBitmapController::State::processHighRequest(const SkImage_Base* image) { if (fQuality != kHigh_SkFilterQuality) { return false; } if (SkMatrixPriv::AdjustHighQualityFilterLevel(fInvMatrix, true) != kHigh_SkFilterQuality) { fQuality = kMedium_SkFilterQuality; return false; } (void)image->getROPixels(&fResultBitmap); return true; } /* * Modulo internal errors, this should always succeed *if* the matrix is downscaling * (in this case, we have the inverse, so it succeeds if fInvMatrix is upscaling) */ bool SkBitmapController::State::processMediumRequest(const SkImage_Base* image) { SkASSERT(fQuality <= kMedium_SkFilterQuality); if (fQuality != kMedium_SkFilterQuality) { return false; } // Our default return state is to downgrade the request to Low, w/ or w/o setting fBitmap // to a valid bitmap. fQuality = kLow_SkFilterQuality; SkSize invScaleSize; if (!fInvMatrix.decomposeScale(&invScaleSize, nullptr)) { return false; } if (invScaleSize.width() > SK_Scalar1 || invScaleSize.height() > SK_Scalar1) { fCurrMip.reset(SkMipMapCache::FindAndRef(SkBitmapCacheDesc::Make(image))); if (nullptr == fCurrMip.get()) { fCurrMip.reset(SkMipMapCache::AddAndRef(image)); if (nullptr == fCurrMip.get()) { return false; } } // diagnostic for a crasher... SkASSERT_RELEASE(fCurrMip->data()); const SkSize scale = SkSize::Make(SkScalarInvert(invScaleSize.width()), SkScalarInvert(invScaleSize.height())); SkMipMap::Level level; if (fCurrMip->extractLevel(scale, &level)) { const SkSize& invScaleFixup = level.fScale; fInvMatrix.postScale(invScaleFixup.width(), invScaleFixup.height()); // todo: if we could wrap the fCurrMip in a pixelref, then we could just install // that here, and not need to explicitly track it ourselves. return fResultBitmap.installPixels(level.fPixmap); } else { // failed to extract, so release the mipmap fCurrMip.reset(nullptr); } } return false; } SkBitmapController::State::State(const SkImage_Base* image, const SkMatrix& inv, SkFilterQuality qual) { fInvMatrix = inv; fQuality = qual; if (this->processHighRequest(image) || this->processMediumRequest(image)) { SkASSERT(fResultBitmap.getPixels()); } else { (void)image->getROPixels(&fResultBitmap); } // fResultBitmap.getPixels() may be null, but our caller knows to check fPixmap.addr() // and will destroy us if it is nullptr. fPixmap.reset(fResultBitmap.info(), fResultBitmap.getPixels(), fResultBitmap.rowBytes()); } <|endoftext|>