text
stringlengths
54
60.6k
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "pow.h" #include "arith_uint256.h" #include "chain.h" #include "primitives/block.h" #include "uint256.h" // ppcoin: find last block index up to pindex const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake) { //CBlockIndex will be updated with information about the proof type later while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake)) pindex = pindex->pprev; return pindex; } unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params, bool* pfProofOfStake) { const arith_uint256 bnTargetLimit = fProofOfStake ? UintToArith256(params.posLimit) : UintToArith256(params.powLimit); // Genesis block if (pindexLast == NULL) return bnTargetLimit; if (params.fPowAllowMinDifficultyBlocks) { // Special difficulty rule for testnet: // If the new block's timestamp is more than 2* 10 minutes // then allow mining of a min-difficulty block. if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2) return bnTargetLimit; else { // Return the last non-special-min-difficulty-rules-block const CBlockIndex* pindex = pindexLast; while (pindex->pprev && pindex->nHeight % params.DifficultyAdjustmentInterval() != 0 && pindex->nBits == bnTargetLimit) pindex = pindex->pprev; return pindex->nBits; } } return CalculateNextWorkRequired(pindexLast, pindexFirst->GetBlockTime(), params); } unsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params, bool fProofOfStake) { if (params.fPowNoRetargeting) return pindexLast->nBits; // Limit adjustment step int64_t nTargetSpacing = params.nPowTargetSpacing; int64_t nActualSpacing = pindexLast->GetBlockTime() - nFirstBlockTime; if (nActualSpacing < 0) nActualSpacing = nTargetSpacing; if (nActualSpacing > nTargetSpacing * 10) nActualSpacing = nTargetSpacing * 10; // Retarget const arith_uint256 bnTargetLimit = fProofOfStake ? UintToArith256(params.posLimit) : UintToArith256(params.powLimit); // ppcoin: target change every block // ppcoin: retarget with exponential moving toward target spacing arith_uint256 bnNew; bnNew.SetCompact(pindexLast->nBits); int64_t nInterval = params.DifficultyAdjustmentInterval(); bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing); bnNew /= ((nInterval + 1) * nTargetSpacing); if (bnNew <= 0 || bnNew > bnTargetLimit) bnNew = bnTargetLimit; return bnNew.GetCompact(); } bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params) { bool fNegative; bool fOverflow; arith_uint256 bnTarget; bnTarget.SetCompact(nBits, &fNegative, &fOverflow); // Check range if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit)) return false; // Check proof of work matches claimed amount if (UintToArith256(hash) > bnTarget) return false; return true; } <commit_msg>Update GetNextWorkRequired for PoS<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "pow.h" #include "arith_uint256.h" #include "chain.h" #include "primitives/block.h" #include "uint256.h" // ppcoin: find last block index up to pindex const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake) { //CBlockIndex will be updated with information about the proof type later while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake)) pindex = pindex->pprev; return pindex; } unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params, bool* pfProofOfStake) { // choose proof bool fProofOfStake = pindexLast->nHeight > params.nLastPOWBlock; if(pfProofOfStake) fProofOfStake = *pfProofOfStake; unsigned int nTargetLimit = (fProofOfStake ? UintToArith256(params.posLimit) : UintToArith256(params.powLimit)).GetCompact(); // genesis block if (pindexLast == NULL) return nTargetLimit; // first block const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake); if (pindexPrev->pprev == NULL) return nTargetLimit; // second block const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake); if (pindexPrevPrev->pprev == NULL) return nTargetLimit; // min difficulty if (params.fPowAllowMinDifficultyBlocks) { // Special difficulty rule for testnet: // If the new block's timestamp is more than 2* 10 minutes // then allow mining of a min-difficulty block. if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2) return nTargetLimit; else { // Return the last non-special-min-difficulty-rules-block const CBlockIndex* pindex = pindexLast; while (pindex->pprev && pindex->nHeight % params.DifficultyAdjustmentInterval() != 0 && pindex->nBits == nTargetLimit) pindex = pindex->pprev; return pindex->nBits; } } return CalculateNextWorkRequired(pindexPrev, pindexPrevPrev->GetBlockTime(), params, fProofOfStake); } unsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params, bool fProofOfStake) { if (params.fPowNoRetargeting) return pindexLast->nBits; // Limit adjustment step int64_t nTargetSpacing = params.nPowTargetSpacing; int64_t nActualSpacing = pindexLast->GetBlockTime() - nFirstBlockTime; if (nActualSpacing < 0) nActualSpacing = nTargetSpacing; if (nActualSpacing > nTargetSpacing * 10) nActualSpacing = nTargetSpacing * 10; // Retarget const arith_uint256 bnTargetLimit = fProofOfStake ? UintToArith256(params.posLimit) : UintToArith256(params.powLimit); // ppcoin: target change every block // ppcoin: retarget with exponential moving toward target spacing arith_uint256 bnNew; bnNew.SetCompact(pindexLast->nBits); int64_t nInterval = params.DifficultyAdjustmentInterval(); bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing); bnNew /= ((nInterval + 1) * nTargetSpacing); if (bnNew <= 0 || bnNew > bnTargetLimit) bnNew = bnTargetLimit; return bnNew.GetCompact(); } bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params) { bool fNegative; bool fOverflow; arith_uint256 bnTarget; bnTarget.SetCompact(nBits, &fNegative, &fOverflow); // Check range if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit)) return false; // Check proof of work matches claimed amount if (UintToArith256(hash) > bnTarget) return false; return true; } <|endoftext|>
<commit_before>//===-- XBeeSyncServer.cpp - XBee Syncing for GameModel ------------ c++ --===// // // UWH Timer // // This file is distributed under the BSD 3-Clause License. // See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "uwhd/sync/ModelSync.h" #include "uwhd/config/Config.h" #ifdef UWHD_HAVE_LIBXBEE3 #include "uwhd/model/GameModel.h" #include <cassert> #include <cstdint> #include <cstring> #include <errno.h> #include <fcntl.h> #include <iomanip> #include <iostream> #include <memory> #include <queue> #include <semaphore.h> #include <sstream> #include <stdio.h> #include <string.h> #include <string> #include <termios.h> #include <thread> #include <time.h> #include <unistd.h> // Serial comm stuff copied from: http://stackoverflow.com/a/6947758 int set_interface_attribs(int fd, int speed, int parity) { struct termios tty; memset (&tty, 0, sizeof tty); if (tcgetattr (fd, &tty) != 0) { printf("error %d from tcgetattr", errno); return -1; } cfsetospeed (&tty, speed); cfsetispeed (&tty, speed); tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8; // 8-bit chars // disable IGNBRK for mismatched speed tests; otherwise receive break // as \000 chars tty.c_iflag &= ~IGNBRK; // disable break processing tty.c_lflag = 0; // no signaling chars, no echo, // no canonical processing tty.c_oflag = 0; // no remapping, no delays tty.c_cc[VMIN] = 0; // read doesn't block tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout tty.c_iflag &= ~(IXON | IXOFF | IXANY); // shut off xon/xoff ctrl tty.c_cflag |= (CLOCAL | CREAD);// ignore modem controls, // enable reading tty.c_cflag &= ~(PARENB | PARODD); // shut off parity tty.c_cflag |= parity; tty.c_cflag &= ~CSTOPB; tty.c_cflag &= ~CRTSCTS; if (tcsetattr (fd, TCSANOW, &tty) != 0) { printf("error %d from tcsetattr", errno); return -1; } return 0; } void set_blocking(int fd, int should_block) { struct termios tty; memset(&tty, 0, sizeof tty); if (tcgetattr(fd, &tty) != 0) { printf("error %d from tggetattr", errno); return; } tty.c_cc[VMIN] = should_block ? 1 : 0; tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout if (tcsetattr(fd, TCSANOW, &tty) != 0) printf("error %d setting term attributes", errno); } namespace { class XBeeSyncServer : public ModelSyncServer, GameModelManager { public: XBeeSyncServer(); ~XBeeSyncServer(); virtual void Init() override; virtual void setMgr(GameModelManager *NewM) override { assert(!M); M = NewM; M->registerListener(this); } virtual GameModelManager &getMgr() override { return *M; } virtual void modelChanged(GameModel Model) override; virtual void heartbeat() override; private: int fd; GameModelManager *M; static const char *XBeeSerialConsole; static const int XBeeBaudRate; }; class XBeeSyncClient : public ModelSync { public: XBeeSyncClient(); ~XBeeSyncClient(); virtual void Init() override; virtual void setMgr(GameModelManager *NewM) override { assert(!M); M = NewM; //M->registerListener(this); } virtual GameModelManager &getMgr() override { return *M; } void receivedModel(GameModel Model); protected: private: int fd; GameModelManager *M; static const char *XBeeSerialConsole; static const int XBeeBaudRate; }; } // anonymous namespace const char *XBeeSyncServer::XBeeSerialConsole = "/dev/ttyAMA0"; const int XBeeSyncServer::XBeeBaudRate = 9600; const char *XBeeSyncClient::XBeeSerialConsole = "/dev/ttyAMA0"; const int XBeeSyncClient::XBeeBaudRate = 9600; XBeeSyncServer::XBeeSyncServer() : fd(0), M(nullptr) { } XBeeSyncServer::~XBeeSyncServer() { } void XBeeSyncServer::Init() { const char *portname = "/dev/ttyAMA0"; fd = open (portname, O_RDWR | O_NOCTTY | O_SYNC); if (fd < 0) { printf("error %d opening %s: %s", errno, portname, strerror (errno)); return; } set_interface_attribs(fd, B9600, 0); // set speed to 9600 bps, 8n1 (no parity) set_blocking(fd, 0); // set no blocking } void XBeeSyncServer::modelChanged(GameModel Model) { std::string Message = Model.serialize(); write(fd, Message.c_str(), Message.size()); } void XBeeSyncServer::heartbeat() { modelChanged(M->getModel()); } XBeeSyncClient::XBeeSyncClient() : fd(0), M(nullptr) { } XBeeSyncClient::~XBeeSyncClient() { } void XBeeSyncClient::Init() { const char *portname = "/dev/ttyAMA0"; fd = open (portname, O_RDWR | O_NOCTTY | O_SYNC); if (fd < 0) { printf("error %d opening %s: %s", errno, portname, strerror (errno)); return; } set_interface_attribs(fd, B9600, 0); // set speed to 9600 bps, 8n1 (no parity) set_blocking(fd, 1); // set no blocking std::thread([this]() { std::queue<char> Queue; std::stringstream Msg; do { char buf[128]; memset(buf, 0, sizeof(buf)); int n = read(fd, buf, sizeof(buf)); //printf("read: [%s]\n", buf); for (int i = 0; i < n; ++i) Queue.push(buf[i]); while (!Queue.empty()) { char C = Queue.front(); Msg << C; Queue.pop(); if (C == 'E') { GameModel Model; if (GameModel::deSerialize(Msg.str(), Model)) { printf("failed to deserialize [%s]\n", Msg.str().c_str()); } else { //printf("updating model:\n"); receivedModel(Model); } Msg.str(""); Msg.clear(); } } usleep(100); } while (true); }).detach(); } void XBeeSyncClient::receivedModel(GameModel Model) { Model.setPrevStartTime(); M->setModel(Model); } #endif // UWHD_HAVE_LIBXBEE3 ModelSyncServer *CreateXBeeSyncServer() { #ifdef UWHD_HAVE_LIBXBEE3 return new XBeeSyncServer(); #else return nullptr; #endif } ModelSync *CreateXBeeSyncClient() { #ifdef UWHD_HAVE_LIBXBEE3 return new XBeeSyncClient(); #else return nullptr; #endif } <commit_msg>[sync] Warn when xbee comms are requested, but built without UWHD_HAVE_LIBXBEE3<commit_after>//===-- XBeeSyncServer.cpp - XBee Syncing for GameModel ------------ c++ --===// // // UWH Timer // // This file is distributed under the BSD 3-Clause License. // See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "uwhd/sync/ModelSync.h" #include "uwhd/config/Config.h" #ifdef UWHD_HAVE_LIBXBEE3 #include "uwhd/model/GameModel.h" #include <cassert> #include <cstdint> #include <cstring> #include <errno.h> #include <fcntl.h> #include <iomanip> #include <iostream> #include <memory> #include <queue> #include <semaphore.h> #include <sstream> #include <stdio.h> #include <string.h> #include <string> #include <termios.h> #include <thread> #include <time.h> #include <unistd.h> // Serial comm stuff copied from: http://stackoverflow.com/a/6947758 int set_interface_attribs(int fd, int speed, int parity) { struct termios tty; memset (&tty, 0, sizeof tty); if (tcgetattr (fd, &tty) != 0) { printf("error %d from tcgetattr", errno); return -1; } cfsetospeed (&tty, speed); cfsetispeed (&tty, speed); tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8; // 8-bit chars // disable IGNBRK for mismatched speed tests; otherwise receive break // as \000 chars tty.c_iflag &= ~IGNBRK; // disable break processing tty.c_lflag = 0; // no signaling chars, no echo, // no canonical processing tty.c_oflag = 0; // no remapping, no delays tty.c_cc[VMIN] = 0; // read doesn't block tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout tty.c_iflag &= ~(IXON | IXOFF | IXANY); // shut off xon/xoff ctrl tty.c_cflag |= (CLOCAL | CREAD);// ignore modem controls, // enable reading tty.c_cflag &= ~(PARENB | PARODD); // shut off parity tty.c_cflag |= parity; tty.c_cflag &= ~CSTOPB; tty.c_cflag &= ~CRTSCTS; if (tcsetattr (fd, TCSANOW, &tty) != 0) { printf("error %d from tcsetattr", errno); return -1; } return 0; } void set_blocking(int fd, int should_block) { struct termios tty; memset(&tty, 0, sizeof tty); if (tcgetattr(fd, &tty) != 0) { printf("error %d from tggetattr", errno); return; } tty.c_cc[VMIN] = should_block ? 1 : 0; tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout if (tcsetattr(fd, TCSANOW, &tty) != 0) printf("error %d setting term attributes", errno); } namespace { class XBeeSyncServer : public ModelSyncServer, GameModelManager { public: XBeeSyncServer(); ~XBeeSyncServer(); virtual void Init() override; virtual void setMgr(GameModelManager *NewM) override { assert(!M); M = NewM; M->registerListener(this); } virtual GameModelManager &getMgr() override { return *M; } virtual void modelChanged(GameModel Model) override; virtual void heartbeat() override; private: int fd; GameModelManager *M; static const char *XBeeSerialConsole; static const int XBeeBaudRate; }; class XBeeSyncClient : public ModelSync { public: XBeeSyncClient(); ~XBeeSyncClient(); virtual void Init() override; virtual void setMgr(GameModelManager *NewM) override { assert(!M); M = NewM; //M->registerListener(this); } virtual GameModelManager &getMgr() override { return *M; } void receivedModel(GameModel Model); protected: private: int fd; GameModelManager *M; static const char *XBeeSerialConsole; static const int XBeeBaudRate; }; } // anonymous namespace const char *XBeeSyncServer::XBeeSerialConsole = "/dev/ttyAMA0"; const int XBeeSyncServer::XBeeBaudRate = 9600; const char *XBeeSyncClient::XBeeSerialConsole = "/dev/ttyAMA0"; const int XBeeSyncClient::XBeeBaudRate = 9600; XBeeSyncServer::XBeeSyncServer() : fd(0), M(nullptr) { } XBeeSyncServer::~XBeeSyncServer() { } void XBeeSyncServer::Init() { const char *portname = "/dev/ttyAMA0"; fd = open (portname, O_RDWR | O_NOCTTY | O_SYNC); if (fd < 0) { printf("error %d opening %s: %s", errno, portname, strerror (errno)); return; } set_interface_attribs(fd, B9600, 0); // set speed to 9600 bps, 8n1 (no parity) set_blocking(fd, 0); // set no blocking } void XBeeSyncServer::modelChanged(GameModel Model) { std::string Message = Model.serialize(); write(fd, Message.c_str(), Message.size()); } void XBeeSyncServer::heartbeat() { modelChanged(M->getModel()); } XBeeSyncClient::XBeeSyncClient() : fd(0), M(nullptr) { } XBeeSyncClient::~XBeeSyncClient() { } void XBeeSyncClient::Init() { const char *portname = "/dev/ttyAMA0"; fd = open (portname, O_RDWR | O_NOCTTY | O_SYNC); if (fd < 0) { printf("error %d opening %s: %s", errno, portname, strerror (errno)); return; } set_interface_attribs(fd, B9600, 0); // set speed to 9600 bps, 8n1 (no parity) set_blocking(fd, 1); // set no blocking std::thread([this]() { std::queue<char> Queue; std::stringstream Msg; do { char buf[128]; memset(buf, 0, sizeof(buf)); int n = read(fd, buf, sizeof(buf)); //printf("read: [%s]\n", buf); for (int i = 0; i < n; ++i) Queue.push(buf[i]); while (!Queue.empty()) { char C = Queue.front(); Msg << C; Queue.pop(); if (C == 'E') { GameModel Model; if (GameModel::deSerialize(Msg.str(), Model)) { printf("failed to deserialize [%s]\n", Msg.str().c_str()); } else { //printf("updating model:\n"); receivedModel(Model); } Msg.str(""); Msg.clear(); } } usleep(100); } while (true); }).detach(); } void XBeeSyncClient::receivedModel(GameModel Model) { Model.setPrevStartTime(); M->setModel(Model); } #endif // UWHD_HAVE_LIBXBEE3 ModelSyncServer *CreateXBeeSyncServer() { #ifdef UWHD_HAVE_LIBXBEE3 return new XBeeSyncServer(); #else printf("warning: CreateXBeeSyncServer configured without UWHD_HAVE_LIBXBEE3\n"); return nullptr; #endif } ModelSync *CreateXBeeSyncClient() { #ifdef UWHD_HAVE_LIBXBEE3 return new XBeeSyncClient(); #else printf("warning: CreateXBeeSyncClient configured without UWHD_HAVE_LIBXBEE3\n"); return nullptr; #endif } <|endoftext|>
<commit_before>#include "Plater/Plate2D.hpp" // libslic3r includes #include "Geometry.hpp" #include "Point.hpp" #include "Log.hpp" #include "ClipperUtils.hpp" // wx includes #include <wx/colour.h> #include <wx/dcbuffer.h> namespace Slic3r { namespace GUI { Plate2D::Plate2D(wxWindow* parent, const wxSize& size, std::vector<PlaterObject>& _objects, std::shared_ptr<Model> _model, std::shared_ptr<Config> _config, std::shared_ptr<Settings> _settings) : wxPanel(parent, wxID_ANY, wxDefaultPosition, size, wxTAB_TRAVERSAL), objects(_objects), model(_model), config(_config), settings(_settings) { this->Bind(wxEVT_PAINT, [=](wxPaintEvent &e) { this->repaint(e); }); this->Bind(wxEVT_MOTION, [=](wxMouseEvent &e) { this->mouse_drag(e); }); this->Bind(wxEVT_LEFT_DOWN, [=](wxMouseEvent &e) { this->mouse_down(e); }); this->Bind(wxEVT_LEFT_UP, [=](wxMouseEvent &e) { this->mouse_up(e); }); this->Bind(wxEVT_LEFT_DCLICK, [=](wxMouseEvent &e) { this->mouse_dclick(e); }); if (user_drawn_background) { this->Bind(wxEVT_ERASE_BACKGROUND, [=](wxEraseEvent& e){ }); } this->Bind(wxEVT_SIZE, [=](wxSizeEvent &e) { this->update_bed_size(); this->Refresh(); }); // Bind the varying mouse events // Set the brushes set_colors(); this->SetBackgroundStyle(wxBG_STYLE_PAINT); } void Plate2D::repaint(wxPaintEvent& e) { // Need focus to catch keyboard events. this->SetFocus(); auto dc {new wxAutoBufferedPaintDC(this)}; const auto& size {wxSize(this->GetSize().GetWidth(), this->GetSize().GetHeight())}; if (this->user_drawn_background) { // On all systems the AutoBufferedPaintDC() achieves double buffering. // On MacOS the background is erased, on Windows the background is not erased // and on Linux/GTK the background is erased to gray color. // Fill DC with the background on Windows & Linux/GTK. const auto& brush_background {wxBrush(this->settings->color->BACKGROUND255(), wxBRUSHSTYLE_SOLID)}; const auto& pen_background {wxPen(this->settings->color->BACKGROUND255(), 1, wxPENSTYLE_SOLID)}; dc->SetPen(pen_background); dc->SetBrush(brush_background); const auto& rect {this->GetUpdateRegion().GetBox()}; dc->DrawRectangle(rect.GetLeft(), rect.GetTop(), rect.GetWidth(), rect.GetHeight()); } // Draw bed { dc->SetPen(this->print_center_pen); dc->SetBrush(this->bed_brush); auto tmp {scaled_points_to_pixel(this->bed_polygon, true)}; dc->DrawPolygon(this->bed_polygon.points.size(), tmp.data(), 0, 0); } // draw print center { if (this->objects.size() > 0 && settings->autocenter) { const auto center = this->unscaled_point_to_pixel(this->print_center); dc->SetPen(print_center_pen); dc->DrawLine(center.x, 0, center.x, size.y); dc->DrawLine(0, center.y, size.x, center.y); dc->SetTextForeground(wxColor(0,0,0)); dc->SetFont(wxFont(10, wxFONTFAMILY_ROMAN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL)); dc->DrawLabel(wxString::Format("X = %.0f", this->print_center.x), wxRect(0,0, center.x*2, this->GetSize().GetHeight()), wxALIGN_CENTER_HORIZONTAL | wxALIGN_BOTTOM); dc->DrawRotatedText(wxString::Format("Y = %.0f", this->print_center.y), 0, center.y + 15, 90); } } // draw text if plate is empty if (this->objects.size() == 0) { dc->SetTextForeground(settings->color->BED_OBJECTS()); dc->SetFont(wxFont(14, wxFONTFAMILY_ROMAN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL)); dc->DrawLabel(CANVAS_TEXT, wxRect(0,0, this->GetSize().GetWidth(), this->GetSize().GetHeight()), wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL); } else { // draw grid dc->SetPen(grid_pen); // Assumption: grid of lines is arranged // as adjacent pairs of wxPoints for (auto i = 0U; i < grid.size(); i+=2) { dc->DrawLine(grid[i], grid[i+1]); } } // Draw thumbnails dc->SetPen(dark_pen); this->clean_instance_thumbnails(); for (auto& obj : this->objects) { auto model_object {this->model->objects.at(obj.identifier)}; if (obj.thumbnail.expolygons.size() == 0) continue; // if there's no thumbnail move on for (size_t instance_idx = 0U; instance_idx < model_object->instances.size(); instance_idx++) { auto& instance {model_object->instances.at(instance_idx)}; if (obj.transformed_thumbnail.expolygons.size()) continue; auto thumbnail {obj.transformed_thumbnail}; // starts in unscaled model coords thumbnail.translate(Point::new_scale(instance->offset)); obj.instance_thumbnails.emplace_back(thumbnail); if (0) { // object is dragged dc->SetBrush(dragged_brush); } else if (0) { dc->SetBrush(instance_brush); } else if (0) { dc->SetBrush(selected_brush); } else { dc->SetBrush(objects_brush); } // porting notes: perl here seems to be making a single-item array of the // thumbnail set. // no idea why. It doesn't look necessary, so skip the outer layer // and draw the contained expolygons for (const auto& points : obj.instance_thumbnails.back().expolygons) { auto poly { this->scaled_points_to_pixel(Polygon(points), 1) }; dc->DrawPolygon(poly.size(), poly.data(), 0, 0); } } } e.Skip(); } void Plate2D::clean_instance_thumbnails() { for (auto& obj : this->objects) { obj.instance_thumbnails.clear(); } } void Plate2D::mouse_drag(wxMouseEvent& e) { const auto pos {e.GetPosition()}; const auto& point {this->point_to_model_units(e.GetPosition())}; if (e.Dragging()) { Slic3r::Log::info(LogChannel, L"Mouse dragging"); } else { auto cursor = wxSTANDARD_CURSOR; /* if (find_first_of(this->objects.begin(), this->objects.end(); [=](const PlaterObject& o) { return o.contour->contains_point(point);} ) == this->object.end()) { cursor = wxCursor(wxCURSOR_HAND); } */ this->SetCursor(*cursor); } } void Plate2D::mouse_down(wxMouseEvent& e) { } void Plate2D::mouse_up(wxMouseEvent& e) { } void Plate2D::mouse_dclick(wxMouseEvent& e) { } void Plate2D::set_colors() { this->SetBackgroundColour(settings->color->BACKGROUND255()); this->objects_brush.SetColour(settings->color->BED_OBJECTS()); this->objects_brush.SetStyle(wxBRUSHSTYLE_SOLID); this->instance_brush.SetColour(settings->color->BED_INSTANCE()); this->instance_brush.SetStyle(wxBRUSHSTYLE_SOLID); this->selected_brush.SetColour(settings->color->BED_SELECTED()); this->selected_brush.SetStyle(wxBRUSHSTYLE_SOLID); this->dragged_brush.SetColour(settings->color->BED_DRAGGED()); this->dragged_brush.SetStyle(wxBRUSHSTYLE_SOLID); this->bed_brush.SetColour(settings->color->BED_COLOR()); this->bed_brush.SetStyle(wxBRUSHSTYLE_SOLID); this->transparent_brush.SetColour(wxColour(0,0,0)); this->transparent_brush.SetStyle(wxBRUSHSTYLE_TRANSPARENT); this->grid_pen.SetColour(settings->color->BED_GRID()); this->grid_pen.SetWidth(1); this->grid_pen.SetStyle(wxPENSTYLE_SOLID); this->print_center_pen.SetColour(settings->color->BED_CENTER()); this->print_center_pen.SetWidth(1); this->print_center_pen.SetStyle(wxPENSTYLE_SOLID); this->clearance_pen.SetColour(settings->color->BED_CLEARANCE()); this->clearance_pen.SetWidth(1); this->clearance_pen.SetStyle(wxPENSTYLE_SOLID); this->skirt_pen.SetColour(settings->color->BED_SKIRT()); this->skirt_pen.SetWidth(1); this->skirt_pen.SetStyle(wxPENSTYLE_SOLID); this->dark_pen.SetColour(settings->color->BED_DARK()); this->dark_pen.SetWidth(1); this->dark_pen.SetStyle(wxPENSTYLE_SOLID); } void Plate2D::nudge_key(wxKeyEvent& e) { const auto key = e.GetKeyCode(); switch( key ) { case WXK_LEFT: this->nudge(MoveDirection::Left); case WXK_RIGHT: this->nudge(MoveDirection::Right); case WXK_DOWN: this->nudge(MoveDirection::Down); case WXK_UP: this->nudge(MoveDirection::Up); default: break; // do nothing } } void Plate2D::nudge(MoveDirection dir) { if (this->selected_instance < this->objects.size()) { auto i = 0U; for (auto& obj : this->objects) { if (obj.selected) { if (obj.selected_instance != -1) { } } i++; } } if (selected_instance >= this->objects.size()) { Slic3r::Log::warn(LogChannel, L"Nudge failed because there is no selected instance."); return; // Abort } } void Plate2D::update_bed_size() { const auto& canvas_size {this->GetSize()}; const auto& canvas_w {canvas_size.GetWidth()}; const auto& canvas_h {canvas_size.GetHeight()}; if (canvas_w == 0) return; // Abort early if we haven't drawn canvas yet. this->bed_polygon = Slic3r::Polygon(scale(dynamic_cast<ConfigOptionPoints*>(config->optptr("bed_shape"))->values)); const auto& polygon = bed_polygon; const auto& bb = bed_polygon.bounding_box(); const auto& size = bb.size(); this->scaling_factor = std::min(static_cast<double>(canvas_w) / unscale(size.x), static_cast<double>(canvas_h) / unscale(size.y)); this->bed_origin = wxPoint( canvas_w / 2.0 - (unscale(bb.max.x + bb.min.x)/2.0 * this->scaling_factor), canvas_h - (canvas_h / 2.0 - (unscale(bb.max.y + bb.min.y)/2.0 * this->scaling_factor)) ); const auto& center = bb.center(); this->print_center = wxPoint(unscale(center.x), unscale(center.y)); // Cache bed contours and grid { const auto& step { scale_(10.0) }; // want a 10mm step for the lines auto grid {Polylines()}; for (coord_t x = (bb.min.x - (bb.min.x % step) + step); x < bb.max.x; x += step) { grid.push_back(Polyline()); grid.back().append(Point(x, bb.min.y)); grid.back().append(Point(x, bb.max.y)); }; for (coord_t y = (bb.min.y - (bb.min.y % step) + step); y < bb.max.y; y += step) { grid.push_back(Polyline()); grid.back().append(Point(bb.min.x, y)); grid.back().append(Point(bb.max.x, y)); }; grid = intersection_pl(grid, polygon); for (auto& i : grid) { const auto& tmpline { this->scaled_points_to_pixel(i, 1) }; this->grid.insert(this->grid.end(), tmpline.begin(), tmpline.end()); } } } std::vector<wxPoint> Plate2D::scaled_points_to_pixel(const Slic3r::Polygon& poly, bool unscale) { return this->scaled_points_to_pixel(Polyline(poly), unscale); } std::vector<wxPoint> Plate2D::scaled_points_to_pixel(const Slic3r::Polyline& poly, bool _unscale) { std::vector<wxPoint> result; for (const auto& pt : poly.points) { const auto x {_unscale ? Slic3r::unscale(pt.x) : pt.x}; const auto y {_unscale ? Slic3r::unscale(pt.y) : pt.y}; result.push_back(wxPoint(x, y)); } return result; } wxPoint Plate2D::unscaled_point_to_pixel(const wxPoint& in) { const auto& canvas_height {this->GetSize().GetHeight()}; const auto& zero = this->bed_origin; return wxPoint(in.x * this->scaling_factor + zero.x, in.y * this->scaling_factor + (zero.y - canvas_height)); } } } // Namespace Slic3r::GUI <commit_msg>Pass bool when we mean bool, not int.<commit_after>#include "Plater/Plate2D.hpp" // libslic3r includes #include "Geometry.hpp" #include "Point.hpp" #include "Log.hpp" #include "ClipperUtils.hpp" // wx includes #include <wx/colour.h> #include <wx/dcbuffer.h> namespace Slic3r { namespace GUI { Plate2D::Plate2D(wxWindow* parent, const wxSize& size, std::vector<PlaterObject>& _objects, std::shared_ptr<Model> _model, std::shared_ptr<Config> _config, std::shared_ptr<Settings> _settings) : wxPanel(parent, wxID_ANY, wxDefaultPosition, size, wxTAB_TRAVERSAL), objects(_objects), model(_model), config(_config), settings(_settings) { this->Bind(wxEVT_PAINT, [=](wxPaintEvent &e) { this->repaint(e); }); this->Bind(wxEVT_MOTION, [=](wxMouseEvent &e) { this->mouse_drag(e); }); this->Bind(wxEVT_LEFT_DOWN, [=](wxMouseEvent &e) { this->mouse_down(e); }); this->Bind(wxEVT_LEFT_UP, [=](wxMouseEvent &e) { this->mouse_up(e); }); this->Bind(wxEVT_LEFT_DCLICK, [=](wxMouseEvent &e) { this->mouse_dclick(e); }); if (user_drawn_background) { this->Bind(wxEVT_ERASE_BACKGROUND, [=](wxEraseEvent& e){ }); } this->Bind(wxEVT_SIZE, [=](wxSizeEvent &e) { this->update_bed_size(); this->Refresh(); }); // Bind the varying mouse events // Set the brushes set_colors(); this->SetBackgroundStyle(wxBG_STYLE_PAINT); } void Plate2D::repaint(wxPaintEvent& e) { // Need focus to catch keyboard events. this->SetFocus(); auto dc {new wxAutoBufferedPaintDC(this)}; const auto& size {wxSize(this->GetSize().GetWidth(), this->GetSize().GetHeight())}; if (this->user_drawn_background) { // On all systems the AutoBufferedPaintDC() achieves double buffering. // On MacOS the background is erased, on Windows the background is not erased // and on Linux/GTK the background is erased to gray color. // Fill DC with the background on Windows & Linux/GTK. const auto& brush_background {wxBrush(this->settings->color->BACKGROUND255(), wxBRUSHSTYLE_SOLID)}; const auto& pen_background {wxPen(this->settings->color->BACKGROUND255(), 1, wxPENSTYLE_SOLID)}; dc->SetPen(pen_background); dc->SetBrush(brush_background); const auto& rect {this->GetUpdateRegion().GetBox()}; dc->DrawRectangle(rect.GetLeft(), rect.GetTop(), rect.GetWidth(), rect.GetHeight()); } // Draw bed { dc->SetPen(this->print_center_pen); dc->SetBrush(this->bed_brush); auto tmp {scaled_points_to_pixel(this->bed_polygon, true)}; dc->DrawPolygon(this->bed_polygon.points.size(), tmp.data(), 0, 0); } // draw print center { if (this->objects.size() > 0 && settings->autocenter) { const auto center = this->unscaled_point_to_pixel(this->print_center); dc->SetPen(print_center_pen); dc->DrawLine(center.x, 0, center.x, size.y); dc->DrawLine(0, center.y, size.x, center.y); dc->SetTextForeground(wxColor(0,0,0)); dc->SetFont(wxFont(10, wxFONTFAMILY_ROMAN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL)); dc->DrawLabel(wxString::Format("X = %.0f", this->print_center.x), wxRect(0,0, center.x*2, this->GetSize().GetHeight()), wxALIGN_CENTER_HORIZONTAL | wxALIGN_BOTTOM); dc->DrawRotatedText(wxString::Format("Y = %.0f", this->print_center.y), 0, center.y + 15, 90); } } // draw text if plate is empty if (this->objects.size() == 0) { dc->SetTextForeground(settings->color->BED_OBJECTS()); dc->SetFont(wxFont(14, wxFONTFAMILY_ROMAN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL)); dc->DrawLabel(CANVAS_TEXT, wxRect(0,0, this->GetSize().GetWidth(), this->GetSize().GetHeight()), wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL); } else { // draw grid dc->SetPen(grid_pen); // Assumption: grid of lines is arranged // as adjacent pairs of wxPoints for (auto i = 0U; i < grid.size(); i+=2) { dc->DrawLine(grid[i], grid[i+1]); } } // Draw thumbnails dc->SetPen(dark_pen); this->clean_instance_thumbnails(); for (auto& obj : this->objects) { auto model_object {this->model->objects.at(obj.identifier)}; if (obj.thumbnail.expolygons.size() == 0) continue; // if there's no thumbnail move on for (size_t instance_idx = 0U; instance_idx < model_object->instances.size(); instance_idx++) { auto& instance {model_object->instances.at(instance_idx)}; if (obj.transformed_thumbnail.expolygons.size()) continue; auto thumbnail {obj.transformed_thumbnail}; // starts in unscaled model coords thumbnail.translate(Point::new_scale(instance->offset)); obj.instance_thumbnails.emplace_back(thumbnail); if (0) { // object is dragged dc->SetBrush(dragged_brush); } else if (0) { dc->SetBrush(instance_brush); } else if (0) { dc->SetBrush(selected_brush); } else { dc->SetBrush(objects_brush); } // porting notes: perl here seems to be making a single-item array of the // thumbnail set. // no idea why. It doesn't look necessary, so skip the outer layer // and draw the contained expolygons for (const auto& points : obj.instance_thumbnails.back().expolygons) { auto poly { this->scaled_points_to_pixel(Polygon(points), true) }; dc->DrawPolygon(poly.size(), poly.data(), 0, 0); } } } e.Skip(); } void Plate2D::clean_instance_thumbnails() { for (auto& obj : this->objects) { obj.instance_thumbnails.clear(); } } void Plate2D::mouse_drag(wxMouseEvent& e) { const auto pos {e.GetPosition()}; const auto& point {this->point_to_model_units(e.GetPosition())}; if (e.Dragging()) { Slic3r::Log::info(LogChannel, L"Mouse dragging"); } else { auto cursor = wxSTANDARD_CURSOR; /* if (find_first_of(this->objects.begin(), this->objects.end(); [=](const PlaterObject& o) { return o.contour->contains_point(point);} ) == this->object.end()) { cursor = wxCursor(wxCURSOR_HAND); } */ this->SetCursor(*cursor); } } void Plate2D::mouse_down(wxMouseEvent& e) { } void Plate2D::mouse_up(wxMouseEvent& e) { } void Plate2D::mouse_dclick(wxMouseEvent& e) { } void Plate2D::set_colors() { this->SetBackgroundColour(settings->color->BACKGROUND255()); this->objects_brush.SetColour(settings->color->BED_OBJECTS()); this->objects_brush.SetStyle(wxBRUSHSTYLE_SOLID); this->instance_brush.SetColour(settings->color->BED_INSTANCE()); this->instance_brush.SetStyle(wxBRUSHSTYLE_SOLID); this->selected_brush.SetColour(settings->color->BED_SELECTED()); this->selected_brush.SetStyle(wxBRUSHSTYLE_SOLID); this->dragged_brush.SetColour(settings->color->BED_DRAGGED()); this->dragged_brush.SetStyle(wxBRUSHSTYLE_SOLID); this->bed_brush.SetColour(settings->color->BED_COLOR()); this->bed_brush.SetStyle(wxBRUSHSTYLE_SOLID); this->transparent_brush.SetColour(wxColour(0,0,0)); this->transparent_brush.SetStyle(wxBRUSHSTYLE_TRANSPARENT); this->grid_pen.SetColour(settings->color->BED_GRID()); this->grid_pen.SetWidth(1); this->grid_pen.SetStyle(wxPENSTYLE_SOLID); this->print_center_pen.SetColour(settings->color->BED_CENTER()); this->print_center_pen.SetWidth(1); this->print_center_pen.SetStyle(wxPENSTYLE_SOLID); this->clearance_pen.SetColour(settings->color->BED_CLEARANCE()); this->clearance_pen.SetWidth(1); this->clearance_pen.SetStyle(wxPENSTYLE_SOLID); this->skirt_pen.SetColour(settings->color->BED_SKIRT()); this->skirt_pen.SetWidth(1); this->skirt_pen.SetStyle(wxPENSTYLE_SOLID); this->dark_pen.SetColour(settings->color->BED_DARK()); this->dark_pen.SetWidth(1); this->dark_pen.SetStyle(wxPENSTYLE_SOLID); } void Plate2D::nudge_key(wxKeyEvent& e) { const auto key = e.GetKeyCode(); switch( key ) { case WXK_LEFT: this->nudge(MoveDirection::Left); case WXK_RIGHT: this->nudge(MoveDirection::Right); case WXK_DOWN: this->nudge(MoveDirection::Down); case WXK_UP: this->nudge(MoveDirection::Up); default: break; // do nothing } } void Plate2D::nudge(MoveDirection dir) { if (this->selected_instance < this->objects.size()) { auto i = 0U; for (auto& obj : this->objects) { if (obj.selected) { if (obj.selected_instance != -1) { } } i++; } } if (selected_instance >= this->objects.size()) { Slic3r::Log::warn(LogChannel, L"Nudge failed because there is no selected instance."); return; // Abort } } void Plate2D::update_bed_size() { const auto& canvas_size {this->GetSize()}; const auto& canvas_w {canvas_size.GetWidth()}; const auto& canvas_h {canvas_size.GetHeight()}; if (canvas_w == 0) return; // Abort early if we haven't drawn canvas yet. this->bed_polygon = Slic3r::Polygon(scale(dynamic_cast<ConfigOptionPoints*>(config->optptr("bed_shape"))->values)); const auto& polygon = bed_polygon; const auto& bb = bed_polygon.bounding_box(); const auto& size = bb.size(); this->scaling_factor = std::min(static_cast<double>(canvas_w) / unscale(size.x), static_cast<double>(canvas_h) / unscale(size.y)); this->bed_origin = wxPoint( canvas_w / 2.0 - (unscale(bb.max.x + bb.min.x)/2.0 * this->scaling_factor), canvas_h - (canvas_h / 2.0 - (unscale(bb.max.y + bb.min.y)/2.0 * this->scaling_factor)) ); const auto& center = bb.center(); this->print_center = wxPoint(unscale(center.x), unscale(center.y)); // Cache bed contours and grid { const auto& step { scale_(10.0) }; // want a 10mm step for the lines auto grid {Polylines()}; for (coord_t x = (bb.min.x - (bb.min.x % step) + step); x < bb.max.x; x += step) { grid.push_back(Polyline()); grid.back().append(Point(x, bb.min.y)); grid.back().append(Point(x, bb.max.y)); }; for (coord_t y = (bb.min.y - (bb.min.y % step) + step); y < bb.max.y; y += step) { grid.push_back(Polyline()); grid.back().append(Point(bb.min.x, y)); grid.back().append(Point(bb.max.x, y)); }; grid = intersection_pl(grid, polygon); for (auto& i : grid) { const auto& tmpline { this->scaled_points_to_pixel(i, 1) }; this->grid.insert(this->grid.end(), tmpline.begin(), tmpline.end()); } } } std::vector<wxPoint> Plate2D::scaled_points_to_pixel(const Slic3r::Polygon& poly, bool unscale) { return this->scaled_points_to_pixel(Polyline(poly), unscale); } std::vector<wxPoint> Plate2D::scaled_points_to_pixel(const Slic3r::Polyline& poly, bool _unscale) { std::vector<wxPoint> result; for (const auto& pt : poly.points) { const auto x {_unscale ? Slic3r::unscale(pt.x) : pt.x}; const auto y {_unscale ? Slic3r::unscale(pt.y) : pt.y}; result.push_back(wxPoint(x, y)); } return result; } wxPoint Plate2D::unscaled_point_to_pixel(const wxPoint& in) { const auto& canvas_height {this->GetSize().GetHeight()}; const auto& zero = this->bed_origin; return wxPoint(in.x * this->scaling_factor + zero.x, in.y * this->scaling_factor + (zero.y - canvas_height)); } } } // Namespace Slic3r::GUI <|endoftext|>
<commit_before>#include "Plater/Plate2D.hpp" // libslic3r includes #include "Geometry.hpp" #include "Log.hpp" // wx includes #include <wx/colour.h> #include <wx/dcbuffer.h> namespace Slic3r { namespace GUI { Plate2D::Plate2D(wxWindow* parent, const wxSize& size, std::vector<Plater2DObject>& _objects, std::shared_ptr<Model> _model, std::shared_ptr<Config> _config, std::shared_ptr<Settings> _settings) : wxPanel(parent, wxID_ANY, wxDefaultPosition, size, wxTAB_TRAVERSAL), objects(_objects), model(_model), config(_config), settings(_settings) { this->Bind(wxEVT_PAINT, [=](wxPaintEvent &e) { this->repaint(e); }); this->Bind(wxEVT_MOTION, [=](wxMouseEvent &e) { this->mouse_drag(e); }); if (user_drawn_background) { this->Bind(wxEVT_ERASE_BACKGROUND, [=](wxEraseEvent& e){ }); } this->Bind(wxEVT_SIZE, [=](wxSizeEvent &e) { this->update_bed_size(); this->Refresh(); }); // Bind the varying mouse events // Set the brushes set_colors(); } void Plate2D::repaint(wxPaintEvent& e) { // Need focus to catch keyboard events. this->SetFocus(); auto dc {new wxAutoBufferedPaintDC(this)}; const auto& size = this->GetSize(); if (this->user_drawn_background) { // On all systems the AutoBufferedPaintDC() achieves double buffering. // On MacOS the background is erased, on Windows the background is not erased // and on Linux/GTK the background is erased to gray color. // Fill DC with the background on Windows & Linux/GTK. const auto& brush_background {wxBrush(this->settings->color->BACKGROUND255(), wxBRUSHSTYLE_SOLID)}; const auto& pen_background {wxPen(this->settings->color->BACKGROUND255(), 1, wxPENSTYLE_SOLID)}; dc->SetPen(pen_background); dc->SetBrush(brush_background); const auto& rect {this->GetUpdateRegion().GetBox()}; dc->DrawRectangle(rect.GetLeft(), rect.GetTop(), rect.GetWidth(), rect.GetHeight()); } // Draw bed { dc->SetPen(this->print_center_pen); dc->SetBrush(this->bed_brush); dc->DrawPolygon(scaled_points_to_pixel(this->bed_polygon, true), 0, 0); } } void Plate2D::mouse_drag(wxMouseEvent& e) { if (e.Dragging()) { Slic3r::Log::info(LogChannel, L"Mouse dragging"); } else { Slic3r::Log::info(LogChannel, L"Mouse moving"); } } void Plate2D::set_colors() { this->SetBackgroundColour(settings->color->BACKGROUND255()); this->objects_brush.SetColour(settings->color->BED_OBJECTS()); this->objects_brush.SetStyle(wxBRUSHSTYLE_SOLID); this->instance_brush.SetColour(settings->color->BED_INSTANCE()); this->instance_brush.SetStyle(wxBRUSHSTYLE_SOLID); this->selected_brush.SetColour(settings->color->BED_SELECTED()); this->selected_brush.SetStyle(wxBRUSHSTYLE_SOLID); this->dragged_brush.SetColour(settings->color->BED_DRAGGED()); this->dragged_brush.SetStyle(wxBRUSHSTYLE_SOLID); this->bed_brush.SetColour(settings->color->BED_COLOR()); this->bed_brush.SetStyle(wxBRUSHSTYLE_SOLID); this->transparent_brush.SetColour(wxColour(0,0,0)); this->transparent_brush.SetStyle(wxBRUSHSTYLE_TRANSPARENT); this->grid_pen.SetColour(settings->color->BED_GRID()); this->grid_pen.SetWidth(1); this->grid_pen.SetStyle(wxPENSTYLE_SOLID); this->print_center_pen.SetColour(settings->color->BED_CENTER()); this->print_center_pen.SetWidth(1); this->print_center_pen.SetStyle(wxPENSTYLE_SOLID); this->clearance_pen.SetColour(settings->color->BED_CLEARANCE()); this->clearance_pen.SetWidth(1); this->clearance_pen.SetStyle(wxPENSTYLE_SOLID); this->skirt_pen.SetColour(settings->color->BED_SKIRT()); this->skirt_pen.SetWidth(1); this->skirt_pen.SetStyle(wxPENSTYLE_SOLID); this->dark_pen.SetColour(settings->color->BED_DARK()); this->dark_pen.SetWidth(1); this->dark_pen.SetStyle(wxPENSTYLE_SOLID); } void Plate2D::nudge_key(wxKeyEvent& e) { const auto key = e.GetKeyCode(); switch( key ) { case WXK_LEFT: this->nudge(MoveDirection::Left); case WXK_RIGHT: this->nudge(MoveDirection::Right); case WXK_DOWN: this->nudge(MoveDirection::Down); case WXK_UP: this->nudge(MoveDirection::Up); default: break; // do nothing } } void Plate2D::nudge(MoveDirection dir) { if (this->selected_instance < this->objects.size()) { auto i = 0U; for (auto& obj : this->objects) { if (obj.selected()) { if (obj.selected_instance != -1) { } } i++; } } if (selected_instance >= this->objects.size()) { Slic3r::Log::warn(LogChannel, L"Nudge failed because there is no selected instance."); return; // Abort } } void Plate2D::update_bed_size() { const auto& canvas_size {this->GetSize()}; const auto& canvas_w {canvas_size.GetWidth()}; const auto& canvas_h {canvas_size.GetHeight()}; if (canvas_w == 0) return; // Abort early if we haven't drawn canvas yet. this->bed_polygon = Slic3r::Polygon(); const auto& polygon = bed_polygon; const auto& bb = bed_polygon.bounding_box(); const auto& size = bb.size(); this->scaling_factor = std::min(static_cast<double>(canvas_w) / unscale(size.x), static_cast<double>(canvas_h) / unscale(size.y)); assert(this->scaling_factor != 0); std::vector<wxPoint> Plate2D::scaled_points_to_pixel(const Slic3r::Polygon& poly, bool unscale) { return this->scaled_points_to_pixel(Polyline(poly), unscale); } std::vector<wxPoint> Plate2D::scaled_points_to_pixel(const Slic3r::Polyline& poly, bool unscale) { std::vector<wxPoint> result; for (const auto& pt : poly.points) { const auto tmp {wxPoint(pt.x, pt.y)}; result.push_back( (unscale ? unscaled_point_to_pixel(tmp) : tmp) ); } return result; } } } // Namespace Slic3r::GUI <commit_msg>Set BackgroundStyle because wxWidgets wants us to.<commit_after>#include "Plater/Plate2D.hpp" // libslic3r includes #include "Geometry.hpp" #include "Log.hpp" // wx includes #include <wx/colour.h> #include <wx/dcbuffer.h> namespace Slic3r { namespace GUI { Plate2D::Plate2D(wxWindow* parent, const wxSize& size, std::vector<Plater2DObject>& _objects, std::shared_ptr<Model> _model, std::shared_ptr<Config> _config, std::shared_ptr<Settings> _settings) : wxPanel(parent, wxID_ANY, wxDefaultPosition, size, wxTAB_TRAVERSAL), objects(_objects), model(_model), config(_config), settings(_settings) { this->Bind(wxEVT_PAINT, [=](wxPaintEvent &e) { this->repaint(e); }); this->Bind(wxEVT_MOTION, [=](wxMouseEvent &e) { this->mouse_drag(e); }); if (user_drawn_background) { this->Bind(wxEVT_ERASE_BACKGROUND, [=](wxEraseEvent& e){ }); } this->Bind(wxEVT_SIZE, [=](wxSizeEvent &e) { this->update_bed_size(); this->Refresh(); }); // Bind the varying mouse events // Set the brushes set_colors(); this->SetBackgroundStyle(wxBG_STYLE_PAINT); } void Plate2D::repaint(wxPaintEvent& e) { // Need focus to catch keyboard events. this->SetFocus(); auto dc {new wxAutoBufferedPaintDC(this)}; const auto& size = this->GetSize(); if (this->user_drawn_background) { // On all systems the AutoBufferedPaintDC() achieves double buffering. // On MacOS the background is erased, on Windows the background is not erased // and on Linux/GTK the background is erased to gray color. // Fill DC with the background on Windows & Linux/GTK. const auto& brush_background {wxBrush(this->settings->color->BACKGROUND255(), wxBRUSHSTYLE_SOLID)}; const auto& pen_background {wxPen(this->settings->color->BACKGROUND255(), 1, wxPENSTYLE_SOLID)}; dc->SetPen(pen_background); dc->SetBrush(brush_background); const auto& rect {this->GetUpdateRegion().GetBox()}; dc->DrawRectangle(rect.GetLeft(), rect.GetTop(), rect.GetWidth(), rect.GetHeight()); } // Draw bed { dc->SetPen(this->print_center_pen); dc->SetBrush(this->bed_brush); dc->DrawPolygon(scaled_points_to_pixel(this->bed_polygon, true), 0, 0); } } void Plate2D::mouse_drag(wxMouseEvent& e) { if (e.Dragging()) { Slic3r::Log::info(LogChannel, L"Mouse dragging"); } else { Slic3r::Log::info(LogChannel, L"Mouse moving"); } } void Plate2D::set_colors() { this->SetBackgroundColour(settings->color->BACKGROUND255()); this->objects_brush.SetColour(settings->color->BED_OBJECTS()); this->objects_brush.SetStyle(wxBRUSHSTYLE_SOLID); this->instance_brush.SetColour(settings->color->BED_INSTANCE()); this->instance_brush.SetStyle(wxBRUSHSTYLE_SOLID); this->selected_brush.SetColour(settings->color->BED_SELECTED()); this->selected_brush.SetStyle(wxBRUSHSTYLE_SOLID); this->dragged_brush.SetColour(settings->color->BED_DRAGGED()); this->dragged_brush.SetStyle(wxBRUSHSTYLE_SOLID); this->bed_brush.SetColour(settings->color->BED_COLOR()); this->bed_brush.SetStyle(wxBRUSHSTYLE_SOLID); this->transparent_brush.SetColour(wxColour(0,0,0)); this->transparent_brush.SetStyle(wxBRUSHSTYLE_TRANSPARENT); this->grid_pen.SetColour(settings->color->BED_GRID()); this->grid_pen.SetWidth(1); this->grid_pen.SetStyle(wxPENSTYLE_SOLID); this->print_center_pen.SetColour(settings->color->BED_CENTER()); this->print_center_pen.SetWidth(1); this->print_center_pen.SetStyle(wxPENSTYLE_SOLID); this->clearance_pen.SetColour(settings->color->BED_CLEARANCE()); this->clearance_pen.SetWidth(1); this->clearance_pen.SetStyle(wxPENSTYLE_SOLID); this->skirt_pen.SetColour(settings->color->BED_SKIRT()); this->skirt_pen.SetWidth(1); this->skirt_pen.SetStyle(wxPENSTYLE_SOLID); this->dark_pen.SetColour(settings->color->BED_DARK()); this->dark_pen.SetWidth(1); this->dark_pen.SetStyle(wxPENSTYLE_SOLID); } void Plate2D::nudge_key(wxKeyEvent& e) { const auto key = e.GetKeyCode(); switch( key ) { case WXK_LEFT: this->nudge(MoveDirection::Left); case WXK_RIGHT: this->nudge(MoveDirection::Right); case WXK_DOWN: this->nudge(MoveDirection::Down); case WXK_UP: this->nudge(MoveDirection::Up); default: break; // do nothing } } void Plate2D::nudge(MoveDirection dir) { if (this->selected_instance < this->objects.size()) { auto i = 0U; for (auto& obj : this->objects) { if (obj.selected()) { if (obj.selected_instance != -1) { } } i++; } } if (selected_instance >= this->objects.size()) { Slic3r::Log::warn(LogChannel, L"Nudge failed because there is no selected instance."); return; // Abort } } void Plate2D::update_bed_size() { const auto& canvas_size {this->GetSize()}; const auto& canvas_w {canvas_size.GetWidth()}; const auto& canvas_h {canvas_size.GetHeight()}; if (canvas_w == 0) return; // Abort early if we haven't drawn canvas yet. this->bed_polygon = Slic3r::Polygon(); const auto& polygon = bed_polygon; const auto& bb = bed_polygon.bounding_box(); const auto& size = bb.size(); this->scaling_factor = std::min(static_cast<double>(canvas_w) / unscale(size.x), static_cast<double>(canvas_h) / unscale(size.y)); assert(this->scaling_factor != 0); std::vector<wxPoint> Plate2D::scaled_points_to_pixel(const Slic3r::Polygon& poly, bool unscale) { return this->scaled_points_to_pixel(Polyline(poly), unscale); } std::vector<wxPoint> Plate2D::scaled_points_to_pixel(const Slic3r::Polyline& poly, bool unscale) { std::vector<wxPoint> result; for (const auto& pt : poly.points) { const auto tmp {wxPoint(pt.x, pt.y)}; result.push_back( (unscale ? unscaled_point_to_pixel(tmp) : tmp) ); } return result; } } } // Namespace Slic3r::GUI <|endoftext|>
<commit_before>/* * Forces_PS.cpp * * Created on: Oct 6, 2016 * Author: isivkov */ #include "Forces_PS.h" //#include "../Beta_gradient/Beta_projectors_gradient.h" #include "../k_set.h" namespace sirius { //--------------------------------------------------------------- //--------------------------------------------------------------- mdarray<double,2> Forces_PS::calc_local_forces() const { // get main arrays const Periodic_function<double>* valence_rho = density_.rho(); const mdarray<double, 2>& vloc_radial_integrals = potential_.get_vloc_radial_integrals(); // other Unit_cell &unit_cell = ctx_.unit_cell(); splindex<block> spl_ngv(valence_rho->gvec().num_gvec(), ctx_.comm().size(), ctx_.comm().rank()); //mdarray<double_complex, 2> vloc_G_comp(unit_cell.num_atoms(), spl_ngv.local_size() ); mdarray<double,2> forces(3, unit_cell.num_atoms()); forces.zero(); double fact = valence_rho->gvec().reduced() ? 2.0 : 1.0 ; // here the calculations are in lattice vectors space #pragma omp parallel for for (int igloc = 0; igloc < spl_ngv.local_size(); igloc++) { int ig = spl_ngv[igloc]; int igs = valence_rho->gvec().shell(ig); // fractional form for calculation of scalar product with atomic position // since atomic positions are stored in fractional coords vector3d<int> gvec = valence_rho->gvec().gvec(ig); // cartesian form for getting cartesian force components vector3d<double> gvec_cart = valence_rho->gvec().gvec_cart(ig); // store conj(rho_G) * 4 * pi double_complex g_dependent_prefactor = fact * std::conj( valence_rho->f_pw_local(igloc) ) * fourpi; for (int ia = 0; ia < unit_cell.num_atoms(); ia++) { Atom &atom = unit_cell.atom(ia); int iat = atom.type_id(); // scalar part of a force without multipying by G-vector double_complex z = vloc_radial_integrals(iat, igs) * g_dependent_prefactor * std::exp(double_complex(0.0, - twopi * (gvec * atom.position()))); // get force components multiplying by cartesian G-vector ( -image part goes from formula) #pragma omp atomic forces(0, ia) += - (gvec_cart[0] * z).imag(); #pragma omp atomic forces(1, ia) += - (gvec_cart[1] * z).imag(); #pragma omp atomic forces(2, ia) += - (gvec_cart[2] * z).imag(); } } ctx_.comm().allreduce(&forces(0,0),forces.size()); return std::move(forces); } //--------------------------------------------------------------- //--------------------------------------------------------------- mdarray<double,2> Forces_PS::calc_ultrasoft_forces() const { // get main arrays const mdarray<double_complex, 4> &density_matrix = density_.density_matrix(); const Periodic_function<double> *veff_full = potential_.effective_potential(); //Periodic_function<double> **magnetization = potential_.effective_magnetic_field(); // other Unit_cell &unit_cell = ctx_.unit_cell(); splindex<block> spl_ngv(veff_full->gvec().num_gvec(), ctx_.comm().size(), ctx_.comm().rank()); mdarray<double,2> forces(3, unit_cell.num_atoms()); forces.zero(); double reduce_g_fact = veff_full->gvec().reduced() ? 2.0 : 1.0 ; // here the calculations are in lattice vectors space #pragma omp parallel for for (int igloc = 0; igloc < spl_ngv.local_size(); igloc++) { int ig = spl_ngv[igloc]; // fractional form for calculation of scalar product with atomic position // since atomic positions are stored in fractional coords vector3d<int> gvec = veff_full->gvec().gvec(ig); // cartesian form for getting cartesian force components vector3d<double> gvec_cart = veff_full->gvec().gvec_cart(ig); // store conjugate of g component of veff double_complex veff_of_g = reduce_g_fact * std::conj(veff_full->f_pw_local(ig)); // iterate over atoms for (int ia = 0; ia < unit_cell.num_atoms(); ia++) { Atom &atom = unit_cell.atom(ia); int iat = atom.type_id(); // scalar part of a force without multipying by G-vector and Qij double_complex g_atom_part = ctx_.unit_cell().omega() * veff_of_g * std::exp(double_complex(0.0, - twopi * (gvec * atom.position()))); const Augmentation_operator &aug_op = ctx_.augmentation_op(iat); // iterate over trangle matrix Qij for (int ib2 = 0; ib2 < atom.type().indexb().size(); ib2++) { for(int ib1 = 0; ib1 <= ib2; ib1++) { int iqij = (ib2 * (ib2 + 1)) / 2 + ib1; double diag_fact = ib1 == ib2 ? 1.0 : 2.0; // scalar part of force double_complex z = diag_fact * density_matrix(ib1,ib2,0,ia) * g_atom_part * double_complex( aug_op.q_pw( iqij , 2*igloc ), aug_op.q_pw( iqij , 2*igloc + 1 ) ); // get force components multiplying by cartesian G-vector ( -image part goes from formula) #pragma omp atomic forces(0, ia) += - (gvec_cart[0] * z).imag(); #pragma omp atomic forces(1, ia) += - (gvec_cart[1] * z).imag(); #pragma omp atomic forces(2, ia) += - (gvec_cart[2] * z).imag(); } } } } ctx_.comm().allreduce(&forces(0,0),forces.size()); return std::move(forces); } //--------------------------------------------------------------- //--------------------------------------------------------------- mdarray<double,2> Forces_PS::calc_nonlocal_forces(K_set& kset) const { Unit_cell &unit_cell = ctx_.unit_cell(); mdarray<double,2> forces(3, unit_cell.num_atoms()); Beta_projectors_gradient grad(&kset.k_point(0)->beta_projectors()); grad.calc_gradient(0); return std::move(forces); } } <commit_msg>forces fixed<commit_after>/* * Forces_PS.cpp * * Created on: Oct 6, 2016 * Author: isivkov */ #include "Forces_PS.h" //#include "../Beta_gradient/Beta_projectors_gradient.h" #include "../k_set.h" namespace sirius { //--------------------------------------------------------------- //--------------------------------------------------------------- mdarray<double,2> Forces_PS::calc_local_forces() const { // get main arrays const Periodic_function<double>* valence_rho = density_.rho(); const mdarray<double, 2>& vloc_radial_integrals = potential_.get_vloc_radial_integrals(); // other Unit_cell &unit_cell = ctx_.unit_cell(); splindex<block> spl_ngv(valence_rho->gvec().num_gvec(), ctx_.comm().size(), ctx_.comm().rank()); //mdarray<double_complex, 2> vloc_G_comp(unit_cell.num_atoms(), spl_ngv.local_size() ); mdarray<double,2> forces(3, unit_cell.num_atoms()); forces.zero(); double fact = valence_rho->gvec().reduced() ? 2.0 : 1.0 ; // here the calculations are in lattice vectors space #pragma omp parallel for for (int ia = 0; ia < unit_cell.num_atoms(); ia++) { Atom &atom = unit_cell.atom(ia); int iat = atom.type_id(); for (int igloc = 0; igloc < spl_ngv.local_size(); igloc++) { int ig = spl_ngv[igloc]; int igs = valence_rho->gvec().shell(ig); // fractional form for calculation of scalar product with atomic position // since atomic positions are stored in fractional coords vector3d<int> gvec = valence_rho->gvec().gvec(ig); // cartesian form for getting cartesian force components vector3d<double> gvec_cart = valence_rho->gvec().gvec_cart(ig); // store conj(rho_G) * 4 * pi double_complex g_dependent_prefactor = fact * std::conj( valence_rho->f_pw_local(igloc) ) * fourpi; // scalar part of a force without multipying by G-vector double_complex z = vloc_radial_integrals(iat, igs) * g_dependent_prefactor * std::exp(double_complex(0.0, - twopi * (gvec * atom.position()))); // get force components multiplying by cartesian G-vector ( -image part goes from formula) forces(0, ia) += - (gvec_cart[0] * z).imag(); forces(1, ia) += - (gvec_cart[1] * z).imag(); forces(2, ia) += - (gvec_cart[2] * z).imag(); } } ctx_.comm().allreduce(&forces(0,0),forces.size()); return std::move(forces); } //--------------------------------------------------------------- //--------------------------------------------------------------- mdarray<double,2> Forces_PS::calc_ultrasoft_forces() const { // get main arrays const mdarray<double_complex, 4> &density_matrix = density_.density_matrix(); const Periodic_function<double> *veff_full = potential_.effective_potential(); //Periodic_function<double> **magnetization = potential_.effective_magnetic_field(); // other Unit_cell &unit_cell = ctx_.unit_cell(); splindex<block> spl_ngv(veff_full->gvec().num_gvec(), ctx_.comm().size(), ctx_.comm().rank()); mdarray<double,2> forces(3, unit_cell.num_atoms()); forces.zero(); double reduce_g_fact = veff_full->gvec().reduced() ? 2.0 : 1.0 ; // iterate over atoms #pragma omp parallel for for (int ia = 0; ia < unit_cell.num_atoms(); ia++) { Atom &atom = unit_cell.atom(ia); int iat = atom.type_id(); for (int igloc = 0; igloc < spl_ngv.local_size(); igloc++) { int ig = spl_ngv[igloc]; // fractional form for calculation of scalar product with atomic position // since atomic positions are stored in fractional coords vector3d<int> gvec = veff_full->gvec().gvec(ig); // cartesian form for getting cartesian force components vector3d<double> gvec_cart = veff_full->gvec().gvec_cart(ig); // store conjugate of g component of veff double_complex veff_of_g = reduce_g_fact * std::conj(veff_full->f_pw_local(ig)); // scalar part of a force without multipying by G-vector and Qij double_complex g_atom_part = ctx_.unit_cell().omega() * veff_of_g * std::exp(double_complex(0.0, - twopi * (gvec * atom.position()))); const Augmentation_operator &aug_op = ctx_.augmentation_op(iat); // iterate over trangle matrix Qij for (int ib2 = 0; ib2 < atom.type().indexb().size(); ib2++) { for(int ib1 = 0; ib1 <= ib2; ib1++) { int iqij = (ib2 * (ib2 + 1)) / 2 + ib1; double diag_fact = ib1 == ib2 ? 1.0 : 2.0; // scalar part of force double_complex z = diag_fact * density_matrix(ib1,ib2,0,ia).real() * g_atom_part * double_complex( aug_op.q_pw( iqij , 2*igloc ), aug_op.q_pw( iqij , 2*igloc + 1 ) ); // get force components multiplying by cartesian G-vector ( -image part goes from formula) forces(0, ia) += - (gvec_cart[0] * z).imag(); forces(1, ia) += - (gvec_cart[1] * z).imag(); forces(2, ia) += - (gvec_cart[2] * z).imag(); } } } } ctx_.comm().allreduce(&forces(0,0),forces.size()); return std::move(forces); } //--------------------------------------------------------------- //--------------------------------------------------------------- mdarray<double,2> Forces_PS::calc_nonlocal_forces(K_set& kset) const { Unit_cell &unit_cell = ctx_.unit_cell(); mdarray<double,2> forces(3, unit_cell.num_atoms()); forces.zero(); return std::move(forces); } } <|endoftext|>
<commit_before>#include "scalyc.h" using namespace scaly; namespace scaly { extern __thread _Page* __CurrentPage; extern __thread _Task* __CurrentTask; } int main(int argc, char** argv) { // Allocate the root page for the main thread _Page* page = 0; posix_memalign((void**)&page, _pageSize, _pageSize * _maxStackPages); if (!page) return -1; new (page) _Page(); __CurrentPage = page; _Task* task = new(page) _Task(); __CurrentTask = task; // Collect the arguments into a string Vector _Vector<string>* arguments = &_Vector<string>::createUninitialized(__CurrentPage, argc - 1); for (int i = 1; i < argc; i++) *(*arguments)[i - 1] = new(__CurrentPage) string(argv[i]); // Call Scaly's top-level code int ret = scalyc::_main(arguments); // Only for monitoring, debugging and stuff __CurrentTask->dispose(); // Give back the return code of the top-level code return ret; }<commit_msg>removed main.cpp from scalyc<commit_after><|endoftext|>
<commit_before>// Copyright 2017-2019 Zuse Institute Berlin // // 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. #pragma once #include "connection.hpp" #include "converter.hpp" #include "exceptions.hpp" #include "json/json.h" #include <sys/time.h> // evil hack #include <boost/asio/io_service.hpp> #include <boost/asio/ip/tcp.hpp> #include <array> #include <iostream> #include <stdexcept> #include <string> namespace scalaris { /// represents a TCP connection to Scalaris to execute JSON-RPC requests class TCPConnection final : public Connection { boost::asio::io_service ioservice; boost::asio::ip::tcp::socket socket; bool hasToConnect = true; public: TCPConnection() = default; /** * creates a connection instance * @param _hostname the host name of the Scalaris instance * @param _link the pathURL for JSON-RPC * @param _port the TCP port of the Scalaris instance */ TCPConnection(const std::string& _hostname, const std::string& _link = "jsonrpc.yaws", unsigned _port = 8000); ~TCPConnection(); bool needsConnect() const { return hasToConnect; }; /// checks whether the TCP connection is alive bool isOpen() const; /// closes the TCP connection void close(); /// returns the server port of the TCP connection unsigned getPort() const; /// connects to the specified server /// it can also be used, if the connection failed void connect(); std::string toString() const { std::stringstream s; s << "http://" << hostname << ":" << port << "/" << link; return s.str(); }; private: virtual Json::Value exec_call(const std::string& methodname, Json::Value params, bool reconnect = true); Json::Value process_result(const Json::Value& value); }; } // namespace scalaris <commit_msg>cpp: tamper clang<commit_after>// Copyright 2017-2019 Zuse Institute Berlin // // 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. #pragma once #include "connection.hpp" #include "converter.hpp" #include "exceptions.hpp" #include "json/json.h" #include <sys/time.h> // evil hack #include <boost/asio/io_service.hpp> #include <boost/asio/ip/tcp.hpp> #include <array> #include <iostream> #include <stdexcept> #include <string> namespace scalaris { /// represents a TCP connection to Scalaris to execute JSON-RPC requests class TCPConnection final : public Connection { boost::asio::io_service ioservice; boost::asio::ip::tcp::socket socket; bool hasToConnect = true; public: /** * creates a connection instance * @param _hostname the host name of the Scalaris instance * @param _link the pathURL for JSON-RPC * @param _port the TCP port of the Scalaris instance */ TCPConnection(const std::string& _hostname, const std::string& _link = "jsonrpc.yaws", unsigned _port = 8000); ~TCPConnection(); bool needsConnect() const { return hasToConnect; }; /// checks whether the TCP connection is alive bool isOpen() const; /// closes the TCP connection void close(); /// returns the server port of the TCP connection unsigned getPort() const; /// connects to the specified server /// it can also be used, if the connection failed void connect(); std::string toString() const { std::stringstream s; s << "http://" << hostname << ":" << port << "/" << link; return s.str(); }; private: virtual Json::Value exec_call(const std::string& methodname, Json::Value params, bool reconnect = true); Json::Value process_result(const Json::Value& value); }; } // namespace scalaris <|endoftext|>
<commit_before>// // Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu> // Creation Date: Mon Aug 17 02:39:28 PDT 2015 // Last Modified: Mon Aug 17 02:39:32 PDT 2015 // Filename: HumdrumFileContent.cpp // URL: https://github.com/craigsapp/humlib/blob/master/src/HumdrumFileContent.cpp // Syntax: C++11; humlib // vim: syntax=cpp ts=3 noexpandtab nowrap // // Description: Used to add content analysis to HumdrumFileStructure class. // #include "HumdrumFileContent.h" #include "HumRegex.h" #include "Convert.h" using namespace std; namespace hum { // START_MERGE ////////////////////////////// // // HumdrumFileContent::HumdrumFileContent -- // HumdrumFileContent::HumdrumFileContent(void) : HumdrumFileStructure() { // do nothing } HumdrumFileContent::HumdrumFileContent(const string& filename) : HumdrumFileStructure() { read(filename); } HumdrumFileContent::HumdrumFileContent(istream& contents) : HumdrumFileStructure() { read(contents); } ////////////////////////////// // // HumdrumFileContent::~HumdrumFileContent -- // HumdrumFileContent::~HumdrumFileContent() { // do nothing } ////////////////////////////// // // HumdrumFileContent::analyzeRScale -- // bool HumdrumFileContent::analyzeRScale(void) { int active = 0; // number of tracks currently having an active rscale parameter HumdrumFileBase& infile = *this; vector<HumNum> rscales(infile.getMaxTrack() + 1, 1); HumRegex hre; for (int i=0; i<infile.getLineCount(); i++) { if (infile[i].isInterpretation()) { int fieldcount = infile[i].getFieldCount(); for (int j=0; j<fieldcount; j++) { HTp token = infile[i].token(j); if (token->compare(0, 8, "*rscale:") != 0) { continue; } if (!token->isKern()) { continue; } int track = token->getTrack(); HumNum value = 1; if (hre.search(*token, "\\*rscale:(\\d+)/(\\d+)")) { int top = hre.getMatchInt(1); int bot = hre.getMatchInt(2); value.setValue(top, bot); } else if (hre.search(*token, "\\*rscale:(\\d+)")) { int top = hre.getMatchInt(1); value.setValue(top, 1); } if (value == 1) { if (rscales[track] != 1) { rscales[track] = 1; active--; } } else { if (rscales[track] == 1) { active++; } rscales[track] = value; } } continue; } if (!active) { continue; } if (!infile[i].isData()) { continue; } int fieldcount = infile[i].getFieldCount(); for (int j=0; j<fieldcount; j++) { HTp token = infile.token(i, j); int track = token->getTrack(); if (rscales[track] == 1) { continue; } if (!token->isKern()) { continue; } if (token->isNull()) { continue; } int dots = token->getDots(); HumNum dur = token->getDurationNoDots(); dur *= rscales[track]; string vis = Convert::durationToRecip(dur); for (int k=0; k<dots; k++) { vis += '.'; } token->setValue("LO", "N", "vis", vis); } } return true; } ////////////////////////////// // // HumdrumFileContent::hasPickup -- Return false if there is no pickup measure. // Return the barline index number if there is a pickup measure. A pickup measure // is identified when the duration from the start of the file to the first // barline is not zero or equal to the duration of the starting time signature. // if there is not starting time signature, then there cannot be an identified // pickup measure. // int HumdrumFileContent::hasPickup(void) { HumdrumFileContent& infile = *this; int barline = -1; HTp tsig = NULL; for (int i=0; i<infile.getLineCount(); i++) { if (infile[i].isBarline()) { if (barline > 0) { // second barline found, so stop looking for time signature break; } barline = i; continue; } if (!infile[i].isInterpretation()) { continue; } if (tsig != NULL) { continue; } for (int j=0; j<infile[i].getFieldCount(); j++) { HTp token = infile.token(i, j); if (token->isTimeSignature()) { tsig = token; break; } } } if (tsig == NULL) { // no time signature so return 0 return 0; } if (barline < 0) { // no barlines in music return 0; } HumNum mdur = infile[barline].getDurationFromStart(); HumNum tdur = Convert::timeSigToDurationInQuarter(tsig); if (mdur == tdur) { return 0; } return barline; } // END_MERGE } // end namespace hum <commit_msg>Rscale analysis.<commit_after>// // Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu> // Creation Date: Mon Aug 17 02:39:28 PDT 2015 // Last Modified: Mon Aug 17 02:39:32 PDT 2015 // Filename: HumdrumFileContent.cpp // URL: https://github.com/craigsapp/humlib/blob/master/src/HumdrumFileContent.cpp // Syntax: C++11; humlib // vim: syntax=cpp ts=3 noexpandtab nowrap // // Description: Used to add content analysis to HumdrumFileStructure class. // #include "HumdrumFileContent.h" #include "HumRegex.h" #include "Convert.h" using namespace std; namespace hum { // START_MERGE ////////////////////////////// // // HumdrumFileContent::HumdrumFileContent -- // HumdrumFileContent::HumdrumFileContent(void) : HumdrumFileStructure() { // do nothing } HumdrumFileContent::HumdrumFileContent(const string& filename) : HumdrumFileStructure() { read(filename); } HumdrumFileContent::HumdrumFileContent(istream& contents) : HumdrumFileStructure() { read(contents); } ////////////////////////////// // // HumdrumFileContent::~HumdrumFileContent -- // HumdrumFileContent::~HumdrumFileContent() { // do nothing } ////////////////////////////// // // HumdrumFileContent::analyzeRScale -- // bool HumdrumFileContent::analyzeRScale(void) { int active = 0; // number of tracks currently having an active rscale parameter HumdrumFileBase& infile = *this; vector<HumNum> rscales(infile.getMaxTrack() + 1, 1); HumRegex hre; for (int i=0; i<infile.getLineCount(); i++) { if (infile[i].isInterpretation()) { int fieldcount = infile[i].getFieldCount(); for (int j=0; j<fieldcount; j++) { HTp token = infile[i].token(j); if (token->compare(0, 8, "*rscale:") != 0) { continue; } if (!token->isKern()) { continue; } int track = token->getTrack(); HumNum value = 1; if (hre.search(*token, "\\*rscale:(\\d+)/(\\d+)")) { int top = hre.getMatchInt(1); int bot = hre.getMatchInt(2); value.setValue(top, bot); } else if (hre.search(*token, "\\*rscale:(\\d+)")) { int top = hre.getMatchInt(1); value.setValue(top, 1); } if (value == 1) { if (rscales[track] != 1) { rscales[track] = 1; active--; } } else { if (rscales[track] == 1) { active++; } rscales[track] = value; } } continue; } if (!active) { continue; } if (!infile[i].isData()) { continue; } int fieldcount = infile[i].getFieldCount(); for (int j=0; j<fieldcount; j++) { HTp token = infile.token(i, j); int track = token->getTrack(); if (rscales[track] == 1) { continue; } if (!token->isKern()) { continue; } if (token->isNull()) { continue; } int dots = token->getDots(); HumNum dur = token->getDurationNoDots(); dur *= rscales[track]; string vis = Convert::durationToRecip(dur); for (int k=0; k<dots; k++) { vis += '.'; } token->setValue("LO", "N", "vis", vis); string rvalue = to_string(rscales[track].getNumerator()); rvalue += '/'; rvalue += to_string(rscales[track].getDenominator()); token->setValue("auto", "rscale", rvalue); } } return true; } ////////////////////////////// // // HumdrumFileContent::hasPickup -- Return false if there is no pickup measure. // Return the barline index number if there is a pickup measure. A pickup measure // is identified when the duration from the start of the file to the first // barline is not zero or equal to the duration of the starting time signature. // if there is not starting time signature, then there cannot be an identified // pickup measure. // int HumdrumFileContent::hasPickup(void) { HumdrumFileContent& infile = *this; int barline = -1; HTp tsig = NULL; for (int i=0; i<infile.getLineCount(); i++) { if (infile[i].isBarline()) { if (barline > 0) { // second barline found, so stop looking for time signature break; } barline = i; continue; } if (!infile[i].isInterpretation()) { continue; } if (tsig != NULL) { continue; } for (int j=0; j<infile[i].getFieldCount(); j++) { HTp token = infile.token(i, j); if (token->isTimeSignature()) { tsig = token; break; } } } if (tsig == NULL) { // no time signature so return 0 return 0; } if (barline < 0) { // no barlines in music return 0; } HumNum mdur = infile[barline].getDurationFromStart(); HumNum tdur = Convert::timeSigToDurationInQuarter(tsig); if (mdur == tdur) { return 0; } return barline; } // END_MERGE } // end namespace hum <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: lngprops.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: tl $ $Date: 2001-05-08 12:42:05 $ * * 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 _LINGUISTIC_LNGPROPS_HHX_ #define _LINGUISTIC_LNGPROPS_HHX_ #ifndef _SVTOOLS_LINGUPROPS_HXX_ #include <svtools/linguprops.hxx> #endif // WIDs for property names //!! Don't change values! They are used as the property handles in //!! the service description #define WID_IS_GERMAN_PRE_REFORM UPH_IS_GERMAN_PRE_REFORM #define WID_IS_USE_DICTIONARY_LIST UPH_IS_USE_DICTIONARY_LIST #define WID_IS_IGNORE_CONTROL_CHARACTERS UPH_IS_IGNORE_CONTROL_CHARACTERS #define WID_IS_SPELL_UPPER_CASE UPH_IS_SPELL_UPPER_CASE #define WID_IS_SPELL_WITH_DIGITS UPH_IS_SPELL_WITH_DIGITS #define WID_IS_SPELL_CAPITALIZATION UPH_IS_SPELL_CAPITALIZATION #define WID_HYPH_MIN_LEADING UPH_HYPH_MIN_LEADING #define WID_HYPH_MIN_TRAILING UPH_HYPH_MIN_TRAILING #define WID_HYPH_MIN_WORD_LENGTH UPH_HYPH_MIN_WORD_LENGTH #define WID_DEFAULT_LOCALE UPH_DEFAULT_LOCALE #define WID_IS_SPELL_AUTO UPH_IS_SPELL_AUTO #define WID_IS_SPELL_HIDE UPH_IS_SPELL_HIDE #define WID_IS_SPELL_IN_ALL_LANGUAGES UPH_IS_SPELL_IN_ALL_LANGUAGES #define WID_IS_SPELL_SPECIAL UPH_IS_SPELL_SPECIAL #define WID_IS_HYPH_AUTO UPH_IS_HYPH_AUTO #define WID_IS_HYPH_SPECIAL UPH_IS_HYPH_SPECIAL #define WID_IS_WRAP_REVERSE UPH_IS_WRAP_REVERSE #define WID_DEFAULT_LANGUAGE UPH_DEFAULT_LANGUAGE #define WID_DEFAULT_LOCALE_CJK UPH_DEFAULT_LOCALE_CJK #define WID_DEFAULT_LOCALE_CTL UPH_DEFAULT_LOCALE_CTL #endif <commit_msg>INTEGRATION: CWS tl04 (1.4.172); FILE MERGED 2004/11/11 10:41:08 tl 1.4.172.1: #118281# switch to Proximity linguistic<commit_after>/************************************************************************* * * $RCSfile: lngprops.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: kz $ $Date: 2004-11-27 13:19:32 $ * * 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 _LINGUISTIC_LNGPROPS_HHX_ #define _LINGUISTIC_LNGPROPS_HHX_ #ifndef _SVTOOLS_LINGUPROPS_HXX_ #include <svtools/linguprops.hxx> #endif // maximal number of suggestions to be returned in spelling context-menu // (may not include results added by looking up user dictionaries) #define UPN_MAX_NUMBER_OF_SUGGESTIONS "MaxNumberOfSuggestions" // WIDs for property names //!! Don't change values! They are used as the property handles in //!! the service description #define WID_IS_GERMAN_PRE_REFORM UPH_IS_GERMAN_PRE_REFORM #define WID_IS_USE_DICTIONARY_LIST UPH_IS_USE_DICTIONARY_LIST #define WID_IS_IGNORE_CONTROL_CHARACTERS UPH_IS_IGNORE_CONTROL_CHARACTERS #define WID_IS_SPELL_UPPER_CASE UPH_IS_SPELL_UPPER_CASE #define WID_IS_SPELL_WITH_DIGITS UPH_IS_SPELL_WITH_DIGITS #define WID_IS_SPELL_CAPITALIZATION UPH_IS_SPELL_CAPITALIZATION #define WID_HYPH_MIN_LEADING UPH_HYPH_MIN_LEADING #define WID_HYPH_MIN_TRAILING UPH_HYPH_MIN_TRAILING #define WID_HYPH_MIN_WORD_LENGTH UPH_HYPH_MIN_WORD_LENGTH #define WID_DEFAULT_LOCALE UPH_DEFAULT_LOCALE #define WID_IS_SPELL_AUTO UPH_IS_SPELL_AUTO #define WID_IS_SPELL_HIDE UPH_IS_SPELL_HIDE #define WID_IS_SPELL_IN_ALL_LANGUAGES UPH_IS_SPELL_IN_ALL_LANGUAGES #define WID_IS_SPELL_SPECIAL UPH_IS_SPELL_SPECIAL #define WID_IS_HYPH_AUTO UPH_IS_HYPH_AUTO #define WID_IS_HYPH_SPECIAL UPH_IS_HYPH_SPECIAL #define WID_IS_WRAP_REVERSE UPH_IS_WRAP_REVERSE #define WID_DEFAULT_LANGUAGE UPH_DEFAULT_LANGUAGE #define WID_DEFAULT_LOCALE_CJK UPH_DEFAULT_LOCALE_CJK #define WID_DEFAULT_LOCALE_CTL UPH_DEFAULT_LOCALE_CTL #endif <|endoftext|>
<commit_before>/* -*- c-basic-offset: 2 -*- */ /* Copyright(C) 2012 Kouhei Sutou <kou@clear-code.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <mrn_mysql.h> #include "mrn_multiple_column_key_codec.hpp" // for debug #define MRN_CLASS_NAME "mrn::MultipleColumnKeyCodec" #ifdef WORDS_BIGENDIAN #define mrn_byte_order_host_to_network(buf, key, size) \ { \ uint32 size_ = (uint32)(size); \ uint8 *buf_ = (uint8 *)(buf); \ uint8 *key_ = (uint8 *)(key); \ while (size_--) { *buf_++ = *key_++; } \ } #else /* WORDS_BIGENDIAN */ #define mrn_byte_order_host_to_network(buf, key, size) \ { \ uint32 size_ = (uint32)(size); \ uint8 *buf_ = (uint8 *)(buf); \ uint8 *key_ = (uint8 *)(key) + size_; \ while (size_--) { *buf_++ = *(--key_); } \ } #endif /* WORDS_BIGENDIAN */ namespace mrn { MultipleColumnKeyCodec::MultipleColumnKeyCodec(KEY *key_info) : key_info_(key_info) { } MultipleColumnKeyCodec::~MultipleColumnKeyCodec() { } int MultipleColumnKeyCodec::encode(const uchar *key, uint key_length, uchar *buffer, uint *encoded_length, bool decode) { MRN_DBUG_ENTER_METHOD(); int error = 0; const uchar *current_key = key; const uchar *key_end = key + key_length; uchar *current_buffer = buffer; int n_key_parts = key_info_->key_parts; DBUG_PRINT("info", ("mroonga: n_key_parts=%d", n_key_parts)); *encoded_length = 0; for (int i = 0; i < n_key_parts && current_key < key_end; i++) { KEY_PART_INFO *key_part = &(key_info_->key_part[i]); Field *field = key_part->field; DBUG_PRINT("info", ("mroonga: key_part->length=%u", key_part->length)); if (field->null_bit) { DBUG_PRINT("info", ("mroonga: field has null bit")); *current_buffer = *current_key; current_key += 1; current_buffer += 1; (*encoded_length)++; } DataType data_type = TYPE_UNKNOWN; uint data_size = 0; get_key_info(key_part, &data_type, &data_size); switch (data_type) { case TYPE_UNKNOWN: // TODO: This will not be happen. This is just for // suppressing warnings by gcc -O2. :< error = HA_ERR_UNSUPPORTED; break; case TYPE_LONG_LONG_NUMBER: { long long int long_long_value = 0; switch (data_size) { case 3: long_long_value = (long long int)sint3korr(current_key); break; case 8: long_long_value = (long long int)sint8korr(current_key); break; } if (decode) *((uint8 *)(&long_long_value)) ^= 0x80; mrn_byte_order_host_to_network(current_buffer, &long_long_value, data_size); if (!decode) *((uint8 *)(current_buffer)) ^= 0x80; } break; case TYPE_NUMBER: if (decode) { Field_num *number_field = (Field_num *)field; if (!number_field->unsigned_flag) { *((uint8 *)(current_key)) ^= 0x80; } } mrn_byte_order_host_to_network(current_buffer, current_key, data_size); if (!decode) { Field_num *number_field = (Field_num *)field; if (!number_field->unsigned_flag) { *((uint8 *)(current_buffer)) ^= 0x80; } } break; case TYPE_FLOAT: { float value; float4get(value, current_key); encode_float(value, data_size, current_buffer, decode); } break; case TYPE_DOUBLE: { double value; float8get(value, current_key); encode_double(value, data_size, current_buffer, decode); } break; case TYPE_BYTE_SEQUENCE: memcpy(current_buffer, current_key, data_size); break; case TYPE_BYTE_REVERSE: encode_reverse(current_key, data_size, current_buffer); break; case TYPE_BYTE_BLOB: if (decode) { memcpy(current_buffer, current_key + data_size, HA_KEY_BLOB_LENGTH); memcpy(current_buffer + HA_KEY_BLOB_LENGTH, current_key, data_size); } else { memcpy(current_buffer + data_size, current_key, HA_KEY_BLOB_LENGTH); memcpy(current_buffer, current_key + HA_KEY_BLOB_LENGTH, data_size); } data_size += HA_KEY_BLOB_LENGTH; break; } if (error) { break; } current_key += data_size; current_buffer += data_size; *encoded_length += data_size; } DBUG_RETURN(error); } uint MultipleColumnKeyCodec::size() { MRN_DBUG_ENTER_METHOD(); int n_key_parts = key_info_->key_parts; DBUG_PRINT("info", ("mroonga: n_key_parts=%d", n_key_parts)); uint total_size = 0; for (int i = 0; i < n_key_parts; ++i) { KEY_PART_INFO *key_part = &(key_info_->key_part[i]); Field *field = key_part->field; DBUG_PRINT("info", ("mroonga: key_part->length=%u", key_part->length)); if (field->null_bit) { DBUG_PRINT("info", ("mroonga: field has null bit")); ++total_size; } DataType data_type = TYPE_UNKNOWN; uint data_size = 0; get_key_info(key_part, &data_type, &data_size); total_size += data_size; if (data_type == TYPE_BYTE_BLOB) { total_size += HA_KEY_BLOB_LENGTH; } } DBUG_RETURN(total_size); } void MultipleColumnKeyCodec::get_key_info(KEY_PART_INFO *key_part, DataType *data_type, uint *data_size) { MRN_DBUG_ENTER_METHOD(); *data_type = TYPE_UNKNOWN; *data_size = 0; Field *field = key_part->field; switch (field->real_type()) { case MYSQL_TYPE_DECIMAL: DBUG_PRINT("info", ("mroonga: MYSQL_TYPE_DECIMAL")); *data_type = TYPE_BYTE_SEQUENCE; *data_size = key_part->length; break; case MYSQL_TYPE_TINY: case MYSQL_TYPE_YEAR: DBUG_PRINT("info", ("mroonga: MYSQL_TYPE_TINY")); *data_type = TYPE_NUMBER; *data_size = 1; break; case MYSQL_TYPE_SHORT: DBUG_PRINT("info", ("mroonga: MYSQL_TYPE_SHORT")); *data_type = TYPE_NUMBER; *data_size = 2; break; case MYSQL_TYPE_LONG: DBUG_PRINT("info", ("mroonga: MYSQL_TYPE_LONG")); *data_type = TYPE_NUMBER; *data_size = 4; break; case MYSQL_TYPE_FLOAT: DBUG_PRINT("info", ("mroonga: MYSQL_TYPE_FLOAT")); *data_type = TYPE_FLOAT; *data_size = 4; break; case MYSQL_TYPE_DOUBLE: DBUG_PRINT("info", ("mroonga: MYSQL_TYPE_DOUBLE")); *data_type = TYPE_DOUBLE; *data_size = 8; break; case MYSQL_TYPE_NULL: DBUG_PRINT("info", ("mroonga: MYSQL_TYPE_NULL")); *data_type = TYPE_NUMBER; *data_size = 1; break; case MYSQL_TYPE_TIMESTAMP: case MYSQL_TYPE_DATE: case MYSQL_TYPE_DATETIME: case MYSQL_TYPE_NEWDATE: DBUG_PRINT("info", ("mroonga: MYSQL_TYPE_DATETIME")); *data_type = TYPE_BYTE_REVERSE; *data_size = key_part->length; break; case MYSQL_TYPE_LONGLONG: DBUG_PRINT("info", ("mroonga: MYSQL_TYPE_LONGLONG")); *data_type = TYPE_NUMBER; *data_size = 8; break; case MYSQL_TYPE_INT24: DBUG_PRINT("info", ("mroonga: MYSQL_TYPE_INT24")); *data_type = TYPE_NUMBER; *data_size = 3; break; case MYSQL_TYPE_TIME: DBUG_PRINT("info", ("mroonga: MYSQL_TYPE_TIME")); *data_type = TYPE_LONG_LONG_NUMBER; *data_size = 3; break; case MYSQL_TYPE_VARCHAR: DBUG_PRINT("info", ("mroonga: MYSQL_TYPE_VARCHAR")); *data_type = TYPE_BYTE_BLOB; *data_size = key_part->length; break; case MYSQL_TYPE_BIT: // TODO DBUG_PRINT("info", ("mroonga: MYSQL_TYPE_BIT")); *data_type = TYPE_NUMBER; *data_size = 1; break; #ifdef MRN_HAVE_MYSQL_TYPE_TIMESTAMP2 case MYSQL_TYPE_TIMESTAMP2: // TODO DBUG_PRINT("info", ("mroonga: MYSQL_TYPE_TIMESTAMP2")); *data_type = TYPE_LONG_LONG_NUMBER; *data_size = 8; break; #endif #ifdef MRN_HAVE_MYSQL_TYPE_DATETIME2 case MYSQL_TYPE_DATETIME2: // TODO DBUG_PRINT("info", ("mroonga: MYSQL_TYPE_DATETIME2")); *data_type = TYPE_BYTE_SEQUENCE; *data_size = key_part->length; break; #endif #ifdef MRN_HAVE_MYSQL_TYPE_TIME2 case MYSQL_TYPE_TIME2: // TODO DBUG_PRINT("info", ("mroonga: MYSQL_TYPE_TIME2")); *data_type = TYPE_LONG_LONG_NUMBER; *data_size = 8; break; #endif case MYSQL_TYPE_NEWDECIMAL: DBUG_PRINT("info", ("mroonga: MYSQL_TYPE_NEWDECIMAL")); *data_type = TYPE_BYTE_SEQUENCE; *data_size = key_part->length; break; case MYSQL_TYPE_ENUM: // TODO DBUG_PRINT("info", ("mroonga: MYSQL_TYPE_ENUM")); *data_type = TYPE_NUMBER; *data_size = 1; break; case MYSQL_TYPE_SET: // TODO DBUG_PRINT("info", ("mroonga: MYSQL_TYPE_SET")); *data_type = TYPE_NUMBER; *data_size = 1; break; case MYSQL_TYPE_TINY_BLOB: case MYSQL_TYPE_MEDIUM_BLOB: case MYSQL_TYPE_LONG_BLOB: case MYSQL_TYPE_BLOB: // TODO DBUG_PRINT("info", ("mroonga: MYSQL_TYPE_BLOB")); *data_type = TYPE_BYTE_BLOB; *data_size = key_part->length; break; case MYSQL_TYPE_VAR_STRING: case MYSQL_TYPE_STRING: // TODO DBUG_PRINT("info", ("mroonga: MYSQL_TYPE_STRING")); *data_type = TYPE_BYTE_SEQUENCE; *data_size = key_part->length; break; case MYSQL_TYPE_GEOMETRY: // TODO DBUG_PRINT("info", ("mroonga: MYSQL_TYPE_GEOMETRY")); *data_type = TYPE_BYTE_SEQUENCE; *data_size = key_part->length; break; } DBUG_VOID_RETURN; } void MultipleColumnKeyCodec::encode_float(volatile float value, uint data_size, uchar *buffer, bool decode) { MRN_DBUG_ENTER_METHOD(); int n_bits = (data_size * 8 - 1); volatile int *int_value_pointer = (int *)(&value); int int_value = *int_value_pointer; if (!decode) int_value ^= ((int_value >> n_bits) | (1 << n_bits)); mrn_byte_order_host_to_network(buffer, &int_value, data_size); if (decode) { int_value = *((int *)buffer); *((int *)buffer) = int_value ^ (((int_value ^ (1 << n_bits)) >> n_bits) | (1 << n_bits)); } DBUG_VOID_RETURN; } void MultipleColumnKeyCodec::encode_double(volatile double value, uint data_size, uchar *buffer, bool decode) { MRN_DBUG_ENTER_METHOD(); int n_bits = (data_size * 8 - 1); volatile long long int *long_long_value_pointer = (long long int *)(&value); volatile long long int long_long_value = *long_long_value_pointer; if (!decode) long_long_value ^= ((long_long_value >> n_bits) | (1LL << n_bits)); mrn_byte_order_host_to_network(buffer, &long_long_value, data_size); if (decode) { long_long_value = *((long long int *)buffer); *((long long int *)buffer) = long_long_value ^ (((long_long_value ^ (1LL << n_bits)) >> n_bits) | (1LL << n_bits)); } DBUG_VOID_RETURN; } void MultipleColumnKeyCodec::encode_reverse(const uchar *key, uint data_size, uchar *buffer) { MRN_DBUG_ENTER_METHOD(); for (uint i = 0; i < data_size; i++) { buffer[i] = key[data_size - i - 1]; } DBUG_VOID_RETURN; } } <commit_msg>Remove needless TODO<commit_after>/* -*- c-basic-offset: 2 -*- */ /* Copyright(C) 2012 Kouhei Sutou <kou@clear-code.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <mrn_mysql.h> #include "mrn_multiple_column_key_codec.hpp" // for debug #define MRN_CLASS_NAME "mrn::MultipleColumnKeyCodec" #ifdef WORDS_BIGENDIAN #define mrn_byte_order_host_to_network(buf, key, size) \ { \ uint32 size_ = (uint32)(size); \ uint8 *buf_ = (uint8 *)(buf); \ uint8 *key_ = (uint8 *)(key); \ while (size_--) { *buf_++ = *key_++; } \ } #else /* WORDS_BIGENDIAN */ #define mrn_byte_order_host_to_network(buf, key, size) \ { \ uint32 size_ = (uint32)(size); \ uint8 *buf_ = (uint8 *)(buf); \ uint8 *key_ = (uint8 *)(key) + size_; \ while (size_--) { *buf_++ = *(--key_); } \ } #endif /* WORDS_BIGENDIAN */ namespace mrn { MultipleColumnKeyCodec::MultipleColumnKeyCodec(KEY *key_info) : key_info_(key_info) { } MultipleColumnKeyCodec::~MultipleColumnKeyCodec() { } int MultipleColumnKeyCodec::encode(const uchar *key, uint key_length, uchar *buffer, uint *encoded_length, bool decode) { MRN_DBUG_ENTER_METHOD(); int error = 0; const uchar *current_key = key; const uchar *key_end = key + key_length; uchar *current_buffer = buffer; int n_key_parts = key_info_->key_parts; DBUG_PRINT("info", ("mroonga: n_key_parts=%d", n_key_parts)); *encoded_length = 0; for (int i = 0; i < n_key_parts && current_key < key_end; i++) { KEY_PART_INFO *key_part = &(key_info_->key_part[i]); Field *field = key_part->field; DBUG_PRINT("info", ("mroonga: key_part->length=%u", key_part->length)); if (field->null_bit) { DBUG_PRINT("info", ("mroonga: field has null bit")); *current_buffer = *current_key; current_key += 1; current_buffer += 1; (*encoded_length)++; } DataType data_type = TYPE_UNKNOWN; uint data_size = 0; get_key_info(key_part, &data_type, &data_size); switch (data_type) { case TYPE_UNKNOWN: // TODO: This will not be happen. This is just for // suppressing warnings by gcc -O2. :< error = HA_ERR_UNSUPPORTED; break; case TYPE_LONG_LONG_NUMBER: { long long int long_long_value = 0; switch (data_size) { case 3: long_long_value = (long long int)sint3korr(current_key); break; case 8: long_long_value = (long long int)sint8korr(current_key); break; } if (decode) *((uint8 *)(&long_long_value)) ^= 0x80; mrn_byte_order_host_to_network(current_buffer, &long_long_value, data_size); if (!decode) *((uint8 *)(current_buffer)) ^= 0x80; } break; case TYPE_NUMBER: if (decode) { Field_num *number_field = (Field_num *)field; if (!number_field->unsigned_flag) { *((uint8 *)(current_key)) ^= 0x80; } } mrn_byte_order_host_to_network(current_buffer, current_key, data_size); if (!decode) { Field_num *number_field = (Field_num *)field; if (!number_field->unsigned_flag) { *((uint8 *)(current_buffer)) ^= 0x80; } } break; case TYPE_FLOAT: { float value; float4get(value, current_key); encode_float(value, data_size, current_buffer, decode); } break; case TYPE_DOUBLE: { double value; float8get(value, current_key); encode_double(value, data_size, current_buffer, decode); } break; case TYPE_BYTE_SEQUENCE: memcpy(current_buffer, current_key, data_size); break; case TYPE_BYTE_REVERSE: encode_reverse(current_key, data_size, current_buffer); break; case TYPE_BYTE_BLOB: if (decode) { memcpy(current_buffer, current_key + data_size, HA_KEY_BLOB_LENGTH); memcpy(current_buffer + HA_KEY_BLOB_LENGTH, current_key, data_size); } else { memcpy(current_buffer + data_size, current_key, HA_KEY_BLOB_LENGTH); memcpy(current_buffer, current_key + HA_KEY_BLOB_LENGTH, data_size); } data_size += HA_KEY_BLOB_LENGTH; break; } if (error) { break; } current_key += data_size; current_buffer += data_size; *encoded_length += data_size; } DBUG_RETURN(error); } uint MultipleColumnKeyCodec::size() { MRN_DBUG_ENTER_METHOD(); int n_key_parts = key_info_->key_parts; DBUG_PRINT("info", ("mroonga: n_key_parts=%d", n_key_parts)); uint total_size = 0; for (int i = 0; i < n_key_parts; ++i) { KEY_PART_INFO *key_part = &(key_info_->key_part[i]); Field *field = key_part->field; DBUG_PRINT("info", ("mroonga: key_part->length=%u", key_part->length)); if (field->null_bit) { DBUG_PRINT("info", ("mroonga: field has null bit")); ++total_size; } DataType data_type = TYPE_UNKNOWN; uint data_size = 0; get_key_info(key_part, &data_type, &data_size); total_size += data_size; if (data_type == TYPE_BYTE_BLOB) { total_size += HA_KEY_BLOB_LENGTH; } } DBUG_RETURN(total_size); } void MultipleColumnKeyCodec::get_key_info(KEY_PART_INFO *key_part, DataType *data_type, uint *data_size) { MRN_DBUG_ENTER_METHOD(); *data_type = TYPE_UNKNOWN; *data_size = 0; Field *field = key_part->field; switch (field->real_type()) { case MYSQL_TYPE_DECIMAL: DBUG_PRINT("info", ("mroonga: MYSQL_TYPE_DECIMAL")); *data_type = TYPE_BYTE_SEQUENCE; *data_size = key_part->length; break; case MYSQL_TYPE_TINY: case MYSQL_TYPE_YEAR: DBUG_PRINT("info", ("mroonga: MYSQL_TYPE_TINY")); *data_type = TYPE_NUMBER; *data_size = 1; break; case MYSQL_TYPE_SHORT: DBUG_PRINT("info", ("mroonga: MYSQL_TYPE_SHORT")); *data_type = TYPE_NUMBER; *data_size = 2; break; case MYSQL_TYPE_LONG: DBUG_PRINT("info", ("mroonga: MYSQL_TYPE_LONG")); *data_type = TYPE_NUMBER; *data_size = 4; break; case MYSQL_TYPE_FLOAT: DBUG_PRINT("info", ("mroonga: MYSQL_TYPE_FLOAT")); *data_type = TYPE_FLOAT; *data_size = 4; break; case MYSQL_TYPE_DOUBLE: DBUG_PRINT("info", ("mroonga: MYSQL_TYPE_DOUBLE")); *data_type = TYPE_DOUBLE; *data_size = 8; break; case MYSQL_TYPE_NULL: DBUG_PRINT("info", ("mroonga: MYSQL_TYPE_NULL")); *data_type = TYPE_NUMBER; *data_size = 1; break; case MYSQL_TYPE_TIMESTAMP: case MYSQL_TYPE_DATE: case MYSQL_TYPE_DATETIME: case MYSQL_TYPE_NEWDATE: DBUG_PRINT("info", ("mroonga: MYSQL_TYPE_DATETIME")); *data_type = TYPE_BYTE_REVERSE; *data_size = key_part->length; break; case MYSQL_TYPE_LONGLONG: DBUG_PRINT("info", ("mroonga: MYSQL_TYPE_LONGLONG")); *data_type = TYPE_NUMBER; *data_size = 8; break; case MYSQL_TYPE_INT24: DBUG_PRINT("info", ("mroonga: MYSQL_TYPE_INT24")); *data_type = TYPE_NUMBER; *data_size = 3; break; case MYSQL_TYPE_TIME: DBUG_PRINT("info", ("mroonga: MYSQL_TYPE_TIME")); *data_type = TYPE_LONG_LONG_NUMBER; *data_size = 3; break; case MYSQL_TYPE_VARCHAR: DBUG_PRINT("info", ("mroonga: MYSQL_TYPE_VARCHAR")); *data_type = TYPE_BYTE_BLOB; *data_size = key_part->length; break; case MYSQL_TYPE_BIT: // TODO DBUG_PRINT("info", ("mroonga: MYSQL_TYPE_BIT")); *data_type = TYPE_NUMBER; *data_size = 1; break; #ifdef MRN_HAVE_MYSQL_TYPE_TIMESTAMP2 case MYSQL_TYPE_TIMESTAMP2: // TODO DBUG_PRINT("info", ("mroonga: MYSQL_TYPE_TIMESTAMP2")); *data_type = TYPE_LONG_LONG_NUMBER; *data_size = 8; break; #endif #ifdef MRN_HAVE_MYSQL_TYPE_DATETIME2 case MYSQL_TYPE_DATETIME2: DBUG_PRINT("info", ("mroonga: MYSQL_TYPE_DATETIME2")); *data_type = TYPE_BYTE_SEQUENCE; *data_size = key_part->length; break; #endif #ifdef MRN_HAVE_MYSQL_TYPE_TIME2 case MYSQL_TYPE_TIME2: // TODO DBUG_PRINT("info", ("mroonga: MYSQL_TYPE_TIME2")); *data_type = TYPE_LONG_LONG_NUMBER; *data_size = 8; break; #endif case MYSQL_TYPE_NEWDECIMAL: DBUG_PRINT("info", ("mroonga: MYSQL_TYPE_NEWDECIMAL")); *data_type = TYPE_BYTE_SEQUENCE; *data_size = key_part->length; break; case MYSQL_TYPE_ENUM: // TODO DBUG_PRINT("info", ("mroonga: MYSQL_TYPE_ENUM")); *data_type = TYPE_NUMBER; *data_size = 1; break; case MYSQL_TYPE_SET: // TODO DBUG_PRINT("info", ("mroonga: MYSQL_TYPE_SET")); *data_type = TYPE_NUMBER; *data_size = 1; break; case MYSQL_TYPE_TINY_BLOB: case MYSQL_TYPE_MEDIUM_BLOB: case MYSQL_TYPE_LONG_BLOB: case MYSQL_TYPE_BLOB: // TODO DBUG_PRINT("info", ("mroonga: MYSQL_TYPE_BLOB")); *data_type = TYPE_BYTE_BLOB; *data_size = key_part->length; break; case MYSQL_TYPE_VAR_STRING: case MYSQL_TYPE_STRING: // TODO DBUG_PRINT("info", ("mroonga: MYSQL_TYPE_STRING")); *data_type = TYPE_BYTE_SEQUENCE; *data_size = key_part->length; break; case MYSQL_TYPE_GEOMETRY: // TODO DBUG_PRINT("info", ("mroonga: MYSQL_TYPE_GEOMETRY")); *data_type = TYPE_BYTE_SEQUENCE; *data_size = key_part->length; break; } DBUG_VOID_RETURN; } void MultipleColumnKeyCodec::encode_float(volatile float value, uint data_size, uchar *buffer, bool decode) { MRN_DBUG_ENTER_METHOD(); int n_bits = (data_size * 8 - 1); volatile int *int_value_pointer = (int *)(&value); int int_value = *int_value_pointer; if (!decode) int_value ^= ((int_value >> n_bits) | (1 << n_bits)); mrn_byte_order_host_to_network(buffer, &int_value, data_size); if (decode) { int_value = *((int *)buffer); *((int *)buffer) = int_value ^ (((int_value ^ (1 << n_bits)) >> n_bits) | (1 << n_bits)); } DBUG_VOID_RETURN; } void MultipleColumnKeyCodec::encode_double(volatile double value, uint data_size, uchar *buffer, bool decode) { MRN_DBUG_ENTER_METHOD(); int n_bits = (data_size * 8 - 1); volatile long long int *long_long_value_pointer = (long long int *)(&value); volatile long long int long_long_value = *long_long_value_pointer; if (!decode) long_long_value ^= ((long_long_value >> n_bits) | (1LL << n_bits)); mrn_byte_order_host_to_network(buffer, &long_long_value, data_size); if (decode) { long_long_value = *((long long int *)buffer); *((long long int *)buffer) = long_long_value ^ (((long_long_value ^ (1LL << n_bits)) >> n_bits) | (1LL << n_bits)); } DBUG_VOID_RETURN; } void MultipleColumnKeyCodec::encode_reverse(const uchar *key, uint data_size, uchar *buffer) { MRN_DBUG_ENTER_METHOD(); for (uint i = 0; i < data_size; i++) { buffer[i] = key[data_size - i - 1]; } DBUG_VOID_RETURN; } } <|endoftext|>
<commit_before>/* * X509_DN * (C) 1999-2007,2018 Jack Lloyd * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/x509_dn.h> #include <botan/der_enc.h> #include <botan/ber_dec.h> #include <botan/parsing.h> #include <botan/internal/stl_util.h> #include <botan/oids.h> #include <ostream> #include <sstream> #include <cctype> namespace Botan { /* * Add an attribute to a X509_DN */ void X509_DN::add_attribute(const std::string& type, const std::string& str) { add_attribute(OIDS::str2oid_or_throw(type), str); } /* * Add an attribute to a X509_DN */ void X509_DN::add_attribute(const OID& oid, const ASN1_String& str) { if(str.empty()) return; m_rdn.push_back(std::make_pair(oid, str)); m_dn_bits.clear(); } /* * Get the attributes of this X509_DN */ std::multimap<OID, std::string> X509_DN::get_attributes() const { std::multimap<OID, std::string> retval; for(auto& i : m_rdn) multimap_insert(retval, i.first, i.second.value()); return retval; } /* * Get the contents of this X.500 Name */ std::multimap<std::string, std::string> X509_DN::contents() const { std::multimap<std::string, std::string> retval; for(auto& i : m_rdn) { const std::string str_value = OIDS::oid2str_or_raw(i.first); multimap_insert(retval, str_value, i.second.value()); } return retval; } bool X509_DN::has_field(const std::string& attr) const { return has_field(OIDS::str2oid_or_throw(deref_info_field(attr))); } bool X509_DN::has_field(const OID& oid) const { for(auto& i : m_rdn) { if(i.first == oid) return true; } return false; } std::string X509_DN::get_first_attribute(const std::string& attr) const { const OID oid = OIDS::str2oid_or_throw(deref_info_field(attr)); return get_first_attribute(oid).value(); } ASN1_String X509_DN::get_first_attribute(const OID& oid) const { for(auto& i : m_rdn) { if(i.first == oid) { return i.second; } } return ASN1_String(); } /* * Get a single attribute type */ std::vector<std::string> X509_DN::get_attribute(const std::string& attr) const { const OID oid = OIDS::str2oid_or_throw(deref_info_field(attr)); std::vector<std::string> values; for(auto& i : m_rdn) { if(i.first == oid) { values.push_back(i.second.value()); } } return values; } /* * Deref aliases in a subject/issuer info request */ std::string X509_DN::deref_info_field(const std::string& info) { if(info == "Name" || info == "CommonName" || info == "CN") return "X520.CommonName"; if(info == "SerialNumber" || info == "SN") return "X520.SerialNumber"; if(info == "Country" || info == "C") return "X520.Country"; if(info == "Organization" || info == "O") return "X520.Organization"; if(info == "Organizational Unit" || info == "OrgUnit" || info == "OU") return "X520.OrganizationalUnit"; if(info == "Locality" || info == "L") return "X520.Locality"; if(info == "State" || info == "Province" || info == "ST") return "X520.State"; if(info == "Email") return "RFC822"; return info; } /* * Compare two X509_DNs for equality */ bool operator==(const X509_DN& dn1, const X509_DN& dn2) { auto attr1 = dn1.get_attributes(); auto attr2 = dn2.get_attributes(); if(attr1.size() != attr2.size()) return false; auto p1 = attr1.begin(); auto p2 = attr2.begin(); while(true) { if(p1 == attr1.end() && p2 == attr2.end()) break; if(p1 == attr1.end()) return false; if(p2 == attr2.end()) return false; if(p1->first != p2->first) return false; if(!x500_name_cmp(p1->second, p2->second)) return false; ++p1; ++p2; } return true; } /* * Compare two X509_DNs for inequality */ bool operator!=(const X509_DN& dn1, const X509_DN& dn2) { return !(dn1 == dn2); } /* * Induce an arbitrary ordering on DNs */ bool operator<(const X509_DN& dn1, const X509_DN& dn2) { auto attr1 = dn1.get_attributes(); auto attr2 = dn2.get_attributes(); // If they are not the same size, choose the smaller as the "lessor" if(attr1.size() < attr2.size()) return true; if(attr1.size() > attr2.size()) return false; // We know they are the same # of elements, now compare the OIDs: auto p1 = attr1.begin(); auto p2 = attr2.begin(); while(p1 != attr1.end() && p2 != attr2.end()) { if(p1->first != p2->first) { return (p1->first < p2->first); } ++p1; ++p2; } // We know this is true because maps have the same size BOTAN_ASSERT_NOMSG(p1 == attr1.end()); BOTAN_ASSERT_NOMSG(p2 == attr2.end()); // Now we know all elements have the same OIDs, compare // their string values: p1 = attr1.begin(); p2 = attr2.begin(); while(p1 != attr1.end() && p2 != attr2.end()) { BOTAN_DEBUG_ASSERT(p1->first == p2->first); // They may be binary different but same by X.500 rules, check this if(!x500_name_cmp(p1->second, p2->second)) { // If they are not (by X.500) the same string, pick the // lexicographic first as the lessor return (p1->second < p2->second); } ++p1; ++p2; } // if we reach here, then the DNs should be identical BOTAN_DEBUG_ASSERT(dn1 == dn2); return false; } /* * DER encode a DistinguishedName */ void X509_DN::encode_into(DER_Encoder& der) const { der.start_cons(SEQUENCE); if(!m_dn_bits.empty()) { /* If we decoded this from somewhere, encode it back exactly as we received it */ der.raw_bytes(m_dn_bits); } else { for(const auto& dn : m_rdn) { der.start_cons(SET) .start_cons(SEQUENCE) .encode(dn.first) .encode(dn.second) .end_cons() .end_cons(); } } der.end_cons(); } /* * Decode a BER encoded DistinguishedName */ void X509_DN::decode_from(BER_Decoder& source) { std::vector<uint8_t> bits; source.start_cons(SEQUENCE) .raw_bytes(bits) .end_cons(); BER_Decoder sequence(bits); while(sequence.more_items()) { BER_Decoder rdn = sequence.start_cons(SET); while(rdn.more_items()) { OID oid; ASN1_String str; rdn.start_cons(SEQUENCE) .decode(oid) .decode(str) // TODO support Any .end_cons().verify_end("Invalid X509_DN, data follows RDN"); add_attribute(oid, str); } } m_dn_bits = bits; } namespace { std::string to_short_form(const OID& oid) { const std::string long_id = OIDS::oid2str_or_raw(oid); if(long_id == "X520.CommonName") return "CN"; if(long_id == "X520.Country") return "C"; if(long_id == "X520.Organization") return "O"; if(long_id == "X520.OrganizationalUnit") return "OU"; return long_id; } } std::string X509_DN::to_string() const { std::ostringstream out; out << *this; return out.str(); } std::ostream& operator<<(std::ostream& out, const X509_DN& dn) { auto info = dn.dn_info(); for(size_t i = 0; i != info.size(); ++i) { out << to_short_form(info[i].first) << "=\""; for(char c : info[i].second.value()) { if(c == '\\' || c == '\"') { out << "\\"; } out << c; } out << "\""; if(i + 1 < info.size()) { out << ","; } } return out; } std::istream& operator>>(std::istream& in, X509_DN& dn) { in >> std::noskipws; do { std::string key; std::string val; char c; while(in.good()) { in >> c; if(std::isspace(c) && key.empty()) continue; else if(!std::isspace(c)) { key.push_back(c); break; } else break; } while(in.good()) { in >> c; if(!std::isspace(c) && c != '=') key.push_back(c); else if(c == '=') break; else throw Invalid_Argument("Ill-formed X.509 DN"); } bool in_quotes = false; while(in.good()) { in >> c; if(std::isspace(c)) { if(!in_quotes && !val.empty()) break; else if(in_quotes) val.push_back(' '); } else if(c == '"') in_quotes = !in_quotes; else if(c == '\\') { if(in.good()) in >> c; val.push_back(c); } else if(c == ',' && !in_quotes) break; else val.push_back(c); } if(!key.empty() && !val.empty()) dn.add_attribute(X509_DN::deref_info_field(key),val); else break; } while(in.good()); return in; } } <commit_msg>Don't throw here<commit_after>/* * X509_DN * (C) 1999-2007,2018 Jack Lloyd * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/x509_dn.h> #include <botan/der_enc.h> #include <botan/ber_dec.h> #include <botan/parsing.h> #include <botan/internal/stl_util.h> #include <botan/oids.h> #include <ostream> #include <sstream> #include <cctype> namespace Botan { /* * Add an attribute to a X509_DN */ void X509_DN::add_attribute(const std::string& type, const std::string& str) { add_attribute(OIDS::str2oid_or_throw(type), str); } /* * Add an attribute to a X509_DN */ void X509_DN::add_attribute(const OID& oid, const ASN1_String& str) { if(str.empty()) return; m_rdn.push_back(std::make_pair(oid, str)); m_dn_bits.clear(); } /* * Get the attributes of this X509_DN */ std::multimap<OID, std::string> X509_DN::get_attributes() const { std::multimap<OID, std::string> retval; for(auto& i : m_rdn) multimap_insert(retval, i.first, i.second.value()); return retval; } /* * Get the contents of this X.500 Name */ std::multimap<std::string, std::string> X509_DN::contents() const { std::multimap<std::string, std::string> retval; for(auto& i : m_rdn) { const std::string str_value = OIDS::oid2str_or_raw(i.first); multimap_insert(retval, str_value, i.second.value()); } return retval; } bool X509_DN::has_field(const std::string& attr) const { const OID o = OIDS::str2oid_or_empty(deref_info_field(attr)); if(o.has_value()) return has_field(o); else return false; } bool X509_DN::has_field(const OID& oid) const { for(auto& i : m_rdn) { if(i.first == oid) return true; } return false; } std::string X509_DN::get_first_attribute(const std::string& attr) const { const OID oid = OIDS::str2oid_or_throw(deref_info_field(attr)); return get_first_attribute(oid).value(); } ASN1_String X509_DN::get_first_attribute(const OID& oid) const { for(auto& i : m_rdn) { if(i.first == oid) { return i.second; } } return ASN1_String(); } /* * Get a single attribute type */ std::vector<std::string> X509_DN::get_attribute(const std::string& attr) const { const OID oid = OIDS::str2oid_or_throw(deref_info_field(attr)); std::vector<std::string> values; for(auto& i : m_rdn) { if(i.first == oid) { values.push_back(i.second.value()); } } return values; } /* * Deref aliases in a subject/issuer info request */ std::string X509_DN::deref_info_field(const std::string& info) { if(info == "Name" || info == "CommonName" || info == "CN") return "X520.CommonName"; if(info == "SerialNumber" || info == "SN") return "X520.SerialNumber"; if(info == "Country" || info == "C") return "X520.Country"; if(info == "Organization" || info == "O") return "X520.Organization"; if(info == "Organizational Unit" || info == "OrgUnit" || info == "OU") return "X520.OrganizationalUnit"; if(info == "Locality" || info == "L") return "X520.Locality"; if(info == "State" || info == "Province" || info == "ST") return "X520.State"; if(info == "Email") return "RFC822"; return info; } /* * Compare two X509_DNs for equality */ bool operator==(const X509_DN& dn1, const X509_DN& dn2) { auto attr1 = dn1.get_attributes(); auto attr2 = dn2.get_attributes(); if(attr1.size() != attr2.size()) return false; auto p1 = attr1.begin(); auto p2 = attr2.begin(); while(true) { if(p1 == attr1.end() && p2 == attr2.end()) break; if(p1 == attr1.end()) return false; if(p2 == attr2.end()) return false; if(p1->first != p2->first) return false; if(!x500_name_cmp(p1->second, p2->second)) return false; ++p1; ++p2; } return true; } /* * Compare two X509_DNs for inequality */ bool operator!=(const X509_DN& dn1, const X509_DN& dn2) { return !(dn1 == dn2); } /* * Induce an arbitrary ordering on DNs */ bool operator<(const X509_DN& dn1, const X509_DN& dn2) { auto attr1 = dn1.get_attributes(); auto attr2 = dn2.get_attributes(); // If they are not the same size, choose the smaller as the "lessor" if(attr1.size() < attr2.size()) return true; if(attr1.size() > attr2.size()) return false; // We know they are the same # of elements, now compare the OIDs: auto p1 = attr1.begin(); auto p2 = attr2.begin(); while(p1 != attr1.end() && p2 != attr2.end()) { if(p1->first != p2->first) { return (p1->first < p2->first); } ++p1; ++p2; } // We know this is true because maps have the same size BOTAN_ASSERT_NOMSG(p1 == attr1.end()); BOTAN_ASSERT_NOMSG(p2 == attr2.end()); // Now we know all elements have the same OIDs, compare // their string values: p1 = attr1.begin(); p2 = attr2.begin(); while(p1 != attr1.end() && p2 != attr2.end()) { BOTAN_DEBUG_ASSERT(p1->first == p2->first); // They may be binary different but same by X.500 rules, check this if(!x500_name_cmp(p1->second, p2->second)) { // If they are not (by X.500) the same string, pick the // lexicographic first as the lessor return (p1->second < p2->second); } ++p1; ++p2; } // if we reach here, then the DNs should be identical BOTAN_DEBUG_ASSERT(dn1 == dn2); return false; } /* * DER encode a DistinguishedName */ void X509_DN::encode_into(DER_Encoder& der) const { der.start_cons(SEQUENCE); if(!m_dn_bits.empty()) { /* If we decoded this from somewhere, encode it back exactly as we received it */ der.raw_bytes(m_dn_bits); } else { for(const auto& dn : m_rdn) { der.start_cons(SET) .start_cons(SEQUENCE) .encode(dn.first) .encode(dn.second) .end_cons() .end_cons(); } } der.end_cons(); } /* * Decode a BER encoded DistinguishedName */ void X509_DN::decode_from(BER_Decoder& source) { std::vector<uint8_t> bits; source.start_cons(SEQUENCE) .raw_bytes(bits) .end_cons(); BER_Decoder sequence(bits); while(sequence.more_items()) { BER_Decoder rdn = sequence.start_cons(SET); while(rdn.more_items()) { OID oid; ASN1_String str; rdn.start_cons(SEQUENCE) .decode(oid) .decode(str) // TODO support Any .end_cons().verify_end("Invalid X509_DN, data follows RDN"); add_attribute(oid, str); } } m_dn_bits = bits; } namespace { std::string to_short_form(const OID& oid) { const std::string long_id = OIDS::oid2str_or_raw(oid); if(long_id == "X520.CommonName") return "CN"; if(long_id == "X520.Country") return "C"; if(long_id == "X520.Organization") return "O"; if(long_id == "X520.OrganizationalUnit") return "OU"; return long_id; } } std::string X509_DN::to_string() const { std::ostringstream out; out << *this; return out.str(); } std::ostream& operator<<(std::ostream& out, const X509_DN& dn) { auto info = dn.dn_info(); for(size_t i = 0; i != info.size(); ++i) { out << to_short_form(info[i].first) << "=\""; for(char c : info[i].second.value()) { if(c == '\\' || c == '\"') { out << "\\"; } out << c; } out << "\""; if(i + 1 < info.size()) { out << ","; } } return out; } std::istream& operator>>(std::istream& in, X509_DN& dn) { in >> std::noskipws; do { std::string key; std::string val; char c; while(in.good()) { in >> c; if(std::isspace(c) && key.empty()) continue; else if(!std::isspace(c)) { key.push_back(c); break; } else break; } while(in.good()) { in >> c; if(!std::isspace(c) && c != '=') key.push_back(c); else if(c == '=') break; else throw Invalid_Argument("Ill-formed X.509 DN"); } bool in_quotes = false; while(in.good()) { in >> c; if(std::isspace(c)) { if(!in_quotes && !val.empty()) break; else if(in_quotes) val.push_back(' '); } else if(c == '"') in_quotes = !in_quotes; else if(c == '\\') { if(in.good()) in >> c; val.push_back(c); } else if(c == ',' && !in_quotes) break; else val.push_back(c); } if(!key.empty() && !val.empty()) dn.add_attribute(X509_DN::deref_info_field(key),val); else break; } while(in.good()); return in; } } <|endoftext|>
<commit_before>// macro to make invariant mass plots // for combinations of 2 muons with opposite charges, // from root file "MUONtrackReco.root" containing the result of track reconstruction, // generated by the macro "MUONrecoNtuple.C". // Histograms are stored on the "MUONmassPlot.root" file. // A model for macros using the Ntuple in the file "MUONtrackReco.root" // may be found in "MUONtrackRecoModel.C": // it has been obtained by reading with Root a file "MUONtrackReco.root", // and executing the command: // MUONtrackReco->MakeCode("MUONtrackRecoModel.C") // Arguments: // FirstEvent (default 0) // LastEvent (default 0) // ResType (default 553) // 553 for Upsilon, anything else for J/Psi // NSigma (default 3) // the number of combinations is counted around the resonance mass // within +/- NSigma times the nominal sigma's // (0.099 GeV for Upsilon, 0.0615 GeV for J/Psi) // Chi2Cut (default 100) // to keep only tracks with chi2 per d.o.f. < Chi2Cut // PtCut (default 1) // to keep only tracks with transverse momentum > PtCut void MUONmassPlot(Int_t FirstEvent = 0, Int_t LastEvent = 0, Int_t ResType = 553, Float_t Nsig = 3., Float_t Chi2Cut = 100., Float_t PtCut = 1.) { cout << "MUONmassPlot" << endl; cout << "FirstEvent" << FirstEvent << endl; cout << "LastEvent" << LastEvent << endl; cout << "ResType" << ResType << endl; cout << "Nsig" << Nsig << endl; cout << "Chi2Cut" << Chi2Cut << endl; cout << "PtCut" << PtCut << endl; ////////////////////////////////////////////////////////// // This file has been automatically generated // (Thu Sep 21 14:53:11 2000 by ROOT version2.25/02) // from TTree MUONtrackReco/MUONtrackReco // found on file: MUONtrackReco.root ////////////////////////////////////////////////////////// //Reset ROOT and connect tree file gROOT->Reset(); TFile *f = (TFile*)gROOT->GetListOfFiles()->FindObject("MUONtrackReco.root"); if (!f) { f = new TFile("MUONtrackReco.root"); } TTree *MUONtrackReco = (TTree*)gDirectory->Get("MUONtrackReco"); //Declaration of leaves types Int_t fEvent; UInt_t fUniqueID; UInt_t fBits; Int_t Tracks_; Int_t Tracks_fCharge[5]; Float_t Tracks_fPxRec[5]; Float_t Tracks_fPyRec[5]; Float_t Tracks_fPzRec[5]; Float_t Tracks_fZRec[5]; Float_t Tracks_fZRec1[5]; Int_t Tracks_fNHits[5]; Float_t Tracks_fChi2[5]; Float_t Tracks_fPxGen[5]; Float_t Tracks_fPyGen[5]; Float_t Tracks_fPzGen[5]; UInt_t Tracks_fUniqueID[5]; UInt_t Tracks_fBits[5]; //Set branch addresses //MUONtrackReco->SetBranchAddress("Header",&Header); MUONtrackReco->SetBranchAddress("fEvent",&fEvent); MUONtrackReco->SetBranchAddress("fUniqueID",&fUniqueID); MUONtrackReco->SetBranchAddress("fBits",&fBits); MUONtrackReco->SetBranchAddress("Tracks_",&Tracks_); MUONtrackReco->SetBranchAddress("Tracks.fCharge",Tracks_fCharge); MUONtrackReco->SetBranchAddress("Tracks.fPxRec",Tracks_fPxRec); MUONtrackReco->SetBranchAddress("Tracks.fPyRec",Tracks_fPyRec); MUONtrackReco->SetBranchAddress("Tracks.fPzRec",Tracks_fPzRec); MUONtrackReco->SetBranchAddress("Tracks.fZRec",Tracks_fZRec); MUONtrackReco->SetBranchAddress("Tracks.fZRec1",Tracks_fZRec1); MUONtrackReco->SetBranchAddress("Tracks.fNHits",Tracks_fNHits); MUONtrackReco->SetBranchAddress("Tracks.fChi2",Tracks_fChi2); MUONtrackReco->SetBranchAddress("Tracks.fPxGen",Tracks_fPxGen); MUONtrackReco->SetBranchAddress("Tracks.fPyGen",Tracks_fPyGen); MUONtrackReco->SetBranchAddress("Tracks.fPzGen",Tracks_fPzGen); MUONtrackReco->SetBranchAddress("Tracks.fUniqueID",Tracks_fUniqueID); MUONtrackReco->SetBranchAddress("Tracks.fBits",Tracks_fBits); // This is the loop skeleton // To read only selected branches, Insert statements like: // MUONtrackReco->SetBranchStatus("*",0); // disable all branches // TTreePlayer->SetBranchStatus("branchname",1); // activate branchname Int_t nentries = MUONtrackReco->GetEntries(); Int_t nbytes = 0; // for (Int_t i=0; i<nentries;i++) { // nbytes += MUONtrackReco->GetEntry(i); // } ///////////////////////////////////////////////////////////////// // Here comes the specialized part for MUONmassPlot ///////////////////////////////////////////////////////////////// // File for histograms and histogram booking TFile *histoFile = new TFile("MUONmassPlot.root", "RECREATE"); TH1F *hPtMuon = new TH1F("hPtMuon", "Muon Pt (GeV/c)", 100, 0., 20.); TH1F *hChi2PerDof = new TH1F("hChi2PerDof", "Muon track chi2/d.o.f.", 100, 0., 20.); TH1F *hInvMassAll = new TH1F("hInvMassAll", "Mu+Mu- invariant mass (GeV/c2)", 240, 0., 12.); if (ResType = 553) TH1F *hInvMassRes = new TH1F("hInvMassRes", "Mu+Mu- invariant mass (GeV/c2) around Upsilon", 60, 8., 11.); else TH1F *hInvMassRes = new TH1F("hInvMassRes", "Mu+Mu- invariant mass (GeV/c2) around J/Psi", 80, 1., 5.); // Loop over events for (Int_t event = FirstEvent; event <= TMath::Min(LastEvent, nentries - 1); event++) { // get current event nbytes += MUONtrackReco->GetEntry(event); // loop over all reconstructed tracks (also first track of combination) for (Int_t t1 = 0; t1 < Tracks_; t1++) { // transverse momentum Float_t pt1 = TMath::Sqrt(Tracks_fPxRec[t1] * Tracks_fPxRec[t1] + Tracks_fPyRec[t1] * Tracks_fPyRec[t1]); // chi2 per d.o.f. Float_t ch1 = Tracks_fChi2[t1] / (2.0 * Tracks_fNHits[t1] - 5); // condition for good track (Chi2Cut and PtCut) if ((ch1 < Chi2Cut) && (pt1 > PtCut)) { // fill histos hPtMuon and hChi2PerDof hPtMuon->Fill(pt1); hChi2PerDof->Fill(ch1); // loop over second track of combination for (Int_t t2 = t1 + 1; t2 < Tracks_; t2++) { // transverse momentum Float_t pt2 = TMath::Sqrt(Tracks_fPxRec[t2] * Tracks_fPxRec[t2] + Tracks_fPyRec[t2] * Tracks_fPyRec[t2]); // chi2 per d.o.f. Float_t ch2 = Tracks_fChi2[t2] / (2.0 * Tracks_fNHits[t2] - 5); // condition for good track (Chi2Cut and PtCut) if ((ch2 < Chi2Cut) && (pt2 > PtCut)) { // condition for opposite charges if ((Tracks_fCharge[t1] * Tracks_fCharge[t2]) == -1) { // invariant mass Float_t invMass = MuPlusMuMinusMass(Tracks_fPxRec[t1], Tracks_fPyRec[t1], Tracks_fPzRec[t1], Tracks_fPxRec[t2], Tracks_fPyRec[t2], Tracks_fPzRec[t2]); // fill histos hInvMassAll and hInvMassRes hInvMassAll->Fill(invMass); hInvMassRes->Fill(invMass); } //if ((Tracks_fCharge[t1] * Tracks_fCharge[t2]) == -1) } // if ((Tracks_fChi2[t2] < Chi2Cut) && (pt2 > PtCut)) } // for (Int_t t2 = t1 + 1; t2 < Tracks_; t2++) } // if ((Tracks_fChi2[t1] < Chi2Cut) && (pt1 > PtCut)) } // for (Int_t t1 = 0; t1 < Tracks_; t1++) } // for (Int_t event = FirstEvent; histoFile->Write(); histoFile->Close(); } Float_t MuPlusMuMinusMass(Float_t Px1, Float_t Py1, Float_t Pz1, Float_t Px2, Float_t Py2, Float_t Pz2) { Float_t muonMass = 0.10566; Float_t e1 = TMath::Sqrt(muonMass * muonMass + Px1 * Px1 + Py1 * Py1 + Pz1 * Pz1); Float_t e2 = TMath::Sqrt(muonMass * muonMass + Px2 * Px2 + Py2 * Py2 + Pz2 * Pz2); return (TMath::Sqrt(2.0 * (muonMass * muonMass + e1 * e2 - Px1 * Px2 - Py1 * Py2 - Pz1 * Pz2))); } <commit_msg>Corrections for running with last Root and AliRoot versions: see important comments at the beginning of the macro<commit_after>// macro to make invariant mass plots // for combinations of 2 muons with opposite charges, // from root file "MUONtrackReco.root" containing the result of track reconstruction, // generated by the macro "MUONrecoNtuple.C". // Histograms are stored on the "MUONmassPlot.root" file. // A model for macros using the Ntuple in the file "MUONtrackReco.root" // may be found in "MUONtrackRecoModel.C": // it has been obtained by reading with Root a file "MUONtrackReco.root", // and executing the command: // MUONtrackReco->MakeCode("MUONtrackRecoModel.C") // Arguments: // FirstEvent (default 0) // LastEvent (default 0) // ResType (default 553) // 553 for Upsilon, anything else for J/Psi // NSigma (default 3) // the number of combinations is counted around the resonance mass // within +/- NSigma times the nominal sigma's // (0.099 GeV for Upsilon, 0.0615 GeV for J/Psi) // Chi2Cut (default 100) // to keep only tracks with chi2 per d.o.f. < Chi2Cut // PtCut (default 1) // to keep only tracks with transverse momentum > PtCut // IMPORTANT NOTICE FOR USERS: // under "root" or "root.exe", execute the following commands: // 1. "gSystem->SetIncludePath("-I$ALICE_ROOT/MUON -I$ALICE_ROOT/STEER")" to get the right path at compilation time // 2. ".x loadlibs.C" to load the shared libraries // 3. ".L MUONrecoNtuple.C+" // 4. ".x MUONmassPlot.C()" with the right arguments according to the list above void MUONmassPlot(Int_t FirstEvent = 0, Int_t LastEvent = 0, Int_t ResType = 553, Float_t Nsig = 3., Float_t Chi2Cut = 100., Float_t PtCut = 1.) { cout << "MUONmassPlot" << endl; cout << "FirstEvent" << FirstEvent << endl; cout << "LastEvent" << LastEvent << endl; cout << "ResType" << ResType << endl; cout << "Nsig" << Nsig << endl; cout << "Chi2Cut" << Chi2Cut << endl; cout << "PtCut" << PtCut << endl; ////////////////////////////////////////////////////////// // This file has been automatically generated // (Thu Sep 21 14:53:11 2000 by ROOT version2.25/02) // from TTree MUONtrackReco/MUONtrackReco // found on file: MUONtrackReco.root ////////////////////////////////////////////////////////// //Reset ROOT and connect tree file gROOT->Reset(); TFile *f = (TFile*)gROOT->GetListOfFiles()->FindObject("MUONtrackReco.root"); if (!f) { f = new TFile("MUONtrackReco.root"); } TTree *MUONtrackReco = (TTree*)gDirectory->Get("MUONtrackReco"); MUONtrackReco->SetMakeClass(1); //Declaration of leaves types Int_t fEvent; UInt_t fUniqueID; UInt_t fBits; Int_t Tracks_; Int_t Tracks_fCharge[5]; Float_t Tracks_fPxRec[5]; Float_t Tracks_fPyRec[5]; Float_t Tracks_fPzRec[5]; Float_t Tracks_fZRec[5]; Float_t Tracks_fZRec1[5]; Int_t Tracks_fNHits[5]; Float_t Tracks_fChi2[5]; Float_t Tracks_fPxGen[5]; Float_t Tracks_fPyGen[5]; Float_t Tracks_fPzGen[5]; UInt_t Tracks_fUniqueID[5]; UInt_t Tracks_fBits[5]; //Set branch addresses //MUONtrackReco->SetBranchAddress("Header",&Header); MUONtrackReco->SetBranchAddress("fEvent",&fEvent); MUONtrackReco->SetBranchAddress("fUniqueID",&fUniqueID); MUONtrackReco->SetBranchAddress("fBits",&fBits); // MUONtrackReco->SetBranchAddress("Tracks_",&Tracks_); MUONtrackReco->SetBranchAddress("Tracks",&Tracks_); MUONtrackReco->SetBranchAddress("Tracks.fCharge",Tracks_fCharge); MUONtrackReco->SetBranchAddress("Tracks.fPxRec",Tracks_fPxRec); MUONtrackReco->SetBranchAddress("Tracks.fPyRec",Tracks_fPyRec); MUONtrackReco->SetBranchAddress("Tracks.fPzRec",Tracks_fPzRec); MUONtrackReco->SetBranchAddress("Tracks.fZRec",Tracks_fZRec); MUONtrackReco->SetBranchAddress("Tracks.fZRec1",Tracks_fZRec1); MUONtrackReco->SetBranchAddress("Tracks.fNHits",Tracks_fNHits); MUONtrackReco->SetBranchAddress("Tracks.fChi2",Tracks_fChi2); MUONtrackReco->SetBranchAddress("Tracks.fPxGen",Tracks_fPxGen); MUONtrackReco->SetBranchAddress("Tracks.fPyGen",Tracks_fPyGen); MUONtrackReco->SetBranchAddress("Tracks.fPzGen",Tracks_fPzGen); MUONtrackReco->SetBranchAddress("Tracks.fUniqueID",Tracks_fUniqueID); MUONtrackReco->SetBranchAddress("Tracks.fBits",Tracks_fBits); // This is the loop skeleton // To read only selected branches, Insert statements like: // MUONtrackReco->SetBranchStatus("*",0); // disable all branches // TTreePlayer->SetBranchStatus("branchname",1); // activate branchname Int_t nentries = MUONtrackReco->GetEntries(); Int_t nbytes = 0; // for (Int_t i=0; i<nentries;i++) { // nbytes += MUONtrackReco->GetEntry(i); // } ///////////////////////////////////////////////////////////////// // Here comes the specialized part for MUONmassPlot ///////////////////////////////////////////////////////////////// // File for histograms and histogram booking TFile *histoFile = new TFile("MUONmassPlot.root", "RECREATE"); TH1F *hPtMuon = new TH1F("hPtMuon", "Muon Pt (GeV/c)", 100, 0., 20.); TH1F *hChi2PerDof = new TH1F("hChi2PerDof", "Muon track chi2/d.o.f.", 100, 0., 20.); TH1F *hInvMassAll = new TH1F("hInvMassAll", "Mu+Mu- invariant mass (GeV/c2)", 240, 0., 12.); if (ResType = 553) TH1F *hInvMassRes = new TH1F("hInvMassRes", "Mu+Mu- invariant mass (GeV/c2) around Upsilon", 60, 8., 11.); else TH1F *hInvMassRes = new TH1F("hInvMassRes", "Mu+Mu- invariant mass (GeV/c2) around J/Psi", 80, 1., 5.); // Loop over events for (Int_t event = FirstEvent; event <= TMath::Min(LastEvent, nentries - 1); event++) { // get current event nbytes += MUONtrackReco->GetEntry(event); // loop over all reconstructed tracks (also first track of combination) for (Int_t t1 = 0; t1 < Tracks_; t1++) { // transverse momentum Float_t pt1 = TMath::Sqrt(Tracks_fPxRec[t1] * Tracks_fPxRec[t1] + Tracks_fPyRec[t1] * Tracks_fPyRec[t1]); // chi2 per d.o.f. Float_t ch1 = Tracks_fChi2[t1] / (2.0 * Tracks_fNHits[t1] - 5); // condition for good track (Chi2Cut and PtCut) if ((ch1 < Chi2Cut) && (pt1 > PtCut)) { // fill histos hPtMuon and hChi2PerDof hPtMuon->Fill(pt1); hChi2PerDof->Fill(ch1); // loop over second track of combination for (Int_t t2 = t1 + 1; t2 < Tracks_; t2++) { // transverse momentum Float_t pt2 = TMath::Sqrt(Tracks_fPxRec[t2] * Tracks_fPxRec[t2] + Tracks_fPyRec[t2] * Tracks_fPyRec[t2]); // chi2 per d.o.f. Float_t ch2 = Tracks_fChi2[t2] / (2.0 * Tracks_fNHits[t2] - 5); // condition for good track (Chi2Cut and PtCut) if ((ch2 < Chi2Cut) && (pt2 > PtCut)) { // condition for opposite charges if ((Tracks_fCharge[t1] * Tracks_fCharge[t2]) == -1) { // invariant mass Float_t invMass = MuPlusMuMinusMass(Tracks_fPxRec[t1], Tracks_fPyRec[t1], Tracks_fPzRec[t1], Tracks_fPxRec[t2], Tracks_fPyRec[t2], Tracks_fPzRec[t2]); // fill histos hInvMassAll and hInvMassRes hInvMassAll->Fill(invMass); hInvMassRes->Fill(invMass); } //if ((Tracks_fCharge[t1] * Tracks_fCharge[t2]) == -1) } // if ((Tracks_fChi2[t2] < Chi2Cut) && (pt2 > PtCut)) } // for (Int_t t2 = t1 + 1; t2 < Tracks_; t2++) } // if ((Tracks_fChi2[t1] < Chi2Cut) && (pt1 > PtCut)) } // for (Int_t t1 = 0; t1 < Tracks_; t1++) } // for (Int_t event = FirstEvent; histoFile->Write(); histoFile->Close(); } Float_t MuPlusMuMinusMass(Float_t Px1, Float_t Py1, Float_t Pz1, Float_t Px2, Float_t Py2, Float_t Pz2) { Float_t muonMass = 0.10566; Float_t e1 = TMath::Sqrt(muonMass * muonMass + Px1 * Px1 + Py1 * Py1 + Pz1 * Pz1); Float_t e2 = TMath::Sqrt(muonMass * muonMass + Px2 * Px2 + Py2 * Py2 + Pz2 * Pz2); return (TMath::Sqrt(2.0 * (muonMass * muonMass + e1 * e2 - Px1 * Px2 - Py1 * Py2 - Pz1 * Pz2))); } <|endoftext|>
<commit_before>#include "Logger.h" #include <iostream> // // (plesslie) // posix_time_zone is just parsing the "-XX" portion and subtracting that from UTC meaning // that it isn't adjusting for daylight savings time. not sure how to fix that, and I don't // really care for now. // Logger::Logger() : ss_(), tz_(new boost::local_time::posix_time_zone("CST-05")), output_facet_(new boost::local_time::local_time_facet()), input_facet_(new boost::local_time::local_time_input_facet()) { ss_.imbue(std::locale(std::locale::classic(), output_facet_)); ss_.imbue(std::locale(ss_.getloc(), input_facet_)); output_facet_->format(boost::local_time::local_time_facet::iso_time_format_extended_specifier); } Logger::~Logger() { delete output_facet_; delete input_facet_; } Logger& Logger::instance() { static Logger logger; return logger; } <commit_msg>Fix delete ordering for input/output facets<commit_after>#include "Logger.h" #include <iostream> // // (plesslie) // posix_time_zone is just parsing the "-XX" portion and subtracting that from UTC meaning // that it isn't adjusting for daylight savings time. not sure how to fix that, and I don't // really care for now. // Logger::Logger() : ss_(), tz_(new boost::local_time::posix_time_zone("CST-05")), output_facet_(new boost::local_time::local_time_facet()), input_facet_(new boost::local_time::local_time_input_facet()) { ss_.imbue(std::locale(std::locale::classic(), output_facet_)); ss_.imbue(std::locale(ss_.getloc(), input_facet_)); output_facet_->format(boost::local_time::local_time_facet::iso_time_format_extended_specifier); } Logger::~Logger() { delete input_facet_; delete output_facet_; } Logger& Logger::instance() { static Logger logger; return logger; } <|endoftext|>
<commit_before>#include <QDebug> #include <QGuiApplication> #include <QScreen> #include "LinuxWindowCapture.h" #include <xcb/xcb_icccm.h> #define WM_WINDOW_INSTANCE "Hearthstone.exe" #define WM_CLASS "Wine" LinuxWindowCapture::LinuxWindowCapture() : mWindow( 0 ) { } bool LinuxWindowCapture::WindowFound() { if ( mWindow == 0 ) mWindow = FindWindow( WM_WINDOW_INSTANCE, WM_CLASS ); if ( mWindow != 0 && !WindowRect() ) mWindow = 0; return mWindow != 0; } int LinuxWindowCapture::Width() { return mRect.width(); } int LinuxWindowCapture::Height() { return mRect.height(); } int LinuxWindowCapture::Left() { return mRect.x(); } int LinuxWindowCapture::Top() { return mRect.y(); } QPixmap LinuxWindowCapture::Capture( int x, int y, int w, int h ) { LOG("Capturing window: %d, %d, %d, %d", x, y, h, w ); QScreen *screen = QGuiApplication::primaryScreen(); QPixmap pixmap = screen->grabWindow( mWindow, x, y, w, h ); return pixmap; } QList< xcb_window_t > LinuxWindowCapture::listWindowsRecursive( xcb_connection_t* dpy, xcb_window_t& window ) { QList< xcb_window_t > windows; xcb_query_tree_reply_t* queryR; xcb_query_tree_cookie_t queryC = xcb_query_tree( dpy, window ); if( ( queryR = xcb_query_tree_reply( dpy, queryC, NULL ) ) ) { xcb_window_t* children = xcb_query_tree_children( queryR ); for( int c = 0; c < xcb_query_tree_children_length( queryR ); ++c ) { windows << children[ c ]; windows << listWindowsRecursive( dpy, children[ c ]); } free( queryR ); } return windows; } bool LinuxWindowCapture::WindowRect() { if( mWindow == 0 ) return false; xcb_connection_t* dpy = xcb_connect( NULL, NULL ); if ( xcb_connection_has_error( dpy ) ) qDebug() << "Can't open display"; xcb_screen_t* screen = xcb_setup_roots_iterator( xcb_get_setup( dpy ) ).data; if( !screen ) qDebug() << "Can't acquire screen"; xcb_get_geometry_cookie_t geometryC = xcb_get_geometry( dpy, mWindow ); xcb_get_geometry_reply_t* geometryR = xcb_get_geometry_reply( dpy, geometryC, NULL ); if( geometryR ) { xcb_translate_coordinates_cookie_t translateC = xcb_translate_coordinates( dpy, mWindow, screen->root, geometryR->x, geometryR->y ); xcb_translate_coordinates_reply_t* translateR = xcb_translate_coordinates_reply( dpy, translateC, NULL ); mRect.setRect( translateR->dst_x, translateR->dst_y, geometryR->width, geometryR->height ); free( geometryR ); free( translateR ); xcb_disconnect( dpy ); return true; } xcb_disconnect( dpy ); return false; } xcb_window_t LinuxWindowCapture::FindWindow( const QString& instanceName, const QString& windowClass ) { xcb_window_t window = static_cast< xcb_window_t > ( 0 ); xcb_connection_t* dpy = xcb_connect( NULL, NULL ); if ( xcb_connection_has_error( dpy ) ) { qDebug() << "Can't open display"; } xcb_screen_t* screen = xcb_setup_roots_iterator( xcb_get_setup( dpy ) ).data; if( !screen ) { qDebug() << "Can't acquire screen"; } xcb_window_t root = screen->root; QList< xcb_window_t > windows = listWindowsRecursive( dpy, root ); foreach( const xcb_window_t& win, windows ) { xcb_icccm_get_wm_class_reply_t wmNameR; xcb_get_property_cookie_t wmClassC = xcb_icccm_get_wm_class( dpy, win ); if ( xcb_icccm_get_wm_class_reply( dpy, wmClassC, &wmNameR, NULL ) ) { if( !qstrcmp( wmNameR.class_name, windowClass.toStdString().c_str() ) && !qstrcmp( wmNameR.instance_name, instanceName.toStdString().c_str() ) ) { qDebug() << wmNameR.instance_name; qDebug() << wmNameR.class_name; window = win; break; } } } xcb_disconnect( dpy ); return window; } bool LinuxWindowCapture::Focus() { if( mWindow ) { xcb_window_t focusW; xcb_connection_t* dpy = xcb_connect( NULL, NULL ); if ( xcb_connection_has_error( dpy ) ) { qDebug() << "Can't open display"; } xcb_get_input_focus_cookie_t focusC = xcb_get_input_focus( dpy ); xcb_get_input_focus_reply_t* focusR = xcb_get_input_focus_reply( dpy, focusC, NULL ); focusW = focusR->focus; free( focusR ); xcb_disconnect( dpy ); return focusW == mWindow; } return false; } <commit_msg>Fix HS window tracking<commit_after>#include <QDebug> #include <QGuiApplication> #include <QScreen> #include "LinuxWindowCapture.h" #include <xcb/xcb_icccm.h> #define WM_WINDOW_INSTANCE "Hearthstone.exe" #define WM_CLASS "Wine" LinuxWindowCapture::LinuxWindowCapture() : mWindow( 0 ) { } bool LinuxWindowCapture::WindowFound() { if ( mWindow == 0 ) mWindow = FindWindow( WM_WINDOW_INSTANCE, WM_CLASS ); if ( mWindow != 0 && !WindowRect() ) mWindow = 0; return mWindow != 0; } int LinuxWindowCapture::Width() { return mRect.width(); } int LinuxWindowCapture::Height() { return mRect.height(); } int LinuxWindowCapture::Left() { return mRect.x(); } int LinuxWindowCapture::Top() { return mRect.y(); } QPixmap LinuxWindowCapture::Capture( int x, int y, int w, int h ) { LOG("Capturing window: %d, %d, %d, %d", x, y, h, w ); QScreen *screen = QGuiApplication::primaryScreen(); QPixmap pixmap = screen->grabWindow( mWindow, x, y, w, h ); return pixmap; } QList< xcb_window_t > LinuxWindowCapture::listWindowsRecursive( xcb_connection_t* dpy, xcb_window_t& window ) { QList< xcb_window_t > windows; xcb_query_tree_reply_t* queryR; xcb_query_tree_cookie_t queryC = xcb_query_tree( dpy, window ); if( ( queryR = xcb_query_tree_reply( dpy, queryC, NULL ) ) ) { xcb_window_t* children = xcb_query_tree_children( queryR ); for( int c = 0; c < xcb_query_tree_children_length( queryR ); ++c ) { windows << children[ c ]; windows << listWindowsRecursive( dpy, children[ c ]); } free( queryR ); } return windows; } bool LinuxWindowCapture::WindowRect() { if( mWindow == 0 ) return false; xcb_connection_t* dpy = xcb_connect( NULL, NULL ); if ( xcb_connection_has_error( dpy ) ) qDebug() << "Can't open display"; xcb_screen_t* screen = xcb_setup_roots_iterator( xcb_get_setup( dpy ) ).data; if( !screen ) qDebug() << "Can't acquire screen"; xcb_get_geometry_cookie_t geometryC = xcb_get_geometry( dpy, mWindow ); xcb_get_geometry_reply_t* geometryR = xcb_get_geometry_reply( dpy, geometryC, NULL ); if( geometryR ) { xcb_translate_coordinates_cookie_t translateC = xcb_translate_coordinates( dpy, mWindow, screen->root, geometryR->x, geometryR->y ); xcb_translate_coordinates_reply_t* translateR = xcb_translate_coordinates_reply( dpy, translateC, NULL ); mRect.setRect( translateR->dst_x, translateR->dst_y, geometryR->width, geometryR->height ); free( geometryR ); free( translateR ); xcb_disconnect( dpy ); return true; } xcb_disconnect( dpy ); return false; } xcb_window_t LinuxWindowCapture::FindWindow( const QString& instanceName, const QString& windowClass ) { xcb_window_t window = static_cast< xcb_window_t > ( 0 ); xcb_connection_t* dpy = xcb_connect( NULL, NULL ); if ( xcb_connection_has_error( dpy ) ) { qDebug() << "Can't open display"; } xcb_screen_t* screen = xcb_setup_roots_iterator( xcb_get_setup( dpy ) ).data; if( !screen ) { qDebug() << "Can't acquire screen"; } xcb_window_t root = screen->root; QList< xcb_window_t > windows = listWindowsRecursive( dpy, root ); foreach( const xcb_window_t& win, windows ) { xcb_icccm_get_wm_class_reply_t wmNameR; xcb_get_property_cookie_t wmClassC = xcb_icccm_get_wm_class( dpy, win ); if ( xcb_icccm_get_wm_class_reply( dpy, wmClassC, &wmNameR, NULL ) ) { if( !qstrcmp( wmNameR.class_name, windowClass.toStdString().c_str() ) || !qstrcmp( wmNameR.instance_name, instanceName.toStdString().c_str() ) ) { qDebug() << wmNameR.instance_name; qDebug() << wmNameR.class_name; window = win; break; } } } xcb_disconnect( dpy ); return window; } bool LinuxWindowCapture::Focus() { if( mWindow ) { xcb_window_t focusW; xcb_connection_t* dpy = xcb_connect( NULL, NULL ); if ( xcb_connection_has_error( dpy ) ) { qDebug() << "Can't open display"; } xcb_get_input_focus_cookie_t focusC = xcb_get_input_focus( dpy ); xcb_get_input_focus_reply_t* focusR = xcb_get_input_focus_reply( dpy, focusC, NULL ); focusW = focusR->focus; free( focusR ); xcb_disconnect( dpy ); return focusW == mWindow; } return false; } <|endoftext|>
<commit_before>// Copyright 2008-present Contributors to the OpenImageIO project. // SPDX-License-Identifier: BSD-3-Clause // https://github.com/OpenImageIO/oiio/blob/master/LICENSE.md /// \file /// Implementation of ImageBufAlgo algorithms that merely move pixels /// or channels between images without altering their values. #include <OpenEXR/half.h> #include <cmath> #include <iostream> #include <OpenImageIO/deepdata.h> #include <OpenImageIO/imagebuf.h> #include <OpenImageIO/imagebufalgo.h> #include <OpenImageIO/imagebufalgo_util.h> #include <OpenImageIO/thread.h> #include "imageio_pvt.h" OIIO_NAMESPACE_BEGIN template<class D, class S> static bool paste_(ImageBuf& dst, const ImageBuf& src, ROI dstroi, ROI srcroi, int nthreads) { // N.B. Punt on parallelizing because of the subtle interplay // between srcroi and dstroi, the parallel_image idiom doesn't // handle that especially well. And it's not worth customizing for // this function which is inexpensive and not commonly used, and so // would benefit little from parallelizing. We can always revisit // this later. But in the mean time, we maintain the 'nthreads' // parameter for uniformity with the rest of IBA. int src_nchans = src.nchannels(); int dst_nchans = dst.nchannels(); ImageBuf::ConstIterator<S, D> s(src, srcroi); ImageBuf::Iterator<D, D> d(dst, dstroi); for (; !s.done(); ++s, ++d) { if (!d.exists()) continue; // Skip paste-into pixels that don't overlap dst's data for (int c = srcroi.chbegin, c_dst = dstroi.chbegin; c < srcroi.chend; ++c, ++c_dst) { if (c_dst >= 0 && c_dst < dst_nchans) d[c_dst] = c < src_nchans ? s[c] : D(0); } } return true; } bool ImageBufAlgo::paste(ImageBuf& dst, int xbegin, int ybegin, int zbegin, int chbegin, const ImageBuf& src, ROI srcroi, int nthreads) { pvt::LoggedTimer logtime("IBA::paste"); if (!srcroi.defined()) srcroi = get_roi(src.spec()); ROI dstroi(xbegin, xbegin + srcroi.width(), ybegin, ybegin + srcroi.height(), zbegin, zbegin + srcroi.depth(), chbegin, chbegin + srcroi.nchannels()); ROI dstroi_save = dstroi; // save the original if (!IBAprep(dstroi, &dst)) return false; // do the actual copying bool ok; OIIO_DISPATCH_COMMON_TYPES2(ok, "paste", paste_, dst.spec().format, src.spec().format, dst, src, dstroi_save, srcroi, nthreads); return ok; } template<class D, class S> static bool copy_(ImageBuf& dst, const ImageBuf& src, ROI roi, int nthreads = 1) { using namespace ImageBufAlgo; parallel_image(roi, nthreads, [&](ROI roi) { ImageBuf::ConstIterator<S, D> s(src, roi); ImageBuf::Iterator<D, D> d(dst, roi); for (; !d.done(); ++d, ++s) { for (int c = roi.chbegin; c < roi.chend; ++c) d[c] = s[c]; } }); return true; } static bool copy_deep(ImageBuf& dst, const ImageBuf& src, ROI roi, int nthreads = 1) { ASSERT(dst.deep() && src.deep()); using namespace ImageBufAlgo; parallel_image(roi, nthreads, [&](ROI roi) { DeepData& dstdeep(*dst.deepdata()); const DeepData& srcdeep(*src.deepdata()); ImageBuf::ConstIterator<float> s(src, roi); for (ImageBuf::Iterator<float> d(dst, roi); !d.done(); ++d, ++s) { int samples = s.deep_samples(); // The caller should ALREADY have set the samples, since that // is not thread-safe against the copying below. // d.set_deep_samples (samples); DASSERT(d.deep_samples() == samples); if (samples == 0) continue; for (int c = roi.chbegin; c < roi.chend; ++c) { if (dstdeep.channeltype(c) == TypeDesc::UINT32 && srcdeep.channeltype(c) == TypeDesc::UINT32) for (int samp = 0; samp < samples; ++samp) d.set_deep_value(c, samp, (uint32_t)s.deep_value_uint(c, samp)); else for (int samp = 0; samp < samples; ++samp) d.set_deep_value(c, samp, (float)s.deep_value(c, samp)); } } }); return true; } bool ImageBufAlgo::copy(ImageBuf& dst, const ImageBuf& src, TypeDesc convert, ROI roi, int nthreads) { pvt::LoggedTimer logtime("IBA::copy"); if (&dst == &src) // trivial copy to self return true; roi.chend = std::min(roi.chend, src.nchannels()); if (!dst.initialized()) { ImageSpec newspec = src.spec(); if (!roi.defined()) roi = src.roi(); set_roi(newspec, roi); newspec.nchannels = roi.chend; if (convert != TypeUnknown) newspec.set_format(convert); dst.reset(newspec); } IBAprep(roi, &dst, &src, IBAprep_SUPPORT_DEEP); if (dst.deep()) { // If it's deep, figure out the sample allocations first, because // it's not thread-safe to do that simultaneously with copying the // values. ImageBuf::ConstIterator<float> s(src, roi); for (ImageBuf::Iterator<float> d(dst, roi); !d.done(); ++d, ++s) d.set_deep_samples(s.deep_samples()); return copy_deep(dst, src, roi, nthreads); } if (src.localpixels() && src.roi().contains(roi)) { // Easy case -- if the buffer is already fully in memory and the roi // is completely contained in the pixel window, this reduces to a // parallel_convert_image, which is both threaded and already // handles many special cases. return parallel_convert_image( roi.nchannels(), roi.width(), roi.height(), roi.depth(), src.pixeladdr(roi.xbegin, roi.ybegin, roi.zbegin, roi.chbegin), src.spec().format, src.pixel_stride(), src.scanline_stride(), src.z_stride(), dst.pixeladdr(roi.xbegin, roi.ybegin, roi.zbegin, roi.chbegin), dst.spec().format, dst.pixel_stride(), dst.scanline_stride(), dst.z_stride(), nthreads); } bool ok; OIIO_DISPATCH_TYPES2(ok, "copy", copy_, dst.spec().format, src.spec().format, dst, src, roi, nthreads); return ok; } ImageBuf ImageBufAlgo::copy(const ImageBuf& src, TypeDesc convert, ROI roi, int nthreads) { ImageBuf result; bool ok = copy(result, src, convert, roi, nthreads); if (!ok && !result.has_error()) result.error("ImageBufAlgo::copy() error"); return result; } bool ImageBufAlgo::crop(ImageBuf& dst, const ImageBuf& src, ROI roi, int nthreads) { pvt::LoggedTimer logtime("IBA::crop"); dst.clear(); roi.chend = std::min(roi.chend, src.nchannels()); if (!IBAprep(roi, &dst, &src, IBAprep_SUPPORT_DEEP)) return false; if (dst.deep()) { // If it's deep, figure out the sample allocations first, because // it's not thread-safe to do that simultaneously with copying the // values. ImageBuf::ConstIterator<float> s(src, roi); for (ImageBuf::Iterator<float> d(dst, roi); !d.done(); ++d, ++s) d.set_deep_samples(s.deep_samples()); return copy_deep(dst, src, roi, nthreads); } if (src.localpixels() && src.roi().contains(roi)) { // Easy case -- if the buffer is already fully in memory and the roi // is completely contained in the pixel window, this reduces to a // parallel_convert_image, which is both threaded and already // handles many special cases. return parallel_convert_image( roi.nchannels(), roi.width(), roi.height(), roi.depth(), src.pixeladdr(roi.xbegin, roi.ybegin, roi.zbegin, roi.chbegin), src.spec().format, src.pixel_stride(), src.scanline_stride(), src.z_stride(), dst.pixeladdr(roi.xbegin, roi.ybegin, roi.zbegin, roi.chbegin), dst.spec().format, dst.pixel_stride(), dst.scanline_stride(), dst.z_stride(), nthreads); } bool ok; OIIO_DISPATCH_TYPES2(ok, "crop", copy_, dst.spec().format, src.spec().format, dst, src, roi, nthreads); return ok; } ImageBuf ImageBufAlgo::crop(const ImageBuf& src, ROI roi, int nthreads) { ImageBuf result; bool ok = crop(result, src, roi, nthreads); if (!ok && !result.has_error()) result.error("ImageBufAlgo::crop() error"); return result; } bool ImageBufAlgo::cut(ImageBuf& dst, const ImageBuf& src, ROI roi, int nthreads) { pvt::LoggedTimer logtime("IBA::cut"); bool ok = crop(dst, src, roi, nthreads); ASSERT(ok); if (!ok) return false; // Crop did the heavy lifting of copying the roi of pixels from src to // dst, but now we need to make it look like we cut that rectangle out // and repositioned it at the origin. dst.specmod().x = 0; dst.specmod().y = 0; dst.specmod().z = 0; dst.set_roi_full(dst.roi()); return true; } ImageBuf ImageBufAlgo::cut(const ImageBuf& src, ROI roi, int nthreads) { ImageBuf result; bool ok = cut(result, src, roi, nthreads); if (!ok && !result.has_error()) result.error("ImageBufAlgo::cut() error"); return result; } template<typename DSTTYPE, typename SRCTYPE> static bool circular_shift_(ImageBuf& dst, const ImageBuf& src, int xshift, int yshift, int zshift, ROI dstroi, ROI roi, int nthreads) { ImageBufAlgo::parallel_image(roi, nthreads, [&](ROI roi) { int width = dstroi.width(), height = dstroi.height(), depth = dstroi.depth(); ImageBuf::ConstIterator<SRCTYPE, DSTTYPE> s(src, roi); ImageBuf::Iterator<DSTTYPE, DSTTYPE> d(dst); for (; !s.done(); ++s) { int dx = s.x() + xshift; OIIO::wrap_periodic(dx, dstroi.xbegin, width); int dy = s.y() + yshift; OIIO::wrap_periodic(dy, dstroi.ybegin, height); int dz = s.z() + zshift; OIIO::wrap_periodic(dz, dstroi.zbegin, depth); d.pos(dx, dy, dz); if (!d.exists()) continue; for (int c = roi.chbegin; c < roi.chend; ++c) d[c] = s[c]; } }); return true; } bool ImageBufAlgo::circular_shift(ImageBuf& dst, const ImageBuf& src, int xshift, int yshift, int zshift, ROI roi, int nthreads) { pvt::LoggedTimer logtime("IBA::circular_shift"); if (!IBAprep(roi, &dst, &src)) return false; bool ok; OIIO_DISPATCH_COMMON_TYPES2(ok, "circular_shift", circular_shift_, dst.spec().format, src.spec().format, dst, src, xshift, yshift, zshift, roi, roi, nthreads); return ok; } ImageBuf ImageBufAlgo::circular_shift(const ImageBuf& src, int xshift, int yshift, int zshift, ROI roi, int nthreads) { ImageBuf result; bool ok = circular_shift(result, src, xshift, yshift, zshift, roi, nthreads); if (!ok && !result.has_error()) result.error("ImageBufAlgo::circular_shift() error"); return result; } OIIO_NAMESPACE_END <commit_msg>Remove wayward assertion (#2328)<commit_after>// Copyright 2008-present Contributors to the OpenImageIO project. // SPDX-License-Identifier: BSD-3-Clause // https://github.com/OpenImageIO/oiio/blob/master/LICENSE.md /// \file /// Implementation of ImageBufAlgo algorithms that merely move pixels /// or channels between images without altering their values. #include <OpenEXR/half.h> #include <cmath> #include <iostream> #include <OpenImageIO/deepdata.h> #include <OpenImageIO/imagebuf.h> #include <OpenImageIO/imagebufalgo.h> #include <OpenImageIO/imagebufalgo_util.h> #include <OpenImageIO/thread.h> #include "imageio_pvt.h" OIIO_NAMESPACE_BEGIN template<class D, class S> static bool paste_(ImageBuf& dst, const ImageBuf& src, ROI dstroi, ROI srcroi, int nthreads) { // N.B. Punt on parallelizing because of the subtle interplay // between srcroi and dstroi, the parallel_image idiom doesn't // handle that especially well. And it's not worth customizing for // this function which is inexpensive and not commonly used, and so // would benefit little from parallelizing. We can always revisit // this later. But in the mean time, we maintain the 'nthreads' // parameter for uniformity with the rest of IBA. int src_nchans = src.nchannels(); int dst_nchans = dst.nchannels(); ImageBuf::ConstIterator<S, D> s(src, srcroi); ImageBuf::Iterator<D, D> d(dst, dstroi); for (; !s.done(); ++s, ++d) { if (!d.exists()) continue; // Skip paste-into pixels that don't overlap dst's data for (int c = srcroi.chbegin, c_dst = dstroi.chbegin; c < srcroi.chend; ++c, ++c_dst) { if (c_dst >= 0 && c_dst < dst_nchans) d[c_dst] = c < src_nchans ? s[c] : D(0); } } return true; } bool ImageBufAlgo::paste(ImageBuf& dst, int xbegin, int ybegin, int zbegin, int chbegin, const ImageBuf& src, ROI srcroi, int nthreads) { pvt::LoggedTimer logtime("IBA::paste"); if (!srcroi.defined()) srcroi = get_roi(src.spec()); ROI dstroi(xbegin, xbegin + srcroi.width(), ybegin, ybegin + srcroi.height(), zbegin, zbegin + srcroi.depth(), chbegin, chbegin + srcroi.nchannels()); ROI dstroi_save = dstroi; // save the original if (!IBAprep(dstroi, &dst)) return false; // do the actual copying bool ok; OIIO_DISPATCH_COMMON_TYPES2(ok, "paste", paste_, dst.spec().format, src.spec().format, dst, src, dstroi_save, srcroi, nthreads); return ok; } template<class D, class S> static bool copy_(ImageBuf& dst, const ImageBuf& src, ROI roi, int nthreads = 1) { using namespace ImageBufAlgo; parallel_image(roi, nthreads, [&](ROI roi) { ImageBuf::ConstIterator<S, D> s(src, roi); ImageBuf::Iterator<D, D> d(dst, roi); for (; !d.done(); ++d, ++s) { for (int c = roi.chbegin; c < roi.chend; ++c) d[c] = s[c]; } }); return true; } static bool copy_deep(ImageBuf& dst, const ImageBuf& src, ROI roi, int nthreads = 1) { ASSERT(dst.deep() && src.deep()); using namespace ImageBufAlgo; parallel_image(roi, nthreads, [&](ROI roi) { DeepData& dstdeep(*dst.deepdata()); const DeepData& srcdeep(*src.deepdata()); ImageBuf::ConstIterator<float> s(src, roi); for (ImageBuf::Iterator<float> d(dst, roi); !d.done(); ++d, ++s) { int samples = s.deep_samples(); // The caller should ALREADY have set the samples, since that // is not thread-safe against the copying below. // d.set_deep_samples (samples); DASSERT(d.deep_samples() == samples); if (samples == 0) continue; for (int c = roi.chbegin; c < roi.chend; ++c) { if (dstdeep.channeltype(c) == TypeDesc::UINT32 && srcdeep.channeltype(c) == TypeDesc::UINT32) for (int samp = 0; samp < samples; ++samp) d.set_deep_value(c, samp, (uint32_t)s.deep_value_uint(c, samp)); else for (int samp = 0; samp < samples; ++samp) d.set_deep_value(c, samp, (float)s.deep_value(c, samp)); } } }); return true; } bool ImageBufAlgo::copy(ImageBuf& dst, const ImageBuf& src, TypeDesc convert, ROI roi, int nthreads) { pvt::LoggedTimer logtime("IBA::copy"); if (&dst == &src) // trivial copy to self return true; roi.chend = std::min(roi.chend, src.nchannels()); if (!dst.initialized()) { ImageSpec newspec = src.spec(); if (!roi.defined()) roi = src.roi(); set_roi(newspec, roi); newspec.nchannels = roi.chend; if (convert != TypeUnknown) newspec.set_format(convert); dst.reset(newspec); } IBAprep(roi, &dst, &src, IBAprep_SUPPORT_DEEP); if (dst.deep()) { // If it's deep, figure out the sample allocations first, because // it's not thread-safe to do that simultaneously with copying the // values. ImageBuf::ConstIterator<float> s(src, roi); for (ImageBuf::Iterator<float> d(dst, roi); !d.done(); ++d, ++s) d.set_deep_samples(s.deep_samples()); return copy_deep(dst, src, roi, nthreads); } if (src.localpixels() && src.roi().contains(roi)) { // Easy case -- if the buffer is already fully in memory and the roi // is completely contained in the pixel window, this reduces to a // parallel_convert_image, which is both threaded and already // handles many special cases. return parallel_convert_image( roi.nchannels(), roi.width(), roi.height(), roi.depth(), src.pixeladdr(roi.xbegin, roi.ybegin, roi.zbegin, roi.chbegin), src.spec().format, src.pixel_stride(), src.scanline_stride(), src.z_stride(), dst.pixeladdr(roi.xbegin, roi.ybegin, roi.zbegin, roi.chbegin), dst.spec().format, dst.pixel_stride(), dst.scanline_stride(), dst.z_stride(), nthreads); } bool ok; OIIO_DISPATCH_TYPES2(ok, "copy", copy_, dst.spec().format, src.spec().format, dst, src, roi, nthreads); return ok; } ImageBuf ImageBufAlgo::copy(const ImageBuf& src, TypeDesc convert, ROI roi, int nthreads) { ImageBuf result; bool ok = copy(result, src, convert, roi, nthreads); if (!ok && !result.has_error()) result.error("ImageBufAlgo::copy() error"); return result; } bool ImageBufAlgo::crop(ImageBuf& dst, const ImageBuf& src, ROI roi, int nthreads) { pvt::LoggedTimer logtime("IBA::crop"); dst.clear(); roi.chend = std::min(roi.chend, src.nchannels()); if (!IBAprep(roi, &dst, &src, IBAprep_SUPPORT_DEEP)) return false; if (dst.deep()) { // If it's deep, figure out the sample allocations first, because // it's not thread-safe to do that simultaneously with copying the // values. ImageBuf::ConstIterator<float> s(src, roi); for (ImageBuf::Iterator<float> d(dst, roi); !d.done(); ++d, ++s) d.set_deep_samples(s.deep_samples()); return copy_deep(dst, src, roi, nthreads); } if (src.localpixels() && src.roi().contains(roi)) { // Easy case -- if the buffer is already fully in memory and the roi // is completely contained in the pixel window, this reduces to a // parallel_convert_image, which is both threaded and already // handles many special cases. return parallel_convert_image( roi.nchannels(), roi.width(), roi.height(), roi.depth(), src.pixeladdr(roi.xbegin, roi.ybegin, roi.zbegin, roi.chbegin), src.spec().format, src.pixel_stride(), src.scanline_stride(), src.z_stride(), dst.pixeladdr(roi.xbegin, roi.ybegin, roi.zbegin, roi.chbegin), dst.spec().format, dst.pixel_stride(), dst.scanline_stride(), dst.z_stride(), nthreads); } bool ok; OIIO_DISPATCH_TYPES2(ok, "crop", copy_, dst.spec().format, src.spec().format, dst, src, roi, nthreads); return ok; } ImageBuf ImageBufAlgo::crop(const ImageBuf& src, ROI roi, int nthreads) { ImageBuf result; bool ok = crop(result, src, roi, nthreads); if (!ok && !result.has_error()) result.error("ImageBufAlgo::crop() error"); return result; } bool ImageBufAlgo::cut(ImageBuf& dst, const ImageBuf& src, ROI roi, int nthreads) { pvt::LoggedTimer logtime("IBA::cut"); bool ok = crop(dst, src, roi, nthreads); if (!ok) return false; // Crop did the heavy lifting of copying the roi of pixels from src to // dst, but now we need to make it look like we cut that rectangle out // and repositioned it at the origin. dst.specmod().x = 0; dst.specmod().y = 0; dst.specmod().z = 0; dst.set_roi_full(dst.roi()); return true; } ImageBuf ImageBufAlgo::cut(const ImageBuf& src, ROI roi, int nthreads) { ImageBuf result; bool ok = cut(result, src, roi, nthreads); if (!ok && !result.has_error()) result.error("ImageBufAlgo::cut() error"); return result; } template<typename DSTTYPE, typename SRCTYPE> static bool circular_shift_(ImageBuf& dst, const ImageBuf& src, int xshift, int yshift, int zshift, ROI dstroi, ROI roi, int nthreads) { ImageBufAlgo::parallel_image(roi, nthreads, [&](ROI roi) { int width = dstroi.width(), height = dstroi.height(), depth = dstroi.depth(); ImageBuf::ConstIterator<SRCTYPE, DSTTYPE> s(src, roi); ImageBuf::Iterator<DSTTYPE, DSTTYPE> d(dst); for (; !s.done(); ++s) { int dx = s.x() + xshift; OIIO::wrap_periodic(dx, dstroi.xbegin, width); int dy = s.y() + yshift; OIIO::wrap_periodic(dy, dstroi.ybegin, height); int dz = s.z() + zshift; OIIO::wrap_periodic(dz, dstroi.zbegin, depth); d.pos(dx, dy, dz); if (!d.exists()) continue; for (int c = roi.chbegin; c < roi.chend; ++c) d[c] = s[c]; } }); return true; } bool ImageBufAlgo::circular_shift(ImageBuf& dst, const ImageBuf& src, int xshift, int yshift, int zshift, ROI roi, int nthreads) { pvt::LoggedTimer logtime("IBA::circular_shift"); if (!IBAprep(roi, &dst, &src)) return false; bool ok; OIIO_DISPATCH_COMMON_TYPES2(ok, "circular_shift", circular_shift_, dst.spec().format, src.spec().format, dst, src, xshift, yshift, zshift, roi, roi, nthreads); return ok; } ImageBuf ImageBufAlgo::circular_shift(const ImageBuf& src, int xshift, int yshift, int zshift, ROI roi, int nthreads) { ImageBuf result; bool ok = circular_shift(result, src, xshift, yshift, zshift, roi, nthreads); if (!ok && !result.has_error()) result.error("ImageBufAlgo::circular_shift() error"); return result; } OIIO_NAMESPACE_END <|endoftext|>
<commit_before>/* --------------------------------------------------------------------- * Numenta Platform for Intelligent Computing (NuPIC) * Copyright (C) 2013, Numenta, Inc. Unless you have an agreement * with Numenta, Inc., for a separate 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 * Utility functions */ #ifndef NTA_UTILS_HPP #define NTA_UTILS_HPP #include <nta/types/types.hpp> namespace utils { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-aliasing" inline bool isSystemLittleEndian() // TODO same fn is in nta/math/utils.hpp, deduplicate! { static const char test[2] = { 1, 0 }; return (*(short *) test) == 1; } #pragma GCC diagnostic pop template<typename T> inline void swapBytesInPlace(T *pxIn, nta::Size n) { union SwapType { T x; unsigned char b[sizeof(T)]; }; SwapType *px = reinterpret_cast<SwapType *>(pxIn); SwapType *pxend = px + n; const int stop = sizeof(T) / 2; for(; px!=pxend; ++px) { for(int j=0; j<stop; ++j) std::swap(px->b[j], px->b[sizeof(T)-j-1]); } } template<typename T> inline void swapBytes(T *pxOut, nta::Size n, const T *pxIn) { NTA_ASSERT(pxOut != pxIn) << "Use swapBytesInPlace() instead."; NTA_ASSERT(!(((pxOut > pxIn) && (pxOut < (pxIn+n))) || ((pxIn > pxOut) && (pxIn < (pxOut+n))))) << "Overlapping ranges not supported."; union SwapType { T x; unsigned char b[sizeof(T)]; }; const SwapType *px0 = reinterpret_cast<SwapType *>(pxIn); const SwapType *pxend = px0 + n; SwapType *px1 = reinterpret_cast<SwapType *>(pxOut); for(; px0!=pxend; ++px0, ++px1) { for(int j=0; j<sizeof(T); ++j) px1->b[j] = px0->b[sizeof(T)-j-1]; } } } // end of namespace nta #endif <commit_msg>Deduplicate utils.hpp<commit_after><|endoftext|>
<commit_before>/** * @file AGLParameters.cpp * * @author <a href="mailto:scheunem@informatik.hu-berlin.de">Marcus Scheunemann</a> * */ #include "AGLParameters.h" #include "Tools/Debug/DebugParameterList.h" AGLParameters::AGLParameters() : ParameterList("AGLParameters") { //Deviation of the second post (seenpost.position + goalwidth), if just one post is seen //PARAMETER_REGISTER(standardDeviationDist) = 500; //in RAD PARAMETER_REGISTER(particleFilter.standardDeviationAngle) = 0.1; PARAMETER_REGISTER(particleFilter.standardDeviationDistance) = 0.3; PARAMETER_REGISTER(particleFilter.motionNoiseDistance) = 100; PARAMETER_REGISTER(particleFilter.motionNoiseRotation) = 0.03; PARAMETER_REGISTER(particleFilter.processNoiseDistance) = 0.3; PARAMETER_REGISTER(particleFilter.processNoiseRotation) = 0.1; PARAMETER_REGISTER(particleFilter.resamplingThreshhold) = 0; PARAMETER_REGISTER(particleFilter.particlesToReset) = 0; PARAMETER_REGISTER(particleFilter.numberOfParticles) = 10; PARAMETER_REGISTER(weightingTreshholdForUpdateWithAngle) = 0.5; PARAMETER_REGISTER(timeFilterRange) = 0.90; //PARAMETER_REGISTER(sigmaWeightingThreshhold) = 0.4; PARAMETER_REGISTER(thresholdCanopy) = 900; PARAMETER_REGISTER(possibleGoalWidhtError) = 200; PARAMETER_REGISTER(deletePFbyTotalWeightingThreshold) = 0.57; // load from the file after registering all parameters syncWithConfig(); DebugParameterList::getInstance().add(this); } AGLParameters::~AGLParameters() { DebugParameterList::getInstance().remove(this); } <commit_msg>working default parameters<commit_after>/** * @file AGLParameters.cpp * * @author <a href="mailto:scheunem@informatik.hu-berlin.de">Marcus Scheunemann</a> * */ #include "AGLParameters.h" #include "Tools/Debug/DebugParameterList.h" AGLParameters::AGLParameters() : ParameterList("AGLParameters") { //Deviation of the second post (seenpost.position + goalwidth), if just one post is seen //PARAMETER_REGISTER(standardDeviationDist) = 500; //in RAD PARAMETER_REGISTER(particleFilter.standardDeviationAngle) = 0.1; PARAMETER_REGISTER(particleFilter.standardDeviationDistance) = 0.1; PARAMETER_REGISTER(particleFilter.motionNoiseDistance) = 100; PARAMETER_REGISTER(particleFilter.motionNoiseRotation) = 0.03; PARAMETER_REGISTER(particleFilter.processNoiseDistance) = 0.01; PARAMETER_REGISTER(particleFilter.processNoiseRotation) = 0.01; PARAMETER_REGISTER(particleFilter.resamplingThreshhold) = 0; PARAMETER_REGISTER(particleFilter.particlesToReset) = 0; PARAMETER_REGISTER(particleFilter.numberOfParticles) = 10; PARAMETER_REGISTER(weightingTreshholdForUpdateWithAngle) = 0.5; PARAMETER_REGISTER(timeFilterRange) = 0.90; //PARAMETER_REGISTER(sigmaWeightingThreshhold) = 0.4; PARAMETER_REGISTER(thresholdCanopy) = 900; PARAMETER_REGISTER(possibleGoalWidhtError) = 200; PARAMETER_REGISTER(deletePFbyTotalWeightingThreshold) = 0.57; // load from the file after registering all parameters syncWithConfig(); DebugParameterList::getInstance().add(this); } AGLParameters::~AGLParameters() { DebugParameterList::getInstance().remove(this); } <|endoftext|>
<commit_before>#include "src/Recorder.h" #include "src/Display.h" #include "src/RobotDetection/Calibrator.h" #include "src/Settings.h" #include <unistd.h> /* For getuid() */ #include <iostream> /* For ofstream */ #include <fstream> /* For ofstream */ using namespace std; string exec_path; Settings* settings = nullptr; void calibrate(int argc, char* argv[]); void printHelp(); void configure(); int main(int argc, char* argv[]) { exec_path = argv[0]; settings = Settings::read("./resources/config.yml"); if(argc == 1) { Display display; display.run(); } else { if(strcmp(argv[1], "start") == 0) { Display display; display.run(); } else if(strcmp(argv[1], "record") == 0) { Recorder recorder(*settings); recorder.run(); } else if(strcmp(argv[1], "calibrate") == 0) calibrate(argc, argv); else if(strcmp(argv[1], "configure") == 0) configure(); else printHelp(); } return 0; } void calibrate(int argc, char* argv[]) { Calibrator *calibrator; if(argc > 2) //There is an option passed to the calibrate function, this means we will be loading from file calibrator = new Calibrator(argv[2]); else { Recorder recorder(*settings); calibrator = new Calibrator(recorder); //TODO: Will now still throw an exception as it is not implemented yet } cout << "Please provide a file name where you want to store the calibration file:" << endl; string filePath; getline(cin, filePath); filePath.append(".yml"); calibrator->writeToFile(filePath); delete calibrator; } void printHelp() { cout << "Usage: " << exec_path << " [COMMAND]" << endl; cout << endl; cout << "Recognises robots and passes the location to Unity3D. Next to that, it attempts to map the world using a 2D top-down image." << endl; cout << endl; cout << "Commands:" << endl; cout << " start Starts the robot recognition. This command can be omitted." << endl; cout << " record Writes camera output to an .avi file with autofocus disabled, useful to create sample data." << endl; cout << " calibrate Extracts features and stores them to a binary file to be used in the main program." << endl; //TODO: Better description cout << " configure Will write a file to /etc/udev/rules.d/ in order to obtain write access to the webcam." << endl; cout << " help Shows this list." << endl; } void configure() { #ifdef __linux__ if(getuid()) { cout << "You must run this command as a root user as we need to write to /etc/udev/rules.d/" << endl; return; } ofstream ruleFile; ruleFile.open("/etc/udev/rules.d/UnityRobot.rules"); ruleFile << "SUBSYSTEM==\"usb\", ATTRS{idVendor}==\"046d\", ATTRS{idProduct}==\"0843\", MODE=\"0666\"\n"; ruleFile << "SUBSYSTEM==\"usb_device\", ATTRS{idVendor}==\"046d\", ATTRS{idProduct}==\"0843\", MODE=\"0666\"\n"; ruleFile.close(); system("sudo /etc/init.d/udev restart"); #elif __WIN32 //TODO: Find if permission error occurs on Windows as well cout << "Configuring udev rules should not be required in Windows." << endl; #endif }<commit_msg>Added guard to unistd include for building on windows.<commit_after>#include "src/Recorder.h" #include "src/Display.h" #include "src/RobotDetection/Calibrator.h" #include "src/Settings.h" #include <iostream> /* For ofstream */ #include <fstream> /* For ofstream */ #ifdef __linux__ #include <unistd.h> /* For getuid() */ #endif using namespace std; string exec_path; Settings* settings = nullptr; void calibrate(int argc, char* argv[]); void printHelp(); void configure(); int main(int argc, char* argv[]) { exec_path = argv[0]; settings = Settings::read("./resources/config.yml"); if(argc == 1) { Display display; display.run(); } else { if(strcmp(argv[1], "start") == 0) { Display display; display.run(); } else if(strcmp(argv[1], "record") == 0) { Recorder recorder(*settings); recorder.run(); } else if(strcmp(argv[1], "calibrate") == 0) calibrate(argc, argv); else if(strcmp(argv[1], "configure") == 0) configure(); else printHelp(); } return 0; } void calibrate(int argc, char* argv[]) { Calibrator *calibrator; if(argc > 2) //There is an option passed to the calibrate function, this means we will be loading from file calibrator = new Calibrator(argv[2]); else { Recorder recorder(*settings); calibrator = new Calibrator(recorder); //TODO: Will now still throw an exception as it is not implemented yet } cout << "Please provide a file name where you want to store the calibration file:" << endl; string filePath; getline(cin, filePath); filePath.append(".yml"); calibrator->writeToFile(filePath); delete calibrator; } void printHelp() { cout << "Usage: " << exec_path << " [COMMAND]" << endl; cout << endl; cout << "Recognises robots and passes the location to Unity3D. Next to that, it attempts to map the world using a 2D top-down image." << endl; cout << endl; cout << "Commands:" << endl; cout << " start Starts the robot recognition. This command can be omitted." << endl; cout << " record Writes camera output to an .avi file with autofocus disabled, useful to create sample data." << endl; cout << " calibrate Extracts features and stores them to a binary file to be used in the main program." << endl; //TODO: Better description cout << " configure Will write a file to /etc/udev/rules.d/ in order to obtain write access to the webcam." << endl; cout << " help Shows this list." << endl; } void configure() { #ifdef __linux__ if(getuid()) { cout << "You must run this command as a root user as we need to write to /etc/udev/rules.d/" << endl; return; } ofstream ruleFile; ruleFile.open("/etc/udev/rules.d/UnityRobot.rules"); ruleFile << "SUBSYSTEM==\"usb\", ATTRS{idVendor}==\"046d\", ATTRS{idProduct}==\"0843\", MODE=\"0666\"\n"; ruleFile << "SUBSYSTEM==\"usb_device\", ATTRS{idVendor}==\"046d\", ATTRS{idProduct}==\"0843\", MODE=\"0666\"\n"; ruleFile.close(); system("sudo /etc/init.d/udev restart"); #elif __WIN32 //TODO: Find if permission error occurs on Windows as well cout << "Configuring udev rules should not be required in Windows." << endl; #endif }<|endoftext|>
<commit_before>/* SWARM Copyright (C) 2012-2022 Torbjorn Rognes and Frederic Mahe This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Contact: Torbjorn Rognes <torognes@ifi.uio.no>, Department of Informatics, University of Oslo, PO Box 1080 Blindern, NO-0316 Oslo, Norway */ #include "swarm.h" #include "db.h" #include "search8.h" #include "search16.h" #include "threads.h" static pthread_mutex_t scan_mutex; static ThreadRunner * search_threads = nullptr; struct search_data { BYTE ** qtable; WORD ** qtable_w; BYTE * dprofile; WORD * dprofile_w; BYTE * hearray; uint64_t * dir_array; uint64_t target_count; uint64_t target_index; }; static struct search_data * sd; static uint64_t master_next; static uint64_t master_length; static uint64_t remainingchunks; static uint64_t * master_targets; static uint64_t * master_scores; static uint64_t * master_diffs; static uint64_t * master_alignlengths; static int master_bits; static uint64_t dirbufferbytes; queryinfo_t query; uint64_t longestdbsequence; void search_alloc(struct search_data * sdp) { constexpr unsigned int one_kilobyte {1024}; constexpr unsigned int nt_per_uint64 {32}; constexpr unsigned int bytes_per_uint64 {8}; dirbufferbytes = bytes_per_uint64 * longestdbsequence * ((longestdbsequence + 3) / 4) * 4; sdp->qtable = new BYTE*[longestdbsequence]; sdp->qtable_w = new WORD*[longestdbsequence]; sdp->dprofile = new BYTE[2 * one_kilobyte]; // 4 * 16 * 32 sdp->dprofile_w = new WORD[2 * one_kilobyte]; // 4 * 2 * 8 * 32 sdp->hearray = new BYTE[longestdbsequence * nt_per_uint64] { }; sdp->dir_array = new uint64_t[dirbufferbytes] { }; } void search_free(struct search_data * sdp) { delete [] sdp->qtable; sdp->qtable = nullptr; delete [] sdp->qtable_w; sdp->qtable_w = nullptr; delete [] sdp->dprofile; sdp->dprofile = nullptr; delete [] sdp->dprofile_w; sdp->dprofile_w = nullptr; delete [] sdp->hearray; sdp->hearray = nullptr; delete [] sdp->dir_array; sdp->dir_array = nullptr; } void search_init(struct search_data * sdp) { constexpr int byte_multiplier {64}; constexpr int word_multiplier {32}; for(auto i = 0U; i < query.len; i++) { int nt_value {nt_extract(query.seq, i) + 1}; // 1, 2, 3, or 4 int byte_offset {byte_multiplier * nt_value}; // 1, 64, 128, or 192 int word_offset {word_multiplier * nt_value}; // 1, 32, 64, or 128 sdp->qtable[i] = sdp->dprofile + byte_offset; sdp->qtable_w[i] = sdp->dprofile_w + word_offset; } } void search_chunk(struct search_data * sdp, const int64_t bits) { constexpr unsigned int bit_mode_16 {16}; if (sdp->target_count == 0) { return; } if (bits == bit_mode_16) { search16(sdp->qtable_w, static_cast<WORD>(penalty_gapopen), static_cast<WORD>(penalty_gapextend), static_cast<WORD*>(score_matrix_16), sdp->dprofile_w, reinterpret_cast<WORD*>(sdp->hearray), sdp->target_count, master_targets + sdp->target_index, master_scores + sdp->target_index, master_diffs + sdp->target_index, master_alignlengths + sdp->target_index, static_cast<uint64_t>(query.len), dirbufferbytes / sizeof(uint64_t), sdp->dir_array, longestdbsequence); } else { search8(sdp->qtable, static_cast<BYTE>(penalty_gapopen), static_cast<BYTE>(penalty_gapextend), static_cast<BYTE*>(score_matrix_8), sdp->dprofile, sdp->hearray, sdp->target_count, master_targets + sdp->target_index, master_scores + sdp->target_index, master_diffs + sdp->target_index, master_alignlengths + sdp->target_index, static_cast<uint64_t>(query.len), dirbufferbytes / sizeof(uint64_t), sdp->dir_array, longestdbsequence); } } auto search_getwork(uint64_t * countref, uint64_t * firstref) -> bool { // * countref = how many sequences to search // * firstref = index into master_targets/scores/diffs where thread should start bool status {false}; pthread_mutex_lock(&scan_mutex); if (master_next < master_length) { uint64_t chunksize = ((master_length - master_next + remainingchunks - 1) / remainingchunks); * countref = chunksize; * firstref = master_next; master_next += chunksize; remainingchunks--; status = true; } pthread_mutex_unlock(&scan_mutex); return status; } void search_worker_core(int64_t t) { search_init(sd + t); while(search_getwork(& sd[t].target_count, & sd[t].target_index)) { search_chunk(sd + t, master_bits); } } void search_do(uint64_t query_no, uint64_t listlength, uint64_t * targets, uint64_t * scores, uint64_t * diffs, uint64_t * alignlengths, int bits) { // constexpr unsigned int bit_mode_16 {16}; constexpr unsigned int channels_8 {8}; constexpr unsigned int bit_mode_8 {8}; constexpr unsigned int channels_16 {16}; query.qno = query_no; unsigned int query_len = 0; db_getsequenceandlength(query_no, &query.seq, &query_len); query.len = query_len; master_next = 0; master_length = listlength; master_targets = targets; master_scores = scores; master_diffs = diffs; master_alignlengths = alignlengths; master_bits = bits; auto thr = static_cast<uint64_t>(opt_threads); if (bits == bit_mode_8) { if (master_length <= (channels_16 - 1) * thr) { thr = (master_length + channels_16 - 1) / channels_16; } } else { if (master_length <= (channels_8 - 1) * thr) { thr = (master_length + channels_8 - 1) / channels_8; } } remainingchunks = thr; if (thr == 1) { search_worker_core(0); } else { search_threads->run(); } } void search_begin() { longestdbsequence = db_getlongestsequence(); sd = new struct search_data[static_cast<uint64_t>(opt_threads)]; for(auto t = 0LL; t < opt_threads; t++) { search_alloc(sd+t); } pthread_mutex_init(& scan_mutex, nullptr); /* start threads */ search_threads = new ThreadRunner(static_cast<int>(opt_threads), search_worker_core); } void search_end() { /* finish and clean up worker threads */ delete search_threads; search_threads = nullptr; pthread_mutex_destroy(& scan_mutex); for(auto t = 0LL; t < opt_threads; t++) { search_free(sd+t); } delete [] sd; sd = nullptr; } <commit_msg>mark as const as values are not mutable in that scope<commit_after>/* SWARM Copyright (C) 2012-2022 Torbjorn Rognes and Frederic Mahe This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Contact: Torbjorn Rognes <torognes@ifi.uio.no>, Department of Informatics, University of Oslo, PO Box 1080 Blindern, NO-0316 Oslo, Norway */ #include "swarm.h" #include "db.h" #include "search8.h" #include "search16.h" #include "threads.h" static pthread_mutex_t scan_mutex; static ThreadRunner * search_threads = nullptr; struct search_data { BYTE ** qtable; WORD ** qtable_w; BYTE * dprofile; WORD * dprofile_w; BYTE * hearray; uint64_t * dir_array; uint64_t target_count; uint64_t target_index; }; static struct search_data * sd; static uint64_t master_next; static uint64_t master_length; static uint64_t remainingchunks; static uint64_t * master_targets; static uint64_t * master_scores; static uint64_t * master_diffs; static uint64_t * master_alignlengths; static int master_bits; static uint64_t dirbufferbytes; queryinfo_t query; uint64_t longestdbsequence; void search_alloc(struct search_data * sdp) { constexpr unsigned int one_kilobyte {1024}; constexpr unsigned int nt_per_uint64 {32}; constexpr unsigned int bytes_per_uint64 {8}; dirbufferbytes = bytes_per_uint64 * longestdbsequence * ((longestdbsequence + 3) / 4) * 4; sdp->qtable = new BYTE*[longestdbsequence]; sdp->qtable_w = new WORD*[longestdbsequence]; sdp->dprofile = new BYTE[2 * one_kilobyte]; // 4 * 16 * 32 sdp->dprofile_w = new WORD[2 * one_kilobyte]; // 4 * 2 * 8 * 32 sdp->hearray = new BYTE[longestdbsequence * nt_per_uint64] { }; sdp->dir_array = new uint64_t[dirbufferbytes] { }; } void search_free(struct search_data * sdp) { delete [] sdp->qtable; sdp->qtable = nullptr; delete [] sdp->qtable_w; sdp->qtable_w = nullptr; delete [] sdp->dprofile; sdp->dprofile = nullptr; delete [] sdp->dprofile_w; sdp->dprofile_w = nullptr; delete [] sdp->hearray; sdp->hearray = nullptr; delete [] sdp->dir_array; sdp->dir_array = nullptr; } void search_init(struct search_data * sdp) { constexpr int byte_multiplier {64}; constexpr int word_multiplier {32}; for(auto i = 0U; i < query.len; i++) { const int nt_value {nt_extract(query.seq, i) + 1}; // 1, 2, 3, or 4 const int byte_offset {byte_multiplier * nt_value}; // 1, 64, 128, or 192 const int word_offset {word_multiplier * nt_value}; // 1, 32, 64, or 128 sdp->qtable[i] = sdp->dprofile + byte_offset; sdp->qtable_w[i] = sdp->dprofile_w + word_offset; } } void search_chunk(struct search_data * sdp, const int64_t bits) { constexpr unsigned int bit_mode_16 {16}; if (sdp->target_count == 0) { return; } if (bits == bit_mode_16) { search16(sdp->qtable_w, static_cast<WORD>(penalty_gapopen), static_cast<WORD>(penalty_gapextend), static_cast<WORD*>(score_matrix_16), sdp->dprofile_w, reinterpret_cast<WORD*>(sdp->hearray), sdp->target_count, master_targets + sdp->target_index, master_scores + sdp->target_index, master_diffs + sdp->target_index, master_alignlengths + sdp->target_index, static_cast<uint64_t>(query.len), dirbufferbytes / sizeof(uint64_t), sdp->dir_array, longestdbsequence); } else { search8(sdp->qtable, static_cast<BYTE>(penalty_gapopen), static_cast<BYTE>(penalty_gapextend), static_cast<BYTE*>(score_matrix_8), sdp->dprofile, sdp->hearray, sdp->target_count, master_targets + sdp->target_index, master_scores + sdp->target_index, master_diffs + sdp->target_index, master_alignlengths + sdp->target_index, static_cast<uint64_t>(query.len), dirbufferbytes / sizeof(uint64_t), sdp->dir_array, longestdbsequence); } } auto search_getwork(uint64_t * countref, uint64_t * firstref) -> bool { // * countref = how many sequences to search // * firstref = index into master_targets/scores/diffs where thread should start bool status {false}; pthread_mutex_lock(&scan_mutex); if (master_next < master_length) { uint64_t chunksize = ((master_length - master_next + remainingchunks - 1) / remainingchunks); * countref = chunksize; * firstref = master_next; master_next += chunksize; remainingchunks--; status = true; } pthread_mutex_unlock(&scan_mutex); return status; } void search_worker_core(int64_t t) { search_init(sd + t); while(search_getwork(& sd[t].target_count, & sd[t].target_index)) { search_chunk(sd + t, master_bits); } } void search_do(uint64_t query_no, uint64_t listlength, uint64_t * targets, uint64_t * scores, uint64_t * diffs, uint64_t * alignlengths, int bits) { // constexpr unsigned int bit_mode_16 {16}; constexpr unsigned int channels_8 {8}; constexpr unsigned int bit_mode_8 {8}; constexpr unsigned int channels_16 {16}; query.qno = query_no; unsigned int query_len = 0; db_getsequenceandlength(query_no, &query.seq, &query_len); query.len = query_len; master_next = 0; master_length = listlength; master_targets = targets; master_scores = scores; master_diffs = diffs; master_alignlengths = alignlengths; master_bits = bits; auto thr = static_cast<uint64_t>(opt_threads); if (bits == bit_mode_8) { if (master_length <= (channels_16 - 1) * thr) { thr = (master_length + channels_16 - 1) / channels_16; } } else { if (master_length <= (channels_8 - 1) * thr) { thr = (master_length + channels_8 - 1) / channels_8; } } remainingchunks = thr; if (thr == 1) { search_worker_core(0); } else { search_threads->run(); } } void search_begin() { longestdbsequence = db_getlongestsequence(); sd = new struct search_data[static_cast<uint64_t>(opt_threads)]; for(auto t = 0LL; t < opt_threads; t++) { search_alloc(sd+t); } pthread_mutex_init(& scan_mutex, nullptr); /* start threads */ search_threads = new ThreadRunner(static_cast<int>(opt_threads), search_worker_core); } void search_end() { /* finish and clean up worker threads */ delete search_threads; search_threads = nullptr; pthread_mutex_destroy(& scan_mutex); for(auto t = 0LL; t < opt_threads; t++) { search_free(sd+t); } delete [] sd; sd = nullptr; } <|endoftext|>
<commit_before>/*! \file \brief Basis for SDL library */ #ifndef SDL_HPP_uyqa3zsm #define SDL_HPP_uyqa3zsm // this must be defined before this is included #ifdef HAVE_SDL_H // Only on really old versions? # include <SDL.h> #else // assume this because it's the normal way # include <SDL/SDL.h> #endif #include <cassert> #include <stdexcept> #include <ostream> #include <cstring> /* http://www.libsdl.org/cgi/docwiki.cgi/SDL_API - scroll down to 'Audio' http://www.libsdl.org/cgi/docwiki.cgi/Audio_Examples // Note: this will be too slow and not good enough quality for my purposes - use OpenAL or // SDL_mixer, or my own one. I need an API for it also. SDL_MixAudio - Mixes audio data */ namespace sdl { //! \brief Convenience base for all errors; what() is SDL_GetError unless specified in ctor struct error : public std::runtime_error { error(const char *e = NULL) : runtime_error(((e == NULL) ? SDL_GetError() : e)) {} }; //!\deprecated Use the type directly typedef error sdl_error; //! \brief SDL_Init failure. struct init_error : public error { init_error(const char *e = NULL) : error(e) {} }; //! \brief SDL_OpenAudio failure. struct open_error : public error { open_error(const char *e = NULL) : error(e) {} }; //! \brief RAII object for SDL_Init and SDL_quit and interface for static audio stuff. class audio { public: audio() { int r = SDL_Init(SDL_INIT_AUDIO); if (r != 0) { const char * const error_str = SDL_GetError(); assert(error_str != NULL); throw init_error(error_str); } } ~audio() { SDL_Quit(); } //! \brief stopped, playing, or paused. SDL_audiostatus status() const { return SDL_GetAudioStatus(); } const char *status_name(SDL_audiostatus s) const { switch (s) { case SDL_AUDIO_STOPPED: return "stopped"; case SDL_AUDIO_PLAYING: return "playing"; case SDL_AUDIO_PAUSED: return "paused"; default: throw std::logic_error("unpossible value for SDL_GetAudioStatus()."); } } const char *status_name() const { return status_name(status()); } }; //! \brief C++ wrapper over SDL_AudioSpec. class audio_spec { friend class device_base; public: typedef void(*callback_type)(void *user_data, Uint8 *stream, int len); typedef enum {defer_init} defer_init_type; //! \brief Defer initialisation until later - intended for the obtained value output, but could be useful. explicit audio_spec(defer_init_type) {} explicit audio_spec(callback_type callback, int freq = 44100, int samples = 1024, int channels = 2, int format = AUDIO_S16SYS) { spec().freq = freq; spec().format = format; spec().callback = callback; spec().channels = channels; spec().samples = samples; spec().userdata = NULL; spec().silence = 0; spec().size = 0; } //! \brief Mono = 1, stereo = 2, etc. int channels() const { return spec().channels; } void channels(int n) { spec().channels = n; } //! \brief Size in bytes of the buffer (calculated from sizeof(data) * samples() * channels()). std::size_t buffer_size() const { return spec().size; } //! \brief Buffer size in samples. int buffer_samples() const { return spec().samples; } //! \brief Audio sample rate. uint32_t frequency() const { return spec().freq; } uint32_t frequency(uint32_t f) { return spec().freq = f; } //! \brief This can be something other than 0 if you're not using signed audio! int silence() const { return spec().silence; } //! \brief Time period in miliseconds of the buffer calculated by ms = (buffer_samples() * 1000) / frequency(). int period() const { return (buffer_samples() * 1000 ) / frequency(); } friend std::ostream &operator<<(std::ostream &o, const audio_spec &a) { a.dump_spec(o); return o; } // \brief Only tests non-calculated functions and *does* include userdata. friend bool operator==(const audio_spec &lhs, const audio_spec &rhs) { return lhs.spec().freq == rhs.spec().freq && lhs.spec().format == rhs.spec().format && lhs.spec().callback == rhs.spec().callback && lhs.spec().channels == rhs.spec().channels && lhs.spec().samples == rhs.spec().samples && lhs.spec().userdata == rhs.spec().userdata; } friend bool operator!=(const audio_spec &lhs, const audio_spec &rhs) { return ! (rhs == lhs); } //! \deprecated Use dump() std::ostream &dump_spec(std::ostream &o, const char *prefix = "") const { return dump(o, prefix); } //! \brief like operator<< but you can indent it. Doesn't have a newline terminating. std::ostream &dump(std::ostream &o, const char *prefix = "") const { const SDL_AudioSpec &s = spec(); o << prefix << "Frequency: " << s.freq << "\n"; o << prefix << "Format: "; switch (s.format) { case AUDIO_U8: o << "u8"; break; case AUDIO_S8: o << "s8"; break; case AUDIO_U16LSB: assert(AUDIO_U16LSB == AUDIO_U16); o << "u16 little"; break; case AUDIO_S16LSB: assert(AUDIO_S16LSB == AUDIO_S16); o << "s16 little"; break; case AUDIO_U16MSB: o << "u16 big"; break; case AUDIO_S16MSB: o << "s16 big"; break; default: o << "(unexpected value)"; } o << "\n"; o << prefix << "Channels: " << (int) s.channels << "\n"; o << prefix << "Silence value: " << (int) s.silence << "\n"; o << prefix << "Buffer in samples: " << s.samples << "\n"; o << prefix << "Buffer in bytes: " << s.size << "\n"; o << prefix << "Buffer in ms: " << period() << "\n"; o << prefix << "Callback: " << (void*) s.callback << "\n"; o << prefix << "Userdata: " << (void*) s.userdata; return o; } private: // because opening audio changes the spec by calculating bytes and silence. mutable SDL_AudioSpec spec_; SDL_AudioSpec &spec() const { return spec_; } }; //! \brief Open/close the audio device; non-instancable base class. class device_base { public: /*! \brief Change the pause state. Silence is written when paused. It should be called with pause_on=0 after opening the audio device to start playing sound. This is so you can safely initialize data for your callback function after opening the audio device. Silence will be written to the audio device during the pause. */ //@{ void pause() { pause_state(1); } void unpause() { pause_state(0); } void pause_state(int on) { SDL_PauseAudio(on); } //@} protected: device_base(sdl::audio &) {} //! \brief Close the audio and stop outputting ~device_base() { SDL_CloseAudio(); } // TODO: what happens in case of a double open? void checked_open(const audio_spec &des, audio_spec &obt) { checked_open(&des.spec(), &obt.spec()); } void checked_open(audio_spec &des) { checked_open(&des.spec()); } private: // "SDL_OpenAudio calculates the size and silence fields for both the desired and // obtained specifications. The size field stores the total size of the audio buffer // in bytes, while the silence stores the value used to represent silence in the // audio buffer" - that's why it's nonconst. void checked_open(SDL_AudioSpec *des, SDL_AudioSpec *obt = NULL) { int r = SDL_OpenAudio(des, obt); if (r != 0) { throw open_error(); } assert(SDL_GetAudioStatus() == SDL_AUDIO_PAUSED); } }; //! \brief Open/close the audio device; don't store any info. class light_device : public device_base { public: //! \brief Doesn't initialise so the desired audio_spec can go out of scope. light_device(sdl::audio &a) : device_base(a) {} //! \brief Call reopen() immediately (throws open_error) . light_device(sdl::audio &a, audio_spec &desired) : device_base(a) { reopen(desired); } //! \brief Call reopen() immediately (throws open_error) . light_device(sdl::audio &a, audio_spec &desired, audio_spec &obtained) : device_base(a) { reopen(desired, obtained); } //! \brief Open audio device with the requested spec (might get something different). Status will be paused. //! Probably better to use \link device \endlink if you are using this method. void reopen(audio_spec &desired, audio_spec &obtained) { checked_open(desired, obtained); } //! \brief Open audio device with the requested spec (might get something different). Status will be paused. void reopen(audio_spec &desired) { checked_open(desired); } }; //! \brief Open the audio output; stores properties of what we opened. class device : public device_base { public: //! \brief Doesn't initialise so the desired audio_spec can go out of scope. device(sdl::audio &a) : device_base(a), obtained_(audio_spec::defer_init) {} //! \brief Call reopen() immediately (throws open_error) . device(sdl::audio &a, audio_spec &desired) : device_base(a), obtained_(audio_spec::defer_init) { checked_open(desired, obtained_); } //! \brief Accessor to what was actually opened. const audio_spec &obtained() const { return obtained_; } //! \brief Open audio device with the requested spec (might get something different). Status will be paused. //! Desired is non-const because there are some values which are calculated. See //! \link audio_spec \endlink for details. void reopen(audio_spec &desired) { checked_open(desired, obtained_); } private: audio_spec obtained_; }; //! \brief Prevent the callback function from being called. class audio_lock_guard { public: //! \brief Call SDL_LockAudio(). Parameter is there to ensures that we are set up. audio_lock_guard(const device_base &) { SDL_LockAudio(); } //! \brief Call SDL_UnlockAudio() ~audio_lock_guard() { SDL_UnlockAudio(); } }; } // ns sdl #endif <commit_msg>Stop sdl from creating a winmain.<commit_after>/*! \file \brief Basis for SDL library */ #ifndef SDL_HPP_uyqa3zsm #define SDL_HPP_uyqa3zsm // this must be defined before this is included #ifdef HAVE_SDL_H // Only on really old versions? # include <SDL.h> #else // assume this because it's the normal way # include <SDL/SDL.h> #endif #ifdef __MINGW32__ #undef main /* Prevents SDL from overriding main() - this might be a hack */ #endif #include <cassert> #include <stdexcept> #include <ostream> #include <cstring> /* http://www.libsdl.org/cgi/docwiki.cgi/SDL_API - scroll down to 'Audio' http://www.libsdl.org/cgi/docwiki.cgi/Audio_Examples // Note: this will be too slow and not good enough quality for my purposes - use OpenAL or // SDL_mixer, or my own one. I need an API for it also. SDL_MixAudio - Mixes audio data */ namespace sdl { //! \brief Convenience base for all errors; what() is SDL_GetError unless specified in ctor struct error : public std::runtime_error { error(const char *e = NULL) : runtime_error(((e == NULL) ? SDL_GetError() : e)) {} }; //!\deprecated Use the type directly typedef error sdl_error; //! \brief SDL_Init failure. struct init_error : public error { init_error(const char *e = NULL) : error(e) {} }; //! \brief SDL_OpenAudio failure. struct open_error : public error { open_error(const char *e = NULL) : error(e) {} }; //! \brief RAII object for SDL_Init and SDL_quit and interface for static audio stuff. class audio { public: audio() { int r = SDL_Init(SDL_INIT_AUDIO); if (r != 0) { const char * const error_str = SDL_GetError(); assert(error_str != NULL); throw init_error(error_str); } } ~audio() { SDL_Quit(); } //! \brief stopped, playing, or paused. SDL_audiostatus status() const { return SDL_GetAudioStatus(); } const char *status_name(SDL_audiostatus s) const { switch (s) { case SDL_AUDIO_STOPPED: return "stopped"; case SDL_AUDIO_PLAYING: return "playing"; case SDL_AUDIO_PAUSED: return "paused"; default: throw std::logic_error("unpossible value for SDL_GetAudioStatus()."); } } const char *status_name() const { return status_name(status()); } }; //! \brief C++ wrapper over SDL_AudioSpec. class audio_spec { friend class device_base; public: typedef void(*callback_type)(void *user_data, Uint8 *stream, int len); typedef enum {defer_init} defer_init_type; //! \brief Defer initialisation until later - intended for the obtained value output, but could be useful. explicit audio_spec(defer_init_type) {} explicit audio_spec(callback_type callback, int freq = 44100, int samples = 1024, int channels = 2, int format = AUDIO_S16SYS) { spec().freq = freq; spec().format = format; spec().callback = callback; spec().channels = channels; spec().samples = samples; spec().userdata = NULL; spec().silence = 0; spec().size = 0; } //! \brief Mono = 1, stereo = 2, etc. int channels() const { return spec().channels; } void channels(int n) { spec().channels = n; } //! \brief Size in bytes of the buffer (calculated from sizeof(data) * samples() * channels()). std::size_t buffer_size() const { return spec().size; } //! \brief Buffer size in samples. int buffer_samples() const { return spec().samples; } //! \brief Audio sample rate. uint32_t frequency() const { return spec().freq; } uint32_t frequency(uint32_t f) { return spec().freq = f; } //! \brief This can be something other than 0 if you're not using signed audio! int silence() const { return spec().silence; } //! \brief Time period in miliseconds of the buffer calculated by ms = (buffer_samples() * 1000) / frequency(). int period() const { return (buffer_samples() * 1000 ) / frequency(); } friend std::ostream &operator<<(std::ostream &o, const audio_spec &a) { a.dump_spec(o); return o; } // \brief Only tests non-calculated functions and *does* include userdata. friend bool operator==(const audio_spec &lhs, const audio_spec &rhs) { return lhs.spec().freq == rhs.spec().freq && lhs.spec().format == rhs.spec().format && lhs.spec().callback == rhs.spec().callback && lhs.spec().channels == rhs.spec().channels && lhs.spec().samples == rhs.spec().samples && lhs.spec().userdata == rhs.spec().userdata; } friend bool operator!=(const audio_spec &lhs, const audio_spec &rhs) { return ! (rhs == lhs); } //! \deprecated Use dump() std::ostream &dump_spec(std::ostream &o, const char *prefix = "") const { return dump(o, prefix); } //! \brief like operator<< but you can indent it. Doesn't have a newline terminating. std::ostream &dump(std::ostream &o, const char *prefix = "") const { const SDL_AudioSpec &s = spec(); o << prefix << "Frequency: " << s.freq << "\n"; o << prefix << "Format: "; switch (s.format) { case AUDIO_U8: o << "u8"; break; case AUDIO_S8: o << "s8"; break; case AUDIO_U16LSB: assert(AUDIO_U16LSB == AUDIO_U16); o << "u16 little"; break; case AUDIO_S16LSB: assert(AUDIO_S16LSB == AUDIO_S16); o << "s16 little"; break; case AUDIO_U16MSB: o << "u16 big"; break; case AUDIO_S16MSB: o << "s16 big"; break; default: o << "(unexpected value)"; } o << "\n"; o << prefix << "Channels: " << (int) s.channels << "\n"; o << prefix << "Silence value: " << (int) s.silence << "\n"; o << prefix << "Buffer in samples: " << s.samples << "\n"; o << prefix << "Buffer in bytes: " << s.size << "\n"; o << prefix << "Buffer in ms: " << period() << "\n"; o << prefix << "Callback: " << (void*) s.callback << "\n"; o << prefix << "Userdata: " << (void*) s.userdata; return o; } private: // because opening audio changes the spec by calculating bytes and silence. mutable SDL_AudioSpec spec_; SDL_AudioSpec &spec() const { return spec_; } }; //! \brief Open/close the audio device; non-instancable base class. class device_base { public: /*! \brief Change the pause state. Silence is written when paused. It should be called with pause_on=0 after opening the audio device to start playing sound. This is so you can safely initialize data for your callback function after opening the audio device. Silence will be written to the audio device during the pause. */ //@{ void pause() { pause_state(1); } void unpause() { pause_state(0); } void pause_state(int on) { SDL_PauseAudio(on); } //@} protected: device_base(sdl::audio &) {} //! \brief Close the audio and stop outputting ~device_base() { SDL_CloseAudio(); } // TODO: what happens in case of a double open? void checked_open(const audio_spec &des, audio_spec &obt) { checked_open(&des.spec(), &obt.spec()); } void checked_open(audio_spec &des) { checked_open(&des.spec()); } private: // "SDL_OpenAudio calculates the size and silence fields for both the desired and // obtained specifications. The size field stores the total size of the audio buffer // in bytes, while the silence stores the value used to represent silence in the // audio buffer" - that's why it's nonconst. void checked_open(SDL_AudioSpec *des, SDL_AudioSpec *obt = NULL) { int r = SDL_OpenAudio(des, obt); if (r != 0) { throw open_error(); } assert(SDL_GetAudioStatus() == SDL_AUDIO_PAUSED); } }; //! \brief Open/close the audio device; don't store any info. class light_device : public device_base { public: //! \brief Doesn't initialise so the desired audio_spec can go out of scope. light_device(sdl::audio &a) : device_base(a) {} //! \brief Call reopen() immediately (throws open_error) . light_device(sdl::audio &a, audio_spec &desired) : device_base(a) { reopen(desired); } //! \brief Call reopen() immediately (throws open_error) . light_device(sdl::audio &a, audio_spec &desired, audio_spec &obtained) : device_base(a) { reopen(desired, obtained); } //! \brief Open audio device with the requested spec (might get something different). Status will be paused. //! Probably better to use \link device \endlink if you are using this method. void reopen(audio_spec &desired, audio_spec &obtained) { checked_open(desired, obtained); } //! \brief Open audio device with the requested spec (might get something different). Status will be paused. void reopen(audio_spec &desired) { checked_open(desired); } }; //! \brief Open the audio output; stores properties of what we opened. class device : public device_base { public: //! \brief Doesn't initialise so the desired audio_spec can go out of scope. device(sdl::audio &a) : device_base(a), obtained_(audio_spec::defer_init) {} //! \brief Call reopen() immediately (throws open_error) . device(sdl::audio &a, audio_spec &desired) : device_base(a), obtained_(audio_spec::defer_init) { checked_open(desired, obtained_); } //! \brief Accessor to what was actually opened. const audio_spec &obtained() const { return obtained_; } //! \brief Open audio device with the requested spec (might get something different). Status will be paused. //! Desired is non-const because there are some values which are calculated. See //! \link audio_spec \endlink for details. void reopen(audio_spec &desired) { checked_open(desired, obtained_); } private: audio_spec obtained_; }; //! \brief Prevent the callback function from being called. class audio_lock_guard { public: //! \brief Call SDL_LockAudio(). Parameter is there to ensures that we are set up. audio_lock_guard(const device_base &) { SDL_LockAudio(); } //! \brief Call SDL_UnlockAudio() ~audio_lock_guard() { SDL_UnlockAudio(); } }; } // ns sdl #endif <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qgeomapgroupobject.h" #include "qgeomapgroupobject_p.h" #include "qgeocoordinate.h" #include "qgeoboundingbox.h" QTM_BEGIN_NAMESPACE /*! \class QGeoMapGroupObject \brief The QGeoMapGroupObject class is a QGeoMapObject used to manager a group of other map objects. \inmodule QtLocation \ingroup maps-mapping-objects The QGeoMapGroupObject class can be used to quickly add and remove groups of objects to a map. The map objects contained in the group will be ordered relative to one another in the usual manner, such that objects with higher z-values will be drawn over objects with lower z-values and objects with equal z-values will be drawn in insertion order. This ordering of the objects will be independent of the other objects that are added to the map, since the z-value and insertion order of the QGeoMapGroupObject is used to determine where the group is placed in the scene. */ /*! Constructs a new group object. */ QGeoMapGroupObject::QGeoMapGroupObject() : d_ptr(new QGeoMapGroupObjectPrivate()) {} /*! Destroys this group object. */ QGeoMapGroupObject::~QGeoMapGroupObject() { delete d_ptr; } /*! \reimp */ QGeoMapObject::Type QGeoMapGroupObject::type() const { return QGeoMapObject::GroupType; } /*! Returns a bounding box which contains this map object. If this map object has children, the bounding box will be large enough to contain both this map object and all of its children. */ QGeoBoundingBox QGeoMapGroupObject::boundingBox() const { QGeoBoundingBox bounds; if (d_ptr->children.size() == 0) return bounds; for (int i = 0; i < d_ptr->children.size(); ++i) bounds = bounds.united(d_ptr->children.at(i)->boundingBox()); return bounds; } /*! Returns whether \a coordinate is contained with the boundary of this map object. If this map object has children, this function will return whether \a coordinate is contained within the boundary of this map object or within the boundary of any of its children. */ bool QGeoMapGroupObject::contains(const QGeoCoordinate &coordinate) const { for (int i = 0; i < d_ptr->children.size(); ++i) if (d_ptr->children.at(i)->contains(coordinate)) return true; return false; } /*! Adds \a childObject to the list of children of this map object. The children objects are drawn in order of the QGeoMapObject::zValue() value. Children objects having the same z value will be drawn in the order they were added. The map object will take ownership of \a childObject. */ void QGeoMapGroupObject::addChildObject(QGeoMapObject *childObject) { if (!childObject || d_ptr->children.contains(childObject)) return; childObject->setMapData(mapData()); //binary search QList<QGeoMapObject*>::iterator i = qUpperBound(d_ptr->children.begin(), d_ptr->children.end(), childObject); d_ptr->children.insert(i, childObject); emit childAdded(childObject); } /*! Removes \a childObject from the list of children of this map object. The map object will release ownership of \a childObject. */ void QGeoMapGroupObject::removeChildObject(QGeoMapObject *childObject) { if (!childObject) return; if (d_ptr->children.removeAll(childObject) > 0) { emit childRemoved(childObject); childObject->setMapData(0); } } /*! Returns the children of this object. */ QList<QGeoMapObject*> QGeoMapGroupObject::childObjects() const { return d_ptr->children; } /*! Clears the children of this object. The child objects will be deleted. */ void QGeoMapGroupObject::clearChildObjects() { for (int i = 0; i < d_ptr->children.size(); ++i) { emit childRemoved(d_ptr->children[i]); d_ptr->children[i]->setMapData(0); delete d_ptr->children[i]; } d_ptr->children.clear(); } /*! \reimp */ void QGeoMapGroupObject::setMapData(QGeoMapData *mapData) { QGeoMapObject::setMapData(mapData); for (int i = 0; i < d_ptr->children.size(); ++i) { d_ptr->children[i]->setMapData(mapData); emit childAdded(d_ptr->children[i]); } } /*! \fn void QGeoMapGroupObject::childAdded(QGeoMapObject *childObject) This signal will be emitted when the map object \a childObject is added to the group. */ /*! \fn void QGeoMapGroupObject::childRemoved(QGeoMapObject *childObject) This signal will be emitted when the map object \a childObject is removed from the group. */ /******************************************************************************* *******************************************************************************/ QGeoMapGroupObjectPrivate::QGeoMapGroupObjectPrivate() {} QGeoMapGroupObjectPrivate::~QGeoMapGroupObjectPrivate() { qDeleteAll(children); } #include "moc_qgeomapgroupobject.cpp" QTM_END_NAMESPACE <commit_msg>Fix for signal confusion with QGeoMapGroupObject.<commit_after>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qgeomapgroupobject.h" #include "qgeomapgroupobject_p.h" #include "qgeocoordinate.h" #include "qgeoboundingbox.h" QTM_BEGIN_NAMESPACE /*! \class QGeoMapGroupObject \brief The QGeoMapGroupObject class is a QGeoMapObject used to manager a group of other map objects. \inmodule QtLocation \ingroup maps-mapping-objects The QGeoMapGroupObject class can be used to quickly add and remove groups of objects to a map. The map objects contained in the group will be ordered relative to one another in the usual manner, such that objects with higher z-values will be drawn over objects with lower z-values and objects with equal z-values will be drawn in insertion order. This ordering of the objects will be independent of the other objects that are added to the map, since the z-value and insertion order of the QGeoMapGroupObject is used to determine where the group is placed in the scene. */ /*! Constructs a new group object. */ QGeoMapGroupObject::QGeoMapGroupObject() : d_ptr(new QGeoMapGroupObjectPrivate()) {} /*! Destroys this group object. */ QGeoMapGroupObject::~QGeoMapGroupObject() { delete d_ptr; } /*! \reimp */ QGeoMapObject::Type QGeoMapGroupObject::type() const { return QGeoMapObject::GroupType; } /*! Returns a bounding box which contains this map object. If this map object has children, the bounding box will be large enough to contain both this map object and all of its children. */ QGeoBoundingBox QGeoMapGroupObject::boundingBox() const { QGeoBoundingBox bounds; if (d_ptr->children.size() == 0) return bounds; for (int i = 0; i < d_ptr->children.size(); ++i) bounds = bounds.united(d_ptr->children.at(i)->boundingBox()); return bounds; } /*! Returns whether \a coordinate is contained with the boundary of this map object. If this map object has children, this function will return whether \a coordinate is contained within the boundary of this map object or within the boundary of any of its children. */ bool QGeoMapGroupObject::contains(const QGeoCoordinate &coordinate) const { for (int i = 0; i < d_ptr->children.size(); ++i) if (d_ptr->children.at(i)->contains(coordinate)) return true; return false; } /*! Adds \a childObject to the list of children of this map object. The children objects are drawn in order of the QGeoMapObject::zValue() value. Children objects having the same z value will be drawn in the order they were added. The map object will take ownership of \a childObject. */ void QGeoMapGroupObject::addChildObject(QGeoMapObject *childObject) { if (!childObject || d_ptr->children.contains(childObject)) return; childObject->setMapData(mapData()); //binary search QList<QGeoMapObject*>::iterator i = qUpperBound(d_ptr->children.begin(), d_ptr->children.end(), childObject); d_ptr->children.insert(i, childObject); emit childAdded(childObject); } /*! Removes \a childObject from the list of children of this map object. The map object will release ownership of \a childObject. */ void QGeoMapGroupObject::removeChildObject(QGeoMapObject *childObject) { if (!childObject) return; if (d_ptr->children.removeAll(childObject) > 0) { emit childRemoved(childObject); childObject->setMapData(0); } } /*! Returns the children of this object. */ QList<QGeoMapObject*> QGeoMapGroupObject::childObjects() const { return d_ptr->children; } /*! Clears the children of this object. The child objects will be deleted. */ void QGeoMapGroupObject::clearChildObjects() { for (int i = 0; i < d_ptr->children.size(); ++i) { emit childRemoved(d_ptr->children[i]); d_ptr->children[i]->setMapData(0); delete d_ptr->children[i]; } d_ptr->children.clear(); } /*! \reimp */ void QGeoMapGroupObject::setMapData(QGeoMapData *mapData) { QGeoMapObject::setMapData(mapData); for (int i = 0; i < d_ptr->children.size(); ++i) { d_ptr->children[i]->setMapData(mapData); if (mapData) emit childAdded(d_ptr->children[i]); } } /*! \fn void QGeoMapGroupObject::childAdded(QGeoMapObject *childObject) This signal will be emitted when the map object \a childObject is added to the group. */ /*! \fn void QGeoMapGroupObject::childRemoved(QGeoMapObject *childObject) This signal will be emitted when the map object \a childObject is removed from the group. */ /******************************************************************************* *******************************************************************************/ QGeoMapGroupObjectPrivate::QGeoMapGroupObjectPrivate() {} QGeoMapGroupObjectPrivate::~QGeoMapGroupObjectPrivate() { qDeleteAll(children); } #include "moc_qgeomapgroupobject.cpp" QTM_END_NAMESPACE <|endoftext|>
<commit_before>/* * AscEmu Framework based on ArcEmu MMORPG Server * Copyright (c) 2014-2019 AscEmu Team <http://www.ascemu.org> * Copyright (C) 2008-2012 ArcEmu Team <http://www.ArcEmu.org/> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "LogonStdAfx.h" #include "LogonConsole.h" #include "Server/Logon.h" initialiseSingleton(LogonConsole); void LogonConsole::TranslateRehash(char* /*str*/) { LogDefault("rehashing config file..."); if (sMasterLogon.LoadLogonConfiguration()) LogDefault("Rehashing config file finished succesfull!"); } void LogonConsole::demoTicker(AscEmu::Threading::AEThread& /*thread*/) { std::cout << "Thread ticker: " << m_demoCounter << std::endl; ++m_demoCounter; } void LogonConsole::threadDemoCmd(char* /*str*/) { std::cout << "Thread Demo init" << std::endl; if (m_demoCounter != 0) { std::cout << "Existing thread found, rebooting" << std::endl; m_demoThread->reboot(); return; } std::function<void(AscEmu::Threading::AEThread&)> f = [this](AscEmu::Threading::AEThread& thread) { this->demoTicker(thread); }; m_demoThread = new AscEmu::Threading::AEThread(std::string("DemoThread"), f, std::chrono::milliseconds(100)); } void LogonConsole::Kill() { if (_thread != nullptr) _thread->kill = true; #ifdef WIN32 /* write the return keydown/keyup event */ DWORD dwTmp; INPUT_RECORD ir[2]; ir[0].EventType = KEY_EVENT; ir[0].Event.KeyEvent.bKeyDown = TRUE; ir[0].Event.KeyEvent.dwControlKeyState = 288; ir[0].Event.KeyEvent.uChar.AsciiChar = 13; ir[0].Event.KeyEvent.wRepeatCount = 1; ir[0].Event.KeyEvent.wVirtualKeyCode = 13; ir[0].Event.KeyEvent.wVirtualScanCode = 28; ir[1].EventType = KEY_EVENT; ir[1].Event.KeyEvent.bKeyDown = FALSE; ir[1].Event.KeyEvent.dwControlKeyState = 288; ir[1].Event.KeyEvent.uChar.AsciiChar = 13; ir[1].Event.KeyEvent.wRepeatCount = 1; ir[1].Event.KeyEvent.wVirtualKeyCode = 13; ir[1].Event.KeyEvent.wVirtualScanCode = 28; WriteConsoleInput(GetStdHandle(STD_INPUT_HANDLE), ir, 2, &dwTmp); #endif LOG_BASIC("Waiting for console thread to terminate...."); while (_thread != nullptr) { Arcemu::Sleep(100); } LOG_BASIC("Console shut down."); } bool LogonConsoleThread::runThread() { new LogonConsole; SetThreadName("Console Interpreter"); sLogonConsole._thread = this; size_t i = 0, len = 0; char cmd[96]; #ifndef WIN32 fd_set fds; struct timeval tv; #endif while (!kill) { #ifndef WIN32 tv.tv_sec = 1; tv.tv_usec = 0; FD_ZERO(&fds); FD_SET(STDIN_FILENO, &fds); if(select(1, &fds, NULL, NULL, &tv) <= 0) { if(!kill.load()) // timeout continue; else break; } #endif // Make sure our buffer is clean to avoid Array bounds overflow memset(cmd, 0, sizeof(cmd)); // Read in single line from "stdin" fgets(cmd, 80, stdin); if (kill) break; len = strlen(cmd); for (i = 0; i < len; ++i) { if (cmd[i] == '\n' || cmd[i] == '\r') cmd[i] = '\0'; } sLogonConsole.ProcessCmd(cmd); } sLogonConsole._thread = NULL; return true; } /////////////////////////////////////////////////////////////////////////////// // Protected methods: /////////////////////////////////////////////////////////////////////////////// // Process one command #define MAX_CONSOLE_INPUT 80 void LogonConsole::ProcessCmd(char* cmd) { typedef void (LogonConsole::*PTranslater)(char * str); struct SCmd { const char* name; PTranslater tr; }; SCmd cmds[] = { { "?", &LogonConsole::TranslateHelp }, { "z", &LogonConsole::threadDemoCmd }, { "help", &LogonConsole::TranslateHelp }, { "account create", &LogonConsole::AccountCreate }, { "account delete", &LogonConsole::AccountDelete }, { "account set password", &LogonConsole::AccountSetPassword }, { "account change password", &LogonConsole::AccountChangePassword }, { "reload", &LogonConsole::ReloadAccts }, { "rehash", &LogonConsole::TranslateRehash }, { "netstatus", &LogonConsole::NetworkStatus }, { "shutdown", &LogonConsole::TranslateQuit }, { "exit", &LogonConsole::TranslateQuit }, { "info", &LogonConsole::Info }, }; char cmd2[MAX_CONSOLE_INPUT]; strncpy(cmd2, cmd, MAX_CONSOLE_INPUT); cmd2[MAX_CONSOLE_INPUT - 1] = '\0'; for (size_t i = 0; i < strlen(cmd); ++i) cmd2[i] = static_cast<char>(tolower(cmd[i])); for (size_t i = 0; i < sizeof(cmds) / sizeof(SCmd); i++) if (strncmp(cmd2, cmds[i].name, strlen(cmds[i].name)) == 0) { (this->*(cmds[i].tr))(cmd + strlen(cmds[i].name)); return; } if (strncmp(cmd, "c", 1) == 0) printf("Console: Unknown console command (use \"help\" for help).\n"); } void LogonConsole::ReloadAccts(char* /*str*/) { sAccountMgr.reloadAccounts(false); sIpBanMgr.reload(); } void LogonConsole::NetworkStatus(char* /*str*/) { sSocketMgr.ShowStatus(); } // quit | exit void LogonConsole::TranslateQuit(char* str) { int delay = str != NULL ? atoi(str) : 5000; if (!delay) delay = 5000; else delay *= 1000; ProcessQuit(delay); } void LogonConsole::ProcessQuit(int /*delay*/) { mrunning = false; } /////////////////////////////////////////////////////////////////////////////// // Console commands - help | ? /////////////////////////////////////////////////////////////////////////////// void LogonConsole::TranslateHelp(char* /*str*/) { ProcessHelp(NULL); } void LogonConsole::ProcessHelp(char* command) { if (command == NULL) { printf("Console:--------help--------\n"); printf(" Help, ?: Prints this help text.\n"); printf(" Account create: Creates a new account\n"); printf(" Account delete: Deletes an account\n"); printf(" Account set password: Sets a new password for an account\n"); printf(" Account change password: Change the current password for an account\n"); printf(" Info: shows some information about the server.\n"); printf(" Netstatus: Shows network status.\n"); printf(" Rehash: Rehashing config file.\n"); printf(" Reload: Reloads accounts.\n"); printf(" Shutdown, exit: Closes the logonserver.\n"); } } void LogonConsole::Info(char* /*str*/) { std::cout << "LogonServer information" << std::endl; std::cout << "-----------------------" << std::endl; std::cout << "CPU Usage: " << sLogon.getCPUUsage() << " %" << std::endl; std::cout << "RAM Usage: " << sLogon.getRAMUsage() << " MB" << std::endl; } void LogonConsole::AccountCreate(char* str) { char name[512]; char password[512]; char email[512]; int count = sscanf(str, "%s %s %s", name, password, email); if (count != 3) { std::cout << "usage: account create <name> <password> <email>" << std::endl; std::cout << "example: account create ghostcrawler Ih4t3p4l4dins greg.street@blizzard.com" << std::endl; return; } checkAccountName(name, ACC_NAME_NOT_EXIST); std::string pass; pass.assign(name); pass.push_back(':'); pass.append(password); std::stringstream query; query << "INSERT INTO `accounts`( `acc_name`,`encrypted_password`,`banned`,`email`,`flags`,`banreason`) VALUES ( '"; query << name << "',"; query << "SHA( UPPER( '" << pass << "' ) ),'0','"; query << email << "','"; #if VERSION_STRING == Classic query << 0 << "','' );"; #elif VERSION_STRING == TBC query << 8 << "','' );"; #elif VERSION_STRING == WotLK query << 24 << "','' );"; #elif VERSION_STRING == Cata query << 32 << "','' );"; #endif if (!sLogonSQL->WaitExecuteNA(query.str().c_str())) { std::cout << "Couldn't save new account to database. Aborting." << std::endl; return; } sAccountMgr.reloadAccounts(true); std::cout << "Account created." << std::endl; } void LogonConsole::AccountDelete(char* str) { char name[512]; int count = sscanf(str, "%s", name); if (count != 1) { std::cout << "usage: account delete <name>" << std::endl; std::cout << "example: account delete ghostcrawler" << std::endl; return; } checkAccountName(name, ACC_NAME_DO_EXIST); std::stringstream query; query << "DELETE FROM `accounts` WHERE `acc_name` = '"; query << name << "';"; if (!sLogonSQL->WaitExecuteNA(query.str().c_str())) { std::cout << "Couldn't delete account. Aborting." << std::endl; return; } sAccountMgr.reloadAccounts(true); std::cout << "Account deleted." << std::endl; } void LogonConsole::AccountSetPassword(char* str) { char name[512]; char password[512]; int count = sscanf(str, "%s %s", name, password); if (count != 2) { std::cout << "usage: account set password <name> <password>" << std::endl; std::cout << "example: account set password ghostcrawler NewPassWoRd" << std::endl; return; } checkAccountName(name, ACC_NAME_DO_EXIST); std::string pass; pass.assign(name); pass.push_back(':'); pass.append(password); std::stringstream query; query << "UPDATE `accounts` SET `encrypted_password` = "; query << "SHA( UPPER( '" << pass << "' ) ) WHERE `acc_name` = '"; query << name << "'"; if (!sLogonSQL->WaitExecuteNA(query.str().c_str())) { std::cout << "Couldn't update password in database. Aborting." << std::endl; return; } sAccountMgr.reloadAccounts(true); std::cout << "Account password updated." << std::endl; } void LogonConsole::AccountChangePassword(char* str) { char account_name[512]; char old_password[512]; char new_password_1[512]; char new_password_2[512]; int count = sscanf(str, "%s %s %s %s", account_name, old_password, new_password_1, new_password_2); if (count != 4) { std::cout << "usage: account change password <account> <old_password> <new_password> <new_password>" << std::endl; std::cout << "example: account change password ghostcrawler OldPasSworD FreshNewPassword FreshNewPassword" << std::endl; return; } checkAccountName(account_name, ACC_NAME_DO_EXIST); if (std::string(new_password_1) != std::string(new_password_2)) { std::cout << "The new passwords doesn't match!" << std::endl; return; } std::string pass; pass.assign(account_name); pass.push_back(':'); pass.append(old_password); auto check_oldpass_query = sLogonSQL->Query("SELECT acc_name, encrypted_password FROM accounts WHERE encrypted_password = SHA(UPPER('%s')) AND acc_name = '%s'", pass.c_str(), std::string(account_name).c_str()); if (!check_oldpass_query) { std::cout << "Your current password doesn't match with your input" << std::endl; return; } else { std::string new_pass; new_pass.assign(account_name); new_pass.push_back(':'); new_pass.append(new_password_1); auto new_pass_query = sLogonSQL->Query("UPDATE accounts SET encrypted_password = SHA(UPPER('%s')) WHERE acc_name = '%s'", new_pass.c_str(), std::string(account_name).c_str()); if (!new_pass_query) { // The query is already done, don't know why we are here. \todo check sLogonSQL query handling. // std::cout << "Can't update the password. Abort." << std::endl; return; } } sAccountMgr.reloadAccounts(true); std::cout << "Account password changed." << std::endl; } void LogonConsole::checkAccountName(std::string name, uint8 type) { std::string aname(name); Util::StringToUpperCase(aname); switch (type) { case ACC_NAME_DO_EXIST: { if (sAccountMgr.getAccountByName(aname) == NULL) { std::cout << "There's no account with name " << name << std::endl; } } break; case ACC_NAME_NOT_EXIST: { if (sAccountMgr.getAccountByName(aname) != NULL) { std::cout << "There's already an account with name " << name << std::endl; } } break; } } LogonConsoleThread::LogonConsoleThread() { kill = false; } LogonConsoleThread::~LogonConsoleThread() { } <commit_msg>MOP Fixed: when creating an account through logon.exe, now the correct flag.<commit_after>/* * AscEmu Framework based on ArcEmu MMORPG Server * Copyright (c) 2014-2019 AscEmu Team <http://www.ascemu.org> * Copyright (C) 2008-2012 ArcEmu Team <http://www.ArcEmu.org/> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "LogonStdAfx.h" #include "LogonConsole.h" #include "Server/Logon.h" initialiseSingleton(LogonConsole); void LogonConsole::TranslateRehash(char* /*str*/) { LogDefault("rehashing config file..."); if (sMasterLogon.LoadLogonConfiguration()) LogDefault("Rehashing config file finished succesfull!"); } void LogonConsole::demoTicker(AscEmu::Threading::AEThread& /*thread*/) { std::cout << "Thread ticker: " << m_demoCounter << std::endl; ++m_demoCounter; } void LogonConsole::threadDemoCmd(char* /*str*/) { std::cout << "Thread Demo init" << std::endl; if (m_demoCounter != 0) { std::cout << "Existing thread found, rebooting" << std::endl; m_demoThread->reboot(); return; } std::function<void(AscEmu::Threading::AEThread&)> f = [this](AscEmu::Threading::AEThread& thread) { this->demoTicker(thread); }; m_demoThread = new AscEmu::Threading::AEThread(std::string("DemoThread"), f, std::chrono::milliseconds(100)); } void LogonConsole::Kill() { if (_thread != nullptr) _thread->kill = true; #ifdef WIN32 /* write the return keydown/keyup event */ DWORD dwTmp; INPUT_RECORD ir[2]; ir[0].EventType = KEY_EVENT; ir[0].Event.KeyEvent.bKeyDown = TRUE; ir[0].Event.KeyEvent.dwControlKeyState = 288; ir[0].Event.KeyEvent.uChar.AsciiChar = 13; ir[0].Event.KeyEvent.wRepeatCount = 1; ir[0].Event.KeyEvent.wVirtualKeyCode = 13; ir[0].Event.KeyEvent.wVirtualScanCode = 28; ir[1].EventType = KEY_EVENT; ir[1].Event.KeyEvent.bKeyDown = FALSE; ir[1].Event.KeyEvent.dwControlKeyState = 288; ir[1].Event.KeyEvent.uChar.AsciiChar = 13; ir[1].Event.KeyEvent.wRepeatCount = 1; ir[1].Event.KeyEvent.wVirtualKeyCode = 13; ir[1].Event.KeyEvent.wVirtualScanCode = 28; WriteConsoleInput(GetStdHandle(STD_INPUT_HANDLE), ir, 2, &dwTmp); #endif LOG_BASIC("Waiting for console thread to terminate...."); while (_thread != nullptr) { Arcemu::Sleep(100); } LOG_BASIC("Console shut down."); } bool LogonConsoleThread::runThread() { new LogonConsole; SetThreadName("Console Interpreter"); sLogonConsole._thread = this; size_t i = 0, len = 0; char cmd[96]; #ifndef WIN32 fd_set fds; struct timeval tv; #endif while (!kill) { #ifndef WIN32 tv.tv_sec = 1; tv.tv_usec = 0; FD_ZERO(&fds); FD_SET(STDIN_FILENO, &fds); if(select(1, &fds, NULL, NULL, &tv) <= 0) { if(!kill.load()) // timeout continue; else break; } #endif // Make sure our buffer is clean to avoid Array bounds overflow memset(cmd, 0, sizeof(cmd)); // Read in single line from "stdin" fgets(cmd, 80, stdin); if (kill) break; len = strlen(cmd); for (i = 0; i < len; ++i) { if (cmd[i] == '\n' || cmd[i] == '\r') cmd[i] = '\0'; } sLogonConsole.ProcessCmd(cmd); } sLogonConsole._thread = NULL; return true; } /////////////////////////////////////////////////////////////////////////////// // Protected methods: /////////////////////////////////////////////////////////////////////////////// // Process one command #define MAX_CONSOLE_INPUT 80 void LogonConsole::ProcessCmd(char* cmd) { typedef void (LogonConsole::*PTranslater)(char * str); struct SCmd { const char* name; PTranslater tr; }; SCmd cmds[] = { { "?", &LogonConsole::TranslateHelp }, { "z", &LogonConsole::threadDemoCmd }, { "help", &LogonConsole::TranslateHelp }, { "account create", &LogonConsole::AccountCreate }, { "account delete", &LogonConsole::AccountDelete }, { "account set password", &LogonConsole::AccountSetPassword }, { "account change password", &LogonConsole::AccountChangePassword }, { "reload", &LogonConsole::ReloadAccts }, { "rehash", &LogonConsole::TranslateRehash }, { "netstatus", &LogonConsole::NetworkStatus }, { "shutdown", &LogonConsole::TranslateQuit }, { "exit", &LogonConsole::TranslateQuit }, { "info", &LogonConsole::Info }, }; char cmd2[MAX_CONSOLE_INPUT]; strncpy(cmd2, cmd, MAX_CONSOLE_INPUT); cmd2[MAX_CONSOLE_INPUT - 1] = '\0'; for (size_t i = 0; i < strlen(cmd); ++i) cmd2[i] = static_cast<char>(tolower(cmd[i])); for (size_t i = 0; i < sizeof(cmds) / sizeof(SCmd); i++) if (strncmp(cmd2, cmds[i].name, strlen(cmds[i].name)) == 0) { (this->*(cmds[i].tr))(cmd + strlen(cmds[i].name)); return; } if (strncmp(cmd, "c", 1) == 0) printf("Console: Unknown console command (use \"help\" for help).\n"); } void LogonConsole::ReloadAccts(char* /*str*/) { sAccountMgr.reloadAccounts(false); sIpBanMgr.reload(); } void LogonConsole::NetworkStatus(char* /*str*/) { sSocketMgr.ShowStatus(); } // quit | exit void LogonConsole::TranslateQuit(char* str) { int delay = str != NULL ? atoi(str) : 5000; if (!delay) delay = 5000; else delay *= 1000; ProcessQuit(delay); } void LogonConsole::ProcessQuit(int /*delay*/) { mrunning = false; } /////////////////////////////////////////////////////////////////////////////// // Console commands - help | ? /////////////////////////////////////////////////////////////////////////////// void LogonConsole::TranslateHelp(char* /*str*/) { ProcessHelp(NULL); } void LogonConsole::ProcessHelp(char* command) { if (command == NULL) { printf("Console:--------help--------\n"); printf(" Help, ?: Prints this help text.\n"); printf(" Account create: Creates a new account\n"); printf(" Account delete: Deletes an account\n"); printf(" Account set password: Sets a new password for an account\n"); printf(" Account change password: Change the current password for an account\n"); printf(" Info: shows some information about the server.\n"); printf(" Netstatus: Shows network status.\n"); printf(" Rehash: Rehashing config file.\n"); printf(" Reload: Reloads accounts.\n"); printf(" Shutdown, exit: Closes the logonserver.\n"); } } void LogonConsole::Info(char* /*str*/) { std::cout << "LogonServer information" << std::endl; std::cout << "-----------------------" << std::endl; std::cout << "CPU Usage: " << sLogon.getCPUUsage() << " %" << std::endl; std::cout << "RAM Usage: " << sLogon.getRAMUsage() << " MB" << std::endl; } void LogonConsole::AccountCreate(char* str) { char name[512]; char password[512]; char email[512]; int count = sscanf(str, "%s %s %s", name, password, email); if (count != 3) { std::cout << "usage: account create <name> <password> <email>" << std::endl; std::cout << "example: account create ghostcrawler Ih4t3p4l4dins greg.street@blizzard.com" << std::endl; return; } checkAccountName(name, ACC_NAME_NOT_EXIST); std::string pass; pass.assign(name); pass.push_back(':'); pass.append(password); std::stringstream query; query << "INSERT INTO `accounts`( `acc_name`,`encrypted_password`,`banned`,`email`,`flags`,`banreason`) VALUES ( '"; query << name << "',"; query << "SHA( UPPER( '" << pass << "' ) ),'0','"; query << email << "','"; #if VERSION_STRING == Classic query << 0 << "','' );"; #elif VERSION_STRING == TBC query << 8 << "','' );"; #elif VERSION_STRING == WotLK query << 24 << "','' );"; #elif VERSION_STRING == Cata query << 32 << "','' );"; #elif VERSION_STRING == Mop query << 40 << "','' );"; #endif if (!sLogonSQL->WaitExecuteNA(query.str().c_str())) { std::cout << "Couldn't save new account to database. Aborting." << std::endl; return; } sAccountMgr.reloadAccounts(true); std::cout << "Account created." << std::endl; } void LogonConsole::AccountDelete(char* str) { char name[512]; int count = sscanf(str, "%s", name); if (count != 1) { std::cout << "usage: account delete <name>" << std::endl; std::cout << "example: account delete ghostcrawler" << std::endl; return; } checkAccountName(name, ACC_NAME_DO_EXIST); std::stringstream query; query << "DELETE FROM `accounts` WHERE `acc_name` = '"; query << name << "';"; if (!sLogonSQL->WaitExecuteNA(query.str().c_str())) { std::cout << "Couldn't delete account. Aborting." << std::endl; return; } sAccountMgr.reloadAccounts(true); std::cout << "Account deleted." << std::endl; } void LogonConsole::AccountSetPassword(char* str) { char name[512]; char password[512]; int count = sscanf(str, "%s %s", name, password); if (count != 2) { std::cout << "usage: account set password <name> <password>" << std::endl; std::cout << "example: account set password ghostcrawler NewPassWoRd" << std::endl; return; } checkAccountName(name, ACC_NAME_DO_EXIST); std::string pass; pass.assign(name); pass.push_back(':'); pass.append(password); std::stringstream query; query << "UPDATE `accounts` SET `encrypted_password` = "; query << "SHA( UPPER( '" << pass << "' ) ) WHERE `acc_name` = '"; query << name << "'"; if (!sLogonSQL->WaitExecuteNA(query.str().c_str())) { std::cout << "Couldn't update password in database. Aborting." << std::endl; return; } sAccountMgr.reloadAccounts(true); std::cout << "Account password updated." << std::endl; } void LogonConsole::AccountChangePassword(char* str) { char account_name[512]; char old_password[512]; char new_password_1[512]; char new_password_2[512]; int count = sscanf(str, "%s %s %s %s", account_name, old_password, new_password_1, new_password_2); if (count != 4) { std::cout << "usage: account change password <account> <old_password> <new_password> <new_password>" << std::endl; std::cout << "example: account change password ghostcrawler OldPasSworD FreshNewPassword FreshNewPassword" << std::endl; return; } checkAccountName(account_name, ACC_NAME_DO_EXIST); if (std::string(new_password_1) != std::string(new_password_2)) { std::cout << "The new passwords doesn't match!" << std::endl; return; } std::string pass; pass.assign(account_name); pass.push_back(':'); pass.append(old_password); auto check_oldpass_query = sLogonSQL->Query("SELECT acc_name, encrypted_password FROM accounts WHERE encrypted_password = SHA(UPPER('%s')) AND acc_name = '%s'", pass.c_str(), std::string(account_name).c_str()); if (!check_oldpass_query) { std::cout << "Your current password doesn't match with your input" << std::endl; return; } else { std::string new_pass; new_pass.assign(account_name); new_pass.push_back(':'); new_pass.append(new_password_1); auto new_pass_query = sLogonSQL->Query("UPDATE accounts SET encrypted_password = SHA(UPPER('%s')) WHERE acc_name = '%s'", new_pass.c_str(), std::string(account_name).c_str()); if (!new_pass_query) { // The query is already done, don't know why we are here. \todo check sLogonSQL query handling. // std::cout << "Can't update the password. Abort." << std::endl; return; } } sAccountMgr.reloadAccounts(true); std::cout << "Account password changed." << std::endl; } void LogonConsole::checkAccountName(std::string name, uint8 type) { std::string aname(name); Util::StringToUpperCase(aname); switch (type) { case ACC_NAME_DO_EXIST: { if (sAccountMgr.getAccountByName(aname) == NULL) { std::cout << "There's no account with name " << name << std::endl; } } break; case ACC_NAME_NOT_EXIST: { if (sAccountMgr.getAccountByName(aname) != NULL) { std::cout << "There's already an account with name " << name << std::endl; } } break; } } LogonConsoleThread::LogonConsoleThread() { kill = false; } LogonConsoleThread::~LogonConsoleThread() { } <|endoftext|>
<commit_before>#include<iostream> #include<vector> #include<cstdio> #include<string> #include<thread> #include<dirent.h> #include<chrono> #include<sys/socket.h> #include<netinet/in.h> #include<sys/types.h> #include<arpa/inet.h> #include<fcntl.h> #include<unistd.h> #include<cstdlib> #include<sys/wait.h> #include<string.h> #include<mutex> #include<unordered_map> #include <iostream> #include <fstream> #define SUCCESS 0 #define FAILURE 1 #define MAX_SIZE 1024 #define CLI_ID "101" #define TOKEN "#" #define BCAST_PORT 6000 #define LISTENER_PORT 54545 char Client_id[15]={0}; char b_cast_time[10]={0}; //unordered_map<std::string,std::string> cluster_info; void config_parser() { std::fstream config_file; std::string line; config_file.open("../files/config",std::ios::in|std::ios::out); while(getline(config_file,line)) { if(0==line.length()) continue; else std::cout<<line<<std::endl; } } void fs_bcast() { //Current Client Socket int bcast_sockfd; bcast_sockfd = socket(AF_INET, SOCK_DGRAM, 0); struct sockaddr_in new_addr; memset(&new_addr, 0, sizeof(new_addr)); new_addr.sin_family = AF_INET; new_addr.sin_port = BCAST_PORT; new_addr.sin_addr.s_addr = htonl(INADDR_ANY); while(1) { std::this_thread::sleep_for(std::chrono::milliseconds(5000)); DIR *dir; struct dirent *ent; char fs_data[MAX_SIZE]; memset(fs_data, 0, MAX_SIZE); strcpy(fs_data, CLI_ID); if ((dir = opendir ("./")) != NULL) { while((ent = readdir (dir)) != NULL) { if (!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, "..")) {continue;} else { strcat(fs_data, TOKEN); strcat(fs_data, ent->d_name); } } } closedir (dir); std::cout << fs_data << std::endl; sendto(bcast_sockfd, fs_data, strlen(fs_data), 0, (struct sockaddr *)&new_addr, sizeof(struct sockaddr_in)); } } void bcast_listener() { int sockfd; std::cout<<"Hello"<<std::endl; struct sockaddr_in new_addr; struct sockaddr_in cli_addr; unsigned slen = sizeof(cli_addr); sockfd = socket(AF_INET, SOCK_DGRAM, 0); memset(&new_addr, 0, sizeof(new_addr)); new_addr.sin_family = AF_INET; new_addr.sin_port = LISTENER_PORT; new_addr.sin_addr.s_addr = htonl(INADDR_ANY); int bind_status = bind(sockfd, (struct sockaddr*)&new_addr, sizeof(new_addr)); while(1) { char bcast_buffer[1024]; memset(bcast_buffer, 0, sizeof(bcast_buffer)); recvfrom(sockfd, bcast_buffer, sizeof(bcast_buffer)-1, 0, (sockaddr *)&cli_addr, &slen); std::cout << "Listening.." <<std::endl; std::cout << "GOT FS" << bcast_buffer << std::endl; } } int main(int argc, char **argv) { std::thread broadcaster(fs_bcast); std::thread listener(bcast_listener); broadcaster.detach(); listener.detach(); while(1){} return SUCCESS; } <commit_msg>totally stuck<commit_after>#include<iostream> #include<vector> #include<cstdio> #include<string> #include<thread> #include<dirent.h> #include<chrono> #include<sys/socket.h> #include<netinet/in.h> #include<sys/types.h> #include<arpa/inet.h> #include<fcntl.h> #include<unistd.h> #include<cstdlib> #include<sys/wait.h> #include<string.h> #include<mutex> #include<unordered_map> #include <iostream> #include <fstream> #define SUCCESS 0 #define FAILURE 1 #define MAX_SIZE 1024 #define CLI_ID "101" #define TOKEN "#" #define BCAST_PORT 6000 #define LISTENER_PORT 54545 char Client_id[15]={0}; char b_cast_time[10]={0}; std::unordered_map<std::string,std::string> cluster_info; void config_parser() { FILE *config_file; char line[255]; config_file = fopen("../config/config","r"); while(fgets(line,sizeof(line),config_file)) { if(line[0]=='\n') continue; else { } } //std::fstream config_file; //char line[255]; //config_file.open("../config/config",std::ios::in|std::ios::out); /* while(config_file.getline(line,255)) { if('\n'==line[0]) continue; else { std::cout<<line<<std::endl; char* ip =strtok(line,"="); //cluster_info[ip]=port; } } */ } void fs_bcast() { //Current Client Socket int bcast_sockfd; bcast_sockfd = socket(AF_INET, SOCK_DGRAM, 0); struct sockaddr_in new_addr; memset(&new_addr, 0, sizeof(new_addr)); new_addr.sin_family = AF_INET; new_addr.sin_port = BCAST_PORT; new_addr.sin_addr.s_addr = htonl(INADDR_ANY); while(1) { std::this_thread::sleep_for(std::chrono::milliseconds(5000)); DIR *dir; struct dirent *ent; char fs_data[MAX_SIZE]; memset(fs_data, 0, MAX_SIZE); strcpy(fs_data, CLI_ID); if ((dir = opendir ("./")) != NULL) { while((ent = readdir (dir)) != NULL) { if (!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, "..")) {continue;} else { strcat(fs_data, TOKEN); strcat(fs_data, ent->d_name); } } } closedir (dir); std::cout << fs_data << std::endl; sendto(bcast_sockfd, fs_data, strlen(fs_data), 0, (struct sockaddr *)&new_addr, sizeof(struct sockaddr_in)); } } void bcast_listener() { int sockfd; std::cout<<"Hello"<<std::endl; struct sockaddr_in new_addr; struct sockaddr_in cli_addr; unsigned slen = sizeof(cli_addr); sockfd = socket(AF_INET, SOCK_DGRAM, 0); memset(&new_addr, 0, sizeof(new_addr)); new_addr.sin_family = AF_INET; new_addr.sin_port = LISTENER_PORT; new_addr.sin_addr.s_addr = htonl(INADDR_ANY); int bind_status = bind(sockfd, (struct sockaddr*)&new_addr, sizeof(new_addr)); while(1) { char bcast_buffer[1024]; memset(bcast_buffer, 0, sizeof(bcast_buffer)); recvfrom(sockfd, bcast_buffer, sizeof(bcast_buffer)-1, 0, (sockaddr *)&cli_addr, &slen); std::cout << "Listening.." <<std::endl; std::cout << "GOT FS" << bcast_buffer << std::endl; } } int main(int argc, char **argv) { config_parser(); std::thread broadcaster(fs_bcast); std::thread listener(bcast_listener); broadcaster.detach(); listener.detach(); while(1){} return SUCCESS; } <|endoftext|>
<commit_before>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2015 * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #ifndef CAF_DETAIL_APPLY_ARGS_HPP #define CAF_DETAIL_APPLY_ARGS_HPP #include <utility> #include "caf/detail/int_list.hpp" #include "caf/detail/type_list.hpp" namespace caf { namespace detail { // this utterly useless function works around a bug in Clang that causes // the compiler to reject the trailing return type of apply_args because // "get" is not defined (it's found during ADL) template<long Pos, class... Ts> typename tl_at<type_list<Ts...>, Pos>::type get(const type_list<Ts...>&); template <class F, long... Is, class Tuple> auto apply_args(F& f, detail::int_list<Is...>, Tuple&& tup) -> decltype(f(get<Is>(tup)...)) { return f(get<Is>(tup)...); } template <class F, class Tuple, class... Ts> auto apply_args_prefixed(F& f, detail::int_list<>, Tuple&, Ts&&... xs) -> decltype(f(std::forward<Ts>(xs)...)) { return f(std::forward<Ts>(xs)...); } template <class F, long... Is, class Tuple, class... Ts> auto apply_args_prefixed(F& f, detail::int_list<Is...>, Tuple& tup, Ts&&... xs) -> decltype(f(std::forward<Ts>(xs)..., get<Is>(tup)...)) { return f(std::forward<Ts>(xs)..., get<Is>(tup)...); } template <class F, long... Is, class Tuple, class... Ts> auto apply_args_suffxied(F& f, detail::int_list<Is...>, Tuple& tup, Ts&&... xs) -> decltype(f(get<Is>(tup)..., std::forward<Ts>(xs)...)) { return f(get<Is>(tup)..., std::forward<Ts>(xs)...); } } // namespace detail } // namespace caf #endif // CAF_DETAIL_APPLY_ARGS_HPP <commit_msg>Fix inconsistent reference in signature<commit_after>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2015 * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #ifndef CAF_DETAIL_APPLY_ARGS_HPP #define CAF_DETAIL_APPLY_ARGS_HPP #include <utility> #include "caf/detail/int_list.hpp" #include "caf/detail/type_list.hpp" namespace caf { namespace detail { // this utterly useless function works around a bug in Clang that causes // the compiler to reject the trailing return type of apply_args because // "get" is not defined (it's found during ADL) template<long Pos, class... Ts> typename tl_at<type_list<Ts...>, Pos>::type get(const type_list<Ts...>&); template <class F, long... Is, class Tuple> auto apply_args(F& f, detail::int_list<Is...>, Tuple& tup) -> decltype(f(get<Is>(tup)...)) { return f(get<Is>(tup)...); } template <class F, class Tuple, class... Ts> auto apply_args_prefixed(F& f, detail::int_list<>, Tuple&, Ts&&... xs) -> decltype(f(std::forward<Ts>(xs)...)) { return f(std::forward<Ts>(xs)...); } template <class F, long... Is, class Tuple, class... Ts> auto apply_args_prefixed(F& f, detail::int_list<Is...>, Tuple& tup, Ts&&... xs) -> decltype(f(std::forward<Ts>(xs)..., get<Is>(tup)...)) { return f(std::forward<Ts>(xs)..., get<Is>(tup)...); } template <class F, long... Is, class Tuple, class... Ts> auto apply_args_suffxied(F& f, detail::int_list<Is...>, Tuple& tup, Ts&&... xs) -> decltype(f(get<Is>(tup)..., std::forward<Ts>(xs)...)) { return f(get<Is>(tup)..., std::forward<Ts>(xs)...); } } // namespace detail } // namespace caf #endif // CAF_DETAIL_APPLY_ARGS_HPP <|endoftext|>
<commit_before>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2015 * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #include <limits> #include "caf/binary_serializer.hpp" namespace caf { class binary_writer : public static_visitor<> { public: using write_fun = binary_serializer::write_fun; explicit binary_writer(write_fun& sink) : out_(sink) { // nop } template <class T> static inline void write_int(write_fun& f, const T& value) { auto first = reinterpret_cast<const char*>(&value); auto last = first + sizeof(T); f(first, last); } static inline void write_string(write_fun& f, const std::string& str) { write_int(f, static_cast<uint32_t>(str.size())); auto first = str.data(); auto last = first + str.size(); f(first, last); } void operator()(const bool& value) const { write_int(out_, static_cast<uint8_t>(value)); } template <class T> typename std::enable_if<std::is_integral<T>::value>::type operator()(const T& value) const { write_int(out_, value); } template <class T> typename std::enable_if<std::is_floating_point<T>::value>::type operator()(const T& value) const { auto tmp = detail::pack754(value); write_int(out_, tmp); } // the IEEE-754 conversion does not work for long double // => fall back to string serialization (event though it sucks) void operator()(const long double& v) const { std::ostringstream oss; oss << std::setprecision(std::numeric_limits<long double>::digits) << v; write_string(out_, oss.str()); } void operator()(const atom_value& val) const { (*this)(static_cast<uint64_t>(val)); } void operator()(const std::string& str) const { write_string(out_, str); } void operator()(const std::u16string& str) const { // write size as 32 bit unsigned write_int(out_, static_cast<uint32_t>(str.size())); for (char16_t c : str) { // force writer to use exactly 16 bit write_int(out_, static_cast<uint16_t>(c)); } } void operator()(const std::u32string& str) const { // write size as 32 bit unsigned write_int(out_, static_cast<uint32_t>(str.size())); for (char32_t c : str) { // force writer to use exactly 32 bit write_int(out_, static_cast<uint32_t>(c)); } } private: write_fun& out_; }; void binary_serializer::begin_object(const uniform_type_info* uti) { auto nr = uti->type_nr(); binary_writer::write_int(out_, nr); if (! nr) { binary_writer::write_string(out_, uti->name()); } } void binary_serializer::end_object() { // nop } void binary_serializer::begin_sequence(size_t list_size) { binary_writer::write_int(out_, static_cast<uint32_t>(list_size)); } void binary_serializer::end_sequence() { // nop } void binary_serializer::write_value(const primitive_variant& value) { binary_writer bw{out_}; apply_visitor(bw, value); } void binary_serializer::write_raw(size_t num_bytes, const void* data) { auto first = reinterpret_cast<const char*>(data); auto last = first + num_bytes; out_(first, last); } } // namespace caf <commit_msg>Use temporary variable to avoid confusing Coverity<commit_after>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2015 * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #include <limits> #include "caf/binary_serializer.hpp" namespace caf { class binary_writer : public static_visitor<> { public: using write_fun = binary_serializer::write_fun; explicit binary_writer(write_fun& sink) : out_(sink) { // nop } template <class T> static inline void write_int(write_fun& f, const T& value) { auto first = reinterpret_cast<const char*>(&value); auto last = first + sizeof(T); f(first, last); } static inline void write_string(write_fun& f, const std::string& str) { write_int(f, static_cast<uint32_t>(str.size())); auto first = str.data(); auto last = first + str.size(); f(first, last); } void operator()(const bool& value) const { uint8_t tmp = value ? 1 : 0; write_int(out_, tmp); } template <class T> typename std::enable_if<std::is_integral<T>::value>::type operator()(const T& value) const { write_int(out_, value); } template <class T> typename std::enable_if<std::is_floating_point<T>::value>::type operator()(const T& value) const { auto tmp = detail::pack754(value); write_int(out_, tmp); } // the IEEE-754 conversion does not work for long double // => fall back to string serialization (event though it sucks) void operator()(const long double& v) const { std::ostringstream oss; oss << std::setprecision(std::numeric_limits<long double>::digits) << v; write_string(out_, oss.str()); } void operator()(const atom_value& val) const { (*this)(static_cast<uint64_t>(val)); } void operator()(const std::string& str) const { write_string(out_, str); } void operator()(const std::u16string& str) const { // write size as 32 bit unsigned write_int(out_, static_cast<uint32_t>(str.size())); for (char16_t c : str) { // force writer to use exactly 16 bit write_int(out_, static_cast<uint16_t>(c)); } } void operator()(const std::u32string& str) const { // write size as 32 bit unsigned write_int(out_, static_cast<uint32_t>(str.size())); for (char32_t c : str) { // force writer to use exactly 32 bit write_int(out_, static_cast<uint32_t>(c)); } } private: write_fun& out_; }; void binary_serializer::begin_object(const uniform_type_info* uti) { auto nr = uti->type_nr(); binary_writer::write_int(out_, nr); if (! nr) { binary_writer::write_string(out_, uti->name()); } } void binary_serializer::end_object() { // nop } void binary_serializer::begin_sequence(size_t list_size) { binary_writer::write_int(out_, static_cast<uint32_t>(list_size)); } void binary_serializer::end_sequence() { // nop } void binary_serializer::write_value(const primitive_variant& value) { binary_writer bw{out_}; apply_visitor(bw, value); } void binary_serializer::write_raw(size_t num_bytes, const void* data) { auto first = reinterpret_cast<const char*>(data); auto last = first + num_bytes; out_(first, last); } } // namespace caf <|endoftext|>
<commit_before>#include <cassert> #include <algorithm> #include "proc.hh" #include "io.hh" namespace ten { static std::atomic<uint64_t> taskidgen(0); void tasksleep(uint64_t ms) { task::cancellation_point cancellable; this_proc()->sched().sleep(milliseconds(ms)); } bool fdwait(int fd, int rw, uint64_t ms) { task::cancellation_point cancellable; return this_proc()->sched().fdwait(fd, rw, ms); } int taskpoll(pollfd *fds, nfds_t nfds, uint64_t ms) { task::cancellation_point cancellable; return this_proc()->sched().poll(fds, nfds, ms); } uint64_t taskspawn(const std::function<void ()> &f, size_t stacksize) { task *t = this_proc()->newtaskinproc(f, stacksize); t->ready(); return t->id; } uint64_t taskid() { DCHECK(this_proc()); DCHECK(this_task()); return this_task()->id; } int64_t taskyield() { task::cancellation_point cancellable; proc *p = this_proc(); uint64_t n = p->nswitch; task *t = p->ctask; t->ready(); taskstate("yield"); t->swap(); DVLOG(5) << "yield: " << (int64_t)(p->nswitch - n - 1); return p->nswitch - n - 1; } void tasksystem() { proc *p = this_proc(); p->mark_system_task(); } bool taskcancel(uint64_t id) { proc *p = this_proc(); DCHECK(p) << "BUG: taskcancel called in null proc"; return p->cancel_task_by_id(id); } const char *taskname(const char *fmt, ...) { task *t = this_task(); if (fmt && strlen(fmt)) { va_list arg; va_start(arg, fmt); t->vsetname(fmt, arg); va_end(arg); } return t->name; } const char *taskstate(const char *fmt, ...) { task *t = this_task(); if (fmt && strlen(fmt)) { va_list arg; va_start(arg, fmt); t->vsetstate(fmt, arg); va_end(arg); } return t->state; } std::string taskdump() { std::stringstream ss; proc *p = this_proc(); DCHECK(p) << "BUG: taskdump called in null proc"; p->dump_tasks(ss); return ss.str(); } void taskdumpf(FILE *of) { std::string dump = taskdump(); fwrite(dump.c_str(), sizeof(char), dump.size(), of); fflush(of); } task::task(const std::function<void ()> &f, size_t stacksize) : co(task::start, this, stacksize) { clear(); fn = f; } void task::init(const std::function<void ()> &f) { fn = f; co.restart(task::start, this); } void task::ready() { proc *p = cproc; if (!_ready.exchange(true)) { p->ready(this); } } task::~task() { clear(false); } void task::clear(bool newid) { fn = nullptr; cancel_points = 0; _ready = false; systask = false; canceled = false; if (newid) { id = ++taskidgen; setname("task[%ju]", id); setstate("new"); } if (!timeouts.empty()) { // free timeouts for (auto i=timeouts.begin(); i<timeouts.end(); ++i) { delete *i; } timeouts.clear(); // remove from scheduler timeout list cproc->sched().remove_timeout_task(this); } cproc = nullptr; } void task::remove_timeout(timeout_t *to) { auto i = std::find(timeouts.begin(), timeouts.end(), to); if (i != timeouts.end()) { delete *i; timeouts.erase(i); } if (timeouts.empty()) { // remove from scheduler timeout list cproc->sched().remove_timeout_task(this); } } void task::safe_swap() noexcept { // swap to scheduler coroutine co.swap(&this_proc()->sched_coro()); } void task::swap() { // swap to scheduler coroutine co.swap(&this_proc()->sched_coro()); if (canceled && cancel_points > 0) { DVLOG(5) << "THROW INTERRUPT: " << this << "\n" << saved_backtrace().str(); throw task_interrupted(); } while (!timeouts.empty()) { timeout_t *to = timeouts.front(); if (to->when <= procnow()) { std::unique_ptr<timeout_t> tmp{to}; // ensure to is freed DVLOG(5) << to << " reached for " << this << " removing."; timeouts.pop_front(); if (timeouts.empty()) { // remove from scheduler timeout list cproc->sched().remove_timeout_task(this); } if (tmp->exception != nullptr) { DVLOG(5) << "THROW TIMEOUT: " << this << "\n" << saved_backtrace().str(); std::rethrow_exception(tmp->exception); } } else { break; } } } deadline::deadline(milliseconds ms) { if (ms.count() < 0) throw errorx("negative deadline: %jdms", intmax_t(ms.count())); if (ms.count() > 0) { task *t = this_task(); timeout_id = this_proc()->sched().add_timeout(t, ms, deadline_reached()); } } void deadline::cancel() { if (timeout_id) { task *t = this_task(); t->remove_timeout((task::timeout_t *)timeout_id); timeout_id = nullptr; } } deadline::~deadline() { cancel(); } milliseconds deadline::remaining() const { task::timeout_t *timeout = (task::timeout_t *)timeout_id; // TODO: need a way of distinguishing between canceled and over due if (timeout != nullptr) { std::chrono::time_point<std::chrono::steady_clock> now = procnow(); if (now > timeout->when) { return milliseconds(0); } return duration_cast<milliseconds>(timeout->when - now); } return milliseconds(0); } task::cancellation_point::cancellation_point() { task *t = this_task(); ++t->cancel_points; } task::cancellation_point::~cancellation_point() { task *t = this_task(); --t->cancel_points; } } // end namespace ten <commit_msg>avoid uninit memory for inactive deadline object<commit_after>#include <cassert> #include <algorithm> #include "proc.hh" #include "io.hh" namespace ten { static std::atomic<uint64_t> taskidgen(0); void tasksleep(uint64_t ms) { task::cancellation_point cancellable; this_proc()->sched().sleep(milliseconds(ms)); } bool fdwait(int fd, int rw, uint64_t ms) { task::cancellation_point cancellable; return this_proc()->sched().fdwait(fd, rw, ms); } int taskpoll(pollfd *fds, nfds_t nfds, uint64_t ms) { task::cancellation_point cancellable; return this_proc()->sched().poll(fds, nfds, ms); } uint64_t taskspawn(const std::function<void ()> &f, size_t stacksize) { task *t = this_proc()->newtaskinproc(f, stacksize); t->ready(); return t->id; } uint64_t taskid() { DCHECK(this_proc()); DCHECK(this_task()); return this_task()->id; } int64_t taskyield() { task::cancellation_point cancellable; proc *p = this_proc(); uint64_t n = p->nswitch; task *t = p->ctask; t->ready(); taskstate("yield"); t->swap(); DVLOG(5) << "yield: " << (int64_t)(p->nswitch - n - 1); return p->nswitch - n - 1; } void tasksystem() { proc *p = this_proc(); p->mark_system_task(); } bool taskcancel(uint64_t id) { proc *p = this_proc(); DCHECK(p) << "BUG: taskcancel called in null proc"; return p->cancel_task_by_id(id); } const char *taskname(const char *fmt, ...) { task *t = this_task(); if (fmt && strlen(fmt)) { va_list arg; va_start(arg, fmt); t->vsetname(fmt, arg); va_end(arg); } return t->name; } const char *taskstate(const char *fmt, ...) { task *t = this_task(); if (fmt && strlen(fmt)) { va_list arg; va_start(arg, fmt); t->vsetstate(fmt, arg); va_end(arg); } return t->state; } std::string taskdump() { std::stringstream ss; proc *p = this_proc(); DCHECK(p) << "BUG: taskdump called in null proc"; p->dump_tasks(ss); return ss.str(); } void taskdumpf(FILE *of) { std::string dump = taskdump(); fwrite(dump.c_str(), sizeof(char), dump.size(), of); fflush(of); } task::task(const std::function<void ()> &f, size_t stacksize) : co(task::start, this, stacksize) { clear(); fn = f; } void task::init(const std::function<void ()> &f) { fn = f; co.restart(task::start, this); } void task::ready() { proc *p = cproc; if (!_ready.exchange(true)) { p->ready(this); } } task::~task() { clear(false); } void task::clear(bool newid) { fn = nullptr; cancel_points = 0; _ready = false; systask = false; canceled = false; if (newid) { id = ++taskidgen; setname("task[%ju]", id); setstate("new"); } if (!timeouts.empty()) { // free timeouts for (auto i=timeouts.begin(); i<timeouts.end(); ++i) { delete *i; } timeouts.clear(); // remove from scheduler timeout list cproc->sched().remove_timeout_task(this); } cproc = nullptr; } void task::remove_timeout(timeout_t *to) { auto i = std::find(timeouts.begin(), timeouts.end(), to); if (i != timeouts.end()) { delete *i; timeouts.erase(i); } if (timeouts.empty()) { // remove from scheduler timeout list cproc->sched().remove_timeout_task(this); } } void task::safe_swap() noexcept { // swap to scheduler coroutine co.swap(&this_proc()->sched_coro()); } void task::swap() { // swap to scheduler coroutine co.swap(&this_proc()->sched_coro()); if (canceled && cancel_points > 0) { DVLOG(5) << "THROW INTERRUPT: " << this << "\n" << saved_backtrace().str(); throw task_interrupted(); } while (!timeouts.empty()) { timeout_t *to = timeouts.front(); if (to->when <= procnow()) { std::unique_ptr<timeout_t> tmp{to}; // ensure to is freed DVLOG(5) << to << " reached for " << this << " removing."; timeouts.pop_front(); if (timeouts.empty()) { // remove from scheduler timeout list cproc->sched().remove_timeout_task(this); } if (tmp->exception != nullptr) { DVLOG(5) << "THROW TIMEOUT: " << this << "\n" << saved_backtrace().str(); std::rethrow_exception(tmp->exception); } } else { break; } } } deadline::deadline(milliseconds ms) : timeout_id() { if (ms.count() < 0) throw errorx("negative deadline: %jdms", intmax_t(ms.count())); if (ms.count() > 0) { task *t = this_task(); timeout_id = this_proc()->sched().add_timeout(t, ms, deadline_reached()); } } void deadline::cancel() { if (timeout_id) { task *t = this_task(); t->remove_timeout((task::timeout_t *)timeout_id); timeout_id = nullptr; } } deadline::~deadline() { cancel(); } milliseconds deadline::remaining() const { task::timeout_t *timeout = (task::timeout_t *)timeout_id; // TODO: need a way of distinguishing between canceled and over due if (timeout != nullptr) { std::chrono::time_point<std::chrono::steady_clock> now = procnow(); if (now > timeout->when) { return milliseconds(0); } return duration_cast<milliseconds>(timeout->when - now); } return milliseconds(0); } task::cancellation_point::cancellation_point() { task *t = this_task(); ++t->cancel_points; } task::cancellation_point::~cancellation_point() { task *t = this_task(); --t->cancel_points; } } // end namespace ten <|endoftext|>
<commit_before>/* This file is part of the KDE project Copyright (C) 2004 David Faure <faure@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // Test program for libemailfunctions/email.h #include "email.h" #include <kcmdlineargs.h> #include <kapplication.h> #include <kdebug.h> #include <stdio.h> #include <stdlib.h> #include <assert.h> using namespace KPIM; static bool check(const QString& txt, const QString& a, const QString& b) { if (a == b) { kdDebug() << txt << " : checking '" << a << "' against expected value '" << b << "'... " << "ok" << endl; } else { kdDebug() << txt << " : checking '" << a << "' against expected value '" << b << "'... " << "KO !" << endl; exit(1); } return true; } static bool checkGetNameAndEmail(const QString& input, const QString& expName, const QString& expEmail, bool expRetVal) { QString name, email; bool retVal = KPIM::getNameAndMail(input, name, email); check( "getNameAndMail " + input + " retVal", retVal?"true":"false", expRetVal?"true":"false" ); check( "getNameAndMail " + input + " name", name, expName ); check( "getNameAndMail " + input + " email", email, expEmail ); return true; } // convert this to a switch instead but hey, nothing speedy in here is needed but still.. it would be nice static QString emailTestParseResultToString( EmailParseResult errorCode ) { if( errorCode == TooManyAts ) { return "TooManyAts"; } else if( errorCode == TooFewAts ) { return "TooFewAts"; } else if( errorCode == AddressEmpty ) { return "AddressEmpty"; } else if( errorCode == MissingLocalPart ) { return "MissingLocalPart"; } else if( errorCode == MissingDomainPart ) { return "MissingDomainPart"; } else if( errorCode == UnbalancedParens ) { return "UnbalancedParens"; } else if( errorCode == AddressOk ) { return "AddressOk"; } else if( errorCode == UnclosedAngleAddr ) { return "UnclosedAngleAddr"; } else if( errorCode == UnexpectedEnd ) { return "UnexpectedEnd"; } else if( errorCode == UnopenedAngleAddr ) { return "UnopenedAngleAddr"; } return "unknown errror code"; } static QString simpleEmailTestParseResultToString( bool validEmail ) { if ( validEmail ) { return "true"; } return "false"; } static QString getEmailParseResultToString( QCString emailAddress ) { return QString( emailAddress ); } static QString getSplitEmailParseResultToString( QStringList emailAddresses ) { return QString( emailAddresses.join( "," ) ); } static bool checkIsValidEmailAddress( const QString& input, const QString& expErrorCode ) { EmailParseResult errorCode = KPIM::isValidEmailAddress( input ); QString errorC = emailTestParseResultToString( errorCode ); check( "isValidEmailAddress " + input + " errorCode ", errorC , expErrorCode ); return true; } static bool checkIsValidSimpleEmailAddress( const QString& input, const QString& expResult ) { bool validEmail = KPIM::isValidSimpleEmailAddress( input ); QString result = simpleEmailTestParseResultToString( validEmail ); check( "isValidSimpleEmailAddress " + input + " result ", result, expResult ); return true; } static bool checkGetEmailAddress( const QString& input, const QString& expResult ) { QString emailAddress = KPIM::getEmailAddress( input ); QString result = emailAddress; check( "getEmailAddress " + input + " result ", result, expResult ); return true; } static bool checkSplitEmailAddrList( const QString& input, const QString& expResult ) { QStringList emailAddresses = KPIM::splitEmailAddrList( input ); QString result = getSplitEmailParseResultToString( emailAddresses ); check( "splitEmailAddrList " + input + " result ", result, expResult ); return true; } int main(int argc, char *argv[]) { KApplication::disableAutoDcopRegistration(); KCmdLineArgs::init( argc, argv, "testemail", 0, 0, 0, 0 ); KApplication app( false, false ); // Empty input checkGetNameAndEmail( QString::null, QString::null, QString::null, false ); // Email only checkGetNameAndEmail( "faure@kde.org", QString::null, "faure@kde.org", false ); // Normal case checkGetNameAndEmail( "David Faure <faure@kde.org>", "David Faure", "faure@kde.org", true ); // Double-quotes checkGetNameAndEmail( "\"Faure, David\" <faure@kde.org>", "Faure, David", "faure@kde.org", true ); checkGetNameAndEmail( "<faure@kde.org> \"David Faure\"", "David Faure", "faure@kde.org", true ); // Parenthesis checkGetNameAndEmail( "faure@kde.org (David Faure)", "David Faure", "faure@kde.org", true ); checkGetNameAndEmail( "(David Faure) faure@kde.org", "David Faure", "faure@kde.org", true ); checkGetNameAndEmail( "My Name (me) <me@home.net>", "My Name (me)", "me@home.net", true ); // #93513 // Double-quotes inside parenthesis checkGetNameAndEmail( "faure@kde.org (David \"Crazy\" Faure)", "David \"Crazy\" Faure", "faure@kde.org", true ); checkGetNameAndEmail( "(David \"Crazy\" Faure) faure@kde.org", "David \"Crazy\" Faure", "faure@kde.org", true ); // Parenthesis inside double-quotes checkGetNameAndEmail( "\"Faure (David)\" <faure@kde.org>", "Faure (David)", "faure@kde.org", true ); checkGetNameAndEmail( "<faure@kde.org> \"Faure (David)\"", "Faure (David)", "faure@kde.org", true ); // Space in email checkGetNameAndEmail( "David Faure < faure@kde.org >", "David Faure", "faure@kde.org", true ); // Check that '@' in name doesn't confuse it checkGetNameAndEmail( "faure@kde.org (a@b)", "a@b", "faure@kde.org", true ); // Interestingly, this isn't supported. //checkGetNameAndEmail( "\"a@b\" <faure@kde.org>", "a@b", "faure@kde.org", true ); // While typing, when there's no '@' yet checkGetNameAndEmail( "foo", "foo", QString::null, false ); checkGetNameAndEmail( "foo <", "foo", QString::null, false ); checkGetNameAndEmail( "foo <b", "foo", "b", true ); // If multiple emails are there, only return the first one checkGetNameAndEmail( "\"Faure, David\" <faure@kde.org>, KHZ <khz@khz.khz>", "Faure, David", "faure@kde.org", true ); // domain literals also need to work checkGetNameAndEmail( "Matt Douhan <matt@[123.123.123.123]>", "Matt Douhan", "matt@[123.123.123.123]", true ); // No '@' checkGetNameAndEmail( "foo <distlist>", "foo", "distlist", true ); // To many @'s checkIsValidEmailAddress( "matt@@fruitsalad.org", "TooManyAts" ); // To few @'s checkIsValidEmailAddress( "mattfruitsalad.org", "TooFewAts" ); // An empty string checkIsValidEmailAddress( QString::null , "AddressEmpty" ); // email address starting with a @ checkIsValidEmailAddress( "@mattfruitsalad.org", "MissingLocalPart" ); // make sure that starting @ and an additional @ in the same email address don't conflict // trap the starting @ first and break checkIsValidEmailAddress( "@matt@fruitsalad.org", "MissingLocalPart" ); // email address ending with a @ checkIsValidEmailAddress( "mattfruitsalad.org@", "MissingDomainPart" ); // make sure that ending with@ and an additional @ in the email address don't conflict checkIsValidEmailAddress( "matt@fruitsalad.org@", "MissingDomainPart" ); // unbalanced Parens checkIsValidEmailAddress( "mattjongel)@fruitsalad.org", "UnbalancedParens" ); // unbalanced Parens the other way around checkIsValidEmailAddress( "mattjongel(@fruitsalad.org", "UnbalancedParens" ); // Correct parens just to make sure it works checkIsValidEmailAddress( "matt(jongel)@fruitsalad.org", "AddressOk" ); // Check that anglebrackets are closed checkIsValidEmailAddress( "matt douhan<matt@fruitsalad.org", "UnclosedAngleAddr" ); // Check that angle brackets are closed the other way around checkIsValidEmailAddress( "matt douhan>matt@fruitsalad.org", "UnopenedAngleAddr" ); // Check that angle brackets are closed the other way around, and anglebrackets in domainpart // instead of local part // checkIsValidEmailAddress( "matt douhanmatt@<fruitsalad.org", "UnclosedAngleAddr" ); // check that a properly formated anglebrackets situation is OK checkIsValidEmailAddress( "matt douhan<matt@fruitsalad.org>", "AddressOk" ); // a full email address with comments angle brackets and the works should be valid too checkIsValidEmailAddress( "Matt (jongel) Douhan <matt@fruitsalad.org>", "AddressOk" ); // Double quotes checkIsValidEmailAddress( "\"Matt Douhan\" <matt@fruitsalad.org>", "AddressOk" ); // Double quotes inside parens checkIsValidEmailAddress( "Matt (\"jongel\") Douhan <matt@fruitsalad.org>", "AddressOk" ); // Parens inside double quotes checkIsValidEmailAddress( "Matt \"(jongel)\" Douhan <matt@fruitsalad.org>", "AddressOk" ); // Space in email checkIsValidEmailAddress( "Matt Douhan < matt@fruitsalad.org >", "AddressOk" ); // @ is allowed inisde doublequotes checkIsValidEmailAddress( "\"matt@jongel\" <matt@fruitsalad.org>", "AddressOk" ); // anglebrackets inside dbl quotes checkIsValidEmailAddress( "\"matt<blah blah>\" <matt@fruitsalad.org>", "AddressOk" ); // a , inside a double quoted string is OK, how do I know this? well Ingo says so // and it makes sense since it is also a seperator of email addresses checkIsValidEmailAddress( "\"Douhan, Matt\" <matt@fruitsalad.org>", "AddressOk" ); // Domains literals also need to work checkIsValidEmailAddress( "Matt Douhan <matt@[123.123.123.123]>", "AddressOk" ); // Some more insane tests but still valid so they must work checkIsValidEmailAddress( "Matt Douhan <\"m@att\"@jongel.com>", "AddressOk" ); // BUG 99657 checkIsValidEmailAddress( "matt@jongel.fibbel.com", "AddressOk" ); // checks for "pure" email addresses in the form of xxx@yyy.tld checkIsValidSimpleEmailAddress( "matt@fruitsalad.org", "true" ); checkIsValidSimpleEmailAddress( QString::fromUtf8("test@täst.invalid"), "true" ); // non-ASCII char as first char of IDN checkIsValidSimpleEmailAddress( QString::fromUtf8("i_want@øl.invalid"), "true" ); checkIsValidSimpleEmailAddress( "matt@[123.123.123.123]", "true" ); checkIsValidSimpleEmailAddress( "\"matt\"@fruitsalad.org", "true" ); checkIsValidSimpleEmailAddress( "-matt@fruitsalad.org", "true" ); checkIsValidSimpleEmailAddress( "\"-matt\"@fruitsalad.org", "true" ); checkIsValidSimpleEmailAddress( "matt@jongel.fibbel.com", "true" ); checkIsValidSimpleEmailAddress( "Matt Douhan <matt@fruitsalad.org>", "false" ); // check if the pure email address is wrong checkIsValidSimpleEmailAddress( "mattfruitsalad.org", "false" ); checkIsValidSimpleEmailAddress( "matt@[123.123.123.123", "false" ); checkIsValidSimpleEmailAddress( "matt@123.123.123.123]", "false" ); checkIsValidSimpleEmailAddress( "\"matt@fruitsalad.org", "false" ); checkIsValidSimpleEmailAddress( "matt\"@fruitsalad.org", "false" ); checkIsValidSimpleEmailAddress( QString::null, "false" ); // and here some insane but still valid cases checkIsValidSimpleEmailAddress( "\"m@tt\"@fruitsalad.org", "true" ); // check the getEmailAddress address method checkGetEmailAddress( "matt@fruitsalad.org", "matt@fruitsalad.org" ); checkGetEmailAddress( "Matt Douhan <matt@fruitsalad.org>", "matt@fruitsalad.org" ); checkGetEmailAddress( "\"Matt Douhan <blah blah>\" <matt@fruitsalad.org>", "matt@fruitsalad.org" ); checkGetEmailAddress( "\"Matt <blah blah>\" <matt@fruitsalad.org>", "matt@fruitsalad.org" ); checkGetEmailAddress( "Matt Douhan (jongel) <matt@fruitsalad.org", QString() ); checkGetEmailAddress( "Matt Douhan (m@tt) <matt@fruitsalad.org>", "matt@fruitsalad.org" ); checkGetEmailAddress( "\"Douhan, Matt\" <matt@fruitsalad.org>", "matt@fruitsalad.org" ); checkGetEmailAddress( "\"Matt Douhan (m@tt)\" <matt@fruitsalad.org>", "matt@fruitsalad.org" ); checkGetEmailAddress( "\"Matt Douhan\" (matt <matt@fruitsalad.org>", QString() ); checkGetEmailAddress( "Matt Douhan <matt@[123.123.123.123]>", "matt@[123.123.123.123]" ); // check the splitEmailAddrList method checkSplitEmailAddrList( "Matt Douhan <matt@fruitsalad.org>, Foo Bar <foo@bar.com>", "Matt Douhan <matt@fruitsalad.org>,Foo Bar <foo@bar.com>" ); checkSplitEmailAddrList( "\"Matt, Douhan\" <matt@fruitsalad.org>, Foo Bar <foo@bar.com>", "\"Matt, Douhan\" <matt@fruitsalad.org>,Foo Bar <foo@bar.com>" ); printf("\nTest OK !\n"); return 0; } <commit_msg>Update testframeowrk to cater for BUG:98720<commit_after>/* This file is part of the KDE project Copyright (C) 2004 David Faure <faure@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // Test program for libemailfunctions/email.h #include "email.h" #include <kcmdlineargs.h> #include <kapplication.h> #include <kdebug.h> #include <stdio.h> #include <stdlib.h> #include <assert.h> using namespace KPIM; static bool check(const QString& txt, const QString& a, const QString& b) { if (a == b) { kdDebug() << txt << " : checking '" << a << "' against expected value '" << b << "'... " << "ok" << endl; } else { kdDebug() << txt << " : checking '" << a << "' against expected value '" << b << "'... " << "KO !" << endl; exit(1); } return true; } static bool checkGetNameAndEmail(const QString& input, const QString& expName, const QString& expEmail, bool expRetVal) { QString name, email; bool retVal = KPIM::getNameAndMail(input, name, email); check( "getNameAndMail " + input + " retVal", retVal?"true":"false", expRetVal?"true":"false" ); check( "getNameAndMail " + input + " name", name, expName ); check( "getNameAndMail " + input + " email", email, expEmail ); return true; } // convert this to a switch instead but hey, nothing speedy in here is needed but still.. it would be nice static QString emailTestParseResultToString( EmailParseResult errorCode ) { if( errorCode == TooManyAts ) { return "TooManyAts"; } else if( errorCode == TooFewAts ) { return "TooFewAts"; } else if( errorCode == AddressEmpty ) { return "AddressEmpty"; } else if( errorCode == MissingLocalPart ) { return "MissingLocalPart"; } else if( errorCode == MissingDomainPart ) { return "MissingDomainPart"; } else if( errorCode == UnbalancedParens ) { return "UnbalancedParens"; } else if( errorCode == AddressOk ) { return "AddressOk"; } else if( errorCode == UnclosedAngleAddr ) { return "UnclosedAngleAddr"; } else if( errorCode == UnexpectedEnd ) { return "UnexpectedEnd"; } else if( errorCode == UnopenedAngleAddr ) { return "UnopenedAngleAddr"; } else if( errorCode == DisallowedChar ) { return "DisallowedChar"; } return "unknown errror code"; } static QString simpleEmailTestParseResultToString( bool validEmail ) { if ( validEmail ) { return "true"; } return "false"; } static QString getEmailParseResultToString( QCString emailAddress ) { return QString( emailAddress ); } static QString getSplitEmailParseResultToString( QStringList emailAddresses ) { return QString( emailAddresses.join( "," ) ); } static bool checkIsValidEmailAddress( const QString& input, const QString& expErrorCode ) { EmailParseResult errorCode = KPIM::isValidEmailAddress( input ); QString errorC = emailTestParseResultToString( errorCode ); check( "isValidEmailAddress " + input + " errorCode ", errorC , expErrorCode ); return true; } static bool checkIsValidSimpleEmailAddress( const QString& input, const QString& expResult ) { bool validEmail = KPIM::isValidSimpleEmailAddress( input ); QString result = simpleEmailTestParseResultToString( validEmail ); check( "isValidSimpleEmailAddress " + input + " result ", result, expResult ); return true; } static bool checkGetEmailAddress( const QString& input, const QString& expResult ) { QString emailAddress = KPIM::getEmailAddress( input ); QString result = emailAddress; check( "getEmailAddress " + input + " result ", result, expResult ); return true; } static bool checkSplitEmailAddrList( const QString& input, const QString& expResult ) { QStringList emailAddresses = KPIM::splitEmailAddrList( input ); QString result = getSplitEmailParseResultToString( emailAddresses ); check( "splitEmailAddrList " + input + " result ", result, expResult ); return true; } int main(int argc, char *argv[]) { KApplication::disableAutoDcopRegistration(); KCmdLineArgs::init( argc, argv, "testemail", 0, 0, 0, 0 ); KApplication app( false, false ); // Empty input checkGetNameAndEmail( QString::null, QString::null, QString::null, false ); // Email only checkGetNameAndEmail( "faure@kde.org", QString::null, "faure@kde.org", false ); // Normal case checkGetNameAndEmail( "David Faure <faure@kde.org>", "David Faure", "faure@kde.org", true ); // Double-quotes checkGetNameAndEmail( "\"Faure, David\" <faure@kde.org>", "Faure, David", "faure@kde.org", true ); checkGetNameAndEmail( "<faure@kde.org> \"David Faure\"", "David Faure", "faure@kde.org", true ); // Parenthesis checkGetNameAndEmail( "faure@kde.org (David Faure)", "David Faure", "faure@kde.org", true ); checkGetNameAndEmail( "(David Faure) faure@kde.org", "David Faure", "faure@kde.org", true ); checkGetNameAndEmail( "My Name (me) <me@home.net>", "My Name (me)", "me@home.net", true ); // #93513 // Double-quotes inside parenthesis checkGetNameAndEmail( "faure@kde.org (David \"Crazy\" Faure)", "David \"Crazy\" Faure", "faure@kde.org", true ); checkGetNameAndEmail( "(David \"Crazy\" Faure) faure@kde.org", "David \"Crazy\" Faure", "faure@kde.org", true ); // Parenthesis inside double-quotes checkGetNameAndEmail( "\"Faure (David)\" <faure@kde.org>", "Faure (David)", "faure@kde.org", true ); checkGetNameAndEmail( "<faure@kde.org> \"Faure (David)\"", "Faure (David)", "faure@kde.org", true ); // Space in email checkGetNameAndEmail( "David Faure < faure@kde.org >", "David Faure", "faure@kde.org", true ); // Check that '@' in name doesn't confuse it checkGetNameAndEmail( "faure@kde.org (a@b)", "a@b", "faure@kde.org", true ); // Interestingly, this isn't supported. //checkGetNameAndEmail( "\"a@b\" <faure@kde.org>", "a@b", "faure@kde.org", true ); // While typing, when there's no '@' yet checkGetNameAndEmail( "foo", "foo", QString::null, false ); checkGetNameAndEmail( "foo <", "foo", QString::null, false ); checkGetNameAndEmail( "foo <b", "foo", "b", true ); // If multiple emails are there, only return the first one checkGetNameAndEmail( "\"Faure, David\" <faure@kde.org>, KHZ <khz@khz.khz>", "Faure, David", "faure@kde.org", true ); // domain literals also need to work checkGetNameAndEmail( "Matt Douhan <matt@[123.123.123.123]>", "Matt Douhan", "matt@[123.123.123.123]", true ); // No '@' checkGetNameAndEmail( "foo <distlist>", "foo", "distlist", true ); // To many @'s checkIsValidEmailAddress( "matt@@fruitsalad.org", "TooManyAts" ); // To few @'s checkIsValidEmailAddress( "mattfruitsalad.org", "TooFewAts" ); // An empty string checkIsValidEmailAddress( QString::null , "AddressEmpty" ); // email address starting with a @ checkIsValidEmailAddress( "@mattfruitsalad.org", "MissingLocalPart" ); // make sure that starting @ and an additional @ in the same email address don't conflict // trap the starting @ first and break checkIsValidEmailAddress( "@matt@fruitsalad.org", "MissingLocalPart" ); // email address ending with a @ checkIsValidEmailAddress( "mattfruitsalad.org@", "MissingDomainPart" ); // make sure that ending with@ and an additional @ in the email address don't conflict checkIsValidEmailAddress( "matt@fruitsalad.org@", "MissingDomainPart" ); // unbalanced Parens checkIsValidEmailAddress( "mattjongel)@fruitsalad.org", "UnbalancedParens" ); // unbalanced Parens the other way around checkIsValidEmailAddress( "mattjongel(@fruitsalad.org", "UnbalancedParens" ); // Correct parens just to make sure it works checkIsValidEmailAddress( "matt(jongel)@fruitsalad.org", "AddressOk" ); // Check that anglebrackets are closed checkIsValidEmailAddress( "matt douhan<matt@fruitsalad.org", "UnclosedAngleAddr" ); // Check that angle brackets are closed the other way around checkIsValidEmailAddress( "matt douhan>matt@fruitsalad.org", "UnopenedAngleAddr" ); // Check that angle brackets are closed the other way around, and anglebrackets in domainpart // instead of local part // checkIsValidEmailAddress( "matt douhanmatt@<fruitsalad.org", "UnclosedAngleAddr" ); // check that a properly formated anglebrackets situation is OK checkIsValidEmailAddress( "matt douhan<matt@fruitsalad.org>", "AddressOk" ); // a full email address with comments angle brackets and the works should be valid too checkIsValidEmailAddress( "Matt (jongel) Douhan <matt@fruitsalad.org>", "AddressOk" ); // Double quotes checkIsValidEmailAddress( "\"Matt Douhan\" <matt@fruitsalad.org>", "AddressOk" ); // Double quotes inside parens checkIsValidEmailAddress( "Matt (\"jongel\") Douhan <matt@fruitsalad.org>", "AddressOk" ); // Parens inside double quotes checkIsValidEmailAddress( "Matt \"(jongel)\" Douhan <matt@fruitsalad.org>", "AddressOk" ); // Space in email checkIsValidEmailAddress( "Matt Douhan < matt@fruitsalad.org >", "AddressOk" ); // @ is allowed inisde doublequotes checkIsValidEmailAddress( "\"matt@jongel\" <matt@fruitsalad.org>", "AddressOk" ); // anglebrackets inside dbl quotes checkIsValidEmailAddress( "\"matt<blah blah>\" <matt@fruitsalad.org>", "AddressOk" ); // a , inside a double quoted string is OK, how do I know this? well Ingo says so // and it makes sense since it is also a seperator of email addresses checkIsValidEmailAddress( "\"Douhan, Matt\" <matt@fruitsalad.org>", "AddressOk" ); // Domains literals also need to work checkIsValidEmailAddress( "Matt Douhan <matt@[123.123.123.123]>", "AddressOk" ); // Some more insane tests but still valid so they must work checkIsValidEmailAddress( "Matt Douhan <\"m@att\"@jongel.com>", "AddressOk" ); // BUG 99657 checkIsValidEmailAddress( "matt@jongel.fibbel.com", "AddressOk" ); // BUG 98720 checkIsValidEmailAddress( "mailto:@mydomain", "DisallowedChar" ); // checks for "pure" email addresses in the form of xxx@yyy.tld checkIsValidSimpleEmailAddress( "matt@fruitsalad.org", "true" ); checkIsValidSimpleEmailAddress( QString::fromUtf8("test@täst.invalid"), "true" ); // non-ASCII char as first char of IDN checkIsValidSimpleEmailAddress( QString::fromUtf8("i_want@øl.invalid"), "true" ); checkIsValidSimpleEmailAddress( "matt@[123.123.123.123]", "true" ); checkIsValidSimpleEmailAddress( "\"matt\"@fruitsalad.org", "true" ); checkIsValidSimpleEmailAddress( "-matt@fruitsalad.org", "true" ); checkIsValidSimpleEmailAddress( "\"-matt\"@fruitsalad.org", "true" ); checkIsValidSimpleEmailAddress( "matt@jongel.fibbel.com", "true" ); checkIsValidSimpleEmailAddress( "Matt Douhan <matt@fruitsalad.org>", "false" ); // check if the pure email address is wrong checkIsValidSimpleEmailAddress( "mattfruitsalad.org", "false" ); checkIsValidSimpleEmailAddress( "matt@[123.123.123.123", "false" ); checkIsValidSimpleEmailAddress( "matt@123.123.123.123]", "false" ); checkIsValidSimpleEmailAddress( "\"matt@fruitsalad.org", "false" ); checkIsValidSimpleEmailAddress( "matt\"@fruitsalad.org", "false" ); checkIsValidSimpleEmailAddress( QString::null, "false" ); // and here some insane but still valid cases checkIsValidSimpleEmailAddress( "\"m@tt\"@fruitsalad.org", "true" ); // check the getEmailAddress address method checkGetEmailAddress( "matt@fruitsalad.org", "matt@fruitsalad.org" ); checkGetEmailAddress( "Matt Douhan <matt@fruitsalad.org>", "matt@fruitsalad.org" ); checkGetEmailAddress( "\"Matt Douhan <blah blah>\" <matt@fruitsalad.org>", "matt@fruitsalad.org" ); checkGetEmailAddress( "\"Matt <blah blah>\" <matt@fruitsalad.org>", "matt@fruitsalad.org" ); checkGetEmailAddress( "Matt Douhan (jongel) <matt@fruitsalad.org", QString() ); checkGetEmailAddress( "Matt Douhan (m@tt) <matt@fruitsalad.org>", "matt@fruitsalad.org" ); checkGetEmailAddress( "\"Douhan, Matt\" <matt@fruitsalad.org>", "matt@fruitsalad.org" ); checkGetEmailAddress( "\"Matt Douhan (m@tt)\" <matt@fruitsalad.org>", "matt@fruitsalad.org" ); checkGetEmailAddress( "\"Matt Douhan\" (matt <matt@fruitsalad.org>", QString() ); checkGetEmailAddress( "Matt Douhan <matt@[123.123.123.123]>", "matt@[123.123.123.123]" ); // check the splitEmailAddrList method checkSplitEmailAddrList( "Matt Douhan <matt@fruitsalad.org>, Foo Bar <foo@bar.com>", "Matt Douhan <matt@fruitsalad.org>,Foo Bar <foo@bar.com>" ); checkSplitEmailAddrList( "\"Matt, Douhan\" <matt@fruitsalad.org>, Foo Bar <foo@bar.com>", "\"Matt, Douhan\" <matt@fruitsalad.org>,Foo Bar <foo@bar.com>" ); printf("\nTest OK !\n"); return 0; } <|endoftext|>
<commit_before>#include "VisitorPrettyPrint.h" #include "AstNode.h" #include "Return.h" #include "FunctionDeclaration.h" #include "ClassDeclaration.h" #include "Conditional.h" #include "UnaryOperator.h" #include "BinaryOperator.h" #include "Assignment.h" #include "MethodCall.h" #include "Declaration.h" #include "WhileLoop.h" #include "Array.h" #include "CompareOperator.h" #include "Range.h" namespace liquid { static inline std::string indent_spaces(size_t indent) { return std::string(indent * 2u, ' '); } void VisitorPrettyPrint::VisitExpression( Expression* expr ) { out << indent_spaces(indent) << "Create " << expr->toString() << std::endl; } void VisitorPrettyPrint::VisitStatement( Statement* stmt ) { out << indent_spaces(indent) << "Create " << stmt->toString() << std::endl; } void VisitorPrettyPrint::VisitReturnStatement( Return* retstmt ) { out << indent_spaces(indent) << "Create " << retstmt->toString() << std::endl; ++indent; retstmt->getRetExpression()->Accept(*this); --indent; } void VisitorPrettyPrint::VisitFunctionDeclaration( FunctionDeclaration* fndecl ) { out << indent_spaces(indent) << "Create " << fndecl->toString() << std::endl; ++indent; auto parameter = fndecl->getParameter(); if(parameter->size()) { out << indent_spaces(indent) << "Parameters :" << std::endl; ++indent; for(auto decl : *parameter) { out << indent_spaces(indent) << decl->getVariablenTypeName() << " " << decl->getVariablenName() << std::endl; } --indent; } auto body = fndecl->getBody(); for( auto stmt : body->statements ) { stmt->Accept( *this ); } --indent; } void VisitorPrettyPrint::VisitConditional( Conditional* cmp ) { out << indent_spaces(indent) << "Create " << cmp->toString() << std::endl; ++indent; cmp->getCompOperator()->Accept(*this); if( cmp->getThen() ) { cmp->getThen()->Accept( *this ); } if( cmp->getElse() ) { cmp->getElse()->Accept( *this ); } --indent; } void VisitorPrettyPrint::VisitInteger( Integer* expr ) { out << indent_spaces(indent) << "Create " << expr->toString() << std::endl; } void VisitorPrettyPrint::VisitDouble( Double* expr ) { out << indent_spaces(indent) << "Create " << expr->toString() << std::endl; } void VisitorPrettyPrint::VisitString( String* expr ) { out << indent_spaces(indent) << "Create " << expr->toString() << std::endl; } void VisitorPrettyPrint::VisitBoolean( Boolean* expr ) { out << indent_spaces(indent) << "Create " << expr->toString() << std::endl; } void VisitorPrettyPrint::VisitIdentifier( Identifier* expr ) { out << indent_spaces(indent) << "Create " << expr->toString() << std::endl; } void VisitorPrettyPrint::VisitUnaryOperator( UnaryOperator* expr ) { out << indent_spaces(indent) << "Create " << expr->toString() << std::endl; ++indent; expr->getRHS()->Accept(*this); --indent; } void VisitorPrettyPrint::VisitBinaryOp( BinaryOp* expr ) { out << indent_spaces(indent) << "Create " << expr->toString() << std::endl; ++indent; expr->getLHS()->Accept(*this); expr->getRHS()->Accept(*this); --indent; } void VisitorPrettyPrint::VisitCompOperator( CompOperator* expr ) { out << indent_spaces(indent) << "Create " << expr->toString() << std::endl; expr->getLHS()->Accept(*this); expr->getRHS()->Accept(*this); } void VisitorPrettyPrint::VisitBlock( Block* expr ) { out << indent_spaces(indent) << "Create " << expr->toString() << std::endl; ++indent; for(auto stmt : expr->statements) { stmt->Accept( *this ); } --indent; out << indent_spaces(indent) << "End " << expr->toString() << std::endl; } void VisitorPrettyPrint::VisitExpressionStatement( ExpressionStatement* expr ) { out << indent_spaces(indent) << "Create " << expr->toString() << std::endl; ++indent; expr->getExpression()->Accept(*this); --indent; } void VisitorPrettyPrint::VisitAssigment( Assignment* expr ) { out << indent_spaces(indent) << "Create " << expr->toString() << std::endl; ++indent; expr->getExpression()->Accept(*this); --indent; } void VisitorPrettyPrint::VisitMethodCall( MethodCall* expr ) { out << indent_spaces(indent) << "Create " << expr->toString() << std::endl; ++indent; auto args = expr->getArguments(); if(args->size()) { out << indent_spaces(indent) << "Arguments are:\n"; for(auto arg : *args) { arg->Accept(*this); } } --indent; } void VisitorPrettyPrint::VisitVariablenDeclaration( VariableDeclaration* expr ) { out << indent_spaces(indent) << "Create " << expr->toString() << std::endl; if(expr->hasAssignmentExpr()) { ++indent; expr->getAssignment()->Accept(*this); --indent; } } void VisitorPrettyPrint::VisitWhileLoop( WhileLoop* expr ) { out << indent_spaces(indent) << "Create " << expr->toString() << std::endl; ++indent; expr->getCondition()->Accept(*this); out << indent_spaces(indent) << "Create Loop Body" << std::endl; expr->getLoopBlock()->Accept(*this); auto elseBlock = expr->getElseBlock(); if(elseBlock) { out << indent_spaces(indent) << "Create Else Body" << std::endl; elseBlock->Accept(*this); } --indent; } void VisitorPrettyPrint::VisitClassDeclaration( ClassDeclaration* expr ) { out << indent_spaces(indent) << "Create " << expr->toString() << std::endl; ++indent; auto block = expr->getBlock(); if(block) { block->Accept(*this); } --indent; } void VisitorPrettyPrint::VisitArray(Array* expr) { out << indent_spaces(indent) << "Create array " << expr->toString() << std::endl; ++indent; for( auto e : *expr->getExpressions() ) { e->Accept(*this); } --indent; } void VisitorPrettyPrint::VisitArrayAccess(ArrayAccess* expr) { out << indent_spaces(indent) << "Create " << expr->toString() << " to element " << expr->index << std::endl; ++indent; if( expr->other != nullptr ) { expr->other->Accept(*this); } --indent; } void VisitorPrettyPrint::VisitArrayAddElement(ArrayAddElement* expr) { out << indent_spaces(indent) << "Create " << expr->toString() << " of " << expr->getExpression()->toString() << " to array " << expr->ident->getName() << std::endl; ++indent; if( expr->getExpression() ) { expr->getExpression()->Accept(*this); } --indent; } void VisitorPrettyPrint::VisitRange(Range* expr) { out << indent_spaces(indent) << "Create " << expr->toString() << std::endl; ++indent; if( expr->begin != nullptr ) { expr->begin->Accept(*this); } if( expr->end != nullptr ) { expr->end->Accept(*this); } --indent; } } <commit_msg>Fix pretty print for simple return statement.<commit_after>#include "VisitorPrettyPrint.h" #include "AstNode.h" #include "Return.h" #include "FunctionDeclaration.h" #include "ClassDeclaration.h" #include "Conditional.h" #include "UnaryOperator.h" #include "BinaryOperator.h" #include "Assignment.h" #include "MethodCall.h" #include "Declaration.h" #include "WhileLoop.h" #include "Array.h" #include "CompareOperator.h" #include "Range.h" namespace liquid { static inline std::string indent_spaces(size_t indent) { return std::string(indent * 2u, ' '); } void VisitorPrettyPrint::VisitExpression( Expression* expr ) { out << indent_spaces(indent) << "Create " << expr->toString() << std::endl; } void VisitorPrettyPrint::VisitStatement( Statement* stmt ) { out << indent_spaces(indent) << "Create " << stmt->toString() << std::endl; } void VisitorPrettyPrint::VisitReturnStatement( Return* retstmt ) { out << indent_spaces(indent) << "Create " << retstmt->toString() << std::endl; if( retstmt->getRetExpression() != nullptr ) { ++indent; retstmt->getRetExpression()->Accept(*this); --indent; } } void VisitorPrettyPrint::VisitFunctionDeclaration( FunctionDeclaration* fndecl ) { out << indent_spaces(indent) << "Create " << fndecl->toString() << std::endl; ++indent; auto parameter = fndecl->getParameter(); if(parameter->size()) { out << indent_spaces(indent) << "Parameters :" << std::endl; ++indent; for(auto decl : *parameter) { out << indent_spaces(indent) << decl->getVariablenTypeName() << " " << decl->getVariablenName() << std::endl; } --indent; } auto body = fndecl->getBody(); for( auto stmt : body->statements ) { stmt->Accept( *this ); } --indent; } void VisitorPrettyPrint::VisitConditional( Conditional* cmp ) { out << indent_spaces(indent) << "Create " << cmp->toString() << std::endl; ++indent; cmp->getCompOperator()->Accept(*this); if( cmp->getThen() ) { cmp->getThen()->Accept( *this ); } if( cmp->getElse() ) { cmp->getElse()->Accept( *this ); } --indent; } void VisitorPrettyPrint::VisitInteger( Integer* expr ) { out << indent_spaces(indent) << "Create " << expr->toString() << std::endl; } void VisitorPrettyPrint::VisitDouble( Double* expr ) { out << indent_spaces(indent) << "Create " << expr->toString() << std::endl; } void VisitorPrettyPrint::VisitString( String* expr ) { out << indent_spaces(indent) << "Create " << expr->toString() << std::endl; } void VisitorPrettyPrint::VisitBoolean( Boolean* expr ) { out << indent_spaces(indent) << "Create " << expr->toString() << std::endl; } void VisitorPrettyPrint::VisitIdentifier( Identifier* expr ) { out << indent_spaces(indent) << "Create " << expr->toString() << std::endl; } void VisitorPrettyPrint::VisitUnaryOperator( UnaryOperator* expr ) { out << indent_spaces(indent) << "Create " << expr->toString() << std::endl; ++indent; expr->getRHS()->Accept(*this); --indent; } void VisitorPrettyPrint::VisitBinaryOp( BinaryOp* expr ) { out << indent_spaces(indent) << "Create " << expr->toString() << std::endl; ++indent; expr->getLHS()->Accept(*this); expr->getRHS()->Accept(*this); --indent; } void VisitorPrettyPrint::VisitCompOperator( CompOperator* expr ) { out << indent_spaces(indent) << "Create " << expr->toString() << std::endl; expr->getLHS()->Accept(*this); expr->getRHS()->Accept(*this); } void VisitorPrettyPrint::VisitBlock( Block* expr ) { out << indent_spaces(indent) << "Create " << expr->toString() << std::endl; ++indent; for(auto stmt : expr->statements) { stmt->Accept( *this ); } --indent; out << indent_spaces(indent) << "End " << expr->toString() << std::endl; } void VisitorPrettyPrint::VisitExpressionStatement( ExpressionStatement* expr ) { out << indent_spaces(indent) << "Create " << expr->toString() << std::endl; ++indent; expr->getExpression()->Accept(*this); --indent; } void VisitorPrettyPrint::VisitAssigment( Assignment* expr ) { out << indent_spaces(indent) << "Create " << expr->toString() << std::endl; ++indent; expr->getExpression()->Accept(*this); --indent; } void VisitorPrettyPrint::VisitMethodCall( MethodCall* expr ) { out << indent_spaces(indent) << "Create " << expr->toString() << std::endl; ++indent; auto args = expr->getArguments(); if(args->size()) { out << indent_spaces(indent) << "Arguments are:\n"; for(auto arg : *args) { arg->Accept(*this); } } --indent; } void VisitorPrettyPrint::VisitVariablenDeclaration( VariableDeclaration* expr ) { out << indent_spaces(indent) << "Create " << expr->toString() << std::endl; if(expr->hasAssignmentExpr()) { ++indent; expr->getAssignment()->Accept(*this); --indent; } } void VisitorPrettyPrint::VisitWhileLoop( WhileLoop* expr ) { out << indent_spaces(indent) << "Create " << expr->toString() << std::endl; ++indent; expr->getCondition()->Accept(*this); out << indent_spaces(indent) << "Create Loop Body" << std::endl; expr->getLoopBlock()->Accept(*this); auto elseBlock = expr->getElseBlock(); if(elseBlock) { out << indent_spaces(indent) << "Create Else Body" << std::endl; elseBlock->Accept(*this); } --indent; } void VisitorPrettyPrint::VisitClassDeclaration( ClassDeclaration* expr ) { out << indent_spaces(indent) << "Create " << expr->toString() << std::endl; ++indent; auto block = expr->getBlock(); if(block) { block->Accept(*this); } --indent; } void VisitorPrettyPrint::VisitArray(Array* expr) { out << indent_spaces(indent) << "Create array " << expr->toString() << std::endl; ++indent; for( auto e : *expr->getExpressions() ) { e->Accept(*this); } --indent; } void VisitorPrettyPrint::VisitArrayAccess(ArrayAccess* expr) { out << indent_spaces(indent) << "Create " << expr->toString() << " to element " << expr->index << std::endl; ++indent; if( expr->other != nullptr ) { expr->other->Accept(*this); } --indent; } void VisitorPrettyPrint::VisitArrayAddElement(ArrayAddElement* expr) { out << indent_spaces(indent) << "Create " << expr->toString() << " of " << expr->getExpression()->toString() << " to array " << expr->ident->getName() << std::endl; ++indent; if( expr->getExpression() ) { expr->getExpression()->Accept(*this); } --indent; } void VisitorPrettyPrint::VisitRange(Range* expr) { out << indent_spaces(indent) << "Create " << expr->toString() << std::endl; ++indent; if( expr->begin != nullptr ) { expr->begin->Accept(*this); } if( expr->end != nullptr ) { expr->end->Accept(*this); } --indent; } } <|endoftext|>
<commit_before>#ifndef _SDD_DD_ALPHA_HH_ #define _SDD_DD_ALPHA_HH_ #include "sdd/dd/definition_fwd.hh" #include "sdd/util/boost_flat_map_no_warnings.hh" #include "sdd/util/hash.hh" namespace sdd { /*------------------------------------------------------------------------------------------------*/ /// @brief Represent an arc of an alpha. template <typename C, typename Valuation> class arc final { private: /// @brief This arc's valuation, either an SDD or a set of values. const Valuation valuation_; /// @brief This arcs's SDD successor. const SDD<C> successor_; public: /// @internal /// @brief Constructor. arc(Valuation&& val, SDD<C>&& succ) : valuation_(std::move(val)) , successor_(std::move(succ)) {} /// @brief Get the valuation of this arc. const Valuation& valuation() const noexcept { return valuation_; } /// @brief Get the successor of this arc. SDD<C> successor() const noexcept { return successor_; } }; /// @brief Equality of two arc. /// @related arc template <typename C, typename Valuation> inline bool operator==(const arc<C, Valuation>& lhs, const arc<C, Valuation>& rhs) noexcept { return lhs.successor() == rhs.successor() and lhs.valuation() == rhs.valuation(); } /*------------------------------------------------------------------------------------------------*/ namespace dd { /// @internal /// @brief Helper class to build an alpha. /// /// It serves two goals. First, it ensures that all alphas use the same order to store arcs. /// Second, it helps to place the alpha directly behind the owner node to avoid an indirection. template <typename C, typename Valuation> class alpha_builder { // Can't copy an alpha_builder alpha_builder(const alpha_builder&) = delete; alpha_builder& operator=(const alpha_builder&) = delete; private: /// @brief Temporay container of arcs. /// /// Arcs are inverted because we are guaranted that the comparison of SDD is O(1), which is /// not the case for Valuation (though, it's likely so). Arcs are put in the correct /// direction in consolidate(). boost::container::flat_map<SDD<C>, Valuation> map_; public: /// @brief Default constructor. alpha_builder() = default; /// @brief Default move constructor. alpha_builder(alpha_builder&&) = default; /// @brief Request for allocation of additional memory. void reserve(std::size_t size) { map_.reserve(size); } /// @brief Tell if the builder doesn't contain any arc. bool empty() const noexcept { return map_.empty(); } /// @brief Get the number of arcs. std::size_t size() const noexcept { return map_.size(); } /// @brief Add an arc to the alpha. /// @param val shall be a non-empty element of a partition, no verification will be made. /// @param succ void add(Valuation&& val, const SDD<C>& succ) { map_.emplace(succ, std::move(val)); } /// @brief Add an arc to the alpha. /// @param val shall be a non-empty element of a partition, no verification will be made. /// @param succ void add(const Valuation& val, const SDD<C>& succ) { map_.emplace(succ, val); } /// @brief Compute the size needed to store all the arcs contained by this builder. std::size_t size_to_allocate() const noexcept { return map_.size() * sizeof(arc<C, Valuation>); } /// @brief Move arcs of this builder to a given memory location. /// @param addr shall point to an allocated memory location of the size returned by /// size_to_allocate(). /// /// Once performed, all subsequent calls to this instance are invalid. void consolidate(char* addr) noexcept { arc<C, Valuation>* base = reinterpret_cast<arc<C, Valuation>*>(addr); std::size_t i = 0; for (auto& a : map_) { new (base + i++) arc<C, Valuation>(std::move(a.second), std::move(a.first)); } } }; /*------------------------------------------------------------------------------------------------*/ }} // namespace sdd::dd namespace std { /*------------------------------------------------------------------------------------------------*/ /// @brief Hash specialization for sdd::arc template <typename C, typename Valuation> struct hash<sdd::arc<C, Valuation>> { std::size_t operator()(const sdd::arc<C, Valuation>& arc) const { std::size_t seed = sdd::util::hash(arc.valuation()); sdd::util::hash_combine(seed, arc.successor()); return seed; } }; /*------------------------------------------------------------------------------------------------*/ } // namespace std #endif // _SDD_DD_ALPHA_HH_ <commit_msg>Export the type of the valuation in an arc.<commit_after>#ifndef _SDD_DD_ALPHA_HH_ #define _SDD_DD_ALPHA_HH_ #include "sdd/dd/definition_fwd.hh" #include "sdd/util/boost_flat_map_no_warnings.hh" #include "sdd/util/hash.hh" namespace sdd { /*------------------------------------------------------------------------------------------------*/ /// @brief Represent an arc of an alpha. template <typename C, typename Valuation> class arc final { private: /// @brief This arc's valuation, either an SDD or a set of values. const Valuation valuation_; /// @brief This arcs's SDD successor. const SDD<C> successor_; public: /// @brief The valuation type. using valuation_type = Valuation; /// @internal /// @brief Constructor. arc(Valuation&& val, SDD<C>&& succ) : valuation_(std::move(val)) , successor_(std::move(succ)) {} /// @brief Get the valuation of this arc. const Valuation& valuation() const noexcept { return valuation_; } /// @brief Get the successor of this arc. SDD<C> successor() const noexcept { return successor_; } }; /// @brief Equality of two arc. /// @related arc template <typename C, typename Valuation> inline bool operator==(const arc<C, Valuation>& lhs, const arc<C, Valuation>& rhs) noexcept { return lhs.successor() == rhs.successor() and lhs.valuation() == rhs.valuation(); } /*------------------------------------------------------------------------------------------------*/ namespace dd { /// @internal /// @brief Helper class to build an alpha. /// /// It serves two goals. First, it ensures that all alphas use the same order to store arcs. /// Second, it helps to place the alpha directly behind the owner node to avoid an indirection. template <typename C, typename Valuation> class alpha_builder { // Can't copy an alpha_builder alpha_builder(const alpha_builder&) = delete; alpha_builder& operator=(const alpha_builder&) = delete; private: /// @brief Temporay container of arcs. /// /// Arcs are inverted because we are guaranted that the comparison of SDD is O(1), which is /// not the case for Valuation (though, it's likely so). Arcs are put in the correct /// direction in consolidate(). boost::container::flat_map<SDD<C>, Valuation> map_; public: /// @brief Default constructor. alpha_builder() = default; /// @brief Default move constructor. alpha_builder(alpha_builder&&) = default; /// @brief Request for allocation of additional memory. void reserve(std::size_t size) { map_.reserve(size); } /// @brief Tell if the builder doesn't contain any arc. bool empty() const noexcept { return map_.empty(); } /// @brief Get the number of arcs. std::size_t size() const noexcept { return map_.size(); } /// @brief Add an arc to the alpha. /// @param val shall be a non-empty element of a partition, no verification will be made. /// @param succ void add(Valuation&& val, const SDD<C>& succ) { map_.emplace(succ, std::move(val)); } /// @brief Add an arc to the alpha. /// @param val shall be a non-empty element of a partition, no verification will be made. /// @param succ void add(const Valuation& val, const SDD<C>& succ) { map_.emplace(succ, val); } /// @brief Compute the size needed to store all the arcs contained by this builder. std::size_t size_to_allocate() const noexcept { return map_.size() * sizeof(arc<C, Valuation>); } /// @brief Move arcs of this builder to a given memory location. /// @param addr shall point to an allocated memory location of the size returned by /// size_to_allocate(). /// /// Once performed, all subsequent calls to this instance are invalid. void consolidate(char* addr) noexcept { arc<C, Valuation>* base = reinterpret_cast<arc<C, Valuation>*>(addr); std::size_t i = 0; for (auto& a : map_) { new (base + i++) arc<C, Valuation>(std::move(a.second), std::move(a.first)); } } }; /*------------------------------------------------------------------------------------------------*/ }} // namespace sdd::dd namespace std { /*------------------------------------------------------------------------------------------------*/ /// @brief Hash specialization for sdd::arc template <typename C, typename Valuation> struct hash<sdd::arc<C, Valuation>> { std::size_t operator()(const sdd::arc<C, Valuation>& arc) const { std::size_t seed = sdd::util::hash(arc.valuation()); sdd::util::hash_combine(seed, arc.successor()); return seed; } }; /*------------------------------------------------------------------------------------------------*/ } // namespace std #endif // _SDD_DD_ALPHA_HH_ <|endoftext|>
<commit_before>/********** tell emacs we use -*- c++ -*- style comments ******************* $Revision: 1.3 $ $Author: trey $ $Date: 2006-02-15 16:24:28 $ @file FRTDP.cc @brief No brief Copyright (c) 2006, Trey Smith. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * The software may not be sold or incorporated into a commercial product without specific prior written permission. * 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 <stdlib.h> #include <unistd.h> #include <stdio.h> #include <assert.h> #include <iostream> #include <fstream> #include <queue> #include "zmdpCommonDefs.h" #include "zmdpCommonTime.h" #include "MatrixUtils.h" #include "Pomdp.h" #include "FRTDP.h" using namespace std; using namespace sla; using namespace MatrixUtils; namespace zmdp { FRTDP::FRTDP(AbstractBound* _initUpperBound) : RTDPCore(_initUpperBound) {} int FRTDP::getMaxPrioOutcome(MDPNode& cn, int a, double* maxPrioP, double* secondBestPrioP) const { double maxPrio = -99e+20; double secondBestPrio = -99e+20; int maxPrioOutcome = -1; double prio; MDPQEntry& Qa = cn.Q[a]; FOR (o, Qa.getNumOutcomes()) { MDPEdge* e = Qa.outcomes[o]; if (NULL != e) { prio = log(e->obsProb) + e->nextState->prio; if (prio > maxPrio) { secondBestPrio = maxPrio; maxPrio = prio; maxPrioOutcome = o; } } } if (NULL != maxPrioP) *maxPrioP = maxPrio; if (NULL != secondBestPrioP) *secondBestPrioP = secondBestPrio; return maxPrioOutcome; } void FRTDP::updateInternal(MDPNode& cn) { double lbVal, ubVal; double maxLBVal = -99e+20; double maxUBVal = -99e+20; FOR (a, cn.getNumActions()) { MDPQEntry& Qa = cn.Q[a]; lbVal = 0; ubVal = 0; FOR (o, Qa.getNumOutcomes()) { MDPEdge* e = Qa.outcomes[o]; if (NULL != e) { MDPNode& sn = *e->nextState; double oprob = e->obsProb; lbVal += oprob * sn.lbVal; ubVal += oprob * sn.ubVal; } } Qa.lbVal = lbVal = Qa.immediateReward + problem->getDiscount() * lbVal; Qa.ubVal = ubVal = Qa.immediateReward + problem->getDiscount() * ubVal; maxLBVal = std::max(maxLBVal, lbVal); maxUBVal = std::max(maxUBVal, ubVal); } cn.lbVal = maxLBVal; cn.ubVal = maxUBVal; //cn.ubVal = std::min(cn.ubVal, maxUBVal); (might be better if UB not uniformly improvable) int maxUBAction = getMaxUBAction(cn); double maxPrio; getMaxPrioOutcome(cn, maxUBAction, &maxPrio); cn.prio = maxPrio; numBackups++; } void FRTDP::trialRecurse(MDPNode& cn, double occ, double altPrio, int depth) { // cached Q values must be up to date for subsequent calls update(cn); int maxUBAction = getMaxUBAction(cn); double maxPrio, secondBestPrio; int maxPrioOutcome = getMaxPrioOutcome(cn, maxUBAction, &maxPrio, &secondBestPrio); // check for termination if (occ+maxPrio < std::max(altPrio - 1e-10, -1000.0)) { #if USE_DEBUG_PRINT printf(" trialRecurse: depth=%d occ=%g maxPrio=%g altPrio=%g occ*maxPrio=%g (terminating)\n", depth, occ, maxPrio, altPrio, maxPrio*occ); printf(" trialRecurse: s=%s\n", sparseRep(cn.s).c_str()); #endif return; } #if USE_DEBUG_PRINT printf(" trialRecurse: depth=%d a=%d o=%d ubVal=%g occ=%g altPrio=%g maxPrio=%g\n", depth, maxUBAction, maxPrioOutcome, cn.ubVal, occ, altPrio, maxPrio); printf(" trialRecurse: s=%s\n", sparseRep(cn.s).c_str()); #endif // recurse to successor double obsProb = cn.Q[maxUBAction].outcomes[maxPrioOutcome]->obsProb; double nextOcc = occ + log(obsProb); double nextAltPrio = std::max(altPrio, occ + secondBestPrio); trialRecurse(cn.getNextState(maxUBAction, maxPrioOutcome), nextOcc, nextAltPrio, depth+1); update(cn); } bool FRTDP::doTrial(MDPNode& cn, double pTarget) { #if USE_DEBUG_PRINT printf("-*- doTrial: trial %d\n", (numTrials+1)); #endif trialRecurse(cn, /* occ = */ 0, /* altPrio = */ -1000, 0); numTrials++; return (cn.ubVal - cn.lbVal < pTarget); } }; // namespace zmdp /*************************************************************************** * REVISION HISTORY: * $Log: not supported by cvs2svn $ * Revision 1.2 2006/02/14 19:34:34 trey * now use targetPrecision properly * * Revision 1.1 2006/02/13 21:46:46 trey * initial check-in * * ***************************************************************************/ <commit_msg>made updates robust to a non-uniformly-improvable lower bound<commit_after>/********** tell emacs we use -*- c++ -*- style comments ******************* $Revision: 1.4 $ $Author: trey $ $Date: 2006-02-17 21:09:50 $ @file FRTDP.cc @brief No brief Copyright (c) 2006, Trey Smith. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * The software may not be sold or incorporated into a commercial product without specific prior written permission. * 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 <stdlib.h> #include <unistd.h> #include <stdio.h> #include <assert.h> #include <iostream> #include <fstream> #include <queue> #include "zmdpCommonDefs.h" #include "zmdpCommonTime.h" #include "MatrixUtils.h" #include "Pomdp.h" #include "FRTDP.h" using namespace std; using namespace sla; using namespace MatrixUtils; namespace zmdp { FRTDP::FRTDP(AbstractBound* _initUpperBound) : RTDPCore(_initUpperBound) {} int FRTDP::getMaxPrioOutcome(MDPNode& cn, int a, double* maxPrioP, double* secondBestPrioP) const { double maxPrio = -99e+20; double secondBestPrio = -99e+20; int maxPrioOutcome = -1; double prio; MDPQEntry& Qa = cn.Q[a]; FOR (o, Qa.getNumOutcomes()) { MDPEdge* e = Qa.outcomes[o]; if (NULL != e) { prio = log(e->obsProb) + e->nextState->prio; if (prio > maxPrio) { secondBestPrio = maxPrio; maxPrio = prio; maxPrioOutcome = o; } } } if (NULL != maxPrioP) *maxPrioP = maxPrio; if (NULL != secondBestPrioP) *secondBestPrioP = secondBestPrio; return maxPrioOutcome; } void FRTDP::updateInternal(MDPNode& cn) { double lbVal, ubVal; double maxLBVal = -99e+20; double maxUBVal = -99e+20; FOR (a, cn.getNumActions()) { MDPQEntry& Qa = cn.Q[a]; lbVal = 0; ubVal = 0; FOR (o, Qa.getNumOutcomes()) { MDPEdge* e = Qa.outcomes[o]; if (NULL != e) { MDPNode& sn = *e->nextState; double oprob = e->obsProb; lbVal += oprob * sn.lbVal; ubVal += oprob * sn.ubVal; } } Qa.lbVal = lbVal = Qa.immediateReward + problem->getDiscount() * lbVal; Qa.ubVal = ubVal = Qa.immediateReward + problem->getDiscount() * ubVal; maxLBVal = std::max(maxLBVal, lbVal); maxUBVal = std::max(maxUBVal, ubVal); } // min and max calls here only necessary if bounds are not uniformly improvable cn.lbVal = std::max(cn.lbVal, maxLBVal); cn.ubVal = std::min(cn.ubVal, maxUBVal); int maxUBAction = getMaxUBAction(cn); double maxPrio; getMaxPrioOutcome(cn, maxUBAction, &maxPrio); cn.prio = maxPrio; numBackups++; } void FRTDP::trialRecurse(MDPNode& cn, double occ, double altPrio, int depth) { // cached Q values must be up to date for subsequent calls update(cn); int maxUBAction = getMaxUBAction(cn); double maxPrio, secondBestPrio; int maxPrioOutcome = getMaxPrioOutcome(cn, maxUBAction, &maxPrio, &secondBestPrio); // check for termination if (occ+maxPrio < std::max(altPrio - 1e-10, -1000.0)) { #if USE_DEBUG_PRINT printf(" trialRecurse: depth=%d occ=%g maxPrio=%g altPrio=%g occ*maxPrio=%g (terminating)\n", depth, occ, maxPrio, altPrio, maxPrio*occ); printf(" trialRecurse: s=%s\n", sparseRep(cn.s).c_str()); #endif return; } #if USE_DEBUG_PRINT printf(" trialRecurse: depth=%d a=%d o=%d ubVal=%g occ=%g altPrio=%g maxPrio=%g\n", depth, maxUBAction, maxPrioOutcome, cn.ubVal, occ, altPrio, maxPrio); printf(" trialRecurse: s=%s\n", sparseRep(cn.s).c_str()); #endif // recurse to successor double obsProb = cn.Q[maxUBAction].outcomes[maxPrioOutcome]->obsProb; double nextOcc = occ + log(obsProb); double nextAltPrio = std::max(altPrio, occ + secondBestPrio); trialRecurse(cn.getNextState(maxUBAction, maxPrioOutcome), nextOcc, nextAltPrio, depth+1); update(cn); } bool FRTDP::doTrial(MDPNode& cn, double pTarget) { #if USE_DEBUG_PRINT printf("-*- doTrial: trial %d\n", (numTrials+1)); #endif trialRecurse(cn, /* occ = */ 0, /* altPrio = */ -1000, 0); numTrials++; return (cn.ubVal - cn.lbVal < pTarget); } }; // namespace zmdp /*************************************************************************** * REVISION HISTORY: * $Log: not supported by cvs2svn $ * Revision 1.3 2006/02/15 16:24:28 trey * switched to a better termination criterion * * Revision 1.2 2006/02/14 19:34:34 trey * now use targetPrecision properly * * Revision 1.1 2006/02/13 21:46:46 trey * initial check-in * * ***************************************************************************/ <|endoftext|>
<commit_before>#include <uri> #include <regex> #include <iostream> using namespace uri; /////////////////////////////////////////////////////////////////////////////// const URI::Span_t URI::zero_span_; /////////////////////////////////////////////////////////////////////////////// URI::URI(const char* uri) : URI{std::string{uri}} {} /////////////////////////////////////////////////////////////////////////////// URI::URI(const std::string& uri) : uri_str_{uri} , port_{} { parse(uri_str_); port_ = port_str_.begin ? static_cast<uint16_t>(std::stoi(port_str())) : 0; } /////////////////////////////////////////////////////////////////////////////// std::string URI::userinfo() const { return uri_str_.substr(userinfo_.begin, userinfo_.end); } /////////////////////////////////////////////////////////////////////////////// std::string URI::host() const { return uri_str_.substr(host_.begin, host_.end); } /////////////////////////////////////////////////////////////////////////////// std::string URI::port_str() const { return uri_str_.substr(port_str_.begin, port_str_.end); } /////////////////////////////////////////////////////////////////////////////// uint16_t URI::port() const noexcept { return port_; } /////////////////////////////////////////////////////////////////////////////// std::string URI::path() const { return uri_str_.substr(path_.begin, path_.end); } /////////////////////////////////////////////////////////////////////////////// std::string URI::query() const { return uri_str_.substr(query_.begin, query_.end); } /////////////////////////////////////////////////////////////////////////////// std::string URI::fragment() const { return uri_str_.substr(fragment_.begin, fragment_.end); } /////////////////////////////////////////////////////////////////////////////// std::string URI::to_string() const{ return uri_str_; } /////////////////////////////////////////////////////////////////////////////// URI::operator std::string () const { return uri_str_; } /////////////////////////////////////////////////////////////////////////////// void URI::parse(const std::string& uri) { static const std::regex uri_pattern_matcher { "^([\\w]+)?(\\://)?" //< scheme "(([^:@]+)(\\:([^@]+))?@)?" //< username && password "([^/:?#]+)?(\\:(\\d+))?" //< hostname && port "([^?#]+)" //< path "(\\?([^#]*))?" //< query "(#(.*))?$" //< fragment }; std::smatch uri_parts; if (std::regex_match(uri, uri_parts, uri_pattern_matcher)) { path_ = Span_t(uri_parts.position(10), uri_parts.length(10)); userinfo_ = uri_parts.length(3) ? Span_t(uri_parts.position(3), uri_parts.length(3)) : zero_span_; host_ = uri_parts.length(7) ? Span_t(uri_parts.position(7), uri_parts.length(7)) : zero_span_; port_str_ = uri_parts.length(9) ? Span_t(uri_parts.position(9), uri_parts.length(9)) : zero_span_; query_ = uri_parts.length(11) ? Span_t(uri_parts.position(11), uri_parts.length(11)) : zero_span_; fragment_ = uri_parts.length(12) ? Span_t(uri_parts.position(12), uri_parts.length(12)) : zero_span_; } } /////////////////////////////////////////////////////////////////////////////// std::ostream& uri::operator<< (std::ostream& out, const URI& uri) { return out << uri.to_string(); } <commit_msg>Fixed a bug to get the fragment from a uri<commit_after>#include <uri> #include <regex> #include <iostream> using namespace uri; /////////////////////////////////////////////////////////////////////////////// const URI::Span_t URI::zero_span_; /////////////////////////////////////////////////////////////////////////////// URI::URI(const char* uri) : URI{std::string{uri}} {} /////////////////////////////////////////////////////////////////////////////// URI::URI(const std::string& uri) : uri_str_{uri} , port_{} { parse(uri_str_); port_ = port_str_.begin ? static_cast<uint16_t>(std::stoi(port_str())) : 0; } /////////////////////////////////////////////////////////////////////////////// std::string URI::userinfo() const { return uri_str_.substr(userinfo_.begin, userinfo_.end); } /////////////////////////////////////////////////////////////////////////////// std::string URI::host() const { return uri_str_.substr(host_.begin, host_.end); } /////////////////////////////////////////////////////////////////////////////// std::string URI::port_str() const { return uri_str_.substr(port_str_.begin, port_str_.end); } /////////////////////////////////////////////////////////////////////////////// uint16_t URI::port() const noexcept { return port_; } /////////////////////////////////////////////////////////////////////////////// std::string URI::path() const { return uri_str_.substr(path_.begin, path_.end); } /////////////////////////////////////////////////////////////////////////////// std::string URI::query() const { return uri_str_.substr(query_.begin, query_.end); } /////////////////////////////////////////////////////////////////////////////// std::string URI::fragment() const { return uri_str_.substr(fragment_.begin, fragment_.end); } /////////////////////////////////////////////////////////////////////////////// std::string URI::to_string() const{ return uri_str_; } /////////////////////////////////////////////////////////////////////////////// URI::operator std::string () const { return uri_str_; } /////////////////////////////////////////////////////////////////////////////// void URI::parse(const std::string& uri) { static const std::regex uri_pattern_matcher { "^([\\w]+)?(\\://)?" //< scheme "(([^:@]+)(\\:([^@]+))?@)?" //< username && password "([^/:?#]+)?(\\:(\\d+))?" //< hostname && port "([^?#]+)" //< path "(\\?([^#]*))?" //< query "(#(.*))?$" //< fragment }; std::smatch uri_parts; if (std::regex_match(uri, uri_parts, uri_pattern_matcher)) { path_ = Span_t(uri_parts.position(10), uri_parts.length(10)); userinfo_ = uri_parts.length(3) ? Span_t(uri_parts.position(3), uri_parts.length(3)) : zero_span_; host_ = uri_parts.length(7) ? Span_t(uri_parts.position(7), uri_parts.length(7)) : zero_span_; port_str_ = uri_parts.length(9) ? Span_t(uri_parts.position(9), uri_parts.length(9)) : zero_span_; query_ = uri_parts.length(11) ? Span_t(uri_parts.position(11), uri_parts.length(11)) : zero_span_; fragment_ = uri_parts.length(13) ? Span_t(uri_parts.position(13), uri_parts.length(13)) : zero_span_; } } /////////////////////////////////////////////////////////////////////////////// std::ostream& uri::operator<< (std::ostream& out, const URI& uri) { return out << uri.to_string(); } <|endoftext|>
<commit_before>/* json11 * * json11 is a tiny JSON library for C++11, providing JSON parsing and serialization. * * The core object provided by the library is json11::Json. A Json object represents any JSON * value: null, bool, number (int or double), string (std::string), array (std::vector), or * object (std::map). * * Json objects act like values: they can be assigned, copied, moved, compared for equality or * order, etc. There are also helper methods Json::dump, to serialize a Json to a string, and * Json::parse (static) to parse a std::string as a Json object. * * Internally, the various types of Json object are represented by the JsonValue class * hierarchy. * * A note on numbers - JSON specifies the syntax of number formatting but not its semantics, * so some JSON implementations distinguish between integers and floating-point numbers, while * some don't. In json11, we choose the latter. Because some JSON implementations (namely * Javascript itself) treat all numbers as the same type, distinguishing the two leads * to JSON that will be *silently* changed by a round-trip through those implementations. * Dangerous! To avoid that risk, json11 stores all numbers as double internally, but also * provides integer helpers. * * Fortunately, double-precision IEEE754 ('double') can precisely store any integer in the * range +/-2^53, which includes every 'int' on most systems. (Timestamps often use int64 * or long long to avoid the Y2038K problem; a double storing microseconds since some epoch * will be exact for +/- 275 years.) */ /* Copyright (c) 2013 Dropbox, 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. */ #pragma once #include <string> #include <vector> #include <map> #include <memory> #include <initializer_list> namespace json11 { enum JsonParse { STANDARD, COMMENTS }; class JsonValue; class Json final { public: // Types enum Type { NUL, NUMBER, BOOL, STRING, ARRAY, OBJECT }; // Array and object typedefs typedef std::vector<Json> array; typedef std::map<std::string, Json> object; // Constructors for the various types of JSON value. Json() noexcept; // NUL Json(std::nullptr_t) noexcept; // NUL Json(double value); // NUMBER Json(int value); // NUMBER Json(bool value); // BOOL Json(const std::string &value); // STRING Json(std::string &&value); // STRING Json(const char * value); // STRING Json(const array &values); // ARRAY Json(array &&values); // ARRAY Json(const object &values); // OBJECT Json(object &&values); // OBJECT // Implicit constructor: anything with a to_json() function. template <class T, class = decltype(&T::to_json)> Json(const T & t) : Json(t.to_json()) {} // Implicit constructor: map-like objects (std::map, std::unordered_map, etc) template <class M, typename std::enable_if< std::is_constructible<std::string, typename M::key_type>::value && std::is_constructible<Json, typename M::mapped_type>::value, int>::type = 0> Json(const M & m) : Json(object(m.begin(), m.end())) {} // Implicit constructor: vector-like objects (std::list, std::vector, std::set, etc) template <class V, typename std::enable_if< std::is_constructible<Json, typename V::value_type>::value, int>::type = 0> Json(const V & v) : Json(array(v.begin(), v.end())) {} // This prevents Json(some_pointer) from accidentally producing a bool. Use // Json(bool(some_pointer)) if that behavior is desired. Json(void *) = delete; // Accessors Type type() const; bool is_null() const { return type() == NUL; } bool is_number() const { return type() == NUMBER; } bool is_bool() const { return type() == BOOL; } bool is_string() const { return type() == STRING; } bool is_array() const { return type() == ARRAY; } bool is_object() const { return type() == OBJECT; } // Return the enclosed value if this is a number, 0 otherwise. Note that json11 does not // distinguish between integer and non-integer numbers - number_value() and int_value() // can both be applied to a NUMBER-typed object. double number_value() const; int int_value() const; // Return the enclosed value if this is a boolean, false otherwise. bool bool_value() const; // Return the enclosed string if this is a string, "" otherwise. const std::string &string_value() const; // Return the enclosed std::vector if this is an array, or an empty vector otherwise. const array &array_items() const; // Return the enclosed std::map if this is an object, or an empty map otherwise. const object &object_items() const; // Return a reference to arr[i] if this is an array, Json() otherwise. const Json & operator[](size_t i) const; // Return a reference to obj[key] if this is an object, Json() otherwise. const Json & operator[](const std::string &key) const; // Serialize. void dump(std::string &out) const; std::string dump() const { std::string out; dump(out); return out; } // Parse. If parse fails, return Json() and assign an error message to err. static Json parse(const std::string & in, std::string & err, JsonParse strategy = JsonParse::STANDARD); static Json parse(const char * in, std::string & err, JsonParse strategy = JsonParse::STANDARD) { if (in) { return parse(std::string(in), err, strategy); } else { err = "null input"; return nullptr; } } // Parse multiple objects, concatenated or separated by whitespace static std::vector<Json> parse_multi( const std::string & in, std::string::size_type & parser_stop_pos, std::string & err, JsonParse strategy = JsonParse::STANDARD); static inline std::vector<Json> parse_multi( const std::string & in, std::string & err, JsonParse strategy = JsonParse::STANDARD) { std::string::size_type parser_stop_pos; return parse_multi(in, parser_stop_pos, err, strategy); } bool operator== (const Json &rhs) const; bool operator< (const Json &rhs) const; bool operator!= (const Json &rhs) const { return !(*this == rhs); } bool operator<= (const Json &rhs) const { return !(rhs < *this); } bool operator> (const Json &rhs) const { return (rhs < *this); } bool operator>= (const Json &rhs) const { return !(*this < rhs); } /* has_shape(types, err) * * Return true if this is a JSON object and, for each item in types, has a field of * the given type. If not, return false and set err to a descriptive message. */ typedef std::initializer_list<std::pair<std::string, Type>> shape; bool has_shape(const shape & types, std::string & err) const; private: std::shared_ptr<JsonValue> m_ptr; }; // Internal class hierarchy - JsonValue objects are not exposed to users of this API. class JsonValue { protected: friend class Json; friend class JsonInt; friend class JsonDouble; virtual Json::Type type() const = 0; virtual bool equals(const JsonValue * other) const = 0; virtual bool less(const JsonValue * other) const = 0; virtual void dump(std::string &out) const = 0; virtual double number_value() const; virtual int int_value() const; virtual bool bool_value() const; virtual const std::string &string_value() const; virtual const Json::array &array_items() const; virtual const Json &operator[](size_t i) const; virtual const Json::object &object_items() const; virtual const Json &operator[](const std::string &key) const; virtual ~JsonValue() {} }; } // namespace json11 <commit_msg>MSVS 2013 compatibility changes.<commit_after>/* json11 * * json11 is a tiny JSON library for C++11, providing JSON parsing and serialization. * * The core object provided by the library is json11::Json. A Json object represents any JSON * value: null, bool, number (int or double), string (std::string), array (std::vector), or * object (std::map). * * Json objects act like values: they can be assigned, copied, moved, compared for equality or * order, etc. There are also helper methods Json::dump, to serialize a Json to a string, and * Json::parse (static) to parse a std::string as a Json object. * * Internally, the various types of Json object are represented by the JsonValue class * hierarchy. * * A note on numbers - JSON specifies the syntax of number formatting but not its semantics, * so some JSON implementations distinguish between integers and floating-point numbers, while * some don't. In json11, we choose the latter. Because some JSON implementations (namely * Javascript itself) treat all numbers as the same type, distinguishing the two leads * to JSON that will be *silently* changed by a round-trip through those implementations. * Dangerous! To avoid that risk, json11 stores all numbers as double internally, but also * provides integer helpers. * * Fortunately, double-precision IEEE754 ('double') can precisely store any integer in the * range +/-2^53, which includes every 'int' on most systems. (Timestamps often use int64 * or long long to avoid the Y2038K problem; a double storing microseconds since some epoch * will be exact for +/- 275 years.) */ /* Copyright (c) 2013 Dropbox, 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. */ #pragma once #include <string> #include <vector> #include <map> #include <memory> #include <initializer_list> #ifdef _MSC_VER #if _MSC_VER <= 1800 // VS 2013 #ifndef noexcept #define noexcept throw() #endif #ifndef snprintf #define snprintf _snprintf_s #endif #endif #endif namespace json11 { enum JsonParse { STANDARD, COMMENTS }; class JsonValue; class Json final { public: // Types enum Type { NUL, NUMBER, BOOL, STRING, ARRAY, OBJECT }; // Array and object typedefs typedef std::vector<Json> array; typedef std::map<std::string, Json> object; // Constructors for the various types of JSON value. Json() noexcept; // NUL Json(std::nullptr_t) noexcept; // NUL Json(double value); // NUMBER Json(int value); // NUMBER Json(bool value); // BOOL Json(const std::string &value); // STRING Json(std::string &&value); // STRING Json(const char * value); // STRING Json(const array &values); // ARRAY Json(array &&values); // ARRAY Json(const object &values); // OBJECT Json(object &&values); // OBJECT // Implicit constructor: anything with a to_json() function. template <class T, class = decltype(&T::to_json)> Json(const T & t) : Json(t.to_json()) {} // Implicit constructor: map-like objects (std::map, std::unordered_map, etc) template <class M, typename std::enable_if< std::is_constructible<std::string, typename M::key_type>::value && std::is_constructible<Json, typename M::mapped_type>::value, int>::type = 0> Json(const M & m) : Json(object(m.begin(), m.end())) {} // Implicit constructor: vector-like objects (std::list, std::vector, std::set, etc) template <class V, typename std::enable_if< std::is_constructible<Json, typename V::value_type>::value, int>::type = 0> Json(const V & v) : Json(array(v.begin(), v.end())) {} // This prevents Json(some_pointer) from accidentally producing a bool. Use // Json(bool(some_pointer)) if that behavior is desired. Json(void *) = delete; // Accessors Type type() const; bool is_null() const { return type() == NUL; } bool is_number() const { return type() == NUMBER; } bool is_bool() const { return type() == BOOL; } bool is_string() const { return type() == STRING; } bool is_array() const { return type() == ARRAY; } bool is_object() const { return type() == OBJECT; } // Return the enclosed value if this is a number, 0 otherwise. Note that json11 does not // distinguish between integer and non-integer numbers - number_value() and int_value() // can both be applied to a NUMBER-typed object. double number_value() const; int int_value() const; // Return the enclosed value if this is a boolean, false otherwise. bool bool_value() const; // Return the enclosed string if this is a string, "" otherwise. const std::string &string_value() const; // Return the enclosed std::vector if this is an array, or an empty vector otherwise. const array &array_items() const; // Return the enclosed std::map if this is an object, or an empty map otherwise. const object &object_items() const; // Return a reference to arr[i] if this is an array, Json() otherwise. const Json & operator[](size_t i) const; // Return a reference to obj[key] if this is an object, Json() otherwise. const Json & operator[](const std::string &key) const; // Serialize. void dump(std::string &out) const; std::string dump() const { std::string out; dump(out); return out; } // Parse. If parse fails, return Json() and assign an error message to err. static Json parse(const std::string & in, std::string & err, JsonParse strategy = JsonParse::STANDARD); static Json parse(const char * in, std::string & err, JsonParse strategy = JsonParse::STANDARD) { if (in) { return parse(std::string(in), err, strategy); } else { err = "null input"; return nullptr; } } // Parse multiple objects, concatenated or separated by whitespace static std::vector<Json> parse_multi( const std::string & in, std::string::size_type & parser_stop_pos, std::string & err, JsonParse strategy = JsonParse::STANDARD); static inline std::vector<Json> parse_multi( const std::string & in, std::string & err, JsonParse strategy = JsonParse::STANDARD) { std::string::size_type parser_stop_pos; return parse_multi(in, parser_stop_pos, err, strategy); } bool operator== (const Json &rhs) const; bool operator< (const Json &rhs) const; bool operator!= (const Json &rhs) const { return !(*this == rhs); } bool operator<= (const Json &rhs) const { return !(rhs < *this); } bool operator> (const Json &rhs) const { return (rhs < *this); } bool operator>= (const Json &rhs) const { return !(*this < rhs); } /* has_shape(types, err) * * Return true if this is a JSON object and, for each item in types, has a field of * the given type. If not, return false and set err to a descriptive message. */ typedef std::initializer_list<std::pair<std::string, Type>> shape; bool has_shape(const shape & types, std::string & err) const; private: std::shared_ptr<JsonValue> m_ptr; }; // Internal class hierarchy - JsonValue objects are not exposed to users of this API. class JsonValue { protected: friend class Json; friend class JsonInt; friend class JsonDouble; virtual Json::Type type() const = 0; virtual bool equals(const JsonValue * other) const = 0; virtual bool less(const JsonValue * other) const = 0; virtual void dump(std::string &out) const = 0; virtual double number_value() const; virtual int int_value() const; virtual bool bool_value() const; virtual const std::string &string_value() const; virtual const Json::array &array_items() const; virtual const Json &operator[](size_t i) const; virtual const Json::object &object_items() const; virtual const Json &operator[](const std::string &key) const; virtual ~JsonValue() {} }; } // namespace json11 <|endoftext|>
<commit_before>#include <stdio.h> #include <algorithm> #include "GIF.h" #include "uint128.h" #include "Ps2Const.h" #include "Profiler.h" #include "Log.h" using namespace Framework; using namespace std; using namespace boost; #ifdef PROFILE #define PROFILE_GIFZONE "GIF" #endif CGIF::CGIF(CGSHandler*& gs, uint8* ram, uint8* spr) : m_gs(gs), m_ram(ram), m_spr(spr), m_nLoops(0), m_nCmd(0), m_nRegs(0), m_nRegsTemp(0), m_nRegList(0), m_nEOP(false), m_nQTemp(0) { } CGIF::~CGIF() { } void CGIF::Reset() { m_nLoops = 0; m_nCmd = 0; m_nEOP = false; } uint32 CGIF::ProcessPacked(CGSHandler::RegisterWriteList& writeList, uint8* pMemory, uint32 nAddress, uint32 nEnd) { uint32 nRegDesc, nStart; uint64 nTemp; uint128 nPacket; nStart = nAddress; while((m_nLoops != 0) && (nAddress < nEnd)) { while((m_nRegsTemp != 0) && (nAddress < nEnd)) { nRegDesc = (uint32)((m_nRegList >> ((m_nRegs - m_nRegsTemp) * 4)) & 0x0F); nPacket = *(uint128*)&pMemory[nAddress]; nAddress += 0x10; m_nRegsTemp--; switch(nRegDesc) { case 0x00: //PRIM writeList.push_back(CGSHandler::RegisterWrite(GS_REG_PRIM, nPacket.nV0)); break; case 0x01: //RGBA nTemp = (nPacket.nV[0] & 0xFF); nTemp |= (nPacket.nV[1] & 0xFF) << 8; nTemp |= (nPacket.nV[2] & 0xFF) << 16; nTemp |= (nPacket.nV[3] & 0xFF) << 24; nTemp |= ((uint64)m_nQTemp << 32); writeList.push_back(CGSHandler::RegisterWrite(GS_REG_RGBAQ, nTemp)); break; case 0x02: //ST m_nQTemp = nPacket.nV2; writeList.push_back(CGSHandler::RegisterWrite(GS_REG_ST, nPacket.nD0)); break; case 0x03: //UV nTemp = (nPacket.nV[0] & 0x7FFF); nTemp |= (nPacket.nV[1] & 0x7FFF) << 16; writeList.push_back(CGSHandler::RegisterWrite(GS_REG_UV, nTemp)); break; case 0x04: //XYZF2 nTemp = (nPacket.nV[0] & 0xFFFF); nTemp |= (nPacket.nV[1] & 0xFFFF) << 16; nTemp |= (uint64)(nPacket.nV[2] & 0x0FFFFFF0) << 28; nTemp |= (uint64)(nPacket.nV[3] & 0x00000FF0) << 52; if(nPacket.nV[3] & 0x8000) { writeList.push_back(CGSHandler::RegisterWrite(GS_REG_XYZF3, nTemp)); } else { writeList.push_back(CGSHandler::RegisterWrite(GS_REG_XYZF2, nTemp)); } break; case 0x05: //XYZ2 nTemp = (nPacket.nV[0] & 0xFFFF); nTemp |= (nPacket.nV[1] & 0xFFFF) << 16; nTemp |= (uint64)(nPacket.nV[2] & 0xFFFFFFFF) << 32; if(nPacket.nV[3] & 0x8000) { writeList.push_back(CGSHandler::RegisterWrite(GS_REG_XYZ3, nTemp)); } else { writeList.push_back(CGSHandler::RegisterWrite(GS_REG_XYZ2, nTemp)); } break; case 0x06: //TEX0_1 writeList.push_back(CGSHandler::RegisterWrite(GS_REG_TEX0_1, nPacket.nD0)); break; case 0x0E: //A + D if(m_gs != NULL) { writeList.push_back(CGSHandler::RegisterWrite(static_cast<uint8>(nPacket.nD1), nPacket.nD0)); } break; case 0x0F: //NOP break; default: assert(0); break; } } if(m_nRegsTemp == 0) { m_nLoops--; m_nRegsTemp = m_nRegs; } } return nAddress - nStart; } uint32 CGIF::ProcessRegList(CGSHandler::RegisterWriteList& writeList, uint8* pMemory, uint32 nAddress, uint32 nEnd) { uint32 nStart = nAddress; while(m_nLoops != 0) { for(uint32 j = 0; j < m_nRegs; j++) { assert(nAddress < nEnd); uint128 nPacket; uint32 nRegDesc = (uint32)((m_nRegList >> (j * 4)) & 0x0F); nPacket.nV[0] = *(uint32*)&pMemory[nAddress + 0x00]; nPacket.nV[1] = *(uint32*)&pMemory[nAddress + 0x04]; nAddress += 0x08; if(nRegDesc == 0x0F) continue; writeList.push_back(CGSHandler::RegisterWrite(static_cast<uint8>(nRegDesc), nPacket.nD0)); } m_nLoops--; } //Align on qword boundary if(nAddress & 0x07) { nAddress += 8; } return nAddress - nStart; } uint32 CGIF::ProcessImage(uint8* pMemory, uint32 nAddress, uint32 nEnd) { uint16 nTotalLoops; nTotalLoops = (uint16)((nEnd - nAddress) / 0x10); nTotalLoops = min(nTotalLoops, m_nLoops); if(m_gs != NULL) { m_gs->FeedImageData(pMemory + nAddress, nTotalLoops * 0x10); } m_nLoops -= nTotalLoops; return (nTotalLoops * 0x10); } uint32 CGIF::ProcessPacket(uint8* pMemory, uint32 nAddress, uint32 nEnd) { mutex::scoped_lock pathLock(m_pathMutex); static CGSHandler::RegisterWriteList writeList; #ifdef PROFILE CProfiler::GetInstance().BeginZone(PROFILE_GIFZONE); #endif #ifdef _DEBUG CLog::GetInstance().Print("gif", "Processed GIF packet at 0x%0.8X.\r\n", nAddress); #endif writeList.clear(); uint32 nStart = nAddress; while(nAddress < nEnd) { if(m_nLoops == 0) { if(m_nEOP) { m_nEOP = false; break; } //We need to update the registers uint128 nPacket = *reinterpret_cast<uint128*>(&pMemory[nAddress]); nAddress += 0x10; m_nLoops = (uint16)((nPacket.nV0 >> 0) & 0x7FFF); m_nCmd = ( uint8)((nPacket.nV1 >> 26) & 0x0003); m_nRegs = ( uint8)((nPacket.nV1 >> 28) & 0x000F); m_nRegList = nPacket.nD1; m_nEOP = (nPacket.nV0 & 0x8000) != 0; if(m_nCmd != 1) { if(nPacket.nV1 & 0x4000) { writeList.push_back(CGSHandler::RegisterWrite(GS_REG_PRIM, (uint16)(nPacket.nV1 >> 15) & 0x3FF)); } } if(m_nRegs == 0) m_nRegs = 0x10; m_nRegsTemp = m_nRegs; continue; } switch(m_nCmd) { case 0x00: nAddress += ProcessPacked(writeList, pMemory, nAddress, nEnd); break; case 0x01: nAddress += ProcessRegList(writeList, pMemory, nAddress, nEnd); break; case 0x02: case 0x03: nAddress += ProcessImage(pMemory, nAddress, nEnd); break; } } if(m_nLoops == 0) { if(m_nEOP) { m_nEOP = false; } } #ifdef PROFILE CProfiler::GetInstance().EndZone(); #endif if(m_gs != NULL && writeList.size() != 0) { CGSHandler::RegisterWrite* writeListBuffer = new CGSHandler::RegisterWrite[writeList.size()]; memcpy(writeListBuffer, &writeList[0], sizeof(CGSHandler::RegisterWrite) * writeList.size()); m_gs->WriteRegisterMassively(writeListBuffer, static_cast<unsigned int>(writeList.size())); } return nAddress - nStart; } uint32 CGIF::ReceiveDMA(uint32 nAddress, uint32 nQWC, uint32 unused, bool nTagIncluded) { uint8* pMemory; assert(nTagIncluded == false); if(nAddress & 0x80000000) { pMemory = m_spr; nAddress &= PS2::SPRSIZE - 1; } else { pMemory = m_ram; } uint32 nSize = nQWC * 0x10; uint32 nEnd = nAddress + nSize; while(nAddress < nEnd) { nAddress += ProcessPacket(pMemory, nAddress, nEnd); } return nQWC; } <commit_msg>Some changes for FFX.<commit_after>#include <stdio.h> #include <algorithm> #include "GIF.h" #include "uint128.h" #include "Ps2Const.h" #include "Profiler.h" #include "Log.h" using namespace Framework; using namespace std; using namespace boost; #ifdef PROFILE #define PROFILE_GIFZONE "GIF" #endif CGIF::CGIF(CGSHandler*& gs, uint8* ram, uint8* spr) : m_gs(gs), m_ram(ram), m_spr(spr), m_nLoops(0), m_nCmd(0), m_nRegs(0), m_nRegsTemp(0), m_nRegList(0), m_nEOP(false), m_nQTemp(0) { } CGIF::~CGIF() { } void CGIF::Reset() { m_nLoops = 0; m_nCmd = 0; m_nEOP = false; } uint32 CGIF::ProcessPacked(CGSHandler::RegisterWriteList& writeList, uint8* pMemory, uint32 nAddress, uint32 nEnd) { uint32 nRegDesc, nStart; uint64 nTemp; uint128 nPacket; nStart = nAddress; while((m_nLoops != 0) && (nAddress < nEnd)) { while((m_nRegsTemp != 0) && (nAddress < nEnd)) { nRegDesc = (uint32)((m_nRegList >> ((m_nRegs - m_nRegsTemp) * 4)) & 0x0F); nPacket = *(uint128*)&pMemory[nAddress]; nAddress += 0x10; m_nRegsTemp--; switch(nRegDesc) { case 0x00: //PRIM writeList.push_back(CGSHandler::RegisterWrite(GS_REG_PRIM, nPacket.nV0)); break; case 0x01: //RGBA nTemp = (nPacket.nV[0] & 0xFF); nTemp |= (nPacket.nV[1] & 0xFF) << 8; nTemp |= (nPacket.nV[2] & 0xFF) << 16; nTemp |= (nPacket.nV[3] & 0xFF) << 24; nTemp |= ((uint64)m_nQTemp << 32); writeList.push_back(CGSHandler::RegisterWrite(GS_REG_RGBAQ, nTemp)); break; case 0x02: //ST m_nQTemp = nPacket.nV2; writeList.push_back(CGSHandler::RegisterWrite(GS_REG_ST, nPacket.nD0)); break; case 0x03: //UV nTemp = (nPacket.nV[0] & 0x7FFF); nTemp |= (nPacket.nV[1] & 0x7FFF) << 16; writeList.push_back(CGSHandler::RegisterWrite(GS_REG_UV, nTemp)); break; case 0x04: //XYZF2 nTemp = (nPacket.nV[0] & 0xFFFF); nTemp |= (nPacket.nV[1] & 0xFFFF) << 16; nTemp |= (uint64)(nPacket.nV[2] & 0x0FFFFFF0) << 28; nTemp |= (uint64)(nPacket.nV[3] & 0x00000FF0) << 52; if(nPacket.nV[3] & 0x8000) { writeList.push_back(CGSHandler::RegisterWrite(GS_REG_XYZF3, nTemp)); } else { writeList.push_back(CGSHandler::RegisterWrite(GS_REG_XYZF2, nTemp)); } break; case 0x05: //XYZ2 nTemp = (nPacket.nV[0] & 0xFFFF); nTemp |= (nPacket.nV[1] & 0xFFFF) << 16; nTemp |= (uint64)(nPacket.nV[2] & 0xFFFFFFFF) << 32; if(nPacket.nV[3] & 0x8000) { writeList.push_back(CGSHandler::RegisterWrite(GS_REG_XYZ3, nTemp)); } else { writeList.push_back(CGSHandler::RegisterWrite(GS_REG_XYZ2, nTemp)); } break; case 0x06: //TEX0_1 writeList.push_back(CGSHandler::RegisterWrite(GS_REG_TEX0_1, nPacket.nD0)); break; case 0x08: //CLAMP_1 writeList.push_back(CGSHandler::RegisterWrite(GS_REG_CLAMP_1, nPacket.nD0)); break; case 0x0E: //A + D if(m_gs != NULL) { writeList.push_back(CGSHandler::RegisterWrite(static_cast<uint8>(nPacket.nD1), nPacket.nD0)); } break; case 0x0F: //NOP break; default: assert(0); break; } } if(m_nRegsTemp == 0) { m_nLoops--; m_nRegsTemp = m_nRegs; } } return nAddress - nStart; } uint32 CGIF::ProcessRegList(CGSHandler::RegisterWriteList& writeList, uint8* pMemory, uint32 nAddress, uint32 nEnd) { uint32 nStart = nAddress; while(m_nLoops != 0) { for(uint32 j = 0; j < m_nRegs; j++) { assert(nAddress < nEnd); uint128 nPacket; uint32 nRegDesc = (uint32)((m_nRegList >> (j * 4)) & 0x0F); nPacket.nV[0] = *(uint32*)&pMemory[nAddress + 0x00]; nPacket.nV[1] = *(uint32*)&pMemory[nAddress + 0x04]; nAddress += 0x08; if(nRegDesc == 0x0F) continue; writeList.push_back(CGSHandler::RegisterWrite(static_cast<uint8>(nRegDesc), nPacket.nD0)); } m_nLoops--; } //Align on qword boundary if(nAddress & 0x07) { nAddress += 8; } return nAddress - nStart; } uint32 CGIF::ProcessImage(uint8* pMemory, uint32 nAddress, uint32 nEnd) { uint16 nTotalLoops; nTotalLoops = (uint16)((nEnd - nAddress) / 0x10); nTotalLoops = min(nTotalLoops, m_nLoops); if(m_gs != NULL) { m_gs->FeedImageData(pMemory + nAddress, nTotalLoops * 0x10); } m_nLoops -= nTotalLoops; return (nTotalLoops * 0x10); } uint32 CGIF::ProcessPacket(uint8* pMemory, uint32 nAddress, uint32 nEnd) { mutex::scoped_lock pathLock(m_pathMutex); static CGSHandler::RegisterWriteList writeList; #ifdef PROFILE CProfiler::GetInstance().BeginZone(PROFILE_GIFZONE); #endif #ifdef _DEBUG CLog::GetInstance().Print("gif", "Processed GIF packet at 0x%0.8X.\r\n", nAddress); #endif writeList.clear(); uint32 nStart = nAddress; while(nAddress < nEnd) { if(m_nLoops == 0) { if(m_nEOP) { m_nEOP = false; break; } //We need to update the registers uint128 nPacket = *reinterpret_cast<uint128*>(&pMemory[nAddress]); nAddress += 0x10; m_nLoops = (uint16)((nPacket.nV0 >> 0) & 0x7FFF); m_nCmd = ( uint8)((nPacket.nV1 >> 26) & 0x0003); m_nRegs = ( uint8)((nPacket.nV1 >> 28) & 0x000F); m_nRegList = nPacket.nD1; m_nEOP = (nPacket.nV0 & 0x8000) != 0; if(m_nCmd != 1) { if(nPacket.nV1 & 0x4000) { writeList.push_back(CGSHandler::RegisterWrite(GS_REG_PRIM, (uint16)(nPacket.nV1 >> 15) & 0x3FF)); } } if(m_nRegs == 0) m_nRegs = 0x10; m_nRegsTemp = m_nRegs; continue; } switch(m_nCmd) { case 0x00: nAddress += ProcessPacked(writeList, pMemory, nAddress, nEnd); break; case 0x01: nAddress += ProcessRegList(writeList, pMemory, nAddress, nEnd); break; case 0x02: case 0x03: nAddress += ProcessImage(pMemory, nAddress, nEnd); break; } } if(m_nLoops == 0) { if(m_nEOP) { m_nEOP = false; } } #ifdef PROFILE CProfiler::GetInstance().EndZone(); #endif if(m_gs != NULL && writeList.size() != 0) { CGSHandler::RegisterWrite* writeListBuffer = new CGSHandler::RegisterWrite[writeList.size()]; memcpy(writeListBuffer, &writeList[0], sizeof(CGSHandler::RegisterWrite) * writeList.size()); m_gs->WriteRegisterMassively(writeListBuffer, static_cast<unsigned int>(writeList.size())); } return nAddress - nStart; } uint32 CGIF::ReceiveDMA(uint32 nAddress, uint32 nQWC, uint32 unused, bool nTagIncluded) { uint8* pMemory; assert(nTagIncluded == false); if(nAddress & 0x80000000) { pMemory = m_spr; nAddress &= PS2::SPRSIZE - 1; } else { pMemory = m_ram; } uint32 nSize = nQWC * 0x10; uint32 nEnd = nAddress + nSize; while(nAddress < nEnd) { nAddress += ProcessPacket(pMemory, nAddress, nEnd); } return nQWC; } <|endoftext|>
<commit_before>/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2019 * * * * 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 <modules/autonavigation/autonavigationhandler.h> #include <modules/autonavigation/helperfunctions.h> #include <modules/autonavigation/instruction.h> #include <modules/autonavigation/pathspecification.h> #include <openspace/engine/globals.h> #include <openspace/engine/windowdelegate.h> #include <openspace/interaction/navigationhandler.h> #include <openspace/scene/scenegraphnode.h> #include <openspace/util/camera.h> #include <openspace/query/query.h> #include <ghoul/logging/logmanager.h> #include <glm/gtx/vector_angle.hpp> #include <glm/gtx/quaternion.hpp> #include <algorithm> namespace { constexpr const char* _loggerCat = "AutoNavigationHandler"; } // namespace namespace openspace::autonavigation { // Temporary function to convert a string to one of the bools above. // TODO: move to a better place / rewrite CurveType stringToCurveType(std::string str) { if (str.empty()) return CurveType::None; std::transform(str.begin(), str.end(), str.begin(), ::tolower); if (str == "bezier3") { return CurveType::Bezier3; } else if (str == "linear") { return CurveType::Linear; } else { LERROR(fmt::format("'{}' is not a valid curve type! Choosing default.", str)); return CurveType::None; } } AutoNavigationHandler::AutoNavigationHandler() : properties::PropertyOwner({ "AutoNavigationHandler" }) { // Add the properties // TODO } AutoNavigationHandler::~AutoNavigationHandler() {} // NOLINT Camera* AutoNavigationHandler::camera() const { return global::navigationHandler.camera(); } const double AutoNavigationHandler::pathDuration() const { double sum = 0.0; for (const PathSegment& ps : _pathSegments) { sum += ps.duration(); } return sum; } const bool AutoNavigationHandler::hasFinished() const { return _currentTime > pathDuration(); } CameraState AutoNavigationHandler::currentCameraState() { CameraState cs; cs.position = camera()->positionVec3(); cs.rotation = camera()->rotationQuaternion(); cs.referenceNode = global::navigationHandler.anchorNode()->identifier(); return cs; } void AutoNavigationHandler::updateCamera(double deltaTime) { ghoul_assert(camera() != nullptr, "Camera must not be nullptr"); if (!_isPlaying || _pathSegments.empty()) return; _currentTime += deltaTime; PathSegment& cps = _pathSegments[_currentSegmentIndex]; // Have we walked past the current segment? if (_currentTime > cps.endTime()) { _currentSegmentIndex++; _distanceAlongCurrentSegment = 0.0; // WStepped past the last segment if (_currentSegmentIndex > _pathSegments.size() - 1) { LINFO("Reached end of path."); _isPlaying = false; return; } cps = _pathSegments[_currentSegmentIndex]; if (_stopAtTargets) { pausePath(); return; } } double prevDistance = _distanceAlongCurrentSegment; double displacement = deltaTime * cps.speedAtTime(_currentTime - cps.startTime()); _distanceAlongCurrentSegment += displacement; double relativeDisplacement = _distanceAlongCurrentSegment / cps.pathLength(); relativeDisplacement = std::max(0.0, std::min(relativeDisplacement, 1.0)); // When halfway along a curve, set anchor node in orbitalNavigator, to render // visible nodes and add possibility to navigate when we reach the end. if (abs(relativeDisplacement - 0.5) < 0.001) { std::string newAnchor = cps.end().referenceNode; global::navigationHandler.orbitalNavigator().setAnchorNode(newAnchor); } glm::dvec3 cameraPosition = cps.getPositionAt(relativeDisplacement); glm::dquat cameraRotation = cps.getRotationAt(relativeDisplacement); camera()->setPositionVec3(cameraPosition); camera()->setRotation(cameraRotation); } void AutoNavigationHandler::createPath(PathSpecification& spec) { clearPath(); _pathCurveType = stringToCurveType(spec.curveType()); bool success = true; for (int i = 0; i < spec.instructions()->size(); i++) { const Instruction& ins = spec.instructions()->at(i); success = handleInstruction(ins, i); if (!success) break; } // OBS! Would it be better to save the spec in the handler class? _stopAtTargets = spec.stopAtTargets(); // Check if we have a specified start state. If so, update the first segment if (spec.hasStartState() && _pathSegments.size() > 0) { CameraState startState = cameraStateFromNavigationState(spec.startState()); _pathSegments[0].setStart(startState); } if (success) { LINFO("Succefully generated camera path."); startPath(); } else LERROR("Could not create path."); } void AutoNavigationHandler::clearPath() { LINFO("Clearing path..."); _pathSegments.clear(); _currentTime = 0.0; _currentSegmentIndex = 0; _distanceAlongCurrentSegment = 0.0; } void AutoNavigationHandler::startPath() { if (_pathSegments.empty()) { LERROR("Cannot start an empty path."); return; } LINFO("Starting path..."); _currentTime = 0.0; _isPlaying = true; } void AutoNavigationHandler::pausePath() { if (!_isPlaying) { LERROR("Cannot pause a path that isn't playing"); return; } LINFO(fmt::format("Paused path at target {} / {}", _currentSegmentIndex, _pathSegments.size())); _isPlaying = false; } void AutoNavigationHandler::continuePath() { if (_pathSegments.empty() || hasFinished()) { LERROR("No path to resume (path is empty or has finished)."); return; } if (_isPlaying) { LERROR("Cannot resume a path that is already playing"); return; } LINFO("Continuing path..."); // Recompute start camera state for the upcoming path segment, to avoid clipping to // the old camera state. _pathSegments[_currentSegmentIndex].setStart(currentCameraState()); _isPlaying = true; } void AutoNavigationHandler::stopPath() { _isPlaying = false; } // TODO: remove when not needed // Created for debugging std::vector<glm::dvec3> AutoNavigationHandler::getCurvePositions(int nPerSegment) { std::vector<glm::dvec3> positions; if (_pathSegments.empty()) { LERROR("There is no current path to sample points from."); return positions; } const double du = 1.0 / nPerSegment; for (PathSegment &p : _pathSegments) { for (double u = 0.0; u < 1.0; u += du) { auto position = p.getPositionAt(u); positions.push_back(position); } } return positions; } // TODO: remove when not needed // Created for debugging std::vector<glm::dvec3> AutoNavigationHandler::getControlPoints() { std::vector<glm::dvec3> points; if (_pathSegments.empty()) { LERROR("There is no current path to sample points from."); return points; } for (PathSegment &p : _pathSegments) { std::vector<glm::dvec3> curvePoints = p.getControlPoints(); points.insert(points.end(), curvePoints.begin(), curvePoints.end()); } return points; } bool AutoNavigationHandler::handleInstruction(const Instruction& instruction, int index) { bool success = true; switch (instruction.type) { case InstructionType::TargetNode: success = handleTargetNodeInstruction(instruction); break; case InstructionType::NavigationState: success = handleNavigationStateInstruction(instruction); break; case InstructionType::Pause: success = handlePauseInstruction(instruction); break; default: LERROR("Non-implemented instruction type."); success = false; break; } if (!success) { LERROR(fmt::format("Failed handling instruction number {}.", std::to_string(index + 1))); return false; } return true; } bool AutoNavigationHandler::handleTargetNodeInstruction(const Instruction& instruction) { // Verify instruction type TargetNodeInstructionProps* props = dynamic_cast<TargetNodeInstructionProps*>(instruction.props.get()); if (!props) { LERROR("Could not handle target node instruction."); return false; } CameraState startState = _pathSegments.empty() ? currentCameraState() : _pathSegments.back().end(); // Compute end state std::string& identifier = props->targetNode; const SceneGraphNode* targetNode = sceneGraphNode(identifier); if (!targetNode) { LERROR(fmt::format("Could not find node '{}' to target", identifier)); return false; } glm::dvec3 targetPos; if (props->position.has_value()) { // note that the anchor and reference frame is our targetnode. // The position in instruction is given is relative coordinates. targetPos = targetNode->worldPosition() + targetNode->worldRotationMatrix() * props->position.value(); } else { bool hasHeight = props->height.has_value(); // TODO: compute defualt height in a better way double defaultHeight = 2 * targetNode->boundingSphere(); double height = hasHeight? props->height.value() : defaultHeight; targetPos = computeTargetPositionAtNode( targetNode, startState.position, height ); } glm::dmat4 lookAtMat = glm::lookAt( targetPos, targetNode->worldPosition(), camera()->lookUpVectorWorldSpace() ); glm::dquat targetRot = glm::normalize(glm::inverse(glm::quat_cast(lookAtMat))); CameraState endState = CameraState{ targetPos, targetRot, identifier }; addSegment(startState, endState, instruction.props->duration); return true; } bool AutoNavigationHandler::handleNavigationStateInstruction( const Instruction& instruction) { // Verify instruction type NavigationStateInstructionProps* props = dynamic_cast<NavigationStateInstructionProps*>(instruction.props.get()); if (!props) { LERROR(fmt::format("Could not handle navigation state instruction.")); return false; } CameraState startState = _pathSegments.empty() ? currentCameraState() : _pathSegments.back().end(); interaction::NavigationHandler::NavigationState ns = props->navState; CameraState endState = cameraStateFromNavigationState(ns); addSegment(startState, endState, instruction.props->duration); return true; } bool AutoNavigationHandler::handlePauseInstruction(const Instruction& instruction) { // Verify instruction type PauseInstructionProps* props = dynamic_cast<PauseInstructionProps*>(instruction.props.get()); if (!props) { LERROR(fmt::format("Could not handle pause instruction.")); return false; } CameraState state =_pathSegments.empty() ? currentCameraState() : _pathSegments.back().end(); // TODO: implement more complex behavior later addPause(state, instruction.props->duration); return true; } void AutoNavigationHandler::addSegment(CameraState& start, CameraState& end, std::optional<double> duration) { // compute startTime double startTime = 0.0; if (!_pathSegments.empty()) { PathSegment& last = _pathSegments.back(); startTime = last.startTime() + last.duration(); } bool hasType = (_pathCurveType != CurveType::None); PathSegment newSegment = hasType ? PathSegment{ start, end, startTime, _pathCurveType } : PathSegment{ start, end, startTime }; // TODO: handle duration better if (duration.has_value()) { newSegment.setDuration(duration.value()); } _pathSegments.push_back(newSegment); } void AutoNavigationHandler::addPause(CameraState& state, std::optional<double> duration) { // compute startTime double startTime = 0.0; if (!_pathSegments.empty()) { PathSegment& last = _pathSegments.back(); startTime = last.startTime() + last.duration(); } PathSegment newSegment = PathSegment{ state, state, startTime, CurveType::Pause }; // TODO: handle duration better if (duration.has_value()) { newSegment.setDuration(duration.value()); } _pathSegments.push_back(newSegment); } glm::dvec3 AutoNavigationHandler::computeTargetPositionAtNode( const SceneGraphNode* node, glm::dvec3 prevPos, double height) { // TODO: compute actual distance above surface and validate negative values glm::dvec3 targetPos = node->worldPosition(); glm::dvec3 targetToPrevVector = prevPos - targetPos; double radius = static_cast<double>(node->boundingSphere()); // move target position out from surface, along vector to camera targetPos += glm::normalize(targetToPrevVector) * (radius + height); return targetPos; } CameraState AutoNavigationHandler::cameraStateFromNavigationState( const interaction::NavigationHandler::NavigationState& ns) { // OBS! The following code is exactly the same as used in // NavigationHandler::applyNavigationState. Should probably be made into a function. const SceneGraphNode* referenceFrame = sceneGraphNode(ns.referenceFrame); const SceneGraphNode* anchorNode = sceneGraphNode(ns.anchor); // The anchor is also the target if (!anchorNode) { LERROR(fmt::format("Could not find node '{}' to target. Returning empty state.", ns.anchor)); return CameraState{}; } const glm::dvec3 anchorWorldPosition = anchorNode->worldPosition(); const glm::dmat3 referenceFrameTransform = referenceFrame->worldRotationMatrix(); const glm::dvec3 targetPositionWorld = anchorWorldPosition + glm::dvec3(referenceFrameTransform * glm::dvec4(ns.position, 1.0)); glm::dvec3 up = ns.up.has_value() ? glm::normalize(referenceFrameTransform * ns.up.value()) : glm::dvec3(0.0, 1.0, 0.0); // Construct vectors of a "neutral" view, i.e. when the aim is centered in view. glm::dvec3 neutralView = glm::normalize(anchorWorldPosition - targetPositionWorld); glm::dquat neutralCameraRotation = glm::inverse(glm::quat_cast(glm::lookAt( glm::dvec3(0.0), neutralView, up ))); glm::dquat pitchRotation = glm::angleAxis(ns.pitch, glm::dvec3(1.f, 0.f, 0.f)); glm::dquat yawRotation = glm::angleAxis(ns.yaw, glm::dvec3(0.f, -1.f, 0.f)); glm::quat targetRotation = neutralCameraRotation * yawRotation * pitchRotation; return CameraState{ targetPositionWorld, targetRotation, ns.anchor }; } } // namespace openspace::autonavigation <commit_msg>Make sure that the anchor node is always updated<commit_after>/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2019 * * * * 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 <modules/autonavigation/autonavigationhandler.h> #include <modules/autonavigation/helperfunctions.h> #include <modules/autonavigation/instruction.h> #include <modules/autonavigation/pathspecification.h> #include <openspace/engine/globals.h> #include <openspace/engine/windowdelegate.h> #include <openspace/interaction/navigationhandler.h> #include <openspace/scene/scenegraphnode.h> #include <openspace/util/camera.h> #include <openspace/query/query.h> #include <ghoul/logging/logmanager.h> #include <glm/gtx/vector_angle.hpp> #include <glm/gtx/quaternion.hpp> #include <algorithm> namespace { constexpr const char* _loggerCat = "AutoNavigationHandler"; } // namespace namespace openspace::autonavigation { // Temporary function to convert a string to one of the bools above. // TODO: move to a better place / rewrite CurveType stringToCurveType(std::string str) { if (str.empty()) return CurveType::None; std::transform(str.begin(), str.end(), str.begin(), ::tolower); if (str == "bezier3") { return CurveType::Bezier3; } else if (str == "linear") { return CurveType::Linear; } else { LERROR(fmt::format("'{}' is not a valid curve type! Choosing default.", str)); return CurveType::None; } } AutoNavigationHandler::AutoNavigationHandler() : properties::PropertyOwner({ "AutoNavigationHandler" }) { // Add the properties // TODO } AutoNavigationHandler::~AutoNavigationHandler() {} // NOLINT Camera* AutoNavigationHandler::camera() const { return global::navigationHandler.camera(); } const double AutoNavigationHandler::pathDuration() const { double sum = 0.0; for (const PathSegment& ps : _pathSegments) { sum += ps.duration(); } return sum; } const bool AutoNavigationHandler::hasFinished() const { return _currentTime > pathDuration(); } CameraState AutoNavigationHandler::currentCameraState() { CameraState cs; cs.position = camera()->positionVec3(); cs.rotation = camera()->rotationQuaternion(); cs.referenceNode = global::navigationHandler.anchorNode()->identifier(); return cs; } void AutoNavigationHandler::updateCamera(double deltaTime) { ghoul_assert(camera() != nullptr, "Camera must not be nullptr"); if (!_isPlaying || _pathSegments.empty()) return; _currentTime += deltaTime; PathSegment& cps = _pathSegments[_currentSegmentIndex]; // Have we walked past the current segment? if (_currentTime > cps.endTime()) { _currentSegmentIndex++; _distanceAlongCurrentSegment = 0.0; // WStepped past the last segment if (_currentSegmentIndex > _pathSegments.size() - 1) { LINFO("Reached end of path."); _isPlaying = false; return; } cps = _pathSegments[_currentSegmentIndex]; if (_stopAtTargets) { pausePath(); return; } } double prevDistance = _distanceAlongCurrentSegment; double displacement = deltaTime * cps.speedAtTime(_currentTime - cps.startTime()); _distanceAlongCurrentSegment += displacement; double relativeDisplacement = _distanceAlongCurrentSegment / cps.pathLength(); relativeDisplacement = std::max(0.0, std::min(relativeDisplacement, 1.0)); // When halfway along a curve, set anchor node in orbitalNavigator, to render // visible nodes and add possibility to navigate when we reach the end. std::string targetAnchor = cps.end().referenceNode; std::string currentAnchor = global::navigationHandler.anchorNode()->identifier(); if ((relativeDisplacement > 0.5) && (currentAnchor != targetAnchor)) { global::navigationHandler.orbitalNavigator().setAnchorNode(targetAnchor); } glm::dvec3 cameraPosition = cps.getPositionAt(relativeDisplacement); glm::dquat cameraRotation = cps.getRotationAt(relativeDisplacement); camera()->setPositionVec3(cameraPosition); camera()->setRotation(cameraRotation); } void AutoNavigationHandler::createPath(PathSpecification& spec) { clearPath(); _pathCurveType = stringToCurveType(spec.curveType()); bool success = true; for (int i = 0; i < spec.instructions()->size(); i++) { const Instruction& ins = spec.instructions()->at(i); success = handleInstruction(ins, i); if (!success) break; } // OBS! Would it be better to save the spec in the handler class? _stopAtTargets = spec.stopAtTargets(); // Check if we have a specified start state. If so, update the first segment if (spec.hasStartState() && _pathSegments.size() > 0) { CameraState startState = cameraStateFromNavigationState(spec.startState()); _pathSegments[0].setStart(startState); } if (success) { LINFO("Succefully generated camera path."); startPath(); } else LERROR("Could not create path."); } void AutoNavigationHandler::clearPath() { LINFO("Clearing path..."); _pathSegments.clear(); _currentTime = 0.0; _currentSegmentIndex = 0; _distanceAlongCurrentSegment = 0.0; } void AutoNavigationHandler::startPath() { if (_pathSegments.empty()) { LERROR("Cannot start an empty path."); return; } LINFO("Starting path..."); _currentTime = 0.0; _isPlaying = true; } void AutoNavigationHandler::pausePath() { if (!_isPlaying) { LERROR("Cannot pause a path that isn't playing"); return; } LINFO(fmt::format("Paused path at target {} / {}", _currentSegmentIndex, _pathSegments.size())); _isPlaying = false; } void AutoNavigationHandler::continuePath() { if (_pathSegments.empty() || hasFinished()) { LERROR("No path to resume (path is empty or has finished)."); return; } if (_isPlaying) { LERROR("Cannot resume a path that is already playing"); return; } LINFO("Continuing path..."); // Recompute start camera state for the upcoming path segment, to avoid clipping to // the old camera state. _pathSegments[_currentSegmentIndex].setStart(currentCameraState()); _isPlaying = true; } void AutoNavigationHandler::stopPath() { _isPlaying = false; } // TODO: remove when not needed // Created for debugging std::vector<glm::dvec3> AutoNavigationHandler::getCurvePositions(int nPerSegment) { std::vector<glm::dvec3> positions; if (_pathSegments.empty()) { LERROR("There is no current path to sample points from."); return positions; } const double du = 1.0 / nPerSegment; for (PathSegment &p : _pathSegments) { for (double u = 0.0; u < 1.0; u += du) { auto position = p.getPositionAt(u); positions.push_back(position); } } return positions; } // TODO: remove when not needed // Created for debugging std::vector<glm::dvec3> AutoNavigationHandler::getControlPoints() { std::vector<glm::dvec3> points; if (_pathSegments.empty()) { LERROR("There is no current path to sample points from."); return points; } for (PathSegment &p : _pathSegments) { std::vector<glm::dvec3> curvePoints = p.getControlPoints(); points.insert(points.end(), curvePoints.begin(), curvePoints.end()); } return points; } bool AutoNavigationHandler::handleInstruction(const Instruction& instruction, int index) { bool success = true; switch (instruction.type) { case InstructionType::TargetNode: success = handleTargetNodeInstruction(instruction); break; case InstructionType::NavigationState: success = handleNavigationStateInstruction(instruction); break; case InstructionType::Pause: success = handlePauseInstruction(instruction); break; default: LERROR("Non-implemented instruction type."); success = false; break; } if (!success) { LERROR(fmt::format("Failed handling instruction number {}.", std::to_string(index + 1))); return false; } return true; } bool AutoNavigationHandler::handleTargetNodeInstruction(const Instruction& instruction) { // Verify instruction type TargetNodeInstructionProps* props = dynamic_cast<TargetNodeInstructionProps*>(instruction.props.get()); if (!props) { LERROR("Could not handle target node instruction."); return false; } CameraState startState = _pathSegments.empty() ? currentCameraState() : _pathSegments.back().end(); // Compute end state std::string& identifier = props->targetNode; const SceneGraphNode* targetNode = sceneGraphNode(identifier); if (!targetNode) { LERROR(fmt::format("Could not find node '{}' to target", identifier)); return false; } glm::dvec3 targetPos; if (props->position.has_value()) { // note that the anchor and reference frame is our targetnode. // The position in instruction is given is relative coordinates. targetPos = targetNode->worldPosition() + targetNode->worldRotationMatrix() * props->position.value(); } else { bool hasHeight = props->height.has_value(); // TODO: compute defualt height in a better way double defaultHeight = 2 * targetNode->boundingSphere(); double height = hasHeight? props->height.value() : defaultHeight; targetPos = computeTargetPositionAtNode( targetNode, startState.position, height ); } glm::dmat4 lookAtMat = glm::lookAt( targetPos, targetNode->worldPosition(), camera()->lookUpVectorWorldSpace() ); glm::dquat targetRot = glm::normalize(glm::inverse(glm::quat_cast(lookAtMat))); CameraState endState = CameraState{ targetPos, targetRot, identifier }; addSegment(startState, endState, instruction.props->duration); return true; } bool AutoNavigationHandler::handleNavigationStateInstruction( const Instruction& instruction) { // Verify instruction type NavigationStateInstructionProps* props = dynamic_cast<NavigationStateInstructionProps*>(instruction.props.get()); if (!props) { LERROR(fmt::format("Could not handle navigation state instruction.")); return false; } CameraState startState = _pathSegments.empty() ? currentCameraState() : _pathSegments.back().end(); interaction::NavigationHandler::NavigationState ns = props->navState; CameraState endState = cameraStateFromNavigationState(ns); addSegment(startState, endState, instruction.props->duration); return true; } bool AutoNavigationHandler::handlePauseInstruction(const Instruction& instruction) { // Verify instruction type PauseInstructionProps* props = dynamic_cast<PauseInstructionProps*>(instruction.props.get()); if (!props) { LERROR(fmt::format("Could not handle pause instruction.")); return false; } CameraState state =_pathSegments.empty() ? currentCameraState() : _pathSegments.back().end(); // TODO: implement more complex behavior later addPause(state, instruction.props->duration); return true; } void AutoNavigationHandler::addSegment(CameraState& start, CameraState& end, std::optional<double> duration) { // compute startTime double startTime = 0.0; if (!_pathSegments.empty()) { PathSegment& last = _pathSegments.back(); startTime = last.startTime() + last.duration(); } bool hasType = (_pathCurveType != CurveType::None); PathSegment newSegment = hasType ? PathSegment{ start, end, startTime, _pathCurveType } : PathSegment{ start, end, startTime }; // TODO: handle duration better if (duration.has_value()) { newSegment.setDuration(duration.value()); } _pathSegments.push_back(newSegment); } void AutoNavigationHandler::addPause(CameraState& state, std::optional<double> duration) { // compute startTime double startTime = 0.0; if (!_pathSegments.empty()) { PathSegment& last = _pathSegments.back(); startTime = last.startTime() + last.duration(); } PathSegment newSegment = PathSegment{ state, state, startTime, CurveType::Pause }; // TODO: handle duration better if (duration.has_value()) { newSegment.setDuration(duration.value()); } _pathSegments.push_back(newSegment); } glm::dvec3 AutoNavigationHandler::computeTargetPositionAtNode( const SceneGraphNode* node, glm::dvec3 prevPos, double height) { // TODO: compute actual distance above surface and validate negative values glm::dvec3 targetPos = node->worldPosition(); glm::dvec3 targetToPrevVector = prevPos - targetPos; double radius = static_cast<double>(node->boundingSphere()); // move target position out from surface, along vector to camera targetPos += glm::normalize(targetToPrevVector) * (radius + height); return targetPos; } CameraState AutoNavigationHandler::cameraStateFromNavigationState( const interaction::NavigationHandler::NavigationState& ns) { // OBS! The following code is exactly the same as used in // NavigationHandler::applyNavigationState. Should probably be made into a function. const SceneGraphNode* referenceFrame = sceneGraphNode(ns.referenceFrame); const SceneGraphNode* anchorNode = sceneGraphNode(ns.anchor); // The anchor is also the target if (!anchorNode) { LERROR(fmt::format("Could not find node '{}' to target. Returning empty state.", ns.anchor)); return CameraState{}; } const glm::dvec3 anchorWorldPosition = anchorNode->worldPosition(); const glm::dmat3 referenceFrameTransform = referenceFrame->worldRotationMatrix(); const glm::dvec3 targetPositionWorld = anchorWorldPosition + glm::dvec3(referenceFrameTransform * glm::dvec4(ns.position, 1.0)); glm::dvec3 up = ns.up.has_value() ? glm::normalize(referenceFrameTransform * ns.up.value()) : glm::dvec3(0.0, 1.0, 0.0); // Construct vectors of a "neutral" view, i.e. when the aim is centered in view. glm::dvec3 neutralView = glm::normalize(anchorWorldPosition - targetPositionWorld); glm::dquat neutralCameraRotation = glm::inverse(glm::quat_cast(glm::lookAt( glm::dvec3(0.0), neutralView, up ))); glm::dquat pitchRotation = glm::angleAxis(ns.pitch, glm::dvec3(1.f, 0.f, 0.f)); glm::dquat yawRotation = glm::angleAxis(ns.yaw, glm::dvec3(0.f, -1.f, 0.f)); glm::quat targetRotation = neutralCameraRotation * yawRotation * pitchRotation; return CameraState{ targetPositionWorld, targetRotation, ns.anchor }; } } // namespace openspace::autonavigation <|endoftext|>
<commit_before>/** * Copyright (c) 2016-2018 mvs developers * * This file is part of metaverse-explorer. * * metaverse-explorer is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <metaverse/explorer/json_helper.hpp> #include <metaverse/explorer/dispatch.hpp> #include <metaverse/explorer/extensions/commands/getaccountasset.hpp> #include <metaverse/explorer/extensions/command_extension_func.hpp> #include <metaverse/explorer/extensions/command_assistant.hpp> #include <metaverse/explorer/extensions/exception.hpp> #include <metaverse/explorer/extensions/base_helper.hpp> namespace libbitcoin { namespace explorer { namespace commands { using namespace bc::explorer::config; /************************ getaccountasset *************************/ console_result getaccountasset::invoke (Json::Value& jv_output, libbitcoin::server::server_node& node) { auto& aroot = jv_output; Json::Value assets; std::string symbol; auto& blockchain = node.chain_impl(); if (argument_.symbol.length() > ASSET_DETAIL_SYMBOL_FIX_SIZE) throw asset_symbol_length_exception{"asset symbol length must be less than 64."}; auto sh_vec = std::make_shared<std::vector<asset_detail>>(); blockchain.is_account_passwd_valid(auth_.name, auth_.auth); auto pvaddr = blockchain.get_account_addresses(auth_.name); if(!pvaddr) throw address_list_nullptr_exception{"nullptr for address list"}; // 1. get asset in blockchain // get address unspent asset balance std::string addr; for (auto& each : *pvaddr){ addr = each.get_address(); sync_fetch_asset_balance_record (addr, blockchain, sh_vec); } Json::Value asset_data; for (auto& elem: *sh_vec) { if(!argument_.symbol.empty() && argument_.symbol != elem.get_symbol()) continue; asset_data["symbol"] = elem.get_symbol(); asset_data["address"] = elem.get_address(); symbol = elem.get_symbol(); if (get_api_version() == 1) { asset_data["quantity"] += elem.get_maximum_supply(); } else { asset_data["quantity"] = elem.get_maximum_supply(); } //asset_data["address"] = elem.get_address(); auto issued_asset = blockchain.get_issued_asset(symbol); if(issued_asset && get_api_version() == 1) { asset_data["decimal_number"] += issued_asset->get_decimal_number(); } if(issued_asset && get_api_version() == 2) { asset_data["decimal_number"] = issued_asset->get_decimal_number(); } asset_data["status"] = "unspent"; assets.append(asset_data); } // 2. get asset in local database // shoudl filter all issued asset which be stored in local account asset database sh_vec->clear(); sh_vec = blockchain.get_issued_assets(); //std::shared_ptr<std::vector<business_address_asset>> auto sh_unissued = blockchain.get_account_unissued_assets(auth_.name); for (auto& elem: *sh_unissued) { auto symbol = elem.detail.get_symbol(); auto pos = std::find_if(sh_vec->begin(), sh_vec->end(), [&](const asset_detail& elem){ return symbol == elem.get_symbol(); }); if (pos != sh_vec->end()){ // asset already issued in blockchain continue; } // symbol filter if(!argument_.symbol.empty() && argument_.symbol != symbol) continue; Json::Value asset_data; asset_data["symbol"] = elem.detail.get_symbol(); asset_data["address"] = ""; symbol = elem.detail.get_symbol(); asset_data["quantity"] += elem.detail.get_maximum_supply(); asset_data["decimal_number"] += elem.detail.get_decimal_number(); //asset_data["address"] = ""; asset_data["status"] = "unissued"; assets.append(asset_data); } if (get_api_version() == 1 && assets.isNull()) { //compatible for v1 aroot["assets"] = ""; } else { aroot["assets"] = assets; } return console_result::okay; } } // namespace commands } // namespace explorer } // namespace libbitcoin <commit_msg>fix: getaccountasset add info for secondissue_assetshare_threshold<commit_after>/** * Copyright (c) 2016-2018 mvs developers * * This file is part of metaverse-explorer. * * metaverse-explorer is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <metaverse/explorer/json_helper.hpp> #include <metaverse/explorer/dispatch.hpp> #include <metaverse/explorer/extensions/commands/getaccountasset.hpp> #include <metaverse/explorer/extensions/command_extension_func.hpp> #include <metaverse/explorer/extensions/command_assistant.hpp> #include <metaverse/explorer/extensions/exception.hpp> #include <metaverse/explorer/extensions/base_helper.hpp> namespace libbitcoin { namespace explorer { namespace commands { using namespace bc::explorer::config; /************************ getaccountasset *************************/ console_result getaccountasset::invoke (Json::Value& jv_output, libbitcoin::server::server_node& node) { auto& aroot = jv_output; Json::Value assets; std::string symbol; auto& blockchain = node.chain_impl(); if (argument_.symbol.length() > ASSET_DETAIL_SYMBOL_FIX_SIZE) throw asset_symbol_length_exception{"asset symbol length must be less than 64."}; auto sh_vec = std::make_shared<std::vector<asset_detail>>(); blockchain.is_account_passwd_valid(auth_.name, auth_.auth); auto pvaddr = blockchain.get_account_addresses(auth_.name); if(!pvaddr) throw address_list_nullptr_exception{"nullptr for address list"}; // 1. get asset in blockchain // get address unspent asset balance std::string addr; for (auto& each : *pvaddr){ addr = each.get_address(); sync_fetch_asset_balance_record (addr, blockchain, sh_vec); } Json::Value asset_data; for (auto& elem: *sh_vec) { if(!argument_.symbol.empty() && argument_.symbol != elem.get_symbol()) continue; auto symbol = elem.get_symbol(); auto issued_asset = blockchain.get_issued_asset(symbol); if (!issued_asset) { continue; } asset_data["symbol"] = symbol; asset_data["address"] = elem.get_address(); if (get_api_version() == 1) { asset_data["quantity"] += elem.get_maximum_supply(); asset_data["decimal_number"] += issued_asset->get_decimal_number(); asset_data["secondissue_assetshare_threshold"] += elem.get_secondissue_assetshare_threshold(); } else { asset_data["quantity"] = elem.get_maximum_supply(); asset_data["decimal_number"] = issued_asset->get_decimal_number(); asset_data["secondissue_assetshare_threshold"] = elem.get_secondissue_assetshare_threshold(); } asset_data["status"] = "unspent"; assets.append(asset_data); } // 2. get asset in local database // shoudl filter all issued asset which be stored in local account asset database sh_vec->clear(); sh_vec = blockchain.get_issued_assets(); auto sh_unissued = blockchain.get_account_unissued_assets(auth_.name); for (auto& elem: *sh_unissued) { auto& symbol = elem.detail.get_symbol(); auto pos = std::find_if(sh_vec->begin(), sh_vec->end(), [&symbol](const asset_detail& elem){ return symbol == elem.get_symbol(); }); if (pos != sh_vec->end()){ // asset already issued in blockchain continue; } // symbol filter if(!argument_.symbol.empty() && argument_.symbol != symbol) continue; Json::Value asset_data; asset_data["symbol"] = symbol; asset_data["address"] = ""; if (get_api_version() == 1) { asset_data["quantity"] += elem.detail.get_maximum_supply(); asset_data["decimal_number"] += elem.detail.get_decimal_number(); asset_data["secondissue_assetshare_threshold"] += elem.detail.get_secondissue_assetshare_threshold(); } else { asset_data["quantity"] = elem.detail.get_maximum_supply(); asset_data["decimal_number"] = elem.detail.get_decimal_number(); asset_data["secondissue_assetshare_threshold"] = elem.detail.get_secondissue_assetshare_threshold(); } asset_data["status"] = "unissued"; assets.append(asset_data); } if (get_api_version() == 1 && assets.isNull()) { //compatible for v1 aroot["assets"] = ""; } else { aroot["assets"] = assets; } return console_result::okay; } } // namespace commands } // namespace explorer } // namespace libbitcoin <|endoftext|>
<commit_before>/* * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef otbDimensionalityReductionModelFactory_hxx #define otbDimensionalityReductionModelFactory_hxx #include "otbDimensionalityReductionModelFactory.h" #include "otbConfigure.h" #include "otbSOMModelFactory.h" #ifdef OTB_USE_SHARK #include "otbAutoencoderModelFactory.h" #include "otbPCAModelFactory.h" #endif #include "itkMutexLockHolder.h" namespace otb { template <class TInputValue, class TTargetValue> using LogAutoencoderModelFactory = AutoencoderModelFactory<TInputValue, TTargetValue, shark::LogisticNeuron> ; template <class TInputValue, class TTargetValue> using SOM2DModelFactory = SOMModelFactory<TInputValue, TTargetValue, 2> ; template <class TInputValue, class TTargetValue> using SOM3DModelFactory = SOMModelFactory<TInputValue, TTargetValue, 3> ; template <class TInputValue, class TTargetValue> using SOM4DModelFactory = SOMModelFactory<TInputValue, TTargetValue, 4> ; template <class TInputValue, class TTargetValue> using SOM5DModelFactory = SOMModelFactory<TInputValue, TTargetValue, 5> ; template <class TInputValue, class TOutputValue> typename DimensionalityReductionModelFactory<TInputValue,TOutputValue>::DimensionalityReductionModelTypePointer DimensionalityReductionModelFactory<TInputValue,TOutputValue> ::CreateDimensionalityReductionModel(const std::string& path, FileModeType mode) { RegisterBuiltInFactories(); std::list<DimensionalityReductionModelTypePointer> possibleDimensionalityReductionModel; std::list<LightObject::Pointer> allobjects = itk::ObjectFactoryBase::CreateAllInstance("DimensionalityReductionModel"); for(std::list<LightObject::Pointer>::iterator i = allobjects.begin(); i != allobjects.end(); ++i) { DimensionalityReductionModelType* io = dynamic_cast<DimensionalityReductionModelType*>(i->GetPointer()); if(io) { possibleDimensionalityReductionModel.push_back(io); } else { std::cerr << "Error DimensionalityReductionModel Factory did not return an DimensionalityReductionModel: " << (*i)->GetNameOfClass() << std::endl; } } for(typename std::list<DimensionalityReductionModelTypePointer>::iterator k = possibleDimensionalityReductionModel.begin(); k != possibleDimensionalityReductionModel.end(); ++k) { if( mode == ReadMode ) { if((*k)->CanReadFile(path)) { return *k; } } else if( mode == WriteMode ) { if((*k)->CanWriteFile(path)) { return *k; } } } return nullptr; } template <class TInputValue, class TOutputValue> void DimensionalityReductionModelFactory<TInputValue,TOutputValue> ::RegisterBuiltInFactories() { itk::MutexLockHolder<itk::SimpleMutexLock> lockHolder(mutex); RegisterFactory(SOM2DModelFactory<TInputValue,TOutputValue>::New()); RegisterFactory(SOM3DModelFactory<TInputValue,TOutputValue>::New()); RegisterFactory(SOM4DModelFactory<TInputValue,TOutputValue>::New()); RegisterFactory(SOM5DModelFactory<TInputValue,TOutputValue>::New()); #ifdef OTB_USE_SHARK RegisterFactory(PCAModelFactory<TInputValue,TOutputValue>::New()); RegisterFactory(LogAutoencoderModelFactory<TInputValue,TOutputValue>::New()); #endif } template <class TInputValue, class TOutputValue> void DimensionalityReductionModelFactory<TInputValue,TOutputValue> ::RegisterFactory(itk::ObjectFactoryBase * factory) { // Unregister any previously registered factory of the same class // Might be more intensive but static bool is not an option due to // ld error. itk::ObjectFactoryBase::UnRegisterFactory(factory); itk::ObjectFactoryBase::RegisterFactory(factory); } template <class TInputValue, class TOutputValue> void DimensionalityReductionModelFactory<TInputValue,TOutputValue> ::CleanFactories() { itk::MutexLockHolder<itk::SimpleMutexLock> lockHolder(mutex); std::list<itk::ObjectFactoryBase*> factories = itk::ObjectFactoryBase::GetRegisteredFactories(); std::list<itk::ObjectFactoryBase*>::iterator itFac; for (itFac = factories.begin(); itFac != factories.end() ; ++itFac) { // SOM 5D SOM5DModelFactory<TInputValue,TOutputValue> *som5dFactory = dynamic_cast<SOM5DModelFactory<TInputValue,TOutputValue> *>(*itFac); if (som5dFactory) { itk::ObjectFactoryBase::UnRegisterFactory(som5dFactory); continue; } // SOM 4D SOM4DModelFactory<TInputValue,TOutputValue> *som4dFactory = dynamic_cast<SOM4DModelFactory<TInputValue,TOutputValue> *>(*itFac); if (som4dFactory) { itk::ObjectFactoryBase::UnRegisterFactory(som4dFactory); continue; } // SOM 3D SOM3DModelFactory<TInputValue,TOutputValue> *som3dFactory = dynamic_cast<SOM3DModelFactory<TInputValue,TOutputValue> *>(*itFac); if (som3dFactory) { itk::ObjectFactoryBase::UnRegisterFactory(som3dFactory); continue; } // SOM 2D SOM2DModelFactory<TInputValue,TOutputValue> *som2dFactory = dynamic_cast<SOM2DModelFactory<TInputValue,TOutputValue> *>(*itFac); if (som2dFactory) { itk::ObjectFactoryBase::UnRegisterFactory(som2dFactory); continue; } #ifdef OTB_USE_SHARK // Autoencoder LogAutoencoderModelFactory<TInputValue,TOutputValue> *aeFactory = dynamic_cast<LogAutoencoderModelFactory<TInputValue,TOutputValue> *>(*itFac); if (aeFactory) { itk::ObjectFactoryBase::UnRegisterFactory(aeFactory); continue; } // PCA PCAModelFactory<TInputValue,TOutputValue> *pcaFactory = dynamic_cast<PCAModelFactory<TInputValue,TOutputValue> *>(*itFac); if (pcaFactory) { itk::ObjectFactoryBase::UnRegisterFactory(pcaFactory); continue; } #endif } } } // end namespace otb #endif <commit_msg>BUG: missing test on OTB_USE_SHARK variable<commit_after>/* * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef otbDimensionalityReductionModelFactory_hxx #define otbDimensionalityReductionModelFactory_hxx #include "otbDimensionalityReductionModelFactory.h" #include "otbConfigure.h" #include "otbSOMModelFactory.h" #ifdef OTB_USE_SHARK #include "otbAutoencoderModelFactory.h" #include "otbPCAModelFactory.h" #endif #include "itkMutexLockHolder.h" namespace otb { #ifdef OTB_USE_SHARK template <class TInputValue, class TTargetValue> using LogAutoencoderModelFactory = AutoencoderModelFactory<TInputValue, TTargetValue, shark::LogisticNeuron> ; #endif template <class TInputValue, class TTargetValue> using SOM2DModelFactory = SOMModelFactory<TInputValue, TTargetValue, 2> ; template <class TInputValue, class TTargetValue> using SOM3DModelFactory = SOMModelFactory<TInputValue, TTargetValue, 3> ; template <class TInputValue, class TTargetValue> using SOM4DModelFactory = SOMModelFactory<TInputValue, TTargetValue, 4> ; template <class TInputValue, class TTargetValue> using SOM5DModelFactory = SOMModelFactory<TInputValue, TTargetValue, 5> ; template <class TInputValue, class TOutputValue> typename DimensionalityReductionModelFactory<TInputValue,TOutputValue>::DimensionalityReductionModelTypePointer DimensionalityReductionModelFactory<TInputValue,TOutputValue> ::CreateDimensionalityReductionModel(const std::string& path, FileModeType mode) { RegisterBuiltInFactories(); std::list<DimensionalityReductionModelTypePointer> possibleDimensionalityReductionModel; std::list<LightObject::Pointer> allobjects = itk::ObjectFactoryBase::CreateAllInstance("DimensionalityReductionModel"); for(std::list<LightObject::Pointer>::iterator i = allobjects.begin(); i != allobjects.end(); ++i) { DimensionalityReductionModelType* io = dynamic_cast<DimensionalityReductionModelType*>(i->GetPointer()); if(io) { possibleDimensionalityReductionModel.push_back(io); } else { std::cerr << "Error DimensionalityReductionModel Factory did not return an DimensionalityReductionModel: " << (*i)->GetNameOfClass() << std::endl; } } for(typename std::list<DimensionalityReductionModelTypePointer>::iterator k = possibleDimensionalityReductionModel.begin(); k != possibleDimensionalityReductionModel.end(); ++k) { if( mode == ReadMode ) { if((*k)->CanReadFile(path)) { return *k; } } else if( mode == WriteMode ) { if((*k)->CanWriteFile(path)) { return *k; } } } return nullptr; } template <class TInputValue, class TOutputValue> void DimensionalityReductionModelFactory<TInputValue,TOutputValue> ::RegisterBuiltInFactories() { itk::MutexLockHolder<itk::SimpleMutexLock> lockHolder(mutex); RegisterFactory(SOM2DModelFactory<TInputValue,TOutputValue>::New()); RegisterFactory(SOM3DModelFactory<TInputValue,TOutputValue>::New()); RegisterFactory(SOM4DModelFactory<TInputValue,TOutputValue>::New()); RegisterFactory(SOM5DModelFactory<TInputValue,TOutputValue>::New()); #ifdef OTB_USE_SHARK RegisterFactory(PCAModelFactory<TInputValue,TOutputValue>::New()); RegisterFactory(LogAutoencoderModelFactory<TInputValue,TOutputValue>::New()); #endif } template <class TInputValue, class TOutputValue> void DimensionalityReductionModelFactory<TInputValue,TOutputValue> ::RegisterFactory(itk::ObjectFactoryBase * factory) { // Unregister any previously registered factory of the same class // Might be more intensive but static bool is not an option due to // ld error. itk::ObjectFactoryBase::UnRegisterFactory(factory); itk::ObjectFactoryBase::RegisterFactory(factory); } template <class TInputValue, class TOutputValue> void DimensionalityReductionModelFactory<TInputValue,TOutputValue> ::CleanFactories() { itk::MutexLockHolder<itk::SimpleMutexLock> lockHolder(mutex); std::list<itk::ObjectFactoryBase*> factories = itk::ObjectFactoryBase::GetRegisteredFactories(); std::list<itk::ObjectFactoryBase*>::iterator itFac; for (itFac = factories.begin(); itFac != factories.end() ; ++itFac) { // SOM 5D SOM5DModelFactory<TInputValue,TOutputValue> *som5dFactory = dynamic_cast<SOM5DModelFactory<TInputValue,TOutputValue> *>(*itFac); if (som5dFactory) { itk::ObjectFactoryBase::UnRegisterFactory(som5dFactory); continue; } // SOM 4D SOM4DModelFactory<TInputValue,TOutputValue> *som4dFactory = dynamic_cast<SOM4DModelFactory<TInputValue,TOutputValue> *>(*itFac); if (som4dFactory) { itk::ObjectFactoryBase::UnRegisterFactory(som4dFactory); continue; } // SOM 3D SOM3DModelFactory<TInputValue,TOutputValue> *som3dFactory = dynamic_cast<SOM3DModelFactory<TInputValue,TOutputValue> *>(*itFac); if (som3dFactory) { itk::ObjectFactoryBase::UnRegisterFactory(som3dFactory); continue; } // SOM 2D SOM2DModelFactory<TInputValue,TOutputValue> *som2dFactory = dynamic_cast<SOM2DModelFactory<TInputValue,TOutputValue> *>(*itFac); if (som2dFactory) { itk::ObjectFactoryBase::UnRegisterFactory(som2dFactory); continue; } #ifdef OTB_USE_SHARK // Autoencoder LogAutoencoderModelFactory<TInputValue,TOutputValue> *aeFactory = dynamic_cast<LogAutoencoderModelFactory<TInputValue,TOutputValue> *>(*itFac); if (aeFactory) { itk::ObjectFactoryBase::UnRegisterFactory(aeFactory); continue; } // PCA PCAModelFactory<TInputValue,TOutputValue> *pcaFactory = dynamic_cast<PCAModelFactory<TInputValue,TOutputValue> *>(*itFac); if (pcaFactory) { itk::ObjectFactoryBase::UnRegisterFactory(pcaFactory); continue; } #endif } } } // end namespace otb #endif <|endoftext|>
<commit_before>/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2016 * * * * 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 <modules/globebrowsing/globes/renderableglobe.h> #include <modules/globebrowsing/tile/tileselector.h> #include <modules/globebrowsing/rendering/layermanager.h> // open space includes #include <openspace/engine/openspaceengine.h> #include <openspace/rendering/renderengine.h> #include <openspace/util/spicemanager.h> #include <openspace/scene/scenegraphnode.h> #include <modules/debugging/rendering/debugrenderer.h> // ghoul includes #include <ghoul/misc/assert.h> #include <ghoul/misc/threadpool.h> namespace { const std::string _loggerCat = "RenderableGlobe"; // Keys for the dictionary const std::string keyFrame = "Frame"; const std::string keyRadii = "Radii"; const std::string keyInteractionDepthBelowEllipsoid = "InteractionDepthBelowEllipsoid"; const std::string keyCameraMinHeight = "CameraMinHeight"; const std::string keySegmentsPerPatch = "SegmentsPerPatch"; const std::string keyLayers = "Layers"; } namespace openspace { namespace globebrowsing { RenderableGlobe::RenderableGlobe(const ghoul::Dictionary& dictionary) : _generalProperties({ properties::BoolProperty("enabled", "Enabled", true), properties::BoolProperty("performShading", "perform shading", true), properties::BoolProperty("atmosphere", "atmosphere", false), properties::FloatProperty("lodScaleFactor", "lodScaleFactor",10.0f, 1.0f, 50.0f), properties::FloatProperty( "cameraMinHeight", "cameraMinHeight", 100.0f, 0.0f, 1000.0f) }) , _debugProperties({ properties::BoolProperty("saveOrThrowCamera", "save or throw camera", false), properties::BoolProperty("showChunkEdges", "show chunk edges", false), properties::BoolProperty("showChunkBounds", "show chunk bounds", false), properties::BoolProperty("showChunkAABB", "show chunk AABB", false), properties::BoolProperty("showHeightResolution", "show height resolution", false), properties::BoolProperty( "showHeightIntensities", "show height intensities", false), properties::BoolProperty( "performFrustumCulling", "perform frustum culling", true), properties::BoolProperty( "performHorizonCulling", "perform horizon culling", true), properties::BoolProperty( "levelByProjectedAreaElseDistance", "level by projected area (else distance)", false), properties::BoolProperty("resetTileProviders", "reset tile providers", false), properties::BoolProperty( "toggleEnabledEveryFrame", "toggle enabled every frame", false)}) { setName("RenderableGlobe"); dictionary.getValue(keyFrame, _frame); // Read the radii in to its own dictionary Vec3 radii; dictionary.getValue(keyRadii, radii); _ellipsoid = Ellipsoid(radii); setBoundingSphere(pss(_ellipsoid.averageRadius(), 0.0)); // Ghoul can't read ints from lua dictionaries... double patchSegmentsd; dictionary.getValue(keySegmentsPerPatch, patchSegmentsd); int patchSegments = patchSegmentsd; dictionary.getValue(keyInteractionDepthBelowEllipsoid, _interactionDepthBelowEllipsoid); float cameraMinHeight; dictionary.getValue(keyCameraMinHeight, cameraMinHeight); _generalProperties.cameraMinHeight.set(cameraMinHeight); // Init layer manager ghoul::Dictionary layersDictionary; if(!dictionary.getValue(keyLayers, layersDictionary)) throw ghoul::RuntimeError(keyLayers + " must be specified specified!"); _layerManager = std::make_shared<LayerManager>(layersDictionary); _chunkedLodGlobe = std::make_shared<ChunkedLodGlobe>( *this, patchSegments, _layerManager); //_pointGlobe = std::make_shared<PointGlobe>(*this); _distanceSwitch.addSwitchValue(_chunkedLodGlobe, 5e9); //_distanceSwitch.addSwitchValue(_pointGlobe, 1e12); _debugPropertyOwner.setName("Debug"); _texturePropertyOwner.setName("Textures"); addProperty(_generalProperties.isEnabled); addProperty(_generalProperties.atmosphereEnabled); addProperty(_generalProperties.performShading); addProperty(_generalProperties.lodScaleFactor); addProperty(_generalProperties.cameraMinHeight); _debugPropertyOwner.addProperty(_debugProperties.saveOrThrowCamera); _debugPropertyOwner.addProperty(_debugProperties.showChunkEdges); _debugPropertyOwner.addProperty(_debugProperties.showChunkBounds); _debugPropertyOwner.addProperty(_debugProperties.showChunkAABB); _debugPropertyOwner.addProperty(_debugProperties.showHeightResolution); _debugPropertyOwner.addProperty(_debugProperties.showHeightIntensities); _debugPropertyOwner.addProperty(_debugProperties.performFrustumCulling); _debugPropertyOwner.addProperty(_debugProperties.performHorizonCulling); _debugPropertyOwner.addProperty(_debugProperties.levelByProjectedAreaElseDistance); _debugPropertyOwner.addProperty(_debugProperties.resetTileProviders); _debugPropertyOwner.addProperty(_debugProperties.toggleEnabledEveryFrame); addPropertySubOwner(_debugPropertyOwner); addPropertySubOwner(_layerManager.get()); } RenderableGlobe::~RenderableGlobe() { } bool RenderableGlobe::initialize() { return _distanceSwitch.initialize(); } bool RenderableGlobe::deinitialize() { return _distanceSwitch.deinitialize(); } bool RenderableGlobe::isReady() const { return _distanceSwitch.isReady(); } void RenderableGlobe::render(const RenderData& data) { if (_debugProperties.toggleEnabledEveryFrame.value()) { _generalProperties.isEnabled.setValue( !_generalProperties.isEnabled.value()); } if (_generalProperties.isEnabled.value()) { if (_debugProperties.saveOrThrowCamera.value()) { _debugProperties.saveOrThrowCamera.setValue(false); if (savedCamera() == nullptr) { // save camera LDEBUG("Saving snapshot of camera!"); setSaveCamera(std::make_shared<Camera>(data.camera)); } else { // throw camera LDEBUG("Throwing away saved camera!"); setSaveCamera(nullptr); } } _distanceSwitch.render(data); } if (_savedCamera != nullptr) { DebugRenderer::ref().renderCameraFrustum(data, *_savedCamera); } } void RenderableGlobe::update(const UpdateData& data) { _time = data.time; _distanceSwitch.update(data); glm::dmat4 translation = glm::translate(glm::dmat4(1.0), data.modelTransform.translation); glm::dmat4 rotation = glm::dmat4(data.modelTransform.rotation); glm::dmat4 scaling = glm::scale(glm::dmat4(1.0), glm::dvec3(data.modelTransform.scale, data.modelTransform.scale, data.modelTransform.scale)); _cachedModelTransform = translation * rotation * scaling; _cachedInverseModelTransform = glm::inverse(_cachedModelTransform); if (_debugProperties.resetTileProviders) { _layerManager->reset(); _debugProperties.resetTileProviders = false; } _layerManager->update(); _chunkedLodGlobe->update(data); } glm::dvec3 RenderableGlobe::projectOnEllipsoid(glm::dvec3 position) { return _ellipsoid.geodeticSurfaceProjection(position); } float RenderableGlobe::getHeight(glm::dvec3 position) { float height = 0; // Get the uv coordinates to sample from Geodetic2 geodeticPosition = _ellipsoid.cartesianToGeodetic2(position); int chunkLevel = _chunkedLodGlobe->findChunkNode( geodeticPosition).getChunk().tileIndex().level; TileIndex tileIndex = TileIndex(geodeticPosition, chunkLevel); GeodeticPatch patch = GeodeticPatch(tileIndex); Geodetic2 geoDiffPatch = patch.getCorner(Quad::NORTH_EAST) - patch.getCorner(Quad::SOUTH_WEST); Geodetic2 geoDiffPoint = geodeticPosition - patch.getCorner(Quad::SOUTH_WEST); glm::vec2 patchUV = glm::vec2( geoDiffPoint.lon / geoDiffPatch.lon, geoDiffPoint.lat / geoDiffPatch.lat); // Get the tile providers for the height maps const auto& heightMapLayers = _layerManager->layerGroup(LayerManager::HeightLayers).activeLayers(); for (const auto& layer : heightMapLayers) { TileProvider* tileProvider = layer->tileProvider(); // Transform the uv coordinates to the current tile texture ChunkTile chunkTile = TileSelector::getHighestResolutionTile(tileProvider, tileIndex); const auto& tile = chunkTile.tile; const auto& uvTransform = chunkTile.uvTransform; const auto& depthTransform = tileProvider->depthTransform(); if (tile.status != Tile::Status::OK) { return 0; } glm::vec2 transformedUv = Tile::TileUvToTextureSamplePosition( uvTransform, patchUV, glm::uvec2(tile.texture->dimensions())); // Sample and do linear interpolation // (could possibly be moved as a function in ghoul texture) // Suggestion: a function in ghoul::opengl::Texture that takes uv coordinates // in range [0,1] and uses the set interpolation method and clamping. glm::uvec3 dimensions = tile.texture->dimensions(); glm::vec2 samplePos = transformedUv * glm::vec2(dimensions); glm::uvec2 samplePos00 = samplePos; samplePos00 = glm::clamp( samplePos00, glm::uvec2(0, 0), glm::uvec2(dimensions) - glm::uvec2(1)); glm::vec2 samplePosFract = samplePos - glm::vec2(samplePos00); glm::uvec2 samplePos10 = glm::min( samplePos00 + glm::uvec2(1, 0), glm::uvec2(dimensions) - glm::uvec2(1)); glm::uvec2 samplePos01 = glm::min( samplePos00 + glm::uvec2(0, 1), glm::uvec2(dimensions) - glm::uvec2(1)); glm::uvec2 samplePos11 = glm::min( samplePos00 + glm::uvec2(1, 1), glm::uvec2(dimensions) - glm::uvec2(1)); float sample00 = tile.texture->texelAsFloat(samplePos00).x; float sample10 = tile.texture->texelAsFloat(samplePos10).x; float sample01 = tile.texture->texelAsFloat(samplePos01).x; float sample11 = tile.texture->texelAsFloat(samplePos11).x; // In case the texture has NaN or no data values don't use this height map. bool anySampleIsNaN = isnan(sample00) || isnan(sample01) || isnan(sample10) || isnan(sample11); bool anySampleIsNoData = sample00 == tileProvider->noDataValueAsFloat() || sample01 == tileProvider->noDataValueAsFloat() || sample10 == tileProvider->noDataValueAsFloat() || sample11 == tileProvider->noDataValueAsFloat(); if (anySampleIsNaN || anySampleIsNoData) { continue; } float sample0 = sample00 * (1.0 - samplePosFract.x) + sample10 * samplePosFract.x; float sample1 = sample01 * (1.0 - samplePosFract.x) + sample11 * samplePosFract.x; float sample = sample0 * (1.0 - samplePosFract.y) + sample1 * samplePosFract.y; // Perform depth transform to get the value in meters height = depthTransform.depthOffset + depthTransform.depthScale * sample; } // Return the result return height; } std::shared_ptr<ChunkedLodGlobe> RenderableGlobe::chunkedLodGlobe() const{ return _chunkedLodGlobe; } const Ellipsoid& RenderableGlobe::ellipsoid() const{ return _ellipsoid; } const glm::dmat4& RenderableGlobe::modelTransform() const{ return _cachedModelTransform; } const glm::dmat4& RenderableGlobe::inverseModelTransform() const{ return _cachedInverseModelTransform; } const RenderableGlobe::DebugProperties& RenderableGlobe::debugProperties() const{ return _debugProperties; } const RenderableGlobe::GeneralProperties& RenderableGlobe::generalProperties() const{ return _generalProperties; } const std::shared_ptr<const Camera> RenderableGlobe::savedCamera() const { return _savedCamera; } double RenderableGlobe::interactionDepthBelowEllipsoid() { return _interactionDepthBelowEllipsoid; } void RenderableGlobe::setSaveCamera(std::shared_ptr<Camera> camera) { _savedCamera = camera; } } // namespace globebrowsing } // namespace openspace <commit_msg>Make distance switch distance dependent on globe radius.<commit_after>/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2016 * * * * 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 <modules/globebrowsing/globes/renderableglobe.h> #include <modules/globebrowsing/tile/tileselector.h> #include <modules/globebrowsing/rendering/layermanager.h> // open space includes #include <openspace/engine/openspaceengine.h> #include <openspace/rendering/renderengine.h> #include <openspace/util/spicemanager.h> #include <openspace/scene/scenegraphnode.h> #include <modules/debugging/rendering/debugrenderer.h> // ghoul includes #include <ghoul/misc/assert.h> #include <ghoul/misc/threadpool.h> namespace { const std::string _loggerCat = "RenderableGlobe"; // Keys for the dictionary const std::string keyFrame = "Frame"; const std::string keyRadii = "Radii"; const std::string keyInteractionDepthBelowEllipsoid = "InteractionDepthBelowEllipsoid"; const std::string keyCameraMinHeight = "CameraMinHeight"; const std::string keySegmentsPerPatch = "SegmentsPerPatch"; const std::string keyLayers = "Layers"; } namespace openspace { namespace globebrowsing { RenderableGlobe::RenderableGlobe(const ghoul::Dictionary& dictionary) : _generalProperties({ properties::BoolProperty("enabled", "Enabled", true), properties::BoolProperty("performShading", "perform shading", true), properties::BoolProperty("atmosphere", "atmosphere", false), properties::FloatProperty("lodScaleFactor", "lodScaleFactor",10.0f, 1.0f, 50.0f), properties::FloatProperty( "cameraMinHeight", "cameraMinHeight", 100.0f, 0.0f, 1000.0f) }) , _debugProperties({ properties::BoolProperty("saveOrThrowCamera", "save or throw camera", false), properties::BoolProperty("showChunkEdges", "show chunk edges", false), properties::BoolProperty("showChunkBounds", "show chunk bounds", false), properties::BoolProperty("showChunkAABB", "show chunk AABB", false), properties::BoolProperty("showHeightResolution", "show height resolution", false), properties::BoolProperty( "showHeightIntensities", "show height intensities", false), properties::BoolProperty( "performFrustumCulling", "perform frustum culling", true), properties::BoolProperty( "performHorizonCulling", "perform horizon culling", true), properties::BoolProperty( "levelByProjectedAreaElseDistance", "level by projected area (else distance)", false), properties::BoolProperty("resetTileProviders", "reset tile providers", false), properties::BoolProperty( "toggleEnabledEveryFrame", "toggle enabled every frame", false)}) { setName("RenderableGlobe"); dictionary.getValue(keyFrame, _frame); // Read the radii in to its own dictionary Vec3 radii; dictionary.getValue(keyRadii, radii); _ellipsoid = Ellipsoid(radii); setBoundingSphere(pss(_ellipsoid.averageRadius(), 0.0)); // Ghoul can't read ints from lua dictionaries... double patchSegmentsd; dictionary.getValue(keySegmentsPerPatch, patchSegmentsd); int patchSegments = patchSegmentsd; dictionary.getValue(keyInteractionDepthBelowEllipsoid, _interactionDepthBelowEllipsoid); float cameraMinHeight; dictionary.getValue(keyCameraMinHeight, cameraMinHeight); _generalProperties.cameraMinHeight.set(cameraMinHeight); // Init layer manager ghoul::Dictionary layersDictionary; if(!dictionary.getValue(keyLayers, layersDictionary)) throw ghoul::RuntimeError(keyLayers + " must be specified specified!"); _layerManager = std::make_shared<LayerManager>(layersDictionary); _chunkedLodGlobe = std::make_shared<ChunkedLodGlobe>( *this, patchSegments, _layerManager); //_pointGlobe = std::make_shared<PointGlobe>(*this); // This distance will be enough to render the globe as one pixel if the field of // view is 'fov' radians and the screen resolution is 'res' pixels. double fov = 2 * M_PI / 6; // 60 degrees int res = 2880; double distance = res * _ellipsoid.maximumRadius() / tan(fov / 2); _distanceSwitch.addSwitchValue(_chunkedLodGlobe, distance); //_distanceSwitch.addSwitchValue(_pointGlobe, 1e12); _debugPropertyOwner.setName("Debug"); _texturePropertyOwner.setName("Textures"); addProperty(_generalProperties.isEnabled); addProperty(_generalProperties.atmosphereEnabled); addProperty(_generalProperties.performShading); addProperty(_generalProperties.lodScaleFactor); addProperty(_generalProperties.cameraMinHeight); _debugPropertyOwner.addProperty(_debugProperties.saveOrThrowCamera); _debugPropertyOwner.addProperty(_debugProperties.showChunkEdges); _debugPropertyOwner.addProperty(_debugProperties.showChunkBounds); _debugPropertyOwner.addProperty(_debugProperties.showChunkAABB); _debugPropertyOwner.addProperty(_debugProperties.showHeightResolution); _debugPropertyOwner.addProperty(_debugProperties.showHeightIntensities); _debugPropertyOwner.addProperty(_debugProperties.performFrustumCulling); _debugPropertyOwner.addProperty(_debugProperties.performHorizonCulling); _debugPropertyOwner.addProperty(_debugProperties.levelByProjectedAreaElseDistance); _debugPropertyOwner.addProperty(_debugProperties.resetTileProviders); _debugPropertyOwner.addProperty(_debugProperties.toggleEnabledEveryFrame); addPropertySubOwner(_debugPropertyOwner); addPropertySubOwner(_layerManager.get()); } RenderableGlobe::~RenderableGlobe() { } bool RenderableGlobe::initialize() { return _distanceSwitch.initialize(); } bool RenderableGlobe::deinitialize() { return _distanceSwitch.deinitialize(); } bool RenderableGlobe::isReady() const { return _distanceSwitch.isReady(); } void RenderableGlobe::render(const RenderData& data) { if (_debugProperties.toggleEnabledEveryFrame.value()) { _generalProperties.isEnabled.setValue( !_generalProperties.isEnabled.value()); } if (_generalProperties.isEnabled.value()) { if (_debugProperties.saveOrThrowCamera.value()) { _debugProperties.saveOrThrowCamera.setValue(false); if (savedCamera() == nullptr) { // save camera LDEBUG("Saving snapshot of camera!"); setSaveCamera(std::make_shared<Camera>(data.camera)); } else { // throw camera LDEBUG("Throwing away saved camera!"); setSaveCamera(nullptr); } } _distanceSwitch.render(data); } if (_savedCamera != nullptr) { DebugRenderer::ref().renderCameraFrustum(data, *_savedCamera); } } void RenderableGlobe::update(const UpdateData& data) { _time = data.time; _distanceSwitch.update(data); glm::dmat4 translation = glm::translate(glm::dmat4(1.0), data.modelTransform.translation); glm::dmat4 rotation = glm::dmat4(data.modelTransform.rotation); glm::dmat4 scaling = glm::scale(glm::dmat4(1.0), glm::dvec3(data.modelTransform.scale, data.modelTransform.scale, data.modelTransform.scale)); _cachedModelTransform = translation * rotation * scaling; _cachedInverseModelTransform = glm::inverse(_cachedModelTransform); if (_debugProperties.resetTileProviders) { _layerManager->reset(); _debugProperties.resetTileProviders = false; } _layerManager->update(); _chunkedLodGlobe->update(data); } glm::dvec3 RenderableGlobe::projectOnEllipsoid(glm::dvec3 position) { return _ellipsoid.geodeticSurfaceProjection(position); } float RenderableGlobe::getHeight(glm::dvec3 position) { float height = 0; // Get the uv coordinates to sample from Geodetic2 geodeticPosition = _ellipsoid.cartesianToGeodetic2(position); int chunkLevel = _chunkedLodGlobe->findChunkNode( geodeticPosition).getChunk().tileIndex().level; TileIndex tileIndex = TileIndex(geodeticPosition, chunkLevel); GeodeticPatch patch = GeodeticPatch(tileIndex); Geodetic2 geoDiffPatch = patch.getCorner(Quad::NORTH_EAST) - patch.getCorner(Quad::SOUTH_WEST); Geodetic2 geoDiffPoint = geodeticPosition - patch.getCorner(Quad::SOUTH_WEST); glm::vec2 patchUV = glm::vec2( geoDiffPoint.lon / geoDiffPatch.lon, geoDiffPoint.lat / geoDiffPatch.lat); // Get the tile providers for the height maps const auto& heightMapLayers = _layerManager->layerGroup(LayerManager::HeightLayers).activeLayers(); for (const auto& layer : heightMapLayers) { TileProvider* tileProvider = layer->tileProvider(); // Transform the uv coordinates to the current tile texture ChunkTile chunkTile = TileSelector::getHighestResolutionTile(tileProvider, tileIndex); const auto& tile = chunkTile.tile; const auto& uvTransform = chunkTile.uvTransform; const auto& depthTransform = tileProvider->depthTransform(); if (tile.status != Tile::Status::OK) { return 0; } glm::vec2 transformedUv = Tile::TileUvToTextureSamplePosition( uvTransform, patchUV, glm::uvec2(tile.texture->dimensions())); // Sample and do linear interpolation // (could possibly be moved as a function in ghoul texture) // Suggestion: a function in ghoul::opengl::Texture that takes uv coordinates // in range [0,1] and uses the set interpolation method and clamping. glm::uvec3 dimensions = tile.texture->dimensions(); glm::vec2 samplePos = transformedUv * glm::vec2(dimensions); glm::uvec2 samplePos00 = samplePos; samplePos00 = glm::clamp( samplePos00, glm::uvec2(0, 0), glm::uvec2(dimensions) - glm::uvec2(1)); glm::vec2 samplePosFract = samplePos - glm::vec2(samplePos00); glm::uvec2 samplePos10 = glm::min( samplePos00 + glm::uvec2(1, 0), glm::uvec2(dimensions) - glm::uvec2(1)); glm::uvec2 samplePos01 = glm::min( samplePos00 + glm::uvec2(0, 1), glm::uvec2(dimensions) - glm::uvec2(1)); glm::uvec2 samplePos11 = glm::min( samplePos00 + glm::uvec2(1, 1), glm::uvec2(dimensions) - glm::uvec2(1)); float sample00 = tile.texture->texelAsFloat(samplePos00).x; float sample10 = tile.texture->texelAsFloat(samplePos10).x; float sample01 = tile.texture->texelAsFloat(samplePos01).x; float sample11 = tile.texture->texelAsFloat(samplePos11).x; // In case the texture has NaN or no data values don't use this height map. bool anySampleIsNaN = isnan(sample00) || isnan(sample01) || isnan(sample10) || isnan(sample11); bool anySampleIsNoData = sample00 == tileProvider->noDataValueAsFloat() || sample01 == tileProvider->noDataValueAsFloat() || sample10 == tileProvider->noDataValueAsFloat() || sample11 == tileProvider->noDataValueAsFloat(); if (anySampleIsNaN || anySampleIsNoData) { continue; } float sample0 = sample00 * (1.0 - samplePosFract.x) + sample10 * samplePosFract.x; float sample1 = sample01 * (1.0 - samplePosFract.x) + sample11 * samplePosFract.x; float sample = sample0 * (1.0 - samplePosFract.y) + sample1 * samplePosFract.y; // Perform depth transform to get the value in meters height = depthTransform.depthOffset + depthTransform.depthScale * sample; } // Return the result return height; } std::shared_ptr<ChunkedLodGlobe> RenderableGlobe::chunkedLodGlobe() const{ return _chunkedLodGlobe; } const Ellipsoid& RenderableGlobe::ellipsoid() const{ return _ellipsoid; } const glm::dmat4& RenderableGlobe::modelTransform() const{ return _cachedModelTransform; } const glm::dmat4& RenderableGlobe::inverseModelTransform() const{ return _cachedInverseModelTransform; } const RenderableGlobe::DebugProperties& RenderableGlobe::debugProperties() const{ return _debugProperties; } const RenderableGlobe::GeneralProperties& RenderableGlobe::generalProperties() const{ return _generalProperties; } const std::shared_ptr<const Camera> RenderableGlobe::savedCamera() const { return _savedCamera; } double RenderableGlobe::interactionDepthBelowEllipsoid() { return _interactionDepthBelowEllipsoid; } void RenderableGlobe::setSaveCamera(std::shared_ptr<Camera> camera) { _savedCamera = camera; } } // namespace globebrowsing } // namespace openspace <|endoftext|>
<commit_before>#include "Vision/RTSVisionInfo.h" #include "EngineUtils.h" #include "Net/UnrealNetwork.h" #include "RTSLog.h" #include "RTSOwnerComponent.h" #include "RTSPlayerController.h" #include "RTSPlayerState.h" #include "RTSTeamInfo.h" #include "Vision/RTSVisionComponent.h" #include "Vision/RTSVisionVolume.h" ARTSVisionInfo::ARTSVisionInfo(const FObjectInitializer& ObjectInitializer /*= FObjectInitializer::Get()*/) : Super(ObjectInitializer) { // Enable replication. SetReplicates(true); bAlwaysRelevant = true; NetUpdateFrequency = 1.0f; // Force ReceivedTeamIndex() on clients. TeamIndex = 255; PrimaryActorTick.bCanEverTick = true; } void ARTSVisionInfo::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const { Super::GetLifetimeReplicatedProps(OutLifetimeProps); DOREPLIFETIME_CONDITION(ARTSVisionInfo, TeamIndex, COND_InitialOnly); } void ARTSVisionInfo::Initialize(ARTSVisionVolume* InVisionVolume) { VisionVolume = InVisionVolume; if (!VisionVolume) { UE_LOG(LogRTS, Warning, TEXT("No vision volume found, won't update vision.")); return; } int32 SizeInTiles = VisionVolume->GetSizeInTiles(); Tiles.SetNumZeroed(SizeInTiles * SizeInTiles); for (int32 Index = 0; Index < Tiles.Num(); ++Index) { Tiles[Index] = VisionVolume->GetMinimumVisionState(); } UE_LOG(LogRTS, Log, TEXT("Set up %s with %s."), *GetName(), *VisionVolume->GetName()); } void ARTSVisionInfo::Tick(float DeltaSeconds) { Super::Tick(DeltaSeconds); if (!VisionVolume) { return; } // Reset tiles. int32 SizeInTiles = VisionVolume->GetSizeInTiles(); Tiles.SetNumZeroed(SizeInTiles * SizeInTiles); const ERTSVisionState VisionAfterVisible = FMath::Max(ERTSVisionState::VISION_Known, VisionVolume->GetMinimumVisionState()); for (int32 Index = 0; Index < Tiles.Num(); ++Index) { if (Tiles[Index] == ERTSVisionState::VISION_Visible) { Tiles[Index] = VisionAfterVisible; } } // Apply vision. for (TActorIterator<AActor> ActorIt(GetWorld()); ActorIt; ++ActorIt) { AActor* Actor = *ActorIt; // Verify vision. URTSVisionComponent* VisionComponent = Actor->FindComponentByClass<URTSVisionComponent>(); if (!VisionComponent) { continue; } // Verify team. URTSOwnerComponent* OwnerComponent = Actor->FindComponentByClass<URTSOwnerComponent>(); ARTSPlayerState* PlayerOwner = OwnerComponent->GetPlayerOwner(); if (!PlayerOwner) { continue; } if (!PlayerOwner->GetTeam()) { continue; } if (PlayerOwner->GetTeam()->GetTeamIndex() != TeamIndex) { continue; } // Convert location and sight radius to tile space. FVector ActorLocationWorld = Actor->GetActorLocation(); FIntVector ActorLocationTile = VisionVolume->WorldToTile(ActorLocationWorld); int32 ActorSightRadiusTile = FMath::FloorToInt(VisionComponent->GetSightRadius() / VisionVolume->GetTileSize()); /*UE_LOG(LogRTS, Log, TEXT("ActorLocationWorld: %s"), *ActorLocationWorld.ToString()); UE_LOG(LogRTS, Log, TEXT("ActorLocationTile: %s"), *ActorLocationTile.ToString()); UE_LOG(LogRTS, Log, TEXT("VisionComponent->SightRadius: %f"), VisionComponent->SightRadius); UE_LOG(LogRTS, Log, TEXT("VisionVolume->SizePerTile: %f"), VisionVolume->SizePerTile); UE_LOG(LogRTS, Log, TEXT("ActorSightRadiusTile: %i"), ActorSightRadiusTile);*/ // XXX VERY simple circle algorithm. for (int32 RadiusY = -ActorSightRadiusTile; RadiusY <= ActorSightRadiusTile; RadiusY++) { for (int32 RadiusX = -ActorSightRadiusTile; RadiusX <= ActorSightRadiusTile; RadiusX++) { int32 TileX = ActorLocationTile.X + RadiusX; int32 TileY = ActorLocationTile.Y + RadiusY; // Check if within circle. if (TileX >= 0 && TileY >= 0 && TileX < SizeInTiles && TileY < SizeInTiles && (RadiusX * RadiusX + RadiusY * RadiusY < ActorSightRadiusTile * ActorSightRadiusTile)) { int32 TileIndex = GetTileIndex(TileX, TileY); Tiles[TileIndex] = ERTSVisionState::VISION_Visible; //UE_LOG(LogRTS, Log, TEXT("Revealed tile (%i, %i)."), TileX, TileY); } } } } } uint8 ARTSVisionInfo::GetTeamIndex() const { return TeamIndex; } void ARTSVisionInfo::SetTeamIndex(uint8 NewTeamIndex) { TeamIndex = NewTeamIndex; NotifyPlayerVisionInfoAvailable(); } ERTSVisionState ARTSVisionInfo::GetVision(int32 X, int32 Y) const { int32 TileIndex = GetTileIndex(X, Y); return Tiles[TileIndex]; } ARTSVisionInfo* ARTSVisionInfo::GetVisionInfoForTeam(UObject* WorldContextObject, uint8 InTeamIndex) { UWorld* World = WorldContextObject->GetWorld(); for (TActorIterator<ARTSVisionInfo> It(World); It; ++It) { ARTSVisionInfo* VisionInfo = *It; if (VisionInfo->TeamIndex == InTeamIndex) { return VisionInfo; } } return nullptr; } bool ARTSVisionInfo::GetTileCoordinates(int Index, int* OutX, int* OutY) const { if (Index < 0 || Index >= Tiles.Num()) { return false; } int32 SizeInTiles = VisionVolume->GetSizeInTiles(); *OutX = Index % SizeInTiles; *OutY = Index / SizeInTiles; return true; } int32 ARTSVisionInfo::GetTileIndex(int X, int Y) const { return Y * VisionVolume->GetSizeInTiles() + X; } void ARTSVisionInfo::NotifyPlayerVisionInfoAvailable() { // Notify local player. UWorld* World = GetWorld(); if (!World) { return; } ARTSPlayerController* Player = Cast<ARTSPlayerController>(World->GetFirstPlayerController()); if (!Player) { return; } ARTSTeamInfo* Team = Player->GetTeamInfo(); if (!Team || Team->GetTeamIndex() != TeamIndex) { return; } Player->NotifyOnVisionInfoAvailable(this); } void ARTSVisionInfo::ReceivedTeamIndex() { NotifyPlayerVisionInfoAvailable(); } <commit_msg>Fix crash that occurred trying to access vision info too early.<commit_after>#include "Vision/RTSVisionInfo.h" #include "EngineUtils.h" #include "Net/UnrealNetwork.h" #include "RTSLog.h" #include "RTSOwnerComponent.h" #include "RTSPlayerController.h" #include "RTSPlayerState.h" #include "RTSTeamInfo.h" #include "Vision/RTSVisionComponent.h" #include "Vision/RTSVisionVolume.h" ARTSVisionInfo::ARTSVisionInfo(const FObjectInitializer& ObjectInitializer /*= FObjectInitializer::Get()*/) : Super(ObjectInitializer) { // Enable replication. SetReplicates(true); bAlwaysRelevant = true; NetUpdateFrequency = 1.0f; // Force ReceivedTeamIndex() on clients. TeamIndex = 255; PrimaryActorTick.bCanEverTick = true; } void ARTSVisionInfo::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const { Super::GetLifetimeReplicatedProps(OutLifetimeProps); DOREPLIFETIME_CONDITION(ARTSVisionInfo, TeamIndex, COND_InitialOnly); } void ARTSVisionInfo::Initialize(ARTSVisionVolume* InVisionVolume) { VisionVolume = InVisionVolume; if (!VisionVolume) { UE_LOG(LogRTS, Warning, TEXT("No vision volume found, won't update vision.")); return; } int32 SizeInTiles = VisionVolume->GetSizeInTiles(); Tiles.SetNumZeroed(SizeInTiles * SizeInTiles); for (int32 Index = 0; Index < Tiles.Num(); ++Index) { Tiles[Index] = VisionVolume->GetMinimumVisionState(); } UE_LOG(LogRTS, Log, TEXT("Set up %s with %s."), *GetName(), *VisionVolume->GetName()); } void ARTSVisionInfo::Tick(float DeltaSeconds) { Super::Tick(DeltaSeconds); if (!VisionVolume) { return; } // Reset tiles. int32 SizeInTiles = VisionVolume->GetSizeInTiles(); Tiles.SetNumZeroed(SizeInTiles * SizeInTiles); const ERTSVisionState VisionAfterVisible = FMath::Max(ERTSVisionState::VISION_Known, VisionVolume->GetMinimumVisionState()); for (int32 Index = 0; Index < Tiles.Num(); ++Index) { if (Tiles[Index] == ERTSVisionState::VISION_Visible) { Tiles[Index] = VisionAfterVisible; } } // Apply vision. for (TActorIterator<AActor> ActorIt(GetWorld()); ActorIt; ++ActorIt) { AActor* Actor = *ActorIt; // Verify vision. URTSVisionComponent* VisionComponent = Actor->FindComponentByClass<URTSVisionComponent>(); if (!VisionComponent) { continue; } // Verify team. URTSOwnerComponent* OwnerComponent = Actor->FindComponentByClass<URTSOwnerComponent>(); ARTSPlayerState* PlayerOwner = OwnerComponent->GetPlayerOwner(); if (!PlayerOwner) { continue; } if (!PlayerOwner->GetTeam()) { continue; } if (PlayerOwner->GetTeam()->GetTeamIndex() != TeamIndex) { continue; } // Convert location and sight radius to tile space. FVector ActorLocationWorld = Actor->GetActorLocation(); FIntVector ActorLocationTile = VisionVolume->WorldToTile(ActorLocationWorld); int32 ActorSightRadiusTile = FMath::FloorToInt(VisionComponent->GetSightRadius() / VisionVolume->GetTileSize()); /*UE_LOG(LogRTS, Log, TEXT("ActorLocationWorld: %s"), *ActorLocationWorld.ToString()); UE_LOG(LogRTS, Log, TEXT("ActorLocationTile: %s"), *ActorLocationTile.ToString()); UE_LOG(LogRTS, Log, TEXT("VisionComponent->SightRadius: %f"), VisionComponent->SightRadius); UE_LOG(LogRTS, Log, TEXT("VisionVolume->SizePerTile: %f"), VisionVolume->SizePerTile); UE_LOG(LogRTS, Log, TEXT("ActorSightRadiusTile: %i"), ActorSightRadiusTile);*/ // XXX VERY simple circle algorithm. for (int32 RadiusY = -ActorSightRadiusTile; RadiusY <= ActorSightRadiusTile; RadiusY++) { for (int32 RadiusX = -ActorSightRadiusTile; RadiusX <= ActorSightRadiusTile; RadiusX++) { int32 TileX = ActorLocationTile.X + RadiusX; int32 TileY = ActorLocationTile.Y + RadiusY; // Check if within circle. if (TileX >= 0 && TileY >= 0 && TileX < SizeInTiles && TileY < SizeInTiles && (RadiusX * RadiusX + RadiusY * RadiusY < ActorSightRadiusTile * ActorSightRadiusTile)) { int32 TileIndex = GetTileIndex(TileX, TileY); Tiles[TileIndex] = ERTSVisionState::VISION_Visible; //UE_LOG(LogRTS, Log, TEXT("Revealed tile (%i, %i)."), TileX, TileY); } } } } } uint8 ARTSVisionInfo::GetTeamIndex() const { return TeamIndex; } void ARTSVisionInfo::SetTeamIndex(uint8 NewTeamIndex) { TeamIndex = NewTeamIndex; NotifyPlayerVisionInfoAvailable(); } ERTSVisionState ARTSVisionInfo::GetVision(int32 X, int32 Y) const { if (!VisionVolume) { return ERTSVisionState::VISION_Unknown; } int32 TileIndex = GetTileIndex(X, Y); return Tiles[TileIndex]; } ARTSVisionInfo* ARTSVisionInfo::GetVisionInfoForTeam(UObject* WorldContextObject, uint8 InTeamIndex) { UWorld* World = WorldContextObject->GetWorld(); for (TActorIterator<ARTSVisionInfo> It(World); It; ++It) { ARTSVisionInfo* VisionInfo = *It; if (VisionInfo->TeamIndex == InTeamIndex) { return VisionInfo; } } return nullptr; } bool ARTSVisionInfo::GetTileCoordinates(int Index, int* OutX, int* OutY) const { if (Index < 0 || Index >= Tiles.Num()) { return false; } int32 SizeInTiles = VisionVolume->GetSizeInTiles(); *OutX = Index % SizeInTiles; *OutY = Index / SizeInTiles; return true; } int32 ARTSVisionInfo::GetTileIndex(int X, int Y) const { return Y * VisionVolume->GetSizeInTiles() + X; } void ARTSVisionInfo::NotifyPlayerVisionInfoAvailable() { // Notify local player. UWorld* World = GetWorld(); if (!World) { return; } ARTSPlayerController* Player = Cast<ARTSPlayerController>(World->GetFirstPlayerController()); if (!Player) { return; } ARTSTeamInfo* Team = Player->GetTeamInfo(); if (!Team || Team->GetTeamIndex() != TeamIndex) { return; } Player->NotifyOnVisionInfoAvailable(this); } void ARTSVisionInfo::ReceivedTeamIndex() { NotifyPlayerVisionInfoAvailable(); } <|endoftext|>
<commit_before>//============================================================================= //File Name: OperatorControl.cpp //Description: Handles driver controls for robot //Author: FRC Team 3512, Spartatroniks //============================================================================= #include <Timer.h> #include "OurRobot.hpp" #include "ButtonTracker.hpp" void OurRobot::OperatorControl() { Timer hammerClock; bool isHammerDown = false; mainCompressor.Start(); isShooting = false; isAutoAiming = false; pinLock.Set( false ); hammer.Set( false ); ButtonTracker driveStick1Buttons( 1 ); ButtonTracker driveStick2Buttons( 2 ); ButtonTracker turretStickButtons( 3 ); shooterEncoder.Start(); while ( IsEnabled() && IsOperatorControl() ) { DS_PrintOut(); // update "new" value of joystick buttons driveStick1Buttons.updateButtons(); driveStick2Buttons.updateButtons(); turretStickButtons.updateButtons(); /* ===== AIM ===== */ if ( fabs( turretStick.GetX() ) > 0.1 ) { // manual turret movement outside of -0.5 to 0.5 range, up to 0.5 speed rotateMotor.Set( -pow( turretStick.GetX() , 2.f ) ); } else if ( isAutoAiming ) { // let autoAiming take over if activated and user isn't rotating turret if( fabs( turretKinect.getPixelOffset() ) < TurretKinect::pxlDeadband ) { // deadband so shooter won't jitter rotateMotor.Set(0); } else { /* Set(x) = x / 320 * -320 <= x <= 320 therefore Set( -1 <= x / 320 <= 1 ) * smooth tracking because as the turret aims closer to the target, the motor value gets smaller */ rotateMotor.Set( static_cast<float>( turretKinect.getPixelOffset() ) / 320.f ); } } else { rotateMotor.Set( 0 ); } /* =============== */ /* ===================== AutoAim ===================== */ if ( turretStickButtons.releasedButton( 3 ) ) { isAutoAiming = !isAutoAiming; // toggles autoAim } /* =================================================== */ /* ================= Target Selection ================ */ // selecting target to left of current target if ( turretStickButtons.releasedButton( 4 ) ) { turretKinect.setTargetSelect( -1 ); turretKinect.send(); } // selecting target to right of current target if ( turretStickButtons.releasedButton( 5 ) ) { turretKinect.setTargetSelect( 1 ); turretKinect.send(); } /* =================================================== */ /* ============== Toggle Shooter Motors ============== */ // turns shooter on/off if ( turretStickButtons.releasedButton( 1 ) ) { // if released trigger isShooting = !isShooting; } if ( isShooting && turretStickButtons.releasedButton( 1 ) ) { pidControl.SetTargetDistance( 15.f ); // * 0.00328084f } if ( isShooting ) { if ( shooterIsManual ) { // let driver change shooter speed manually shooterMotorLeft.Set( -ScaleZ(turretStick) ); shooterMotorRight.Set( ScaleZ(turretStick) ); } else { // else adjust shooter voltage to match RPM //pidControl.SetTargetDistance( 25.f ); // * 0.00328084f pidControl.Update(); /*float encoderRPM = 60.f / ( 16.f * shooterEncoder.GetPeriod() ); if ( encoderRPM >= 72.0 * ScaleZ(turretStick) * 60.0 ) { shooterMotorLeft.Set( 0 ); shooterMotorRight.Set( 0 ); } else if ( encoderRPM > 2242.f ) { shooterMotorLeft.Set( -0.3f ); shooterMotorRight.Set( 0.3f ); } else { shooterMotorLeft.Set( -1 ); shooterMotorRight.Set( 1 ); }*/ } } else { shooterMotorLeft.Set( 0 ); shooterMotorRight.Set( 0 ); } // toggle manual RPM setting vs setting with encoder input if ( turretStickButtons.releasedButton( 2 ) ) { shooterIsManual = !shooterIsManual; } /* =================================================== */ /* ===== Ball Intake/Conveyor ===== */ if ( turretStick.GetRawButton( 6 ) ) { // move lift up lift.Set( Relay::kForward ); } else if ( turretStick.GetRawButton( 7 ) ) { // move lift down lift.Set( Relay::kReverse ); } else { lift.Set( Relay::kOff ); // turn off lift } /* ================================ */ /* ===== Hammer ===== * There are two parts to switching the state of this mechanism. * * 1) The first device is moved into position and out of the other one's way. * 2) The second device is moved after a delay to avoid a mechanical lock-up. * * When the trigger is released, the state variable switches and a timer is started. * The first device is moved into position immediately. * * After the delay for the respective state change has passed, * the second device is moved into position. This is done * to make sure that there are no mechanical lock-ups caused * by the devices being triggered at the same time. It may * damage them. * * After the second device is told to move, the timers are stopped and * reset since they aren't needed anymore. * * Note: We don't know for sure if either device moved out of the way by * the time the second device needs to be moved. It's just * assumed that the delay gave the first device enough time * to do so. */ // ===== PART 1 if ( driveStick2Buttons.releasedButton( 1 ) ) { // if released trigger // start process of switching position of hammer isHammerDown = !isHammerDown; hammerClock.Start(); // used to track delay between actions // move the first device immediately if( isHammerDown ) { hammer.Set( true ); // if hammer should be going down, deploy it immediately } else { pinLock.Set( false ); // if hammer is coming back up, unlock solenoid immediately } } // ============ // ===== PART 2 // move second device after delay has passed if ( isHammerDown && hammerClock.Get() > 0 ) { // if hammer is down and delay passed, deploy locks pinLock.Set( true ); // stop timer because the device has finished switching states hammerClock.Stop(); hammerClock.Reset(); } if ( !isHammerDown && hammerClock.Get() > 0.2 ) { // if hammer is coming back up after delay passed, locks are disengaged so bring hammer back up hammer.Set( false ); // stop timer because the device has finished switching states hammerClock.Stop(); hammerClock.Reset(); } // ============ /* ================== */ /* ===== Shifter ===== */ if ( driveStick1Buttons.releasedButton( 1 ) ) { // if released trigger shifter.Set( !shifter.Get() ); // shifts between low and high gear } /* =================== */ // move robot based on two joystick inputs mainDrive.ArcadeDrive( ScaleZ( driveStick1 ) * driveStick1.GetY() , ScaleZ( driveStick2 ) * driveStick2.GetX() , false ); Wait( 0.1 ); } shooterEncoder.Stop(); } <commit_msg>Moved comments in OperatorControl.cpp to match location of others in an if-else structure<commit_after>//============================================================================= //File Name: OperatorControl.cpp //Description: Handles driver controls for robot //Author: FRC Team 3512, Spartatroniks //============================================================================= #include <Timer.h> #include "OurRobot.hpp" #include "ButtonTracker.hpp" void OurRobot::OperatorControl() { Timer hammerClock; bool isHammerDown = false; mainCompressor.Start(); isShooting = false; isAutoAiming = false; pinLock.Set( false ); hammer.Set( false ); ButtonTracker driveStick1Buttons( 1 ); ButtonTracker driveStick2Buttons( 2 ); ButtonTracker turretStickButtons( 3 ); shooterEncoder.Start(); while ( IsEnabled() && IsOperatorControl() ) { DS_PrintOut(); // update "new" value of joystick buttons driveStick1Buttons.updateButtons(); driveStick2Buttons.updateButtons(); turretStickButtons.updateButtons(); /* ===== AIM ===== */ if ( fabs( turretStick.GetX() ) > 0.1 ) { // manual turret movement outside of -0.5 to 0.5 range, up to 0.5 speed rotateMotor.Set( -pow( turretStick.GetX() , 2.f ) ); } else if ( isAutoAiming ) { // let autoAiming take over if activated and user isn't rotating turret if( fabs( turretKinect.getPixelOffset() ) < TurretKinect::pxlDeadband ) { // deadband so shooter won't jitter rotateMotor.Set(0); } else { /* Set(x) = x / 320 * -320 <= x <= 320 therefore Set( -1 <= x / 320 <= 1 ) * smooth tracking because as the turret aims closer to the target, the motor value gets smaller */ rotateMotor.Set( static_cast<float>( turretKinect.getPixelOffset() ) / 320.f ); } } else { rotateMotor.Set( 0 ); } /* =============== */ /* ===================== AutoAim ===================== */ if ( turretStickButtons.releasedButton( 3 ) ) { isAutoAiming = !isAutoAiming; // toggles autoAim } /* =================================================== */ /* ================= Target Selection ================ */ // selecting target to left of current target if ( turretStickButtons.releasedButton( 4 ) ) { turretKinect.setTargetSelect( -1 ); turretKinect.send(); } // selecting target to right of current target if ( turretStickButtons.releasedButton( 5 ) ) { turretKinect.setTargetSelect( 1 ); turretKinect.send(); } /* =================================================== */ /* ============== Toggle Shooter Motors ============== */ // turns shooter on/off if ( turretStickButtons.releasedButton( 1 ) ) { // if released trigger isShooting = !isShooting; } if ( isShooting && turretStickButtons.releasedButton( 1 ) ) { pidControl.SetTargetDistance( 15.f ); // * 0.00328084f } if ( isShooting ) { if ( shooterIsManual ) { // let driver change shooter speed manually shooterMotorLeft.Set( -ScaleZ(turretStick) ); shooterMotorRight.Set( ScaleZ(turretStick) ); } else { // else adjust shooter voltage to match RPM //pidControl.SetTargetDistance( 25.f ); // * 0.00328084f pidControl.Update(); /*float encoderRPM = 60.f / ( 16.f * shooterEncoder.GetPeriod() ); if ( encoderRPM >= 72.0 * ScaleZ(turretStick) * 60.0 ) { shooterMotorLeft.Set( 0 ); shooterMotorRight.Set( 0 ); } else if ( encoderRPM > 2242.f ) { shooterMotorLeft.Set( -0.3f ); shooterMotorRight.Set( 0.3f ); } else { shooterMotorLeft.Set( -1 ); shooterMotorRight.Set( 1 ); }*/ } } else { shooterMotorLeft.Set( 0 ); shooterMotorRight.Set( 0 ); } // toggle manual RPM setting vs setting with encoder input if ( turretStickButtons.releasedButton( 2 ) ) { shooterIsManual = !shooterIsManual; } /* =================================================== */ /* ===== Ball Intake/Conveyor ===== */ if ( turretStick.GetRawButton( 6 ) ) { lift.Set( Relay::kForward ); // move lift up } else if ( turretStick.GetRawButton( 7 ) ) { lift.Set( Relay::kReverse ); // move lift down } else { lift.Set( Relay::kOff ); // turn off lift } /* ================================ */ /* ===== Hammer ===== * There are two parts to switching the state of this mechanism. * * 1) The first device is moved into position and out of the other one's way. * 2) The second device is moved after a delay to avoid a mechanical lock-up. * * When the trigger is released, the state variable switches and a timer is started. * The first device is moved into position immediately. * * After the delay for the respective state change has passed, * the second device is moved into position. This is done * to make sure that there are no mechanical lock-ups caused * by the devices being triggered at the same time. It may * damage them. * * After the second device is told to move, the timers are stopped and * reset since they aren't needed anymore. * * Note: We don't know for sure if either device moved out of the way by * the time the second device needs to be moved. It's just * assumed that the delay gave the first device enough time * to do so. */ // ===== PART 1 if ( driveStick2Buttons.releasedButton( 1 ) ) { // if released trigger // start process of switching position of hammer isHammerDown = !isHammerDown; hammerClock.Start(); // used to track delay between actions // move the first device immediately if( isHammerDown ) { hammer.Set( true ); // if hammer should be going down, deploy it immediately } else { pinLock.Set( false ); // if hammer is coming back up, unlock solenoid immediately } } // ============ // ===== PART 2 // move second device after delay has passed if ( isHammerDown && hammerClock.Get() > 0 ) { // if hammer is down and delay passed, deploy locks pinLock.Set( true ); // stop timer because the device has finished switching states hammerClock.Stop(); hammerClock.Reset(); } if ( !isHammerDown && hammerClock.Get() > 0.2 ) { // if hammer is coming back up after delay passed, locks are disengaged so bring hammer back up hammer.Set( false ); // stop timer because the device has finished switching states hammerClock.Stop(); hammerClock.Reset(); } // ============ /* ================== */ /* ===== Shifter ===== */ if ( driveStick1Buttons.releasedButton( 1 ) ) { // if released trigger shifter.Set( !shifter.Get() ); // shifts between low and high gear } /* =================== */ // move robot based on two joystick inputs mainDrive.ArcadeDrive( ScaleZ( driveStick1 ) * driveStick1.GetY() , ScaleZ( driveStick2 ) * driveStick2.GetX() , false ); Wait( 0.1 ); } shooterEncoder.Stop(); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: xmlsignaturehelper.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: rt $ $Date: 2004-11-26 14:50:21 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _XMLSECURITY_XMLSIGNATUREHELPER_HXX #define _XMLSECURITY_XMLSIGNATUREHELPER_HXX #ifndef _STLP_VECTOR #include <vector> #endif #include <tools/link.hxx> #include <rtl/ustring.hxx> #include <xmlsecurity/sigstruct.hxx> #include <com/sun/star/xml/sax/XDocumentHandler.hpp> #include <com/sun/star/xml/crypto/XUriBinding.hpp> #include <com/sun/star/xml/crypto/XSEInitializer.hpp> #include <com/sun/star/xml/crypto/sax/XSecurityController.hpp> #include <com/sun/star/xml/crypto/sax/XSignatureCreationResultListener.hpp> #include <com/sun/star/xml/crypto/sax/XSignatureVerifyResultListener.hpp> class XSecController; class Date; class Time; namespace com { namespace sun { namespace star { namespace lang { class XMultiServiceFactory; } namespace io { class XOutputStream; class XInputStream; } namespace embed { class XStorage; } }}} struct XMLSignatureCreationResult { sal_Int32 nSecurityId; com::sun::star::xml::crypto::SecurityOperationStatus nSignatureCreationResult; XMLSignatureCreationResult( sal_Int32 nId, com::sun::star::xml::crypto::SecurityOperationStatus nResult ) { nSecurityId = nId; nSignatureCreationResult = nResult; } }; struct XMLSignatureVerifyResult { sal_Int32 nSecurityId; com::sun::star::xml::crypto::SecurityOperationStatus nSignatureVerifyResult; XMLSignatureVerifyResult( sal_Int32 nId, com::sun::star::xml::crypto::SecurityOperationStatus nResult ) { nSecurityId = nId; nSignatureVerifyResult = nResult; } }; typedef ::std::vector<XMLSignatureCreationResult> XMLSignatureCreationResults; typedef ::std::vector<XMLSignatureVerifyResult> XMLSignatureVerifyResults; /********************************************************** XMLSignatureHelper Helper class for the XML Security framework Functions: 1. help to create a security context; 2. help to listen signature creation result; 3. help to listen signature verify result; 4. help to indicate which signature to verify. **********************************************************/ class XMLSignatureHelper { private: ::com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory> mxMSF; ::com::sun::star::uno::Reference< com::sun::star::xml::crypto::sax::XSecurityController > mxSecurityController; ::com::sun::star::uno::Reference< com::sun::star::xml::crypto::XUriBinding > mxUriBinding; ::com::sun::star::uno::Reference< com::sun::star::xml::crypto::XSEInitializer > mxSEInitializer; ::com::sun::star::uno::Reference< com::sun::star::xml::crypto::XXMLSecurityContext > mxSecurityContext; XMLSignatureCreationResults maCreationResults; XMLSignatureVerifyResults maVerifyResults; XSecController* mpXSecController; bool mbError; Link maStartVerifySignatureHdl; private: void ImplCreateSEInitializer(); DECL_LINK( SignatureCreationResultListener, XMLSignatureCreationResult*); DECL_LINK( SignatureVerifyResultListener, XMLSignatureVerifyResult* ); DECL_LINK( StartVerifySignatureElement, const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >* ); // Not allowed: XMLSignatureHelper(const XMLSignatureHelper&); public: XMLSignatureHelper(const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory>& rxMSF ); ~XMLSignatureHelper(); // Initialize the security context with given crypto token. // Empty string means default crypto token. // Returns true for success. bool Init( const rtl::OUString& rTokenPath ); // Set UriBinding to create input streams to open files. // Default implementation is capable to open files from disk. void SetUriBinding( com::sun::star::uno::Reference< com::sun::star::xml::crypto::XUriBinding >& rxUriBinding ); com::sun::star::uno::Reference< com::sun::star::xml::crypto::XUriBinding > GetUriBinding() const; // Set the storage which should be used by the default UriBinding // Must be set before StatrtMission(). void SetStorage( const com::sun::star::uno::Reference < com::sun::star::embed::XStorage >& rxStorage ); // Argument for the Link is a uno::Reference< xml::sax::XAttributeList >* // Return 1 to verify, 0 to skip. // Default handler will verify all. void SetStartVerifySignatureHdl( const Link& rLink ); // Get the security environment ::com::sun::star::uno::Reference< ::com::sun::star::xml::crypto::XSecurityEnvironment > GetSecurityEnvironment(); // After signing/veryfieng, get information about signatures SignatureInformation GetSignatureInformation( sal_Int32 nSecurityId ) const; SignatureInformations GetSignatureInformations() const; // See XSecController for documentation void StartMission(); void EndMission(); sal_Int32 GetNewSecurityId(); void SetX509Certificate( sal_Int32 nSecurityId, const rtl::OUString& ouX509IssuerName, const rtl::OUString& ouX509SerialNumber); void SetDateTime( sal_Int32 nSecurityId, const Date& rDate, const Time& rTime ); void AddForSigning( sal_Int32 securityId, const rtl::OUString& uri, const rtl::OUString& objectURL, sal_Bool bBinary ); bool CreateAndWriteSignature( const com::sun::star::uno::Reference< com::sun::star::xml::sax::XDocumentHandler >& xDocumentHandler ); bool CreateAndWriteSignature( const com::sun::star::uno::Reference< com::sun::star::io::XOutputStream >& xOutputStream ); bool ReadAndVerifySignature( const com::sun::star::uno::Reference< com::sun::star::io::XInputStream >& xInputStream ); // MT: ??? I think only for adding/removing, not for new signatures... // MM: Yes, but if you want to insert a new signature into an existing signature file, those function // will be very usefull, see Mission 3 in the new "multisigdemo" program :-) ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XDocumentHandler> CreateDocumentHandlerWithHeader( const com::sun::star::uno::Reference< com::sun::star::io::XOutputStream >& xOutputStream ); void CloseDocumentHandler( const ::com::sun::star::uno::Reference< com::sun::star::xml::sax::XDocumentHandler>& xDocumentHandler ); void ExportSignature( const com::sun::star::uno::Reference< com::sun::star::xml::sax::XDocumentHandler >& xDocumentHandler, const SignatureInformation& signatureInfo ); }; #endif // _XMLSECURITY_XMLSIGNATUREHELPER_HXX <commit_msg>INTEGRATION: CWS xmlsec08 (1.7.10); FILE MERGED 2005/01/20 03:34:20 mmi 1.7.10.1: smartcard support Issue number: 38448 Submitted by: Reviewed by:<commit_after>/************************************************************************* * * $RCSfile: xmlsignaturehelper.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: vg $ $Date: 2005-03-10 18:03:02 $ * * 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 _XMLSECURITY_XMLSIGNATUREHELPER_HXX #define _XMLSECURITY_XMLSIGNATUREHELPER_HXX #ifndef _STLP_VECTOR #include <vector> #endif #include <tools/link.hxx> #include <rtl/ustring.hxx> #include <xmlsecurity/sigstruct.hxx> #include <com/sun/star/xml/sax/XDocumentHandler.hpp> #include <com/sun/star/xml/crypto/XUriBinding.hpp> #include <com/sun/star/xml/crypto/XSEInitializer.hpp> #include <com/sun/star/xml/crypto/sax/XSecurityController.hpp> #include <com/sun/star/xml/crypto/sax/XSignatureCreationResultListener.hpp> #include <com/sun/star/xml/crypto/sax/XSignatureVerifyResultListener.hpp> class XSecController; class Date; class Time; namespace com { namespace sun { namespace star { namespace lang { class XMultiServiceFactory; } namespace io { class XOutputStream; class XInputStream; } namespace embed { class XStorage; } }}} struct XMLSignatureCreationResult { sal_Int32 nSecurityId; com::sun::star::xml::crypto::SecurityOperationStatus nSignatureCreationResult; XMLSignatureCreationResult( sal_Int32 nId, com::sun::star::xml::crypto::SecurityOperationStatus nResult ) { nSecurityId = nId; nSignatureCreationResult = nResult; } }; struct XMLSignatureVerifyResult { sal_Int32 nSecurityId; com::sun::star::xml::crypto::SecurityOperationStatus nSignatureVerifyResult; XMLSignatureVerifyResult( sal_Int32 nId, com::sun::star::xml::crypto::SecurityOperationStatus nResult ) { nSecurityId = nId; nSignatureVerifyResult = nResult; } }; typedef ::std::vector<XMLSignatureCreationResult> XMLSignatureCreationResults; typedef ::std::vector<XMLSignatureVerifyResult> XMLSignatureVerifyResults; /********************************************************** XMLSignatureHelper Helper class for the XML Security framework Functions: 1. help to create a security context; 2. help to listen signature creation result; 3. help to listen signature verify result; 4. help to indicate which signature to verify. **********************************************************/ class XMLSignatureHelper { private: ::com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory> mxMSF; ::com::sun::star::uno::Reference< com::sun::star::xml::crypto::sax::XSecurityController > mxSecurityController; ::com::sun::star::uno::Reference< com::sun::star::xml::crypto::XUriBinding > mxUriBinding; ::com::sun::star::uno::Reference< com::sun::star::xml::crypto::XSEInitializer > mxSEInitializer; ::com::sun::star::uno::Reference< com::sun::star::xml::crypto::XXMLSecurityContext > mxSecurityContext; XMLSignatureCreationResults maCreationResults; XMLSignatureVerifyResults maVerifyResults; XSecController* mpXSecController; bool mbError; Link maStartVerifySignatureHdl; private: void ImplCreateSEInitializer(); DECL_LINK( SignatureCreationResultListener, XMLSignatureCreationResult*); DECL_LINK( SignatureVerifyResultListener, XMLSignatureVerifyResult* ); DECL_LINK( StartVerifySignatureElement, const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList >* ); // Not allowed: XMLSignatureHelper(const XMLSignatureHelper&); public: XMLSignatureHelper(const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory>& rxMSF ); ~XMLSignatureHelper(); // Initialize the security context with given crypto token. // Empty string means default crypto token. // Returns true for success. bool Init( const rtl::OUString& rTokenPath ); // Set UriBinding to create input streams to open files. // Default implementation is capable to open files from disk. void SetUriBinding( com::sun::star::uno::Reference< com::sun::star::xml::crypto::XUriBinding >& rxUriBinding ); com::sun::star::uno::Reference< com::sun::star::xml::crypto::XUriBinding > GetUriBinding() const; // Set the storage which should be used by the default UriBinding // Must be set before StatrtMission(). void SetStorage( const com::sun::star::uno::Reference < com::sun::star::embed::XStorage >& rxStorage ); // Argument for the Link is a uno::Reference< xml::sax::XAttributeList >* // Return 1 to verify, 0 to skip. // Default handler will verify all. void SetStartVerifySignatureHdl( const Link& rLink ); // Get the security environment ::com::sun::star::uno::Reference< ::com::sun::star::xml::crypto::XSecurityEnvironment > GetSecurityEnvironment(); ::com::sun::star::uno::Reference< ::com::sun::star::xml::crypto::XSecurityEnvironment > GetSecurityEnvironmentByIndex(sal_Int32 nId); sal_Int32 GetSecurityEnvironmentNumber(); // After signing/veryfieng, get information about signatures SignatureInformation GetSignatureInformation( sal_Int32 nSecurityId ) const; SignatureInformations GetSignatureInformations() const; // See XSecController for documentation void StartMission(); void EndMission(); sal_Int32 GetNewSecurityId(); void SetX509Certificate( sal_Int32 nSecurityId, const rtl::OUString& ouX509IssuerName, const rtl::OUString& ouX509SerialNumber); void SetX509Certificate( sal_Int32 nSecurityId, sal_Int32 nSecurityEnvironmentIndex, const rtl::OUString& ouX509IssuerName, const rtl::OUString& ouX509SerialNumber); void SetDateTime( sal_Int32 nSecurityId, const Date& rDate, const Time& rTime ); void AddForSigning( sal_Int32 securityId, const rtl::OUString& uri, const rtl::OUString& objectURL, sal_Bool bBinary ); bool CreateAndWriteSignature( const com::sun::star::uno::Reference< com::sun::star::xml::sax::XDocumentHandler >& xDocumentHandler ); bool CreateAndWriteSignature( const com::sun::star::uno::Reference< com::sun::star::io::XOutputStream >& xOutputStream ); bool ReadAndVerifySignature( const com::sun::star::uno::Reference< com::sun::star::io::XInputStream >& xInputStream ); // MT: ??? I think only for adding/removing, not for new signatures... // MM: Yes, but if you want to insert a new signature into an existing signature file, those function // will be very usefull, see Mission 3 in the new "multisigdemo" program :-) ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XDocumentHandler> CreateDocumentHandlerWithHeader( const com::sun::star::uno::Reference< com::sun::star::io::XOutputStream >& xOutputStream ); void CloseDocumentHandler( const ::com::sun::star::uno::Reference< com::sun::star::xml::sax::XDocumentHandler>& xDocumentHandler ); void ExportSignature( const com::sun::star::uno::Reference< com::sun::star::xml::sax::XDocumentHandler >& xDocumentHandler, const SignatureInformation& signatureInfo ); }; #endif // _XMLSECURITY_XMLSIGNATUREHELPER_HXX <|endoftext|>
<commit_before>/* * Copyright (c) 2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Nathan Binkert */ #include <string> #include "arch/arm/isa_traits.hh" #include "arch/arm/stacktrace.hh" #include "arch/arm/vtophys.hh" #include "base/bitfield.hh" #include "base/trace.hh" #include "cpu/base.hh" #include "cpu/thread_context.hh" #include "mem/fs_translating_port_proxy.hh" #include "sim/system.hh" using namespace std; namespace ArmISA { ProcessInfo::ProcessInfo(ThreadContext *_tc) : tc(_tc) { Addr addr = 0; FSTranslatingPortProxy &vp = tc->getVirtProxy(); if (!tc->getSystemPtr()->kernelSymtab->findAddress("thread_info_size", addr)) panic("thread info not compiled into kernel\n"); thread_info_size = vp.readGtoH<int32_t>(addr); if (!tc->getSystemPtr()->kernelSymtab->findAddress("task_struct_size", addr)) panic("thread info not compiled into kernel\n"); task_struct_size = vp.readGtoH<int32_t>(addr); if (!tc->getSystemPtr()->kernelSymtab->findAddress("thread_info_task", addr)) panic("thread info not compiled into kernel\n"); task_off = vp.readGtoH<int32_t>(addr); if (!tc->getSystemPtr()->kernelSymtab->findAddress("task_struct_pid", addr)) panic("thread info not compiled into kernel\n"); pid_off = vp.readGtoH<int32_t>(addr); if (!tc->getSystemPtr()->kernelSymtab->findAddress("task_struct_comm", addr)) panic("thread info not compiled into kernel\n"); name_off = vp.readGtoH<int32_t>(addr); } Addr ProcessInfo::task(Addr ksp) const { return 0; } int ProcessInfo::pid(Addr ksp) const { return -1; } string ProcessInfo::name(Addr ksp) const { return "Implement me"; } StackTrace::StackTrace() : tc(0), stack(64) { } StackTrace::StackTrace(ThreadContext *_tc, StaticInstPtr inst) : tc(0), stack(64) { trace(_tc, inst); } StackTrace::~StackTrace() { } void StackTrace::trace(ThreadContext *_tc, bool is_call) { } bool StackTrace::isEntry(Addr addr) { return false; } bool StackTrace::decodeStack(MachInst inst, int &disp) { return false; } bool StackTrace::decodeSave(MachInst inst, int &reg, int &disp) { return false; } /* * Decode the function prologue for the function we're in, and note * which registers are stored where, and how large the stack frame is. */ bool StackTrace::decodePrologue(Addr sp, Addr callpc, Addr func, int &size, Addr &ra) { return false; } #if TRACING_ON void StackTrace::dump() { DPRINTFN("------ Stack ------\n"); DPRINTFN(" Not implemented\n"); } #endif } <commit_msg>ARM: implement the ProcessInfo methods<commit_after>/* * Copyright (c) 2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Nathan Binkert */ #include <string> #include "arch/arm/isa_traits.hh" #include "arch/arm/stacktrace.hh" #include "arch/arm/vtophys.hh" #include "base/bitfield.hh" #include "base/trace.hh" #include "cpu/base.hh" #include "cpu/thread_context.hh" #include "mem/fs_translating_port_proxy.hh" #include "sim/system.hh" using namespace std; namespace ArmISA { ProcessInfo::ProcessInfo(ThreadContext *_tc) : tc(_tc) { Addr addr = 0; FSTranslatingPortProxy &vp = tc->getVirtProxy(); if (!tc->getSystemPtr()->kernelSymtab->findAddress("thread_info_size", addr)) panic("thread info not compiled into kernel\n"); thread_info_size = vp.readGtoH<int32_t>(addr); if (!tc->getSystemPtr()->kernelSymtab->findAddress("task_struct_size", addr)) panic("thread info not compiled into kernel\n"); task_struct_size = vp.readGtoH<int32_t>(addr); if (!tc->getSystemPtr()->kernelSymtab->findAddress("thread_info_task", addr)) panic("thread info not compiled into kernel\n"); task_off = vp.readGtoH<int32_t>(addr); if (!tc->getSystemPtr()->kernelSymtab->findAddress("task_struct_pid", addr)) panic("thread info not compiled into kernel\n"); pid_off = vp.readGtoH<int32_t>(addr); if (!tc->getSystemPtr()->kernelSymtab->findAddress("task_struct_comm", addr)) panic("thread info not compiled into kernel\n"); name_off = vp.readGtoH<int32_t>(addr); } Addr ProcessInfo::task(Addr ksp) const { Addr base = ksp & ~0x1fff; if (base == ULL(0xffffffffc0000000)) return 0; Addr tsk; FSTranslatingPortProxy &vp = tc->getVirtProxy(); tsk = vp.readGtoH<Addr>(base + task_off); return tsk; } int ProcessInfo::pid(Addr ksp) const { Addr task = this->task(ksp); if (!task) return -1; uint16_t pd; FSTranslatingPortProxy &vp = tc->getVirtProxy(); pd = vp.readGtoH<uint16_t>(task + pid_off); return pd; } string ProcessInfo::name(Addr ksp) const { Addr task = this->task(ksp); if (!task) return "unknown"; char comm[256]; CopyStringOut(tc, comm, task + name_off, sizeof(comm)); if (!comm[0]) return "startup"; return comm; } StackTrace::StackTrace() : tc(0), stack(64) { } StackTrace::StackTrace(ThreadContext *_tc, StaticInstPtr inst) : tc(0), stack(64) { trace(_tc, inst); } StackTrace::~StackTrace() { } void StackTrace::trace(ThreadContext *_tc, bool is_call) { } bool StackTrace::isEntry(Addr addr) { return false; } bool StackTrace::decodeStack(MachInst inst, int &disp) { return false; } bool StackTrace::decodeSave(MachInst inst, int &reg, int &disp) { return false; } /* * Decode the function prologue for the function we're in, and note * which registers are stored where, and how large the stack frame is. */ bool StackTrace::decodePrologue(Addr sp, Addr callpc, Addr func, int &size, Addr &ra) { return false; } #if TRACING_ON void StackTrace::dump() { DPRINTFN("------ Stack ------\n"); DPRINTFN(" Not implemented\n"); } #endif } <|endoftext|>
<commit_before>#ifndef LOGGER_HPP #define LOGGER_HPP /* Defines the Logger class * which logs the contents * of the program to disk. */ #include <fstream> #include <string> #include "./Exceptions.hpp" class Logger { private: std::string logs; std::string logfile; std::fstream logstream; enum LOG_STATES { APP = 0, NON_APP }; public: Logger() { try { logs = " "; logfile = " "; } catch(const std::exception& e) { std::cerr<<"Oops...caught an error!!!\n" <<e.what()<<std::endl; } Logger(std::string Logfile) { try { logs = " "; logfile = Logfile; } catch(const std::exception& e) { std::cerr<<"Oops...caught an error!!!\n" <<e.what()<<std::endl; } } Logger(const Logger& lvalue) { try { logs = lvalue.logs; logfile = lvalue.logfile; } catch(const std::exception& e) { std::cerr<<"Oops...caught an error!!!\n" <<e.what()<<std::endl; } } Logger(Logger&& rvalue) { try { logs = lvalue.logs; logfile = lvalue.logfile; lvalue.logs = nullptr; lvalue.logfile = nullptr; } catch(const std::exception& e) { std::cerr<<"Oops...caught an error!!!\n" <<e.what()<<std::endl; } } virtual Logger& operator=(const Logger& lvalue) { try { logs = lvalue.logs; logfile = lvalue.logfile; return *this; } catch(const std::exception& e) { std::cerr<<"Oops...caught an error!!!\n" <<e.what()<<std::endl; } } virtual void getLogs(const std::string& msg) { logs = msg; logs += "\n"; } virtual void getLogs(const char* msg) { logs.assign(msg); logs += "\n"; } void Log(unsigned in state = 0) { if(state!=0 || state!=1) throw Exception("Logger Error: Wrong Log State...\n" + "Log State = " + std::string::to_string(state) + ".\n") if(state == APP) logstream.open(logfile.c_str(),std::ios::out | std::ios::app); else if(state == NON_APP) logstream.open(logfile.c_str(),std::ios::out); logstream<<logs<<std::endl; logstream.flush(); logstream.close(); } void Log(const std::string& msg,unsigned int state=0) { if(state!=0 || state!=1) throw Exception("Logger Error: Wrong Log State...\n" + "Log State = " + std::string::to_string(state) + ".\n") if(state == APP) logstream.open(logfile.c_str(),std::ios::out | std::ios::app); else if(state == NON_APP) logstream.open(logfile.c_str(),std::ios::out); logstream<<msg<<std::endl; logstream.flush(); logstream.close(); } void Log(const char* msg,unsigned int state=0) { if(state!=0 || state!=1) throw Exception("Logger Error: Wrong Log State...\n" + "Log State = " + std::string::to_string(state) + ".\n") if(state == APP) logstream.open(logfile.c_str(),std::ios::out | std::ios::app); else if(state == NON_APP) logstream.open(logfile.c_str(),std::ios::out); logstream<<&msg<<std::endl; logstream.flush(); logstream.close(); } }; <commit_msg>Added some more changes to the Logger class.<commit_after>#ifndef LOGGER_HPP #define LOGGER_HPP /* Defines the Logger class * which logs the contents * of the program to disk. */ #include <fstream> #include <string> #include "./Exceptions.hpp" class Logger { private: std::string logs; std::string logfile; std::fstream logstream; enum LOG_STATES { APP = 0, NON_APP }; public: Logger() { try { logs = " "; logfile = " "; } catch(const std::exception& e) { std::cerr<<"Oops...caught an error!!!\n" <<e.what()<<std::endl; } Logger(std::string Logfile) { try { logs = " "; logfile = Logfile; } catch(const std::exception& e) { std::cerr<<"Oops...caught an error!!!\n" <<e.what()<<std::endl; } } Logger(const Logger& lvalue) { try { logs = lvalue.logs; logfile = lvalue.logfile; } catch(const std::exception& e) { std::cerr<<"Oops...caught an error!!!\n" <<e.what()<<std::endl; } } Logger(Logger&& rvalue) { try { logs = lvalue.logs; logfile = lvalue.logfile; lvalue.logs = nullptr; lvalue.logfile = nullptr; } catch(const std::exception& e) { std::cerr<<"Oops...caught an error!!!\n" <<e.what()<<std::endl; } } virtual Logger& operator=(const Logger& lvalue) { try { logs = lvalue.logs; logfile = lvalue.logfile; return *this; } catch(const std::exception& e) { std::cerr<<"Oops...caught an error!!!\n" <<e.what()<<std::endl; } } virtual void getLogs(const std::string& msg) { logs = msg; logs += "\n"; } virtual void getLogs(const char* msg) { logs.assign(msg); logs += "\n"; } void Log(unsigned in state = 0) { if(state!=0 && state!=1) throw Exception("Logger Error: Wrong Log State...\n" + "Log State = " + std::string::to_string(state) + ".\n") if(state == APP) logstream.open(logfile.c_str(),std::ios::out | std::ios::app); else if(state == NON_APP) logstream.open(logfile.c_str(),std::ios::out); logstream<<logs<<std::endl; logstream.flush(); logstream.close(); } void Log(const std::string& msg,unsigned int state=0) { if(state!=0 && state!=1) throw Exception("Logger Error: Wrong Log State...\n" + "Log State = " + std::string::to_string(state) + ".\n") if(state == APP) logstream.open(logfile.c_str(),std::ios::out | std::ios::app); else if(state == NON_APP) logstream.open(logfile.c_str(),std::ios::out); logstream<<msg<<std::endl; logstream.flush(); logstream.close(); } void Log(const char* msg,unsigned int state=0) { if(state!=0 && state!=1) throw Exception("Logger Error: Wrong Log State...\n" + "Log State = " + std::string::to_string(state) + ".\n") if(state == APP) logstream.open(logfile.c_str(),std::ios::out | std::ios::app); else if(state == NON_APP) logstream.open(logfile.c_str(),std::ios::out); logstream<<&msg<<std::endl; logstream.flush(); logstream.close(); } }; <|endoftext|>
<commit_before>/* * @file decision_stump_test.cpp * @author Udit Saxena * * Test for Decision Stump */ #include <mlpack/core.hpp> #include <mlpack/methods/decision_stump/decision_stump.hpp> #include <boost/test/unit_test.hpp> #include "old_boost_test_definitions.hpp" using namespace mlpack; using namespace mlpack::decision_stump; using namespace arma; BOOST_AUTO_TEST_SUITE(DSTEST); /* This tests handles the case wherein only one class exists in the input labels. It checks whether the only class supplied was the only class predicted. */ BOOST_AUTO_TEST_CASE(OneClass) { size_t numClasses = 2; size_t inpBucketSize = 6; mat trainingData; trainingData << 2.4 << 3.8 << 3.8 << endr << 1 << 1 << 2 << endr << 1.3 << 1.9 << 1.3 << endr; Mat<size_t> labelsIn; labelsIn << 1 << 1 << 1; // no need to normalize labels here. mat testingData; testingData << 2.4 << 2.5 << 2.6; DecisionStump<> ds(trainingData, labelsIn.row(0), numClasses, inpBucketSize); Row<size_t> predictedLabels(testingData.n_cols); ds.Classify(testingData, predictedLabels); for(size_t i = 0; i < predictedLabels.size(); i++ ) BOOST_CHECK_EQUAL(predictedLabels(i),1); } /* This tests for the classification: if testinput < 0 - class 0 if testinput > 0 - class 1 An almost perfect split on zero. */ BOOST_AUTO_TEST_CASE(PerfectSplitOnZero) { size_t numClasses = 2; const char* output = "outputPerfectSplitOnZero.csv"; size_t inpBucketSize = 2; mat trainingData; trainingData << -1 << 1 << -2 << 2 << -3 << 3; Mat<size_t> labelsIn; labelsIn << 0 << 1 << 0 << 1 << 0 << 1; // no need to normalize labels here. mat testingData; testingData << -4 << 7 << -7 << -5 << 6; DecisionStump<> ds(trainingData, labelsIn.row(0), numClasses, inpBucketSize); Row<size_t> predictedLabels(testingData.n_cols); ds.Classify(testingData, predictedLabels); data::Save(output, predictedLabels, true, true); } /* This tests the binning function for the case when a dataset with cardinality of input < inpBucketSize is provided. */ BOOST_AUTO_TEST_CASE(BinningTesting) { size_t numClasses = 2; const char* output = "outputBinningTesting.csv"; size_t inpBucketSize = 10; mat trainingData; trainingData << -1 << 1 << -2 << 2 << -3 << 3 << -4; Mat<size_t> labelsIn; labelsIn << 0 << 1 << 0 << 1 << 0 << 1 << 0; // no need to normalize labels here. mat testingData; testingData << 5; DecisionStump<> ds(trainingData, labelsIn.row(0), numClasses, inpBucketSize); Row<size_t> predictedLabels(testingData.n_cols); ds.Classify(testingData, predictedLabels); data::Save(output, predictedLabels, true, true); } /* This is a test for the case when non-overlapping, multiple classes are provided. It tests for a perfect split due to the non-overlapping nature of the input classes. */ BOOST_AUTO_TEST_CASE(PerfectMultiClassSplit) { size_t numClasses = 4; const char* output = "outputPerfectMultiClassSplit.csv"; size_t inpBucketSize = 3; mat trainingData; trainingData << -8 << -7 << -6 << -5 << -4 << -3 << -2 << -1 << 0 << 1 << 2 << 3 << 4 << 5 << 6 << 7; Mat<size_t> labelsIn; labelsIn << 0 << 0 << 0 << 0 << 1 << 1 << 1 << 1 << 2 << 2 << 2 << 2 << 3 << 3 << 3 << 3; // no need to normalize labels here. mat testingData; testingData << -6.1 << -2.1 << 1.1 << 5.1; DecisionStump<> ds(trainingData, labelsIn.row(0), numClasses, inpBucketSize); Row<size_t> predictedLabels(testingData.n_cols); ds.Classify(testingData, predictedLabels); data::Save(output, predictedLabels, true, true); } /* This test is for the case when reasonably overlapping, multiple classes are provided in the input label set. It tests whether classification takes place with a reasonable amount of error due to the overlapping nature of input classes. */ BOOST_AUTO_TEST_CASE(MultiClassSplit) { size_t numClasses = 3; const char* output = "outputMultiClassSplit.csv"; size_t inpBucketSize = 3; mat trainingData; trainingData << -7 << -6 << -5 << -4 << -3 << -2 << -1 << 0 << 1 << 2 << 3 << 4 << 5 << 6 << 7 << 8 << 9 << 10; Mat<size_t> labelsIn; labelsIn << 0 << 0 << 0 << 0 << 1 << 1 << 0 << 0 << 1 << 1 << 1 << 2 << 1 << 2 << 2 << 2 << 2 << 2; // no need to normalize labels here. mat testingData; testingData << -6.1 << -5.9 << -2.1 << -0.7 << 2.5 << 4.7 << 7.2 << 9.1; DecisionStump<> ds(trainingData, labelsIn.row(0), numClasses, inpBucketSize); Row<size_t> predictedLabels(testingData.n_cols); ds.Classify(testingData, predictedLabels); data::Save(output, predictedLabels, true, true); } BOOST_AUTO_TEST_SUITE_END();<commit_msg>Minor changes to test. const-correctness and comment normalization for Doxygen.<commit_after>/** * @file decision_stump_test.cpp * @author Udit Saxena * * Tests for DecisionStump class. */ #include <mlpack/core.hpp> #include <mlpack/methods/decision_stump/decision_stump.hpp> #include <boost/test/unit_test.hpp> #include "old_boost_test_definitions.hpp" using namespace mlpack; using namespace mlpack::decision_stump; using namespace arma; BOOST_AUTO_TEST_SUITE(DecisionStumpTest); /** * This tests handles the case wherein only one class exists in the input * labels. It checks whether the only class supplied was the only class * predicted. */ BOOST_AUTO_TEST_CASE(OneClass) { const size_t numClasses = 2; const size_t inpBucketSize = 6; mat trainingData; trainingData << 2.4 << 3.8 << 3.8 << endr << 1 << 1 << 2 << endr << 1.3 << 1.9 << 1.3 << endr; // No need to normalize labels here. Mat<size_t> labelsIn; labelsIn << 1 << 1 << 1; mat testingData; testingData << 2.4 << 2.5 << 2.6; DecisionStump<> ds(trainingData, labelsIn.row(0), numClasses, inpBucketSize); Row<size_t> predictedLabels(testingData.n_cols); ds.Classify(testingData, predictedLabels); for (size_t i = 0; i < predictedLabels.size(); i++ ) BOOST_CHECK_EQUAL(predictedLabels(i), 1); } /** * This tests for the classification: * if testinput < 0 - class 0 * if testinput > 0 - class 1 * An almost perfect split on zero. */ BOOST_AUTO_TEST_CASE(PerfectSplitOnZero) { const size_t numClasses = 2; const char* output = "outputPerfectSplitOnZero.csv"; const size_t inpBucketSize = 2; mat trainingData; trainingData << -1 << 1 << -2 << 2 << -3 << 3; // No need to normalize labels here. Mat<size_t> labelsIn; labelsIn << 0 << 1 << 0 << 1 << 0 << 1; mat testingData; testingData << -4 << 7 << -7 << -5 << 6; DecisionStump<> ds(trainingData, labelsIn.row(0), numClasses, inpBucketSize); Row<size_t> predictedLabels(testingData.n_cols); ds.Classify(testingData, predictedLabels); data::Save(output, predictedLabels, true, true); } /** * This tests the binning function for the case when a dataset with cardinality * of input < inpBucketSize is provided. */ BOOST_AUTO_TEST_CASE(BinningTesting) { const size_t numClasses = 2; const char* output = "outputBinningTesting.csv"; const size_t inpBucketSize = 10; mat trainingData; trainingData << -1 << 1 << -2 << 2 << -3 << 3 << -4; // No need to normalize labels here. Mat<size_t> labelsIn; labelsIn << 0 << 1 << 0 << 1 << 0 << 1 << 0; mat testingData; testingData << 5; DecisionStump<> ds(trainingData, labelsIn.row(0), numClasses, inpBucketSize); Row<size_t> predictedLabels(testingData.n_cols); ds.Classify(testingData, predictedLabels); data::Save(output, predictedLabels, true, true); } /** * This is a test for the case when non-overlapping, multiple classes are * provided. It tests for a perfect split due to the non-overlapping nature of * the input classes. */ BOOST_AUTO_TEST_CASE(PerfectMultiClassSplit) { const size_t numClasses = 4; const char* output = "outputPerfectMultiClassSplit.csv"; const size_t inpBucketSize = 3; mat trainingData; trainingData << -8 << -7 << -6 << -5 << -4 << -3 << -2 << -1 << 0 << 1 << 2 << 3 << 4 << 5 << 6 << 7; // No need to normalize labels here. Mat<size_t> labelsIn; labelsIn << 0 << 0 << 0 << 0 << 1 << 1 << 1 << 1 << 2 << 2 << 2 << 2 << 3 << 3 << 3 << 3; mat testingData; testingData << -6.1 << -2.1 << 1.1 << 5.1; DecisionStump<> ds(trainingData, labelsIn.row(0), numClasses, inpBucketSize); Row<size_t> predictedLabels(testingData.n_cols); ds.Classify(testingData, predictedLabels); data::Save(output, predictedLabels, true, true); } /** * This test is for the case when reasonably overlapping, multiple classes are * provided in the input label set. It tests whether classification takes place * with a reasonable amount of error due to the overlapping nature of input * classes. */ BOOST_AUTO_TEST_CASE(MultiClassSplit) { const size_t numClasses = 3; const char* output = "outputMultiClassSplit.csv"; const size_t inpBucketSize = 3; mat trainingData; trainingData << -7 << -6 << -5 << -4 << -3 << -2 << -1 << 0 << 1 << 2 << 3 << 4 << 5 << 6 << 7 << 8 << 9 << 10; // No need to normalize labels here. Mat<size_t> labelsIn; labelsIn << 0 << 0 << 0 << 0 << 1 << 1 << 0 << 0 << 1 << 1 << 1 << 2 << 1 << 2 << 2 << 2 << 2 << 2; mat testingData; testingData << -6.1 << -5.9 << -2.1 << -0.7 << 2.5 << 4.7 << 7.2 << 9.1; DecisionStump<> ds(trainingData, labelsIn.row(0), numClasses, inpBucketSize); Row<size_t> predictedLabels(testingData.n_cols); ds.Classify(testingData, predictedLabels); data::Save(output, predictedLabels, true, true); } BOOST_AUTO_TEST_SUITE_END(); <|endoftext|>
<commit_before>// Copyright 2020 PDFium 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 <cassert> #include <codecvt> #include <fstream> #include <iostream> #include <iterator> #include <locale> #include <vector> #include <fpdf_signature.h> #include <fpdfview.h> #include "public/cpp/fpdf_scopers.h" #include <cert.h> #include <cms.h> #include <nss.h> #include <sechash.h> struct HASHContextDeleter { void operator()(HASHContext* ptr) { HASH_Destroy(ptr); } }; using ScopedHASHContext = std::unique_ptr<HASHContext, HASHContextDeleter>; struct CERTCertificateDeleter { void operator()(CERTCertificate* ptr) { CERT_DestroyCertificate(ptr); } }; using ScopedCERTCertificate = std::unique_ptr<CERTCertificate, CERTCertificateDeleter>; class Crypto { public: enum class ValidationStatus { SUCCESS, FAILURE, }; Crypto(); ~Crypto(); /** * Validates if `signature` is a proper signature of `bytes`. This only * focuses on if the digest matches or not, ignoring cert validation. Not * specific to PDF in any way. * * The flow is: message -> content_info -> signed_data -> signer_info */ bool validateBytes(const std::vector<unsigned char>& bytes, const std::vector<unsigned char>& signature, ValidationStatus& status); }; Crypto::Crypto() { SECStatus ret = NSS_NoDB_Init(nullptr); if (ret != SECSuccess) { std::cerr << "warning, NSS_NoDB_Init() failed" << std::endl; } } Crypto::~Crypto() { SECStatus ret = NSS_Shutdown(); if (ret != SECSuccess) { std::cerr << "warning, NSS_Shutdown() failed" << std::endl; } } bool Crypto::validateBytes(const std::vector<unsigned char>& bytes, const std::vector<unsigned char>& signature, ValidationStatus& status) { SECItem signature_item; signature_item.data = const_cast<unsigned char*>(signature.data()); signature_item.len = signature.size(); NSSCMSMessage* message = NSS_CMSMessage_CreateFromDER(&signature_item, /*cb=*/nullptr, /*cb_arg=*/nullptr, /*pwfn=*/nullptr, /*pwfn_arg=*/nullptr, /*decrypt_key_cb=*/nullptr, /*decrypt_key_cb_arg=*/nullptr); if (!NSS_CMSMessage_IsSigned(message)) { std::cerr << "warning, NSS_CMSMessage_IsSigned() failed" << std::endl; return false; } NSSCMSContentInfo* content_info = NSS_CMSMessage_ContentLevel(message, /*n=*/0); if (!content_info) { std::cerr << "warning, NSS_CMSMessage_ContentLevel() failed" << std::endl; return false; } auto signed_data = static_cast<NSSCMSSignedData*>( NSS_CMSContentInfo_GetContent(content_info)); if (!signed_data) { std::cerr << "warning, NSS_CMSContentInfo_GetContent() failed" << std::endl; return false; } std::vector<ScopedCERTCertificate> message_certificates; for (size_t i = 0; signed_data->rawCerts[i]; ++i) { ScopedCERTCertificate certificate(CERT_NewTempCertificate( CERT_GetDefaultCertDB(), signed_data->rawCerts[i], /*nickname=*/nullptr, /*isperm=*/0, /*copyDER=*/0)); message_certificates.push_back(std::move(certificate)); } SECItem alg_item = NSS_CMSSignedData_GetDigestAlgs(signed_data)[0]->algorithm; SECOidTag alg_oid = SECOID_FindOIDTag(&alg_item); HASH_HashType hash_type = HASH_GetHashTypeByOidTag(alg_oid); ScopedHASHContext hash_context(HASH_Create(hash_type)); if (!hash_context) { std::cerr << "warning, HASH_Create() failed" << std::endl; return false; } HASH_Update(hash_context.get(), bytes.data(), bytes.size()); NSSCMSSignerInfo* signer_info = NSS_CMSSignedData_GetSignerInfo(signed_data, 0); if (!signer_info) { std::cerr << "warning, NSS_CMSSignedData_GetSignerInfo() failed" << std::endl; return false; } std::vector<unsigned char> hash(HASH_ResultLenContext(hash_context.get())); unsigned int actual_hash_length; HASH_End(hash_context.get(), hash.data(), &actual_hash_length, HASH_ResultLenContext(hash_context.get())); // Need to call this manually, so that signer_info->cert gets set. Otherwise // NSS_CMSSignerInfo_Verify() will call // NSS_CMSSignerInfo_GetSigningCertificate() with certdb=nullptr, which // won't find the certificate. ScopedCERTCertificate certificate(NSS_CMSSignerInfo_GetSigningCertificate( signer_info, CERT_GetDefaultCertDB())); SECItem hash_item; hash_item.data = hash.data(); hash_item.len = actual_hash_length; SECStatus ret = NSS_CMSSignerInfo_Verify(signer_info, &hash_item, /*contentType=*/nullptr); if (ret != SECSuccess) { status = ValidationStatus::FAILURE; return true; } status = ValidationStatus::SUCCESS; return true; } struct ByteRange { size_t offset; size_t length; }; struct Signature { FPDF_SIGNATURE signature; std::vector<ByteRange> byte_ranges; }; void validateByteRanges(const std::vector<unsigned char>& bytes, const std::vector<ByteRange>& byte_ranges, const std::vector<unsigned char>& signature) { Crypto crypto; std::vector<unsigned char> buffer; for (const auto& byte_range : byte_ranges) { size_t buffer_size = buffer.size(); buffer.resize(buffer_size + byte_range.length); memcpy(buffer.data() + buffer_size, bytes.data() + byte_range.offset, byte_range.length); } Crypto::ValidationStatus status{}; if (!crypto.validateBytes(buffer, signature, status)) { std::cerr << "warning, failed to determine digest match" << std::endl; return; } if (status == Crypto::ValidationStatus::FAILURE) { std::cerr << " - Signature Verification: digest does not match" << std::endl; return; } std::cerr << " - Signature Verification: digest matches" << std::endl; } void validateSignature(const std::vector<unsigned char>& bytes, const Signature& signature_info, int signature_index) { FPDF_SIGNATURE signature = signature_info.signature; const std::vector<ByteRange>& byte_ranges = signature_info.byte_ranges; std::cerr << "Signature #" << signature_index << ":" << std::endl; int contents_len = FPDFSignatureObj_GetContents(signature, nullptr, 0); std::vector<unsigned char> contents(contents_len); FPDFSignatureObj_GetContents(signature, contents.data(), contents.size()); int sub_filter_len = FPDFSignatureObj_GetSubFilter(signature, nullptr, 0); std::vector<char> sub_filter_buf(sub_filter_len); FPDFSignatureObj_GetSubFilter(signature, sub_filter_buf.data(), sub_filter_buf.size()); // Buffer is NUL-terminated. std::string sub_filter(sub_filter_buf.data(), sub_filter_buf.size() - 1); // Sanity checks. if (sub_filter != "adbe.pkcs7.detached" && sub_filter != "ETSI.CAdES.detached") { std::cerr << "warning, unexpected sub-filter: '" << sub_filter << "'" << std::endl; return; } if (byte_ranges.size() < 2) { std::cerr << "warning, expected 2 byte ranges" << std::endl; return; } if (byte_ranges[0].offset != 0) { std::cerr << "warning, first range start is not 0" << std::endl; return; } // Binary vs hex dump and 2 is the leading "<" and the trailing ">" around // the hex string. size_t signature_length = contents.size() * 2 + 2; if (byte_ranges[1].offset != (byte_ranges[0].length + signature_length)) { std::cerr << "warning, second range start is not the end of the signature" << std::endl; return; } int reason_len = FPDFSignatureObj_GetReason(signature, nullptr, 0); if (reason_len > 0) { std::vector<char16_t> reason_buf(reason_len); FPDFSignatureObj_GetReason(signature, reason_buf.data(), reason_buf.size()); std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> conversion; std::string reason = conversion.to_bytes(reason_buf.data()); std::cerr << " - Signature Reason: " << reason << std::endl; } int time_len = FPDFSignatureObj_GetTime(signature, nullptr, 0); if (time_len > 0) { std::vector<char> time_buf(time_len); FPDFSignatureObj_GetTime(signature, time_buf.data(), time_buf.size()); std::cerr << " - Signature Time: " << time_buf.data() << std::endl; } validateByteRanges(bytes, byte_ranges, contents); } std::vector<ByteRange> getByteRanges(FPDF_SIGNATURE signature) { int byte_range_len = FPDFSignatureObj_GetByteRange(signature, nullptr, 0); std::vector<int> byte_range(byte_range_len); FPDFSignatureObj_GetByteRange(signature, byte_range.data(), byte_range.size()); std::vector<ByteRange> byte_ranges; size_t byte_range_offset = 0; for (size_t i = 0; i < byte_range.size(); ++i) { if (i % 2 == 0) { byte_range_offset = byte_range[i]; continue; } size_t byte_range_len = byte_range[i]; byte_ranges.push_back({byte_range_offset, byte_range_len}); } return byte_ranges; } int main(int argc, char* argv[]) { FPDF_LIBRARY_CONFIG config; config.version = 2; config.m_pUserFontPaths = nullptr; config.m_pIsolate = nullptr; config.m_v8EmbedderSlot = 0; FPDF_InitLibraryWithConfig(&config); std::ifstream file_stream(argv[1], std::ios::binary); std::vector<unsigned char> file_contents( (std::istreambuf_iterator<char>(file_stream)), std::istreambuf_iterator<char>()); { ScopedFPDFDocument document(FPDF_LoadMemDocument( file_contents.data(), file_contents.size(), /*password=*/nullptr)); assert(document); int signature_count = FPDF_GetSignatureCount(document.get()); std::vector<Signature> signatures(signature_count); for (int i = 0; i < signature_count; ++i) { FPDF_SIGNATURE signature = FPDF_GetSignatureObject(document.get(), i); std::vector<ByteRange> byte_ranges = getByteRanges(signature); signatures[i] = Signature{signature, byte_ranges}; } for (int i = 0; i < signature_count; ++i) { validateSignature(file_contents, signatures[i], i); } int num_trailers = FPDF_GetTrailerEnds(document.get(), nullptr, 0); std::vector<unsigned int> trailer_ends(num_trailers); FPDF_GetTrailerEnds(document.get(), trailer_ends.data(), trailer_ends.size()); std::cerr << "Trailer end offsets:" << std::endl; for (auto end : trailer_ends) std::cerr << " - " << end << std::endl; } FPDF_DestroyLibrary(); } <commit_msg>pdfiumsig: show how to use FPDF_GetTrailerEnds() to detect partial sigs<commit_after>// Copyright 2020 PDFium 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 <cassert> #include <codecvt> #include <fstream> #include <iostream> #include <iterator> #include <locale> #include <set> #include <vector> #include <fpdf_signature.h> #include <fpdfview.h> #include "public/cpp/fpdf_scopers.h" #include <cert.h> #include <cms.h> #include <nss.h> #include <sechash.h> struct HASHContextDeleter { void operator()(HASHContext* ptr) { HASH_Destroy(ptr); } }; using ScopedHASHContext = std::unique_ptr<HASHContext, HASHContextDeleter>; struct CERTCertificateDeleter { void operator()(CERTCertificate* ptr) { CERT_DestroyCertificate(ptr); } }; using ScopedCERTCertificate = std::unique_ptr<CERTCertificate, CERTCertificateDeleter>; /** * Crypto is meant to contain all code that interacts with a real crypto * library. */ class Crypto { public: enum class ValidationStatus { SUCCESS, FAILURE, }; Crypto(); ~Crypto(); /** * Validates if `signature` is a proper signature of `bytes`. This only * focuses on if the digest matches or not, ignoring cert validation. Not * specific to PDF in any way. * * The flow is: message -> content_info -> signed_data -> signer_info */ bool validateBytes(const std::vector<unsigned char>& bytes, const std::vector<unsigned char>& signature, ValidationStatus& status); }; Crypto::Crypto() { SECStatus ret = NSS_NoDB_Init(nullptr); if (ret != SECSuccess) { std::cerr << "warning, NSS_NoDB_Init() failed" << std::endl; } } Crypto::~Crypto() { SECStatus ret = NSS_Shutdown(); if (ret != SECSuccess) { std::cerr << "warning, NSS_Shutdown() failed" << std::endl; } } bool Crypto::validateBytes(const std::vector<unsigned char>& bytes, const std::vector<unsigned char>& signature, ValidationStatus& status) { SECItem signature_item; signature_item.data = const_cast<unsigned char*>(signature.data()); signature_item.len = signature.size(); NSSCMSMessage* message = NSS_CMSMessage_CreateFromDER(&signature_item, /*cb=*/nullptr, /*cb_arg=*/nullptr, /*pwfn=*/nullptr, /*pwfn_arg=*/nullptr, /*decrypt_key_cb=*/nullptr, /*decrypt_key_cb_arg=*/nullptr); if (!NSS_CMSMessage_IsSigned(message)) { std::cerr << "warning, NSS_CMSMessage_IsSigned() failed" << std::endl; return false; } NSSCMSContentInfo* content_info = NSS_CMSMessage_ContentLevel(message, /*n=*/0); if (!content_info) { std::cerr << "warning, NSS_CMSMessage_ContentLevel() failed" << std::endl; return false; } auto signed_data = static_cast<NSSCMSSignedData*>( NSS_CMSContentInfo_GetContent(content_info)); if (!signed_data) { std::cerr << "warning, NSS_CMSContentInfo_GetContent() failed" << std::endl; return false; } std::vector<ScopedCERTCertificate> message_certificates; for (size_t i = 0; signed_data->rawCerts[i]; ++i) { ScopedCERTCertificate certificate(CERT_NewTempCertificate( CERT_GetDefaultCertDB(), signed_data->rawCerts[i], /*nickname=*/nullptr, /*isperm=*/0, /*copyDER=*/0)); message_certificates.push_back(std::move(certificate)); } SECItem alg_item = NSS_CMSSignedData_GetDigestAlgs(signed_data)[0]->algorithm; SECOidTag alg_oid = SECOID_FindOIDTag(&alg_item); HASH_HashType hash_type = HASH_GetHashTypeByOidTag(alg_oid); ScopedHASHContext hash_context(HASH_Create(hash_type)); if (!hash_context) { std::cerr << "warning, HASH_Create() failed" << std::endl; return false; } HASH_Update(hash_context.get(), bytes.data(), bytes.size()); NSSCMSSignerInfo* signer_info = NSS_CMSSignedData_GetSignerInfo(signed_data, 0); if (!signer_info) { std::cerr << "warning, NSS_CMSSignedData_GetSignerInfo() failed" << std::endl; return false; } std::vector<unsigned char> hash(HASH_ResultLenContext(hash_context.get())); unsigned int actual_hash_length; HASH_End(hash_context.get(), hash.data(), &actual_hash_length, HASH_ResultLenContext(hash_context.get())); // Need to call this manually, so that signer_info->cert gets set. Otherwise // NSS_CMSSignerInfo_Verify() will call // NSS_CMSSignerInfo_GetSigningCertificate() with certdb=nullptr, which // won't find the certificate. ScopedCERTCertificate certificate(NSS_CMSSignerInfo_GetSigningCertificate( signer_info, CERT_GetDefaultCertDB())); SECItem hash_item; hash_item.data = hash.data(); hash_item.len = actual_hash_length; SECStatus ret = NSS_CMSSignerInfo_Verify(signer_info, &hash_item, /*contentType=*/nullptr); if (ret != SECSuccess) { status = ValidationStatus::FAILURE; return true; } status = ValidationStatus::SUCCESS; return true; } struct ByteRange { size_t offset; size_t length; }; struct Signature { FPDF_SIGNATURE signature; std::vector<ByteRange> byte_ranges; }; void validateByteRanges(const std::vector<unsigned char>& bytes, const std::vector<ByteRange>& byte_ranges, const std::vector<unsigned char>& signature) { Crypto crypto; std::vector<unsigned char> buffer; for (const auto& byte_range : byte_ranges) { size_t buffer_size = buffer.size(); buffer.resize(buffer_size + byte_range.length); memcpy(buffer.data() + buffer_size, bytes.data() + byte_range.offset, byte_range.length); } Crypto::ValidationStatus status{}; if (!crypto.validateBytes(buffer, signature, status)) { std::cerr << "warning, failed to determine digest match" << std::endl; return; } if (status == Crypto::ValidationStatus::FAILURE) { std::cerr << " - Signature Verification: digest does not match" << std::endl; return; } std::cerr << " - Signature Verification: digest matches" << std::endl; } int getEofOfSignature(const Signature& signature) { return signature.byte_ranges[1].offset + signature.byte_ranges[1].length; } bool isCompleteSignature(const std::vector<unsigned int>& trailer_ends, const Signature& signature_info, const std::set<unsigned int>& signature_eofs) { unsigned int own_eof = getEofOfSignature(signature_info); bool found_own = false; for (const auto& eof : trailer_ends) { if (eof == own_eof) { found_own = true; continue; } if (!found_own) continue; if (signature_eofs.find(eof) == signature_eofs.end()) // Unsigned incremental update found. return false; } // Make sure we find the incremental update of the signature itself. return found_own; } void validateSignature(const std::vector<unsigned char>& bytes, const std::vector<unsigned int>& trailer_ends, const Signature& signature_info, const std::set<unsigned int>& signature_eofs, int signature_index) { FPDF_SIGNATURE signature = signature_info.signature; const std::vector<ByteRange>& byte_ranges = signature_info.byte_ranges; std::cerr << "Signature #" << signature_index << ":" << std::endl; int contents_len = FPDFSignatureObj_GetContents(signature, nullptr, 0); std::vector<unsigned char> contents(contents_len); FPDFSignatureObj_GetContents(signature, contents.data(), contents.size()); int sub_filter_len = FPDFSignatureObj_GetSubFilter(signature, nullptr, 0); std::vector<char> sub_filter_buf(sub_filter_len); FPDFSignatureObj_GetSubFilter(signature, sub_filter_buf.data(), sub_filter_buf.size()); // Buffer is NUL-terminated. std::string sub_filter(sub_filter_buf.data(), sub_filter_buf.size() - 1); // Sanity checks. if (sub_filter != "adbe.pkcs7.detached" && sub_filter != "ETSI.CAdES.detached") { std::cerr << "warning, unexpected sub-filter: '" << sub_filter << "'" << std::endl; return; } if (byte_ranges.size() < 2) { std::cerr << "warning, expected 2 byte ranges" << std::endl; return; } if (byte_ranges[0].offset != 0) { std::cerr << "warning, first range start is not 0" << std::endl; return; } // Binary vs hex dump and 2 is the leading "<" and the trailing ">" around // the hex string. size_t signature_length = contents.size() * 2 + 2; if (byte_ranges[1].offset != (byte_ranges[0].length + signature_length)) { std::cerr << "warning, second range start is not the end of the signature" << std::endl; return; } if (!isCompleteSignature(trailer_ends, signature_info, signature_eofs)) std::cerr << " - Signature is partial" << std::endl; else std::cerr << " - Signature is complete" << std::endl; int reason_len = FPDFSignatureObj_GetReason(signature, nullptr, 0); if (reason_len > 0) { std::vector<char16_t> reason_buf(reason_len); FPDFSignatureObj_GetReason(signature, reason_buf.data(), reason_buf.size()); std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> conversion; std::string reason = conversion.to_bytes(reason_buf.data()); std::cerr << " - Signature Reason: " << reason << std::endl; } int time_len = FPDFSignatureObj_GetTime(signature, nullptr, 0); if (time_len > 0) { std::vector<char> time_buf(time_len); FPDFSignatureObj_GetTime(signature, time_buf.data(), time_buf.size()); std::cerr << " - Signature Time: " << time_buf.data() << std::endl; } validateByteRanges(bytes, byte_ranges, contents); } std::vector<ByteRange> getByteRanges(FPDF_SIGNATURE signature) { int byte_range_len = FPDFSignatureObj_GetByteRange(signature, nullptr, 0); std::vector<int> byte_range(byte_range_len); FPDFSignatureObj_GetByteRange(signature, byte_range.data(), byte_range.size()); std::vector<ByteRange> byte_ranges; size_t byte_range_offset = 0; for (size_t i = 0; i < byte_range.size(); ++i) { if (i % 2 == 0) { byte_range_offset = byte_range[i]; continue; } size_t byte_range_len = byte_range[i]; byte_ranges.push_back({byte_range_offset, byte_range_len}); } return byte_ranges; } int main(int argc, char* argv[]) { FPDF_LIBRARY_CONFIG config; config.version = 2; config.m_pUserFontPaths = nullptr; config.m_pIsolate = nullptr; config.m_v8EmbedderSlot = 0; FPDF_InitLibraryWithConfig(&config); std::cerr << "Digital Signature Info of: " << argv[1] << std::endl; std::ifstream file_stream(argv[1], std::ios::binary); std::vector<unsigned char> file_contents( (std::istreambuf_iterator<char>(file_stream)), std::istreambuf_iterator<char>()); { ScopedFPDFDocument document(FPDF_LoadMemDocument( file_contents.data(), file_contents.size(), /*password=*/nullptr)); assert(document); // Collect info about signatures. int signature_count = FPDF_GetSignatureCount(document.get()); std::vector<Signature> signatures(signature_count); for (int i = 0; i < signature_count; ++i) { FPDF_SIGNATURE signature = FPDF_GetSignatureObject(document.get(), i); std::vector<ByteRange> byte_ranges = getByteRanges(signature); signatures[i] = Signature{signature, byte_ranges}; } std::set<unsigned int> signature_eofs; for (const auto& signature : signatures) { signature_eofs.insert(getEofOfSignature(signature)); } int num_trailers = FPDF_GetTrailerEnds(document.get(), nullptr, 0); std::vector<unsigned int> trailer_ends(num_trailers); FPDF_GetTrailerEnds(document.get(), trailer_ends.data(), trailer_ends.size()); // Validate them. for (int i = 0; i < signature_count; ++i) { validateSignature(file_contents, trailer_ends, signatures[i], signature_eofs, i); } } FPDF_DestroyLibrary(); } <|endoftext|>
<commit_before>#include "physics/n_body_system.hpp" #include <cmath> #include <functional> #include <set> #include <vector> #include "geometry/named_quantities.hpp" #include "geometry/r3_element.hpp" #include "glog/logging.h" #include "integrators/symplectic_partitioned_runge_kutta_integrator.hpp" #include "quantities/quantities.hpp" using principia::geometry::Dot; using principia::geometry::Instant; using principia::geometry::R3Element; using principia::integrators::SPRKIntegrator; using principia::integrators::SymplecticIntegrator; using principia::quantities::Acceleration; using principia::quantities::Exponentiation; using principia::quantities::GravitationalParameter; using principia::quantities::Length; using principia::quantities::Speed; namespace principia { namespace physics { namespace { R3Element<Acceleration> Order2ZonalAcceleration(Body const& body, R3Element<Length> const& r, Exponentiation<Length, -2> const one_over_r_squared, Exponentiation<Length, -3> const one_over_r_cubed) { R3Element<double> const& axis = body.axis(); Length const r_axis_projection = Dot(axis, r); auto const j2_over_r_fifth = body.j2() * one_over_r_cubed * one_over_r_squared; R3Element<Acceleration> const& axis_acceleration = (-3 * j2_over_r_fifth * r_axis_projection) * axis; R3Element<Acceleration> const& radial_acceleration = (j2_over_r_fifth * (-1.5 + 7.5 * r_axis_projection * r_axis_projection * one_over_r_squared)) * r; return axis_acceleration + radial_acceleration; } } // namespace template<typename InertialFrame> void NBodySystem<InertialFrame>::Integrate( SymplecticIntegrator<Length, Speed> const& integrator, Instant const& tmax, Time const& Δt, int const sampling_period, bool const tmax_is_exact, Trajectories const& trajectories) { SymplecticIntegrator<Length, Speed>::Parameters parameters; std::vector<SymplecticIntegrator<Length, Speed>::SystemState> solution; // TODO(phl): Use a position based on the first mantissa bits of the // center-of-mass referential and a time in the middle of the integration // interval. In the integrator itself, all quantities are "vectors" relative // to these references. Position<InertialFrame> const reference_position; Instant const reference_time; // These objects are for checking the consistency of the parameters. std::set<Instant> times_in_trajectories; std::set<Body const*> bodies_in_trajectories; // Prepare the initial state of the integrator. For efficiently computing the // accelerations, we need to separate the trajectories of massive bodies from // those of massless bodies. They are put in this order in // |reordered_trajectories|. The trajectories of massive and massless bodies // are put in |massive_trajectories| and |massless_trajectories|, // respectively. std::vector<Trajectory<InertialFrame>*> reordered_trajectories; std::vector<Trajectory<InertialFrame> const*> massive_trajectories; std::vector<Trajectory<InertialFrame> const*> massless_trajectories; // This loop ensures that the massive bodies precede the massless bodies in // the vectors representing the initial data. for (bool is_massless : {false, true}) { for (auto const& trajectory : trajectories) { // See if this trajectory should be processed in this iteration and // update the appropriate vector. Body const* const body = &trajectory->body(); if (body->is_massless() != is_massless) { continue; } if (is_massless) { massless_trajectories.push_back(trajectory); } else { massive_trajectories.push_back(trajectory); } reordered_trajectories.push_back(trajectory); // Fill the initial position/velocity/time. R3Element<Length> const& position = (trajectory->last_position() - reference_position).coordinates(); R3Element<Speed> const& velocity = trajectory->last_velocity().coordinates(); Instant const& time = trajectory->last_time(); for (int i = 0; i < 3; ++i) { parameters.initial.positions.emplace_back(position[i]); } for (int i = 0; i < 3; ++i) { parameters.initial.momenta.emplace_back(velocity[i]); } // Check that all trajectories are for different bodies. auto const inserted = bodies_in_trajectories.insert(body); CHECK(inserted.second) << "Multiple trajectories for the same body"; // The final points of all trajectories must all be for the same time. times_in_trajectories.insert(time); CHECK_GE(1U, times_in_trajectories.size()) << "Inconsistent last time in trajectories"; } } { // Beyond this point we must not use the |trajectories| parameter as it is // in the wrong order with respect to the data passed to the integrator. We // use this block to hide it. Trajectories const& trajectories = reordered_trajectories; parameters.initial.time = *times_in_trajectories.cbegin() - reference_time; parameters.tmax = tmax - reference_time; parameters.Δt = Δt; parameters.sampling_period = sampling_period; parameters.tmax_is_exact = tmax_is_exact; dynamic_cast<const SPRKIntegrator<Length, Speed>*>(&integrator)->Solve( std::bind(&NBodySystem::ComputeGravitationalAccelerations, massive_trajectories, massless_trajectories, reference_time, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3), &ComputeGravitationalVelocities, parameters, &solution); // TODO(phl): Ignoring errors for now. // Loop over the time steps. for (std::size_t i = 0; i < solution.size(); ++i) { SymplecticIntegrator<Length, Speed>::SystemState const& state = solution[i]; Instant const time = state.time.value + reference_time; CHECK_EQ(state.positions.size(), state.momenta.size()); // Loop over the dimensions. for (std::size_t k = 0, t = 0; k < state.positions.size(); k += 3, ++t) { Vector<Length, InertialFrame> const position( R3Element<Length>(state.positions[k].value, state.positions[k + 1].value, state.positions[k + 2].value)); Velocity<InertialFrame> const velocity( R3Element<Speed>(state.momenta[k].value, state.momenta[k + 1].value, state.momenta[k + 2].value)); trajectories[t]->Append( time, DegreesOfFreedom<InertialFrame>(position + reference_position, velocity)); } } } } template<typename InertialFrame> void NBodySystem<InertialFrame>::ComputeGravitationalAccelerations( std::vector<Trajectory<InertialFrame> const*> const& massive_trajectories, std::vector<Trajectory<InertialFrame> const*> const& massless_trajectories, Instant const& reference_time, Time const& t, std::vector<Length> const& q, std::vector<Acceleration>* result) { result->assign(result->size(), Acceleration()); size_t const number_of_massive_trajectories = massive_trajectories.size(); size_t const number_of_massless_trajectories = massless_trajectories.size(); // Declaring variables for values like 3 * b1 + 1, 3 * b2 + 1, etc. in the // code below brings no performance advantage as it seems that the compiler is // smart enough to figure common subexpressions. for (std::size_t b1 = 0, three_b1 = 0; b1 < number_of_massive_trajectories; ++b1, three_b1 += 3) { Body const& body1 = massive_trajectories[b1]->body(); GravitationalParameter const& body1_gravitational_parameter = body1.gravitational_parameter(); bool const body1_is_oblate = body1.is_oblate(); for (std::size_t b2 = b1 + 1; b2 < massive_trajectories.size(); ++b2) { Body const& body2 = massive_trajectories[b2]->body(); GravitationalParameter const& body2_gravitational_parameter = body2.gravitational_parameter(); bool const body2_is_oblate = body2.is_oblate(); std::size_t const three_b2 = 3 * b2; Length const Δq0 = q[three_b1] - q[three_b2]; Length const Δq1 = q[three_b1 + 1] - q[three_b2 + 1]; Length const Δq2 = q[three_b1 + 2] - q[three_b2 + 2]; Exponentiation<Length, 2> const r_squared = Δq0 * Δq0 + Δq1 * Δq1 + Δq2 * Δq2; // Don't try to compute one_over_r_squared here, it makes the non-oblate // path slower. Exponentiation<Length, -3> const one_over_r_cubed = Sqrt(r_squared) / (r_squared * r_squared); auto const μ2_over_r_cubed = body2_gravitational_parameter * one_over_r_cubed; (*result)[three_b1] -= Δq0 * μ2_over_r_cubed; (*result)[three_b1 + 1] -= Δq1 * μ2_over_r_cubed; (*result)[three_b1 + 2] -= Δq2 * μ2_over_r_cubed; // Lex. III. Actioni contrariam semper & æqualem esse reactionem: // sive corporum duorum actiones in se mutuo semper esse æquales & // in partes contrarias dirigi. auto const μ1_over_r_cubed = body1_gravitational_parameter * one_over_r_cubed; (*result)[three_b2] += Δq0 * μ1_over_r_cubed; (*result)[three_b2 + 1] += Δq1 * μ1_over_r_cubed; (*result)[three_b2 + 2] += Δq2 * μ1_over_r_cubed; if (!body1_is_oblate && !body2_is_oblate) { continue; } Exponentiation<Length, -2> const one_over_r_squared = 1 / r_squared; if (body1_is_oblate) { R3Element<Acceleration> const order_2_zonal_acceleration1 = Order2ZonalAcceleration(body1, {Δq0, Δq1, Δq2}, one_over_r_squared, one_over_r_cubed); (*result)[three_b2] += order_2_zonal_acceleration1.x; (*result)[three_b2 + 1] += order_2_zonal_acceleration1.y; (*result)[three_b2 + 2] += order_2_zonal_acceleration1.z; } if (body2_is_oblate) { R3Element<Acceleration> const order_2_zonal_acceleration2 = Order2ZonalAcceleration(body2, {Δq0, Δq1, Δq2}, one_over_r_squared, one_over_r_cubed); (*result)[three_b1] += order_2_zonal_acceleration2.x; (*result)[three_b1 + 1] += order_2_zonal_acceleration2.y; (*result)[three_b1 + 2] += order_2_zonal_acceleration2.z; } } for (size_t b2 = number_of_massive_trajectories; b2 < number_of_massive_trajectories + number_of_massless_trajectories; ++b2) { std::size_t const three_b2 = 3 * b2; Length const Δq0 = q[three_b1] - q[three_b2]; Length const Δq1 = q[three_b1 + 1] - q[three_b2 + 1]; Length const Δq2 = q[three_b1 + 2] - q[three_b2 + 2]; Exponentiation<Length, 2> const r_squared = Δq0 * Δq0 + Δq1 * Δq1 + Δq2 * Δq2; Exponentiation<Length, -3> const one_over_r_cubed = Sqrt(r_squared) / (r_squared * r_squared); auto const μ1_over_r_cubed = body1_gravitational_parameter * one_over_r_cubed; (*result)[three_b2] += Δq0 * μ1_over_r_cubed; (*result)[three_b2 + 1] += Δq1 * μ1_over_r_cubed; (*result)[three_b2 + 2] += Δq2 * μ1_over_r_cubed; if (true/*!body1_is_oblate*/) { continue; } Exponentiation<Length, -2> const one_over_r_squared = 1 / r_squared; R3Element<Acceleration> const order_2_zonal_acceleration1 = Order2ZonalAcceleration(body1, {Δq0, Δq1, Δq2}, one_over_r_squared, one_over_r_cubed); (*result)[three_b2] += order_2_zonal_acceleration1.x; (*result)[three_b2 + 1] += order_2_zonal_acceleration1.y; (*result)[three_b2 + 2] += order_2_zonal_acceleration1.z; } } // Finally, take into account the intrinsic accelerations. for (size_t b2 = number_of_massive_trajectories; b2 < number_of_massive_trajectories + number_of_massless_trajectories; ++b2) { std::size_t const three_b2 = 3 * b2; Trajectory<InertialFrame> const* trajectory = massless_trajectories[b2 - number_of_massive_trajectories]; if (trajectory->has_intrinsic_acceleration()) { R3Element<Acceleration> const acceleration = trajectory->evaluate_intrinsic_acceleration( t + reference_time).coordinates(); (*result)[three_b2] += acceleration.x; (*result)[three_b2 + 1] += acceleration.y; (*result)[three_b2 + 2] += acceleration.z; } } } template<typename InertialFrame> void NBodySystem<InertialFrame>::ComputeGravitationalVelocities( std::vector<Speed> const& p, std::vector<Speed>* result) { *result = p; } } // namespace physics } // namespace principia <commit_msg>Comment.<commit_after>#include "physics/n_body_system.hpp" #include <cmath> #include <functional> #include <set> #include <vector> #include "geometry/named_quantities.hpp" #include "geometry/r3_element.hpp" #include "glog/logging.h" #include "integrators/symplectic_partitioned_runge_kutta_integrator.hpp" #include "quantities/quantities.hpp" using principia::geometry::Dot; using principia::geometry::Instant; using principia::geometry::R3Element; using principia::integrators::SPRKIntegrator; using principia::integrators::SymplecticIntegrator; using principia::quantities::Acceleration; using principia::quantities::Exponentiation; using principia::quantities::GravitationalParameter; using principia::quantities::Length; using principia::quantities::Speed; namespace principia { namespace physics { namespace { // If j is a unit vector along the axis of rotation, and r is the separation // between the bodies, the acceleration computed here is: // // -(3 J2 / 2 |r|^5) (2 j (r.j) + r (1 - 5 (r.j)^2 / |r|^2) // // Where |r| is the norm of r and r.j is the inner product. // R3Element<Acceleration> Order2ZonalAcceleration(Body const& body, R3Element<Length> const& r, Exponentiation<Length, -2> const one_over_r_squared, Exponentiation<Length, -3> const one_over_r_cubed) { R3Element<double> const& axis = body.axis(); Length const r_axis_projection = Dot(axis, r); auto const j2_over_r_fifth = body.j2() * one_over_r_cubed * one_over_r_squared; R3Element<Acceleration> const& axis_acceleration = (-3 * j2_over_r_fifth * r_axis_projection) * axis; R3Element<Acceleration> const& radial_acceleration = (j2_over_r_fifth * (-1.5 + 7.5 * r_axis_projection * r_axis_projection * one_over_r_squared)) * r; return axis_acceleration + radial_acceleration; } } // namespace template<typename InertialFrame> void NBodySystem<InertialFrame>::Integrate( SymplecticIntegrator<Length, Speed> const& integrator, Instant const& tmax, Time const& Δt, int const sampling_period, bool const tmax_is_exact, Trajectories const& trajectories) { SymplecticIntegrator<Length, Speed>::Parameters parameters; std::vector<SymplecticIntegrator<Length, Speed>::SystemState> solution; // TODO(phl): Use a position based on the first mantissa bits of the // center-of-mass referential and a time in the middle of the integration // interval. In the integrator itself, all quantities are "vectors" relative // to these references. Position<InertialFrame> const reference_position; Instant const reference_time; // These objects are for checking the consistency of the parameters. std::set<Instant> times_in_trajectories; std::set<Body const*> bodies_in_trajectories; // Prepare the initial state of the integrator. For efficiently computing the // accelerations, we need to separate the trajectories of massive bodies from // those of massless bodies. They are put in this order in // |reordered_trajectories|. The trajectories of massive and massless bodies // are put in |massive_trajectories| and |massless_trajectories|, // respectively. std::vector<Trajectory<InertialFrame>*> reordered_trajectories; std::vector<Trajectory<InertialFrame> const*> massive_trajectories; std::vector<Trajectory<InertialFrame> const*> massless_trajectories; // This loop ensures that the massive bodies precede the massless bodies in // the vectors representing the initial data. for (bool is_massless : {false, true}) { for (auto const& trajectory : trajectories) { // See if this trajectory should be processed in this iteration and // update the appropriate vector. Body const* const body = &trajectory->body(); if (body->is_massless() != is_massless) { continue; } if (is_massless) { massless_trajectories.push_back(trajectory); } else { massive_trajectories.push_back(trajectory); } reordered_trajectories.push_back(trajectory); // Fill the initial position/velocity/time. R3Element<Length> const& position = (trajectory->last_position() - reference_position).coordinates(); R3Element<Speed> const& velocity = trajectory->last_velocity().coordinates(); Instant const& time = trajectory->last_time(); for (int i = 0; i < 3; ++i) { parameters.initial.positions.emplace_back(position[i]); } for (int i = 0; i < 3; ++i) { parameters.initial.momenta.emplace_back(velocity[i]); } // Check that all trajectories are for different bodies. auto const inserted = bodies_in_trajectories.insert(body); CHECK(inserted.second) << "Multiple trajectories for the same body"; // The final points of all trajectories must all be for the same time. times_in_trajectories.insert(time); CHECK_GE(1U, times_in_trajectories.size()) << "Inconsistent last time in trajectories"; } } { // Beyond this point we must not use the |trajectories| parameter as it is // in the wrong order with respect to the data passed to the integrator. We // use this block to hide it. Trajectories const& trajectories = reordered_trajectories; parameters.initial.time = *times_in_trajectories.cbegin() - reference_time; parameters.tmax = tmax - reference_time; parameters.Δt = Δt; parameters.sampling_period = sampling_period; parameters.tmax_is_exact = tmax_is_exact; dynamic_cast<const SPRKIntegrator<Length, Speed>*>(&integrator)->Solve( std::bind(&NBodySystem::ComputeGravitationalAccelerations, massive_trajectories, massless_trajectories, reference_time, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3), &ComputeGravitationalVelocities, parameters, &solution); // TODO(phl): Ignoring errors for now. // Loop over the time steps. for (std::size_t i = 0; i < solution.size(); ++i) { SymplecticIntegrator<Length, Speed>::SystemState const& state = solution[i]; Instant const time = state.time.value + reference_time; CHECK_EQ(state.positions.size(), state.momenta.size()); // Loop over the dimensions. for (std::size_t k = 0, t = 0; k < state.positions.size(); k += 3, ++t) { Vector<Length, InertialFrame> const position( R3Element<Length>(state.positions[k].value, state.positions[k + 1].value, state.positions[k + 2].value)); Velocity<InertialFrame> const velocity( R3Element<Speed>(state.momenta[k].value, state.momenta[k + 1].value, state.momenta[k + 2].value)); trajectories[t]->Append( time, DegreesOfFreedom<InertialFrame>(position + reference_position, velocity)); } } } } template<typename InertialFrame> void NBodySystem<InertialFrame>::ComputeGravitationalAccelerations( std::vector<Trajectory<InertialFrame> const*> const& massive_trajectories, std::vector<Trajectory<InertialFrame> const*> const& massless_trajectories, Instant const& reference_time, Time const& t, std::vector<Length> const& q, std::vector<Acceleration>* result) { result->assign(result->size(), Acceleration()); size_t const number_of_massive_trajectories = massive_trajectories.size(); size_t const number_of_massless_trajectories = massless_trajectories.size(); // Declaring variables for values like 3 * b1 + 1, 3 * b2 + 1, etc. in the // code below brings no performance advantage as it seems that the compiler is // smart enough to figure common subexpressions. for (std::size_t b1 = 0, three_b1 = 0; b1 < number_of_massive_trajectories; ++b1, three_b1 += 3) { Body const& body1 = massive_trajectories[b1]->body(); GravitationalParameter const& body1_gravitational_parameter = body1.gravitational_parameter(); bool const body1_is_oblate = body1.is_oblate(); for (std::size_t b2 = b1 + 1; b2 < massive_trajectories.size(); ++b2) { Body const& body2 = massive_trajectories[b2]->body(); GravitationalParameter const& body2_gravitational_parameter = body2.gravitational_parameter(); bool const body2_is_oblate = body2.is_oblate(); std::size_t const three_b2 = 3 * b2; Length const Δq0 = q[three_b1] - q[three_b2]; Length const Δq1 = q[three_b1 + 1] - q[three_b2 + 1]; Length const Δq2 = q[three_b1 + 2] - q[three_b2 + 2]; Exponentiation<Length, 2> const r_squared = Δq0 * Δq0 + Δq1 * Δq1 + Δq2 * Δq2; // Don't try to compute one_over_r_squared here, it makes the non-oblate // path slower. Exponentiation<Length, -3> const one_over_r_cubed = Sqrt(r_squared) / (r_squared * r_squared); auto const μ2_over_r_cubed = body2_gravitational_parameter * one_over_r_cubed; (*result)[three_b1] -= Δq0 * μ2_over_r_cubed; (*result)[three_b1 + 1] -= Δq1 * μ2_over_r_cubed; (*result)[three_b1 + 2] -= Δq2 * μ2_over_r_cubed; // Lex. III. Actioni contrariam semper & æqualem esse reactionem: // sive corporum duorum actiones in se mutuo semper esse æquales & // in partes contrarias dirigi. auto const μ1_over_r_cubed = body1_gravitational_parameter * one_over_r_cubed; (*result)[three_b2] += Δq0 * μ1_over_r_cubed; (*result)[three_b2 + 1] += Δq1 * μ1_over_r_cubed; (*result)[three_b2 + 2] += Δq2 * μ1_over_r_cubed; if (!body1_is_oblate && !body2_is_oblate) { continue; } Exponentiation<Length, -2> const one_over_r_squared = 1 / r_squared; if (body1_is_oblate) { R3Element<Acceleration> const order_2_zonal_acceleration1 = Order2ZonalAcceleration(body1, {Δq0, Δq1, Δq2}, one_over_r_squared, one_over_r_cubed); (*result)[three_b2] += order_2_zonal_acceleration1.x; (*result)[three_b2 + 1] += order_2_zonal_acceleration1.y; (*result)[three_b2 + 2] += order_2_zonal_acceleration1.z; } if (body2_is_oblate) { R3Element<Acceleration> const order_2_zonal_acceleration2 = Order2ZonalAcceleration(body2, {Δq0, Δq1, Δq2}, one_over_r_squared, one_over_r_cubed); (*result)[three_b1] += order_2_zonal_acceleration2.x; (*result)[three_b1 + 1] += order_2_zonal_acceleration2.y; (*result)[three_b1 + 2] += order_2_zonal_acceleration2.z; } } for (size_t b2 = number_of_massive_trajectories; b2 < number_of_massive_trajectories + number_of_massless_trajectories; ++b2) { std::size_t const three_b2 = 3 * b2; Length const Δq0 = q[three_b1] - q[three_b2]; Length const Δq1 = q[three_b1 + 1] - q[three_b2 + 1]; Length const Δq2 = q[three_b1 + 2] - q[three_b2 + 2]; Exponentiation<Length, 2> const r_squared = Δq0 * Δq0 + Δq1 * Δq1 + Δq2 * Δq2; Exponentiation<Length, -3> const one_over_r_cubed = Sqrt(r_squared) / (r_squared * r_squared); auto const μ1_over_r_cubed = body1_gravitational_parameter * one_over_r_cubed; (*result)[three_b2] += Δq0 * μ1_over_r_cubed; (*result)[three_b2 + 1] += Δq1 * μ1_over_r_cubed; (*result)[three_b2 + 2] += Δq2 * μ1_over_r_cubed; if (true/*!body1_is_oblate*/) { continue; } Exponentiation<Length, -2> const one_over_r_squared = 1 / r_squared; R3Element<Acceleration> const order_2_zonal_acceleration1 = Order2ZonalAcceleration(body1, {Δq0, Δq1, Δq2}, one_over_r_squared, one_over_r_cubed); (*result)[three_b2] += order_2_zonal_acceleration1.x; (*result)[three_b2 + 1] += order_2_zonal_acceleration1.y; (*result)[three_b2 + 2] += order_2_zonal_acceleration1.z; } } // Finally, take into account the intrinsic accelerations. for (size_t b2 = number_of_massive_trajectories; b2 < number_of_massive_trajectories + number_of_massless_trajectories; ++b2) { std::size_t const three_b2 = 3 * b2; Trajectory<InertialFrame> const* trajectory = massless_trajectories[b2 - number_of_massive_trajectories]; if (trajectory->has_intrinsic_acceleration()) { R3Element<Acceleration> const acceleration = trajectory->evaluate_intrinsic_acceleration( t + reference_time).coordinates(); (*result)[three_b2] += acceleration.x; (*result)[three_b2 + 1] += acceleration.y; (*result)[three_b2 + 2] += acceleration.z; } } } template<typename InertialFrame> void NBodySystem<InertialFrame>::ComputeGravitationalVelocities( std::vector<Speed> const& p, std::vector<Speed>* result) { *result = p; } } // namespace physics } // namespace principia <|endoftext|>
<commit_before> // Copyright (c) 2012, 2013 Pierre MOULON. // 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/. // An example of a minimal, self-contained bundle adjuster using Ceres // It refines Focal, Rotation and Translation of the cameras. // => A synthetic scene is used: // a random noise between [-.5,.5] is added on observed data points #include "testing/testing.h" #include "openMVG/multiview/test_data_sets.hpp" #include "openMVG/multiview/projection.hpp" // Bundle Adjustment includes #include "openMVG/bundle_adjustment/pinhole_Rtf_ceres_functor.hpp" #include "openMVG/bundle_adjustment/problem_data_container.hpp" using namespace openMVG; using namespace openMVG::bundle_adjustment; #include <cmath> #include <cstdio> #include <iostream> TEST(BUNDLE_ADJUSTMENT, EffectiveMinimization) { int nviews = 3; int npoints = 6; NViewDataSet d = NRealisticCamerasRing(nviews, npoints); // Setup a BA problem BA_Problem_data<7> ba_problem; // Configure the size of the problem ba_problem.num_cameras_ = nviews; ba_problem.num_points_ = npoints; ba_problem.num_observations_ = nviews * npoints; ba_problem.point_index_.reserve(ba_problem.num_observations_); ba_problem.camera_index_.reserve(ba_problem.num_observations_); ba_problem.observations_.reserve(2 * ba_problem.num_observations_); ba_problem.num_parameters_ = 7 * ba_problem.num_cameras_ + 3 * ba_problem.num_points_; ba_problem.parameters_.reserve(ba_problem.num_parameters_); double ppx = 500, ppy = 500; // Fill it with data (tracks and points coords) for (int i = 0; i < npoints; ++i) { // Collect the image of point i in each frame. for (int j = 0; j < nviews; ++j) { ba_problem.camera_index_.push_back(j); ba_problem.point_index_.push_back(i); const Vec2 & pt = d._x[j].col(i); // => random noise between [-.5,.5] is added ba_problem.observations_.push_back( pt(0) - ppx + rand()/RAND_MAX - .5); ba_problem.observations_.push_back( pt(1) - ppy + rand()/RAND_MAX - .5); } } // Add camera parameters (R, t, focal) for (int j = 0; j < nviews; ++j) { // Rotation matrix to angle axis std::vector<double> angleAxis(3); ceres::RotationMatrixToAngleAxis((const double*)d._R[j].data(), &angleAxis[0]); // translation Vec3 t = d._t[j]; double focal = d._K[j](0,0); ba_problem.parameters_.push_back(angleAxis[0]); ba_problem.parameters_.push_back(angleAxis[1]); ba_problem.parameters_.push_back(angleAxis[2]); ba_problem.parameters_.push_back(t[0]); ba_problem.parameters_.push_back(t[1]); ba_problem.parameters_.push_back(t[2]); ba_problem.parameters_.push_back(focal); } // Add 3D points coordinates parameters for (int i = 0; i < npoints; ++i) { Vec3 pt3D = d._X.col(i); double * ptr3D = ba_problem.mutable_points()+i*3; ba_problem.parameters_.push_back(pt3D[0]); ba_problem.parameters_.push_back(pt3D[1]); ba_problem.parameters_.push_back(pt3D[2]); } // Create residuals for each observation in the bundle adjustment problem. The // parameters for cameras and points are added automatically. ceres::Problem problem; for (int i = 0; i < ba_problem.num_observations(); ++i) { // Each Residual block takes a point and a camera as input and outputs a 2 // dimensional residual. Internally, the cost function stores the observed // image location and compares the reprojection against the observation. ceres::CostFunction* cost_function = new ceres::AutoDiffCostFunction<Pinhole_Rtf_ReprojectionError, 2, 7, 3>( new Pinhole_Rtf_ReprojectionError( ba_problem.observations()[2 * i + 0], ba_problem.observations()[2 * i + 1])); problem.AddResidualBlock(cost_function, NULL, // squared loss ba_problem.mutable_camera_for_observation(i), ba_problem.mutable_point_for_observation(i)); } // Make Ceres automatically detect the bundle structure. Note that the // standard solver, SPARSE_NORMAL_CHOLESKY, also works fine but it is slower // for standard bundle adjustment problems. ceres::Solver::Options options; options.linear_solver_type = ceres::SPARSE_SCHUR; if (ceres::IsSparseLinearAlgebraLibraryTypeAvailable(ceres::SUITE_SPARSE)) options.sparse_linear_algebra_library_type = ceres::SUITE_SPARSE; else if (ceres::IsSparseLinearAlgebraLibraryTypeAvailable(ceres::CX_SPARSE)) options.sparse_linear_algebra_library_type = ceres::CX_SPARSE; else { // No sparse backend for Ceres. // Use dense solving options.linear_solver_type = ceres::DENSE_SCHUR; } options.minimizer_progress_to_stdout = false; options.logging_type = ceres::SILENT; #ifdef USE_OPENMP options.num_threads = omp_get_num_threads(); #endif // USE_OPENMP ceres::Solver::Summary summary; ceres::Solve(options, &problem, &summary); std::cout << summary.FullReport() << "\n"; double dResidual_before = std::sqrt( summary.initial_cost / (ba_problem.num_observations_*2.)); double dResidual_after = std::sqrt( summary.final_cost / (ba_problem.num_observations_*2.)); std::cout << std::endl << " Initial RMSE : " << dResidual_before << "\n" << " Final RMSE : " << dResidual_after << "\n" << std::endl; CHECK(summary.termination_type != ceres::DID_NOT_RUN && summary.termination_type != ceres::USER_ABORT && summary.termination_type != ceres::NUMERICAL_FAILURE); EXPECT_TRUE( dResidual_before > dResidual_after); } /* ************************************************************************* */ int main() { TestResult tr; return TestRegistry::runAllTests(tr);} /* ************************************************************************* */ <commit_msg>update name of the tests. #23<commit_after> // Copyright (c) 2012, 2013 Pierre MOULON. // 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/. // An example of a minimal, self-contained bundle adjuster using Ceres // It refines Focal, Rotation and Translation of the cameras. // => A synthetic scene is used: // a random noise between [-.5,.5] is added on observed data points #include "testing/testing.h" #include "openMVG/multiview/test_data_sets.hpp" #include "openMVG/multiview/projection.hpp" // Bundle Adjustment includes #include "openMVG/bundle_adjustment/pinhole_Rtf_ceres_functor.hpp" #include "openMVG/bundle_adjustment/problem_data_container.hpp" using namespace openMVG; using namespace openMVG::bundle_adjustment; #include <cmath> #include <cstdio> #include <iostream> TEST(BUNDLE_ADJUSTMENT, EffectiveMinimization_RTf) { int nviews = 3; int npoints = 6; NViewDataSet d = NRealisticCamerasRing(nviews, npoints); // Setup a BA problem BA_Problem_data<7> ba_problem; // Configure the size of the problem ba_problem.num_cameras_ = nviews; ba_problem.num_points_ = npoints; ba_problem.num_observations_ = nviews * npoints; ba_problem.point_index_.reserve(ba_problem.num_observations_); ba_problem.camera_index_.reserve(ba_problem.num_observations_); ba_problem.observations_.reserve(2 * ba_problem.num_observations_); ba_problem.num_parameters_ = 7 * ba_problem.num_cameras_ + 3 * ba_problem.num_points_; ba_problem.parameters_.reserve(ba_problem.num_parameters_); double ppx = 500, ppy = 500; // Fill it with data (tracks and points coords) for (int i = 0; i < npoints; ++i) { // Collect the image of point i in each frame. for (int j = 0; j < nviews; ++j) { ba_problem.camera_index_.push_back(j); ba_problem.point_index_.push_back(i); const Vec2 & pt = d._x[j].col(i); // => random noise between [-.5,.5] is added ba_problem.observations_.push_back( pt(0) - ppx + rand()/RAND_MAX - .5); ba_problem.observations_.push_back( pt(1) - ppy + rand()/RAND_MAX - .5); } } // Add camera parameters (R, t, focal) for (int j = 0; j < nviews; ++j) { // Rotation matrix to angle axis std::vector<double> angleAxis(3); ceres::RotationMatrixToAngleAxis((const double*)d._R[j].data(), &angleAxis[0]); // translation Vec3 t = d._t[j]; double focal = d._K[j](0,0); ba_problem.parameters_.push_back(angleAxis[0]); ba_problem.parameters_.push_back(angleAxis[1]); ba_problem.parameters_.push_back(angleAxis[2]); ba_problem.parameters_.push_back(t[0]); ba_problem.parameters_.push_back(t[1]); ba_problem.parameters_.push_back(t[2]); ba_problem.parameters_.push_back(focal); } // Add 3D points coordinates parameters for (int i = 0; i < npoints; ++i) { Vec3 pt3D = d._X.col(i); double * ptr3D = ba_problem.mutable_points()+i*3; ba_problem.parameters_.push_back(pt3D[0]); ba_problem.parameters_.push_back(pt3D[1]); ba_problem.parameters_.push_back(pt3D[2]); } // Create residuals for each observation in the bundle adjustment problem. The // parameters for cameras and points are added automatically. ceres::Problem problem; for (int i = 0; i < ba_problem.num_observations(); ++i) { // Each Residual block takes a point and a camera as input and outputs a 2 // dimensional residual. Internally, the cost function stores the observed // image location and compares the reprojection against the observation. ceres::CostFunction* cost_function = new ceres::AutoDiffCostFunction<Pinhole_Rtf_ReprojectionError, 2, 7, 3>( new Pinhole_Rtf_ReprojectionError( ba_problem.observations()[2 * i + 0], ba_problem.observations()[2 * i + 1])); problem.AddResidualBlock(cost_function, NULL, // squared loss ba_problem.mutable_camera_for_observation(i), ba_problem.mutable_point_for_observation(i)); } // Make Ceres automatically detect the bundle structure. Note that the // standard solver, SPARSE_NORMAL_CHOLESKY, also works fine but it is slower // for standard bundle adjustment problems. ceres::Solver::Options options; options.linear_solver_type = ceres::SPARSE_SCHUR; if (ceres::IsSparseLinearAlgebraLibraryTypeAvailable(ceres::SUITE_SPARSE)) options.sparse_linear_algebra_library_type = ceres::SUITE_SPARSE; else if (ceres::IsSparseLinearAlgebraLibraryTypeAvailable(ceres::CX_SPARSE)) options.sparse_linear_algebra_library_type = ceres::CX_SPARSE; else { // No sparse backend for Ceres. // Use dense solving options.linear_solver_type = ceres::DENSE_SCHUR; } options.minimizer_progress_to_stdout = false; options.logging_type = ceres::SILENT; #ifdef USE_OPENMP options.num_threads = omp_get_num_threads(); #endif // USE_OPENMP ceres::Solver::Summary summary; ceres::Solve(options, &problem, &summary); std::cout << summary.FullReport() << "\n"; double dResidual_before = std::sqrt( summary.initial_cost / (ba_problem.num_observations_*2.)); double dResidual_after = std::sqrt( summary.final_cost / (ba_problem.num_observations_*2.)); std::cout << std::endl << " Initial RMSE : " << dResidual_before << "\n" << " Final RMSE : " << dResidual_after << "\n" << std::endl; CHECK(summary.termination_type != ceres::DID_NOT_RUN && summary.termination_type != ceres::USER_ABORT && summary.termination_type != ceres::NUMERICAL_FAILURE); EXPECT_TRUE( dResidual_before > dResidual_after); } TEST(BUNDLE_ADJUSTMENT, EffectiveMinimization_RT_f) { int nviews = 3; int npoints = 6; NViewDataSet d = NRealisticCamerasRing(nviews, npoints); // Setup a BA problem BA_Problem_data<7> ba_problem; // Configure the size of the problem ba_problem.num_cameras_ = nviews; ba_problem.num_points_ = npoints; ba_problem.num_observations_ = nviews * npoints; ba_problem.point_index_.reserve(ba_problem.num_observations_); ba_problem.camera_index_.reserve(ba_problem.num_observations_); ba_problem.observations_.reserve(2 * ba_problem.num_observations_); ba_problem.num_parameters_ = 7 * ba_problem.num_cameras_ + 3 * ba_problem.num_points_; ba_problem.parameters_.reserve(ba_problem.num_parameters_); double ppx = 500, ppy = 500; // Fill it with data (tracks and points coords) for (int i = 0; i < npoints; ++i) { // Collect the image of point i in each frame. for (int j = 0; j < nviews; ++j) { ba_problem.camera_index_.push_back(j); ba_problem.point_index_.push_back(i); const Vec2 & pt = d._x[j].col(i); // => random noise between [-.5,.5] is added ba_problem.observations_.push_back( pt(0) - ppx + rand()/RAND_MAX - .5); ba_problem.observations_.push_back( pt(1) - ppy + rand()/RAND_MAX - .5); } } // Add camera parameters (R, t, focal) for (int j = 0; j < nviews; ++j) { // Rotation matrix to angle axis std::vector<double> angleAxis(3); ceres::RotationMatrixToAngleAxis((const double*)d._R[j].data(), &angleAxis[0]); // translation Vec3 t = d._t[j]; double focal = d._K[j](0,0); ba_problem.parameters_.push_back(angleAxis[0]); ba_problem.parameters_.push_back(angleAxis[1]); ba_problem.parameters_.push_back(angleAxis[2]); ba_problem.parameters_.push_back(t[0]); ba_problem.parameters_.push_back(t[1]); ba_problem.parameters_.push_back(t[2]); ba_problem.parameters_.push_back(focal); } // Add 3D points coordinates parameters for (int i = 0; i < npoints; ++i) { Vec3 pt3D = d._X.col(i); double * ptr3D = ba_problem.mutable_points()+i*3; ba_problem.parameters_.push_back(pt3D[0]); ba_problem.parameters_.push_back(pt3D[1]); ba_problem.parameters_.push_back(pt3D[2]); } // Create residuals for each observation in the bundle adjustment problem. The // parameters for cameras and points are added automatically. ceres::Problem problem; for (int i = 0; i < ba_problem.num_observations(); ++i) { // Each Residual block takes a point and a camera as input and outputs a 2 // dimensional residual. Internally, the cost function stores the observed // image location and compares the reprojection against the observation. ceres::CostFunction* cost_function = new ceres::AutoDiffCostFunction<Pinhole_Rtf_ReprojectionError, 2, 7, 3>( new Pinhole_Rtf_ReprojectionError( ba_problem.observations()[2 * i + 0], ba_problem.observations()[2 * i + 1])); problem.AddResidualBlock(cost_function, NULL, // squared loss ba_problem.mutable_camera_for_observation(i), ba_problem.mutable_point_for_observation(i)); } // Make Ceres automatically detect the bundle structure. Note that the // standard solver, SPARSE_NORMAL_CHOLESKY, also works fine but it is slower // for standard bundle adjustment problems. ceres::Solver::Options options; options.linear_solver_type = ceres::SPARSE_SCHUR; if (ceres::IsSparseLinearAlgebraLibraryTypeAvailable(ceres::SUITE_SPARSE)) options.sparse_linear_algebra_library_type = ceres::SUITE_SPARSE; else if (ceres::IsSparseLinearAlgebraLibraryTypeAvailable(ceres::CX_SPARSE)) options.sparse_linear_algebra_library_type = ceres::CX_SPARSE; else { // No sparse backend for Ceres. // Use dense solving options.linear_solver_type = ceres::DENSE_SCHUR; } options.minimizer_progress_to_stdout = false; options.logging_type = ceres::SILENT; #ifdef USE_OPENMP options.num_threads = omp_get_num_threads(); #endif // USE_OPENMP ceres::Solver::Summary summary; ceres::Solve(options, &problem, &summary); std::cout << summary.FullReport() << "\n"; double dResidual_before = std::sqrt( summary.initial_cost / (ba_problem.num_observations_*2.)); double dResidual_after = std::sqrt( summary.final_cost / (ba_problem.num_observations_*2.)); std::cout << std::endl << " Initial RMSE : " << dResidual_before << "\n" << " Final RMSE : " << dResidual_after << "\n" << std::endl; CHECK(summary.termination_type != ceres::DID_NOT_RUN && summary.termination_type != ceres::USER_ABORT && summary.termination_type != ceres::NUMERICAL_FAILURE); EXPECT_TRUE( dResidual_before > dResidual_after); } /* ************************************************************************* */ int main() { TestResult tr; return TestRegistry::runAllTests(tr);} /* ************************************************************************* */ <|endoftext|>
<commit_before>#include <iostream> #include <iomanip> #include <fstream> #include <vector> #include <algorithm> #include <cmath> #include <time.h> #include <string> #include <cassert> #include "KDTree.hpp" #include "MWC.hpp" using namespace std; //#define VERBOSE void BenchMark(const int numPoints); const Point& BruteForceNearestNeighbour(const vector<Point*>& pointList, const Point& point); //______________________________________________________________________________ int main(int argc, char **argv) { BenchMark(100); return 0; } //______________________________________________________________________________ void BenchMark(const int numPoints) { // -- Benchmark builds 'numPoints' random points, constructs a kd-tree of these points // -- then tests how long it takes to calculate the nearest neighbour of some random search point // -- against an brute-force search cout << "Benchmarking kd-tree nearest neighbour search, against brute-force search" << endl; //----------------------------------------------------------- // -- Generate random points MWC rng; vector<Point*> points; for (int i=0; i<numPoints; i++) { points.push_back(new Point(rng.rnd(),rng.rnd(),rng.rnd())); } // Print points #ifdef VERBOSE cout << "--------------------" << endl; cout << "Input Points" << endl; vector<Point*>::iterator it; for (it = points.begin(); it != points.end(); it++) { cout << it - points.begin() << "\t" << (*it)->ToString() << endl; } cout << "--------------------" << endl; #endif //----------------------------------------------------------- // -- Build Tree // Set up timing clock_t start, end; start = clock(); KDTree tree(points); // Output time to build tree end = clock(); const double treeBuildTime = (double)(end-start)/CLOCKS_PER_SEC; cout << "--------------------" << endl; cout << "Number of points in Tree: " << numPoints << endl; cout << "Time required to build Tree: "; cout << treeBuildTime; cout << " seconds." << endl; //----------------------------------------------------------- Point searchPoint(rng.rnd(),rng.rnd(),rng.rnd()); #ifdef VERBOSE cout << "--------------------" << endl; cout << "Search Point: " << searchPoint.ToString() << endl; #endif //----------------------------------------------------------- // -- Perform Brute force search for point // Set up timing start = clock(); cout << "--------------------" << endl; cout << "Performing Brute Force Search..." << endl; const Point& brutePoint = BruteForceNearestNeighbour(points, searchPoint); // Output time to build tree end = clock(); const double bruteForceTime = (double)(end-start)/CLOCKS_PER_SEC; //----------------------------------------------------------- // -- Perform Tree-based search for point // Set up timing start = clock(); cout << "--------------------" << endl; cout << "Performing Tree-based Search..." << endl; const Point& treePoint = tree.NearestNeighbour(searchPoint); // calculate time to build tree end = clock(); const double treeSearchTime = (double)(end-start)/CLOCKS_PER_SEC; //----------------------------------------------------------- cout << "--------------------" << endl; cout << "Brute force solution: " << brutePoint.ToString() << endl; cout << "Time required for Brute force search: "; cout << bruteForceTime; cout << " seconds." << endl; cout << "--------------------" << endl; cout << "Tree solution: " << treePoint.ToString() << endl; cout << "Time required for Tree search: "; cout << treeSearchTime; cout << " seconds." << endl; cout << "--------------------" << endl; assert(treePoint == brutePoint); } //______________________________________________________________________________ const Point& BruteForceNearestNeighbour(const vector<Point*>& pointList, const Point& point) { // Take list of points and do a brute force search to find the nearest neighbour // Return nearest neighbour double currentBestDist = 0.0; int currentBestPoint = 0; vector<Point*>::const_iterator it; for (it = pointList.begin(); it != pointList.end(); it++) { double dist = (*it)->DistanceTo(point); #ifdef VERBOSE cout << setfill(' ') << setw(20); cout << (*it)->ToString(); cout << "\t" << dist << endl; #endif if (currentBestDist == 0.0 || dist < currentBestDist) { currentBestDist = dist; currentBestPoint = it - pointList.begin(); } } return *(pointList[currentBestPoint]); } <commit_msg>Updated Benchmark to calculate average and stdDev<commit_after>#include <iostream> #include <iomanip> #include <fstream> #include <vector> #include <algorithm> #include <cmath> #include <time.h> #include <string> #include <cassert> #include "KDTree.hpp" #include "MWC.hpp" using namespace std; //#define VERBOSE void BenchMark(const int numPoints, const int repetitions, ostream& out); const Point& BruteForceNearestNeighbour(const vector<Point*>& pointList, const Point& point); //______________________________________________________________________________ int main(int argc, char **argv) { ofstream out("benchmark_data.txt"); out << "Num Points" << "\t" << "Brute Force Time" << "\t" << "Tree Search Time" << "\t"; out << "Std Dev Brute Force" << "\t" << "Std Dev Tree Search" << endl; BenchMark(10, 10, out); BenchMark(100, 10, out); BenchMark(1000, 10, out); BenchMark(10000, 10, out); BenchMark(100000, 10, out); BenchMark(1000000, 10, out); BenchMark(10000000, 10, out); return 0; } //______________________________________________________________________________ void BenchMark(const int numPoints, const int repetitions, ostream& out) { // -- Benchmark builds 'numPoints' random points, constructs a kd-tree of these points // -- then tests how long it takes to calculate the nearest neighbour of some random search point // -- against an brute-force search #ifdef VERBOSE cout << "Benchmarking kd-tree nearest neighbour search, against brute-force search" << endl; #endif //----------------------------------------------------------- // -- Generate random points MWC rng; vector<Point*> points; for (int i=0; i<numPoints; i++) { points.push_back(new Point(rng.rnd(),rng.rnd(),rng.rnd())); } // Print points #ifdef VERBOSE cout << "--------------------" << endl; cout << "Input Points" << endl; vector<Point*>::iterator it; for (it = points.begin(); it != points.end(); it++) { cout << it - points.begin() << "\t" << (*it)->ToString() << endl; } cout << "--------------------" << endl; #endif //----------------------------------------------------------- // -- Build Tree // Set up timing clock_t start, end; start = clock(); KDTree tree(points); // Output time to build tree end = clock(); const double treeBuildTime = (double)(end-start)/CLOCKS_PER_SEC; cout << "--------------------" << endl; cout << "Number of points in Tree: " << numPoints << endl; cout << "Time required to build Tree: "; cout << treeBuildTime; cout << " seconds." << endl; //----------------------------------------------------------- // Repeat search for number of times defined by 'repetitions' // Store all times in vector for averaging and std dev double totBruteForceTime = 0.; double totTreeSearchTime = 0.; vector<double> bruteForceTimes; vector<double> treeSearchTimes; for (int iter = 0; iter < repetitions; iter++) { Point searchPoint(rng.rnd(),rng.rnd(),rng.rnd()); #ifdef VERBOSE cout << "--------------------" << endl; cout << "Search Point: " << searchPoint.ToString() << endl; #endif //----------------------------------------------------------- // -- Perform Brute force search for point // Set up timing start = clock(); #ifdef VERBOSE cout << "--------------------" << endl; cout << "Performing Brute Force Search..." << endl; #endif const Point& brutePoint = BruteForceNearestNeighbour(points, searchPoint); // Output time to build tree end = clock(); const double bruteForceTime = (double)(end-start)/CLOCKS_PER_SEC; //----------------------------------------------------------- // -- Perform Tree-based search for point // Set up timing start = clock(); #ifdef VERBOSE cout << "--------------------" << endl; cout << "Performing Tree-based Search..." << endl; #endif const Point& treePoint = tree.NearestNeighbour(searchPoint); // calculate time to build tree end = clock(); const double treeSearchTime = (double)(end-start)/CLOCKS_PER_SEC; //----------------------------------------------------------- #ifdef VERBOSE cout << "--------------------" << endl; cout << "Brute force solution: " << brutePoint.ToString() << endl; cout << "Time required for Brute force search: "; cout << bruteForceTime; cout << " seconds." << endl; cout << "--------------------" << endl; cout << "Tree solution: " << treePoint.ToString() << endl; cout << "Time required for Tree search: "; cout << treeSearchTime; cout << " seconds." << endl; cout << "--------------------" << endl; #endif assert(treePoint == brutePoint); bruteForceTimes.push_back(bruteForceTime); treeSearchTimes.push_back(treeSearchTime); totBruteForceTime += bruteForceTime; totTreeSearchTime += treeSearchTime; } // Calculate mean search times double avgBruteForceTime = totBruteForceTime/repetitions; double avgTreeSearchTime = totTreeSearchTime/repetitions; // Calculate Std Dev double sumBrute = 0.; double sumTree = 0.; for (int iter = 0; iter < repetitions; iter++) { sumBrute += pow((bruteForceTimes[iter] - avgBruteForceTime), 2.0); sumTree += pow((treeSearchTimes[iter] - avgTreeSearchTime), 2.0); } double stdDevBrute = sqrt(sumBrute/(repetitions-1)); double stdDevTree = sqrt(sumTree/(repetitions-1)); #ifdef VERBOSE cout << "--------------------" << endl; cout << "Average Time required for Brute force search: "; cout << avgBruteForceTime; cout << " seconds." << endl; cout << "--------------------" << endl; cout << "Average Time required for Tree search: "; cout << avgTreeSearchTime; cout << " seconds." << endl; cout << "--------------------" << endl; #endif out << numPoints << "\t" << avgBruteForceTime << "\t" << avgTreeSearchTime << "\t"; out << stdDevBrute << "\t" << stdDevTree << endl; return; } //______________________________________________________________________________ const Point& BruteForceNearestNeighbour(const vector<Point*>& pointList, const Point& point) { // Take list of points and do a brute force search to find the nearest neighbour // Return nearest neighbour double currentBestDist = 0.0; int currentBestPoint = 0; vector<Point*>::const_iterator it; for (it = pointList.begin(); it != pointList.end(); it++) { double dist = (*it)->DistanceTo(point); #ifdef VERBOSE cout << setfill(' ') << setw(20); cout << (*it)->ToString(); cout << "\t" << dist << endl; #endif if (currentBestDist == 0.0 || dist < currentBestDist) { currentBestDist = dist; currentBestPoint = it - pointList.begin(); } } return *(pointList[currentBestPoint]); } <|endoftext|>
<commit_before>/* * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <boost/algorithm/string.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/xml_parser.hpp> #include <osquery/config.h> #include <osquery/core.h> #include <osquery/logger.h> #include <osquery/tables.h> #include "osquery/core/conversions.h" #include "osquery/core/json.h" #include "osquery/core/windows/wmi.h" #include "osquery/events/windows/windows_event_log.h" #include "osquery/filesystem/fileops.h" namespace pt = boost::property_tree; namespace osquery { /* * @brief the Windows Event log channels to subscribe to * * By default we subscribe to all system channels. To subscribe to additional * channels specify them via this flag as a comma separated list. */ FLAG(string, windows_event_channels, "System,Application,Setup,Security", "Comma-separated list of Windows event log channels"); class WindowsEventSubscriber : public EventSubscriber<WindowsEventLogEventPublisher> { public: Status init() override { auto wc = createSubscriptionContext(); for (auto& chan : osquery::split(FLAGS_windows_event_channels, ",")) { // We remove quotes if they exist boost::erase_all(chan, "\""); boost::erase_all(chan, "\'"); wc->sources.insert(stringToWstring(chan)); } subscribe(&WindowsEventSubscriber::Callback, wc); return Status(0, "OK"); } Status Callback(const ECRef& ec, const SCRef& sc); }; REGISTER(WindowsEventSubscriber, "event_subscriber", "windows_events"); /// Helper function to recursively parse a boost ptree void parseTree(const pt::ptree& tree, std::map<std::string, std::string>& res) { for (const auto& node : tree) { auto nodeName = node.second.get("<xmlattr>.Name", ""); if (nodeName.empty()) { nodeName = node.first.empty() ? "DataElement" : node.first; } res[nodeName] = res[nodeName] == "" ? node.second.data() : res[nodeName] + "," + node.second.data(); parseTree(node.second, res); } } Status WindowsEventSubscriber::Callback(const ECRef& ec, const SCRef& sc) { Row r; FILETIME cTime; GetSystemTimeAsFileTime(&cTime); r["time"] = BIGINT(filetimeToUnixtime(cTime)); r["datetime"] = ec->eventRecord.get("Event.System.TimeCreated.<xmlattr>.SystemTime", ""); r["source"] = ec->eventRecord.get("Event.System.Channel", ""); r["provider_name"] = ec->eventRecord.get("Event.System.Provider.<xmlattr>.Name", ""); r["provider_guid"] = ec->eventRecord.get("Event.System.Provider.<xmlattr>.Guid", ""); r["eventid"] = INTEGER(ec->eventRecord.get("Event.System.EventID", -1)); r["task"] = INTEGER(ec->eventRecord.get("Event.System.Task", -1)); r["level"] = INTEGER(ec->eventRecord.get("Event.System.Level", -1)); r["keywords"] = BIGINT(ec->eventRecord.get("Event.System.Keywords", -1)); /* * From the MSDN definition of the Event Schema, each event will have * an XML choice element containing the event data, if any. The first * iteration enumerates this choice, and the second iteration enumerates * all data elements belonging to the choice. */ pt::ptree jsonOut; std::map<std::string, std::string> results; std::string eventDataType; for (const auto& node : ec->eventRecord.get_child("Event", pt::ptree())) { /// We have already processed the System event data above if (node.first == "System" || node.first == "<xmlattr>") { continue; } eventDataType = node.first; parseTree(node.second, results); } for (const auto& val : results) { /// Reconstruct the event format as much as possible jsonOut.put(eventDataType + "." + val.first, val.second); } std::stringstream ss; boost::property_tree::write_json(ss, jsonOut, false); r["data"] = ss.str(); add(r); return Status(0, "OK"); } } <commit_msg>events: removing newline from windows event log lines (#3985)<commit_after>/* * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <boost/algorithm/string.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/xml_parser.hpp> #include <osquery/config.h> #include <osquery/core.h> #include <osquery/logger.h> #include <osquery/tables.h> #include "osquery/core/conversions.h" #include "osquery/core/json.h" #include "osquery/core/windows/wmi.h" #include "osquery/events/windows/windows_event_log.h" #include "osquery/filesystem/fileops.h" namespace pt = boost::property_tree; namespace osquery { /* * @brief the Windows Event log channels to subscribe to * * By default we subscribe to all system channels. To subscribe to additional * channels specify them via this flag as a comma separated list. */ FLAG(string, windows_event_channels, "System,Application,Setup,Security", "Comma-separated list of Windows event log channels"); class WindowsEventSubscriber : public EventSubscriber<WindowsEventLogEventPublisher> { public: Status init() override { auto wc = createSubscriptionContext(); for (auto& chan : osquery::split(FLAGS_windows_event_channels, ",")) { // We remove quotes if they exist boost::erase_all(chan, "\""); boost::erase_all(chan, "\'"); wc->sources.insert(stringToWstring(chan)); } subscribe(&WindowsEventSubscriber::Callback, wc); return Status(0, "OK"); } Status Callback(const ECRef& ec, const SCRef& sc); }; REGISTER(WindowsEventSubscriber, "event_subscriber", "windows_events"); /// Helper function to recursively parse a boost ptree void parseTree(const pt::ptree& tree, std::map<std::string, std::string>& res) { for (const auto& node : tree) { auto nodeName = node.second.get("<xmlattr>.Name", ""); if (nodeName.empty()) { nodeName = node.first.empty() ? "DataElement" : node.first; } res[nodeName] = res[nodeName] == "" ? node.second.data() : res[nodeName] + "," + node.second.data(); parseTree(node.second, res); } } Status WindowsEventSubscriber::Callback(const ECRef& ec, const SCRef& sc) { Row r; FILETIME cTime; GetSystemTimeAsFileTime(&cTime); r["time"] = BIGINT(filetimeToUnixtime(cTime)); r["datetime"] = ec->eventRecord.get("Event.System.TimeCreated.<xmlattr>.SystemTime", ""); r["source"] = ec->eventRecord.get("Event.System.Channel", ""); r["provider_name"] = ec->eventRecord.get("Event.System.Provider.<xmlattr>.Name", ""); r["provider_guid"] = ec->eventRecord.get("Event.System.Provider.<xmlattr>.Guid", ""); r["eventid"] = INTEGER(ec->eventRecord.get("Event.System.EventID", -1)); r["task"] = INTEGER(ec->eventRecord.get("Event.System.Task", -1)); r["level"] = INTEGER(ec->eventRecord.get("Event.System.Level", -1)); r["keywords"] = BIGINT(ec->eventRecord.get("Event.System.Keywords", -1)); /* * From the MSDN definition of the Event Schema, each event will have * an XML choice element containing the event data, if any. The first * iteration enumerates this choice, and the second iteration enumerates * all data elements belonging to the choice. */ pt::ptree jsonOut; std::map<std::string, std::string> results; std::string eventDataType; for (const auto& node : ec->eventRecord.get_child("Event", pt::ptree())) { /// We have already processed the System event data above if (node.first == "System" || node.first == "<xmlattr>") { continue; } eventDataType = node.first; parseTree(node.second, results); } for (const auto& val : results) { /// Reconstruct the event format as much as possible jsonOut.put(eventDataType + "." + val.first, val.second); } std::stringstream ss; boost::property_tree::write_json(ss, jsonOut, false); auto s = ss.str(); if (s.at(s.size() - 1) == '\n') { s.erase(s.end()); } r["data"] = s; add(r); return Status(0, "OK"); } } <|endoftext|>
<commit_before>#define FP_T double #include "Units.hpp" #include <iostream> using namespace std; int main() { using namespace SI; typedef Value<Velocity> MpS; typedef Value<Acceleration> MpSS; typedef Value<Force> Newton; auto sum = 100.0_m + 22.0_m; MpS velocity = 5.0_m / 20._s; Meter fall = velocity * 20.4_s + .5 * MpSS(-9.8) * 20.4_s * 20.4_s; Newton grav_force = 100.0_kg * MpSS(9.8); Watt elec_power = Ampere(15) * Volt(20); Joule heat_added = Value<SpecificHeat>(4.1813) * 10.0_kg * 5.0_K; cout << "Value of 100m + 22m = " << sum << endl; cout << "Value of 5m / 20s = " << velocity << endl; cout << "Fall distance of an object on earth after 20.4s in meters with initial velocity .25m/s = " << fall << endl; cout << "Gravitational force on 100kg mass = " << grav_force << "N" << endl; cout << "Electrical Power of circuit with 15A current and 20V potential = " << elec_power << "W" << endl; cout << "Energy needed to raise 10kg of water 5C (5K) using 4.1813 as specific heat = " << heat_added << "J" << endl; cout.flush(); return 0; } <commit_msg>Removed dead code<commit_after>#define FP_T double #include "Units.hpp" #include <iostream> using namespace std; int main() { using namespace SI; typedef Value<Velocity> MpS; typedef Value<Acceleration> MpSS; typedef Value<Force> Newton; auto sum = 100.0_m + 22.0_m; MpS velocity = 5.0_m / 20._s; Meter fall = velocity * 20.4_s + .5 * MpSS(-9.8) * 20.4_s * 20.4_s; Newton grav_force = 100.0_kg * MpSS(9.8); Watt elec_power = Ampere(15) * Volt(20); Joule heat_added = Value<SpecificHeat>(4.1813) * 10.0_kg * 5.0_K; cout << "Value of 100m + 22m = " << sum << endl; cout << "Value of 5m / 20s = " << velocity << endl; cout << "Fall distance of an object on earth after 20.4s in meters with initial velocity .25m/s = " << fall << endl; cout << "Gravitational force on 100kg mass = " << grav_force << "N" << endl; cout << "Electrical Power of circuit with 15A current and 20V potential = " << elec_power << "W" << endl; cout << "Energy needed to raise 10kg of water 5C (5K) using 4.1813 as specific heat = " << heat_added << "J" << endl; return 0; } <|endoftext|>
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2005 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #include "FreeTypeFont.h" #include <osg/Notify> #include <osgDB/WriteFile> FreeTypeFont::FreeTypeFont(const std::string& filename, FT_Face face): _filename(filename), _face(face) { } FreeTypeFont::~FreeTypeFont() { } void FreeTypeFont::setFontResolution(unsigned int width, unsigned int height) { if (width+2*_facade->getGlyphImageMargin()>_facade->getTextureWidthHint() || height+2*_facade->getGlyphImageMargin()>_facade->getTextureHeightHint()) { osg::notify(osg::WARN)<<"Warning: FreeTypeFont::setSize("<<width<<","<<height<<") sizes too large,"<<std::endl; width = _facade->getTextureWidthHint()-2*_facade->getGlyphImageMargin(); height = _facade->getTextureHeightHint()-2*_facade->getGlyphImageMargin(); osg::notify(osg::WARN)<<" sizes capped ("<<width<<","<<height<<") to fit int current glyph texture size."<<std::endl; } FT_Error error = FT_Set_Pixel_Sizes( _face, /* handle to face object */ width, /* pixel_width */ height ); /* pixel_height */ if (error) { osg::notify(osg::WARN)<<"FT_Set_Pixel_Sizes() - error "<<error<<std::endl; } else { setFontWidth(width); setFontHeight(height); } } osgText::Font::Glyph* FreeTypeFont::getGlyph(unsigned int charcode) { FT_Error error = FT_Load_Char( _face, charcode, FT_LOAD_RENDER|FT_LOAD_NO_BITMAP ); if (error) { osg::notify(osg::WARN) << "FT_Load_Char(...) error "<<error<<std::endl; return 0; } FT_GlyphSlot glyphslot = _face->glyph; int pitch = glyphslot->bitmap.pitch; unsigned char* buffer = glyphslot->bitmap.buffer; unsigned int sourceWidth = glyphslot->bitmap.width;; unsigned int sourceHeight = glyphslot->bitmap.rows; unsigned int margin = _facade->getGlyphImageMargin(); unsigned int width = sourceWidth+2*margin; unsigned int height = sourceHeight+2*margin; osg::ref_ptr<osgText::Font::Glyph> glyph = new osgText::Font::Glyph; #ifdef OSG_FONT_USE_LUMINANCE_ALPHA unsigned int dataSize = width*height*2; unsigned char* data = new unsigned char[dataSize]; // clear the image to zeros. for(unsigned char* p=data;p<data+dataSize;) { *p++ = 255; *p++ = 0; } glyph->setImage(width,height,1, GL_LUMINANCE_ALPHA, GL_LUMINANCE_ALPHA,GL_UNSIGNED_BYTE, data, osg::Image::USE_NEW_DELETE, 1); glyph->setInternalTextureFormat(GL_LUMINANCE_ALPHA); // skip the top margin data += (margin*width)*2; // copy image across to osgText::Glyph image. for(int r=sourceHeight-1;r>=0;--r) { data+=2*margin; // skip the left margin unsigned char* ptr = buffer+r*pitch; for(unsigned int c=0;c<sourceWidth;++c,++ptr) { (*data++)=255; (*data++)=*ptr; } data+=2*margin; // skip the right margin. } #else unsigned int dataSize = width*height; unsigned char* data = new unsigned char[dataSize]; // clear the image to zeros. for(unsigned char* p=data;p<data+dataSize;) { *p++ = 0; } glyph->setImage(width,height,1, GL_ALPHA, GL_ALPHA,GL_UNSIGNED_BYTE, data, osg::Image::USE_NEW_DELETE, 1); glyph->setInternalTextureFormat(GL_ALPHA); // skip the top margin data += (margin*width); // copy image across to osgText::Glyph image. for(int r=sourceHeight-1;r>=0;--r) { data+=margin; // skip the left margin unsigned char* ptr = buffer+r*pitch; for(unsigned int c=0;c<sourceWidth;++c,++ptr) { (*data++)=*ptr; } data+=margin; // skip the right margin. } #endif FT_Glyph_Metrics* metrics = &(glyphslot->metrics); glyph->setHorizontalBearing(osg::Vec2((float)metrics->horiBearingX/64.0f,(float)(metrics->horiBearingY-metrics->height)/64.0f)); // bottom left. glyph->setHorizontalAdvance((float)metrics->horiAdvance/64.0f); glyph->setVerticalBearing(osg::Vec2((float)metrics->vertBearingX/64.0f,(float)(metrics->vertBearingY-metrics->height)/64.0f)); // top middle. glyph->setVerticalAdvance((float)metrics->vertAdvance/64.0f); addGlyph(_facade->getFontWidth(),_facade->getFontHeight(),charcode,glyph.get()); // cout << " in getGlyph() implementation="<<this<<" "<<_filename<<" facade="<<_facade<<endl; return glyph.get(); } osg::Vec2 FreeTypeFont::getKerning(unsigned int leftcharcode,unsigned int rightcharcode, osgText::KerningType kerningType) { if (!FT_HAS_KERNING(_face) || (kerningType == osgText::KERNING_NONE)) return osg::Vec2(0.0f,0.0f); FT_Kerning_Mode mode = (kerningType==osgText::KERNING_DEFAULT) ? ft_kerning_default : ft_kerning_unfitted; // convert character code to glyph index FT_UInt left = FT_Get_Char_Index( _face, leftcharcode ); FT_UInt right = FT_Get_Char_Index( _face, rightcharcode ); // get the kerning distances. FT_Vector kerning; FT_Error error = FT_Get_Kerning( _face, // handle to face object left, // left glyph index right, // right glyph index mode, // kerning mode &kerning ); // target vector if (error) { return osg::Vec2(0.0f,0.0f); } return osg::Vec2((float)kerning.x/64.0f,(float)kerning.y/64.0f); } bool FreeTypeFont::hasVertical() const { return FT_HAS_VERTICAL(_face)!=0; } <commit_msg>From Garrat Potts, fixed face memory leak in FreTypeFont destructor.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2005 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #include "FreeTypeFont.h" #include <osg/Notify> #include <osgDB/WriteFile> FreeTypeFont::FreeTypeFont(const std::string& filename, FT_Face face): _filename(filename), _face(face) { } FreeTypeFont::~FreeTypeFont() { if(_face) { FT_Done_Face(_face); _face = 0; } } void FreeTypeFont::setFontResolution(unsigned int width, unsigned int height) { if (width+2*_facade->getGlyphImageMargin()>_facade->getTextureWidthHint() || height+2*_facade->getGlyphImageMargin()>_facade->getTextureHeightHint()) { osg::notify(osg::WARN)<<"Warning: FreeTypeFont::setSize("<<width<<","<<height<<") sizes too large,"<<std::endl; width = _facade->getTextureWidthHint()-2*_facade->getGlyphImageMargin(); height = _facade->getTextureHeightHint()-2*_facade->getGlyphImageMargin(); osg::notify(osg::WARN)<<" sizes capped ("<<width<<","<<height<<") to fit int current glyph texture size."<<std::endl; } FT_Error error = FT_Set_Pixel_Sizes( _face, /* handle to face object */ width, /* pixel_width */ height ); /* pixel_height */ if (error) { osg::notify(osg::WARN)<<"FT_Set_Pixel_Sizes() - error "<<error<<std::endl; } else { setFontWidth(width); setFontHeight(height); } } osgText::Font::Glyph* FreeTypeFont::getGlyph(unsigned int charcode) { FT_Error error = FT_Load_Char( _face, charcode, FT_LOAD_RENDER|FT_LOAD_NO_BITMAP ); if (error) { osg::notify(osg::WARN) << "FT_Load_Char(...) error "<<error<<std::endl; return 0; } FT_GlyphSlot glyphslot = _face->glyph; int pitch = glyphslot->bitmap.pitch; unsigned char* buffer = glyphslot->bitmap.buffer; unsigned int sourceWidth = glyphslot->bitmap.width;; unsigned int sourceHeight = glyphslot->bitmap.rows; unsigned int margin = _facade->getGlyphImageMargin(); unsigned int width = sourceWidth+2*margin; unsigned int height = sourceHeight+2*margin; osg::ref_ptr<osgText::Font::Glyph> glyph = new osgText::Font::Glyph; #ifdef OSG_FONT_USE_LUMINANCE_ALPHA unsigned int dataSize = width*height*2; unsigned char* data = new unsigned char[dataSize]; // clear the image to zeros. for(unsigned char* p=data;p<data+dataSize;) { *p++ = 255; *p++ = 0; } glyph->setImage(width,height,1, GL_LUMINANCE_ALPHA, GL_LUMINANCE_ALPHA,GL_UNSIGNED_BYTE, data, osg::Image::USE_NEW_DELETE, 1); glyph->setInternalTextureFormat(GL_LUMINANCE_ALPHA); // skip the top margin data += (margin*width)*2; // copy image across to osgText::Glyph image. for(int r=sourceHeight-1;r>=0;--r) { data+=2*margin; // skip the left margin unsigned char* ptr = buffer+r*pitch; for(unsigned int c=0;c<sourceWidth;++c,++ptr) { (*data++)=255; (*data++)=*ptr; } data+=2*margin; // skip the right margin. } #else unsigned int dataSize = width*height; unsigned char* data = new unsigned char[dataSize]; // clear the image to zeros. for(unsigned char* p=data;p<data+dataSize;) { *p++ = 0; } glyph->setImage(width,height,1, GL_ALPHA, GL_ALPHA,GL_UNSIGNED_BYTE, data, osg::Image::USE_NEW_DELETE, 1); glyph->setInternalTextureFormat(GL_ALPHA); // skip the top margin data += (margin*width); // copy image across to osgText::Glyph image. for(int r=sourceHeight-1;r>=0;--r) { data+=margin; // skip the left margin unsigned char* ptr = buffer+r*pitch; for(unsigned int c=0;c<sourceWidth;++c,++ptr) { (*data++)=*ptr; } data+=margin; // skip the right margin. } #endif FT_Glyph_Metrics* metrics = &(glyphslot->metrics); glyph->setHorizontalBearing(osg::Vec2((float)metrics->horiBearingX/64.0f,(float)(metrics->horiBearingY-metrics->height)/64.0f)); // bottom left. glyph->setHorizontalAdvance((float)metrics->horiAdvance/64.0f); glyph->setVerticalBearing(osg::Vec2((float)metrics->vertBearingX/64.0f,(float)(metrics->vertBearingY-metrics->height)/64.0f)); // top middle. glyph->setVerticalAdvance((float)metrics->vertAdvance/64.0f); addGlyph(_facade->getFontWidth(),_facade->getFontHeight(),charcode,glyph.get()); // cout << " in getGlyph() implementation="<<this<<" "<<_filename<<" facade="<<_facade<<endl; return glyph.get(); } osg::Vec2 FreeTypeFont::getKerning(unsigned int leftcharcode,unsigned int rightcharcode, osgText::KerningType kerningType) { if (!FT_HAS_KERNING(_face) || (kerningType == osgText::KERNING_NONE)) return osg::Vec2(0.0f,0.0f); FT_Kerning_Mode mode = (kerningType==osgText::KERNING_DEFAULT) ? ft_kerning_default : ft_kerning_unfitted; // convert character code to glyph index FT_UInt left = FT_Get_Char_Index( _face, leftcharcode ); FT_UInt right = FT_Get_Char_Index( _face, rightcharcode ); // get the kerning distances. FT_Vector kerning; FT_Error error = FT_Get_Kerning( _face, // handle to face object left, // left glyph index right, // right glyph index mode, // kerning mode &kerning ); // target vector if (error) { return osg::Vec2(0.0f,0.0f); } return osg::Vec2((float)kerning.x/64.0f,(float)kerning.y/64.0f); } bool FreeTypeFont::hasVertical() const { return FT_HAS_VERTICAL(_face)!=0; } <|endoftext|>
<commit_before>#include <tiffio.h> #include <osg/Image> #include <osg/Notify> #include <osg/Geode> #include <osg/GL> #include <osgDB/Registry> #include <stdio.h> /**************************************************************************** * * Follows is code extracted from the simage library. Original Authors: * * Systems in Motion, * <URL:http://www.sim.no> * * Peder Blekken <pederb@sim.no> * Morten Eriksen <mortene@sim.no> * Marius Bugge Monsen <mariusbu@sim.no> * * The original COPYING notice * * All files in this library are public domain, except simage_rgb.cpp which is * Copyright (c) Mark J Kilgard <mjk@nvidia.com>. I will contact Mark * very soon to hear if this source also can become public domain. * * Please send patches for bugs and new features to: <pederb@sim.no>. * * Peder Blekken * * * Ported into the OSG as a plugin, Robert Osfield Decemeber 2000. * Note, reference above to license of simage_rgb is not relevent to the OSG * as the OSG does not use it. Also for patches, bugs and new features * please send them direct to the OSG dev team rather than address above. * **********************************************************************/ #include <string.h> #include <stdarg.h> #include <assert.h> #include <stdlib.h> #define ERR_NO_ERROR 0 #define ERR_OPEN 1 #define ERR_READ 2 #define ERR_MEM 3 #define ERR_UNSUPPORTED 4 #define ERR_TIFFLIB 5 static int tifferror = ERR_NO_ERROR; int simage_tiff_error(char * buffer, int buflen) { switch (tifferror) { case ERR_OPEN: strncpy(buffer, "TIFF loader: Error opening file", buflen); break; case ERR_MEM: strncpy(buffer, "TIFF loader: Out of memory error", buflen); break; case ERR_UNSUPPORTED: strncpy(buffer, "TIFF loader: Unsupported image type", buflen); break; case ERR_TIFFLIB: strncpy(buffer, "TIFF loader: Illegal tiff file", buflen); break; } return tifferror; } static void tiff_error(const char*, const char*, va_list) { // values are (const char* module, const char* fmt, va_list list) /* FIXME: store error message ? */ } static void tiff_warn(const char *, const char *, va_list) { // values are (const char* module, const char* fmt, va_list list) /* FIXME: notify? */ } static int checkcmap(int n, uint16* r, uint16* g, uint16* b) { while (n-- > 0) if (*r++ >= 256 || *g++ >= 256 || *b++ >= 256) return (16); /* Assuming 8-bit colormap */ return (8); } static void invert_row(unsigned char *ptr, unsigned char *data, int n, int invert) { while (n--) { if (invert) *ptr++ = 255 - *data++; else *ptr++ = *data++; } } static void remap_row(unsigned char *ptr, unsigned char *data, int n, unsigned short *rmap, unsigned short *gmap, unsigned short *bmap) { unsigned int ix; while (n--) { ix = *data++; *ptr++ = (unsigned char) rmap[ix]; *ptr++ = (unsigned char) gmap[ix]; *ptr++ = (unsigned char) bmap[ix]; } } static void copy_row(unsigned char *ptr, unsigned char *data, int n) { while (n--) { *ptr++ = *data++; *ptr++ = *data++; *ptr++ = *data++; } } static void interleave_row(unsigned char *ptr, unsigned char *red, unsigned char *blue, unsigned char *green, int n) { while (n--) { *ptr++ = *red++; *ptr++ = *green++; *ptr++ = *blue++; } } int simage_tiff_identify(const char *, const unsigned char *header, int headerlen) { static unsigned char tifcmp[] = {0x4d, 0x4d, 0x0, 0x2a}; static unsigned char tifcmp2[] = {0x49, 0x49, 0x2a, 0}; if (headerlen < 4) return 0; if (memcmp((const void*)header, (const void*)tifcmp, 4) == 0) return 1; if (memcmp((const void*)header, (const void*)tifcmp2, 4) == 0) return 1; return 0; } /* useful defines (undef'ed below) */ #define CVT(x) (((x) * 255L) / ((1L<<16)-1)) #define pack(a,b) ((a)<<8 | (b)) unsigned char * simage_tiff_load(const char *filename, int *width_ret, int *height_ret, int *numComponents_ret) { TIFF *in; uint16 samplesperpixel; uint16 bitspersample; uint16 photometric; uint32 w, h; uint16 config; uint16* red; uint16* green; uint16* blue; unsigned char *inbuf = NULL; tsize_t rowsize; uint32 row; int format; unsigned char *buffer; int width; int height; unsigned char *currPtr; TIFFSetErrorHandler(tiff_error); TIFFSetWarningHandler(tiff_warn); in = TIFFOpen(filename, "r"); if (in == NULL) { tifferror = ERR_OPEN; return NULL; } if (TIFFGetField(in, TIFFTAG_PHOTOMETRIC, &photometric) == 1) { if (photometric != PHOTOMETRIC_RGB && photometric != PHOTOMETRIC_PALETTE && photometric != PHOTOMETRIC_MINISWHITE && photometric != PHOTOMETRIC_MINISBLACK) { /*Bad photometric; can only handle Grayscale, RGB and Palette images :-( */ TIFFClose(in); tifferror = ERR_UNSUPPORTED; return NULL; } } else { tifferror = ERR_READ; TIFFClose(in); return NULL; } if (TIFFGetField(in, TIFFTAG_SAMPLESPERPIXEL, &samplesperpixel) == 1) { if (samplesperpixel != 1 && samplesperpixel != 3) { /* Bad samples/pixel */ tifferror = ERR_UNSUPPORTED; TIFFClose(in); return NULL; } } else { tifferror = ERR_READ; TIFFClose(in); return NULL; } if (TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bitspersample) == 1) { if (bitspersample != 8) { /* can only handle 8-bit samples. */ TIFFClose(in); tifferror = ERR_UNSUPPORTED; return NULL; } } else { tifferror = ERR_READ; TIFFClose(in); return NULL; } if (TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &w) != 1 || TIFFGetField(in, TIFFTAG_IMAGELENGTH, &h) != 1 || TIFFGetField(in, TIFFTAG_PLANARCONFIG, &config) != 1) { TIFFClose(in); tifferror = ERR_READ; return NULL; } if (photometric == PHOTOMETRIC_MINISWHITE || photometric == PHOTOMETRIC_MINISBLACK) format = 1; else format = 3; buffer = (unsigned char*)malloc(w*h*format); if (!buffer) { tifferror = ERR_MEM; TIFFClose(in); return NULL; } width = w; height = h; currPtr = buffer + (h-1)*w*format; tifferror = ERR_NO_ERROR; switch (pack(photometric, config)) { case pack(PHOTOMETRIC_MINISWHITE, PLANARCONFIG_CONTIG): case pack(PHOTOMETRIC_MINISBLACK, PLANARCONFIG_CONTIG): case pack(PHOTOMETRIC_MINISWHITE, PLANARCONFIG_SEPARATE): case pack(PHOTOMETRIC_MINISBLACK, PLANARCONFIG_SEPARATE): inbuf = (unsigned char *)malloc(TIFFScanlineSize(in)); for (row = 0; row < h; row++) { if (TIFFReadScanline(in, inbuf, row, 0) < 0) { tifferror = ERR_READ; break; } invert_row(currPtr, inbuf, w, photometric == PHOTOMETRIC_MINISWHITE); currPtr -= format*w; } break; case pack(PHOTOMETRIC_PALETTE, PLANARCONFIG_CONTIG): case pack(PHOTOMETRIC_PALETTE, PLANARCONFIG_SEPARATE): if (TIFFGetField(in, TIFFTAG_COLORMAP, &red, &green, &blue) != 1) tifferror = ERR_READ; /* */ /* Convert 16-bit colormap to 8-bit (unless it looks */ /* like an old-style 8-bit colormap). */ /* */ if (!tifferror && checkcmap(1<<bitspersample, red, green, blue) == 16) { int i; for (i = (1<<bitspersample)-1; i >= 0; i--) { red[i] = CVT(red[i]); green[i] = CVT(green[i]); blue[i] = CVT(blue[i]); } } inbuf = (unsigned char *)malloc(TIFFScanlineSize(in)); for (row = 0; row < h; row++) { if (TIFFReadScanline(in, inbuf, row, 0) < 0) { tifferror = ERR_READ; break; } remap_row(currPtr, inbuf, w, red, green, blue); currPtr -= format*w; } break; case pack(PHOTOMETRIC_RGB, PLANARCONFIG_CONTIG): inbuf = (unsigned char *)malloc(TIFFScanlineSize(in)); for (row = 0; row < h; row++) { if (TIFFReadScanline(in, inbuf, row, 0) < 0) { tifferror = ERR_READ; break; } copy_row(currPtr, inbuf, w); currPtr -= format*w; } break; case pack(PHOTOMETRIC_RGB, PLANARCONFIG_SEPARATE): rowsize = TIFFScanlineSize(in); inbuf = (unsigned char *)malloc(3*rowsize); for (row = 0; !tifferror && row < h; row++) { int s; for (s = 0; s < 3; s++) { if (TIFFReadScanline(in, (tdata_t)(inbuf+s*rowsize), (uint32)row, (tsample_t)s) < 0) { tifferror = ERR_READ; break; } } if (!tifferror) { interleave_row(currPtr, inbuf, inbuf+rowsize, inbuf+2*rowsize, w); currPtr -= format*w; } } break; default: tifferror = ERR_UNSUPPORTED; break; } if (inbuf) free(inbuf); TIFFClose(in); if (tifferror) { if (buffer) free(buffer); return NULL; } *width_ret = width; *height_ret = height; *numComponents_ret = format; return buffer; } #undef CVT #undef pack class ReaderWriterTIFF : public osgDB::ReaderWriter { public: virtual const char* className() { return "TIFF Image Reader"; } virtual bool acceptsExtension(const std::string& extension) { return extension=="tiff"; } virtual ReadResult readImage(const std::string& fileName, const osgDB::ReaderWriter::Options*) { unsigned char *imageData = NULL; int width_ret; int height_ret; int numComponents_ret; imageData = simage_tiff_load(fileName.c_str(),&width_ret,&height_ret,&numComponents_ret); if (imageData==NULL) return ReadResult::FILE_NOT_HANDLED; int s = width_ret; int t = height_ret; int r = 1; int internalFormat = numComponents_ret; unsigned int pixelFormat = numComponents_ret == 1 ? GL_LUMINANCE : numComponents_ret == 2 ? GL_LUMINANCE_ALPHA : numComponents_ret == 3 ? GL_RGB : numComponents_ret == 4 ? GL_RGBA : (GLenum)-1; unsigned int dataType = GL_UNSIGNED_BYTE; osg::Image* pOsgImage = new osg::Image; pOsgImage->setFileName(fileName.c_str()); pOsgImage->setImage(s,t,r, internalFormat, pixelFormat, dataType, imageData); return pOsgImage; } }; // now register with Registry to instantiate the above // reader/writer. osgDB::RegisterReaderWriterProxy<ReaderWriterTIFF> g_readerWriter_TIFF_Proxy; <commit_msg>Added ability to accept '.tif' files (as well as '.tiff') and printed notify() on error<commit_after>#include <tiffio.h> #include <osg/Image> #include <osg/Notify> #include <osg/Geode> #include <osg/GL> #include <osgDB/Registry> #include <stdio.h> /**************************************************************************** * * Follows is code extracted from the simage library. Original Authors: * * Systems in Motion, * <URL:http://www.sim.no> * * Peder Blekken <pederb@sim.no> * Morten Eriksen <mortene@sim.no> * Marius Bugge Monsen <mariusbu@sim.no> * * The original COPYING notice * * All files in this library are public domain, except simage_rgb.cpp which is * Copyright (c) Mark J Kilgard <mjk@nvidia.com>. I will contact Mark * very soon to hear if this source also can become public domain. * * Please send patches for bugs and new features to: <pederb@sim.no>. * * Peder Blekken * * * Ported into the OSG as a plugin, Robert Osfield Decemeber 2000. * Note, reference above to license of simage_rgb is not relevent to the OSG * as the OSG does not use it. Also for patches, bugs and new features * please send them direct to the OSG dev team rather than address above. * **********************************************************************/ #include <string.h> #include <stdarg.h> #include <assert.h> #include <stdlib.h> #define ERR_NO_ERROR 0 #define ERR_OPEN 1 #define ERR_READ 2 #define ERR_MEM 3 #define ERR_UNSUPPORTED 4 #define ERR_TIFFLIB 5 static int tifferror = ERR_NO_ERROR; int simage_tiff_error(char * buffer, int buflen) { switch (tifferror) { case ERR_OPEN: strncpy(buffer, "TIFF loader: Error opening file", buflen); break; case ERR_MEM: strncpy(buffer, "TIFF loader: Out of memory error", buflen); break; case ERR_UNSUPPORTED: strncpy(buffer, "TIFF loader: Unsupported image type", buflen); break; case ERR_TIFFLIB: strncpy(buffer, "TIFF loader: Illegal tiff file", buflen); break; } return tifferror; } static void tiff_error(const char*, const char*, va_list) { // values are (const char* module, const char* fmt, va_list list) /* FIXME: store error message ? */ } static void tiff_warn(const char *, const char *, va_list) { // values are (const char* module, const char* fmt, va_list list) /* FIXME: notify? */ } static int checkcmap(int n, uint16* r, uint16* g, uint16* b) { while (n-- > 0) if (*r++ >= 256 || *g++ >= 256 || *b++ >= 256) return (16); /* Assuming 8-bit colormap */ return (8); } static void invert_row(unsigned char *ptr, unsigned char *data, int n, int invert) { while (n--) { if (invert) *ptr++ = 255 - *data++; else *ptr++ = *data++; } } static void remap_row(unsigned char *ptr, unsigned char *data, int n, unsigned short *rmap, unsigned short *gmap, unsigned short *bmap) { unsigned int ix; while (n--) { ix = *data++; *ptr++ = (unsigned char) rmap[ix]; *ptr++ = (unsigned char) gmap[ix]; *ptr++ = (unsigned char) bmap[ix]; } } static void copy_row(unsigned char *ptr, unsigned char *data, int n) { while (n--) { *ptr++ = *data++; *ptr++ = *data++; *ptr++ = *data++; } } static void interleave_row(unsigned char *ptr, unsigned char *red, unsigned char *blue, unsigned char *green, int n) { while (n--) { *ptr++ = *red++; *ptr++ = *green++; *ptr++ = *blue++; } } int simage_tiff_identify(const char *, const unsigned char *header, int headerlen) { static unsigned char tifcmp[] = {0x4d, 0x4d, 0x0, 0x2a}; static unsigned char tifcmp2[] = {0x49, 0x49, 0x2a, 0}; if (headerlen < 4) return 0; if (memcmp((const void*)header, (const void*)tifcmp, 4) == 0) return 1; if (memcmp((const void*)header, (const void*)tifcmp2, 4) == 0) return 1; return 0; } /* useful defines (undef'ed below) */ #define CVT(x) (((x) * 255L) / ((1L<<16)-1)) #define pack(a,b) ((a)<<8 | (b)) unsigned char * simage_tiff_load(const char *filename, int *width_ret, int *height_ret, int *numComponents_ret) { TIFF *in; uint16 samplesperpixel; uint16 bitspersample; uint16 photometric; uint32 w, h; uint16 config; uint16* red; uint16* green; uint16* blue; unsigned char *inbuf = NULL; tsize_t rowsize; uint32 row; int format; unsigned char *buffer; int width; int height; unsigned char *currPtr; TIFFSetErrorHandler(tiff_error); TIFFSetWarningHandler(tiff_warn); in = TIFFOpen(filename, "r"); if (in == NULL) { tifferror = ERR_OPEN; return NULL; } if (TIFFGetField(in, TIFFTAG_PHOTOMETRIC, &photometric) == 1) { if (photometric != PHOTOMETRIC_RGB && photometric != PHOTOMETRIC_PALETTE && photometric != PHOTOMETRIC_MINISWHITE && photometric != PHOTOMETRIC_MINISBLACK) { /*Bad photometric; can only handle Grayscale, RGB and Palette images :-( */ TIFFClose(in); tifferror = ERR_UNSUPPORTED; return NULL; } } else { tifferror = ERR_READ; TIFFClose(in); return NULL; } if (TIFFGetField(in, TIFFTAG_SAMPLESPERPIXEL, &samplesperpixel) == 1) { if (samplesperpixel != 1 && samplesperpixel != 3) { /* Bad samples/pixel */ tifferror = ERR_UNSUPPORTED; TIFFClose(in); return NULL; } } else { tifferror = ERR_READ; TIFFClose(in); return NULL; } if (TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bitspersample) == 1) { if (bitspersample != 8) { /* can only handle 8-bit samples. */ TIFFClose(in); tifferror = ERR_UNSUPPORTED; return NULL; } } else { tifferror = ERR_READ; TIFFClose(in); return NULL; } if (TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &w) != 1 || TIFFGetField(in, TIFFTAG_IMAGELENGTH, &h) != 1 || TIFFGetField(in, TIFFTAG_PLANARCONFIG, &config) != 1) { TIFFClose(in); tifferror = ERR_READ; return NULL; } if (photometric == PHOTOMETRIC_MINISWHITE || photometric == PHOTOMETRIC_MINISBLACK) format = 1; else format = 3; buffer = (unsigned char*)malloc(w*h*format); if (!buffer) { tifferror = ERR_MEM; TIFFClose(in); return NULL; } width = w; height = h; currPtr = buffer + (h-1)*w*format; tifferror = ERR_NO_ERROR; switch (pack(photometric, config)) { case pack(PHOTOMETRIC_MINISWHITE, PLANARCONFIG_CONTIG): case pack(PHOTOMETRIC_MINISBLACK, PLANARCONFIG_CONTIG): case pack(PHOTOMETRIC_MINISWHITE, PLANARCONFIG_SEPARATE): case pack(PHOTOMETRIC_MINISBLACK, PLANARCONFIG_SEPARATE): inbuf = (unsigned char *)malloc(TIFFScanlineSize(in)); for (row = 0; row < h; row++) { if (TIFFReadScanline(in, inbuf, row, 0) < 0) { tifferror = ERR_READ; break; } invert_row(currPtr, inbuf, w, photometric == PHOTOMETRIC_MINISWHITE); currPtr -= format*w; } break; case pack(PHOTOMETRIC_PALETTE, PLANARCONFIG_CONTIG): case pack(PHOTOMETRIC_PALETTE, PLANARCONFIG_SEPARATE): if (TIFFGetField(in, TIFFTAG_COLORMAP, &red, &green, &blue) != 1) tifferror = ERR_READ; /* */ /* Convert 16-bit colormap to 8-bit (unless it looks */ /* like an old-style 8-bit colormap). */ /* */ if (!tifferror && checkcmap(1<<bitspersample, red, green, blue) == 16) { int i; for (i = (1<<bitspersample)-1; i >= 0; i--) { red[i] = CVT(red[i]); green[i] = CVT(green[i]); blue[i] = CVT(blue[i]); } } inbuf = (unsigned char *)malloc(TIFFScanlineSize(in)); for (row = 0; row < h; row++) { if (TIFFReadScanline(in, inbuf, row, 0) < 0) { tifferror = ERR_READ; break; } remap_row(currPtr, inbuf, w, red, green, blue); currPtr -= format*w; } break; case pack(PHOTOMETRIC_RGB, PLANARCONFIG_CONTIG): inbuf = (unsigned char *)malloc(TIFFScanlineSize(in)); for (row = 0; row < h; row++) { if (TIFFReadScanline(in, inbuf, row, 0) < 0) { tifferror = ERR_READ; break; } copy_row(currPtr, inbuf, w); currPtr -= format*w; } break; case pack(PHOTOMETRIC_RGB, PLANARCONFIG_SEPARATE): rowsize = TIFFScanlineSize(in); inbuf = (unsigned char *)malloc(3*rowsize); for (row = 0; !tifferror && row < h; row++) { int s; for (s = 0; s < 3; s++) { if (TIFFReadScanline(in, (tdata_t)(inbuf+s*rowsize), (uint32)row, (tsample_t)s) < 0) { tifferror = ERR_READ; break; } } if (!tifferror) { interleave_row(currPtr, inbuf, inbuf+rowsize, inbuf+2*rowsize, w); currPtr -= format*w; } } break; default: tifferror = ERR_UNSUPPORTED; break; } if (inbuf) free(inbuf); TIFFClose(in); if (tifferror) { if (buffer) free(buffer); return NULL; } *width_ret = width; *height_ret = height; *numComponents_ret = format; return buffer; } #undef CVT #undef pack class ReaderWriterTIFF : public osgDB::ReaderWriter { public: virtual const char* className() { return "TIFF Image Reader"; } virtual bool acceptsExtension(const std::string& extension) { if( extension == "tiff" ) return true; if( extension == "tif" ) return true; return false; } virtual ReadResult readImage(const std::string& fileName, const osgDB::ReaderWriter::Options*) { unsigned char *imageData = NULL; int width_ret; int height_ret; int numComponents_ret; imageData = simage_tiff_load(fileName.c_str(),&width_ret,&height_ret,&numComponents_ret); if (imageData==NULL) { char err_msg[256]; simage_tiff_error( err_msg, sizeof(err_msg)); osg::notify(osg::WARN) << err_msg << std::endl; return ReadResult::FILE_NOT_HANDLED; } int s = width_ret; int t = height_ret; int r = 1; int internalFormat = numComponents_ret; unsigned int pixelFormat = numComponents_ret == 1 ? GL_LUMINANCE : numComponents_ret == 2 ? GL_LUMINANCE_ALPHA : numComponents_ret == 3 ? GL_RGB : numComponents_ret == 4 ? GL_RGBA : (GLenum)-1; unsigned int dataType = GL_UNSIGNED_BYTE; osg::Image* pOsgImage = new osg::Image; pOsgImage->setFileName(fileName.c_str()); pOsgImage->setImage(s,t,r, internalFormat, pixelFormat, dataType, imageData); return pOsgImage; } }; // now register with Registry to instantiate the above // reader/writer. osgDB::RegisterReaderWriterProxy<ReaderWriterTIFF> g_readerWriter_TIFF_Proxy; <|endoftext|>
<commit_before>#include "elliptic_homogenizer.hh" namespace Dune { namespace Multiscale { NULLFUNCTION(ZeroFunction) //! the following class is comparable to a SecondSource-Class (some kind of -div G ) class CellSource : CommonTraits::FunctionBaseType { private: typedef typename CommonTraits::DiffusionType TensorType; typedef CommonTraits::FunctionSpaceType FunctionSpaceType; typedef typename FunctionSpaceType::DomainType DomainType; typedef typename FunctionSpaceType::RangeType RangeType; typedef typename FunctionSpaceType::JacobianRangeType JacobianRangeType; typedef typename FunctionSpaceType::DomainFieldType DomainFieldType; typedef typename FunctionSpaceType::RangeFieldType RangeFieldType; const TensorType& tensor_; const int& j_; public: inline explicit CellSource(const FunctionSpaceType& /*functionSpace*/, const TensorType& tensor, const int& j) : tensor_(tensor) , j_(j) // we solve the j'th cell problem {} inline void evaluate(const DomainType& /*x*/, RangeType& y) const { y[0] = 0; } inline void evaluate(const int i, const DomainType& y, RangeType& z) const { JacobianRangeType direction; JacobianRangeType flux; for (int j = 0; j < DomainType::dimension; ++j) { direction[0][j] = int(j_ == j); } tensor_.diffusiveFlux(y, direction, flux); // tensor_.evaluate( i, j_, y, z); z = -flux[0][i]; } // evaluate }; NULLFUNCTION(DefaultDummyAdvection) Homogenizer::Homogenizer(const std::string &filename) : filename_(filename) {} double Homogenizer::getEntry(const TransformTensor &tensor, const Homogenizer::PeriodicDiscreteFunctionSpaceType &periodicDiscreteFunctionSpace, const Homogenizer::PeriodicDiscreteFunctionType &w_i, const Homogenizer::PeriodicDiscreteFunctionType &w_j, const int &i, const int &j) const { double a_ij_hom = 0; for (const auto& entity : periodicDiscreteFunctionSpace) { auto localW_i = w_i.localFunction(entity); auto localW_j = w_j.localFunction(entity); // create quadrature for given geometry type //!\TODO soll das WIRLKLICH pold order 2 sein? const auto quadrature = make_quadrature(entity, periodicDiscreteFunctionSpace, 2); // get geoemetry of entity const auto& geometry = entity.geometry(); // integrate for (const auto localQuadPoint : DSC::valueRange(quadrature.nop())) { RangeType localIntegral = 0; PeriodicJacobianRangeType grad_w_i; localW_i.jacobian(quadrature[localQuadPoint], grad_w_i); PeriodicJacobianRangeType grad_w_j; localW_j.jacobian(quadrature[localQuadPoint], grad_w_j); // local (barycentric) coordinates (with respect to cell grid entity) const auto& local_point = quadrature.point(localQuadPoint); // global point in the unit cell Y const auto global_point_in_Y = geometry.global(local_point); PeriodicJacobianRangeType direction_i; for (int k = 0; k < dimension; ++k) { direction_i[0][k] = grad_w_i[0][k]; if (k == i) { direction_i[0][k] += 1.0; } } PeriodicJacobianRangeType direction_j; for (int k = 0; k < dimension; ++k) { direction_j[0][k] = 0.0; if (k == j) { direction_j[0][k] += 1.0; } } PeriodicJacobianRangeType flux_i; tensor.diffusiveFlux(global_point_in_Y, direction_i, flux_i); localIntegral = (flux_i[0] * direction_j[0]); const double entityVolume = quadrature.weight(localQuadPoint) * geometry.integrationElement(quadrature.point(localQuadPoint)); a_ij_hom += entityVolume * localIntegral; } } return a_ij_hom; } Homogenizer::HomTensorType Homogenizer::getHomTensor(const Homogenizer::TensorType &tensor) const { HomTensorType a_hom; // to solve cell problems, we always need to use a perforated unit cube as domain: GridPtr<GridType> periodicgridptr(filename_); Dune::Fem::GlobalRefine::apply(*periodicgridptr, 10); PeriodicGridPartType periodicGridPart(*periodicgridptr); PeriodicDiscreteFunctionSpaceType periodicDiscreteFunctionSpace(periodicGridPart); // to avoid confusions: const DummySpaceType dummySpace(periodicGridPart); // (sometimes periodicDiscreteFunctionSpace is only a dummy) //! define the type of the corresponding solutions ( discrete functions of the type 'DiscreteFunctionType'): PeriodicDiscreteFunctionType cellSolution_0("cellSolution 0", periodicDiscreteFunctionSpace); cellSolution_0.clear(); PeriodicDiscreteFunctionType cellSolution_1("cellSolution 1", periodicDiscreteFunctionSpace); cellSolution_1.clear(); PeriodicDiscreteFunctionType rhs_0("rhs_0", periodicDiscreteFunctionSpace); rhs_0.clear(); PeriodicDiscreteFunctionType rhs_1("rhs_1", periodicDiscreteFunctionSpace); rhs_1.clear(); const RangeType lambda = 1e-07; // we need solve several cell problems with a periodic boundary condition. To fix the solution we need some kind of // additional condition. Therefor we solve // \lambda w - \div A \nabla w = rhs instead of - \div A \nabla w = rhs const TransformTensor tensor_transformed(tensor); // if we have some additional source term (-div G), define: const CellSource G_0(periodicDiscreteFunctionSpace, tensor_transformed, 0); // 0'th cell problem const CellSource G_1(periodicDiscreteFunctionSpace, tensor_transformed, 1); // 1'th cell problem // - div ( A \nabla u^{\epsilon} ) = f - div G // quite a dummy. It's always f = 0 const ZeroFunction<FunctionSpaceType> zero; //! build the left hand side (lhs) of the problem const std::unique_ptr<const Problem::LowerOrderBase> mass(new MassWeightType(lambda)); // define mass (just for cell problems \lambda w - \div A \nabla w = rhs) const EllipticOperatorType discrete_cell_elliptic_op(periodicDiscreteFunctionSpace, tensor_transformed, mass); LinearOperatorType lhsMatrix("Cell Problem Stiffness Matrix", periodicDiscreteFunctionSpace, periodicDiscreteFunctionSpace); discrete_cell_elliptic_op.assemble_matrix(lhsMatrix, false /*no boundary treatment*/); //! build the right hand side (rhs) of the problem // the same right hand side for HM and FEM methods: typedef RightHandSideAssembler<PeriodicDiscreteFunctionType> RhsAssembler; // Alternativly it is possible to call the RightHandSideAssembler with a second source Term '- div G': // RightHandSideAssembler< DiscreteFunctionType > rhsassembler( tensor , G ); RhsAssembler::assemble<2 * PeriodicDiscreteFunctionSpaceType::polynomialOrder>(zero, G_0, rhs_0); RhsAssembler::assemble<2 * PeriodicDiscreteFunctionSpaceType::polynomialOrder>(zero, G_1, rhs_1); // solve the linear systems (with Bi-CG): const InverseLinearOperatorType fembiCG(lhsMatrix, 1e-8, 1e-8, 20000, DSC_CONFIG_GET("global.cgsolver_verbose", false)); fembiCG(rhs_0, cellSolution_0); fembiCG(rhs_1, cellSolution_1); a_hom[0][0] = getEntry(tensor_transformed, periodicDiscreteFunctionSpace, cellSolution_0, cellSolution_0, 0, 0); a_hom[1][1] = getEntry(tensor_transformed, periodicDiscreteFunctionSpace, cellSolution_1, cellSolution_1, 1, 1); a_hom[0][1] = getEntry(tensor_transformed, periodicDiscreteFunctionSpace, cellSolution_0, cellSolution_1, 0, 1); a_hom[1][0] = a_hom[0][1]; DSC_LOG_DEBUG << "A_homogenized[0][0] = " << a_hom[0][0] << std::endl << "A_homogenized[0][1] = " << a_hom[0][1] << std::endl << "A_homogenized[1][0] = " << a_hom[1][0] << std::endl << "A_homogenized[1][1] = " << a_hom[1][1] << std::endl; return a_hom; } void TransformTensor::diffusiveFlux(const TransformTensor::DomainType &y, const TransformTensor::JacobianRangeType &direction, TransformTensor::JacobianRangeType &flux) const { DomainType new_y = y; new_y *= DSC_CONFIG_GET("problem.epsilon", 1.0f); tensor_.diffusiveFlux(new_y, direction, flux); } void TransformTensor::jacobianDiffusiveFlux(const TransformTensor::DomainType &, const TransformTensor::JacobianRangeType &, const TransformTensor::JacobianRangeType &, TransformTensor::JacobianRangeType &) const { DUNE_THROW(Dune::NotImplemented, ""); } void TransformTensor::evaluate(const TransformTensor::DomainType &, const TransformTensor::TimeType &, TransformTensor::RangeType &) const { DUNE_THROW(Dune::NotImplemented, ""); } void TransformTensor::evaluate(const int, const int, const TransformTensor::DomainType &, const TransformTensor::TimeType &, TransformTensor::RangeType &) const { DUNE_THROW(Dune::NotImplemented, ""); } } // namespace Multiscale { } // end namespace <commit_msg>removes another unused file<commit_after><|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qwaylandglcontext.h" #include "qwaylanddisplay.h" #include "qwaylandwindow.h" #include "qwaylandeglwindow.h" #include "qwaylanddecoration.h" #include <QDebug> #include <QtPlatformSupport/private/qeglconvenience_p.h> #include <QtGui/private/qopenglcontext_p.h> #include <QtGui/private/qopengltexturecache_p.h> #include <qpa/qplatformopenglcontext.h> #include <QtGui/QSurfaceFormat> #include <QtGui/QOpenGLShaderProgram> QT_USE_NAMESPACE QWaylandGLContext::QWaylandGLContext(EGLDisplay eglDisplay, const QSurfaceFormat &format, QPlatformOpenGLContext *share) : QPlatformOpenGLContext() , m_eglDisplay(eglDisplay) , m_config(q_configFromGLFormat(m_eglDisplay, format, true)) , m_format(q_glFormatFromConfig(m_eglDisplay, m_config)) , m_blitProgram(0) , m_textureCache(0) { m_shareEGLContext = share ? static_cast<QWaylandGLContext *>(share)->eglContext() : EGL_NO_CONTEXT; eglBindAPI(EGL_OPENGL_ES_API); QVector<EGLint> eglContextAttrs; eglContextAttrs.append(EGL_CONTEXT_CLIENT_VERSION); eglContextAttrs.append(format.majorVersion() == 1 ? 1 : 2); eglContextAttrs.append(EGL_NONE); m_context = eglCreateContext(m_eglDisplay, m_config, m_shareEGLContext, eglContextAttrs.constData()); if (m_context == EGL_NO_CONTEXT) { m_context = eglCreateContext(m_eglDisplay, m_config, EGL_NO_CONTEXT, eglContextAttrs.constData()); m_shareEGLContext = EGL_NO_CONTEXT; } } QWaylandGLContext::~QWaylandGLContext() { delete m_blitProgram; delete m_textureCache; eglDestroyContext(m_eglDisplay, m_context); } bool QWaylandGLContext::makeCurrent(QPlatformSurface *surface) { QWaylandEglWindow *window = static_cast<QWaylandEglWindow *>(surface); EGLSurface eglSurface = window->eglSurface(); if (!eglMakeCurrent(m_eglDisplay, eglSurface, eglSurface, m_context)) return false; // FIXME: remove this as soon as https://codereview.qt-project.org/#change,38879 is merged QOpenGLContextPrivate::setCurrentContext(context()); window->bindContentFBO(); return true; } void QWaylandGLContext::doneCurrent() { eglMakeCurrent(m_eglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); } void QWaylandGLContext::swapBuffers(QPlatformSurface *surface) { QWaylandEglWindow *window = static_cast<QWaylandEglWindow *>(surface); EGLSurface eglSurface = window->eglSurface(); if (window->decoration()) { makeCurrent(surface); if (!m_blitProgram) { m_blitProgram = new QOpenGLShaderProgram(); m_blitProgram->addShaderFromSourceCode(QOpenGLShader::Vertex, "attribute vec4 position;\n\ attribute vec4 texCoords;\n\ varying vec2 outTexCoords;\n\ void main()\n\ {\n\ gl_Position = position;\n\ outTexCoords = texCoords.xy;\n\ }"); m_blitProgram->addShaderFromSourceCode(QOpenGLShader::Fragment, "varying vec2 outTexCoords;\n\ uniform sampler2D texture;\n\ void main()\n\ {\n\ gl_FragColor = texture2D(texture, outTexCoords);\n\ }"); if (!m_blitProgram->link()) { qDebug() << "Shader Program link failed."; qDebug() << m_blitProgram->log(); } } if (!m_textureCache) { m_textureCache = new QOpenGLTextureCache(this->context()); } glDisable(GL_DEPTH_TEST); glDisable(GL_BLEND); glBindFramebuffer(GL_FRAMEBUFFER, 0); static const GLfloat squareVertices[] = { -1.f, -1.f, 1.0f, -1.f, -1.f, 1.0f, 1.0f, 1.0f }; static const GLfloat inverseSquareVertices[] = { -1.f, 1.f, 1.f, 1.f, -1.f, -1.f, 1.f, -1.f }; static const GLfloat textureVertices[] = { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, }; m_blitProgram->setUniformValue("texture", 0); m_blitProgram->enableAttributeArray("position"); m_blitProgram->enableAttributeArray("texCoords"); m_blitProgram->setAttributeArray("texCoords", textureVertices, 2); m_blitProgram->bind(); glActiveTexture(GL_TEXTURE0); //Draw Decoration m_blitProgram->setAttributeArray("position", inverseSquareVertices, 2); QImage decorationImage = window->decoration()->contentImage(); m_textureCache->bindTexture(context(), decorationImage); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); QRect windowRect = window->window()->frameGeometry(); glViewport(0, 0, windowRect.width(), windowRect.height()); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); //Draw Content m_blitProgram->setAttributeArray("position", squareVertices, 2); glBindTexture(GL_TEXTURE_2D, window->contentTexture()); QRect r = window->contentsRect(); glViewport(r.x(), r.y(), r.width(), r.height()); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); //Cleanup m_blitProgram->disableAttributeArray("position"); m_blitProgram->disableAttributeArray("texCoords"); m_blitProgram->release(); } eglSwapBuffers(m_eglDisplay, eglSurface); window->doResize(); } GLuint QWaylandGLContext::defaultFramebufferObject(QPlatformSurface *surface) const { return static_cast<QWaylandEglWindow *>(surface)->contentFBO(); } bool QWaylandGLContext::isSharing() const { return m_shareEGLContext != EGL_NO_CONTEXT; } bool QWaylandGLContext::isValid() const { return m_context != EGL_NO_CONTEXT; } void (*QWaylandGLContext::getProcAddress(const QByteArray &procName)) () { return eglGetProcAddress(procName.constData()); } EGLConfig QWaylandGLContext::eglConfig() const { return m_config; } <commit_msg>Add warning to makeCurrent if it fails<commit_after>/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the plugins of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qwaylandglcontext.h" #include "qwaylanddisplay.h" #include "qwaylandwindow.h" #include "qwaylandeglwindow.h" #include "qwaylanddecoration.h" #include <QDebug> #include <QtPlatformSupport/private/qeglconvenience_p.h> #include <QtGui/private/qopenglcontext_p.h> #include <QtGui/private/qopengltexturecache_p.h> #include <qpa/qplatformopenglcontext.h> #include <QtGui/QSurfaceFormat> #include <QtGui/QOpenGLShaderProgram> QT_USE_NAMESPACE QWaylandGLContext::QWaylandGLContext(EGLDisplay eglDisplay, const QSurfaceFormat &format, QPlatformOpenGLContext *share) : QPlatformOpenGLContext() , m_eglDisplay(eglDisplay) , m_config(q_configFromGLFormat(m_eglDisplay, format, true)) , m_format(q_glFormatFromConfig(m_eglDisplay, m_config)) , m_blitProgram(0) , m_textureCache(0) { m_shareEGLContext = share ? static_cast<QWaylandGLContext *>(share)->eglContext() : EGL_NO_CONTEXT; eglBindAPI(EGL_OPENGL_ES_API); QVector<EGLint> eglContextAttrs; eglContextAttrs.append(EGL_CONTEXT_CLIENT_VERSION); eglContextAttrs.append(format.majorVersion() == 1 ? 1 : 2); eglContextAttrs.append(EGL_NONE); m_context = eglCreateContext(m_eglDisplay, m_config, m_shareEGLContext, eglContextAttrs.constData()); if (m_context == EGL_NO_CONTEXT) { m_context = eglCreateContext(m_eglDisplay, m_config, EGL_NO_CONTEXT, eglContextAttrs.constData()); m_shareEGLContext = EGL_NO_CONTEXT; } } QWaylandGLContext::~QWaylandGLContext() { delete m_blitProgram; delete m_textureCache; eglDestroyContext(m_eglDisplay, m_context); } bool QWaylandGLContext::makeCurrent(QPlatformSurface *surface) { QWaylandEglWindow *window = static_cast<QWaylandEglWindow *>(surface); EGLSurface eglSurface = window->eglSurface(); if (!eglMakeCurrent(m_eglDisplay, eglSurface, eglSurface, m_context)) { qWarning("QEGLPlatformContext::makeCurrent: eglError: %x, this: %p \n", eglGetError(), this); return false; } window->bindContentFBO(); return true; } void QWaylandGLContext::doneCurrent() { eglMakeCurrent(m_eglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); } void QWaylandGLContext::swapBuffers(QPlatformSurface *surface) { QWaylandEglWindow *window = static_cast<QWaylandEglWindow *>(surface); EGLSurface eglSurface = window->eglSurface(); if (window->decoration()) { makeCurrent(surface); if (!m_blitProgram) { m_blitProgram = new QOpenGLShaderProgram(); m_blitProgram->addShaderFromSourceCode(QOpenGLShader::Vertex, "attribute vec4 position;\n\ attribute vec4 texCoords;\n\ varying vec2 outTexCoords;\n\ void main()\n\ {\n\ gl_Position = position;\n\ outTexCoords = texCoords.xy;\n\ }"); m_blitProgram->addShaderFromSourceCode(QOpenGLShader::Fragment, "varying vec2 outTexCoords;\n\ uniform sampler2D texture;\n\ void main()\n\ {\n\ gl_FragColor = texture2D(texture, outTexCoords);\n\ }"); if (!m_blitProgram->link()) { qDebug() << "Shader Program link failed."; qDebug() << m_blitProgram->log(); } } if (!m_textureCache) { m_textureCache = new QOpenGLTextureCache(this->context()); } glDisable(GL_DEPTH_TEST); glDisable(GL_BLEND); glBindFramebuffer(GL_FRAMEBUFFER, 0); static const GLfloat squareVertices[] = { -1.f, -1.f, 1.0f, -1.f, -1.f, 1.0f, 1.0f, 1.0f }; static const GLfloat inverseSquareVertices[] = { -1.f, 1.f, 1.f, 1.f, -1.f, -1.f, 1.f, -1.f }; static const GLfloat textureVertices[] = { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, }; m_blitProgram->setUniformValue("texture", 0); m_blitProgram->enableAttributeArray("position"); m_blitProgram->enableAttributeArray("texCoords"); m_blitProgram->setAttributeArray("texCoords", textureVertices, 2); m_blitProgram->bind(); glActiveTexture(GL_TEXTURE0); //Draw Decoration m_blitProgram->setAttributeArray("position", inverseSquareVertices, 2); QImage decorationImage = window->decoration()->contentImage(); m_textureCache->bindTexture(context(), decorationImage); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); QRect windowRect = window->window()->frameGeometry(); glViewport(0, 0, windowRect.width(), windowRect.height()); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); //Draw Content m_blitProgram->setAttributeArray("position", squareVertices, 2); glBindTexture(GL_TEXTURE_2D, window->contentTexture()); QRect r = window->contentsRect(); glViewport(r.x(), r.y(), r.width(), r.height()); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); //Cleanup m_blitProgram->disableAttributeArray("position"); m_blitProgram->disableAttributeArray("texCoords"); m_blitProgram->release(); } eglSwapBuffers(m_eglDisplay, eglSurface); window->doResize(); } GLuint QWaylandGLContext::defaultFramebufferObject(QPlatformSurface *surface) const { return static_cast<QWaylandEglWindow *>(surface)->contentFBO(); } bool QWaylandGLContext::isSharing() const { return m_shareEGLContext != EGL_NO_CONTEXT; } bool QWaylandGLContext::isValid() const { return m_context != EGL_NO_CONTEXT; } void (*QWaylandGLContext::getProcAddress(const QByteArray &procName)) () { return eglGetProcAddress(procName.constData()); } EGLConfig QWaylandGLContext::eglConfig() const { return m_config; } <|endoftext|>
<commit_before>#include <gst/gst.h> #include "MediaPipeline.hpp" #include <WebRtcEndpointImplFactory.hpp> #include "WebRtcEndpointImpl.hpp" #include <jsonrpc/JsonSerializer.hpp> #include <KurentoException.hpp> #include <gst/gst.h> #include <boost/filesystem.hpp> #include <IceCandidate.hpp> #include <webrtcendpoint/kmsicecandidate.h> #define GST_CAT_DEFAULT kurento_web_rtc_endpoint_impl GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT); #define GST_DEFAULT_NAME "KurentoWebRtcEndpointImpl" #define FACTORY_NAME "webrtcendpoint" namespace kurento { static const std::string CERTTOOL_TEMPLATE = "autoCerttool.tmpl"; static const std::string CERT_KEY_PEM_FILE = "autoCertkey.pem"; static const uint DEFAULT_STUN_PORT = 3478; static std::shared_ptr<std::string> pemCertificate; std::mutex WebRtcEndpointImpl::certificateMutex; static void on_ice_candidate (GstElement *webrtcendpoint, KmsIceCandidate *candidate, gpointer data) { auto handler = reinterpret_cast<std::function<void (KmsIceCandidate *) >*> (data); (*handler) (candidate); } static void on_ice_gathering_done (GstElement *webrtcendpoint, gpointer data) { auto handler = reinterpret_cast<std::function<void() >*> (data); (*handler) (); } class TemporalDirectory { public: ~TemporalDirectory() { if (!dir.string ().empty() ) { boost::filesystem::remove_all (dir); } } void setDir (boost::filesystem::path &dir) { this->dir = dir; } private: boost::filesystem::path dir; }; static TemporalDirectory tmpDir; static void create_pem_certificate () { int ret; boost::filesystem::path temporalDirectory = boost::filesystem::unique_path ( boost::filesystem::temp_directory_path() / "WebRtcEndpoint_%%%%%%%%" ); boost::filesystem::create_directories (temporalDirectory); tmpDir.setDir (temporalDirectory); boost::filesystem::path pemFile = temporalDirectory / CERT_KEY_PEM_FILE; std::string pemGenerationCommand = "/bin/sh -c \"certtool --generate-privkey --outfile " + pemFile .string() + "\""; ret = system (pemGenerationCommand.c_str() ); if (ret == -1) { return; } boost::filesystem::path templateFile = temporalDirectory / CERTTOOL_TEMPLATE; std::string certtoolCommand = "/bin/sh -c \"echo 'organization = kurento' > " + templateFile.string() + " && certtool --generate-self-signed --load-privkey " + pemFile.string() + " --template " + templateFile.string() + " >> " + pemFile.string() + " 2>/dev/null\""; ret = system (certtoolCommand.c_str() ); if (ret == -1) { return; } pemCertificate = std::shared_ptr <std::string> (new std::string ( pemFile.string() ) ); } std::shared_ptr<std::string> WebRtcEndpointImpl::getPemCertificate () { std::unique_lock<std::mutex> lock (certificateMutex); if (pemCertificate) { return pemCertificate; } try { boost::filesystem::path pem_certificate_file_name ( getConfigValue<std::string, WebRtcEndpoint> ("pemCertificate") ); if (pem_certificate_file_name.is_relative() ) { pem_certificate_file_name = boost::filesystem::path ( config.get<std::string> ("configPath") ) / pem_certificate_file_name; } pemCertificate = std::shared_ptr <std::string> (new std::string ( pem_certificate_file_name.string() ) ); return pemCertificate; } catch (boost::property_tree::ptree_error &e) { } create_pem_certificate(); return pemCertificate; } WebRtcEndpointImpl::WebRtcEndpointImpl (const boost::property_tree::ptree &conf, std::shared_ptr<MediaPipeline> mediaPipeline) : BaseRtpEndpointImpl (conf, std::dynamic_pointer_cast<MediaObjectImpl> (mediaPipeline), FACTORY_NAME) { uint stunPort; std::string stunAddress; std::string turnURL; //set properties try { stunPort = getConfigValue <uint, WebRtcEndpoint> ("stunServerPort"); } catch (boost::property_tree::ptree_error &e) { GST_INFO ("Setting default port %d to stun server", DEFAULT_STUN_PORT); stunPort = DEFAULT_STUN_PORT; } if (stunPort != 0) { try { stunAddress = getConfigValue <std::string, WebRtcEndpoint> ("stunServerAddress"); } catch (boost::property_tree::ptree_error &e) { GST_INFO ("Stun address not found in config, cannot operate behind a NAT" ); } if (!stunAddress.empty() ) { GST_INFO ("stun port %d\n", stunPort ); g_object_set ( G_OBJECT (element), "stun-server-port", stunPort, NULL); GST_INFO ("stun address %s\n", stunAddress.c_str() ); g_object_set ( G_OBJECT (element), "stun-server", stunAddress.c_str(), NULL); } } try { turnURL = getConfigValue <std::string, WebRtcEndpoint> ("turnURL"); GST_INFO ("turn info: %s\n", turnURL.c_str() ); g_object_set ( G_OBJECT (element), "turn-url", turnURL.c_str(), NULL); } catch (boost::property_tree::ptree_error &e) { } g_object_set ( G_OBJECT (element), "certificate-pem-file", getPemCertificate ()->c_str(), NULL); onIceCandidateLambda = [&] (KmsIceCandidate * candidate) { try { std::string cand_str (kms_ice_candidate_get_candidate (candidate) ); std::string mid_str (kms_ice_candidate_get_sdp_mid (candidate) ); int sdp_m_line_index = kms_ice_candidate_get_sdp_m_line_index (candidate); std::shared_ptr <IceCandidate> cand ( new IceCandidate (cand_str, mid_str, sdp_m_line_index) ); OnIceCandidate event (cand, shared_from_this(), OnIceCandidate::getName() ); signalOnIceCandidate (event); } catch (std::bad_weak_ptr &e) { } }; handlerOnIceCandidate = g_signal_connect (element, "on-ice-candidate", G_CALLBACK (on_ice_candidate), &onIceCandidateLambda); onIceGatheringDoneLambda = [&] () { try { OnIceGatheringDone event (shared_from_this(), OnIceGatheringDone::getName() ); signalOnIceGatheringDone (event); } catch (std::bad_weak_ptr &e) { } }; handlerOnIceGatheringDone = g_signal_connect (element, "on-ice-gathering-done", G_CALLBACK (on_ice_gathering_done), &onIceGatheringDoneLambda); } WebRtcEndpointImpl::~WebRtcEndpointImpl() { g_signal_handler_disconnect (element, handlerOnIceCandidate); g_signal_handler_disconnect (element, handlerOnIceGatheringDone); } void WebRtcEndpointImpl::gatherCandidates () { gboolean ret; g_signal_emit_by_name (element, "gather-candidates", &ret); if (!ret) { throw KurentoException (ICE_GATHER_CANDIDATES_ERROR, "Error gathering candidates"); } } void WebRtcEndpointImpl::addIceCandidate (std::shared_ptr<IceCandidate> candidate) { gboolean ret; const char *cand_str = candidate->getCandidate().c_str (); const char *mid_str = candidate->getSdpMid().c_str (); guint8 sdp_m_line_index = candidate->getSdpMLineIndex (); KmsIceCandidate *cand = kms_ice_candidate_new (cand_str, mid_str, sdp_m_line_index); g_signal_emit_by_name (element, "add-ice-candidate", cand, &ret); if (!ret) { throw KurentoException (ICE_ADD_CANDIDATE_ERROR, "Error adding candidate"); } } MediaObjectImpl * WebRtcEndpointImplFactory::createObject (const boost::property_tree::ptree &conf, std::shared_ptr<MediaPipeline> mediaPipeline) const { return new WebRtcEndpointImpl (conf, mediaPipeline); } WebRtcEndpointImpl::StaticConstructor WebRtcEndpointImpl::staticConstructor; WebRtcEndpointImpl::StaticConstructor::StaticConstructor() { GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); } } /* kurento */ <commit_msg>WebRtcEndpoint: Fix format<commit_after>#include <gst/gst.h> #include "MediaPipeline.hpp" #include <WebRtcEndpointImplFactory.hpp> #include "WebRtcEndpointImpl.hpp" #include <jsonrpc/JsonSerializer.hpp> #include <KurentoException.hpp> #include <gst/gst.h> #include <boost/filesystem.hpp> #include <IceCandidate.hpp> #include <webrtcendpoint/kmsicecandidate.h> #define GST_CAT_DEFAULT kurento_web_rtc_endpoint_impl GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT); #define GST_DEFAULT_NAME "KurentoWebRtcEndpointImpl" #define FACTORY_NAME "webrtcendpoint" namespace kurento { static const std::string CERTTOOL_TEMPLATE = "autoCerttool.tmpl"; static const std::string CERT_KEY_PEM_FILE = "autoCertkey.pem"; static const uint DEFAULT_STUN_PORT = 3478; static std::shared_ptr<std::string> pemCertificate; std::mutex WebRtcEndpointImpl::certificateMutex; static void on_ice_candidate (GstElement *webrtcendpoint, KmsIceCandidate *candidate, gpointer data) { auto handler = reinterpret_cast<std::function<void (KmsIceCandidate *) >*> (data); (*handler) (candidate); } static void on_ice_gathering_done (GstElement *webrtcendpoint, gpointer data) { auto handler = reinterpret_cast<std::function<void() >*> (data); (*handler) (); } class TemporalDirectory { public: ~TemporalDirectory() { if (!dir.string ().empty() ) { boost::filesystem::remove_all (dir); } } void setDir (boost::filesystem::path &dir) { this->dir = dir; } private: boost::filesystem::path dir; }; static TemporalDirectory tmpDir; static void create_pem_certificate () { int ret; boost::filesystem::path temporalDirectory = boost::filesystem::unique_path ( boost::filesystem::temp_directory_path() / "WebRtcEndpoint_%%%%%%%%" ); boost::filesystem::create_directories (temporalDirectory); tmpDir.setDir (temporalDirectory); boost::filesystem::path pemFile = temporalDirectory / CERT_KEY_PEM_FILE; std::string pemGenerationCommand = "/bin/sh -c \"certtool --generate-privkey --outfile " + pemFile .string() + "\""; ret = system (pemGenerationCommand.c_str() ); if (ret == -1) { return; } boost::filesystem::path templateFile = temporalDirectory / CERTTOOL_TEMPLATE; std::string certtoolCommand = "/bin/sh -c \"echo 'organization = kurento' > " + templateFile.string() + " && certtool --generate-self-signed --load-privkey " + pemFile.string() + " --template " + templateFile.string() + " >> " + pemFile.string() + " 2>/dev/null\""; ret = system (certtoolCommand.c_str() ); if (ret == -1) { return; } pemCertificate = std::shared_ptr <std::string> (new std::string ( pemFile.string() ) ); } std::shared_ptr<std::string> WebRtcEndpointImpl::getPemCertificate () { std::unique_lock<std::mutex> lock (certificateMutex); if (pemCertificate) { return pemCertificate; } try { boost::filesystem::path pem_certificate_file_name ( getConfigValue<std::string, WebRtcEndpoint> ("pemCertificate") ); if (pem_certificate_file_name.is_relative() ) { pem_certificate_file_name = boost::filesystem::path ( config.get<std::string> ("configPath") ) / pem_certificate_file_name; } pemCertificate = std::shared_ptr <std::string> (new std::string ( pem_certificate_file_name.string() ) ); return pemCertificate; } catch (boost::property_tree::ptree_error &e) { } create_pem_certificate(); return pemCertificate; } WebRtcEndpointImpl::WebRtcEndpointImpl (const boost::property_tree::ptree &conf, std::shared_ptr<MediaPipeline> mediaPipeline) : BaseRtpEndpointImpl (conf, std::dynamic_pointer_cast<MediaObjectImpl> (mediaPipeline), FACTORY_NAME) { uint stunPort; std::string stunAddress; std::string turnURL; //set properties try { stunPort = getConfigValue <uint, WebRtcEndpoint> ("stunServerPort"); } catch (boost::property_tree::ptree_error &e) { GST_INFO ("Setting default port %d to stun server", DEFAULT_STUN_PORT); stunPort = DEFAULT_STUN_PORT; } if (stunPort != 0) { try { stunAddress = getConfigValue <std::string, WebRtcEndpoint> ("stunServerAddress"); } catch (boost::property_tree::ptree_error &e) { GST_INFO ("Stun address not found in config, cannot operate behind a NAT" ); } if (!stunAddress.empty() ) { GST_INFO ("stun port %d\n", stunPort ); g_object_set ( G_OBJECT (element), "stun-server-port", stunPort, NULL); GST_INFO ("stun address %s\n", stunAddress.c_str() ); g_object_set ( G_OBJECT (element), "stun-server", stunAddress.c_str(), NULL); } } try { turnURL = getConfigValue <std::string, WebRtcEndpoint> ("turnURL"); GST_INFO ("turn info: %s\n", turnURL.c_str() ); g_object_set ( G_OBJECT (element), "turn-url", turnURL.c_str(), NULL); } catch (boost::property_tree::ptree_error &e) { } g_object_set ( G_OBJECT (element), "certificate-pem-file", getPemCertificate ()->c_str(), NULL); onIceCandidateLambda = [&] (KmsIceCandidate * candidate) { try { std::string cand_str (kms_ice_candidate_get_candidate (candidate) ); std::string mid_str (kms_ice_candidate_get_sdp_mid (candidate) ); int sdp_m_line_index = kms_ice_candidate_get_sdp_m_line_index (candidate); std::shared_ptr <IceCandidate> cand ( new IceCandidate (cand_str, mid_str, sdp_m_line_index) ); OnIceCandidate event (cand, shared_from_this(), OnIceCandidate::getName() ); signalOnIceCandidate (event); } catch (std::bad_weak_ptr &e) { } }; handlerOnIceCandidate = g_signal_connect (element, "on-ice-candidate", G_CALLBACK (on_ice_candidate), &onIceCandidateLambda); onIceGatheringDoneLambda = [&] () { try { OnIceGatheringDone event (shared_from_this(), OnIceGatheringDone::getName() ); signalOnIceGatheringDone (event); } catch (std::bad_weak_ptr &e) { } }; handlerOnIceGatheringDone = g_signal_connect (element, "on-ice-gathering-done", G_CALLBACK (on_ice_gathering_done), &onIceGatheringDoneLambda); } WebRtcEndpointImpl::~WebRtcEndpointImpl() { g_signal_handler_disconnect (element, handlerOnIceCandidate); g_signal_handler_disconnect (element, handlerOnIceGatheringDone); } void WebRtcEndpointImpl::gatherCandidates () { gboolean ret; g_signal_emit_by_name (element, "gather-candidates", &ret); if (!ret) { throw KurentoException (ICE_GATHER_CANDIDATES_ERROR, "Error gathering candidates"); } } void WebRtcEndpointImpl::addIceCandidate (std::shared_ptr<IceCandidate> candidate) { gboolean ret; const char *cand_str = candidate->getCandidate().c_str (); const char *mid_str = candidate->getSdpMid().c_str (); guint8 sdp_m_line_index = candidate->getSdpMLineIndex (); KmsIceCandidate *cand = kms_ice_candidate_new (cand_str, mid_str, sdp_m_line_index); g_signal_emit_by_name (element, "add-ice-candidate", cand, &ret); if (!ret) { throw KurentoException (ICE_ADD_CANDIDATE_ERROR, "Error adding candidate"); } } MediaObjectImpl * WebRtcEndpointImplFactory::createObject (const boost::property_tree::ptree &conf, std::shared_ptr<MediaPipeline> mediaPipeline) const { return new WebRtcEndpointImpl (conf, mediaPipeline); } WebRtcEndpointImpl::StaticConstructor WebRtcEndpointImpl::staticConstructor; WebRtcEndpointImpl::StaticConstructor::StaticConstructor() { GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); } } /* kurento */ <|endoftext|>
<commit_before>//.............................................................................. // // This file is part of the AXL library. // // AXL is distributed under the MIT license. // For details see accompanying license.txt file, // the public copy of which is also available at: // http://tibbo.com/downloads/archive/axl/license.txt // //.............................................................................. #include "pch.h" #include "axl_io_File.h" #include "axl_io_Mapping.h" namespace axl { namespace io { //.............................................................................. #if (_AXL_OS_WIN) bool File::open ( const sl::StringRef& fileName, uint_t flags ) { uint_t accessMode = (flags & FileFlag_ReadOnly) ? GENERIC_READ : (flags & FileFlag_WriteOnly) ? GENERIC_WRITE : GENERIC_READ | GENERIC_WRITE; uint_t shareMode = (flags & FileFlag_Exclusive) ? 0 : (flags & (FileFlag_ReadOnly | FileFlag_ShareWrite)) ? FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE : FILE_SHARE_READ; uint_t creationDisposition = (flags & (FileFlag_ReadOnly | FileFlag_OpenExisting)) ? OPEN_EXISTING : OPEN_ALWAYS; uint_t flagsAttributes = (flags & FileFlag_DeleteOnClose) ? FILE_FLAG_DELETE_ON_CLOSE : 0; if (flags & FileFlag_Asynchronous) flagsAttributes |= FILE_FLAG_OVERLAPPED; char buffer [256]; sl::String_w fileName_w (ref::BufKind_Stack, buffer, sizeof (buffer)); fileName_w = fileName; bool result = m_file.create ( fileName_w, accessMode, shareMode, NULL, creationDisposition, flagsAttributes ); if (!result) return false; if (flags & FileFlag_Clear) m_file.setSize (0); return true; } #elif (_AXL_OS_POSIX) bool File::open ( const sl::StringRef& fileName, uint_t flags ) { uint_t posixFlags = (flags & FileFlag_ReadOnly) ? O_RDONLY : (flags & FileFlag_WriteOnly) ? O_WRONLY : O_RDWR; if (!(flags & (FileFlag_ReadOnly | FileFlag_OpenExisting))) posixFlags |= O_CREAT; if (flags & FileFlag_Asynchronous) posixFlags |= O_NONBLOCK; // TODO: handle exclusive and share write flags with fcntl locks bool result = m_file.open (fileName.sz (), posixFlags); if (!result) return false; if (flags & FileFlag_DeleteOnClose) ::unlink (fileName.sz ()); if (flags & FileFlag_Clear) m_file.setSize (0); return true; } #endif //.............................................................................. #if (_AXL_OS_POSIX) void TemporaryFile::close () { if (!isOpen ()) return; File::close (); deleteFile (m_fileName); m_fileName.clear (); } bool TemporaryFile::open ( const sl::StringRef& fileName, uint_t flags ) { close (); bool result = File::open (fileName, flags & ~FileFlag_DeleteOnClose); if (!result) return false; m_fileName = fileName; return true; } #endif //.............................................................................. uint64_t copyFile ( const sl::StringRef& srcFileName, const sl::StringRef& dstFileName, uint64_t size ) { File srcFile; bool result = srcFile.open (srcFileName, FileFlag_ReadOnly); if (!result) return -1; return copyFile (&srcFile, dstFileName, size); } uint64_t copyFile ( const io::File* srcFile, const sl::StringRef& dstFileName, uint64_t size ) { File dstFile; bool result = dstFile.open (dstFileName); if (!result) return -1; enum { BlockSize = 32 * 1024, // 32 K }; if (size == -1) size = srcFile->getSize (); uint64_t offset = 0; #if (_AXL_OS_WIN) win::Mapping srcMapping; win::Mapping dstMapping; win::MappedView srcView; win::MappedView dstView; result = srcMapping.create (srcFile->m_file, NULL, PAGE_READONLY, size) && dstMapping.create (dstFile.m_file, NULL, PAGE_READWRITE, size); while (size) { size_t blockSize = (size_t) AXL_MIN (BlockSize, size); const void* src = srcView.view (srcMapping, FILE_MAP_READ, offset, blockSize); void* dst = dstView.view (dstMapping, FILE_MAP_READ | FILE_MAP_WRITE, offset, blockSize); if (!src || !dst) return -1; memcpy (dst, src, blockSize); offset += blockSize; size -= blockSize; } srcMapping.close (); dstMapping.close (); srcView.close (); dstView.close (); #else psx::Mapping srcMapping; psx::Mapping dstMapping; result = dstFile.setSize (size); if (!result) return -1; while (size) { size_t blockSize = AXL_MIN (BlockSize, size); const void* src = srcMapping.map (NULL, blockSize, PROT_READ, MAP_SHARED, srcFile->m_file, offset); void* dst = dstMapping.map (NULL, blockSize, PROT_READ | PROT_WRITE, MAP_SHARED, dstFile.m_file, offset); if (!src || !dst) return -1; memcpy (dst, src, blockSize); offset += blockSize; size -= blockSize; } srcMapping.close (); dstMapping.close (); #endif return offset; } //.............................................................................. } // namespace io } // namespace axl <commit_msg>[axl_io] critical bugfix: block size for file copying should be a multiple of systemInfo->m_mappingAlignFactor<commit_after>//.............................................................................. // // This file is part of the AXL library. // // AXL is distributed under the MIT license. // For details see accompanying license.txt file, // the public copy of which is also available at: // http://tibbo.com/downloads/archive/axl/license.txt // //.............................................................................. #include "pch.h" #include "axl_io_File.h" #include "axl_io_Mapping.h" namespace axl { namespace io { //.............................................................................. #if (_AXL_OS_WIN) bool File::open ( const sl::StringRef& fileName, uint_t flags ) { uint_t accessMode = (flags & FileFlag_ReadOnly) ? GENERIC_READ : (flags & FileFlag_WriteOnly) ? GENERIC_WRITE : GENERIC_READ | GENERIC_WRITE; uint_t shareMode = (flags & FileFlag_Exclusive) ? 0 : (flags & (FileFlag_ReadOnly | FileFlag_ShareWrite)) ? FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE : FILE_SHARE_READ; uint_t creationDisposition = (flags & (FileFlag_ReadOnly | FileFlag_OpenExisting)) ? OPEN_EXISTING : OPEN_ALWAYS; uint_t flagsAttributes = (flags & FileFlag_DeleteOnClose) ? FILE_FLAG_DELETE_ON_CLOSE : 0; if (flags & FileFlag_Asynchronous) flagsAttributes |= FILE_FLAG_OVERLAPPED; char buffer [256]; sl::String_w fileName_w (ref::BufKind_Stack, buffer, sizeof (buffer)); fileName_w = fileName; bool result = m_file.create ( fileName_w, accessMode, shareMode, NULL, creationDisposition, flagsAttributes ); if (!result) return false; if (flags & FileFlag_Clear) m_file.setSize (0); return true; } #elif (_AXL_OS_POSIX) bool File::open ( const sl::StringRef& fileName, uint_t flags ) { uint_t posixFlags = (flags & FileFlag_ReadOnly) ? O_RDONLY : (flags & FileFlag_WriteOnly) ? O_WRONLY : O_RDWR; if (!(flags & (FileFlag_ReadOnly | FileFlag_OpenExisting))) posixFlags |= O_CREAT; if (flags & FileFlag_Asynchronous) posixFlags |= O_NONBLOCK; // TODO: handle exclusive and share write flags with fcntl locks bool result = m_file.open (fileName.sz (), posixFlags); if (!result) return false; if (flags & FileFlag_DeleteOnClose) ::unlink (fileName.sz ()); if (flags & FileFlag_Clear) m_file.setSize (0); return true; } #endif //.............................................................................. #if (_AXL_OS_POSIX) void TemporaryFile::close () { if (!isOpen ()) return; File::close (); deleteFile (m_fileName); m_fileName.clear (); } bool TemporaryFile::open ( const sl::StringRef& fileName, uint_t flags ) { close (); bool result = File::open (fileName, flags & ~FileFlag_DeleteOnClose); if (!result) return false; m_fileName = fileName; return true; } #endif //.............................................................................. uint64_t copyFile ( const sl::StringRef& srcFileName, const sl::StringRef& dstFileName, uint64_t size ) { File srcFile; bool result = srcFile.open (srcFileName, FileFlag_ReadOnly); if (!result) return -1; return copyFile (&srcFile, dstFileName, size); } uint64_t copyFile ( const io::File* srcFile, const sl::StringRef& dstFileName, uint64_t size ) { File dstFile; bool result = dstFile.open (dstFileName); if (!result) return -1; enum { BaseBlockSize = 64 * 1024, // 64K }; g::SystemInfo* systemInfo = g::getModule ()->getSystemInfo (); size_t blockSize = BaseBlockSize + systemInfo->m_mappingAlignFactor - BaseBlockSize % systemInfo->m_mappingAlignFactor; uint64_t offset = 0; if (size == -1) size = srcFile->getSize (); #if (_AXL_OS_WIN) win::Mapping srcMapping; win::Mapping dstMapping; win::MappedView srcView; win::MappedView dstView; result = srcMapping.create (srcFile->m_file, NULL, PAGE_READONLY, size) && dstMapping.create (dstFile.m_file, NULL, PAGE_READWRITE, size); if (!result) return -1; while (size) { if (blockSize > size) blockSize = (size_t) size; const void* src = srcView.view (srcMapping, FILE_MAP_READ, offset, blockSize); void* dst = dstView.view (dstMapping, FILE_MAP_READ | FILE_MAP_WRITE, offset, blockSize); if (!src || !dst) return -1; memcpy (dst, src, blockSize); offset += blockSize; size -= blockSize; } srcMapping.close (); dstMapping.close (); srcView.close (); dstView.close (); #else psx::Mapping srcMapping; psx::Mapping dstMapping; result = dstFile.setSize (size); if (!result) return -1; while (size) { if (blockSize > size) blockSize = (size_t) size; const void* src = srcMapping.map (NULL, blockSize, PROT_READ, MAP_SHARED, srcFile->m_file, offset); void* dst = dstMapping.map (NULL, blockSize, PROT_READ | PROT_WRITE, MAP_SHARED, dstFile.m_file, offset); if (!src || !dst) return -1; memcpy (dst, src, blockSize); offset += blockSize; size -= blockSize; } srcMapping.close (); dstMapping.close (); #endif return offset; } //.............................................................................. } // namespace io } // namespace axl <|endoftext|>
<commit_before>// Copyright 2010-2012 Google // 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 "base/filelinereader.h" #include <string.h> #include <string> #include "base/file.h" #include "base/logging.h" #include "base/scoped_ptr.h" namespace operations_research { FileLineReader::FileLineReader(const char* const filename) : filename_(filename), line_callback_(NULL), loaded_successfully_(false) {} FileLineReader::~FileLineReader() {} void FileLineReader::set_line_callback(Callback1<char*>* const callback) { line_callback_.reset(callback); } void FileLineReader::Reload() { const int kMaxLineLength = 60 * 1024; File* const data_file = File::Open(filename_, "r"); if (data_file == NULL) { loaded_successfully_ = false; return; } scoped_array<char> line(new char[kMaxLineLength]); for (;;) { char* const result = data_file->ReadLine(line.get(), kMaxLineLength); if (result == NULL) { data_file->Close(); loaded_successfully_ = true; return; } // Chop the last linefeed if present. int len = strlen(result); if (len > 0 && result[len - 1] == '\n') { // Linefeed. result[--len] = '\0'; } if (len > 0 && result[len - 1] == '\r') { // Carriage return. result[--len] = '\0'; } if (line_callback_.get() != NULL) { line_callback_->Run(result); } } } bool FileLineReader::loaded_successfully() const { return loaded_successfully_; } } // namespace operations_research <commit_msg>fix some leak on file API<commit_after>// Copyright 2010-2012 Google // 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 "base/filelinereader.h" #include <string.h> #include <string> #include "base/file.h" #include "base/logging.h" #include "base/scoped_ptr.h" namespace operations_research { FileLineReader::FileLineReader(const char* const filename) : filename_(filename), line_callback_(NULL), loaded_successfully_(false) {} FileLineReader::~FileLineReader() {} void FileLineReader::set_line_callback(Callback1<char*>* const callback) { line_callback_.reset(callback); } void FileLineReader::Reload() { const int kMaxLineLength = 60 * 1024; File* const data_file = File::Open(filename_, "r"); if (data_file == NULL) { loaded_successfully_ = false; return; } scoped_array<char> line(new char[kMaxLineLength]); for (;;) { char* const result = data_file->ReadLine(line.get(), kMaxLineLength); if (result == NULL) { data_file->Close(); loaded_successfully_ = true; return; } // Chop the last linefeed if present. int len = strlen(result); if (len > 0 && result[len - 1] == '\n') { // Linefeed. result[--len] = '\0'; } if (len > 0 && result[len - 1] == '\r') { // Carriage return. result[--len] = '\0'; } if (line_callback_.get() != NULL) { line_callback_->Run(result); } } data_file->Close(); } bool FileLineReader::loaded_successfully() const { return loaded_successfully_; } } // namespace operations_research <|endoftext|>
<commit_before>/* * Copyright (c) 2014 Juniper Networks, Inc. All rights reserved. */ extern "C" { #include <ovsdb_wrapper.h> } #include <ovsdb_object.h> #include <ovsdb_entry.h> #include <ovsdb_types.h> using OVSDB::OvsdbEntry; using OVSDB::OvsdbDBEntry; using OVSDB::OvsdbObject; using OVSDB::OvsdbDBObject; OvsdbEntry::OvsdbEntry(OvsdbObject *table) : KSyncEntry(), table_(table), ovs_entry_(NULL) { } OvsdbEntry::OvsdbEntry(OvsdbObject *table, uint32_t index) : KSyncEntry(index), table_(table), ovs_entry_(NULL) { } OvsdbEntry::~OvsdbEntry() { } bool OvsdbEntry::Add() { return true; } bool OvsdbEntry::Change() { return true; } bool OvsdbEntry::Delete() { return true; } KSyncObject *OvsdbEntry::GetObject() { return table_; } void OvsdbEntry::Ack(bool success) { // TODO we don't handle failures for these entries if (!success) { OVSDB_TRACE(Error, "Transaction failed for " + ToString()); } OvsdbObject *object = static_cast<OvsdbObject*>(GetObject()); object->NotifyEvent(this, ack_event_); } OvsdbDBEntry::OvsdbDBEntry(OvsdbDBObject *table) : KSyncDBEntry(), table_(table), ovs_entry_(NULL) { } OvsdbDBEntry::OvsdbDBEntry(OvsdbDBObject *table, struct ovsdb_idl_row *ovs_entry) : KSyncDBEntry(), table_(table), ovs_entry_(ovs_entry) { } OvsdbDBEntry::~OvsdbDBEntry() { } bool OvsdbDBEntry::Add() { OvsdbDBObject *object = static_cast<OvsdbDBObject*>(GetObject()); // trigger pre add/change only if idl is not marked deleted. // we should not update KSync references as, these references eventually // need to be released as part of delete trigger due to cleanup. if (object->client_idl_ != NULL && !object->client_idl_->deleted()) { PreAddChange(); } if (IsNoTxnEntry()) { // trigger AddMsg with NULL pointer and return true to complete // KSync state AddMsg(NULL); return true; } struct ovsdb_idl_txn *txn; if (UseBulkTxn()) { txn = object->client_idl_->CreateBulkTxn(this, KSyncEntry::ADD_ACK); } else { txn = object->client_idl_->CreateTxn(this, KSyncEntry::ADD_ACK); } if (txn == NULL) { // failed to create transaction because of idl marked for // deletion return from here. TxnDoneNoMessage(); return true; } AddMsg(txn); return object->client_idl_->EncodeSendTxn(txn, this); } bool OvsdbDBEntry::Change() { OvsdbDBObject *object = static_cast<OvsdbDBObject*>(GetObject()); // trigger pre add/change only if idl is not marked deleted. // we should not update KSync references as, these references eventually // need to be released as part of delete trigger due to cleanup. if (object->client_idl_ != NULL && !object->client_idl_->deleted()) { PreAddChange(); } if (IsNoTxnEntry()) { // trigger ChangeMsg with NULL pointer and return true to complete // KSync state ChangeMsg(NULL); return true; } struct ovsdb_idl_txn *txn; if (UseBulkTxn()) { txn = object->client_idl_->CreateBulkTxn(this, KSyncEntry::CHANGE_ACK); } else { txn = object->client_idl_->CreateTxn(this, KSyncEntry::CHANGE_ACK); } if (txn == NULL) { // failed to create transaction because of idl marked for // deletion return from here. TxnDoneNoMessage(); return true; } ChangeMsg(txn); return object->client_idl_->EncodeSendTxn(txn, this); } bool OvsdbDBEntry::Delete() { if (IsNoTxnEntry()) { // trigger DeleteMsg with NULL pointer DeleteMsg(NULL); // trigger Post Delete, to allow post delete processing PostDelete(); // return true to complete KSync State return true; } OvsdbDBObject *object = static_cast<OvsdbDBObject*>(GetObject()); struct ovsdb_idl_txn *txn; if (UseBulkTxn()) { txn = object->client_idl_->CreateBulkTxn(this, KSyncEntry::DEL_ACK); } else { txn = object->client_idl_->CreateTxn(this, KSyncEntry::DEL_ACK); } if (txn == NULL) { // failed to create transaction because of idl marked for // deletion return from here. TxnDoneNoMessage(); return true; } DeleteMsg(txn); bool ret = object->client_idl_->EncodeSendTxn(txn, this); // trigger post delete if we are not waiting for Ack // otherwise trigger post delete on Ack if (ret) { // current transaction send completed trigger post delete PostDelete(); } return ret; } bool OvsdbDBEntry::IsDataResolved() { return (ovs_entry_ == NULL) ? false : true; } bool OvsdbDBEntry::IsDelAckWaiting() { KSyncState state = GetState(); return (state >= DEL_DEFER_DEL_ACK && state <= RENEW_WAIT); } bool OvsdbDBEntry::IsAddChangeAckWaiting() { KSyncState state = GetState(); return (state == SYNC_WAIT || state == NEED_SYNC || state == DEL_DEFER_SYNC); } void OvsdbDBEntry::NotifyAdd(struct ovsdb_idl_row *row) { if (ovs_entry_ == NULL) { ovs_entry_ = row; } else { // ovs_entry should never change from Non-NULL value to // another Non-NULL value. assert(ovs_entry_ == row); } OvsdbChange(); } void OvsdbDBEntry::NotifyDelete(struct ovsdb_idl_row *row) { ovs_entry_ = NULL; } KSyncObject *OvsdbDBEntry::GetObject() { return table_; } void OvsdbDBEntry::Ack(bool success) { OvsdbDBObject *object = static_cast<OvsdbDBObject*>(GetObject()); // trigger post delete for Del Ack if (ack_event_ == KSyncEntry::DEL_ACK) { // current transaction send completed trigger post delete PostDelete(); } if (success) { if (IsDelAckWaiting()) object->NotifyEvent(this, KSyncEntry::DEL_ACK); else if (IsAddChangeAckWaiting()) object->NotifyEvent(this, KSyncEntry::ADD_ACK); else delete this; } else { bool trigger_ack = false; // On Failure try again if (IsDelAckWaiting()) { OVSDB_TRACE(Error, "Delete Transaction failed for " + ToString()); // if we are waiting to renew, dont retry delete. if (GetState() != RENEW_WAIT) { // trigger ack when if no message to send, on calling delete trigger_ack = Delete(); } else { trigger_ack = true; } if (trigger_ack) { object->NotifyEvent(this, KSyncEntry::DEL_ACK); } } else if (IsAddChangeAckWaiting()) { OVSDB_TRACE(Error, "Add Transaction failed for " + ToString()); // if we are waiting to delete, dont retry add. if (GetState() != DEL_DEFER_SYNC) { // Enqueue a change before generating an ADD_ACK to keep // the entry in a not sync'd state. object->Change(this); } object->NotifyEvent(this, KSyncEntry::ADD_ACK); } else { // should never happen assert(0); } } } void OvsdbDBEntry::TriggerDeleteAdd() { GetObject()->SafeNotifyEvent(this, KSyncEntry::DEL_ADD_REQ); } <commit_msg>Fix ToR agent DELADD operation usage<commit_after>/* * Copyright (c) 2014 Juniper Networks, Inc. All rights reserved. */ extern "C" { #include <ovsdb_wrapper.h> } #include <ovsdb_object.h> #include <ovsdb_entry.h> #include <ovsdb_types.h> using OVSDB::OvsdbEntry; using OVSDB::OvsdbDBEntry; using OVSDB::OvsdbObject; using OVSDB::OvsdbDBObject; OvsdbEntry::OvsdbEntry(OvsdbObject *table) : KSyncEntry(), table_(table), ovs_entry_(NULL) { } OvsdbEntry::OvsdbEntry(OvsdbObject *table, uint32_t index) : KSyncEntry(index), table_(table), ovs_entry_(NULL) { } OvsdbEntry::~OvsdbEntry() { } bool OvsdbEntry::Add() { return true; } bool OvsdbEntry::Change() { return true; } bool OvsdbEntry::Delete() { return true; } KSyncObject *OvsdbEntry::GetObject() { return table_; } void OvsdbEntry::Ack(bool success) { // TODO we don't handle failures for these entries if (!success) { OVSDB_TRACE(Error, "Transaction failed for " + ToString()); } OvsdbObject *object = static_cast<OvsdbObject*>(GetObject()); object->NotifyEvent(this, ack_event_); } OvsdbDBEntry::OvsdbDBEntry(OvsdbDBObject *table) : KSyncDBEntry(), table_(table), ovs_entry_(NULL) { } OvsdbDBEntry::OvsdbDBEntry(OvsdbDBObject *table, struct ovsdb_idl_row *ovs_entry) : KSyncDBEntry(), table_(table), ovs_entry_(ovs_entry) { } OvsdbDBEntry::~OvsdbDBEntry() { } bool OvsdbDBEntry::Add() { OvsdbDBObject *object = static_cast<OvsdbDBObject*>(GetObject()); // trigger pre add/change only if idl is not marked deleted. // we should not update KSync references as, these references eventually // need to be released as part of delete trigger due to cleanup. if (object->client_idl_ != NULL && !object->client_idl_->deleted()) { PreAddChange(); } if (IsNoTxnEntry()) { // trigger AddMsg with NULL pointer and return true to complete // KSync state AddMsg(NULL); return true; } struct ovsdb_idl_txn *txn; if (UseBulkTxn()) { txn = object->client_idl_->CreateBulkTxn(this, KSyncEntry::ADD_ACK); } else { txn = object->client_idl_->CreateTxn(this, KSyncEntry::ADD_ACK); } if (txn == NULL) { // failed to create transaction because of idl marked for // deletion return from here. TxnDoneNoMessage(); return true; } AddMsg(txn); return object->client_idl_->EncodeSendTxn(txn, this); } bool OvsdbDBEntry::Change() { OvsdbDBObject *object = static_cast<OvsdbDBObject*>(GetObject()); // trigger pre add/change only if idl is not marked deleted. // we should not update KSync references as, these references eventually // need to be released as part of delete trigger due to cleanup. if (object->client_idl_ != NULL && !object->client_idl_->deleted()) { PreAddChange(); } if (IsNoTxnEntry()) { // trigger ChangeMsg with NULL pointer and return true to complete // KSync state ChangeMsg(NULL); return true; } struct ovsdb_idl_txn *txn; if (UseBulkTxn()) { txn = object->client_idl_->CreateBulkTxn(this, KSyncEntry::CHANGE_ACK); } else { txn = object->client_idl_->CreateTxn(this, KSyncEntry::CHANGE_ACK); } if (txn == NULL) { // failed to create transaction because of idl marked for // deletion return from here. TxnDoneNoMessage(); return true; } ChangeMsg(txn); return object->client_idl_->EncodeSendTxn(txn, this); } bool OvsdbDBEntry::Delete() { if (IsNoTxnEntry()) { // trigger DeleteMsg with NULL pointer DeleteMsg(NULL); // trigger Post Delete, to allow post delete processing PostDelete(); // return true to complete KSync State return true; } OvsdbDBObject *object = static_cast<OvsdbDBObject*>(GetObject()); struct ovsdb_idl_txn *txn; if (UseBulkTxn()) { txn = object->client_idl_->CreateBulkTxn(this, KSyncEntry::DEL_ACK); } else { txn = object->client_idl_->CreateTxn(this, KSyncEntry::DEL_ACK); } if (txn == NULL) { // failed to create transaction because of idl marked for // deletion return from here. TxnDoneNoMessage(); return true; } DeleteMsg(txn); bool ret = object->client_idl_->EncodeSendTxn(txn, this); // trigger post delete if we are not waiting for Ack // otherwise trigger post delete on Ack if (ret) { // current transaction send completed trigger post delete PostDelete(); } return ret; } bool OvsdbDBEntry::IsDataResolved() { return (ovs_entry_ == NULL) ? false : true; } bool OvsdbDBEntry::IsDelAckWaiting() { KSyncState state = GetState(); return (state >= DEL_DEFER_DEL_ACK && state <= RENEW_WAIT); } bool OvsdbDBEntry::IsAddChangeAckWaiting() { KSyncState state = GetState(); return (state == SYNC_WAIT || state == NEED_SYNC || state == DEL_DEFER_SYNC); } void OvsdbDBEntry::NotifyAdd(struct ovsdb_idl_row *row) { if (ovs_entry_ == NULL) { ovs_entry_ = row; } else { // ovs_entry should never change from Non-NULL value to // another Non-NULL value. assert(ovs_entry_ == row); } OvsdbChange(); } void OvsdbDBEntry::NotifyDelete(struct ovsdb_idl_row *row) { ovs_entry_ = NULL; } KSyncObject *OvsdbDBEntry::GetObject() { return table_; } void OvsdbDBEntry::Ack(bool success) { OvsdbDBObject *object = static_cast<OvsdbDBObject*>(GetObject()); // trigger post delete for Del Ack if (ack_event_ == KSyncEntry::DEL_ACK) { // current transaction send completed trigger post delete PostDelete(); } if (success) { if (IsDelAckWaiting()) object->NotifyEvent(this, KSyncEntry::DEL_ACK); else if (IsAddChangeAckWaiting()) object->NotifyEvent(this, KSyncEntry::ADD_ACK); else delete this; } else { bool trigger_ack = false; // On Failure try again if (IsDelAckWaiting()) { OVSDB_TRACE(Error, "Delete Transaction failed for " + ToString()); // if we are waiting to renew, dont retry delete. if (GetState() != RENEW_WAIT) { // trigger ack when if no message to send, on calling delete trigger_ack = Delete(); } else { trigger_ack = true; } if (trigger_ack) { object->NotifyEvent(this, KSyncEntry::DEL_ACK); } } else if (IsAddChangeAckWaiting()) { OVSDB_TRACE(Error, "Add Transaction failed for " + ToString()); // if we are waiting to delete, dont retry add. if (GetState() != DEL_DEFER_SYNC) { // Enqueue a change before generating an ADD_ACK to keep // the entry in a not sync'd state. object->Change(this); } object->NotifyEvent(this, KSyncEntry::ADD_ACK); } else { // should never happen assert(0); } } } void OvsdbDBEntry::TriggerDeleteAdd() { if (IsDeleted() || stale()) { // skip this operation for Deleted/stale Entry, After this operation // Deleted/Stale entry would become active/non-stale which is not // intended use of this API, caller must ensure the entry to be Active // if this operation is required return; } GetObject()->SafeNotifyEvent(this, KSyncEntry::DEL_ADD_REQ); } <|endoftext|>
<commit_before>#pragma once #include <mutex> /*! * Namespace indents were made intentionally to improve the readability. */ namespace blackhole { namespace repository { namespace config { template<class T> struct transformer_t; template<class To> class parser_t; } // namespace config } // namespace repository class base_frontend_t; class frontend_factory_t; class formatter_config_t; class sink_config_t; class logger_base_t; template<typename Level> class verbose_logger_t; template<class Logger> class wrapper_t; template<class T, class Mutex = std::mutex> class synchronized; } // namespace blackhole <commit_msg>[Aux] More forward declarations.<commit_after>#pragma once #include <mutex> /*! * Namespace indents were made intentionally to improve the readability. */ namespace blackhole { namespace repository { namespace config { template<class T> struct transformer_t; template<class To> class parser_t; } // namespace config } // namespace repository class base_frontend_t; class frontend_factory_t; class formatter_config_t; class sink_config_t; class record_t; class logger_base_t; template<typename Level> class verbose_logger_t; template<class Logger> class wrapper_t; template<class T, class Mutex = std::mutex> class synchronized; } // namespace blackhole <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** **************************************************************************/ #include "generalsettingspage.h" #include "bookmarkmanager.h" #include "centralwidget.h" #include "helpconstants.h" #include "helpviewer.h" #include "localhelpmanager.h" #include "xbelsupport.h" #include <coreplugin/coreconstants.h> #include <coreplugin/helpmanager.h> #include <coreplugin/icore.h> #include <utils/fileutils.h> #include <QCoreApplication> #include <QSettings> #include <QTextStream> #include <QApplication> #include <QFileDialog> #if !defined(QT_NO_WEBKIT) #include <QWebSettings> #endif using namespace Help::Internal; GeneralSettingsPage::GeneralSettingsPage() : m_ui(0) { m_font = qApp->font(); #if !defined(QT_NO_WEBKIT) QWebSettings* webSettings = QWebSettings::globalSettings(); m_font.setPointSize(webSettings->fontSize(QWebSettings::DefaultFontSize)); #endif setId(QLatin1String("A.General settings")); setDisplayName(tr("General")); setCategory(QLatin1String(Help::Constants::HELP_CATEGORY)); setDisplayCategory(QCoreApplication::translate("Help", Help::Constants::HELP_TR_CATEGORY)); setCategoryIcon(QLatin1String(Help::Constants::HELP_CATEGORY_ICON)); } QWidget *GeneralSettingsPage::createPage(QWidget *parent) { QWidget *widget = new QWidget(parent); m_ui = new Ui::GeneralSettingsPage; m_ui->setupUi(widget); m_ui->sizeComboBox->setEditable(false); m_ui->styleComboBox->setEditable(false); Core::HelpManager *manager = Core::HelpManager::instance(); m_font = qVariantValue<QFont>(manager->customValue(QLatin1String("font"), m_font)); updateFontSize(); updateFontStyle(); updateFontFamily(); m_homePage = manager->customValue(QLatin1String("HomePage"), QString()) .toString(); if (m_homePage.isEmpty()) { m_homePage = manager->customValue(QLatin1String("DefaultHomePage"), Help::Constants::AboutBlank).toString(); } m_ui->homePageLineEdit->setText(m_homePage); const int startOption = manager->customValue(QLatin1String("StartOption"), Help::Constants::ShowLastPages).toInt(); m_ui->helpStartComboBox->setCurrentIndex(startOption); m_contextOption = manager->customValue(QLatin1String("ContextHelpOption"), Help::Constants::SideBySideIfPossible).toInt(); m_ui->contextHelpComboBox->setCurrentIndex(m_contextOption); connect(m_ui->currentPageButton, SIGNAL(clicked()), this, SLOT(setCurrentPage())); connect(m_ui->blankPageButton, SIGNAL(clicked()), this, SLOT(setBlankPage())); connect(m_ui->defaultPageButton, SIGNAL(clicked()), this, SLOT(setDefaultPage())); HelpViewer *viewer = CentralWidget::instance()->currentHelpViewer(); if (!viewer) m_ui->currentPageButton->setEnabled(false); m_ui->errorLabel->setVisible(false); connect(m_ui->importButton, SIGNAL(clicked()), this, SLOT(importBookmarks())); connect(m_ui->exportButton, SIGNAL(clicked()), this, SLOT(exportBookmarks())); if (m_searchKeywords.isEmpty()) { QTextStream(&m_searchKeywords) << ' ' << m_ui->contextHelpLabel->text() << ' ' << m_ui->startPageLabel->text() << ' ' << m_ui->homePageLabel->text() << ' ' << m_ui->bookmarkGroupBox->title(); m_searchKeywords.remove(QLatin1Char('&')); } m_returnOnClose = manager->customValue(QLatin1String("ReturnOnClose"), false).toBool(); m_ui->m_returnOnClose->setChecked(m_returnOnClose); return widget; } void GeneralSettingsPage::apply() { if (!m_ui) // page was never shown return; QFont newFont; const QString &family = m_ui->familyComboBox->currentFont().family(); newFont.setFamily(family); int fontSize = 14; int currentIndex = m_ui->sizeComboBox->currentIndex(); if (currentIndex != -1) fontSize = m_ui->sizeComboBox->itemData(currentIndex).toInt(); newFont.setPointSize(fontSize); QString fontStyle = QLatin1String("Normal"); currentIndex = m_ui->styleComboBox->currentIndex(); if (currentIndex != -1) fontStyle = m_ui->styleComboBox->itemText(currentIndex); newFont.setBold(m_fontDatabase.bold(family, fontStyle)); if (fontStyle.contains(QLatin1String("Italic"))) newFont.setStyle(QFont::StyleItalic); else if (fontStyle.contains(QLatin1String("Oblique"))) newFont.setStyle(QFont::StyleOblique); else newFont.setStyle(QFont::StyleNormal); const int weight = m_fontDatabase.weight(family, fontStyle); if (weight >= 0) // Weight < 0 asserts... newFont.setWeight(weight); Core::HelpManager *manager = Core::HelpManager::instance(); if (newFont != m_font) { m_font = newFont; manager->setCustomValue(QLatin1String("font"), newFont); emit fontChanged(); } QString homePage = m_ui->homePageLineEdit->text(); if (homePage.isEmpty()) homePage = Help::Constants::AboutBlank; manager->setCustomValue(QLatin1String("HomePage"), homePage); const int startOption = m_ui->helpStartComboBox->currentIndex(); manager->setCustomValue(QLatin1String("StartOption"), startOption); const int helpOption = m_ui->contextHelpComboBox->currentIndex(); if (m_contextOption != helpOption) { m_contextOption = helpOption; manager->setCustomValue(QLatin1String("ContextHelpOption"), helpOption); QSettings *settings = Core::ICore::settings(); settings->beginGroup(Help::Constants::ID_MODE_HELP); settings->setValue(QLatin1String("ContextHelpOption"), helpOption); settings->endGroup(); emit contextHelpOptionChanged(); } const bool close = m_ui->m_returnOnClose->isChecked(); if (m_returnOnClose != close) { m_returnOnClose = close; manager->setCustomValue(QLatin1String("ReturnOnClose"), close); emit returnOnCloseChanged(); } } void GeneralSettingsPage::setCurrentPage() { HelpViewer *viewer = CentralWidget::instance()->currentHelpViewer(); if (viewer) m_ui->homePageLineEdit->setText(viewer->source().toString()); } void GeneralSettingsPage::setBlankPage() { m_ui->homePageLineEdit->setText(Help::Constants::AboutBlank); } void GeneralSettingsPage::setDefaultPage() { const QString &defaultHomePage = Core::HelpManager::instance() ->customValue(QLatin1String("DefaultHomePage"), QString()).toString(); m_ui->homePageLineEdit->setText(defaultHomePage); } void GeneralSettingsPage::importBookmarks() { m_ui->errorLabel->setVisible(false); QString fileName = QFileDialog::getOpenFileName(0, tr("Import Bookmarks"), QDir::currentPath(), tr("Files (*.xbel)")); if (fileName.isEmpty()) return; QFile file(fileName); if (file.open(QIODevice::ReadOnly)) { const BookmarkManager &manager = LocalHelpManager::bookmarkManager(); XbelReader reader(manager.treeBookmarkModel(), manager.listBookmarkModel()); if (reader.readFromFile(&file)) return; } m_ui->errorLabel->setVisible(true); m_ui->errorLabel->setText(tr("Cannot import bookmarks.")); } void GeneralSettingsPage::exportBookmarks() { m_ui->errorLabel->setVisible(false); QString fileName = QFileDialog::getSaveFileName(0, tr("Save File"), "untitled.xbel", tr("Files (*.xbel)")); QLatin1String suffix(".xbel"); if (!fileName.endsWith(suffix)) fileName.append(suffix); Utils::FileSaver saver(fileName); if (!saver.hasError()) { XbelWriter writer(LocalHelpManager::bookmarkManager().treeBookmarkModel()); writer.writeToFile(saver.file()); saver.setResult(&writer); } if (!saver.finalize()) { m_ui->errorLabel->setVisible(true); m_ui->errorLabel->setText(saver.errorString()); } } void GeneralSettingsPage::updateFontSize() { const QString &family = m_font.family(); const QString &fontStyle = m_fontDatabase.styleString(m_font); QList<int> pointSizes = m_fontDatabase.pointSizes(family, fontStyle); if (pointSizes.empty()) pointSizes = QFontDatabase::standardSizes(); m_ui->sizeComboBox->clear(); m_ui->sizeComboBox->setCurrentIndex(-1); m_ui->sizeComboBox->setEnabled(!pointSizes.empty()); // try to maintain selection or select closest. if (!pointSizes.empty()) { QString n; foreach (int pointSize, pointSizes) m_ui->sizeComboBox->addItem(n.setNum(pointSize), QVariant(pointSize)); const int closestIndex = closestPointSizeIndex(m_font.pointSize()); if (closestIndex != -1) m_ui->sizeComboBox->setCurrentIndex(closestIndex); } } void GeneralSettingsPage::updateFontStyle() { const QString &fontStyle = m_fontDatabase.styleString(m_font); const QStringList &styles = m_fontDatabase.styles(m_font.family()); m_ui->styleComboBox->clear(); m_ui->styleComboBox->setCurrentIndex(-1); m_ui->styleComboBox->setEnabled(!styles.empty()); if (!styles.empty()) { int normalIndex = -1; const QString normalStyle = QLatin1String("Normal"); foreach (const QString &style, styles) { // try to maintain selection or select 'normal' preferably const int newIndex = m_ui->styleComboBox->count(); m_ui->styleComboBox->addItem(style); if (fontStyle == style) { m_ui->styleComboBox->setCurrentIndex(newIndex); } else { if (fontStyle == normalStyle) normalIndex = newIndex; } } if (m_ui->styleComboBox->currentIndex() == -1 && normalIndex != -1) m_ui->styleComboBox->setCurrentIndex(normalIndex); } } void GeneralSettingsPage::updateFontFamily() { m_ui->familyComboBox->setCurrentFont(m_font); } int GeneralSettingsPage::closestPointSizeIndex(int desiredPointSize) const { // try to maintain selection or select closest. int closestIndex = -1; int closestAbsError = 0xFFFF; const int pointSizeCount = m_ui->sizeComboBox->count(); for (int i = 0; i < pointSizeCount; i++) { const int itemPointSize = m_ui->sizeComboBox->itemData(i).toInt(); const int absError = qAbs(desiredPointSize - itemPointSize); if (absError < closestAbsError) { closestIndex = i; closestAbsError = absError; if (closestAbsError == 0) break; } else { // past optimum if (absError > closestAbsError) { break; } } } return closestIndex; } bool GeneralSettingsPage::matches(const QString &s) const { return m_searchKeywords.contains(s, Qt::CaseInsensitive); } void GeneralSettingsPage::finish() { if (!m_ui) // page was never shown return; delete m_ui; m_ui = 0; } <commit_msg>Return a valid URL from a user supplied input.<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** **************************************************************************/ #include "generalsettingspage.h" #include "bookmarkmanager.h" #include "centralwidget.h" #include "helpconstants.h" #include "helpviewer.h" #include "localhelpmanager.h" #include "xbelsupport.h" #include <coreplugin/coreconstants.h> #include <coreplugin/helpmanager.h> #include <coreplugin/icore.h> #include <utils/fileutils.h> #include <QCoreApplication> #include <QSettings> #include <QTextStream> #include <QApplication> #include <QFileDialog> #if !defined(QT_NO_WEBKIT) #include <QWebSettings> #endif using namespace Help::Internal; GeneralSettingsPage::GeneralSettingsPage() : m_ui(0) { m_font = qApp->font(); #if !defined(QT_NO_WEBKIT) QWebSettings* webSettings = QWebSettings::globalSettings(); m_font.setPointSize(webSettings->fontSize(QWebSettings::DefaultFontSize)); #endif setId(QLatin1String("A.General settings")); setDisplayName(tr("General")); setCategory(QLatin1String(Help::Constants::HELP_CATEGORY)); setDisplayCategory(QCoreApplication::translate("Help", Help::Constants::HELP_TR_CATEGORY)); setCategoryIcon(QLatin1String(Help::Constants::HELP_CATEGORY_ICON)); } QWidget *GeneralSettingsPage::createPage(QWidget *parent) { QWidget *widget = new QWidget(parent); m_ui = new Ui::GeneralSettingsPage; m_ui->setupUi(widget); m_ui->sizeComboBox->setEditable(false); m_ui->styleComboBox->setEditable(false); Core::HelpManager *manager = Core::HelpManager::instance(); m_font = qVariantValue<QFont>(manager->customValue(QLatin1String("font"), m_font)); updateFontSize(); updateFontStyle(); updateFontFamily(); m_homePage = manager->customValue(QLatin1String("HomePage"), QString()) .toString(); if (m_homePage.isEmpty()) { m_homePage = manager->customValue(QLatin1String("DefaultHomePage"), Help::Constants::AboutBlank).toString(); } m_ui->homePageLineEdit->setText(m_homePage); const int startOption = manager->customValue(QLatin1String("StartOption"), Help::Constants::ShowLastPages).toInt(); m_ui->helpStartComboBox->setCurrentIndex(startOption); m_contextOption = manager->customValue(QLatin1String("ContextHelpOption"), Help::Constants::SideBySideIfPossible).toInt(); m_ui->contextHelpComboBox->setCurrentIndex(m_contextOption); connect(m_ui->currentPageButton, SIGNAL(clicked()), this, SLOT(setCurrentPage())); connect(m_ui->blankPageButton, SIGNAL(clicked()), this, SLOT(setBlankPage())); connect(m_ui->defaultPageButton, SIGNAL(clicked()), this, SLOT(setDefaultPage())); HelpViewer *viewer = CentralWidget::instance()->currentHelpViewer(); if (!viewer) m_ui->currentPageButton->setEnabled(false); m_ui->errorLabel->setVisible(false); connect(m_ui->importButton, SIGNAL(clicked()), this, SLOT(importBookmarks())); connect(m_ui->exportButton, SIGNAL(clicked()), this, SLOT(exportBookmarks())); if (m_searchKeywords.isEmpty()) { QTextStream(&m_searchKeywords) << ' ' << m_ui->contextHelpLabel->text() << ' ' << m_ui->startPageLabel->text() << ' ' << m_ui->homePageLabel->text() << ' ' << m_ui->bookmarkGroupBox->title(); m_searchKeywords.remove(QLatin1Char('&')); } m_returnOnClose = manager->customValue(QLatin1String("ReturnOnClose"), false).toBool(); m_ui->m_returnOnClose->setChecked(m_returnOnClose); return widget; } void GeneralSettingsPage::apply() { if (!m_ui) // page was never shown return; QFont newFont; const QString &family = m_ui->familyComboBox->currentFont().family(); newFont.setFamily(family); int fontSize = 14; int currentIndex = m_ui->sizeComboBox->currentIndex(); if (currentIndex != -1) fontSize = m_ui->sizeComboBox->itemData(currentIndex).toInt(); newFont.setPointSize(fontSize); QString fontStyle = QLatin1String("Normal"); currentIndex = m_ui->styleComboBox->currentIndex(); if (currentIndex != -1) fontStyle = m_ui->styleComboBox->itemText(currentIndex); newFont.setBold(m_fontDatabase.bold(family, fontStyle)); if (fontStyle.contains(QLatin1String("Italic"))) newFont.setStyle(QFont::StyleItalic); else if (fontStyle.contains(QLatin1String("Oblique"))) newFont.setStyle(QFont::StyleOblique); else newFont.setStyle(QFont::StyleNormal); const int weight = m_fontDatabase.weight(family, fontStyle); if (weight >= 0) // Weight < 0 asserts... newFont.setWeight(weight); Core::HelpManager *manager = Core::HelpManager::instance(); if (newFont != m_font) { m_font = newFont; manager->setCustomValue(QLatin1String("font"), newFont); emit fontChanged(); } QString homePage = QUrl::fromUserInput(m_ui->homePageLineEdit->text()).toString(); if (homePage.isEmpty()) homePage = Help::Constants::AboutBlank; m_ui->homePageLineEdit->setText(homePage); manager->setCustomValue(QLatin1String("HomePage"), homePage); const int startOption = m_ui->helpStartComboBox->currentIndex(); manager->setCustomValue(QLatin1String("StartOption"), startOption); const int helpOption = m_ui->contextHelpComboBox->currentIndex(); if (m_contextOption != helpOption) { m_contextOption = helpOption; manager->setCustomValue(QLatin1String("ContextHelpOption"), helpOption); QSettings *settings = Core::ICore::settings(); settings->beginGroup(Help::Constants::ID_MODE_HELP); settings->setValue(QLatin1String("ContextHelpOption"), helpOption); settings->endGroup(); emit contextHelpOptionChanged(); } const bool close = m_ui->m_returnOnClose->isChecked(); if (m_returnOnClose != close) { m_returnOnClose = close; manager->setCustomValue(QLatin1String("ReturnOnClose"), close); emit returnOnCloseChanged(); } } void GeneralSettingsPage::setCurrentPage() { HelpViewer *viewer = CentralWidget::instance()->currentHelpViewer(); if (viewer) m_ui->homePageLineEdit->setText(viewer->source().toString()); } void GeneralSettingsPage::setBlankPage() { m_ui->homePageLineEdit->setText(Help::Constants::AboutBlank); } void GeneralSettingsPage::setDefaultPage() { const QString &defaultHomePage = Core::HelpManager::instance() ->customValue(QLatin1String("DefaultHomePage"), QString()).toString(); m_ui->homePageLineEdit->setText(defaultHomePage); } void GeneralSettingsPage::importBookmarks() { m_ui->errorLabel->setVisible(false); QString fileName = QFileDialog::getOpenFileName(0, tr("Import Bookmarks"), QDir::currentPath(), tr("Files (*.xbel)")); if (fileName.isEmpty()) return; QFile file(fileName); if (file.open(QIODevice::ReadOnly)) { const BookmarkManager &manager = LocalHelpManager::bookmarkManager(); XbelReader reader(manager.treeBookmarkModel(), manager.listBookmarkModel()); if (reader.readFromFile(&file)) return; } m_ui->errorLabel->setVisible(true); m_ui->errorLabel->setText(tr("Cannot import bookmarks.")); } void GeneralSettingsPage::exportBookmarks() { m_ui->errorLabel->setVisible(false); QString fileName = QFileDialog::getSaveFileName(0, tr("Save File"), "untitled.xbel", tr("Files (*.xbel)")); QLatin1String suffix(".xbel"); if (!fileName.endsWith(suffix)) fileName.append(suffix); Utils::FileSaver saver(fileName); if (!saver.hasError()) { XbelWriter writer(LocalHelpManager::bookmarkManager().treeBookmarkModel()); writer.writeToFile(saver.file()); saver.setResult(&writer); } if (!saver.finalize()) { m_ui->errorLabel->setVisible(true); m_ui->errorLabel->setText(saver.errorString()); } } void GeneralSettingsPage::updateFontSize() { const QString &family = m_font.family(); const QString &fontStyle = m_fontDatabase.styleString(m_font); QList<int> pointSizes = m_fontDatabase.pointSizes(family, fontStyle); if (pointSizes.empty()) pointSizes = QFontDatabase::standardSizes(); m_ui->sizeComboBox->clear(); m_ui->sizeComboBox->setCurrentIndex(-1); m_ui->sizeComboBox->setEnabled(!pointSizes.empty()); // try to maintain selection or select closest. if (!pointSizes.empty()) { QString n; foreach (int pointSize, pointSizes) m_ui->sizeComboBox->addItem(n.setNum(pointSize), QVariant(pointSize)); const int closestIndex = closestPointSizeIndex(m_font.pointSize()); if (closestIndex != -1) m_ui->sizeComboBox->setCurrentIndex(closestIndex); } } void GeneralSettingsPage::updateFontStyle() { const QString &fontStyle = m_fontDatabase.styleString(m_font); const QStringList &styles = m_fontDatabase.styles(m_font.family()); m_ui->styleComboBox->clear(); m_ui->styleComboBox->setCurrentIndex(-1); m_ui->styleComboBox->setEnabled(!styles.empty()); if (!styles.empty()) { int normalIndex = -1; const QString normalStyle = QLatin1String("Normal"); foreach (const QString &style, styles) { // try to maintain selection or select 'normal' preferably const int newIndex = m_ui->styleComboBox->count(); m_ui->styleComboBox->addItem(style); if (fontStyle == style) { m_ui->styleComboBox->setCurrentIndex(newIndex); } else { if (fontStyle == normalStyle) normalIndex = newIndex; } } if (m_ui->styleComboBox->currentIndex() == -1 && normalIndex != -1) m_ui->styleComboBox->setCurrentIndex(normalIndex); } } void GeneralSettingsPage::updateFontFamily() { m_ui->familyComboBox->setCurrentFont(m_font); } int GeneralSettingsPage::closestPointSizeIndex(int desiredPointSize) const { // try to maintain selection or select closest. int closestIndex = -1; int closestAbsError = 0xFFFF; const int pointSizeCount = m_ui->sizeComboBox->count(); for (int i = 0; i < pointSizeCount; i++) { const int itemPointSize = m_ui->sizeComboBox->itemData(i).toInt(); const int absError = qAbs(desiredPointSize - itemPointSize); if (absError < closestAbsError) { closestIndex = i; closestAbsError = absError; if (closestAbsError == 0) break; } else { // past optimum if (absError > closestAbsError) { break; } } } return closestIndex; } bool GeneralSettingsPage::matches(const QString &s) const { return m_searchKeywords.contains(s, Qt::CaseInsensitive); } void GeneralSettingsPage::finish() { if (!m_ui) // page was never shown return; delete m_ui; m_ui = 0; } <|endoftext|>
<commit_before>#include "texture.h" #include <cassert> #include <stdexcept> namespace possumwood { Texture::Texture(const unsigned char* data, std::size_t width, std::size_t height, const Format& format) : m_id(0) { int original_alignment; glGetIntegerv(GL_UNPACK_ALIGNMENT, &original_alignment); glPixelStorei(GL_UNPACK_ALIGNMENT, format.row_byte_align); glGenTextures(1, &m_id); glBindTexture(GL_TEXTURE_2D, m_id); // this assumes all image data are stored as a flat 8-bit per channel array! switch(format.channel_order) { case kRGB: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); break; case kBGR: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_BGR, GL_UNSIGNED_BYTE, data); break; case kGray: glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, width, height, 0, GL_RED, GL_UNSIGNED_BYTE, data); break; default: assert(false && "Invalid channel order"); } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, format.interpolation); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, format.interpolation); glBindTexture(GL_TEXTURE_2D, 0); glPixelStorei(GL_UNPACK_ALIGNMENT, original_alignment); } Texture::Texture(const float* data, std::size_t width, std::size_t height, const Format& format) : m_id(0) { int original_alignment; glGetIntegerv(GL_UNPACK_ALIGNMENT, &original_alignment); glPixelStorei(GL_UNPACK_ALIGNMENT, format.row_byte_align); glGenTextures(1, &m_id); glBindTexture(GL_TEXTURE_2D, m_id); // this assumes all image data are stored as a flat float per channel array! switch(format.channel_order) { case kRGB: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F, width, height, 0, GL_RGB, GL_FLOAT, data); break; case kBGR: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F, width, height, 0, GL_BGR, GL_FLOAT, data); break; case kGray: throw std::runtime_error("Greyscale HDR images not supported."); break; default: assert(false && "Invalid channel order"); } if(format.channel_order == kRGB) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F, width, height, 0, GL_RGB, GL_FLOAT, data); else if(format.channel_order == kBGR) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F, width, height, 0, GL_BGR, GL_UNSIGNED_BYTE, data); else assert(false && "Invalid channel order"); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, format.interpolation); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, format.interpolation); glBindTexture(GL_TEXTURE_2D, 0); glPixelStorei(GL_UNPACK_ALIGNMENT, original_alignment); } Texture::~Texture() { if(m_id != 0) glDeleteTextures(1, &m_id); } GLuint Texture::id() const { return m_id; } void Texture::use(GLint attribLocation, GLenum textureUnit) const { if(m_id != 0) { glUniform1i(attribLocation, textureUnit-GL_TEXTURE0); glActiveTexture(textureUnit); glBindTexture(GL_TEXTURE_2D, m_id); } } } <commit_msg>More generic OpenGL texture wrapper<commit_after>#include "texture.h" #include <cassert> #include <stdexcept> namespace possumwood { namespace { template<typename T> struct TextureTraits; template<> struct TextureTraits<const unsigned char*> { static constexpr GLint GLType() { return GL_UNSIGNED_BYTE; }; }; template<> struct TextureTraits<const float*> { static constexpr GLint GLType() { return GL_FLOAT; }; }; template<typename T_PTR> std::string makeTexture(GLuint id, T_PTR data, std::size_t width, std::size_t height, const Texture::Format& format) { std::string error; int original_alignment; glGetIntegerv(GL_UNPACK_ALIGNMENT, &original_alignment); glPixelStorei(GL_UNPACK_ALIGNMENT, format.row_byte_align); glBindTexture(GL_TEXTURE_2D, id); // this assumes all image data are stored as a flat 8-bit per channel array! switch(format.channel_order) { case Texture::kRGB: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, TextureTraits<T_PTR>::GLType(), data); break; case Texture::kBGR: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_BGR, TextureTraits<T_PTR>::GLType(), data); break; case Texture::kGray: glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, width, height, 0, GL_RED, TextureTraits<T_PTR>::GLType(), data); break; default: assert(false && "Unsupported channel order"); error = "Unsupported channel order for OpenGL texture storage."; } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, format.interpolation); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, format.interpolation); glBindTexture(GL_TEXTURE_2D, 0); glPixelStorei(GL_UNPACK_ALIGNMENT, original_alignment); return error; } } Texture::Texture(const unsigned char* data, std::size_t width, std::size_t height, const Format& format) : m_id(0) { glGenTextures(1, &m_id); const std::string err = makeTexture(m_id, data, width, height, format); if(!err.empty()) { glDeleteTextures(1, &m_id); throw std::runtime_error(err); } } Texture::Texture(const float* data, std::size_t width, std::size_t height, const Format& format) : m_id(0) { glGenTextures(1, &m_id); const std::string err = makeTexture(m_id, data, width, height, format); if(!err.empty()) { glDeleteTextures(1, &m_id); throw std::runtime_error(err); } } Texture::~Texture() { if(m_id != 0) glDeleteTextures(1, &m_id); } GLuint Texture::id() const { return m_id; } void Texture::use(GLint attribLocation, GLenum textureUnit) const { if(m_id != 0) { glUniform1i(attribLocation, textureUnit-GL_TEXTURE0); glActiveTexture(textureUnit); glBindTexture(GL_TEXTURE_2D, m_id); } } } <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2004 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* interface header */ #include "DisplayMenu.h" #include "TextureManager.h" /* system implementation headers */ #include <string> #include <vector> #include <math.h> /* common implementation headers */ #include "BzfDisplay.h" #include "SceneRenderer.h" #include "FontManager.h" #include "OpenGLTexture.h" #include "StateDatabase.h" #include "BZDBCache.h" /* local implementation headers */ #include "MainMenu.h" #include "HUDDialogStack.h" #include "HUDuiControl.h" #include "HUDuiList.h" #include "HUDuiLabel.h" #include "MainWindow.h" /* FIXME - from playing.h */ BzfDisplay* getDisplay(); MainWindow* getMainWindow(); SceneRenderer* getSceneRenderer(); void setSceneDatabase(); DisplayMenu::DisplayMenu() : formatMenu(NULL) { // add controls std::vector<std::string>* options; std::vector<HUDuiControl*>& list = getControls(); HUDuiList* option; // cache font face id int fontFace = MainMenu::getFontFace(); HUDuiLabel* label = new HUDuiLabel; label->setFontFace(fontFace); label->setString("Display Settings"); list.push_back(label); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Dithering:"); option->setCallback(callback, (void*)"1"); options = &option->getList(); options->push_back(std::string("Off")); options->push_back(std::string("On")); option->update(); list.push_back(option); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Blending:"); option->setCallback(callback, (void*)"2"); options = &option->getList(); options->push_back(std::string("Off")); options->push_back(std::string("On")); option->update(); list.push_back(option); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Smoothing:"); option->setCallback(callback, (void*)"3"); options = &option->getList(); options->push_back(std::string("Off")); options->push_back(std::string("On")); option->update(); list.push_back(option); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Lighting:"); option->setCallback(callback, (void*)"4"); options = &option->getList(); options->push_back(std::string("None")); options->push_back(std::string("Fast")); options->push_back(std::string("Best")); option->update(); list.push_back(option); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Texturing:"); option->setCallback(callback, (void*)"5"); options = &option->getList(); options->push_back(std::string("Off")); options->push_back(std::string("Nearest")); options->push_back(std::string("Linear")); options->push_back(std::string("Nearest Mipmap Nearest")); options->push_back(std::string("Linear Mipmap Nearest")); options->push_back(std::string("Nearest Mipmap Linear")); options->push_back(std::string("Linear Mipmap Linear")); option->update(); list.push_back(option); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Quality:"); option->setCallback(callback, (void*)"6"); options = &option->getList(); options->push_back(std::string("Low")); options->push_back(std::string("Medium")); options->push_back(std::string("High")); options->push_back(std::string("Experimental")); option->update(); list.push_back(option); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Shadows:"); option->setCallback(callback, (void*)"7"); options = &option->getList(); options->push_back(std::string("Off")); options->push_back(std::string("On")); option->update(); list.push_back(option); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Depth Buffer:"); option->setCallback(callback, (void*)"8"); options = &option->getList(); GLint value; glGetIntegerv(GL_DEPTH_BITS, &value); if (value == 0) { options->push_back(std::string("Not available")); } else { options->push_back(std::string("Off")); options->push_back(std::string("On")); } option->update(); list.push_back(option); #if defined(DEBUG_RENDERING) option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Hidden Line:"); option->setCallback(callback, (void*)"a"); options = &option->getList(); options->push_back(std::string("Off")); options->push_back(std::string("On")); option->update(); list.push_back(option); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Wireframe:"); option->setCallback(callback, (void*)"b"); options = &option->getList(); options->push_back(std::string("Off")); options->push_back(std::string("On")); option->update(); list.push_back(option); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Depth Complexity:"); option->setCallback(callback, (void*)"c"); options = &option->getList(); options->push_back(std::string("Off")); options->push_back(std::string("On")); option->update(); list.push_back(option); #endif option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Culling Tree:"); option->setCallback(callback, (void*)"d"); options = &option->getList(); options->push_back(std::string("Off")); options->push_back(std::string("On")); option->update(); list.push_back(option); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Collision Tree:"); option->setCallback(callback, (void*)"e"); options = &option->getList(); options->push_back(std::string("Off")); options->push_back(std::string("On")); option->update(); list.push_back(option); BzfWindow* window = getMainWindow()->getWindow(); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Brightness:"); option->setCallback(callback, (void*)"g"); if (window->hasGammaControl()) { option->createSlider(15); } else { options = &option->getList(); options->push_back(std::string("Unavailable")); } option->update(); list.push_back(option); BzfDisplay* display = getDisplay(); int numFormats = display->getNumResolutions(); if (numFormats < 2) { videoFormat = NULL; } else { videoFormat = label = new HUDuiLabel; label->setFontFace(fontFace); label->setLabel("Change Video Format"); list.push_back(label); } initNavigation(list, 1,list.size()-1); } DisplayMenu::~DisplayMenu() { delete formatMenu; } void DisplayMenu::execute() { HUDuiControl* focus = HUDui::getFocus(); if (focus == videoFormat) { if (!formatMenu) formatMenu = new FormatMenu; HUDDialogStack::get()->push(formatMenu); } } void DisplayMenu::resize(int width, int height) { HUDDialog::resize(width, height); int i; // use a big font for title, smaller font for the rest const float titleFontSize = (float)height / 15.0f; const float fontSize = (float)height / 45.0f; FontManager &fm = FontManager::instance(); int fontFace = MainMenu::getFontFace(); // reposition title std::vector<HUDuiControl*>& list = getControls(); HUDuiLabel* title = (HUDuiLabel*)list[0]; title->setFontSize(titleFontSize); const float titleWidth = fm.getStrLength(fontFace, titleFontSize, title->getString()); const float titleHeight = fm.getStrHeight(fontFace, titleFontSize, " "); float x = 0.5f * ((float)width - titleWidth); float y = (float)height - titleHeight; title->setPosition(x, y); // reposition options x = 0.5f * ((float)width); y -= 0.6f * titleHeight; const float h = fm.getStrHeight(fontFace, fontSize, " "); const int count = list.size(); for (i = 1; i < count; i++) { list[i]->setFontSize(fontSize); list[i]->setPosition(x, y); y -= 1.0f * h; } i = 1; // load current settings SceneRenderer* renderer = getSceneRenderer(); if (renderer) { HUDuiList* tex; ((HUDuiList*)list[i++])->setIndex(BZDB.isTrue("dither")); ((HUDuiList*)list[i++])->setIndex(BZDB.isTrue("blend")); ((HUDuiList*)list[i++])->setIndex(BZDB.isTrue("smooth")); if (BZDBCache::lighting) { if (BZDB.isTrue("tesselation")) { ((HUDuiList*)list[i++])->setIndex(2); } else { ((HUDuiList*)list[i++])->setIndex(1); } } else { ((HUDuiList*)list[i++])->setIndex(0); } tex = (HUDuiList*)list[i++]; ((HUDuiList*)list[i++])->setIndex(renderer->useQuality()); ((HUDuiList*)list[i++])->setIndex(BZDB.isTrue("shadows")); ((HUDuiList*)list[i++])->setIndex(BZDBCache::zbuffer); #if defined(DEBUG_RENDERING) ((HUDuiList*)list[i++])->setIndex(renderer->useHiddenLine() ? 1 : 0); ((HUDuiList*)list[i++])->setIndex(renderer->useWireframe() ? 1 : 0); ((HUDuiList*)list[i++])->setIndex(renderer->useDepthComplexity() ? 1 : 0); #endif ((HUDuiList*)list[i++])->setIndex(renderer->useCullingTree() ? 1 : 0); ((HUDuiList*)list[i++])->setIndex(renderer->useCollisionTree() ? 1 : 0); if (!BZDB.isTrue("texture")) tex->setIndex(0); else tex->setIndex(OpenGLTexture::getFilter()); } // brightness BzfWindow* window = getMainWindow()->getWindow(); if (window->hasGammaControl()) ((HUDuiList*)list[i])->setIndex(gammaToIndex(window->getGamma())); i++; } int DisplayMenu::gammaToIndex(float gamma) { return (int)(0.5f + 5.0f * (1.0f + logf(gamma) / logf(2.0))); } float DisplayMenu::indexToGamma(int index) { // map index 5 to gamma 1.0 and index 0 to gamma 0.5 return powf(2.0f, (float)index / 5.0f - 1.0f); } void DisplayMenu::callback(HUDuiControl* w, void* data) { HUDuiList* list = (HUDuiList*)w; SceneRenderer* sceneRenderer = getSceneRenderer(); switch (((const char*)data)[0]) { case '1': BZDB.set("dither", list->getIndex() ? "1" : "0"); sceneRenderer->notifyStyleChange(); break; case '2': BZDB.set("blend", list->getIndex() ? "1" : "0"); sceneRenderer->notifyStyleChange(); break; case '3': BZDB.set("smooth", list->getIndex() ? "1" : "0"); sceneRenderer->notifyStyleChange(); break; case '4': { bool oldLighting = BZDBCache::lighting; BZDB.set("lighting", list->getIndex() == 0 ? "0" : "1"); BZDB.set("tesselation", list->getIndex() == 2 ? "1" : "0"); if (oldLighting != BZDBCache::lighting) { BZDB.set("_texturereplace", (!BZDBCache::lighting && sceneRenderer->useQuality() < 2) ? "1" : "0"); BZDB.setPersistent("_texturereplace", false); sceneRenderer->notifyStyleChange(); } break; } case '5': TextureManager::instance().setMaxFilter((eTextureFilter)list->getIndex()); BZDB.set("texture", TextureManager::instance().getMaxFilterName()); sceneRenderer->notifyStyleChange(); break; case '6': sceneRenderer->setQuality(list->getIndex()); if (list->getIndex() > 3) { BZDB.set("zbuffer","1"); setSceneDatabase(); } BZDB.set("_texturereplace", (!BZDBCache::lighting && sceneRenderer->useQuality() < 2) ? "1" : "0"); BZDB.setPersistent("_texturereplace", false); sceneRenderer->notifyStyleChange(); break; case '7': BZDB.set("shadows", list->getIndex() ? "1" : "0"); sceneRenderer->notifyStyleChange(); break; case '8': BZDB.set("zbuffer", list->getIndex() ? "1" : "0"); // FIXME - test for whether the z buffer will work setSceneDatabase(); sceneRenderer->notifyStyleChange(); break; #if defined(DEBUG_RENDERING) case 'a': sceneRenderer->setHiddenLine(list->getIndex() != 0); break; case 'b': sceneRenderer->setWireframe(list->getIndex() != 0); break; case 'c': sceneRenderer->setDepthComplexity(list->getIndex() != 0); break; #endif case 'd': sceneRenderer->setCullingTree(list->getIndex() != 0); break; case 'e': sceneRenderer->setCollisionTree(list->getIndex() != 0); break; case 'g': BzfWindow* window = getMainWindow()->getWindow(); if (window->hasGammaControl()) window->setGamma(indexToGamma(list->getIndex())); break; } } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>remove depth buffer selection, hide cull & collision<commit_after>/* bzflag * Copyright (c) 1993 - 2004 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* interface header */ #include "DisplayMenu.h" #include "TextureManager.h" /* system implementation headers */ #include <string> #include <vector> #include <math.h> /* common implementation headers */ #include "BzfDisplay.h" #include "SceneRenderer.h" #include "FontManager.h" #include "OpenGLTexture.h" #include "StateDatabase.h" #include "BZDBCache.h" /* local implementation headers */ #include "MainMenu.h" #include "HUDDialogStack.h" #include "HUDuiControl.h" #include "HUDuiList.h" #include "HUDuiLabel.h" #include "MainWindow.h" /* FIXME - from playing.h */ BzfDisplay* getDisplay(); MainWindow* getMainWindow(); SceneRenderer* getSceneRenderer(); void setSceneDatabase(); DisplayMenu::DisplayMenu() : formatMenu(NULL) { // add controls std::vector<std::string>* options; std::vector<HUDuiControl*>& list = getControls(); HUDuiList* option; // cache font face id int fontFace = MainMenu::getFontFace(); HUDuiLabel* label = new HUDuiLabel; label->setFontFace(fontFace); label->setString("Display Settings"); list.push_back(label); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Dithering:"); option->setCallback(callback, (void*)"1"); options = &option->getList(); options->push_back(std::string("Off")); options->push_back(std::string("On")); option->update(); list.push_back(option); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Blending:"); option->setCallback(callback, (void*)"2"); options = &option->getList(); options->push_back(std::string("Off")); options->push_back(std::string("On")); option->update(); list.push_back(option); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Smoothing:"); option->setCallback(callback, (void*)"3"); options = &option->getList(); options->push_back(std::string("Off")); options->push_back(std::string("On")); option->update(); list.push_back(option); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Lighting:"); option->setCallback(callback, (void*)"4"); options = &option->getList(); options->push_back(std::string("None")); options->push_back(std::string("Fast")); options->push_back(std::string("Best")); option->update(); list.push_back(option); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Texturing:"); option->setCallback(callback, (void*)"5"); options = &option->getList(); options->push_back(std::string("Off")); options->push_back(std::string("Nearest")); options->push_back(std::string("Linear")); options->push_back(std::string("Nearest Mipmap Nearest")); options->push_back(std::string("Linear Mipmap Nearest")); options->push_back(std::string("Nearest Mipmap Linear")); options->push_back(std::string("Linear Mipmap Linear")); option->update(); list.push_back(option); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Quality:"); option->setCallback(callback, (void*)"6"); options = &option->getList(); options->push_back(std::string("Low")); options->push_back(std::string("Medium")); options->push_back(std::string("High")); options->push_back(std::string("Experimental")); option->update(); list.push_back(option); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Shadows:"); option->setCallback(callback, (void*)"7"); options = &option->getList(); options->push_back(std::string("Off")); options->push_back(std::string("On")); option->update(); list.push_back(option); #if defined(DEBUG_RENDERING) option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Hidden Line:"); option->setCallback(callback, (void*)"a"); options = &option->getList(); options->push_back(std::string("Off")); options->push_back(std::string("On")); option->update(); list.push_back(option); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Wireframe:"); option->setCallback(callback, (void*)"b"); options = &option->getList(); options->push_back(std::string("Off")); options->push_back(std::string("On")); option->update(); list.push_back(option); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Depth Complexity:"); option->setCallback(callback, (void*)"c"); options = &option->getList(); options->push_back(std::string("Off")); options->push_back(std::string("On")); option->update(); list.push_back(option); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Culling Tree:"); option->setCallback(callback, (void*)"d"); options = &option->getList(); options->push_back(std::string("Off")); options->push_back(std::string("On")); option->update(); list.push_back(option); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Collision Tree:"); option->setCallback(callback, (void*)"e"); options = &option->getList(); options->push_back(std::string("Off")); options->push_back(std::string("On")); option->update(); list.push_back(option); #endif BzfWindow* window = getMainWindow()->getWindow(); option = new HUDuiList; option->setFontFace(fontFace); option->setLabel("Brightness:"); option->setCallback(callback, (void*)"g"); if (window->hasGammaControl()) { option->createSlider(15); } else { options = &option->getList(); options->push_back(std::string("Unavailable")); } option->update(); list.push_back(option); BzfDisplay* display = getDisplay(); int numFormats = display->getNumResolutions(); if (numFormats < 2) { videoFormat = NULL; } else { videoFormat = label = new HUDuiLabel; label->setFontFace(fontFace); label->setLabel("Change Video Format"); list.push_back(label); } initNavigation(list, 1,list.size()-1); } DisplayMenu::~DisplayMenu() { delete formatMenu; } void DisplayMenu::execute() { HUDuiControl* focus = HUDui::getFocus(); if (focus == videoFormat) { if (!formatMenu) formatMenu = new FormatMenu; HUDDialogStack::get()->push(formatMenu); } } void DisplayMenu::resize(int width, int height) { HUDDialog::resize(width, height); int i; // use a big font for title, smaller font for the rest const float titleFontSize = (float)height / 15.0f; const float fontSize = (float)height / 45.0f; FontManager &fm = FontManager::instance(); int fontFace = MainMenu::getFontFace(); // reposition title std::vector<HUDuiControl*>& list = getControls(); HUDuiLabel* title = (HUDuiLabel*)list[0]; title->setFontSize(titleFontSize); const float titleWidth = fm.getStrLength(fontFace, titleFontSize, title->getString()); const float titleHeight = fm.getStrHeight(fontFace, titleFontSize, " "); float x = 0.5f * ((float)width - titleWidth); float y = (float)height - titleHeight; title->setPosition(x, y); // reposition options x = 0.5f * ((float)width); y -= 0.6f * titleHeight; const float h = fm.getStrHeight(fontFace, fontSize, " "); const int count = list.size(); for (i = 1; i < count; i++) { list[i]->setFontSize(fontSize); list[i]->setPosition(x, y); y -= 1.0f * h; } i = 1; // load current settings SceneRenderer* renderer = getSceneRenderer(); if (renderer) { HUDuiList* tex; ((HUDuiList*)list[i++])->setIndex(BZDB.isTrue("dither")); ((HUDuiList*)list[i++])->setIndex(BZDB.isTrue("blend")); ((HUDuiList*)list[i++])->setIndex(BZDB.isTrue("smooth")); if (BZDBCache::lighting) { if (BZDB.isTrue("tesselation")) { ((HUDuiList*)list[i++])->setIndex(2); } else { ((HUDuiList*)list[i++])->setIndex(1); } } else { ((HUDuiList*)list[i++])->setIndex(0); } tex = (HUDuiList*)list[i++]; ((HUDuiList*)list[i++])->setIndex(renderer->useQuality()); ((HUDuiList*)list[i++])->setIndex(BZDB.isTrue("shadows")); #if defined(DEBUG_RENDERING) ((HUDuiList*)list[i++])->setIndex(renderer->useHiddenLine() ? 1 : 0); ((HUDuiList*)list[i++])->setIndex(renderer->useWireframe() ? 1 : 0); ((HUDuiList*)list[i++])->setIndex(renderer->useDepthComplexity() ? 1 : 0); ((HUDuiList*)list[i++])->setIndex(renderer->useCullingTree() ? 1 : 0); ((HUDuiList*)list[i++])->setIndex(renderer->useCollisionTree() ? 1 : 0); #endif if (!BZDB.isTrue("texture")) tex->setIndex(0); else tex->setIndex(OpenGLTexture::getFilter()); } // brightness BzfWindow* window = getMainWindow()->getWindow(); if (window->hasGammaControl()) ((HUDuiList*)list[i])->setIndex(gammaToIndex(window->getGamma())); i++; } int DisplayMenu::gammaToIndex(float gamma) { return (int)(0.5f + 5.0f * (1.0f + logf(gamma) / logf(2.0))); } float DisplayMenu::indexToGamma(int index) { // map index 5 to gamma 1.0 and index 0 to gamma 0.5 return powf(2.0f, (float)index / 5.0f - 1.0f); } void DisplayMenu::callback(HUDuiControl* w, void* data) { HUDuiList* list = (HUDuiList*)w; SceneRenderer* sceneRenderer = getSceneRenderer(); switch (((const char*)data)[0]) { case '1': BZDB.set("dither", list->getIndex() ? "1" : "0"); sceneRenderer->notifyStyleChange(); break; case '2': BZDB.set("blend", list->getIndex() ? "1" : "0"); sceneRenderer->notifyStyleChange(); break; case '3': BZDB.set("smooth", list->getIndex() ? "1" : "0"); sceneRenderer->notifyStyleChange(); break; case '4': { bool oldLighting = BZDBCache::lighting; BZDB.set("lighting", list->getIndex() == 0 ? "0" : "1"); BZDB.set("tesselation", list->getIndex() == 2 ? "1" : "0"); if (oldLighting != BZDBCache::lighting) { BZDB.set("_texturereplace", (!BZDBCache::lighting && sceneRenderer->useQuality() < 2) ? "1" : "0"); BZDB.setPersistent("_texturereplace", false); sceneRenderer->notifyStyleChange(); } break; } case '5': TextureManager::instance().setMaxFilter((eTextureFilter)list->getIndex()); BZDB.set("texture", TextureManager::instance().getMaxFilterName()); sceneRenderer->notifyStyleChange(); break; case '6': sceneRenderer->setQuality(list->getIndex()); if (list->getIndex() > 3) { BZDB.set("zbuffer","1"); setSceneDatabase(); } BZDB.set("_texturereplace", (!BZDBCache::lighting && sceneRenderer->useQuality() < 2) ? "1" : "0"); BZDB.setPersistent("_texturereplace", false); sceneRenderer->notifyStyleChange(); break; case '7': BZDB.set("shadows", list->getIndex() ? "1" : "0"); sceneRenderer->notifyStyleChange(); break; #if defined(DEBUG_RENDERING) case 'a': sceneRenderer->setHiddenLine(list->getIndex() != 0); break; case 'b': sceneRenderer->setWireframe(list->getIndex() != 0); break; case 'c': sceneRenderer->setDepthComplexity(list->getIndex() != 0); break; #endif case 'd': sceneRenderer->setCullingTree(list->getIndex() != 0); break; case 'e': sceneRenderer->setCollisionTree(list->getIndex() != 0); break; case 'g': BzfWindow* window = getMainWindow()->getWindow(); if (window->hasGammaControl()) window->setGamma(indexToGamma(list->getIndex())); break; } } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>// Main entry point for SDLGame // 2016 createjump // sorry about everything being convoluted, linker dosen't like it if i create a function // it dosen't just not like it, it goes MENTAL! i swear, this programming thing is making me rant too much. #include "stdafx.h" #include "SDLGame.h" #include "SDL.h" #include "SDL_video.h" #include "SDL_messagebox.h" #include "SDL_error.h" const int SCREEN_WIDTH = 640; const int SCREEN_HEIGHT = 480; SDL_Event event; SDL_Window* Wnd = NULL; SDL_Renderer* Rend = NULL; int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow) { Wnd = SDL_CreateWindow("SDL 2D Game Engine", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, SDL_WINDOW_SHOWN); if (Wnd == NULL) { SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "SDL Error!","Window could not be created!",NULL); } Rend = SDL_CreateRenderer(Wnd,-1,SDL_RENDERER_ACCELERATED); if (Rend == NULL) { SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "SDL Error!", "Renderer could not be created!", NULL); } SDL_Rect Rect = { SCREEN_WIDTH / 4, SCREEN_HEIGHT / 4, SCREEN_WIDTH / 4, SCREEN_HEIGHT / 2}; while (1) { SDL_Delay(200); SDL_SetRenderDrawColor(Rend, 50, 54, 100, SDL_ALPHA_OPAQUE); SDL_RenderFillRect(Rend,&Rect); SDL_RenderPresent(Rend); while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { SDL_DestroyRenderer(Rend); SDL_DestroyWindow(Wnd); SDL_Quit(); return 0; } } } // TODO: Add looping code here. } <commit_msg>add comments, and remove rant<commit_after>// Main entry point for SDLGame // 2016 createjump #include "stdafx.h" #include "SDLGame.h" #include "SDL.h" #include "SDL_video.h" #include "SDL_messagebox.h" #include "SDL_error.h" const int SCREEN_WIDTH = 640; // because assuming screen size is enought for us to comprehend const int SCREEN_HEIGHT = 480; SDL_Event event; // initalize sdl things, for us to use SDL_Window* Wnd = NULL; SDL_Renderer* Rend = NULL; int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow) { Wnd = SDL_CreateWindow("SDL 2D Physics Test", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, SDL_WINDOW_SHOWN); if (Wnd == NULL) { SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "SDL Error!","Window could not be created!",NULL); } Rend = SDL_CreateRenderer(Wnd,-1,SDL_RENDERER_ACCELERATED); if (Rend == NULL) { SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "SDL Error!", "Renderer could not be created!", NULL); } SDL_Rect Rect = { SCREEN_WIDTH / 4, SCREEN_HEIGHT / 4, SCREEN_WIDTH / 4, SCREEN_HEIGHT / 2}; // tempoary rectangle, to see that we can actaully draw something. // our insanely huge loop while (1) { SDL_Delay(200); SDL_SetRenderDrawColor(Rend, 50, 54, 100, SDL_ALPHA_OPAQUE); SDL_RenderFillRect(Rend,&Rect); SDL_RenderPresent(Rend); while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { SDL_DestroyRenderer(Rend); SDL_DestroyWindow(Wnd); SDL_Quit(); return 0; } } } // TODO: Add looping code here. } <|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. * **************************************************************************/ //------------------------------------------------------------------------- // Implementation of Class AliESDZDC // This is a class that summarizes the ZDC data // for the ESD // Origin: Christian Klein-Boesing, CERN, Christian.Klein-Boesing@cern.ch //------------------------------------------------------------------------- #include "AliESDZDC.h" ClassImp(AliESDZDC) //______________________________________________________________________________ AliESDZDC::AliESDZDC() : TObject(), fZDCN1Energy(0), fZDCP1Energy(0), fZDCN2Energy(0), fZDCP2Energy(0), fZDCEMEnergy(0), fZDCEMEnergy1(0), fZDCParticipants(0), fZDCPartSideA(0), fZDCPartSideC(0), fImpactParameter(0), fImpactParamSideA(0), fImpactParamSideC(0), fESDQuality(0) { for(Int_t i=0; i<5; i++){ fZN1TowerEnergy[i] = fZN2TowerEnergy[i] = 0.; fZP1TowerEnergy[i] = fZP2TowerEnergy[i] = 0.; fZN1TowerEnergyLR[i] = fZN2TowerEnergyLR[i] = 0.; fZP1TowerEnergyLR[i] = fZP2TowerEnergyLR[i] = 0.; } for(Int_t i=0; i<2; i++){ fZNACentrCoord[i] = fZNCCentrCoord[i] = 0.; } } //______________________________________________________________________________ AliESDZDC::AliESDZDC(const AliESDZDC& zdc) : TObject(zdc), fZDCN1Energy(zdc.fZDCN1Energy), fZDCP1Energy(zdc.fZDCP1Energy), fZDCN2Energy(zdc.fZDCN2Energy), fZDCP2Energy(zdc.fZDCP2Energy), fZDCEMEnergy(zdc.fZDCEMEnergy), fZDCEMEnergy1(zdc.fZDCEMEnergy1), fZDCParticipants(zdc.fZDCParticipants), fZDCPartSideA(zdc.fZDCPartSideA), fZDCPartSideC(zdc.fZDCPartSideC), fImpactParameter(zdc.fImpactParameter), fImpactParamSideA(zdc.fImpactParamSideA), fImpactParamSideC(zdc.fImpactParamSideC), fESDQuality(zdc.fESDQuality) { // copy constructor for(Int_t i=0; i<5; i++){ fZN1TowerEnergy[i] = zdc.fZN1TowerEnergy[i]; fZN2TowerEnergy[i] = zdc.fZN2TowerEnergy[i]; fZP1TowerEnergy[i] = zdc.fZP1TowerEnergy[i]; fZP2TowerEnergy[i] = zdc.fZP2TowerEnergy[i]; fZN1TowerEnergyLR[i] = zdc.fZN1TowerEnergyLR[i]; fZN2TowerEnergyLR[i] = zdc.fZN2TowerEnergyLR[i]; fZP1TowerEnergyLR[i] = zdc.fZP1TowerEnergyLR[i]; fZP2TowerEnergyLR[i] = zdc.fZP2TowerEnergyLR[i]; } for(Int_t i=0; i<2; i++){ fZNACentrCoord[i] = zdc.fZNACentrCoord[i]; fZNCCentrCoord[i] = zdc.fZNCCentrCoord[i]; } } //______________________________________________________________________________ AliESDZDC& AliESDZDC::operator=(const AliESDZDC&zdc) { // assigment operator if(this!=&zdc) { TObject::operator=(zdc); fZDCN1Energy = zdc.fZDCN1Energy; fZDCP1Energy = zdc.fZDCP1Energy; fZDCN2Energy = zdc.fZDCN2Energy; fZDCP2Energy = zdc.fZDCP2Energy; fZDCEMEnergy = zdc.fZDCEMEnergy; fZDCEMEnergy1 = zdc.fZDCEMEnergy1; for(Int_t i=0; i<5; i++){ fZN1TowerEnergy[i] = zdc.fZN1TowerEnergy[i]; fZN2TowerEnergy[i] = zdc.fZN2TowerEnergy[i]; fZP1TowerEnergy[i] = zdc.fZP1TowerEnergy[i]; fZP2TowerEnergy[i] = zdc.fZP2TowerEnergy[i]; fZN1TowerEnergyLR[i] = zdc.fZN1TowerEnergyLR[i]; fZN2TowerEnergyLR[i] = zdc.fZN2TowerEnergyLR[i]; fZP1TowerEnergyLR[i] = zdc.fZP1TowerEnergyLR[i]; fZP2TowerEnergyLR[i] = zdc.fZP2TowerEnergyLR[i]; } // fZDCParticipants = zdc.fZDCParticipants; fZDCPartSideA = zdc.fZDCPartSideA; fZDCPartSideC = zdc.fZDCPartSideC; fImpactParameter = zdc.fImpactParameter; fImpactParamSideA = zdc.fImpactParamSideA; fImpactParamSideC = zdc.fImpactParamSideC; // for(Int_t i=0; i<2; i++){ fZNACentrCoord[i] = zdc.fZNACentrCoord[i]; fZNCCentrCoord[i] = zdc.fZNCCentrCoord[i]; } // fESDQuality = zdc.fESDQuality; } return *this; } //______________________________________________________________________________ void AliESDZDC::Copy(TObject &obj) const { // this overwrites the virtual TOBject::Copy() // to allow run time copying without casting // in AliESDEvent if(this==&obj)return; AliESDZDC *robj = dynamic_cast<AliESDZDC*>(&obj); if(!robj)return; // not an AliESDZDC *robj = *this; } //______________________________________________________________________________ void AliESDZDC::Reset() { // reset all data members fZDCN1Energy=0; fZDCP1Energy=0; fZDCN2Energy=0; fZDCP2Energy=0; fZDCEMEnergy=0; fZDCEMEnergy1=0; for(Int_t i=0; i<5; i++){ fZN1TowerEnergy[i] = fZN2TowerEnergy[i] = 0.; fZP1TowerEnergy[i] = fZP2TowerEnergy[i] = 0.; fZN1TowerEnergyLR[i] = fZN2TowerEnergyLR[i] = 0.; fZP1TowerEnergyLR[i] = fZP2TowerEnergyLR[i] = 0.; } fZDCParticipants=0; fZDCPartSideA=0; fZDCPartSideC=0; fImpactParameter=0; fImpactParamSideA=0; fImpactParamSideC=0; for(Int_t i=0; i<2; i++){ fZNACentrCoord[i] = fZNCCentrCoord[i] = 0.; } fESDQuality=0; } //______________________________________________________________________________ void AliESDZDC::Print(const Option_t *) const { // Print ESD for the ZDC printf("\n \t E_{ZNC} = %f TeV, E_{ZPC} = %f TeV, E_{ZNA} = %f TeV, E_{ZPA} = %f TeV," " E_{ZEM} = %f GeV, Npart = %d, b = %1.2f fm\n", fZDCN1Energy/1000.,fZDCP1Energy/1000.,fZDCN2Energy/1000.,fZDCP2Energy/1000., fZDCEMEnergy+fZDCEMEnergy1, fZDCParticipants,fImpactParameter); } //______________________________________________________________________________ Double32_t * AliESDZDC::GetZNCCentroid() { // Provide coordinates of centroid over ZN (side C) front face Float_t x[4] = {-1.75, 1.75, -1.75, 1.75}; Float_t y[4] = {-1.75, -1.75, 1.75, 1.75}; Float_t numX=0., numY=0., den=0.; Float_t c, alpha=0.395, w; // for(Int_t i=0; i<4; i++){ if(fZN1TowerEnergy[i+1]<0.) fZN1TowerEnergy[i+1]=0.; w = TMath::Power(fZN1TowerEnergy[i+1], alpha); numX += x[i]*w; numY += y[i]*w; den += w; } if(den!=0){ // ATTENTION! Needs to be changed if E_beam(A-A) != 2.76 A TeV !!!! c = fZDCN1Energy/2760.; fZNCCentrCoord[0] = c*numX/den; fZNCCentrCoord[1] = c*numY/den; } return fZNCCentrCoord; } //______________________________________________________________________________ Double32_t * AliESDZDC::GetZNACentroid() { // Provide coordinates of centroid over ZN (side A) front face Float_t x[4] = {-1.75, 1.75, -1.75, 1.75}; Float_t y[4] = {-1.75, -1.75, 1.75, 1.75}; Float_t numX=0., numY=0., den=0.; Float_t c, alpha=0.395, w; for(Int_t i=0; i<4; i++){ if(fZN2TowerEnergy[i+1]<0.) fZN2TowerEnergy[i+1]=0.; w = TMath::Power(fZN2TowerEnergy[i+1], alpha); numX += x[i]*w; numY += y[i]*w; den += w; } // if(den!=0){ // ATTENTION! Needs to be changed if E_beam(A-A) != 2.76 A TeV !!!! c = fZDCN2Energy/2760.; fZNACentrCoord[0] = c*numX/den; fZNACentrCoord[1] = c*numY/den; } return fZNACentrCoord; } <commit_msg>Centroid calculation corrected (Chiara)<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. * **************************************************************************/ //------------------------------------------------------------------------- // Implementation of Class AliESDZDC // This is a class that summarizes the ZDC data // for the ESD // Origin: Christian Klein-Boesing, CERN, Christian.Klein-Boesing@cern.ch //------------------------------------------------------------------------- #include "AliESDZDC.h" ClassImp(AliESDZDC) //______________________________________________________________________________ AliESDZDC::AliESDZDC() : TObject(), fZDCN1Energy(0), fZDCP1Energy(0), fZDCN2Energy(0), fZDCP2Energy(0), fZDCEMEnergy(0), fZDCEMEnergy1(0), fZDCParticipants(0), fZDCPartSideA(0), fZDCPartSideC(0), fImpactParameter(0), fImpactParamSideA(0), fImpactParamSideC(0), fESDQuality(0) { for(Int_t i=0; i<5; i++){ fZN1TowerEnergy[i] = fZN2TowerEnergy[i] = 0.; fZP1TowerEnergy[i] = fZP2TowerEnergy[i] = 0.; fZN1TowerEnergyLR[i] = fZN2TowerEnergyLR[i] = 0.; fZP1TowerEnergyLR[i] = fZP2TowerEnergyLR[i] = 0.; } for(Int_t i=0; i<2; i++){ fZNACentrCoord[i] = fZNCCentrCoord[i] = 0.; } } //______________________________________________________________________________ AliESDZDC::AliESDZDC(const AliESDZDC& zdc) : TObject(zdc), fZDCN1Energy(zdc.fZDCN1Energy), fZDCP1Energy(zdc.fZDCP1Energy), fZDCN2Energy(zdc.fZDCN2Energy), fZDCP2Energy(zdc.fZDCP2Energy), fZDCEMEnergy(zdc.fZDCEMEnergy), fZDCEMEnergy1(zdc.fZDCEMEnergy1), fZDCParticipants(zdc.fZDCParticipants), fZDCPartSideA(zdc.fZDCPartSideA), fZDCPartSideC(zdc.fZDCPartSideC), fImpactParameter(zdc.fImpactParameter), fImpactParamSideA(zdc.fImpactParamSideA), fImpactParamSideC(zdc.fImpactParamSideC), fESDQuality(zdc.fESDQuality) { // copy constructor for(Int_t i=0; i<5; i++){ fZN1TowerEnergy[i] = zdc.fZN1TowerEnergy[i]; fZN2TowerEnergy[i] = zdc.fZN2TowerEnergy[i]; fZP1TowerEnergy[i] = zdc.fZP1TowerEnergy[i]; fZP2TowerEnergy[i] = zdc.fZP2TowerEnergy[i]; fZN1TowerEnergyLR[i] = zdc.fZN1TowerEnergyLR[i]; fZN2TowerEnergyLR[i] = zdc.fZN2TowerEnergyLR[i]; fZP1TowerEnergyLR[i] = zdc.fZP1TowerEnergyLR[i]; fZP2TowerEnergyLR[i] = zdc.fZP2TowerEnergyLR[i]; } for(Int_t i=0; i<2; i++){ fZNACentrCoord[i] = zdc.fZNACentrCoord[i]; fZNCCentrCoord[i] = zdc.fZNCCentrCoord[i]; } } //______________________________________________________________________________ AliESDZDC& AliESDZDC::operator=(const AliESDZDC&zdc) { // assigment operator if(this!=&zdc) { TObject::operator=(zdc); fZDCN1Energy = zdc.fZDCN1Energy; fZDCP1Energy = zdc.fZDCP1Energy; fZDCN2Energy = zdc.fZDCN2Energy; fZDCP2Energy = zdc.fZDCP2Energy; fZDCEMEnergy = zdc.fZDCEMEnergy; fZDCEMEnergy1 = zdc.fZDCEMEnergy1; for(Int_t i=0; i<5; i++){ fZN1TowerEnergy[i] = zdc.fZN1TowerEnergy[i]; fZN2TowerEnergy[i] = zdc.fZN2TowerEnergy[i]; fZP1TowerEnergy[i] = zdc.fZP1TowerEnergy[i]; fZP2TowerEnergy[i] = zdc.fZP2TowerEnergy[i]; fZN1TowerEnergyLR[i] = zdc.fZN1TowerEnergyLR[i]; fZN2TowerEnergyLR[i] = zdc.fZN2TowerEnergyLR[i]; fZP1TowerEnergyLR[i] = zdc.fZP1TowerEnergyLR[i]; fZP2TowerEnergyLR[i] = zdc.fZP2TowerEnergyLR[i]; } // fZDCParticipants = zdc.fZDCParticipants; fZDCPartSideA = zdc.fZDCPartSideA; fZDCPartSideC = zdc.fZDCPartSideC; fImpactParameter = zdc.fImpactParameter; fImpactParamSideA = zdc.fImpactParamSideA; fImpactParamSideC = zdc.fImpactParamSideC; // for(Int_t i=0; i<2; i++){ fZNACentrCoord[i] = zdc.fZNACentrCoord[i]; fZNCCentrCoord[i] = zdc.fZNCCentrCoord[i]; } // fESDQuality = zdc.fESDQuality; } return *this; } //______________________________________________________________________________ void AliESDZDC::Copy(TObject &obj) const { // this overwrites the virtual TOBject::Copy() // to allow run time copying without casting // in AliESDEvent if(this==&obj)return; AliESDZDC *robj = dynamic_cast<AliESDZDC*>(&obj); if(!robj)return; // not an AliESDZDC *robj = *this; } //______________________________________________________________________________ void AliESDZDC::Reset() { // reset all data members fZDCN1Energy=0; fZDCP1Energy=0; fZDCN2Energy=0; fZDCP2Energy=0; fZDCEMEnergy=0; fZDCEMEnergy1=0; for(Int_t i=0; i<5; i++){ fZN1TowerEnergy[i] = fZN2TowerEnergy[i] = 0.; fZP1TowerEnergy[i] = fZP2TowerEnergy[i] = 0.; fZN1TowerEnergyLR[i] = fZN2TowerEnergyLR[i] = 0.; fZP1TowerEnergyLR[i] = fZP2TowerEnergyLR[i] = 0.; } fZDCParticipants=0; fZDCPartSideA=0; fZDCPartSideC=0; fImpactParameter=0; fImpactParamSideA=0; fImpactParamSideC=0; for(Int_t i=0; i<2; i++){ fZNACentrCoord[i] = fZNCCentrCoord[i] = 0.; } fESDQuality=0; } //______________________________________________________________________________ void AliESDZDC::Print(const Option_t *) const { // Print ESD for the ZDC printf("\n \t E_{ZNC} = %f TeV, E_{ZPC} = %f TeV, E_{ZNA} = %f TeV, E_{ZPA} = %f TeV," " E_{ZEM} = %f GeV, Npart = %d, b = %1.2f fm\n", fZDCN1Energy/1000.,fZDCP1Energy/1000.,fZDCN2Energy/1000.,fZDCP2Energy/1000., fZDCEMEnergy+fZDCEMEnergy1, fZDCParticipants,fImpactParameter); } //______________________________________________________________________________ Double32_t * AliESDZDC::GetZNCCentroid() { // Provide coordinates of centroid over ZN (side C) front face Float_t x[4] = {-1.75, 1.75, -1.75, 1.75}; Float_t y[4] = {-1.75, -1.75, 1.75, 1.75}; Float_t numX=0., numY=0., den=0.; Float_t c, alpha=0.395, w; // for(Int_t i=0; i<4; i++){ if(fZN1TowerEnergy[i+1]<0.) fZN1TowerEnergy[i+1]=0.; w = TMath::Power(fZN1TowerEnergy[i+1], alpha); numX += x[i]*w; numY += y[i]*w; den += w; } if(den!=0){ // ATTENTION! Needs to be changed if E_beam(A-A) != 2.76 A TeV !!!! Float_t nSpecn = fZDCN1Energy/2760.; c = 1.89358-0.71262/(nSpecn+0.71789); fZNCCentrCoord[0] = c*numX/den; fZNCCentrCoord[1] = c*numY/den; } return fZNCCentrCoord; } //______________________________________________________________________________ Double32_t * AliESDZDC::GetZNACentroid() { // Provide coordinates of centroid over ZN (side A) front face Float_t x[4] = {-1.75, 1.75, -1.75, 1.75}; Float_t y[4] = {-1.75, -1.75, 1.75, 1.75}; Float_t numX=0., numY=0., den=0.; Float_t c, alpha=0.395, w; for(Int_t i=0; i<4; i++){ if(fZN2TowerEnergy[i+1]<0.) fZN2TowerEnergy[i+1]=0.; w = TMath::Power(fZN2TowerEnergy[i+1], alpha); numX += x[i]*w; numY += y[i]*w; den += w; } // if(den!=0){ // ATTENTION! Needs to be changed if E_beam(A-A) != 2.76 A TeV !!!! Float_t nSpecn = fZDCN2Energy/2760.; c = 1.89358-0.71262/(nSpecn+0.71789); fZNACentrCoord[0] = c*numX/den; fZNACentrCoord[1] = c*numY/den; } return fZNACentrCoord; } <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-2008, 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. * **************************************************************************/ //------------------------------------------------------------------------- // base class for ESD and AOD tracks // Author: A. Dainese //------------------------------------------------------------------------- #include <TGeoGlobalMagField.h> #include "AliMagF.h" #include "AliVTrack.h" ClassImp(AliVTrack) AliVTrack::AliVTrack(const AliVTrack& vTrack) : AliVParticle(vTrack) { } // Copy constructor AliVTrack& AliVTrack::operator=(const AliVTrack& vTrack) { if (this!=&vTrack) { AliVParticle::operator=(vTrack); } return *this; } Double_t AliVTrack::GetBz() const { // returns Bz component of the magnetic field (kG) AliMagF* fld = (AliMagF*)TGeoGlobalMagField::Instance()->GetField(); if (!fld) return 0.5*kAlmost0Field; double bz; if (fld->IsUniform()) bz = fld->SolenoidField(); else { Double_t r[3]; GetXYZ(r); bz = fld->GetBz(r); } return TMath::Sign(0.5*kAlmost0Field,bz) + bz; } void AliVTrack::GetBxByBz(Double_t b[3]) const { // returns Bz component of the magnetic field (kG) AliMagF* fld = (AliMagF*)TGeoGlobalMagField::Instance()->GetField(); if (!fld) { b[0] = b[1] = 0.; b[2] = 0.5*kAlmost0Field; return; } if (fld->IsUniform()) { b[0] = b[1] = 0.; b[2] = fld->SolenoidField(); } else { Double_t r[3]; GetXYZ(r); fld->Field(r,b); } b[2] = (TMath::Sign(0.5*kAlmost0Field,b[2]) + b[2]); return; } <commit_msg>Correcting the comment<commit_after>/************************************************************************** * Copyright(c) 1998-2008, 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. * **************************************************************************/ //------------------------------------------------------------------------- // base class for ESD and AOD tracks // Author: A. Dainese //------------------------------------------------------------------------- #include <TGeoGlobalMagField.h> #include "AliMagF.h" #include "AliVTrack.h" ClassImp(AliVTrack) AliVTrack::AliVTrack(const AliVTrack& vTrack) : AliVParticle(vTrack) { } // Copy constructor AliVTrack& AliVTrack::operator=(const AliVTrack& vTrack) { if (this!=&vTrack) { AliVParticle::operator=(vTrack); } return *this; } Double_t AliVTrack::GetBz() const { // returns Bz component of the magnetic field (kG) AliMagF* fld = (AliMagF*)TGeoGlobalMagField::Instance()->GetField(); if (!fld) return 0.5*kAlmost0Field; double bz; if (fld->IsUniform()) bz = fld->SolenoidField(); else { Double_t r[3]; GetXYZ(r); bz = fld->GetBz(r); } return TMath::Sign(0.5*kAlmost0Field,bz) + bz; } void AliVTrack::GetBxByBz(Double_t b[3]) const { // returns the Bx, By and Bz components of the magnetic field (kG) AliMagF* fld = (AliMagF*)TGeoGlobalMagField::Instance()->GetField(); if (!fld) { b[0] = b[1] = 0.; b[2] = 0.5*kAlmost0Field; return; } if (fld->IsUniform()) { b[0] = b[1] = 0.; b[2] = fld->SolenoidField(); } else { Double_t r[3]; GetXYZ(r); fld->Field(r,b); } b[2] = (TMath::Sign(0.5*kAlmost0Field,b[2]) + b[2]); return; } <|endoftext|>
<commit_before>#include "data_block_manager.hpp" #include "log_serializer.hpp" #include "utils.hpp" #include "cpu_context.hpp" #include "event_queue.hpp" #include "arch/io.hpp" void data_block_manager_t::start(fd_t fd) { assert(state == state_unstarted); dbfd = fd; last_data_extent = extent_manager->gen_extent(); blocks_in_last_data_extent = 0; add_gc_entry(); state = state_ready; } void data_block_manager_t::start(fd_t fd, metablock_mixin_t *last_metablock) { assert(state == state_unstarted); dbfd = fd; last_data_extent = last_metablock->last_data_extent; blocks_in_last_data_extent = last_metablock->blocks_in_last_data_extent; state = state_ready; } bool data_block_manager_t::read(off64_t off_in, void *buf_out, iocallback_t *cb) { assert(state == state_ready); event_queue_t *queue = get_cpu_context()->event_queue; queue->iosys.schedule_aio_read(dbfd, off_in, block_size, buf_out, queue, cb); return false; } bool data_block_manager_t::write(void *buf_in, off64_t *off_out, iocallback_t *cb) { // Either we're ready to write, or we're shutting down and just // finished reading blocks for gc and called do_write. assert(state == state_ready || (state == state_shutting_down && gc_state.step == gc_read)); off64_t offset = *off_out = gimme_a_new_offset(); event_queue_t *queue = get_cpu_context()->event_queue; queue->iosys.schedule_aio_write(dbfd, offset, block_size, buf_in, queue, cb); return false; } void data_block_manager_t::mark_garbage(off64_t offset) { unsigned int extent_id = (offset / extent_manager->extent_size); unsigned int block_id = (offset % extent_manager->extent_size) / block_size; if ((gc_state.step == gc_read || gc_state.step == gc_write) && gc_state.current_entry.offset / extent_manager->extent_size == extent_id) { gc_state.current_entry.g_array.set(block_id, 1); } else { assert(entries.get(extent_id)); entries.get(extent_id)->data.g_array.set(block_id, 1); entries.get(extent_id)->update(); } gc_stats.garbage_blocks++; } void data_block_manager_t::start_reconstruct() { gc_state.step = gc_reconstruct; } void data_block_manager_t::mark_live(off64_t offset) { assert(gc_state.step == gc_reconstruct); unsigned int extent_id = (offset / extent_manager->extent_size); unsigned int block_id = (offset % extent_manager->extent_size) / block_size; if (entries.get(extent_id) == NULL) { gc_entry entry; entry.offset = extent_id * extent_manager->extent_size; entry.active = false; entry.g_array.set(); //set everything to garbage entries.set(extent_id, gc_pq.push(entry)); } /* mark the block as alive */ entries.get(extent_id)->data.g_array.set(block_id, 0); } void data_block_manager_t::end_reconstruct() { gc_state.step = gc_ready; } void data_block_manager_t::start_gc() { if (gc_state.step == gc_ready) run_gc(); } /* TODO this currently cleans extent by extent, we should tune it to always have a certain number of outstanding blocks */ void data_block_manager_t::run_gc() { do { bool fallthrough; switch (gc_state.step) { case gc_ready: fallthrough = false; //TODO, need to make sure we don't gc the extent we're writing to if (gc_criterion()(gc_pq.peak())) { /* grab the entry */ gc_state.current_entry = gc_pq.pop(); delete entries.get(gc_state.current_entry.offset / EXTENT_SIZE); entries.set(gc_state.current_entry.offset / EXTENT_SIZE, NULL); /* read all the live data into buffers */ event_queue_t *queue = get_cpu_context()->event_queue; /* make sure the read callback knows who we are */ gc_state.gc_read_callback.parent = this; for (unsigned int i = 0; i < extent_manager->extent_size / BTREE_BLOCK_SIZE; i++) { if (!gc_state.current_entry.g_array[i]) { queue->iosys.schedule_aio_read(dbfd, gc_state.current_entry.offset + (i * block_size), block_size, gc_state.gc_blocks + (i * block_size), queue, &(gc_state.gc_read_callback)); gc_state.refcount++; gc_state.blocks_copying++; } } gc_state.step = gc_read; if (gc_state.refcount == 0) fallthrough = true; } else { return; } if (!fallthrough) break; case gc_read: fallthrough = false; /* refcount can == 0 here if we fell through */ gc_state.refcount--; if (gc_state.refcount <= 0) { /* we can get here with a refcount of 0 */ gc_state.refcount = 0; /* check if blocks need to be copied */ if (gc_state.current_entry.g_array.count() < gc_state.current_entry.g_array.size()) { /* an array to put our writes in */ log_serializer_t::write_t writes[gc_state.current_entry.g_array.size() - gc_state.current_entry.g_array.count()]; int nwrites = 0; for (unsigned int i = 0; i < extent_manager->extent_size / BTREE_BLOCK_SIZE; i++) { if (!gc_state.current_entry.g_array[i]) { writes[nwrites].block_id = *((block_id_t *) (gc_state.gc_blocks + (i * block_size))); writes[nwrites].buf = gc_state.gc_blocks + (i * block_size); writes[nwrites].callback = NULL; nwrites++; } } /* make sure the callback knows who we are */ gc_state.gc_write_callback.parent = this; /* schedule the write */ serializer->do_write(writes, gc_state.current_entry.g_array.size() - gc_state.current_entry.g_array.count() , (log_serializer_t::write_txn_callback_t *) &gc_state.gc_write_callback); } else { fallthrough = true; } gc_state.step = gc_write; } if (!fallthrough) break; case gc_write: //not valid when writes are asynchronous (it would be nice if we could have this) assert(gc_state.current_entry.g_array.count() == gc_state.current_entry.g_array.size()); assert(entries.get(gc_state.current_entry.offset / extent_manager->extent_size) == NULL); extent_manager->release_extent(gc_state.current_entry.offset); assert(gc_state.refcount == 0); gc_state.blocks_copying = 0; gc_state.step = gc_ready; /* update stats */ gc_stats.total_blocks -= EXTENT_SIZE / BTREE_BLOCK_SIZE; gc_stats.garbage_blocks -= EXTENT_SIZE / BTREE_BLOCK_SIZE; if(state == state_shutting_down) { if(shutdown_callback) shutdown_callback->on_datablock_manager_shutdown(); state = state_shut_down; } break; default: fail("Unknown gc_step"); break; } } while (gc_state.step == gc_ready); } void data_block_manager_t::prepare_metablock(metablock_mixin_t *metablock) { assert(state == state_ready); metablock->last_data_extent = last_data_extent; metablock->blocks_in_last_data_extent = blocks_in_last_data_extent; } bool data_block_manager_t::shutdown(shutdown_callback_t *cb) { assert(cb); assert(state == state_ready); if(gc_state.step != gc_ready) { state = state_shutting_down; shutdown_callback = cb; return false; } state = state_shut_down; return true; } off64_t data_block_manager_t::gimme_a_new_offset() { if (blocks_in_last_data_extent == extent_manager->extent_size / block_size) { /* deactivate the last extent */ entries.get(last_data_extent / EXTENT_SIZE)->data.active = false; entries.get(last_data_extent / EXTENT_SIZE)->update(); last_data_extent = extent_manager->gen_extent(); blocks_in_last_data_extent = 0; add_gc_entry(); } off64_t offset = last_data_extent + blocks_in_last_data_extent * block_size; blocks_in_last_data_extent ++; return offset; } void data_block_manager_t::add_gc_entry() { gc_entry entry; entry.offset = last_data_extent; entry.active = true; unsigned int extent_id = last_data_extent / extent_manager->extent_size; assert(entries.get(extent_id) == NULL); entries.set(extent_id, gc_pq.push(entry)); /* update stats */ gc_stats.total_blocks += EXTENT_SIZE / BTREE_BLOCK_SIZE; } /* functions for gc structures */ bool data_block_manager_t::gc_criterion::operator() (const gc_entry entry) { return entry.g_array.count() >= ((EXTENT_SIZE / BTREE_BLOCK_SIZE) * 3) / 4 && !entry.active; // 3/4 garbage } /* !< is x less than y */ bool data_block_manager_t::Less::operator() (const data_block_manager_t::gc_entry x, const data_block_manager_t::gc_entry y) { if (x.active) return true; else if (y.active) return false; else return x.g_array.count() < y.g_array.count(); } /**************** *Stat functions* ****************/ float data_block_manager_t::garbage_ratio() { return (float) gc_stats.garbage_blocks / (float) gc_stats.total_blocks; } <commit_msg>Data block manager should be able to prepare metablock during shutdown<commit_after>#include "data_block_manager.hpp" #include "log_serializer.hpp" #include "utils.hpp" #include "cpu_context.hpp" #include "event_queue.hpp" #include "arch/io.hpp" void data_block_manager_t::start(fd_t fd) { assert(state == state_unstarted); dbfd = fd; last_data_extent = extent_manager->gen_extent(); blocks_in_last_data_extent = 0; add_gc_entry(); state = state_ready; } void data_block_manager_t::start(fd_t fd, metablock_mixin_t *last_metablock) { assert(state == state_unstarted); dbfd = fd; last_data_extent = last_metablock->last_data_extent; blocks_in_last_data_extent = last_metablock->blocks_in_last_data_extent; state = state_ready; } bool data_block_manager_t::read(off64_t off_in, void *buf_out, iocallback_t *cb) { assert(state == state_ready); event_queue_t *queue = get_cpu_context()->event_queue; queue->iosys.schedule_aio_read(dbfd, off_in, block_size, buf_out, queue, cb); return false; } bool data_block_manager_t::write(void *buf_in, off64_t *off_out, iocallback_t *cb) { // Either we're ready to write, or we're shutting down and just // finished reading blocks for gc and called do_write. assert(state == state_ready || (state == state_shutting_down && gc_state.step == gc_read)); off64_t offset = *off_out = gimme_a_new_offset(); event_queue_t *queue = get_cpu_context()->event_queue; queue->iosys.schedule_aio_write(dbfd, offset, block_size, buf_in, queue, cb); return false; } void data_block_manager_t::mark_garbage(off64_t offset) { unsigned int extent_id = (offset / extent_manager->extent_size); unsigned int block_id = (offset % extent_manager->extent_size) / block_size; if ((gc_state.step == gc_read || gc_state.step == gc_write) && gc_state.current_entry.offset / extent_manager->extent_size == extent_id) { gc_state.current_entry.g_array.set(block_id, 1); } else { assert(entries.get(extent_id)); entries.get(extent_id)->data.g_array.set(block_id, 1); entries.get(extent_id)->update(); } gc_stats.garbage_blocks++; } void data_block_manager_t::start_reconstruct() { gc_state.step = gc_reconstruct; } void data_block_manager_t::mark_live(off64_t offset) { assert(gc_state.step == gc_reconstruct); unsigned int extent_id = (offset / extent_manager->extent_size); unsigned int block_id = (offset % extent_manager->extent_size) / block_size; if (entries.get(extent_id) == NULL) { gc_entry entry; entry.offset = extent_id * extent_manager->extent_size; entry.active = false; entry.g_array.set(); //set everything to garbage entries.set(extent_id, gc_pq.push(entry)); } /* mark the block as alive */ entries.get(extent_id)->data.g_array.set(block_id, 0); } void data_block_manager_t::end_reconstruct() { gc_state.step = gc_ready; } void data_block_manager_t::start_gc() { if (gc_state.step == gc_ready) run_gc(); } /* TODO this currently cleans extent by extent, we should tune it to always have a certain number of outstanding blocks */ void data_block_manager_t::run_gc() { do { bool fallthrough; switch (gc_state.step) { case gc_ready: fallthrough = false; //TODO, need to make sure we don't gc the extent we're writing to if (gc_criterion()(gc_pq.peak())) { /* grab the entry */ gc_state.current_entry = gc_pq.pop(); delete entries.get(gc_state.current_entry.offset / EXTENT_SIZE); entries.set(gc_state.current_entry.offset / EXTENT_SIZE, NULL); /* read all the live data into buffers */ event_queue_t *queue = get_cpu_context()->event_queue; /* make sure the read callback knows who we are */ gc_state.gc_read_callback.parent = this; for (unsigned int i = 0; i < extent_manager->extent_size / BTREE_BLOCK_SIZE; i++) { if (!gc_state.current_entry.g_array[i]) { queue->iosys.schedule_aio_read(dbfd, gc_state.current_entry.offset + (i * block_size), block_size, gc_state.gc_blocks + (i * block_size), queue, &(gc_state.gc_read_callback)); gc_state.refcount++; gc_state.blocks_copying++; } } gc_state.step = gc_read; if (gc_state.refcount == 0) fallthrough = true; } else { return; } if (!fallthrough) break; case gc_read: fallthrough = false; /* refcount can == 0 here if we fell through */ gc_state.refcount--; if (gc_state.refcount <= 0) { /* we can get here with a refcount of 0 */ gc_state.refcount = 0; /* check if blocks need to be copied */ if (gc_state.current_entry.g_array.count() < gc_state.current_entry.g_array.size()) { /* an array to put our writes in */ log_serializer_t::write_t writes[gc_state.current_entry.g_array.size() - gc_state.current_entry.g_array.count()]; int nwrites = 0; for (unsigned int i = 0; i < extent_manager->extent_size / BTREE_BLOCK_SIZE; i++) { if (!gc_state.current_entry.g_array[i]) { writes[nwrites].block_id = *((block_id_t *) (gc_state.gc_blocks + (i * block_size))); writes[nwrites].buf = gc_state.gc_blocks + (i * block_size); writes[nwrites].callback = NULL; nwrites++; } } /* make sure the callback knows who we are */ gc_state.gc_write_callback.parent = this; /* schedule the write */ serializer->do_write(writes, gc_state.current_entry.g_array.size() - gc_state.current_entry.g_array.count() , (log_serializer_t::write_txn_callback_t *) &gc_state.gc_write_callback); } else { fallthrough = true; } gc_state.step = gc_write; } if (!fallthrough) break; case gc_write: //not valid when writes are asynchronous (it would be nice if we could have this) assert(gc_state.current_entry.g_array.count() == gc_state.current_entry.g_array.size()); assert(entries.get(gc_state.current_entry.offset / extent_manager->extent_size) == NULL); extent_manager->release_extent(gc_state.current_entry.offset); assert(gc_state.refcount == 0); gc_state.blocks_copying = 0; gc_state.step = gc_ready; /* update stats */ gc_stats.total_blocks -= EXTENT_SIZE / BTREE_BLOCK_SIZE; gc_stats.garbage_blocks -= EXTENT_SIZE / BTREE_BLOCK_SIZE; if(state == state_shutting_down) { if(shutdown_callback) shutdown_callback->on_datablock_manager_shutdown(); state = state_shut_down; } break; default: fail("Unknown gc_step"); break; } } while (gc_state.step == gc_ready); } void data_block_manager_t::prepare_metablock(metablock_mixin_t *metablock) { assert(state == state_ready || (state == state_shutting_down && gc_state.step == gc_read)); metablock->last_data_extent = last_data_extent; metablock->blocks_in_last_data_extent = blocks_in_last_data_extent; } bool data_block_manager_t::shutdown(shutdown_callback_t *cb) { assert(cb); assert(state == state_ready); if(gc_state.step != gc_ready) { state = state_shutting_down; shutdown_callback = cb; return false; } state = state_shut_down; return true; } off64_t data_block_manager_t::gimme_a_new_offset() { if (blocks_in_last_data_extent == extent_manager->extent_size / block_size) { /* deactivate the last extent */ entries.get(last_data_extent / EXTENT_SIZE)->data.active = false; entries.get(last_data_extent / EXTENT_SIZE)->update(); last_data_extent = extent_manager->gen_extent(); blocks_in_last_data_extent = 0; add_gc_entry(); } off64_t offset = last_data_extent + blocks_in_last_data_extent * block_size; blocks_in_last_data_extent ++; return offset; } void data_block_manager_t::add_gc_entry() { gc_entry entry; entry.offset = last_data_extent; entry.active = true; unsigned int extent_id = last_data_extent / extent_manager->extent_size; assert(entries.get(extent_id) == NULL); entries.set(extent_id, gc_pq.push(entry)); /* update stats */ gc_stats.total_blocks += EXTENT_SIZE / BTREE_BLOCK_SIZE; } /* functions for gc structures */ bool data_block_manager_t::gc_criterion::operator() (const gc_entry entry) { return entry.g_array.count() >= ((EXTENT_SIZE / BTREE_BLOCK_SIZE) * 3) / 4 && !entry.active; // 3/4 garbage } /* !< is x less than y */ bool data_block_manager_t::Less::operator() (const data_block_manager_t::gc_entry x, const data_block_manager_t::gc_entry y) { if (x.active) return true; else if (y.active) return false; else return x.g_array.count() < y.g_array.count(); } /**************** *Stat functions* ****************/ float data_block_manager_t::garbage_ratio() { return (float) gc_stats.garbage_blocks / (float) gc_stats.total_blocks; } <|endoftext|>
<commit_before>/* Copyright 2016 Mitchell Young 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 "plane_sweeper_2d3d.hpp" #include <cmath> #include <iomanip> #include <iostream> #include "util/error.hpp" #include "util/range.hpp" #include "util/validate_input.hpp" using mocc::sn::SnSweeper; using std::setfill; using std::setw; namespace { const std::vector<std::string> recognized_attributes = { "type", "expose_sn", "sn_project", "moc_project", "tl", "inactive_moc", "moc_modulo", "preserve_sn_quadrature", "relax", "discrepant_flux_update", "dump_corrections"}; } namespace mocc { namespace cmdo { //////////////////////////////////////////////////////////////////////////////// PlaneSweeper_2D3D::PlaneSweeper_2D3D(const pugi::xml_node &input, const CoreMesh &mesh) : TransportSweeper(input), mesh_(mesh), pair_(SnSweeperFactory_CDD(input.child("sn_sweeper"), mesh)), sn_sweeper_(std::move(pair_.first)), corrections_(pair_.second), moc_sweeper_(input.child("moc_sweeper"), mesh), ang_quad_(moc_sweeper_.get_ang_quad()), tl_(sn_sweeper_->n_group(), mesh_.n_pin()), sn_resid_norm_(sn_sweeper_->n_group()), sn_resid_(sn_sweeper_->n_group(), mesh_.n_pin()), prev_moc_flux_(sn_sweeper_->n_group(), mesh_.n_pin()), i_outer_(-1) { validate_input(input, recognized_attributes); this->parse_options(input); core_mesh_ = &mesh; xs_mesh_ = moc_sweeper_.get_xs_mesh(); flux_.reference(moc_sweeper_.flux()); vol_ = moc_sweeper_.volumes(); n_reg_ = moc_sweeper_.n_reg(); n_group_ = xs_mesh_->n_group(); groups_ = Range(n_group_); auto sn_xs_mesh = sn_sweeper_->get_homogenized_xsmesh(); assert(corrections_); moc_sweeper_.set_coupling(corrections_, sn_xs_mesh); if (!keep_sn_quad_) { sn_sweeper_->set_ang_quad(ang_quad_); } sn_sweeper_->get_homogenized_xsmesh()->set_flux(moc_sweeper_.flux()); coarse_data_ = nullptr; return; } //////////////////////////////////////////////////////////////////////////////// void PlaneSweeper_2D3D::sweep(int group) { if (!coarse_data_) { throw EXCEPT("CMFD must be enabled to do 2D3D."); } /// \todo do something less brittle if (group == 0) { i_outer_++; } // Calculate transverse leakage source if (do_tl_) { this->add_tl(group); } // MoC Sweeper bool do_moc = ((i_outer_ + 1) > n_inactive_moc_) && ((i_outer_ % moc_modulo_) == 0); if (do_moc) { moc_sweeper_.sweep(group); int n_negative = 0; const auto flux = moc_sweeper_.flux()(blitz::Range::all(), group); for (const auto &v : flux) { if (v < 0.0) { n_negative++; } } if (n_negative > 0) { std::cout << n_negative << " negative fluxes in group " << group << std::endl; } } ArrayB1 prev_moc_flux = prev_moc_flux_(group, blitz::Range::all()); prev_moc_flux(0) = 0.0; moc_sweeper_.get_pin_flux_1g(group, prev_moc_flux); if (do_mocproject_) { sn_sweeper_->set_pin_flux_1g(group, prev_moc_flux); } // Sn sweeper sn_sweeper_->sweep(group); if (do_snproject_) { ArrayB1 sn_flux(mesh_.n_pin()); sn_sweeper_->get_pin_flux_1g(group, sn_flux); moc_sweeper_.set_pin_flux_1g(group, sn_flux); } // Compute Sn-MoC residual real_t residual = 0.0; for (size_t i = 0; i < prev_moc_flux.size(); i++) { residual += (prev_moc_flux(i) - sn_sweeper_->flux(group, i)) * (prev_moc_flux(i) - sn_sweeper_->flux(group, i)); sn_resid_(group, (int)i) = sn_sweeper_->flux(group, i) - prev_moc_flux(i); } residual = sqrt(residual) / mesh_.n_pin(); std::cout << "MoC/Sn residual: " << residual; if (sn_resid_norm_[group].size() > 0) { std::cout << " \t" << residual / sn_resid_norm_[group].back(); } std::cout << std::endl; sn_resid_norm_[group].push_back(residual); } //////////////////////////////////////////////////////////////////////////////// void PlaneSweeper_2D3D::initialize() { sn_sweeper_->initialize(); moc_sweeper_.initialize(); } //////////////////////////////////////////////////////////////////////////////// void PlaneSweeper_2D3D::get_pin_flux_1g(int ig, ArrayB1 &flux) const { if (expose_sn_) { sn_sweeper_->get_pin_flux_1g(ig, flux); } else { moc_sweeper_.get_pin_flux_1g(ig, flux); } } //////////////////////////////////////////////////////////////////////////////// void PlaneSweeper_2D3D::add_tl(int group) { assert(coarse_data_); ArrayB1 tl_fsr(n_reg_); int ireg_pin = 0; int ipin = 0; blitz::Array<real_t, 1> tl_g = tl_(group, blitz::Range::all()); for (const auto &pin : mesh_) { Position pos = mesh_.pin_position(ipin); size_t icell = mesh_.coarse_cell(pos); real_t dz = mesh_.dz(pos.z); int surf_up = mesh_.coarse_surf(icell, Surface::TOP); int surf_down = mesh_.coarse_surf(icell, Surface::BOTTOM); real_t j_up = coarse_data_->current(surf_up, group); real_t j_down = coarse_data_->current(surf_down, group); tl_g(ipin) = tl_g(ipin) * (1.0 - relax_) + relax_ * (j_down - j_up) / dz; for (int ir = 0; ir < pin->n_reg(); ir++) { tl_fsr(ir + ireg_pin) = tl_g(ipin); } ipin++; ireg_pin += pin->n_reg(); } // Hand the transverse leakage to the MoC sweeper. moc_sweeper_.apply_transverse_leakage(group, tl_fsr); } //////////////////////////////////////////////////////////////////////////////// void PlaneSweeper_2D3D::output(H5Node &file) const { // Put the Sn data in its own location { auto g = file.create_group("/Sn"); sn_sweeper_->output(g); } // Put the MoC data in its own location { auto g = file.create_group("/MoC"); moc_sweeper_.output(g); } VecI dims; dims.push_back(mesh_.nz()); dims.push_back(mesh_.ny()); dims.push_back(mesh_.nx()); // Write out the Sn-MoC residual convergence file.create_group("/SnResid"); for (int g = 0; g < n_group_; g++) { std::stringstream setname; setname << "/SnResid/" << setfill('0') << setw(3) << g; VecI niter(1, sn_resid_norm_[g].size()); file.write(setname.str(), sn_resid_norm_[g], niter); } { auto flux = prev_moc_flux_.copy(); Normalize(flux.begin(), flux.end()); auto h5g = file.create_group("moc_flux"); for (const auto &ig : groups_) { std::stringstream setname; setname << setfill('0') << setw(3) << ig + 1; h5g.write(setname.str(), flux(ig, blitz::Range::all()), dims); } } // Write out the transverse leakages { auto group = file.create_group("/transverse_leakage"); for (int g = 0; g < n_group_; g++) { std::stringstream setname; setname << setfill('0') << setw(3) << g; const auto tl_slice = tl_((int)g, blitz::Range::all()); group.write(setname.str(), tl_slice.begin(), tl_slice.end(), dims); } } // Write out the correction factors if (dump_corrections_) { corrections_->output(file); } } //////////////////////////////////////////////////////////////////////////////// // At some point it might be nice to make the options const and initialized // them in the initializer list, then just check for validity later. This if // fine for now. void PlaneSweeper_2D3D::parse_options(const pugi::xml_node &input) { // Set defaults for everything expose_sn_ = false; do_snproject_ = false; do_mocproject_ = false; keep_sn_quad_ = false; do_tl_ = true; n_inactive_moc_ = 0; moc_modulo_ = 1; relax_ = 1.0; discrepant_flux_update_ = false; dump_corrections_ = false; // Override with entries in the input node if (!input.attribute("expose_sn").empty()) { expose_sn_ = input.attribute("expose_sn").as_bool(); } if (!input.attribute("sn_project").empty()) { do_snproject_ = input.attribute("sn_project").as_bool(); } if (!input.attribute("moc_project").empty()) { do_mocproject_ = input.attribute("moc_project").as_bool(); } if (!input.attribute("tl").empty()) { do_tl_ = input.attribute("tl").as_bool(); } if (!input.attribute("inactive_moc").empty()) { n_inactive_moc_ = input.attribute("inactive_moc").as_int(); } if (!input.attribute("moc_modulo").empty()) { moc_modulo_ = input.attribute("moc_modulo").as_int(); } if (!input.attribute("preserve_sn_quadrature").empty()) { keep_sn_quad_ = input.attribute("preserve_sn_quadrature").as_bool(); } if (!input.attribute("relax").empty()) { relax_ = input.attribute("relax").as_double(1.0); } if (!input.attribute("discrepant_flux_update").empty()) { discrepant_flux_update_ = input.attribute("discrepant_flux_update").as_bool(); } dump_corrections_ = input.attribute("dump_corrections").as_bool(false); // Throw a warning if TL is disabled if (!do_tl_) { Warn("Transverse leakage is disabled. Are you sure that's what you " "want?"); } // Make sure that if we are doing expose_sn, we arent also trying to do // MoC. Doesnt work right now. if (expose_sn_) { // Cheat and peek into the MoC tag int n_inner = input.child("moc_sweeper").attribute("n_inner").as_int(0); if (n_inner > 0) { throw EXCEPT("Probably shouldn't expose the Sn sweeper while " "doing MoC sweeps"); } } LogFile << "2D3D Sweeper options:" << std::endl; LogFile << " Sn Projection: " << do_snproject_ << std::endl; LogFile << " MoC Projection: " << do_mocproject_ << std::endl; LogFile << " Expose Sn pin flux: " << expose_sn_ << std::endl; LogFile << " Keep original Sn quadrature: " << keep_sn_quad_ << std::endl; LogFile << " Transverse Leakage: " << do_tl_ << std::endl; LogFile << " Relaxation factor: " << relax_ << std::endl; LogFile << " Inactive MoC Outer Iterations: " << n_inactive_moc_ << std::endl; LogFile << " MoC sweep modulo: " << moc_modulo_ << std::endl; LogFile << " Apply Sn-MoC flux residual to CMFD updates: " << discrepant_flux_update_ << std::endl; } } } // Namespace mocc::cmdo <commit_msg>Clean up some namespace stuff in 2d3d<commit_after>/* Copyright 2016 Mitchell Young 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 "plane_sweeper_2d3d.hpp" #include <cmath> #include <iomanip> #include <iostream> #include "util/error.hpp" #include "util/range.hpp" #include "util/validate_input.hpp" using mocc::sn::SnSweeper; using std::setfill; using std::setw; namespace { const std::vector<std::string> recognized_attributes = { "type", "expose_sn", "sn_project", "moc_project", "tl", "inactive_moc", "moc_modulo", "preserve_sn_quadrature", "relax", "discrepant_flux_update", "dump_corrections"}; } namespace mocc { namespace cmdo { //////////////////////////////////////////////////////////////////////////////// PlaneSweeper_2D3D::PlaneSweeper_2D3D(const pugi::xml_node &input, const CoreMesh &mesh) : TransportSweeper(input), mesh_(mesh), pair_(SnSweeperFactory_CDD(input.child("sn_sweeper"), mesh)), sn_sweeper_(std::move(pair_.first)), corrections_(pair_.second), moc_sweeper_(input.child("moc_sweeper"), mesh), ang_quad_(moc_sweeper_.get_ang_quad()), tl_(sn_sweeper_->n_group(), mesh_.n_pin()), sn_resid_norm_(sn_sweeper_->n_group()), sn_resid_(sn_sweeper_->n_group(), mesh_.n_pin()), prev_moc_flux_(sn_sweeper_->n_group(), mesh_.n_pin()), i_outer_(-1) { validate_input(input, recognized_attributes); this->parse_options(input); core_mesh_ = &mesh; xs_mesh_ = moc_sweeper_.get_xs_mesh(); flux_.reference(moc_sweeper_.flux()); vol_ = moc_sweeper_.volumes(); n_reg_ = moc_sweeper_.n_reg(); n_group_ = xs_mesh_->n_group(); groups_ = Range(n_group_); auto sn_xs_mesh = sn_sweeper_->get_homogenized_xsmesh(); assert(corrections_); moc_sweeper_.set_coupling(corrections_, sn_xs_mesh); if (!keep_sn_quad_) { sn_sweeper_->set_ang_quad(ang_quad_); } sn_sweeper_->get_homogenized_xsmesh()->set_flux(moc_sweeper_.flux()); coarse_data_ = nullptr; return; } //////////////////////////////////////////////////////////////////////////////// void PlaneSweeper_2D3D::sweep(int group) { if (!coarse_data_) { throw EXCEPT("CMFD must be enabled to do 2D3D."); } /// \todo do something less brittle if (group == 0) { i_outer_++; } // Calculate transverse leakage source if (do_tl_) { this->add_tl(group); } // MoC Sweeper bool do_moc = ((i_outer_ + 1) > n_inactive_moc_) && ((i_outer_ % moc_modulo_) == 0); if (do_moc) { moc_sweeper_.sweep(group); int n_negative = 0; const auto flux = moc_sweeper_.flux()(blitz::Range::all(), group); for (const auto &v : flux) { if (v < 0.0) { n_negative++; } } if (n_negative > 0) { std::cout << n_negative << " negative fluxes in group " << group << std::endl; } } ArrayB1 prev_moc_flux = prev_moc_flux_(group, blitz::Range::all()); moc_sweeper_.get_pin_flux_1g(group, prev_moc_flux); if (do_mocproject_) { sn_sweeper_->set_pin_flux_1g(group, prev_moc_flux); } // Sn sweeper sn_sweeper_->sweep(group); if (do_snproject_) { ArrayB1 sn_flux(mesh_.n_pin()); sn_sweeper_->get_pin_flux_1g(group, sn_flux); moc_sweeper_.set_pin_flux_1g(group, sn_flux); } // Compute Sn-MoC residual real_t residual = 0.0; for (size_t i = 0; i < prev_moc_flux.size(); i++) { residual += (prev_moc_flux(i) - sn_sweeper_->flux(group, i)) * (prev_moc_flux(i) - sn_sweeper_->flux(group, i)); sn_resid_(group, (int)i) = sn_sweeper_->flux(group, i) - prev_moc_flux(i); } residual = sqrt(residual) / mesh_.n_pin(); LogScreen << "MoC/Sn residual: " << residual; if (sn_resid_norm_[group].size() > 0) { std::cout << " \t" << residual / sn_resid_norm_[group].back(); } LogScreen << std::endl; sn_resid_norm_[group].push_back(residual); } //////////////////////////////////////////////////////////////////////////////// void PlaneSweeper_2D3D::initialize() { sn_sweeper_->initialize(); moc_sweeper_.initialize(); } //////////////////////////////////////////////////////////////////////////////// void PlaneSweeper_2D3D::get_pin_flux_1g(int ig, ArrayB1 &flux) const { if (expose_sn_) { sn_sweeper_->get_pin_flux_1g(ig, flux); } else { moc_sweeper_.get_pin_flux_1g(ig, flux); } } //////////////////////////////////////////////////////////////////////////////// void PlaneSweeper_2D3D::add_tl(int group) { assert(coarse_data_); ArrayB1 tl_fsr(n_reg_); int ireg_pin = 0; int ipin = 0; blitz::Array<real_t, 1> tl_g = tl_(group, blitz::Range::all()); for (const auto &pin : mesh_) { Position pos = mesh_.pin_position(ipin); size_t icell = mesh_.coarse_cell(pos); real_t dz = mesh_.dz(pos.z); int surf_up = mesh_.coarse_surf(icell, Surface::TOP); int surf_down = mesh_.coarse_surf(icell, Surface::BOTTOM); real_t j_up = coarse_data_->current(surf_up, group); real_t j_down = coarse_data_->current(surf_down, group); tl_g(ipin) = tl_g(ipin) * (1.0 - relax_) + relax_ * (j_down - j_up) / dz; for (int ir = 0; ir < pin->n_reg(); ir++) { tl_fsr(ir + ireg_pin) = tl_g(ipin); } ipin++; ireg_pin += pin->n_reg(); } // Hand the transverse leakage to the MoC sweeper. moc_sweeper_.apply_transverse_leakage(group, tl_fsr); } //////////////////////////////////////////////////////////////////////////////// void PlaneSweeper_2D3D::output(H5Node &file) const { // Put the Sn data in its own location { auto g = file.create_group("/Sn"); sn_sweeper_->output(g); } // Put the MoC data in its own location { auto g = file.create_group("/MoC"); moc_sweeper_.output(g); } VecI dims; dims.push_back(mesh_.nz()); dims.push_back(mesh_.ny()); dims.push_back(mesh_.nx()); // Write out the Sn-MoC residual convergence file.create_group("/SnResid"); for (int g = 0; g < n_group_; g++) { std::stringstream setname; setname << "/SnResid/" << std::setfill('0') << std::setw(3) << g; VecI niter(1, sn_resid_norm_[g].size()); file.write(setname.str(), sn_resid_norm_[g], niter); } { auto flux = prev_moc_flux_.copy(); Normalize(flux.begin(), flux.end()); auto h5g = file.create_group("moc_flux"); for (const auto &ig : groups_) { std::stringstream setname; setname << std::setfill('0') << std::setw(3) << ig + 1; h5g.write(setname.str(), flux(ig, blitz::Range::all()), dims); } } // Write out the transverse leakages { auto group = file.create_group("/transverse_leakage"); for (int g = 0; g < n_group_; g++) { std::stringstream setname; setname << std::setfill('0') << std::setw(3) << g; const auto tl_slice = tl_((int)g, blitz::Range::all()); group.write(setname.str(), tl_slice.begin(), tl_slice.end(), dims); } } // Write out the correction factors if (dump_corrections_) { corrections_->output(file); } } //////////////////////////////////////////////////////////////////////////////// // At some point it might be nice to make the options const and initialized // them in the initializer list, then just check for validity later. This if // fine for now. void PlaneSweeper_2D3D::parse_options(const pugi::xml_node &input) { // Set defaults for everything expose_sn_ = false; do_snproject_ = false; do_mocproject_ = false; keep_sn_quad_ = false; do_tl_ = true; n_inactive_moc_ = 0; moc_modulo_ = 1; relax_ = 1.0; discrepant_flux_update_ = false; dump_corrections_ = false; // Override with entries in the input node if (!input.attribute("expose_sn").empty()) { expose_sn_ = input.attribute("expose_sn").as_bool(); } if (!input.attribute("sn_project").empty()) { do_snproject_ = input.attribute("sn_project").as_bool(); } if (!input.attribute("moc_project").empty()) { do_mocproject_ = input.attribute("moc_project").as_bool(); } if (!input.attribute("tl").empty()) { do_tl_ = input.attribute("tl").as_bool(); } if (!input.attribute("inactive_moc").empty()) { n_inactive_moc_ = input.attribute("inactive_moc").as_int(); } if (!input.attribute("moc_modulo").empty()) { moc_modulo_ = input.attribute("moc_modulo").as_int(); } if (!input.attribute("preserve_sn_quadrature").empty()) { keep_sn_quad_ = input.attribute("preserve_sn_quadrature").as_bool(); } if (!input.attribute("relax").empty()) { relax_ = input.attribute("relax").as_double(1.0); } if (!input.attribute("discrepant_flux_update").empty()) { discrepant_flux_update_ = input.attribute("discrepant_flux_update").as_bool(); } dump_corrections_ = input.attribute("dump_corrections").as_bool(false); // Throw a warning if TL is disabled if (!do_tl_) { Warn("Transverse leakage is disabled. Are you sure that's what you " "want?"); } // Make sure that if we are doing expose_sn, we arent also trying to do // MoC. Doesnt work right now. if (expose_sn_) { // Cheat and peek into the MoC tag int n_inner = input.child("moc_sweeper").attribute("n_inner").as_int(0); if (n_inner > 0) { throw EXCEPT("Probably shouldn't expose the Sn sweeper while " "doing MoC sweeps"); } } LogFile << "2D3D Sweeper options:" << std::endl; LogFile << " Sn Projection: " << do_snproject_ << std::endl; LogFile << " MoC Projection: " << do_mocproject_ << std::endl; LogFile << " Expose Sn pin flux: " << expose_sn_ << std::endl; LogFile << " Keep original Sn quadrature: " << keep_sn_quad_ << std::endl; LogFile << " Transverse Leakage: " << do_tl_ << std::endl; LogFile << " Relaxation factor: " << relax_ << std::endl; LogFile << " Inactive MoC Outer Iterations: " << n_inactive_moc_ << std::endl; LogFile << " MoC sweep modulo: " << moc_modulo_ << std::endl; LogFile << " Apply Sn-MoC flux residual to CMFD updates: " << discrepant_flux_update_ << std::endl; } } } // Namespace mocc::cmdo <|endoftext|>
<commit_before> /* * Copyright (c) 2012 Karl N. Redgate * * 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. */ /** \file Thread.cc * \brief C++ class implementing a thread abstraction. * * This is a wrapper around a pthread library implementation that also * connects to a TCL library for debugging/configuration, etc. */ #include <stdlib.h> #include <string.h> #include <pthread.h> #include <tcl.h> #include "tcl_util.h" #include "Thread.h" #include "PlatformThread.h" #include "AppInit.h" namespace { Tcl_Interp *interpreter = NULL; } Tcl_Interp *Thread::global_interp() { return interpreter; } int thread_cmd( ClientData data, Tcl_Interp *interp, int objc, Tcl_Obj * CONST *objv ) { Thread *thread = (Thread *)data; if ( objc < 2 ) { Tcl_ResetResult( interp ); Tcl_WrongNumArgs( interp, 1, objv, "command ..." ); return TCL_ERROR; } char *command = Tcl_GetStringFromObj( objv[1], NULL ); if ( Tcl_StringMatch(command, "pid") ) { Tcl_Obj *result = Tcl_NewIntObj( thread->getpid() ); Tcl_SetObjResult( interp, result ); return TCL_OK; } if ( Tcl_StringMatch(command, "status") ) { Tcl_Obj *result = Tcl_NewStringObj( thread->status, -1 ); Tcl_SetObjResult( interp, result ); return TCL_OK; } Svc_SetResult( interp, "Unknown command for thread object", TCL_STATIC ); return TCL_ERROR; } void register_thread( Thread *thread ) { if ( thread->thread_name() == NULL ) return; char buffer[80]; snprintf( buffer, sizeof(buffer), "Thread::%s", thread->thread_name() ); Tcl_EvalEx( interpreter, "namespace eval Thread {}", -1, TCL_EVAL_GLOBAL ); Tcl_CreateObjCommand( interpreter, buffer, thread_cmd, (ClientData)thread, NULL ); } /** * The interpreter created here is not useful until it has been initialized * by the main program. */ class MainThread : public Thread { public: MainThread() : Thread("main") { set_main_thread_name(); id = pthread_self(); pid = ::getpid(); } virtual ~MainThread() {} virtual void run() { } virtual bool start() { return false; } }; pthread_key_t CurrentThread; class ThreadList { Thread *thread; ThreadList *next; public: ThreadList() { interpreter = Tcl_CreateInterp(); pthread_key_create( &CurrentThread, NULL ); thread = new MainThread; next = 0; pthread_setspecific( CurrentThread, thread ); register_thread( thread ); } ~ThreadList() { delete next; delete thread; } ThreadList( Thread *thread, ThreadList *next ) : thread(thread), next(next) { register_thread( thread ); } void add( Thread *that ) { ThreadList *entry = new ThreadList( that, next ); next = entry; } }; ThreadList threads; #if 0 union SIGNAL * receive( const SIGSELECT *segsel ) { Thread *self = (Thread *)pthread_getspecific(CurrentThread); // cycle through SignalQueue looking for the first // that matches the SIGSELECTLIST } #endif static void *boot( void *data ) { Thread *thread = (Thread *)data; pthread_setspecific( CurrentThread, thread ); pthread_setcancelstate( PTHREAD_CANCEL_ENABLE, NULL ); thread->setpid(); thread->running(); set_thread_name( thread->thread_name() ); thread->run(); return NULL; } bool Thread::start() { if ( pthread_create(&id, NULL, boot, this) ) { return false; } return true; } bool Thread::stop() { if ( pthread_cancel(id) != 0 ) { return false; } return true; } Thread::Thread( const char *_name ) : _thread_name(NULL) { thread_name( _name ); status = "stop ready"; threads.add( this ); } /** * Since _thread_name might be static - we cannot free it. * Thread names do not change frequently enough to warrant * worrying about the leak. */ void Thread::thread_name( const char *_name ) { if ( _name == NULL ) return; // if ( _thread_name != NULL ) free(_thread_name); _thread_name = strdup(_name); } int Thread::TclCommand( ClientData data, Tcl_Interp *interp, int objc, Tcl_Obj * CONST *objv ) { Thread *thread = (Thread *)data; if ( objc < 2 ) { Tcl_ResetResult( interp ); Tcl_WrongNumArgs( interp, 1, objv, "command ..." ); return TCL_ERROR; } char *command = Tcl_GetStringFromObj( objv[1], NULL ); if ( Tcl_StringMatch(command, "start") ) { thread->start(); Tcl_ResetResult( interp ); return TCL_OK; } if ( Tcl_StringMatch(command, "pid") ) { Tcl_Obj *result = Tcl_NewIntObj( thread->getpid() ); Tcl_SetObjResult( interp, result ); return TCL_OK; } if ( Tcl_StringMatch(command, "status") ) { Tcl_Obj *result = Tcl_NewStringObj( thread->status, -1 ); Tcl_SetObjResult( interp, result ); return TCL_OK; } Svc_SetResult( interp, "Unknown command for thread object", TCL_STATIC ); return TCL_ERROR; } static bool Thread_Module( Tcl_Interp *interp ) { return true; } app_init( Thread_Module ); /* vim: set autoindent expandtab sw=4 : */ <commit_msg>add spots for comments<commit_after> /* * Copyright (c) 2012 Karl N. Redgate * * 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. */ /** \file Thread.cc * \brief C++ class implementing a thread abstraction. * * This is a wrapper around a pthread library implementation that also * connects to a TCL library for debugging/configuration, etc. */ #include <stdlib.h> #include <string.h> #include <pthread.h> #include <tcl.h> #include "tcl_util.h" #include "Thread.h" #include "PlatformThread.h" #include "AppInit.h" namespace { Tcl_Interp *interpreter = NULL; } Tcl_Interp *Thread::global_interp() { return interpreter; } /** */ int thread_cmd( ClientData data, Tcl_Interp *interp, int objc, Tcl_Obj * CONST *objv ) { Thread *thread = (Thread *)data; if ( objc < 2 ) { Tcl_ResetResult( interp ); Tcl_WrongNumArgs( interp, 1, objv, "command ..." ); return TCL_ERROR; } char *command = Tcl_GetStringFromObj( objv[1], NULL ); if ( Tcl_StringMatch(command, "pid") ) { Tcl_Obj *result = Tcl_NewIntObj( thread->getpid() ); Tcl_SetObjResult( interp, result ); return TCL_OK; } if ( Tcl_StringMatch(command, "status") ) { Tcl_Obj *result = Tcl_NewStringObj( thread->status, -1 ); Tcl_SetObjResult( interp, result ); return TCL_OK; } Svc_SetResult( interp, "Unknown command for thread object", TCL_STATIC ); return TCL_ERROR; } /** */ void register_thread( Thread *thread ) { if ( thread->thread_name() == NULL ) return; char buffer[80]; snprintf( buffer, sizeof(buffer), "Thread::%s", thread->thread_name() ); Tcl_EvalEx( interpreter, "namespace eval Thread {}", -1, TCL_EVAL_GLOBAL ); Tcl_CreateObjCommand( interpreter, buffer, thread_cmd, (ClientData)thread, NULL ); } /** * The interpreter created here is not useful until it has been initialized * by the main program. */ class MainThread : public Thread { public: MainThread() : Thread("main") { set_main_thread_name(); id = pthread_self(); pid = ::getpid(); } virtual ~MainThread() {} virtual void run() { } virtual bool start() { return false; } }; pthread_key_t CurrentThread; class ThreadList { Thread *thread; ThreadList *next; public: ThreadList() { interpreter = Tcl_CreateInterp(); pthread_key_create( &CurrentThread, NULL ); thread = new MainThread; next = 0; pthread_setspecific( CurrentThread, thread ); register_thread( thread ); } ~ThreadList() { delete next; delete thread; } ThreadList( Thread *thread, ThreadList *next ) : thread(thread), next(next) { register_thread( thread ); } void add( Thread *that ) { ThreadList *entry = new ThreadList( that, next ); next = entry; } }; ThreadList threads; #if 0 union SIGNAL * receive( const SIGSELECT *segsel ) { Thread *self = (Thread *)pthread_getspecific(CurrentThread); // cycle through SignalQueue looking for the first // that matches the SIGSELECTLIST } #endif /** */ static void *boot( void *data ) { Thread *thread = (Thread *)data; pthread_setspecific( CurrentThread, thread ); pthread_setcancelstate( PTHREAD_CANCEL_ENABLE, NULL ); thread->setpid(); thread->running(); set_thread_name( thread->thread_name() ); thread->run(); return NULL; } /** */ bool Thread::start() { if ( pthread_create(&id, NULL, boot, this) ) { return false; } return true; } /** */ bool Thread::stop() { if ( pthread_cancel(id) != 0 ) { return false; } return true; } /** */ Thread::Thread( const char *_name ) : _thread_name(NULL) { thread_name( _name ); status = "stop ready"; threads.add( this ); } /** * Since _thread_name might be static - we cannot free it. * Thread names do not change frequently enough to warrant * worrying about the leak. */ void Thread::thread_name( const char *_name ) { if ( _name == NULL ) return; // if ( _thread_name != NULL ) free(_thread_name); _thread_name = strdup(_name); } /** */ int Thread::TclCommand( ClientData data, Tcl_Interp *interp, int objc, Tcl_Obj * CONST *objv ) { Thread *thread = (Thread *)data; if ( objc < 2 ) { Tcl_ResetResult( interp ); Tcl_WrongNumArgs( interp, 1, objv, "command ..." ); return TCL_ERROR; } char *command = Tcl_GetStringFromObj( objv[1], NULL ); if ( Tcl_StringMatch(command, "start") ) { thread->start(); Tcl_ResetResult( interp ); return TCL_OK; } if ( Tcl_StringMatch(command, "pid") ) { Tcl_Obj *result = Tcl_NewIntObj( thread->getpid() ); Tcl_SetObjResult( interp, result ); return TCL_OK; } if ( Tcl_StringMatch(command, "status") ) { Tcl_Obj *result = Tcl_NewStringObj( thread->status, -1 ); Tcl_SetObjResult( interp, result ); return TCL_OK; } Svc_SetResult( interp, "Unknown command for thread object", TCL_STATIC ); return TCL_ERROR; } /** */ static bool Thread_Module( Tcl_Interp *interp ) { return true; } app_init( Thread_Module ); /* vim: set autoindent expandtab sw=4 : */ <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "adddeviceoperation.h" #include "findkeyoperation.h" #include "getoperation.h" #include "addkeysoperation.h" #include "rmkeysoperation.h" #include "../../plugins/mer/merconstants.h" #include <iostream> // copy pasted from const char DisplayNameKey[] = "Name"; const char TypeKey[] = "OsType"; const char IdKey[] = "InternalId"; const char OriginKey[] = "Origin"; const char MachineTypeKey[] = "Type"; const char DeviceManagerKey[] = "DeviceManager"; const char DeviceListKey[] = "DeviceList"; // Connection const char HostKey[] = "Host"; const char SshPortKey[] = "SshPort"; const char PortsSpecKey[] = "FreePortsSpec"; const char UserNameKey[] = "Uname"; const char AuthKey[] = "Authentication"; const char KeyFileKey[] = "KeyFile"; const char PasswordKey[] = "Password"; const char TimeoutKey[] = "Timeout"; AddDeviceOperation::AddDeviceOperation(): m_origin(0), m_port(0), m_autheticationType(0), m_timeout(0), m_machineType(0) { } QString AddDeviceOperation::name() const { return QLatin1String("addDevice"); } QString AddDeviceOperation::helpText() const { return QLatin1String("add device to Qt Creator configuration"); } QString AddDeviceOperation::param(const QString &text) { return QLatin1String("--") + text.toLower(); } QString AddDeviceOperation::argumentsHelpText() const { const QString indent = QLatin1String(" "); return indent + param(QLatin1String(DisplayNameKey))+ QLatin1String(" <NAME> device name (required).\n") + indent + param(QLatin1String(TypeKey)) + QLatin1String(" <NAME> device type (required).\n") + indent + indent + QLatin1String(Mer::Constants::MER_DEVICE_TYPE_I486) + QLatin1String(" for mer i486 target\n") + indent + indent + QLatin1String(Mer::Constants::MER_DEVICE_TYPE_ARM) + QLatin1String(" for mer arm target\n") + indent + param(QLatin1String(OriginKey)) + QLatin1String(" <manuallyAdded/autoDetected> origin.\n") + indent + param(QLatin1String(MachineTypeKey)) + QLatin1String(" <hardware/emulator> machine type.\n") + indent + param(QLatin1String(HostKey)) + QLatin1String(" <NAME> host name for ssh connection.\n") + indent + param(QLatin1String(SshPortKey)) + QLatin1String(" <NUMBER> port for ssh connection.\n") + indent + param(QLatin1String(UserNameKey)) + QLatin1String(" <NAME> user name for ssh connection.\n") + indent + param(QLatin1String(AuthKey)) + QLatin1String(" <password/privateKey> authentication Id type (required).\n") + indent + param(QLatin1String(KeyFileKey)) + QLatin1String(" <FILE> private key file (required).\n") + indent + param(QLatin1String(PasswordKey)) + QLatin1String(" <NAME> password for ssh connection.\n") + indent + param(QLatin1String(TimeoutKey)) + QLatin1String(" <NUMBER> timeout for ssh connection.\n") + indent + param(QLatin1String(PortsSpecKey)) + QLatin1String(" <NUMBER,NUMBER|NUMBER-NUMBER> free ports.\n"); } bool AddDeviceOperation::setArguments(const QStringList &args) { for (int i = 0; i < args.count(); ++i) { const QString current = args.at(i); const QString next = ((i + 1) < args.count()) ? args.at(i + 1) : QString(); if (current == param(QLatin1String(DisplayNameKey))) { if (next.isNull()) return false; ++i; // skip next; m_displayName = next; continue; } if (current == param(QLatin1String(TypeKey))) { if (next.isNull()) return false; ++i; // skip next; m_type = next; continue; } if (current == param(QLatin1String(MachineTypeKey))) { if (next.isNull()) return false; ++i; // skip next; m_machineType = next == QLatin1String("emulator"); continue; } if (current == param(QLatin1String(OriginKey))) { if (next.isNull()) return false; ++i; // skip next; m_origin = next == QLatin1String("manuallyAdded"); continue; } if (current == param(QLatin1String(SshPortKey))) { if (next.isNull()) return false; ++i; // skip next; m_port = next.toInt(); continue; } if (current == param(QLatin1String(UserNameKey))) { if (next.isNull()) return false; ++i; // skip next; m_userName = next; continue; } if (current == param(QLatin1String(AuthKey))) { if (next.isNull()) return false; ++i; // skip next; m_autheticationType = next == QLatin1String("privateKey"); continue; } if (current == param(QLatin1String(KeyFileKey))) { if (next.isNull()) return false; ++i; // skip next; m_privateKeyFile = next; continue; } if (current == param(QLatin1String(PasswordKey))) { if (next.isNull()) return false; ++i; // skip next; m_password = next; continue; } if (current == param(QLatin1String(TimeoutKey))) { if (next.isNull()) return false; ++i; // skip next; m_timeout = next.toInt(); continue; } if (current == param(QLatin1String(PortsSpecKey))) { if (next.isNull()) return false; ++i; // skip next; m_freePorts = next; continue; } } const char MISSING[] = " parameter missing."; bool error = false; if (m_displayName.isEmpty()) { std::cerr << DisplayNameKey << MISSING << std::endl << std::endl; error = true; } if (m_type.isEmpty()) { std::cerr << TypeKey << MISSING << std::endl << std::endl; error = true; } return !error; } int AddDeviceOperation::execute() const { const QString devicesKey = QLatin1String("devices"); QVariantMap map = load(devicesKey); if (map.isEmpty()) map = initializeDevices(); QVariantMap mapdevice = map.value(QLatin1String(DeviceManagerKey)).toMap(); if (map.isEmpty()) std::cerr << "Error: Count found devices, file seems wrong." << std::endl; const QVariantMap result = addDevice(mapdevice, m_displayName, m_type, m_origin, m_machineType, m_host, m_port, m_userName, m_autheticationType, m_password, m_privateKeyFile, m_timeout,m_freePorts); if (result.isEmpty() || mapdevice == result) return -2; map.remove(QLatin1String(DeviceManagerKey)); map.insert(QLatin1String(DeviceManagerKey), result); return save(map, devicesKey) ? 0 : -3; } QVariantMap AddDeviceOperation::initializeDevices() { QVariantMap map; QVariantList deviceList; map.insert(QLatin1String(DeviceListKey), deviceList); QVariantMap data; data.insert(QLatin1String(DeviceManagerKey), map); return data; } QVariantMap AddDeviceOperation::addDevice(const QVariantMap &map, const QString &displayName, const QString &type, int origin, int machineType, const QString &host, int port, const QString &userName, int authenticationType, const QString &password, const QString &privateKeyFile, int timeout, const QString &freePorts) { QVariantMap result = map; QVariantList deviceList = map.value(QLatin1String(DeviceListKey)).toList(); QVariantMap data; data.insert(QLatin1String(DisplayNameKey), QVariant(displayName)); data.insert(QLatin1String(TypeKey), QVariant(type)); data.insert(QLatin1String(OriginKey),QVariant(origin)); data.insert(QLatin1String(MachineTypeKey), QVariant(machineType)); data.insert(QLatin1String(HostKey), QVariant(host)); data.insert(QLatin1String(SshPortKey), QVariant(port)); data.insert(QLatin1String(UserNameKey), QVariant(userName)); data.insert(QLatin1String(AuthKey), QVariant(authenticationType)); data.insert(QLatin1String(PasswordKey), QVariant(password)); data.insert(QLatin1String(KeyFileKey), QVariant(privateKeyFile)); data.insert(QLatin1String(TimeoutKey), QVariant(timeout)); data.insert(QLatin1String(PortsSpecKey), QVariant(freePorts)); deviceList.append(QVariant(data)); result.remove(QLatin1String(DeviceListKey)); result.insert(QLatin1String(DeviceListKey), deviceList); return result; } <commit_msg>Mer: SdkTool fix: parsing --host parameter<commit_after>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "adddeviceoperation.h" #include "findkeyoperation.h" #include "getoperation.h" #include "addkeysoperation.h" #include "rmkeysoperation.h" #include "../../plugins/mer/merconstants.h" #include <iostream> // copy pasted from const char DisplayNameKey[] = "Name"; const char TypeKey[] = "OsType"; const char IdKey[] = "InternalId"; const char OriginKey[] = "Origin"; const char MachineTypeKey[] = "Type"; const char DeviceManagerKey[] = "DeviceManager"; const char DeviceListKey[] = "DeviceList"; // Connection const char HostKey[] = "Host"; const char SshPortKey[] = "SshPort"; const char PortsSpecKey[] = "FreePortsSpec"; const char UserNameKey[] = "Uname"; const char AuthKey[] = "Authentication"; const char KeyFileKey[] = "KeyFile"; const char PasswordKey[] = "Password"; const char TimeoutKey[] = "Timeout"; AddDeviceOperation::AddDeviceOperation(): m_origin(0), m_port(0), m_autheticationType(0), m_timeout(0), m_machineType(0) { } QString AddDeviceOperation::name() const { return QLatin1String("addDevice"); } QString AddDeviceOperation::helpText() const { return QLatin1String("add device to Qt Creator configuration"); } QString AddDeviceOperation::param(const QString &text) { return QLatin1String("--") + text.toLower(); } QString AddDeviceOperation::argumentsHelpText() const { const QString indent = QLatin1String(" "); return indent + param(QLatin1String(DisplayNameKey))+ QLatin1String(" <NAME> device name (required).\n") + indent + param(QLatin1String(TypeKey)) + QLatin1String(" <NAME> device type (required).\n") + indent + indent + QLatin1String(Mer::Constants::MER_DEVICE_TYPE_I486) + QLatin1String(" for mer i486 target\n") + indent + indent + QLatin1String(Mer::Constants::MER_DEVICE_TYPE_ARM) + QLatin1String(" for mer arm target\n") + indent + param(QLatin1String(OriginKey)) + QLatin1String(" <manuallyAdded/autoDetected> origin.\n") + indent + param(QLatin1String(MachineTypeKey)) + QLatin1String(" <hardware/emulator> machine type.\n") + indent + param(QLatin1String(HostKey)) + QLatin1String(" <NAME> host name for ssh connection.\n") + indent + param(QLatin1String(SshPortKey)) + QLatin1String(" <NUMBER> port for ssh connection.\n") + indent + param(QLatin1String(UserNameKey)) + QLatin1String(" <NAME> user name for ssh connection.\n") + indent + param(QLatin1String(AuthKey)) + QLatin1String(" <password/privateKey> authentication Id type (required).\n") + indent + param(QLatin1String(KeyFileKey)) + QLatin1String(" <FILE> private key file (required).\n") + indent + param(QLatin1String(PasswordKey)) + QLatin1String(" <NAME> password for ssh connection.\n") + indent + param(QLatin1String(TimeoutKey)) + QLatin1String(" <NUMBER> timeout for ssh connection.\n") + indent + param(QLatin1String(PortsSpecKey)) + QLatin1String(" <NUMBER,NUMBER|NUMBER-NUMBER> free ports.\n"); } bool AddDeviceOperation::setArguments(const QStringList &args) { for (int i = 0; i < args.count(); ++i) { const QString current = args.at(i); const QString next = ((i + 1) < args.count()) ? args.at(i + 1) : QString(); if (current == param(QLatin1String(DisplayNameKey))) { if (next.isNull()) return false; ++i; // skip next; m_displayName = next; continue; } if (current == param(QLatin1String(TypeKey))) { if (next.isNull()) return false; ++i; // skip next; m_type = next; continue; } if (current == param(QLatin1String(MachineTypeKey))) { if (next.isNull()) return false; ++i; // skip next; m_machineType = next == QLatin1String("emulator"); continue; } if (current == param(QLatin1String(OriginKey))) { if (next.isNull()) return false; ++i; // skip next; m_origin = next == QLatin1String("manuallyAdded"); continue; } if (current == param(QLatin1String(SshPortKey))) { if (next.isNull()) return false; ++i; // skip next; m_port = next.toInt(); continue; } if (current == param(QLatin1String(HostKey))) { if (next.isNull()) return false; ++i; // skip next; m_host = next; continue; } if (current == param(QLatin1String(UserNameKey))) { if (next.isNull()) return false; ++i; // skip next; m_userName = next; continue; } if (current == param(QLatin1String(AuthKey))) { if (next.isNull()) return false; ++i; // skip next; m_autheticationType = next == QLatin1String("privateKey"); continue; } if (current == param(QLatin1String(KeyFileKey))) { if (next.isNull()) return false; ++i; // skip next; m_privateKeyFile = next; continue; } if (current == param(QLatin1String(PasswordKey))) { if (next.isNull()) return false; ++i; // skip next; m_password = next; continue; } if (current == param(QLatin1String(TimeoutKey))) { if (next.isNull()) return false; ++i; // skip next; m_timeout = next.toInt(); continue; } if (current == param(QLatin1String(PortsSpecKey))) { if (next.isNull()) return false; ++i; // skip next; m_freePorts = next; continue; } } const char MISSING[] = " parameter missing."; bool error = false; if (m_displayName.isEmpty()) { std::cerr << DisplayNameKey << MISSING << std::endl << std::endl; error = true; } if (m_type.isEmpty()) { std::cerr << TypeKey << MISSING << std::endl << std::endl; error = true; } return !error; } int AddDeviceOperation::execute() const { const QString devicesKey = QLatin1String("devices"); QVariantMap map = load(devicesKey); if (map.isEmpty()) map = initializeDevices(); QVariantMap mapdevice = map.value(QLatin1String(DeviceManagerKey)).toMap(); if (map.isEmpty()) std::cerr << "Error: Count found devices, file seems wrong." << std::endl; const QVariantMap result = addDevice(mapdevice, m_displayName, m_type, m_origin, m_machineType, m_host, m_port, m_userName, m_autheticationType, m_password, m_privateKeyFile, m_timeout,m_freePorts); if (result.isEmpty() || mapdevice == result) return -2; map.remove(QLatin1String(DeviceManagerKey)); map.insert(QLatin1String(DeviceManagerKey), result); return save(map, devicesKey) ? 0 : -3; } QVariantMap AddDeviceOperation::initializeDevices() { QVariantMap map; QVariantList deviceList; map.insert(QLatin1String(DeviceListKey), deviceList); QVariantMap data; data.insert(QLatin1String(DeviceManagerKey), map); return data; } QVariantMap AddDeviceOperation::addDevice(const QVariantMap &map, const QString &displayName, const QString &type, int origin, int machineType, const QString &host, int port, const QString &userName, int authenticationType, const QString &password, const QString &privateKeyFile, int timeout, const QString &freePorts) { QVariantMap result = map; QVariantList deviceList = map.value(QLatin1String(DeviceListKey)).toList(); QVariantMap data; data.insert(QLatin1String(DisplayNameKey), QVariant(displayName)); data.insert(QLatin1String(TypeKey), QVariant(type)); data.insert(QLatin1String(OriginKey),QVariant(origin)); data.insert(QLatin1String(MachineTypeKey), QVariant(machineType)); data.insert(QLatin1String(HostKey), QVariant(host)); data.insert(QLatin1String(SshPortKey), QVariant(port)); data.insert(QLatin1String(UserNameKey), QVariant(userName)); data.insert(QLatin1String(AuthKey), QVariant(authenticationType)); data.insert(QLatin1String(PasswordKey), QVariant(password)); data.insert(QLatin1String(KeyFileKey), QVariant(privateKeyFile)); data.insert(QLatin1String(TimeoutKey), QVariant(timeout)); data.insert(QLatin1String(PortsSpecKey), QVariant(freePorts)); deviceList.append(QVariant(data)); result.remove(QLatin1String(DeviceListKey)); result.insert(QLatin1String(DeviceListKey), deviceList); return result; } <|endoftext|>
<commit_before>#include "clang/Analysis/Til/Bytecode.h" #include "clang/ASTMatchers/ASTMatchFinder.h" #include "clang/Tooling/CompilationDatabase.h" #include "clang/Tooling/Tooling.h" #include "gtest/gtest.h" #include "lsa/BuildCallGraph.h" #include "til/TILCompare.h" /// Registers the necessary matcher and runs the call graph generation tool. void RunToolWithBuilder(ohmu::lsa::DefaultCallGraphBuilder &Builder, const std::string &content) { clang::ast_matchers::MatchFinder Finder; ohmu::lsa::CallGraphBuilderTool Tool; Tool.RegisterMatchers(Builder, &Finder); clang::FrontendAction *Action = clang::tooling::newFrontendActionFactory(&Finder)->create(); bool Success = clang::tooling::runToolOnCode(Action, content); ASSERT_TRUE(Success); } /// Helper function running actual tests. Creates a virtual file with the /// specified content and runs the call graph generation on it. It then checks /// whether the generated call graph matches the provided expected mapping. void TestCallGraph( const std::string &content, const std::unordered_map<std::string, std::vector<std::string>> &expected) { ohmu::lsa::DefaultCallGraphBuilder GraphBuilder; RunToolWithBuilder(GraphBuilder, content); const auto &graph = GraphBuilder.GetGraph(); EXPECT_EQ(expected.size(), graph.size()); for (auto &El : expected) { std::string Func = El.first; const std::vector<std::string> &ExpCalls = El.second; auto Element = graph.find(Func); EXPECT_NE(Element, graph.end()) << "Searching function-node " << Func << "."; if (Element != graph.end()) { ohmu::lsa::DefaultCallGraphBuilder::CallGraphNode *Node = (*Element).second.get(); EXPECT_NE(Node, nullptr) << "Searching function-node " << Func << "."; if (Node != nullptr) { const std::unordered_set<std::string> *Calls = Node->GetCalls(); EXPECT_EQ(ExpCalls.size(), Calls->size()) << "Within function-node " << Func << "."; auto NotFound = Calls->end(); for (auto &C : ExpCalls) { EXPECT_NE(Calls->find(C), NotFound) << "Within function-node " << Func << " did not find expected call " << C << "."; } } } } } /// Testing that the OhmuIR is generated and stored correctly. Does not intend /// to test the correctness of the generated IR, hence using a minimal function. TEST(BuildCallGraph, StoreOhmuIR) { std::string data = "void f() { }"; // Note: this encoding only works under GNU C++ name mangling. const std::string f = "_Z1fv"; ohmu::lsa::DefaultCallGraphBuilder GraphBuilder; RunToolWithBuilder(GraphBuilder, data); const auto &graph = GraphBuilder.GetGraph(); ASSERT_EQ(1, graph.size()); auto Element = graph.find(f); ASSERT_NE(Element, graph.end()) << "Searching function-node " << f << "."; ohmu::lsa::DefaultCallGraphBuilder::CallGraphNode *Node = (*Element).second.get(); const std::string &OhmuIR = Node->GetIR(); ohmu::MemRegion Region; ohmu::MemRegionRef Arena(&Region); ohmu::til::CFGBuilder Builder(Arena); ohmu::til::InMemoryReader ReadStream(OhmuIR.data(), OhmuIR.length(), Arena); ohmu::til::BytecodeReader Reader(Builder, &ReadStream); auto *Expr = Reader.read(); ASSERT_NE(nullptr, Expr); // Build expected SCFG Builder.beginCFG(nullptr); auto *SCFG = Builder.currentCFG(); Builder.beginBlock(SCFG->entry()); Builder.newGoto(SCFG->exit(), nullptr); Builder.endCFG(); auto *VoidType = Builder.newScalarType(ohmu::til::BaseType::getBaseType<void>()); auto *Code = Builder.newCode(VoidType, SCFG); auto *Expected = Builder.newSlot("f", Code); bool IRCorrect = ohmu::til::EqualsComparator::compareExprs(Expected, Expr); ASSERT_TRUE(IRCorrect); } TEST(BuildCallGraph, BasicSingleFunction) { std::string data = "void f() { }"; std::unordered_map<std::string, std::vector<std::string>> expected; expected["_Z1fv"] = std::vector<std::string>(); TestCallGraph(data, expected); } TEST(BuildCallGraph, BasicFunctionCallGraph) { std::string data = "void i(); void j(); " "void f() { i(); j(); j(); } " "void g() { f(); } " "void h() { f(); g(); } " "void i() { g(); g(); h(); f(); g(); } " "void j() { }"; const std::string f = "_Z1fv", g = "_Z1gv", h = "_Z1hv", i = "_Z1iv", j = "_Z1jv"; TestCallGraph(data, {{f, {i, j}}, {g, {f}}, {h, {f, g}}, {i, {f, g, h}}, {j, {}}}); } TEST(BuildCallGraph, MemberFunction) { std::string data = "void g() { } " "class B { " "public: " " void m() { } " " void m(int x) { g(); } " "}; " "void call() { B b; b.m(15); } " "void call(B *b) { b->m(); } "; const std::string g = "_Z1gv", call = "_Z4callv", callB = "_Z4callP1B", m = "_ZN1B1mEv", mInt = "_ZN1B1mEi", bCons = "_ZN1BC2Ev"; TestCallGraph(data, {{g, {}}, {bCons, {}}, {m, {}}, {mInt, {g}}, {call, {mInt, bCons}}, {callB, {m}}}); } TEST(BuildCallGraph, DestructorCall) { std::string data = "void g() { } " "class B { " "public: " " ~B() { g(); } " "}; " "void call() { B b; } "; const std::string g = "_Z1gv", call = "_Z4callv", bCons = "_ZN1BC2Ev", bDest = "_ZN1BD2Ev"; TestCallGraph(data, {{g, {}}, {bCons, {}}, {bDest, {g}}, {call, {bCons, bDest}}}); } TEST(BuildCallGraph, TemplatedFunction) { std::string data = "void g() { } " "template <class T> " "void t(T t) { g(); } " "void c() { t<bool>(false); t<int>(3); } " "template <class T> " "void cT(T t) { t.m(); } " "class B { " "public: " " void m() { } " "}; " "void cB() { B b; cT(b); } "; const std::string g = "_Z1gv", tBool = "_Z1tIbEvT_", tInt = "_Z1tIiEvT_", c = "_Z1cv", cTB = "_Z2cTI1BEvT_", bCons = "_ZN1BC2Ev", bCopy = "_ZN1BC2ERKS_", m = "_ZN1B1mEv", cB = "_Z2cBv"; TestCallGraph(data, {{g, {}}, {tBool, {g}}, {tInt, {g}}, {c, {tBool, tInt}}, {cTB, {m}}, {bCons, {}}, {bCopy, {}}, {m, {}}, {cB, {bCopy, bCons, cTB}}}); } TEST(BuildCallGraph, TemplatedSpecializeFunction) { std::string data = "void g() { } " "template <class T> " "void t(T t) { g(); } " "template <> " "void t(int t) { } " "void c() { t(13); } "; const std::string g = "_Z1gv", tInt = "_Z1tIiEvT_", c = "_Z1cv"; TestCallGraph(data, {{g, {}}, {tInt, {}}, {c, {tInt}}}); } TEST(BuildCallGraph, TemplatedClass) { std::string data = "void g() { } " "template <class T> " "class X { " "public: " " void x(); " "private: " " int * _m; " "}; " "template <class T> " "void X<T>::x() { delete this->_m; g(); }" "void c() { X<int> x; x.x(); } "; const std::string g = "_Z1gv", xCons = "_ZN1XIiEC2Ev", x = "_ZN1XIiE1xEv", c = "_Z1cv"; TestCallGraph(data, {{g, {}}, {xCons, {}}, {x, {g}}, {c, {xCons, x}}}); } TEST(BuildCallGraph, CRTP) { std::string data = "void g() { } " "template <class Self> " "class CRTP { " "public: " " Self *self() { " " return static_cast<Self *>(this); " " } " " void f() { " " Self *s = self(); " " s->v(); " " } " "}; " "class Inst : public CRTP<Inst> { " "public: " " void v() { g(); } " "}; " "void c(Inst I) { I.f(); } "; const std::string g = "_Z1gv", self = "_ZN4CRTPI4InstE4selfEv", f = "_ZN4CRTPI4InstE1fEv", v = "_ZN4Inst1vEv", c = "_Z1c4Inst"; TestCallGraph(data, {{g, {}}, {self, {}}, {f, {self, v}}, {v, {g}}, {c, {f}}}); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>Updating build call graph unit tests to use mangled names as well.<commit_after>#include "clang/Analysis/Til/Bytecode.h" #include "clang/ASTMatchers/ASTMatchFinder.h" #include "clang/Tooling/CompilationDatabase.h" #include "clang/Tooling/Tooling.h" #include "gtest/gtest.h" #include "lsa/BuildCallGraph.h" #include "til/TILCompare.h" /// Registers the necessary matcher and runs the call graph generation tool. void RunToolWithBuilder(ohmu::lsa::DefaultCallGraphBuilder &Builder, const std::string &content) { clang::ast_matchers::MatchFinder Finder; ohmu::lsa::CallGraphBuilderTool Tool; Tool.RegisterMatchers(Builder, &Finder); clang::FrontendAction *Action = clang::tooling::newFrontendActionFactory(&Finder)->create(); bool Success = clang::tooling::runToolOnCode(Action, content); ASSERT_TRUE(Success); } /// Helper function running actual tests. Creates a virtual file with the /// specified content and runs the call graph generation on it. It then checks /// whether the generated call graph matches the provided expected mapping. void TestCallGraph( const std::string &content, const std::unordered_map<std::string, std::vector<std::string>> &expected) { ohmu::lsa::DefaultCallGraphBuilder GraphBuilder; RunToolWithBuilder(GraphBuilder, content); const auto &graph = GraphBuilder.GetGraph(); EXPECT_EQ(expected.size(), graph.size()); for (auto &El : expected) { std::string Func = El.first; const std::vector<std::string> &ExpCalls = El.second; auto Element = graph.find(Func); EXPECT_NE(Element, graph.end()) << "Searching function-node " << Func << "."; if (Element != graph.end()) { ohmu::lsa::DefaultCallGraphBuilder::CallGraphNode *Node = (*Element).second.get(); EXPECT_NE(Node, nullptr) << "Searching function-node " << Func << "."; if (Node != nullptr) { const std::unordered_set<std::string> *Calls = Node->GetCalls(); EXPECT_EQ(ExpCalls.size(), Calls->size()) << "Within function-node " << Func << "."; auto NotFound = Calls->end(); for (auto &C : ExpCalls) { EXPECT_NE(Calls->find(C), NotFound) << "Within function-node " << Func << " did not find expected call " << C << "."; } } } } } /// Testing that the OhmuIR is generated and stored correctly. Does not intend /// to test the correctness of the generated IR, hence using a minimal function. TEST(BuildCallGraph, StoreOhmuIR) { std::string data = "void f() { }"; // Note: this encoding only works under GNU C++ name mangling. const std::string f = "_Z1fv"; ohmu::lsa::DefaultCallGraphBuilder GraphBuilder; RunToolWithBuilder(GraphBuilder, data); const auto &graph = GraphBuilder.GetGraph(); ASSERT_EQ(1, graph.size()); auto Element = graph.find(f); ASSERT_NE(Element, graph.end()) << "Searching function-node " << f << "."; ohmu::lsa::DefaultCallGraphBuilder::CallGraphNode *Node = (*Element).second.get(); const std::string &OhmuIR = Node->GetIR(); ohmu::MemRegion Region; ohmu::MemRegionRef Arena(&Region); ohmu::til::CFGBuilder Builder(Arena); ohmu::til::InMemoryReader ReadStream(OhmuIR.data(), OhmuIR.length(), Arena); ohmu::til::BytecodeReader Reader(Builder, &ReadStream); auto *Expr = Reader.read(); ASSERT_NE(nullptr, Expr); // Build expected SCFG Builder.beginCFG(nullptr); auto *SCFG = Builder.currentCFG(); Builder.beginBlock(SCFG->entry()); Builder.newGoto(SCFG->exit(), nullptr); Builder.endCFG(); auto *VoidType = Builder.newScalarType(ohmu::til::BaseType::getBaseType<void>()); auto *Code = Builder.newCode(VoidType, SCFG); auto *Expected = Builder.newSlot(f, Code); bool IRCorrect = ohmu::til::EqualsComparator::compareExprs(Expected, Expr); ASSERT_TRUE(IRCorrect); } TEST(BuildCallGraph, BasicSingleFunction) { std::string data = "void f() { }"; std::unordered_map<std::string, std::vector<std::string>> expected; expected["_Z1fv"] = std::vector<std::string>(); TestCallGraph(data, expected); } TEST(BuildCallGraph, BasicFunctionCallGraph) { std::string data = "void i(); void j(); " "void f() { i(); j(); j(); } " "void g() { f(); } " "void h() { f(); g(); } " "void i() { g(); g(); h(); f(); g(); } " "void j() { }"; const std::string f = "_Z1fv", g = "_Z1gv", h = "_Z1hv", i = "_Z1iv", j = "_Z1jv"; TestCallGraph(data, {{f, {i, j}}, {g, {f}}, {h, {f, g}}, {i, {f, g, h}}, {j, {}}}); } TEST(BuildCallGraph, MemberFunction) { std::string data = "void g() { } " "class B { " "public: " " void m() { } " " void m(int x) { g(); } " "}; " "void call() { B b; b.m(15); } " "void call(B *b) { b->m(); } "; const std::string g = "_Z1gv", call = "_Z4callv", callB = "_Z4callP1B", m = "_ZN1B1mEv", mInt = "_ZN1B1mEi", bCons = "_ZN1BC2Ev"; TestCallGraph(data, {{g, {}}, {bCons, {}}, {m, {}}, {mInt, {g}}, {call, {mInt, bCons}}, {callB, {m}}}); } TEST(BuildCallGraph, DestructorCall) { std::string data = "void g() { } " "class B { " "public: " " ~B() { g(); } " "}; " "void call() { B b; } "; const std::string g = "_Z1gv", call = "_Z4callv", bCons = "_ZN1BC2Ev", bDest = "_ZN1BD2Ev"; TestCallGraph(data, {{g, {}}, {bCons, {}}, {bDest, {g}}, {call, {bCons, bDest}}}); } TEST(BuildCallGraph, TemplatedFunction) { std::string data = "void g() { } " "template <class T> " "void t(T t) { g(); } " "void c() { t<bool>(false); t<int>(3); } " "template <class T> " "void cT(T t) { t.m(); } " "class B { " "public: " " void m() { } " "}; " "void cB() { B b; cT(b); } "; const std::string g = "_Z1gv", tBool = "_Z1tIbEvT_", tInt = "_Z1tIiEvT_", c = "_Z1cv", cTB = "_Z2cTI1BEvT_", bCons = "_ZN1BC2Ev", bCopy = "_ZN1BC2ERKS_", m = "_ZN1B1mEv", cB = "_Z2cBv"; TestCallGraph(data, {{g, {}}, {tBool, {g}}, {tInt, {g}}, {c, {tBool, tInt}}, {cTB, {m}}, {bCons, {}}, {bCopy, {}}, {m, {}}, {cB, {bCopy, bCons, cTB}}}); } TEST(BuildCallGraph, TemplatedSpecializeFunction) { std::string data = "void g() { } " "template <class T> " "void t(T t) { g(); } " "template <> " "void t(int t) { } " "void c() { t(13); } "; const std::string g = "_Z1gv", tInt = "_Z1tIiEvT_", c = "_Z1cv"; TestCallGraph(data, {{g, {}}, {tInt, {}}, {c, {tInt}}}); } TEST(BuildCallGraph, TemplatedClass) { std::string data = "void g() { } " "template <class T> " "class X { " "public: " " void x(); " "private: " " int * _m; " "}; " "template <class T> " "void X<T>::x() { delete this->_m; g(); }" "void c() { X<int> x; x.x(); } "; const std::string g = "_Z1gv", xCons = "_ZN1XIiEC2Ev", x = "_ZN1XIiE1xEv", c = "_Z1cv"; TestCallGraph(data, {{g, {}}, {xCons, {}}, {x, {g}}, {c, {xCons, x}}}); } TEST(BuildCallGraph, CRTP) { std::string data = "void g() { } " "template <class Self> " "class CRTP { " "public: " " Self *self() { " " return static_cast<Self *>(this); " " } " " void f() { " " Self *s = self(); " " s->v(); " " } " "}; " "class Inst : public CRTP<Inst> { " "public: " " void v() { g(); } " "}; " "void c(Inst I) { I.f(); } "; const std::string g = "_Z1gv", self = "_ZN4CRTPI4InstE4selfEv", f = "_ZN4CRTPI4InstE1fEv", v = "_ZN4Inst1vEv", c = "_Z1c4Inst"; TestCallGraph(data, {{g, {}}, {self, {}}, {f, {self, v}}, {v, {g}}, {c, {f}}}); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>/*ckwg +5 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #include "schedule_registry.h" #include "schedule_registry_exception.h" #include "types.h" #include <boost/foreach.hpp> #include <boost/thread/locks.hpp> #include <boost/thread/mutex.hpp> #include <utility> /** * \file schedule_registry.cxx * * \brief Implementation of the \link vistk::schedule_registry schedule registry\endlink. */ namespace vistk { schedule_registry_t schedule_registry::m_self = schedule_registry_t(); schedule_registry::type_t const schedule_registry::default_type = type_t("thread_pool"); schedule_registry ::~schedule_registry() { } void schedule_registry ::register_schedule(type_t const& type, description_t const& desc, schedule_ctor_t ctor) { if (!ctor) { throw null_schedule_ctor_exception(type); } if (m_registry.find(type) != m_registry.end()) { throw schedule_type_already_exists_exception(type); } m_registry[type] = schedule_typeinfo_t(desc, ctor); } schedule_t schedule_registry ::create_schedule(type_t const& type, config_t const& config, pipeline_t const& pipe) const { if (!config) { throw null_schedule_registry_config_exception(); } if (!pipe) { throw null_schedule_registry_pipeline_exception(); } schedule_store_t::const_iterator const i = m_registry.find(type); if (i == m_registry.end()) { throw no_such_schedule_type_exception(type); } return i->second.get<1>()(config, pipe); } schedule_registry::types_t schedule_registry ::types() const { types_t ts; BOOST_FOREACH (schedule_store_t::value_type const& entry, m_registry) { ts.push_back(entry.first); } return ts; } schedule_registry::description_t schedule_registry ::description(type_t const& type) const { schedule_store_t::const_iterator const i = m_registry.find(type); if (i == m_registry.end()) { throw no_such_schedule_type_exception(type); } return i->second.get<0>(); } schedule_registry_t schedule_registry ::self() { static boost::mutex mut; if (m_self) { return m_self; } boost::unique_lock<boost::mutex> lock(mut); if (!m_self) { m_self = schedule_registry_t(new schedule_registry); } return m_self; } schedule_registry ::schedule_registry() { } } <commit_msg>Change the default schedule type<commit_after>/*ckwg +5 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #include "schedule_registry.h" #include "schedule_registry_exception.h" #include "types.h" #include <boost/foreach.hpp> #include <boost/thread/locks.hpp> #include <boost/thread/mutex.hpp> #include <utility> /** * \file schedule_registry.cxx * * \brief Implementation of the \link vistk::schedule_registry schedule registry\endlink. */ namespace vistk { schedule_registry_t schedule_registry::m_self = schedule_registry_t(); schedule_registry::type_t const schedule_registry::default_type = type_t("thread_per_process"); schedule_registry ::~schedule_registry() { } void schedule_registry ::register_schedule(type_t const& type, description_t const& desc, schedule_ctor_t ctor) { if (!ctor) { throw null_schedule_ctor_exception(type); } if (m_registry.find(type) != m_registry.end()) { throw schedule_type_already_exists_exception(type); } m_registry[type] = schedule_typeinfo_t(desc, ctor); } schedule_t schedule_registry ::create_schedule(type_t const& type, config_t const& config, pipeline_t const& pipe) const { if (!config) { throw null_schedule_registry_config_exception(); } if (!pipe) { throw null_schedule_registry_pipeline_exception(); } schedule_store_t::const_iterator const i = m_registry.find(type); if (i == m_registry.end()) { throw no_such_schedule_type_exception(type); } return i->second.get<1>()(config, pipe); } schedule_registry::types_t schedule_registry ::types() const { types_t ts; BOOST_FOREACH (schedule_store_t::value_type const& entry, m_registry) { ts.push_back(entry.first); } return ts; } schedule_registry::description_t schedule_registry ::description(type_t const& type) const { schedule_store_t::const_iterator const i = m_registry.find(type); if (i == m_registry.end()) { throw no_such_schedule_type_exception(type); } return i->second.get<0>(); } schedule_registry_t schedule_registry ::self() { static boost::mutex mut; if (m_self) { return m_self; } boost::unique_lock<boost::mutex> lock(mut); if (!m_self) { m_self = schedule_registry_t(new schedule_registry); } return m_self; } schedule_registry ::schedule_registry() { } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: dibpreview.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: tra $ $Date: 2002-03-21 07:37:13 $ * * 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 _DIBPREVIEW_HXX_ #define _DIBPREVIEW_HXX_ //------------------------------------------------------------------------ // includes //------------------------------------------------------------------------ #ifndef _PREVIEWBASE_HXX_ #include "previewbase.hxx" #endif #ifndef _OSL_MUTEX_HXX_ #include <osl/mutex.hxx> #endif #include <windows.h> //--------------------------------------------- // A very simple wrapper for a window that does // display DIBs. // Maybe it would be better and more extensible // to create another class that is responsible // for rendering a specific image format into // the area of the window, but for our purpose // it's enough to go the simple way - KISS. //--------------------------------------------- class CDIBPreview : public PreviewBase { public: // ctor CDIBPreview(HINSTANCE instance,HWND parent,sal_Bool bShowWindow = sal_False); // dtor virtual ~CDIBPreview( ); // preview interface implementation virtual sal_Int32 SAL_CALL getTargetColorDepth() throw (::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getAvailableWidth() throw (::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getAvailableHeight() throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setImage(sal_Int16 aImageFormat, const ::com::sun::star::uno::Any& aImage) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL setShowState(sal_Bool bShowState) throw (::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL getShowState() throw (::com::sun::star::uno::RuntimeException); virtual HWND SAL_CALL getWindowHandle() const; private: virtual void SAL_CALL onPaint( HWND hWnd, HDC hDC ); ATOM SAL_CALL RegisterDibPreviewWindowClass( ); void SAL_CALL UnregisterDibPreviewWindowClass( ); static LRESULT CALLBACK WndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ); private: HINSTANCE m_Instance; HWND m_Hwnd; com::sun::star::uno::Sequence<sal_Int8> m_Image; osl::Mutex m_PaintLock; // the preview window class has to be registered only // once per process, so multiple instance of this class // share the registered window class static ATOM s_ClassAtom; static osl::Mutex s_Mutex; static sal_Int32 s_RegisterDibPreviewWndCount; // prevent copy and assignment private: CDIBPreview(const CDIBPreview&); CDIBPreview& operator=(const CDIBPreview&); }; #endif<commit_msg>INTEGRATION: CWS rt02 (1.4.50); FILE MERGED 2003/10/01 10:41:57 rt 1.4.50.1: #i19697# No newline at end of file<commit_after>/************************************************************************* * * $RCSfile: dibpreview.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2003-10-06 15:55:39 $ * * 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 _DIBPREVIEW_HXX_ #define _DIBPREVIEW_HXX_ //------------------------------------------------------------------------ // includes //------------------------------------------------------------------------ #ifndef _PREVIEWBASE_HXX_ #include "previewbase.hxx" #endif #ifndef _OSL_MUTEX_HXX_ #include <osl/mutex.hxx> #endif #include <windows.h> //--------------------------------------------- // A very simple wrapper for a window that does // display DIBs. // Maybe it would be better and more extensible // to create another class that is responsible // for rendering a specific image format into // the area of the window, but for our purpose // it's enough to go the simple way - KISS. //--------------------------------------------- class CDIBPreview : public PreviewBase { public: // ctor CDIBPreview(HINSTANCE instance,HWND parent,sal_Bool bShowWindow = sal_False); // dtor virtual ~CDIBPreview( ); // preview interface implementation virtual sal_Int32 SAL_CALL getTargetColorDepth() throw (::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getAvailableWidth() throw (::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getAvailableHeight() throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setImage(sal_Int16 aImageFormat, const ::com::sun::star::uno::Any& aImage) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL setShowState(sal_Bool bShowState) throw (::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL getShowState() throw (::com::sun::star::uno::RuntimeException); virtual HWND SAL_CALL getWindowHandle() const; private: virtual void SAL_CALL onPaint( HWND hWnd, HDC hDC ); ATOM SAL_CALL RegisterDibPreviewWindowClass( ); void SAL_CALL UnregisterDibPreviewWindowClass( ); static LRESULT CALLBACK WndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ); private: HINSTANCE m_Instance; HWND m_Hwnd; com::sun::star::uno::Sequence<sal_Int8> m_Image; osl::Mutex m_PaintLock; // the preview window class has to be registered only // once per process, so multiple instance of this class // share the registered window class static ATOM s_ClassAtom; static osl::Mutex s_Mutex; static sal_Int32 s_RegisterDibPreviewWndCount; // prevent copy and assignment private: CDIBPreview(const CDIBPreview&); CDIBPreview& operator=(const CDIBPreview&); }; #endif <|endoftext|>
<commit_before>#ifndef __SOCKADDR_HPP__ #define __SOCKADDR_HPP__ #include "../config.h" #include <netinet/in.h> #include <memory> #include <string> #include <boost/ptr_container/ptr_vector.hpp> #include "Errno.hxx" namespace SockAddr { class SockAddr { protected: SockAddr() throw() {} public: virtual ~SockAddr() throw() {}; virtual operator struct sockaddr const*() const throw() =0; virtual socklen_t const addr_len() const throw() =0; virtual std::string string() const throw(std::runtime_error) = 0; virtual int const proto_family() const throw() =0; virtual int const addr_family() const throw() =0; virtual bool is_any() const throw() =0; virtual bool is_loopback() const throw() =0; }; std::auto_ptr<SockAddr> create(struct sockaddr_storage const *addr) throw(std::invalid_argument); inline std::auto_ptr<SockAddr> create(struct sockaddr_in const *addr) throw(std::invalid_argument) { return create( reinterpret_cast<struct sockaddr_storage const*>(addr) ); } inline std::auto_ptr<SockAddr> create(struct sockaddr_in6 const *addr) throw(std::invalid_argument) { return create( reinterpret_cast<struct sockaddr_storage const*>(addr) ); } std::auto_ptr<SockAddr> translate(std::string const &host, unsigned short const port) throw(std::invalid_argument); std::auto_ptr< boost::ptr_vector< SockAddr > > resolve(std::string const &host, std::string const &service, int const family = 0, int const socktype = 0, int const protocol = 0, bool const v4_mapped = false); class Inet4 : public SockAddr { protected: struct sockaddr_in m_addr; public: Inet4(struct sockaddr_in const &addr) throw(); virtual ~Inet4() throw() {}; socklen_t const addr_len() const throw() { return sizeof(m_addr); } virtual operator struct sockaddr const*() const throw() { return reinterpret_cast<struct sockaddr const*>(&m_addr); } virtual std::string string() const throw(Errno); virtual int const proto_family() const throw() { return PF_INET; } virtual int const addr_family() const throw() { return AF_INET; } virtual bool is_any() const throw() { return m_addr.sin_addr.s_addr == INADDR_ANY; } virtual bool is_loopback() const throw() { return m_addr.sin_addr.s_addr == INADDR_LOOPBACK; } }; class Inet6 : public SockAddr { protected: struct sockaddr_in6 m_addr; public: Inet6(struct sockaddr_in6 const &addr) throw(); virtual ~Inet6() throw() {} socklen_t const addr_len() const throw() { return sizeof(m_addr); } virtual operator struct sockaddr const*() const throw() { return reinterpret_cast<struct sockaddr const*>(&m_addr); } virtual std::string string() const throw(std::runtime_error); virtual int const proto_family() const throw() { return PF_INET6; } virtual int const addr_family() const throw() { return AF_INET6; } virtual bool is_any() const throw() { return memcmp(&m_addr.sin6_addr, &in6addr_any, 16); } virtual bool is_loopback() const throw() { return memcmp(&m_addr.sin6_addr, &in6addr_loopback, 16); } }; } // namespace #endif // __SOCKADDR_HPP__ <commit_msg>Added port_number() method to SockAddr<commit_after>#ifndef __SOCKADDR_HPP__ #define __SOCKADDR_HPP__ #include "../config.h" #include <netinet/in.h> #include <memory> #include <string> #include <boost/ptr_container/ptr_vector.hpp> #include "Errno.hxx" namespace SockAddr { class SockAddr { protected: SockAddr() throw() {} public: virtual ~SockAddr() throw() {}; virtual operator struct sockaddr const*() const throw() =0; virtual socklen_t const addr_len() const throw() =0; virtual std::string string() const throw(std::runtime_error) = 0; virtual int const proto_family() const throw() =0; virtual int const addr_family() const throw() =0; virtual int const port_number() const throw() =0; virtual bool is_any() const throw() =0; virtual bool is_loopback() const throw() =0; }; std::auto_ptr<SockAddr> create(struct sockaddr_storage const *addr) throw(std::invalid_argument); inline std::auto_ptr<SockAddr> create(struct sockaddr_in const *addr) throw(std::invalid_argument) { return create( reinterpret_cast<struct sockaddr_storage const*>(addr) ); } inline std::auto_ptr<SockAddr> create(struct sockaddr_in6 const *addr) throw(std::invalid_argument) { return create( reinterpret_cast<struct sockaddr_storage const*>(addr) ); } std::auto_ptr<SockAddr> translate(std::string const &host, unsigned short const port) throw(std::invalid_argument); std::auto_ptr< boost::ptr_vector< SockAddr > > resolve(std::string const &host, std::string const &service, int const family = 0, int const socktype = 0, int const protocol = 0, bool const v4_mapped = false); class Inet4 : public SockAddr { protected: struct sockaddr_in m_addr; public: Inet4(struct sockaddr_in const &addr) throw(); virtual ~Inet4() throw() {}; socklen_t const addr_len() const throw() { return sizeof(m_addr); } virtual operator struct sockaddr const*() const throw() { return reinterpret_cast<struct sockaddr const*>(&m_addr); } virtual std::string string() const throw(Errno); virtual int const proto_family() const throw() { return PF_INET; } virtual int const addr_family() const throw() { return AF_INET; } virtual int const port_number() const throw() { return ntohs(m_addr.sin_port); } virtual bool is_any() const throw() { return m_addr.sin_addr.s_addr == INADDR_ANY; } virtual bool is_loopback() const throw() { return m_addr.sin_addr.s_addr == INADDR_LOOPBACK; } }; class Inet6 : public SockAddr { protected: struct sockaddr_in6 m_addr; public: Inet6(struct sockaddr_in6 const &addr) throw(); virtual ~Inet6() throw() {} socklen_t const addr_len() const throw() { return sizeof(m_addr); } virtual operator struct sockaddr const*() const throw() { return reinterpret_cast<struct sockaddr const*>(&m_addr); } virtual std::string string() const throw(std::runtime_error); virtual int const proto_family() const throw() { return PF_INET6; } virtual int const addr_family() const throw() { return AF_INET6; } virtual int const port_number() const throw() { return ntohs(m_addr.sin6_port); } virtual bool is_any() const throw() { return memcmp(&m_addr.sin6_addr, &in6addr_any, 16); } virtual bool is_loopback() const throw() { return memcmp(&m_addr.sin6_addr, &in6addr_loopback, 16); } }; } // namespace #endif // __SOCKADDR_HPP__ <|endoftext|>
<commit_before>/* * gtgtrace * * Performs the core loop of the program: propagating satellite position * forward for the specified number of steps from the specified start time. */ #include <stdio.h> #include <string.h> #include <math.h> #include "SGP4.h" #include "Julian.h" #include "Timespan.h" #include "Tle.h" #include "gtg.h" #include "gtgutil.h" #include "gtgtle.h" #include "gtgshp.h" #include "gtgattr.h" #include "gtgtrace.h" /* InitTime Parameters: desc, string to read time specification from. Accepts four formats: now[OFFSET] - current time epoch[OFFSET] - reference time of orbit info If specified, OFFSET is number (positive or negative) followed by a character indicating units - s seconds, m minutes, h hours, d days. YYYY-MM-DD HH:MM:SS.SSSSSS UTC S - UNIX time (seconds since 1970-01-01 00:00:00) now, reference date to use if "now" time is specified epoch, reference date to use if orbit "epoch" is specified Returns: MFE (minutes from TLE epoch) of the described time */ double InitTime(const char *desc, const Julian& now, const Julian& epoch) { double mfe = 0; double offset; char unit; if (0 == strcmp("now", desc)) { mfe = (now - epoch).GetTotalMinutes(); } else if (2 == sscanf(desc, "now%lf%c", &offset, &unit)) { /* start with mfe of "now", then apply offset to that */ mfe = (now - epoch).GetTotalMinutes(); switch (unit) { case 's': mfe += offset / 60.0; break; case 'm': mfe += offset; break; case 'h': mfe += offset * 60.0; break; case 'd': mfe += offset * 1440.0; break; default: Fail("invalid current time offset unit: %c\n", unit); break; } } else if (0 == strcmp("epoch", desc)) { mfe = 0.0; } else if (2 == sscanf(desc, "epoch%lf%c", &offset, &unit)) { switch (unit) { case 's': mfe = offset / 60.0; break; case 'm': mfe = offset; break; case 'h': mfe = offset * 60.0; break; case 'd': mfe = offset * 1440.0; break; default: Fail("invalid epoch time offset unit: %c\n", unit); break; } } else { int year, month, day, hour, minute; double second; if (6 == sscanf(desc, "%4d-%2d-%2d %2d:%2d:%9lf UTC", &year, &month, &day, &hour, &minute, &second)) { Julian time(year, month, day, hour, minute, second); mfe = (time - epoch).GetTotalMinutes(); } else { double unixtime; if (1 == sscanf(desc, "%lf", &unixtime)) { Julian time((time_t)unixtime); mfe = (time - epoch).GetTotalMinutes(); } else { Fail("cannot parse time: %s\n", desc); } } } return mfe; } /* * Construct the output filename, minus shapefile file extensions. * The general format is: <basepath>/<prefix>rootname<suffix> * * If this is the only output file and basepath is specified, * the format is simply basepath and other elements are ignored. */ std::string BuildBasepath(const std::string& rootname, const GTGConfiguration& cfg) { std::string shpbase; /* if only one TLE was specified, we use --output as the unmodified basepath, and ignore --prefix and --suffix, and do not insert any ID. This only applies if --output is defined! Otherwise, use id/prefix/suffix. */ if (cfg.single && (cfg.basepath != NULL)) { shpbase += cfg.basepath; return shpbase; } if (NULL != cfg.basepath) { shpbase += cfg.basepath; if ('/' != shpbase[shpbase.length() - 1]) { shpbase += '/'; } } if (NULL != cfg.prefix) { shpbase += cfg.prefix; } shpbase += rootname; if (NULL != cfg.suffix) { shpbase += cfg.suffix; } return shpbase; } /* * Do some initialization that may be specific to this track (output start time, * name, etc.) and do the main orbit propagation loop, outputting at each step. */ void GenerateGroundTrack(Tle& tle, SGP4& model, Julian& now, const GTGConfiguration& cfg, const Timespan& interval) { int step = 0; Eci eci(now, 0, 0, 0); bool stop = false; CoordGeodetic geo; double minutes; double startMFE; double endMFE; double intervalMinutes; ShapefileWriter *shpwriter = NULL; AttributeWriter *attrwriter = NULL; int shpindex = 0; intervalMinutes = interval.GetTotalMinutes(); /* for line output mode */ Eci prevEci(eci); int prevSet = 0; /* Initialize the starting timestamp; default to epoch */ startMFE = InitTime(cfg.start == NULL ? "epoch" : cfg.start, now, tle.Epoch()); minutes = startMFE; Note("TLE epoch: %s\n", tle.Epoch().ToString().c_str()); Note("Start MFE: %.9lf\n", startMFE); /* Initialize the ending timestamp, if needed */ if (NULL != cfg.end) { endMFE = InitTime(cfg.end, now, tle.Epoch()); /* Sanity check 1 */ if (startMFE >= endMFE) { Fail("end time (%.9lf MFE) not after start time (%.9lf MFE)\n", endMFE, startMFE); } /* Sanity check 2 */ if (intervalMinutes > endMFE - startMFE) { Fail("interval (%.9lf minutes) exceeds period between start time and end time (%.9lf minutes).\n", intervalMinutes, endMFE - startMFE); } Note("End MFE: %.9lf\n", endMFE); } std::ostringstream ns; ns << tle.NoradNumber(); std::string basepath(BuildBasepath(ns.str(), cfg)); if (!(cfg.csvMode && (cfg.basepath == NULL))) { Note("Output basepath: %s\n", basepath.c_str()); } if (!cfg.csvMode) { shpwriter = new ShapefileWriter(basepath.c_str(), cfg.features, cfg.prj); } attrwriter = new AttributeWriter( cfg.csvMode && (cfg.basepath == NULL) ? NULL : basepath.c_str(), cfg.has_observer, cfg.obslat, cfg.obslon, cfg.obsalt, cfg.csvMode, cfg.csvHeader); while (1) { /* where is the satellite now? */ try { eci = model.FindPosition(minutes); } catch (SatelliteException &e) { Warn("satellite exception (stopping at step %d): %s\n", step, e.what()); break; } catch (DecayedException &e) { Warn("satellite decayed (stopping at step %d).\n", step); break; } if (line == cfg.features) { if (prevSet) { geo = prevEci.ToGeodetic(); if (cfg.csvMode) { // increment shpindex ourselves in csvMode attrwriter->output(shpindex++, minutes, prevEci, geo); } else { shpindex = shpwriter->output(prevEci, geo, &eci, cfg.split); attrwriter->output(shpindex, minutes, prevEci, geo); } step++; } else { /* prevSet is only false on the first pass, which yields an extra interval not counted against step count - needed since line segments imply n+1 intervals for n steps */ prevSet = 1; } prevEci = eci; } else { geo = eci.ToGeodetic(); if (cfg.csvMode) { attrwriter->output(shpindex++, minutes, eci, geo); } else { shpindex = shpwriter->output(eci, geo); attrwriter->output(shpindex, minutes, eci, geo); } step++; } /* increment time interval */ minutes += intervalMinutes; /* stop ground track once we've exceeded step count or end time */ if ((0 != cfg.steps) && (step >= cfg.steps)) { break; } else if ((NULL != cfg.end) && (minutes >= endMFE) ) { if (!cfg.forceend or stop) { break; } else { /* force output of the exact end time, then stop next time */ minutes = endMFE; stop = true; } } } if (shpwriter != NULL) { shpwriter->close(); delete shpwriter; } if (attrwriter != NULL) { attrwriter->close(); delete attrwriter; } } /* * Create an SGP4 model for the specified satellite two-line element set * and start generating its ground track. */ void InitGroundTrace(Tle& tle, Julian& now, const GTGConfiguration &cfg, const Timespan& interval) { try { SGP4 model(tle); GenerateGroundTrack(tle, model, now, cfg, interval); } catch (SatelliteException &e) { Fail("cannot initialize satellite model: %s\n", e.what()); } } <commit_msg>added support for time offsets with unixtime start/end<commit_after>/* * gtgtrace * * Performs the core loop of the program: propagating satellite position * forward for the specified number of steps from the specified start time. */ #include <stdio.h> #include <string.h> #include <math.h> #include "SGP4.h" #include "Julian.h" #include "Timespan.h" #include "Tle.h" #include "gtg.h" #include "gtgutil.h" #include "gtgtle.h" #include "gtgshp.h" #include "gtgattr.h" #include "gtgtrace.h" /* InitTime Parameters: desc, string to read time specification from. Accepts four formats: now[OFFSET] - current time epoch[OFFSET] - reference time of orbit info If specified, OFFSET is number (positive or negative) followed by a character indicating units - s seconds, m minutes, h hours, d days. YYYY-MM-DD HH:MM:SS.SSSSSS UTC S - UNIX time (seconds since 1970-01-01 00:00:00) now, reference date to use if "now" time is specified epoch, reference date to use if orbit "epoch" is specified Returns: MFE (minutes from TLE epoch) of the described time */ double InitTime(const char *desc, const Julian& now, const Julian& epoch) { double mfe = 0; double offset; char unit; if (0 == strcmp("now", desc)) { mfe = (now - epoch).GetTotalMinutes(); } else if (2 == sscanf(desc, "now%lf%c", &offset, &unit)) { /* start with mfe of "now", then apply offset to that */ mfe = (now - epoch).GetTotalMinutes(); switch (unit) { case 's': mfe += offset / 60.0; break; case 'm': mfe += offset; break; case 'h': mfe += offset * 60.0; break; case 'd': mfe += offset * 1440.0; break; default: Fail("invalid current time offset unit: %c\n", unit); break; } } else if (0 == strcmp("epoch", desc)) { mfe = 0.0; } else if (2 == sscanf(desc, "epoch%lf%c", &offset, &unit)) { switch (unit) { case 's': mfe = offset / 60.0; break; case 'm': mfe = offset; break; case 'h': mfe = offset * 60.0; break; case 'd': mfe = offset * 1440.0; break; default: Fail("invalid epoch time offset unit: %c\n", unit); break; } } else { int year, month, day, hour, minute; double second; if (6 == sscanf(desc, "%4d-%2d-%2d %2d:%2d:%9lf UTC", &year, &month, &day, &hour, &minute, &second)) { Julian time(year, month, day, hour, minute, second); mfe = (time - epoch).GetTotalMinutes(); } else { double unixtime; if (3 == sscanf(desc, "%lf%lf%c", &unixtime, &offset, &unit)) { Julian time((time_t)unixtime); mfe = (time - epoch).GetTotalMinutes(); switch (unit) { case 's': mfe += offset / 60.0; break; case 'm': mfe += offset; break; case 'h': mfe += offset * 60.0; break; case 'd': mfe += offset * 1440.0; break; default: Fail("invalid unix timestamp offset unit: %c\n", unit); break; } } else if (1 == sscanf(desc, "%lf", &unixtime)) { Julian time((time_t)unixtime); mfe = (time - epoch).GetTotalMinutes(); } else { Fail("cannot parse time: %s\n", desc); } } } return mfe; } /* * Construct the output filename, minus shapefile file extensions. * The general format is: <basepath>/<prefix>rootname<suffix> * * If this is the only output file and basepath is specified, * the format is simply basepath and other elements are ignored. */ std::string BuildBasepath(const std::string& rootname, const GTGConfiguration& cfg) { std::string shpbase; /* if only one TLE was specified, we use --output as the unmodified basepath, and ignore --prefix and --suffix, and do not insert any ID. This only applies if --output is defined! Otherwise, use id/prefix/suffix. */ if (cfg.single && (cfg.basepath != NULL)) { shpbase += cfg.basepath; return shpbase; } if (NULL != cfg.basepath) { shpbase += cfg.basepath; if ('/' != shpbase[shpbase.length() - 1]) { shpbase += '/'; } } if (NULL != cfg.prefix) { shpbase += cfg.prefix; } shpbase += rootname; if (NULL != cfg.suffix) { shpbase += cfg.suffix; } return shpbase; } /* * Do some initialization that may be specific to this track (output start time, * name, etc.) and do the main orbit propagation loop, outputting at each step. */ void GenerateGroundTrack(Tle& tle, SGP4& model, Julian& now, const GTGConfiguration& cfg, const Timespan& interval) { int step = 0; Eci eci(now, 0, 0, 0); bool stop = false; CoordGeodetic geo; double minutes; double startMFE; double endMFE; double intervalMinutes; ShapefileWriter *shpwriter = NULL; AttributeWriter *attrwriter = NULL; int shpindex = 0; intervalMinutes = interval.GetTotalMinutes(); /* for line output mode */ Eci prevEci(eci); int prevSet = 0; /* Initialize the starting timestamp; default to epoch */ startMFE = InitTime(cfg.start == NULL ? "epoch" : cfg.start, now, tle.Epoch()); minutes = startMFE; Note("TLE epoch: %s\n", tle.Epoch().ToString().c_str()); Note("Start MFE: %.9lf\n", startMFE); /* Initialize the ending timestamp, if needed */ if (NULL != cfg.end) { endMFE = InitTime(cfg.end, now, tle.Epoch()); /* Sanity check 1 */ if (startMFE >= endMFE) { Fail("end time (%.9lf MFE) not after start time (%.9lf MFE)\n", endMFE, startMFE); } /* Sanity check 2 */ if (intervalMinutes > endMFE - startMFE) { Fail("interval (%.9lf minutes) exceeds period between start time and end time (%.9lf minutes).\n", intervalMinutes, endMFE - startMFE); } Note("End MFE: %.9lf\n", endMFE); } std::ostringstream ns; ns << tle.NoradNumber(); std::string basepath(BuildBasepath(ns.str(), cfg)); if (!(cfg.csvMode && (cfg.basepath == NULL))) { Note("Output basepath: %s\n", basepath.c_str()); } if (!cfg.csvMode) { shpwriter = new ShapefileWriter(basepath.c_str(), cfg.features, cfg.prj); } attrwriter = new AttributeWriter( cfg.csvMode && (cfg.basepath == NULL) ? NULL : basepath.c_str(), cfg.has_observer, cfg.obslat, cfg.obslon, cfg.obsalt, cfg.csvMode, cfg.csvHeader); while (1) { /* where is the satellite now? */ try { eci = model.FindPosition(minutes); } catch (SatelliteException &e) { Warn("satellite exception (stopping at step %d): %s\n", step, e.what()); break; } catch (DecayedException &e) { Warn("satellite decayed (stopping at step %d).\n", step); break; } if (line == cfg.features) { if (prevSet) { geo = prevEci.ToGeodetic(); if (cfg.csvMode) { // increment shpindex ourselves in csvMode attrwriter->output(shpindex++, minutes, prevEci, geo); } else { shpindex = shpwriter->output(prevEci, geo, &eci, cfg.split); attrwriter->output(shpindex, minutes, prevEci, geo); } step++; } else { /* prevSet is only false on the first pass, which yields an extra interval not counted against step count - needed since line segments imply n+1 intervals for n steps */ prevSet = 1; } prevEci = eci; } else { geo = eci.ToGeodetic(); if (cfg.csvMode) { attrwriter->output(shpindex++, minutes, eci, geo); } else { shpindex = shpwriter->output(eci, geo); attrwriter->output(shpindex, minutes, eci, geo); } step++; } /* increment time interval */ minutes += intervalMinutes; /* stop ground track once we've exceeded step count or end time */ if ((0 != cfg.steps) && (step >= cfg.steps)) { break; } else if ((NULL != cfg.end) && (minutes >= endMFE) ) { if (!cfg.forceend or stop) { break; } else { /* force output of the exact end time, then stop next time */ minutes = endMFE; stop = true; } } } if (shpwriter != NULL) { shpwriter->close(); delete shpwriter; } if (attrwriter != NULL) { attrwriter->close(); delete attrwriter; } } /* * Create an SGP4 model for the specified satellite two-line element set * and start generating its ground track. */ void InitGroundTrace(Tle& tle, Julian& now, const GTGConfiguration &cfg, const Timespan& interval) { try { SGP4 model(tle); GenerateGroundTrack(tle, model, now, cfg, interval); } catch (SatelliteException &e) { Fail("cannot initialize satellite model: %s\n", e.what()); } } <|endoftext|>
<commit_before>#include <Endure.h> #include "Catch/single_include/catch.hpp" #include <memory> using namespace Endure; using namespace std; namespace Endure { template <typename T> class _List; template <typename T> class _List { public: static shared_ptr<_List<T>> Cons(T item, shared_ptr<_List<T>> list) { return shared_ptr<_List<T>>(new _List<T>(item, list)); } const T Head; const shared_ptr<_List<T>> Tail; const int Count; _List(T head) : Head(head), Tail(nullptr), Count(1) { } _List(T head, shared_ptr<_List<T>> tail) : Head(head), Tail(tail), Count(tail.get()->Count + 1) { } }; // TODO: Upgrade VS and use this everywhere //template <typename T> using List = shared_ptr<_List<T>>; } TEST_CASE("Create single element int list", "[List]") { auto l = shared_ptr<_List<int>>(new _List<int>(6)); REQUIRE(l->Head == 6); REQUIRE(!l->Tail); REQUIRE(l->Count == 1); } TEST_CASE("Create two element int list", "[List]") { auto tail = shared_ptr<_List<int>>(new _List<int>(29)); auto l = shared_ptr<_List<int>>(new _List<int>(45, tail)); REQUIRE(l->Head == 45); REQUIRE(l->Tail == tail); REQUIRE(l->Count == 2); shared_ptr<_List<int>> t = l->Tail; REQUIRE(t->Head == 29); REQUIRE(!t->Tail); REQUIRE(t->Count == 1); } TEST_CASE("Cons to single element int list", "[List]") { auto l = shared_ptr<_List<int>>(new _List<int>(2000)); auto l2 = _List<int>::Cons(1984, l); REQUIRE(l2->Head == 1984); REQUIRE(l2->Tail == l); REQUIRE(l2->Count == 2); REQUIRE(l2->Tail->Head == 2000); REQUIRE(!l2->Tail->Tail); REQUIRE(l2->Tail->Count == 1); } <commit_msg>played with basic stress test (looking good!), but I'll need more<commit_after>#include <Endure.h> #include "Catch/single_include/catch.hpp" #include <memory> using namespace Endure; using namespace std; namespace Endure { template <typename T> class _List; template <typename T> class _List { public: static shared_ptr<_List<T>> Cons(T item, shared_ptr<_List<T>> list) { return shared_ptr<_List<T>>(new _List<T>(item, list)); } const T Head; const shared_ptr<_List<T>> Tail; const int Count; _List(T head) : Head(head), Tail(nullptr), Count(1) { } _List(T head, shared_ptr<_List<T>> tail) : Head(head), Tail(tail), Count(tail.get()->Count + 1) { } }; // TODO: Upgrade VS and use this everywhere //template <typename T> using List = shared_ptr<_List<T>>; } TEST_CASE("Create single element int list", "[List]") { auto l = shared_ptr<_List<int>>(new _List<int>(6)); REQUIRE(l->Head == 6); REQUIRE(!l->Tail); REQUIRE(l->Count == 1); } TEST_CASE("Create two element int list", "[List]") { auto tail = shared_ptr<_List<int>>(new _List<int>(29)); auto l = shared_ptr<_List<int>>(new _List<int>(45, tail)); REQUIRE(l->Head == 45); REQUIRE(l->Tail == tail); REQUIRE(l->Count == 2); shared_ptr<_List<int>> t = l->Tail; REQUIRE(t->Head == 29); REQUIRE(!t->Tail); REQUIRE(t->Count == 1); } TEST_CASE("Cons to single element int list", "[List]") { auto l = shared_ptr<_List<int>>(new _List<int>(2000)); auto l2 = _List<int>::Cons(1984, l); REQUIRE(l2->Head == 1984); REQUIRE(l2->Tail == l); REQUIRE(l2->Count == 2); REQUIRE(l2->Tail->Head == 2000); REQUIRE(!l2->Tail->Tail); REQUIRE(l2->Tail->Count == 1); } TEST_CASE("Simple int list cons stress test", "[List") { auto l = shared_ptr<_List<int>>(new _List<int>(0)); for (int i = 1; i < 10000; i++) l = _List<int>::Cons(i, l); REQUIRE(l->Head == 9999); REQUIRE(l->Tail->Count == 9999); REQUIRE(l->Count == 10000); } <|endoftext|>
<commit_before>#include "hooks.h" #include "undocumented.h" #include "ssdt.h" #include "hider.h" #include "misc.h" #include "log.h" static HOOK hNtQueryInformationProcess = 0; static HOOK hNtQueryObject = 0; static HOOK hNtQuerySystemInformation = 0; static HOOK hNtClose = 0; static HOOK hNtSetInformationThread = 0; static HOOK hNtSetContextThread = 0; static HOOK hNtSystemDebugControl = 0; static KMUTEX gDebugPortMutex; //https://forum.tuts4you.com/topic/40011-debugme-vmprotect-312-build-886-anti-debug-method-improved/#comment-192824 //https://github.com/x64dbg/ScyllaHide/issues/47 //https://github.com/mrexodia/TitanHide/issues/27 #define BACKUP_RETURNLENGTH() \ ULONG TempReturnLength = 0; \ if(ARGUMENT_PRESENT(ReturnLength)) \ TempReturnLength = *ReturnLength #define RESTORE_RETURNLENGTH() \ if(ARGUMENT_PRESENT(ReturnLength)) \ *ReturnLength = TempReturnLength static NTSTATUS NTAPI HookNtSetInformationThread( IN HANDLE ThreadHandle, IN THREADINFOCLASS ThreadInformationClass, IN PVOID ThreadInformation, IN ULONG ThreadInformationLength) { //Bug found by Aguila, thanks! if(ThreadInformationClass == ThreadHideFromDebugger && !ThreadInformationLength) { ULONG pid = (ULONG)(ULONG_PTR)PsGetCurrentProcessId(); if(Hider::IsHidden(pid, HideThreadHideFromDebugger)) { Log("[TITANHIDE] ThreadHideFromDebugger by %d\r\n", pid); PETHREAD Thread; NTSTATUS status; #if NTDDI_VERSION >= NTDDI_WIN8 status = ObReferenceObjectByHandleWithTag(ThreadHandle, THREAD_SET_INFORMATION, *PsThreadType, ExGetPreviousMode(), 'yQsP', // special 'PsQuery' tag used in many Windows 8/8.1/10 NtXX/ZwXX functions (PVOID*)&Thread, NULL); #else // Vista and XP don't have ObReferenceObjectByHandleWithTag; 7 has it but doesn't use it in NtSetInformationThread status = ObReferenceObjectByHandle(ThreadHandle, THREAD_SET_INFORMATION, *PsThreadType, ExGetPreviousMode(), (PVOID*)&Thread, NULL); #endif if(NT_SUCCESS(status)) { #if NTDDI_VERSION >= NTDDI_WIN8 ObfDereferenceObjectWithTag(Thread, 'yQsP'); #else ObDereferenceObject(Thread); #endif } return status; } } return Undocumented::NtSetInformationThread(ThreadHandle, ThreadInformationClass, ThreadInformation, ThreadInformationLength); } static NTSTATUS NTAPI HookNtClose( IN HANDLE Handle) { ULONG pid = (ULONG)(ULONG_PTR)PsGetCurrentProcessId(); KPROCESSOR_MODE PreviousMode = ExGetPreviousMode(); if(Hider::IsHidden(pid, HideNtClose)) { KeWaitForSingleObject(&gDebugPortMutex, Executive, KernelMode, FALSE, nullptr); // Check if this is a valid handle without raising exceptionss BOOLEAN AuditOnClose; const NTSTATUS ObStatus = ObQueryObjectAuditingByHandle(Handle, &AuditOnClose); NTSTATUS Status; if(ObStatus != STATUS_INVALID_HANDLE) // Don't change the return path for any status except this one { Status = ObCloseHandle(Handle, PreviousMode); } else { Log("[TITANHIDE] NtClose(0x%p) by %d\r\n", Handle, pid); Status = STATUS_INVALID_HANDLE; } KeReleaseMutex(&gDebugPortMutex, FALSE); return Status; } return ObCloseHandle(Handle, PreviousMode); } static NTSTATUS NTAPI HookNtQuerySystemInformation( IN SYSTEM_INFORMATION_CLASS SystemInformationClass, OUT PVOID SystemInformation, IN ULONG SystemInformationLength, OUT PULONG ReturnLength OPTIONAL) { NTSTATUS ret = Undocumented::NtQuerySystemInformation(SystemInformationClass, SystemInformation, SystemInformationLength, ReturnLength); if(NT_SUCCESS(ret) && SystemInformation) { ULONG pid = (ULONG)(ULONG_PTR)PsGetCurrentProcessId(); if(SystemInformationClass == SystemKernelDebuggerInformation) { if(Hider::IsHidden(pid, HideSystemDebuggerInformation)) { Log("[TITANHIDE] SystemKernelDebuggerInformation by %d\r\n", pid); typedef struct _SYSTEM_KERNEL_DEBUGGER_INFORMATION { BOOLEAN DebuggerEnabled; BOOLEAN DebuggerNotPresent; } SYSTEM_KERNEL_DEBUGGER_INFORMATION, *PSYSTEM_KERNEL_DEBUGGER_INFORMATION; SYSTEM_KERNEL_DEBUGGER_INFORMATION* DebuggerInfo = (SYSTEM_KERNEL_DEBUGGER_INFORMATION*)SystemInformation; __try { BACKUP_RETURNLENGTH(); DebuggerInfo->DebuggerEnabled = false; DebuggerInfo->DebuggerNotPresent = true; RESTORE_RETURNLENGTH(); } __except(EXCEPTION_EXECUTE_HANDLER) { ret = GetExceptionCode(); } } } } return ret; } static NTSTATUS NTAPI HookNtQueryObject( IN HANDLE Handle OPTIONAL, IN OBJECT_INFORMATION_CLASS ObjectInformationClass, OUT PVOID ObjectInformation OPTIONAL, IN ULONG ObjectInformationLength, OUT PULONG ReturnLength OPTIONAL) { NTSTATUS ret = Undocumented::NtQueryObject(Handle, ObjectInformationClass, ObjectInformation, ObjectInformationLength, ReturnLength); if(NT_SUCCESS(ret) && ObjectInformation) { ULONG pid = (ULONG)(ULONG_PTR)PsGetCurrentProcessId(); UNICODE_STRING DebugObject; RtlInitUnicodeString(&DebugObject, L"DebugObject"); if(ObjectInformationClass == ObjectTypeInformation && Hider::IsHidden(pid, HideDebugObject)) { __try { BACKUP_RETURNLENGTH(); OBJECT_TYPE_INFORMATION* type = (OBJECT_TYPE_INFORMATION*)ObjectInformation; ProbeForRead(type->TypeName.Buffer, 1, 1); if(RtlEqualUnicodeString(&type->TypeName, &DebugObject, FALSE)) //DebugObject { Log("[TITANHIDE] DebugObject by %d\r\n", pid); type->TotalNumberOfObjects = 0; type->TotalNumberOfHandles = 0; } RESTORE_RETURNLENGTH(); } __except(EXCEPTION_EXECUTE_HANDLER) { ret = GetExceptionCode(); } } else if(ObjectInformationClass == ObjectTypesInformation && Hider::IsHidden(pid, HideDebugObject)) { //NCC Group Security Advisory __try { BACKUP_RETURNLENGTH(); OBJECT_ALL_INFORMATION* pObjectAllInfo = (OBJECT_ALL_INFORMATION*)ObjectInformation; unsigned char* pObjInfoLocation = (unsigned char*)pObjectAllInfo->ObjectTypeInformation; unsigned int TotalObjects = pObjectAllInfo->NumberOfObjects; for(unsigned int i = 0; i < TotalObjects; i++) { OBJECT_TYPE_INFORMATION* pObjectTypeInfo = (OBJECT_TYPE_INFORMATION*)pObjInfoLocation; ProbeForRead(pObjectTypeInfo, 1, 1); ProbeForRead(pObjectTypeInfo->TypeName.Buffer, 1, 1); if(RtlEqualUnicodeString(&pObjectTypeInfo->TypeName, &DebugObject, FALSE)) //DebugObject { Log("[TITANHIDE] DebugObject by %d\r\n", pid); pObjectTypeInfo->TotalNumberOfObjects = 0; //Bug found by Aguila, thanks! pObjectTypeInfo->TotalNumberOfHandles = 0; } pObjInfoLocation = (unsigned char*)pObjectTypeInfo->TypeName.Buffer; pObjInfoLocation += pObjectTypeInfo->TypeName.MaximumLength; ULONG_PTR tmp = ((ULONG_PTR)pObjInfoLocation) & -(LONG_PTR)sizeof(void*); if((ULONG_PTR)tmp != (ULONG_PTR)pObjInfoLocation) tmp += sizeof(void*); pObjInfoLocation = ((unsigned char*)tmp); } RESTORE_RETURNLENGTH(); } __except(EXCEPTION_EXECUTE_HANDLER) { ret = GetExceptionCode(); } } } return ret; } static NTSTATUS NTAPI HookNtQueryInformationProcess( IN HANDLE ProcessHandle, IN PROCESSINFOCLASS ProcessInformationClass, OUT PVOID ProcessInformation, IN ULONG ProcessInformationLength, OUT PULONG ReturnLength) { NTSTATUS ret = Undocumented::NtQueryInformationProcess(ProcessHandle, ProcessInformationClass, ProcessInformation, ProcessInformationLength, ReturnLength); if(NT_SUCCESS(ret) && ProcessInformation && ProcessInformationClass != ProcessBasicInformation) //prevent stack overflow { ULONG pid = Misc::GetProcessIDFromProcessHandle(ProcessHandle); if(ProcessInformationClass == ProcessDebugFlags) { if(Hider::IsHidden(pid, HideProcessDebugFlags)) { Log("[TITANHIDE] ProcessDebugFlags by %d\r\n", pid); __try { BACKUP_RETURNLENGTH(); *(unsigned int*)ProcessInformation = TRUE; RESTORE_RETURNLENGTH(); } __except(EXCEPTION_EXECUTE_HANDLER) { ret = GetExceptionCode(); } } } else if(ProcessInformationClass == ProcessDebugPort) { if(Hider::IsHidden(pid, HideProcessDebugPort)) { Log("[TITANHIDE] ProcessDebugPort by %d\r\n", pid); __try { BACKUP_RETURNLENGTH(); *(ULONG_PTR*)ProcessInformation = 0; RESTORE_RETURNLENGTH(); } __except(EXCEPTION_EXECUTE_HANDLER) { ret = GetExceptionCode(); } } } else if(ProcessInformationClass == ProcessDebugObjectHandle) { if(Hider::IsHidden(pid, HideProcessDebugObjectHandle)) { Log("[TITANHIDE] ProcessDebugObjectHandle by %d\r\n", pid); __try { BACKUP_RETURNLENGTH(); __try { // This was a successful request and a valid handle was returned. // That means we should close it before we nuke it to prevent handle leaks. ObCloseHandle(*(PHANDLE)ProcessInformation, KernelMode); } __except(EXCEPTION_EXECUTE_HANDLER) { NOTHING; } *(ULONG_PTR*)ProcessInformation = 0; RESTORE_RETURNLENGTH(); } __except(EXCEPTION_EXECUTE_HANDLER) { ret = GetExceptionCode(); } //Taken from: http://newgre.net/idastealth ret = STATUS_PORT_NOT_SET; } } } return ret; } static NTSTATUS NTAPI HookNtSetContextThread( IN HANDLE ThreadHandle, IN PCONTEXT Context) { ULONG pid = (ULONG)PsGetCurrentProcessId(); KPROCESSOR_MODE PreviousMode = ExGetPreviousMode(); bool IsHidden = PreviousMode != KernelMode && Hider::IsHidden(pid, HideNtSetContextThread); ULONG OriginalContextFlags = 0; if(IsHidden) { //http://lifeinhex.com/dont-touch-this-writing-good-drivers-is-really-hard //http://lifeinhex.com/when-software-is-good-enough Log("[TITANHIDE] NtSetContextThread by %d\r\n", pid); __try { ProbeForRead(&Context->ContextFlags, sizeof(ULONG), 1); OriginalContextFlags = Context->ContextFlags; ULONG NewContextFlags = OriginalContextFlags & ~0x10; //CONTEXT_DEBUG_REGISTERS ^ CONTEXT_AMD64/CONTEXT_i386 RtlSuperCopyMemory(&Context->ContextFlags, &NewContextFlags, sizeof(ULONG)); } __except(EXCEPTION_EXECUTE_HANDLER) { return Undocumented::NtSetContextThread(ThreadHandle, Context); } } NTSTATUS ret = Undocumented::NtSetContextThread(ThreadHandle, Context); if(IsHidden) { __try { ProbeForRead(&Context->ContextFlags, sizeof(ULONG), 1); RtlSuperCopyMemory(&Context->ContextFlags, &OriginalContextFlags, sizeof(ULONG)); } __except(EXCEPTION_EXECUTE_HANDLER) { } } return ret; } static NTSTATUS NTAPI HookNtSystemDebugControl( IN SYSDBG_COMMAND Command, IN PVOID InputBuffer, IN ULONG InputBufferLength, OUT PVOID OutputBuffer, IN ULONG OutputBufferLength, OUT PULONG ReturnLength) { ULONG pid = (ULONG)(ULONG_PTR)PsGetCurrentProcessId(); if(Hider::IsHidden(pid, HideNtSystemDebugControl)) { Log("[TITANHIDE] NtSystemDebugControl by %d\r\n", pid); if(Command == SysDbgGetTriageDump) return STATUS_INFO_LENGTH_MISMATCH; return STATUS_DEBUGGER_INACTIVE; } return Undocumented::NtSystemDebugControl(Command, InputBuffer, InputBufferLength, OutputBuffer, OutputBufferLength, ReturnLength); } int Hooks::Initialize() { KeInitializeMutex(&gDebugPortMutex, 0); int hook_count = 0; hNtQueryInformationProcess = SSDT::Hook("NtQueryInformationProcess", (void*)HookNtQueryInformationProcess); if(hNtQueryInformationProcess) hook_count++; hNtQueryObject = SSDT::Hook("NtQueryObject", (void*)HookNtQueryObject); if(hNtQueryObject) hook_count++; hNtQuerySystemInformation = SSDT::Hook("NtQuerySystemInformation", (void*)HookNtQuerySystemInformation); if(hNtQuerySystemInformation) hook_count++; hNtSetInformationThread = SSDT::Hook("NtSetInformationThread", (void*)HookNtSetInformationThread); if(hNtSetInformationThread) hook_count++; hNtClose = SSDT::Hook("NtClose", (void*)HookNtClose); if(hNtClose) hook_count++; hNtSetContextThread = SSDT::Hook("NtSetContextThread", (void*)HookNtSetContextThread); if(hNtSetContextThread) hook_count++; hNtSystemDebugControl = SSDT::Hook("NtSystemDebugControl", (void*)HookNtSystemDebugControl); if(hNtSystemDebugControl) hook_count++; return hook_count; } void Hooks::Deinitialize() { SSDT::Unhook(hNtQueryInformationProcess, true); SSDT::Unhook(hNtQueryObject, true); SSDT::Unhook(hNtQuerySystemInformation, true); SSDT::Unhook(hNtSetInformationThread, true); SSDT::Unhook(hNtClose, true); SSDT::Unhook(hNtSetContextThread, true); SSDT::Unhook(hNtSystemDebugControl, true); } <commit_msg>Fix VMProtect detection of NtQueryInformationProcess(HideProcessDebugObjectHandle) hook<commit_after>#include "hooks.h" #include "undocumented.h" #include "ssdt.h" #include "hider.h" #include "misc.h" #include "log.h" static HOOK hNtQueryInformationProcess = 0; static HOOK hNtQueryObject = 0; static HOOK hNtQuerySystemInformation = 0; static HOOK hNtClose = 0; static HOOK hNtSetInformationThread = 0; static HOOK hNtSetContextThread = 0; static HOOK hNtSystemDebugControl = 0; static KMUTEX gDebugPortMutex; //https://forum.tuts4you.com/topic/40011-debugme-vmprotect-312-build-886-anti-debug-method-improved/#comment-192824 //https://github.com/x64dbg/ScyllaHide/issues/47 //https://github.com/mrexodia/TitanHide/issues/27 #define BACKUP_RETURNLENGTH() \ ULONG TempReturnLength = 0; \ if(ARGUMENT_PRESENT(ReturnLength)) \ TempReturnLength = *ReturnLength #define RESTORE_RETURNLENGTH() \ if(ARGUMENT_PRESENT(ReturnLength)) \ *ReturnLength = TempReturnLength static NTSTATUS NTAPI HookNtSetInformationThread( IN HANDLE ThreadHandle, IN THREADINFOCLASS ThreadInformationClass, IN PVOID ThreadInformation, IN ULONG ThreadInformationLength) { //Bug found by Aguila, thanks! if(ThreadInformationClass == ThreadHideFromDebugger && !ThreadInformationLength) { ULONG pid = (ULONG)(ULONG_PTR)PsGetCurrentProcessId(); if(Hider::IsHidden(pid, HideThreadHideFromDebugger)) { Log("[TITANHIDE] ThreadHideFromDebugger by %d\r\n", pid); PETHREAD Thread; NTSTATUS status; #if NTDDI_VERSION >= NTDDI_WIN8 status = ObReferenceObjectByHandleWithTag(ThreadHandle, THREAD_SET_INFORMATION, *PsThreadType, ExGetPreviousMode(), 'yQsP', // special 'PsQuery' tag used in many Windows 8/8.1/10 NtXX/ZwXX functions (PVOID*)&Thread, NULL); #else // Vista and XP don't have ObReferenceObjectByHandleWithTag; 7 has it but doesn't use it in NtSetInformationThread status = ObReferenceObjectByHandle(ThreadHandle, THREAD_SET_INFORMATION, *PsThreadType, ExGetPreviousMode(), (PVOID*)&Thread, NULL); #endif if(NT_SUCCESS(status)) { #if NTDDI_VERSION >= NTDDI_WIN8 ObfDereferenceObjectWithTag(Thread, 'yQsP'); #else ObDereferenceObject(Thread); #endif } return status; } } return Undocumented::NtSetInformationThread(ThreadHandle, ThreadInformationClass, ThreadInformation, ThreadInformationLength); } static NTSTATUS NTAPI HookNtClose( IN HANDLE Handle) { ULONG pid = (ULONG)(ULONG_PTR)PsGetCurrentProcessId(); KPROCESSOR_MODE PreviousMode = ExGetPreviousMode(); if(Hider::IsHidden(pid, HideNtClose)) { KeWaitForSingleObject(&gDebugPortMutex, Executive, KernelMode, FALSE, nullptr); // Check if this is a valid handle without raising exceptionss BOOLEAN AuditOnClose; const NTSTATUS ObStatus = ObQueryObjectAuditingByHandle(Handle, &AuditOnClose); NTSTATUS Status; if(ObStatus != STATUS_INVALID_HANDLE) // Don't change the return path for any status except this one { Status = ObCloseHandle(Handle, PreviousMode); } else { Log("[TITANHIDE] NtClose(0x%p) by %d\r\n", Handle, pid); Status = STATUS_INVALID_HANDLE; } KeReleaseMutex(&gDebugPortMutex, FALSE); return Status; } return ObCloseHandle(Handle, PreviousMode); } static NTSTATUS NTAPI HookNtQuerySystemInformation( IN SYSTEM_INFORMATION_CLASS SystemInformationClass, OUT PVOID SystemInformation, IN ULONG SystemInformationLength, OUT PULONG ReturnLength OPTIONAL) { NTSTATUS ret = Undocumented::NtQuerySystemInformation(SystemInformationClass, SystemInformation, SystemInformationLength, ReturnLength); if(NT_SUCCESS(ret) && SystemInformation) { ULONG pid = (ULONG)(ULONG_PTR)PsGetCurrentProcessId(); if(SystemInformationClass == SystemKernelDebuggerInformation) { if(Hider::IsHidden(pid, HideSystemDebuggerInformation)) { Log("[TITANHIDE] SystemKernelDebuggerInformation by %d\r\n", pid); typedef struct _SYSTEM_KERNEL_DEBUGGER_INFORMATION { BOOLEAN DebuggerEnabled; BOOLEAN DebuggerNotPresent; } SYSTEM_KERNEL_DEBUGGER_INFORMATION, *PSYSTEM_KERNEL_DEBUGGER_INFORMATION; SYSTEM_KERNEL_DEBUGGER_INFORMATION* DebuggerInfo = (SYSTEM_KERNEL_DEBUGGER_INFORMATION*)SystemInformation; __try { BACKUP_RETURNLENGTH(); DebuggerInfo->DebuggerEnabled = false; DebuggerInfo->DebuggerNotPresent = true; RESTORE_RETURNLENGTH(); } __except(EXCEPTION_EXECUTE_HANDLER) { ret = GetExceptionCode(); } } } } return ret; } static NTSTATUS NTAPI HookNtQueryObject( IN HANDLE Handle OPTIONAL, IN OBJECT_INFORMATION_CLASS ObjectInformationClass, OUT PVOID ObjectInformation OPTIONAL, IN ULONG ObjectInformationLength, OUT PULONG ReturnLength OPTIONAL) { NTSTATUS ret = Undocumented::NtQueryObject(Handle, ObjectInformationClass, ObjectInformation, ObjectInformationLength, ReturnLength); if(NT_SUCCESS(ret) && ObjectInformation) { ULONG pid = (ULONG)(ULONG_PTR)PsGetCurrentProcessId(); UNICODE_STRING DebugObject; RtlInitUnicodeString(&DebugObject, L"DebugObject"); if(ObjectInformationClass == ObjectTypeInformation && Hider::IsHidden(pid, HideDebugObject)) { __try { BACKUP_RETURNLENGTH(); OBJECT_TYPE_INFORMATION* type = (OBJECT_TYPE_INFORMATION*)ObjectInformation; ProbeForRead(type->TypeName.Buffer, 1, 1); if(RtlEqualUnicodeString(&type->TypeName, &DebugObject, FALSE)) //DebugObject { Log("[TITANHIDE] DebugObject by %d\r\n", pid); type->TotalNumberOfObjects = 0; type->TotalNumberOfHandles = 0; } RESTORE_RETURNLENGTH(); } __except(EXCEPTION_EXECUTE_HANDLER) { ret = GetExceptionCode(); } } else if(ObjectInformationClass == ObjectTypesInformation && Hider::IsHidden(pid, HideDebugObject)) { //NCC Group Security Advisory __try { BACKUP_RETURNLENGTH(); OBJECT_ALL_INFORMATION* pObjectAllInfo = (OBJECT_ALL_INFORMATION*)ObjectInformation; unsigned char* pObjInfoLocation = (unsigned char*)pObjectAllInfo->ObjectTypeInformation; unsigned int TotalObjects = pObjectAllInfo->NumberOfObjects; for(unsigned int i = 0; i < TotalObjects; i++) { OBJECT_TYPE_INFORMATION* pObjectTypeInfo = (OBJECT_TYPE_INFORMATION*)pObjInfoLocation; ProbeForRead(pObjectTypeInfo, 1, 1); ProbeForRead(pObjectTypeInfo->TypeName.Buffer, 1, 1); if(RtlEqualUnicodeString(&pObjectTypeInfo->TypeName, &DebugObject, FALSE)) //DebugObject { Log("[TITANHIDE] DebugObject by %d\r\n", pid); pObjectTypeInfo->TotalNumberOfObjects = 0; //Bug found by Aguila, thanks! pObjectTypeInfo->TotalNumberOfHandles = 0; } pObjInfoLocation = (unsigned char*)pObjectTypeInfo->TypeName.Buffer; pObjInfoLocation += pObjectTypeInfo->TypeName.MaximumLength; ULONG_PTR tmp = ((ULONG_PTR)pObjInfoLocation) & -(LONG_PTR)sizeof(void*); if((ULONG_PTR)tmp != (ULONG_PTR)pObjInfoLocation) tmp += sizeof(void*); pObjInfoLocation = ((unsigned char*)tmp); } RESTORE_RETURNLENGTH(); } __except(EXCEPTION_EXECUTE_HANDLER) { ret = GetExceptionCode(); } } } return ret; } static NTSTATUS NTAPI HookNtQueryInformationProcess( IN HANDLE ProcessHandle, IN PROCESSINFOCLASS ProcessInformationClass, OUT PVOID ProcessInformation, IN ULONG ProcessInformationLength, OUT PULONG ReturnLength) { NTSTATUS ret = Undocumented::NtQueryInformationProcess(ProcessHandle, ProcessInformationClass, ProcessInformation, ProcessInformationLength, ReturnLength); if(NT_SUCCESS(ret) && ProcessInformation && ProcessInformationClass != ProcessBasicInformation) //prevent stack overflow { ULONG pid = Misc::GetProcessIDFromProcessHandle(ProcessHandle); if(ProcessInformationClass == ProcessDebugFlags) { if(Hider::IsHidden(pid, HideProcessDebugFlags)) { Log("[TITANHIDE] ProcessDebugFlags by %d\r\n", pid); __try { BACKUP_RETURNLENGTH(); *(unsigned int*)ProcessInformation = TRUE; RESTORE_RETURNLENGTH(); } __except(EXCEPTION_EXECUTE_HANDLER) { ret = GetExceptionCode(); } } } else if(ProcessInformationClass == ProcessDebugPort) { if(Hider::IsHidden(pid, HideProcessDebugPort)) { Log("[TITANHIDE] ProcessDebugPort by %d\r\n", pid); __try { BACKUP_RETURNLENGTH(); *(ULONG_PTR*)ProcessInformation = 0; RESTORE_RETURNLENGTH(); } __except(EXCEPTION_EXECUTE_HANDLER) { ret = GetExceptionCode(); } } } else if(ProcessInformationClass == ProcessDebugObjectHandle) { if(Hider::IsHidden(pid, HideProcessDebugObjectHandle)) { Log("[TITANHIDE] ProcessDebugObjectHandle by %d\r\n", pid); HANDLE CantTouchThis = nullptr; __try { __try { // This was a successful request and a valid handle was returned. // That means we should close it and not just nuke it to prevent handle leaks. // Copy the handle to our kernel thread stack first so that VMProte... the nice user application can't mess with it CantTouchThis = *static_cast<PHANDLE>(ProcessInformation); } __except(EXCEPTION_EXECUTE_HANDLER) { NOTHING; // Do nothing; a new exception will follow } // Do not change the order of the following statements ever BACKUP_RETURNLENGTH(); *static_cast<PHANDLE>(ProcessInformation) = nullptr; RESTORE_RETURNLENGTH(); // Taken from : http://newgre.net/idastealth ret = STATUS_PORT_NOT_SET; } __except(EXCEPTION_EXECUTE_HANDLER) { // If an exception occured anywhere, this means the process was manipulating the output buffer on purpose during a write. // Mimic the kernel here and return the exception code it caused by fucking things up for itself, rather than any other status. ret = GetExceptionCode(); } // We passed all of the user mode buffer booby traps; now close the debug object handle. While this handle can't be // messed with *anymore*, that doesn't mean we didn't receive garbage when originally dereferencing it :) So test it first if(CantTouchThis != nullptr) { BOOLEAN AuditOnClose; const NTSTATUS HandleStatus = ObQueryObjectAuditingByHandle(CantTouchThis, &AuditOnClose); if(HandleStatus != STATUS_INVALID_HANDLE) ObCloseHandle(CantTouchThis, KernelMode); } } } } return ret; } static NTSTATUS NTAPI HookNtSetContextThread( IN HANDLE ThreadHandle, IN PCONTEXT Context) { ULONG pid = (ULONG)PsGetCurrentProcessId(); KPROCESSOR_MODE PreviousMode = ExGetPreviousMode(); bool IsHidden = PreviousMode != KernelMode && Hider::IsHidden(pid, HideNtSetContextThread); ULONG OriginalContextFlags = 0; if(IsHidden) { //http://lifeinhex.com/dont-touch-this-writing-good-drivers-is-really-hard //http://lifeinhex.com/when-software-is-good-enough Log("[TITANHIDE] NtSetContextThread by %d\r\n", pid); __try { ProbeForRead(&Context->ContextFlags, sizeof(ULONG), 1); OriginalContextFlags = Context->ContextFlags; ULONG NewContextFlags = OriginalContextFlags & ~0x10; //CONTEXT_DEBUG_REGISTERS ^ CONTEXT_AMD64/CONTEXT_i386 RtlSuperCopyMemory(&Context->ContextFlags, &NewContextFlags, sizeof(ULONG)); } __except(EXCEPTION_EXECUTE_HANDLER) { return Undocumented::NtSetContextThread(ThreadHandle, Context); } } NTSTATUS ret = Undocumented::NtSetContextThread(ThreadHandle, Context); if(IsHidden) { __try { ProbeForRead(&Context->ContextFlags, sizeof(ULONG), 1); RtlSuperCopyMemory(&Context->ContextFlags, &OriginalContextFlags, sizeof(ULONG)); } __except(EXCEPTION_EXECUTE_HANDLER) { } } return ret; } static NTSTATUS NTAPI HookNtSystemDebugControl( IN SYSDBG_COMMAND Command, IN PVOID InputBuffer, IN ULONG InputBufferLength, OUT PVOID OutputBuffer, IN ULONG OutputBufferLength, OUT PULONG ReturnLength) { ULONG pid = (ULONG)(ULONG_PTR)PsGetCurrentProcessId(); if(Hider::IsHidden(pid, HideNtSystemDebugControl)) { Log("[TITANHIDE] NtSystemDebugControl by %d\r\n", pid); if(Command == SysDbgGetTriageDump) return STATUS_INFO_LENGTH_MISMATCH; return STATUS_DEBUGGER_INACTIVE; } return Undocumented::NtSystemDebugControl(Command, InputBuffer, InputBufferLength, OutputBuffer, OutputBufferLength, ReturnLength); } int Hooks::Initialize() { KeInitializeMutex(&gDebugPortMutex, 0); int hook_count = 0; hNtQueryInformationProcess = SSDT::Hook("NtQueryInformationProcess", (void*)HookNtQueryInformationProcess); if(hNtQueryInformationProcess) hook_count++; hNtQueryObject = SSDT::Hook("NtQueryObject", (void*)HookNtQueryObject); if(hNtQueryObject) hook_count++; hNtQuerySystemInformation = SSDT::Hook("NtQuerySystemInformation", (void*)HookNtQuerySystemInformation); if(hNtQuerySystemInformation) hook_count++; hNtSetInformationThread = SSDT::Hook("NtSetInformationThread", (void*)HookNtSetInformationThread); if(hNtSetInformationThread) hook_count++; hNtClose = SSDT::Hook("NtClose", (void*)HookNtClose); if(hNtClose) hook_count++; hNtSetContextThread = SSDT::Hook("NtSetContextThread", (void*)HookNtSetContextThread); if(hNtSetContextThread) hook_count++; hNtSystemDebugControl = SSDT::Hook("NtSystemDebugControl", (void*)HookNtSystemDebugControl); if(hNtSystemDebugControl) hook_count++; return hook_count; } void Hooks::Deinitialize() { SSDT::Unhook(hNtQueryInformationProcess, true); SSDT::Unhook(hNtQueryObject, true); SSDT::Unhook(hNtQuerySystemInformation, true); SSDT::Unhook(hNtSetInformationThread, true); SSDT::Unhook(hNtClose, true); SSDT::Unhook(hNtSetContextThread, true); SSDT::Unhook(hNtSystemDebugControl, true); } <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 2000-2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #include "TraceListenerDefault.hpp" #include <xalanc/PlatformSupport/PrintWriter.hpp> #include <xalanc/DOMSupport/DOMServices.hpp> #include <xalanc/XPath/NodeRefListBase.hpp> #include <xalanc/XPath/XPath.hpp> #include "Constants.hpp" #include "ElemTextLiteral.hpp" #include "ElemTemplate.hpp" #include "GenerateEvent.hpp" #include "SelectionEvent.hpp" #include "StylesheetConstructionContext.hpp" #include "StylesheetRoot.hpp" #include "TracerEvent.hpp" XALAN_CPP_NAMESPACE_BEGIN TraceListenerDefault::TraceListenerDefault( PrintWriter& thePrintWriter, bool traceTemplates, bool traceElements, bool traceGeneration, bool traceSelection) : m_printWriter(thePrintWriter), m_traceTemplates(traceTemplates), m_traceElements(traceElements), m_traceGeneration(traceGeneration), m_traceSelection(traceSelection) { } TraceListenerDefault::~TraceListenerDefault() { } void TraceListenerDefault::trace(const TracerEvent& ev) { switch(ev.m_styleNode.getXSLToken()) { case StylesheetConstructionContext::ELEMNAME_TEXT_LITERAL_RESULT: if(m_traceElements == true) { m_printWriter.print(XALAN_STATIC_UCODE_STRING("Line #")); m_printWriter.print(ev.m_styleNode.getLineNumber()); m_printWriter.print(XALAN_STATIC_UCODE_STRING(", ")); m_printWriter.print(XALAN_STATIC_UCODE_STRING("Column #")); m_printWriter.print(ev.m_styleNode.getColumnNumber()); m_printWriter.print(XALAN_STATIC_UCODE_STRING(": ")); m_printWriter.print(ev.m_styleNode.getElementName()); m_printWriter.print(XALAN_STATIC_UCODE_STRING(" ")); const ElemTextLiteral& etl = #if defined(XALAN_OLD_STYLE_CASTS) (const ElemTextLiteral&)ev.m_styleNode; #else static_cast<const ElemTextLiteral&>(ev.m_styleNode); #endif m_printWriter.println(etl.getText()); } break; case StylesheetConstructionContext::ELEMNAME_TEMPLATE: if(m_traceTemplates == true || m_traceElements == true) { const ElemTemplate& et = #if defined(XALAN_OLD_STYLE_CASTS) (const ElemTemplate&)ev.m_styleNode; #else static_cast<const ElemTemplate&>(ev.m_styleNode); #endif m_printWriter.print(XALAN_STATIC_UCODE_STRING("Line #")); m_printWriter.print(ev.m_styleNode.getLineNumber()); m_printWriter.print(XALAN_STATIC_UCODE_STRING(", ")); m_printWriter.print(XALAN_STATIC_UCODE_STRING("Column #")); m_printWriter.print(ev.m_styleNode.getColumnNumber()); m_printWriter.print(XALAN_STATIC_UCODE_STRING(": ")); m_printWriter.print(ev.m_styleNode.getElementName()); const XPath* const theMatchPattern = et.getMatchPattern(); if(0 != theMatchPattern) { m_printWriter.print(XALAN_STATIC_UCODE_STRING(" match=\"")); m_printWriter.print(theMatchPattern->getExpression().getCurrentPattern()); m_printWriter.print(XALAN_STATIC_UCODE_STRING("\" ")); } const XalanQName& theName = et.getNameAttribute(); if(theName.isEmpty() == false) { m_printWriter.print(XALAN_STATIC_UCODE_STRING("name=\"")); const XalanDOMString& theNamespace = theName.getNamespace(); if (isEmpty(theNamespace) == false) { m_printWriter.print(theNamespace); m_printWriter.print(XalanUnicode::charColon); } m_printWriter.print(theName.getLocalPart()); m_printWriter.print(XALAN_STATIC_UCODE_STRING("\" ")); } m_printWriter.println(); } break; default: if(m_traceElements == true) { m_printWriter.print(XALAN_STATIC_UCODE_STRING("Line #")); m_printWriter.print(ev.m_styleNode.getLineNumber()); m_printWriter.print(XALAN_STATIC_UCODE_STRING(", Column #")); m_printWriter.print(ev.m_styleNode.getColumnNumber()); m_printWriter.print(XALAN_STATIC_UCODE_STRING(": ")); m_printWriter.println(ev.m_styleNode.getElementName()); } break; } } void TraceListenerDefault::processNodeList(const NodeRefListBase& nl) { m_printWriter.println(); const NodeRefListBase::size_type n = nl.getLength(); if(n == 0) { m_printWriter.println(XALAN_STATIC_UCODE_STRING(" [empty node list]")); } else { for(NodeRefListBase::size_type i = 0; i < n; i++) { assert(nl.item(i) != 0); m_printWriter.print(XALAN_STATIC_UCODE_STRING(" ")); m_printWriter.println(DOMServices::getNodeData(*nl.item(i))); } } } void TraceListenerDefault::selected(const SelectionEvent& ev) { if(m_traceSelection == true) { const ElemTemplateElement& ete = ev.m_styleNode; if(ev.m_styleNode.getLineNumber() == 0) { // You may not have line numbers if the selection is occuring from a // default template. ElemTemplateElement* const parent = ete.getParentNodeElem(); if(parent == ete.getStylesheet().getStylesheetRoot().getDefaultRootRule()) { m_printWriter.print("(default root rule) "); } else if(parent == ete.getStylesheet().getStylesheetRoot().getDefaultTextRule()) { m_printWriter.print("(default text rule) "); } else if(parent == ete.getStylesheet().getStylesheetRoot().getDefaultRule()) { m_printWriter.print("(default rule) "); } } else { m_printWriter.print(XALAN_STATIC_UCODE_STRING("Line #")); m_printWriter.print(ev.m_styleNode.getLineNumber()); m_printWriter.print(XALAN_STATIC_UCODE_STRING(", ")); m_printWriter.print(XALAN_STATIC_UCODE_STRING("Column #")); m_printWriter.print(ev.m_styleNode.getColumnNumber()); m_printWriter.print(", "); } m_printWriter.print(ete.getElementName()); m_printWriter.print(XALAN_STATIC_UCODE_STRING(", ")); m_printWriter.print(ev.m_attributeName); m_printWriter.print(XALAN_STATIC_UCODE_STRING("=\"")); m_printWriter.print(ev.m_xpathExpression); m_printWriter.print(XALAN_STATIC_UCODE_STRING("\": ")); if (ev.m_selection.null() == true) { if (ev.m_type == SelectionEvent::eBoolean) { m_printWriter.println(ev.m_boolean == true ? "true" : "false"); } else if (ev.m_type == SelectionEvent::eNodeSet) { assert(ev.m_nodeList != 0); processNodeList(*ev.m_nodeList); } } else if(ev.m_selection->getType() == XObject::eTypeNodeSet) { processNodeList(ev.m_selection->nodeset()); } else { m_printWriter.println(ev.m_selection->str()); } } } void TraceListenerDefault::generated(const GenerateEvent& ev) { if(m_traceGeneration == true) { switch(ev.m_eventType) { case GenerateEvent::EVENTTYPE_STARTDOCUMENT: m_printWriter.println(XALAN_STATIC_UCODE_STRING("STARTDOCUMENT")); break; case GenerateEvent::EVENTTYPE_ENDDOCUMENT: m_printWriter.println(); m_printWriter.println(XALAN_STATIC_UCODE_STRING("ENDDOCUMENT")); break; case GenerateEvent::EVENTTYPE_STARTELEMENT: m_printWriter.print(XALAN_STATIC_UCODE_STRING("STARTELEMENT: ")); m_printWriter.println(ev.m_name); break; case GenerateEvent::EVENTTYPE_ENDELEMENT: m_printWriter.print(XALAN_STATIC_UCODE_STRING("ENDELEMENT: ")); m_printWriter.println(ev.m_name); break; case GenerateEvent::EVENTTYPE_CHARACTERS: m_printWriter.print(XALAN_STATIC_UCODE_STRING("CHARACTERS: ")); m_printWriter.println(ev.m_characters); break; case GenerateEvent::EVENTTYPE_CDATA: m_printWriter.print(XALAN_STATIC_UCODE_STRING("CDATA: ")); m_printWriter.println(ev.m_characters); break; case GenerateEvent::EVENTTYPE_COMMENT: m_printWriter.print(XALAN_STATIC_UCODE_STRING("COMMENT: ")); m_printWriter.println(ev.m_data); break; case GenerateEvent::EVENTTYPE_PI: m_printWriter.print(XALAN_STATIC_UCODE_STRING("PI: ")); m_printWriter.print(ev.m_name); m_printWriter.print(XALAN_STATIC_UCODE_STRING(", ")); m_printWriter.println(ev.m_data); break; case GenerateEvent::EVENTTYPE_ENTITYREF: m_printWriter.println(XALAN_STATIC_UCODE_STRING("ENTITYREF: ")); m_printWriter.println(ev.m_name); break; case GenerateEvent::EVENTTYPE_IGNORABLEWHITESPACE: m_printWriter.println(XALAN_STATIC_UCODE_STRING("IGNORABLEWHITESPACE")); break; } } } XALAN_CPP_NAMESPACE_END <commit_msg>Use proper function call for unknown line/column value. Fixes Bugzilla 22198.<commit_after>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 2000-2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #include "TraceListenerDefault.hpp" #include <xalanc/PlatformSupport/PrintWriter.hpp> #include <xalanc/PlatformSupport/XalanLocator.hpp> #include <xalanc/DOMSupport/DOMServices.hpp> #include <xalanc/XPath/NodeRefListBase.hpp> #include <xalanc/XPath/XPath.hpp> #include "Constants.hpp" #include "ElemTextLiteral.hpp" #include "ElemTemplate.hpp" #include "GenerateEvent.hpp" #include "SelectionEvent.hpp" #include "StylesheetConstructionContext.hpp" #include "StylesheetRoot.hpp" #include "TracerEvent.hpp" XALAN_CPP_NAMESPACE_BEGIN TraceListenerDefault::TraceListenerDefault( PrintWriter& thePrintWriter, bool traceTemplates, bool traceElements, bool traceGeneration, bool traceSelection) : m_printWriter(thePrintWriter), m_traceTemplates(traceTemplates), m_traceElements(traceElements), m_traceGeneration(traceGeneration), m_traceSelection(traceSelection) { } TraceListenerDefault::~TraceListenerDefault() { } void TraceListenerDefault::trace(const TracerEvent& ev) { switch(ev.m_styleNode.getXSLToken()) { case StylesheetConstructionContext::ELEMNAME_TEXT_LITERAL_RESULT: if(m_traceElements == true) { m_printWriter.print(XALAN_STATIC_UCODE_STRING("Line #")); m_printWriter.print(ev.m_styleNode.getLineNumber()); m_printWriter.print(XALAN_STATIC_UCODE_STRING(", ")); m_printWriter.print(XALAN_STATIC_UCODE_STRING("Column #")); m_printWriter.print(ev.m_styleNode.getColumnNumber()); m_printWriter.print(XALAN_STATIC_UCODE_STRING(": ")); m_printWriter.print(ev.m_styleNode.getElementName()); m_printWriter.print(XALAN_STATIC_UCODE_STRING(" ")); const ElemTextLiteral& etl = #if defined(XALAN_OLD_STYLE_CASTS) (const ElemTextLiteral&)ev.m_styleNode; #else static_cast<const ElemTextLiteral&>(ev.m_styleNode); #endif m_printWriter.println(etl.getText()); } break; case StylesheetConstructionContext::ELEMNAME_TEMPLATE: if(m_traceTemplates == true || m_traceElements == true) { const ElemTemplate& et = #if defined(XALAN_OLD_STYLE_CASTS) (const ElemTemplate&)ev.m_styleNode; #else static_cast<const ElemTemplate&>(ev.m_styleNode); #endif m_printWriter.print(XALAN_STATIC_UCODE_STRING("Line #")); m_printWriter.print(ev.m_styleNode.getLineNumber()); m_printWriter.print(XALAN_STATIC_UCODE_STRING(", ")); m_printWriter.print(XALAN_STATIC_UCODE_STRING("Column #")); m_printWriter.print(ev.m_styleNode.getColumnNumber()); m_printWriter.print(XALAN_STATIC_UCODE_STRING(": ")); m_printWriter.print(ev.m_styleNode.getElementName()); const XPath* const theMatchPattern = et.getMatchPattern(); if(0 != theMatchPattern) { m_printWriter.print(XALAN_STATIC_UCODE_STRING(" match=\"")); m_printWriter.print(theMatchPattern->getExpression().getCurrentPattern()); m_printWriter.print(XALAN_STATIC_UCODE_STRING("\" ")); } const XalanQName& theName = et.getNameAttribute(); if(theName.isEmpty() == false) { m_printWriter.print(XALAN_STATIC_UCODE_STRING("name=\"")); const XalanDOMString& theNamespace = theName.getNamespace(); if (isEmpty(theNamespace) == false) { m_printWriter.print(theNamespace); m_printWriter.print(XalanUnicode::charColon); } m_printWriter.print(theName.getLocalPart()); m_printWriter.print(XALAN_STATIC_UCODE_STRING("\" ")); } m_printWriter.println(); } break; default: if(m_traceElements == true) { m_printWriter.print(XALAN_STATIC_UCODE_STRING("Line #")); m_printWriter.print(ev.m_styleNode.getLineNumber()); m_printWriter.print(XALAN_STATIC_UCODE_STRING(", Column #")); m_printWriter.print(ev.m_styleNode.getColumnNumber()); m_printWriter.print(XALAN_STATIC_UCODE_STRING(": ")); m_printWriter.println(ev.m_styleNode.getElementName()); } break; } } void TraceListenerDefault::processNodeList(const NodeRefListBase& nl) { m_printWriter.println(); const NodeRefListBase::size_type n = nl.getLength(); if(n == 0) { m_printWriter.println(XALAN_STATIC_UCODE_STRING(" [empty node list]")); } else { for(NodeRefListBase::size_type i = 0; i < n; i++) { assert(nl.item(i) != 0); m_printWriter.print(XALAN_STATIC_UCODE_STRING(" ")); m_printWriter.println(DOMServices::getNodeData(*nl.item(i))); } } } void TraceListenerDefault::selected(const SelectionEvent& ev) { if(m_traceSelection == true) { const ElemTemplateElement& ete = ev.m_styleNode; if(ev.m_styleNode.getLineNumber() == XalanLocator::getUnknownValue()) { // You may not have line numbers if the selection is occuring from a // default template. ElemTemplateElement* const parent = ete.getParentNodeElem(); if(parent == ete.getStylesheet().getStylesheetRoot().getDefaultRootRule()) { m_printWriter.print("(default root rule) "); } else if(parent == ete.getStylesheet().getStylesheetRoot().getDefaultTextRule()) { m_printWriter.print("(default text rule) "); } else if(parent == ete.getStylesheet().getStylesheetRoot().getDefaultRule()) { m_printWriter.print("(default rule) "); } } else { m_printWriter.print(XALAN_STATIC_UCODE_STRING("Line #")); m_printWriter.print(ev.m_styleNode.getLineNumber()); m_printWriter.print(XALAN_STATIC_UCODE_STRING(", ")); m_printWriter.print(XALAN_STATIC_UCODE_STRING("Column #")); m_printWriter.print(ev.m_styleNode.getColumnNumber()); m_printWriter.print(", "); } m_printWriter.print(ete.getElementName()); m_printWriter.print(XALAN_STATIC_UCODE_STRING(", ")); m_printWriter.print(ev.m_attributeName); m_printWriter.print(XALAN_STATIC_UCODE_STRING("=\"")); m_printWriter.print(ev.m_xpathExpression); m_printWriter.print(XALAN_STATIC_UCODE_STRING("\": ")); if (ev.m_selection.null() == true) { if (ev.m_type == SelectionEvent::eBoolean) { m_printWriter.println(ev.m_boolean == true ? "true" : "false"); } else if (ev.m_type == SelectionEvent::eNodeSet) { assert(ev.m_nodeList != 0); processNodeList(*ev.m_nodeList); } } else if(ev.m_selection->getType() == XObject::eTypeNodeSet) { processNodeList(ev.m_selection->nodeset()); } else { m_printWriter.println(ev.m_selection->str()); } } } void TraceListenerDefault::generated(const GenerateEvent& ev) { if(m_traceGeneration == true) { switch(ev.m_eventType) { case GenerateEvent::EVENTTYPE_STARTDOCUMENT: m_printWriter.println(XALAN_STATIC_UCODE_STRING("STARTDOCUMENT")); break; case GenerateEvent::EVENTTYPE_ENDDOCUMENT: m_printWriter.println(); m_printWriter.println(XALAN_STATIC_UCODE_STRING("ENDDOCUMENT")); break; case GenerateEvent::EVENTTYPE_STARTELEMENT: m_printWriter.print(XALAN_STATIC_UCODE_STRING("STARTELEMENT: ")); m_printWriter.println(ev.m_name); break; case GenerateEvent::EVENTTYPE_ENDELEMENT: m_printWriter.print(XALAN_STATIC_UCODE_STRING("ENDELEMENT: ")); m_printWriter.println(ev.m_name); break; case GenerateEvent::EVENTTYPE_CHARACTERS: m_printWriter.print(XALAN_STATIC_UCODE_STRING("CHARACTERS: ")); m_printWriter.println(ev.m_characters); break; case GenerateEvent::EVENTTYPE_CDATA: m_printWriter.print(XALAN_STATIC_UCODE_STRING("CDATA: ")); m_printWriter.println(ev.m_characters); break; case GenerateEvent::EVENTTYPE_COMMENT: m_printWriter.print(XALAN_STATIC_UCODE_STRING("COMMENT: ")); m_printWriter.println(ev.m_data); break; case GenerateEvent::EVENTTYPE_PI: m_printWriter.print(XALAN_STATIC_UCODE_STRING("PI: ")); m_printWriter.print(ev.m_name); m_printWriter.print(XALAN_STATIC_UCODE_STRING(", ")); m_printWriter.println(ev.m_data); break; case GenerateEvent::EVENTTYPE_ENTITYREF: m_printWriter.println(XALAN_STATIC_UCODE_STRING("ENTITYREF: ")); m_printWriter.println(ev.m_name); break; case GenerateEvent::EVENTTYPE_IGNORABLEWHITESPACE: m_printWriter.println(XALAN_STATIC_UCODE_STRING("IGNORABLEWHITESPACE")); break; } } } XALAN_CPP_NAMESPACE_END <|endoftext|>
<commit_before>#include "inputdevice.h" namespace openalpp { // Static int InputDevice::nobjects_=0; void InputDevice::Init() { if(!nobjects_) { PaError err=Pa_Initialize(); if(err!=paNoError) throw InitError("Error initializing PortAudio"); } nobjects_++; } InputDevice::InputDevice() { Init(); updater_=new DeviceUpdater(-1,44100,10000,Mono16,buffername_,buffer2_->GetName()); } InputDevice::InputDevice(int device,unsigned int samplerate,unsigned int buffersize, SampleFormat format) { Init(); updater_=new DeviceUpdater(device,samplerate,buffersize,format,buffername_,buffer2_->GetName()); } InputDevice::InputDevice(const InputDevice &input) { // TODO: Copy/Reference etc. updater.. } InputDevice &InputDevice::operator=(const InputDevice &input) { if(this!=&input) { // TODO: Delete/DeReference etc. updater.. // TODO: Copy/Reference etc. updater.. } return *this; } InputDevice::~InputDevice() { delete updater_; nobjects_--; if(!nobjects_) Pa_Terminate(); } } <commit_msg>Minor fixes<commit_after>#include "inputdevice.h" namespace openalpp { // Static int InputDevice::nobjects_=0; void InputDevice::Init() { if(!nobjects_) { PaError err=Pa_Initialize(); if(err!=paNoError) throw InitError("Error initializing PortAudio"); } nobjects_++; } InputDevice::InputDevice() { Init(); updater_=new DeviceUpdater(-1,44100,10000,Mono16,buffername_,buffer2_->GetName()); } InputDevice::InputDevice(int device,unsigned int samplerate,unsigned int buffersize, SampleFormat format) { Init(); updater_=new DeviceUpdater(device,samplerate,buffersize,format,buffername_,buffer2_->GetName()); } InputDevice::InputDevice(const InputDevice &input) : Stream((const Stream &)input) { } InputDevice &InputDevice::operator=(const InputDevice &input) { if(this!=&input) { Stream::operator=((const Stream &)input); } return *this; } InputDevice::~InputDevice() { nobjects_--; if(!nobjects_) Pa_Terminate(); } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: ZipPackageStream.cxx,v $ * * $Revision: 1.26 $ * * last change: $Author: mtg $ $Date: 2001-09-24 18:25:30 $ * * 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): Martin Gallwey (gallwey@sun.com) * * ************************************************************************/ #ifndef _ZIP_PACKAGE_STREAM_HXX #include <ZipPackageStream.hxx> #endif #ifndef _ZIP_PACKAGE_HXX #include <ZipPackage.hxx> #endif #ifndef _ZIP_FILE_HXX #include <ZipFile.hxx> #endif #ifndef _VOS_DIAGNOSE_H_ #include <vos/diagnose.hxx> #endif #ifndef _COM_SUN_STAR_PACKAGES_ZIP_ZIPCONSTANTS_HPP_ #include <com/sun/star/packages/zip/ZipConstants.hpp> #endif using namespace com::sun::star::packages::zip::ZipConstants; using namespace com::sun::star::packages::zip; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star; using namespace cppu; using namespace rtl; ZipPackageStream::ZipPackageStream (ZipPackage & rNewPackage ) : rZipPackage(rNewPackage) , bToBeCompressed ( sal_True ) , bToBeEncrypted ( sal_False ) , bPackageMember ( sal_False ) , bHaveOwnKey ( sal_False ) , xEncryptionData ( ) , ZipPackageEntry ( false ) { aEntry.nVersion = -1; aEntry.nFlag = 0; aEntry.nMethod = -1; aEntry.nTime = -1; aEntry.nCrc = -1; aEntry.nCompressedSize = -1; aEntry.nSize = -1; aEntry.nOffset = -1; } ZipPackageStream::~ZipPackageStream( void ) { } void ZipPackageStream::setZipEntry( const ZipEntry &rInEntry) { aEntry.nVersion = rInEntry.nVersion; aEntry.nFlag = rInEntry.nFlag; aEntry.nMethod = rInEntry.nMethod; aEntry.nTime = rInEntry.nTime; aEntry.nCrc = rInEntry.nCrc; aEntry.nCompressedSize = rInEntry.nCompressedSize; aEntry.nSize = rInEntry.nSize; aEntry.nOffset = rInEntry.nOffset; aEntry.sName = rInEntry.sName; } //XInterface Any SAL_CALL ZipPackageStream::queryInterface( const Type& rType ) throw(RuntimeException) { return ( ::cppu::queryInterface ( rType , // OWeakObject interfaces reinterpret_cast< XInterface* > ( this ) , static_cast< XWeak* > ( this ) , // ZipPackageEntry interfaces static_cast< container::XNamed* > ( this ) , static_cast< container::XChild* > ( this ) , static_cast< XUnoTunnel* > ( this ) , // My own interfaces static_cast< io::XActiveDataSink* > ( this ) , static_cast< beans::XPropertySet* > ( this ) ) ); } void SAL_CALL ZipPackageStream::acquire( ) throw() { OWeakObject::acquire(); } void SAL_CALL ZipPackageStream::release( ) throw() { OWeakObject::release(); } // XActiveDataSink void SAL_CALL ZipPackageStream::setInputStream( const Reference< io::XInputStream >& aStream ) throw(RuntimeException) { xStream = aStream; SetPackageMember ( sal_False ); aEntry.nTime = -1; } Reference< io::XInputStream > SAL_CALL ZipPackageStream::getRawStream( ) throw(RuntimeException) { if (IsPackageMember()) { try { if ( !xEncryptionData.isEmpty() && !bHaveOwnKey ) xEncryptionData->aKey = rZipPackage.getEncryptionKey(); return rZipPackage.getZipFile().getRawStream(aEntry, xEncryptionData); } catch (ZipException &)//rException) { VOS_ENSURE( 0, "ZipException thrown");//rException.Message); return Reference < io::XInputStream > (); } } else return xStream; } Reference< io::XInputStream > SAL_CALL ZipPackageStream::getInputStream( ) throw(RuntimeException) { if (IsPackageMember()) { try { if ( !xEncryptionData.isEmpty() && !bHaveOwnKey ) xEncryptionData->aKey = rZipPackage.getEncryptionKey(); return rZipPackage.getZipFile().getInputStream( aEntry, xEncryptionData); } catch (ZipException &)//rException) { VOS_ENSURE( 0,"ZipException thrown");//rException.Message); return Reference < io::XInputStream > (); } } else return xStream; } // XPropertySet Sequence< sal_Int8 > ZipPackageStream::getUnoTunnelImplementationId( void ) throw (RuntimeException) { static ::cppu::OImplementationId * pId = 0; if (! pId) { ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); if (! pId) { static ::cppu::OImplementationId aId; pId = &aId; } } return pId->getImplementationId(); } sal_Int64 SAL_CALL ZipPackageStream::getSomething( const Sequence< sal_Int8 >& aIdentifier ) throw(RuntimeException) { sal_Int64 nMe = 0; if (aIdentifier.getLength() == 16 && ( 0 == rtl_compareMemory(getUnoTunnelImplementationId().getConstArray(), aIdentifier.getConstArray(), 16 ) || 0 == rtl_compareMemory(ZipPackageEntry::getUnoTunnelImplementationId().getConstArray(), aIdentifier.getConstArray(), 16 ) ) ) nMe = reinterpret_cast < sal_Int64 > ( this ); return nMe; } void SAL_CALL ZipPackageStream::setPropertyValue( const OUString& aPropertyName, const Any& aValue ) throw(beans::UnknownPropertyException, beans::PropertyVetoException, IllegalArgumentException, WrappedTargetException, RuntimeException) { if (aPropertyName.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM("MediaType"))) { aValue >>= sMediaType; if (sMediaType.getLength() > 0) { if ( sMediaType.indexOf (OUString( RTL_CONSTASCII_USTRINGPARAM ( "text" ) ) ) != -1) bToBeCompressed = sal_True; else bToBeCompressed = sal_False; } } else if (aPropertyName.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM("Size") ) ) aValue >>= aEntry.nSize; else if (aPropertyName.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM("Encrypted") ) ) { aValue >>= bToBeEncrypted; if ( bToBeEncrypted && xEncryptionData.isEmpty()) xEncryptionData = new EncryptionData; } else if (aPropertyName.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM("EncryptionKey") ) ) { if ( xEncryptionData.isEmpty()) xEncryptionData = new EncryptionData; bHaveOwnKey = bToBeEncrypted = sal_True; if ( !( aValue >>= xEncryptionData->aKey ) ) throw IllegalArgumentException(); } #if SUPD>617 else if (aPropertyName.equalsAsciiL ( RTL_CONSTASCII_STRINGPARAM ( "Compressed" ) ) ) #else else if (aPropertyName.equalsAsciiL ( RTL_CONSTASCII_STRINGPARAM ( "Compress" ) ) ) #endif aValue >>= bToBeCompressed; else throw beans::UnknownPropertyException(); } Any SAL_CALL ZipPackageStream::getPropertyValue( const OUString& PropertyName ) throw(beans::UnknownPropertyException, WrappedTargetException, RuntimeException) { Any aAny; if (PropertyName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "MediaType" ) ) ) { aAny <<= sMediaType; return aAny; } else if (PropertyName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( "Size" ) ) ) { aAny <<= aEntry.nSize; return aAny; } else if (PropertyName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( "Encrypted" ) ) ) { aAny <<= bToBeEncrypted; return aAny; } #if SUPD>617 else if (PropertyName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( "Compressed" ) ) ) #else else if (PropertyName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( "Compress" ) ) ) #endif { aAny <<= bToBeCompressed; return aAny; } else if (PropertyName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "EncryptionKey" ) ) ) { aAny <<= xEncryptionData.isEmpty () ? Sequence < sal_Int8 > () : xEncryptionData->aKey; return aAny; } else throw beans::UnknownPropertyException(); } void ZipPackageStream::setSize (const sal_Int32 nNewSize) { if (aEntry.nCompressedSize != nNewSize ) aEntry.nMethod = DEFLATED; aEntry.nSize = nNewSize; } <commit_msg>#92664# Support XTypeProvider to allow access from Basic<commit_after>/************************************************************************* * * $RCSfile: ZipPackageStream.cxx,v $ * * $Revision: 1.27 $ * * last change: $Author: mtg $ $Date: 2001-10-02 22:27:29 $ * * 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): Martin Gallwey (gallwey@sun.com) * * ************************************************************************/ #ifndef _ZIP_PACKAGE_STREAM_HXX #include <ZipPackageStream.hxx> #endif #ifndef _ZIP_PACKAGE_HXX #include <ZipPackage.hxx> #endif #ifndef _ZIP_FILE_HXX #include <ZipFile.hxx> #endif #ifndef _VOS_DIAGNOSE_H_ #include <vos/diagnose.hxx> #endif #ifndef _COM_SUN_STAR_PACKAGES_ZIP_ZIPCONSTANTS_HPP_ #include <com/sun/star/packages/zip/ZipConstants.hpp> #endif using namespace com::sun::star::packages::zip::ZipConstants; using namespace com::sun::star::packages::zip; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star; using namespace cppu; using namespace rtl; ::cppu::class_data5 ZipPackageStream::s_cd = { 5 +1, sal_False, sal_False, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { { (::cppu::fptr_getCppuType)(::com::sun::star::uno::Type const & (SAL_CALL *)( ::com::sun::star::uno::Reference< ::com::sun::star::io::XActiveDataSink > const * )) &getCppuType, ((sal_Int32)(::com::sun::star::io::XActiveDataSink *) (ZipPackageStream * ) 16) - 16 }, { (::cppu::fptr_getCppuType)(::com::sun::star::uno::Type const & (SAL_CALL *)( ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > const * )) &getCppuType, ((sal_Int32)(::com::sun::star::beans::XPropertySet *) (ZipPackageStream * ) 16) - 16 }, { (::cppu::fptr_getCppuType)(::com::sun::star::uno::Type const & (SAL_CALL *)( ::com::sun::star::uno::Reference< ::com::sun::star::container::XNamed > const * )) &getCppuType, ((sal_Int32)(::com::sun::star::container::XNamed *) (ZipPackageStream * ) 16) - 16 }, { (::cppu::fptr_getCppuType)(::com::sun::star::uno::Type const & (SAL_CALL *)( ::com::sun::star::uno::Reference< ::com::sun::star::container::XChild > const * )) &getCppuType, ((sal_Int32)(::com::sun::star::container::XChild *) (ZipPackageStream * ) 16) - 16 }, { (::cppu::fptr_getCppuType)(::com::sun::star::uno::Type const & (SAL_CALL *)( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XUnoTunnel > const * )) &getCppuType, ((sal_Int32)(::com::sun::star::lang::XUnoTunnel *) (ZipPackageStream * ) 16) - 16 }, { (::cppu::fptr_getCppuType)(::com::sun::star::uno::Type const & (SAL_CALL *)( ::com::sun::star::uno::Reference< ::com::sun::star::lang::XTypeProvider > const * )) &getCppuType, ((sal_Int32)(::com::sun::star::lang::XTypeProvider *) (ZipPackageStream * ) 16) - 16 } } }; ZipPackageStream::ZipPackageStream (ZipPackage & rNewPackage ) : rZipPackage(rNewPackage) , bToBeCompressed ( sal_True ) , bToBeEncrypted ( sal_False ) , bPackageMember ( sal_False ) , bHaveOwnKey ( sal_False ) , xEncryptionData ( ) , ZipPackageEntry ( false ) { aEntry.nVersion = -1; aEntry.nFlag = 0; aEntry.nMethod = -1; aEntry.nTime = -1; aEntry.nCrc = -1; aEntry.nCompressedSize = -1; aEntry.nSize = -1; aEntry.nOffset = -1; } ZipPackageStream::~ZipPackageStream( void ) { } void ZipPackageStream::setZipEntry( const ZipEntry &rInEntry) { aEntry.nVersion = rInEntry.nVersion; aEntry.nFlag = rInEntry.nFlag; aEntry.nMethod = rInEntry.nMethod; aEntry.nTime = rInEntry.nTime; aEntry.nCrc = rInEntry.nCrc; aEntry.nCompressedSize = rInEntry.nCompressedSize; aEntry.nSize = rInEntry.nSize; aEntry.nOffset = rInEntry.nOffset; aEntry.sName = rInEntry.sName; } // XActiveDataSink void SAL_CALL ZipPackageStream::setInputStream( const Reference< io::XInputStream >& aStream ) throw(RuntimeException) { xStream = aStream; SetPackageMember ( sal_False ); aEntry.nTime = -1; } Reference< io::XInputStream > SAL_CALL ZipPackageStream::getRawStream( ) throw(RuntimeException) { if (IsPackageMember()) { try { if ( !xEncryptionData.isEmpty() && !bHaveOwnKey ) xEncryptionData->aKey = rZipPackage.getEncryptionKey(); return rZipPackage.getZipFile().getRawStream(aEntry, xEncryptionData); } catch (ZipException &)//rException) { VOS_ENSURE( 0, "ZipException thrown");//rException.Message); return Reference < io::XInputStream > (); } } else return xStream; } Reference< io::XInputStream > SAL_CALL ZipPackageStream::getInputStream( ) throw(RuntimeException) { if (IsPackageMember()) { try { if ( !xEncryptionData.isEmpty() && !bHaveOwnKey ) xEncryptionData->aKey = rZipPackage.getEncryptionKey(); return rZipPackage.getZipFile().getInputStream( aEntry, xEncryptionData); } catch (ZipException &)//rException) { VOS_ENSURE( 0,"ZipException thrown");//rException.Message); return Reference < io::XInputStream > (); } } else return xStream; } sal_Int64 SAL_CALL ZipPackageStream::getSomething( const Sequence< sal_Int8 >& aIdentifier ) throw(RuntimeException) { sal_Int64 nMe = 0; if ( aIdentifier.getLength() == 16 && 0 == rtl_compareMemory(getUnoTunnelImplementationId().getConstArray(), aIdentifier.getConstArray(), 16 ) ) nMe = reinterpret_cast < sal_Int64 > ( this ); return nMe; } // XPropertySet void SAL_CALL ZipPackageStream::setPropertyValue( const OUString& aPropertyName, const Any& aValue ) throw(beans::UnknownPropertyException, beans::PropertyVetoException, IllegalArgumentException, WrappedTargetException, RuntimeException) { if (aPropertyName.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM("MediaType"))) { aValue >>= sMediaType; if (sMediaType.getLength() > 0) { if ( sMediaType.indexOf (OUString( RTL_CONSTASCII_USTRINGPARAM ( "text" ) ) ) != -1) bToBeCompressed = sal_True; else bToBeCompressed = sal_False; } } else if (aPropertyName.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM("Size") ) ) aValue >>= aEntry.nSize; else if (aPropertyName.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM("Encrypted") ) ) { aValue >>= bToBeEncrypted; if ( bToBeEncrypted && xEncryptionData.isEmpty()) xEncryptionData = new EncryptionData; } else if (aPropertyName.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM("EncryptionKey") ) ) { if ( xEncryptionData.isEmpty()) xEncryptionData = new EncryptionData; bHaveOwnKey = bToBeEncrypted = sal_True; if ( !( aValue >>= xEncryptionData->aKey ) ) throw IllegalArgumentException(); } #if SUPD>617 else if (aPropertyName.equalsAsciiL ( RTL_CONSTASCII_STRINGPARAM ( "Compressed" ) ) ) #else else if (aPropertyName.equalsAsciiL ( RTL_CONSTASCII_STRINGPARAM ( "Compress" ) ) ) #endif aValue >>= bToBeCompressed; else throw beans::UnknownPropertyException(); } Any SAL_CALL ZipPackageStream::getPropertyValue( const OUString& PropertyName ) throw(beans::UnknownPropertyException, WrappedTargetException, RuntimeException) { Any aAny; if (PropertyName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "MediaType" ) ) ) { aAny <<= sMediaType; return aAny; } else if (PropertyName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( "Size" ) ) ) { aAny <<= aEntry.nSize; return aAny; } else if (PropertyName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( "Encrypted" ) ) ) { aAny <<= bToBeEncrypted; return aAny; } #if SUPD>617 else if (PropertyName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( "Compressed" ) ) ) #else else if (PropertyName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( "Compress" ) ) ) #endif { aAny <<= bToBeCompressed; return aAny; } else if (PropertyName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( "EncryptionKey" ) ) ) { aAny <<= xEncryptionData.isEmpty () ? Sequence < sal_Int8 > () : xEncryptionData->aKey; return aAny; } else throw beans::UnknownPropertyException(); } void ZipPackageStream::setSize (const sal_Int32 nNewSize) { if (aEntry.nCompressedSize != nNewSize ) aEntry.nMethod = DEFLATED; aEntry.nSize = nNewSize; } <|endoftext|>
<commit_before>/* * SchemeAdHoc.c * * Scheme adhoc callback into opencog * * Copyright (c) 2008 Linas Vepstas <linas@linas.org> */ #ifdef HAVE_GUILE #include <libguile.h> #include <opencog/server/CogServer.h> #include <opencog/nlp/question/SentenceQuery.h> #include <opencog/nlp/question/TripleQuery.h> #include <opencog/nlp/wsd/WordSenseProcessor.h> #include <opencog/query/PatternMatch.h> #include <opencog/reasoning/pln/PLNModule.h> #include "SchemeSmob.h" using namespace opencog; /* ============================================================== */ /** * Dispatcher to invoke various miscellaneous C++ riff-raff from * scheme code. */ SCM SchemeSmob::ss_ad_hoc(SCM command, SCM optargs) { std::string cmdname = decode_string (command, "cog-ad-hoc", "string command name"); if (0 == cmdname.compare("do-wsd")) { WordSenseProcessor wsp; wsp.use_threads(false); wsp.run_no_delay(&cogserver()); // XXX What an ugly interface. Alas. return SCM_BOOL_T; } // Run implication, assuming that the argument is a handle to // an ImplicationLink. XXX DEPRECATED: Use varscope below! if (0 == cmdname.compare("do-implication")) { // XXX we should also allow opt-args to be a list of handles Handle h = verify_handle(optargs, "cog-ad-hoc do-implication"); AtomSpace *as = &atomspace(); PatternMatch pm; pm.set_atomspace(as); Handle grounded_expressions = pm.crisp_logic_imply(h); return handle_to_scm(grounded_expressions); } // Run implication, assuming that the argument is a handle to // an VarScopeLink containing variables and an ImplicationLink if (0 == cmdname.compare("do-varscope")) { // XXX we should also allow opt-args to be a list of handles Handle h = verify_handle(optargs, "cog-ad-hoc do-implication"); AtomSpace *as = &atomspace(); PatternMatch pm; pm.set_atomspace(as); Handle grounded_expressions = pm.varscope(h); return handle_to_scm(grounded_expressions); } // Store the single atom to the backing store hanging off the atom-space if (0 == cmdname.compare("store-atom")) { // XXX we should also allow opt-args to be a list of handles Handle h = verify_handle(optargs, "cog-ad-hoc store-atom"); AtomSpace *as = &atomspace(); as->storeAtom(h); return SCM_BOOL_T; } if (0 == cmdname.compare("fetch-atom")) { // XXX we should also allow opt-args to be a list of handles Handle h = verify_handle(optargs, "cog-ad-hoc fetch-atom"); AtomSpace *as = &atomspace(); h = as->fetchAtom(h); return handle_to_scm(h); } if (0 == cmdname.compare("fetch-incoming-set")) { // XXX we should also allow opt-args to be a list of handles Handle h = verify_handle(optargs, "cog-ad-hoc fetch-incoming-set"); // The "true" flag here means "fetch resursive". AtomSpace *as = &atomspace(); h = as->fetchIncomingSet(h, true); return handle_to_scm(h); } if (0 == cmdname.compare("question")) { Handle h = verify_handle(optargs, "cog-ad-hoc question"); AtomSpace *as = &atomspace(); SentenceQuery rlx; if (rlx.is_query(h)) { rlx.solve(as, h); return SCM_BOOL_T; } return SCM_BOOL_F; #if EXAMPLE_FRAME_QUERY_API FrameQuery frq; if (frq.is_query(h)) { frq.solve(as, h); } #endif return handle_to_scm(h); } return SCM_BOOL_F; } /* ============================================================== */ /** * Specify the target Atom for PLN backward chaining inference. * Creates a new BIT for that Atom. * Runs ssteps steps of searching through the BIT. * Currently you can also use the cogserver commands on the resulting * BIT. */ SCM SchemeSmob::pln_bc (SCM starget, SCM ssteps) { Handle h = verify_handle(starget, "pln-bc"); int steps = scm_to_int(ssteps); Atom *a = TLB::getAtom(h); // We need to make a copy. Wish I could do this on stack ... TruthValue *t = a->getTruthValue().clone(); opencog::pln::infer(h, steps, true); // Return true only if the truth value changed, // else return false. SCM rc = SCM_BOOL_T; if (*t == a->getTruthValue()) rc = SCM_BOOL_F; delete t; return rc; } #endif /* ===================== END OF FILE ============================ */ <commit_msg>whops -- remove the deleted header file too<commit_after>/* * SchemeAdHoc.c * * Scheme adhoc callback into opencog * * Copyright (c) 2008 Linas Vepstas <linas@linas.org> */ #ifdef HAVE_GUILE #include <libguile.h> #include <opencog/server/CogServer.h> #include <opencog/nlp/question/SentenceQuery.h> #include <opencog/nlp/wsd/WordSenseProcessor.h> #include <opencog/query/PatternMatch.h> #include <opencog/reasoning/pln/PLNModule.h> #include "SchemeSmob.h" using namespace opencog; /* ============================================================== */ /** * Dispatcher to invoke various miscellaneous C++ riff-raff from * scheme code. */ SCM SchemeSmob::ss_ad_hoc(SCM command, SCM optargs) { std::string cmdname = decode_string (command, "cog-ad-hoc", "string command name"); if (0 == cmdname.compare("do-wsd")) { WordSenseProcessor wsp; wsp.use_threads(false); wsp.run_no_delay(&cogserver()); // XXX What an ugly interface. Alas. return SCM_BOOL_T; } // Run implication, assuming that the argument is a handle to // an ImplicationLink. XXX DEPRECATED: Use varscope below! if (0 == cmdname.compare("do-implication")) { // XXX we should also allow opt-args to be a list of handles Handle h = verify_handle(optargs, "cog-ad-hoc do-implication"); AtomSpace *as = &atomspace(); PatternMatch pm; pm.set_atomspace(as); Handle grounded_expressions = pm.crisp_logic_imply(h); return handle_to_scm(grounded_expressions); } // Run implication, assuming that the argument is a handle to // an VarScopeLink containing variables and an ImplicationLink if (0 == cmdname.compare("do-varscope")) { // XXX we should also allow opt-args to be a list of handles Handle h = verify_handle(optargs, "cog-ad-hoc do-implication"); AtomSpace *as = &atomspace(); PatternMatch pm; pm.set_atomspace(as); Handle grounded_expressions = pm.varscope(h); return handle_to_scm(grounded_expressions); } // Store the single atom to the backing store hanging off the atom-space if (0 == cmdname.compare("store-atom")) { // XXX we should also allow opt-args to be a list of handles Handle h = verify_handle(optargs, "cog-ad-hoc store-atom"); AtomSpace *as = &atomspace(); as->storeAtom(h); return SCM_BOOL_T; } if (0 == cmdname.compare("fetch-atom")) { // XXX we should also allow opt-args to be a list of handles Handle h = verify_handle(optargs, "cog-ad-hoc fetch-atom"); AtomSpace *as = &atomspace(); h = as->fetchAtom(h); return handle_to_scm(h); } if (0 == cmdname.compare("fetch-incoming-set")) { // XXX we should also allow opt-args to be a list of handles Handle h = verify_handle(optargs, "cog-ad-hoc fetch-incoming-set"); // The "true" flag here means "fetch resursive". AtomSpace *as = &atomspace(); h = as->fetchIncomingSet(h, true); return handle_to_scm(h); } if (0 == cmdname.compare("question")) { Handle h = verify_handle(optargs, "cog-ad-hoc question"); AtomSpace *as = &atomspace(); SentenceQuery rlx; if (rlx.is_query(h)) { rlx.solve(as, h); return SCM_BOOL_T; } return SCM_BOOL_F; #if EXAMPLE_FRAME_QUERY_API FrameQuery frq; if (frq.is_query(h)) { frq.solve(as, h); } #endif return handle_to_scm(h); } return SCM_BOOL_F; } /* ============================================================== */ /** * Specify the target Atom for PLN backward chaining inference. * Creates a new BIT for that Atom. * Runs ssteps steps of searching through the BIT. * Currently you can also use the cogserver commands on the resulting * BIT. */ SCM SchemeSmob::pln_bc (SCM starget, SCM ssteps) { Handle h = verify_handle(starget, "pln-bc"); int steps = scm_to_int(ssteps); Atom *a = TLB::getAtom(h); // We need to make a copy. Wish I could do this on stack ... TruthValue *t = a->getTruthValue().clone(); opencog::pln::infer(h, steps, true); // Return true only if the truth value changed, // else return false. SCM rc = SCM_BOOL_T; if (*t == a->getTruthValue()) rc = SCM_BOOL_F; delete t; return rc; } #endif /* ===================== END OF FILE ============================ */ <|endoftext|>
<commit_before>/* Kopete , The KDE Instant Messenger Copyright (c) 2001-2002 by Duncan Mac-Vicar Prett <duncan@kde.org> Viva Chile Mierda! Started at Wed Dec 26 03:12:10 CLST 2001, Santiago de Chile Kopete (c) 2002 by the Kopete developers <kopete-devel@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; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include <kcmdlineargs.h> #include <kaboutdata.h> #include <klocale.h> #include "kopete.h" #include <dcopclient.h> #include "kopeteiface.h" static const char *description = I18N_NOOP("Kopete, the KDE Instant Messenger"); #define KOPETE_VERSION "0.5.8cvs >= 20021020" static KCmdLineOptions options[] = { { "noplugins", I18N_NOOP("Do not load plugins"), 0 }, { "disable <plugin>", I18N_NOOP("Do not load specified plugin"), 0 }, { "!+[plugin]", I18N_NOOP("Load specified plugins"), 0 }, { 0, 0, 0 } }; int main(int argc, char *argv[]) { KAboutData aboutData( "kopete", I18N_NOOP("Kopete"), KOPETE_VERSION, description, KAboutData::License_GPL, I18N_NOOP("(c) 2001,2002, Duncan Mac-Vicar Prett\n(c) 2002, The Kopete Development Team"), "kopete-devel@kde.org", "http://kopete.kde.org"); aboutData.addAuthor ( "Duncan Mac-Vicar Prett", I18N_NOOP("Original author, core developer"), "duncan@kde.org", "http://www.mac-vicar.com" ); aboutData.addAuthor ( "Nick Betcher", I18N_NOOP("Core developer, fastest plugin developer on earth."), "nbetcher@kde.org", "http://www.kdedevelopers.net" ); aboutData.addAuthor ( "Ryan Cumming", I18N_NOOP("Core developer"), "ryan@kde.org" ); aboutData.addAuthor ( "Martijn Klingens", I18N_NOOP("Core developer"), "klingens@kde.org" ); aboutData.addAuthor ( "Richard Stellingwerff", I18N_NOOP("Developer"), "remenic@linuxfromscratch.org"); aboutData.addAuthor ( "Daniel Stone", I18N_NOOP("Core developer, Jabber plugin"), "dstone@kde.org", "http://raging.dropbear.id.au/daniel/"); aboutData.addAuthor ( "Till Gerken", I18N_NOOP("Core developer, Jabber plugin"), "till@tantalo.net"); aboutData.addAuthor ( "Olivier Goffart", I18N_NOOP("Core developer"), "ogoffart@tiscalinet.be"); aboutData.addAuthor ( "Hendrik vom Lehn", I18N_NOOP("Developer"), "hennevl@hennevl.de", "http://www.hennevl.de"); aboutData.addAuthor ( "Stefan Gehn", I18N_NOOP("Developer"), "metz@gehn.net", "http://metz.gehn.net" ); aboutData.addAuthor ( "Andres Krapf", I18N_NOOP("Developer"), "dae@chez.com" ); aboutData.addAuthor ( "Gav Wood", I18N_NOOP("Winpopup plugin"), "gjw102@york.ac.uk" ); aboutData.addAuthor ( "Zack Rusin", I18N_NOOP("Core developer, Gadu plugin"), "zack@kde.org" ); aboutData.addAuthor ( "Carsten Pfeiffer", I18N_NOOP("Misc Bugfixes and Enhancelets"), "pfeiffer@kde.org" ); aboutData.addAuthor ( "Chris TenHarmsel", I18N_NOOP("Developer"), "tenharmsel@users.sourceforge.net", "http://bemis.kicks-ass.net"); aboutData.addCredit ( "Luciash d' Being", I18N_NOOP("Icon Author") ); aboutData.addCredit ( "Vladimir Shutoff", I18N_NOOP("SIM icq library") ); aboutData.addCredit ( "Herwin Jan Steehouwer", I18N_NOOP("KxEngine icq code") ); aboutData.addCredit ( "Olaf Lueg", I18N_NOOP("Kmerlin MSN code") ); aboutData.addCredit ( "Neil Stevens", I18N_NOOP("TAim engine AIM code") ); aboutData.addCredit ( "Justin Karneges", I18N_NOOP("Psi Jabber code") ); aboutData.addCredit ( "Steve Cable", I18N_NOOP("Sounds") ); KCmdLineArgs::init( argc, argv, &aboutData ); KCmdLineArgs::addCmdLineOptions( options ); // Add our own options. KUniqueApplication::addCmdLineOptions(); Kopete kopete; kapp->dcopClient()->setDefaultObject( (new KopeteIface())->objId() ); // Has to be called before exec kopete.exec(); } /* * Local variables: * c-indentation-style: k&r * c-basic-offset: 8 * indent-tabs-mode: t * End: */ // vim: set noet ts=4 sts=4 sw=4: <commit_msg>Mention plugin<commit_after>/* Kopete , The KDE Instant Messenger Copyright (c) 2001-2002 by Duncan Mac-Vicar Prett <duncan@kde.org> Viva Chile Mierda! Started at Wed Dec 26 03:12:10 CLST 2001, Santiago de Chile Kopete (c) 2002 by the Kopete developers <kopete-devel@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; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include <kcmdlineargs.h> #include <kaboutdata.h> #include <klocale.h> #include "kopete.h" #include <dcopclient.h> #include "kopeteiface.h" static const char *description = I18N_NOOP("Kopete, the KDE Instant Messenger"); #define KOPETE_VERSION "0.5.8cvs >= 20021020" static KCmdLineOptions options[] = { { "noplugins", I18N_NOOP("Do not load plugins"), 0 }, { "disable <plugin>", I18N_NOOP("Do not load specified plugin"), 0 }, { "!+[plugin]", I18N_NOOP("Load specified plugins"), 0 }, { 0, 0, 0 } }; int main(int argc, char *argv[]) { KAboutData aboutData( "kopete", I18N_NOOP("Kopete"), KOPETE_VERSION, description, KAboutData::License_GPL, I18N_NOOP("(c) 2001,2002, Duncan Mac-Vicar Prett\n(c) 2002, The Kopete Development Team"), "kopete-devel@kde.org", "http://kopete.kde.org"); aboutData.addAuthor ( "Duncan Mac-Vicar Prett", I18N_NOOP("Original author, core developer"), "duncan@kde.org", "http://www.mac-vicar.com" ); aboutData.addAuthor ( "Nick Betcher", I18N_NOOP("Core developer, fastest plugin developer on earth."), "nbetcher@kde.org", "http://www.kdedevelopers.net" ); aboutData.addAuthor ( "Ryan Cumming", I18N_NOOP("Core developer"), "ryan@kde.org" ); aboutData.addAuthor ( "Martijn Klingens", I18N_NOOP("Core developer"), "klingens@kde.org" ); aboutData.addAuthor ( "Richard Stellingwerff", I18N_NOOP("Developer"), "remenic@linuxfromscratch.org"); aboutData.addAuthor ( "Daniel Stone", I18N_NOOP("Core developer, Jabber plugin"), "dstone@kde.org", "http://raging.dropbear.id.au/daniel/"); aboutData.addAuthor ( "Till Gerken", I18N_NOOP("Core developer, Jabber plugin"), "till@tantalo.net"); aboutData.addAuthor ( "Olivier Goffart", I18N_NOOP("Core developer"), "ogoffart@tiscalinet.be"); aboutData.addAuthor ( "Hendrik vom Lehn", I18N_NOOP("Developer"), "hennevl@hennevl.de", "http://www.hennevl.de"); aboutData.addAuthor ( "Stefan Gehn", I18N_NOOP("Developer"), "metz@gehn.net", "http://metz.gehn.net" ); aboutData.addAuthor ( "Andres Krapf", I18N_NOOP("Developer"), "dae@chez.com" ); aboutData.addAuthor ( "Gav Wood", I18N_NOOP("Winpopup plugin"), "gjw102@york.ac.uk" ); aboutData.addAuthor ( "Zack Rusin", I18N_NOOP("Core developer, Gadu plugin"), "zack@kde.org" ); aboutData.addAuthor ( "Carsten Pfeiffer", I18N_NOOP("Misc Bugfixes and Enhancelets"), "pfeiffer@kde.org" ); aboutData.addAuthor ( "Chris TenHarmsel", I18N_NOOP("Developer"), "tenharmsel@users.sourceforge.net", "http://bemis.kicks-ass.net"); aboutData.addAuthor ( "Chris Howells", I18N_NOOP("Connection status plugin author"), "howells@kde.org", "http://chrishowells.co.uk"); aboutData.addCredit ( "Luciash d' Being", I18N_NOOP("Icon Author") ); aboutData.addCredit ( "Vladimir Shutoff", I18N_NOOP("SIM icq library") ); aboutData.addCredit ( "Herwin Jan Steehouwer", I18N_NOOP("KxEngine icq code") ); aboutData.addCredit ( "Olaf Lueg", I18N_NOOP("Kmerlin MSN code") ); aboutData.addCredit ( "Neil Stevens", I18N_NOOP("TAim engine AIM code") ); aboutData.addCredit ( "Justin Karneges", I18N_NOOP("Psi Jabber code") ); aboutData.addCredit ( "Steve Cable", I18N_NOOP("Sounds") ); KCmdLineArgs::init( argc, argv, &aboutData ); KCmdLineArgs::addCmdLineOptions( options ); // Add our own options. KUniqueApplication::addCmdLineOptions(); Kopete kopete; kapp->dcopClient()->setDefaultObject( (new KopeteIface())->objId() ); // Has to be called before exec kopete.exec(); } /* * Local variables: * c-indentation-style: k&r * c-basic-offset: 8 * indent-tabs-mode: t * End: */ // vim: set noet ts=4 sts=4 sw=4: <|endoftext|>
<commit_before>/* * Listener on a TCP port. * * author: Max Kellermann <mk@cm4all.com> */ #include "ServerSocket.hxx" #include "SocketDescriptor.hxx" #include "SocketAddress.hxx" #include "StaticSocketAddress.hxx" #include "fd_util.h" #include "pool.hxx" #include "util/Error.hxx" #include <socket/util.h> #include <socket/address.h> #include <assert.h> #include <stddef.h> #include <sys/socket.h> #include <sys/un.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <stdio.h> #include <errno.h> #include <unistd.h> #include <string.h> #include <fcntl.h> inline void ServerSocket::Callback() { StaticSocketAddress remote_address; Error error; auto remote_fd = fd.Accept(remote_address, error); if (!remote_fd.IsDefined()) { if (!error.IsDomain(errno_domain) || (error.GetCode() != EAGAIN && error.GetCode() != EWOULDBLOCK)) OnAcceptError(std::move(error)); return; } if (!socket_set_nodelay(remote_fd.Get(), true)) { error.SetErrno("setsockopt(TCP_NODELAY) failed"); OnAcceptError(std::move(error)); return; } OnAccept(std::move(remote_fd), remote_address); } void ServerSocket::Callback(gcc_unused int fd, gcc_unused short event, void *ctx) { ServerSocket &ss = *(ServerSocket *)ctx; ss.Callback(); pool_commit(); } bool ServerSocket::Listen(int family, int socktype, int protocol, SocketAddress address, Error &error) { if (address.GetFamily() == AF_UNIX) { const struct sockaddr_un *sun = (const struct sockaddr_un *)(const struct sockaddr *)address; if (sun->sun_path[0] != '\0') /* delete non-abstract socket files before reusing them */ unlink(sun->sun_path); } if (!fd.CreateListen(family, socktype, protocol, address, error)) return nullptr; event_set(&event, fd.Get(), EV_READ|EV_PERSIST, Callback, this); AddEvent(); return true; } bool ServerSocket::ListenTCP(unsigned port, Error &error) { assert(port > 0); struct sockaddr_in6 sa6; struct sockaddr_in sa4; memset(&sa6, 0, sizeof(sa6)); sa6.sin6_family = AF_INET6; sa6.sin6_addr = in6addr_any; sa6.sin6_port = htons(port); memset(&sa4, 0, sizeof(sa4)); sa4.sin_family = AF_INET; sa4.sin_addr.s_addr = INADDR_ANY; sa4.sin_port = htons(port); return Listen(PF_INET6, SOCK_STREAM, 0, SocketAddress((const struct sockaddr *)&sa6, sizeof(sa6)), IgnoreError()) || Listen(PF_INET, SOCK_STREAM, 0, SocketAddress((const struct sockaddr *)&sa4, sizeof(sa4)), error); } bool ServerSocket::ListenPath(const char *path, Error &error) { unlink(path); StaticSocketAddress address; address.SetLocal(path); return Listen(AF_LOCAL, SOCK_STREAM, 0, address, error); } ServerSocket::~ServerSocket() { event_del(&event); } <commit_msg>net/ServerSocket: set TCP_NODELAY only for TCP sockets<commit_after>/* * Listener on a TCP port. * * author: Max Kellermann <mk@cm4all.com> */ #include "ServerSocket.hxx" #include "SocketDescriptor.hxx" #include "SocketAddress.hxx" #include "StaticSocketAddress.hxx" #include "fd_util.h" #include "pool.hxx" #include "util/Error.hxx" #include <socket/util.h> #include <socket/address.h> #include <assert.h> #include <stddef.h> #include <sys/socket.h> #include <sys/un.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <stdio.h> #include <errno.h> #include <unistd.h> #include <string.h> #include <fcntl.h> static bool IsTCP(SocketAddress address) { return address.GetFamily() == AF_INET || address.GetFamily() == AF_INET6; } inline void ServerSocket::Callback() { StaticSocketAddress remote_address; Error error; auto remote_fd = fd.Accept(remote_address, error); if (!remote_fd.IsDefined()) { if (!error.IsDomain(errno_domain) || (error.GetCode() != EAGAIN && error.GetCode() != EWOULDBLOCK)) OnAcceptError(std::move(error)); return; } if (IsTCP(remote_address) && !socket_set_nodelay(remote_fd.Get(), true)) { error.SetErrno("setsockopt(TCP_NODELAY) failed"); OnAcceptError(std::move(error)); return; } OnAccept(std::move(remote_fd), remote_address); } void ServerSocket::Callback(gcc_unused int fd, gcc_unused short event, void *ctx) { ServerSocket &ss = *(ServerSocket *)ctx; ss.Callback(); pool_commit(); } bool ServerSocket::Listen(int family, int socktype, int protocol, SocketAddress address, Error &error) { if (address.GetFamily() == AF_UNIX) { const struct sockaddr_un *sun = (const struct sockaddr_un *)(const struct sockaddr *)address; if (sun->sun_path[0] != '\0') /* delete non-abstract socket files before reusing them */ unlink(sun->sun_path); } if (!fd.CreateListen(family, socktype, protocol, address, error)) return nullptr; event_set(&event, fd.Get(), EV_READ|EV_PERSIST, Callback, this); AddEvent(); return true; } bool ServerSocket::ListenTCP(unsigned port, Error &error) { assert(port > 0); struct sockaddr_in6 sa6; struct sockaddr_in sa4; memset(&sa6, 0, sizeof(sa6)); sa6.sin6_family = AF_INET6; sa6.sin6_addr = in6addr_any; sa6.sin6_port = htons(port); memset(&sa4, 0, sizeof(sa4)); sa4.sin_family = AF_INET; sa4.sin_addr.s_addr = INADDR_ANY; sa4.sin_port = htons(port); return Listen(PF_INET6, SOCK_STREAM, 0, SocketAddress((const struct sockaddr *)&sa6, sizeof(sa6)), IgnoreError()) || Listen(PF_INET, SOCK_STREAM, 0, SocketAddress((const struct sockaddr *)&sa4, sizeof(sa4)), error); } bool ServerSocket::ListenPath(const char *path, Error &error) { unlink(path); StaticSocketAddress address; address.SetLocal(path); return Listen(AF_LOCAL, SOCK_STREAM, 0, address, error); } ServerSocket::~ServerSocket() { event_del(&event); } <|endoftext|>
<commit_before>#include "net/http_request.h" namespace loftili { namespace net { HttpRequest::HttpRequest(const loftili::net::Url& url) : m_url(url), m_method("GET") { } HttpRequest::HttpRequest(const loftili::net::Url& url, std::string method) : m_url(url), m_method(method) { } HttpRequest::HttpRequest(const loftili::net::Url& url, std::string method, std::string body) : m_url(url), m_method(method), m_body(body) { } HttpRequest::operator std::string() { std::stringstream req_str; req_str << m_method << " " << m_url.Path() << " HTTP/1.1\n"; req_str << "Host: " << m_url.Host() << "\n"; req_str << "Content-Length: " << m_body.size() << "\n"; for(auto it : m_headers) { req_str << std::get<0>(it) << ": " << std::get<1>(it) << "\n"; } req_str << "X-Powered-By: loftili core"; req_str << "\r\n\r\n"; req_str << m_body; return req_str.str(); } int HttpRequest::Header(std::string key, std::string val) { m_headers.push_back(std::make_pair(key, val)); return m_headers.size(); } } } <commit_msg>[LFTCE-23] avoiding auto type in http_request header iteration<commit_after>#include "net/http_request.h" namespace loftili { namespace net { HttpRequest::HttpRequest(const loftili::net::Url& url) : m_url(url), m_method("GET") { } HttpRequest::HttpRequest(const loftili::net::Url& url, std::string method) : m_url(url), m_method(method) { } HttpRequest::HttpRequest(const loftili::net::Url& url, std::string method, std::string body) : m_url(url), m_method(method), m_body(body) { } HttpRequest::operator std::string() { std::stringstream req_str; req_str << m_method << " " << m_url.Path() << " HTTP/1.1\n"; req_str << "Host: " << m_url.Host() << "\n"; req_str << "Content-Length: " << m_body.size() << "\n"; typedef std::pair<std::string, std::string> header_pairs; std::vector<header_pairs>::iterator it = m_headers.begin(); for(; it != m_headers.end(); ++it) { req_str << std::get<0>(*it) << ": " << std::get<1>(*it) << "\n"; } req_str << "X-Powered-By: loftili core"; req_str << "\r\n\r\n"; req_str << m_body; return req_str.str(); } int HttpRequest::Header(std::string key, std::string val) { m_headers.push_back(std::make_pair(key, val)); return m_headers.size(); } } } <|endoftext|>
<commit_before>/*////////////////////////////////////////////////////////////////// //// SKIRT -- an advanced radiative transfer code //// //// © Astronomical Observatory, Ghent University //// ///////////////////////////////////////////////////////////////// */ #ifndef OLIGOFITSCHEME_HPP #define OLIGOFITSCHEME_HPP #include "AdjustableSkirtSimulation.hpp" #include "FitScheme.hpp" class ParameterRanges; class ReferenceImages; class Optimization; //////////////////////////////////////////////////////////////////// /** OligoFitScheme represents a complete FitSKIRT fit scheme for oligochromatic fits/simulations. It contains the SKIRT simulation, parameter ranges, reference images and the optimization type.*/ class OligoFitScheme : public FitScheme { Q_OBJECT Q_CLASSINFO("Title", "an oligochromatic fit scheme") Q_CLASSINFO("Property", "simulation") Q_CLASSINFO("Title", "the SKIRT simulation to be run for this fit scheme") Q_CLASSINFO("Property", "fixedSeed") Q_CLASSINFO("Title", "Do you want a fixed seed (only for testing purposes)") Q_CLASSINFO("Default", "no") Q_CLASSINFO("Property", "parameterRanges") Q_CLASSINFO("Title", "the parameter ranges") Q_CLASSINFO("Property", "referenceImages") Q_CLASSINFO("Title", "the refence images") Q_CLASSINFO("Property", "optim") Q_CLASSINFO("Title", "the optimization properties") //======== Construction - Setup - Run - Destruction =========== public: /** The default constructor. */ Q_INVOKABLE OligoFitScheme(); protected: /** This function actually runs the fit scheme. It assumes that setup() has been already performed. */ void runSelf(); //======== Setters & Getters for Discoverable Attributes ======= public: /** Sets the SKIRT simulation to be run for this fit scheme. */ Q_INVOKABLE void setSimulation(AdjustableSkirtSimulation* value); /** Returns the SKIRT simulation to be run for this fit scheme. */ Q_INVOKABLE AdjustableSkirtSimulation* simulation() const; /** Sets the boolean value whether to use a fixed seed or not. */ Q_INVOKABLE void setFixedSeed(bool value); /** Returns the boolean value whether to use a fixed seed or not. */ Q_INVOKABLE bool fixedSeed() const; /** Sets the parameterranges for this fit scheme. */ Q_INVOKABLE void setParameterRanges(ParameterRanges* value); /** This function returns the list of parameter ranges in the fit scheme. */ Q_INVOKABLE ParameterRanges* parameterRanges() const; /** Sets the reference images for this fit scheme. */ Q_INVOKABLE void setReferenceImages(ReferenceImages* value); /** This function returns the reference images in this fit scheme. */ Q_INVOKABLE ReferenceImages* referenceImages() const; /** Sets the optimization properties for this fit scheme. */ Q_INVOKABLE void setOptim(Optimization* value); /** This function returns the optimization properties in this fit scheme. */ Q_INVOKABLE Optimization* optim() const; //======================== Other Functions ======================= /** This function is used by the Optimization object. It requires a ReplacementDict for the AdjustableSkirtSimulation and returns the total \f$\chi^2\f$ value together with lists of the best fitting luminosities, the separate \f$\chi^2\f$ values and the masked simulations. */ double objective(AdjustableSkirtSimulation::ReplacementDict replacement, QList<QList<double>> *luminosities, QList<double> *Chis, int index); //======================== Data Members ======================== protected: // data members AdjustableSkirtSimulation* _simulation; bool _fixedSeed; ParameterRanges* _ranges; ReferenceImages* _rimages; Optimization* _optim; }; //////////////////////////////////////////////////////////////////// #endif // OLIGOFITSCHEME_HPP <commit_msg>Corrected a typo in the FitSKIRT Q&A.<commit_after>/*////////////////////////////////////////////////////////////////// //// SKIRT -- an advanced radiative transfer code //// //// © Astronomical Observatory, Ghent University //// ///////////////////////////////////////////////////////////////// */ #ifndef OLIGOFITSCHEME_HPP #define OLIGOFITSCHEME_HPP #include "AdjustableSkirtSimulation.hpp" #include "FitScheme.hpp" class ParameterRanges; class ReferenceImages; class Optimization; //////////////////////////////////////////////////////////////////// /** OligoFitScheme represents a complete FitSKIRT fit scheme for oligochromatic fits/simulations. It contains the SKIRT simulation, parameter ranges, reference images and the optimization type.*/ class OligoFitScheme : public FitScheme { Q_OBJECT Q_CLASSINFO("Title", "an oligochromatic fit scheme") Q_CLASSINFO("Property", "simulation") Q_CLASSINFO("Title", "the SKIRT simulation to be run for this fit scheme") Q_CLASSINFO("Property", "fixedSeed") Q_CLASSINFO("Title", "have a fixed seed (only for testing purposes)") Q_CLASSINFO("Default", "no") Q_CLASSINFO("Property", "parameterRanges") Q_CLASSINFO("Title", "the parameter ranges") Q_CLASSINFO("Property", "referenceImages") Q_CLASSINFO("Title", "the refence images") Q_CLASSINFO("Property", "optim") Q_CLASSINFO("Title", "the optimization properties") //======== Construction - Setup - Run - Destruction =========== public: /** The default constructor. */ Q_INVOKABLE OligoFitScheme(); protected: /** This function actually runs the fit scheme. It assumes that setup() has been already performed. */ void runSelf(); //======== Setters & Getters for Discoverable Attributes ======= public: /** Sets the SKIRT simulation to be run for this fit scheme. */ Q_INVOKABLE void setSimulation(AdjustableSkirtSimulation* value); /** Returns the SKIRT simulation to be run for this fit scheme. */ Q_INVOKABLE AdjustableSkirtSimulation* simulation() const; /** Sets the boolean value whether to use a fixed seed or not. */ Q_INVOKABLE void setFixedSeed(bool value); /** Returns the boolean value whether to use a fixed seed or not. */ Q_INVOKABLE bool fixedSeed() const; /** Sets the parameterranges for this fit scheme. */ Q_INVOKABLE void setParameterRanges(ParameterRanges* value); /** This function returns the list of parameter ranges in the fit scheme. */ Q_INVOKABLE ParameterRanges* parameterRanges() const; /** Sets the reference images for this fit scheme. */ Q_INVOKABLE void setReferenceImages(ReferenceImages* value); /** This function returns the reference images in this fit scheme. */ Q_INVOKABLE ReferenceImages* referenceImages() const; /** Sets the optimization properties for this fit scheme. */ Q_INVOKABLE void setOptim(Optimization* value); /** This function returns the optimization properties in this fit scheme. */ Q_INVOKABLE Optimization* optim() const; //======================== Other Functions ======================= /** This function is used by the Optimization object. It requires a ReplacementDict for the AdjustableSkirtSimulation and returns the total \f$\chi^2\f$ value together with lists of the best fitting luminosities, the separate \f$\chi^2\f$ values and the masked simulations. */ double objective(AdjustableSkirtSimulation::ReplacementDict replacement, QList<QList<double>> *luminosities, QList<double> *Chis, int index); //======================== Data Members ======================== protected: // data members AdjustableSkirtSimulation* _simulation; bool _fixedSeed; ParameterRanges* _ranges; ReferenceImages* _rimages; Optimization* _optim; }; //////////////////////////////////////////////////////////////////// #endif // OLIGOFITSCHEME_HPP <|endoftext|>
<commit_before>/* -*- mode: C++; c-file-style: "gnu" -*- partnodebodypart.cpp This file is part of KMail, the KDE mail client. Copyright (c) 2004 Marc Mutz <mutz@kde.org>, Ingo Kloecker <kloecker@kde.org> KMail 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. KMail 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 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 "partnodebodypart.h" #include "nodehelper.h" #include <kurl.h> #include <kmime/kmime_content.h> #include <KDebug> #include <QString> #include <QTextCodec> using namespace Message; static int serial = 0; PartNodeBodyPart::PartNodeBodyPart( KMime::Content *content, const QTextCodec * codec ) : Interface::BodyPart(), mContent( content ), mCodec( codec ), mDefaultDisplay( Interface::BodyPart::None ) {} QString PartNodeBodyPart::makeLink( const QString & path ) const { // FIXME: use a PRNG for the first arg, instead of a serial number return QString( "x-kmail:/bodypart/%1/%2/%3" ) .arg( serial++ ).arg( mContent->index().toString() ) .arg( QString::fromLatin1( KUrl::toPercentEncoding( path, "/" ) ) ); } QString PartNodeBodyPart::asText() const { if ( !mContent->contentType()->isText() ) return QString(); return mCodec->toUnicode( mContent->decodedContent() ); } QByteArray PartNodeBodyPart::asBinary() const { return mContent->decodedContent(); } QString PartNodeBodyPart::contentTypeParameter( const char * param ) const { return mContent->contentType()->parameter( param ); } QString PartNodeBodyPart::contentDescription() const { return mContent->contentDescription()->asUnicodeString(); } QString PartNodeBodyPart::contentDispositionParameter( const char * param ) const { return mContent->contentDisposition()->parameter( param ); return QString(); } bool PartNodeBodyPart::hasCompleteBody() const { kWarning() << "Sorry, not yet implemented."; return true; } Interface::BodyPartMemento * PartNodeBodyPart::memento() const { /*TODO(Andras) Volker suggests to use a ContentIndex->Mememnto mapping Also review if the reader's bodyPartMemento should be returned or the NodeHelper's one */ return NodeHelper::instance()->bodyPartMemento( mContent, "__plugin__" ); } void PartNodeBodyPart::setBodyPartMemento( Interface::BodyPartMemento * memento ) { /*TODO(Andras) Volker suggests to use a ContentIndex->Memento mapping Also review if the reader's bodyPartMemento should be set or the NodeHelper's one */ NodeHelper::instance()->setBodyPartMemento( mContent, "__plugin__" , memento ); } Interface::BodyPart::Display PartNodeBodyPart::defaultDisplay() const { return mDefaultDisplay; } void PartNodeBodyPart::setDefaultDisplay( Interface::BodyPart::Display d ){ mDefaultDisplay = d; } <commit_msg>Minor fix<commit_after>/* -*- mode: C++; c-file-style: "gnu" -*- partnodebodypart.cpp This file is part of KMail, the KDE mail client. Copyright (c) 2004 Marc Mutz <mutz@kde.org>, Ingo Kloecker <kloecker@kde.org> KMail 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. KMail 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 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 "partnodebodypart.h" #include "nodehelper.h" #include <kurl.h> #include <kmime/kmime_content.h> #include <KDebug> #include <QString> #include <QTextCodec> using namespace Message; static int serial = 0; PartNodeBodyPart::PartNodeBodyPart( KMime::Content *content, const QTextCodec * codec ) : Interface::BodyPart(), mContent( content ), mCodec( codec ), mDefaultDisplay( Interface::BodyPart::None ) {} QString PartNodeBodyPart::makeLink( const QString & path ) const { // FIXME: use a PRNG for the first arg, instead of a serial number return QString( "x-kmail:/bodypart/%1/%2/%3" ) .arg( serial++ ).arg( mContent->index().toString() ) .arg( QString::fromLatin1( KUrl::toPercentEncoding( path, "/" ) ) ); } QString PartNodeBodyPart::asText() const { if ( !mContent->contentType()->isText() ) return QString(); return mCodec->toUnicode( mContent->decodedContent() ); } QByteArray PartNodeBodyPart::asBinary() const { return mContent->decodedContent(); } QString PartNodeBodyPart::contentTypeParameter( const char * param ) const { return mContent->contentType()->parameter( param ); } QString PartNodeBodyPart::contentDescription() const { return mContent->contentDescription()->asUnicodeString(); } QString PartNodeBodyPart::contentDispositionParameter( const char * param ) const { return mContent->contentDisposition()->parameter( param ); } bool PartNodeBodyPart::hasCompleteBody() const { kWarning() << "Sorry, not yet implemented."; return true; } Interface::BodyPartMemento * PartNodeBodyPart::memento() const { /*TODO(Andras) Volker suggests to use a ContentIndex->Mememnto mapping Also review if the reader's bodyPartMemento should be returned or the NodeHelper's one */ return NodeHelper::instance()->bodyPartMemento( mContent, "__plugin__" ); } void PartNodeBodyPart::setBodyPartMemento( Interface::BodyPartMemento * memento ) { /*TODO(Andras) Volker suggests to use a ContentIndex->Memento mapping Also review if the reader's bodyPartMemento should be set or the NodeHelper's one */ NodeHelper::instance()->setBodyPartMemento( mContent, "__plugin__" , memento ); } Interface::BodyPart::Display PartNodeBodyPart::defaultDisplay() const { return mDefaultDisplay; } void PartNodeBodyPart::setDefaultDisplay( Interface::BodyPart::Display d ){ mDefaultDisplay = d; } <|endoftext|>
<commit_before>/* * The MIT License (MIT) * * Copyright (c) 2015 Microsoft Corporation * * -=- Robust Distributed System Nucleus (rDSN) -=- * * 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. */ # ifdef __linux__ # include "hpc_network_provider.h" # include "mix_all_io_looper.h" # include <netinet/tcp.h> # ifdef __TITLE__ # undef __TITLE__ # endif # define __TITLE__ "network.provider.hpc" namespace dsn { namespace tools { static socket_t create_tcp_socket(sockaddr_in* addr) { socket_t s = -1; if ((s = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP)) == -1) { dwarn("socket failed, err = %s", strerror(errno)); return -1; } int nodelay = 1; if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (char*)&nodelay, sizeof(int)) != 0) { dwarn("setsockopt TCP_NODELAY failed, err = %s", strerror(errno)); } //int isopt = 1; //if (setsockopt(s, SOL_SOCKET, SO_DONTLINGER, (char*)&isopt, sizeof(int)) != 0) //{ // dwarn("setsockopt SO_DONTLINGER failed, err = %s", strerror(errno)); //} int buflen = 8 * 1024 * 1024; if (setsockopt(s, SOL_SOCKET, SO_RCVBUF, (char*)&buflen, sizeof(buflen)) != 0) { dwarn("setsockopt SO_RCVBUF failed, err = %s", strerror(errno)); } int keepalive = 0; if (setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (char*)&keepalive, sizeof(keepalive)) != 0) { dwarn("setsockopt SO_KEEPALIVE failed, err = %s", strerror(errno)); } if (addr != 0) { if (bind(s, (struct sockaddr*)addr, sizeof(*addr)) != 0) { derror("bind failed, err = %s", strerror(errno)); close(s); return -1; } } return s; } hpc_network_provider::hpc_network_provider(rpc_engine* srv, network* inner_provider) : connection_oriented_network(srv, inner_provider) { _listen_fd = -1; _looper = get_io_looper(node()); } error_code hpc_network_provider::start(rpc_channel channel, int port, bool client_only) { if (_listen_fd != -1) return ERR_SERVICE_ALREADY_RUNNING; dassert(channel == RPC_CHANNEL_TCP || channel == RPC_CHANNEL_UDP, "invalid given channel %s", channel.to_string()); gethostname(_address.name, sizeof(_address.name)); dsn_address_build(&_address, _address.name, port); if (!client_only) { struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_addr.s_addr = INADDR_ANY; addr.sin_port = htons(port); _listen_fd = create_tcp_socket(&addr); if (_listen_fd == -1) { dassert(false, ""); } int forcereuse = 1; if (setsockopt(_listen_fd, SOL_SOCKET, SO_REUSEADDR, (char*)&forcereuse, sizeof(forcereuse)) != 0) { dwarn("setsockopt SO_REUSEDADDR failed, err = %s", strerror(errno)); } _accept_event.callback = [this](int err, uint32_t size, uintptr_t lpolp) { this->do_accept(); }; get_looper()->bind_io_handle((dsn_handle_t)_listen_fd, &_accept_event.callback, EPOLLIN | EPOLLOUT | EPOLLHUP | EPOLLRDHUP | EPOLLET); if (listen(_listen_fd, SOMAXCONN) != 0) { dwarn("listen failed, err = %s", strerror(errno)); return ERR_NETWORK_START_FAILED; } } return ERR_OK; } rpc_client_session_ptr hpc_network_provider::create_client_session(const dsn_address_t& server_addr) { auto matcher = new_client_matcher(); auto parser = new_message_parser(); struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_addr.s_addr = INADDR_ANY; addr.sin_port = 0; auto sock = create_tcp_socket(&addr); auto client = new hpc_rpc_client_session(sock, parser, *this, server_addr, matcher); client->bind_looper(get_looper()); return client; } void hpc_network_provider::do_accept() { struct sockaddr_in local_addr; socklen_t len = (socklen_t)sizeof(local_addr); socket_t s = accept(_listen_fd, (struct sockaddr*)&local_addr, &len); if (s != -1) { struct sockaddr_in addr; memset((void*)&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = INADDR_ANY; addr.sin_port = 0; socklen_t addr_len = (socklen_t)sizeof(addr); if (getpeername(s, (struct sockaddr*)&addr, &addr_len) == -1) { dassert(false, "getpeername failed, err = %s", strerror(errno)); } dsn_address_t client_addr; dsn_address_build_ipv4(&client_addr, ntohl(addr.sin_addr.s_addr), ntohs(addr.sin_port)); auto parser = new_message_parser(); auto rs = new hpc_rpc_server_session(s, parser, *this, client_addr); rs->bind_looper(get_looper()); rpc_server_session_ptr s1(rs); this->on_server_session_accepted(s1); } else { derror("accept failed, err = %s", strerror(errno)); } } hpc_rpc_session::hpc_rpc_session( socket_t sock, std::shared_ptr<dsn::message_parser>& parser ) : _socket(sock), _parser(parser) { _sending_msg = nullptr; _sending_next_offset = 0; memset((void*)&_peer_addr, 0, sizeof(_peer_addr)); _peer_addr.sin_family = AF_INET; _peer_addr.sin_addr.s_addr = INADDR_ANY; _peer_addr.sin_port = 0; _ready_event = [this](int err, uint32_t length, uintptr_t lolp_or_events) { uint32_t events = (uint32_t)lolp_or_events; if (events & EPOLLIN) { do_read(); } if (events & EPOLLOUT) { if (_sending_msg) { do_write(_sending_msg); } else { on_write_completed(nullptr); // send next msg if there is. } } if ((events & EPOLLHUP) || (events & EPOLLRDHUP)) { on_failure(); } }; } void hpc_rpc_session::bind_looper(io_looper* looper) { looper->bind_io_handle((dsn_handle_t)_socket, &_ready_event, EPOLLIN | EPOLLOUT | EPOLLHUP | EPOLLRDHUP | EPOLLET); } void hpc_rpc_session::do_read(int read_next) { while (true) { char* ptr = (char*)_parser->read_buffer_ptr((int)read_next); int remaining = _parser->read_buffer_capacity(); int sz = recv(_socket, ptr, remaining, 0); if (sz > 0) { message_ex* msg = _parser->get_message_on_receive(sz, read_next); while (msg != nullptr) { this->on_read_completed(msg); msg = _parser->get_message_on_receive(0, read_next); } } else { int err = errno; if (err != EAGAIN && err != EWOULDBLOCK) { derror("recv failed, err = %s", strerror(err)); on_failure(); } break; } } } void hpc_rpc_session::do_write(message_ex* msg) { static_assert (sizeof(dsn_message_parser::send_buf) == sizeof(struct iovec), "make sure they are compatible"); // new msg if (_sending_msg != msg) { dassert(_sending_msg == nullptr, "only one sending msg is possible"); _sending_msg = msg; _sending_next_offset = 0; } // continue old msg else { // nothing to do } // prepare send buffer, make sure header is already in the buffer int total_length = 0; int buffer_count = _parser->get_send_buffers_count_and_total_length(msg, &total_length); auto buffers = (dsn_message_parser::send_buf*)alloca(buffer_count * sizeof(dsn_message_parser::send_buf)); int count = _parser->prepare_buffers_on_send(msg, _sending_next_offset, buffers); struct msghdr hdr; memset((void*)&hdr, 0, sizeof(hdr)); hdr.msg_name = (void*)&_peer_addr; hdr.msg_namelen = (socklen_t)sizeof(_peer_addr); hdr.msg_iov = (struct iovec*)buffers; hdr.msg_iovlen = (size_t)count; int sz = sendmsg(_socket, &hdr, MSG_NOSIGNAL); if (sz > 0) { _sending_next_offset += sz; // message completed, continue next message if (_sending_next_offset == total_length) { msg = _sending_msg; _sending_msg = nullptr; on_write_completed(msg); return; } } else { int err = errno; if (err == EAGAIN || err == EWOULDBLOCK) { // wait for next ready } else { derror("sendmsg failed, err = %s", strerror(err)); on_failure(); } } } void hpc_rpc_session::close() { ::close(_socket); on_closed(); } hpc_rpc_client_session::hpc_rpc_client_session( socket_t sock, std::shared_ptr<dsn::message_parser>& parser, connection_oriented_network& net, const dsn_address_t& remote_addr, rpc_client_matcher_ptr& matcher ) : rpc_client_session(net, remote_addr, matcher), hpc_rpc_session(sock, parser) { _reconnect_count = 0; _state = SS_CLOSED; } void hpc_rpc_client_session::on_failure() { _state = SS_CLOSED; if (++_reconnect_count > 3) { close(); on_disconnected(); return; } connect(); } void hpc_rpc_client_session::connect() { session_state closed_state = SS_CLOSED; if (!_state.compare_exchange_strong(closed_state, SS_CONNECTING)) return; struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(_remote_addr.ip); addr.sin_port = htons(_remote_addr.port); int rt = ::connect(_socket, (struct sockaddr*)&addr, (int)sizeof(addr)); if (rt == -1) { dwarn("connect failed, err = %s", strerror(errno)); on_failure(); } else { socklen_t addr_len = (socklen_t)sizeof(_peer_addr); if (getpeername(_socket, (struct sockaddr*)&_peer_addr, &addr_len) == -1) { dassert(false, "getpeername failed, err = %s", strerror(errno)); } // looper is already bound, so nothing to do } } hpc_rpc_server_session::hpc_rpc_server_session( socket_t sock, std::shared_ptr<dsn::message_parser>& parser, connection_oriented_network& net, const dsn_address_t& remote_addr ) : rpc_server_session(net, remote_addr), hpc_rpc_session(sock, parser) { socklen_t addr_len = (socklen_t)sizeof(_peer_addr); if (getpeername(_socket, (struct sockaddr*)&_peer_addr, &addr_len) == -1) { dassert(false, "getpeername failed, err = %s", strerror(errno)); } do_read(); } } } # endif <commit_msg>looper bind must be after listen so accept call happen after listen<commit_after>/* * The MIT License (MIT) * * Copyright (c) 2015 Microsoft Corporation * * -=- Robust Distributed System Nucleus (rDSN) -=- * * 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. */ # ifdef __linux__ # include "hpc_network_provider.h" # include "mix_all_io_looper.h" # include <netinet/tcp.h> # ifdef __TITLE__ # undef __TITLE__ # endif # define __TITLE__ "network.provider.hpc" namespace dsn { namespace tools { static socket_t create_tcp_socket(sockaddr_in* addr) { socket_t s = -1; if ((s = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP)) == -1) { dwarn("socket failed, err = %s", strerror(errno)); return -1; } int nodelay = 1; if (setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (char*)&nodelay, sizeof(int)) != 0) { dwarn("setsockopt TCP_NODELAY failed, err = %s", strerror(errno)); } //int isopt = 1; //if (setsockopt(s, SOL_SOCKET, SO_DONTLINGER, (char*)&isopt, sizeof(int)) != 0) //{ // dwarn("setsockopt SO_DONTLINGER failed, err = %s", strerror(errno)); //} int buflen = 8 * 1024 * 1024; if (setsockopt(s, SOL_SOCKET, SO_RCVBUF, (char*)&buflen, sizeof(buflen)) != 0) { dwarn("setsockopt SO_RCVBUF failed, err = %s", strerror(errno)); } int keepalive = 0; if (setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (char*)&keepalive, sizeof(keepalive)) != 0) { dwarn("setsockopt SO_KEEPALIVE failed, err = %s", strerror(errno)); } if (addr != 0) { if (bind(s, (struct sockaddr*)addr, sizeof(*addr)) != 0) { derror("bind failed, err = %s", strerror(errno)); close(s); return -1; } } return s; } hpc_network_provider::hpc_network_provider(rpc_engine* srv, network* inner_provider) : connection_oriented_network(srv, inner_provider) { _listen_fd = -1; _looper = get_io_looper(node()); } error_code hpc_network_provider::start(rpc_channel channel, int port, bool client_only) { if (_listen_fd != -1) return ERR_SERVICE_ALREADY_RUNNING; dassert(channel == RPC_CHANNEL_TCP || channel == RPC_CHANNEL_UDP, "invalid given channel %s", channel.to_string()); gethostname(_address.name, sizeof(_address.name)); dsn_address_build(&_address, _address.name, port); if (!client_only) { struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_addr.s_addr = INADDR_ANY; addr.sin_port = htons(port); _listen_fd = create_tcp_socket(&addr); if (_listen_fd == -1) { dassert(false, "cannot create listen socket"); } int forcereuse = 1; if (setsockopt(_listen_fd, SOL_SOCKET, SO_REUSEADDR, (char*)&forcereuse, sizeof(forcereuse)) != 0) { dwarn("setsockopt SO_REUSEDADDR failed, err = %s", strerror(errno)); } if (listen(_listen_fd, SOMAXCONN) != 0) { dwarn("listen failed, err = %s", strerror(errno)); return ERR_NETWORK_START_FAILED; } _accept_event.callback = [this](int err, uint32_t size, uintptr_t lpolp) { this->do_accept(); }; get_looper()->bind_io_handle((dsn_handle_t)_listen_fd, &_accept_event.callback, EPOLLIN | EPOLLET); } return ERR_OK; } rpc_client_session_ptr hpc_network_provider::create_client_session(const dsn_address_t& server_addr) { auto matcher = new_client_matcher(); auto parser = new_message_parser(); struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_addr.s_addr = INADDR_ANY; addr.sin_port = 0; auto sock = create_tcp_socket(&addr); auto client = new hpc_rpc_client_session(sock, parser, *this, server_addr, matcher); client->bind_looper(get_looper()); return client; } void hpc_network_provider::do_accept() { struct sockaddr_in addr; socklen_t addr_len = (socklen_t)sizeof(addr); socket_t s = ::accept(_listen_fd, (struct sockaddr*)&addr, &addr_len); if (s != -1) { dsn_address_t client_addr; dsn_address_build_ipv4(&client_addr, ntohl(addr.sin_addr.s_addr), ntohs(addr.sin_port)); auto parser = new_message_parser(); auto rs = new hpc_rpc_server_session(s, parser, *this, client_addr); rs->bind_looper(get_looper()); rpc_server_session_ptr s1(rs); this->on_server_session_accepted(s1); } else { derror("accept failed, err = %s", strerror(errno)); } } hpc_rpc_session::hpc_rpc_session( socket_t sock, std::shared_ptr<dsn::message_parser>& parser ) : _socket(sock), _parser(parser) { _sending_msg = nullptr; _sending_next_offset = 0; memset((void*)&_peer_addr, 0, sizeof(_peer_addr)); _peer_addr.sin_family = AF_INET; _peer_addr.sin_addr.s_addr = INADDR_ANY; _peer_addr.sin_port = 0; _ready_event = [this](int err, uint32_t length, uintptr_t lolp_or_events) { uint32_t events = (uint32_t)lolp_or_events; if (events & EPOLLIN) { do_read(); } if (events & EPOLLOUT) { if (_sending_msg) { do_write(_sending_msg); } else { on_write_completed(nullptr); // send next msg if there is. } } if ((events & EPOLLHUP) || (events & EPOLLRDHUP)) { on_failure(); } }; } void hpc_rpc_session::bind_looper(io_looper* looper) { looper->bind_io_handle((dsn_handle_t)_socket, &_ready_event, EPOLLIN | EPOLLOUT | EPOLLHUP | EPOLLRDHUP | EPOLLET); } void hpc_rpc_session::do_read(int read_next) { while (true) { char* ptr = (char*)_parser->read_buffer_ptr((int)read_next); int remaining = _parser->read_buffer_capacity(); int sz = recv(_socket, ptr, remaining, 0); if (sz > 0) { message_ex* msg = _parser->get_message_on_receive(sz, read_next); while (msg != nullptr) { this->on_read_completed(msg); msg = _parser->get_message_on_receive(0, read_next); } } else { int err = errno; if (err != EAGAIN && err != EWOULDBLOCK) { derror("recv failed, err = %s", strerror(err)); on_failure(); } break; } } } void hpc_rpc_session::do_write(message_ex* msg) { static_assert (sizeof(dsn_message_parser::send_buf) == sizeof(struct iovec), "make sure they are compatible"); // new msg if (_sending_msg != msg) { dassert(_sending_msg == nullptr, "only one sending msg is possible"); _sending_msg = msg; _sending_next_offset = 0; } // continue old msg else { // nothing to do } // prepare send buffer, make sure header is already in the buffer int total_length = 0; int buffer_count = _parser->get_send_buffers_count_and_total_length(msg, &total_length); auto buffers = (dsn_message_parser::send_buf*)alloca(buffer_count * sizeof(dsn_message_parser::send_buf)); int count = _parser->prepare_buffers_on_send(msg, _sending_next_offset, buffers); struct msghdr hdr; memset((void*)&hdr, 0, sizeof(hdr)); hdr.msg_name = (void*)&_peer_addr; hdr.msg_namelen = (socklen_t)sizeof(_peer_addr); hdr.msg_iov = (struct iovec*)buffers; hdr.msg_iovlen = (size_t)count; int sz = sendmsg(_socket, &hdr, MSG_NOSIGNAL); if (sz > 0) { _sending_next_offset += sz; // message completed, continue next message if (_sending_next_offset == total_length) { msg = _sending_msg; _sending_msg = nullptr; on_write_completed(msg); return; } } else { int err = errno; if (err == EAGAIN || err == EWOULDBLOCK) { // wait for next ready } else { derror("sendmsg failed, err = %s", strerror(err)); on_failure(); } } } void hpc_rpc_session::close() { ::close(_socket); on_closed(); } hpc_rpc_client_session::hpc_rpc_client_session( socket_t sock, std::shared_ptr<dsn::message_parser>& parser, connection_oriented_network& net, const dsn_address_t& remote_addr, rpc_client_matcher_ptr& matcher ) : rpc_client_session(net, remote_addr, matcher), hpc_rpc_session(sock, parser) { _reconnect_count = 0; _state = SS_CLOSED; } void hpc_rpc_client_session::on_failure() { _state = SS_CLOSED; if (++_reconnect_count > 3) { close(); on_disconnected(); return; } connect(); } void hpc_rpc_client_session::connect() { session_state closed_state = SS_CLOSED; if (!_state.compare_exchange_strong(closed_state, SS_CONNECTING)) return; struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(_remote_addr.ip); addr.sin_port = htons(_remote_addr.port); int rt = ::connect(_socket, (struct sockaddr*)&addr, (int)sizeof(addr)); if (rt == -1) { dwarn("connect failed, err = %s", strerror(errno)); on_failure(); } else { socklen_t addr_len = (socklen_t)sizeof(_peer_addr); if (getpeername(_socket, (struct sockaddr*)&_peer_addr, &addr_len) == -1) { dassert(false, "getpeername failed, err = %s", strerror(errno)); } // looper is already bound, so nothing to do } } hpc_rpc_server_session::hpc_rpc_server_session( socket_t sock, std::shared_ptr<dsn::message_parser>& parser, connection_oriented_network& net, const dsn_address_t& remote_addr ) : rpc_server_session(net, remote_addr), hpc_rpc_session(sock, parser) { socklen_t addr_len = (socklen_t)sizeof(_peer_addr); if (getpeername(_socket, (struct sockaddr*)&_peer_addr, &addr_len) == -1) { dassert(false, "getpeername failed, err = %s", strerror(errno)); } do_read(); } } } # endif <|endoftext|>
<commit_before>/* * (c) Copyright Ascensio System SIA 2010-2019 * * This program is a free software product. You can redistribute it and/or * modify it under the terms of the GNU Affero General Public License (AGPL) * version 3 as published by the Free Software Foundation. In accordance with * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect * that Ascensio System SIA expressly excludes the warranty of non-infringement * of any third-party rights. * * This program is distributed WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html * * You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha * street, Riga, Latvia, EU, LV-1050. * * The interactive user interfaces in modified source and object code versions * of the Program must display Appropriate Legal Notices, as required under * Section 5 of the GNU AGPL version 3. * * Pursuant to Section 7(b) of the License you must retain the original Product * logo when distributing the program. Pursuant to Section 7(e) we decline to * grant you any rights under trademark law for use of our trademarks. * * All the Product's GUI elements, including illustrations and icon sets, as * well as technical writing content are licensed under the terms of the * Creative Commons Attribution-ShareAlike 4.0 International. See the License * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode * */ #include "FooterMapping.h" #include "TableMapping.h" namespace DocFileFormat { FooterMapping::FooterMapping (ConversionContext* ctx, CharacterRange ftr) : DocumentMapping(ctx, this), _ftr(ftr) { } void FooterMapping::Apply( IVisitable* visited ) { m_document = static_cast<WordDocument*>( visited ); //start the document m_pXmlWriter->WriteNodeBegin( L"?xml version=\"1.0\" encoding=\"UTF-8\"?" ); m_pXmlWriter->WriteNodeBegin( L"w:ftr", TRUE ); //write namespaces m_pXmlWriter->WriteAttribute( L"xmlns:w", OpenXmlNamespaces::WordprocessingML ); m_pXmlWriter->WriteAttribute( L"xmlns:v", OpenXmlNamespaces::VectorML ); m_pXmlWriter->WriteAttribute( L"xmlns:o", OpenXmlNamespaces::Office ); m_pXmlWriter->WriteAttribute( L"xmlns:w10", OpenXmlNamespaces::OfficeWord ); m_pXmlWriter->WriteAttribute( L"xmlns:r", OpenXmlNamespaces::Relationships ); m_pXmlWriter->WriteNodeEnd( L"", TRUE, FALSE ); //convert the footer text _lastValidPapx = (*(m_document->AllPapxFkps->begin()))->grppapx[0]; int cp = _ftr.GetCharacterPosition(); int cpMax = _ftr.GetCharacterPosition() + _ftr.GetCharacterCount(); //the CharacterCount of the footers also counts the guard paragraph mark. //this additional paragraph mark shall not be converted. cpMax--; while ( cp < cpMax && cp < (int)m_document->Text->size()) { int fc = m_document->FindFileCharPos(cp); if (fc < 0) break; ParagraphPropertyExceptions* papx = findValidPapx( fc ); TableInfo tai( papx, m_document->nWordVersion ); if ( tai.fInTable ) { //this PAPX is for a table int start_table_cp = cp; Table table( this, cp, ( ( tai.iTap > 0 ) ? ( 1 ) : ( 0 ) ) ); table.Convert( this ); cp = table.GetCPEnd(); if (cp == start_table_cp) cp++; } else { //this PAPX is for a normal paragraph cp = writeParagraph( cp, 0x7fffffff ); } } m_pXmlWriter->WriteNodeEnd( L"w:ftr" ); m_context->_docx->FooterXMLList.push_back( std::wstring( m_pXmlWriter->GetXmlString() ) ); } } <commit_msg>fix bug #57702<commit_after>/* * (c) Copyright Ascensio System SIA 2010-2019 * * This program is a free software product. You can redistribute it and/or * modify it under the terms of the GNU Affero General Public License (AGPL) * version 3 as published by the Free Software Foundation. In accordance with * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect * that Ascensio System SIA expressly excludes the warranty of non-infringement * of any third-party rights. * * This program is distributed WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html * * You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha * street, Riga, Latvia, EU, LV-1050. * * The interactive user interfaces in modified source and object code versions * of the Program must display Appropriate Legal Notices, as required under * Section 5 of the GNU AGPL version 3. * * Pursuant to Section 7(b) of the License you must retain the original Product * logo when distributing the program. Pursuant to Section 7(e) we decline to * grant you any rights under trademark law for use of our trademarks. * * All the Product's GUI elements, including illustrations and icon sets, as * well as technical writing content are licensed under the terms of the * Creative Commons Attribution-ShareAlike 4.0 International. See the License * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode * */ #include "FooterMapping.h" #include "TableMapping.h" namespace DocFileFormat { FooterMapping::FooterMapping (ConversionContext* ctx, CharacterRange ftr) : DocumentMapping(ctx, this), _ftr(ftr) { } void FooterMapping::Apply( IVisitable* visited ) { m_document = static_cast<WordDocument*>( visited ); //start the document m_pXmlWriter->WriteNodeBegin( L"w:ftr", TRUE ); //write namespaces m_pXmlWriter->WriteAttribute( L"xmlns:w", OpenXmlNamespaces::WordprocessingML ); m_pXmlWriter->WriteAttribute( L"xmlns:v", OpenXmlNamespaces::VectorML ); m_pXmlWriter->WriteAttribute( L"xmlns:o", OpenXmlNamespaces::Office ); m_pXmlWriter->WriteAttribute( L"xmlns:w10", OpenXmlNamespaces::OfficeWord ); m_pXmlWriter->WriteAttribute( L"xmlns:r", OpenXmlNamespaces::Relationships ); m_pXmlWriter->WriteNodeEnd( L"", TRUE, FALSE ); //convert the footer text _lastValidPapx = (*(m_document->AllPapxFkps->begin()))->grppapx[0]; int cp = _ftr.GetCharacterPosition(); int cpMax = _ftr.GetCharacterPosition() + _ftr.GetCharacterCount(); //the CharacterCount of the footers also counts the guard paragraph mark. //this additional paragraph mark shall not be converted. cpMax--; while ( cp < cpMax && cp < (int)m_document->Text->size()) { int fc = m_document->FindFileCharPos(cp); if (fc < 0) break; ParagraphPropertyExceptions* papx = findValidPapx( fc ); TableInfo tai( papx, m_document->nWordVersion ); if ( tai.fInTable ) { //this PAPX is for a table int start_table_cp = cp; Table table( this, cp, ( ( tai.iTap > 0 ) ? ( 1 ) : ( 0 ) ) ); table.Convert( this ); cp = table.GetCPEnd(); if (cp == start_table_cp) cp++; } else { //this PAPX is for a normal paragraph cp = writeParagraph( cp, 0x7fffffff ); } } m_pXmlWriter->WriteNodeEnd( L"w:ftr" ); m_context->_docx->FooterXMLList.push_back( std::wstring( m_pXmlWriter->GetXmlString() ) ); } } <|endoftext|>
<commit_before>#include "typesolver.hh" #include "typeident.hh" #include <cmath> #include <limits> #include <iostream> #include "trim.hh" using namespace nolang; TypeSolver::TypeSolver() : method(nullptr) { } TypeSolver::TypeSolver(const PureMethod *m) : method(m) { } bool TypeSolver::isNative(const std::string & s) { if (s.substr(0, 3) == "int" || s.substr(0, 4) == "uint" || s == "Double" || s == "f64" || s == "f32" || s == "boolean" || s == "string" || s == "String") { return true; } return false; } std::string TypeSolver::native(const std::string & s) { // Defaulting "int" to int32 if (s == "int32" || s == "int") { return "int32_t"; } else if (s == "int8") { return "int8_t"; } else if (s == "int16") { return "int16_t"; } else if (s == "int64") { return "int64_t"; } else if (s == "uint32") { return "uint32_t"; } else if (s == "uint8") { return "uint8_t"; } else if (s == "uint16") { return "uint16_t"; } else if (s == "uint64") { return "uint64_t"; } else if (s == "Double") { return "double"; } else if (s == "f64") { return "double"; } else if (s == "f32") { return "float"; } else if (s == "boolean") { return "boolean"; } else if (s == "string" || s == "String") { return "const char *"; } else { return s + " *"; } throw "Unknown native type: " + s; } TypeIdent *TypeSolver::solveVariable(const std::string &name) const { if (!method) return nullptr; for (auto var : method->variables()) { if (var->code() == name) { return var; } } return nullptr; } std::string TypeSolver::native(const Statement *s) const { if (s->type() == "TypeDef") { if (s->code() == "void") { return "void"; } return native(s->code()); } else if (s->type() == "TypeIdent") { const TypeIdent *i = static_cast<const TypeIdent *>(s); std::string n = native(i->varType()); // FIXME std::cerr << "INVALID TYPEIDENT\n"; } else if (s->type() == "Identifier") { TypeIdent *var = solveVariable(s->code()); if (var) { return native(var->varType()); } return "invalid"; } else if (s->type() == "String" || s->type() == "string") { // FIXME "const char*" or "char*" return "char *"; } else if (s->type() == "Number") { // FIXME type and size, floats std::string num = s->code(); num = trim(num); /* TODO FIXME if (num.substr(0,2) == "0b") { // TODO Convert binary to hex } */ double value = std::stod(num, nullptr); if (num[0] == '-') { if (fabs(value) >= std::numeric_limits<int32_t>::max()) { return "int64_t"; } return "int32_t"; } else { if (value >= std::numeric_limits<int32_t>::max()) { return "uint64_t"; } return "uint32_t"; } } else if (s->type() == "Boolean") { return "boolean"; } else { throw std::string("Unknown native type: " + s->type()); } return ""; } std::string TypeSolver::nolangType(const Statement *s) const { if (s->type() == "TypeDef") { if (s->code() == "void") { return "void"; } return s->code(); // FIXME } else if (s->type() == "TypeIdent") { const TypeIdent *i = static_cast<const TypeIdent *>(s); return i->varType(); } else if (s->type() == "Identifier") { TypeIdent *var = solveVariable(s->code()); if (var) { var->varType(); } return "invalid"; } else if (s->type() == "String") { return "String"; } else if (s->type() == "Number") { // FIXME type and size, floats return "int32"; } else if (s->type() == "Boolean") { return "boolean"; } else { throw std::string("Unknown type: " + s->type()); } return ""; } // FIXME Combine with below std::string TypeSolver::typeOfChain(std::vector<Statement*> chain) const { std::string res; for (auto c : chain) { std::string t = native(c); if (!t.empty()) { if (res.empty()) { res = t; } else if (res == t) { // OK } else { // Need to solve std::cerr << "*** ERROR: Can't solve type of chain, conflicting types: " << res << ", " << t << "\n"; } } } return res; } std::string TypeSolver::nolangTypeOfChain(std::vector<Statement*> chain) const { std::string res; for (auto c : chain) { std::string t = nolangType(c); if (!t.empty()) { if (res.empty()) { res = t; } else if (res == t) { // OK } else { // Need to solve std::cerr << "*** ERROR: Can't solve type of chain, conflicting types: " << res << ", " << t << "\n"; } } } return res; } <commit_msg>Fix number conversion<commit_after>#include "typesolver.hh" #include "typeident.hh" #include <cmath> #include <limits> #include <iostream> #include "trim.hh" using namespace nolang; TypeSolver::TypeSolver() : method(nullptr) { } TypeSolver::TypeSolver(const PureMethod *m) : method(m) { } bool TypeSolver::isNative(const std::string & s) { if (s.substr(0, 3) == "int" || s.substr(0, 4) == "uint" || s == "Double" || s == "f64" || s == "f32" || s == "boolean" || s == "string" || s == "String") { return true; } return false; } std::string TypeSolver::native(const std::string & s) { // Defaulting "int" to int32 if (s == "int32" || s == "int") { return "int32_t"; } else if (s == "int8") { return "int8_t"; } else if (s == "int16") { return "int16_t"; } else if (s == "int64") { return "int64_t"; } else if (s == "uint32") { return "uint32_t"; } else if (s == "uint8") { return "uint8_t"; } else if (s == "uint16") { return "uint16_t"; } else if (s == "uint64") { return "uint64_t"; } else if (s == "Double") { return "double"; } else if (s == "f64") { return "double"; } else if (s == "f32") { return "float"; } else if (s == "boolean") { return "boolean"; } else if (s == "string" || s == "String") { return "const char *"; } else { return s + " *"; } throw "Unknown native type: " + s; } TypeIdent *TypeSolver::solveVariable(const std::string &name) const { if (!method) return nullptr; for (auto var : method->variables()) { if (var->code() == name) { return var; } } return nullptr; } std::string TypeSolver::native(const Statement *s) const { if (s->type() == "TypeDef") { if (s->code() == "void") { return "void"; } return native(s->code()); } else if (s->type() == "TypeIdent") { const TypeIdent *i = static_cast<const TypeIdent *>(s); std::string n = native(i->varType()); // FIXME std::cerr << "INVALID TYPEIDENT\n"; } else if (s->type() == "Identifier") { TypeIdent *var = solveVariable(s->code()); if (var) { return native(var->varType()); } return "invalid"; } else if (s->type() == "String" || s->type() == "string") { // FIXME "const char*" or "char*" return "char *"; } else if (s->type() == "Number") { // FIXME type and size, floats std::string num = s->code(); num = trim(num); /* TODO FIXME if (num.substr(0,2) == "0b") { // TODO Convert binary to hex } */ double value = 0; try { value = std::stod(num, nullptr); } catch (std::out_of_range r) { throw "Invalid number: " + num; } if (num[0] == '-') { if (fabs(value) >= std::numeric_limits<int32_t>::max()) { return "int64_t"; } return "int32_t"; } else { if (value >= std::numeric_limits<int32_t>::max()) { return "uint64_t"; } return "uint32_t"; } } else if (s->type() == "Boolean") { return "boolean"; } else { throw std::string("Unknown native type: " + s->type()); } return ""; } std::string TypeSolver::nolangType(const Statement *s) const { if (s->type() == "TypeDef") { if (s->code() == "void") { return "void"; } return s->code(); // FIXME } else if (s->type() == "TypeIdent") { const TypeIdent *i = static_cast<const TypeIdent *>(s); return i->varType(); } else if (s->type() == "Identifier") { TypeIdent *var = solveVariable(s->code()); if (var) { var->varType(); } return "invalid"; } else if (s->type() == "String") { return "String"; } else if (s->type() == "Number") { // FIXME type and size, floats return "int32"; } else if (s->type() == "Boolean") { return "boolean"; } else { throw std::string("Unknown type: " + s->type()); } return ""; } // FIXME Combine with below std::string TypeSolver::typeOfChain(std::vector<Statement*> chain) const { std::string res; for (auto c : chain) { std::string t = native(c); if (!t.empty()) { if (res.empty()) { res = t; } else if (res == t) { // OK } else { // Need to solve std::cerr << "*** ERROR: Can't solve type of chain, conflicting types: " << res << ", " << t << "\n"; } } } return res; } std::string TypeSolver::nolangTypeOfChain(std::vector<Statement*> chain) const { std::string res; for (auto c : chain) { std::string t = nolangType(c); if (!t.empty()) { if (res.empty()) { res = t; } else if (res == t) { // OK } else { // Need to solve std::cerr << "*** ERROR: Can't solve type of chain, conflicting types: " << res << ", " << t << "\n"; } } } return res; } <|endoftext|>
<commit_before>/*************************************************************************/ /* audio_stream_ogg_vorbis.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* 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 "audio_stream_ogg_vorbis.h" #include "os/file_access.h" #include "thirdparty/stb_vorbis/stb_vorbis.c" void AudioStreamPlaybackOGGVorbis::_mix_internal(AudioFrame *p_buffer, int p_frames) { ERR_FAIL_COND(!active); int todo = p_frames; while (todo) { int mixed = stb_vorbis_get_samples_float_interleaved(ogg_stream, 2, (float *)p_buffer, todo * 2); todo -= mixed; if (todo) { //end of file! if (vorbis_stream->loop) { //loop seek_pos(0); loops++; } else { for (int i = mixed; i < p_frames; i++) { p_buffer[i] = AudioFrame(0, 0); } active = false; } } } } float AudioStreamPlaybackOGGVorbis::get_stream_sampling_rate() { return vorbis_stream->sample_rate; } void AudioStreamPlaybackOGGVorbis::start(float p_from_pos) { active = true; seek_pos(p_from_pos); loops = 0; _begin_resample(); } void AudioStreamPlaybackOGGVorbis::stop() { active = false; } bool AudioStreamPlaybackOGGVorbis::is_playing() const { return active; } int AudioStreamPlaybackOGGVorbis::get_loop_count() const { return loops; } float AudioStreamPlaybackOGGVorbis::get_pos() const { return float(frames_mixed) / vorbis_stream->sample_rate; } void AudioStreamPlaybackOGGVorbis::seek_pos(float p_time) { if (!active) return; stb_vorbis_seek(ogg_stream, uint32_t(p_time * vorbis_stream->sample_rate)); } float AudioStreamPlaybackOGGVorbis::get_length() const { return vorbis_stream->length; } AudioStreamPlaybackOGGVorbis::~AudioStreamPlaybackOGGVorbis() { if (ogg_alloc.alloc_buffer) { AudioServer::get_singleton()->audio_data_free(ogg_alloc.alloc_buffer); stb_vorbis_close(ogg_stream); } } Ref<AudioStreamPlayback> AudioStreamOGGVorbis::instance_playback() { Ref<AudioStreamPlaybackOGGVorbis> ovs; printf("instance at %p, data %p\n", this, data); ERR_FAIL_COND_V(data == NULL, ovs); ovs.instance(); ovs->vorbis_stream = Ref<AudioStreamOGGVorbis>(this); ovs->ogg_alloc.alloc_buffer = (char *)AudioServer::get_singleton()->audio_data_alloc(decode_mem_size); ovs->ogg_alloc.alloc_buffer_length_in_bytes = decode_mem_size; ovs->frames_mixed = 0; ovs->active = false; ovs->loops = 0; int error; ovs->ogg_stream = stb_vorbis_open_memory((const unsigned char *)data, data_len, &error, &ovs->ogg_alloc); if (!ovs->ogg_stream) { AudioServer::get_singleton()->audio_data_free(ovs->ogg_alloc.alloc_buffer); ovs->ogg_alloc.alloc_buffer = NULL; ERR_FAIL_COND_V(!ovs->ogg_stream, Ref<AudioStreamPlaybackOGGVorbis>()); } return ovs; } String AudioStreamOGGVorbis::get_stream_name() const { return ""; //return stream_name; } void AudioStreamOGGVorbis::set_data(const PoolVector<uint8_t> &p_data) { int src_data_len = p_data.size(); #define MAX_TEST_MEM (1 << 20) uint32_t alloc_try = 1024; PoolVector<char> alloc_mem; PoolVector<char>::Write w; stb_vorbis *ogg_stream = NULL; stb_vorbis_alloc ogg_alloc; while (alloc_try < MAX_TEST_MEM) { alloc_mem.resize(alloc_try); w = alloc_mem.write(); ogg_alloc.alloc_buffer = w.ptr(); ogg_alloc.alloc_buffer_length_in_bytes = alloc_try; PoolVector<uint8_t>::Read src_datar = p_data.read(); int error; ogg_stream = stb_vorbis_open_memory((const unsigned char *)src_datar.ptr(), src_data_len, &error, &ogg_alloc); if (!ogg_stream && error == VORBIS_outofmem) { w = PoolVector<char>::Write(); alloc_try *= 2; } else { ERR_FAIL_COND(alloc_try == MAX_TEST_MEM); ERR_FAIL_COND(ogg_stream == NULL); stb_vorbis_info info = stb_vorbis_get_info(ogg_stream); channels = info.channels; sample_rate = info.sample_rate; decode_mem_size = alloc_try; //does this work? (it's less mem..) //decode_mem_size = ogg_alloc.alloc_buffer_length_in_bytes + info.setup_memory_required + info.temp_memory_required + info.max_frame_size; //print_line("succeeded "+itos(ogg_alloc.alloc_buffer_length_in_bytes)+" setup "+itos(info.setup_memory_required)+" setup temp "+itos(info.setup_temp_memory_required)+" temp "+itos(info.temp_memory_required)+" maxframe"+itos(info.max_frame_size)); length = stb_vorbis_stream_length_in_seconds(ogg_stream); stb_vorbis_close(ogg_stream); data = AudioServer::get_singleton()->audio_data_alloc(src_data_len, src_datar.ptr()); data_len = src_data_len; break; } } printf("create at %p, data %p\n", this, data); } PoolVector<uint8_t> AudioStreamOGGVorbis::get_data() const { PoolVector<uint8_t> vdata; if (data_len && data) { vdata.resize(data_len); { PoolVector<uint8_t>::Write w = vdata.write(); copymem(w.ptr(), data, data_len); } } return vdata; } void AudioStreamOGGVorbis::set_loop(bool p_enable) { loop = p_enable; } bool AudioStreamOGGVorbis::has_loop() const { return loop; } void AudioStreamOGGVorbis::_bind_methods() { ClassDB::bind_method(D_METHOD("set_data", "data"), &AudioStreamOGGVorbis::set_data); ClassDB::bind_method(D_METHOD("get_data"), &AudioStreamOGGVorbis::get_data); ClassDB::bind_method(D_METHOD("set_loop", "enable"), &AudioStreamOGGVorbis::set_loop); ClassDB::bind_method(D_METHOD("has_loop"), &AudioStreamOGGVorbis::has_loop); ADD_PROPERTY(PropertyInfo(Variant::POOL_BYTE_ARRAY, "data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_data", "get_data"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "loop", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_loop", "has_loop"); } AudioStreamOGGVorbis::AudioStreamOGGVorbis() { data = NULL; length = 0; sample_rate = 1; channels = 1; decode_mem_size = 0; loop = false; } <commit_msg>Fix AudioPlayer.get_pos() always returns 0<commit_after>/*************************************************************************/ /* audio_stream_ogg_vorbis.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* 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 "audio_stream_ogg_vorbis.h" #include "os/file_access.h" #include "thirdparty/stb_vorbis/stb_vorbis.c" void AudioStreamPlaybackOGGVorbis::_mix_internal(AudioFrame *p_buffer, int p_frames) { ERR_FAIL_COND(!active); int todo = p_frames; while (todo) { int mixed = stb_vorbis_get_samples_float_interleaved(ogg_stream, 2, (float *)p_buffer, todo * 2); todo -= mixed; frames_mixed += mixed; if (todo) { //end of file! if (vorbis_stream->loop) { //loop seek_pos(0); loops++; } else { for (int i = mixed; i < p_frames; i++) { p_buffer[i] = AudioFrame(0, 0); } active = false; } } } } float AudioStreamPlaybackOGGVorbis::get_stream_sampling_rate() { return vorbis_stream->sample_rate; } void AudioStreamPlaybackOGGVorbis::start(float p_from_pos) { active = true; seek_pos(p_from_pos); loops = 0; _begin_resample(); } void AudioStreamPlaybackOGGVorbis::stop() { active = false; } bool AudioStreamPlaybackOGGVorbis::is_playing() const { return active; } int AudioStreamPlaybackOGGVorbis::get_loop_count() const { return loops; } float AudioStreamPlaybackOGGVorbis::get_pos() const { return float(frames_mixed) / vorbis_stream->sample_rate; } void AudioStreamPlaybackOGGVorbis::seek_pos(float p_time) { if (!active) return; if (p_time >= get_length()) { p_time = 0; } frames_mixed = uint32_t(vorbis_stream->sample_rate * p_time); stb_vorbis_seek(ogg_stream, frames_mixed); } float AudioStreamPlaybackOGGVorbis::get_length() const { return vorbis_stream->length; } AudioStreamPlaybackOGGVorbis::~AudioStreamPlaybackOGGVorbis() { if (ogg_alloc.alloc_buffer) { AudioServer::get_singleton()->audio_data_free(ogg_alloc.alloc_buffer); stb_vorbis_close(ogg_stream); } } Ref<AudioStreamPlayback> AudioStreamOGGVorbis::instance_playback() { Ref<AudioStreamPlaybackOGGVorbis> ovs; printf("instance at %p, data %p\n", this, data); ERR_FAIL_COND_V(data == NULL, ovs); ovs.instance(); ovs->vorbis_stream = Ref<AudioStreamOGGVorbis>(this); ovs->ogg_alloc.alloc_buffer = (char *)AudioServer::get_singleton()->audio_data_alloc(decode_mem_size); ovs->ogg_alloc.alloc_buffer_length_in_bytes = decode_mem_size; ovs->frames_mixed = 0; ovs->active = false; ovs->loops = 0; int error; ovs->ogg_stream = stb_vorbis_open_memory((const unsigned char *)data, data_len, &error, &ovs->ogg_alloc); if (!ovs->ogg_stream) { AudioServer::get_singleton()->audio_data_free(ovs->ogg_alloc.alloc_buffer); ovs->ogg_alloc.alloc_buffer = NULL; ERR_FAIL_COND_V(!ovs->ogg_stream, Ref<AudioStreamPlaybackOGGVorbis>()); } return ovs; } String AudioStreamOGGVorbis::get_stream_name() const { return ""; //return stream_name; } void AudioStreamOGGVorbis::set_data(const PoolVector<uint8_t> &p_data) { int src_data_len = p_data.size(); #define MAX_TEST_MEM (1 << 20) uint32_t alloc_try = 1024; PoolVector<char> alloc_mem; PoolVector<char>::Write w; stb_vorbis *ogg_stream = NULL; stb_vorbis_alloc ogg_alloc; while (alloc_try < MAX_TEST_MEM) { alloc_mem.resize(alloc_try); w = alloc_mem.write(); ogg_alloc.alloc_buffer = w.ptr(); ogg_alloc.alloc_buffer_length_in_bytes = alloc_try; PoolVector<uint8_t>::Read src_datar = p_data.read(); int error; ogg_stream = stb_vorbis_open_memory((const unsigned char *)src_datar.ptr(), src_data_len, &error, &ogg_alloc); if (!ogg_stream && error == VORBIS_outofmem) { w = PoolVector<char>::Write(); alloc_try *= 2; } else { ERR_FAIL_COND(alloc_try == MAX_TEST_MEM); ERR_FAIL_COND(ogg_stream == NULL); stb_vorbis_info info = stb_vorbis_get_info(ogg_stream); channels = info.channels; sample_rate = info.sample_rate; decode_mem_size = alloc_try; //does this work? (it's less mem..) //decode_mem_size = ogg_alloc.alloc_buffer_length_in_bytes + info.setup_memory_required + info.temp_memory_required + info.max_frame_size; //print_line("succeeded "+itos(ogg_alloc.alloc_buffer_length_in_bytes)+" setup "+itos(info.setup_memory_required)+" setup temp "+itos(info.setup_temp_memory_required)+" temp "+itos(info.temp_memory_required)+" maxframe"+itos(info.max_frame_size)); length = stb_vorbis_stream_length_in_seconds(ogg_stream); stb_vorbis_close(ogg_stream); data = AudioServer::get_singleton()->audio_data_alloc(src_data_len, src_datar.ptr()); data_len = src_data_len; break; } } printf("create at %p, data %p\n", this, data); } PoolVector<uint8_t> AudioStreamOGGVorbis::get_data() const { PoolVector<uint8_t> vdata; if (data_len && data) { vdata.resize(data_len); { PoolVector<uint8_t>::Write w = vdata.write(); copymem(w.ptr(), data, data_len); } } return vdata; } void AudioStreamOGGVorbis::set_loop(bool p_enable) { loop = p_enable; } bool AudioStreamOGGVorbis::has_loop() const { return loop; } void AudioStreamOGGVorbis::_bind_methods() { ClassDB::bind_method(D_METHOD("set_data", "data"), &AudioStreamOGGVorbis::set_data); ClassDB::bind_method(D_METHOD("get_data"), &AudioStreamOGGVorbis::get_data); ClassDB::bind_method(D_METHOD("set_loop", "enable"), &AudioStreamOGGVorbis::set_loop); ClassDB::bind_method(D_METHOD("has_loop"), &AudioStreamOGGVorbis::has_loop); ADD_PROPERTY(PropertyInfo(Variant::POOL_BYTE_ARRAY, "data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_data", "get_data"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "loop", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_loop", "has_loop"); } AudioStreamOGGVorbis::AudioStreamOGGVorbis() { data = NULL; length = 0; sample_rate = 1; channels = 1; decode_mem_size = 0; loop = false; } <|endoftext|>
<commit_before>#include "FlowChannel1Phase.h" #include "FlowModelSinglePhase.h" #include "StabilizationSettings.h" #include "HeatTransfer1PhaseBase.h" #include "Closures1PhaseBase.h" #include "THMApp.h" registerMooseObject("THMApp", FlowChannel1Phase); template <> InputParameters validParams<FlowChannel1Phase>() { InputParameters params = validParams<FlowChannelBase>(); params.addRequiredParam<FunctionName>("A", "Area of the pipe, can be a constant or a function"); params.addParam<Real>("roughness", 0.0, "roughness, [m]"); params.addParam<FunctionName>("f", "Wall friction"); params.addParam<MaterialPropertyName>("f_2phase_mult_liquid", "2-phase multiplier property for friction for liquid"); params.addParam<MaterialPropertyName>("f_2phase_mult_vapor", "2-phase multiplier property for friction for vapor"); params.addParam<FunctionName>("K_prime", "Form loss coefficient per unit length function"); params.addParam<MaterialPropertyName>("K_2phase_mult_liquid", "2-phase multiplier property for form loss for liquid"); params.addParam<MaterialPropertyName>("K_2phase_mult_vapor", "2-phase multiplier property for form loss for vapor"); params.addParam<MooseEnum>("heat_transfer_geom", FlowChannel1Phase::getConvHeatTransGeometry("PIPE"), "Convective heat transfer geometry"); params.addParam<Real>("PoD", 1, "pitch to diameter ratio for parallel bundle heat transfer"); params.addParam<FunctionName>("initial_p", "Initial pressure in the pipe"); params.addParam<FunctionName>("initial_vel", "Initial velocity in the pipe"); params.addParam<FunctionName>("initial_T", "Initial temperature in the pipe"); params.addClassDescription("1-phase 1D flow channel"); return params; } FlowChannel1Phase::FlowChannel1Phase(const InputParameters & params) : FlowChannelBase(params) {} std::shared_ptr<FlowModel> FlowChannel1Phase::buildFlowModel() { const std::string class_name = "FlowModelSinglePhase"; InputParameters pars = _factory.getValidParams(class_name); pars.set<Simulation *>("_sim") = &_sim; pars.set<FlowChannelBase *>("_pipe") = this; pars.set<UserObjectName>("fp") = _fp_name; pars.set<UserObjectName>("numerical_flux") = _numerical_flux_name; pars.set<AuxVariableName>("A_linear_name") = _A_linear_name; pars.set<MooseEnum>("rdg_slope_reconstruction") = _rdg_slope_reconstruction; return _factory.create<FlowModel>(class_name, name(), pars, 0); } void FlowChannel1Phase::check() const { FlowChannelBase::check(); bool ics_set = isParamValid("initial_p") && isParamValid("initial_T") && isParamValid("initial_vel"); if (!ics_set && !_app.isRestarting()) { // create a list of the missing IC parameters const std::vector<std::string> ic_params{"initial_p", "initial_T", "initial_vel"}; std::ostringstream oss; for (const auto & ic_param : ic_params) if (!isParamValid(ic_param)) oss << " " << ic_param; logError("The following initial condition parameters are missing:", oss.str()); } } void FlowChannel1Phase::addFormLossObjects() { if (isParamValid("K_prime")) { const std::string class_name = "OneDMomentumFormLoss"; InputParameters params = _factory.getValidParams(class_name); params.set<NonlinearVariableName>("variable") = FlowModelSinglePhase::RHOUA; params.set<std::vector<SubdomainName>>("block") = getSubdomainNames(); params.set<std::vector<VariableName>>("arhoA") = {FlowModelSinglePhase::RHOA}; params.set<std::vector<VariableName>>("arhouA") = {FlowModelSinglePhase::RHOUA}; params.set<std::vector<VariableName>>("arhoEA") = {FlowModelSinglePhase::RHOEA}; params.set<std::vector<VariableName>>("A") = {FlowModel::AREA}; params.set<MaterialPropertyName>("alpha") = FlowModel::UNITY; params.set<MaterialPropertyName>("rho") = FlowModelSinglePhase::DENSITY; params.set<MaterialPropertyName>("vel") = FlowModelSinglePhase::VELOCITY; params.set<MaterialPropertyName>("2phase_multiplier") = FlowModel::UNITY; params.set<FunctionName>("K_prime") = getParam<FunctionName>("K_prime"); _sim.addKernel(class_name, Component::genName(name(), class_name), params); } } void FlowChannel1Phase::addMooseObjects() { FlowChannelBase::addMooseObjects(); addFormLossObjects(); } void FlowChannel1Phase::getHeatTransferVariableNames() { FlowChannelBase::getHeatTransferVariableNames(); for (unsigned int i = 0; i < _n_heat_transfer_connections; i++) { const HeatTransfer1PhaseBase & heat_transfer = getComponentByName<HeatTransfer1PhaseBase>(_heat_transfer_names[i]); _Hw_1phase_names.push_back(heat_transfer.getWallHeatTransferCoefficient1PhaseName()); } } <commit_msg>Check coupled heat transfer components<commit_after>#include "FlowChannel1Phase.h" #include "FlowModelSinglePhase.h" #include "StabilizationSettings.h" #include "HeatTransfer1PhaseBase.h" #include "Closures1PhaseBase.h" #include "THMApp.h" registerMooseObject("THMApp", FlowChannel1Phase); template <> InputParameters validParams<FlowChannel1Phase>() { InputParameters params = validParams<FlowChannelBase>(); params.addRequiredParam<FunctionName>("A", "Area of the pipe, can be a constant or a function"); params.addParam<Real>("roughness", 0.0, "roughness, [m]"); params.addParam<FunctionName>("f", "Wall friction"); params.addParam<MaterialPropertyName>("f_2phase_mult_liquid", "2-phase multiplier property for friction for liquid"); params.addParam<MaterialPropertyName>("f_2phase_mult_vapor", "2-phase multiplier property for friction for vapor"); params.addParam<FunctionName>("K_prime", "Form loss coefficient per unit length function"); params.addParam<MaterialPropertyName>("K_2phase_mult_liquid", "2-phase multiplier property for form loss for liquid"); params.addParam<MaterialPropertyName>("K_2phase_mult_vapor", "2-phase multiplier property for form loss for vapor"); params.addParam<MooseEnum>("heat_transfer_geom", FlowChannel1Phase::getConvHeatTransGeometry("PIPE"), "Convective heat transfer geometry"); params.addParam<Real>("PoD", 1, "pitch to diameter ratio for parallel bundle heat transfer"); params.addParam<FunctionName>("initial_p", "Initial pressure in the pipe"); params.addParam<FunctionName>("initial_vel", "Initial velocity in the pipe"); params.addParam<FunctionName>("initial_T", "Initial temperature in the pipe"); params.addClassDescription("1-phase 1D flow channel"); return params; } FlowChannel1Phase::FlowChannel1Phase(const InputParameters & params) : FlowChannelBase(params) {} std::shared_ptr<FlowModel> FlowChannel1Phase::buildFlowModel() { const std::string class_name = "FlowModelSinglePhase"; InputParameters pars = _factory.getValidParams(class_name); pars.set<Simulation *>("_sim") = &_sim; pars.set<FlowChannelBase *>("_pipe") = this; pars.set<UserObjectName>("fp") = _fp_name; pars.set<UserObjectName>("numerical_flux") = _numerical_flux_name; pars.set<AuxVariableName>("A_linear_name") = _A_linear_name; pars.set<MooseEnum>("rdg_slope_reconstruction") = _rdg_slope_reconstruction; return _factory.create<FlowModel>(class_name, name(), pars, 0); } void FlowChannel1Phase::check() const { FlowChannelBase::check(); // only 1-phase flow compatible heat transfers are allowed for (unsigned int i = 0; i < _heat_transfer_names.size(); i++) { if (!hasComponentByName<HeatTransfer1PhaseBase>(_heat_transfer_names[i])) logError("Coupled heat sources '", _heat_transfer_names[i], "' is not compatible with single phase flow channel. Either change the type of the " "flow channel or the heat transfer component."); } bool ics_set = isParamValid("initial_p") && isParamValid("initial_T") && isParamValid("initial_vel"); if (!ics_set && !_app.isRestarting()) { // create a list of the missing IC parameters const std::vector<std::string> ic_params{"initial_p", "initial_T", "initial_vel"}; std::ostringstream oss; for (const auto & ic_param : ic_params) if (!isParamValid(ic_param)) oss << " " << ic_param; logError("The following initial condition parameters are missing:", oss.str()); } } void FlowChannel1Phase::addFormLossObjects() { if (isParamValid("K_prime")) { const std::string class_name = "OneDMomentumFormLoss"; InputParameters params = _factory.getValidParams(class_name); params.set<NonlinearVariableName>("variable") = FlowModelSinglePhase::RHOUA; params.set<std::vector<SubdomainName>>("block") = getSubdomainNames(); params.set<std::vector<VariableName>>("arhoA") = {FlowModelSinglePhase::RHOA}; params.set<std::vector<VariableName>>("arhouA") = {FlowModelSinglePhase::RHOUA}; params.set<std::vector<VariableName>>("arhoEA") = {FlowModelSinglePhase::RHOEA}; params.set<std::vector<VariableName>>("A") = {FlowModel::AREA}; params.set<MaterialPropertyName>("alpha") = FlowModel::UNITY; params.set<MaterialPropertyName>("rho") = FlowModelSinglePhase::DENSITY; params.set<MaterialPropertyName>("vel") = FlowModelSinglePhase::VELOCITY; params.set<MaterialPropertyName>("2phase_multiplier") = FlowModel::UNITY; params.set<FunctionName>("K_prime") = getParam<FunctionName>("K_prime"); _sim.addKernel(class_name, Component::genName(name(), class_name), params); } } void FlowChannel1Phase::addMooseObjects() { FlowChannelBase::addMooseObjects(); addFormLossObjects(); } void FlowChannel1Phase::getHeatTransferVariableNames() { FlowChannelBase::getHeatTransferVariableNames(); for (unsigned int i = 0; i < _n_heat_transfer_connections; i++) { const HeatTransfer1PhaseBase & heat_transfer = getComponentByName<HeatTransfer1PhaseBase>(_heat_transfer_names[i]); _Hw_1phase_names.push_back(heat_transfer.getWallHeatTransferCoefficient1PhaseName()); } } <|endoftext|>
<commit_before>#include "bart_builder.h" #include <unordered_map> #include <deal.II/fe/fe_dgq.h> #include <deal.II/fe/fe_q.h> #include <deal.II/fe/fe_raviart_thomas.h> namespace bbuilders { template <int dim> void BuildFESpaces (const dealii::ParameterHandler &prm, std::vector<dealii::FiniteElement<dim, dim>*> &fe_ptrs) { // getting parameter values const bool do_nda = prm.get_bool ("do nda"); const int p_order = prm.get_integer("finite element polynomial degree"); const std::string ho_discretization = prm.get ("ho spatial discretization"); const std::string nda_discretization = prm.get ("nda spatial discretization"); fe_ptrs.resize (do_nda ? 2 : 1); std::unordered_map<std::string, unsigned int> discretization_ind = { {"cfem", 0}, {"dfem", 1}, {"cmfd", 2}, {"rtk", 3}}; switch (discretization_ind[ho_discretization]) { case 0: fe_ptrs.front () = new dealii::FE_Q<dim> (p_order); break; case 1: fe_ptrs.front () = new dealii::FE_DGQ<dim> (p_order); break; default: AssertThrow (false, dealii::ExcMessage("Invalid HO discretization name")); break; } if (do_nda) { switch (discretization_ind[nda_discretization]) { case 0: fe_ptrs.back () = new dealii::FE_Q<dim> (p_order); break; case 1: fe_ptrs.back () = new dealii::FE_DGQ<dim> (p_order); break; case 2: fe_ptrs.back () = new dealii::FE_DGQ<dim> (0); break; case 3: fe_ptrs.back () = new dealii::FE_RaviartThomas<dim> (p_order); break; default: AssertThrow (false, dealii::ExcMessage("Invalid NDA discretization name")); break; } } } template <int dim> void BuildAQ (const dealii::ParameterHandler &prm, std::unique_ptr<AQBase<dim>> &aq_ptr) { // getting parameter values const std::string aq_name = prm.get ("angular quadrature name"); const int aq_order = prm.get_integer ("angular quadrature order"); if (dim==1) { // AQBase implements 1D quadrature aq_ptr = std::unique_ptr<AQBase<dim>> (new AQBase<dim>(prm)); } else if (dim>1) { std::unordered_map<std::string, int> aq_ind = {{"lsgc", 0}}; switch (aq_ind[aq_name]) { case 0: aq_ptr = std::unique_ptr<AQBase<dim>> (new LSGC<dim>(prm)); break; default: AssertThrow (false, dealii::ExcMessage("Proper name is not given for AQ")); break; } } } } // explicitly instantiate all builders using templates // explicit instantiation for BuildFESpaces template void bbuilders::BuildFESpaces<1> (const dealii::ParameterHandler&, std::vector<dealii::FiniteElement<1, 1>*> &); template void bbuilders::BuildFESpaces<2> (const dealii::ParameterHandler&, std::vector<dealii::FiniteElement<2, 2>*> &); template void bbuilders::BuildFESpaces<3> (const dealii::ParameterHandler&, std::vector<dealii::FiniteElement<3, 3>*> &); // explicit instantiation for BuildAQ template void bbuilders::BuildAQ<1> (const dealii::ParameterHandler&, std::unique_ptr<AQBase<1>> &); template void bbuilders::BuildAQ<2> (const dealii::ParameterHandler&, std::unique_ptr<AQBase<2>> &); template void bbuilders::BuildAQ<3> (const dealii::ParameterHandler&, std::unique_ptr<AQBase<3>> &); <commit_msg>removed unused variable in builder<commit_after>#include "bart_builder.h" #include <unordered_map> #include <deal.II/fe/fe_dgq.h> #include <deal.II/fe/fe_q.h> #include <deal.II/fe/fe_raviart_thomas.h> namespace bbuilders { template <int dim> void BuildFESpaces (const dealii::ParameterHandler &prm, std::vector<dealii::FiniteElement<dim, dim>*> &fe_ptrs) { // getting parameter values const bool do_nda = prm.get_bool ("do nda"); const int p_order = prm.get_integer("finite element polynomial degree"); const std::string ho_discretization = prm.get ("ho spatial discretization"); const std::string nda_discretization = prm.get ("nda spatial discretization"); fe_ptrs.resize (do_nda ? 2 : 1); std::unordered_map<std::string, unsigned int> discretization_ind = { {"cfem", 0}, {"dfem", 1}, {"cmfd", 2}, {"rtk", 3}}; switch (discretization_ind[ho_discretization]) { case 0: fe_ptrs.front () = new dealii::FE_Q<dim> (p_order); break; case 1: fe_ptrs.front () = new dealii::FE_DGQ<dim> (p_order); break; default: AssertThrow (false, dealii::ExcMessage("Invalid HO discretization name")); break; } if (do_nda) { switch (discretization_ind[nda_discretization]) { case 0: fe_ptrs.back () = new dealii::FE_Q<dim> (p_order); break; case 1: fe_ptrs.back () = new dealii::FE_DGQ<dim> (p_order); break; case 2: fe_ptrs.back () = new dealii::FE_DGQ<dim> (0); break; case 3: fe_ptrs.back () = new dealii::FE_RaviartThomas<dim> (p_order); break; default: AssertThrow (false, dealii::ExcMessage("Invalid NDA discretization name")); break; } } } template <int dim> void BuildAQ (const dealii::ParameterHandler &prm, std::unique_ptr<AQBase<dim>> &aq_ptr) { // getting parameter values const std::string aq_name = prm.get ("angular quadrature name"); if (dim==1) { // AQBase implements 1D quadrature aq_ptr = std::unique_ptr<AQBase<dim>> (new AQBase<dim>(prm)); } else if (dim>1) { std::unordered_map<std::string, int> aq_ind = {{"lsgc", 0}}; switch (aq_ind[aq_name]) { case 0: aq_ptr = std::unique_ptr<AQBase<dim>> (new LSGC<dim>(prm)); break; default: AssertThrow (false, dealii::ExcMessage("Proper name is not given for AQ")); break; } } } } // explicitly instantiate all builders using templates // explicit instantiation for BuildFESpaces template void bbuilders::BuildFESpaces<1> (const dealii::ParameterHandler&, std::vector<dealii::FiniteElement<1, 1>*> &); template void bbuilders::BuildFESpaces<2> (const dealii::ParameterHandler&, std::vector<dealii::FiniteElement<2, 2>*> &); template void bbuilders::BuildFESpaces<3> (const dealii::ParameterHandler&, std::vector<dealii::FiniteElement<3, 3>*> &); // explicit instantiation for BuildAQ template void bbuilders::BuildAQ<1> (const dealii::ParameterHandler&, std::unique_ptr<AQBase<1>> &); template void bbuilders::BuildAQ<2> (const dealii::ParameterHandler&, std::unique_ptr<AQBase<2>> &); template void bbuilders::BuildAQ<3> (const dealii::ParameterHandler&, std::unique_ptr<AQBase<3>> &); <|endoftext|>
<commit_before>/*------------------------------------------------------------------------ * (The MIT License) * * Copyright (c) 2008-2011 Rhomobile, 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. * * http://rhomobile.com *------------------------------------------------------------------------*/ #include <sys/stat.h> #include <sys/resource.h> #include <pwd.h> #include "rhodes/JNIRhodes.h" #include "common/AutoPointer.h" #include "common/RhoStd.h" #include "common/RhoConf.h" #include "common/RhodesAppBase.h" #include "sqlite/sqlite3.h" #include "logging/RhoLogConf.h" //-------------------------------------------------------------------------------------------------- static rho::common::CAutoPtr<rho::common::AndroidLogSink> s_logSink(new rho::common::AndroidLogSink()); static rho::String s_root_path; static rho::String s_sqlite_path; //-------------------------------------------------------------------------------------------------- RHO_GLOBAL void android_set_path(const rho::String& root, const rho::String& sqlite) { s_root_path = root; s_sqlite_path = sqlite; } //-------------------------------------------------------------------------------------------------- rho::String const &rho_root_path() { return s_root_path; } //-------------------------------------------------------------------------------------------------- const char* rho_native_rhopath() { return rho_root_path().c_str(); } //-------------------------------------------------------------------------------------------------- rho::String rho_cur_path() { char buf[PATH_MAX]; if (::getcwd(buf, sizeof(buf)) == NULL) return ""; return buf; } //-------------------------------------------------------------------------------------------------- static bool set_posix_environment(JNIEnv *env, jclass clsRE) { // Set USER variable struct passwd *pwd = ::getpwuid(::getuid()); if (!pwd) { env->ThrowNew(clsRE, "Can't find user name for current user"); return false; } size_t len = ::strlen(pwd->pw_name) + 16; char *buf = (char *)::malloc(len + 1); buf[len] = '\0'; ::snprintf(buf, len, "USER=%s", pwd->pw_name); int e = ::putenv(buf); ::free(buf); if (e != 0) { env->ThrowNew(clsRE, "Can't set USER environment variable"); return false; } // Set HOME variable std::string root_path = rho_root_path(); if (!root_path.empty() && root_path[root_path.size() - 1] == '/') root_path.erase(root_path.size() - 1); len = root_path.size() + 16; buf = (char *)::malloc(len + 1); buf[len] = '\0'; ::snprintf(buf, len, "HOME=%s", root_path.c_str()); e = ::putenv(buf); ::free(buf); if (e != 0) { env->ThrowNew(clsRE, "Can't set HOME environment variable"); return false; } // Set TMP variable len = root_path.size() + 32; buf = (char *)::malloc(len + 1); buf[len] = '\0'; ::snprintf(buf, len, "TMP=%s/tmp", root_path.c_str()); e = ::putenv(buf); ::free(buf); if (e != 0) { env->ThrowNew(clsRE, "Can't set TMP environment variable"); return false; } return true; } //-------------------------------------------------------------------------------------------------- RHO_GLOBAL void android_setup(JNIEnv *env) { jclass clsRE = getJNIClass(RHODES_JAVA_CLASS_RUNTIME_EXCEPTION); if (!clsRE) return; struct rlimit rlim; if (getrlimit(RLIMIT_NOFILE, &rlim) == -1) { env->ThrowNew(clsRE, "Can not get maximum number of open files"); return; } if (rlim.rlim_max < (unsigned long)RHO_FD_BASE) { env->ThrowNew(clsRE, "Current limit of open files is less then RHO_FD_BASE"); return; } if (rlim.rlim_cur > (unsigned long)RHO_FD_BASE) { rlim.rlim_cur = RHO_FD_BASE; rlim.rlim_max = RHO_FD_BASE; if (setrlimit(RLIMIT_NOFILE, &rlim) == -1) { env->ThrowNew(clsRE, "Can not set maximum number of open files"); return; } } if (!set_posix_environment(env, clsRE)) return; if (::chdir(rho_root_path().c_str()) == -1) { env->ThrowNew(clsRE, "Can not chdir to HOME directory"); return; } // Init SQLite temp directory sqlite3_temp_directory = (char*)s_sqlite_path.c_str(); // Init logconf rho_logconf_Init(rho_native_rhopath(), ""); // Disable log to stdout as on android all stdout redirects to /dev/null RHOCONF().setBool("LogToOutput", false, true); LOGCONF().setLogToOutput(false); // Add android system log sink LOGCONF().setLogView(s_logSink); } //-------------------------------------------------------------------------------------------------- RHO_GLOBAL void *rho_nativethread_start() { JNIEnv *env; jvm()->AttachCurrentThread(&env, NULL); store_thr_jnienv(env); return NULL; } //-------------------------------------------------------------------------------------------------- RHO_GLOBAL void rho_nativethread_end(void *) { jvm()->DetachCurrentThread(); } //-------------------------------------------------------------------------------------------------- <commit_msg>android: build fix<commit_after>/*------------------------------------------------------------------------ * (The MIT License) * * Copyright (c) 2008-2011 Rhomobile, 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. * * http://rhomobile.com *------------------------------------------------------------------------*/ #include <sys/stat.h> #include <sys/resource.h> #include <pwd.h> #include "rhodes/JNIRhodes.h" #include "common/AutoPointer.h" #include "common/RhoStd.h" #include "common/RhoConf.h" #include "common/RhodesAppBase.h" #include "sqlite/sqlite3.h" #include "logging/RhoLogConf.h" //-------------------------------------------------------------------------------------------------- static rho::common::CAutoPtr<rho::common::AndroidLogSink> s_logSink(new rho::common::AndroidLogSink()); static rho::String s_root_path; static rho::String s_sqlite_path; //-------------------------------------------------------------------------------------------------- RHO_GLOBAL void android_set_path(const rho::String& root, const rho::String& sqlite) { s_root_path = root; s_sqlite_path = sqlite; } //-------------------------------------------------------------------------------------------------- rho::String const &rho_root_path() { return s_root_path; } //-------------------------------------------------------------------------------------------------- const char* rho_native_rhopath() { return rho_root_path().c_str(); } //-------------------------------------------------------------------------------------------------- const char* rho_native_reruntimepath() { return rho_root_path().c_str(); } //-------------------------------------------------------------------------------------------------- rho::String rho_cur_path() { char buf[PATH_MAX]; if (::getcwd(buf, sizeof(buf)) == NULL) return ""; return buf; } //-------------------------------------------------------------------------------------------------- static bool set_posix_environment(JNIEnv *env, jclass clsRE) { // Set USER variable struct passwd *pwd = ::getpwuid(::getuid()); if (!pwd) { env->ThrowNew(clsRE, "Can't find user name for current user"); return false; } size_t len = ::strlen(pwd->pw_name) + 16; char *buf = (char *)::malloc(len + 1); buf[len] = '\0'; ::snprintf(buf, len, "USER=%s", pwd->pw_name); int e = ::putenv(buf); ::free(buf); if (e != 0) { env->ThrowNew(clsRE, "Can't set USER environment variable"); return false; } // Set HOME variable std::string root_path = rho_root_path(); if (!root_path.empty() && root_path[root_path.size() - 1] == '/') root_path.erase(root_path.size() - 1); len = root_path.size() + 16; buf = (char *)::malloc(len + 1); buf[len] = '\0'; ::snprintf(buf, len, "HOME=%s", root_path.c_str()); e = ::putenv(buf); ::free(buf); if (e != 0) { env->ThrowNew(clsRE, "Can't set HOME environment variable"); return false; } // Set TMP variable len = root_path.size() + 32; buf = (char *)::malloc(len + 1); buf[len] = '\0'; ::snprintf(buf, len, "TMP=%s/tmp", root_path.c_str()); e = ::putenv(buf); ::free(buf); if (e != 0) { env->ThrowNew(clsRE, "Can't set TMP environment variable"); return false; } return true; } //-------------------------------------------------------------------------------------------------- RHO_GLOBAL void android_setup(JNIEnv *env) { jclass clsRE = getJNIClass(RHODES_JAVA_CLASS_RUNTIME_EXCEPTION); if (!clsRE) return; struct rlimit rlim; if (getrlimit(RLIMIT_NOFILE, &rlim) == -1) { env->ThrowNew(clsRE, "Can not get maximum number of open files"); return; } if (rlim.rlim_max < (unsigned long)RHO_FD_BASE) { env->ThrowNew(clsRE, "Current limit of open files is less then RHO_FD_BASE"); return; } if (rlim.rlim_cur > (unsigned long)RHO_FD_BASE) { rlim.rlim_cur = RHO_FD_BASE; rlim.rlim_max = RHO_FD_BASE; if (setrlimit(RLIMIT_NOFILE, &rlim) == -1) { env->ThrowNew(clsRE, "Can not set maximum number of open files"); return; } } if (!set_posix_environment(env, clsRE)) return; if (::chdir(rho_root_path().c_str()) == -1) { env->ThrowNew(clsRE, "Can not chdir to HOME directory"); return; } // Init SQLite temp directory sqlite3_temp_directory = (char*)s_sqlite_path.c_str(); // Init logconf rho_logconf_Init(rho_native_rhopath(), ""); // Disable log to stdout as on android all stdout redirects to /dev/null RHOCONF().setBool("LogToOutput", false, true); LOGCONF().setLogToOutput(false); // Add android system log sink LOGCONF().setLogView(s_logSink); } //-------------------------------------------------------------------------------------------------- RHO_GLOBAL void *rho_nativethread_start() { JNIEnv *env; jvm()->AttachCurrentThread(&env, NULL); store_thr_jnienv(env); return NULL; } //-------------------------------------------------------------------------------------------------- RHO_GLOBAL void rho_nativethread_end(void *) { jvm()->DetachCurrentThread(); } //-------------------------------------------------------------------------------------------------- <|endoftext|>
<commit_before>// $Id$ /////////////////////////////////////////////////////////////////////////////// // // // class for HLT reconstruction // // <Cvetan.Cheshkov@cern.ch> // // <loizides@ikf.uni-frankfurt.de> // /////////////////////////////////////////////////////////////////////////////// // very ugly but it has to work fast #ifdef use_reconstruction #include <Riostream.h> #include <TSystem.h> #include <TArrayF.h> #include <AliRunLoader.h> #include <AliHeader.h> #include <AliGenEventHeader.h> #include <AliESD.h> #include <AliESDHLTtrack.h> #include "AliL3StandardIncludes.h" #include "AliL3Logging.h" #include "AliLevel3.h" #include "AliL3Evaluate.h" #include "AliHLTReconstructor.h" #include "AliL3Transform.h" #include "AliL3Hough.h" #include "AliL3FileHandler.h" #include "AliL3Track.h" #include "AliL3HoughTrack.h" #include "AliL3TrackArray.h" #if __GNUC__== 3 using namespace std; #endif ClassImp(AliHLTReconstructor) AliHLTReconstructor::AliHLTReconstructor(): AliReconstructor() { //constructor AliL3Log::fgLevel=AliL3Log::kWarning; fDoTracker=1; fDoHough=1; fDoBench=0; fDoCleanUp=1; } AliHLTReconstructor::AliHLTReconstructor(Bool_t doTracker, Bool_t doHough): AliReconstructor() { //constructor AliL3Log::fgLevel=AliL3Log::kWarning; fDoTracker=doTracker; fDoHough=doHough; fDoBench=0; fDoCleanUp=1; } AliHLTReconstructor::~AliHLTReconstructor() { //deconstructor if(fDoCleanUp){ char name[256]; gSystem->Exec("rm -rf hlt"); sprintf(name, "rm -f confmap_*.root confmap_*.dat"); gSystem->Exec(name); gSystem->Exec("rm -rf hough"); sprintf(name, "rm -f hough_*.root hough_*.dat"); gSystem->Exec(name); } } void AliHLTReconstructor::Reconstruct(AliRunLoader* runLoader) const { // do the standard and hough reconstruction chain if(!runLoader) { LOG(AliL3Log::kFatal,"AliHLTReconstructor::Reconstruct","RunLoader") <<" Missing RunLoader! 0x0"<<ENDLOG; return; } gSystem->Exec("rm -rf hlt"); gSystem->MakeDirectory("hlt"); gSystem->Exec("rm -rf hough"); gSystem->MakeDirectory("hough"); Bool_t isinit=AliL3Transform::Init(runLoader); if(!isinit){ LOG(AliL3Log::kError,"AliHLTReconstructor::Reconstruct","Transformer") << "Could not create transform settings, please check log for error messages!" << ENDLOG; return; } Int_t nEvents = runLoader->GetNumberOfEvents(); for(Int_t iEvent = 0; iEvent < nEvents; iEvent++) { runLoader->GetEvent(iEvent); if(fDoTracker) ReconstructWithConformalMapping(runLoader,iEvent); if(fDoHough) ReconstructWithHoughTransform(runLoader,iEvent); } } void AliHLTReconstructor::ReconstructWithConformalMapping(AliRunLoader* runLoader,Int_t iEvent) const { // reconstruct with conformal mapper AliLevel3 *fHLT = new AliLevel3(runLoader); fHLT->Init("./", AliLevel3::kRunLoader, 1); Int_t phiSegments = 50; Int_t etaSegments = 100; Int_t trackletlength = 3; Int_t tracklength = 10; Int_t rowscopetracklet = 2; Int_t rowscopetrack = 10; Double_t minPtFit = 0; Double_t maxangle = 0.1745; Double_t goodDist = 5; Double_t maxphi = 0.1; Double_t maxeta = 0.1; Double_t hitChi2Cut = 20; Double_t goodHitChi2 = 5; Double_t trackChi2Cut = 10; Double_t xyerror = -1; Double_t zerror = -1; fHLT->SetClusterFinderParam(xyerror,zerror,kTRUE); fHLT->SetTrackerParam(phiSegments, etaSegments, trackletlength, tracklength, rowscopetracklet, rowscopetrack, minPtFit, maxangle, goodDist, hitChi2Cut, goodHitChi2, trackChi2Cut, 50, maxphi, maxeta, kTRUE); fHLT->SetTrackerParam(phiSegments, etaSegments, trackletlength, tracklength, rowscopetracklet, rowscopetrack, minPtFit, maxangle, goodDist, hitChi2Cut, goodHitChi2, trackChi2Cut, 50, maxphi, maxeta, kFALSE); fHLT->SetMergerParameters(2,3,0.003,0.1,0.05); fHLT->DoMc(); fHLT->DoNonVertexTracking(); /*2 tracking passes, last without vertex contraint.*/ fHLT->WriteFiles("./hlt/"); fHLT->ProcessEvent(0, 35, iEvent); if(fDoBench){ char filename[256]; sprintf(filename, "confmap_%d",iEvent); fHLT->DoBench(filename); } delete fHLT; } void AliHLTReconstructor::ReconstructWithHoughTransform(AliRunLoader* runLoader,Int_t iEvent) const { //reconstruct with hough Float_t ptmin = 0.1*AliL3Transform::GetSolenoidField(); Float_t zvertex = 0; TArrayF mcVertex(3); runLoader->GetHeader()->GenEventHeader()->PrimaryVertex(mcVertex); zvertex = mcVertex[2]; LOG(AliL3Log::kInformational,"AliHLTReconstructor::Reconstruct","HoughTransform") <<" Hough Transform will run with ptmin="<<ptmin<<" and zvertex="<<zvertex<<ENDLOG; AliL3Hough *hough = new AliL3Hough(); hough->SetThreshold(4); hough->SetTransformerParams(76,140,ptmin,-1); hough->SetPeakThreshold(70,-1); hough->SetRunLoader(runLoader); hough->Init("./", kFALSE, 100, kFALSE,4,0,0,zvertex); hough->SetAddHistograms(); for(Int_t slice=0; slice<=35; slice++) { //cout<<"Processing slice "<<slice<<endl; hough->ReadData(slice,iEvent); hough->Transform(); hough->AddAllHistogramsRows(); hough->FindTrackCandidatesRow(); //hough->WriteTracks(slice,"./hough"); hough->AddTracks(); } hough->WriteTracks("./hough"); if(fDoBench){ char filename[256]; sprintf(filename, "hough_%d",iEvent); hough->DoBench(filename); } delete hough; } void AliHLTReconstructor::FillESD(AliRunLoader* runLoader, AliESD* esd) const { //fill the esd file with found tracks Int_t iEvent = runLoader->GetEventNumber(); if(fDoTracker) FillESDforConformalMapping(esd,iEvent); if(fDoHough) FillESDforHoughTransform(esd,iEvent); } void AliHLTReconstructor::FillESDforConformalMapping(AliESD* esd,Int_t iEvent) const { //fill esd with tracks from conformal mapping Int_t slicerange[2]={0,35}; Int_t good = (int)(0.4*AliL3Transform::GetNRows()); Int_t nclusters = (int)(0.4*AliL3Transform::GetNRows()); Int_t nminpointsontracks = (int)(0.3*AliL3Transform::GetNRows()); Float_t ptmin = 0.; Float_t ptmax = 0.; Float_t maxfalseratio = 0.1; AliL3Evaluate *fHLTEval = new AliL3Evaluate("./hlt",nclusters,good,ptmin,ptmax,slicerange); fHLTEval->SetMaxFalseClusters(maxfalseratio); fHLTEval->LoadData(iEvent,kTRUE); fHLTEval->AssignPIDs(); fHLTEval->AssignIDs(); AliL3TrackArray *fTracks = fHLTEval->GetTracks(); if(!fTracks){ delete fHLTEval; return; } for(Int_t i=0; i<fTracks->GetNTracks(); i++) { AliL3Track *tpt = (AliL3Track *)fTracks->GetCheckedTrack(i); if(!tpt) continue; if(tpt->GetNumberOfPoints() < nminpointsontracks) continue; AliESDHLTtrack *esdtrack = new AliESDHLTtrack() ; esdtrack->SetRowRange(tpt->GetFirstRow(),tpt->GetLastRow()); esdtrack->SetNHits(tpt->GetNHits()); esdtrack->SetFirstPoint(tpt->GetFirstPointX(),tpt->GetFirstPointY(),tpt->GetFirstPointZ()); esdtrack->SetLastPoint(tpt->GetLastPointX(),tpt->GetLastPointY(),tpt->GetLastPointZ()); esdtrack->SetPt(tpt->GetPt()); esdtrack->SetPsi(tpt->GetPsi()); esdtrack->SetTgl(tpt->GetTgl()); esdtrack->SetCharge(tpt->GetCharge()); esdtrack->SetMCid(tpt->GetMCid()); esdtrack->SetSector(tpt->GetSector()); esdtrack->SetPID(tpt->GetPID()); esdtrack->ComesFromMainVertex(tpt->ComesFromMainVertex()); esd->AddHLTConfMapTrack(esdtrack); delete esdtrack; } delete fHLTEval; } void AliHLTReconstructor::FillESDforHoughTransform(AliESD* esd,Int_t iEvent) const { //fill esd with tracks from hough char filename[256]; sprintf(filename,"./hough/tracks_%d.raw",iEvent); AliL3FileHandler *tfile = new AliL3FileHandler(); if(!tfile->SetBinaryInput(filename)){ LOG(AliL3Log::kError,"AliHLTReconstructor::FillESDforHoughTransform","Input file") <<" Missing file "<<filename<<ENDLOG; return; } AliL3TrackArray *fTracks = new AliL3TrackArray("AliL3HoughTrack"); tfile->Binary2TrackArray(fTracks); tfile->CloseBinaryInput(); delete tfile; if(!fTracks) return; for(Int_t i=0; i<fTracks->GetNTracks(); i++) { AliL3HoughTrack *tpt = (AliL3HoughTrack *)fTracks->GetCheckedTrack(i); if(!tpt) continue; AliESDHLTtrack *esdtrack = new AliESDHLTtrack() ; esdtrack->SetRowRange(tpt->GetFirstRow(),tpt->GetLastRow()); esdtrack->SetNHits(tpt->GetNHits()); esdtrack->SetFirstPoint(tpt->GetFirstPointX(),tpt->GetFirstPointY(),tpt->GetFirstPointZ()); esdtrack->SetLastPoint(tpt->GetLastPointX(),tpt->GetLastPointY(),tpt->GetLastPointZ()); esdtrack->SetPt(tpt->GetPt()); esdtrack->SetPsi(tpt->GetPsi()); esdtrack->SetTgl(tpt->GetTgl()); esdtrack->SetCharge(tpt->GetCharge()); esdtrack->SetMCid(tpt->GetMCid()); esdtrack->SetWeight(tpt->GetWeight()); esdtrack->SetSector(tpt->GetSector()); esdtrack->SetBinXY(tpt->GetBinX(),tpt->GetBinY(),tpt->GetSizeX(),tpt->GetSizeY()); esdtrack->SetPID(tpt->GetPID()); esdtrack->ComesFromMainVertex(tpt->ComesFromMainVertex()); esd->AddHLTHoughTrack(esdtrack); delete esdtrack; } delete fTracks; } #endif <commit_msg>Additiona protection<commit_after>// $Id$ /////////////////////////////////////////////////////////////////////////////// // // // class for HLT reconstruction // // <Cvetan.Cheshkov@cern.ch> // // <loizides@ikf.uni-frankfurt.de> // /////////////////////////////////////////////////////////////////////////////// // very ugly but it has to work fast #ifdef use_reconstruction #include <Riostream.h> #include <TSystem.h> #include <TArrayF.h> #include <AliRunLoader.h> #include <AliHeader.h> #include <AliGenEventHeader.h> #include <AliESD.h> #include <AliESDHLTtrack.h> #include "AliL3StandardIncludes.h" #include "AliL3Logging.h" #include "AliLevel3.h" #include "AliL3Evaluate.h" #include "AliHLTReconstructor.h" #include "AliL3Transform.h" #include "AliL3Hough.h" #include "AliL3FileHandler.h" #include "AliL3Track.h" #include "AliL3HoughTrack.h" #include "AliL3TrackArray.h" #if __GNUC__== 3 using namespace std; #endif ClassImp(AliHLTReconstructor) AliHLTReconstructor::AliHLTReconstructor(): AliReconstructor() { //constructor AliL3Log::fgLevel=AliL3Log::kWarning; fDoTracker=1; fDoHough=1; fDoBench=0; fDoCleanUp=1; } AliHLTReconstructor::AliHLTReconstructor(Bool_t doTracker, Bool_t doHough): AliReconstructor() { //constructor AliL3Log::fgLevel=AliL3Log::kWarning; fDoTracker=doTracker; fDoHough=doHough; fDoBench=0; fDoCleanUp=1; } AliHLTReconstructor::~AliHLTReconstructor() { //deconstructor if(fDoCleanUp){ char name[256]; gSystem->Exec("rm -rf hlt"); sprintf(name, "rm -f confmap_*.root confmap_*.dat"); gSystem->Exec(name); gSystem->Exec("rm -rf hough"); sprintf(name, "rm -f hough_*.root hough_*.dat"); gSystem->Exec(name); } } void AliHLTReconstructor::Reconstruct(AliRunLoader* runLoader) const { // do the standard and hough reconstruction chain if(!runLoader) { LOG(AliL3Log::kFatal,"AliHLTReconstructor::Reconstruct","RunLoader") <<" Missing RunLoader! 0x0"<<ENDLOG; return; } gSystem->Exec("rm -rf hlt"); gSystem->MakeDirectory("hlt"); gSystem->Exec("rm -rf hough"); gSystem->MakeDirectory("hough"); Bool_t isinit=AliL3Transform::Init(runLoader); if(!isinit){ LOG(AliL3Log::kError,"AliHLTReconstructor::Reconstruct","Transformer") << "Could not create transform settings, please check log for error messages!" << ENDLOG; return; } Int_t nEvents = runLoader->GetNumberOfEvents(); for(Int_t iEvent = 0; iEvent < nEvents; iEvent++) { runLoader->GetEvent(iEvent); if(fDoTracker) ReconstructWithConformalMapping(runLoader,iEvent); if(fDoHough) ReconstructWithHoughTransform(runLoader,iEvent); } } void AliHLTReconstructor::ReconstructWithConformalMapping(AliRunLoader* runLoader,Int_t iEvent) const { // reconstruct with conformal mapper AliLevel3 *fHLT = new AliLevel3(runLoader); fHLT->Init("./", AliLevel3::kRunLoader, 1); Int_t phiSegments = 50; Int_t etaSegments = 100; Int_t trackletlength = 3; Int_t tracklength = 10; Int_t rowscopetracklet = 2; Int_t rowscopetrack = 10; Double_t minPtFit = 0; Double_t maxangle = 0.1745; Double_t goodDist = 5; Double_t maxphi = 0.1; Double_t maxeta = 0.1; Double_t hitChi2Cut = 20; Double_t goodHitChi2 = 5; Double_t trackChi2Cut = 10; Double_t xyerror = -1; Double_t zerror = -1; fHLT->SetClusterFinderParam(xyerror,zerror,kTRUE); fHLT->SetTrackerParam(phiSegments, etaSegments, trackletlength, tracklength, rowscopetracklet, rowscopetrack, minPtFit, maxangle, goodDist, hitChi2Cut, goodHitChi2, trackChi2Cut, 50, maxphi, maxeta, kTRUE); fHLT->SetTrackerParam(phiSegments, etaSegments, trackletlength, tracklength, rowscopetracklet, rowscopetrack, minPtFit, maxangle, goodDist, hitChi2Cut, goodHitChi2, trackChi2Cut, 50, maxphi, maxeta, kFALSE); fHLT->SetMergerParameters(2,3,0.003,0.1,0.05); fHLT->DoMc(); fHLT->DoNonVertexTracking(); /*2 tracking passes, last without vertex contraint.*/ fHLT->WriteFiles("./hlt/"); fHLT->ProcessEvent(0, 35, iEvent); if(fDoBench){ char filename[256]; sprintf(filename, "confmap_%d",iEvent); fHLT->DoBench(filename); } delete fHLT; } void AliHLTReconstructor::ReconstructWithHoughTransform(AliRunLoader* runLoader,Int_t iEvent) const { //reconstruct with hough Float_t ptmin = 0.1*AliL3Transform::GetSolenoidField(); Float_t zvertex = 0; TArrayF mcVertex(3); AliHeader * header = runLoader->GetHeader(); if (header) { AliGenEventHeader * genHeader = header->GenEventHeader(); if (genHeader) genHeader->PrimaryVertex(mcVertex); } zvertex = mcVertex[2]; LOG(AliL3Log::kInformational,"AliHLTReconstructor::Reconstruct","HoughTransform") <<" Hough Transform will run with ptmin="<<ptmin<<" and zvertex="<<zvertex<<ENDLOG; AliL3Hough *hough = new AliL3Hough(); hough->SetThreshold(4); hough->SetTransformerParams(76,140,ptmin,-1); hough->SetPeakThreshold(70,-1); hough->SetRunLoader(runLoader); hough->Init("./", kFALSE, 100, kFALSE,4,0,0,zvertex); hough->SetAddHistograms(); for(Int_t slice=0; slice<=35; slice++) { //cout<<"Processing slice "<<slice<<endl; hough->ReadData(slice,iEvent); hough->Transform(); hough->AddAllHistogramsRows(); hough->FindTrackCandidatesRow(); //hough->WriteTracks(slice,"./hough"); hough->AddTracks(); } hough->WriteTracks("./hough"); if(fDoBench){ char filename[256]; sprintf(filename, "hough_%d",iEvent); hough->DoBench(filename); } delete hough; } void AliHLTReconstructor::FillESD(AliRunLoader* runLoader, AliESD* esd) const { //fill the esd file with found tracks Int_t iEvent = runLoader->GetEventNumber(); if(fDoTracker) FillESDforConformalMapping(esd,iEvent); if(fDoHough) FillESDforHoughTransform(esd,iEvent); } void AliHLTReconstructor::FillESDforConformalMapping(AliESD* esd,Int_t iEvent) const { //fill esd with tracks from conformal mapping Int_t slicerange[2]={0,35}; Int_t good = (int)(0.4*AliL3Transform::GetNRows()); Int_t nclusters = (int)(0.4*AliL3Transform::GetNRows()); Int_t nminpointsontracks = (int)(0.3*AliL3Transform::GetNRows()); Float_t ptmin = 0.; Float_t ptmax = 0.; Float_t maxfalseratio = 0.1; AliL3Evaluate *fHLTEval = new AliL3Evaluate("./hlt",nclusters,good,ptmin,ptmax,slicerange); fHLTEval->SetMaxFalseClusters(maxfalseratio); fHLTEval->LoadData(iEvent,kTRUE); fHLTEval->AssignPIDs(); fHLTEval->AssignIDs(); AliL3TrackArray *fTracks = fHLTEval->GetTracks(); if(!fTracks){ delete fHLTEval; return; } for(Int_t i=0; i<fTracks->GetNTracks(); i++) { AliL3Track *tpt = (AliL3Track *)fTracks->GetCheckedTrack(i); if(!tpt) continue; if(tpt->GetNumberOfPoints() < nminpointsontracks) continue; AliESDHLTtrack *esdtrack = new AliESDHLTtrack() ; esdtrack->SetRowRange(tpt->GetFirstRow(),tpt->GetLastRow()); esdtrack->SetNHits(tpt->GetNHits()); esdtrack->SetFirstPoint(tpt->GetFirstPointX(),tpt->GetFirstPointY(),tpt->GetFirstPointZ()); esdtrack->SetLastPoint(tpt->GetLastPointX(),tpt->GetLastPointY(),tpt->GetLastPointZ()); esdtrack->SetPt(tpt->GetPt()); esdtrack->SetPsi(tpt->GetPsi()); esdtrack->SetTgl(tpt->GetTgl()); esdtrack->SetCharge(tpt->GetCharge()); esdtrack->SetMCid(tpt->GetMCid()); esdtrack->SetSector(tpt->GetSector()); esdtrack->SetPID(tpt->GetPID()); esdtrack->ComesFromMainVertex(tpt->ComesFromMainVertex()); esd->AddHLTConfMapTrack(esdtrack); delete esdtrack; } delete fHLTEval; } void AliHLTReconstructor::FillESDforHoughTransform(AliESD* esd,Int_t iEvent) const { //fill esd with tracks from hough char filename[256]; sprintf(filename,"./hough/tracks_%d.raw",iEvent); AliL3FileHandler *tfile = new AliL3FileHandler(); if(!tfile->SetBinaryInput(filename)){ LOG(AliL3Log::kError,"AliHLTReconstructor::FillESDforHoughTransform","Input file") <<" Missing file "<<filename<<ENDLOG; return; } AliL3TrackArray *fTracks = new AliL3TrackArray("AliL3HoughTrack"); tfile->Binary2TrackArray(fTracks); tfile->CloseBinaryInput(); delete tfile; if(!fTracks) return; for(Int_t i=0; i<fTracks->GetNTracks(); i++) { AliL3HoughTrack *tpt = (AliL3HoughTrack *)fTracks->GetCheckedTrack(i); if(!tpt) continue; AliESDHLTtrack *esdtrack = new AliESDHLTtrack() ; esdtrack->SetRowRange(tpt->GetFirstRow(),tpt->GetLastRow()); esdtrack->SetNHits(tpt->GetNHits()); esdtrack->SetFirstPoint(tpt->GetFirstPointX(),tpt->GetFirstPointY(),tpt->GetFirstPointZ()); esdtrack->SetLastPoint(tpt->GetLastPointX(),tpt->GetLastPointY(),tpt->GetLastPointZ()); esdtrack->SetPt(tpt->GetPt()); esdtrack->SetPsi(tpt->GetPsi()); esdtrack->SetTgl(tpt->GetTgl()); esdtrack->SetCharge(tpt->GetCharge()); esdtrack->SetMCid(tpt->GetMCid()); esdtrack->SetWeight(tpt->GetWeight()); esdtrack->SetSector(tpt->GetSector()); esdtrack->SetBinXY(tpt->GetBinX(),tpt->GetBinY(),tpt->GetSizeX(),tpt->GetSizeY()); esdtrack->SetPID(tpt->GetPID()); esdtrack->ComesFromMainVertex(tpt->ComesFromMainVertex()); esd->AddHLTHoughTrack(esdtrack); delete esdtrack; } delete fTracks; } #endif <|endoftext|>
<commit_before>#include <Network/cUDPServerManager.h> #include <Network/cUDPManager.h> #include <Network/cDeliverManager.h> #include <Network/cEventManager.h> #include <Network/cRequestManager.h> #include <Network/cResponseManager.h> #include <cinder/app/App.h> #include <limits> #include <Node/action.hpp> #include <Utility/MessageBox.h> namespace Network { cUDPServerManager::cUDPServerManager( ) : mRoot( Node::node::create( ) ) { mRoot->set_schedule_update( ); } void cUDPServerManager::close( ) { mSocket.close( ); mIsAccept = false; } void cUDPServerManager::open( ) { mSocket.open( 25565 ); mIsAccept = true; } void cUDPServerManager::closeAccepter( ) { mIsAccept = false; } void cUDPServerManager::openAccepter( ) { mIsAccept = true; } void cUDPServerManager::update( float delta ) { updateRecv( ); updateSend( ); mRoot->entry_update( delta ); } ubyte1 cUDPServerManager::getPlayerId( cNetworkHandle const & handle ) { auto itr = mHandle.find( handle ); if ( itr != mHandle.end( ) ) { return itr->second.id; } else { throw std::runtime_error( "Networkhandle nothing" ); } } void cUDPServerManager::updateSend( ) { // M̂΃obt@[ođB for ( auto& handle : mHandle ) { // ]ĂpPbg𑗂܂B if ( !handle.second.buffer.empty( ) ) { mSocket.write( handle.first, handle.second.buffer.size( ), handle.second.buffer.data( ) ); handle.second.buffer.clear( ); handle.second.buffer.shrink_to_fit( ); } } } void cUDPServerManager::updateRecv( ) { // M̂΃obt@[oăpPbg̕ʂsB while ( !mSocket.emptyChunk( ) ) { auto chunk = mSocket.popChunk( ); if ( cUDPManager::getInstance( )->isConnectPacket( chunk ) || ( mHandle.find( chunk.networkHandle ) != mHandle.end( ) ) ) { cUDPManager::getInstance( )->onReceive( chunk ); } else { // RlNVmȂ܂ܑMĂꍇB } } connection( ); ping( ); } void cUDPServerManager::sendDataBufferAdd( cNetworkHandle const & networkHandle, cPacketBuffer const & packetBuffer ) { auto itr = mHandle.find(networkHandle); if (itr == mHandle.end()) return; auto& buf = itr->second.buffer; // pPbg傫Ȃ肻ȂɑĂ܂܂B if ( 1024 < buf.size( ) ) { mSocket.write( networkHandle, buf.size( ), buf.data( ) ); buf.clear( ); buf.shrink_to_fit( ); } ubyte2 const& byte = packetBuffer.transferredBytes; cBuffer const& buffer = packetBuffer.buffer; buf.resize( buf.size( ) + byte ); memcpy( buf.data( ) + buf.size( ) - byte, &buffer, byte ); } void cUDPServerManager::connection( ) { while ( auto p = cRequestManager::getInstance( )->getReqConnect( ) ) { if ( !mIsAccept ) continue; auto itr = mHandle.insert( std::make_pair( p->mNetworkHandle, std::move( cClientInfo( ) ) ) ); send( p->mNetworkHandle, new Packet::Response::cResConnect( ) ); using namespace Node::Action; auto networkHandle = p->mNetworkHandle; auto act = repeat_forever::create( sequence::create( delay::create( 1.5F ), call_func::create( [ networkHandle, this ] { send( networkHandle, new Packet::Event::cEvePing( ) ); } ) ) ); act->set_tag( itr.first->second.id ); mRoot->run_action( act ); } } void cUDPServerManager::ping( ) { while ( auto p = cDeliverManager::getInstance( )->getDliPing( ) ) { auto itr = mHandle.find(p->mNetworkHandle); if (itr != mHandle.end()) { itr->second.closeSecond = cinder::app::getElapsedSeconds() + 5.0F; } } for ( auto itr = mHandle.begin( ); itr != mHandle.end( ); ) { if ( itr->second.closeSecond < cinder::app::getElapsedSeconds( ) ) { mRoot->remove_action_by_tag( itr->second.id ); mHandle.erase( itr ); continue; } itr++; } } cUDPServerManager::cClientInfo::cClientInfo( ) : closeSecond( cinder::app::getElapsedSeconds( ) + 5.0F ) { // Ƃ肠9lȏ͓܂B if ( idCount == 8 ) { Utility::MessageBoxOk( "NCAg̐ɒB܂B", [ ] { exit( 0 ); } ); } else { id = idCount; } idCount += 1; } ubyte1 cUDPServerManager::cClientInfo::idCount = 0U; }<commit_msg>ローカルプレイヤーの場合タイムアウトをしないようにしました。<commit_after>#include <Network/cUDPServerManager.h> #include <Network/cUDPManager.h> #include <Network/cDeliverManager.h> #include <Network/cEventManager.h> #include <Network/cRequestManager.h> #include <Network/cResponseManager.h> #include <cinder/app/App.h> #include <limits> #include <Node/action.hpp> #include <Utility/MessageBox.h> #include <Network/IpHost.h> namespace Network { cUDPServerManager::cUDPServerManager( ) : mRoot( Node::node::create( ) ) { mRoot->set_schedule_update( ); } void cUDPServerManager::close( ) { mSocket.close( ); mIsAccept = false; } void cUDPServerManager::open( ) { mSocket.open( 25565 ); mIsAccept = true; } void cUDPServerManager::closeAccepter( ) { mIsAccept = false; } void cUDPServerManager::openAccepter( ) { mIsAccept = true; } void cUDPServerManager::update( float delta ) { updateRecv( ); updateSend( ); mRoot->entry_update( delta ); } ubyte1 cUDPServerManager::getPlayerId( cNetworkHandle const & handle ) { auto itr = mHandle.find( handle ); if ( itr != mHandle.end( ) ) { return itr->second.id; } else { throw std::runtime_error( "Networkhandle nothing" ); } } void cUDPServerManager::updateSend( ) { // M̂΃obt@[ođB for ( auto& handle : mHandle ) { // ]ĂpPbg𑗂܂B if ( !handle.second.buffer.empty( ) ) { mSocket.write( handle.first, handle.second.buffer.size( ), handle.second.buffer.data( ) ); handle.second.buffer.clear( ); handle.second.buffer.shrink_to_fit( ); } } } void cUDPServerManager::updateRecv( ) { // M̂΃obt@[oăpPbg̕ʂsB while ( !mSocket.emptyChunk( ) ) { auto chunk = mSocket.popChunk( ); if ( cUDPManager::getInstance( )->isConnectPacket( chunk ) || ( mHandle.find( chunk.networkHandle ) != mHandle.end( ) ) ) { cUDPManager::getInstance( )->onReceive( chunk ); } else { // RlNVmȂ܂ܑMĂꍇB } } connection( ); ping( ); } void cUDPServerManager::sendDataBufferAdd( cNetworkHandle const & networkHandle, cPacketBuffer const & packetBuffer ) { auto itr = mHandle.find(networkHandle); if (itr == mHandle.end()) return; auto& buf = itr->second.buffer; // pPbg傫Ȃ肻ȂɑĂ܂܂B if ( 1024 < buf.size( ) ) { mSocket.write( networkHandle, buf.size( ), buf.data( ) ); buf.clear( ); buf.shrink_to_fit( ); } ubyte2 const& byte = packetBuffer.transferredBytes; cBuffer const& buffer = packetBuffer.buffer; buf.resize( buf.size( ) + byte ); memcpy( buf.data( ) + buf.size( ) - byte, &buffer, byte ); } void cUDPServerManager::connection( ) { while ( auto p = cRequestManager::getInstance( )->getReqConnect( ) ) { if ( !mIsAccept ) continue; auto itr = mHandle.insert( std::make_pair( p->mNetworkHandle, std::move( cClientInfo( ) ) ) ); send( p->mNetworkHandle, new Packet::Response::cResConnect( ) ); using namespace Node::Action; auto networkHandle = p->mNetworkHandle; auto act = repeat_forever::create( sequence::create( delay::create( 1.5F ), call_func::create( [ networkHandle, this ] { send( networkHandle, new Packet::Event::cEvePing( ) ); } ) ) ); act->set_tag( itr.first->second.id ); mRoot->run_action( act ); } } void cUDPServerManager::ping( ) { while ( auto p = cDeliverManager::getInstance( )->getDliPing( ) ) { auto itr = mHandle.find(p->mNetworkHandle); if (itr != mHandle.end()) { itr->second.closeSecond = cinder::app::getElapsedSeconds() + 5.0F; } } for ( auto itr = mHandle.begin( ); itr != mHandle.end( ); ) { // [J̏ꍇ̓JEg_E܂B if (itr->first.ipAddress != Network::getLocalIpAddressHost()) { if (itr->second.closeSecond < cinder::app::getElapsedSeconds()) { mRoot->remove_action_by_tag(itr->second.id); mHandle.erase(itr); continue; } } itr++; } } cUDPServerManager::cClientInfo::cClientInfo( ) : closeSecond( cinder::app::getElapsedSeconds( ) + 5.0F ) { // Ƃ肠9lȏ͓܂B if ( idCount == 8 ) { Utility::MessageBoxOk( "NCAg̐ɒB܂B", [ ] { exit( 0 ); } ); } else { id = idCount; } idCount += 1; } ubyte1 cUDPServerManager::cClientInfo::idCount = 0U; }<|endoftext|>
<commit_before>// Copyright (C) 2016 Elviss Strazdins // This file is part of the Ouzel engine. #define NOMINMAX #include <windows.h> #include "InputWin.h" #include "core/Engine.h" #include "events/EventDispatcher.h" #include "GamepadWin.h" #include "utils/Utils.h" namespace ouzel { namespace input { KeyboardKey InputWin::convertKeyCode(WPARAM wParam) { switch (wParam) { case VK_CANCEL: return KeyboardKey::CANCEL; case VK_BACK: return KeyboardKey::BACKSPACE; case VK_TAB: return KeyboardKey::TAB; case VK_CLEAR: return KeyboardKey::CLEAR; case VK_RETURN: return KeyboardKey::RETURN; case VK_SHIFT: return KeyboardKey::SHIFT; case VK_CONTROL: return KeyboardKey::CONTROL; case VK_MENU: return KeyboardKey::MENU; case VK_PAUSE: return KeyboardKey::PAUSE; case VK_CAPITAL: return KeyboardKey::CAPITAL; // ... Japanese ... case VK_ESCAPE: return KeyboardKey::ESCAPE; // ... IME ... case VK_SPACE: return KeyboardKey::SPACE; case VK_PRIOR: return KeyboardKey::PRIOR; case VK_NEXT: return KeyboardKey::NEXT; case VK_END: return KeyboardKey::END; case VK_HOME: return KeyboardKey::HOME; case VK_LEFT: return KeyboardKey::LEFT; case VK_UP: return KeyboardKey::UP; case VK_RIGHT: return KeyboardKey::RIGHT; case VK_DOWN: return KeyboardKey::DOWN; case VK_SELECT: return KeyboardKey::SELECT; case VK_PRINT: return KeyboardKey::PRINT; case VK_EXECUTE: return KeyboardKey::EXECUT; case VK_SNAPSHOT: return KeyboardKey::SNAPSHOT; case VK_INSERT: return KeyboardKey::INSERT; case VK_DELETE: return KeyboardKey::DEL; case VK_HELP: return KeyboardKey::HELP; case '0': return KeyboardKey::KEY_0; case '1': return KeyboardKey::KEY_1; case '2': return KeyboardKey::KEY_2; case '3': return KeyboardKey::KEY_3; case '4': return KeyboardKey::KEY_4; case '5': return KeyboardKey::KEY_5; case '6': return KeyboardKey::KEY_6; case '7': return KeyboardKey::KEY_7; case '8': return KeyboardKey::KEY_8; case '9': return KeyboardKey::KEY_9; case 'A': return KeyboardKey::KEY_A; case 'B': return KeyboardKey::KEY_B; case 'C': return KeyboardKey::KEY_C; case 'D': return KeyboardKey::KEY_D; case 'E': return KeyboardKey::KEY_E; case 'F': return KeyboardKey::KEY_F; case 'G': return KeyboardKey::KEY_G; case 'H': return KeyboardKey::KEY_H; case 'I': return KeyboardKey::KEY_I; case 'J': return KeyboardKey::KEY_J; case 'K': return KeyboardKey::KEY_K; case 'L': return KeyboardKey::KEY_L; case 'M': return KeyboardKey::KEY_M; case 'N': return KeyboardKey::KEY_N; case 'O': return KeyboardKey::KEY_O; case 'P': return KeyboardKey::KEY_P; case 'Q': return KeyboardKey::KEY_Q; case 'R': return KeyboardKey::KEY_R; case 'S': return KeyboardKey::KEY_S; case 'T': return KeyboardKey::KEY_T; case 'U': return KeyboardKey::KEY_U; case 'V': return KeyboardKey::KEY_V; case 'W': return KeyboardKey::KEY_W; case 'X': return KeyboardKey::KEY_X; case 'Y': return KeyboardKey::KEY_Y; case 'Z': return KeyboardKey::KEY_Z; case VK_LWIN: return KeyboardKey::LWIN; case VK_RWIN: return KeyboardKey::RWIN; case VK_APPS: return KeyboardKey::MENU; case VK_SLEEP: return KeyboardKey::SLEEP; case VK_NUMPAD0: return KeyboardKey::NUMPAD0; case VK_NUMPAD1: return KeyboardKey::NUMPAD1; case VK_NUMPAD2: return KeyboardKey::NUMPAD2; case VK_NUMPAD3: return KeyboardKey::NUMPAD3; case VK_NUMPAD4: return KeyboardKey::NUMPAD4; case VK_NUMPAD5: return KeyboardKey::NUMPAD5; case VK_NUMPAD6: return KeyboardKey::NUMPAD6; case VK_NUMPAD7: return KeyboardKey::NUMPAD7; case VK_NUMPAD8: return KeyboardKey::NUMPAD8; case VK_NUMPAD9: return KeyboardKey::NUMPAD9; case VK_MULTIPLY: return KeyboardKey::MULTIPLY; case VK_ADD: return KeyboardKey::ADD; case VK_SEPARATOR: return KeyboardKey::SEPARATOR; case VK_SUBTRACT: return KeyboardKey::SUBTRACT; case VK_DECIMAL: return KeyboardKey::DECIMAL; case VK_DIVIDE: return KeyboardKey::DIVIDE; case VK_F1: return KeyboardKey::F1; case VK_F2: return KeyboardKey::F2; case VK_F3: return KeyboardKey::F3; case VK_F4: return KeyboardKey::F4; case VK_F5: return KeyboardKey::F5; case VK_F6: return KeyboardKey::F6; case VK_F7: return KeyboardKey::F7; case VK_F8: return KeyboardKey::F8; case VK_F9: return KeyboardKey::F9; case VK_F10: return KeyboardKey::F10; case VK_F11: return KeyboardKey::F11; case VK_F12: return KeyboardKey::F12; case VK_F13: return KeyboardKey::F13; case VK_F14: return KeyboardKey::F14; case VK_F15: return KeyboardKey::F15; case VK_F16: return KeyboardKey::F16; case VK_F17: return KeyboardKey::F17; case VK_F18: return KeyboardKey::F18; case VK_F19: return KeyboardKey::F19; case VK_F20: return KeyboardKey::F20; case VK_F21: return KeyboardKey::F21; case VK_F22: return KeyboardKey::F22; case VK_F23: return KeyboardKey::F23; case VK_F24: return KeyboardKey::F24; case VK_NUMLOCK: return KeyboardKey::NUMLOCK; case VK_SCROLL: return KeyboardKey::SCROLL; case VK_LSHIFT: return KeyboardKey::LSHIFT; case VK_RSHIFT: return KeyboardKey::RSHIFT; case VK_LCONTROL: return KeyboardKey::LCONTROL; case VK_RCONTROL: return KeyboardKey::RCONTROL; case VK_LMENU: return KeyboardKey::LMENU; case VK_RMENU: return KeyboardKey::RMENU; case VK_OEM_1: return KeyboardKey::OEM_1; case VK_OEM_PLUS: return KeyboardKey::PLUS; case VK_OEM_COMMA: return KeyboardKey::COMMA; case VK_OEM_MINUS: return KeyboardKey::MINUS; case VK_OEM_PERIOD: return KeyboardKey::PERIOD; case VK_OEM_2: return KeyboardKey::OEM_2; case VK_OEM_3: return KeyboardKey::OEM_3; case VK_OEM_4: return KeyboardKey::OEM_4; case VK_OEM_5: return KeyboardKey::OEM_5; case VK_OEM_6: return KeyboardKey::OEM_6; case VK_OEM_7: return KeyboardKey::OEM_7; case VK_OEM_8: return KeyboardKey::OEM_8; case VK_OEM_AX: return KeyboardKey::OEM_AX; case VK_OEM_102: return KeyboardKey::OEM_102; // ... misc keys ... } return KeyboardKey::NONE; } uint32_t InputWin::getKeyboardModifiers(WPARAM wParam) { uint32_t modifiers = 0; if (wParam & MK_SHIFT) modifiers |= SHIFT_DOWN; if (wParam & MK_ALT) modifiers |= ALT_DOWN; if (wParam & MK_CONTROL) modifiers |= CONTROL_DOWN; return modifiers; } uint32_t InputWin::getMouseModifiers(WPARAM wParam) { uint32_t modifiers = 0; if (wParam & MK_SHIFT) modifiers |= SHIFT_DOWN; if (wParam & MK_CONTROL) modifiers |= CONTROL_DOWN; if (wParam & MK_LBUTTON) modifiers |= LEFT_MOUSE_DOWN; if (wParam & MK_RBUTTON) modifiers |= RIGHT_MOUSE_DOWN; if (wParam & MK_MBUTTON) modifiers |= MIDDLE_MOUSE_DOWN; return modifiers; } InputWin::InputWin() { } InputWin::~InputWin() { } void InputWin::update() { for (DWORD i = 0; i < XUSER_MAX_COUNT; ++i) { XINPUT_STATE state; memset(&state, 0, sizeof(XINPUT_STATE)); DWORD result = XInputGetState(i, &state); if (result == ERROR_SUCCESS) { if (!gamepads[i]) { gamepads[i].reset(new GamepadWin(static_cast<int32_t>(i))); Event event; event.type = Event::Type::GAMEPAD_CONNECT; event.gamepadEvent.gamepad = gamepads[i]; sharedEngine->getEventDispatcher()->postEvent(event); } gamepads[i]->update(state); } else if (result == ERROR_DEVICE_NOT_CONNECTED) { if (gamepads[i]) { Event event; event.type = Event::Type::GAMEPAD_DISCONNECT; event.gamepadEvent.gamepad = gamepads[i]; sharedEngine->getEventDispatcher()->postEvent(event); gamepads[i].reset(); } } else { log(LOG_LEVEL_WARNING, "Failed to get state for gamepad %d", i); } } } void InputWin::setCursorVisible(bool visible) { cursorVisible = visible; if (cursorVisible) { SetCursor(LoadCursor(nullptr, IDC_ARROW)); } else { SetCursor(nullptr); } } bool InputWin::isCursorVisible() const { return cursorVisible; } } // namespace input } // namespace ouzel <commit_msg>Use GetKeyState to get alt modifier on Windows<commit_after>// Copyright (C) 2016 Elviss Strazdins // This file is part of the Ouzel engine. #define NOMINMAX #include <windows.h> #include "InputWin.h" #include "core/Engine.h" #include "events/EventDispatcher.h" #include "GamepadWin.h" #include "utils/Utils.h" namespace ouzel { namespace input { KeyboardKey InputWin::convertKeyCode(WPARAM wParam) { switch (wParam) { case VK_CANCEL: return KeyboardKey::CANCEL; case VK_BACK: return KeyboardKey::BACKSPACE; case VK_TAB: return KeyboardKey::TAB; case VK_CLEAR: return KeyboardKey::CLEAR; case VK_RETURN: return KeyboardKey::RETURN; case VK_SHIFT: return KeyboardKey::SHIFT; case VK_CONTROL: return KeyboardKey::CONTROL; case VK_MENU: return KeyboardKey::MENU; case VK_PAUSE: return KeyboardKey::PAUSE; case VK_CAPITAL: return KeyboardKey::CAPITAL; // ... Japanese ... case VK_ESCAPE: return KeyboardKey::ESCAPE; // ... IME ... case VK_SPACE: return KeyboardKey::SPACE; case VK_PRIOR: return KeyboardKey::PRIOR; case VK_NEXT: return KeyboardKey::NEXT; case VK_END: return KeyboardKey::END; case VK_HOME: return KeyboardKey::HOME; case VK_LEFT: return KeyboardKey::LEFT; case VK_UP: return KeyboardKey::UP; case VK_RIGHT: return KeyboardKey::RIGHT; case VK_DOWN: return KeyboardKey::DOWN; case VK_SELECT: return KeyboardKey::SELECT; case VK_PRINT: return KeyboardKey::PRINT; case VK_EXECUTE: return KeyboardKey::EXECUT; case VK_SNAPSHOT: return KeyboardKey::SNAPSHOT; case VK_INSERT: return KeyboardKey::INSERT; case VK_DELETE: return KeyboardKey::DEL; case VK_HELP: return KeyboardKey::HELP; case '0': return KeyboardKey::KEY_0; case '1': return KeyboardKey::KEY_1; case '2': return KeyboardKey::KEY_2; case '3': return KeyboardKey::KEY_3; case '4': return KeyboardKey::KEY_4; case '5': return KeyboardKey::KEY_5; case '6': return KeyboardKey::KEY_6; case '7': return KeyboardKey::KEY_7; case '8': return KeyboardKey::KEY_8; case '9': return KeyboardKey::KEY_9; case 'A': return KeyboardKey::KEY_A; case 'B': return KeyboardKey::KEY_B; case 'C': return KeyboardKey::KEY_C; case 'D': return KeyboardKey::KEY_D; case 'E': return KeyboardKey::KEY_E; case 'F': return KeyboardKey::KEY_F; case 'G': return KeyboardKey::KEY_G; case 'H': return KeyboardKey::KEY_H; case 'I': return KeyboardKey::KEY_I; case 'J': return KeyboardKey::KEY_J; case 'K': return KeyboardKey::KEY_K; case 'L': return KeyboardKey::KEY_L; case 'M': return KeyboardKey::KEY_M; case 'N': return KeyboardKey::KEY_N; case 'O': return KeyboardKey::KEY_O; case 'P': return KeyboardKey::KEY_P; case 'Q': return KeyboardKey::KEY_Q; case 'R': return KeyboardKey::KEY_R; case 'S': return KeyboardKey::KEY_S; case 'T': return KeyboardKey::KEY_T; case 'U': return KeyboardKey::KEY_U; case 'V': return KeyboardKey::KEY_V; case 'W': return KeyboardKey::KEY_W; case 'X': return KeyboardKey::KEY_X; case 'Y': return KeyboardKey::KEY_Y; case 'Z': return KeyboardKey::KEY_Z; case VK_LWIN: return KeyboardKey::LWIN; case VK_RWIN: return KeyboardKey::RWIN; case VK_APPS: return KeyboardKey::MENU; case VK_SLEEP: return KeyboardKey::SLEEP; case VK_NUMPAD0: return KeyboardKey::NUMPAD0; case VK_NUMPAD1: return KeyboardKey::NUMPAD1; case VK_NUMPAD2: return KeyboardKey::NUMPAD2; case VK_NUMPAD3: return KeyboardKey::NUMPAD3; case VK_NUMPAD4: return KeyboardKey::NUMPAD4; case VK_NUMPAD5: return KeyboardKey::NUMPAD5; case VK_NUMPAD6: return KeyboardKey::NUMPAD6; case VK_NUMPAD7: return KeyboardKey::NUMPAD7; case VK_NUMPAD8: return KeyboardKey::NUMPAD8; case VK_NUMPAD9: return KeyboardKey::NUMPAD9; case VK_MULTIPLY: return KeyboardKey::MULTIPLY; case VK_ADD: return KeyboardKey::ADD; case VK_SEPARATOR: return KeyboardKey::SEPARATOR; case VK_SUBTRACT: return KeyboardKey::SUBTRACT; case VK_DECIMAL: return KeyboardKey::DECIMAL; case VK_DIVIDE: return KeyboardKey::DIVIDE; case VK_F1: return KeyboardKey::F1; case VK_F2: return KeyboardKey::F2; case VK_F3: return KeyboardKey::F3; case VK_F4: return KeyboardKey::F4; case VK_F5: return KeyboardKey::F5; case VK_F6: return KeyboardKey::F6; case VK_F7: return KeyboardKey::F7; case VK_F8: return KeyboardKey::F8; case VK_F9: return KeyboardKey::F9; case VK_F10: return KeyboardKey::F10; case VK_F11: return KeyboardKey::F11; case VK_F12: return KeyboardKey::F12; case VK_F13: return KeyboardKey::F13; case VK_F14: return KeyboardKey::F14; case VK_F15: return KeyboardKey::F15; case VK_F16: return KeyboardKey::F16; case VK_F17: return KeyboardKey::F17; case VK_F18: return KeyboardKey::F18; case VK_F19: return KeyboardKey::F19; case VK_F20: return KeyboardKey::F20; case VK_F21: return KeyboardKey::F21; case VK_F22: return KeyboardKey::F22; case VK_F23: return KeyboardKey::F23; case VK_F24: return KeyboardKey::F24; case VK_NUMLOCK: return KeyboardKey::NUMLOCK; case VK_SCROLL: return KeyboardKey::SCROLL; case VK_LSHIFT: return KeyboardKey::LSHIFT; case VK_RSHIFT: return KeyboardKey::RSHIFT; case VK_LCONTROL: return KeyboardKey::LCONTROL; case VK_RCONTROL: return KeyboardKey::RCONTROL; case VK_LMENU: return KeyboardKey::LMENU; case VK_RMENU: return KeyboardKey::RMENU; case VK_OEM_1: return KeyboardKey::OEM_1; case VK_OEM_PLUS: return KeyboardKey::PLUS; case VK_OEM_COMMA: return KeyboardKey::COMMA; case VK_OEM_MINUS: return KeyboardKey::MINUS; case VK_OEM_PERIOD: return KeyboardKey::PERIOD; case VK_OEM_2: return KeyboardKey::OEM_2; case VK_OEM_3: return KeyboardKey::OEM_3; case VK_OEM_4: return KeyboardKey::OEM_4; case VK_OEM_5: return KeyboardKey::OEM_5; case VK_OEM_6: return KeyboardKey::OEM_6; case VK_OEM_7: return KeyboardKey::OEM_7; case VK_OEM_8: return KeyboardKey::OEM_8; case VK_OEM_AX: return KeyboardKey::OEM_AX; case VK_OEM_102: return KeyboardKey::OEM_102; // ... misc keys ... } return KeyboardKey::NONE; } uint32_t InputWin::getKeyboardModifiers(WPARAM wParam) { uint32_t modifiers = 0; if (wParam & MK_SHIFT) modifiers |= SHIFT_DOWN; if (wParam & MK_ALT) modifiers |= ALT_DOWN; if (wParam & MK_CONTROL) modifiers |= CONTROL_DOWN; return modifiers; } uint32_t InputWin::getMouseModifiers(WPARAM wParam) { uint32_t modifiers = 0; if (wParam & MK_SHIFT) modifiers |= SHIFT_DOWN; if (GetKeyState(VK_MENU) & 0x8000) modifiers |= ALT_DOWN; if (wParam & MK_CONTROL) modifiers |= CONTROL_DOWN; if (wParam & MK_LBUTTON) modifiers |= LEFT_MOUSE_DOWN; if (wParam & MK_RBUTTON) modifiers |= RIGHT_MOUSE_DOWN; if (wParam & MK_MBUTTON) modifiers |= MIDDLE_MOUSE_DOWN; return modifiers; } InputWin::InputWin() { } InputWin::~InputWin() { } void InputWin::update() { for (DWORD i = 0; i < XUSER_MAX_COUNT; ++i) { XINPUT_STATE state; memset(&state, 0, sizeof(XINPUT_STATE)); DWORD result = XInputGetState(i, &state); if (result == ERROR_SUCCESS) { if (!gamepads[i]) { gamepads[i].reset(new GamepadWin(static_cast<int32_t>(i))); Event event; event.type = Event::Type::GAMEPAD_CONNECT; event.gamepadEvent.gamepad = gamepads[i]; sharedEngine->getEventDispatcher()->postEvent(event); } gamepads[i]->update(state); } else if (result == ERROR_DEVICE_NOT_CONNECTED) { if (gamepads[i]) { Event event; event.type = Event::Type::GAMEPAD_DISCONNECT; event.gamepadEvent.gamepad = gamepads[i]; sharedEngine->getEventDispatcher()->postEvent(event); gamepads[i].reset(); } } else { log(LOG_LEVEL_WARNING, "Failed to get state for gamepad %d", i); } } } void InputWin::setCursorVisible(bool visible) { cursorVisible = visible; if (cursorVisible) { SetCursor(LoadCursor(nullptr, IDC_ARROW)); } else { SetCursor(nullptr); } } bool InputWin::isCursorVisible() const { return cursorVisible; } } // namespace input } // namespace ouzel <|endoftext|>
<commit_before>#include <QMessageBox> #include "sharefolderwindow.h" #include "ui_sharefolderwindow.h" #include "binapi.h" #include "pcloudapp.h" #include "common.h" ShareFolderWindow::ShareFolderWindow(PCloudApp *a, QWidget *parent) : QMainWindow(parent), ui(new Ui::ShareFolderWindow) { app=a; setWindowIcon(QIcon(WINDOW_ICON)); ui->setupUi(this); connect(ui->cancelbutton, SIGNAL(clicked()), this, SLOT(hide())); connect(ui->sharebutton, SIGNAL(clicked()), this, SLOT(shareFolder())); connect(ui->dirtree, SIGNAL(currentItemChanged(QTreeWidgetItem *, QTreeWidgetItem *)), this, SLOT(dirSelected(QTreeWidgetItem *))); } ShareFolderWindow::~ShareFolderWindow() { delete ui; } void ShareFolderWindow::closeEvent(QCloseEvent *event) { hide(); event->ignore(); } static QList<QTreeWidgetItem *> binresToQList(binresult *res){ QList<QTreeWidgetItem *> items; QTreeWidgetItem *item; binresult *e; uint32_t i; for (i=0; i<res->length; i++){ e=res->array[i]; item=new QTreeWidgetItem((QTreeWidget*)0, QStringList(QString(find_res(e, "name")->str))); item->setData(1, Qt::UserRole, (qulonglong)find_res(e, "folderid")->num); item->addChildren(binresToQList(find_res(e, "contents"))); items.append(item); } return items; } void ShareFolderWindow::showEvent(QShowEvent *) { apisock *conn; binresult *res, *result; QByteArray auth=app->settings->get("auth").toUtf8(); if (!(conn=app->getAPISock())){ showError("Could not connect to server. Check your Internet connection."); return; } ui->dirtree->clear(); ui->dirtree->setColumnCount(1); ui->dirtree->setHeaderLabels(QStringList("Name")); res=send_command(conn, "listfolder", P_LSTR("auth", auth.constData(), auth.size()), P_STR("filtermeta", "contents,folderid,name"), P_NUM("folderid", 0), P_BOOL("recursive", 1), P_BOOL("nofiles", 1), P_BOOL("noshares", 1)); api_close(conn); result=find_res(res, "result"); if (!result){ showError("Could not connect to server. Check your Internet connection."); free(res); return; } if (result->num!=0){ showError(find_res(res, "error")->str); free(res); return; } result=find_res(find_res(res, "metadata"), "contents"); ui->dirtree->insertTopLevelItems(0, binresToQList(result)); free(res); } void ShareFolderWindow::showError(const QString &err){ ui->error->setText(err); } void ShareFolderWindow::verifyEmail(apisock *conn){ QMessageBox::StandardButton reply; reply=QMessageBox::question(this, "Please verify your e-mail address", "E-mail address verification is required to share folders. Send verification email now?", QMessageBox::Yes|QMessageBox::No); if (reply==QMessageBox::Yes){ QByteArray auth=app->settings->get("auth").toUtf8(); binresult *res; res=send_command(conn, "sendverificationemail", P_LSTR("auth", auth.constData(), auth.size())); free(res); QMessageBox::information(this, "Please check your e-mail", "E-mail verification sent to: "+app->username); } } void ShareFolderWindow::shareFolder() { QByteArray auth=app->settings->get("auth").toUtf8(); QStringList mails=ui->email->text().split(","); QByteArray name=ui->sharename->text().toUtf8(); uint64_t folderid=ui->dirtree->currentItem()->data(1, Qt::UserRole).toULongLong(); uint32_t perms=(ui->permCreate->isChecked()?1:0)+ (ui->permModify->isChecked()?2:0)+ (ui->permDelete->isChecked()?4:0); apisock *conn=app->getAPISock(); binresult *res, *result; int i; if (!conn){ showError("Could not connect to server. Check your Internet connection."); return; } for (i=0; i<mails.count(); i++){ QByteArray mail=mails[i].trimmed().toUtf8(); res=send_command(conn, "sharefolder", P_LSTR("auth", auth.constData(), auth.size()), P_LSTR("mail", mail.constData(), mail.size()), P_LSTR("name", name.constData(), name.size()), P_NUM("folderid", folderid), P_NUM("permissions", perms)); result=find_res(res, "result"); if (!result){ showError("Could not connect to server. Check your Internet connection."); free(res); api_close(conn); return; } if (result->num==2014){ free(res); verifyEmail(conn); api_close(conn); return; } if (result->num!=0){ showError(find_res(res, "error")->str); api_close(conn); free(res); return; } free(res); } api_close(conn); ui->error->setText(""); ui->email->setText(""); hide(); } void ShareFolderWindow::dirSelected(QTreeWidgetItem *dir) { ui->sharename->setText(dir->text(0)); } <commit_msg>remove successfully shared emails when sharing with multiple recipients<commit_after>#include <QMessageBox> #include "sharefolderwindow.h" #include "ui_sharefolderwindow.h" #include "binapi.h" #include "pcloudapp.h" #include "common.h" ShareFolderWindow::ShareFolderWindow(PCloudApp *a, QWidget *parent) : QMainWindow(parent), ui(new Ui::ShareFolderWindow) { app=a; setWindowIcon(QIcon(WINDOW_ICON)); ui->setupUi(this); connect(ui->cancelbutton, SIGNAL(clicked()), this, SLOT(hide())); connect(ui->sharebutton, SIGNAL(clicked()), this, SLOT(shareFolder())); connect(ui->dirtree, SIGNAL(currentItemChanged(QTreeWidgetItem *, QTreeWidgetItem *)), this, SLOT(dirSelected(QTreeWidgetItem *))); } ShareFolderWindow::~ShareFolderWindow() { delete ui; } void ShareFolderWindow::closeEvent(QCloseEvent *event) { hide(); event->ignore(); } static QList<QTreeWidgetItem *> binresToQList(binresult *res){ QList<QTreeWidgetItem *> items; QTreeWidgetItem *item; binresult *e; uint32_t i; for (i=0; i<res->length; i++){ e=res->array[i]; item=new QTreeWidgetItem((QTreeWidget*)0, QStringList(QString(find_res(e, "name")->str))); item->setData(1, Qt::UserRole, (qulonglong)find_res(e, "folderid")->num); item->addChildren(binresToQList(find_res(e, "contents"))); items.append(item); } return items; } void ShareFolderWindow::showEvent(QShowEvent *) { apisock *conn; binresult *res, *result; QByteArray auth=app->settings->get("auth").toUtf8(); if (!(conn=app->getAPISock())){ showError("Could not connect to server. Check your Internet connection."); return; } ui->dirtree->clear(); ui->dirtree->setColumnCount(1); ui->dirtree->setHeaderLabels(QStringList("Name")); res=send_command(conn, "listfolder", P_LSTR("auth", auth.constData(), auth.size()), P_STR("filtermeta", "contents,folderid,name"), P_NUM("folderid", 0), P_BOOL("recursive", 1), P_BOOL("nofiles", 1), P_BOOL("noshares", 1)); api_close(conn); result=find_res(res, "result"); if (!result){ showError("Could not connect to server. Check your Internet connection."); free(res); return; } if (result->num!=0){ showError(find_res(res, "error")->str); free(res); return; } result=find_res(find_res(res, "metadata"), "contents"); ui->dirtree->insertTopLevelItems(0, binresToQList(result)); free(res); } void ShareFolderWindow::showError(const QString &err){ ui->error->setText(err); } void ShareFolderWindow::verifyEmail(apisock *conn){ QMessageBox::StandardButton reply; reply=QMessageBox::question(this, "Please verify your e-mail address", "E-mail address verification is required to share folders. Send verification email now?", QMessageBox::Yes|QMessageBox::No); if (reply==QMessageBox::Yes){ QByteArray auth=app->settings->get("auth").toUtf8(); binresult *res; res=send_command(conn, "sendverificationemail", P_LSTR("auth", auth.constData(), auth.size())); free(res); QMessageBox::information(this, "Please check your e-mail", "E-mail verification sent to: "+app->username); } } void ShareFolderWindow::shareFolder() { QByteArray auth=app->settings->get("auth").toUtf8(); QStringList mails=ui->email->text().split(","); QByteArray name=ui->sharename->text().toUtf8(); uint64_t folderid=ui->dirtree->currentItem()->data(1, Qt::UserRole).toULongLong(); uint32_t perms=(ui->permCreate->isChecked()?1:0)+ (ui->permModify->isChecked()?2:0)+ (ui->permDelete->isChecked()?4:0); apisock *conn=app->getAPISock(); binresult *res, *result; if (!conn){ showError("Could not connect to server. Check your Internet connection."); return; } while (!mails.empty()){ QByteArray mail=mails[0].trimmed().toUtf8(); ui->email->setText(mails.join(",")); res=send_command(conn, "sharefolder", P_LSTR("auth", auth.constData(), auth.size()), P_LSTR("mail", mail.constData(), mail.size()), P_LSTR("name", name.constData(), name.size()), P_NUM("folderid", folderid), P_NUM("permissions", perms)); result=find_res(res, "result"); if (!result){ showError("Could not connect to server. Check your Internet connection."); free(res); api_close(conn); return; } if (result->num==2014){ free(res); verifyEmail(conn); api_close(conn); return; } if (result->num!=0){ showError(find_res(res, "error")->str); api_close(conn); free(res); return; } free(res); mails.removeFirst(); } api_close(conn); ui->error->setText(""); ui->email->setText(""); hide(); } void ShareFolderWindow::dirSelected(QTreeWidgetItem *dir) { ui->sharename->setText(dir->text(0)); } <|endoftext|>
<commit_before>#include "plat.h" #ifdef PWRE_PLAT_X11 #include "x11.hpp" #include <X11/Xutil.h> #include <unordered_map> #include "zk_rwlock.hpp" #include <mutex> #include <atomic> #include <climits> #include <cstring> namespace Pwre { Atom netWmName; Atom utf8Str; Atom wmDelWnd; Atom wmProtocols; Atom netWmState; #define netWmStateRemove 0 #define netWmStateAdd 1 #define netWmStateToggle 2 Atom netWmStateHide; Atom netWmStateMaxVert; Atom netWmStateMaxHorz; Atom netWmStateFullscr; Atom motifWmHints; namespace System { std::unordered_map<XWindow, Window *> wndMap; _shared_mutex wndMapLock; std::mutex xEventMux; std::atomic<int> wndCount; Display *dpy; XWindow root; bool Init() { XInitThreads(); dpy = XOpenDisplay(NULL); if (!dpy) { std::cout << "Pwre: X11.XOpenDisplay error!" << std::endl; return false; } root = XRootWindow(dpy, 0); netWmName = XInternAtom(dpy, "_NET_WM_NAME", False); utf8Str = XInternAtom(dpy, "UTF8_STRING", False); wmDelWnd = XInternAtom(dpy, "WM_DELETE_WINDOW", False); wmProtocols = XInternAtom(dpy, "WM_PROTOCOLS", False); netWmState = XInternAtom(dpy, "_NET_WM_STATE", False); netWmStateHide = XInternAtom(dpy, "_NET_WM_STATE_HIDDEN", False); netWmStateMaxVert = XInternAtom(dpy, "_NET_WM_STATE_MAXIMIZED_VERT", False); netWmStateMaxHorz = XInternAtom(dpy, "_NET_WM_STATE_MAXIMIZED_HORZ", False); netWmStateFullscr = XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN", False); motifWmHints = XInternAtom(dpy, "_MOTIF_WM_HINTS", True); wndCount = 0; return true; } #define _XEVENT_SYNC(_wnd, _event, _conds, _bingo) { \ XEvent event; \ while (System::XEventRecv(&event, false)) { \ if ( \ event.xany.window == _wnd && \ event.xany.type == _event \ _conds \ ) { \ _bingo \ break; \ } \ } \ } bool XEventRecv(XEvent *event, bool mux) { if (mux) { System::xEventMux.lock(); XNextEvent(dpy, event); System::xEventMux.unlock(); } else { XNextEvent(dpy, event); } System::wndMapLock.lock_shared(); auto wnd = System::wndMap[event->xany.window]; System::wndMapLock.unlock_shared(); if (wnd) { switch (event->xany.type) { case ConfigureNotify: wnd->OnSize.Receive(event->xconfigure.width, event->xconfigure.height); break; case Expose: wnd->OnPaint.Receive(); break; case ClientMessage: if (event->xclient.message_type == wmProtocols && (Atom)event->xclient.data.l[0] == wmDelWnd) { if (!wnd->OnClose.Accept()) { return true; } bool ret = false; System::xEventMux.lock(); XDestroyWindow(dpy, event->xany.window); _XEVENT_SYNC( wnd->_m->xWnd, DestroyNotify, , ret = true; ) System::xEventMux.unlock(); return ret; } break; case DestroyNotify: wnd->OnDestroy.Receive(); System::wndMapLock.lock(); System::wndMap.erase(wnd->_m->xWnd); System::wndMapLock.unlock(); if (!--wndCount) { System::wndMap.clear(); XCloseDisplay(dpy); return false; } } } return true; } bool Step() { XEvent event; while (XPending(dpy)) { if (!XEventRecv(&event, true)) { return false; } } return true; } void Run() { XEvent event; while (XEventRecv(&event, true)); } } /* System */ bool WindowCoreConstructor( Window *wnd, uint64_t hints, int depth, Visual *visual, unsigned long valuemask, XSetWindowAttributes *swa ) { wnd->_m->xWnd = XCreateWindow( System::dpy, System::root, 0, 0, 150, 150, 0, depth, InputOutput, visual, valuemask, swa ); if (!wnd->_m->xWnd) { std::cout << "Pwre: X11.XCreateSimpleWindow error!" << std::endl; return false; } XSetWMProtocols(System::dpy, wnd->_m->xWnd, &wmDelWnd, 1); System::wndCount++; System::wndMapLock.lock(); System::wndMap[wnd->_m->xWnd] = wnd; System::wndMapLock.unlock(); return true; } Window::Window(uint64_t hints) { _m = new _BlackBox; if (hints != (uint64_t)-1) { XSetWindowAttributes swa; swa.event_mask = ExposureMask | KeyPressMask | StructureNotifyMask; WindowCoreConstructor( this, hints, XDefaultDepth(System::dpy, 0), XDefaultVisual(System::dpy, 0), CWEventMask, &swa ); } } Window::~Window() { delete _m; } uintptr_t Window::NativeObj() { return (uintptr_t)_m->xWnd; } void Window::Close() { if (OnClose.Accept()) { Destroy(); } } void Window::Destroy() { XDestroyWindow(System::dpy, _m->xWnd); } std::string Window::Title() { std::string title; Atom type; int format; unsigned long nitems, after; unsigned char *data; if (Success == XGetWindowProperty(System::dpy, _m->xWnd, netWmName, 0, LONG_MAX, False, utf8Str, &type, &format, &nitems, &after, &data) && data) { title = (const char *)data; XFree(data); } return title; } void Window::Retitle(const std::string &title) { XChangeProperty(System::dpy, _m->xWnd, netWmName, utf8Str, 8, PropModeReplace, (const unsigned char*)title.c_str(), title.size()); } #include "fixpos.hpp" void Window::Move(int x, int y) { XWindowAttributes wa; XGetWindowAttributes(System::dpy, _m->xWnd, &wa); FixPos(x, y, wa.width, wa.height); System::xEventMux.lock(); int err = XMoveWindow(System::dpy, _m->xWnd, x, y); if (err != BadValue && err != BadWindow && err != BadMatch) { _XEVENT_SYNC( _m->xWnd, ConfigureNotify, && ( event.xconfigure.x != 0 || event.xconfigure.y != 0 ), ) } System::xEventMux.unlock(); } void Window::Size(int &width, int &height) { XWindowAttributes wa; XGetWindowAttributes(System::dpy, _m->xWnd, &wa); if (width) { width = wa.width; } if (height) { height = wa.height; } } void Window::Resize(int width, int height) { System::xEventMux.lock(); int err = XResizeWindow(System::dpy, _m->xWnd, width, height); if (err != BadValue && err != BadWindow) { _XEVENT_SYNC( _m->xWnd, ConfigureNotify, && event.xconfigure.width == width && event.xconfigure.height == height, ) } System::xEventMux.unlock(); } static void Visible(Window *wnd) { XWindowAttributes wa; XGetWindowAttributes(System::dpy, wnd->_m->xWnd, &wa); System::xEventMux.lock(); if (wa.map_state != IsViewable && XMapRaised(System::dpy, wnd->_m->xWnd) != BadWindow && wa.map_state == IsUnmapped) { _XEVENT_SYNC( wnd->_m->xWnd, MapNotify, , ) } System::xEventMux.unlock(); } void Window::AddStates(uint32_t type) { XEvent event; switch (type) { case PWRE_STATE_VISIBLE: Visible(this); break; case PWRE_STATE_MINIMIZE: Visible(this); XIconifyWindow(System::dpy, _m->xWnd, 0); break; case PWRE_STATE_MAXIMIZE: Visible(this); memset(&event, 0, sizeof(event)); event.type = ClientMessage; event.xclient.window = _m->xWnd; event.xclient.message_type = netWmState; event.xclient.format = 32; event.xclient.data.l[0] = netWmStateAdd; event.xclient.data.l[1] = netWmStateMaxVert; event.xclient.data.l[2] = netWmStateMaxHorz; XSendEvent(System::dpy, System::root, False, StructureNotifyMask, &event); break; case PWRE_STATE_FULLSCREEN: Visible(this); memset(&event, 0, sizeof(event)); event.type = ClientMessage; event.xclient.window = _m->xWnd; event.xclient.message_type = netWmState; event.xclient.format = 32; event.xclient.data.l[0] = netWmStateAdd; event.xclient.data.l[1] = netWmStateFullscr; XSendEvent(System::dpy, System::root, False, StructureNotifyMask, &event); } return; } void Window::RmStates(uint32_t type) { XEvent event; switch (type) { case PWRE_STATE_VISIBLE: Visible(this); break; case PWRE_STATE_MINIMIZE: Visible(this); break; case PWRE_STATE_MAXIMIZE: Visible(this); memset(&event, 0, sizeof(event)); event.type = ClientMessage; event.xclient.window = _m->xWnd; event.xclient.message_type = netWmState; event.xclient.format = 32; event.xclient.data.l[0] = netWmStateRemove; event.xclient.data.l[1] = netWmStateMaxVert; event.xclient.data.l[2] = netWmStateMaxHorz; XSendEvent(System::dpy, System::root, False, StructureNotifyMask, &event); break; case PWRE_STATE_FULLSCREEN: Visible(this); memset(&event, 0, sizeof(event)); event.type = ClientMessage; event.xclient.window = _m->xWnd; event.xclient.message_type = netWmState; event.xclient.format = 32; event.xclient.data.l[0] = netWmStateRemove; event.xclient.data.l[1] = netWmStateFullscr; XSendEvent(System::dpy, System::root, False, StructureNotifyMask, &event); } } bool Window::HasStates(uint32_t type) { return false; } const unsigned MWM_HINTS_DECORATIONS = (1 << 1); const int PROP_MOTIF_WM_HINTS_ELEMENTS = 5; struct PropMotifWmHints { unsigned long flags; unsigned long functions; unsigned long decorations; long inputMode; unsigned long status; }; void Window::Less(bool less) { PropMotifWmHints motifHints; motifHints.flags = MWM_HINTS_DECORATIONS; motifHints.decorations = 0; XChangeProperty(System::dpy, _m->xWnd, motifWmHints, motifWmHints, 32, PropModeReplace, (unsigned char *) &motifHints, PROP_MOTIF_WM_HINTS_ELEMENTS); } } /* Pwre */ #endif // PWRE_PLAT_X11 <commit_msg>Use std::recursive_mutex<commit_after>#include "plat.h" #ifdef PWRE_PLAT_X11 #include "x11.hpp" #include <X11/Xutil.h> #include <unordered_map> #include "zk_rwlock.hpp" #include <mutex> #include <atomic> #include <climits> #include <cstring> namespace Pwre { Atom netWmName; Atom utf8Str; Atom wmDelWnd; Atom wmProtocols; Atom netWmState; #define netWmStateRemove 0 #define netWmStateAdd 1 #define netWmStateToggle 2 Atom netWmStateHide; Atom netWmStateMaxVert; Atom netWmStateMaxHorz; Atom netWmStateFullscr; Atom motifWmHints; namespace System { std::unordered_map<XWindow, Window *> wndMap; _shared_mutex wndMapLock; std::recursive_mutex xEventMux; std::atomic<int> wndCount; Display *dpy; XWindow root; bool Init() { XInitThreads(); dpy = XOpenDisplay(NULL); if (!dpy) { std::cout << "Pwre: X11.XOpenDisplay error!" << std::endl; return false; } root = XRootWindow(dpy, 0); netWmName = XInternAtom(dpy, "_NET_WM_NAME", False); utf8Str = XInternAtom(dpy, "UTF8_STRING", False); wmDelWnd = XInternAtom(dpy, "WM_DELETE_WINDOW", False); wmProtocols = XInternAtom(dpy, "WM_PROTOCOLS", False); netWmState = XInternAtom(dpy, "_NET_WM_STATE", False); netWmStateHide = XInternAtom(dpy, "_NET_WM_STATE_HIDDEN", False); netWmStateMaxVert = XInternAtom(dpy, "_NET_WM_STATE_MAXIMIZED_VERT", False); netWmStateMaxHorz = XInternAtom(dpy, "_NET_WM_STATE_MAXIMIZED_HORZ", False); netWmStateFullscr = XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN", False); motifWmHints = XInternAtom(dpy, "_MOTIF_WM_HINTS", True); wndCount = 0; return true; } #define _XEVENT_SYNC(_wnd, _event, _conds, _bingo) { \ XEvent event; \ while (System::XEventRecv(&event, false)) { \ if ( \ event.xany.window == _wnd && \ event.xany.type == _event \ _conds \ ) { \ _bingo \ break; \ } \ } \ } bool XEventRecv(XEvent *event, bool mux) { if (mux) { System::xEventMux.lock(); XNextEvent(dpy, event); System::xEventMux.unlock(); } else { XNextEvent(dpy, event); } System::wndMapLock.lock_shared(); auto wnd = System::wndMap[event->xany.window]; System::wndMapLock.unlock_shared(); if (wnd) { switch (event->xany.type) { case ConfigureNotify: wnd->OnSize.Receive(event->xconfigure.width, event->xconfigure.height); break; case Expose: wnd->OnPaint.Receive(); break; case ClientMessage: if (event->xclient.message_type == wmProtocols && (Atom)event->xclient.data.l[0] == wmDelWnd) { if (!wnd->OnClose.Accept()) { return true; } bool ret = false; System::xEventMux.lock(); XDestroyWindow(dpy, event->xany.window); _XEVENT_SYNC( wnd->_m->xWnd, DestroyNotify, , ret = true; ) System::xEventMux.unlock(); return ret; } break; case DestroyNotify: wnd->OnDestroy.Receive(); System::wndMapLock.lock(); System::wndMap.erase(wnd->_m->xWnd); System::wndMapLock.unlock(); if (!--wndCount) { System::wndMap.clear(); XCloseDisplay(dpy); return false; } } } return true; } bool Step() { XEvent event; while (XPending(dpy)) { if (!XEventRecv(&event, true)) { return false; } } return true; } void Run() { XEvent event; while (XEventRecv(&event, true)); } } /* System */ bool WindowCoreConstructor( Window *wnd, uint64_t hints, int depth, Visual *visual, unsigned long valuemask, XSetWindowAttributes *swa ) { wnd->_m->xWnd = XCreateWindow( System::dpy, System::root, 0, 0, 150, 150, 0, depth, InputOutput, visual, valuemask, swa ); if (!wnd->_m->xWnd) { std::cout << "Pwre: X11.XCreateSimpleWindow error!" << std::endl; return false; } XSetWMProtocols(System::dpy, wnd->_m->xWnd, &wmDelWnd, 1); System::wndCount++; System::wndMapLock.lock(); System::wndMap[wnd->_m->xWnd] = wnd; System::wndMapLock.unlock(); return true; } Window::Window(uint64_t hints) { _m = new _BlackBox; if (hints != (uint64_t)-1) { XSetWindowAttributes swa; swa.event_mask = ExposureMask | KeyPressMask | StructureNotifyMask; WindowCoreConstructor( this, hints, XDefaultDepth(System::dpy, 0), XDefaultVisual(System::dpy, 0), CWEventMask, &swa ); } } Window::~Window() { delete _m; } uintptr_t Window::NativeObj() { return (uintptr_t)_m->xWnd; } void Window::Close() { if (OnClose.Accept()) { Destroy(); } } void Window::Destroy() { XDestroyWindow(System::dpy, _m->xWnd); } std::string Window::Title() { std::string title; Atom type; int format; unsigned long nitems, after; unsigned char *data; if (Success == XGetWindowProperty(System::dpy, _m->xWnd, netWmName, 0, LONG_MAX, False, utf8Str, &type, &format, &nitems, &after, &data) && data) { title = (const char *)data; XFree(data); } return title; } void Window::Retitle(const std::string &title) { XChangeProperty(System::dpy, _m->xWnd, netWmName, utf8Str, 8, PropModeReplace, (const unsigned char*)title.c_str(), title.size()); } #include "fixpos.hpp" void Window::Move(int x, int y) { XWindowAttributes wa; XGetWindowAttributes(System::dpy, _m->xWnd, &wa); FixPos(x, y, wa.width, wa.height); System::xEventMux.lock(); int err = XMoveWindow(System::dpy, _m->xWnd, x, y); if (err != BadValue && err != BadWindow && err != BadMatch) { _XEVENT_SYNC( _m->xWnd, ConfigureNotify, && ( event.xconfigure.x != 0 || event.xconfigure.y != 0 ), ) } System::xEventMux.unlock(); } void Window::Size(int &width, int &height) { XWindowAttributes wa; XGetWindowAttributes(System::dpy, _m->xWnd, &wa); if (width) { width = wa.width; } if (height) { height = wa.height; } } void Window::Resize(int width, int height) { System::xEventMux.lock(); int err = XResizeWindow(System::dpy, _m->xWnd, width, height); if (err != BadValue && err != BadWindow) { _XEVENT_SYNC( _m->xWnd, ConfigureNotify, && event.xconfigure.width == width && event.xconfigure.height == height, ) } System::xEventMux.unlock(); } static void Visible(Window *wnd) { XWindowAttributes wa; XGetWindowAttributes(System::dpy, wnd->_m->xWnd, &wa); System::xEventMux.lock(); if (wa.map_state != IsViewable && XMapRaised(System::dpy, wnd->_m->xWnd) != BadWindow && wa.map_state == IsUnmapped) { _XEVENT_SYNC( wnd->_m->xWnd, MapNotify, , ) } System::xEventMux.unlock(); } void Window::AddStates(uint32_t type) { XEvent event; switch (type) { case PWRE_STATE_VISIBLE: Visible(this); break; case PWRE_STATE_MINIMIZE: Visible(this); XIconifyWindow(System::dpy, _m->xWnd, 0); break; case PWRE_STATE_MAXIMIZE: Visible(this); memset(&event, 0, sizeof(event)); event.type = ClientMessage; event.xclient.window = _m->xWnd; event.xclient.message_type = netWmState; event.xclient.format = 32; event.xclient.data.l[0] = netWmStateAdd; event.xclient.data.l[1] = netWmStateMaxVert; event.xclient.data.l[2] = netWmStateMaxHorz; XSendEvent(System::dpy, System::root, False, StructureNotifyMask, &event); break; case PWRE_STATE_FULLSCREEN: Visible(this); memset(&event, 0, sizeof(event)); event.type = ClientMessage; event.xclient.window = _m->xWnd; event.xclient.message_type = netWmState; event.xclient.format = 32; event.xclient.data.l[0] = netWmStateAdd; event.xclient.data.l[1] = netWmStateFullscr; XSendEvent(System::dpy, System::root, False, StructureNotifyMask, &event); } return; } void Window::RmStates(uint32_t type) { XEvent event; switch (type) { case PWRE_STATE_VISIBLE: Visible(this); break; case PWRE_STATE_MINIMIZE: Visible(this); break; case PWRE_STATE_MAXIMIZE: Visible(this); memset(&event, 0, sizeof(event)); event.type = ClientMessage; event.xclient.window = _m->xWnd; event.xclient.message_type = netWmState; event.xclient.format = 32; event.xclient.data.l[0] = netWmStateRemove; event.xclient.data.l[1] = netWmStateMaxVert; event.xclient.data.l[2] = netWmStateMaxHorz; XSendEvent(System::dpy, System::root, False, StructureNotifyMask, &event); break; case PWRE_STATE_FULLSCREEN: Visible(this); memset(&event, 0, sizeof(event)); event.type = ClientMessage; event.xclient.window = _m->xWnd; event.xclient.message_type = netWmState; event.xclient.format = 32; event.xclient.data.l[0] = netWmStateRemove; event.xclient.data.l[1] = netWmStateFullscr; XSendEvent(System::dpy, System::root, False, StructureNotifyMask, &event); } } bool Window::HasStates(uint32_t type) { return false; } const unsigned MWM_HINTS_DECORATIONS = (1 << 1); const int PROP_MOTIF_WM_HINTS_ELEMENTS = 5; struct PropMotifWmHints { unsigned long flags; unsigned long functions; unsigned long decorations; long inputMode; unsigned long status; }; void Window::Less(bool less) { PropMotifWmHints motifHints; motifHints.flags = MWM_HINTS_DECORATIONS; motifHints.decorations = 0; XChangeProperty(System::dpy, _m->xWnd, motifWmHints, motifWmHints, 32, PropModeReplace, (unsigned char *) &motifHints, PROP_MOTIF_WM_HINTS_ELEMENTS); } } /* Pwre */ #endif // PWRE_PLAT_X11 <|endoftext|>
<commit_before>#include "LibSVMClassificationDataset.h" #include <fstream> // XXX #include <iostream> LibSVMClassificationDataset::LibSVMClassificationDataset(ClassificationDataset<double> &classificationDataset) { m_InputSize = classificationDataset.getInputSize(); const int numberOfInputs = classificationDataset.getNumberOfInputs(); const int numberOfInputValues = (m_InputSize + 1) * numberOfInputs; prob.l = numberOfInputs; try { prob.x = new svm_node*[numberOfInputs]; prob.y = new double[numberOfInputs]; x_space = boost::shared_array<struct svm_node>(new svm_node[numberOfInputValues]); } catch (std::bad_alloc& ba) { if(NULL == prob.y) delete[] prob.x; throw LibSVMClassificationDatasetException("Cannot allocate memory."); } // XXX std::ofstream file; file.open ("haralick.scale"); int globalInputId = 0, globalInputValueId = 0; for(int i = 0; i < classificationDataset.getNumberOfClasses(); ++i) { const ClassificationDataset<double>::Class &c = classificationDataset.getClass(i); for(int inputId = 0; inputId < c.size(); ++inputId, ++globalInputId) { prob.y[globalInputId] = i+1; // The class prob.x[globalInputId] = &x_space[globalInputValueId]; file << i+1; // XXX const ClassificationDataset<double>::InputType &input = c[inputId]; for(int inputValueId = 0; inputValueId < classificationDataset.getInputSize(); ++inputValueId, ++globalInputValueId) { x_space[globalInputValueId].index = inputValueId + 1; x_space[globalInputValueId].value = input[inputValueId]; file << " " << (inputValueId+1) << ":" << input[inputValueId]; // XXX } file << std::endl; // XXX x_space[globalInputValueId].index = -1; ++globalInputValueId; } } file.close(); // XXX } LibSVMClassificationDataset::~LibSVMClassificationDataset() { delete[] prob.x; delete[] prob.y; } svm_problem* LibSVMClassificationDataset::getProblem() { return &prob; } int LibSVMClassificationDataset::getInputSize() const { return m_InputSize; } <commit_msg>Removes some debugging code.<commit_after>#include "LibSVMClassificationDataset.h" //#include <fstream> // XXX #include <iostream> LibSVMClassificationDataset::LibSVMClassificationDataset(ClassificationDataset<double> &classificationDataset) { m_InputSize = classificationDataset.getInputSize(); const int numberOfInputs = classificationDataset.getNumberOfInputs(); const int numberOfInputValues = (m_InputSize + 1) * numberOfInputs; prob.l = numberOfInputs; try { prob.x = new svm_node*[numberOfInputs]; prob.y = new double[numberOfInputs]; x_space = boost::shared_array<struct svm_node>(new svm_node[numberOfInputValues]); } catch (std::bad_alloc& ba) { if(NULL == prob.y) delete[] prob.x; throw LibSVMClassificationDatasetException("Cannot allocate memory."); } // XXX //std::ofstream file; //file.open ("haralick.scale"); int globalInputId = 0, globalInputValueId = 0; for(int i = 0; i < classificationDataset.getNumberOfClasses(); ++i) { const ClassificationDataset<double>::Class &c = classificationDataset.getClass(i); for(int inputId = 0; inputId < c.size(); ++inputId, ++globalInputId) { prob.y[globalInputId] = i+1; // The class prob.x[globalInputId] = &x_space[globalInputValueId]; //file << i+1; // XXX const ClassificationDataset<double>::InputType &input = c[inputId]; for(int inputValueId = 0; inputValueId < classificationDataset.getInputSize(); ++inputValueId, ++globalInputValueId) { x_space[globalInputValueId].index = inputValueId + 1; x_space[globalInputValueId].value = input[inputValueId]; //file << " " << (inputValueId+1) << ":" << input[inputValueId]; // XXX } //file << std::endl; // XXX x_space[globalInputValueId].index = -1; ++globalInputValueId; } } //file.close(); // XXX } LibSVMClassificationDataset::~LibSVMClassificationDataset() { delete[] prob.x; delete[] prob.y; } svm_problem* LibSVMClassificationDataset::getProblem() { return &prob; } int LibSVMClassificationDataset::getInputSize() const { return m_InputSize; } <|endoftext|>
<commit_before>/* * Copyright (C) 2005 Tommi Maekitalo * * 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. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <tntdb/mysql/impl/connection.h> #include <tntdb/mysql/impl/result.h> #include <tntdb/mysql/impl/statement.h> #include <tntdb/result.h> #include <tntdb/statement.h> #include <tntdb/mysql/error.h> #include <cctype> #include <cxxtools/log.h> log_define("tntdb.mysql.connection") namespace tntdb { namespace mysql { namespace { std::string str(const char* s) { return s && *s ? std::string("\"") + s + '"' : std::string("null"); } const char* zstr(const char* s) { return s && s[0] ? s : 0; } } void Connection::open(const char* app, const char* host, const char* user, const char* passwd, const char* db, unsigned int port, const char* unix_socket, unsigned long client_flag) { log_debug("mysql_real_connect(MYSQL, " << str(app) << ", " << str(host) << ", " << str(user) << ", " << str(passwd) << ", " << str(db) << ", " << port << ", " << str(unix_socket) << ", " << client_flag << ')'); if (::mysql_init(&mysql) == 0) throw std::runtime_error("cannot initalize mysql"); initialized = true; if (::mysql_options(&mysql, MYSQL_READ_DEFAULT_GROUP, app && app[0] ? app : "tntdb") != 0) throw MysqlError("mysql_options", &mysql); if (!::mysql_real_connect(&mysql, zstr(host), zstr(user), zstr(passwd), zstr(db), port, zstr(unix_socket), client_flag)) throw MysqlError("mysql_real_connect", &mysql); } Connection::Connection(const char* app, const char* host, const char* user, const char* passwd, const char* db, unsigned int port, const char* unix_socket, unsigned long client_flag) : initialized(false), transactionActive(0) { open(app, host, user, passwd, db, port, unix_socket, client_flag); } Connection::Connection(const char* conn) : initialized(false) { log_debug("Connection::Connection(\"" << conn << "\")"); std::string app; std::string host; std::string user; std::string passwd; std::string db; unsigned int port = 3306; std::string unix_socket; unsigned long client_flag = 0; enum state_type { state_key, state_value, state_value_esc, state_qvalue, state_qvaluee, state_qvalue_esc, state_port, state_flag } state = state_key; std::string key; std::string* value; char quote = '\0'; for (const char* p = conn; *p; ++p) { switch (state) { case state_key: if (*p == '=') { if (key == "port") { port = 0; key.clear(); state = state_port; } else if (key == "flags") { key.clear(); state = state_flag; } else { if (key == "app") value = &app; else if (key == "host") value = &host; else if (key == "user") value = &user; else if (key == "passwd" || key == "password") value = &passwd; else if (key == "db" || key == "dbname" || key == "database") value = &db; else if (key == "unix_socket") value = &unix_socket; else throw std::runtime_error("invalid key \"" + key + "\" in connectionstring \"" + conn + '"'); if (!value->empty()) throw std::runtime_error("value already set for key \"" + key + "\" in connectionstring \"" + conn + '"'); key.clear(); value->clear(); state = state_value; } } else if (key.empty() && std::isspace(*p)) ; else key += *p; break; case state_value: if (*p == ';' || std::isspace(*p)) state = state_key; else if (*p == '\\') state = state_value_esc; else if (value->empty() && (*p == '\'' || *p == '"')) { quote = *p; state = state_qvalue; } else *value += *p; break; case state_value_esc: *value += *p; state = state_value; break; case state_qvalue: if (*p == quote) state = state_key; else if (*p == '\\') state = state_qvalue_esc; else *value += *p; break; case state_qvaluee: if (*p == ';' || std::isspace(*p)) state = state_key; else throw std::runtime_error(std::string("delimiter expected in connectionstring ") + conn); break; case state_qvalue_esc: *value += *p; state = state_qvalue; break; case state_port: if (*p == ';' || std::isspace(*p)) state = state_key; else if (std::isdigit(*p)) port = port * 10 + (*p - '0'); else throw std::runtime_error( std::string("invalid port in connectionstring ") + conn); break; case state_flag: if (*p == ';' || std::isspace(*p)) state = state_key; else if (std::isdigit(*p)) client_flag = client_flag * 10 + (*p - '0'); else throw std::runtime_error( std::string("invalid flag in connectionstring ") + conn); break; } } if (state == state_key && !key.empty()) throw std::runtime_error(std::string("invalid connectionstring ") + conn); open(app.c_str(), host.c_str(), user.c_str(), passwd.c_str(), db.c_str(), port, unix_socket.c_str(), client_flag); } Connection::~Connection() { if (initialized) { clearStatementCache(); if (!lockTablesQuery.empty()) { log_debug("mysql_query(\"UNLOCK TABLES\")"); if (::mysql_query(&mysql, "UNLOCK TABLES") != 0) log_warn(MysqlError("mysql_query", &mysql).what()); } log_debug("mysql_close(" << &mysql << ')'); ::mysql_close(&mysql); } } void Connection::beginTransaction() { if (transactionActive == 0) { log_debug("mysql_autocomit(" << &mysql << ", " << 0 << ')'); if (::mysql_autocommit(&mysql, 0) != 0) throw MysqlError("mysql_autocommit", &mysql); } ++transactionActive; } void Connection::commitTransaction() { if (transactionActive == 0 || --transactionActive == 0) { log_debug("mysql_commit(" << &mysql << ')'); if (::mysql_commit(&mysql) != 0) throw MysqlError("mysql_commit", &mysql); if (!lockTablesQuery.empty()) { log_debug("mysql_query(\"UNLOCK TABLES\")"); if (::mysql_query(&mysql, "UNLOCK TABLES") != 0) throw MysqlError("mysql_query", &mysql); lockTablesQuery.clear(); } log_debug("mysql_autocomit(" << &mysql << ", " << 1 << ')'); if (::mysql_autocommit(&mysql, 1) != 0) throw MysqlError("mysql_autocommit", &mysql); } } void Connection::rollbackTransaction() { if (transactionActive == 0 || --transactionActive == 0) { log_debug("mysql_rollback(" << &mysql << ')'); if (::mysql_rollback(&mysql) != 0) throw MysqlError("mysql_rollback", &mysql); if (!lockTablesQuery.empty()) { log_debug("mysql_query(\"UNLOCK TABLES\")"); if (::mysql_query(&mysql, "UNLOCK TABLES") != 0) throw MysqlError("mysql_query", &mysql); lockTablesQuery.clear(); } log_debug("mysql_autocommit(" << &mysql << ", " << 1 << ')'); if (::mysql_autocommit(&mysql, 1) != 0) throw MysqlError("mysql_autocommit", &mysql); } } Connection::size_type Connection::execute(const std::string& query) { log_debug("mysql_query(\"" << query << "\")"); if (::mysql_query(&mysql, query.c_str()) != 0) throw MysqlError("mysql_query", &mysql); log_debug("mysql_affected_rows(" << &mysql << ')'); return ::mysql_affected_rows(&mysql); } tntdb::Result Connection::select(const std::string& query) { execute(query); log_debug("mysql_store_result(" << &mysql << ')'); MYSQL_RES* res = ::mysql_store_result(&mysql); if (res == 0) throw MysqlError("mysql_store_result", &mysql); return tntdb::Result(new Result(tntdb::Connection(this), &mysql, res)); } Row Connection::selectRow(const std::string& query) { tntdb::Result result = select(query); if (result.empty()) throw NotFound(); return result.getRow(0); } Value Connection::selectValue(const std::string& query) { Row t = selectRow(query); if (t.empty()) throw NotFound(); return t.getValue(0); } tntdb::Statement Connection::prepare(const std::string& query) { return tntdb::Statement(new Statement(tntdb::Connection(this), &mysql, query)); } bool Connection::ping() { int ret = ::mysql_ping(&mysql); log_debug("mysql_ping() => " << ret); return ret == 0; } long Connection::lastInsertId(const std::string& name) { return static_cast<long>(::mysql_insert_id(&mysql)); } void Connection::lockTable(const std::string& tablename, bool exclusive) { if (lockTablesQuery.empty()) lockTablesQuery = "LOCK TABLES "; else lockTablesQuery += ", "; lockTablesQuery += tablename; lockTablesQuery += exclusive ? " WRITE" : " READ"; log_debug("mysql_query(\"" << lockTablesQuery << "\")"); if (::mysql_query(&mysql, lockTablesQuery.c_str()) != 0) throw MysqlError("mysql_query", &mysql); } } } <commit_msg>Initialize transactionActive in constructor<commit_after>/* * Copyright (C) 2005 Tommi Maekitalo * * 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. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <tntdb/mysql/impl/connection.h> #include <tntdb/mysql/impl/result.h> #include <tntdb/mysql/impl/statement.h> #include <tntdb/result.h> #include <tntdb/statement.h> #include <tntdb/mysql/error.h> #include <cctype> #include <cxxtools/log.h> log_define("tntdb.mysql.connection") namespace tntdb { namespace mysql { namespace { std::string str(const char* s) { return s && *s ? std::string("\"") + s + '"' : std::string("null"); } const char* zstr(const char* s) { return s && s[0] ? s : 0; } } void Connection::open(const char* app, const char* host, const char* user, const char* passwd, const char* db, unsigned int port, const char* unix_socket, unsigned long client_flag) { log_debug("mysql_real_connect(MYSQL, " << str(app) << ", " << str(host) << ", " << str(user) << ", " << str(passwd) << ", " << str(db) << ", " << port << ", " << str(unix_socket) << ", " << client_flag << ')'); if (::mysql_init(&mysql) == 0) throw std::runtime_error("cannot initalize mysql"); initialized = true; if (::mysql_options(&mysql, MYSQL_READ_DEFAULT_GROUP, app && app[0] ? app : "tntdb") != 0) throw MysqlError("mysql_options", &mysql); if (!::mysql_real_connect(&mysql, zstr(host), zstr(user), zstr(passwd), zstr(db), port, zstr(unix_socket), client_flag)) throw MysqlError("mysql_real_connect", &mysql); } Connection::Connection(const char* app, const char* host, const char* user, const char* passwd, const char* db, unsigned int port, const char* unix_socket, unsigned long client_flag) : initialized(false), transactionActive(0) { open(app, host, user, passwd, db, port, unix_socket, client_flag); } Connection::Connection(const char* conn) : initialized(false), transactionActive(0) { log_debug("Connection::Connection(\"" << conn << "\")"); std::string app; std::string host; std::string user; std::string passwd; std::string db; unsigned int port = 3306; std::string unix_socket; unsigned long client_flag = 0; enum state_type { state_key, state_value, state_value_esc, state_qvalue, state_qvaluee, state_qvalue_esc, state_port, state_flag } state = state_key; std::string key; std::string* value; char quote = '\0'; for (const char* p = conn; *p; ++p) { switch (state) { case state_key: if (*p == '=') { if (key == "port") { port = 0; key.clear(); state = state_port; } else if (key == "flags") { key.clear(); state = state_flag; } else { if (key == "app") value = &app; else if (key == "host") value = &host; else if (key == "user") value = &user; else if (key == "passwd" || key == "password") value = &passwd; else if (key == "db" || key == "dbname" || key == "database") value = &db; else if (key == "unix_socket") value = &unix_socket; else throw std::runtime_error("invalid key \"" + key + "\" in connectionstring \"" + conn + '"'); if (!value->empty()) throw std::runtime_error("value already set for key \"" + key + "\" in connectionstring \"" + conn + '"'); key.clear(); value->clear(); state = state_value; } } else if (key.empty() && std::isspace(*p)) ; else key += *p; break; case state_value: if (*p == ';' || std::isspace(*p)) state = state_key; else if (*p == '\\') state = state_value_esc; else if (value->empty() && (*p == '\'' || *p == '"')) { quote = *p; state = state_qvalue; } else *value += *p; break; case state_value_esc: *value += *p; state = state_value; break; case state_qvalue: if (*p == quote) state = state_key; else if (*p == '\\') state = state_qvalue_esc; else *value += *p; break; case state_qvaluee: if (*p == ';' || std::isspace(*p)) state = state_key; else throw std::runtime_error(std::string("delimiter expected in connectionstring ") + conn); break; case state_qvalue_esc: *value += *p; state = state_qvalue; break; case state_port: if (*p == ';' || std::isspace(*p)) state = state_key; else if (std::isdigit(*p)) port = port * 10 + (*p - '0'); else throw std::runtime_error( std::string("invalid port in connectionstring ") + conn); break; case state_flag: if (*p == ';' || std::isspace(*p)) state = state_key; else if (std::isdigit(*p)) client_flag = client_flag * 10 + (*p - '0'); else throw std::runtime_error( std::string("invalid flag in connectionstring ") + conn); break; } } if (state == state_key && !key.empty()) throw std::runtime_error(std::string("invalid connectionstring ") + conn); open(app.c_str(), host.c_str(), user.c_str(), passwd.c_str(), db.c_str(), port, unix_socket.c_str(), client_flag); } Connection::~Connection() { if (initialized) { clearStatementCache(); if (!lockTablesQuery.empty()) { log_debug("mysql_query(\"UNLOCK TABLES\")"); if (::mysql_query(&mysql, "UNLOCK TABLES") != 0) log_warn(MysqlError("mysql_query", &mysql).what()); } log_debug("mysql_close(" << &mysql << ')'); ::mysql_close(&mysql); } } void Connection::beginTransaction() { if (transactionActive == 0) { log_debug("mysql_autocomit(" << &mysql << ", " << 0 << ')'); if (::mysql_autocommit(&mysql, 0) != 0) throw MysqlError("mysql_autocommit", &mysql); } ++transactionActive; } void Connection::commitTransaction() { if (transactionActive == 0 || --transactionActive == 0) { log_debug("mysql_commit(" << &mysql << ')'); if (::mysql_commit(&mysql) != 0) throw MysqlError("mysql_commit", &mysql); if (!lockTablesQuery.empty()) { log_debug("mysql_query(\"UNLOCK TABLES\")"); if (::mysql_query(&mysql, "UNLOCK TABLES") != 0) throw MysqlError("mysql_query", &mysql); lockTablesQuery.clear(); } log_debug("mysql_autocomit(" << &mysql << ", " << 1 << ')'); if (::mysql_autocommit(&mysql, 1) != 0) throw MysqlError("mysql_autocommit", &mysql); } } void Connection::rollbackTransaction() { if (transactionActive == 0 || --transactionActive == 0) { log_debug("mysql_rollback(" << &mysql << ')'); if (::mysql_rollback(&mysql) != 0) throw MysqlError("mysql_rollback", &mysql); if (!lockTablesQuery.empty()) { log_debug("mysql_query(\"UNLOCK TABLES\")"); if (::mysql_query(&mysql, "UNLOCK TABLES") != 0) throw MysqlError("mysql_query", &mysql); lockTablesQuery.clear(); } log_debug("mysql_autocommit(" << &mysql << ", " << 1 << ')'); if (::mysql_autocommit(&mysql, 1) != 0) throw MysqlError("mysql_autocommit", &mysql); } } Connection::size_type Connection::execute(const std::string& query) { log_debug("mysql_query(\"" << query << "\")"); if (::mysql_query(&mysql, query.c_str()) != 0) throw MysqlError("mysql_query", &mysql); log_debug("mysql_affected_rows(" << &mysql << ')'); return ::mysql_affected_rows(&mysql); } tntdb::Result Connection::select(const std::string& query) { execute(query); log_debug("mysql_store_result(" << &mysql << ')'); MYSQL_RES* res = ::mysql_store_result(&mysql); if (res == 0) throw MysqlError("mysql_store_result", &mysql); return tntdb::Result(new Result(tntdb::Connection(this), &mysql, res)); } Row Connection::selectRow(const std::string& query) { tntdb::Result result = select(query); if (result.empty()) throw NotFound(); return result.getRow(0); } Value Connection::selectValue(const std::string& query) { Row t = selectRow(query); if (t.empty()) throw NotFound(); return t.getValue(0); } tntdb::Statement Connection::prepare(const std::string& query) { return tntdb::Statement(new Statement(tntdb::Connection(this), &mysql, query)); } bool Connection::ping() { int ret = ::mysql_ping(&mysql); log_debug("mysql_ping() => " << ret); return ret == 0; } long Connection::lastInsertId(const std::string& name) { return static_cast<long>(::mysql_insert_id(&mysql)); } void Connection::lockTable(const std::string& tablename, bool exclusive) { if (lockTablesQuery.empty()) lockTablesQuery = "LOCK TABLES "; else lockTablesQuery += ", "; lockTablesQuery += tablename; lockTablesQuery += exclusive ? " WRITE" : " READ"; log_debug("mysql_query(\"" << lockTablesQuery << "\")"); if (::mysql_query(&mysql, lockTablesQuery.c_str()) != 0) throw MysqlError("mysql_query", &mysql); } } } <|endoftext|>
<commit_before>#include "KAI/Network/Node.h" #include <raknet/RakPeerInterface.h> KAI_NET_BEGIN using namespace RakNet; using namespace std; struct Node::Impl { int constexpr NumSockets = 100; int constexpr Port = 6666; shared_ptr<RakPeerInterface> _peer; SocketDescriptor _sockets[NumSockets]; Impl() : _peer(make_shared<RakPeerInterface>()) { for (auto &sock : _sockets) { sock.port = Port; sock.blockingSocket = false; } _peer->Startup(200, _sockets, NumSockets); } void Something() { } }; Node::Node() : _impl(std::make_shared<Impl>()) { } void Node::Listen(int port) { KAI_UNUSED_1(port); KAI_NOT_IMPLEMENTED(); } void Node::Connect(IpAddress const &, int port) { KAI_UNUSED_1(port); KAI_NOT_IMPLEMENTED(); } //Future Node::Send(NetHandle, Object) //{ // KAI_NOT_IMPLEMENTED(); // return Future(); //} // //Future Node::Receive(NetHandle, Object) //{ // KAI_NOT_IMPLEMENTED(); // return Future(); //} KAI_NET_END <commit_msg>Made constexpt static and const<commit_after>#include "KAI/Network/Node.h" #include <raknet/RakPeerInterface.h> KAI_NET_BEGIN using namespace RakNet; using namespace std; struct Node::Impl { static const int constexpr NumSockets = 100; static const int constexpr Port = 6666; shared_ptr<RakPeerInterface> _peer; SocketDescriptor _sockets[NumSockets]; Impl() : _peer(make_shared<RakPeerInterface>()) { for (auto &sock : _sockets) { sock.port = Port; sock.blockingSocket = false; } _peer->Startup(200, _sockets, NumSockets); } void Something() { } }; Node::Node() : _impl(std::make_shared<Impl>()) { } void Node::Listen(int port) { KAI_UNUSED_1(port); KAI_NOT_IMPLEMENTED(); } void Node::Connect(IpAddress const &, int port) { KAI_UNUSED_1(port); KAI_NOT_IMPLEMENTED(); } //Future Node::Send(NetHandle, Object) //{ // KAI_NOT_IMPLEMENTED(); // return Future(); //} // //Future Node::Receive(NetHandle, Object) //{ // KAI_NOT_IMPLEMENTED(); // return Future(); //} KAI_NET_END <|endoftext|>
<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef CNETLINK_H_ #define CNETLINK_H_ 1 #include <deque> #include <exception> #include <mutex> #include <tuple> #include <netlink/cache.h> #include <netlink/object.h> #include <netlink/route/addr.h> #include <netlink/route/link.h> #include <netlink/route/neighbour.h> #include <rofl/common/cthread.hpp> #include "netlink/nl_bridge.hpp" #include "netlink/nl_obj.hpp" #include "sai.hpp" namespace basebox { class eNetLinkBase : public std::runtime_error { public: eNetLinkBase(const std::string &__arg) : std::runtime_error(__arg){}; }; class eNetLinkCritical : public eNetLinkBase { public: eNetLinkCritical(const std::string &__arg) : eNetLinkBase(__arg){}; }; class eNetLinkFailed : public eNetLinkBase { public: eNetLinkFailed(const std::string &__arg) : eNetLinkBase(__arg){}; }; class cnetlink : public rofl::cthread_env { enum nl_cache_t { NL_LINK_CACHE, NL_NEIGH_CACHE, }; enum timer { NL_TIMER_RESEND_STATE, NL_TIMER_RESYNC, }; switch_interface *swi; rofl::cthread thread; struct nl_sock *sock; struct nl_cache_mngr *mngr; std::map<enum nl_cache_t, struct nl_cache *> caches; std::map<std::string, uint32_t> registered_ports; mutable std::mutex rp_mutex; std::map<int, uint32_t> ifindex_to_registered_port; std::map<uint32_t, int> registered_port_to_ifindex; std::deque<std::tuple<uint32_t, enum nbi::port_status, int>> port_status_changes; std::mutex pc_mutex; ofdpa_bridge *bridge; int nl_proc_max; bool running; bool rfd_scheduled; std::deque<nl_obj> nl_objs; void route_link_apply(const nl_obj &obj); void route_neigh_apply(const nl_obj &obj); enum cnetlink_event_t { EVENT_NONE, EVENT_UPDATE_LINKS, }; cnetlink(switch_interface *); ~cnetlink() override; int load_from_file(const std::string &path); void init_caches(); void destroy_caches(); void handle_wakeup(rofl::cthread &thread) override; void handle_read_event(rofl::cthread &thread, int fd) override; void handle_write_event(rofl::cthread &thread, int fd) override; void handle_timeout(rofl::cthread &thread, uint32_t timer_id) override; void link_created(rtnl_link *, uint32_t port_id) noexcept; void link_updated(rtnl_link *old_link, rtnl_link *new_link, uint32_t port_id) noexcept; void link_deleted(rtnl_link *, uint32_t port_id) noexcept; void neigh_ll_created(rtnl_neigh *neigh) noexcept; void neigh_ll_updated(rtnl_neigh *old_neigh, rtnl_neigh *new_neigh) noexcept; void neigh_ll_deleted(rtnl_neigh *neigh) noexcept; uint32_t get_port_id(int ifindex) { return ifindex_to_registered_port.at(ifindex); } int get_ifindex(uint32_t port_id) { return registered_port_to_ifindex.at(port_id); } public: void resend_state() noexcept; void register_switch(switch_interface *) noexcept; void unregister_switch(switch_interface *) noexcept; void port_status_changed(uint32_t, enum nbi::port_status) noexcept; static void nl_cb(struct nl_cache *cache, struct nl_object *obj, int action, void *data); static void nl_cb_v2(struct nl_cache *cache, struct nl_object *old_obj, struct nl_object *new_obj, uint64_t diff, int action, void *data); static cnetlink &get_instance(); void register_link(uint32_t, std::string); void unregister_link(uint32_t id, std::string port_name); std::map<std::string, uint32_t> get_registered_ports() const { std::lock_guard<std::mutex> lock(rp_mutex); return registered_ports; } void start() { if (running) return; running = true; thread.wakeup(); } void stop() { running = false; thread.wakeup(); } }; } // end of namespace basebox #endif /* CLINKCACHE_H_ */ <commit_msg>cnetlink: do not throw in get_port_id<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef CNETLINK_H_ #define CNETLINK_H_ 1 #include <deque> #include <exception> #include <mutex> #include <tuple> #include <netlink/cache.h> #include <netlink/object.h> #include <netlink/route/addr.h> #include <netlink/route/link.h> #include <netlink/route/neighbour.h> #include <rofl/common/cthread.hpp> #include "netlink/nl_bridge.hpp" #include "netlink/nl_obj.hpp" #include "sai.hpp" namespace basebox { class eNetLinkBase : public std::runtime_error { public: eNetLinkBase(const std::string &__arg) : std::runtime_error(__arg){}; }; class eNetLinkCritical : public eNetLinkBase { public: eNetLinkCritical(const std::string &__arg) : eNetLinkBase(__arg){}; }; class eNetLinkFailed : public eNetLinkBase { public: eNetLinkFailed(const std::string &__arg) : eNetLinkBase(__arg){}; }; class cnetlink : public rofl::cthread_env { enum nl_cache_t { NL_LINK_CACHE, NL_NEIGH_CACHE, }; enum timer { NL_TIMER_RESEND_STATE, NL_TIMER_RESYNC, }; switch_interface *swi; rofl::cthread thread; struct nl_sock *sock; struct nl_cache_mngr *mngr; std::map<enum nl_cache_t, struct nl_cache *> caches; std::map<std::string, uint32_t> registered_ports; mutable std::mutex rp_mutex; std::map<int, uint32_t> ifindex_to_registered_port; std::map<uint32_t, int> registered_port_to_ifindex; std::deque<std::tuple<uint32_t, enum nbi::port_status, int>> port_status_changes; std::mutex pc_mutex; ofdpa_bridge *bridge; int nl_proc_max; bool running; bool rfd_scheduled; std::deque<nl_obj> nl_objs; void route_link_apply(const nl_obj &obj); void route_neigh_apply(const nl_obj &obj); enum cnetlink_event_t { EVENT_NONE, EVENT_UPDATE_LINKS, }; cnetlink(switch_interface *); ~cnetlink() override; int load_from_file(const std::string &path); void init_caches(); void destroy_caches(); void handle_wakeup(rofl::cthread &thread) override; void handle_read_event(rofl::cthread &thread, int fd) override; void handle_write_event(rofl::cthread &thread, int fd) override; void handle_timeout(rofl::cthread &thread, uint32_t timer_id) override; void link_created(rtnl_link *, uint32_t port_id) noexcept; void link_updated(rtnl_link *old_link, rtnl_link *new_link, uint32_t port_id) noexcept; void link_deleted(rtnl_link *, uint32_t port_id) noexcept; void neigh_ll_created(rtnl_neigh *neigh) noexcept; void neigh_ll_updated(rtnl_neigh *old_neigh, rtnl_neigh *new_neigh) noexcept; void neigh_ll_deleted(rtnl_neigh *neigh) noexcept; uint32_t get_port_id(int ifindex) const { auto it = ifindex_to_registered_port.find(ifindex); if (it == ifindex_to_registered_port.end()) { return 0; } else { return it->second; } } int get_ifindex(uint32_t port_id) { return registered_port_to_ifindex.at(port_id); } public: void resend_state() noexcept; void register_switch(switch_interface *) noexcept; void unregister_switch(switch_interface *) noexcept; void port_status_changed(uint32_t, enum nbi::port_status) noexcept; static void nl_cb(struct nl_cache *cache, struct nl_object *obj, int action, void *data); static void nl_cb_v2(struct nl_cache *cache, struct nl_object *old_obj, struct nl_object *new_obj, uint64_t diff, int action, void *data); static cnetlink &get_instance(); void register_link(uint32_t, std::string); void unregister_link(uint32_t id, std::string port_name); std::map<std::string, uint32_t> get_registered_ports() const { std::lock_guard<std::mutex> lock(rp_mutex); return registered_ports; } void start() { if (running) return; running = true; thread.wakeup(); } void stop() { running = false; thread.wakeup(); } }; } // end of namespace basebox #endif /* CLINKCACHE_H_ */ <|endoftext|>