text
stringlengths
54
60.6k
<commit_before>#include <limits.h> #include "aio_private.h" #define EVEN_DISTRIBUTE const int MAX_BUF_REQS = 1024 * 3; /* * each file gets the same number of outstanding requests. */ #ifdef EVEN_DISTRIBUTE #define MAX_OUTSTANDING_NREQS (AIO_DEPTH / num_open_files()) #define ALLOW_DROP #endif class extended_io_request: public io_request { char *orig_embedded_bufs[NUM_EMBEDDED_IOVECS]; char **orig_bufs; slab_allocator *allocator; void assign_extended(extended_io_request &req) { this->allocator = req.allocator; if (req.orig_bufs == req.orig_embedded_bufs) { this->orig_bufs = this->orig_embedded_bufs; memcpy(this->orig_embedded_bufs, req.orig_embedded_bufs, sizeof(orig_embedded_bufs)); } else { this->orig_bufs = req.orig_bufs; req.orig_bufs = NULL; } } public: extended_io_request() { orig_bufs = NULL; allocator = NULL; memset(orig_embedded_bufs, 0, sizeof(orig_embedded_bufs)); } /** * The buffers in the IO request are allocated in a different NUMA node * than the SSDs are connected to, and allocate buffers on the local node. */ extended_io_request(io_request &req, slab_allocator *allocator) { init(req, allocator); } /** * The buffers are allocated in the same NUMA node as the SSDs * are connected to. */ extended_io_request(io_request &req): io_request(req) { allocator = NULL; orig_bufs = NULL; memset(orig_embedded_bufs, 0, sizeof(orig_embedded_bufs)); } extended_io_request(extended_io_request &req) { io_request::assign(req); assign_extended(req); } ~extended_io_request() { reset(); } extended_io_request &operator=(io_request &req) { io_request::assign(req); orig_bufs = NULL; allocator = NULL; memset(orig_embedded_bufs, 0, sizeof(orig_embedded_bufs)); return *this; } extended_io_request &operator=(extended_io_request &req) { io_request::assign(req); assign_extended(req); return *this; } void reset(); void init(io_request &req, slab_allocator *allocator); bool is_replaced() const { return orig_bufs != NULL; } void use_orig_bufs(); }; void extended_io_request::use_orig_bufs() { for (int i = 0; i < get_num_bufs(); i++) { char *buf = get_buf(i); // This memory copy can significantly decrease the performance. // But it seems there isn't a better way to avoid it. memcpy(orig_bufs[i], buf, get_buf_size(i)); set_buf(i, orig_bufs[i]); if (this->get_buf_size(i) <= PAGE_SIZE) allocator->free(&buf, 1); else free(buf); } // We have to reset orig_bufs because all original buffers // will be destroyed when the object is destructed. if (orig_bufs != orig_embedded_bufs) delete orig_bufs; orig_bufs = NULL; } void extended_io_request::init(io_request &req, slab_allocator *allocator) { io_request::assign(req); this->allocator = allocator; memset(orig_embedded_bufs, 0, sizeof(orig_embedded_bufs)); if (this->get_num_bufs() > NUM_EMBEDDED_IOVECS) orig_bufs = new char *[this->get_num_bufs()]; else orig_bufs = orig_embedded_bufs; for (int i = 0; i < this->get_num_bufs(); i++) { char *remote_buf = this->get_buf(i); char *local_buf; if (this->get_buf_size(i) <= PAGE_SIZE) { int ret = allocator->alloc(&local_buf, 1); assert(ret == 1); } else local_buf = (char *) valloc(this->get_buf_size(i)); this->set_buf(i, local_buf); orig_bufs[i] = remote_buf; } } void extended_io_request::reset() { if (orig_bufs) { char *local_pages[get_num_bufs()]; for (int i = 0; i < get_num_bufs(); i++) { local_pages[i] = get_buf(i); } allocator->free(local_pages, get_num_bufs()); if (orig_bufs != orig_embedded_bufs) delete orig_bufs; orig_bufs = NULL; } } struct thread_callback_s { struct io_callback_s cb; async_io *aio; extended_io_request req; }; void aio_callback(io_context_t ctx, struct iocb* iocb[], void *cbs[], long res[], long res2[], int num) { async_io *aio = NULL; thread_callback_s *tcbs[num]; for (int i = 0; i < num; i++) { assert(res2[i] == 0); tcbs[i] = (thread_callback_s *) cbs[i]; if (aio == NULL) aio = tcbs[i]->aio; // This is true when disks are only accessed by disk access threads. assert(aio == tcbs[i]->aio); } aio->return_cb(tcbs, num); } async_io::async_io(const logical_file_partition &partition, long size, int aio_depth_per_file, int node_id): buffered_io(partition, size, node_id, O_DIRECT | O_RDWR), AIO_DEPTH(aio_depth_per_file * partition.get_num_files()), allocator(PAGE_SIZE, AIO_DEPTH * PAGE_SIZE, INT_MAX, node_id) { printf("aio is used\n"); buf_idx = 0; ctx = create_aio_ctx(AIO_DEPTH); for (int i = 0; i < AIO_DEPTH * 5; i++) { cbs.push_back(new thread_callback_s()); } cb = NULL; num_iowait = 0; } void async_io::cleanup() { int slot = max_io_slot(ctx); while (slot < AIO_DEPTH) { io_wait(ctx, NULL); slot = max_io_slot(ctx); } buffered_io::cleanup(); } async_io::~async_io() { cleanup(); } struct iocb *async_io::construct_req(io_request &io_req, callback_t cb_func) { if (cbs.empty()) { fprintf(stderr, "no callback object left\n"); return NULL; } thread_callback_s *tcb = cbs.front(); io_callback_s *cb = (io_callback_s *) tcb; cbs.pop_front(); cb->func = cb_func; if (get_node_id() == io_req.get_node_id() || get_node_id() == -1) tcb->req = io_req; else tcb->req.init(io_req, &allocator); tcb->aio = this; assert(tcb->req.get_size() >= MIN_BLOCK_SIZE); assert(tcb->req.get_size() % MIN_BLOCK_SIZE == 0); assert(tcb->req.get_offset() % MIN_BLOCK_SIZE == 0); assert((long) tcb->req.get_buf() % MIN_BLOCK_SIZE == 0); int io_type = tcb->req.get_access_method() == READ ? A_READ : A_WRITE; block_identifier bid; get_partition().map(tcb->req.get_offset() / PAGE_SIZE, bid); if (tcb->req.get_num_bufs() == 1) return make_io_request(ctx, get_fd(tcb->req.get_offset()), tcb->req.get_size(), bid.off * PAGE_SIZE, tcb->req.get_buf(), io_type, cb); else { int num_bufs = tcb->req.get_num_bufs(); for (int i = 0; i < num_bufs; i++) { assert((long) tcb->req.get_buf(i) % MIN_BLOCK_SIZE == 0); assert(tcb->req.get_buf_size(i) % MIN_BLOCK_SIZE == 0); } return make_io_request(ctx, get_fd(tcb->req.get_offset()), /* * iocb only contains a pointer to the io vector. * the space for the IO vector is stored * in the callback structure. */ tcb->req.get_vec(), num_bufs, bid.off * PAGE_SIZE, io_type, cb); } } ssize_t async_io::access(io_request *requests, int num) { ssize_t ret = 0; while (num > 0) { int slot = max_io_slot(ctx); if (slot == 0) { /* * To achieve the best performance, we need to submit requests * as long as there is a slot available. */ num_iowait++; io_wait(ctx, NULL, 1); slot = max_io_slot(ctx); } struct iocb *reqs[slot]; int min = slot > num ? num : slot; for (int i = 0; i < min; i++) { ret += requests->get_size(); reqs[i] = construct_req(*requests, aio_callback); requests++; } submit_io_request(ctx, reqs, min); num -= min; } return ret; } void async_io::return_cb(thread_callback_s *tcbs[], int num) { io_request *reqs[num]; for (int i = 0; i < num; i++) { thread_callback_s *tcb = tcbs[i]; if (tcb->req.is_replaced()) tcb->req.use_orig_bufs(); reqs[i] = &tcb->req; } if (this->cb) { this->cb->invoke(reqs, num); } for (int i = 0; i < num; i++) { thread_callback_s *tcb = tcbs[i]; tcb->req.reset(); cbs.push_back(tcb); } } <commit_msg>Fix a bug in aio for writing data to a remote SSD.<commit_after>#include <limits.h> #include "aio_private.h" #define EVEN_DISTRIBUTE const int MAX_BUF_REQS = 1024 * 3; /* * each file gets the same number of outstanding requests. */ #ifdef EVEN_DISTRIBUTE #define MAX_OUTSTANDING_NREQS (AIO_DEPTH / num_open_files()) #define ALLOW_DROP #endif class extended_io_request: public io_request { char *orig_embedded_bufs[NUM_EMBEDDED_IOVECS]; char **orig_bufs; slab_allocator *allocator; void assign_extended(extended_io_request &req) { this->allocator = req.allocator; if (req.orig_bufs == req.orig_embedded_bufs) { this->orig_bufs = this->orig_embedded_bufs; memcpy(this->orig_embedded_bufs, req.orig_embedded_bufs, sizeof(orig_embedded_bufs)); } else { this->orig_bufs = req.orig_bufs; req.orig_bufs = NULL; } } public: extended_io_request() { orig_bufs = NULL; allocator = NULL; memset(orig_embedded_bufs, 0, sizeof(orig_embedded_bufs)); } /** * The buffers in the IO request are allocated in a different NUMA node * than the SSDs are connected to, and allocate buffers on the local node. */ extended_io_request(io_request &req, slab_allocator *allocator) { init(req, allocator); } /** * The buffers are allocated in the same NUMA node as the SSDs * are connected to. */ extended_io_request(io_request &req): io_request(req) { allocator = NULL; orig_bufs = NULL; memset(orig_embedded_bufs, 0, sizeof(orig_embedded_bufs)); } extended_io_request(extended_io_request &req) { io_request::assign(req); assign_extended(req); } ~extended_io_request() { reset(); } extended_io_request &operator=(io_request &req) { io_request::assign(req); orig_bufs = NULL; allocator = NULL; memset(orig_embedded_bufs, 0, sizeof(orig_embedded_bufs)); return *this; } extended_io_request &operator=(extended_io_request &req) { io_request::assign(req); assign_extended(req); return *this; } void reset(); void init(io_request &req, slab_allocator *allocator); bool is_replaced() const { return orig_bufs != NULL; } void use_orig_bufs(); }; void extended_io_request::use_orig_bufs() { for (int i = 0; i < get_num_bufs(); i++) { char *buf = get_buf(i); // This memory copy can significantly decrease the performance. // But it seems there isn't a better way to avoid it. if (this->get_access_method() == READ) memcpy(orig_bufs[i], buf, get_buf_size(i)); set_buf(i, orig_bufs[i]); if (this->get_buf_size(i) <= PAGE_SIZE) allocator->free(&buf, 1); else free(buf); } // We have to reset orig_bufs because all original buffers // will be destroyed when the object is destructed. if (orig_bufs != orig_embedded_bufs) delete orig_bufs; orig_bufs = NULL; } void extended_io_request::init(io_request &req, slab_allocator *allocator) { io_request::assign(req); this->allocator = allocator; memset(orig_embedded_bufs, 0, sizeof(orig_embedded_bufs)); if (this->get_num_bufs() > NUM_EMBEDDED_IOVECS) orig_bufs = new char *[this->get_num_bufs()]; else orig_bufs = orig_embedded_bufs; for (int i = 0; i < this->get_num_bufs(); i++) { char *remote_buf = this->get_buf(i); char *local_buf; if (this->get_buf_size(i) <= PAGE_SIZE) { int ret = allocator->alloc(&local_buf, 1); assert(ret == 1); } else local_buf = (char *) valloc(this->get_buf_size(i)); if (this->get_access_method() == WRITE) memcpy(local_buf, remote_buf, this->get_buf_size(i)); this->set_buf(i, local_buf); orig_bufs[i] = remote_buf; } } void extended_io_request::reset() { if (orig_bufs) { char *local_pages[get_num_bufs()]; for (int i = 0; i < get_num_bufs(); i++) { local_pages[i] = get_buf(i); } allocator->free(local_pages, get_num_bufs()); if (orig_bufs != orig_embedded_bufs) delete orig_bufs; orig_bufs = NULL; } } struct thread_callback_s { struct io_callback_s cb; async_io *aio; extended_io_request req; }; void aio_callback(io_context_t ctx, struct iocb* iocb[], void *cbs[], long res[], long res2[], int num) { async_io *aio = NULL; thread_callback_s *tcbs[num]; for (int i = 0; i < num; i++) { assert(res2[i] == 0); tcbs[i] = (thread_callback_s *) cbs[i]; if (aio == NULL) aio = tcbs[i]->aio; // This is true when disks are only accessed by disk access threads. assert(aio == tcbs[i]->aio); } aio->return_cb(tcbs, num); } async_io::async_io(const logical_file_partition &partition, long size, int aio_depth_per_file, int node_id): buffered_io(partition, size, node_id, O_DIRECT | O_RDWR), AIO_DEPTH(aio_depth_per_file * partition.get_num_files()), allocator(PAGE_SIZE, AIO_DEPTH * PAGE_SIZE, INT_MAX, node_id) { printf("aio is used\n"); buf_idx = 0; ctx = create_aio_ctx(AIO_DEPTH); for (int i = 0; i < AIO_DEPTH * 5; i++) { cbs.push_back(new thread_callback_s()); } cb = NULL; num_iowait = 0; } void async_io::cleanup() { int slot = max_io_slot(ctx); while (slot < AIO_DEPTH) { io_wait(ctx, NULL); slot = max_io_slot(ctx); } buffered_io::cleanup(); } async_io::~async_io() { cleanup(); } struct iocb *async_io::construct_req(io_request &io_req, callback_t cb_func) { if (cbs.empty()) { fprintf(stderr, "no callback object left\n"); return NULL; } thread_callback_s *tcb = cbs.front(); io_callback_s *cb = (io_callback_s *) tcb; cbs.pop_front(); cb->func = cb_func; if (get_node_id() == io_req.get_node_id() || get_node_id() == -1) tcb->req = io_req; else tcb->req.init(io_req, &allocator); tcb->aio = this; assert(tcb->req.get_size() >= MIN_BLOCK_SIZE); assert(tcb->req.get_size() % MIN_BLOCK_SIZE == 0); assert(tcb->req.get_offset() % MIN_BLOCK_SIZE == 0); assert((long) tcb->req.get_buf() % MIN_BLOCK_SIZE == 0); int io_type = tcb->req.get_access_method() == READ ? A_READ : A_WRITE; block_identifier bid; get_partition().map(tcb->req.get_offset() / PAGE_SIZE, bid); if (tcb->req.get_num_bufs() == 1) return make_io_request(ctx, get_fd(tcb->req.get_offset()), tcb->req.get_size(), bid.off * PAGE_SIZE, tcb->req.get_buf(), io_type, cb); else { int num_bufs = tcb->req.get_num_bufs(); for (int i = 0; i < num_bufs; i++) { assert((long) tcb->req.get_buf(i) % MIN_BLOCK_SIZE == 0); assert(tcb->req.get_buf_size(i) % MIN_BLOCK_SIZE == 0); } return make_io_request(ctx, get_fd(tcb->req.get_offset()), /* * iocb only contains a pointer to the io vector. * the space for the IO vector is stored * in the callback structure. */ tcb->req.get_vec(), num_bufs, bid.off * PAGE_SIZE, io_type, cb); } } ssize_t async_io::access(io_request *requests, int num) { ssize_t ret = 0; while (num > 0) { int slot = max_io_slot(ctx); if (slot == 0) { /* * To achieve the best performance, we need to submit requests * as long as there is a slot available. */ num_iowait++; io_wait(ctx, NULL, 1); slot = max_io_slot(ctx); } struct iocb *reqs[slot]; int min = slot > num ? num : slot; for (int i = 0; i < min; i++) { ret += requests->get_size(); reqs[i] = construct_req(*requests, aio_callback); requests++; } submit_io_request(ctx, reqs, min); num -= min; } return ret; } void async_io::return_cb(thread_callback_s *tcbs[], int num) { io_request *reqs[num]; for (int i = 0; i < num; i++) { thread_callback_s *tcb = tcbs[i]; if (tcb->req.is_replaced()) tcb->req.use_orig_bufs(); reqs[i] = &tcb->req; } if (this->cb) { this->cb->invoke(reqs, num); } for (int i = 0; i < num; i++) { thread_callback_s *tcb = tcbs[i]; tcb->req.reset(); cbs.push_back(tcb); } } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 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 "S60mediarecognizer.h" #include <MPMediaRecognizer.h> #include <e32def.h> #include <e32cmn.h> #include <QUrl> #include <QDir> S60MediaRecognizer::S60MediaRecognizer(QObject *parent) : QObject(parent) { m_recognizer = NULL; TRAP(m_error, m_recognizer = CMPMediaRecognizer::NewL()); } S60MediaRecognizer::~S60MediaRecognizer() { delete m_recognizer; m_recognizer = NULL; } /* * Checks if Url is valid or not. */ bool S60MediaRecognizer::checkUrl(const QUrl& url) { TBool validUrl = false; if (m_recognizer) { TPtrC myDesc (static_cast<const TUint16*>(url.toString().utf16()), url.toString().length()); validUrl = m_recognizer->ValidUrl(myDesc); } return validUrl; } S60MediaRecognizer::MediaType S60MediaRecognizer::IdentifyMediaType(const QUrl& url) { CMPMediaRecognizer::TMPMediaType type; QString filePath = QDir::toNativeSeparators(url.toLocalFile()); TPtrC16 urlPtr(reinterpret_cast<const TUint16*>(filePath.utf16())); MediaType mediaType = NotSupported; TRAP(m_error, type = m_recognizer->IdentifyMediaTypeL(urlPtr, EFalse)); if (!m_error) { switch (type) { case CMPMediaRecognizer::ELocalAudioFile: mediaType = Audio; break; case CMPMediaRecognizer::ELocalVideoFile: mediaType = Video; break; case CMPMediaRecognizer::ELocalAudioPlaylist: case CMPMediaRecognizer::EUrl: // TODO: Must be considered when streams will be implemented case CMPMediaRecognizer::ELocalRamFile: case CMPMediaRecognizer::ELocalSdpFile: case CMPMediaRecognizer::EProgressiveDownload: case CMPMediaRecognizer::EUnidentified: default: break; } } return mediaType; } <commit_msg>Exclude EProgressiveDownload from switch.<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 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 "S60mediarecognizer.h" #include <MPMediaRecognizer.h> #include <e32def.h> #include <e32cmn.h> #include <QUrl> #include <QDir> S60MediaRecognizer::S60MediaRecognizer(QObject *parent) : QObject(parent) { m_recognizer = NULL; TRAP(m_error, m_recognizer = CMPMediaRecognizer::NewL()); } S60MediaRecognizer::~S60MediaRecognizer() { delete m_recognizer; m_recognizer = NULL; } /* * Checks if Url is valid or not. */ bool S60MediaRecognizer::checkUrl(const QUrl& url) { TBool validUrl = false; if (m_recognizer) { TPtrC myDesc (static_cast<const TUint16*>(url.toString().utf16()), url.toString().length()); validUrl = m_recognizer->ValidUrl(myDesc); } return validUrl; } S60MediaRecognizer::MediaType S60MediaRecognizer::IdentifyMediaType(const QUrl& url) { CMPMediaRecognizer::TMPMediaType type; QString filePath = QDir::toNativeSeparators(url.toLocalFile()); TPtrC16 urlPtr(reinterpret_cast<const TUint16*>(filePath.utf16())); MediaType mediaType = NotSupported; TRAP(m_error, type = m_recognizer->IdentifyMediaTypeL(urlPtr, EFalse)); if (!m_error) { switch (type) { case CMPMediaRecognizer::ELocalAudioFile: mediaType = Audio; break; case CMPMediaRecognizer::ELocalVideoFile: mediaType = Video; break; case CMPMediaRecognizer::ELocalAudioPlaylist: case CMPMediaRecognizer::EUrl: // TODO: Must be considered when streams will be implemented case CMPMediaRecognizer::ELocalRamFile: case CMPMediaRecognizer::ELocalSdpFile: // case CMPMediaRecognizer::EProgressiveDownload: case CMPMediaRecognizer::EUnidentified: default: break; } } return mediaType; } <|endoftext|>
<commit_before>// // yas_db_model.cpp // #include <unordered_map> #include <vector> #include "yas_db_model.h" #include "yas_db_entity.h" #include "yas_db_index.h" #include "yas_db_attribute.h" #include "yas_db_relation.h" using namespace yas; namespace yas::db { static std::string const version_key = "version"; static std::string const entities_key = "entities"; static std::string const indices_key = "indices"; static std::string const attributes_key = "attributes"; static std::string const relations_key = "relations"; static std::unordered_map<std::string, db::string_set_map_t> make_inverse_relation_names( std::vector<db::entity_args> const &enitity_args_vec) { std::unordered_map<std::string, db::string_set_map_t> entity_inv_rel_names; for (db::entity_args const &entity : enitity_args_vec) { std::string const &entity_name = entity.name; for (db::relation_args const &relation : entity.relations) { std::string const &tgt_entity_name = relation.target; if (entity_inv_rel_names.count(tgt_entity_name) == 0) { entity_inv_rel_names.insert(std::make_pair(tgt_entity_name, db::string_set_map_t{})); } auto &inv_rel_names = entity_inv_rel_names.at(tgt_entity_name); if (inv_rel_names.count(entity_name) == 0) { inv_rel_names.insert(std::make_pair(entity_name, db::string_set_t{})); } inv_rel_names.at(entity_name).insert(relation.name); } } return entity_inv_rel_names; } } struct db::model::impl : base::impl { struct args { yas::version const version; db::entity_map_t const entities; db::index_map_t const indices; }; args _args; static db::model::impl::args to_args(model_args &&args) { auto entity_inv_rel_names = make_inverse_relation_names(args.entities); db::entity_map_t entities; entities.reserve(args.entities.size()); for (db::entity_args &entity_args : args.entities) { db::string_set_map_t inv_rel_names; if (entity_inv_rel_names.count(entity_args.name)) { inv_rel_names = std::move(entity_inv_rel_names.at(entity_args.name)); } std::string name = entity_args.name; entities.emplace(std::move(name), db::entity{{.name = std::move(entity_args.name), .attributes = std::move(entity_args.attributes), .relations = std::move(entity_args.relations)}, std::move(inv_rel_names)}); } db::index_map_t indices; indices.reserve(args.indices.size()); for (db::index_args &index_args : args.indices) { std::string name = index_args.name; indices.emplace(std::move(name), db::index{std::move(index_args)}); } return {.version = std::move(args.version), .entities = std::move(entities), .indices = std::move(indices)}; } impl(model_args &&args) : _args(to_args(std::move(args))) { } }; db::model::model(model_args args) : base(std::make_shared<impl>(std::move(args))) { } db::model::model(std::nullptr_t) : base(nullptr) { } yas::version const &db::model::version() const { return impl_ptr<impl>()->_args.version; } db::entity_map_t const &db::model::entities() const { return impl_ptr<impl>()->_args.entities; } db::index_map_t const &db::model::indices() const { return impl_ptr<impl>()->_args.indices; } db::entity const &db::model::entity(std::string const &entity) const { return this->entities().at(entity); } db::attribute_map_t const &db::model::attributes(std::string const &entity) const { return this->entities().at(entity).all_attributes; } db::attribute_map_t const &db::model::custom_attributes(std::string const &entity) const { return this->entities().at(entity).custom_attributes; } db::relation_map_t const &db::model::relations(std::string const &entity) const { return this->entities().at(entity).relations; } db::attribute const &db::model::attribute(std::string const &entity, std::string const &attr_name) const { return this->entities().at(entity).all_attributes.at(attr_name); } db::relation const &db::model::relation(std::string const &entity, std::string const &rel_name) const { return this->entities().at(entity).relations.at(rel_name); } db::index const &db::model::index(std::string const &index_name) const { return this->indices().at(index_name); } bool db::model::entity_exists(std::string const &entity) const { return this->entities().count(entity) > 0; } bool db::model::attribute_exists(std::string const &entity, std::string const &attr_name) const { if (this->entity_exists(entity)) { if (this->entities().at(entity).all_attributes.count(attr_name) > 0) { return true; } } return false; } bool db::model::relation_exists(std::string const &entity, std::string const &rel_name) const { if (this->entity_exists(entity)) { if (this->entities().at(entity).relations.count(rel_name) > 0) { return true; } } return false; } bool db::model::index_exists(std::string const &index_name) const { return this->indices().count(index_name) > 0; } <commit_msg>remove key<commit_after>// // yas_db_model.cpp // #include <unordered_map> #include <vector> #include "yas_db_model.h" #include "yas_db_entity.h" #include "yas_db_index.h" #include "yas_db_attribute.h" #include "yas_db_relation.h" using namespace yas; namespace yas::db { static std::unordered_map<std::string, db::string_set_map_t> make_inverse_relation_names( std::vector<db::entity_args> const &enitity_args_vec) { std::unordered_map<std::string, db::string_set_map_t> entity_inv_rel_names; for (db::entity_args const &entity : enitity_args_vec) { std::string const &entity_name = entity.name; for (db::relation_args const &relation : entity.relations) { std::string const &tgt_entity_name = relation.target; if (entity_inv_rel_names.count(tgt_entity_name) == 0) { entity_inv_rel_names.insert(std::make_pair(tgt_entity_name, db::string_set_map_t{})); } auto &inv_rel_names = entity_inv_rel_names.at(tgt_entity_name); if (inv_rel_names.count(entity_name) == 0) { inv_rel_names.insert(std::make_pair(entity_name, db::string_set_t{})); } inv_rel_names.at(entity_name).insert(relation.name); } } return entity_inv_rel_names; } } struct db::model::impl : base::impl { struct args { yas::version const version; db::entity_map_t const entities; db::index_map_t const indices; }; args _args; static db::model::impl::args to_args(model_args &&args) { auto entity_inv_rel_names = make_inverse_relation_names(args.entities); db::entity_map_t entities; entities.reserve(args.entities.size()); for (db::entity_args &entity_args : args.entities) { db::string_set_map_t inv_rel_names; if (entity_inv_rel_names.count(entity_args.name)) { inv_rel_names = std::move(entity_inv_rel_names.at(entity_args.name)); } std::string name = entity_args.name; entities.emplace(std::move(name), db::entity{{.name = std::move(entity_args.name), .attributes = std::move(entity_args.attributes), .relations = std::move(entity_args.relations)}, std::move(inv_rel_names)}); } db::index_map_t indices; indices.reserve(args.indices.size()); for (db::index_args &index_args : args.indices) { std::string name = index_args.name; indices.emplace(std::move(name), db::index{std::move(index_args)}); } return {.version = std::move(args.version), .entities = std::move(entities), .indices = std::move(indices)}; } impl(model_args &&args) : _args(to_args(std::move(args))) { } }; db::model::model(model_args args) : base(std::make_shared<impl>(std::move(args))) { } db::model::model(std::nullptr_t) : base(nullptr) { } yas::version const &db::model::version() const { return impl_ptr<impl>()->_args.version; } db::entity_map_t const &db::model::entities() const { return impl_ptr<impl>()->_args.entities; } db::index_map_t const &db::model::indices() const { return impl_ptr<impl>()->_args.indices; } db::entity const &db::model::entity(std::string const &entity) const { return this->entities().at(entity); } db::attribute_map_t const &db::model::attributes(std::string const &entity) const { return this->entities().at(entity).all_attributes; } db::attribute_map_t const &db::model::custom_attributes(std::string const &entity) const { return this->entities().at(entity).custom_attributes; } db::relation_map_t const &db::model::relations(std::string const &entity) const { return this->entities().at(entity).relations; } db::attribute const &db::model::attribute(std::string const &entity, std::string const &attr_name) const { return this->entities().at(entity).all_attributes.at(attr_name); } db::relation const &db::model::relation(std::string const &entity, std::string const &rel_name) const { return this->entities().at(entity).relations.at(rel_name); } db::index const &db::model::index(std::string const &index_name) const { return this->indices().at(index_name); } bool db::model::entity_exists(std::string const &entity) const { return this->entities().count(entity) > 0; } bool db::model::attribute_exists(std::string const &entity, std::string const &attr_name) const { if (this->entity_exists(entity)) { if (this->entities().at(entity).all_attributes.count(attr_name) > 0) { return true; } } return false; } bool db::model::relation_exists(std::string const &entity, std::string const &rel_name) const { if (this->entity_exists(entity)) { if (this->entities().at(entity).relations.count(rel_name) > 0) { return true; } } return false; } bool db::model::index_exists(std::string const &index_name) const { return this->indices().count(index_name) > 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com> */ #include <uavcan/transport/frame.hpp> #include <uavcan/transport/can_io.hpp> #include <uavcan/debug.hpp> #include <cassert> namespace uavcan { /** * Frame */ const uint8_t Frame::MaxIndexForService; const uint8_t Frame::MaxIndexForMessage; uint_fast8_t Frame::getMaxIndexForTransferType(const TransferType type) { if (type == TransferTypeMessageBroadcast || type == TransferTypeMessageUnicast) { return MaxIndexForMessage; } else if (type == TransferTypeServiceRequest || type == TransferTypeServiceResponse) { return MaxIndexForService; } else { UAVCAN_ASSERT(0); return 0; } } void Frame::setPriority(const TransferPriority priority) { UAVCAN_ASSERT(priority < NumTransferPriorities); if (transfer_type_ == TransferTypeMessageBroadcast || transfer_type_ == TransferTypeMessageUnicast) { if (priority != TransferPriorityService) { transfer_priority_ = priority; } else { UAVCAN_ASSERT(0); } } else { UAVCAN_ASSERT(0); } } int Frame::getMaxPayloadLen() const { switch (getTransferType()) { case TransferTypeMessageBroadcast: { return int(sizeof(payload_)); } case TransferTypeServiceResponse: case TransferTypeServiceRequest: case TransferTypeMessageUnicast: { return int(sizeof(payload_)) - 1; } default: { UAVCAN_ASSERT(0); return -ErrLogic; } } } int Frame::setPayload(const uint8_t* data, unsigned len) { const int maxlen = getMaxPayloadLen(); if (maxlen < 0) { return maxlen; } len = min(unsigned(maxlen), len); (void)copy(data, data + len, payload_); payload_len_ = uint_fast8_t(len); return int(len); } template <int OFFSET, int WIDTH> inline static uint32_t bitunpack(uint32_t val) { StaticAssert<(OFFSET >= 0)>::check(); StaticAssert<(WIDTH > 0)>::check(); StaticAssert<((OFFSET + WIDTH) <= 29)>::check(); return (val >> OFFSET) & ((1UL << WIDTH) - 1); } bool Frame::parse(const CanFrame& can_frame) { if (can_frame.isErrorFrame() || can_frame.isRemoteTransmissionRequest() || !can_frame.isExtended()) { return false; } if (can_frame.dlc > sizeof(can_frame.data)) { UAVCAN_ASSERT(0); // This is not a protocol error, so UAVCAN_ASSERT() is ok return false; } /* * CAN ID parsing */ const uint32_t id = can_frame.id & CanFrame::MaskExtID; transfer_id_ = uint8_t(bitunpack<0, 3>(id)); last_frame_ = bitunpack<3, 1>(id) != 0; // TT-specific fields skipped transfer_priority_ = TransferPriority(bitunpack<27, 2>(id)); if (transfer_priority_ == TransferPriorityService) { frame_index_ = uint_fast8_t(bitunpack<4, 6>(id)); src_node_id_ = uint8_t(bitunpack<10, 7>(id)); data_type_id_ = uint16_t(bitunpack<17, 9>(id)); // RequestNotResponse transfer_type_ = (bitunpack<26, 1>(id) == 1U) ? TransferTypeServiceRequest : TransferTypeServiceResponse; } else { frame_index_ = uint_fast8_t(bitunpack<4, 4>(id)); // BroadcastNotUnicast transfer_type_ = (bitunpack<8, 1>(id) == 1U) ? TransferTypeMessageBroadcast : TransferTypeMessageUnicast; src_node_id_ = uint8_t(bitunpack<9, 7>(id)); data_type_id_ = uint16_t(bitunpack<16, 11>(id)); } /* * CAN payload parsing */ switch (transfer_type_) { case TransferTypeMessageBroadcast: { dst_node_id_ = NodeID::Broadcast; payload_len_ = can_frame.dlc; (void)copy(can_frame.data, can_frame.data + can_frame.dlc, payload_); break; } case TransferTypeServiceResponse: case TransferTypeServiceRequest: case TransferTypeMessageUnicast: { if (can_frame.dlc < 1) { return false; } if (can_frame.data[0] & 0x80) // RESERVED, must be zero { return false; } dst_node_id_ = can_frame.data[0] & 0x7F; payload_len_ = uint8_t(can_frame.dlc - 1); (void)copy(can_frame.data + 1, can_frame.data + can_frame.dlc, payload_); break; } default: { return false; } } /* * Special case for anonymous transfers - trailing 8 bits of CAN ID must be ignored * - Transfer ID (assumed zero) * - Last Frame (assumed true) * - Frame Index (assumed zero) */ if (src_node_id_.isBroadcast()) { transfer_id_ = TransferID(0); last_frame_ = true; frame_index_ = 0; } return isValid(); } template <int OFFSET, int WIDTH> inline static uint32_t bitpack(uint32_t field) { StaticAssert<(OFFSET >= 0)>::check(); StaticAssert<(WIDTH > 0)>::check(); StaticAssert<((OFFSET + WIDTH) <= 29)>::check(); UAVCAN_ASSERT((field & ((1UL << WIDTH) - 1)) == field); return uint32_t((field & ((1UL << WIDTH) - 1)) << OFFSET); } bool Frame::compile(CanFrame& out_can_frame) const { if (!isValid()) { UAVCAN_ASSERT(0); // This is an application error, so we need to maximize it. return false; } /* * Setting CAN ID field */ // Common fields for messages and services out_can_frame.id = CanFrame::FlagEFF | bitpack<0, 3>(transfer_id_.get()) | bitpack<3, 1>(last_frame_) | /* TT-specific fields skipped */ bitpack<27, 2>(transfer_priority_); if (transfer_type_ == TransferTypeServiceRequest || transfer_type_ == TransferTypeServiceResponse) { out_can_frame.id |= bitpack<4, 6>(frame_index_) | bitpack<10, 7>(src_node_id_.get()) | bitpack<17, 9>(data_type_id_.get()) | bitpack<26, 1>((transfer_type_ == TransferTypeServiceRequest) ? 1U : 0U); } else if (transfer_type_ == TransferTypeMessageBroadcast || transfer_type_ == TransferTypeMessageUnicast) { out_can_frame.id |= bitpack<4, 4>(frame_index_) | bitpack<8, 1>((transfer_type_ == TransferTypeMessageBroadcast) ? 1U : 0U) | bitpack<9, 7>(src_node_id_.get()) | bitpack<16, 11>(data_type_id_.get()); } else { UAVCAN_ASSERT(0); return false; } /* * Setting payload */ switch (transfer_type_) { case TransferTypeMessageBroadcast: { out_can_frame.dlc = uint8_t(payload_len_); (void)copy(payload_, payload_ + payload_len_, out_can_frame.data); break; } case TransferTypeServiceResponse: case TransferTypeServiceRequest: case TransferTypeMessageUnicast: { UAVCAN_ASSERT((payload_len_ + 1U) <= sizeof(out_can_frame.data)); out_can_frame.data[0] = dst_node_id_.get(); out_can_frame.dlc = uint8_t(payload_len_ + 1); (void)copy(payload_, payload_ + payload_len_, out_can_frame.data + 1); break; } default: { UAVCAN_ASSERT(0); return false; } } /* * Setting trailing bits of CAN ID for anonymous message * This overrides the following fields: * - Transfer ID (assumed zero) * - Last Frame (assumed true) * - Frame Index (assumed zero) */ if (src_node_id_.isBroadcast()) { uint8_t sum = 0; out_can_frame.id &= ~bitpack<0, 8>(sum); // Clearing bits for (uint_fast8_t i = 0; i < payload_len_; i++) { sum = static_cast<uint8_t>(sum + payload_[i]); } out_can_frame.id |= bitpack<0, 8>(sum); // Setting the checksum } return true; } bool Frame::isValid() const { /* * Frame index */ if (frame_index_ > getMaxIndex()) { UAVCAN_TRACE("Frame", "Validness check failed at line %d", __LINE__); return false; } if ((frame_index_ == getMaxIndex()) && !last_frame_) { UAVCAN_TRACE("Frame", "Validness check failed at line %d", __LINE__); return false; } /* * Node ID */ if (!src_node_id_.isValid() || !dst_node_id_.isValid()) { UAVCAN_TRACE("Frame", "Validness check failed at line %d", __LINE__); return false; } if (src_node_id_.isUnicast() && (src_node_id_ == dst_node_id_)) { UAVCAN_TRACE("Frame", "Validness check failed at line %d", __LINE__); return false; } /* * Transfer type */ if (transfer_type_ >= NumTransferTypes) { UAVCAN_TRACE("Frame", "Validness check failed at line %d", __LINE__); return false; } if ((transfer_type_ == TransferTypeMessageBroadcast) != dst_node_id_.isBroadcast()) { UAVCAN_TRACE("Frame", "Validness check failed at line %d", __LINE__); return false; } // Anonymous transfers if (src_node_id_.isBroadcast() && (!last_frame_ || (frame_index_ > 0) || (transfer_type_ != TransferTypeMessageBroadcast))) { return false; } /* * Payload */ if (static_cast<int>(payload_len_) > getMaxPayloadLen()) { UAVCAN_TRACE("Frame", "Validness check failed at line %d", __LINE__); return false; } /* * Data type ID */ if (!data_type_id_.isValidForDataTypeKind(getDataTypeKindForTransferType(transfer_type_))) { UAVCAN_TRACE("Frame", "Validness check failed at line %d", __LINE__); return false; } /* * Priority */ if (transfer_priority_ >= NumTransferPriorities) { UAVCAN_TRACE("Frame", "Validness check failed at line %d", __LINE__); return false; } if (transfer_type_ == TransferTypeServiceRequest || transfer_type_ == TransferTypeServiceResponse) { if (transfer_priority_ != TransferPriorityService) { UAVCAN_TRACE("Frame", "Validness check failed at line %d", __LINE__); return false; } } return true; } bool Frame::operator==(const Frame& rhs) const { return (transfer_priority_ == rhs.transfer_priority_) && (transfer_type_ == rhs.transfer_type_) && (data_type_id_ == rhs.data_type_id_) && (src_node_id_ == rhs.src_node_id_) && (dst_node_id_ == rhs.dst_node_id_) && (frame_index_ == rhs.frame_index_) && (transfer_id_ == rhs.transfer_id_) && (last_frame_ == rhs.last_frame_) && (payload_len_ == rhs.payload_len_) && equal(payload_, payload_ + payload_len_, rhs.payload_); } #if UAVCAN_TOSTRING std::string Frame::toString() const { /* * - Priority * - Data Type ID * - Transfer Type * - Source Node ID * - Frame Index * - Last Frame * - Transfer ID */ static const int BUFLEN = 100; char buf[BUFLEN]; int ofs = snprintf(buf, BUFLEN, "prio=%d dtid=%d tt=%d snid=%d dnid=%d idx=%d last=%d tid=%d payload=[", int(transfer_priority_), int(data_type_id_.get()), int(transfer_type_), int(src_node_id_.get()), int(dst_node_id_.get()), int(frame_index_), int(last_frame_), int(transfer_id_.get())); for (unsigned i = 0; i < payload_len_; i++) { ofs += snprintf(buf + ofs, unsigned(BUFLEN - ofs), "%02x", payload_[i]); if ((i + 1) < payload_len_) { ofs += snprintf(buf + ofs, unsigned(BUFLEN - ofs), " "); } } (void)snprintf(buf + ofs, unsigned(BUFLEN - ofs), "]"); return std::string(buf); } #endif /** * RxFrame */ bool RxFrame::parse(const CanRxFrame& can_frame) { if (!Frame::parse(can_frame)) { return false; } if (can_frame.ts_mono.isZero()) // Monotonic timestamps are mandatory. { UAVCAN_ASSERT(0); // If it is not set, it's a driver failure. return false; } ts_mono_ = can_frame.ts_mono; ts_utc_ = can_frame.ts_utc; iface_index_ = can_frame.iface_index; return true; } #if UAVCAN_TOSTRING std::string RxFrame::toString() const { std::string out = Frame::toString(); out.reserve(128); out += " ts_m=" + ts_mono_.toString(); out += " ts_utc=" + ts_utc_.toString(); out += " iface="; out += char('0' + iface_index_); return out; } #endif } <commit_msg>Coverity 1304848<commit_after>/* * Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com> */ #include <uavcan/transport/frame.hpp> #include <uavcan/transport/can_io.hpp> #include <uavcan/debug.hpp> #include <cassert> namespace uavcan { /** * Frame */ const uint8_t Frame::MaxIndexForService; const uint8_t Frame::MaxIndexForMessage; uint_fast8_t Frame::getMaxIndexForTransferType(const TransferType type) { if (type == TransferTypeMessageBroadcast || type == TransferTypeMessageUnicast) { return MaxIndexForMessage; } else if (type == TransferTypeServiceRequest || type == TransferTypeServiceResponse) { return MaxIndexForService; } else { UAVCAN_ASSERT(0); return 0; } } void Frame::setPriority(const TransferPriority priority) { UAVCAN_ASSERT(priority < NumTransferPriorities); if (transfer_type_ == TransferTypeMessageBroadcast || transfer_type_ == TransferTypeMessageUnicast) { if (priority != TransferPriorityService) { transfer_priority_ = priority; } else { UAVCAN_ASSERT(0); } } else { UAVCAN_ASSERT(0); } } int Frame::getMaxPayloadLen() const { switch (getTransferType()) { case TransferTypeMessageBroadcast: { return int(sizeof(payload_)); } case TransferTypeServiceResponse: case TransferTypeServiceRequest: case TransferTypeMessageUnicast: { return int(sizeof(payload_)) - 1; } default: { UAVCAN_ASSERT(0); return -ErrLogic; } } } int Frame::setPayload(const uint8_t* data, unsigned len) { const int maxlen = getMaxPayloadLen(); if (maxlen < 0) { return maxlen; } len = min(unsigned(maxlen), len); (void)copy(data, data + len, payload_); payload_len_ = uint_fast8_t(len); return int(len); } template <int OFFSET, int WIDTH> inline static uint32_t bitunpack(uint32_t val) { StaticAssert<(OFFSET >= 0)>::check(); StaticAssert<(WIDTH > 0)>::check(); StaticAssert<((OFFSET + WIDTH) <= 29)>::check(); return (val >> OFFSET) & ((1UL << WIDTH) - 1); } bool Frame::parse(const CanFrame& can_frame) { if (can_frame.isErrorFrame() || can_frame.isRemoteTransmissionRequest() || !can_frame.isExtended()) { return false; } if (can_frame.dlc > sizeof(can_frame.data)) { UAVCAN_ASSERT(0); // This is not a protocol error, so UAVCAN_ASSERT() is ok return false; } /* * CAN ID parsing */ const uint32_t id = can_frame.id & CanFrame::MaskExtID; transfer_id_ = uint8_t(bitunpack<0, 3>(id)); last_frame_ = bitunpack<3, 1>(id) != 0; // TT-specific fields skipped transfer_priority_ = TransferPriority(bitunpack<27, 2>(id)); if (transfer_priority_ == TransferPriorityService) { frame_index_ = uint_fast8_t(bitunpack<4, 6>(id)); src_node_id_ = uint8_t(bitunpack<10, 7>(id)); data_type_id_ = uint16_t(bitunpack<17, 9>(id)); // RequestNotResponse transfer_type_ = (bitunpack<26, 1>(id) == 1U) ? TransferTypeServiceRequest : TransferTypeServiceResponse; } else { frame_index_ = uint_fast8_t(bitunpack<4, 4>(id)); // BroadcastNotUnicast transfer_type_ = (bitunpack<8, 1>(id) == 1U) ? TransferTypeMessageBroadcast : TransferTypeMessageUnicast; src_node_id_ = uint8_t(bitunpack<9, 7>(id)); data_type_id_ = uint16_t(bitunpack<16, 11>(id)); } /* * CAN payload parsing */ switch (transfer_type_) { case TransferTypeMessageBroadcast: { dst_node_id_ = NodeID::Broadcast; payload_len_ = can_frame.dlc; (void)copy(can_frame.data, can_frame.data + can_frame.dlc, payload_); break; } case TransferTypeServiceResponse: case TransferTypeServiceRequest: case TransferTypeMessageUnicast: { if (can_frame.dlc < 1) { return false; } if (can_frame.data[0] & 0x80) // RESERVED, must be zero { return false; } dst_node_id_ = can_frame.data[0] & 0x7F; payload_len_ = uint8_t(can_frame.dlc - 1); (void)copy(can_frame.data + 1, can_frame.data + can_frame.dlc, payload_); break; } default: { return false; } } /* * Special case for anonymous transfers - trailing 8 bits of CAN ID must be ignored * - Transfer ID (assumed zero) * - Last Frame (assumed true) * - Frame Index (assumed zero) */ if (src_node_id_.isBroadcast()) { transfer_id_ = TransferID(0); last_frame_ = true; frame_index_ = 0; } return isValid(); } template <int OFFSET, int WIDTH> inline static uint32_t bitpack(uint32_t field) { StaticAssert<(OFFSET >= 0)>::check(); StaticAssert<(WIDTH > 0)>::check(); StaticAssert<((OFFSET + WIDTH) <= 29)>::check(); UAVCAN_ASSERT((field & ((1UL << WIDTH) - 1)) == field); return uint32_t((field & ((1UL << WIDTH) - 1)) << OFFSET); } bool Frame::compile(CanFrame& out_can_frame) const { if (!isValid()) { UAVCAN_ASSERT(0); // This is an application error, so we need to maximize it. return false; } /* * Setting CAN ID field */ // Common fields for messages and services out_can_frame.id = CanFrame::FlagEFF | bitpack<0, 3>(transfer_id_.get()) | bitpack<3, 1>(last_frame_) | /* TT-specific fields skipped */ bitpack<27, 2>(transfer_priority_); if (transfer_type_ == TransferTypeServiceRequest || transfer_type_ == TransferTypeServiceResponse) { out_can_frame.id |= bitpack<4, 6>(frame_index_) | bitpack<10, 7>(src_node_id_.get()) | bitpack<17, 9>(data_type_id_.get()) | bitpack<26, 1>((transfer_type_ == TransferTypeServiceRequest) ? 1U : 0U); } else if (transfer_type_ == TransferTypeMessageBroadcast || transfer_type_ == TransferTypeMessageUnicast) { out_can_frame.id |= bitpack<4, 4>(frame_index_) | bitpack<8, 1>((transfer_type_ == TransferTypeMessageBroadcast) ? 1U : 0U) | bitpack<9, 7>(src_node_id_.get()) | bitpack<16, 11>(data_type_id_.get()); } else { UAVCAN_ASSERT(0); return false; } /* * Setting payload */ switch (transfer_type_) { case TransferTypeMessageBroadcast: { out_can_frame.dlc = uint8_t(payload_len_); (void)copy(payload_, payload_ + payload_len_, out_can_frame.data); break; } case TransferTypeServiceResponse: case TransferTypeServiceRequest: case TransferTypeMessageUnicast: { UAVCAN_ASSERT((payload_len_ + 1U) <= sizeof(out_can_frame.data)); out_can_frame.data[0] = dst_node_id_.get(); out_can_frame.dlc = uint8_t(payload_len_ + 1); (void)copy(payload_, payload_ + payload_len_, out_can_frame.data + 1); break; } default: { UAVCAN_ASSERT(0); return false; } } /* * Setting trailing bits of CAN ID for anonymous message * This overrides the following fields: * - Transfer ID (assumed zero) * - Last Frame (assumed true) * - Frame Index (assumed zero) */ if (src_node_id_.isBroadcast()) { uint8_t sum = 0; out_can_frame.id &= ~bitpack<0, 8>(sum); // Clearing bits for (uint_fast8_t i = 0; i < payload_len_; i++) { sum = static_cast<uint8_t>(sum + payload_[i]); } out_can_frame.id |= bitpack<0, 8>(sum); // Setting the checksum } return true; } bool Frame::isValid() const { /* * Frame index */ if (frame_index_ > getMaxIndex()) { UAVCAN_TRACE("Frame", "Validness check failed at line %d", __LINE__); return false; } if ((frame_index_ == getMaxIndex()) && !last_frame_) { UAVCAN_TRACE("Frame", "Validness check failed at line %d", __LINE__); return false; } /* * Node ID */ if (!src_node_id_.isValid() || !dst_node_id_.isValid()) { UAVCAN_TRACE("Frame", "Validness check failed at line %d", __LINE__); return false; } if (src_node_id_.isUnicast() && (src_node_id_ == dst_node_id_)) { UAVCAN_TRACE("Frame", "Validness check failed at line %d", __LINE__); return false; } /* * Transfer type */ if (transfer_type_ >= NumTransferTypes) { UAVCAN_TRACE("Frame", "Validness check failed at line %d", __LINE__); return false; } if ((transfer_type_ == TransferTypeMessageBroadcast) != dst_node_id_.isBroadcast()) { UAVCAN_TRACE("Frame", "Validness check failed at line %d", __LINE__); return false; } // Anonymous transfers if (src_node_id_.isBroadcast() && (!last_frame_ || (frame_index_ > 0) || (transfer_type_ != TransferTypeMessageBroadcast))) { return false; } /* * Payload */ if (static_cast<int>(payload_len_) > getMaxPayloadLen()) { UAVCAN_TRACE("Frame", "Validness check failed at line %d", __LINE__); return false; } /* * Data type ID */ if (!data_type_id_.isValidForDataTypeKind(getDataTypeKindForTransferType(transfer_type_))) { UAVCAN_TRACE("Frame", "Validness check failed at line %d", __LINE__); return false; } /* * Priority */ if (transfer_priority_ >= NumTransferPriorities) { UAVCAN_TRACE("Frame", "Validness check failed at line %d", __LINE__); return false; } if (transfer_type_ == TransferTypeServiceRequest || transfer_type_ == TransferTypeServiceResponse) { if (transfer_priority_ != TransferPriorityService) { UAVCAN_TRACE("Frame", "Validness check failed at line %d", __LINE__); return false; } } return true; } bool Frame::operator==(const Frame& rhs) const { return (transfer_priority_ == rhs.transfer_priority_) && (transfer_type_ == rhs.transfer_type_) && (data_type_id_ == rhs.data_type_id_) && (src_node_id_ == rhs.src_node_id_) && (dst_node_id_ == rhs.dst_node_id_) && (frame_index_ == rhs.frame_index_) && (transfer_id_ == rhs.transfer_id_) && (last_frame_ == rhs.last_frame_) && (payload_len_ == rhs.payload_len_) && equal(payload_, payload_ + payload_len_, rhs.payload_); } #if UAVCAN_TOSTRING std::string Frame::toString() const { /* * - Priority * - Data Type ID * - Transfer Type * - Source Node ID * - Frame Index * - Last Frame * - Transfer ID */ static const int BUFLEN = 100; char buf[BUFLEN]; int ofs = snprintf(buf, BUFLEN, "prio=%d dtid=%d tt=%d snid=%d dnid=%d idx=%d last=%d tid=%d payload=[", int(transfer_priority_), int(data_type_id_.get()), int(transfer_type_), int(src_node_id_.get()), int(dst_node_id_.get()), int(frame_index_), int(last_frame_), int(transfer_id_.get())); for (unsigned i = 0; i < payload_len_; i++) { // Coverity Scan complains about payload_ being not default initialized. This is OK. // coverity[read_parm_fld] ofs += snprintf(buf + ofs, unsigned(BUFLEN - ofs), "%02x", payload_[i]); if ((i + 1) < payload_len_) { ofs += snprintf(buf + ofs, unsigned(BUFLEN - ofs), " "); } } (void)snprintf(buf + ofs, unsigned(BUFLEN - ofs), "]"); return std::string(buf); } #endif /** * RxFrame */ bool RxFrame::parse(const CanRxFrame& can_frame) { if (!Frame::parse(can_frame)) { return false; } if (can_frame.ts_mono.isZero()) // Monotonic timestamps are mandatory. { UAVCAN_ASSERT(0); // If it is not set, it's a driver failure. return false; } ts_mono_ = can_frame.ts_mono; ts_utc_ = can_frame.ts_utc; iface_index_ = can_frame.iface_index; return true; } #if UAVCAN_TOSTRING std::string RxFrame::toString() const { std::string out = Frame::toString(); out.reserve(128); out += " ts_m=" + ts_mono_.toString(); out += " ts_utc=" + ts_utc_.toString(); out += " iface="; out += char('0' + iface_index_); return out; } #endif } <|endoftext|>
<commit_before>/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #include "vast/system/pivot_command.hpp" #include "vast/defaults.hpp" #include "vast/detail/assert.hpp" #include "vast/detail/make_io_stream.hpp" #include "vast/error.hpp" #include "vast/format/csv.hpp" #include "vast/format/json.hpp" #include "vast/format/pcap.hpp" #include "vast/format/zeek.hpp" #include "vast/logger.hpp" #include "vast/scope_linked.hpp" #include "vast/system/atoms.hpp" #include "vast/system/read_query.hpp" #include "vast/system/signal_monitor.hpp" #include "vast/system/sink.hpp" #include "vast/system/sink_command.hpp" #include "vast/system/spawn_or_connect_to_node.hpp" #include "vast/system/tracker.hpp" #include <caf/event_based_actor.hpp> #include <caf/scoped_actor.hpp> #include <caf/settings.hpp> #include <caf/stateful_actor.hpp> #include <caf/typed_event_based_actor.hpp> #include <csignal> #include <string> #include <string_view> using namespace std::chrono_literals; namespace vast::system { namespace { template <class Writer> caf::expected<caf::actor> make_writer(caf::actor_system& sys, const caf::settings& options) { using defaults = typename Writer::defaults; using ostream_ptr = std::unique_ptr<std::ostream>; std::string category = defaults::category; if constexpr (std::is_constructible_v<Writer, ostream_ptr>) { auto output = get_or(options, category + ".write", defaults::write); auto uds = get_or(options, category + ".uds", false); auto out = detail::make_output_stream(output, uds); if (!out) return out.error(); Writer writer{std::move(*out)}; return sys.spawn(sink<Writer>, std::move(writer), max_events); } else { Writer writer; return sys.spawn(sink<Writer>, std::move(writer), max_events); } } } // namespace caf::message pivot_command(const command::invocation& invocation, caf::actor_system& sys) { VAST_TRACE(invocation); // Read query from input file, STDIN or CLI arguments. auto query = read_query(invocation, "export.read", size_t{1}); if (!query) return caf::make_message(std::move(query.error())); auto& options = invocation.options; auto& target = invocation.arguments[0]; // using caf::get_or; auto limit = get_or(options, "export.max-events", defaults::export_::max_events); caf::actor writer; if (detail::starts_with(target, "pcap")) { using defaults_t = defaults::export_::pcap; std::string category = defaults_t::category; auto output = get_or(options, category + ".write", defaults_t::write); auto flush = get_or(options, category + ".flush-interval", defaults_t::flush_interval); format::pcap::writer w{output, flush}; writer = sys.spawn(sink<format::pcap::writer>, std::move(w), limit); } else if (detail::starts_with(target, "suricata")) { auto w = make_writer<format::json::writer>(sys, invocation.options); if (!w) return make_message(w.error()); writer = *w; } else if (detail::starts_with(target, "zeek")) { auto w = make_writer<format::zeek::writer>(sys, invocation.options); if (!w) return make_message(w.error()); writer = *w; } else return make_message(make_error(ec::unimplemented, "pivoting is only " "implemented for pcap, " "suricata and zeek")); caf::scoped_actor self{sys}; // Get VAST node. auto node_opt = spawn_or_connect_to_node(self, invocation.options, content(sys.config())); if (auto err = caf::get_if<caf::error>(&node_opt)) return caf::make_message(std::move(*err)); auto& node = caf::holds_alternative<caf::actor>(node_opt) ? caf::get<caf::actor>(node_opt) : caf::get<scope_linked_actor>(node_opt).get(); VAST_ASSERT(node != nullptr); // TODO(ch9412): Factor guard into a function. // Start signal monitor. std::thread sig_mon_thread; auto guard = signal_monitor::run_guarded(sig_mon_thread, sys, 750ms, self); // Spawn exporter at the node. caf::actor exp; auto exporter_invocation = command::invocation{invocation.options, "spawn exporter", {*query}}; VAST_DEBUG(invocation.full_name, "spawns exporter with parameters:", exporter_invocation); error err; self->request(node, caf::infinite, std::move(exporter_invocation)) .receive( [&](caf::actor& a) { exp = std::move(a); if (!exp) err = make_error(ec::invalid_result, "remote spawn returned nullptr"); }, [&](error& e) { err = std::move(e); }); if (err) { self->send_exit(writer, caf::exit_reason::user_shutdown); return caf::make_message(std::move(err)); } // Spawn pivoter at the node. caf::actor piv; auto pivoter_invocation = command::invocation{ invocation.options, "spawn pivoter", {invocation.arguments[0], *query}}; VAST_DEBUG(invocation.full_name, "spawns exporter with parameters:", pivoter_invocation); self->request(node, caf::infinite, std::move(pivoter_invocation)) .receive( [&](caf::actor& a) { piv = std::move(a); if (!piv) err = make_error(ec::invalid_result, "remote spawn returned nullptr"); }, [&](error& e) { err = std::move(e); }); if (err) { self->send_exit(exp, caf::exit_reason::user_shutdown); self->send_exit(writer, caf::exit_reason::user_shutdown); return caf::make_message(std::move(err)); } self->request(node, caf::infinite, get_atom::value) .receive( [&](const std::string& id, system::registry& reg) { // Assign accountant to sink. VAST_DEBUG(invocation.full_name, "assigns accountant from node", id, "to new sink"); auto er = reg.components[id].find("accountant"); if (er != reg.components[id].end()) { auto accountant = er->second.actor; self->send(writer, caf::actor_cast<accountant_type>(accountant)); } }, [&](error& e) { err = std::move(e); }); if (err) { self->send_exit(writer, caf::exit_reason::user_shutdown); return caf::make_message(std::move(err)); } self->monitor(writer); self->monitor(piv); // Start the exporter. self->send(exp, system::sink_atom::value, piv); // (Ab)use query_statistics as done message. self->send(exp, system::statistics_atom::value, piv); self->send(piv, system::sink_atom::value, writer); self->send(exp, system::run_atom::value); auto stop = false; self ->do_receive( [&](caf::down_msg& msg) { if (msg.source == node) { VAST_DEBUG_ANON(__func__, "received DOWN from node"); self->send_exit(writer, caf::exit_reason::user_shutdown); self->send_exit(exp, caf::exit_reason::user_shutdown); self->send_exit(piv, caf::exit_reason::user_shutdown); } else if (msg.source == piv) { VAST_DEBUG(invocation.full_name, "received DOWN from pivoter"); self->send_exit(exp, caf::exit_reason::user_shutdown); self->send_exit(writer, caf::exit_reason::user_shutdown); } else if (msg.source == writer) { VAST_DEBUG(invocation.full_name, "received DOWN from sink"); self->send_exit(exp, caf::exit_reason::user_shutdown); self->send_exit(piv, caf::exit_reason::user_shutdown); } else { VAST_ASSERT(!"received DOWN from inexplicable actor"); } if (msg.reason) { VAST_WARNING(invocation.full_name, "received error message:", self->system().render(msg.reason)); err = std::move(msg.reason); } stop = true; }, [&](system::signal_atom, int signal) { VAST_DEBUG(invocation.full_name, "got " << ::strsignal(signal)); if (signal == SIGINT || signal == SIGTERM) { self->send_exit(exp, caf::exit_reason::user_shutdown); self->send_exit(piv, caf::exit_reason::user_shutdown); self->send_exit(writer, caf::exit_reason::user_shutdown); } }) .until([&] { return stop; }); if (err) return caf::make_message(std::move(err)); return caf::none; } } // namespace vast::system <commit_msg>Use node control functions in pivoter command<commit_after>/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #include "vast/system/pivot_command.hpp" #include "vast/defaults.hpp" #include "vast/detail/assert.hpp" #include "vast/detail/make_io_stream.hpp" #include "vast/error.hpp" #include "vast/format/csv.hpp" #include "vast/format/json.hpp" #include "vast/format/pcap.hpp" #include "vast/format/zeek.hpp" #include "vast/logger.hpp" #include "vast/scope_linked.hpp" #include "vast/system/atoms.hpp" #include "vast/system/node_control.hpp" #include "vast/system/read_query.hpp" #include "vast/system/signal_monitor.hpp" #include "vast/system/sink.hpp" #include "vast/system/sink_command.hpp" #include "vast/system/spawn_or_connect_to_node.hpp" #include "vast/system/tracker.hpp" #include <caf/event_based_actor.hpp> #include <caf/scoped_actor.hpp> #include <caf/settings.hpp> #include <caf/stateful_actor.hpp> #include <caf/typed_event_based_actor.hpp> #include <csignal> #include <string> #include <string_view> using namespace std::chrono_literals; namespace vast::system { namespace { template <class Writer> caf::expected<caf::actor> make_writer(caf::actor_system& sys, const caf::settings& options) { using defaults = typename Writer::defaults; using ostream_ptr = std::unique_ptr<std::ostream>; std::string category = defaults::category; if constexpr (std::is_constructible_v<Writer, ostream_ptr>) { auto output = get_or(options, category + ".write", defaults::write); auto uds = get_or(options, category + ".uds", false); auto out = detail::make_output_stream(output, uds); if (!out) return out.error(); Writer writer{std::move(*out)}; return sys.spawn(sink<Writer>, std::move(writer), max_events); } else { Writer writer; return sys.spawn(sink<Writer>, std::move(writer), max_events); } } } // namespace caf::message pivot_command(const command::invocation& invocation, caf::actor_system& sys) { VAST_TRACE(invocation); // Read query from input file, STDIN or CLI arguments. auto query = read_query(invocation, "export.read", size_t{1}); if (!query) return caf::make_message(std::move(query.error())); auto& options = invocation.options; auto& target = invocation.arguments[0]; // using caf::get_or; auto limit = get_or(options, "export.max-events", defaults::export_::max_events); caf::actor writer; if (detail::starts_with(target, "pcap")) { using defaults_t = defaults::export_::pcap; std::string category = defaults_t::category; auto output = get_or(options, category + ".write", defaults_t::write); auto flush = get_or(options, category + ".flush-interval", defaults_t::flush_interval); format::pcap::writer w{output, flush}; writer = sys.spawn(sink<format::pcap::writer>, std::move(w), limit); } else if (detail::starts_with(target, "suricata")) { auto w = make_writer<format::json::writer>(sys, invocation.options); if (!w) return make_message(w.error()); writer = *w; } else if (detail::starts_with(target, "zeek")) { auto w = make_writer<format::zeek::writer>(sys, invocation.options); if (!w) return make_message(w.error()); writer = *w; } else return make_message(make_error(ec::unimplemented, "pivoting is only " "implemented for pcap, " "suricata and zeek")); caf::scoped_actor self{sys}; auto writer_guard = caf::detail::make_scope_guard( [&] { self->send_exit(writer, caf::exit_reason::user_shutdown); }); // Get VAST node. auto node_opt = spawn_or_connect_to_node(self, invocation.options, content(sys.config())); if (auto err = caf::get_if<caf::error>(&node_opt)) return caf::make_message(std::move(*err)); auto& node = caf::holds_alternative<caf::actor>(node_opt) ? caf::get<caf::actor>(node_opt) : caf::get<scope_linked_actor>(node_opt).get(); VAST_ASSERT(node != nullptr); // TODO(ch9412): Factor guard into a function. // Start signal monitor. std::thread sig_mon_thread; auto signal_guard = signal_monitor::run_guarded(sig_mon_thread, sys, 750ms, self); // Spawn exporter at the node. auto spawn_exporter = command::invocation{invocation.options, "spawn exporter", {*query}}; VAST_DEBUG(&invocation, "spawns exporter with parameters:", spawn_exporter); auto exp = spawn_at_node(self, node, spawn_exporter); if (!exp) return caf::make_message(std::move(exp.error())); auto exp_guard = caf::detail::make_scope_guard( [&] { self->send_exit(*exp, caf::exit_reason::user_shutdown); }); // Spawn pivoter at the node. auto spawn_pivoter = command::invocation{ invocation.options, "spawn pivoter", {invocation.arguments[0], *query}}; VAST_DEBUG(&invocation, "spawns pivoter with parameters:", spawn_pivoter); auto piv = spawn_at_node(self, node, spawn_pivoter); if (!piv) return caf::make_message(std::move(piv.error())); auto piv_guard = caf::detail::make_scope_guard( [&] { self->send_exit(*piv, caf::exit_reason::user_shutdown); }); // Register the accountant at the Sink. auto components = get_node_component<accountant_atom>(self, node); if (!components) return caf::make_message(std::move(components.error())); auto& [accountant] = *components; if (accountant) { VAST_DEBUG(invocation.full_name, "assigns accountant to writer"); self->send(writer, caf::actor_cast<accountant_type>(*accountant)); } caf::error err; self->monitor(writer); self->monitor(*piv); // Start the exporter. self->send(*exp, system::sink_atom::value, *piv); // (Ab)use query_statistics as done message. self->send(*exp, system::statistics_atom::value, *piv); self->send(*piv, system::sink_atom::value, writer); self->send(*exp, system::run_atom::value); auto stop = false; self ->do_receive( [&](caf::down_msg& msg) { if (msg.source == node) { VAST_DEBUG(invocation.full_name, "received DOWN from node"); } else if (msg.source == *piv) { VAST_DEBUG(invocation.full_name, "received DOWN from pivoter"); piv_guard.disable(); } else if (msg.source == writer) { VAST_DEBUG(invocation.full_name, "received DOWN from sink"); writer_guard.disable(); } else { VAST_ASSERT(!"received DOWN from inexplicable actor"); } if (msg.reason) { VAST_WARNING(invocation.full_name, "received error message:", self->system().render(msg.reason)); err = std::move(msg.reason); } stop = true; }, [&](system::signal_atom, int signal) { VAST_DEBUG(invocation.full_name, "got " << ::strsignal(signal)); if (signal == SIGINT || signal == SIGTERM) { stop = true; } }) .until([&] { return stop; }); if (err) return caf::make_message(std::move(err)); return caf::none; } } // namespace vast::system <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sal.hxx" #include "system.h" #include <osl/process.h> #include <sal/types.h> #ifdef __cplusplus extern "C" { #endif // Prototypes for initialization and deinitialization of SAL library void SAL_CALL sal_detail_initialize(int argc, char ** argv) { WSADATA wsaData; int error; WORD wVersionRequested; wVersionRequested = MAKEWORD(1, 1); error = WSAStartup(wVersionRequested, &wsaData); if ( 0 == error ) { WORD wMajorVersionRequired = 1; WORD wMinorVersionRequired = 1; if ((LOBYTE(wsaData.wVersion) < wMajorVersionRequired) || (LOBYTE(wsaData.wVersion) == wMajorVersionRequired) && ((HIBYTE(wsaData.wVersion) < wMinorVersionRequired))) { // How to handle a very unlikely error ??? } } else { // How to handle a very unlikely error ??? } osl_setCommandArgs(argc, argv); } void SAL_CALL sal_detail_deinitialize() { if ( SOCKET_ERROR == WSACleanup() ) { // We should never reach this point or we did wrong elsewhere } } #ifdef __cplusplus } // extern "C" #endif <commit_msg>mhu23 #i113531# use recommended Windows linker flags and DLL search path.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sal.hxx" #include "system.h" #include <osl/process.h> #include <sal/types.h> #ifdef __cplusplus extern "C" { #endif // Prototypes for initialization and deinitialization of SAL library void SAL_CALL sal_detail_initialize(int argc, char ** argv) { // SetProcessDEPPolicy(PROCESS_DEP_ENABLE); // SetDllDirectoryW(L""); // SetSearchPathMode( // BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE | BASE_SEARCH_PATH_PERMANENT); HMODULE h = GetModuleHandleW(L"kernel32.dll"); if (h != 0) { FARPROC p = GetProcAddress(h, "SetProcessDEPPolicy"); if (p != 0) { reinterpret_cast< BOOL (WINAPI *)(DWORD) >(p)(0x00000001); } p = GetProcAddress(h, "SetDllDirectoryW"); if (p != 0) { reinterpret_cast< BOOL (WINAPI *)(LPCWSTR) >(p)(L""); } p = GetProcAddress(h, "SetSearchPathMode"); if (p != 0) { reinterpret_cast< BOOL (WINAPI *)(DWORD) >(p)(0x8001); } } WSADATA wsaData; int error; WORD wVersionRequested; wVersionRequested = MAKEWORD(1, 1); error = WSAStartup(wVersionRequested, &wsaData); if ( 0 == error ) { WORD wMajorVersionRequired = 1; WORD wMinorVersionRequired = 1; if ((LOBYTE(wsaData.wVersion) < wMajorVersionRequired) || (LOBYTE(wsaData.wVersion) == wMajorVersionRequired) && ((HIBYTE(wsaData.wVersion) < wMinorVersionRequired))) { // How to handle a very unlikely error ??? } } else { // How to handle a very unlikely error ??? } osl_setCommandArgs(argc, argv); } void SAL_CALL sal_detail_deinitialize() { if ( SOCKET_ERROR == WSACleanup() ) { // We should never reach this point or we did wrong elsewhere } } #ifdef __cplusplus } // extern "C" #endif <|endoftext|>
<commit_before>/* alm_cui.cpp Copyright (c) 2014, 2015, 2016 Terumasa Tadano This file is distributed under the terms of the MIT license. Please see the file 'LICENCE.txt' in the root directory or http://opensource.org/licenses/mit-license.php for information. */ #include "alm_cui.h" #include "alm.h" #include "input_parser.h" #include "timer.h" #include "version.h" #include "writer.h" #include <iostream> #include <iomanip> #ifdef _OPENMP #include <omp.h> #endif using namespace ALM_NS; ALMCUI::ALMCUI() {} ALMCUI::~ALMCUI() {} void ALMCUI::run(const int narg, char **arg) const { auto alm = new ALM(); // alm->mode is set herein. auto input_parser = new InputParser(); input_parser->run(alm, narg, arg); auto run_mode = input_parser->get_run_mode(); delete input_parser; if (alm->get_verbosity() > 0) { std::cout << " +-----------------------------------------------------------------+" << std::endl; std::cout << " + Program ALM +" << std::endl; std::cout << " + Ver."; std::cout << std::setw(7) << ALAMODE_VERSION; std::cout << " +" << std::endl; std::cout << " +-----------------------------------------------------------------+" << std::endl; std::cout << std::endl; #ifdef _OPENMP std::cout << " Number of OpenMP threads = " << omp_get_max_threads() << std::endl << std::endl; #endif std::cout << " Job started at " << alm->timer->DateAndTime() << std::endl; } auto writer = new Writer(); if (alm->get_verbosity() > 0) { writer->write_input_vars(alm, run_mode); } alm->init_fc_table(); if (run_mode == "optimize") { alm->run_optimize(); if (alm->get_optimizer_control().linear_model == 1 || (alm->get_optimizer_control().linear_model >= 2 && alm->get_optimizer_control().cross_validation == 0)) { writer->writeall(alm); } } else if (run_mode == "suggest") { alm->run_suggest(); writer->write_displacement_pattern(alm); } delete writer; if (alm->get_verbosity() > 0) { std::cout << std::endl << " Job finished at " << alm->timer->DateAndTime() << std::endl; } delete alm; } <commit_msg>Minor output formatting<commit_after>/* alm_cui.cpp Copyright (c) 2014, 2015, 2016 Terumasa Tadano This file is distributed under the terms of the MIT license. Please see the file 'LICENCE.txt' in the root directory or http://opensource.org/licenses/mit-license.php for information. */ #include "alm_cui.h" #include "alm.h" #include "input_parser.h" #include "timer.h" #include "version.h" #include "writer.h" #include <iostream> #include <iomanip> #ifdef _OPENMP #include <omp.h> #endif using namespace ALM_NS; ALMCUI::ALMCUI() {} ALMCUI::~ALMCUI() {} void ALMCUI::run(const int narg, char **arg) const { auto alm = new ALM(); // alm->mode is set herein. auto input_parser = new InputParser(); input_parser->run(alm, narg, arg); auto run_mode = input_parser->get_run_mode(); delete input_parser; if (alm->get_verbosity() > 0) { std::cout << " +-----------------------------------------------------------------+" << std::endl; std::cout << " + Program ALM +" << std::endl; std::cout << " + Ver."; std::cout << std::setw(7) << ALAMODE_VERSION; std::cout << " +" << std::endl; std::cout << " +-----------------------------------------------------------------+" << std::endl; std::cout << std::endl; #ifdef _OPENMP std::cout << " Number of OpenMP threads = " << omp_get_max_threads() << std::endl << std::endl; #endif std::cout << " Job started at " << alm->timer->DateAndTime() << std::endl; } auto writer = new Writer(); if (alm->get_verbosity() > 0) { writer->write_input_vars(alm, run_mode); } alm->init_fc_table(); if (run_mode == "optimize") { alm->run_optimize(); if (alm->get_optimizer_control().linear_model == 1 || (alm->get_optimizer_control().linear_model >= 2 && alm->get_optimizer_control().cross_validation == 0)) { writer->writeall(alm); } } else if (run_mode == "suggest") { alm->run_suggest(); writer->write_displacement_pattern(alm); } delete writer; if (alm->get_verbosity() > 0) { std::cout << std::endl << " Job finished at " << alm->timer->DateAndTime() << std::endl; } delete alm; } <|endoftext|>
<commit_before>/*========================================================================= Program: KWSys - Kitware System Library Module: DynamicLoader.cxx Copyright (c) Kitware, Inc., Insight Consortium. All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "kwsysPrivate.h" #include KWSYS_HEADER(DynamicLoader.hxx) #include KWSYS_HEADER(Configure.hxx) // Work-around CMake dependency scanning limitation. This must // duplicate the above list of headers. #if 0 # include "DynamicLoader.hxx.in" # include "Configure.hxx.in" #endif // This file is actually 3 different implementations. // 1. HP machines which uses shl_load // 2. Power PC MAC which uses GetSharedLibrary // 3. Windows which uses LoadLibrary // 4. Most unix systems which use dlopen (default ) // Each part of the ifdef contains a complete implementation for // the static methods of DynamicLoader. namespace KWSYS_NAMESPACE { //---------------------------------------------------------------------------- DynamicLoader::DynamicLoader() { } //---------------------------------------------------------------------------- DynamicLoader::~DynamicLoader() { } } // --------------------------------------------------------------- // 1. Implementation for HPUX machines #ifdef __hpux #include <dl.h> #define DYNAMICLOADER_DEFINED 1 namespace KWSYS_NAMESPACE { //---------------------------------------------------------------------------- LibHandle DynamicLoader::OpenLibrary(const char* libname ) { return shl_load(libname, BIND_DEFERRED | DYNAMIC_PATH, 0L); } //---------------------------------------------------------------------------- int DynamicLoader::CloseLibrary(LibHandle lib) { return !shl_unload(lib); } //---------------------------------------------------------------------------- DynamicLoaderFunction DynamicLoader::GetSymbolAddress(LibHandle lib, const char* sym) { void* addr; int status; status = shl_findsym (&lib, sym, TYPE_PROCEDURE, &addr); void* result = (status < 0) ? (void*)0 : addr; // Hack to cast pointer-to-data to pointer-to-function. return *reinterpret_cast<DynamicLoaderFunction*>(&result); } //---------------------------------------------------------------------------- const char* DynamicLoader::LibPrefix() { return "lib"; } //---------------------------------------------------------------------------- const char* DynamicLoader::LibExtension() { return ".sl"; } //---------------------------------------------------------------------------- const char* DynamicLoader::LastError() { // TODO: Need implementation with errno/strerror /* If successful, shl_findsym returns an integer (int) value zero. If * shl_findsym cannot find sym, it returns -1 and sets errno to zero. * If any other errors occur, shl_findsym returns -1 and sets errno to one * of these values (defined in <errno.h>): * ENOEXEC * A format error was detected in the specified library. * ENOSYM * A symbol on which sym depends could not be found. * EINVAL * The specified handle is invalid. */ return 0; } } // namespace KWSYS_NAMESPACE #endif //__hpux // --------------------------------------------------------------- // 2. Implementation for Mac OS X 10.2.x and earlier #ifdef __APPLE__ #if MAC_OS_X_VERSION_MIN_REQUIRED < 1030 #include <mach-o/dyld.h> #define DYNAMICLOADER_DEFINED 1 namespace KWSYS_NAMESPACE { //---------------------------------------------------------------------------- LibHandle DynamicLoader::OpenLibrary(const char* libname ) { NSObjectFileImageReturnCode rc; NSObjectFileImage image = 0; rc = NSCreateObjectFileImageFromFile(libname, &image); if(!image) { return 0; } return NSLinkModule(image, libname, NSLINKMODULE_OPTION_BINDNOW); } //---------------------------------------------------------------------------- int DynamicLoader::CloseLibrary( LibHandle lib) { DYLD_BOOL success = NSUnLinkModule(lib, NSUNLINKMODULE_OPTION_NONE); return success; } //---------------------------------------------------------------------------- DynamicLoaderFunction DynamicLoader::GetSymbolAddress(LibHandle /* lib */, const char* sym) { void *result=0; if(NSIsSymbolNameDefined(sym)) { NSSymbol symbol= NSLookupAndBindSymbol(sym); if(symbol) { result = NSAddressOfSymbol(symbol); } } // Hack to cast pointer-to-data to pointer-to-function. return *reinterpret_cast<DynamicLoaderFunction*>(&result); } //---------------------------------------------------------------------------- const char* DynamicLoader::LibPrefix() { return ""; } //---------------------------------------------------------------------------- const char* DynamicLoader::LibExtension() { return ".dylib"; } //---------------------------------------------------------------------------- const char* DynamicLoader::LastError() { return 0; } } // namespace KWSYS_NAMESPACE #endif //MAC_OS_X_VERSION_MIN_REQUIRED < 1030 #endif // __APPLE__ // --------------------------------------------------------------- // 3. Implementation for Windows win32 code #ifdef _WIN32 #include <windows.h> #define DYNAMICLOADER_DEFINED 1 namespace KWSYS_NAMESPACE { //---------------------------------------------------------------------------- LibHandle DynamicLoader::OpenLibrary(const char* libname) { LibHandle lh; #ifdef UNICODE wchar_t libn[MB_CUR_MAX]; mbstowcs(libn, libname, MB_CUR_MAX); lh = LoadLibrary(libn); #else lh = LoadLibrary(libname); #endif return lh; } //---------------------------------------------------------------------------- int DynamicLoader::CloseLibrary(LibHandle lib) { return (int)FreeLibrary(lib); } //---------------------------------------------------------------------------- DynamicLoaderFunction DynamicLoader::GetSymbolAddress(LibHandle lib, const char* sym) { void *result; #ifdef UNICODE wchar_t wsym[MB_CUR_MAX]; mbstowcs(wsym, sym, MB_CUR_MAX); result = GetProcAddress(lib, wsym); #else result = (void*)GetProcAddress(lib, sym); #endif // Hack to cast pointer-to-data to pointer-to-function. return *reinterpret_cast<DynamicLoaderFunction*>(&result); } //---------------------------------------------------------------------------- const char* DynamicLoader::LibPrefix() { return ""; } //---------------------------------------------------------------------------- const char* DynamicLoader::LibExtension() { return ".dll"; } //---------------------------------------------------------------------------- const char* DynamicLoader::LastError() { LPVOID lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR) &lpMsgBuf, 0, NULL ); static char* str = 0; delete [] str; str = strcpy(new char[strlen((char*)lpMsgBuf)+1], (char*)lpMsgBuf); // Free the buffer. LocalFree( lpMsgBuf ); return str; } } // namespace KWSYS_NAMESPACE #endif //_WIN32 // --------------------------------------------------------------- // 4. Implementation for default UNIX machines. // if nothing has been defined then use this #ifndef DYNAMICLOADER_DEFINED #define DYNAMICLOADER_DEFINED 1 // Setup for most unix machines #include <dlfcn.h> namespace KWSYS_NAMESPACE { //---------------------------------------------------------------------------- LibHandle DynamicLoader::OpenLibrary(const char* libname ) { return dlopen(libname, RTLD_LAZY); } //---------------------------------------------------------------------------- int DynamicLoader::CloseLibrary(LibHandle lib) { if (lib) { // The function dlclose() returns 0 on success, and non-zero on error. return !(int)dlclose(lib); } // else return 0; } //---------------------------------------------------------------------------- DynamicLoaderFunction DynamicLoader::GetSymbolAddress(LibHandle lib, const char* sym) { void* result = dlsym(lib, sym); // Hack to cast pointer-to-data to pointer-to-function. return *reinterpret_cast<DynamicLoaderFunction*>(&result); } //---------------------------------------------------------------------------- const char* DynamicLoader::LibPrefix() { return "lib"; } //---------------------------------------------------------------------------- const char* DynamicLoader::LibExtension() { return ".so"; } //---------------------------------------------------------------------------- const char* DynamicLoader::LastError() { return dlerror(); } } // namespace KWSYS_NAMESPACE #endif <commit_msg>COMP: Fix compilation on MacOSX<commit_after>/*========================================================================= Program: KWSys - Kitware System Library Module: DynamicLoader.cxx Copyright (c) Kitware, Inc., Insight Consortium. All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "kwsysPrivate.h" #include KWSYS_HEADER(DynamicLoader.hxx) #include KWSYS_HEADER(Configure.hxx) // Work-around CMake dependency scanning limitation. This must // duplicate the above list of headers. #if 0 # include "DynamicLoader.hxx.in" # include "Configure.hxx.in" #endif // This file is actually 3 different implementations. // 1. HP machines which uses shl_load // 2. Power PC MAC which uses GetSharedLibrary // 3. Windows which uses LoadLibrary // 4. Most unix systems which use dlopen (default ) // Each part of the ifdef contains a complete implementation for // the static methods of DynamicLoader. namespace KWSYS_NAMESPACE { //---------------------------------------------------------------------------- DynamicLoader::DynamicLoader() { } //---------------------------------------------------------------------------- DynamicLoader::~DynamicLoader() { } } // --------------------------------------------------------------- // 1. Implementation for HPUX machines #ifdef __hpux #include <dl.h> #define DYNAMICLOADER_DEFINED 1 namespace KWSYS_NAMESPACE { //---------------------------------------------------------------------------- LibHandle DynamicLoader::OpenLibrary(const char* libname ) { return shl_load(libname, BIND_DEFERRED | DYNAMIC_PATH, 0L); } //---------------------------------------------------------------------------- int DynamicLoader::CloseLibrary(LibHandle lib) { return !shl_unload(lib); } //---------------------------------------------------------------------------- DynamicLoaderFunction DynamicLoader::GetSymbolAddress(LibHandle lib, const char* sym) { void* addr; int status; status = shl_findsym (&lib, sym, TYPE_PROCEDURE, &addr); void* result = (status < 0) ? (void*)0 : addr; // Hack to cast pointer-to-data to pointer-to-function. return *reinterpret_cast<DynamicLoaderFunction*>(&result); } //---------------------------------------------------------------------------- const char* DynamicLoader::LibPrefix() { return "lib"; } //---------------------------------------------------------------------------- const char* DynamicLoader::LibExtension() { return ".sl"; } //---------------------------------------------------------------------------- const char* DynamicLoader::LastError() { // TODO: Need implementation with errno/strerror /* If successful, shl_findsym returns an integer (int) value zero. If * shl_findsym cannot find sym, it returns -1 and sets errno to zero. * If any other errors occur, shl_findsym returns -1 and sets errno to one * of these values (defined in <errno.h>): * ENOEXEC * A format error was detected in the specified library. * ENOSYM * A symbol on which sym depends could not be found. * EINVAL * The specified handle is invalid. */ return 0; } } // namespace KWSYS_NAMESPACE #endif //__hpux // --------------------------------------------------------------- // 2. Implementation for Mac OS X 10.2.x and earlier #ifdef __APPLE__ #if MAC_OS_X_VERSION_MIN_REQUIRED < 1030 #include <mach-o/dyld.h> #define DYNAMICLOADER_DEFINED 1 namespace KWSYS_NAMESPACE { //---------------------------------------------------------------------------- LibHandle DynamicLoader::OpenLibrary(const char* libname ) { NSObjectFileImageReturnCode rc; NSObjectFileImage image = 0; rc = NSCreateObjectFileImageFromFile(libname, &image); if(!image) { return 0; } return NSLinkModule(image, libname, NSLINKMODULE_OPTION_BINDNOW); } //---------------------------------------------------------------------------- int DynamicLoader::CloseLibrary( LibHandle lib) { bool success = NSUnLinkModule(lib, NSUNLINKMODULE_OPTION_NONE); return success; } //---------------------------------------------------------------------------- DynamicLoaderFunction DynamicLoader::GetSymbolAddress(LibHandle /* lib */, const char* sym) { void *result=0; if(NSIsSymbolNameDefined(sym)) { NSSymbol symbol= NSLookupAndBindSymbol(sym); if(symbol) { result = NSAddressOfSymbol(symbol); } } // Hack to cast pointer-to-data to pointer-to-function. return *reinterpret_cast<DynamicLoaderFunction*>(&result); } //---------------------------------------------------------------------------- const char* DynamicLoader::LibPrefix() { return ""; } //---------------------------------------------------------------------------- const char* DynamicLoader::LibExtension() { return ".dylib"; } //---------------------------------------------------------------------------- const char* DynamicLoader::LastError() { return 0; } } // namespace KWSYS_NAMESPACE #endif //MAC_OS_X_VERSION_MIN_REQUIRED < 1030 #endif // __APPLE__ // --------------------------------------------------------------- // 3. Implementation for Windows win32 code #ifdef _WIN32 #include <windows.h> #define DYNAMICLOADER_DEFINED 1 namespace KWSYS_NAMESPACE { //---------------------------------------------------------------------------- LibHandle DynamicLoader::OpenLibrary(const char* libname) { LibHandle lh; #ifdef UNICODE wchar_t libn[MB_CUR_MAX]; mbstowcs(libn, libname, MB_CUR_MAX); lh = LoadLibrary(libn); #else lh = LoadLibrary(libname); #endif return lh; } //---------------------------------------------------------------------------- int DynamicLoader::CloseLibrary(LibHandle lib) { return (int)FreeLibrary(lib); } //---------------------------------------------------------------------------- DynamicLoaderFunction DynamicLoader::GetSymbolAddress(LibHandle lib, const char* sym) { void *result; #ifdef UNICODE wchar_t wsym[MB_CUR_MAX]; mbstowcs(wsym, sym, MB_CUR_MAX); result = GetProcAddress(lib, wsym); #else result = (void*)GetProcAddress(lib, sym); #endif // Hack to cast pointer-to-data to pointer-to-function. return *reinterpret_cast<DynamicLoaderFunction*>(&result); } //---------------------------------------------------------------------------- const char* DynamicLoader::LibPrefix() { return ""; } //---------------------------------------------------------------------------- const char* DynamicLoader::LibExtension() { return ".dll"; } //---------------------------------------------------------------------------- const char* DynamicLoader::LastError() { LPVOID lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR) &lpMsgBuf, 0, NULL ); static char* str = 0; delete [] str; str = strcpy(new char[strlen((char*)lpMsgBuf)+1], (char*)lpMsgBuf); // Free the buffer. LocalFree( lpMsgBuf ); return str; } } // namespace KWSYS_NAMESPACE #endif //_WIN32 // --------------------------------------------------------------- // 4. Implementation for default UNIX machines. // if nothing has been defined then use this #ifndef DYNAMICLOADER_DEFINED #define DYNAMICLOADER_DEFINED 1 // Setup for most unix machines #include <dlfcn.h> namespace KWSYS_NAMESPACE { //---------------------------------------------------------------------------- LibHandle DynamicLoader::OpenLibrary(const char* libname ) { return dlopen(libname, RTLD_LAZY); } //---------------------------------------------------------------------------- int DynamicLoader::CloseLibrary(LibHandle lib) { if (lib) { // The function dlclose() returns 0 on success, and non-zero on error. return !(int)dlclose(lib); } // else return 0; } //---------------------------------------------------------------------------- DynamicLoaderFunction DynamicLoader::GetSymbolAddress(LibHandle lib, const char* sym) { void* result = dlsym(lib, sym); // Hack to cast pointer-to-data to pointer-to-function. return *reinterpret_cast<DynamicLoaderFunction*>(&result); } //---------------------------------------------------------------------------- const char* DynamicLoader::LibPrefix() { return "lib"; } //---------------------------------------------------------------------------- const char* DynamicLoader::LibExtension() { return ".so"; } //---------------------------------------------------------------------------- const char* DynamicLoader::LastError() { return dlerror(); } } // namespace KWSYS_NAMESPACE #endif <|endoftext|>
<commit_before>// Terminal.cpp -- source file /* * * Author: septimomend (Ivan Chapkailo) * * 30.06.2017 * */ #include "stdafx.h" #include "Terminal.h" Terminal::Terminal() // cstr { } void Terminal::emergencyDestruction(const char* str) { write(STDOUT_FILENO, "\x1b[2J", 4); // write clr code to file write(STDOUT_FILENO, "\x1b[H", 3); perror(str); exit(1); // exit with error } void Terminal::rowModeOff() { // the change will occur after all output written to STDIN_FILENO is transmitted, // and all input so far received but not read will be discarded before the change is made if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &configObj.baseTermiosObj) == -1) emergencyDestruction("tcsetattr"); } void Terminal::rowModeOn() { if (tcgetattr(STDIN_FILENO, &configObj.baseTermiosObj) == -1) emergencyDestruction("tcgetattr"); atexit(rowModeOff); struct termios raw = configObj.baseTermiosObj; // setting flags // raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON); raw.c_oflag &= ~(OPOST); // Post-process output raw.c_cflag |= (CS8); // Character size 8 bits raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG); raw.c_cc[VMIN] = 0; raw.c_cc[VTIME] = 1; } int Terminal::whatKey() // defines key pressing { // TODO } int Terminal::getCursorPosition(int *row, int *column) // returns cursor position { // TODO } int Terminal::getWindowSize(int *row, int *column) // returns size of window { // TODO } <commit_msg>fixed inheritance errors<commit_after>// Terminal.cpp -- source file /* * * Author: septimomend (Ivan Chapkailo) * * 30.06.2017 * */ #include "stdafx.h" #include "Terminal.h" Terminal::Terminal() // cstr { } void Terminal::emergencyDestruction(const char* str) { write(STDOUT_FILENO, "\x1b[2J", 4); // write clr code to file write(STDOUT_FILENO, "\x1b[H", 3); perror(str); exit(1); // exit with error } void Terminal::rowModeOff() { AllControllers all; ConfigurationController* configObj = all.getConfigObj(); struct termios* termObj = configObj->getTermios(); // the change will occur after all output written to STDIN_FILENO is transmitted, // and all input so far received but not read will be discarded before the change is made if (tcsetattr(STDIN_FILENO, TCSAFLUSH, termObj) == -1) emergencyDestruction("tcsetattr"); } void Terminal::rowModeOn() { AllControllers all; ConfigurationController* configObj = all.getConfigObj(); struct termios* termObj = configObj->getTermios(); if (tcgetattr(STDIN_FILENO, termObj) == -1) emergencyDestruction("tcgetattr"); atexit(rowModeOff); struct termios raw = *termObj; // setting flags // raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON); raw.c_oflag &= ~(OPOST); // Post-process output raw.c_cflag |= (CS8); // Character size 8 bits raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG); raw.c_cc[VMIN] = 0; raw.c_cc[VTIME] = 1; } int Terminal::whatKey() // defines key pressing { // TODO } int Terminal::getCursorPosition(int *row, int *column) // returns cursor position { // TODO } int Terminal::getWindowSize(int *row, int *column) // returns size of window { // TODO } <|endoftext|>
<commit_before><commit_msg>SIMD componentProduct<commit_after><|endoftext|>
<commit_before>/* * Copyright (C) 2015 Cloudius Systems, Ltd. */ #pragma once #include "exceptions/exceptions.hh" enum class compressor { none, lz4, snappy, deflate, }; class compression_parameters { public: static constexpr int32_t DEFAULT_CHUNK_LENGTH = 64 * 1024; static constexpr double DEFAULT_CRC_CHECK_CHANCE = 1.0; static constexpr auto SSTABLE_COMPRESSION = "sstable_compression"; static constexpr auto CHUNK_LENGTH_KB = "chunk_length_kb"; static constexpr auto CRC_CHECK_CHANCE = "crc_check_chance"; private: compressor _compressor = compressor::none; int _chunk_length = DEFAULT_CHUNK_LENGTH; double _crc_check_chance = DEFAULT_CRC_CHECK_CHANCE; public: compression_parameters() = default; compression_parameters(compressor c) : _compressor(c) { } compression_parameters(const std::map<sstring, sstring>& options) { validate_options(options); const auto& compressor_class = options.at(SSTABLE_COMPRESSION); if (compressor_class == "LZ4Compressor") { _compressor = compressor::lz4; } else if (compressor_class == "SnappyCompressor") { _compressor = compressor::snappy; } else if (compressor_class == "DeflateCompressor") { _compressor = compressor::deflate; } else { throw exceptions::configuration_exception(sstring("Unsupported compression class '") + compressor_class + "'."); } auto chunk_length = options.find(CHUNK_LENGTH_KB); if (chunk_length != options.end()) { try { _chunk_length = std::stoi(chunk_length->second) * 1024; } catch (const std::exception& e) { throw exceptions::syntax_exception(sstring("Invalid integer value ") + chunk_length->second + " for " + CHUNK_LENGTH_KB); } } auto crc_chance = options.find(CRC_CHECK_CHANCE); if (crc_chance != options.end()) { try { _crc_check_chance = std::stod(crc_chance->second); } catch (const std::exception& e) { throw exceptions::syntax_exception(sstring("Invalid double value ") + crc_chance->second + "for " + CRC_CHECK_CHANCE); } } } compressor get_compressor() const { return _compressor; } int32_t chunk_length() const { return _chunk_length; } double crc_check_chance() const { return _crc_check_chance; } void validate() { if (_chunk_length <= 0) { throw exceptions::configuration_exception(sstring("Invalid negative or null ") + CHUNK_LENGTH_KB); } // _chunk_length must be a power of two if (_chunk_length & (_chunk_length - 1)) { throw exceptions::configuration_exception(sstring(CHUNK_LENGTH_KB) + " must be a power of 2."); } if (_crc_check_chance < 0.0 || _crc_check_chance > 1.0) { throw exceptions::configuration_exception(sstring(CRC_CHECK_CHANCE) + " must be between 0.0 and 1.0."); } } private: void validate_options(const std::map<sstring, sstring>& options) { // currently, there are no options specific to a particular compressor static std::set<sstring> keywords({ sstring(SSTABLE_COMPRESSION), sstring(CHUNK_LENGTH_KB), sstring(CRC_CHECK_CHANCE), }); for (auto&& opt : options) { if (!keywords.count(opt.first)) { throw exceptions::configuration_exception(sprint("Unknown compression option '%s'.", opt.first)); } } } }; <commit_msg>compress: accept both qualified and unqualified class names<commit_after>/* * Copyright (C) 2015 Cloudius Systems, Ltd. */ #pragma once #include "exceptions/exceptions.hh" enum class compressor { none, lz4, snappy, deflate, }; class compression_parameters { public: static constexpr int32_t DEFAULT_CHUNK_LENGTH = 64 * 1024; static constexpr double DEFAULT_CRC_CHECK_CHANCE = 1.0; static constexpr auto SSTABLE_COMPRESSION = "sstable_compression"; static constexpr auto CHUNK_LENGTH_KB = "chunk_length_kb"; static constexpr auto CRC_CHECK_CHANCE = "crc_check_chance"; private: compressor _compressor = compressor::none; int _chunk_length = DEFAULT_CHUNK_LENGTH; double _crc_check_chance = DEFAULT_CRC_CHECK_CHANCE; public: compression_parameters() = default; compression_parameters(compressor c) : _compressor(c) { } compression_parameters(const std::map<sstring, sstring>& options) { validate_options(options); const auto& compressor_class = options.at(SSTABLE_COMPRESSION); if (is_compressor_class(compressor_class, "LZ4Compressor")) { _compressor = compressor::lz4; } else if (is_compressor_class(compressor_class, "SnappyCompressor")) { _compressor = compressor::snappy; } else if (is_compressor_class(compressor_class, "DeflateCompressor")) { _compressor = compressor::deflate; } else { throw exceptions::configuration_exception(sstring("Unsupported compression class '") + compressor_class + "'."); } auto chunk_length = options.find(CHUNK_LENGTH_KB); if (chunk_length != options.end()) { try { _chunk_length = std::stoi(chunk_length->second) * 1024; } catch (const std::exception& e) { throw exceptions::syntax_exception(sstring("Invalid integer value ") + chunk_length->second + " for " + CHUNK_LENGTH_KB); } } auto crc_chance = options.find(CRC_CHECK_CHANCE); if (crc_chance != options.end()) { try { _crc_check_chance = std::stod(crc_chance->second); } catch (const std::exception& e) { throw exceptions::syntax_exception(sstring("Invalid double value ") + crc_chance->second + "for " + CRC_CHECK_CHANCE); } } } compressor get_compressor() const { return _compressor; } int32_t chunk_length() const { return _chunk_length; } double crc_check_chance() const { return _crc_check_chance; } void validate() { if (_chunk_length <= 0) { throw exceptions::configuration_exception(sstring("Invalid negative or null ") + CHUNK_LENGTH_KB); } // _chunk_length must be a power of two if (_chunk_length & (_chunk_length - 1)) { throw exceptions::configuration_exception(sstring(CHUNK_LENGTH_KB) + " must be a power of 2."); } if (_crc_check_chance < 0.0 || _crc_check_chance > 1.0) { throw exceptions::configuration_exception(sstring(CRC_CHECK_CHANCE) + " must be between 0.0 and 1.0."); } } private: void validate_options(const std::map<sstring, sstring>& options) { // currently, there are no options specific to a particular compressor static std::set<sstring> keywords({ sstring(SSTABLE_COMPRESSION), sstring(CHUNK_LENGTH_KB), sstring(CRC_CHECK_CHANCE), }); for (auto&& opt : options) { if (!keywords.count(opt.first)) { throw exceptions::configuration_exception(sprint("Unknown compression option '%s'.", opt.first)); } } } bool is_compressor_class(const sstring& value, const sstring& class_name) { static const sstring namespace_prefix = "org.apache.cassandra.io.compress."; return value == class_name || value == namespace_prefix + class_name; } }; <|endoftext|>
<commit_before>// Copyright (c) 2014 Vicente Romero Calero // // Distributed under the MIT software license, see the file LICENSE // // Author: Vicente Romero <vteromero@gmail.com> #include "compress.h" #include <algorithm> #include <cstdint> #include <cstdio> #include <cstdlib> #include <list> #include <unordered_set> #include <vector> #include "bpe.h" #include "endian.h" using namespace std; struct BytePairOccurs { uint8_t byte1; uint8_t byte2; int occurs; }; extern Config config; static void replaceBytes( uint8_t byte, uint8_t bytepair1, uint8_t bytepair2, list<uint8_t> &byte_block, vector<vector<int> > &byte_pairs, BytePairOccurs &best_byte_pair) { list<uint8_t>::iterator it1 = byte_block.begin(); list<uint8_t>::iterator it2 = next(it1); list<uint8_t>::iterator prev_it, next_it; best_byte_pair.occurs = 0; while(it2 != byte_block.end()) { if((*it1 == bytepair1) && (*it2 == bytepair2)) { // Update byte pairs prev_it = prev(it1); next_it = next(it2); --byte_pairs[bytepair1][bytepair2]; if(prev_it != byte_block.end()) { --byte_pairs[*prev_it][bytepair1]; int occurs = ++byte_pairs[*prev_it][byte]; if(occurs > best_byte_pair.occurs) { best_byte_pair.byte1 = *prev_it; best_byte_pair.byte2 = byte; best_byte_pair.occurs = occurs; } } if(next_it != byte_block.end()) { --byte_pairs[bytepair2][*next_it]; int occurs = ++byte_pairs[byte][*next_it]; if(occurs > best_byte_pair.occurs) { best_byte_pair.byte1 = byte; best_byte_pair.byte2 = *next_it; best_byte_pair.occurs = occurs; } } // Perform the replacement it1 = byte_block.erase(it1, next_it); byte_block.insert(it1, byte); it2 = next(it1); } else { ++it1; ++it2; } } } static void compressBlock( uint8_t *buffer, int len, list<uint8_t> &byte_block, vector<pair<uint8_t, uint16_t> > &dictionary) { unordered_set<uint8_t> unused_bytes; unordered_set<uint8_t>::iterator it_set; vector<vector<int> > byte_pairs(256, vector<int>(256, 0)); BytePairOccurs best_byte_pair; uint8_t byte; best_byte_pair.byte1 = 0; best_byte_pair.byte2 = 0; best_byte_pair.occurs = 0; for(int i=0; i<256; ++i) unused_bytes.emplace(i); for(int i=0; i<len; ++i) { byte_block.push_back(buffer[i]); it_set = unused_bytes.find(buffer[i]); if(it_set != unused_bytes.end()) unused_bytes.erase(it_set); if((i + 1) < len) { int occurs = ++byte_pairs[buffer[i]][buffer[i + 1]]; if(occurs > best_byte_pair.occurs) { best_byte_pair.byte1 = buffer[i]; best_byte_pair.byte2 = buffer[i + 1]; best_byte_pair.occurs = occurs; } } } while(!unused_bytes.empty()) { if(best_byte_pair.occurs < 4) break; it_set = unused_bytes.begin(); byte = *it_set; dictionary.push_back(make_pair(byte, (best_byte_pair.byte1 << 8) | best_byte_pair.byte2)); replaceBytes( byte, best_byte_pair.byte1, best_byte_pair.byte2, byte_block, byte_pairs, best_byte_pair); unused_bytes.erase(it_set); } } static int writeBlock( FILE *outfile, const list<uint8_t> &byte_block, const vector<pair<uint8_t, uint16_t> > &dictionary) { uint8_t dict_size = dictionary.size(); uint16_t data_size = byte_block.size(); uint8_t buffer[data_size]; int block_size = 3 + 3 * dict_size + data_size; fwrite(&dict_size, 1, 1, outfile); for(int i=dict_size-1; i>=0; --i) { fwrite(&(dictionary[i].first), 1, 1, outfile); fwrite16(dictionary[i].second, outfile); } fwrite16(data_size, outfile); copy(byte_block.begin(), byte_block.end(), buffer); fwrite(buffer, 1, data_size, outfile); return block_size; } void compress() { int num_blocks = 0; uint8_t buffer[config.block_size]; size_t read_size; long long total_size=0, total_compressed_size=0; FILE *infile = fopen(config.infile, "rb"); if(infile == NULL) { perror(config.infile); exit(1); } FILE *outfile = NULL; if(config.stdout_opt) { outfile = stdout; } else { outfile = fopen(config.outfile, "wb"); if(outfile == NULL) { perror(config.outfile); exit(1); } } do { read_size = fread(buffer, sizeof(uint8_t), config.block_size, infile); total_size += read_size; list<uint8_t> byte_block; vector<pair<uint8_t, uint16_t> > dictionary; compressBlock(buffer, read_size, byte_block, dictionary); total_compressed_size += writeBlock(outfile, byte_block, dictionary); num_blocks++; } while(!feof(infile)); if(config.verbose_opt) { double reduction = (total_size - total_compressed_size) / (double)total_size; fprintf(stderr, "Reduction: %.2f%%\n", reduction * 100.0); } fclose(infile); if(!config.stdout_opt) { fclose(outfile); remove(config.infile); } } <commit_msg>deleted unused variable<commit_after>// Copyright (c) 2014 Vicente Romero Calero // // Distributed under the MIT software license, see the file LICENSE // // Author: Vicente Romero <vteromero@gmail.com> #include "compress.h" #include <algorithm> #include <cstdint> #include <cstdio> #include <cstdlib> #include <list> #include <unordered_set> #include <vector> #include "bpe.h" #include "endian.h" using namespace std; struct BytePairOccurs { uint8_t byte1; uint8_t byte2; int occurs; }; extern Config config; static void replaceBytes( uint8_t byte, uint8_t bytepair1, uint8_t bytepair2, list<uint8_t> &byte_block, vector<vector<int> > &byte_pairs, BytePairOccurs &best_byte_pair) { list<uint8_t>::iterator it1 = byte_block.begin(); list<uint8_t>::iterator it2 = next(it1); list<uint8_t>::iterator prev_it, next_it; best_byte_pair.occurs = 0; while(it2 != byte_block.end()) { if((*it1 == bytepair1) && (*it2 == bytepair2)) { // Update byte pairs prev_it = prev(it1); next_it = next(it2); --byte_pairs[bytepair1][bytepair2]; if(prev_it != byte_block.end()) { --byte_pairs[*prev_it][bytepair1]; int occurs = ++byte_pairs[*prev_it][byte]; if(occurs > best_byte_pair.occurs) { best_byte_pair.byte1 = *prev_it; best_byte_pair.byte2 = byte; best_byte_pair.occurs = occurs; } } if(next_it != byte_block.end()) { --byte_pairs[bytepair2][*next_it]; int occurs = ++byte_pairs[byte][*next_it]; if(occurs > best_byte_pair.occurs) { best_byte_pair.byte1 = byte; best_byte_pair.byte2 = *next_it; best_byte_pair.occurs = occurs; } } // Perform the replacement it1 = byte_block.erase(it1, next_it); byte_block.insert(it1, byte); it2 = next(it1); } else { ++it1; ++it2; } } } static void compressBlock( uint8_t *buffer, int len, list<uint8_t> &byte_block, vector<pair<uint8_t, uint16_t> > &dictionary) { unordered_set<uint8_t> unused_bytes; unordered_set<uint8_t>::iterator it_set; vector<vector<int> > byte_pairs(256, vector<int>(256, 0)); BytePairOccurs best_byte_pair; uint8_t byte; best_byte_pair.byte1 = 0; best_byte_pair.byte2 = 0; best_byte_pair.occurs = 0; for(int i=0; i<256; ++i) unused_bytes.emplace(i); for(int i=0; i<len; ++i) { byte_block.push_back(buffer[i]); it_set = unused_bytes.find(buffer[i]); if(it_set != unused_bytes.end()) unused_bytes.erase(it_set); if((i + 1) < len) { int occurs = ++byte_pairs[buffer[i]][buffer[i + 1]]; if(occurs > best_byte_pair.occurs) { best_byte_pair.byte1 = buffer[i]; best_byte_pair.byte2 = buffer[i + 1]; best_byte_pair.occurs = occurs; } } } while(!unused_bytes.empty()) { if(best_byte_pair.occurs < 4) break; it_set = unused_bytes.begin(); byte = *it_set; dictionary.push_back(make_pair(byte, (best_byte_pair.byte1 << 8) | best_byte_pair.byte2)); replaceBytes( byte, best_byte_pair.byte1, best_byte_pair.byte2, byte_block, byte_pairs, best_byte_pair); unused_bytes.erase(it_set); } } static int writeBlock( FILE *outfile, const list<uint8_t> &byte_block, const vector<pair<uint8_t, uint16_t> > &dictionary) { uint8_t dict_size = dictionary.size(); uint16_t data_size = byte_block.size(); uint8_t buffer[data_size]; int block_size = 3 + 3 * dict_size + data_size; fwrite(&dict_size, 1, 1, outfile); for(int i=dict_size-1; i>=0; --i) { fwrite(&(dictionary[i].first), 1, 1, outfile); fwrite16(dictionary[i].second, outfile); } fwrite16(data_size, outfile); copy(byte_block.begin(), byte_block.end(), buffer); fwrite(buffer, 1, data_size, outfile); return block_size; } void compress() { uint8_t buffer[config.block_size]; size_t read_size; long long total_size=0, total_compressed_size=0; FILE *infile = fopen(config.infile, "rb"); if(infile == NULL) { perror(config.infile); exit(1); } FILE *outfile = NULL; if(config.stdout_opt) { outfile = stdout; } else { outfile = fopen(config.outfile, "wb"); if(outfile == NULL) { perror(config.outfile); exit(1); } } do { read_size = fread(buffer, sizeof(uint8_t), config.block_size, infile); total_size += read_size; list<uint8_t> byte_block; vector<pair<uint8_t, uint16_t> > dictionary; compressBlock(buffer, read_size, byte_block, dictionary); total_compressed_size += writeBlock(outfile, byte_block, dictionary); } while(!feof(infile)); if(config.verbose_opt) { double reduction = (total_size - total_compressed_size) / (double)total_size; fprintf(stderr, "Reduction: %.2f%%\n", reduction * 100.0); } fclose(infile); if(!config.stdout_opt) { fclose(outfile); remove(config.infile); } } <|endoftext|>
<commit_before>/* This file is part of Mapnik (c++ mapping toolkit) * Copyright (C) 2005 Artem Pavlenko * * Mapnik 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 any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ //$Id$ #ifndef GEOMETRY_HH #define GEOMETRY_HH #include "vertex_vector.hh" #include "vertex_transform.hh" #include "ctrans.hh" #include "ptr.hh" namespace mapnik { enum { Point = 1, LineString = 2, Polygon = 3, }; template <typename T,template <typename> class Container=vertex_vector> class geometry { public: typedef T vertex_type; typedef typename vertex_type::type value_type; typedef Container<vertex_type> container_type; private: int srid_; mutable unsigned itr_; protected: container_type cont_; public: geometry (int srid=-1) : srid_(srid), itr_(0), cont_() {} virtual int type() const=0; virtual bool hit_test(value_type x,value_type y) const=0; int srid() const { return srid_; } void move_to(value_type x,value_type y) { cont_.push_back(x,y,SEG_MOVETO); } void line_to(value_type x,value_type y) { cont_.push_back(x,y,SEG_LINETO); } //unsigned vertex(double* x, double* y) // { // return cont_.get_vertex(itr_++,x,y); // } //void rewind(unsigned ) // { // itr_=0; // } template <typename Transform> class path_iterator { typedef vertex<typename Transform::return_type,2> vertex_type; const container_type* cont_; unsigned pos_; unsigned cmd_; vertex_type vertex_; private: void advance () { if (pos_ < cont_->size()) { value_type x,y; vertex_.cmd=cont_->get_vertex(pos_,&x,&y); vertex_.x=Transform::apply(x); vertex_.y=Transform::apply(y); } else { vertex_.cmd=SEG_END; vertex_.x=0; vertex_.y=0; } ++pos_; } public: path_iterator() : cont_(0), pos_(0), cmd_(SEG_END), vertex_(0,0,cmd_) {} explicit path_iterator(const container_type& cont) : cont_(&cont), pos_(0), cmd_(SEG_MOVETO), vertex_(0,0,cmd_) { advance(); } path_iterator& operator++() { advance(); return *this; } const vertex_type& operator*() const { return vertex_; } const vertex_type* operator->() const { return &vertex_; } bool operator !=(const path_iterator& itr) { return vertex_.cmd !=itr.vertex_.cmd; } }; template <typename Transform> path_iterator<Transform> begin() const { return path_iterator<Transform>(cont_); } template <typename Transform> path_iterator<Transform> end() const { return path_iterator<Transform>(); } void transform(const mapnik::CoordTransform& t) { for (unsigned pos=0;pos<cont_.size();++pos) { cont_.transform_at(pos,t); } } unsigned num_points() const { return cont_.size(); } virtual ~geometry() {} private: geometry(const geometry&); geometry& operator=(const geometry&); }; template <typename T, template <typename> class Container=vertex_vector> class point : public geometry<T,Container> { typedef typename geometry<T,Container>::value_type value_type; using geometry<T,Container>::cont_; public: point(int srid) : geometry<T,Container>(srid) {} int type() const { return Point; } bool hit_test(value_type x,value_type y) const { return point_on_points(x,y,*this); } }; template <typename T, template <typename> class Container=vertex_vector> class polygon : public geometry<T,Container> { typedef geometry<T,Container> geometry_base; typedef typename geometry_base::value_type value_type; typedef typename geometry_base::template path_iterator<NO_SHIFT> path_iterator; public: polygon(int srid) : geometry_base(srid) {} int type() const { return Polygon; } bool hit_test(value_type x,value_type y) const { path_iterator start = geometry_base::template begin<NO_SHIFT>(); path_iterator end = geometry_base::template end<NO_SHIFT>(); return point_inside_path(start,end,x,y); } }; template <typename T, template <typename> class Container=vertex_vector> class line_string : public geometry<T,Container> { typedef typename geometry<T,Container>::value_type value_type; public: line_string(int srid) : geometry<T,Container>(srid) {} int type() const { return LineString; } bool hit_test(value_type x,value_type y) const { return point_on_path(x,y,*this); } }; typedef point<vertex2d> point_impl; typedef line_string<vertex2d> line_string_impl; typedef polygon<vertex2d> polygon_impl; typedef geometry<vertex2d> geometry_type; typedef ref_ptr<geometry_type> geometry_ptr; } #endif //GEOMETRY_HH <commit_msg>moved typedef typename geometry_base::template path_iterator<NO_SHIFT> path_iterator<commit_after>/* This file is part of Mapnik (c++ mapping toolkit) * Copyright (C) 2005 Artem Pavlenko * * Mapnik 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 any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ //$Id$ #ifndef GEOMETRY_HH #define GEOMETRY_HH #include "vertex_vector.hh" #include "vertex_transform.hh" #include "ctrans.hh" #include "ptr.hh" namespace mapnik { enum { Point = 1, LineString = 2, Polygon = 3, }; template <typename T,template <typename> class Container=vertex_vector> class geometry { public: typedef T vertex_type; typedef typename vertex_type::type value_type; typedef Container<vertex_type> container_type; private: int srid_; mutable unsigned itr_; protected: container_type cont_; public: geometry (int srid=-1) : srid_(srid), itr_(0), cont_() {} virtual int type() const=0; virtual bool hit_test(value_type x,value_type y) const=0; int srid() const { return srid_; } void move_to(value_type x,value_type y) { cont_.push_back(x,y,SEG_MOVETO); } void line_to(value_type x,value_type y) { cont_.push_back(x,y,SEG_LINETO); } //unsigned vertex(double* x, double* y) // { // return cont_.get_vertex(itr_++,x,y); // } //void rewind(unsigned ) // { // itr_=0; // } template <typename Transform> class path_iterator { typedef vertex<typename Transform::return_type,2> vertex_type; const container_type* cont_; unsigned pos_; unsigned cmd_; vertex_type vertex_; private: void advance () { if (pos_ < cont_->size()) { value_type x,y; vertex_.cmd=cont_->get_vertex(pos_,&x,&y); vertex_.x=Transform::apply(x); vertex_.y=Transform::apply(y); } else { vertex_.cmd=SEG_END; vertex_.x=0; vertex_.y=0; } ++pos_; } public: path_iterator() : cont_(0), pos_(0), cmd_(SEG_END), vertex_(0,0,cmd_) {} explicit path_iterator(const container_type& cont) : cont_(&cont), pos_(0), cmd_(SEG_MOVETO), vertex_(0,0,cmd_) { advance(); } path_iterator& operator++() { advance(); return *this; } const vertex_type& operator*() const { return vertex_; } const vertex_type* operator->() const { return &vertex_; } bool operator !=(const path_iterator& itr) { return vertex_.cmd !=itr.vertex_.cmd; } }; template <typename Transform> path_iterator<Transform> begin() const { return path_iterator<Transform>(cont_); } template <typename Transform> path_iterator<Transform> end() const { return path_iterator<Transform>(); } void transform(const mapnik::CoordTransform& t) { for (unsigned pos=0;pos<cont_.size();++pos) { cont_.transform_at(pos,t); } } unsigned num_points() const { return cont_.size(); } virtual ~geometry() {} private: geometry(const geometry&); geometry& operator=(const geometry&); }; template <typename T, template <typename> class Container=vertex_vector> class point : public geometry<T,Container> { typedef typename geometry<T,Container>::value_type value_type; using geometry<T,Container>::cont_; public: point(int srid) : geometry<T,Container>(srid) {} int type() const { return Point; } bool hit_test(value_type x,value_type y) const { return point_on_points(x,y,*this); } }; template <typename T, template <typename> class Container=vertex_vector> class polygon : public geometry<T,Container> { typedef geometry<T,Container> geometry_base; typedef typename geometry_base::value_type value_type; public: polygon(int srid) : geometry_base(srid) {} int type() const { return Polygon; } bool hit_test(value_type x,value_type y) const { typedef typename geometry_base::template path_iterator<NO_SHIFT> path_iterator; path_iterator start = geometry_base::template begin<NO_SHIFT>(); path_iterator end = geometry_base::template end<NO_SHIFT>(); return point_inside_path(start,end,x,y); } }; template <typename T, template <typename> class Container=vertex_vector> class line_string : public geometry<T,Container> { typedef typename geometry<T,Container>::value_type value_type; public: line_string(int srid) : geometry<T,Container>(srid) {} int type() const { return LineString; } bool hit_test(value_type x,value_type y) const { return point_on_path(x,y,*this); } }; typedef point<vertex2d> point_impl; typedef line_string<vertex2d> line_string_impl; typedef polygon<vertex2d> polygon_impl; typedef geometry<vertex2d> geometry_type; typedef ref_ptr<geometry_type> geometry_ptr; } #endif //GEOMETRY_HH <|endoftext|>
<commit_before>#include <fstream> #include <iostream> #include <glob.h> // TODO #include <pdal/StageFactory.hpp> #include <entwine/drivers/arbiter.hpp> #include <entwine/types/bbox.hpp> #include <entwine/types/schema.hpp> #include <entwine/tree/clipper.hpp> #include <entwine/tree/reader.hpp> #include "read-queries/entwine.hpp" #include "read-queries/unindexed.hpp" #include "types/paths.hpp" #include "util/buffer-pool.hpp" #include "session.hpp" namespace { // TODO Put this somewhere else - platform dependent code. std::vector<std::string> resolve( const std::vector<std::string>& dirs, const std::string& name) { glob_t buffer; for (std::size_t i(0); i < dirs.size(); ++i) { auto flags(GLOB_NOSORT | GLOB_TILDE); if (i) flags |= GLOB_APPEND; glob((dirs[i] + "/" + name + "*").c_str(), flags, 0, &buffer); } std::vector<std::string> results; for (std::size_t i(0); i < buffer.gl_pathc; ++i) { results.push_back(buffer.gl_pathv[i]); } globfree(&buffer); return results; } } Session::Session( pdal::StageFactory& stageFactory, std::mutex& factoryMutex) : m_stageFactory(stageFactory) , m_factoryMutex(factoryMutex) , m_initOnce() , m_source() , m_entwine() , m_name() , m_paths() , m_arbiter() { } Session::~Session() { } bool Session::initialize( const std::string& name, const Paths& paths, std::shared_ptr<entwine::Arbiter> arbiter) { m_initOnce.ensure([this, &name, &paths, arbiter]() { std::cout << "Discovering " << name << std::endl; m_name = name; m_paths.reset(new Paths(paths)); m_arbiter = arbiter; resolveSource(); resolveIndex(); std::cout << "Source for " << name << ": " << (sourced() ? "FOUND" : "NOT found") << std::endl; std::cout << "Index for " << name << ": " << (indexed() ? "FOUND" : "NOT found") << std::endl; }); return sourced() || indexed(); } std::size_t Session::getNumPoints() { if (indexed()) return m_entwine->numPoints(); else return m_source->numPoints(); } std::string Session::getStats() { // TODO return "{ }"; } std::string Session::getSrs() { return ""; } entwine::BBox Session::getBounds() { if (resolveIndex()) { return m_entwine->bbox(); } else { throw std::runtime_error("No index found for " + m_name); } } std::shared_ptr<ReadQuery> Session::query( const entwine::Schema& schema, const bool compress) { if (resolveSource()) { return std::shared_ptr<ReadQuery>( new UnindexedReadQuery( schema, compress, *m_source)); } else { return std::shared_ptr<ReadQuery>(); } } std::shared_ptr<ReadQuery> Session::query( const entwine::Schema& schema, bool compress, const entwine::BBox& bbox, std::size_t depthBegin, std::size_t depthEnd) { if (resolveIndex()) { std::vector<std::size_t> results( m_entwine->query( bbox.exists() ? bbox : m_entwine->bbox(), depthBegin, depthEnd)); return std::shared_ptr<ReadQuery>( new EntwineReadQuery( schema, compress, false, *m_entwine, results)); } else { return std::shared_ptr<ReadQuery>(); } } std::shared_ptr<ReadQuery> Session::query( const entwine::Schema& schema, bool compress, const entwine::BBox& bbox, std::size_t rasterize, RasterMeta& rasterMeta) { throw std::runtime_error("TODO - Session::query (rastered)"); return std::shared_ptr<ReadQuery>(); } const entwine::Schema& Session::schema() { if (indexed()) return m_entwine->schema(); else return m_source->schema(); } bool Session::sourced() { std::lock_guard<std::mutex> lock(m_sourceMutex); return m_source.get() != 0; } bool Session::indexed() { std::lock_guard<std::mutex> lock(m_indexMutex); return m_entwine.get() != 0; } bool Session::resolveSource() { // TODO For now only works for local paths. Support any Source the Arbiter // contains. std::lock_guard<std::mutex> lock(m_sourceMutex); if (!m_source) { const auto sources(resolve(m_paths->inputs, m_name)); if (sources.size() > 1) { std::cout << "Found competing sources for " << m_name << std::endl; } if (sources.size()) { std::size_t i(0); while (!m_source && i < sources.size()) { const std::string path(sources[i++]); std::unique_lock<std::mutex> lock(m_factoryMutex); const std::string driver( m_stageFactory.inferReaderDriver(path)); lock.unlock(); if (driver.size()) { try { m_source.reset( new SourceManager( m_stageFactory, m_factoryMutex, path, driver)); } catch (...) { std::cout << "Bad source: " << path << std::endl; m_source.reset(0); } } } } } return m_source.get() != 0; } bool Session::resolveIndex() { std::lock_guard<std::mutex> lock(m_indexMutex); if (!m_entwine) { std::vector<std::string> searchPaths(m_paths->inputs); searchPaths.push_back(m_paths->output); searchPaths.push_back("s3://"); for (std::string path : searchPaths) { try { if (path.size() && path.back() != '/') path.push_back('/'); entwine::Source source(m_arbiter->getSource(path + m_name)); // TODO Specify via config. m_entwine.reset(new entwine::Reader(source, 128, 128)); } catch (...) { m_entwine.reset(0); } if (m_entwine) break; } } return m_entwine.get() != 0; } <commit_msg>Add failure logging to indexed Reader creation loop.<commit_after>#include <fstream> #include <iostream> #include <glob.h> // TODO #include <pdal/StageFactory.hpp> #include <entwine/drivers/arbiter.hpp> #include <entwine/types/bbox.hpp> #include <entwine/types/schema.hpp> #include <entwine/tree/clipper.hpp> #include <entwine/tree/reader.hpp> #include "read-queries/entwine.hpp" #include "read-queries/unindexed.hpp" #include "types/paths.hpp" #include "util/buffer-pool.hpp" #include "session.hpp" namespace { // TODO Put this somewhere else - platform dependent code. std::vector<std::string> resolve( const std::vector<std::string>& dirs, const std::string& name) { glob_t buffer; for (std::size_t i(0); i < dirs.size(); ++i) { auto flags(GLOB_NOSORT | GLOB_TILDE); if (i) flags |= GLOB_APPEND; glob((dirs[i] + "/" + name + "*").c_str(), flags, 0, &buffer); } std::vector<std::string> results; for (std::size_t i(0); i < buffer.gl_pathc; ++i) { results.push_back(buffer.gl_pathv[i]); } globfree(&buffer); return results; } } Session::Session( pdal::StageFactory& stageFactory, std::mutex& factoryMutex) : m_stageFactory(stageFactory) , m_factoryMutex(factoryMutex) , m_initOnce() , m_source() , m_entwine() , m_name() , m_paths() , m_arbiter() { } Session::~Session() { } bool Session::initialize( const std::string& name, const Paths& paths, std::shared_ptr<entwine::Arbiter> arbiter) { m_initOnce.ensure([this, &name, &paths, arbiter]() { std::cout << "Discovering " << name << std::endl; m_name = name; m_paths.reset(new Paths(paths)); m_arbiter = arbiter; resolveSource(); resolveIndex(); std::cout << "Source for " << name << ": " << (sourced() ? "FOUND" : "NOT found") << std::endl; std::cout << "Index for " << name << ": " << (indexed() ? "FOUND" : "NOT found") << std::endl; }); return sourced() || indexed(); } std::size_t Session::getNumPoints() { if (indexed()) return m_entwine->numPoints(); else return m_source->numPoints(); } std::string Session::getStats() { // TODO return "{ }"; } std::string Session::getSrs() { return ""; } entwine::BBox Session::getBounds() { if (resolveIndex()) { return m_entwine->bbox(); } else { throw std::runtime_error("No index found for " + m_name); } } std::shared_ptr<ReadQuery> Session::query( const entwine::Schema& schema, const bool compress) { if (resolveSource()) { return std::shared_ptr<ReadQuery>( new UnindexedReadQuery( schema, compress, *m_source)); } else { return std::shared_ptr<ReadQuery>(); } } std::shared_ptr<ReadQuery> Session::query( const entwine::Schema& schema, bool compress, const entwine::BBox& bbox, std::size_t depthBegin, std::size_t depthEnd) { if (resolveIndex()) { std::vector<std::size_t> results( m_entwine->query( bbox.exists() ? bbox : m_entwine->bbox(), depthBegin, depthEnd)); return std::shared_ptr<ReadQuery>( new EntwineReadQuery( schema, compress, false, *m_entwine, results)); } else { return std::shared_ptr<ReadQuery>(); } } std::shared_ptr<ReadQuery> Session::query( const entwine::Schema& schema, bool compress, const entwine::BBox& bbox, std::size_t rasterize, RasterMeta& rasterMeta) { throw std::runtime_error("TODO - Session::query (rastered)"); return std::shared_ptr<ReadQuery>(); } const entwine::Schema& Session::schema() { if (indexed()) return m_entwine->schema(); else return m_source->schema(); } bool Session::sourced() { std::lock_guard<std::mutex> lock(m_sourceMutex); return m_source.get() != 0; } bool Session::indexed() { std::lock_guard<std::mutex> lock(m_indexMutex); return m_entwine.get() != 0; } bool Session::resolveSource() { // TODO For now only works for local paths. Support any Source the Arbiter // contains. std::lock_guard<std::mutex> lock(m_sourceMutex); if (!m_source) { const auto sources(resolve(m_paths->inputs, m_name)); if (sources.size() > 1) { std::cout << "Found competing sources for " << m_name << std::endl; } if (sources.size()) { std::size_t i(0); while (!m_source && i < sources.size()) { const std::string path(sources[i++]); std::unique_lock<std::mutex> lock(m_factoryMutex); const std::string driver( m_stageFactory.inferReaderDriver(path)); lock.unlock(); if (driver.size()) { try { m_source.reset( new SourceManager( m_stageFactory, m_factoryMutex, path, driver)); } catch (...) { std::cout << "Bad source: " << path << std::endl; m_source.reset(0); } } } } } return m_source.get() != 0; } bool Session::resolveIndex() { std::lock_guard<std::mutex> lock(m_indexMutex); if (!m_entwine) { std::vector<std::string> searchPaths(m_paths->inputs); searchPaths.push_back(m_paths->output); searchPaths.push_back("s3://"); for (std::string path : searchPaths) { try { if (path.size() && path.back() != '/') path.push_back('/'); entwine::Source source(m_arbiter->getSource(path + m_name)); // TODO Specify via config. m_entwine.reset(new entwine::Reader(source, 128, 128)); } catch (std::runtime_error& e) { std::cout << "At " << path << ": " << e.what() << "\n" << std::endl; } catch (...) { m_entwine.reset(0); } if (m_entwine) break; } } return m_entwine.get() != 0; } <|endoftext|>
<commit_before>#include "BLITSaw_vst3.h" #include "BLITSaw_vst3_guids.h" #include "pluginterfaces/base/ibstream.h" #include "pluginterfaces/vst/ivstparameterchanges.h" #include "pluginterfaces/vst/ivstevents.h" #include <algorithm> namespace Steinberg { namespace Vst { //------------------------------------------------------------------------- // BLITSaw_vst3 Implementation //------------------------------------------------------------------------- BLITSaw_vst3::BLITSaw_vst3() { setControllerClass(AGainControllerUID); } //------------------------------------------------------------------------- FUnknown* BLITSaw_vst3::createInstance(void* context) { return (IAudioProcessor*)new BLITSaw_vst3(); } //------------------------------------------------------------------------- tresult PLUGIN_API BLITSaw_vst3::initialize(FUnknown* context) { /*親クラス初期化処理*/ tresult result = AudioEffect::initialize(context); if(result != kResultOk) { return result; } /*バスの設定*/ addAudioOutput(STR16("Stereo Out"), SpeakerArr::kStereo); addEventInput (STR16 ("Event Input"), 1); return kResultOk; } //------------------------------------------------------------------------- tresult PLUGIN_API BLITSaw_vst3::setBusArrangements( SpeakerArrangement* inputs, int32 numIns, SpeakerArrangement* outputs, int32 numOuts ){ if (numIns == 0 && numOuts == 1 && outputs[0] == SpeakerArr::kStereo) { return AudioEffect::setBusArrangements (inputs, numIns, outputs, numOuts); } return kResultFalse; } tresult PLUGIN_API BLITSaw_vst3::setProcessing (TBool state) { // state 起動1 終了0 if( state == 1 ) { for(auto note = _notes.begin(); note != _notes.end(); ++note) { note->setSampleRate( processSetup.sampleRate ); } _filter.setSampleRate( processSetup.sampleRate ); } return kResultOk; } //------------------------------------------------------------------------- tresult PLUGIN_API BLITSaw_vst3::process(ProcessData& data) { // update parameters if( data.inputParameterChanges ) { int32 numParamsChanged = data.inputParameterChanges->getParameterCount(); for( int32 ii = 0; ii < numParamsChanged; ii++ ) { IParamValueQueue* paramQueue = data.inputParameterChanges->getParameterData(ii); if( paramQueue ) { int32 offsetSamples; double value; // 末尾の値を取得 if(paramQueue->getPoint(paramQueue->getPointCount() - 1, offsetSamples, value) == kResultTrue) { ParamID id = paramQueue->getParameterId(); if( id == feedback ) { // -> [0.99, 1.0] double feedback = 0.99 + 0.01 * value; blit.setFeedback(feedback); } else if( id == coarse ) { double coarse_pitch = static_cast<int>( 48 * value + 0.5 ) - 24; for(auto note = _notes.begin(); note != _notes.end(); ++note) { note->setCorasePitch( coarse_pitch ); } } else if( id == fine ) { double finepitch = static_cast<int>( 200 * value + 0.5 ) - 100; for(auto note = _notes.begin(); note != _notes.end(); ++note) { note->setFinePitch( finepitch ); } } else if( id == attack ) { double attack_time = value * 0.2; // [0, 0.2] blit.setAttackTime( attack_time, processSetup.sampleRate ); } else if( id == release ) { double release_time = value * 0.2; // [0, 0.2] blit.setReleaseTime( release_time, processSetup.sampleRate ); } else if( id == cutoff ) { double cutoff_freq = 200.0 * pow(20.0, (double)value); // [200, 4000] _filter.setCutoff( cutoff_freq ); } else if( id == resonance ) { double q = 0.70710678118654757274 * (1.0 - value) + 20.0*value; _filter.setResonance( q ); } else if( id == high ) { _filter.setHigh( value ); } else if( id == band ) { _filter.setBand( value ); } else if( id == low ) { _filter.setLow( value ); } } } } } // process events if( data.inputEvents ) { int nEventCount = data.inputEvents->getEventCount(); for( int ii = 0; ii < nEventCount; ii++ ) { Event e; tresult result = data.inputEvents->getEvent(ii, e); if( result != kResultOk )continue; if( e.type == Event::kNoteOnEvent ) { int16 note_no = e.noteOff.pitch; auto target_note = std::find_if( _notes.begin(), _notes.end(), [note_no](const bandlimited_sawtooth_oscillator_note_vst3& n){return n.id() == note_no;}); if( target_note != _notes.end() ) { // ノートOFF target_note->trigger(e.noteOn); } else { // 利用可能なノートを検索する auto available_note = std::find_if( _notes.begin(), _notes.end(), [](const bandlimited_sawtooth_oscillator_note_vst3& n){return n.adsr == bandlimited_sawtooth_oscillator_note::Silent;}); if( available_note != _notes.end() ) { // ノートON available_note->trigger( e.noteOn ); } } } else if( e.type == Event::kNoteOffEvent ) { //int32 note_id = e.noteOff.noteId; //auto target_note = std::find_if( // _notes.begin(), // _notes.end(), // [note_id](const bandlimited_sawtooth_oscillator_note_vst3& n){return n.id() == note_id;}); int16 note_no = e.noteOff.pitch; auto target_note = std::find_if( _notes.begin(), _notes.end(), [note_no](const bandlimited_sawtooth_oscillator_note_vst3& n){return n.id() == note_no;}); if( target_note != _notes.end() ) { // ノートOFF target_note->release(); } } else if( e.type == Event::kDataEvent ) { unsigned char status = e.data.bytes[0] & 0xf0; // ignoring channel if( status == 0xE0 ) { unsigned char data1 = e.data.bytes[1] & 0x7f; unsigned char data2 = e.data.bytes[2] & 0x7f; double pitch_bend = (( data1 + data2*128 ) - 8192 ) / 8192.0; for(auto note = _notes.begin(); note != _notes.end(); ++note) { note->setPitchBend( pitch_bend ); } } } } } bool bAllSilent= std::all_of( _notes.begin(), _notes.end(), [](const bandlimited_sawtooth_oscillator_note_vst3& n){return n.adsr == bandlimited_sawtooth_oscillator_note::Silent;}); if( bAllSilent ) { return kResultOk; } _filter.updateFilter(); /*--------*/ /*音声処理*/ /*--------*/ if (data.numInputs == 0 && data.numOutputs == 1 ) { for(auto note = _notes.begin(); note != _notes.end(); ++note) { // ピッチを更新 note->updateFrequency(); } if( data.outputs[0].numChannels == 2 ) { //float** in = data.inputs[0].channelBuffers32; float** out = data.outputs[0].channelBuffers32; const int32 sampleFrames = data.numSamples; for( int ii = 0; ii < sampleFrames; ii++ ) { double value = 0.0; for(auto note = _notes.begin(); note != _notes.end(); ++note) { if( note->adsr == bandlimited_sawtooth_oscillator_note::Silent )continue; // ノート毎の音を足し合わせる value += note->saw * note->envelope * note->velocity(); // オシレーター更新 blit.updateOcsillater( *note ); // エンベロープ更新 blit.updateEnvelope( *note ); } // // フィルタを掛けたければ掛ける // double filterd_value = _filter.process(value); // 出力バッファに設定する double pan = 0.0; out[0][ii] = static_cast<float>( filterd_value * (1.0 - pan) * 0.5 ); out[1][ii] = static_cast<float>( filterd_value * (1.0 + pan) * 0.5 ); } } } return kResultOk; } }} <commit_msg>コメント訂正<commit_after>#include "BLITSaw_vst3.h" #include "BLITSaw_vst3_guids.h" #include "pluginterfaces/base/ibstream.h" #include "pluginterfaces/vst/ivstparameterchanges.h" #include "pluginterfaces/vst/ivstevents.h" #include <algorithm> namespace Steinberg { namespace Vst { //------------------------------------------------------------------------- // BLITSaw_vst3 Implementation //------------------------------------------------------------------------- BLITSaw_vst3::BLITSaw_vst3() { setControllerClass(AGainControllerUID); } //------------------------------------------------------------------------- FUnknown* BLITSaw_vst3::createInstance(void* context) { return (IAudioProcessor*)new BLITSaw_vst3(); } //------------------------------------------------------------------------- tresult PLUGIN_API BLITSaw_vst3::initialize(FUnknown* context) { /*親クラス初期化処理*/ tresult result = AudioEffect::initialize(context); if(result != kResultOk) { return result; } /*バスの設定*/ addAudioOutput(STR16("Stereo Out"), SpeakerArr::kStereo); addEventInput (STR16 ("Event Input"), 1); return kResultOk; } //------------------------------------------------------------------------- tresult PLUGIN_API BLITSaw_vst3::setBusArrangements( SpeakerArrangement* inputs, int32 numIns, SpeakerArrangement* outputs, int32 numOuts ){ if (numIns == 0 && numOuts == 1 && outputs[0] == SpeakerArr::kStereo) { return AudioEffect::setBusArrangements (inputs, numIns, outputs, numOuts); } return kResultFalse; } tresult PLUGIN_API BLITSaw_vst3::setProcessing (TBool state) { // state 起動1 終了0 if( state == 1 ) { for(auto note = _notes.begin(); note != _notes.end(); ++note) { note->setSampleRate( processSetup.sampleRate ); } _filter.setSampleRate( processSetup.sampleRate ); } return kResultOk; } //------------------------------------------------------------------------- tresult PLUGIN_API BLITSaw_vst3::process(ProcessData& data) { // update parameters if( data.inputParameterChanges ) { int32 numParamsChanged = data.inputParameterChanges->getParameterCount(); for( int32 ii = 0; ii < numParamsChanged; ii++ ) { IParamValueQueue* paramQueue = data.inputParameterChanges->getParameterData(ii); if( paramQueue ) { int32 offsetSamples; double value; // 末尾の値を取得 if(paramQueue->getPoint(paramQueue->getPointCount() - 1, offsetSamples, value) == kResultTrue) { ParamID id = paramQueue->getParameterId(); if( id == feedback ) { // -> [0.99, 1.0] double feedback = 0.99 + 0.01 * value; blit.setFeedback(feedback); } else if( id == coarse ) { double coarse_pitch = static_cast<int>( 48 * value + 0.5 ) - 24; for(auto note = _notes.begin(); note != _notes.end(); ++note) { note->setCorasePitch( coarse_pitch ); } } else if( id == fine ) { double finepitch = static_cast<int>( 200 * value + 0.5 ) - 100; for(auto note = _notes.begin(); note != _notes.end(); ++note) { note->setFinePitch( finepitch ); } } else if( id == attack ) { double attack_time = value * 0.2; // [0, 0.2] blit.setAttackTime( attack_time, processSetup.sampleRate ); } else if( id == release ) { double release_time = value * 0.2; // [0, 0.2] blit.setReleaseTime( release_time, processSetup.sampleRate ); } else if( id == cutoff ) { double cutoff_freq = 200.0 * pow(20.0, (double)value); // [200, 4000] _filter.setCutoff( cutoff_freq ); } else if( id == resonance ) { double q = 0.70710678118654757274 * (1.0 - value) + 20.0*value; _filter.setResonance( q ); } else if( id == high ) { _filter.setHigh( value ); } else if( id == band ) { _filter.setBand( value ); } else if( id == low ) { _filter.setLow( value ); } } } } } // process events if( data.inputEvents ) { int nEventCount = data.inputEvents->getEventCount(); for( int ii = 0; ii < nEventCount; ii++ ) { Event e; tresult result = data.inputEvents->getEvent(ii, e); if( result != kResultOk )continue; if( e.type == Event::kNoteOnEvent ) { int16 note_no = e.noteOff.pitch; auto target_note = std::find_if( _notes.begin(), _notes.end(), [note_no](const bandlimited_sawtooth_oscillator_note_vst3& n){return n.id() == note_no;}); if( target_note != _notes.end() ) { // 再度ノートON target_note->trigger(e.noteOn); } else { // 利用可能なノートを検索する auto available_note = std::find_if( _notes.begin(), _notes.end(), [](const bandlimited_sawtooth_oscillator_note_vst3& n){return n.adsr == bandlimited_sawtooth_oscillator_note::Silent;}); if( available_note != _notes.end() ) { // ノートON available_note->trigger( e.noteOn ); } } } else if( e.type == Event::kNoteOffEvent ) { //int32 note_id = e.noteOff.noteId; //auto target_note = std::find_if( // _notes.begin(), // _notes.end(), // [note_id](const bandlimited_sawtooth_oscillator_note_vst3& n){return n.id() == note_id;}); int16 note_no = e.noteOff.pitch; auto target_note = std::find_if( _notes.begin(), _notes.end(), [note_no](const bandlimited_sawtooth_oscillator_note_vst3& n){return n.id() == note_no;}); if( target_note != _notes.end() ) { // ノートOFF target_note->release(); } } else if( e.type == Event::kDataEvent ) { unsigned char status = e.data.bytes[0] & 0xf0; // ignoring channel if( status == 0xE0 ) { unsigned char data1 = e.data.bytes[1] & 0x7f; unsigned char data2 = e.data.bytes[2] & 0x7f; double pitch_bend = (( data1 + data2*128 ) - 8192 ) / 8192.0; for(auto note = _notes.begin(); note != _notes.end(); ++note) { note->setPitchBend( pitch_bend ); } } } } } bool bAllSilent= std::all_of( _notes.begin(), _notes.end(), [](const bandlimited_sawtooth_oscillator_note_vst3& n){return n.adsr == bandlimited_sawtooth_oscillator_note::Silent;}); if( bAllSilent ) { return kResultOk; } _filter.updateFilter(); /*--------*/ /*音声処理*/ /*--------*/ if (data.numInputs == 0 && data.numOutputs == 1 ) { for(auto note = _notes.begin(); note != _notes.end(); ++note) { // ピッチを更新 note->updateFrequency(); } if( data.outputs[0].numChannels == 2 ) { float** out = data.outputs[0].channelBuffers32; const int32 sampleFrames = data.numSamples; for( int ii = 0; ii < sampleFrames; ii++ ) { double value = 0.0; for(auto note = _notes.begin(); note != _notes.end(); ++note) { if( note->adsr == bandlimited_sawtooth_oscillator_note::Silent )continue; // ノート毎の音を足し合わせる value += note->saw * note->envelope * note->velocity(); // オシレーター更新 blit.updateOcsillater( *note ); // エンベロープ更新 blit.updateEnvelope( *note ); } // // フィルタを掛けたければ掛ける // double filterd_value = _filter.process(value); // 出力バッファに設定する double pan = 0.0; out[0][ii] = static_cast<float>( filterd_value * (1.0 - pan) * 0.5 ); out[1][ii] = static_cast<float>( filterd_value * (1.0 + pan) * 0.5 ); } } } return kResultOk; } }} <|endoftext|>
<commit_before>/* * Simple ASN.1 String Types * (C) 1999-2007,2020 Jack Lloyd * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/asn1_obj.h> #include <botan/der_enc.h> #include <botan/ber_dec.h> #include <botan/internal/charset.h> #include <botan/internal/ct_utils.h> namespace Botan { namespace { /* * Choose an encoding for the string */ ASN1_Type choose_encoding(const std::string& str) { auto all_printable = CT::Mask<uint8_t>::set(); for(size_t i = 0; i != str.size(); ++i) { const uint8_t c = static_cast<uint8_t>(str[i]); auto is_alpha_lower = CT::Mask<uint8_t>::is_within_range(c, 'a', 'z'); auto is_alpha_upper = CT::Mask<uint8_t>::is_within_range(c, 'A', 'Z'); auto is_decimal = CT::Mask<uint8_t>::is_within_range(c, '0', '9'); auto is_print_punc = CT::Mask<uint8_t>::is_any_of(c, { ' ', '(', ')', '+', ',', '=', ',', '-', '.', '/', ':', '=', '?'}); auto is_printable = is_alpha_lower | is_alpha_upper | is_decimal | is_print_punc; all_printable &= is_printable; } if(all_printable.is_set()) return ASN1_Type::PrintableString; else return ASN1_Type::Utf8String; } bool is_utf8_subset_string_type(ASN1_Type tag) { return (tag == ASN1_Type::NumericString || tag == ASN1_Type::PrintableString || tag == ASN1_Type::VisibleString || tag == ASN1_Type::Ia5String || tag == ASN1_Type::Utf8String); } bool is_asn1_string_type(ASN1_Type tag) { return (is_utf8_subset_string_type(tag) || tag == ASN1_Type::TeletexString || tag == ASN1_Type::BmpString || tag == ASN1_Type::UniversalString); } } //static bool ASN1_String::is_string_type(ASN1_Type tag) { return is_asn1_string_type(tag); } ASN1_String::ASN1_String(const std::string& str, ASN1_Type t) : m_utf8_str(str), m_tag(t) { if(!is_utf8_subset_string_type(m_tag)) { throw Invalid_Argument("ASN1_String only supports encoding to UTF-8 or a UTF-8 subset"); } } ASN1_String::ASN1_String(const std::string& str) : ASN1_String(str, choose_encoding(str)) {} /* * DER encode an ASN1_String */ void ASN1_String::encode_into(DER_Encoder& encoder) const { if(m_data.empty()) { BOTAN_ASSERT_NOMSG(is_utf8_subset_string_type(tagging())); encoder.add_object(tagging(), ASN1_Class::Universal, m_utf8_str); } else { // If this string was decoded, reserialize using original encoding encoder.add_object(tagging(), ASN1_Class::Universal, m_data.data(), m_data.size()); } } /* * Decode a BER encoded ASN1_String */ void ASN1_String::decode_from(BER_Decoder& source) { BER_Object obj = source.get_next_object(); if(!is_asn1_string_type(obj.type())) { throw Decoding_Error("ASN1_String: Unknown string type " + std::to_string(static_cast<uint32_t>(obj.type()))); } m_tag = obj.type(); m_data.assign(obj.bits(), obj.bits() + obj.length()); if(m_tag == ASN1_Type::BmpString) { m_utf8_str = ucs2_to_utf8(m_data.data(), m_data.size()); } else if(m_tag == ASN1_Type::UniversalString) { m_utf8_str = ucs4_to_utf8(m_data.data(), m_data.size()); } else if(m_tag == ASN1_Type::TeletexString) { /* TeletexString is nominally ITU T.61 not ISO-8859-1 but it seems the majority of implementations actually used that charset here. */ m_utf8_str = latin1_to_utf8(m_data.data(), m_data.size()); } else { // All other supported string types are UTF-8 or some subset thereof m_utf8_str = ASN1::to_string(obj); } } } <commit_msg>Remove duplicated chars from allowed chars in ASN1_Type::PrintableString<commit_after>/* * Simple ASN.1 String Types * (C) 1999-2007,2020 Jack Lloyd * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/asn1_obj.h> #include <botan/der_enc.h> #include <botan/ber_dec.h> #include <botan/internal/charset.h> #include <botan/internal/ct_utils.h> namespace Botan { namespace { /* * Choose an encoding for the string */ ASN1_Type choose_encoding(const std::string& str) { auto all_printable = CT::Mask<uint8_t>::set(); for(size_t i = 0; i != str.size(); ++i) { const uint8_t c = static_cast<uint8_t>(str[i]); auto is_alpha_lower = CT::Mask<uint8_t>::is_within_range(c, 'a', 'z'); auto is_alpha_upper = CT::Mask<uint8_t>::is_within_range(c, 'A', 'Z'); auto is_decimal = CT::Mask<uint8_t>::is_within_range(c, '0', '9'); auto is_print_punc = CT::Mask<uint8_t>::is_any_of(c, { ' ', '(', ')', '+', ',', '-', '.', '/', ':', '=', '?'}); auto is_printable = is_alpha_lower | is_alpha_upper | is_decimal | is_print_punc; all_printable &= is_printable; } if(all_printable.is_set()) return ASN1_Type::PrintableString; else return ASN1_Type::Utf8String; } bool is_utf8_subset_string_type(ASN1_Type tag) { return (tag == ASN1_Type::NumericString || tag == ASN1_Type::PrintableString || tag == ASN1_Type::VisibleString || tag == ASN1_Type::Ia5String || tag == ASN1_Type::Utf8String); } bool is_asn1_string_type(ASN1_Type tag) { return (is_utf8_subset_string_type(tag) || tag == ASN1_Type::TeletexString || tag == ASN1_Type::BmpString || tag == ASN1_Type::UniversalString); } } //static bool ASN1_String::is_string_type(ASN1_Type tag) { return is_asn1_string_type(tag); } ASN1_String::ASN1_String(const std::string& str, ASN1_Type t) : m_utf8_str(str), m_tag(t) { if(!is_utf8_subset_string_type(m_tag)) { throw Invalid_Argument("ASN1_String only supports encoding to UTF-8 or a UTF-8 subset"); } } ASN1_String::ASN1_String(const std::string& str) : ASN1_String(str, choose_encoding(str)) {} /* * DER encode an ASN1_String */ void ASN1_String::encode_into(DER_Encoder& encoder) const { if(m_data.empty()) { BOTAN_ASSERT_NOMSG(is_utf8_subset_string_type(tagging())); encoder.add_object(tagging(), ASN1_Class::Universal, m_utf8_str); } else { // If this string was decoded, reserialize using original encoding encoder.add_object(tagging(), ASN1_Class::Universal, m_data.data(), m_data.size()); } } /* * Decode a BER encoded ASN1_String */ void ASN1_String::decode_from(BER_Decoder& source) { BER_Object obj = source.get_next_object(); if(!is_asn1_string_type(obj.type())) { throw Decoding_Error("ASN1_String: Unknown string type " + std::to_string(static_cast<uint32_t>(obj.type()))); } m_tag = obj.type(); m_data.assign(obj.bits(), obj.bits() + obj.length()); if(m_tag == ASN1_Type::BmpString) { m_utf8_str = ucs2_to_utf8(m_data.data(), m_data.size()); } else if(m_tag == ASN1_Type::UniversalString) { m_utf8_str = ucs4_to_utf8(m_data.data(), m_data.size()); } else if(m_tag == ASN1_Type::TeletexString) { /* TeletexString is nominally ITU T.61 not ISO-8859-1 but it seems the majority of implementations actually used that charset here. */ m_utf8_str = latin1_to_utf8(m_data.data(), m_data.size()); } else { // All other supported string types are UTF-8 or some subset thereof m_utf8_str = ASN1::to_string(obj); } } } <|endoftext|>
<commit_before><commit_msg>useless aStr string<commit_after><|endoftext|>
<commit_before>//******************************************************************* //glfont2.cpp -- glFont Version 2.0 implementation //Copyright (c) 1998-2002 Brad Fish //See glfont.html for terms of use //May 14, 2002 //******************************************************************* //STL headers #include <string> #include <utility> #include <iostream> #include <fstream> using namespace std; //OpenGL headers #ifdef _WINDOWS #include <windows.h> #endif #include <GL/gl.h> //glFont header #include "glfont2.h" using namespace glfont; //******************************************************************* //GLFont Class Implementation //******************************************************************* GLFont::GLFont () { //Initialize header to safe state header.tex = -1; header.tex_width = 0; header.tex_height = 0; header.start_char = 0; header.end_char = 0; header.chars = NULL; } //******************************************************************* GLFont::~GLFont () { //Destroy the font Destroy(); } //******************************************************************* bool GLFont::Create (const char *file_name, int tex) { ifstream input; int num_chars, num_tex_bytes; char *tex_bytes; //Destroy the old font if there was one, just to be safe Destroy(); //Open input file input.open(file_name, ios::in | ios::binary); if (!input) return false; //Read the header from file input.read((char *)&header, sizeof(header)); header.tex = tex; //Allocate space for character array num_chars = header.end_char - header.start_char + 1; if ((header.chars = new GLFontChar[num_chars]) == NULL) return false; //Read character array for(int i=0; i < num_chars; i++) input.read((char *)&header.chars[i], sizeof(GLFontChar) - (sizeof(void*) - 4)); //Read texture pixel data num_tex_bytes = header.tex_width * header.tex_height * 2; tex_bytes = new char[num_tex_bytes]; input.read(tex_bytes, num_tex_bytes); //Create OpenGL texture glBindTexture(GL_TEXTURE_2D, tex); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glTexImage2D(GL_TEXTURE_2D, 0, 2, header.tex_width, header.tex_height, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, (void *)tex_bytes); //Free texture pixels memory delete[] tex_bytes; //Close input file input.close(); //Return successfully cout << "Start: " << header.start_char << ", End: " << header.end_char << ", Chars: " << header.chars << endl; cout << "Height: " << header.tex_height << ", Width: " << header.tex_width << endl; //Read character array for(int i=header.start_char; i < header.end_char; i++) { GLFontChar c = header.chars[i - header.start_char]; cout << "Char: " << i << ", dx: " << c.dx << ", dy: " << c.dy << endl; cout << "ty1: " << c.ty1 << ", ty2: " << c.ty2 << ", tx1: " << c.tx1 << ", tx2: " << c.tx2 << endl; } return true; } //******************************************************************* bool GLFont::Create (const std::string &file_name, int tex) { return Create(file_name.c_str(), tex); } //******************************************************************* void GLFont::Destroy (void) { //Delete the character array if necessary if (header.chars) { delete[] header.chars; header.chars = NULL; } } //******************************************************************* void GLFont::GetTexSize (std::pair<int, int> *size) { //Retrieve texture size size->first = header.tex_width; size->second = header.tex_height; } //******************************************************************* int GLFont::GetTexWidth (void) { //Return texture width return header.tex_width; } //******************************************************************* int GLFont::GetTexHeight (void) { //Return texture height return header.tex_height; } //******************************************************************* void GLFont::GetCharInterval (std::pair<int, int> *interval) { //Retrieve character interval interval->first = header.start_char; interval->second = header.end_char; } //******************************************************************* int GLFont::GetStartChar (void) { //Return start character return header.start_char; } //******************************************************************* int GLFont::GetEndChar (void) { //Return end character return header.end_char; } //******************************************************************* void GLFont::GetCharSize (int c, std::pair<int, int> *size) { //Make sure character is in range if (c < header.start_char || c > header.end_char) { //Not a valid character, so it obviously has no size size->first = 0; size->second = 0; } else { GLFontChar *glfont_char; //Retrieve character size glfont_char = &header.chars[c - header.start_char]; size->first = (int)(glfont_char->dx * header.tex_width); size->second = (int)(glfont_char->dy * header.tex_height); } } //******************************************************************* int GLFont::GetCharWidth (int c) { //Make sure in range if (c < header.start_char || c > header.end_char) return 0; else { GLFontChar *glfont_char; //Retrieve character width glfont_char = &header.chars[c - header.start_char]; return (int)(glfont_char->dx * header.tex_width); } } //******************************************************************* int GLFont::GetCharHeight (int c) { //Make sure in range if (c < header.start_char || c > header.end_char) return 0; else { GLFontChar *glfont_char; //Retrieve character height glfont_char = &header.chars[c - header.start_char]; return (int)(glfont_char->dy * header.tex_height); } } //******************************************************************* void GLFont::Begin (void) { //Bind to font texture glBindTexture(GL_TEXTURE_2D, header.tex); } //******************************************************************* //End of file <commit_msg>fix for 64-bit. i mean it really<commit_after>//******************************************************************* //glfont2.cpp -- glFont Version 2.0 implementation //Copyright (c) 1998-2002 Brad Fish //See glfont.html for terms of use //May 14, 2002 //******************************************************************* //STL headers #include <string> #include <utility> #include <iostream> #include <fstream> using namespace std; //OpenGL headers #ifdef _WINDOWS #include <windows.h> #endif #include <GL/gl.h> //glFont header #include "glfont2.h" using namespace glfont; //******************************************************************* //GLFont Class Implementation //******************************************************************* GLFont::GLFont () { //Initialize header to safe state header.tex = -1; header.tex_width = 0; header.tex_height = 0; header.start_char = 0; header.end_char = 0; header.chars = NULL; } //******************************************************************* GLFont::~GLFont () { //Destroy the font Destroy(); } //******************************************************************* bool GLFont::Create (const char *file_name, int tex) { ifstream input; int num_chars, num_tex_bytes; char *tex_bytes; //Destroy the old font if there was one, just to be safe Destroy(); //Open input file input.open(file_name, ios::in | ios::binary); if (!input) return false; //Read the header from file input.read((char *)&header, sizeof(header) - (sizeof(void*) - 4)); header.tex = tex; //Allocate space for character array num_chars = header.end_char - header.start_char + 1; if ((header.chars = new GLFontChar[num_chars]) == NULL) return false; //Read character array for(int i=0; i < num_chars; i++) input.read((char *)&header.chars[i], sizeof(GLFontChar)); //Read texture pixel data num_tex_bytes = header.tex_width * header.tex_height * 2; tex_bytes = new char[num_tex_bytes]; input.read(tex_bytes, num_tex_bytes); //Create OpenGL texture glBindTexture(GL_TEXTURE_2D, tex); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glTexImage2D(GL_TEXTURE_2D, 0, 2, header.tex_width, header.tex_height, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, (void *)tex_bytes); //Free texture pixels memory delete[] tex_bytes; //Close input file input.close(); //Return successfully cout << "Start: " << header.start_char << ", End: " << header.end_char << ", Chars: " << header.chars << endl; cout << "Height: " << header.tex_height << ", Width: " << header.tex_width << endl; //Read character array for(int i=header.start_char; i < header.end_char; i++) { GLFontChar c = header.chars[i - header.start_char]; cout << "Char: " << i << ", dx: " << c.dx << ", dy: " << c.dy << endl; cout << "ty1: " << c.ty1 << ", ty2: " << c.ty2 << ", tx1: " << c.tx1 << ", tx2: " << c.tx2 << endl; } return true; } //******************************************************************* bool GLFont::Create (const std::string &file_name, int tex) { return Create(file_name.c_str(), tex); } //******************************************************************* void GLFont::Destroy (void) { //Delete the character array if necessary if (header.chars) { delete[] header.chars; header.chars = NULL; } } //******************************************************************* void GLFont::GetTexSize (std::pair<int, int> *size) { //Retrieve texture size size->first = header.tex_width; size->second = header.tex_height; } //******************************************************************* int GLFont::GetTexWidth (void) { //Return texture width return header.tex_width; } //******************************************************************* int GLFont::GetTexHeight (void) { //Return texture height return header.tex_height; } //******************************************************************* void GLFont::GetCharInterval (std::pair<int, int> *interval) { //Retrieve character interval interval->first = header.start_char; interval->second = header.end_char; } //******************************************************************* int GLFont::GetStartChar (void) { //Return start character return header.start_char; } //******************************************************************* int GLFont::GetEndChar (void) { //Return end character return header.end_char; } //******************************************************************* void GLFont::GetCharSize (int c, std::pair<int, int> *size) { //Make sure character is in range if (c < header.start_char || c > header.end_char) { //Not a valid character, so it obviously has no size size->first = 0; size->second = 0; } else { GLFontChar *glfont_char; //Retrieve character size glfont_char = &header.chars[c - header.start_char]; size->first = (int)(glfont_char->dx * header.tex_width); size->second = (int)(glfont_char->dy * header.tex_height); } } //******************************************************************* int GLFont::GetCharWidth (int c) { //Make sure in range if (c < header.start_char || c > header.end_char) return 0; else { GLFontChar *glfont_char; //Retrieve character width glfont_char = &header.chars[c - header.start_char]; return (int)(glfont_char->dx * header.tex_width); } } //******************************************************************* int GLFont::GetCharHeight (int c) { //Make sure in range if (c < header.start_char || c > header.end_char) return 0; else { GLFontChar *glfont_char; //Retrieve character height glfont_char = &header.chars[c - header.start_char]; return (int)(glfont_char->dy * header.tex_height); } } //******************************************************************* void GLFont::Begin (void) { //Bind to font texture glBindTexture(GL_TEXTURE_2D, header.tex); } //******************************************************************* //End of file <|endoftext|>
<commit_before>// Copyright (C) 2014 - 2015 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. #include "copasi/utilities/CBaseUnit.h" #include "copasi/utilities/CCopasiMessage.h" #include "copasi/UI/qtUtilities.h" // static const char * CBaseUnit::Name[] = { "dimensionless", "meter", "gram", "second", "Ampere", "Kelvin", "item", "Candela", NULL }; // static (because CBaseUnit is not meant to be constructed) const std::string CBaseUnit::getSymbol(Kind kind) { switch (kind) { case dimensionless: return ""; case meter: return "m"; case gram: return "g"; case second: return "s"; case ampere: return "A"; case kelvin: return "K"; case candela: return "cd"; case item: return "#"; default: return ""; } } // static (because CBaseUnit is not meant to be constructed) const CBaseUnit::Kind CBaseUnit::fromSymbol(const std::string & symbol) { if (symbol == "m") return meter; if (symbol == "g") return gram; if (symbol == "s") return second; if (symbol == "A") return ampere; if (symbol == "K") return kelvin; if (symbol == "cd") return candela; if (symbol == "#") return item; if (symbol == "") return dimensionless; fatalError(); return dimensionless; } // static (because CBaseUnit is not meant to be constructed) const CBaseUnit::Scale CBaseUnit::scaleFromPrefix(const std::string & prefix) { if (prefix == "a") return atto; if (prefix == "f") return femto; if (prefix == "p") return pico; if (prefix == "u" || prefix == "\xc2\xb5") return micro; if (prefix == "m") return milli; if (prefix == "c") return centi; if (prefix == "d") return deci; if (prefix == "h") return hecto; if (prefix == "k") return kilo; if (prefix == "M") return mega; if (prefix == "G") return giga; if (prefix == "T") return tera; if (prefix == "P") return peta; return zero; } <commit_msg>- cbaseuntit should not include qt, as we currently don't have a qt dependency for libcopasise/copasise<commit_after>// Copyright (C) 2014 - 2016 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. #include "copasi/utilities/CBaseUnit.h" #include "copasi/utilities/CCopasiMessage.h" // static const char * CBaseUnit::Name[] = { "dimensionless", "meter", "gram", "second", "Ampere", "Kelvin", "item", "Candela", NULL }; // static (because CBaseUnit is not meant to be constructed) const std::string CBaseUnit::getSymbol(Kind kind) { switch (kind) { case dimensionless: return ""; case meter: return "m"; case gram: return "g"; case second: return "s"; case ampere: return "A"; case kelvin: return "K"; case candela: return "cd"; case item: return "#"; default: return ""; } } // static (because CBaseUnit is not meant to be constructed) const CBaseUnit::Kind CBaseUnit::fromSymbol(const std::string & symbol) { if (symbol == "m") return meter; if (symbol == "g") return gram; if (symbol == "s") return second; if (symbol == "A") return ampere; if (symbol == "K") return kelvin; if (symbol == "cd") return candela; if (symbol == "#") return item; if (symbol == "") return dimensionless; fatalError(); return dimensionless; } // static (because CBaseUnit is not meant to be constructed) const CBaseUnit::Scale CBaseUnit::scaleFromPrefix(const std::string & prefix) { if (prefix == "a") return atto; if (prefix == "f") return femto; if (prefix == "p") return pico; if (prefix == "u" || prefix == "\xc2\xb5") return micro; if (prefix == "m") return milli; if (prefix == "c") return centi; if (prefix == "d") return deci; if (prefix == "h") return hecto; if (prefix == "k") return kilo; if (prefix == "M") return mega; if (prefix == "G") return giga; if (prefix == "T") return tera; if (prefix == "P") return peta; return zero; } <|endoftext|>
<commit_before>/* * Copyright 2009-2011 The VOTCA Development Team (http://www.votca.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <string> #include <votca/tools/statement.h> namespace votca { namespace tools { using namespace std; Statement::~Statement() { sqlite3_finalize(_stmt); } template<> void Statement::Bind(int col, const int &value) { sqlite3_bind_int(_stmt, col, value); } template<> void Statement::Bind(int col, const double &value) { sqlite3_bind_double(_stmt, col, value); } template<> int Statement::Column<int>(int col) { return sqlite3_column_int(_stmt, col); } template<> double Statement::Column<double>(int col) { return sqlite3_column_double(_stmt, col); } template<> string Statement::Column<string>(int col) { return string((const char*)sqlite3_column_text(_stmt, col)); } template<> void Statement::Bind(int col, const string &value) { sqlite3_bind_text(_stmt, col, value.c_str(), -1, NULL);; } int Statement::Step() { return sqlite3_step(_stmt); } void Statement::Reset() { sqlite3_reset(_stmt); } }} <commit_msg>error handling in statement<commit_after>/* * Copyright 2009-2011 The VOTCA Development Team (http://www.votca.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <string> #include <votca/tools/statement.h> #include <stdexcept> namespace votca { namespace tools { using namespace std; Statement::~Statement() { sqlite3_finalize(_stmt); } template<> void Statement::Bind(int col, const int &value) { if(sqlite3_bind_int(_stmt, col, value) != SQLITE_OK) throw std::runtime_error("sqlite_bind failed"); } template<> void Statement::Bind(int col, const double &value) { if(sqlite3_bind_double(_stmt, col, value) != SQLITE_OK) throw std::runtime_error("sqlite_bind failed"); } template<> int Statement::Column<int>(int col) { return sqlite3_column_int(_stmt, col); } template<> double Statement::Column<double>(int col) { return sqlite3_column_double(_stmt, col); } template<> string Statement::Column<string>(int col) { return string((const char*)sqlite3_column_text(_stmt, col)); } template<> void Statement::Bind(int col, const string &value) { if(sqlite3_bind_text(_stmt, col, value.c_str(), -1, NULL) != SQLITE_OK) throw std::runtime_error("sqlite_bind failed"); } int Statement::Step() { return sqlite3_step(_stmt); } void Statement::Reset() { sqlite3_reset(_stmt); } }} <|endoftext|>
<commit_before><commit_msg>Propagate first_and_last option into nonlinear iterative solvers.<commit_after><|endoftext|>
<commit_before><commit_msg>Fix nvcc sign warning<commit_after><|endoftext|>
<commit_before>#define PGDLLIMPORT "C" #include <cstdlib> #include "postgres.h" #include "funcapi.h" #include "access/extprotocol.h" #include "catalog/pg_proc.h" #include "utils/array.h" #include "utils/builtins.h" #include "utils/memutils.h" #include "fmgr.h" #include "S3ExtWrapper.h" #include "S3Common.h" #include "S3Log.h" #include "utils.h" #include "gps3ext.h" #include "gps3conf.h" #include <pthread.h> #include <openssl/err.h> /* Do the module magic dance */ PG_MODULE_MAGIC; PG_FUNCTION_INFO_V1(s3_export); PG_FUNCTION_INFO_V1(s3_import); PG_FUNCTION_INFO_V1(s3_validate_urls); extern "C" { Datum s3_export(PG_FUNCTION_ARGS); Datum s3_import(PG_FUNCTION_ARGS); Datum s3_validate_urls(PG_FUNCTION_ARGS); } #define MUTEX_TYPE pthread_mutex_t #define MUTEX_SETUP(x) pthread_mutex_init(&(x), NULL) #define MUTEX_CLEANUP(x) pthread_mutex_destroy(&(x)) #define MUTEX_LOCK(x) pthread_mutex_lock(&(x)) #define MUTEX_UNLOCK(x) pthread_mutex_unlock(&(x)) #define THREAD_ID pthread_self() /* This array will store all of the mutexes available to OpenSSL. */ static MUTEX_TYPE *mutex_buf = NULL; static void locking_function(int mode, int n, const char *file, int line) { if (mode & CRYPTO_LOCK) MUTEX_LOCK(mutex_buf[n]); else MUTEX_UNLOCK(mutex_buf[n]); } static unsigned long id_function(void) { return ((unsigned long)THREAD_ID); } int thread_setup(void) { int i; mutex_buf = (pthread_mutex_t *)palloc(CRYPTO_num_locks() * sizeof(MUTEX_TYPE)); if (!mutex_buf) return 0; for (i = 0; i < CRYPTO_num_locks(); i++) MUTEX_SETUP(mutex_buf[i]); CRYPTO_set_id_callback(id_function); CRYPTO_set_locking_callback(locking_function); return 1; } int thread_cleanup(void) { int i; if (!mutex_buf) return 0; CRYPTO_set_id_callback(NULL); CRYPTO_set_locking_callback(NULL); for (i = 0; i < CRYPTO_num_locks(); i++) MUTEX_CLEANUP(mutex_buf[i]); pfree(mutex_buf); mutex_buf = NULL; return 1; } /* * Import data into GPDB. */ Datum s3_import(PG_FUNCTION_ARGS) { S3ExtBase *myData; char *data; int data_len; size_t nread = 0; /* Must be called via the external table format manager */ if (!CALLED_AS_EXTPROTOCOL(fcinfo)) elog(ERROR, "extprotocol_import: not called by external protocol manager"); /* Get our internal description of the protocol */ myData = (S3ExtBase *)EXTPROTOCOL_GET_USER_CTX(fcinfo); if (EXTPROTOCOL_IS_LAST_CALL(fcinfo)) { if (myData) { thread_cleanup(); if (!myData->Destroy()) { ereport(ERROR, (0, errmsg("Cleanup S3 extention failed"))); } delete myData; } PG_RETURN_INT32(0); } if (myData == NULL) { /* first call. do any desired init */ curl_global_init(CURL_GLOBAL_ALL); thread_setup(); const char *p_name = "s3"; char *url_with_options = EXTPROTOCOL_GET_URL(fcinfo); char *url = truncate_options(url_with_options); char *config_path = get_opt_s3(url_with_options, "config"); if (!config_path) { // no config path in url, use default value // data_folder/gpseg0/s3/s3.conf config_path = pstrdup("s3/s3.conf"); } bool result = InitConfig(config_path, ""); if (!result) { ereport(ERROR, (0, errmsg("Can't find config file %s", config_path))); pfree(config_path); } else { ClearConfig(); pfree(config_path); } InitLog(); if (s3ext_accessid == "") { ereport(ERROR, (0, errmsg("ERROR: access id is empty"))); } if (s3ext_secret == "") { ereport(ERROR, (0, errmsg("ERROR: secret is empty"))); } if ((s3ext_segnum == -1) || (s3ext_segid == -1)) { ereport(ERROR, (0, errmsg("ERROR: segment id is invalid"))); } myData = CreateExtWrapper(url); if (!myData || !myData->Init(s3ext_segid, s3ext_segnum, s3ext_chunksize)) { if (myData) delete myData; ereport(ERROR, (0, errmsg("Failed to init S3 extension, segid = " "%d, segnum = %d, please check your " "configurations and net connection", s3ext_segid, s3ext_segnum))); } /* if(strcasecmp(parsed_url->protocol, p_name) != 0) { elog(ERROR, "internal error: s3prot called with a different protocol (%s)", parsed_url->protocol); } */ EXTPROTOCOL_SET_USER_CTX(fcinfo, myData); free(url); } /* ======================================================================= * DO THE IMPORT * ======================================================================= */ data = EXTPROTOCOL_GET_DATABUF(fcinfo); data_len = EXTPROTOCOL_GET_DATALEN(fcinfo); uint64_t readlen = 0; if (data_len > 0) { readlen = data_len; if (!myData->TransferData(data, readlen)) ereport(ERROR, (0, errmsg("s3_import: could not read data"))); nread = (size_t)readlen; // S3DEBUG("read %d data from S3", nread); } PG_RETURN_INT32((int)nread); } /* * Export data out of GPDB. */ Datum s3_export(PG_FUNCTION_ARGS) { PG_RETURN_INT32(0); } Datum s3_validate_urls(PG_FUNCTION_ARGS) { int nurls; int i; ValidatorDirection direction; PG_RETURN_VOID(); } <commit_msg>don't use use pg alloc functions here, conflict with get_opt_s3() in unit test env<commit_after>#define PGDLLIMPORT "C" #include <cstdlib> #include "postgres.h" #include "funcapi.h" #include "access/extprotocol.h" #include "catalog/pg_proc.h" #include "utils/array.h" #include "utils/builtins.h" #include "utils/memutils.h" #include "fmgr.h" #include "S3ExtWrapper.h" #include "S3Common.h" #include "S3Log.h" #include "utils.h" #include "gps3ext.h" #include "gps3conf.h" #include <pthread.h> #include <openssl/err.h> /* Do the module magic dance */ PG_MODULE_MAGIC; PG_FUNCTION_INFO_V1(s3_export); PG_FUNCTION_INFO_V1(s3_import); PG_FUNCTION_INFO_V1(s3_validate_urls); extern "C" { Datum s3_export(PG_FUNCTION_ARGS); Datum s3_import(PG_FUNCTION_ARGS); Datum s3_validate_urls(PG_FUNCTION_ARGS); } #define MUTEX_TYPE pthread_mutex_t #define MUTEX_SETUP(x) pthread_mutex_init(&(x), NULL) #define MUTEX_CLEANUP(x) pthread_mutex_destroy(&(x)) #define MUTEX_LOCK(x) pthread_mutex_lock(&(x)) #define MUTEX_UNLOCK(x) pthread_mutex_unlock(&(x)) #define THREAD_ID pthread_self() /* This array will store all of the mutexes available to OpenSSL. */ static MUTEX_TYPE *mutex_buf = NULL; static void locking_function(int mode, int n, const char *file, int line) { if (mode & CRYPTO_LOCK) MUTEX_LOCK(mutex_buf[n]); else MUTEX_UNLOCK(mutex_buf[n]); } static unsigned long id_function(void) { return ((unsigned long)THREAD_ID); } int thread_setup(void) { int i; mutex_buf = (pthread_mutex_t *)palloc(CRYPTO_num_locks() * sizeof(MUTEX_TYPE)); if (!mutex_buf) return 0; for (i = 0; i < CRYPTO_num_locks(); i++) MUTEX_SETUP(mutex_buf[i]); CRYPTO_set_id_callback(id_function); CRYPTO_set_locking_callback(locking_function); return 1; } int thread_cleanup(void) { int i; if (!mutex_buf) return 0; CRYPTO_set_id_callback(NULL); CRYPTO_set_locking_callback(NULL); for (i = 0; i < CRYPTO_num_locks(); i++) MUTEX_CLEANUP(mutex_buf[i]); pfree(mutex_buf); mutex_buf = NULL; return 1; } /* * Import data into GPDB. */ Datum s3_import(PG_FUNCTION_ARGS) { S3ExtBase *myData; char *data; int data_len; size_t nread = 0; /* Must be called via the external table format manager */ if (!CALLED_AS_EXTPROTOCOL(fcinfo)) elog(ERROR, "extprotocol_import: not called by external protocol manager"); /* Get our internal description of the protocol */ myData = (S3ExtBase *)EXTPROTOCOL_GET_USER_CTX(fcinfo); if (EXTPROTOCOL_IS_LAST_CALL(fcinfo)) { if (myData) { thread_cleanup(); if (!myData->Destroy()) { ereport(ERROR, (0, errmsg("Cleanup S3 extention failed"))); } delete myData; } PG_RETURN_INT32(0); } if (myData == NULL) { /* first call. do any desired init */ curl_global_init(CURL_GLOBAL_ALL); thread_setup(); const char *p_name = "s3"; char *url_with_options = EXTPROTOCOL_GET_URL(fcinfo); char *url = truncate_options(url_with_options); char *config_path = get_opt_s3(url_with_options, "config"); if (!config_path) { // no config path in url, use default value // data_folder/gpseg0/s3/s3.conf config_path = strdup("s3/s3.conf"); } bool result = InitConfig(config_path, ""); if (!result) { free(config_path); ereport(ERROR, (0, errmsg("Can't find config file, please check"))); } else { ClearConfig(); free(config_path); } InitLog(); if (s3ext_accessid == "") { ereport(ERROR, (0, errmsg("ERROR: access id is empty"))); } if (s3ext_secret == "") { ereport(ERROR, (0, errmsg("ERROR: secret is empty"))); } if ((s3ext_segnum == -1) || (s3ext_segid == -1)) { ereport(ERROR, (0, errmsg("ERROR: segment id is invalid"))); } myData = CreateExtWrapper(url); if (!myData || !myData->Init(s3ext_segid, s3ext_segnum, s3ext_chunksize)) { if (myData) delete myData; ereport(ERROR, (0, errmsg("Failed to init S3 extension, segid = " "%d, segnum = %d, please check your " "configurations and net connection", s3ext_segid, s3ext_segnum))); } /* if(strcasecmp(parsed_url->protocol, p_name) != 0) { elog(ERROR, "internal error: s3prot called with a different protocol (%s)", parsed_url->protocol); } */ EXTPROTOCOL_SET_USER_CTX(fcinfo, myData); free(url); } /* ======================================================================= * DO THE IMPORT * ======================================================================= */ data = EXTPROTOCOL_GET_DATABUF(fcinfo); data_len = EXTPROTOCOL_GET_DATALEN(fcinfo); uint64_t readlen = 0; if (data_len > 0) { readlen = data_len; if (!myData->TransferData(data, readlen)) ereport(ERROR, (0, errmsg("s3_import: could not read data"))); nread = (size_t)readlen; // S3DEBUG("read %d data from S3", nread); } PG_RETURN_INT32((int)nread); } /* * Export data out of GPDB. */ Datum s3_export(PG_FUNCTION_ARGS) { PG_RETURN_INT32(0); } Datum s3_validate_urls(PG_FUNCTION_ARGS) { int nurls; int i; ValidatorDirection direction; PG_RETURN_VOID(); } <|endoftext|>
<commit_before>#include "renderState.h" #include "platform.h" #include "vertexLayout.h" #include "gl/hardware.h" namespace Tangram { // Incremented when the GL context is invalidated static int s_validGeneration; static int s_textureUnit; namespace RenderState { Blending blending; DepthTest depthTest; StencilTest stencilTest; Culling culling; DepthWrite depthWrite; BlendingFunc blendingFunc; StencilWrite stencilWrite; StencilFunc stencilFunc; StencilOp stencilOp; ColorWrite colorWrite; FrontFace frontFace; CullFace cullFace; VertexBuffer vertexBuffer; IndexBuffer indexBuffer; ShaderProgram shaderProgram; TextureUnit textureUnit; Texture texture; ClearColor clearColor; GLuint getTextureUnit(GLuint _unit) { return GL_TEXTURE0 + _unit; } void bindVertexBuffer(GLuint _id) { GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, _id)); } void bindIndexBuffer(GLuint _id) { GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _id)); } void activeTextureUnit(GLuint _unit) { GL_CHECK(glActiveTexture(getTextureUnit(_unit))); } void bindTexture(GLenum _target, GLuint _textureId) { GL_CHECK(glBindTexture(_target, _textureId)); } void configure() { s_textureUnit = -1; s_validGeneration++; VertexLayout::clearCache(); blending.init(GL_FALSE); blendingFunc.init(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); culling.init(GL_TRUE); cullFace.init(GL_BACK); frontFace.init(GL_CCW); depthTest.init(GL_TRUE); depthWrite.init(GL_TRUE); GL_CHECK(glDisable(GL_STENCIL_TEST)); GL_CHECK(glDepthFunc(GL_LESS)); GL_CHECK(glClearDepthf(1.0)); GL_CHECK(glDepthRangef(0.0, 1.0)); static size_t max = std::numeric_limits<size_t>::max(); clearColor.init(0.0, 0.0, 0.0, 0.0); shaderProgram.init(max, false); vertexBuffer.init(max, false); indexBuffer.init(max, false); texture.init(GL_TEXTURE_2D, max, false); texture.init(GL_TEXTURE_CUBE_MAP, max, false); textureUnit.init(max, false); } bool isValidGeneration(int _generation) { return _generation == s_validGeneration; } int generation() { return s_validGeneration; } int nextAvailableTextureUnit() { if (s_textureUnit + 1 > Hardware::maxCombinedTextureUnits) { LOGE("Too many combined texture units are being used"); LOGE("GPU supports %d combined texture units", Hardware::maxCombinedTextureUnits); } return ++s_textureUnit; } void releaseTextureUnit() { s_textureUnit--; } int currentTextureUnit() { return s_textureUnit; } void resetTextureUnit() { s_textureUnit = -1; } } } <commit_msg>Invalidate render state tracking of current texture binding (#784)<commit_after>#include "renderState.h" #include "platform.h" #include "vertexLayout.h" #include "gl/hardware.h" namespace Tangram { // Incremented when the GL context is invalidated static int s_validGeneration; static int s_textureUnit; namespace RenderState { Blending blending; DepthTest depthTest; StencilTest stencilTest; Culling culling; DepthWrite depthWrite; BlendingFunc blendingFunc; StencilWrite stencilWrite; StencilFunc stencilFunc; StencilOp stencilOp; ColorWrite colorWrite; FrontFace frontFace; CullFace cullFace; VertexBuffer vertexBuffer; IndexBuffer indexBuffer; ShaderProgram shaderProgram; TextureUnit textureUnit; Texture texture; ClearColor clearColor; GLuint getTextureUnit(GLuint _unit) { return GL_TEXTURE0 + _unit; } static size_t max = std::numeric_limits<size_t>::max(); void bindVertexBuffer(GLuint _id) { GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, _id)); } void bindIndexBuffer(GLuint _id) { GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _id)); } void activeTextureUnit(GLuint _unit) { // current texture unit is changing, invalidate current texture binding: texture.init(GL_TEXTURE_2D, max, false); GL_CHECK(glActiveTexture(getTextureUnit(_unit))); } void bindTexture(GLenum _target, GLuint _textureId) { GL_CHECK(glBindTexture(_target, _textureId)); } void configure() { s_textureUnit = -1; s_validGeneration++; VertexLayout::clearCache(); blending.init(GL_FALSE); blendingFunc.init(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); culling.init(GL_TRUE); cullFace.init(GL_BACK); frontFace.init(GL_CCW); depthTest.init(GL_TRUE); depthWrite.init(GL_TRUE); GL_CHECK(glDisable(GL_STENCIL_TEST)); GL_CHECK(glDepthFunc(GL_LESS)); GL_CHECK(glClearDepthf(1.0)); GL_CHECK(glDepthRangef(0.0, 1.0)); clearColor.init(0.0, 0.0, 0.0, 0.0); shaderProgram.init(max, false); vertexBuffer.init(max, false); indexBuffer.init(max, false); texture.init(GL_TEXTURE_2D, max, false); texture.init(GL_TEXTURE_CUBE_MAP, max, false); textureUnit.init(max, false); } bool isValidGeneration(int _generation) { return _generation == s_validGeneration; } int generation() { return s_validGeneration; } int nextAvailableTextureUnit() { if (s_textureUnit + 1 > Hardware::maxCombinedTextureUnits) { LOGE("Too many combined texture units are being used"); LOGE("GPU supports %d combined texture units", Hardware::maxCombinedTextureUnits); } return ++s_textureUnit; } void releaseTextureUnit() { s_textureUnit--; } int currentTextureUnit() { return s_textureUnit; } void resetTextureUnit() { s_textureUnit = -1; } } } <|endoftext|>
<commit_before>#include "pbfParser.h" #include "tile/tile.h" #include "platform.h" namespace Tangram { void PbfParser::extractGeometry(ParserContext& _ctx, protobuf::message& _geomIn) { pbfGeomCmd cmd = pbfGeomCmd::moveTo; uint32_t cmdRepeat = 0; double invTileExtent = (1.0/(double)_ctx.tileExtent); int64_t x = 0; int64_t y = 0; size_t numCoordinates = 0; while(_geomIn.getData() < _geomIn.getEnd()) { if(cmdRepeat == 0) { // get new command, lengh and parameters.. uint32_t cmdData = static_cast<uint32_t>(_geomIn.varint()); cmd = static_cast<pbfGeomCmd>(cmdData & 0x7); //first 3 bits of the cmdData cmdRepeat = cmdData >> 3; //last 5 bits } if(cmd == pbfGeomCmd::moveTo || cmd == pbfGeomCmd::lineTo) { // get parameters/points // if cmd is move then move to a new line/set of points and save this line if(cmd == pbfGeomCmd::moveTo) { if(_ctx.coordinates.size() > 0) { _ctx.numCoordinates.push_back(numCoordinates); } numCoordinates = 0; } x += _geomIn.svarint(); y += _geomIn.svarint(); // bring the points in -1 to 1 space Point p; p.x = invTileExtent * (double)(2 * x - _ctx.tileExtent); p.y = invTileExtent * (double)(_ctx.tileExtent - 2 * y); _ctx.coordinates.push_back(p); numCoordinates++; } else if(cmd == pbfGeomCmd::closePath) { // end of a polygon, push first point in this line as last and push line to poly _ctx.coordinates.push_back(_ctx.coordinates[_ctx.coordinates.size() - numCoordinates]); _ctx.numCoordinates.push_back(numCoordinates + 1); numCoordinates = 0; } cmdRepeat--; } // Enter the last line if (numCoordinates > 0) { _ctx.numCoordinates.push_back(numCoordinates); } } void PbfParser::extractFeature(ParserContext& _ctx, protobuf::message& _featureIn, Feature& _out) { //Iterate through this feature protobuf::message geometry; // By default data_ and end_ are nullptr _ctx.properties.clear(); _ctx.coordinates.clear(); _ctx.numCoordinates.clear(); while(_featureIn.next()) { switch(_featureIn.tag) { // Feature ID case 1: // ignored for now, also not used in json parsing _featureIn.skip(); break; // Feature tags (properties) case 2: { // extract tags message protobuf::message tagsMsg = _featureIn.getMessage(); while(tagsMsg) { std::size_t tagKey = tagsMsg.varint(); if(_ctx.keys.size() <= tagKey) { logMsg("ERROR: accessing out of bound key\n"); return; } if(!tagsMsg) { logMsg("ERROR: uneven number of feature tag ids\n"); return; } std::size_t valueKey = tagsMsg.varint(); if( _ctx.values.size() <= valueKey ) { logMsg("ERROR: accessing out of bound values\n"); return; } _ctx.properties.emplace_back(_ctx.keys[tagKey], _ctx.values[valueKey]); } break; } // Feature Type case 3: _out.geometryType = (GeometryType)_featureIn.varint(); break; // Actual geometry data case 4: geometry = _featureIn.getMessage(); extractGeometry(_ctx, geometry); break; // None.. skip default: _featureIn.skip(); break; } } _out.props = std::move(_ctx.properties); switch(_out.geometryType) { case GeometryType::points: _out.points.insert(_out.points.begin(), _ctx.coordinates.begin(), _ctx.coordinates.end()); break; case GeometryType::lines: case GeometryType::polygons: { std::vector<Line> lines; int offset = 0; lines.reserve(_ctx.numCoordinates.size()); for (int length : _ctx.numCoordinates) { if (length == 0) { continue; } lines.emplace_back(); auto& line = lines.back(); line.reserve(length); line.insert(line.begin(), _ctx.coordinates.begin() + offset, _ctx.coordinates.begin() + offset + length); offset += length; } if (_out.geometryType == GeometryType::lines) { _out.lines = std::move(lines); } else { _out.polygons.push_back(std::move(lines)); } break; } case GeometryType::unknown: break; default: break; } } void PbfParser::extractLayer(ParserContext& _ctx, protobuf::message& _layerIn, Layer& _out) { _ctx.keys.clear(); _ctx.values.clear(); _ctx.featureMsgs.clear(); //iterate layer to populate featureMsgs, keys and values while(_layerIn.next()) { switch(_layerIn.tag) { case 2: // features { _ctx.featureMsgs.push_back(_layerIn.getMessage()); break; } case 3: // key string { _ctx.keys.push_back(_layerIn.string()); break; } case 4: // values { protobuf::message valueItr = _layerIn.getMessage(); while (valueItr.next()) { switch (valueItr.tag) { case 1: // string value _ctx.values.push_back(valueItr.string()); break; case 2: // float value _ctx.values.push_back(valueItr.float32()); break; case 3: // double value _ctx.values.push_back(valueItr.float64()); break; case 4: // int value _ctx.values.push_back(valueItr.int64()); break; case 5: // uint value _ctx.values.push_back(valueItr.varint()); break; case 6: // sint value _ctx.values.push_back(valueItr.int64()); break; case 7: // bool value _ctx.values.push_back(valueItr.boolean()); break; default: _ctx.values.push_back(none_type{}); valueItr.skip(); break; } } break; } case 5: //extent _ctx.tileExtent = static_cast<int>(_layerIn.int64()); break; default: // skip _layerIn.skip(); break; } } _out.features.reserve(_ctx.featureMsgs.size()); for(auto& featureMsg : _ctx.featureMsgs) { _out.features.emplace_back(); extractFeature(_ctx, featureMsg, _out.features.back()); } } } <commit_msg>move value string in pbf parser<commit_after>#include "pbfParser.h" #include "tile/tile.h" #include "platform.h" namespace Tangram { void PbfParser::extractGeometry(ParserContext& _ctx, protobuf::message& _geomIn) { pbfGeomCmd cmd = pbfGeomCmd::moveTo; uint32_t cmdRepeat = 0; double invTileExtent = (1.0/(double)_ctx.tileExtent); int64_t x = 0; int64_t y = 0; size_t numCoordinates = 0; while(_geomIn.getData() < _geomIn.getEnd()) { if(cmdRepeat == 0) { // get new command, lengh and parameters.. uint32_t cmdData = static_cast<uint32_t>(_geomIn.varint()); cmd = static_cast<pbfGeomCmd>(cmdData & 0x7); //first 3 bits of the cmdData cmdRepeat = cmdData >> 3; //last 5 bits } if(cmd == pbfGeomCmd::moveTo || cmd == pbfGeomCmd::lineTo) { // get parameters/points // if cmd is move then move to a new line/set of points and save this line if(cmd == pbfGeomCmd::moveTo) { if(_ctx.coordinates.size() > 0) { _ctx.numCoordinates.push_back(numCoordinates); } numCoordinates = 0; } x += _geomIn.svarint(); y += _geomIn.svarint(); // bring the points in -1 to 1 space Point p; p.x = invTileExtent * (double)(2 * x - _ctx.tileExtent); p.y = invTileExtent * (double)(_ctx.tileExtent - 2 * y); _ctx.coordinates.push_back(p); numCoordinates++; } else if(cmd == pbfGeomCmd::closePath) { // end of a polygon, push first point in this line as last and push line to poly _ctx.coordinates.push_back(_ctx.coordinates[_ctx.coordinates.size() - numCoordinates]); _ctx.numCoordinates.push_back(numCoordinates + 1); numCoordinates = 0; } cmdRepeat--; } // Enter the last line if (numCoordinates > 0) { _ctx.numCoordinates.push_back(numCoordinates); } } void PbfParser::extractFeature(ParserContext& _ctx, protobuf::message& _featureIn, Feature& _out) { //Iterate through this feature protobuf::message geometry; // By default data_ and end_ are nullptr _ctx.properties.clear(); _ctx.coordinates.clear(); _ctx.numCoordinates.clear(); while(_featureIn.next()) { switch(_featureIn.tag) { // Feature ID case 1: // ignored for now, also not used in json parsing _featureIn.skip(); break; // Feature tags (properties) case 2: { // extract tags message protobuf::message tagsMsg = _featureIn.getMessage(); while(tagsMsg) { std::size_t tagKey = tagsMsg.varint(); if(_ctx.keys.size() <= tagKey) { logMsg("ERROR: accessing out of bound key\n"); return; } if(!tagsMsg) { logMsg("ERROR: uneven number of feature tag ids\n"); return; } std::size_t valueKey = tagsMsg.varint(); if( _ctx.values.size() <= valueKey ) { logMsg("ERROR: accessing out of bound values\n"); return; } _ctx.properties.emplace_back(_ctx.keys[tagKey], _ctx.values[valueKey]); } break; } // Feature Type case 3: _out.geometryType = (GeometryType)_featureIn.varint(); break; // Actual geometry data case 4: geometry = _featureIn.getMessage(); extractGeometry(_ctx, geometry); break; // None.. skip default: _featureIn.skip(); break; } } _out.props = std::move(_ctx.properties); switch(_out.geometryType) { case GeometryType::points: _out.points.insert(_out.points.begin(), _ctx.coordinates.begin(), _ctx.coordinates.end()); break; case GeometryType::lines: case GeometryType::polygons: { std::vector<Line> lines; int offset = 0; lines.reserve(_ctx.numCoordinates.size()); for (int length : _ctx.numCoordinates) { if (length == 0) { continue; } lines.emplace_back(); auto& line = lines.back(); line.reserve(length); line.insert(line.begin(), _ctx.coordinates.begin() + offset, _ctx.coordinates.begin() + offset + length); offset += length; } if (_out.geometryType == GeometryType::lines) { _out.lines = std::move(lines); } else { _out.polygons.push_back(std::move(lines)); } break; } case GeometryType::unknown: break; default: break; } } void PbfParser::extractLayer(ParserContext& _ctx, protobuf::message& _layerIn, Layer& _out) { _ctx.keys.clear(); _ctx.values.clear(); _ctx.featureMsgs.clear(); //iterate layer to populate featureMsgs, keys and values while(_layerIn.next()) { switch(_layerIn.tag) { case 2: // features { _ctx.featureMsgs.push_back(_layerIn.getMessage()); break; } case 3: // key string { _ctx.keys.push_back(_layerIn.string()); break; } case 4: // values { protobuf::message valueItr = _layerIn.getMessage(); while (valueItr.next()) { switch (valueItr.tag) { case 1: // string value _ctx.values.push_back(std::move(valueItr.string())); break; case 2: // float value _ctx.values.push_back(valueItr.float32()); break; case 3: // double value _ctx.values.push_back(valueItr.float64()); break; case 4: // int value _ctx.values.push_back(valueItr.int64()); break; case 5: // uint value _ctx.values.push_back(valueItr.varint()); break; case 6: // sint value _ctx.values.push_back(valueItr.int64()); break; case 7: // bool value _ctx.values.push_back(valueItr.boolean()); break; default: _ctx.values.push_back(none_type{}); valueItr.skip(); break; } } break; } case 5: //extent _ctx.tileExtent = static_cast<int>(_layerIn.int64()); break; default: // skip _layerIn.skip(); break; } } _out.features.reserve(_ctx.featureMsgs.size()); for(auto& featureMsg : _ctx.featureMsgs) { _out.features.emplace_back(); extractFeature(_ctx, featureMsg, _out.features.back()); } } } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file implements the ViewGLContext and PbufferGLContext classes. #include <dlfcn.h> #include <GL/glew.h> #include <GL/glxew.h> #include <GL/glx.h> #include <GL/osmew.h> #include <X11/Xlib.h> #include <X11/Xutil.h> #include "app/x11_util.h" #include "base/logging.h" #include "base/scoped_ptr.h" #include "app/gfx/gl/gl_context.h" #include "app/gfx/gl/gl_context_osmesa.h" namespace gfx { typedef GLXContext GLContextHandle; typedef GLXPbuffer PbufferHandle; // This class is a wrapper around a GL context that renders directly to a // window. class ViewGLContext : public GLContext { public: explicit ViewGLContext(gfx::PluginWindowHandle window) : window_(window), context_(NULL) { DCHECK(window); } // Initializes the GL context. bool Initialize(bool multisampled); virtual void Destroy(); virtual bool MakeCurrent(); virtual bool IsCurrent(); virtual bool IsOffscreen(); virtual void SwapBuffers(); virtual gfx::Size GetSize(); virtual void* GetHandle(); private: gfx::PluginWindowHandle window_; GLContextHandle context_; DISALLOW_COPY_AND_ASSIGN(ViewGLContext); }; // This class is a wrapper around a GL context used for offscreen rendering. // It is initially backed by a 1x1 pbuffer. Use it to create an FBO to do useful // rendering. class PbufferGLContext : public GLContext { public: explicit PbufferGLContext() : context_(NULL), pbuffer_(0) { } // Initializes the GL context. bool Initialize(void* shared_handle); virtual void Destroy(); virtual bool MakeCurrent(); virtual bool IsCurrent(); virtual bool IsOffscreen(); virtual void SwapBuffers(); virtual gfx::Size GetSize(); virtual void* GetHandle(); private: GLContextHandle context_; PbufferHandle pbuffer_; DISALLOW_COPY_AND_ASSIGN(PbufferGLContext); }; // Backup context if Pbuffers (GLX 1.3) aren't supported. May run slower... class PixmapGLContext : public GLContext { public: explicit PixmapGLContext() : context_(NULL), pixmap_(0), glx_pixmap_(0) { } // Initializes the GL context. bool Initialize(void* shared_handle); virtual void Destroy(); virtual bool MakeCurrent(); virtual bool IsCurrent(); virtual bool IsOffscreen(); virtual void SwapBuffers(); virtual gfx::Size GetSize(); virtual void* GetHandle(); private: GLContextHandle context_; Pixmap pixmap_; GLXPixmap glx_pixmap_; DISALLOW_COPY_AND_ASSIGN(PixmapGLContext); }; // scoped_ptr functor for XFree(). Use as follows: // scoped_ptr_malloc<XVisualInfo, ScopedPtrXFree> foo(...); // where "XVisualInfo" is any X type that is freed with XFree. class ScopedPtrXFree { public: void operator()(void* x) const { ::XFree(x); } }; // Some versions of NVIDIA's GL libGL.so include a broken version of // dlopen/dlsym, and so linking it into chrome breaks it. So we dynamically // load it, and use glew to dynamically resolve symbols. // See http://code.google.com/p/chromium/issues/detail?id=16800 static bool InitializeOneOff() { static bool initialized = false; if (initialized) return true; osmewInit(); if (!OSMesaCreateContext) { void* handle = dlopen("libGL.so.1", RTLD_LAZY | RTLD_GLOBAL); if (!handle) { LOG(ERROR) << "Could not find libGL.so.1"; return false; } // Initializes context-independent parts of GLEW if (glxewInit() != GLEW_OK) { LOG(ERROR) << "glxewInit failed"; return false; } // glxewContextInit really only needs a display connection to // complete, and we don't want to have to create an OpenGL context // just to get access to GLX 1.3 entry points to create pbuffers. // We therefore added a glxewContextInitWithDisplay entry point. Display* display = x11_util::GetXDisplay(); if (glxewContextInitWithDisplay(display) != GLEW_OK) { LOG(ERROR) << "glxewContextInit failed"; return false; } } initialized = true; return true; } bool ViewGLContext::Initialize(bool multisampled) { if (multisampled) { DLOG(WARNING) << "Multisampling not implemented."; } Display* display = x11_util::GetXDisplay(); XWindowAttributes attributes; XGetWindowAttributes(display, window_, &attributes); XVisualInfo visual_info_template; visual_info_template.visualid = XVisualIDFromVisual(attributes.visual); int visual_info_count = 0; scoped_ptr_malloc<XVisualInfo, ScopedPtrXFree> visual_info_list( XGetVisualInfo(display, VisualIDMask, &visual_info_template, &visual_info_count)); DCHECK(visual_info_list.get()); DCHECK_GT(visual_info_count, 0); context_ = NULL; for (int i = 0; i < visual_info_count; ++i) { context_ = glXCreateContext(display, visual_info_list.get() + i, 0, True); if (context_) break; } if (!context_) { DLOG(ERROR) << "Couldn't create GL context."; return false; } if (!MakeCurrent()) { Destroy(); DLOG(ERROR) << "Couldn't make context current for initialization."; return false; } if (!InitializeGLEW()) { Destroy(); return false; } if (!InitializeCommon()) { Destroy(); return false; } return true; } void ViewGLContext::Destroy() { Display* display = x11_util::GetXDisplay(); Bool result = glXMakeCurrent(display, 0, 0); // glXMakeCurrent isn't supposed to fail when unsetting the context, unless // we have pending draws on an invalid window - which shouldn't be the case // here. DCHECK(result); if (context_) { glXDestroyContext(display, context_); context_ = NULL; } } bool ViewGLContext::MakeCurrent() { if (IsCurrent()) { return true; } Display* display = x11_util::GetXDisplay(); if (glXMakeCurrent(display, window_, context_) != True) { glXDestroyContext(display, context_); context_ = 0; DLOG(ERROR) << "Couldn't make context current."; return false; } return true; } bool ViewGLContext::IsCurrent() { return glXGetCurrentDrawable() == window_ && glXGetCurrentContext() == context_; } bool ViewGLContext::IsOffscreen() { return false; } void ViewGLContext::SwapBuffers() { Display* display = x11_util::GetXDisplay(); glXSwapBuffers(display, window_); } gfx::Size ViewGLContext::GetSize() { XWindowAttributes attributes; Display* display = x11_util::GetXDisplay(); XGetWindowAttributes(display, window_, &attributes); return gfx::Size(attributes.width, attributes.height); } void* ViewGLContext::GetHandle() { return context_; } GLContext* GLContext::CreateViewGLContext(gfx::PluginWindowHandle window, bool multisampled) { if (!InitializeOneOff()) return NULL; if (OSMesaCreateContext) { // TODO(apatrick): Support OSMesa rendering to a window on Linux. NOTREACHED() << "OSMesa rendering to a window is not yet implemented."; return NULL; } else { scoped_ptr<ViewGLContext> context(new ViewGLContext(window)); if (!context->Initialize(multisampled)) return NULL; return context.release(); } } bool PbufferGLContext::Initialize(void* shared_handle) { if (!glXChooseFBConfig || !glXCreateNewContext || !glXCreatePbuffer || !glXDestroyPbuffer) { DLOG(ERROR) << "Pbuffer support not available."; return false; } static const int config_attributes[] = { GLX_DRAWABLE_TYPE, GLX_PBUFFER_BIT, GLX_RENDER_TYPE, GLX_RGBA_BIT, GLX_DOUBLEBUFFER, 0, 0 }; Display* display = x11_util::GetXDisplay(); int nelements = 0; // TODO(kbr): figure out whether hardcoding screen to 0 is sufficient. scoped_ptr_malloc<GLXFBConfig, ScopedPtrXFree> config( glXChooseFBConfig(display, 0, config_attributes, &nelements)); if (!config.get()) { DLOG(ERROR) << "glXChooseFBConfig failed."; return false; } if (!nelements) { DLOG(ERROR) << "glXChooseFBConfig returned 0 elements."; return false; } context_ = glXCreateNewContext(display, config.get()[0], GLX_RGBA_TYPE, static_cast<GLContextHandle>(shared_handle), True); if (!context_) { DLOG(ERROR) << "glXCreateNewContext failed."; return false; } static const int pbuffer_attributes[] = { GLX_PBUFFER_WIDTH, 1, GLX_PBUFFER_HEIGHT, 1, 0 }; pbuffer_ = glXCreatePbuffer(display, config.get()[0], pbuffer_attributes); if (!pbuffer_) { Destroy(); DLOG(ERROR) << "glXCreatePbuffer failed."; return false; } if (!MakeCurrent()) { Destroy(); DLOG(ERROR) << "Couldn't make context current for initialization."; return false; } if (!InitializeGLEW()) { Destroy(); return false; } if (!InitializeCommon()) { Destroy(); return false; } return true; } void PbufferGLContext::Destroy() { Display* display = x11_util::GetXDisplay(); Bool result = glXMakeCurrent(display, 0, 0); // glXMakeCurrent isn't supposed to fail when unsetting the context, unless // we have pending draws on an invalid window - which shouldn't be the case // here. DCHECK(result); if (context_) { glXDestroyContext(display, context_); context_ = NULL; } if (pbuffer_) { glXDestroyPbuffer(display, pbuffer_); pbuffer_ = 0; } } bool PbufferGLContext::MakeCurrent() { if (IsCurrent()) { return true; } Display* display = x11_util::GetXDisplay(); if (glXMakeCurrent(display, pbuffer_, context_) != True) { glXDestroyContext(display, context_); context_ = NULL; DLOG(ERROR) << "Couldn't make context current."; return false; } return true; } bool PbufferGLContext::IsCurrent() { return glXGetCurrentDrawable() == pbuffer_ && glXGetCurrentContext() == context_; } bool PbufferGLContext::IsOffscreen() { return true; } void PbufferGLContext::SwapBuffers() { NOTREACHED() << "Attempted to call SwapBuffers on a pbuffer."; } gfx::Size PbufferGLContext::GetSize() { NOTREACHED() << "Should not be requesting size of this pbuffer."; return gfx::Size(1, 1); } void* PbufferGLContext::GetHandle() { return context_; } bool PixmapGLContext::Initialize(void* shared_handle) { DLOG(INFO) << "GL context: using pixmaps."; if (!glXChooseVisual || !glXCreateGLXPixmap || !glXDestroyGLXPixmap) { DLOG(ERROR) << "Pixmap support not available."; return false; } static int attributes[] = { GLX_RGBA, 0 }; Display* display = x11_util::GetXDisplay(); int screen = DefaultScreen(display); scoped_ptr_malloc<XVisualInfo, ScopedPtrXFree> visual_info( glXChooseVisual(display, screen, attributes)); if (!visual_info.get()) { DLOG(ERROR) << "glXChooseVisual failed."; return false; } context_ = glXCreateContext(display, visual_info.get(), static_cast<GLContextHandle>(shared_handle), True); if (!context_) { DLOG(ERROR) << "glXCreateContext failed."; return false; } pixmap_ = XCreatePixmap(display, RootWindow(display, screen), 1, 1, visual_info->depth); if (!pixmap_) { DLOG(ERROR) << "XCreatePixmap failed."; return false; } glx_pixmap_ = glXCreateGLXPixmap(display, visual_info.get(), pixmap_); if (!glx_pixmap_) { DLOG(ERROR) << "XCreatePixmap failed."; return false; } if (!MakeCurrent()) { Destroy(); DLOG(ERROR) << "Couldn't make context current for initialization."; return false; } if (!InitializeGLEW()) { Destroy(); return false; } if (!InitializeCommon()) { Destroy(); return false; } return true; } void PixmapGLContext::Destroy() { Display* display = x11_util::GetXDisplay(); Bool result = glXMakeCurrent(display, 0, 0); // glXMakeCurrent isn't supposed to fail when unsetting the context, unless // we have pending draws on an invalid window - which shouldn't be the case // here. DCHECK(result); if (context_) { glXDestroyContext(display, context_); context_ = NULL; } if (glx_pixmap_) { glXDestroyGLXPixmap(display, glx_pixmap_); glx_pixmap_ = 0; } if (pixmap_) { XFreePixmap(display, pixmap_); pixmap_ = 0; } } bool PixmapGLContext::MakeCurrent() { if (IsCurrent()) { return true; } Display* display = x11_util::GetXDisplay(); if (glXMakeCurrent(display, glx_pixmap_, context_) != True) { glXDestroyContext(display, context_); context_ = NULL; DLOG(ERROR) << "Couldn't make context current."; return false; } return true; } bool PixmapGLContext::IsCurrent() { return glXGetCurrentDrawable() == glx_pixmap_ && glXGetCurrentContext() == context_; } bool PixmapGLContext::IsOffscreen() { return true; } void PixmapGLContext::SwapBuffers() { NOTREACHED() << "Attempted to call SwapBuffers on a pixmap."; } gfx::Size PixmapGLContext::GetSize() { NOTREACHED() << "Should not be requesting size of this pixmap."; return gfx::Size(1, 1); } void* PixmapGLContext::GetHandle() { return context_; } GLContext* GLContext::CreateOffscreenGLContext(void* shared_handle) { if (!InitializeOneOff()) return NULL; if (OSMesaCreateContext) { scoped_ptr<OSMesaGLContext> context(new OSMesaGLContext); if (!context->Initialize(shared_handle)) return NULL; return context.release(); } else { scoped_ptr<PbufferGLContext> context(new PbufferGLContext); if (context->Initialize(shared_handle)) return context.release(); scoped_ptr<PixmapGLContext> context_pixmap(new PixmapGLContext); if (context_pixmap->Initialize(shared_handle)) return context_pixmap.release(); return NULL; } } } // namespace gfx <commit_msg>Changed DLOG to LOG in gl_context_linux.cc to get informative error messages even in release builds when WebGL initialization fails.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file implements the ViewGLContext and PbufferGLContext classes. #include <dlfcn.h> #include <GL/glew.h> #include <GL/glxew.h> #include <GL/glx.h> #include <GL/osmew.h> #include <X11/Xlib.h> #include <X11/Xutil.h> #include "app/x11_util.h" #include "base/logging.h" #include "base/scoped_ptr.h" #include "app/gfx/gl/gl_context.h" #include "app/gfx/gl/gl_context_osmesa.h" namespace gfx { typedef GLXContext GLContextHandle; typedef GLXPbuffer PbufferHandle; // This class is a wrapper around a GL context that renders directly to a // window. class ViewGLContext : public GLContext { public: explicit ViewGLContext(gfx::PluginWindowHandle window) : window_(window), context_(NULL) { DCHECK(window); } // Initializes the GL context. bool Initialize(bool multisampled); virtual void Destroy(); virtual bool MakeCurrent(); virtual bool IsCurrent(); virtual bool IsOffscreen(); virtual void SwapBuffers(); virtual gfx::Size GetSize(); virtual void* GetHandle(); private: gfx::PluginWindowHandle window_; GLContextHandle context_; DISALLOW_COPY_AND_ASSIGN(ViewGLContext); }; // This class is a wrapper around a GL context used for offscreen rendering. // It is initially backed by a 1x1 pbuffer. Use it to create an FBO to do useful // rendering. class PbufferGLContext : public GLContext { public: explicit PbufferGLContext() : context_(NULL), pbuffer_(0) { } // Initializes the GL context. bool Initialize(void* shared_handle); virtual void Destroy(); virtual bool MakeCurrent(); virtual bool IsCurrent(); virtual bool IsOffscreen(); virtual void SwapBuffers(); virtual gfx::Size GetSize(); virtual void* GetHandle(); private: GLContextHandle context_; PbufferHandle pbuffer_; DISALLOW_COPY_AND_ASSIGN(PbufferGLContext); }; // Backup context if Pbuffers (GLX 1.3) aren't supported. May run slower... class PixmapGLContext : public GLContext { public: explicit PixmapGLContext() : context_(NULL), pixmap_(0), glx_pixmap_(0) { } // Initializes the GL context. bool Initialize(void* shared_handle); virtual void Destroy(); virtual bool MakeCurrent(); virtual bool IsCurrent(); virtual bool IsOffscreen(); virtual void SwapBuffers(); virtual gfx::Size GetSize(); virtual void* GetHandle(); private: GLContextHandle context_; Pixmap pixmap_; GLXPixmap glx_pixmap_; DISALLOW_COPY_AND_ASSIGN(PixmapGLContext); }; // scoped_ptr functor for XFree(). Use as follows: // scoped_ptr_malloc<XVisualInfo, ScopedPtrXFree> foo(...); // where "XVisualInfo" is any X type that is freed with XFree. class ScopedPtrXFree { public: void operator()(void* x) const { ::XFree(x); } }; // Some versions of NVIDIA's GL libGL.so include a broken version of // dlopen/dlsym, and so linking it into chrome breaks it. So we dynamically // load it, and use glew to dynamically resolve symbols. // See http://code.google.com/p/chromium/issues/detail?id=16800 static bool InitializeOneOff() { static bool initialized = false; if (initialized) return true; osmewInit(); if (!OSMesaCreateContext) { void* handle = dlopen("libGL.so.1", RTLD_LAZY | RTLD_GLOBAL); if (!handle) { LOG(ERROR) << "Could not find libGL.so.1"; return false; } // Initializes context-independent parts of GLEW if (glxewInit() != GLEW_OK) { LOG(ERROR) << "glxewInit failed"; return false; } // glxewContextInit really only needs a display connection to // complete, and we don't want to have to create an OpenGL context // just to get access to GLX 1.3 entry points to create pbuffers. // We therefore added a glxewContextInitWithDisplay entry point. Display* display = x11_util::GetXDisplay(); if (glxewContextInitWithDisplay(display) != GLEW_OK) { LOG(ERROR) << "glxewContextInit failed"; return false; } } initialized = true; return true; } bool ViewGLContext::Initialize(bool multisampled) { if (multisampled) { LOG(WARNING) << "Multisampling not implemented."; } Display* display = x11_util::GetXDisplay(); XWindowAttributes attributes; XGetWindowAttributes(display, window_, &attributes); XVisualInfo visual_info_template; visual_info_template.visualid = XVisualIDFromVisual(attributes.visual); int visual_info_count = 0; scoped_ptr_malloc<XVisualInfo, ScopedPtrXFree> visual_info_list( XGetVisualInfo(display, VisualIDMask, &visual_info_template, &visual_info_count)); DCHECK(visual_info_list.get()); DCHECK_GT(visual_info_count, 0); context_ = NULL; for (int i = 0; i < visual_info_count; ++i) { context_ = glXCreateContext(display, visual_info_list.get() + i, 0, True); if (context_) break; } if (!context_) { LOG(ERROR) << "Couldn't create GL context."; return false; } if (!MakeCurrent()) { Destroy(); LOG(ERROR) << "Couldn't make context current for initialization."; return false; } if (!InitializeGLEW()) { Destroy(); return false; } if (!InitializeCommon()) { Destroy(); return false; } return true; } void ViewGLContext::Destroy() { Display* display = x11_util::GetXDisplay(); Bool result = glXMakeCurrent(display, 0, 0); // glXMakeCurrent isn't supposed to fail when unsetting the context, unless // we have pending draws on an invalid window - which shouldn't be the case // here. DCHECK(result); if (context_) { glXDestroyContext(display, context_); context_ = NULL; } } bool ViewGLContext::MakeCurrent() { if (IsCurrent()) { return true; } Display* display = x11_util::GetXDisplay(); if (glXMakeCurrent(display, window_, context_) != True) { glXDestroyContext(display, context_); context_ = 0; LOG(ERROR) << "Couldn't make context current."; return false; } return true; } bool ViewGLContext::IsCurrent() { return glXGetCurrentDrawable() == window_ && glXGetCurrentContext() == context_; } bool ViewGLContext::IsOffscreen() { return false; } void ViewGLContext::SwapBuffers() { Display* display = x11_util::GetXDisplay(); glXSwapBuffers(display, window_); } gfx::Size ViewGLContext::GetSize() { XWindowAttributes attributes; Display* display = x11_util::GetXDisplay(); XGetWindowAttributes(display, window_, &attributes); return gfx::Size(attributes.width, attributes.height); } void* ViewGLContext::GetHandle() { return context_; } GLContext* GLContext::CreateViewGLContext(gfx::PluginWindowHandle window, bool multisampled) { if (!InitializeOneOff()) return NULL; if (OSMesaCreateContext) { // TODO(apatrick): Support OSMesa rendering to a window on Linux. NOTREACHED() << "OSMesa rendering to a window is not yet implemented."; return NULL; } else { scoped_ptr<ViewGLContext> context(new ViewGLContext(window)); if (!context->Initialize(multisampled)) return NULL; return context.release(); } } bool PbufferGLContext::Initialize(void* shared_handle) { if (!glXChooseFBConfig || !glXCreateNewContext || !glXCreatePbuffer || !glXDestroyPbuffer) { LOG(ERROR) << "Pbuffer support not available."; return false; } static const int config_attributes[] = { GLX_DRAWABLE_TYPE, GLX_PBUFFER_BIT, GLX_RENDER_TYPE, GLX_RGBA_BIT, GLX_DOUBLEBUFFER, 0, 0 }; Display* display = x11_util::GetXDisplay(); int nelements = 0; // TODO(kbr): figure out whether hardcoding screen to 0 is sufficient. scoped_ptr_malloc<GLXFBConfig, ScopedPtrXFree> config( glXChooseFBConfig(display, 0, config_attributes, &nelements)); if (!config.get()) { LOG(ERROR) << "glXChooseFBConfig failed."; return false; } if (!nelements) { LOG(ERROR) << "glXChooseFBConfig returned 0 elements."; return false; } context_ = glXCreateNewContext(display, config.get()[0], GLX_RGBA_TYPE, static_cast<GLContextHandle>(shared_handle), True); if (!context_) { LOG(ERROR) << "glXCreateNewContext failed."; return false; } static const int pbuffer_attributes[] = { GLX_PBUFFER_WIDTH, 1, GLX_PBUFFER_HEIGHT, 1, 0 }; pbuffer_ = glXCreatePbuffer(display, config.get()[0], pbuffer_attributes); if (!pbuffer_) { Destroy(); LOG(ERROR) << "glXCreatePbuffer failed."; return false; } if (!MakeCurrent()) { Destroy(); LOG(ERROR) << "Couldn't make context current for initialization."; return false; } if (!InitializeGLEW()) { Destroy(); return false; } if (!InitializeCommon()) { Destroy(); return false; } return true; } void PbufferGLContext::Destroy() { Display* display = x11_util::GetXDisplay(); Bool result = glXMakeCurrent(display, 0, 0); // glXMakeCurrent isn't supposed to fail when unsetting the context, unless // we have pending draws on an invalid window - which shouldn't be the case // here. DCHECK(result); if (context_) { glXDestroyContext(display, context_); context_ = NULL; } if (pbuffer_) { glXDestroyPbuffer(display, pbuffer_); pbuffer_ = 0; } } bool PbufferGLContext::MakeCurrent() { if (IsCurrent()) { return true; } Display* display = x11_util::GetXDisplay(); if (glXMakeCurrent(display, pbuffer_, context_) != True) { glXDestroyContext(display, context_); context_ = NULL; LOG(ERROR) << "Couldn't make context current."; return false; } return true; } bool PbufferGLContext::IsCurrent() { return glXGetCurrentDrawable() == pbuffer_ && glXGetCurrentContext() == context_; } bool PbufferGLContext::IsOffscreen() { return true; } void PbufferGLContext::SwapBuffers() { NOTREACHED() << "Attempted to call SwapBuffers on a pbuffer."; } gfx::Size PbufferGLContext::GetSize() { NOTREACHED() << "Should not be requesting size of this pbuffer."; return gfx::Size(1, 1); } void* PbufferGLContext::GetHandle() { return context_; } bool PixmapGLContext::Initialize(void* shared_handle) { LOG(INFO) << "GL context: using pixmaps."; if (!glXChooseVisual || !glXCreateGLXPixmap || !glXDestroyGLXPixmap) { LOG(ERROR) << "Pixmap support not available."; return false; } static int attributes[] = { GLX_RGBA, 0 }; Display* display = x11_util::GetXDisplay(); int screen = DefaultScreen(display); scoped_ptr_malloc<XVisualInfo, ScopedPtrXFree> visual_info( glXChooseVisual(display, screen, attributes)); if (!visual_info.get()) { LOG(ERROR) << "glXChooseVisual failed."; return false; } context_ = glXCreateContext(display, visual_info.get(), static_cast<GLContextHandle>(shared_handle), True); if (!context_) { LOG(ERROR) << "glXCreateContext failed."; return false; } pixmap_ = XCreatePixmap(display, RootWindow(display, screen), 1, 1, visual_info->depth); if (!pixmap_) { LOG(ERROR) << "XCreatePixmap failed."; return false; } glx_pixmap_ = glXCreateGLXPixmap(display, visual_info.get(), pixmap_); if (!glx_pixmap_) { LOG(ERROR) << "XCreatePixmap failed."; return false; } if (!MakeCurrent()) { Destroy(); LOG(ERROR) << "Couldn't make context current for initialization."; return false; } if (!InitializeGLEW()) { Destroy(); return false; } if (!InitializeCommon()) { Destroy(); return false; } return true; } void PixmapGLContext::Destroy() { Display* display = x11_util::GetXDisplay(); Bool result = glXMakeCurrent(display, 0, 0); // glXMakeCurrent isn't supposed to fail when unsetting the context, unless // we have pending draws on an invalid window - which shouldn't be the case // here. DCHECK(result); if (context_) { glXDestroyContext(display, context_); context_ = NULL; } if (glx_pixmap_) { glXDestroyGLXPixmap(display, glx_pixmap_); glx_pixmap_ = 0; } if (pixmap_) { XFreePixmap(display, pixmap_); pixmap_ = 0; } } bool PixmapGLContext::MakeCurrent() { if (IsCurrent()) { return true; } Display* display = x11_util::GetXDisplay(); if (glXMakeCurrent(display, glx_pixmap_, context_) != True) { glXDestroyContext(display, context_); context_ = NULL; LOG(ERROR) << "Couldn't make context current."; return false; } return true; } bool PixmapGLContext::IsCurrent() { return glXGetCurrentDrawable() == glx_pixmap_ && glXGetCurrentContext() == context_; } bool PixmapGLContext::IsOffscreen() { return true; } void PixmapGLContext::SwapBuffers() { NOTREACHED() << "Attempted to call SwapBuffers on a pixmap."; } gfx::Size PixmapGLContext::GetSize() { NOTREACHED() << "Should not be requesting size of this pixmap."; return gfx::Size(1, 1); } void* PixmapGLContext::GetHandle() { return context_; } GLContext* GLContext::CreateOffscreenGLContext(void* shared_handle) { if (!InitializeOneOff()) return NULL; if (OSMesaCreateContext) { scoped_ptr<OSMesaGLContext> context(new OSMesaGLContext); if (!context->Initialize(shared_handle)) return NULL; return context.release(); } else { scoped_ptr<PbufferGLContext> context(new PbufferGLContext); if (context->Initialize(shared_handle)) return context.release(); scoped_ptr<PixmapGLContext> context_pixmap(new PixmapGLContext); if (context_pixmap->Initialize(shared_handle)) return context_pixmap.release(); return NULL; } } } // namespace gfx <|endoftext|>
<commit_before>#include <iostream> #include <cstdio> #include <algorithm> #include <queue> #include <map> #include <set> #include <stack> #include <cstring> #include <string> #include <vector> #include <iomanip> #include <cmath> #include <list> #include <bitset> using namespace std; #define ll long long #define lson l,mid,id<<1 #define rson mid+1,r,id<<1|1 typedef pair<int, int>pii; typedef pair<ll, ll>pll; typedef pair<double, double>pdd; const double eps = 1e-6; const ll LINF = 0x3f3f3f3f3f3f3f3fLL; const int INF = 0x3f3f3f3f; const double FINF = 1e18; #define x first #define y second #define REP(i,j,k) for(int i =(j);i<=(k);i++) #define REPD(i,j,k) for(int i =(j);i>=(k);i--) #define print(x) cout<<x<<endl; #define IOS ios::sync_with_stdio(0);cin.tie(0); int a[105][105]; int n; int dp[105][105]={0}; void Init(){ scanf("%d",&n); REP(i,1,n) REP(j,1,i){ scanf("%d",&a[i][j]); } return ; } void Solve(){ dp[0][0]=0; REPD(i,n,1) REP(j,1,i){ print(a[i][j]<<" "<<dp[i+1][j]<<" "<<dp[i+1][j-1]); dp[i][j]=a[i][j]+max(dp[i+1][j],dp[i+1][j-1]); } REP(i,1,n){ REP(j,1,n){ cout<<dp[i][j]<<"\t";} cout<<endl;} return ; } int main(){ freopen("hdu2084.in","r",stdin); int T; scanf("%d",&T); while(T--) Init(),Solve(); return 0; }<commit_msg>update hdu2084<commit_after>#include <iostream> #include <cstdio> #include <algorithm> #include <queue> #include <map> #include <set> #include <stack> #include <cstring> #include <string> #include <vector> #include <iomanip> #include <cmath> #include <list> #include <bitset> using namespace std; #define ll long long #define lson l,mid,id<<1 #define rson mid+1,r,id<<1|1 typedef pair<int, int>pii; typedef pair<ll, ll>pll; typedef pair<double, double>pdd; const double eps = 1e-6; const ll LINF = 0x3f3f3f3f3f3f3f3fLL; const int INF = 0x3f3f3f3f; const double FINF = 1e18; #define x first #define y second #define REP(i,j,k) for(int i =(j);i<=(k);i++) #define REPD(i,j,k) for(int i =(j);i>=(k);i--) #define print(x) cout<<x<<endl; #define IOS ios::sync_with_stdio(0);cin.tie(0); int a[105][105]; int n; int dp[105][105]={0}; void Init(){ scanf("%d",&n); REP(i,1,n) REP(j,1,i){ scanf("%d",&a[i][j]); } return ; } void Solve(){ dp[0][0]=0; REPD(i,n,1) REP(j,1,i){ print(a[i][j]<<" "<<dp[i+1][j]<<" "<<dp[i+1][j+1]); dp[i][j]=a[i][j]+max(dp[i+1][j],dp[i+1][j+1]); } REP(i,1,n){ REP(j,1,n){ cout<<dp[i][j]<<"\t";} cout<<endl;} return ; } int main(){ freopen("hdu2084.in","r",stdin); int T; scanf("%d",&T); while(T--) Init(),Solve(); return 0; }<|endoftext|>
<commit_before>#include "Runtime/CResFactory.hpp" #include "Runtime/CSimplePool.hpp" #include "Runtime/CStopwatch.hpp" namespace urde { static logvisor::Module Log("CResFactory"); void CResFactory::AddToLoadList(SLoadingData&& data) { const SObjectTag tag = data.x0_tag; m_loadMap.insert_or_assign(tag, m_loadList.insert(m_loadList.end(), std::move(data))); } CFactoryFnReturn CResFactory::BuildSync(const SObjectTag& tag, const CVParamTransfer& xfer, CObjectReference* selfRef) { CFactoryFnReturn ret; if (x5c_factoryMgr.CanMakeMemory(tag)) { std::unique_ptr<uint8_t[]> data; int size = 0; x4_loader.LoadMemResourceSync(tag, data, &size); if (size) ret = x5c_factoryMgr.MakeObjectFromMemory(tag, std::move(data), size, x4_loader.GetResourceCompression(tag), xfer, selfRef); else ret = std::make_unique<TObjOwnerDerivedFromIObjUntyped>(nullptr); } else { if (auto rp = x4_loader.LoadNewResourceSync(tag, nullptr)) ret = x5c_factoryMgr.MakeObject(tag, *rp, xfer, selfRef); else ret = std::make_unique<TObjOwnerDerivedFromIObjUntyped>(nullptr); } Log.report(logvisor::Warning, FMT_STRING("sync-built {}"), tag); return ret; } bool CResFactory::PumpResource(SLoadingData& data) { if (data.x8_dvdReq && data.x8_dvdReq->IsComplete()) { data.x8_dvdReq.reset(); *data.xc_targetPtr = x5c_factoryMgr.MakeObjectFromMemory(data.x0_tag, std::move(data.x10_loadBuffer), data.x14_resSize, data.m_compressed, data.x18_cvXfer, data.m_selfRef); Log.report(logvisor::Info, FMT_STRING("async-built {}"), data.x0_tag); return true; } return false; } std::unique_ptr<IObj> CResFactory::Build(const SObjectTag& tag, const CVParamTransfer& xfer, CObjectReference* selfRef) { auto search = m_loadMap.find(tag); if (search != m_loadMap.end()) { while (!PumpResource(*search->second) || !search->second->xc_targetPtr) {} std::unique_ptr<IObj> ret = std::move(*search->second->xc_targetPtr); m_loadList.erase(search->second); m_loadMap.erase(search); return ret; } return BuildSync(tag, xfer, selfRef); } void CResFactory::BuildAsync(const SObjectTag& tag, const CVParamTransfer& xfer, std::unique_ptr<IObj>* target, CObjectReference* selfRef) { auto search = m_loadMap.find(tag); if (search == m_loadMap.end()) { SLoadingData data(tag, target, xfer, x4_loader.GetResourceCompression(tag), selfRef); data.x14_resSize = x4_loader.ResourceSize(tag); if (data.x14_resSize) { data.x10_loadBuffer = std::unique_ptr<u8[]>(new u8[data.x14_resSize]); data.x8_dvdReq = x4_loader.LoadResourceAsync(tag, data.x10_loadBuffer.get()); AddToLoadList(std::move(data)); } else { *target = std::make_unique<TObjOwnerDerivedFromIObjUntyped>(nullptr); } } } void CResFactory::AsyncIdle() { if (m_loadList.empty()) return; auto startTime = std::chrono::steady_clock::now(); while (std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - startTime).count() < 2) { auto& task = m_loadList.front(); if (PumpResource(task)) { m_loadMap.erase(task.x0_tag); m_loadList.pop_front(); if (m_loadList.empty()) return; } } } void CResFactory::CancelBuild(const SObjectTag& tag) { auto search = m_loadMap.find(tag); if (search != m_loadMap.end()) { if (search->second->x8_dvdReq) search->second->x8_dvdReq->PostCancelRequest(); m_loadList.erase(search->second); m_loadMap.erase(search); } } void CResFactory::LoadPersistentResources(CSimplePool& sp) { const auto& paks = x4_loader.GetPaks(); for (auto it = paks.begin(); it != paks.end(); ++it) { if (!(*it)->IsWorldPak()) { for (const CAssetId& id : (*it)->GetDepList()) { SObjectTag tag(GetResourceTypeById(id), id); m_nonWorldTokens.push_back(sp.GetObj(tag)); m_nonWorldTokens.back().Lock(); } } } } } // namespace urde <commit_msg>Change CResFactory::AsyncIdle timeout to 5ms<commit_after>#include "Runtime/CResFactory.hpp" #include "Runtime/CSimplePool.hpp" #include "Runtime/CStopwatch.hpp" namespace urde { static logvisor::Module Log("CResFactory"); void CResFactory::AddToLoadList(SLoadingData&& data) { const SObjectTag tag = data.x0_tag; m_loadMap.insert_or_assign(tag, m_loadList.insert(m_loadList.end(), std::move(data))); } CFactoryFnReturn CResFactory::BuildSync(const SObjectTag& tag, const CVParamTransfer& xfer, CObjectReference* selfRef) { CFactoryFnReturn ret; if (x5c_factoryMgr.CanMakeMemory(tag)) { std::unique_ptr<uint8_t[]> data; int size = 0; x4_loader.LoadMemResourceSync(tag, data, &size); if (size) ret = x5c_factoryMgr.MakeObjectFromMemory(tag, std::move(data), size, x4_loader.GetResourceCompression(tag), xfer, selfRef); else ret = std::make_unique<TObjOwnerDerivedFromIObjUntyped>(nullptr); } else { if (auto rp = x4_loader.LoadNewResourceSync(tag, nullptr)) ret = x5c_factoryMgr.MakeObject(tag, *rp, xfer, selfRef); else ret = std::make_unique<TObjOwnerDerivedFromIObjUntyped>(nullptr); } Log.report(logvisor::Warning, FMT_STRING("sync-built {}"), tag); return ret; } bool CResFactory::PumpResource(SLoadingData& data) { if (data.x8_dvdReq && data.x8_dvdReq->IsComplete()) { data.x8_dvdReq.reset(); *data.xc_targetPtr = x5c_factoryMgr.MakeObjectFromMemory(data.x0_tag, std::move(data.x10_loadBuffer), data.x14_resSize, data.m_compressed, data.x18_cvXfer, data.m_selfRef); Log.report(logvisor::Info, FMT_STRING("async-built {}"), data.x0_tag); return true; } return false; } std::unique_ptr<IObj> CResFactory::Build(const SObjectTag& tag, const CVParamTransfer& xfer, CObjectReference* selfRef) { auto search = m_loadMap.find(tag); if (search != m_loadMap.end()) { while (!PumpResource(*search->second) || !search->second->xc_targetPtr) {} std::unique_ptr<IObj> ret = std::move(*search->second->xc_targetPtr); m_loadList.erase(search->second); m_loadMap.erase(search); return ret; } return BuildSync(tag, xfer, selfRef); } void CResFactory::BuildAsync(const SObjectTag& tag, const CVParamTransfer& xfer, std::unique_ptr<IObj>* target, CObjectReference* selfRef) { auto search = m_loadMap.find(tag); if (search == m_loadMap.end()) { SLoadingData data(tag, target, xfer, x4_loader.GetResourceCompression(tag), selfRef); data.x14_resSize = x4_loader.ResourceSize(tag); if (data.x14_resSize) { data.x10_loadBuffer = std::unique_ptr<u8[]>(new u8[data.x14_resSize]); data.x8_dvdReq = x4_loader.LoadResourceAsync(tag, data.x10_loadBuffer.get()); AddToLoadList(std::move(data)); } else { *target = std::make_unique<TObjOwnerDerivedFromIObjUntyped>(nullptr); } } } void CResFactory::AsyncIdle() { if (m_loadList.empty()) return; auto startTime = std::chrono::steady_clock::now(); while (std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - startTime).count() < 5) { auto& task = m_loadList.front(); if (PumpResource(task)) { m_loadMap.erase(task.x0_tag); m_loadList.pop_front(); if (m_loadList.empty()) return; } } } void CResFactory::CancelBuild(const SObjectTag& tag) { auto search = m_loadMap.find(tag); if (search != m_loadMap.end()) { if (search->second->x8_dvdReq) search->second->x8_dvdReq->PostCancelRequest(); m_loadList.erase(search->second); m_loadMap.erase(search); } } void CResFactory::LoadPersistentResources(CSimplePool& sp) { const auto& paks = x4_loader.GetPaks(); for (auto it = paks.begin(); it != paks.end(); ++it) { if (!(*it)->IsWorldPak()) { for (const CAssetId& id : (*it)->GetDepList()) { SObjectTag tag(GetResourceTypeById(id), id); m_nonWorldTokens.push_back(sp.GetObj(tag)); m_nonWorldTokens.back().Lock(); } } } } } // namespace urde <|endoftext|>
<commit_before><commit_msg>sw: RingContainer::merge(): assert that the Rings aren't already linked<commit_after><|endoftext|>
<commit_before>/* Copyright 2017 QReal Research Group * * 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 "pioneerStateMachineGenerator.h" #include <generatorBase/semanticTree/semanticNode.h> #include <generatorBase/semanticTree/simpleNode.h> using namespace pioneer::lua; using namespace generatorBase; using namespace generatorBase::semantics; PioneerStateMachineGenerator::PioneerStateMachineGenerator( const qrRepo::RepoApi &repo , qReal::ErrorReporterInterface &errorReporter , generatorBase::GeneratorCustomizer &customizer , generatorBase::PrimaryControlFlowValidator &validator , const qReal::Id &diagramId , QObject *parent , bool isThisDiagramMain) : GotoControlFlowGenerator(repo, errorReporter, customizer, validator, diagramId, parent, isThisDiagramMain) { mAsynchronousNodes << "GeoTakeoff" << "GeoLanding" << "GoToPoint"; } void PioneerStateMachineGenerator::registerNodeHook(std::function<void(const qReal::Id)> hook) { mNodeHooks.append(hook); } void PioneerStateMachineGenerator::performGeneration() { mSemanticTreeManager.reset(new SemanticTreeManager(*mSemanticTree, mErrorReporter, mErrorsOccured)); GotoControlFlowGenerator::performGeneration(); } void PioneerStateMachineGenerator::visitRegular(const qReal::Id &id, const QList<LinkInfo> &links) { // Base class method checks for subprogram calls, which is irrelevant for now, but does not hurt and hopefully // will be needed later. ControlFlowGeneratorBase::visitRegular(id, links); SimpleNode * const thisNode = static_cast<SimpleNode *>(mSemanticTree->findNodeFor(id)); SemanticNode *nextNode = nullptr; const qReal::Id target = links[0].target; if (mAsynchronousNodes.contains(id.element())) { if (mSemanticTree->findNodeFor(target)) { // thisNode is asyncronous node that transfers control to already visited node. // Generated code for thisNode will initiate asynchronous action and all we need to do is to generate // transition to a state which will execute target block when this block finishes its asynchronous // operation. nextNode = produceGotoNode(target); mSemanticTreeManager->addAfter(thisNode, nextNode); if (!mLabeledNodes.contains(target)) { // // Target node, despite being already visited, does not have a label, it means that it is a part of a // synchronous fragment. We copy that fragment from this node to the first asyncronous node and // label a start of the copied fragment. At the end of the fragment we will generate said asynchronous // node, which will initiate asynchronous operation, and then transition to its next state, which will // continue execution when operation is done. // // It will confuse "findNodeFor(id)" (there will be many semantic nodes for a block with given id), but // we actually do not care which copy will be used later, since they are the same. // nextNode = copySynchronousFragment(nextNode, target, true); } if (mSemanticTreeManager->isTopLevelNode(thisNode)) { SemanticNode * const endNode = produceEndOfHandlerNode(); mSemanticTreeManager->addAfter(nextNode, endNode); } } else { // thisNode is asynchronous node that transfers control to a node that has not been visited yet. Generating // transition into a state associated with that node and then a new handler for target node itself. nextNode = mSemanticTreeManager->produceLabeledNode(target); if (!nextNode) { return; } else { mLabeledNodes << nextNode->id(); } SemanticNode * const gotoNode = produceGotoNode(target); mSemanticTreeManager->addAfter(thisNode, gotoNode); // Labeled node can not be a part of a zone (i.e. "then" or "else" branch), it shall be generated in top // level zone. if (mSemanticTreeManager->isTopLevelNode(thisNode)) { SemanticNode * const endNode = produceEndOfHandlerNode(); mSemanticTreeManager->addAfter(gotoNode, endNode); mSemanticTreeManager->addAfter(endNode, nextNode); } else { // Getting parent node (i.e. If statement to the branch of which our node belongs). NonZoneNode *aParent = mSemanticTreeManager->parent(thisNode); while (!mSemanticTreeManager->isTopLevelNode(aParent)) { aParent = mSemanticTreeManager->parent(aParent); } // Skipping "end" that finishes handler with If. SemanticNode * const endOfHandler = mSemanticTreeManager->findSibling( aParent , [](SemanticNode *node){ return node->id().element() == "EndOfHandler"; }); if (!endOfHandler) { mErrorReporter.addError(tr("Can not find end of an If statement, generation internal error or " "too complex algorithmic construction.")); mErrorsOccured = true; return; } // Adding our labeled node denoting new handler after the end of a handler with If node. mSemanticTreeManager->addAfter(endOfHandler, nextNode); } } } else { if (!mSemanticTree->findNodeFor(target)) { // It is not an asynchronous node, generating as-is. nextNode = mSemanticTree->produceNodeFor(target); mSemanticTreeManager->addAfter(thisNode, nextNode); } else { // Synchronous node leading to already visited node. Need some copypasting of synchronous fragments, // or else we will stall the program waiting for an event that was never initiated. copySynchronousFragment(thisNode, target, false); } } } void PioneerStateMachineGenerator::visitConditional(const qReal::Id &id, const QList<LinkInfo> &links) { Q_UNUSED(links) const QPair<LinkInfo, LinkInfo> branches(ifBranchesFor(id)); const LinkInfo thenLink = branches.first; const LinkInfo elseLink = branches.second; IfNode * const thisNode = static_cast<IfNode *>(mSemanticTree->findNodeFor(id)); mSemanticTreeManager->addToZone(thisNode->thenZone(), thenLink.target); mSemanticTreeManager->addToZone(thisNode->elseZone(), elseLink.target); if (mSemanticTreeManager->isTopLevelNode(thisNode)) { SemanticNode * const endNode = produceEndOfHandlerNode(); mSemanticTreeManager->addAfter(thisNode, endNode); } } void PioneerStateMachineGenerator::visitFinal(const qReal::Id &id, const QList<LinkInfo> &links) { generatorBase::GotoControlFlowGenerator::visitFinal(id, links); // Here we are going to add finishing end-of-handler node in case it is missing (for example, diagrams like // "Initial Node" -> "Final Node" will not generate it automatically). // It is a kind of hack because asynchronous handler shall be a first-class entity and a zone node. SimpleNode * const thisNode = static_cast<SimpleNode *>(mSemanticTree->findNodeFor(id)); // Getting root node. NonZoneNode *aParent = mSemanticTreeManager->parent(thisNode); while (!mSemanticTreeManager->isTopLevelNode(aParent)) { aParent = mSemanticTreeManager->parent(aParent); } // Searching for end-of-handler node. SemanticNode * endOfHandler = mSemanticTreeManager->findSibling( aParent , [](SemanticNode *node){ return node->id().element() == "EndOfHandler"; }); if (!endOfHandler) { // If not found, create and add one. endOfHandler = produceEndOfHandlerNode(); mSemanticTreeManager->addAfter(thisNode, endOfHandler); } } void PioneerStateMachineGenerator::visit(const qReal::Id &nodeId, QList<utils::DeepFirstSearcher::LinkInfo> &links) { generatorBase::GotoControlFlowGenerator::visit(nodeId, links); for (const auto &hook : mNodeHooks) { hook(nodeId); } } SemanticNode *PioneerStateMachineGenerator::copySynchronousFragment( SemanticNode *after , const qReal::Id &from , bool withLabel) { NonZoneNode *oldTarget = dynamic_cast<NonZoneNode *>(mSemanticTree->findNodeFor(from)); if (!oldTarget) { /// @todo: actually, why not? mErrorReporter.addError(tr("Can not close a loop on algorithmic block.")); mErrorsOccured = true; return nullptr; } NonZoneNode *fragmentStartNode = withLabel ? mSemanticTreeManager->produceLabeledNode(from) : dynamic_cast<NonZoneNode *>(mSemanticTree->produceNodeFor(from)); if (!fragmentStartNode) { return nullptr; } else { mLabeledNodes << fragmentStartNode->id(); } if (!dynamic_cast<NonZoneNode *>(after)) { mErrorReporter.addError(tr("Generation internal error, non-zone node is a start of a fragment.")); mErrorsOccured = true; return nullptr; } // End-of-handler shall go before every labeled node, since label here is actually a start of a new handler. SemanticNode * const endNode = produceEndOfHandlerNode(); mSemanticTreeManager->addAfter(after, endNode); mSemanticTreeManager->addAfter(endNode, fragmentStartNode); if (isAsynchronous(fragmentStartNode)) { // Synchronous fragment is trivial and its first node is asynchronous. Generating transition from it and we're // done here. // // Using oldTarget because fragmentStartNode was just added and does not have siblings, but it is a copy // of oldTarget. const auto rightSibling = mSemanticTreeManager->findRightSibling(oldTarget); if (rightSibling) { auto gotoNode = produceGotoNode(rightSibling->id()); fragmentStartNode->appendSibling(gotoNode); return gotoNode; } else { mErrorReporter.addError(tr("Generation internal error, asynchronous fragment start node generation " \ "failed.")); mErrorsOccured = true; } return nullptr; } auto siblings = mSemanticTreeManager->copyRightSiblingsUntil( oldTarget , [this](SemanticNode * node){ return isAsynchronous(node); }); if (siblings.isEmpty()) { mErrorReporter.addError(tr("Loop can not be closed on a block that is last in its structural construct.")); mErrorsOccured = true; return nullptr; } if (isAsynchronous(siblings.last())) { // Synchronous fragment finished with asynchronous node fragmentStartNode->appendSiblings(siblings); // Now we shall look for the end of original fragment: find asynchronous node on which a fragment shall be // ending and get its target node. Assuming that they are already visited (here we assuming that it is a loop, // may not be the case when logical branching blocks will be introduced). auto asynchronousNode = mSemanticTreeManager->findSibling( oldTarget , [this](SemanticNode * node){ return isAsynchronous(node); }); const auto asynchronousNodeTarget = mSemanticTreeManager->findRightSibling(asynchronousNode); if (!asynchronousNodeTarget) { mErrorReporter.addError(tr("Generation internal error, asynchronous node does not have target node.")); mErrorsOccured = true; return nullptr; } auto gotoNode = produceGotoNode(asynchronousNodeTarget->id()); fragmentStartNode->appendSibling(gotoNode); return gotoNode; } else { mErrorReporter.addError(tr("Purely synchronous loops or If branches are not supported yet.")); mErrorsOccured = true; } return nullptr; } bool PioneerStateMachineGenerator::isAsynchronous(const SemanticNode * const node) const { return mAsynchronousNodes.contains(node->id().element()); } SemanticNode *PioneerStateMachineGenerator::produceEndOfHandlerNode() { qReal::Id syntheticId = qReal::Id::createElementId("synthetic", "synthetic", "EndOfHandler"); SimpleNode * const result = mSemanticTree->produceSimple(syntheticId); // No need for special handling, from the point of view of a generator it is just some simple node. result->bindToSyntheticConstruction(SimpleNode::noSytheticBinding); return result; } <commit_msg>If branches converging on final node are generating now<commit_after>/* Copyright 2017 QReal Research Group * * 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 "pioneerStateMachineGenerator.h" #include <generatorBase/semanticTree/semanticNode.h> #include <generatorBase/semanticTree/simpleNode.h> using namespace pioneer::lua; using namespace generatorBase; using namespace generatorBase::semantics; PioneerStateMachineGenerator::PioneerStateMachineGenerator( const qrRepo::RepoApi &repo , qReal::ErrorReporterInterface &errorReporter , generatorBase::GeneratorCustomizer &customizer , generatorBase::PrimaryControlFlowValidator &validator , const qReal::Id &diagramId , QObject *parent , bool isThisDiagramMain) : GotoControlFlowGenerator(repo, errorReporter, customizer, validator, diagramId, parent, isThisDiagramMain) { mAsynchronousNodes << "GeoTakeoff" << "GeoLanding" << "GoToPoint"; } void PioneerStateMachineGenerator::registerNodeHook(std::function<void(const qReal::Id)> hook) { mNodeHooks.append(hook); } void PioneerStateMachineGenerator::performGeneration() { mSemanticTreeManager.reset(new SemanticTreeManager(*mSemanticTree, mErrorReporter, mErrorsOccured)); GotoControlFlowGenerator::performGeneration(); } void PioneerStateMachineGenerator::visitRegular(const qReal::Id &id, const QList<LinkInfo> &links) { // Base class method checks for subprogram calls, which is irrelevant for now, but does not hurt and hopefully // will be needed later. ControlFlowGeneratorBase::visitRegular(id, links); SimpleNode * const thisNode = static_cast<SimpleNode *>(mSemanticTree->findNodeFor(id)); SemanticNode *nextNode = nullptr; const qReal::Id target = links[0].target; if (mAsynchronousNodes.contains(id.element())) { if (mSemanticTree->findNodeFor(target)) { // thisNode is asyncronous node that transfers control to already visited node. // Generated code for thisNode will initiate asynchronous action and all we need to do is to generate // transition to a state which will execute target block when this block finishes its asynchronous // operation. nextNode = produceGotoNode(target); mSemanticTreeManager->addAfter(thisNode, nextNode); if (!mLabeledNodes.contains(target)) { // // Target node, despite being already visited, does not have a label, it means that it is a part of a // synchronous fragment. We copy that fragment from this node to the first asyncronous node and // label a start of the copied fragment. At the end of the fragment we will generate said asynchronous // node, which will initiate asynchronous operation, and then transition to its next state, which will // continue execution when operation is done. // // It will confuse "findNodeFor(id)" (there will be many semantic nodes for a block with given id), but // we actually do not care which copy will be used later, since they are the same. // nextNode = copySynchronousFragment(nextNode, target, true); } if (mSemanticTreeManager->isTopLevelNode(thisNode)) { SemanticNode * const endNode = produceEndOfHandlerNode(); mSemanticTreeManager->addAfter(nextNode, endNode); } } else { // thisNode is asynchronous node that transfers control to a node that has not been visited yet. Generating // transition into a state associated with that node and then a new handler for target node itself. nextNode = mSemanticTreeManager->produceLabeledNode(target); if (!nextNode) { return; } else { mLabeledNodes << nextNode->id(); } SemanticNode * const gotoNode = produceGotoNode(target); mSemanticTreeManager->addAfter(thisNode, gotoNode); // Labeled node can not be a part of a zone (i.e. "then" or "else" branch), it shall be generated in top // level zone. if (mSemanticTreeManager->isTopLevelNode(thisNode)) { SemanticNode * const endNode = produceEndOfHandlerNode(); mSemanticTreeManager->addAfter(gotoNode, endNode); mSemanticTreeManager->addAfter(endNode, nextNode); } else { // Getting parent node (i.e. If statement to the branch of which our node belongs). NonZoneNode *aParent = mSemanticTreeManager->parent(thisNode); while (!mSemanticTreeManager->isTopLevelNode(aParent)) { aParent = mSemanticTreeManager->parent(aParent); } // Skipping "end" that finishes handler with If. SemanticNode * const endOfHandler = mSemanticTreeManager->findSibling( aParent , [](SemanticNode *node){ return node->id().element() == "EndOfHandler"; }); if (!endOfHandler) { mErrorReporter.addError(tr("Can not find end of an If statement, generation internal error or " "too complex algorithmic construction.")); mErrorsOccured = true; return; } // Adding our labeled node denoting new handler after the end of a handler with If node. mSemanticTreeManager->addAfter(endOfHandler, nextNode); } } } else { if (!mSemanticTree->findNodeFor(target)) { // It is not an asynchronous node, generating as-is. nextNode = mSemanticTree->produceNodeFor(target); mSemanticTreeManager->addAfter(thisNode, nextNode); } else { // Synchronous node leading to already visited node. Need some copypasting of synchronous fragments, // or else we will stall the program waiting for an event that was never initiated. copySynchronousFragment(thisNode, target, false); } } } void PioneerStateMachineGenerator::visitConditional(const qReal::Id &id, const QList<LinkInfo> &links) { Q_UNUSED(links) const QPair<LinkInfo, LinkInfo> branches(ifBranchesFor(id)); const LinkInfo thenLink = branches.first; const LinkInfo elseLink = branches.second; IfNode * const thisNode = static_cast<IfNode *>(mSemanticTree->findNodeFor(id)); mSemanticTreeManager->addToZone(thisNode->thenZone(), thenLink.target); mSemanticTreeManager->addToZone(thisNode->elseZone(), elseLink.target); if (mSemanticTreeManager->isTopLevelNode(thisNode)) { SemanticNode * const endNode = produceEndOfHandlerNode(); mSemanticTreeManager->addAfter(thisNode, endNode); } } void PioneerStateMachineGenerator::visitFinal(const qReal::Id &id, const QList<LinkInfo> &links) { generatorBase::GotoControlFlowGenerator::visitFinal(id, links); // Here we are going to add finishing end-of-handler node in case it is missing (for example, diagrams like // "Initial Node" -> "Final Node" will not generate it automatically). // It is a kind of hack because asynchronous handler shall be a first-class entity and a zone node. SimpleNode * const thisNode = static_cast<SimpleNode *>(mSemanticTree->findNodeFor(id)); // Getting root node. NonZoneNode *aParent = mSemanticTreeManager->parent(thisNode); while (!mSemanticTreeManager->isTopLevelNode(aParent)) { aParent = mSemanticTreeManager->parent(aParent); } // Searching for end-of-handler node. SemanticNode * endOfHandler = mSemanticTreeManager->findSibling( aParent , [](SemanticNode *node){ return node->id().element() == "EndOfHandler"; }); if (!endOfHandler) { // If not found, create and add one. endOfHandler = produceEndOfHandlerNode(); mSemanticTreeManager->addAfter(thisNode, endOfHandler); } } void PioneerStateMachineGenerator::visit(const qReal::Id &nodeId, QList<utils::DeepFirstSearcher::LinkInfo> &links) { generatorBase::GotoControlFlowGenerator::visit(nodeId, links); for (const auto &hook : mNodeHooks) { hook(nodeId); } } SemanticNode *PioneerStateMachineGenerator::copySynchronousFragment( SemanticNode *after , const qReal::Id &from , bool withLabel) { NonZoneNode *oldTarget = dynamic_cast<NonZoneNode *>(mSemanticTree->findNodeFor(from)); if (!oldTarget) { /// @todo: actually, why not? mErrorReporter.addError(tr("Can not close a loop on algorithmic block.")); mErrorsOccured = true; return nullptr; } NonZoneNode *fragmentStartNode = withLabel ? mSemanticTreeManager->produceLabeledNode(from) : dynamic_cast<NonZoneNode *>(mSemanticTree->produceNodeFor(from)); if (!fragmentStartNode) { return nullptr; } else { mLabeledNodes << fragmentStartNode->id(); } if (!dynamic_cast<NonZoneNode *>(after)) { mErrorReporter.addError(tr("Generation internal error, non-zone node is a start of a fragment.")); mErrorsOccured = true; return nullptr; } if (withLabel) { // End-of-handler shall go before every labeled node, since label here is actually a start of a new handler. SemanticNode * const endNode = produceEndOfHandlerNode(); mSemanticTreeManager->addAfter(after, endNode); mSemanticTreeManager->addAfter(endNode, fragmentStartNode); } else { mSemanticTreeManager->addAfter(after, fragmentStartNode); } if (isAsynchronous(fragmentStartNode)) { // Synchronous fragment is trivial and its first node is asynchronous. Generating transition from it and we're // done here. // // Using oldTarget because fragmentStartNode was just added and does not have siblings, but it is a copy // of oldTarget. const auto rightSibling = mSemanticTreeManager->findRightSibling(oldTarget); if (rightSibling) { auto gotoNode = produceGotoNode(rightSibling->id()); fragmentStartNode->appendSibling(gotoNode); return gotoNode; } else { mErrorReporter.addError(tr("Generation internal error, asynchronous fragment start node generation " \ "failed.")); mErrorsOccured = true; } return nullptr; } auto siblings = mSemanticTreeManager->copyRightSiblingsUntil( oldTarget , [this](SemanticNode * node){ return isAsynchronous(node); }); if (siblings.isEmpty()) { // Fragment is trivial and non-asynchronous --- so it must be FinalNode. Fine, no need to copy it. if (fragmentStartNode->id().element() != "FinalNode") { mErrorReporter.addError(tr("Generation internal error, program ends abruptly.")); mErrorsOccured = true; return nullptr; } return fragmentStartNode; } if (isAsynchronous(siblings.last())) { // Synchronous fragment finished with asynchronous node fragmentStartNode->appendSiblings(siblings); // Now we shall look for the end of original fragment: find asynchronous node on which a fragment shall be // ending and get its target node. Assuming that they are already visited (here we assuming that it is a loop, // may not be the case when logical branching blocks will be introduced). auto asynchronousNode = mSemanticTreeManager->findSibling( oldTarget , [this](SemanticNode * node){ return isAsynchronous(node); }); const auto asynchronousNodeTarget = mSemanticTreeManager->findRightSibling(asynchronousNode); if (!asynchronousNodeTarget) { mErrorReporter.addError(tr("Generation internal error, asynchronous node does not have target node.")); mErrorsOccured = true; return nullptr; } auto gotoNode = produceGotoNode(asynchronousNodeTarget->id()); fragmentStartNode->appendSibling(gotoNode); return gotoNode; } else { mErrorReporter.addError(tr("Purely synchronous loops or If branches are not supported yet.")); mErrorsOccured = true; } return nullptr; } bool PioneerStateMachineGenerator::isAsynchronous(const SemanticNode * const node) const { return mAsynchronousNodes.contains(node->id().element()); } SemanticNode *PioneerStateMachineGenerator::produceEndOfHandlerNode() { qReal::Id syntheticId = qReal::Id::createElementId("synthetic", "synthetic", "EndOfHandler"); SimpleNode * const result = mSemanticTree->produceSimple(syntheticId); // No need for special handling, from the point of view of a generator it is just some simple node. result->bindToSyntheticConstruction(SimpleNode::noSytheticBinding); return result; } <|endoftext|>
<commit_before>/** * @file hud_fox.cpp * @brief Purpose: Contains methods to game class' management. * * MIT License * Copyright (c) 2017 MindScape * * https://github.com/TecProg2017-2/mindscape/blob/master/LICENSE.md */ #include "../include/hud_fox.hpp" #include "../engine/include/log.hpp" using namespace mindscape; /** * @brief Class Contructor. * * Sets Hud Fox's firsts informations (attributes' values). * (Hud Fox: Fox's health bar). * * @param name Hud Fox's name(name of the object). * @param position Hud Fox's coordinates in the game's map. * @param priority Hud Fox's priority in game's execution. * @return void. */ HudFox::HudFox( std::string name, std::pair<int, int> position, int priority) :engine::GameObject( name, position, priority, { //No engine Keyboard Event needed. } ) { initialize_animations(); initialize_audio_effects(); }; /** * @brief Initiates Hud Fox's sound effect. * * Sets sound effect of heart. * @return void. */ void HudFox::initialize_audio_effects() { DEBUG("Started"); /* Initiates sound effect */ engine::Audio * take_this_hp = nullptr; take_this_hp = new engine::Audio( "heart", "../assets/audios/effects_songs/mindscape_heart.wav", engine::Audio::CHUNK); /* Set duration of the sound effect and add component in game */ take_this_hp->set_duration(1); add_component(take_this_hp); DEBUG("Ended"); } /** * @brief Notifies Hud Fox of Fox's state. * * Verifies Fox's state and sets stars' animation depending of the quantity of * stars collected. * * @param game_object Object for observe game's situation, * in this case, the Fox. * @return void. */ void HudFox::notify(engine::Observable* game_object) { Fox* fox = nullptr; fox = dynamic_cast<Fox *>(game_object); if(fox) { /* If the fox exists */ bool give_hp = false; /*< Boolean. Boolean that defines if hp is being given or not */ give_hp = fox->get_animation_hud_fading(); engine::Animation* actual = NULL; actual = get_actual_animation(); if(actual == animations["three_star_fading"]) { /* If stars are fading */ if(actual->is_finished) { /* If stars already faded */ give_hp = false; fox->set_star_count(0); set_actual_animation(animations["zero_star"]); } else { /* Do nothing */ } } else { /* If the animation is not stars fading */ int count = 0; /*< Integer. Number of stars */ count = fox->get_star_count(); if(count == 0) { /* If there are no stars */ if(!(get_actual_animation() == animations["zero_star"])) { set_actual_animation(animations["zero_star"]); } else { /* Do nothing */ } } else if(count == 1) { /* If there is one star */ if(!(get_actual_animation() == animations["one_star"])){ set_actual_animation(animations["one_star"]); } else { /* Do nothing */ } } else if(count == 2) { /* If there are two stars */ if(!(get_actual_animation() == animations["two_star"])) { set_actual_animation(animations["two_star"]); } else { /* Do nothing */ } } else if(count == 3 && !give_hp) { /* If there are three stars and is not giving hp */ if(!(get_actual_animation() == animations["three_star"])) { set_actual_animation(animations["three_star"]); } else { /* Do nothing */ } } else if(count == 3 && give_hp) { /* If there are three stars and is giving hp */ fox->set_animation_hud_fading(false); set_actual_animation(animations["three_star_fading"]); play_song("heart"); } else { /* Do nothing */ } } } else { /* Do nothing */ WARN("HudFox: Fox IS NULL"); } } /** * @brief Initiates Hud Fox's animation. * * Initiates all Hud Fox's sprites(images). * * @return void. */ void HudFox::initialize_animations() { DEBUG("Started"); engine::Animation* fox_zero_star = nullptr; fox_zero_star = create_animation( "../assets/images/sprites/hud/hud_fox_0.png", 1,1,0.9, "RIGHT" ); add_animation("zero_star", fox_zero_star); engine::Animation* fox_one_star = nullptr; fox_one_star = create_animation( "../assets/images/sprites/hud/hud_fox_1.png", 1,1,0.9, "RIGHT" ); add_animation("one_star", fox_one_star); engine::Animation* fox_two_star = nullptr; fox_two_star = create_animation( "../assets/images/sprites/hud/hud_fox_2.png", 1,1,0.9, "RIGHT" ); add_animation("two_star", fox_two_star); engine::Animation* fox_three_star = nullptr; fox_three_star = create_animation( "../assets/images/sprites/hud/hud_fox_3.png", 1,1,0.9, "RIGHT" ); add_animation("three_star", fox_three_star); engine::Animation* fox_three_star_fading = nullptr; fox_three_star_fading = create_animation( "../assets/images/sprites/hud/hud_fox_3_animation.png", 1,4,1.0, "RIGHT" ); fox_three_star_fading->in_loop = false; add_animation("three_star_fading", fox_three_star_fading); fox_zero_star->activate(); set_actual_animation(fox_zero_star); DEBUG("Ended"); } /** * @brief Creates Hud Fox's animation. * * Creates all Hud Fox's animation based on Hud Fox's sprites. * * @param image_path Path of the Hud Fox's sprite. * @param sprite_lines Line of the Hud Fox's sprite. * @warning Limitations of sprite_lines and sprite_columns are * 1 to the quantity of lines/columns in the image. * @param sprite_columns Column of the Fox's sprite needed. * @param duration Duration of the Hud Fox's image to show up. * @param direction Direction of the Hud Fox's image. * @return engine::Animation* The animation constructed. */ engine::Animation* HudFox::create_animation( std::string path, int sprite_lines, int sprite_columns, double duration, std::string direction) { DEBUG("Started"); engine::Game& game = engine::Game::get_instance(); engine::Animation* animation = nullptr; animation = new engine::Animation( game.get_renderer(), path, // is_active false, std::make_pair(0, 0), // priority 1, sprite_lines, sprite_columns, duration, // in_loop true, direction ); animation->set_values( std::make_pair(170, 78), std::make_pair(170, 78), std::make_pair(0, 0) ); DEBUG("Ended"); return animation; } <commit_msg>[CONSTANTS] Applies constants in Hud_Fox.cpp<commit_after>/** * @file hud_fox.cpp * @brief Purpose: Contains methods to game class' management. * * MIT License * Copyright (c) 2017 MindScape * * https://github.com/TecProg2017-2/mindscape/blob/master/LICENSE.md */ #include "../include/hud_fox.hpp" #include "../engine/include/log.hpp" using namespace mindscape; /** * @brief Class Contructor. * * Sets Hud Fox's firsts informations (attributes' values). * (Hud Fox: Fox's health bar). * * @param name Hud Fox's name(name of the object). * @param position Hud Fox's coordinates in the game's map. * @param priority Hud Fox's priority in game's execution. * @return void. */ HudFox::HudFox( std::string name, std::pair<int, int> position, int priority) :engine::GameObject( name, position, priority, { //No engine Keyboard Event needed. } ) { initialize_animations(); initialize_audio_effects(); }; /** * @brief Initiates Hud Fox's sound effect. * * Sets sound effect of heart. * @return void. */ void HudFox::initialize_audio_effects() { DEBUG("Started"); /* Initiates sound effect */ engine::Audio * take_this_hp = nullptr; take_this_hp = new engine::Audio( "heart", "../assets/audios/effects_songs/mindscape_heart.wav", engine::Audio::CHUNK); /* Set duration of the sound effect and add component in game */ const int sound_duration = 1; /**< Integer. Duration of the sound effect in seconds*/ take_this_hp->set_duration(sound_duration); add_component(take_this_hp); DEBUG("Ended"); } /** * @brief Notifies Hud Fox of Fox's state. * * Verifies Fox's state and sets stars' animation depending of the quantity of * stars collected. * * @param game_object Object for observe game's situation, * in this case, the Fox. * @return void. */ void HudFox::notify(engine::Observable* game_object) { Fox* fox = nullptr; fox = dynamic_cast<Fox *>(game_object); if(fox) { /* If the fox exists */ bool give_hp = false; /*< Boolean. Boolean that defines if hp is being given or not */ give_hp = fox->get_animation_hud_fading(); engine::Animation* actual = NULL; actual = get_actual_animation(); if(actual == animations["three_star_fading"]) { /* If stars are fading */ if(actual->is_finished) { /* If stars already faded */ give_hp = false; const int default_star_count = 0; /**< Integer. Default star count. Range 0-3*/ fox->set_star_count(default_star_count); set_actual_animation(animations["zero_star"]); } else { /* Do nothing */ } } else { /* If the animation is not stars fading */ int count = 0; /*< Integer. Number of stars */ count = fox->get_star_count(); if(count == 0) { /* If there are no stars */ if(!(get_actual_animation() == animations["zero_star"])) { set_actual_animation(animations["zero_star"]); } else { /* Do nothing */ } } else if(count == 1) { /* If there is one star */ if(!(get_actual_animation() == animations["one_star"])){ set_actual_animation(animations["one_star"]); } else { /* Do nothing */ } } else if(count == 2) { /* If there are two stars */ if(!(get_actual_animation() == animations["two_star"])) { set_actual_animation(animations["two_star"]); } else { /* Do nothing */ } } else if(count == 3 && !give_hp) { /* If there are three stars and is not giving hp */ if(!(get_actual_animation() == animations["three_star"])) { set_actual_animation(animations["three_star"]); } else { /* Do nothing */ } } else if(count == 3 && give_hp) { /* If there are three stars and is giving hp */ fox->set_animation_hud_fading(false); set_actual_animation(animations["three_star_fading"]); play_song("heart"); } else { /* Do nothing */ } } } else { /* Do nothing */ WARN("HudFox: Fox IS NULL"); } } /** * @brief Initiates Hud Fox's animation. * * Initiates all Hud Fox's sprites(images). * * @return void. */ void HudFox::initialize_animations() { DEBUG("Started"); const int default_sprite_line = 1; /**< Integer. Default sprite line, RANGE 1 */ const int default_sprite_column = 1; /**< Integer. Default sprite column, RANGE 1 */ const double default_animation_duration = 0.9; /**< Double. Default animation duration in seconds */ engine::Animation* fox_zero_star = nullptr; fox_zero_star = create_animation( "../assets/images/sprites/hud/hud_fox_0.png", default_sprite_line, default_sprite_column, default_animation_duration, "RIGHT" ); add_animation("zero_star", fox_zero_star); engine::Animation* fox_one_star = nullptr; fox_one_star = create_animation( "../assets/images/sprites/hud/hud_fox_1.png", default_sprite_line, default_sprite_column, default_animation_duration, "RIGHT" ); add_animation("one_star", fox_one_star); engine::Animation* fox_two_star = nullptr; fox_two_star = create_animation( "../assets/images/sprites/hud/hud_fox_2.png", default_sprite_line, default_sprite_column, default_animation_duration, "RIGHT" ); add_animation("two_star", fox_two_star); engine::Animation* fox_three_star = nullptr; fox_three_star = create_animation( "../assets/images/sprites/hud/hud_fox_3.png", default_sprite_line, default_sprite_column, default_animation_duration, "RIGHT" ); add_animation("three_star", fox_three_star); const int sprite_columns_tree_star = 4; /**< Default sprite column of tree star fading */ const double duration_tree_star = 1.0; /**< Default duration of tree star fading in seconds */ engine::Animation* fox_three_star_fading = nullptr; fox_three_star_fading = create_animation( "../assets/images/sprites/hud/hud_fox_3_animation.png", default_sprite_line, sprite_columns_tree_star, duration_tree_star, "RIGHT" ); fox_three_star_fading->in_loop = false; add_animation("three_star_fading", fox_three_star_fading); fox_zero_star->activate(); set_actual_animation(fox_zero_star); DEBUG("Ended"); } /** * @brief Creates Hud Fox's animation. * * Creates all Hud Fox's animation based on Hud Fox's sprites. * * @param image_path Path of the Hud Fox's sprite. * @param sprite_lines Line of the Hud Fox's sprite. * @warning Limitations of sprite_lines and sprite_columns are * 1 to the quantity of lines/columns in the image. * @param sprite_columns Column of the Fox's sprite needed. * @param duration Duration of the Hud Fox's image to show up. * @param direction Direction of the Hud Fox's image. * @return engine::Animation* The animation constructed. */ engine::Animation* HudFox::create_animation( std::string path, int sprite_lines, int sprite_columns, double duration, std::string direction) { DEBUG("Started"); engine::Game& game = engine::Game::get_instance(); /* Constants for default animation creation */ const bool default_is_active = false; const std::pair<int, int> default_displacement = std::make_pair(0, 0); const int default_priority = 1; const bool default_in_loop = true; engine::Animation* animation = nullptr; animation = new engine::Animation( game.get_renderer(), path, default_is_active, default_displacement, default_priority, sprite_lines, sprite_columns, duration, default_in_loop, direction ); /* Defaults dimensions and coordinates of hud fox in pixels */ const std::pair<int, int> default_dimensions_hud_fox = std::make_pair(170, 78); const std::pair<int, int> coordinates_on_texture_hud_fox = std::make_pair(0, 0); animation->set_values( default_dimensions_hud_fox, default_dimensions_hud_fox , coordinates_on_texture_hud_fox ); DEBUG("Ended"); return animation; } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/utils/stopreg/p9_stop_data_struct.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_stop_data_struct.H /// @brief describes data structures internal to STOP API. /// // *HWP HW Owner : Greg Still <stillgs@us.ibm.com> // *HWP FW Owner : Prem Shanker Jha <premjha2@in.ibm.com> // *HWP Team : PM // *HWP Level : 2 // *HWP Consumed by : HB:HYP #ifndef __STOP_DATA_STRUCT_ #define __STOP_DATA_STRUCT_ #include "p9_hcd_memmap_base.H" #ifdef __SKIBOOT__ #include <skiboot.h> #endif #ifdef __FAPI_2_ #include <fapi2.H> #endif #ifdef PPC_HYP #define STATIC #else #define STATIC static #endif #ifdef __cplusplus extern "C" { namespace stopImageSection { #endif enum { MAX_SPR_RESTORE_INST = 0x08, SIZE_PER_SPR_RESTORE_INST = ((4 * sizeof(uint8_t)) / sizeof(uint32_t)), }; typedef struct { uint32_t scomEntryHeader; uint32_t scomEntryAddress; uint64_t scomEntryData; } ScomEntry_t; /** * @brief models a CPU register restoration area in STOP section of homer image. */ typedef struct { uint8_t threadArea[CORE_RESTORE_THREAD_AREA_SIZE]; uint8_t coreArea[CORE_RESTORE_CORE_AREA_SIZE]; } SprRestoreArea_t; /** * @brief models homer image of a chip. * @note sections not relevant for CPU register restoration have been * abstracted using field 'reserve'. */ typedef struct { uint8_t occ_host_sgpe_area[ TWO_MB ]; // CPU restore area starts at an offset of 2MB from chip HOMER uint8_t interrruptHandler[SELF_RESTORE_INT_SIZE]; uint8_t threadLauncher[THREAD_LAUNCHER_SIZE]; SprRestoreArea_t coreThreadRestore[MAX_CORES_PER_CHIP][MAX_THREADS_PER_CORE]; uint8_t reserve[(ONE_KB * ONE_KB) - SELF_RESTORE_SIZE_TOTAL]; } HomerSection_t; /** * @brief models cache subsection in STOP section of a given homer image. * @note given the start of cache subsection associated with a given core, * the structure below represents what a cache subsection would look * like. Based on known start address, quick traversing can be done * within the cache subsection. */ typedef struct { ScomEntry_t nonCacheArea[MAX_EQ_SCOM_ENTRIES]; ScomEntry_t l2CacheArea[MAX_L2_SCOM_ENTRIES]; ScomEntry_t l3CacheArea[MAX_L3_SCOM_ENTRIES]; } StopCacheSection_t; /** * @brief summarizes attributes associated with a SPR register. */ typedef struct { uint32_t sprId; bool isThreadScope; } StopSprReg_t; enum { SIZE_SCOM_ENTRY = sizeof( ScomEntry_t ), SCOM_ENTRY_START = 0xDEADDEAD, }; #ifdef __FAPI_2_ #define MY_ERR( _fmt_, _args_...) FAPI_ERR(_fmt_, ##_args_) #define MY_INF(_fmt_, _args_...) FAPI_INF(_fmt_, ##_args_) #else #define MY_ERR( _fmt_, _args_...) #define MY_INF(_fmt_, _args_...) #endif #define CORE_ID_SCOM_START(io_image,\ i_chipletId) \ ((ScomEntry_t*)(((uint8_t*)(io_image)) + CORE_SCOM_RESTORE_HOMER_OFFSET +\ ((i_chipletId - CORE_CHIPLET_ID_MIN) * \ CORE_SCOM_RESTORE_SIZE_PER_CORE))); #define CACHE_SECTN_START(io_image,\ i_chipletId) \ ((StopCacheSection_t *)(((uint8_t *)(io_image)) + QUAD_SCOM_RESTORE_HOMER_OFFSET +\ ((i_chipletId - CACHE_CHIPLET_ID_MIN) * \ QUAD_SCOM_RESTORE_SIZE_PER_QUAD))); #define CACHE_SCOM_ADDR(io_image,\ i_chipletId,\ i_maxScomEntry)\ ((ScomEntry_t *)(((uint8_t *)(io_image)) + QUAD_SCOM_RESTORE_HOMER_OFFSET +\ ((i_chipletId - CACHE_CHIPLET_ID_MIN) * \ ((i_maxScomEntry + 1) * 16 )))); #ifdef __cplusplus } // extern "C" } //namespace stopImageSection ends #endif //__cplusplus #endif <commit_msg>UV Support : Augmented STOP API and self restore for enabling ultravisor.<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/utils/stopreg/p9_stop_data_struct.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_stop_data_struct.H /// @brief describes data structures internal to STOP API. /// // *HWP HW Owner : Greg Still <stillgs@us.ibm.com> // *HWP FW Owner : Prem Shanker Jha <premjha2@in.ibm.com> // *HWP Team : PM // *HWP Level : 2 // *HWP Consumed by : HB:HYP #ifndef __STOP_DATA_STRUCT_ #define __STOP_DATA_STRUCT_ #include "p9_hcd_memmap_base.H" #ifdef __SKIBOOT__ #include <skiboot.h> #endif #ifdef __FAPI_2_ #include <fapi2.H> #endif #ifdef PPC_HYP #define STATIC #else #define STATIC static #endif #ifdef __cplusplus extern "C" { namespace stopImageSection { #endif enum { MAX_SPR_RESTORE_INST = 0x08, SIZE_PER_SPR_RESTORE_INST = ((4 * sizeof(uint8_t)) / sizeof(uint32_t)), MAX_THREAD_LEVEL_SPRS = 11, MAX_CORE_LEVEL_SPRS = 6, MAX_SPR_BIT_POS = 31, SPR_BIT_POS_8 = 8, SPR_BIT_POS_19 = 19, SPR_BIT_POS_25 = 25, SPR_BIT_POS_27 = 27, }; enum SprEntryUpdateMode { INIT_SPR_REGION = 0x01, UPDATE_SPR_ENTRY = 0x02, }; typedef struct { uint32_t scomEntryHeader; uint32_t scomEntryAddress; uint64_t scomEntryData; } ScomEntry_t; /** * @brief models a CPU register restoration area in STOP section of homer image. */ typedef struct { uint8_t iv_threadRestoreArea[MAX_THREADS_PER_CORE][CORE_RESTORE_THREAD_AREA_SIZE]; uint8_t iv_threadSaveArea[MAX_THREADS_PER_CORE][SELF_SAVE_THREAD_AREA_SIZE]; uint8_t iv_coreRestoreArea[CORE_RESTORE_CORE_AREA_SIZE]; uint8_t iv_coreSaveArea[CORE_SAVE_CORE_AREA_SIZE]; } SprRestoreArea_t; /** * @brief models homer image of a chip. * @note sections not relevant for CPU register restoration have been * abstracted using field 'reserve'. */ typedef struct { uint8_t iv_occ_host_sgpe_area[ TWO_MB ]; // CPU restore area starts at an offset of 2MB from chip HOMER uint8_t iv_interrruptHandler[SELF_RESTORE_INT_SIZE]; uint8_t iv_threadLauncher[THREAD_LAUNCHER_SIZE]; SprRestoreArea_t iv_coreThreadRestore[MAX_CORES_PER_CHIP]; uint8_t reserve[(ONE_KB * ONE_KB) - SELF_RESTORE_SIZE_TOTAL]; } HomerSection_t; /** * @brief models cache subsection in STOP section of a given homer image. * @note given the start of cache subsection associated with a given core, * the structure below represents what a cache subsection would look * like. Based on known start address, quick traversing can be done * within the cache subsection. */ typedef struct { ScomEntry_t nonCacheArea[MAX_EQ_SCOM_ENTRIES]; ScomEntry_t l2CacheArea[MAX_L2_SCOM_ENTRIES]; ScomEntry_t l3CacheArea[MAX_L3_SCOM_ENTRIES]; } StopCacheSection_t; /** * @brief summarizes attributes associated with a SPR register. */ typedef struct { uint32_t iv_sprId; bool iv_isThreadScope; uint32_t iv_saveMaskPos; } StopSprReg_t; enum { SIZE_SCOM_ENTRY = sizeof( ScomEntry_t ), SCOM_ENTRY_START = 0xDEADDEAD, BAD_SAVE_MASK = 0x007FF000, MAX_SPR_INDEX = 31, TEST_BIT_PATTERN = 0x80000000, }; #ifdef __FAPI_2_ #define MY_ERR( _fmt_, _args_...) FAPI_ERR(_fmt_, ##_args_) #define MY_INF(_fmt_, _args_...) FAPI_INF(_fmt_, ##_args_) #else #define MY_ERR( _fmt_, _args_...) #define MY_INF(_fmt_, _args_...) #endif #define CORE_ID_SCOM_START(io_image,\ i_chipletId) \ ((ScomEntry_t*)(((uint8_t*)(io_image)) + CORE_SCOM_RESTORE_HOMER_OFFSET +\ ((i_chipletId - CORE_CHIPLET_ID_MIN) * \ CORE_SCOM_RESTORE_SIZE_PER_CORE))); #define CACHE_SECTN_START(io_image,\ i_chipletId) \ ((StopCacheSection_t *)(((uint8_t *)(io_image)) + QUAD_SCOM_RESTORE_HOMER_OFFSET +\ ((i_chipletId - CACHE_CHIPLET_ID_MIN) * \ QUAD_SCOM_RESTORE_SIZE_PER_QUAD))); #define CACHE_SCOM_ADDR(io_image,\ i_chipletId,\ i_maxScomEntry)\ ((ScomEntry_t *)(((uint8_t *)(io_image)) + QUAD_SCOM_RESTORE_HOMER_OFFSET +\ ((i_chipletId - CACHE_CHIPLET_ID_MIN) * \ ((i_maxScomEntry + 1) * 16 )))); #ifdef __cplusplus } // extern "C" } //namespace stopImageSection ends #endif //__cplusplus #endif <|endoftext|>
<commit_before>#define BOOST_TEST_MAIN #define BOOST_TEST_DYN_LINK #include <sys/types.h> #include <sys/wait.h> #include <mutex> #include <thread> #include <boost/test/unit_test.hpp> #include "jml/arch/atomic_ops.h" #include "jml/arch/exception.h" #include "jml/arch/futex.h" #include "jml/arch/timers.h" #include "jml/utils/exc_assert.h" #include "jml/utils/string_functions.h" #include "soa/service/message_loop.h" #include "soa/service/runner.h" #include "soa/service/sink.h" #include "soa/types/date.h" #include <iostream> #include "runner_test.h" #include "signals.h" using namespace std; using namespace Datacratic; // #define BOOST_CHECK_EQUAL(x,y) { ExcCheckEqual((x), (y), ""); } struct _Init { _Init() { signal(SIGPIPE, SIG_IGN); } } myInit; #if 1 /* ensures that the basic callback system works */ BOOST_AUTO_TEST_CASE( test_runner_callbacks ) { BlockedSignals blockedSigs2(SIGCHLD); MessageLoop loop; RunnerTestHelperCommands commands; commands.sendOutput(true, "hello stdout"); commands.sendOutput(true, "hello stdout2"); commands.sendOutput(false, "hello stderr"); commands.sendExit(0); string receivedStdOut, expectedStdOut; string receivedStdErr, expectedStdErr; expectedStdOut = ("helper: ready\nhello stdout\nhello stdout2\n" "helper: exit with code 0\n"); expectedStdErr = "hello stderr\n"; int done = false; auto onTerminate = [&] (const Runner::RunResult & result) { done = true; ML::futex_wake(done); }; auto onStdOut = [&] (string && message) { // cerr << "received message on stdout: /" + message + "/" << endl; receivedStdOut += message; }; auto stdOutSink = make_shared<CallbackInputSink>(onStdOut); auto onStdErr = [&] (string && message) { // cerr << "received message on stderr: /" + message + "/" << endl; receivedStdErr += message; }; auto stdErrSink = make_shared<CallbackInputSink>(onStdErr); Runner runner; loop.addSource("runner", runner); loop.start(); auto & stdInSink = runner.getStdInSink(); runner.run({"build/x86_64/bin/runner_test_helper"}, onTerminate, stdOutSink, stdErrSink); for (const string & command: commands) { while (!stdInSink.write(string(command))) { ML::sleep(0.1); } } stdInSink.requestClose(); while (!done) { ML::futex_wait(done, false); } BOOST_CHECK_EQUAL(ML::hexify_string(receivedStdOut), ML::hexify_string(expectedStdOut)); BOOST_CHECK_EQUAL(ML::hexify_string(receivedStdErr), ML::hexify_string(expectedStdErr)); loop.shutdown(); } #endif #if 1 /* ensures that the returned status is properly set after termination */ BOOST_AUTO_TEST_CASE( test_runner_normal_exit ) { BlockedSignals blockedSigs(SIGCHLD); auto nullSink = make_shared<NullInputSink>(); /* normal termination, with code */ { MessageLoop loop; RunnerTestHelperCommands commands; commands.sendExit(123); Runner::RunResult result; auto onTerminate = [&] (const Runner::RunResult & newResult) { result = newResult; }; Runner runner; loop.addSource("runner", runner); loop.start(); auto & stdInSink = runner.getStdInSink(); runner.run({"build/x86_64/bin/runner_test_helper"}, onTerminate, nullSink, nullSink); for (const string & command: commands) { stdInSink.write(string(command)); } stdInSink.requestClose(); runner.waitTermination(); BOOST_CHECK_EQUAL(result.signaled, false); BOOST_CHECK_EQUAL(result.returnCode, 123); loop.shutdown(); } /* aborted termination, with signum */ { MessageLoop loop; RunnerTestHelperCommands commands; commands.sendAbort(); Runner::RunResult result; auto onTerminate = [&] (const Runner::RunResult & newResult) { result = newResult; }; Runner runner; loop.addSource("runner", runner); loop.start(); auto & stdInSink = runner.getStdInSink(); runner.run({"build/x86_64/bin/runner_test_helper"}, onTerminate, nullSink, nullSink); for (const string & command: commands) { stdInSink.write(string(command)); } stdInSink.requestClose(); runner.waitTermination(); BOOST_CHECK_EQUAL(result.signaled, true); BOOST_CHECK_EQUAL(result.returnCode, SIGABRT); loop.shutdown(); } } #endif #if 1 /* test the behaviour of the Runner class when attempting to launch a missing * executable, mostly mimicking bash */ BOOST_AUTO_TEST_CASE( test_runner_missing_exe ) { Runner::RunResult result; auto onTerminate = [&] (const Runner::RunResult & newResult) { result = newResult; }; /* running a program that does not exist */ { MessageLoop loop; Runner runner; loop.start(); loop.addSource("runner1", runner); runner.run({"/this/command/is/missing"}, onTerminate); runner.waitTermination(); BOOST_CHECK_EQUAL(result.signaled, false); BOOST_CHECK_EQUAL(result.returnCode, 127); loop.removeSource(&runner); loop.shutdown(); } /* running a non-executable but existing file */ { MessageLoop loop; Runner runner; loop.start(); loop.addSource("runner2", runner); runner.run({"/dev/null"}, onTerminate); runner.waitTermination(); BOOST_CHECK_EQUAL(result.signaled, false); BOOST_CHECK_EQUAL(result.returnCode, 126); loop.removeSource(&runner); loop.shutdown(); } /* running a non-executable but existing non-file */ { MessageLoop loop; Runner runner; loop.start(); loop.addSource("runner3", runner); runner.run({"/dev"}, onTerminate); runner.waitTermination(); BOOST_CHECK_EQUAL(result.signaled, false); BOOST_CHECK_EQUAL(result.returnCode, 126); loop.removeSource(&runner); loop.shutdown(); } } #endif #if 1 /* test the "execute" function */ BOOST_AUTO_TEST_CASE( test_runner_execute ) { string received; auto onStdOut = [&] (string && message) { received = move(message); }; auto stdOutSink = make_shared<CallbackInputSink>(onStdOut, nullptr); auto result = execute({"/bin/cat", "-"}, stdOutSink, nullptr, "hello callbacks"); BOOST_CHECK_EQUAL(received, "hello callbacks"); BOOST_CHECK_EQUAL(result.signaled, false); BOOST_CHECK_EQUAL(result.returnCode, 0); } #endif #if 1 /* perform multiple runs with the same Runner and ensures task-specific * components are properly segregated */ BOOST_AUTO_TEST_CASE( test_runner_cleanup ) { MessageLoop loop; Runner runner; loop.addSource("runner", runner); loop.start(); auto nullSink = make_shared<NullInputSink>(); auto performLoop = [&] (const string & loopData) { RunnerTestHelperCommands commands; commands.sendOutput(true, loopData); commands.sendExit(0); string expectedStdOut("helper: ready\n" + loopData + "\nhelper: exit with code 0\n"); string receivedStdOut; auto onStdOut = [&] (string && message) { // cerr << "received message on stdout: /" + message + "/" << endl; receivedStdOut += message; }; auto stdOutSink = make_shared<CallbackInputSink>(onStdOut); auto & stdInSink = runner.getStdInSink(); runner.run({"build/x86_64/bin/runner_test_helper"}, nullptr, stdOutSink, nullSink); for (const string & command: commands) { stdInSink.write(string(command)); } stdInSink.requestClose(); runner.waitTermination(); BOOST_CHECK_EQUAL(ML::hexify_string(receivedStdOut), ML::hexify_string(expectedStdOut)); }; for (int i = 0; i < 5; i++) { performLoop(to_string(i)); } loop.shutdown(); } #endif #if 1 /* Ensures that the output is received as soon as it is emitted, and not by * chunks. This is done by expecting different types of strings: a simple one * with a few chars, another one with two carriage returns and a third one * with 1024 chars. The test works by ensuring that all strings are received * one by one, with a relatively precise and constant delay of 1 second * between them. */ static void test_runner_no_output_delay_helper(bool stdout) { double delays[3]; int sizes[3]; int pos(stdout ? -1 : 0); shared_ptr<CallbackInputSink> stdOutSink(nullptr); shared_ptr<CallbackInputSink> stdErrSink(nullptr); Date start = Date::now(); Date last = start; auto onCapture = [&] (string && message) { Date now = Date::now(); if (pos > -1 && pos < 3) { /* skip "helper: ready" message */ delays[pos] = now.secondsSinceEpoch() - last.secondsSinceEpoch(); sizes[pos] = message.size(); } pos++; last = now; }; if (stdout) { stdOutSink.reset(new CallbackInputSink(onCapture)); } else { stdErrSink.reset(new CallbackInputSink(onCapture)); } RunnerTestHelperCommands commands; commands.sendSleep(10); commands.sendOutput(stdout, "first"); commands.sendSleep(10); commands.sendOutput(stdout, "second\nsecond"); commands.sendSleep(10); string third; for (int i = 0; i < 128; i++) { third += "abcdefgh"; } commands.sendOutput(stdout, third); commands.sendSleep(10); commands.sendExit(0); MessageLoop loop; Runner runner; loop.addSource("runner", runner); loop.start(); auto & stdInSink = runner.getStdInSink(); runner.run({"build/x86_64/bin/runner_test_helper"}, nullptr, stdOutSink, stdErrSink); for (const string & command: commands) { while (!stdInSink.write(string(command))) { ML::sleep(0.1); } } stdInSink.requestClose(); Date end = Date::now(); runner.waitTermination(); BOOST_CHECK_EQUAL(sizes[0], 6); BOOST_CHECK(delays[0] >= 0.9); BOOST_CHECK_EQUAL(sizes[1], 14); BOOST_CHECK(delays[1] >= 0.9); BOOST_CHECK_EQUAL(sizes[2], 1025); BOOST_CHECK(delays[2] >= 0.9); for (int i = 0; i < 3; i++) { ::fprintf(stderr, "%d: size: %d; delay: %f\n", i, sizes[i], delays[i]); } } BOOST_AUTO_TEST_CASE( test_runner_no_output_delay_stdout ) { test_runner_no_output_delay_helper(true); } BOOST_AUTO_TEST_CASE( test_runner_no_output_delay_stderr ) { test_runner_no_output_delay_helper(false); } #endif <commit_msg>Revert "runner_test: worked around timing issues causing test to hang when using the same MessageLoop"<commit_after>#define BOOST_TEST_MAIN #define BOOST_TEST_DYN_LINK #include <sys/types.h> #include <sys/wait.h> #include <mutex> #include <thread> #include <boost/test/unit_test.hpp> #include "jml/arch/atomic_ops.h" #include "jml/arch/exception.h" #include "jml/arch/futex.h" #include "jml/arch/timers.h" #include "jml/utils/exc_assert.h" #include "jml/utils/string_functions.h" #include "soa/service/message_loop.h" #include "soa/service/runner.h" #include "soa/service/sink.h" #include "soa/types/date.h" #include <iostream> #include "runner_test.h" #include "signals.h" using namespace std; using namespace Datacratic; // #define BOOST_CHECK_EQUAL(x,y) { ExcCheckEqual((x), (y), ""); } struct _Init { _Init() { signal(SIGPIPE, SIG_IGN); } } myInit; #if 1 /* ensures that the basic callback system works */ BOOST_AUTO_TEST_CASE( test_runner_callbacks ) { BlockedSignals blockedSigs2(SIGCHLD); MessageLoop loop; RunnerTestHelperCommands commands; commands.sendOutput(true, "hello stdout"); commands.sendOutput(true, "hello stdout2"); commands.sendOutput(false, "hello stderr"); commands.sendExit(0); string receivedStdOut, expectedStdOut; string receivedStdErr, expectedStdErr; expectedStdOut = ("helper: ready\nhello stdout\nhello stdout2\n" "helper: exit with code 0\n"); expectedStdErr = "hello stderr\n"; int done = false; auto onTerminate = [&] (const Runner::RunResult & result) { done = true; ML::futex_wake(done); }; auto onStdOut = [&] (string && message) { // cerr << "received message on stdout: /" + message + "/" << endl; receivedStdOut += message; }; auto stdOutSink = make_shared<CallbackInputSink>(onStdOut); auto onStdErr = [&] (string && message) { // cerr << "received message on stderr: /" + message + "/" << endl; receivedStdErr += message; }; auto stdErrSink = make_shared<CallbackInputSink>(onStdErr); Runner runner; loop.addSource("runner", runner); loop.start(); auto & stdInSink = runner.getStdInSink(); runner.run({"build/x86_64/bin/runner_test_helper"}, onTerminate, stdOutSink, stdErrSink); for (const string & command: commands) { while (!stdInSink.write(string(command))) { ML::sleep(0.1); } } stdInSink.requestClose(); while (!done) { ML::futex_wait(done, false); } BOOST_CHECK_EQUAL(ML::hexify_string(receivedStdOut), ML::hexify_string(expectedStdOut)); BOOST_CHECK_EQUAL(ML::hexify_string(receivedStdErr), ML::hexify_string(expectedStdErr)); loop.shutdown(); } #endif #if 1 /* ensures that the returned status is properly set after termination */ BOOST_AUTO_TEST_CASE( test_runner_normal_exit ) { BlockedSignals blockedSigs(SIGCHLD); auto nullSink = make_shared<NullInputSink>(); /* normal termination, with code */ { MessageLoop loop; RunnerTestHelperCommands commands; commands.sendExit(123); Runner::RunResult result; auto onTerminate = [&] (const Runner::RunResult & newResult) { result = newResult; }; Runner runner; loop.addSource("runner", runner); loop.start(); auto & stdInSink = runner.getStdInSink(); runner.run({"build/x86_64/bin/runner_test_helper"}, onTerminate, nullSink, nullSink); for (const string & command: commands) { stdInSink.write(string(command)); } stdInSink.requestClose(); runner.waitTermination(); BOOST_CHECK_EQUAL(result.signaled, false); BOOST_CHECK_EQUAL(result.returnCode, 123); loop.shutdown(); } /* aborted termination, with signum */ { MessageLoop loop; RunnerTestHelperCommands commands; commands.sendAbort(); Runner::RunResult result; auto onTerminate = [&] (const Runner::RunResult & newResult) { result = newResult; }; Runner runner; loop.addSource("runner", runner); loop.start(); auto & stdInSink = runner.getStdInSink(); runner.run({"build/x86_64/bin/runner_test_helper"}, onTerminate, nullSink, nullSink); for (const string & command: commands) { stdInSink.write(string(command)); } stdInSink.requestClose(); runner.waitTermination(); BOOST_CHECK_EQUAL(result.signaled, true); BOOST_CHECK_EQUAL(result.returnCode, SIGABRT); loop.shutdown(); } } #endif #if 1 /* test the behaviour of the Runner class when attempting to launch a missing * executable, mostly mimicking bash */ BOOST_AUTO_TEST_CASE( test_runner_missing_exe ) { MessageLoop loop; loop.start(); Runner::RunResult result; auto onTerminate = [&] (const Runner::RunResult & newResult) { result = newResult; }; /* running a program that does not exist */ { Runner runner; loop.addSource("runner1", runner); runner.run({"/this/command/is/missing"}, onTerminate); runner.waitTermination(); BOOST_CHECK_EQUAL(result.signaled, false); BOOST_CHECK_EQUAL(result.returnCode, 127); loop.removeSource(&runner); } /* running a non-executable but existing file */ { Runner runner; loop.addSource("runner2", runner); runner.run({"/dev/null"}, onTerminate); runner.waitTermination(); BOOST_CHECK_EQUAL(result.signaled, false); BOOST_CHECK_EQUAL(result.returnCode, 126); loop.removeSource(&runner); } /* running a non-executable but existing non-file */ { Runner runner; loop.addSource("runner2", runner); runner.run({"/dev"}, onTerminate); runner.waitTermination(); BOOST_CHECK_EQUAL(result.signaled, false); BOOST_CHECK_EQUAL(result.returnCode, 126); loop.removeSource(&runner); } loop.shutdown(); } #endif #if 1 /* test the "execute" function */ BOOST_AUTO_TEST_CASE( test_runner_execute ) { string received; auto onStdOut = [&] (string && message) { received = move(message); }; auto stdOutSink = make_shared<CallbackInputSink>(onStdOut, nullptr); auto result = execute({"/bin/cat", "-"}, stdOutSink, nullptr, "hello callbacks"); BOOST_CHECK_EQUAL(received, "hello callbacks"); BOOST_CHECK_EQUAL(result.signaled, false); BOOST_CHECK_EQUAL(result.returnCode, 0); } #endif #if 1 /* perform multiple runs with the same Runner and ensures task-specific * components are properly segregated */ BOOST_AUTO_TEST_CASE( test_runner_cleanup ) { MessageLoop loop; Runner runner; loop.addSource("runner", runner); loop.start(); auto nullSink = make_shared<NullInputSink>(); auto performLoop = [&] (const string & loopData) { RunnerTestHelperCommands commands; commands.sendOutput(true, loopData); commands.sendExit(0); string expectedStdOut("helper: ready\n" + loopData + "\nhelper: exit with code 0\n"); string receivedStdOut; auto onStdOut = [&] (string && message) { // cerr << "received message on stdout: /" + message + "/" << endl; receivedStdOut += message; }; auto stdOutSink = make_shared<CallbackInputSink>(onStdOut); auto & stdInSink = runner.getStdInSink(); runner.run({"build/x86_64/bin/runner_test_helper"}, nullptr, stdOutSink, nullSink); for (const string & command: commands) { stdInSink.write(string(command)); } stdInSink.requestClose(); runner.waitTermination(); BOOST_CHECK_EQUAL(ML::hexify_string(receivedStdOut), ML::hexify_string(expectedStdOut)); }; for (int i = 0; i < 5; i++) { performLoop(to_string(i)); } loop.shutdown(); } #endif #if 1 /* Ensures that the output is received as soon as it is emitted, and not by * chunks. This is done by expecting different types of strings: a simple one * with a few chars, another one with two carriage returns and a third one * with 1024 chars. The test works by ensuring that all strings are received * one by one, with a relatively precise and constant delay of 1 second * between them. */ static void test_runner_no_output_delay_helper(bool stdout) { double delays[3]; int sizes[3]; int pos(stdout ? -1 : 0); shared_ptr<CallbackInputSink> stdOutSink(nullptr); shared_ptr<CallbackInputSink> stdErrSink(nullptr); Date start = Date::now(); Date last = start; auto onCapture = [&] (string && message) { Date now = Date::now(); if (pos > -1 && pos < 3) { /* skip "helper: ready" message */ delays[pos] = now.secondsSinceEpoch() - last.secondsSinceEpoch(); sizes[pos] = message.size(); } pos++; last = now; }; if (stdout) { stdOutSink.reset(new CallbackInputSink(onCapture)); } else { stdErrSink.reset(new CallbackInputSink(onCapture)); } RunnerTestHelperCommands commands; commands.sendSleep(10); commands.sendOutput(stdout, "first"); commands.sendSleep(10); commands.sendOutput(stdout, "second\nsecond"); commands.sendSleep(10); string third; for (int i = 0; i < 128; i++) { third += "abcdefgh"; } commands.sendOutput(stdout, third); commands.sendSleep(10); commands.sendExit(0); MessageLoop loop; Runner runner; loop.addSource("runner", runner); loop.start(); auto & stdInSink = runner.getStdInSink(); runner.run({"build/x86_64/bin/runner_test_helper"}, nullptr, stdOutSink, stdErrSink); for (const string & command: commands) { while (!stdInSink.write(string(command))) { ML::sleep(0.1); } } stdInSink.requestClose(); Date end = Date::now(); runner.waitTermination(); BOOST_CHECK_EQUAL(sizes[0], 6); BOOST_CHECK(delays[0] >= 0.9); BOOST_CHECK_EQUAL(sizes[1], 14); BOOST_CHECK(delays[1] >= 0.9); BOOST_CHECK_EQUAL(sizes[2], 1025); BOOST_CHECK(delays[2] >= 0.9); for (int i = 0; i < 3; i++) { ::fprintf(stderr, "%d: size: %d; delay: %f\n", i, sizes[i], delays[i]); } } BOOST_AUTO_TEST_CASE( test_runner_no_output_delay_stdout ) { test_runner_no_output_delay_helper(true); } BOOST_AUTO_TEST_CASE( test_runner_no_output_delay_stderr ) { test_runner_no_output_delay_helper(false); } #endif <|endoftext|>
<commit_before>/*********************************************************************** Moses - factored phrase-based language decoder Copyright (C) 2006 University of Edinburgh This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #include <cassert> #include <limits> #include <iostream> #include <fstream> #include "LanguageModelRandLM.h" #include "FactorCollection.h" #include "Phrase.h" #include "InputFileStream.h" #include "StaticData.h" namespace Moses { using namespace std; bool LanguageModelRandLM::Load(const std::string &filePath, FactorType factorType, size_t nGramOrder) { cerr << "Loading LanguageModelRandLM..." << endl; FactorCollection &factorCollection = FactorCollection::Instance(); m_filePath = filePath; m_factorType = factorType; m_nGramOrder = nGramOrder; int cache_MB = 50; // increase cache size m_lm = randlm::RandLM::initRandLM(filePath, nGramOrder, cache_MB); assert(m_lm != NULL); // get special word ids m_oov_id = m_lm->getWordID(m_lm->getOOV()); CreateFactors(factorCollection); return true; } void LanguageModelRandLM::CreateFactors(FactorCollection &factorCollection) { // add factors which have randlm id // code copied & paste from SRI LM class. should do template function // first get all bf vocab in map std::map<size_t, randlm::WordID> randlm_ids_map; // map from factor id -> randlm id size_t maxFactorId = 0; // to create lookup vector later on for(std::map<randlm::Word, randlm::WordID>::const_iterator vIter = m_lm->vocabStart(); vIter != m_lm->vocabEnd(); vIter++){ // get word from randlm vocab and associate with (new) factor id size_t factorId=factorCollection.AddFactor(Output,m_factorType,vIter->first)->GetId(); randlm_ids_map[factorId] = vIter->second; maxFactorId = (factorId > maxFactorId) ? factorId : maxFactorId; } // add factors for BOS and EOS and store bf word ids size_t factorId; m_sentenceStart = factorCollection.AddFactor(Output, m_factorType, m_lm->getBOS()); factorId = m_sentenceStart->GetId(); maxFactorId = (factorId > maxFactorId) ? factorId : maxFactorId; m_sentenceStartArray[m_factorType] = m_sentenceStart; m_sentenceEnd = factorCollection.AddFactor(Output, m_factorType, m_lm->getEOS()); factorId = m_sentenceEnd->GetId(); maxFactorId = (factorId > maxFactorId) ? factorId : maxFactorId; m_sentenceEndArray[m_factorType] = m_sentenceEnd; // add to lookup vector in object m_randlm_ids_vec.resize(maxFactorId+1); // fill with OOV code fill(m_randlm_ids_vec.begin(), m_randlm_ids_vec.end(), m_oov_id); for (map<size_t, randlm::WordID>::const_iterator iter = randlm_ids_map.begin(); iter != randlm_ids_map.end() ; ++iter) m_randlm_ids_vec[iter->first] = iter->second; } randlm::WordID LanguageModelRandLM::GetLmID( const std::string &str ) const { return m_lm->getWordID(str); } float LanguageModelRandLM::GetValue(const vector<const Word*> &contextFactor, State* finalState) const { FactorType factorType = GetFactorType(); // set up context randlm::WordID ngram[MAX_NGRAM_SIZE]; int count = contextFactor.size(); for (int i = 0 ; i < count ; i++) { ngram[i] = GetLmID((*contextFactor[i])[factorType]); //std::cerr << m_lm->getWord(ngram[i]) << " "; } int found = 0; float logprob = FloorScore(TransformLMScore(m_lm->getProb(&ngram[0], count, &found, finalState))); //if (finalState) // std::cerr << " = " << logprob << "(" << *finalState << ", " <<")"<< std::endl; //else // std::cerr << " = " << logprob << std::endl; return logprob; } } <commit_msg>Changed white space to test effect on svn blame.<commit_after>/*********************************************************************** Moses - factored phrase-based language decoder Copyright (C) 2006 University of Edinburgh This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #include <cassert> #include <limits> #include <iostream> #include <fstream> #include "LanguageModelRandLM.h" #include "FactorCollection.h" #include "Phrase.h" #include "InputFileStream.h" #include "StaticData.h" namespace Moses { using namespace std; bool LanguageModelRandLM::Load(const std::string &filePath, FactorType factorType, size_t nGramOrder) { cerr << "Loading LanguageModelRandLM..." << endl; FactorCollection &factorCollection = FactorCollection::Instance(); m_filePath = filePath; m_factorType = factorType; m_nGramOrder = nGramOrder; int cache_MB = 50; // increase cache size m_lm = randlm::RandLM::initRandLM(filePath, nGramOrder, cache_MB); assert(m_lm != NULL); // get special word ids m_oov_id = m_lm->getWordID(m_lm->getOOV()); CreateFactors(factorCollection); return true; } void LanguageModelRandLM::CreateFactors(FactorCollection &factorCollection) { // add factors which have randlm id // code copied & paste from SRI LM class. should do template function // first get all bf vocab in map std::map<size_t, randlm::WordID> randlm_ids_map; // map from factor id -> randlm id size_t maxFactorId = 0; // to create lookup vector later on for(std::map<randlm::Word, randlm::WordID>::const_iterator vIter = m_lm->vocabStart(); vIter != m_lm->vocabEnd(); vIter++){ // get word from randlm vocab and associate with (new) factor id size_t factorId=factorCollection.AddFactor(Output,m_factorType,vIter->first)->GetId(); randlm_ids_map[factorId] = vIter->second; maxFactorId = (factorId > maxFactorId) ? factorId : maxFactorId; } // add factors for BOS and EOS and store bf word ids size_t factorId; m_sentenceStart = factorCollection.AddFactor(Output, m_factorType, m_lm->getBOS()); factorId = m_sentenceStart->GetId(); maxFactorId = (factorId > maxFactorId) ? factorId : maxFactorId; m_sentenceStartArray[m_factorType] = m_sentenceStart; m_sentenceEnd = factorCollection.AddFactor(Output, m_factorType, m_lm->getEOS()); factorId = m_sentenceEnd->GetId(); maxFactorId = (factorId > maxFactorId) ? factorId : maxFactorId; m_sentenceEndArray[m_factorType] = m_sentenceEnd; // add to lookup vector in object m_randlm_ids_vec.resize(maxFactorId+1); // fill with OOV code fill(m_randlm_ids_vec.begin(), m_randlm_ids_vec.end(), m_oov_id); for (map<size_t, randlm::WordID>::const_iterator iter = randlm_ids_map.begin(); iter != randlm_ids_map.end() ; ++iter) m_randlm_ids_vec[iter->first] = iter->second; } randlm::WordID LanguageModelRandLM::GetLmID( const std::string &str ) const { return m_lm->getWordID(str); } float LanguageModelRandLM::GetValue(const vector<const Word*> &contextFactor, State* finalState) const { FactorType factorType = GetFactorType(); // set up context randlm::WordID ngram[MAX_NGRAM_SIZE]; int count = contextFactor.size(); for (int i = 0 ; i < count ; i++) { ngram[i] = GetLmID((*contextFactor[i])[factorType]); //std::cerr << m_lm->getWord(ngram[i]) << " "; } int found = 0; float logprob = FloorScore(TransformLMScore(m_lm->getProb(&ngram[0], count, &found, finalState))); //if (finalState) // std::cerr << " = " << logprob << "(" << *finalState << ", " <<")"<< std::endl; //else // std::cerr << " = " << logprob << std::endl; return logprob; } } <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2013-2018 Baptiste Wicht. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <iostream> #include <fstream> #include <sstream> #include <unordered_map> #include "incomes.hpp" #include "accounts.hpp" #include "budget_exception.hpp" #include "args.hpp" #include "data.hpp" #include "guid.hpp" #include "config.hpp" #include "utils.hpp" #include "console.hpp" #include "earnings.hpp" #include "expenses.hpp" #include "writer.hpp" using namespace budget; namespace { static data_handler<income> incomes { "incomes", "incomes.data" }; } //end of anonymous namespace std::map<std::string, std::string> budget::income::get_params(){ std::map<std::string, std::string> params; params["input_id"] = budget::to_string(id); params["input_guid"] = guid; params["input_amount"] = budget::to_string(amount); params["input_since"] = budget::to_string(since); params["input_until"] = budget::to_string(until); return params; } void budget::incomes_module::load(){ load_incomes(); } void budget::incomes_module::unload(){ save_incomes(); } void budget::incomes_module::handle(const std::vector<std::string>& args){ console_writer w(std::cout); if(args.size() == 1){ show_incomes(w); } else { auto& subcommand = args[1]; if (subcommand == "show") { show_incomes(w); } else if (subcommand == "set") { budget::money amount; edit_money(amount, "Amount", not_negative_checker()); auto & new_income = budget::new_income(amount, true); std::cout << "Income " << new_income.id << " has been created" << std::endl; } else { throw budget_exception("Invalid subcommand \"" + subcommand + "\""); } } } void budget::show_incomes(budget::writer& w) { if (!incomes.size()) { w << title_begin << "No income " << add_button("incomes") << title_end; return; } w << title_begin << "Incomes " << add_button("incomes") << title_end; std::vector<std::string> columns = {"ID", "Amount", "Since", "Until", "Edit"}; std::vector<std::vector<std::string>> contents; for(auto& income : incomes.data){ contents.push_back({to_string(income.id), to_string(income.amount), to_string(income.since), to_string(income.until), "::edit::incomes::" + to_string(income.id)}); } w.display_table(columns, contents); } void budget::load_incomes(){ incomes.load(); } void budget::save_incomes(){ incomes.save(); } std::ostream& budget::operator<<(std::ostream& stream, const income& income){ return stream << income.id << ':' << income.guid << ':' << income.amount << ':' << to_string(income.since) << ':' << to_string(income.until); } void budget::operator>>(const std::vector<std::string>& parts, income& income){ bool random = config_contains("random"); income.id = to_number<size_t>(parts[0]); income.guid = parts[1]; income.since = from_string(parts[3]); income.until = from_string(parts[4]); if(random){ income.amount = budget::random_money(1000, 10000); } else { income.amount = parse_money(parts[2]); } } std::vector<income>& budget::all_incomes(){ return incomes.data; } void budget::set_incomes_changed(){ incomes.set_changed(); } void budget::set_incomes_next_id(size_t next_id){ incomes.next_id = next_id; } bool budget::income_exists(size_t id){ return incomes.exists(id); } void budget::income_delete(size_t id) { if (!incomes.exists(id)) { throw budget_exception("There are no income with id "); } incomes.remove(id); } income& budget::income_get(size_t id) { if (!incomes.exists(id)) { throw budget_exception("There are no income with id "); } return incomes[id]; } void budget::add_income(budget::income&& income){ incomes.add(std::forward<budget::income>(income)); } budget::money budget::get_base_income(){ auto today = budget::local_day(); return get_base_income(today); } budget::money budget::get_base_income(budget::date d){ // First, we try to get the base income from the incomes module for (auto & income : incomes) { if (income.since <= d && income.until >= d) { return income.amount; } } // Otherwise, we use the accounts budget::money income; for (auto& account : all_accounts(d.year(), d.month())) { income += account.amount; } return income; } budget::income & budget::new_income(budget::money amount, bool print){ budget::date d = budget::local_day(); budget::date since(d.year(), d.month(), 1); budget::date until = budget::date(2099,12,31); budget::income new_income; new_income.guid = generate_guid(); new_income.since = since; new_income.until = until; new_income.amount = amount; if (incomes.size()) { // Try to edit the income from the same month for (auto & income : incomes) { if (income.since == since && income.until == until) { income.amount = new_income.amount; if (incomes.edit(income)) { if (print) { std::cout << "Income " << income.id << " has been modified" << std::endl; } } return income; } } // Edit the previous income budget::date date = incomes.data.front().since; size_t id = incomes.data.front().id; for (auto & income : incomes) { if (income.since > date) { date = income.since; id = income.id; } } auto & previous_income = incomes[id]; previous_income.until = since - budget::days(1); if (incomes.edit(previous_income)) { if (print) { std::cout << "Income " << id << " has been modified" << std::endl; } } return previous_income; } auto id = incomes.add(std::move(new_income)); return incomes[id]; } <commit_msg>Display current income<commit_after>//======================================================================= // Copyright (c) 2013-2018 Baptiste Wicht. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <iostream> #include <fstream> #include <sstream> #include <unordered_map> #include "incomes.hpp" #include "accounts.hpp" #include "budget_exception.hpp" #include "args.hpp" #include "data.hpp" #include "guid.hpp" #include "config.hpp" #include "utils.hpp" #include "console.hpp" #include "earnings.hpp" #include "expenses.hpp" #include "writer.hpp" using namespace budget; namespace { static data_handler<income> incomes { "incomes", "incomes.data" }; } //end of anonymous namespace std::map<std::string, std::string> budget::income::get_params(){ std::map<std::string, std::string> params; params["input_id"] = budget::to_string(id); params["input_guid"] = guid; params["input_amount"] = budget::to_string(amount); params["input_since"] = budget::to_string(since); params["input_until"] = budget::to_string(until); return params; } void budget::incomes_module::load(){ load_incomes(); } void budget::incomes_module::unload(){ save_incomes(); } void budget::incomes_module::handle(const std::vector<std::string>& args){ console_writer w(std::cout); if(args.size() == 1){ show_incomes(w); } else { auto& subcommand = args[1]; if (subcommand == "show") { show_incomes(w); } else if (subcommand == "set") { budget::money amount; edit_money(amount, "Amount", not_negative_checker()); auto & new_income = budget::new_income(amount, true); std::cout << "Income " << new_income.id << " has been created" << std::endl; } else { throw budget_exception("Invalid subcommand \"" + subcommand + "\""); } } } void budget::show_incomes(budget::writer& w) { if (!incomes.size()) { w << title_begin << "No income " << add_button("incomes") << title_end; return; } w << title_begin << "Incomes " << add_button("incomes") << title_end; w << p_begin << "Current income: " << get_base_income() << " " << get_default_currency() << p_end; std::vector<std::string> columns = {"ID", "Amount", "Since", "Until", "Edit"}; std::vector<std::vector<std::string>> contents; for(auto& income : incomes.data){ contents.push_back({to_string(income.id), to_string(income.amount), to_string(income.since), to_string(income.until), "::edit::incomes::" + to_string(income.id)}); } w.display_table(columns, contents); } void budget::load_incomes(){ incomes.load(); } void budget::save_incomes(){ incomes.save(); } std::ostream& budget::operator<<(std::ostream& stream, const income& income){ return stream << income.id << ':' << income.guid << ':' << income.amount << ':' << to_string(income.since) << ':' << to_string(income.until); } void budget::operator>>(const std::vector<std::string>& parts, income& income){ bool random = config_contains("random"); income.id = to_number<size_t>(parts[0]); income.guid = parts[1]; income.since = from_string(parts[3]); income.until = from_string(parts[4]); if(random){ income.amount = budget::random_money(1000, 10000); } else { income.amount = parse_money(parts[2]); } } std::vector<income>& budget::all_incomes(){ return incomes.data; } void budget::set_incomes_changed(){ incomes.set_changed(); } void budget::set_incomes_next_id(size_t next_id){ incomes.next_id = next_id; } bool budget::income_exists(size_t id){ return incomes.exists(id); } void budget::income_delete(size_t id) { if (!incomes.exists(id)) { throw budget_exception("There are no income with id "); } incomes.remove(id); } income& budget::income_get(size_t id) { if (!incomes.exists(id)) { throw budget_exception("There are no income with id "); } return incomes[id]; } void budget::add_income(budget::income&& income){ incomes.add(std::forward<budget::income>(income)); } budget::money budget::get_base_income(){ auto today = budget::local_day(); return get_base_income(today); } budget::money budget::get_base_income(budget::date d){ // First, we try to get the base income from the incomes module for (auto & income : incomes) { if (income.since <= d && income.until >= d) { return income.amount; } } // Otherwise, we use the accounts budget::money income; for (auto& account : all_accounts(d.year(), d.month())) { income += account.amount; } return income; } budget::income & budget::new_income(budget::money amount, bool print){ budget::date d = budget::local_day(); budget::date since(d.year(), d.month(), 1); budget::date until = budget::date(2099,12,31); budget::income new_income; new_income.guid = generate_guid(); new_income.since = since; new_income.until = until; new_income.amount = amount; if (incomes.size()) { // Try to edit the income from the same month for (auto & income : incomes) { if (income.since == since && income.until == until) { income.amount = new_income.amount; if (incomes.edit(income)) { if (print) { std::cout << "Income " << income.id << " has been modified" << std::endl; } } return income; } } // Edit the previous income budget::date date = incomes.data.front().since; size_t id = incomes.data.front().id; for (auto & income : incomes) { if (income.since > date) { date = income.since; id = income.id; } } auto & previous_income = incomes[id]; previous_income.until = since - budget::days(1); if (incomes.edit(previous_income)) { if (print) { std::cout << "Income " << id << " has been modified" << std::endl; } } return previous_income; } auto id = incomes.add(std::move(new_income)); return incomes[id]; } <|endoftext|>
<commit_before>// ============================================================================= // This file is part of: // Dynamic Adaptive System for Hierarchical Multipole Methods (DASHMM) // // Copyright (c) 2015-2016, Trustees of Indiana University, // All rights reserved. // // DASHMM is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // DASHMM 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 DASHMM. If not, see <http://www.gnu.org/licenses/>. // // This software was created at the Indiana University Center for Research in // Extreme Scale Technologies (CREST). // ============================================================================= /// \file /// \brief Implemention of DASHMM initialization and finalization #include <hpx/hpx.h> #include <libhpx/libhpx.h> #include "dashmm/types.h" namespace dashmm { ReturnCode init(int *argc, char ***argv) { if (HPX_SUCCESS != hpx_init(argc, argv)) { return kRuntimeError; } if (libhpx_inst_tracer_active()) { libhpx_inst_phase_end(); } return kSuccess; } ReturnCode finalize() { hpx_finalize(); return kSuccess; } } // namespace dashmm <commit_msg>Protect against poor coding in HPX-5 instrumentation. init() now checks for DASHMM_INSTRUMENTATION before interacting with the instrumentation stuff at all.<commit_after>// ============================================================================= // This file is part of: // Dynamic Adaptive System for Hierarchical Multipole Methods (DASHMM) // // Copyright (c) 2015-2016, Trustees of Indiana University, // All rights reserved. // // DASHMM is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // DASHMM 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 DASHMM. If not, see <http://www.gnu.org/licenses/>. // // This software was created at the Indiana University Center for Research in // Extreme Scale Technologies (CREST). // ============================================================================= /// \file /// \brief Implemention of DASHMM initialization and finalization #include <hpx/hpx.h> #include <libhpx/libhpx.h> #include "dashmm/types.h" namespace dashmm { ReturnCode init(int *argc, char ***argv) { if (HPX_SUCCESS != hpx_init(argc, argv)) { return kRuntimeError; } #ifdef DASHMM_INSTRUMENTATION if (libhpx_inst_tracer_active()) { libhpx_inst_phase_end(); } #endif return kSuccess; } ReturnCode finalize() { hpx_finalize(); return kSuccess; } } // namespace dashmm <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/system/power/tray_power.h" #include "ash/shell.h" #include "ash/system/date/date_view.h" #include "ash/system/power/power_supply_status.h" #include "ash/system/tray/system_tray_delegate.h" #include "ash/system/tray/tray_constants.h" #include "base/string_number_conversions.h" #include "base/stringprintf.h" #include "base/utf_string_conversions.h" #include "grit/ash_strings.h" #include "grit/ui_resources.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkRect.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/image/image.h" #include "ui/gfx/size.h" #include "ui/base/l10n/l10n_util.h" #include "ui/views/controls/button/button.h" #include "ui/views/controls/button/text_button.h" #include "ui/views/controls/image_view.h" #include "ui/views/controls/label.h" #include "ui/views/layout/box_layout.h" #include "ui/views/view.h" #include "ui/views/widget/widget.h" #include "unicode/fieldpos.h" #include "unicode/fmtable.h" namespace ash { namespace internal { namespace { // Width and height of battery images. const int kBatteryImageHeight = 25; const int kBatteryImageWidth = 25; // Number of different power states. const int kNumPowerImages = 15; } namespace tray { // This view is used only for the tray. class PowerTrayView : public views::ImageView { public: PowerTrayView() { UpdateImage(); } virtual ~PowerTrayView() { } void UpdatePowerStatus(const PowerSupplyStatus& status) { supply_status_ = status; // Sanitize. if (supply_status_.battery_is_full) supply_status_.battery_percentage = 100.0; UpdateImage(); SetVisible(status.battery_is_present); } private: void UpdateImage() { SkBitmap image; gfx::Image all = ui::ResourceBundle::GetSharedInstance().GetImageNamed( IDR_AURA_UBER_TRAY_POWER_SMALL); int image_index = 0; if (supply_status_.battery_percentage >= 100) { image_index = kNumPowerImages - 1; } else if (!supply_status_.battery_is_present) { image_index = kNumPowerImages; } else { image_index = static_cast<int> ( supply_status_.battery_percentage / 100.0 * (kNumPowerImages - 1)); image_index = std::max(std::min(image_index, kNumPowerImages - 2), 0); } // TODO(mbolohan): Remove the 2px offset when the assets are centered. See // crbug.com/119832. SkIRect region = SkIRect::MakeXYWH( (supply_status_.line_power_on ? kBatteryImageWidth : 0) + 2, image_index * kBatteryImageHeight, kBatteryImageWidth - 2, kBatteryImageHeight); all.ToSkBitmap()->extractSubset(&image, region); SetImage(image); } PowerSupplyStatus supply_status_; DISALLOW_COPY_AND_ASSIGN(PowerTrayView); }; // This view is used only for the popup. class PowerPopupView : public views::Label { public: PowerPopupView() { SetHorizontalAlignment(ALIGN_RIGHT); UpdateText(); } virtual ~PowerPopupView() { } void UpdatePowerStatus(const PowerSupplyStatus& status) { supply_status_ = status; // Sanitize. if (supply_status_.battery_is_full) supply_status_.battery_percentage = 100.0; UpdateText(); } private: void UpdateText() { base::TimeDelta time = base::TimeDelta::FromSeconds( supply_status_.line_power_on ? supply_status_.battery_seconds_to_full : supply_status_.battery_seconds_to_empty); int hour = time.InHours(); int min = (time - base::TimeDelta::FromHours(hour)).InMinutes(); ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance(); if (hour && min) { SetText(l10n_util::GetStringFUTF16(IDS_ASH_STATUS_TRAY_BATTERY_STATUS, base::IntToString16( static_cast<int>(supply_status_.battery_percentage)), base::IntToString16(hour), base::IntToString16(min))); } else { if (supply_status_.line_power_on) { SetText(bundle.GetLocalizedString(IDS_ASH_STATUS_TRAY_BATTERY_FULL)); } else { // Completely discharged? ... ha? SetText(string16()); } } } PowerSupplyStatus supply_status_; DISALLOW_COPY_AND_ASSIGN(PowerPopupView); }; } // namespace tray TrayPower::TrayPower() : power_(NULL), power_tray_(NULL) { } TrayPower::~TrayPower() { } views::View* TrayPower::CreateTrayView(user::LoginStatus status) { // There may not be enough information when this is created about whether // there is a battery or not. So always create this, and adjust visibility as // necessary. PowerSupplyStatus power_status = ash::Shell::GetInstance()->tray_delegate()->GetPowerSupplyStatus(); power_tray_.reset(new tray::PowerTrayView()); power_tray_->UpdatePowerStatus(power_status); return power_tray_.get(); } views::View* TrayPower::CreateDefaultView(user::LoginStatus status) { date_.reset(new tray::DateView(tray::DateView::DATE)); if (status != user::LOGGED_IN_NONE && status != user::LOGGED_IN_LOCKED) date_->set_actionable(true); views::View* container = new views::View; views::BoxLayout* layout = new views::BoxLayout(views::BoxLayout::kHorizontal, kTrayPopupPaddingHorizontal, 10, 0); layout->set_spread_blank_space(true); container->SetLayoutManager(layout); container->set_background(views::Background::CreateSolidBackground( SkColorSetRGB(245, 245, 245))); container->AddChildView(date_.get()); PowerSupplyStatus power_status = ash::Shell::GetInstance()->tray_delegate()->GetPowerSupplyStatus(); if (power_status.battery_is_present) { power_.reset(new tray::PowerPopupView()); power_->UpdatePowerStatus(power_status); container->AddChildView(power_.get()); } return container; } views::View* TrayPower::CreateDetailedView(user::LoginStatus status) { return NULL; } void TrayPower::DestroyTrayView() { power_tray_.reset(); } void TrayPower::DestroyDefaultView() { date_.reset(); power_.reset(); } void TrayPower::DestroyDetailedView() { } void TrayPower::OnPowerStatusChanged(const PowerSupplyStatus& status) { if (power_tray_.get()) power_tray_->UpdatePowerStatus(status); if (power_.get()) power_->UpdatePowerStatus(status); } } // namespace internal } // namespace ash <commit_msg>ash: Fix the awesome logic for showing battery status.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/system/power/tray_power.h" #include "ash/shell.h" #include "ash/system/date/date_view.h" #include "ash/system/power/power_supply_status.h" #include "ash/system/tray/system_tray_delegate.h" #include "ash/system/tray/tray_constants.h" #include "base/string_number_conversions.h" #include "base/stringprintf.h" #include "base/utf_string_conversions.h" #include "grit/ash_strings.h" #include "grit/ui_resources.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkRect.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/image/image.h" #include "ui/gfx/size.h" #include "ui/base/l10n/l10n_util.h" #include "ui/views/controls/button/button.h" #include "ui/views/controls/button/text_button.h" #include "ui/views/controls/image_view.h" #include "ui/views/controls/label.h" #include "ui/views/layout/box_layout.h" #include "ui/views/view.h" #include "ui/views/widget/widget.h" #include "unicode/fieldpos.h" #include "unicode/fmtable.h" namespace ash { namespace internal { namespace { // Width and height of battery images. const int kBatteryImageHeight = 25; const int kBatteryImageWidth = 25; // Number of different power states. const int kNumPowerImages = 15; } namespace tray { // This view is used only for the tray. class PowerTrayView : public views::ImageView { public: PowerTrayView() { UpdateImage(); } virtual ~PowerTrayView() { } void UpdatePowerStatus(const PowerSupplyStatus& status) { supply_status_ = status; // Sanitize. if (supply_status_.battery_is_full) supply_status_.battery_percentage = 100.0; UpdateImage(); SetVisible(status.battery_is_present); } private: void UpdateImage() { SkBitmap image; gfx::Image all = ui::ResourceBundle::GetSharedInstance().GetImageNamed( IDR_AURA_UBER_TRAY_POWER_SMALL); int image_index = 0; if (supply_status_.battery_percentage >= 100) { image_index = kNumPowerImages - 1; } else if (!supply_status_.battery_is_present) { image_index = kNumPowerImages; } else { image_index = static_cast<int> ( supply_status_.battery_percentage / 100.0 * (kNumPowerImages - 1)); image_index = std::max(std::min(image_index, kNumPowerImages - 2), 0); } // TODO(mbolohan): Remove the 2px offset when the assets are centered. See // crbug.com/119832. SkIRect region = SkIRect::MakeXYWH( (supply_status_.line_power_on ? kBatteryImageWidth : 0) + 2, image_index * kBatteryImageHeight, kBatteryImageWidth - 2, kBatteryImageHeight); all.ToSkBitmap()->extractSubset(&image, region); SetImage(image); } PowerSupplyStatus supply_status_; DISALLOW_COPY_AND_ASSIGN(PowerTrayView); }; // This view is used only for the popup. class PowerPopupView : public views::Label { public: PowerPopupView() { SetHorizontalAlignment(ALIGN_RIGHT); UpdateText(); } virtual ~PowerPopupView() { } void UpdatePowerStatus(const PowerSupplyStatus& status) { supply_status_ = status; // Sanitize. if (supply_status_.battery_is_full) supply_status_.battery_percentage = 100.0; UpdateText(); } private: void UpdateText() { base::TimeDelta time = base::TimeDelta::FromSeconds( supply_status_.line_power_on ? supply_status_.battery_seconds_to_full : supply_status_.battery_seconds_to_empty); int hour = time.InHours(); int min = (time - base::TimeDelta::FromHours(hour)).InMinutes(); ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance(); if (hour || min) { SetText(l10n_util::GetStringFUTF16(IDS_ASH_STATUS_TRAY_BATTERY_STATUS, base::IntToString16( static_cast<int>(supply_status_.battery_percentage)), base::IntToString16(hour), base::IntToString16(min))); } else { if (supply_status_.line_power_on) { SetText(bundle.GetLocalizedString(IDS_ASH_STATUS_TRAY_BATTERY_FULL)); } else { // Completely discharged? ... ha? SetText(string16()); } } } PowerSupplyStatus supply_status_; DISALLOW_COPY_AND_ASSIGN(PowerPopupView); }; } // namespace tray TrayPower::TrayPower() : power_(NULL), power_tray_(NULL) { } TrayPower::~TrayPower() { } views::View* TrayPower::CreateTrayView(user::LoginStatus status) { // There may not be enough information when this is created about whether // there is a battery or not. So always create this, and adjust visibility as // necessary. PowerSupplyStatus power_status = ash::Shell::GetInstance()->tray_delegate()->GetPowerSupplyStatus(); power_tray_.reset(new tray::PowerTrayView()); power_tray_->UpdatePowerStatus(power_status); return power_tray_.get(); } views::View* TrayPower::CreateDefaultView(user::LoginStatus status) { date_.reset(new tray::DateView(tray::DateView::DATE)); if (status != user::LOGGED_IN_NONE && status != user::LOGGED_IN_LOCKED) date_->set_actionable(true); views::View* container = new views::View; views::BoxLayout* layout = new views::BoxLayout(views::BoxLayout::kHorizontal, kTrayPopupPaddingHorizontal, 10, 0); layout->set_spread_blank_space(true); container->SetLayoutManager(layout); container->set_background(views::Background::CreateSolidBackground( SkColorSetRGB(245, 245, 245))); container->AddChildView(date_.get()); PowerSupplyStatus power_status = ash::Shell::GetInstance()->tray_delegate()->GetPowerSupplyStatus(); if (power_status.battery_is_present) { power_.reset(new tray::PowerPopupView()); power_->UpdatePowerStatus(power_status); container->AddChildView(power_.get()); } return container; } views::View* TrayPower::CreateDetailedView(user::LoginStatus status) { return NULL; } void TrayPower::DestroyTrayView() { power_tray_.reset(); } void TrayPower::DestroyDefaultView() { date_.reset(); power_.reset(); } void TrayPower::DestroyDetailedView() { } void TrayPower::OnPowerStatusChanged(const PowerSupplyStatus& status) { if (power_tray_.get()) power_tray_->UpdatePowerStatus(status); if (power_.get()) power_->UpdatePowerStatus(status); } } // namespace internal } // namespace ash <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: frmhtml.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: obo $ $Date: 2006-09-17 16:23:09 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sfx2.hxx" #include <tools/list.hxx> #include <tools/table.hxx> #ifndef _HTMLTOKN_H #include <svtools/htmltokn.h> #endif #ifndef SVTOOLS_ASYNCLINK_HXX #include <svtools/asynclink.hxx> #endif #ifndef GCC #endif #include "docinf.hxx" #define _SVSTDARR_USHORTS #define _SVSTDARR_ULONGS #include <svtools/svstdarr.hxx> #include "sfx.hrc" #include "frmhtml.hxx" #include "docfile.hxx" #include "viewfrm.hxx" #include "evntconf.hxx" #include "request.hxx" #include "fcontnr.hxx" #include "sfxtypes.hxx" #define SFX_HTMLFRMSIZE_REL 0x0001 #define SFX_HTMLFRMSIZE_PERCENT 0x0002 static sal_Char __READONLY_DATA sHTML_SC_yes[] = "YES"; static sal_Char __READONLY_DATA sHTML_SC_no[] = "NO"; static sal_Char __READONLY_DATA sHTML_SC_auto[] = "AUTO"; #define HTML_O_READONLY "READONLY" #define HTML_O_EDIT "EDIT" static HTMLOptionEnum __READONLY_DATA aScollingTable[] = { { sHTML_SC_yes, ScrollingYes }, { sHTML_SC_no, ScrollingNo }, { sHTML_SC_auto, ScrollingAuto }, { 0, 0 } }; void SfxFrameHTMLParser::ParseFrameOptions( SfxFrameDescriptor *pFrame, const HTMLOptions *pOptions, const String& rBaseURL ) { // die Optionen holen und setzen Size aMargin( pFrame->GetMargin() ); // MIB 15.7.97: Netscape scheint marginwidth auf 0 zu setzen, sobald // marginheight gesetzt wird und umgekehrt. Machen wir jetzt wegen // bug #41665# auch so. // Netscape l"a\st aber ein direktes Setzen auf 0 nicht zu, IE4.0 schon. // Den Bug machen wir nicht mit! BOOL bMarginWidth = FALSE, bMarginHeight = FALSE; USHORT nArrLen = pOptions->Count(); for ( USHORT i=0; i<nArrLen; i++ ) { const HTMLOption *pOption = (*pOptions)[i]; switch( pOption->GetToken() ) { case HTML_O_BORDERCOLOR: { Color aColor; pOption->GetColor( aColor ); pFrame->SetWallpaper( Wallpaper( aColor ) ); break; } case HTML_O_SRC: pFrame->SetURL( String( INetURLObject::GetAbsURL( rBaseURL, pOption->GetString())) ); break; case HTML_O_NAME: pFrame->SetName( pOption->GetString() ); break; case HTML_O_MARGINWIDTH: aMargin.Width() = pOption->GetNumber(); // if( aMargin.Width() < 1 ) // aMargin.Width() = 1; if( !bMarginHeight ) aMargin.Height() = 0; bMarginWidth = TRUE; break; case HTML_O_MARGINHEIGHT: aMargin.Height() = pOption->GetNumber(); // if( aMargin.Height() < 1 ) // aMargin.Height() = 1; if( !bMarginWidth ) aMargin.Width() = 0; bMarginHeight = TRUE; break; case HTML_O_SCROLLING: pFrame->SetScrollingMode( (ScrollingMode)pOption->GetEnum( aScollingTable, ScrollingAuto ) ); break; case HTML_O_FRAMEBORDER: { String aStr = pOption->GetString(); BOOL bBorder = TRUE; if ( aStr.EqualsIgnoreCaseAscii("NO") || aStr.EqualsIgnoreCaseAscii("0") ) bBorder = FALSE; pFrame->SetFrameBorder( bBorder ); break; } case HTML_O_NORESIZE: pFrame->SetResizable( FALSE ); break; default: if ( pOption->GetTokenString().EqualsIgnoreCaseAscii( HTML_O_READONLY ) ) { String aStr = pOption->GetString(); BOOL bReadonly = TRUE; if ( aStr.EqualsIgnoreCaseAscii("FALSE") ) bReadonly = FALSE; pFrame->SetReadOnly( bReadonly ); } else if ( pOption->GetTokenString().EqualsIgnoreCaseAscii( HTML_O_EDIT ) ) { String aStr = pOption->GetString(); BOOL bEdit = TRUE; if ( aStr.EqualsIgnoreCaseAscii("FALSE") ) bEdit = FALSE; pFrame->SetEditable( bEdit ); } break; } } pFrame->SetMargin( aMargin ); } <commit_msg>INTEGRATION: CWS vgbugs07 (1.11.218); FILE MERGED 2007/06/04 13:34:43 vg 1.11.218.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: frmhtml.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: hr $ $Date: 2007-06-27 23:03:11 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sfx2.hxx" #include <tools/list.hxx> #include <tools/table.hxx> #ifndef _HTMLTOKN_H #include <svtools/htmltokn.h> #endif #ifndef SVTOOLS_ASYNCLINK_HXX #include <svtools/asynclink.hxx> #endif #ifndef GCC #endif #include <sfx2/docinf.hxx> #define _SVSTDARR_USHORTS #define _SVSTDARR_ULONGS #include <svtools/svstdarr.hxx> #include <sfx2/sfx.hrc> #include <sfx2/frmhtml.hxx> #include <sfx2/docfile.hxx> #include <sfx2/viewfrm.hxx> #include <sfx2/evntconf.hxx> #include <sfx2/request.hxx> #include <sfx2/fcontnr.hxx> #include "sfxtypes.hxx" #define SFX_HTMLFRMSIZE_REL 0x0001 #define SFX_HTMLFRMSIZE_PERCENT 0x0002 static sal_Char __READONLY_DATA sHTML_SC_yes[] = "YES"; static sal_Char __READONLY_DATA sHTML_SC_no[] = "NO"; static sal_Char __READONLY_DATA sHTML_SC_auto[] = "AUTO"; #define HTML_O_READONLY "READONLY" #define HTML_O_EDIT "EDIT" static HTMLOptionEnum __READONLY_DATA aScollingTable[] = { { sHTML_SC_yes, ScrollingYes }, { sHTML_SC_no, ScrollingNo }, { sHTML_SC_auto, ScrollingAuto }, { 0, 0 } }; void SfxFrameHTMLParser::ParseFrameOptions( SfxFrameDescriptor *pFrame, const HTMLOptions *pOptions, const String& rBaseURL ) { // die Optionen holen und setzen Size aMargin( pFrame->GetMargin() ); // MIB 15.7.97: Netscape scheint marginwidth auf 0 zu setzen, sobald // marginheight gesetzt wird und umgekehrt. Machen wir jetzt wegen // bug #41665# auch so. // Netscape l"a\st aber ein direktes Setzen auf 0 nicht zu, IE4.0 schon. // Den Bug machen wir nicht mit! BOOL bMarginWidth = FALSE, bMarginHeight = FALSE; USHORT nArrLen = pOptions->Count(); for ( USHORT i=0; i<nArrLen; i++ ) { const HTMLOption *pOption = (*pOptions)[i]; switch( pOption->GetToken() ) { case HTML_O_BORDERCOLOR: { Color aColor; pOption->GetColor( aColor ); pFrame->SetWallpaper( Wallpaper( aColor ) ); break; } case HTML_O_SRC: pFrame->SetURL( String( INetURLObject::GetAbsURL( rBaseURL, pOption->GetString())) ); break; case HTML_O_NAME: pFrame->SetName( pOption->GetString() ); break; case HTML_O_MARGINWIDTH: aMargin.Width() = pOption->GetNumber(); // if( aMargin.Width() < 1 ) // aMargin.Width() = 1; if( !bMarginHeight ) aMargin.Height() = 0; bMarginWidth = TRUE; break; case HTML_O_MARGINHEIGHT: aMargin.Height() = pOption->GetNumber(); // if( aMargin.Height() < 1 ) // aMargin.Height() = 1; if( !bMarginWidth ) aMargin.Width() = 0; bMarginHeight = TRUE; break; case HTML_O_SCROLLING: pFrame->SetScrollingMode( (ScrollingMode)pOption->GetEnum( aScollingTable, ScrollingAuto ) ); break; case HTML_O_FRAMEBORDER: { String aStr = pOption->GetString(); BOOL bBorder = TRUE; if ( aStr.EqualsIgnoreCaseAscii("NO") || aStr.EqualsIgnoreCaseAscii("0") ) bBorder = FALSE; pFrame->SetFrameBorder( bBorder ); break; } case HTML_O_NORESIZE: pFrame->SetResizable( FALSE ); break; default: if ( pOption->GetTokenString().EqualsIgnoreCaseAscii( HTML_O_READONLY ) ) { String aStr = pOption->GetString(); BOOL bReadonly = TRUE; if ( aStr.EqualsIgnoreCaseAscii("FALSE") ) bReadonly = FALSE; pFrame->SetReadOnly( bReadonly ); } else if ( pOption->GetTokenString().EqualsIgnoreCaseAscii( HTML_O_EDIT ) ) { String aStr = pOption->GetString(); BOOL bEdit = TRUE; if ( aStr.EqualsIgnoreCaseAscii("FALSE") ) bEdit = FALSE; pFrame->SetEditable( bEdit ); } break; } } pFrame->SetMargin( aMargin ); } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2010 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ // $Id$ #include "sqlite_datasource.hpp" #include "sqlite_featureset.hpp" // mapnik #include <mapnik/ptree_helpers.hpp> #include <mapnik/sql_utils.hpp> // boost #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> #include <boost/tokenizer.hpp> #include <boost/filesystem/operations.hpp> using boost::lexical_cast; using boost::bad_lexical_cast; using mapnik::datasource; using mapnik::parameters; DATASOURCE_PLUGIN(sqlite_datasource) using mapnik::box2d; using mapnik::coord2d; using mapnik::query; using mapnik::featureset_ptr; using mapnik::layer_descriptor; using mapnik::attribute_descriptor; using mapnik::datasource_exception; sqlite_datasource::sqlite_datasource(parameters const& params, bool bind) : datasource(params), extent_(), extent_initialized_(false), type_(datasource::Vector), table_(*params_.get<std::string>("table","")), fields_(*params_.get<std::string>("fields","*")), metadata_(*params_.get<std::string>("metadata","")), geometry_table_(*params_.get<std::string>("geometry_table","")), geometry_field_(*params_.get<std::string>("geometry_field","the_geom")), // http://www.sqlite.org/lang_createtable.html#rowid key_field_(*params_.get<std::string>("key_field","rowid")), row_offset_(*params_.get<int>("row_offset",0)), row_limit_(*params_.get<int>("row_limit",0)), desc_(*params_.get<std::string>("type"), *params_.get<std::string>("encoding","utf-8")), format_(mapnik::wkbGeneric) { boost::optional<std::string> file = params_.get<std::string>("file"); if (!file) throw datasource_exception("Sqlite Plugin: missing <file> parameter"); if (table_.empty()) throw mapnik::datasource_exception("Sqlite Plugin: missing <table> parameter"); boost::optional<std::string> wkb = params_.get<std::string>("wkb_format"); if (wkb) { if (*wkb == "spatialite") format_ = mapnik::wkbSpatiaLite; } multiple_geometries_ = *params_.get<mapnik::boolean>("multiple_geometries",false); use_spatial_index_ = *params_.get<mapnik::boolean>("use_spatial_index",true); boost::optional<std::string> ext = params_.get<std::string>("extent"); if (ext) extent_initialized_ = extent_.from_string(*ext); boost::optional<std::string> base = params_.get<std::string>("base"); if (base) dataset_name_ = *base + "/" + *file; else dataset_name_ = *file; if (bind) { this->bind(); } } void sqlite_datasource::bind() const { if (is_bound_) return; if (!boost::filesystem::exists(dataset_name_)) throw datasource_exception("Sqlite Plugin: " + dataset_name_ + " does not exist"); dataset_ = new sqlite_connection (dataset_name_); if(geometry_table_.empty()) { geometry_table_ = mapnik::table_from_sql(table_); } if (use_spatial_index_) { std::ostringstream s; s << "SELECT COUNT (*) FROM sqlite_master"; s << " WHERE LOWER(name) = LOWER('idx_" << geometry_table_ << "_" << geometry_field_ << "')"; boost::scoped_ptr<sqlite_resultset> rs (dataset_->execute_query (s.str())); if (rs->is_valid () && rs->step_next()) { use_spatial_index_ = rs->column_integer (0) == 1; } if (!use_spatial_index_) std::clog << "Sqlite Plugin: spatial index not found for table '" << geometry_table_ << "'" << std::endl; } if (metadata_ != "" && !extent_initialized_) { std::ostringstream s; s << "SELECT xmin, ymin, xmax, ymax FROM " << metadata_; s << " WHERE LOWER(f_table_name) = LOWER('" << geometry_table_ << "')"; boost::scoped_ptr<sqlite_resultset> rs (dataset_->execute_query (s.str())); if (rs->is_valid () && rs->step_next()) { double xmin = rs->column_double (0); double ymin = rs->column_double (1); double xmax = rs->column_double (2); double ymax = rs->column_double (3); extent_.init (xmin,ymin,xmax,ymax); extent_initialized_ = true; } } if (!extent_initialized_ && use_spatial_index_) { std::ostringstream s; s << "SELECT MIN(xmin), MIN(ymin), MAX(xmax), MAX(ymax) FROM " << "idx_" << geometry_table_ << "_" << geometry_field_; boost::scoped_ptr<sqlite_resultset> rs (dataset_->execute_query (s.str())); if (rs->is_valid () && rs->step_next()) { double xmin = rs->column_double (0); double ymin = rs->column_double (1); double xmax = rs->column_double (2); double ymax = rs->column_double (3); extent_.init (xmin,ymin,xmax,ymax); extent_initialized_ = true; } } { // should we deduce column names and types using PRAGMA? bool use_pragma_table_info = true; if (table_ != geometry_table_) { // if 'table_' is a subquery then we try to deduce names // and types from the first row returned from that query use_pragma_table_info = false; } if (!use_pragma_table_info) { std::ostringstream s; s << "SELECT " << fields_ << " FROM (" << table_ << ") LIMIT 1"; boost::scoped_ptr<sqlite_resultset> rs (dataset_->execute_query (s.str())); if (rs->is_valid () && rs->step_next()) { for (int i = 0; i < rs->column_count (); ++i) { const int type_oid = rs->column_type (i); const char* fld_name = rs->column_name (i); switch (type_oid) { case SQLITE_INTEGER: desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Integer)); break; case SQLITE_FLOAT: desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Double)); break; case SQLITE_TEXT: desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::String)); break; case SQLITE_NULL: // sqlite reports based on value, not actual column type unless // PRAGMA table_info is used so here we assume the column is a string // which is a lesser evil than altogether dropping the column desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::String)); case SQLITE_BLOB: break; default: #ifdef MAPNIK_DEBUG std::clog << "Sqlite Plugin: unknown type_oid=" << type_oid << std::endl; #endif break; } } } else { // if we do not have at least a row and // we cannot determine the right columns types and names // as all column_type are SQLITE_NULL // so we fallback to using PRAGMA table_info use_pragma_table_info = true; } } // TODO - ensure that the supplied key_field is a valid "integer primary key" desc_.add_descriptor(attribute_descriptor("rowid",mapnik::Integer)); if (use_pragma_table_info) { std::ostringstream s; s << "PRAGMA table_info(" << geometry_table_ << ")"; boost::scoped_ptr<sqlite_resultset> rs (dataset_->execute_query (s.str())); while (rs->is_valid () && rs->step_next()) { const char* fld_name = rs->column_text(1); std::string fld_type(rs->column_text(2)); boost::algorithm::to_lower(fld_type); // see 2.1 "Column Affinity" at http://www.sqlite.org/datatype3.html if (boost::algorithm::contains(fld_type,"int")) { desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Integer)); } else if (boost::algorithm::contains(fld_type,"text") || boost::algorithm::contains(fld_type,"char") || boost::algorithm::contains(fld_type,"clob")) { desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::String)); } else if (boost::algorithm::contains(fld_type,"real") || boost::algorithm::contains(fld_type,"float") || boost::algorithm::contains(fld_type,"double")) { desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Double)); } //else if (boost::algorithm::contains(fld_type,"blob") // desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::String)); #ifdef MAPNIK_DEBUG else { // "Column Affinity" says default to "Numeric" but for now we pass.. //desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Double)); std::clog << "Sqlite Plugin: unknown type_oid=" << fld_type << std::endl; } #endif } } } is_bound_ = true; } sqlite_datasource::~sqlite_datasource() { if (is_bound_) { delete dataset_; } } std::string sqlite_datasource::name() { return "sqlite"; } int sqlite_datasource::type() const { return type_; } box2d<double> sqlite_datasource::envelope() const { if (!is_bound_) bind(); return extent_; } layer_descriptor sqlite_datasource::get_descriptor() const { if (!is_bound_) bind(); return desc_; } featureset_ptr sqlite_datasource::features(query const& q) const { if (!is_bound_) bind(); if (dataset_) { mapnik::box2d<double> const& e = q.get_bbox(); std::ostringstream s; s << "SELECT " << geometry_field_ << "," << key_field_; std::set<std::string> const& props = q.property_names(); std::set<std::string>::const_iterator pos = props.begin(); std::set<std::string>::const_iterator end = props.end(); while (pos != end) { s << ",\"" << *pos << "\""; ++pos; } s << " FROM "; std::string query (table_); if (use_spatial_index_) { std::ostringstream spatial_sql; spatial_sql << std::setprecision(16); spatial_sql << " WHERE " << key_field_ << " IN (SELECT pkid FROM idx_" << geometry_table_ << "_" << geometry_field_; spatial_sql << " WHERE xmax>=" << e.minx() << " AND xmin<=" << e.maxx() ; spatial_sql << " AND ymax>=" << e.miny() << " AND ymin<=" << e.maxy() << ")"; if (boost::algorithm::ifind_first(query, "WHERE")) { boost::algorithm::ireplace_first(query, "WHERE", spatial_sql.str() + " AND "); } else if (boost::algorithm::ifind_first(query, geometry_table_)) { boost::algorithm::ireplace_first(query, table_, table_ + " " + spatial_sql.str()); } } s << query ; if (row_limit_ > 0) { s << " LIMIT " << row_limit_; } if (row_offset_ > 0) { s << " OFFSET " << row_offset_; } #ifdef MAPNIK_DEBUG std::clog << "Sqlite Plugin: " << s.str() << std::endl; #endif boost::shared_ptr<sqlite_resultset> rs (dataset_->execute_query (s.str())); return featureset_ptr (new sqlite_featureset(rs, desc_.get_encoding(), format_, multiple_geometries_)); } return featureset_ptr(); } featureset_ptr sqlite_datasource::features_at_point(coord2d const& pt) const { if (!is_bound_) bind(); return featureset_ptr(); } <commit_msg>sqlite plugin: add features_at_point() impl<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2010 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ // $Id$ #include "sqlite_datasource.hpp" #include "sqlite_featureset.hpp" // mapnik #include <mapnik/ptree_helpers.hpp> #include <mapnik/sql_utils.hpp> // boost #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> #include <boost/tokenizer.hpp> #include <boost/filesystem/operations.hpp> using boost::lexical_cast; using boost::bad_lexical_cast; using mapnik::datasource; using mapnik::parameters; DATASOURCE_PLUGIN(sqlite_datasource) using mapnik::box2d; using mapnik::coord2d; using mapnik::query; using mapnik::featureset_ptr; using mapnik::layer_descriptor; using mapnik::attribute_descriptor; using mapnik::datasource_exception; sqlite_datasource::sqlite_datasource(parameters const& params, bool bind) : datasource(params), extent_(), extent_initialized_(false), type_(datasource::Vector), table_(*params_.get<std::string>("table","")), fields_(*params_.get<std::string>("fields","*")), metadata_(*params_.get<std::string>("metadata","")), geometry_table_(*params_.get<std::string>("geometry_table","")), geometry_field_(*params_.get<std::string>("geometry_field","the_geom")), // http://www.sqlite.org/lang_createtable.html#rowid key_field_(*params_.get<std::string>("key_field","rowid")), row_offset_(*params_.get<int>("row_offset",0)), row_limit_(*params_.get<int>("row_limit",0)), desc_(*params_.get<std::string>("type"), *params_.get<std::string>("encoding","utf-8")), format_(mapnik::wkbGeneric) { boost::optional<std::string> file = params_.get<std::string>("file"); if (!file) throw datasource_exception("Sqlite Plugin: missing <file> parameter"); if (table_.empty()) throw mapnik::datasource_exception("Sqlite Plugin: missing <table> parameter"); boost::optional<std::string> wkb = params_.get<std::string>("wkb_format"); if (wkb) { if (*wkb == "spatialite") format_ = mapnik::wkbSpatiaLite; } multiple_geometries_ = *params_.get<mapnik::boolean>("multiple_geometries",false); use_spatial_index_ = *params_.get<mapnik::boolean>("use_spatial_index",true); boost::optional<std::string> ext = params_.get<std::string>("extent"); if (ext) extent_initialized_ = extent_.from_string(*ext); boost::optional<std::string> base = params_.get<std::string>("base"); if (base) dataset_name_ = *base + "/" + *file; else dataset_name_ = *file; if (bind) { this->bind(); } } void sqlite_datasource::bind() const { if (is_bound_) return; if (!boost::filesystem::exists(dataset_name_)) throw datasource_exception("Sqlite Plugin: " + dataset_name_ + " does not exist"); dataset_ = new sqlite_connection (dataset_name_); if(geometry_table_.empty()) { geometry_table_ = mapnik::table_from_sql(table_); } if (use_spatial_index_) { std::ostringstream s; s << "SELECT COUNT (*) FROM sqlite_master"; s << " WHERE LOWER(name) = LOWER('idx_" << geometry_table_ << "_" << geometry_field_ << "')"; boost::scoped_ptr<sqlite_resultset> rs (dataset_->execute_query (s.str())); if (rs->is_valid () && rs->step_next()) { use_spatial_index_ = rs->column_integer (0) == 1; } if (!use_spatial_index_) std::clog << "Sqlite Plugin: spatial index not found for table '" << geometry_table_ << "'" << std::endl; } if (metadata_ != "" && !extent_initialized_) { std::ostringstream s; s << "SELECT xmin, ymin, xmax, ymax FROM " << metadata_; s << " WHERE LOWER(f_table_name) = LOWER('" << geometry_table_ << "')"; boost::scoped_ptr<sqlite_resultset> rs (dataset_->execute_query (s.str())); if (rs->is_valid () && rs->step_next()) { double xmin = rs->column_double (0); double ymin = rs->column_double (1); double xmax = rs->column_double (2); double ymax = rs->column_double (3); extent_.init (xmin,ymin,xmax,ymax); extent_initialized_ = true; } } if (!extent_initialized_ && use_spatial_index_) { std::ostringstream s; s << "SELECT MIN(xmin), MIN(ymin), MAX(xmax), MAX(ymax) FROM " << "idx_" << geometry_table_ << "_" << geometry_field_; boost::scoped_ptr<sqlite_resultset> rs (dataset_->execute_query (s.str())); if (rs->is_valid () && rs->step_next()) { double xmin = rs->column_double (0); double ymin = rs->column_double (1); double xmax = rs->column_double (2); double ymax = rs->column_double (3); extent_.init (xmin,ymin,xmax,ymax); extent_initialized_ = true; } } { // should we deduce column names and types using PRAGMA? bool use_pragma_table_info = true; if (table_ != geometry_table_) { // if 'table_' is a subquery then we try to deduce names // and types from the first row returned from that query use_pragma_table_info = false; } if (!use_pragma_table_info) { std::ostringstream s; s << "SELECT " << fields_ << " FROM (" << table_ << ") LIMIT 1"; boost::scoped_ptr<sqlite_resultset> rs (dataset_->execute_query (s.str())); if (rs->is_valid () && rs->step_next()) { for (int i = 0; i < rs->column_count (); ++i) { const int type_oid = rs->column_type (i); const char* fld_name = rs->column_name (i); switch (type_oid) { case SQLITE_INTEGER: desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Integer)); break; case SQLITE_FLOAT: desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Double)); break; case SQLITE_TEXT: desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::String)); break; case SQLITE_NULL: // sqlite reports based on value, not actual column type unless // PRAGMA table_info is used so here we assume the column is a string // which is a lesser evil than altogether dropping the column desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::String)); case SQLITE_BLOB: break; default: #ifdef MAPNIK_DEBUG std::clog << "Sqlite Plugin: unknown type_oid=" << type_oid << std::endl; #endif break; } } } else { // if we do not have at least a row and // we cannot determine the right columns types and names // as all column_type are SQLITE_NULL // so we fallback to using PRAGMA table_info use_pragma_table_info = true; } } // TODO - ensure that the supplied key_field is a valid "integer primary key" desc_.add_descriptor(attribute_descriptor("rowid",mapnik::Integer)); if (use_pragma_table_info) { std::ostringstream s; s << "PRAGMA table_info(" << geometry_table_ << ")"; boost::scoped_ptr<sqlite_resultset> rs (dataset_->execute_query (s.str())); while (rs->is_valid () && rs->step_next()) { const char* fld_name = rs->column_text(1); std::string fld_type(rs->column_text(2)); boost::algorithm::to_lower(fld_type); // see 2.1 "Column Affinity" at http://www.sqlite.org/datatype3.html if (boost::algorithm::contains(fld_type,"int")) { desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Integer)); } else if (boost::algorithm::contains(fld_type,"text") || boost::algorithm::contains(fld_type,"char") || boost::algorithm::contains(fld_type,"clob")) { desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::String)); } else if (boost::algorithm::contains(fld_type,"real") || boost::algorithm::contains(fld_type,"float") || boost::algorithm::contains(fld_type,"double")) { desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Double)); } //else if (boost::algorithm::contains(fld_type,"blob") // desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::String)); #ifdef MAPNIK_DEBUG else { // "Column Affinity" says default to "Numeric" but for now we pass.. //desc_.add_descriptor(attribute_descriptor(fld_name,mapnik::Double)); std::clog << "Sqlite Plugin: unknown type_oid=" << fld_type << std::endl; } #endif } } } is_bound_ = true; } sqlite_datasource::~sqlite_datasource() { if (is_bound_) { delete dataset_; } } std::string sqlite_datasource::name() { return "sqlite"; } int sqlite_datasource::type() const { return type_; } box2d<double> sqlite_datasource::envelope() const { if (!is_bound_) bind(); return extent_; } layer_descriptor sqlite_datasource::get_descriptor() const { if (!is_bound_) bind(); return desc_; } featureset_ptr sqlite_datasource::features(query const& q) const { if (!is_bound_) bind(); if (dataset_) { mapnik::box2d<double> const& e = q.get_bbox(); std::ostringstream s; s << "SELECT " << geometry_field_ << "," << key_field_; std::set<std::string> const& props = q.property_names(); std::set<std::string>::const_iterator pos = props.begin(); std::set<std::string>::const_iterator end = props.end(); while (pos != end) { s << ",\"" << *pos << "\""; ++pos; } s << " FROM "; std::string query (table_); if (use_spatial_index_) { std::ostringstream spatial_sql; spatial_sql << std::setprecision(16); spatial_sql << " WHERE " << key_field_ << " IN (SELECT pkid FROM idx_" << geometry_table_ << "_" << geometry_field_; spatial_sql << " WHERE xmax>=" << e.minx() << " AND xmin<=" << e.maxx() ; spatial_sql << " AND ymax>=" << e.miny() << " AND ymin<=" << e.maxy() << ")"; if (boost::algorithm::ifind_first(query, "WHERE")) { boost::algorithm::ireplace_first(query, "WHERE", spatial_sql.str() + " AND "); } else if (boost::algorithm::ifind_first(query, geometry_table_)) { boost::algorithm::ireplace_first(query, table_, table_ + " " + spatial_sql.str()); } } s << query ; if (row_limit_ > 0) { s << " LIMIT " << row_limit_; } if (row_offset_ > 0) { s << " OFFSET " << row_offset_; } #ifdef MAPNIK_DEBUG std::clog << "Sqlite Plugin: " << s.str() << std::endl; #endif boost::shared_ptr<sqlite_resultset> rs (dataset_->execute_query (s.str())); return featureset_ptr (new sqlite_featureset(rs, desc_.get_encoding(), format_, multiple_geometries_)); } return featureset_ptr(); } featureset_ptr sqlite_datasource::features_at_point(coord2d const& pt) const { if (!is_bound_) bind(); if (dataset_) { // TODO - need tolerance mapnik::box2d<double> const e(pt.x,pt.y,pt.x,pt.y); std::ostringstream s; s << "SELECT " << geometry_field_ << "," << key_field_; std::vector<attribute_descriptor>::const_iterator itr = desc_.get_descriptors().begin(); std::vector<attribute_descriptor>::const_iterator end = desc_.get_descriptors().end(); while (itr != end) { std::string fld_name = itr->get_name(); if (fld_name != key_field_) s << ",\"" << itr->get_name() << "\""; ++itr; } s << " FROM "; std::string query (table_); if (use_spatial_index_) { std::ostringstream spatial_sql; spatial_sql << std::setprecision(16); spatial_sql << " WHERE " << key_field_ << " IN (SELECT pkid FROM idx_" << geometry_table_ << "_" << geometry_field_; spatial_sql << " WHERE xmax>=" << e.minx() << " AND xmin<=" << e.maxx() ; spatial_sql << " AND ymax>=" << e.miny() << " AND ymin<=" << e.maxy() << ")"; if (boost::algorithm::ifind_first(query, "WHERE")) { boost::algorithm::ireplace_first(query, "WHERE", spatial_sql.str() + " AND "); } else if (boost::algorithm::ifind_first(query, geometry_table_)) { boost::algorithm::ireplace_first(query, table_, table_ + " " + spatial_sql.str()); } } s << query ; if (row_limit_ > 0) { s << " LIMIT " << row_limit_; } if (row_offset_ > 0) { s << " OFFSET " << row_offset_; } #ifdef MAPNIK_DEBUG std::clog << "Sqlite Plugin: " << s.str() << std::endl; #endif boost::shared_ptr<sqlite_resultset> rs (dataset_->execute_query (s.str())); return featureset_ptr (new sqlite_featureset(rs, desc_.get_encoding(), format_, multiple_geometries_)); } return featureset_ptr(); } <|endoftext|>
<commit_before>//----------------------------------*-C++-*----------------------------------// /*! * \file xs/test/tstXS.cc * \author Thomas M. Evans * \date Fri Jan 31 12:54:58 2014 * \brief XS container test. * \note Copyright (C) 2014 Oak Ridge National Laboratory, UT-Battelle, LLC. */ //---------------------------------------------------------------------------// #include "gtest/utils_gtest.hh" #include "../XS.hh" //---------------------------------------------------------------------------// // Test fixture //---------------------------------------------------------------------------// // NOTE: the test class name must not contain underscores. class XS_Test : public testing::Test { protected: typedef profugus::XS XS; typedef XS::Vector Vector; typedef XS::Matrix Matrix; typedef XS::OneDArray OneDArray; typedef XS::TwoDArray TwoDArray; typedef XS::Vec_Int Vec_Int; protected: // Initialization that are performed for each test void SetUp() { Ng = 4; // build data m1_sig.resize(Ng); m5_sig.resize(Ng); sigf.resize(Ng); nusigf.resize(Ng); chi.resize(Ng); m1_sig[0] = 2.0; m1_sig[1] = 3.0; m1_sig[2] = 4.0; m1_sig[3] = 5.0; m5_sig[0] = 20.0; m5_sig[1] = 30.0; m5_sig[2] = 40.0; m5_sig[3] = 50.0; sigf[0] = 11.0; sigf[1] = 12.0; sigf[2] = 13.0; sigf[3] = 14.0; double nu = 2.4; for (int n = 0; n < 4; ++n) { nusigf[n] = sigf[n] * nu; } chi[0] = 0.6; chi[1] = 0.3; chi[2] = 0.1; xs.set(1, Ng); } protected: int Ng; OneDArray m1_sig; OneDArray m5_sig, sigf, nusigf, chi; XS xs; }; //---------------------------------------------------------------------------// // TESTS //---------------------------------------------------------------------------// TEST_F(XS_Test, totals_assignment) { EXPECT_EQ(1, xs.pn_order()); EXPECT_EQ(4, xs.num_groups()); EXPECT_EQ(0, xs.num_mat()); xs.add(1, XS::TOTAL, m1_sig); xs.add(5, XS::TOTAL, m5_sig); xs.add(5, XS::SIG_F, sigf); xs.add(5, XS::NU_SIG_F, nusigf); xs.add(5, XS::CHI, chi); EXPECT_EQ(0, xs.num_mat()); xs.complete(); EXPECT_EQ(2, xs.num_mat()); EXPECT_EQ(1, xs.pn_order()); EXPECT_EQ(4, xs.num_groups()); EXPECT_TRUE(xs.has(1)); EXPECT_TRUE(xs.has(5)); Vec_Int mids; xs.get_matids(mids); EXPECT_EQ(2, mids.size()); EXPECT_EQ(1, mids[0]); EXPECT_EQ(5, mids[1]); // material 1 { const Vector &sigt = xs.vector(1, XS::TOTAL); EXPECT_EQ(4, sigt.length()); EXPECT_EQ(2.0, sigt(0)); EXPECT_EQ(3.0, sigt(1)); EXPECT_EQ(4.0, sigt(2)); EXPECT_EQ(5.0, sigt(3)); for (int t = 1; t < XS::END_XS_TYPES; ++t) { const Vector &sig = xs.vector(1, t); EXPECT_EQ(4, sig.length()); for (int g = 0; g < 4; ++g) { EXPECT_EQ(0.0, sig(g)); } } } // material 5 { const Vector &sigt = xs.vector(5, XS::TOTAL); EXPECT_EQ(4, sigt.length()); EXPECT_EQ(20.0, sigt(0)); EXPECT_EQ(30.0, sigt(1)); EXPECT_EQ(40.0, sigt(2)); EXPECT_EQ(50.0, sigt(3)); const Vector &sigf = xs.vector(5, XS::SIG_F); EXPECT_EQ(4, sigf.length()); EXPECT_EQ(11.0, sigf(0)); EXPECT_EQ(12.0, sigf(1)); EXPECT_EQ(13.0, sigf(2)); EXPECT_EQ(14.0, sigf(3)); const Vector &nusigf = xs.vector(5, XS::NU_SIG_F); EXPECT_EQ(4, nusigf.length()); EXPECT_EQ(2.4*11.0, nusigf(0)); EXPECT_EQ(2.4*12.0, nusigf(1)); EXPECT_EQ(2.4*13.0, nusigf(2)); EXPECT_EQ(2.4*14.0, nusigf(3)); const Vector &chi = xs.vector(5, XS::CHI); EXPECT_EQ(4, chi.length()); EXPECT_EQ(0.6, chi(0)); EXPECT_EQ(0.3, chi(1)); EXPECT_EQ(0.1, chi(2)); EXPECT_EQ(0.0, chi(3)); } for (int m = 0; m < 2; ++m) { int matid = mids[m]; for (int n = 0; n < 1; ++n) { const Matrix &sigs = xs.matrix(matid, n); EXPECT_EQ(4, sigs.numRows()); EXPECT_EQ(4, sigs.numCols()); for (int g = 0; g < 4; ++g) { for (int gp = 0; gp < 4; ++gp) { EXPECT_EQ(0.0, sigs(g, gp)); } } } } } //---------------------------------------------------------------------------// // end of tstXS.cc //---------------------------------------------------------------------------// <commit_msg>Finished XS assignment.<commit_after>//----------------------------------*-C++-*----------------------------------// /*! * \file xs/test/tstXS.cc * \author Thomas M. Evans * \date Fri Jan 31 12:54:58 2014 * \brief XS container test. * \note Copyright (C) 2014 Oak Ridge National Laboratory, UT-Battelle, LLC. */ //---------------------------------------------------------------------------// #include "gtest/utils_gtest.hh" #include "../XS.hh" //---------------------------------------------------------------------------// // Test fixture //---------------------------------------------------------------------------// // NOTE: the test class name must not contain underscores. class XS_Test : public testing::Test { protected: typedef profugus::XS XS; typedef XS::Vector Vector; typedef XS::Matrix Matrix; typedef XS::OneDArray OneDArray; typedef XS::TwoDArray TwoDArray; typedef XS::Vec_Int Vec_Int; protected: // Initialization that are performed for each test void SetUp() { Ng = 4; // build data m1_sig.resize(Ng); m5_sig.resize(Ng); sigf.resize(Ng); nusigf.resize(Ng); chi.resize(Ng); m1_sigs0.resizeRows(Ng); m1_sigs0.resizeCols(Ng); m1_sigs1.resizeRows(Ng); m1_sigs1.resizeCols(Ng); m5_sigs0.resizeRows(Ng); m5_sigs0.resizeCols(Ng); m5_sigs1.resizeRows(Ng); m5_sigs1.resizeCols(Ng); m1_sig[0] = 2.0; m1_sig[1] = 3.0; m1_sig[2] = 4.0; m1_sig[3] = 5.0; m5_sig[0] = 20.0; m5_sig[1] = 30.0; m5_sig[2] = 40.0; m5_sig[3] = 50.0; sigf[0] = 11.0; sigf[1] = 12.0; sigf[2] = 13.0; sigf[3] = 14.0; double nu = 2.4; for (int n = 0; n < 4; ++n) { nusigf[n] = sigf[n] * nu; } chi[0] = 0.6; chi[1] = 0.3; chi[2] = 0.1; // scattering m1 double m1s0[][4] = {{1.1, 0.0, 0.0, 0.0}, {0.4, 1.4, 0.0, 0.0}, {0.2, 0.9, 3.2, 0.2}, {0.1, 0.2, 0.4, 4.8}}; double m1s1[][4] = {{0.11, 0.00, 0.00, 0.00}, {0.04, 0.14, 0.00, 0.00}, {0.02, 0.09, 0.32, 0.02}, {0.01, 0.02, 0.04, 0.48}}; // scattering m5 double m5s0[][4] = {{2.1, 0.0, 0.0, 0.0}, {1.4, 2.4, 0.0, 0.0}, {1.2, 1.9, 5.2, 1.2}, {1.1, 1.2, 2.4, 9.8}}; double m5s1[][4] = {{0.21, 0.00, 0.00, 0.00}, {0.14, 0.24, 0.00, 0.00}, {0.12, 0.19, 0.52, 0.12}, {0.11, 0.12, 0.24, 0.98}}; for (int g = 0; g < 4; ++g) { for (int gp = 0; gp < 4; ++gp) { m1_sigs0(g, gp) = m1s0[g][gp]; m1_sigs1(g, gp) = m1s1[g][gp]; m5_sigs0(g, gp) = m5s0[g][gp]; m5_sigs1(g, gp) = m5s1[g][gp]; } } xs.set(1, Ng); } protected: int Ng; OneDArray m1_sig; OneDArray m5_sig, sigf, nusigf, chi; TwoDArray m1_sigs0, m1_sigs1, m5_sigs0, m5_sigs1; XS xs; }; //---------------------------------------------------------------------------// // TESTS //---------------------------------------------------------------------------// TEST_F(XS_Test, totals_assignment) { EXPECT_EQ(1, xs.pn_order()); EXPECT_EQ(4, xs.num_groups()); EXPECT_EQ(0, xs.num_mat()); xs.add(1, XS::TOTAL, m1_sig); xs.add(5, XS::TOTAL, m5_sig); xs.add(5, XS::SIG_F, sigf); xs.add(5, XS::NU_SIG_F, nusigf); xs.add(5, XS::CHI, chi); EXPECT_EQ(0, xs.num_mat()); xs.complete(); EXPECT_EQ(2, xs.num_mat()); EXPECT_EQ(1, xs.pn_order()); EXPECT_EQ(4, xs.num_groups()); EXPECT_TRUE(xs.has(1)); EXPECT_TRUE(xs.has(5)); Vec_Int mids; xs.get_matids(mids); EXPECT_EQ(2, mids.size()); EXPECT_EQ(1, mids[0]); EXPECT_EQ(5, mids[1]); // material 1 { const Vector &sigt = xs.vector(1, XS::TOTAL); EXPECT_EQ(4, sigt.length()); EXPECT_EQ(2.0, sigt(0)); EXPECT_EQ(3.0, sigt(1)); EXPECT_EQ(4.0, sigt(2)); EXPECT_EQ(5.0, sigt(3)); for (int t = 1; t < XS::END_XS_TYPES; ++t) { const Vector &sig = xs.vector(1, t); EXPECT_EQ(4, sig.length()); for (int g = 0; g < 4; ++g) { EXPECT_EQ(0.0, sig(g)); } } } // material 5 { const Vector &sigt = xs.vector(5, XS::TOTAL); EXPECT_EQ(4, sigt.length()); EXPECT_EQ(20.0, sigt(0)); EXPECT_EQ(30.0, sigt(1)); EXPECT_EQ(40.0, sigt(2)); EXPECT_EQ(50.0, sigt(3)); const Vector &sigf = xs.vector(5, XS::SIG_F); EXPECT_EQ(4, sigf.length()); EXPECT_EQ(11.0, sigf(0)); EXPECT_EQ(12.0, sigf(1)); EXPECT_EQ(13.0, sigf(2)); EXPECT_EQ(14.0, sigf(3)); const Vector &nusigf = xs.vector(5, XS::NU_SIG_F); EXPECT_EQ(4, nusigf.length()); EXPECT_EQ(2.4*11.0, nusigf(0)); EXPECT_EQ(2.4*12.0, nusigf(1)); EXPECT_EQ(2.4*13.0, nusigf(2)); EXPECT_EQ(2.4*14.0, nusigf(3)); const Vector &chi = xs.vector(5, XS::CHI); EXPECT_EQ(4, chi.length()); EXPECT_EQ(0.6, chi(0)); EXPECT_EQ(0.3, chi(1)); EXPECT_EQ(0.1, chi(2)); EXPECT_EQ(0.0, chi(3)); } for (int m = 0; m < 2; ++m) { int matid = mids[m]; for (int n = 0; n < 1; ++n) { const Matrix &sigs = xs.matrix(matid, n); EXPECT_EQ(4, sigs.numRows()); EXPECT_EQ(4, sigs.numCols()); for (int g = 0; g < 4; ++g) { for (int gp = 0; gp < 4; ++gp) { EXPECT_EQ(0.0, sigs(g, gp)); } } } } } //---------------------------------------------------------------------------// TEST_F(XS_Test, scat_assignment) { xs.add(1, XS::TOTAL, m1_sig); xs.add(1, 0, m1_sigs0); xs.add(1, 1, m1_sigs1); xs.add(5, XS::TOTAL, m5_sig); xs.add(5, 0, m5_sigs0); xs.add(5, 1, m5_sigs1); xs.complete(); EXPECT_EQ(2, xs.num_mat()); EXPECT_EQ(1, xs.pn_order()); EXPECT_EQ(4, xs.num_groups()); // material 1 { const Vector &sigt = xs.vector(1, XS::TOTAL); EXPECT_EQ(4, sigt.length()); EXPECT_EQ(2.0, sigt(0)); EXPECT_EQ(3.0, sigt(1)); EXPECT_EQ(4.0, sigt(2)); EXPECT_EQ(5.0, sigt(3)); const Matrix &p0 = xs.matrix(1, 0); const Matrix &p1 = xs.matrix(1, 1); EXPECT_EQ(4, p0.numRows()); EXPECT_EQ(4, p0.numCols()); EXPECT_EQ(4, p1.numRows()); EXPECT_EQ(4, p1.numCols()); EXPECT_EQ(1.1, p0(0, 0)); EXPECT_EQ(0.0, p0(0, 1)); EXPECT_EQ(0.0, p0(0, 2)); EXPECT_EQ(0.0, p0(0, 3)); EXPECT_EQ(0.4, p0(1, 0)); EXPECT_EQ(1.4, p0(1, 1)); EXPECT_EQ(0.0, p0(1, 2)); EXPECT_EQ(0.0, p0(1, 3)); EXPECT_EQ(0.2, p0(2, 0)); EXPECT_EQ(0.9, p0(2, 1)); EXPECT_EQ(3.2, p0(2, 2)); EXPECT_EQ(0.2, p0(2, 3)); EXPECT_EQ(0.1, p0(3, 0)); EXPECT_EQ(0.2, p0(3, 1)); EXPECT_EQ(0.4, p0(3, 2)); EXPECT_EQ(4.8, p0(3, 3)); for (int g = 0; g < 4; ++g) { for (int gp = 0; gp < 4; ++gp) { EXPECT_SOFTEQ(p0(g,gp)*0.1, p1(g,gp), 1.0e-12); } } } // material 5 { const Vector &sigt = xs.vector(5, XS::TOTAL); EXPECT_EQ(4, sigt.length()); EXPECT_EQ(20.0, sigt(0)); EXPECT_EQ(30.0, sigt(1)); EXPECT_EQ(40.0, sigt(2)); EXPECT_EQ(50.0, sigt(3)); const Matrix &p0 = xs.matrix(5, 0); const Matrix &p1 = xs.matrix(5, 1); EXPECT_EQ(4, p0.numRows()); EXPECT_EQ(4, p0.numCols()); EXPECT_EQ(4, p1.numRows()); EXPECT_EQ(4, p1.numCols()); EXPECT_EQ(2.1, p0(0, 0)); EXPECT_EQ(0.0, p0(0, 1)); EXPECT_EQ(0.0, p0(0, 2)); EXPECT_EQ(0.0, p0(0, 3)); EXPECT_EQ(1.4, p0(1, 0)); EXPECT_EQ(2.4, p0(1, 1)); EXPECT_EQ(0.0, p0(1, 2)); EXPECT_EQ(0.0, p0(1, 3)); EXPECT_EQ(1.2, p0(2, 0)); EXPECT_EQ(1.9, p0(2, 1)); EXPECT_EQ(5.2, p0(2, 2)); EXPECT_EQ(1.2, p0(2, 3)); EXPECT_EQ(1.1, p0(3, 0)); EXPECT_EQ(1.2, p0(3, 1)); EXPECT_EQ(2.4, p0(3, 2)); EXPECT_EQ(9.8, p0(3, 3)); for (int g = 0; g < 4; ++g) { for (int gp = 0; gp < 4; ++gp) { EXPECT_SOFTEQ(p0(g,gp)*0.1, p1(g,gp), 1.0e-12); } } } Vec_Int mids; xs.get_matids(mids); for (int m = 0; m < 2; ++m) { for (int t = 1; t < XS::END_XS_TYPES; ++t) { const Vector &sig = xs.vector(mids[m], t); EXPECT_EQ(4, sig.length()); for (int g = 0; g < 4; ++g) { EXPECT_EQ(0.0, sig(g)); } } } } //---------------------------------------------------------------------------// // end of tstXS.cc //---------------------------------------------------------------------------// <|endoftext|>
<commit_before>/*********************************************************************** created: 22/2/2004 author: Paul D Turner purpose: Implements the WindowFactoryManager *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGUI/WindowFactoryManager.h" #include "CEGUI/WindowFactory.h" #include "CEGUI/Exceptions.h" #include <algorithm> // Start of CEGUI namespace section namespace CEGUI { /************************************************************************* Static Data Definitions *************************************************************************/ // singleton instance pointer template<> WindowFactoryManager* Singleton<WindowFactoryManager>::ms_Singleton = 0; // list of owned WindowFactory object pointers WindowFactoryManager::OwnedWindowFactoryList WindowFactoryManager::d_ownedFactories; //----------------------------------------------------------------------------// WindowFactoryManager::WindowFactoryManager(void) { Logger::getSingleton().logEvent( "CEGUI::WindowFactoryManager singleton created"); // complete addition of any pre-added WindowFactory objects WindowFactoryManager::OwnedWindowFactoryList::iterator i = d_ownedFactories.begin(); if (d_ownedFactories.end() != i) { Logger::getSingleton().logEvent( "---- Adding pre-registered WindowFactory objects ----"); for (; d_ownedFactories.end() != i; ++i) addFactory(*i); } } /************************************************************************* Adds a WindowFactory object to the registry *************************************************************************/ void WindowFactoryManager::addFactory(WindowFactory* factory) { // throw exception if passed factory is null. if (!factory) { CEGUI_THROW(NullObjectException( "The provided WindowFactory pointer was invalid.")); } // throw exception if type name for factory is already in use if (d_factoryRegistry.find(factory->getTypeName()) != d_factoryRegistry.end()) { CEGUI_THROW(AlreadyExistsException( "A WindowFactory for type '" + factory->getTypeName() + "' is already registered.")); } // add the factory to the registry d_factoryRegistry[factory->getTypeName()] = factory; char addr_buff[32]; sprintf(addr_buff, "(%p)", static_cast<void*>(factory)); Logger::getSingleton().logEvent("WindowFactory for '" + factory->getTypeName() +"' windows added. " + addr_buff); } /************************************************************************* removes a WindowFactory from the registry (by name) *************************************************************************/ void WindowFactoryManager::removeFactory(const String& name) { WindowFactoryRegistry::iterator i = d_factoryRegistry.find(name); // exit if no factory exists for this type if (i == d_factoryRegistry.end()) return; // see if we own this factory OwnedWindowFactoryList::iterator j = std::find(d_ownedFactories.begin(), d_ownedFactories.end(), (*i).second); char addr_buff[32]; sprintf(addr_buff, "(%p)", static_cast<void*>((*i).second)); d_factoryRegistry.erase(name); Logger::getSingleton().logEvent("WindowFactory for '" + name + "' windows removed. " + addr_buff); // delete factory object if we created it if (j != d_ownedFactories.end()) { Logger::getSingleton().logEvent("Deleted WindowFactory for '" + (*j)->getTypeName() + "' windows."); CEGUI_DELETE_AO (*j); d_ownedFactories.erase(j); } } /************************************************************************* removes a WindowFactory from the registry (by pointer) *************************************************************************/ void WindowFactoryManager::removeFactory(WindowFactory* factory) { if (factory) { removeFactory(factory->getTypeName()); } } //----------------------------------------------------------------------------// void WindowFactoryManager::removeAllFactories(void) { while (!d_factoryRegistry.empty()) removeFactory((*d_factoryRegistry.begin()).second); } /************************************************************************* returns a pointer to the requested WindowFactory object *************************************************************************/ WindowFactory* WindowFactoryManager::getFactory(const String& type) const { // first, dereference aliased types, as needed. String targetType(getDereferencedAliasType(type)); // try for a 'real' type WindowFactoryRegistry::const_iterator pos = d_factoryRegistry.find(targetType); // found an actual factory for this type if (pos != d_factoryRegistry.end()) { return pos->second; } // no concrete type, try for a falagard mapped type else { FalagardMapRegistry::const_iterator falagard = d_falagardRegistry.find(targetType); // found falagard mapping for this type if (falagard != d_falagardRegistry.end()) { // recursively call getFactory on the target base type return getFactory(falagard->second.d_baseType); } // type not found anywhere, give up with an exception. else { CEGUI_THROW(UnknownObjectException( "A WindowFactory object, an alias, or mapping for '" + type + "' Window objects is not registered with the system.")); } } } /************************************************************************* Returns true if a WindowFactory, an alias, or a falagard mapping for a specified window type is present *************************************************************************/ bool WindowFactoryManager::isFactoryPresent(const String& name) const { // first, dereference aliased types, as needed. String targetType(getDereferencedAliasType(name)); // now try for a 'real' type if (d_factoryRegistry.find(targetType) != d_factoryRegistry.end()) { return true; } // not a concrete type, so return whether it's a Falagard mapped type. else { return (d_falagardRegistry.find(targetType) != d_falagardRegistry.end()); } } /************************************************************************* Return a WindowFactoryManager::WindowFactoryIterator object to iterate over the available WindowFactory types. *************************************************************************/ WindowFactoryManager::WindowFactoryIterator WindowFactoryManager::getIterator(void) const { return WindowFactoryIterator(d_factoryRegistry.begin(), d_factoryRegistry.end()); } /************************************************************************* Return a WindowFactoryManager::TypeAliasIterator object to iterate over the defined aliases for window types. *************************************************************************/ WindowFactoryManager::TypeAliasIterator WindowFactoryManager::getAliasIterator(void) const { return TypeAliasIterator(d_aliasRegistry.begin(), d_aliasRegistry.end()); } /************************************************************************* Add a window type alias mapping *************************************************************************/ void WindowFactoryManager::addWindowTypeAlias(const String& aliasName, const String& targetType) { TypeAliasRegistry::iterator pos = d_aliasRegistry.find(aliasName); if (pos == d_aliasRegistry.end()) { d_aliasRegistry[aliasName].d_targetStack.push_back(targetType); } // alias already exists, add our new entry to the list already there else { pos->second.d_targetStack.push_back(targetType); } Logger::getSingleton().logEvent("Window type alias named '" + aliasName + "' added for window type '" + targetType +"'."); } /************************************************************************* Remove a window type alias mapping *************************************************************************/ void WindowFactoryManager::removeWindowTypeAlias(const String& aliasName, const String& targetType) { // find alias name TypeAliasRegistry::iterator pos = d_aliasRegistry.find(aliasName); // if alias name exists if (pos != d_aliasRegistry.end()) { // find the specified target for this alias AliasTargetStack::TargetTypeStack::iterator aliasPos = std::find(pos->second.d_targetStack.begin(), pos->second.d_targetStack.end(), targetType); // if the target exists for this alias if (aliasPos != pos->second.d_targetStack.end()) { // erase the target mapping pos->second.d_targetStack.erase(aliasPos); Logger::getSingleton().logEvent("Window type alias named '" + aliasName + "' removed for window type '" + targetType +"'."); // if the list of targets for this alias is now empty if (pos->second.d_targetStack.empty()) { // erase the alias name also d_aliasRegistry.erase(aliasName); Logger::getSingleton().logEvent("Window type alias named '" + aliasName + "' has no more targets and has been removed.", Informative); } } } } void WindowFactoryManager::removeAllWindowTypeAliases() { d_aliasRegistry.clear(); } void WindowFactoryManager::addFalagardWindowMapping(const String& newType, const String& targetType, const String& lookName, const String& renderer, const String& effectName) { WindowFactoryManager::FalagardWindowMapping mapping; mapping.d_windowType = newType; mapping.d_baseType = targetType; mapping.d_lookName = lookName; mapping.d_rendererType = renderer; mapping.d_effectName = effectName; // see if the type we're creating already exists if (d_falagardRegistry.find(newType) != d_falagardRegistry.end()) { // type already exists, log the fact that it's going to be replaced. Logger::getSingleton().logEvent("Falagard mapping for type '" + newType + "' already exists - current mapping will be replaced."); } char addr_buff[32]; sprintf(addr_buff, "(%p)", static_cast<void*>(&mapping)); Logger::getSingleton().logEvent("Creating falagard mapping for type '" + newType + "' using base type '" + targetType + "', window renderer '" + renderer + "' Look'N'Feel '" + lookName + "' and RenderEffect '" + effectName + "'. " + addr_buff); d_falagardRegistry[newType] = mapping; } void WindowFactoryManager::removeFalagardWindowMapping(const String& type) { FalagardMapRegistry::iterator iter = d_falagardRegistry.find(type); if (iter != d_falagardRegistry.end()) { Logger::getSingleton().logEvent("Removing falagard mapping for type '" + type + "'."); d_falagardRegistry.erase(iter); } } void WindowFactoryManager::removeAllFalagardWindowMappings() { d_falagardRegistry.clear(); } WindowFactoryManager::FalagardMappingIterator WindowFactoryManager::getFalagardMappingIterator() const { return FalagardMappingIterator(d_falagardRegistry.begin(), d_falagardRegistry.end()); } bool WindowFactoryManager::isFalagardMappedType(const String& type) const { return d_falagardRegistry.find(getDereferencedAliasType(type)) != d_falagardRegistry.end(); } const String& WindowFactoryManager::getMappedLookForType(const String& type) const { FalagardMapRegistry::const_iterator iter = d_falagardRegistry.find(getDereferencedAliasType(type)); if (iter != d_falagardRegistry.end()) { return (*iter).second.d_lookName; } // type does not exist as a mapped type (or an alias for one) else { CEGUI_THROW(InvalidRequestException( "Window factory type '" + type + "' is not a falagard mapped type (or an alias for one).")); } } const String& WindowFactoryManager::getMappedRendererForType(const String& type) const { FalagardMapRegistry::const_iterator iter = d_falagardRegistry.find(getDereferencedAliasType(type)); if (iter != d_falagardRegistry.end()) { return (*iter).second.d_rendererType; } // type does not exist as a mapped type (or an alias for one) else { CEGUI_THROW(InvalidRequestException( "Window factory type '" + type + "' is not a falagard mapped type (or an alias for one).")); } } String WindowFactoryManager::getDereferencedAliasType(const String& type) const { TypeAliasRegistry::const_iterator alias = d_aliasRegistry.find(type); // if this is an aliased type, ensure to fully dereference by recursively // calling ourselves on the active target for the given type. if (alias != d_aliasRegistry.end()) return getDereferencedAliasType(alias->second.getActiveTarget()); // we're not an alias, so return the input type unchanged return type; } const WindowFactoryManager::FalagardWindowMapping& WindowFactoryManager::getFalagardMappingForType(const String& type) const { FalagardMapRegistry::const_iterator iter = d_falagardRegistry.find(getDereferencedAliasType(type)); if (iter != d_falagardRegistry.end()) { return (*iter).second; } // type does not exist as a mapped type (or an alias for one) else { CEGUI_THROW(InvalidRequestException( "Window factory type '" + type + "' is not a falagard mapped type (or an alias for one).")); } } ////////////////////////////////////////////////////////////////////////// /************************************************************************* Methods for AliasTargetStack class *************************************************************************/ ////////////////////////////////////////////////////////////////////////// const String& WindowFactoryManager::AliasTargetStack::getActiveTarget(void) const { return d_targetStack.back(); } uint WindowFactoryManager::AliasTargetStack::getStackedTargetCount(void) const { return (uint)d_targetStack.size(); } } // End of CEGUI namespace section <commit_msg>Hint towards SchemeManager when window factory manager can't find a window factory<commit_after>/*********************************************************************** created: 22/2/2004 author: Paul D Turner purpose: Implements the WindowFactoryManager *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGUI/WindowFactoryManager.h" #include "CEGUI/WindowFactory.h" #include "CEGUI/Exceptions.h" #include <algorithm> // Start of CEGUI namespace section namespace CEGUI { /************************************************************************* Static Data Definitions *************************************************************************/ // singleton instance pointer template<> WindowFactoryManager* Singleton<WindowFactoryManager>::ms_Singleton = 0; // list of owned WindowFactory object pointers WindowFactoryManager::OwnedWindowFactoryList WindowFactoryManager::d_ownedFactories; //----------------------------------------------------------------------------// WindowFactoryManager::WindowFactoryManager(void) { Logger::getSingleton().logEvent( "CEGUI::WindowFactoryManager singleton created"); // complete addition of any pre-added WindowFactory objects WindowFactoryManager::OwnedWindowFactoryList::iterator i = d_ownedFactories.begin(); if (d_ownedFactories.end() != i) { Logger::getSingleton().logEvent( "---- Adding pre-registered WindowFactory objects ----"); for (; d_ownedFactories.end() != i; ++i) addFactory(*i); } } /************************************************************************* Adds a WindowFactory object to the registry *************************************************************************/ void WindowFactoryManager::addFactory(WindowFactory* factory) { // throw exception if passed factory is null. if (!factory) { CEGUI_THROW(NullObjectException( "The provided WindowFactory pointer was invalid.")); } // throw exception if type name for factory is already in use if (d_factoryRegistry.find(factory->getTypeName()) != d_factoryRegistry.end()) { CEGUI_THROW(AlreadyExistsException( "A WindowFactory for type '" + factory->getTypeName() + "' is already registered.")); } // add the factory to the registry d_factoryRegistry[factory->getTypeName()] = factory; char addr_buff[32]; sprintf(addr_buff, "(%p)", static_cast<void*>(factory)); Logger::getSingleton().logEvent("WindowFactory for '" + factory->getTypeName() +"' windows added. " + addr_buff); } /************************************************************************* removes a WindowFactory from the registry (by name) *************************************************************************/ void WindowFactoryManager::removeFactory(const String& name) { WindowFactoryRegistry::iterator i = d_factoryRegistry.find(name); // exit if no factory exists for this type if (i == d_factoryRegistry.end()) return; // see if we own this factory OwnedWindowFactoryList::iterator j = std::find(d_ownedFactories.begin(), d_ownedFactories.end(), (*i).second); char addr_buff[32]; sprintf(addr_buff, "(%p)", static_cast<void*>((*i).second)); d_factoryRegistry.erase(name); Logger::getSingleton().logEvent("WindowFactory for '" + name + "' windows removed. " + addr_buff); // delete factory object if we created it if (j != d_ownedFactories.end()) { Logger::getSingleton().logEvent("Deleted WindowFactory for '" + (*j)->getTypeName() + "' windows."); CEGUI_DELETE_AO (*j); d_ownedFactories.erase(j); } } /************************************************************************* removes a WindowFactory from the registry (by pointer) *************************************************************************/ void WindowFactoryManager::removeFactory(WindowFactory* factory) { if (factory) { removeFactory(factory->getTypeName()); } } //----------------------------------------------------------------------------// void WindowFactoryManager::removeAllFactories(void) { while (!d_factoryRegistry.empty()) removeFactory((*d_factoryRegistry.begin()).second); } /************************************************************************* returns a pointer to the requested WindowFactory object *************************************************************************/ WindowFactory* WindowFactoryManager::getFactory(const String& type) const { // first, dereference aliased types, as needed. String targetType(getDereferencedAliasType(type)); // try for a 'real' type WindowFactoryRegistry::const_iterator pos = d_factoryRegistry.find(targetType); // found an actual factory for this type if (pos != d_factoryRegistry.end()) { return pos->second; } // no concrete type, try for a falagard mapped type else { FalagardMapRegistry::const_iterator falagard = d_falagardRegistry.find(targetType); // found falagard mapping for this type if (falagard != d_falagardRegistry.end()) { // recursively call getFactory on the target base type return getFactory(falagard->second.d_baseType); } // type not found anywhere, give up with an exception. else { CEGUI_THROW(UnknownObjectException( "A WindowFactory object, an alias, or mapping for '" + type + "' Window objects is not registered with the system.\n\n" "Have you forgotten to load a scheme using " "CEGUI::SchemeManager::createFromFile(..)?")); } } } /************************************************************************* Returns true if a WindowFactory, an alias, or a falagard mapping for a specified window type is present *************************************************************************/ bool WindowFactoryManager::isFactoryPresent(const String& name) const { // first, dereference aliased types, as needed. String targetType(getDereferencedAliasType(name)); // now try for a 'real' type if (d_factoryRegistry.find(targetType) != d_factoryRegistry.end()) { return true; } // not a concrete type, so return whether it's a Falagard mapped type. else { return (d_falagardRegistry.find(targetType) != d_falagardRegistry.end()); } } /************************************************************************* Return a WindowFactoryManager::WindowFactoryIterator object to iterate over the available WindowFactory types. *************************************************************************/ WindowFactoryManager::WindowFactoryIterator WindowFactoryManager::getIterator(void) const { return WindowFactoryIterator(d_factoryRegistry.begin(), d_factoryRegistry.end()); } /************************************************************************* Return a WindowFactoryManager::TypeAliasIterator object to iterate over the defined aliases for window types. *************************************************************************/ WindowFactoryManager::TypeAliasIterator WindowFactoryManager::getAliasIterator(void) const { return TypeAliasIterator(d_aliasRegistry.begin(), d_aliasRegistry.end()); } /************************************************************************* Add a window type alias mapping *************************************************************************/ void WindowFactoryManager::addWindowTypeAlias(const String& aliasName, const String& targetType) { TypeAliasRegistry::iterator pos = d_aliasRegistry.find(aliasName); if (pos == d_aliasRegistry.end()) { d_aliasRegistry[aliasName].d_targetStack.push_back(targetType); } // alias already exists, add our new entry to the list already there else { pos->second.d_targetStack.push_back(targetType); } Logger::getSingleton().logEvent("Window type alias named '" + aliasName + "' added for window type '" + targetType +"'."); } /************************************************************************* Remove a window type alias mapping *************************************************************************/ void WindowFactoryManager::removeWindowTypeAlias(const String& aliasName, const String& targetType) { // find alias name TypeAliasRegistry::iterator pos = d_aliasRegistry.find(aliasName); // if alias name exists if (pos != d_aliasRegistry.end()) { // find the specified target for this alias AliasTargetStack::TargetTypeStack::iterator aliasPos = std::find(pos->second.d_targetStack.begin(), pos->second.d_targetStack.end(), targetType); // if the target exists for this alias if (aliasPos != pos->second.d_targetStack.end()) { // erase the target mapping pos->second.d_targetStack.erase(aliasPos); Logger::getSingleton().logEvent("Window type alias named '" + aliasName + "' removed for window type '" + targetType +"'."); // if the list of targets for this alias is now empty if (pos->second.d_targetStack.empty()) { // erase the alias name also d_aliasRegistry.erase(aliasName); Logger::getSingleton().logEvent("Window type alias named '" + aliasName + "' has no more targets and has been removed.", Informative); } } } } void WindowFactoryManager::removeAllWindowTypeAliases() { d_aliasRegistry.clear(); } void WindowFactoryManager::addFalagardWindowMapping(const String& newType, const String& targetType, const String& lookName, const String& renderer, const String& effectName) { WindowFactoryManager::FalagardWindowMapping mapping; mapping.d_windowType = newType; mapping.d_baseType = targetType; mapping.d_lookName = lookName; mapping.d_rendererType = renderer; mapping.d_effectName = effectName; // see if the type we're creating already exists if (d_falagardRegistry.find(newType) != d_falagardRegistry.end()) { // type already exists, log the fact that it's going to be replaced. Logger::getSingleton().logEvent("Falagard mapping for type '" + newType + "' already exists - current mapping will be replaced."); } char addr_buff[32]; sprintf(addr_buff, "(%p)", static_cast<void*>(&mapping)); Logger::getSingleton().logEvent("Creating falagard mapping for type '" + newType + "' using base type '" + targetType + "', window renderer '" + renderer + "' Look'N'Feel '" + lookName + "' and RenderEffect '" + effectName + "'. " + addr_buff); d_falagardRegistry[newType] = mapping; } void WindowFactoryManager::removeFalagardWindowMapping(const String& type) { FalagardMapRegistry::iterator iter = d_falagardRegistry.find(type); if (iter != d_falagardRegistry.end()) { Logger::getSingleton().logEvent("Removing falagard mapping for type '" + type + "'."); d_falagardRegistry.erase(iter); } } void WindowFactoryManager::removeAllFalagardWindowMappings() { d_falagardRegistry.clear(); } WindowFactoryManager::FalagardMappingIterator WindowFactoryManager::getFalagardMappingIterator() const { return FalagardMappingIterator(d_falagardRegistry.begin(), d_falagardRegistry.end()); } bool WindowFactoryManager::isFalagardMappedType(const String& type) const { return d_falagardRegistry.find(getDereferencedAliasType(type)) != d_falagardRegistry.end(); } const String& WindowFactoryManager::getMappedLookForType(const String& type) const { FalagardMapRegistry::const_iterator iter = d_falagardRegistry.find(getDereferencedAliasType(type)); if (iter != d_falagardRegistry.end()) { return (*iter).second.d_lookName; } // type does not exist as a mapped type (or an alias for one) else { CEGUI_THROW(InvalidRequestException( "Window factory type '" + type + "' is not a falagard mapped type (or an alias for one).")); } } const String& WindowFactoryManager::getMappedRendererForType(const String& type) const { FalagardMapRegistry::const_iterator iter = d_falagardRegistry.find(getDereferencedAliasType(type)); if (iter != d_falagardRegistry.end()) { return (*iter).second.d_rendererType; } // type does not exist as a mapped type (or an alias for one) else { CEGUI_THROW(InvalidRequestException( "Window factory type '" + type + "' is not a falagard mapped type (or an alias for one).")); } } String WindowFactoryManager::getDereferencedAliasType(const String& type) const { TypeAliasRegistry::const_iterator alias = d_aliasRegistry.find(type); // if this is an aliased type, ensure to fully dereference by recursively // calling ourselves on the active target for the given type. if (alias != d_aliasRegistry.end()) return getDereferencedAliasType(alias->second.getActiveTarget()); // we're not an alias, so return the input type unchanged return type; } const WindowFactoryManager::FalagardWindowMapping& WindowFactoryManager::getFalagardMappingForType(const String& type) const { FalagardMapRegistry::const_iterator iter = d_falagardRegistry.find(getDereferencedAliasType(type)); if (iter != d_falagardRegistry.end()) { return (*iter).second; } // type does not exist as a mapped type (or an alias for one) else { CEGUI_THROW(InvalidRequestException( "Window factory type '" + type + "' is not a falagard mapped type (or an alias for one).")); } } ////////////////////////////////////////////////////////////////////////// /************************************************************************* Methods for AliasTargetStack class *************************************************************************/ ////////////////////////////////////////////////////////////////////////// const String& WindowFactoryManager::AliasTargetStack::getActiveTarget(void) const { return d_targetStack.back(); } uint WindowFactoryManager::AliasTargetStack::getStackedTargetCount(void) const { return (uint)d_targetStack.size(); } } // End of CEGUI namespace section <|endoftext|>
<commit_before>/** * @file Cosa/Wireless.hh * @version 1.0 * * @section License * Copyright (C) 2013, Mikael Patel * * 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 * * This file is part of the Arduino Che Cosa project. */ #ifndef __COSA_WIRELESS_HH__ #define __COSA_WIRELESS_HH__ #include "Cosa/Power.hh" /** * Cosa Common Wireless devise driver interface. */ class Wireless { public: class Driver { public: /** Network address */ struct addr_t { uint8_t device; /**< device address (LSB) */ int16_t network; /**< network address */ addr_t(int16_t net, uint8_t dev) { network = net; device = dev; } }; protected: /** Current channel */ uint8_t m_channel; /** Current network and device address */ addr_t m_addr; /** Message available */ volatile bool m_avail; /** Sleep mode on wait */ uint8_t m_mode; public: /** * Construct Wireless Driver with given network and device address. * @param[in] network address. * @param[in] device address. */ Driver(int16_t network, uint8_t device) : m_channel(0), m_addr(network, device), m_avail(false), m_mode(SLEEP_MODE_IDLE) {} /** * Set power sleep mode during wait. * @param[in] mode of sleep. */ void set_sleep(uint8_t mode) { m_mode = mode; } /** * Set network and device address. Do not use the broadcast * address(0). Should be used before calling begin(). * @param[in] net network address. * @param[in] dev device address. */ void set_address(int16_t net, uint8_t dev) { m_addr.network = net; m_addr.device = dev; } /** * Set device transmission channel. Should be used before calling * begin(). * @param[in] channel. */ void set_channel(uint8_t channel) { m_channel = channel; } /** * Start the Wireless device driver. Return true(1) if successful * otherwise false(0). * @param[in] config configuration vector (default NULL) * @return bool */ virtual bool begin(const void* config = NULL) = 0; /** * Shut down the device driver. Return true(1) if successful * otherwise false(0). * @return bool */ virtual bool end() { return (true); } /** * Set device in power down mode. */ virtual void powerdown() {} /** * Set device in wakeup on radio mode. */ virtual void wakeup_on_radio() {} /** * Return true(1) if a message is available otherwise false(0). * @return bool */ virtual bool available() { return (m_avail); } /** * Return true(1) if there is room to send on the device otherwise * false(0). * @return bool */ virtual bool room() { return (true); } /** * Send message in given buffer, with given number of bytes. Returns * number of bytes sent. Returns error code(-1) if number of bytes * is greater than PAYLOAD_MAX. Return error code(-2) if fails to * set transmit mode. * @param[in] dest destination network address. * @param[in] buf buffer to transmit. * @param[in] len number of bytes in buffer. * @return number of bytes send or negative error code. */ virtual int send(uint8_t dest, const void* buf, size_t len) = 0; /** * Boardcast message in given buffer, with given number of bytes. * Returns number of bytes sent. Returns error code(-1) if number * of bytes is greater than PAYLOAD_MAX. Return error code(-2) if * fails to set transmit mode. * @param[in] buf buffer to transmit. * @param[in] len number of bytes in buffer. * @return number of bytes send or negative error code. */ int broadcast(const void* buf, size_t len) { return (send(0x00, buf, len)); } /** * Receive message and store into given buffer with given maximum * length. The source network address is returned in the parameter src. * Returns error code(-2) if no message is available and/or a * timeout occured. Returns error code(-1) if the buffer size if to * small for incoming message or if the receiver fifo has overflowed. * Otherwise the actual number of received bytes is returned * @param[out] src source network address. * @param[in] buf buffer to store incoming message. * @param[in] len maximum number of bytes to receive. * @param[in] ms maximum time out period. * @return number of bytes received or negative error code. */ virtual int recv(uint8_t& src, void* buf, size_t len, uint32_t ms = 0L) = 0; }; }; #endif <commit_msg>Fixed spelling error.<commit_after>/** * @file Cosa/Wireless.hh * @version 1.0 * * @section License * Copyright (C) 2013, Mikael Patel * * 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 * * This file is part of the Arduino Che Cosa project. */ #ifndef __COSA_WIRELESS_HH__ #define __COSA_WIRELESS_HH__ #include "Cosa/Power.hh" /** * Cosa Common Wireless device driver interface. */ class Wireless { public: class Driver { public: /** Network address */ struct addr_t { uint8_t device; /**< device address (LSB) */ int16_t network; /**< network address */ addr_t(int16_t net, uint8_t dev) { network = net; device = dev; } }; protected: /** Current channel */ uint8_t m_channel; /** Current network and device address */ addr_t m_addr; /** Message available */ volatile bool m_avail; /** Sleep mode on wait */ uint8_t m_mode; public: /** * Construct Wireless Driver with given network and device address. * @param[in] network address. * @param[in] device address. */ Driver(int16_t network, uint8_t device) : m_channel(0), m_addr(network, device), m_avail(false), m_mode(SLEEP_MODE_IDLE) {} /** * Set power sleep mode during wait. * @param[in] mode of sleep. */ void set_sleep(uint8_t mode) { m_mode = mode; } /** * Set network and device address. Do not use the broadcast * address(0). Should be used before calling begin(). * @param[in] net network address. * @param[in] dev device address. */ void set_address(int16_t net, uint8_t dev) { m_addr.network = net; m_addr.device = dev; } /** * Set device transmission channel. Should be used before calling * begin(). * @param[in] channel. */ void set_channel(uint8_t channel) { m_channel = channel; } /** * Start the Wireless device driver. Return true(1) if successful * otherwise false(0). * @param[in] config configuration vector (default NULL) * @return bool */ virtual bool begin(const void* config = NULL) = 0; /** * Shut down the device driver. Return true(1) if successful * otherwise false(0). * @return bool */ virtual bool end() { return (true); } /** * Set device in power down mode. */ virtual void powerdown() {} /** * Set device in wakeup on radio mode. */ virtual void wakeup_on_radio() {} /** * Return true(1) if a message is available otherwise false(0). * @return bool */ virtual bool available() { return (m_avail); } /** * Return true(1) if there is room to send on the device otherwise * false(0). * @return bool */ virtual bool room() { return (true); } /** * Send message in given buffer, with given number of bytes. Returns * number of bytes sent. Returns error code(-1) if number of bytes * is greater than PAYLOAD_MAX. Return error code(-2) if fails to * set transmit mode. * @param[in] dest destination network address. * @param[in] buf buffer to transmit. * @param[in] len number of bytes in buffer. * @return number of bytes send or negative error code. */ virtual int send(uint8_t dest, const void* buf, size_t len) = 0; /** * Boardcast message in given buffer, with given number of bytes. * Returns number of bytes sent. Returns error code(-1) if number * of bytes is greater than PAYLOAD_MAX. Return error code(-2) if * fails to set transmit mode. * @param[in] buf buffer to transmit. * @param[in] len number of bytes in buffer. * @return number of bytes send or negative error code. */ int broadcast(const void* buf, size_t len) { return (send(0x00, buf, len)); } /** * Receive message and store into given buffer with given maximum * length. The source network address is returned in the parameter src. * Returns error code(-2) if no message is available and/or a * timeout occured. Returns error code(-1) if the buffer size if to * small for incoming message or if the receiver fifo has overflowed. * Otherwise the actual number of received bytes is returned * @param[out] src source network address. * @param[in] buf buffer to store incoming message. * @param[in] len maximum number of bytes to receive. * @param[in] ms maximum time out period. * @return number of bytes received or negative error code. */ virtual int recv(uint8_t& src, void* buf, size_t len, uint32_t ms = 0L) = 0; }; }; #endif <|endoftext|>
<commit_before>/** \brief Utility to determine Zeder entries that have yet to be imported into zts_harvester. * \author Madeeswaran Kannan (madeeswaran.kannan@uni-tuebingen.de) * * \copyright 2019 Universitätsbibliothek Tübingen. All rights reserved. * * 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/>. */ #include <stdexcept> #include <cstdlib> #include <algorithm> #include <set> #include "IniFile.h" #include "JournalConfig.h" #include "MiscUtil.h" #include "StringUtil.h" #include "util.h" #include "Zeder.h" namespace { void LoadToolConfig(const IniFile &config_file, const Zeder::Flavour flavour, std::unordered_map<std::string, std::string> * const filter_regexps) { const auto flavour_section(config_file.getSection(Zeder::FLAVOUR_TO_STRING_MAP.at(flavour))); for (const auto &column_name : flavour_section->getEntryNames()) (*filter_regexps)[column_name] = flavour_section->getString(column_name); } void DownloadFullDump(const Zeder::Flavour flavour, const std::unordered_map<std::string, std::string> & filter_regexps, Zeder::EntryCollection * const downloaded_entries) { const auto endpoint_url(Zeder::GetFullDumpEndpointPath(flavour)); std::unique_ptr<Zeder::FullDumpDownloader::Params> downloader_params(new Zeder::FullDumpDownloader::Params(endpoint_url, {}, filter_regexps)); auto downloader(Zeder::FullDumpDownloader::Factory(Zeder::FullDumpDownloader::Type::FULL_DUMP, std::move(downloader_params))); if (not downloader->download(downloaded_entries)) LOG_ERROR("Couldn't download full dump for " + Zeder::FLAVOUR_TO_STRING_MAP.at(flavour)); } } // unnamed namespace int Main(int argc, char *argv[]) { if (argc != 4) ::Usage("flavour config_file harvester_config_file"); const Zeder::Flavour flavour(Zeder::ParseFlavour(argv[1])); const IniFile tool_config(argv[2]); const IniFile harvester_config(argv[3]); const JournalConfig::Reader bundle_reader(harvester_config); std::unordered_map<std::string, std::string> column_filter_regexps; Zeder::EntryCollection full_dump; LoadToolConfig(tool_config, flavour, &column_filter_regexps); DownloadFullDump(flavour, column_filter_regexps, &full_dump); std::set<unsigned int> imported_ids; for (const auto &section : harvester_config) { const auto section_name(section.getSectionName()); const auto group(bundle_reader.zotero(section_name).value(JournalConfig::Zotero::GROUP, "")); if (group != Zeder::FLAVOUR_TO_STRING_MAP.at(flavour)) continue; imported_ids.insert(StringUtil::ToUnsigned(bundle_reader.zeder(section_name).value(JournalConfig::Zeder::ID))); } std::set<unsigned int> full_dump_ids, not_imported_ids; std::transform(full_dump.begin(), full_dump.end(), std::inserter(full_dump_ids, full_dump_ids.begin()), [](const Zeder::Entry &entry) -> unsigned int { return entry.getId(); }); std::set_difference(full_dump_ids.begin(), full_dump_ids.end(), imported_ids.begin(), imported_ids.end(), std::inserter(not_imported_ids, not_imported_ids.begin())); LOG_INFO("Zeder '" + Zeder::FLAVOUR_TO_STRING_MAP.at(flavour) + "' instance: " + std::to_string(full_dump.size()) + " entries"); LOG_INFO("Number of imported entries: " + std::to_string(imported_ids.size())); LOG_INFO("Number of yet-to-be-imported entries: " + std::to_string(not_imported_ids.size())); std::set<std::string> buffer; std::transform(imported_ids.begin(), imported_ids.end(), std::inserter(buffer, buffer.begin()), [](unsigned int id) -> std::string { return std::to_string(id); }); LOG_INFO("\nImported entries: " + StringUtil::Join(buffer.begin(), buffer.end(), ",")); buffer.clear(); std::transform(not_imported_ids.begin(), not_imported_ids.end(), std::inserter(buffer, buffer.begin()), [](unsigned int id) -> std::string { return std::to_string(id); }); LOG_INFO("\nYet-to-be-imported entries: " + StringUtil::Join(buffer.begin(), buffer.end(), ",")); return EXIT_SUCCESS; } <commit_msg>zeder_count_imported: fix syntax for CentOS compatibility<commit_after>/** \brief Utility to determine Zeder entries that have yet to be imported into zts_harvester. * \author Madeeswaran Kannan (madeeswaran.kannan@uni-tuebingen.de) * * \copyright 2019 Universitätsbibliothek Tübingen. All rights reserved. * * 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/>. */ #include <stdexcept> #include <cstdlib> #include <algorithm> #include <set> #include "IniFile.h" #include "JournalConfig.h" #include "MiscUtil.h" #include "StringUtil.h" #include "util.h" #include "Zeder.h" namespace { void LoadToolConfig(const IniFile &config_file, const Zeder::Flavour flavour, std::unordered_map<std::string, std::string> * const filter_regexps) { const auto flavour_section(config_file.getSection(Zeder::FLAVOUR_TO_STRING_MAP.at(flavour))); for (const auto &column_name : flavour_section->getEntryNames()) (*filter_regexps)[column_name] = flavour_section->getString(column_name); } void DownloadFullDump(const Zeder::Flavour flavour, const std::unordered_map<std::string, std::string> & filter_regexps, Zeder::EntryCollection * const downloaded_entries) { const auto endpoint_url(Zeder::GetFullDumpEndpointPath(flavour)); const std::unordered_set<std::string> columns_to_download; // intentionally empty std::unique_ptr<Zeder::FullDumpDownloader::Params> downloader_params(new Zeder::FullDumpDownloader::Params(endpoint_url, columns_to_download, filter_regexps)); auto downloader(Zeder::FullDumpDownloader::Factory(Zeder::FullDumpDownloader::Type::FULL_DUMP, std::move(downloader_params))); if (not downloader->download(downloaded_entries)) LOG_ERROR("Couldn't download full dump for " + Zeder::FLAVOUR_TO_STRING_MAP.at(flavour)); } } // unnamed namespace int Main(int argc, char *argv[]) { if (argc != 4) ::Usage("flavour config_file harvester_config_file"); const Zeder::Flavour flavour(Zeder::ParseFlavour(argv[1])); const IniFile tool_config(argv[2]); const IniFile harvester_config(argv[3]); const JournalConfig::Reader bundle_reader(harvester_config); std::unordered_map<std::string, std::string> column_filter_regexps; Zeder::EntryCollection full_dump; LoadToolConfig(tool_config, flavour, &column_filter_regexps); DownloadFullDump(flavour, column_filter_regexps, &full_dump); std::set<unsigned int> imported_ids; for (const auto &section : harvester_config) { const auto section_name(section.getSectionName()); const auto group(bundle_reader.zotero(section_name).value(JournalConfig::Zotero::GROUP, "")); if (group != Zeder::FLAVOUR_TO_STRING_MAP.at(flavour)) continue; imported_ids.insert(StringUtil::ToUnsigned(bundle_reader.zeder(section_name).value(JournalConfig::Zeder::ID))); } std::set<unsigned int> full_dump_ids, not_imported_ids; std::transform(full_dump.begin(), full_dump.end(), std::inserter(full_dump_ids, full_dump_ids.begin()), [](const Zeder::Entry &entry) -> unsigned int { return entry.getId(); }); std::set_difference(full_dump_ids.begin(), full_dump_ids.end(), imported_ids.begin(), imported_ids.end(), std::inserter(not_imported_ids, not_imported_ids.begin())); LOG_INFO("Zeder '" + Zeder::FLAVOUR_TO_STRING_MAP.at(flavour) + "' instance: " + std::to_string(full_dump.size()) + " entries"); LOG_INFO("Number of imported entries: " + std::to_string(imported_ids.size())); LOG_INFO("Number of yet-to-be-imported entries: " + std::to_string(not_imported_ids.size())); std::set<std::string> buffer; std::transform(imported_ids.begin(), imported_ids.end(), std::inserter(buffer, buffer.begin()), [](unsigned int id) -> std::string { return std::to_string(id); }); LOG_INFO("\nImported entries: " + StringUtil::Join(buffer.begin(), buffer.end(), ",")); buffer.clear(); std::transform(not_imported_ids.begin(), not_imported_ids.end(), std::inserter(buffer, buffer.begin()), [](unsigned int id) -> std::string { return std::to_string(id); }); LOG_INFO("\nYet-to-be-imported entries: " + StringUtil::Join(buffer.begin(), buffer.end(), ",")); return EXIT_SUCCESS; } <|endoftext|>
<commit_before><commit_msg>Map and link in also the filterconfig1 UNO component<commit_after><|endoftext|>
<commit_before>#ifndef __DISRUPTOR_MULTITHREADEDCLAIMSTRATEGY_HPP__ #define __DISRUPTOR_MULTITHREADEDCLAIMSTRATEGY_HPP__ #include <stdexcept> #include "ClaimStrategy.hpp" #include "AbstractMultithreadedClaimStrategy.hpp" namespace disruptor { class MultiThreadedClaimStrategy : public AbstractMultithreadedClaimStrategy { static const int RETRIES = 1000; std::atomic_long* pendingPublication_; std::size_t pendingBufferSize_; int pendingMask_; public: /** * Construct a new multi-threaded publisher {@link ClaimStrategy} for a given buffer size. * * @param bufferSize for the underlying data structure. * @param pendingBufferSize number of item that can be pending for serialisation */ MultiThreadedClaimStrategy(const int bufferSize, const int pendingBufferSize) : AbstractMultithreadedClaimStrategy(bufferSize) , pendingPublication_(nullptr) , pendingBufferSize_(pendingBufferSize) , pendingMask_(pendingBufferSize - 1) { if (util::bitCount(pendingBufferSize) != 1) { throw std::out_of_range("pendingBufferSize must be a power of 2, was: " + pendingBufferSize_); } pendingPublication_ = new std::atomic_long[pendingBufferSize_]; } /** * Construct a new multi-threaded publisher {@link ClaimStrategy} for a given buffer size. * * @param bufferSize for the underlying data structure. */ MultiThreadedClaimStrategy(const int bufferSize) : AbstractMultithreadedClaimStrategy(bufferSize) , pendingPublication_(nullptr) , pendingBufferSize_(1024) , pendingMask_(pendingBufferSize_ - 1) { pendingPublication_ = new std::atomic_long[pendingBufferSize_]; } ~MultiThreadedClaimStrategy() { if (nullptr != pendingPublication_) { delete [] pendingPublication_; } } MultiThreadedClaimStrategy(const MultiThreadedClaimStrategy&) = delete; MultiThreadedClaimStrategy& operator=(const MultiThreadedClaimStrategy&) = delete; void serialisePublishing(const long sequence, Sequence& cursor, const int batchSize) { int counter = RETRIES; while ((sequence - cursor.get()) > (int)pendingBufferSize_) { if (--counter == 0) { std::this_thread::yield(); counter = RETRIES; } } long expectedSequence = sequence - batchSize; for (long pendingSequence = expectedSequence + 1; pendingSequence < sequence; pendingSequence++) { /* XXX: I *believe* store(..., std::memory_order_relaxed) to be the correct alternative to lazySet. Whether that is the reality, we shall see. */ pendingPublication_[(int) pendingSequence & pendingMask_].store(pendingSequence, std::memory_order_relaxed); } pendingPublication_[(int) sequence & pendingMask_].store(sequence); long cursorSequence = cursor.get(); if (cursorSequence >= sequence) { return; } expectedSequence = std::max(expectedSequence, cursorSequence); long nextSequence = expectedSequence + 1; while (cursor.compareAndSet(expectedSequence, nextSequence)) { expectedSequence = nextSequence; nextSequence++; if (pendingPublication_[(int) nextSequence & pendingMask_] != nextSequence) { break; } } } }; } #endif /* __DISRUPTOR_MULTITHREADEDCLAIMSTRATEGY_HPP__ */ <commit_msg>Cleanup - removed unnecessary header and formatting.<commit_after>#ifndef __DISRUPTOR_MULTITHREADEDCLAIMSTRATEGY_HPP__ #define __DISRUPTOR_MULTITHREADEDCLAIMSTRATEGY_HPP__ #include <stdexcept> #include "AbstractMultithreadedClaimStrategy.hpp" namespace disruptor { class MultiThreadedClaimStrategy : public AbstractMultithreadedClaimStrategy { static const int RETRIES = 1000; std::atomic_long* pendingPublication_; std::size_t pendingBufferSize_; int pendingMask_; public: /** * Construct a new multi-threaded publisher {@link ClaimStrategy} for a given buffer size. * * @param bufferSize for the underlying data structure. * @param pendingBufferSize number of item that can be pending for serialisation */ MultiThreadedClaimStrategy(const int bufferSize, const int pendingBufferSize) : AbstractMultithreadedClaimStrategy(bufferSize) , pendingPublication_(nullptr) , pendingBufferSize_(pendingBufferSize) , pendingMask_(pendingBufferSize - 1) { if (util::bitCount(pendingBufferSize) != 1) { throw std::out_of_range("pendingBufferSize must be a power of 2, was: " + pendingBufferSize_); } pendingPublication_ = new std::atomic_long[pendingBufferSize_]; } /** * Construct a new multi-threaded publisher {@link ClaimStrategy} for a given buffer size. * * @param bufferSize for the underlying data structure. */ MultiThreadedClaimStrategy(const int bufferSize) : AbstractMultithreadedClaimStrategy(bufferSize) , pendingPublication_(nullptr) , pendingBufferSize_(1024) , pendingMask_(pendingBufferSize_ - 1) { pendingPublication_ = new std::atomic_long[pendingBufferSize_]; } ~MultiThreadedClaimStrategy() { if (nullptr != pendingPublication_) { delete [] pendingPublication_; } } MultiThreadedClaimStrategy(const MultiThreadedClaimStrategy&) = delete; MultiThreadedClaimStrategy& operator=(const MultiThreadedClaimStrategy&) = delete; void serialisePublishing(const long sequence, Sequence& cursor, const int batchSize) { int counter = RETRIES; while ((sequence - cursor.get()) > (int)pendingBufferSize_) { if (--counter == 0) { std::this_thread::yield(); counter = RETRIES; } } long expectedSequence = sequence - batchSize; for (long pendingSequence = expectedSequence + 1; pendingSequence < sequence; pendingSequence++) { /* XXX: I *believe* store(..., std::memory_order_relaxed) to be the correct alternative to lazySet. Whether that is the reality, we shall see. */ pendingPublication_[(int) pendingSequence & pendingMask_].store(pendingSequence, std::memory_order_relaxed); } pendingPublication_[(int) sequence & pendingMask_].store(sequence); long cursorSequence = cursor.get(); if (cursorSequence >= sequence) { return; } expectedSequence = std::max(expectedSequence, cursorSequence); long nextSequence = expectedSequence + 1; while (cursor.compareAndSet(expectedSequence, nextSequence)) { expectedSequence = nextSequence; nextSequence++; if (pendingPublication_[(int) nextSequence & pendingMask_] != nextSequence) { break; } } } }; } #endif /* __DISRUPTOR_MULTITHREADEDCLAIMSTRATEGY_HPP__ */ <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/browser_main.h" #include "chrome/browser/browser_main_win.h" #include <windows.h> #include <shellapi.h> #include <algorithm> #include "app/l10n_util.h" #include "app/l10n_util_win.h" #include "app/win_util.h" #include "base/command_line.h" #include "base/environment.h" #include "base/i18n/rtl.h" #include "base/nss_util.h" #include "base/path_service.h" #include "base/scoped_ptr.h" #include "base/utf_string_conversions.h" #include "base/win/windows_version.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/first_run/first_run.h" #include "chrome/browser/metrics/metrics_service.h" #include "chrome/browser/views/uninstall_view.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/env_vars.h" #include "chrome/common/main_function_params.h" #include "chrome/common/result_codes.h" #include "chrome/installer/util/browser_distribution.h" #include "chrome/installer/util/helper.h" #include "chrome/installer/util/install_util.h" #include "chrome/installer/util/shell_util.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "net/base/winsock_init.h" #include "net/socket/ssl_client_socket_nss_factory.h" #include "views/focus/accelerator_handler.h" #include "views/window/window.h" void DidEndMainMessageLoop() { OleUninitialize(); } void RecordBreakpadStatusUMA(MetricsService* metrics) { DWORD len = ::GetEnvironmentVariableW( ASCIIToWide(env_vars::kNoOOBreakpad).c_str() , NULL, 0); metrics->RecordBreakpadRegistration((len == 0)); metrics->RecordBreakpadHasDebugger(TRUE == ::IsDebuggerPresent()); } void WarnAboutMinimumSystemRequirements() { if (base::win::GetVersion() < base::win::VERSION_XP) { // Display a warning message if the user is running chrome on Windows 2000. const std::wstring text = l10n_util::GetString(IDS_UNSUPPORTED_OS_PRE_WIN_XP); const std::wstring caption = l10n_util::GetString(IDS_PRODUCT_NAME); win_util::MessageBox(NULL, text, caption, MB_OK | MB_ICONWARNING | MB_TOPMOST); } } int AskForUninstallConfirmation() { int ret = ResultCodes::NORMAL_EXIT; views::Window::CreateChromeWindow(NULL, gfx::Rect(), new UninstallView(ret))->Show(); views::AcceleratorHandler accelerator_handler; MessageLoopForUI::current()->Run(&accelerator_handler); return ret; } void ShowCloseBrowserFirstMessageBox() { const std::wstring text = l10n_util::GetString(IDS_UNINSTALL_CLOSE_APP); const std::wstring caption = l10n_util::GetString(IDS_PRODUCT_NAME); const UINT flags = MB_OK | MB_ICONWARNING | MB_TOPMOST; win_util::MessageBox(NULL, text, caption, flags); } int DoUninstallTasks(bool chrome_still_running) { // We want to show a warning to user (and exit) if Chrome is already running // *before* we show the uninstall confirmation dialog box. But while the // uninstall confirmation dialog is up, user might start Chrome, so we // check once again after user acknowledges Uninstall dialog. if (chrome_still_running) { ShowCloseBrowserFirstMessageBox(); return ResultCodes::UNINSTALL_CHROME_ALIVE; } int ret = AskForUninstallConfirmation(); if (Upgrade::IsBrowserAlreadyRunning()) { ShowCloseBrowserFirstMessageBox(); return ResultCodes::UNINSTALL_CHROME_ALIVE; } if (ret != ResultCodes::UNINSTALL_USER_CANCEL) { // The following actions are just best effort. VLOG(1) << "Executing uninstall actions"; if (!FirstRun::RemoveSentinel()) VLOG(1) << "Failed to delete sentinel file."; // We want to remove user level shortcuts and we only care about the ones // created by us and not by the installer so |alternate| is false. BrowserDistribution* dist = BrowserDistribution::GetDistribution(); if (!ShellUtil::RemoveChromeDesktopShortcut(dist, ShellUtil::CURRENT_USER, false)) VLOG(1) << "Failed to delete desktop shortcut."; if (!ShellUtil::RemoveChromeQuickLaunchShortcut(dist, ShellUtil::CURRENT_USER)) VLOG(1) << "Failed to delete quick launch shortcut."; } return ret; } // Prepares the localized strings that are going to be displayed to // the user if the browser process dies. These strings are stored in the // environment block so they are accessible in the early stages of the // chrome executable's lifetime. void PrepareRestartOnCrashEnviroment(const CommandLine &parsed_command_line) { // Clear this var so child processes don't show the dialog by default. scoped_ptr<base::Environment> env(base::Environment::Create()); env->UnSetVar(env_vars::kShowRestart); // For non-interactive tests we don't restart on crash. if (env->HasVar(env_vars::kHeadless)) return; // If the known command-line test options are used we don't create the // environment block which means we don't get the restart dialog. if (parsed_command_line.HasSwitch(switches::kBrowserCrashTest) || parsed_command_line.HasSwitch(switches::kBrowserAssertTest) || parsed_command_line.HasSwitch(switches::kNoErrorDialogs)) return; // The encoding we use for the info is "title|context|direction" where // direction is either env_vars::kRtlLocale or env_vars::kLtrLocale depending // on the current locale. string16 dlg_strings(l10n_util::GetStringUTF16(IDS_CRASH_RECOVERY_TITLE)); dlg_strings.push_back('|'); string16 adjusted_string( l10n_util::GetStringUTF16(IDS_CRASH_RECOVERY_CONTENT)); base::i18n::AdjustStringForLocaleDirection(&adjusted_string); dlg_strings.append(adjusted_string); dlg_strings.push_back('|'); dlg_strings.append(ASCIIToUTF16( base::i18n::IsRTL() ? env_vars::kRtlLocale : env_vars::kLtrLocale)); env->SetVar(env_vars::kRestartInfo, UTF16ToUTF8(dlg_strings)); } // This method handles the --hide-icons and --show-icons command line options // for chrome that get triggered by Windows from registry entries // HideIconsCommand & ShowIconsCommand. Chrome doesn't support hide icons // functionality so we just ask the users if they want to uninstall Chrome. int HandleIconsCommands(const CommandLine &parsed_command_line) { if (parsed_command_line.HasSwitch(switches::kHideIcons)) { std::wstring cp_applet; base::win::Version version = base::win::GetVersion(); if (version >= base::win::VERSION_VISTA) { cp_applet.assign(L"Programs and Features"); // Windows Vista and later. } else if (version >= base::win::VERSION_XP) { cp_applet.assign(L"Add/Remove Programs"); // Windows XP. } else { return ResultCodes::UNSUPPORTED_PARAM; // Not supported } const std::wstring msg = l10n_util::GetStringF(IDS_HIDE_ICONS_NOT_SUPPORTED, cp_applet); const std::wstring caption = l10n_util::GetString(IDS_PRODUCT_NAME); const UINT flags = MB_OKCANCEL | MB_ICONWARNING | MB_TOPMOST; if (IDOK == win_util::MessageBox(NULL, msg, caption, flags)) ShellExecute(NULL, NULL, L"appwiz.cpl", NULL, NULL, SW_SHOWNORMAL); return ResultCodes::NORMAL_EXIT; // Exit as we are not launching browser. } // We don't hide icons so we shouldn't do anything special to show them return ResultCodes::UNSUPPORTED_PARAM; } // Check if there is any machine level Chrome installed on the current // machine. If yes and the current Chrome process is user level, we do not // allow the user level Chrome to run. So we notify the user and uninstall // user level Chrome. bool CheckMachineLevelInstall() { // TODO(tommi): Check if using the default distribution is always the right // thing to do. BrowserDistribution* dist = BrowserDistribution::GetDistribution(); scoped_ptr<installer::Version> version(InstallUtil::GetChromeVersion(dist, true)); if (version.get()) { FilePath exe_path; PathService::Get(base::DIR_EXE, &exe_path); std::wstring exe = exe_path.value(); FilePath user_exe_path(installer::GetChromeInstallPath(false, dist)); if (FilePath::CompareEqualIgnoreCase(exe, user_exe_path.value())) { const std::wstring text = l10n_util::GetString(IDS_MACHINE_LEVEL_INSTALL_CONFLICT); const std::wstring caption = l10n_util::GetString(IDS_PRODUCT_NAME); const UINT flags = MB_OK | MB_ICONERROR | MB_TOPMOST; win_util::MessageBox(NULL, text, caption, flags); FilePath uninstall_path(InstallUtil::GetChromeUninstallCmd(false, dist)); CommandLine uninstall_cmd(uninstall_path); if (!uninstall_cmd.GetProgram().value().empty()) { uninstall_cmd.AppendSwitch(installer_util::switches::kForceUninstall); uninstall_cmd.AppendSwitch( installer_util::switches::kDoNotRemoveSharedItems); base::LaunchApp(uninstall_cmd, false, false, NULL); } return true; } } return false; } // BrowserMainPartsWin --------------------------------------------------------- class BrowserMainPartsWin : public BrowserMainParts { public: explicit BrowserMainPartsWin(const MainFunctionParams& parameters) : BrowserMainParts(parameters) {} protected: virtual void PreEarlyInitialization() { // Initialize Winsock. net::EnsureWinsockInit(); } virtual void PreMainMessageLoopStart() { OleInitialize(NULL); // If we're running tests (ui_task is non-null), then the ResourceBundle // has already been initialized. if (!parameters().ui_task) { // Override the configured locale with the user's preferred UI language. l10n_util::OverrideLocaleWithUILanguageList(); } } private: virtual void InitializeSSL() { // Use NSS for SSL by default. // Because of a build system issue (http://crbug.com/43461), the default // client socket factory uses SChannel (the system SSL library) for SSL by // default on Windows. if (!parsed_command_line().HasSwitch(switches::kUseSystemSSL)) { net::ClientSocketFactory::SetSSLClientSocketFactory( net::SSLClientSocketNSSFactory); // We want to be sure to init NSPR on the main thread. base::EnsureNSPRInit(); } } }; // static BrowserMainParts* BrowserMainParts::CreateBrowserMainParts( const MainFunctionParams& parameters) { return new BrowserMainPartsWin(parameters); } <commit_msg>Use SChannel for Windows.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/browser_main.h" #include "chrome/browser/browser_main_win.h" #include <windows.h> #include <shellapi.h> #include <algorithm> #include "app/l10n_util.h" #include "app/l10n_util_win.h" #include "app/win_util.h" #include "base/command_line.h" #include "base/environment.h" #include "base/i18n/rtl.h" #include "base/nss_util.h" #include "base/path_service.h" #include "base/scoped_ptr.h" #include "base/utf_string_conversions.h" #include "base/win/windows_version.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/first_run/first_run.h" #include "chrome/browser/metrics/metrics_service.h" #include "chrome/browser/views/uninstall_view.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/env_vars.h" #include "chrome/common/main_function_params.h" #include "chrome/common/result_codes.h" #include "chrome/installer/util/browser_distribution.h" #include "chrome/installer/util/helper.h" #include "chrome/installer/util/install_util.h" #include "chrome/installer/util/shell_util.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "net/base/winsock_init.h" #include "net/socket/ssl_client_socket_nss_factory.h" #include "views/focus/accelerator_handler.h" #include "views/window/window.h" void DidEndMainMessageLoop() { OleUninitialize(); } void RecordBreakpadStatusUMA(MetricsService* metrics) { DWORD len = ::GetEnvironmentVariableW( ASCIIToWide(env_vars::kNoOOBreakpad).c_str() , NULL, 0); metrics->RecordBreakpadRegistration((len == 0)); metrics->RecordBreakpadHasDebugger(TRUE == ::IsDebuggerPresent()); } void WarnAboutMinimumSystemRequirements() { if (base::win::GetVersion() < base::win::VERSION_XP) { // Display a warning message if the user is running chrome on Windows 2000. const std::wstring text = l10n_util::GetString(IDS_UNSUPPORTED_OS_PRE_WIN_XP); const std::wstring caption = l10n_util::GetString(IDS_PRODUCT_NAME); win_util::MessageBox(NULL, text, caption, MB_OK | MB_ICONWARNING | MB_TOPMOST); } } int AskForUninstallConfirmation() { int ret = ResultCodes::NORMAL_EXIT; views::Window::CreateChromeWindow(NULL, gfx::Rect(), new UninstallView(ret))->Show(); views::AcceleratorHandler accelerator_handler; MessageLoopForUI::current()->Run(&accelerator_handler); return ret; } void ShowCloseBrowserFirstMessageBox() { const std::wstring text = l10n_util::GetString(IDS_UNINSTALL_CLOSE_APP); const std::wstring caption = l10n_util::GetString(IDS_PRODUCT_NAME); const UINT flags = MB_OK | MB_ICONWARNING | MB_TOPMOST; win_util::MessageBox(NULL, text, caption, flags); } int DoUninstallTasks(bool chrome_still_running) { // We want to show a warning to user (and exit) if Chrome is already running // *before* we show the uninstall confirmation dialog box. But while the // uninstall confirmation dialog is up, user might start Chrome, so we // check once again after user acknowledges Uninstall dialog. if (chrome_still_running) { ShowCloseBrowserFirstMessageBox(); return ResultCodes::UNINSTALL_CHROME_ALIVE; } int ret = AskForUninstallConfirmation(); if (Upgrade::IsBrowserAlreadyRunning()) { ShowCloseBrowserFirstMessageBox(); return ResultCodes::UNINSTALL_CHROME_ALIVE; } if (ret != ResultCodes::UNINSTALL_USER_CANCEL) { // The following actions are just best effort. VLOG(1) << "Executing uninstall actions"; if (!FirstRun::RemoveSentinel()) VLOG(1) << "Failed to delete sentinel file."; // We want to remove user level shortcuts and we only care about the ones // created by us and not by the installer so |alternate| is false. BrowserDistribution* dist = BrowserDistribution::GetDistribution(); if (!ShellUtil::RemoveChromeDesktopShortcut(dist, ShellUtil::CURRENT_USER, false)) VLOG(1) << "Failed to delete desktop shortcut."; if (!ShellUtil::RemoveChromeQuickLaunchShortcut(dist, ShellUtil::CURRENT_USER)) VLOG(1) << "Failed to delete quick launch shortcut."; } return ret; } // Prepares the localized strings that are going to be displayed to // the user if the browser process dies. These strings are stored in the // environment block so they are accessible in the early stages of the // chrome executable's lifetime. void PrepareRestartOnCrashEnviroment(const CommandLine &parsed_command_line) { // Clear this var so child processes don't show the dialog by default. scoped_ptr<base::Environment> env(base::Environment::Create()); env->UnSetVar(env_vars::kShowRestart); // For non-interactive tests we don't restart on crash. if (env->HasVar(env_vars::kHeadless)) return; // If the known command-line test options are used we don't create the // environment block which means we don't get the restart dialog. if (parsed_command_line.HasSwitch(switches::kBrowserCrashTest) || parsed_command_line.HasSwitch(switches::kBrowserAssertTest) || parsed_command_line.HasSwitch(switches::kNoErrorDialogs)) return; // The encoding we use for the info is "title|context|direction" where // direction is either env_vars::kRtlLocale or env_vars::kLtrLocale depending // on the current locale. string16 dlg_strings(l10n_util::GetStringUTF16(IDS_CRASH_RECOVERY_TITLE)); dlg_strings.push_back('|'); string16 adjusted_string( l10n_util::GetStringUTF16(IDS_CRASH_RECOVERY_CONTENT)); base::i18n::AdjustStringForLocaleDirection(&adjusted_string); dlg_strings.append(adjusted_string); dlg_strings.push_back('|'); dlg_strings.append(ASCIIToUTF16( base::i18n::IsRTL() ? env_vars::kRtlLocale : env_vars::kLtrLocale)); env->SetVar(env_vars::kRestartInfo, UTF16ToUTF8(dlg_strings)); } // This method handles the --hide-icons and --show-icons command line options // for chrome that get triggered by Windows from registry entries // HideIconsCommand & ShowIconsCommand. Chrome doesn't support hide icons // functionality so we just ask the users if they want to uninstall Chrome. int HandleIconsCommands(const CommandLine &parsed_command_line) { if (parsed_command_line.HasSwitch(switches::kHideIcons)) { std::wstring cp_applet; base::win::Version version = base::win::GetVersion(); if (version >= base::win::VERSION_VISTA) { cp_applet.assign(L"Programs and Features"); // Windows Vista and later. } else if (version >= base::win::VERSION_XP) { cp_applet.assign(L"Add/Remove Programs"); // Windows XP. } else { return ResultCodes::UNSUPPORTED_PARAM; // Not supported } const std::wstring msg = l10n_util::GetStringF(IDS_HIDE_ICONS_NOT_SUPPORTED, cp_applet); const std::wstring caption = l10n_util::GetString(IDS_PRODUCT_NAME); const UINT flags = MB_OKCANCEL | MB_ICONWARNING | MB_TOPMOST; if (IDOK == win_util::MessageBox(NULL, msg, caption, flags)) ShellExecute(NULL, NULL, L"appwiz.cpl", NULL, NULL, SW_SHOWNORMAL); return ResultCodes::NORMAL_EXIT; // Exit as we are not launching browser. } // We don't hide icons so we shouldn't do anything special to show them return ResultCodes::UNSUPPORTED_PARAM; } // Check if there is any machine level Chrome installed on the current // machine. If yes and the current Chrome process is user level, we do not // allow the user level Chrome to run. So we notify the user and uninstall // user level Chrome. bool CheckMachineLevelInstall() { // TODO(tommi): Check if using the default distribution is always the right // thing to do. BrowserDistribution* dist = BrowserDistribution::GetDistribution(); scoped_ptr<installer::Version> version(InstallUtil::GetChromeVersion(dist, true)); if (version.get()) { FilePath exe_path; PathService::Get(base::DIR_EXE, &exe_path); std::wstring exe = exe_path.value(); FilePath user_exe_path(installer::GetChromeInstallPath(false, dist)); if (FilePath::CompareEqualIgnoreCase(exe, user_exe_path.value())) { const std::wstring text = l10n_util::GetString(IDS_MACHINE_LEVEL_INSTALL_CONFLICT); const std::wstring caption = l10n_util::GetString(IDS_PRODUCT_NAME); const UINT flags = MB_OK | MB_ICONERROR | MB_TOPMOST; win_util::MessageBox(NULL, text, caption, flags); FilePath uninstall_path(InstallUtil::GetChromeUninstallCmd(false, dist)); CommandLine uninstall_cmd(uninstall_path); if (!uninstall_cmd.GetProgram().value().empty()) { uninstall_cmd.AppendSwitch(installer_util::switches::kForceUninstall); uninstall_cmd.AppendSwitch( installer_util::switches::kDoNotRemoveSharedItems); base::LaunchApp(uninstall_cmd, false, false, NULL); } return true; } } return false; } // BrowserMainPartsWin --------------------------------------------------------- class BrowserMainPartsWin : public BrowserMainParts { public: explicit BrowserMainPartsWin(const MainFunctionParams& parameters) : BrowserMainParts(parameters) {} protected: virtual void PreEarlyInitialization() { // Initialize Winsock. net::EnsureWinsockInit(); } virtual void PreMainMessageLoopStart() { OleInitialize(NULL); // If we're running tests (ui_task is non-null), then the ResourceBundle // has already been initialized. if (!parameters().ui_task) { // Override the configured locale with the user's preferred UI language. l10n_util::OverrideLocaleWithUILanguageList(); } } private: virtual void InitializeSSL() { // Use NSS for SSL by default. // Because of a build system issue (http://crbug.com/43461), the default // client socket factory uses SChannel (the system SSL library) for SSL by // default on Windows. // Disabling this temporarily to test out if NSS is causing heap corruption. #if 0 if (!parsed_command_line().HasSwitch(switches::kUseSystemSSL)) { net::ClientSocketFactory::SetSSLClientSocketFactory( net::SSLClientSocketNSSFactory); // We want to be sure to init NSPR on the main thread. base::EnsureNSPRInit(); } #endif } }; // static BrowserMainParts* BrowserMainParts::CreateBrowserMainParts( const MainFunctionParams& parameters) { return new BrowserMainPartsWin(parameters); } <|endoftext|>
<commit_before><commit_msg>The table was deleted after the model and the table accesses the model in its destructor, causing a failure in the browser tests.<commit_after><|endoftext|>
<commit_before>/* * examples/nullspacebasis.C * * Copyright (C) 2014 J-G. Dumas * ========LICENCE======== * This file is part of the library LinBox. * * LinBox is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ========LICENCE======== */ /**\file examples/nullspacebasis.C * @example examples/nullspacebasis_rank.C \brief NullSpace of sparse matrix over GFq. \brief nullspace is allocated m \times n. \ingroup examples */ #include <iostream> #include "linbox/field/Givaro/givaro-gfq.h" #include "linbox/algorithms/gauss.h" using namespace LinBox; int main (int argc, char **argv) { if ( argc < 2 || argc > 4) { std::cerr << "Usage to get a random null space basis over GF(p,k): <matrix-file-in-SMS-format> p [k]" << std::endl; return -1; } std::ifstream input (argv[1]); if (!input) { std::cerr << "Error opening matrix file " << argv[1] << std::endl; return -1; } //typedef Modular<int> Field; typedef GivaroGfq Field; Field F(atoi(argv[2]),argc>3?atoi(argv[3]):1); SparseMatrix<Field, SparseMatrixFormat::SparseSeq > B (F); B.read (input); std::cout << "B is " << B.rowdim() << " by " << B.coldim() << std::endl; BlasMatrix<Field> NullSpace(F,B.coldim(),B.coldim()); GaussDomain<Field> GD(F); GD.nullspacebasisin(NullSpace, B); NullSpace.write( std::cerr << "X:=", Tag::FileFormat::Maple ) << ';' << std::endl; std::cerr << "NullsSpace dimensions:" << NullSpace.rowdim() << 'x' << NullSpace.coldim() << std::endl; return 0; } <commit_msg>licence<commit_after>/* * examples/nullspacebasis.C * * Copyright (C) 2014 J-G. Dumas * ========LICENCE======== * This file is part of the library LinBox. * * LinBox is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ========LICENCE======== */ /**\file examples/nullspacebasis.C * @example examples/nullspacebasis.C \brief NullSpace of sparse matrix over GFq. \brief nullspace is allocated m \times n. \ingroup examples */ #include <iostream> #include "linbox/field/Givaro/givaro-gfq.h" #include "linbox/algorithms/gauss.h" using namespace LinBox; int main (int argc, char **argv) { if ( argc < 2 || argc > 4) { std::cerr << "Usage to get a random null space basis over GF(p,k): <matrix-file-in-SMS-format> p [k]" << std::endl; return -1; } std::ifstream input (argv[1]); if (!input) { std::cerr << "Error opening matrix file " << argv[1] << std::endl; return -1; } //typedef Modular<int> Field; typedef GivaroGfq Field; Field F(atoi(argv[2]),argc>3?atoi(argv[3]):1); SparseMatrix<Field, SparseMatrixFormat::SparseSeq > B (F); B.read (input); std::cout << "B is " << B.rowdim() << " by " << B.coldim() << std::endl; BlasMatrix<Field> NullSpace(F,B.coldim(),B.coldim()); GaussDomain<Field> GD(F); GD.nullspacebasisin(NullSpace, B); NullSpace.write( std::cerr << "X:=", Tag::FileFormat::Maple ) << ';' << std::endl; std::cerr << "NullsSpace dimensions:" << NullSpace.rowdim() << 'x' << NullSpace.coldim() << std::endl; return 0; } <|endoftext|>
<commit_before>//===-- Symbols.cpp ---------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "lldb/Host/Symbols.h" #include "lldb/Core/ArchSpec.h" #include "lldb/Core/DataBuffer.h" #include "lldb/Core/DataExtractor.h" #include "lldb/Core/Module.h" #include "lldb/Core/ModuleSpec.h" #include "lldb/Core/StreamString.h" #include "lldb/Core/Timer.h" #include "lldb/Core/UUID.h" #include "lldb/Symbol/ObjectFile.h" #include "lldb/Target/Target.h" using namespace lldb; using namespace lldb_private; #if defined (__linux__) || defined (__FreeBSD__) FileSpec Symbols::LocateExecutableObjectFile (const ModuleSpec &module_spec) { // FIXME return FileSpec(); } FileSpec Symbols::LocateExecutableSymbolFile (const ModuleSpec &module_spec) { const char *symbol_filename = module_spec.GetSymbolFileSpec().GetFilename().AsCString(); if (!symbol_filename || !symbol_filename[0]) return FileSpec(); FileSpecList debug_file_search_paths (Target::GetDefaultDebugFileSearchPaths()); // Add module directory. const ConstString &file_dir = module_spec.GetFileSpec().GetDirectory(); debug_file_search_paths.AppendIfUnique (FileSpec(file_dir.AsCString("."), true)); // Add current working directory. debug_file_search_paths.AppendIfUnique (FileSpec(".", true)); // Add /usr/lib/debug directory. debug_file_search_paths.AppendIfUnique (FileSpec("/usr/lib/debug", true)); std::string uuid_str; const UUID &module_uuid = module_spec.GetUUID(); if (module_uuid.IsValid()) { // Some debug files are stored in the .build-id directory like this: // /usr/lib/debug/.build-id/ff/e7fe727889ad82bb153de2ad065b2189693315.debug uuid_str = module_uuid.GetAsString(""); uuid_str.insert (2, 1, '/'); uuid_str = uuid_str + ".debug"; } // Get full path to our module. Needed to check debug files like this: // /usr/lib/debug/usr/lib/libboost_date_time.so.1.46.1 std::string module_filename = module_spec.GetFileSpec().GetPath(); size_t num_directories = debug_file_search_paths.GetSize(); for (size_t idx = 0; idx < num_directories; ++idx) { FileSpec dirspec = debug_file_search_paths.GetFileSpecAtIndex (idx); dirspec.ResolvePath(); if (!dirspec.Exists() || !dirspec.IsDirectory()) continue; std::vector<std::string> files; std::string dirname = dirspec.GetPath(); files.push_back (dirname + "/" + symbol_filename); files.push_back (dirname + "/.debug/" + symbol_filename); files.push_back (dirname + "/.build-id/" + uuid_str); files.push_back (dirname + module_filename); const uint32_t num_files = files.size(); for (size_t idx_file = 0; idx_file < num_files; ++idx_file) { const std::string &filename = files[idx_file]; FileSpec file_spec (filename.c_str(), true); if (file_spec == module_spec.GetFileSpec()) continue; if (file_spec.Exists()) { lldb_private::ModuleSpecList specs; const size_t num_specs = ObjectFile::GetModuleSpecifications (file_spec, 0, specs); assert (num_specs <= 1 && "Symbol Vendor supports only a single architecture"); if (num_specs == 1) { ModuleSpec mspec; if (specs.GetModuleSpecAtIndex (0, mspec)) { if (mspec.GetUUID() == module_uuid) return file_spec; } } } } } return FileSpec(); } FileSpec Symbols::FindSymbolFileInBundle (const FileSpec& symfile_bundle, const lldb_private::UUID *uuid, const ArchSpec *arch) { // FIXME return FileSpec(); } bool Symbols::DownloadObjectAndSymbolFile (ModuleSpec &module_spec, bool force_lookup) { // Fill in the module_spec.GetFileSpec() for the object file and/or the // module_spec.GetSymbolFileSpec() for the debug symbols file. return false; } #elif !defined (__APPLE__) FileSpec Symbols::LocateExecutableObjectFile (const ModuleSpec &module_spec) { // FIXME return FileSpec(); } FileSpec Symbols::LocateExecutableSymbolFile (const ModuleSpec &module_spec) { // FIXME return FileSpec(); } FileSpec Symbols::FindSymbolFileInBundle (const FileSpec& symfile_bundle, const lldb_private::UUID *uuid, const ArchSpec *arch) { return FileSpec(); } bool Symbols::DownloadObjectAndSymbolFile (ModuleSpec &module_spec, bool force_lookup) { // Fill in the module_spec.GetFileSpec() for the object file and/or the // module_spec.GetSymbolFileSpec() for the debug symbols file. return false; } #endif <commit_msg>Missed a checking that should have been checked in with 186211.<commit_after>//===-- Symbols.cpp ---------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "lldb/Host/Symbols.h" #include "lldb/Core/ArchSpec.h" #include "lldb/Core/DataBuffer.h" #include "lldb/Core/DataExtractor.h" #include "lldb/Core/Module.h" #include "lldb/Core/ModuleSpec.h" #include "lldb/Core/StreamString.h" #include "lldb/Core/Timer.h" #include "lldb/Core/UUID.h" #include "lldb/Symbol/ObjectFile.h" #include "lldb/Target/Target.h" using namespace lldb; using namespace lldb_private; #if defined (__linux__) || defined (__FreeBSD__) FileSpec Symbols::LocateExecutableObjectFile (const ModuleSpec &module_spec) { // FIXME return FileSpec(); } FileSpec Symbols::LocateExecutableSymbolFile (const ModuleSpec &module_spec) { const char *symbol_filename = module_spec.GetSymbolFileSpec().GetFilename().AsCString(); if (!symbol_filename || !symbol_filename[0]) return FileSpec(); FileSpecList debug_file_search_paths (Target::GetDefaultDebugFileSearchPaths()); // Add module directory. const ConstString &file_dir = module_spec.GetFileSpec().GetDirectory(); debug_file_search_paths.AppendIfUnique (FileSpec(file_dir.AsCString("."), true)); // Add current working directory. debug_file_search_paths.AppendIfUnique (FileSpec(".", true)); // Add /usr/lib/debug directory. debug_file_search_paths.AppendIfUnique (FileSpec("/usr/lib/debug", true)); std::string uuid_str; const UUID &module_uuid = module_spec.GetUUID(); if (module_uuid.IsValid()) { // Some debug files are stored in the .build-id directory like this: // /usr/lib/debug/.build-id/ff/e7fe727889ad82bb153de2ad065b2189693315.debug uuid_str = module_uuid.GetAsString(""); uuid_str.insert (2, 1, '/'); uuid_str = uuid_str + ".debug"; } // Get full path to our module. Needed to check debug files like this: // /usr/lib/debug/usr/lib/libboost_date_time.so.1.46.1 std::string module_filename = module_spec.GetFileSpec().GetPath(); size_t num_directories = debug_file_search_paths.GetSize(); for (size_t idx = 0; idx < num_directories; ++idx) { FileSpec dirspec = debug_file_search_paths.GetFileSpecAtIndex (idx); dirspec.ResolvePath(); if (!dirspec.Exists() || !dirspec.IsDirectory()) continue; std::vector<std::string> files; std::string dirname = dirspec.GetPath(); files.push_back (dirname + "/" + symbol_filename); files.push_back (dirname + "/.debug/" + symbol_filename); files.push_back (dirname + "/.build-id/" + uuid_str); files.push_back (dirname + module_filename); const uint32_t num_files = files.size(); for (size_t idx_file = 0; idx_file < num_files; ++idx_file) { const std::string &filename = files[idx_file]; FileSpec file_spec (filename.c_str(), true); if (file_spec == module_spec.GetFileSpec()) continue; if (file_spec.Exists()) { lldb_private::ModuleSpecList specs; const size_t num_specs = ObjectFile::GetModuleSpecifications (file_spec, 0, 0, specs); assert (num_specs <= 1 && "Symbol Vendor supports only a single architecture"); if (num_specs == 1) { ModuleSpec mspec; if (specs.GetModuleSpecAtIndex (0, mspec)) { if (mspec.GetUUID() == module_uuid) return file_spec; } } } } } return FileSpec(); } FileSpec Symbols::FindSymbolFileInBundle (const FileSpec& symfile_bundle, const lldb_private::UUID *uuid, const ArchSpec *arch) { // FIXME return FileSpec(); } bool Symbols::DownloadObjectAndSymbolFile (ModuleSpec &module_spec, bool force_lookup) { // Fill in the module_spec.GetFileSpec() for the object file and/or the // module_spec.GetSymbolFileSpec() for the debug symbols file. return false; } #elif !defined (__APPLE__) FileSpec Symbols::LocateExecutableObjectFile (const ModuleSpec &module_spec) { // FIXME return FileSpec(); } FileSpec Symbols::LocateExecutableSymbolFile (const ModuleSpec &module_spec) { // FIXME return FileSpec(); } FileSpec Symbols::FindSymbolFileInBundle (const FileSpec& symfile_bundle, const lldb_private::UUID *uuid, const ArchSpec *arch) { return FileSpec(); } bool Symbols::DownloadObjectAndSymbolFile (ModuleSpec &module_spec, bool force_lookup) { // Fill in the module_spec.GetFileSpec() for the object file and/or the // module_spec.GetSymbolFileSpec() for the debug symbols file. return false; } #endif <|endoftext|>
<commit_before>// $Id: TCPTransfer_test.C,v 1.12 2002/01/09 12:22:17 amoll Exp $ #include <BALL/CONCEPT/classTest.h> /////////////////////////// #include <BALL/SYSTEM/TCPTransfer.h> #include <BALL/SYSTEM/file.h> /////////////////////////// using namespace BALL; using namespace std; // include a helper class testing for network availability // (or more precisely: the ability to perform HTTP or FTP transfers) #include "networkTest.h" START_TEST(TCPTransfer, "$Id: TCPTransfer_test.C,v 1.12 2002/01/09 12:22:17 amoll Exp $") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// TCPTransfer* tcp_ptr; CHECK(cstr) tcp_ptr = new TCPTransfer; TEST_NOT_EQUAL(tcp_ptr, 0) TEST_EQUAL(tcp_ptr->getStatusCode(), TCPTransfer::UNINITIALIZED_ERROR) RESULT CHECK(~TCPTransfer_test) delete tcp_ptr; RESULT CHECK(set(ofstream& file, const String& address)) ABORT_IF(!NetworkTest::test("www.mpi-sb.mpg.de", NetworkTest::HTTP)) TCPTransfer tcp_t; ofstream out; tcp_t.set(out, "http://www.mpi-sb.mpg.de/BALL/test/http_test.txt"); TEST_EQUAL(tcp_t.getHostAddress(), "www.mpi-sb.mpg.de") TEST_EQUAL(tcp_t.getFileAddress(), "/BALL/test/http_test.txt") TEST_EQUAL(tcp_t.getPort(), 80) TEST_EQUAL(tcp_t.getStatusCode(), TCPTransfer::NO_ERROR) TEST_EQUAL(tcp_t.getReceivedBytes(), 0) TEST_EQUAL(tcp_t.getLogin(), "") TEST_EQUAL(tcp_t.getPassword(), "") TEST_EQUAL(tcp_t.getStream(), &out) RESULT CHECK(http/no login) ABORT_IF(!NetworkTest::test("www.mpi-sb.mpg.de", NetworkTest::HTTP)) String filename; File::createTemporaryFilename(filename); ofstream out(filename.c_str(), std::ios::out); TCPTransfer tcp_t(out ,"http://www.mpi-sb.mpg.de/BALL/test/http_test.txt" , false); TEST_EQUAL(tcp_t.getHostAddress(), "www.mpi-sb.mpg.de") TEST_EQUAL(tcp_t.getFileAddress(), "/BALL/test/http_test.txt") TEST_EQUAL(tcp_t.getPort(), 80) TEST_EQUAL(tcp_t.getStatusCode(), TCPTransfer::NO_ERROR) TEST_EQUAL(tcp_t.getReceivedBytes(), 3048) TEST_EQUAL(tcp_t.getLogin(), "") TEST_EQUAL(tcp_t.getPassword(), "") out.close(); TEST_FILE(filename.c_str(), "data/http_test.txt", false) RESULT CHECK(http/login) ABORT_IF(!NetworkTest::test("www.mpi-sb.mpg.de", NetworkTest::HTTP)) String filename; File::createTemporaryFilename(filename); ofstream out(filename.c_str(), std::ios::out); TCPTransfer tcp_t2(out ,"http://BALL:test@www.mpi-sb.mpg.de/BALL/INTERNAL/internal.html", true); TEST_EQUAL(tcp_t2.getHostAddress(), "www.mpi-sb.mpg.de") TEST_EQUAL(tcp_t2.getFileAddress(), "/BALL/INTERNAL/internal.html") TEST_EQUAL(tcp_t2.getPort(), 80) TEST_EQUAL(tcp_t2.getStatusCode(), TCPTransfer::NO_ERROR) //?????, waiting for www-server config //TEST_EQUAL(tcp_t2.getReceivedBytes(), 11908) TEST_EQUAL(tcp_t2.getLogin(), "BALL") TEST_EQUAL(tcp_t2.getPassword(), "test") out.close(); RESULT CHECK(ftp) ABORT_IF(!NetworkTest::test("ftp.mpi-sb.mpg.de", NetworkTest::FTP)) String filename; File::createTemporaryFilename(filename); ofstream out(filename.c_str(), std::ios::out); TCPTransfer tcp_t(out, "ftp://ftp.mpi-sb.mpg.de/pub/outgoing/BALL/ftp_test.txt"); TEST_EQUAL(tcp_t.getHostAddress(), "ftp.mpi-sb.mpg.de") TEST_EQUAL(tcp_t.getFileAddress(), "/pub/outgoing/BALL/ftp_test.txt") TEST_EQUAL(tcp_t.getPort(), 21) TEST_EQUAL(tcp_t.getStatusCode(), TCPTransfer::NO_ERROR) TEST_EQUAL(tcp_t.getReceivedBytes(), 2312) TEST_EQUAL(tcp_t.getLogin(), "") TEST_EQUAL(tcp_t.getPassword(), "") TEST_EQUAL(tcp_t.getStream(), &out) out.close(); TEST_FILE(filename.c_str(), "data/ftp_test.txt", false) RESULT ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST <commit_msg>fixed: removed superfluous test for network in set test<commit_after>// $Id: TCPTransfer_test.C,v 1.13 2002/01/09 12:27:03 amoll Exp $ #include <BALL/CONCEPT/classTest.h> /////////////////////////// #include <BALL/SYSTEM/TCPTransfer.h> #include <BALL/SYSTEM/file.h> /////////////////////////// using namespace BALL; using namespace std; // include a helper class testing for network availability // (or more precisely: the ability to perform HTTP or FTP transfers) #include "networkTest.h" START_TEST(TCPTransfer, "$Id: TCPTransfer_test.C,v 1.13 2002/01/09 12:27:03 amoll Exp $") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// TCPTransfer* tcp_ptr; CHECK(cstr) tcp_ptr = new TCPTransfer; TEST_NOT_EQUAL(tcp_ptr, 0) TEST_EQUAL(tcp_ptr->getStatusCode(), TCPTransfer::UNINITIALIZED_ERROR) RESULT CHECK(~TCPTransfer_test) delete tcp_ptr; RESULT CHECK(set(ofstream& file, const String& address)) TCPTransfer tcp_t; ofstream out; tcp_t.set(out, "http://www.mpi-sb.mpg.de/BALL/test/http_test.txt"); TEST_EQUAL(tcp_t.getHostAddress(), "www.mpi-sb.mpg.de") TEST_EQUAL(tcp_t.getFileAddress(), "/BALL/test/http_test.txt") TEST_EQUAL(tcp_t.getPort(), 80) TEST_EQUAL(tcp_t.getStatusCode(), TCPTransfer::NO_ERROR) TEST_EQUAL(tcp_t.getReceivedBytes(), 0) TEST_EQUAL(tcp_t.getLogin(), "") TEST_EQUAL(tcp_t.getPassword(), "") TEST_EQUAL(tcp_t.getStream(), &out) RESULT CHECK(http/no login) ABORT_IF(!NetworkTest::test("www.mpi-sb.mpg.de", NetworkTest::HTTP)) String filename; File::createTemporaryFilename(filename); ofstream out(filename.c_str(), std::ios::out); TCPTransfer tcp_t(out ,"http://www.mpi-sb.mpg.de/BALL/test/http_test.txt" , false); TEST_EQUAL(tcp_t.getHostAddress(), "www.mpi-sb.mpg.de") TEST_EQUAL(tcp_t.getFileAddress(), "/BALL/test/http_test.txt") TEST_EQUAL(tcp_t.getPort(), 80) TEST_EQUAL(tcp_t.getStatusCode(), TCPTransfer::NO_ERROR) TEST_EQUAL(tcp_t.getReceivedBytes(), 3048) TEST_EQUAL(tcp_t.getLogin(), "") TEST_EQUAL(tcp_t.getPassword(), "") out.close(); TEST_FILE(filename.c_str(), "data/http_test.txt", false) RESULT CHECK(http/login) ABORT_IF(!NetworkTest::test("www.mpi-sb.mpg.de", NetworkTest::HTTP)) String filename; File::createTemporaryFilename(filename); ofstream out(filename.c_str(), std::ios::out); TCPTransfer tcp_t2(out ,"http://BALL:test@www.mpi-sb.mpg.de/BALL/INTERNAL/internal.html", true); TEST_EQUAL(tcp_t2.getHostAddress(), "www.mpi-sb.mpg.de") TEST_EQUAL(tcp_t2.getFileAddress(), "/BALL/INTERNAL/internal.html") TEST_EQUAL(tcp_t2.getPort(), 80) TEST_EQUAL(tcp_t2.getStatusCode(), TCPTransfer::NO_ERROR) //?????, waiting for www-server config //TEST_EQUAL(tcp_t2.getReceivedBytes(), 11908) TEST_EQUAL(tcp_t2.getLogin(), "BALL") TEST_EQUAL(tcp_t2.getPassword(), "test") out.close(); RESULT CHECK(ftp) ABORT_IF(!NetworkTest::test("ftp.mpi-sb.mpg.de", NetworkTest::FTP)) String filename; File::createTemporaryFilename(filename); ofstream out(filename.c_str(), std::ios::out); TCPTransfer tcp_t(out, "ftp://ftp.mpi-sb.mpg.de/pub/outgoing/BALL/ftp_test.txt"); TEST_EQUAL(tcp_t.getHostAddress(), "ftp.mpi-sb.mpg.de") TEST_EQUAL(tcp_t.getFileAddress(), "/pub/outgoing/BALL/ftp_test.txt") TEST_EQUAL(tcp_t.getPort(), 21) TEST_EQUAL(tcp_t.getStatusCode(), TCPTransfer::NO_ERROR) TEST_EQUAL(tcp_t.getReceivedBytes(), 2312) TEST_EQUAL(tcp_t.getLogin(), "") TEST_EQUAL(tcp_t.getPassword(), "") TEST_EQUAL(tcp_t.getStream(), &out) out.close(); TEST_FILE(filename.c_str(), "data/ftp_test.txt", false) RESULT ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST <|endoftext|>
<commit_before>//===--------------------- ModuleCache.cpp ----------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "ModuleCache.h" #include "lldb/Core/Log.h" #include "lldb/Core/Module.h" #include "lldb/Core/ModuleList.h" #include "lldb/Core/ModuleSpec.h" #include "lldb/Host/File.h" #include "lldb/Host/FileSystem.h" #include "lldb/Host/LockFile.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/FileUtilities.h" #include <assert.h> #include <cstdio> using namespace lldb; using namespace lldb_private; namespace { const char* kModulesSubdir = ".cache"; const char* kLockDirName = ".lock"; const char* kTempFileName = ".temp"; const char* kTempSymFileName = ".symtemp"; const char* kSymFileExtension = ".sym"; class ModuleLock { private: File m_file; std::unique_ptr<lldb_private::LockFile> m_lock; FileSpec m_file_spec; public: ModuleLock (const FileSpec &root_dir_spec, const UUID &uuid, Error& error); void Delete (); }; FileSpec JoinPath (const FileSpec &path1, const char* path2) { FileSpec result_spec (path1); result_spec.AppendPathComponent (path2); return result_spec; } Error MakeDirectory (const FileSpec &dir_path) { if (dir_path.Exists ()) { if (!dir_path.IsDirectory ()) return Error ("Invalid existing path"); return Error (); } return FileSystem::MakeDirectory(dir_path, eFilePermissionsDirectoryDefault); } FileSpec GetModuleDirectory (const FileSpec &root_dir_spec, const UUID &uuid) { const auto modules_dir_spec = JoinPath (root_dir_spec, kModulesSubdir); return JoinPath (modules_dir_spec, uuid.GetAsString ().c_str ()); } FileSpec GetSymbolFileSpec(const FileSpec& module_file_spec) { return FileSpec((module_file_spec.GetPath() + kSymFileExtension).c_str(), false); } void DeleteExistingModule (const FileSpec &root_dir_spec, const FileSpec &sysroot_module_path_spec) { Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_MODULES)); UUID module_uuid; { auto module_sp = std::make_shared<Module>(ModuleSpec (sysroot_module_path_spec)); module_uuid = module_sp->GetUUID (); } if (!module_uuid.IsValid ()) return; Error error; ModuleLock lock (root_dir_spec, module_uuid, error); if (error.Fail ()) { if (log) log->Printf ("Failed to lock module %s: %s", module_uuid.GetAsString ().c_str (), error.AsCString ()); } auto link_count = FileSystem::GetHardlinkCount (sysroot_module_path_spec); if (link_count == -1) return; if (link_count > 2) // module is referred by other hosts. return; const auto module_spec_dir = GetModuleDirectory (root_dir_spec, module_uuid); FileSystem::DeleteDirectory (module_spec_dir, true); lock.Delete(); } void DecrementRefExistingModule (const FileSpec &root_dir_spec, const FileSpec &sysroot_module_path_spec) { // Remove $platform/.cache/$uuid folder if nobody else references it. DeleteExistingModule (root_dir_spec, sysroot_module_path_spec); // Remove sysroot link. FileSystem::Unlink (sysroot_module_path_spec); FileSpec symfile_spec = GetSymbolFileSpec (sysroot_module_path_spec); if (symfile_spec.Exists ()) // delete module's symbol file if exists. FileSystem::Unlink (symfile_spec); } Error CreateHostSysRootModuleLink (const FileSpec &root_dir_spec, const char *hostname, const FileSpec &platform_module_spec, const FileSpec &local_module_spec, bool delete_existing) { const auto sysroot_module_path_spec = JoinPath ( JoinPath (root_dir_spec, hostname), platform_module_spec.GetPath ().c_str ()); if (sysroot_module_path_spec.Exists()) { if (!delete_existing) return Error (); DecrementRefExistingModule (root_dir_spec, sysroot_module_path_spec); } const auto error = MakeDirectory (FileSpec (sysroot_module_path_spec.GetDirectory ().AsCString (), false)); if (error.Fail ()) return error; return FileSystem::Hardlink(sysroot_module_path_spec, local_module_spec); } } // namespace ModuleLock::ModuleLock (const FileSpec &root_dir_spec, const UUID &uuid, Error& error) { const auto lock_dir_spec = JoinPath (root_dir_spec, kLockDirName); error = MakeDirectory (lock_dir_spec); if (error.Fail ()) return; m_file_spec = JoinPath (lock_dir_spec, uuid.GetAsString ().c_str ()); m_file.Open (m_file_spec.GetCString (), File::eOpenOptionWrite | File::eOpenOptionCanCreate | File::eOpenOptionCloseOnExec); if (!m_file) { error.SetErrorToErrno (); return; } m_lock.reset (new lldb_private::LockFile (m_file.GetDescriptor ())); error = m_lock->WriteLock (0, 1); if (error.Fail ()) error.SetErrorStringWithFormat ("Failed to lock file: %s", error.AsCString ()); } void ModuleLock::Delete () { if (!m_file) return; m_file.Close (); FileSystem::Unlink (m_file_spec); } ///////////////////////////////////////////////////////////////////////// Error ModuleCache::Put (const FileSpec &root_dir_spec, const char *hostname, const ModuleSpec &module_spec, const FileSpec &tmp_file, const FileSpec &target_file) { const auto module_spec_dir = GetModuleDirectory (root_dir_spec, module_spec.GetUUID ()); const auto module_file_path = JoinPath (module_spec_dir, target_file.GetFilename ().AsCString ()); const auto tmp_file_path = tmp_file.GetPath (); const auto err_code = llvm::sys::fs::rename (tmp_file_path.c_str (), module_file_path.GetPath ().c_str ()); if (err_code) return Error ("Failed to rename file %s to %s: %s", tmp_file_path.c_str (), module_file_path.GetPath ().c_str (), err_code.message ().c_str ()); const auto error = CreateHostSysRootModuleLink(root_dir_spec, hostname, target_file, module_file_path, true); if (error.Fail ()) return Error ("Failed to create link to %s: %s", module_file_path.GetPath ().c_str (), error.AsCString ()); return Error (); } Error ModuleCache::Get (const FileSpec &root_dir_spec, const char *hostname, const ModuleSpec &module_spec, ModuleSP &cached_module_sp, bool *did_create_ptr) { const auto find_it = m_loaded_modules.find (module_spec.GetUUID ().GetAsString()); if (find_it != m_loaded_modules.end ()) { cached_module_sp = (*find_it).second.lock (); if (cached_module_sp) return Error (); m_loaded_modules.erase (find_it); } const auto module_spec_dir = GetModuleDirectory (root_dir_spec, module_spec.GetUUID ()); const auto module_file_path = JoinPath (module_spec_dir, module_spec.GetFileSpec ().GetFilename ().AsCString ()); if (!module_file_path.Exists ()) return Error ("Module %s not found", module_file_path.GetPath ().c_str ()); if (module_file_path.GetByteSize () != module_spec.GetObjectSize ()) return Error ("Module %s has invalid file size", module_file_path.GetPath ().c_str ()); // We may have already cached module but downloaded from an another host - in this case let's create a link to it. auto error = CreateHostSysRootModuleLink(root_dir_spec, hostname, module_spec.GetFileSpec(), module_file_path, false); if (error.Fail ()) return Error ("Failed to create link to %s: %s", module_file_path.GetPath().c_str(), error.AsCString()); auto cached_module_spec (module_spec); cached_module_spec.GetUUID ().Clear (); // Clear UUID since it may contain md5 content hash instead of real UUID. cached_module_spec.GetFileSpec () = module_file_path; cached_module_spec.GetPlatformFileSpec () = module_spec.GetFileSpec (); error = ModuleList::GetSharedModule(cached_module_spec, cached_module_sp, nullptr, nullptr, did_create_ptr, false); if (error.Fail()) return error; FileSpec symfile_spec = GetSymbolFileSpec(cached_module_sp->GetFileSpec ()); if (symfile_spec.Exists ()) cached_module_sp->SetSymbolFileFileSpec (symfile_spec); m_loaded_modules.insert (std::make_pair (module_spec.GetUUID ().GetAsString (), cached_module_sp)); return Error (); } Error ModuleCache::GetAndPut (const FileSpec &root_dir_spec, const char *hostname, const ModuleSpec &module_spec, const ModuleDownloader &module_downloader, const SymfileDownloader &symfile_downloader, lldb::ModuleSP &cached_module_sp, bool *did_create_ptr) { const auto module_spec_dir = GetModuleDirectory (root_dir_spec, module_spec.GetUUID ()); auto error = MakeDirectory (module_spec_dir); if (error.Fail ()) return error; ModuleLock lock (root_dir_spec, module_spec.GetUUID (), error); if (error.Fail ()) return Error("Failed to lock module %s: %s", module_spec.GetUUID ().GetAsString().c_str(), error.AsCString ()); // Check local cache for a module. error = Get (root_dir_spec, hostname, module_spec, cached_module_sp, did_create_ptr); if (error.Success ()) return error; const auto tmp_download_file_spec = JoinPath (module_spec_dir, kTempFileName); error = module_downloader (module_spec, tmp_download_file_spec); llvm::FileRemover tmp_file_remover (tmp_download_file_spec.GetPath ().c_str ()); if (error.Fail ()) return Error("Failed to download module: %s", error.AsCString ()); // Put downloaded file into local module cache. error = Put (root_dir_spec, hostname, module_spec, tmp_download_file_spec, module_spec.GetFileSpec ()); if (error.Fail ()) return Error ("Failed to put module into cache: %s", error.AsCString ()); tmp_file_remover.releaseFile (); error = Get (root_dir_spec, hostname, module_spec, cached_module_sp, did_create_ptr); if (error.Fail ()) return error; // Fetching a symbol file for the module const auto tmp_download_sym_file_spec = JoinPath (module_spec_dir, kTempSymFileName); error = symfile_downloader (cached_module_sp, tmp_download_sym_file_spec); llvm::FileRemover tmp_symfile_remover (tmp_download_sym_file_spec.GetPath ().c_str ()); if (error.Fail ()) // Failed to download a symfile but fetching the module was successful. The module might // contain the neccessary symbols and the debugging is also possible without a symfile. return Error (); error = Put (root_dir_spec, hostname, module_spec, tmp_download_sym_file_spec, GetSymbolFileSpec(module_spec.GetFileSpec ())); if (error.Fail ()) return Error ("Failed to put symbol file into cache: %s", error.AsCString ()); tmp_symfile_remover.releaseFile(); FileSpec symfile_spec = GetSymbolFileSpec (cached_module_sp->GetFileSpec ()); cached_module_sp->SetSymbolFileFileSpec (symfile_spec); return Error (); } <commit_msg>Replace file system forbidden symbols in the hostname which passed to the ModuleCache.<commit_after>//===--------------------- ModuleCache.cpp ----------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "ModuleCache.h" #include "lldb/Core/Log.h" #include "lldb/Core/Module.h" #include "lldb/Core/ModuleList.h" #include "lldb/Core/ModuleSpec.h" #include "lldb/Host/File.h" #include "lldb/Host/FileSystem.h" #include "lldb/Host/LockFile.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/FileUtilities.h" #include <assert.h> #include <cstdio> using namespace lldb; using namespace lldb_private; namespace { const char* kModulesSubdir = ".cache"; const char* kLockDirName = ".lock"; const char* kTempFileName = ".temp"; const char* kTempSymFileName = ".symtemp"; const char* kSymFileExtension = ".sym"; const char* kFSIllegalChars = "\\/:*?\"<>|"; std::string GetEscapedHostname(const char* hostname) { std::string result(hostname); size_t size = result.size(); for (size_t i = 0; i < size; ++i) { if ((result[i] >=1 && result[i] <= 31) || strchr(kFSIllegalChars, result[i]) != nullptr) result[i] = '_'; } return result; } class ModuleLock { private: File m_file; std::unique_ptr<lldb_private::LockFile> m_lock; FileSpec m_file_spec; public: ModuleLock (const FileSpec &root_dir_spec, const UUID &uuid, Error& error); void Delete (); }; FileSpec JoinPath (const FileSpec &path1, const char* path2) { FileSpec result_spec (path1); result_spec.AppendPathComponent (path2); return result_spec; } Error MakeDirectory (const FileSpec &dir_path) { if (dir_path.Exists ()) { if (!dir_path.IsDirectory ()) return Error ("Invalid existing path"); return Error (); } return FileSystem::MakeDirectory(dir_path, eFilePermissionsDirectoryDefault); } FileSpec GetModuleDirectory (const FileSpec &root_dir_spec, const UUID &uuid) { const auto modules_dir_spec = JoinPath (root_dir_spec, kModulesSubdir); return JoinPath (modules_dir_spec, uuid.GetAsString ().c_str ()); } FileSpec GetSymbolFileSpec(const FileSpec& module_file_spec) { return FileSpec((module_file_spec.GetPath() + kSymFileExtension).c_str(), false); } void DeleteExistingModule (const FileSpec &root_dir_spec, const FileSpec &sysroot_module_path_spec) { Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_MODULES)); UUID module_uuid; { auto module_sp = std::make_shared<Module>(ModuleSpec (sysroot_module_path_spec)); module_uuid = module_sp->GetUUID (); } if (!module_uuid.IsValid ()) return; Error error; ModuleLock lock (root_dir_spec, module_uuid, error); if (error.Fail ()) { if (log) log->Printf ("Failed to lock module %s: %s", module_uuid.GetAsString ().c_str (), error.AsCString ()); } auto link_count = FileSystem::GetHardlinkCount (sysroot_module_path_spec); if (link_count == -1) return; if (link_count > 2) // module is referred by other hosts. return; const auto module_spec_dir = GetModuleDirectory (root_dir_spec, module_uuid); FileSystem::DeleteDirectory (module_spec_dir, true); lock.Delete(); } void DecrementRefExistingModule (const FileSpec &root_dir_spec, const FileSpec &sysroot_module_path_spec) { // Remove $platform/.cache/$uuid folder if nobody else references it. DeleteExistingModule (root_dir_spec, sysroot_module_path_spec); // Remove sysroot link. FileSystem::Unlink (sysroot_module_path_spec); FileSpec symfile_spec = GetSymbolFileSpec (sysroot_module_path_spec); if (symfile_spec.Exists ()) // delete module's symbol file if exists. FileSystem::Unlink (symfile_spec); } Error CreateHostSysRootModuleLink (const FileSpec &root_dir_spec, const char *hostname, const FileSpec &platform_module_spec, const FileSpec &local_module_spec, bool delete_existing) { const auto sysroot_module_path_spec = JoinPath ( JoinPath (root_dir_spec, hostname), platform_module_spec.GetPath ().c_str ()); if (sysroot_module_path_spec.Exists()) { if (!delete_existing) return Error (); DecrementRefExistingModule (root_dir_spec, sysroot_module_path_spec); } const auto error = MakeDirectory (FileSpec (sysroot_module_path_spec.GetDirectory ().AsCString (), false)); if (error.Fail ()) return error; return FileSystem::Hardlink(sysroot_module_path_spec, local_module_spec); } } // namespace ModuleLock::ModuleLock (const FileSpec &root_dir_spec, const UUID &uuid, Error& error) { const auto lock_dir_spec = JoinPath (root_dir_spec, kLockDirName); error = MakeDirectory (lock_dir_spec); if (error.Fail ()) return; m_file_spec = JoinPath (lock_dir_spec, uuid.GetAsString ().c_str ()); m_file.Open (m_file_spec.GetCString (), File::eOpenOptionWrite | File::eOpenOptionCanCreate | File::eOpenOptionCloseOnExec); if (!m_file) { error.SetErrorToErrno (); return; } m_lock.reset (new lldb_private::LockFile (m_file.GetDescriptor ())); error = m_lock->WriteLock (0, 1); if (error.Fail ()) error.SetErrorStringWithFormat ("Failed to lock file: %s", error.AsCString ()); } void ModuleLock::Delete () { if (!m_file) return; m_file.Close (); FileSystem::Unlink (m_file_spec); } ///////////////////////////////////////////////////////////////////////// Error ModuleCache::Put (const FileSpec &root_dir_spec, const char *hostname, const ModuleSpec &module_spec, const FileSpec &tmp_file, const FileSpec &target_file) { const auto module_spec_dir = GetModuleDirectory (root_dir_spec, module_spec.GetUUID ()); const auto module_file_path = JoinPath (module_spec_dir, target_file.GetFilename ().AsCString ()); const auto tmp_file_path = tmp_file.GetPath (); const auto err_code = llvm::sys::fs::rename (tmp_file_path.c_str (), module_file_path.GetPath ().c_str ()); if (err_code) return Error ("Failed to rename file %s to %s: %s", tmp_file_path.c_str (), module_file_path.GetPath ().c_str (), err_code.message ().c_str ()); const auto error = CreateHostSysRootModuleLink(root_dir_spec, hostname, target_file, module_file_path, true); if (error.Fail ()) return Error ("Failed to create link to %s: %s", module_file_path.GetPath ().c_str (), error.AsCString ()); return Error (); } Error ModuleCache::Get (const FileSpec &root_dir_spec, const char *hostname, const ModuleSpec &module_spec, ModuleSP &cached_module_sp, bool *did_create_ptr) { const auto find_it = m_loaded_modules.find (module_spec.GetUUID ().GetAsString()); if (find_it != m_loaded_modules.end ()) { cached_module_sp = (*find_it).second.lock (); if (cached_module_sp) return Error (); m_loaded_modules.erase (find_it); } const auto module_spec_dir = GetModuleDirectory (root_dir_spec, module_spec.GetUUID ()); const auto module_file_path = JoinPath (module_spec_dir, module_spec.GetFileSpec ().GetFilename ().AsCString ()); if (!module_file_path.Exists ()) return Error ("Module %s not found", module_file_path.GetPath ().c_str ()); if (module_file_path.GetByteSize () != module_spec.GetObjectSize ()) return Error ("Module %s has invalid file size", module_file_path.GetPath ().c_str ()); // We may have already cached module but downloaded from an another host - in this case let's create a link to it. auto error = CreateHostSysRootModuleLink(root_dir_spec, hostname, module_spec.GetFileSpec(), module_file_path, false); if (error.Fail ()) return Error ("Failed to create link to %s: %s", module_file_path.GetPath().c_str(), error.AsCString()); auto cached_module_spec (module_spec); cached_module_spec.GetUUID ().Clear (); // Clear UUID since it may contain md5 content hash instead of real UUID. cached_module_spec.GetFileSpec () = module_file_path; cached_module_spec.GetPlatformFileSpec () = module_spec.GetFileSpec (); error = ModuleList::GetSharedModule(cached_module_spec, cached_module_sp, nullptr, nullptr, did_create_ptr, false); if (error.Fail()) return error; FileSpec symfile_spec = GetSymbolFileSpec(cached_module_sp->GetFileSpec ()); if (symfile_spec.Exists ()) cached_module_sp->SetSymbolFileFileSpec (symfile_spec); m_loaded_modules.insert (std::make_pair (module_spec.GetUUID ().GetAsString (), cached_module_sp)); return Error (); } Error ModuleCache::GetAndPut (const FileSpec &root_dir_spec, const char *hostname, const ModuleSpec &module_spec, const ModuleDownloader &module_downloader, const SymfileDownloader &symfile_downloader, lldb::ModuleSP &cached_module_sp, bool *did_create_ptr) { const auto module_spec_dir = GetModuleDirectory (root_dir_spec, module_spec.GetUUID ()); auto error = MakeDirectory (module_spec_dir); if (error.Fail ()) return error; ModuleLock lock (root_dir_spec, module_spec.GetUUID (), error); if (error.Fail ()) return Error("Failed to lock module %s: %s", module_spec.GetUUID ().GetAsString().c_str(), error.AsCString ()); const auto escaped_hostname(GetEscapedHostname(hostname)); // Check local cache for a module. error = Get (root_dir_spec, escaped_hostname.c_str(), module_spec, cached_module_sp, did_create_ptr); if (error.Success ()) return error; const auto tmp_download_file_spec = JoinPath (module_spec_dir, kTempFileName); error = module_downloader (module_spec, tmp_download_file_spec); llvm::FileRemover tmp_file_remover (tmp_download_file_spec.GetPath ().c_str ()); if (error.Fail ()) return Error("Failed to download module: %s", error.AsCString ()); // Put downloaded file into local module cache. error = Put (root_dir_spec, escaped_hostname.c_str(), module_spec, tmp_download_file_spec, module_spec.GetFileSpec ()); if (error.Fail ()) return Error ("Failed to put module into cache: %s", error.AsCString ()); tmp_file_remover.releaseFile (); error = Get (root_dir_spec, escaped_hostname.c_str(), module_spec, cached_module_sp, did_create_ptr); if (error.Fail ()) return error; // Fetching a symbol file for the module const auto tmp_download_sym_file_spec = JoinPath (module_spec_dir, kTempSymFileName); error = symfile_downloader (cached_module_sp, tmp_download_sym_file_spec); llvm::FileRemover tmp_symfile_remover (tmp_download_sym_file_spec.GetPath ().c_str ()); if (error.Fail ()) // Failed to download a symfile but fetching the module was successful. The module might // contain the neccessary symbols and the debugging is also possible without a symfile. return Error (); error = Put (root_dir_spec, escaped_hostname.c_str(), module_spec, tmp_download_sym_file_spec, GetSymbolFileSpec(module_spec.GetFileSpec ())); if (error.Fail ()) return Error ("Failed to put symbol file into cache: %s", error.AsCString ()); tmp_symfile_remover.releaseFile(); FileSpec symfile_spec = GetSymbolFileSpec (cached_module_sp->GetFileSpec ()); cached_module_sp->SetSymbolFileFileSpec (symfile_spec); return Error (); } <|endoftext|>
<commit_before>#ifndef VRTYPE_HPP #define VRTYPE_HPP #include <vector> #include <string> #include <exception> #include <algorithm> #include <functional> #include <boost/algorithm/string.hpp> namespace dicom { namespace data { namespace vrtype { bool rule_n(std::size_t multiplier, std::size_t current, std::size_t new_elements) { return (current + new_elements) % multiplier == 0; } bool rule_less(std::size_t size, std::size_t current, std::size_t new_elements) { return current + new_elements <= size; } bool rule_more(std::size_t size, std::size_t current, std::size_t new_elements) { return current + new_elements >= size; } bool rule_equals(std::size_t size, std::size_t current, std::size_t new_elements) { return current + new_elements == size; } template <typename T> class vrtype { private: std::vector<T> value_sequence; std::string multiplicity; std::vector<std::function<bool(std::size_t, std::size_t)>> multiplicity_rules; /** * @brief validate_multiplicity verifies that the respective attribute's * multiplicity definitions are satisfied. * @param num_new_elements number of new elements to be added * @pre multiplicity rule must be satisfied for the current number of * elements. * @return */ bool validate_multiplicity(std::size_t num_new_elements) const { return std::all_of(multiplicity_rules.begin() , multiplicity_rules.end() , [=](std::function<bool(std::size_t, std::size_t)> rule) { return rule(value_sequence.size(), num_new_elements); } ); } /** * @brief populate_mult_rules parses the multiplicity definiton and adds * all necessary rules. */ void populate_mult_rules() { auto it = std::remove_if(multiplicity.begin(), multiplicity.end(), ::isspace); multiplicity.erase(it, multiplicity.end()); std::vector<std::string> components; boost::split(components, multiplicity, boost::is_any_of("-")); if (components.size() > 1) { if (std::all_of(components[0].begin(), components[0].end(), ::isdigit)) { std::size_t lower = std::stoull(components[0]); if (std::all_of(components[1].begin(), components[1].end(), ::isdigit)) { std::size_t upper = std::stoull(components[1]); multiplicity_rules.push_back(std::bind1st(rule_more, lower)); multiplicity_rules.push_back(std::bind1st(rule_less, upper)); } else if (components[1].find('n') != std::string::npos) { std::string multiplier {components[1].begin(), components[1].find_last_of('n')}; multiplicity_rules.push_back(std::bind1st(rule_n, std::stoul(multiplier))); multiplicity_rules.push_back(std::bind1st(rule_more, lower)); } } } else { if (std::all_of(components[0].begin(), components[0].end(), ::isdigit)) { std::size_t value = std::stoull(components[0]); multiplicity_rules.push_back(std::bind1st(rule_equals, value)); } else if (components[0].find('n') != std::string::npos) { std::string multiplier {components[0].begin(), components[0].find_last_of('n')}; multiplicity_rules.push_back(std::bind1st(rule_n, std::stoul(multiplier))); multiplicity_rules.push_back(std::bind1st(rule_more, 1)); } } } protected: vrtype(std::string multiplicity): multiplicity {multiplicity} { populate_mult_rules(); } vrtype(std::string multiplicity, std::initializer_list<T> values): vrtype(multiplicity) { add(values); } public: virtual ~vrtype() = 0; /** * @brief is_sequence checks if the attribute can hold more than one value. * @return */ bool is_sequence() const { return !multiplicity == "0" && !multiplicity == "1"; } /** * @brief add adds all specified values to the attribute, if doing so * does not break multiplicity conditions. * @param values list of values to be added. */ void add(std::initializer_list<T> values) { if (!is_sequence()) { throw new std::runtime_error("can't add to a non-sequence!"); } if (!validate_multiplicity(values.size())) { throw new std::runtime_error("addition of " + values.size() + " elements would violate the multiplicity rule: " + multiplicity); } std::copy(values.begin(), values.end(), std::back_inserter(value_sequence)); value_sequence.push_back(element); } }; template <typename T> vrtype<T>::~vrtype() { } } } } #endif // VRTYPE_HPP <commit_msg>added abstract (de)serialization methods<commit_after>#ifndef VRTYPE_HPP #define VRTYPE_HPP #include <vector> #include <string> #include <exception> #include <algorithm> #include <functional> #include <boost/algorithm/string.hpp> namespace dicom { namespace data { namespace vrtype { bool rule_n(std::size_t multiplier, std::size_t current, std::size_t new_elements) { return (current + new_elements) % multiplier == 0; } bool rule_less(std::size_t size, std::size_t current, std::size_t new_elements) { return current + new_elements <= size; } bool rule_more(std::size_t size, std::size_t current, std::size_t new_elements) { return current + new_elements >= size; } bool rule_equals(std::size_t size, std::size_t current, std::size_t new_elements) { return current + new_elements == size; } /** * The vrtype class represents the value field of an attribute. It holds the * value(s) of type T and asserts the consistency of the appropriate value * multiplicity with the value count. * @tparam T type of the underlying data */ template <typename T> class vrtype { private: std::vector<T> value_sequence; const std::string multiplicity; std::vector<std::function<bool(std::size_t, std::size_t)>> multiplicity_rules; /** * @brief validate_multiplicity verifies that the respective attribute's * multiplicity definitions are satisfied. * @param num_new_elements number of new elements to be added * @pre multiplicity rule must be satisfied for the current number of * elements. * @return */ bool validate_multiplicity(std::size_t num_new_elements) const { return std::all_of(multiplicity_rules.begin() , multiplicity_rules.end() , [=](std::function<bool(std::size_t, std::size_t)> rule) { return rule(value_sequence.size(), num_new_elements); } ); } /** * @brief populate_mult_rules parses the multiplicity definiton and adds * all necessary rules. */ void populate_mult_rules() { auto it = std::remove_if(multiplicity.begin(), multiplicity.end(), ::isspace); multiplicity.erase(it, multiplicity.end()); std::vector<std::string> components; boost::split(components, multiplicity, boost::is_any_of("-")); if (components.size() > 1) { if (std::all_of(components[0].begin(), components[0].end(), ::isdigit)) { std::size_t lower = std::stoull(components[0]); if (std::all_of(components[1].begin(), components[1].end(), ::isdigit)) { std::size_t upper = std::stoull(components[1]); multiplicity_rules.push_back(std::bind1st(rule_more, lower)); multiplicity_rules.push_back(std::bind1st(rule_less, upper)); } else if (components[1].find('n') != std::string::npos) { std::string multiplier {components[1].begin(), components[1].find_last_of('n')}; multiplicity_rules.push_back(std::bind1st(rule_n, std::stoul(multiplier))); multiplicity_rules.push_back(std::bind1st(rule_more, lower)); } } } else { if (std::all_of(components[0].begin(), components[0].end(), ::isdigit)) { std::size_t value = std::stoull(components[0]); multiplicity_rules.push_back(std::bind1st(rule_equals, value)); } else if (components[0].find('n') != std::string::npos) { std::string multiplier {components[0].begin(), components[0].find_last_of('n')}; multiplicity_rules.push_back(std::bind1st(rule_n, std::stoul(multiplier))); multiplicity_rules.push_back(std::bind1st(rule_more, 1)); } } } protected: vrtype(std::string multiplicity): multiplicity {multiplicity} { populate_mult_rules(); } vrtype(std::string multiplicity, std::initializer_list<T> values): vrtype(multiplicity) { add(values); } /** * @brief serialize serializes the current instance into a byte stream * @return serialized data */ virtual std::vector<unsigned char> serialize() = 0; /** * @brief deserialize deserializes the raw byte data into a structured * representation. * @param data serialized data * @return reference to the instance which contains the data */ virtual vrtype<T>& deserialize(std::vector<unsigned char> data) = 0; public: virtual ~vrtype() = 0; /** * @brief is_sequence checks if the attribute can hold more than one value. * @return */ bool is_sequence() const { return !multiplicity == "0" && !multiplicity == "1"; } /** * @brief add adds all specified values to the attribute, if doing so * does not break multiplicity conditions. * @param values list of values to be added. */ void add(std::initializer_list<T> values) { if (!is_sequence()) { throw new std::runtime_error("can't add to a non-sequence!"); } if (!validate_multiplicity(values.size())) { throw new std::runtime_error("addition of " + values.size() + " elements would violate the multiplicity rule: " + multiplicity); } std::copy(values.begin(), values.end(), std::back_inserter(value_sequence)); value_sequence.push_back(element); } }; template <typename T> vrtype<T>::~vrtype() { } } } } #endif // VRTYPE_HPP <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // ValueSymbol.cpp // Base class for all value symbols // // File is under the MIT license; see LICENSE for details //------------------------------------------------------------------------------ #include "slang/symbols/ValueSymbol.h" #include "slang/binding/AssignmentExpressions.h" #include "slang/binding/Expression.h" #include "slang/binding/MiscExpressions.h" #include "slang/binding/SelectExpressions.h" #include "slang/compilation/Compilation.h" #include "slang/diagnostics/ExpressionsDiags.h" #include "slang/symbols/Scope.h" #include "slang/symbols/VariableSymbols.h" #include "slang/syntax/AllSyntax.h" #include "slang/types/NetType.h" namespace slang { ValueSymbol::ValueSymbol(SymbolKind kind, string_view name, SourceLocation location, bitmask<DeclaredTypeFlags> flags) : Symbol(kind, name, location), declaredType(*this, flags) { } void ValueSymbol::setFromDeclarator(const DeclaratorSyntax& decl) { declaredType.setFromDeclarator(decl); setSyntax(decl); } bool ValueSymbol::isKind(SymbolKind kind) { switch (kind) { case SymbolKind::Net: case SymbolKind::EnumValue: case SymbolKind::Parameter: case SymbolKind::PrimitivePort: case SymbolKind::ModportPort: case SymbolKind::Specparam: return true; default: return VariableSymbol::isKind(kind); } } ValueSymbol::Driver::Driver(DriverKind kind, const Expression& longestStaticPrefix) : longestStaticPrefix(&longestStaticPrefix), kind(kind) { } static const Expression* nextPrefix(const Expression& expr) { switch (expr.kind) { case ExpressionKind::NamedValue: case ExpressionKind::HierarchicalValue: return nullptr; case ExpressionKind::ElementSelect: return &expr.as<ElementSelectExpression>().value(); case ExpressionKind::RangeSelect: return &expr.as<RangeSelectExpression>().value(); case ExpressionKind::MemberAccess: return &expr.as<MemberAccessExpression>().value(); default: THROW_UNREACHABLE; } } static bool prefixOverlaps(EvalContext& ctx, const Expression& left, const Expression& right) { // A named value here should always point to the same symbol, // so we only need to check if they have the same expression kind. if (ValueExpressionBase::isKind(left.kind) && ValueExpressionBase::isKind(right.kind)) return true; auto getRange = [&ctx](const Expression& expr) -> optional<ConstantRange> { ConstantValue unused; if (expr.kind == ExpressionKind::ElementSelect) return expr.as<ElementSelectExpression>().evalIndex(ctx, nullptr, unused); if (expr.kind == ExpressionKind::RangeSelect) return expr.as<RangeSelectExpression>().evalRange(ctx, nullptr); if (expr.kind == ExpressionKind::MemberAccess) return expr.as<MemberAccessExpression>().getSelectRange(); return std::nullopt; }; auto lrange = getRange(left); auto rrange = getRange(right); if (!lrange || !rrange) return false; return lrange->overlaps(*rrange); } bool ValueSymbol::Driver::overlaps(Compilation& compilation, const Driver& other) const { auto buildPath = [](const Expression* expr, SmallVector<const Expression*>& path) { do { if (expr->kind == ExpressionKind::Conversion) { expr = &expr->as<ConversionExpression>().operand(); } else { path.append({ expr }); expr = nextPrefix(*expr); } } while (expr); }; SmallVectorSized<const Expression*, 4> ourPath; buildPath(longestStaticPrefix, ourPath); SmallVectorSized<const Expression*, 4> otherPath; buildPath(other.longestStaticPrefix, otherPath); EvalContext ctx(compilation); for (size_t i = ourPath.size(), j = otherPath.size(); i > 0 && j > 0; i--, j--) { auto ourElem = ourPath[i - 1]; auto otherElem = otherPath[j - 1]; if (!prefixOverlaps(ctx, *ourElem, *otherElem)) return false; } return true; } void ValueSymbol::addDriver(DriverKind driverKind, const Expression& longestStaticPrefix) const { auto scope = getParentScope(); ASSERT(scope); auto& comp = scope->getCompilation(); auto driver = comp.emplace<Driver>(driverKind, longestStaticPrefix); if (!firstDriver) { auto makeRef = [&]() -> const Expression& { BindContext bindContext(*scope, LookupLocation::min); SourceRange range = { location, location + name.length() }; return ValueExpressionBase::fromSymbol(bindContext, *this, /* isHierarchical */ false, range); }; // The first time we add a driver, check whether there is also an // initializer expression that should count as a driver as well. switch (kind) { case SymbolKind::Net: if (auto init = getInitializer()) firstDriver = comp.emplace<Driver>(DriverKind::Continuous, makeRef()); break; case SymbolKind::Variable: case SymbolKind::ClassProperty: case SymbolKind::Field: if (as<VariableSymbol>().lifetime == VariableLifetime::Static) { if (auto init = getInitializer()) firstDriver = comp.emplace<Driver>(DriverKind::Procedural, makeRef()); } break; default: break; } if (!firstDriver) { firstDriver = driver; return; } } const bool checkOverlap = (VariableSymbol::isKind(kind) && as<VariableSymbol>().lifetime == VariableLifetime::Static) || (kind == SymbolKind::Net && as<NetSymbol>().netType.netKind == NetType::UWire); // Walk the list of drivers to the end and add this one there. // Along the way, check that the driver is valid given the ones that already exist. auto curr = firstDriver; while (true) { // Variables can't be driven by multiple continuous assignments or // a mix of continuous and procedural assignments. if (checkOverlap && (driverKind == DriverKind::Continuous || curr->kind == DriverKind::Continuous) && curr->overlaps(comp, *driver)) { auto currRange = curr->longestStaticPrefix->sourceRange; auto driverRange = driver->longestStaticPrefix->sourceRange; auto code = kind == SymbolKind::Net ? diag::MultipleUWireDrivers : (driverKind == DriverKind::Continuous && curr->kind == DriverKind::Continuous) ? diag::MultipleContAssigns : diag::MixedVarAssigns; auto& diag = scope->addDiag(code, driverRange); diag << name; diag.addNote(diag::NoteAssignedHere, currRange.start()) << currRange; return; } if (!curr->next) { curr->next = driver; return; } curr = curr->next; } } } // namespace slang <commit_msg>Fix warning about unused variable<commit_after>//------------------------------------------------------------------------------ // ValueSymbol.cpp // Base class for all value symbols // // File is under the MIT license; see LICENSE for details //------------------------------------------------------------------------------ #include "slang/symbols/ValueSymbol.h" #include "slang/binding/AssignmentExpressions.h" #include "slang/binding/Expression.h" #include "slang/binding/MiscExpressions.h" #include "slang/binding/SelectExpressions.h" #include "slang/compilation/Compilation.h" #include "slang/diagnostics/ExpressionsDiags.h" #include "slang/symbols/Scope.h" #include "slang/symbols/VariableSymbols.h" #include "slang/syntax/AllSyntax.h" #include "slang/types/NetType.h" namespace slang { ValueSymbol::ValueSymbol(SymbolKind kind, string_view name, SourceLocation location, bitmask<DeclaredTypeFlags> flags) : Symbol(kind, name, location), declaredType(*this, flags) { } void ValueSymbol::setFromDeclarator(const DeclaratorSyntax& decl) { declaredType.setFromDeclarator(decl); setSyntax(decl); } bool ValueSymbol::isKind(SymbolKind kind) { switch (kind) { case SymbolKind::Net: case SymbolKind::EnumValue: case SymbolKind::Parameter: case SymbolKind::PrimitivePort: case SymbolKind::ModportPort: case SymbolKind::Specparam: return true; default: return VariableSymbol::isKind(kind); } } ValueSymbol::Driver::Driver(DriverKind kind, const Expression& longestStaticPrefix) : longestStaticPrefix(&longestStaticPrefix), kind(kind) { } static const Expression* nextPrefix(const Expression& expr) { switch (expr.kind) { case ExpressionKind::NamedValue: case ExpressionKind::HierarchicalValue: return nullptr; case ExpressionKind::ElementSelect: return &expr.as<ElementSelectExpression>().value(); case ExpressionKind::RangeSelect: return &expr.as<RangeSelectExpression>().value(); case ExpressionKind::MemberAccess: return &expr.as<MemberAccessExpression>().value(); default: THROW_UNREACHABLE; } } static bool prefixOverlaps(EvalContext& ctx, const Expression& left, const Expression& right) { // A named value here should always point to the same symbol, // so we only need to check if they have the same expression kind. if (ValueExpressionBase::isKind(left.kind) && ValueExpressionBase::isKind(right.kind)) return true; auto getRange = [&ctx](const Expression& expr) -> optional<ConstantRange> { ConstantValue unused; if (expr.kind == ExpressionKind::ElementSelect) return expr.as<ElementSelectExpression>().evalIndex(ctx, nullptr, unused); if (expr.kind == ExpressionKind::RangeSelect) return expr.as<RangeSelectExpression>().evalRange(ctx, nullptr); if (expr.kind == ExpressionKind::MemberAccess) return expr.as<MemberAccessExpression>().getSelectRange(); return std::nullopt; }; auto lrange = getRange(left); auto rrange = getRange(right); if (!lrange || !rrange) return false; return lrange->overlaps(*rrange); } bool ValueSymbol::Driver::overlaps(Compilation& compilation, const Driver& other) const { auto buildPath = [](const Expression* expr, SmallVector<const Expression*>& path) { do { if (expr->kind == ExpressionKind::Conversion) { expr = &expr->as<ConversionExpression>().operand(); } else { path.append({ expr }); expr = nextPrefix(*expr); } } while (expr); }; SmallVectorSized<const Expression*, 4> ourPath; buildPath(longestStaticPrefix, ourPath); SmallVectorSized<const Expression*, 4> otherPath; buildPath(other.longestStaticPrefix, otherPath); EvalContext ctx(compilation); for (size_t i = ourPath.size(), j = otherPath.size(); i > 0 && j > 0; i--, j--) { auto ourElem = ourPath[i - 1]; auto otherElem = otherPath[j - 1]; if (!prefixOverlaps(ctx, *ourElem, *otherElem)) return false; } return true; } void ValueSymbol::addDriver(DriverKind driverKind, const Expression& longestStaticPrefix) const { auto scope = getParentScope(); ASSERT(scope); auto& comp = scope->getCompilation(); auto driver = comp.emplace<Driver>(driverKind, longestStaticPrefix); if (!firstDriver) { auto makeRef = [&]() -> const Expression& { BindContext bindContext(*scope, LookupLocation::min); SourceRange range = { location, location + name.length() }; return ValueExpressionBase::fromSymbol(bindContext, *this, /* isHierarchical */ false, range); }; // The first time we add a driver, check whether there is also an // initializer expression that should count as a driver as well. switch (kind) { case SymbolKind::Net: if (getInitializer()) firstDriver = comp.emplace<Driver>(DriverKind::Continuous, makeRef()); break; case SymbolKind::Variable: case SymbolKind::ClassProperty: case SymbolKind::Field: if (as<VariableSymbol>().lifetime == VariableLifetime::Static) { if (getInitializer()) firstDriver = comp.emplace<Driver>(DriverKind::Procedural, makeRef()); } break; default: break; } if (!firstDriver) { firstDriver = driver; return; } } const bool checkOverlap = (VariableSymbol::isKind(kind) && as<VariableSymbol>().lifetime == VariableLifetime::Static) || (kind == SymbolKind::Net && as<NetSymbol>().netType.netKind == NetType::UWire); // Walk the list of drivers to the end and add this one there. // Along the way, check that the driver is valid given the ones that already exist. auto curr = firstDriver; while (true) { // Variables can't be driven by multiple continuous assignments or // a mix of continuous and procedural assignments. if (checkOverlap && (driverKind == DriverKind::Continuous || curr->kind == DriverKind::Continuous) && curr->overlaps(comp, *driver)) { auto currRange = curr->longestStaticPrefix->sourceRange; auto driverRange = driver->longestStaticPrefix->sourceRange; auto code = kind == SymbolKind::Net ? diag::MultipleUWireDrivers : (driverKind == DriverKind::Continuous && curr->kind == DriverKind::Continuous) ? diag::MultipleContAssigns : diag::MixedVarAssigns; auto& diag = scope->addDiag(code, driverRange); diag << name; diag.addNote(diag::NoteAssignedHere, currRange.start()) << currRange; return; } if (!curr->next) { curr->next = driver; return; } curr = curr->next; } } } // namespace slang <|endoftext|>
<commit_before>// MIT License // // Copyright (c) 2016-2017 Simon Ninon <simon.ninon@gmail.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include <tacopie/error.hpp> #include <tacopie/logger.hpp> #include <tacopie/network/tcp_server.hpp> #include <algorithm> namespace tacopie { //! //! ctor & dtor //! tcp_server::tcp_server(void) : m_io_service(get_default_io_service()) , m_on_new_connection_callback(nullptr) { __TACOPIE_LOG(debug, "create tcp_server"); } tcp_server::~tcp_server(void) { __TACOPIE_LOG(debug, "destroy tcp_server"); stop(); } //! //! start & stop the tcp server //! void tcp_server::start(const std::string& host, std::uint32_t port, const on_new_connection_callback_t& callback) { if (is_running()) { __TACOPIE_THROW(warn, "tcp_server is already running"); } m_socket.bind(host, port); m_socket.listen(__TACOPIE_CONNECTION_QUEUE_SIZE); m_io_service->track(m_socket); m_io_service->set_rd_callback(m_socket, std::bind(&tcp_server::on_read_available, this, std::placeholders::_1)); m_on_new_connection_callback = callback; m_is_running = true; __TACOPIE_LOG(info, "tcp_server running"); } void tcp_server::stop(bool wait_for_removal, bool recursive_wait_for_removal) { if (!is_running()) { return; } m_is_running = false; m_io_service->untrack(m_socket); if (wait_for_removal) { m_io_service->wait_for_removal(m_socket); } m_socket.close(); std::lock_guard<std::mutex> lock(m_clients_mtx); for (auto& client : m_clients) { client->disconnect(recursive_wait_for_removal && wait_for_removal); } m_clients.clear(); __TACOPIE_LOG(info, "tcp_server stopped"); } //! //! io service read callback //! void tcp_server::on_read_available(fd_t) { try { __TACOPIE_LOG(info, "tcp_server received new connection"); auto client = std::make_shared<tcp_client>(m_socket.accept()); if (!m_on_new_connection_callback || m_on_new_connection_callback(client)) { __TACOPIE_LOG(info, "tcp_server accepted new connection"); client->set_on_disconnection_handler(std::bind(&tcp_server::on_client_disconnected, this, client)); m_clients.push_back(client); } else { __TACOPIE_LOG(info, "tcp_server dismissed new connection"); } } catch (const tacopie::tacopie_error&) { __TACOPIE_LOG(warn, "accept operation failure"); stop(); } } //! //! client disconnected //! void tcp_server::on_client_disconnected(const std::shared_ptr<tcp_client>& client) { //! If we are not running the server //! Then it means that this function is called by tcp_client::disconnect() at the destruction of all clients if (!is_running()) { return; } __TACOPIE_LOG(debug, "handle server's client disconnection"); std::lock_guard<std::mutex> lock(m_clients_mtx); auto it = std::find(m_clients.begin(), m_clients.end(), client); if (it != m_clients.end()) { m_clients.erase(it); } } //! //! returns whether the server is currently running or not //! bool tcp_server::is_running(void) const { return m_is_running; } //! //! get socket //! tcp_socket& tcp_server::get_socket(void) { return m_socket; } const tcp_socket& tcp_server::get_socket(void) const { return m_socket; } //! //! get client sockets //! const std::list<std::shared_ptr<tacopie::tcp_client>>& tcp_server::get_clients(void) const { return m_clients; } //! //! comparison operator //! bool tcp_server::operator==(const tcp_server& rhs) const { return m_socket == rhs.m_socket; } bool tcp_server::operator!=(const tcp_server& rhs) const { return !operator==(rhs); } } //! tacopie <commit_msg>change behavior of on_new_connection_handler. Returning true means connection is handled by tcp_client wrapper and nothing will be done by tcp_server. Returning false means connection is handled by tcp_server, will be stored in an internal list and tcp_client disconection_handler overriden.<commit_after>// MIT License // // Copyright (c) 2016-2017 Simon Ninon <simon.ninon@gmail.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include <tacopie/error.hpp> #include <tacopie/logger.hpp> #include <tacopie/network/tcp_server.hpp> #include <algorithm> namespace tacopie { //! //! ctor & dtor //! tcp_server::tcp_server(void) : m_io_service(get_default_io_service()) , m_on_new_connection_callback(nullptr) { __TACOPIE_LOG(debug, "create tcp_server"); } tcp_server::~tcp_server(void) { __TACOPIE_LOG(debug, "destroy tcp_server"); stop(); } //! //! start & stop the tcp server //! void tcp_server::start(const std::string& host, std::uint32_t port, const on_new_connection_callback_t& callback) { if (is_running()) { __TACOPIE_THROW(warn, "tcp_server is already running"); } m_socket.bind(host, port); m_socket.listen(__TACOPIE_CONNECTION_QUEUE_SIZE); m_io_service->track(m_socket); m_io_service->set_rd_callback(m_socket, std::bind(&tcp_server::on_read_available, this, std::placeholders::_1)); m_on_new_connection_callback = callback; m_is_running = true; __TACOPIE_LOG(info, "tcp_server running"); } void tcp_server::stop(bool wait_for_removal, bool recursive_wait_for_removal) { if (!is_running()) { return; } m_is_running = false; m_io_service->untrack(m_socket); if (wait_for_removal) { m_io_service->wait_for_removal(m_socket); } m_socket.close(); std::lock_guard<std::mutex> lock(m_clients_mtx); for (auto& client : m_clients) { client->disconnect(recursive_wait_for_removal && wait_for_removal); } m_clients.clear(); __TACOPIE_LOG(info, "tcp_server stopped"); } //! //! io service read callback //! void tcp_server::on_read_available(fd_t) { try { __TACOPIE_LOG(info, "tcp_server received new connection"); auto client = std::make_shared<tcp_client>(m_socket.accept()); if (!m_on_new_connection_callback || !m_on_new_connection_callback(client)) { __TACOPIE_LOG(info, "connection handling delegated to tcp_server"); client->set_on_disconnection_handler(std::bind(&tcp_server::on_client_disconnected, this, client)); m_clients.push_back(client); } else { __TACOPIE_LOG(info, "connection handled by tcp_server wrapper"); } } catch (const tacopie::tacopie_error&) { __TACOPIE_LOG(warn, "accept operation failure"); stop(); } } //! //! client disconnected //! void tcp_server::on_client_disconnected(const std::shared_ptr<tcp_client>& client) { //! If we are not running the server //! Then it means that this function is called by tcp_client::disconnect() at the destruction of all clients if (!is_running()) { return; } __TACOPIE_LOG(debug, "handle server's client disconnection"); std::lock_guard<std::mutex> lock(m_clients_mtx); auto it = std::find(m_clients.begin(), m_clients.end(), client); if (it != m_clients.end()) { m_clients.erase(it); } } //! //! returns whether the server is currently running or not //! bool tcp_server::is_running(void) const { return m_is_running; } //! //! get socket //! tcp_socket& tcp_server::get_socket(void) { return m_socket; } const tcp_socket& tcp_server::get_socket(void) const { return m_socket; } //! //! get client sockets //! const std::list<std::shared_ptr<tacopie::tcp_client>>& tcp_server::get_clients(void) const { return m_clients; } //! //! comparison operator //! bool tcp_server::operator==(const tcp_server& rhs) const { return m_socket == rhs.m_socket; } bool tcp_server::operator!=(const tcp_server& rhs) const { return !operator==(rhs); } } // namespace tacopie <|endoftext|>
<commit_before>/* * Copyright 2016-2017 deepstreamHub GmbH * * 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. */ #define BOOST_TEST_MAIN #include <boost/test/unit_test.hpp> #include <cstring> #include <numeric> #include <vector> #include <message.hpp> #include <parser.hpp> // Remarks: // - Do not use BOOST_CHECK_EQUAL() to compare const char* variables as // Boost.Test attempts to be smart by calling std::strcmp() // [with Boost 1.53, see boost/test/impl/test_tools.ipp:383, equal_impl()]. // In this file, const char* variables do not always reference null-terminated // strings, e.g., when using std::vector<char*>::data(). If this happens, // Valgrind may detect invalid reads. namespace deepstream { namespace parser { BOOST_AUTO_TEST_CASE(empty_string) { deepstream_parser_state state("", 0); int token = state.handle_token(TOKEN_EOF, "\0", 1); BOOST_CHECK_EQUAL( token, TOKEN_EOF ); BOOST_CHECK( state.tokenizing_header_ ); BOOST_CHECK_EQUAL( state.offset_, 1 ); BOOST_CHECK( state.messages_.empty() ); BOOST_CHECK( state.errors_.empty() ); } BOOST_AUTO_TEST_CASE(simple) { const auto input = Message::from_human_readable("A|A+"); const auto copy(input); const char* matches[] = { &input[0], &input[3], "" }; std::size_t sizes[] = { 3, 1, 1 }; const deepstream_token tokens[] = { TOKEN_A_A, TOKEN_MESSAGE_SEPARATOR, TOKEN_EOF }; const std::size_t num_tokens = sizeof(tokens) / sizeof(tokens[0]); deepstream_parser_state state( &copy[0], copy.size() ); for(std::size_t i = 0; i < num_tokens; ++i) { int ret = state.handle_token(tokens[i], matches[i], sizes[i]); BOOST_CHECK_EQUAL( ret, tokens[i] ); BOOST_CHECK_EQUAL( state.messages_.size(), 1 ); BOOST_CHECK( state.errors_.empty() ); std::size_t offset = std::accumulate( sizes, sizes+i+1, 0 ); BOOST_CHECK_EQUAL( state.offset_, offset ); } Message& msg = state.messages_.front(); BOOST_CHECK( msg.base_ == copy.data() ); BOOST_CHECK_EQUAL( msg.offset_, 0 ); BOOST_CHECK_EQUAL( msg.size_, input.size() ); BOOST_CHECK_EQUAL( msg.topic(), Topic::AUTH ); BOOST_CHECK_EQUAL( msg.action(), Action::REQUEST ); BOOST_CHECK( msg.is_ack() ); BOOST_CHECK( msg.arguments_.empty() ); } BOOST_AUTO_TEST_CASE(concatenated_messages) { const char STRING[] = "E|L|listen+E|S|event+"; const auto input = Message::from_human_readable(STRING); const auto copy(input); const deepstream_token tokens[] = { TOKEN_E_L, TOKEN_PAYLOAD, TOKEN_MESSAGE_SEPARATOR, TOKEN_E_S, TOKEN_PAYLOAD, TOKEN_MESSAGE_SEPARATOR, TOKEN_EOF }; const std::size_t num_tokens = sizeof(tokens) / sizeof(tokens[0]); const std::size_t matchlens[num_tokens] = { 3, 7, 1, 3, 6, 1, 1 }; const char* matches[num_tokens] = { &input[ 0], &input[3], &input[10], &input[11], &input[14], &input[20], "" }; deepstream_parser_state state( &copy[0], copy.size() ); for(std::size_t i = 0; i < num_tokens; ++i) { std::size_t offset = std::accumulate( matchlens, matchlens+i, 0 ); BOOST_CHECK_EQUAL( state.offset_, offset ); int ret = state.handle_token(tokens[i], matches[i], matchlens[i]); BOOST_CHECK_EQUAL( ret, tokens[i] ); BOOST_CHECK_EQUAL( state.messages_.size(), (i>=3) ? 2 : 1 ); BOOST_CHECK( state.errors_.empty() ); BOOST_CHECK_EQUAL( state.offset_, offset+matchlens[i] ); } for(const Message& msg : state.messages_) { BOOST_CHECK( msg.base_ == copy.data() ); BOOST_CHECK_EQUAL( msg.topic(), Topic::EVENT ); BOOST_CHECK( !msg.is_ack() ); BOOST_CHECK_EQUAL( msg.arguments_.size(), 1 ); } BOOST_CHECK_EQUAL( state.messages_.size(), 2 ); const Message& msg_f = state.messages_.front(); BOOST_CHECK_EQUAL( msg_f.offset(), 0 ); BOOST_CHECK_EQUAL( msg_f.size(), 11 ); BOOST_CHECK_EQUAL( msg_f.topic(), Topic::EVENT ); BOOST_CHECK_EQUAL( msg_f.action(), Action::LISTEN ); const Location& arg_f = msg_f.arguments_.front(); BOOST_CHECK_EQUAL( arg_f.offset_, 4 ); BOOST_CHECK_EQUAL( arg_f.length_, 6 ); BOOST_CHECK( !strncmp(&input[arg_f.offset_], "listen", arg_f.length_) ); const Message& msg_b = state.messages_.back(); BOOST_CHECK_EQUAL( msg_b.offset(), 11 ); BOOST_CHECK_EQUAL( msg_b.size(), 10 ); BOOST_CHECK_EQUAL( msg_b.topic(), Topic::EVENT ); BOOST_CHECK_EQUAL( msg_b.action(), Action::SUBSCRIBE ); const Location& arg_b = msg_b.arguments_.front(); BOOST_CHECK_EQUAL( arg_b.offset_, 15 ); BOOST_CHECK_EQUAL( arg_b.length_, 5 ); BOOST_CHECK( !strncmp(&input[arg_b.offset_], "event", arg_b.length_) ); } BOOST_AUTO_TEST_CASE(invalid_number_of_arguments) { const char STRING[] = "E|A|L|l+"; const auto input = Message::from_human_readable(STRING); const auto copy(input); const deepstream_token TOKENS[] = { TOKEN_E_A_L, TOKEN_PAYLOAD, TOKEN_MESSAGE_SEPARATOR, TOKEN_EOF }; const std::size_t NUM_TOKENS = sizeof(TOKENS) / sizeof(TOKENS[0]); const std::size_t MATCHLENS[NUM_TOKENS] = { 5, 2, 1, 1 }; const char* MATCHES[NUM_TOKENS] = { &input[0], &input[5], &input[7], "" }; deepstream_parser_state state( &copy[0], copy.size() ); for(std::size_t i = 0; i < NUM_TOKENS; ++i) { std::size_t offset = std::accumulate( MATCHLENS, MATCHLENS+i, 0 ); BOOST_CHECK_EQUAL( state.offset_, offset ); int ret = state.handle_token(TOKENS[i], MATCHES[i], MATCHLENS[i]); BOOST_CHECK_EQUAL( ret, TOKENS[i] ); BOOST_CHECK_EQUAL( state.messages_.size(), (i>=2) ? 0 : 1 ); BOOST_CHECK_EQUAL( state.errors_.size(), (i>=2) ? 1 : 0 ); BOOST_CHECK_EQUAL( state.offset_, offset+MATCHLENS[i] ); } const Error& e = state.errors_.front(); BOOST_CHECK_EQUAL( e.location_.offset_, 0 ); BOOST_CHECK_EQUAL( e.location_.length_, 8 ); BOOST_CHECK_EQUAL( e.tag_, Error::INVALID_NUMBER_OF_ARGUMENTS ); } } } <commit_msg>Parser: more strict tests<commit_after>/* * Copyright 2016-2017 deepstreamHub GmbH * * 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. */ #define BOOST_TEST_MAIN #include <boost/test/unit_test.hpp> #include <cstring> #include <numeric> #include <vector> #include <message.hpp> #include <parser.hpp> // Remarks: // - Do not use BOOST_CHECK_EQUAL() to compare const char* variables as // Boost.Test attempts to be smart by calling std::strcmp() // [with Boost 1.53, see boost/test/impl/test_tools.ipp:383, equal_impl()]. // In this file, const char* variables do not always reference null-terminated // strings, e.g., when using std::vector<char*>::data(). If this happens, // Valgrind may detect invalid reads. namespace deepstream { namespace parser { BOOST_AUTO_TEST_CASE(empty_string) { deepstream_parser_state state("", 0); int token = state.handle_token(TOKEN_EOF, "\0", 1); BOOST_CHECK_EQUAL( token, TOKEN_EOF ); BOOST_CHECK( state.tokenizing_header_ ); BOOST_CHECK_EQUAL( state.offset_, 1 ); BOOST_CHECK( state.messages_.empty() ); BOOST_CHECK( state.errors_.empty() ); } BOOST_AUTO_TEST_CASE(simple) { const auto input = Message::from_human_readable("A|A+"); const auto copy(input); const char* matches[] = { &input[0], &input[3], "" }; std::size_t sizes[] = { 3, 1, 1 }; const deepstream_token tokens[] = { TOKEN_A_A, TOKEN_MESSAGE_SEPARATOR, TOKEN_EOF }; const std::size_t num_tokens = sizeof(tokens) / sizeof(tokens[0]); deepstream_parser_state state( &copy[0], copy.size() ); for(std::size_t i = 0; i < num_tokens; ++i) { bool tokenizing_header = state.tokenizing_header_; BOOST_CHECK( (i==0||i==2) ? tokenizing_header : !tokenizing_header ); int ret = state.handle_token(tokens[i], matches[i], sizes[i]); BOOST_CHECK_EQUAL( ret, tokens[i] ); BOOST_CHECK_EQUAL( state.messages_.size(), 1 ); BOOST_CHECK( state.errors_.empty() ); std::size_t offset = std::accumulate( sizes, sizes+i+1, 0 ); BOOST_CHECK_EQUAL( state.offset_, offset ); } Message& msg = state.messages_.front(); BOOST_CHECK( msg.base_ == copy.data() ); BOOST_CHECK_EQUAL( msg.offset_, 0 ); BOOST_CHECK_EQUAL( msg.size_, input.size() ); BOOST_CHECK_EQUAL( msg.topic(), Topic::AUTH ); BOOST_CHECK_EQUAL( msg.action(), Action::REQUEST ); BOOST_CHECK( msg.is_ack() ); BOOST_CHECK( msg.arguments_.empty() ); } BOOST_AUTO_TEST_CASE(concatenated_messages) { const char STRING[] = "E|L|listen+E|S|event+"; const auto input = Message::from_human_readable(STRING); const auto copy(input); const deepstream_token tokens[] = { TOKEN_E_L, TOKEN_PAYLOAD, TOKEN_MESSAGE_SEPARATOR, TOKEN_E_S, TOKEN_PAYLOAD, TOKEN_MESSAGE_SEPARATOR, TOKEN_EOF }; const std::size_t num_tokens = sizeof(tokens) / sizeof(tokens[0]); const std::size_t matchlens[num_tokens] = { 3, 7, 1, 3, 6, 1, 1 }; const char* matches[num_tokens] = { &input[ 0], &input[3], &input[10], &input[11], &input[14], &input[20], "" }; deepstream_parser_state state( &copy[0], copy.size() ); for(std::size_t i = 0; i < num_tokens; ++i) { BOOST_CHECK( (i==0||i==3||i==6) ? state.tokenizing_header_ : !state.tokenizing_header_ ); std::size_t offset = std::accumulate( matchlens, matchlens+i, 0 ); BOOST_CHECK_EQUAL( state.offset_, offset ); int ret = state.handle_token(tokens[i], matches[i], matchlens[i]); BOOST_CHECK_EQUAL( ret, tokens[i] ); BOOST_CHECK_EQUAL( state.messages_.size(), (i>=3) ? 2 : 1 ); BOOST_CHECK( state.errors_.empty() ); BOOST_CHECK_EQUAL( state.offset_, offset+matchlens[i] ); } BOOST_CHECK( state.tokenizing_header_ ); for(const Message& msg : state.messages_) { BOOST_CHECK( msg.base_ == copy.data() ); BOOST_CHECK_EQUAL( msg.topic(), Topic::EVENT ); BOOST_CHECK( !msg.is_ack() ); BOOST_CHECK_EQUAL( msg.arguments_.size(), 1 ); } BOOST_CHECK_EQUAL( state.messages_.size(), 2 ); const Message& msg_f = state.messages_.front(); BOOST_CHECK_EQUAL( msg_f.offset(), 0 ); BOOST_CHECK_EQUAL( msg_f.size(), 11 ); BOOST_CHECK_EQUAL( msg_f.topic(), Topic::EVENT ); BOOST_CHECK_EQUAL( msg_f.action(), Action::LISTEN ); const Location& arg_f = msg_f.arguments_.front(); BOOST_CHECK_EQUAL( arg_f.offset_, 4 ); BOOST_CHECK_EQUAL( arg_f.length_, 6 ); BOOST_CHECK( !strncmp(&input[arg_f.offset_], "listen", arg_f.length_) ); const Message& msg_b = state.messages_.back(); BOOST_CHECK_EQUAL( msg_b.offset(), 11 ); BOOST_CHECK_EQUAL( msg_b.size(), 10 ); BOOST_CHECK_EQUAL( msg_b.topic(), Topic::EVENT ); BOOST_CHECK_EQUAL( msg_b.action(), Action::SUBSCRIBE ); const Location& arg_b = msg_b.arguments_.front(); BOOST_CHECK_EQUAL( arg_b.offset_, 15 ); BOOST_CHECK_EQUAL( arg_b.length_, 5 ); BOOST_CHECK( !strncmp(&input[arg_b.offset_], "event", arg_b.length_) ); } BOOST_AUTO_TEST_CASE(invalid_number_of_arguments) { const char STRING[] = "E|A|L|l+"; const auto input = Message::from_human_readable(STRING); const auto copy(input); const deepstream_token TOKENS[] = { TOKEN_E_A_L, TOKEN_PAYLOAD, TOKEN_MESSAGE_SEPARATOR, TOKEN_EOF }; const std::size_t NUM_TOKENS = sizeof(TOKENS) / sizeof(TOKENS[0]); const std::size_t MATCHLENS[NUM_TOKENS] = { 5, 2, 1, 1 }; const char* MATCHES[NUM_TOKENS] = { &input[0], &input[5], &input[7], "" }; deepstream_parser_state state( &copy[0], copy.size() ); for(std::size_t i = 0; i < NUM_TOKENS; ++i) { bool tokenizing_header = state.tokenizing_header_; BOOST_CHECK( (i==0||i==3) ? tokenizing_header : !tokenizing_header ); std::size_t offset = std::accumulate( MATCHLENS, MATCHLENS+i, 0 ); BOOST_CHECK_EQUAL( state.offset_, offset ); int ret = state.handle_token(TOKENS[i], MATCHES[i], MATCHLENS[i]); BOOST_CHECK_EQUAL( ret, TOKENS[i] ); BOOST_CHECK_EQUAL( state.messages_.size(), (i>=2) ? 0 : 1 ); BOOST_CHECK_EQUAL( state.errors_.size(), (i>=2) ? 1 : 0 ); BOOST_CHECK_EQUAL( state.offset_, offset+MATCHLENS[i] ); } const Error& e = state.errors_.front(); BOOST_CHECK_EQUAL( e.location_.offset_, 0 ); BOOST_CHECK_EQUAL( e.location_.length_, 8 ); BOOST_CHECK_EQUAL( e.tag_, Error::INVALID_NUMBER_OF_ARGUMENTS ); } } } <|endoftext|>
<commit_before>#include "lextrans.h" #include <iostream> #include "filelib.h" #include "hg.h" #include "tdict.h" #include "grammar.h" #include "sentence_metadata.h" using namespace std; struct LexicalTransImpl { LexicalTransImpl(const boost::program_options::variables_map& conf) : use_null(conf.count("lexcrf_use_null") > 0), kXCAT(TD::Convert("X")*-1), kNULL(TD::Convert("<eps>")), kBINARY(new TRule("[X] ||| [X,1] [X,2] ||| [1] [2]")), kGOAL_RULE(new TRule("[Goal] ||| [X,1] ||| [1]")) { vector<string> gfiles = conf["grammar"].as<vector<string> >(); assert(gfiles.size() == 1); ReadFile rf(gfiles.front()); TextGrammar *tg = new TextGrammar; grammar.reset(tg); istream* in = rf.stream(); int lc = 0; bool flag = false; while(*in) { string line; getline(*in, line); if (line.empty()) continue; ++lc; TRulePtr r(TRule::CreateRulePhrasetable(line)); tg->AddRule(r); if (lc % 50000 == 0) { cerr << '.'; flag = true; } if (lc % 2000000 == 0) { cerr << " [" << lc << "]\n"; flag = false; } } if (flag) cerr << endl; cerr << "Loaded " << lc << " rules\n"; } void BuildTrellis(const Lattice& lattice, const SentenceMetadata& smeta, Hypergraph* forest) { const int e_len = smeta.GetTargetLength(); assert(e_len > 0); const int f_len = lattice.size(); // hack to tell the feature function system how big the sentence pair is const int f_start = (use_null ? -1 : 0); int prev_node_id = -1; for (int i = 0; i < e_len; ++i) { // for each word in the *target* Hypergraph::Node* node = forest->AddNode(kXCAT); const int new_node_id = node->id_; for (int j = f_start; j < f_len; ++j) { // for each word in the source const WordID src_sym = (j < 0 ? kNULL : lattice[j][0].label); const GrammarIter* gi = grammar->GetRoot()->Extend(src_sym); if (!gi) { cerr << "No translations found for: " << TD::Convert(src_sym) << "\n"; abort(); } const RuleBin* rb = gi->GetRules(); assert(rb); for (int k = 0; k < rb->GetNumRules(); ++k) { TRulePtr rule = rb->GetIthRule(k); Hypergraph::Edge* edge = forest->AddEdge(rule, Hypergraph::TailNodeVector()); edge->i_ = j; edge->j_ = j+1; edge->prev_i_ = i; edge->prev_j_ = i+1; edge->feature_values_ += edge->rule_->GetFeatureValues(); forest->ConnectEdgeToHeadNode(edge->id_, new_node_id); } } if (prev_node_id >= 0) { const int comb_node_id = forest->AddNode(kXCAT)->id_; Hypergraph::TailNodeVector tail(2, prev_node_id); tail[1] = new_node_id; Hypergraph::Edge* edge = forest->AddEdge(kBINARY, tail); forest->ConnectEdgeToHeadNode(edge->id_, comb_node_id); prev_node_id = comb_node_id; } else { prev_node_id = new_node_id; } } Hypergraph::TailNodeVector tail(1, forest->nodes_.size() - 1); Hypergraph::Node* goal = forest->AddNode(TD::Convert("Goal")*-1); Hypergraph::Edge* hg_edge = forest->AddEdge(kGOAL_RULE, tail); forest->ConnectEdgeToHeadNode(hg_edge, goal); } private: const bool use_null; const WordID kXCAT; const WordID kNULL; const TRulePtr kBINARY; const TRulePtr kGOAL_RULE; GrammarPtr grammar; }; LexicalTrans::LexicalTrans(const boost::program_options::variables_map& conf) : pimpl_(new LexicalTransImpl(conf)) {} bool LexicalTrans::TranslateImpl(const string& input, SentenceMetadata* smeta, const vector<double>& weights, Hypergraph* forest) { Lattice& lattice = smeta->src_lattice_; LatticeTools::ConvertTextOrPLF(input, &lattice); if (!lattice.IsSentence()) { // lexical models make independence assumptions // that don't work with lattices or conf nets cerr << "LexicalTrans: cannot deal with lattice source input!\n"; abort(); } smeta->SetSourceLength(lattice.size()); pimpl_->BuildTrellis(lattice, *smeta, forest); forest->is_linear_chain_ = true; forest->Reweight(weights); return true; } <commit_msg>fix typo<commit_after>#include "lextrans.h" #include <iostream> #include "filelib.h" #include "hg.h" #include "tdict.h" #include "grammar.h" #include "sentence_metadata.h" using namespace std; struct LexicalTransImpl { LexicalTransImpl(const boost::program_options::variables_map& conf) : use_null(conf.count("lextrans_use_null") > 0), kXCAT(TD::Convert("X")*-1), kNULL(TD::Convert("<eps>")), kBINARY(new TRule("[X] ||| [X,1] [X,2] ||| [1] [2]")), kGOAL_RULE(new TRule("[Goal] ||| [X,1] ||| [1]")) { vector<string> gfiles = conf["grammar"].as<vector<string> >(); assert(gfiles.size() == 1); ReadFile rf(gfiles.front()); TextGrammar *tg = new TextGrammar; grammar.reset(tg); istream* in = rf.stream(); int lc = 0; bool flag = false; while(*in) { string line; getline(*in, line); if (line.empty()) continue; ++lc; TRulePtr r(TRule::CreateRulePhrasetable(line)); tg->AddRule(r); if (lc % 50000 == 0) { cerr << '.'; flag = true; } if (lc % 2000000 == 0) { cerr << " [" << lc << "]\n"; flag = false; } } if (flag) cerr << endl; cerr << "Loaded " << lc << " rules\n"; } void BuildTrellis(const Lattice& lattice, const SentenceMetadata& smeta, Hypergraph* forest) { const int e_len = smeta.GetTargetLength(); assert(e_len > 0); const int f_len = lattice.size(); // hack to tell the feature function system how big the sentence pair is const int f_start = (use_null ? -1 : 0); int prev_node_id = -1; for (int i = 0; i < e_len; ++i) { // for each word in the *target* Hypergraph::Node* node = forest->AddNode(kXCAT); const int new_node_id = node->id_; for (int j = f_start; j < f_len; ++j) { // for each word in the source const WordID src_sym = (j < 0 ? kNULL : lattice[j][0].label); const GrammarIter* gi = grammar->GetRoot()->Extend(src_sym); if (!gi) { cerr << "No translations found for: " << TD::Convert(src_sym) << "\n"; abort(); } const RuleBin* rb = gi->GetRules(); assert(rb); for (int k = 0; k < rb->GetNumRules(); ++k) { TRulePtr rule = rb->GetIthRule(k); Hypergraph::Edge* edge = forest->AddEdge(rule, Hypergraph::TailNodeVector()); edge->i_ = j; edge->j_ = j+1; edge->prev_i_ = i; edge->prev_j_ = i+1; edge->feature_values_ += edge->rule_->GetFeatureValues(); forest->ConnectEdgeToHeadNode(edge->id_, new_node_id); } } if (prev_node_id >= 0) { const int comb_node_id = forest->AddNode(kXCAT)->id_; Hypergraph::TailNodeVector tail(2, prev_node_id); tail[1] = new_node_id; Hypergraph::Edge* edge = forest->AddEdge(kBINARY, tail); forest->ConnectEdgeToHeadNode(edge->id_, comb_node_id); prev_node_id = comb_node_id; } else { prev_node_id = new_node_id; } } Hypergraph::TailNodeVector tail(1, forest->nodes_.size() - 1); Hypergraph::Node* goal = forest->AddNode(TD::Convert("Goal")*-1); Hypergraph::Edge* hg_edge = forest->AddEdge(kGOAL_RULE, tail); forest->ConnectEdgeToHeadNode(hg_edge, goal); } private: const bool use_null; const WordID kXCAT; const WordID kNULL; const TRulePtr kBINARY; const TRulePtr kGOAL_RULE; GrammarPtr grammar; }; LexicalTrans::LexicalTrans(const boost::program_options::variables_map& conf) : pimpl_(new LexicalTransImpl(conf)) {} bool LexicalTrans::TranslateImpl(const string& input, SentenceMetadata* smeta, const vector<double>& weights, Hypergraph* forest) { Lattice& lattice = smeta->src_lattice_; LatticeTools::ConvertTextOrPLF(input, &lattice); if (!lattice.IsSentence()) { // lexical models make independence assumptions // that don't work with lattices or conf nets cerr << "LexicalTrans: cannot deal with lattice source input!\n"; abort(); } smeta->SetSourceLength(lattice.size()); pimpl_->BuildTrellis(lattice, *smeta, forest); forest->is_linear_chain_ = true; forest->Reweight(weights); return true; } <|endoftext|>
<commit_before>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr> // // Eigen is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 3 of the License, or (at your option) any later version. // // Alternatively, you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 2 of // the License, or (at your option) any later version. // // Eigen is distributed in the hope that it will be useful, but WITHOUT ANY // WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS // FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. #include "main.h" template<typename MatrixType> void verifySizeOf(const MatrixType&) { typedef typename MatrixType::Scalar Scalar; if (MatrixType::RowsAtCompileTime!=Dynamic && MatrixType::ColsAtCompileTime!=Dynamic) VERIFY(sizeof(MatrixType)==static_cast<int>(sizeof(Scalar))*MatrixType::SizeAtCompileTime); else VERIFY(sizeof(MatrixType)==sizeof(Scalar*) + 2 * sizeof(typename MatrixType::Index)); } void test_sizeof() { CALL_SUBTEST(verifySizeOf(Matrix<float, 1, 1>()) ); CALL_SUBTEST(verifySizeOf(Matrix4d()) ); CALL_SUBTEST(verifySizeOf(Matrix<double, 4, 2>()) ); CALL_SUBTEST(verifySizeOf(Matrix<bool, 7, 5>()) ); CALL_SUBTEST(verifySizeOf(MatrixXcf(3, 3)) ); CALL_SUBTEST(verifySizeOf(MatrixXi(8, 12)) ); CALL_SUBTEST(verifySizeOf(MatrixXcd(20, 20)) ); CALL_SUBTEST(verifySizeOf(Matrix<float, 100, 100>()) ); VERIFY(sizeof(std::complex<float>) == 2*sizeof(float)); VERIFY(sizeof(std::complex<double>) == 2*sizeof(double)); } <commit_msg>fix icc warning #68<commit_after>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr> // // Eigen is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 3 of the License, or (at your option) any later version. // // Alternatively, you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 2 of // the License, or (at your option) any later version. // // Eigen is distributed in the hope that it will be useful, but WITHOUT ANY // WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS // FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. #include "main.h" template<typename MatrixType> void verifySizeOf(const MatrixType&) { typedef typename MatrixType::Scalar Scalar; if (MatrixType::RowsAtCompileTime!=Dynamic && MatrixType::ColsAtCompileTime!=Dynamic) VERIFY(sizeof(MatrixType)==sizeof(Scalar)*size_t(MatrixType::SizeAtCompileTime)); else VERIFY(sizeof(MatrixType)==sizeof(Scalar*) + 2 * sizeof(typename MatrixType::Index)); } void test_sizeof() { CALL_SUBTEST(verifySizeOf(Matrix<float, 1, 1>()) ); CALL_SUBTEST(verifySizeOf(Matrix4d()) ); CALL_SUBTEST(verifySizeOf(Matrix<double, 4, 2>()) ); CALL_SUBTEST(verifySizeOf(Matrix<bool, 7, 5>()) ); CALL_SUBTEST(verifySizeOf(MatrixXcf(3, 3)) ); CALL_SUBTEST(verifySizeOf(MatrixXi(8, 12)) ); CALL_SUBTEST(verifySizeOf(MatrixXcd(20, 20)) ); CALL_SUBTEST(verifySizeOf(Matrix<float, 100, 100>()) ); VERIFY(sizeof(std::complex<float>) == 2*sizeof(float)); VERIFY(sizeof(std::complex<double>) == 2*sizeof(double)); } <|endoftext|>
<commit_before>#include <unordered_map> #include <lug/System/Logger/Logger.hpp> #include <lug/Window/Keyboard.hpp> #include <lug/Window/Mouse.hpp> #include <lug/Window/Window.hpp> #if defined(LUG_SYSTEM_ANDROID) #include <lug/System/Logger/LogCatHandler.hpp> #else #include <lug/System/Logger/OstreamHandler.hpp> #endif auto createKeyEnumMap() { std::unordered_map<lug::Window::Keyboard::Key, std::string> returnValue; returnValue[lug::Window::Keyboard::Key::Unknown] = "Unknown"; // Basic keys returnValue[lug::Window::Keyboard::Key::A] = "A"; returnValue[lug::Window::Keyboard::Key::B] = "B"; returnValue[lug::Window::Keyboard::Key::C] = "C"; returnValue[lug::Window::Keyboard::Key::D] = "D"; returnValue[lug::Window::Keyboard::Key::E] = "E"; returnValue[lug::Window::Keyboard::Key::F] = "F"; returnValue[lug::Window::Keyboard::Key::G] = "G"; returnValue[lug::Window::Keyboard::Key::H] = "H"; returnValue[lug::Window::Keyboard::Key::I] = "I"; returnValue[lug::Window::Keyboard::Key::J] = "J"; returnValue[lug::Window::Keyboard::Key::K] = "K"; returnValue[lug::Window::Keyboard::Key::L] = "L"; returnValue[lug::Window::Keyboard::Key::M] = "M"; returnValue[lug::Window::Keyboard::Key::N] = "N"; returnValue[lug::Window::Keyboard::Key::O] = "O"; returnValue[lug::Window::Keyboard::Key::P] = "P"; returnValue[lug::Window::Keyboard::Key::Q] = "Q"; returnValue[lug::Window::Keyboard::Key::R] = "R"; returnValue[lug::Window::Keyboard::Key::S] = "S"; returnValue[lug::Window::Keyboard::Key::T] = "T"; returnValue[lug::Window::Keyboard::Key::U] = "U"; returnValue[lug::Window::Keyboard::Key::V] = "V"; returnValue[lug::Window::Keyboard::Key::W] = "W"; returnValue[lug::Window::Keyboard::Key::X] = "X"; returnValue[lug::Window::Keyboard::Key::Y] = "Y"; returnValue[lug::Window::Keyboard::Key::Z] = "Z"; returnValue[lug::Window::Keyboard::Key::Num0] = "Num0"; returnValue[lug::Window::Keyboard::Key::Num1] = "Num1"; returnValue[lug::Window::Keyboard::Key::Num2] = "Num2"; returnValue[lug::Window::Keyboard::Key::Num3] = "Num3"; returnValue[lug::Window::Keyboard::Key::Num4] = "Num4"; returnValue[lug::Window::Keyboard::Key::Num5] = "Num5"; returnValue[lug::Window::Keyboard::Key::Num6] = "Num6"; returnValue[lug::Window::Keyboard::Key::Num7] = "Num7"; returnValue[lug::Window::Keyboard::Key::Num8] = "Num8"; returnValue[lug::Window::Keyboard::Key::Num9] = "Num9"; // Modifiers returnValue[lug::Window::Keyboard::Key::LControl] = "LControl"; returnValue[lug::Window::Keyboard::Key::LShift] = "LShift"; returnValue[lug::Window::Keyboard::Key::LAlt] = "LAlt"; returnValue[lug::Window::Keyboard::Key::LSystem] = "LSystem"; returnValue[lug::Window::Keyboard::Key::RControl] = "RControl"; returnValue[lug::Window::Keyboard::Key::RShift] = "RShift"; returnValue[lug::Window::Keyboard::Key::RAlt] = "RAlt"; returnValue[lug::Window::Keyboard::Key::RSystem] = "RSystem"; // Advanced keys returnValue[lug::Window::Keyboard::Key::Menu] = "Menu"; returnValue[lug::Window::Keyboard::Key::LBracket] = "LBracket"; returnValue[lug::Window::Keyboard::Key::RBracket] = "RBracket"; returnValue[lug::Window::Keyboard::Key::SemiColon] = "SemiColon"; returnValue[lug::Window::Keyboard::Key::Comma] = "Comma"; returnValue[lug::Window::Keyboard::Key::Period] = "Period"; returnValue[lug::Window::Keyboard::Key::Quote] = "Quote"; returnValue[lug::Window::Keyboard::Key::Slash] = "Slash"; returnValue[lug::Window::Keyboard::Key::BackSlash] = "BackSlash"; returnValue[lug::Window::Keyboard::Key::Tilde] = "Tilde"; returnValue[lug::Window::Keyboard::Key::Equal] = "Equal"; returnValue[lug::Window::Keyboard::Key::Dash] = "Dash"; returnValue[lug::Window::Keyboard::Key::Space] = "Space"; returnValue[lug::Window::Keyboard::Key::Return] = "Return"; returnValue[lug::Window::Keyboard::Key::BackSpace] = "BackSpace"; returnValue[lug::Window::Keyboard::Key::Tab] = "Tab"; returnValue[lug::Window::Keyboard::Key::PageUp] = "PageUp"; returnValue[lug::Window::Keyboard::Key::PageDown] = "PageDown"; returnValue[lug::Window::Keyboard::Key::End] = "End"; returnValue[lug::Window::Keyboard::Key::Home] = "Home"; returnValue[lug::Window::Keyboard::Key::Insert] = "Insert"; returnValue[lug::Window::Keyboard::Key::Delete] = "Delete"; returnValue[lug::Window::Keyboard::Key::Add] = "Add"; returnValue[lug::Window::Keyboard::Key::Subtract] = "Subtract"; returnValue[lug::Window::Keyboard::Key::Multiply] = "Multiply"; returnValue[lug::Window::Keyboard::Key::Divide] = "Divide"; returnValue[lug::Window::Keyboard::Key::Left] = "Left"; returnValue[lug::Window::Keyboard::Key::Right] = "Right"; returnValue[lug::Window::Keyboard::Key::Up] = "Up"; returnValue[lug::Window::Keyboard::Key::Down] = "Down"; returnValue[lug::Window::Keyboard::Key::Pause] = "Pause"; returnValue[lug::Window::Keyboard::Key::CapsLock] = "CapsLock"; returnValue[lug::Window::Keyboard::Key::Escape] = "Escape"; // AZERTY Specifics returnValue[lug::Window::Keyboard::Key::Twosuperior] = "Twosuperior"; returnValue[lug::Window::Keyboard::Key::Ampersand] = "Ampersand"; returnValue[lug::Window::Keyboard::Key::Eacute] = "Eacute"; returnValue[lug::Window::Keyboard::Key::QuoteDouble] = "QuoteDouble"; returnValue[lug::Window::Keyboard::Key::LParen] = "LParen"; returnValue[lug::Window::Keyboard::Key::Egrave] = "Egrave"; returnValue[lug::Window::Keyboard::Key::Underscore] = "Underscore"; returnValue[lug::Window::Keyboard::Key::Ccedilla] = "Ccedilla"; returnValue[lug::Window::Keyboard::Key::Agrave] = "Agrave"; returnValue[lug::Window::Keyboard::Key::RParen] = "RParen"; returnValue[lug::Window::Keyboard::Key::DeadCircumflex] = "DeadCircumflex"; returnValue[lug::Window::Keyboard::Key::Ugrave] = "Ugrave"; returnValue[lug::Window::Keyboard::Key::Asterisk] = "Asterisk"; returnValue[lug::Window::Keyboard::Key::Dollar] = "Dollar"; returnValue[lug::Window::Keyboard::Key::Colon] = "Colon"; returnValue[lug::Window::Keyboard::Key::Exclam] = "Exclam"; returnValue[lug::Window::Keyboard::Key::Less] = "Less"; returnValue[lug::Window::Keyboard::Key::Greater] = "Greater"; // Numpad returnValue[lug::Window::Keyboard::Key::Numpad0] = "Numpad0"; returnValue[lug::Window::Keyboard::Key::Numpad1] = "Numpad1"; returnValue[lug::Window::Keyboard::Key::Numpad2] = "Numpad2"; returnValue[lug::Window::Keyboard::Key::Numpad3] = "Numpad3"; returnValue[lug::Window::Keyboard::Key::Numpad4] = "Numpad4"; returnValue[lug::Window::Keyboard::Key::Numpad5] = "Numpad5"; returnValue[lug::Window::Keyboard::Key::Numpad6] = "Numpad6"; returnValue[lug::Window::Keyboard::Key::Numpad7] = "Numpad7"; returnValue[lug::Window::Keyboard::Key::Numpad8] = "Numpad8"; returnValue[lug::Window::Keyboard::Key::Numpad9] = "Numpad9"; // Function keys returnValue[lug::Window::Keyboard::Key::F1] = "F1"; returnValue[lug::Window::Keyboard::Key::F2] = "F2"; returnValue[lug::Window::Keyboard::Key::F3] = "F3"; returnValue[lug::Window::Keyboard::Key::F4] = "F4"; returnValue[lug::Window::Keyboard::Key::F5] = "F5"; returnValue[lug::Window::Keyboard::Key::F6] = "F6"; returnValue[lug::Window::Keyboard::Key::F7] = "F7"; returnValue[lug::Window::Keyboard::Key::F8] = "F8"; returnValue[lug::Window::Keyboard::Key::F9] = "F9"; returnValue[lug::Window::Keyboard::Key::F10] = "F10"; returnValue[lug::Window::Keyboard::Key::F11] = "F11"; returnValue[lug::Window::Keyboard::Key::F12] = "F12"; returnValue[lug::Window::Keyboard::Key::F13] = "F13"; returnValue[lug::Window::Keyboard::Key::F14] = "F14"; returnValue[lug::Window::Keyboard::Key::F15] = "F15"; return returnValue; } auto createButtonEnumMap() { std::unordered_map<lug::Window::Mouse::Button, std::string> returnValue; // Function keys returnValue[lug::Window::Mouse::Button::Left] = "Left"; returnValue[lug::Window::Mouse::Button::Right] = "Right"; returnValue[lug::Window::Mouse::Button::Middle] = "Middle"; returnValue[lug::Window::Mouse::Button::XButton1] = "XButton1"; returnValue[lug::Window::Mouse::Button::XButton2] = "XButton2"; return returnValue; } int main() { auto window = lug::Window::Window::create({ 800, // width 600, // height "Default Window", // title lug::Window::Style::Default // style }); auto logger = lug::System::Logger::makeLogger("LugdunumSamples"); auto keyEnumMap = createKeyEnumMap(); auto buttonEnumMap = createButtonEnumMap(); #if defined(LUG_SYSTEM_ANDROID) auto handler = lug::System::Logger::makeHandler<lug::System::Logger::LogCatHandler>("LogCat"); #else auto handler = lug::System::Logger::makeHandler<lug::System::Logger::StdoutHandler>("Stdout"); #endif logger->addHandler(handler); LUG_LOG.addHandler(handler); if (!window) { logger->fatal("Window was not created"); return 1; } logger->info("Window was created successfully"); window->setKeyRepeat(true); // While window is open execute the following while (window->isOpen()) { lug::Window::Event event; while (window->pollEvent(event)) { logger->info("Event received: {}", static_cast<uint32_t>(event.type)); if (event.type == lug::Window::Event::Type::Close) { logger->info("Closing the app"); window->close(); } if (event.type == lug::Window::Event::Type::KeyPressed && event.key.code == lug::Window::Keyboard::Key::Escape) { logger->info("Closing the app (escape)"); window->close(); } if (event.type == lug::Window::Event::Type::KeyPressed && event.key.code == lug::Window::Keyboard::Key::Q && event.key.ctrl) { logger->info("Closing the app (ctrl+Q)"); window->close(); } // // Checking to see if mouse position is stored correctly // { // uint32_t x; // uint32_t y; // // window->getMousePos(x, y); // logger->info("Mouse is at position {} {}", x, y); // } // Checking KeyPressed events if (event.type == lug::Window::Event::Type::KeyPressed) { logger->info(keyEnumMap[event.key.code] + " is pressed"); } // Checking KeyReleased events if (event.type == lug::Window::Event::Type::KeyReleased) { logger->info(keyEnumMap[event.key.code] + " is released"); } // Checking ButtonPressed events if (event.type == lug::Window::Event::Type::ButtonPressed) { logger->info(buttonEnumMap[event.button.code] + " is pressed at position {} {}", event.button.coord.x, event.button.coord.y); } // Checking ButtonReleased events if (event.type == lug::Window::Event::Type::ButtonReleased) { logger->info(buttonEnumMap[event.button.code] + " is released at position {} {}", event.button.coord.x, event.button.coord.y); } // // Checking MouseWheel events // if (event.type == lug::Window::Event::Type::MouseWheel) { // logger->info("Mouse scroll wheel offset {} {}", event.button.scrollOffset.xOffset, event.button.scrollOffset.yOffset); // if (event.button.ctrl) { // logger->info("MODIFIER CTRL"); // } // if (event.button.shift) { // logger->info("MODIFIER SHIFT"); // } // } // // Checking MouseMoved events // if (event.type == lug::Window::Event::Type::MouseMoved) { // logger->info("Mouse moved at position {} {}", event.button.coord.x, event.button.coord.y); // } if (event.type == lug::Window::Event::Type::CharEntered) { logger->info("Char event received: {}", static_cast<char>(event.character.val)); } // Checking to see if any special keys are pressed if (event.type == lug::Window::Event::Type::KeyPressed || event.type == lug::Window::Event::Type::KeyReleased) { if (event.key.ctrl) { logger->info("MODIFIER CTRL"); } if (event.key.alt) { logger->info("MODIFIER ALT"); } if (event.key.shift) { logger->info("MODIFIER SHIFT"); } if (event.key.system) { logger->info("MODIFIER SYSTEM"); } } } // // Checking that keys states are correctly set // for (auto it = keyEnumMap.begin(); it != keyEnumMap.end(); ++it) { // if (window->isKeyPressed(it->first)) { // logger->info(it->second + " is set to pressed"); // } // } // // Checking that mouse button states are correctly set // for (auto it = buttonEnumMap.begin(); it != buttonEnumMap.end(); ++it) { // if (window->isMousePressed(it->first)) { // logger->info(it->second + " is set to pressed"); // } // } } return 0; } <commit_msg>Avoid MouseMoved spam<commit_after>#include <unordered_map> #include <lug/System/Logger/Logger.hpp> #include <lug/Window/Keyboard.hpp> #include <lug/Window/Mouse.hpp> #include <lug/Window/Window.hpp> #if defined(LUG_SYSTEM_ANDROID) #include <lug/System/Logger/LogCatHandler.hpp> #else #include <lug/System/Logger/OstreamHandler.hpp> #endif auto createKeyEnumMap() { std::unordered_map<lug::Window::Keyboard::Key, std::string> returnValue; returnValue[lug::Window::Keyboard::Key::Unknown] = "Unknown"; // Basic keys returnValue[lug::Window::Keyboard::Key::A] = "A"; returnValue[lug::Window::Keyboard::Key::B] = "B"; returnValue[lug::Window::Keyboard::Key::C] = "C"; returnValue[lug::Window::Keyboard::Key::D] = "D"; returnValue[lug::Window::Keyboard::Key::E] = "E"; returnValue[lug::Window::Keyboard::Key::F] = "F"; returnValue[lug::Window::Keyboard::Key::G] = "G"; returnValue[lug::Window::Keyboard::Key::H] = "H"; returnValue[lug::Window::Keyboard::Key::I] = "I"; returnValue[lug::Window::Keyboard::Key::J] = "J"; returnValue[lug::Window::Keyboard::Key::K] = "K"; returnValue[lug::Window::Keyboard::Key::L] = "L"; returnValue[lug::Window::Keyboard::Key::M] = "M"; returnValue[lug::Window::Keyboard::Key::N] = "N"; returnValue[lug::Window::Keyboard::Key::O] = "O"; returnValue[lug::Window::Keyboard::Key::P] = "P"; returnValue[lug::Window::Keyboard::Key::Q] = "Q"; returnValue[lug::Window::Keyboard::Key::R] = "R"; returnValue[lug::Window::Keyboard::Key::S] = "S"; returnValue[lug::Window::Keyboard::Key::T] = "T"; returnValue[lug::Window::Keyboard::Key::U] = "U"; returnValue[lug::Window::Keyboard::Key::V] = "V"; returnValue[lug::Window::Keyboard::Key::W] = "W"; returnValue[lug::Window::Keyboard::Key::X] = "X"; returnValue[lug::Window::Keyboard::Key::Y] = "Y"; returnValue[lug::Window::Keyboard::Key::Z] = "Z"; returnValue[lug::Window::Keyboard::Key::Num0] = "Num0"; returnValue[lug::Window::Keyboard::Key::Num1] = "Num1"; returnValue[lug::Window::Keyboard::Key::Num2] = "Num2"; returnValue[lug::Window::Keyboard::Key::Num3] = "Num3"; returnValue[lug::Window::Keyboard::Key::Num4] = "Num4"; returnValue[lug::Window::Keyboard::Key::Num5] = "Num5"; returnValue[lug::Window::Keyboard::Key::Num6] = "Num6"; returnValue[lug::Window::Keyboard::Key::Num7] = "Num7"; returnValue[lug::Window::Keyboard::Key::Num8] = "Num8"; returnValue[lug::Window::Keyboard::Key::Num9] = "Num9"; // Modifiers returnValue[lug::Window::Keyboard::Key::LControl] = "LControl"; returnValue[lug::Window::Keyboard::Key::LShift] = "LShift"; returnValue[lug::Window::Keyboard::Key::LAlt] = "LAlt"; returnValue[lug::Window::Keyboard::Key::LSystem] = "LSystem"; returnValue[lug::Window::Keyboard::Key::RControl] = "RControl"; returnValue[lug::Window::Keyboard::Key::RShift] = "RShift"; returnValue[lug::Window::Keyboard::Key::RAlt] = "RAlt"; returnValue[lug::Window::Keyboard::Key::RSystem] = "RSystem"; // Advanced keys returnValue[lug::Window::Keyboard::Key::Menu] = "Menu"; returnValue[lug::Window::Keyboard::Key::LBracket] = "LBracket"; returnValue[lug::Window::Keyboard::Key::RBracket] = "RBracket"; returnValue[lug::Window::Keyboard::Key::SemiColon] = "SemiColon"; returnValue[lug::Window::Keyboard::Key::Comma] = "Comma"; returnValue[lug::Window::Keyboard::Key::Period] = "Period"; returnValue[lug::Window::Keyboard::Key::Quote] = "Quote"; returnValue[lug::Window::Keyboard::Key::Slash] = "Slash"; returnValue[lug::Window::Keyboard::Key::BackSlash] = "BackSlash"; returnValue[lug::Window::Keyboard::Key::Tilde] = "Tilde"; returnValue[lug::Window::Keyboard::Key::Equal] = "Equal"; returnValue[lug::Window::Keyboard::Key::Dash] = "Dash"; returnValue[lug::Window::Keyboard::Key::Space] = "Space"; returnValue[lug::Window::Keyboard::Key::Return] = "Return"; returnValue[lug::Window::Keyboard::Key::BackSpace] = "BackSpace"; returnValue[lug::Window::Keyboard::Key::Tab] = "Tab"; returnValue[lug::Window::Keyboard::Key::PageUp] = "PageUp"; returnValue[lug::Window::Keyboard::Key::PageDown] = "PageDown"; returnValue[lug::Window::Keyboard::Key::End] = "End"; returnValue[lug::Window::Keyboard::Key::Home] = "Home"; returnValue[lug::Window::Keyboard::Key::Insert] = "Insert"; returnValue[lug::Window::Keyboard::Key::Delete] = "Delete"; returnValue[lug::Window::Keyboard::Key::Add] = "Add"; returnValue[lug::Window::Keyboard::Key::Subtract] = "Subtract"; returnValue[lug::Window::Keyboard::Key::Multiply] = "Multiply"; returnValue[lug::Window::Keyboard::Key::Divide] = "Divide"; returnValue[lug::Window::Keyboard::Key::Left] = "Left"; returnValue[lug::Window::Keyboard::Key::Right] = "Right"; returnValue[lug::Window::Keyboard::Key::Up] = "Up"; returnValue[lug::Window::Keyboard::Key::Down] = "Down"; returnValue[lug::Window::Keyboard::Key::Pause] = "Pause"; returnValue[lug::Window::Keyboard::Key::CapsLock] = "CapsLock"; returnValue[lug::Window::Keyboard::Key::Escape] = "Escape"; // AZERTY Specifics returnValue[lug::Window::Keyboard::Key::Twosuperior] = "Twosuperior"; returnValue[lug::Window::Keyboard::Key::Ampersand] = "Ampersand"; returnValue[lug::Window::Keyboard::Key::Eacute] = "Eacute"; returnValue[lug::Window::Keyboard::Key::QuoteDouble] = "QuoteDouble"; returnValue[lug::Window::Keyboard::Key::LParen] = "LParen"; returnValue[lug::Window::Keyboard::Key::Egrave] = "Egrave"; returnValue[lug::Window::Keyboard::Key::Underscore] = "Underscore"; returnValue[lug::Window::Keyboard::Key::Ccedilla] = "Ccedilla"; returnValue[lug::Window::Keyboard::Key::Agrave] = "Agrave"; returnValue[lug::Window::Keyboard::Key::RParen] = "RParen"; returnValue[lug::Window::Keyboard::Key::DeadCircumflex] = "DeadCircumflex"; returnValue[lug::Window::Keyboard::Key::Ugrave] = "Ugrave"; returnValue[lug::Window::Keyboard::Key::Asterisk] = "Asterisk"; returnValue[lug::Window::Keyboard::Key::Dollar] = "Dollar"; returnValue[lug::Window::Keyboard::Key::Colon] = "Colon"; returnValue[lug::Window::Keyboard::Key::Exclam] = "Exclam"; returnValue[lug::Window::Keyboard::Key::Less] = "Less"; returnValue[lug::Window::Keyboard::Key::Greater] = "Greater"; // Numpad returnValue[lug::Window::Keyboard::Key::Numpad0] = "Numpad0"; returnValue[lug::Window::Keyboard::Key::Numpad1] = "Numpad1"; returnValue[lug::Window::Keyboard::Key::Numpad2] = "Numpad2"; returnValue[lug::Window::Keyboard::Key::Numpad3] = "Numpad3"; returnValue[lug::Window::Keyboard::Key::Numpad4] = "Numpad4"; returnValue[lug::Window::Keyboard::Key::Numpad5] = "Numpad5"; returnValue[lug::Window::Keyboard::Key::Numpad6] = "Numpad6"; returnValue[lug::Window::Keyboard::Key::Numpad7] = "Numpad7"; returnValue[lug::Window::Keyboard::Key::Numpad8] = "Numpad8"; returnValue[lug::Window::Keyboard::Key::Numpad9] = "Numpad9"; // Function keys returnValue[lug::Window::Keyboard::Key::F1] = "F1"; returnValue[lug::Window::Keyboard::Key::F2] = "F2"; returnValue[lug::Window::Keyboard::Key::F3] = "F3"; returnValue[lug::Window::Keyboard::Key::F4] = "F4"; returnValue[lug::Window::Keyboard::Key::F5] = "F5"; returnValue[lug::Window::Keyboard::Key::F6] = "F6"; returnValue[lug::Window::Keyboard::Key::F7] = "F7"; returnValue[lug::Window::Keyboard::Key::F8] = "F8"; returnValue[lug::Window::Keyboard::Key::F9] = "F9"; returnValue[lug::Window::Keyboard::Key::F10] = "F10"; returnValue[lug::Window::Keyboard::Key::F11] = "F11"; returnValue[lug::Window::Keyboard::Key::F12] = "F12"; returnValue[lug::Window::Keyboard::Key::F13] = "F13"; returnValue[lug::Window::Keyboard::Key::F14] = "F14"; returnValue[lug::Window::Keyboard::Key::F15] = "F15"; return returnValue; } auto createButtonEnumMap() { std::unordered_map<lug::Window::Mouse::Button, std::string> returnValue; // Function keys returnValue[lug::Window::Mouse::Button::Left] = "Left"; returnValue[lug::Window::Mouse::Button::Right] = "Right"; returnValue[lug::Window::Mouse::Button::Middle] = "Middle"; returnValue[lug::Window::Mouse::Button::XButton1] = "XButton1"; returnValue[lug::Window::Mouse::Button::XButton2] = "XButton2"; return returnValue; } int main() { auto window = lug::Window::Window::create({ 800, // width 600, // height "Default Window", // title lug::Window::Style::Default // style }); auto logger = lug::System::Logger::makeLogger("LugdunumSamples"); auto keyEnumMap = createKeyEnumMap(); auto buttonEnumMap = createButtonEnumMap(); #if defined(LUG_SYSTEM_ANDROID) auto handler = lug::System::Logger::makeHandler<lug::System::Logger::LogCatHandler>("LogCat"); #else auto handler = lug::System::Logger::makeHandler<lug::System::Logger::StdoutHandler>("Stdout"); #endif logger->addHandler(handler); LUG_LOG.addHandler(handler); if (!window) { logger->fatal("Window was not created"); return 1; } logger->info("Window was created successfully"); window->setKeyRepeat(true); // While window is open execute the following while (window->isOpen()) { lug::Window::Event event; while (window->pollEvent(event)) { /* * AVOID MOUSE MOVE SPAM !!! */ if (event.type != lug::Window::Event::Type::MouseMoved) { logger->info("Event received: {}", static_cast<uint32_t>(event.type)); } if (event.type == lug::Window::Event::Type::Close) { logger->info("Closing the app"); window->close(); } if (event.type == lug::Window::Event::Type::KeyPressed && event.key.code == lug::Window::Keyboard::Key::Escape) { logger->info("Closing the app (escape)"); window->close(); } if (event.type == lug::Window::Event::Type::KeyPressed && event.key.code == lug::Window::Keyboard::Key::Q && event.key.ctrl) { logger->info("Closing the app (ctrl+Q)"); window->close(); } // // Checking to see if mouse position is stored correctly // { // uint32_t x; // uint32_t y; // // window->getMousePos(x, y); // logger->info("Mouse is at position {} {}", x, y); // } // Checking KeyPressed events if (event.type == lug::Window::Event::Type::KeyPressed) { logger->info(keyEnumMap[event.key.code] + " is pressed"); } // Checking KeyReleased events if (event.type == lug::Window::Event::Type::KeyReleased) { logger->info(keyEnumMap[event.key.code] + " is released"); } // Checking ButtonPressed events if (event.type == lug::Window::Event::Type::ButtonPressed) { logger->info(buttonEnumMap[event.button.code] + " is pressed at position {} {}", event.button.coord.x, event.button.coord.y); } // Checking ButtonReleased events if (event.type == lug::Window::Event::Type::ButtonReleased) { logger->info(buttonEnumMap[event.button.code] + " is released at position {} {}", event.button.coord.x, event.button.coord.y); } // Checking MouseWheel events if (event.type == lug::Window::Event::Type::MouseWheel) { logger->info("Mouse scroll wheel offset {} {}", event.button.scrollOffset.xOffset, event.button.scrollOffset.yOffset); if (event.button.ctrl) { logger->info("MODIFIER CTRL"); } if (event.button.shift) { logger->info("MODIFIER SHIFT"); } } if (event.type == lug::Window::Event::Type::MouseLeave) { logger->info("Mouse just left the window."); if (event.button.ctrl) { logger->info("MODIFIER CTRL"); } if (event.button.shift) { logger->info("MODIFIER SHIFT"); } } if (event.type == lug::Window::Event::Type::MouseEnter) { logger->info("Mouse just entered the window."); if (event.button.ctrl) { logger->info("MODIFIER CTRL"); } if (event.button.shift) { logger->info("MODIFIER SHIFT"); } } // // Checking MouseMoved events // if (event.type == lug::Window::Event::Type::MouseMoved) { // logger->info("Mouse moved at position {} {}", event.button.coord.x, event.button.coord.y); // } if (event.type == lug::Window::Event::Type::CharEntered) { logger->info("Char event received: {}", static_cast<char>(event.character.val)); } // Checking to see if any special keys are pressed if (event.type == lug::Window::Event::Type::KeyPressed || event.type == lug::Window::Event::Type::KeyReleased) { if (event.key.ctrl) { logger->info("MODIFIER CTRL"); } if (event.key.alt) { logger->info("MODIFIER ALT"); } if (event.key.shift) { logger->info("MODIFIER SHIFT"); } if (event.key.system) { logger->info("MODIFIER SYSTEM"); } } } // // Checking that keys states are correctly set // for (auto it = keyEnumMap.begin(); it != keyEnumMap.end(); ++it) { // if (window->isKeyPressed(it->first)) { // logger->info(it->second + " is set to pressed"); // } // } // // Checking that mouse button states are correctly set // for (auto it = buttonEnumMap.begin(); it != buttonEnumMap.end(); ++it) { // if (window->isMousePressed(it->first)) { // logger->info(it->second + " is set to pressed"); // } // } } return 0; } <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Copyright (c) 2009, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id$ * */ #ifndef PCL_SAMPLE_CONSENSUS_IMPL_PROSAC_H_ #define PCL_SAMPLE_CONSENSUS_IMPL_PROSAC_H_ #include <boost/math/distributions/binomial.hpp> #include "pcl/sample_consensus/prosac.h" ////////////////////////////////////////////////////////////////////////// // Variable naming uses capital letters to make the comparison with the original paper easier template<typename PointT> bool pcl::ProgressiveSampleConsensus<PointT>::computeModel (int debug_verbosity_level) { // Warn and exit if no threshold was set if (threshold_ == DBL_MAX) { PCL_ERROR ("[pcl::ProgressiveSampleConsensus::computeModel] No threshold set!\n"); return (false); } // Initialize some PROSAC constants float T_N = 200000; unsigned int N = sac_model_->indices_->size (); unsigned int m = sac_model_->getSampleSize (); float T_n = T_N; for (unsigned int i = 0; i < m; ++i) T_n *= (float)(m - i) / (float)(N - i); float T_prime_n = 1; unsigned int I_N_best = 0; float n = m; // Define the n_Start coefficients from Section 2.2 float n_star = N; unsigned int I_n_star = 0; float epsilon_n_star = (float)I_n_star / n_star; unsigned int k_n_star = T_N; // Compute the I_n_star_min of Equation 8 std::vector<unsigned int> I_n_star_min (N); // Initialize the usual RANSAC parameters iterations_ = 0; std::vector<int> inliers; std::vector<int> selection; Eigen::VectorXf model_coefficients; // We will increase the pool so the indices_ vector can only contain m elements at first std::vector<int> index_pool; index_pool.reserve (N); for (unsigned int i = 0; i < n; ++i) index_pool.push_back (sac_model_->indices_->operator[](i)); // Iterate while ((unsigned int)iterations_ < k_n_star) { // Choose the samples // Step 1 // According to Equation 5 in the text text, not the algorithm if ((iterations_ == T_prime_n) && (n < n_star)) { // Increase the pool ++n; if (n >= N) break; index_pool.push_back (sac_model_->indices_->at(n - 1)); // Update other variables float T_n_minus_1 = T_n; T_n *= (float)(n + 1) / (float)(n + 1 - m); T_prime_n += ceil(T_n - T_n_minus_1); } // Step 2 sac_model_->indices_->swap (index_pool); selection.clear (); sac_model_->getSamples (iterations_, selection); if (T_prime_n < iterations_) { selection.pop_back (); selection.push_back (sac_model_->indices_->at(n - 1)); } // Make sure we use the right indices for testing sac_model_->indices_->swap (index_pool); if (selection.empty ()) { PCL_ERROR ("[pcl::ProgressiveSampleConsensus::computeModel] No samples could be selected!\n"); break; } // Search for inliers in the point cloud for the current model if (!sac_model_->computeModelCoefficients (selection, model_coefficients)) { ++iterations_; continue; } // Select the inliers that are within threshold_ from the model inliers.clear (); sac_model_->selectWithinDistance (model_coefficients, threshold_, inliers); unsigned int I_N = inliers.size (); // If we find more inliers than before if (I_N > I_N_best) { I_N_best = I_N; // Save the current model/inlier/coefficients selection as being the best so far inliers_ = inliers; model_ = selection; model_coefficients_ = model_coefficients; // We estimate I_n_star for different possible values of n_star by using the inliers std::sort (inliers.begin (), inliers.end ()); // Try to find a better n_star // We minimize k_n_star and therefore maximize epsilon_n_star = I_n_star / n_star unsigned int possible_n_star_best = N, I_possible_n_star_best = I_N; float epsilon_possible_n_star_best = (float)I_possible_n_star_best / possible_n_star_best; // We only need to compute possible better epsilon_n_star for when _n is just about to be removed an inlier unsigned int I_possible_n_star = I_N; for (std::vector<int>::const_reverse_iterator last_inlier = inliers.rbegin (); last_inlier != inliers.rend (); ++last_inlier, --I_possible_n_star) { // The best possible_n_star for a given I_possible_n_star is the index of the last inlier unsigned int possible_n_star = (*last_inlier) + 1; if (possible_n_star <= m) break; // If we find a better epsilon_n_star float epsilon_possible_n_star = (float)I_possible_n_star / possible_n_star; // Make sure we have a better epsilon_possible_n_star if ((epsilon_possible_n_star > epsilon_n_star) && (epsilon_possible_n_star > epsilon_possible_n_star_best)) { using namespace boost::math; // Typo in Equation 7, not (n-m choose i-m) but (n choose i-m) unsigned int I_possible_n_star_min = m + ceil (quantile (complement (binomial_distribution<float>(possible_n_star, 0.1), 0.05))); // If Equation 9 is not verified, exit if (I_possible_n_star < I_possible_n_star_min) break; possible_n_star_best = possible_n_star; I_possible_n_star_best = I_possible_n_star; epsilon_possible_n_star_best = epsilon_possible_n_star; } } // Check if we get a better epsilon if (epsilon_possible_n_star_best > epsilon_n_star) { // update the best value epsilon_n_star = epsilon_possible_n_star_best; // Compute the new k_n_star float bottom_log = 1 - std::pow (epsilon_n_star, static_cast<float>(m)); if (bottom_log == 0) k_n_star = 1; else if (bottom_log == 1) k_n_star = T_N; else k_n_star = (int)ceil (log(0.05) / log (bottom_log)); // It seems weird to have very few iterations, so do have a few (totally empirical) k_n_star = (std::max)(k_n_star, 2 * m); } } ++iterations_; if (debug_verbosity_level > 1) PCL_DEBUG ("[pcl::ProgressiveSampleConsensus::computeModel] Trial %d out of %d: %d inliers (best is: %d so far).\n", iterations_, k_n_star, I_N, I_N_best); if (iterations_ > max_iterations_) { if (debug_verbosity_level > 0) PCL_DEBUG ("[pcl::ProgressiveSampleConsensus::computeModel] RANSAC reached the maximum number of trials.\n"); break; } } if (debug_verbosity_level > 0) PCL_DEBUG ("[pcl::ProgressiveSampleConsensus::computeModel] Model: %lu size, %d inliers.\n", (unsigned long)model_.size (), I_N_best); if (model_.empty ()) { inliers_.clear (); return (false); } // Get the set of inliers that correspond to the best model found so far //sac_model_->selectWithinDistance (model_coefficients_, threshold_, inliers_); return (true); } #define PCL_INSTANTIATE_ProgressiveSampleConsensus(T) template class PCL_EXPORTS pcl::ProgressiveSampleConsensus<T>; #endif // PCL_SAMPLE_CONSENSUS_IMPL_PROSAC_H_ <commit_msg>friendlier PROSAC for pathCC<commit_after>/* * Software License Agreement (BSD License) * * Copyright (c) 2009, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id$ * */ #ifndef PCL_SAMPLE_CONSENSUS_IMPL_PROSAC_H_ #define PCL_SAMPLE_CONSENSUS_IMPL_PROSAC_H_ #include <boost/math/distributions/binomial.hpp> #include "pcl/sample_consensus/prosac.h" ////////////////////////////////////////////////////////////////////////// // Variable naming uses capital letters to make the comparison with the original paper easier template<typename PointT> bool pcl::ProgressiveSampleConsensus<PointT>::computeModel (int debug_verbosity_level) { // Warn and exit if no threshold was set if (threshold_ == DBL_MAX) { PCL_ERROR ("[pcl::ProgressiveSampleConsensus::computeModel] No threshold set!\n"); return (false); } // Initialize some PROSAC constants float T_N = 200000; unsigned int N = sac_model_->indices_->size (); unsigned int m = sac_model_->getSampleSize (); float T_n = T_N; for (unsigned int i = 0; i < m; ++i) T_n *= (float)(m - i) / (float)(N - i); float T_prime_n = 1; unsigned int I_N_best = 0; float n = m; // Define the n_Start coefficients from Section 2.2 float n_star = N; unsigned int I_n_star = 0; float epsilon_n_star = (float)I_n_star / n_star; unsigned int k_n_star = T_N; // Compute the I_n_star_min of Equation 8 std::vector<unsigned int> I_n_star_min (N); // Initialize the usual RANSAC parameters iterations_ = 0; std::vector<int> inliers; std::vector<int> selection; Eigen::VectorXf model_coefficients; // We will increase the pool so the indices_ vector can only contain m elements at first std::vector<int> index_pool; index_pool.reserve (N); for (unsigned int i = 0; i < n; ++i) index_pool.push_back (sac_model_->indices_->operator[](i)); // Iterate while ((unsigned int)iterations_ < k_n_star) { // Choose the samples // Step 1 // According to Equation 5 in the text text, not the algorithm if ((iterations_ == T_prime_n) && (n < n_star)) { // Increase the pool ++n; if (n >= N) break; index_pool.push_back (sac_model_->indices_->at(n - 1)); // Update other variables float T_n_minus_1 = T_n; T_n *= (float)(n + 1) / (float)(n + 1 - m); T_prime_n += ceil(T_n - T_n_minus_1); } // Step 2 sac_model_->indices_->swap (index_pool); selection.clear (); sac_model_->getSamples (iterations_, selection); if (T_prime_n < iterations_) { selection.pop_back (); selection.push_back (sac_model_->indices_->at(n - 1)); } // Make sure we use the right indices for testing sac_model_->indices_->swap (index_pool); if (selection.empty ()) { PCL_ERROR ("[pcl::ProgressiveSampleConsensus::computeModel] No samples could be selected!\n"); break; } // Search for inliers in the point cloud for the current model if (!sac_model_->computeModelCoefficients (selection, model_coefficients)) { ++iterations_; continue; } // Select the inliers that are within threshold_ from the model inliers.clear (); sac_model_->selectWithinDistance (model_coefficients, threshold_, inliers); unsigned int I_N = inliers.size (); // If we find more inliers than before if (I_N > I_N_best) { I_N_best = I_N; // Save the current model/inlier/coefficients selection as being the best so far inliers_ = inliers; model_ = selection; model_coefficients_ = model_coefficients; // We estimate I_n_star for different possible values of n_star by using the inliers std::sort (inliers.begin (), inliers.end ()); // Try to find a better n_star // We minimize k_n_star and therefore maximize epsilon_n_star = I_n_star / n_star unsigned int possible_n_star_best = N, I_possible_n_star_best = I_N; float epsilon_possible_n_star_best = (float)I_possible_n_star_best / possible_n_star_best; // We only need to compute possible better epsilon_n_star for when _n is just about to be removed an inlier unsigned int I_possible_n_star = I_N; for (std::vector<int>::const_reverse_iterator last_inlier = inliers.rbegin (), inliers_end = inliers.rend (); last_inlier != inliers_end; ++last_inlier, --I_possible_n_star) { // The best possible_n_star for a given I_possible_n_star is the index of the last inlier unsigned int possible_n_star = (*last_inlier) + 1; if (possible_n_star <= m) break; // If we find a better epsilon_n_star float epsilon_possible_n_star = (float)I_possible_n_star / possible_n_star; // Make sure we have a better epsilon_possible_n_star if ((epsilon_possible_n_star > epsilon_n_star) && (epsilon_possible_n_star > epsilon_possible_n_star_best)) { using namespace boost::math; // Typo in Equation 7, not (n-m choose i-m) but (n choose i-m) unsigned int I_possible_n_star_min = m + ceil (quantile (complement (binomial_distribution<float>(possible_n_star, 0.1), 0.05))); // If Equation 9 is not verified, exit if (I_possible_n_star < I_possible_n_star_min) break; possible_n_star_best = possible_n_star; I_possible_n_star_best = I_possible_n_star; epsilon_possible_n_star_best = epsilon_possible_n_star; } } // Check if we get a better epsilon if (epsilon_possible_n_star_best > epsilon_n_star) { // update the best value epsilon_n_star = epsilon_possible_n_star_best; // Compute the new k_n_star float bottom_log = 1 - std::pow (epsilon_n_star, static_cast<float>(m)); if (bottom_log == 0) k_n_star = 1; else if (bottom_log == 1) k_n_star = T_N; else k_n_star = (int)ceil (log(0.05) / log (bottom_log)); // It seems weird to have very few iterations, so do have a few (totally empirical) k_n_star = (std::max)(k_n_star, 2 * m); } } ++iterations_; if (debug_verbosity_level > 1) PCL_DEBUG ("[pcl::ProgressiveSampleConsensus::computeModel] Trial %d out of %d: %d inliers (best is: %d so far).\n", iterations_, k_n_star, I_N, I_N_best); if (iterations_ > max_iterations_) { if (debug_verbosity_level > 0) PCL_DEBUG ("[pcl::ProgressiveSampleConsensus::computeModel] RANSAC reached the maximum number of trials.\n"); break; } } if (debug_verbosity_level > 0) PCL_DEBUG ("[pcl::ProgressiveSampleConsensus::computeModel] Model: %lu size, %d inliers.\n", (unsigned long)model_.size (), I_N_best); if (model_.empty ()) { inliers_.clear (); return (false); } // Get the set of inliers that correspond to the best model found so far //sac_model_->selectWithinDistance (model_coefficients_, threshold_, inliers_); return (true); } #define PCL_INSTANTIATE_ProgressiveSampleConsensus(T) template class PCL_EXPORTS pcl::ProgressiveSampleConsensus<T>; #endif // PCL_SAMPLE_CONSENSUS_IMPL_PROSAC_H_ <|endoftext|>
<commit_before>#include "test.h" #include "include/config.h" #include "geo/point2.h" #include "geo/vector2.h" using namespace std; using namespace valhalla::geo; namespace { void TryDotProduct(const Vector2& a, const Vector2& b, float expected) { float result = a.Dot(b); if (expected != result) throw runtime_error("DotProduct test failed"); } void TestDotProduct() { TryDotProduct(Vector2(3.0f, 0.0f), Vector2(5.0f, 5.0f), 15.0f); TryDotProduct(Vector2(3.0f, 4.0f), Vector2(-8.0f, 6.0f), 0.0f); } void TryCrossProduct(const Vector2& a, const Vector2& b, float expected) { float result = a.Cross(b); if (expected != result) throw runtime_error("CrossProduct test failed"); } void TestCrossProduct() { TryCrossProduct(Vector2(3.0f, 0.0f), Vector2(5.0f, 5.0f), 15.0f); TryCrossProduct(Vector2(3.0f, 4.0f), Vector2(-8.0f, 6.0f), 50.0f); } void TryPerpendicular(const Vector2& a, const Vector2& expected) { Vector2 result = a.GetPerpendicular(); if (!(expected == result)) throw runtime_error("Perpendicular test failed"); } void TestPerpendicular() { TryPerpendicular(Vector2(3.0f, 4.0f), Vector2(-4.0f, 3.0f)); } void TryNorm(const Vector2& a, float expected) { float result = a.Norm(); if (expected != result) throw runtime_error("Norm test failed"); } void TestNorm() { TryNorm(Vector2(3.0f, 4.0f), 5.0f); TryNorm(Vector2(6.0f, 8.0f), 10.0f); } void TryNormSquared(const Vector2& a, float expected) { float result = a.NormSquared(); if (expected != result) throw runtime_error("NormSquared test failed"); } void TestNormSquared() { TryNormSquared(Vector2(3.0f, 4.0f), 25.0f); TryNormSquared(Vector2(6.0f, 8.0f), 100.0f); } void TryNormalize(Vector2& a, const Vector2& expected) { a.Normalize(); if (!(expected == a)) throw runtime_error("Normalize test failed"); } void TestNormalize() { Vector2 v(3.0f, 4.0f); TryNormalize(v, Vector2(3.0f / 5.0f, 4.0f / 5.0f)); Vector2 w(6.0f, 8.0f); TryNormalize(w, Vector2(6.0f / 10.0f, 8.0f / 10.0f)); } void TryComponent(const Vector2& a, const Vector2& b, float expected) { float result = a.Component(b); if (expected != result) throw runtime_error("Component test failed"); } void TestComponent() { TryComponent(Vector2(3.0f, 4.0f), Vector2(6.0f, 8.0f), 0.5f); TryComponent(Vector2(6.0f, 8.0f), Vector2(3.0f, 4.0f), 2.0f); } void TryProjection(const Vector2& a, const Vector2& b, const Vector2& expected) { Vector2 result = a.Projection(b); if (!(expected == result)) throw runtime_error("Projection test failed"); } void TestProjection() { TryProjection(Vector2(3.0f, 4.0f), Vector2(6.0f, 8.0f), Vector2(3.0f, 4.0f)); TryProjection(Vector2(6.0f, 8.0f), Vector2(3.0f, 4.0f), Vector2(6.0f, 8.0f)); TryProjection(Vector2(2.0f, 1.0f), Vector2(-3.0f, 4.0f), Vector2(6.0f / 25.0f, -8.0f / 25.0f)); } void TryAngleBetween(const Vector2& a, const Vector2& b, float expected) { float result = (a.AngleBetween(b) * kDegPerRad); if (expected != result) throw runtime_error("AngleBetween test failed"); } void TestAngleBetween() { TryAngleBetween(Vector2(3.0f, 0.0f), Vector2(5.0f, 5.0f), 45.0f); TryAngleBetween(Vector2(3.0f, 4.0f), Vector2(-8.0f, 6.0f), 90.0f); } void TryReflect(const Vector2& a, const Vector2& b, const Vector2& expected) { Vector2 result = a.Reflect(b); if (!(expected == result)) throw runtime_error("Reflect test failed"); } void TestReflect() { Vector2 n1 { 0.0f, 2.0f }; n1.Normalize(); TryReflect(Vector2(4.0f, -2.0f), n1, Vector2(4.0f, 2.0f)); Vector2 n2 { -3.0f, 0.0f }; n2.Normalize(); TryReflect(Vector2(3.0f, -4.0f), n2, Vector2(-3.0f, -4.0f)); } } int main() { test::suite suite("vector2"); // Dot Product suite.test(TEST_CASE(TestDotProduct)); // Cross Product suite.test(TEST_CASE(TestCrossProduct)); // Perpendicular suite.test(TEST_CASE(TestPerpendicular)); // Norm suite.test(TEST_CASE(TestNorm)); // NormSquared suite.test(TEST_CASE(TestNormSquared)); // Normalize suite.test(TEST_CASE(TestNormalize)); // Component suite.test(TEST_CASE(TestComponent)); // Projection suite.test(TEST_CASE(TestProjection)); // Angle Between suite.test(TEST_CASE(TestAngleBetween)); // Reflect suite.test(TEST_CASE(TestReflect)); return suite.tear_down(); } <commit_msg>Added ctor and op assignment unit tests as follows:<commit_after>#include "test.h" #include "include/config.h" #include "geo/point2.h" #include "geo/vector2.h" using namespace std; using namespace valhalla::geo; namespace { void TestCtorDefault() { Vector2 target; Vector2 expected { 0.0f, 0.0f }; if (!(expected == target)) throw runtime_error("CtorDefault test failed"); } void TryCtorPoint2(const Point2& pt, const Vector2& expected) { Vector2 result(pt); if (!(expected == result)) throw runtime_error("CtorPoint2 test failed"); } void TestCtorPoint2() { TryCtorPoint2(Point2(3.0f, 0.0f), Vector2(3.0f, 0.0f)); TryCtorPoint2(Point2(-8.0f, 6.0f), Vector2(-8.0f, 6.0f)); } void TryCtorFloatFloat(const float x, const float y, const Vector2& expected) { Vector2 result(x, y); if (!(expected == result)) throw runtime_error("CtorFloatFloat test failed"); } void TestCtorFloatFloat() { TryCtorFloatFloat(3.0f, 0.0f, Vector2(3.0f, 0.0f)); TryCtorFloatFloat(-8.0f, 6.0f, Vector2(-8.0f, 6.0f)); } void TryCtorPoint2Point2(const Point2& from, const Point2& to, const Vector2& expected) { Vector2 result(from, to); if (!(expected == result)) throw runtime_error("CtorPoint2Point2 test failed"); } void TestCtorPoint2Point2() { TryCtorPoint2Point2(Point2(4.0f, 0.0f), Point2(3.0f, 3.0f), Vector2(-1.0f, 3.0f)); TryCtorPoint2Point2(Point2(4.0f, 2.0f), Point2(4.0f, -2.0f), Vector2(0.0f, -4.0f)); } void TryCtorVector2(const Vector2& v, const Vector2& expected) { Vector2 result(v); if (!(expected == result)) throw runtime_error("CtorVector2 test failed"); } void TestCtorVector2() { TryCtorVector2(Vector2(3.0f, 0.0f), Vector2(3.0f, 0.0f)); TryCtorVector2(Vector2(-8.0f, 6.0f), Vector2(-8.0f, 6.0f)); } void TryOpAssignment(const Vector2& v, const Vector2& expected) { Vector2 result; result = v; if (!(expected == result)) throw runtime_error("OpAssignment test failed"); } void TestOpAssignment() { TryOpAssignment(Vector2(3.0f, 0.0f), Vector2(3.0f, 0.0f)); TryOpAssignment(Vector2(-8.0f, 6.0f), Vector2(-8.0f, 6.0f)); } void TryDotProduct(const Vector2& a, const Vector2& b, float expected) { float result = a.Dot(b); if (expected != result) throw runtime_error("DotProduct test failed"); } void TestDotProduct() { TryDotProduct(Vector2(3.0f, 0.0f), Vector2(5.0f, 5.0f), 15.0f); TryDotProduct(Vector2(3.0f, 4.0f), Vector2(-8.0f, 6.0f), 0.0f); } void TryCrossProduct(const Vector2& a, const Vector2& b, float expected) { float result = a.Cross(b); if (expected != result) throw runtime_error("CrossProduct test failed"); } void TestCrossProduct() { TryCrossProduct(Vector2(3.0f, 0.0f), Vector2(5.0f, 5.0f), 15.0f); TryCrossProduct(Vector2(3.0f, 4.0f), Vector2(-8.0f, 6.0f), 50.0f); } void TryPerpendicular(const Vector2& a, const Vector2& expected) { Vector2 result = a.GetPerpendicular(); if (!(expected == result)) throw runtime_error("Perpendicular test failed"); } void TestPerpendicular() { TryPerpendicular(Vector2(3.0f, 4.0f), Vector2(-4.0f, 3.0f)); } void TryNorm(const Vector2& a, float expected) { float result = a.Norm(); if (expected != result) throw runtime_error("Norm test failed"); } void TestNorm() { TryNorm(Vector2(3.0f, 4.0f), 5.0f); TryNorm(Vector2(6.0f, 8.0f), 10.0f); } void TryNormSquared(const Vector2& a, float expected) { float result = a.NormSquared(); if (expected != result) throw runtime_error("NormSquared test failed"); } void TestNormSquared() { TryNormSquared(Vector2(3.0f, 4.0f), 25.0f); TryNormSquared(Vector2(6.0f, 8.0f), 100.0f); } void TryNormalize(Vector2& a, const Vector2& expected) { a.Normalize(); if (!(expected == a)) throw runtime_error("Normalize test failed"); } void TestNormalize() { Vector2 v(3.0f, 4.0f); TryNormalize(v, Vector2(3.0f / 5.0f, 4.0f / 5.0f)); Vector2 w(6.0f, 8.0f); TryNormalize(w, Vector2(6.0f / 10.0f, 8.0f / 10.0f)); } void TryComponent(const Vector2& a, const Vector2& b, float expected) { float result = a.Component(b); if (expected != result) throw runtime_error("Component test failed"); } void TestComponent() { TryComponent(Vector2(3.0f, 4.0f), Vector2(6.0f, 8.0f), 0.5f); TryComponent(Vector2(6.0f, 8.0f), Vector2(3.0f, 4.0f), 2.0f); } void TryProjection(const Vector2& a, const Vector2& b, const Vector2& expected) { Vector2 result = a.Projection(b); if (!(expected == result)) throw runtime_error("Projection test failed"); } void TestProjection() { TryProjection(Vector2(3.0f, 4.0f), Vector2(6.0f, 8.0f), Vector2(3.0f, 4.0f)); TryProjection(Vector2(6.0f, 8.0f), Vector2(3.0f, 4.0f), Vector2(6.0f, 8.0f)); TryProjection(Vector2(2.0f, 1.0f), Vector2(-3.0f, 4.0f), Vector2(6.0f / 25.0f, -8.0f / 25.0f)); } void TryAngleBetween(const Vector2& a, const Vector2& b, float expected) { float result = (a.AngleBetween(b) * kDegPerRad); if (expected != result) throw runtime_error("AngleBetween test failed"); } void TestAngleBetween() { TryAngleBetween(Vector2(3.0f, 0.0f), Vector2(5.0f, 5.0f), 45.0f); TryAngleBetween(Vector2(3.0f, 4.0f), Vector2(-8.0f, 6.0f), 90.0f); } void TryReflect(const Vector2& a, const Vector2& b, const Vector2& expected) { Vector2 result = a.Reflect(b); if (!(expected == result)) throw runtime_error("Reflect test failed"); } void TestReflect() { Vector2 n1 { 0.0f, 2.0f }; n1.Normalize(); TryReflect(Vector2(4.0f, -2.0f), n1, Vector2(4.0f, 2.0f)); Vector2 n2 { -3.0f, 0.0f }; n2.Normalize(); TryReflect(Vector2(3.0f, -4.0f), n2, Vector2(-3.0f, -4.0f)); } } int main() { test::suite suite("vector2"); // Ctor default suite.test(TEST_CASE(TestCtorDefault)); // Ctor Point2 suite.test(TEST_CASE(TestCtorPoint2)); // Ctor float, float suite.test(TEST_CASE(TestCtorFloatFloat)); // Ctor Point2, Point2 suite.test(TEST_CASE(TestCtorPoint2Point2)); // Ctor Vector2 suite.test(TEST_CASE(TestCtorVector2)); // Op Assignment suite.test(TEST_CASE(TestOpAssignment)); // Dot Product suite.test(TEST_CASE(TestDotProduct)); // Cross Product suite.test(TEST_CASE(TestCrossProduct)); // Perpendicular suite.test(TEST_CASE(TestPerpendicular)); // Norm suite.test(TEST_CASE(TestNorm)); // NormSquared suite.test(TEST_CASE(TestNormSquared)); // Normalize suite.test(TEST_CASE(TestNormalize)); // Component suite.test(TEST_CASE(TestComponent)); // Projection suite.test(TEST_CASE(TestProjection)); // Angle Between suite.test(TEST_CASE(TestAngleBetween)); // Reflect suite.test(TEST_CASE(TestReflect)); return suite.tear_down(); } <|endoftext|>
<commit_before>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org Copyright (c) 2000-2014 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreShaderPrecompiledHeaders.h" #ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS #define SGX_LIB_NORMALMAP "SGXLib_NormalMap" #define SGX_FUNC_FETCHNORMAL "SGX_FetchNormal" namespace Ogre { namespace RTShader { /************************************************************************/ /* */ /************************************************************************/ const String SRS_NORMALMAP = "NormalMap"; //----------------------------------------------------------------------- NormalMapLighting::NormalMapLighting() { mNormalMapSamplerIndex = 0; mVSTexCoordSetIndex = 0; mNormalMapSpace = NMS_TANGENT; mNormalMapSampler = TextureManager::getSingleton().createSampler(); mNormalMapSampler->setMipmapBias(-1.0); } //----------------------------------------------------------------------- const String& NormalMapLighting::getType() const { return SRS_NORMALMAP; } //----------------------------------------------------------------------- bool NormalMapLighting::createCpuSubPrograms(ProgramSet* programSet) { Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); Function* vsMain = vsProgram->getEntryPointFunction(); Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); Function* psMain = psProgram->getEntryPointFunction(); vsProgram->addDependency(FFP_LIB_TRANSFORM); psProgram->addDependency(FFP_LIB_TRANSFORM); psProgram->addDependency(FFP_LIB_TEXTURING); psProgram->addDependency(SGX_LIB_NORMALMAP); // Resolve texture coordinates. auto vsInTexcoord = vsMain->resolveInputParameter( Parameter::Content(Parameter::SPC_TEXTURE_COORDINATE0 + mVSTexCoordSetIndex), GCT_FLOAT2); auto vsOutTexcoord = vsMain->resolveOutputParameter( Parameter::Content(Parameter::SPC_TEXTURE_COORDINATE0 + mVSTexCoordSetIndex), GCT_FLOAT2); auto psInTexcoord = psMain->resolveInputParameter(vsOutTexcoord); // Resolve normal. auto vsInNormal = vsMain->resolveInputParameter(Parameter::SPC_NORMAL_OBJECT_SPACE); auto vsOutNormal = vsMain->resolveOutputParameter(Parameter::SPC_NORMAL_VIEW_SPACE); auto viewNormal = psMain->resolveInputParameter(vsOutNormal); auto newViewNormal = psMain->resolveLocalParameter(Parameter::SPC_NORMAL_VIEW_SPACE); // insert before lighting stage auto vstage = vsMain->getStage(FFP_PS_COLOUR_BEGIN + 1); auto fstage = psMain->getStage(FFP_PS_COLOUR_BEGIN + 1); // Output texture coordinates. vstage.assign(vsInTexcoord, vsOutTexcoord); // Add the normal fetch function invocation auto normalMapSampler = psProgram->resolveParameter(GCT_SAMPLER2D, "gNormalMapSampler", mNormalMapSamplerIndex); fstage.callFunction(SGX_FUNC_FETCHNORMAL, normalMapSampler, psInTexcoord, newViewNormal); if (mNormalMapSpace & NMS_TANGENT) { auto vsInTangent = vsMain->resolveInputParameter(Parameter::SPC_TANGENT_OBJECT_SPACE); auto vsOutTangent = vsMain->resolveOutputParameter(Parameter::SPC_TANGENT_OBJECT_SPACE); auto psInTangent = psMain->resolveInputParameter(vsOutTangent); // transform normal & tangent auto normalMatrix = vsProgram->resolveParameter(GpuProgramParameters::ACT_NORMAL_MATRIX); vstage.callFunction(FFP_FUNC_TRANSFORM, normalMatrix, vsInNormal, vsOutNormal); vstage.callFunction(FFP_FUNC_TRANSFORM, normalMatrix, vsInTangent, vsOutTangent); // transform normal fstage.callFunction("SGX_TransformNormal", {In(viewNormal), In(psInTangent), InOut(newViewNormal)}); } else if (mNormalMapSpace & NMS_OBJECT) { // transform normal in FS auto normalMatrix = psProgram->resolveParameter(GpuProgramParameters::ACT_NORMAL_MATRIX); fstage.callFunction(FFP_FUNC_TRANSFORM, normalMatrix, newViewNormal, newViewNormal); } if (mNormalMapSpace == NMS_PARALLAX) { // assuming: lighting stage computed this auto vsOutViewPos = vsMain->resolveOutputParameter(Parameter::SPC_POSITION_VIEW_SPACE); auto viewPos = psMain->resolveInputParameter(vsOutViewPos); // TODO: user specificed scale and bias fstage.callFunction("SGX_Generate_Parallax_Texcoord", {In(normalMapSampler), In(psInTexcoord), In(viewPos), In(Vector2(0.04, -0.02)), Out(psInTexcoord)}); // overwrite texcoord0 unconditionally, only one texcoord set is supported with parallax mapping // we are before FFP_PS_TEXTURING, so the new value will be used auto texcoord0 = psMain->resolveInputParameter(Parameter::SPC_TEXTURE_COORDINATE0, GCT_FLOAT2); fstage.assign(psInTexcoord, texcoord0); } return true; } //----------------------------------------------------------------------- void NormalMapLighting::copyFrom(const SubRenderState& rhs) { const NormalMapLighting& rhsLighting = static_cast<const NormalMapLighting&>(rhs); mNormalMapSpace = rhsLighting.mNormalMapSpace; mNormalMapTextureName = rhsLighting.mNormalMapTextureName; mNormalMapSampler = rhsLighting.mNormalMapSampler; } //----------------------------------------------------------------------- bool NormalMapLighting::preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass) { TextureUnitState* normalMapTexture = dstPass->createTextureUnitState(); normalMapTexture->setTextureName(mNormalMapTextureName); normalMapTexture->setSampler(mNormalMapSampler); mNormalMapSamplerIndex = dstPass->getNumTextureUnitStates() - 1; return true; } bool NormalMapLighting::setParameter(const String& name, const String& value) { if(name == "normalmap_space") { // Normal map defines normals in tangent space. if (value == "tangent_space") { setNormalMapSpace(NMS_TANGENT); return true; } // Normal map defines normals in object space. if (value == "object_space") { setNormalMapSpace(NMS_OBJECT); return true; } if (value == "parallax") { setNormalMapSpace(NMS_PARALLAX); return true; } return false; } if(name == "texture") { mNormalMapTextureName = value; return true; } if(name == "texcoord_index") { setTexCoordIndex(StringConverter::parseInt(value)); return true; } if(name == "sampler") { auto sampler = TextureManager::getSingleton().getSampler(value); if(!sampler) return false; mNormalMapSampler = sampler; return true; } return false; } //----------------------------------------------------------------------- const String& NormalMapLightingFactory::getType() const { return SRS_NORMALMAP; } //----------------------------------------------------------------------- SubRenderState* NormalMapLightingFactory::createInstance(ScriptCompiler* compiler, PropertyAbstractNode* prop, Pass* pass, SGScriptTranslator* translator) { if (prop->name == "lighting_stage") { if(prop->values.size() >= 2) { String strValue; AbstractNodeList::const_iterator it = prop->values.begin(); // Read light model type. if(false == SGScriptTranslator::getString(*it, &strValue)) { compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); return NULL; } // Case light model type is normal map if (strValue == "normal_map") { ++it; if (false == SGScriptTranslator::getString(*it, &strValue)) { compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, prop->file, prop->line); return NULL; } SubRenderState* subRenderState = createOrRetrieveInstance(translator); NormalMapLighting* normalMapSubRenderState = static_cast<NormalMapLighting*>(subRenderState); normalMapSubRenderState->setParameter("texture", strValue); // Read normal map space type. if (prop->values.size() >= 3) { ++it; if (false == SGScriptTranslator::getString(*it, &strValue)) { compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, prop->file, prop->line); return NULL; } if(!normalMapSubRenderState->setParameter("normalmap_space", strValue)) { compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); return NULL; } } // Read texture coordinate index. if (prop->values.size() >= 4) { unsigned int textureCoordinateIndex = 0; ++it; if (SGScriptTranslator::getUInt(*it, &textureCoordinateIndex)) { normalMapSubRenderState->setTexCoordIndex(textureCoordinateIndex); } } // Read texture filtering format. if (prop->values.size() >= 5) { ++it; if (false == SGScriptTranslator::getString(*it, &strValue)) { compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, prop->file, prop->line); return NULL; } // sampler reference if(!normalMapSubRenderState->setParameter("sampler", strValue)) { compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); return NULL; } } return subRenderState; } } } return NULL; } //----------------------------------------------------------------------- void NormalMapLightingFactory::writeInstance(MaterialSerializer* ser, SubRenderState* subRenderState, Pass* srcPass, Pass* dstPass) { NormalMapLighting* normalMapSubRenderState = static_cast<NormalMapLighting*>(subRenderState); ser->writeAttribute(4, "lighting_stage"); ser->writeValue("normal_map"); ser->writeValue(normalMapSubRenderState->getNormalMapTextureName()); if (normalMapSubRenderState->getNormalMapSpace() == NormalMapLighting::NMS_TANGENT) { ser->writeValue("tangent_space"); } else if (normalMapSubRenderState->getNormalMapSpace() == NormalMapLighting::NMS_OBJECT) { ser->writeValue("object_space"); } ser->writeValue(StringConverter::toString(normalMapSubRenderState->getTexCoordIndex())); } //----------------------------------------------------------------------- SubRenderState* NormalMapLightingFactory::createInstanceImpl() { return OGRE_NEW NormalMapLighting; } } } #endif <commit_msg>RTSS: NormalMap - we must normalise tangents & normals in VS<commit_after>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org Copyright (c) 2000-2014 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreShaderPrecompiledHeaders.h" #ifdef RTSHADER_SYSTEM_BUILD_EXT_SHADERS #define SGX_LIB_NORMALMAP "SGXLib_NormalMap" #define SGX_FUNC_FETCHNORMAL "SGX_FetchNormal" namespace Ogre { namespace RTShader { /************************************************************************/ /* */ /************************************************************************/ const String SRS_NORMALMAP = "NormalMap"; //----------------------------------------------------------------------- NormalMapLighting::NormalMapLighting() { mNormalMapSamplerIndex = 0; mVSTexCoordSetIndex = 0; mNormalMapSpace = NMS_TANGENT; mNormalMapSampler = TextureManager::getSingleton().createSampler(); mNormalMapSampler->setMipmapBias(-1.0); } //----------------------------------------------------------------------- const String& NormalMapLighting::getType() const { return SRS_NORMALMAP; } //----------------------------------------------------------------------- bool NormalMapLighting::createCpuSubPrograms(ProgramSet* programSet) { Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); Function* vsMain = vsProgram->getEntryPointFunction(); Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); Function* psMain = psProgram->getEntryPointFunction(); vsProgram->addDependency(FFP_LIB_TRANSFORM); psProgram->addDependency(FFP_LIB_TRANSFORM); psProgram->addDependency(FFP_LIB_TEXTURING); psProgram->addDependency(SGX_LIB_NORMALMAP); // Resolve texture coordinates. auto vsInTexcoord = vsMain->resolveInputParameter( Parameter::Content(Parameter::SPC_TEXTURE_COORDINATE0 + mVSTexCoordSetIndex), GCT_FLOAT2); auto vsOutTexcoord = vsMain->resolveOutputParameter( Parameter::Content(Parameter::SPC_TEXTURE_COORDINATE0 + mVSTexCoordSetIndex), GCT_FLOAT2); auto psInTexcoord = psMain->resolveInputParameter(vsOutTexcoord); // Resolve normal. auto vsInNormal = vsMain->resolveInputParameter(Parameter::SPC_NORMAL_OBJECT_SPACE); auto vsOutNormal = vsMain->resolveOutputParameter(Parameter::SPC_NORMAL_VIEW_SPACE); auto viewNormal = psMain->resolveInputParameter(vsOutNormal); auto newViewNormal = psMain->resolveLocalParameter(Parameter::SPC_NORMAL_VIEW_SPACE); // insert before lighting stage auto vstage = vsMain->getStage(FFP_PS_COLOUR_BEGIN + 1); auto fstage = psMain->getStage(FFP_PS_COLOUR_BEGIN + 1); // Output texture coordinates. vstage.assign(vsInTexcoord, vsOutTexcoord); // Add the normal fetch function invocation auto normalMapSampler = psProgram->resolveParameter(GCT_SAMPLER2D, "gNormalMapSampler", mNormalMapSamplerIndex); fstage.callFunction(SGX_FUNC_FETCHNORMAL, normalMapSampler, psInTexcoord, newViewNormal); if (mNormalMapSpace & NMS_TANGENT) { auto vsInTangent = vsMain->resolveInputParameter(Parameter::SPC_TANGENT_OBJECT_SPACE); auto vsOutTangent = vsMain->resolveOutputParameter(Parameter::SPC_TANGENT_OBJECT_SPACE); auto psInTangent = psMain->resolveInputParameter(vsOutTangent); // transform normal & tangent auto normalMatrix = vsProgram->resolveParameter(GpuProgramParameters::ACT_NORMAL_MATRIX); vstage.callFunction(FFP_FUNC_TRANSFORM, normalMatrix, vsInNormal, vsOutNormal); vstage.callBuiltin("normalize", vsOutNormal, vsOutNormal); vstage.callFunction(FFP_FUNC_TRANSFORM, normalMatrix, vsInTangent, vsOutTangent); vstage.callBuiltin("normalize", vsOutTangent, vsOutTangent); // transform normal fstage.callFunction("SGX_TransformNormal", {In(viewNormal), In(psInTangent), InOut(newViewNormal)}); } else if (mNormalMapSpace & NMS_OBJECT) { // transform normal in FS auto normalMatrix = psProgram->resolveParameter(GpuProgramParameters::ACT_NORMAL_MATRIX); fstage.callFunction(FFP_FUNC_TRANSFORM, normalMatrix, newViewNormal, newViewNormal); } if (mNormalMapSpace == NMS_PARALLAX) { // assuming: lighting stage computed this auto vsOutViewPos = vsMain->resolveOutputParameter(Parameter::SPC_POSITION_VIEW_SPACE); auto viewPos = psMain->resolveInputParameter(vsOutViewPos); // TODO: user specificed scale and bias fstage.callFunction("SGX_Generate_Parallax_Texcoord", {In(normalMapSampler), In(psInTexcoord), In(viewPos), In(Vector2(0.04, -0.02)), Out(psInTexcoord)}); // overwrite texcoord0 unconditionally, only one texcoord set is supported with parallax mapping // we are before FFP_PS_TEXTURING, so the new value will be used auto texcoord0 = psMain->resolveInputParameter(Parameter::SPC_TEXTURE_COORDINATE0, GCT_FLOAT2); fstage.assign(psInTexcoord, texcoord0); } return true; } //----------------------------------------------------------------------- void NormalMapLighting::copyFrom(const SubRenderState& rhs) { const NormalMapLighting& rhsLighting = static_cast<const NormalMapLighting&>(rhs); mNormalMapSpace = rhsLighting.mNormalMapSpace; mNormalMapTextureName = rhsLighting.mNormalMapTextureName; mNormalMapSampler = rhsLighting.mNormalMapSampler; } //----------------------------------------------------------------------- bool NormalMapLighting::preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass) { TextureUnitState* normalMapTexture = dstPass->createTextureUnitState(); normalMapTexture->setTextureName(mNormalMapTextureName); normalMapTexture->setSampler(mNormalMapSampler); mNormalMapSamplerIndex = dstPass->getNumTextureUnitStates() - 1; return true; } bool NormalMapLighting::setParameter(const String& name, const String& value) { if(name == "normalmap_space") { // Normal map defines normals in tangent space. if (value == "tangent_space") { setNormalMapSpace(NMS_TANGENT); return true; } // Normal map defines normals in object space. if (value == "object_space") { setNormalMapSpace(NMS_OBJECT); return true; } if (value == "parallax") { setNormalMapSpace(NMS_PARALLAX); return true; } return false; } if(name == "texture") { mNormalMapTextureName = value; return true; } if(name == "texcoord_index") { setTexCoordIndex(StringConverter::parseInt(value)); return true; } if(name == "sampler") { auto sampler = TextureManager::getSingleton().getSampler(value); if(!sampler) return false; mNormalMapSampler = sampler; return true; } return false; } //----------------------------------------------------------------------- const String& NormalMapLightingFactory::getType() const { return SRS_NORMALMAP; } //----------------------------------------------------------------------- SubRenderState* NormalMapLightingFactory::createInstance(ScriptCompiler* compiler, PropertyAbstractNode* prop, Pass* pass, SGScriptTranslator* translator) { if (prop->name == "lighting_stage") { if(prop->values.size() >= 2) { String strValue; AbstractNodeList::const_iterator it = prop->values.begin(); // Read light model type. if(false == SGScriptTranslator::getString(*it, &strValue)) { compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); return NULL; } // Case light model type is normal map if (strValue == "normal_map") { ++it; if (false == SGScriptTranslator::getString(*it, &strValue)) { compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, prop->file, prop->line); return NULL; } SubRenderState* subRenderState = createOrRetrieveInstance(translator); NormalMapLighting* normalMapSubRenderState = static_cast<NormalMapLighting*>(subRenderState); normalMapSubRenderState->setParameter("texture", strValue); // Read normal map space type. if (prop->values.size() >= 3) { ++it; if (false == SGScriptTranslator::getString(*it, &strValue)) { compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, prop->file, prop->line); return NULL; } if(!normalMapSubRenderState->setParameter("normalmap_space", strValue)) { compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); return NULL; } } // Read texture coordinate index. if (prop->values.size() >= 4) { unsigned int textureCoordinateIndex = 0; ++it; if (SGScriptTranslator::getUInt(*it, &textureCoordinateIndex)) { normalMapSubRenderState->setTexCoordIndex(textureCoordinateIndex); } } // Read texture filtering format. if (prop->values.size() >= 5) { ++it; if (false == SGScriptTranslator::getString(*it, &strValue)) { compiler->addError(ScriptCompiler::CE_STRINGEXPECTED, prop->file, prop->line); return NULL; } // sampler reference if(!normalMapSubRenderState->setParameter("sampler", strValue)) { compiler->addError(ScriptCompiler::CE_INVALIDPARAMETERS, prop->file, prop->line); return NULL; } } return subRenderState; } } } return NULL; } //----------------------------------------------------------------------- void NormalMapLightingFactory::writeInstance(MaterialSerializer* ser, SubRenderState* subRenderState, Pass* srcPass, Pass* dstPass) { NormalMapLighting* normalMapSubRenderState = static_cast<NormalMapLighting*>(subRenderState); ser->writeAttribute(4, "lighting_stage"); ser->writeValue("normal_map"); ser->writeValue(normalMapSubRenderState->getNormalMapTextureName()); if (normalMapSubRenderState->getNormalMapSpace() == NormalMapLighting::NMS_TANGENT) { ser->writeValue("tangent_space"); } else if (normalMapSubRenderState->getNormalMapSpace() == NormalMapLighting::NMS_OBJECT) { ser->writeValue("object_space"); } ser->writeValue(StringConverter::toString(normalMapSubRenderState->getTexCoordIndex())); } //----------------------------------------------------------------------- SubRenderState* NormalMapLightingFactory::createInstanceImpl() { return OGRE_NEW NormalMapLighting; } } } #endif <|endoftext|>
<commit_before>/*------------ant.cpp---------------------------------------------------------// * * ants -- We have them * * Purpose: Figure out ant pathing to food. I want food. * *-----------------------------------------------------------------------------*/ #include <iostream> #include <vector> /*----------------------------------------------------------------------------// * STRUCTS *-----------------------------------------------------------------------------*/ const int n = 5; struct coord{ int x, y; }; struct ant{ coord pos; std::vector<coord> phepath, antpath; int step; }; struct grid{ bool wall[n][n]; coord prize; }; /*----------------------------------------------------------------------------// * MAIN *-----------------------------------------------------------------------------*/ int main(){ } /*----------------------------------------------------------------------------// * SUBROUTINES *-----------------------------------------------------------------------------*/ <commit_msg>updating generation 1 pathing.<commit_after>/*------------ant.cpp---------------------------------------------------------// * * ants -- We have them * * Purpose: Figure out ant pathing to food. I want food. * *-----------------------------------------------------------------------------*/ #include <iostream> #include <vector> #include <random> /*----------------------------------------------------------------------------// * STRUCTS *-----------------------------------------------------------------------------*/ // grid size const int n = 5; // structs for ant movement struct coord{ int x, y; }; struct ant{ coord pos; std::vector<coord> phepath, antpath; int step; }; struct grid{ bool wall[n][n]; coord prize; }; // Functions for ant movement // Chooses step ant step1(ant curr, grid landscape, coord spawn_point); ant step(ant curr, grid landscape, coord spawn_point); // Generates ants std::vector <ant> gen_ants(coord spawn_point); // Moves simulation every timestep std::vector <ant> move(std::vector <ant> ants, grid landscape); /*----------------------------------------------------------------------------// * MAIN *-----------------------------------------------------------------------------*/ int main(){ } /*----------------------------------------------------------------------------// * SUBROUTINES *-----------------------------------------------------------------------------*/ // Chooses step ant step1(ant curr, grid landscape, coord spawn_point){ coord next_step[3]; coord up, down, left, right, next; int pcount = 0; up.x = curr.pos.x; up.y = curr.pos.y + 1; down.x = curr.pos.x; down.y = curr.pos.y - 1; left.x = curr.pos.x - 1; left.y = curr.pos.y; right.x = curr.pos.x + 1; right.y = curr.pos.y; // determine possible movement for (int i = 0; i < 4; i++){ switch(i){ // up case case 0: if (up.x == curr.antpath.back().x && up.y == curr.antpath.back().y){ } else{ next_step[pcount] = up; pcount++; } break; // down case case 1: if (down.x == curr.antpath.back().x && down.y == curr.antpath.back().y){ } else{ next_step[pcount] = down; pcount++; } break; // left case case 2: if (left.x == curr.antpath.back().x && left.y == curr.antpath.back().y){ } else{ next_step[pcount] = left; pcount++; } break; // right case case 3: if (right.x == curr.antpath.back().x && right.y == curr.antpath.back().y){ } else{ next_step[pcount] = right; pcount++; } break; } } static std::random_device rd; int seed = rd(); static std::mt19937 gen(seed); std::uniform_int_distribution<int> ant_distribution(0,3); next = next_step[ant_distribution(gen)]; curr.antpath.push_back(curr.pos); curr.pos = next; return curr; } <|endoftext|>
<commit_before>/** * @file CleanRoleDecision.h * * @author <a href="mailto:schahin.tofangchi@hu-berlin.de">Schahin Tofangchi</a> */ #include "CleanRoleDecision.h" #include <PlatformInterface/Platform.h> #include <Tools/DataConversion.h> #include <math.h> #include <list> using namespace std; CleanRoleDecision::CleanRoleDecision() { getDebugParameterList().add(&parameters); DEBUG_REQUEST_REGISTER("RoleDecision:min_ball_distance", "draws the circle of the min. ball distance to be recognized as different balls between first/second striker.", false); } CleanRoleDecision::~CleanRoleDecision() { getDebugParameterList().remove(&parameters); } void CleanRoleDecision::execute() { computeStrikers(); // reset second striker decision, if we doesn't want to use the second striker if(!parameters.useSecondStriker) { getRoleDecisionModel().secondStriker = std::numeric_limits<unsigned int>::max(); } }//end execute void CleanRoleDecision::computeStrikers() { // skip "first frame"! (until i add myself to teamcomm) if(getTeamMessage().data.find(getPlayerInfo().playerNumber) == getTeamMessage().data.end()) { return; } // container storing robots, which want to be striker, sorted by their playernumber and their time to ball std::map<unsigned int, unsigned int> possible_striker; // iterate over all robots(messages) for (auto const& i : getTeamMessage().data) { unsigned int robotNumber = i.first; const TeamMessageData& msg = i.second; // if striker lost the ball, he gets a time bonus before he lost the ball completely ... double loose_ball_bonus = msg.playerNumber == getRoleDecisionModel().firstStriker?parameters.strikerBonusTime:0.0; // check if the robot is able to play and sees the ball bool isRobotInactive = !getTeamMessagePlayersState().isPlaying(robotNumber) || msg.ballAge < 0 //Ball was never seen || (msg.ballAge + getFrameInfo().getTimeSince(msg.frameInfo.getTime()) > parameters.maxBallLostTime + loose_ball_bonus); //Ball isn't fresh // ignore inactive robots if(robotNumber != getPlayerInfo().playerNumber && isRobotInactive) { continue; } // for all active robots, which sees the ball AND previously announced to want to be striker OR is striker ... if (msg.custom.wantsToBeStriker || msg.custom.wasStriker) { // ... remember them as possible striker with their time to ball possible_striker[robotNumber] = msg.custom.timeToBall; } }//end for // get my own message auto ownMessage = getTeamMessage().data.at(getPlayerInfo().playerNumber); // i want to be striker, if i'm not the goalie and i'm "active" (not fallen/penalized, see the ball)!!! getRoleDecisionModel().wantsToBeStriker = ownMessage.playerNumber != 1 && getTeamMessagePlayersState().isPlaying(getPlayerInfo().playerNumber) && !(ownMessage.ballAge < 0 || (ownMessage.ballAge + getFrameInfo().getTimeSince(ownMessage.frameInfo.getTime()) > parameters.maxBallLostTime + (getPlayerInfo().playerNumber==getRoleDecisionModel().firstStriker?parameters.strikerBonusTime:0.0))); // if i'm striker, i get a time bonus! // NOTE: ownTimeToBall can be negative if the robot is close to ball (!) double ownTimeToBall = static_cast<double>(ownMessage.custom.timeToBall) - (ownMessage.custom.wasStriker ? 300.0 : 0.0); // clear for new striker decision getRoleDecisionModel().resetStriker(); (this->*parameters.strikerSelectionFunction)(possible_striker, ownTimeToBall); PLOT(std::string("CleanRoleDecision:FirstStrikerDecision"), getRoleDecisionModel().firstStriker); PLOT(std::string("CleanRoleDecision:SecondStrikerDecision"), getRoleDecisionModel().secondStriker); PLOT(std::string("CleanRoleDecision:PossibleStriker"), static_cast<double>(possible_striker.size())); } void CleanRoleDecision::strikerSelectionByNumber(std::map<unsigned int, unsigned int>& possible_striker, double& ownTimeToBall) { for (auto it = possible_striker.cbegin(); it != possible_striker.cend(); ++it) { //If two robots want to be striker, the one with a smaller number is favoured => is the first in the map!! // NOTE: we're doesn't using 'timeToBall' as decision criteria by intention! // if goalie is striker, he get's the first striker if(getRoleDecisionModel().firstStriker == std::numeric_limits<unsigned int>::max()) { getRoleDecisionModel().firstStriker = it->first; } else if (getRoleDecisionModel().secondStriker == std::numeric_limits<unsigned int>::max()) { getRoleDecisionModel().secondStriker = it->first; } // if there's a robot closer to the ball than myself, i don't want to be striker! if(it->second < ownTimeToBall) { getRoleDecisionModel().wantsToBeStriker = false; } } } void CleanRoleDecision::strikerSelectionByTime(std::map<unsigned int, unsigned int>& possible_striker, double &ownTimeToBall) { unsigned int stFastest = std::numeric_limits<unsigned int>::max(); // time to ball of the fastest player unsigned int ndFastest = std::numeric_limits<unsigned int>::max(); // time to ball of the second fastest player for (auto it = possible_striker.cbegin(); it != possible_striker.cend(); ++it) { // current player faster? if(it->second < stFastest) { // is there already a "fastest" striker ... but the current player is faster if(getRoleDecisionModel().firstStriker != std::numeric_limits<unsigned int>::max()) { // make the previous player the "second fastest" player getRoleDecisionModel().secondStriker = getRoleDecisionModel().firstStriker; ndFastest = stFastest; } // set the fastest player getRoleDecisionModel().firstStriker = it->first; stFastest = it->second; } else if (it->second < ndFastest) { // set the second fastest player getRoleDecisionModel().secondStriker = it->first; ndFastest = it->second; } // if there's a 2nd robot closer to the ball than myself, i don't want to be (second)striker! if(ndFastest < ownTimeToBall) { getRoleDecisionModel().wantsToBeStriker = false; } } } void CleanRoleDecision::strikerSelectionByTimeExceptGoalie(std::map<unsigned int, unsigned int>& possible_striker, double &ownTimeToBall) { unsigned int stFastest = std::numeric_limits<unsigned int>::max(); // time to ball of the fastest player unsigned int ndFastest = std::numeric_limits<unsigned int>::max(); // time to ball of the second fastest player // NOTE: if the goalie is one of the "possible striker", it gets set as first strike! (sorted map!) // and doesn't change, even if someone is faster (condition!) // ATTENTION: we're iterating from the smallest player number to the highest! for (auto it = possible_striker.cbegin(); it != possible_striker.cend(); ++it) { // is current player clearly faster? if(it->second < stFastest && (it->second + parameters.strikerSelectionDiffThreshold) < stFastest && getRoleDecisionModel().firstStriker != 1) { // is there already a "fastest" striker ... but the current player is faster if(getRoleDecisionModel().firstStriker != std::numeric_limits<unsigned int>::max()) { // make the previous player the "second fastest" player getRoleDecisionModel().secondStriker = getRoleDecisionModel().firstStriker; ndFastest = stFastest; } // set the fastest player getRoleDecisionModel().firstStriker = it->first; stFastest = it->second; } else if (it->second < ndFastest && (it->second + parameters.strikerSelectionDiffThreshold) < ndFastest) { // set the second (clearly) fastest player getRoleDecisionModel().secondStriker = it->first; ndFastest = it->second; } // if there's a 2nd robot closer to the ball than myself, i don't want to be (second)striker! if(ndFastest < ownTimeToBall) { getRoleDecisionModel().wantsToBeStriker = false; } } } void CleanRoleDecision::strikerSelectionByTimeExceptGoalieWithBallCompare(std::map<unsigned int, unsigned int>& possible_striker, double &ownTimeToBall) { unsigned int stFastest = std::numeric_limits<unsigned int>::max(); // time to ball of the fastest player unsigned int ndFastest = std::numeric_limits<unsigned int>::max(); // time to ball of the second fastest player // NOTE: if the goalie is one of the "possible striker", it gets set as first strike! (sorted map!) // and doesn't change, even if someone is faster (condition!) // ATTENTION: we're iterating from the smallest player number to the highest! for (auto it = possible_striker.cbegin(); it != possible_striker.cend(); ++it) { // is current player clearly faster? if(it->second < stFastest && (it->second + parameters.strikerSelectionDiffThreshold) < stFastest && getRoleDecisionModel().firstStriker != 1) { // is there already a "fastest" striker ... but the current player is faster if(getRoleDecisionModel().firstStriker != std::numeric_limits<unsigned int>::max() && isSecondStrikerDifferentFromFirst(getRoleDecisionModel().firstStriker, it->first)) { // make the previous player the "second fastest" player, if they see different balls getRoleDecisionModel().secondStriker = getRoleDecisionModel().firstStriker; ndFastest = stFastest; } // set the fastest player getRoleDecisionModel().firstStriker = it->first; stFastest = it->second; } else if (it->second < ndFastest && (it->second + parameters.strikerSelectionDiffThreshold) < ndFastest && isSecondStrikerDifferentFromFirst(getRoleDecisionModel().firstStriker, it->first)) { // make the previous player the "second fastest" player, if they see different balls getRoleDecisionModel().secondStriker = it->first; ndFastest = it->second; } // if there's a 2nd robot closer to the ball than myself, i don't want to be (second)striker! if(ndFastest < ownTimeToBall) { getRoleDecisionModel().wantsToBeStriker = false; } } } bool CleanRoleDecision::isSecondStrikerDifferentFromFirst(unsigned int firstNumber, unsigned int secondNumber) { // retrieve the message of the players const auto& first = getTeamMessage().data.at(firstNumber); const auto& second = getTeamMessage().data.at(secondNumber); // get the global ball position Vector2d firstBall = first.pose * first.ballPosition; Vector2d secondBall = second.pose * second.ballPosition; // check if the ball distance is greater than the given parameter distance radius double r = parameters.radius(first.ballPosition, second.ballPosition); DEBUG_REQUEST("RoleDecision:min_ball_distance", FIELD_DRAWING_CONTEXT; PEN("000000", 30); CIRCLE(firstBall.x, firstBall.y, r); TEXT_DRAWING(firstBall.x, firstBall.y, secondNumber); ); return ((firstBall - secondBall).abs2() > r*r); } <commit_msg>better description/info of the drawing<commit_after>/** * @file CleanRoleDecision.h * * @author <a href="mailto:schahin.tofangchi@hu-berlin.de">Schahin Tofangchi</a> */ #include "CleanRoleDecision.h" #include <PlatformInterface/Platform.h> #include <Tools/DataConversion.h> #include <math.h> #include <list> using namespace std; CleanRoleDecision::CleanRoleDecision() { getDebugParameterList().add(&parameters); DEBUG_REQUEST_REGISTER( "RoleDecision:min_ball_distance", "Draws the distance in which the balls of the first and second striker are recognized as identical (only with strikerSelection = 3).", false ); } CleanRoleDecision::~CleanRoleDecision() { getDebugParameterList().remove(&parameters); } void CleanRoleDecision::execute() { computeStrikers(); // reset second striker decision, if we doesn't want to use the second striker if(!parameters.useSecondStriker) { getRoleDecisionModel().secondStriker = std::numeric_limits<unsigned int>::max(); } }//end execute void CleanRoleDecision::computeStrikers() { // skip "first frame"! (until i add myself to teamcomm) if(getTeamMessage().data.find(getPlayerInfo().playerNumber) == getTeamMessage().data.end()) { return; } // container storing robots, which want to be striker, sorted by their playernumber and their time to ball std::map<unsigned int, unsigned int> possible_striker; // iterate over all robots(messages) for (auto const& i : getTeamMessage().data) { unsigned int robotNumber = i.first; const TeamMessageData& msg = i.second; // if striker lost the ball, he gets a time bonus before he lost the ball completely ... double loose_ball_bonus = msg.playerNumber == getRoleDecisionModel().firstStriker?parameters.strikerBonusTime:0.0; // check if the robot is able to play and sees the ball bool isRobotInactive = !getTeamMessagePlayersState().isPlaying(robotNumber) || msg.ballAge < 0 //Ball was never seen || (msg.ballAge + getFrameInfo().getTimeSince(msg.frameInfo.getTime()) > parameters.maxBallLostTime + loose_ball_bonus); //Ball isn't fresh // ignore inactive robots if(robotNumber != getPlayerInfo().playerNumber && isRobotInactive) { continue; } // for all active robots, which sees the ball AND previously announced to want to be striker OR is striker ... if (msg.custom.wantsToBeStriker || msg.custom.wasStriker) { // ... remember them as possible striker with their time to ball possible_striker[robotNumber] = msg.custom.timeToBall; } }//end for // get my own message auto ownMessage = getTeamMessage().data.at(getPlayerInfo().playerNumber); // i want to be striker, if i'm not the goalie and i'm "active" (not fallen/penalized, see the ball)!!! getRoleDecisionModel().wantsToBeStriker = ownMessage.playerNumber != 1 && getTeamMessagePlayersState().isPlaying(getPlayerInfo().playerNumber) && !(ownMessage.ballAge < 0 || (ownMessage.ballAge + getFrameInfo().getTimeSince(ownMessage.frameInfo.getTime()) > parameters.maxBallLostTime + (getPlayerInfo().playerNumber==getRoleDecisionModel().firstStriker?parameters.strikerBonusTime:0.0))); // if i'm striker, i get a time bonus! // NOTE: ownTimeToBall can be negative if the robot is close to ball (!) double ownTimeToBall = static_cast<double>(ownMessage.custom.timeToBall) - (ownMessage.custom.wasStriker ? 300.0 : 0.0); // clear for new striker decision getRoleDecisionModel().resetStriker(); (this->*parameters.strikerSelectionFunction)(possible_striker, ownTimeToBall); PLOT(std::string("CleanRoleDecision:FirstStrikerDecision"), getRoleDecisionModel().firstStriker); PLOT(std::string("CleanRoleDecision:SecondStrikerDecision"), getRoleDecisionModel().secondStriker); PLOT(std::string("CleanRoleDecision:PossibleStriker"), static_cast<double>(possible_striker.size())); } void CleanRoleDecision::strikerSelectionByNumber(std::map<unsigned int, unsigned int>& possible_striker, double& ownTimeToBall) { for (auto it = possible_striker.cbegin(); it != possible_striker.cend(); ++it) { //If two robots want to be striker, the one with a smaller number is favoured => is the first in the map!! // NOTE: we're doesn't using 'timeToBall' as decision criteria by intention! // if goalie is striker, he get's the first striker if(getRoleDecisionModel().firstStriker == std::numeric_limits<unsigned int>::max()) { getRoleDecisionModel().firstStriker = it->first; } else if (getRoleDecisionModel().secondStriker == std::numeric_limits<unsigned int>::max()) { getRoleDecisionModel().secondStriker = it->first; } // if there's a robot closer to the ball than myself, i don't want to be striker! if(it->second < ownTimeToBall) { getRoleDecisionModel().wantsToBeStriker = false; } } } void CleanRoleDecision::strikerSelectionByTime(std::map<unsigned int, unsigned int>& possible_striker, double &ownTimeToBall) { unsigned int stFastest = std::numeric_limits<unsigned int>::max(); // time to ball of the fastest player unsigned int ndFastest = std::numeric_limits<unsigned int>::max(); // time to ball of the second fastest player for (auto it = possible_striker.cbegin(); it != possible_striker.cend(); ++it) { // current player faster? if(it->second < stFastest) { // is there already a "fastest" striker ... but the current player is faster if(getRoleDecisionModel().firstStriker != std::numeric_limits<unsigned int>::max()) { // make the previous player the "second fastest" player getRoleDecisionModel().secondStriker = getRoleDecisionModel().firstStriker; ndFastest = stFastest; } // set the fastest player getRoleDecisionModel().firstStriker = it->first; stFastest = it->second; } else if (it->second < ndFastest) { // set the second fastest player getRoleDecisionModel().secondStriker = it->first; ndFastest = it->second; } // if there's a 2nd robot closer to the ball than myself, i don't want to be (second)striker! if(ndFastest < ownTimeToBall) { getRoleDecisionModel().wantsToBeStriker = false; } } } void CleanRoleDecision::strikerSelectionByTimeExceptGoalie(std::map<unsigned int, unsigned int>& possible_striker, double &ownTimeToBall) { unsigned int stFastest = std::numeric_limits<unsigned int>::max(); // time to ball of the fastest player unsigned int ndFastest = std::numeric_limits<unsigned int>::max(); // time to ball of the second fastest player // NOTE: if the goalie is one of the "possible striker", it gets set as first strike! (sorted map!) // and doesn't change, even if someone is faster (condition!) // ATTENTION: we're iterating from the smallest player number to the highest! for (auto it = possible_striker.cbegin(); it != possible_striker.cend(); ++it) { // is current player clearly faster? if(it->second < stFastest && (it->second + parameters.strikerSelectionDiffThreshold) < stFastest && getRoleDecisionModel().firstStriker != 1) { // is there already a "fastest" striker ... but the current player is faster if(getRoleDecisionModel().firstStriker != std::numeric_limits<unsigned int>::max()) { // make the previous player the "second fastest" player getRoleDecisionModel().secondStriker = getRoleDecisionModel().firstStriker; ndFastest = stFastest; } // set the fastest player getRoleDecisionModel().firstStriker = it->first; stFastest = it->second; } else if (it->second < ndFastest && (it->second + parameters.strikerSelectionDiffThreshold) < ndFastest) { // set the second (clearly) fastest player getRoleDecisionModel().secondStriker = it->first; ndFastest = it->second; } // if there's a 2nd robot closer to the ball than myself, i don't want to be (second)striker! if(ndFastest < ownTimeToBall) { getRoleDecisionModel().wantsToBeStriker = false; } } } void CleanRoleDecision::strikerSelectionByTimeExceptGoalieWithBallCompare(std::map<unsigned int, unsigned int>& possible_striker, double &ownTimeToBall) { unsigned int stFastest = std::numeric_limits<unsigned int>::max(); // time to ball of the fastest player unsigned int ndFastest = std::numeric_limits<unsigned int>::max(); // time to ball of the second fastest player // NOTE: if the goalie is one of the "possible striker", it gets set as first strike! (sorted map!) // and doesn't change, even if someone is faster (condition!) // ATTENTION: we're iterating from the smallest player number to the highest! for (auto it = possible_striker.cbegin(); it != possible_striker.cend(); ++it) { // is current player clearly faster? if(it->second < stFastest && (it->second + parameters.strikerSelectionDiffThreshold) < stFastest && getRoleDecisionModel().firstStriker != 1) { // is there already a "fastest" striker ... but the current player is faster if(getRoleDecisionModel().firstStriker != std::numeric_limits<unsigned int>::max() && isSecondStrikerDifferentFromFirst(it->first, getRoleDecisionModel().firstStriker)) { // make the previous player the "second fastest" player, if they see different balls getRoleDecisionModel().secondStriker = getRoleDecisionModel().firstStriker; ndFastest = stFastest; } // set the fastest player getRoleDecisionModel().firstStriker = it->first; stFastest = it->second; } else if (it->second < ndFastest && (it->second + parameters.strikerSelectionDiffThreshold) < ndFastest && isSecondStrikerDifferentFromFirst(getRoleDecisionModel().firstStriker, it->first)) { // make the previous player the "second fastest" player, if they see different balls getRoleDecisionModel().secondStriker = it->first; ndFastest = it->second; } // if there's a 2nd robot closer to the ball than myself, i don't want to be (second)striker! if(ndFastest < ownTimeToBall) { getRoleDecisionModel().wantsToBeStriker = false; } } } bool CleanRoleDecision::isSecondStrikerDifferentFromFirst(unsigned int firstNumber, unsigned int secondNumber) { // retrieve the message of the players const auto& first = getTeamMessage().data.at(firstNumber); const auto& second = getTeamMessage().data.at(secondNumber); // get the global ball position Vector2d firstBall = first.pose * first.ballPosition; Vector2d secondBall = second.pose * second.ballPosition; // check if the ball distance is greater than the given parameter distance radius double r = parameters.radius(first.ballPosition, second.ballPosition); DEBUG_REQUEST("RoleDecision:min_ball_distance", FIELD_DRAWING_CONTEXT; PEN("000000", 30); CIRCLE(firstBall.x, firstBall.y, r); TEXT_DRAWING(firstBall.x, firstBall.y+60, secondNumber); TEXT_DRAWING(firstBall.x, firstBall.y-60, r); ); return ((firstBall - secondBall).abs2() > r*r); } <|endoftext|>
<commit_before>//##################################################################### // Module math //##################################################################### #include <other/core/python/wrap.h> void wrap_math() { OTHER_WRAP(uint128) OTHER_WRAP(numeric_limits) } <commit_msg>utility/module: Wrap integer_log for Python<commit_after>//##################################################################### // Module math //##################################################################### #include <other/core/math/integer_log.h> #include <other/core/python/wrap.h> using namespace other; void wrap_math() { OTHER_WRAP(uint128) OTHER_WRAP(numeric_limits) OTHER_FUNCTION_2(integer_log,static_cast<int(*)(uint64_t)>(integer_log)); } <|endoftext|>
<commit_before>// // API.cpp // miniSQL // // Created by Kael on 11/3/14. // Copyright (c) 2014 Xinyuan Lu. All rights reserved. // // v2.0, see comment in "APT.h" #include "API.h" Recordinfo API::dealCmd(sqlcommand& sql){ // 使用get方法更好,这里先直接调用public switch(sql.sqlType){ case 0: return select(sql); break; case 1: return del(sql); break; case 2: return insert(sql); break; case 3: return createTable(sql); break; case 4: return createIndex(sql); break; case 5: return dropTable(sql); break; case 6: return dropIndex(sql); break; } return Recordinfo(); } int API::AttrCount(std::string tablename){ return catalogmanager->AttrCount(tablename); } bool API::TableExists(std::string tablename){ return catalogmanager->TableExists(tablename); } bool API::IndexExists(std::string indexname){ return catalogmanager->IndexExists(indexname); } bool API::AttrExists(std::string attrname,std::string tablename){ return catalogmanager->AttrExists(attrname, tablename); } // 以下所有的都需要错误输入的检查? Recordinfo API::select(sqlcommand& sql){ // 先到catalog查看是否有index // 如果有就用,然后作intersection // 如果没有,直接交给record? // 可以减少数据传递的overhead bool flag=false; std::vector<std::vector<std::string> >::iterator conditioni; Recordinfo result; int IndexAttrType=0x7fff; for(conditioni=sql.conditions.begin(); conditioni<sql.conditions.end(); conditioni++){ flag=catalogmanager->hasIndex(sql.tablename, (*conditioni).at(0)); if(flag) { IndexAttrType=catalogmanager->getAttrType(sql.tablename, (*conditioni).at(0)); break; } } // 需要商量 Table table=catalogmanager->getTable(sql.tablename); if(!flag) { std::vector<slot> slots; result=recordmanager->Select_Record(sql, table, false, slots); } else{ Value *v=NULL; switch(IndexAttrType){ case 0: v=new Value(IndexAttrType, std::stoi((*conditioni).at(2))); break; case 1: v=new Value(IndexAttrType, (*conditioni).at(2)); break; case -1: v=new Value(IndexAttrType, std::stof((*conditioni).at(2))); break; } IndexManager *indexmanager=new IndexManager(); std::vector<slot> s; if((*conditioni).at(1)=="<") s=indexmanager->_FindSmall((*conditioni).at(0), *v); else if((*conditioni).at(1)=="<=") s=indexmanager->_FindSmallEqual((*conditioni).at(0), *v); else if((*conditioni).at(1)==">") s=indexmanager->_FindBigger((*conditioni).at(0), *v); else if((*conditioni).at(1)==">=") s=indexmanager->_FindBiggerEqual((*conditioni).at(0), *v); else if((*conditioni).at(1)=="<>") s=indexmanager->_FindNotEqual((*conditioni).at(0), *v); else if((*conditioni).at(1)=="=") s.push_back(indexmanager->select((*conditioni).at(0), *v)); if(s.size()==0 || (s.size()==1 && s[0].block_id==-1)){ delete v; return Recordinfo(false, "Cannot find the record!", Result(), 0); } result=recordmanager->Select_Record(sql, table, true, s); // 然后开始剩下的暴力获取 sql.conditions.erase(conditioni); Recordinfo result2=recordmanager->Select_Record(sql, table, false, s); // and result.AND(result2); delete v; } return result; } Recordinfo API::del(sqlcommand& sql){ bool flag=false; // int n=-1; // 记录第几个是index std::vector<std::vector<std::string> >::iterator conditioni; Recordinfo result; int IndexAttrType=0x7fff; for(conditioni=sql.conditions.begin(); conditioni<sql.conditions.end(); conditioni++){ flag=catalogmanager->hasIndex(sql.tablename, (*conditioni).at(0)); if(flag) { IndexAttrType=catalogmanager->getAttrType(sql.tablename, (*conditioni).at(0)); break; } } // 需要商量 Table table=catalogmanager->getTable(sql.tablename); if(!flag) { std::vector<slot> slots; result=recordmanager->Delete_Record(sql, table, false, slots); } else{ Value *v=NULL; switch(IndexAttrType){ case 0:v=new Value(IndexAttrType, std::stoi((*conditioni).at(2)));break; case 1:v=new Value(IndexAttrType, (*conditioni).at(2));break; case -1:v=new Value(IndexAttrType, std::stof((*conditioni).at(2)));break; } std::vector<slot> s; if((*conditioni).at(1)=="<") s=indexmanager->_FindSmall((*conditioni).at(0), *v); else if((*conditioni).at(1)=="<=") s=indexmanager->_FindSmallEqual((*conditioni).at(0), *v); else if((*conditioni).at(1)==">") s=indexmanager->_FindBigger((*conditioni).at(0), *v); else if((*conditioni).at(1)==">=") s=indexmanager->_FindBiggerEqual((*conditioni).at(0), *v); else if((*conditioni).at(1)=="<>") s=indexmanager->_FindNotEqual((*conditioni).at(0), *v); else if((*conditioni).at(1)=="=") s.push_back(indexmanager->select((*conditioni).at(0), *v)); if(s.size()==0 || (s.size()==1 && s[0].block_id==-1)){ delete v; return Recordinfo(false, "Cannot find the record!", Result(), 0); } result=recordmanager->Delete_Record(sql, table, true, s); // 然后开始剩下的暴力获取 sql.conditions.erase(conditioni); Recordinfo result2=recordmanager->Select_Record(sql, table, false, s); // and result.AND(result2); delete v; } return result; } Recordinfo API::insert(sqlcommand& sql){ // 为什么insert也要有sqlcommand???? // 插入index Recordinfo result; Table table=catalogmanager->getTable(sql.tablename); int block_id; int record_id; // check primary std::string primarykey=catalogmanager->pkOnTable(sql.tablename); if(primarykey=="Table not found in CatalogBlocks!"){ result=Recordinfo(false, primarykey, Result(), 0); return result; } else{ for(int i=0; i<sql.colValue.size(); i++){ if(catalogmanager->isUnique(sql.tablename, i) || catalogmanager->isPK(sql.tablename, i)){ std::string attrname=catalogmanager->getAttrName(sql.tablename, i); // 如果有索引就用索引,并且更新索引 if(catalogmanager->hasIndex(sql.tablename, attrname)){ std::string indexname=catalogmanager->getIndexName(sql.tablename, attrname); int AttrType=catalogmanager->getAttrType(sql.tablename, primarykey); Value *v=NULL; switch(AttrType){ case 0:v=new Value(AttrType, std::stoi((sql.colValue).at(i)));break; case 1:v=new Value(AttrType, (sql.colValue).at(i));break; case -1:v=new Value(AttrType, std::stof(sql.colValue.at(i)));break; } slot s=indexmanager->select(indexname, *v); if(s.block_id!=-1){ Recordinfo result=Recordinfo(false, "The unique key value has existed!", Result(), 0); delete v; return result; } delete v; } // 没有索引直接查询 sqlcommand tempsql=sql; tempsql.sqlType=0; tempsql.conditions={{attrname, "=", sql.colValue[i]}}; tempsql.selectInfo={"*"}; Recordinfo r=recordmanager->Select_Record(tempsql, table, 0, std::vector<slot>()); if(r.successful){ result=Recordinfo(false, "The unique key value has existed!", Result(), 0); return result; } } } result=recordmanager->Insert_Record(sql, table, block_id, record_id); //插入索引 slot s=slot(block_id, record_id); for(int i=0; i<sql.colValue.size(); i++){ std::string attrname=catalogmanager->getAttrName(sql.tablename, i); if(catalogmanager->hasIndex(sql.tablename, attrname)){ std::string indexname=catalogmanager->getIndexName(sql.tablename, attrname); int AttrType=catalogmanager->getAttrType(sql.tablename, primarykey); Value *v=NULL; switch(AttrType){ case 0:v=new Value(AttrType, std::stoi((sql.colValue).at(i)));break; case 1:v=new Value(AttrType, (sql.colValue).at(i));break; case -1:v=new Value(AttrType, std::stof(sql.colValue.at(i)));break; } indexmanager->_insert(indexname, *v, s); } } // 解决可能的返回错误? return result; } } Recordinfo API::createTable(sqlcommand& sql){ catalogmanager->insertTable(sql); std::string pk; std::string tablename=sql.createTableInfo[0].at(0); if((pk=catalogmanager->pkOnTable(tablename))!="No primary key on this table!"){ // 可以创建空的index吧? indexmanager->CreateIndex(tablename+"$"+pk, catalogmanager->getAttrType(tablename, pk), std::vector<Value>(0), std::vector<slot>(0)); sqlcommand tempsql=sqlcommand(); tempsql.sqlType=4; tempsql.indexname=tablename+"$"+pk; tempsql.setCreateIndexInfo(tablename, pk); catalogmanager->insertIndex(tempsql); } return Recordinfo(); // further improve } Recordinfo API::createIndex(sqlcommand& sql){ std::string tablename=sql.createIndexInfo[1]; std::string indexname=sql.createIndexInfo[0]; int attrtype=catalogmanager->getAttrType(tablename, sql.createIndexInfo[2]); indexmanager->CreateIndex(sql.indexname, attrtype, std::vector<Value>(), std::vector<slot>()); catalogmanager->insertIndex(sql); return Recordinfo(); // further improve } // turn to Catalog find all index and // drop index // dropCatalog // drop all records Recordinfo API::dropTable(sqlcommand& sql){ std::string tablename=sql.tablename; for(int i=0; i<catalogmanager->AttrCount(tablename); i++){ std::string attrname=catalogmanager->getAttrName(tablename, i); if(catalogmanager->hasIndex(tablename, attrname)){ indexmanager->DropIndex(catalogmanager->getIndexName(tablename, attrname)); catalogmanager->dropIndex(catalogmanager->getIndexName(tablename, attrname)); } } catalogmanager->dropTable(sql.tablename); return Recordinfo(); // further improve } Recordinfo API::dropIndex(sqlcommand& sql){ catalogmanager->dropIndex(sql.indexname); indexmanager->DropIndex(sql.indexname); return Recordinfo(); // further improve // catalog }<commit_msg>update API<commit_after>// // API.cpp // miniSQL // // Created by Kael on 11/3/14. // Copyright (c) 2014 Xinyuan Lu. All rights reserved. // // v2.0, see comment in "APT.h" #include "API.h" Recordinfo API::dealCmd(sqlcommand& sql){ // 使用get方法更好,这里先直接调用public switch(sql.sqlType){ case 0: return select(sql); break; case 1: return del(sql); break; case 2: return insert(sql); break; case 3: return createTable(sql); break; case 4: return createIndex(sql); break; case 5: return dropTable(sql); break; case 6: return dropIndex(sql); break; } return Recordinfo(); } int API::AttrCount(std::string tablename){ return catalogmanager->AttrCount(tablename); } bool API::TableExists(std::string tablename){ return catalogmanager->TableExists(tablename); } bool API::IndexExists(std::string indexname){ return catalogmanager->IndexExists(indexname); } bool API::AttrExists(std::string attrname,std::string tablename){ return catalogmanager->AttrExists(attrname, tablename); } // 以下所有的都需要错误输入的检查? Recordinfo API::select(sqlcommand& sql){ // 先到catalog查看是否有index // 如果有就用,然后作intersection // 如果没有,直接交给record? // 可以减少数据传递的overhead bool flag=false; std::vector<std::vector<std::string> >::iterator conditioni; Recordinfo result; int IndexAttrType=0x7fff; for(conditioni=sql.conditions.begin(); conditioni<sql.conditions.end(); conditioni++){ flag=catalogmanager->hasIndex(sql.tablename, (*conditioni).at(0)); if(flag) { IndexAttrType=catalogmanager->getAttrType(sql.tablename, (*conditioni).at(0)); break; } } // 需要商量 Table table=catalogmanager->getTable(sql.tablename); if(!flag) { std::vector<slot> slots; result=recordmanager->Select_Record(sql, table, false, slots); } else{ Value *v=NULL; switch(IndexAttrType){ case 0: v=new Value(IndexAttrType, std::stoi((*conditioni).at(2))); break; case 1: v=new Value(IndexAttrType, (*conditioni).at(2)); break; case -1: v=new Value(IndexAttrType, std::stof((*conditioni).at(2))); break; } IndexManager *indexmanager=new IndexManager(); std::vector<slot> s; if((*conditioni).at(1)=="<") s=indexmanager->_FindSmall((*conditioni).at(0), *v); else if((*conditioni).at(1)=="<=") s=indexmanager->_FindSmallEqual((*conditioni).at(0), *v); else if((*conditioni).at(1)==">") s=indexmanager->_FindBigger((*conditioni).at(0), *v); else if((*conditioni).at(1)==">=") s=indexmanager->_FindBiggerEqual((*conditioni).at(0), *v); else if((*conditioni).at(1)=="<>") s=indexmanager->_FindNotEqual((*conditioni).at(0), *v); else if((*conditioni).at(1)=="=") s.push_back(indexmanager->select((*conditioni).at(0), *v)); if(s.size()==0 || (s.size()==1 && s[0].block_id==-1)){ delete v; return Recordinfo(false, "Cannot find the record!", Result(), 0); } result=recordmanager->Select_Record(sql, table, true, s); // 然后开始剩下的暴力获取 sql.conditions.erase(conditioni); Recordinfo result2=recordmanager->Select_Record(sql, table, false, s); // and result.AND(result2); delete v; } return result; } Recordinfo API::del(sqlcommand& sql){ bool flag=false; // int n=-1; // 记录第几个是index std::vector<std::vector<std::string> >::iterator conditioni; Recordinfo result; int IndexAttrType=0x7fff; for(conditioni=sql.conditions.begin(); conditioni<sql.conditions.end(); conditioni++){ flag=catalogmanager->hasIndex(sql.tablename, (*conditioni).at(0)); if(flag) { IndexAttrType=catalogmanager->getAttrType(sql.tablename, (*conditioni).at(0)); break; } } // 需要商量 Table table=catalogmanager->getTable(sql.tablename); if(!flag) { std::vector<slot> slots; result=recordmanager->Delete_Record(sql, table, false, slots); } else{ Value *v=NULL; switch(IndexAttrType){ case 0:v=new Value(IndexAttrType, std::stoi((*conditioni).at(2)));break; case 1:v=new Value(IndexAttrType, (*conditioni).at(2));break; case -1:v=new Value(IndexAttrType, std::stof((*conditioni).at(2)));break; } std::vector<slot> s; if((*conditioni).at(1)=="<") s=indexmanager->_FindSmall((*conditioni).at(0), *v); else if((*conditioni).at(1)=="<=") s=indexmanager->_FindSmallEqual((*conditioni).at(0), *v); else if((*conditioni).at(1)==">") s=indexmanager->_FindBigger((*conditioni).at(0), *v); else if((*conditioni).at(1)==">=") s=indexmanager->_FindBiggerEqual((*conditioni).at(0), *v); else if((*conditioni).at(1)=="<>") s=indexmanager->_FindNotEqual((*conditioni).at(0), *v); else if((*conditioni).at(1)=="=") s.push_back(indexmanager->select((*conditioni).at(0), *v)); if(s.size()==0 || (s.size()==1 && s[0].block_id==-1)){ delete v; return Recordinfo(false, "Cannot find the record!", Result(), 0); } result=recordmanager->Delete_Record(sql, table, true, s); // 然后开始剩下的暴力获取 sql.conditions.erase(conditioni); Recordinfo result2=recordmanager->Select_Record(sql, table, false, s); // and result.AND(result2); delete v; } return result; } Recordinfo API::insert(sqlcommand& sql){ // 为什么insert也要有sqlcommand???? // 插入index Recordinfo result; Table table=catalogmanager->getTable(sql.tablename); int block_id; int record_id; // check primary std::string primarykey=catalogmanager->pkOnTable(sql.tablename); if(primarykey=="Table not found in CatalogBlocks!"){ result=Recordinfo(false, primarykey, Result(), 0); return result; } else{ for(int i=0; i<sql.colValue.size(); i++){ if(catalogmanager->isUnique(sql.tablename, i) || catalogmanager->isPK(sql.tablename, i)){ std::string attrname=catalogmanager->getAttrName(sql.tablename, i); // 如果有索引就用索引,并且更新索引 if(catalogmanager->hasIndex(sql.tablename, attrname)){ std::string indexname=catalogmanager->getIndexName(sql.tablename, attrname); int AttrType=catalogmanager->getAttrType(sql.tablename, primarykey); Value *v=NULL; switch(AttrType){ case 0:v=new Value(AttrType, std::stoi((sql.colValue).at(i)));break; case 1:v=new Value(AttrType, (sql.colValue).at(i));break; case -1:v=new Value(AttrType, std::stof(sql.colValue.at(i)));break; } slot s=indexmanager->select(indexname, *v); if(s.block_id!=-1){ Recordinfo result=Recordinfo(false, "The unique key value has existed!", Result(), 0); delete v; return result; } delete v; } // 没有索引直接查询 sqlcommand tempsql=sql; tempsql.sqlType=0; tempsql.conditions={{attrname, "=", sql.colValue[i]}}; tempsql.selectInfo={"*"}; Recordinfo r=recordmanager->Select_Record(tempsql, table, 0, std::vector<slot>()); if(r.successful){ result=Recordinfo(false, "The unique key value has existed!", Result(), 0); return result; } } } result=recordmanager->Insert_Record(sql, table, block_id, record_id); //插入索引 slot s=slot(block_id, record_id); for(int i=0; i<sql.colValue.size(); i++){ std::string attrname=catalogmanager->getAttrName(sql.tablename, i); if(catalogmanager->hasIndex(sql.tablename, attrname)){ std::string indexname=catalogmanager->getIndexName(sql.tablename, attrname); int AttrType=catalogmanager->getAttrType(sql.tablename, primarykey); Value *v=NULL; switch(AttrType){ case 0:v=new Value(AttrType, std::stoi((sql.colValue).at(i)));break; case 1:v=new Value(AttrType, (sql.colValue).at(i));break; case -1:v=new Value(AttrType, std::stof(sql.colValue.at(i)));break; } indexmanager->_insert(indexname, *v, s); } } // 解决可能的返回错误? return result; } } Recordinfo API::createTable(sqlcommand& sql){ catalogmanager->insertTable(sql); std::string pk; std::string tablename=sql.createTableInfo[0].at(0); if((pk=catalogmanager->pkOnTable(tablename))!="No primary key on this table!"){ // 可以创建空的index吧? indexmanager->CreateIndex(tablename+"$"+pk, catalogmanager->getAttrType(tablename, pk), std::vector<Value>(0), std::vector<slot>(0)); sqlcommand tempsql=sqlcommand(); tempsql.sqlType=4; tempsql.indexname=tablename+"$"+pk; tempsql.setCreateIndexInfo(tablename, pk); catalogmanager->insertIndex(tempsql); } return Recordinfo(); // further improve } Recordinfo API::createIndex(sqlcommand& sql){ std::string tablename=sql.createIndexInfo[1]; std::string indexname=sql.createIndexInfo[0]; int attrtype=catalogmanager->getAttrType(tablename, sql.createIndexInfo[2]); catalogmanager->insertIndex(sql); indexmanager->CreateIndex(sql.indexname, attrtype, std::vector<Value>(), std::vector<slot>()); // insert all records to index sqlcommand tempsql=sqlcommand(); tempsql.sqlType=0; tempsql.selectInfo=std::vector<std::string>(); tempsql.selectInfo.push_back(sql.createIndexInfo[2]); tempsql.tablename=tablename; tempsql.conditions=std::vector<std::vector<std::string> >(); Table temptable=catalogmanager->getTable(tablename); std::vector<slot> tempslot=std::vector<slot>(); Recordinfo result=recordmanager->Select_Record(tempsql, temptable, 0, tempslot); for(int i=0;i<tempslot.size();i++){ Value v; switch(attrtype){ case 0:v=Value(attrtype, std::stoi(result.res.rows[i].cols[0]));break; case 1:v=Value(attrtype, result.res.rows[i].cols[0]);break; case -1:v=Value(attrtype, std::stof(result.res.rows[i].cols[0]));break; } indexmanager->_insert(indexname, v, tempslot[i]); } return Recordinfo(); // further improve } // turn to Catalog find all index and // drop index // dropCatalog // drop all records Recordinfo API::dropTable(sqlcommand& sql){ std::string tablename=sql.tablename; // delete all records sqlcommand tempsql=sqlcommand(); tempsql.sqlType=1; tempsql.conditions=std::vector<std::vector<std::string> >(); tempsql.tablename=sql.tablename; Table temptable=catalogmanager->getTable(sql.tablename); recordmanager->Delete_Record(tempsql, temptable, 0, std::vector<slot>()); // delete all indexes for(int i=0; i<catalogmanager->AttrCount(tablename); i++){ std::string attrname=catalogmanager->getAttrName(tablename, i); if(catalogmanager->hasIndex(tablename, attrname)){ indexmanager->DropIndex(catalogmanager->getIndexName(tablename, attrname)); catalogmanager->dropIndex(catalogmanager->getIndexName(tablename, attrname)); } } // delete catalog catalogmanager->dropTable(sql.tablename); return Recordinfo(); // further improve } Recordinfo API::dropIndex(sqlcommand& sql){ catalogmanager->dropIndex(sql.indexname); indexmanager->DropIndex(sql.indexname); return Recordinfo(); // further improve // catalog }<|endoftext|>
<commit_before>class TrieNode { public: bool isKey; TrieNode* children[26]; TrieNode(): isKey(false) { memset(children, NULL, sizeof(TrieNode*) * 26); } }; class WordDictionary { public: WordDictionary() { root = new TrieNode(); } // Adds a word into the data structure. void addWord(string word) { TrieNode* run = root; for (char c : word) { if (!(run -> children[c - 'a'])) run -> children[c - 'a'] = new TrieNode(); run = run -> children[c - 'a']; } run -> isKey = true; } // Returns if the word is in the data structure. A word could // contain the dot character '.' to represent any one letter. bool search(string word) { return query(word.c_str(), root); } private: TrieNode* root; bool query(const char* word, TrieNode* node) { TrieNode* run = node; for (int i = 0; word[i]; i++) { if (run && word[i] != '.') run = run -> children[word[i] - 'a']; else if (run && word[i] == '.') { TrieNode* tmp = run; for (int j = 0; j < 26; j++) { run = tmp -> children[j]; if (query(word + i + 1, run)) return true; } } else break; } return run && run -> isKey; } }; // Your WordDictionary object will be instantiated and called as such: // WordDictionary wordDictionary; // wordDictionary.addWord("word"); // wordDictionary.search("pattern");<commit_msg>Update 211.cpp<commit_after>/* * Trie * */ class TrieNode { public: bool isKey; TrieNode* children[26]; TrieNode(): isKey(false) { memset(children, NULL, sizeof(TrieNode*) * 26); } }; class WordDictionary { public: WordDictionary() { root = new TrieNode(); } // Adds a word into the data structure. void addWord(string word) { TrieNode* run = root; for (char c : word) { if (!(run -> children[c - 'a'])) run -> children[c - 'a'] = new TrieNode(); run = run -> children[c - 'a']; } run -> isKey = true; } // Returns if the word is in the data structure. A word could // contain the dot character '.' to represent any one letter. bool search(string word) { return query(word.c_str(), root); } private: TrieNode* root; bool query(const char* word, TrieNode* node) { TrieNode* run = node; for (int i = 0; word[i]; i++) { if (run && word[i] != '.') run = run -> children[word[i] - 'a']; else if (run && word[i] == '.') { TrieNode* tmp = run; for (int j = 0; j < 26; j++) { run = tmp -> children[j]; if (query(word + i + 1, run)) return true; } } else break; } return run && run -> isKey; } }; // Conclusion: // // // <|endoftext|>
<commit_before>/** * The MIT License (MIT) * * Copyright (c) 2015 Michael Egli * * 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. * * \author Michael Egli * \copyright Michael Egli * \date 11-Jul-2015 * * \file cpptime.cpp * * See the description in the header file for for more information. * */ // Includes #include <thread> #include <mutex> #include <condition_variable> #include <algorithm> #include <stack> #include <set> #include <queue> #include <unordered_map> #include "cpptime.h" namespace { using scoped_m = std::unique_lock<std::mutex>; // Prototypes CppTime::timer_id next_id(); // Use to terminate the timer thread. bool done = false; // The index variable used to construct the timer_id. uint64_t cur_id = 0; // Locking & Co std::mutex m; std::condition_variable cond; std::thread worker; // The event structure that holds the information about a timer. struct Event { CppTime::timer_id id; CppTime::timestamp start; CppTime::duration period; CppTime::handler_t handler; bool valid; Event() : id(0), start(CppTime::duration::zero()), period(CppTime::duration::zero()), handler(nullptr), valid(false) { } template <typename Func> Event(CppTime::timer_id id, CppTime::timestamp start, CppTime::duration period, Func &&handler) : id(id), start(start), period(period), handler(std::forward<Func>(handler)), valid(true) { } Event(Event &&r) noexcept : id(r.id), start(r.start), period(r.period), handler(std::move(r.handler)), valid(r.valid) { } Event &operator=(Event &&ev) noexcept { if(this != &ev) { id = ev.id; start = ev.start; period = ev.period; handler = std::move(ev.handler); valid = ev.valid; } return *this; } Event(const Event &r) = delete; Event &operator=(const Event &r) = delete; }; // A time event structure that holds the next timeout and a reference to its // Event struct. struct Time_event { CppTime::timestamp next; CppTime::timer_id ref; }; inline bool operator<(const Time_event &l, const Time_event &r) { return l.next < r.next; } // The vector that holds all active events. std::vector<Event> events; // Sorted queue that has the next timeout at its top. std::priority_queue<Time_event> time_events; // A list of ids to be re-used. If possible, ids are used from this pool. std::stack<CppTime::timer_id> free_ids; // Returns the next free id. First, we check the free ids before creating a new // one. CppTime::timer_id next_id() { if(free_ids.empty()) { return cur_id++; } CppTime::timer_id id = free_ids.top(); free_ids.pop(); return id; } // The thread main entry points. This is an endless loop until the `done` flag // is set to false. // TODO cleanup code to make it more readable (less if-else blocks). void run() { scoped_m lock(m); while(!done) { if(time_events.empty()) { // Wait for work cond.wait(lock); } else { auto te = time_events.top(); if(CppTime::clock::now() >= te.next) { // Remove time event time_events.pop(); Event &ev = events[te.ref]; if(!ev.valid) { // Return the id if the event is no longer valid. free_ids.push(te.ref); } else { // Invoke the handler lock.unlock(); ev.handler(te.ref); lock.lock(); if(!ev.valid) { // The callback removed the event. free_ids.push(te.ref); } else { if(ev.period.count() > 0) { te.next += ev.period; time_events.push(te); } else { ev.valid = false; free_ids.push(te.ref); } } } } else { cond.wait_until(lock, te.next); } } } } } // end anonymous namespace namespace CppTime { void start(size_t expected) { scoped_m lock(m); done = false; if(expected > 0) { events.resize(expected); } worker = std::thread(&run); } void stop() { scoped_m lock(m); done = true; events.clear(); while(!time_events.empty()) { time_events.pop(); } cond.notify_all(); lock.unlock(); worker.join(); } timer_id add(const timestamp &when, handler_t &&handler, const duration &period) { scoped_m lock(m); timer_id id = next_id(); Event e(id, when, period, std::move(handler)); if(events.size() <= id) { events.resize(id + 1); } events.insert(events.begin() + id, std::move(e)); time_events.push(Time_event{e.start, e.id}); cond.notify_all(); return e.id; } bool remove(timer_id id) { scoped_m lock(m); if(events.size() < id) { return false; } events[id].valid = false; return true; } } // end namespace CppTime <commit_msg>Do not use the value from the moved object for the timer_id.<commit_after>/** * The MIT License (MIT) * * Copyright (c) 2015 Michael Egli * * 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. * * \author Michael Egli * \copyright Michael Egli * \date 11-Jul-2015 * * \file cpptime.cpp * * See the description in the header file for for more information. * */ // Includes #include <thread> #include <mutex> #include <condition_variable> #include <algorithm> #include <stack> #include <set> #include <queue> #include <unordered_map> #include "cpptime.h" namespace { using scoped_m = std::unique_lock<std::mutex>; // Prototypes CppTime::timer_id next_id(); // Use to terminate the timer thread. bool done = false; // The index variable used to construct the timer_id. uint64_t cur_id = 0; // Locking & Co std::mutex m; std::condition_variable cond; std::thread worker; // The event structure that holds the information about a timer. struct Event { CppTime::timer_id id; CppTime::timestamp start; CppTime::duration period; CppTime::handler_t handler; bool valid; Event() : id(0), start(CppTime::duration::zero()), period(CppTime::duration::zero()), handler(nullptr), valid(false) { } template <typename Func> Event(CppTime::timer_id id, CppTime::timestamp start, CppTime::duration period, Func &&handler) : id(id), start(start), period(period), handler(std::forward<Func>(handler)), valid(true) { } Event(Event &&r) noexcept : id(r.id), start(r.start), period(r.period), handler(std::move(r.handler)), valid(r.valid) { } Event &operator=(Event &&ev) noexcept { if(this != &ev) { id = ev.id; start = ev.start; period = ev.period; handler = std::move(ev.handler); valid = ev.valid; } return *this; } Event(const Event &r) = delete; Event &operator=(const Event &r) = delete; }; // A time event structure that holds the next timeout and a reference to its // Event struct. struct Time_event { CppTime::timestamp next; CppTime::timer_id ref; }; inline bool operator<(const Time_event &l, const Time_event &r) { return l.next < r.next; } // The vector that holds all active events. std::vector<Event> events; // Sorted queue that has the next timeout at its top. std::priority_queue<Time_event> time_events; // A list of ids to be re-used. If possible, ids are used from this pool. std::stack<CppTime::timer_id> free_ids; // Returns the next free id. First, we check the free ids before creating a new // one. CppTime::timer_id next_id() { if(free_ids.empty()) { return cur_id++; } CppTime::timer_id id = free_ids.top(); free_ids.pop(); return id; } // The thread main entry points. This is an endless loop until the `done` flag // is set to false. // TODO cleanup code to make it more readable (less if-else blocks). void run() { scoped_m lock(m); while(!done) { if(time_events.empty()) { // Wait for work cond.wait(lock); } else { auto te = time_events.top(); if(CppTime::clock::now() >= te.next) { // Remove time event time_events.pop(); Event &ev = events[te.ref]; if(!ev.valid) { // Return the id if the event is no longer valid. free_ids.push(te.ref); } else { // Invoke the handler lock.unlock(); ev.handler(te.ref); lock.lock(); if(!ev.valid) { // The callback removed the event. free_ids.push(te.ref); } else { if(ev.period.count() > 0) { te.next += ev.period; time_events.push(te); } else { ev.valid = false; free_ids.push(te.ref); } } } } else { cond.wait_until(lock, te.next); } } } } } // end anonymous namespace namespace CppTime { void start(size_t expected) { scoped_m lock(m); done = false; if(expected > 0) { events.resize(expected); } worker = std::thread(&run); } void stop() { scoped_m lock(m); done = true; events.clear(); while(!time_events.empty()) { time_events.pop(); } cond.notify_all(); lock.unlock(); worker.join(); } timer_id add(const timestamp &when, handler_t &&handler, const duration &period) { scoped_m lock(m); timer_id id = next_id(); Event e(id, when, period, std::move(handler)); if(events.size() <= id) { events.resize(id + 1); } events.insert(events.begin() + id, std::move(e)); time_events.push(Time_event{e.start, id}); cond.notify_all(); return id; } bool remove(timer_id id) { scoped_m lock(m); if(events.size() < id) { return false; } events[id].valid = false; return true; } } // end namespace CppTime <|endoftext|>
<commit_before>#pragma once #include <cstddef> #include <iostream> #include <set> #include <string> #include <tuple> #include <utility> #include <vector> namespace Traits { /** * @brief P.F.M * * @see N3911 */ template<class...> using void_t = void; /** * @brief Strips constness and volatility from rvalues. */ template<typename Type> using unqualified_t = std::remove_cv_t<std::remove_reference_t<Type>>; /** * Base case for the testing of STD compatible container types. */ template< typename /*Type*/, typename = void > struct is_printable_as_container : std::false_type { }; /** * @brief Specialization to ensure that Standard Library compatible containers that have * `begin()`, `end()`, and `empty()` member functions, as well as the `value_type` and * `iterator` typedefs are treated as printable containers. */ template<typename Type> struct is_printable_as_container< Type, void_t< decltype(std::declval<Type&>().begin()), decltype(std::declval<Type&>().end()), decltype(std::declval<Type&>().empty()), typename Type::value_type, typename Type::iterator > > : public std::true_type { }; /** * @brief Specialization to treat std::pair<...> as a printable container type. */ template< typename FirstType, typename SecondType > struct is_printable_as_container<std::pair<FirstType, SecondType>> : public std::true_type { }; /** * @brief Specialization to treat arrays as printable container types. */ template< typename ArrayType, std::size_t ArraySize > struct is_printable_as_container<ArrayType[ArraySize]> : public std::true_type { }; /** * @brief Narrow character array specialization in order to ensure that we print character arrays * as string and not as delimiter containers. */ template<std::size_t ArraySize> struct is_printable_as_container<char[ArraySize]> : public std::false_type { }; /** * @brief Wide character array specialization in order to ensure that we print character arrays * as string and not as delimiter containers. */ template<std::size_t ArraySize> struct is_printable_as_container<wchar_t[ArraySize]> : public std::false_type { }; /** * @brief String specialization in order to ensure that we treat strings as nothing more than strings. */ template< typename CharacterType, typename TraitsType, typename AllocatorType > struct is_printable_as_container< std::basic_string< CharacterType, TraitsType, AllocatorType > > : public std::false_type { }; /** * @brief Helper variable template. */ template<typename Type> constexpr bool is_printable_as_container_v = is_printable_as_container<Type>::value; } namespace Printer { /** * Convenience struct to neatly wrap up all the additional characters we'll need in order to * print out the containers. */ template<typename DelimiterType> struct delimiter_values { using type = DelimiterType; const type* prefix; const type* delimiter; const type* postfix; }; /** * */ template< typename /*ContainerType*/, typename DelimiterType > struct delimiters { using type = delimiter_values<DelimiterType>; static const type values; }; /** * Default narrow delimiters for any container type that isn't specialized. */ template<typename ContainerType> struct delimiters<ContainerType, char> { using type = delimiter_values<char>; static constexpr type values = { "[", ", ", "]" }; }; /** * Default wide delimiters for any container type that isn't specialized. */ template<typename ContainerType> struct delimiters<ContainerType, wchar_t> { using type = delimiter_values<wchar_t>; static constexpr type values = { L"[", L", ", L"]" }; }; /** * Narrow character specialization for std::set<...>. */ template< typename Type, typename ComparatorType, typename AllocatorType > struct delimiters<std::set<Type, ComparatorType, AllocatorType>, char> { static constexpr delimiter_values<char> values = { "{", ", ", "}" }; }; /** * Wide character specialization for std::set<...>. */ template< typename Type, typename ComparatorType, typename AllocatorType > struct delimiters<std::set<Type, ComparatorType, AllocatorType>, wchar_t> { static constexpr delimiter_values<wchar_t> values = { L"{", L", ", L"}" }; }; /** * Narrow character specialization for std::pair<...>. */ template< typename FirstType, typename SecondType > struct delimiters<std::pair<FirstType, SecondType>, char> { static constexpr delimiter_values<char> values = { "(", ", ", ")" }; }; /** * Wide character specialization for std::pair<...>. */ template< typename FirstType, typename SecondType > struct delimiters<std::pair<FirstType, SecondType>, wchar_t> { static constexpr delimiter_values<wchar_t> values = { L"(", L", ", L")" }; }; /** * Narrow character specialization for std::tuple<...>. */ template<typename... Types> struct delimiters<std::tuple<Types...>, char> { static constexpr delimiter_values<char> values = { "<", ", ", ">" }; }; /** * Wide character specialization for std::tuple<...>. */ template<typename... Types> struct delimiters<std::tuple<Types...>, wchar_t> { static constexpr delimiter_values<wchar_t> values = { L"<", L", ", L">" }; }; ///** //* @brief Base specialization for std::tuple<...>. //*/ //template< // typename ContainerType, // typename TupleType, // typename CharacterType, // typename TraitsType //> //void PrintingHelper( // std::basic_ostream<CharacterType, TraitsType>& stream, // const std::tuple<TupleType>& container) //{ // stream << std::get<0>(container); //} ///** //* @brief Recursive specialization for std::tuple<...>. //*/ //template< // typename FirstTupleType, // typename... RemainingTupleTypes, // typename CharacterType, // typename TraitsType //> //void PrintingHelper( // std::basic_ostream<CharacterType, TraitsType>& stream, // const std::tuple<FirstTupleType, RemainingTupleTypes...>& container) //{ // static constexpr auto delimiters = // Printer::delimiters<std::tuple<...>, CharacterType>::values; // stream << std::get<0>(container) << delimiters.delimiter; // PrintingHelper(stream, container); //} /** * see http://stackoverflow.com/questions/6245735/pretty-print-stdtuple/6245777 */ template< typename CharacterType, typename TraitsType, typename Tuple, std::size_t... IndexSequence > void print_tuple_impl( std::basic_ostream<CharacterType, TraitsType>& stream, const Tuple& tuple, std::index_sequence<IndexSequence...>) { static constexpr auto delimiters = Printer::delimiters<std::tuple<...>, CharacterType>::values; using swallow = int[]; // guarantees left to right order (void) swallow { 0, (void (stream << (IndexSequence == 0 ? "" : delimiters.delimiter) << std::get<IndexSequence>(tuple)), 0)... }; } /** * @brief Printing specialization suitable for most container types. */ template< typename ContainerType, typename CharacterType, typename TraitsType > void PrintingHelper( std::basic_ostream<CharacterType, TraitsType>& stream, const ContainerType& container) { static constexpr auto delimiters = Printer::delimiters<ContainerType, CharacterType>::values; if (container.empty()) { return; } auto begin = std::begin(container); stream << delimiters.prefix << *begin; std::advance(begin, 1); std::for_each(begin, std::end(container), [&stream] (const auto& value) { stream << delimiters.delimiter << value; }); stream << delimiters.postfix; } /** * @brief Printing specialization for std::pair<...>. */ template< typename FirstType, typename SecondType, typename CharacterType, typename TraitsType > void PrintingHelper( std::basic_ostream<CharacterType, TraitsType>& stream, const std::pair<FirstType, SecondType>& container) { static constexpr auto delimiters = Printer::delimiters< Traits::unqualified_t<decltype(container)>, CharacterType >::values; stream << delimiters.prefix << container.first << delimiters.delimiter << container.second << delimiters.postfix; } /** * @brief Main class that will print out the container with the help of various templated * helper functions. */ template< typename ContainerType, typename CharacterType, typename TraitsType > class ContainerPrinter { public: ContainerPrinter(const ContainerType& container) : m_container{ container } { } inline void PrintTo(std::basic_ostream<CharacterType, TraitsType>& stream) const { PrintingHelper(stream, m_container); } private: const ContainerType& m_container; }; } /** * @brief Overload of the stream output operator for compatible containers. */ template< typename ContainerType, typename CharacterType, typename TraitsType, typename = std::enable_if_t<Traits::is_printable_as_container_v<ContainerType>> > auto& operator<<( std::basic_ostream<CharacterType, TraitsType>& stream, const ContainerType& container) { Printer::ContainerPrinter<ContainerType, CharacterType, TraitsType>(container).PrintTo(stream); return stream; } <commit_msg>Got std::tuple<...> Printing Working<commit_after>#pragma once #include <cstddef> #include <iostream> #include <set> #include <string> #include <tuple> #include <utility> #include <vector> namespace Traits { /** * @brief P.F.M * * @see N3911 */ template<class...> using void_t = void; /** * @brief Strips constness and volatility from rvalues. */ template<typename Type> using unqualified_t = std::remove_cv_t<std::remove_reference_t<Type>>; /** * Base case for the testing of STD compatible container types. */ template< typename /*Type*/, typename = void > struct is_printable_as_container : std::false_type { }; /** * @brief Specialization to ensure that Standard Library compatible containers that have * `begin()`, `end()`, and `empty()` member functions, as well as the `value_type` and * `iterator` typedefs are treated as printable containers. */ template<typename Type> struct is_printable_as_container< Type, void_t< decltype(std::declval<Type&>().begin()), decltype(std::declval<Type&>().end()), decltype(std::declval<Type&>().empty()), typename Type::value_type, typename Type::iterator > > : public std::true_type { }; /** * @brief Specialization to treat std::pair<...> as a printable container type. */ template< typename FirstType, typename SecondType > struct is_printable_as_container<std::pair<FirstType, SecondType>> : public std::true_type { }; /** * @brief Specialization to treat std::tuple<...> as a printable container type. */ template<typename... DataTypes> struct is_printable_as_container<std::tuple<DataTypes...>> : public std::true_type { }; /** * @brief Specialization to treat arrays as printable container types. */ template< typename ArrayType, std::size_t ArraySize > struct is_printable_as_container<ArrayType[ArraySize]> : public std::true_type { }; /** * @brief Narrow character array specialization in order to ensure that we print character arrays * as string and not as delimiter containers. */ template<std::size_t ArraySize> struct is_printable_as_container<char[ArraySize]> : public std::false_type { }; /** * @brief Wide character array specialization in order to ensure that we print character arrays * as string and not as delimiter containers. */ template<std::size_t ArraySize> struct is_printable_as_container<wchar_t[ArraySize]> : public std::false_type { }; /** * @brief String specialization in order to ensure that we treat strings as nothing more than strings. */ template< typename CharacterType, typename TraitsType, typename AllocatorType > struct is_printable_as_container< std::basic_string< CharacterType, TraitsType, AllocatorType > > : public std::false_type { }; /** * @brief Helper variable template. */ template<typename Type> constexpr bool is_printable_as_container_v = is_printable_as_container<Type>::value; } namespace Printer { /** * Convenience struct to neatly wrap up all the additional characters we'll need in order to * print out the containers. */ template<typename DelimiterType> struct delimiter_values { using type = DelimiterType; const type* prefix; const type* delimiter; const type* postfix; }; /** * */ template< typename /*ContainerType*/, typename DelimiterType > struct delimiters { using type = delimiter_values<DelimiterType>; static const type values; }; /** * Default narrow delimiters for any container type that isn't specialized. */ template<typename ContainerType> struct delimiters<ContainerType, char> { using type = delimiter_values<char>; static constexpr type values = { "[", ", ", "]" }; }; /** * Default wide delimiters for any container type that isn't specialized. */ template<typename ContainerType> struct delimiters<ContainerType, wchar_t> { using type = delimiter_values<wchar_t>; static constexpr type values = { L"[", L", ", L"]" }; }; /** * Narrow character specialization for std::set<...>. */ template< typename Type, typename ComparatorType, typename AllocatorType > struct delimiters<std::set<Type, ComparatorType, AllocatorType>, char> { static constexpr delimiter_values<char> values = { "{", ", ", "}" }; }; /** * Wide character specialization for std::set<...>. */ template< typename Type, typename ComparatorType, typename AllocatorType > struct delimiters<std::set<Type, ComparatorType, AllocatorType>, wchar_t> { static constexpr delimiter_values<wchar_t> values = { L"{", L", ", L"}" }; }; /** * Narrow character specialization for std::pair<...>. */ template< typename FirstType, typename SecondType > struct delimiters<std::pair<FirstType, SecondType>, char> { static constexpr delimiter_values<char> values = { "(", ", ", ")" }; }; /** * Wide character specialization for std::pair<...>. */ template< typename FirstType, typename SecondType > struct delimiters<std::pair<FirstType, SecondType>, wchar_t> { static constexpr delimiter_values<wchar_t> values = { L"(", L", ", L")" }; }; /** * Narrow character specialization for std::tuple<...>. */ template<typename... Types> struct delimiters<std::tuple<Types...>, char> { static constexpr delimiter_values<char> values = { "<", ", ", ">" }; }; /** * Wide character specialization for std::tuple<...>. */ template<typename... Types> struct delimiters<std::tuple<Types...>, wchar_t> { static constexpr delimiter_values<wchar_t> values = { L"<", L", ", L">" }; }; /** * @brief Helper template to unpack and print tuple arguments. */ template< typename TupleType, std::size_t N, typename... Args > struct TuplePrinter { template< typename CharacterType, typename TraitsType, typename DelimiterValues > static void Print( std::basic_ostream<CharacterType, TraitsType>& stream, const TupleType& container, const DelimiterValues& delimiters) { TuplePrinter<TupleType, N - 1>::Print(stream, container, delimiters); stream << delimiters.delimiter << std::get<N - 1>(container); } }; /** * @brief Helper template to unpack and print tuple arguments. */ template<typename TupleType> struct TuplePrinter<TupleType, 1> { template< typename CharacterType, typename TraitsType, typename DelimiterValues > static void Print( std::basic_ostream<CharacterType, TraitsType>& stream, const TupleType& tuple, const DelimiterValues& delimiters) { stream << std::get<0>(tuple); } }; /** * @brief Recursive specialization for std::tuple<...>. * * @see http://en.cppreference.com/w/cpp/utility/tuple/tuple_cat */ template< typename CharacterType, typename TraitsType, typename... Args > void PrintingHelper( std::basic_ostream<CharacterType, TraitsType>& stream, const std::tuple<Args...>& container) { static constexpr auto delimiters = Printer::delimiters<Traits::unqualified_t<decltype(container)>, CharacterType>::values; stream << delimiters.prefix; TuplePrinter<decltype(container), sizeof...(Args)>::Print(stream, container, delimiters); stream << delimiters.postfix; } /** * @brief Printing specialization suitable for most container types. */ template< typename ContainerType, typename CharacterType, typename TraitsType > void PrintingHelper( std::basic_ostream<CharacterType, TraitsType>& stream, const ContainerType& container) { static constexpr auto delimiters = Printer::delimiters<ContainerType, CharacterType>::values; if (container.empty()) { return; } auto begin = std::begin(container); stream << delimiters.prefix << *begin; std::advance(begin, 1); std::for_each(begin, std::end(container), [&stream] (const auto& value) { stream << delimiters.delimiter << value; }); stream << delimiters.postfix; } /** * @brief Printing specialization for std::pair<...>. */ template< typename FirstType, typename SecondType, typename CharacterType, typename TraitsType > void PrintingHelper( std::basic_ostream<CharacterType, TraitsType>& stream, const std::pair<FirstType, SecondType>& container) { static constexpr auto delimiters = Printer::delimiters< Traits::unqualified_t<decltype(container)>, CharacterType >::values; stream << delimiters.prefix << container.first << delimiters.delimiter << container.second << delimiters.postfix; } /** * @brief Main class that will print out the container with the help of various templated * helper functions. */ template< typename ContainerType, typename CharacterType, typename TraitsType > class ContainerPrinter { public: ContainerPrinter(const ContainerType& container) : m_container{ container } { } inline void PrintTo(std::basic_ostream<CharacterType, TraitsType>& stream) const { PrintingHelper(stream, m_container); } private: const ContainerType& m_container; }; } /** * @brief Overload of the stream output operator for compatible containers. */ template< typename ContainerType, typename CharacterType, typename TraitsType, typename = std::enable_if_t<Traits::is_printable_as_container_v<ContainerType>> > auto& operator<<( std::basic_ostream<CharacterType, TraitsType>& stream, const ContainerType& container) { Printer::ContainerPrinter<ContainerType, CharacterType, TraitsType>(container).PrintTo(stream); return stream; } <|endoftext|>
<commit_before> #include <gloperate/painter/CameraCollisionCapability.h> #include <limits> #include <glm/gtc/matrix_transform.hpp> #include <glbinding/gl/enum.h> #include <glbinding/gl/functions.h> #include <glbinding/gl/bitfield.h> #include <glbinding/gl/types.h> #include <globjects/Framebuffer.h> using namespace gl; namespace gloperate { CameraCollisionCapability::CameraCollisionCapability() : m_fbo(nullptr) , m_size(1024) , m_samplingSize(1) { } CameraCollisionCapability::~CameraCollisionCapability() { } void CameraCollisionCapability::setCollisionFBO(globjects::ref_ptr<globjects::Framebuffer> collisionFBO, size_t texSize) { m_fbo = collisionFBO; m_size = texSize; } void CameraCollisionCapability::setSamplingSize(size_t samplingSize) { m_samplingSize = samplingSize; } float CameraCollisionCapability::getDistance(const glm::vec3 &dir) const { if(!m_fbo) { return std::numeric_limits<float>::max(); } float xAbs = std::abs(dir.x); float yAbs = std::abs(dir.y); float zAbs = std::abs(dir.z); float main, u, v; GLenum face; if(xAbs == 0 && yAbs == 0 && zAbs == 0) { return std::numeric_limits<float>::max(); } //Find the correct axis to sample if(xAbs > yAbs && xAbs > zAbs) { face = GL_COLOR_ATTACHMENT0; main = dir.x; u = -dir.z; v = -dir.y; } else if(yAbs > zAbs) { face = GL_COLOR_ATTACHMENT2; main = dir.y; u = dir.x; v = dir.z; } else { face = GL_COLOR_ATTACHMENT4; main = dir.z; u = -dir.x; v = -dir.y; } //Find the correct orientation on this axis face = face + static_cast<int>(std::signbit(main)); //Sample the coordinates glm::vec2 uv{u/std::abs(main), v/std::abs(main)}; glm::ivec2 i_uv = uv * static_cast<float>(m_size/2)+static_cast<float>(m_size/2); std::vector<glm::vec3> buf(m_samplingSize*m_samplingSize); m_fbo->bind(); std::array<GLint,4> sampleRange{i_uv.x,i_uv.y,m_samplingSize,m_samplingSize}; m_fbo->readPixels(face, sampleRange,GL_RGB,GL_FLOAT,buf.data()); m_fbo->unbind(); return buf[0].x; } } // namespace gloperate <commit_msg>Final fix for collision sampling<commit_after> #include <gloperate/painter/CameraCollisionCapability.h> #include <limits> #include <glm/gtc/matrix_transform.hpp> #include <glbinding/gl/enum.h> #include <glbinding/gl/functions.h> #include <glbinding/gl/bitfield.h> #include <glbinding/gl/types.h> #include <globjects/Framebuffer.h> using namespace gl; namespace gloperate { CameraCollisionCapability::CameraCollisionCapability() : m_fbo(nullptr) , m_size(1024) , m_samplingSize(1) { } CameraCollisionCapability::~CameraCollisionCapability() { } void CameraCollisionCapability::setCollisionFBO(globjects::ref_ptr<globjects::Framebuffer> collisionFBO, size_t texSize) { m_fbo = collisionFBO; m_size = texSize; } void CameraCollisionCapability::setSamplingSize(size_t samplingSize) { m_samplingSize = samplingSize; } float CameraCollisionCapability::getDistance(const glm::vec3 &dir) const { if(!m_fbo) { return std::numeric_limits<float>::max(); } float xAbs = std::abs(dir.x); float yAbs = std::abs(dir.y); float zAbs = std::abs(dir.z); float main, u, v; GLenum face; if(xAbs == 0 && yAbs == 0 && zAbs == 0) { return std::numeric_limits<float>::max(); } // Find the correct axis to sample if(xAbs > yAbs && xAbs > zAbs) { face = GL_COLOR_ATTACHMENT0; main = dir.x; u = -dir.z; v = -dir.y; } else if(yAbs > zAbs) { auto sign = std::signbit(dir.y) ? -1 : 1; face = GL_COLOR_ATTACHMENT2; main = dir.y; u = dir.x; v = sign *dir.z; } else { face = GL_COLOR_ATTACHMENT4; main = dir.z; u = -dir.x; v = -dir.y; } // Find the correct orientation on this axis face = face + static_cast<int>(std::signbit(main)); // Sample the coordinates glm::vec2 uv{u/std::abs(main), v/std::abs(main)}; glm::ivec2 i_uv = uv * static_cast<float>(m_size/2)+static_cast<float>(m_size/2); std::vector<glm::vec3> buf(m_samplingSize*m_samplingSize); m_fbo->bind(); std::array<GLint,4> sampleRange{i_uv.x,i_uv.y,m_samplingSize,m_samplingSize}; m_fbo->readPixels(face, sampleRange,GL_RGB,GL_FLOAT,buf.data()); m_fbo->unbind(); return buf[0].x; } } // namespace gloperate <|endoftext|>
<commit_before>// [WriteFile Name=LoadWfsXmlQuery, Category=Layers] // [Legal] // Copyright 2019 Esri. // 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. // [Legal] #include "LoadWfsXmlQuery.h" #include "Map.h" #include "MapQuickView.h" #include "FeatureLayer.h" #include "WfsFeatureTable.h" using namespace Esri::ArcGISRuntime; namespace { static const QString xmlQueryString = R"( <wfs:GetFeature service="WFS" version="2.0.0" xmlns:Seattle_Downtown_Features="https://dservices2.arcgis.com/ZQgQTuoyBrtmoGdP/arcgis/services/Seattle_Downtown_Features/WFSServer" xmlns:wfs="http://www.opengis.net/wfs/2.0" xmlns:fes="http://www.opengis.net/fes/2.0" xmlns:gml="http://www.opengis.net/gml/3.2"> <wfs:Query typeNames="Seattle_Downtown_Features:Trees"> <fes:Filter> <fes:PropertyIsLike wildCard="*" escapeChar="\"> <fes:ValueReference>Trees:SCIENTIFIC</fes:ValueReference> <fes:Literal>Tilia *</fes:Literal> </fes:PropertyIsLike> </fes:Filter> </wfs:Query> </wfs:GetFeature> )"; } LoadWfsXmlQuery::LoadWfsXmlQuery(QObject* parent /* = nullptr */): QObject(parent), m_map(new Map(Basemap::navigationVector(this), this)) { // create WFS Feature Table const QUrl featureTableUrl("https://dservices2.arcgis.com/ZQgQTuoyBrtmoGdP/arcgis/services/Seattle_Downtown_Features/WFSServer?service=wfs&request=getcapabilities"); WfsFeatureTable* wfsFeatureTable = new WfsFeatureTable(featureTableUrl, "Seattle_Downtown_Features:Trees", this); wfsFeatureTable->setFeatureRequestMode(FeatureRequestMode::ManualCache); // connect to feature table doneLoading signal connect(wfsFeatureTable, &WfsFeatureTable::doneLoading, this, [wfsFeatureTable, this](Error e) { if (!e.isEmpty()) return; // populate the table with XML Query wfsFeatureTable->populateFromService(xmlQueryString, true); // set the viewpoint to the center of the extent m_mapView->setViewpointGeometry(wfsFeatureTable->extent(), 50); }); // create Feature Layer FeatureLayer* featureLayer = new FeatureLayer(wfsFeatureTable, this); // add layer to the map m_map->operationalLayers()->append(featureLayer); } LoadWfsXmlQuery::~LoadWfsXmlQuery() = default; void LoadWfsXmlQuery::init() { // Register the map view for QML qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView"); qmlRegisterType<LoadWfsXmlQuery>("Esri.Samples", 1, 0, "LoadWfsXmlQuerySample"); } MapQuickView* LoadWfsXmlQuery::mapView() const { return m_mapView; } // Set the view (created in QML) void LoadWfsXmlQuery::setMapView(MapQuickView* mapView) { if (!mapView || mapView == m_mapView) return; m_mapView = mapView; m_mapView->setMap(m_map); emit mapViewChanged(); } <commit_msg>reformatting query<commit_after>// [WriteFile Name=LoadWfsXmlQuery, Category=Layers] // [Legal] // Copyright 2019 Esri. // 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. // [Legal] #include "LoadWfsXmlQuery.h" #include "Map.h" #include "MapQuickView.h" #include "FeatureLayer.h" #include "WfsFeatureTable.h" using namespace Esri::ArcGISRuntime; namespace { const QString xmlQueryString = R"( <wfs:GetFeature service="WFS" version="2.0.0" xmlns:Seattle_Downtown_Features="https://dservices2.arcgis.com/ZQgQTuoyBrtmoGdP/arcgis/services/Seattle_Downtown_Features/WFSServer" xmlns:wfs="http://www.opengis.net/wfs/2.0" xmlns:fes="http://www.opengis.net/fes/2.0" xmlns:gml="http://www.opengis.net/gml/3.2"> <wfs:Query typeNames="Seattle_Downtown_Features:Trees"> <fes:Filter> <fes:PropertyIsLike wildCard="*" escapeChar="\"> <fes:ValueReference>Trees:SCIENTIFIC</fes:ValueReference> <fes:Literal>Tilia *</fes:Literal> </fes:PropertyIsLike> </fes:Filter> </wfs:Query> </wfs:GetFeature>)"; } LoadWfsXmlQuery::LoadWfsXmlQuery(QObject* parent /* = nullptr */): QObject(parent), m_map(new Map(Basemap::navigationVector(this), this)) { // create WFS Feature Table const QUrl featureTableUrl("https://dservices2.arcgis.com/ZQgQTuoyBrtmoGdP/arcgis/services/Seattle_Downtown_Features/WFSServer?service=wfs&request=getcapabilities"); WfsFeatureTable* wfsFeatureTable = new WfsFeatureTable(featureTableUrl, "Seattle_Downtown_Features:Trees", this); wfsFeatureTable->setFeatureRequestMode(FeatureRequestMode::ManualCache); // connect to feature table doneLoading signal connect(wfsFeatureTable, &WfsFeatureTable::doneLoading, this, [wfsFeatureTable, this](Error e) { if (!e.isEmpty()) return; // populate the table with XML Query wfsFeatureTable->populateFromService(xmlQueryString, true); // set the viewpoint to the center of the extent m_mapView->setViewpointGeometry(wfsFeatureTable->extent(), 50); }); // create Feature Layer FeatureLayer* featureLayer = new FeatureLayer(wfsFeatureTable, this); // add layer to the map m_map->operationalLayers()->append(featureLayer); } LoadWfsXmlQuery::~LoadWfsXmlQuery() = default; void LoadWfsXmlQuery::init() { // Register the map view for QML qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView"); qmlRegisterType<LoadWfsXmlQuery>("Esri.Samples", 1, 0, "LoadWfsXmlQuerySample"); } MapQuickView* LoadWfsXmlQuery::mapView() const { return m_mapView; } // Set the view (created in QML) void LoadWfsXmlQuery::setMapView(MapQuickView* mapView) { if (!mapView || mapView == m_mapView) return; m_mapView = mapView; m_mapView->setMap(m_map); emit mapViewChanged(); } <|endoftext|>
<commit_before>/******************************************************************************\ * ___ __ * * /\_ \ __/\ \ * * \//\ \ /\_\ \ \____ ___ _____ _____ __ * * \ \ \ \/\ \ \ '__`\ /'___\/\ '__`\/\ '__`\ /'__`\ * * \_\ \_\ \ \ \ \L\ \/\ \__/\ \ \L\ \ \ \L\ \/\ \L\.\_ * * /\____\\ \_\ \_,__/\ \____\\ \ ,__/\ \ ,__/\ \__/.\_\ * * \/____/ \/_/\/___/ \/____/ \ \ \/ \ \ \/ \/__/\/_/ * * \ \_\ \ \_\ * * \/_/ \/_/ * * * * Copyright (C) 2011, 2012 * * Dominik Charousset <dominik.charousset@haw-hamburg.de> * * * * This file is part of libcppa. * * libcppa is free software: you can redistribute it and/or modify it under * * the terms of the GNU Lesser General Public License as published by the * * Free Software Foundation, either version 3 of the License * * or (at your option) any later version. * * * * libcppa 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 libcppa. If not, see <http://www.gnu.org/licenses/>. * \******************************************************************************/ #include <iostream> #include "cppa/to_string.hpp" #include "cppa/self.hpp" #include "cppa/detail/invokable.hpp" #include "cppa/abstract_event_based_actor.hpp" namespace cppa { abstract_event_based_actor::abstract_event_based_actor() : super(super::blocked) { //m_mailbox_pos = m_mailbox.cache().end(); } void abstract_event_based_actor::dequeue(behavior&) { quit(exit_reason::unallowed_function_call); } void abstract_event_based_actor::dequeue(partial_function&) { quit(exit_reason::unallowed_function_call); } auto abstract_event_based_actor::handle_message(mailbox_element& node) -> handle_message_result { CPPA_REQUIRE(m_loop_stack.empty() == false); auto& bhvr = *(m_loop_stack.back()); switch (filter_msg(node.msg)) { case normal_exit_signal: case expired_timeout_message: return drop_msg; case timeout_message: m_has_pending_timeout_request = false; CPPA_REQUIRE(bhvr.timeout().valid()); bhvr.handle_timeout(); if (!m_loop_stack.empty()) { auto& next_bhvr = *(m_loop_stack.back()); request_timeout(next_bhvr.timeout()); } return msg_handled; default: break; } std::swap(m_last_dequeued, node.msg); std::swap(m_last_sender, node.sender); //m_last_dequeued = node.msg; //m_last_sender = node.sender; // make sure no timeout is handled incorrectly in a nested receive ++m_active_timeout_id; if ((bhvr.get_partial_function())(m_last_dequeued)) { m_last_dequeued.reset(); m_last_sender.reset(); // we definitely don't have a pending timeout now m_has_pending_timeout_request = false; return msg_handled; } // no match, restore members --m_active_timeout_id; std::swap(m_last_dequeued, node.msg); std::swap(m_last_sender, node.sender); return cache_msg; } void abstract_event_based_actor::resume(util::fiber*, scheduler::callback* cb) { auto done_cb = [&]() { m_state.store(abstract_scheduled_actor::done); m_loop_stack.clear(); on_exit(); cb->exec_done(); }; self.set(this); try { std::unique_ptr<detail::recursive_queue_node> e; for (;;) { e.reset(m_mailbox.try_pop()); if (!e) { m_state.store(abstract_scheduled_actor::about_to_block); CPPA_MEMORY_BARRIER(); if (m_mailbox.can_fetch_more() == false) { switch (compare_exchange_state(abstract_scheduled_actor::about_to_block, abstract_scheduled_actor::blocked)) { case abstract_scheduled_actor::ready: { break; } case abstract_scheduled_actor::blocked: { return; } default: exit(7); // illegal state }; } } else { switch (handle_message(*e)) { case drop_msg: { break; // nop } case msg_handled: { if (m_loop_stack.empty()) { done_cb(); return; } // try to match cached messages before receiving new ones auto i = m_cache.begin(); while (i != m_cache.end()) { switch (handle_message(*(*i))) { case drop_msg: { i = m_cache.erase(i); break; } case msg_handled: { m_cache.erase(i); if (m_loop_stack.empty()) { done_cb(); return; } i = m_cache.begin(); break; } case cache_msg: { ++i; break; } default: exit(7); // illegal state } } break; } case cache_msg: { m_cache.push_back(std::move(e)); break; } default: exit(7); // illegal state } } } } catch (actor_exited& what) { cleanup(what.reason()); } catch (...) { cleanup(exit_reason::unhandled_exception); } done_cb(); } void abstract_event_based_actor::on_exit() { } } // namespace cppa <commit_msg>removed obsolete code<commit_after>/******************************************************************************\ * ___ __ * * /\_ \ __/\ \ * * \//\ \ /\_\ \ \____ ___ _____ _____ __ * * \ \ \ \/\ \ \ '__`\ /'___\/\ '__`\/\ '__`\ /'__`\ * * \_\ \_\ \ \ \ \L\ \/\ \__/\ \ \L\ \ \ \L\ \/\ \L\.\_ * * /\____\\ \_\ \_,__/\ \____\\ \ ,__/\ \ ,__/\ \__/.\_\ * * \/____/ \/_/\/___/ \/____/ \ \ \/ \ \ \/ \/__/\/_/ * * \ \_\ \ \_\ * * \/_/ \/_/ * * * * Copyright (C) 2011, 2012 * * Dominik Charousset <dominik.charousset@haw-hamburg.de> * * * * This file is part of libcppa. * * libcppa is free software: you can redistribute it and/or modify it under * * the terms of the GNU Lesser General Public License as published by the * * Free Software Foundation, either version 3 of the License * * or (at your option) any later version. * * * * libcppa 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 libcppa. If not, see <http://www.gnu.org/licenses/>. * \******************************************************************************/ #include <iostream> #include "cppa/to_string.hpp" #include "cppa/self.hpp" #include "cppa/detail/invokable.hpp" #include "cppa/abstract_event_based_actor.hpp" namespace cppa { abstract_event_based_actor::abstract_event_based_actor() : super(super::blocked) { //m_mailbox_pos = m_mailbox.cache().end(); } void abstract_event_based_actor::dequeue(behavior&) { quit(exit_reason::unallowed_function_call); } void abstract_event_based_actor::dequeue(partial_function&) { quit(exit_reason::unallowed_function_call); } auto abstract_event_based_actor::handle_message(mailbox_element& node) -> handle_message_result { CPPA_REQUIRE(m_loop_stack.empty() == false); auto& bhvr = *(m_loop_stack.back()); switch (filter_msg(node.msg)) { case normal_exit_signal: case expired_timeout_message: return drop_msg; case timeout_message: m_has_pending_timeout_request = false; CPPA_REQUIRE(bhvr.timeout().valid()); bhvr.handle_timeout(); if (!m_loop_stack.empty()) { auto& next_bhvr = *(m_loop_stack.back()); request_timeout(next_bhvr.timeout()); } return msg_handled; default: break; } std::swap(m_last_dequeued, node.msg); std::swap(m_last_sender, node.sender); //m_last_dequeued = node.msg; //m_last_sender = node.sender; if ((bhvr.get_partial_function())(m_last_dequeued)) { m_last_dequeued.reset(); m_last_sender.reset(); // we definitely don't have a pending timeout now m_has_pending_timeout_request = false; return msg_handled; } // no match, restore members std::swap(m_last_dequeued, node.msg); std::swap(m_last_sender, node.sender); return cache_msg; } void abstract_event_based_actor::resume(util::fiber*, scheduler::callback* cb) { auto done_cb = [&]() { m_state.store(abstract_scheduled_actor::done); m_loop_stack.clear(); on_exit(); cb->exec_done(); }; self.set(this); try { std::unique_ptr<detail::recursive_queue_node> e; for (;;) { e.reset(m_mailbox.try_pop()); if (!e) { m_state.store(abstract_scheduled_actor::about_to_block); CPPA_MEMORY_BARRIER(); if (m_mailbox.can_fetch_more() == false) { switch (compare_exchange_state(abstract_scheduled_actor::about_to_block, abstract_scheduled_actor::blocked)) { case abstract_scheduled_actor::ready: { break; } case abstract_scheduled_actor::blocked: { return; } default: exit(7); // illegal state }; } } else { switch (handle_message(*e)) { case drop_msg: { break; // nop } case msg_handled: { if (m_loop_stack.empty()) { done_cb(); return; } // try to match cached messages before receiving new ones auto i = m_cache.begin(); while (i != m_cache.end()) { switch (handle_message(*(*i))) { case drop_msg: { i = m_cache.erase(i); break; } case msg_handled: { m_cache.erase(i); if (m_loop_stack.empty()) { done_cb(); return; } i = m_cache.begin(); break; } case cache_msg: { ++i; break; } default: exit(7); // illegal state } } break; } case cache_msg: { m_cache.push_back(std::move(e)); break; } default: exit(7); // illegal state } } } } catch (actor_exited& what) { cleanup(what.reason()); } catch (...) { cleanup(exit_reason::unhandled_exception); } done_cb(); } void abstract_event_based_actor::on_exit() { } } // namespace cppa <|endoftext|>
<commit_before>#include "OI.h" #include "Commands/ControlIntakeWheels.h" #include "Subsystems/IntakeWheel.h" #include "Misc/ToggleClass.h" /// Default constructor of the class. ControlIntakeWheels::ControlIntakeWheels() { IntakeArmPosition = new Toggle<bool>(false,true); Requires(IntakeWheel::GetInstance()); } /// Called just before this Command runs the first time. void ControlIntakeWheels::Initialize() { IntakeWheel::GetInstance()->SpinIntake(0); } void ControlIntakeWheels::Execute() { OI* oi = OI::GetInstance(); //In and out control for the intake bar if(oi->gamepad->GetRawButton(BTN_INTAKE)) { IntakeWheel::GetInstance()->SpinIntake(Preferences::GetInstance()->GetDouble("Intake Speed",1)); }else if(oi->gamepad->GetRawButton(BTN_OUTAKE)){ IntakeWheel::GetInstance()->SpinIntake(-Preferences::GetInstance()->GetDouble("Intake Speed",1)); }else{ IntakeWheel::GetInstance()->SpinIntake(0); } } /// Make this return true when this Command no longer needs to run execute(). /// \return always false since this is the default command and should never finish. bool ControlIntakeWheels::IsFinished() { return false; } /// Called once after isFinished returns true void ControlIntakeWheels::End() { IntakeWheel::GetInstance()->SpinIntake(0); } /// Called when another command which requires one or more of the same /// subsystems is scheduled to run void ControlIntakeWheels::Interrupted() { End(); } <commit_msg>Added a second throttle specifically for intake wheels out.<commit_after>#include "OI.h" #include "Commands/ControlIntakeWheels.h" #include "Subsystems/IntakeWheel.h" #include "Misc/ToggleClass.h" /// Default constructor of the class. ControlIntakeWheels::ControlIntakeWheels() { IntakeArmPosition = new Toggle<bool>(false,true); Requires(IntakeWheel::GetInstance()); } /// Called just before this Command runs the first time. void ControlIntakeWheels::Initialize() { IntakeWheel::GetInstance()->SpinIntake(0); } void ControlIntakeWheels::Execute() { OI* oi = OI::GetInstance(); //In and out control for the intake bar if(oi->gamepad->GetRawButton(BTN_INTAKE)) { IntakeWheel::GetInstance()->SpinIntake(Preferences::GetInstance()->GetDouble("Intake Speed",1)); }else if(oi->gamepad->GetRawButton(BTN_OUTAKE)){ IntakeWheel::GetInstance()->SpinIntake(Preferences::GetInstance()->GetDouble("Intake Speed Out",-1)); }else{ IntakeWheel::GetInstance()->SpinIntake(0); } } /// Make this return true when this Command no longer needs to run execute(). /// \return always false since this is the default command and should never finish. bool ControlIntakeWheels::IsFinished() { return false; } /// Called once after isFinished returns true void ControlIntakeWheels::End() { IntakeWheel::GetInstance()->SpinIntake(0); } /// Called when another command which requires one or more of the same /// subsystems is scheduled to run void ControlIntakeWheels::Interrupted() { End(); } <|endoftext|>
<commit_before> #ifndef ONI_VICON_RECORDER_ONI_RECORDER_HPP #define ONI_VICON_RECORDER_ONI_RECORDER_HPP #include <string> #include <map> #include <boost/thread/mutex.hpp> #include <ros/ros.h> #include <actionlib/server/simple_action_server.h> #include <oni_vicon_recorder/RunDepthSensorAction.h> #include <oni_vicon_recorder/ChangeDepthSensorModeAction.h> #include "kinect.h" #define KINECT_IMAGE_COLS 640 #define KINECT_IMAGE_ROWS 480 #define KINECT_RGB_FOCAL_LENGTH_DEFAULT 525 #define KINECT_RGB_CENTER_COL_DEFAULT 320 #define KINECT_RGB_CENTER_ROW_DEFAULT 240 #define KINECT_IR_FOCAL_LENGTH_DEFAULT 580 #define KINECT_IR_CENTER_COL_DEFAULT 320 #define KINECT_IR_CENTER_ROW_DEFAULT 240 #define KINECT_RGB_TO_IR_X_DEFAULT (-0.0254) #define KINECT_RGB_TO_IR_Y_DEFAULT (-0.00013) #define KINECT_RGB_TO_IR_Z_DEFAULT (-0.00218) #define KINECT_RGB_TO_IR_ROLL_DEFAULT 0.0 // rad #define KINECT_RGB_TO_IR_PITCH_DEFAULT 0.0 // rad #define KINECT_RGB_TO_IR_YAW_DEFAULT 0.0 // rad #define KINECT_VENDOR_ID 0x45e #define XTION_VENDOR_ID 0x1d27 #define CHECK_RC(rc, what) \ if (rc != XN_STATUS_OK) \ { \ ROS_ERROR("%s failed: %s\n", what, xnGetStatusString(rc)); \ return false; \ } class OniRecorder { public: public: OniRecorder(ros::NodeHandle& node_handle); ~OniRecorder(); void changeDeptSensorModeCB(const oni_vicon_recorder::ChangeDepthSensorModeGoalConstPtr &goal); void runDepthSensorCB(const oni_vicon_recorder::RunDepthSensorGoalConstPtr& goal); bool closeDevice(); bool startRecording(std::string file); bool stopRecording(); int countFrames(); bool isRecording(); std::map<std::string, XnMapOutputMode> getSupportedModes(const DepthGenerator *generator); std::vector<std::string> getSupportedModeList(const std::map<std::string, XnMapOutputMode>& mode_map); XnMapOutputMode getCurrentMode(const DepthGenerator *generator) const; std::string getModeName(const XnMapOutputMode& mode) const; private: ros::NodeHandle node_handle_; kinect_t* kinect_; Recorder recorder_; bool recording_; bool running_; int frames; boost::shared_mutex frameLock_; std::map<std::string, XnMapOutputMode> modes_; actionlib::SimpleActionServer< oni_vicon_recorder::RunDepthSensorAction> run_depth_sensor_as_; actionlib::SimpleActionServer< oni_vicon_recorder::ChangeDepthSensorModeAction> change_depth_sensor_mode_as_; }; #endif <commit_msg>Added former rosbuild arm_rgbd package as rgbd_sensor catkin package<commit_after> #ifndef ONI_VICON_RECORDER_ONI_RECORDER_HPP #define ONI_VICON_RECORDER_ONI_RECORDER_HPP #include <string> #include <map> #include <signal.h> #include <boost/thread/mutex.hpp> #include <boost/format.hpp> // ROS #include <ros/ros.h> #include <image_transport/image_transport.h> #include <sensor_msgs/CameraInfo.h> #include <stereo_msgs/DisparityImage.h> #include <sensor_msgs/image_encodings.h> #include <message_filters/synchronizer.h> #include <message_filters/sync_policies/approximate_time.h> #include <tf/transform_listener.h> #include <actionlib/server/simple_action_server.h> #include <oni_vicon_recorder/RunDepthSensorAction.h> #include <oni_vicon_recorder/ChangeDepthSensorModeAction.h> #include "kinect.h" #define KINECT_IMAGE_COLS 640 #define KINECT_IMAGE_ROWS 480 #define KINECT_RGB_FOCAL_LENGTH_DEFAULT 525 #define KINECT_RGB_CENTER_COL_DEFAULT 320 #define KINECT_RGB_CENTER_ROW_DEFAULT 240 #define KINECT_IR_FOCAL_LENGTH_DEFAULT 580 #define KINECT_IR_CENTER_COL_DEFAULT 320 #define KINECT_IR_CENTER_ROW_DEFAULT 240 #define KINECT_RGB_TO_IR_X_DEFAULT (-0.0254) #define KINECT_RGB_TO_IR_Y_DEFAULT (-0.00013) #define KINECT_RGB_TO_IR_Z_DEFAULT (-0.00218) #define KINECT_RGB_TO_IR_ROLL_DEFAULT 0.0 // rad #define KINECT_RGB_TO_IR_PITCH_DEFAULT 0.0 // rad #define KINECT_RGB_TO_IR_YAW_DEFAULT 0.0 // rad #define KINECT_VENDOR_ID 0x45e #define XTION_VENDOR_ID 0x1d27 #define CHECK_RC(rc, what) \ if (rc != XN_STATUS_OK) \ { \ ROS_ERROR("%s failed: %s\n", what, xnGetStatusString(rc)); \ return false; \ } class OniRecorder { public: public: OniRecorder(ros::NodeHandle& node_handle); ~OniRecorder(); void changeDeptSensorModeCB(const oni_vicon_recorder::ChangeDepthSensorModeGoalConstPtr &goal); void runDepthSensorCB(const oni_vicon_recorder::RunDepthSensorGoalConstPtr& goal); bool closeDevice(); bool startRecording(std::string file); bool stopRecording(); int countFrames(); bool isRecording(); std::map<std::string, XnMapOutputMode> getSupportedModes(const DepthGenerator *generator); std::vector<std::string> getSupportedModeList(const std::map<std::string, XnMapOutputMode>& mode_map); XnMapOutputMode getCurrentMode(const DepthGenerator *generator) const; std::string getModeName(const XnMapOutputMode& mode) const; private: ros::NodeHandle node_handle_; kinect_t* kinect_; Recorder recorder_; bool recording_; bool running_; int frames; boost::shared_mutex frameLock_; std::map<std::string, XnMapOutputMode> modes_; actionlib::SimpleActionServer< oni_vicon_recorder::RunDepthSensorAction> run_depth_sensor_as_; actionlib::SimpleActionServer< oni_vicon_recorder::ChangeDepthSensorModeAction> change_depth_sensor_mode_as_; image_transport::ImageTransport* it_; std::string camera_name_; std::string frame_id_; sensor_msgs::Image gray_image_; sensor_msgs::CameraInfo depth_cam_info_; std::string calib_url_; // Standard parameters bool bus_reset_; std::string bayer_pattern_; std::string encoding_; std::string guid_; int iso_speed_; std::string video_mode_; inline bool isDepthStreamRequired() const; sensor_msgs::CameraInfoPtr fillCameraInfo (ros::Time time, bool is_rgb); void subscriberChangedEvent (); bool calibration_valid_; bool calibration_loaded_; // Publishers Camera Info ros::Publisher pub_depth_info_; // Publishers Images image_transport::Publisher pub_gray_image_; image_transport::Publisher pub_depth_image_; // Publishers Point Clouds ros::Publisher pub_disp_image_; ros::Publisher pub_point_cloud_; ros::Publisher pub_point_cloud_rgb_; // publish methods void publishGrayImage (ros::Time time); void publishDepthImage (ros::Time time); void publishDisparity (ros::Time time); void publishXYZPointCloud (ros::Time time); std::string depth_frame_id_; unsigned image_width_; unsigned image_height_; unsigned depth_width_; unsigned depth_height_; }; #endif <|endoftext|>
<commit_before>#include "MP3DataProvider.h" #include "Utils.h" #include "id3v2lib.h" extern "C" { #include "minimp3/minimp3.h" } clMP3DataProvider::clMP3DataProvider( const std::shared_ptr<clBlob>& Data ) : m_Data( Data ) , m_Format() , m_DecodingBuffer( MP3_MAX_SAMPLES_PER_FRAME * 16 ) , m_BufferUsed( 0 ) , m_StreamPos( 0 ) , m_InitialStreamPos( 0 ) , m_IsEndOfStream( false ) , m_MP3Decoder( mp3_create() ) { LoadMP3Info(); m_Format.m_NumChannels = m_MP3Info.channels; m_Format.m_SamplesPerSecond = m_MP3Info.sample_rate; m_Format.m_BitsPerSample = 16; } clMP3DataProvider::~clMP3DataProvider() { mp3_done( (mp3_decoder_t*)m_MP3Decoder ); } void clMP3DataProvider::SkipTags() { ID3v2_header* ID3TagHeader = get_tag_header_with_buffer( reinterpret_cast<const char*>( m_Data->GetDataPtr() + m_StreamPos ), static_cast<int>( m_Data->GetDataSize() - m_StreamPos ) ); if ( ID3TagHeader ) { m_StreamPos += ID3TagHeader->tag_size; free( ID3TagHeader ); } } void clMP3DataProvider::LoadMP3Info() { SkipTags(); int byteCount = mp3_decode( (mp3_decoder_t*)m_MP3Decoder, m_Data ? const_cast<uint8_t*>( m_Data->GetDataPtr() + m_StreamPos ) : nullptr, m_Data ? m_Data->GetDataSize() - m_StreamPos: 0, (signed short*)m_DecodingBuffer.data(), &m_MP3Info ); m_StreamPos += byteCount; m_InitialStreamPos = m_StreamPos; } const uint8_t* clMP3DataProvider::GetWaveData() const { return m_DecodingBuffer.data(); } size_t clMP3DataProvider::GetWaveDataSize() const { return m_BufferUsed; } int clMP3DataProvider::DecodeFromFile( size_t BytesRead ) { if ( m_IsEndOfStream || !m_Data ) { return 0; } size_t ByteCount = mp3_decode( (mp3_decoder_t*)m_MP3Decoder, const_cast<uint8_t*>( m_Data->GetDataPtr() + m_StreamPos ), m_Data->GetDataSize() - m_StreamPos, (signed short*)( m_DecodingBuffer.data() + BytesRead ), &m_MP3Info ); m_Format.m_NumChannels = m_MP3Info.channels; m_Format.m_SamplesPerSecond = m_MP3Info.sample_rate; m_StreamPos += ByteCount; if ( m_StreamPos >= m_Data->GetDataSize() || !ByteCount ) { m_IsEndOfStream = true; } return m_MP3Info.audio_bytes; } size_t clMP3DataProvider::StreamWaveData( size_t Size ) { if ( m_IsEndOfStream ) { return 0; } size_t OldSize = m_DecodingBuffer.size(); if ( Size > OldSize ) { m_DecodingBuffer.resize( Size, 0 ); } size_t BytesRead = 0; while ( BytesRead + MP3_MAX_SAMPLES_PER_FRAME * 2 < Size ) { int Ret = DecodeFromFile( BytesRead ); if ( Ret > 0 ) { BytesRead += Ret; } else if ( Ret == 0 ) { m_IsEndOfStream = true; break; } else { // there is no audio data in this frame, just skip it } } m_BufferUsed = BytesRead; return m_BufferUsed; } void clMP3DataProvider::Seek( float Seconds ) { mp3_done( (mp3_decoder_t*)m_MP3Decoder ); m_MP3Decoder = mp3_create(); m_StreamPos = 0; m_IsEndOfStream = false; LoadMP3Info(); } <commit_msg>OS X: compilation fix<commit_after>#include "MP3DataProvider.h" #include "Utils.h" #include "id3v2lib.h" extern "C" { #include "minimp3/minimp3.h" } clMP3DataProvider::clMP3DataProvider( const std::shared_ptr<clBlob>& Data ) : m_Data( Data ) , m_Format() , m_DecodingBuffer( MP3_MAX_SAMPLES_PER_FRAME * 16 ) , m_BufferUsed( 0 ) , m_StreamPos( 0 ) , m_InitialStreamPos( 0 ) , m_IsEndOfStream( false ) , m_MP3Decoder( mp3_create() ) { LoadMP3Info(); m_Format.m_NumChannels = m_MP3Info.channels; m_Format.m_SamplesPerSecond = m_MP3Info.sample_rate; m_Format.m_BitsPerSample = 16; } clMP3DataProvider::~clMP3DataProvider() { mp3_done( (mp3_decoder_t*)m_MP3Decoder ); } void clMP3DataProvider::SkipTags() { ID3v2_header* ID3TagHeader = get_tag_header_with_buffer( reinterpret_cast<const char*>( m_Data->GetDataPtr() + m_StreamPos ), static_cast<int>( m_Data->GetDataSize() - m_StreamPos ) ); if ( ID3TagHeader ) { m_StreamPos += ID3TagHeader->tag_size; delete_header( ID3TagHeader ); } } void clMP3DataProvider::LoadMP3Info() { SkipTags(); int byteCount = mp3_decode( (mp3_decoder_t*)m_MP3Decoder, m_Data ? const_cast<uint8_t*>( m_Data->GetDataPtr() + m_StreamPos ) : nullptr, m_Data ? m_Data->GetDataSize() - m_StreamPos: 0, (signed short*)m_DecodingBuffer.data(), &m_MP3Info ); m_StreamPos += byteCount; m_InitialStreamPos = m_StreamPos; } const uint8_t* clMP3DataProvider::GetWaveData() const { return m_DecodingBuffer.data(); } size_t clMP3DataProvider::GetWaveDataSize() const { return m_BufferUsed; } int clMP3DataProvider::DecodeFromFile( size_t BytesRead ) { if ( m_IsEndOfStream || !m_Data ) { return 0; } size_t ByteCount = mp3_decode( (mp3_decoder_t*)m_MP3Decoder, const_cast<uint8_t*>( m_Data->GetDataPtr() + m_StreamPos ), m_Data->GetDataSize() - m_StreamPos, (signed short*)( m_DecodingBuffer.data() + BytesRead ), &m_MP3Info ); m_Format.m_NumChannels = m_MP3Info.channels; m_Format.m_SamplesPerSecond = m_MP3Info.sample_rate; m_StreamPos += ByteCount; if ( m_StreamPos >= m_Data->GetDataSize() || !ByteCount ) { m_IsEndOfStream = true; } return m_MP3Info.audio_bytes; } size_t clMP3DataProvider::StreamWaveData( size_t Size ) { if ( m_IsEndOfStream ) { return 0; } size_t OldSize = m_DecodingBuffer.size(); if ( Size > OldSize ) { m_DecodingBuffer.resize( Size, 0 ); } size_t BytesRead = 0; while ( BytesRead + MP3_MAX_SAMPLES_PER_FRAME * 2 < Size ) { int Ret = DecodeFromFile( BytesRead ); if ( Ret > 0 ) { BytesRead += Ret; } else if ( Ret == 0 ) { m_IsEndOfStream = true; break; } else { // there is no audio data in this frame, just skip it } } m_BufferUsed = BytesRead; return m_BufferUsed; } void clMP3DataProvider::Seek( float Seconds ) { mp3_done( (mp3_decoder_t*)m_MP3Decoder ); m_MP3Decoder = mp3_create(); m_StreamPos = 0; m_IsEndOfStream = false; LoadMP3Info(); } <|endoftext|>
<commit_before>/** * @file */ #pragma once #include "bi/common/TypeParameterised.hpp" #include "bi/io/indentable_ostream.hpp" namespace bi { /** * C++ code generator. * * @ingroup io */ class CppBaseGenerator: public indentable_ostream { public: CppBaseGenerator(std::ostream& base, const int level = 0, const bool header = false); using indentable_ostream::visit; virtual void visit(const Name* o); virtual void visit(const ExpressionList* o); virtual void visit(const Literal<bool>* o); virtual void visit(const Literal<int64_t>* o); virtual void visit(const Literal<double>* o); virtual void visit(const Literal<const char*>* o); virtual void visit(const Parentheses* o); virtual void visit(const Sequence* o); virtual void visit(const Cast* o); virtual void visit(const Call<Unknown>* o); virtual void visit(const Call<Function>* o); virtual void visit(const Call<MemberFunction>* o); virtual void visit(const Call<Fiber>* o); virtual void visit(const Call<MemberFiber>* o); virtual void visit(const Call<Parameter>* o); virtual void visit(const Call<LocalVariable>* o); virtual void visit(const Call<MemberVariable>* o); virtual void visit(const Call<GlobalVariable>* o); virtual void visit(const Call<BinaryOperator>* o); virtual void visit(const Call<UnaryOperator>* o); virtual void visit(const Assign* o); virtual void visit(const Slice* o); virtual void visit(const Query* o); virtual void visit(const Get* o); virtual void visit(const LambdaFunction* o); virtual void visit(const Span* o); virtual void visit(const Index* o); virtual void visit(const Range* o); virtual void visit(const Member* o); virtual void visit(const Global* o); virtual void visit(const This* o); virtual void visit(const Super* o); virtual void visit(const Nil* o); virtual void visit(const Parameter* o); virtual void visit(const Identifier<Unknown>* o); virtual void visit(const Identifier<Parameter>* o); virtual void visit(const Identifier<GlobalVariable>* o); virtual void visit(const Identifier<LocalVariable>* o); virtual void visit(const Identifier<MemberVariable>* o); virtual void visit(const OverloadedIdentifier<Function>* o); virtual void visit(const OverloadedIdentifier<Fiber>* o); virtual void visit(const OverloadedIdentifier<MemberFunction>* o); virtual void visit(const OverloadedIdentifier<MemberFiber>* o); virtual void visit(const OverloadedIdentifier<BinaryOperator>* o); virtual void visit(const OverloadedIdentifier<UnaryOperator>* o); virtual void visit(const File* o); virtual void visit(const GlobalVariable* o); virtual void visit(const LocalVariable* o); virtual void visit(const MemberVariable* o); virtual void visit(const Function* o); virtual void visit(const Fiber* o); virtual void visit(const MemberFunction* o); virtual void visit(const MemberFiber* o); virtual void visit(const Program* o); virtual void visit(const BinaryOperator* o); virtual void visit(const UnaryOperator* o); virtual void visit(const AssignmentOperator* o); virtual void visit(const ConversionOperator* o); virtual void visit(const Basic* o); virtual void visit(const Class* o); virtual void visit(const Generic* o); virtual void visit(const Assume* o); virtual void visit(const ExpressionStatement* o); virtual void visit(const If* o); virtual void visit(const For* o); virtual void visit(const While* o); virtual void visit(const DoWhile* o); virtual void visit(const Assert* o); virtual void visit(const Return* o); virtual void visit(const Yield* o); virtual void visit(const Raw* o); virtual void visit(const StatementList* o); virtual void visit(const EmptyType* o); virtual void visit(const ArrayType* o); virtual void visit(const TupleType* o); virtual void visit(const FunctionType* o); virtual void visit(const FiberType* o); virtual void visit(const OptionalType* o); virtual void visit(const ClassType* o); virtual void visit(const BasicType* o); virtual void visit(const GenericType* o); virtual void visit(const MemberType* o); virtual void visit(const UnknownType* o); virtual void visit(const TypeList* o); protected: /** * Generate code for template parameters (`template<...>`). */ template<class ObjectType> void genTemplateParams(const ObjectType* o); /** * Generate code for template arguments (`<...>`). */ template<class ObjectType> void genTemplateArgs(const ObjectType* o); /** * Generate the initialization of a variable, including the call to the * constructor and/or assignment of the initial value. */ template<class T> void genInit(const T* o); /** * Generate macro to put function call on stack trace. */ void genTraceFunction(const std::string& name, const Location* loc); /** * Generate macro to update line on stack trace. */ void genTraceLine(const Location* loc); /* * Generate arguments for function calls with appropriate casts where * necessary. */ void genArgs(const Expression* args, const Type* types); void genLeftArg(const Call<BinaryOperator>* o); void genRightArg(const Call<BinaryOperator>* o); void genSingleArg(const Call<UnaryOperator>* o); void genArg(const Expression* arg, const Type* type); /** * Output header instead of source? */ bool header; /** * Are we on the left side of an assignment statement? */ int inAssign; /** * Are we inside a constructor? */ int inConstructor; /** * Are we inside the body of a lambda function? */ int inLambda; /** * Are we inside a sequence? */ int inSequence; }; } template<class T> void bi::CppBaseGenerator::genInit(const T* o) { if (o->type->isArray()) { ArrayType* type = dynamic_cast<ArrayType*>(o->type->canonical()); assert(type); if (!o->brackets->isEmpty()) { if (!o->value->isEmpty()) { middle(" = "); if (o->value->type->isConvertible(*type)) { middle(o->value); } else { middle("libbirch::make_array_and_assign<" << type->single << ">("); if (!o->isValue()) { middle("context_, "); } middle("libbirch::make_shape(" << o->brackets << ')'); middle(", " << o->value << ')'); } } else { middle(" = libbirch::make_array<" << type->single << ">("); if (!o->isValue()) { middle("context_, "); } middle("libbirch::make_shape(" << o->brackets << ')'); if (!o->args->isEmpty()) { middle(", " << o->args); } middle(')'); } } else if (!o->value->isEmpty()) { middle(" = " << o->value); } } else if (o->type->isClass()) { if (!o->value->isEmpty()) { middle("(context_, " << o->value << ')'); } else { middle(" = libbirch::make_pointer<" << o->type << ">(context_"); if (!o->args->isEmpty()) { middle(", " << o->args); } middle(")"); } } else if (!o->value->isEmpty()) { middle('('); if (!o->type->isValue()) { middle("context_, "); } middle(o->value << ')'); } } template<class ObjectType> void bi::CppBaseGenerator::genTemplateParams(const ObjectType* o) { if (o->isGeneric()) { start("template<"); if (!o->isBound()) { for (auto iter = o->typeParams->begin(); iter != o->typeParams->end(); ++iter) { if (iter != o->typeParams->begin()) { middle(", "); } middle("class " << *iter); } } finish('>'); } } template<class ObjectType> void bi::CppBaseGenerator::genTemplateArgs(const ObjectType* o) { if (o->isGeneric()) { middle('<' << o->typeParams << '>'); } } <commit_msg>Fixed C++ code generation for initializing lambda function variables.<commit_after>/** * @file */ #pragma once #include "bi/common/TypeParameterised.hpp" #include "bi/io/indentable_ostream.hpp" namespace bi { /** * C++ code generator. * * @ingroup io */ class CppBaseGenerator: public indentable_ostream { public: CppBaseGenerator(std::ostream& base, const int level = 0, const bool header = false); using indentable_ostream::visit; virtual void visit(const Name* o); virtual void visit(const ExpressionList* o); virtual void visit(const Literal<bool>* o); virtual void visit(const Literal<int64_t>* o); virtual void visit(const Literal<double>* o); virtual void visit(const Literal<const char*>* o); virtual void visit(const Parentheses* o); virtual void visit(const Sequence* o); virtual void visit(const Cast* o); virtual void visit(const Call<Unknown>* o); virtual void visit(const Call<Function>* o); virtual void visit(const Call<MemberFunction>* o); virtual void visit(const Call<Fiber>* o); virtual void visit(const Call<MemberFiber>* o); virtual void visit(const Call<Parameter>* o); virtual void visit(const Call<LocalVariable>* o); virtual void visit(const Call<MemberVariable>* o); virtual void visit(const Call<GlobalVariable>* o); virtual void visit(const Call<BinaryOperator>* o); virtual void visit(const Call<UnaryOperator>* o); virtual void visit(const Assign* o); virtual void visit(const Slice* o); virtual void visit(const Query* o); virtual void visit(const Get* o); virtual void visit(const LambdaFunction* o); virtual void visit(const Span* o); virtual void visit(const Index* o); virtual void visit(const Range* o); virtual void visit(const Member* o); virtual void visit(const Global* o); virtual void visit(const This* o); virtual void visit(const Super* o); virtual void visit(const Nil* o); virtual void visit(const Parameter* o); virtual void visit(const Identifier<Unknown>* o); virtual void visit(const Identifier<Parameter>* o); virtual void visit(const Identifier<GlobalVariable>* o); virtual void visit(const Identifier<LocalVariable>* o); virtual void visit(const Identifier<MemberVariable>* o); virtual void visit(const OverloadedIdentifier<Function>* o); virtual void visit(const OverloadedIdentifier<Fiber>* o); virtual void visit(const OverloadedIdentifier<MemberFunction>* o); virtual void visit(const OverloadedIdentifier<MemberFiber>* o); virtual void visit(const OverloadedIdentifier<BinaryOperator>* o); virtual void visit(const OverloadedIdentifier<UnaryOperator>* o); virtual void visit(const File* o); virtual void visit(const GlobalVariable* o); virtual void visit(const LocalVariable* o); virtual void visit(const MemberVariable* o); virtual void visit(const Function* o); virtual void visit(const Fiber* o); virtual void visit(const MemberFunction* o); virtual void visit(const MemberFiber* o); virtual void visit(const Program* o); virtual void visit(const BinaryOperator* o); virtual void visit(const UnaryOperator* o); virtual void visit(const AssignmentOperator* o); virtual void visit(const ConversionOperator* o); virtual void visit(const Basic* o); virtual void visit(const Class* o); virtual void visit(const Generic* o); virtual void visit(const Assume* o); virtual void visit(const ExpressionStatement* o); virtual void visit(const If* o); virtual void visit(const For* o); virtual void visit(const While* o); virtual void visit(const DoWhile* o); virtual void visit(const Assert* o); virtual void visit(const Return* o); virtual void visit(const Yield* o); virtual void visit(const Raw* o); virtual void visit(const StatementList* o); virtual void visit(const EmptyType* o); virtual void visit(const ArrayType* o); virtual void visit(const TupleType* o); virtual void visit(const FunctionType* o); virtual void visit(const FiberType* o); virtual void visit(const OptionalType* o); virtual void visit(const ClassType* o); virtual void visit(const BasicType* o); virtual void visit(const GenericType* o); virtual void visit(const MemberType* o); virtual void visit(const UnknownType* o); virtual void visit(const TypeList* o); protected: /** * Generate code for template parameters (`template<...>`). */ template<class ObjectType> void genTemplateParams(const ObjectType* o); /** * Generate code for template arguments (`<...>`). */ template<class ObjectType> void genTemplateArgs(const ObjectType* o); /** * Generate the initialization of a variable, including the call to the * constructor and/or assignment of the initial value. */ template<class T> void genInit(const T* o); /** * Generate macro to put function call on stack trace. */ void genTraceFunction(const std::string& name, const Location* loc); /** * Generate macro to update line on stack trace. */ void genTraceLine(const Location* loc); /* * Generate arguments for function calls with appropriate casts where * necessary. */ void genArgs(const Expression* args, const Type* types); void genLeftArg(const Call<BinaryOperator>* o); void genRightArg(const Call<BinaryOperator>* o); void genSingleArg(const Call<UnaryOperator>* o); void genArg(const Expression* arg, const Type* type); /** * Output header instead of source? */ bool header; /** * Are we on the left side of an assignment statement? */ int inAssign; /** * Are we inside a constructor? */ int inConstructor; /** * Are we inside the body of a lambda function? */ int inLambda; /** * Are we inside a sequence? */ int inSequence; }; } template<class T> void bi::CppBaseGenerator::genInit(const T* o) { if (o->type->isArray()) { ArrayType* type = dynamic_cast<ArrayType*>(o->type->canonical()); assert(type); if (!o->brackets->isEmpty()) { if (!o->value->isEmpty()) { middle(" = "); if (o->value->type->isConvertible(*type)) { middle(o->value); } else { middle("libbirch::make_array_and_assign<" << type->single << ">("); if (!o->isValue()) { middle("context_, "); } middle("libbirch::make_shape(" << o->brackets << ')'); middle(", " << o->value << ')'); } } else { middle(" = libbirch::make_array<" << type->single << ">("); if (!o->isValue()) { middle("context_, "); } middle("libbirch::make_shape(" << o->brackets << ')'); if (!o->args->isEmpty()) { middle(", " << o->args); } middle(')'); } } else if (!o->value->isEmpty()) { middle(" = " << o->value); } } else if (o->type->isClass()) { if (!o->value->isEmpty()) { middle("(context_, " << o->value << ')'); } else { middle(" = libbirch::make_pointer<" << o->type << ">(context_"); if (!o->args->isEmpty()) { middle(", " << o->args); } middle(")"); } } else if (!o->value->isEmpty()) { middle('('); if (!o->type->isValue() && !o->type->isFunction()) { middle("context_, "); } middle(o->value << ')'); } } template<class ObjectType> void bi::CppBaseGenerator::genTemplateParams(const ObjectType* o) { if (o->isGeneric()) { start("template<"); if (!o->isBound()) { for (auto iter = o->typeParams->begin(); iter != o->typeParams->end(); ++iter) { if (iter != o->typeParams->begin()) { middle(", "); } middle("class " << *iter); } } finish('>'); } } template<class ObjectType> void bi::CppBaseGenerator::genTemplateArgs(const ObjectType* o) { if (o->isGeneric()) { middle('<' << o->typeParams << '>'); } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: testhelper.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: dbo $ $Date: 2001-05-08 15:55:51 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include <stdio.h> #include <rtl/ustrbuf.hxx> #include <osl/diagnose.h> #include <cppuhelper/servicefactory.hxx> #include <com/sun/star/registry/XSimpleRegistry.hpp> #include <com/sun/star/registry/XImplementationRegistration.hpp> #include <com/sun/star/lang/XMultiServiceFactory.hpp> #include <com/sun/star/lang/XComponent.hpp> #include "testhelper.hxx" using namespace rtl; using namespace cppu; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::registry; #if (defined UNX) || (defined OS2) int main( int argc, char * argv[] ) #else int __cdecl main( int argc, char * argv[] ) #endif { Reference< XMultiServiceFactory > xMgr( createRegistryServiceFactory( OUString( RTL_CONSTASCII_USTRINGPARAM("cpputest.rdb") ) ) ); sal_Bool bSucc = sal_False; try { Reference< XImplementationRegistration > xImplReg( xMgr->createInstance( OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.registry.ImplementationRegistration") ) ), UNO_QUERY ); OSL_ENSURE( xImplReg.is(), "### no impl reg!" ); #ifdef UNX #define REG_PREFIX "lib" #ifdef MACOSX #define DLL_POSTFIX ".dylib.framework" #else #define DLL_POSTFIX ".so" #endif #else #define REG_PREFIX "" #define DLL_POSTFIX ".dll" #endif OString aLibName( REG_PREFIX ); aLibName += "corefl"; #ifndef OS2 aLibName += DLL_POSTFIX; #endif xImplReg->registerImplementation( OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.loader.SharedLibrary") ), OUString::createFromAscii( aLibName.getStr() ), Reference< XSimpleRegistry >() ); testPropertyTypeHelper(); testidlclass( xMgr ); test_PropertySetHelper(); test_ImplHelper( xMgr ); test_interfacecontainer(); } catch (Exception & rExc) { OSL_ENSURE( sal_False, "### exception occured!" ); OString aMsg( OUStringToOString( rExc.Message, RTL_TEXTENCODING_ASCII_US ) ); OSL_TRACE( "### exception occured: " ); OSL_TRACE( aMsg.getStr() ); OSL_TRACE( "\n" ); } Reference< XComponent >( xMgr, UNO_QUERY )->dispose(); printf( "Test finished\n" ); return 0; } <commit_msg>context tests<commit_after>/************************************************************************* * * $RCSfile: testhelper.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: dbo $ $Date: 2001-06-01 11:47:11 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include <stdio.h> #include <rtl/ustrbuf.hxx> #include <osl/diagnose.h> #include <cppuhelper/component_context.hxx> #include <cppuhelper/servicefactory.hxx> #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/registry/XSimpleRegistry.hpp> #include <com/sun/star/registry/XImplementationRegistration.hpp> #include <com/sun/star/lang/XMultiServiceFactory.hpp> #include <com/sun/star/lang/XComponent.hpp> #include "testhelper.hxx" using namespace rtl; using namespace cppu; using namespace com::sun::star::uno; using namespace com::sun::star; using namespace com::sun::star::lang; using namespace com::sun::star::registry; #if (defined UNX) || (defined OS2) int main( int argc, char * argv[] ) #else int __cdecl main( int argc, char * argv[] ) #endif { Reference< XMultiComponentFactory > xMgr( createRegistryServiceFactory( OUString( RTL_CONSTASCII_USTRINGPARAM("cpputest.rdb") ) ), UNO_QUERY ); Reference< XComponentContext > xInitialContext; OSL_VERIFY( Reference< beans::XPropertySet >( xMgr, UNO_QUERY )->getPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM("DefaultContext") ) ) >>= xInitialContext ); ContextEntry_Init aEntry; aEntry.bLateInitService = false; aEntry.name = OUString( RTL_CONSTASCII_USTRINGPARAM("bla, bla") ); aEntry.value = makeAny( (sal_Int32)5 ); Reference< XComponentContext > xContext( createComponentContext( &aEntry, 1, xInitialContext ) ); OSL_ASSERT( xContext->getServiceManager() == xMgr ); sal_Bool bSucc = sal_False; try { Reference< XImplementationRegistration > xImplReg( xMgr->createInstanceWithContext( OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.registry.ImplementationRegistration") ), xContext ), UNO_QUERY ); OSL_ENSURE( xImplReg.is(), "### no impl reg!" ); #ifdef UNX #define REG_PREFIX "lib" #ifdef MACOSX #define DLL_POSTFIX ".dylib.framework" #else #define DLL_POSTFIX ".so" #endif #else #define REG_PREFIX "" #define DLL_POSTFIX ".dll" #endif OString aLibName( REG_PREFIX ); aLibName += "corefl"; #ifndef OS2 aLibName += DLL_POSTFIX; #endif xImplReg->registerImplementation( OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.loader.SharedLibrary") ), OUString::createFromAscii( aLibName.getStr() ), Reference< XSimpleRegistry >() ); Reference< XMultiServiceFactory > x( xMgr, UNO_QUERY ); testPropertyTypeHelper(); testidlclass( x ); test_PropertySetHelper(); test_ImplHelper( x ); test_interfacecontainer(); } catch (Exception & rExc) { OSL_ENSURE( sal_False, "### exception occured!" ); OString aMsg( OUStringToOString( rExc.Message, RTL_TEXTENCODING_ASCII_US ) ); OSL_TRACE( "### exception occured: " ); OSL_TRACE( aMsg.getStr() ); OSL_TRACE( "\n" ); } OSL_VERIFY( xContext->getValueByName( OUString( RTL_CONSTASCII_USTRINGPARAM("bla, bla") ) ) == (sal_Int32)5 ); Reference< XComponent >( xInitialContext, UNO_QUERY )->dispose(); printf( "Test finished\n" ); return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2014 Bauhaus-Universitaet Weimar // This Software is distributed under the Modified BSD License, see license.txt. // // Virtual Reality and Visualization Research Group // Faculty of Media, Bauhaus-Universitaet Weimar // http://www.uni-weimar.de/medien/vr #include <lamure/ren/gpu_context.h> #include <lamure/ren/model_database.h> #include <lamure/ren/policy.h> #include <lamure/ren/cut_database.h> #include <lamure/ren/config.h> namespace lamure { namespace ren { gpu_context:: gpu_context(const context_t context_id) : context_id_(context_id), is_created_(false), temp_buffer_a_(nullptr), temp_buffer_b_(nullptr), primary_buffer_(nullptr), temporary_storages_(temporary_storages(nullptr, nullptr)), temporary_storages_provenance_(temporary_storages(nullptr, nullptr)), upload_budget_in_nodes_(LAMURE_DEFAULT_UPLOAD_BUDGET), render_budget_in_nodes_(LAMURE_DEFAULT_VIDEO_MEMORY_BUDGET) { } gpu_context:: ~gpu_context() { temporary_storages_ = temporary_storages(nullptr, nullptr); temporary_storages_provenance_ = temporary_storages(nullptr, nullptr); if (temp_buffer_a_) { delete temp_buffer_a_; temp_buffer_a_ = nullptr; } if (temp_buffer_b_) { delete temp_buffer_b_; temp_buffer_b_ = nullptr; } if (primary_buffer_) { delete primary_buffer_; primary_buffer_ = nullptr; } } void gpu_context:: create(scm::gl::render_device_ptr device) { assert(device); if (is_created_) { return; } is_created_ = true; test_video_memory(device); model_database* database = model_database::get_instance(); temp_buffer_a_ = new gpu_access(device, upload_budget_in_nodes_, database->get_primitives_per_node(), false); temp_buffer_b_ = new gpu_access(device, upload_budget_in_nodes_, database->get_primitives_per_node(), false); primary_buffer_ = new gpu_access(device, render_budget_in_nodes_, database->get_primitives_per_node(), true); map_temporary_storage(cut_database_record::temporary_buffer::BUFFER_A, device); map_temporary_storage(cut_database_record::temporary_buffer::BUFFER_B, device); } void gpu_context:: test_video_memory(scm::gl::render_device_ptr device) { model_database* database = model_database::get_instance(); policy* policy = policy::get_instance(); float safety = 0.75; size_t video_ram_free_in_mb = gpu_access::query_video_memory_in_mb(device) * safety; size_t render_budget_in_mb = policy->render_budget_in_mb(); if(policy->out_of_core_budget_in_mb() == 0) { std::cout << "##### Total free video memory (" << video_ram_free_in_mb << " MB) will be used for the render budget #####" << std::endl; render_budget_in_mb = video_ram_free_in_mb; } else if(video_ram_free_in_mb < render_budget_in_mb) { std::cout << "##### The specified render budget is too large! " << video_ram_free_in_mb << " MB will be used for the render budget #####" << std::endl; render_budget_in_mb = video_ram_free_in_mb; } else { std::cout << "##### " << policy->render_budget_in_mb() << " MB will be used for the render budget #####" << std::endl; } long node_size_total = database->get_primitives_per_node() * sizeof(provenance_data) + database->get_slot_size(); render_budget_in_nodes_ = (render_budget_in_mb * 1024 * 1024) / node_size_total; // std::cout << "RENDER1: " << render_budget_in_mb << std::endl; // std::cout << "RENDER1: " << render_budget_in_mb * 0.75 << std::endl; // std::cout << "RENDER1: " << node_size_total << std::endl; // std::cout << "RENDER1: " << (render_budget_in_mb * 0.75) / node_size_total << std::endl; // std::cout << "RENDER1: " << render_budget_in_nodes_ << std::endl; // render_budget_in_mb = policy->render_budget_in_mb(); // // render_budget_in_mb = render_budget_in_mb < LAMURE_MIN_VIDEO_MEMORY_BUDGET ? LAMURE_MIN_VIDEO_MEMORY_BUDGET : render_budget_in_mb; // render_budget_in_mb = render_budget_in_mb > video_ram_free_in_mb * 0.75 ? video_ram_free_in_mb * 0.75 : render_budget_in_mb; // render_budget_in_nodes_ = (render_budget_in_mb * 1024u * 1024u) / (database->get_primitives_per_node() * sizeof(provenance_data) + database->get_slot_size()); // std::cout << "RENDER2: " << render_budget_in_nodes_ << std::endl; size_t max_upload_budget_in_mb = policy->max_upload_budget_in_mb(); max_upload_budget_in_mb = max_upload_budget_in_mb < LAMURE_MIN_UPLOAD_BUDGET ? LAMURE_MIN_UPLOAD_BUDGET : max_upload_budget_in_mb; max_upload_budget_in_mb = max_upload_budget_in_mb > video_ram_free_in_mb * 0.125 ? video_ram_free_in_mb * 0.125 : max_upload_budget_in_mb; size_t max_upload_budget_in_nodes = (max_upload_budget_in_mb * 1024u * 1024u) / database->get_slot_size(); upload_budget_in_nodes_ = max_upload_budget_in_nodes; #if 1 // upload_budget_in_nodes_ = max_upload_budget_in_nodes/4; #else gpu_access* test_temp = new gpu_access(device, 1, database->surfels_per_node(), false); gpu_access* test_main = new gpu_access(device, 1, database->surfels_per_node(), true); LodPointCloud::serializedsurfel* node_data = (LodPointCloud::serializedsurfel*)new char[size_of_node_in_bytes]; memset((char*)node_data, 0, size_of_node_in_bytes); char* mapped_temp = test_temp->map(device); memcpy(mapped_temp, node_data, size_of_node_in_bytes); test_temp->unmap(device); auto frame_duration_in_ns = boost::timer::nanosecond_type(16.0 * 1000 * 1000); boost::timer::cpu_timer upload_timer; unsigned int iteration = 0; while (true) { upload_timer.start(); for (unsigned int i = 0; i < upload_budget_in_nodes_; ++i) { size_t offset_in_temp_VBO = 0; size_t offset_in_render_VBO = 0; device->main_context()->copy_buffer_data(test_main->buffer(), test_temp->buffer(), offset_in_render_VBO, offset_in_temp_VBO, size_of_node_in_bytes); } upload_timer.stop(); boost::timer::cpu_times const elapsed(upload_timer.elapsed()); boost::timer::nanosecond_type const elapsed_ns(elapsed.system + elapsed.user); if (iteration++ > 1) { if (elapsed_ns < frame_duration_in_ns) { if (upload_budget_in_nodes_ < max_upload_budget_in_nodes) { ++upload_budget_in_nodes_; } else { break; } } else { break; } } } delete test_temp; delete test_main; delete[] node_data; device->main_context()->apply(); #endif #ifdef LAMURE_ENABLE_INFO std::cout << "lamure: context " << context_id_ << " render budget (MB): " << render_budget_in_mb << std::endl; std::cout << "lamure: context " << context_id_ << " upload budget (MB): " << max_upload_budget_in_mb << std::endl; #endif } scm::gl::buffer_ptr gpu_context:: get_context_buffer(scm::gl::render_device_ptr device) { if (!is_created_) create(device); assert(device); return primary_buffer_->get_buffer(); } scm::gl::vertex_array_ptr gpu_context:: get_context_memory(bvh::primitive_type type, scm::gl::render_device_ptr device) { if (!is_created_) create(device); assert(device); return primary_buffer_->get_memory(type); } void gpu_context:: map_temporary_storage(const cut_database_record::temporary_buffer& buffer, scm::gl::render_device_ptr device) { if (!is_created_) create(device); assert(device); switch (buffer) { case cut_database_record::temporary_buffer::BUFFER_A: if (!temp_buffer_a_->is_mapped()) { temporary_storages_.storage_a_ = temp_buffer_a_->map(device); temporary_storages_provenance_.storage_a_ = temp_buffer_a_->map_provenance(device); } return; break; case cut_database_record::temporary_buffer::BUFFER_B: if (!temp_buffer_b_->is_mapped()) { temporary_storages_.storage_b_ = temp_buffer_b_->map(device); temporary_storages_provenance_.storage_b_ = temp_buffer_b_->map_provenance(device); } return; break; default: break; } throw std::runtime_error( "lamure: Failed to map temporary buffer on context: " + context_id_); } void gpu_context:: unmap_temporary_storage(const cut_database_record::temporary_buffer& buffer, scm::gl::render_device_ptr device) { if (!is_created_) create(device); assert(device); switch (buffer) { case cut_database_record::temporary_buffer::BUFFER_A: if (temp_buffer_a_->is_mapped()) { temp_buffer_a_->unmap(device); temp_buffer_a_->unmap_provenance(device); } break; case cut_database_record::temporary_buffer::BUFFER_B: if (temp_buffer_b_->is_mapped()) { temp_buffer_b_->unmap(device); temp_buffer_b_->unmap_provenance(device); } break; default: break; } } //returns true if any node has been uploaded; false otherwise bool gpu_context:: update_primary_buffer(const cut_database_record::temporary_buffer& from_buffer, scm::gl::render_device_ptr device) { if (!is_created_) create(device); assert(device); model_database* database = model_database::get_instance(); cut_database* cuts = cut_database::get_instance(); size_t uploaded_nodes = 0; switch (from_buffer) { case cut_database_record::temporary_buffer::BUFFER_A: { if (temp_buffer_a_->is_mapped()) { throw std::runtime_error( "lamure: gpu_context::Failed to transfer nodes into main memory on context: " + context_id_); } std::vector<cut_database_record::slot_update_desc>& transfer_descr_list = cuts->get_updated_set(context_id_); if (!transfer_descr_list.empty()) { uploaded_nodes += transfer_descr_list.size(); for (const auto& transfer_desc : transfer_descr_list) { size_t offset_in_temp_VBO = transfer_desc.src_ * database->get_slot_size(); size_t offset_in_render_VBO = transfer_desc.dst_ * database->get_slot_size(); device->main_context()->copy_buffer_data( primary_buffer_->get_buffer(), temp_buffer_a_->get_buffer(), offset_in_render_VBO, offset_in_temp_VBO, database->get_slot_size() ); size_t offset_in_temp_VBO_provenance = transfer_desc.src_ * database->get_primitives_per_node() * sizeof(provenance_data); size_t offset_in_render_VBO_provenance = transfer_desc.dst_ * database->get_primitives_per_node() * sizeof(provenance_data); device->main_context()->copy_buffer_data( primary_buffer_->get_buffer_provenance(), temp_buffer_a_->get_buffer_provenance(), offset_in_render_VBO_provenance, offset_in_temp_VBO_provenance, database->get_primitives_per_node() * sizeof(provenance_data) ); } } break; } case cut_database_record::temporary_buffer::BUFFER_B: { if (temp_buffer_b_->is_mapped()) { throw std::runtime_error( "lamure: gpu_context::Failed to transfer nodes into main memory on context: " + context_id_); } std::vector<cut_database_record::slot_update_desc>& transfer_descr_list = cuts->get_updated_set(context_id_); if (!transfer_descr_list.empty()) { uploaded_nodes += transfer_descr_list.size(); for (const auto& transfer_desc : transfer_descr_list) { size_t offset_in_temp_VBO = transfer_desc.src_ * database->get_slot_size(); size_t offset_in_render_VBO = transfer_desc.dst_ * database->get_slot_size(); device->main_context()->copy_buffer_data( primary_buffer_->get_buffer(), temp_buffer_b_->get_buffer(), offset_in_render_VBO, offset_in_temp_VBO, database->get_slot_size() ); size_t offset_in_temp_VBO_provenance = transfer_desc.src_ * database->get_primitives_per_node() * sizeof(provenance_data); size_t offset_in_render_VBO_provenance = transfer_desc.dst_ * database->get_primitives_per_node() * sizeof(provenance_data); device->main_context()->copy_buffer_data( primary_buffer_->get_buffer_provenance(), temp_buffer_b_->get_buffer_provenance(), offset_in_render_VBO_provenance, offset_in_temp_VBO_provenance, database->get_primitives_per_node() * sizeof(provenance_data) ); } } break; } default: break; } return uploaded_nodes != 0; } } } <commit_msg>*improved budget-usage<commit_after>// Copyright (c) 2014 Bauhaus-Universitaet Weimar // This Software is distributed under the Modified BSD License, see license.txt. // // Virtual Reality and Visualization Research Group // Faculty of Media, Bauhaus-Universitaet Weimar // http://www.uni-weimar.de/medien/vr #include <lamure/ren/gpu_context.h> #include <lamure/ren/model_database.h> #include <lamure/ren/policy.h> #include <lamure/ren/cut_database.h> #include <lamure/ren/config.h> namespace lamure { namespace ren { gpu_context:: gpu_context(const context_t context_id) : context_id_(context_id), is_created_(false), temp_buffer_a_(nullptr), temp_buffer_b_(nullptr), primary_buffer_(nullptr), temporary_storages_(temporary_storages(nullptr, nullptr)), temporary_storages_provenance_(temporary_storages(nullptr, nullptr)), upload_budget_in_nodes_(LAMURE_DEFAULT_UPLOAD_BUDGET), render_budget_in_nodes_(LAMURE_DEFAULT_VIDEO_MEMORY_BUDGET) { } gpu_context:: ~gpu_context() { temporary_storages_ = temporary_storages(nullptr, nullptr); temporary_storages_provenance_ = temporary_storages(nullptr, nullptr); if (temp_buffer_a_) { delete temp_buffer_a_; temp_buffer_a_ = nullptr; } if (temp_buffer_b_) { delete temp_buffer_b_; temp_buffer_b_ = nullptr; } if (primary_buffer_) { delete primary_buffer_; primary_buffer_ = nullptr; } } void gpu_context:: create(scm::gl::render_device_ptr device) { assert(device); if (is_created_) { return; } is_created_ = true; test_video_memory(device); model_database* database = model_database::get_instance(); temp_buffer_a_ = new gpu_access(device, upload_budget_in_nodes_, database->get_primitives_per_node(), false); temp_buffer_b_ = new gpu_access(device, upload_budget_in_nodes_, database->get_primitives_per_node(), false); primary_buffer_ = new gpu_access(device, render_budget_in_nodes_, database->get_primitives_per_node(), true); map_temporary_storage(cut_database_record::temporary_buffer::BUFFER_A, device); map_temporary_storage(cut_database_record::temporary_buffer::BUFFER_B, device); } void gpu_context:: test_video_memory(scm::gl::render_device_ptr device) { model_database* database = model_database::get_instance(); policy* policy = policy::get_instance(); float safety = 0.75; size_t video_ram_free_in_mb = gpu_access::query_video_memory_in_mb(device) * safety; size_t render_budget_in_mb = policy->render_budget_in_mb(); if(policy->out_of_core_budget_in_mb() == 0) { std::cout << "##### Total free video memory (" << video_ram_free_in_mb << " MB) will be used for the render budget #####" << std::endl; render_budget_in_mb = video_ram_free_in_mb; } else if(video_ram_free_in_mb < render_budget_in_mb) { std::cout << "##### The specified render budget is too large! " << video_ram_free_in_mb << " MB will be used for the render budget #####" << std::endl; render_budget_in_mb = video_ram_free_in_mb; } else { std::cout << "##### " << policy->render_budget_in_mb() << " MB will be used for the render budget #####" << std::endl; } long node_size_total = database->get_primitives_per_node() * sizeof(provenance_data) + database->get_slot_size(); render_budget_in_nodes_ = (render_budget_in_mb * 1024 * 1024) / node_size_total; // render_budget_in_mb = policy->render_budget_in_mb(); // // render_budget_in_mb = render_budget_in_mb < LAMURE_MIN_VIDEO_MEMORY_BUDGET ? LAMURE_MIN_VIDEO_MEMORY_BUDGET : render_budget_in_mb; // render_budget_in_mb = render_budget_in_mb > video_ram_free_in_mb * 0.75 ? video_ram_free_in_mb * 0.75 : render_budget_in_mb; // render_budget_in_nodes_ = (render_budget_in_mb * 1024u * 1024u) / (database->get_primitives_per_node() * sizeof(provenance_data) + database->get_slot_size()); // std::cout << "RENDER2: " << render_budget_in_nodes_ << std::endl; size_t max_upload_budget_in_mb = policy->max_upload_budget_in_mb(); max_upload_budget_in_mb = max_upload_budget_in_mb < LAMURE_MIN_UPLOAD_BUDGET ? LAMURE_MIN_UPLOAD_BUDGET : max_upload_budget_in_mb; max_upload_budget_in_mb = max_upload_budget_in_mb > video_ram_free_in_mb * 0.125 ? video_ram_free_in_mb * 0.125 : max_upload_budget_in_mb; upload_budget_in_nodes_ = (max_upload_budget_in_mb * 1024u * 1024u) / node_size_total; #if 1 // upload_budget_in_nodes_ = max_upload_budget_in_nodes/4; #else gpu_access* test_temp = new gpu_access(device, 1, database->surfels_per_node(), false); gpu_access* test_main = new gpu_access(device, 1, database->surfels_per_node(), true); LodPointCloud::serializedsurfel* node_data = (LodPointCloud::serializedsurfel*)new char[size_of_node_in_bytes]; memset((char*)node_data, 0, size_of_node_in_bytes); char* mapped_temp = test_temp->map(device); memcpy(mapped_temp, node_data, size_of_node_in_bytes); test_temp->unmap(device); auto frame_duration_in_ns = boost::timer::nanosecond_type(16.0 * 1000 * 1000); boost::timer::cpu_timer upload_timer; unsigned int iteration = 0; while (true) { upload_timer.start(); for (unsigned int i = 0; i < upload_budget_in_nodes_; ++i) { size_t offset_in_temp_VBO = 0; size_t offset_in_render_VBO = 0; device->main_context()->copy_buffer_data(test_main->buffer(), test_temp->buffer(), offset_in_render_VBO, offset_in_temp_VBO, size_of_node_in_bytes); } upload_timer.stop(); boost::timer::cpu_times const elapsed(upload_timer.elapsed()); boost::timer::nanosecond_type const elapsed_ns(elapsed.system + elapsed.user); if (iteration++ > 1) { if (elapsed_ns < frame_duration_in_ns) { if (upload_budget_in_nodes_ < max_upload_budget_in_nodes) { ++upload_budget_in_nodes_; } else { break; } } else { break; } } } delete test_temp; delete test_main; delete[] node_data; device->main_context()->apply(); #endif #ifdef LAMURE_ENABLE_INFO std::cout << "lamure: context " << context_id_ << " render budget (MB): " << render_budget_in_mb << std::endl; std::cout << "lamure: context " << context_id_ << " upload budget (MB): " << max_upload_budget_in_mb << std::endl; #endif } scm::gl::buffer_ptr gpu_context:: get_context_buffer(scm::gl::render_device_ptr device) { if (!is_created_) create(device); assert(device); return primary_buffer_->get_buffer(); } scm::gl::vertex_array_ptr gpu_context:: get_context_memory(bvh::primitive_type type, scm::gl::render_device_ptr device) { if (!is_created_) create(device); assert(device); return primary_buffer_->get_memory(type); } void gpu_context:: map_temporary_storage(const cut_database_record::temporary_buffer& buffer, scm::gl::render_device_ptr device) { if (!is_created_) create(device); assert(device); switch (buffer) { case cut_database_record::temporary_buffer::BUFFER_A: if (!temp_buffer_a_->is_mapped()) { temporary_storages_.storage_a_ = temp_buffer_a_->map(device); temporary_storages_provenance_.storage_a_ = temp_buffer_a_->map_provenance(device); } return; break; case cut_database_record::temporary_buffer::BUFFER_B: if (!temp_buffer_b_->is_mapped()) { temporary_storages_.storage_b_ = temp_buffer_b_->map(device); temporary_storages_provenance_.storage_b_ = temp_buffer_b_->map_provenance(device); } return; break; default: break; } throw std::runtime_error( "lamure: Failed to map temporary buffer on context: " + context_id_); } void gpu_context:: unmap_temporary_storage(const cut_database_record::temporary_buffer& buffer, scm::gl::render_device_ptr device) { if (!is_created_) create(device); assert(device); switch (buffer) { case cut_database_record::temporary_buffer::BUFFER_A: if (temp_buffer_a_->is_mapped()) { temp_buffer_a_->unmap(device); temp_buffer_a_->unmap_provenance(device); } break; case cut_database_record::temporary_buffer::BUFFER_B: if (temp_buffer_b_->is_mapped()) { temp_buffer_b_->unmap(device); temp_buffer_b_->unmap_provenance(device); } break; default: break; } } //returns true if any node has been uploaded; false otherwise bool gpu_context:: update_primary_buffer(const cut_database_record::temporary_buffer& from_buffer, scm::gl::render_device_ptr device) { if (!is_created_) create(device); assert(device); model_database* database = model_database::get_instance(); cut_database* cuts = cut_database::get_instance(); size_t uploaded_nodes = 0; switch (from_buffer) { case cut_database_record::temporary_buffer::BUFFER_A: { if (temp_buffer_a_->is_mapped()) { throw std::runtime_error( "lamure: gpu_context::Failed to transfer nodes into main memory on context: " + context_id_); } std::vector<cut_database_record::slot_update_desc>& transfer_descr_list = cuts->get_updated_set(context_id_); if (!transfer_descr_list.empty()) { uploaded_nodes += transfer_descr_list.size(); for (const auto& transfer_desc : transfer_descr_list) { size_t offset_in_temp_VBO = transfer_desc.src_ * database->get_slot_size(); size_t offset_in_render_VBO = transfer_desc.dst_ * database->get_slot_size(); device->main_context()->copy_buffer_data( primary_buffer_->get_buffer(), temp_buffer_a_->get_buffer(), offset_in_render_VBO, offset_in_temp_VBO, database->get_slot_size() ); size_t offset_in_temp_VBO_provenance = transfer_desc.src_ * database->get_primitives_per_node() * sizeof(provenance_data); size_t offset_in_render_VBO_provenance = transfer_desc.dst_ * database->get_primitives_per_node() * sizeof(provenance_data); device->main_context()->copy_buffer_data( primary_buffer_->get_buffer_provenance(), temp_buffer_a_->get_buffer_provenance(), offset_in_render_VBO_provenance, offset_in_temp_VBO_provenance, database->get_primitives_per_node() * sizeof(provenance_data) ); } } break; } case cut_database_record::temporary_buffer::BUFFER_B: { if (temp_buffer_b_->is_mapped()) { throw std::runtime_error( "lamure: gpu_context::Failed to transfer nodes into main memory on context: " + context_id_); } std::vector<cut_database_record::slot_update_desc>& transfer_descr_list = cuts->get_updated_set(context_id_); if (!transfer_descr_list.empty()) { uploaded_nodes += transfer_descr_list.size(); for (const auto& transfer_desc : transfer_descr_list) { size_t offset_in_temp_VBO = transfer_desc.src_ * database->get_slot_size(); size_t offset_in_render_VBO = transfer_desc.dst_ * database->get_slot_size(); device->main_context()->copy_buffer_data( primary_buffer_->get_buffer(), temp_buffer_b_->get_buffer(), offset_in_render_VBO, offset_in_temp_VBO, database->get_slot_size() ); size_t offset_in_temp_VBO_provenance = transfer_desc.src_ * database->get_primitives_per_node() * sizeof(provenance_data); size_t offset_in_render_VBO_provenance = transfer_desc.dst_ * database->get_primitives_per_node() * sizeof(provenance_data); device->main_context()->copy_buffer_data( primary_buffer_->get_buffer_provenance(), temp_buffer_b_->get_buffer_provenance(), offset_in_render_VBO_provenance, offset_in_temp_VBO_provenance, database->get_primitives_per_node() * sizeof(provenance_data) ); } } break; } default: break; } return uploaded_nodes != 0; } } } <|endoftext|>
<commit_before>#include "libtorrent/session.hpp" #include "libtorrent/session_settings.hpp" #include "libtorrent/hasher.hpp" #include <boost/thread.hpp> #include <boost/tuple/tuple.hpp> #include <boost/filesystem/operations.hpp> #include "test.hpp" #include "setup_transfer.hpp" using boost::filesystem::remove_all; void test_swarm() { using namespace libtorrent; session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48000, 49000)); session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49000, 50000)); session ses3(fingerprint("LT", 0, 1, 0, 0), std::make_pair(50000, 51000)); // this is to avoid everything finish from a single peer // immediately. To make the swarm actually connect all // three peers before finishing. float rate_limit = 40000; ses1.set_upload_rate_limit(int(rate_limit)); ses2.set_download_rate_limit(int(rate_limit)); ses3.set_download_rate_limit(int(rate_limit)); ses2.set_upload_rate_limit(int(rate_limit / 2)); ses3.set_upload_rate_limit(int(rate_limit / 2)); session_settings settings; settings.allow_multiple_connections_per_ip = true; ses1.set_settings(settings); ses2.set_settings(settings); ses3.set_settings(settings); #ifndef TORRENT_DISABLE_ENCRYPTION pe_settings pes; pes.out_enc_policy = pe_settings::disabled; pes.in_enc_policy = pe_settings::disabled; ses1.set_pe_settings(pes); ses2.set_pe_settings(pes); ses3.set_pe_settings(pes); #endif torrent_handle tor1; torrent_handle tor2; torrent_handle tor3; boost::tie(tor1, tor2, tor3) = setup_transfer(&ses1, &ses2, &ses3, true, false); float sum_dl_rate2 = 0.f; float sum_dl_rate3 = 0.f; int count_dl_rates2 = 0; int count_dl_rates3 = 0; for (int i = 0; i < 65; ++i) { std::auto_ptr<alert> a; a = ses1.pop_alert(); if (a.get()) std::cerr << "ses1: " << a->msg() << "\n"; a = ses2.pop_alert(); if (a.get()) std::cerr << "ses2: " << a->msg() << "\n"; a = ses3.pop_alert(); if (a.get()) std::cerr << "ses3: " << a->msg() << "\n"; torrent_status st1 = tor1.status(); torrent_status st2 = tor2.status(); torrent_status st3 = tor3.status(); if (st2.progress < 1.f && st2.progress > 0.3f) { sum_dl_rate2 += st2.download_payload_rate; ++count_dl_rates2; } if (st3.progress < 1.f && st3.progress > 0.3f) { sum_dl_rate3 += st3.download_rate; ++count_dl_rates3; } std::cerr << "\033[33m" << int(st1.upload_payload_rate / 1000.f) << "kB/s: " << "\033[32m" << int(st2.download_payload_rate / 1000.f) << "kB/s " << "\033[31m" << int(st2.upload_payload_rate / 1000.f) << "kB/s " << "\033[0m" << int(st2.progress * 100) << "% - " << "\033[32m" << int(st3.download_payload_rate / 1000.f) << "kB/s " << "\033[31m" << int(st3.upload_payload_rate / 1000.f) << "kB/s " << "\033[0m" << int(st3.progress * 100) << "% " << std::endl; if (tor2.is_seed() && tor3.is_seed()) break; test_sleep(1000); } TEST_CHECK(tor2.is_seed()); TEST_CHECK(tor3.is_seed()); float average2 = sum_dl_rate2 / float(count_dl_rates2); float average3 = sum_dl_rate3 / float(count_dl_rates3); std::cerr << "average rate: " << (average2 / 1000.f) << "kB/s - " << (average3 / 1000.f) << "kB/s" << std::endl; TEST_CHECK(std::fabs(average2 - float(rate_limit)) < 3000.f); TEST_CHECK(std::fabs(average3 - float(rate_limit)) < 3000.f); if (tor2.is_seed() && tor3.is_seed()) std::cerr << "done\n"; } int test_main() { using namespace libtorrent; using namespace boost::filesystem; // in case the previous run was terminated try { remove_all("./tmp1"); } catch (std::exception&) {} try { remove_all("./tmp2"); } catch (std::exception&) {} try { remove_all("./tmp3"); } catch (std::exception&) {} test_swarm(); remove_all("./tmp1"); remove_all("./tmp2"); remove_all("./tmp3"); return 0; } <commit_msg>more output in test_swarm<commit_after>#include "libtorrent/session.hpp" #include "libtorrent/session_settings.hpp" #include "libtorrent/hasher.hpp" #include <boost/thread.hpp> #include <boost/tuple/tuple.hpp> #include <boost/filesystem/operations.hpp> #include "test.hpp" #include "setup_transfer.hpp" using boost::filesystem::remove_all; void test_swarm() { using namespace libtorrent; session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48000, 49000)); session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49000, 50000)); session ses3(fingerprint("LT", 0, 1, 0, 0), std::make_pair(50000, 51000)); // this is to avoid everything finish from a single peer // immediately. To make the swarm actually connect all // three peers before finishing. float rate_limit = 40000; ses1.set_upload_rate_limit(int(rate_limit)); ses2.set_download_rate_limit(int(rate_limit)); ses3.set_download_rate_limit(int(rate_limit)); ses2.set_upload_rate_limit(int(rate_limit / 2)); ses3.set_upload_rate_limit(int(rate_limit / 2)); session_settings settings; settings.allow_multiple_connections_per_ip = true; ses1.set_settings(settings); ses2.set_settings(settings); ses3.set_settings(settings); #ifndef TORRENT_DISABLE_ENCRYPTION pe_settings pes; pes.out_enc_policy = pe_settings::disabled; pes.in_enc_policy = pe_settings::disabled; ses1.set_pe_settings(pes); ses2.set_pe_settings(pes); ses3.set_pe_settings(pes); #endif torrent_handle tor1; torrent_handle tor2; torrent_handle tor3; boost::tie(tor1, tor2, tor3) = setup_transfer(&ses1, &ses2, &ses3, true, false); float sum_dl_rate2 = 0.f; float sum_dl_rate3 = 0.f; int count_dl_rates2 = 0; int count_dl_rates3 = 0; for (int i = 0; i < 65; ++i) { std::auto_ptr<alert> a; a = ses1.pop_alert(); if (a.get()) std::cerr << "ses1: " << a->msg() << "\n"; a = ses2.pop_alert(); if (a.get()) std::cerr << "ses2: " << a->msg() << "\n"; a = ses3.pop_alert(); if (a.get()) std::cerr << "ses3: " << a->msg() << "\n"; torrent_status st1 = tor1.status(); torrent_status st2 = tor2.status(); torrent_status st3 = tor3.status(); if (st2.progress < 1.f && st2.progress > 0.3f) { sum_dl_rate2 += st2.download_payload_rate; ++count_dl_rates2; } if (st3.progress < 1.f && st3.progress > 0.3f) { sum_dl_rate3 += st3.download_rate; ++count_dl_rates3; } std::cerr << "\033[33m" << int(st1.upload_payload_rate / 1000.f) << "kB/s " << st1.num_peers << ": " << "\033[32m" << int(st2.download_payload_rate / 1000.f) << "kB/s " << "\033[31m" << int(st2.upload_payload_rate / 1000.f) << "kB/s " << "\033[0m" << int(st2.progress * 100) << "% " << st2.num_peers << " - " << "\033[32m" << int(st3.download_payload_rate / 1000.f) << "kB/s " << "\033[31m" << int(st3.upload_payload_rate / 1000.f) << "kB/s " << "\033[0m" << int(st3.progress * 100) << "% " << st3.num_peers << std::endl; if (tor2.is_seed() && tor3.is_seed()) break; test_sleep(1000); } TEST_CHECK(tor2.is_seed()); TEST_CHECK(tor3.is_seed()); float average2 = sum_dl_rate2 / float(count_dl_rates2); float average3 = sum_dl_rate3 / float(count_dl_rates3); std::cerr << "average rate: " << (average2 / 1000.f) << "kB/s - " << (average3 / 1000.f) << "kB/s" << std::endl; TEST_CHECK(std::fabs(average2 - float(rate_limit)) < 3000.f); TEST_CHECK(std::fabs(average3 - float(rate_limit)) < 3000.f); if (tor2.is_seed() && tor3.is_seed()) std::cerr << "done\n"; } int test_main() { using namespace libtorrent; using namespace boost::filesystem; // in case the previous run was terminated try { remove_all("./tmp1"); } catch (std::exception&) {} try { remove_all("./tmp2"); } catch (std::exception&) {} try { remove_all("./tmp3"); } catch (std::exception&) {} test_swarm(); remove_all("./tmp1"); remove_all("./tmp2"); remove_all("./tmp3"); return 0; } <|endoftext|>
<commit_before>/* Copyright (c) 2008, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/session.hpp" #include "libtorrent/session_settings.hpp" #include "libtorrent/hasher.hpp" #include "libtorrent/alert_types.hpp" #include <boost/thread.hpp> #include <boost/tuple/tuple.hpp> #include <boost/filesystem/operations.hpp> #include "test.hpp" #include "setup_transfer.hpp" using boost::filesystem::remove_all; using boost::filesystem::exists; void test_swarm() { using namespace libtorrent; session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48000, 49000)); session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49000, 50000)); session ses3(fingerprint("LT", 0, 1, 0, 0), std::make_pair(50000, 51000)); // this is to avoid everything finish from a single peer // immediately. To make the swarm actually connect all // three peers before finishing. float rate_limit = 100000; ses1.set_upload_rate_limit(int(rate_limit)); ses2.set_download_rate_limit(int(rate_limit)); ses3.set_download_rate_limit(int(rate_limit)); ses2.set_upload_rate_limit(int(rate_limit / 2)); ses3.set_upload_rate_limit(int(rate_limit / 2)); session_settings settings; settings.allow_multiple_connections_per_ip = true; settings.ignore_limits_on_local_network = false; ses1.set_settings(settings); ses2.set_settings(settings); ses3.set_settings(settings); #ifndef TORRENT_DISABLE_ENCRYPTION pe_settings pes; pes.out_enc_policy = pe_settings::forced; pes.in_enc_policy = pe_settings::forced; ses1.set_pe_settings(pes); ses2.set_pe_settings(pes); ses3.set_pe_settings(pes); #endif torrent_handle tor1; torrent_handle tor2; torrent_handle tor3; // test using piece sizes smaller than 16kB boost::tie(tor1, tor2, tor3) = setup_transfer(&ses1, &ses2, &ses3, true, false, true, "_swarm", 8 * 1024); ses1.set_alert_mask(alert::all_categories & ~alert::progress_notification); ses2.set_alert_mask(alert::all_categories & ~alert::progress_notification); ses3.set_alert_mask(alert::all_categories & ~alert::progress_notification); float sum_dl_rate2 = 0.f; float sum_dl_rate3 = 0.f; int count_dl_rates2 = 0; int count_dl_rates3 = 0; for (int i = 0; i < 30; ++i) { print_alerts(ses1, "ses1"); print_alerts(ses2, "ses2"); print_alerts(ses3, "ses3"); torrent_status st1 = tor1.status(); torrent_status st2 = tor2.status(); torrent_status st3 = tor3.status(); if (st2.progress < 1.f && st2.progress > 0.5f) { sum_dl_rate2 += st2.download_payload_rate; ++count_dl_rates2; } if (st3.progress < 1.f && st3.progress > 0.5f) { sum_dl_rate3 += st3.download_rate; ++count_dl_rates3; } std::cerr << "\033[33m" << int(st1.upload_payload_rate / 1000.f) << "kB/s " << st1.num_peers << ": " << "\033[32m" << int(st2.download_payload_rate / 1000.f) << "kB/s " << "\033[31m" << int(st2.upload_payload_rate / 1000.f) << "kB/s " << "\033[0m" << int(st2.progress * 100) << "% " << st2.num_peers << " - " << "\033[32m" << int(st3.download_payload_rate / 1000.f) << "kB/s " << "\033[31m" << int(st3.upload_payload_rate / 1000.f) << "kB/s " << "\033[0m" << int(st3.progress * 100) << "% " << st3.num_peers << std::endl; if (tor2.is_seed() && tor3.is_seed()) break; test_sleep(1000); } TEST_CHECK(tor2.is_seed()); TEST_CHECK(tor3.is_seed()); float average2 = sum_dl_rate2 / float(count_dl_rates2); float average3 = sum_dl_rate3 / float(count_dl_rates3); std::cerr << average2 << std::endl; std::cerr << "average rate: " << (average2 / 1000.f) << "kB/s - " << (average3 / 1000.f) << "kB/s" << std::endl; TEST_CHECK(std::fabs(average2 - float(rate_limit)) < rate_limit / 11.f); TEST_CHECK(std::fabs(average3 - float(rate_limit)) < rate_limit / 11.f); if (tor2.is_seed() && tor3.is_seed()) std::cerr << "done\n"; // make sure the files are deleted ses1.remove_torrent(tor1, session::delete_files); ses2.remove_torrent(tor2, session::delete_files); ses3.remove_torrent(tor3, session::delete_files); std::auto_ptr<alert> a = ses1.pop_alert(); ptime end = time_now() + seconds(20); while (a.get() == 0 || dynamic_cast<torrent_deleted_alert*>(a.get()) == 0) { if (ses1.wait_for_alert(end - time_now()) == 0) { std::cerr << "wait_for_alert() expired" << std::endl; break; } a = ses1.pop_alert(); assert(a.get()); std::cerr << a->message() << std::endl; } TEST_CHECK(dynamic_cast<torrent_deleted_alert*>(a.get()) != 0); // there shouldn't be any alerts generated from now on // make sure that the timer in wait_for_alert() works // this should time out (ret == 0) and it should take // about 2 seconds ptime start = time_now(); alert const* ret = ses1.wait_for_alert(seconds(2)); TEST_CHECK(ret == 0); if (ret != 0) std::cerr << ret->message() << std::endl; TEST_CHECK(time_now() - start < seconds(3)); TEST_CHECK(time_now() - start > seconds(2)); } int test_main() { using namespace libtorrent; using namespace boost::filesystem; // in case the previous run was terminated try { remove_all("./tmp1_swarm"); } catch (std::exception&) {} try { remove_all("./tmp2_swarm"); } catch (std::exception&) {} try { remove_all("./tmp3_swarm"); } catch (std::exception&) {} test_swarm(); test_sleep(2000); TEST_CHECK(!exists("./tmp1_swarm/temporary")); TEST_CHECK(!exists("./tmp2_swarm/temporary")); TEST_CHECK(!exists("./tmp3_swarm/temporary")); remove_all("./tmp1_swarm"); remove_all("./tmp2_swarm"); remove_all("./tmp3_swarm"); return 0; } <commit_msg>fixed test_swarm<commit_after>/* Copyright (c) 2008, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "libtorrent/session.hpp" #include "libtorrent/session_settings.hpp" #include "libtorrent/hasher.hpp" #include "libtorrent/alert_types.hpp" #include <boost/thread.hpp> #include <boost/tuple/tuple.hpp> #include <boost/filesystem/operations.hpp> #include "test.hpp" #include "setup_transfer.hpp" using boost::filesystem::remove_all; using boost::filesystem::exists; void test_swarm() { using namespace libtorrent; session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48000, 49000)); session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49000, 50000)); session ses3(fingerprint("LT", 0, 1, 0, 0), std::make_pair(50000, 51000)); // this is to avoid everything finish from a single peer // immediately. To make the swarm actually connect all // three peers before finishing. float rate_limit = 100000; ses1.set_upload_rate_limit(int(rate_limit)); ses2.set_download_rate_limit(int(rate_limit)); ses3.set_download_rate_limit(int(rate_limit)); ses2.set_upload_rate_limit(int(rate_limit / 2)); ses3.set_upload_rate_limit(int(rate_limit / 2)); session_settings settings; settings.allow_multiple_connections_per_ip = true; settings.ignore_limits_on_local_network = false; ses1.set_settings(settings); ses2.set_settings(settings); ses3.set_settings(settings); #ifndef TORRENT_DISABLE_ENCRYPTION pe_settings pes; pes.out_enc_policy = pe_settings::forced; pes.in_enc_policy = pe_settings::forced; ses1.set_pe_settings(pes); ses2.set_pe_settings(pes); ses3.set_pe_settings(pes); #endif torrent_handle tor1; torrent_handle tor2; torrent_handle tor3; // test using piece sizes smaller than 16kB boost::tie(tor1, tor2, tor3) = setup_transfer(&ses1, &ses2, &ses3, true, false, true, "_swarm", 8 * 1024); ses1.set_alert_mask(alert::all_categories & ~alert::progress_notification); ses2.set_alert_mask(alert::all_categories & ~alert::progress_notification); ses3.set_alert_mask(alert::all_categories & ~alert::progress_notification); float sum_dl_rate2 = 0.f; float sum_dl_rate3 = 0.f; int count_dl_rates2 = 0; int count_dl_rates3 = 0; for (int i = 0; i < 30; ++i) { print_alerts(ses1, "ses1"); print_alerts(ses2, "ses2"); print_alerts(ses3, "ses3"); torrent_status st1 = tor1.status(); torrent_status st2 = tor2.status(); torrent_status st3 = tor3.status(); if (st2.progress < 1.f && st2.progress > 0.5f) { sum_dl_rate2 += st2.download_payload_rate; ++count_dl_rates2; } if (st3.progress < 1.f && st3.progress > 0.5f) { sum_dl_rate3 += st3.download_rate; ++count_dl_rates3; } std::cerr << "\033[33m" << int(st1.upload_payload_rate / 1000.f) << "kB/s " << st1.num_peers << ": " << "\033[32m" << int(st2.download_payload_rate / 1000.f) << "kB/s " << "\033[31m" << int(st2.upload_payload_rate / 1000.f) << "kB/s " << "\033[0m" << int(st2.progress * 100) << "% " << st2.num_peers << " - " << "\033[32m" << int(st3.download_payload_rate / 1000.f) << "kB/s " << "\033[31m" << int(st3.upload_payload_rate / 1000.f) << "kB/s " << "\033[0m" << int(st3.progress * 100) << "% " << st3.num_peers << std::endl; if (tor2.is_seed() && tor3.is_seed()) break; test_sleep(1000); } TEST_CHECK(tor2.is_seed()); TEST_CHECK(tor3.is_seed()); float average2 = sum_dl_rate2 / float(count_dl_rates2); float average3 = sum_dl_rate3 / float(count_dl_rates3); std::cerr << average2 << std::endl; std::cerr << "average rate: " << (average2 / 1000.f) << "kB/s - " << (average3 / 1000.f) << "kB/s" << std::endl; TEST_CHECK(std::fabs(average2 - float(rate_limit)) < rate_limit / 11.f); TEST_CHECK(std::fabs(average3 - float(rate_limit)) < rate_limit / 11.f); if (tor2.is_seed() && tor3.is_seed()) std::cerr << "done\n"; // make sure the files are deleted ses1.remove_torrent(tor1, session::delete_files); ses2.remove_torrent(tor2, session::delete_files); ses3.remove_torrent(tor3, session::delete_files); std::auto_ptr<alert> a = ses1.pop_alert(); ptime end = time_now() + seconds(20); while (a.get() == 0 || dynamic_cast<torrent_deleted_alert*>(a.get()) == 0) { if (ses1.wait_for_alert(end - time_now()) == 0) { std::cerr << "wait_for_alert() expired" << std::endl; break; } a = ses1.pop_alert(); assert(a.get()); std::cerr << a->message() << std::endl; } TEST_CHECK(dynamic_cast<torrent_deleted_alert*>(a.get()) != 0); // there shouldn't be any alerts generated from now on // make sure that the timer in wait_for_alert() works // this should time out (ret == 0) and it should take // about 2 seconds ptime start = time_now(); alert const* ret; while (ret = ses1.wait_for_alert(seconds(2))) { a = ses1.pop_alert(); std::cerr << ret->message() << std::endl; start = time_now(); } TEST_CHECK(time_now() - start < seconds(3)); TEST_CHECK(time_now() - start >= seconds(2)); } int test_main() { using namespace libtorrent; using namespace boost::filesystem; // in case the previous run was terminated try { remove_all("./tmp1_swarm"); } catch (std::exception&) {} try { remove_all("./tmp2_swarm"); } catch (std::exception&) {} try { remove_all("./tmp3_swarm"); } catch (std::exception&) {} test_swarm(); test_sleep(2000); TEST_CHECK(!exists("./tmp1_swarm/temporary")); TEST_CHECK(!exists("./tmp2_swarm/temporary")); TEST_CHECK(!exists("./tmp3_swarm/temporary")); remove_all("./tmp1_swarm"); remove_all("./tmp2_swarm"); remove_all("./tmp3_swarm"); return 0; } <|endoftext|>
<commit_before>#include "animation_system.h" #include "animation/animation.h" #include "engine/base_proxy_allocator.h" #include "engine/blob.h" #include "engine/crc32.h" #include "engine/engine.h" #include "engine/json_serializer.h" #include "engine/lua_wrapper.h" #include "engine/profiler.h" #include "engine/property_descriptor.h" #include "engine/property_register.h" #include "engine/resource_manager.h" #include "engine/universe/universe.h" #include "renderer/model.h" #include "renderer/pose.h" #include "renderer/render_scene.h" #include <cfloat> namespace Lumix { static const ComponentType ANIMABLE_TYPE = PropertyRegister::getComponentType("animable"); static const ResourceType ANIMATION_TYPE("animation"); namespace FS { class FileSystem; }; class Animation; class Engine; class JsonSerializer; class Universe; enum class AnimationSceneVersion : int { FIRST, REFACTOR, LATEST }; struct AnimationSceneImpl : public AnimationScene { friend struct AnimationSystemImpl; struct Animable { float time; float time_scale; float start_time; Animation* animation; Entity entity; }; struct Mixer { struct Input { Animation* animation = nullptr; float time = 0.0f; float weight = 0.0f; }; Input inputs[8]; Entity entity; }; AnimationSceneImpl(IPlugin& anim_system, Engine& engine, Universe& universe, IAllocator& allocator) : m_universe(universe) , m_engine(engine) , m_anim_system(anim_system) , m_animables(allocator) , m_mixers(allocator) { m_universe.entityDestroyed().bind<AnimationSceneImpl, &AnimationSceneImpl::onEntityDestroyed>(this); m_is_game_running = false; m_render_scene = static_cast<RenderScene*>(universe.getScene(crc32("renderer"))); universe.registerComponentTypeScene(ANIMABLE_TYPE, this); ASSERT(m_render_scene); } ~AnimationSceneImpl() { m_universe.entityDestroyed().unbind<AnimationSceneImpl, &AnimationSceneImpl::onEntityDestroyed>(this); } void onEntityDestroyed(Entity entity) { m_mixers.erase(entity); } void clear() override { for (Mixer& mixer : m_mixers) { for (auto& input : mixer.inputs) { unloadAnimation(input.animation); } } m_mixers.clear(); for (Animable& animable : m_animables) { unloadAnimation(animable.animation); } m_animables.clear(); } float getAnimationLength(int animation_idx) { auto* animation = static_cast<Animation*>(animation_idx > 0 ? m_engine.getLuaResource(animation_idx) : nullptr); if (animation) return animation->getLength(); return 0; } void mixAnimation(Entity entity, int animation_idx, int input_idx, float time, float weight) { auto* animation = static_cast<Animation*>(animation_idx > 0 ? m_engine.getLuaResource(animation_idx) : nullptr); int mixer_idx = m_mixers.find(entity); if (mixer_idx < 0) { Mixer& mixer = m_mixers.insert(entity); mixer.entity = entity; mixer_idx = m_mixers.find(entity); } Mixer& mixer = m_mixers.at(mixer_idx); auto& input = mixer.inputs[input_idx]; input.animation = animation; input.time = time; input.weight = weight; } float getAnimableTime(ComponentHandle cmp) override { return m_animables[{cmp.index}].time; } void setAnimableTime(ComponentHandle cmp, float time) override { m_animables[{cmp.index}].time = time; } Animation* getAnimableAnimation(ComponentHandle cmp) override { return m_animables[{cmp.index}].animation; } void startGame() override { m_is_game_running = true; } void stopGame() override { m_is_game_running = false; } Universe& getUniverse() override { return m_universe; } ComponentHandle getComponent(Entity entity, ComponentType type) override { if (type == ANIMABLE_TYPE) { if (m_animables.find(entity) < 0) return INVALID_COMPONENT; return {entity.index}; } return INVALID_COMPONENT; } ComponentHandle createComponent(ComponentType type, Entity entity) override { if (type == ANIMABLE_TYPE) return createAnimable(entity); return INVALID_COMPONENT; } void unloadAnimation(Animation* animation) { if (!animation) return; animation->getResourceManager().unload(*animation); } void destroyComponent(ComponentHandle component, ComponentType type) override { if (type == ANIMABLE_TYPE) { Entity entity = {component.index}; auto& animable = m_animables[entity]; unloadAnimation(animable.animation); m_animables.erase(entity); m_universe.destroyComponent(entity, type, this, component); } } void serialize(OutputBlob& serializer) override { serializer.write((int32)m_animables.size()); for (const Animable& animable : m_animables) { serializer.write(animable.entity); serializer.write(animable.time_scale); serializer.write(animable.start_time); serializer.writeString(animable.animation ? animable.animation->getPath().c_str() : ""); } } int getVersion() const override { return (int)AnimationSceneVersion::LATEST; } void deserialize(InputBlob& serializer, int version) override { int32 count; serializer.read(count); m_animables.reserve(count); for (int i = 0; i < count; ++i) { Animable animable; serializer.read(animable.entity); bool free = false; if (version <= (int)AnimationSceneVersion::FIRST) { serializer.read(animable.time); serializer.read(free); animable.time_scale = 1; animable.start_time = 0; } else { uint32 flags = 0; if(version <= (int)AnimationSceneVersion::REFACTOR) serializer.read(flags); free = flags != 0; serializer.read(animable.time_scale); serializer.read(animable.start_time); animable.time = animable.start_time; } char path[MAX_PATH_LENGTH]; serializer.readString(path, sizeof(path)); animable.animation = path[0] == '\0' ? nullptr : loadAnimation(Path(path)); if (!free) { m_animables.insert(animable.entity, animable); ComponentHandle cmp = {animable.entity.index}; m_universe.addComponent(animable.entity, ANIMABLE_TYPE, this, cmp); } } } float getTimeScale(ComponentHandle cmp) { return m_animables[{cmp.index}].time_scale; } void setTimeScale(ComponentHandle cmp, float time_scale) { m_animables[{cmp.index}].time_scale = time_scale; } float getStartTime(ComponentHandle cmp) { return m_animables[{cmp.index}].start_time; } void setStartTime(ComponentHandle cmp, float time) { m_animables[{cmp.index}].start_time = time; } Path getAnimation(ComponentHandle cmp) { const auto& animable = m_animables[{cmp.index}]; return animable.animation ? animable.animation->getPath() : Path(""); } void setAnimation(ComponentHandle cmp, const Path& path) { auto& animable = m_animables[{cmp.index}]; unloadAnimation(animable.animation); animable.animation = loadAnimation(path); animable.time = 0; } void updateMixer(Mixer& mixer, float time_delta) { ComponentHandle renderable = m_render_scene->getRenderableComponent(mixer.entity); if (renderable == INVALID_COMPONENT) return; auto* pose = m_render_scene->getPose(renderable); auto* model = m_render_scene->getRenderableModel(renderable); if (!pose) return; if (!model->isReady()) return; model->getPose(*pose); pose->computeRelative(*model); for (int i = 0; i < lengthOf(mixer.inputs); ++i) { Mixer::Input& input = mixer.inputs[i]; if (!input.animation) break; ASSERT(input.animation->isReady()); if (i == 0) { input.animation->getRelativePose(input.time, *pose, *model); } else { input.animation->getRelativePose(input.time, *pose, *model, input.weight); } input.animation = nullptr; } pose->computeAbsolute(*model); } void updateAnimable(Animable& animable, float time_delta) { if (!animable.animation || !animable.animation->isReady()) return; ComponentHandle renderable = m_render_scene->getRenderableComponent(animable.entity); if (renderable == INVALID_COMPONENT) return; auto* pose = m_render_scene->getPose(renderable); auto* model = m_render_scene->getRenderableModel(renderable); if (!pose) return; if (!model->isReady()) return; model->getPose(*pose); pose->computeRelative(*model); animable.animation->getRelativePose(animable.time, *pose, *model); pose->computeAbsolute(*model); float t = animable.time + time_delta * animable.time_scale; float l = animable.animation->getLength(); while (t > l) { t -= l; } animable.time = t; } void updateAnimable(ComponentHandle cmp, float time_delta) override { Animable& animable = m_animables[{cmp.index}]; updateAnimable(animable, time_delta); } void update(float time_delta, bool paused) override { PROFILE_FUNCTION(); if (!m_is_game_running) return; for (Mixer& mixer : m_mixers) { AnimationSceneImpl::updateMixer(mixer, time_delta); } for (Animable& animable : m_animables) { AnimationSceneImpl::updateAnimable(animable, time_delta); } } Animation* loadAnimation(const Path& path) { ResourceManager& rm = m_engine.getResourceManager(); return static_cast<Animation*>(rm.get(ANIMATION_TYPE)->load(path)); } ComponentHandle createAnimable(Entity entity) { Animable& animable = m_animables.insert(entity); animable.time = 0; animable.animation = nullptr; animable.entity = entity; animable.time_scale = 1; animable.start_time = 0; ComponentHandle cmp = {entity.index}; m_universe.addComponent(entity, ANIMABLE_TYPE, this, cmp); return cmp; } IPlugin& getPlugin() const override { return m_anim_system; } Universe& m_universe; IPlugin& m_anim_system; Engine& m_engine; AssociativeArray<Entity, Animable> m_animables; AssociativeArray<Entity, Mixer> m_mixers; RenderScene* m_render_scene; bool m_is_game_running; }; struct AnimationSystemImpl : public IPlugin { explicit AnimationSystemImpl(Engine& engine) : m_allocator(engine.getAllocator()) , m_engine(engine) , animation_manager(m_allocator) { animation_manager.create(ANIMATION_TYPE, m_engine.getResourceManager()); PropertyRegister::add("animable", LUMIX_NEW(m_allocator, ResourcePropertyDescriptor<AnimationSceneImpl>)("Animation", &AnimationSceneImpl::getAnimation, &AnimationSceneImpl::setAnimation, "Animation (*.ani)", ANIMATION_TYPE)); PropertyRegister::add("animable", LUMIX_NEW(m_allocator, DecimalPropertyDescriptor<AnimationSceneImpl>)( "Start time", &AnimationSceneImpl::getStartTime, &AnimationSceneImpl::setStartTime, 0, FLT_MAX, 0.1f)); PropertyRegister::add("animable", LUMIX_NEW(m_allocator, DecimalPropertyDescriptor<AnimationSceneImpl>)( "Time scale", &AnimationSceneImpl::getTimeScale, &AnimationSceneImpl::setTimeScale, 0, FLT_MAX, 0.1f)); registerLuaAPI(); } void registerLuaAPI() { lua_State* L = m_engine.getState(); #define REGISTER_FUNCTION(name) \ do {\ auto f = &LuaWrapper::wrapMethod<AnimationSceneImpl, decltype(&AnimationSceneImpl::name), &AnimationSceneImpl::name>; \ LuaWrapper::createSystemFunction(L, "Animation", #name, f); \ } while(false) \ REGISTER_FUNCTION(mixAnimation); REGISTER_FUNCTION(getAnimationLength); #undef REGISTER_FUNCTION } IScene* createScene(Universe& ctx) override { return LUMIX_NEW(m_allocator, AnimationSceneImpl)(*this, m_engine, ctx, m_allocator); } void destroyScene(IScene* scene) override { LUMIX_DELETE(m_allocator, scene); } const char* getName() const override { return "animation"; } Lumix::IAllocator& m_allocator; Engine& m_engine; AnimationManager animation_manager; private: void operator=(const AnimationSystemImpl&); AnimationSystemImpl(const AnimationSystemImpl&); }; LUMIX_PLUGIN_ENTRY(animation) { return LUMIX_NEW(engine.getAllocator(), AnimationSystemImpl)(engine); } } <commit_msg>fixed crash when mixing animation that does not exist<commit_after>#include "animation_system.h" #include "animation/animation.h" #include "engine/base_proxy_allocator.h" #include "engine/blob.h" #include "engine/crc32.h" #include "engine/engine.h" #include "engine/json_serializer.h" #include "engine/lua_wrapper.h" #include "engine/profiler.h" #include "engine/property_descriptor.h" #include "engine/property_register.h" #include "engine/resource_manager.h" #include "engine/universe/universe.h" #include "renderer/model.h" #include "renderer/pose.h" #include "renderer/render_scene.h" #include <cfloat> namespace Lumix { static const ComponentType ANIMABLE_TYPE = PropertyRegister::getComponentType("animable"); static const ResourceType ANIMATION_TYPE("animation"); namespace FS { class FileSystem; }; class Animation; class Engine; class JsonSerializer; class Universe; enum class AnimationSceneVersion : int { FIRST, REFACTOR, LATEST }; struct AnimationSceneImpl : public AnimationScene { friend struct AnimationSystemImpl; struct Animable { float time; float time_scale; float start_time; Animation* animation; Entity entity; }; struct Mixer { struct Input { Animation* animation = nullptr; float time = 0.0f; float weight = 0.0f; }; Input inputs[8]; Entity entity; }; AnimationSceneImpl(IPlugin& anim_system, Engine& engine, Universe& universe, IAllocator& allocator) : m_universe(universe) , m_engine(engine) , m_anim_system(anim_system) , m_animables(allocator) , m_mixers(allocator) { m_universe.entityDestroyed().bind<AnimationSceneImpl, &AnimationSceneImpl::onEntityDestroyed>(this); m_is_game_running = false; m_render_scene = static_cast<RenderScene*>(universe.getScene(crc32("renderer"))); universe.registerComponentTypeScene(ANIMABLE_TYPE, this); ASSERT(m_render_scene); } ~AnimationSceneImpl() { m_universe.entityDestroyed().unbind<AnimationSceneImpl, &AnimationSceneImpl::onEntityDestroyed>(this); } void onEntityDestroyed(Entity entity) { m_mixers.erase(entity); } void clear() override { for (Mixer& mixer : m_mixers) { for (auto& input : mixer.inputs) { unloadAnimation(input.animation); } } m_mixers.clear(); for (Animable& animable : m_animables) { unloadAnimation(animable.animation); } m_animables.clear(); } float getAnimationLength(int animation_idx) { auto* animation = static_cast<Animation*>(animation_idx > 0 ? m_engine.getLuaResource(animation_idx) : nullptr); if (animation) return animation->getLength(); return 0; } void mixAnimation(Entity entity, int animation_idx, int input_idx, float time, float weight) { auto* animation = static_cast<Animation*>(animation_idx > 0 ? m_engine.getLuaResource(animation_idx) : nullptr); int mixer_idx = m_mixers.find(entity); if (mixer_idx < 0) { Mixer& mixer = m_mixers.insert(entity); mixer.entity = entity; mixer_idx = m_mixers.find(entity); } Mixer& mixer = m_mixers.at(mixer_idx); auto& input = mixer.inputs[input_idx]; input.animation = animation; input.time = time; input.weight = weight; } float getAnimableTime(ComponentHandle cmp) override { return m_animables[{cmp.index}].time; } void setAnimableTime(ComponentHandle cmp, float time) override { m_animables[{cmp.index}].time = time; } Animation* getAnimableAnimation(ComponentHandle cmp) override { return m_animables[{cmp.index}].animation; } void startGame() override { m_is_game_running = true; } void stopGame() override { m_is_game_running = false; } Universe& getUniverse() override { return m_universe; } ComponentHandle getComponent(Entity entity, ComponentType type) override { if (type == ANIMABLE_TYPE) { if (m_animables.find(entity) < 0) return INVALID_COMPONENT; return {entity.index}; } return INVALID_COMPONENT; } ComponentHandle createComponent(ComponentType type, Entity entity) override { if (type == ANIMABLE_TYPE) return createAnimable(entity); return INVALID_COMPONENT; } void unloadAnimation(Animation* animation) { if (!animation) return; animation->getResourceManager().unload(*animation); } void destroyComponent(ComponentHandle component, ComponentType type) override { if (type == ANIMABLE_TYPE) { Entity entity = {component.index}; auto& animable = m_animables[entity]; unloadAnimation(animable.animation); m_animables.erase(entity); m_universe.destroyComponent(entity, type, this, component); } } void serialize(OutputBlob& serializer) override { serializer.write((int32)m_animables.size()); for (const Animable& animable : m_animables) { serializer.write(animable.entity); serializer.write(animable.time_scale); serializer.write(animable.start_time); serializer.writeString(animable.animation ? animable.animation->getPath().c_str() : ""); } } int getVersion() const override { return (int)AnimationSceneVersion::LATEST; } void deserialize(InputBlob& serializer, int version) override { int32 count; serializer.read(count); m_animables.reserve(count); for (int i = 0; i < count; ++i) { Animable animable; serializer.read(animable.entity); bool free = false; if (version <= (int)AnimationSceneVersion::FIRST) { serializer.read(animable.time); serializer.read(free); animable.time_scale = 1; animable.start_time = 0; } else { uint32 flags = 0; if(version <= (int)AnimationSceneVersion::REFACTOR) serializer.read(flags); free = flags != 0; serializer.read(animable.time_scale); serializer.read(animable.start_time); animable.time = animable.start_time; } char path[MAX_PATH_LENGTH]; serializer.readString(path, sizeof(path)); animable.animation = path[0] == '\0' ? nullptr : loadAnimation(Path(path)); if (!free) { m_animables.insert(animable.entity, animable); ComponentHandle cmp = {animable.entity.index}; m_universe.addComponent(animable.entity, ANIMABLE_TYPE, this, cmp); } } } float getTimeScale(ComponentHandle cmp) { return m_animables[{cmp.index}].time_scale; } void setTimeScale(ComponentHandle cmp, float time_scale) { m_animables[{cmp.index}].time_scale = time_scale; } float getStartTime(ComponentHandle cmp) { return m_animables[{cmp.index}].start_time; } void setStartTime(ComponentHandle cmp, float time) { m_animables[{cmp.index}].start_time = time; } Path getAnimation(ComponentHandle cmp) { const auto& animable = m_animables[{cmp.index}]; return animable.animation ? animable.animation->getPath() : Path(""); } void setAnimation(ComponentHandle cmp, const Path& path) { auto& animable = m_animables[{cmp.index}]; unloadAnimation(animable.animation); animable.animation = loadAnimation(path); animable.time = 0; } void updateMixer(Mixer& mixer, float time_delta) { ComponentHandle renderable = m_render_scene->getRenderableComponent(mixer.entity); if (renderable == INVALID_COMPONENT) return; auto* pose = m_render_scene->getPose(renderable); auto* model = m_render_scene->getRenderableModel(renderable); if (!pose) return; if (!model->isReady()) return; model->getPose(*pose); pose->computeRelative(*model); for (int i = 0; i < lengthOf(mixer.inputs); ++i) { Mixer::Input& input = mixer.inputs[i]; if (!input.animation || !input.animation->isReady()) break; if (i == 0) { input.animation->getRelativePose(input.time, *pose, *model); } else { input.animation->getRelativePose(input.time, *pose, *model, input.weight); } input.animation = nullptr; } pose->computeAbsolute(*model); } void updateAnimable(Animable& animable, float time_delta) { if (!animable.animation || !animable.animation->isReady()) return; ComponentHandle renderable = m_render_scene->getRenderableComponent(animable.entity); if (renderable == INVALID_COMPONENT) return; auto* pose = m_render_scene->getPose(renderable); auto* model = m_render_scene->getRenderableModel(renderable); if (!pose) return; if (!model->isReady()) return; model->getPose(*pose); pose->computeRelative(*model); animable.animation->getRelativePose(animable.time, *pose, *model); pose->computeAbsolute(*model); float t = animable.time + time_delta * animable.time_scale; float l = animable.animation->getLength(); while (t > l) { t -= l; } animable.time = t; } void updateAnimable(ComponentHandle cmp, float time_delta) override { Animable& animable = m_animables[{cmp.index}]; updateAnimable(animable, time_delta); } void update(float time_delta, bool paused) override { PROFILE_FUNCTION(); if (!m_is_game_running) return; for (Mixer& mixer : m_mixers) { AnimationSceneImpl::updateMixer(mixer, time_delta); } for (Animable& animable : m_animables) { AnimationSceneImpl::updateAnimable(animable, time_delta); } } Animation* loadAnimation(const Path& path) { ResourceManager& rm = m_engine.getResourceManager(); return static_cast<Animation*>(rm.get(ANIMATION_TYPE)->load(path)); } ComponentHandle createAnimable(Entity entity) { Animable& animable = m_animables.insert(entity); animable.time = 0; animable.animation = nullptr; animable.entity = entity; animable.time_scale = 1; animable.start_time = 0; ComponentHandle cmp = {entity.index}; m_universe.addComponent(entity, ANIMABLE_TYPE, this, cmp); return cmp; } IPlugin& getPlugin() const override { return m_anim_system; } Universe& m_universe; IPlugin& m_anim_system; Engine& m_engine; AssociativeArray<Entity, Animable> m_animables; AssociativeArray<Entity, Mixer> m_mixers; RenderScene* m_render_scene; bool m_is_game_running; }; struct AnimationSystemImpl : public IPlugin { explicit AnimationSystemImpl(Engine& engine) : m_allocator(engine.getAllocator()) , m_engine(engine) , animation_manager(m_allocator) { animation_manager.create(ANIMATION_TYPE, m_engine.getResourceManager()); PropertyRegister::add("animable", LUMIX_NEW(m_allocator, ResourcePropertyDescriptor<AnimationSceneImpl>)("Animation", &AnimationSceneImpl::getAnimation, &AnimationSceneImpl::setAnimation, "Animation (*.ani)", ANIMATION_TYPE)); PropertyRegister::add("animable", LUMIX_NEW(m_allocator, DecimalPropertyDescriptor<AnimationSceneImpl>)( "Start time", &AnimationSceneImpl::getStartTime, &AnimationSceneImpl::setStartTime, 0, FLT_MAX, 0.1f)); PropertyRegister::add("animable", LUMIX_NEW(m_allocator, DecimalPropertyDescriptor<AnimationSceneImpl>)( "Time scale", &AnimationSceneImpl::getTimeScale, &AnimationSceneImpl::setTimeScale, 0, FLT_MAX, 0.1f)); registerLuaAPI(); } void registerLuaAPI() { lua_State* L = m_engine.getState(); #define REGISTER_FUNCTION(name) \ do {\ auto f = &LuaWrapper::wrapMethod<AnimationSceneImpl, decltype(&AnimationSceneImpl::name), &AnimationSceneImpl::name>; \ LuaWrapper::createSystemFunction(L, "Animation", #name, f); \ } while(false) \ REGISTER_FUNCTION(mixAnimation); REGISTER_FUNCTION(getAnimationLength); #undef REGISTER_FUNCTION } IScene* createScene(Universe& ctx) override { return LUMIX_NEW(m_allocator, AnimationSceneImpl)(*this, m_engine, ctx, m_allocator); } void destroyScene(IScene* scene) override { LUMIX_DELETE(m_allocator, scene); } const char* getName() const override { return "animation"; } Lumix::IAllocator& m_allocator; Engine& m_engine; AnimationManager animation_manager; private: void operator=(const AnimationSystemImpl&); AnimationSystemImpl(const AnimationSystemImpl&); }; LUMIX_PLUGIN_ENTRY(animation) { return LUMIX_NEW(engine.getAllocator(), AnimationSystemImpl)(engine); } } <|endoftext|>
<commit_before>// RosterSystem.cpp // Created by Evan Almonte // #include "RosterSystem.hpp" #include "Roster.hpp" #include "RSFileManager.hpp" #include "Student.hpp" #include "Utilities.hpp" #include <iostream> using std::cout; using std::cin; using std::string; namespace RosterSystemUtils { int getMenuOptSelection (int start, int end); char getLoginOptSelection ( ); } const string RosterSystem::menuOpts[numOfMenuOpts] = { "Create a new Roster", "Drop a Roster", "Display Roster Information", "Display All Rosters", "Select a Roster" }; const string RosterSystem::selectOpts[numOfSelectOpts] = { "Add a New Student", "Remove a Student", "Update a Student", "List All Students" }; RosterSystem::RosterSystem( ) : loginStatus(NOT_LOGGED), rListSz(0), rListCap(0), rosterList(nullptr), eListSz(0), eListCap(0), enrollmentList(nullptr) {} RosterSystem::~RosterSystem( ) { for (int i = 0; i < rListSz; ++i) { delete rosterList[i]; } delete[] rosterList; for (int i = 0; i < eListSz; ++i) { delete enrollmentList[i]; } delete[] enrollmentList; } void RosterSystem::loginMenu( ) { clearScreen ( ); loginStatus = USER; cout << "********************************\n"; cout << " Welcome To SchoolManager v.1 \n"; cout << "********************************\n"; cout << "A) Supervisor Mode\n"; cout << "B) User Mode\n"; cout << "C) Exit\n"; cout << "Please choose an option: "; char choice = RosterSystemUtils::getLoginOptSelection ( ); switch(choice) { case 'A': case 'a': { RosterSystem::RSFileManager userDatabase ("Database.txt", false); loginStatus = userDatabase.attemptLogin ( ); } case 'B': case 'b': mainMenu ( ); loginMenu ( ); break; case 'C': case 'c': break; default: cout << "Invalid choice please try again.\n"; cout << "Press ENTER to continue . . ."; cin.get ( ); loginMenu ( ); } } void RosterSystem::mainMenu( ) { clearScreen ( ); cout << "******************************\n"; cout << " Main Menu \n"; cout << "******************************\n"; int startOption = 1, endOption; if (loginStatus == SUPERVISOR) { endOption = numOfMenuOpts; displayAdminMenu(); } else { endOption = 1; displayUserMenu(); } cout << "Please choose an option(q to Quit): "; int choice = RosterSystemUtils::getMenuOptSelection(startOption, endOption); if (choice == 1 && loginStatus != SUPERVISOR) { choice = 5; } switch (choice) { case 1: addRoster(); break; case 2: { string courseNumber; cout << "Please enter the rosters course number: "; getline(cin, courseNumber); removeRoster(courseNumber); } break; case 3: { cout << "Please enter the rosters course number: "; string courseNumber; getline(cin, courseNumber); displayRoster(courseNumber); } break; case 4: displayAllRosters(); break; case 5: { string courseNumber; cout << "Please enter the rosters course number: "; getline(cin, courseNumber); selectRoster(courseNumber); } break; default: cout << "Exiting to login menu.\n"; return; } cout << "Press ENTER to continue . . ."; cin.get(); mainMenu(); } void RosterSystem::displayAdminMenu( ) { for (int i = 0; i < numOfMenuOpts; ++i) { cout << i + 1 << ") " << menuOpts[i] << "\n"; } } void RosterSystem::displayUserMenu( ) { int i = numOfMenuOpts - 1; cout << i + 1 << ") " << menuOpts[numOfMenuOpts - 1] << "\n"; } void RosterSystem::addToEnrollmentList(Student* aStudent) { if (eListSz == eListCap) { growEnrollmentList(); } enrollmentList[eListSz++] = aStudent; } void RosterSystem::addToEnrollmentAndRoster(Roster& selectedRoster) { clearScreen(); if (eListSz == eListCap) { growEnrollmentList(); } Student* aStudent = new Student; cout << "******************************\n"; cout << " New Student Added \n"; cout << "******************************\n"; cin >> *aStudent; enrollmentList[eListSz++] = aStudent; selectedRoster.addStudent(aStudent); } int RosterSystem::findRoster(std::string courseCode) const { if (rListSz == 0) { cout << "There are no rosters in the system.\n"; return EMPTY_LIST; } int foundIndex = NOT_FOUND; for (int i = 0; i < rListSz; ++i) { if (courseCode == rosterList[i]->getCourseCode()) { foundIndex = i; } } if(foundIndex == NOT_FOUND) { cout << "No roster with a course number of: " << courseCode << " was found.\n"; } return foundIndex; } void RosterSystem::addRoster( ) { clearScreen(); if (rListSz == rListCap) { growRosterList(); } Roster* rosterToAdd = new Roster; cout << "******************************\n"; cout << " New Roster Created \n"; cout << "******************************\n"; cin >> *rosterToAdd; rosterList[rListSz++] = rosterToAdd; } void RosterSystem::selectRoster(std::string courseNumber) { int location = findRoster (courseNumber); if (location == NOT_FOUND || location == EMPTY_LIST) { return; } Roster* rosterToEdit = rosterList[location]; do { if (loginStatus == SUPERVISOR) { adminSelectOpts(*rosterToEdit); } else { userSelectOpts(*rosterToEdit); } cout << "Would you like to continue editing the same roster(Y/N)? "; } while (getYesOrNo()); } void RosterSystem::removeRoster(std::string courseCode) { int location = findRoster(courseCode); if (location == NOT_FOUND || location == EMPTY_LIST) { return; } clearScreen ( ); // Displays a title as: //******************************* // CourseName Has Been Deleted //******************************* int lengthOfName = rosterList[location]->getCourseName ( ).length ( ); string numOfAsterixs = "**"; for (int i = 0; i < lengthOfName; ++i) { numOfAsterixs += "*"; } cout << numOfAsterixs << "*******************\n"; cout << " " << rosterList[location]->getCourseName() << " Has Been Deleted \n"; cout << numOfAsterixs << "*******************\n"; //Shifts all rosters over to the left. delete rosterList[location]; for (; location < rListSz - 1; ++location) { rosterList[location] = rosterList[location + 1]; }; rosterList[rListSz - 1] = nullptr; --rListSz; } void RosterSystem::growEnrollmentList( ) { int newCap = eListCap * 2 + 1; Student** tempList = new Student*[newCap]; for (int i = 0; i < eListSz; ++i) { tempList[i] = enrollmentList[i]; } delete[] enrollmentList; enrollmentList = tempList; } void RosterSystem::growRosterList( ) { int newCap = rListCap * 2 + 1; Roster** tempList = new Roster*[newCap]; for (int i = 0; i < rListSz; ++i) { tempList[i] = rosterList[i]; } delete[] rosterList; rListCap = newCap; rosterList = tempList; } void RosterSystem::adminSelectOpts(Roster& selectedRoster) { clearScreen(); cout << "******************************\n"; cout << " Editing Roster \n"; cout << "******************************\n"; cout << "Course: " << selectedRoster.getCourseName() << "\n"; cout << "Code: " << selectedRoster.getCourseCode() << "\n"; for (int i = 0; i < numOfSelectOpts; ++i) { cout << static_cast<char>('a' + i) << ") " << selectOpts[i] << "\n"; } string userChoice; cout << "Please choose an option(a-d): "; getline(cin, userChoice); switch (userChoice[0]) { case 'A': case 'a': { addToEnrollmentAndRoster(selectedRoster); } break; case 'B': case 'b': { cout << "Please enter the student's last name: "; string lastName; getline(cin, lastName); selectedRoster.removeStudent(lastName); } break; case 'C': case 'c': { cout << "Please enter the student's last name: "; string lastName; getline(cin, lastName); selectedRoster.editStudent(lastName); } break; case 'D': case 'd': selectedRoster.listAllStudents(); break; default: cout << "Invalid option selected.\n"; } } void RosterSystem::displayRoster(std::string courseNumber) const { clearScreen ( ); int location = findRoster(courseNumber); if (location == NOT_FOUND || location == EMPTY_LIST) { return; } Roster* rosterToDisplay = rosterList[location]; rosterToDisplay->displayInfo(); } void RosterSystem::displayAllRosters( ) const { clearScreen ( ); if(rListSz == 0) { cout << "There are no rosters in the system.\n"; return; } cout << "******************************\n"; cout << " Display All Rosters \n"; cout << "******************************\n"; for (int i = 0; i < rListSz; ++i) { rosterList[i]->displayInfo(); cout << "\n"; } } void RosterSystem::userSelectOpts(Roster& selectedRoster) { clearScreen(); cout << "******************************\n"; cout << " Editing Roster \n"; cout << "******************************\n"; cout << "Course: " << selectedRoster.getCourseName() << "\n"; cout << "Code: " << selectedRoster.getCourseCode() << "\n"; //Subtract 1 due to the fact that "user" does not have access to the last option. for (int i = 0; i < numOfSelectOpts - 1; ++i) { cout << static_cast<char>('a' + i) << ") " << selectOpts[i] << "\n"; } string userChoice; cout << "Please choose an option(a-c): "; getline(cin, userChoice); switch (userChoice[0]) { case 'A': case 'a': { addToEnrollmentAndRoster(selectedRoster); } break; case 'B': case 'b': { cout << "Please enter the student's last name: "; string lastName; getline(cin, lastName); selectedRoster.removeStudent(lastName); } break; case 'C': case 'c': { cout << "Please enter the student's last name: "; string lastName; getline(cin, lastName); selectedRoster.editStudent(lastName); } break; default: cout << "Invalid option selected.\n"; } } namespace RosterSystemUtils { int getMenuOptSelection (int start, int end) { string choice; do { getline (cin, choice); } while (choice[0] - '0' < start || choice[0] - '0' > end && choice != "q" && choice != "Q"); int selection = choice[0] - '0'; return selection; } char getLoginOptSelection ( ) { string choice; do { getline (cin, choice); } while (choice != "A" && choice != "B" && choice != "C" && choice != "a" && choice != "b" && choice != "c"); return choice[0]; } }<commit_msg>Adds case C to the login menu which exports the rosters to a file<commit_after>// RosterSystem.cpp // Created by Evan Almonte // #include "RosterSystem.hpp" #include "Roster.hpp" #include "RSFileManager.hpp" #include "Student.hpp" #include "Utilities.hpp" #include <iostream> using std::cout; using std::cin; using std::string; namespace RosterSystemUtils { int getMenuOptSelection (int start, int end); char getLoginOptSelection ( ); } const string RosterSystem::menuOpts[numOfMenuOpts] = { "Create a new Roster", "Drop a Roster", "Display Roster Information", "Display All Rosters", "Select a Roster" }; const string RosterSystem::selectOpts[numOfSelectOpts] = { "Add a New Student", "Remove a Student", "Update a Student", "List All Students" }; RosterSystem::RosterSystem( ) : loginStatus(NOT_LOGGED), rListSz(0), rListCap(0), rosterList(nullptr), eListSz(0), eListCap(0), enrollmentList(nullptr) {} RosterSystem::~RosterSystem( ) { for (int i = 0; i < rListSz; ++i) { delete rosterList[i]; } delete[] rosterList; for (int i = 0; i < eListSz; ++i) { delete enrollmentList[i]; } delete[] enrollmentList; } void RosterSystem::loginMenu( ) { clearScreen ( ); loginStatus = USER; cout << "********************************\n"; cout << " Welcome To SchoolManager v.1 \n"; cout << "********************************\n"; cout << "A) Supervisor Mode\n"; cout << "B) User Mode\n"; cout << "C) Exit\n"; cout << "Please choose an option: "; char choice = RosterSystemUtils::getLoginOptSelection ( ); switch(choice) { case 'A': case 'a': { RSFileManager database ("Database.txt", false); loginStatus = database.attemptLogin ( ); } case 'B': case 'b': mainMenu ( ); loginMenu ( ); break; case 'C': case 'c': { RSFileManager writeRosters ("RosterFile.txt", true); writeRosters.exportRosters (rosterList, rListSz); } break; default: cout << "Invalid choice please try again.\n"; cout << "Press ENTER to continue . . ."; cin.get ( ); loginMenu ( ); } } void RosterSystem::mainMenu( ) { clearScreen ( ); cout << "******************************\n"; cout << " Main Menu \n"; cout << "******************************\n"; int startOption = 1, endOption; if (loginStatus == SUPERVISOR) { endOption = numOfMenuOpts; displayAdminMenu(); } else { endOption = 1; displayUserMenu(); } cout << "Please choose an option(q to Quit): "; int choice = RosterSystemUtils::getMenuOptSelection(startOption, endOption); if (choice == 1 && loginStatus != SUPERVISOR) { choice = 5; } switch (choice) { case 1: addRoster(); break; case 2: { string courseNumber; cout << "Please enter the rosters course number: "; getline(cin, courseNumber); removeRoster(courseNumber); } break; case 3: { cout << "Please enter the rosters course number: "; string courseNumber; getline(cin, courseNumber); displayRoster(courseNumber); } break; case 4: displayAllRosters(); break; case 5: { string courseNumber; cout << "Please enter the rosters course number: "; getline(cin, courseNumber); selectRoster(courseNumber); } break; default: cout << "Exiting to login menu.\n"; return; } cout << "Press ENTER to continue . . ."; cin.get(); mainMenu(); } void RosterSystem::displayAdminMenu( ) { for (int i = 0; i < numOfMenuOpts; ++i) { cout << i + 1 << ") " << menuOpts[i] << "\n"; } } void RosterSystem::displayUserMenu( ) { int i = numOfMenuOpts - 1; cout << i + 1 << ") " << menuOpts[numOfMenuOpts - 1] << "\n"; } void RosterSystem::addToEnrollmentList(Student* aStudent) { if (eListSz == eListCap) { growEnrollmentList(); } enrollmentList[eListSz++] = aStudent; } void RosterSystem::addToEnrollmentAndRoster(Roster& selectedRoster) { clearScreen(); if (eListSz == eListCap) { growEnrollmentList(); } Student* studentToAdd = new Student(); cout << "******************************\n"; cout << " New Student Added \n"; cout << "******************************\n"; cin >> *studentToAdd; enrollmentList[eListSz++] = studentToAdd; selectedRoster.addStudent(studentToAdd); } int RosterSystem::findRoster(std::string courseCode) const { if (rListSz == 0) { cout << "There are no rosters in the system.\n"; return EMPTY_LIST; } int foundIndex = NOT_FOUND; for (int i = 0; i < rListSz; ++i) { if (courseCode == rosterList[i]->getCourseCode()) { foundIndex = i; } } if(foundIndex == NOT_FOUND) { cout << "No roster with a course number of: " << courseCode << " was found.\n"; } return foundIndex; } void RosterSystem::addRoster( ) { clearScreen(); if (rListSz == rListCap) { growRosterList(); } Roster* rosterToAdd = new Roster; cout << "******************************\n"; cout << " New Roster Created \n"; cout << "******************************\n"; cin >> *rosterToAdd; rosterList[rListSz++] = rosterToAdd; } void RosterSystem::selectRoster(std::string courseNumber) { int location = findRoster (courseNumber); if (location == NOT_FOUND || location == EMPTY_LIST) { return; } Roster* rosterToEdit = rosterList[location]; do { if (loginStatus == SUPERVISOR) { adminSelectOpts(*rosterToEdit); } else { userSelectOpts(*rosterToEdit); } cout << "Would you like to continue editing the same roster(Y/N)? "; } while (getYesOrNo()); } void RosterSystem::removeRoster(std::string courseCode) { int location = findRoster(courseCode); if (location == NOT_FOUND || location == EMPTY_LIST) { return; } clearScreen ( ); // Displays a title as: //******************************* // CourseName Has Been Deleted //******************************* int lengthOfName = rosterList[location]->getCourseName ( ).length ( ); string numOfAsterixs = "**"; for (int i = 0; i < lengthOfName; ++i) { numOfAsterixs += "*"; } cout << numOfAsterixs << "*******************\n"; cout << " " << rosterList[location]->getCourseName() << " Has Been Deleted \n"; cout << numOfAsterixs << "*******************\n"; //Shifts all rosters over to the left. delete rosterList[location]; for (; location < rListSz - 1; ++location) { rosterList[location] = rosterList[location + 1]; }; rosterList[rListSz - 1] = nullptr; --rListSz; } void RosterSystem::growEnrollmentList( ) { int newCap = eListCap * 2 + 1; Student** tempList = new Student*[newCap]; for (int i = 0; i < eListSz; ++i) { tempList[i] = enrollmentList[i]; } for (int i = eListSz; i < eListCap; i++) { enrollmentList[i] = nullptr; } delete[] enrollmentList; eListCap = newCap; enrollmentList = tempList; } void RosterSystem::growRosterList( ) { int newCap = rListCap * 2 + 1; Roster** tempList = new Roster*[newCap]; for (int i = 0; i < rListSz; ++i) { tempList[i] = rosterList[i]; } for (int i = rListSz; i < rListCap; i++) { rosterList[i] = nullptr; } delete[] rosterList; rListCap = newCap; rosterList = tempList; } void RosterSystem::adminSelectOpts(Roster& selectedRoster) { clearScreen(); cout << "******************************\n"; cout << " Editing Roster \n"; cout << "******************************\n"; cout << "Course: " << selectedRoster.getCourseName() << "\n"; cout << "Code: " << selectedRoster.getCourseCode() << "\n"; for (int i = 0; i < numOfSelectOpts; ++i) { cout << static_cast<char>('a' + i) << ") " << selectOpts[i] << "\n"; } string userChoice; cout << "Please choose an option(a-d): "; getline(cin, userChoice); switch (userChoice[0]) { case 'A': case 'a': { addToEnrollmentAndRoster(selectedRoster); } break; case 'B': case 'b': { cout << "Please enter the student's last name: "; string lastName; getline(cin, lastName); selectedRoster.removeStudent(lastName); } break; case 'C': case 'c': { cout << "Please enter the student's last name: "; string lastName; getline(cin, lastName); selectedRoster.editStudent(lastName); } break; case 'D': case 'd': selectedRoster.listAllStudents(); break; default: cout << "Invalid option selected.\n"; } } void RosterSystem::displayRoster(std::string courseNumber) const { clearScreen ( ); int location = findRoster(courseNumber); if (location == NOT_FOUND || location == EMPTY_LIST) { return; } Roster* rosterToDisplay = rosterList[location]; rosterToDisplay->displayInfo(); } void RosterSystem::displayAllRosters( ) const { clearScreen ( ); if(rListSz == 0) { cout << "There are no rosters in the system.\n"; return; } cout << "******************************\n"; cout << " Display All Rosters \n"; cout << "******************************\n"; for (int i = 0; i < rListSz; ++i) { rosterList[i]->displayInfo(); cout << "\n"; } } void RosterSystem::userSelectOpts(Roster& selectedRoster) { clearScreen(); cout << "******************************\n"; cout << " Editing Roster \n"; cout << "******************************\n"; cout << "Course: " << selectedRoster.getCourseName() << "\n"; cout << "Code: " << selectedRoster.getCourseCode() << "\n"; //Subtract 1 due to the fact that "user" does not have access to the last option. for (int i = 0; i < numOfSelectOpts - 1; ++i) { cout << static_cast<char>('a' + i) << ") " << selectOpts[i] << "\n"; } string userChoice; cout << "Please choose an option(a-c): "; getline(cin, userChoice); switch (userChoice[0]) { case 'A': case 'a': { addToEnrollmentAndRoster(selectedRoster); } break; case 'B': case 'b': { cout << "Please enter the student's last name: "; string lastName; getline(cin, lastName); selectedRoster.removeStudent(lastName); } break; case 'C': case 'c': { cout << "Please enter the student's last name: "; string lastName; getline(cin, lastName); selectedRoster.editStudent(lastName); } break; default: cout << "Invalid option selected.\n"; } } namespace RosterSystemUtils { int getMenuOptSelection (int start, int end) { string choice; do { getline (cin, choice); } while (choice[0] - '0' < start || choice[0] - '0' > end && choice != "q" && choice != "Q"); int selection = choice[0] - '0'; return selection; } char getLoginOptSelection ( ) { string choice; do { getline (cin, choice); } while (choice != "A" && choice != "B" && choice != "C" && choice != "a" && choice != "b" && choice != "c"); return choice[0]; } }<|endoftext|>
<commit_before>/************************************************************************* > File Name: Deck.cpp > Project Name: Hearthstone++ > Author: Chan-Ho Chris Ohk > Purpose: Deck class that stores a list of cards. > Created Time: 2017/10/13 > Copyright (c) 2017, Chan-Ho Chris Ohk *************************************************************************/ #include <Models/Deck.h> #include <algorithm> #include <iostream> namespace Hearthstonepp { Deck::Deck() : m_name("Empty"), m_class(CardClass::INVALID), m_numOfCards(0) { } Deck::Deck(std::string name, const CardClass playerClass) : m_name(std::move(name)), m_class(playerClass), m_numOfCards(0) { } std::string Deck::GetName() const { return m_name; } CardClass Deck::GetClass() const { return m_class; } unsigned int Deck::GetNumOfCards() const { return m_numOfCards; } size_t Deck::GetUniqueNumOfCards() const { return m_cards.size(); } unsigned int Deck::GetNumCardInDeck(std::string cardID) { auto isCardExistInDeck = std::find_if(m_cards.begin(), m_cards.end(), [&cardID](const std::pair<std::string, int>& elem) { return elem.first == cardID; }); if (isCardExistInDeck != m_cards.end()) { return (*isCardExistInDeck).second; } return 0; } std::vector<const Card*> Deck::GetPrimitiveDeck() const { Cards* cards = Cards::GetInstance(); std::vector<const Card*> deck; for (const auto& pair : m_cards) { const Card* card = cards->FindCardByID(pair.first); for (int i = 0; i < pair.second; ++i) { deck.push_back(card); } } return deck; } std::pair<std::string, int> Deck::GetCard(size_t idx) const { return m_cards.at(idx); } void Deck::ShowCardList() const { int idx = 1; for (auto& cardInfo : m_cards) { const Card* card = Cards::GetInstance()->FindCardByID(cardInfo.first); if (card == nullptr) { continue; } std::cout << idx << ". "; card->ShowBriefInfo(); std::cout << "(" << cardInfo.second << " card(s))\n"; idx++; } } int Deck::AddCard(std::string cardID, int numCardToAdd) { const Card* card = Cards::GetInstance()->FindCardByID(cardID); CardClass cls = card->GetCardClass(); if (cls != GetClass() && cls != CardClass::NEUTRAL || card->GetMaxAllowedInDeck() < numCardToAdd) { return -1; } auto isCardExistInDeck = std::find_if(m_cards.begin(), m_cards.end(), [&cardID](const std::pair<std::string, int>& elem) { return elem.first == cardID; }); if (isCardExistInDeck != m_cards.end()) // card is in deck { if (card->GetMaxAllowedInDeck() < (*isCardExistInDeck).second + numCardToAdd) return -1; (*isCardExistInDeck).second += numCardToAdd; } else { m_cards.emplace_back(std::make_pair(cardID, numCardToAdd)); } m_numOfCards += numCardToAdd; return 0; } int Deck::DeleteCard(std::string cardID, const int numCardToDelete) { auto isCardExistInDeck = std::find_if(m_cards.begin(), m_cards.end(), [&cardID](const std::pair<std::string, int>& elem) { return elem.first == cardID; }); if (isCardExistInDeck != m_cards.end()) { if ((*isCardExistInDeck).second - numCardToDelete == 0) { m_cards.erase(isCardExistInDeck); } else if ((*isCardExistInDeck).second - numCardToDelete < 0) { return -1; } (*isCardExistInDeck).second -= numCardToDelete; m_numOfCards -= numCardToDelete; return 0; } return -1; } }<commit_msg>Modi Deck.cpp - fix parentheses, sign-compare<commit_after>/************************************************************************* > File Name: Deck.cpp > Project Name: Hearthstone++ > Author: Chan-Ho Chris Ohk > Purpose: Deck class that stores a list of cards. > Created Time: 2017/10/13 > Copyright (c) 2017, Chan-Ho Chris Ohk *************************************************************************/ #include <Models/Deck.h> #include <algorithm> #include <iostream> namespace Hearthstonepp { Deck::Deck() : m_name("Empty"), m_class(CardClass::INVALID), m_numOfCards(0) { } Deck::Deck(std::string name, const CardClass playerClass) : m_name(std::move(name)), m_class(playerClass), m_numOfCards(0) { } std::string Deck::GetName() const { return m_name; } CardClass Deck::GetClass() const { return m_class; } unsigned int Deck::GetNumOfCards() const { return m_numOfCards; } size_t Deck::GetUniqueNumOfCards() const { return m_cards.size(); } unsigned int Deck::GetNumCardInDeck(std::string cardID) { auto isCardExistInDeck = std::find_if(m_cards.begin(), m_cards.end(), [&cardID](const std::pair<std::string, int>& elem) { return elem.first == cardID; }); if (isCardExistInDeck != m_cards.end()) { return (*isCardExistInDeck).second; } return 0; } std::vector<const Card*> Deck::GetPrimitiveDeck() const { Cards* cards = Cards::GetInstance(); std::vector<const Card*> deck; for (const auto& pair : m_cards) { const Card* card = cards->FindCardByID(pair.first); for (int i = 0; i < pair.second; ++i) { deck.push_back(card); } } return deck; } std::pair<std::string, int> Deck::GetCard(size_t idx) const { return m_cards.at(idx); } void Deck::ShowCardList() const { int idx = 1; for (auto& cardInfo : m_cards) { const Card* card = Cards::GetInstance()->FindCardByID(cardInfo.first); if (card == nullptr) { continue; } std::cout << idx << ". "; card->ShowBriefInfo(); std::cout << "(" << cardInfo.second << " card(s))\n"; idx++; } } int Deck::AddCard(std::string cardID, int numCardToAdd) { const Card* card = Cards::GetInstance()->FindCardByID(cardID); CardClass cls = card->GetCardClass(); if ((cls != GetClass() && cls != +CardClass::NEUTRAL) || int(card->GetMaxAllowedInDeck()) < numCardToAdd) { return -1; } auto isCardExistInDeck = std::find_if(m_cards.begin(), m_cards.end(), [&cardID](const std::pair<std::string, int>& elem) { return elem.first == cardID; }); if (isCardExistInDeck != m_cards.end()) // card is in deck { if (int(card->GetMaxAllowedInDeck()) < (*isCardExistInDeck).second + numCardToAdd) return -1; (*isCardExistInDeck).second += numCardToAdd; } else { m_cards.emplace_back(std::make_pair(cardID, numCardToAdd)); } m_numOfCards += numCardToAdd; return 0; } int Deck::DeleteCard(std::string cardID, const int numCardToDelete) { auto isCardExistInDeck = std::find_if(m_cards.begin(), m_cards.end(), [&cardID](const std::pair<std::string, int>& elem) { return elem.first == cardID; }); if (isCardExistInDeck != m_cards.end()) { if ((*isCardExistInDeck).second - numCardToDelete == 0) { m_cards.erase(isCardExistInDeck); } else if ((*isCardExistInDeck).second - numCardToDelete < 0) { return -1; } (*isCardExistInDeck).second -= numCardToDelete; m_numOfCards -= numCardToDelete; return 0; } return -1; } }<|endoftext|>
<commit_before>#include <fstream> #include <pxcsession.h> #include <util/tiny_logger.hpp> int main() { PXCSession *session = PXCSession::CreateInstance(); PXCSession::ImplVersion ver = session->QueryVersion(); TLOG(INFO) << ver.major << "." << ver.minor; session->Release(); return EXIT_SUCCESS; } <commit_msg>Started implementing RealSense grabber<commit_after>#include <fstream> #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable: 4309) // truncation of const value #endif #include <pxcsensemanager.h> #ifdef _MSC_VER #pragma warning(pop) #endif #include <util/tiny_logger.hpp> int main() { /*PXCSession *session = PXCSession::CreateInstance(); PXCSession::ImplVersion ver = session->QueryVersion(); TLOG(INFO) << ver.major << "." << ver.minor; session->Release();*/ PXCSenseManager *senseManager = PXCSenseManager::CreateInstance(); senseManager->EnableStream(Intel::RealSense::StreamType::STREAM_TYPE_COLOR, 1920, 1080, 30.0f); senseManager->EnableStream(Intel::RealSense::StreamType::STREAM_TYPE_DEPTH, 628, 468, 30.0f); senseManager->Init(); int numFrames = 0; while (senseManager->AcquireFrame(true) >= PXC_STATUS_NO_ERROR) { PXCCapture::Sample *sample = senseManager->QuerySample(); const auto colorInfo = sample->color->QueryInfo(), depthInfo = sample->depth->QueryInfo(); senseManager->ReleaseFrame(); ++numFrames; TLOG(INFO) << "Captured color frame #" << numFrames << " " << colorInfo.format << " " << colorInfo.width << " " << colorInfo.height << " " << colorInfo.reserved; TLOG(INFO) << "Captured depth frame #" << numFrames << " " << depthInfo.format << " " << depthInfo.width << " " << depthInfo.height << " " << depthInfo.reserved; } senseManager->Release(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved. #include "stdafx.h" #include "AutowiringDebug.h" #include "Autowired.h" #include <iomanip> #include <iostream> #include <sstream> using namespace autowiring; using namespace autowiring::dbg; #ifdef _MSC_VER // On Windows, lambda functions start with the key string "class <" bool autowiring::dbg::IsLambda(const std::type_info& ti) { return demangle(ti).compare(0, 7, "class <") == 0; } #else // On other platforms, try to find lambda functions by the presence of forbidden characters bool autowiring::dbg::IsLambda(const std::type_info& ti) { auto name = demangle(ti); for (auto cur : name) if ( !('a' <= cur && cur <= 'z') && !('A' <= cur && cur <= 'Z') && !('0' <= cur && cur <= '9') && cur != '_' && cur != ':' && cur != '<' && cur != '>' && cur != ',' && cur != ' ' ) return true; return false; } #endif static std::string TrimPrefix(std::string name) { // "class" or "struct" prefixes should be eliminated if (name.compare(0, 6, "class ")) name = name.substr(5); if (name.compare(0, 7, "struct ")) name = name.substr(6); return name; } static std::string DemangleWithAutoID(const std::type_info& ti) { auto retVal = demangle(ti); // prefix is at the beginning of the string, skip over it static const char prefix [] = "struct auto_id<"; if (retVal.compare(0, sizeof(prefix) - 1, prefix) == 0) { size_t off = sizeof(prefix) - 1; retVal = retVal.substr(off, retVal.length() - off - 2); } return TrimPrefix(retVal); } std::string autowiring::dbg::ContextName(void) { AutoCurrentContext ctxt; return autowiring::demangle(ctxt->GetSigilType()); } AutoPacket* autowiring::dbg::CurrentPacket(void) { Autowired<AutoPacketFactory> factory; if (!factory) return nullptr; return factory->CurrentPacket().get(); } static const AutoFilterDescriptor* DescriptorByName(const char* name, const std::vector<AutoFilterDescriptor>& filters) { for (const auto& filter : filters) { auto type = filter.GetType(); if (!type) continue; auto curName = TrimPrefix(demangle(type)); if (!curName.compare(name)) return &filter; } return nullptr; } const AutoFilterDescriptor* autowiring::dbg::DescriptorByName(const char* name) { Autowired<AutoPacketFactory> factory; if (!factory) return nullptr; return DescriptorByName(name, factory->GetAutoFilters()); } std::string autowiring::dbg::AutoFilterInfo(const char* name) { Autowired<AutoPacketFactory> factory; if (!factory) return "No factory detected in this context"; // Obtain all descriptors: const std::vector<AutoFilterDescriptor> descs = factory->GetAutoFilters(); // Need the root descriptor first const AutoFilterDescriptor* desc = DescriptorByName(name, descs); if (!desc) return "Filter not found"; std::ostringstream os; std::function<void(const AutoFilterDescriptor&, int)> fnCall = [&](const AutoFilterDescriptor& desc, size_t nLevels) { auto args = desc.GetAutoFilterArguments(); for (size_t i = 0; i < desc.GetArity(); i++) { // Argument must be an input to the filter we want to know more about if (!args[i].is_input) continue; // Who provides this input? for (const auto& providerDesc : descs) { auto providerArg = providerDesc.GetArgumentType(args[i].ti); if (providerArg && providerArg->is_output) { // Need to print information about this provider: os << demangle(*args[i].ti) << ' ' << std::string(' ', nLevels) << demangle(*providerDesc.GetType()) << std::endl; // The current descriptor provides an input to the parent, recurse fnCall(providerDesc, nLevels + 1); } } } }; // Root typename print first: os << demangle(desc->GetType()) << std::endl; fnCall(*desc, 1); auto retVal = os.str(); return retVal; } std::vector<std::string> autowiring::dbg::ListRootDecorations(void) { Autowired<AutoPacketFactory> factory; if (!factory) return std::vector<std::string>{}; // Obtain all descriptors: const std::vector<AutoFilterDescriptor> descs = factory->GetAutoFilters(); // Get all baseline descriptor types, figure out what isn't satisfied: std::unordered_map<std::type_index, const std::type_info*> outputs; std::unordered_map<std::type_index, const std::type_info*> inputs; for (const auto& desc : descs) { auto args = desc.GetAutoFilterArguments(); for (size_t i = 0; i < desc.GetArity(); i++) (args[i].is_output ? outputs : inputs)[*args[i].ti] = args[i].ti; } // Remove all inputs that exist in the outputs set: for (auto& output : outputs) inputs.erase(*output.second); // Any remaining inputs are unsatisfied std::vector<std::string> retVal; for (auto& input : inputs) if (input.second) retVal.push_back(DemangleWithAutoID(*input.second)); return retVal; } void autowiring::dbg::DebugInit(void) { }<commit_msg>Make TrimPrefix a noop on mac<commit_after>// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved. #include "stdafx.h" #include "AutowiringDebug.h" #include "Autowired.h" #include <iomanip> #include <iostream> #include <sstream> using namespace autowiring; using namespace autowiring::dbg; #ifdef _MSC_VER // On Windows, lambda functions start with the key string "class <" bool autowiring::dbg::IsLambda(const std::type_info& ti) { return demangle(ti).compare(0, 7, "class <") == 0; } #else // On other platforms, try to find lambda functions by the presence of forbidden characters bool autowiring::dbg::IsLambda(const std::type_info& ti) { auto name = demangle(ti); for (auto cur : name) if ( !('a' <= cur && cur <= 'z') && !('A' <= cur && cur <= 'Z') && !('0' <= cur && cur <= '9') && cur != '_' && cur != ':' && cur != '<' && cur != '>' && cur != ',' && cur != ' ' ) return true; return false; } #endif static std::string TrimPrefix(std::string name) { #ifdef _MSC_VER // "class" or "struct" prefixes should be eliminated if (name.compare(0, 6, "class ")) name = name.substr(5); if (name.compare(0, 7, "struct ")) name = name.substr(6); #endif return name; } static std::string DemangleWithAutoID(const std::type_info& ti) { auto retVal = demangle(ti); // prefix is at the beginning of the string, skip over it static const char prefix [] = "struct auto_id<"; if (retVal.compare(0, sizeof(prefix) - 1, prefix) == 0) { size_t off = sizeof(prefix) - 1; retVal = retVal.substr(off, retVal.length() - off - 2); } return TrimPrefix(retVal); } std::string autowiring::dbg::ContextName(void) { AutoCurrentContext ctxt; return autowiring::demangle(ctxt->GetSigilType()); } AutoPacket* autowiring::dbg::CurrentPacket(void) { Autowired<AutoPacketFactory> factory; if (!factory) return nullptr; return factory->CurrentPacket().get(); } static const AutoFilterDescriptor* DescriptorByName(const char* name, const std::vector<AutoFilterDescriptor>& filters) { for (const auto& filter : filters) { auto type = filter.GetType(); if (!type) continue; auto curName = TrimPrefix(demangle(type)); if (!curName.compare(name)) return &filter; } return nullptr; } const AutoFilterDescriptor* autowiring::dbg::DescriptorByName(const char* name) { Autowired<AutoPacketFactory> factory; if (!factory) return nullptr; return DescriptorByName(name, factory->GetAutoFilters()); } std::string autowiring::dbg::AutoFilterInfo(const char* name) { Autowired<AutoPacketFactory> factory; if (!factory) return "No factory detected in this context"; // Obtain all descriptors: const std::vector<AutoFilterDescriptor> descs = factory->GetAutoFilters(); // Need the root descriptor first const AutoFilterDescriptor* desc = DescriptorByName(name, descs); if (!desc) return "Filter not found"; std::ostringstream os; std::function<void(const AutoFilterDescriptor&, int)> fnCall = [&](const AutoFilterDescriptor& desc, size_t nLevels) { auto args = desc.GetAutoFilterArguments(); for (size_t i = 0; i < desc.GetArity(); i++) { // Argument must be an input to the filter we want to know more about if (!args[i].is_input) continue; // Who provides this input? for (const auto& providerDesc : descs) { auto providerArg = providerDesc.GetArgumentType(args[i].ti); if (providerArg && providerArg->is_output) { // Need to print information about this provider: os << demangle(*args[i].ti) << ' ' << std::string(' ', nLevels) << demangle(*providerDesc.GetType()) << std::endl; // The current descriptor provides an input to the parent, recurse fnCall(providerDesc, nLevels + 1); } } } }; // Root typename print first: os << demangle(desc->GetType()) << std::endl; fnCall(*desc, 1); auto retVal = os.str(); return retVal; } std::vector<std::string> autowiring::dbg::ListRootDecorations(void) { Autowired<AutoPacketFactory> factory; if (!factory) return std::vector<std::string>{}; // Obtain all descriptors: const std::vector<AutoFilterDescriptor> descs = factory->GetAutoFilters(); // Get all baseline descriptor types, figure out what isn't satisfied: std::unordered_map<std::type_index, const std::type_info*> outputs; std::unordered_map<std::type_index, const std::type_info*> inputs; for (const auto& desc : descs) { auto args = desc.GetAutoFilterArguments(); for (size_t i = 0; i < desc.GetArity(); i++) (args[i].is_output ? outputs : inputs)[*args[i].ti] = args[i].ti; } // Remove all inputs that exist in the outputs set: for (auto& output : outputs) inputs.erase(*output.second); // Any remaining inputs are unsatisfied std::vector<std::string> retVal; for (auto& input : inputs) if (input.second) retVal.push_back(DemangleWithAutoID(*input.second)); return retVal; } void autowiring::dbg::DebugInit(void) { }<|endoftext|>
<commit_before>/***************************************************************************** mergeBed.cpp (c) 2009 - Aaron Quinlan Hall Laboratory Department of Biochemistry and Molecular Genetics University of Virginia aaronquinlan@gmail.com Licenced under the GNU General Public License 2.0+ license. ******************************************************************************/ #include "lineFileUtilities.h" #include "mergeBed.h" // =============== // = Constructor = // =============== BedMerge::BedMerge(string &bedFile, bool &numEntries, int &maxDistance, bool &forceStrand, bool &reportNames) { this->bedFile = bedFile; this->numEntries = numEntries; this->maxDistance = -1 * maxDistance; this->forceStrand = forceStrand; this->reportNames = reportNames; this->bed = new BedFile(bedFile); } // ================= // = Destructor = // ================= BedMerge::~BedMerge(void) { } // ===================================================== // = Merge overlapping BED entries into a single entry = // ===================================================== void BedMerge::MergeBed() { // load the "B" bed file into a map so // that we can easily compare "A" to it for overlaps bed->loadBedFileIntoMapNoBin(); // loop through each chromosome and merge their BED entries for (masterBedMapNoBin::iterator m = bed->bedMapNoBin.begin(); m != bed->bedMapNoBin.end(); ++m) { // bedList is already sorted by start position. vector<BED> bedList = m->second; int minStart = INT_MAX; int maxEnd = 0; bool OIP = false; // OIP = Overlap In Progress. Lame, I realize. unsigned int prev = 0; unsigned int curr = 0; int mergeCount = 1; vector<string> names; // loop through the BED entries for this chromosome // and look for overlaps for (curr = 1; curr < bedList.size(); ++curr) { // Is there an overlap between the current and previous entries? if ( overlaps(bedList[prev].start, bedList[prev].end, bedList[curr].start, bedList[curr].end) >= this->maxDistance) { OIP = true; mergeCount++; minStart = min(bedList[prev].start, min(minStart, bedList[curr].start)); maxEnd = max(bedList[prev].end, max(maxEnd, bedList[curr].end)); //names.push_back(bedList[prev].name); names.push_back(bedList[curr].name); } else if ( overlaps(minStart, maxEnd, bedList[curr].start, bedList[curr].end) >= this->maxDistance) { mergeCount++; minStart = min(minStart, bedList[curr].start); maxEnd = max(maxEnd, bedList[curr].end); names.push_back(bedList[curr].name); } else { // was there an overlap befor the current entry broke it? if (OIP) { if (this->numEntries) { cout << bedList[prev].chrom << "\t" << minStart << "\t" << maxEnd << "\t" << mergeCount << endl; } else if (this->reportNames) { cout << bedList[prev].chrom << "\t" << minStart << "\t" << maxEnd << "\t"; for (unsigned int n = 0; n < names.size(); ++n) { if (n < (names.size() - 1)) {cout << names[n] << ";";} else {cout << names[n];} } cout << endl; } else { cout << bedList[prev].chrom << "\t" << minStart << "\t" << maxEnd << endl; } } else { if (this->numEntries) { cout << bedList[prev].chrom << "\t" << bedList[prev].start << "\t" << bedList[prev].end << "\t" << mergeCount << endl; } else if (this->reportNames) { cout << bedList[prev].chrom << "\t" << bedList[prev].start << "\t" << bedList[prev].end << "\t" << bedList[prev].name << endl; } else { cout << bedList[prev].chrom << "\t" << bedList[prev].start << "\t" << bedList[prev].end << endl; } } // reset things for the next overlapping "block" OIP = false; mergeCount = 1; minStart = INT_MAX; maxEnd = 0; names.clear(); names.push_back(bedList[prev].name); } prev = curr; } // clean up based on the last entry for the current chromosome if (OIP) { if (this->numEntries) { cout << bedList[prev].chrom << "\t" << minStart << "\t" << maxEnd << "\t" << mergeCount << endl; } else if (this->reportNames) { cout << bedList[prev].chrom << "\t" << minStart << "\t" << maxEnd << "\t"; for (unsigned int n = 0; n < names.size(); ++n) { if (n < (names.size() - 1)) {cout << names[n] << ";";} else {cout << names[n];} } cout << endl; } else { cout << bedList[prev].chrom << "\t" << minStart << "\t" << maxEnd << endl; } } else { if (this->numEntries) { cout << bedList[prev].chrom << "\t" << bedList[prev].start << "\t" << bedList[prev].end << "\t" << mergeCount << endl; } else if (this->reportNames) { cout << bedList[prev].chrom << "\t" << bedList[prev].start << "\t" << bedList[prev].end << "\t" << bedList[prev].name << endl; } else { cout << bedList[prev].chrom << "\t" << bedList[prev].start << "\t" << bedList[prev].end << endl; } } } } // ================================================================================== // = Merge overlapping BED entries into a single entry, accounting for strandedness = // ================================================================================== void BedMerge::MergeBedStranded() { // load the "B" bed file into a map so // that we can easily compare "A" to it for overlaps bed->loadBedFileIntoMapNoBin(); // loop through each chromosome and merge their BED entries for (masterBedMapNoBin::iterator m = bed->bedMapNoBin.begin(); m != bed->bedMapNoBin.end(); ++m) { // bedList is already sorted by start position. vector<BED> bedList = m->second; // make a list of the two strands to merge separately. vector<string> strands(2); strands[0] = "+"; strands[1] = "-"; // do two passes, one for each strand. for (unsigned int s = 0; s < strands.size(); s++) { int minStart = INT_MAX; int maxEnd = 0; bool OIP = false; // OIP = Overlap In Progress. Lame, I realize. int prev = -1; unsigned int curr = 0; int mergeCount = 1; int numOnStrand = 0; vector<string> names; // loop through the BED entries for this chromosome // and look for overlaps for (curr = 0; curr < bedList.size(); ++curr) { // if forcing strandedness, move on if the hit // is not on the current strand. if (bedList[curr].strand != strands[s]) { continue; // continue force the next iteration of the for loop. } else { numOnStrand++; } // make sure prev points to an actual element on the // current strand if (prev < 0) { if (bedList[curr].strand == strands[s]) { prev = curr; } continue; } if ( overlaps(bedList[prev].start, bedList[prev].end, bedList[curr].start, bedList[curr].end) >= this->maxDistance) { OIP = true; mergeCount++; minStart = min(bedList[prev].start, min(minStart, bedList[curr].start)); maxEnd = max(bedList[prev].end, max(maxEnd, bedList[curr].end)); names.push_back(bedList[curr].name); } else if ( overlaps(minStart, maxEnd, bedList[curr].start, bedList[curr].end) >= this->maxDistance) { mergeCount++; minStart = min(minStart, bedList[curr].start); maxEnd = max(maxEnd, bedList[curr].end); names.push_back(bedList[curr].name); } else { // was there an overlap before the current entry broke it? if (OIP) { if (this->numEntries) { cout << bedList[prev].chrom << "\t" << minStart << "\t" << maxEnd << "\t" << mergeCount << "\t" << strands[s] << endl; } else if (this->reportNames) { cout << bedList[prev].chrom << "\t" << minStart << "\t" << maxEnd << "\t"; for (unsigned int n = 0; n < names.size(); ++n) { if (n < (names.size() - 1)) {cout << names[n] << ";";} else {cout << names[n];} } cout << endl; } else { cout << bedList[prev].chrom << "\t" << minStart << "\t" << maxEnd << "\t" << strands[s] << endl; } } else { if ((this->numEntries) && (numOnStrand > 0)) { cout << bedList[prev].chrom << "\t" << bedList[prev].start << "\t" << bedList[prev].end << "\t" << mergeCount << "\t" << strands[s] << endl; } else if (this->reportNames) { cout << bedList[prev].chrom << "\t" << bedList[prev].start << "\t" << bedList[prev].end << "\t" << bedList[prev].name << endl; } else if (numOnStrand > 0) { cout << bedList[prev].chrom << "\t" << bedList[prev].start << "\t" << bedList[prev].end << "\t" << strands[s] << endl; } } // reset things for the next overlapping "block" OIP = false; mergeCount = 1; minStart = INT_MAX; maxEnd = 0; names.clear(); // add the name of the names.push_back(bedList[prev].name); } prev = curr; } // clean up based on the last entry for the current chromosome if (OIP) { if (this->numEntries) { cout << bedList[prev].chrom << "\t" << minStart << "\t" << maxEnd << "\t" << mergeCount << "\t" << strands[s] << endl; } else if (this->reportNames) { cout << bedList[prev].chrom << "\t" << minStart << "\t" << maxEnd << "\t"; for (unsigned int n = 0; n < names.size(); ++n) { if (n < (names.size() - 1)) {cout << names[n] << ";";} else {cout << names[n];} } cout << endl; } else { cout << bedList[prev].chrom << "\t" << minStart << "\t" << maxEnd << "\t" << strands[s] << endl; } } else { if ((this->numEntries) && (numOnStrand > 0)) { cout << bedList[prev].chrom << "\t" << bedList[prev].start << "\t" << bedList[prev].end << "\t" << mergeCount << "\t" << strands[s] << endl; } else if (this->reportNames) { cout << bedList[prev].chrom << "\t" << bedList[prev].start << "\t" << bedList[prev].end << "\t" << bedList[prev].name << endl; } else if (numOnStrand > 0) { cout << bedList[prev].chrom << "\t" << bedList[prev].start << "\t" << bedList[prev].end << "\t" << strands[s] << endl; } } } } } <commit_msg>Fixed bug in mergeBed that caused segfault when -nms and -s used together.<commit_after>/***************************************************************************** mergeBed.cpp (c) 2009 - Aaron Quinlan Hall Laboratory Department of Biochemistry and Molecular Genetics University of Virginia aaronquinlan@gmail.com Licenced under the GNU General Public License 2.0+ license. ******************************************************************************/ #include "lineFileUtilities.h" #include "mergeBed.h" // =============== // = Constructor = // =============== BedMerge::BedMerge(string &bedFile, bool &numEntries, int &maxDistance, bool &forceStrand, bool &reportNames) { this->bedFile = bedFile; this->numEntries = numEntries; this->maxDistance = -1 * maxDistance; this->forceStrand = forceStrand; this->reportNames = reportNames; this->bed = new BedFile(bedFile); } // ================= // = Destructor = // ================= BedMerge::~BedMerge(void) { } // ===================================================== // = Merge overlapping BED entries into a single entry = // ===================================================== void BedMerge::MergeBed() { // load the "B" bed file into a map so // that we can easily compare "A" to it for overlaps bed->loadBedFileIntoMapNoBin(); // loop through each chromosome and merge their BED entries for (masterBedMapNoBin::iterator m = bed->bedMapNoBin.begin(); m != bed->bedMapNoBin.end(); ++m) { // bedList is already sorted by start position. vector<BED> bedList = m->second; int minStart = INT_MAX; int maxEnd = 0; bool OIP = false; // OIP = Overlap In Progress. Lame, I realize. unsigned int prev = 0; unsigned int curr = 0; int mergeCount = 1; vector<string> names; // loop through the BED entries for this chromosome // and look for overlaps for (curr = 1; curr < bedList.size(); ++curr) { // Is there an overlap between the current and previous entries? if ( overlaps(bedList[prev].start, bedList[prev].end, bedList[curr].start, bedList[curr].end) >= this->maxDistance) { OIP = true; mergeCount++; minStart = min(bedList[prev].start, min(minStart, bedList[curr].start)); maxEnd = max(bedList[prev].end, max(maxEnd, bedList[curr].end)); //names.push_back(bedList[prev].name); names.push_back(bedList[curr].name); } else if ( overlaps(minStart, maxEnd, bedList[curr].start, bedList[curr].end) >= this->maxDistance) { mergeCount++; minStart = min(minStart, bedList[curr].start); maxEnd = max(maxEnd, bedList[curr].end); names.push_back(bedList[curr].name); } else { // was there an overlap befor the current entry broke it? if (OIP) { if (this->numEntries) { cout << bedList[prev].chrom << "\t" << minStart << "\t" << maxEnd << "\t" << mergeCount << endl; } else if (this->reportNames) { cout << bedList[prev].chrom << "\t" << minStart << "\t" << maxEnd << "\t"; for (unsigned int n = 0; n < names.size(); ++n) { if (n < (names.size() - 1)) {cout << names[n] << ";";} else {cout << names[n];} } cout << endl; } else { cout << bedList[prev].chrom << "\t" << minStart << "\t" << maxEnd << endl; } } else { if (this->numEntries) { cout << bedList[prev].chrom << "\t" << bedList[prev].start << "\t" << bedList[prev].end << "\t" << mergeCount << endl; } else if (this->reportNames) { cout << bedList[prev].chrom << "\t" << bedList[prev].start << "\t" << bedList[prev].end << "\t" << bedList[prev].name << endl; } else { cout << bedList[prev].chrom << "\t" << bedList[prev].start << "\t" << bedList[prev].end << endl; } } // reset things for the next overlapping "block" OIP = false; mergeCount = 1; minStart = INT_MAX; maxEnd = 0; names.clear(); names.push_back(bedList[prev].name); } prev = curr; } // clean up based on the last entry for the current chromosome if (OIP) { if (this->numEntries) { cout << bedList[prev].chrom << "\t" << minStart << "\t" << maxEnd << "\t" << mergeCount << endl; } else if (this->reportNames) { cout << bedList[prev].chrom << "\t" << minStart << "\t" << maxEnd << "\t"; for (unsigned int n = 0; n < names.size(); ++n) { if (n < (names.size() - 1)) {cout << names[n] << ";";} else {cout << names[n];} } cout << endl; } else { cout << bedList[prev].chrom << "\t" << minStart << "\t" << maxEnd << endl; } } else { if (this->numEntries) { cout << bedList[prev].chrom << "\t" << bedList[prev].start << "\t" << bedList[prev].end << "\t" << mergeCount << endl; } else if (this->reportNames) { cout << bedList[prev].chrom << "\t" << bedList[prev].start << "\t" << bedList[prev].end << "\t" << bedList[prev].name << endl; } else { cout << bedList[prev].chrom << "\t" << bedList[prev].start << "\t" << bedList[prev].end << endl; } } } } // ================================================================================== // = Merge overlapping BED entries into a single entry, accounting for strandedness = // ================================================================================== void BedMerge::MergeBedStranded() { // load the "B" bed file into a map so // that we can easily compare "A" to it for overlaps bed->loadBedFileIntoMapNoBin(); // loop through each chromosome and merge their BED entries for (masterBedMapNoBin::iterator m = bed->bedMapNoBin.begin(); m != bed->bedMapNoBin.end(); ++m) { // bedList is already sorted by start position. vector<BED> bedList = m->second; // make a list of the two strands to merge separately. vector<string> strands(2); strands[0] = "+"; strands[1] = "-"; // do two passes, one for each strand. for (unsigned int s = 0; s < strands.size(); s++) { int minStart = INT_MAX; int maxEnd = 0; bool OIP = false; // OIP = Overlap In Progress. Lame, I realize. int prev = -1; unsigned int curr = 0; int mergeCount = 1; int numOnStrand = 0; vector<string> names; // loop through the BED entries for this chromosome // and look for overlaps for (curr = 0; curr < bedList.size(); ++curr) { // if forcing strandedness, move on if the hit // is not on the current strand. if (bedList[curr].strand != strands[s]) { continue; // continue force the next iteration of the for loop. } else { numOnStrand++; } // make sure prev points to an actual element on the // current strand if (prev < 0) { if (bedList[curr].strand == strands[s]) { prev = curr; } continue; } if ( overlaps(bedList[prev].start, bedList[prev].end, bedList[curr].start, bedList[curr].end) >= this->maxDistance) { OIP = true; mergeCount++; minStart = min(bedList[prev].start, min(minStart, bedList[curr].start)); maxEnd = max(bedList[prev].end, max(maxEnd, bedList[curr].end)); names.push_back(bedList[curr].name); } else if ( overlaps(minStart, maxEnd, bedList[curr].start, bedList[curr].end) >= this->maxDistance) { mergeCount++; minStart = min(minStart, bedList[curr].start); maxEnd = max(maxEnd, bedList[curr].end); names.push_back(bedList[curr].name); } else { // was there an overlap before the current entry broke it? if (OIP) { if (this->numEntries) { cout << bedList[prev].chrom << "\t" << minStart << "\t" << maxEnd << "\t" << mergeCount << "\t" << strands[s] << endl; } else if (this->reportNames) { cout << bedList[prev].chrom << "\t" << minStart << "\t" << maxEnd << "\t"; for (unsigned int n = 0; n < names.size(); ++n) { if (n < (names.size() - 1)) {cout << names[n] << ";";} else {cout << names[n];} } cout << "\t" << strands[s] << endl; } else { cout << bedList[prev].chrom << "\t" << minStart << "\t" << maxEnd << "\t" << strands[s] << endl; } } else { if ((this->numEntries) && (numOnStrand > 0)) { cout << bedList[prev].chrom << "\t" << bedList[prev].start << "\t" << bedList[prev].end << "\t" << mergeCount << "\t" << strands[s] << endl; } else if (this->reportNames) { cout << bedList[prev].chrom << "\t" << bedList[prev].start << "\t" << bedList[prev].end << "\t" << bedList[prev].name << "\t" << strands[s] << endl; } else if (numOnStrand > 0) { cout << bedList[prev].chrom << "\t" << bedList[prev].start << "\t" << bedList[prev].end << "\t" << strands[s] << endl; } } // reset things for the next overlapping "block" OIP = false; mergeCount = 1; minStart = INT_MAX; maxEnd = 0; names.clear(); // add the name of the names.push_back(bedList[prev].name); } prev = curr; } // clean up based on the last entry for the current chromosome if (OIP) { if (this->numEntries) { cout << bedList[prev].chrom << "\t" << minStart << "\t" << maxEnd << "\t" << mergeCount << "\t" << strands[s] << endl; } else if (this->reportNames) { cout << bedList[prev].chrom << "\t" << minStart << "\t" << maxEnd << "\t"; for (unsigned int n = 0; n < names.size(); ++n) { if (n < (names.size() - 1)) {cout << names[n] << ";";} else {cout << names[n];} } cout << "\t" << strands[s] << endl; } else { cout << bedList[prev].chrom << "\t" << minStart << "\t" << maxEnd << "\t" << strands[s] << endl; } } else { if ((this->numEntries) && (numOnStrand > 0)) { cout << bedList[prev].chrom << "\t" << bedList[prev].start << "\t" << bedList[prev].end << "\t" << mergeCount << "\t" << strands[s] << endl; } else if ((this->reportNames) && (numOnStrand > 0)) { cout << bedList[prev].chrom << "\t" << bedList[prev].start << "\t" << bedList[prev].end << "\t" << bedList[prev].name << "\t" << strands[s] << endl; } else if (numOnStrand > 0) { cout << bedList[prev].chrom << "\t" << bedList[prev].start << "\t" << bedList[prev].end << "\t" << strands[s] << endl; } } } } } <|endoftext|>
<commit_before>/******************************************************************************* * c7a/api/dia.hpp * * Interface for Operations, holds pointer to node and lambda from node to state * * Part of Project c7a. * * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #pragma once #ifndef C7A_API_DIA_HEADER #define C7A_API_DIA_HEADER #include <functional> #include <vector> #include <stack> #include <iostream> #include <fstream> #include <cassert> #include <memory> #include <unordered_map> #include <string> #include <utility> #include "dia_node.hpp" #include "function_traits.hpp" #include "lop_node.hpp" #include "zip_node.hpp" #include "read_node.hpp" #include "reduce_node.hpp" #include "context.hpp" #include "write_node.hpp" namespace c7a { //! \addtogroup api Interface //! \{ /*! * DIARef is the interface between the user and the c7a framework. A DIARef can * be imagined as an immutable array, even though the data does not need to be * materialized at all. A DIARef contains a pointer to a DIANode of type T, * which represents the state after the previous DOp or Action. Additionally, a * DIARef stores the local lambda function chain of type Stack, which can transform * elements of the DIANode to elements of this DIARef. DOps/Actions create a * DIARef and a new DIANode, to which the DIARef links to. LOps only create a * new DIARef, which link to the previous DIANode. * * \tparam T Type of elements in this DIARef. * * \tparam Stack Type of the function chain. */ template <typename T, typename Stack = FunctionStack<> > class DIARef { friend class Context; using DIANodePtr = std::shared_ptr<DIANode<T> >; public: /*! * Constructor of a new DIARef with a pointer to a DIANode and a * function chain from the DIANode to this DIARef. * * \param node Pointer to the last DIANode, DOps and Actions create a new * DIANode, LOps link to the DIANode of the previous DIARef. * * \param stack Function stack consisting of functions between last DIANode * and this DIARef. */ DIARef(DIANodePtr& node, Stack& stack) : node_(node), local_stack_(stack) { } /*! * Constructor of a new DIARef supporting move semantics of nodes. * * \param node Pointer to the last DIANode, DOps and Actions create a new * DIANode, LOps link to the DIANode of the previous DIARef. * * \param stack Function stack consisting of functions between last DIANode * and this DIARef. */ DIARef(DIANodePtr&& node, Stack& stack) : node_(std::move(node)), local_stack_(stack) { } /*! * Copy-Constructor of a DIARef with empty function chain * from a DIARef with a non-empty chain. * The functionality of the chain is stored in a newly created LOpNode. * The current DIARef than points to this LOpNode. * This is needed to support assignment operations between DIARef's. * * \param rhs DIA containing a non-empty function chain. */ template <typename AnyStack> DIARef(const DIARef<T, AnyStack>& rhs) { // Create new LOpNode // Transfer stack from rhs to LOpNode // Build new DIARef with empty stack and LOpNode auto rhs_node = std::move(rhs.get_node()); auto rhs_stack = rhs.get_stack(); using LOpChainNode = LOpNode<T, decltype(rhs_stack)>; auto shared_node = std::make_shared<LOpChainNode>(rhs_node->get_context(), rhs_node, rhs_stack); node_ = std::move(shared_node); local_stack_ = FunctionStack<>(); } /*! * Returns a pointer to the according DIANode. */ DIANode<T> * get_node() const { return node_.get(); } /*! * Returns the number of references to the according DIANode. */ int get_node_count() const { return node_.use_count(); } /*! * Returns the stored function chain. */ Stack & get_stack() { return local_stack_; } /*! * Map is a LOp, which maps this DIARef according to the map_fn given by the * user. The map_fn maps each element to another * element of a possibly different type. The DIARef returned by Map has the * same type T. The function chain of the returned DIARef is this DIARef's * local_stack_ chained with map_fn. * * \tparam map_fn_t Type of the map function. * * \param map_fn Map function of type map_fn_t, which maps each element to * an element of a possibly different type. * */ template <typename map_fn_t> auto Map(const map_fn_t &map_fn) { using map_arg_t = typename FunctionTraits<map_fn_t>::template arg<0>; using map_result_t = typename FunctionTraits<map_fn_t>::result_type; auto conv_map_fn = [=](map_arg_t input, std::function<void(map_result_t)> emit_func) { emit_func(map_fn(input)); }; auto new_stack = local_stack_.push(conv_map_fn); return DIARef<T, decltype(new_stack)>(node_, new_stack); } /*! * Filter is a LOp, which filters elements from this DIARef * according to the filter_fn given by the * user. The filter_fn maps each element to a boolean. * The DIARef returned by Filter has the same type T. * The function chain of the returned DIARef is this DIARef's * local_stack_ chained with filter_fn. * * \tparam filter_fn_t Type of the map function. * * \param filter_fn Filter function of type filter_fn_t, which maps each element to * a boolean. * */ template <typename filter_fn_t> auto Filter(const filter_fn_t &filter_fn) { using filter_arg_t = typename FunctionTraits<filter_fn_t>::template arg<0>; auto conv_filter_fn = [=](filter_arg_t input, std::function<void(filter_arg_t)> emit_func) { if (filter_fn(input)) emit_func(input); }; auto new_stack = local_stack_.push(conv_filter_fn); return DIARef<T, decltype(new_stack)>(node_, new_stack); } /*! * FlatMap is a LOp, which maps this DIARef according to the flatmap_fn * given by the user. The flatmap_fn maps each element * to elements of a possibly different type. The flatmap_fn has an emitter * function as it's second parameter. This emitter is called once for each * element to be emitted. The DIARef returned by FlatMap has the same type * T. The function chain of the returned DIARef is this DIARef's * local_stack_ chained with flatmap_fn. * * \tparam flatmap_fn_t Type of the map function. * * \param flatmap_fn Map function of type map_fn_t, which maps each element * to elements of a possibly different type. */ template <typename flatmap_fn_t> auto FlatMap(const flatmap_fn_t &flatmap_fn) { auto new_stack = local_stack_.push(flatmap_fn); return DIARef<T, decltype(new_stack)>(node_, new_stack); } /*! * Reduce is a DOp, which groups elements of the DIARef with the * key_extractor and reduces each key-bucket to a single element using the * associative reduce_function. The reduce_function defines how two elements * can be reduced to a single element of equal type. Since Reduce is a DOp, it * creates a new DIANode. The DIARef returned by Reduce links to this newly * created DIANode. The local_stack_ of the returned DIARef consists of * the PostOp of Reduce, as a reduced element can * directly be chained to the following LOps. * * \tparam key_extr_fn_t Type of the key_extractor function. * The key_extractor function is equal to a map function. * * \param key_extractor Key extractor function, which maps each element to a * key of possibly different type. * */ template <typename key_extr_fn_t> auto ReduceBy(const key_extr_fn_t &key_extractor) { return ReduceSugar<key_extr_fn_t>(key_extractor, node_.get(), local_stack_); } /*! * Zip is a DOp, which Zips two DIAs in style of functional programming. The * zip_function is used to zip the i-th elements of both input DIAs together * to form the i-th element of the output DIARef. The type of the output * DIARef can be inferred from the zip_function. * * \tparam zip_fn_t Type of the zip_function. This is a function with two * input elements, both of the local type, and one output element, which is * the type of the Zip node. * * \param zip_fn Zip function, which zips two elements together * * \param second_dia DIARef, which is zipped together with the original * DIARef. */ template <typename zip_fn_t, typename second_dia_t> auto Zip(const zip_fn_t &zip_fn, second_dia_t second_dia) { using zip_result_t = typename FunctionTraits<zip_fn_t>::result_type; using zip_arg_0_t = typename FunctionTraits<zip_fn_t>::template arg<0>; using zip_arg_1_t = typename FunctionTraits<zip_fn_t>::template arg<1>; using ZipResultNode = TwoZipNode<zip_arg_0_t, zip_arg_1_t, zip_result_t, decltype(local_stack_), decltype(second_dia.get_stack()), zip_fn_t>; auto shared_node = std::make_shared<ZipResultNode>(node_->get_context(), node_.get(), second_dia.get_node(), local_stack_, second_dia.get_stack(), zip_fn); auto zip_stack = shared_node->ProduceStack(); return DIARef<zip_result_t, decltype(zip_stack)> (std::move(shared_node), zip_stack); } template <typename write_fn_t> void WriteToFileSystem(std::string filepath, const write_fn_t &write_fn) { using write_result_t = typename FunctionTraits<write_fn_t>::result_type; using WriteResultNode = WriteNode<T, write_result_t, write_fn_t>; auto shared_node = std::make_shared<WriteResultNode>(node_->get_context(), node_.get(), write_fn, filepath); shared_node->ProduceStack(); } /*! * Returns Chuck Norris! * * \return Chuck Norris */ const std::vector<T> & evil_get_data() const { return (std::vector<T>{ T() }); } /*! * Returns the string which defines the DIANode node_. * * \return The string of node_ */ std::string NodeString() { return node_->ToString(); } /*! * Prints the DIANode and all it's children recursively. The printing is * performed tree-style. */ void PrintNodes() { using BasePair = std::pair<DIABase*, int>; std::stack<BasePair> dia_stack; dia_stack.push(std::make_pair(node_, 0)); while (!dia_stack.empty()) { auto curr = dia_stack.top(); auto node = curr.first; int depth = curr.second; dia_stack.pop(); auto is_end = true; if (!dia_stack.empty()) is_end = dia_stack.top().second < depth; for (int i = 0; i < depth - 1; ++i) { std::cout << "│ "; } if (is_end && depth > 0) std::cout << "└── "; else if (depth > 0) std::cout << "├── "; std::cout << node->ToString() << std::endl; auto children = node->get_childs(); for (auto c : children) { dia_stack.push(std::make_pair(c, depth + 1)); } } } private: //! The DIANode which DIARef points to. The node represents the latest DOp //! or Action performed previously. DIANodePtr node_; //! The local function chain, which stores the chained lambda function from //! the last DIANode to this DIARef. Stack local_stack_; /*! * Syntactic sugaaah for reduce */ template <typename key_extr_fn_t> class ReduceSugar { public: ReduceSugar(const key_extr_fn_t& key_extractor, DIANode<T>* node, Stack& local_stack) : key_extractor_(key_extractor), node_(node), local_stack_(local_stack) { } /*! * Syntactic sugaaah * * \tparam reduce_fn_t Type of the reduce_function. This is a function * reducing two elements of L's result type to a single element of equal * type. * * \param reduce_function Reduce function, which defines how the key * buckets are reduced to a single element. This function is applied * associative but not necessarily commutative. * */ template <typename reduce_fn_t> auto With(const reduce_fn_t &reduce_function) { using dop_result_t = typename FunctionTraits<reduce_fn_t>::result_type; using ReduceResultNode = ReduceNode<T, dop_result_t, decltype(local_stack_), key_extr_fn_t, reduce_fn_t>; auto shared_node = std::make_shared<ReduceResultNode>(node_->get_context(), node_, local_stack_, key_extractor_, reduce_function); auto reduce_stack = shared_node->ProduceStack(); return DIARef<dop_result_t, decltype(reduce_stack)> (std::move(shared_node), reduce_stack); } private: const key_extr_fn_t& key_extractor_; DIANode<T>* node_; Stack& local_stack_; }; }; //! \} template <typename read_fn_t> auto ReadFromFileSystem(Context & ctx, std::string filepath, const read_fn_t &read_fn) { using read_result_t = typename FunctionTraits<read_fn_t>::result_type; using ReadResultNode = ReadNode<read_result_t, read_fn_t>; auto shared_node = std::make_shared<ReadResultNode>(ctx, read_fn, filepath); auto read_stack = shared_node->ProduceStack(); return DIARef<read_result_t, decltype(read_stack)> (std::move(shared_node), read_stack); } } // namespace c7a #endif // !C7A_API_DIA_HEADER /******************************************************************************/ <commit_msg>added doc to WriteToFileSystem<commit_after>/******************************************************************************* * c7a/api/dia.hpp * * Interface for Operations, holds pointer to node and lambda from node to state * * Part of Project c7a. * * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #pragma once #ifndef C7A_API_DIA_HEADER #define C7A_API_DIA_HEADER #include <functional> #include <vector> #include <stack> #include <iostream> #include <fstream> #include <cassert> #include <memory> #include <unordered_map> #include <string> #include <utility> #include "dia_node.hpp" #include "function_traits.hpp" #include "lop_node.hpp" #include "zip_node.hpp" #include "read_node.hpp" #include "reduce_node.hpp" #include "context.hpp" #include "write_node.hpp" namespace c7a { //! \addtogroup api Interface //! \{ /*! * DIARef is the interface between the user and the c7a framework. A DIARef can * be imagined as an immutable array, even though the data does not need to be * materialized at all. A DIARef contains a pointer to a DIANode of type T, * which represents the state after the previous DOp or Action. Additionally, a * DIARef stores the local lambda function chain of type Stack, which can transform * elements of the DIANode to elements of this DIARef. DOps/Actions create a * DIARef and a new DIANode, to which the DIARef links to. LOps only create a * new DIARef, which link to the previous DIANode. * * \tparam T Type of elements in this DIARef. * * \tparam Stack Type of the function chain. */ template <typename T, typename Stack = FunctionStack<> > class DIARef { friend class Context; using DIANodePtr = std::shared_ptr<DIANode<T> >; public: /*! * Constructor of a new DIARef with a pointer to a DIANode and a * function chain from the DIANode to this DIARef. * * \param node Pointer to the last DIANode, DOps and Actions create a new * DIANode, LOps link to the DIANode of the previous DIARef. * * \param stack Function stack consisting of functions between last DIANode * and this DIARef. */ DIARef(DIANodePtr& node, Stack& stack) : node_(node), local_stack_(stack) { } /*! * Constructor of a new DIARef supporting move semantics of nodes. * * \param node Pointer to the last DIANode, DOps and Actions create a new * DIANode, LOps link to the DIANode of the previous DIARef. * * \param stack Function stack consisting of functions between last DIANode * and this DIARef. */ DIARef(DIANodePtr&& node, Stack& stack) : node_(std::move(node)), local_stack_(stack) { } /*! * Copy-Constructor of a DIARef with empty function chain * from a DIARef with a non-empty chain. * The functionality of the chain is stored in a newly created LOpNode. * The current DIARef than points to this LOpNode. * This is needed to support assignment operations between DIARef's. * * \param rhs DIA containing a non-empty function chain. */ template <typename AnyStack> DIARef(const DIARef<T, AnyStack>& rhs) { // Create new LOpNode // Transfer stack from rhs to LOpNode // Build new DIARef with empty stack and LOpNode auto rhs_node = std::move(rhs.get_node()); auto rhs_stack = rhs.get_stack(); using LOpChainNode = LOpNode<T, decltype(rhs_stack)>; auto shared_node = std::make_shared<LOpChainNode>(rhs_node->get_context(), rhs_node, rhs_stack); node_ = std::move(shared_node); local_stack_ = FunctionStack<>(); } /*! * Returns a pointer to the according DIANode. */ DIANode<T> * get_node() const { return node_.get(); } /*! * Returns the number of references to the according DIANode. */ int get_node_count() const { return node_.use_count(); } /*! * Returns the stored function chain. */ Stack & get_stack() { return local_stack_; } /*! * Map is a LOp, which maps this DIARef according to the map_fn given by the * user. The map_fn maps each element to another * element of a possibly different type. The DIARef returned by Map has the * same type T. The function chain of the returned DIARef is this DIARef's * local_stack_ chained with map_fn. * * \tparam map_fn_t Type of the map function. * * \param map_fn Map function of type map_fn_t, which maps each element to * an element of a possibly different type. * */ template <typename map_fn_t> auto Map(const map_fn_t &map_fn) { using map_arg_t = typename FunctionTraits<map_fn_t>::template arg<0>; using map_result_t = typename FunctionTraits<map_fn_t>::result_type; auto conv_map_fn = [=](map_arg_t input, std::function<void(map_result_t)> emit_func) { emit_func(map_fn(input)); }; auto new_stack = local_stack_.push(conv_map_fn); return DIARef<T, decltype(new_stack)>(node_, new_stack); } /*! * Filter is a LOp, which filters elements from this DIARef * according to the filter_fn given by the * user. The filter_fn maps each element to a boolean. * The DIARef returned by Filter has the same type T. * The function chain of the returned DIARef is this DIARef's * local_stack_ chained with filter_fn. * * \tparam filter_fn_t Type of the map function. * * \param filter_fn Filter function of type filter_fn_t, which maps each element to * a boolean. * */ template <typename filter_fn_t> auto Filter(const filter_fn_t &filter_fn) { using filter_arg_t = typename FunctionTraits<filter_fn_t>::template arg<0>; auto conv_filter_fn = [=](filter_arg_t input, std::function<void(filter_arg_t)> emit_func) { if (filter_fn(input)) emit_func(input); }; auto new_stack = local_stack_.push(conv_filter_fn); return DIARef<T, decltype(new_stack)>(node_, new_stack); } /*! * FlatMap is a LOp, which maps this DIARef according to the flatmap_fn * given by the user. The flatmap_fn maps each element * to elements of a possibly different type. The flatmap_fn has an emitter * function as it's second parameter. This emitter is called once for each * element to be emitted. The DIARef returned by FlatMap has the same type * T. The function chain of the returned DIARef is this DIARef's * local_stack_ chained with flatmap_fn. * * \tparam flatmap_fn_t Type of the map function. * * \param flatmap_fn Map function of type map_fn_t, which maps each element * to elements of a possibly different type. */ template <typename flatmap_fn_t> auto FlatMap(const flatmap_fn_t &flatmap_fn) { auto new_stack = local_stack_.push(flatmap_fn); return DIARef<T, decltype(new_stack)>(node_, new_stack); } /*! * Reduce is a DOp, which groups elements of the DIARef with the * key_extractor and reduces each key-bucket to a single element using the * associative reduce_function. The reduce_function defines how two elements * can be reduced to a single element of equal type. Since Reduce is a DOp, it * creates a new DIANode. The DIARef returned by Reduce links to this newly * created DIANode. The local_stack_ of the returned DIARef consists of * the PostOp of Reduce, as a reduced element can * directly be chained to the following LOps. * * \tparam key_extr_fn_t Type of the key_extractor function. * The key_extractor function is equal to a map function. * * \param key_extractor Key extractor function, which maps each element to a * key of possibly different type. * */ template <typename key_extr_fn_t> auto ReduceBy(const key_extr_fn_t &key_extractor) { return ReduceSugar<key_extr_fn_t>(key_extractor, node_.get(), local_stack_); } /*! * Zip is a DOp, which Zips two DIAs in style of functional programming. The * zip_function is used to zip the i-th elements of both input DIAs together * to form the i-th element of the output DIARef. The type of the output * DIARef can be inferred from the zip_function. * * \tparam zip_fn_t Type of the zip_function. This is a function with two * input elements, both of the local type, and one output element, which is * the type of the Zip node. * * \param zip_fn Zip function, which zips two elements together * * \param second_dia DIARef, which is zipped together with the original * DIARef. */ template <typename zip_fn_t, typename second_dia_t> auto Zip(const zip_fn_t &zip_fn, second_dia_t second_dia) { using zip_result_t = typename FunctionTraits<zip_fn_t>::result_type; using zip_arg_0_t = typename FunctionTraits<zip_fn_t>::template arg<0>; using zip_arg_1_t = typename FunctionTraits<zip_fn_t>::template arg<1>; using ZipResultNode = TwoZipNode<zip_arg_0_t, zip_arg_1_t, zip_result_t, decltype(local_stack_), decltype(second_dia.get_stack()), zip_fn_t>; auto shared_node = std::make_shared<ZipResultNode>(node_->get_context(), node_.get(), second_dia.get_node(), local_stack_, second_dia.get_stack(), zip_fn); auto zip_stack = shared_node->ProduceStack(); return DIARef<zip_result_t, decltype(zip_stack)> (std::move(shared_node), zip_stack); } /*! * WriteToFileSystem is an Action, which writes elements to an output file. A * provided function is used prepare the elements before written. * * \tparam write_fn_t Type of the write_function. This is a function with one * input element of the local type. * * \param write_fn Write function, which prepares an element to be written to disk. * * \param filepath Destination of the output file. */ template <typename write_fn_t> void WriteToFileSystem(std::string filepath, const write_fn_t &write_fn) { using write_result_t = typename FunctionTraits<write_fn_t>::result_type; using WriteResultNode = WriteNode<T, write_result_t, write_fn_t>; auto shared_node = std::make_shared<WriteResultNode>(node_->get_context(), node_.get(), write_fn, filepath); shared_node->ProduceStack(); } /*! * Returns Chuck Norris! * * \return Chuck Norris */ const std::vector<T> & evil_get_data() const { return (std::vector<T>{ T() }); } /*! * Returns the string which defines the DIANode node_. * * \return The string of node_ */ std::string NodeString() { return node_->ToString(); } /*! * Prints the DIANode and all it's children recursively. The printing is * performed tree-style. */ void PrintNodes() { using BasePair = std::pair<DIABase*, int>; std::stack<BasePair> dia_stack; dia_stack.push(std::make_pair(node_, 0)); while (!dia_stack.empty()) { auto curr = dia_stack.top(); auto node = curr.first; int depth = curr.second; dia_stack.pop(); auto is_end = true; if (!dia_stack.empty()) is_end = dia_stack.top().second < depth; for (int i = 0; i < depth - 1; ++i) { std::cout << "│ "; } if (is_end && depth > 0) std::cout << "└── "; else if (depth > 0) std::cout << "├── "; std::cout << node->ToString() << std::endl; auto children = node->get_childs(); for (auto c : children) { dia_stack.push(std::make_pair(c, depth + 1)); } } } private: //! The DIANode which DIARef points to. The node represents the latest DOp //! or Action performed previously. DIANodePtr node_; //! The local function chain, which stores the chained lambda function from //! the last DIANode to this DIARef. Stack local_stack_; /*! * Syntactic sugaaah for reduce */ template <typename key_extr_fn_t> class ReduceSugar { public: ReduceSugar(const key_extr_fn_t& key_extractor, DIANode<T>* node, Stack& local_stack) : key_extractor_(key_extractor), node_(node), local_stack_(local_stack) { } /*! * Syntactic sugaaah * * \tparam reduce_fn_t Type of the reduce_function. This is a function * reducing two elements of L's result type to a single element of equal * type. * * \param reduce_function Reduce function, which defines how the key * buckets are reduced to a single element. This function is applied * associative but not necessarily commutative. * */ template <typename reduce_fn_t> auto With(const reduce_fn_t &reduce_function) { using dop_result_t = typename FunctionTraits<reduce_fn_t>::result_type; using ReduceResultNode = ReduceNode<T, dop_result_t, decltype(local_stack_), key_extr_fn_t, reduce_fn_t>; auto shared_node = std::make_shared<ReduceResultNode>(node_->get_context(), node_, local_stack_, key_extractor_, reduce_function); auto reduce_stack = shared_node->ProduceStack(); return DIARef<dop_result_t, decltype(reduce_stack)> (std::move(shared_node), reduce_stack); } private: const key_extr_fn_t& key_extractor_; DIANode<T>* node_; Stack& local_stack_; }; }; //! \} template <typename read_fn_t> auto ReadFromFileSystem(Context & ctx, std::string filepath, const read_fn_t &read_fn) { using read_result_t = typename FunctionTraits<read_fn_t>::result_type; using ReadResultNode = ReadNode<read_result_t, read_fn_t>; auto shared_node = std::make_shared<ReadResultNode>(ctx, read_fn, filepath); auto read_stack = shared_node->ProduceStack(); return DIARef<read_result_t, decltype(read_stack)> (std::move(shared_node), read_stack); } } // namespace c7a #endif // !C7A_API_DIA_HEADER /******************************************************************************/ <|endoftext|>
<commit_before>/**************************************************************************** ** Meta object code from reading C++ file 'LogDock.h' ** ** Created by: The Qt Meta Object Compiler version 63 (Qt 4.8.5) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "src/Widgets/LogDock.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'LogDock.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 63 #error "This file was generated using the moc from 4.8.5. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_LogDock[] = { // content: 6, // revision 0, // classname 0, 0, // classinfo 0, 0, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount 0 // eod }; static const char qt_meta_stringdata_LogDock[] = { "LogDock\0" }; void LogDock::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { Q_UNUSED(_o); Q_UNUSED(_id); Q_UNUSED(_c); Q_UNUSED(_a); } const QMetaObjectExtraData LogDock::staticMetaObjectExtraData = { 0, qt_static_metacall }; const QMetaObject LogDock::staticMetaObject = { { &QDockWidget::staticMetaObject, qt_meta_stringdata_LogDock, qt_meta_data_LogDock, &staticMetaObjectExtraData } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &LogDock::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *LogDock::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *LogDock::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_LogDock)) return static_cast<void*>(const_cast< LogDock*>(this)); return QDockWidget::qt_metacast(_clname); } int LogDock::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QDockWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; return _id; } QT_END_MOC_NAMESPACE <commit_msg>Delete moc_LogDock.cpp<commit_after><|endoftext|>
<commit_before>/* * Copyright 2015-2017 Two Pore Guys, Inc. * All rights reserved * * Redistribution and use in source and binary forms, with or without * modification, are permitted providing that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ #include "catch.hpp" #include <rpc/object.h> #include "../src/internal.h" #include <glib/gprintf.h> SCENARIO("RPC_NULL_OBJECT", "Create a NULL RPC object and perform basic operations on it") { GIVEN("BOOL object") { rpc_object_t object; rpc_object_t copy; object = rpc_null_create(); THEN("Type is NULL") { REQUIRE(rpc_get_type(object) == RPC_TYPE_NULL); } AND_THEN("Refcount equals 1") { REQUIRE(object->ro_refcnt == 1); } WHEN("Object's copy is created") { copy = rpc_copy(object); THEN("Source and copy are equal"){ REQUIRE(rpc_equal(object, copy)); } } WHEN("reference count is incremented") { rpc_retain(object); THEN("reference count equals 2"){ REQUIRE(object->ro_refcnt == 2); } AND_WHEN("reference count is decremented") { rpc_release(object); THEN("reference count equals 1") { REQUIRE(object->ro_refcnt == 1); } AND_WHEN("reference count reaches 0") { rpc_release(object); THEN("RPC object pointer is NULL") { REQUIRE(object == NULL); } } } } } } SCENARIO("RPC_BOOL_OBJECT", "Create a BOOL RPC object and perform basic operations on it") { GIVEN("BOOL object") { rpc_object_t object; rpc_object_t different_object; rpc_object_t copy; bool value = true; bool different_value = false; object = rpc_bool_create(value); different_object = rpc_bool_create(different_value); THEN("Type is BOOL") { REQUIRE(rpc_get_type(object) == RPC_TYPE_BOOL); } THEN("Refcount equals 1") { REQUIRE(object->ro_refcnt == 1); } THEN("Extracted value matches") { REQUIRE(rpc_bool_get_value(object) == value); } AND_THEN("Direct value matches") { REQUIRE(object->ro_value.rv_b == value); } WHEN("Object's copy is created") { copy = rpc_copy(object); THEN("Source and copy are equal"){ REQUIRE(rpc_equal(object, copy)); } AND_THEN("Object is different from object initialized with different value") { REQUIRE(!rpc_equal(object, different_object)); } } WHEN("reference count is incremented") { rpc_retain(object); THEN("reference count equals 2"){ REQUIRE(object->ro_refcnt == 2); } AND_WHEN("reference count is decremented") { rpc_release(object); THEN("reference count equals 1") { REQUIRE(object->ro_refcnt == 1); } AND_WHEN("reference count reaches 0") { rpc_release(object); THEN("RPC object pointer is NULL") { REQUIRE(object == NULL); } } } } rpc_release(different_object); } } SCENARIO("RPC_UINT64_OBJECT", "Create a UINT64 RPC object and perform basic operations on it") { GIVEN("UINT64 object") { rpc_object_t object; rpc_object_t different_object; rpc_object_t copy; uint64_t value = 1234; uint64_t different_value = 5678; object = rpc_uint64_create(value); different_object = rpc_uint64_create(different_value); THEN("Type is UINT64") { REQUIRE(rpc_get_type(object) == RPC_TYPE_UINT64); } THEN("Refcount equals 1") { REQUIRE(object->ro_refcnt == 1); } THEN("Extracted value matches") { REQUIRE(rpc_uint64_get_value(object) == value); } AND_THEN("Direct value matches") { REQUIRE(object->ro_value.rv_ui == value); } WHEN("Object's copy is created") { copy = rpc_copy(object); THEN("Source and copy are equal"){ REQUIRE(rpc_equal(object, copy)); } AND_THEN("Object is different from object initialized with different value") { REQUIRE(!rpc_equal(object, different_object)); } } WHEN("reference count is incremented") { rpc_retain(object); THEN("reference count equals 2"){ REQUIRE(object->ro_refcnt == 2); } AND_WHEN("reference count is decremented") { rpc_release(object); THEN("reference count equals 1") { REQUIRE(object->ro_refcnt == 1); } AND_WHEN("reference count reaches 0") { rpc_release(object); THEN("RPC object pointer is NULL") { REQUIRE(object == NULL); } } } } rpc_release(different_object); } } SCENARIO("RPC_INT64_OBJECT", "Create a INT64 RPC object and perform basic operations on it") { GIVEN("INT64 object") { rpc_object_t object; rpc_object_t different_object; rpc_object_t copy; int64_t value = 1234; int64_t different_value = -1234; object = rpc_int64_create(value); different_object = rpc_int64_create(different_value); THEN("Type is INT64") { REQUIRE(rpc_get_type(object) == RPC_TYPE_INT64); } THEN("Refcount equals 1") { REQUIRE(object->ro_refcnt == 1); } THEN("Extracted value matches") { REQUIRE(rpc_int64_get_value(object) == value); } AND_THEN("Direct value matches") { REQUIRE(object->ro_value.rv_i == value); } WHEN("Object's copy is created") { copy = rpc_copy(object); THEN("Source and copy are equal"){ REQUIRE(rpc_equal(object, copy)); } AND_THEN("Object is different from object initialized with different value") { REQUIRE(!rpc_equal(object, different_object)); } } WHEN("reference count is incremented") { rpc_retain(object); THEN("reference count equals 2"){ REQUIRE(object->ro_refcnt == 2); } AND_WHEN("reference count is decremented") { rpc_release(object); THEN("reference count equals 1") { REQUIRE(object->ro_refcnt == 1); } AND_WHEN("reference count reaches 0") { rpc_release(object); THEN("RPC object pointer is NULL") { REQUIRE(object == NULL); } } } } rpc_release(different_object); } } SCENARIO("RPC_DOUBLE_OBJECT", "Create a DOUBLE RPC object and perform basic operations on it") { GIVEN("DOUBLE object") { rpc_object_t object; rpc_object_t different_object; rpc_object_t copy; double value = 12.34; double different_value = -12.34; object = rpc_double_create(value); different_object = rpc_double_create(different_value); THEN("Type is DOUBLE") { REQUIRE(rpc_get_type(object) == RPC_TYPE_DOUBLE); } THEN("Refcount equals 1") { REQUIRE(object->ro_refcnt == 1); } THEN("Extracted value matches") { REQUIRE(rpc_double_get_value(object) == value); } AND_THEN("Direct value matches") { REQUIRE(object->ro_value.rv_d == value); } WHEN("Object's copy is created") { copy = rpc_copy(object); THEN("Source and copy are equal"){ REQUIRE(rpc_equal(object, copy)); } AND_THEN("Object is different from object initialized with different value") { REQUIRE(!rpc_equal(object, different_object)); } } WHEN("reference count is incremented") { rpc_retain(object); THEN("reference count equals 2"){ REQUIRE(object->ro_refcnt == 2); } AND_WHEN("reference count is decremented") { rpc_release(object); THEN("reference count equals 1") { REQUIRE(object->ro_refcnt == 1); } AND_WHEN("reference count reaches 0") { rpc_release(object); THEN("RPC object pointer is NULL") { REQUIRE(object == NULL); } } } } rpc_release(different_object); } } SCENARIO("RPC_DESCRIPTION_TEST", "Create a tree of RPC objects and print their description") { GIVEN("RPC objects tree") { int data = 0xff00ff00; static const char *referene = "<dictionary> {\n" " null_val: <null> ,\n" " array: <array> [\n" " 0: <null> ,\n" " 1: <bool> true,\n" " 2: <uint64> 1234,\n" " 3: <int64> -1234,\n" " 4: <double> 12.340000,\n" " 5: <date> 1970-01-01 00:00:00,\n" " 6: <string> \"test string\",\n" " 7: <binary> 00ff00ff,\n" " 8: <fd> 10,\n" " ],\n" " test_string2: <string> \"test_test_test\",\n" "}\n"; rpc_object_t null = rpc_null_create(); rpc_object_t boolean = rpc_bool_create(true); rpc_object_t u_integer = rpc_uint64_create(1234); rpc_object_t integer = rpc_int64_create(-1234); rpc_object_t dbl = rpc_double_create(12.34); rpc_object_t date = rpc_date_create(0); rpc_object_t string = rpc_string_create("test string"); rpc_object_t binary = rpc_data_create(&data, sizeof(data), false); rpc_object_t fd = rpc_fd_create(10); rpc_object_t dict = rpc_dictionary_create(); rpc_object_t array = rpc_array_create(); rpc_array_append_stolen_value(array, null); rpc_array_append_stolen_value(array, boolean); rpc_array_append_stolen_value(array, u_integer); rpc_array_append_stolen_value(array, integer); rpc_array_append_stolen_value(array, dbl); rpc_array_append_stolen_value(array, date); rpc_array_append_stolen_value(array, string); rpc_array_append_stolen_value(array, binary); rpc_array_append_stolen_value(array, fd); rpc_dictionary_set_value(dict, "null_val", null); rpc_dictionary_set_value(dict, "array", array); rpc_dictionary_set_string(dict, "test_string2", "test_test_test"); THEN("Parent RPC object's description is equal to refrence description") { REQUIRE(g_strcmp0(referene, rpc_copy_description(dict)) == 0); } } } <commit_msg>FIXED: make sure to free memory in tests<commit_after>/* * Copyright 2015-2017 Two Pore Guys, Inc. * All rights reserved * * Redistribution and use in source and binary forms, with or without * modification, are permitted providing that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ #include "catch.hpp" #include <rpc/object.h> #include "../src/internal.h" SCENARIO("RPC_NULL_OBJECT", "Create a NULL RPC object and perform basic operations on it") { GIVEN("BOOL object") { rpc_object_t object; rpc_object_t copy; object = rpc_null_create(); THEN("Type is NULL") { REQUIRE(rpc_get_type(object) == RPC_TYPE_NULL); } AND_THEN("Refcount equals 1") { REQUIRE(object->ro_refcnt == 1); } WHEN("Object's copy is created") { copy = rpc_copy(object); THEN("Source and copy are equal"){ REQUIRE(rpc_equal(object, copy)); } } WHEN("reference count is incremented") { rpc_retain(object); THEN("reference count equals 2"){ REQUIRE(object->ro_refcnt == 2); } AND_WHEN("reference count is decremented") { rpc_release(object); THEN("reference count equals 1") { REQUIRE(object->ro_refcnt == 1); } AND_WHEN("reference count reaches 0") { rpc_release(object); THEN("RPC object pointer is NULL") { REQUIRE(object == NULL); } } } } } } SCENARIO("RPC_BOOL_OBJECT", "Create a BOOL RPC object and perform basic operations on it") { GIVEN("BOOL object") { rpc_object_t object; rpc_object_t different_object; rpc_object_t copy; bool value = true; bool different_value = false; object = rpc_bool_create(value); different_object = rpc_bool_create(different_value); THEN("Type is BOOL") { REQUIRE(rpc_get_type(object) == RPC_TYPE_BOOL); } THEN("Refcount equals 1") { REQUIRE(object->ro_refcnt == 1); } THEN("Extracted value matches") { REQUIRE(rpc_bool_get_value(object) == value); } AND_THEN("Direct value matches") { REQUIRE(object->ro_value.rv_b == value); } WHEN("Object's copy is created") { copy = rpc_copy(object); THEN("Source and copy are equal"){ REQUIRE(rpc_equal(object, copy)); } AND_THEN("Object is different from object initialized with different value") { REQUIRE(!rpc_equal(object, different_object)); } } WHEN("reference count is incremented") { rpc_retain(object); THEN("reference count equals 2"){ REQUIRE(object->ro_refcnt == 2); } AND_WHEN("reference count is decremented") { rpc_release(object); THEN("reference count equals 1") { REQUIRE(object->ro_refcnt == 1); } AND_WHEN("reference count reaches 0") { rpc_release(object); THEN("RPC object pointer is NULL") { REQUIRE(object == NULL); } } } } rpc_release(different_object); } } SCENARIO("RPC_UINT64_OBJECT", "Create a UINT64 RPC object and perform basic operations on it") { GIVEN("UINT64 object") { rpc_object_t object; rpc_object_t different_object; rpc_object_t copy; uint64_t value = 1234; uint64_t different_value = 5678; object = rpc_uint64_create(value); different_object = rpc_uint64_create(different_value); THEN("Type is UINT64") { REQUIRE(rpc_get_type(object) == RPC_TYPE_UINT64); } THEN("Refcount equals 1") { REQUIRE(object->ro_refcnt == 1); } THEN("Extracted value matches") { REQUIRE(rpc_uint64_get_value(object) == value); } AND_THEN("Direct value matches") { REQUIRE(object->ro_value.rv_ui == value); } WHEN("Object's copy is created") { copy = rpc_copy(object); THEN("Source and copy are equal"){ REQUIRE(rpc_equal(object, copy)); } AND_THEN("Object is different from object initialized with different value") { REQUIRE(!rpc_equal(object, different_object)); } } WHEN("reference count is incremented") { rpc_retain(object); THEN("reference count equals 2"){ REQUIRE(object->ro_refcnt == 2); } AND_WHEN("reference count is decremented") { rpc_release(object); THEN("reference count equals 1") { REQUIRE(object->ro_refcnt == 1); } AND_WHEN("reference count reaches 0") { rpc_release(object); THEN("RPC object pointer is NULL") { REQUIRE(object == NULL); } } } } rpc_release(different_object); } } SCENARIO("RPC_INT64_OBJECT", "Create a INT64 RPC object and perform basic operations on it") { GIVEN("INT64 object") { rpc_object_t object; rpc_object_t different_object; rpc_object_t copy; int64_t value = 1234; int64_t different_value = -1234; object = rpc_int64_create(value); different_object = rpc_int64_create(different_value); THEN("Type is INT64") { REQUIRE(rpc_get_type(object) == RPC_TYPE_INT64); } THEN("Refcount equals 1") { REQUIRE(object->ro_refcnt == 1); } THEN("Extracted value matches") { REQUIRE(rpc_int64_get_value(object) == value); } AND_THEN("Direct value matches") { REQUIRE(object->ro_value.rv_i == value); } WHEN("Object's copy is created") { copy = rpc_copy(object); THEN("Source and copy are equal"){ REQUIRE(rpc_equal(object, copy)); } AND_THEN("Object is different from object initialized with different value") { REQUIRE(!rpc_equal(object, different_object)); } } WHEN("reference count is incremented") { rpc_retain(object); THEN("reference count equals 2"){ REQUIRE(object->ro_refcnt == 2); } AND_WHEN("reference count is decremented") { rpc_release(object); THEN("reference count equals 1") { REQUIRE(object->ro_refcnt == 1); } AND_WHEN("reference count reaches 0") { rpc_release(object); THEN("RPC object pointer is NULL") { REQUIRE(object == NULL); } } } } rpc_release(different_object); } } SCENARIO("RPC_DOUBLE_OBJECT", "Create a DOUBLE RPC object and perform basic operations on it") { GIVEN("DOUBLE object") { rpc_object_t object; rpc_object_t different_object; rpc_object_t copy; double value = 12.34; double different_value = -12.34; object = rpc_double_create(value); different_object = rpc_double_create(different_value); THEN("Type is DOUBLE") { REQUIRE(rpc_get_type(object) == RPC_TYPE_DOUBLE); } THEN("Refcount equals 1") { REQUIRE(object->ro_refcnt == 1); } THEN("Extracted value matches") { REQUIRE(rpc_double_get_value(object) == value); } AND_THEN("Direct value matches") { REQUIRE(object->ro_value.rv_d == value); } WHEN("Object's copy is created") { copy = rpc_copy(object); THEN("Source and copy are equal"){ REQUIRE(rpc_equal(object, copy)); } AND_THEN("Object is different from object initialized with different value") { REQUIRE(!rpc_equal(object, different_object)); } } WHEN("reference count is incremented") { rpc_retain(object); THEN("reference count equals 2"){ REQUIRE(object->ro_refcnt == 2); } AND_WHEN("reference count is decremented") { rpc_release(object); THEN("reference count equals 1") { REQUIRE(object->ro_refcnt == 1); } AND_WHEN("reference count reaches 0") { rpc_release(object); THEN("RPC object pointer is NULL") { REQUIRE(object == NULL); } } } } rpc_release(different_object); } } SCENARIO("RPC_DESCRIPTION_TEST", "Create a tree of RPC objects and print their description") { GIVEN("RPC objects tree") { int data = 0xff00ff00; static const char *referene = "<dictionary> {\n" " null_val: <null> ,\n" " array: <array> [\n" " 0: <null> ,\n" " 1: <bool> true,\n" " 2: <uint64> 1234,\n" " 3: <int64> -1234,\n" " 4: <double> 12.340000,\n" " 5: <date> 1970-01-01 00:00:00,\n" " 6: <string> \"test string\",\n" " 7: <binary> 00ff00ff,\n" " 8: <fd> 10,\n" " ],\n" " test_string2: <string> \"test_test_test\",\n" "}\n"; rpc_object_t null = rpc_null_create(); rpc_object_t boolean = rpc_bool_create(true); rpc_object_t u_integer = rpc_uint64_create(1234); rpc_object_t integer = rpc_int64_create(-1234); rpc_object_t dbl = rpc_double_create(12.34); rpc_object_t date = rpc_date_create(0); rpc_object_t string = rpc_string_create("test string"); rpc_object_t binary = rpc_data_create(&data, sizeof(data), false); rpc_object_t fd = rpc_fd_create(10); rpc_object_t dict = rpc_dictionary_create(); rpc_object_t array = rpc_array_create(); rpc_array_append_stolen_value(array, null); rpc_array_append_stolen_value(array, boolean); rpc_array_append_stolen_value(array, u_integer); rpc_array_append_stolen_value(array, integer); rpc_array_append_stolen_value(array, dbl); rpc_array_append_stolen_value(array, date); rpc_array_append_stolen_value(array, string); rpc_array_append_stolen_value(array, binary); rpc_array_append_stolen_value(array, fd); rpc_dictionary_set_value(dict, "null_val", null); rpc_dictionary_set_value(dict, "array", array); rpc_dictionary_set_string(dict, "test_string2", "test_test_test"); THEN("Parent RPC object's description is equal to refrence description") { REQUIRE(g_strcmp0(referene, rpc_copy_description(dict)) == 0); } rpc_release(dict); } } <|endoftext|>
<commit_before>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2011,2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include "global_id_generator.hpp" #include "exception.hpp" #include <cassert> #ifndef ATOMIC_I8_SUPPORT #include <pficommon/concurrent/lock.h> #include <pficommon/concurrent/mutex.h> #endif namespace jubatus { namespace common { class global_id_generator_impl { private: bool is_standalone_; uint64_t counter_; std::string path_; cshared_ptr<lock_service> ls_; #ifndef ATOMIC_I8_SUPPORT pfi::concurrent::mutex counter_mutex_; #endif public: global_id_generator_impl(): is_standalone_(true), counter_(0) {} global_id_generator_impl(bool is_standalone): is_standalone_(is_standalone), counter_(0) {} uint64_t generate() { if(is_standalone_){ #ifdef ATOMIC_I8_SUPPORT return __sync_fetch_and_add(&counter_, 1); #else pfi::concurrent::scoped_lock lk(counter_mutex_); return ++counter_; #endif }else{ #ifdef HAVE_ZOOKEEPER_H uint64_t res; if (ls_->create_id(path_, 0, res)) return res; else throw JUBATUS_EXCEPTION(jubatus::exception::runtime_error("Failed to create id")); #else // never reaches here assert(is_standalone_); return 0; // dummy to remove warning #endif } } void set_ls(cshared_ptr<lock_service>& ls, const std::string& path_prefix) { #ifdef HAVE_ZOOKEEPER_H if (!is_standalone_) { path_ = path_prefix + "/id_generator"; ls_ = ls; if (!ls_->create(path_)) throw JUBATUS_EXCEPTION(jubatus::exception::runtime_error("Failed to create global id generator") << jubatus::exception::error_api_func("lock_service::create") << jubatus::exception::error_message(path_)); } #endif } }; global_id_generator::global_id_generator(): pimpl_(new global_id_generator_impl()) {} global_id_generator::global_id_generator(bool is_standalone): pimpl_(new global_id_generator_impl(is_standalone)) {} global_id_generator::~global_id_generator() {} uint64_t global_id_generator::generate() { return pimpl_->generate(); } void global_id_generator::set_ls(cshared_ptr<lock_service>& ls, const std::string& path_prefix) { pimpl_->set_ls(ls, path_prefix); } }} <commit_msg>fix initial value of global_id_generator (fix #165)<commit_after>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2011,2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include "global_id_generator.hpp" #include "exception.hpp" #include <cassert> #ifndef ATOMIC_I8_SUPPORT #include <pficommon/concurrent/lock.h> #include <pficommon/concurrent/mutex.h> #endif namespace jubatus { namespace common { class global_id_generator_impl { private: bool is_standalone_; uint64_t counter_; std::string path_; cshared_ptr<lock_service> ls_; #ifndef ATOMIC_I8_SUPPORT pfi::concurrent::mutex counter_mutex_; #endif public: global_id_generator_impl(): is_standalone_(true), counter_(0) {} global_id_generator_impl(bool is_standalone): is_standalone_(is_standalone), counter_(0) {} uint64_t generate() { if(is_standalone_){ #ifdef ATOMIC_I8_SUPPORT return __sync_fetch_and_add(&counter_, 1); #else pfi::concurrent::scoped_lock lk(counter_mutex_); return counter_++; #endif }else{ #ifdef HAVE_ZOOKEEPER_H uint64_t res; if (ls_->create_id(path_, 0, res)) return res; else throw JUBATUS_EXCEPTION(jubatus::exception::runtime_error("Failed to create id")); #else // never reaches here assert(is_standalone_); return 0; // dummy to remove warning #endif } } void set_ls(cshared_ptr<lock_service>& ls, const std::string& path_prefix) { #ifdef HAVE_ZOOKEEPER_H if (!is_standalone_) { path_ = path_prefix + "/id_generator"; ls_ = ls; if (!ls_->create(path_)) throw JUBATUS_EXCEPTION(jubatus::exception::runtime_error("Failed to create global id generator") << jubatus::exception::error_api_func("lock_service::create") << jubatus::exception::error_message(path_)); } #endif } }; global_id_generator::global_id_generator(): pimpl_(new global_id_generator_impl()) {} global_id_generator::global_id_generator(bool is_standalone): pimpl_(new global_id_generator_impl(is_standalone)) {} global_id_generator::~global_id_generator() {} uint64_t global_id_generator::generate() { return pimpl_->generate(); } void global_id_generator::set_ls(cshared_ptr<lock_service>& ls, const std::string& path_prefix) { pimpl_->set_ls(ls, path_prefix); } }} <|endoftext|>
<commit_before>#include "invertebrate.h" Invertebrate::Invertebrate() { } bool Invertebrate::operator <(const Invertebrate& inv) const { return name < inv.name; } bool Invertebrate::operator >(const Invertebrate& inv) const { return name > inv.name; } bool Invertebrate::operator ==(const Invertebrate& inv) const { return name == inv.name; } QDataStream &operator<<(QDataStream &ds, const Invertebrate &obj) { ds << obj.commonName << obj.description << obj.family << obj.flyName << obj.genus << obj.imageFileLocal << obj.imageFileRemote << obj.imageIsReady << obj.imageIsUpToDate << obj.name; return ds; } QDataStream &operator>>(QDataStream &ds, Invertebrate &obj) { ds >> obj.commonName; ds >> obj.description; ds >> obj.family; ds >> obj.flyName; ds >> obj.genus; ds >> obj.imageFileLocal; ds >> obj.imageFileRemote; ds >> obj.imageIsReady; ds >> obj.imageIsUpToDate; ds >> obj.name; return ds; } QDebug operator<<(QDebug debug, const Invertebrate &invertebrate) { QDebugStateSaver saver(debug); QStringList list{invertebrate.name, invertebrate.commonName, invertebrate.description, invertebrate.family, invertebrate.flyName, invertebrate.genus, invertebrate.imageFileLocal, invertebrate.imageFileRemote}; debug.nospace() << "(" << list.join(", ") << ")"; return debug; } <commit_msg>Improved QDebug implmentation for Invertebrate<commit_after>#include "invertebrate.h" Invertebrate::Invertebrate() { } bool Invertebrate::operator <(const Invertebrate& inv) const { return name < inv.name; } bool Invertebrate::operator >(const Invertebrate& inv) const { return name > inv.name; } bool Invertebrate::operator ==(const Invertebrate& inv) const { return name == inv.name; } QDataStream &operator<<(QDataStream &ds, const Invertebrate &obj) { ds << obj.commonName << obj.description << obj.family << obj.flyName << obj.genus << obj.imageFileLocal << obj.imageFileRemote << obj.imageIsReady << obj.imageIsUpToDate << obj.name; return ds; } QDataStream &operator>>(QDataStream &ds, Invertebrate &obj) { ds >> obj.commonName; ds >> obj.description; ds >> obj.family; ds >> obj.flyName; ds >> obj.genus; ds >> obj.imageFileLocal; ds >> obj.imageFileRemote; ds >> obj.imageIsReady; ds >> obj.imageIsUpToDate; ds >> obj.name; return ds; } QDebug operator<<(QDebug debug, const Invertebrate &invertebrate) { QDebugStateSaver saver(debug); debug.nospace() << "(\n" << " commonName: " << invertebrate.commonName << ",\n" << " description: " << invertebrate.description << ",\n" << " family: " << invertebrate.family << ",\n" << " flyName: " << invertebrate.flyName << ",\n" << " genus: " << invertebrate.genus << ",\n" << " imageFileLocal: " << invertebrate.imageFileLocal << ",\n" << " imageFileRemote: " << invertebrate.imageFileRemote << ",\n" << " imageIsReady: " << invertebrate.imageIsReady << ",\n" << " imageIsUpToDate: " << invertebrate.imageIsUpToDate << ",\n" << " name: " << invertebrate.name << ",\n" << " order: " << invertebrate.order << "\n)"; return debug; } <|endoftext|>
<commit_before>/******************************************************************************* Licensed to the OpenCOR team under one or more contributor license agreements. See the NOTICE.txt file distributed with this work for additional information regarding copyright ownership. The OpenCOR team licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *******************************************************************************/ //============================================================================== // Single cell view widget //============================================================================== #include "cellmlfilemanager.h" #include "singlecellviewsimulationwidget.h" #include "singlecellviewwidget.h" //============================================================================== #include "ui_singlecellviewwidget.h" //============================================================================== namespace OpenCOR { namespace SingleCellView { //============================================================================== SingleCellViewWidget::SingleCellViewWidget(SingleCellViewPlugin *pPlugin, QWidget *pParent) : ViewWidget(pParent), mPlugin(pPlugin), mSimulationWidget(0), mSimulationWidgets(QMap<QString, SingleCellViewSimulationWidget *>()) { } //============================================================================== void SingleCellViewWidget::retranslateUi() { // Retranslate our simulation widgets foreach (SingleCellViewSimulationWidget *simulationWidget, mSimulationWidgets) simulationWidget->retranslateUi(); } //============================================================================== bool SingleCellViewWidget::contains(const QString &pFileName) const { // Return whether we know about the given file return mSimulationWidgets.contains(pFileName); } //============================================================================== void SingleCellViewWidget::initialize(const QString &pFileName) { // Retrieve the simulation widget associated with the given file, if any SingleCellViewSimulationWidget *oldSimulationWidget = mSimulationWidget; mSimulationWidget = mSimulationWidgets.value(pFileName); if (!mSimulationWidget) { // No simulation widget exists for the given file, so create one mSimulationWidget = new SingleCellViewSimulationWidget(mPlugin, this); // Keep track of our editing widget and add it to ourselves mSimulationWidgets.insert(pFileName, mSimulationWidget); layout()->addWidget(mSimulationWidget); } // Hide our previous simulation widget and show our new one mSimulationWidget->show(); if (oldSimulationWidget && (mSimulationWidget != oldSimulationWidget)) oldSimulationWidget->hide(); // Set our focus proxy to our 'new' simulation widget and make sure that the // latter immediately gets the focus setFocusProxy(mSimulationWidget); mSimulationWidget->setFocus(); } //============================================================================== void SingleCellViewWidget::finalize(const QString &pFileName) { // Remove the simulation widget, should there be one for the given file SingleCellViewSimulationWidget *simulationWidget = mSimulationWidgets.value(pFileName); if (simulationWidget) { // There is a simulation widget for the given file name, so delete it // and remove it from our list delete simulationWidget; mSimulationWidgets.remove(pFileName); // Reset our memory of the current editor, if needed if (simulationWidget == mSimulationWidget) mSimulationWidget = 0; } } //============================================================================== void SingleCellViewWidget::filePermissionsChanged(const QString &pFileName) { // The given file has been un/locked, so enable/disable parts of our GUI, // should the given file be managed SingleCellViewSimulationWidget *simulationWidget = mSimulationWidgets.value(pFileName); if (simulationWidget) simulationWidget->filePermissionsChanged(); } //============================================================================== void SingleCellViewWidget::fileReloaded(const QString &pFileName) { // The given file has been reloaded, so reload it, should it be managed if (contains(pFileName)) { finalize(pFileName); if (CellMLSupport::CellmlFileManager::instance()->isCellmlFile(pFileName)) initialize(pFileName); } } //============================================================================== void SingleCellViewWidget::fileRenamed(const QString &pOldFileName, const QString &pNewFileName) { // The given file has been renamed, so update our simulating widgets mapping SingleCellViewSimulationWidget *simulationWidget = mSimulationWidgets.value(pOldFileName); if (simulationWidget) { mSimulationWidgets.insert(pNewFileName, simulationWidget); mSimulationWidgets.remove(pOldFileName); } } //============================================================================== } // namespace SingleCellView } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <commit_msg>Single Cell view: some work on making the view more file specific (#590) [ci skip].<commit_after>/******************************************************************************* Licensed to the OpenCOR team under one or more contributor license agreements. See the NOTICE.txt file distributed with this work for additional information regarding copyright ownership. The OpenCOR team licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *******************************************************************************/ //============================================================================== // Single cell view widget //============================================================================== #include "cellmlfilemanager.h" #include "singlecellviewsimulationwidget.h" #include "singlecellviewwidget.h" //============================================================================== #include <QLayout> //============================================================================== namespace OpenCOR { namespace SingleCellView { //============================================================================== SingleCellViewWidget::SingleCellViewWidget(SingleCellViewPlugin *pPlugin, QWidget *pParent) : ViewWidget(pParent), mPlugin(pPlugin), mSimulationWidget(0), mSimulationWidgets(QMap<QString, SingleCellViewSimulationWidget *>()) { } //============================================================================== void SingleCellViewWidget::retranslateUi() { // Retranslate our simulation widgets foreach (SingleCellViewSimulationWidget *simulationWidget, mSimulationWidgets) simulationWidget->retranslateUi(); } //============================================================================== bool SingleCellViewWidget::contains(const QString &pFileName) const { // Return whether we know about the given file return mSimulationWidgets.contains(pFileName); } //============================================================================== void SingleCellViewWidget::initialize(const QString &pFileName) { // Retrieve the simulation widget associated with the given file, if any SingleCellViewSimulationWidget *oldSimulationWidget = mSimulationWidget; mSimulationWidget = mSimulationWidgets.value(pFileName); if (!mSimulationWidget) { // No simulation widget exists for the given file, so create one mSimulationWidget = new SingleCellViewSimulationWidget(mPlugin, this); // Keep track of our editing widget and add it to ourselves mSimulationWidgets.insert(pFileName, mSimulationWidget); layout()->addWidget(mSimulationWidget); } // Hide our previous simulation widget and show our new one mSimulationWidget->show(); if (oldSimulationWidget && (mSimulationWidget != oldSimulationWidget)) oldSimulationWidget->hide(); // Set our focus proxy to our 'new' simulation widget and make sure that the // latter immediately gets the focus setFocusProxy(mSimulationWidget); mSimulationWidget->setFocus(); } //============================================================================== void SingleCellViewWidget::finalize(const QString &pFileName) { // Remove the simulation widget, should there be one for the given file SingleCellViewSimulationWidget *simulationWidget = mSimulationWidgets.value(pFileName); if (simulationWidget) { // There is a simulation widget for the given file name, so delete it // and remove it from our list delete simulationWidget; mSimulationWidgets.remove(pFileName); // Reset our memory of the current editor, if needed if (simulationWidget == mSimulationWidget) mSimulationWidget = 0; } } //============================================================================== void SingleCellViewWidget::filePermissionsChanged(const QString &pFileName) { // The given file has been un/locked, so enable/disable parts of our GUI, // should the given file be managed SingleCellViewSimulationWidget *simulationWidget = mSimulationWidgets.value(pFileName); if (simulationWidget) simulationWidget->filePermissionsChanged(); } //============================================================================== void SingleCellViewWidget::fileReloaded(const QString &pFileName) { // The given file has been reloaded, so reload it, should it be managed if (contains(pFileName)) { finalize(pFileName); if (CellMLSupport::CellmlFileManager::instance()->isCellmlFile(pFileName)) initialize(pFileName); } } //============================================================================== void SingleCellViewWidget::fileRenamed(const QString &pOldFileName, const QString &pNewFileName) { // The given file has been renamed, so update our simulating widgets mapping SingleCellViewSimulationWidget *simulationWidget = mSimulationWidgets.value(pOldFileName); if (simulationWidget) { mSimulationWidgets.insert(pNewFileName, simulationWidget); mSimulationWidgets.remove(pOldFileName); } } //============================================================================== } // namespace SingleCellView } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <|endoftext|>
<commit_before>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE** * CONDOR Copyright Notice * * See LICENSE.TXT for additional notices and disclaimers. * * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department, * University of Wisconsin-Madison, Madison, WI. All Rights Reserved. * No use of the CONDOR Software Program Source Code is authorized * without the express consent of the CONDOR Team. For more information * contact: CONDOR Team, Attention: Professor Miron Livny, * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685, * (608) 262-0856 or miron@cs.wisc.edu. * * U.S. Government Rights Restrictions: Use, duplication, or disclosure * by the U.S. Government is subject to restrictions as set forth in * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and * (2) of Commercial Computer Software-Restricted Rights at 48 CFR * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison, * WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu. ****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/ #include "condor_common.h" #include <iostream.h> #include <stdio.h> #include <string.h> #if !defined(WIN32) #include <netinet/in.h> #endif #include "condor_query.h" #include "condor_attributes.h" #include "condor_collector.h" #include "condor_config.h" #include "condor_network.h" #include "condor_io.h" #include "condor_parser.h" #include "condor_adtypes.h" #include "condor_debug.h" #define XDR_ASSERT(x) {if (!(x)) return Q_COMMUNICATION_ERROR;} char *new_strdup (const char *); // The order and number of the elements of the following arrays *are* // important. (They follow the structure of the enumerations supplied // in the header file condor_query.h) const char *ScheddStringKeywords [] = { ATTR_NAME }; const char *ScheddIntegerKeywords [] = { ATTR_NUM_USERS, ATTR_IDLE_JOBS, ATTR_RUNNING_JOBS }; const char *ScheddFloatKeywords [] = { "" // add null string to avoid compiler error }; const char *StartdStringKeywords [] = { ATTR_NAME, ATTR_MACHINE, ATTR_ARCH, ATTR_OPSYS }; const char *StartdIntegerKeywords [] = { ATTR_MEMORY, ATTR_DISK }; const char *StartdFloatKeywords [] = { "" // add null string to avoid compiler error }; // normal ctor CondorQuery:: CondorQuery (AdTypes qType) { queryType = qType; switch (qType) { case STARTD_AD: query.setNumStringCats (STARTD_STRING_THRESHOLD); query.setNumIntegerCats(STARTD_INT_THRESHOLD); query.setNumFloatCats (STARTD_FLOAT_THRESHOLD); query.setIntegerKwList ((char **)StartdIntegerKeywords); query.setStringKwList ((char **)StartdStringKeywords); query.setFloatKwList ((char **)StartdFloatKeywords); command = QUERY_STARTD_ADS; break; case STARTD_PVT_AD: query.setNumStringCats (STARTD_STRING_THRESHOLD); query.setNumIntegerCats(STARTD_INT_THRESHOLD); query.setNumFloatCats (STARTD_FLOAT_THRESHOLD); query.setIntegerKwList ((char **)StartdIntegerKeywords); query.setStringKwList ((char **)StartdStringKeywords); query.setFloatKwList ((char **)StartdFloatKeywords); command = QUERY_STARTD_PVT_ADS; break; case SCHEDD_AD: query.setNumStringCats (SCHEDD_STRING_THRESHOLD); query.setNumIntegerCats(SCHEDD_INT_THRESHOLD); query.setNumFloatCats (SCHEDD_FLOAT_THRESHOLD); query.setIntegerKwList ((char **)ScheddIntegerKeywords); query.setStringKwList ((char **)ScheddStringKeywords); query.setFloatKwList ((char **)ScheddFloatKeywords); command = QUERY_SCHEDD_ADS; break; case SUBMITTOR_AD: query.setNumStringCats (SCHEDD_STRING_THRESHOLD); query.setNumIntegerCats(SCHEDD_INT_THRESHOLD); query.setNumFloatCats (SCHEDD_FLOAT_THRESHOLD); query.setIntegerKwList ((char **)ScheddIntegerKeywords); query.setStringKwList ((char **)ScheddStringKeywords); query.setFloatKwList ((char **)ScheddFloatKeywords); command = QUERY_SUBMITTOR_ADS; break; case LICENSE_AD: query.setNumStringCats (0); query.setNumIntegerCats(0); query.setNumFloatCats (0); command = QUERY_LICENSE_ADS; break; case MASTER_AD: query.setNumStringCats (0); query.setNumIntegerCats(0); query.setNumFloatCats (0); command = QUERY_MASTER_ADS; break; case CKPT_SRVR_AD: query.setNumStringCats (0); query.setNumIntegerCats(0); query.setNumFloatCats (0); command = QUERY_CKPT_SRVR_ADS; break; case COLLECTOR_AD: query.setNumStringCats (0); query.setNumIntegerCats(0); query.setNumFloatCats (0); command = QUERY_COLLECTOR_ADS; break; default: command = -1; queryType = (AdTypes) -1; } } // copy ctor; makes deep copy CondorQuery:: CondorQuery (const CondorQuery &from) { } // dtor CondorQuery:: ~CondorQuery () { } // clear particular string category QueryResult CondorQuery:: clearStringConstraints (const int i) { return (QueryResult) query.clearString (i); } // clear particular integer category QueryResult CondorQuery:: clearIntegerConstraints (const int i) { return (QueryResult) query.clearInteger (i); } // clear particular float category QueryResult CondorQuery:: clearFloatConstraints (const int i) { return (QueryResult) query.clearFloat (i); } void CondorQuery:: clearCustomConstraints (void) { query.clearCustom (); } // add a string constraint QueryResult CondorQuery:: addConstraint (const int cat, const char *value) { return (QueryResult) query.addString (cat, (char *) value); } // add an integer constraint QueryResult CondorQuery:: addConstraint (const int cat, const int value) { return (QueryResult) query.addInteger (cat, value); } // add a float constraint QueryResult CondorQuery:: addConstraint (const int cat, const float value) { return (QueryResult) query.addFloat (cat, value); } // add a custom constraint QueryResult CondorQuery:: addConstraint (const char *value) { return (QueryResult) query.addCustom ((char *) value); } // fetch all ads from the collector that satisfy the constraints QueryResult CondorQuery:: fetchAds (ClassAdList &adList, const char *poolName) { char *pool; char defaultPool[32]; ReliSock sock; int more; QueryResult result; ClassAd queryAd, *ad; // use current pool's collector if not specified if (poolName == NULL || poolName[0] == '\0') { if ((pool = param ("COLLECTOR_HOST")) == NULL) { return Q_NO_COLLECTOR_HOST; } strcpy (defaultPool, pool); free (pool); pool = defaultPool; } else { // pool specified pool = (char *) poolName; } // make the query ad result = (QueryResult) query.makeQuery (queryAd); if (result != Q_OK) return result; // fix types queryAd.SetMyTypeName (QUERY_ADTYPE); switch (queryType) { case STARTD_AD: case STARTD_PVT_AD: queryAd.SetTargetTypeName (STARTD_ADTYPE); break; case SCHEDD_AD: case SUBMITTOR_AD: queryAd.SetTargetTypeName (SCHEDD_ADTYPE); break; case LICENSE_AD: queryAd.SetTargetTypeName (LICENSE_ADTYPE); break; case MASTER_AD: queryAd.SetTargetTypeName (MASTER_ADTYPE); break; case CKPT_SRVR_AD: queryAd.SetTargetTypeName (CKPT_SRVR_ADTYPE); break; case COLLECTOR_AD: queryAd.SetTargetTypeName (COLLECTOR_ADTYPE); break; default: return Q_INVALID_QUERY; } // contact collector if (!sock.connect(pool, COLLECTOR_COMM_PORT)) { return Q_COMMUNICATION_ERROR; } // ship query sock.encode(); if (!sock.code (command) || !queryAd.put (sock) || !sock.end_of_message()) { return Q_COMMUNICATION_ERROR; } // get result sock.decode (); more = 1; while (more) { if (!sock.code (more)) { sock.end_of_message(); return Q_COMMUNICATION_ERROR; } if (more) { ad = new ClassAd; if (!ad->get (sock)) { sock.end_of_message(); delete ad; return Q_COMMUNICATION_ERROR; } adList.Insert (ad); } } sock.end_of_message(); // finalize sock.close (); return (Q_OK); } QueryResult CondorQuery:: getQueryAd (ClassAd &queryAd) { QueryResult result; result = (QueryResult) query.makeQuery (queryAd); if (result != Q_OK) return result; // fix types queryAd.SetMyTypeName (QUERY_ADTYPE); switch (queryType) { case STARTD_AD: case STARTD_PVT_AD: queryAd.SetTargetTypeName (STARTD_ADTYPE); break; case SCHEDD_AD: case SUBMITTOR_AD: queryAd.SetTargetTypeName (SCHEDD_ADTYPE); break; case LICENSE_AD: queryAd.SetTargetTypeName (LICENSE_ADTYPE); break; case MASTER_AD: queryAd.SetTargetTypeName (MASTER_ADTYPE); break; case CKPT_SRVR_AD: queryAd.SetTargetTypeName (CKPT_SRVR_ADTYPE); break; case COLLECTOR_AD: queryAd.SetTargetTypeName (COLLECTOR_ADTYPE); break; default: return Q_INVALID_QUERY; } return Q_OK; } QueryResult CondorQuery:: filterAds (ClassAdList &in, ClassAdList &out) { ClassAd queryAd, *candidate; QueryResult result; // make the query ad result = (QueryResult) query.makeQuery (queryAd); if (result != Q_OK) return result; in.Open(); while (candidate = (ClassAd *) in.Next()) { // if a match occurs if ((*candidate) >= (queryAd)) out.Insert (candidate); } in.Close (); return Q_OK; } char *getStrQueryResult(QueryResult q) { switch (q) { case Q_OK: return "ok"; case Q_INVALID_CATEGORY: return "invalid category"; case Q_MEMORY_ERROR: return "memory error"; case Q_PARSE_ERROR: return "parse error"; case Q_COMMUNICATION_ERROR: return "communication error"; case Q_INVALID_QUERY: return "invalid query"; case Q_NO_COLLECTOR_HOST: return "no COLLECTOR_HOST"; default: return "unknown error"; } } <commit_msg>+ Use get_collector_addr() instead of doing things manually. + Removed some system header files we don't need.<commit_after>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE** * CONDOR Copyright Notice * * See LICENSE.TXT for additional notices and disclaimers. * * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department, * University of Wisconsin-Madison, Madison, WI. All Rights Reserved. * No use of the CONDOR Software Program Source Code is authorized * without the express consent of the CONDOR Team. For more information * contact: CONDOR Team, Attention: Professor Miron Livny, * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685, * (608) 262-0856 or miron@cs.wisc.edu. * * U.S. Government Rights Restrictions: Use, duplication, or disclosure * by the U.S. Government is subject to restrictions as set forth in * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and * (2) of Commercial Computer Software-Restricted Rights at 48 CFR * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison, * WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu. ****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/ #include "condor_common.h" #include "condor_query.h" #include "condor_attributes.h" #include "condor_collector.h" #include "condor_config.h" #include "condor_network.h" #include "condor_io.h" #include "condor_parser.h" #include "condor_adtypes.h" #include "condor_debug.h" #include "get_daemon_addr.h" #define XDR_ASSERT(x) {if (!(x)) return Q_COMMUNICATION_ERROR;} char *new_strdup (const char *); // The order and number of the elements of the following arrays *are* // important. (They follow the structure of the enumerations supplied // in the header file condor_query.h) const char *ScheddStringKeywords [] = { ATTR_NAME }; const char *ScheddIntegerKeywords [] = { ATTR_NUM_USERS, ATTR_IDLE_JOBS, ATTR_RUNNING_JOBS }; const char *ScheddFloatKeywords [] = { "" // add null string to avoid compiler error }; const char *StartdStringKeywords [] = { ATTR_NAME, ATTR_MACHINE, ATTR_ARCH, ATTR_OPSYS }; const char *StartdIntegerKeywords [] = { ATTR_MEMORY, ATTR_DISK }; const char *StartdFloatKeywords [] = { "" // add null string to avoid compiler error }; // normal ctor CondorQuery:: CondorQuery (AdTypes qType) { queryType = qType; switch (qType) { case STARTD_AD: query.setNumStringCats (STARTD_STRING_THRESHOLD); query.setNumIntegerCats(STARTD_INT_THRESHOLD); query.setNumFloatCats (STARTD_FLOAT_THRESHOLD); query.setIntegerKwList ((char **)StartdIntegerKeywords); query.setStringKwList ((char **)StartdStringKeywords); query.setFloatKwList ((char **)StartdFloatKeywords); command = QUERY_STARTD_ADS; break; case STARTD_PVT_AD: query.setNumStringCats (STARTD_STRING_THRESHOLD); query.setNumIntegerCats(STARTD_INT_THRESHOLD); query.setNumFloatCats (STARTD_FLOAT_THRESHOLD); query.setIntegerKwList ((char **)StartdIntegerKeywords); query.setStringKwList ((char **)StartdStringKeywords); query.setFloatKwList ((char **)StartdFloatKeywords); command = QUERY_STARTD_PVT_ADS; break; case SCHEDD_AD: query.setNumStringCats (SCHEDD_STRING_THRESHOLD); query.setNumIntegerCats(SCHEDD_INT_THRESHOLD); query.setNumFloatCats (SCHEDD_FLOAT_THRESHOLD); query.setIntegerKwList ((char **)ScheddIntegerKeywords); query.setStringKwList ((char **)ScheddStringKeywords); query.setFloatKwList ((char **)ScheddFloatKeywords); command = QUERY_SCHEDD_ADS; break; case SUBMITTOR_AD: query.setNumStringCats (SCHEDD_STRING_THRESHOLD); query.setNumIntegerCats(SCHEDD_INT_THRESHOLD); query.setNumFloatCats (SCHEDD_FLOAT_THRESHOLD); query.setIntegerKwList ((char **)ScheddIntegerKeywords); query.setStringKwList ((char **)ScheddStringKeywords); query.setFloatKwList ((char **)ScheddFloatKeywords); command = QUERY_SUBMITTOR_ADS; break; case LICENSE_AD: query.setNumStringCats (0); query.setNumIntegerCats(0); query.setNumFloatCats (0); command = QUERY_LICENSE_ADS; break; case MASTER_AD: query.setNumStringCats (0); query.setNumIntegerCats(0); query.setNumFloatCats (0); command = QUERY_MASTER_ADS; break; case CKPT_SRVR_AD: query.setNumStringCats (0); query.setNumIntegerCats(0); query.setNumFloatCats (0); command = QUERY_CKPT_SRVR_ADS; break; case COLLECTOR_AD: query.setNumStringCats (0); query.setNumIntegerCats(0); query.setNumFloatCats (0); command = QUERY_COLLECTOR_ADS; break; default: command = -1; queryType = (AdTypes) -1; } } // copy ctor; makes deep copy CondorQuery:: CondorQuery (const CondorQuery &from) { } // dtor CondorQuery:: ~CondorQuery () { } // clear particular string category QueryResult CondorQuery:: clearStringConstraints (const int i) { return (QueryResult) query.clearString (i); } // clear particular integer category QueryResult CondorQuery:: clearIntegerConstraints (const int i) { return (QueryResult) query.clearInteger (i); } // clear particular float category QueryResult CondorQuery:: clearFloatConstraints (const int i) { return (QueryResult) query.clearFloat (i); } void CondorQuery:: clearCustomConstraints (void) { query.clearCustom (); } // add a string constraint QueryResult CondorQuery:: addConstraint (const int cat, const char *value) { return (QueryResult) query.addString (cat, (char *) value); } // add an integer constraint QueryResult CondorQuery:: addConstraint (const int cat, const int value) { return (QueryResult) query.addInteger (cat, value); } // add a float constraint QueryResult CondorQuery:: addConstraint (const int cat, const float value) { return (QueryResult) query.addFloat (cat, value); } // add a custom constraint QueryResult CondorQuery:: addConstraint (const char *value) { return (QueryResult) query.addCustom ((char *) value); } // fetch all ads from the collector that satisfy the constraints QueryResult CondorQuery:: fetchAds (ClassAdList &adList, const char *poolName) { char *pool; char defaultPool[32]; ReliSock sock; int more; QueryResult result; ClassAd queryAd, *ad; // This will return the correct addr for the local pool's // collector if poolName is NULL. pool = get_collector_addr( poolName ); // make the query ad result = (QueryResult) query.makeQuery (queryAd); if (result != Q_OK) return result; // fix types queryAd.SetMyTypeName (QUERY_ADTYPE); switch (queryType) { case STARTD_AD: case STARTD_PVT_AD: queryAd.SetTargetTypeName (STARTD_ADTYPE); break; case SCHEDD_AD: case SUBMITTOR_AD: queryAd.SetTargetTypeName (SCHEDD_ADTYPE); break; case LICENSE_AD: queryAd.SetTargetTypeName (LICENSE_ADTYPE); break; case MASTER_AD: queryAd.SetTargetTypeName (MASTER_ADTYPE); break; case CKPT_SRVR_AD: queryAd.SetTargetTypeName (CKPT_SRVR_ADTYPE); break; case COLLECTOR_AD: queryAd.SetTargetTypeName (COLLECTOR_ADTYPE); break; default: return Q_INVALID_QUERY; } // contact collector if (!sock.connect(pool, COLLECTOR_COMM_PORT)) { return Q_COMMUNICATION_ERROR; } // ship query sock.encode(); if (!sock.code (command) || !queryAd.put (sock) || !sock.end_of_message()) { return Q_COMMUNICATION_ERROR; } // get result sock.decode (); more = 1; while (more) { if (!sock.code (more)) { sock.end_of_message(); return Q_COMMUNICATION_ERROR; } if (more) { ad = new ClassAd; if (!ad->get (sock)) { sock.end_of_message(); delete ad; return Q_COMMUNICATION_ERROR; } adList.Insert (ad); } } sock.end_of_message(); // finalize sock.close (); return (Q_OK); } QueryResult CondorQuery:: getQueryAd (ClassAd &queryAd) { QueryResult result; result = (QueryResult) query.makeQuery (queryAd); if (result != Q_OK) return result; // fix types queryAd.SetMyTypeName (QUERY_ADTYPE); switch (queryType) { case STARTD_AD: case STARTD_PVT_AD: queryAd.SetTargetTypeName (STARTD_ADTYPE); break; case SCHEDD_AD: case SUBMITTOR_AD: queryAd.SetTargetTypeName (SCHEDD_ADTYPE); break; case LICENSE_AD: queryAd.SetTargetTypeName (LICENSE_ADTYPE); break; case MASTER_AD: queryAd.SetTargetTypeName (MASTER_ADTYPE); break; case CKPT_SRVR_AD: queryAd.SetTargetTypeName (CKPT_SRVR_ADTYPE); break; case COLLECTOR_AD: queryAd.SetTargetTypeName (COLLECTOR_ADTYPE); break; default: return Q_INVALID_QUERY; } return Q_OK; } QueryResult CondorQuery:: filterAds (ClassAdList &in, ClassAdList &out) { ClassAd queryAd, *candidate; QueryResult result; // make the query ad result = (QueryResult) query.makeQuery (queryAd); if (result != Q_OK) return result; in.Open(); while (candidate = (ClassAd *) in.Next()) { // if a match occurs if ((*candidate) >= (queryAd)) out.Insert (candidate); } in.Close (); return Q_OK; } char *getStrQueryResult(QueryResult q) { switch (q) { case Q_OK: return "ok"; case Q_INVALID_CATEGORY: return "invalid category"; case Q_MEMORY_ERROR: return "memory error"; case Q_PARSE_ERROR: return "parse error"; case Q_COMMUNICATION_ERROR: return "communication error"; case Q_INVALID_QUERY: return "invalid query"; case Q_NO_COLLECTOR_HOST: return "no COLLECTOR_HOST"; default: return "unknown error"; } } <|endoftext|>
<commit_before>/* **============================================================================== ** ** Copyright (c) 2003, 2004, 2005, 2006, Michael Brasher, Karl Schopmeyer ** Copyright (c) 2008, Michael E. Brasher ** ** 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 "MOF_Data_Type.h" #include "MOF_Error.h" #include "MOF_String.h" #include "MOF_Yacc.h" const char* MOF_Data_Type::to_string(int data_type) { switch (data_type) { case TOK_UINT8: return "uint8"; case TOK_SINT8: return "sint8"; case TOK_UINT16: return "uint16"; case TOK_SINT16: return "sint16"; case TOK_UINT32: return "uint32"; case TOK_SINT32: return "sint32"; case TOK_UINT64: return "uint64"; case TOK_SINT64: return "sint64"; case TOK_REAL32: return "real32"; case TOK_REAL64: return "real64"; case TOK_CHAR16: return "char16"; case TOK_STRING: return "string"; case TOK_BOOLEAN: return "boolean"; case TOK_DATETIME: return "datetime"; default: MOF_ASSERT(false); return 0; } /* Unreachable */ return 0; } <commit_msg>Fix instance to string conversion<commit_after>/* **============================================================================== ** ** Copyright (c) 2003, 2004, 2005, 2006, Michael Brasher, Karl Schopmeyer ** Copyright (c) 2008, Michael E. Brasher ** ** 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 "MOF_Data_Type.h" #include "MOF_Error.h" #include "MOF_String.h" #include "MOF_Yacc.h" const char* MOF_Data_Type::to_string(int data_type) { switch (data_type) { case TOK_UINT8: return "uint8"; case TOK_SINT8: return "sint8"; case TOK_UINT16: return "uint16"; case TOK_SINT16: return "sint16"; case TOK_UINT32: return "uint32"; case TOK_SINT32: return "sint32"; case TOK_UINT64: return "uint64"; case TOK_SINT64: return "sint64"; case TOK_REAL32: return "real32"; case TOK_REAL64: return "real64"; case TOK_CHAR16: return "char16"; case TOK_STRING: return "string"; case TOK_BOOLEAN: return "boolean"; case TOK_DATETIME: return "datetime"; case TOK_INSTANCE: return "instance"; default: MOF_ASSERT(false); return 0; } /* Unreachable */ return 0; } <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2012, John Haddon. All rights reserved. // Copyright (c) 2013, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above // copyright notice, this list of conditions and the following // disclaimer. // // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided with // the distribution. // // * Neither the name of John Haddon nor the names of // any other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "GafferScene/GlobalsProcessor.h" using namespace Gaffer; using namespace GafferScene; GAFFER_GRAPHCOMPONENT_DEFINE_TYPE( GlobalsProcessor ); GlobalsProcessor::GlobalsProcessor( const std::string &name ) : SceneProcessor( name ) { // Fast pass-throughs for everything except the globals outPlug()->boundPlug()->setInput( inPlug()->boundPlug() ); outPlug()->transformPlug()->setInput( inPlug()->transformPlug() ); outPlug()->attributesPlug()->setInput( inPlug()->attributesPlug() ); outPlug()->objectPlug()->setInput( inPlug()->objectPlug() ); outPlug()->childNamesPlug()->setInput( inPlug()->childNamesPlug() ); outPlug()->setNamesPlug()->setInput( inPlug()->setNamesPlug() ); outPlug()->setPlug()->setInput( inPlug()->setPlug() ); } GlobalsProcessor::~GlobalsProcessor() { } void GlobalsProcessor::affects( const Plug *input, AffectedPlugsContainer &outputs ) const { SceneProcessor::affects( input, outputs ); if( input == inPlug()->globalsPlug() ) { outputs.push_back( outPlug()->globalsPlug() ); } } void GlobalsProcessor::hashGlobals( const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const { SceneProcessor::hashGlobals( context, parent, h ); inPlug()->globalsPlug()->hash( h ); hashProcessedGlobals( context, h ); } IECore::ConstCompoundObjectPtr GlobalsProcessor::computeGlobals( const Gaffer::Context *context, const ScenePlug *parent ) const { IECore::ConstCompoundObjectPtr globals = inPlug()->globalsPlug()->getValue(); return computeProcessedGlobals( context, globals ); } <commit_msg>GlobalsProcessor : Add pass-through for `childBoundsPlug()`<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2012, John Haddon. All rights reserved. // Copyright (c) 2013, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above // copyright notice, this list of conditions and the following // disclaimer. // // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided with // the distribution. // // * Neither the name of John Haddon nor the names of // any other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "GafferScene/GlobalsProcessor.h" using namespace Gaffer; using namespace GafferScene; GAFFER_GRAPHCOMPONENT_DEFINE_TYPE( GlobalsProcessor ); GlobalsProcessor::GlobalsProcessor( const std::string &name ) : SceneProcessor( name ) { // Fast pass-throughs for everything except the globals outPlug()->boundPlug()->setInput( inPlug()->boundPlug() ); outPlug()->transformPlug()->setInput( inPlug()->transformPlug() ); outPlug()->attributesPlug()->setInput( inPlug()->attributesPlug() ); outPlug()->objectPlug()->setInput( inPlug()->objectPlug() ); outPlug()->childNamesPlug()->setInput( inPlug()->childNamesPlug() ); outPlug()->setNamesPlug()->setInput( inPlug()->setNamesPlug() ); outPlug()->setPlug()->setInput( inPlug()->setPlug() ); outPlug()->childBoundsPlug()->setInput( inPlug()->childBoundsPlug() ); } GlobalsProcessor::~GlobalsProcessor() { } void GlobalsProcessor::affects( const Plug *input, AffectedPlugsContainer &outputs ) const { SceneProcessor::affects( input, outputs ); if( input == inPlug()->globalsPlug() ) { outputs.push_back( outPlug()->globalsPlug() ); } } void GlobalsProcessor::hashGlobals( const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const { SceneProcessor::hashGlobals( context, parent, h ); inPlug()->globalsPlug()->hash( h ); hashProcessedGlobals( context, h ); } IECore::ConstCompoundObjectPtr GlobalsProcessor::computeGlobals( const Gaffer::Context *context, const ScenePlug *parent ) const { IECore::ConstCompoundObjectPtr globals = inPlug()->globalsPlug()->getValue(); return computeProcessedGlobals( context, globals ); } <|endoftext|>
<commit_before><commit_msg>some fixes<commit_after><|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include <mitkTestingMacros.h> #include <mitkTestFixture.h> #include "mitkIOUtil.h" #include <cmath> #include <mitkGIFGreyLevelSizeZone.h> class mitkGIFGreyLevelSizeZoneTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkGIFGreyLevelSizeZoneTestSuite ); MITK_TEST(ImageDescription_PhantomTest_3D); MITK_TEST(ImageDescription_PhantomTest_2D); CPPUNIT_TEST_SUITE_END(); private: mitk::Image::Pointer m_IBSI_Phantom_Image_Small; mitk::Image::Pointer m_IBSI_Phantom_Image_Large; mitk::Image::Pointer m_IBSI_Phantom_Mask_Small; mitk::Image::Pointer m_IBSI_Phantom_Mask_Large; public: void setUp(void) override { m_IBSI_Phantom_Image_Small = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Image_Small.nrrd")); m_IBSI_Phantom_Image_Large = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Image_Large.nrrd")); m_IBSI_Phantom_Mask_Small = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Mask_Small.nrrd")); m_IBSI_Phantom_Mask_Large = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Mask_Large.nrrd")); } void ImageDescription_PhantomTest_3D() { mitk::GIFGreyLevelSizeZone::Pointer featureCalculator = mitk::GIFGreyLevelSizeZone::New(); featureCalculator->SetUseBinsize(true); featureCalculator->SetBinsize(1.0); featureCalculator->SetUseMinimumIntensity(true); featureCalculator->SetUseMaximumIntensity(true); featureCalculator->SetMinimumIntensity(0.5); featureCalculator->SetMaximumIntensity(6.5); auto featureList = featureCalculator->CalculateFeatures(m_IBSI_Phantom_Image_Large, m_IBSI_Phantom_Mask_Large); std::map<std::string, double> results; for (auto valuePair : featureList) { MITK_INFO << valuePair.first << " : " << valuePair.second; results[valuePair.first] = valuePair.second; } CPPUNIT_ASSERT_EQUAL_MESSAGE("Image Diagnostics should calculate 18 features.", std::size_t(18), featureList.size()); // These values are obtained with IBSI // Standard accuracy is 0.01 CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Small Zone Emphasis with Large IBSI Phantom Image", 0.255, results["Grey Level Size Zone::Small Zone Emphasis"], 0.001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Large Zone Emphasis with Large IBSI Phantom Image", 550, results["Grey Level Size Zone::Large Zone Emphasis"], 0.001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Low Grey Level Emphasis with Large IBSI Phantom Image", 0.253, results["Grey Level Size Zone::Low Grey Level Emphasis"], 0.001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::High Grey Level Emphasis with Large IBSI Phantom Image", 15.6, results["Grey Level Size Zone::High Grey Level Emphasis"], 0.001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Small Zone Low Grey Level Emphasis with Large IBSI Phantom Image", 0.0256, results["Grey Level Size Zone::Small Zone Low Grey Level Emphasis"], 0.001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Small Zone High Grey Level Emphasis with Large IBSI Phantom Image", 2.76, results["Grey Level Size Zone::Small Zone High Grey Level Emphasis"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Large Zone Low Grey Level Emphasis with Large IBSI Phantom Image", 503, results["Grey Level Size Zone::Large Zone Low Grey Level Emphasis"], 1); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Large Zone High Grey Level Emphasis with Large IBSI Phantom Image", 1495, results["Grey Level Size Zone::Large Zone High Grey Level Emphasis"], 1); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Grey Level Non-Uniformity with Large IBSI Phantom Image", 1.4, results["Grey Level Size Zone::Grey Level Non-Uniformity"], 0.001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Grey Level Non-Uniformity Normalized with Large IBSI Phantom Image", 0.28, results["Grey Level Size Zone::Grey Level Non-Uniformity Normalized"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Zone Size Non-Uniformity with Large IBSI Phantom Image", 1, results["Grey Level Size Zone::Zone Size Non-Uniformity"], 0.1); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Zone Size Non-Uniformity Normalized with Large IBSI Phantom Image", 0.2, results["Grey Level Size Zone::Zone Size Non-Uniformity Normalized"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Zone Percentage with Large IBSI Phantom Image", 0.0676, results["Grey Level Size Zone::Zone Percentage"], 0.001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Grey Level Variance with Large IBSI Phantom Image", 2.64, results["Grey Level Size Zone::Grey Level Variance"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Zone Size Variance with Large IBSI Phantom Image", 331, results["Grey Level Size Zone::Zone Size Variance"], 0.1); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Zone Size Entropy with Large IBSI Phantom Image", 2.32, results["Grey Level Size Zone::Zone Size Entropy"], 0.01); //CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone:: with Large IBSI Phantom Image", 0.045, results["Grey Level Size Zone::"], 0.001); // These values are obtained by manually running the tool // Values might be wrong. CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Grey Level Mean with Large IBSI Phantom Image", 3.6, results["Grey Level Size Zone::Grey Level Mean"], 0.001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Zone Size Mean with Large IBSI Phantom Image", 14.8, results["Grey Level Size Zone::Zone Size Mean"], 0.001); } void ImageDescription_PhantomTest_2D() { mitk::GIFGreyLevelSizeZone::Pointer featureCalculator = mitk::GIFGreyLevelSizeZone::New(); featureCalculator->SetUseBinsize(true); featureCalculator->SetBinsize(1.0); featureCalculator->SetUseMinimumIntensity(true); featureCalculator->SetUseMaximumIntensity(true); featureCalculator->SetMinimumIntensity(0.5); featureCalculator->SetMaximumIntensity(6.5); auto featureList = featureCalculator->CalculateFeaturesSlicewise(m_IBSI_Phantom_Image_Large, m_IBSI_Phantom_Mask_Large, 2); std::map<std::string, double> results; for (auto valuePair : featureList) { MITK_INFO << valuePair.first << " : " << valuePair.second; results[valuePair.first] = valuePair.second; } CPPUNIT_ASSERT_EQUAL_MESSAGE("Image Diagnostics should calculate 108 features.", std::size_t(108), featureList.size()); // These values are obtained with IBSI // Standard accuracy is 0.01 CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Small Zone Emphasis with Large IBSI Phantom Image", 0.363, results["SliceWise Mean Grey Level Size Zone::Small Zone Emphasis"], 0.001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Large Zone Emphasis with Large IBSI Phantom Image", 43.9, results["SliceWise Mean Grey Level Size Zone::Large Zone Emphasis"], 0.001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Low Grey Level Emphasis with Large IBSI Phantom Image", 0.371, results["SliceWise Mean Grey Level Size Zone::Low Grey Level Emphasis"], 0.001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::High Grey Level Emphasis with Large IBSI Phantom Image", 16.4, results["SliceWise Mean Grey Level Size Zone::High Grey Level Emphasis"], 0.001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Small Zone Low Grey Level Emphasis with Large IBSI Phantom Image", 0.0259, results["SliceWise Mean Grey Level Size Zone::Small Zone Low Grey Level Emphasis"], 0.001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Small Zone High Grey Level Emphasis with Large IBSI Phantom Image", 10.3, results["SliceWise Mean Grey Level Size Zone::Small Zone High Grey Level Emphasis"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Large Zone Low Grey Level Emphasis with Large IBSI Phantom Image", 40.4, results["SliceWise Mean Grey Level Size Zone::Large Zone Low Grey Level Emphasis"], 1); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Large Zone High Grey Level Emphasis with Large IBSI Phantom Image", 113, results["SliceWise Mean Grey Level Size Zone::Large Zone High Grey Level Emphasis"], 1); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Grey Level Non-Uniformity with Large IBSI Phantom Image", 1.41, results["SliceWise Mean Grey Level Size Zone::Grey Level Non-Uniformity"], 0.001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Grey Level Non-Uniformity Normalized with Large IBSI Phantom Image", 0.323, results["SliceWise Mean Grey Level Size Zone::Grey Level Non-Uniformity Normalized"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Zone Size Non-Uniformity with Large IBSI Phantom Image", 1.49, results["SliceWise Mean Grey Level Size Zone::Zone Size Non-Uniformity"], 0.1); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Zone Size Non-Uniformity Normalized with Large IBSI Phantom Image", 0.333, results["SliceWise Mean Grey Level Size Zone::Zone Size Non-Uniformity Normalized"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Zone Percentage with Large IBSI Phantom Image", 0.24, results["SliceWise Mean Grey Level Size Zone::Zone Percentage"], 0.001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Grey Level Variance with Large IBSI Phantom Image", 3.97, results["SliceWise Mean Grey Level Size Zone::Grey Level Variance"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Zone Size Variance with Large IBSI Phantom Image", 21, results["SliceWise Mean Grey Level Size Zone::Zone Size Variance"], 0.1); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Zone Size Entropy with Large IBSI Phantom Image", 1.93, results["SliceWise Mean Grey Level Size Zone::Zone Size Entropy"], 0.01); //CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone:: with Large IBSI Phantom Image", 0.045, results["SliceWise Mean Grey Level Size Zone::"], 0.001); // These values are obtained by manually running the tool // Values might be wrong. CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Grey Level Mean with Large IBSI Phantom Image", 3.6, results["SliceWise Mean Grey Level Size Zone::Grey Level Mean"], 0.001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Zone Size Mean with Large IBSI Phantom Image", 14.8, results["SliceWise Mean Grey Level Size Zone::Zone Size Mean"], 0.001); } }; MITK_TEST_SUITE_REGISTRATION(mitkGIFGreyLevelSizeZone )<commit_msg>Updated test tolerances<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include <mitkTestingMacros.h> #include <mitkTestFixture.h> #include "mitkIOUtil.h" #include <cmath> #include <mitkGIFGreyLevelSizeZone.h> class mitkGIFGreyLevelSizeZoneTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkGIFGreyLevelSizeZoneTestSuite ); MITK_TEST(ImageDescription_PhantomTest_3D); MITK_TEST(ImageDescription_PhantomTest_2D); CPPUNIT_TEST_SUITE_END(); private: mitk::Image::Pointer m_IBSI_Phantom_Image_Small; mitk::Image::Pointer m_IBSI_Phantom_Image_Large; mitk::Image::Pointer m_IBSI_Phantom_Mask_Small; mitk::Image::Pointer m_IBSI_Phantom_Mask_Large; public: void setUp(void) override { m_IBSI_Phantom_Image_Small = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Image_Small.nrrd")); m_IBSI_Phantom_Image_Large = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Image_Large.nrrd")); m_IBSI_Phantom_Mask_Small = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Mask_Small.nrrd")); m_IBSI_Phantom_Mask_Large = mitk::IOUtil::LoadImage(GetTestDataFilePath("Radiomics/IBSI_Phantom_Mask_Large.nrrd")); } void ImageDescription_PhantomTest_3D() { mitk::GIFGreyLevelSizeZone::Pointer featureCalculator = mitk::GIFGreyLevelSizeZone::New(); featureCalculator->SetUseBinsize(true); featureCalculator->SetBinsize(1.0); featureCalculator->SetUseMinimumIntensity(true); featureCalculator->SetUseMaximumIntensity(true); featureCalculator->SetMinimumIntensity(0.5); featureCalculator->SetMaximumIntensity(6.5); auto featureList = featureCalculator->CalculateFeatures(m_IBSI_Phantom_Image_Large, m_IBSI_Phantom_Mask_Large); std::map<std::string, double> results; for (auto valuePair : featureList) { MITK_INFO << valuePair.first << " : " << valuePair.second; results[valuePair.first] = valuePair.second; } CPPUNIT_ASSERT_EQUAL_MESSAGE("Image Diagnostics should calculate 18 features.", std::size_t(18), featureList.size()); // These values are obtained with IBSI // Standard accuracy is 0.01 CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Small Zone Emphasis with Large IBSI Phantom Image", 0.255, results["Grey Level Size Zone::Small Zone Emphasis"], 0.001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Large Zone Emphasis with Large IBSI Phantom Image", 550, results["Grey Level Size Zone::Large Zone Emphasis"], 0.001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Low Grey Level Emphasis with Large IBSI Phantom Image", 0.253, results["Grey Level Size Zone::Low Grey Level Emphasis"], 0.001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::High Grey Level Emphasis with Large IBSI Phantom Image", 15.6, results["Grey Level Size Zone::High Grey Level Emphasis"], 0.001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Small Zone Low Grey Level Emphasis with Large IBSI Phantom Image", 0.0256, results["Grey Level Size Zone::Small Zone Low Grey Level Emphasis"], 0.001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Small Zone High Grey Level Emphasis with Large IBSI Phantom Image", 2.76, results["Grey Level Size Zone::Small Zone High Grey Level Emphasis"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Large Zone Low Grey Level Emphasis with Large IBSI Phantom Image", 503, results["Grey Level Size Zone::Large Zone Low Grey Level Emphasis"], 1); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Large Zone High Grey Level Emphasis with Large IBSI Phantom Image", 1495, results["Grey Level Size Zone::Large Zone High Grey Level Emphasis"], 1); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Grey Level Non-Uniformity with Large IBSI Phantom Image", 1.4, results["Grey Level Size Zone::Grey Level Non-Uniformity"], 0.001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Grey Level Non-Uniformity Normalized with Large IBSI Phantom Image", 0.28, results["Grey Level Size Zone::Grey Level Non-Uniformity Normalized"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Zone Size Non-Uniformity with Large IBSI Phantom Image", 1, results["Grey Level Size Zone::Zone Size Non-Uniformity"], 0.1); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Zone Size Non-Uniformity Normalized with Large IBSI Phantom Image", 0.2, results["Grey Level Size Zone::Zone Size Non-Uniformity Normalized"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Zone Percentage with Large IBSI Phantom Image", 0.0676, results["Grey Level Size Zone::Zone Percentage"], 0.001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Grey Level Variance with Large IBSI Phantom Image", 2.64, results["Grey Level Size Zone::Grey Level Variance"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Zone Size Variance with Large IBSI Phantom Image", 331, results["Grey Level Size Zone::Zone Size Variance"], 0.1); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Zone Size Entropy with Large IBSI Phantom Image", 2.32, results["Grey Level Size Zone::Zone Size Entropy"], 0.01); //CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone:: with Large IBSI Phantom Image", 0.045, results["Grey Level Size Zone::"], 0.001); // These values are obtained by manually running the tool // Values might be wrong. CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Grey Level Mean with Large IBSI Phantom Image", 3.6, results["Grey Level Size Zone::Grey Level Mean"], 0.001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("Grey Level Size Zone::Zone Size Mean with Large IBSI Phantom Image", 14.8, results["Grey Level Size Zone::Zone Size Mean"], 0.001); } void ImageDescription_PhantomTest_2D() { mitk::GIFGreyLevelSizeZone::Pointer featureCalculator = mitk::GIFGreyLevelSizeZone::New(); featureCalculator->SetUseBinsize(true); featureCalculator->SetBinsize(1.0); featureCalculator->SetUseMinimumIntensity(true); featureCalculator->SetUseMaximumIntensity(true); featureCalculator->SetMinimumIntensity(0.5); featureCalculator->SetMaximumIntensity(6.5); auto featureList = featureCalculator->CalculateFeaturesSlicewise(m_IBSI_Phantom_Image_Large, m_IBSI_Phantom_Mask_Large, 2); std::map<std::string, double> results; for (auto valuePair : featureList) { MITK_INFO << valuePair.first << " : " << valuePair.second; results[valuePair.first] = valuePair.second; } CPPUNIT_ASSERT_EQUAL_MESSAGE("Image Diagnostics should calculate 108 features.", std::size_t(108), featureList.size()); // These values are obtained with IBSI // Standard accuracy is 0.01 CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Small Zone Emphasis with Large IBSI Phantom Image", 0.363, results["SliceWise Mean Grey Level Size Zone::Small Zone Emphasis"], 0.001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Large Zone Emphasis with Large IBSI Phantom Image", 43.9, results["SliceWise Mean Grey Level Size Zone::Large Zone Emphasis"], 0.1); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Low Grey Level Emphasis with Large IBSI Phantom Image", 0.371, results["SliceWise Mean Grey Level Size Zone::Low Grey Level Emphasis"], 0.001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::High Grey Level Emphasis with Large IBSI Phantom Image", 16.4, results["SliceWise Mean Grey Level Size Zone::High Grey Level Emphasis"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Small Zone Low Grey Level Emphasis with Large IBSI Phantom Image", 0.0259, results["SliceWise Mean Grey Level Size Zone::Small Zone Low Grey Level Emphasis"], 0.001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Small Zone High Grey Level Emphasis with Large IBSI Phantom Image", 10.3, results["SliceWise Mean Grey Level Size Zone::Small Zone High Grey Level Emphasis"], 0.1); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Large Zone Low Grey Level Emphasis with Large IBSI Phantom Image", 40.4, results["SliceWise Mean Grey Level Size Zone::Large Zone Low Grey Level Emphasis"], 1); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Large Zone High Grey Level Emphasis with Large IBSI Phantom Image", 113, results["SliceWise Mean Grey Level Size Zone::Large Zone High Grey Level Emphasis"], 1); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Grey Level Non-Uniformity with Large IBSI Phantom Image", 1.41, results["SliceWise Mean Grey Level Size Zone::Grey Level Non-Uniformity"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Grey Level Non-Uniformity Normalized with Large IBSI Phantom Image", 0.323, results["SliceWise Mean Grey Level Size Zone::Grey Level Non-Uniformity Normalized"], 0.001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Zone Size Non-Uniformity with Large IBSI Phantom Image", 1.49, results["SliceWise Mean Grey Level Size Zone::Zone Size Non-Uniformity"], 0.1); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Zone Size Non-Uniformity Normalized with Large IBSI Phantom Image", 0.333, results["SliceWise Mean Grey Level Size Zone::Zone Size Non-Uniformity Normalized"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Zone Percentage with Large IBSI Phantom Image", 0.24, results["SliceWise Mean Grey Level Size Zone::Zone Percentage"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Grey Level Variance with Large IBSI Phantom Image", 3.97, results["SliceWise Mean Grey Level Size Zone::Grey Level Variance"], 0.01); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Zone Size Variance with Large IBSI Phantom Image", 21, results["SliceWise Mean Grey Level Size Zone::Zone Size Variance"], 0.1); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Zone Size Entropy with Large IBSI Phantom Image", 1.93, results["SliceWise Mean Grey Level Size Zone::Zone Size Entropy"], 0.01); //CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone:: with Large IBSI Phantom Image", 0.045, results["SliceWise Mean Grey Level Size Zone::"], 0.001); // These values are obtained by manually running the tool // Values might be wrong. CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Grey Level Mean with Large IBSI Phantom Image", 3.526, results["SliceWise Mean Grey Level Size Zone::Grey Level Mean"], 0.001); CPPUNIT_ASSERT_DOUBLES_EQUAL_MESSAGE("SliceWise Mean Grey Level Size Zone::Zone Size Mean with Large IBSI Phantom Image", 4.59524, results["SliceWise Mean Grey Level Size Zone::Zone Size Mean"], 0.001); } }; MITK_TEST_SUITE_REGISTRATION(mitkGIFGreyLevelSizeZone )<|endoftext|>
<commit_before>#include "sampler.hpp" #include "context.hpp" #include "texture.hpp" #include "internal/wrapper.hpp" #include "internal/modules.hpp" #include "internal/tools.hpp" #include "internal/glsl.hpp" /* MGLContext.sampler(texture) */ PyObject * MGLContext_meth_sampler(MGLContext * self, PyObject * const * args, Py_ssize_t nargs) { if (nargs != 1) { // TODO: error return 0; } PyObject * texture = args[0]; MGLSampler * sampler = MGLContext_new_object(self, Sampler); const GLMethods & gl = self->gl; gl.GenSamplers(1, (GLuint *)&sampler->sampler_obj); if (!sampler->sampler_obj) { PyErr_Format(moderngl_error, "cannot create sampler"); Py_DECREF(sampler); return 0; } gl.SamplerParameteri(sampler->sampler_obj, GL_TEXTURE_MIN_FILTER, GL_NEAREST); gl.SamplerParameteri(sampler->sampler_obj, GL_TEXTURE_MAG_FILTER, GL_NEAREST); SLOT(sampler->wrapper, PyObject, Sampler_class_texture) = texture; return NEW_REF(sampler->wrapper); } /* MGLSampler.use(location) */ PyObject * MGLSampler_meth_use(MGLSampler * self, PyObject * arg) { PyObject * wrapper = SLOT(self->wrapper, PyObject, Sampler_class_texture); MGLTexture * texture = SLOT(wrapper, MGLTexture, Texture_class_mglo); int location = PyLong_AsLong(arg); self->context->bind_sampler(location, texture->texture_target, texture->texture_obj, self->sampler_obj); Py_RETURN_NONE; } int MGLSampler_set_filter(MGLSampler * self, PyObject * value) { return 0; } enum MGLSamplerWrapModes { MGL_CLAMP_TO_EDGE = 0x01, MGL_REPEAT = 0x02, MGL_MIRRORED_REPEAT = 0x04, MGL_MIRROR_CLAMP_TO_EDGE = 0x08, MGL_CLAMP_TO_BORDER = 0x10, }; int MGLSampler_set_wrap(MGLSampler * self, PyObject * value) { int wrap = PyLong_AsLong(value); SLOT(self->wrapper, PyObject, Sampler_class_wrap) = PyLong_FromLong(wrap); switch (((unsigned char *)&wrap)[0]) { case 0: case MGL_CLAMP_TO_EDGE: self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); break; case MGL_REPEAT: self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_S, GL_REPEAT); break; case MGL_MIRRORED_REPEAT: self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT); break; case MGL_MIRROR_CLAMP_TO_EDGE: self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_S, GL_MIRROR_CLAMP_TO_EDGE); break; case MGL_CLAMP_TO_BORDER: self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); break; default: // TODO: error return -1; } switch (((unsigned char *)&wrap)[1]) { case 0: case MGL_CLAMP_TO_EDGE: self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); break; case MGL_REPEAT: self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_T, GL_REPEAT); break; case MGL_MIRRORED_REPEAT: self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT); break; case MGL_MIRROR_CLAMP_TO_EDGE: self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_T, GL_MIRROR_CLAMP_TO_EDGE); break; case MGL_CLAMP_TO_BORDER: self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); break; default: // TODO: error return -1; } PyObject * wrapper = SLOT(self->wrapper, PyObject, Sampler_class_texture); MGLTexture * texture = SLOT(wrapper, MGLTexture, Texture_class_mglo); if (texture->texture_target == GL_TEXTURE_3D) { switch (((unsigned char *)&wrap)[2]) { case 0: case MGL_CLAMP_TO_EDGE: self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); break; case MGL_REPEAT: self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_R, GL_REPEAT); break; case MGL_MIRRORED_REPEAT: self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_R, GL_MIRRORED_REPEAT); break; case MGL_MIRROR_CLAMP_TO_EDGE: self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_R, GL_MIRROR_CLAMP_TO_EDGE); break; case MGL_CLAMP_TO_BORDER: self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_BORDER); break; default: // TODO: error return -1; } } else if (((unsigned char *)&wrap)[2]) { return -1; } return 0; } int MGLSampler_set_border_color(MGLSampler * self, PyObject * value) { PyObject * border_color = PySequence_Fast(value, "not iterable"); if (!border_color) { return -1; } float color[4] = {}; switch (PySequence_Fast_GET_SIZE(border_color)) { case 4: color[3] = (float)PyFloat_AsDouble(PySequence_Fast_GET_ITEM(border_color, 3)); case 3: color[2] = (float)PyFloat_AsDouble(PySequence_Fast_GET_ITEM(border_color, 2)); case 2: color[1] = (float)PyFloat_AsDouble(PySequence_Fast_GET_ITEM(border_color, 1)); case 1: color[0] = (float)PyFloat_AsDouble(PySequence_Fast_GET_ITEM(border_color, 0)); default: // TODO: error return -1; } self->context->gl.SamplerParameterfv(self->sampler_obj, GL_TEXTURE_BORDER_COLOR, color); return 0; } int MGLSampler_set_anisotropy(MGLSampler * self, PyObject * value) { float anisotropy = (float)PyFloat_AsDouble(value); if (anisotropy < 1.0) { anisotropy = 1.0; } // if (anisotropy > max_anisotropy) { // anisotropy = max_anisotropy; // } // SLOT(self->wrapper, PyObject, Sampler_class_max_lod) = PyFloat_FromDouble(anisotropy); self->context->gl.SamplerParameterf(self->sampler_obj, GL_TEXTURE_MAX_ANISOTROPY, anisotropy); return 0; } int MGLSampler_set_lod_range(MGLSampler * self, PyObject * value) { PyObject * lod_range = PySequence_Fast(value, "not iterable"); if (!lod_range) { return -1; } int min_lod; int max_lod; float lod_bias = 0.0f; switch (PySequence_Fast_GET_SIZE(lod_range)) { case 3: lod_bias = (float)PyFloat_AsDouble(PySequence_Fast_GET_ITEM(lod_range, 2)); case 2: min_lod = PyLong_AsLong(PySequence_Fast_GET_ITEM(lod_range, 0)); max_lod = PyLong_AsLong(PySequence_Fast_GET_ITEM(lod_range, 1)); default: // TODO: error return -1; } // SLOT(self->wrapper, PyObject, Sampler_class_max_lod) = PyFloat_FromDouble(anisotropy); self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_MIN_LOD, min_lod); self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_MIN_LOD, max_lod); self->context->gl.SamplerParameterf(self->sampler_obj, GL_TEXTURE_LOD_BIAS, lod_bias); return 0; } #if PY_VERSION_HEX >= 0x03070000 PyMethodDef MGLSampler_methods[] = { {"use", (PyCFunction)MGLSampler_meth_use, METH_O, 0}, {0}, }; #else PyMethodDef MGLSampler_methods[] = { {"use", (PyCFunction)MGLSampler_meth_use, METH_O, 0}, {0}, }; #endif PyGetSetDef MGLSampler_getset[] = { {"filter", 0, (setter)MGLSampler_set_filter, 0, 0}, {"wrap", 0, (setter)MGLSampler_set_wrap, 0, 0}, {"anisotropy", 0, (setter)MGLSampler_set_anisotropy, 0, 0}, {"border_color", 0, (setter)MGLSampler_set_border_color, 0, 0}, {"lod_range", 0, (setter)MGLSampler_set_lod_range, 0, 0}, {0}, }; PyType_Slot MGLSampler_slots[] = { {Py_tp_methods, MGLSampler_methods}, {Py_tp_getset, MGLSampler_getset}, {0}, }; PyType_Spec MGLSampler_spec = { mgl_ext ".Sampler", sizeof(MGLSampler), 0, Py_TPFLAGS_DEFAULT, MGLSampler_slots, }; <commit_msg>sampler properties<commit_after>#include "sampler.hpp" #include "context.hpp" #include "texture.hpp" #include "internal/wrapper.hpp" #include "internal/modules.hpp" #include "internal/tools.hpp" #include "internal/glsl.hpp" /* MGLContext.sampler(texture) */ PyObject * MGLContext_meth_sampler(MGLContext * self, PyObject * const * args, Py_ssize_t nargs) { if (nargs != 1) { // TODO: error return 0; } PyObject * texture = args[0]; MGLSampler * sampler = MGLContext_new_object(self, Sampler); const GLMethods & gl = self->gl; gl.GenSamplers(1, (GLuint *)&sampler->sampler_obj); if (!sampler->sampler_obj) { PyErr_Format(moderngl_error, "cannot create sampler"); Py_DECREF(sampler); return 0; } gl.SamplerParameteri(sampler->sampler_obj, GL_TEXTURE_MIN_FILTER, GL_NEAREST); gl.SamplerParameteri(sampler->sampler_obj, GL_TEXTURE_MAG_FILTER, GL_NEAREST); SLOT(sampler->wrapper, PyObject, Sampler_class_texture) = texture; return NEW_REF(sampler->wrapper); } /* MGLSampler.use(location) */ PyObject * MGLSampler_meth_use(MGLSampler * self, PyObject * arg) { PyObject * wrapper = SLOT(self->wrapper, PyObject, Sampler_class_texture); MGLTexture * texture = SLOT(wrapper, MGLTexture, Texture_class_mglo); int location = PyLong_AsLong(arg); self->context->bind_sampler(location, texture->texture_target, texture->texture_obj, self->sampler_obj); Py_RETURN_NONE; } int MGLSampler_set_filter(MGLSampler * self, PyObject * value) { return 0; } enum MGLSamplerWrapModes { MGL_CLAMP_TO_EDGE = 0x01, MGL_REPEAT = 0x02, MGL_MIRRORED_REPEAT = 0x04, MGL_MIRROR_CLAMP_TO_EDGE = 0x08, MGL_CLAMP_TO_BORDER = 0x10, }; int MGLSampler_set_wrap(MGLSampler * self, PyObject * value) { int wrap = PyLong_AsLong(value); SLOT(self->wrapper, PyObject, Sampler_class_wrap) = PyLong_FromLong(wrap); switch (((unsigned char *)&wrap)[0]) { case 0: case MGL_CLAMP_TO_EDGE: self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); break; case MGL_REPEAT: self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_S, GL_REPEAT); break; case MGL_MIRRORED_REPEAT: self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT); break; case MGL_MIRROR_CLAMP_TO_EDGE: self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_S, GL_MIRROR_CLAMP_TO_EDGE); break; case MGL_CLAMP_TO_BORDER: self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); break; default: // TODO: error return -1; } switch (((unsigned char *)&wrap)[1]) { case 0: case MGL_CLAMP_TO_EDGE: self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); break; case MGL_REPEAT: self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_T, GL_REPEAT); break; case MGL_MIRRORED_REPEAT: self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT); break; case MGL_MIRROR_CLAMP_TO_EDGE: self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_T, GL_MIRROR_CLAMP_TO_EDGE); break; case MGL_CLAMP_TO_BORDER: self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); break; default: // TODO: error return -1; } PyObject * wrapper = SLOT(self->wrapper, PyObject, Sampler_class_texture); MGLTexture * texture = SLOT(wrapper, MGLTexture, Texture_class_mglo); if (texture->texture_target == GL_TEXTURE_3D) { switch (((unsigned char *)&wrap)[2]) { case 0: case MGL_CLAMP_TO_EDGE: self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); break; case MGL_REPEAT: self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_R, GL_REPEAT); break; case MGL_MIRRORED_REPEAT: self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_R, GL_MIRRORED_REPEAT); break; case MGL_MIRROR_CLAMP_TO_EDGE: self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_R, GL_MIRROR_CLAMP_TO_EDGE); break; case MGL_CLAMP_TO_BORDER: self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_BORDER); break; default: // TODO: error return -1; } } else if (((unsigned char *)&wrap)[2]) { return -1; } return 0; } int MGLSampler_set_border(MGLSampler * self, PyObject * value) { PyObject * border = PySequence_Fast(value, "not iterable"); if (!border) { return -1; } float color[4] = {}; switch (PySequence_Fast_GET_SIZE(border)) { case 4: color[3] = (float)PyFloat_AsDouble(PySequence_Fast_GET_ITEM(border, 3)); case 3: color[2] = (float)PyFloat_AsDouble(PySequence_Fast_GET_ITEM(border, 2)); case 2: color[1] = (float)PyFloat_AsDouble(PySequence_Fast_GET_ITEM(border, 1)); case 1: color[0] = (float)PyFloat_AsDouble(PySequence_Fast_GET_ITEM(border, 0)); default: Py_DECREF(border); // TODO: error return -1; } Py_DECREF(border); self->context->gl.SamplerParameterfv(self->sampler_obj, GL_TEXTURE_BORDER_COLOR, color); Py_XSETREF(SLOT(self->wrapper, PyObject, Sampler_class_border), float_tuple(color[0], color[1], color[2], color[3])); return 0; } int MGLSampler_set_anisotropy(MGLSampler * self, PyObject * value) { float anisotropy = (float)PyFloat_AsDouble(value); if (anisotropy < 1.0) { anisotropy = 1.0; } // TODO: clamp with max value self->context->gl.SamplerParameterf(self->sampler_obj, GL_TEXTURE_MAX_ANISOTROPY, anisotropy); Py_XSETREF(SLOT(self->wrapper, PyObject, Sampler_class_anisotropy), PyFloat_FromDouble(anisotropy)); return 0; } int MGLSampler_set_lod_range(MGLSampler * self, PyObject * value) { PyObject * lod_range = PySequence_Fast(value, "not iterable"); if (!lod_range) { return -1; } if (PySequence_Fast_GET_SIZE(lod_range) != 2) { Py_DECREF(lod_range); // TODO: error return -1; } int min_lod = PyLong_AsLong(PySequence_Fast_GET_ITEM(lod_range, 0)); int max_lod = PyLong_AsLong(PySequence_Fast_GET_ITEM(lod_range, 1)); Py_DECREF(lod_range); self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_MIN_LOD, min_lod); self->context->gl.SamplerParameteri(self->sampler_obj, GL_TEXTURE_MIN_LOD, max_lod); Py_XSETREF(SLOT(self->wrapper, PyObject, Sampler_class_lod_range), int_tuple(min_lod, max_lod)); return 0; } int MGLSampler_set_lod_bias(MGLSampler * self, PyObject * value) { float lod_bias = (float)PyFloat_AsDouble(value); self->context->gl.SamplerParameterf(self->sampler_obj, GL_TEXTURE_LOD_BIAS, lod_bias); Py_XSETREF(SLOT(self->wrapper, PyObject, Sampler_class_lod_bias), PyFloat_FromDouble(lod_bias)); return 0; } #if PY_VERSION_HEX >= 0x03070000 PyMethodDef MGLSampler_methods[] = { {"use", (PyCFunction)MGLSampler_meth_use, METH_O, 0}, {0}, }; #else PyMethodDef MGLSampler_methods[] = { {"use", (PyCFunction)MGLSampler_meth_use, METH_O, 0}, {0}, }; #endif PyGetSetDef MGLSampler_getset[] = { {"filter", 0, (setter)MGLSampler_set_filter, 0, 0}, {"wrap", 0, (setter)MGLSampler_set_wrap, 0, 0}, {"anisotropy", 0, (setter)MGLSampler_set_anisotropy, 0, 0}, {"border", 0, (setter)MGLSampler_set_border, 0, 0}, {"lod_range", 0, (setter)MGLSampler_set_lod_range, 0, 0}, {"lod_bias", 0, (setter)MGLSampler_set_lod_bias, 0, 0}, {0}, }; PyType_Slot MGLSampler_slots[] = { {Py_tp_methods, MGLSampler_methods}, {Py_tp_getset, MGLSampler_getset}, {0}, }; PyType_Spec MGLSampler_spec = { mgl_ext ".Sampler", sizeof(MGLSampler), 0, Py_TPFLAGS_DEFAULT, MGLSampler_slots, }; <|endoftext|>
<commit_before>/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkContourModelLiveWireInteractor.h" #include "mitkInteractionPositionEvent.h" #include "mitkToolManager.h" #include "mitkBaseRenderer.h" #include "mitkRenderingManager.h" #include <mitkInteractionConst.h> #include "mitkIOUtil.h" mitk::ContourModelLiveWireInteractor::ContourModelLiveWireInteractor() : ContourModelInteractor() { m_LiveWireFilter = mitk::ImageLiveWireContourModelFilter::New(); m_LiveWireFilter->SetUseCostFunction(true); m_NextActiveVertexDown.Fill(0); m_NextActiveVertexUp.Fill(0); } mitk::ContourModelLiveWireInteractor::~ContourModelLiveWireInteractor() { } void mitk::ContourModelLiveWireInteractor::ConnectActionsAndFunctions() { CONNECT_CONDITION("checkisOverPoint", OnCheckPointClick); CONNECT_CONDITION("mouseMove", IsHovering); CONNECT_FUNCTION("movePoint", OnMovePoint); CONNECT_FUNCTION("deletePoint", OnDeletePoint); CONNECT_FUNCTION("addPoint", OnAddPoint) CONNECT_FUNCTION("finish", OnFinishEditing); } bool mitk::ContourModelLiveWireInteractor::OnCheckPointClick(const InteractionEvent *interactionEvent) { auto isVertexSelected = Superclass::OnCheckPointClick(interactionEvent); if (isVertexSelected) { auto* contour = dynamic_cast<mitk::ContourModel*>(this->GetDataNode()->GetData()); const auto* positionEvent = dynamic_cast<const mitk::InteractionPositionEvent*>(interactionEvent); mitk::Point3D click = positionEvent->GetPositionInWorld(); const auto timeStep = interactionEvent->GetSender()->GetTimeStep(GetDataNode()->GetData()); auto controlVertices = contour->GetControlVertices(timeStep); const mitk::ContourModel::VertexType* nextPoint = contour->GetNextControlVertexAt(click, mitk::ContourModelLiveWireInteractor::eps, timeStep); const mitk::ContourModel::VertexType* previousPoint = contour->GetPreviousControlVertexAt(click, mitk::ContourModelLiveWireInteractor::eps, timeStep); this->SplitContourFromSelectedVertex(contour, nextPoint, previousPoint, timeStep); m_NextActiveVertexUp = nextPoint->Coordinates; m_NextActiveVertexDown = previousPoint->Coordinates; // clear previous void positions this->m_LiveWireFilter->ClearRepulsivePoints(); // all points in lower and upper part should be marked as repulsive points to not be changed this->SetRepulsivePoints(previousPoint, m_ContourLeft, timeStep); this->SetRepulsivePoints(nextPoint, m_ContourRight, timeStep); // clear container with void points between neighboring control points m_ContourBeingModified.clear(); } return isVertexSelected; } void mitk::ContourModelLiveWireInteractor::SetWorkingImage(mitk::Image *_arg) { if (this->m_WorkingSlice != _arg) { this->m_WorkingSlice = _arg; this->m_LiveWireFilter->SetInput(this->m_WorkingSlice); } } void mitk::ContourModelLiveWireInteractor::OnAddPoint(StateMachineAction* sm, InteractionEvent* interactionEvent) { Superclass::OnAddPoint(sm, interactionEvent); } void mitk::ContourModelLiveWireInteractor::OnDeletePoint(StateMachineAction *, InteractionEvent *interactionEvent) { const auto timeStep = interactionEvent->GetSender()->GetTimeStep(GetDataNode()->GetData()); auto *contour = dynamic_cast<mitk::ContourModel *>(this->GetDataNode()->GetData()); if (contour == nullptr) { MITK_ERROR << "Invalid Contour!"; return; } if (contour->GetSelectedVertex()) { mitk::ContourModel::Pointer newContour = mitk::ContourModel::New(); newContour->Expand(contour->GetTimeSteps()); newContour->SetTimeGeometry(contour->GetTimeGeometry()->Clone()); newContour->Concatenate(m_ContourLeft, timeStep); // recompute contour between neighbored two active control points this->m_LiveWireFilter->SetStartPoint(this->m_NextActiveVertexDown); this->m_LiveWireFilter->SetEndPoint(this->m_NextActiveVertexUp); this->m_LiveWireFilter->Update(); mitk::ContourModel *liveWireContour = this->m_LiveWireFilter->GetOutput(); assert(liveWireContour); if (liveWireContour->IsEmpty(timeStep)) return; liveWireContour->RemoveVertexAt(0, timeStep); liveWireContour->RemoveVertexAt(liveWireContour->GetNumberOfVertices(timeStep) - 1, timeStep); // insert new live wire computed points newContour->Concatenate(liveWireContour, timeStep); // insert right side of original contour newContour->Concatenate(this->m_ContourRight, timeStep); newContour->SetClosed(contour->IsClosed(timeStep), timeStep); // instead of leaving a single point, delete all points if (newContour->GetNumberOfVertices(timeStep) <= 2) { newContour->Clear(timeStep); } this->GetDataNode()->SetData(newContour); mitk::RenderingManager::GetInstance()->RequestUpdate(interactionEvent->GetSender()->GetRenderWindow()); } } void mitk::ContourModelLiveWireInteractor::OnMovePoint(StateMachineAction *, InteractionEvent *interactionEvent) { const auto *positionEvent = dynamic_cast<const InteractionPositionEvent *>(interactionEvent); if (!positionEvent) return; const auto timeStep = interactionEvent->GetSender()->GetTimeStep(GetDataNode()->GetData()); mitk::Point3D currentPosition = positionEvent->GetPositionInWorld(); auto *contour = dynamic_cast<mitk::ContourModel *>(this->GetDataNode()->GetData()); if (contour == nullptr) { MITK_ERROR << "invalid contour"; return; } std::cout << currentPosition << std::endl; mitk::ContourModel::Pointer editingContour = mitk::ContourModel::New(); editingContour->Expand(contour->GetTimeSteps()); editingContour->SetTimeGeometry(contour->GetTimeGeometry()->Clone()); // recompute left live wire, i.e. the contour between previous active vertex and selected vertex this->m_LiveWireFilter->SetStartPoint(this->m_NextActiveVertexDown); this->m_LiveWireFilter->SetEndPoint(currentPosition); // remove void positions between previous active vertex and next active vertex. if (!m_ContourBeingModified.empty()) { std::vector<itk::Index<2>>::const_iterator iter = m_ContourBeingModified.begin(); for (; iter != m_ContourBeingModified.end(); iter++) { this->m_LiveWireFilter->RemoveRepulsivePoint((*iter)); } } // update to get the left livewire. Remember that the points in the rest of the contour are already // set as void positions in the filter this->m_LiveWireFilter->Update(); mitk::ContourModel::Pointer leftLiveWire = this->m_LiveWireFilter->GetOutput(); assert(leftLiveWire); if (!leftLiveWire->IsEmpty(timeStep)) leftLiveWire->RemoveVertexAt(0, timeStep); editingContour->Concatenate(leftLiveWire, timeStep); // the new index of the selected vertex unsigned int selectedVertexIndex = this->m_ContourLeft->GetNumberOfVertices(timeStep) + leftLiveWire->GetNumberOfVertices(timeStep) - 1; // at this point the container has to be empty m_ContourBeingModified.clear(); // add points from left live wire contour auto iter = leftLiveWire->IteratorBegin(timeStep); for (; iter != leftLiveWire->IteratorEnd(timeStep); iter++) { itk::Index<2> idx; this->m_WorkingSlice->GetGeometry()->WorldToIndex((*iter)->Coordinates, idx); this->m_LiveWireFilter->AddRepulsivePoint(idx); // add indices m_ContourBeingModified.push_back(idx); } // recompute right live wire, i.e. the contour between selected vertex and next active vertex this->m_LiveWireFilter->SetStartPoint(currentPosition); this->m_LiveWireFilter->SetEndPoint(m_NextActiveVertexUp); // update filter with all contour points set as void but the right live wire portion to be calculated now this->m_LiveWireFilter->Update(); mitk::ContourModel::Pointer rightLiveWire = this->m_LiveWireFilter->GetOutput(); assert(rightLiveWire); if (!leftLiveWire->IsEmpty(timeStep)) leftLiveWire->SetControlVertexAt(leftLiveWire->GetNumberOfVertices() - 1, timeStep); if (!rightLiveWire->IsEmpty(timeStep)) rightLiveWire->RemoveVertexAt(0, timeStep); editingContour->Concatenate(rightLiveWire, timeStep); mitk::ContourModel::Pointer newContour = mitk::ContourModel::New(); newContour->Expand(contour->GetTimeSteps()); newContour->SetTimeGeometry(contour->GetTimeGeometry()->Clone()); // concatenate left original contour newContour->Concatenate(this->m_ContourLeft, timeStep); newContour->Concatenate(editingContour, timeStep, true); // set last inserted vertex as selected newContour->SelectVertexAt(selectedVertexIndex, timeStep); // set as control point newContour->SetSelectedVertexAsControlPoint(true); // concatenate right original contour newContour->Concatenate(this->m_ContourRight, timeStep); newContour->SetClosed(contour->IsClosed(timeStep), timeStep); this->GetDataNode()->SetData(newContour); mitk::RenderingManager::GetInstance()->RequestUpdate(positionEvent->GetSender()->GetRenderWindow()); } void mitk::ContourModelLiveWireInteractor::SplitContourFromSelectedVertex(mitk::ContourModel *srcContour, const mitk::ContourModel::VertexType *nextPoint, const mitk::ContourModel::VertexType *previousPoint, int timeStep) { m_ContourLeft = mitk::ContourModel::New(); m_ContourRight = mitk::ContourModel::New(); auto it = srcContour->IteratorBegin(); // part between nextPoint and end of Countour bool upperPart = false; // part between start of countour and previousPoint bool lowerPart = true; // edge cases when point right before first control vertex is selected or first control vertex is selected if (nextPoint == (*it) || srcContour->GetSelectedVertex() == (*it)) { upperPart = true; lowerPart = false; m_ContourLeft->AddVertex(previousPoint->Coordinates, previousPoint->IsControlPoint, timeStep); } // if first control vertex is selected, move to next point before adding vertices to m_ContourRight // otherwise, second line appears when moving the vertex if (srcContour->GetSelectedVertex() == (*it)) { while (*it != nextPoint) { it++; } } for (; it != srcContour->IteratorEnd(timeStep); it++) { // everything in lower part should be added to m_CountoutLeft if (lowerPart) { m_ContourLeft->AddVertex((*it)->Coordinates, (*it)->IsControlPoint, timeStep); } // start of "restricted area" where no vertex should be added to m_CountoutLeft or m_CountoutRight if (*it == previousPoint) { lowerPart = false; upperPart = false; } // start of upperPart if (*it == nextPoint) { upperPart = true; } // everything in upper part should be added to m_CountoutRight if (upperPart) { m_ContourRight->AddVertex((*it)->Coordinates, (*it)->IsControlPoint, timeStep); } } } void mitk::ContourModelLiveWireInteractor::SetRepulsivePoints(const mitk::ContourModel::VertexType *pointToExclude, mitk::ContourModel *contour, int timeStep) { auto it = contour->IteratorBegin(); for (; it != contour->IteratorEnd(timeStep); it++) { if (*it != pointToExclude) { itk::Index<2> idx; this->m_WorkingSlice->GetGeometry()->WorldToIndex((*it)->Coordinates, idx); this->m_LiveWireFilter->AddRepulsivePoint(idx); } } } void mitk::ContourModelLiveWireInteractor::OnFinishEditing(StateMachineAction *, InteractionEvent *) { } <commit_msg>Remove output from changing livewire points<commit_after>/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkContourModelLiveWireInteractor.h" #include "mitkInteractionPositionEvent.h" #include "mitkToolManager.h" #include "mitkBaseRenderer.h" #include "mitkRenderingManager.h" #include <mitkInteractionConst.h> #include "mitkIOUtil.h" mitk::ContourModelLiveWireInteractor::ContourModelLiveWireInteractor() : ContourModelInteractor() { m_LiveWireFilter = mitk::ImageLiveWireContourModelFilter::New(); m_LiveWireFilter->SetUseCostFunction(true); m_NextActiveVertexDown.Fill(0); m_NextActiveVertexUp.Fill(0); } mitk::ContourModelLiveWireInteractor::~ContourModelLiveWireInteractor() { } void mitk::ContourModelLiveWireInteractor::ConnectActionsAndFunctions() { CONNECT_CONDITION("checkisOverPoint", OnCheckPointClick); CONNECT_CONDITION("mouseMove", IsHovering); CONNECT_FUNCTION("movePoint", OnMovePoint); CONNECT_FUNCTION("deletePoint", OnDeletePoint); CONNECT_FUNCTION("addPoint", OnAddPoint) CONNECT_FUNCTION("finish", OnFinishEditing); } bool mitk::ContourModelLiveWireInteractor::OnCheckPointClick(const InteractionEvent *interactionEvent) { auto isVertexSelected = Superclass::OnCheckPointClick(interactionEvent); if (isVertexSelected) { auto* contour = dynamic_cast<mitk::ContourModel*>(this->GetDataNode()->GetData()); const auto* positionEvent = dynamic_cast<const mitk::InteractionPositionEvent*>(interactionEvent); mitk::Point3D click = positionEvent->GetPositionInWorld(); const auto timeStep = interactionEvent->GetSender()->GetTimeStep(GetDataNode()->GetData()); auto controlVertices = contour->GetControlVertices(timeStep); const mitk::ContourModel::VertexType* nextPoint = contour->GetNextControlVertexAt(click, mitk::ContourModelLiveWireInteractor::eps, timeStep); const mitk::ContourModel::VertexType* previousPoint = contour->GetPreviousControlVertexAt(click, mitk::ContourModelLiveWireInteractor::eps, timeStep); this->SplitContourFromSelectedVertex(contour, nextPoint, previousPoint, timeStep); m_NextActiveVertexUp = nextPoint->Coordinates; m_NextActiveVertexDown = previousPoint->Coordinates; // clear previous void positions this->m_LiveWireFilter->ClearRepulsivePoints(); // all points in lower and upper part should be marked as repulsive points to not be changed this->SetRepulsivePoints(previousPoint, m_ContourLeft, timeStep); this->SetRepulsivePoints(nextPoint, m_ContourRight, timeStep); // clear container with void points between neighboring control points m_ContourBeingModified.clear(); } return isVertexSelected; } void mitk::ContourModelLiveWireInteractor::SetWorkingImage(mitk::Image *_arg) { if (this->m_WorkingSlice != _arg) { this->m_WorkingSlice = _arg; this->m_LiveWireFilter->SetInput(this->m_WorkingSlice); } } void mitk::ContourModelLiveWireInteractor::OnAddPoint(StateMachineAction* sm, InteractionEvent* interactionEvent) { Superclass::OnAddPoint(sm, interactionEvent); } void mitk::ContourModelLiveWireInteractor::OnDeletePoint(StateMachineAction *, InteractionEvent *interactionEvent) { const auto timeStep = interactionEvent->GetSender()->GetTimeStep(GetDataNode()->GetData()); auto *contour = dynamic_cast<mitk::ContourModel *>(this->GetDataNode()->GetData()); if (contour == nullptr) { MITK_ERROR << "Invalid Contour!"; return; } if (contour->GetSelectedVertex()) { mitk::ContourModel::Pointer newContour = mitk::ContourModel::New(); newContour->Expand(contour->GetTimeSteps()); newContour->SetTimeGeometry(contour->GetTimeGeometry()->Clone()); newContour->Concatenate(m_ContourLeft, timeStep); // recompute contour between neighbored two active control points this->m_LiveWireFilter->SetStartPoint(this->m_NextActiveVertexDown); this->m_LiveWireFilter->SetEndPoint(this->m_NextActiveVertexUp); this->m_LiveWireFilter->Update(); mitk::ContourModel *liveWireContour = this->m_LiveWireFilter->GetOutput(); assert(liveWireContour); if (liveWireContour->IsEmpty(timeStep)) return; liveWireContour->RemoveVertexAt(0, timeStep); liveWireContour->RemoveVertexAt(liveWireContour->GetNumberOfVertices(timeStep) - 1, timeStep); // insert new live wire computed points newContour->Concatenate(liveWireContour, timeStep); // insert right side of original contour newContour->Concatenate(this->m_ContourRight, timeStep); newContour->SetClosed(contour->IsClosed(timeStep), timeStep); // instead of leaving a single point, delete all points if (newContour->GetNumberOfVertices(timeStep) <= 2) { newContour->Clear(timeStep); } this->GetDataNode()->SetData(newContour); mitk::RenderingManager::GetInstance()->RequestUpdate(interactionEvent->GetSender()->GetRenderWindow()); } } void mitk::ContourModelLiveWireInteractor::OnMovePoint(StateMachineAction *, InteractionEvent *interactionEvent) { const auto *positionEvent = dynamic_cast<const InteractionPositionEvent *>(interactionEvent); if (!positionEvent) return; const auto timeStep = interactionEvent->GetSender()->GetTimeStep(GetDataNode()->GetData()); mitk::Point3D currentPosition = positionEvent->GetPositionInWorld(); auto *contour = dynamic_cast<mitk::ContourModel *>(this->GetDataNode()->GetData()); if (contour == nullptr) { MITK_ERROR << "invalid contour"; return; } mitk::ContourModel::Pointer editingContour = mitk::ContourModel::New(); editingContour->Expand(contour->GetTimeSteps()); editingContour->SetTimeGeometry(contour->GetTimeGeometry()->Clone()); // recompute left live wire, i.e. the contour between previous active vertex and selected vertex this->m_LiveWireFilter->SetStartPoint(this->m_NextActiveVertexDown); this->m_LiveWireFilter->SetEndPoint(currentPosition); // remove void positions between previous active vertex and next active vertex. if (!m_ContourBeingModified.empty()) { std::vector<itk::Index<2>>::const_iterator iter = m_ContourBeingModified.begin(); for (; iter != m_ContourBeingModified.end(); iter++) { this->m_LiveWireFilter->RemoveRepulsivePoint((*iter)); } } // update to get the left livewire. Remember that the points in the rest of the contour are already // set as void positions in the filter this->m_LiveWireFilter->Update(); mitk::ContourModel::Pointer leftLiveWire = this->m_LiveWireFilter->GetOutput(); assert(leftLiveWire); if (!leftLiveWire->IsEmpty(timeStep)) leftLiveWire->RemoveVertexAt(0, timeStep); editingContour->Concatenate(leftLiveWire, timeStep); // the new index of the selected vertex unsigned int selectedVertexIndex = this->m_ContourLeft->GetNumberOfVertices(timeStep) + leftLiveWire->GetNumberOfVertices(timeStep) - 1; // at this point the container has to be empty m_ContourBeingModified.clear(); // add points from left live wire contour auto iter = leftLiveWire->IteratorBegin(timeStep); for (; iter != leftLiveWire->IteratorEnd(timeStep); iter++) { itk::Index<2> idx; this->m_WorkingSlice->GetGeometry()->WorldToIndex((*iter)->Coordinates, idx); this->m_LiveWireFilter->AddRepulsivePoint(idx); // add indices m_ContourBeingModified.push_back(idx); } // recompute right live wire, i.e. the contour between selected vertex and next active vertex this->m_LiveWireFilter->SetStartPoint(currentPosition); this->m_LiveWireFilter->SetEndPoint(m_NextActiveVertexUp); // update filter with all contour points set as void but the right live wire portion to be calculated now this->m_LiveWireFilter->Update(); mitk::ContourModel::Pointer rightLiveWire = this->m_LiveWireFilter->GetOutput(); assert(rightLiveWire); if (!leftLiveWire->IsEmpty(timeStep)) leftLiveWire->SetControlVertexAt(leftLiveWire->GetNumberOfVertices() - 1, timeStep); if (!rightLiveWire->IsEmpty(timeStep)) rightLiveWire->RemoveVertexAt(0, timeStep); editingContour->Concatenate(rightLiveWire, timeStep); mitk::ContourModel::Pointer newContour = mitk::ContourModel::New(); newContour->Expand(contour->GetTimeSteps()); newContour->SetTimeGeometry(contour->GetTimeGeometry()->Clone()); // concatenate left original contour newContour->Concatenate(this->m_ContourLeft, timeStep); newContour->Concatenate(editingContour, timeStep, true); // set last inserted vertex as selected newContour->SelectVertexAt(selectedVertexIndex, timeStep); // set as control point newContour->SetSelectedVertexAsControlPoint(true); // concatenate right original contour newContour->Concatenate(this->m_ContourRight, timeStep); newContour->SetClosed(contour->IsClosed(timeStep), timeStep); this->GetDataNode()->SetData(newContour); mitk::RenderingManager::GetInstance()->RequestUpdate(positionEvent->GetSender()->GetRenderWindow()); } void mitk::ContourModelLiveWireInteractor::SplitContourFromSelectedVertex(mitk::ContourModel *srcContour, const mitk::ContourModel::VertexType *nextPoint, const mitk::ContourModel::VertexType *previousPoint, int timeStep) { m_ContourLeft = mitk::ContourModel::New(); m_ContourRight = mitk::ContourModel::New(); auto it = srcContour->IteratorBegin(); // part between nextPoint and end of Countour bool upperPart = false; // part between start of countour and previousPoint bool lowerPart = true; // edge cases when point right before first control vertex is selected or first control vertex is selected if (nextPoint == (*it) || srcContour->GetSelectedVertex() == (*it)) { upperPart = true; lowerPart = false; m_ContourLeft->AddVertex(previousPoint->Coordinates, previousPoint->IsControlPoint, timeStep); } // if first control vertex is selected, move to next point before adding vertices to m_ContourRight // otherwise, second line appears when moving the vertex if (srcContour->GetSelectedVertex() == (*it)) { while (*it != nextPoint) { it++; } } for (; it != srcContour->IteratorEnd(timeStep); it++) { // everything in lower part should be added to m_CountoutLeft if (lowerPart) { m_ContourLeft->AddVertex((*it)->Coordinates, (*it)->IsControlPoint, timeStep); } // start of "restricted area" where no vertex should be added to m_CountoutLeft or m_CountoutRight if (*it == previousPoint) { lowerPart = false; upperPart = false; } // start of upperPart if (*it == nextPoint) { upperPart = true; } // everything in upper part should be added to m_CountoutRight if (upperPart) { m_ContourRight->AddVertex((*it)->Coordinates, (*it)->IsControlPoint, timeStep); } } } void mitk::ContourModelLiveWireInteractor::SetRepulsivePoints(const mitk::ContourModel::VertexType *pointToExclude, mitk::ContourModel *contour, int timeStep) { auto it = contour->IteratorBegin(); for (; it != contour->IteratorEnd(timeStep); it++) { if (*it != pointToExclude) { itk::Index<2> idx; this->m_WorkingSlice->GetGeometry()->WorldToIndex((*it)->Coordinates, idx); this->m_LiveWireFilter->AddRepulsivePoint(idx); } } } void mitk::ContourModelLiveWireInteractor::OnFinishEditing(StateMachineAction *, InteractionEvent *) { } <|endoftext|>
<commit_before>/* * enlargeshrinkplugin.cpp * * Copyright (C) 2012 Igalia, S.L. * Author: Antia Puentes <apuentes@igalia.com> * * This file is part of the Gallery Enlarge/Shrink Plugin. * * 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; version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see http://www.gnu.org/licenses/ * */ #include "enlargeshrink.h" #include <math.h> #define FILTER_NAME_ENLARGESHRINK "com.igalia.enlargeshrink" #define FORCE_OPTION "force" #define FORCE_FACTOR 3.2 #ifndef M_PI #define M_PI 3.14159265358979323846264338327950288 #endif // Maximum "width" of a pixel, measured diagonally #ifndef M_SQRT2 #define M_SQRT2 1.41421356237309504880168872420969808 #endif #define FIXEDPOINT_FRACTIONBITS 8 #define FIXEDPOINT_MULTIPLIER (1 << FIXEDPOINT_FRACTIONBITS) static double fraction(double n) { return n - floor(n); } static int fixedfraction(double n) { return (int) (fraction(n) * FIXEDPOINT_MULTIPLIER); } static QRgb weighpixel(QRgb rgb, int percentage) { return qRgb((qRed(rgb) * percentage) >> (FIXEDPOINT_FRACTIONBITS * 2), (qGreen(rgb) * percentage) >> (FIXEDPOINT_FRACTIONBITS * 2), (qBlue(rgb) * percentage) >> (FIXEDPOINT_FRACTIONBITS * 2)); } /* * Gets a pixel at a floating-point coordinate, thus causing it to take into * accountance neighbour pixels if one of the coordinates have a fractional part * * The function will calculate the pixel value by calculating all areas the * pixel occupies in each neighbouring pixel. */ static QRgb getPixel(const QImage &img, double x, double y) { int fx = fixedfraction(x); int fy = fixedfraction(y); int px = (int) x; int py = (int) y; int right = 1; if (px >= img.width() - 1) { right = 0; } int below = 1; if (py >= img.height() - 1) { below = 0; } QRgb p1 = weighpixel(img.pixel(px, py), (FIXEDPOINT_MULTIPLIER - fx) * (FIXEDPOINT_MULTIPLIER - fy)); QRgb p2 = weighpixel(img.pixel(px + right, py), fx * (FIXEDPOINT_MULTIPLIER - fy)); QRgb p3 = weighpixel(img.pixel(px, py + below), (FIXEDPOINT_MULTIPLIER - fx) * fy); QRgb p4 = weighpixel(img.pixel(px + right, py + below), fx * fy); return qRgb((qRed(p1) + qRed(p2) + qRed(p3) + qRed(p4)), (qGreen(p1) + qGreen(p2) + qGreen(p3) + qGreen(p4)), (qBlue(p1) + qBlue(p2) + qBlue(p3) + qBlue(p4))); } /** * Returns the enlarge/shrink effect for a given "n". * The function should be continous and should return 0 for x=0 and return 1 for * x = 1 if not, abrupt changes might appear in the image. The function only * needs to be valid for the interval [0..1]. * \a amplitude should be in the interval [-0.3125, 0.3125], if it is outside * this interval the function might return negative values (which might give * interesting effects but not an enlarge/shrink effect) * A positive \a amplitude will give a "punch", negative a "pinch" * * Keeping the function linear (return x;) will in theory not change the image, * but due to rounding errors one might expect minor distortion. */ static double distort(double n, double amplitude) { return n - sin(M_PI * n) * amplitude; } EnlargeShrink::EnlargeShrink() : m_Radius(0), m_Center(-1, -1), m_Force(0) { } EnlargeShrink::~EnlargeShrink() { } const QString EnlargeShrink::name() const { return FILTER_NAME_ENLARGESHRINK; } const QStringList EnlargeShrink::supportedOptions() const { QStringList supportedOptions; supportedOptions << QuillImageFilter::Radius << QuillImageFilter::Center << FORCE_OPTION; return supportedOptions; } bool EnlargeShrink::setOption(const QString &option, const QVariant &value) { bool ok = false; if (option == QuillImageFilter::Radius) { double radius = value.toDouble(&ok); if (ok) { m_Radius = radius; } } else if (option == QuillImageFilter::Center) { QPoint center = value.toPoint(); if (!center.isNull()) { m_Center = center; ok = true; } } else if (option == FORCE_OPTION) { double force = value.toDouble(&ok); ok = ok && force <= 1.0 && force >= -1.0; if (ok) { // Divide by the FORCE_FACTOR to get appropiated values for // the Amplitude used by the "distort" function m_Force = force/FORCE_FACTOR; } } return ok; } QVariant EnlargeShrink::option(const QString &option) const { QVariant value; if (option == QuillImageFilter::Radius) { value = m_Radius; } else if (option == QuillImageFilter::Center) { value = m_Center; } else if (option == FORCE_OPTION) { value = m_Force * FORCE_FACTOR; } return value; } QuillImage EnlargeShrink::apply(const QuillImage& image) const { if (image.fullImageSize().isEmpty()) { return QImage(); } QuillImage out; enlargeShrink(image, &out); return out; } double EnlargeShrink::getRadius(const QuillImage &img) const { double radius = m_Radius; if (!img.isFragment() || (img.width() == 170 && img.height() == 170)) { if (img.fullImageSize().width() < img.fullImageSize().height()) { radius = radius * img.width() / img.fullImageSize().width(); } else { radius = radius * img.height() / img.fullImageSize().height(); } } return radius; } QPoint EnlargeShrink::getCenter(const QuillImage &img) const { QPoint center = m_Center; if (!img.isFragment() || (img.width() == 170 && img.height() == 170)) { center.setX(center.x() * img.width() / img.fullImageSize().width()); center.setY(center.y() * img.height() / img.fullImageSize().height()); } return center; } bool EnlargeShrink::enlargeShrink(const QuillImage &img, QuillImage *outputImg) const { *outputImg = img; double radius = getRadius(img); QPoint center = getCenter(img); for (int y = 0; y < img.height(); y++) { for (int x = 0; x < img.width(); x++) { int dx = x - center.x(); int dy = y - center.y(); double distance = sqrt(dx * dx + dy * dy); if (distance <= radius + M_SQRT2) { // Evaluate the area inside the radius + this M_SQRT2 // (to reduce aliasing effects) double n = distance / radius; if (n > 0.0 && n < 1.0) { n = distort(n, m_Force); } // Normalize the distance vector< and find the length after // distortion if (dx != 0 || dy != 0) { double mag = n * radius/distance; dx = dx * mag; dy = dy * mag; } double tx = center.x() + dx; double ty = center.y() + dy; // Crop off overflows if (tx > img.width() || tx < 0) tx = x; if (ty > img.height() || ty < 0) ty = y; outputImg->setPixel(x, y, getPixel(img, tx, ty)); } } } return true; } <commit_msg>Fixed an overflow<commit_after>/* * enlargeshrinkplugin.cpp * * Copyright (C) 2012 Igalia, S.L. * Author: Antia Puentes <apuentes@igalia.com> * * This file is part of the Gallery Enlarge/Shrink Plugin. * * 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; version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see http://www.gnu.org/licenses/ * */ #include "enlargeshrink.h" #include <math.h> #define FILTER_NAME_ENLARGESHRINK "com.igalia.enlargeshrink" #define FORCE_OPTION "force" #define FORCE_FACTOR 3.2 #ifndef M_PI #define M_PI 3.14159265358979323846264338327950288 #endif // Maximum "width" of a pixel, measured diagonally #ifndef M_SQRT2 #define M_SQRT2 1.41421356237309504880168872420969808 #endif #define FIXEDPOINT_FRACTIONBITS 8 #define FIXEDPOINT_MULTIPLIER (1 << FIXEDPOINT_FRACTIONBITS) static double fraction(double n) { return n - floor(n); } static int fixedfraction(double n) { return (int) (fraction(n) * FIXEDPOINT_MULTIPLIER); } static QRgb weighpixel(QRgb rgb, int percentage) { return qRgb((qRed(rgb) * percentage) >> (FIXEDPOINT_FRACTIONBITS * 2), (qGreen(rgb) * percentage) >> (FIXEDPOINT_FRACTIONBITS * 2), (qBlue(rgb) * percentage) >> (FIXEDPOINT_FRACTIONBITS * 2)); } /* * Gets a pixel at a floating-point coordinate, thus causing it to take into * accountance neighbour pixels if one of the coordinates have a fractional part * * The function will calculate the pixel value by calculating all areas the * pixel occupies in each neighbouring pixel. */ static QRgb getPixel(const QImage &img, double x, double y) { int fx = fixedfraction(x); int fy = fixedfraction(y); int px = (int) x; int py = (int) y; int right = 1; if (px >= img.width() - 1) { right = 0; } int below = 1; if (py >= img.height() - 1) { below = 0; } QRgb p1 = weighpixel(img.pixel(px, py), (FIXEDPOINT_MULTIPLIER - fx) * (FIXEDPOINT_MULTIPLIER - fy)); QRgb p2 = weighpixel(img.pixel(px + right, py), fx * (FIXEDPOINT_MULTIPLIER - fy)); QRgb p3 = weighpixel(img.pixel(px, py + below), (FIXEDPOINT_MULTIPLIER - fx) * fy); QRgb p4 = weighpixel(img.pixel(px + right, py + below), fx * fy); return qRgb((qRed(p1) + qRed(p2) + qRed(p3) + qRed(p4)), (qGreen(p1) + qGreen(p2) + qGreen(p3) + qGreen(p4)), (qBlue(p1) + qBlue(p2) + qBlue(p3) + qBlue(p4))); } /** * Returns the enlarge/shrink effect for a given "n". * The function should be continous and should return 0 for x=0 and return 1 for * x = 1 if not, abrupt changes might appear in the image. The function only * needs to be valid for the interval [0..1]. * \a amplitude should be in the interval [-0.3125, 0.3125], if it is outside * this interval the function might return negative values (which might give * interesting effects but not an enlarge/shrink effect) * A positive \a amplitude will give a "punch", negative a "pinch" * * Keeping the function linear (return x;) will in theory not change the image, * but due to rounding errors one might expect minor distortion. */ static double distort(double n, double amplitude) { return n - sin(M_PI * n) * amplitude; } EnlargeShrink::EnlargeShrink() : m_Radius(0), m_Center(-1, -1), m_Force(0) { } EnlargeShrink::~EnlargeShrink() { } const QString EnlargeShrink::name() const { return FILTER_NAME_ENLARGESHRINK; } const QStringList EnlargeShrink::supportedOptions() const { QStringList supportedOptions; supportedOptions << QuillImageFilter::Radius << QuillImageFilter::Center << FORCE_OPTION; return supportedOptions; } bool EnlargeShrink::setOption(const QString &option, const QVariant &value) { bool ok = false; if (option == QuillImageFilter::Radius) { double radius = value.toDouble(&ok); if (ok) { m_Radius = radius; } } else if (option == QuillImageFilter::Center) { QPoint center = value.toPoint(); if (!center.isNull()) { m_Center = center; ok = true; } } else if (option == FORCE_OPTION) { double force = value.toDouble(&ok); ok = ok && force <= 1.0 && force >= -1.0; if (ok) { // Divide by the FORCE_FACTOR to get appropiated values for // the Amplitude used by the "distort" function m_Force = force/FORCE_FACTOR; } } return ok; } QVariant EnlargeShrink::option(const QString &option) const { QVariant value; if (option == QuillImageFilter::Radius) { value = m_Radius; } else if (option == QuillImageFilter::Center) { value = m_Center; } else if (option == FORCE_OPTION) { value = m_Force * FORCE_FACTOR; } return value; } QuillImage EnlargeShrink::apply(const QuillImage& image) const { if (image.fullImageSize().isEmpty()) { return QImage(); } QuillImage out; enlargeShrink(image, &out); return out; } double EnlargeShrink::getRadius(const QuillImage &img) const { double radius = m_Radius; if (!img.isFragment() || (img.width() == 170 && img.height() == 170)) { if (img.fullImageSize().width() < img.fullImageSize().height()) { radius = radius * img.width() / img.fullImageSize().width(); } else { radius = radius * img.height() / img.fullImageSize().height(); } } return radius; } QPoint EnlargeShrink::getCenter(const QuillImage &img) const { QPoint center = m_Center; if (!img.isFragment() || (img.width() == 170 && img.height() == 170)) { center.setX(center.x() * img.width() / img.fullImageSize().width()); center.setY(center.y() * img.height() / img.fullImageSize().height()); } return center; } bool EnlargeShrink::enlargeShrink(const QuillImage &img, QuillImage *outputImg) const { *outputImg = img; double radius = getRadius(img); QPoint center = getCenter(img); for (int y = 0; y < img.height(); y++) { for (int x = 0; x < img.width(); x++) { int dx = x - center.x(); int dy = y - center.y(); double distance = sqrt(dx * dx + dy * dy); if (distance <= radius + M_SQRT2) { // Evaluate the area inside the radius + this M_SQRT2 // (to reduce aliasing effects) double n = distance / radius; if (n > 0.0 && n < 1.0) { n = distort(n, m_Force); } // Normalize the distance vector< and find the length after // distortion if (dx != 0 || dy != 0) { double mag = n * radius/distance; dx = dx * mag; dy = dy * mag; } double tx = center.x() + dx; double ty = center.y() + dy; // Crop off overflows if (tx >= img.width() || tx < 0) tx = x; if (ty >= img.height() || ty < 0) ty = y; outputImg->setPixel(x, y, getPixel(img, tx, ty)); } } } return true; } <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Log$ Revision 1.1.4.1 2000/05/08 15:13:59 cblume Introduce boundary checking Revision 1.1 2000/02/28 18:59:19 cblume Add new TRD classes */ /////////////////////////////////////////////////////////////////////////////// // // // Base class of a general container for data of a TRD detector segment. // // Adapted from AliDigits (origin: M.Ivanov). // // // /////////////////////////////////////////////////////////////////////////////// #include "TClass.h" #include "TError.h" #include "AliTRDsegmentID.h" #include "AliTRDarrayI.h" #include "AliTRDdataArray.h" ClassImp(AliTRDdataArray) //_____________________________________________________________________________ AliTRDdataArray::AliTRDdataArray() { // // Default constructor // fIndex = 0; fNdim1 = -1; fNdim2 = -1; fNelems = -1; fBufType = -1; fNrow = 0; fNcol = 0; fNtime = 0; } //_____________________________________________________________________________ AliTRDdataArray::AliTRDdataArray(Int_t nrow, Int_t ncol, Int_t ntime) { // // Creates a AliTRDdataArray with the dimensions <nrow>, <ncol>, and <ntime>. // The row- and column dimensions are compressible. // Allocate(nrow,ncol,ntime); } //_____________________________________________________________________________ AliTRDdataArray::~AliTRDdataArray() { // // Destructor // if (fIndex) fIndex->Delete(); } //_____________________________________________________________________________ void AliTRDdataArray::Allocate(Int_t nrow, Int_t ncol,Int_t ntime) { // // Allocates memory for a AliTRDdataArray with the dimensions // <nrow>, <ncol>, and <ntime>. // The row- and column dimensions are compressible. // if (nrow <= 0) { Error("AliTRDdataArray::Allocate","The number of rows has to be positive"); exit(1); } if (ncol <= 0) { Error("AliTRDdataArray::Allocate","The number of columns has to be positive"); exit(1); } if (ntime <= 0) { Error("AliTRDdataArray::Allocate","The number of timebins has to be positive"); exit(1); } // The two-dimensional array row/column gets mapped into the first // dimension of the array. The second array dimension, which is not compressible, // corresponds to the time direction fNdim1 = nrow * ncol; fNdim2 = ntime; fNelems = fNdim1 * fNdim2; fNrow = nrow; fNcol = ncol; fNtime = ntime; if (fIndex) delete fIndex; fIndex = new AliTRDarrayI; fIndex->Set(fNdim2); for (Int_t i = 0, k = 0; i < fNdim2; i++, k += fNdim1) { (*fIndex)[i] = k; } fBufType = 0; } //_____________________________________________________________________________ void AliTRDdataArray::Reset() { // // Reset the array (old content gets deleted) // if (fIndex) delete fIndex; fIndex = new AliTRDarrayI; fIndex->Set(0); fNdim1 = -1; fNdim2 = -1; fNelems = -1; fBufType = -1; fNrow = 0; fNcol = 0; fNtime = 0; } <commit_msg>Added #include <stdlib.h><commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Log$ Revision 1.2 2000/05/08 16:17:27 cblume Merge TRD-develop Revision 1.1.4.1 2000/05/08 15:13:59 cblume Introduce boundary checking Revision 1.1 2000/02/28 18:59:19 cblume Add new TRD classes */ /////////////////////////////////////////////////////////////////////////////// // // // Base class of a general container for data of a TRD detector segment. // // Adapted from AliDigits (origin: M.Ivanov). // // // /////////////////////////////////////////////////////////////////////////////// #include <stdlib.h> #include "TClass.h" #include "TError.h" #include "AliTRDsegmentID.h" #include "AliTRDarrayI.h" #include "AliTRDdataArray.h" ClassImp(AliTRDdataArray) //_____________________________________________________________________________ AliTRDdataArray::AliTRDdataArray() { // // Default constructor // fIndex = 0; fNdim1 = -1; fNdim2 = -1; fNelems = -1; fBufType = -1; fNrow = 0; fNcol = 0; fNtime = 0; } //_____________________________________________________________________________ AliTRDdataArray::AliTRDdataArray(Int_t nrow, Int_t ncol, Int_t ntime) { // // Creates a AliTRDdataArray with the dimensions <nrow>, <ncol>, and <ntime>. // The row- and column dimensions are compressible. // Allocate(nrow,ncol,ntime); } //_____________________________________________________________________________ AliTRDdataArray::~AliTRDdataArray() { // // Destructor // if (fIndex) fIndex->Delete(); } //_____________________________________________________________________________ void AliTRDdataArray::Allocate(Int_t nrow, Int_t ncol,Int_t ntime) { // // Allocates memory for a AliTRDdataArray with the dimensions // <nrow>, <ncol>, and <ntime>. // The row- and column dimensions are compressible. // if (nrow <= 0) { Error("AliTRDdataArray::Allocate","The number of rows has to be positive"); exit(1); } if (ncol <= 0) { Error("AliTRDdataArray::Allocate","The number of columns has to be positive"); exit(1); } if (ntime <= 0) { Error("AliTRDdataArray::Allocate","The number of timebins has to be positive"); exit(1); } // The two-dimensional array row/column gets mapped into the first // dimension of the array. The second array dimension, which is not compressible, // corresponds to the time direction fNdim1 = nrow * ncol; fNdim2 = ntime; fNelems = fNdim1 * fNdim2; fNrow = nrow; fNcol = ncol; fNtime = ntime; if (fIndex) delete fIndex; fIndex = new AliTRDarrayI; fIndex->Set(fNdim2); for (Int_t i = 0, k = 0; i < fNdim2; i++, k += fNdim1) { (*fIndex)[i] = k; } fBufType = 0; } //_____________________________________________________________________________ void AliTRDdataArray::Reset() { // // Reset the array (old content gets deleted) // if (fIndex) delete fIndex; fIndex = new AliTRDarrayI; fIndex->Set(0); fNdim1 = -1; fNdim2 = -1; fNelems = -1; fBufType = -1; fNrow = 0; fNcol = 0; fNtime = 0; } <|endoftext|>