text
stringlengths
54
60.6k
<commit_before>#include <Element.h> #include <FWPlatform.h> #include <HeadingText.h> #include <TextLabel.h> #include <LinearLayout.h> #include <FWApplication.h> #include <cassert> using namespace std; int Element::nextInternalId = 1; Element::~Element() { if (platform) { platform->unregisterElement(this); } } void Element::initialize(FWPlatform * _platform) { assert(_platform); if (_platform) { platform = _platform; platform->registerElement(this); create(); for (auto & c : pendingCommands) { sendCommand(c); } pendingCommands.clear(); } assert(isInitialized()); } void Element::initializeChildren() { assert(isInitialized()); if (isInitialized()) { for (auto & c : getChildren()) { c->initialize(platform); c->initializeChildren(); } } } void Element::setError(bool t) { if ((t && !has_error) || (!t && has_error)) { has_error = t; cerr << "setting error to " << has_error << endl; Command c(Command::SET_ERROR, getInternalId()); c.setValue(t ? 1 : 0); if (t) c.setTextValue("Arvo ei kelpaa!"); sendCommand(c); } } void Element::setEnabled(bool _is_enabled) { is_enabled = _is_enabled; Command c(Command::SET_ENABLED, getInternalId()); c.setValue(is_enabled ? 1 : 0); sendCommand(c); } void Element::show() { is_visible = true; Command c(Command::SET_VISIBILITY, getInternalId()); c.setValue(1); sendCommand(c); } void Element::hide() { is_visible = false; Command c(Command::SET_VISIBILITY, getInternalId()); c.setValue(0); sendCommand(c); } void Element::style(const std::string & key, const std::string & value) { Command c(Command::SET_STYLE, getInternalId()); c.setTextValue(key); c.setTextValue2(value); sendCommand(c); } void Element::sendCommand(const Command & command) { if (platform) { platform->sendCommand2(command); } else { pendingCommands.push_back(command); } } Element & Element::addHeading(const std::string & text) { return addChild(make_shared<HeadingText>(text)); } Element & Element::addText(const std::string & text) { return addChild(make_shared<TextLabel>(text)); } Element & Element::addHorizontalLayout(int _id) { return addChild(make_shared<LinearLayout>(FW_HORIZONTAL, _id)); } Element & Element::addVerticalLayout(int _id) { return addChild(make_shared<LinearLayout>(FW_VERTICAL, _id)); } void Element::onEvent(Event & ev) { if (!ev.isHandled()) { if (ev.isBroadcast()) { for (auto & c : getChildren()){ ev.dispatch(*c); } } else if (parent) { ev.dispatch(*parent); } } } void Element::showMessageDialog(const std::string & title, const std::string & text) { Command c(Command::SHOW_MESSAGE_DIALOG, getParentInternalId(), getInternalId()); c.setTextValue(title); c.setTextValue2(text); sendCommand(c); } std::string Element::showInputDialog(const std::string & title, const std::string & text) { Command c(Command::SHOW_INPUT_DIALOG, getParentInternalId(), getInternalId()); c.setTextValue(title); c.setTextValue2(text); sendCommand(c); return platform->getModalResultText(); } void Element::showToast(const std::string & message, int duration) { Command c(Command::CREATE_TOAST, getParentInternalId(), getInternalId()); c.setTextValue(message); c.setValue(duration); sendCommand(c); } FWApplication & Element::getApplication() { auto p = getPlatform().getFirstChild(); return dynamic_cast<FWApplication&>(*p); } const FWApplication & Element::getApplication() const { auto p = getPlatform().getFirstChild(); return dynamic_cast<const FWApplication&>(*p); } void Element::removeChild(Element * child) { for (auto it = children.begin(); it != children.end(); it++) { if (it->get() == child) { sendCommand(Command(Command::DELETE_ELEMENT, getInternalId(), child->getInternalId())); children.erase(it); return; } } } <commit_msg>fix crash<commit_after>#include <Element.h> #include <FWPlatform.h> #include <HeadingText.h> #include <TextLabel.h> #include <LinearLayout.h> #include <FWApplication.h> #include <cassert> using namespace std; int Element::nextInternalId = 1; Element::~Element() { // the platform itself cannot be unregistered at this point if (platform && this != platform) { platform->unregisterElement(this); } } void Element::initialize(FWPlatform * _platform) { assert(_platform); if (_platform) { platform = _platform; platform->registerElement(this); create(); for (auto & c : pendingCommands) { sendCommand(c); } pendingCommands.clear(); } assert(isInitialized()); } void Element::initializeChildren() { assert(isInitialized()); if (isInitialized()) { for (auto & c : getChildren()) { c->initialize(platform); c->initializeChildren(); } } } void Element::setError(bool t) { if ((t && !has_error) || (!t && has_error)) { has_error = t; cerr << "setting error to " << has_error << endl; Command c(Command::SET_ERROR, getInternalId()); c.setValue(t ? 1 : 0); if (t) c.setTextValue("Arvo ei kelpaa!"); sendCommand(c); } } void Element::setEnabled(bool _is_enabled) { is_enabled = _is_enabled; Command c(Command::SET_ENABLED, getInternalId()); c.setValue(is_enabled ? 1 : 0); sendCommand(c); } void Element::show() { is_visible = true; Command c(Command::SET_VISIBILITY, getInternalId()); c.setValue(1); sendCommand(c); } void Element::hide() { is_visible = false; Command c(Command::SET_VISIBILITY, getInternalId()); c.setValue(0); sendCommand(c); } void Element::style(const std::string & key, const std::string & value) { Command c(Command::SET_STYLE, getInternalId()); c.setTextValue(key); c.setTextValue2(value); sendCommand(c); } void Element::sendCommand(const Command & command) { if (platform) { platform->sendCommand2(command); } else { pendingCommands.push_back(command); } } Element & Element::addHeading(const std::string & text) { return addChild(make_shared<HeadingText>(text)); } Element & Element::addText(const std::string & text) { return addChild(make_shared<TextLabel>(text)); } Element & Element::addHorizontalLayout(int _id) { return addChild(make_shared<LinearLayout>(FW_HORIZONTAL, _id)); } Element & Element::addVerticalLayout(int _id) { return addChild(make_shared<LinearLayout>(FW_VERTICAL, _id)); } void Element::onEvent(Event & ev) { if (!ev.isHandled()) { if (ev.isBroadcast()) { for (auto & c : getChildren()){ ev.dispatch(*c); } } else if (parent) { ev.dispatch(*parent); } } } void Element::showMessageDialog(const std::string & title, const std::string & text) { Command c(Command::SHOW_MESSAGE_DIALOG, getParentInternalId(), getInternalId()); c.setTextValue(title); c.setTextValue2(text); sendCommand(c); } std::string Element::showInputDialog(const std::string & title, const std::string & text) { Command c(Command::SHOW_INPUT_DIALOG, getParentInternalId(), getInternalId()); c.setTextValue(title); c.setTextValue2(text); sendCommand(c); return platform->getModalResultText(); } void Element::showToast(const std::string & message, int duration) { Command c(Command::CREATE_TOAST, getParentInternalId(), getInternalId()); c.setTextValue(message); c.setValue(duration); sendCommand(c); } FWApplication & Element::getApplication() { auto p = getPlatform().getFirstChild(); return dynamic_cast<FWApplication&>(*p); } const FWApplication & Element::getApplication() const { auto p = getPlatform().getFirstChild(); return dynamic_cast<const FWApplication&>(*p); } void Element::removeChild(Element * child) { for (auto it = children.begin(); it != children.end(); it++) { if (it->get() == child) { sendCommand(Command(Command::DELETE_ELEMENT, getInternalId(), child->getInternalId())); children.erase(it); return; } } } <|endoftext|>
<commit_before>///////////////////////////////////////////////////////////////////// // = NMatrix // // A linear algebra library for scientific computation in Ruby. // NMatrix is part of SciRuby. // // NMatrix was originally inspired by and derived from NArray, by // Masahiro Tanaka: http://narray.rubyforge.org // // == Copyright Information // // SciRuby is Copyright (c) 2010 - 2012, Ruby Science Foundation // NMatrix is Copyright (c) 2012, Ruby Science Foundation // // Please see LICENSE.txt for additional copyright notices. // // == Contributing // // By contributing source code to SciRuby, you agree to be bound by // our Contributor Agreement: // // * https://github.com/SciRuby/sciruby/wiki/Contributor-Agreement // // == storage.c // // Code that is used by or involves more then one storage type. /* * Standard Includes */ /* * Project Includes */ #include "data/data.h" #include "storage.h" /* * Macros */ /* * Global Variables */ const char* const STYPE_NAMES[NUM_STYPES] { "dense", "list", "yale" } /* * Forward Declarations */ /* * Functions */ <commit_msg>Moved code from storage_templates.cpp into this file now that everything is being compiled by g++.<commit_after>///////////////////////////////////////////////////////////////////// // = NMatrix // // A linear algebra library for scientific computation in Ruby. // NMatrix is part of SciRuby. // // NMatrix was originally inspired by and derived from NArray, by // Masahiro Tanaka: http://narray.rubyforge.org // // == Copyright Information // // SciRuby is Copyright (c) 2010 - 2012, Ruby Science Foundation // NMatrix is Copyright (c) 2012, Ruby Science Foundation // // Please see LICENSE.txt for additional copyright notices. // // == Contributing // // By contributing source code to SciRuby, you agree to be bound by // our Contributor Agreement: // // * https://github.com/SciRuby/sciruby/wiki/Contributor-Agreement // // == storage.cpp // // Code that is used by or involves more then one storage type. /* * Standard Includes */ /* * Project Includes */ #include "data/data.h" #include "storage.h" /* * Macros */ /* * Global Variables */ const char* const STYPE_NAMES[NUM_STYPES] = { "dense", "list", "yale" }; /* * Forward Declarations */ // FIXME: Template //static void dense_storage_cast_copy_list_contents(void* lhs, const LIST* rhs, void* default_val, dtype_t l_dtype, dtype_t r_dtype, // size_t* pos, const size_t* shape, size_t rank, size_t max_elements, size_t recursions); // FIXME: Template //static void dense_storage_cast_copy_list_default(void* lhs, void* default_val, dtype_t l_dtype, dtype_t r_dtype, // size_t* pos, const size_t* shape, size_t rank, size_t max_elements, size_t recursions); /* * Functions */ ///////////////////////// // Templated Functions // ///////////////////////// #if false // To be fixed once each storage class is compiling on its own. /* * Convert (by creating a copy) from list storage to dense storage. * * FIXME: Add templating. */ DENSE_STORAGE* dense_storage_from_list(const LIST_STORAGE* rhs, dtype_t l_dtype) { DENSE_STORAGE* lhs; // Position in lhs->elements. size_t pos = 0; // allocate and copy shape size_t* shape = ALLOC_N(size_t, rhs->rank); memcpy(shape, rhs->shape, rhs->rank * sizeof(size_t)); lhs = dense_storage_create(l_dtype, shape, rhs->rank, NULL, 0); // recursively copy the contents dense_storage_cast_copy_list_contents(lhs->elements, rhs->rows, rhs->default_val, l_dtype, rhs->dtype, &pos, shape, lhs->rank, count_storage_max_elements((STORAGE*)rhs), rhs->rank-1); return lhs; } /* * Documentation goes here. * * FIXME: Add templating. */ DENSE_STORAGE* dense_storage_from_yale(const YALE_STORAGE* rhs, dtype_t l_dtype) { DENSE_STORAGE* lhs; // Position in lhs->elements. y_size_t i, j // Position in rhs->elements. y_size_t ija, ija_next, jj; // Position in dense to write to. y_size_t pos = 0; // Determine zero representation. void* R_ZERO = (char*)(rhs->a) + rhs->shape[0] * nm_sizeof[rhs->dtype]; // Allocate and set shape. size_t* shape = ALLOC_N(size_t, rhs->rank); memcpy(shape, rhs->shape, rhs->rank * sizeof(size_t)); lhs = dense_storage_create(l_dtype, shape, rhs->rank, NULL, 0); // Walk through rows. For each entry we set in dense, increment pos. for (i = rhs->shape[0]; i-- > 0;) { // Get boundaries of this row, store in ija and ija_next. YaleGetIJA(ija, rhs, i); YaleGetIJA(ija_next, rhs, i+1); if (ija == ija_next) { // Row is empty? // Write zeros in each column. for (j = rhs->shape[1]; j-- > 0;) { // Fill in zeros (except for diagonal) if (i == j) { cast_copy_value_single((char*)(lhs->elements) + pos*nm_sizeof[l_dtype], (char*)(rhs->a) + i*nm_sizeof[rhs->dtype], l_dtype, rhs->dtype); } else { cast_copy_value_single((char*)(lhs->elements) + pos*nm_sizeof[l_dtype], R_ZERO, l_dtype, rhs->dtype); } // Move to next dense position. ++pos; } } else { // Row contains entries: write those in each column, interspersed with zeros. YaleGetIJA(jj, rhs, ija); for (j = rhs->shape[1]; j-- > 0;) { if (i == j) { cast_copy_value_single((char*)(lhs->elements) + pos*nm_sizeof[l_dtype], (char*)(rhs->a) + i*nm_sizeof[rhs->dtype], l_dtype, rhs->dtype); } else if (j == jj) { // Copy from rhs. cast_copy_value_single((char*)(lhs->elements) + pos*nm_sizeof[l_dtype], (char*)(rhs->a) + ija*nm_sizeof[rhs->dtype], l_dtype, rhs->dtype); // Get next. ++ija; // Increment to next column ID (or go off the end). if (ija < ija_next) { YaleGetIJA(jj, rhs, ija); } else { jj = rhs->shape[1]; } } else { // j < jj // Insert zero. cast_copy_value_single((char*)(lhs->elements) + pos*nm_sizeof[l_dtype], R_ZERO, l_dtype, rhs->dtype); } // Move to next dense position. ++pos; } } } return lhs; } /* * Documentation goes here. * * FIXME: Add templating. */ LIST_STORAGE* list_storage_from_dense(const DENSE_STORAGE* rhs, int8_t l_dtype) { LIST_STORAGE* lhs; size_t pos = 0; void* l_default_val = ALLOC_N(char, nm_sizeof[l_dtype]); void* r_default_val = ALLOCA_N(char, nm_sizeof[rhs->dtype]); // clean up when finished with this function // allocate and copy shape and coords size_t *shape = ALLOC_N(size_t, rhs->rank), *coords = ALLOC_N(size_t, rhs->rank); memcpy(shape, rhs->shape, rhs->rank * sizeof(size_t)); memset(coords, 0, rhs->rank * sizeof(size_t)); // set list default_val to 0 if (l_dtype == NM_ROBJ) { *(VALUE*)l_default_val = INT2FIX(0); } else { memset(l_default_val, 0, nm_sizeof[l_dtype]); } // need test default value for comparing to elements in dense matrix if (rhs->dtype == l_dtype) { r_default_val = l_default_val; } else if (rhs->dtype == NM_ROBJ) { *(VALUE*)r_default_val = INT2FIX(0); } else { memset(r_default_val, 0, nm_sizeof[rhs->dtype]); } lhs = create_list_storage(l_dtype, shape, rhs->rank, l_default_val); lhs->rows = create_list(); cast_copy_list_contents_dense(lhs->rows, rhs->elements, r_default_val, l_dtype, rhs->dtype, &pos, coords, rhs->shape, rhs->rank, rhs->rank - 1); return lhs; } /* * Documentation goes here. * * FIXME: Add templating. */ LIST_STORAGE* list_storage_from_yale(const YALE_STORAGE* rhs, int8_t l_dtype) { LIST_STORAGE* lhs; NODE *last_added, *last_row_added = NULL; LIST* curr_row; y_size_t ija, ija_next, i, jj; bool add_diag; void* default_val = ALLOC_N(char, nm_sizeof[l_dtype]); void* R_ZERO = (char*)(rhs->a) + rhs->shape[0]*nm_sizeof[rhs->dtype]; void* insert_val; // allocate and copy shape size_t *shape = ALLOC_N(size_t, rhs->rank); shape[0] = rhs->shape[0]; shape[1] = rhs->shape[1]; // copy default value from the zero location in the Yale matrix SetFuncs[l_dtype][rhs->dtype](1, default_val, 0, R_ZERO, 0); lhs = create_list_storage(l_dtype, shape, rhs->rank, default_val); if (rhs->rank != 2) { rb_raise(nm_eStorageTypeError, "Can only convert matrices of rank 2 from yale."); } // Walk through rows and columns as if RHS were a dense matrix for (i = rhs->shape[0]; i-- > 0;) { // Get boundaries of beginning and end of row YaleGetIJA(ija, rhs, i); YaleGetIJA(ija_next, rhs, i+1); // Are we going to need to add a diagonal for this row? if (ElemEqEq[rhs->dtype][0]((char*)(rhs->a) + i*nm_sizeof[rhs->dtype], R_ZERO, 1, nm_sizeof[rhs->dtype])) { // zero add_diag = false; } else { // nonzero diagonal add_diag = true; } if (ija < ija_next || add_diag) { curr_row = create_list(); last_added = NULL; while (ija < ija_next) { YaleGetIJA(jj, rhs, ija); // what column number is this? // Is there a nonzero diagonal item between the previously added item and the current one? if (jj > i && add_diag) { // Allocate and copy insertion value insert_val = ALLOC_N(char, nm_sizeof[l_dtype]); SetFuncs[l_dtype][rhs->dtype](1, insert_val, 0, (char*)(rhs->a) + i*nm_sizeof[rhs->dtype], 0); // insert the item in the list at the appropriate location if (last_added) { last_added = list_insert_after(last_added, i, insert_val); } else { last_added = list_insert(curr_row, false, i, insert_val); } // don't add again! add_diag = false; } // now allocate and add the current item insert_val = ALLOC_N(char, nm_sizeof[l_dtype]); SetFuncs[l_dtype][rhs->dtype](1, insert_val, 0, (char*)(rhs->a) + ija*nm_sizeof[rhs->dtype], 0); if (last_added) { last_added = list_insert_after(last_added, jj, insert_val); } else { last_added = list_insert(curr_row, false, jj, insert_val); } ++ija; // move to next entry in Yale matrix } if (add_diag) { // still haven't added the diagonal. insert_val = ALLOC_N(char, nm_sizeof[l_dtype]); SetFuncs[l_dtype][rhs->dtype](1, insert_val, 0, (char*)(rhs->a) + i*nm_sizeof[rhs->dtype], 0); // insert the item in the list at the appropriate location if (last_added) { last_added = list_insert_after(last_added, i, insert_val); } else { last_added = list_insert(curr_row, false, i, insert_val); } } // Now add the list at the appropriate location if (last_row_added) { last_row_added = list_insert_after(last_row_added, i, curr_row); } else { last_row_added = list_insert(lhs->rows, false, i, curr_row); } } // end of walk through rows } return lhs; } /* * Documentation goes here. * * FIXME: Add templating. */ YALE_STORAGE* yale_storage_from_dense(const DENSE_STORAGE* rhs, int8_t l_dtype) { YALE_STORAGE* lhs; size_t i, j; y_size_t pos = 0, ndnz = 0, ija; size_t* shape; // Figure out values to write for zero in yale and compare to zero in dense void *R_ZERO = ALLOCA_N(char, nm_sizeof[rhs->dtype]); if (rhs->dtype == NM_ROBJ) { *(VALUE*)R_ZERO = INT2FIX(0); } else { memset(R_ZERO, 0, nm_sizeof[rhs->dtype]); } if (rhs->rank != 2) { rb_raise(nm_eStorageTypeError, "can only convert matrices of rank 2 to yale"); } // First, count the non-diagonal nonzeros for (i = rhs->shape[0]; i-- > 0;) { for (j = rhs->shape[1]; j-- > 0;) { if (i != j && !ElemEqEq[rhs->dtype][0]((char*)(rhs->elements) + pos*nm_sizeof[rhs->dtype], R_ZERO, 1, nm_sizeof[rhs->dtype])) { ++ndnz; } // move forward 1 position in dense matrix elements array ++pos; } } // Copy shape for yale construction shape = ALLOC_N(size_t, 2); shape[0] = rhs->shape[0]; shape[1] = rhs->shape[1]; // Create with minimum possible capacity -- just enough to hold all of the entries lhs = yale_storage_create(l_dtype, shape, 2, shape[0] + ndnz + 1); // Set the zero position in the yale matrix cast_copy_value_single((char*)(lhs->a) + shape[0]*nm_sizeof[l_dtype], R_ZERO, l_dtype, rhs->dtype); // Start just after the zero position. ija = lhs->shape[0]+1; pos = 0; // Copy contents for (i = 0; i < rhs->shape[0]; ++i) { // indicate the beginning of a row in the IJA array YaleSetIJA(i, lhs, ija); for (j = 0; j < rhs->shape[1]; ++j) { if (i == j) { // copy to diagonal cast_copy_value_single((char*)(lhs->a) + i*nm_sizeof[l_dtype], (char*)(rhs->elements) + pos*nm_sizeof[rhs->dtype], l_dtype, rhs->dtype); } else if (!ElemEqEq[rhs->dtype][0]((char*)(rhs->elements) + pos*nm_sizeof[rhs->dtype], R_ZERO, 1, nm_sizeof[rhs->dtype])) { // copy nonzero to LU YaleSetIJA(ija, lhs, j); // write column index cast_copy_value_single((char*)(lhs->a) + ija*nm_sizeof[l_dtype], (char*)(rhs->elements) + pos*nm_sizeof[rhs->dtype], l_dtype, rhs->dtype); ++ija; } ++pos; } } YaleSetIJA(i, lhs, ija); // indicate the end of the last row lhs->ndnz = ndnz; return lhs; } /* * Documentation goes here. * * FIXME: Add templating. */ YALE_STORAGE* yale_storage_from_list(const LIST_STORAGE* rhs, int8_t l_dtype) { YALE_STORAGE* lhs; size_t* shape; NODE *i_curr, *j_curr; y_size_t ija; size_t ndnz = count_list_storage_nd_elements(rhs); if (rhs->rank != 2) { rb_raise(nm_eStorageTypeError, "can only convert matrices of rank 2 to yale"); } if ((rhs->dtype == NM_ROBJ && *(VALUE*)(rhs->default_val) == INT2FIX(0)) || strncmp(rhs->default_val, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", nm_sizeof[rhs->dtype])) { rb_raise(nm_eStorageTypeError, "list matrix must have default value of 0 to convert to yale"); } // Copy shape for yale construction shape = ALLOC_N(size_t, 2); shape[0] = rhs->shape[0]; shape[1] = rhs->shape[1]; lhs = yale_storage_create(l_dtype, shape, 2, shape[0] + ndnz + 1); clear_diagonal_and_zero(lhs); // clear the diagonal and the zero location. ija = lhs->shape[0]+1; for (i_curr = rhs->rows->first; i_curr; i_curr = i_curr->next) { // indicate the beginning of a row in the IJA array YaleSetIJA(i_curr->key, lhs, ija); for (j_curr = ((LIST*)(i_curr->val))->first; j_curr; j_curr = j_curr->next) { if (i_curr->key == j_curr->key) { // set diagonal SetFuncs[l_dtype][rhs->dtype](1, (char*)(lhs->a) + (i_curr->key)*nm_sizeof[l_dtype], 0, j_curr->val, 0); } else { // set column value YaleSetIJA(ija, lhs, j_curr->key); // write column index // set cell value SetFuncs[l_dtype][rhs->dtype](1, (char*)(lhs->a) + ija*nm_sizeof[l_dtype], 0, j_curr->val, 0); ++ija; } } if (!i_curr->next) { // indicate the end of the last row YaleSetIJA(i_curr->key, lhs, ija); } } lhs->ndnz = ndnz; return lhs; } ////////////////////// // Helper Functions // ////////////////////// /* * Copy list contents into dense recursively. */ static void dense_storage_cast_copy_list_contents(void* lhs, const LIST* rhs, void* default_val, dtype_t l_dtype, dtype_t r_dtype,size_t* pos, const size_t* shape, size_t rank, size_t max_elements, size_t recursions) { NODE *curr = rhs->first; int last_key = -1; size_t i = 0; for (i = shape[rank - 1 - recursions]; i-- > 0; ++(*pos) { if (!curr || (curr->key > (size_t)(last_key+1))) { //fprintf(stderr, "pos = %u, dim = %u, curr->key XX, last_key+1 = %d\t", *pos, shape[rank-1-recursions], last_key+1); if (recursions == 0) { cast_copy_value_single((char*)lhs + (*pos)*nm_sizeof[l_dtype], default_val, l_dtype, r_dtype); //fprintf(stderr, "zero\n"); } else { dense_storage_cast_copy_list_default(lhs, default_val, l_dtype, r_dtype, pos, shape, rank, max_elements, recursions-1); //fprintf(stderr, "column of zeros\n"); } ++last_key; } else { //fprintf(stderr, "pos = %u, dim = %u, curr->key = %u, last_key+1 = %d\t", *pos, shape[rank-1-recursions], curr->key, last_key+1); if (recursions == 0) { cast_copy_value_single((char*)lhs + (*pos)*nm_sizeof[l_dtype], curr->val, l_dtype, r_dtype); //fprintf(stderr, "zero\n"); } else { dense_storage_cast_copy_list_default(lhs, curr->val, default_val, l_dtype, r_dtype, pos, shape, rank, max_elements, recursions-1); //fprintf(stderr, "column of zeros\n"); } last_key = curr->key; curr = curr->next; } } --(*pos); } /* * Copy a set of default values into dense. */ static void dense_storage_cast_copy_list_default(void* lhs, void* default_val, dtype_t l_dtype, dtype_t r_dtype, size_t* pos, const size_t* shape, size_t rank, size_t max_elements, size_t recursions) { size_t i; for (i = shape[rank - 1 - recursions]; i-- > 0; ++(*pos)) { //fprintf(stderr, "default: pos = %u, dim = %u\t", *pos, shape[rank-1-recursions]); if (recursions == 0) { cast_copy_value_single((char*)lhs + (*pos)*nm_sizeof[l_dtype], default_val, l_dtype, r_dtype); //fprintf(stderr, "zero\n"); } else { dense_storage_cast_copy_list_default(lhs, default_val, l_dtype, r_dtype, pos, shape, rank, max_elements, recursions-1); //fprintf(stderr, "column of zeros\n"); } } --(*pos); } #endif <|endoftext|>
<commit_before>/* =========================================================================== Daemon GPL Source Code Copyright (C) 2013 Unvanquished Developers This file is part of the Daemon GPL Source Code (Daemon Source Code). Daemon Source Code 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. Daemon Source Code 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 Daemon Source Code. If not, see <http://www.gnu.org/licenses/>. =========================================================================== */ #include "Command.h" #include "Log.h" #include "../engine/qcommon/qcommon.h" #include "../engine/framework/CommandSystem.h" #include "../engine/framework/CvarSystem.h" namespace Cmd { std::string Escape(Str::StringRef text) { std::string res = "\""; for (size_t i = 0; i < text.size(); i ++) { if (text[i] == '\\') { res.append("\\\\"); } else if (text[i] == '\"') { res.append("\\\""); } else { res.push_back(text[i]); } } res += "\""; return res; } static bool SkipSpaces(std::string::const_iterator& in, std::string::const_iterator end) { bool foundSpace = false; while (in != end) { // Handle spaces if ((in[0] & 0xff) <= ' ') { foundSpace = true; in++; } else if (in + 1 != end) { // Handle // comments if (in[0] == '/' && in[1] == '/') { in = end; return true; } // Handle /* */ comments if (in[0] == '/' && in[1] == '*') { foundSpace = true; in += 2; while (in != end) { if (in + 1 != end && in[0] == '*' && in[1] == '/') { in += 2; break; } else { in++; } } } else { // Non-space character return foundSpace; } } else { // Non-space character return foundSpace; } } return true; } const char* SplitCommand(const char* start, const char* end) { bool inQuote = false; bool inComment = false; bool inInlineComment = false; while (start != end) { //End of comment if (inInlineComment && start + 1 != end && start[0] == '*' && start[1] == '/') { inInlineComment = false; start += 2; continue; } //Ignore everything else in an inline comment if (inInlineComment) { start++; continue; } //Start of comment if (not inQuote && not inComment && start + 1 != end && start[0] == '/' && start[1] == '*') { inInlineComment = true; start += 2; continue; } if (not inQuote && start + 1 != end && start[0] == '/' && start[1] == '/') { inComment = true; start += 2; continue; } //Escaped quote if (inQuote && start + 1 != end && start[0] == '\\') { start += 2; continue; } //Quote if (start[0] == '"') { inQuote = !inQuote; start++; continue; } //Semicolon if (start[0] == ';' && !inQuote && !inComment) { return start + 1; } //Newline if (start[0] == '\n') { return start + 1; } //Normal character start++; } return end; } std::string SubstituteCvars(Str::StringRef text) { const char* raw_text = text.data(); std::string result; bool isEscaped = false; bool inCvarName = false; int lastBlockStart = 0; //Cvar are delimited by $ so we parse a bloc at a time for(size_t i = 0; i < text.size(); i++){ // a \ escapes the next letter so we don't use it for block delimitation if (isEscaped) { isEscaped = false; continue; } if (text[i] == '\\') { isEscaped = true; } else if (text[i] == '$') { //Found a block, every second block is a cvar name block std::string block(raw_text + lastBlockStart, i - lastBlockStart); if (inCvarName) { result += Escape(Cvar::GetValue(block)); inCvarName = false; } else { result += block; inCvarName = true; } lastBlockStart = i + 1; } } //Handle the last block if (inCvarName) { Com_Printf("Warning: last CVar substitution block not closed in %s\n", raw_text); } else { std::string block(raw_text + lastBlockStart, text.size() - lastBlockStart); result += block; } return result; } /* =============================================================================== Cmd::CmdArgs =============================================================================== */ Args::Args() { } Args::Args(std::vector<std::string> args_) { args = std::move(args_); for (size_t i = 0; i < args.size(); i++) { argsStarts.push_back(cmd.size()); cmd += Escape(args[i]); if (i != args.size() - 1) { cmd += " "; } } } Args::Args(std::string command) { cmd = std::move(command); std::string::const_iterator in = cmd.begin(); //Skip leading whitespace SkipSpaces(in, cmd.end()); //Return if the cmd is empty if (in == cmd.end()) return; //Build arg tokens std::string currentToken; int currentTokenStart = in - cmd.begin(); while (true) { //Check for end of current token if (SkipSpaces(in, cmd.end())) { args.push_back(std::move(currentToken)); argsStarts.push_back(currentTokenStart); if (in == cmd.end()) return; currentToken.clear(); currentTokenStart = in - cmd.begin(); } //Handle quoted strings if (in[0] == '\"') { in++; //Read all characters until quote end while (in != cmd.end()) { if (in[0] == '\"') { in++; break; } else if (in + 1 != cmd.end() && in[0] == '\\') { currentToken.push_back(in[1]); in += 2; } else { currentToken.push_back(in[0]); in++; } } } else { //Handle normal character currentToken.push_back(in[0]); in++; } } } int Args::Argc() const { return args.size(); } const std::string& Args::Argv(int argNum) const { return args[argNum]; } std::string Args::EscapedArgs(int start, int end) const { std::string res; if (end < 0) { end = args.size() - 1; } for (int i = start; i < end + 1; i++) { if (i != start) { res += " "; } res += Escape(args[i]); } return res; } const std::string& Args::RawCmd() const { return cmd; } std::string Args::RawArgsFrom(unsigned start) const { if (start < argsStarts.size()) { return std::string(cmd.begin() + argsStarts[start], cmd.end()); } else { return ""; } } int Args::PosToArg(int pos) const { for (int i = argsStarts.size(); i-->0;) { if (argsStarts[i] <= pos) { return i; } } return -1; } int Args::ArgStartPos(unsigned argNum) const { if (argNum > argsStarts.size()) { return cmd.size(); } return argsStarts[argNum]; } std::string Args::ArgPrefix(int pos) const { int argNum = PosToArg(pos); return args[argNum].substr(0, pos); } const std::vector<std::string>& Args::ArgVector() const { return args; } int Args::size() const { return Argc(); } const std::string& Args::operator[] (int argNum) const { return Argv(argNum); } /* =============================================================================== Cmd::CmdBase =============================================================================== */ CmdBase::CmdBase(const int flags): flags(flags) { } CompletionResult CmdBase::Complete(int argNum, const Args& args, const std::string& prefix) const { Q_UNUSED(argNum); Q_UNUSED(args); Q_UNUSED(prefix); return {}; } void CmdBase::PrintUsage(const Args& args, Str::StringRef syntax, Str::StringRef description) const { if(description.empty()) { Print("%s: %s %s\n", _("usage"), args.Argv(0).c_str(), syntax.c_str()); } else { Print("%s: %s %s — %s\n", _("usage"), args.Argv(0).c_str(), syntax.c_str(), description.c_str()); } } int CmdBase::GetFlags() const { return flags; } void CmdBase::ExecuteAfter(Str::StringRef text, bool parseCvars) const { GetEnv().ExecuteAfter(text, parseCvars); } Environment& CmdBase::GetEnv() const { return *Cmd::GetEnv(); } StaticCmd::StaticCmd(std::string name, const int flags, std::string description) :CmdBase(flags){ //Register this command statically AddCommand(std::move(name), *this, std::move(description)); } } <commit_msg>Remove extra newlines in PrintUsage<commit_after>/* =========================================================================== Daemon GPL Source Code Copyright (C) 2013 Unvanquished Developers This file is part of the Daemon GPL Source Code (Daemon Source Code). Daemon Source Code 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. Daemon Source Code 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 Daemon Source Code. If not, see <http://www.gnu.org/licenses/>. =========================================================================== */ #include "Command.h" #include "Log.h" #include "../engine/qcommon/qcommon.h" #include "../engine/framework/CommandSystem.h" #include "../engine/framework/CvarSystem.h" namespace Cmd { std::string Escape(Str::StringRef text) { std::string res = "\""; for (size_t i = 0; i < text.size(); i ++) { if (text[i] == '\\') { res.append("\\\\"); } else if (text[i] == '\"') { res.append("\\\""); } else { res.push_back(text[i]); } } res += "\""; return res; } static bool SkipSpaces(std::string::const_iterator& in, std::string::const_iterator end) { bool foundSpace = false; while (in != end) { // Handle spaces if ((in[0] & 0xff) <= ' ') { foundSpace = true; in++; } else if (in + 1 != end) { // Handle // comments if (in[0] == '/' && in[1] == '/') { in = end; return true; } // Handle /* */ comments if (in[0] == '/' && in[1] == '*') { foundSpace = true; in += 2; while (in != end) { if (in + 1 != end && in[0] == '*' && in[1] == '/') { in += 2; break; } else { in++; } } } else { // Non-space character return foundSpace; } } else { // Non-space character return foundSpace; } } return true; } const char* SplitCommand(const char* start, const char* end) { bool inQuote = false; bool inComment = false; bool inInlineComment = false; while (start != end) { //End of comment if (inInlineComment && start + 1 != end && start[0] == '*' && start[1] == '/') { inInlineComment = false; start += 2; continue; } //Ignore everything else in an inline comment if (inInlineComment) { start++; continue; } //Start of comment if (not inQuote && not inComment && start + 1 != end && start[0] == '/' && start[1] == '*') { inInlineComment = true; start += 2; continue; } if (not inQuote && start + 1 != end && start[0] == '/' && start[1] == '/') { inComment = true; start += 2; continue; } //Escaped quote if (inQuote && start + 1 != end && start[0] == '\\') { start += 2; continue; } //Quote if (start[0] == '"') { inQuote = !inQuote; start++; continue; } //Semicolon if (start[0] == ';' && !inQuote && !inComment) { return start + 1; } //Newline if (start[0] == '\n') { return start + 1; } //Normal character start++; } return end; } std::string SubstituteCvars(Str::StringRef text) { const char* raw_text = text.data(); std::string result; bool isEscaped = false; bool inCvarName = false; int lastBlockStart = 0; //Cvar are delimited by $ so we parse a bloc at a time for(size_t i = 0; i < text.size(); i++){ // a \ escapes the next letter so we don't use it for block delimitation if (isEscaped) { isEscaped = false; continue; } if (text[i] == '\\') { isEscaped = true; } else if (text[i] == '$') { //Found a block, every second block is a cvar name block std::string block(raw_text + lastBlockStart, i - lastBlockStart); if (inCvarName) { result += Escape(Cvar::GetValue(block)); inCvarName = false; } else { result += block; inCvarName = true; } lastBlockStart = i + 1; } } //Handle the last block if (inCvarName) { Com_Printf("Warning: last CVar substitution block not closed in %s\n", raw_text); } else { std::string block(raw_text + lastBlockStart, text.size() - lastBlockStart); result += block; } return result; } /* =============================================================================== Cmd::CmdArgs =============================================================================== */ Args::Args() { } Args::Args(std::vector<std::string> args_) { args = std::move(args_); for (size_t i = 0; i < args.size(); i++) { argsStarts.push_back(cmd.size()); cmd += Escape(args[i]); if (i != args.size() - 1) { cmd += " "; } } } Args::Args(std::string command) { cmd = std::move(command); std::string::const_iterator in = cmd.begin(); //Skip leading whitespace SkipSpaces(in, cmd.end()); //Return if the cmd is empty if (in == cmd.end()) return; //Build arg tokens std::string currentToken; int currentTokenStart = in - cmd.begin(); while (true) { //Check for end of current token if (SkipSpaces(in, cmd.end())) { args.push_back(std::move(currentToken)); argsStarts.push_back(currentTokenStart); if (in == cmd.end()) return; currentToken.clear(); currentTokenStart = in - cmd.begin(); } //Handle quoted strings if (in[0] == '\"') { in++; //Read all characters until quote end while (in != cmd.end()) { if (in[0] == '\"') { in++; break; } else if (in + 1 != cmd.end() && in[0] == '\\') { currentToken.push_back(in[1]); in += 2; } else { currentToken.push_back(in[0]); in++; } } } else { //Handle normal character currentToken.push_back(in[0]); in++; } } } int Args::Argc() const { return args.size(); } const std::string& Args::Argv(int argNum) const { return args[argNum]; } std::string Args::EscapedArgs(int start, int end) const { std::string res; if (end < 0) { end = args.size() - 1; } for (int i = start; i < end + 1; i++) { if (i != start) { res += " "; } res += Escape(args[i]); } return res; } const std::string& Args::RawCmd() const { return cmd; } std::string Args::RawArgsFrom(unsigned start) const { if (start < argsStarts.size()) { return std::string(cmd.begin() + argsStarts[start], cmd.end()); } else { return ""; } } int Args::PosToArg(int pos) const { for (int i = argsStarts.size(); i-->0;) { if (argsStarts[i] <= pos) { return i; } } return -1; } int Args::ArgStartPos(unsigned argNum) const { if (argNum > argsStarts.size()) { return cmd.size(); } return argsStarts[argNum]; } std::string Args::ArgPrefix(int pos) const { int argNum = PosToArg(pos); return args[argNum].substr(0, pos); } const std::vector<std::string>& Args::ArgVector() const { return args; } int Args::size() const { return Argc(); } const std::string& Args::operator[] (int argNum) const { return Argv(argNum); } /* =============================================================================== Cmd::CmdBase =============================================================================== */ CmdBase::CmdBase(const int flags): flags(flags) { } CompletionResult CmdBase::Complete(int argNum, const Args& args, const std::string& prefix) const { Q_UNUSED(argNum); Q_UNUSED(args); Q_UNUSED(prefix); return {}; } void CmdBase::PrintUsage(const Args& args, Str::StringRef syntax, Str::StringRef description) const { if(description.empty()) { Print("%s: %s %s", _("usage"), args.Argv(0).c_str(), syntax.c_str()); } else { Print("%s: %s %s — %s", _("usage"), args.Argv(0).c_str(), syntax.c_str(), description.c_str()); } } int CmdBase::GetFlags() const { return flags; } void CmdBase::ExecuteAfter(Str::StringRef text, bool parseCvars) const { GetEnv().ExecuteAfter(text, parseCvars); } Environment& CmdBase::GetEnv() const { return *Cmd::GetEnv(); } StaticCmd::StaticCmd(std::string name, const int flags, std::string description) :CmdBase(flags){ //Register this command statically AddCommand(std::move(name), *this, std::move(description)); } } <|endoftext|>
<commit_before>#ifndef COMPOSE_NODE_HPP #define COMPOSE_NODE_HPP #include <memory> #include <map> #include <set> #include <stdexcept> #include <east.hpp> #include "core/composed_node.hpp" #include "phi_node.hpp" #include "const_node.hpp" #include "sqrt_node.hpp" #include "log_node.hpp" #include "log10_node.hpp" #include "logit_node.hpp" #include "ilogit_node.hpp" #include "sin_node.hpp" #include "cos_node.hpp" #include "tan_node.hpp" #include "arithmetic_node.hpp" #include "phi_node.hpp" #include <atomic> namespace mcmc_utilities { template <typename T> class str_node :public composed_node<T,std::string> { public: static std::map<std::string,std::shared_ptr<abstract_node_factory<T> > > node_factories; static void init_node_factories() { std::atomic<bool> initialized(false); if(initialized) { return; } auto& node_factories=str_node::node_factories; node_factories["add"]=std::shared_ptr<abstract_node_factory<T> >(new add_node_factory<T>()); node_factories["sub"]=std::shared_ptr<abstract_node_factory<T> >(new sub_node_factory<T>()); node_factories["neg"]=std::shared_ptr<abstract_node_factory<T> >(new neg_node_factory<T>()); node_factories["pos"]=std::shared_ptr<abstract_node_factory<T> >(new pos_node_factory<T>()); node_factories["mul"]=std::shared_ptr<abstract_node_factory<T> >(new mul_node_factory<T>()); node_factories["div"]=std::shared_ptr<abstract_node_factory<T> >(new div_node_factory<T>()); node_factories["pow"]=std::shared_ptr<abstract_node_factory<T> >(new pow_node_factory<T>()); node_factories["con"]=std::shared_ptr<abstract_node_factory<T> >(new const_node_factory<T>()); node_factories["phi"]=std::shared_ptr<abstract_node_factory<T> >(new phi_node_factory<T>()); node_factories["sqrt"]=std::shared_ptr<abstract_node_factory<T> >(new sqrt_node_factory<T>()); node_factories["log"]=std::shared_ptr<abstract_node_factory<T> >(new log_node_factory<T>()); node_factories["log10"]=std::shared_ptr<abstract_node_factory<T> >(new log10_node_factory<T>()); node_factories["sin"]=std::shared_ptr<abstract_node_factory<T> >(new sin_node_factory<T>()); node_factories["cos"]=std::shared_ptr<abstract_node_factory<T> >(new cos_node_factory<T>()); node_factories["tan"]=std::shared_ptr<abstract_node_factory<T> >(new tan_node_factory<T>()); node_factories["logit"]=std::shared_ptr<abstract_node_factory<T> >(new logit_node_factory<T>()); node_factories["ilogit"]=std::shared_ptr<abstract_node_factory<T> >(new ilogit_node_factory<T>()); initialized=true; } private: void count_input(const east::expression_node& en, std::set<std::string>& tags) { for(int i=0;i<en.get_num_of_parents();++i) { count_input(en.get_parent(i),tags); } if(en.get_kind()=="var") { tags.insert(en.get_symbol()); } } private: std::shared_ptr<deterministic_node<T> > add_node(const east::expression_node& en,int& n) { if(en.get_kind()=="con") { if(this->elements.count(en.get_symbol())==0) { auto p=std::dynamic_pointer_cast<deterministic_node<T> >(node_factories["con"]->get_node({(T)std::stod(en.get_symbol())})); this->elements[en.get_symbol()]=p; return p; } else { return this->elements[en.get_symbol()]; } } else if(en.get_kind()=="var") { return this->elements[en.get_symbol()]; } else { std::shared_ptr<deterministic_node<T> > p; if(en.get_kind()!="ftn") { p=std::dynamic_pointer_cast<deterministic_node<T> >(node_factories[en.get_kind()]->get_node()); } else { p=std::dynamic_pointer_cast<deterministic_node<T> >(node_factories[en.get_symbol()]->get_node()); } for(int i=0;i<en.get_num_of_parents();++i) { auto p1=add_node(en.get_parent(i),n); p->connect_to_parent(p1.get(),i,0); } std::string tag="node_"+std::to_string(n++); this->elements[tag]=p; return p; } } public: str_node(const std::string& expression, const std::vector<std::string>& input_names) :composed_node<T,std::string>(input_names.size(),1) { str_node::init_node_factories(); east::parser parser; std::shared_ptr<east::expression_node> enode=parser.parse(expression); std::set<std::string> tags; count_input(*enode,tags); if(input_names.size()!=tags.size()) { throw std::logic_error("input names mismatch"); } for(auto s:input_names) { if(tags.count(s)!=1) { throw std::logic_error("input names mismatch"); } } for(int i=0;i<input_names.size();++i) { std::shared_ptr<deterministic_node<T> > pn(new forward_node<T>); this->elements.insert(std::make_pair(input_names[i],pn)); this->param_list.push_back(pn); } int n=1; auto pn=add_node(*enode,n); this->return_list.push_back({pn,0}); } }; template <typename T> std::map<std::string,std::shared_ptr<abstract_node_factory<T> > > str_node<T>::node_factories; template <typename T> void add_node_to(composed_node<T,std::string>& cn,const east::expression_node& en,std::set<std::string>& tag_set) { } }; #endif <commit_msg> 修改: ../nodes/str_node.hpp<commit_after>#ifndef COMPOSE_NODE_HPP #define COMPOSE_NODE_HPP #include <memory> #include <map> #include <set> #include <stdexcept> #include <east.hpp> #include "core/composed_node.hpp" #include "phi_node.hpp" #include "const_node.hpp" #include "sqrt_node.hpp" #include "log_node.hpp" #include "log10_node.hpp" #include "logit_node.hpp" #include "ilogit_node.hpp" #include "sin_node.hpp" #include "cos_node.hpp" #include "tan_node.hpp" #include "arithmetic_node.hpp" #include "phi_node.hpp" #include <atomic> namespace mcmc_utilities { template <typename T> class str_node :public composed_node<T,std::string> { public: static std::map<std::string,std::shared_ptr<abstract_node_factory<T> > > node_factories; static void init_node_factories() { std::atomic<bool> initialized(false); if(initialized) { return; } auto& node_factories=str_node::node_factories; register_function({"add"},std::shared_ptr<abstract_node_factory<T> >(new add_node_factory<T>())); register_function({"sub"},std::shared_ptr<abstract_node_factory<T> >(new sub_node_factory<T>())); register_function({"neg"},std::shared_ptr<abstract_node_factory<T> >(new neg_node_factory<T>())); register_function({"pos"},std::shared_ptr<abstract_node_factory<T> >(new pos_node_factory<T>())); register_function({"mul"},std::shared_ptr<abstract_node_factory<T> >(new mul_node_factory<T>())); register_function({"div"},std::shared_ptr<abstract_node_factory<T> >(new div_node_factory<T>())); register_function({"pow"},std::shared_ptr<abstract_node_factory<T> >(new pow_node_factory<T>())); register_function({"con"},std::shared_ptr<abstract_node_factory<T> >(new const_node_factory<T>())); register_function({"phi"},std::shared_ptr<abstract_node_factory<T> >(new phi_node_factory<T>())); register_function({"sqrt"},std::shared_ptr<abstract_node_factory<T> >(new sqrt_node_factory<T>())); register_function({"log"},std::shared_ptr<abstract_node_factory<T> >(new log_node_factory<T>())); register_function({"log10"},std::shared_ptr<abstract_node_factory<T> >(new log10_node_factory<T>())); register_function({"sin"},std::shared_ptr<abstract_node_factory<T> >(new sin_node_factory<T>())); register_function({"cos"},std::shared_ptr<abstract_node_factory<T> >(new cos_node_factory<T>())); register_function({"tan"},std::shared_ptr<abstract_node_factory<T> >(new tan_node_factory<T>())); register_function({"logit"},std::shared_ptr<abstract_node_factory<T> >(new logit_node_factory<T>())); register_function({"ilogit"},std::shared_ptr<abstract_node_factory<T> >(new ilogit_node_factory<T>())); initialized=true; } static void register_function(const std::string& name,const std::shared_ptr<abstract_node_factory<T> >& ptr) { node_factories[name]=ptr; } static void unregister_function(const std::string& name) { node_factories.erase(name); } private: void count_input(const east::expression_node& en, std::set<std::string>& tags) { for(int i=0;i<en.get_num_of_parents();++i) { count_input(en.get_parent(i),tags); } if(en.get_kind()=="var") { tags.insert(en.get_symbol()); } } private: std::shared_ptr<deterministic_node<T> > add_node(const east::expression_node& en,int& n) { if(en.get_kind()=="con") { if(this->elements.count(en.get_symbol())==0) { auto p=std::dynamic_pointer_cast<deterministic_node<T> >(node_factories["con"]->get_node({(T)std::stod(en.get_symbol())})); this->elements[en.get_symbol()]=p; return p; } else { return this->elements[en.get_symbol()]; } } else if(en.get_kind()=="var") { return this->elements[en.get_symbol()]; } else { std::shared_ptr<deterministic_node<T> > p; if(en.get_kind()!="ftn") { p=std::dynamic_pointer_cast<deterministic_node<T> >(node_factories[en.get_kind()]->get_node()); } else { p=std::dynamic_pointer_cast<deterministic_node<T> >(node_factories[en.get_symbol()]->get_node()); } for(int i=0;i<en.get_num_of_parents();++i) { auto p1=add_node(en.get_parent(i),n); p->connect_to_parent(p1.get(),i,0); } std::string tag="node_"+std::to_string(n++); this->elements[tag]=p; return p; } } public: str_node(const std::string& expression, const std::vector<std::string>& input_names) :composed_node<T,std::string>(input_names.size(),1) { str_node::init_node_factories(); east::parser parser; std::shared_ptr<east::expression_node> enode=parser.parse(expression); std::set<std::string> tags; count_input(*enode,tags); if(input_names.size()!=tags.size()) { throw std::logic_error("input names mismatch"); } for(auto s:input_names) { if(tags.count(s)!=1) { throw std::logic_error("input names mismatch"); } } for(int i=0;i<input_names.size();++i) { std::shared_ptr<deterministic_node<T> > pn(new forward_node<T>); this->elements.insert(std::make_pair(input_names[i],pn)); this->param_list.push_back(pn); } int n=1; auto pn=add_node(*enode,n); this->return_list.push_back({pn,0}); } }; template <typename T> std::map<std::string,std::shared_ptr<abstract_node_factory<T> > > str_node<T>::node_factories; template <typename T> void add_node_to(composed_node<T,std::string>& cn,const east::expression_node& en,std::set<std::string>& tag_set) { } }; #endif <|endoftext|>
<commit_before>#include <immintrin.h> #include <cstdint> #include <cassert> char* remove_spaces__avx512vbmi(const char* src, char* dst, size_t n) { assert(n % 64 == 0); // values 0..63 const __m512i no_gaps_indices = _mm512_setr_epi32( 0x03020100, 0x07060504, 0x0b0a0908, 0x0f0e0d0c, 0x13121110, 0x17161514, 0x1b1a1918, 0x1f1e1d1c, 0x23222120, 0x27262524, 0x2b2a2928, 0x2f2e2d2c, 0x33323130, 0x37363534, 0x3b3a3938, 0x3f3e3d3c ); const __m512i ones = _mm512_set1_epi8(1); const __m512i NL = _mm512_set1_epi8('\n'); const __m512i CR = _mm512_set1_epi8('\r'); const __m512i spaces = _mm512_set1_epi8(' '); size_t len; for (size_t i=0; i < n; i += 64) { const __m512i input = _mm512_loadu_si512((const __m512i*)(src + i)); __m512i output; uint64_t mask = _mm512_cmpeq_epi8_mask(input, spaces) | _mm512_cmpeq_epi8_mask(input, NL) | _mm512_cmpeq_epi8_mask(input, CR); if (mask) { len = 64 - __builtin_popcountll(mask); __m512i indices = no_gaps_indices; __m512i increment = ones; uint64_t first; uint64_t prev; first = (mask & -mask); // isolate the first bit set prev = first; mask ^= first; // reset it in the mask mask >>= 1; // and shift by 1 while (mask) { const uint64_t curr = (mask & -mask); mask ^= curr; mask >>= 1; if (prev == curr) { // run continues increment = _mm512_add_epi8(increment, ones); prev = curr; } else { // new run indices = _mm512_mask_add_epi8(indices, ~(first - 1), indices, increment); first = curr; prev = curr; increment = ones; } } indices = _mm512_mask_add_epi8(indices, ~(first - 1), indices, increment); output = _mm512_permutexvar_epi8(indices, input); } else { output = input; len = 64; } _mm512_storeu_si512((__m512i*)(dst), output); dst += len; } return dst; } <commit_msg>Use PEXT to build up the shuffle indices in parallel<commit_after>#include <immintrin.h> #include <cstdint> #include <cassert> char* remove_spaces__avx512vbmi(const char* src, char* dst, size_t n) { assert(n % 64 == 0); const __m512i NL = _mm512_set1_epi8('\n'); const __m512i CR = _mm512_set1_epi8('\r'); const __m512i spaces = _mm512_set1_epi8(' '); uint64_t index_masks[6] = { 0xaaaaaaaaaaaaaaaa, 0xcccccccccccccccc, 0xf0f0f0f0f0f0f0f0, 0xff00ff00ff00ff00, 0xffff0000ffff0000, 0xffffffff00000000, }; const __m512i bit_masks[6] = { _mm512_set1_epi8(1), _mm512_set1_epi8(2), _mm512_set1_epi8(4), _mm512_set1_epi8(8), _mm512_set1_epi8(16), _mm512_set1_epi8(32), }; size_t len; for (size_t i=0; i < n; i += 64) { const __m512i input = _mm512_loadu_si512((const __m512i*)(src + i)); __m512i output; uint64_t mask = _mm512_cmpeq_epi8_mask(input, spaces) | _mm512_cmpeq_epi8_mask(input, NL) | _mm512_cmpeq_epi8_mask(input, CR); if (mask) { mask = ~mask; __m512i indices = _mm512_set1_epi8(0); for (size_t index = 0; index < 6; index++) { uint64_t m = _pext_u64(index_masks[index], mask); indices = _mm512_mask_add_epi8(indices, m, indices, bit_masks[index]); } output = _mm512_permutexvar_epi8(indices, input); } else { output = input; len = 64; } _mm512_storeu_si512((__m512i*)(dst), output); dst += len; } return dst; } <|endoftext|>
<commit_before>/** * Copyright 2016 Yahoo Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "Url.h" #include <gtest/gtest.h> using namespace pulsar; TEST(UrlTest, testUrl) { Url url; ASSERT_TRUE(Url::parse("http://example.com", url)); ASSERT_EQ("http", url.protocol()); ASSERT_EQ(80, url.port()); ASSERT_TRUE(Url::parse("https://example.com", url)); ASSERT_EQ("https", url.protocol()); ASSERT_EQ(443, url.port()); ASSERT_TRUE(Url::parse("http://example.com:8080", url)); ASSERT_EQ("http", url.protocol()); ASSERT_EQ(8080, url.port()); ASSERT_TRUE(Url::parse("http://example.com:8080/", url)); ASSERT_EQ("http", url.protocol()); ASSERT_EQ(8080, url.port()); ASSERT_TRUE(Url::parse("http://example.com", url)); ASSERT_EQ("http", url.protocol()); ASSERT_EQ(80, url.port()); ASSERT_TRUE(Url::parse("http://example.com:8080/test/my/path", url)); ASSERT_EQ("http", url.protocol()); ASSERT_EQ(8080, url.port()); ASSERT_TRUE(Url::parse("http://example.com:8080/test/my/path?key=value#adsasda", url)); ASSERT_EQ("http", url.protocol()); ASSERT_EQ(8080, url.port()); ASSERT_TRUE(Url::parse("pulsar://example.com:8080", url)); ASSERT_EQ("pulsar", url.protocol()); ASSERT_EQ(8080, url.port()); ASSERT_TRUE(Url::parse("pulsar://example.com", url)); ASSERT_EQ("pulsar", url.protocol()); ASSERT_EQ(6650, url.port()); } <commit_msg>Added more checks in CPP Client URL Tests (#312)<commit_after>/** * Copyright 2016 Yahoo Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "Url.h" #include <gtest/gtest.h> using namespace pulsar; TEST(UrlTest, testUrl) { Url url; ASSERT_TRUE(Url::parse("http://example.com", url)); ASSERT_EQ("http", url.protocol()); ASSERT_EQ(80, url.port()); ASSERT_TRUE(Url::parse("https://example.com", url)); ASSERT_EQ("https", url.protocol()); ASSERT_EQ(443, url.port()); ASSERT_TRUE(Url::parse("http://example.com:8080", url)); ASSERT_EQ("http", url.protocol()); ASSERT_EQ(8080, url.port()); ASSERT_TRUE(Url::parse("http://example.com:8080/", url)); ASSERT_EQ("http", url.protocol()); ASSERT_EQ(8080, url.port()); ASSERT_TRUE(Url::parse("http://example.com", url)); ASSERT_EQ("example.com", url.host()); ASSERT_EQ("http", url.protocol()); ASSERT_EQ(80, url.port()); ASSERT_TRUE(Url::parse("http://example.com:8080/test/my/path", url)); ASSERT_EQ("example.com", url.host()); ASSERT_EQ("http", url.protocol()); ASSERT_EQ(8080, url.port()); ASSERT_TRUE(Url::parse("http://example.com:8080/test/my/path?key=value#adsasda", url)); ASSERT_EQ("example.com", url.host()); ASSERT_EQ("http", url.protocol()); ASSERT_EQ(8080, url.port()); ASSERT_TRUE(Url::parse("pulsar://example.com:8080", url)); ASSERT_EQ("example.com", url.host()); ASSERT_EQ("pulsar", url.protocol()); ASSERT_EQ(8080, url.port()); ASSERT_TRUE(Url::parse("pulsar://example.com", url)); ASSERT_EQ("example.com", url.host()); ASSERT_EQ("pulsar", url.protocol()); ASSERT_EQ(6650, url.port()); } <|endoftext|>
<commit_before>#include <sstream> #include "controller.hpp" Controller::Controller(): n("~"), new_task(false), ac_speak("/speak", true), ac_gaze("/gaze_at_pose", true), memory_ppl(), name_dict(), person_id(-1), client_facts(n.serviceClient<facts::TellFacts>("tell_facts")), initialized(false) { name_tag_sub = n.subscribe<circle_detection::detection_results_array>("/circle_detection/results_array", 1000, &Controller::tagSubscriber, this); rnd_walk_start = n.serviceClient<std_srvs::Empty>("/start_random_walk"); rnd_walk_stop = n.serviceClient<std_srvs::Empty>("/stop_random_walk"); fillDictionary(); ros::spinOnce(); } void Controller::startDialog() { std::cerr<<"I feel like I should talk more..."<<std::endl; ac_speak.waitForServer(); std::stringstream ss; std::string name = ""; // get the name for that person std::map<int,std::string>::iterator it; it = name_dict.find(person_id); if(it != name_dict.end()) { name = it->second; } else { name = "unknown person. I do not recognize you"; // start an alarm? } ss << "Hi " << name << "."; // check how often we have seen that person before std::map<int,int>::iterator it_count; it_count = memory_ppl.find(person_id); if(it_count != memory_ppl.end()) { ss << "We have already met " << it_count->second << " times before."; // query the facts service facts::TellFacts srv; srv.request.person = person_id; if(client_facts.call(srv)) { // we got a new fact std::cerr<<"Received a new fact: " << srv.response.fact << std::endl; ss << srv.response.fact << std::endl; } else { std::cerr<<"Did not receive a new fact."<<std::endl; } } else { ss << " Welcome to the E C M R."; ss << " Be aware of the other robots. They are plotting an evil plan"; ss << " against you. Especially the green one."; ss << " I am looking forward to seeing you again."; ss << std::endl; } mary_tts::maryttsGoal goal; goal.text = ss.str(); ac_speak.sendGoal(goal); bool finished_before_timeout = ac_speak.waitForResult(ros::Duration(30.0)); if (finished_before_timeout) { actionlib::SimpleClientGoalState state = ac_speak.getState(); ROS_INFO("Action finished: %s",state.toString().c_str()); } } void Controller::startGaze() { ac_gaze.waitForServer(); strands_gazing::GazeAtPoseGoal goal; goal.runtime_sec = 0; goal.topic_name = "/upper_body_detector/closest_bounding_box_centre"; ac_gaze.sendGoal(goal); bool finished_before_timeout = ac_gaze.waitForResult(ros::Duration(10.0)); if (finished_before_timeout) { actionlib::SimpleClientGoalState state = ac_gaze.getState(); ROS_INFO("Action finished: %s",state.toString().c_str()); } } void Controller::tagSubscriber(const circle_detection::detection_results_array::ConstPtr& _msg) { if( person_id != _msg->personId ) { new_task = true; person_id = _msg->personId; std::cerr<<"This is another person with the id: "<<person_id<<std::endl; } } void Controller::update() { std_srvs::Empty srv; // initialization: start with random walking if(!initialized) { rnd_walk_start.call(srv); initialized=true; // will never bet to false again } if (new_task) { new_task = false; // update our people memory updatePersonSeen(person_id); std::cerr<<"Let's stop here for a while..."<<std::endl; rnd_walk_stop.call(srv); std::cerr<<"Look at this!"<<std::endl; startGaze(); std::cerr<<"I feel active..."<<std::endl; startDialog(); ac_gaze.cancelAllGoals(); std::cerr<<"I would like to start roaming again..."<<std::endl; rnd_walk_start.call(srv); } } void Controller::updatePersonSeen(const int & _person_id) { // check whether that person exists in the memory std::map<int,int>::iterator it; it = memory_ppl.find(_person_id); if(it != memory_ppl.end()) { // increase it for a known user std::cerr<<"I have seen the person already "<<it->second<<" times."<<std::endl; memory_ppl[_person_id] = it->second++; } else { // init new user std::cerr<<"This is a new person to me."<<std::endl; memory_ppl[_person_id] = 1; } } void Controller::fillDictionary() { // fill the name dictionary with peoples' names name_dict[0] = "Bob"; name_dict[1] = "Betty"; name_dict[2] = "Linda"; name_dict[3] = "Lucie"; } int main(int argc, char** argv) { ros::init(argc, argv, "controller_bev"); Controller theController; ros::Rate loop_rate(5); // [Hz] while(ros::ok()) { theController.update(); ros::spinOnce(); loop_rate.sleep(); } return 0; } <commit_msg>change name of tell facts<commit_after>#include <sstream> #include "controller.hpp" Controller::Controller(): n("~"), new_task(false), ac_speak("/speak", true), ac_gaze("/gaze_at_pose", true), memory_ppl(), name_dict(), person_id(-1), client_facts(n.serviceClient<facts::TellFacts>("/tell_facts")), initialized(false) { name_tag_sub = n.subscribe<circle_detection::detection_results_array>("/circle_detection/results_array", 1000, &Controller::tagSubscriber, this); rnd_walk_start = n.serviceClient<std_srvs::Empty>("/start_random_walk"); rnd_walk_stop = n.serviceClient<std_srvs::Empty>("/stop_random_walk"); fillDictionary(); ros::spinOnce(); } void Controller::startDialog() { std::cerr<<"I feel like I should talk more..."<<std::endl; ac_speak.waitForServer(); std::stringstream ss; std::string name = ""; // get the name for that person std::map<int,std::string>::iterator it; it = name_dict.find(person_id); if(it != name_dict.end()) { name = it->second; } else { name = "unknown person. I do not recognize you"; // start an alarm? } ss << "Hi " << name << "."; // check how often we have seen that person before std::map<int,int>::iterator it_count; it_count = memory_ppl.find(person_id); if(it_count != memory_ppl.end()) { ss << "We have already met " << it_count->second << " times before."; // query the facts service facts::TellFacts srv; srv.request.person = person_id; if(client_facts.call(srv)) { // we got a new fact std::cerr<<"Received a new fact: " << srv.response.fact << std::endl; ss << srv.response.fact << std::endl; } else { std::cerr<<"Did not receive a new fact."<<std::endl; } } else { ss << " Welcome to the E C M R."; ss << " Be aware of the other robots. They are plotting an evil plan"; ss << " against you. Especially the green one."; ss << " I am looking forward to seeing you again."; ss << std::endl; } mary_tts::maryttsGoal goal; goal.text = ss.str(); ac_speak.sendGoal(goal); bool finished_before_timeout = ac_speak.waitForResult(ros::Duration(30.0)); if (finished_before_timeout) { actionlib::SimpleClientGoalState state = ac_speak.getState(); ROS_INFO("Action finished: %s",state.toString().c_str()); } } void Controller::startGaze() { ac_gaze.waitForServer(); strands_gazing::GazeAtPoseGoal goal; goal.runtime_sec = 0; goal.topic_name = "/upper_body_detector/closest_bounding_box_centre"; ac_gaze.sendGoal(goal); bool finished_before_timeout = ac_gaze.waitForResult(ros::Duration(10.0)); if (finished_before_timeout) { actionlib::SimpleClientGoalState state = ac_gaze.getState(); ROS_INFO("Action finished: %s",state.toString().c_str()); } } void Controller::tagSubscriber(const circle_detection::detection_results_array::ConstPtr& _msg) { if( person_id != _msg->personId ) { new_task = true; person_id = _msg->personId; std::cerr<<"This is another person with the id: "<<person_id<<std::endl; } } void Controller::update() { std_srvs::Empty srv; // initialization: start with random walking if(!initialized) { rnd_walk_start.call(srv); initialized=true; // will never bet to false again } if (new_task) { new_task = false; // update our people memory updatePersonSeen(person_id); std::cerr<<"Let's stop here for a while..."<<std::endl; rnd_walk_stop.call(srv); std::cerr<<"Look at this!"<<std::endl; startGaze(); std::cerr<<"I feel active..."<<std::endl; startDialog(); ac_gaze.cancelAllGoals(); std::cerr<<"I would like to start roaming again..."<<std::endl; rnd_walk_start.call(srv); } } void Controller::updatePersonSeen(const int & _person_id) { // check whether that person exists in the memory std::map<int,int>::iterator it; it = memory_ppl.find(_person_id); if(it != memory_ppl.end()) { // increase it for a known user std::cerr<<"I have seen the person already "<<it->second<<" times."<<std::endl; memory_ppl[_person_id] = it->second++; } else { // init new user std::cerr<<"This is a new person to me."<<std::endl; memory_ppl[_person_id] = 1; } } void Controller::fillDictionary() { // fill the name dictionary with peoples' names name_dict[0] = "Bob"; name_dict[1] = "Betty"; name_dict[2] = "Linda"; name_dict[3] = "Lucie"; } int main(int argc, char** argv) { ros::init(argc, argv, "controller_bev"); Controller theController; ros::Rate loop_rate(5); // [Hz] while(ros::ok()) { theController.update(); ros::spinOnce(); loop_rate.sleep(); } return 0; } <|endoftext|>
<commit_before>#include "detectors.h" #include <iostream> #include <numeric> #include <algorithm> #include <cmath> #include <limits> using namespace std; #include "poptemplate.h" static const bool kDelayMatch = false; static const int kBlockSize = DETECTORS_BLOCK_SIZE; static const int kLogBlockSize = 9; static const int kSpectrumSize = kBlockSize/2; static const int kWindowSize = kBlockSize; static const int kNumSteps = 4; static const int kStepSize = kBlockSize / kNumSteps; static const size_t kMainBandLow = 40; static const size_t kMainBandHi = 100; static const size_t kOptionalBandHi = 180; static const size_t kLowerBandLow = 3; static const size_t kLowerBandHi = kMainBandLow; static const size_t kUpperBandLo = kOptionalBandHi; static const size_t kUpperBandHi = kSpectrumSize; static const float kDefaultLowPassWeight = 0.6; static const int kSpeechShadowTime = 100; static const float kSpeechThresh = 0.5; Detectors::Detectors() { m_overlapBuffer = new float[kBlockSize * 2]; // === Tss Detection m_sensitivity = 5.0; m_hysterisisFactor = 0.4; m_minFrames = 20; m_minFramesLong = 100; m_lowPassWeight = kDefaultLowPassWeight; // === Pop detection m_startBin = 2; m_maxShiftDown = 4; m_maxShiftUp = 2; m_popSensitivity = 8.5; m_framesSincePop = 0; // debugLog = new std::ofstream("/Users/tristan/misc/popclick.log"); // === FFT m_inReal = new float[kBlockSize]; m_splitData.realp = new float[kSpectrumSize]; m_splitData.imagp = new float[kSpectrumSize]; m_window = new float[kWindowSize]; memset(m_window, 0, sizeof(float) * kWindowSize); vDSP_hann_window(m_window, kWindowSize, vDSP_HANN_NORM); m_fftSetup = vDSP_create_fftsetup(kLogBlockSize, FFT_RADIX2); } Detectors::~Detectors() { delete[] m_overlapBuffer; delete[] m_inReal; delete[] m_splitData.realp; delete[] m_splitData.imagp; delete[] m_window; // delete debugLog; vDSP_destroy_fftsetup(m_fftSetup); } bool Detectors::initialise() { // Real initialisation work goes here! m_savedOtherBands = 0.0002; m_consecutiveMatches = 0; m_framesSinceSpeech = 1000; m_framesSinceMatch = 1000; m_lowPassBuffer.resize(kSpectrumSize, 0.0); m_spectrum.resize(kSpectrumSize, 0.0); m_popBuffer.clear(); for(unsigned i = 0; i < kBufferSize; ++i) { m_popBuffer.push_back(0.0); } return true; } int Detectors::process(const float *buffer) { // return processChunk(buffer); // copy last frame to start of the buffer std::copy(m_overlapBuffer+kBlockSize, m_overlapBuffer+(kBlockSize*2), m_overlapBuffer); // copy new input to the second half of the overlap buffer std::copy(buffer,buffer+kBlockSize,m_overlapBuffer+kBlockSize); int result = 0; for(int i = 0; i < kNumSteps; ++i) { float *ptr = m_overlapBuffer+((i+1)*kStepSize); result |= processChunk(ptr); } return result; } void Detectors::doFFT(const float *buffer) { vDSP_vmul(buffer, 1, m_window, 1, m_inReal, 1, kBlockSize); vDSP_ctoz(reinterpret_cast<DSPComplex*>(m_inReal), 2, &m_splitData, 1, kSpectrumSize); vDSP_fft_zrip(m_fftSetup, &m_splitData, 1, kLogBlockSize, FFT_FORWARD); m_splitData.imagp[0] = 0.0f; float scale = 1.0f / static_cast<float>(2 * kBlockSize); vDSP_vsmul(m_splitData.realp, 1, &scale, m_splitData.realp, 1, kSpectrumSize); vDSP_vsmul(m_splitData.imagp, 1, &scale, m_splitData.imagp, 1, kSpectrumSize); } int Detectors::processChunk(const float *buffer) { doFFT(buffer); int result = 0; size_t n = kSpectrumSize; for (size_t i = 0; i < n; ++i) { float real = m_splitData.realp[i]; float imag = m_splitData.imagp[i]; float newVal = real * real + imag * imag; m_spectrum[i] = newVal; m_lowPassBuffer[i] = m_lowPassBuffer[i]*(1.0f-m_lowPassWeight) + newVal*m_lowPassWeight; // infinite values happen non-deterministically, probably due to glitchy audio input at start of recording // but inifinities it could mess up things forever if(m_lowPassBuffer[i] >= numeric_limits<float>::infinity()) { std::fill(m_lowPassBuffer.begin(), m_lowPassBuffer.end(), 0.0f); return 0; // discard the frame, it's probably garbage } } float lowerBand = avgBand(m_lowPassBuffer, kLowerBandLow, kLowerBandHi); float mainBand = avgBand(m_lowPassBuffer, kMainBandLow, kMainBandHi); float upperBand = avgBand(m_lowPassBuffer, kUpperBandLo, kUpperBandHi); m_framesSinceSpeech += 1; if(lowerBand > kSpeechThresh) { m_framesSinceSpeech = 0; } float debugMarker = 0.0002; float matchiness = mainBand / ((lowerBand+upperBand)/2.0f); bool outOfShadow = m_framesSinceSpeech > kSpeechShadowTime; int immediateMatchFrame = kDelayMatch ? m_minFramesLong : m_minFrames; m_framesSinceMatch += 1; if(((matchiness >= m_sensitivity) || (m_consecutiveMatches > 0 && matchiness >= m_sensitivity*m_hysterisisFactor) || (m_consecutiveMatches > immediateMatchFrame && (mainBand/m_savedOtherBands) >= m_sensitivity*m_hysterisisFactor*0.5f)) && outOfShadow) { debugMarker = 0.01; // second one in double "tss" came earlier than trigger timer if(kDelayMatch && m_consecutiveMatches == 0 && m_framesSinceMatch <= m_minFramesLong) { result |= TSS_START_CODE; result |= TSS_STOP_CODE; m_framesSinceMatch = 1000; } m_consecutiveMatches += 1; if(kDelayMatch && m_consecutiveMatches == m_minFrames) { m_framesSinceMatch = m_consecutiveMatches; } else if(m_consecutiveMatches == immediateMatchFrame) { debugMarker = 1.0; result |= TSS_START_CODE; m_savedOtherBands = ((lowerBand+upperBand)/2.0f); } } else { bool delayedMatch = kDelayMatch && (m_framesSinceMatch == m_minFramesLong && outOfShadow); if(delayedMatch) { result |= TSS_START_CODE; } if(m_consecutiveMatches >= immediateMatchFrame || delayedMatch) { debugMarker = 2.0; result |= TSS_STOP_CODE; } m_consecutiveMatches = 0; } // ===================== Pop Detection ================================= // update buffer forward one time step for(unsigned i = 0; i < kBufferPrimaryHeight; ++i) { m_popBuffer.pop_front(); m_popBuffer.push_back(m_spectrum[i]); } // high frequencies aren't useful so we bin them all together m_popBuffer.pop_front(); float highSum = accumulate(m_spectrum.begin()+kBufferPrimaryHeight,m_spectrum.end(),0.0); m_popBuffer.push_back(highSum); std::deque<float>::iterator maxIt = max_element(m_popBuffer.begin(), m_popBuffer.end()); float minDiff = 10000000.0; for(int i = -m_maxShiftUp; i < m_maxShiftDown; ++i) { float diff = templateDiff(*maxIt, i); if(diff < minDiff) minDiff = diff; } m_framesSincePop += 1; if(minDiff < m_popSensitivity && m_framesSincePop > 15) { result |= POP_CODE; // Detected pop m_framesSincePop = 0; } // *debugLog << lowerBand << ' ' << mainBand << ' ' << optionalBand << ' ' << upperBand << '-' << matchiness << ' ' << debugMarker << std::endl; return result; } float Detectors::avgBand(std::vector<float> &frame, size_t low, size_t hi) { float sum = 0; for (size_t i = low; i < hi; ++i) { sum += frame[i]; } return sum / (hi - low); } float Detectors::templateAt(int i, int shift) { int bin = i % kBufferHeight; if(i % kBufferHeight >= kBufferPrimaryHeight) { return kPopTemplate[i]/kPopTemplateMax; } if(bin+shift < 0 || bin+shift >= kBufferPrimaryHeight) { return 0.0; } return kPopTemplate[i+shift]/kPopTemplateMax; } float Detectors::diffCol(int templStart, int bufStart, float maxVal, int shift) { float diff = 0; for(unsigned i = m_startBin; i < kBufferHeight; ++i) { float d = templateAt(templStart+i, shift) - m_popBuffer[bufStart+i]/maxVal; diff += abs(d); } return diff; } float Detectors::templateDiff(float maxVal, int shift) { float diff = 0; for(unsigned i = 0; i < kBufferSize; i += kBufferHeight) { diff += diffCol(i,i, maxVal,shift); } return diff; } extern "C" { detectors_t *detectors_new() { Detectors *dets = new Detectors(); dets->initialise(); return reinterpret_cast<detectors_t*>(dets); } void detectors_free(detectors_t *detectors) { Detectors *dets = reinterpret_cast<Detectors*>(detectors); delete dets; } int detectors_process(detectors_t *detectors, const float *buffer) { Detectors *dets = reinterpret_cast<Detectors*>(detectors); return dets->process(buffer); } } <commit_msg>Fix #include in hs.noises for the correct filename case<commit_after>#include "detectors.h" #include <iostream> #include <numeric> #include <algorithm> #include <cmath> #include <limits> using namespace std; #include "popTemplate.h" static const bool kDelayMatch = false; static const int kBlockSize = DETECTORS_BLOCK_SIZE; static const int kLogBlockSize = 9; static const int kSpectrumSize = kBlockSize/2; static const int kWindowSize = kBlockSize; static const int kNumSteps = 4; static const int kStepSize = kBlockSize / kNumSteps; static const size_t kMainBandLow = 40; static const size_t kMainBandHi = 100; static const size_t kOptionalBandHi = 180; static const size_t kLowerBandLow = 3; static const size_t kLowerBandHi = kMainBandLow; static const size_t kUpperBandLo = kOptionalBandHi; static const size_t kUpperBandHi = kSpectrumSize; static const float kDefaultLowPassWeight = 0.6; static const int kSpeechShadowTime = 100; static const float kSpeechThresh = 0.5; Detectors::Detectors() { m_overlapBuffer = new float[kBlockSize * 2]; // === Tss Detection m_sensitivity = 5.0; m_hysterisisFactor = 0.4; m_minFrames = 20; m_minFramesLong = 100; m_lowPassWeight = kDefaultLowPassWeight; // === Pop detection m_startBin = 2; m_maxShiftDown = 4; m_maxShiftUp = 2; m_popSensitivity = 8.5; m_framesSincePop = 0; // debugLog = new std::ofstream("/Users/tristan/misc/popclick.log"); // === FFT m_inReal = new float[kBlockSize]; m_splitData.realp = new float[kSpectrumSize]; m_splitData.imagp = new float[kSpectrumSize]; m_window = new float[kWindowSize]; memset(m_window, 0, sizeof(float) * kWindowSize); vDSP_hann_window(m_window, kWindowSize, vDSP_HANN_NORM); m_fftSetup = vDSP_create_fftsetup(kLogBlockSize, FFT_RADIX2); } Detectors::~Detectors() { delete[] m_overlapBuffer; delete[] m_inReal; delete[] m_splitData.realp; delete[] m_splitData.imagp; delete[] m_window; // delete debugLog; vDSP_destroy_fftsetup(m_fftSetup); } bool Detectors::initialise() { // Real initialisation work goes here! m_savedOtherBands = 0.0002; m_consecutiveMatches = 0; m_framesSinceSpeech = 1000; m_framesSinceMatch = 1000; m_lowPassBuffer.resize(kSpectrumSize, 0.0); m_spectrum.resize(kSpectrumSize, 0.0); m_popBuffer.clear(); for(unsigned i = 0; i < kBufferSize; ++i) { m_popBuffer.push_back(0.0); } return true; } int Detectors::process(const float *buffer) { // return processChunk(buffer); // copy last frame to start of the buffer std::copy(m_overlapBuffer+kBlockSize, m_overlapBuffer+(kBlockSize*2), m_overlapBuffer); // copy new input to the second half of the overlap buffer std::copy(buffer,buffer+kBlockSize,m_overlapBuffer+kBlockSize); int result = 0; for(int i = 0; i < kNumSteps; ++i) { float *ptr = m_overlapBuffer+((i+1)*kStepSize); result |= processChunk(ptr); } return result; } void Detectors::doFFT(const float *buffer) { vDSP_vmul(buffer, 1, m_window, 1, m_inReal, 1, kBlockSize); vDSP_ctoz(reinterpret_cast<DSPComplex*>(m_inReal), 2, &m_splitData, 1, kSpectrumSize); vDSP_fft_zrip(m_fftSetup, &m_splitData, 1, kLogBlockSize, FFT_FORWARD); m_splitData.imagp[0] = 0.0f; float scale = 1.0f / static_cast<float>(2 * kBlockSize); vDSP_vsmul(m_splitData.realp, 1, &scale, m_splitData.realp, 1, kSpectrumSize); vDSP_vsmul(m_splitData.imagp, 1, &scale, m_splitData.imagp, 1, kSpectrumSize); } int Detectors::processChunk(const float *buffer) { doFFT(buffer); int result = 0; size_t n = kSpectrumSize; for (size_t i = 0; i < n; ++i) { float real = m_splitData.realp[i]; float imag = m_splitData.imagp[i]; float newVal = real * real + imag * imag; m_spectrum[i] = newVal; m_lowPassBuffer[i] = m_lowPassBuffer[i]*(1.0f-m_lowPassWeight) + newVal*m_lowPassWeight; // infinite values happen non-deterministically, probably due to glitchy audio input at start of recording // but inifinities it could mess up things forever if(m_lowPassBuffer[i] >= numeric_limits<float>::infinity()) { std::fill(m_lowPassBuffer.begin(), m_lowPassBuffer.end(), 0.0f); return 0; // discard the frame, it's probably garbage } } float lowerBand = avgBand(m_lowPassBuffer, kLowerBandLow, kLowerBandHi); float mainBand = avgBand(m_lowPassBuffer, kMainBandLow, kMainBandHi); float upperBand = avgBand(m_lowPassBuffer, kUpperBandLo, kUpperBandHi); m_framesSinceSpeech += 1; if(lowerBand > kSpeechThresh) { m_framesSinceSpeech = 0; } float debugMarker = 0.0002; float matchiness = mainBand / ((lowerBand+upperBand)/2.0f); bool outOfShadow = m_framesSinceSpeech > kSpeechShadowTime; int immediateMatchFrame = kDelayMatch ? m_minFramesLong : m_minFrames; m_framesSinceMatch += 1; if(((matchiness >= m_sensitivity) || (m_consecutiveMatches > 0 && matchiness >= m_sensitivity*m_hysterisisFactor) || (m_consecutiveMatches > immediateMatchFrame && (mainBand/m_savedOtherBands) >= m_sensitivity*m_hysterisisFactor*0.5f)) && outOfShadow) { debugMarker = 0.01; // second one in double "tss" came earlier than trigger timer if(kDelayMatch && m_consecutiveMatches == 0 && m_framesSinceMatch <= m_minFramesLong) { result |= TSS_START_CODE; result |= TSS_STOP_CODE; m_framesSinceMatch = 1000; } m_consecutiveMatches += 1; if(kDelayMatch && m_consecutiveMatches == m_minFrames) { m_framesSinceMatch = m_consecutiveMatches; } else if(m_consecutiveMatches == immediateMatchFrame) { debugMarker = 1.0; result |= TSS_START_CODE; m_savedOtherBands = ((lowerBand+upperBand)/2.0f); } } else { bool delayedMatch = kDelayMatch && (m_framesSinceMatch == m_minFramesLong && outOfShadow); if(delayedMatch) { result |= TSS_START_CODE; } if(m_consecutiveMatches >= immediateMatchFrame || delayedMatch) { debugMarker = 2.0; result |= TSS_STOP_CODE; } m_consecutiveMatches = 0; } // ===================== Pop Detection ================================= // update buffer forward one time step for(unsigned i = 0; i < kBufferPrimaryHeight; ++i) { m_popBuffer.pop_front(); m_popBuffer.push_back(m_spectrum[i]); } // high frequencies aren't useful so we bin them all together m_popBuffer.pop_front(); float highSum = accumulate(m_spectrum.begin()+kBufferPrimaryHeight,m_spectrum.end(),0.0); m_popBuffer.push_back(highSum); std::deque<float>::iterator maxIt = max_element(m_popBuffer.begin(), m_popBuffer.end()); float minDiff = 10000000.0; for(int i = -m_maxShiftUp; i < m_maxShiftDown; ++i) { float diff = templateDiff(*maxIt, i); if(diff < minDiff) minDiff = diff; } m_framesSincePop += 1; if(minDiff < m_popSensitivity && m_framesSincePop > 15) { result |= POP_CODE; // Detected pop m_framesSincePop = 0; } // *debugLog << lowerBand << ' ' << mainBand << ' ' << optionalBand << ' ' << upperBand << '-' << matchiness << ' ' << debugMarker << std::endl; return result; } float Detectors::avgBand(std::vector<float> &frame, size_t low, size_t hi) { float sum = 0; for (size_t i = low; i < hi; ++i) { sum += frame[i]; } return sum / (hi - low); } float Detectors::templateAt(int i, int shift) { int bin = i % kBufferHeight; if(i % kBufferHeight >= kBufferPrimaryHeight) { return kPopTemplate[i]/kPopTemplateMax; } if(bin+shift < 0 || bin+shift >= kBufferPrimaryHeight) { return 0.0; } return kPopTemplate[i+shift]/kPopTemplateMax; } float Detectors::diffCol(int templStart, int bufStart, float maxVal, int shift) { float diff = 0; for(unsigned i = m_startBin; i < kBufferHeight; ++i) { float d = templateAt(templStart+i, shift) - m_popBuffer[bufStart+i]/maxVal; diff += abs(d); } return diff; } float Detectors::templateDiff(float maxVal, int shift) { float diff = 0; for(unsigned i = 0; i < kBufferSize; i += kBufferHeight) { diff += diffCol(i,i, maxVal,shift); } return diff; } extern "C" { detectors_t *detectors_new() { Detectors *dets = new Detectors(); dets->initialise(); return reinterpret_cast<detectors_t*>(dets); } void detectors_free(detectors_t *detectors) { Detectors *dets = reinterpret_cast<Detectors*>(detectors); delete dets; } int detectors_process(detectors_t *detectors, const float *buffer) { Detectors *dets = reinterpret_cast<Detectors*>(detectors); return dets->process(buffer); } } <|endoftext|>
<commit_before>/* * Copyright (c) 2003-2006 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Nathan Binkert */ #ifndef __SIM_PSEUDO_INST_HH__ #define __SIM_PSEUDO_INST_HH__ class ThreadContext; //We need the "Tick" and "Addr" data types from here #include "base/types.hh" namespace PseudoInst { /** * @todo these externs are only here for a hack in fullCPU::takeOver... */ extern bool doStatisticsInsts; extern bool doCheckpointInsts; extern bool doQuiesce; void arm(ThreadContext *tc); void quiesce(ThreadContext *tc); void quiesceSkip(ThreadContext *tc); void quiesceNs(ThreadContext *tc, uint64_t ns); void quiesceCycles(ThreadContext *tc, uint64_t cycles); uint64_t quiesceTime(ThreadContext *tc); uint64_t readfile(ThreadContext *tc, Addr vaddr, uint64_t len, uint64_t offset); uint64_t writefile(ThreadContext *tc, Addr vaddr, uint64_t len, uint64_t offset, Addr filenameAddr); void loadsymbol(ThreadContext *xc); void addsymbol(ThreadContext *tc, Addr addr, Addr symbolAddr); uint64_t initParam(ThreadContext *xc); uint64_t rpns(ThreadContext *tc); void wakeCPU(ThreadContext *tc, uint64_t cpuid); void m5exit(ThreadContext *tc, Tick delay); void resetstats(ThreadContext *tc, Tick delay, Tick period); void dumpstats(ThreadContext *tc, Tick delay, Tick period); void dumpresetstats(ThreadContext *tc, Tick delay, Tick period); void m5checkpoint(ThreadContext *tc, Tick delay, Tick period); void debugbreak(ThreadContext *tc); void switchcpu(ThreadContext *tc); void workbegin(ThreadContext *tc, uint64_t workid, uint64_t threadid); void workend(ThreadContext *tc, uint64_t workid, uint64_t threadid); } // namespace PseudoInst #endif // __SIM_PSEUDO_INST_HH__ <commit_msg>sim: Remove unused variables<commit_after>/* * Copyright (c) 2003-2006 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Nathan Binkert */ #ifndef __SIM_PSEUDO_INST_HH__ #define __SIM_PSEUDO_INST_HH__ class ThreadContext; //We need the "Tick" and "Addr" data types from here #include "base/types.hh" namespace PseudoInst { void arm(ThreadContext *tc); void quiesce(ThreadContext *tc); void quiesceSkip(ThreadContext *tc); void quiesceNs(ThreadContext *tc, uint64_t ns); void quiesceCycles(ThreadContext *tc, uint64_t cycles); uint64_t quiesceTime(ThreadContext *tc); uint64_t readfile(ThreadContext *tc, Addr vaddr, uint64_t len, uint64_t offset); uint64_t writefile(ThreadContext *tc, Addr vaddr, uint64_t len, uint64_t offset, Addr filenameAddr); void loadsymbol(ThreadContext *xc); void addsymbol(ThreadContext *tc, Addr addr, Addr symbolAddr); uint64_t initParam(ThreadContext *xc); uint64_t rpns(ThreadContext *tc); void wakeCPU(ThreadContext *tc, uint64_t cpuid); void m5exit(ThreadContext *tc, Tick delay); void resetstats(ThreadContext *tc, Tick delay, Tick period); void dumpstats(ThreadContext *tc, Tick delay, Tick period); void dumpresetstats(ThreadContext *tc, Tick delay, Tick period); void m5checkpoint(ThreadContext *tc, Tick delay, Tick period); void debugbreak(ThreadContext *tc); void switchcpu(ThreadContext *tc); void workbegin(ThreadContext *tc, uint64_t workid, uint64_t threadid); void workend(ThreadContext *tc, uint64_t workid, uint64_t threadid); } // namespace PseudoInst #endif // __SIM_PSEUDO_INST_HH__ <|endoftext|>
<commit_before>#include "singleton_edge.h" void siren_edge_install(mrb_state* mrb, RObject* o) { mrb_define_singleton_method(mrb, o, "sp", siren_edge_sp, MRB_ARGS_NONE()); mrb_define_singleton_method(mrb, o, "tp", siren_edge_tp, MRB_ARGS_NONE()); mrb_define_singleton_method(mrb, o, "to_pts", siren_edge_to_pts, MRB_ARGS_OPT(1)); mrb_define_singleton_method(mrb, o, "param", siren_edge_param, MRB_ARGS_REQ(1) | MRB_ARGS_OPT(1)); mrb_define_singleton_method(mrb, o, "to_xyz", siren_edge_to_xyz, MRB_ARGS_REQ(1)); mrb_define_singleton_method(mrb, o, "curvature", siren_edge_curvature, MRB_ARGS_REQ(1)); mrb_define_singleton_method(mrb, o, "tangent", siren_edge_tangent, MRB_ARGS_REQ(1)); mrb_define_singleton_method(mrb, o, "nurbs_def", siren_edge_nurbs_def, MRB_ARGS_NONE()); return; } mrb_value siren_edge_sp(mrb_state* mrb, mrb_value self) { TopoDS_Shape* c = siren_shape_get(mrb, self); BRepAdaptor_Curve bracurve(TopoDS::Edge(*c)); gp_Pnt sp = bracurve.Value(bracurve.FirstParameter()); return siren_vec_new(mrb, sp.X(), sp.Y(), sp.Z()); } mrb_value siren_edge_tp(mrb_state* mrb, mrb_value self) { TopoDS_Shape* c = siren_shape_get(mrb, self); BRepAdaptor_Curve bracurve(TopoDS::Edge(*c)); gp_Pnt tp = bracurve.Value(bracurve.LastParameter()); return siren_vec_new(mrb, tp.X(), tp.Y(), tp.Z()); } mrb_value siren_edge_to_pts(mrb_state* mrb, mrb_value self) { mrb_float deflect; int argc = mrb_get_args(mrb, "|f", &deflect); TopoDS_Shape* shape = siren_shape_get(mrb, self); if (argc != 2) { deflect = 1.0e-1; } mrb_value result = mrb_ary_new(mrb); double first_param, last_param; TopExp_Explorer exp(*shape, TopAbs_EDGE); for(; exp.More(); exp.Next()) { TopoDS_Edge edge = TopoDS::Edge(exp.Current()); BRepAdaptor_Curve adaptor(edge); first_param = adaptor.FirstParameter(); last_param = adaptor.LastParameter(); GCPnts_UniformDeflection unidef(adaptor, deflect); if (!unidef.IsDone()) { continue; } mrb_value line = mrb_ary_new(mrb); // first point gp_Pnt p = adaptor.Value(first_param); mrb_ary_push(mrb, line, siren_vec_new(mrb, p.X(), p.Y(), p.Z())); for (int i=1; i<=unidef.NbPoints(); i++) { p = unidef.Value(i); mrb_ary_push(mrb, line, siren_vec_new(mrb, p.X(), p.Y(), p.Z())); } // last point p = adaptor.Value(last_param); mrb_ary_push(mrb, line, siren_vec_new(mrb, p.X(), p.Y(), p.Z())); mrb_ary_push(mrb, result, line); } return result; } mrb_value siren_edge_param(mrb_state* mrb, mrb_value self) { mrb_value xyz; mrb_float tol; int argc = mrb_get_args(mrb, "A|f", &xyz, &tol); TopoDS_Shape* shape = siren_shape_get(mrb, self); TopoDS_Edge edge = TopoDS::Edge(*shape); ShapeAnalysis_Curve ana; BRepAdaptor_Curve gcurve(edge); gp_Pnt p = siren_ary_to_pnt(mrb, xyz); gp_Pnt pp; Standard_Real param; Standard_Real distance = ana.Project(gcurve, p, tol, pp, param); if (fabs(distance) > tol) { mrb_raise(mrb, E_ARGUMENT_ERROR, "Specified position is not on the edge."); } return mrb_float_value(mrb, param); } mrb_value siren_edge_to_xyz(mrb_state* mrb, mrb_value self) { mrb_float param; int argc = mrb_get_args(mrb, "f", &param); TopoDS_Shape* shape = siren_shape_get(mrb, self); BRepAdaptor_Curve C(TopoDS::Edge(*shape)); gp_Pnt p; gp_Vec v1, v2; C.D2(param, p, v1, v2); return siren_vec_new(mrb, p.X(), p.Y(), p.Z()); } mrb_value siren_edge_curvature(mrb_state* mrb, mrb_value self) { mrb_float param; int argc = mrb_get_args(mrb, "f", &param); TopoDS_Shape* shape = siren_shape_get(mrb, self); BRepAdaptor_Curve C(TopoDS::Edge(*shape)); gp_Pnt p; gp_Vec v1, v2; C.D2(param, p, v1, v2); return siren_vec_new(mrb, v2.X(), v2.Y(), v2.Z()); } mrb_value siren_edge_tangent(mrb_state* mrb, mrb_value self) { mrb_float param; int argc = mrb_get_args(mrb, "f", &param); TopoDS_Shape* shape = siren_shape_get(mrb, self); BRepAdaptor_Curve C(TopoDS::Edge(*shape)); gp_Pnt p; gp_Vec v1, v2; C.D2(param, p, v1, v2); return siren_vec_new(mrb, v1.X(), v1.Y(), v1.Z()); } mrb_value siren_edge_nurbs_def(mrb_state* mrb, mrb_value self) { TopoDS_Shape* shape = siren_shape_get(mrb, self); TopoDS_Edge edge = TopoDS::Edge(*shape); Standard_Real first, last; Handle(Geom_Curve) hgcurve = BRep_Tool::Curve(edge, first, last); #if 0 Handle(Geom_TrimmedCurve) hgtc = new Geom_TrimmedCurve(hgcurve, first, last); Handle(Geom_BSplineCurve) hgbc = Handle(Geom_BSplineCurve)::DownCast(hgtc->BasisCurve()); #else Handle(Geom_BSplineCurve) hgbc = Handle(Geom_BSplineCurve)::DownCast(hgcurve); #endif if (hgbc.IsNull()) { // Failed to downcast to BSplineCurve return mrb_nil_value(); } mrb_value res = mrb_ary_new(mrb); // degree mrb_ary_push(mrb, res, mrb_fixnum_value((int)hgbc->Degree())); // knots mrb_value knots = mrb_ary_new(mrb); for (int i=1; i <= hgbc->NbKnots(); i++) { mrb_ary_push(mrb, knots, mrb_float_value(mrb, hgbc->Knot(i))); } mrb_ary_push(mrb, res, knots); // mults mrb_value mults = mrb_ary_new(mrb); for (int i=1; i <= hgbc->NbKnots(); i++) { mrb_ary_push(mrb, mults, mrb_fixnum_value(hgbc->Multiplicity(i))); } mrb_ary_push(mrb, res, mults); // poles mrb_value poles = mrb_ary_new(mrb); for (int i=1; i <= hgbc->NbPoles(); i++) { mrb_ary_push(mrb, poles, siren_vec_new(mrb, hgbc->Pole(i).X(), hgbc->Pole(i).Y(), hgbc->Pole(i).Z())); } mrb_ary_push(mrb, res, poles); // weights mrb_value weights = mrb_ary_new(mrb); for (int i=1; i <= hgbc->NbPoles(); i++) { mrb_ary_push(mrb, weights, mrb_float_value(mrb, hgbc->Weight(i))); } mrb_ary_push(mrb, res, weights); // params mrb_ary_push(mrb, res, mrb_float_value(mrb, first)); mrb_ary_push(mrb, res, mrb_float_value(mrb, last)); return res; } <commit_msg>Fix bug of argument check.<commit_after>#include "singleton_edge.h" void siren_edge_install(mrb_state* mrb, RObject* o) { mrb_define_singleton_method(mrb, o, "sp", siren_edge_sp, MRB_ARGS_NONE()); mrb_define_singleton_method(mrb, o, "tp", siren_edge_tp, MRB_ARGS_NONE()); mrb_define_singleton_method(mrb, o, "to_pts", siren_edge_to_pts, MRB_ARGS_OPT(1)); mrb_define_singleton_method(mrb, o, "param", siren_edge_param, MRB_ARGS_REQ(1) | MRB_ARGS_OPT(1)); mrb_define_singleton_method(mrb, o, "to_xyz", siren_edge_to_xyz, MRB_ARGS_REQ(1)); mrb_define_singleton_method(mrb, o, "curvature", siren_edge_curvature, MRB_ARGS_REQ(1)); mrb_define_singleton_method(mrb, o, "tangent", siren_edge_tangent, MRB_ARGS_REQ(1)); mrb_define_singleton_method(mrb, o, "nurbs_def", siren_edge_nurbs_def, MRB_ARGS_NONE()); return; } mrb_value siren_edge_sp(mrb_state* mrb, mrb_value self) { TopoDS_Shape* c = siren_shape_get(mrb, self); BRepAdaptor_Curve bracurve(TopoDS::Edge(*c)); gp_Pnt sp = bracurve.Value(bracurve.FirstParameter()); return siren_vec_new(mrb, sp.X(), sp.Y(), sp.Z()); } mrb_value siren_edge_tp(mrb_state* mrb, mrb_value self) { TopoDS_Shape* c = siren_shape_get(mrb, self); BRepAdaptor_Curve bracurve(TopoDS::Edge(*c)); gp_Pnt tp = bracurve.Value(bracurve.LastParameter()); return siren_vec_new(mrb, tp.X(), tp.Y(), tp.Z()); } mrb_value siren_edge_to_pts(mrb_state* mrb, mrb_value self) { mrb_float deflect; int argc = mrb_get_args(mrb, "|f", &deflect); TopoDS_Shape* shape = siren_shape_get(mrb, self); if (argc != 1) { deflect = 1.0e-1; } mrb_value result = mrb_ary_new(mrb); double first_param, last_param; TopExp_Explorer exp(*shape, TopAbs_EDGE); for(; exp.More(); exp.Next()) { TopoDS_Edge edge = TopoDS::Edge(exp.Current()); BRepAdaptor_Curve adaptor(edge); first_param = adaptor.FirstParameter(); last_param = adaptor.LastParameter(); GCPnts_UniformDeflection unidef(adaptor, deflect); if (!unidef.IsDone()) { continue; } mrb_value line = mrb_ary_new(mrb); // first point gp_Pnt p = adaptor.Value(first_param); mrb_ary_push(mrb, line, siren_vec_new(mrb, p.X(), p.Y(), p.Z())); for (int i=1; i<=unidef.NbPoints(); i++) { p = unidef.Value(i); mrb_ary_push(mrb, line, siren_vec_new(mrb, p.X(), p.Y(), p.Z())); } // last point p = adaptor.Value(last_param); mrb_ary_push(mrb, line, siren_vec_new(mrb, p.X(), p.Y(), p.Z())); mrb_ary_push(mrb, result, line); } return result; } mrb_value siren_edge_param(mrb_state* mrb, mrb_value self) { mrb_value xyz; mrb_float tol; int argc = mrb_get_args(mrb, "A|f", &xyz, &tol); TopoDS_Shape* shape = siren_shape_get(mrb, self); TopoDS_Edge edge = TopoDS::Edge(*shape); ShapeAnalysis_Curve ana; BRepAdaptor_Curve gcurve(edge); gp_Pnt p = siren_ary_to_pnt(mrb, xyz); gp_Pnt pp; Standard_Real param; Standard_Real distance = ana.Project(gcurve, p, tol, pp, param); if (fabs(distance) > tol) { mrb_raise(mrb, E_ARGUMENT_ERROR, "Specified position is not on the edge."); } return mrb_float_value(mrb, param); } mrb_value siren_edge_to_xyz(mrb_state* mrb, mrb_value self) { mrb_float param; int argc = mrb_get_args(mrb, "f", &param); TopoDS_Shape* shape = siren_shape_get(mrb, self); BRepAdaptor_Curve C(TopoDS::Edge(*shape)); gp_Pnt p; gp_Vec v1, v2; C.D2(param, p, v1, v2); return siren_vec_new(mrb, p.X(), p.Y(), p.Z()); } mrb_value siren_edge_curvature(mrb_state* mrb, mrb_value self) { mrb_float param; int argc = mrb_get_args(mrb, "f", &param); TopoDS_Shape* shape = siren_shape_get(mrb, self); BRepAdaptor_Curve C(TopoDS::Edge(*shape)); gp_Pnt p; gp_Vec v1, v2; C.D2(param, p, v1, v2); return siren_vec_new(mrb, v2.X(), v2.Y(), v2.Z()); } mrb_value siren_edge_tangent(mrb_state* mrb, mrb_value self) { mrb_float param; int argc = mrb_get_args(mrb, "f", &param); TopoDS_Shape* shape = siren_shape_get(mrb, self); BRepAdaptor_Curve C(TopoDS::Edge(*shape)); gp_Pnt p; gp_Vec v1, v2; C.D2(param, p, v1, v2); return siren_vec_new(mrb, v1.X(), v1.Y(), v1.Z()); } mrb_value siren_edge_nurbs_def(mrb_state* mrb, mrb_value self) { TopoDS_Shape* shape = siren_shape_get(mrb, self); TopoDS_Edge edge = TopoDS::Edge(*shape); Standard_Real first, last; Handle(Geom_Curve) hgcurve = BRep_Tool::Curve(edge, first, last); #if 0 Handle(Geom_TrimmedCurve) hgtc = new Geom_TrimmedCurve(hgcurve, first, last); Handle(Geom_BSplineCurve) hgbc = Handle(Geom_BSplineCurve)::DownCast(hgtc->BasisCurve()); #else Handle(Geom_BSplineCurve) hgbc = Handle(Geom_BSplineCurve)::DownCast(hgcurve); #endif if (hgbc.IsNull()) { // Failed to downcast to BSplineCurve return mrb_nil_value(); } mrb_value res = mrb_ary_new(mrb); // degree mrb_ary_push(mrb, res, mrb_fixnum_value((int)hgbc->Degree())); // knots mrb_value knots = mrb_ary_new(mrb); for (int i=1; i <= hgbc->NbKnots(); i++) { mrb_ary_push(mrb, knots, mrb_float_value(mrb, hgbc->Knot(i))); } mrb_ary_push(mrb, res, knots); // mults mrb_value mults = mrb_ary_new(mrb); for (int i=1; i <= hgbc->NbKnots(); i++) { mrb_ary_push(mrb, mults, mrb_fixnum_value(hgbc->Multiplicity(i))); } mrb_ary_push(mrb, res, mults); // poles mrb_value poles = mrb_ary_new(mrb); for (int i=1; i <= hgbc->NbPoles(); i++) { mrb_ary_push(mrb, poles, siren_vec_new(mrb, hgbc->Pole(i).X(), hgbc->Pole(i).Y(), hgbc->Pole(i).Z())); } mrb_ary_push(mrb, res, poles); // weights mrb_value weights = mrb_ary_new(mrb); for (int i=1; i <= hgbc->NbPoles(); i++) { mrb_ary_push(mrb, weights, mrb_float_value(mrb, hgbc->Weight(i))); } mrb_ary_push(mrb, res, weights); // params mrb_ary_push(mrb, res, mrb_float_value(mrb, first)); mrb_ary_push(mrb, res, mrb_float_value(mrb, last)); return res; } <|endoftext|>
<commit_before>#include <babylon/cameras/arc_rotate_camera.h> #include <babylon/core/random.h> #include <babylon/engines/scene.h> #include <babylon/interfaces/irenderable_scene.h> #include <babylon/lights/point_light.h> #include <babylon/materials/standard_material.h> #include <babylon/maths/vector3.h> #include <babylon/meshes/builders/mesh_builder_options.h> #include <babylon/meshes/instanced_mesh.h> #include <babylon/meshes/mesh.h> #include <babylon/meshes/mesh_builder.h> #include <babylon/samples/babylon_register_sample.h> namespace BABYLON { class AbstractMesh; class Mesh; using AbstractMeshPtr = std::shared_ptr<AbstractMesh>; using MeshPtr = std::shared_ptr<Mesh>; namespace Samples { /** * @brief Bouncing Cube Scene. * * In this simple example, you've got : * - a finite world defined by the big box * - some random platforms inside it, built with instances * - a Mario player, the tiny red box * * Mario is given an initial random velocity and applied a constant gravity. You can tweak the * energy loss against the box walls with the variable restitution (here : 100% = 1.0) * * When Mario hits a platform coming downward (he's above the platform), he bounces back with some * energy loss (variable platformBounceRestitution), when he hits the platform under it, he's just * rejected. This is a very simple and naive physics engine because I don't even test if Mario hits * the platform borders here. But it is fast.  * * Note that I also test all the platforms what is not performant at all (well, they aren't very * numerous). The use of an octree or any preselection (we know where all the obstacles are in the * space before the scene starts !) would be better.  * * @see http://www.babylonjs-playground.com/#PBVEM#17 */ class BouncingCubeScene : public IRenderableScene { public: BouncingCubeScene(ICanvas* iCanvas) : IRenderableScene(iCanvas) , _limit{0.f} , _restitution{0.f} , _platformBounceRestitution{0.f} , _k{0.f} , _mario{nullptr} { } ~BouncingCubeScene() override = default; const char* getName() override { return "Bouncing Cube Scene"; } void initializeScene(ICanvas* canvas, Scene* scene) override { scene->clearColor = Color3::Black(); auto camera = ArcRotateCamera::New("camera1", 0.f, 0.f, 0.f, Vector3::Zero(), scene); camera->setPosition(Vector3(0.f, 10.f, -500.f)); camera->attachControl(canvas, true); auto pl = PointLight::New("pl", Vector3::Zero(), scene); pl->diffuse = Color3(1.f, 1.f, 1.f); pl->intensity = 1.f; pl->position = camera->position; auto boxSize = 300.f; auto marioSize = 5.f; auto platformNb = 25; auto platformHeight = 3.f; auto platformMaxWidth = 40.f; auto platformMaxDepth = 20.f; auto platformMinSize = 20.f; _gravity = Vector3(0.f, -0.2f, 0.f); _platformBounceRestitution = 0.97f; auto speed = 2.f; _restitution = 0.95f; _limit = (boxSize - marioSize) * 0.5f; auto platformLimit = boxSize - platformMaxWidth - 10.f; _velocity = Vector3(Math::random(), Math::random(), Math::random()); _velocity.scaleInPlace(speed); auto initialVel = Vector3(0.5f, 2.f, 0.f); _velocity.addInPlace(initialVel); BoxOptions boxOptions; boxOptions.size = boxSize; boxOptions.sideOrientation = Mesh::BACKSIDE; auto box = MeshBuilder::CreateBox("b", boxOptions, scene); auto boxmat = StandardMaterial::New("boxmat", scene); boxmat->diffuseColor = Color3(0.4f, 0.6f, 1.f); boxmat->specularColor = Color3::Black(); box->material = boxmat; BoxOptions marioOptions; marioOptions.size = marioSize; _mario = MeshBuilder::CreateBox("m", marioOptions, scene); auto marioMat = StandardMaterial::New("marioMat", scene); marioMat->diffuseColor = Color3::Red(); marioMat->specularColor = Color3::Black(); _mario->material = marioMat; BoxOptions platformOptions; platformOptions.size = 1.f; auto platform = MeshBuilder::CreateBox("p", platformOptions, scene); auto platformMat = StandardMaterial::New("platform0", scene); platformMat->diffuseColor = Color3::Green(); platformMat->specularColor = Color3::Black(); platformMat->alpha = 0.7f; platform->material = platformMat; platform->position = Vector3((0.5f - Math::random()) * platformLimit, (0.5f - Math::random()) * platformLimit, (0.5f - Math::random()) * platformLimit); platform->scaling = Vector3(platformMinSize + platformMaxWidth * Math::random(), platformHeight, platformMinSize + Math::random() * platformMaxDepth); _platforms.emplace_back(platform); for (int i = 1; i < platformNb; ++i) { const auto instance = platform->createInstance("platform" + std::to_string(i)); instance->position = Vector3((0.5f - Math::random()) * platformLimit, (0.5f - Math::random()) * platformLimit, (0.5f - Math::random()) * platformLimit); platform->scaling = Vector3(platformMinSize + platformMaxWidth * Math::random(), platformHeight, platformMinSize + Math::random() * platformMaxDepth); _platforms.emplace_back(instance); } scene->registerBeforeRender([this](Scene* /*scene*/, EventState& /*es*/) { _applyForces(); _checkCollisions(); _moveMario(); _movePlatforms(); _k += 0.001f; }); } private: void _applyForces(); void _checkCollisions(); void _moveMario(); void _movePlatforms(); private: Vector3 _gravity; Vector3 _velocity; float _limit; float _restitution; float _platformBounceRestitution; float _k; MeshPtr _mario; std::vector<AbstractMeshPtr> _platforms; }; // end of class BouncingCubeScene } // end of namespace Samples } // end of namespace BABYLON namespace BABYLON { namespace Samples { void BouncingCubeScene::_applyForces() { _velocity.addInPlace(_gravity); } void BouncingCubeScene::_checkCollisions() { // Check box walls if (std::abs(_mario->position().x) > _limit) { _velocity.x *= -1.f; _mario->position().x = (_mario->position().x > 0.f) ? _limit : -_limit; } if (std::abs(_mario->position().y) > _limit) { _velocity.y *= -1.f * _restitution; _mario->position().y = (_mario->position().y > 0.f) ? _limit : -_limit; } if (std::abs(_mario->position().z) > _limit) { _velocity.z *= -1.f; _mario->position().z = (_mario->position().z > 0.f) ? _limit : -_limit; } // Check platforms size_t i = 0; for (auto& platform : _platforms) { if (_mario->intersectsMesh(*platform)) { // naive impact point check if (_mario->position().y > platform->position().y) { _mario->position().y = platform->position().y + platform->scaling().y * 0.5f; _velocity.y *= -_platformBounceRestitution; } if (_mario->position().y < platform->position().y) { _velocity.y *= -1.f; } } ++i; } } void BouncingCubeScene::_moveMario() { _mario->position().addInPlace(_velocity); } void BouncingCubeScene::_movePlatforms() { size_t i = 0; for (auto& platform : _platforms) { auto p = i % 3; switch (p) { case 0: platform->position().x += 0.1f * std::sin(_k * i); break; case 1: platform->position().y -= 0.2f * std::cos(_k * i); break; case 2: platform->position().z -= 0.03f * std::sin(_k * i); break; } ++i; } } BABYLON_REGISTER_SAMPLE("Animations", BouncingCubeScene) } // end of namespace Samples } // end of namespace BABYLON <commit_msg>Added lambda return type<commit_after>#include <babylon/cameras/arc_rotate_camera.h> #include <babylon/core/random.h> #include <babylon/engines/scene.h> #include <babylon/interfaces/irenderable_scene.h> #include <babylon/lights/point_light.h> #include <babylon/materials/standard_material.h> #include <babylon/maths/vector3.h> #include <babylon/meshes/builders/mesh_builder_options.h> #include <babylon/meshes/instanced_mesh.h> #include <babylon/meshes/mesh.h> #include <babylon/meshes/mesh_builder.h> #include <babylon/samples/babylon_register_sample.h> namespace BABYLON { class AbstractMesh; class Mesh; using AbstractMeshPtr = std::shared_ptr<AbstractMesh>; using MeshPtr = std::shared_ptr<Mesh>; namespace Samples { /** * @brief Bouncing Cube Scene. * * In this simple example, you've got : * - a finite world defined by the big box * - some random platforms inside it, built with instances * - a Mario player, the tiny red box * * Mario is given an initial random velocity and applied a constant gravity. You can tweak the * energy loss against the box walls with the variable restitution (here : 100% = 1.0) * * When Mario hits a platform coming downward (he's above the platform), he bounces back with some * energy loss (variable platformBounceRestitution), when he hits the platform under it, he's just * rejected. This is a very simple and naive physics engine because I don't even test if Mario hits * the platform borders here. But it is fast.  * * Note that I also test all the platforms what is not performant at all (well, they aren't very * numerous). The use of an octree or any preselection (we know where all the obstacles are in the * space before the scene starts !) would be better.  * * @see http://www.babylonjs-playground.com/#PBVEM#17 */ class BouncingCubeScene : public IRenderableScene { public: BouncingCubeScene(ICanvas* iCanvas) : IRenderableScene(iCanvas) , _limit{0.f} , _restitution{0.f} , _platformBounceRestitution{0.f} , _k{0.f} , _mario{nullptr} { } ~BouncingCubeScene() override = default; const char* getName() override { return "Bouncing Cube Scene"; } void initializeScene(ICanvas* canvas, Scene* scene) override { scene->clearColor = Color3::Black(); auto camera = ArcRotateCamera::New("camera1", 0.f, 0.f, 0.f, Vector3::Zero(), scene); camera->setPosition(Vector3(0.f, 10.f, -500.f)); camera->attachControl(canvas, true); auto pl = PointLight::New("pl", Vector3::Zero(), scene); pl->diffuse = Color3(1.f, 1.f, 1.f); pl->intensity = 1.f; pl->position = camera->position; auto boxSize = 300.f; auto marioSize = 5.f; auto platformNb = 25; auto platformHeight = 3.f; auto platformMaxWidth = 40.f; auto platformMaxDepth = 20.f; auto platformMinSize = 20.f; _gravity = Vector3(0.f, -0.2f, 0.f); _platformBounceRestitution = 0.97f; auto speed = 2.f; _restitution = 0.95f; _limit = (boxSize - marioSize) * 0.5f; auto platformLimit = boxSize - platformMaxWidth - 10.f; _velocity = Vector3(Math::random(), Math::random(), Math::random()); _velocity.scaleInPlace(speed); auto initialVel = Vector3(0.5f, 2.f, 0.f); _velocity.addInPlace(initialVel); BoxOptions boxOptions; boxOptions.size = boxSize; boxOptions.sideOrientation = Mesh::BACKSIDE; auto box = MeshBuilder::CreateBox("b", boxOptions, scene); auto boxmat = StandardMaterial::New("boxmat", scene); boxmat->diffuseColor = Color3(0.4f, 0.6f, 1.f); boxmat->specularColor = Color3::Black(); box->material = boxmat; BoxOptions marioOptions; marioOptions.size = marioSize; _mario = MeshBuilder::CreateBox("m", marioOptions, scene); auto marioMat = StandardMaterial::New("marioMat", scene); marioMat->diffuseColor = Color3::Red(); marioMat->specularColor = Color3::Black(); _mario->material = marioMat; BoxOptions platformOptions; platformOptions.size = 1.f; auto platform = MeshBuilder::CreateBox("p", platformOptions, scene); auto platformMat = StandardMaterial::New("platform0", scene); platformMat->diffuseColor = Color3::Green(); platformMat->specularColor = Color3::Black(); platformMat->alpha = 0.7f; platform->material = platformMat; platform->position = Vector3((0.5f - Math::random()) * platformLimit, (0.5f - Math::random()) * platformLimit, (0.5f - Math::random()) * platformLimit); platform->scaling = Vector3(platformMinSize + platformMaxWidth * Math::random(), platformHeight, platformMinSize + Math::random() * platformMaxDepth); _platforms.emplace_back(platform); for (int i = 1; i < platformNb; ++i) { const auto instance = platform->createInstance("platform" + std::to_string(i)); instance->position = Vector3((0.5f - Math::random()) * platformLimit, (0.5f - Math::random()) * platformLimit, (0.5f - Math::random()) * platformLimit); platform->scaling = Vector3(platformMinSize + platformMaxWidth * Math::random(), platformHeight, platformMinSize + Math::random() * platformMaxDepth); _platforms.emplace_back(instance); } scene->registerBeforeRender([this](Scene* /*scene*/, EventState& /*es*/) -> void { _applyForces(); _checkCollisions(); _moveMario(); _movePlatforms(); _k += 0.001f; }); } private: void _applyForces(); void _checkCollisions(); void _moveMario(); void _movePlatforms(); private: Vector3 _gravity; Vector3 _velocity; float _limit; float _restitution; float _platformBounceRestitution; float _k; MeshPtr _mario; std::vector<AbstractMeshPtr> _platforms; }; // end of class BouncingCubeScene } // end of namespace Samples } // end of namespace BABYLON namespace BABYLON { namespace Samples { void BouncingCubeScene::_applyForces() { _velocity.addInPlace(_gravity); } void BouncingCubeScene::_checkCollisions() { // Check box walls if (std::abs(_mario->position().x) > _limit) { _velocity.x *= -1.f; _mario->position().x = (_mario->position().x > 0.f) ? _limit : -_limit; } if (std::abs(_mario->position().y) > _limit) { _velocity.y *= -1.f * _restitution; _mario->position().y = (_mario->position().y > 0.f) ? _limit : -_limit; } if (std::abs(_mario->position().z) > _limit) { _velocity.z *= -1.f; _mario->position().z = (_mario->position().z > 0.f) ? _limit : -_limit; } // Check platforms size_t i = 0; for (auto& platform : _platforms) { if (_mario->intersectsMesh(*platform)) { // naive impact point check if (_mario->position().y > platform->position().y) { _mario->position().y = platform->position().y + platform->scaling().y * 0.5f; _velocity.y *= -_platformBounceRestitution; } if (_mario->position().y < platform->position().y) { _velocity.y *= -1.f; } } ++i; } } void BouncingCubeScene::_moveMario() { _mario->position().addInPlace(_velocity); } void BouncingCubeScene::_movePlatforms() { size_t i = 0; for (auto& platform : _platforms) { auto p = i % 3; switch (p) { case 0: platform->position().x += 0.1f * std::sin(_k * i); break; case 1: platform->position().y -= 0.2f * std::cos(_k * i); break; case 2: platform->position().z -= 0.03f * std::sin(_k * i); break; } ++i; } } BABYLON_REGISTER_SAMPLE("Animations", BouncingCubeScene) } // end of namespace Samples } // end of namespace BABYLON <|endoftext|>
<commit_before>#include <numeric> #include <cstdlib> #include <iostream> #include <fstream> #include <string> #include <vector> #include <map> #include <iomanip> #include <cmath> #include <algorithm> #include "sdd/sdd.hh" #include "sdd/tools/size.hh" using namespace std; struct conf : public sdd::flat_set_default_configuration { using Identifier = unsigned int; using Values = sdd::values::flat_set<char>; }; using SDD = sdd::SDD<conf>; using values_type = conf::Values; static const auto sublength = 35; SDD build (const string& str){ if (str.size() == sublength) { SDD result = sdd::one<conf>(); for (size_t i = 0; i != str.size(); ++i) result = SDD(i, { str[str.size() - i - 1] }, result); return result; } else { SDD result = sdd::one<conf>(); const auto subsize = str.size() / sublength; for (size_t i = 0; i != sublength; ++i) { const auto substr = str.substr(subsize * (sublength - i - 1), sublength); result = SDD(i, build (substr), result); } return result; } } int main (int argc, const char** argv) { const auto subsize = 1000; size_t max_size = 1; size_t max_name = 1; map<string, size_t> counts; vector<SDD> collections; vector<SDD> subcollection; subcollection.reserve(subsize); conf c; c.final_cleanup = false; // don't cleanup memory on manager scope exit. c.hom_cache_size = 2; c.hom_unique_table_size = 2; c.sdd_intersection_cache_size = 16000000; c.sdd_sum_cache_size = 16000000; c.sdd_difference_cache_size = 16000000; c.sdd_unique_table_size = 10000000; auto manager = sdd::init<conf>(c); if (argc == 0) { cerr << "No arguments" << endl; return 1; } string line; line.reserve(256); const size_t max_length = [&] { size_t length = 0; for (size_t param = 1; param < argc; ++param) { const string filename = argv[param]; max_name = max (max_name, filename.length()); ifstream dict(filename); if (dict.is_open()) { size_t count = 0; while (std::getline(dict, line)) { count++; length = length > line.size() ? length : line.size(); } counts [filename] = count; max_size = max (max_size, count > 0 ? (size_t) log10 ((double) count) + 1 : 1); } else { cerr << "Warning, can't open " << filename << endl; } } return length; }(); cout << "Max word length is " << max_length << endl; size_t rounded_length = 1; while (true) { if (rounded_length >= max_length) break; else rounded_length *= sublength; } line.reserve(rounded_length + 1); // Construct the SDD order: we need one level per letter. // vector<unsigned int> v(max_length); // iota(v.begin(), v.end(), 0); // sdd::order_builder<conf> ob; // const sdd::order<conf> order(sdd::order_builder<conf>(v.begin(), v.end())); for (size_t param = 1; param < argc; ++param) { string filename = argv[param]; ifstream dict (filename); if (dict.is_open()) { size_t count = 0; size_t max = counts [filename]; cout << setw(max_name + 5) << left << filename << right << "\033[s" << "\033[u" << setw(max_size) << count << " / " << setw(max_size) << max << flush; while (getline(dict, line)) { count++; line.insert(line.size(), rounded_length - line.size(), ' '); subcollection.push_back (build (line)); if (count % subsize == 0) { collections.emplace_back(sdd::sum<conf>(subcollection.cbegin(), subcollection.cend())); subcollection.clear(); cout << "\033[u" << setw(max_size) << count << " / " << setw(max_size) << max << flush; } } collections.emplace_back(sdd::sum<conf>(subcollection.cbegin(), subcollection.cend())); cout << "\033[u" << setw(max_size) << count << " / " << setw(max_size) << max << flush; } else { cerr << "Warning, can't open " << filename << endl; } dict.close(); cout << endl; } cout << "# Collections: " << collections.size() << endl; for (auto& c : collections) { cout << "Size: " << c.size() << endl; } const auto collection = sdd::sum<conf>(collections.cbegin(), collections.cend()); cout << "# Words: " << collection.size() << endl; cout << "Size: " << sdd::tools::size(collection) << " bytes" << endl; return 0; } <commit_msg>Show more information.<commit_after>#include <numeric> #include <cstdlib> #include <iostream> #include <fstream> #include <string> #include <vector> #include <map> #include <iomanip> #include <cmath> #include <algorithm> #include "sdd/sdd.hh" #include "sdd/tools/size.hh" #include "sdd/tools/nodes.hh" using namespace std; struct conf : public sdd::flat_set_default_configuration { using Identifier = unsigned int; using Values = sdd::values::flat_set<char>; }; using SDD = sdd::SDD<conf>; using values_type = conf::Values; static const auto sublength = 35; SDD build (const string& str){ if (str.size() == sublength) { SDD result = sdd::one<conf>(); for (size_t i = 0; i != str.size(); ++i) result = SDD(i, { str[str.size() - i - 1] }, result); return result; } else { SDD result = sdd::one<conf>(); const auto subsize = str.size() / sublength; for (size_t i = 0; i != sublength; ++i) { const auto substr = str.substr(subsize * (sublength - i - 1), sublength); result = SDD(i, build (substr), result); } return result; } } int main (int argc, const char** argv) { const auto subsize = 1000; size_t max_size = 1; size_t max_name = 1; map<string, size_t> counts; vector<SDD> collections; vector<SDD> subcollection; subcollection.reserve(subsize); conf c; c.final_cleanup = false; // don't cleanup memory on manager scope exit. c.hom_cache_size = 2; c.hom_unique_table_size = 2; // c.sdd_intersection_cache_size = 16000000; // c.sdd_sum_cache_size = 16000000; // c.sdd_difference_cache_size = 16000000; c.sdd_unique_table_size = 10000000; auto manager = sdd::init<conf>(c); if (argc == 0) { cerr << "No arguments" << endl; return 1; } string line; line.reserve(256); const size_t max_length = [&] { size_t length = 0; for (size_t param = 1; param < argc; ++param) { const string filename = argv[param]; max_name = max (max_name, filename.length()); ifstream dict(filename); if (dict.is_open()) { size_t count = 0; while (std::getline(dict, line)) { count++; length = length > line.size() ? length : line.size(); } counts [filename] = count; max_size = max (max_size, count > 0 ? (size_t) log10 ((double) count) + 1 : 1); } else { cerr << "Warning, can't open " << filename << endl; } } return length; }(); cout << "Max word length is " << max_length << endl; size_t rounded_length = 1; while (true) { if (rounded_length >= max_length) break; else rounded_length *= sublength; } line.reserve(rounded_length + 1); // Construct the SDD order: we need one level per letter. // vector<unsigned int> v(max_length); // iota(v.begin(), v.end(), 0); // sdd::order_builder<conf> ob; // const sdd::order<conf> order(sdd::order_builder<conf>(v.begin(), v.end())); for (size_t param = 1; param < argc; ++param) { string filename = argv[param]; ifstream dict (filename); if (dict.is_open()) { size_t count = 0; size_t max = counts [filename]; cout << setw(max_name + 5) << left << filename << right << "\033[s" << "\033[u" << setw(max_size) << count << " / " << setw(max_size) << max << flush; while (getline(dict, line)) { count++; line.insert(line.size(), rounded_length - line.size(), ' '); subcollection.push_back (build (line)); if (count % subsize == 0) { collections.emplace_back(sdd::sum<conf>(subcollection.cbegin(), subcollection.cend())); subcollection.clear(); cout << "\033[u" << setw(max_size) << count << " / " << setw(max_size) << max << flush; } } collections.emplace_back(sdd::sum<conf>(subcollection.cbegin(), subcollection.cend())); cout << "\033[u" << setw(max_size) << count << " / " << setw(max_size) << max << flush; } else { cerr << "Warning, can't open " << filename << endl; } dict.close(); cout << endl; } const auto collection = sdd::sum<conf>(collections.cbegin(), collections.cend()); cout << "# Words: " << collection.size() << endl; cout << "# Nodes: " << sdd::tools::nodes(collection).first << ", " << sdd::tools::nodes(collection).second << endl; cout << "Size: " << sdd::tools::size(collection) << " bytes" << endl; return 0; } <|endoftext|>
<commit_before>/* * This is the Calvin mini library for Arduino due * *Created on: 5 okt. 2015 * */ #include <stdio.h> #include "CalvinMini.h" #include <inttypes.h> #ifdef ARDUINO #include <SPI.h> #include <Ethernet.h> #include <util.h> //byte mac[] = { 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 }; byte mac[] = { 0x90, 0xA2, 0xDA, 0x0E, 0xF5, 0x93 }; IPAddress ip(192,168,0,5); //IPAddress ip(192,168,1,146); uint16_t slaveport = 5002; EthernetServer server(slaveport); EthernetClient client; const int messageOutLength = 4; String messageOut[messageOutLength] = {}; int nextMessage = 0; #endif actor globalActor; fifo actorFifo; /** * Current standard out is the lcd screen connected to arduino due */ int8_t StdOut(){ uint8_t inFifo; const char* token; token = "null"; inFifo = lengthOfData(globalActor.inportsFifo[0]); if(inFifo > 0) { token = fifoPop(globalActor.inportsFifo[0]); } return standardOut(token); } /** * What's up with the external C you might wonder, * well thats the only way i could ad a function pointer to a strut, * Apparently c++ handles this different from c. */ extern "C"{ rStatus actorInit(){ rStatus allOk = FAIL; globalActor.fireActor = &StdOut; /*This sets up the fifo for the actor, not sure *if it should be done here but for now it works*/ allOk = initFifo(&actorFifo); globalActor.inportsFifo[0] = &actorFifo; return allOk; } } /** * Create an new actor. * @param msg json list * @return return 1 if successful. */ rStatus CalvinMini::createActor(JsonObject &msg){ rStatus allOk = FAIL; JsonObject &state = msg.get("state"); JsonObject &name = state.get("actor_state"); globalActor.type = state.get("actor_type"); globalActor.name = name.get("name"); globalActor.id = name.get("id"); allOk = SUCCESS; actorInit(); return allOk; } extern "C"{ /** * This Function initiate the fifo must be * called prior to using the fifo. * * This fifo implementation is based upon a circular * buffert written by Elcia White found in the book * "Making Embedded Systems by Elecia White(O'Reilly). * * Copyright 2012 Elecia White,978-1-449-30214-6" */ rStatus initFifo(fifo *fif) { fif->size = FIFO_SIZE; fif->read = 0; fif->write = 0; return SUCCESS; } /** * Used by Add and Pop to determine fifo length. * * This fifo implementation is based upon a circular * buffert written by Elcia White found in the book * "Making Embedded Systems by Elecia White(O'Reilly). * Copyright 2012 Elecia White,978-1-449-30214-6" * * @return Fifo length */ int8_t lengthOfData(fifo *fif) { return ((fif->write - fif->read) & (fif->size -1)); } /** * Adds a new element to the fifo * * This fifo implementation is based upon a circular * buffert written by Elcia White found in the book * "Making Embedded Systems by Elecia White(O'Reilly). * * Copyright 2012 Elecia White,978-1-449-30214-6" * @return returns 0 if the fifo is full */ rStatus fifoAdd(fifo *fif, const char* element){ if(lengthOfData(fif) == (fif->size-1)) { return FAIL; //fifo full; } fif->element[fif->write] = element; fif->write = (fif->write + 1) & (fif->size - 1); return SUCCESS; //all is well } /** * Return and removes the oldest element in the fifo. * * This fifo implementation is based upon a circular * buffert written by Elcia White found in the book * "Making Embedded Systems by Elecia White(O'Reilly). * Copyright 2012 Elecia White,978-1-449-30214-6" * * @Return Returns fifo element, returns NULL if fifo is * empty. */ const char* fifoPop(fifo *fif){ const char* ret; if(lengthOfData(fif) == 0) { return "Null"; //fifo empty } ret = fif->element[fif->read]; fif->read = (fif->read + 1) & (fif->size - 1); return ret; } } /** * Process an incomming token and add the token data to * an actor fifo. * @param Token data as a string * @return if data vas added to fifo this function returns * 1, if something went wrong it returns 0. */ rStatus CalvinMini::process(const char* token){ rStatus allOk; allOk = FAIL; allOk = fifoAdd(globalActor.inportsFifo[0],token); return allOk; } /** * Function for setting the Json reply back to Calvin-Base when the request message from * Calvin-Base is "Token" * @param msg is the JsonObject that is message from Calvin-Base * @param reply is the JsonObject with the reply message from Calvin-Arduino */ void CalvinMini::handleToken(JsonObject &msg, JsonObject &reply) { process(msg.get("token")); reply.set("cmd", "TOKEN_REPLY"); reply.set("sequencenbr", msg.get("sequencenbr")); reply.set("port_id", msg.get("port_id")); reply.set("peer_port_id", msg.get("peer_port_id")); reply.set("value", "ACK"); } /** * Method for handle the tunnel data using JSON, JSON is added to the JsonObject reference reply * @param &msg JsonObject received from Calvin-Base * @param &reply JsonObject that is added to the "reply" list * * Author: Jesper Hansen */ void CalvinMini::handleTunnelData(JsonObject &msg, JsonObject &reply, JsonObject &request) { JsonObject &value = msg.get("value"); reply.set("to_rt_uuid", msg.get("from_rt_uuid")); reply.set("from_rt_uuid", msg.get("to_rt_uuid")); reply.set("cmd", "TUNNEL_DATA"); reply.set("tunnel_id", "NULL"); // None in python #ifdef ARDUINO handleMsg(value,reply,request); #endif } void CalvinMini::handleActorNew(JsonObject &msg, JsonObject &reply) { createActor(msg); reply.set("cmd", "REPLY"); reply.set("msg_uuid", msg.get("msg_uuid")); reply.set("value", "ACK"); reply.set("from_rt_uuid", "calvin-miniscule"); reply.set("to_rt_uuid", msg.get("from_rt_uuid")); } /** * Handle all different messages * @param msg JsonObject * @param reply JsonObject * @param request JsonObject */ int8_t CalvinMini::handleMsg(JsonObject &msg, JsonObject &reply, JsonObject &request) { char replyTemp[512] = {}; char requestTemp[512] = {}; if(!strcmp(msg.get("cmd"),"JOIN_REQUEST")) { // JsonObject for replying a join request StaticJsonBuffer<200> jsonBuffer; JsonObject &policy = jsonBuffer.createObject(); handleJoin(msg,reply); handleSetupTunnel(msg, request, policy); // Print JsonObject and send to Calvin #ifdef ARDUINO Serial.println("Sending..."); reply.printTo(replyTemp,512); request.printTo(requestTemp,512); String str(replyTemp); String str2(requestTemp); addToMessageOut(str); addToMessageOut(str2); #endif return 1; } else if(!strcmp(msg.get("cmd"),"ACTOR_NEW")) { Serial.println("In ACTOR_NEW"); handleActorNew(msg, reply); return 2; } else if(!strcmp(msg.get("cmd"),"TUNNEL_DATA")) { handleTunnelData(msg, reply, request); return 3; } else if(!strcmp(msg.get("cmd"),"TOKEN")) { // reply object return 4; } else if(!strcmp(msg.get("cmd"),"TOKEN_REPLY")) { // reply array return 5; } else if(!strcmp(msg.get("cmd"),"REPLY")) { #ifdef ARDUINO JsonObject &value = msg["value"]; if(!strcmp(value.get("status"),"ACK")) { String test = value.get("status"); Serial.println(test.c_str()); } else { Serial.println("NACK"); } #endif return 6; } else { standardOut("UNKNOWN CMD"); return 7; } } #ifdef ARDUINO /** * Adds messages to a global array and * creates the array size for sending * @param reply String */ void CalvinMini::addToMessageOut(String reply) { messageOut[nextMessage] = reply; if(nextMessage < messageOutLength) nextMessage = nextMessage+1; } /** * Receive message from calvin base * @return String */ String CalvinMini::recvMsg() { Serial.println("Reading..."); char temp[MAX_LENGTH+1] = {}; String str = ""; byte data[4]; int found = 0; int count = 0; int sizeOfMsg; while(!found) { client.readBytes(temp, MAX_LENGTH); data[count] = *temp; count++; if(*temp == '{') { str += temp; found = 1; } } sizeOfMsg = (data[0] << 24) | (data[1] << 16) | (data[2] << 8) | data[3]; for(int i = 0;i < sizeOfMsg-1;i++) { int size = client.readBytes(temp, MAX_LENGTH); temp[size] = '\0'; // Null terminate char str += temp; } Serial.println(temp); return str; } /** * Reply message to calvin base * @param str char pointer of String * @param length size of String */ void CalvinMini::sendMsg(const char *str, size_t length) { byte binary[4] = {}; binary[0] = (length & 0xFF000000); binary[1] = (length & 0x00FF0000); binary[2] = (length & 0x0000FF00); binary[3] = (length & 0x000000FF); for(int i = 0; i< 4;i++) { server.write(binary[i]); } server.write(str); } #endif /** * Create a reply message * @param msg JsonObject * @param reply JsonObject */ void CalvinMini::handleJoin(JsonObject &msg, JsonObject &reply) { reply["cmd"] = "JOIN_REPLY"; reply["id"] = "calvin-miniscule"; reply["sid"] = msg.get("sid"); reply["serializer"] = "json"; } /** * Method for setting up a tunnel using JSON message back to Calvin-Base, * JSON is added to the JsonObject request that is added to the reply list. * @param &msg JsonObject received from Calvin-Base * @param &request JsonObject that is added to the "reply" list * @param &policy JsonObject that is an empty JsonObject */ void CalvinMini::handleSetupTunnel(JsonObject &msg, JsonObject &request, JsonObject &policy) { request["msg_uuid"] = "MSG-00531ac3-1d2d-454d-964a-7e9573f6ebb6"; // Should be a unique id request["from_rt_uuid"] = "calvin-miniscule"; request["to_rt_uuid"] = msg.get("id"); request["cmd"] = "TUNNEL_NEW"; request["tunnel_id"] = "fake-tunnel"; request["policy"] = policy; // Unused request["type"] = "token"; } #ifdef ARDUINO /** * Start a server connection */ void CalvinMini::setupServer() { //getIPFromRouter(); // Doesn't work with shield Ethernet.begin(mac, ip); printIp(); server.begin(); } /** * Prints the IP-address assigned to the Ethernet shield. */ void CalvinMini::printIp() { Serial.println(Ethernet.localIP()); } /** * Assign an IP-address to the Ethernet shield. */ void CalvinMini::getIPFromRouter() { // Disable SD pinMode(4,OUTPUT); digitalWrite(4,HIGH); if (Ethernet.begin(mac) == 0) { Serial.println("Failed to configure Ethernet using DHCP"); // Set static IP-address if fail Ethernet.begin(mac, ip); } } /** * Serializes a String to Json syntax. * From this: {"sensor":"gps","time":1351824120} * To this: {\"sensor\":\"gps\",\"time\":1351824120} * @param str char* pointer * @return char* pointer */ char* CalvinMini::jsonSerialize(const char *str) { const char *json = str; char *temp = new char[256]; int counter = 0; for(int i = 0; json[i] != '\0'; i++) { if(json[i] == '\"') { temp[counter] = '\\'; counter++; } temp[counter] = json[i]; counter++; } temp[counter] = '\0'; return temp; } void CalvinMini::loop() { setupServer(); while(1) { // 1: Kontrollera anslutna sockets client = server.available(); // 2: Fixa koppling if(client) // Wait for client { // 3: Läs av meddelande Serial.println("Connected..."); String str = recvMsg(); StaticJsonBuffer<4096> jsonBuffer; JsonObject &msg = jsonBuffer.parseObject(str.c_str()); msg.printTo(Serial); JsonObject &reply = jsonBuffer.createObject(); JsonObject &request = jsonBuffer.createObject(); // 4: Hantera meddelande handleMsg(msg, reply, request); // 5: Fire Actors // 6: Läs av utlistan for(int i = 0;i < nextMessage;i++) { // 7: Skicka utmeddelande sendMsg(messageOut[i].c_str(),messageOut[i].length()); messageOut[i] = ""; } nextMessage = 0; } } } #endif <commit_msg>Removed a serial print<commit_after>/* * This is the Calvin mini library for Arduino due * *Created on: 5 okt. 2015 * */ #include <stdio.h> #include "CalvinMini.h" #include <inttypes.h> #ifdef ARDUINO #include <SPI.h> #include <Ethernet.h> #include <util.h> //byte mac[] = { 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 }; byte mac[] = { 0x90, 0xA2, 0xDA, 0x0E, 0xF5, 0x93 }; IPAddress ip(192,168,0,5); //IPAddress ip(192,168,1,146); uint16_t slaveport = 5002; EthernetServer server(slaveport); EthernetClient client; const int messageOutLength = 4; String messageOut[messageOutLength] = {}; int nextMessage = 0; #endif actor globalActor; fifo actorFifo; /** * Current standard out is the lcd screen connected to arduino due */ int8_t StdOut(){ uint8_t inFifo; const char* token; token = "null"; inFifo = lengthOfData(globalActor.inportsFifo[0]); if(inFifo > 0) { token = fifoPop(globalActor.inportsFifo[0]); } return standardOut(token); } /** * What's up with the external C you might wonder, * well thats the only way i could ad a function pointer to a strut, * Apparently c++ handles this different from c. */ extern "C"{ rStatus actorInit(){ rStatus allOk = FAIL; globalActor.fireActor = &StdOut; /*This sets up the fifo for the actor, not sure *if it should be done here but for now it works*/ allOk = initFifo(&actorFifo); globalActor.inportsFifo[0] = &actorFifo; return allOk; } } /** * Create an new actor. * @param msg json list * @return return 1 if successful. */ rStatus CalvinMini::createActor(JsonObject &msg){ rStatus allOk = FAIL; JsonObject &state = msg.get("state"); JsonObject &name = state.get("actor_state"); globalActor.type = state.get("actor_type"); globalActor.name = name.get("name"); globalActor.id = name.get("id"); allOk = SUCCESS; actorInit(); return allOk; } extern "C"{ /** * This Function initiate the fifo must be * called prior to using the fifo. * * This fifo implementation is based upon a circular * buffert written by Elcia White found in the book * "Making Embedded Systems by Elecia White(O'Reilly). * * Copyright 2012 Elecia White,978-1-449-30214-6" */ rStatus initFifo(fifo *fif) { fif->size = FIFO_SIZE; fif->read = 0; fif->write = 0; return SUCCESS; } /** * Used by Add and Pop to determine fifo length. * * This fifo implementation is based upon a circular * buffert written by Elcia White found in the book * "Making Embedded Systems by Elecia White(O'Reilly). * Copyright 2012 Elecia White,978-1-449-30214-6" * * @return Fifo length */ int8_t lengthOfData(fifo *fif) { return ((fif->write - fif->read) & (fif->size -1)); } /** * Adds a new element to the fifo * * This fifo implementation is based upon a circular * buffert written by Elcia White found in the book * "Making Embedded Systems by Elecia White(O'Reilly). * * Copyright 2012 Elecia White,978-1-449-30214-6" * @return returns 0 if the fifo is full */ rStatus fifoAdd(fifo *fif, const char* element){ if(lengthOfData(fif) == (fif->size-1)) { return FAIL; //fifo full; } fif->element[fif->write] = element; fif->write = (fif->write + 1) & (fif->size - 1); return SUCCESS; //all is well } /** * Return and removes the oldest element in the fifo. * * This fifo implementation is based upon a circular * buffert written by Elcia White found in the book * "Making Embedded Systems by Elecia White(O'Reilly). * Copyright 2012 Elecia White,978-1-449-30214-6" * * @Return Returns fifo element, returns NULL if fifo is * empty. */ const char* fifoPop(fifo *fif){ const char* ret; if(lengthOfData(fif) == 0) { return "Null"; //fifo empty } ret = fif->element[fif->read]; fif->read = (fif->read + 1) & (fif->size - 1); return ret; } } /** * Process an incomming token and add the token data to * an actor fifo. * @param Token data as a string * @return if data vas added to fifo this function returns * 1, if something went wrong it returns 0. */ rStatus CalvinMini::process(const char* token){ rStatus allOk; allOk = FAIL; allOk = fifoAdd(globalActor.inportsFifo[0],token); return allOk; } /** * Function for setting the Json reply back to Calvin-Base when the request message from * Calvin-Base is "Token" * @param msg is the JsonObject that is message from Calvin-Base * @param reply is the JsonObject with the reply message from Calvin-Arduino */ void CalvinMini::handleToken(JsonObject &msg, JsonObject &reply) { process(msg.get("token")); reply.set("cmd", "TOKEN_REPLY"); reply.set("sequencenbr", msg.get("sequencenbr")); reply.set("port_id", msg.get("port_id")); reply.set("peer_port_id", msg.get("peer_port_id")); reply.set("value", "ACK"); } /** * Method for handle the tunnel data using JSON, JSON is added to the JsonObject reference reply * @param &msg JsonObject received from Calvin-Base * @param &reply JsonObject that is added to the "reply" list * * Author: Jesper Hansen */ void CalvinMini::handleTunnelData(JsonObject &msg, JsonObject &reply, JsonObject &request) { JsonObject &value = msg.get("value"); reply.set("to_rt_uuid", msg.get("from_rt_uuid")); reply.set("from_rt_uuid", msg.get("to_rt_uuid")); reply.set("cmd", "TUNNEL_DATA"); reply.set("tunnel_id", "NULL"); // None in python #ifdef ARDUINO handleMsg(value,reply,request); #endif } void CalvinMini::handleActorNew(JsonObject &msg, JsonObject &reply) { createActor(msg); reply.set("cmd", "REPLY"); reply.set("msg_uuid", msg.get("msg_uuid")); reply.set("value", "ACK"); reply.set("from_rt_uuid", "calvin-miniscule"); reply.set("to_rt_uuid", msg.get("from_rt_uuid")); } /** * Handle all different messages * @param msg JsonObject * @param reply JsonObject * @param request JsonObject */ int8_t CalvinMini::handleMsg(JsonObject &msg, JsonObject &reply, JsonObject &request) { char replyTemp[512] = {}; char requestTemp[512] = {}; if(!strcmp(msg.get("cmd"),"JOIN_REQUEST")) { // JsonObject for replying a join request StaticJsonBuffer<200> jsonBuffer; JsonObject &policy = jsonBuffer.createObject(); handleJoin(msg,reply); handleSetupTunnel(msg, request, policy); // Print JsonObject and send to Calvin #ifdef ARDUINO Serial.println("Sending..."); reply.printTo(replyTemp,512); request.printTo(requestTemp,512); String str(replyTemp); String str2(requestTemp); addToMessageOut(str); addToMessageOut(str2); #endif return 1; } else if(!strcmp(msg.get("cmd"),"ACTOR_NEW")) { handleActorNew(msg, reply); return 2; } else if(!strcmp(msg.get("cmd"),"TUNNEL_DATA")) { handleTunnelData(msg, reply, request); return 3; } else if(!strcmp(msg.get("cmd"),"TOKEN")) { // reply object return 4; } else if(!strcmp(msg.get("cmd"),"TOKEN_REPLY")) { // reply array return 5; } else if(!strcmp(msg.get("cmd"),"REPLY")) { #ifdef ARDUINO JsonObject &value = msg["value"]; if(!strcmp(value.get("status"),"ACK")) { String test = value.get("status"); Serial.println(test.c_str()); } else { Serial.println("NACK"); } #endif return 6; } else { standardOut("UNKNOWN CMD"); return 7; } } #ifdef ARDUINO /** * Adds messages to a global array and * creates the array size for sending * @param reply String */ void CalvinMini::addToMessageOut(String reply) { messageOut[nextMessage] = reply; if(nextMessage < messageOutLength) nextMessage = nextMessage+1; } /** * Receive message from calvin base * @return String */ String CalvinMini::recvMsg() { Serial.println("Reading..."); char temp[MAX_LENGTH+1] = {}; String str = ""; byte data[4]; int found = 0; int count = 0; int sizeOfMsg; while(!found) { client.readBytes(temp, MAX_LENGTH); data[count] = *temp; count++; if(*temp == '{') { str += temp; found = 1; } } sizeOfMsg = (data[0] << 24) | (data[1] << 16) | (data[2] << 8) | data[3]; for(int i = 0;i < sizeOfMsg-1;i++) { int size = client.readBytes(temp, MAX_LENGTH); temp[size] = '\0'; // Null terminate char str += temp; } Serial.println(temp); return str; } /** * Reply message to calvin base * @param str char pointer of String * @param length size of String */ void CalvinMini::sendMsg(const char *str, size_t length) { byte binary[4] = {}; binary[0] = (length & 0xFF000000); binary[1] = (length & 0x00FF0000); binary[2] = (length & 0x0000FF00); binary[3] = (length & 0x000000FF); for(int i = 0; i< 4;i++) { server.write(binary[i]); } server.write(str); } #endif /** * Create a reply message * @param msg JsonObject * @param reply JsonObject */ void CalvinMini::handleJoin(JsonObject &msg, JsonObject &reply) { reply["cmd"] = "JOIN_REPLY"; reply["id"] = "calvin-miniscule"; reply["sid"] = msg.get("sid"); reply["serializer"] = "json"; } /** * Method for setting up a tunnel using JSON message back to Calvin-Base, * JSON is added to the JsonObject request that is added to the reply list. * @param &msg JsonObject received from Calvin-Base * @param &request JsonObject that is added to the "reply" list * @param &policy JsonObject that is an empty JsonObject */ void CalvinMini::handleSetupTunnel(JsonObject &msg, JsonObject &request, JsonObject &policy) { request["msg_uuid"] = "MSG-00531ac3-1d2d-454d-964a-7e9573f6ebb6"; // Should be a unique id request["from_rt_uuid"] = "calvin-miniscule"; request["to_rt_uuid"] = msg.get("id"); request["cmd"] = "TUNNEL_NEW"; request["tunnel_id"] = "fake-tunnel"; request["policy"] = policy; // Unused request["type"] = "token"; } #ifdef ARDUINO /** * Start a server connection */ void CalvinMini::setupServer() { //getIPFromRouter(); // Doesn't work with shield Ethernet.begin(mac, ip); printIp(); server.begin(); } /** * Prints the IP-address assigned to the Ethernet shield. */ void CalvinMini::printIp() { Serial.println(Ethernet.localIP()); } /** * Assign an IP-address to the Ethernet shield. */ void CalvinMini::getIPFromRouter() { // Disable SD pinMode(4,OUTPUT); digitalWrite(4,HIGH); if (Ethernet.begin(mac) == 0) { Serial.println("Failed to configure Ethernet using DHCP"); // Set static IP-address if fail Ethernet.begin(mac, ip); } } /** * Serializes a String to Json syntax. * From this: {"sensor":"gps","time":1351824120} * To this: {\"sensor\":\"gps\",\"time\":1351824120} * @param str char* pointer * @return char* pointer */ char* CalvinMini::jsonSerialize(const char *str) { const char *json = str; char *temp = new char[256]; int counter = 0; for(int i = 0; json[i] != '\0'; i++) { if(json[i] == '\"') { temp[counter] = '\\'; counter++; } temp[counter] = json[i]; counter++; } temp[counter] = '\0'; return temp; } void CalvinMini::loop() { setupServer(); while(1) { // 1: Kontrollera anslutna sockets client = server.available(); // 2: Fixa koppling if(client) // Wait for client { // 3: Läs av meddelande Serial.println("Connected..."); String str = recvMsg(); StaticJsonBuffer<4096> jsonBuffer; JsonObject &msg = jsonBuffer.parseObject(str.c_str()); msg.printTo(Serial); JsonObject &reply = jsonBuffer.createObject(); JsonObject &request = jsonBuffer.createObject(); // 4: Hantera meddelande handleMsg(msg, reply, request); // 5: Fire Actors // 6: Läs av utlistan for(int i = 0;i < nextMessage;i++) { // 7: Skicka utmeddelande sendMsg(messageOut[i].c_str(),messageOut[i].length()); messageOut[i] = ""; } nextMessage = 0; } } } #endif <|endoftext|>
<commit_before>#include <cstdlib> #include <cassert> #include "api-loader.h" #include "pointers.h" #include <string> //here direct pointers are kept (pointers to entrypoints exposed by underlying OpenGL32 implementation //use DIRECT_CALL(name) to call one of these pointers void* g_DirectPointers[Entrypoints_NUM]; HINSTANCE openGLLibraryHandle; void * LoadOpenGLPointer(char* name) { return GetProcAddress(openGLLibraryHandle, name); } void* LoadOpenGLExtPointer(Entrypoint entryp) { return g_DirectPointers[entryp] = DIRECT_CALL(wglGetProcAddress)(GetEntryPointName(entryp)); } #define FUNCTION_LIST_ELEMENT(name, type) POINTER(name) = LoadOpenGLPointer(#name); void LoadOpenGLPointers () { #include "../../dump/codegen/functionList.inl" } #undef FUNCTION_LIST_ELEMENT void LoadOpenGLLibrary() { openGLLibraryHandle = LoadLibrary("C:\\Windows\\SysWOW64\\opengl32.dll"); if (!openGLLibraryHandle) { openGLLibraryHandle = LoadLibrary("C:\\Windows\\System32\\opengl32.dll"); } assert(openGLLibraryHandle); if (!openGLLibraryHandle) { MessageBox(0, "Cannot load library", "Cannot Load library OpenGL32.dll", MB_OK | MB_ICONSTOP); exit(EXIT_FAILURE); } LoadOpenGLPointers(); } void* EnsurePointer(Entrypoint entryp) { if (g_DirectPointers[entryp] || LoadOpenGLExtPointer(entryp)) { return g_DirectPointers[entryp]; } else { std::string error = "Operation aborted, because the "; error += GetEntryPointName(entryp); error += " function is not available on current context. Try updating GPU drivers."; throw std::runtime_error(error); } } <commit_msg>Fixed bug: wglGetProcAddress() called by application on core entrypoint.<commit_after>#include <cstdlib> #include <cassert> #include "api-loader.h" #include "pointers.h" #include <string> //here direct pointers are kept (pointers to entrypoints exposed by underlying OpenGL32 implementation //use DIRECT_CALL(name) to call one of these pointers void* g_DirectPointers[Entrypoints_NUM]; HINSTANCE openGLLibraryHandle; void * LoadOpenGLPointer(char* name) { return GetProcAddress(openGLLibraryHandle, name); } void* LoadOpenGLExtPointer(Entrypoint entryp) { if (!g_DirectPointers[entryp]) { return g_DirectPointers[entryp] = DIRECT_CALL(wglGetProcAddress)(GetEntryPointName(entryp)); } else { return g_DirectPointers[entryp]; } } #define FUNCTION_LIST_ELEMENT(name, type) POINTER(name) = LoadOpenGLPointer(#name); void LoadOpenGLPointers () { #include "../../dump/codegen/functionList.inl" } #undef FUNCTION_LIST_ELEMENT void LoadOpenGLLibrary() { openGLLibraryHandle = LoadLibrary("C:\\Windows\\SysWOW64\\opengl32.dll"); if (!openGLLibraryHandle) { openGLLibraryHandle = LoadLibrary("C:\\Windows\\System32\\opengl32.dll"); } assert(openGLLibraryHandle); if (!openGLLibraryHandle) { MessageBox(0, "Cannot load library", "Cannot Load library OpenGL32.dll", MB_OK | MB_ICONSTOP); exit(EXIT_FAILURE); } LoadOpenGLPointers(); } void* EnsurePointer(Entrypoint entryp) { if (g_DirectPointers[entryp] || LoadOpenGLExtPointer(entryp)) { return g_DirectPointers[entryp]; } else { std::string error = "Operation aborted, because the "; error += GetEntryPointName(entryp); error += " function is not available on current context. Try updating GPU drivers."; throw std::runtime_error(error); } } <|endoftext|>
<commit_before>/*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 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 3 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. ========================================================================== SeqCons -- Read alignment via realignment or MSA. ========================================================================== Author: Tobias Rausch <[email protected]> ========================================================================== */ #include <seqan/basic.h> #include <seqan/consensus.h> #include <seqan/modifier.h> #include <iostream> #include <fstream> #include <seqan/arg_parse.h> using namespace seqan; void _setVersion(ArgumentParser & parser) { ::std::string rev = "$Revision: 4663 $"; setVersion(parser, "0.23.1 Revision: " + rev.substr(11, 4) + ""); setDate(parser, "Nov 21, 2012"); } seqan::ArgumentParser::ParseResult parseCommandLine(ConsensusOptions & consOpt, int argc, const char * argv[]) { // Setup ArgumentParser. seqan::ArgumentParser parser("seqcons"); _setVersion(parser); setShortDescription(parser, "Multi-read alignment."); addDescription(parser, "(c) Copyright 2009 by Tobias Rausch"); setCategory(parser, "Sequence Alignment"); addUsageLine(parser, "-r <FASTA file with reads> [Options]"); addUsageLine(parser, "-a <AMOS message file> [Options]"); addUsageLine(parser, "-s <Sam file> [-c <FASTA contigs file>] [Options]"); addSection(parser, "Main Options:"); addOption(parser, ArgParseOption("r", "reads", "file with reads", ArgParseArgument::INPUTFILE, "<FASTA reads file>")); setValidValues(parser, "reads", "fa fasta"); addOption(parser, ArgParseOption("a", "afg", "message file", ArgParseArgument::INPUTFILE, "<AMOS afg file>")); setValidValues(parser, "afg", "afg"); addOption(parser, ArgParseOption("s", "sam", "Sam file", ArgParseArgument::INPUTFILE, "<Sam file>")); setValidValues(parser, "s", "sam"); addOption(parser, ArgParseOption("c", "contigs", "FASTA file with contigs, ignored if not Sam input", ArgParseArgument::INPUTFILE, "<FASTA contigs file>")); setValidValues(parser, "contigs", "fa fasta"); addOption(parser, ArgParseOption("o", "outfile", "output filename", ArgParseArgument::OUTPUTFILE, "<Filename>")); setValidValues(parser, "outfile", "afg seqan cgb sam"); setDefaultValue(parser, "outfile", "align.sam"); addOption(parser, ArgParseOption("m", "method", "alignment method", ArgParseArgument::STRING, "realign", "[realign | msa]")); setDefaultValue(parser, "method", "realign"); addOption(parser, ArgParseOption("b", "bandwidth", "bandwidth", ArgParseArgument::INTEGER, "<Int>")); setDefaultValue(parser, "bandwidth", "8"); addOption(parser, ArgParseOption("n", "noalign", "no align, only convert input", ArgParseArgument::INTEGER, "<Bool>")); setDefaultValue(parser, "noalign", "0"); addOption(parser, ArgParseOption("ma", "matchlength", "min. overlap length", ArgParseArgument::INTEGER, "<Int>")); setDefaultValue(parser, "matchlength", "15"); addOption(parser, ArgParseOption("qu", "quality", "min. overlap precent identity", ArgParseArgument::INTEGER, "<Int>")); setDefaultValue(parser, "quality", "80"); addOption(parser, ArgParseOption("ov", "overlaps", "min. number of overlaps per read", ArgParseArgument::INTEGER, "<Int>")); setDefaultValue(parser, "overlaps", "3"); addOption(parser, ArgParseOption("wi", "window", "The window size. If this parameter is greater than 0 then all overlaps within a given window are computed.", ArgParseArgument::INTEGER,"<Int>")); setDefaultValue(parser, "window", "0"); addSection(parser, "ReAlign Method Options:"); addOption(parser, ArgParseOption("in", "include", "include contig sequence", ArgParseArgument::INTEGER, "<Bool>")); setDefaultValue(parser, "include", "0"); addOption(parser, ArgParseOption("rm", "rmethod", "realign method", ArgParseArgument::STRING, "[nw | gotoh]")); setDefaultValue(parser, "rmethod", "gotoh"); // Parse command line. seqan::ArgumentParser::ParseResult res = seqan::parse(parser, argc, argv); // If parsing was not successful then exit with code 1 if there were errors. // Otherwise, exit with code 0 (e.g. help was printed). if (res != seqan::ArgumentParser::PARSE_OK) return res; // Main options getOptionValue(consOpt.readsfile, parser, "reads"); getOptionValue(consOpt.afgfile, parser, "afg"); getOptionValue(consOpt.samfile, parser, "sam"); getOptionValue(consOpt.contigsfile, parser, "contigs"); getOptionValue(consOpt.outfile, parser, "outfile"); if (empty(consOpt.samfile) && !empty(consOpt.contigsfile)) std::cerr << "WARNING: Contigs specified by input is not FASTA, ignoring --contigs parameters." << std::endl; // Get lower case of the output file name. File endings are accepted in both upper and lower case. CharString tmp = consOpt.outfile; toLower(tmp); if (endsWith(tmp, ".seqan")) consOpt.output = 0; else if (endsWith(tmp, ".afg")) consOpt.output = 1; else if (endsWith(tmp, ".frg")) consOpt.output = 2; else if (endsWith(tmp, ".cgb")) consOpt.output = 3; else if (endsWith(tmp, ".sam")) consOpt.output = 4; String<char> optionVal; getOptionValue(optionVal, parser, "method"); if (optionVal == "realign") consOpt.method = 0; else if (optionVal == "msa") consOpt.method = 1; getOptionValue(consOpt.bandwidth, parser, "bandwidth"); #ifdef CELERA_OFFSET if (!isSetLong(parser, "bandwidth")) consOpt.bandwidth = 15; #endif getOptionValue(consOpt.noalign, parser, "noalign"); // MSA options getOptionValue(consOpt.matchlength, parser, "matchlength"); getOptionValue(consOpt.quality, parser, "quality"); getOptionValue(consOpt.overlaps, parser, "overlaps"); #ifdef CELERA_OFFSET if (!isSetLong(parser, "overlaps")) consOpt.overlaps = 5; #endif getOptionValue(consOpt.window, parser, "window"); // ReAlign options getOptionValue(consOpt.include, parser, "include"); getOptionValue(optionVal, parser, "rmethod"); if (optionVal == "nw") consOpt.rmethod = 0; else if (optionVal == "gotoh") consOpt.rmethod = 1; return seqan::ArgumentParser::PARSE_OK; } // Load the reads and layout positions template <typename TFragmentStore, typename TSize> int loadFiles(TFragmentStore & fragStore, TSize & numberOfContigs, ConsensusOptions const & consOpt) { //IOREV std::cerr << "Reading input..." << std::endl; if (!empty(consOpt.readsfile)) { // Load simple read file std::fstream strmReads(consOpt.readsfile.c_str(), std::fstream::in | std::fstream::binary); bool moveToFront = false; if (consOpt.noalign) moveToFront = true; if (_convertSimpleReadFile(strmReads, fragStore, consOpt.readsfile, moveToFront) != 0) return 1; numberOfContigs = 1; } else if (!empty(consOpt.afgfile)) { // Load Amos message file std::fstream strmReads(consOpt.afgfile.c_str(), std::fstream::in | std::fstream::binary); read(strmReads, fragStore, Amos()); numberOfContigs = length(fragStore.contigStore); } else if (!empty(consOpt.samfile)) { // Possibly load contigs into fragment store. if (!empty(consOpt.contigsfile)) { if (!loadContigs(fragStore, consOpt.contigsfile.c_str())) { std::cerr << "Could not load contigs file " << consOpt.contigsfile.c_str() << std::endl; return 1; } } // Load Sam message file std::fstream strmReads(consOpt.samfile.c_str(), std::fstream::in | std::fstream::binary); read(strmReads, fragStore, Sam()); numberOfContigs = length(fragStore.contigStore); } else { return 1; } return 0; } // Write resulting alignment. template <typename TFragmentStore> int writeOutput(TFragmentStore /*const*/ & fragStore, ConsensusOptions const & consOpt) { //IOREV std::cerr << "Writing output..." << std::endl; if (consOpt.output == 0) { // Write old SeqAn multi-read alignment format FILE* strmWrite = fopen(consOpt.outfile.c_str(), "w"); write(strmWrite, fragStore, FastaReadFormat()); fclose(strmWrite); } else if (consOpt.output == 1) { // Write Amos FILE* strmWrite = fopen(consOpt.outfile.c_str(), "w"); write(strmWrite, fragStore, Amos()); fclose(strmWrite); } else if (consOpt.output == 2) { FILE* strmWrite = fopen(consOpt.outfile.c_str(), "w"); _writeCeleraFrg(strmWrite, fragStore); fclose(strmWrite); } else if (consOpt.output == 3) { FILE* strmWrite = fopen(consOpt.outfile.c_str(), "w"); _writeCeleraCgb(strmWrite, fragStore); fclose(strmWrite); } else if (consOpt.output == 4) { // Write out resulting MSA in a Sam file. FILE* strmWrite = fopen(consOpt.outfile.c_str(), "w"); write(strmWrite, fragStore, Sam()); fclose(strmWrite); // Write out resulting consensus sequence. char buffer[10*1024]; buffer[0] = '\0'; strcat(buffer, consOpt.outfile.c_str()); strcat(buffer, ".consensus.fasta"); strmWrite = fopen(buffer, "w"); writeContigs(strmWrite, fragStore, Fasta()); fclose(strmWrite); } return 0; } int main(int argc, const char *argv[]) { // Command line parsing ArgumentParser parser; ConsensusOptions consOpt; seqan::ArgumentParser::ParseResult res = parseCommandLine(consOpt, argc, argv); if (res != seqan::ArgumentParser::PARSE_OK) return res == seqan::ArgumentParser::PARSE_ERROR; // Create a new fragment store typedef FragmentStore<> TFragmentStore; typedef Size<TFragmentStore>::Type TSize; TFragmentStore fragStore; // Load the reads and layout positions TSize numberOfContigs = 0; int ret = loadFiles(fragStore, numberOfContigs, consOpt); // Multi-realignment desired or just conversion of the input if (!consOpt.noalign) { // Iterate over all contigs if (consOpt.method == 0) std::cerr << "Performing realignment..." << std::endl; else std::cerr << "Performing consensus alignment..." << std::endl; for (TSize currentContig = 0; currentContig < numberOfContigs; ++currentContig) { std::cerr << "contig " << (currentContig + 1) << "/" << numberOfContigs << std::endl; if (consOpt.method == 0) { Score<int, WeightedConsensusScore<Score<int, FractionalScore>, Score<int, ConsensusScore> > > combinedScore; reAlign(fragStore, combinedScore, currentContig, consOpt.rmethod, consOpt.bandwidth, consOpt.include); if (consOpt.include) reAlign(fragStore, combinedScore, currentContig, consOpt.rmethod, consOpt.bandwidth, false); } else { std::cerr << "Performing consensus alignment..." << std::endl; // Import all reads of the given contig typedef TFragmentStore::TReadSeq TReadSeq; StringSet<TReadSeq, Owner<> > readSet; String<Pair<TSize, TSize> > begEndPos; _loadContigReads(readSet, begEndPos, fragStore, currentContig); if (!length(readSet)) continue; // Align the reads typedef StringSet<TReadSeq, Dependent<> > TStringSet; typedef Graph<Alignment<TStringSet, void, WithoutEdgeId> > TAlignGraph; TAlignGraph gOut(readSet); consensusAlignment(gOut, begEndPos, consOpt); // Update the contig in the fragment store if (!empty(gOut)) updateContig(fragStore, gOut, currentContig); clear(gOut); //// Debug code for CA //mtRandInit(); //String<char> fileTmp1 = "tmp1"; //String<char> fileTmp2 = "tmp2"; //for(int i = 0; i<10; ++i) { // int file = (mtRand() % 20) + 65; // appendValue(fileTmp1, char(file)); // appendValue(fileTmp2, char(file)); //} //std::fstream strm3; //strm3.open(toCString(fileTmp2), std::ios_base::out | std::ios_base::trunc); //for(int i = 0;i<(int) length(origStrSet); ++i) { // std::stringstream name; // name << value(begEndPos, i).i1 << "," << value(begEndPos, i).i2; // String<char> myTitle = name.str(); // write(strm3, origStrSet[i], myTitle, Fasta()); // if (value(begEndPos, i).i1 > value(begEndPos, i).i2) reverseComplement(origStrSet[i]); //} //strm3.close(); } } // end loop over all contigs } // Write result. ret = writeOutput(fragStore, consOpt); return ret; } <commit_msg>[CLI] Fixing CLI arguments with seqcons.<commit_after>/*========================================================================== SeqAn - The Library for Sequence Analysis http://www.seqan.de ============================================================================ Copyright (C) 2007 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 3 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. ========================================================================== SeqCons -- Read alignment via realignment or MSA. ========================================================================== Author: Tobias Rausch <[email protected]> ========================================================================== */ #include <seqan/basic.h> #include <seqan/consensus.h> #include <seqan/modifier.h> #include <iostream> #include <fstream> #include <seqan/arg_parse.h> using namespace seqan; void _setVersion(ArgumentParser & parser) { ::std::string rev = "$Revision: 4663 $"; setVersion(parser, "0.23.1 Revision: " + rev.substr(11, 4) + ""); setDate(parser, "Nov 21, 2012"); } seqan::ArgumentParser::ParseResult parseCommandLine(ConsensusOptions & consOpt, int argc, const char * argv[]) { // Setup ArgumentParser. seqan::ArgumentParser parser("seqcons"); _setVersion(parser); setShortDescription(parser, "Multi-read alignment."); addDescription(parser, "(c) Copyright 2009 by Tobias Rausch"); setCategory(parser, "Sequence Alignment"); addUsageLine(parser, "-r <FASTA file with reads> [Options]"); addUsageLine(parser, "-a <AMOS message file> [Options]"); addUsageLine(parser, "-s <Sam file> [-c <FASTA contigs file>] [Options]"); addSection(parser, "Main Options:"); addOption(parser, ArgParseOption("r", "reads", "file with reads", ArgParseArgument::INPUTFILE, "<FASTA reads file>")); setValidValues(parser, "reads", "fa fasta"); addOption(parser, ArgParseOption("a", "afg", "message file", ArgParseArgument::INPUTFILE, "<AMOS afg file>")); setValidValues(parser, "afg", "afg"); addOption(parser, ArgParseOption("s", "sam", "Sam file", ArgParseArgument::INPUTFILE, "<Sam file>")); setValidValues(parser, "s", "sam"); addOption(parser, ArgParseOption("c", "contigs", "FASTA file with contigs, ignored if not Sam input", ArgParseArgument::INPUTFILE, "<FASTA contigs file>")); setValidValues(parser, "contigs", "fa fasta"); addOption(parser, ArgParseOption("o", "outfile", "output filename", ArgParseArgument::OUTPUTFILE, "<Filename>")); setValidValues(parser, "outfile", "afg seqan cgb sam"); setDefaultValue(parser, "outfile", "align.sam"); addOption(parser, ArgParseOption("m", "method", "alignment method", ArgParseArgument::STRING, "realign", "[realign | msa]")); setDefaultValue(parser, "method", "realign"); addOption(parser, ArgParseOption("b", "bandwidth", "bandwidth", ArgParseArgument::INTEGER, "<Int>")); setDefaultValue(parser, "bandwidth", "8"); addOption(parser, ArgParseOption("n", "noalign", "no align, only convert input")); addOption(parser, ArgParseOption("ma", "matchlength", "min. overlap length", ArgParseArgument::INTEGER, "<Int>")); setDefaultValue(parser, "matchlength", "15"); addOption(parser, ArgParseOption("qu", "quality", "min. overlap precent identity", ArgParseArgument::INTEGER, "<Int>")); setDefaultValue(parser, "quality", "80"); addOption(parser, ArgParseOption("ov", "overlaps", "min. number of overlaps per read", ArgParseArgument::INTEGER, "<Int>")); setDefaultValue(parser, "overlaps", "3"); addOption(parser, ArgParseOption("wi", "window", "The window size. If this parameter is greater than 0 then all overlaps within a given window are computed.", ArgParseArgument::INTEGER,"<Int>")); setDefaultValue(parser, "window", "0"); addSection(parser, "ReAlign Method Options:"); addOption(parser, ArgParseOption("in", "include", "include contig sequence")); addOption(parser, ArgParseOption("rm", "rmethod", "realign method", ArgParseArgument::STRING, "[nw | gotoh]")); setDefaultValue(parser, "rmethod", "gotoh"); // Parse command line. seqan::ArgumentParser::ParseResult res = seqan::parse(parser, argc, argv); // If parsing was not successful then exit with code 1 if there were errors. // Otherwise, exit with code 0 (e.g. help was printed). if (res != seqan::ArgumentParser::PARSE_OK) return res; // Main options getOptionValue(consOpt.readsfile, parser, "reads"); getOptionValue(consOpt.afgfile, parser, "afg"); getOptionValue(consOpt.samfile, parser, "sam"); getOptionValue(consOpt.contigsfile, parser, "contigs"); getOptionValue(consOpt.outfile, parser, "outfile"); if (empty(consOpt.samfile) && !empty(consOpt.contigsfile)) std::cerr << "WARNING: Contigs specified by input is not FASTA, ignoring --contigs parameters." << std::endl; // Get lower case of the output file name. File endings are accepted in both upper and lower case. CharString tmp = consOpt.outfile; toLower(tmp); if (endsWith(tmp, ".seqan")) consOpt.output = 0; else if (endsWith(tmp, ".afg")) consOpt.output = 1; else if (endsWith(tmp, ".frg")) consOpt.output = 2; else if (endsWith(tmp, ".cgb")) consOpt.output = 3; else if (endsWith(tmp, ".sam")) consOpt.output = 4; String<char> optionVal; getOptionValue(optionVal, parser, "method"); if (optionVal == "realign") consOpt.method = 0; else if (optionVal == "msa") consOpt.method = 1; getOptionValue(consOpt.bandwidth, parser, "bandwidth"); #ifdef CELERA_OFFSET if (!isSetLong(parser, "bandwidth")) consOpt.bandwidth = 15; #endif getOptionValue(consOpt.noalign, parser, "noalign"); // MSA options getOptionValue(consOpt.matchlength, parser, "matchlength"); getOptionValue(consOpt.quality, parser, "quality"); getOptionValue(consOpt.overlaps, parser, "overlaps"); #ifdef CELERA_OFFSET if (!isSetLong(parser, "overlaps")) consOpt.overlaps = 5; #endif getOptionValue(consOpt.window, parser, "window"); // ReAlign options getOptionValue(consOpt.include, parser, "include"); getOptionValue(optionVal, parser, "rmethod"); if (optionVal == "nw") consOpt.rmethod = 0; else if (optionVal == "gotoh") consOpt.rmethod = 1; return seqan::ArgumentParser::PARSE_OK; } // Load the reads and layout positions template <typename TFragmentStore, typename TSize> int loadFiles(TFragmentStore & fragStore, TSize & numberOfContigs, ConsensusOptions const & consOpt) { //IOREV std::cerr << "Reading input..." << std::endl; if (!empty(consOpt.readsfile)) { // Load simple read file std::fstream strmReads(consOpt.readsfile.c_str(), std::fstream::in | std::fstream::binary); bool moveToFront = false; if (consOpt.noalign) moveToFront = true; if (_convertSimpleReadFile(strmReads, fragStore, consOpt.readsfile, moveToFront) != 0) return 1; numberOfContigs = 1; } else if (!empty(consOpt.afgfile)) { // Load Amos message file std::fstream strmReads(consOpt.afgfile.c_str(), std::fstream::in | std::fstream::binary); read(strmReads, fragStore, Amos()); numberOfContigs = length(fragStore.contigStore); } else if (!empty(consOpt.samfile)) { // Possibly load contigs into fragment store. if (!empty(consOpt.contigsfile)) { if (!loadContigs(fragStore, consOpt.contigsfile.c_str())) { std::cerr << "Could not load contigs file " << consOpt.contigsfile.c_str() << std::endl; return 1; } } // Load Sam message file std::fstream strmReads(consOpt.samfile.c_str(), std::fstream::in | std::fstream::binary); read(strmReads, fragStore, Sam()); numberOfContigs = length(fragStore.contigStore); } else { return 1; } return 0; } // Write resulting alignment. template <typename TFragmentStore> int writeOutput(TFragmentStore /*const*/ & fragStore, ConsensusOptions const & consOpt) { //IOREV std::cerr << "Writing output..." << std::endl; if (consOpt.output == 0) { // Write old SeqAn multi-read alignment format FILE* strmWrite = fopen(consOpt.outfile.c_str(), "w"); write(strmWrite, fragStore, FastaReadFormat()); fclose(strmWrite); } else if (consOpt.output == 1) { // Write Amos FILE* strmWrite = fopen(consOpt.outfile.c_str(), "w"); write(strmWrite, fragStore, Amos()); fclose(strmWrite); } else if (consOpt.output == 2) { FILE* strmWrite = fopen(consOpt.outfile.c_str(), "w"); _writeCeleraFrg(strmWrite, fragStore); fclose(strmWrite); } else if (consOpt.output == 3) { FILE* strmWrite = fopen(consOpt.outfile.c_str(), "w"); _writeCeleraCgb(strmWrite, fragStore); fclose(strmWrite); } else if (consOpt.output == 4) { // Write out resulting MSA in a Sam file. FILE* strmWrite = fopen(consOpt.outfile.c_str(), "w"); write(strmWrite, fragStore, Sam()); fclose(strmWrite); // Write out resulting consensus sequence. char buffer[10*1024]; buffer[0] = '\0'; strcat(buffer, consOpt.outfile.c_str()); strcat(buffer, ".consensus.fasta"); strmWrite = fopen(buffer, "w"); writeContigs(strmWrite, fragStore, Fasta()); fclose(strmWrite); } return 0; } int main(int argc, const char *argv[]) { // Command line parsing ArgumentParser parser; ConsensusOptions consOpt; seqan::ArgumentParser::ParseResult res = parseCommandLine(consOpt, argc, argv); if (res != seqan::ArgumentParser::PARSE_OK) return res == seqan::ArgumentParser::PARSE_ERROR; // Create a new fragment store typedef FragmentStore<> TFragmentStore; typedef Size<TFragmentStore>::Type TSize; TFragmentStore fragStore; // Load the reads and layout positions TSize numberOfContigs = 0; int ret = loadFiles(fragStore, numberOfContigs, consOpt); // Multi-realignment desired or just conversion of the input if (!consOpt.noalign) { // Iterate over all contigs if (consOpt.method == 0) std::cerr << "Performing realignment..." << std::endl; else std::cerr << "Performing consensus alignment..." << std::endl; for (TSize currentContig = 0; currentContig < numberOfContigs; ++currentContig) { std::cerr << "contig " << (currentContig + 1) << "/" << numberOfContigs << std::endl; if (consOpt.method == 0) { Score<int, WeightedConsensusScore<Score<int, FractionalScore>, Score<int, ConsensusScore> > > combinedScore; reAlign(fragStore, combinedScore, currentContig, consOpt.rmethod, consOpt.bandwidth, consOpt.include); if (consOpt.include) reAlign(fragStore, combinedScore, currentContig, consOpt.rmethod, consOpt.bandwidth, false); } else { std::cerr << "Performing consensus alignment..." << std::endl; // Import all reads of the given contig typedef TFragmentStore::TReadSeq TReadSeq; StringSet<TReadSeq, Owner<> > readSet; String<Pair<TSize, TSize> > begEndPos; _loadContigReads(readSet, begEndPos, fragStore, currentContig); if (!length(readSet)) continue; // Align the reads typedef StringSet<TReadSeq, Dependent<> > TStringSet; typedef Graph<Alignment<TStringSet, void, WithoutEdgeId> > TAlignGraph; TAlignGraph gOut(readSet); consensusAlignment(gOut, begEndPos, consOpt); // Update the contig in the fragment store if (!empty(gOut)) updateContig(fragStore, gOut, currentContig); clear(gOut); //// Debug code for CA //mtRandInit(); //String<char> fileTmp1 = "tmp1"; //String<char> fileTmp2 = "tmp2"; //for(int i = 0; i<10; ++i) { // int file = (mtRand() % 20) + 65; // appendValue(fileTmp1, char(file)); // appendValue(fileTmp2, char(file)); //} //std::fstream strm3; //strm3.open(toCString(fileTmp2), std::ios_base::out | std::ios_base::trunc); //for(int i = 0;i<(int) length(origStrSet); ++i) { // std::stringstream name; // name << value(begEndPos, i).i1 << "," << value(begEndPos, i).i2; // String<char> myTitle = name.str(); // write(strm3, origStrSet[i], myTitle, Fasta()); // if (value(begEndPos, i).i1 > value(begEndPos, i).i2) reverseComplement(origStrSet[i]); //} //strm3.close(); } } // end loop over all contigs } // Write result. ret = writeOutput(fragStore, consOpt); return ret; } <|endoftext|>
<commit_before>/*************************************************************************** * containers/test_iterators.cpp * * Part of the STXXL. See http://stxxl.sourceforge.net * * Copyright (C) 2007 Roman Dementiev <[email protected]> * Copyright (C) 2009 Andreas Beckmann <[email protected]> * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) **************************************************************************/ #include <cassert> #include <cstring> #include <deque> #include <vector> #include <stxxl.h> #define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100) template <typename T> const char * _() { return strchr(STXXL_PRETTY_FUNCTION_NAME, '['); } template <typename I> void dump_iterator_info(I) { STXXL_MSG(STXXL_PRETTY_FUNCTION_NAME); STXXL_MSG(" category: " << _<typename std::iterator_traits<I>::iterator_category>()); STXXL_MSG(" value_type: " << _<typename std::iterator_traits<I>::value_type>()); STXXL_MSG(" difference_type: " << _<typename std::iterator_traits<I>::difference_type>()); STXXL_MSG(" pointer: " << _<typename std::iterator_traits<I>::pointer>()); STXXL_MSG(" reference: " << _<typename std::iterator_traits<I>::reference>()); } template <typename T> struct modify { void operator () (T & obj) const { ++obj; } }; template <typename Iterator> bool test_inc_dec(Iterator it) { Iterator i = it; ++i; i++; --i; i--; assert(it == i); return it == i; } template <typename Iterator> bool test_inc_dec_random(Iterator it) { Iterator i = it; ++i; i = i + 2; i++; i += 3; --i; i = i - 3; i--; i -= 2; assert(it == i); return it == i; } template <typename IteratorA, typename IteratorB, typename Category> struct test_comparison_lt_gt { void operator() (IteratorA, IteratorB) { // operators <, <=, >=, > are not available in all iterator categories } }; template <typename IteratorA, typename IteratorB> struct test_comparison_lt_gt<IteratorA, IteratorB, std::random_access_iterator_tag> { void operator() (IteratorA a, IteratorB b) { a < b; a <= b; a > b; a >= b; b < a; b <= a; b > a; b >= a; } }; template <typename IteratorA, typename IteratorB> void test_comparison(IteratorA a, IteratorB b) { a == b; a != b; b == a; b != a; test_comparison_lt_gt<IteratorA, IteratorB, typename std::iterator_traits<IteratorA>::iterator_category>() (a, b); } template <typename Iterator> void test_operators(Iterator it) { *it; it.operator->(); test_comparison(it, it); } template <typename svt> void test(svt & sv) { typedef const svt csvt; typedef typename svt::value_type value_type; sv[0] = 108; typename svt::iterator svi = sv.begin(); dump_iterator_info(svi); modify<value_type>() (*svi); typename svt::const_iterator svci = sv.begin(); dump_iterator_info(svci); //modify<value_type>()(*svci); // read-only typename csvt::iterator xsvi = sv.begin(); modify<value_type>() (*xsvi); // test assignment svci = xsvi; //xsvi = svci; // not allowed typename csvt::const_iterator xsvci = sv.begin(); //modify<value_type>()(*xsvci); // read-only // test comparison between const and non-const iterators test_comparison(svci, xsvi); // test increment/decrement test_inc_dec(svi); test_inc_dec(svci); test_inc_dec(xsvi); test_inc_dec(xsvci); // test operators test_operators(svi); test_operators(svci); test_operators(xsvi); test_operators(xsvci); // test forward iteration for (typename svt::iterator i = sv.begin(); i != sv.end(); ++i) ; /////////////////////////////////////////////////////////////////////////// csvt & csv = sv; //csv[0] = 108; // read-only //typename csvt::iterator csvi = csv.begin(); // read-only //modify<value_type>()(*csvi); // read-only typename csvt::const_iterator csvci = csv.begin(); //modify<value_type>()(*csvci); // read-only //typename svt::iterator xcsvi = csv.begin(); // read-only //modify<value_type>()(*xcsvi); // read-only typename svt::const_iterator xcsvci = csv.begin(); //modify<value_type>()(*csvci); // read-only // test increment/decrement test_inc_dec(csvci); test_inc_dec(xcsvci); // test operators test_operators(csvci); test_operators(xcsvci); // test forward iteration for (typename svt::const_iterator ci = sv.begin(); ci != sv.end(); ++ci) ; } template <typename svt> void test_reverse(svt & sv) { typedef const svt csvt; typedef typename svt::value_type value_type; sv[0] = 108; typename svt::reverse_iterator svi = sv.rbegin(); dump_iterator_info(svi); modify<value_type>() (*svi); typename svt::const_reverse_iterator svci = sv.rbegin(); dump_iterator_info(svci); //modify<value_type>()(*svci); // read-only typename csvt::reverse_iterator xsvi = sv.rbegin(); modify<value_type>() (*xsvi); // test assignment svci = xsvi; //xsvi = svci; // not allowed typename csvt::const_reverse_iterator xsvci = sv.rbegin(); //modify<value_type>()(*xsvci); // read-only #if !defined(__GNUG__) || (GCC_VERSION >= 40000) // test comparison between const and non-const iterators test_comparison(svci, xsvi); #endif // test increment/decrement test_inc_dec(svi); test_inc_dec(svci); test_inc_dec(xsvi); test_inc_dec(xsvci); // test operators test_operators(svi); test_operators(svci); test_operators(xsvi); test_operators(xsvci); // test forward iteration for (typename svt::reverse_iterator i = sv.rbegin(); i != sv.rend(); ++i) ; /////////////////////////////////////////////////////////////////////////// csvt & csv = sv; //csv[0] = 108; // read-only //typename csvt::reverse_iterator csvi = csv.rbegin(); // read-only //modify<value_type>()(*csvi); // read-only typename csvt::const_reverse_iterator csvci = csv.rbegin(); //modify<value_type>()(*csvci); // read-only //typename svt::reverse_iterator xcsvi = csv.rbegin(); // read-only //modify<value_type>()(*xcsvi); // read-only typename svt::const_reverse_iterator xcsvci = csv.rbegin(); //modify<value_type>()(*csvci); // read-only // test increment/decrement test_inc_dec(csvci); test_inc_dec(xcsvci); // test operators test_operators(csvci); test_operators(xcsvci); // test forward iteration #if !defined(__GNUG__) || (GCC_VERSION >= 40000) for (typename svt::const_reverse_iterator ci = sv.rbegin(); ci != sv.rend(); ++ci) ; #else for (typename svt::const_reverse_iterator ci = sv.rbegin(); ci != typename svt::const_reverse_iterator(sv.rend()); ++ci) ; #endif } template <typename svt> void test_random_access(svt & sv) { typename svt::const_iterator svci = sv.begin(); typename svt::iterator xsvi = sv.begin(); // test subtraction of const and non-const iterators svci - xsvi; xsvi - svci; // bracket operators svci[0]; xsvi[0]; //svci[0] = 1; // read-only xsvi[0] = 1; // test +, -, +=, -= test_inc_dec_random(svci); test_inc_dec_random(xsvi); } template <typename svt> void test_random_access_reverse(svt & sv) { typename svt::const_reverse_iterator svcri = sv.rbegin(); typename svt::reverse_iterator xsvri = sv.rbegin(); #if !defined(__GNUG__) || (GCC_VERSION >= 40000) // test subtraction of const and non-const iterators svcri - xsvri; xsvri - svcri; #endif // bracket operators svcri[0]; xsvri[0]; //svcri[0] = 1; // read-only xsvri[0] = 1; // test +, -, +=, -= test_inc_dec_random(svcri); test_inc_dec_random(xsvri); } typedef float key_type; typedef double data_type; struct cmp : public std::less<key_type> { static key_type min_value() { return (std::numeric_limits<key_type>::min)(); } static key_type max_value() { return (std::numeric_limits<key_type>::max)(); } }; template <> struct modify<std::pair<const key_type, data_type> > { void operator () (std::pair<const key_type, data_type> & obj) const { ++(obj.second); } }; int main() { std::vector<double> V(8); test(V); test_reverse(V); test_random_access(V); test_random_access_reverse(V); stxxl::vector<double> Vector(8); test(Vector); //test_reverse(Vector); test_random_access(Vector); //test_random_access_reverse(Vector); #if !defined(__GNUG__) || (GCC_VERSION >= 30400) typedef stxxl::map<key_type, data_type, cmp, 4096, 4096> map_type; map_type Map(4096 * 10, 4096 * 10); Map[4] = 8; Map[15] = 16; Map[23] = 42; test(Map); #endif std::deque<double> D(1); test(D); test_reverse(D); test_random_access(D); test_random_access_reverse(D); stxxl::deque<double> Deque(1); test(Deque); //test_reverse(Deque); test_random_access(Deque); //test_random_access_reverse(Deque); return 0; } // vim: et:ts=4:sw=4 <commit_msg>dump container type information, too<commit_after>/*************************************************************************** * containers/test_iterators.cpp * * Part of the STXXL. See http://stxxl.sourceforge.net * * Copyright (C) 2007 Roman Dementiev <[email protected]> * Copyright (C) 2009 Andreas Beckmann <[email protected]> * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) **************************************************************************/ #include <cassert> #include <cstring> #include <deque> #include <map> #include <vector> #include <stxxl.h> #define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100) template <typename T> const char * _() { return strchr(STXXL_PRETTY_FUNCTION_NAME, '['); } template <typename I> void dump_iterator_info(I&) { STXXL_MSG(STXXL_PRETTY_FUNCTION_NAME); STXXL_MSG(" category: " << _<typename std::iterator_traits<I>::iterator_category>()); STXXL_MSG(" value_type: " << _<typename std::iterator_traits<I>::value_type>()); STXXL_MSG(" difference_type: " << _<typename std::iterator_traits<I>::difference_type>()); STXXL_MSG(" pointer: " << _<typename std::iterator_traits<I>::pointer>()); STXXL_MSG(" reference: " << _<typename std::iterator_traits<I>::reference>()); } template <typename C> void dump_container_info(C&) { STXXL_MSG(STXXL_PRETTY_FUNCTION_NAME); STXXL_MSG(" value_type: " << _<typename C::value_type>()); STXXL_MSG(" size_type: " << _<typename C::size_type>()); STXXL_MSG(" difference_type: " << _<typename C::difference_type>()); STXXL_MSG(" pointer: " << _<typename C::pointer>()); STXXL_MSG(" const_pointer: " << _<typename C::const_pointer>()); STXXL_MSG(" reference: " << _<typename C::reference>()); STXXL_MSG(" const_reference: " << _<typename C::const_reference>()); STXXL_MSG(" iterator: " << _<typename C::iterator>()); STXXL_MSG(" const_iterator: " << _<typename C::const_iterator>()); } template <typename T> struct modify { void operator () (T & obj) const { ++obj; } }; template <typename Iterator> bool test_inc_dec(Iterator it) { Iterator i = it; ++i; i++; --i; i--; assert(it == i); return it == i; } template <typename Iterator> bool test_inc_dec_random(Iterator it) { Iterator i = it; ++i; i = i + 2; i++; i += 3; --i; i = i - 3; i--; i -= 2; assert(it == i); return it == i; } template <typename IteratorA, typename IteratorB, typename Category> struct test_comparison_lt_gt { void operator() (IteratorA, IteratorB) { // operators <, <=, >=, > are not available in all iterator categories } }; template <typename IteratorA, typename IteratorB> struct test_comparison_lt_gt<IteratorA, IteratorB, std::random_access_iterator_tag> { void operator() (IteratorA a, IteratorB b) { a < b; a <= b; a > b; a >= b; b < a; b <= a; b > a; b >= a; } }; template <typename IteratorA, typename IteratorB> void test_comparison(IteratorA a, IteratorB b) { a == b; a != b; b == a; b != a; test_comparison_lt_gt<IteratorA, IteratorB, typename std::iterator_traits<IteratorA>::iterator_category>() (a, b); } template <typename Iterator> void test_operators(Iterator it) { *it; it.operator->(); test_comparison(it, it); } template <typename svt> void test(svt & sv) { dump_container_info(sv); typedef const svt csvt; typedef typename svt::value_type value_type; sv[0] = 108; typename svt::iterator svi = sv.begin(); dump_iterator_info(svi); modify<value_type>() (*svi); typename svt::const_iterator svci = sv.begin(); dump_iterator_info(svci); //modify<value_type>()(*svci); // read-only typename csvt::iterator xsvi = sv.begin(); modify<value_type>() (*xsvi); // test assignment svci = xsvi; //xsvi = svci; // not allowed typename csvt::const_iterator xsvci = sv.begin(); //modify<value_type>()(*xsvci); // read-only // test comparison between const and non-const iterators test_comparison(svci, xsvi); // test increment/decrement test_inc_dec(svi); test_inc_dec(svci); test_inc_dec(xsvi); test_inc_dec(xsvci); // test operators test_operators(svi); test_operators(svci); test_operators(xsvi); test_operators(xsvci); // test forward iteration for (typename svt::iterator i = sv.begin(); i != sv.end(); ++i) ; /////////////////////////////////////////////////////////////////////////// csvt & csv = sv; //csv[0] = 108; // read-only //typename csvt::iterator csvi = csv.begin(); // read-only //modify<value_type>()(*csvi); // read-only typename csvt::const_iterator csvci = csv.begin(); //modify<value_type>()(*csvci); // read-only //typename svt::iterator xcsvi = csv.begin(); // read-only //modify<value_type>()(*xcsvi); // read-only typename svt::const_iterator xcsvci = csv.begin(); //modify<value_type>()(*csvci); // read-only // test increment/decrement test_inc_dec(csvci); test_inc_dec(xcsvci); // test operators test_operators(csvci); test_operators(xcsvci); // test forward iteration for (typename svt::const_iterator ci = sv.begin(); ci != sv.end(); ++ci) ; } template <typename svt> void test_reverse(svt & sv) { dump_container_info(sv); typedef const svt csvt; typedef typename svt::value_type value_type; sv[0] = 108; typename svt::reverse_iterator svi = sv.rbegin(); dump_iterator_info(svi); modify<value_type>() (*svi); typename svt::const_reverse_iterator svci = sv.rbegin(); dump_iterator_info(svci); //modify<value_type>()(*svci); // read-only typename csvt::reverse_iterator xsvi = sv.rbegin(); modify<value_type>() (*xsvi); // test assignment svci = xsvi; //xsvi = svci; // not allowed typename csvt::const_reverse_iterator xsvci = sv.rbegin(); //modify<value_type>()(*xsvci); // read-only #if !defined(__GNUG__) || (GCC_VERSION >= 40000) // test comparison between const and non-const iterators test_comparison(svci, xsvi); #endif // test increment/decrement test_inc_dec(svi); test_inc_dec(svci); test_inc_dec(xsvi); test_inc_dec(xsvci); // test operators test_operators(svi); test_operators(svci); test_operators(xsvi); test_operators(xsvci); // test forward iteration for (typename svt::reverse_iterator i = sv.rbegin(); i != sv.rend(); ++i) ; /////////////////////////////////////////////////////////////////////////// csvt & csv = sv; //csv[0] = 108; // read-only //typename csvt::reverse_iterator csvi = csv.rbegin(); // read-only //modify<value_type>()(*csvi); // read-only typename csvt::const_reverse_iterator csvci = csv.rbegin(); //modify<value_type>()(*csvci); // read-only //typename svt::reverse_iterator xcsvi = csv.rbegin(); // read-only //modify<value_type>()(*xcsvi); // read-only typename svt::const_reverse_iterator xcsvci = csv.rbegin(); //modify<value_type>()(*csvci); // read-only // test increment/decrement test_inc_dec(csvci); test_inc_dec(xcsvci); // test operators test_operators(csvci); test_operators(xcsvci); // test forward iteration #if !defined(__GNUG__) || (GCC_VERSION >= 40000) for (typename svt::const_reverse_iterator ci = sv.rbegin(); ci != sv.rend(); ++ci) ; #else for (typename svt::const_reverse_iterator ci = sv.rbegin(); ci != typename svt::const_reverse_iterator(sv.rend()); ++ci) ; #endif } template <typename svt> void test_random_access(svt & sv) { typename svt::const_iterator svci = sv.begin(); typename svt::iterator xsvi = sv.begin(); // test subtraction of const and non-const iterators svci - xsvi; xsvi - svci; // bracket operators svci[0]; xsvi[0]; //svci[0] = 1; // read-only xsvi[0] = 1; // test +, -, +=, -= test_inc_dec_random(svci); test_inc_dec_random(xsvi); } template <typename svt> void test_random_access_reverse(svt & sv) { typename svt::const_reverse_iterator svcri = sv.rbegin(); typename svt::reverse_iterator xsvri = sv.rbegin(); #if !defined(__GNUG__) || (GCC_VERSION >= 40000) // test subtraction of const and non-const iterators svcri - xsvri; xsvri - svcri; #endif // bracket operators svcri[0]; xsvri[0]; //svcri[0] = 1; // read-only xsvri[0] = 1; // test +, -, +=, -= test_inc_dec_random(svcri); test_inc_dec_random(xsvri); } typedef float key_type; typedef double data_type; struct cmp : public std::less<key_type> { static key_type min_value() { return (std::numeric_limits<key_type>::min)(); } static key_type max_value() { return (std::numeric_limits<key_type>::max)(); } }; template <> struct modify<std::pair<const key_type, data_type> > { void operator () (std::pair<const key_type, data_type> & obj) const { ++(obj.second); } }; int main() { std::vector<double> V(8); test(V); test_reverse(V); test_random_access(V); test_random_access_reverse(V); stxxl::vector<double> Vector(8); test(Vector); //test_reverse(Vector); test_random_access(Vector); //test_random_access_reverse(Vector); std::map<key_type, data_type, cmp> M; M[4] = 8; M[15] = 16; M[23] = 42; test(M); #if !defined(__GNUG__) || (GCC_VERSION >= 30400) typedef stxxl::map<key_type, data_type, cmp, 4096, 4096> map_type; map_type Map(4096 * 10, 4096 * 10); Map[4] = 8; Map[15] = 16; Map[23] = 42; test(Map); #endif std::deque<double> D(1); test(D); test_reverse(D); test_random_access(D); test_random_access_reverse(D); stxxl::deque<double> Deque(1); test(Deque); //test_reverse(Deque); test_random_access(Deque); //test_random_access_reverse(Deque); return 0; } // vim: et:ts=4:sw=4 <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #if !defined(XercesPARSERLIAISONDEFINITIONS_HEADER_GUARD_1357924680) #define XercesPARSERLIAISONDEFINITIONS_HEADER_GUARD_1357924680 #include <Include/PlatformDefinitions.hpp> #if defined(XALAN_XERCESPARSERLIAISON_BUILD_DLL) #define XALAN_XERCESPARSERLIAISON_EXPORT XALAN_PLATFORM_EXPORT #define XALAN_XERCESPARSERLIAISON_EXPORT_FUNCTION(T) XALAN_PLATFORM_EXPORT_FUNCTION(T) #else #define XALAN_XERCESPARSERLIAISON_EXPORT XALAN_PLATFORM_IMPORT #define XALAN_XERCESPARSERLIAISON_EXPORT_FUNCTION(T) XALAN_PLATFORM_IMPORT_FUNCTION(T) #endif #endif // XercesPARSERLIAISONDEFINITIONS_HEADER_GUARD_1357924680 <commit_msg>Include Xerces defs file so the version macros are defined.<commit_after>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #if !defined(XercesPARSERLIAISONDEFINITIONS_HEADER_GUARD_1357924680) #define XercesPARSERLIAISONDEFINITIONS_HEADER_GUARD_1357924680 #include <Include/PlatformDefinitions.hpp> #include <xercesc/util/XercesDefs.hpp> #if defined(XALAN_XERCESPARSERLIAISON_BUILD_DLL) #define XALAN_XERCESPARSERLIAISON_EXPORT XALAN_PLATFORM_EXPORT #define XALAN_XERCESPARSERLIAISON_EXPORT_FUNCTION(T) XALAN_PLATFORM_EXPORT_FUNCTION(T) #else #define XALAN_XERCESPARSERLIAISON_EXPORT XALAN_PLATFORM_IMPORT #define XALAN_XERCESPARSERLIAISON_EXPORT_FUNCTION(T) XALAN_PLATFORM_IMPORT_FUNCTION(T) #endif #endif // XercesPARSERLIAISONDEFINITIONS_HEADER_GUARD_1357924680 <|endoftext|>
<commit_before>// Begin CVS Header // $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/function/CEvaluationNode.cpp,v $ // $Revision: 1.34 $ // $Name: $ // $Author: ssahle $ // $Date: 2007/09/21 15:40:12 $ // End CVS Header // Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. #include "copasi.h" #include "CEvaluationNode.h" #include "sbml/math/ASTNode.h" #include "sbml/ConverterASTNode.h" #include "sbml/util/List.h" CEvaluationNode::CPrecedence::CPrecedence(const unsigned C_INT32 & left, const unsigned C_INT32 & right): left(left), right(right) {} CEvaluationNode::CPrecedence::CPrecedence(const CPrecedence & src): left(src.left), right(src.right) {} CEvaluationNode::CPrecedence::~CPrecedence() {} CEvaluationNode * CEvaluationNode::create(const Type & type, const std::string & contents) { CEvaluationNode * pNode = NULL; switch (CEvaluationNode::type(type)) { case CEvaluationNode::CALL: pNode = new CEvaluationNodeCall((CEvaluationNodeCall::SubType) subType(type), contents); break; case CEvaluationNode::CHOICE: pNode = new CEvaluationNodeChoice((CEvaluationNodeChoice::SubType) subType(type), contents); break; case CEvaluationNode::CONSTANT: pNode = new CEvaluationNodeConstant((CEvaluationNodeConstant::SubType) subType(type), contents); break; case CEvaluationNode::FUNCTION: pNode = new CEvaluationNodeFunction((CEvaluationNodeFunction::SubType) subType(type), contents); break; case CEvaluationNode::LOGICAL: pNode = new CEvaluationNodeLogical((CEvaluationNodeLogical::SubType) subType(type), contents); break; case CEvaluationNode::NUMBER: pNode = new CEvaluationNodeNumber((CEvaluationNodeNumber::SubType) subType(type), contents); break; case CEvaluationNode::OBJECT: pNode = new CEvaluationNodeObject((CEvaluationNodeObject::SubType) subType(type), contents); break; case CEvaluationNode::OPERATOR: pNode = new CEvaluationNodeOperator((CEvaluationNodeOperator::SubType) subType(type), contents); break; case CEvaluationNode::STRUCTURE: pNode = new CEvaluationNodeStructure((CEvaluationNodeStructure::SubType) subType(type), contents); break; case CEvaluationNode::VARIABLE: pNode = new CEvaluationNodeVariable((CEvaluationNodeVariable::SubType) subType(type), contents); break; case CEvaluationNode::VECTOR: pNode = new CEvaluationNodeVector((CEvaluationNodeVector::SubType) subType(type), contents); break; case CEvaluationNode::WHITESPACE: pNode = new CEvaluationNodeWhiteSpace((CEvaluationNodeWhiteSpace::SubType) subType(type), contents); break; } return pNode; } CEvaluationNode::Type CEvaluationNode::subType(const Type & type) {return (Type) (type & 0x00FFFFFF);} CEvaluationNode::Type CEvaluationNode::type(const Type & type) {return (Type) (type & 0xFF000000);} CEvaluationNode::CEvaluationNode(): CCopasiNode<Data>(), mType(CEvaluationNode::INVALID), mValue(std::numeric_limits<C_FLOAT64>::quiet_NaN()), mData(""), mPrecedence(PRECEDENCE_DEFAULT) {} CEvaluationNode::CEvaluationNode(const Type & type, const Data & data): CCopasiNode<Data>(), mType(type), mValue(std::numeric_limits<C_FLOAT64>::quiet_NaN()), mData(data), mPrecedence(PRECEDENCE_DEFAULT) {assert(mData != "");} CEvaluationNode::CEvaluationNode(const CEvaluationNode & src): CCopasiNode<Data>(src), mType(src.mType), mValue(src.mValue), mData(src.mData), mPrecedence(src.mPrecedence) {assert(mData != "");} CEvaluationNode::~CEvaluationNode() {} bool CEvaluationNode::compile(const CEvaluationTree * /* pTree */) {return true;} CEvaluationNode::Data CEvaluationNode::getData() const {return mData;} bool CEvaluationNode::setData(const Data & data) { mData = data; return true; } std::string CEvaluationNode::getInfix() const {return mData;} std::string CEvaluationNode::getDisplayString(const CEvaluationTree * /* pTree */) const {return mData;} std::string CEvaluationNode::getDisplay_C_String(const CEvaluationTree * /* pTree */) const {return mData;} std::string CEvaluationNode::getDisplay_MMD_String(const CEvaluationTree * /* pTree */) const {return mData;} std::string CEvaluationNode::getDisplay_XPP_String(const CEvaluationTree * /* pTree */) const {return mData;} const CEvaluationNode::Type & CEvaluationNode::getType() const {return mType;} bool CEvaluationNode::operator < (const CEvaluationNode & rhs) {return (mPrecedence.right < rhs.mPrecedence.left);} CEvaluationNode* CEvaluationNode::copyNode(CEvaluationNode* child1, CEvaluationNode* child2) const { std::vector<CEvaluationNode*> children; if (child1 != NULL) children.push_back(child1); if (child2 != NULL) children.push_back(child2); return copyNode(children); } CEvaluationNode* CEvaluationNode::copyNode(const std::vector<CEvaluationNode*>& children) const { //std::cout << " this->getData() " << this->CEvaluationNode::getData() << std::endl; CEvaluationNode *newnode = create(getType(), getData()); std::vector<CEvaluationNode*>::const_iterator it = children.begin(), endit = children.end(); while (it != endit) { newnode->addChild(*it); ++it; } return newnode; } CEvaluationNode* CEvaluationNode::copyBranch() const { std::vector<CEvaluationNode*> children; const CEvaluationNode* child = dynamic_cast<const CEvaluationNode*>(getChild()); while (child != NULL) { CEvaluationNode *newchild = NULL; newchild = child->copyBranch(); children.push_back(newchild); child = dynamic_cast<const CEvaluationNode*>(child->getSibling()); } children.push_back(NULL); CEvaluationNode *newnode = copyNode(children); return newnode; } CEvaluationNode* CEvaluationNode::simplifyNode(const std::vector<CEvaluationNode*>& children) const { CEvaluationNode *newnode = copyNode(children); return newnode; } ASTNode* CEvaluationNode::toAST() const { return new ASTNode(); } const C_FLOAT64 * CEvaluationNode::getValuePointer() const {return &mValue;} void CEvaluationNode::writeMathML(std::ostream & /* out */, const std::vector<std::vector<std::string> > & /* env */, bool /* expand */, unsigned C_INT32 /* l */) const {} void CEvaluationNode::printRecursively(std::ostream & os, int indent) const { int i; os << std::endl; for (i = 0; i < indent; ++i) os << " "; os << "mData: " << mData << std::endl; for (i = 0; i < indent; ++i) os << " "; os << "mType: " << type(mType) << " subType: " << subType(mType) << std::endl; for (i = 0; i < indent; ++i) os << " "; os << "mValue: " << mValue << std::endl; CEvaluationNode* tmp; tmp = (CEvaluationNode*)getChild(); while (tmp) { tmp -> printRecursively(os, indent + 2); tmp = (CEvaluationNode*)tmp->getSibling(); } /* if (getChild()) ((CEvaluationNode*)getChild())->printRecursively(os, indent + 2); if (getSibling()) ((CEvaluationNode*)getSibling())->printRecursively(os, indent);*/ } void CEvaluationNode::printRecursively() const { this->printRecursively(std::cout, 0); } /** * Replaces all LOG10 (AST_FUNCTION_LOG) nodes that have two * children with the quotient of two LOG10 nodes with the base * as the argument for the divisor LOG10 node. */ void CEvaluationNode::replaceLog(ConverterASTNode* sourceNode) { if (sourceNode->getType() == AST_FUNCTION_LOG && sourceNode->getNumChildren() == 2) { List* l = new List(); ConverterASTNode* child1 = (ConverterASTNode*)sourceNode->getChild(0); ConverterASTNode* child2 = (ConverterASTNode*)sourceNode->getChild(1); ConverterASTNode* logNode1 = new ConverterASTNode(AST_FUNCTION_LOG); l->add(child1); logNode1->setChildren(l); ConverterASTNode* logNode2 = new ConverterASTNode(AST_FUNCTION_LOG); l = new List(); l->add(child2); logNode2->setChildren(l); l = new List(); l->add(logNode2); l->add(logNode1); sourceNode->setChildren(l); sourceNode->setType(AST_DIVIDE); } } /** * Replaces all root nodes with the corresponding power * operator since COPASI does not have the ROOT function. */ void CEvaluationNode::replaceRoot(ConverterASTNode* sourceNode) { if (sourceNode->getType() == AST_FUNCTION_ROOT && sourceNode->getNumChildren() == 2) { ConverterASTNode* child1 = (ConverterASTNode*)sourceNode->getChild(0); ConverterASTNode* child2 = (ConverterASTNode*)sourceNode->getChild(1); ConverterASTNode* divideNode = new ConverterASTNode(AST_DIVIDE); ConverterASTNode* oneNode = new ConverterASTNode(AST_REAL); oneNode->setValue(1.0); List* l = new List(); l->add(divideNode); divideNode->addChild(oneNode); divideNode->addChild(child1); List* l2 = new List(); l2->add(child2); l2->add(divideNode); sourceNode->setChildren(l2); sourceNode->setType(AST_POWER); } } CEvaluationNode* CEvaluationNode::splitBranch(const CEvaluationNode* splitnode, bool left) const { if (splitnode == this) { const CEvaluationNode *child = dynamic_cast<const CEvaluationNode*>(this->getChild()); if (!child) return NULL; if (left) { return child->copyBranch(); } else { child = dynamic_cast<const CEvaluationNode*>(child->getSibling()); if (!child) return NULL; return child->copyBranch(); } } else { /* const CEvaluationNode *child1 = dynamic_cast<const CEvaluationNode*>(getChild()); CEvaluationNode *newchild1 = NULL; CEvaluationNode *newchild2 = NULL; if (child1 != NULL) { newchild1 = child1->splitBranch(splitnode, left); const CEvaluationNode *child2 = dynamic_cast<const CEvaluationNode*>(child1->getSibling()); if (child2 != NULL) { newchild2 = child2->splitBranch(splitnode, left); } } CEvaluationNode *newnode = copyNode(newchild1, newchild2); return newnode;*/ std::vector<CEvaluationNode*> children; const CEvaluationNode* child = dynamic_cast<const CEvaluationNode*>(getChild()); while (child != NULL) { CEvaluationNode *newchild = NULL; newchild = child->splitBranch(splitnode, left); children.push_back(newchild); child = dynamic_cast<const CEvaluationNode*>(child->getSibling()); } children.push_back(NULL); CEvaluationNode *newnode = copyNode(children); return newnode; } } const CEvaluationNode* CEvaluationNode::findTopMinus(const std::vector<CFunctionAnalyzer::CValue> & callParameters) const { if (getType() == (OPERATOR | CEvaluationNodeOperator::MINUS)) return this; if (getType() == (OPERATOR | CEvaluationNodeOperator::MULTIPLY)) { //look at left child recursively const CEvaluationNode *child = dynamic_cast<const CEvaluationNode*>(this->getChild()); const CEvaluationNode *tmp = NULL; if (child) tmp = child->findTopMinus(callParameters); if (tmp) { //we have found a minus operator in the branch of the left child. We //only want to report this as a split point if the other branch is positive. const CEvaluationNode *child2 = dynamic_cast<const CEvaluationNode*>(child->getSibling()); if (CFunctionAnalyzer::evaluateNode(child2, callParameters).isPositive()) return tmp; else return NULL; } //otherwise look at right child const CEvaluationNode *child2 = dynamic_cast<const CEvaluationNode*>(child->getSibling()); if (child2) tmp = child2->findTopMinus(callParameters); if (tmp) { //we have found a minus operator in the branch of the right child. We //only want to report this as a split point if the other branch is positive. if (CFunctionAnalyzer::evaluateNode(child, callParameters).isPositive()) return tmp; else return NULL; } //TODO: check if both children contain a minus. This would not be a valid split point. } if (getType() == (OPERATOR | CEvaluationNodeOperator::DIVIDE)) { //look at left child only (recursively) const CEvaluationNode *child = dynamic_cast<const CEvaluationNode*>(this->getChild()); const CEvaluationNode *tmp = NULL; if (child) tmp = child->findTopMinus(callParameters); if (tmp) return tmp; } return NULL; } <commit_msg>adapt to changes in CFunctionAnalyzer<commit_after>// Begin CVS Header // $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/function/CEvaluationNode.cpp,v $ // $Revision: 1.35 $ // $Name: $ // $Author: ssahle $ // $Date: 2007/10/26 12:59:02 $ // End CVS Header // Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. #include "copasi.h" #include "CEvaluationNode.h" #include "sbml/math/ASTNode.h" #include "sbml/ConverterASTNode.h" #include "sbml/util/List.h" CEvaluationNode::CPrecedence::CPrecedence(const unsigned C_INT32 & left, const unsigned C_INT32 & right): left(left), right(right) {} CEvaluationNode::CPrecedence::CPrecedence(const CPrecedence & src): left(src.left), right(src.right) {} CEvaluationNode::CPrecedence::~CPrecedence() {} CEvaluationNode * CEvaluationNode::create(const Type & type, const std::string & contents) { CEvaluationNode * pNode = NULL; switch (CEvaluationNode::type(type)) { case CEvaluationNode::CALL: pNode = new CEvaluationNodeCall((CEvaluationNodeCall::SubType) subType(type), contents); break; case CEvaluationNode::CHOICE: pNode = new CEvaluationNodeChoice((CEvaluationNodeChoice::SubType) subType(type), contents); break; case CEvaluationNode::CONSTANT: pNode = new CEvaluationNodeConstant((CEvaluationNodeConstant::SubType) subType(type), contents); break; case CEvaluationNode::FUNCTION: pNode = new CEvaluationNodeFunction((CEvaluationNodeFunction::SubType) subType(type), contents); break; case CEvaluationNode::LOGICAL: pNode = new CEvaluationNodeLogical((CEvaluationNodeLogical::SubType) subType(type), contents); break; case CEvaluationNode::NUMBER: pNode = new CEvaluationNodeNumber((CEvaluationNodeNumber::SubType) subType(type), contents); break; case CEvaluationNode::OBJECT: pNode = new CEvaluationNodeObject((CEvaluationNodeObject::SubType) subType(type), contents); break; case CEvaluationNode::OPERATOR: pNode = new CEvaluationNodeOperator((CEvaluationNodeOperator::SubType) subType(type), contents); break; case CEvaluationNode::STRUCTURE: pNode = new CEvaluationNodeStructure((CEvaluationNodeStructure::SubType) subType(type), contents); break; case CEvaluationNode::VARIABLE: pNode = new CEvaluationNodeVariable((CEvaluationNodeVariable::SubType) subType(type), contents); break; case CEvaluationNode::VECTOR: pNode = new CEvaluationNodeVector((CEvaluationNodeVector::SubType) subType(type), contents); break; case CEvaluationNode::WHITESPACE: pNode = new CEvaluationNodeWhiteSpace((CEvaluationNodeWhiteSpace::SubType) subType(type), contents); break; } return pNode; } CEvaluationNode::Type CEvaluationNode::subType(const Type & type) {return (Type) (type & 0x00FFFFFF);} CEvaluationNode::Type CEvaluationNode::type(const Type & type) {return (Type) (type & 0xFF000000);} CEvaluationNode::CEvaluationNode(): CCopasiNode<Data>(), mType(CEvaluationNode::INVALID), mValue(std::numeric_limits<C_FLOAT64>::quiet_NaN()), mData(""), mPrecedence(PRECEDENCE_DEFAULT) {} CEvaluationNode::CEvaluationNode(const Type & type, const Data & data): CCopasiNode<Data>(), mType(type), mValue(std::numeric_limits<C_FLOAT64>::quiet_NaN()), mData(data), mPrecedence(PRECEDENCE_DEFAULT) {assert(mData != "");} CEvaluationNode::CEvaluationNode(const CEvaluationNode & src): CCopasiNode<Data>(src), mType(src.mType), mValue(src.mValue), mData(src.mData), mPrecedence(src.mPrecedence) {assert(mData != "");} CEvaluationNode::~CEvaluationNode() {} bool CEvaluationNode::compile(const CEvaluationTree * /* pTree */) {return true;} CEvaluationNode::Data CEvaluationNode::getData() const {return mData;} bool CEvaluationNode::setData(const Data & data) { mData = data; return true; } std::string CEvaluationNode::getInfix() const {return mData;} std::string CEvaluationNode::getDisplayString(const CEvaluationTree * /* pTree */) const {return mData;} std::string CEvaluationNode::getDisplay_C_String(const CEvaluationTree * /* pTree */) const {return mData;} std::string CEvaluationNode::getDisplay_MMD_String(const CEvaluationTree * /* pTree */) const {return mData;} std::string CEvaluationNode::getDisplay_XPP_String(const CEvaluationTree * /* pTree */) const {return mData;} const CEvaluationNode::Type & CEvaluationNode::getType() const {return mType;} bool CEvaluationNode::operator < (const CEvaluationNode & rhs) {return (mPrecedence.right < rhs.mPrecedence.left);} CEvaluationNode* CEvaluationNode::copyNode(CEvaluationNode* child1, CEvaluationNode* child2) const { std::vector<CEvaluationNode*> children; if (child1 != NULL) children.push_back(child1); if (child2 != NULL) children.push_back(child2); return copyNode(children); } CEvaluationNode* CEvaluationNode::copyNode(const std::vector<CEvaluationNode*>& children) const { //std::cout << " this->getData() " << this->CEvaluationNode::getData() << std::endl; CEvaluationNode *newnode = create(getType(), getData()); std::vector<CEvaluationNode*>::const_iterator it = children.begin(), endit = children.end(); while (it != endit) { newnode->addChild(*it); ++it; } return newnode; } CEvaluationNode* CEvaluationNode::copyBranch() const { std::vector<CEvaluationNode*> children; const CEvaluationNode* child = dynamic_cast<const CEvaluationNode*>(getChild()); while (child != NULL) { CEvaluationNode *newchild = NULL; newchild = child->copyBranch(); children.push_back(newchild); child = dynamic_cast<const CEvaluationNode*>(child->getSibling()); } children.push_back(NULL); CEvaluationNode *newnode = copyNode(children); return newnode; } CEvaluationNode* CEvaluationNode::simplifyNode(const std::vector<CEvaluationNode*>& children) const { CEvaluationNode *newnode = copyNode(children); return newnode; } ASTNode* CEvaluationNode::toAST() const { return new ASTNode(); } const C_FLOAT64 * CEvaluationNode::getValuePointer() const {return &mValue;} void CEvaluationNode::writeMathML(std::ostream & /* out */, const std::vector<std::vector<std::string> > & /* env */, bool /* expand */, unsigned C_INT32 /* l */) const {} void CEvaluationNode::printRecursively(std::ostream & os, int indent) const { int i; os << std::endl; for (i = 0; i < indent; ++i) os << " "; os << "mData: " << mData << std::endl; for (i = 0; i < indent; ++i) os << " "; os << "mType: " << type(mType) << " subType: " << subType(mType) << std::endl; for (i = 0; i < indent; ++i) os << " "; os << "mValue: " << mValue << std::endl; CEvaluationNode* tmp; tmp = (CEvaluationNode*)getChild(); while (tmp) { tmp -> printRecursively(os, indent + 2); tmp = (CEvaluationNode*)tmp->getSibling(); } /* if (getChild()) ((CEvaluationNode*)getChild())->printRecursively(os, indent + 2); if (getSibling()) ((CEvaluationNode*)getSibling())->printRecursively(os, indent);*/ } void CEvaluationNode::printRecursively() const { this->printRecursively(std::cout, 0); } /** * Replaces all LOG10 (AST_FUNCTION_LOG) nodes that have two * children with the quotient of two LOG10 nodes with the base * as the argument for the divisor LOG10 node. */ void CEvaluationNode::replaceLog(ConverterASTNode* sourceNode) { if (sourceNode->getType() == AST_FUNCTION_LOG && sourceNode->getNumChildren() == 2) { List* l = new List(); ConverterASTNode* child1 = (ConverterASTNode*)sourceNode->getChild(0); ConverterASTNode* child2 = (ConverterASTNode*)sourceNode->getChild(1); ConverterASTNode* logNode1 = new ConverterASTNode(AST_FUNCTION_LOG); l->add(child1); logNode1->setChildren(l); ConverterASTNode* logNode2 = new ConverterASTNode(AST_FUNCTION_LOG); l = new List(); l->add(child2); logNode2->setChildren(l); l = new List(); l->add(logNode2); l->add(logNode1); sourceNode->setChildren(l); sourceNode->setType(AST_DIVIDE); } } /** * Replaces all root nodes with the corresponding power * operator since COPASI does not have the ROOT function. */ void CEvaluationNode::replaceRoot(ConverterASTNode* sourceNode) { if (sourceNode->getType() == AST_FUNCTION_ROOT && sourceNode->getNumChildren() == 2) { ConverterASTNode* child1 = (ConverterASTNode*)sourceNode->getChild(0); ConverterASTNode* child2 = (ConverterASTNode*)sourceNode->getChild(1); ConverterASTNode* divideNode = new ConverterASTNode(AST_DIVIDE); ConverterASTNode* oneNode = new ConverterASTNode(AST_REAL); oneNode->setValue(1.0); List* l = new List(); l->add(divideNode); divideNode->addChild(oneNode); divideNode->addChild(child1); List* l2 = new List(); l2->add(child2); l2->add(divideNode); sourceNode->setChildren(l2); sourceNode->setType(AST_POWER); } } CEvaluationNode* CEvaluationNode::splitBranch(const CEvaluationNode* splitnode, bool left) const { if (splitnode == this) { const CEvaluationNode *child = dynamic_cast<const CEvaluationNode*>(this->getChild()); if (!child) return NULL; if (left) { return child->copyBranch(); } else { child = dynamic_cast<const CEvaluationNode*>(child->getSibling()); if (!child) return NULL; return child->copyBranch(); } } else { /* const CEvaluationNode *child1 = dynamic_cast<const CEvaluationNode*>(getChild()); CEvaluationNode *newchild1 = NULL; CEvaluationNode *newchild2 = NULL; if (child1 != NULL) { newchild1 = child1->splitBranch(splitnode, left); const CEvaluationNode *child2 = dynamic_cast<const CEvaluationNode*>(child1->getSibling()); if (child2 != NULL) { newchild2 = child2->splitBranch(splitnode, left); } } CEvaluationNode *newnode = copyNode(newchild1, newchild2); return newnode;*/ std::vector<CEvaluationNode*> children; const CEvaluationNode* child = dynamic_cast<const CEvaluationNode*>(getChild()); while (child != NULL) { CEvaluationNode *newchild = NULL; newchild = child->splitBranch(splitnode, left); children.push_back(newchild); child = dynamic_cast<const CEvaluationNode*>(child->getSibling()); } children.push_back(NULL); CEvaluationNode *newnode = copyNode(children); return newnode; } } const CEvaluationNode* CEvaluationNode::findTopMinus(const std::vector<CFunctionAnalyzer::CValue> & callParameters) const { if (getType() == (OPERATOR | CEvaluationNodeOperator::MINUS)) return this; if (getType() == (OPERATOR | CEvaluationNodeOperator::MULTIPLY)) { //look at left child recursively const CEvaluationNode *child = dynamic_cast<const CEvaluationNode*>(this->getChild()); const CEvaluationNode *tmp = NULL; if (child) tmp = child->findTopMinus(callParameters); if (tmp) { //we have found a minus operator in the branch of the left child. We //only want to report this as a split point if the other branch is positive. const CEvaluationNode *child2 = dynamic_cast<const CEvaluationNode*>(child->getSibling()); if (CFunctionAnalyzer::evaluateNode(child2, callParameters, CFunctionAnalyzer::NOOBJECT).isPositive()) return tmp; else return NULL; } //otherwise look at right child const CEvaluationNode *child2 = dynamic_cast<const CEvaluationNode*>(child->getSibling()); if (child2) tmp = child2->findTopMinus(callParameters); if (tmp) { //we have found a minus operator in the branch of the right child. We //only want to report this as a split point if the other branch is positive. if (CFunctionAnalyzer::evaluateNode(child, callParameters, CFunctionAnalyzer::NOOBJECT).isPositive()) return tmp; else return NULL; } //TODO: check if both children contain a minus. This would not be a valid split point. } if (getType() == (OPERATOR | CEvaluationNodeOperator::DIVIDE)) { //look at left child only (recursively) const CEvaluationNode *child = dynamic_cast<const CEvaluationNode*>(this->getChild()); const CEvaluationNode *tmp = NULL; if (child) tmp = child->findTopMinus(callParameters); if (tmp) return tmp; } return NULL; } <|endoftext|>
<commit_before>#pragma once #include <regex> #include <optional> #include "acmacs-base/fmt.hh" // ====================================================================== // Support for multiple regex and replacements, see acmacs-virus/cc/reassortant.cc // ====================================================================== namespace acmacs::regex { struct look_replace_t { const std::regex look_for; std::vector<const char*> fmt; }; // returns pair of empty strings if no matches found template <typename Container> std::optional<std::vector<std::string>> scan_replace(std::string_view source, const Container& scan_data) { for (const auto& entry : scan_data) { if (std::cmatch match; std::regex_search(std::begin(source), std::end(source), match, entry.look_for)) { std::vector<std::string> result(entry.fmt.size()); std::transform(std::begin(entry.fmt), std::end(entry.fmt), std::begin(result), [&match](const char* fmt) { return match.format(fmt); }); return result; } } return {}; } } // ====================================================================== // fmt support for std::smatch and std::cmatch // ====================================================================== // specialization below follows fmt lib description, but it does not work due to ambiguity with // template <typename RangeT, typename Char> struct formatter<RangeT, Char, enable_if_t<fmt::is_range<RangeT, Char>::value>> // // template <typename Match> struct fmt::formatter<Match, std::enable_if_t<std::is_same_v<Match, std::smatch> || std::is_same_v<Match, std::cmatch>, char>> : fmt::formatter<acmacs::fmt_default_formatter> // ---------------------------------------------------------------------- namespace acmacs { template <typename Match> struct fmt_regex_match_formatter {}; } template <typename Match> struct fmt::formatter<acmacs::fmt_regex_match_formatter<Match>> : fmt::formatter<acmacs::fmt_default_formatter> { template <typename FormatCtx> auto format(const Match& mr, FormatCtx& ctx) { format_to(ctx.out(), "\"{}\" -> ({})[", mr.str(0), mr.size()); for (size_t nr = 1; nr <= mr.size(); ++nr) format_to(ctx.out(), " {}:\"{}\"", nr, mr.str(nr)); format_to(ctx.out(), " ]"); return ctx.out(); } }; template <> struct fmt::formatter<std::smatch> : fmt::formatter<acmacs::fmt_regex_match_formatter<std::smatch>> { }; template <> struct fmt::formatter<std::cmatch> : fmt::formatter<acmacs::fmt_regex_match_formatter<std::cmatch>> { }; // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <commit_msg>common regex constant<commit_after>#pragma once #include <regex> #include <optional> #include "acmacs-base/fmt.hh" // ====================================================================== // Support for multiple regex and replacements, see acmacs-virus/cc/reassortant.cc // ====================================================================== namespace acmacs::regex { constexpr auto icase = std::regex::icase | std::regex::ECMAScript | std::regex::optimize; struct look_replace_t { const std::regex look_for; std::vector<const char*> fmt; }; // returns pair of empty strings if no matches found template <typename Container> std::optional<std::vector<std::string>> scan_replace(std::string_view source, const Container& scan_data) { for (const auto& entry : scan_data) { if (std::cmatch match; std::regex_search(std::begin(source), std::end(source), match, entry.look_for)) { std::vector<std::string> result(entry.fmt.size()); std::transform(std::begin(entry.fmt), std::end(entry.fmt), std::begin(result), [&match](const char* fmt) { return match.format(fmt); }); return result; } } return {}; } } // ====================================================================== // fmt support for std::smatch and std::cmatch // ====================================================================== // specialization below follows fmt lib description, but it does not work due to ambiguity with // template <typename RangeT, typename Char> struct formatter<RangeT, Char, enable_if_t<fmt::is_range<RangeT, Char>::value>> // // template <typename Match> struct fmt::formatter<Match, std::enable_if_t<std::is_same_v<Match, std::smatch> || std::is_same_v<Match, std::cmatch>, char>> : fmt::formatter<acmacs::fmt_default_formatter> // ---------------------------------------------------------------------- namespace acmacs { template <typename Match> struct fmt_regex_match_formatter {}; } template <typename Match> struct fmt::formatter<acmacs::fmt_regex_match_formatter<Match>> : fmt::formatter<acmacs::fmt_default_formatter> { template <typename FormatCtx> auto format(const Match& mr, FormatCtx& ctx) { format_to(ctx.out(), "\"{}\" -> ({})[", mr.str(0), mr.size()); for (size_t nr = 1; nr <= mr.size(); ++nr) format_to(ctx.out(), " {}:\"{}\"", nr, mr.str(nr)); format_to(ctx.out(), " ]"); return ctx.out(); } }; template <> struct fmt::formatter<std::smatch> : fmt::formatter<acmacs::fmt_regex_match_formatter<std::smatch>> { }; template <> struct fmt::formatter<std::cmatch> : fmt::formatter<acmacs::fmt_regex_match_formatter<std::cmatch>> { }; // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <|endoftext|>
<commit_before>/* Copyright (c) 2014-2015 DataStax Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef __CASS_STREAM_MANAGER_HPP_INCLUDED__ #define __CASS_STREAM_MANAGER_HPP_INCLUDED__ #include "scoped_ptr.hpp" #include <assert.h> #include <stdint.h> #include <string.h> #include <google/sparse_hash_map> #if defined(_MSC_VER) #include <intrin.h> #endif namespace cass { template <class T> class StreamManager { public: StreamManager(int protocol_version) : max_streams_(1 << (num_bytes_for_stream(protocol_version) * 8 - 1)) , num_words_(max_streams_ / NUM_BITS_PER_WORD) , offset_(0) , words_(new word_t[num_words_]) { pending_.set_deleted_key(-1); memset(words_.get(), 0xFF, sizeof(word_t) * num_words_); } int acquire(const T& item) { int stream = acquire_stream(); if (stream < 0) return -1; pending_[stream] = item; return stream; } void release(int stream) { assert(stream >= 0 && static_cast<size_t>(stream) < max_streams_); pending_.erase(stream); release_stream(stream); } bool get_pending_and_release(int stream, T& output) { typename google::sparse_hash_map<int, T>::iterator i = pending_.find(stream); if (i != pending_.end()) { output = i->second; pending_.erase(i); release_stream(stream); return true; } return false; } size_t available_streams() const { return max_streams_ - pending_.size(); } size_t pending_streams() const { return pending_.size(); } size_t max_streams() const { return max_streams_; } private: #if defined(_MSC_VER) && defined(_M_AMD64) typedef __int64 word_t; #else typedef unsigned long word_t; #endif static const size_t NUM_BITS_PER_WORD = sizeof(word_t) * 8; static inline int num_bytes_for_stream(int protocol_version) { if (protocol_version >= 3) { return 2; } else { return 1; } } static inline int count_trailing_zeros(word_t word) { #if defined(__GNUC__) return __builtin_ctzl(word); #elif defined(_MSC_VER) unsigned long index; # if defined(_M_AMD64) assert(_BitScanForward64(&index, word) != 0); # else assert(_BitScanForward(&index, word) != 0); # endif return static_cast<int>(index); #else #endif } private: int acquire_stream() { const size_t offset = offset_; const size_t num_words = num_words_; ++offset_; for (size_t i = 0; i < num_words; ++i) { size_t index = (i + offset) % num_words; int stream = get_and_set_first_available_stream(index); if (stream >= 0) return stream + (NUM_BITS_PER_WORD * index); } return -1; } inline void release_stream(int stream) { assert((words_[stream / NUM_BITS_PER_WORD] & (1L << (stream % NUM_BITS_PER_WORD))) == 0); words_[stream / NUM_BITS_PER_WORD] |= (static_cast<word_t>(1) << (stream % NUM_BITS_PER_WORD)); } inline int get_and_set_first_available_stream(size_t index) { word_t word = words_[index]; if (word == 0) return -1; int stream = count_trailing_zeros(word); words_[index] ^= (static_cast<word_t>(1) << stream); return stream; } private: const size_t max_streams_; const size_t num_words_; size_t offset_; ScopedPtr<word_t[]> words_; google::sparse_hash_map<int, T> pending_; }; } // namespace cass #endif <commit_msg>Moved to using dense hash map<commit_after>/* Copyright (c) 2014-2015 DataStax Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef __CASS_STREAM_MANAGER_HPP_INCLUDED__ #define __CASS_STREAM_MANAGER_HPP_INCLUDED__ #include "macros.hpp" #include "scoped_ptr.hpp" #include <assert.h> #include <stdint.h> #include <string.h> #include <google/dense_hash_map> #if defined(_MSC_VER) #include <intrin.h> #endif namespace cass { template <class T> class StreamManager { public: StreamManager(int protocol_version) : max_streams_(1 << (num_bytes_for_stream(protocol_version) * 8 - 1)) , num_words_(max_streams_ / NUM_BITS_PER_WORD) , offset_(0) , words_(new word_t[num_words_]) { pending_.set_empty_key(-1); pending_.set_deleted_key(-2); pending_.min_load_factor(0.0); memset(words_.get(), 0xFF, sizeof(word_t) * num_words_); } int acquire(const T& item) { int stream = acquire_stream(); if (stream < 0) return -1; pending_[stream] = item; return stream; } void release(int stream) { assert(stream >= 0 && static_cast<size_t>(stream) < max_streams_); pending_.erase(stream); release_stream(stream); } bool get_pending_and_release(int stream, T& output) { typename google::dense_hash_map<int, T>::iterator i = pending_.find(stream); if (i != pending_.end()) { output = i->second; pending_.erase(i); release_stream(stream); return true; } return false; } size_t available_streams() const { return max_streams_ - pending_.size(); } size_t pending_streams() const { return pending_.size(); } size_t max_streams() const { return max_streams_; } private: #if defined(_MSC_VER) && defined(_M_AMD64) typedef __int64 word_t; #else typedef unsigned long word_t; #endif static const size_t NUM_BITS_PER_WORD = sizeof(word_t) * 8; static inline int num_bytes_for_stream(int protocol_version) { if (protocol_version >= 3) { return 2; } else { return 1; } } static inline int count_trailing_zeros(word_t word) { #if defined(__GNUC__) return __builtin_ctzl(word); #elif defined(_MSC_VER) unsigned long index; # if defined(_M_AMD64) assert(_BitScanForward64(&index, word) != 0); # else assert(_BitScanForward(&index, word) != 0); # endif return static_cast<int>(index); #else #endif } private: int acquire_stream() { const size_t offset = offset_; const size_t num_words = num_words_; ++offset_; for (size_t i = 0; i < num_words; ++i) { size_t index = (i + offset) % num_words; int stream = get_and_set_first_available_stream(index); if (stream >= 0) return stream + (NUM_BITS_PER_WORD * index); } return -1; } inline void release_stream(int stream) { assert((words_[stream / NUM_BITS_PER_WORD] & (1L << (stream % NUM_BITS_PER_WORD))) == 0); words_[stream / NUM_BITS_PER_WORD] |= (static_cast<word_t>(1) << (stream % NUM_BITS_PER_WORD)); } inline int get_and_set_first_available_stream(size_t index) { word_t word = words_[index]; if (word == 0) return -1; int stream = count_trailing_zeros(word); words_[index] ^= (static_cast<word_t>(1) << stream); return stream; } private: const size_t max_streams_; const size_t num_words_; size_t offset_; ScopedPtr<word_t[]> words_; google::dense_hash_map<int, T> pending_; private: DISALLOW_COPY_AND_ASSIGN(StreamManager); }; } // namespace cass #endif <|endoftext|>
<commit_before>/// /// @file PhiTiny.cpp /// /// Copyright (C) 2014 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include "PhiTiny.hpp" #include <stdint.h> #include <vector> #include <cassert> #include <cstddef> namespace { /// Thread-safe singleton without locking /// @note Meyer's singleton (static const Singleton instance) causes a /// race condition with MSVC 2013 and OpenMP /// const primecount::PhiTiny phiTiny; } namespace primecount { int64_t phi_tiny(int64_t x, int64_t a) { return phiTiny.phi(x, a); } const int64_t PhiTiny::MAX_A = 6; const int32_t PhiTiny::primes_[7] = { 0, 2, 3, 5, 7, 11, 13 }; /// prime_products_[n] = \prod_{i=1}^{n} primes_[i] const int32_t PhiTiny::prime_products_[7] = { 1, 2, 6, 30, 210, 2310, 30030 }; /// totients_[n] = \prod_{i=1}^{n} (primes_[i] - 1) const int32_t PhiTiny::totients_[7] = { 1, 1, 2, 8, 48, 480, 5760 }; PhiTiny::PhiTiny() { phi_cache_[0].push_back(0); // Initialize the phi_cache_ lookup tables for (int a = 1; a <= MAX_A; a++) { std::size_t size = prime_products_[a]; phi_cache_[a].reserve(size); for (int x = 0; x < size; x++) { int16_t phixa = static_cast<int16_t>(phi(x, a - 1) - phi(x / primes_[a], a - 1)); phi_cache_[a].push_back(phixa); } } } /// Partial sieve function (a.k.a. Legendre-sum). /// phi(x, a) counts the numbers <= x that are not divisible /// by any of the first a primes. /// @pre is_cached(a) == true. /// int64_t PhiTiny::phi(int64_t x, int64_t a) const { assert(x >= 0); assert(a <= MAX_A); return (x / prime_products_[a]) * totients_[a] + phi_cache_[a][x % prime_products_[a]]; } } // namespace primecount <commit_msg>Silence warning<commit_after>/// /// @file PhiTiny.cpp /// /// Copyright (C) 2014 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include "PhiTiny.hpp" #include <stdint.h> #include <vector> #include <cassert> namespace { /// Thread-safe singleton without locking /// @note Meyer's singleton (static const Singleton instance) causes a /// race condition with MSVC 2013 and OpenMP /// const primecount::PhiTiny phiTiny; } namespace primecount { int64_t phi_tiny(int64_t x, int64_t a) { return phiTiny.phi(x, a); } const int64_t PhiTiny::MAX_A = 6; const int32_t PhiTiny::primes_[7] = { 0, 2, 3, 5, 7, 11, 13 }; /// prime_products_[n] = \prod_{i=1}^{n} primes_[i] const int32_t PhiTiny::prime_products_[7] = { 1, 2, 6, 30, 210, 2310, 30030 }; /// totients_[n] = \prod_{i=1}^{n} (primes_[i] - 1) const int32_t PhiTiny::totients_[7] = { 1, 1, 2, 8, 48, 480, 5760 }; PhiTiny::PhiTiny() { phi_cache_[0].push_back(0); // Initialize the phi_cache_ lookup tables for (int a = 1; a <= MAX_A; a++) { int size = prime_products_[a]; std::vector<int16_t>& cache = phi_cache_[a]; cache.reserve(size); for (int x = 0; x < size; x++) { int16_t phixa = static_cast<int16_t>(phi(x, a - 1) - phi(x / primes_[a], a - 1)); cache.push_back(phixa); } } } /// Partial sieve function (a.k.a. Legendre-sum). /// phi(x, a) counts the numbers <= x that are not divisible /// by any of the first a primes. /// @pre is_cached(a) == true. /// int64_t PhiTiny::phi(int64_t x, int64_t a) const { assert(x >= 0); assert(a <= MAX_A); return (x / prime_products_[a]) * totients_[a] + phi_cache_[a][x % prime_products_[a]]; } } // namespace primecount <|endoftext|>
<commit_before>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved. // Copyright (c) 2021 by Apex.AI Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // SPDX-License-Identifier: Apache-2.0 #ifndef IOX_UTILS_CXX_HELPLETS_HPP #define IOX_UTILS_CXX_HELPLETS_HPP #include "iceoryx_utils/cxx/generic_raii.hpp" #include "iceoryx_utils/platform/platform_correction.hpp" #include <assert.h> #include <iostream> #include <limits> #include <type_traits> namespace iox { namespace cxx { namespace internal { inline void Require(const bool condition, const char* file, const int line, const char* function, const char* conditionString) { if (!condition) { std::cerr << "Condition: " << conditionString << " in " << function << " is violated. (" << file << ":" << line << ")" << std::endl; std::terminate(); } } /// @brief struct to find the best fitting unsigned integer type template <bool GreaterUint8, bool GreaterUint16, bool GreaterUint32> struct bestFittingTypeImpl { using Type_t = uint64_t; }; template <> struct bestFittingTypeImpl<false, false, false> { using Type_t = uint8_t; }; template <> struct bestFittingTypeImpl<true, false, false> { using Type_t = uint16_t; }; template <> struct bestFittingTypeImpl<true, true, false> { using Type_t = uint32_t; }; } // namespace internal // implementing C++ Core Guideline, I.6. Prefer Expects // see: // https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Ri-expects #define Expects(condition) internal::Require(condition, __FILE__, __LINE__, __PRETTY_FUNCTION__, #condition) // implementing C++ Core Guideline, I.8. Prefer Ensures // see: // https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Ri-ensures #define Ensures(condition) internal::Require(condition, __FILE__, __LINE__, __PRETTY_FUNCTION__, #condition) template <typename T, typename = typename std::enable_if<std::is_pointer<T>::value, void>::type> struct not_null { public: not_null(T t) : value(t) { Expects(t != nullptr); } constexpr operator T() const { return value; } private: T value; }; template <typename T, T Minimum> struct greater_or_equal { public: greater_or_equal(T t) : value(t) { Expects(t >= Minimum); } constexpr operator T() const { return value; } private: T value; }; template <typename T, T Minimum, T Maximum> struct range { public: range(T t) : value(t) { Expects(t >= Minimum && t <= Maximum); } constexpr operator T() const { return value; } private: T value; }; template <typename T> T align(const T value, const T alignment) { T remainder = value % alignment; return value + ((remainder == 0u) ? 0u : alignment - remainder); } /// @brief allocates aligned memory which can only be free'd by alignedFree /// @param[in] alignment, alignment of the memory /// @param[in] size, memory size /// @return void pointer to the aligned memory void* alignedAlloc(const uint64_t alignment, const uint64_t size) noexcept; /// @brief frees aligned memory allocated with alignedAlloc /// @param[in] memory, pointer to the aligned memory void alignedFree(void* const memory); /// template recursion stopper for maximum alignment calculation template <size_t s = 0> constexpr size_t maxAlignment() { return s; } /// calculate maximum alignment of supplied types template <typename T, typename... Args> constexpr size_t maxAlignment() { return alignof(T) > maxAlignment<Args...>() ? alignof(T) : maxAlignment<Args...>(); } /// template recursion stopper for maximum size calculation template <size_t s = 0> constexpr size_t maxSize() { return s; } /// calculate maximum size of supplied types template <typename T, typename... Args> constexpr size_t maxSize() { return sizeof(T) > maxSize<Args...>() ? sizeof(T) : maxSize<Args...>(); } /// @todo better name /// create a GenericRAII object to cleanup a static optional object at the end of the scope /// @param [in] T memory container which has emplace(...) and reset /// @param [in] CTorArgs ctor types for the object to construct /// @param [in] memory is a reference to a memory container, e.g. cxx::optional /// @param [in] ctorArgs ctor arguments for the object to construct /// @return cxx::GenericRAII template <typename T, typename... CTorArgs> GenericRAII makeScopedStatic(T& memory, CTorArgs&&... ctorArgs) { memory.emplace(std::forward<CTorArgs>(ctorArgs)...); return GenericRAII([] {}, [&memory] { memory.reset(); }); } /// Convert Enum class type to string template <typename T, typename Enumeration> const char* convertEnumToString(T port, const Enumeration source) { return port[static_cast<size_t>(source)]; } /// cast an enum to its underlying type template <typename enum_type> auto enumTypeAsUnderlyingType(enum_type const value) -> typename std::underlying_type<enum_type>::type { return static_cast<typename std::underlying_type<enum_type>::type>(value); } /// calls a given functor for every element in a given container /// @tparam[in] Container type which must be iteratable /// @tparam[in] Functor which has one argument, the element type of the container /// @param[in] c container which should be iterated /// @param[in] f functor which should be applied to every element template <typename Container, typename Functor> void forEach(Container& c, const Functor& f) noexcept { for (auto& element : c) { f(element); } } /// @brief Get the size of a string represented by a char array at compile time. /// @tparam The size of the char array filled out by the compiler. /// @param[in] The actual content of the char array is not of interest. Its just the size of the array that matters. /// @return Returns the size of a char array at compile time. template <uint64_t SizeValue> static constexpr uint64_t strlen2(char const (&/*notInterested*/)[SizeValue]) { return SizeValue - 1; } /// @brief get the best fitting unsigned integer type for a given value at compile time template <uint64_t Value> struct bestFittingType { using Type_t = typename internal::bestFittingTypeImpl<(Value > std::numeric_limits<uint8_t>::max()), (Value > std::numeric_limits<uint16_t>::max()), (Value > std::numeric_limits<uint32_t>::max())>::Type_t; }; template <uint64_t Value> using BestFittingType_t = typename bestFittingType<Value>::Type_t; /// @brief if a function has a return value which you do not want to use then you can wrap the function with that macro. /// Purpose is to suppress the unused compiler warning by adding an attribute to the return value /// @param[in] name name of the function where the return value is not used. /// @code /// uint32_t foo(); /// DISCARD_RESULT(foo()); // suppress compiler warning for unused return value /// @endcode // clang-format off #define DISCARD_RESULT_VARIABLE_GENERATOR(name, suffix) name ## _ ## suffix #define DISCARD_RESULT_VARIABLE(name, suffix) DISCARD_RESULT_VARIABLE_GENERATOR(name, suffix) #define DISCARD_RESULT(expr) auto DISCARD_RESULT_VARIABLE(unusedOnLine, __LINE__) [[gnu::unused]] = expr // clang-format on } // namespace cxx } // namespace iox #endif // IOX_UTILS_CXX_HELPLETS_HPP <commit_msg>iox-#350 ignore warnings for comparisons in bestFittingType implementation<commit_after>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved. // Copyright (c) 2021 by Apex.AI Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // SPDX-License-Identifier: Apache-2.0 #ifndef IOX_UTILS_CXX_HELPLETS_HPP #define IOX_UTILS_CXX_HELPLETS_HPP #include "iceoryx_utils/cxx/generic_raii.hpp" #include "iceoryx_utils/platform/platform_correction.hpp" #include <assert.h> #include <iostream> #include <limits> #include <type_traits> namespace iox { namespace cxx { namespace internal { inline void Require(const bool condition, const char* file, const int line, const char* function, const char* conditionString) { if (!condition) { std::cerr << "Condition: " << conditionString << " in " << function << " is violated. (" << file << ":" << line << ")" << std::endl; std::terminate(); } } /// @brief struct to find the best fitting unsigned integer type template <bool GreaterUint8, bool GreaterUint16, bool GreaterUint32> struct bestFittingTypeImpl { using Type_t = uint64_t; }; template <> struct bestFittingTypeImpl<false, false, false> { using Type_t = uint8_t; }; template <> struct bestFittingTypeImpl<true, false, false> { using Type_t = uint16_t; }; template <> struct bestFittingTypeImpl<true, true, false> { using Type_t = uint32_t; }; } // namespace internal // implementing C++ Core Guideline, I.6. Prefer Expects // see: // https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Ri-expects #define Expects(condition) internal::Require(condition, __FILE__, __LINE__, __PRETTY_FUNCTION__, #condition) // implementing C++ Core Guideline, I.8. Prefer Ensures // see: // https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Ri-ensures #define Ensures(condition) internal::Require(condition, __FILE__, __LINE__, __PRETTY_FUNCTION__, #condition) template <typename T, typename = typename std::enable_if<std::is_pointer<T>::value, void>::type> struct not_null { public: not_null(T t) : value(t) { Expects(t != nullptr); } constexpr operator T() const { return value; } private: T value; }; template <typename T, T Minimum> struct greater_or_equal { public: greater_or_equal(T t) : value(t) { Expects(t >= Minimum); } constexpr operator T() const { return value; } private: T value; }; template <typename T, T Minimum, T Maximum> struct range { public: range(T t) : value(t) { Expects(t >= Minimum && t <= Maximum); } constexpr operator T() const { return value; } private: T value; }; template <typename T> T align(const T value, const T alignment) { T remainder = value % alignment; return value + ((remainder == 0u) ? 0u : alignment - remainder); } /// @brief allocates aligned memory which can only be free'd by alignedFree /// @param[in] alignment, alignment of the memory /// @param[in] size, memory size /// @return void pointer to the aligned memory void* alignedAlloc(const uint64_t alignment, const uint64_t size) noexcept; /// @brief frees aligned memory allocated with alignedAlloc /// @param[in] memory, pointer to the aligned memory void alignedFree(void* const memory); /// template recursion stopper for maximum alignment calculation template <size_t s = 0> constexpr size_t maxAlignment() { return s; } /// calculate maximum alignment of supplied types template <typename T, typename... Args> constexpr size_t maxAlignment() { return alignof(T) > maxAlignment<Args...>() ? alignof(T) : maxAlignment<Args...>(); } /// template recursion stopper for maximum size calculation template <size_t s = 0> constexpr size_t maxSize() { return s; } /// calculate maximum size of supplied types template <typename T, typename... Args> constexpr size_t maxSize() { return sizeof(T) > maxSize<Args...>() ? sizeof(T) : maxSize<Args...>(); } /// @todo better name /// create a GenericRAII object to cleanup a static optional object at the end of the scope /// @param [in] T memory container which has emplace(...) and reset /// @param [in] CTorArgs ctor types for the object to construct /// @param [in] memory is a reference to a memory container, e.g. cxx::optional /// @param [in] ctorArgs ctor arguments for the object to construct /// @return cxx::GenericRAII template <typename T, typename... CTorArgs> GenericRAII makeScopedStatic(T& memory, CTorArgs&&... ctorArgs) { memory.emplace(std::forward<CTorArgs>(ctorArgs)...); return GenericRAII([] {}, [&memory] { memory.reset(); }); } /// Convert Enum class type to string template <typename T, typename Enumeration> const char* convertEnumToString(T port, const Enumeration source) { return port[static_cast<size_t>(source)]; } /// cast an enum to its underlying type template <typename enum_type> auto enumTypeAsUnderlyingType(enum_type const value) -> typename std::underlying_type<enum_type>::type { return static_cast<typename std::underlying_type<enum_type>::type>(value); } /// calls a given functor for every element in a given container /// @tparam[in] Container type which must be iteratable /// @tparam[in] Functor which has one argument, the element type of the container /// @param[in] c container which should be iterated /// @param[in] f functor which should be applied to every element template <typename Container, typename Functor> void forEach(Container& c, const Functor& f) noexcept { for (auto& element : c) { f(element); } } /// @brief Get the size of a string represented by a char array at compile time. /// @tparam The size of the char array filled out by the compiler. /// @param[in] The actual content of the char array is not of interest. Its just the size of the array that matters. /// @return Returns the size of a char array at compile time. template <uint64_t SizeValue> static constexpr uint64_t strlen2(char const (&/*notInterested*/)[SizeValue]) { return SizeValue - 1; } /// @brief get the best fitting unsigned integer type for a given value at compile time template <uint64_t Value> struct bestFittingType { /// ignore the warnings because we need the comparisons to find the best fitting type #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wtype-limits" using Type_t = typename internal::bestFittingTypeImpl<(Value > std::numeric_limits<uint8_t>::max()), (Value > std::numeric_limits<uint16_t>::max()), (Value > std::numeric_limits<uint32_t>::max())>::Type_t; #pragma GCC diagnostic pop }; template <uint64_t Value> using BestFittingType_t = typename bestFittingType<Value>::Type_t; /// @brief if a function has a return value which you do not want to use then you can wrap the function with that macro. /// Purpose is to suppress the unused compiler warning by adding an attribute to the return value /// @param[in] name name of the function where the return value is not used. /// @code /// uint32_t foo(); /// DISCARD_RESULT(foo()); // suppress compiler warning for unused return value /// @endcode // clang-format off #define DISCARD_RESULT_VARIABLE_GENERATOR(name, suffix) name ## _ ## suffix #define DISCARD_RESULT_VARIABLE(name, suffix) DISCARD_RESULT_VARIABLE_GENERATOR(name, suffix) #define DISCARD_RESULT(expr) auto DISCARD_RESULT_VARIABLE(unusedOnLine, __LINE__) [[gnu::unused]] = expr // clang-format on } // namespace cxx } // namespace iox #endif // IOX_UTILS_CXX_HELPLETS_HPP <|endoftext|>
<commit_before>#include "parallel-hashmap/parallel_hashmap/phmap.h" #include "smhasher/meow_hash_x64_aesni.h" #include "wyhash/wyhash.h" #include "xxHash/xxhash.c" #include "t1ha/t1ha.h" #include <sys/time.h> #include <iostream> #include <fstream> #include <sstream> #include <vector> using namespace std; //struct hasher{ size_t operator()(const string &s)const{ return wyhash(s.c_str(),s.size(),34432,_wyp); }}; //struct full_hasher{ size_t operator()(void *p, uint64_t len, uint64_t seed)const{ return wyhash(p,len,seed,_wyp); }}; struct hasher{ size_t operator()(const string &s)const{ return XXH3_64bits_withSeed(s.c_str(),s.size(),34432); }}; struct full_hasher{ size_t operator()(void *p, uint64_t len, uint64_t seed)const{ return XXH3_64bits_withSeed(p,len,seed); }}; uint64_t bench_hash(vector<string> &v, string name){ hasher h; full_hasher f; timeval beg, end; uint64_t dummy=0, N=v.size(), R=0x10000000ull/N; cout.precision(2); cout.setf(ios::fixed); cout<<name<<(name.size()<8?"\t\t":"\t"); for(size_t i=0; i<N; i++) dummy+=h(v[i]); gettimeofday(&beg,NULL); for(size_t r=0; r<R; r++) for(size_t i=0; i<N; i++) dummy+=h(v[i]); gettimeofday(&end,NULL); cout<<1e-6*R*N/(end.tv_sec-beg.tv_sec+1e-6*(end.tv_usec-beg.tv_usec))<<"\t"; phmap::flat_hash_map<string,unsigned,hasher> ma; for(size_t i=0; i<N; i++) ma[v[i]]++; gettimeofday(&beg,NULL); for(size_t r=0; r<R; r++) for(size_t i=0; i<N; i++) dummy+=ma[v[i]]++; gettimeofday(&end,NULL); cout<<1e-6*R*N/(end.tv_sec-beg.tv_sec+1e-6*(end.tv_usec-beg.tv_usec))<<"\t"; char temp[128]; gettimeofday(&beg,NULL); //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Modify here !!!!!!!!!!!!!!!!!!!!!!!!!!!!!! for(size_t r=0; r<R; r++) for(size_t i=0; i<N; i++){ dummy+=f(temp,(dummy&31)+1,i); (*temp)++; } //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! gettimeofday(&end,NULL); cout<<1e-6*R*N/(end.tv_sec-beg.tv_sec+1e-6*(end.tv_usec-beg.tv_usec))<<"\t"; string s; s.resize(1024); dummy+=h(s); gettimeofday(&beg,NULL); for(size_t r=0; r<(1ull<<26); r++){ dummy+=h(s); s[0]++; } gettimeofday(&end,NULL); cout<<1e-9*(1ull<<26)*s.size()/(end.tv_sec-beg.tv_sec+1e-6*(end.tv_usec-beg.tv_usec))<<"\t"; s.resize(0x40000ull); dummy+=h(s); gettimeofday(&beg,NULL); for(size_t r=0; r<(1ull<<20); r++){ dummy+=h(s); s[0]++; } gettimeofday(&end,NULL); cout<<1e-9*(1ull<<20)*s.size()/(end.tv_sec-beg.tv_sec+1e-6*(end.tv_usec-beg.tv_usec))<<"\t"; s.resize(0x1000000ull); dummy+=h(s); gettimeofday(&beg,NULL); for(size_t r=0; r<4096; r++){ dummy+=h(s); s[0]++; } gettimeofday(&end,NULL); cout<<1e-9*4096*s.size()/(end.tv_sec-beg.tv_sec+1e-6*(end.tv_usec-beg.tv_usec))<<"\t"; s.resize(0x40000000ull); dummy+=h(s); gettimeofday(&beg,NULL); for(size_t r=0; r<64; r++){ dummy+=h(s); s[0]++; } gettimeofday(&end,NULL); cout<<1e-9*64*s.size()/(end.tv_sec-beg.tv_sec+1e-6*(end.tv_usec-beg.tv_usec))<<"\n"; return dummy; } int main(int ac, char **av){ string file="/usr/share/dict/words"; if(ac>1) file=av[1]; vector<string> v; string s; ifstream fi(file.c_str()); for(fi>>s; !fi.eof(); fi>>s) if(s.size()) v.push_back(s); fi.close(); uint64_t r=0; cout<<"Benchmarking\t"<<file<<'\n'; cout<<"HashFunction\tWords\tHashmap\tRand32\t1K\t256K\t16M\t1G\n"; r+=bench_hash(v,""); return r; } <commit_msg>Delete benchhash.cpp<commit_after><|endoftext|>
<commit_before>#ifndef OCLUTIL_REDUCE_HPP #define OCLUTIL_REDUCE_HPP /** * \file reduce.hpp * \author Denis Demidov <[email protected]> * \brief OpenCL vector reduction. */ #ifdef WIN32 # pragma warning(disable : 4290 4715) # define NOMINMAX #endif #include <vector> #include <sstream> #include <numeric> #include <limits> #include <CL/cl.hpp> #include <oclutil/vector.hpp> namespace clu { enum ReductionKind { SUM = 0, MAX = 1, MIN = 2 }; /// Parallel reduction of arbitrary expression. template <typename real, ReductionKind RDC> class Reductor { public: Reductor(const std::vector<cl::CommandQueue> &queue); template <class Expr> real operator()(const Expr &expr) const; private: cl::Context context; std::vector<cl::CommandQueue> queue; std::vector<uint> idx; mutable std::vector<real> hbuf; std::vector<clu::vector<real>> dbuf; template <class Expr> struct exdata { static bool compiled[3]; static cl::Kernel kernel[3]; static uint wgsize[3]; }; }; template <typename real, ReductionKind RDC> template <class Expr> bool Reductor<real,RDC>::exdata<Expr>::compiled[3] = {false, false, false}; template <typename real, ReductionKind RDC> template <class Expr> cl::Kernel Reductor<real,RDC>::exdata<Expr>::kernel[3]; template <typename real, ReductionKind RDC> template <class Expr> uint Reductor<real,RDC>::exdata<Expr>::wgsize[3]; template <typename real, ReductionKind RDC> Reductor<real,RDC>::Reductor(const std::vector<cl::CommandQueue> &queue) : context(queue[0].getInfo<CL_QUEUE_CONTEXT>()), queue(queue) { idx.reserve(queue.size() + 1); idx.push_back(0); for(auto q = queue.begin(); q != queue.end(); q++) { cl::Device d = q->getInfo<CL_QUEUE_DEVICE>(); uint bufsize = d.getInfo<CL_DEVICE_MAX_COMPUTE_UNITS>() * 2U; idx.push_back(idx.back() + bufsize); std::vector<cl::CommandQueue> lq(1, *q); dbuf.push_back(clu::vector<real>(lq, CL_MEM_READ_WRITE, bufsize)); } hbuf.resize(idx.back()); } template <typename real, ReductionKind RDC> template <class Expr> real Reductor<real,RDC>::operator()(const Expr &expr) const { if (!exdata<Expr>::compiled[RDC]) { std::ostringstream source; std::string kernel_name = std::string("reduce_") + expr.kernel_name(); std::ostringstream increment_line; switch (RDC) { case SUM: increment_line << "mySum += "; expr.kernel_expr(increment_line); increment_line << ";\n"; break; case MAX: increment_line << "mySum = max(mySum, "; expr.kernel_expr(increment_line); increment_line << ");\n"; break; case MIN: increment_line << "mySum = min(mySum, "; expr.kernel_expr(increment_line); increment_line << ");\n"; break; } source << "#if defined(cl_khr_fp64)\n" "# pragma OPENCL EXTENSION cl_khr_fp64: enable\n" "#elif defined(cl_amd_fp64)\n" "# pragma OPENCL EXTENSION cl_amd_fp64: enable\n" "#endif\n" << "typedef " << type_name<real>() << " real;\n" << "kernel void " << kernel_name << "(uint n"; expr.kernel_prm(source); source << ",\n\tglobal real *g_odata,\n" "\tlocal real *sdata\n" "\t)\n" "{\n" " uint tid = get_local_id(0);\n" " uint block_size = get_local_size(0);\n" " uint p = get_group_id(0) * block_size * 2 + tid;\n" " uint gridSize = get_num_groups(0) * block_size * 2;\n" " uint i;\n" "\n" " real mySum = "; switch(RDC) { case SUM: source << 0; break; case MAX: source << -std::numeric_limits<real>::max(); break; case MIN: source << std::numeric_limits<real>::max(); break; } source << ";\n" "\n" " while (p < n) {\n" " i = p;\n" " " << increment_line.str() << " i = p + block_size;\n" " if (i < n)\n" " " << increment_line.str() << " p += gridSize;\n" " }\n" "\n" " sdata[tid] = mySum;\n" " barrier(CLK_LOCAL_MEM_FENCE);\n" "\n"; switch (RDC) { case SUM: source << " if (block_size >= 512) { if (tid < 256) { sdata[tid] = mySum = mySum + sdata[tid + 256]; } barrier(CLK_LOCAL_MEM_FENCE); }\n" " if (block_size >= 256) { if (tid < 128) { sdata[tid] = mySum = mySum + sdata[tid + 128]; } barrier(CLK_LOCAL_MEM_FENCE); }\n" " if (block_size >= 128) { if (tid < 64) { sdata[tid] = mySum = mySum + sdata[tid + 64]; } barrier(CLK_LOCAL_MEM_FENCE); }\n" "\n" " if (tid < 32) {\n" " local volatile real* smem = sdata;\n" " if (block_size >= 64) { smem[tid] = mySum = mySum + smem[tid + 32]; }\n" " if (block_size >= 32) { smem[tid] = mySum = mySum + smem[tid + 16]; }\n" " if (block_size >= 16) { smem[tid] = mySum = mySum + smem[tid + 8]; }\n" " if (block_size >= 8) { smem[tid] = mySum = mySum + smem[tid + 4]; }\n" " if (block_size >= 4) { smem[tid] = mySum = mySum + smem[tid + 2]; }\n" " if (block_size >= 2) { smem[tid] = mySum = mySum + smem[tid + 1]; }\n" " }\n" "\n" " if (tid == 0) g_odata[get_group_id(0)] = sdata[0];\n" "}\n"; break; case MAX: source << " if (block_size >= 512) { if (tid < 256) { sdata[tid] = mySum = max(mySum, sdata[tid + 256]); } barrier(CLK_LOCAL_MEM_FENCE); }\n" " if (block_size >= 256) { if (tid < 128) { sdata[tid] = mySum = max(mySum, sdata[tid + 128]); } barrier(CLK_LOCAL_MEM_FENCE); }\n" " if (block_size >= 128) { if (tid < 64) { sdata[tid] = mySum = max(mySum, sdata[tid + 64]); } barrier(CLK_LOCAL_MEM_FENCE); }\n" "\n" " if (tid < 32) {\n" " local volatile real* smem = sdata;\n" " if (block_size >= 64) { smem[tid] = mySum = max(mySum, smem[tid + 32]); }\n" " if (block_size >= 32) { smem[tid] = mySum = max(mySum, smem[tid + 16]); }\n" " if (block_size >= 16) { smem[tid] = mySum = max(mySum, smem[tid + 8]); }\n" " if (block_size >= 8) { smem[tid] = mySum = max(mySum, smem[tid + 4]); }\n" " if (block_size >= 4) { smem[tid] = mySum = max(mySum, smem[tid + 2]); }\n" " if (block_size >= 2) { smem[tid] = mySum = max(mySum, smem[tid + 1]); }\n" " }\n" "\n" " if (tid == 0) g_odata[get_group_id(0)] = sdata[0];\n" "}\n"; break; case MIN: source << " if (block_size >= 512) { if (tid < 256) { sdata[tid] = mySum = min(mySum, sdata[tid + 256]); } barrier(CLK_LOCAL_MEM_FENCE); }\n" " if (block_size >= 256) { if (tid < 128) { sdata[tid] = mySum = min(mySum, sdata[tid + 128]); } barrier(CLK_LOCAL_MEM_FENCE); }\n" " if (block_size >= 128) { if (tid < 64) { sdata[tid] = mySum = min(mySum, sdata[tid + 64]); } barrier(CLK_LOCAL_MEM_FENCE); }\n" "\n" " if (tid < 32) {\n" " local volatile real* smem = sdata;\n" " if (block_size >= 64) { smem[tid] = mySum = min(mySum, smem[tid + 32]); }\n" " if (block_size >= 32) { smem[tid] = mySum = min(mySum, smem[tid + 16]); }\n" " if (block_size >= 16) { smem[tid] = mySum = min(mySum, smem[tid + 8]); }\n" " if (block_size >= 8) { smem[tid] = mySum = min(mySum, smem[tid + 4]); }\n" " if (block_size >= 4) { smem[tid] = mySum = min(mySum, smem[tid + 2]); }\n" " if (block_size >= 2) { smem[tid] = mySum = min(mySum, smem[tid + 1]); }\n" " }\n" "\n" " if (tid == 0) g_odata[get_group_id(0)] = sdata[0];\n" "}\n"; break; } std::vector<cl::Device> device; device.reserve(queue.size()); for(auto q = queue.begin(); q != queue.end(); q++) device.push_back(q->getInfo<CL_QUEUE_DEVICE>()); auto program = build_sources(context, source.str()); exdata<Expr>::kernel[RDC] = cl::Kernel(program, kernel_name.c_str()); exdata<Expr>::compiled[RDC] = true; exdata<Expr>::wgsize[RDC] = kernel_workgroup_size( exdata<Expr>::kernel[RDC], device); } for(uint d = 0; d < queue.size(); d++) { uint psize = expr.part_size(d); uint g_size = (idx[d + 1] - idx[d]) * exdata<Expr>::wgsize[RDC]; auto lmem = cl::__local(exdata<Expr>::wgsize[RDC] * sizeof(real)); uint pos = 0; exdata<Expr>::kernel[RDC].setArg(pos++, psize); expr.kernel_args(exdata<Expr>::kernel[RDC], d, pos); exdata<Expr>::kernel[RDC].setArg(pos++, dbuf[d]()); exdata<Expr>::kernel[RDC].setArg(pos++, lmem); queue[d].enqueueNDRangeKernel(exdata<Expr>::kernel[RDC], cl::NullRange, g_size, exdata<Expr>::wgsize[RDC]); } for(uint d = 0; d < queue.size(); d++) { copy(dbuf[d], &hbuf[idx[d]]); } switch(RDC) { case SUM: return std::accumulate( hbuf.begin(), hbuf.end(), static_cast<real>(0)); case MAX: return *std::max_element(hbuf.begin(), hbuf.end()); case MIN: return *std::min_element(hbuf.begin(), hbuf.end()); } } /// Sum of vector elements. template <typename real> real sum(const clu::vector<real> &x) { static Reductor<real,SUM> rdc(x.queue); return rdc(x); } /// Inner product of two vectors. template <typename real> real inner_product(const clu::vector<real> &x, const clu::vector<real> &y) { static Reductor<real,SUM> rdc(x.queue); return rdc(x * y); } } // namespace clu #endif <commit_msg>Bug fix in reduction for workgroup size >= 1024<commit_after>#ifndef OCLUTIL_REDUCE_HPP #define OCLUTIL_REDUCE_HPP /** * \file reduce.hpp * \author Denis Demidov <[email protected]> * \brief OpenCL vector reduction. */ #ifdef WIN32 # pragma warning(disable : 4290 4715) # define NOMINMAX #endif #include <vector> #include <sstream> #include <numeric> #include <limits> #include <CL/cl.hpp> #include <oclutil/vector.hpp> namespace clu { enum ReductionKind { SUM = 0, MAX = 1, MIN = 2 }; /// Parallel reduction of arbitrary expression. template <typename real, ReductionKind RDC> class Reductor { public: Reductor(const std::vector<cl::CommandQueue> &queue); template <class Expr> real operator()(const Expr &expr) const; private: cl::Context context; std::vector<cl::CommandQueue> queue; std::vector<uint> idx; mutable std::vector<real> hbuf; std::vector<clu::vector<real>> dbuf; template <class Expr> struct exdata { static bool compiled[3]; static cl::Kernel kernel[3]; static uint wgsize[3]; }; }; template <typename real, ReductionKind RDC> template <class Expr> bool Reductor<real,RDC>::exdata<Expr>::compiled[3] = {false, false, false}; template <typename real, ReductionKind RDC> template <class Expr> cl::Kernel Reductor<real,RDC>::exdata<Expr>::kernel[3]; template <typename real, ReductionKind RDC> template <class Expr> uint Reductor<real,RDC>::exdata<Expr>::wgsize[3]; template <typename real, ReductionKind RDC> Reductor<real,RDC>::Reductor(const std::vector<cl::CommandQueue> &queue) : context(queue[0].getInfo<CL_QUEUE_CONTEXT>()), queue(queue) { idx.reserve(queue.size() + 1); idx.push_back(0); for(auto q = queue.begin(); q != queue.end(); q++) { cl::Device d = q->getInfo<CL_QUEUE_DEVICE>(); uint bufsize = d.getInfo<CL_DEVICE_MAX_COMPUTE_UNITS>() * 2U; idx.push_back(idx.back() + bufsize); std::vector<cl::CommandQueue> lq(1, *q); dbuf.push_back(clu::vector<real>(lq, CL_MEM_READ_WRITE, bufsize)); } hbuf.resize(idx.back()); } template <typename real, ReductionKind RDC> template <class Expr> real Reductor<real,RDC>::operator()(const Expr &expr) const { if (!exdata<Expr>::compiled[RDC]) { std::ostringstream source; std::string kernel_name = std::string("reduce_") + expr.kernel_name(); std::ostringstream increment_line; switch (RDC) { case SUM: increment_line << "mySum += "; expr.kernel_expr(increment_line); increment_line << ";\n"; break; case MAX: increment_line << "mySum = max(mySum, "; expr.kernel_expr(increment_line); increment_line << ");\n"; break; case MIN: increment_line << "mySum = min(mySum, "; expr.kernel_expr(increment_line); increment_line << ");\n"; break; } source << "#if defined(cl_khr_fp64)\n" "# pragma OPENCL EXTENSION cl_khr_fp64: enable\n" "#elif defined(cl_amd_fp64)\n" "# pragma OPENCL EXTENSION cl_amd_fp64: enable\n" "#endif\n" << "typedef " << type_name<real>() << " real;\n" << "kernel void " << kernel_name << "(uint n"; expr.kernel_prm(source); source << ",\n\tglobal real *g_odata,\n" "\tlocal real *sdata\n" "\t)\n" "{\n" " uint tid = get_local_id(0);\n" " uint block_size = get_local_size(0);\n" " uint p = get_group_id(0) * block_size * 2 + tid;\n" " uint gridSize = get_num_groups(0) * block_size * 2;\n" " uint i;\n" "\n" " real mySum = "; switch(RDC) { case SUM: source << 0; break; case MAX: source << -std::numeric_limits<real>::max(); break; case MIN: source << std::numeric_limits<real>::max(); break; } source << ";\n" "\n" " while (p < n) {\n" " i = p;\n" " " << increment_line.str() << " i = p + block_size;\n" " if (i < n)\n" " " << increment_line.str() << " p += gridSize;\n" " }\n" "\n" " sdata[tid] = mySum;\n" " barrier(CLK_LOCAL_MEM_FENCE);\n" "\n"; switch (RDC) { case SUM: source << " if (block_size >= 1024) { if (tid < 512) { sdata[tid] = mySum = mySum + sdata[tid + 512]; } barrier(CLK_LOCAL_MEM_FENCE); }\n" " if (block_size >= 512) { if (tid < 256) { sdata[tid] = mySum = mySum + sdata[tid + 256]; } barrier(CLK_LOCAL_MEM_FENCE); }\n" " if (block_size >= 256) { if (tid < 128) { sdata[tid] = mySum = mySum + sdata[tid + 128]; } barrier(CLK_LOCAL_MEM_FENCE); }\n" " if (block_size >= 128) { if (tid < 64) { sdata[tid] = mySum = mySum + sdata[tid + 64]; } barrier(CLK_LOCAL_MEM_FENCE); }\n" "\n" " if (tid < 32) {\n" " local volatile real* smem = sdata;\n" " if (block_size >= 64) { smem[tid] = mySum = mySum + smem[tid + 32]; }\n" " if (block_size >= 32) { smem[tid] = mySum = mySum + smem[tid + 16]; }\n" " if (block_size >= 16) { smem[tid] = mySum = mySum + smem[tid + 8]; }\n" " if (block_size >= 8) { smem[tid] = mySum = mySum + smem[tid + 4]; }\n" " if (block_size >= 4) { smem[tid] = mySum = mySum + smem[tid + 2]; }\n" " if (block_size >= 2) { smem[tid] = mySum = mySum + smem[tid + 1]; }\n" " }\n" "\n" " if (tid == 0) g_odata[get_group_id(0)] = sdata[0];\n" "}\n"; break; case MAX: source << " if (block_size >= 1024) { if (tid < 512) { sdata[tid] = mySum = max(mySum, sdata[tid + 512]); } barrier(CLK_LOCAL_MEM_FENCE); }\n" " if (block_size >= 512) { if (tid < 256) { sdata[tid] = mySum = max(mySum, sdata[tid + 256]); } barrier(CLK_LOCAL_MEM_FENCE); }\n" " if (block_size >= 256) { if (tid < 128) { sdata[tid] = mySum = max(mySum, sdata[tid + 128]); } barrier(CLK_LOCAL_MEM_FENCE); }\n" " if (block_size >= 128) { if (tid < 64) { sdata[tid] = mySum = max(mySum, sdata[tid + 64]); } barrier(CLK_LOCAL_MEM_FENCE); }\n" "\n" " if (tid < 32) {\n" " local volatile real* smem = sdata;\n" " if (block_size >= 64) { smem[tid] = mySum = max(mySum, smem[tid + 32]); }\n" " if (block_size >= 32) { smem[tid] = mySum = max(mySum, smem[tid + 16]); }\n" " if (block_size >= 16) { smem[tid] = mySum = max(mySum, smem[tid + 8]); }\n" " if (block_size >= 8) { smem[tid] = mySum = max(mySum, smem[tid + 4]); }\n" " if (block_size >= 4) { smem[tid] = mySum = max(mySum, smem[tid + 2]); }\n" " if (block_size >= 2) { smem[tid] = mySum = max(mySum, smem[tid + 1]); }\n" " }\n" "\n" " if (tid == 0) g_odata[get_group_id(0)] = sdata[0];\n" "}\n"; break; case MIN: source << " if (block_size >= 1024) { if (tid < 512) { sdata[tid] = mySum = min(mySum, sdata[tid + 512]); } barrier(CLK_LOCAL_MEM_FENCE); }\n" " if (block_size >= 512) { if (tid < 256) { sdata[tid] = mySum = min(mySum, sdata[tid + 256]); } barrier(CLK_LOCAL_MEM_FENCE); }\n" " if (block_size >= 256) { if (tid < 128) { sdata[tid] = mySum = min(mySum, sdata[tid + 128]); } barrier(CLK_LOCAL_MEM_FENCE); }\n" " if (block_size >= 128) { if (tid < 64) { sdata[tid] = mySum = min(mySum, sdata[tid + 64]); } barrier(CLK_LOCAL_MEM_FENCE); }\n" "\n" " if (tid < 32) {\n" " local volatile real* smem = sdata;\n" " if (block_size >= 64) { smem[tid] = mySum = min(mySum, smem[tid + 32]); }\n" " if (block_size >= 32) { smem[tid] = mySum = min(mySum, smem[tid + 16]); }\n" " if (block_size >= 16) { smem[tid] = mySum = min(mySum, smem[tid + 8]); }\n" " if (block_size >= 8) { smem[tid] = mySum = min(mySum, smem[tid + 4]); }\n" " if (block_size >= 4) { smem[tid] = mySum = min(mySum, smem[tid + 2]); }\n" " if (block_size >= 2) { smem[tid] = mySum = min(mySum, smem[tid + 1]); }\n" " }\n" "\n" " if (tid == 0) g_odata[get_group_id(0)] = sdata[0];\n" "}\n"; break; } std::vector<cl::Device> device; device.reserve(queue.size()); for(auto q = queue.begin(); q != queue.end(); q++) device.push_back(q->getInfo<CL_QUEUE_DEVICE>()); auto program = build_sources(context, source.str()); exdata<Expr>::kernel[RDC] = cl::Kernel(program, kernel_name.c_str()); exdata<Expr>::compiled[RDC] = true; exdata<Expr>::wgsize[RDC] = kernel_workgroup_size( exdata<Expr>::kernel[RDC], device); // Strange bug(?) in g++: cannot call getWorkGroupInfo directly on // exdata<Expr>::kernel[RDC], but it works like this: cl::Kernel &krn = exdata<Expr>::kernel[RDC]; for(auto d = device.begin(); d != device.end(); d++) { uint smem = d->getInfo<CL_DEVICE_LOCAL_MEM_SIZE>() - krn.getWorkGroupInfo<CL_KERNEL_LOCAL_MEM_SIZE>(*d); while(exdata<Expr>::wgsize[RDC] * sizeof(real) > smem) exdata<Expr>::wgsize[RDC] /= 2; } } for(uint d = 0; d < queue.size(); d++) { uint psize = expr.part_size(d); uint g_size = (idx[d + 1] - idx[d]) * exdata<Expr>::wgsize[RDC]; auto lmem = cl::__local(exdata<Expr>::wgsize[RDC] * sizeof(real)); uint pos = 0; exdata<Expr>::kernel[RDC].setArg(pos++, psize); expr.kernel_args(exdata<Expr>::kernel[RDC], d, pos); exdata<Expr>::kernel[RDC].setArg(pos++, dbuf[d]()); exdata<Expr>::kernel[RDC].setArg(pos++, lmem); queue[d].enqueueNDRangeKernel(exdata<Expr>::kernel[RDC], cl::NullRange, g_size, exdata<Expr>::wgsize[RDC]); } for(uint d = 0; d < queue.size(); d++) { copy(dbuf[d], &hbuf[idx[d]]); } switch(RDC) { case SUM: return std::accumulate( hbuf.begin(), hbuf.end(), static_cast<real>(0)); case MAX: return *std::max_element(hbuf.begin(), hbuf.end()); case MIN: return *std::min_element(hbuf.begin(), hbuf.end()); } } /// Sum of vector elements. template <typename real> real sum(const clu::vector<real> &x) { static Reductor<real,SUM> rdc(x.queue); return rdc(x); } /// Inner product of two vectors. template <typename real> real inner_product(const clu::vector<real> &x, const clu::vector<real> &y) { static Reductor<real,SUM> rdc(x.queue); return rdc(x * y); } } // namespace clu #endif <|endoftext|>
<commit_before><commit_msg>Resolves: #i119450# Added EMR_ALPHABLEND case to EnhWMFReader<commit_after><|endoftext|>
<commit_before>#include <cstring> #include <iomanip> #include <iostream> #include <map> #include <vector> #include "hash.hpp" #include "hvectors.hpp" #include "slice.hpp" struct Block { hash256_t hash = {}; hash256_t prevBlockHash = {}; uint32_t bits; Block () {} Block (const hash256_t& hash, const hash256_t& prevBlockHash, const uint32_t bits) : hash(hash), prevBlockHash(prevBlockHash), bits(bits) {} }; // find all blocks who are not parents to any other blocks (aka, a chain tip) auto findChainTips (const HMap<hash256_t, Block>& blocks) { std::map<hash256_t, bool> hasChildren; for (const auto& blockIter : blocks) { const auto& block = blockIter.second; // ignore genesis block if (blocks.find(block.prevBlockHash) == blocks.end()) continue; hasChildren[block.prevBlockHash] = true; } std::vector<Block> tips; for (const auto& blockIter : blocks) { const auto& block = blockIter.second; // filter to only blocks who have no children if (hasChildren.find(block.hash) != hasChildren.end()) continue; tips.emplace_back(block); } return tips; } auto determineWork (const HMap<hash256_t, size_t>& workCache, const HMap<hash256_t, Block>& blocks, const Block source) { auto visitor = source; size_t totalWork = source.bits; // naively walk the chain while (true) { const auto prevBlockIter = blocks.find(visitor.prevBlockHash); if (prevBlockIter == blocks.end()) break; const auto prevBlockWorkCacheIter = workCache.find(visitor.prevBlockHash); if (prevBlockWorkCacheIter != workCache.end()) { totalWork += prevBlockWorkCacheIter->second; break; } visitor = prevBlockIter->second; totalWork += visitor.bits; } return totalWork; } auto findBestChain (const HMap<hash256_t, Block>& blocks) { auto bestBlock = Block(); size_t mostWork = 0; HMap<hash256_t, size_t> workCache; for (const auto& blockIter : blocks) { const auto& block = blockIter.second; const auto work = determineWork(workCache, blocks, block); workCache.insort(block.hash, work); if (work > mostWork) { bestBlock = block; mostWork = work; } } auto visitor = bestBlock; std::vector<Block> blockchain; blockchain.push_back(visitor); // walk the chain while (true) { const auto prevBlockIter = blocks.find(visitor.prevBlockHash); if (prevBlockIter == blocks.end()) break; visitor = prevBlockIter->second; blockchain.push_back(visitor); } std::reverse(blockchain.begin(), blockchain.end()); return blockchain; } void printerr_hash32 (hash256_t hash) { std::cerr << std::hex; for (size_t i = 31; i < 32; --i) { std::cerr << std::setw(2) << std::setfill('0') << (uint32_t) hash[i]; } std::cerr << std::dec; } int main () { HMap<hash256_t, Block> blocks; // read block headers from stdin until EOF { while (true) { uint8_t rbuf[80]; const auto read = fread(rbuf, sizeof(rbuf), 1, stdin); // EOF? if (read == 0) break; hash256_t hash, prevBlockHash; uint32_t bits; hash256(hash.begin(), rbuf, 80); memcpy(prevBlockHash.begin(), rbuf + 4, 32); memcpy(&bits, rbuf + 72, 4); blocks.emplace_back(std::make_pair(hash, Block(hash, prevBlockHash, bits))); } std::cerr << "Read " << blocks.size() << " headers" << std::endl; blocks.sort(); std::cerr << "Sorted " << blocks.size() << " headers" << std::endl; } // how many tips exist? { const auto chainTips = findChainTips(blocks); std::cerr << "Found " << chainTips.size() << " chain tips" << std::endl; } // what is the best? const auto bestBlockChain = findBestChain(blocks); // print some general information { const auto genesis = bestBlockChain.front(); const auto tip = bestBlockChain.back(); // output std::cerr << "Best chain" << std::endl; std::cerr << "- Height: " << bestBlockChain.size() - 1 << std::endl; std::cerr << "- Genesis: "; printerr_hash32(genesis.hash); std::cerr << std::endl << "- Tip: "; printerr_hash32(tip.hash); std::cerr << std::endl; } // output the best chain [in order] { HMap<hash256_t, uint32_t> blockChainMap; int32_t height = 0; for (const auto& block : bestBlockChain) { blockChainMap.push_back(std::make_pair(block.hash, height)); ++height; } blockChainMap.sort(); StackSlice<36> buffer; for (auto&& blockIter : blockChainMap) { auto _data = buffer.drop(0); _data.writeN(blockIter.first.begin(), 32); _data.write<uint32_t>(blockIter.second); assert(_data.length() == 0); fwrite(buffer.begin(), buffer.length(), 1, stdout); } } return 0; } <commit_msg>bestchain: simplify and clarify work calculations<commit_after>#include <cstring> #include <iomanip> #include <iostream> #include <map> #include <vector> #include "hash.hpp" #include "hvectors.hpp" #include "slice.hpp" struct Block { hash256_t hash = {}; hash256_t prevBlockHash = {}; uint32_t bits; Block () {} Block (const hash256_t& hash, const hash256_t& prevBlockHash, const uint32_t bits) : hash(hash), prevBlockHash(prevBlockHash), bits(bits) {} }; // find all blocks who are not parents to any other blocks (aka, a chain tip) auto findChainTips (const HMap<hash256_t, Block>& blocks) { std::map<hash256_t, bool> hasChildren; for (const auto& blockIter : blocks) { const auto& block = blockIter.second; // ignore genesis block if (blocks.find(block.prevBlockHash) == blocks.end()) continue; hasChildren[block.prevBlockHash] = true; } std::vector<Block> tips; for (const auto& blockIter : blocks) { const auto& block = blockIter.second; // filter to only blocks who have no children if (hasChildren.find(block.hash) != hasChildren.end()) continue; tips.emplace_back(block); } return tips; } auto determineWork (const HMap<hash256_t, size_t>& workCache, const HMap<hash256_t, Block>& blocks, Block visitor) { size_t totalWork = 0; // naively walk the chain while (true) { totalWork += visitor.bits; const auto prevBlockIter = blocks.find(visitor.prevBlockHash); // is the visitor a genesis block? (no prevBlockIter) if (prevBlockIter == blocks.end()) break; const auto prevBlockWorkCacheIter = workCache.find(visitor.prevBlockHash); if (prevBlockWorkCacheIter != workCache.end()) { totalWork += prevBlockWorkCacheIter->second; break; } visitor = prevBlockIter->second; } return totalWork; } auto findBestChain (const HMap<hash256_t, Block>& blocks) { auto bestBlock = Block(); size_t bestChainWork = 0; HMap<hash256_t, size_t> workCache; for (const auto& blockIter : blocks) { const auto& block = blockIter.second; const auto chainWork = determineWork(workCache, blocks, block); workCache.insort(block.hash, chainWork); if (chainWork > bestChainWork) { bestBlock = block; bestChainWork = chainWork; } } auto visitor = bestBlock; std::vector<Block> blockchain; blockchain.push_back(visitor); // walk the chain while (true) { const auto prevBlockIter = blocks.find(visitor.prevBlockHash); if (prevBlockIter == blocks.end()) break; visitor = prevBlockIter->second; blockchain.push_back(visitor); } std::reverse(blockchain.begin(), blockchain.end()); return blockchain; } void printerr_hash32 (hash256_t hash) { std::cerr << std::hex; for (size_t i = 31; i < 32; --i) { std::cerr << std::setw(2) << std::setfill('0') << (uint32_t) hash[i]; } std::cerr << std::dec; } int main () { HMap<hash256_t, Block> blocks; // read block headers from stdin until EOF { while (true) { uint8_t rbuf[80]; const auto read = fread(rbuf, sizeof(rbuf), 1, stdin); // EOF? if (read == 0) break; hash256_t hash, prevBlockHash; uint32_t bits; hash256(hash.begin(), rbuf, 80); memcpy(prevBlockHash.begin(), rbuf + 4, 32); memcpy(&bits, rbuf + 72, 4); blocks.emplace_back(std::make_pair(hash, Block(hash, prevBlockHash, bits))); } std::cerr << "Read " << blocks.size() << " headers" << std::endl; blocks.sort(); std::cerr << "Sorted " << blocks.size() << " headers" << std::endl; } // how many tips exist? { const auto chainTips = findChainTips(blocks); std::cerr << "Found " << chainTips.size() << " chain tips" << std::endl; } // what is the best? const auto bestBlockChain = findBestChain(blocks); // print some general information { const auto genesis = bestBlockChain.front(); const auto tip = bestBlockChain.back(); // output std::cerr << "Best chain" << std::endl; std::cerr << "- Height: " << bestBlockChain.size() - 1 << std::endl; std::cerr << "- Genesis: "; printerr_hash32(genesis.hash); std::cerr << std::endl << "- Tip: "; printerr_hash32(tip.hash); std::cerr << std::endl; } // output the best chain [in order] { HMap<hash256_t, uint32_t> blockChainMap; int32_t height = 0; for (const auto& block : bestBlockChain) { blockChainMap.push_back(std::make_pair(block.hash, height)); ++height; } blockChainMap.sort(); StackSlice<36> buffer; for (auto&& blockIter : blockChainMap) { auto _data = buffer.drop(0); _data.writeN(blockIter.first.begin(), 32); _data.write<uint32_t>(blockIter.second); assert(_data.length() == 0); fwrite(buffer.begin(), buffer.length(), 1, stdout); } } return 0; } <|endoftext|>
<commit_before>#include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdlib.h> #include <unistd.h> #include <netdb.h> #include <sys/uio.h> #include <string.h> #include <sstream> #include <istream> #include "socket.h" #include "Command.h" #include "CommandBulider.h" #include "macro.h" #include "Message.h" #include <stdlib.h> inline slist_t splitString(const std::string &s) { slist_t elems; std::istringstream stream(s); str_t str; while (std::getline(stream, str)) { elems.push_back(str); } return elems; } namespace rirc { Socket::Socket(str_t ip,uint32_t port,str_t username,command_handler_t commandHandler) :self(*this) ,m_ip(ip) ,m_username(username) ,m_port(port) ,m_commandHandler(commandHandler) ,m_socketfd(-1) { if (pthread_mutex_init(&m_lock, NULL) != 0) { __LOGS("\n mutex init failed\n"); exit(-1); } } Socket::~Socket() { pthread_mutex_destroy(&m_lock); } void Socket::connect() { struct sockaddr_in server; struct hostent *hserver = NULL; int socket = ::socket(AF_INET , SOCK_STREAM , 0); __CHECK(socket > 0); bzero(&server,sizeof(struct sockaddr_in)); hserver = gethostbyname(m_ip.data()); bcopy(hserver->h_addr, (char *)&server.sin_addr.s_addr,hserver->h_length); server.sin_family = AF_INET; server.sin_port = htons(m_port); __IF_DO(::connect(socket , (struct sockaddr *)&server , sizeof(server)) < 0, __LOGS("connect error"); return;); m_socketfd = socket; Command* cmds[3] = {CommandBulider::bulidPassCommand(m_username), CommandBulider::bulidNickCommand(m_username), CommandBulider::bulidUserCommand(m_username.data(), "tolmoon", "tolsun", ":Ronnie Reagan")}; for (int i = 0; i < 3; ++i) { Command* cmd = cmds[i]; self.sendCommand(*cmd); delete cmd; cmds[i] = NULL; } pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); int res = pthread_create(&m_thread, &attr, Socket::handleSocketStream, (void *)this); pthread_attr_destroy(&attr); __CHECK(res>0); } void Socket::disconnect() { Command* cmd = CommandBulider::bulidQuitCommand(""); self.sendCommand(*cmd); delete cmd; close(m_socketfd); __IF_DO(m_thread>0,pthread_cancel(m_thread);); } void Socket::sendCommand(const Command& cmd) const { const size_t size = cmd.length(); uint8_t *buf = new uint8_t[size]; cmd.serialization(buf,size); write(m_socketfd,buf,size); delete [] buf; } void* Socket::handleSocketStream(void* param) { const Socket& self = *((Socket*)param); uint8_t buf[512]; str_t message; ssize_t size = 0; do { message.clear(); size = 0; do{ bzero(buf,512*sizeof(uint8_t)); size = ::read(self.m_socketfd,buf,512); const str_t msg((char*)buf,size); message += msg; } while (size >= 512); if (message.size() > 0) { const slist_t array = ::splitString(message); for (const str_t & mesg : array) { Message msg = Message::parseMessage(mesg); pthread_mutex_lock((pthread_mutex_t*)&self.m_lock); self.m_commandHandler(msg,(Socket*)param); pthread_mutex_unlock((pthread_mutex_t*)&self.m_lock); } } } while (true); return NULL; } } <commit_msg>first commit<commit_after>#include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdlib.h> #include <unistd.h> #include <netdb.h> #include <sys/uio.h> #include <string.h> #include <sstream> #include <istream> #include "socket.h" #include "Command.h" #include "CommandBulider.h" #include "macro.h" #include "Message.h" #include <stdlib.h> inline slist_t splitString(const std::string &s) { slist_t elems; std::istringstream stream(s); str_t str; while (std::getline(stream, str)) { elems.push_back(str); } return elems; } namespace rirc { Socket::Socket(str_t ip,uint32_t port,str_t username,command_handler_t commandHandler) :self(*this) ,m_ip(ip) ,m_username(username) ,m_port(port) ,m_commandHandler(commandHandler) ,m_socketfd(-1) { if (pthread_mutex_init(&m_lock, NULL) != 0) { __LOGS("\n mutex init failed\n"); exit(-1); } } Socket::~Socket() { pthread_mutex_destroy(&m_lock); } void Socket::connect() { struct sockaddr_in server; struct hostent *hserver = NULL; int socket = ::socket(AF_INET , SOCK_STREAM , 0); __CHECK(socket > 0); bzero(&server,sizeof(struct sockaddr_in)); hserver = gethostbyname(m_ip.data()); bcopy(hserver->h_addr, (char *)&server.sin_addr.s_addr,hserver->h_length); server.sin_family = AF_INET; server.sin_port = htons(m_port); __IF_DO(::connect(socket , (struct sockaddr *)&server , sizeof(server)) < 0, __LOGS("connect error"); return;); m_socketfd = socket; Command* cmds[3] = {CommandBulider::bulidPassCommand(m_username), CommandBulider::bulidNickCommand(m_username), CommandBulider::bulidUserCommand(m_username.data(), "tolmoon", "tolsun", ":Ronnie Reagan")}; for (int i = 0; i < 3; ++i) { Command* cmd = cmds[i]; self.sendCommand(*cmd); delete cmd; cmds[i] = NULL; } pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); int res = pthread_create(&m_thread, &attr, Socket::handleSocketStream, (void *)this); pthread_attr_destroy(&attr); __CHECK(res>0); } void Socket::disconnect() { Command* cmd = CommandBulider::bulidQuitCommand(""); self.sendCommand(*cmd); delete cmd; close(m_socketfd); __IF_DO(m_thread>0,pthread_cancel(m_thread);); } void Socket::sendCommand(const Command& cmd) const { const size_t size = cmd.length(); uint8_t *buf = new uint8_t[size]; cmd.serialization(buf,size); write(m_socketfd,buf,size); delete [] buf; } void* Socket::handleSocketStream(void* param) { const Socket& self = *((Socket*)param); uint8_t buf[512]; str_t message; ssize_t size = 0; do { message.clear(); size = 0; do{ bzero(buf,512*sizeof(uint8_t)); size = ::read(self.m_socketfd,buf,512); const str_t msg((char*)buf,size); message += msg; } while (size >= 512); if (message.size() > 0) { const slist_t array = ::splitString(message); for (const str_t & mesg : array) { Message msg = Message::parseMessage(mesg); pthread_mutex_lock((pthread_mutex_t*)&self.m_lock); self.m_commandHandler(msg,(Socket*)param); pthread_mutex_unlock((pthread_mutex_t*)&self.m_lock); } } } while (true); return NULL; } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: gcach_ftyp.hxx,v $ * * $Revision: 1.28 $ * * last change: $Author: rt $ $Date: 2004-07-13 09:30:12 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SV_GCACHFTYP_HXX #define _SV_GCACHFTYP_HXX #include <glyphcache.hxx> #include <rtl/textcvt.h> #include <freetype/freetype.h> class FreetypeServerFont; struct FT_GlyphRec_; // ----------------------------------------------------------------------- // FtFontFile has the responsibility that a font file is only mapped once. // (#86621#) the old directly ft-managed solution caused it to be mapped // in up to nTTC*nSizes*nOrientation*nSynthetic times class FtFontFile { public: static FtFontFile* FindFontFile( const ::rtl::OString& rNativeFileName ); bool Map(); void Unmap(); const unsigned char* GetBuffer() const { return mpFileMap; } int GetFileSize() const { return mnFileSize; } const ::rtl::OString* GetFileName() const { return &maNativeFileName; } int GetLangBoost() const { return mnLangBoost; } private: FtFontFile( const ::rtl::OString& rNativeFileName ); const ::rtl::OString maNativeFileName; const unsigned char* mpFileMap; int mnFileSize; int mnRefCount; int mnLangBoost; }; // ----------------------------------------------------------------------- // FtFontInfo corresponds to an unscaled font face class FtFontInfo { public: FtFontInfo( const ImplDevFontAttributes&, const ::rtl::OString& rNativeFileName, int nFaceNum, int nFontId, int nSynthetic, const ExtraKernInfo* ); ~FtFontInfo(); const unsigned char* GetTable( const char*, ULONG* pLength=0 ) const; FT_FaceRec_* GetFaceFT(); void ReleaseFaceFT( FT_FaceRec_* ); const ::rtl::OString* GetFontFileName() const { return mpFontFile->GetFileName(); } int GetFaceNum() const { return mnFaceNum; } int GetSynthetic() const { return mnSynthetic; } int GetFontId() const { return mnFontId; } bool IsSymbolFont() const { return maDevFontAttributes.IsSymbolFont(); } const ImplFontAttributes& GetFontAttributes() const { return maDevFontAttributes; } void AnnounceFont( ImplDevFontList* ); int GetGlyphIndex( sal_UCS4 cChar ) const; void CacheGlyphIndex( sal_UCS4 cChar, int nGI ) const; bool HasExtraKerning() const; int GetExtraKernPairs( ImplKernPairData** ) const; int GetExtraGlyphKernValue( int nLeftGlyph, int nRightGlyph ) const; private: FT_FaceRec_* maFaceFT; FtFontFile* mpFontFile; const int mnFaceNum; int mnRefCount; const int mnSynthetic; int mnFontId; ImplDevFontAttributes maDevFontAttributes; // cache unicode->glyphid mapping because looking it up is expensive // TODO: change to hash_multimap when a use case requires a m:n mapping typedef ::std::hash_map<int,int> Int2IntMap; mutable Int2IntMap maChar2Glyph; mutable Int2IntMap maGlyph2Char; const ExtraKernInfo* mpExtraKernInfo; }; // these two inlines are very important for performance inline int FtFontInfo::GetGlyphIndex( sal_UCS4 cChar ) const { Int2IntMap::const_iterator it = maChar2Glyph.find( cChar ); if( it == maChar2Glyph.end() ) return -1; return it->second; } inline void FtFontInfo::CacheGlyphIndex( sal_UCS4 cChar, int nIndex ) const { maChar2Glyph[ cChar ] = nIndex; maGlyph2Char[ nIndex ] = cChar; } // ----------------------------------------------------------------------- class FreetypeManager { public: FreetypeManager(); ~FreetypeManager(); long AddFontDir( const String& rUrlName ); void AddFontFile( const rtl::OString& rNormalizedName, int nFaceNum, int nFontId, const ImplDevFontAttributes&, const ExtraKernInfo* ); void AnnounceFonts( ImplDevFontList* ) const; void ClearFontList(); FreetypeServerFont* CreateFont( const ImplFontSelectData& ); private: typedef ::std::hash_map<int,FtFontInfo*> FontList; FontList maFontList; int mnMaxFontId; int mnNextFontId; }; // ----------------------------------------------------------------------- class FreetypeServerFont : public ServerFont { public: FreetypeServerFont( const ImplFontSelectData&, FtFontInfo* ); virtual ~FreetypeServerFont(); virtual const ::rtl::OString* GetFontFileName() const { return mpFontInfo->GetFontFileName(); } virtual int GetFontFaceNum() const { return mpFontInfo->GetFaceNum(); } virtual bool TestFont() const; virtual void FetchFontMetric( ImplFontMetricData&, long& rFactor ) const; virtual int GetGlyphIndex( sal_UCS4 ) const; int GetRawGlyphIndex( sal_UCS4 ) const; int FixupGlyphIndex( int nGlyphIndex, sal_UCS4 ) const; virtual bool GetAntialiasAdvice( void ) const; virtual bool GetGlyphBitmap1( int nGlyphIndex, RawBitmap& ) const; virtual bool GetGlyphBitmap8( int nGlyphIndex, RawBitmap& ) const; virtual bool GetGlyphOutline( int nGlyphIndex, PolyPolygon& ) const; virtual int GetGlyphKernValue( int nLeftGlyph, int nRightGlyph ) const; virtual ULONG GetKernPairs( ImplKernPairData** ) const; const unsigned char* GetTable( const char* pName, ULONG* pLength ) { return mpFontInfo->GetTable( pName, pLength ); } int GetEmUnits() const; const FT_Size_Metrics& GetMetricsFT() const { return maSizeFT->metrics; } protected: friend class GlyphCache; int ApplyGlyphTransform( int nGlyphFlags, FT_GlyphRec_* ) const; virtual void InitGlyphData( int nGlyphIndex, GlyphData& ) const; virtual ULONG GetFontCodeRanges( sal_uInt32* pCodes ) const; bool ApplyGSUB( const ImplFontSelectData& ); virtual ServerFontLayoutEngine* GetLayoutEngine(); private: int mnWidth; FtFontInfo* mpFontInfo; FT_Int mnLoadFlags; double mfStretch; FT_FaceRec_* maFaceFT; FT_SizeRec_* maSizeFT; typedef ::std::hash_map<int,int> GlyphSubstitution; GlyphSubstitution maGlyphSubstitution; rtl_UnicodeToTextConverter maRecodeConverter; ServerFontLayoutEngine* mpLayoutEngine; }; // ----------------------------------------------------------------------- class ImplFTSFontData : public ImplFontData { private: FtFontInfo* mpFtFontInfo; enum { IFTSFONT_MAGIC = 0x1F150A1C }; public: ImplFTSFontData( FtFontInfo*, const ImplDevFontAttributes& ); virtual ~ImplFTSFontData(); FtFontInfo* GetFtFontInfo() const { return mpFtFontInfo; } virtual ImplFontEntry* CreateFontInstance( ImplFontSelectData& ) const; virtual ImplFontData* Clone() const { return new ImplFTSFontData( *this ); } virtual int GetFontId() const { return mpFtFontInfo->GetFontId(); } static bool CheckFontData( const ImplFontData& r ) { return r.CheckMagic( IFTSFONT_MAGIC ); } }; // ----------------------------------------------------------------------- #endif // _SV_GCACHFTYP_HXX <commit_msg>INTEGRATION: CWS ooo20040704 (1.27.34); FILE MERGED 2004/08/09 14:56:37 vg 1.27.34.4: RESYNC MERGED 1.27 1.28 Everything below this line will be added to the revision comment. 2004/07/12 14:02:25 haggai 1.27.34.3: #i31318# - Use ft2build.h to include freetype headers 2004/07/02 09:49:06 cmc 1.27.34.2: #i30891# revert header and namespace change 2004/06/28 14:49:08 cmc 1.27.34.1: #i30801# allow using system stl if possible<commit_after>/************************************************************************* * * $RCSfile: gcach_ftyp.hxx,v $ * * $Revision: 1.29 $ * * last change: $Author: rt $ $Date: 2004-09-08 15:08:12 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SV_GCACHFTYP_HXX #define _SV_GCACHFTYP_HXX #include <glyphcache.hxx> #include <rtl/textcvt.h> #include <ft2build.h> #include FT_FREETYPE_H class FreetypeServerFont; struct FT_GlyphRec_; // ----------------------------------------------------------------------- // FtFontFile has the responsibility that a font file is only mapped once. // (#86621#) the old directly ft-managed solution caused it to be mapped // in up to nTTC*nSizes*nOrientation*nSynthetic times class FtFontFile { public: static FtFontFile* FindFontFile( const ::rtl::OString& rNativeFileName ); bool Map(); void Unmap(); const unsigned char* GetBuffer() const { return mpFileMap; } int GetFileSize() const { return mnFileSize; } const ::rtl::OString* GetFileName() const { return &maNativeFileName; } int GetLangBoost() const { return mnLangBoost; } private: FtFontFile( const ::rtl::OString& rNativeFileName ); const ::rtl::OString maNativeFileName; const unsigned char* mpFileMap; int mnFileSize; int mnRefCount; int mnLangBoost; }; // ----------------------------------------------------------------------- // FtFontInfo corresponds to an unscaled font face class FtFontInfo { public: FtFontInfo( const ImplDevFontAttributes&, const ::rtl::OString& rNativeFileName, int nFaceNum, int nFontId, int nSynthetic, const ExtraKernInfo* ); ~FtFontInfo(); const unsigned char* GetTable( const char*, ULONG* pLength=0 ) const; FT_FaceRec_* GetFaceFT(); void ReleaseFaceFT( FT_FaceRec_* ); const ::rtl::OString* GetFontFileName() const { return mpFontFile->GetFileName(); } int GetFaceNum() const { return mnFaceNum; } int GetSynthetic() const { return mnSynthetic; } int GetFontId() const { return mnFontId; } bool IsSymbolFont() const { return maDevFontAttributes.IsSymbolFont(); } const ImplFontAttributes& GetFontAttributes() const { return maDevFontAttributes; } void AnnounceFont( ImplDevFontList* ); int GetGlyphIndex( sal_UCS4 cChar ) const; void CacheGlyphIndex( sal_UCS4 cChar, int nGI ) const; bool HasExtraKerning() const; int GetExtraKernPairs( ImplKernPairData** ) const; int GetExtraGlyphKernValue( int nLeftGlyph, int nRightGlyph ) const; private: FT_FaceRec_* maFaceFT; FtFontFile* mpFontFile; const int mnFaceNum; int mnRefCount; const int mnSynthetic; int mnFontId; ImplDevFontAttributes maDevFontAttributes; // cache unicode->glyphid mapping because looking it up is expensive // TODO: change to hash_multimap when a use case requires a m:n mapping typedef ::std::hash_map<int,int> Int2IntMap; mutable Int2IntMap maChar2Glyph; mutable Int2IntMap maGlyph2Char; const ExtraKernInfo* mpExtraKernInfo; }; // these two inlines are very important for performance inline int FtFontInfo::GetGlyphIndex( sal_UCS4 cChar ) const { Int2IntMap::const_iterator it = maChar2Glyph.find( cChar ); if( it == maChar2Glyph.end() ) return -1; return it->second; } inline void FtFontInfo::CacheGlyphIndex( sal_UCS4 cChar, int nIndex ) const { maChar2Glyph[ cChar ] = nIndex; maGlyph2Char[ nIndex ] = cChar; } // ----------------------------------------------------------------------- class FreetypeManager { public: FreetypeManager(); ~FreetypeManager(); long AddFontDir( const String& rUrlName ); void AddFontFile( const rtl::OString& rNormalizedName, int nFaceNum, int nFontId, const ImplDevFontAttributes&, const ExtraKernInfo* ); void AnnounceFonts( ImplDevFontList* ) const; void ClearFontList(); FreetypeServerFont* CreateFont( const ImplFontSelectData& ); private: typedef ::std::hash_map<int,FtFontInfo*> FontList; FontList maFontList; int mnMaxFontId; int mnNextFontId; }; // ----------------------------------------------------------------------- class FreetypeServerFont : public ServerFont { public: FreetypeServerFont( const ImplFontSelectData&, FtFontInfo* ); virtual ~FreetypeServerFont(); virtual const ::rtl::OString* GetFontFileName() const { return mpFontInfo->GetFontFileName(); } virtual int GetFontFaceNum() const { return mpFontInfo->GetFaceNum(); } virtual bool TestFont() const; virtual void FetchFontMetric( ImplFontMetricData&, long& rFactor ) const; virtual int GetGlyphIndex( sal_UCS4 ) const; int GetRawGlyphIndex( sal_UCS4 ) const; int FixupGlyphIndex( int nGlyphIndex, sal_UCS4 ) const; virtual bool GetAntialiasAdvice( void ) const; virtual bool GetGlyphBitmap1( int nGlyphIndex, RawBitmap& ) const; virtual bool GetGlyphBitmap8( int nGlyphIndex, RawBitmap& ) const; virtual bool GetGlyphOutline( int nGlyphIndex, PolyPolygon& ) const; virtual int GetGlyphKernValue( int nLeftGlyph, int nRightGlyph ) const; virtual ULONG GetKernPairs( ImplKernPairData** ) const; const unsigned char* GetTable( const char* pName, ULONG* pLength ) { return mpFontInfo->GetTable( pName, pLength ); } int GetEmUnits() const; const FT_Size_Metrics& GetMetricsFT() const { return maSizeFT->metrics; } protected: friend class GlyphCache; int ApplyGlyphTransform( int nGlyphFlags, FT_GlyphRec_* ) const; virtual void InitGlyphData( int nGlyphIndex, GlyphData& ) const; virtual ULONG GetFontCodeRanges( sal_uInt32* pCodes ) const; bool ApplyGSUB( const ImplFontSelectData& ); virtual ServerFontLayoutEngine* GetLayoutEngine(); private: int mnWidth; FtFontInfo* mpFontInfo; FT_Int mnLoadFlags; double mfStretch; FT_FaceRec_* maFaceFT; FT_SizeRec_* maSizeFT; typedef ::std::hash_map<int,int> GlyphSubstitution; GlyphSubstitution maGlyphSubstitution; rtl_UnicodeToTextConverter maRecodeConverter; ServerFontLayoutEngine* mpLayoutEngine; }; // ----------------------------------------------------------------------- class ImplFTSFontData : public ImplFontData { private: FtFontInfo* mpFtFontInfo; enum { IFTSFONT_MAGIC = 0x1F150A1C }; public: ImplFTSFontData( FtFontInfo*, const ImplDevFontAttributes& ); virtual ~ImplFTSFontData(); FtFontInfo* GetFtFontInfo() const { return mpFtFontInfo; } virtual ImplFontEntry* CreateFontInstance( ImplFontSelectData& ) const; virtual ImplFontData* Clone() const { return new ImplFTSFontData( *this ); } virtual int GetFontId() const { return mpFtFontInfo->GetFontId(); } static bool CheckFontData( const ImplFontData& r ) { return r.CheckMagic( IFTSFONT_MAGIC ); } }; // ----------------------------------------------------------------------- #endif // _SV_GCACHFTYP_HXX <|endoftext|>
<commit_before>// Copyright (c) 2014 The Caroline authors. All rights reserved. // Use of this source file is governed by a MIT license that can be found in the // LICENSE file. // Author: Kukleva Anna <[email protected]> #include "core/camera_calibration.h" #include <vector> #include "core/cameras.h" namespace core { Cameras CameraCalibration::calibrate(int nx, int ny, float square_size) { int n = nx * ny; int len; int count_of_pairs; cv::Matx33d K1_; cv::Matx33d K2_; cv::Matx33d R_; cv::Matx31d T_; cv::Matx33d E_; cv::Matx33d F_; std::vector<double> D1(5, 0); std::vector<double> D2(5, 0); cv::Size imageSize = {0, 0}; imageSize = left_images_.at(0).size(); len = left_images_.size(); // HARVEST CHESSBOARD 3D OBJECT POINT LIST: count_of_pairs = VPoints1.size(); std::vector<std::vector<cv::Point3f>> VobjectPoints(count_of_pairs); for (int i = 0; i < count_of_pairs; i++) { VobjectPoints[i] = object_points_; } first_ = CalebrationOneCamera(kLeft, nx, ny, square_size); D1 = D; second_ = CalebrationOneCamera(kRight, nx, ny, square_size); D2 = D; // StereoCalibrate cv::stereoCalibrate(VobjectPoints, VPoints1, VPoints2, first_, D1, second_, D2, imageSize, R_, T_, E_, F_); cv::Matx34d P1_(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0); cv::Matx34d P2_(R_(0, 0), R_(0, 1), R_(0, 2), T_(0, 0), R_(1, 0), R_(1, 1), R_(1, 2), T_(1, 0), R_(2, 0), R_(2, 1), R_(2, 2), T_(0, 0)); Cameras cameras_par; cameras_par.set_K1(first_); cameras_par.set_K2(second_); cameras_par.set_P1(P1_); cameras_par.set_P2(P2_); return cameras_par; } void CameraCalibration::addImagePair(const cv::Mat &image1, const cv::Mat &image2, int nx, int ny) { left_images_.push_back(image1); right_images_.push_back(image2); // harvest points of corners for one image std::vector<cv::Point2f> temp1(nx * ny); std::vector<cv::Point2f> temp2(nx * ny); int len; int result1 = 0; int result2 = 0; // Finds the positions of //internal corners of the chessboard result1 = cv::findChessboardCorners( image1, cv::Size(nx, ny), temp1); result2 = cv::findChessboardCorners( image2, cv::Size(nx, ny), temp2); if (result1 && result2) { // Refines the corner locations cv::cornerSubPix(image1, temp1, cv::Size(5, 5), cv::Size(-1, -1), cv::TermCriteria(cv::TermCriteria::EPS + cv::TermCriteria::COUNT, 30, 0.01)); cv::cornerSubPix(image2, temp2, cv::Size(11, 11), cv::Size(-1, -1), cv::TermCriteria(cv::TermCriteria::EPS + cv::TermCriteria::COUNT, 30, 0.01)); VPoints1.push_back(temp1); VPoints2.push_back(temp2); } } void CameraCalibration::HarvestChessboardIdealPointList( int nx, int ny, float square_size) { object_points_.resize(nx * ny); for (int i = 0; i < ny; i++) { for (int j = 0; j < nx; j++) { object_points_[i*nx+j] = cv::Point3f(i*square_size, j*square_size, 0); } } } cv::Matx33d CameraCalibration::CalebrationOneCamera(int CameraOrientation, int nx, int ny, float square_size) { std::vector<std::vector<cv::Point2f>> VPoints; std::vector<cv::Mat> images; if (CameraOrientation == kLeft) { images = left_images_; VPoints = VPoints1; } else { images = right_images_; VPoints = VPoints2; } int result = 0; int n = nx * ny; int counter; int length; std::vector<cv::Point2f> temp(n); cv::Size imageSize = {0, 0}; imageSize = images.at(0).size(); cv::Matx33d K; std::vector<cv::Mat> vrvec; std::vector<cv::Mat> tvec; length = images.size(); counter = VPoints.size(); std::vector<std::vector<cv::Point3f>> VobjectPoints(counter); for (int i = 0; i < counter; i++) { VobjectPoints[i] = object_points_; } cv::setIdentity(K); cv::calibrateCamera( VobjectPoints, VPoints, imageSize, K, D, vrvec, tvec, 0, cv::TermCriteria(cv::TermCriteria::EPS + cv::TermCriteria::COUNT, 30, 0.01)); return K; } } // namespace core <commit_msg>#58: Style was fixed.<commit_after>// Copyright (c) 2014 The Caroline authors. All rights reserved. // Use of this source file is governed by a MIT license that can be found in the // LICENSE file. // Author: Kukleva Anna <[email protected]> #include "core/camera_calibration.h" #include <vector> #include "core/cameras.h" namespace core { Cameras CameraCalibration::calibrate(int nx, int ny, float square_size) { int n = nx * ny; int len; int count_of_pairs; cv::Matx33d K1_; cv::Matx33d K2_; cv::Matx33d R_; cv::Matx31d T_; cv::Matx33d E_; cv::Matx33d F_; std::vector<double> D1(5, 0); std::vector<double> D2(5, 0); cv::Size imageSize = {0, 0}; imageSize = left_images_.at(0).size(); len = left_images_.size(); // HARVEST CHESSBOARD 3D OBJECT POINT LIST: count_of_pairs = VPoints1.size(); std::vector<std::vector<cv::Point3f>> VobjectPoints(count_of_pairs); for (int i = 0; i < count_of_pairs; i++) { VobjectPoints[i] = object_points_; } first_ = CalebrationOneCamera(kLeft, nx, ny, square_size); D1 = D; second_ = CalebrationOneCamera(kRight, nx, ny, square_size); D2 = D; // StereoCalibrate cv::stereoCalibrate(VobjectPoints, VPoints1, VPoints2, first_, D1, second_, D2, imageSize, R_, T_, E_, F_); cv::Matx34d P1_(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0); cv::Matx34d P2_(R_(0, 0), R_(0, 1), R_(0, 2), T_(0, 0), R_(1, 0), R_(1, 1), R_(1, 2), T_(1, 0), R_(2, 0), R_(2, 1), R_(2, 2), T_(0, 0)); Cameras cameras_par; cameras_par.set_K1(first_); cameras_par.set_K2(second_); cameras_par.set_P1(P1_); cameras_par.set_P2(P2_); return cameras_par; } void CameraCalibration::addImagePair(const cv::Mat &image1, const cv::Mat &image2, int nx, int ny) { left_images_.push_back(image1); right_images_.push_back(image2); // harvest points of corners for one image std::vector<cv::Point2f> temp1(nx * ny); std::vector<cv::Point2f> temp2(nx * ny); int len; int result1 = 0; int result2 = 0; // Finds the positions of // internal corners of the chessboard result1 = cv::findChessboardCorners( image1, cv::Size(nx, ny), temp1); result2 = cv::findChessboardCorners( image2, cv::Size(nx, ny), temp2); if (result1 && result2) { // Refines the corner locations cv::cornerSubPix(image1, temp1, cv::Size(5, 5), cv::Size(-1, -1), cv::TermCriteria(cv::TermCriteria::EPS + cv::TermCriteria::COUNT, 30, 0.01)); cv::cornerSubPix(image2, temp2, cv::Size(11, 11), cv::Size(-1, -1), cv::TermCriteria(cv::TermCriteria::EPS + cv::TermCriteria::COUNT, 30, 0.01)); VPoints1.push_back(temp1); VPoints2.push_back(temp2); } } void CameraCalibration::HarvestChessboardIdealPointList( int nx, int ny, float square_size) { object_points_.resize(nx * ny); for (int i = 0; i < ny; i++) { for (int j = 0; j < nx; j++) { object_points_[i*nx+j] = cv::Point3f(i*square_size, j*square_size, 0); } } } cv::Matx33d CameraCalibration::CalebrationOneCamera(int CameraOrientation, int nx, int ny, float square_size) { std::vector<std::vector<cv::Point2f>> VPoints; std::vector<cv::Mat> images; if (CameraOrientation == kLeft) { images = left_images_; VPoints = VPoints1; } else { images = right_images_; VPoints = VPoints2; } int result = 0; int n = nx * ny; int counter; int length; std::vector<cv::Point2f> temp(n); cv::Size imageSize = {0, 0}; imageSize = images.at(0).size(); cv::Matx33d K; std::vector<cv::Mat> vrvec; std::vector<cv::Mat> tvec; length = images.size(); counter = VPoints.size(); std::vector<std::vector<cv::Point3f>> VobjectPoints(counter); for (int i = 0; i < counter; i++) { VobjectPoints[i] = object_points_; } cv::setIdentity(K); cv::calibrateCamera( VobjectPoints, VPoints, imageSize, K, D, vrvec, tvec, 0, cv::TermCriteria(cv::TermCriteria::EPS + cv::TermCriteria::COUNT, 30, 0.01)); return K; } } // namespace core <|endoftext|>
<commit_before>// // Copyright © 2017 Arm Ltd. All rights reserved. // SPDX-License-Identifier: MIT // #include "ClResizeBilinearFloatWorkload.hpp" #include <backends/cl/ClTensorHandle.hpp> #include <backends/CpuTensorHandle.hpp> #include <backends/cl/ClLayerSupport.hpp> #include <backends/aclCommon/ArmComputeUtils.hpp> #include <backends/aclCommon/ArmComputeTensorUtils.hpp> #include "ClWorkloadUtils.hpp" using namespace armnn::armcomputetensorutils; namespace armnn { ClResizeBilinearFloatWorkload::ClResizeBilinearFloatWorkload(const ResizeBilinearQueueDescriptor& descriptor, const WorkloadInfo& info) : FloatWorkload<ResizeBilinearQueueDescriptor>(descriptor, info) { m_Data.ValidateInputsOutputs("ClResizeBilinearFloatWorkload", 1, 1); arm_compute::ICLTensor& input = static_cast<IClTensorHandle*>(m_Data.m_Inputs[0])->GetTensor(); arm_compute::ICLTensor& output = static_cast<IClTensorHandle*>(m_Data.m_Outputs[0])->GetTensor(); (&input)->info()->set_data_layout(ConvertDataLayout(m_Data.m_Parameters.m_DataLayout)); (&output)->info()->set_data_layout(ConvertDataLayout(m_Data.m_Parameters.m_DataLayout)); m_ResizeBilinearLayer.configure(&input, &output, arm_compute::InterpolationPolicy::BILINEAR, arm_compute::BorderMode::REPLICATE, arm_compute::PixelValue(0.f), arm_compute::SamplingPolicy::TOP_LEFT); }; void ClResizeBilinearFloatWorkload::Execute() const { ARMNN_SCOPED_PROFILING_EVENT_CL("ClResizeBilinearFloatWorkload_Execute"); m_ResizeBilinearLayer.run(); } } //namespace armnn <commit_msg>IVGCVSW-1931: Refactor ClResizeBilinearFloatWorkload<commit_after>// // Copyright © 2017 Arm Ltd. All rights reserved. // SPDX-License-Identifier: MIT // #include "ClResizeBilinearFloatWorkload.hpp" #include <backends/cl/ClTensorHandle.hpp> #include <backends/CpuTensorHandle.hpp> #include <backends/cl/ClLayerSupport.hpp> #include <backends/aclCommon/ArmComputeUtils.hpp> #include <backends/aclCommon/ArmComputeTensorUtils.hpp> #include "ClWorkloadUtils.hpp" using namespace armnn::armcomputetensorutils; namespace armnn { ClResizeBilinearFloatWorkload::ClResizeBilinearFloatWorkload(const ResizeBilinearQueueDescriptor& descriptor, const WorkloadInfo& info) : FloatWorkload<ResizeBilinearQueueDescriptor>(descriptor, info) { m_Data.ValidateInputsOutputs("ClResizeBilinearFloatWorkload", 1, 1); arm_compute::ICLTensor& input = static_cast<IClTensorHandle*>(m_Data.m_Inputs[0])->GetTensor(); arm_compute::ICLTensor& output = static_cast<IClTensorHandle*>(m_Data.m_Outputs[0])->GetTensor(); arm_compute::DataLayout aclDataLayout = ConvertDataLayout(m_Data.m_Parameters.m_DataLayout); input.info()->set_data_layout(aclDataLayout); output.info()->set_data_layout(aclDataLayout); m_ResizeBilinearLayer.configure(&input, &output, arm_compute::InterpolationPolicy::BILINEAR, arm_compute::BorderMode::REPLICATE, arm_compute::PixelValue(0.f), arm_compute::SamplingPolicy::TOP_LEFT); }; void ClResizeBilinearFloatWorkload::Execute() const { ARMNN_SCOPED_PROFILING_EVENT_CL("ClResizeBilinearFloatWorkload_Execute"); m_ResizeBilinearLayer.run(); } } //namespace armnn <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkVectorTopology.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2000 Ken Martin, Will Schroeder, Bill Lorensen 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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. 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 REGENTS 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 <math.h> #include "vtkVectorTopology.h" #include "vtkObjectFactory.h" //------------------------------------------------------------------------------ vtkVectorTopology* vtkVectorTopology::New() { // First try to create the object from the vtkObjectFactory vtkObject* ret = vtkObjectFactory::CreateInstance("vtkVectorTopology"); if(ret) { return (vtkVectorTopology*)ret; } // If the factory was unable to create the object, then create it here. return new vtkVectorTopology; } // Construct object with distance 0.1. vtkVectorTopology::vtkVectorTopology() { this->Distance = 0.1; } void vtkVectorTopology::Execute() { int cellId, i, j, ptId, npts; int negative[3], positive[3], subId=0; float x[3], pcoords[3], *v; vtkCell *cell; vtkVectors *inVectors; vtkPoints *newPts; vtkCellArray *newVerts; vtkDataSet *input=(vtkDataSet *)this->Input; vtkPointData *pd=input->GetPointData(); vtkPolyData *output=(vtkPolyData *)this->Output; vtkPointData *outputPD=output->GetPointData(); float *weights=new float[input->GetMaxCellSize()]; // // Initialize self; check input; create output objects // vtkDebugMacro(<< "Executing vector topology..."); // make sure we have vector data if ( ! (inVectors = input->GetPointData()->GetVectors()) ) { vtkErrorMacro(<<"No vector data, can't create topology markers..."); return; } newPts = vtkPoints::New(); newPts->Allocate(100); newVerts = vtkCellArray::New(); newVerts->Allocate(newVerts->EstimateSize(1,100)); outputPD->CopyAllocate(pd); // // Find cells whose vector components all pass through zero // pcoords[0] = pcoords[1] = pcoords[2] = 0.5; newVerts->InsertNextCell(100); //temporary count for (cellId=0; cellId<input->GetNumberOfCells(); cellId++) { cell = input->GetCell(cellId); npts = cell->GetNumberOfPoints(); for (i=0; i<3; i++) { negative[i] = positive[i] = 0; } for (i=0; i < npts; i++) { ptId = cell->GetPointId(i); v = inVectors->GetVector(ptId); for (j=0; j<3; j++) { if ( v[j] < 0.0 ) { negative[j] = 1; } else if ( v[j] >= 0.0 ) { positive[j] = 1; } } } if ( negative[0] && positive[0] && negative[1] && positive[1] && negative[2] && positive[2] ) { // place point at center of cell cell->EvaluateLocation(subId, pcoords, x, weights); ptId = newPts->InsertNextPoint(x); newVerts->InsertCellPoint(ptId); } } newVerts->UpdateCellCount(newPts->GetNumberOfPoints()); vtkDebugMacro(<< "Created " << newPts->GetNumberOfPoints() << "points"); delete [] weights; // // Update ourselves // output->SetPoints(newPts); output->SetVerts(newVerts); output->Squeeze(); } void vtkVectorTopology::PrintSelf(ostream& os, vtkIndent indent) { vtkDataSetToPolyDataFilter::PrintSelf(os,indent); os << indent << "Distance: " << this->Distance << "\n"; } <commit_msg>Changed output to GetOutput()<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkVectorTopology.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2000 Ken Martin, Will Schroeder, Bill Lorensen 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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. 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 REGENTS 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 <math.h> #include "vtkVectorTopology.h" #include "vtkObjectFactory.h" //------------------------------------------------------------------------------ vtkVectorTopology* vtkVectorTopology::New() { // First try to create the object from the vtkObjectFactory vtkObject* ret = vtkObjectFactory::CreateInstance("vtkVectorTopology"); if(ret) { return (vtkVectorTopology*)ret; } // If the factory was unable to create the object, then create it here. return new vtkVectorTopology; } // Construct object with distance 0.1. vtkVectorTopology::vtkVectorTopology() { this->Distance = 0.1; } void vtkVectorTopology::Execute() { int cellId, i, j, ptId, npts; int negative[3], positive[3], subId=0; float x[3], pcoords[3], *v; vtkCell *cell; vtkVectors *inVectors; vtkPoints *newPts; vtkCellArray *newVerts; vtkDataSet *input=(vtkDataSet *)this->GetInput(); vtkPointData *pd=input->GetPointData(); vtkPolyData *output=(vtkPolyData *)this->GetOutput(); vtkPointData *outputPD=output->GetPointData(); float *weights=new float[input->GetMaxCellSize()]; // // Initialize self; check input; create output objects // vtkDebugMacro(<< "Executing vector topology..."); // make sure we have vector data if ( ! (inVectors = input->GetPointData()->GetVectors()) ) { vtkErrorMacro(<<"No vector data, can't create topology markers..."); return; } newPts = vtkPoints::New(); newPts->Allocate(100); newVerts = vtkCellArray::New(); newVerts->Allocate(newVerts->EstimateSize(1,100)); outputPD->CopyAllocate(pd); // // Find cells whose vector components all pass through zero // pcoords[0] = pcoords[1] = pcoords[2] = 0.5; newVerts->InsertNextCell(100); //temporary count for (cellId=0; cellId<input->GetNumberOfCells(); cellId++) { cell = input->GetCell(cellId); npts = cell->GetNumberOfPoints(); for (i=0; i<3; i++) { negative[i] = positive[i] = 0; } for (i=0; i < npts; i++) { ptId = cell->GetPointId(i); v = inVectors->GetVector(ptId); for (j=0; j<3; j++) { if ( v[j] < 0.0 ) { negative[j] = 1; } else if ( v[j] >= 0.0 ) { positive[j] = 1; } } } if ( negative[0] && positive[0] && negative[1] && positive[1] && negative[2] && positive[2] ) { // place point at center of cell cell->EvaluateLocation(subId, pcoords, x, weights); ptId = newPts->InsertNextPoint(x); newVerts->InsertCellPoint(ptId); } } newVerts->UpdateCellCount(newPts->GetNumberOfPoints()); vtkDebugMacro(<< "Created " << newPts->GetNumberOfPoints() << "points"); delete [] weights; // // Update ourselves // output->SetPoints(newPts); output->SetVerts(newVerts); output->Squeeze(); } void vtkVectorTopology::PrintSelf(ostream& os, vtkIndent indent) { vtkDataSetToPolyDataFilter::PrintSelf(os,indent); os << indent << "Distance: " << this->Distance << "\n"; } <|endoftext|>
<commit_before> #include "IPCSession.hpp" #include "../Client.hpp" #include <onions-common/Log.hpp> #include <onions-common/tcp/MemAllocator.hpp> #include <onions-common/Utils.hpp> #include <boost/bind.hpp> #include <algorithm> #include <fstream> template <typename Handler> inline MemAllocator<Handler> makeHandler(HandleAlloc& a, Handler h) { return MemAllocator<Handler>(a, h); } IPCSession::IPCSession(boost::asio::io_service& ios) : socket_(ios) { } boost::asio::ip::tcp::socket& IPCSession::getSocket() { return socket_; } void IPCSession::start() { asyncReadBuffer(); } void IPCSession::processRead(const boost::system::error_code& error, size_t n) { if (error || n <= 0) { Log::get().warn("IPC processRead: " + error.message()); return; } std::string domainIn(buffer_.begin(), buffer_.begin() + n); Log::get().notice("Read \"" + domainIn + "\" from Tor Browser."); std::string onionOut = Client::get().resolve(domainIn); Log::get().notice("Writing \"" + onionOut + "\" to Tor Browser... "); for (std::size_t j = 0; j < onionOut.size(); j++) buffer_[j] = onionOut[j]; asyncWriteBuffer(onionOut.size()); } // called by Asio when the buffer has been written to the socket void IPCSession::processWrite(const boost::system::error_code& error) { if (error) { Log::get().warn("IPC processWrite: " + error.message()); return; } Log::get().notice("Write complete."); asyncReadBuffer(); } // ***************************** PRIVATE METHODS ***************************** void IPCSession::asyncReadBuffer() { socket_.async_read_some( boost::asio::buffer(buffer_), makeHandler(allocator_, boost::bind(&IPCSession::processRead, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred))); } void IPCSession::asyncWriteBuffer(std::size_t len) { boost::asio::async_write( socket_, boost::asio::buffer(buffer_, len), makeHandler(allocator_, boost::bind(&IPCSession::processWrite, shared_from_this(), boost::asio::placeholders::error))); } <commit_msg>trim IPC read<commit_after> #include "IPCSession.hpp" #include "../Client.hpp" #include <onions-common/Log.hpp> #include <onions-common/tcp/MemAllocator.hpp> #include <onions-common/Utils.hpp> #include <boost/bind.hpp> #include <algorithm> #include <fstream> template <typename Handler> inline MemAllocator<Handler> makeHandler(HandleAlloc& a, Handler h) { return MemAllocator<Handler>(a, h); } IPCSession::IPCSession(boost::asio::io_service& ios) : socket_(ios) { } boost::asio::ip::tcp::socket& IPCSession::getSocket() { return socket_; } void IPCSession::start() { asyncReadBuffer(); } void IPCSession::processRead(const boost::system::error_code& error, size_t n) { if (error || n <= 0) { Log::get().warn("IPC " + error.message()); return; } std::string domainIn(buffer_.begin(), buffer_.begin() + n); domainIn = Utils::trimString(domainIn); Log::get().notice("Read \"" + domainIn + "\" from Tor Browser."); std::string onionOut = Client::get().resolve(domainIn); Log::get().notice("Writing \"" + onionOut + "\" to Tor Browser... "); for (std::size_t j = 0; j < onionOut.size(); j++) buffer_[j] = onionOut[j]; asyncWriteBuffer(onionOut.size()); } // called by Asio when the buffer has been written to the socket void IPCSession::processWrite(const boost::system::error_code& error) { if (error) { Log::get().warn("IPC processWrite: " + error.message()); return; } Log::get().notice("Write complete."); asyncReadBuffer(); } // ***************************** PRIVATE METHODS ***************************** void IPCSession::asyncReadBuffer() { socket_.async_read_some( boost::asio::buffer(buffer_), makeHandler(allocator_, boost::bind(&IPCSession::processRead, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred))); } void IPCSession::asyncWriteBuffer(std::size_t len) { boost::asio::async_write( socket_, boost::asio::buffer(buffer_, len), makeHandler(allocator_, boost::bind(&IPCSession::processWrite, shared_from_this(), boost::asio::placeholders::error))); } <|endoftext|>
<commit_before>#include <ros/console.h> #include <string> #include <teraranger_hub/RangeArray.h> #include <teraranger_hub/teraranger_evo.h> #include <teraranger_hub/helper_lib.h> namespace teraranger_hub { TerarangerHubEvo::TerarangerHubEvo() { // Get parameters and namespace ros::NodeHandle private_node_handle_("~"); private_node_handle_.param("portname", portname_, std::string("/dev/ttyACM0")); ns_ = ros::this_node::getNamespace(); ns_ = ros::names::clean(ns_); ROS_INFO("node namespace: [%s]", ns_.c_str()); // Publishers range_publisher_ = nh_.advertise<teraranger_hub::RangeArray>("teraranger_evo", 8); // Serial Port init serial_port_ = new SerialPort(); if (!serial_port_->connect(portname_)) { ROS_ERROR("Could not open : %s ", portname_.c_str()); ros::shutdown(); return; } else { serial_data_callback_function_ = boost::bind(&TerarangerHubEvo::serialDataCallback, this, _1); serial_port_->setSerialCallbackFunction(&serial_data_callback_function_); } // Output loaded parameters to console for double checking ROS_INFO("[%s] is up and running with the following parameters:", ros::this_node::getName().c_str()); ROS_INFO("[%s] portname: %s", ros::this_node::getName().c_str(), portname_.c_str()); //Initialize local parameters and measurement array field_of_view = 0.0593; max_range = 14.0; min_range = 0.2; number_of_sensor = 8; frame_id = "base_range_"; // Initialize rangeArray for (size_t i=0; i < number_of_sensor; i++) { sensor_msgs::Range range; range.field_of_view = field_of_view; range.max_range = max_range; range.min_range = min_range; range.radiation_type = sensor_msgs::Range::INFRARED; range.range = 0.0; // set the right range frame depending of the namespace if (ns_ == ""){ range.header.frame_id = frame_id + boost::lexical_cast<std::string>(i); } else{ range.header.frame_id = ns_.erase(0,1) + '_'+ frame_id + boost::lexical_cast<std::string>(i); } measure.ranges.push_back(range); } // set the right RangeArray frame depending of the namespace if (ns_ == ""){ measure.header.frame_id = "base_hub"; } else{ measure.header.frame_id = "base_" + ns_.erase(0,1);// Remove first slash } // This line is needed to start measurements on the hub setMode(ENABLE_CMD, 5); setMode(BINARY_MODE, 4); setMode(TOWER_MODE, 4); setMode(RATE_ASAP, 5); // Dynamic reconfigure dyn_param_server_callback_function_ = boost::bind(&TerarangerHubEvo::dynParamCallback, this, _1, _2); dyn_param_server_.setCallback(dyn_param_server_callback_function_); } TerarangerHubEvo::~TerarangerHubEvo() {} void TerarangerHubEvo::setMode(const char *c, int length) { serial_port_->sendChar(c, length); } void TerarangerHubEvo::dynParamCallback( const teraranger_evo_cfg::TerarangerHubEvoConfig &config, uint32_t level) { // Set the mode dynamically if (config.Mode == teraranger_evo_cfg::TerarangerHubEvo_Binary) { setMode(BINARY_MODE, 4); } if (config.Mode == teraranger_evo_cfg::TerarangerHubEvo_Text) { setMode(TEXT_MODE, 4); } // Set the rate dynamically if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_ASAP){ setMode(RATE_ASAP, 5); } if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_700){ setMode(RATE_700, 5); } if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_600){ setMode(RATE_600, 5); } if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_500){ setMode(RATE_500, 5); } if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_250){ setMode(RATE_250, 5); } if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_100){ setMode(RATE_100, 5); } if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_50){ setMode(RATE_50, 5); } } void TerarangerHubEvo::serialDataCallback(uint8_t single_character) { static uint8_t input_buffer[BUFFER_SIZE]; static int buffer_ctr = 0; static int seq_ctr = 0; ROS_DEBUG("Buffer of size %d : %s | current char : %c", buffer_ctr, input_buffer, (char)single_character); if (single_character == 'T' && buffer_ctr == 0) { // Waiting for T input_buffer[buffer_ctr++] = single_character; return; } else if (single_character == 'H' && buffer_ctr == 1) { // Waiting for H after a T input_buffer[buffer_ctr++] = single_character; return; } // Gathering after-header range data if (buffer_ctr > 1 && buffer_ctr < RANGES_FRAME_LENGTH) { input_buffer[buffer_ctr++] = single_character; return; } else if (buffer_ctr == RANGES_FRAME_LENGTH) { //Processing full range frame int16_t crc = crc8(input_buffer, 19); if (crc == input_buffer[RANGE_CRC_POS]) { //ROS_DEBUG("Frame of size %d : %s ", buffer_ctr, input_buffer); for (size_t i=0; i < measure.ranges.size(); i++) { measure.ranges.at(i).header.stamp = ros::Time::now(); measure.ranges.at(i).header.seq = seq_ctr++; // Doesn't go out of range because of fixed buffer size as long as the number of sensor is not above 8 char c1 = input_buffer[2 * (i + 1)]; char c2 = input_buffer[2 * (i + 1) + 1]; ROS_DEBUG("c1 : %x, c2 : %x", (c1 & 0x0FF), (c2 & 0x0FF)); int16_t current_range = (c1 & 0x0FF) << 8; current_range |= (c2 & 0x0FF); float float_range = (float)current_range; ROS_DEBUG("Value int : %d | float : %f", current_range, float_range); if (current_range <= 1 || current_range == 255) { float_range = -1.0; } else { float_range = float_range * 0.001; } measure.ranges.at(i).range = float_range; } measure.header.seq = (int) seq_ctr / 8; measure.header.stamp = ros::Time::now(); range_publisher_.publish(measure); } else { ROS_DEBUG("[%s] crc missmatch", ros::this_node::getName().c_str()); } } else if (buffer_ctr > RANGES_FRAME_LENGTH){ ROS_DEBUG("[%s] : Buffer overflow, resetting buffer without " "evaluating data", ros::this_node::getName().c_str()); } // resetting buffer and ctr buffer_ctr = 0; bzero(&input_buffer, BUFFER_SIZE); // Appending current char to hook next frame input_buffer[buffer_ctr++] = single_character; } } int main(int argc, char **argv) { ros::init(argc, argv, "teraranger_hub_evo"); teraranger_hub::TerarangerHubEvo node; ros::spin(); return 0; } <commit_msg>Correct crc8 function naming<commit_after>#include <ros/console.h> #include <string> #include <teraranger_hub/RangeArray.h> #include <teraranger_hub/teraranger_evo.h> #include <teraranger_hub/helper_lib.h> namespace teraranger_hub { TerarangerHubEvo::TerarangerHubEvo() { // Get parameters and namespace ros::NodeHandle private_node_handle_("~"); private_node_handle_.param("portname", portname_, std::string("/dev/ttyACM0")); ns_ = ros::this_node::getNamespace(); ns_ = ros::names::clean(ns_); ROS_INFO("node namespace: [%s]", ns_.c_str()); // Publishers range_publisher_ = nh_.advertise<teraranger_hub::RangeArray>("teraranger_evo", 8); // Serial Port init serial_port_ = new SerialPort(); if (!serial_port_->connect(portname_)) { ROS_ERROR("Could not open : %s ", portname_.c_str()); ros::shutdown(); return; } else { serial_data_callback_function_ = boost::bind(&TerarangerHubEvo::serialDataCallback, this, _1); serial_port_->setSerialCallbackFunction(&serial_data_callback_function_); } // Output loaded parameters to console for double checking ROS_INFO("[%s] is up and running with the following parameters:", ros::this_node::getName().c_str()); ROS_INFO("[%s] portname: %s", ros::this_node::getName().c_str(), portname_.c_str()); //Initialize local parameters and measurement array field_of_view = 0.0593; max_range = 14.0; min_range = 0.2; number_of_sensor = 8; frame_id = "base_range_"; // Initialize rangeArray for (size_t i=0; i < number_of_sensor; i++) { sensor_msgs::Range range; range.field_of_view = field_of_view; range.max_range = max_range; range.min_range = min_range; range.radiation_type = sensor_msgs::Range::INFRARED; range.range = 0.0; // set the right range frame depending of the namespace if (ns_ == ""){ range.header.frame_id = frame_id + boost::lexical_cast<std::string>(i); } else{ range.header.frame_id = ns_.erase(0,1) + '_'+ frame_id + boost::lexical_cast<std::string>(i); } measure.ranges.push_back(range); } // set the right RangeArray frame depending of the namespace if (ns_ == ""){ measure.header.frame_id = "base_hub"; } else{ measure.header.frame_id = "base_" + ns_.erase(0,1);// Remove first slash } // This line is needed to start measurements on the hub setMode(ENABLE_CMD, 5); setMode(BINARY_MODE, 4); setMode(TOWER_MODE, 4); setMode(RATE_ASAP, 5); // Dynamic reconfigure dyn_param_server_callback_function_ = boost::bind(&TerarangerHubEvo::dynParamCallback, this, _1, _2); dyn_param_server_.setCallback(dyn_param_server_callback_function_); } TerarangerHubEvo::~TerarangerHubEvo() {} void TerarangerHubEvo::setMode(const char *c, int length) { serial_port_->sendChar(c, length); } void TerarangerHubEvo::dynParamCallback( const teraranger_evo_cfg::TerarangerHubEvoConfig &config, uint32_t level) { // Set the mode dynamically if (config.Mode == teraranger_evo_cfg::TerarangerHubEvo_Binary) { setMode(BINARY_MODE, 4); } if (config.Mode == teraranger_evo_cfg::TerarangerHubEvo_Text) { setMode(TEXT_MODE, 4); } // Set the rate dynamically if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_ASAP){ setMode(RATE_ASAP, 5); } if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_700){ setMode(RATE_700, 5); } if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_600){ setMode(RATE_600, 5); } if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_500){ setMode(RATE_500, 5); } if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_250){ setMode(RATE_250, 5); } if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_100){ setMode(RATE_100, 5); } if (config.Rate == teraranger_evo_cfg::TerarangerHubEvo_50){ setMode(RATE_50, 5); } } void TerarangerHubEvo::serialDataCallback(uint8_t single_character) { static uint8_t input_buffer[BUFFER_SIZE]; static int buffer_ctr = 0; static int seq_ctr = 0; ROS_DEBUG("Buffer of size %d : %s | current char : %c", buffer_ctr, input_buffer, (char)single_character); if (single_character == 'T' && buffer_ctr == 0) { // Waiting for T input_buffer[buffer_ctr++] = single_character; return; } else if (single_character == 'H' && buffer_ctr == 1) { // Waiting for H after a T input_buffer[buffer_ctr++] = single_character; return; } // Gathering after-header range data if (buffer_ctr > 1 && buffer_ctr < RANGES_FRAME_LENGTH) { input_buffer[buffer_ctr++] = single_character; return; } else if (buffer_ctr == RANGES_FRAME_LENGTH) { //Processing full range frame int16_t crc = HelperLib::crc8(input_buffer, 19); if (crc == input_buffer[RANGE_CRC_POS]) { //ROS_DEBUG("Frame of size %d : %s ", buffer_ctr, input_buffer); for (size_t i=0; i < measure.ranges.size(); i++) { measure.ranges.at(i).header.stamp = ros::Time::now(); measure.ranges.at(i).header.seq = seq_ctr++; // Doesn't go out of range because of fixed buffer size as long as the number of sensor is not above 8 char c1 = input_buffer[2 * (i + 1)]; char c2 = input_buffer[2 * (i + 1) + 1]; ROS_DEBUG("c1 : %x, c2 : %x", (c1 & 0x0FF), (c2 & 0x0FF)); int16_t current_range = (c1 & 0x0FF) << 8; current_range |= (c2 & 0x0FF); float float_range = (float)current_range; ROS_DEBUG("Value int : %d | float : %f", current_range, float_range); if (current_range <= 1 || current_range == 255) { float_range = -1.0; } else { float_range = float_range * 0.001; } measure.ranges.at(i).range = float_range; } measure.header.seq = (int) seq_ctr / 8; measure.header.stamp = ros::Time::now(); range_publisher_.publish(measure); } else { ROS_DEBUG("[%s] crc missmatch", ros::this_node::getName().c_str()); } } else if (buffer_ctr > RANGES_FRAME_LENGTH){ ROS_DEBUG("[%s] : Buffer overflow, resetting buffer without " "evaluating data", ros::this_node::getName().c_str()); } // resetting buffer and ctr buffer_ctr = 0; bzero(&input_buffer, BUFFER_SIZE); // Appending current char to hook next frame input_buffer[buffer_ctr++] = single_character; } } int main(int argc, char **argv) { ros::init(argc, argv, "teraranger_hub_evo"); teraranger_hub::TerarangerHubEvo node; ros::spin(); return 0; } <|endoftext|>
<commit_before>// This file will be removed when the code is accepted into the Thrift library. /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #include "config.h" #ifdef HAVE_SASL_SASL_H #include <stdint.h> #include <sstream> #include <boost/shared_ptr.hpp> #include <boost/scoped_ptr.hpp> #include <thrift/transport/TBufferTransports.h> #include "transport/TSaslTransport.h" #include "common/names.h" // Default size, in bytes, for the memory buffer used to stage reads. const int32_t DEFAULT_MEM_BUF_SIZE = 32 * 1024; namespace apache { namespace thrift { namespace transport { TSaslTransport::TSaslTransport(boost::shared_ptr<TTransport> transport) : transport_(transport), memBuf_(new TMemoryBuffer(DEFAULT_MEM_BUF_SIZE)), shouldWrap_(false), isClient_(false) { } TSaslTransport::TSaslTransport(boost::shared_ptr<sasl::TSasl> saslClient, boost::shared_ptr<TTransport> transport) : transport_(transport), memBuf_(new TMemoryBuffer()), sasl_(saslClient), shouldWrap_(false), isClient_(true) { } TSaslTransport::~TSaslTransport() { delete memBuf_; } bool TSaslTransport::isOpen() { return transport_->isOpen(); } bool TSaslTransport::peek(){ return (transport_->peek()); } string TSaslTransport::getUsername() { return sasl_->getUsername(); } void TSaslTransport::sendSaslMessage(const NegotiationStatus status, const uint8_t* payload, const uint32_t length, bool flush) { uint8_t messageHeader[STATUS_BYTES + PAYLOAD_LENGTH_BYTES]; uint8_t dummy = 0; if (payload == NULL) { payload = &dummy; } messageHeader[0] = (uint8_t)status; encodeInt(length, messageHeader, STATUS_BYTES); transport_->write(messageHeader, HEADER_LENGTH); transport_->write(payload, length); if (flush) transport_->flush(); } void TSaslTransport::open() { NegotiationStatus status = TSASL_INVALID; uint32_t resLength; // Only client should open the underlying transport. if (isClient_ && !transport_->isOpen()) { transport_->open(); } // initiate SASL message handleSaslStartMessage(); // SASL connection handshake while (!sasl_->isComplete()) { uint8_t* message = receiveSaslMessage(&status, &resLength); if (status == TSASL_COMPLETE) { if (isClient_) break; // handshake complete } else if (status != TSASL_OK) { stringstream ss; ss << "Expected COMPLETE or OK, got " << status; throw TTransportException(ss.str()); } uint32_t challengeLength; uint8_t* challenge = sasl_->evaluateChallengeOrResponse( message, resLength, &challengeLength); sendSaslMessage(sasl_->isComplete() ? TSASL_COMPLETE : TSASL_OK, challenge, challengeLength); } // If the server isn't complete yet, we need to wait for its response. // This will occur with ANONYMOUS auth, for example, where we send an // initial response and are immediately complete. if (isClient_ && (status == TSASL_INVALID || status == TSASL_OK)) { receiveSaslMessage(&status, &resLength); if (status != TSASL_COMPLETE) { stringstream ss; ss << "Expected COMPLETE or OK, got " << status; throw TTransportException(ss.str()); } } // TODO : need to set the shouldWrap_ based on QOP /* String qop = (String) sasl.getNegotiatedProperty(Sasl.QOP); if (qop != null && !qop.equalsIgnoreCase("auth")) shouldWrap_ = true; */ } void TSaslTransport::close() { transport_->close(); } uint32_t TSaslTransport::readLength() { uint8_t lenBuf[PAYLOAD_LENGTH_BYTES]; transport_->readAll(lenBuf, PAYLOAD_LENGTH_BYTES); int32_t len = decodeInt(lenBuf, 0); if (len < 0) { throw TTransportException("Frame size has negative value"); } return static_cast<uint32_t>(len); } void TSaslTransport::shrinkBuffer() { // readEnd() returns the number of bytes already read, i.e. the number of 'junk' bytes // taking up space at the front of the memory buffer. uint32_t read_end = memBuf_->readEnd(); // If the size of the junk space at the beginning of the buffer is too large, and // there's no data left in the buffer to read (number of bytes read == number of bytes // written), then shrink the buffer back to the default. We don't want to do this on // every read that exhausts the buffer, since the layer above often reads in small // chunks, which is why we only resize if there's too much junk. The write and read // pointers will eventually catch up after every RPC, so we will always take this path // eventually once the buffer becomes sufficiently full. // // readEnd() may reset the write / read pointers (but only once if there's no // intervening read or write between calls), so needs to be called a second time to // get their current position. if (read_end > DEFAULT_MEM_BUF_SIZE && memBuf_->writeEnd() == memBuf_->readEnd()) { memBuf_->resetBuffer(DEFAULT_MEM_BUF_SIZE); } } uint32_t TSaslTransport::read(uint8_t* buf, uint32_t len) { uint32_t read_bytes = memBuf_->read(buf, len); if (read_bytes > 0) { shrinkBuffer(); return read_bytes; } // if there's not enough data in cache, read from underlying transport uint32_t dataLength = readLength(); // Fast path if (len == dataLength && !shouldWrap_) { transport_->readAll(buf, len); return len; } uint8_t* tmpBuf = new uint8_t[dataLength]; transport_->readAll(tmpBuf, dataLength); if (shouldWrap_) { tmpBuf = sasl_->unwrap(tmpBuf, 0, dataLength, &dataLength); } // We will consume all the data, no need to put it in the memory buffer. if (len == dataLength) { memcpy(buf, tmpBuf, len); delete[] tmpBuf; return len; } memBuf_->write(tmpBuf, dataLength); memBuf_->flush(); delete[] tmpBuf; uint32_t ret = memBuf_->read(buf, len); shrinkBuffer(); return ret; } void TSaslTransport::writeLength(uint32_t length) { uint8_t lenBuf[PAYLOAD_LENGTH_BYTES]; encodeInt(length, lenBuf, 0); transport_->write(lenBuf, PAYLOAD_LENGTH_BYTES); } void TSaslTransport::write(const uint8_t* buf, uint32_t len) { const uint8_t* newBuf; if (shouldWrap_) { newBuf = sasl_->wrap((uint8_t*)buf, 0, len, &len); } else { newBuf = buf; } writeLength(len); transport_->write(newBuf, len); } void TSaslTransport::flush() { transport_->flush(); } uint8_t* TSaslTransport::receiveSaslMessage(NegotiationStatus* status, uint32_t* length) { uint8_t messageHeader[HEADER_LENGTH]; // read header transport_->readAll(messageHeader, HEADER_LENGTH); // get payload status *status = (NegotiationStatus)messageHeader[0]; if ((*status < TSASL_START) || (*status > TSASL_COMPLETE)) { throw TTransportException("invalid sasl status"); } else if (*status == TSASL_BAD || *status == TSASL_ERROR) { throw TTransportException("sasl Peer indicated failure: "); } // get the length *length = decodeInt(messageHeader, STATUS_BYTES); // get payload protoBuf_.reset(new uint8_t[*length]); transport_->readAll(protoBuf_.get(), *length); return protoBuf_.get(); } } } } #endif <commit_msg>IMPALA-5005: Don't allow server to send SASL COMPLETE msg out of order<commit_after>// This file will be removed when the code is accepted into the Thrift library. /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #include "config.h" #ifdef HAVE_SASL_SASL_H #include <stdint.h> #include <sstream> #include <boost/shared_ptr.hpp> #include <boost/scoped_ptr.hpp> #include <thrift/transport/TBufferTransports.h> #include "transport/TSaslTransport.h" #include "common/names.h" // Default size, in bytes, for the memory buffer used to stage reads. const int32_t DEFAULT_MEM_BUF_SIZE = 32 * 1024; namespace apache { namespace thrift { namespace transport { TSaslTransport::TSaslTransport(boost::shared_ptr<TTransport> transport) : transport_(transport), memBuf_(new TMemoryBuffer(DEFAULT_MEM_BUF_SIZE)), shouldWrap_(false), isClient_(false) { } TSaslTransport::TSaslTransport(boost::shared_ptr<sasl::TSasl> saslClient, boost::shared_ptr<TTransport> transport) : transport_(transport), memBuf_(new TMemoryBuffer()), sasl_(saslClient), shouldWrap_(false), isClient_(true) { } TSaslTransport::~TSaslTransport() { delete memBuf_; } bool TSaslTransport::isOpen() { return transport_->isOpen(); } bool TSaslTransport::peek(){ return (transport_->peek()); } string TSaslTransport::getUsername() { return sasl_->getUsername(); } void TSaslTransport::sendSaslMessage(const NegotiationStatus status, const uint8_t* payload, const uint32_t length, bool flush) { uint8_t messageHeader[STATUS_BYTES + PAYLOAD_LENGTH_BYTES]; uint8_t dummy = 0; if (payload == NULL) { payload = &dummy; } messageHeader[0] = (uint8_t)status; encodeInt(length, messageHeader, STATUS_BYTES); transport_->write(messageHeader, HEADER_LENGTH); transport_->write(payload, length); if (flush) transport_->flush(); } void TSaslTransport::open() { NegotiationStatus status = TSASL_INVALID; uint32_t resLength; // Only client should open the underlying transport. if (isClient_ && !transport_->isOpen()) { transport_->open(); } // initiate SASL message handleSaslStartMessage(); // SASL connection handshake while (!sasl_->isComplete()) { uint8_t* message = receiveSaslMessage(&status, &resLength); if (status == TSASL_COMPLETE) { if (isClient_) { if (!sasl_->isComplete()) { // Server sent COMPLETE out of order. throw TTransportException("Received COMPLETE but no handshake occurred"); } break; // handshake complete } } else if (status != TSASL_OK) { stringstream ss; ss << "Expected COMPLETE or OK, got " << status; throw TTransportException(ss.str()); } uint32_t challengeLength; uint8_t* challenge = sasl_->evaluateChallengeOrResponse( message, resLength, &challengeLength); sendSaslMessage(sasl_->isComplete() ? TSASL_COMPLETE : TSASL_OK, challenge, challengeLength); } // If the server isn't complete yet, we need to wait for its response. // This will occur with ANONYMOUS auth, for example, where we send an // initial response and are immediately complete. if (isClient_ && (status == TSASL_INVALID || status == TSASL_OK)) { receiveSaslMessage(&status, &resLength); if (status != TSASL_COMPLETE) { stringstream ss; ss << "Expected COMPLETE or OK, got " << status; throw TTransportException(ss.str()); } } // TODO : need to set the shouldWrap_ based on QOP /* String qop = (String) sasl.getNegotiatedProperty(Sasl.QOP); if (qop != null && !qop.equalsIgnoreCase("auth")) shouldWrap_ = true; */ } void TSaslTransport::close() { transport_->close(); } uint32_t TSaslTransport::readLength() { uint8_t lenBuf[PAYLOAD_LENGTH_BYTES]; transport_->readAll(lenBuf, PAYLOAD_LENGTH_BYTES); int32_t len = decodeInt(lenBuf, 0); if (len < 0) { throw TTransportException("Frame size has negative value"); } return static_cast<uint32_t>(len); } void TSaslTransport::shrinkBuffer() { // readEnd() returns the number of bytes already read, i.e. the number of 'junk' bytes // taking up space at the front of the memory buffer. uint32_t read_end = memBuf_->readEnd(); // If the size of the junk space at the beginning of the buffer is too large, and // there's no data left in the buffer to read (number of bytes read == number of bytes // written), then shrink the buffer back to the default. We don't want to do this on // every read that exhausts the buffer, since the layer above often reads in small // chunks, which is why we only resize if there's too much junk. The write and read // pointers will eventually catch up after every RPC, so we will always take this path // eventually once the buffer becomes sufficiently full. // // readEnd() may reset the write / read pointers (but only once if there's no // intervening read or write between calls), so needs to be called a second time to // get their current position. if (read_end > DEFAULT_MEM_BUF_SIZE && memBuf_->writeEnd() == memBuf_->readEnd()) { memBuf_->resetBuffer(DEFAULT_MEM_BUF_SIZE); } } uint32_t TSaslTransport::read(uint8_t* buf, uint32_t len) { uint32_t read_bytes = memBuf_->read(buf, len); if (read_bytes > 0) { shrinkBuffer(); return read_bytes; } // if there's not enough data in cache, read from underlying transport uint32_t dataLength = readLength(); // Fast path if (len == dataLength && !shouldWrap_) { transport_->readAll(buf, len); return len; } uint8_t* tmpBuf = new uint8_t[dataLength]; transport_->readAll(tmpBuf, dataLength); if (shouldWrap_) { tmpBuf = sasl_->unwrap(tmpBuf, 0, dataLength, &dataLength); } // We will consume all the data, no need to put it in the memory buffer. if (len == dataLength) { memcpy(buf, tmpBuf, len); delete[] tmpBuf; return len; } memBuf_->write(tmpBuf, dataLength); memBuf_->flush(); delete[] tmpBuf; uint32_t ret = memBuf_->read(buf, len); shrinkBuffer(); return ret; } void TSaslTransport::writeLength(uint32_t length) { uint8_t lenBuf[PAYLOAD_LENGTH_BYTES]; encodeInt(length, lenBuf, 0); transport_->write(lenBuf, PAYLOAD_LENGTH_BYTES); } void TSaslTransport::write(const uint8_t* buf, uint32_t len) { const uint8_t* newBuf; if (shouldWrap_) { newBuf = sasl_->wrap((uint8_t*)buf, 0, len, &len); } else { newBuf = buf; } writeLength(len); transport_->write(newBuf, len); } void TSaslTransport::flush() { transport_->flush(); } uint8_t* TSaslTransport::receiveSaslMessage(NegotiationStatus* status, uint32_t* length) { uint8_t messageHeader[HEADER_LENGTH]; // read header transport_->readAll(messageHeader, HEADER_LENGTH); // get payload status *status = (NegotiationStatus)messageHeader[0]; if ((*status < TSASL_START) || (*status > TSASL_COMPLETE)) { throw TTransportException("invalid sasl status"); } else if (*status == TSASL_BAD || *status == TSASL_ERROR) { throw TTransportException("sasl Peer indicated failure: "); } // get the length *length = decodeInt(messageHeader, STATUS_BYTES); // get payload protoBuf_.reset(new uint8_t[*length]); transport_->readAll(protoBuf_.get(), *length); return protoBuf_.get(); } } } } #endif <|endoftext|>
<commit_before>#include <iostream> #include <iomanip> #include <string> #include <sstream> #include <memory> #include <initializer_list> #include <stdlib.h> #include <string.h> #include <assert.h> #include <ctype.h> enum class token_type { identifier, literal, op, eof }; std::ostream& operator<<(std::ostream& os, token_type t) { switch (t) { #define HANDLE_TOKEN_TYPE(t) case token_type::t: os << #t; break HANDLE_TOKEN_TYPE(identifier); HANDLE_TOKEN_TYPE(literal); HANDLE_TOKEN_TYPE(op); HANDLE_TOKEN_TYPE(eof); #undef HANDLE_TOKEN_TYPE } return os; } static size_t try_parse(token_type t, const char* text, size_t length) { assert(length != 0); if (t == token_type::identifier) { size_t l = 0; while (l < length && isalpha(text[l])) { ++l; } return l; } else if (t == token_type::literal) { std::istringstream iss{std::string{text, text+length}}; assert(iss.tellg() == 0); double value; if (iss >> value) { const auto l = iss.eof() ? length : static_cast<size_t>(iss.tellg()); assert(l != 0); assert(l <= length); return l; } } else if (t == token_type::op) { for (const auto& op : "*+-/=") { if (*text == op) { return 1; } } } else { std::ostringstream oss; oss << "Unhandled token type '" << t << "' str='" << std::string{text, text+length} << "' in " << __func__; throw std::logic_error(oss.str()); } return 0; } class token { public: static const size_t nts = size_t(-1); static token eof_token() { return token{token_type::eof, "", 0}; } static token identifier_token(const char* str, size_t len = nts) { return token{token_type::identifier, str, len == nts ? strlen(str) : len}; } static token literal_token(const char* str, size_t len = nts) { return token{token_type::literal, str, len == nts ? strlen(str) : len}; } static token op_token(const char* str, size_t len = nts) { return token{token_type::op, str, len == nts ? strlen(str) : len}; } token_type type() const { return type_; } std::string str() const { return std::string(text_, text_ + length_); } size_t length() const { return length_; } private: friend class tokenizer; token(token_type type, const char* text, size_t length) : type_(type), text_(text), length_(length) { assert((type == token_type::eof && length == 0) || try_parse(type, text, length) == length); } token_type type_; const char* text_; size_t length_; }; bool operator==(const token& a, const token& b) { return a.type() == b.type() && a.str() == b.str(); } bool operator!=(const token& a, const token& b) { return !(a == b); } std::ostream& operator<<(std::ostream& os, const token& t) { os << "{" << t.type() << " '" << t.str() << "'}"; return os; } class tokenizer { public: tokenizer(const char* text, size_t length) : text_(text), length_(length), pos_(0), current_(token::eof_token()) { next_token(); } const token& current() const { return current_; } token consume() { auto cur = current_; next_token(); return cur; } private: const char* text_; size_t length_; size_t pos_; token current_; // initialize current_ with appropriate token type from pos_ bytes into text_ // advance pos_ by the tokens length void next_token() { // loop until we reach eof or get a now whitespace character for (;;) { // handle end of text if (pos_ >= length_) { assert(pos_ == length_); current_ = token::eof_token(); return; } // we can now safely extract text_[pos_] const char* const text_pos = text_ + pos_; const size_t remaining = length_ - pos_; // skip whitespace if (isspace(*text_pos)) { pos_++; continue; } for (const auto& t : { token_type::identifier, token_type::literal, token_type::op}) { if (const auto l = try_parse(t, text_pos, remaining)) { assert(l <= remaining); pos_ += l; current_ = token{t, text_pos, l}; return; } } throw std::runtime_error("Parse error at: " + std::string(text_pos, text_pos+remaining)); } } }; void test_tokenizer(const std::string& text, std::initializer_list<token> expected_tokens) { tokenizer t{text.c_str(), text.length()}; for (const auto& expected_token : expected_tokens) { auto current_token = t.consume(); std::cout << current_token << " "; if (current_token != expected_token) { std::cerr << "Tokenizer error. Expeceted " << expected_token << " got " << current_token << std::endl; abort(); } } assert(t.current().type() == token_type::eof); std::cout << "OK!\n"; } int main() { test_tokenizer("",{token::eof_token()}); test_tokenizer("\t\n\r ",{token::eof_token()}); test_tokenizer(" id ",{token::identifier_token("id"), token::eof_token()}); test_tokenizer("3.14",{token::literal_token("3.14"), token::eof_token()}); test_tokenizer("=\n",{token::op_token("="), token::eof_token()}); test_tokenizer("\thello 42",{token::identifier_token("hello"), token::literal_token("42"), token::eof_token()}); test_tokenizer("\tx + 1e3 = 20",{token::identifier_token("x"), token::op_token("+"), token::literal_token("1e3"), token::op_token("="), token::literal_token("20"), token::eof_token()}); #if 0 const char* const program = R"( vals = 2000 valsize = 8 freq = 1 bspersec = vals * valsize * freq bsperday = bspersec * 60 * 60 * 24 )"; test_tokenizer(program, {make_token(token_type #endif } <commit_msg>More tests<commit_after>#include <iostream> #include <iomanip> #include <string> #include <sstream> #include <memory> #include <initializer_list> #include <stdlib.h> #include <string.h> #include <assert.h> #include <ctype.h> enum class token_type { identifier, literal, op, eof }; std::ostream& operator<<(std::ostream& os, token_type t) { switch (t) { #define HANDLE_TOKEN_TYPE(t) case token_type::t: os << #t; break HANDLE_TOKEN_TYPE(identifier); HANDLE_TOKEN_TYPE(literal); HANDLE_TOKEN_TYPE(op); HANDLE_TOKEN_TYPE(eof); #undef HANDLE_TOKEN_TYPE } return os; } static size_t try_parse(token_type t, const char* text, size_t length) { assert(length != 0); if (t == token_type::identifier) { size_t l = 0; while (l < length && isalpha(text[l])) { ++l; } return l; } else if (t == token_type::literal) { std::istringstream iss{std::string{text, text+length}}; assert(iss.tellg() == 0); double value; if (iss >> value) { const auto l = iss.eof() ? length : static_cast<size_t>(iss.tellg()); assert(l != 0); assert(l <= length); return l; } } else if (t == token_type::op) { for (const auto& op : "*+-/=") { if (*text == op) { return 1; } } } else { std::ostringstream oss; oss << "Unhandled token type '" << t << "' str='" << std::string{text, text+length} << "' in " << __func__; throw std::logic_error(oss.str()); } return 0; } class token { public: static const size_t nts = size_t(-1); static token eof() { return token{token_type::eof, "", 0}; } static token identifier(const char* str, size_t len = nts) { return token{token_type::identifier, str, len == nts ? strlen(str) : len}; } static token literal(const char* str, size_t len = nts) { return token{token_type::literal, str, len == nts ? strlen(str) : len}; } static token op(const char* str, size_t len = nts) { return token{token_type::op, str, len == nts ? strlen(str) : len}; } token_type type() const { return type_; } std::string str() const { return std::string(text_, text_ + length_); } size_t length() const { return length_; } private: friend class tokenizer; token(token_type type, const char* text, size_t length) : type_(type), text_(text), length_(length) { assert((type == token_type::eof && length == 0) || try_parse(type, text, length) == length); } token_type type_; const char* text_; size_t length_; }; bool operator==(const token& a, const token& b) { return a.type() == b.type() && a.str() == b.str(); } bool operator!=(const token& a, const token& b) { return !(a == b); } std::ostream& operator<<(std::ostream& os, const token& t) { os << "{" << t.type() << " '" << t.str() << "'}"; return os; } class tokenizer { public: tokenizer(const char* text, size_t length) : text_(text), length_(length), pos_(0), current_(token::eof()) { next_token(); } const token& current() const { return current_; } token consume() { auto cur = current_; next_token(); return cur; } private: const char* text_; size_t length_; size_t pos_; token current_; // initialize current_ with appropriate token type from pos_ bytes into text_ // advance pos_ by the tokens length void next_token() { // loop until we reach eof or get a now whitespace character for (;;) { // handle end of text if (pos_ >= length_) { assert(pos_ == length_); current_ = token::eof(); return; } // we can now safely extract text_[pos_] const char* const text_pos = text_ + pos_; const size_t remaining = length_ - pos_; // skip whitespace if (isspace(*text_pos)) { pos_++; continue; } for (const auto& t : { token_type::identifier, token_type::literal, token_type::op}) { if (const auto l = try_parse(t, text_pos, remaining)) { assert(l <= remaining); pos_ += l; current_ = token{t, text_pos, l}; return; } } throw std::runtime_error("Parse error at: " + std::string(text_pos, text_pos+remaining)); } } }; void test_tokenizer(const std::string& text, std::initializer_list<token> expected_tokens) { tokenizer t{text.c_str(), text.length()}; for (const auto& expected_token : expected_tokens) { auto current_token = t.consume(); std::cout << current_token << " " << std::flush; if (current_token != expected_token) { std::cerr << "Tokenizer error. Expeceted " << expected_token << " got " << current_token << std::endl; abort(); } } assert(t.current().type() == token_type::eof); std::cout << "OK!\n"; } int main() { test_tokenizer("",{token::eof()}); test_tokenizer("\t\n\r ",{token::eof()}); test_tokenizer(" id ",{token::identifier("id"), token::eof()}); test_tokenizer("3.14",{token::literal("3.14"), token::eof()}); test_tokenizer("=\n",{token::op("="), token::eof()}); test_tokenizer("\thello 42",{token::identifier("hello"), token::literal("42"), token::eof()}); test_tokenizer("\tx + 1e3 = 20",{token::identifier("x"), token::op("+"), token::literal("1e3"), token::op("="), token::literal("20"), token::eof()}); const char* const program = R"( vals = 2000 valsize = 8 freq = 1 bspersec = vals * valsize * freq bsperday = bspersec * 60 * 60 * 24 )"; test_tokenizer(program, { token::identifier("vals"), token::op("="), token::literal("2000"), token::identifier("valsize"), token::op("="), token::literal("8"), token::identifier("freq"), token::op("="), token::literal("1"), token::identifier("bspersec"), token::op("="), token::identifier("vals"), token::op("*"), token::identifier("valsize"), token::op("*"), token::identifier("freq"), token::identifier("bsperday"), token::op("="), token::identifier("bspersec"), token::op("*"), token::literal("60"), token::op("*"), token::literal("60"), token::op("*"), token::literal("24"), token::eof(), }); } <|endoftext|>
<commit_before>// Copyright (c) 2009 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/icon_loader.h" #include "base/message_loop.h" #include "base/thread.h" #include "chrome/browser/browser_process.h" #include "third_party/skia/include/core/SkBitmap.h" IconLoader::IconLoader(const IconGroupID& group, IconSize size, Delegate* delegate) : group_(group), icon_size_(size), bitmap_(NULL), delegate_(delegate) { } IconLoader::~IconLoader() { delete bitmap_; } void IconLoader::Start() { target_message_loop_ = MessageLoop::current(); g_browser_process->file_thread()->message_loop()->PostTask(FROM_HERE, NewRunnableMethod(this, &IconLoader::ReadIcon)); } void IconLoader::NotifyDelegate() { delegate_->OnBitmapLoaded(this, bitmap_); bitmap_ = NULL; } <commit_msg>Icon loader: respect delegate's response to NotifyDelegate call (false means the delegate doesn't assume ownership).<commit_after>// Copyright (c) 2009 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/icon_loader.h" #include "base/message_loop.h" #include "base/thread.h" #include "chrome/browser/browser_process.h" #include "third_party/skia/include/core/SkBitmap.h" IconLoader::IconLoader(const IconGroupID& group, IconSize size, Delegate* delegate) : group_(group), icon_size_(size), bitmap_(NULL), delegate_(delegate) { } IconLoader::~IconLoader() { delete bitmap_; } void IconLoader::Start() { target_message_loop_ = MessageLoop::current(); g_browser_process->file_thread()->message_loop()->PostTask(FROM_HERE, NewRunnableMethod(this, &IconLoader::ReadIcon)); } void IconLoader::NotifyDelegate() { if (delegate_->OnBitmapLoaded(this, bitmap_)) bitmap_ = NULL; } <|endoftext|>
<commit_before>/* The OpenTRV project licenses this file to you under the Apache Licence, Version 2.0 (the "Licence"); you may not use this file except in compliance with the Licence. You may obtain a copy of the Licence at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the Licence for the specific language governing permissions and limitations under the Licence. Author(s) / Copyright (s): Damon Hart-Davis 2016 */ /* * Driver for OTV0P2BASE_SensorAmbientLightOccupancy tests. */ #include <stdint.h> #include <gtest/gtest.h> #include <OTV0p2Base.h> #include "OTV0P2BASE_SensorAmbientLightOccupancy.h" // Sanity test. TEST(AmbientLightOccupancyDetection,SanityTest) { EXPECT_EQ(42, 42); } // Basic test of update() behaviour. TEST(AmbientLightOccupancyDetection,updateBasics) { // Check that initial update never indicates occupancy. OTV0P2BASE::SensorAmbientLightOccupancyDetectorSimple ds1; EXPECT_FALSE(ds1.update(0)) << "no initial update should imply occupancy"; OTV0P2BASE::SensorAmbientLightOccupancyDetectorSimple ds2; EXPECT_FALSE(ds2.update(255)) << "no initial update should imply occupancy"; // Check that update from 0 to max does force occupancy indication (but steady does not). EXPECT_TRUE(ds1.update(255)) << "update from 0 to 255 (max) illumination should signal occupancy"; EXPECT_FALSE(ds2.update(255)) << "unchanged 255 (max) light level should not imply occupancy"; } class ALDataSample { public: const uint8_t d, H, M, L, expected; // Day/hour/minute and light level and expected result. // An expected result of 0 means no particular result expected from this (anything is acceptable). // An expected result of 1 means occupancy should NOT be reported for this sample. // An expected result of 2+ means occupancy should be reported for this sample. ALDataSample(uint8_t dayOfMonth, uint8_t hour24, uint8_t minute, uint8_t lightLevel, uint8_t expectedResult = 0) : d(dayOfMonth), H(hour24), M(minute), L(lightLevel), expected(expectedResult) { } // Create/mark a terminating entry; all input values invalid. ALDataSample() : d(255), H(255), M(255), L(255), expected(0) { } // Compute current minute for this record. long currentMinute() const { return((((d * 24L) + H) * 60L) + M); } // True for empty/termination data record. bool isEnd() const { return(d > 31); } }; // Trivial sample, testing initial reaction to start transient. static const ALDataSample trivialSample1[] = { { 0, 0, 0, 254, 1 }, // Should NOT predict occupancy on first tick. { 0, 0, 1, 0, 1 }, // Should NOT predict occupancy on falling level. { 0, 0, 5, 0 }, // Should NOT predict occupancy on falling level. { 0, 0, 9, 254, 2 }, // Should predict occupancy on level rising to (near) max. { } }; // Do a simple run over the supplied data, one call per simulated minute until the terminating record is found. // Ensures that any required predictions/detections in either direction are met. // Uses only the update() call. void simpleDataSampleRun(const ALDataSample *const data, OTV0P2BASE::SensorAmbientLightOccupancyDetectorInterface *const detector) { ASSERT_TRUE(NULL != data); ASSERT_TRUE(NULL != detector); ASSERT_FALSE(data->isEnd()) << "do not pass in empty data set"; for(const ALDataSample *dp = data; !dp->isEnd(); ++dp) { long currentMinute = dp->currentMinute(); do { fprintf(stderr, "Mins: %ld\n", currentMinute); const bool prediction = detector->update(dp->L); const uint8_t expected = dp->expected; if(0 != expected) { // If a particular outcome was expected, test against it. const bool expectedOccupancy = (expected > 1); EXPECT_EQ(expectedOccupancy, prediction); } ++currentMinute; } while((!(dp+1)->isEnd()) && (currentMinute < (dp+1)->currentMinute())); } } // Basic test of update() behaviour. TEST(AmbientLightOccupancyDetection,simpleDataSampleRun) { OTV0P2BASE::SensorAmbientLightOccupancyDetectorSimple ds1; simpleDataSampleRun(trivialSample1, &ds1); } <commit_msg>TODO-996: WIP<commit_after>/* The OpenTRV project licenses this file to you under the Apache Licence, Version 2.0 (the "Licence"); you may not use this file except in compliance with the Licence. You may obtain a copy of the Licence at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the Licence for the specific language governing permissions and limitations under the Licence. Author(s) / Copyright (s): Damon Hart-Davis 2016 */ /* * Driver for OTV0P2BASE_SensorAmbientLightOccupancy tests. */ #include <stdint.h> #include <gtest/gtest.h> #include <OTV0p2Base.h> #include "OTV0P2BASE_SensorAmbientLightOccupancy.h" // Sanity test. TEST(AmbientLightOccupancyDetection,SanityTest) { EXPECT_EQ(42, 42); } // Basic test of update() behaviour. TEST(AmbientLightOccupancyDetection,updateBasics) { // Check that initial update never indicates occupancy. OTV0P2BASE::SensorAmbientLightOccupancyDetectorSimple ds1; EXPECT_FALSE(ds1.update(0)) << "no initial update should imply occupancy"; OTV0P2BASE::SensorAmbientLightOccupancyDetectorSimple ds2; EXPECT_FALSE(ds2.update(255)) << "no initial update should imply occupancy"; // Check that update from 0 to max does force occupancy indication (but steady does not). EXPECT_TRUE(ds1.update(255)) << "update from 0 to 255 (max) illumination should signal occupancy"; EXPECT_FALSE(ds2.update(255)) << "unchanged 255 (max) light level should not imply occupancy"; } class ALDataSample { public: const uint8_t d, H, M, L, expected; // Day/hour/minute and light level and expected result. // An expected result of 0 means no particular result expected from this (anything is acceptable). // An expected result of 1 means occupancy should NOT be reported for this sample. // An expected result of 2+ means occupancy should be reported for this sample. ALDataSample(uint8_t dayOfMonth, uint8_t hour24, uint8_t minute, uint8_t lightLevel, uint8_t expectedResult = 0) : d(dayOfMonth), H(hour24), M(minute), L(lightLevel), expected(expectedResult) { } // Create/mark a terminating entry; all input values invalid. ALDataSample() : d(255), H(255), M(255), L(255), expected(0) { } // Compute current minute for this record. long currentMinute() const { return((((d * 24L) + H) * 60L) + M); } // True for empty/termination data record. bool isEnd() const { return(d > 31); } }; // Trivial sample, testing initial reaction to start transient. static const ALDataSample trivialSample1[] = { { 0, 0, 0, 254, 1 }, // Should NOT predict occupancy on first tick. { 0, 0, 1, 0, 1 }, // Should NOT predict occupancy on falling level. { 0, 0, 5, 0 }, // Should NOT predict occupancy on falling level. { 0, 0, 9, 254, 2 }, // Should predict occupancy on level rising to (near) max. { } }; // Do a simple run over the supplied data, one call per simulated minute until the terminating record is found. // Must be supplied in ascending order with a terminating (empty) entry. // Repeated rows with the same light value and expected result can be omitted // as they will be synthesised by this routine for each virtual minute until the next supplied item. // Ensures that any required predictions/detections in either direction are met. // Uses only the update() call. void simpleDataSampleRun(const ALDataSample *const data, OTV0P2BASE::SensorAmbientLightOccupancyDetectorInterface *const detector) { ASSERT_TRUE(NULL != data); ASSERT_TRUE(NULL != detector); ASSERT_FALSE(data->isEnd()) << "do not pass in empty data set"; for(const ALDataSample *dp = data; !dp->isEnd(); ++dp) { long currentMinute = dp->currentMinute(); do { fprintf(stderr, "Mins: %ld\n", currentMinute); const bool prediction = detector->update(dp->L); const uint8_t expected = dp->expected; if(0 != expected) { // If a particular outcome was expected, test against it. const bool expectedOccupancy = (expected > 1); EXPECT_EQ(expectedOccupancy, prediction); } ++currentMinute; } while((!(dp+1)->isEnd()) && (currentMinute < (dp+1)->currentMinute())); } } // Basic test of update() behaviour. TEST(AmbientLightOccupancyDetection,simpleDataSampleRun) { OTV0P2BASE::SensorAmbientLightOccupancyDetectorSimple ds1; simpleDataSampleRun(trivialSample1, &ds1); } <|endoftext|>
<commit_before>#include <zlib.h> #include <lcm/lcm-cpp.hpp> #include <lcmtypes/bot_core/planar_lidar_t.hpp> #include <lcmtypes/bot_core/pointcloud_t.hpp> #include <lcmtypes/bot_core/pose_t.hpp> #include <lcmtypes/bot_core/rigid_transform_t.hpp> #include <boost/shared_ptr.hpp> #include "lidar-odometry.hpp" #include <ConciseArgs> #include <bot_param/param_client.h> #include <bot_frames/bot_frames.h> using namespace std; struct CommandLineConfig { bool use_velodyne; bool init_with_message; // initialize off of a pose or vicon std::string output_channel; std::string init_channel; }; class App{ public: App(boost::shared_ptr<lcm::LCM> &lcm_, const CommandLineConfig& cl_cfg_); ~App(){ } private: boost::shared_ptr<lcm::LCM> lcm_; const CommandLineConfig cl_cfg_; BotParam* botparam_; BotFrames* botframes_; void lidarHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const bot_core::planar_lidar_t* msg); void pointCloudHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const bot_core::pointcloud_t* msg); LidarOdom* lidarOdom_; Eigen::Isometry3d body_to_lidar_; // Fixed tf from the lidar to the robot's base link Eigen::Isometry3d world_to_body_init_; // Captures the position of the body frame in world at launch Eigen::Isometry3d world_to_body_now_; // running position estimate // Init handlers: void rigidTransformInitHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const bot_core::rigid_transform_t* msg); void poseInitHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const bot_core::pose_t* msg); void initState( const double trans[3], const double quat[4]); bool pose_initialized_; bot_core::pose_t getPoseAsBotPose(Eigen::Isometry3d pose, int64_t utime); int get_trans_with_utime(BotFrames *bot_frames, const char *from_frame, const char *to_frame, int64_t utime, Eigen::Isometry3d& mat); }; App::App(boost::shared_ptr<lcm::LCM> &lcm_, const CommandLineConfig& cl_cfg_) : lcm_(lcm_), cl_cfg_(cl_cfg_){ // Set up frames and config: botparam_ = bot_param_new_from_server(lcm_->getUnderlyingLCM(), 0); botframes_= bot_frames_get_global(lcm_->getUnderlyingLCM(), botparam_); if (cl_cfg_.use_velodyne){ lcm_->subscribe("VELODYNE_HORIZONTAL",&App::pointCloudHandler,this); int status = get_trans_with_utime( botframes_ , "VELODYNE", "body" , 0, body_to_lidar_); }else{ lcm_->subscribe("SCAN",&App::lidarHandler,this); int status = get_trans_with_utime( botframes_ , "SCAN", "body" , 0, body_to_lidar_); } pose_initialized_ = false; if (!cl_cfg_.init_with_message){ std::cout << "Init internal est using default\n"; world_to_body_init_ = Eigen::Isometry3d::Identity(); /* world_to_body_init_.setIdentity(); world_to_body_init_.translation() << 1.2, 1.67, 0.32; Eigen::Quaterniond q(-0.045668, -0.004891, -0.00909, 0.9989); world_to_body_init_.rotate(q); bot_core::pose_t pose_msg_body = getPoseAsBotPose( world_to_lidar_init_ , 0); lcm_->publish("POSE_BODY_ALT", &pose_msg_body ); pose_initialized_ = true; */ pose_initialized_ = true; }else{ lcm_->subscribe("VICON_BODY|VICON_FRONTPLATE",&App::rigidTransformInitHandler,this); lcm_->subscribe(cl_cfg_.init_channel,&App::poseInitHandler,this); std::cout << "Waiting for Init message to LIDAR estimator\n"; } lidarOdom_ = new LidarOdom(lcm_); } int App::get_trans_with_utime(BotFrames *bot_frames, const char *from_frame, const char *to_frame, int64_t utime, Eigen::Isometry3d & mat){ int status; double matx[16]; status = bot_frames_get_trans_mat_4x4_with_utime( bot_frames, from_frame, to_frame, utime, matx); for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { mat(i,j) = matx[i*4+j]; } } return status; } bot_core::pose_t App::getPoseAsBotPose(Eigen::Isometry3d pose, int64_t utime){ bot_core::pose_t pose_msg; pose_msg.utime = utime; pose_msg.pos[0] = pose.translation().x(); pose_msg.pos[1] = pose.translation().y(); pose_msg.pos[2] = pose.translation().z(); Eigen::Quaterniond r_x(pose.rotation()); pose_msg.orientation[0] = r_x.w(); pose_msg.orientation[1] = r_x.x(); pose_msg.orientation[2] = r_x.y(); pose_msg.orientation[3] = r_x.z(); return pose_msg; } void App::lidarHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const bot_core::planar_lidar_t* msg){ if (!pose_initialized_){ std::cout << "Estimate not initialised, exiting lidarHandler\n"; return; } // 1. Update LIDAR Odometry std::vector<float> ranges_copy = msg->ranges; float* ranges = &ranges_copy[0]; lidarOdom_->doOdometry(ranges, msg->nranges, msg->rad0, msg->radstep, msg->utime); // 2. Determine the body position using the LIDAR motion estimate: Eigen::Isometry3d lidar_init_to_lidar_now = lidarOdom_->getCurrentPose(); Eigen::Isometry3d world_to_lidar_now = world_to_body_init_*body_to_lidar_*lidar_init_to_lidar_now; world_to_body_now_ = world_to_lidar_now * body_to_lidar_.inverse(); //bot_core::pose_t pose_msg = getPoseAsBotPose( lidar_init_to_lidar_now , msg->utime); //lcm_->publish("POSE_BODY_ALT", &pose_msg ); bot_core::pose_t pose_msg_body = getPoseAsBotPose( world_to_body_now_ , msg->utime); lcm_->publish(cl_cfg_.output_channel, &pose_msg_body ); } void App::pointCloudHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const bot_core::pointcloud_t* msg){ if (!pose_initialized_){ std::cout << "Estimate not initialised, exiting pointCloudHandler\n"; return; } // 1. Update LIDAR Odometry std::vector<float> x; std::vector<float> y; for (int i=0;i<msg->n_points; i++){ x.push_back( msg->points[i][0] ); y.push_back( msg->points[i][1] ); } lidarOdom_->doOdometry(x, y, msg->n_points, msg->utime); // 2. Determine the body position using the LIDAR motion estimate: Eigen::Isometry3d lidar_init_to_lidar_now = lidarOdom_->getCurrentPose(); Eigen::Isometry3d world_to_lidar_now = world_to_body_init_*body_to_lidar_*lidar_init_to_lidar_now; world_to_body_now_ = world_to_lidar_now * body_to_lidar_.inverse(); //bot_core::pose_t pose_msg = getPoseAsBotPose( world_to_lidar_now , msg->utime); //lcm_->publish("POSE_BODY_ALT", &pose_msg ); bot_core::pose_t pose_msg_body = getPoseAsBotPose( world_to_body_now_ , msg->utime); lcm_->publish(cl_cfg_.output_channel, &pose_msg_body ); } void App::initState(const double trans[3], const double quat[4]){ if ( !cl_cfg_.init_with_message || pose_initialized_ ){ return; } std::cout << "Init internal est using rigid transform or pose\n"; world_to_body_init_.setIdentity(); world_to_body_init_.translation() << trans[0], trans[1] , trans[2]; Eigen::Quaterniond quatE = Eigen::Quaterniond(quat[0], quat[1], quat[2], quat[3]); world_to_body_init_.rotate(quatE); pose_initialized_ = TRUE; } void App::rigidTransformInitHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const bot_core::rigid_transform_t* msg){ initState(msg->trans, msg->quat); } void App::poseInitHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const bot_core::pose_t* msg){ initState(msg->pos, msg->orientation); } int main(int argc, char **argv){ CommandLineConfig cl_cfg; cl_cfg.use_velodyne = false; cl_cfg.init_with_message = TRUE; cl_cfg.output_channel = "POSE_BODY"; ConciseArgs parser(argc, argv, "simple-fusion"); parser.add(cl_cfg.init_with_message, "g", "init_with_message", "Bootstrap internal estimate using VICON or POSE_INIT"); parser.add(cl_cfg.output_channel, "o", "output_channel", "Output message e.g POSE_BODY"); parser.add(cl_cfg.use_velodyne, "v", "use_velodyne", "Use a velodyne instead of the LIDAR"); parser.add(cl_cfg.init_channel, "i", "init_channel", "Read the init message from this channel, e.g., POSE_GROUND_TRUTH"); parser.parse(); boost::shared_ptr<lcm::LCM> lcm(new lcm::LCM); if(!lcm->good()){ std::cerr <<"ERROR: lcm is not good()" <<std::endl; } App app= App(lcm, cl_cfg); while(0 == lcm->handle()); } <commit_msg>setting default value for init message<commit_after>#include <zlib.h> #include <lcm/lcm-cpp.hpp> #include <lcmtypes/bot_core/planar_lidar_t.hpp> #include <lcmtypes/bot_core/pointcloud_t.hpp> #include <lcmtypes/bot_core/pose_t.hpp> #include <lcmtypes/bot_core/rigid_transform_t.hpp> #include <boost/shared_ptr.hpp> #include "lidar-odometry.hpp" #include <ConciseArgs> #include <bot_param/param_client.h> #include <bot_frames/bot_frames.h> using namespace std; struct CommandLineConfig { bool use_velodyne; bool init_with_message; // initialize off of a pose or vicon std::string output_channel; std::string init_channel; }; class App{ public: App(boost::shared_ptr<lcm::LCM> &lcm_, const CommandLineConfig& cl_cfg_); ~App(){ } private: boost::shared_ptr<lcm::LCM> lcm_; const CommandLineConfig cl_cfg_; BotParam* botparam_; BotFrames* botframes_; void lidarHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const bot_core::planar_lidar_t* msg); void pointCloudHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const bot_core::pointcloud_t* msg); LidarOdom* lidarOdom_; Eigen::Isometry3d body_to_lidar_; // Fixed tf from the lidar to the robot's base link Eigen::Isometry3d world_to_body_init_; // Captures the position of the body frame in world at launch Eigen::Isometry3d world_to_body_now_; // running position estimate // Init handlers: void rigidTransformInitHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const bot_core::rigid_transform_t* msg); void poseInitHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const bot_core::pose_t* msg); void initState( const double trans[3], const double quat[4]); bool pose_initialized_; bot_core::pose_t getPoseAsBotPose(Eigen::Isometry3d pose, int64_t utime); int get_trans_with_utime(BotFrames *bot_frames, const char *from_frame, const char *to_frame, int64_t utime, Eigen::Isometry3d& mat); }; App::App(boost::shared_ptr<lcm::LCM> &lcm_, const CommandLineConfig& cl_cfg_) : lcm_(lcm_), cl_cfg_(cl_cfg_){ // Set up frames and config: botparam_ = bot_param_new_from_server(lcm_->getUnderlyingLCM(), 0); botframes_= bot_frames_get_global(lcm_->getUnderlyingLCM(), botparam_); if (cl_cfg_.use_velodyne){ lcm_->subscribe("VELODYNE_HORIZONTAL",&App::pointCloudHandler,this); int status = get_trans_with_utime( botframes_ , "VELODYNE", "body" , 0, body_to_lidar_); }else{ lcm_->subscribe("SCAN",&App::lidarHandler,this); int status = get_trans_with_utime( botframes_ , "SCAN", "body" , 0, body_to_lidar_); } pose_initialized_ = false; if (!cl_cfg_.init_with_message){ std::cout << "Init internal est using default\n"; world_to_body_init_ = Eigen::Isometry3d::Identity(); /* world_to_body_init_.setIdentity(); world_to_body_init_.translation() << 1.2, 1.67, 0.32; Eigen::Quaterniond q(-0.045668, -0.004891, -0.00909, 0.9989); world_to_body_init_.rotate(q); bot_core::pose_t pose_msg_body = getPoseAsBotPose( world_to_lidar_init_ , 0); lcm_->publish("POSE_BODY_ALT", &pose_msg_body ); pose_initialized_ = true; */ pose_initialized_ = true; }else{ lcm_->subscribe("VICON_BODY|VICON_FRONTPLATE",&App::rigidTransformInitHandler,this); lcm_->subscribe(cl_cfg_.init_channel,&App::poseInitHandler,this); std::cout << "Waiting for Init message to LIDAR estimator\n"; } lidarOdom_ = new LidarOdom(lcm_); } int App::get_trans_with_utime(BotFrames *bot_frames, const char *from_frame, const char *to_frame, int64_t utime, Eigen::Isometry3d & mat){ int status; double matx[16]; status = bot_frames_get_trans_mat_4x4_with_utime( bot_frames, from_frame, to_frame, utime, matx); for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { mat(i,j) = matx[i*4+j]; } } return status; } bot_core::pose_t App::getPoseAsBotPose(Eigen::Isometry3d pose, int64_t utime){ bot_core::pose_t pose_msg; pose_msg.utime = utime; pose_msg.pos[0] = pose.translation().x(); pose_msg.pos[1] = pose.translation().y(); pose_msg.pos[2] = pose.translation().z(); Eigen::Quaterniond r_x(pose.rotation()); pose_msg.orientation[0] = r_x.w(); pose_msg.orientation[1] = r_x.x(); pose_msg.orientation[2] = r_x.y(); pose_msg.orientation[3] = r_x.z(); return pose_msg; } void App::lidarHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const bot_core::planar_lidar_t* msg){ if (!pose_initialized_){ std::cout << "Estimate not initialised, exiting lidarHandler\n"; return; } // 1. Update LIDAR Odometry std::vector<float> ranges_copy = msg->ranges; float* ranges = &ranges_copy[0]; lidarOdom_->doOdometry(ranges, msg->nranges, msg->rad0, msg->radstep, msg->utime); // 2. Determine the body position using the LIDAR motion estimate: Eigen::Isometry3d lidar_init_to_lidar_now = lidarOdom_->getCurrentPose(); Eigen::Isometry3d world_to_lidar_now = world_to_body_init_*body_to_lidar_*lidar_init_to_lidar_now; world_to_body_now_ = world_to_lidar_now * body_to_lidar_.inverse(); //bot_core::pose_t pose_msg = getPoseAsBotPose( lidar_init_to_lidar_now , msg->utime); //lcm_->publish("POSE_BODY_ALT", &pose_msg ); bot_core::pose_t pose_msg_body = getPoseAsBotPose( world_to_body_now_ , msg->utime); lcm_->publish(cl_cfg_.output_channel, &pose_msg_body ); } void App::pointCloudHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const bot_core::pointcloud_t* msg){ if (!pose_initialized_){ std::cout << "Estimate not initialised, exiting pointCloudHandler\n"; return; } // 1. Update LIDAR Odometry std::vector<float> x; std::vector<float> y; for (int i=0;i<msg->n_points; i++){ x.push_back( msg->points[i][0] ); y.push_back( msg->points[i][1] ); } lidarOdom_->doOdometry(x, y, msg->n_points, msg->utime); // 2. Determine the body position using the LIDAR motion estimate: Eigen::Isometry3d lidar_init_to_lidar_now = lidarOdom_->getCurrentPose(); Eigen::Isometry3d world_to_lidar_now = world_to_body_init_*body_to_lidar_*lidar_init_to_lidar_now; world_to_body_now_ = world_to_lidar_now * body_to_lidar_.inverse(); //bot_core::pose_t pose_msg = getPoseAsBotPose( world_to_lidar_now , msg->utime); //lcm_->publish("POSE_BODY_ALT", &pose_msg ); bot_core::pose_t pose_msg_body = getPoseAsBotPose( world_to_body_now_ , msg->utime); lcm_->publish(cl_cfg_.output_channel, &pose_msg_body ); } void App::initState(const double trans[3], const double quat[4]){ if ( !cl_cfg_.init_with_message || pose_initialized_ ){ return; } std::cout << "Init internal est using rigid transform or pose\n"; world_to_body_init_.setIdentity(); world_to_body_init_.translation() << trans[0], trans[1] , trans[2]; Eigen::Quaterniond quatE = Eigen::Quaterniond(quat[0], quat[1], quat[2], quat[3]); world_to_body_init_.rotate(quatE); pose_initialized_ = TRUE; } void App::rigidTransformInitHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const bot_core::rigid_transform_t* msg){ initState(msg->trans, msg->quat); } void App::poseInitHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const bot_core::pose_t* msg){ initState(msg->pos, msg->orientation); } int main(int argc, char **argv){ CommandLineConfig cl_cfg; cl_cfg.use_velodyne = false; cl_cfg.init_with_message = TRUE; cl_cfg.output_channel = "POSE_BODY"; cl_cfg.init_channel = "POSE_GROUND_TRUTH"; ConciseArgs parser(argc, argv, "simple-fusion"); parser.add(cl_cfg.init_with_message, "g", "init_with_message", "Bootstrap internal estimate using VICON or POSE_INIT"); parser.add(cl_cfg.output_channel, "o", "output_channel", "Output message e.g POSE_BODY"); parser.add(cl_cfg.use_velodyne, "v", "use_velodyne", "Use a velodyne instead of the LIDAR"); parser.add(cl_cfg.init_channel, "i", "init_channel", "Read the init message from this channel, e.g., POSE_GROUND_TRUTH"); parser.parse(); boost::shared_ptr<lcm::LCM> lcm(new lcm::LCM); if(!lcm->good()){ std::cerr <<"ERROR: lcm is not good()" <<std::endl; } App app= App(lcm, cl_cfg); while(0 == lcm->handle()); } <|endoftext|>
<commit_before>// Copyright (c) 2006-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/common/chrome_paths.h" #include "base/command_line.h" #include "base/file_util.h" #include "base/logging.h" #include "base/path_service.h" #include "base/string_util.h" #include "base/sys_info.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_paths_internal.h" #include "chrome/common/chrome_switches.h" #if defined(OS_MACOSX) #include "base/mac_util.h" #endif namespace { // File name of the internal Flash plugin on different platforms. const FilePath::CharType kInternalFlashPluginFileName[] = #if defined(OS_MACOSX) FILE_PATH_LITERAL("Flash Player Plugin for Chrome.plugin"); #elif defined(OS_WIN) FILE_PATH_LITERAL("gcswf32.dll"); #else // OS_LINUX, etc. FILE_PATH_LITERAL("libgcflashplayer.so"); #endif } // namespace namespace chrome { // Gets the path for internal (or bundled) plugins. bool GetInternalPluginsDirectory(FilePath* result) { #if defined(OS_MACOSX) // If called from Chrome, get internal plugins from the versioned directory. if (mac_util::AmIBundled()) { *result = chrome::GetVersionedDirectory(); DCHECK(!result->empty()); return true; } // In tests, just look in the module directory (below). #endif // The rest of the world expects plugins in the module directory. return PathService::Get(base::DIR_MODULE, result); } bool GetGearsPluginPathFromCommandLine(FilePath* path) { #ifndef NDEBUG // for debugging, support a cmd line based override FilePath plugin_path = CommandLine::ForCurrentProcess()->GetSwitchValuePath( switches::kGearsPluginPathOverride); *path = plugin_path; return !plugin_path.empty(); #else return false; #endif } bool PathProvider(int key, FilePath* result) { // Some keys are just aliases... switch (key) { case chrome::DIR_APP: return PathService::Get(base::DIR_MODULE, result); case chrome::DIR_LOGS: #ifdef NDEBUG // Release builds write to the data dir return PathService::Get(chrome::DIR_USER_DATA, result); #else // Debug builds write next to the binary (in the build tree) #if defined(OS_MACOSX) if (!PathService::Get(base::DIR_EXE, result)) return false; if (mac_util::AmIBundled()) { // If we're called from chrome, dump it beside the app (outside the // app bundle), if we're called from a unittest, we'll already // outside the bundle so use the exe dir. // exe_dir gave us .../Chromium.app/Contents/MacOS/Chromium. *result = result->DirName(); *result = result->DirName(); *result = result->DirName(); } return true; #else return PathService::Get(base::DIR_EXE, result); #endif // defined(OS_MACOSX) #endif // NDEBUG case chrome::FILE_RESOURCE_MODULE: return PathService::Get(base::FILE_MODULE, result); } // Assume that we will not need to create the directory if it does not exist. // This flag can be set to true for the cases where we want to create it. bool create_dir = false; FilePath cur; switch (key) { case chrome::DIR_USER_DATA: if (!GetDefaultUserDataDirectory(&cur)) { NOTREACHED(); return false; } create_dir = true; break; case chrome::DIR_USER_DOCUMENTS: if (!GetUserDocumentsDirectory(&cur)) return false; create_dir = true; break; case chrome::DIR_DEFAULT_DOWNLOADS_SAFE: #if defined(OS_WIN) if (!GetUserDownloadsDirectorySafe(&cur)) return false; break; #else // Fall through for all other platforms. #endif case chrome::DIR_DEFAULT_DOWNLOADS: if (!GetUserDownloadsDirectory(&cur)) return false; // Do not create the download directory here, we have done it twice now // and annoyed a lot of users. break; case chrome::DIR_CRASH_DUMPS: // The crash reports are always stored relative to the default user data // directory. This avoids the problem of having to re-initialize the // exception handler after parsing command line options, which may // override the location of the app's profile directory. if (!GetDefaultUserDataDirectory(&cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("Crash Reports")); create_dir = true; break; case chrome::DIR_USER_DESKTOP: if (!GetUserDesktop(&cur)) return false; break; case chrome::DIR_RESOURCES: #if defined(OS_MACOSX) cur = mac_util::MainAppBundlePath(); cur = cur.Append(FILE_PATH_LITERAL("Resources")); #else if (!PathService::Get(chrome::DIR_APP, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("resources")); #endif break; case chrome::DIR_SHARED_RESOURCES: if (!PathService::Get(chrome::DIR_RESOURCES, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("shared")); break; case chrome::DIR_BOOKMARK_MANAGER: if (!PathService::Get(chrome::DIR_RESOURCES, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("bookmark_manager")); break; case chrome::DIR_INSPECTOR: if (!PathService::Get(chrome::DIR_RESOURCES, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("inspector")); break; case chrome::DIR_NET_INTERNALS: if (!PathService::Get(chrome::DIR_RESOURCES, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("net_internals")); break; case chrome::DIR_APP_DICTIONARIES: #if defined(OS_LINUX) || defined(OS_MACOSX) // We can't write into the EXE dir on Linux, so keep dictionaries // alongside the safe browsing database in the user data dir. // And we don't want to write into the bundle on the Mac, so push // it to the user data dir there also. if (!PathService::Get(chrome::DIR_USER_DATA, &cur)) return false; #else if (!PathService::Get(base::DIR_EXE, &cur)) return false; #endif cur = cur.Append(FILE_PATH_LITERAL("Dictionaries")); create_dir = true; break; case chrome::DIR_USER_DATA_TEMP: if (!PathService::Get(chrome::DIR_USER_DATA, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("Temp")); create_dir = true; break; case chrome::DIR_INTERNAL_PLUGINS: if (!GetInternalPluginsDirectory(&cur)) return false; break; case chrome::FILE_LOCAL_STATE: if (!PathService::Get(chrome::DIR_USER_DATA, &cur)) return false; cur = cur.Append(chrome::kLocalStateFilename); break; case chrome::FILE_RECORDED_SCRIPT: if (!PathService::Get(chrome::DIR_USER_DATA, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("script.log")); break; case chrome::FILE_GEARS_PLUGIN: if (!GetGearsPluginPathFromCommandLine(&cur)) { #if defined(OS_WIN) // Search for gears.dll alongside chrome.dll first. This new model // allows us to package gears.dll with the Chrome installer and update // it while Chrome is running. if (!GetInternalPluginsDirectory(&cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("gears.dll")); if (!file_util::PathExists(cur)) { if (!PathService::Get(base::DIR_EXE, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("plugins")); cur = cur.Append(FILE_PATH_LITERAL("gears")); cur = cur.Append(FILE_PATH_LITERAL("gears.dll")); } #else // No gears.dll on non-Windows systems. return false; #endif } break; case chrome::FILE_FLASH_PLUGIN: if (!GetInternalPluginsDirectory(&cur)) return false; cur = cur.Append(kInternalFlashPluginFileName); if (!file_util::PathExists(cur)) return false; break; case chrome::FILE_PDF_PLUGIN: if (!PathService::Get(base::DIR_MODULE, &cur)) return false; #if defined(OS_WIN) cur = cur.Append(FILE_PATH_LITERAL("pdf.dll")); #elif defined(OS_MACOSX) NOTIMPLEMENTED(); return false; #else // Linux and Chrome OS cur = cur.Append(FILE_PATH_LITERAL("libpdf.so")); #endif if (!file_util::PathExists(cur)) return false; break; #if defined(OS_CHROMEOS) case chrome::FILE_CHROMEOS_API: if (!PathService::Get(base::DIR_MODULE, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("chromeos")); cur = cur.Append(FILE_PATH_LITERAL("libcros.so")); break; #endif // The following are only valid in the development environment, and // will fail if executed from an installed executable (because the // generated path won't exist). case chrome::DIR_TEST_DATA: if (!PathService::Get(base::DIR_SOURCE_ROOT, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("chrome")); cur = cur.Append(FILE_PATH_LITERAL("test")); cur = cur.Append(FILE_PATH_LITERAL("data")); if (!file_util::PathExists(cur)) // we don't want to create this return false; break; case chrome::DIR_TEST_TOOLS: if (!PathService::Get(base::DIR_SOURCE_ROOT, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("chrome")); cur = cur.Append(FILE_PATH_LITERAL("tools")); cur = cur.Append(FILE_PATH_LITERAL("test")); if (!file_util::PathExists(cur)) // we don't want to create this return false; break; default: return false; } if (create_dir && !file_util::PathExists(cur) && !file_util::CreateDirectory(cur)) return false; *result = cur; return true; } // This cannot be done as a static initializer sadly since Visual Studio will // eliminate this object file if there is no direct entry point into it. void RegisterPathProvider() { PathService::RegisterProvider(PathProvider, PATH_START, PATH_END); } } // namespace chrome <commit_msg>[Mac] stop the output that is slowing down all the tests that seem to walk this code path.<commit_after>// Copyright (c) 2006-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/common/chrome_paths.h" #include "base/command_line.h" #include "base/file_util.h" #include "base/logging.h" #include "base/path_service.h" #include "base/string_util.h" #include "base/sys_info.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_paths_internal.h" #include "chrome/common/chrome_switches.h" #if defined(OS_MACOSX) #include "base/mac_util.h" #endif namespace { // File name of the internal Flash plugin on different platforms. const FilePath::CharType kInternalFlashPluginFileName[] = #if defined(OS_MACOSX) FILE_PATH_LITERAL("Flash Player Plugin for Chrome.plugin"); #elif defined(OS_WIN) FILE_PATH_LITERAL("gcswf32.dll"); #else // OS_LINUX, etc. FILE_PATH_LITERAL("libgcflashplayer.so"); #endif } // namespace namespace chrome { // Gets the path for internal (or bundled) plugins. bool GetInternalPluginsDirectory(FilePath* result) { #if defined(OS_MACOSX) // If called from Chrome, get internal plugins from the versioned directory. if (mac_util::AmIBundled()) { *result = chrome::GetVersionedDirectory(); DCHECK(!result->empty()); return true; } // In tests, just look in the module directory (below). #endif // The rest of the world expects plugins in the module directory. return PathService::Get(base::DIR_MODULE, result); } bool GetGearsPluginPathFromCommandLine(FilePath* path) { #ifndef NDEBUG // for debugging, support a cmd line based override FilePath plugin_path = CommandLine::ForCurrentProcess()->GetSwitchValuePath( switches::kGearsPluginPathOverride); *path = plugin_path; return !plugin_path.empty(); #else return false; #endif } bool PathProvider(int key, FilePath* result) { // Some keys are just aliases... switch (key) { case chrome::DIR_APP: return PathService::Get(base::DIR_MODULE, result); case chrome::DIR_LOGS: #ifdef NDEBUG // Release builds write to the data dir return PathService::Get(chrome::DIR_USER_DATA, result); #else // Debug builds write next to the binary (in the build tree) #if defined(OS_MACOSX) if (!PathService::Get(base::DIR_EXE, result)) return false; if (mac_util::AmIBundled()) { // If we're called from chrome, dump it beside the app (outside the // app bundle), if we're called from a unittest, we'll already // outside the bundle so use the exe dir. // exe_dir gave us .../Chromium.app/Contents/MacOS/Chromium. *result = result->DirName(); *result = result->DirName(); *result = result->DirName(); } return true; #else return PathService::Get(base::DIR_EXE, result); #endif // defined(OS_MACOSX) #endif // NDEBUG case chrome::FILE_RESOURCE_MODULE: return PathService::Get(base::FILE_MODULE, result); } // Assume that we will not need to create the directory if it does not exist. // This flag can be set to true for the cases where we want to create it. bool create_dir = false; FilePath cur; switch (key) { case chrome::DIR_USER_DATA: if (!GetDefaultUserDataDirectory(&cur)) { NOTREACHED(); return false; } create_dir = true; break; case chrome::DIR_USER_DOCUMENTS: if (!GetUserDocumentsDirectory(&cur)) return false; create_dir = true; break; case chrome::DIR_DEFAULT_DOWNLOADS_SAFE: #if defined(OS_WIN) if (!GetUserDownloadsDirectorySafe(&cur)) return false; break; #else // Fall through for all other platforms. #endif case chrome::DIR_DEFAULT_DOWNLOADS: if (!GetUserDownloadsDirectory(&cur)) return false; // Do not create the download directory here, we have done it twice now // and annoyed a lot of users. break; case chrome::DIR_CRASH_DUMPS: // The crash reports are always stored relative to the default user data // directory. This avoids the problem of having to re-initialize the // exception handler after parsing command line options, which may // override the location of the app's profile directory. if (!GetDefaultUserDataDirectory(&cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("Crash Reports")); create_dir = true; break; case chrome::DIR_USER_DESKTOP: if (!GetUserDesktop(&cur)) return false; break; case chrome::DIR_RESOURCES: #if defined(OS_MACOSX) cur = mac_util::MainAppBundlePath(); cur = cur.Append(FILE_PATH_LITERAL("Resources")); #else if (!PathService::Get(chrome::DIR_APP, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("resources")); #endif break; case chrome::DIR_SHARED_RESOURCES: if (!PathService::Get(chrome::DIR_RESOURCES, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("shared")); break; case chrome::DIR_BOOKMARK_MANAGER: if (!PathService::Get(chrome::DIR_RESOURCES, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("bookmark_manager")); break; case chrome::DIR_INSPECTOR: if (!PathService::Get(chrome::DIR_RESOURCES, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("inspector")); break; case chrome::DIR_NET_INTERNALS: if (!PathService::Get(chrome::DIR_RESOURCES, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("net_internals")); break; case chrome::DIR_APP_DICTIONARIES: #if defined(OS_LINUX) || defined(OS_MACOSX) // We can't write into the EXE dir on Linux, so keep dictionaries // alongside the safe browsing database in the user data dir. // And we don't want to write into the bundle on the Mac, so push // it to the user data dir there also. if (!PathService::Get(chrome::DIR_USER_DATA, &cur)) return false; #else if (!PathService::Get(base::DIR_EXE, &cur)) return false; #endif cur = cur.Append(FILE_PATH_LITERAL("Dictionaries")); create_dir = true; break; case chrome::DIR_USER_DATA_TEMP: if (!PathService::Get(chrome::DIR_USER_DATA, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("Temp")); create_dir = true; break; case chrome::DIR_INTERNAL_PLUGINS: if (!GetInternalPluginsDirectory(&cur)) return false; break; case chrome::FILE_LOCAL_STATE: if (!PathService::Get(chrome::DIR_USER_DATA, &cur)) return false; cur = cur.Append(chrome::kLocalStateFilename); break; case chrome::FILE_RECORDED_SCRIPT: if (!PathService::Get(chrome::DIR_USER_DATA, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("script.log")); break; case chrome::FILE_GEARS_PLUGIN: if (!GetGearsPluginPathFromCommandLine(&cur)) { #if defined(OS_WIN) // Search for gears.dll alongside chrome.dll first. This new model // allows us to package gears.dll with the Chrome installer and update // it while Chrome is running. if (!GetInternalPluginsDirectory(&cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("gears.dll")); if (!file_util::PathExists(cur)) { if (!PathService::Get(base::DIR_EXE, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("plugins")); cur = cur.Append(FILE_PATH_LITERAL("gears")); cur = cur.Append(FILE_PATH_LITERAL("gears.dll")); } #else // No gears.dll on non-Windows systems. return false; #endif } break; case chrome::FILE_FLASH_PLUGIN: if (!GetInternalPluginsDirectory(&cur)) return false; cur = cur.Append(kInternalFlashPluginFileName); if (!file_util::PathExists(cur)) return false; break; case chrome::FILE_PDF_PLUGIN: if (!PathService::Get(base::DIR_MODULE, &cur)) return false; #if defined(OS_WIN) cur = cur.Append(FILE_PATH_LITERAL("pdf.dll")); #elif defined(OS_MACOSX) // http://crbug.com/44900 return false; #else // Linux and Chrome OS cur = cur.Append(FILE_PATH_LITERAL("libpdf.so")); #endif if (!file_util::PathExists(cur)) return false; break; #if defined(OS_CHROMEOS) case chrome::FILE_CHROMEOS_API: if (!PathService::Get(base::DIR_MODULE, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("chromeos")); cur = cur.Append(FILE_PATH_LITERAL("libcros.so")); break; #endif // The following are only valid in the development environment, and // will fail if executed from an installed executable (because the // generated path won't exist). case chrome::DIR_TEST_DATA: if (!PathService::Get(base::DIR_SOURCE_ROOT, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("chrome")); cur = cur.Append(FILE_PATH_LITERAL("test")); cur = cur.Append(FILE_PATH_LITERAL("data")); if (!file_util::PathExists(cur)) // we don't want to create this return false; break; case chrome::DIR_TEST_TOOLS: if (!PathService::Get(base::DIR_SOURCE_ROOT, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("chrome")); cur = cur.Append(FILE_PATH_LITERAL("tools")); cur = cur.Append(FILE_PATH_LITERAL("test")); if (!file_util::PathExists(cur)) // we don't want to create this return false; break; default: return false; } if (create_dir && !file_util::PathExists(cur) && !file_util::CreateDirectory(cur)) return false; *result = cur; return true; } // This cannot be done as a static initializer sadly since Visual Studio will // eliminate this object file if there is no direct entry point into it. void RegisterPathProvider() { PathService::RegisterProvider(PathProvider, PATH_START, PATH_END); } } // namespace chrome <|endoftext|>
<commit_before>#include <string> #include "nbind/api.h" #include "control.h" #include "ui.h" #include "values.h" class UiWindow { DEFINE_EVENT(onClosing) DEFINE_EVENT(onContentSizeChanged) private: uiWindow *win; public: UiWindow(std::string title, int width, int height, bool hasMenubar); uiWindow *getHandle(); void show(); void close(); void setMargined(bool margined); bool getMargined(); void setChild(UiControl *control); void setTitle(std::string title); std::string getTitle(); bool getFullscreen(); void setFullscreen(bool value); bool getBorderless(); void setBorderless(bool value); Size getContentSize(); void setContentSize(Size value); }; static int UiWindow_onClosing(uiWindow *w, void *data) { nbind::cbFunction *cb = (nbind::cbFunction *)data; (*cb)(); return 0; } void UiWindow::onClosing(nbind::cbFunction &cb) { onClosingCallback = new nbind::cbFunction(cb); uiWindowOnClosing(uiWindow(getHandle()), UiWindow_onClosing, onClosingCallback); } static void UiWindow_onContentSizeChanged(uiWindow *w, void *data) { nbind::cbFunction *cb = (nbind::cbFunction *)data; (*cb)(); } void UiWindow::onContentSizeChanged(nbind::cbFunction &cb) { onContentSizeChangedCallback = new nbind::cbFunction(cb); uiWindowOnContentSizeChanged(uiWindow(getHandle()), UiWindow_onContentSizeChanged, onContentSizeChangedCallback); } UiWindow::UiWindow(std::string title, int width, int height, bool hasMenubar) { win = uiNewWindow(title.c_str(), width, height, hasMenubar); } uiWindow *UiWindow::getHandle() { return win; } void UiWindow::show() { uiControlShow(uiControl(win)); } void UiWindow::close() { uiControlDestroy(uiControl(win)); } void UiWindow::setMargined(bool margined) { uiWindowSetMargined(win, margined); } bool UiWindow::getMargined() { return uiWindowMargined(win); } void UiWindow::setChild(UiControl *control) { uiWindowSetChild(win, control->getHandle()); } void UiWindow::setTitle(std::string title) { uiWindowSetTitle(win, title.c_str()); } std::string UiWindow::getTitle() { char *char_ptr = uiWindowTitle(win); std::string s(char_ptr); uiFreeText(char_ptr); return s; } bool UiWindow::getFullscreen() { return uiWindowFullscreen(win); } void UiWindow::setFullscreen(bool value) { uiWindowSetFullscreen(win, value); } void UiWindow::setBorderless(bool value) { uiWindowSetBorderless(win, value); } bool UiWindow::getBorderless() { return uiWindowBorderless(win); } void UiWindow::setContentSize(Size value) { uiWindowSetContentSize(win, value.getWidth(), value.getHeight()); } Size UiWindow::getContentSize() { int w = 0; int h = 0; uiWindowContentSize(win, &w, &h); return Size(w, h); } NBIND_CLASS(UiWindow) { construct<std::string, int, int, bool>(); method(show); method(close); method(setChild); method(onClosing); method(onContentSizeChanged); getset(getMargined, setMargined); getset(getTitle, setTitle); getset(getContentSize, setContentSize); method(getContentSize); method(setContentSize); method(onContentSizeChanged); getset(getFullscreen, setFullscreen); method(getFullscreen); method(setFullscreen); getset(getBorderless, setBorderless); method(getBorderless); method(setBorderless); } struct UiDialogs { static std::string openFile(UiWindow *parent) { char *char_ptr = uiOpenFile(parent->getHandle()); std::string s(char_ptr); uiFreeText(char_ptr); return s; } static std::string saveFile(UiWindow *parent) { char *char_ptr = uiSaveFile(parent->getHandle()); std::string s(char_ptr); uiFreeText(char_ptr); return s; } static void msgBox(UiWindow *parent, std::string title, std::string description) { uiMsgBox(parent->getHandle(), title.c_str(), description.c_str()); } static void msgBoxError(UiWindow *parent, std::string title, std::string description) { uiMsgBoxError(parent->getHandle(), title.c_str(), description.c_str()); } }; NBIND_CLASS(UiDialogs) { method(openFile); method(saveFile); method(msgBox); method(msgBoxError); } <commit_msg>Freeing event callbacks on close to allow JS to garbage collect UiWindow<commit_after>#include <string> #include "nbind/api.h" #include "control.h" #include "ui.h" #include "values.h" class UiWindow { DEFINE_EVENT(onClosing) DEFINE_EVENT(onContentSizeChanged) private: uiWindow *win; public: UiWindow(std::string title, int width, int height, bool hasMenubar); uiWindow *getHandle(); void show(); void close(); void setMargined(bool margined); bool getMargined(); void setChild(UiControl *control); void setTitle(std::string title); std::string getTitle(); bool getFullscreen(); void setFullscreen(bool value); bool getBorderless(); void setBorderless(bool value); Size getContentSize(); void setContentSize(Size value); }; static int UiWindow_onClosing(uiWindow *w, void *data) { nbind::cbFunction *cb = (nbind::cbFunction *)data; (*cb)(); return 0; } void UiWindow::onClosing(nbind::cbFunction &cb) { onClosingCallback = new nbind::cbFunction(cb); uiWindowOnClosing(uiWindow(getHandle()), UiWindow_onClosing, onClosingCallback); } static void UiWindow_onContentSizeChanged(uiWindow *w, void *data) { nbind::cbFunction *cb = (nbind::cbFunction *)data; (*cb)(); } void UiWindow::onContentSizeChanged(nbind::cbFunction &cb) { onContentSizeChangedCallback = new nbind::cbFunction(cb); uiWindowOnContentSizeChanged(uiWindow(getHandle()), UiWindow_onContentSizeChanged, onContentSizeChangedCallback); } UiWindow::UiWindow(std::string title, int width, int height, bool hasMenubar) { win = uiNewWindow(title.c_str(), width, height, hasMenubar); } uiWindow *UiWindow::getHandle() { return win; } void UiWindow::show() { uiControlShow(uiControl(win)); } void UiWindow::close() { uiControlDestroy(uiControl(win)); /* freeing event callbacks to allow JS to garbage collect this class when there are no references to it left in JS code. */ if (onClosingCallback != nullptr) { delete onClosingCallback; onClosingCallback = nullptr; } if (onContentSizeChangedCallback != nullptr) { delete onContentSizeChangedCallback; onContentSizeChangedCallback = nullptr; } } void UiWindow::setMargined(bool margined) { uiWindowSetMargined(win, margined); } bool UiWindow::getMargined() { return uiWindowMargined(win); } void UiWindow::setChild(UiControl *control) { uiWindowSetChild(win, control->getHandle()); } void UiWindow::setTitle(std::string title) { uiWindowSetTitle(win, title.c_str()); } std::string UiWindow::getTitle() { char *char_ptr = uiWindowTitle(win); std::string s(char_ptr); uiFreeText(char_ptr); return s; } bool UiWindow::getFullscreen() { return uiWindowFullscreen(win); } void UiWindow::setFullscreen(bool value) { uiWindowSetFullscreen(win, value); } void UiWindow::setBorderless(bool value) { uiWindowSetBorderless(win, value); } bool UiWindow::getBorderless() { return uiWindowBorderless(win); } void UiWindow::setContentSize(Size value) { uiWindowSetContentSize(win, value.getWidth(), value.getHeight()); } Size UiWindow::getContentSize() { int w = 0; int h = 0; uiWindowContentSize(win, &w, &h); return Size(w, h); } NBIND_CLASS(UiWindow) { construct<std::string, int, int, bool>(); method(show); method(close); method(setChild); method(onClosing); method(onContentSizeChanged); getset(getMargined, setMargined); getset(getTitle, setTitle); getset(getContentSize, setContentSize); method(getContentSize); method(setContentSize); method(onContentSizeChanged); getset(getFullscreen, setFullscreen); method(getFullscreen); method(setFullscreen); getset(getBorderless, setBorderless); method(getBorderless); method(setBorderless); } struct UiDialogs { static std::string openFile(UiWindow *parent) { char *char_ptr = uiOpenFile(parent->getHandle()); std::string s(char_ptr); uiFreeText(char_ptr); return s; } static std::string saveFile(UiWindow *parent) { char *char_ptr = uiSaveFile(parent->getHandle()); std::string s(char_ptr); uiFreeText(char_ptr); return s; } static void msgBox(UiWindow *parent, std::string title, std::string description) { uiMsgBox(parent->getHandle(), title.c_str(), description.c_str()); } static void msgBoxError(UiWindow *parent, std::string title, std::string description) { uiMsgBoxError(parent->getHandle(), title.c_str(), description.c_str()); } }; NBIND_CLASS(UiDialogs) { method(openFile); method(saveFile); method(msgBox); method(msgBoxError); } <|endoftext|>
<commit_before>#include <GDE/Core/ConfigReader.hpp> #include <GDE/Core/StringsUtil.hpp> #include <GDE/Core/Log.hpp> #include <cstdio> #include <cstring> namespace GDE { ConfigReader::ConfigReader() { ////ILOGM("ConfigReader::ctor()"); } ConfigReader::ConfigReader(const ConfigReader& theCopy) : sections(theCopy.sections) { } ConfigReader::~ConfigReader() { ////ILOGM("ConfigReader::dtor()"); // Borra todos los pares <clave,valor> del mapa std::map<const std::string, typeNameValue*>::iterator iter; iter = this->sections.begin(); while (iter != this->sections.end()) { typeNameValue* anMap = iter->second; this->sections.erase(iter++); delete anMap; } } bool ConfigReader::isSectionEmpty(const std::string theSection) const { bool anResult = false; // Comprueba si una sección existe std::map<const std::string, typeNameValue*>::const_iterator iter; iter = this->sections.find(theSection); if (iter != this->sections.end()) { typeNameValue* anMap = iter->second; if (NULL != anMap) { anResult = anMap->empty(); } } // Devuelve el resultado obtenido anteriormente o false en caso de no encontrase la sección return anResult; } bool ConfigReader::getBool(const std::string theSection, const std::string theName, const bool theDefault) const { bool anResult = theDefault; // Comprueba si la sección existe std::map<const std::string, typeNameValue*>::const_iterator iter; iter = this->sections.find(theSection); if (iter != this->sections.end()) { // Intenta obtener el par <clave, valor> typeNameValue* anMap = iter->second; if (NULL != anMap) { typeNameValueIter iterNameValue; iterNameValue = anMap->find(theName); if (iterNameValue != anMap->end()) { anResult = parseBool(iterNameValue->second, theDefault); } } } // Devuelve el resultado encontrado o el valor de theDefault return anResult; } float ConfigReader::getFloat(const std::string theSection, const std::string theName, const float theDefault) const { float anResult = theDefault; // Comprueba si la sección existe std::map<const std::string, typeNameValue*>::const_iterator iter; iter = this->sections.find(theSection); if (iter != this->sections.end()) { // Intenta obtener el par <clave, valor> typeNameValue* anMap = iter->second; if (NULL != anMap) { typeNameValueIter iterNameValue; iterNameValue = anMap->find(theName); if (iterNameValue != anMap->end()) { anResult = parseFloat(iterNameValue->second, theDefault); } } } // Devuelve el resultado encontrado o el valor de theDefault return anResult; } std::string ConfigReader::getString(const std::string theSection, const std::string theName, const std::string theDefault) const { std::string anResult = theDefault; // Comprueba si la sección existe std::map<const std::string, typeNameValue*>::const_iterator iter; iter = this->sections.find(theSection); if (iter != this->sections.end()) { // Intenta obtener el par <clave, valor> typeNameValue* anMap = iter->second; if (NULL != anMap) { typeNameValueIter iterNameValue; iterNameValue = anMap->find(theName); if (iterNameValue != anMap->end()) { anResult = iterNameValue->second; } } } // Devuelve el resultado encontrado o el valor de theDefault return anResult; } sf::Uint32 ConfigReader::getUint32(const std::string theSection, const std::string theName, const sf::Uint32 theDefault) const { sf::Uint32 anResult = theDefault; // Comprueba si la sección existe std::map<const std::string, typeNameValue*>::const_iterator iter; iter = this->sections.find(theSection); if (iter != this->sections.end()) { // Intenta obtener el par <clave, valor> typeNameValue* anMap = iter->second; if (NULL != anMap) { typeNameValueIter iterNameValue; iterNameValue = anMap->find(theName); if (iterNameValue != anMap->end()) { anResult = parseUint32(iterNameValue->second, theDefault); } } } // Devuelve el resultado encontrado o el valor de theDefault return anResult; } bool ConfigReader::loadFromFile(const std::string& theFilename) { bool anResult = false; char anLine[MAX_CHARS]; std::string anSection; unsigned long anCount = 1; // Indicamos en el log que estamos cargando un fichero GDE::Log::info("ConfigReader::loadFromFile","Abriendo fichero "+theFilename+"."); // Intentamos abrir el fichero FILE* anFile = fopen(theFilename.c_str(), "r"); // Leemos el fichero si se abrió correctamente if (NULL != anFile) { // Leemos hasta que lleguemos al final del fichero while (!feof(anFile)) { // Obtenemos la primera línea del fichero if (fgets(anLine, MAX_CHARS, anFile) == NULL) { // Si ocurre un error lo metemos en el log if (!feof(anFile)) { GDE::Log::error("ConfigReader::Read", "Error leyendo la línea " + anCount); } // Salimos del bucle break; } else { // Parseamos la línea anSection = parseLine(anLine, anCount, anSection); } // Incrementamos el contador de líneas anCount++; } // Cerramos el fichero fclose(anFile); // Indicamos que todo se realizó correctamente anResult = true; } else { GDE::Log::error("ConfigReader::loadFromFile","Error al leer fichero " + theFilename+"."); } // Devuelve true en caso de éxito, false en caso contrario return anResult; } ConfigReader& ConfigReader::operator=(const ConfigReader& theRight) { // Usamos el contructor de copia ConfigReader temp(theRight); // Intercambiamos las copias std::swap(this->sections, temp.sections); // Devolvemos el puntero return *this; } std::string ConfigReader::parseLine(const char* theLine, const unsigned long theCount, const std::string theSection) { std::string anResult = theSection; size_t anLength = strlen(theLine); if (anLength > 1) { // Ignoramos los espacios size_t anOffset = 0; while (anOffset < anLength && theLine[anOffset] == ' ') { anOffset++; } // Comprobamos si hay comentarios if (theLine[anOffset] != '#' && theLine[anOffset] != ';') { // Comprobamos el comienzo de una nueva sección if (theLine[anOffset] == '[') { // Saltamos el inicio de sección '[' anOffset++; // Ignoramos los espacios while (anOffset < anLength && theLine[anOffset] == ' ') { anOffset++; } // Obtenemos el nombre de la sección mientras buscamos el final de la sección ']' size_t anIndex = 0; char anSection[MAX_CHARS] = { 0 }; while ((anOffset + anIndex) < anLength && theLine[anOffset + anIndex] != ']') { // Obtenemos el nombre de la sección de theLine anSection[anIndex] = theLine[anOffset + anIndex]; // Incrementamos anIndex anIndex++; } // Añadimos el delimitador de final de cadena anSection[anIndex] = '\0'; // Eliminamos espacios finales while (anIndex > 0 && anSection[anIndex - 1] == ' ') { // Ponemos el delimitador de final de cadena a la sección anSection[--anIndex] = '\0'; } //Solo actualizamos el nombre de sección si encontramos el deliminador de sección ']' //antes del final de la línea if ((anOffset + anIndex) < anLength && anIndex > 0) { // Actualizamos el nombre de la sección anResult = anSection; } else { GDE::Log::error("ConfigReader::parseLine", "No se encontró el delimitador de sección ']' en la línea " + theCount); } } // Leemos el par <clave,valor> de la sección actual. else { size_t anNameIndex = 0; char anName[MAX_CHARS]; // Obtenemos la clave mientras buscamos "=" o ":" while ((anOffset + anNameIndex) < anLength && theLine[(anOffset + anNameIndex)] != '=' && theLine[(anOffset + anNameIndex)] != ':') { // Obtenemos anName de theLine anName[anNameIndex] = theLine[anOffset + anNameIndex]; // Incrementamos anNameIndex anNameIndex++; } // Asignamos nuestro valor offset anOffset += anNameIndex; // Ponemos el delimitador de cadena anName[anNameIndex] = '\0'; // Eliminamos los espacios del final while (anNameIndex > 0 && anName[anNameIndex - 1] == ' ') { // Ponemos el delimitador de cadena anName[--anNameIndex] = '\0'; } // Solo buscamos el valor si encontramos el delimitador ":" o "=" if (anOffset < anLength && anNameIndex > 0) { size_t anValueIndex = 0; char anValue[MAX_CHARS]; // Nos saltamos el delimitador ":" o "=" anOffset++; // Eliminamos espacios while (anOffset < anLength && theLine[anOffset] == ' ') { anOffset++; } // Obtenemos el valor mientras buscamos el final de línea o el comienzo de un comentario while ((anOffset + anValueIndex) < anLength && theLine[(anOffset + anValueIndex)] != '\r' && theLine[(anOffset + anValueIndex)] != '\n' && theLine[(anOffset + anValueIndex)] != ';' && theLine[(anOffset + anValueIndex)] != '#') { // Obtenemos anValue de theLine anValue[anValueIndex] = theLine[anOffset + anValueIndex]; // Incrementamos anValueIndex anValueIndex++; } // Ponemos el delimitador de final de cadena anValue[anValueIndex] = '\0'; // Eliminamos los espacios while (anValueIndex > 0 && anValue[anValueIndex - 1] == ' ') { // Ponemos el delimitador de final de cadena anValue[--anValueIndex] = '\0'; } // Almacenamos el par <clave,valor> storeNameValue(theSection, anName, anValue); } else { GDE::Log::error("ConfigReader::parseLine","No se encontró el delimitador de nombre o valor '=' o ':' en la línea " + theCount); } } } // if(theLine[anOffset] != '#' && theLine[anOffset] != ';') } // if(anLength > 1) // Devolvemos la el nombre de la nueva sección en caso de encontrarla, en caso contrario // se devuelve el nombre de la sección anterior return anResult; } void ConfigReader::storeNameValue(const std::string theSection, const std::string theName, const std::string theValue) { // Comprobamos si el par <clave,valor> ya existe para theSection std::map<const std::string, typeNameValue*>::iterator iterSection; iterSection = this->sections.find(theSection); if (iterSection == this->sections.end()) { // Intentamos crear un nuevo mapa para almacenar los pares <clave,valor> de dicha sección typeNameValue* anMap = new(std::nothrow) typeNameValue; // Nos aseguramos de que hemos creado el mapa correctamente if (NULL != anMap) { GDE::Log::info("ConfigReader::StoreNameValue","Añadiendo "+theName+"="+theValue + " a la sección [" + theSection+"]."); // Añadimos el nuevo par <clave,valor> al mapa anMap->insert(std::pair<const std::string, const std::string>(theName, theValue)); // Añadimos el mapa creado anteriormente a la sección this->sections.insert(std::pair<const std::string, typeNameValue*>(theSection, anMap)); } else { GDE::Log::error("ConfigReader::StoreNameValue","Imposible añadir "+theName+"="+theValue + " a la sección [" + theSection+"] posible falta de memoria."); } } else { // Retrieve the existing name, value pair map typeNameValue* anMap = iterSection->second; // Nos aseguramos de que hemos creado el mapa correctamente if (NULL != anMap) { // Nos aseguramos de que el par <clave,valor> no esté ya en el mapa typeNameValueIter iterNameValue; iterNameValue = anMap->find(theName); if (iterNameValue == anMap->end()) { GDE::Log::info("ConfigReader::StoreNameValue","Añadiendo "+theName+"="+theValue + " a la sección [" + theSection+"]."); // Añadimos el nuevo par <clave,valor> anMap->insert(std::pair<const std::string, const std::string>(theName, theValue)); } else { GDE::Log::error("ConfigReader::StoreNameValue","Imposible añadir "+theName+"="+theValue + " a la sección [" + theSection+"] porque ya existe."); } } } // else(iterSection == mSections.end()) } } // namespace GDE <commit_msg>Eliminados comentarios innecesarios<commit_after>#include <GDE/Core/ConfigReader.hpp> #include <GDE/Core/StringsUtil.hpp> #include <GDE/Core/Log.hpp> #include <cstdio> #include <cstring> namespace GDE { ConfigReader::ConfigReader() { } ConfigReader::ConfigReader(const ConfigReader& theCopy) : sections(theCopy.sections) { } ConfigReader::~ConfigReader() { // Borra todos los pares <clave,valor> del mapa std::map<const std::string, typeNameValue*>::iterator iter; iter = this->sections.begin(); while (iter != this->sections.end()) { typeNameValue* anMap = iter->second; this->sections.erase(iter++); delete anMap; } } bool ConfigReader::isSectionEmpty(const std::string theSection) const { bool anResult = false; // Comprueba si una sección existe std::map<const std::string, typeNameValue*>::const_iterator iter; iter = this->sections.find(theSection); if (iter != this->sections.end()) { typeNameValue* anMap = iter->second; if (NULL != anMap) { anResult = anMap->empty(); } } // Devuelve el resultado obtenido anteriormente o false en caso de no encontrase la sección return anResult; } bool ConfigReader::getBool(const std::string theSection, const std::string theName, const bool theDefault) const { bool anResult = theDefault; // Comprueba si la sección existe std::map<const std::string, typeNameValue*>::const_iterator iter; iter = this->sections.find(theSection); if (iter != this->sections.end()) { // Intenta obtener el par <clave, valor> typeNameValue* anMap = iter->second; if (NULL != anMap) { typeNameValueIter iterNameValue; iterNameValue = anMap->find(theName); if (iterNameValue != anMap->end()) { anResult = parseBool(iterNameValue->second, theDefault); } } } // Devuelve el resultado encontrado o el valor de theDefault return anResult; } float ConfigReader::getFloat(const std::string theSection, const std::string theName, const float theDefault) const { float anResult = theDefault; // Comprueba si la sección existe std::map<const std::string, typeNameValue*>::const_iterator iter; iter = this->sections.find(theSection); if (iter != this->sections.end()) { // Intenta obtener el par <clave, valor> typeNameValue* anMap = iter->second; if (NULL != anMap) { typeNameValueIter iterNameValue; iterNameValue = anMap->find(theName); if (iterNameValue != anMap->end()) { anResult = parseFloat(iterNameValue->second, theDefault); } } } // Devuelve el resultado encontrado o el valor de theDefault return anResult; } std::string ConfigReader::getString(const std::string theSection, const std::string theName, const std::string theDefault) const { std::string anResult = theDefault; // Comprueba si la sección existe std::map<const std::string, typeNameValue*>::const_iterator iter; iter = this->sections.find(theSection); if (iter != this->sections.end()) { // Intenta obtener el par <clave, valor> typeNameValue* anMap = iter->second; if (NULL != anMap) { typeNameValueIter iterNameValue; iterNameValue = anMap->find(theName); if (iterNameValue != anMap->end()) { anResult = iterNameValue->second; } } } // Devuelve el resultado encontrado o el valor de theDefault return anResult; } sf::Uint32 ConfigReader::getUint32(const std::string theSection, const std::string theName, const sf::Uint32 theDefault) const { sf::Uint32 anResult = theDefault; // Comprueba si la sección existe std::map<const std::string, typeNameValue*>::const_iterator iter; iter = this->sections.find(theSection); if (iter != this->sections.end()) { // Intenta obtener el par <clave, valor> typeNameValue* anMap = iter->second; if (NULL != anMap) { typeNameValueIter iterNameValue; iterNameValue = anMap->find(theName); if (iterNameValue != anMap->end()) { anResult = parseUint32(iterNameValue->second, theDefault); } } } // Devuelve el resultado encontrado o el valor de theDefault return anResult; } bool ConfigReader::loadFromFile(const std::string& theFilename) { bool anResult = false; char anLine[MAX_CHARS]; std::string anSection; unsigned long anCount = 1; // Indicamos en el log que estamos cargando un fichero GDE::Log::info("ConfigReader::loadFromFile","Abriendo fichero "+theFilename+"."); // Intentamos abrir el fichero FILE* anFile = fopen(theFilename.c_str(), "r"); // Leemos el fichero si se abrió correctamente if (NULL != anFile) { // Leemos hasta que lleguemos al final del fichero while (!feof(anFile)) { // Obtenemos la primera línea del fichero if (fgets(anLine, MAX_CHARS, anFile) == NULL) { // Si ocurre un error lo metemos en el log if (!feof(anFile)) { GDE::Log::error("ConfigReader::Read", "Error leyendo la línea " + anCount); } // Salimos del bucle break; } else { // Parseamos la línea anSection = parseLine(anLine, anCount, anSection); } // Incrementamos el contador de líneas anCount++; } // Cerramos el fichero fclose(anFile); // Indicamos que todo se realizó correctamente anResult = true; } else { GDE::Log::error("ConfigReader::loadFromFile","Error al leer fichero " + theFilename+"."); } // Devuelve true en caso de éxito, false en caso contrario return anResult; } ConfigReader& ConfigReader::operator=(const ConfigReader& theRight) { // Usamos el contructor de copia ConfigReader temp(theRight); // Intercambiamos las copias std::swap(this->sections, temp.sections); // Devolvemos el puntero return *this; } std::string ConfigReader::parseLine(const char* theLine, const unsigned long theCount, const std::string theSection) { std::string anResult = theSection; size_t anLength = strlen(theLine); if (anLength > 1) { // Ignoramos los espacios size_t anOffset = 0; while (anOffset < anLength && theLine[anOffset] == ' ') { anOffset++; } // Comprobamos si hay comentarios if (theLine[anOffset] != '#' && theLine[anOffset] != ';') { // Comprobamos el comienzo de una nueva sección if (theLine[anOffset] == '[') { // Saltamos el inicio de sección '[' anOffset++; // Ignoramos los espacios while (anOffset < anLength && theLine[anOffset] == ' ') { anOffset++; } // Obtenemos el nombre de la sección mientras buscamos el final de la sección ']' size_t anIndex = 0; char anSection[MAX_CHARS] = { 0 }; while ((anOffset + anIndex) < anLength && theLine[anOffset + anIndex] != ']') { // Obtenemos el nombre de la sección de theLine anSection[anIndex] = theLine[anOffset + anIndex]; // Incrementamos anIndex anIndex++; } // Añadimos el delimitador de final de cadena anSection[anIndex] = '\0'; // Eliminamos espacios finales while (anIndex > 0 && anSection[anIndex - 1] == ' ') { // Ponemos el delimitador de final de cadena a la sección anSection[--anIndex] = '\0'; } //Solo actualizamos el nombre de sección si encontramos el deliminador de sección ']' //antes del final de la línea if ((anOffset + anIndex) < anLength && anIndex > 0) { // Actualizamos el nombre de la sección anResult = anSection; } else { GDE::Log::error("ConfigReader::parseLine", "No se encontró el delimitador de sección ']' en la línea " + theCount); } } // Leemos el par <clave,valor> de la sección actual. else { size_t anNameIndex = 0; char anName[MAX_CHARS]; // Obtenemos la clave mientras buscamos "=" o ":" while ((anOffset + anNameIndex) < anLength && theLine[(anOffset + anNameIndex)] != '=' && theLine[(anOffset + anNameIndex)] != ':') { // Obtenemos anName de theLine anName[anNameIndex] = theLine[anOffset + anNameIndex]; // Incrementamos anNameIndex anNameIndex++; } // Asignamos nuestro valor offset anOffset += anNameIndex; // Ponemos el delimitador de cadena anName[anNameIndex] = '\0'; // Eliminamos los espacios del final while (anNameIndex > 0 && anName[anNameIndex - 1] == ' ') { // Ponemos el delimitador de cadena anName[--anNameIndex] = '\0'; } // Solo buscamos el valor si encontramos el delimitador ":" o "=" if (anOffset < anLength && anNameIndex > 0) { size_t anValueIndex = 0; char anValue[MAX_CHARS]; // Nos saltamos el delimitador ":" o "=" anOffset++; // Eliminamos espacios while (anOffset < anLength && theLine[anOffset] == ' ') { anOffset++; } // Obtenemos el valor mientras buscamos el final de línea o el comienzo de un comentario while ((anOffset + anValueIndex) < anLength && theLine[(anOffset + anValueIndex)] != '\r' && theLine[(anOffset + anValueIndex)] != '\n' && theLine[(anOffset + anValueIndex)] != ';' && theLine[(anOffset + anValueIndex)] != '#') { // Obtenemos anValue de theLine anValue[anValueIndex] = theLine[anOffset + anValueIndex]; // Incrementamos anValueIndex anValueIndex++; } // Ponemos el delimitador de final de cadena anValue[anValueIndex] = '\0'; // Eliminamos los espacios while (anValueIndex > 0 && anValue[anValueIndex - 1] == ' ') { // Ponemos el delimitador de final de cadena anValue[--anValueIndex] = '\0'; } // Almacenamos el par <clave,valor> storeNameValue(theSection, anName, anValue); } else { GDE::Log::error("ConfigReader::parseLine","No se encontró el delimitador de nombre o valor '=' o ':' en la línea " + theCount); } } } // if(theLine[anOffset] != '#' && theLine[anOffset] != ';') } // if(anLength > 1) // Devolvemos la el nombre de la nueva sección en caso de encontrarla, en caso contrario // se devuelve el nombre de la sección anterior return anResult; } void ConfigReader::storeNameValue(const std::string theSection, const std::string theName, const std::string theValue) { // Comprobamos si el par <clave,valor> ya existe para theSection std::map<const std::string, typeNameValue*>::iterator iterSection; iterSection = this->sections.find(theSection); if (iterSection == this->sections.end()) { // Intentamos crear un nuevo mapa para almacenar los pares <clave,valor> de dicha sección typeNameValue* anMap = new(std::nothrow) typeNameValue; // Nos aseguramos de que hemos creado el mapa correctamente if (NULL != anMap) { GDE::Log::info("ConfigReader::StoreNameValue","Añadiendo "+theName+"="+theValue + " a la sección [" + theSection+"]."); // Añadimos el nuevo par <clave,valor> al mapa anMap->insert(std::pair<const std::string, const std::string>(theName, theValue)); // Añadimos el mapa creado anteriormente a la sección this->sections.insert(std::pair<const std::string, typeNameValue*>(theSection, anMap)); } else { GDE::Log::error("ConfigReader::StoreNameValue","Imposible añadir "+theName+"="+theValue + " a la sección [" + theSection+"] posible falta de memoria."); } } else { // Retrieve the existing name, value pair map typeNameValue* anMap = iterSection->second; // Nos aseguramos de que hemos creado el mapa correctamente if (NULL != anMap) { // Nos aseguramos de que el par <clave,valor> no esté ya en el mapa typeNameValueIter iterNameValue; iterNameValue = anMap->find(theName); if (iterNameValue == anMap->end()) { GDE::Log::info("ConfigReader::StoreNameValue","Añadiendo "+theName+"="+theValue + " a la sección [" + theSection+"]."); // Añadimos el nuevo par <clave,valor> anMap->insert(std::pair<const std::string, const std::string>(theName, theValue)); } else { GDE::Log::error("ConfigReader::StoreNameValue","Imposible añadir "+theName+"="+theValue + " a la sección [" + theSection+"] porque ya existe."); } } } // else(iterSection == mSections.end()) } } // namespace GDE <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: provider.cxx,v $ * * $Revision: 1.1 $ * * last change: $Author: dg $ $Date: 2000-11-10 22:42:46 $ * * 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 "provider.hxx" #ifndef CONFIGMGR_MODULE_HXX_ #include "configmodule.hxx" #endif #ifndef CONFIGMGR_CMTREEMODEL_HXX #include "cmtreemodel.hxx" #endif #ifndef _OSL_MUTEX_HXX_ #include <osl/mutex.hxx> #endif #ifndef __SGI_STL_ALGORITHM #include <stl/algorithm> #endif #ifndef _COMPHELPER_SEQUENCE_HXX_ #include <comphelper/sequence.hxx> #endif #ifndef _CPPUHELPER_TYPEPROVIDER_HXX_ #include <cppuhelper/typeprovider.hxx> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif #define THISREF() static_cast< ::cppu::OWeakObject* >(this) namespace configmgr { namespace css = ::com::sun::star; namespace uno = css::uno; namespace lang = css::lang; namespace beans = css::beans; using ::rtl::OUString; using ::vos::ORef; using namespace osl; //============================================================================= //= OProvider //============================================================================= //----------------------------------------------------------------------------- OProvider::OProvider(Module& aModule, ServiceInfo const* pInfo) :ServiceComponentImpl(pInfo) ,m_aModule(aModule) { } // XTypeOProvider //----------------------------------------------------------------------------- uno::Sequence< uno::Type > SAL_CALL OProvider::getTypes( ) throw(uno::RuntimeException) { return ::comphelper::concatSequences(ServiceComponentImpl::getTypes(), OProvider_Base::getTypes()); } // XInterface //----------------------------------------------------------------------------- uno::Any SAL_CALL OProvider::queryInterface(uno::Type const& rType) throw(uno::RuntimeException) { uno::Any aRet( ServiceComponentImpl::queryInterface(rType) ); if ( !aRet.hasValue() ) aRet = OProvider_Base::queryInterface(rType); return aRet; } //----------------------------------------------------------------------------- void SAL_CALL OProvider::disposing() { sal_Bool bIsConnected = isConnected(); if (bIsConnected) { ::osl::MutexGuard aGuard(m_aMutex); if (isConnected()) disconnect(); } ServiceComponentImpl::disposing(); } // XInitialization //----------------------------------------------------------------------------- void SAL_CALL OProvider::initialize( const uno::Sequence< uno::Any >& _rArguments ) throw (uno::Exception, uno::RuntimeException) { ::osl::MutexGuard aGuard(m_aMutex); if (isConnected() || m_aSecurityOverride.size()) { if (0 == _rArguments.getLength()) // allow initialize without arguments .... return; //? Should this not ensureConnection() ? throw uno::Exception(::rtl::OUString::createFromAscii("The configuration OProvider has already been initialized."), THISREF()); } const uno::Any* pArguments = _rArguments.getConstArray(); beans::PropertyValue aCurrentArg; for (sal_Int32 i=0; i<_rArguments.getLength(); ++i, ++pArguments) { if (!((*pArguments) >>= aCurrentArg)) throw lang::IllegalArgumentException(::rtl::OUString::createFromAscii("Arguments have to be com.sun.star.beans.PropertyValue's."), THISREF(), i); // no check if the argument is known and valid. This would require to much testing m_aSecurityOverride[aCurrentArg.Name] = aCurrentArg.Value; } // connect here and now, thus the createInstanceWithArguments fails if no connection is made connect(); } } // namespace configmgr <commit_msg>compiler problems<commit_after>/************************************************************************* * * $RCSfile: provider.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: dg $ $Date: 2000-11-10 23:02:35 $ * * 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 "provider.hxx" #ifndef CONFIGMGR_MODULE_HXX_ #include "configmodule.hxx" #endif #ifndef CONFIGMGR_CMTREEMODEL_HXX #include "cmtreemodel.hxx" #endif #ifndef _OSL_MUTEX_HXX_ #include <osl/mutex.hxx> #endif #ifndef __SGI_STL_ALGORITHM #include <stl/algorithm> #endif #ifndef _COMPHELPER_SEQUENCE_HXX_ #include <comphelper/sequence.hxx> #endif #ifndef _CPPUHELPER_TYPEPROVIDER_HXX_ #include <cppuhelper/typeprovider.hxx> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif #define THISREF() static_cast< ::cppu::OWeakObject* >(this) namespace configmgr { namespace css = ::com::sun::star; namespace uno = css::uno; namespace lang = css::lang; namespace beans = css::beans; using ::rtl::OUString; using ::vos::ORef; using namespace osl; //============================================================================= //= OProvider //============================================================================= //----------------------------------------------------------------------------- OProvider::OProvider(Module& aModule, ServiceInfo const* pInfo) :ServiceComponentImpl(pInfo) ,m_aModule(aModule) { } // XTypeOProvider //----------------------------------------------------------------------------- uno::Sequence< uno::Type > SAL_CALL OProvider::getTypes( ) throw(uno::RuntimeException) { return ::comphelper::concatSequences(ServiceComponentImpl::getTypes(), OProvider_Base::getTypes()); } // XInterface //----------------------------------------------------------------------------- uno::Any SAL_CALL OProvider::queryInterface(uno::Type const& rType) throw(uno::RuntimeException) { uno::Any aRet( ServiceComponentImpl::queryInterface(rType) ); if ( !aRet.hasValue() ) aRet = OProvider_Base::queryInterface(rType); return aRet; } //----------------------------------------------------------------------------- void SAL_CALL OProvider::disposing() { sal_Bool bIsConnected = isConnected(); if (bIsConnected) { ::osl::MutexGuard aGuard(m_aMutex); if (isConnected()) disconnect(); } ServiceComponentImpl::disposing(); } // XInitialization //----------------------------------------------------------------------------- void SAL_CALL OProvider::initialize( const uno::Sequence< uno::Any >& _rArguments ) throw (uno::Exception, uno::RuntimeException) { ::osl::MutexGuard aGuard(m_aMutex); if (isConnected() || m_aSecurityOverride.size()) { if (0 == _rArguments.getLength()) // allow initialize without arguments .... return; //? Should this not ensureConnection() ? throw uno::Exception(::rtl::OUString::createFromAscii("The configuration OProvider has already been initialized."), THISREF()); } const uno::Any* pArguments = _rArguments.getConstArray(); beans::PropertyValue aCurrentArg; for (sal_Int32 i=0; i<_rArguments.getLength(); ++i, ++pArguments) { if (!((*pArguments) >>= aCurrentArg)) { throw uno::Exception(::rtl::OUString::createFromAscii("The configuration OProvider has already been initialized."), THISREF()); //throw lang::IllegalArgumentException(::rtl::OUString::createFromAscii("Arguments have to be com.sun.star.beans.PropertyValue's."), THISREF()); } // no check if the argument is known and valid. This would require to much testing m_aSecurityOverride[aCurrentArg.Name] = aCurrentArg.Value; } // connect here and now, thus the createInstanceWithArguments fails if no connection is made connect(); } } // namespace configmgr <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (c) Juergen Riegel ([email protected]) 2012 * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <sstream> # include <QApplication> # include <Inventor/SoPickedPoint.h> # include <Inventor/events/SoMouseButtonEvent.h> # include <Inventor/nodes/SoSeparator.h> # include <Inventor/nodes/SoBaseColor.h> # include <Inventor/nodes/SoFontStyle.h> # include <Inventor/nodes/SoPickStyle.h> # include <Inventor/nodes/SoText2.h> # include <Inventor/nodes/SoTranslation.h> # include <Inventor/nodes/SoCoordinate3.h> # include <Inventor/nodes/SoIndexedLineSet.h> # include <Inventor/nodes/SoMarkerSet.h> # include <Inventor/nodes/SoDrawStyle.h> #endif #include <Inventor/nodes/SoMaterial.h> #include <Inventor/nodes/SoAnnotation.h> #include <Inventor/details/SoLineDetail.h> #include <Inventor/nodes/SoAsciiText.h> #include "ViewProviderPlane.h" #include "SoFCSelection.h" #include "Application.h" #include "Document.h" #include "View3DInventorViewer.h" #include "Inventor/SoAutoZoomTranslation.h" #include "SoAxisCrossKit.h" //#include <SoDepthBuffer.h> #include <App/PropertyGeo.h> #include <App/PropertyStandard.h> #include <App/MeasureDistance.h> #include <Base/Console.h> using namespace Gui; PROPERTY_SOURCE(Gui::ViewProviderPlane, Gui::ViewProviderGeometryObject) ViewProviderPlane::ViewProviderPlane() { ADD_PROPERTY(Size,(1.0)); pMat = new SoMaterial(); pMat->ref(); float size = Size.getValue(); // Note: If you change this, you need to also adapt App/Plane.cpp getBoundBox() SbVec3f verts[4] = { SbVec3f(size,size,0), SbVec3f(size,-size,0), SbVec3f(-size,-size,0), SbVec3f(-size,size,0), }; // indexes used to create the edges static const int32_t lines[6] = { 0,1,2,3,0,-1 }; pMat->diffuseColor.setNum(1); pMat->diffuseColor.set1Value(0, SbColor(1.0f, 1.0f, 1.0f)); pCoords = new SoCoordinate3(); pCoords->ref(); pCoords->point.setNum(4); pCoords->point.setValues(0, 4, verts); pLines = new SoIndexedLineSet(); pLines->ref(); pLines->coordIndex.setNum(6); pLines->coordIndex.setValues(0, 6, lines); pFont = new SoFont(); pFont->size.setValue(Size.getValue()/10.); pTranslation = new SoTranslation(); pTranslation->translation.setValue(SbVec3f(-1,9./10.,0)); pText = new SoAsciiText(); pText->width.setValue(-1); sPixmap = "view-measurement"; } ViewProviderPlane::~ViewProviderPlane() { pCoords->unref(); pLines->unref(); pMat->unref(); } void ViewProviderPlane::onChanged(const App::Property* prop) { if (prop == &Size){ float size = Size.getValue(); // Note: If you change this, you need to also adapt App/Plane.cpp getBoundBox() SbVec3f verts[4] = { SbVec3f(size,size,0), SbVec3f(size,-size,0), SbVec3f(-size,-size,0), SbVec3f(-size,size,0), }; pCoords->point.setValues(0, 4, verts); pFont->size.setValue(Size.getValue()/10.); pTranslation->translation.setValue(SbVec3f(-size,size*9./10.,0)); } else ViewProviderGeometryObject::onChanged(prop); } std::vector<std::string> ViewProviderPlane::getDisplayModes(void) const { // add modes std::vector<std::string> StrList; StrList.push_back("Base"); return StrList; } void ViewProviderPlane::setDisplayMode(const char* ModeName) { if (strcmp(ModeName, "Base") == 0) setDisplayMaskMode("Base"); ViewProviderGeometryObject::setDisplayMode(ModeName); } void ViewProviderPlane::attach(App::DocumentObject* pcObject) { ViewProviderGeometryObject::attach(pcObject); SoSeparator *sep = new SoSeparator(); SoAnnotation *lineSep = new SoAnnotation(); SoDrawStyle* style = new SoDrawStyle(); style->lineWidth = 1.0f; SoMaterialBinding* matBinding = new SoMaterialBinding; matBinding->value = SoMaterialBinding::PER_FACE; sep->addChild(style); sep->addChild(matBinding); sep->addChild(pMat); sep->addChild(pCoords); sep->addChild(pLines); style = new SoDrawStyle(); style->lineWidth = 1.0f; style->linePattern.setValue(0x00FF); lineSep->addChild(style); lineSep->addChild(pLines); lineSep->addChild(pFont); pText->string.setValue(SbString(pcObject->Label.getValue())); lineSep->addChild(pTranslation); lineSep->addChild(pText); sep->addChild(lineSep); addDisplayMaskMode(sep, "Base"); } void ViewProviderPlane::updateData(const App::Property* prop) { pText->string.setValue(SbString(pcObject->Label.getValue())); ViewProviderGeometryObject::updateData(prop); } std::string ViewProviderPlane::getElement(const SoDetail* detail) const { if (detail) { if (detail->getTypeId() == SoLineDetail::getClassTypeId()) { const SoLineDetail* line_detail = static_cast<const SoLineDetail*>(detail); int edge = line_detail->getLineIndex(); if (edge == 0) { return std::string("Main"); } } } return std::string(""); } SoDetail* ViewProviderPlane::getDetail(const char* subelement) const { SoLineDetail* detail = 0; std::string subelem(subelement); int edge = -1; if(subelem == "Main") edge = 0; if(edge >= 0) { detail = new SoLineDetail(); detail->setPartIndex(edge); } return detail; } bool ViewProviderPlane::isSelectable(void) const { return true; } // ---------------------------------------------------------------------------- <commit_msg>highlight planes<commit_after>/*************************************************************************** * Copyright (c) Juergen Riegel ([email protected]) 2012 * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <sstream> # include <QApplication> # include <Inventor/SoPickedPoint.h> # include <Inventor/events/SoMouseButtonEvent.h> # include <Inventor/nodes/SoSeparator.h> # include <Inventor/nodes/SoBaseColor.h> # include <Inventor/nodes/SoFontStyle.h> # include <Inventor/nodes/SoPickStyle.h> # include <Inventor/nodes/SoText2.h> # include <Inventor/nodes/SoTranslation.h> # include <Inventor/nodes/SoCoordinate3.h> # include <Inventor/nodes/SoIndexedLineSet.h> # include <Inventor/nodes/SoMarkerSet.h> # include <Inventor/nodes/SoDrawStyle.h> #endif #include <Inventor/nodes/SoMaterial.h> #include <Inventor/nodes/SoAnnotation.h> #include <Inventor/details/SoLineDetail.h> #include <Inventor/nodes/SoAsciiText.h> #include "ViewProviderPlane.h" #include "SoFCSelection.h" #include "Application.h" #include "Document.h" #include "View3DInventorViewer.h" #include "Inventor/SoAutoZoomTranslation.h" #include "SoAxisCrossKit.h" //#include <SoDepthBuffer.h> #include <App/PropertyGeo.h> #include <App/PropertyStandard.h> #include <App/MeasureDistance.h> #include <Base/Console.h> using namespace Gui; PROPERTY_SOURCE(Gui::ViewProviderPlane, Gui::ViewProviderGeometryObject) ViewProviderPlane::ViewProviderPlane() { ADD_PROPERTY(Size,(1.0)); pMat = new SoMaterial(); pMat->ref(); float size = Size.getValue(); // Note: If you change this, you need to also adapt App/Plane.cpp getBoundBox() SbVec3f verts[4] = { SbVec3f(size,size,0), SbVec3f(size,-size,0), SbVec3f(-size,-size,0), SbVec3f(-size,size,0), }; // indexes used to create the edges static const int32_t lines[6] = { 0,1,2,3,0,-1 }; pMat->diffuseColor.setNum(1); pMat->diffuseColor.set1Value(0, SbColor(1.0f, 1.0f, 1.0f)); pCoords = new SoCoordinate3(); pCoords->ref(); pCoords->point.setNum(4); pCoords->point.setValues(0, 4, verts); pLines = new SoIndexedLineSet(); pLines->ref(); pLines->coordIndex.setNum(6); pLines->coordIndex.setValues(0, 6, lines); pFont = new SoFont(); pFont->size.setValue(Size.getValue()/10.); pTranslation = new SoTranslation(); pTranslation->translation.setValue(SbVec3f(-1,9./10.,0)); pText = new SoAsciiText(); pText->width.setValue(-1); sPixmap = "view-measurement"; } ViewProviderPlane::~ViewProviderPlane() { pCoords->unref(); pLines->unref(); pMat->unref(); } void ViewProviderPlane::onChanged(const App::Property* prop) { if (prop == &Size){ float size = Size.getValue(); // Note: If you change this, you need to also adapt App/Plane.cpp getBoundBox() SbVec3f verts[4] = { SbVec3f(size,size,0), SbVec3f(size,-size,0), SbVec3f(-size,-size,0), SbVec3f(-size,size,0), }; pCoords->point.setValues(0, 4, verts); pFont->size.setValue(Size.getValue()/10.); pTranslation->translation.setValue(SbVec3f(-size,size*9./10.,0)); } else ViewProviderGeometryObject::onChanged(prop); } std::vector<std::string> ViewProviderPlane::getDisplayModes(void) const { // add modes std::vector<std::string> StrList; StrList.push_back("Base"); return StrList; } void ViewProviderPlane::setDisplayMode(const char* ModeName) { if (strcmp(ModeName, "Base") == 0) setDisplayMaskMode("Base"); ViewProviderGeometryObject::setDisplayMode(ModeName); } void ViewProviderPlane::attach(App::DocumentObject* pcObject) { ViewProviderGeometryObject::attach(pcObject); SoSeparator *sep = new SoSeparator(); SoAnnotation *lineSep = new SoAnnotation(); SoFCSelection *highlight = new SoFCSelection(); SoDrawStyle* style = new SoDrawStyle(); style->lineWidth = 2.0f; SoMaterialBinding* matBinding = new SoMaterialBinding; matBinding->value = SoMaterialBinding::OVERALL; sep->addChild(matBinding); sep->addChild(pMat); sep->addChild(highlight); highlight->addChild(style); highlight->addChild(pCoords); highlight->addChild(pLines); style = new SoDrawStyle(); style->lineWidth = 2.0f; style->linePattern.setValue(0x00FF); lineSep->addChild(style); lineSep->addChild(pLines); lineSep->addChild(pFont); pText->string.setValue(SbString(pcObject->Label.getValue())); lineSep->addChild(pTranslation); lineSep->addChild(pText); highlight->addChild(lineSep); highlight->style = SoFCSelection::EMISSIVE_DIFFUSE; addDisplayMaskMode(sep, "Base"); } void ViewProviderPlane::updateData(const App::Property* prop) { pText->string.setValue(SbString(pcObject->Label.getValue())); ViewProviderGeometryObject::updateData(prop); } std::string ViewProviderPlane::getElement(const SoDetail* detail) const { if (detail) { if (detail->getTypeId() == SoLineDetail::getClassTypeId()) { const SoLineDetail* line_detail = static_cast<const SoLineDetail*>(detail); int edge = line_detail->getLineIndex(); if (edge == 0) { return std::string("Main"); } } } return std::string(""); } SoDetail* ViewProviderPlane::getDetail(const char* subelement) const { SoLineDetail* detail = 0; std::string subelem(subelement); int edge = -1; if(subelem == "Main") edge = 0; if(edge >= 0) { detail = new SoLineDetail(); detail->setPartIndex(edge); } return detail; } bool ViewProviderPlane::isSelectable(void) const { return true; } // ---------------------------------------------------------------------------- <|endoftext|>
<commit_before>// Copyright 2020 Google LLC // // 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 // // https://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 "iree/compiler/Dialect/HAL/Target/LLVM/LLVMAOTTargetLinker.h" namespace mlir { namespace iree_compiler { namespace IREE { namespace HAL { iree::StatusOr<std::string> linkLLVMAOTObjects( const std::string& linkerToolPath, const std::string& objData) { std::string archiveFile, sharedLibFile; ASSIGN_OR_RETURN(archiveFile, iree::file_io::GetTempFile("objfile")); RETURN_IF_ERROR(iree::file_io::SetFileContents(archiveFile, objData)); ASSIGN_OR_RETURN(sharedLibFile, iree::file_io::GetTempFile("dylibfile")); std::string linkingCmd = linkerToolPath + " -shared " + archiveFile + " -o " + sharedLibFile; system(linkingCmd.c_str()); return iree::file_io::GetFileContents(sharedLibFile); } iree::StatusOr<std::string> linkLLVMAOTObjectsWithLLDElf( const std::string& objData) { return iree::UnimplementedErrorBuilder(IREE_LOC) << "linkLLVMAOTObjectsWithLLD not implemented yet!"; } } // namespace HAL } // namespace IREE } // namespace iree_compiler } // namespace mlir <commit_msg>Avoid unused result warning (#2469)<commit_after>// Copyright 2020 Google LLC // // 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 // // https://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 "iree/compiler/Dialect/HAL/Target/LLVM/LLVMAOTTargetLinker.h" #include "iree/base/status.h" namespace mlir { namespace iree_compiler { namespace IREE { namespace HAL { iree::StatusOr<std::string> linkLLVMAOTObjects( const std::string& linkerToolPath, const std::string& objData) { std::string archiveFile, sharedLibFile; ASSIGN_OR_RETURN(archiveFile, iree::file_io::GetTempFile("objfile")); RETURN_IF_ERROR(iree::file_io::SetFileContents(archiveFile, objData)); ASSIGN_OR_RETURN(sharedLibFile, iree::file_io::GetTempFile("dylibfile")); std::string linkingCmd = linkerToolPath + " -shared " + archiveFile + " -o " + sharedLibFile; int systemRet = system(linkingCmd.c_str()); if (systemRet != 0) { return iree::InternalErrorBuilder(IREE_LOC) << linkingCmd << " failed with exit code " << systemRet; } return iree::file_io::GetFileContents(sharedLibFile); } iree::StatusOr<std::string> linkLLVMAOTObjectsWithLLDElf( const std::string& objData) { return iree::UnimplementedErrorBuilder(IREE_LOC) << "linkLLVMAOTObjectsWithLLD not implemented yet!"; } } // namespace HAL } // namespace IREE } // namespace iree_compiler } // namespace mlir <|endoftext|>
<commit_before>/* This file is part of the ORK library. Full copyright and license terms can be found in the LICENSE.txt file. */ #include "ork/ork.hpp" #include "ork/string_utils.hpp" #define CATCH_CONFIG_MAIN 1 #include "ork/test/catch_include.hpp" ORK_GLOBAL_LOG(ORK("../Logs")) using namespace ork; TEST_CASE("Strings are encoded", "[string]") { const bstring test_1{BORK("Encode this 1!")}; const bstring result_1{BORK("RW5jb2RlIHRoaXMgMSE=")}; REQUIRE( encode( reinterpret_cast<const unsigned char*>(test_1.data()), test_1.size(), encoding::base_64) == result_1); REQUIRE(decode(result_1, encoding::base_64) == test_1); } // We to avoid a second project to generate code TEST_CASE("Macro Generation", "[pp_meta]") { static const size_t macro_max = 40; ORK_FILE_WRITE_B(ORK("generated.cpp")); LOOPI(macro_max) { fout << BORK("#define ORK_GET_ARG_") << (i / 10 > 0 ? BORK("") : BORK("0")) << i << BORK("_("); LOOPJ(i + 1) { fout << BORK('A') << j << BORK(", "); } fout << BORK("...) A") << i << BORK('\n'); } fout << BORK("\n"); fout << BORK("#define ORK_ARG_N_("); LOOPI(macro_max + 1) { fout << BORK('A') << i + 1 << BORK(", "); } fout << BORK("...) A") << macro_max + 1 << BORK('\n'); fout << BORK("\n"); fout << BORK("#define ORK_DESCENDING_N_ "); LOOPRI(macro_max + 1) { fout << i << (i > 0 ? BORK(", ") : BORK("")); } const int arg_1 = ORK_NUM_ARG(a); REQUIRE(arg_1 == 1); const int arg_3 = ORK_NUM_ARG(a, b, c); REQUIRE(arg_3 == 3); } TEST_CASE("Macro Test", "[pp_meta]") { REQUIRE(ORK_IF_(1)(4, 5) == 4); REQUIRE(ORK_IF_(0)(4, 5) == 5); #define T() 1 #define F() 0 REQUIRE(ORK_IF_(T())(4, 5) == 4); REQUIRE(ORK_IF_(F())(4, 5) == 5); REQUIRE(ORK_CHECK_1_() == 0); REQUIRE(ORK_CHECK_1_(1) == 0); REQUIRE(ORK_CHECK_1_(1, 2) == 2); REQUIRE(ORK_CHECK_1_(1, 2, 3) == 2); #define A1() 1 #define A2() 1, 2 #define A3() 1, 2, 3 REQUIRE(ORK_CHECK_1_(A1()) == 0); REQUIRE(ORK_CHECK_1_(A2()) == 2); REQUIRE(ORK_CHECK_1_(A3()) == 2); REQUIRE(ORK_CHECK_1_(ORK_APPEND_1_(1)) == 1); REQUIRE(ORK_CHECK_1_(ORK_APPEND_1_(1, 2)) == 2); REQUIRE(ORK_CHECK_1_(ORK_APPEND_1_(A1())) == 1); REQUIRE(ORK_CHECK_1_(ORK_APPEND_1_(A2())) == 2); REQUIRE(ORK_IS_PAREN(()) == 1); REQUIRE(ORK_IS_PAREN(~) == 0); #define P() () #define NP() ~ REQUIRE(ORK_IS_PAREN(P()) == 1); REQUIRE(ORK_IS_PAREN(NP()) == 0); REQUIRE(ORK_NOT(0) == 1); REQUIRE(ORK_NOT(1) == 0); REQUIRE(ORK_NOT(F()) == 1); REQUIRE(ORK_NOT(T()) == 0); REQUIRE(ORK_BOOL(0) == 0); REQUIRE(ORK_BOOL(1) == 1); REQUIRE(ORK_BOOL(a) == 1); static const char a = 'a'; static const char b = 'b'; #define A() a #define B() b REQUIRE(ORK_BOOL(F()) == 0); REQUIRE(ORK_BOOL(T()) == 1); REQUIRE(ORK_BOOL(A()) == 1); REQUIRE(ORK_IF(0)(a, b) == b); REQUIRE(ORK_IF(1)(a, b) == a); REQUIRE(ORK_IF(a)(a, b) == a); REQUIRE(ORK_IF(B())(a, b) == a); REQUIRE(1 ORK_WHEN(0)(+1) == 1); REQUIRE(1 ORK_WHEN(1)(+1) == 2); // clang-format off #define ORK_SQUARE(A, I) A*A #define ORK_ADD(A, B, I) A + B // clang-format on const ork::bstring square_list{ORK_STR(ORK_MAP(ORK_SQUARE, ORK_ADD, 1, 2))}; REQUIRE(square_list == BORK("1*1 + 2*2")); int val = ORK_MAP(ORK_SQUARE, ORK_ADD, 1, 2); REQUIRE(val == 5); // clang-format off #define CALL(ARG, I) my--ARG #define STITCH(X, Y, I) (X + Y) // clang-format on const ork::bstring assoc_list{ORK_STR(ORK_MAP(CALL, STITCH, a, b, c))}; REQUIRE(assoc_list == BORK("(my--a + (my--b + my--c))")); } <commit_msg>Added increment and decrement macros<commit_after>/* This file is part of the ORK library. Full copyright and license terms can be found in the LICENSE.txt file. */ #include "ork/ork.hpp" #include "ork/string_utils.hpp" #define CATCH_CONFIG_MAIN 1 #include "ork/test/catch_include.hpp" ORK_GLOBAL_LOG(ORK("../Logs")) using namespace ork; TEST_CASE("Strings are encoded", "[string]") { const bstring test_1{BORK("Encode this 1!")}; const bstring result_1{BORK("RW5jb2RlIHRoaXMgMSE=")}; REQUIRE( encode( reinterpret_cast<const unsigned char*>(test_1.data()), test_1.size(), encoding::base_64) == result_1); REQUIRE(decode(result_1, encoding::base_64) == test_1); } // We to avoid a second project to generate code TEST_CASE("Macro Generation", "[pp_meta]") { static const size_t dumb_macro_max = 40; ORK_FILE_WRITE_B(ORK("generated.cpp")); LOOPI(dumb_macro_max) { fout << BORK("#define ORK_GET_ARG_") << (i / 10 > 0 ? BORK("") : BORK("0")) << i << BORK("_("); LOOPJ(i + 1) { fout << BORK('A') << j << BORK(", "); } fout << BORK("...) A") << i << BORK('\n'); } fout << BORK("\n"); fout << BORK("#define ORK_ARG_N_("); LOOPI(dumb_macro_max + 1) { fout << BORK('A') << i + 1 << BORK(", "); } fout << BORK("...) A") << dumb_macro_max + 1 << BORK('\n'); fout << BORK("\n"); fout << BORK("#define ORK_DESCENDING_N_ "); LOOPRI(dumb_macro_max + 1) { fout << i << (i > 0 ? BORK(", ") : BORK("")); } static const size_t macro_max = 256; fout << BORK("\n\n"); LOOPI(macro_max) { fout << BORK("#define ORK_INC_") << i << BORK(" ") << i + 1 << BORK('\n'); } fout << BORK("\n"); LOOPI(macro_max) { fout << BORK("#define ORK_DEC_") << i + 1 << BORK(" ") << i << BORK('\n'); } } TEST_CASE("Macro Test", "[pp_meta]") { REQUIRE(ORK_IF_(1)(4, 5) == 4); REQUIRE(ORK_IF_(0)(4, 5) == 5); #define T() 1 #define F() 0 REQUIRE(ORK_IF_(T())(4, 5) == 4); REQUIRE(ORK_IF_(F())(4, 5) == 5); REQUIRE(ORK_CHECK_1_() == 0); REQUIRE(ORK_CHECK_1_(1) == 0); REQUIRE(ORK_CHECK_1_(1, 2) == 2); REQUIRE(ORK_CHECK_1_(1, 2, 3) == 2); #define A1() 1 #define A2() 1, 2 #define A3() 1, 2, 3 REQUIRE(ORK_CHECK_1_(A1()) == 0); REQUIRE(ORK_CHECK_1_(A2()) == 2); REQUIRE(ORK_CHECK_1_(A3()) == 2); REQUIRE(ORK_CHECK_1_(ORK_APPEND_1_(1)) == 1); REQUIRE(ORK_CHECK_1_(ORK_APPEND_1_(1, 2)) == 2); REQUIRE(ORK_CHECK_1_(ORK_APPEND_1_(A1())) == 1); REQUIRE(ORK_CHECK_1_(ORK_APPEND_1_(A2())) == 2); REQUIRE(ORK_IS_PAREN(()) == 1); REQUIRE(ORK_IS_PAREN(~) == 0); #define P() () #define NP() ~ REQUIRE(ORK_IS_PAREN(P()) == 1); REQUIRE(ORK_IS_PAREN(NP()) == 0); REQUIRE(ORK_NOT(0) == 1); REQUIRE(ORK_NOT(1) == 0); REQUIRE(ORK_NOT(F()) == 1); REQUIRE(ORK_NOT(T()) == 0); REQUIRE(ORK_BOOL(0) == 0); REQUIRE(ORK_BOOL(1) == 1); REQUIRE(ORK_BOOL(a) == 1); static const char a = 'a'; static const char b = 'b'; #define A() a #define B() b REQUIRE(ORK_BOOL(F()) == 0); REQUIRE(ORK_BOOL(T()) == 1); REQUIRE(ORK_BOOL(A()) == 1); REQUIRE(ORK_IF(0)(a, b) == b); REQUIRE(ORK_IF(1)(a, b) == a); REQUIRE(ORK_IF(a)(a, b) == a); REQUIRE(ORK_IF(B())(a, b) == a); REQUIRE(1 ORK_WHEN(0)(+1) == 1); REQUIRE(1 ORK_WHEN(1)(+1) == 2); // clang-format off #define ORK_SQUARE(A, I) A*A #define ORK_ADD(A, B, I) A + B // clang-format on const ork::bstring square_list{ORK_STR(ORK_MAP(ORK_SQUARE, ORK_ADD, 1, 2))}; REQUIRE(square_list == BORK("1*1 + 2*2")); int val = ORK_MAP(ORK_SQUARE, ORK_ADD, 1, 2); REQUIRE(val == 5); // clang-format off #define CALL(ARG, I) my--ARG #define STITCH(X, Y, I) (X + Y) // clang-format on const ork::bstring assoc_list{ORK_STR(ORK_MAP(CALL, STITCH, a, b, c))}; REQUIRE(assoc_list == BORK("(my--a + (my--b + my--c))")); } <|endoftext|>
<commit_before>#include <iostream> #include <arc_utilities/dijkstras.hpp> #include <arc_utilities/pretty_print.hpp> int main(int argc, char* argv[]) { (void)argc; (void)argv; std::cout << "Creating graph with nodes indices:\n\n"; std::cout << " 2 | 5 | 8\n" << " --+---+--\n" << " 1 | 4 | 7\n" << " --+---+--\n" << " 0 | 3 | 6\n\n"; arc_dijkstras::Graph<Eigen::Vector2d> graph(9); for (double x = -1; x <= 1; x += 1) { for (double y = -1; y <= 1; y += 1) { graph.AddNode(Eigen::Vector2d(x, y)); } } // Y-direction edges graph.AddEdgesBetweenNodes(0, 1, 1.0); graph.AddEdgesBetweenNodes(1, 2, 1.0); graph.AddEdgesBetweenNodes(3, 4, 1.0); graph.AddEdgesBetweenNodes(4, 5, 1.0); graph.AddEdgesBetweenNodes(6, 7, 1.0); graph.AddEdgesBetweenNodes(7, 8, 1.0); // X-direction edges graph.AddEdgesBetweenNodes(0, 3, 1.0); graph.AddEdgesBetweenNodes(3, 6, 1.0); graph.AddEdgesBetweenNodes(1, 4, 1.0); graph.AddEdgesBetweenNodes(4, 7, 1.0); graph.AddEdgesBetweenNodes(2, 5, 1.0); graph.AddEdgesBetweenNodes(5, 8, 1.0); assert(graph.CheckGraphLinkage()); auto dijkstras_result_4connected = arc_dijkstras::SimpleDijkstrasAlgorithm<Eigen::Vector2d, std::allocator<Eigen::Vector2d>>::PerformDijkstrasAlgorithm(graph, 0); std::cout << "4-connected edges\n" << "Node index : 0, 1, 2, 3, 4, 5, 6, 7, 8\n"; std::cout << "Previous graph indices: " << PrettyPrint::PrettyPrint(dijkstras_result_4connected.second.first) << std::endl; std::cout << "Distance : " << PrettyPrint::PrettyPrint(dijkstras_result_4connected.second.second) << std::endl; // Diagonal edges graph.AddEdgesBetweenNodes(0, 4, std::sqrt(2)); graph.AddEdgesBetweenNodes(1, 5, std::sqrt(2)); graph.AddEdgesBetweenNodes(3, 7, std::sqrt(2)); graph.AddEdgesBetweenNodes(4, 8, std::sqrt(2)); graph.AddEdgesBetweenNodes(1, 3, std::sqrt(2)); graph.AddEdgesBetweenNodes(2, 4, std::sqrt(2)); graph.AddEdgesBetweenNodes(4, 6, std::sqrt(2)); graph.AddEdgesBetweenNodes(5, 7, std::sqrt(2)); assert(graph.CheckGraphLinkage()); auto dijkstras_result_8connected = arc_dijkstras::SimpleDijkstrasAlgorithm<Eigen::Vector2d, std::allocator<Eigen::Vector2d>>::PerformDijkstrasAlgorithm(graph, 0); std::cout << "\n8-connected edges\n" << "Node index : 0, 1, 2, 3, 4, 5, 6, 7, 8\n"; std::cout << "Previous graph indices: " << PrettyPrint::PrettyPrint(dijkstras_result_8connected.second.first) << std::endl; std::cout << "Distance : " << PrettyPrint::PrettyPrint(dijkstras_result_8connected.second.second) << std::endl; std::cout << "Serialization test... "; // Define the graph value serialization function const auto value_serializer_fn = [] (const Eigen::Vector2d& value, std::vector<uint8_t>& buffer) { // return 0UL; const uint64_t start_buffer_size = buffer.size(); uint64_t running_total = 0; running_total += arc_helpers::SerializeFixedSizePOD<double>(value(0), buffer); running_total += arc_helpers::SerializeFixedSizePOD<double>(value(1), buffer); const uint64_t end_buffer_size = buffer.size(); const uint64_t bytes_written = end_buffer_size - start_buffer_size; assert(running_total == bytes_written); return bytes_written; }; // Define the graph value serialization function const auto value_deserializer_fn = [] (const std::vector<uint8_t>& buffer, const int64_t current) { // return std::make_pair(Eigen::Vector2d(), 0UL); uint64_t current_position = current; // Deserialze 2 doubles std::pair<double, uint64_t> x = arc_helpers::DeserializeFixedSizePOD<double>(buffer, current_position); current_position += x.second; std::pair<double, uint64_t> y = arc_helpers::DeserializeFixedSizePOD<double>(buffer, current_position); current_position += y.second; const Eigen::Vector2d deserialized(x.first, y.first); // Figure out how many bytes were read const uint64_t bytes_read = current_position - current; return std::make_pair(deserialized, bytes_read); }; // Serialze the graph std::vector<uint8_t> buffer; graph.SerializeSelf(buffer, value_serializer_fn); auto deserialized_result = arc_dijkstras::Graph<Eigen::Vector2d>::Deserialize(buffer, 0, value_deserializer_fn); assert(deserialized_result.first.CheckGraphLinkage()); std::cout << "passed" << std::endl; return 0; } <commit_msg>Even simpler graph - 2 nodes, 1 single-directional edge<commit_after>#include <iostream> #include <arc_utilities/dijkstras.hpp> #include <arc_utilities/pretty_print.hpp> int main(int argc, char* argv[]) { (void)argc; (void)argv; std::cout << "Creating graph with nodes indices:\n\n"; std::cout << " 2 | 5 | 8\n" << " --+---+--\n" << " 1 | 4 | 7\n" << " --+---+--\n" << " 0 | 3 | 6\n\n"; arc_dijkstras::Graph<Eigen::Vector2d> graph(9); graph.AddNode(Eigen::Vector2d(0,0)); graph.AddNode(Eigen::Vector2d(1,1)); for (double x = -1; x <= 1; x += 1) { for (double y = -1; y <= 1; y += 1) { graph.AddNode(Eigen::Vector2d(x, y)); } } // Y-direction edges graph.AddEdgeBetweenNodes(0, 1, 1.0); graph.AddEdgesBetweenNodes(1, 2, 1.0); graph.AddEdgesBetweenNodes(3, 4, 1.0); graph.AddEdgesBetweenNodes(4, 5, 1.0); graph.AddEdgesBetweenNodes(6, 7, 1.0); graph.AddEdgesBetweenNodes(7, 8, 1.0); // X-direction edges graph.AddEdgesBetweenNodes(0, 3, 1.0); graph.AddEdgesBetweenNodes(3, 6, 1.0); graph.AddEdgesBetweenNodes(1, 4, 1.0); graph.AddEdgesBetweenNodes(4, 7, 1.0); graph.AddEdgesBetweenNodes(2, 5, 1.0); graph.AddEdgesBetweenNodes(5, 8, 1.0); assert(graph.CheckGraphLinkage()); auto dijkstras_result_4connected = arc_dijkstras::SimpleDijkstrasAlgorithm<Eigen::Vector2d, std::allocator<Eigen::Vector2d>>::PerformDijkstrasAlgorithm(graph, 0); std::cout << "4-connected edges\n" << "Node index : 0, 1, 2, 3, 4, 5, 6, 7, 8\n"; std::cout << "Previous graph indices: " << PrettyPrint::PrettyPrint(dijkstras_result_4connected.second.first) << std::endl; std::cout << "Distance : " << PrettyPrint::PrettyPrint(dijkstras_result_4connected.second.second) << std::endl; // Diagonal edges graph.AddEdgesBetweenNodes(0, 4, std::sqrt(2)); graph.AddEdgesBetweenNodes(1, 5, std::sqrt(2)); graph.AddEdgesBetweenNodes(3, 7, std::sqrt(2)); graph.AddEdgesBetweenNodes(4, 8, std::sqrt(2)); graph.AddEdgesBetweenNodes(1, 3, std::sqrt(2)); graph.AddEdgesBetweenNodes(2, 4, std::sqrt(2)); graph.AddEdgesBetweenNodes(4, 6, std::sqrt(2)); graph.AddEdgesBetweenNodes(5, 7, std::sqrt(2)); assert(graph.CheckGraphLinkage()); auto dijkstras_result_8connected = arc_dijkstras::SimpleDijkstrasAlgorithm<Eigen::Vector2d, std::allocator<Eigen::Vector2d>>::PerformDijkstrasAlgorithm(graph, 0); std::cout << "\n8-connected edges\n" << "Node index : 0, 1, 2, 3, 4, 5, 6, 7, 8\n"; std::cout << "Previous graph indices: " << PrettyPrint::PrettyPrint(dijkstras_result_8connected.second.first) << std::endl; std::cout << "Distance : " << PrettyPrint::PrettyPrint(dijkstras_result_8connected.second.second) << std::endl; std::cout << "Serialization test... "; arc_dijkstras::Graph<Eigen::Vector2d> serialization_test_graph(2); serialization_test_graph.AddNode(Eigen::Vector2d(0,0)); serialization_test_graph.AddNode(Eigen::Vector2d(1,1)); serialization_test_graph.AddEdgesBetweenNodes(0, 1, 1.0); // Define the graph value serialization function const auto value_serializer_fn = [] (const Eigen::Vector2d& value, std::vector<uint8_t>& buffer) { // return 0UL; const uint64_t start_buffer_size = buffer.size(); uint64_t running_total = 0; running_total += arc_helpers::SerializeFixedSizePOD<double>(value(0), buffer); running_total += arc_helpers::SerializeFixedSizePOD<double>(value(1), buffer); const uint64_t end_buffer_size = buffer.size(); const uint64_t bytes_written = end_buffer_size - start_buffer_size; assert(running_total == bytes_written); return bytes_written; }; // Define the graph value serialization function const auto value_deserializer_fn = [] (const std::vector<uint8_t>& buffer, const int64_t current) { // return std::make_pair(Eigen::Vector2d(), 0UL); uint64_t current_position = current; // Deserialze 2 doubles std::pair<double, uint64_t> x = arc_helpers::DeserializeFixedSizePOD<double>(buffer, current_position); current_position += x.second; std::pair<double, uint64_t> y = arc_helpers::DeserializeFixedSizePOD<double>(buffer, current_position); current_position += y.second; const Eigen::Vector2d deserialized(x.first, y.first); // Figure out how many bytes were read const uint64_t bytes_read = current_position - current; return std::make_pair(deserialized, bytes_read); }; // Serialze the graph std::vector<uint8_t> buffer; serialization_test_graph.SerializeSelf(buffer, value_serializer_fn); auto deserialized_result = arc_dijkstras::Graph<Eigen::Vector2d>::Deserialize(buffer, 0, value_deserializer_fn); assert(deserialized_result.first.CheckGraphLinkage()); std::cout << "passed" << std::endl; return 0; } <|endoftext|>
<commit_before>/* * * AESCipher * ledger-core * * Created by Pierre Pollastri on 08/12/2016. * * The MIT License (MIT) * * Copyright (c) 2016 Ledger * * 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 "AESCipher.hpp" #include "PBKDF2.hpp" #include "AES256.hpp" namespace ledger { namespace core { AESCipher::AESCipher(const std::shared_ptr<api::RandomNumberGenerator> &rng, const std::string &password, const std::string &salt, uint32_t iter) { _rng = rng; _key = PBKDF2::derive( std::vector<uint8_t>(password.data(), password.data() + password.size()), std::vector<uint8_t>(salt.data(), salt.data() + salt.size()) , iter, 32); } void AESCipher::encrypt(std::istream *input, std::ostream *output) { #if defined(_WIN32) || defined(_WIN64) #else input->seekg(0, input->beg); uint32_t maxRead = 254 * AES256::BLOCK_SIZE; uint8_t buffer[maxRead]; do { // Read 254 * AES_BLOCK_SIZE bytes (we want at most 0xFF blocks to encrypt we the same IV) input->read((char *)buffer, maxRead); uint32_t read = input->gcount(); // Create an IVt auto IV = _rng->getRandomBytes(AES256::BLOCK_SIZE); // Encrypt auto encrypted = AES256::encrypt(IV, _key, std::vector<uint8_t>(buffer, buffer + read)); // Store number of blocks uint8_t blocksCount = (encrypted.size() / AES256::BLOCK_SIZE); (*output) << blocksCount; (*output) << read; // Store IV output->write((char *)IV.data(), IV.size()); // Store encrypted data output->write((char *)encrypted.data(), encrypted.size()); } while (!input->eof()); #endif } void AESCipher::decrypt(std::istream *input, std::ostream *output) { #if defined(_WIN32) || defined(_WIN64) #else input->seekg(0, input->beg); uint32_t maxRead = 255 * AES256::BLOCK_SIZE; uint8_t buffer[maxRead]; do { uint8_t blocksCount; uint32_t dataSize; (*input) >> blocksCount; (*input) >> dataSize; std::vector<uint8_t> IV; IV.resize(AES256::BLOCK_SIZE); input->read((char *)IV.data(), IV.size()); input->read((char *)buffer, blocksCount * AES256::BLOCK_SIZE); if (input->gcount() < blocksCount * AES256::BLOCK_SIZE) break; auto decrypted = AES256::decrypt(IV, _key, std::vector<uint8_t>(buffer, buffer + (blocksCount * AES256::BLOCK_SIZE))); output->write((char *)decrypted.data(), dataSize); } while (!input->eof()); #endif } void AESCipher::encrypt(BytesReader& input, BytesWriter& output) { uint32_t maxRead = 254 * AES256::BLOCK_SIZE; do { // Read 254 * AES_BLOCK_SIZE bytes (we want at most 0xFF blocks to encrypt we the same IV) uint32_t available = input.available(); uint32_t minEncryptedRead = std::min(maxRead,available); std::vector<uint8_t> dataToEncrypt = input.read(minEncryptedRead); uint32_t read = dataToEncrypt.size(); // Create an IVt auto IV = _rng->getRandomBytes(AES256::BLOCK_SIZE); // Encrypt auto encrypted = AES256::encrypt(IV, _key, dataToEncrypt); // Store number of blocks uint8_t blocksCount = (encrypted.size() / AES256::BLOCK_SIZE); //Number of blocks of size AES256::BLOCK_SIZE in enrypted data output.writeByte(blocksCount); //Limit of reading (padding or string terminating before maxRead) output.writeVarInt(read); // Store IV output.writeByteArray(IV); // Store encrypted data output.writeByteArray(encrypted); } while (input.hasNext()); } void AESCipher::decrypt(BytesReader& input, BytesWriter& output) { uint32_t maxRead = 255 * AES256::BLOCK_SIZE; do { //Get number of blocks in encrypted data uint8_t blocksCount = input.readNextByte(); //Size of encrypted (chunk of) data uint32_t encryptedDataSize = blocksCount*AES256::BLOCK_SIZE; //Get data that we read uint32_t dataSize = input.readNextVarInt(); //Read IV std::vector<uint8_t> IV = input.read(AES256::BLOCK_SIZE); //Get number of bytes to read uint32_t available = input.available(); if(available < encryptedDataSize) { //Should not read than more available data break; } //Read encrypted data std::vector<uint8_t> encryptedData = input.read(encryptedDataSize); //Decrypt auto decrypted = AES256::decrypt(IV, _key, encryptedData); //Truncate if needed to size of encrypted data that we stored in dataSize bytes if(dataSize < decrypted.size()){ decrypted.resize(dataSize); } //Store decrypted data output.writeByteArray(decrypted); } while (input.hasNext()); } } } <commit_msg>Add an assert in the AESCipher to ensure IV is never null.<commit_after>/* * * AESCipher * ledger-core * * Created by Pierre Pollastri on 08/12/2016. * * The MIT License (MIT) * * Copyright (c) 2016 Ledger * * 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 "AESCipher.hpp" #include "PBKDF2.hpp" #include "AES256.hpp" namespace ledger { namespace core { AESCipher::AESCipher(const std::shared_ptr<api::RandomNumberGenerator> &rng, const std::string &password, const std::string &salt, uint32_t iter) { _rng = rng; _key = PBKDF2::derive( std::vector<uint8_t>(password.data(), password.data() + password.size()), std::vector<uint8_t>(salt.data(), salt.data() + salt.size()) , iter, 32); } void AESCipher::encrypt(std::istream *input, std::ostream *output) { #if defined(_WIN32) || defined(_WIN64) #else input->seekg(0, input->beg); uint32_t maxRead = 254 * AES256::BLOCK_SIZE; uint8_t buffer[maxRead]; do { // Read 254 * AES_BLOCK_SIZE bytes (we want at most 0xFF blocks to encrypt we the same IV) input->read((char *)buffer, maxRead); uint32_t read = input->gcount(); // Create an IVt auto IV = _rng->getRandomBytes(AES256::BLOCK_SIZE); assert(IV.size() == AES256::BLOCK_SIZE); // Encrypt auto encrypted = AES256::encrypt(IV, _key, std::vector<uint8_t>(buffer, buffer + read)); // Store number of blocks uint8_t blocksCount = (encrypted.size() / AES256::BLOCK_SIZE); (*output) << blocksCount; (*output) << read; // Store IV output->write((char *)IV.data(), IV.size()); // Store encrypted data output->write((char *)encrypted.data(), encrypted.size()); } while (!input->eof()); #endif } void AESCipher::decrypt(std::istream *input, std::ostream *output) { #if defined(_WIN32) || defined(_WIN64) #else input->seekg(0, input->beg); uint32_t maxRead = 255 * AES256::BLOCK_SIZE; uint8_t buffer[maxRead]; do { uint8_t blocksCount; uint32_t dataSize; (*input) >> blocksCount; (*input) >> dataSize; std::vector<uint8_t> IV; IV.resize(AES256::BLOCK_SIZE); input->read((char *)IV.data(), IV.size()); input->read((char *)buffer, blocksCount * AES256::BLOCK_SIZE); if (input->gcount() < blocksCount * AES256::BLOCK_SIZE) break; auto decrypted = AES256::decrypt(IV, _key, std::vector<uint8_t>(buffer, buffer + (blocksCount * AES256::BLOCK_SIZE))); output->write((char *)decrypted.data(), dataSize); } while (!input->eof()); #endif } void AESCipher::encrypt(BytesReader& input, BytesWriter& output) { uint32_t maxRead = 254 * AES256::BLOCK_SIZE; do { // Read 254 * AES_BLOCK_SIZE bytes (we want at most 0xFF blocks to encrypt we the same IV) uint32_t available = input.available(); uint32_t minEncryptedRead = std::min(maxRead,available); std::vector<uint8_t> dataToEncrypt = input.read(minEncryptedRead); uint32_t read = dataToEncrypt.size(); // Create an IVt auto IV = _rng->getRandomBytes(AES256::BLOCK_SIZE); // Encrypt auto encrypted = AES256::encrypt(IV, _key, dataToEncrypt); // Store number of blocks uint8_t blocksCount = (encrypted.size() / AES256::BLOCK_SIZE); //Number of blocks of size AES256::BLOCK_SIZE in enrypted data output.writeByte(blocksCount); //Limit of reading (padding or string terminating before maxRead) output.writeVarInt(read); // Store IV output.writeByteArray(IV); // Store encrypted data output.writeByteArray(encrypted); } while (input.hasNext()); } void AESCipher::decrypt(BytesReader& input, BytesWriter& output) { uint32_t maxRead = 255 * AES256::BLOCK_SIZE; do { //Get number of blocks in encrypted data uint8_t blocksCount = input.readNextByte(); //Size of encrypted (chunk of) data uint32_t encryptedDataSize = blocksCount*AES256::BLOCK_SIZE; //Get data that we read uint32_t dataSize = input.readNextVarInt(); //Read IV std::vector<uint8_t> IV = input.read(AES256::BLOCK_SIZE); //Get number of bytes to read uint32_t available = input.available(); if(available < encryptedDataSize) { //Should not read than more available data break; } //Read encrypted data std::vector<uint8_t> encryptedData = input.read(encryptedDataSize); //Decrypt auto decrypted = AES256::decrypt(IV, _key, encryptedData); //Truncate if needed to size of encrypted data that we stored in dataSize bytes if(dataSize < decrypted.size()){ decrypted.resize(dataSize); } //Store decrypted data output.writeByteArray(decrypted); } while (input.hasNext()); } } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: Date.cxx,v $ * * $Revision: 1.23 $ * * last change: $Author: obo $ $Date: 2006-09-16 23:48:14 $ * * 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_forms.hxx" #ifndef _FORMS_DATE_HXX_ #include "Date.hxx" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _DATE_HXX #include <tools/date.hxx> #endif #ifndef _DBHELPER_DBCONVERSION_HXX_ #include <connectivity/dbconversion.hxx> #endif #ifndef _COM_SUN_STAR_SDBC_DATATYPE_HPP_ #include <com/sun/star/sdbc/DataType.hpp> #endif using namespace dbtools; //......................................................................... namespace frm { //......................................................................... using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::sdb; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::util; using namespace ::com::sun::star::container; using namespace ::com::sun::star::form; using namespace ::com::sun::star::awt; using namespace ::com::sun::star::io; using namespace ::com::sun::star::lang; //------------------------------------------------------------------ ODateControl::ODateControl(const Reference<XMultiServiceFactory>& _rxFactory) :OBoundControl(_rxFactory, VCL_CONTROL_DATEFIELD) { } //------------------------------------------------------------------ InterfaceRef SAL_CALL ODateControl_CreateInstance(const Reference<XMultiServiceFactory>& _rxFactory) { return *(new ODateControl(_rxFactory)); } //------------------------------------------------------------------------------ Sequence<Type> ODateControl::_getTypes() { return OBoundControl::_getTypes(); } //------------------------------------------------------------------------------ StringSequence SAL_CALL ODateControl::getSupportedServiceNames() throw() { StringSequence aSupported = OBoundControl::getSupportedServiceNames(); aSupported.realloc(aSupported.getLength() + 1); ::rtl::OUString*pArray = aSupported.getArray(); pArray[aSupported.getLength()-1] = FRM_SUN_CONTROL_DATEFIELD; return aSupported; } /*************************************************************************/ //------------------------------------------------------------------ InterfaceRef SAL_CALL ODateModel_CreateInstance(const Reference<XMultiServiceFactory>& _rxFactory) { return *(new ODateModel(_rxFactory)); } //------------------------------------------------------------------------------ Sequence<Type> ODateModel::_getTypes() { return OEditBaseModel::_getTypes(); } //------------------------------------------------------------------ DBG_NAME( ODateModel ) //------------------------------------------------------------------ ODateModel::ODateModel(const Reference<XMultiServiceFactory>& _rxFactory) :OEditBaseModel( _rxFactory, VCL_CONTROLMODEL_DATEFIELD, FRM_SUN_CONTROL_DATEFIELD, sal_True, sal_True ) // use the old control name for compytibility reasons ,OLimitedFormats( _rxFactory, FormComponentType::DATEFIELD ) { DBG_CTOR( ODateModel, NULL ); m_nClassId = FormComponentType::DATEFIELD; initValueProperty( PROPERTY_DATE, PROPERTY_ID_DATE ); setAggregateSet(m_xAggregateFastSet, getOriginalHandle(PROPERTY_ID_DATEFORMAT)); osl_incrementInterlockedCount( &m_refCount ); try { if ( m_xAggregateSet.is() ) m_xAggregateSet->setPropertyValue( PROPERTY_DATEMIN, makeAny( (sal_Int32)( ::Date( 1, 1, 1800 ).GetDate() ) ) ); } catch( const Exception& ) { OSL_ENSURE( sal_False, "ODateModel::ODateModel: caught an exception!" ); } osl_decrementInterlockedCount( &m_refCount ); } //------------------------------------------------------------------------------ ODateModel::ODateModel( const ODateModel* _pOriginal, const Reference<XMultiServiceFactory>& _rxFactory ) :OEditBaseModel( _pOriginal, _rxFactory ) ,OLimitedFormats( _rxFactory, FormComponentType::DATEFIELD ) { DBG_CTOR( ODateModel, NULL ); setAggregateSet( m_xAggregateFastSet, getOriginalHandle( PROPERTY_ID_DATEFORMAT ) ); } //------------------------------------------------------------------------------ ODateModel::~ODateModel( ) { setAggregateSet(Reference< XFastPropertySet >(), -1); DBG_DTOR( ODateModel, NULL ); } // XCloneable //------------------------------------------------------------------------------ IMPLEMENT_DEFAULT_CLONING( ODateModel ) // XServiceInfo //------------------------------------------------------------------------------ StringSequence SAL_CALL ODateModel::getSupportedServiceNames() throw() { StringSequence aSupported = OBoundControlModel::getSupportedServiceNames(); sal_Int32 nOldLen = aSupported.getLength(); aSupported.realloc( nOldLen + 8 ); ::rtl::OUString* pStoreTo = aSupported.getArray() + nOldLen; *pStoreTo++ = BINDABLE_CONTROL_MODEL; *pStoreTo++ = DATA_AWARE_CONTROL_MODEL; *pStoreTo++ = VALIDATABLE_CONTROL_MODEL; *pStoreTo++ = BINDABLE_DATA_AWARE_CONTROL_MODEL; *pStoreTo++ = VALIDATABLE_BINDABLE_CONTROL_MODEL; *pStoreTo++ = FRM_SUN_COMPONENT_DATEFIELD; *pStoreTo++ = FRM_SUN_COMPONENT_DATABASE_DATEFIELD; *pStoreTo++ = BINDABLE_DATABASE_DATE_FIELD; return aSupported; } //------------------------------------------------------------------------------ ::rtl::OUString SAL_CALL ODateModel::getServiceName() throw ( ::com::sun::star::uno::RuntimeException) { return FRM_COMPONENT_DATEFIELD; // old (non-sun) name for compatibility ! } // XPropertySet //------------------------------------------------------------------------------ Reference<XPropertySetInfo> SAL_CALL ODateModel::getPropertySetInfo() throw( RuntimeException ) { Reference<XPropertySetInfo> xInfo( createPropertySetInfo( getInfoHelper() ) ); return xInfo; } //------------------------------------------------------------------------------ void ODateModel::fillProperties( Sequence< Property >& _rProps, Sequence< Property >& _rAggregateProps ) const { BEGIN_DESCRIBE_PROPERTIES( 4, OEditBaseModel ) DECL_PROP3(DEFAULT_DATE, sal_Int32, BOUND, MAYBEDEFAULT, MAYBEVOID); DECL_PROP1(TABINDEX, sal_Int16, BOUND); DECL_PROP1(FORMATKEY, sal_Int32, TRANSIENT); DECL_IFACE_PROP2(FORMATSSUPPLIER, XNumberFormatsSupplier, READONLY, TRANSIENT); END_DESCRIBE_PROPERTIES(); } //------------------------------------------------------------------------------ ::cppu::IPropertyArrayHelper& ODateModel::getInfoHelper() { return *const_cast<ODateModel*>(this)->getArrayHelper(); } //------------------------------------------------------------------------------ void SAL_CALL ODateModel::getFastPropertyValue(Any& _rValue, sal_Int32 _nHandle ) const { switch (_nHandle) { case PROPERTY_ID_FORMATKEY: getFormatKeyPropertyValue(_rValue); break; case PROPERTY_ID_FORMATSSUPPLIER: _rValue <<= getFormatsSupplier(); break; default: OEditBaseModel::getFastPropertyValue(_rValue, _nHandle); break; } } //------------------------------------------------------------------------------ sal_Bool SAL_CALL ODateModel::convertFastPropertyValue(Any& _rConvertedValue, Any& _rOldValue, sal_Int32 _nHandle, const Any& _rValue ) throw(IllegalArgumentException) { if (PROPERTY_ID_FORMATKEY == _nHandle) return convertFormatKeyPropertyValue(_rConvertedValue, _rOldValue, _rValue); else return OEditBaseModel::convertFastPropertyValue(_rConvertedValue, _rOldValue, _nHandle, _rValue ); } //------------------------------------------------------------------------------ void SAL_CALL ODateModel::setFastPropertyValue_NoBroadcast(sal_Int32 _nHandle, const Any& _rValue) throw ( ::com::sun::star::uno::Exception) { if (PROPERTY_ID_FORMATKEY == _nHandle) setFormatKeyPropertyValue(_rValue); else OEditBaseModel::setFastPropertyValue_NoBroadcast(_nHandle, _rValue); } // XLoadListener //------------------------------------------------------------------------------ void ODateModel::onConnectedDbColumn( const Reference< XInterface >& _rxForm ) { OBoundControlModel::onConnectedDbColumn( _rxForm ); Reference<XPropertySet> xField = getField(); if (xField.is()) { m_bDateTimeField = sal_False; try { sal_Int32 nFieldType; xField->getPropertyValue(PROPERTY_FIELDTYPE) >>= nFieldType; m_bDateTimeField = (nFieldType == DataType::TIMESTAMP); } catch(Exception&) { } } } //------------------------------------------------------------------------------ sal_Bool ODateModel::commitControlValueToDbColumn( bool /*_bPostReset*/ ) { Any aControlValue( m_xAggregateFastSet->getFastPropertyValue( getValuePropertyAggHandle() ) ); if ( !compare( aControlValue, m_aSaveValue ) ) { if ( !aControlValue.hasValue() ) m_xColumnUpdate->updateNull(); else { try { util::Date aDate; if ( !( aControlValue >>= aDate ) ) { sal_Int32 nAsInt(0); aControlValue >>= nAsInt; aDate = DBTypeConversion::toDate(nAsInt); } if ( !m_bDateTimeField ) m_xColumnUpdate->updateDate( aDate ); else { util::DateTime aDateTime = m_xColumn->getTimestamp(); aDateTime.Day = aDate.Day; aDateTime.Month = aDate.Month; aDateTime.Year = aDate.Year; m_xColumnUpdate->updateTimestamp( aDateTime ); } } catch(Exception&) { return sal_False; } } m_aSaveValue = aControlValue; } return sal_True; } //------------------------------------------------------------------------------ void ODateModel::impl_translateControlValueToUNODate( Any& _rUNOValue ) const { _rUNOValue = getControlValue(); if ( _rUNOValue.hasValue() ) { sal_Int32 nDate = 0; OSL_VERIFY( _rUNOValue >>= nDate ); _rUNOValue <<= DBTypeConversion::toDate( nDate ); } } //------------------------------------------------------------------------------ Any ODateModel::translateControlValueToExternalValue( ) const { Any aExternalValue; impl_translateControlValueToUNODate( aExternalValue ); return aExternalValue; } //------------------------------------------------------------------------------ Any ODateModel::translateExternalValueToControlValue( ) const { OSL_PRECOND( hasExternalValueBinding(), "ODateModel::translateExternalValueToControlValue: precondition not met!" ); Any aControlValue; if ( hasExternalValueBinding() ) { Any aExternalValue = getExternalValueBinding()->getValue( ::getCppuType( static_cast< util::Date* >( NULL ) ) ); if ( aExternalValue.hasValue() ) { util::Date aDate; OSL_VERIFY( aExternalValue >>= aDate ); aControlValue <<= DBTypeConversion::toINT32( aDate ); } } return aControlValue; } //------------------------------------------------------------------------------ Any ODateModel::translateControlValueToValidatableValue( ) const { Any aValidatableValue; impl_translateControlValueToUNODate( aValidatableValue ); return aValidatableValue; } //------------------------------------------------------------------------------ Any ODateModel::translateDbColumnToControlValue() { util::Date aDate = m_xColumn->getDate(); if (m_xColumn->wasNull()) m_aSaveValue.clear(); else // the aggregated set expects an Int32 as value ... m_aSaveValue <<= DBTypeConversion::toINT32(aDate); return m_aSaveValue; } //------------------------------------------------------------------------------ Any ODateModel::getDefaultForReset() const { return m_aDefault; } //------------------------------------------------------------------------------ sal_Bool ODateModel::approveValueBinding( const Reference< binding::XValueBinding >& _rxBinding ) { OSL_PRECOND( _rxBinding.is(), "ODateModel::approveValueBinding: invalid binding!" ); return _rxBinding.is() && _rxBinding->supportsType( ::getCppuType( static_cast< util::Date* >( NULL ) ) ); } //......................................................................... } // namespace frm //......................................................................... <commit_msg>INTEGRATION: CWS pj65 (1.23.22); FILE MERGED 2006/10/31 13:40:59 pjanik 1.23.22.1: #i71027#: prevent warnings on Mac OS X with gcc 4.0.1.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: Date.cxx,v $ * * $Revision: 1.24 $ * * last change: $Author: vg $ $Date: 2006-11-21 17:40:26 $ * * 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_forms.hxx" #ifndef _FORMS_DATE_HXX_ #include "Date.hxx" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _DATE_HXX #include <tools/date.hxx> #endif #ifndef _DBHELPER_DBCONVERSION_HXX_ #include <connectivity/dbconversion.hxx> #endif #ifndef _COM_SUN_STAR_SDBC_DATATYPE_HPP_ #include <com/sun/star/sdbc/DataType.hpp> #endif using namespace dbtools; //......................................................................... namespace frm { //......................................................................... using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::sdb; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::util; using namespace ::com::sun::star::container; using namespace ::com::sun::star::form; using namespace ::com::sun::star::awt; using namespace ::com::sun::star::io; using namespace ::com::sun::star::lang; //------------------------------------------------------------------ ODateControl::ODateControl(const Reference<XMultiServiceFactory>& _rxFactory) :OBoundControl(_rxFactory, VCL_CONTROL_DATEFIELD) { } //------------------------------------------------------------------ InterfaceRef SAL_CALL ODateControl_CreateInstance(const Reference<XMultiServiceFactory>& _rxFactory) { return *(new ODateControl(_rxFactory)); } //------------------------------------------------------------------------------ Sequence<Type> ODateControl::_getTypes() { return OBoundControl::_getTypes(); } //------------------------------------------------------------------------------ StringSequence SAL_CALL ODateControl::getSupportedServiceNames() throw() { StringSequence aSupported = OBoundControl::getSupportedServiceNames(); aSupported.realloc(aSupported.getLength() + 1); ::rtl::OUString*pArray = aSupported.getArray(); pArray[aSupported.getLength()-1] = FRM_SUN_CONTROL_DATEFIELD; return aSupported; } /*************************************************************************/ //------------------------------------------------------------------ InterfaceRef SAL_CALL ODateModel_CreateInstance(const Reference<XMultiServiceFactory>& _rxFactory) { return *(new ODateModel(_rxFactory)); } //------------------------------------------------------------------------------ Sequence<Type> ODateModel::_getTypes() { return OEditBaseModel::_getTypes(); } //------------------------------------------------------------------ DBG_NAME( ODateModel ) //------------------------------------------------------------------ ODateModel::ODateModel(const Reference<XMultiServiceFactory>& _rxFactory) :OEditBaseModel( _rxFactory, VCL_CONTROLMODEL_DATEFIELD, FRM_SUN_CONTROL_DATEFIELD, sal_True, sal_True ) // use the old control name for compytibility reasons ,OLimitedFormats( _rxFactory, FormComponentType::DATEFIELD ) { DBG_CTOR( ODateModel, NULL ); m_nClassId = FormComponentType::DATEFIELD; initValueProperty( PROPERTY_DATE, PROPERTY_ID_DATE ); setAggregateSet(m_xAggregateFastSet, getOriginalHandle(PROPERTY_ID_DATEFORMAT)); osl_incrementInterlockedCount( &m_refCount ); try { if ( m_xAggregateSet.is() ) m_xAggregateSet->setPropertyValue( PROPERTY_DATEMIN, makeAny( (sal_Int32)( ::Date( 1, 1, 1800 ).GetDate() ) ) ); } catch( const Exception& ) { OSL_ENSURE( sal_False, "ODateModel::ODateModel: caught an exception!" ); } osl_decrementInterlockedCount( &m_refCount ); } //------------------------------------------------------------------------------ ODateModel::ODateModel( const ODateModel* _pOriginal, const Reference<XMultiServiceFactory>& _rxFactory ) :OEditBaseModel( _pOriginal, _rxFactory ) ,OLimitedFormats( _rxFactory, FormComponentType::DATEFIELD ) { DBG_CTOR( ODateModel, NULL ); setAggregateSet( m_xAggregateFastSet, getOriginalHandle( PROPERTY_ID_DATEFORMAT ) ); } //------------------------------------------------------------------------------ ODateModel::~ODateModel( ) { setAggregateSet(Reference< XFastPropertySet >(), -1); DBG_DTOR( ODateModel, NULL ); } // XCloneable //------------------------------------------------------------------------------ IMPLEMENT_DEFAULT_CLONING( ODateModel ) // XServiceInfo //------------------------------------------------------------------------------ StringSequence SAL_CALL ODateModel::getSupportedServiceNames() throw() { StringSequence aSupported = OBoundControlModel::getSupportedServiceNames(); sal_Int32 nOldLen = aSupported.getLength(); aSupported.realloc( nOldLen + 8 ); ::rtl::OUString* pStoreTo = aSupported.getArray() + nOldLen; *pStoreTo++ = BINDABLE_CONTROL_MODEL; *pStoreTo++ = DATA_AWARE_CONTROL_MODEL; *pStoreTo++ = VALIDATABLE_CONTROL_MODEL; *pStoreTo++ = BINDABLE_DATA_AWARE_CONTROL_MODEL; *pStoreTo++ = VALIDATABLE_BINDABLE_CONTROL_MODEL; *pStoreTo++ = FRM_SUN_COMPONENT_DATEFIELD; *pStoreTo++ = FRM_SUN_COMPONENT_DATABASE_DATEFIELD; *pStoreTo++ = BINDABLE_DATABASE_DATE_FIELD; return aSupported; } //------------------------------------------------------------------------------ ::rtl::OUString SAL_CALL ODateModel::getServiceName() throw ( ::com::sun::star::uno::RuntimeException) { return FRM_COMPONENT_DATEFIELD; // old (non-sun) name for compatibility ! } // XPropertySet //------------------------------------------------------------------------------ Reference<XPropertySetInfo> SAL_CALL ODateModel::getPropertySetInfo() throw( RuntimeException ) { Reference<XPropertySetInfo> xInfo( createPropertySetInfo( getInfoHelper() ) ); return xInfo; } //------------------------------------------------------------------------------ void ODateModel::fillProperties( Sequence< Property >& _rProps, Sequence< Property >& _rAggregateProps ) const { BEGIN_DESCRIBE_PROPERTIES( 4, OEditBaseModel ) DECL_PROP3(DEFAULT_DATE, sal_Int32, BOUND, MAYBEDEFAULT, MAYBEVOID); DECL_PROP1(TABINDEX, sal_Int16, BOUND); DECL_PROP1(FORMATKEY, sal_Int32, TRANSIENT); DECL_IFACE_PROP2(FORMATSSUPPLIER, XNumberFormatsSupplier, READONLY, TRANSIENT); END_DESCRIBE_PROPERTIES(); } //------------------------------------------------------------------------------ ::cppu::IPropertyArrayHelper& ODateModel::getInfoHelper() { return *const_cast<ODateModel*>(this)->getArrayHelper(); } //------------------------------------------------------------------------------ void SAL_CALL ODateModel::getFastPropertyValue(Any& _rValue, sal_Int32 _nHandle ) const { switch (_nHandle) { case PROPERTY_ID_FORMATKEY: getFormatKeyPropertyValue(_rValue); break; case PROPERTY_ID_FORMATSSUPPLIER: _rValue <<= getFormatsSupplier(); break; default: OEditBaseModel::getFastPropertyValue(_rValue, _nHandle); break; } } //------------------------------------------------------------------------------ sal_Bool SAL_CALL ODateModel::convertFastPropertyValue(Any& _rConvertedValue, Any& _rOldValue, sal_Int32 _nHandle, const Any& _rValue ) throw(IllegalArgumentException) { if (PROPERTY_ID_FORMATKEY == _nHandle) return convertFormatKeyPropertyValue(_rConvertedValue, _rOldValue, _rValue); else return OEditBaseModel::convertFastPropertyValue(_rConvertedValue, _rOldValue, _nHandle, _rValue ); } //------------------------------------------------------------------------------ void SAL_CALL ODateModel::setFastPropertyValue_NoBroadcast(sal_Int32 _nHandle, const Any& _rValue) throw ( ::com::sun::star::uno::Exception) { if (PROPERTY_ID_FORMATKEY == _nHandle) setFormatKeyPropertyValue(_rValue); else OEditBaseModel::setFastPropertyValue_NoBroadcast(_nHandle, _rValue); } // XLoadListener //------------------------------------------------------------------------------ void ODateModel::onConnectedDbColumn( const Reference< XInterface >& _rxForm ) { OBoundControlModel::onConnectedDbColumn( _rxForm ); Reference<XPropertySet> xField = getField(); if (xField.is()) { m_bDateTimeField = sal_False; try { sal_Int32 nFieldType = 0; xField->getPropertyValue(PROPERTY_FIELDTYPE) >>= nFieldType; m_bDateTimeField = (nFieldType == DataType::TIMESTAMP); } catch(Exception&) { } } } //------------------------------------------------------------------------------ sal_Bool ODateModel::commitControlValueToDbColumn( bool /*_bPostReset*/ ) { Any aControlValue( m_xAggregateFastSet->getFastPropertyValue( getValuePropertyAggHandle() ) ); if ( !compare( aControlValue, m_aSaveValue ) ) { if ( !aControlValue.hasValue() ) m_xColumnUpdate->updateNull(); else { try { util::Date aDate; if ( !( aControlValue >>= aDate ) ) { sal_Int32 nAsInt(0); aControlValue >>= nAsInt; aDate = DBTypeConversion::toDate(nAsInt); } if ( !m_bDateTimeField ) m_xColumnUpdate->updateDate( aDate ); else { util::DateTime aDateTime = m_xColumn->getTimestamp(); aDateTime.Day = aDate.Day; aDateTime.Month = aDate.Month; aDateTime.Year = aDate.Year; m_xColumnUpdate->updateTimestamp( aDateTime ); } } catch(Exception&) { return sal_False; } } m_aSaveValue = aControlValue; } return sal_True; } //------------------------------------------------------------------------------ void ODateModel::impl_translateControlValueToUNODate( Any& _rUNOValue ) const { _rUNOValue = getControlValue(); if ( _rUNOValue.hasValue() ) { sal_Int32 nDate = 0; OSL_VERIFY( _rUNOValue >>= nDate ); _rUNOValue <<= DBTypeConversion::toDate( nDate ); } } //------------------------------------------------------------------------------ Any ODateModel::translateControlValueToExternalValue( ) const { Any aExternalValue; impl_translateControlValueToUNODate( aExternalValue ); return aExternalValue; } //------------------------------------------------------------------------------ Any ODateModel::translateExternalValueToControlValue( ) const { OSL_PRECOND( hasExternalValueBinding(), "ODateModel::translateExternalValueToControlValue: precondition not met!" ); Any aControlValue; if ( hasExternalValueBinding() ) { Any aExternalValue = getExternalValueBinding()->getValue( ::getCppuType( static_cast< util::Date* >( NULL ) ) ); if ( aExternalValue.hasValue() ) { util::Date aDate; OSL_VERIFY( aExternalValue >>= aDate ); aControlValue <<= DBTypeConversion::toINT32( aDate ); } } return aControlValue; } //------------------------------------------------------------------------------ Any ODateModel::translateControlValueToValidatableValue( ) const { Any aValidatableValue; impl_translateControlValueToUNODate( aValidatableValue ); return aValidatableValue; } //------------------------------------------------------------------------------ Any ODateModel::translateDbColumnToControlValue() { util::Date aDate = m_xColumn->getDate(); if (m_xColumn->wasNull()) m_aSaveValue.clear(); else // the aggregated set expects an Int32 as value ... m_aSaveValue <<= DBTypeConversion::toINT32(aDate); return m_aSaveValue; } //------------------------------------------------------------------------------ Any ODateModel::getDefaultForReset() const { return m_aDefault; } //------------------------------------------------------------------------------ sal_Bool ODateModel::approveValueBinding( const Reference< binding::XValueBinding >& _rxBinding ) { OSL_PRECOND( _rxBinding.is(), "ODateModel::approveValueBinding: invalid binding!" ); return _rxBinding.is() && _rxBinding->supportsType( ::getCppuType( static_cast< util::Date* >( NULL ) ) ); } //......................................................................... } // namespace frm //......................................................................... <|endoftext|>
<commit_before>#include "styleParam.h" #include "platform.h" #include "util/builders.h" // for cap, join #include "util/geom.h" // for CLAMP #include <map> namespace Tangram { const std::map<std::string, StyleParamKey> s_StyleParamMap = { {"cap", StyleParamKey::cap}, {"color", StyleParamKey::color}, {"extrude", StyleParamKey::extrude}, {"font:family", StyleParamKey::font_family}, {"font:fill", StyleParamKey::font_fill}, {"font:size", StyleParamKey::font_size}, {"font:stroke", StyleParamKey::font_stroke}, {"font:stroke_color", StyleParamKey::font_stroke_color}, {"font:stroke_width", StyleParamKey::font_stroke_width}, {"font:style", StyleParamKey::font_style}, {"font:weight", StyleParamKey::font_weight}, {"join", StyleParamKey::join}, {"none", StyleParamKey::none}, {"offset", StyleParamKey::offset}, {"order", StyleParamKey::order}, {"outline:cap", StyleParamKey::outline_cap}, {"outline:color", StyleParamKey::outline_color}, {"outline:join", StyleParamKey::outline_join}, {"outline:width", StyleParamKey::outline_width}, {"priority", StyleParamKey::priority}, {"sprite", StyleParamKey::sprite}, {"transform", StyleParamKey::transform}, {"visible", StyleParamKey::visible}, {"width", StyleParamKey::width}, }; static const char* keyName(StyleParamKey key) { static std::string empty = ""; for (const auto& entry : s_StyleParamMap) { if (entry.second == key) { return entry.first.c_str(); } } return empty.c_str(); } StyleParam::StyleParam(const std::string& _key, const std::string& _value) { auto it = s_StyleParamMap.find(_key); if (it == s_StyleParamMap.end()) { logMsg("Unknown StyleParam %s:%s\n", _key.c_str(), _value.c_str()); key = StyleParamKey::none; value = none_type{}; return; } key = it->second; value = parseString(key, _value); } StyleParam::Value StyleParam::parseString(StyleParamKey key, const std::string& _value) { switch (key) { case StyleParamKey::extrude: { if (_value == "true") { return glm::vec2(NAN, NAN); } if (_value == "false") { return glm::vec2(0, 0) ; } auto vec2 = glm::vec2(NAN, NAN); if (!parseVec2(_value, {"m", "px"}, vec2)) { logMsg("Warning: Badly formed extrude parameter %s.\n", _value.c_str()); } return vec2; } case StyleParamKey::offset: { auto vec2 = glm::vec2(0.f, 0.f); if (!parseVec2(_value, {"px"}, vec2)) { logMsg("Warning: Badly formed offset parameter %s.\n", _value.c_str()); } return vec2; } case StyleParamKey::font_family: case StyleParamKey::font_weight: case StyleParamKey::font_style: case StyleParamKey::transform: case StyleParamKey::sprite: return _value; case StyleParamKey::font_size: { float fontSize = 16; if (!parseFontSize(_value, fontSize)) { logMsg("Warning: Invalid font-size '%s'.\n", _value.c_str()); } return fontSize; } case StyleParamKey::visible: if (_value == "true") { return true; } if (_value == "false") { return false; } logMsg("Warning: Bool value required for capitalized/visible. Using Default."); break; case StyleParamKey::order: case StyleParamKey::priority: { try { return static_cast<uint32_t>(std::stoi(_value)); } catch (std::invalid_argument) { } catch (std::out_of_range) {} logMsg("Warning: Not an Integer '%s', key: '%s'", _value.c_str(), keyName(key)); break; } case StyleParamKey::width: case StyleParamKey::outline_width: case StyleParamKey::font_stroke_width: { try { return static_cast<float>(std::stof(_value)); } catch (std::invalid_argument) { } catch (std::out_of_range) {} logMsg("Warning: Not a Float '%s', key: '%s'", _value.c_str(), keyName(key)); break; } case StyleParamKey::color: case StyleParamKey::outline_color: case StyleParamKey::font_fill: case StyleParamKey::font_stroke: case StyleParamKey::font_stroke_color: return parseColor(_value); case StyleParamKey::cap: case StyleParamKey::outline_cap: return static_cast<uint32_t>(CapTypeFromString(_value)); case StyleParamKey::join: case StyleParamKey::outline_join: return static_cast<uint32_t>(JoinTypeFromString(_value)); case StyleParamKey::none: break; } return none_type{}; } std::string StyleParam::toString() const { std::string k(keyName(key)); k += " : "; // TODO: cap, join and color toString() if (value.is<none_type>()) { return k + "undefined"; } switch (key) { case StyleParamKey::extrude: { if (!value.is<glm::vec2>()) break; auto p = value.get<glm::vec2>(); return k + "(" + std::to_string(p[0]) + ", " + std::to_string(p[1]) + ")"; } case StyleParamKey::offset: { if (!value.is<glm::vec2>()) break; auto p = value.get<glm::vec2>(); return "offset : (" + std::to_string(p.x) + "px, " + std::to_string(p.y) + "px)"; } case StyleParamKey::font_family: case StyleParamKey::font_weight: case StyleParamKey::font_style: case StyleParamKey::transform: case StyleParamKey::sprite: if (!value.is<std::string>()) break; return k + value.get<std::string>(); case StyleParamKey::visible: if (!value.is<bool>()) break; return k + std::to_string(value.get<bool>()); case StyleParamKey::width: case StyleParamKey::outline_width: case StyleParamKey::font_stroke_width: case StyleParamKey::font_size: if (!value.is<float>()) break; return k + std::to_string(value.get<float>()); case StyleParamKey::order: case StyleParamKey::priority: case StyleParamKey::color: case StyleParamKey::outline_color: case StyleParamKey::font_fill: case StyleParamKey::font_stroke: case StyleParamKey::font_stroke_color: case StyleParamKey::cap: case StyleParamKey::outline_cap: case StyleParamKey::join: case StyleParamKey::outline_join: if (!value.is<uint32_t>()) break; return k + std::to_string(value.get<uint32_t>()); case StyleParamKey::none: break; } return k + "undefined"; } bool StyleParam::parseVec2(const std::string& _value, const std::vector<std::string>& _allowedUnit, glm::vec2& _vec2) { if (_value.empty()) { return false; } std::string value = _value; // replace all unit occurences for (auto& unit : _allowedUnit) { auto i = value.find(unit); // TODO: conversion while (i != std::string::npos) { value.replace(i, unit.size(), ""); i = value.find(unit); } } std::replace(value.begin(), value.end(), ',', ' '); if (std::any_of(value.begin(), value.end(), ::isalpha)) { return false; } float f1, f2; int num = std::sscanf(value.c_str(), "%f %f", &f1, &f2); switch(num) { case 1: _vec2 = { f1, NAN }; break; case 2: _vec2 = { f1, f2 }; break; case 0: default: return false; } return true; } uint32_t StyleParam::parseColor(const std::string& _color) { Color color; if (isdigit(_color.front())) { // try to parse as comma-separated rgba components float r, g, b, a = 1.; if (sscanf(_color.c_str(), "%f,%f,%f,%f", &r, &g, &b, &a) >= 3) { color = Color { static_cast<uint8_t>(CLAMP((r * 255.), 0, 255)), static_cast<uint8_t>(CLAMP((g * 255.), 0, 255)), static_cast<uint8_t>(CLAMP((b * 255.), 0, 255)), CLAMP(a, 0, 1) }; } } else { // parse as css color or #hex-num color = CSSColorParser::parse(_color); } return color.getInt(); } bool StyleParam::parseFontSize(const std::string& _str, float& _pxSize) { if (_str.empty()) { return false; } size_t index = 0; std::string kind; try { _pxSize = std::stof(_str, &index); } catch (std::invalid_argument) { return false; } catch (std::out_of_range) { return false; } if (index == _str.length() && (_str.find('.') == std::string::npos)) { return true; } kind = _str.substr(index, _str.length() - 1); if (kind == "px") { // px may not be fractional value if (_str.find('.') != std::string::npos) return false; } else if (kind == "em") { _pxSize *= 16.f; } else if (kind == "pt") { _pxSize /= 0.75f; } else if (kind == "%") { _pxSize /= 6.25f; } else { return false; } return true; } } <commit_msg>Missing <algorithm> include<commit_after>#include "styleParam.h" #include "platform.h" #include "util/builders.h" // for cap, join #include "util/geom.h" // for CLAMP #include <algorithm> #include <map> namespace Tangram { const std::map<std::string, StyleParamKey> s_StyleParamMap = { {"cap", StyleParamKey::cap}, {"color", StyleParamKey::color}, {"extrude", StyleParamKey::extrude}, {"font:family", StyleParamKey::font_family}, {"font:fill", StyleParamKey::font_fill}, {"font:size", StyleParamKey::font_size}, {"font:stroke", StyleParamKey::font_stroke}, {"font:stroke_color", StyleParamKey::font_stroke_color}, {"font:stroke_width", StyleParamKey::font_stroke_width}, {"font:style", StyleParamKey::font_style}, {"font:weight", StyleParamKey::font_weight}, {"join", StyleParamKey::join}, {"none", StyleParamKey::none}, {"offset", StyleParamKey::offset}, {"order", StyleParamKey::order}, {"outline:cap", StyleParamKey::outline_cap}, {"outline:color", StyleParamKey::outline_color}, {"outline:join", StyleParamKey::outline_join}, {"outline:width", StyleParamKey::outline_width}, {"priority", StyleParamKey::priority}, {"sprite", StyleParamKey::sprite}, {"transform", StyleParamKey::transform}, {"visible", StyleParamKey::visible}, {"width", StyleParamKey::width}, }; static const char* keyName(StyleParamKey key) { static std::string empty = ""; for (const auto& entry : s_StyleParamMap) { if (entry.second == key) { return entry.first.c_str(); } } return empty.c_str(); } StyleParam::StyleParam(const std::string& _key, const std::string& _value) { auto it = s_StyleParamMap.find(_key); if (it == s_StyleParamMap.end()) { logMsg("Unknown StyleParam %s:%s\n", _key.c_str(), _value.c_str()); key = StyleParamKey::none; value = none_type{}; return; } key = it->second; value = parseString(key, _value); } StyleParam::Value StyleParam::parseString(StyleParamKey key, const std::string& _value) { switch (key) { case StyleParamKey::extrude: { if (_value == "true") { return glm::vec2(NAN, NAN); } if (_value == "false") { return glm::vec2(0, 0) ; } auto vec2 = glm::vec2(NAN, NAN); if (!parseVec2(_value, {"m", "px"}, vec2)) { logMsg("Warning: Badly formed extrude parameter %s.\n", _value.c_str()); } return vec2; } case StyleParamKey::offset: { auto vec2 = glm::vec2(0.f, 0.f); if (!parseVec2(_value, {"px"}, vec2)) { logMsg("Warning: Badly formed offset parameter %s.\n", _value.c_str()); } return vec2; } case StyleParamKey::font_family: case StyleParamKey::font_weight: case StyleParamKey::font_style: case StyleParamKey::transform: case StyleParamKey::sprite: return _value; case StyleParamKey::font_size: { float fontSize = 16; if (!parseFontSize(_value, fontSize)) { logMsg("Warning: Invalid font-size '%s'.\n", _value.c_str()); } return fontSize; } case StyleParamKey::visible: if (_value == "true") { return true; } if (_value == "false") { return false; } logMsg("Warning: Bool value required for capitalized/visible. Using Default."); break; case StyleParamKey::order: case StyleParamKey::priority: { try { return static_cast<uint32_t>(std::stoi(_value)); } catch (std::invalid_argument) { } catch (std::out_of_range) {} logMsg("Warning: Not an Integer '%s', key: '%s'", _value.c_str(), keyName(key)); break; } case StyleParamKey::width: case StyleParamKey::outline_width: case StyleParamKey::font_stroke_width: { try { return static_cast<float>(std::stof(_value)); } catch (std::invalid_argument) { } catch (std::out_of_range) {} logMsg("Warning: Not a Float '%s', key: '%s'", _value.c_str(), keyName(key)); break; } case StyleParamKey::color: case StyleParamKey::outline_color: case StyleParamKey::font_fill: case StyleParamKey::font_stroke: case StyleParamKey::font_stroke_color: return parseColor(_value); case StyleParamKey::cap: case StyleParamKey::outline_cap: return static_cast<uint32_t>(CapTypeFromString(_value)); case StyleParamKey::join: case StyleParamKey::outline_join: return static_cast<uint32_t>(JoinTypeFromString(_value)); case StyleParamKey::none: break; } return none_type{}; } std::string StyleParam::toString() const { std::string k(keyName(key)); k += " : "; // TODO: cap, join and color toString() if (value.is<none_type>()) { return k + "undefined"; } switch (key) { case StyleParamKey::extrude: { if (!value.is<glm::vec2>()) break; auto p = value.get<glm::vec2>(); return k + "(" + std::to_string(p[0]) + ", " + std::to_string(p[1]) + ")"; } case StyleParamKey::offset: { if (!value.is<glm::vec2>()) break; auto p = value.get<glm::vec2>(); return "offset : (" + std::to_string(p.x) + "px, " + std::to_string(p.y) + "px)"; } case StyleParamKey::font_family: case StyleParamKey::font_weight: case StyleParamKey::font_style: case StyleParamKey::transform: case StyleParamKey::sprite: if (!value.is<std::string>()) break; return k + value.get<std::string>(); case StyleParamKey::visible: if (!value.is<bool>()) break; return k + std::to_string(value.get<bool>()); case StyleParamKey::width: case StyleParamKey::outline_width: case StyleParamKey::font_stroke_width: case StyleParamKey::font_size: if (!value.is<float>()) break; return k + std::to_string(value.get<float>()); case StyleParamKey::order: case StyleParamKey::priority: case StyleParamKey::color: case StyleParamKey::outline_color: case StyleParamKey::font_fill: case StyleParamKey::font_stroke: case StyleParamKey::font_stroke_color: case StyleParamKey::cap: case StyleParamKey::outline_cap: case StyleParamKey::join: case StyleParamKey::outline_join: if (!value.is<uint32_t>()) break; return k + std::to_string(value.get<uint32_t>()); case StyleParamKey::none: break; } return k + "undefined"; } bool StyleParam::parseVec2(const std::string& _value, const std::vector<std::string>& _allowedUnit, glm::vec2& _vec2) { if (_value.empty()) { return false; } std::string value = _value; // replace all unit occurences for (auto& unit : _allowedUnit) { auto i = value.find(unit); // TODO: conversion while (i != std::string::npos) { value.replace(i, unit.size(), ""); i = value.find(unit); } } std::replace(value.begin(), value.end(), ',', ' '); if (std::any_of(value.begin(), value.end(), ::isalpha)) { return false; } float f1, f2; int num = std::sscanf(value.c_str(), "%f %f", &f1, &f2); switch(num) { case 1: _vec2 = { f1, NAN }; break; case 2: _vec2 = { f1, f2 }; break; case 0: default: return false; } return true; } uint32_t StyleParam::parseColor(const std::string& _color) { Color color; if (isdigit(_color.front())) { // try to parse as comma-separated rgba components float r, g, b, a = 1.; if (sscanf(_color.c_str(), "%f,%f,%f,%f", &r, &g, &b, &a) >= 3) { color = Color { static_cast<uint8_t>(CLAMP((r * 255.), 0, 255)), static_cast<uint8_t>(CLAMP((g * 255.), 0, 255)), static_cast<uint8_t>(CLAMP((b * 255.), 0, 255)), CLAMP(a, 0, 1) }; } } else { // parse as css color or #hex-num color = CSSColorParser::parse(_color); } return color.getInt(); } bool StyleParam::parseFontSize(const std::string& _str, float& _pxSize) { if (_str.empty()) { return false; } size_t index = 0; std::string kind; try { _pxSize = std::stof(_str, &index); } catch (std::invalid_argument) { return false; } catch (std::out_of_range) { return false; } if (index == _str.length() && (_str.find('.') == std::string::npos)) { return true; } kind = _str.substr(index, _str.length() - 1); if (kind == "px") { // px may not be fractional value if (_str.find('.') != std::string::npos) return false; } else if (kind == "em") { _pxSize *= 16.f; } else if (kind == "pt") { _pxSize /= 0.75f; } else if (kind == "%") { _pxSize /= 6.25f; } else { return false; } return true; } } <|endoftext|>
<commit_before>// $Id$ /* Copyright (c) 2007-2011, Trustees of The Leland Stanford Junior University 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 Stanford University 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. */ ////////////////////////////////////////////////////////////////////// // // File Name: channel.hpp // // The Channel models a generic channel with a multi-cycle // transmission delay. The channel latency can be specified as // an integer number of simulator cycles. // ///// #ifndef _CHANNEL_HPP #define _CHANNEL_HPP #include <queue> #include <cassert> #include "globals.hpp" #include "module.hpp" #include "timed_module.hpp" using namespace std; template<typename T> class Channel : public TimedModule { public: Channel(Module * parent, string const & name); virtual ~Channel() {} // Physical Parameters void SetLatency(int cycles); int GetLatency() const { return _delay ; } // Send data virtual void Send(T * data); // Receive data virtual T * Receive(); virtual void ReadInputs(); virtual void Evaluate() {} virtual void WriteOutputs(); protected: int _delay; T * _input; T * _output; queue<pair<int, T *> > _wait_queue; }; template<typename T> Channel<T>::Channel(Module * parent, string const & name) : TimedModule(parent, name), _delay(1), _input(0), _output(0) { } template<typename T> void Channel<T>::SetLatency(int cycles) { if(!cycles) { Error("Channel must have positive delay."); } _delay = cycles ; } template<typename T> void Channel<T>::Send(T * data) { _input = data; } template<typename T> T * Channel<T>::Receive() { return _output; } template<typename T> void Channel<T>::ReadInputs() { if(_input) { _wait_queue.push(make_pair(GetSimTime() + _delay - 1, _input)); _input = 0; } } template<typename T> void Channel<T>::WriteOutputs() { _output = 0; if(_wait_queue.empty()) { return; } pair<int, T *> const & item = _wait_queue.front(); int const & time = item.first; if(GetSimTime() < time) { return; } assert(GetSimTime() == time); _wait_queue.pop(); _output = item.second; assert(_output); } #endif <commit_msg>channel write output, element is popped before assignment, rare occasion causes segfault<commit_after>// $Id$ /* Copyright (c) 2007-2011, Trustees of The Leland Stanford Junior University 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 Stanford University 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. */ ////////////////////////////////////////////////////////////////////// // // File Name: channel.hpp // // The Channel models a generic channel with a multi-cycle // transmission delay. The channel latency can be specified as // an integer number of simulator cycles. // ///// #ifndef _CHANNEL_HPP #define _CHANNEL_HPP #include <queue> #include <cassert> #include "globals.hpp" #include "module.hpp" #include "timed_module.hpp" using namespace std; template<typename T> class Channel : public TimedModule { public: Channel(Module * parent, string const & name); virtual ~Channel() {} // Physical Parameters void SetLatency(int cycles); int GetLatency() const { return _delay ; } // Send data virtual void Send(T * data); // Receive data virtual T * Receive(); virtual void ReadInputs(); virtual void Evaluate() {} virtual void WriteOutputs(); protected: int _delay; T * _input; T * _output; queue<pair<int, T *> > _wait_queue; }; template<typename T> Channel<T>::Channel(Module * parent, string const & name) : TimedModule(parent, name), _delay(1), _input(0), _output(0) { } template<typename T> void Channel<T>::SetLatency(int cycles) { if(!cycles) { Error("Channel must have positive delay."); } _delay = cycles ; } template<typename T> void Channel<T>::Send(T * data) { _input = data; } template<typename T> T * Channel<T>::Receive() { return _output; } template<typename T> void Channel<T>::ReadInputs() { if(_input) { _wait_queue.push(make_pair(GetSimTime() + _delay - 1, _input)); _input = 0; } } template<typename T> void Channel<T>::WriteOutputs() { _output = 0; if(_wait_queue.empty()) { return; } pair<int, T *> const & item = _wait_queue.front(); int const & time = item.first; if(GetSimTime() < time) { return; } assert(GetSimTime() == time); _output = item.second; _wait_queue.pop(); assert(_output); } #endif <|endoftext|>
<commit_before>#include "tileManager.h" #include "data/dataSource.h" #include "platform.h" #include "scene/scene.h" #include "tile/mapTile.h" #include "view/view.h" #include "glm/gtx/norm.hpp" #include <chrono> #include <algorithm> TileManager::TileManager() : m_loadPending(0) { // Instantiate workers for (size_t i = 0; i < MAX_WORKERS; i++) { m_workers.push_back(std::unique_ptr<TileWorker>(new TileWorker(*this))); } m_dataCallback = std::bind(&TileManager::tileLoaded, this, std::placeholders::_1); } TileManager::~TileManager() { for (auto& worker : m_workers) { if (worker->isRunning()) { worker->abort(); worker->drain(); } // We stop all workers before we destroy the resources they use. // TODO: This will wait for any pending network requests to finish, // which could delay closing of the application. } m_dataSources.clear(); m_tileSet.clear(); } void TileManager::addDataSource(std::unique_ptr<DataSource> _source) { m_dataSources.push_back(std::move(_source)); } void TileManager::tileLoaded(TileTask task) { std::lock_guard<std::mutex> lock(m_queueTileMutex); m_queuedTiles.push_back(std::move(task)); } void TileManager::tileProcessed(TileTask task) { std::lock_guard<std::mutex> lock(m_readyTileMutex); m_readyTiles.push_back(std::move(task)); } TileTask TileManager::pollProcessQueue() { std::lock_guard<std::mutex> lock(m_queueTileMutex); while (!m_queuedTiles.empty()) { auto task = std::move(m_queuedTiles.front()); m_queuedTiles.pop_front(); if (!setTileState(*(task->tile), TileState::processing)) { // Drop canceled task. continue; } return task; } return TileTask(nullptr); } bool TileManager::setTileState(MapTile& tile, TileState state) { std::lock_guard<std::mutex> lock(m_tileStateMutex); switch (tile.state()) { case TileState::none: if (state == TileState::loading) { tile.setState(state); m_loadPending++; return true; } break; case TileState::loading: if (state == TileState::processing) { tile.setState(state); m_loadPending--; return true; } if (state == TileState::canceled) { tile.setState(state); m_loadPending--; return true; } break; case TileState::processing: if (state == TileState::ready) { tile.setState(state); return true; } break; case TileState::canceled: return false; default: break; } if (state == TileState::canceled) { return false; } logMsg("Wrong state change %d -> %d<<<", tile.state(), state); assert(false); } void TileManager::enqueueLoadTask(const TileID& tileID, const glm::dvec2& viewCenter) { // Keep the items sorted by distance and limit list to MAX_DOWNLOADS auto tileCenter = m_view->getMapProjection().TileCenter(tileID); double distance = glm::length2(tileCenter - viewCenter); bool isFull = m_loadTasks.size() == MAX_DOWNLOADS; if (isFull && m_loadTasks.back().first < distance) { return; } auto iter = m_loadTasks.begin(); while (iter != m_loadTasks.end()){ if (iter->first > distance) { break; } ++iter; } if (!isFull || iter != m_loadTasks.end()) { m_loadTasks.insert(iter, { distance, &tileID }); } if (isFull) { m_loadTasks.pop_back(); } } void TileManager::updateTileSet() { m_tileSetChanged = false; // Check if any native worker needs to be dispatched. if (!m_queuedTiles.empty()) { for (auto& worker : m_workers) { if (worker->isRunning()) { continue; } worker->process(m_scene->getStyles()); } } if (!m_readyTiles.empty()) { std::lock_guard<std::mutex> lock(m_readyTileMutex); auto it = m_readyTiles.begin(); while (it != m_readyTiles.end()) { auto& task = *it; auto& tile = *(task->tile); if (setTileState(tile, TileState::ready)) { cleanProxyTiles(tile); m_tileSetChanged = true; } it = m_readyTiles.erase(it); } } if (m_view->changedOnLastUpdate() || m_tileSetChanged) { glm::dvec2 viewCenter(m_view->getPosition().x, -m_view->getPosition().y); const std::set<TileID>& visibleTiles = m_view->getVisibleTiles(); // Loop over visibleTiles and add any needed tiles to tileSet { auto setTilesIter = m_tileSet.begin(); auto visTilesIter = visibleTiles.begin(); while (visTilesIter != visibleTiles.end()) { auto& visTileId = *visTilesIter; auto& curTileId = setTilesIter == m_tileSet.end() ? NOT_A_TILE : setTilesIter->first; if (visTileId == curTileId) { if (setTilesIter->second->state() == TileState::none) { //logMsg("[%d, %d, %d] - Enqueue\n", curTileId.z, curTileId.x, curTileId.y); enqueueLoadTask(visTileId, viewCenter); } // tiles in both sets match ++setTilesIter; ++visTilesIter; } else if (curTileId == NOT_A_TILE || visTileId < curTileId) { // tileSet is missing an element present in visibleTiles addTile(visTileId); enqueueLoadTask(visTileId, viewCenter); ++visTilesIter; } else { // visibleTiles is missing an element present in tileSet (handled below) ++setTilesIter; } } } // Loop over tileSet and remove any tiles that are neither visible nor proxies { auto setTilesIter = m_tileSet.begin(); auto visTilesIter = visibleTiles.begin(); while (setTilesIter != m_tileSet.end()) { auto& visTileId = visTilesIter == visibleTiles.end() ? NOT_A_TILE : *visTilesIter; auto& curTileId = setTilesIter->first; if (visTileId == curTileId) { // tiles in both sets match ++setTilesIter; ++visTilesIter; } else if (visTileId == NOT_A_TILE || curTileId < visTileId) { // remove element from tileSet not present in visibleTiles const auto& tile = setTilesIter->second; if (tile->getProxyCounter() <= 0) { removeTile(setTilesIter); } else { ++setTilesIter; } } else { // tileSet is missing an element present in visibleTiles (shouldn't occur) ++visTilesIter; } } } } if (m_loadPending < MAX_DOWNLOADS) { for (auto& item : m_loadTasks) { auto& id = *item.second; auto& tile = m_tileSet[id]; setTileState(*tile, TileState::loading); for (auto& source : m_dataSources) { TileTask task = std::make_shared<TileTaskData>(tile, source.get()); logMsg("[%d, %d, %d] Load\n", id.z, id.x, id.y); if (!source->loadTileData(task, m_dataCallback)) { logMsg("ERROR: Loading failed for tile [%d, %d, %d]\n", id.z, id.x, id.y); } } if (m_loadPending == MAX_DOWNLOADS) { break; } } } m_loadTasks.clear(); // logMsg("all:%d loading:%d processing:%d pending:%d\n", // m_tileSet.size(), m_loadTasks.size(), // m_queuedTiles.size(), m_loadPending); } void TileManager::addTile(const TileID& _tileID) { logMsg("[%d, %d, %d] Add\n", _tileID.z, _tileID.x, _tileID.y); std::shared_ptr<MapTile> tile(new MapTile(_tileID, m_view->getMapProjection())); //Add Proxy if corresponding proxy MapTile ready updateProxyTiles(*tile); m_tileSet[_tileID] = std::move(tile); } void TileManager::removeTile(std::map< TileID, std::shared_ptr<MapTile> >::iterator& _tileIter) { const TileID& id = _tileIter->first; auto& tile = _tileIter->second; logMsg("[%d, %d, %d] Remove\n", id.z, id.x, id.y); if (setTileState(*tile, TileState::canceled)) { // 1. Remove from Datasource // Make sure to cancel the network request associated with this tile. for(auto& dataSource : m_dataSources) { dataSource->cancelLoadingTile(id); } } cleanProxyTiles(*tile); // Remove tile from set _tileIter = m_tileSet.erase(_tileIter); } void TileManager::updateProxyTiles(MapTile& _tile) { const TileID& _tileID = _tile.getID(); const auto& parentID = _tileID.getParent(); const auto& parentTileIter = m_tileSet.find(parentID); if (parentTileIter != m_tileSet.end()) { auto& parent = parentTileIter->second; if (_tile.setProxy(MapTile::parent)) { parent->incProxyCounter(); } return; } if (m_view->s_maxZoom > _tileID.z) { for(int i = 0; i < 4; i++) { const auto& childID = _tileID.getChild(i); const auto& childTileIter = m_tileSet.find(childID); if(childTileIter != m_tileSet.end()) { if (_tile.setProxy((MapTile::ProxyID)(1 << i))) { childTileIter->second->incProxyCounter(); } } } } } void TileManager::cleanProxyTiles(MapTile& _tile) { const TileID& _tileID = _tile.getID(); // check if parent proxy is present if (_tile.hasProxy(MapTile::parent)) { const auto& parentID = _tileID.getParent(); const auto& parentTileIter = m_tileSet.find(parentID); if (parentTileIter != m_tileSet.end()) { parentTileIter->second->decProxyCounter(); } } // check if child proxies are present for(int i = 0; i < 4; i++) { if (_tile.hasProxy((MapTile::ProxyID)(1 << i))) { const auto& childID = _tileID.getChild(i); const auto& childTileIter = m_tileSet.find(childID); if (childTileIter != m_tileSet.end()) { childTileIter->second->decProxyCounter(); } } } _tile.clearProxies(); } <commit_msg>--warning<commit_after>#include "tileManager.h" #include "data/dataSource.h" #include "platform.h" #include "scene/scene.h" #include "tile/mapTile.h" #include "view/view.h" #include "glm/gtx/norm.hpp" #include <chrono> #include <algorithm> TileManager::TileManager() : m_loadPending(0) { // Instantiate workers for (size_t i = 0; i < MAX_WORKERS; i++) { m_workers.push_back(std::unique_ptr<TileWorker>(new TileWorker(*this))); } m_dataCallback = std::bind(&TileManager::tileLoaded, this, std::placeholders::_1); } TileManager::~TileManager() { for (auto& worker : m_workers) { if (worker->isRunning()) { worker->abort(); worker->drain(); } // We stop all workers before we destroy the resources they use. // TODO: This will wait for any pending network requests to finish, // which could delay closing of the application. } m_dataSources.clear(); m_tileSet.clear(); } void TileManager::addDataSource(std::unique_ptr<DataSource> _source) { m_dataSources.push_back(std::move(_source)); } void TileManager::tileLoaded(TileTask task) { std::lock_guard<std::mutex> lock(m_queueTileMutex); m_queuedTiles.push_back(std::move(task)); } void TileManager::tileProcessed(TileTask task) { std::lock_guard<std::mutex> lock(m_readyTileMutex); m_readyTiles.push_back(std::move(task)); } TileTask TileManager::pollProcessQueue() { std::lock_guard<std::mutex> lock(m_queueTileMutex); while (!m_queuedTiles.empty()) { auto task = std::move(m_queuedTiles.front()); m_queuedTiles.pop_front(); if (!setTileState(*(task->tile), TileState::processing)) { // Drop canceled task. continue; } return task; } return TileTask(nullptr); } bool TileManager::setTileState(MapTile& tile, TileState state) { std::lock_guard<std::mutex> lock(m_tileStateMutex); switch (tile.state()) { case TileState::none: if (state == TileState::loading) { tile.setState(state); m_loadPending++; return true; } break; case TileState::loading: if (state == TileState::processing) { tile.setState(state); m_loadPending--; return true; } if (state == TileState::canceled) { tile.setState(state); m_loadPending--; return true; } break; case TileState::processing: if (state == TileState::ready) { tile.setState(state); return true; } break; case TileState::canceled: return false; default: break; } if (state == TileState::canceled) { return false; } logMsg("Wrong state change %d -> %d<<<", tile.state(), state); assert(false); return false; // ... } void TileManager::enqueueLoadTask(const TileID& tileID, const glm::dvec2& viewCenter) { // Keep the items sorted by distance and limit list to MAX_DOWNLOADS auto tileCenter = m_view->getMapProjection().TileCenter(tileID); double distance = glm::length2(tileCenter - viewCenter); bool isFull = m_loadTasks.size() == MAX_DOWNLOADS; if (isFull && m_loadTasks.back().first < distance) { return; } auto iter = m_loadTasks.begin(); while (iter != m_loadTasks.end()){ if (iter->first > distance) { break; } ++iter; } if (!isFull || iter != m_loadTasks.end()) { m_loadTasks.insert(iter, { distance, &tileID }); } if (isFull) { m_loadTasks.pop_back(); } } void TileManager::updateTileSet() { m_tileSetChanged = false; // Check if any native worker needs to be dispatched. if (!m_queuedTiles.empty()) { for (auto& worker : m_workers) { if (worker->isRunning()) { continue; } worker->process(m_scene->getStyles()); } } if (!m_readyTiles.empty()) { std::lock_guard<std::mutex> lock(m_readyTileMutex); auto it = m_readyTiles.begin(); while (it != m_readyTiles.end()) { auto& task = *it; auto& tile = *(task->tile); if (setTileState(tile, TileState::ready)) { cleanProxyTiles(tile); m_tileSetChanged = true; } it = m_readyTiles.erase(it); } } if (m_view->changedOnLastUpdate() || m_tileSetChanged) { glm::dvec2 viewCenter(m_view->getPosition().x, -m_view->getPosition().y); const std::set<TileID>& visibleTiles = m_view->getVisibleTiles(); // Loop over visibleTiles and add any needed tiles to tileSet { auto setTilesIter = m_tileSet.begin(); auto visTilesIter = visibleTiles.begin(); while (visTilesIter != visibleTiles.end()) { auto& visTileId = *visTilesIter; auto& curTileId = setTilesIter == m_tileSet.end() ? NOT_A_TILE : setTilesIter->first; if (visTileId == curTileId) { if (setTilesIter->second->state() == TileState::none) { //logMsg("[%d, %d, %d] - Enqueue\n", curTileId.z, curTileId.x, curTileId.y); enqueueLoadTask(visTileId, viewCenter); } // tiles in both sets match ++setTilesIter; ++visTilesIter; } else if (curTileId == NOT_A_TILE || visTileId < curTileId) { // tileSet is missing an element present in visibleTiles addTile(visTileId); enqueueLoadTask(visTileId, viewCenter); ++visTilesIter; } else { // visibleTiles is missing an element present in tileSet (handled below) ++setTilesIter; } } } // Loop over tileSet and remove any tiles that are neither visible nor proxies { auto setTilesIter = m_tileSet.begin(); auto visTilesIter = visibleTiles.begin(); while (setTilesIter != m_tileSet.end()) { auto& visTileId = visTilesIter == visibleTiles.end() ? NOT_A_TILE : *visTilesIter; auto& curTileId = setTilesIter->first; if (visTileId == curTileId) { // tiles in both sets match ++setTilesIter; ++visTilesIter; } else if (visTileId == NOT_A_TILE || curTileId < visTileId) { // remove element from tileSet not present in visibleTiles const auto& tile = setTilesIter->second; if (tile->getProxyCounter() <= 0) { removeTile(setTilesIter); } else { ++setTilesIter; } } else { // tileSet is missing an element present in visibleTiles (shouldn't occur) ++visTilesIter; } } } } if (m_loadPending < MAX_DOWNLOADS) { for (auto& item : m_loadTasks) { auto& id = *item.second; auto& tile = m_tileSet[id]; setTileState(*tile, TileState::loading); for (auto& source : m_dataSources) { TileTask task = std::make_shared<TileTaskData>(tile, source.get()); logMsg("[%d, %d, %d] Load\n", id.z, id.x, id.y); if (!source->loadTileData(task, m_dataCallback)) { logMsg("ERROR: Loading failed for tile [%d, %d, %d]\n", id.z, id.x, id.y); } } if (m_loadPending == MAX_DOWNLOADS) { break; } } } m_loadTasks.clear(); // logMsg("all:%d loading:%d processing:%d pending:%d\n", // m_tileSet.size(), m_loadTasks.size(), // m_queuedTiles.size(), m_loadPending); } void TileManager::addTile(const TileID& _tileID) { logMsg("[%d, %d, %d] Add\n", _tileID.z, _tileID.x, _tileID.y); std::shared_ptr<MapTile> tile(new MapTile(_tileID, m_view->getMapProjection())); //Add Proxy if corresponding proxy MapTile ready updateProxyTiles(*tile); m_tileSet[_tileID] = std::move(tile); } void TileManager::removeTile(std::map< TileID, std::shared_ptr<MapTile> >::iterator& _tileIter) { const TileID& id = _tileIter->first; auto& tile = _tileIter->second; logMsg("[%d, %d, %d] Remove\n", id.z, id.x, id.y); if (setTileState(*tile, TileState::canceled)) { // 1. Remove from Datasource // Make sure to cancel the network request associated with this tile. for(auto& dataSource : m_dataSources) { dataSource->cancelLoadingTile(id); } } cleanProxyTiles(*tile); // Remove tile from set _tileIter = m_tileSet.erase(_tileIter); } void TileManager::updateProxyTiles(MapTile& _tile) { const TileID& _tileID = _tile.getID(); const auto& parentID = _tileID.getParent(); const auto& parentTileIter = m_tileSet.find(parentID); if (parentTileIter != m_tileSet.end()) { auto& parent = parentTileIter->second; if (_tile.setProxy(MapTile::parent)) { parent->incProxyCounter(); } return; } if (m_view->s_maxZoom > _tileID.z) { for(int i = 0; i < 4; i++) { const auto& childID = _tileID.getChild(i); const auto& childTileIter = m_tileSet.find(childID); if(childTileIter != m_tileSet.end()) { if (_tile.setProxy((MapTile::ProxyID)(1 << i))) { childTileIter->second->incProxyCounter(); } } } } } void TileManager::cleanProxyTiles(MapTile& _tile) { const TileID& _tileID = _tile.getID(); // check if parent proxy is present if (_tile.hasProxy(MapTile::parent)) { const auto& parentID = _tileID.getParent(); const auto& parentTileIter = m_tileSet.find(parentID); if (parentTileIter != m_tileSet.end()) { parentTileIter->second->decProxyCounter(); } } // check if child proxies are present for(int i = 0; i < 4; i++) { if (_tile.hasProxy((MapTile::ProxyID)(1 << i))) { const auto& childID = _tileID.getChild(i); const auto& childTileIter = m_tileSet.find(childID); if (childTileIter != m_tileSet.end()) { childTileIter->second->decProxyCounter(); } } } _tile.clearProxies(); } <|endoftext|>
<commit_before>/* * Copyright (C) 2003-2005 Tommi Maekitalo * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <tnt/httpparser.h> #include <tnt/httperror.h> #include <tnt/httpheader.h> #include <tnt/tntconfig.h> #include <cxxtools/log.h> #include <sstream> #include <algorithm> #define SET_STATE(new_state) state = &Parser::new_state namespace tnt { namespace { std::string chartoprint(char ch) { const static char hex[] = "0123456789abcdef"; if (std::isprint(ch)) return std::string(1, '\'') + ch + '\''; else return std::string("'\\x") + hex[(ch >> 4) & 0xf] + hex[ch & 0xf] + '\''; } inline bool istokenchar(char ch) { static const char s[] = "\"(),/:;<=>?@[\\]{}"; return std::isalpha(ch) || std::binary_search(s, s + sizeof(s) - 1, ch); } inline bool isHexDigit(char ch) { return (ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'F') || (ch >= 'a' && ch <= 'f'); } inline unsigned valueOfHexDigit(char ch) { return ch >= '0' && ch <= '9' ? ch - '0' : ch >= 'a' && ch <= 'z' ? ch - 'a' + 10 : ch >= 'A' && ch <= 'Z' ? ch - 'A' + 10 : 0; } } log_define("tntnet.httpmessage.parser") bool RequestSizeMonitor::post(bool ret) { if (++requestSize > TntConfig::it().maxRequestSize && TntConfig::it().maxRequestSize > 0) { requestSizeExceeded(); return true; } return ret; } void RequestSizeMonitor::requestSizeExceeded() { } void HttpRequest::Parser::reset() { message.clear(); SET_STATE(state_cmd0); httpCode = HTTP_OK; failedFlag = false; RequestSizeMonitor::reset(); headerParser.reset(); } bool HttpRequest::Parser::state_cmd0(char ch) { if (istokenchar(ch)) { message.method[0] = ch; message.methodLen = 1; SET_STATE(state_cmd); } else if (ch != ' ' && ch != '\t') { log_warn("invalid character " << chartoprint(ch) << " in method"); httpCode = HTTP_BAD_REQUEST; failedFlag = true; } return failedFlag; } bool HttpRequest::Parser::state_cmd(char ch) { if (istokenchar(ch)) { if (message.methodLen >= sizeof(message.method) - 1) { log_debug("invalid method field; method=" << std::string(message.method, message.methodLen) << ", len=" << message.methodLen); throw HttpError(HTTP_BAD_REQUEST, "invalid method field"); } message.method[message.methodLen++] = ch; } else if (ch == ' ') { message.method[message.methodLen] = '\0'; log_debug("method=" << message.method); SET_STATE(state_url0); } else { log_warn("invalid character " << chartoprint(ch) << " in method"); httpCode = HTTP_BAD_REQUEST; failedFlag = true; } return failedFlag; } bool HttpRequest::Parser::state_url0(char ch) { if (ch == ' ' || ch == '\t') { } else if (ch == '/') { message.url.clear(); message.url.reserve(32); message.url += ch; SET_STATE(state_url); } else if (std::isalpha(ch)) { SET_STATE(state_protocol); } else { log_warn("invalid character " << chartoprint(ch) << " in url"); httpCode = HTTP_BAD_REQUEST; failedFlag = true; } return failedFlag; } bool HttpRequest::Parser::state_protocol(char ch) { if (ch == ':') SET_STATE(state_protocol_slash1); else if (!std::isalpha(ch)) { log_warn("invalid character " << chartoprint(ch) << " in url"); httpCode = HTTP_BAD_REQUEST; failedFlag = true; } return failedFlag; } bool HttpRequest::Parser::state_protocol_slash1(char ch) { if (ch == '/') SET_STATE(state_protocol_slash2); else { log_warn("invalid character " << chartoprint(ch) << " in url"); httpCode = HTTP_BAD_REQUEST; failedFlag = true; } return failedFlag; } bool HttpRequest::Parser::state_protocol_slash2(char ch) { if (ch == '/') SET_STATE(state_protocol_host); else { log_warn("invalid character " << chartoprint(ch) << " in url"); httpCode = HTTP_BAD_REQUEST; failedFlag = true; } return failedFlag; } bool HttpRequest::Parser::state_protocol_host(char ch) { if (ch == '/') { message.url.clear(); message.url.reserve(32); message.url += ch; SET_STATE(state_url); } else if (!std::isalpha(ch) && !std::isdigit(ch) && ch != '[' && ch != ']' && ch != '.' && ch != ':') { log_warn("invalid character " << chartoprint(ch) << " in url"); httpCode = HTTP_BAD_REQUEST; failedFlag = true; } return failedFlag; } bool HttpRequest::Parser::state_url(char ch) { if (ch == '?') { log_debug("url=" << message.url); SET_STATE(state_qparam); } else if (ch == '\r') { log_debug("url=" << message.url); SET_STATE(state_end0); } else if (ch == '\n') { log_debug("url=" << message.url); SET_STATE(state_header); } else if (ch == ' ' || ch == '\t') { log_debug("url=" << message.url); SET_STATE(state_version); } else if (ch == '%') { SET_STATE(state_urlesc); message.url += ch; } else if (ch > ' ') message.url += ch; else { log_warn("invalid character " << chartoprint(ch) << " in url"); httpCode = HTTP_BAD_REQUEST; failedFlag = true; } return failedFlag; } bool HttpRequest::Parser::state_urlesc(char ch) { if (isHexDigit(ch)) { if (message.url.size() >= 2 && message.url[message.url.size() - 2] == '%') { unsigned v = (valueOfHexDigit(message.url[message.url.size() - 1]) << 4) | valueOfHexDigit(ch); message.url[message.url.size() - 2] = static_cast<char>(v); message.url.resize(message.url.size() - 1); SET_STATE(state_url); } else { message.url += ch; } return false; } else { SET_STATE(state_url); return state_url(ch); } } bool HttpRequest::Parser::state_qparam(char ch) { if (ch == ' ' || ch == '\t') { log_debug("queryString=" << message.queryString); SET_STATE(state_version); } else message.queryString += ch; return false; } bool HttpRequest::Parser::state_version(char ch) { if (ch == '/') { message.setVersion(0, 0); skipWs(&Parser::state_version_major); } else if (ch == '\r') { log_warn("invalid character " << chartoprint(ch) << " in version"); httpCode = HTTP_BAD_REQUEST; failedFlag = true; } return failedFlag; } bool HttpRequest::Parser::state_version_major(char ch) { if (ch == '.') SET_STATE(state_version_minor0); else if (std::isdigit(ch)) message.setVersion(message.getMajorVersion() * 10 + (ch - '0'), message.getMinorVersion()); else if (ch == ' ' || ch == '\t') SET_STATE(state_version_major_sp); else { log_warn("invalid character " << chartoprint(ch) << " in version-major"); httpCode = HTTP_BAD_REQUEST; failedFlag = true; } return failedFlag; } bool HttpRequest::Parser::state_version_major_sp(char ch) { if (ch == '.') SET_STATE(state_version_minor0); else { log_warn("invalid character " << chartoprint(ch) << " in version-major"); httpCode = HTTP_BAD_REQUEST; failedFlag = true; } return failedFlag; } bool HttpRequest::Parser::state_version_minor0(char ch) { return ch == ' ' || ch == '\t' ? failedFlag : state_version_minor(ch); } bool HttpRequest::Parser::state_version_minor(char ch) { if (ch == '\n') SET_STATE(state_header); else if (ch == ' ' || ch == '\t' || ch == '\r') SET_STATE(state_end0); else if (std::isdigit(ch)) message.setVersion(message.getMajorVersion(), message.getMinorVersion() * 10 + (ch - '0')); else { log_warn("invalid character " << chartoprint(ch) << " in version-minor"); httpCode = HTTP_BAD_REQUEST; failedFlag = true; } return failedFlag; } bool HttpRequest::Parser::state_end0(char ch) { if (ch == '\n') SET_STATE(state_header); else if (ch != ' ' && ch != '\t') { log_warn("invalid character " << chartoprint(ch) << " in end"); httpCode = HTTP_BAD_REQUEST; failedFlag = true; } return failedFlag; } bool HttpRequest::Parser::state_header(char ch) { if (headerParser.parse(ch)) { if (headerParser.failed()) { httpCode = HTTP_BAD_REQUEST; failedFlag = true; return true; } const char* content_length_header = message.getHeader(httpheader::contentLength); if (*content_length_header) { bodySize = 0; for (const char* c = content_length_header; *c; ++c) { if (*c > '9' || *c < '0') throw HttpError(HTTP_BAD_REQUEST, "invalid Content-Length"); bodySize = bodySize * 10 + *c - '0'; } if (TntConfig::it().maxRequestSize > 0 && getCurrentRequestSize() + bodySize > TntConfig::it().maxRequestSize) { requestSizeExceeded(); return true; } message.contentSize = bodySize; if (bodySize == 0) return true; else { SET_STATE(state_body); message.body.reserve(bodySize); return false; } } return true; } return false; } bool HttpRequest::Parser::state_body(char ch) { message.body += ch; return --bodySize == 0; } void HttpRequest::Parser::requestSizeExceeded() { log_warn("max request size " << TntConfig::it().maxRequestSize << " exceeded"); httpCode = HTTP_REQUEST_ENTITY_TOO_LARGE; failedFlag = true; } } <commit_msg>do not accept %00 in url since it is not processed correctly anyway<commit_after>/* * Copyright (C) 2003-2005 Tommi Maekitalo * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <tnt/httpparser.h> #include <tnt/httperror.h> #include <tnt/httpheader.h> #include <tnt/tntconfig.h> #include <cxxtools/log.h> #include <sstream> #include <algorithm> #define SET_STATE(new_state) state = &Parser::new_state namespace tnt { namespace { std::string chartoprint(char ch) { const static char hex[] = "0123456789abcdef"; if (std::isprint(ch)) return std::string(1, '\'') + ch + '\''; else return std::string("'\\x") + hex[(ch >> 4) & 0xf] + hex[ch & 0xf] + '\''; } inline bool istokenchar(char ch) { static const char s[] = "\"(),/:;<=>?@[\\]{}"; return std::isalpha(ch) || std::binary_search(s, s + sizeof(s) - 1, ch); } inline bool isHexDigit(char ch) { return (ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'F') || (ch >= 'a' && ch <= 'f'); } inline unsigned valueOfHexDigit(char ch) { return ch >= '0' && ch <= '9' ? ch - '0' : ch >= 'a' && ch <= 'z' ? ch - 'a' + 10 : ch >= 'A' && ch <= 'Z' ? ch - 'A' + 10 : 0; } } log_define("tntnet.httpmessage.parser") bool RequestSizeMonitor::post(bool ret) { if (++requestSize > TntConfig::it().maxRequestSize && TntConfig::it().maxRequestSize > 0) { requestSizeExceeded(); return true; } return ret; } void RequestSizeMonitor::requestSizeExceeded() { } void HttpRequest::Parser::reset() { message.clear(); SET_STATE(state_cmd0); httpCode = HTTP_OK; failedFlag = false; RequestSizeMonitor::reset(); headerParser.reset(); } bool HttpRequest::Parser::state_cmd0(char ch) { if (istokenchar(ch)) { message.method[0] = ch; message.methodLen = 1; SET_STATE(state_cmd); } else if (ch != ' ' && ch != '\t') { log_warn("invalid character " << chartoprint(ch) << " in method"); httpCode = HTTP_BAD_REQUEST; failedFlag = true; } return failedFlag; } bool HttpRequest::Parser::state_cmd(char ch) { if (istokenchar(ch)) { if (message.methodLen >= sizeof(message.method) - 1) { log_debug("invalid method field; method=" << std::string(message.method, message.methodLen) << ", len=" << message.methodLen); throw HttpError(HTTP_BAD_REQUEST, "invalid method field"); } message.method[message.methodLen++] = ch; } else if (ch == ' ') { message.method[message.methodLen] = '\0'; log_debug("method=" << message.method); SET_STATE(state_url0); } else { log_warn("invalid character " << chartoprint(ch) << " in method"); httpCode = HTTP_BAD_REQUEST; failedFlag = true; } return failedFlag; } bool HttpRequest::Parser::state_url0(char ch) { if (ch == ' ' || ch == '\t') { } else if (ch == '/') { message.url.clear(); message.url.reserve(32); message.url += ch; SET_STATE(state_url); } else if (std::isalpha(ch)) { SET_STATE(state_protocol); } else { log_warn("invalid character " << chartoprint(ch) << " in url"); httpCode = HTTP_BAD_REQUEST; failedFlag = true; } return failedFlag; } bool HttpRequest::Parser::state_protocol(char ch) { if (ch == ':') SET_STATE(state_protocol_slash1); else if (!std::isalpha(ch)) { log_warn("invalid character " << chartoprint(ch) << " in url"); httpCode = HTTP_BAD_REQUEST; failedFlag = true; } return failedFlag; } bool HttpRequest::Parser::state_protocol_slash1(char ch) { if (ch == '/') SET_STATE(state_protocol_slash2); else { log_warn("invalid character " << chartoprint(ch) << " in url"); httpCode = HTTP_BAD_REQUEST; failedFlag = true; } return failedFlag; } bool HttpRequest::Parser::state_protocol_slash2(char ch) { if (ch == '/') SET_STATE(state_protocol_host); else { log_warn("invalid character " << chartoprint(ch) << " in url"); httpCode = HTTP_BAD_REQUEST; failedFlag = true; } return failedFlag; } bool HttpRequest::Parser::state_protocol_host(char ch) { if (ch == '/') { message.url.clear(); message.url.reserve(32); message.url += ch; SET_STATE(state_url); } else if (!std::isalpha(ch) && !std::isdigit(ch) && ch != '[' && ch != ']' && ch != '.' && ch != ':') { log_warn("invalid character " << chartoprint(ch) << " in url"); httpCode = HTTP_BAD_REQUEST; failedFlag = true; } return failedFlag; } bool HttpRequest::Parser::state_url(char ch) { if (ch == '?') { log_debug("url=" << message.url); SET_STATE(state_qparam); } else if (ch == '\r') { log_debug("url=" << message.url); SET_STATE(state_end0); } else if (ch == '\n') { log_debug("url=" << message.url); SET_STATE(state_header); } else if (ch == ' ' || ch == '\t') { log_debug("url=" << message.url); SET_STATE(state_version); } else if (ch == '%') { SET_STATE(state_urlesc); message.url += ch; } else if (ch > ' ') message.url += ch; else { log_warn("invalid character " << chartoprint(ch) << " in url"); httpCode = HTTP_BAD_REQUEST; failedFlag = true; } return failedFlag; } bool HttpRequest::Parser::state_urlesc(char ch) { if (isHexDigit(ch)) { if (message.url.size() >= 2 && message.url[message.url.size() - 2] == '%') { unsigned v = (valueOfHexDigit(message.url[message.url.size() - 1]) << 4) | valueOfHexDigit(ch); if (v == 0) throw HttpError(HTTP_BAD_REQUEST, "invalid value in url"); message.url[message.url.size() - 2] = static_cast<char>(v); message.url.resize(message.url.size() - 1); SET_STATE(state_url); } else { message.url += ch; } return false; } else { SET_STATE(state_url); return state_url(ch); } } bool HttpRequest::Parser::state_qparam(char ch) { if (ch == ' ' || ch == '\t') { log_debug("queryString=" << message.queryString); SET_STATE(state_version); } else message.queryString += ch; return false; } bool HttpRequest::Parser::state_version(char ch) { if (ch == '/') { message.setVersion(0, 0); skipWs(&Parser::state_version_major); } else if (ch == '\r') { log_warn("invalid character " << chartoprint(ch) << " in version"); httpCode = HTTP_BAD_REQUEST; failedFlag = true; } return failedFlag; } bool HttpRequest::Parser::state_version_major(char ch) { if (ch == '.') SET_STATE(state_version_minor0); else if (std::isdigit(ch)) message.setVersion(message.getMajorVersion() * 10 + (ch - '0'), message.getMinorVersion()); else if (ch == ' ' || ch == '\t') SET_STATE(state_version_major_sp); else { log_warn("invalid character " << chartoprint(ch) << " in version-major"); httpCode = HTTP_BAD_REQUEST; failedFlag = true; } return failedFlag; } bool HttpRequest::Parser::state_version_major_sp(char ch) { if (ch == '.') SET_STATE(state_version_minor0); else { log_warn("invalid character " << chartoprint(ch) << " in version-major"); httpCode = HTTP_BAD_REQUEST; failedFlag = true; } return failedFlag; } bool HttpRequest::Parser::state_version_minor0(char ch) { return ch == ' ' || ch == '\t' ? failedFlag : state_version_minor(ch); } bool HttpRequest::Parser::state_version_minor(char ch) { if (ch == '\n') SET_STATE(state_header); else if (ch == ' ' || ch == '\t' || ch == '\r') SET_STATE(state_end0); else if (std::isdigit(ch)) message.setVersion(message.getMajorVersion(), message.getMinorVersion() * 10 + (ch - '0')); else { log_warn("invalid character " << chartoprint(ch) << " in version-minor"); httpCode = HTTP_BAD_REQUEST; failedFlag = true; } return failedFlag; } bool HttpRequest::Parser::state_end0(char ch) { if (ch == '\n') SET_STATE(state_header); else if (ch != ' ' && ch != '\t') { log_warn("invalid character " << chartoprint(ch) << " in end"); httpCode = HTTP_BAD_REQUEST; failedFlag = true; } return failedFlag; } bool HttpRequest::Parser::state_header(char ch) { if (headerParser.parse(ch)) { if (headerParser.failed()) { httpCode = HTTP_BAD_REQUEST; failedFlag = true; return true; } const char* content_length_header = message.getHeader(httpheader::contentLength); if (*content_length_header) { bodySize = 0; for (const char* c = content_length_header; *c; ++c) { if (*c > '9' || *c < '0') throw HttpError(HTTP_BAD_REQUEST, "invalid Content-Length"); bodySize = bodySize * 10 + *c - '0'; } if (TntConfig::it().maxRequestSize > 0 && getCurrentRequestSize() + bodySize > TntConfig::it().maxRequestSize) { requestSizeExceeded(); return true; } message.contentSize = bodySize; if (bodySize == 0) return true; else { SET_STATE(state_body); message.body.reserve(bodySize); return false; } } return true; } return false; } bool HttpRequest::Parser::state_body(char ch) { message.body += ch; return --bodySize == 0; } void HttpRequest::Parser::requestSizeExceeded() { log_warn("max request size " << TntConfig::it().maxRequestSize << " exceeded"); httpCode = HTTP_REQUEST_ENTITY_TOO_LARGE; failedFlag = true; } } <|endoftext|>
<commit_before>// Copyright 2016 The SwiftShader Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "PixelProgram.hpp" #include "SamplerCore.hpp" #include "Device/Primitive.hpp" #include "Device/Renderer.hpp" namespace sw { extern bool postBlendSRGB; void PixelProgram::setBuiltins(Int &x, Int &y, Float4(&z)[4], Float4 &w) { routine.windowSpacePosition[0] = x + SIMD::Int(0,1,0,1); routine.windowSpacePosition[1] = y + SIMD::Int(0,0,1,1); auto it = spirvShader->inputBuiltins.find(spv::BuiltInFragCoord); if (it != spirvShader->inputBuiltins.end()) { auto &var = routine.getVariable(it->second.Id); var[it->second.FirstComponent] = SIMD::Float(Float(x)) + SIMD::Float(0.5f, 1.5f, 0.5f, 1.5f); var[it->second.FirstComponent+1] = SIMD::Float(Float(y)) + SIMD::Float(0.5f, 0.5f, 1.5f, 1.5f); var[it->second.FirstComponent+2] = z[0]; // sample 0 var[it->second.FirstComponent+3] = w; } it = spirvShader->inputBuiltins.find(spv::BuiltInSubgroupSize); if (it != spirvShader->inputBuiltins.end()) { ASSERT(it->second.SizeInComponents == 1); routine.getVariable(it->second.Id)[it->second.FirstComponent] = As<SIMD::Float>(SIMD::Int(SIMD::Width)); } it = spirvShader->inputBuiltins.find(spv::BuiltInSubgroupLocalInvocationId); if (it != spirvShader->inputBuiltins.end()) { ASSERT(it->second.SizeInComponents == 1); routine.getVariable(it->second.Id)[it->second.FirstComponent] = As<SIMD::Float>(SIMD::Int(0, 1, 2, 3)); } } void PixelProgram::applyShader(Int cMask[4]) { routine.descriptorSets = data + OFFSET(DrawData, descriptorSets); routine.descriptorDynamicOffsets = data + OFFSET(DrawData, descriptorDynamicOffsets); routine.pushConstants = data + OFFSET(DrawData, pushConstants); routine.constants = *Pointer<Pointer<Byte>>(data + OFFSET(DrawData, constants)); auto it = spirvShader->inputBuiltins.find(spv::BuiltInFrontFacing); if (it != spirvShader->inputBuiltins.end()) { ASSERT(it->second.SizeInComponents == 1); auto frontFacing = Int4(*Pointer<Int>(primitive + OFFSET(Primitive, clockwiseMask))); routine.getVariable(it->second.Id)[it->second.FirstComponent] = As<Float4>(frontFacing); } // Note: all lanes initially active to facilitate derivatives etc. Actual coverage is // handled separately, through the cMask. auto activeLaneMask = SIMD::Int(0xFFFFFFFF); routine.killMask = 0; spirvShader->emit(&routine, activeLaneMask, descriptorSets); spirvShader->emitEpilog(&routine); for(int i = 0; i < RENDERTARGETS; i++) { c[i].x = routine.outputs[i * 4]; c[i].y = routine.outputs[i * 4 + 1]; c[i].z = routine.outputs[i * 4 + 2]; c[i].w = routine.outputs[i * 4 + 3]; } clampColor(c); if(spirvShader->getModes().ContainsKill) { for (auto i = 0u; i < state.multiSample; i++) { cMask[i] &= ~routine.killMask; } } it = spirvShader->outputBuiltins.find(spv::BuiltInFragDepth); if (it != spirvShader->outputBuiltins.end()) { oDepth = routine.getVariable(it->second.Id)[it->second.FirstComponent]; } if(spirvShader->getModes().DepthReplacing) { oDepth = Min(Max(oDepth, Float4(0.0f)), Float4(1.0f)); } } Bool PixelProgram::alphaTest(Int cMask[4]) { if(!state.alphaToCoverage) { return true; } alphaToCoverage(cMask, c[0].w); Int pass = cMask[0]; for(unsigned int q = 1; q < state.multiSample; q++) { pass = pass | cMask[q]; } return pass != 0x0; } void PixelProgram::rasterOperation(Pointer<Byte> cBuffer[4], Int &x, Int sMask[4], Int zMask[4], Int cMask[4]) { for(int index = 0; index < RENDERTARGETS; index++) { if(!state.colorWriteActive(index)) { continue; } switch(state.targetFormat[index]) { case VK_FORMAT_R5G6B5_UNORM_PACK16: case VK_FORMAT_B8G8R8A8_UNORM: case VK_FORMAT_B8G8R8A8_SRGB: case VK_FORMAT_R8G8B8A8_UNORM: case VK_FORMAT_R8G8B8A8_SRGB: case VK_FORMAT_R8G8_UNORM: case VK_FORMAT_R8_UNORM: case VK_FORMAT_R16G16_UNORM: case VK_FORMAT_R16G16B16A16_UNORM: case VK_FORMAT_A8B8G8R8_UNORM_PACK32: case VK_FORMAT_A8B8G8R8_SRGB_PACK32: for(unsigned int q = 0; q < state.multiSample; q++) { Pointer<Byte> buffer = cBuffer[index] + q * *Pointer<Int>(data + OFFSET(DrawData, colorSliceB[index])); Vector4s color; if(state.targetFormat[index] == VK_FORMAT_R5G6B5_UNORM_PACK16) { color.x = UShort4(c[index].x * Float4(0xFBFF), false); color.y = UShort4(c[index].y * Float4(0xFDFF), false); color.z = UShort4(c[index].z * Float4(0xFBFF), false); color.w = UShort4(c[index].w * Float4(0xFFFF), false); } else { color.x = convertFixed16(c[index].x, false); color.y = convertFixed16(c[index].y, false); color.z = convertFixed16(c[index].z, false); color.w = convertFixed16(c[index].w, false); } if(state.multiSampleMask & (1 << q)) { alphaBlend(index, buffer, color, x); writeColor(index, buffer, x, color, sMask[q], zMask[q], cMask[q]); } } break; case VK_FORMAT_R32_SFLOAT: case VK_FORMAT_R32G32_SFLOAT: case VK_FORMAT_R32G32B32A32_SFLOAT: case VK_FORMAT_R32_SINT: case VK_FORMAT_R32G32_SINT: case VK_FORMAT_R32G32B32A32_SINT: case VK_FORMAT_R32_UINT: case VK_FORMAT_R32G32_UINT: case VK_FORMAT_R32G32B32A32_UINT: case VK_FORMAT_R16_SINT: case VK_FORMAT_R16G16_SINT: case VK_FORMAT_R16G16B16A16_SINT: case VK_FORMAT_R16_UINT: case VK_FORMAT_R16G16_UINT: case VK_FORMAT_R16G16B16A16_UINT: case VK_FORMAT_R8_SINT: case VK_FORMAT_R8G8_SINT: case VK_FORMAT_R8G8B8A8_SINT: case VK_FORMAT_R8_UINT: case VK_FORMAT_R8G8_UINT: case VK_FORMAT_R8G8B8A8_UINT: case VK_FORMAT_A8B8G8R8_UINT_PACK32: case VK_FORMAT_A8B8G8R8_SINT_PACK32: for(unsigned int q = 0; q < state.multiSample; q++) { Pointer<Byte> buffer = cBuffer[index] + q * *Pointer<Int>(data + OFFSET(DrawData, colorSliceB[index])); Vector4f color = c[index]; if(state.multiSampleMask & (1 << q)) { alphaBlend(index, buffer, color, x); writeColor(index, buffer, x, color, sMask[q], zMask[q], cMask[q]); } } break; default: UNIMPLEMENTED("VkFormat: %d", int(state.targetFormat[index])); } } } void PixelProgram::clampColor(Vector4f oC[RENDERTARGETS]) { for(int index = 0; index < RENDERTARGETS; index++) { if(!state.colorWriteActive(index) && !(index == 0 && state.alphaToCoverage)) { continue; } switch(state.targetFormat[index]) { case VK_FORMAT_UNDEFINED: break; case VK_FORMAT_R5G6B5_UNORM_PACK16: case VK_FORMAT_B8G8R8A8_UNORM: case VK_FORMAT_B8G8R8A8_SRGB: case VK_FORMAT_R8G8B8A8_UNORM: case VK_FORMAT_R8G8B8A8_SRGB: case VK_FORMAT_R8G8_UNORM: case VK_FORMAT_R8_UNORM: case VK_FORMAT_R16G16_UNORM: case VK_FORMAT_R16G16B16A16_UNORM: case VK_FORMAT_A8B8G8R8_UNORM_PACK32: case VK_FORMAT_A8B8G8R8_SRGB_PACK32: oC[index].x = Max(oC[index].x, Float4(0.0f)); oC[index].x = Min(oC[index].x, Float4(1.0f)); oC[index].y = Max(oC[index].y, Float4(0.0f)); oC[index].y = Min(oC[index].y, Float4(1.0f)); oC[index].z = Max(oC[index].z, Float4(0.0f)); oC[index].z = Min(oC[index].z, Float4(1.0f)); oC[index].w = Max(oC[index].w, Float4(0.0f)); oC[index].w = Min(oC[index].w, Float4(1.0f)); break; case VK_FORMAT_R32_SFLOAT: case VK_FORMAT_R32G32_SFLOAT: case VK_FORMAT_R32G32B32A32_SFLOAT: case VK_FORMAT_R32_SINT: case VK_FORMAT_R32G32_SINT: case VK_FORMAT_R32G32B32A32_SINT: case VK_FORMAT_R32_UINT: case VK_FORMAT_R32G32_UINT: case VK_FORMAT_R32G32B32A32_UINT: case VK_FORMAT_R16_SINT: case VK_FORMAT_R16G16_SINT: case VK_FORMAT_R16G16B16A16_SINT: case VK_FORMAT_R16_UINT: case VK_FORMAT_R16G16_UINT: case VK_FORMAT_R16G16B16A16_UINT: case VK_FORMAT_R8_SINT: case VK_FORMAT_R8G8_SINT: case VK_FORMAT_R8G8B8A8_SINT: case VK_FORMAT_R8_UINT: case VK_FORMAT_R8G8_UINT: case VK_FORMAT_R8G8B8A8_UINT: case VK_FORMAT_A8B8G8R8_UINT_PACK32: case VK_FORMAT_A8B8G8R8_SINT_PACK32: break; default: UNIMPLEMENTED("VkFormat: %d", int(state.targetFormat[index])); } } } Float4 PixelProgram::linearToSRGB(const Float4 &x) // Approximates x^(1.0/2.2) { Float4 sqrtx = Rcp_pp(RcpSqrt_pp(x)); Float4 sRGB = sqrtx * Float4(1.14f) - x * Float4(0.14f); return Min(Max(sRGB, Float4(0.0f)), Float4(1.0f)); } } <commit_msg>Minor tidying in PixelProgram<commit_after>// Copyright 2016 The SwiftShader Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "PixelProgram.hpp" #include "SamplerCore.hpp" #include "Device/Primitive.hpp" #include "Device/Renderer.hpp" namespace sw { extern bool postBlendSRGB; void PixelProgram::setBuiltins(Int &x, Int &y, Float4(&z)[4], Float4 &w) { routine.windowSpacePosition[0] = x + SIMD::Int(0,1,0,1); routine.windowSpacePosition[1] = y + SIMD::Int(0,0,1,1); auto it = spirvShader->inputBuiltins.find(spv::BuiltInFragCoord); if (it != spirvShader->inputBuiltins.end()) { auto &var = routine.getVariable(it->second.Id); var[it->second.FirstComponent] = SIMD::Float(Float(x)) + SIMD::Float(0.5f, 1.5f, 0.5f, 1.5f); var[it->second.FirstComponent+1] = SIMD::Float(Float(y)) + SIMD::Float(0.5f, 0.5f, 1.5f, 1.5f); var[it->second.FirstComponent+2] = z[0]; // sample 0 var[it->second.FirstComponent+3] = w; } it = spirvShader->inputBuiltins.find(spv::BuiltInSubgroupSize); if (it != spirvShader->inputBuiltins.end()) { ASSERT(it->second.SizeInComponents == 1); routine.getVariable(it->second.Id)[it->second.FirstComponent] = As<SIMD::Float>(SIMD::Int(SIMD::Width)); } it = spirvShader->inputBuiltins.find(spv::BuiltInSubgroupLocalInvocationId); if (it != spirvShader->inputBuiltins.end()) { ASSERT(it->second.SizeInComponents == 1); routine.getVariable(it->second.Id)[it->second.FirstComponent] = As<SIMD::Float>(SIMD::Int(0, 1, 2, 3)); } } void PixelProgram::applyShader(Int cMask[4]) { routine.descriptorSets = data + OFFSET(DrawData, descriptorSets); routine.descriptorDynamicOffsets = data + OFFSET(DrawData, descriptorDynamicOffsets); routine.pushConstants = data + OFFSET(DrawData, pushConstants); routine.constants = *Pointer<Pointer<Byte>>(data + OFFSET(DrawData, constants)); auto it = spirvShader->inputBuiltins.find(spv::BuiltInFrontFacing); if (it != spirvShader->inputBuiltins.end()) { ASSERT(it->second.SizeInComponents == 1); auto frontFacing = Int4(*Pointer<Int>(primitive + OFFSET(Primitive, clockwiseMask))); routine.getVariable(it->second.Id)[it->second.FirstComponent] = As<Float4>(frontFacing); } // Note: all lanes initially active to facilitate derivatives etc. Actual coverage is // handled separately, through the cMask. auto activeLaneMask = SIMD::Int(0xFFFFFFFF); routine.killMask = 0; spirvShader->emit(&routine, activeLaneMask, descriptorSets); spirvShader->emitEpilog(&routine); for(int i = 0; i < RENDERTARGETS; i++) { c[i].x = routine.outputs[i * 4]; c[i].y = routine.outputs[i * 4 + 1]; c[i].z = routine.outputs[i * 4 + 2]; c[i].w = routine.outputs[i * 4 + 3]; } clampColor(c); if(spirvShader->getModes().ContainsKill) { for (auto i = 0u; i < state.multiSample; i++) { cMask[i] &= ~routine.killMask; } } it = spirvShader->outputBuiltins.find(spv::BuiltInFragDepth); if (it != spirvShader->outputBuiltins.end()) { oDepth = Min(Max(routine.getVariable(it->second.Id)[it->second.FirstComponent], Float4(0.0f)), Float4(1.0f)); } } Bool PixelProgram::alphaTest(Int cMask[4]) { if(!state.alphaToCoverage) { return true; } alphaToCoverage(cMask, c[0].w); Int pass = cMask[0]; for(unsigned int q = 1; q < state.multiSample; q++) { pass = pass | cMask[q]; } return pass != 0x0; } void PixelProgram::rasterOperation(Pointer<Byte> cBuffer[4], Int &x, Int sMask[4], Int zMask[4], Int cMask[4]) { for(int index = 0; index < RENDERTARGETS; index++) { if(!state.colorWriteActive(index)) { continue; } switch(state.targetFormat[index]) { case VK_FORMAT_R5G6B5_UNORM_PACK16: case VK_FORMAT_B8G8R8A8_UNORM: case VK_FORMAT_B8G8R8A8_SRGB: case VK_FORMAT_R8G8B8A8_UNORM: case VK_FORMAT_R8G8B8A8_SRGB: case VK_FORMAT_R8G8_UNORM: case VK_FORMAT_R8_UNORM: case VK_FORMAT_R16G16_UNORM: case VK_FORMAT_R16G16B16A16_UNORM: case VK_FORMAT_A8B8G8R8_UNORM_PACK32: case VK_FORMAT_A8B8G8R8_SRGB_PACK32: for(unsigned int q = 0; q < state.multiSample; q++) { Pointer<Byte> buffer = cBuffer[index] + q * *Pointer<Int>(data + OFFSET(DrawData, colorSliceB[index])); Vector4s color; if(state.targetFormat[index] == VK_FORMAT_R5G6B5_UNORM_PACK16) { color.x = UShort4(c[index].x * Float4(0xFBFF), false); color.y = UShort4(c[index].y * Float4(0xFDFF), false); color.z = UShort4(c[index].z * Float4(0xFBFF), false); color.w = UShort4(c[index].w * Float4(0xFFFF), false); } else { color.x = convertFixed16(c[index].x, false); color.y = convertFixed16(c[index].y, false); color.z = convertFixed16(c[index].z, false); color.w = convertFixed16(c[index].w, false); } if(state.multiSampleMask & (1 << q)) { alphaBlend(index, buffer, color, x); writeColor(index, buffer, x, color, sMask[q], zMask[q], cMask[q]); } } break; case VK_FORMAT_R32_SFLOAT: case VK_FORMAT_R32G32_SFLOAT: case VK_FORMAT_R32G32B32A32_SFLOAT: case VK_FORMAT_R32_SINT: case VK_FORMAT_R32G32_SINT: case VK_FORMAT_R32G32B32A32_SINT: case VK_FORMAT_R32_UINT: case VK_FORMAT_R32G32_UINT: case VK_FORMAT_R32G32B32A32_UINT: case VK_FORMAT_R16_SINT: case VK_FORMAT_R16G16_SINT: case VK_FORMAT_R16G16B16A16_SINT: case VK_FORMAT_R16_UINT: case VK_FORMAT_R16G16_UINT: case VK_FORMAT_R16G16B16A16_UINT: case VK_FORMAT_R8_SINT: case VK_FORMAT_R8G8_SINT: case VK_FORMAT_R8G8B8A8_SINT: case VK_FORMAT_R8_UINT: case VK_FORMAT_R8G8_UINT: case VK_FORMAT_R8G8B8A8_UINT: case VK_FORMAT_A8B8G8R8_UINT_PACK32: case VK_FORMAT_A8B8G8R8_SINT_PACK32: for(unsigned int q = 0; q < state.multiSample; q++) { Pointer<Byte> buffer = cBuffer[index] + q * *Pointer<Int>(data + OFFSET(DrawData, colorSliceB[index])); Vector4f color = c[index]; if(state.multiSampleMask & (1 << q)) { alphaBlend(index, buffer, color, x); writeColor(index, buffer, x, color, sMask[q], zMask[q], cMask[q]); } } break; default: UNIMPLEMENTED("VkFormat: %d", int(state.targetFormat[index])); } } } void PixelProgram::clampColor(Vector4f oC[RENDERTARGETS]) { for(int index = 0; index < RENDERTARGETS; index++) { if(!state.colorWriteActive(index) && !(index == 0 && state.alphaToCoverage)) { continue; } switch(state.targetFormat[index]) { case VK_FORMAT_UNDEFINED: break; case VK_FORMAT_R5G6B5_UNORM_PACK16: case VK_FORMAT_B8G8R8A8_UNORM: case VK_FORMAT_B8G8R8A8_SRGB: case VK_FORMAT_R8G8B8A8_UNORM: case VK_FORMAT_R8G8B8A8_SRGB: case VK_FORMAT_R8G8_UNORM: case VK_FORMAT_R8_UNORM: case VK_FORMAT_R16G16_UNORM: case VK_FORMAT_R16G16B16A16_UNORM: case VK_FORMAT_A8B8G8R8_UNORM_PACK32: case VK_FORMAT_A8B8G8R8_SRGB_PACK32: oC[index].x = Max(oC[index].x, Float4(0.0f)); oC[index].x = Min(oC[index].x, Float4(1.0f)); oC[index].y = Max(oC[index].y, Float4(0.0f)); oC[index].y = Min(oC[index].y, Float4(1.0f)); oC[index].z = Max(oC[index].z, Float4(0.0f)); oC[index].z = Min(oC[index].z, Float4(1.0f)); oC[index].w = Max(oC[index].w, Float4(0.0f)); oC[index].w = Min(oC[index].w, Float4(1.0f)); break; case VK_FORMAT_R32_SFLOAT: case VK_FORMAT_R32G32_SFLOAT: case VK_FORMAT_R32G32B32A32_SFLOAT: case VK_FORMAT_R32_SINT: case VK_FORMAT_R32G32_SINT: case VK_FORMAT_R32G32B32A32_SINT: case VK_FORMAT_R32_UINT: case VK_FORMAT_R32G32_UINT: case VK_FORMAT_R32G32B32A32_UINT: case VK_FORMAT_R16_SINT: case VK_FORMAT_R16G16_SINT: case VK_FORMAT_R16G16B16A16_SINT: case VK_FORMAT_R16_UINT: case VK_FORMAT_R16G16_UINT: case VK_FORMAT_R16G16B16A16_UINT: case VK_FORMAT_R8_SINT: case VK_FORMAT_R8G8_SINT: case VK_FORMAT_R8G8B8A8_SINT: case VK_FORMAT_R8_UINT: case VK_FORMAT_R8G8_UINT: case VK_FORMAT_R8G8B8A8_UINT: case VK_FORMAT_A8B8G8R8_UINT_PACK32: case VK_FORMAT_A8B8G8R8_SINT_PACK32: break; default: UNIMPLEMENTED("VkFormat: %d", int(state.targetFormat[index])); } } } Float4 PixelProgram::linearToSRGB(const Float4 &x) // Approximates x^(1.0/2.2) { Float4 sqrtx = Rcp_pp(RcpSqrt_pp(x)); Float4 sRGB = sqrtx * Float4(1.14f) - x * Float4(0.14f); return Min(Max(sRGB, Float4(0.0f)), Float4(1.0f)); } } <|endoftext|>
<commit_before>/* * Copyright (C) 2005-2006 Tommi Maekitalo * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "tnt/pollerimpl.h" #include "tnt/tntnet.h" #include <cxxtools/systemerror.h> #include <cxxtools/log.h> #include <ios> #include <unistd.h> #include <fcntl.h> #ifdef WITH_EPOLL # include <sys/epoll.h> # include <errno.h> #endif log_define("tntnet.pollerimpl") namespace tnt { #ifdef WITH_EPOLL PollerImpl::PollerImpl(Jobqueue& q) : _queue(q), _pollFd(-1), _pollTimeout(-1) { #ifdef HAVE_EPOLL_CREATE1 _pollFd = ::epoll_create1(EPOLL_CLOEXEC); #else _pollFd = ::epoll_create(1); #endif if (_pollFd < 0) throw cxxtools::SystemError("epoll_create"); fcntl(_notifyPipe.getReadFd(), F_SETFL, O_NONBLOCK); addFd(_notifyPipe.getReadFd()); } PollerImpl::~PollerImpl() { close(_pollFd); } void PollerImpl::addFd(int fd) { log_trace("addFd(" << fd << ')'); epoll_event e; e.events = EPOLLIN; e.data.fd = fd; int ret = ::epoll_ctl(_pollFd, EPOLL_CTL_ADD, fd, &e); if (ret < 0) throw cxxtools::SystemError("epoll_ctl(EPOLL_CTL_ADD)"); } bool PollerImpl::removeFd(int fd) { epoll_event e; e.data.fd = fd; int ret = ::epoll_ctl(_pollFd, EPOLL_CTL_DEL, fd, &e); if (ret < 0) { if (errno == EBADF || errno == ENOENT) return false; else throw cxxtools::SystemError("epoll_ctl(EPOLL_CTL_DEL)"); } return true; } void PollerImpl::doStop() { _notifyPipe.write('A'); } void PollerImpl::addIdleJob(Jobqueue::JobPtr& job) { if (job->getFd() == -1) { log_debug("ignore idle socket which is not connected any more"); cxxtools::MutexLock lock(_mutex); job = 0; } else { log_debug("add idle socket " << job->getFd()); cxxtools::MutexLock lock(_mutex); _newJobs.push_back(job); job = 0; } _notifyPipe.write('A'); } void PollerImpl::appendNewJobs() { cxxtools::MutexLock lock(_mutex); if (!_newJobs.empty()) { // append new jobs to current log_trace("append " << _newJobs.size() << " sockets to poll"); time_t currentTime; time(&currentTime); for (new_jobs_type::iterator it = _newJobs.begin(); it != _newJobs.end(); ++it) { try { addFd((*it)->getFd()); _jobs[(*it)->getFd()] = *it; int msec = (*it)->msecToTimeout(currentTime); if (_pollTimeout < 0) _pollTimeout = msec; else if (msec < _pollTimeout) _pollTimeout = msec; } catch (const std::exception& e) { log_error("failed to add fd " << (*it)->getFd() << " to poll: " << e.what()); } } _newJobs.clear(); } } void PollerImpl::run() { epoll_event events[16]; time_t pollTime; time(&pollTime); while (!Tntnet::shouldStop()) { usleep(100); appendNewJobs(); if (_jobs.empty()) _pollTimeout = -1; int ret = ::epoll_wait(_pollFd, events, 16, _pollTimeout); if (ret < 0) { if (errno != EINTR) throw cxxtools::SystemError("epoll_wait"); } else if (ret == 0) { // timeout reached - check for timed out requests and get next timeout _pollTimeout = -1; time_t currentTime; time(&currentTime); for (jobs_type::iterator it = _jobs.begin(); it != _jobs.end(); ) { int msec = it->second->msecToTimeout(currentTime); if (msec <= 0) { log_debug("timeout for fd " << it->second->getFd() << " reached"); jobs_type::iterator it2 = it++; _jobs.erase(it2); } else { if (_pollTimeout < 0 || msec < _pollTimeout) _pollTimeout = msec; ++it; } } } else { time_t currentTime; time(&currentTime); _pollTimeout -= (currentTime - pollTime) * 1000; if (_pollTimeout <= 0) _pollTimeout = 100; pollTime = currentTime; // no timeout - process events bool rebuildPollFd = false; for (int i = 0; i < ret; ++i) { if (events[i].data.fd == _notifyPipe.getReadFd()) { if (Tntnet::shouldStop()) { log_info("stop poller"); break; } char buffer[64]; _notifyPipe.read(buffer, sizeof(buffer)); } else { jobs_type::iterator it = _jobs.find(events[i].data.fd); if (it == _jobs.end()) { log_fatal("internal error: job for fd " << events[i].data.fd << " not found in jobs-list"); ::close(events[i].data.fd); rebuildPollFd = true; } else { Jobqueue::JobPtr j = it->second; int ev = events[i].events; _jobs.erase(it); if (!removeFd(events[i].data.fd)) rebuildPollFd = true; if (ev & EPOLLIN) _queue.put(j); } } } if (rebuildPollFd) { // rebuild poll-structure log_warn("need to rebuild poll structure"); close(_pollFd); _pollFd = ::epoll_create(256); if (_pollFd < 0) throw cxxtools::SystemError("epoll_create"); int ret = fcntl(_notifyPipe.getReadFd(), F_SETFL, O_NONBLOCK); if (ret < 0) throw cxxtools::SystemError("fcntl"); addFd(_notifyPipe.getReadFd()); for (jobs_type::iterator it = _jobs.begin(); it != _jobs.end(); ++it) addFd(it->first); } } } } #else PollerImpl::PollerImpl(Jobqueue& q) : _queue(q), _pollTimeout(-1) { fcntl(_notifyPipe.getReadFd(), F_SETFL, O_NONBLOCK); _pollfds.push_back(pollfd()); _pollfds.back().fd = _notifyPipe.getReadFd(); _pollfds.back().events = POLLIN; _pollfds.back().revents = 0; } void PollerImpl::appendNewJobs() { cxxtools::MutexLock lock(_mutex); if (!_newJobs.empty()) { // append new jobs to current log_trace("append " << _newJobs.size() << " sockets to poll"); time_t currentTime; time(&currentTime); for (jobs_type::iterator it = _newJobs.begin(); it != _newJobs.end(); ++it) { append(*it); int msec = (*it)->msecToTimeout(currentTime); if (_pollTimeout < 0 || msec < _pollTimeout) _pollTimeout = msec; } _newJobs.clear(); } } void PollerImpl::append(Jobqueue::JobPtr& job) { _currentJobs.push_back(job); _pollfds.push_back(pollfd()); _pollfds.back().fd = job->getFd(); _pollfds.back().events = POLLIN; } void PollerImpl::run() { while (!Tntnet::shouldStop()) { usleep(100); appendNewJobs(); try { ::poll(&_pollfds[0], _pollfds.size(), _pollTimeout); _pollTimeout = -1; if (_pollfds[0].revents != 0) { if (Tntnet::shouldStop()) { log_info("stop poller"); break; } char buffer[64]; _notifyPipe.read(buffer, sizeof(buffer)); _pollfds[0].revents = 0; } if (_currentJobs.size() > 0) dispatch(); } catch (const std::exception& e) { log_error("error in poll-loop: " << e.what()); } } } void PollerImpl::doStop() { _notifyPipe.write('A'); } void PollerImpl::dispatch() { time_t currentTime; time(&currentTime); for (unsigned i = 0; i < _currentJobs.size(); ) { if (_pollfds[i + 1].revents & POLLIN) { // put job into work-queue _queue.put(_currentJobs[i]); remove(i); } else if (_pollfds[i + 1].revents != 0) remove(i); else { // check timeout int msec = _currentJobs[i]->msecToTimeout(currentTime); if (msec <= 0) remove(i); else if (_pollTimeout < 0 || msec < _pollTimeout) _pollTimeout = msec; ++i; } } } void PollerImpl::remove(jobs_type::size_type n) { // replace job with last job in poller-list jobs_type::size_type last = _currentJobs.size() - 1; if (n != last) { _pollfds[n + 1] = _pollfds[last + 1]; _currentJobs[n] = _currentJobs[last]; } _pollfds.pop_back(); _currentJobs.pop_back(); } void PollerImpl::addIdleJob(Jobqueue::JobPtr& job) { if (job->getFd() == -1) { log_debug("ignore idle socket which is not connected any more"); cxxtools::MutexLock lock(_mutex); job = 0; } else { log_debug("add idle socket " << job->getFd()); cxxtools::MutexLock lock(_mutex); _newJobs.push_back(job); job = 0; } _notifyPipe.write('A'); } #endif // #else WITH_EPOLL } <commit_msg>set close on exec flag on poll fd also on systems, which do not have epoll_create1<commit_after>/* * Copyright (C) 2005-2006 Tommi Maekitalo * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "tnt/pollerimpl.h" #include "tnt/tntnet.h" #include <cxxtools/systemerror.h> #include <cxxtools/log.h> #include <ios> #include <unistd.h> #include <fcntl.h> #ifdef WITH_EPOLL # include <sys/epoll.h> # include <errno.h> #endif log_define("tntnet.pollerimpl") namespace tnt { #ifdef WITH_EPOLL PollerImpl::PollerImpl(Jobqueue& q) : _queue(q), _pollFd(-1), _pollTimeout(-1) { #ifdef HAVE_EPOLL_CREATE1 _pollFd = ::epoll_create1(EPOLL_CLOEXEC); if (_pollFd < 0) throw cxxtools::SystemError("epoll_create1"); #else _pollFd = ::epoll_create(1); if (_pollFd < 0) throw cxxtools::SystemError("epoll_create"); int flags = ::fcntl(_pollFd, F_GETFD); flags |= FD_CLOEXEC ; int ret = ::fcntl(_pollFd, F_SETFD, flags); if(-1 == ret) throw cxxtools::SystemError("fcntl(FD_CLOEXEC)"); #endif fcntl(_notifyPipe.getReadFd(), F_SETFL, O_NONBLOCK); addFd(_notifyPipe.getReadFd()); } PollerImpl::~PollerImpl() { close(_pollFd); } void PollerImpl::addFd(int fd) { log_trace("addFd(" << fd << ')'); epoll_event e; e.events = EPOLLIN; e.data.fd = fd; int ret = ::epoll_ctl(_pollFd, EPOLL_CTL_ADD, fd, &e); if (ret < 0) throw cxxtools::SystemError("epoll_ctl(EPOLL_CTL_ADD)"); } bool PollerImpl::removeFd(int fd) { epoll_event e; e.data.fd = fd; int ret = ::epoll_ctl(_pollFd, EPOLL_CTL_DEL, fd, &e); if (ret < 0) { if (errno == EBADF || errno == ENOENT) return false; else throw cxxtools::SystemError("epoll_ctl(EPOLL_CTL_DEL)"); } return true; } void PollerImpl::doStop() { _notifyPipe.write('A'); } void PollerImpl::addIdleJob(Jobqueue::JobPtr& job) { if (job->getFd() == -1) { log_debug("ignore idle socket which is not connected any more"); cxxtools::MutexLock lock(_mutex); job = 0; } else { log_debug("add idle socket " << job->getFd()); cxxtools::MutexLock lock(_mutex); _newJobs.push_back(job); job = 0; } _notifyPipe.write('A'); } void PollerImpl::appendNewJobs() { cxxtools::MutexLock lock(_mutex); if (!_newJobs.empty()) { // append new jobs to current log_trace("append " << _newJobs.size() << " sockets to poll"); time_t currentTime; time(&currentTime); for (new_jobs_type::iterator it = _newJobs.begin(); it != _newJobs.end(); ++it) { try { addFd((*it)->getFd()); _jobs[(*it)->getFd()] = *it; int msec = (*it)->msecToTimeout(currentTime); if (_pollTimeout < 0) _pollTimeout = msec; else if (msec < _pollTimeout) _pollTimeout = msec; } catch (const std::exception& e) { log_error("failed to add fd " << (*it)->getFd() << " to poll: " << e.what()); } } _newJobs.clear(); } } void PollerImpl::run() { epoll_event events[16]; time_t pollTime; time(&pollTime); while (!Tntnet::shouldStop()) { usleep(100); appendNewJobs(); if (_jobs.empty()) _pollTimeout = -1; int ret = ::epoll_wait(_pollFd, events, 16, _pollTimeout); if (ret < 0) { if (errno != EINTR) throw cxxtools::SystemError("epoll_wait"); } else if (ret == 0) { // timeout reached - check for timed out requests and get next timeout _pollTimeout = -1; time_t currentTime; time(&currentTime); for (jobs_type::iterator it = _jobs.begin(); it != _jobs.end(); ) { int msec = it->second->msecToTimeout(currentTime); if (msec <= 0) { log_debug("timeout for fd " << it->second->getFd() << " reached"); jobs_type::iterator it2 = it++; _jobs.erase(it2); } else { if (_pollTimeout < 0 || msec < _pollTimeout) _pollTimeout = msec; ++it; } } } else { time_t currentTime; time(&currentTime); _pollTimeout -= (currentTime - pollTime) * 1000; if (_pollTimeout <= 0) _pollTimeout = 100; pollTime = currentTime; // no timeout - process events bool rebuildPollFd = false; for (int i = 0; i < ret; ++i) { if (events[i].data.fd == _notifyPipe.getReadFd()) { if (Tntnet::shouldStop()) { log_info("stop poller"); break; } char buffer[64]; _notifyPipe.read(buffer, sizeof(buffer)); } else { jobs_type::iterator it = _jobs.find(events[i].data.fd); if (it == _jobs.end()) { log_fatal("internal error: job for fd " << events[i].data.fd << " not found in jobs-list"); ::close(events[i].data.fd); rebuildPollFd = true; } else { Jobqueue::JobPtr j = it->second; int ev = events[i].events; _jobs.erase(it); if (!removeFd(events[i].data.fd)) rebuildPollFd = true; if (ev & EPOLLIN) _queue.put(j); } } } if (rebuildPollFd) { // rebuild poll-structure log_warn("need to rebuild poll structure"); close(_pollFd); _pollFd = ::epoll_create(256); if (_pollFd < 0) throw cxxtools::SystemError("epoll_create"); int ret = fcntl(_notifyPipe.getReadFd(), F_SETFL, O_NONBLOCK); if (ret < 0) throw cxxtools::SystemError("fcntl"); addFd(_notifyPipe.getReadFd()); for (jobs_type::iterator it = _jobs.begin(); it != _jobs.end(); ++it) addFd(it->first); } } } } #else PollerImpl::PollerImpl(Jobqueue& q) : _queue(q), _pollTimeout(-1) { fcntl(_notifyPipe.getReadFd(), F_SETFL, O_NONBLOCK); _pollfds.push_back(pollfd()); _pollfds.back().fd = _notifyPipe.getReadFd(); _pollfds.back().events = POLLIN; _pollfds.back().revents = 0; } void PollerImpl::appendNewJobs() { cxxtools::MutexLock lock(_mutex); if (!_newJobs.empty()) { // append new jobs to current log_trace("append " << _newJobs.size() << " sockets to poll"); time_t currentTime; time(&currentTime); for (jobs_type::iterator it = _newJobs.begin(); it != _newJobs.end(); ++it) { append(*it); int msec = (*it)->msecToTimeout(currentTime); if (_pollTimeout < 0 || msec < _pollTimeout) _pollTimeout = msec; } _newJobs.clear(); } } void PollerImpl::append(Jobqueue::JobPtr& job) { _currentJobs.push_back(job); _pollfds.push_back(pollfd()); _pollfds.back().fd = job->getFd(); _pollfds.back().events = POLLIN; } void PollerImpl::run() { while (!Tntnet::shouldStop()) { usleep(100); appendNewJobs(); try { ::poll(&_pollfds[0], _pollfds.size(), _pollTimeout); _pollTimeout = -1; if (_pollfds[0].revents != 0) { if (Tntnet::shouldStop()) { log_info("stop poller"); break; } char buffer[64]; _notifyPipe.read(buffer, sizeof(buffer)); _pollfds[0].revents = 0; } if (_currentJobs.size() > 0) dispatch(); } catch (const std::exception& e) { log_error("error in poll-loop: " << e.what()); } } } void PollerImpl::doStop() { _notifyPipe.write('A'); } void PollerImpl::dispatch() { time_t currentTime; time(&currentTime); for (unsigned i = 0; i < _currentJobs.size(); ) { if (_pollfds[i + 1].revents & POLLIN) { // put job into work-queue _queue.put(_currentJobs[i]); remove(i); } else if (_pollfds[i + 1].revents != 0) remove(i); else { // check timeout int msec = _currentJobs[i]->msecToTimeout(currentTime); if (msec <= 0) remove(i); else if (_pollTimeout < 0 || msec < _pollTimeout) _pollTimeout = msec; ++i; } } } void PollerImpl::remove(jobs_type::size_type n) { // replace job with last job in poller-list jobs_type::size_type last = _currentJobs.size() - 1; if (n != last) { _pollfds[n + 1] = _pollfds[last + 1]; _currentJobs[n] = _currentJobs[last]; } _pollfds.pop_back(); _currentJobs.pop_back(); } void PollerImpl::addIdleJob(Jobqueue::JobPtr& job) { if (job->getFd() == -1) { log_debug("ignore idle socket which is not connected any more"); cxxtools::MutexLock lock(_mutex); job = 0; } else { log_debug("add idle socket " << job->getFd()); cxxtools::MutexLock lock(_mutex); _newJobs.push_back(job); job = 0; } _notifyPipe.write('A'); } #endif // #else WITH_EPOLL } <|endoftext|>
<commit_before>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ #ifndef __OPENCV_OBJDETECT_ERFILTER_HPP__ #define __OPENCV_OBJDETECT_ERFILTER_HPP__ #include "opencv2/core.hpp" #include <vector> #include <deque> namespace cv { /*! Extremal Region Stat structure The ERStat structure represents a class-specific Extremal Region (ER). An ER is a 4-connected set of pixels with all its grey-level values smaller than the values in its outer boundary. A class-specific ER is selected (using a classifier) from all the ER's in the component tree of the image. */ struct CV_EXPORTS ERStat { public: //! Constructor ERStat(int level = 256, int pixel = 0, int x = 0, int y = 0); //! Destructor ~ERStat(){}; //! seed point and the threshold (max grey-level value) int pixel; int level; //! incrementally computable features int area; int perimeter; int euler; //!< euler number int bbox[4]; double raw_moments[2]; //!< order 1 raw moments to derive the centroid double central_moments[3]; //!< order 2 central moments to construct the covariance matrix std::deque<int> *crossings;//!< horizontal crossings //! 1st stage features float aspect_ratio; float compactness; float num_holes; float med_crossings; //! 2nd stage features float hole_area_ratio; float convex_hull_ratio; float num_inflexion_points; // TODO Other features can be added (average color, standard deviation, and such) // TODO shall we include the pixel list whenever available (i.e. after 2nd stage) ? std::vector<int> *pixels; //! probability that the ER belongs to the class we are looking for double probability; //! pointers preserving the tree structure of the component tree ERStat* parent; ERStat* child; ERStat* next; ERStat* prev; //! wenever the regions is a local maxima of the probability bool local_maxima; ERStat* max_probability_ancestor; ERStat* min_probability_ancestor; }; /*! Base class for 1st and 2nd stages of Neumann and Matas scene text detection algorithms Neumann L., Matas J.: Real-Time Scene Text Localization and Recognition, CVPR 2012 Extracts the component tree (if needed) and filter the extremal regions (ER's) by using a given classifier. */ class CV_EXPORTS ERFilter : public cv::Algorithm { public: //! callback with the classifier is made a class. By doing it we hide SVM, Boost etc. class CV_EXPORTS Callback { public: virtual ~Callback(){}; //! The classifier must return probability measure for the region. virtual double eval(const ERStat& stat) = 0; //const = 0; //TODO why cannot use const = 0 here? }; /*! the key method. Takes image on input and returns the selected regions in a vector of ERStat only distinctive ERs which correspond to characters are selected by a sequential classifier \param image is the input image \param regions is output for the first stage, input/output for the second one. */ virtual void run( cv::InputArray image, std::vector<ERStat>& regions ) = 0; //! set/get methods to set the algorithm properties, virtual void setCallback(const cv::Ptr<ERFilter::Callback>& cb) = 0; virtual void setThresholdDelta(int thresholdDelta) = 0; virtual void setMinArea(float minArea) = 0; virtual void setMaxArea(float maxArea) = 0; virtual void setMinProbability(float minProbability) = 0; virtual void setMinProbabilityDiff(float minProbabilityDiff) = 0; virtual void setNonMaxSuppression(bool nonMaxSuppression) = 0; virtual int getNumRejected() = 0; }; /*! Create an Extremal Region Filter for the 1st stage classifier of N&M algorithm Neumann L., Matas J.: Real-Time Scene Text Localization and Recognition, CVPR 2012 The component tree of the image is extracted by a threshold increased step by step from 0 to 255, incrementally computable descriptors (aspect_ratio, compactness, number of holes, and number of horizontal crossings) are computed for each ER and used as features for a classifier which estimates the class-conditional probability P(er|character). The value of P(er|character) is tracked using the inclusion relation of ER across all thresholds and only the ERs which correspond to local maximum of the probability P(er|character) are selected (if the local maximum of the probability is above a global limit pmin and the difference between local maximum and local minimum is greater than minProbabilityDiff). \param cb Callback with the classifier. if omitted tries to load a default classifier from file trained_classifierNM1.xml \param thresholdDelta Threshold step in subsequent thresholds when extracting the component tree \param minArea The minimum area (% of image size) allowed for retreived ER's \param minArea The maximum area (% of image size) allowed for retreived ER's \param minProbability The minimum probability P(er|character) allowed for retreived ER's \param nonMaxSuppression Whenever non-maximum suppression is done over the branch probabilities \param minProbability The minimum probability difference between local maxima and local minima ERs */ CV_EXPORTS cv::Ptr<ERFilter> createERFilterNM1(const cv::Ptr<ERFilter::Callback>& cb = NULL, int thresholdDelta = 1, float minArea = 0.000025, float maxArea = 0.13, float minProbability = 0.2, bool nonMaxSuppression = true, float minProbabilityDiff = 0.1); /*! Create an Extremal Region Filter for the 2nd stage classifier of N&M algorithm Neumann L., Matas J.: Real-Time Scene Text Localization and Recognition, CVPR 2012 In the second stage, the ERs that passed the first stage are classified into character and non-character classes using more informative but also more computationally expensive features. The classifier uses all the features calculated in the first stage and the following additional features: hole area ratio, convex hull ratio, and number of outer inflexion points. \param cb Callback with the classifier if omitted tries to load a default classifier from file trained_classifierNM2.xml \param minProbability The minimum probability P(er|character) allowed for retreived ER's */ CV_EXPORTS cv::Ptr<ERFilter> createERFilterNM2(const cv::Ptr<ERFilter::Callback>& cb = NULL, float minProbability = 0.85); } #endif // _OPENCV_ERFILTER_HPP_ <commit_msg>using explicit keyword in the ERStat constructor for safe contruction<commit_after>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ #ifndef __OPENCV_OBJDETECT_ERFILTER_HPP__ #define __OPENCV_OBJDETECT_ERFILTER_HPP__ #include "opencv2/core.hpp" #include <vector> #include <deque> namespace cv { /*! Extremal Region Stat structure The ERStat structure represents a class-specific Extremal Region (ER). An ER is a 4-connected set of pixels with all its grey-level values smaller than the values in its outer boundary. A class-specific ER is selected (using a classifier) from all the ER's in the component tree of the image. */ struct CV_EXPORTS ERStat { public: //! Constructor explicit ERStat(int level = 256, int pixel = 0, int x = 0, int y = 0); //! Destructor ~ERStat(){}; //! seed point and the threshold (max grey-level value) int pixel; int level; //! incrementally computable features int area; int perimeter; int euler; //!< euler number int bbox[4]; double raw_moments[2]; //!< order 1 raw moments to derive the centroid double central_moments[3]; //!< order 2 central moments to construct the covariance matrix std::deque<int> *crossings;//!< horizontal crossings //! 1st stage features float aspect_ratio; float compactness; float num_holes; float med_crossings; //! 2nd stage features float hole_area_ratio; float convex_hull_ratio; float num_inflexion_points; // TODO Other features can be added (average color, standard deviation, and such) // TODO shall we include the pixel list whenever available (i.e. after 2nd stage) ? std::vector<int> *pixels; //! probability that the ER belongs to the class we are looking for double probability; //! pointers preserving the tree structure of the component tree ERStat* parent; ERStat* child; ERStat* next; ERStat* prev; //! wenever the regions is a local maxima of the probability bool local_maxima; ERStat* max_probability_ancestor; ERStat* min_probability_ancestor; }; /*! Base class for 1st and 2nd stages of Neumann and Matas scene text detection algorithms Neumann L., Matas J.: Real-Time Scene Text Localization and Recognition, CVPR 2012 Extracts the component tree (if needed) and filter the extremal regions (ER's) by using a given classifier. */ class CV_EXPORTS ERFilter : public cv::Algorithm { public: //! callback with the classifier is made a class. By doing it we hide SVM, Boost etc. class CV_EXPORTS Callback { public: virtual ~Callback(){}; //! The classifier must return probability measure for the region. virtual double eval(const ERStat& stat) = 0; //const = 0; //TODO why cannot use const = 0 here? }; /*! the key method. Takes image on input and returns the selected regions in a vector of ERStat only distinctive ERs which correspond to characters are selected by a sequential classifier \param image is the input image \param regions is output for the first stage, input/output for the second one. */ virtual void run( cv::InputArray image, std::vector<ERStat>& regions ) = 0; //! set/get methods to set the algorithm properties, virtual void setCallback(const cv::Ptr<ERFilter::Callback>& cb) = 0; virtual void setThresholdDelta(int thresholdDelta) = 0; virtual void setMinArea(float minArea) = 0; virtual void setMaxArea(float maxArea) = 0; virtual void setMinProbability(float minProbability) = 0; virtual void setMinProbabilityDiff(float minProbabilityDiff) = 0; virtual void setNonMaxSuppression(bool nonMaxSuppression) = 0; virtual int getNumRejected() = 0; }; /*! Create an Extremal Region Filter for the 1st stage classifier of N&M algorithm Neumann L., Matas J.: Real-Time Scene Text Localization and Recognition, CVPR 2012 The component tree of the image is extracted by a threshold increased step by step from 0 to 255, incrementally computable descriptors (aspect_ratio, compactness, number of holes, and number of horizontal crossings) are computed for each ER and used as features for a classifier which estimates the class-conditional probability P(er|character). The value of P(er|character) is tracked using the inclusion relation of ER across all thresholds and only the ERs which correspond to local maximum of the probability P(er|character) are selected (if the local maximum of the probability is above a global limit pmin and the difference between local maximum and local minimum is greater than minProbabilityDiff). \param cb Callback with the classifier. if omitted tries to load a default classifier from file trained_classifierNM1.xml \param thresholdDelta Threshold step in subsequent thresholds when extracting the component tree \param minArea The minimum area (% of image size) allowed for retreived ER's \param minArea The maximum area (% of image size) allowed for retreived ER's \param minProbability The minimum probability P(er|character) allowed for retreived ER's \param nonMaxSuppression Whenever non-maximum suppression is done over the branch probabilities \param minProbability The minimum probability difference between local maxima and local minima ERs */ CV_EXPORTS cv::Ptr<ERFilter> createERFilterNM1(const cv::Ptr<ERFilter::Callback>& cb = NULL, int thresholdDelta = 1, float minArea = 0.000025, float maxArea = 0.13, float minProbability = 0.2, bool nonMaxSuppression = true, float minProbabilityDiff = 0.1); /*! Create an Extremal Region Filter for the 2nd stage classifier of N&M algorithm Neumann L., Matas J.: Real-Time Scene Text Localization and Recognition, CVPR 2012 In the second stage, the ERs that passed the first stage are classified into character and non-character classes using more informative but also more computationally expensive features. The classifier uses all the features calculated in the first stage and the following additional features: hole area ratio, convex hull ratio, and number of outer inflexion points. \param cb Callback with the classifier if omitted tries to load a default classifier from file trained_classifierNM2.xml \param minProbability The minimum probability P(er|character) allowed for retreived ER's */ CV_EXPORTS cv::Ptr<ERFilter> createERFilterNM2(const cv::Ptr<ERFilter::Callback>& cb = NULL, float minProbability = 0.85); } #endif // _OPENCV_ERFILTER_HPP_ <|endoftext|>
<commit_before>/* * Copyright (C) 2008-2010 The QXmpp developers * * Author: * Manjeet Dahiya * * Source: * http://code.google.com/p/qxmpp * * This file is a part of QXmpp library. * * 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. * */ #include "QXmppDiscoveryManager.h" #include <QDomElement> #include <QCoreApplication> #include "QXmppClient.h" #include "QXmppConstants.h" #include "QXmppDiscoveryIq.h" #include "QXmppStream.h" #include "QXmppGlobal.h" QXmppDiscoveryManager::QXmppDiscoveryManager() : QXmppClientExtension(), m_clientCategory("client"), m_clientType("pc"), m_clientName(QString("%1 %2").arg(qApp->applicationName(), qApp->applicationVersion())) { if(m_clientName.isEmpty()) { m_clientName = QString("%1 %2").arg("Based on QXmpp", QXmppVersion()); } } bool QXmppDiscoveryManager::handleStanza(QXmppStream *stream, const QDomElement &element) { if (element.tagName() == "iq" && QXmppDiscoveryIq::isDiscoveryIq(element)) { QXmppDiscoveryIq receivedIq; receivedIq.parse(element); if(receivedIq.type() == QXmppIq::Get && receivedIq.queryType() == QXmppDiscoveryIq::InfoQuery && (receivedIq.queryNode().isEmpty() || receivedIq.queryNode().startsWith(QString(capabilities_node)))) { // respond to query QXmppDiscoveryIq qxmppFeatures = capabilities(); qxmppFeatures.setId(receivedIq.id()); qxmppFeatures.setTo(receivedIq.from()); qxmppFeatures.setQueryNode(receivedIq.queryNode()); stream->sendPacket(qxmppFeatures); } else if(receivedIq.queryType() == QXmppDiscoveryIq::InfoQuery) emit infoReceived(receivedIq); else if(receivedIq.queryType() == QXmppDiscoveryIq::ItemsQuery) emit itemsReceived(receivedIq); return true; } return false; } QString QXmppDiscoveryManager::requestInfo(const QString& jid, const QString& node) { QXmppDiscoveryIq request; request.setType(QXmppIq::Get); request.setQueryType(QXmppDiscoveryIq::InfoQuery); request.setTo(jid); request.setFrom(client()->configuration().jid()); if(!node.isEmpty()) request.setQueryNode(node); if(client()->sendPacket(request)) return request.id(); else return ""; } QString QXmppDiscoveryManager::requestItems(const QString& jid, const QString& node) { QXmppDiscoveryIq request; request.setType(QXmppIq::Get); request.setQueryType(QXmppDiscoveryIq::ItemsQuery); request.setTo(jid); request.setFrom(client()->configuration().jid()); if(!node.isEmpty()) request.setQueryNode(node); if(client()->sendPacket(request)) return request.id(); else return ""; } QStringList QXmppDiscoveryManager::discoveryFeatures() const { return QStringList() << ns_disco_info; } QXmppDiscoveryIq QXmppDiscoveryManager::capabilities() { QXmppDiscoveryIq iq; iq.setType(QXmppIq::Result); iq.setQueryType(QXmppDiscoveryIq::InfoQuery); // features QStringList features; features << ns_rpc // XEP-0009: Jabber-RPC // << ns_disco_info // XEP-0030: Service Discovery << ns_ibb // XEP-0047: In-Band Bytestreams << ns_vcard // XEP-0054: vcard-temp << ns_bytestreams // XEP-0065: SOCKS5 Bytestreams << ns_chat_states // XEP-0085: Chat State Notifications << ns_stream_initiation // XEP-0095: Stream Initiation << ns_stream_initiation_file_transfer // XEP-0096: SI File Transfer << ns_capabilities // XEP-0115 : Entity Capabilities << ns_jingle // XEP-0166 : Jingle << ns_jingle_rtp // XEP-0167 : Jingle RTP Sessions << ns_jingle_rtp_audio << ns_jingle_ice_udp // XEP-0176 : Jingle ICE-UDP Transport Method << ns_ping; // XEP-0199: XMPP Ping foreach(QXmppClientExtension* extension, client()->extensions()) { if(extension) features << extension->discoveryFeatures(); } iq.setFeatures(features); // TODO: get identities from the extensions itself like the features // identities QList<QXmppDiscoveryIq::Identity> identities; QXmppDiscoveryIq::Identity identity; identity.setCategory("automation"); identity.setType("rpc"); identities.append(identity); identity.setCategory(clientCategory()); identity.setType(clientType()); identity.setName(clientName()); identities.append(identity); iq.setIdentities(identities); return iq; } /// http://xmpp.org/registrar/disco-categories.html#client void QXmppDiscoveryManager::setClientCategory(const QString& category) { m_clientCategory = category; } void QXmppDiscoveryManager::setClientType(const QString& type) { m_clientType = type; } void QXmppDiscoveryManager::setClientName(const QString& name) { m_clientName = name; } QString QXmppDiscoveryManager::clientCategory() { return m_clientCategory; } QString QXmppDiscoveryManager::clientType() { return m_clientType; } QString QXmppDiscoveryManager::clientName() { return m_clientName; } <commit_msg>feature will come from discoveryFeatures<commit_after>/* * Copyright (C) 2008-2010 The QXmpp developers * * Author: * Manjeet Dahiya * * Source: * http://code.google.com/p/qxmpp * * This file is a part of QXmpp library. * * 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. * */ #include "QXmppDiscoveryManager.h" #include <QDomElement> #include <QCoreApplication> #include "QXmppClient.h" #include "QXmppConstants.h" #include "QXmppDiscoveryIq.h" #include "QXmppStream.h" #include "QXmppGlobal.h" QXmppDiscoveryManager::QXmppDiscoveryManager() : QXmppClientExtension(), m_clientCategory("client"), m_clientType("pc"), m_clientName(QString("%1 %2").arg(qApp->applicationName(), qApp->applicationVersion())) { if(m_clientName.isEmpty()) { m_clientName = QString("%1 %2").arg("Based on QXmpp", QXmppVersion()); } } bool QXmppDiscoveryManager::handleStanza(QXmppStream *stream, const QDomElement &element) { if (element.tagName() == "iq" && QXmppDiscoveryIq::isDiscoveryIq(element)) { QXmppDiscoveryIq receivedIq; receivedIq.parse(element); if(receivedIq.type() == QXmppIq::Get && receivedIq.queryType() == QXmppDiscoveryIq::InfoQuery && (receivedIq.queryNode().isEmpty() || receivedIq.queryNode().startsWith(QString(capabilities_node)))) { // respond to query QXmppDiscoveryIq qxmppFeatures = capabilities(); qxmppFeatures.setId(receivedIq.id()); qxmppFeatures.setTo(receivedIq.from()); qxmppFeatures.setQueryNode(receivedIq.queryNode()); stream->sendPacket(qxmppFeatures); } else if(receivedIq.queryType() == QXmppDiscoveryIq::InfoQuery) emit infoReceived(receivedIq); else if(receivedIq.queryType() == QXmppDiscoveryIq::ItemsQuery) emit itemsReceived(receivedIq); return true; } return false; } QString QXmppDiscoveryManager::requestInfo(const QString& jid, const QString& node) { QXmppDiscoveryIq request; request.setType(QXmppIq::Get); request.setQueryType(QXmppDiscoveryIq::InfoQuery); request.setTo(jid); request.setFrom(client()->configuration().jid()); if(!node.isEmpty()) request.setQueryNode(node); if(client()->sendPacket(request)) return request.id(); else return ""; } QString QXmppDiscoveryManager::requestItems(const QString& jid, const QString& node) { QXmppDiscoveryIq request; request.setType(QXmppIq::Get); request.setQueryType(QXmppDiscoveryIq::ItemsQuery); request.setTo(jid); request.setFrom(client()->configuration().jid()); if(!node.isEmpty()) request.setQueryNode(node); if(client()->sendPacket(request)) return request.id(); else return ""; } QStringList QXmppDiscoveryManager::discoveryFeatures() const { return QStringList() << ns_disco_info; } QXmppDiscoveryIq QXmppDiscoveryManager::capabilities() { QXmppDiscoveryIq iq; iq.setType(QXmppIq::Result); iq.setQueryType(QXmppDiscoveryIq::InfoQuery); // features QStringList features; features << ns_rpc // XEP-0009: Jabber-RPC // << ns_disco_info // XEP-0030: Service Discovery << ns_ibb // XEP-0047: In-Band Bytestreams // << ns_vcard // XEP-0054: vcard-temp << ns_bytestreams // XEP-0065: SOCKS5 Bytestreams << ns_chat_states // XEP-0085: Chat State Notifications << ns_stream_initiation // XEP-0095: Stream Initiation << ns_stream_initiation_file_transfer // XEP-0096: SI File Transfer << ns_capabilities // XEP-0115 : Entity Capabilities << ns_jingle // XEP-0166 : Jingle << ns_jingle_rtp // XEP-0167 : Jingle RTP Sessions << ns_jingle_rtp_audio << ns_jingle_ice_udp // XEP-0176 : Jingle ICE-UDP Transport Method << ns_ping; // XEP-0199: XMPP Ping foreach(QXmppClientExtension* extension, client()->extensions()) { if(extension) features << extension->discoveryFeatures(); } iq.setFeatures(features); // TODO: get identities from the extensions itself like the features // identities QList<QXmppDiscoveryIq::Identity> identities; QXmppDiscoveryIq::Identity identity; identity.setCategory("automation"); identity.setType("rpc"); identities.append(identity); identity.setCategory(clientCategory()); identity.setType(clientType()); identity.setName(clientName()); identities.append(identity); iq.setIdentities(identities); return iq; } /// http://xmpp.org/registrar/disco-categories.html#client void QXmppDiscoveryManager::setClientCategory(const QString& category) { m_clientCategory = category; } void QXmppDiscoveryManager::setClientType(const QString& type) { m_clientType = type; } void QXmppDiscoveryManager::setClientName(const QString& name) { m_clientName = name; } QString QXmppDiscoveryManager::clientCategory() { return m_clientCategory; } QString QXmppDiscoveryManager::clientType() { return m_clientType; } QString QXmppDiscoveryManager::clientName() { return m_clientName; } <|endoftext|>
<commit_before>/* $Id$ $URL$ Copyright (c) 1998 - 2012 This file is part of tscan tscan 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. tscan is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. For questions and suggestions, see: or send mail to: */ #include <cstdio> // for remove() #include <cstring> // for strerror() #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <iostream> #include <fstream> #include "config.h" #include "libfolia/folia.h" #include "libfolia/document.h" #include "tscan/Alpino.h" using namespace std; //using namespace TiCC; using namespace folia; void addSU( xmlNode *n, vector<Word*>& words, FoliaElement *s ){ if ( Name( n ) == "node" ){ KWargs atts = getAttributes( n ); string cls = atts["cat"]; bool leaf = false; if ( cls.empty() ){ cls = atts["lcat"]; leaf = true; } if ( !cls.empty() ){ FoliaElement *e = s->append( new SyntacticUnit( s->doc(), "cls='" + cls + "'" ) ); if ( leaf ){ string posS = atts["begin"]; int start = stringTo<int>( posS ); e->append( words[start] ); } else { xmlNode *pnt = n->children; while ( pnt ){ addSU( pnt, words, e ); pnt = pnt->next; } } } } } void extractSyntax( xmlNode *node, Sentence *s ){ Document *doc = s->doc(); doc->declare( AnnotationType::SYNTAX, "mysyntaxse4t", "annotator='alpino'" ); vector<Word*> words = s->words(); FoliaElement *layer = s->append( new SyntaxLayer( doc ) ); FoliaElement *sent = layer->append( new SyntacticUnit( doc, "cls='s'" ) ); xmlNode *pnt = node->children; while ( pnt ){ addSU( pnt, words, sent ); pnt = pnt->next; } } xmlNode *findSubHead( xmlNode *node ){ xmlNode *pnt = node->children; while ( pnt ){ KWargs atts = getAttributes( pnt ); string rel = atts["rel"]; if ( rel == "hd" ){ return pnt; break; } pnt = pnt->next; } return 0; } void addDep( xmlNode *node, vector<Word*>& words, FoliaElement *layer ){ KWargs atts = getAttributes( node ); cerr << "addDep rel=" << atts["rel"] << endl; xmlNode *hd = 0; xmlNode *pnt = node->children; while ( pnt ){ KWargs atts = getAttributes( pnt ); string rel = atts["rel"]; if ( rel == "hd" ){ hd = pnt; break; } pnt = pnt->next; } if ( hd ){ KWargs atts = getAttributes( hd ); string posH = atts["begin"]; int headStart = stringTo<int>( posH ); cerr << "found a head: " << words[headStart]->text() << endl; pnt = node->children; while ( pnt ){ if ( pnt != hd ){ KWargs atts = getAttributes( pnt ); string rel = atts["rel"]; cerr << "bekijk REL=" << rel << endl; FoliaElement *dep = layer->append( new Dependency( layer->doc(), "class='" + rel + "'" ) ); FoliaElement *h = dep->append( new DependencyHead() ); h->append( words[headStart] ); xmlNode *sub = findSubHead( pnt ); if ( !sub ){ cerr << "geen subHead " << endl; string posD = atts["begin"]; int start = stringTo<int>( posD ); FoliaElement *d = dep->append( new DependencyDependent() ); d->append( words[start] ); } else { KWargs atts = getAttributes( sub ); string posD = atts["begin"]; int start = stringTo<int>( posD ); cerr << "er is een subHead " << words[start]->text() << endl; FoliaElement *d = dep->append( new DependencyDependent() ); d->append( words[start] ); addDep( pnt, words, layer ); } } pnt = pnt->next; } } else { cerr << "found no head, recurse " << endl; xmlNode *pnt = node->children; while ( pnt ){ addDep( pnt, words, layer ); pnt = pnt->next; } } } void extractDependency( xmlNode *node, folia::Sentence *s ){ Document *doc = s->doc(); doc->declare( AnnotationType::DEPENDENCY, "mysdepset", "annotator='alpino'" ); vector<Word*> words = s->words(); FoliaElement *layer = s->append( new DependenciesLayer( doc ) ); addDep( node, words, layer ); } void extractAndAppendParse( xmlDoc *doc, folia::Sentence *s ){ cerr << "extract the Alpino results!" << endl; xmlNode *root = xmlDocGetRootElement( doc ); xmlNode *pnt = root->children; while ( pnt ){ if ( folia::Name( pnt ) == "node" ){ cerr << "found a node" << endl; // 1 top node i hope extractSyntax( pnt, s ); extractDependency( pnt, s ); cerr << "added syntax and dependencies " << s->xmlstring() << endl; break; } pnt = pnt->next; } } bool AlpinoParse( folia::Sentence *s ){ string txt = folia::UnicodeToUTF8(s->toktext()); cerr << "parse line: " << txt << endl; struct stat sbuf; int res = stat( "/tmp/alpino", &sbuf ); if ( !S_ISDIR(sbuf.st_mode) ){ res = mkdir( "/tmp/alpino/", S_IRWXU|S_IRWXG ); } res = stat( "/tmp/alpino/parses", &sbuf ); if ( !S_ISDIR(sbuf.st_mode) ){ res = mkdir( "/tmp/alpino/parses", S_IRWXU|S_IRWXG ); } ofstream os( "/tmp/alpino/tempparse.txt" ); os << txt; os.close(); string parseCmd = "Alpino -fast -flag treebank /tmp/alpino/parses end_hook=xml -parse < /tmp/alpino/tempparse.txt -notk > /dev/null 2>&1"; res = system( parseCmd.c_str() ); cerr << "parse res: " << res << endl; remove( "/tmp/alpino/tempparse.txt" ); xmlDoc *xmldoc = xmlReadFile( "/tmp/alpino/parses/1.xml", 0, XML_PARSE_NOBLANKS ); if ( xmldoc ){ extractAndAppendParse( xmldoc, s ); } return (xmldoc != 0 ); } <commit_msg>cleanup <commit_after>/* $Id$ $URL$ Copyright (c) 1998 - 2012 This file is part of tscan tscan 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. tscan is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. For questions and suggestions, see: or send mail to: */ #include <cstdio> // for remove() #include <cstring> // for strerror() #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <iostream> #include <fstream> #include "config.h" #include "libfolia/folia.h" #include "libfolia/document.h" #include "tscan/Alpino.h" using namespace std; using namespace folia; void addSU( xmlNode *n, vector<Word*>& words, FoliaElement *s ){ if ( Name( n ) == "node" ){ KWargs atts = getAttributes( n ); string cls = atts["cat"]; bool leaf = false; if ( cls.empty() ){ cls = atts["lcat"]; leaf = true; } if ( !cls.empty() ){ FoliaElement *e = s->append( new SyntacticUnit( s->doc(), "cls='" + cls + "'" ) ); if ( leaf ){ string posS = atts["begin"]; int start = stringTo<int>( posS ); e->append( words[start] ); } else { xmlNode *pnt = n->children; while ( pnt ){ addSU( pnt, words, e ); pnt = pnt->next; } } } } } void extractSyntax( xmlNode *node, Sentence *s ){ Document *doc = s->doc(); doc->declare( AnnotationType::SYNTAX, "mysyntaxset", "annotator='alpino'" ); vector<Word*> words = s->words(); FoliaElement *layer = s->append( new SyntaxLayer( doc ) ); FoliaElement *sent = layer->append( new SyntacticUnit( doc, "cls='s'" ) ); xmlNode *pnt = node->children; while ( pnt ){ addSU( pnt, words, sent ); pnt = pnt->next; } } xmlNode *findSubHead( xmlNode *node ){ xmlNode *pnt = node->children; while ( pnt ){ KWargs atts = getAttributes( pnt ); string rel = atts["rel"]; if ( rel == "hd" ){ return pnt; break; } pnt = pnt->next; } return 0; } void addDep( xmlNode *node, vector<Word*>& words, FoliaElement *layer ){ KWargs atts = getAttributes( node ); xmlNode *hd = 0; xmlNode *pnt = node->children; while ( pnt ){ KWargs atts = getAttributes( pnt ); string rel = atts["rel"]; if ( rel == "hd" ){ hd = pnt; break; } pnt = pnt->next; } if ( hd ){ KWargs atts = getAttributes( hd ); string posH = atts["begin"]; int headStart = stringTo<int>( posH ); pnt = node->children; while ( pnt ){ if ( pnt != hd ){ KWargs atts = getAttributes( pnt ); string rel = atts["rel"]; FoliaElement *dep = layer->append( new Dependency( layer->doc(), "class='" + rel + "'" ) ); FoliaElement *h = dep->append( new DependencyHead() ); h->append( words[headStart] ); xmlNode *sub = findSubHead( pnt ); if ( !sub ){ string posD = atts["begin"]; int start = stringTo<int>( posD ); FoliaElement *d = dep->append( new DependencyDependent() ); d->append( words[start] ); } else { KWargs atts = getAttributes( sub ); string posD = atts["begin"]; int start = stringTo<int>( posD ); FoliaElement *d = dep->append( new DependencyDependent() ); d->append( words[start] ); addDep( pnt, words, layer ); } } pnt = pnt->next; } } else { xmlNode *pnt = node->children; while ( pnt ){ addDep( pnt, words, layer ); pnt = pnt->next; } } } void extractDependency( xmlNode *node, folia::Sentence *s ){ Document *doc = s->doc(); doc->declare( AnnotationType::DEPENDENCY, "mysdepset", "annotator='alpino'" ); vector<Word*> words = s->words(); FoliaElement *layer = s->append( new DependenciesLayer( doc ) ); addDep( node, words, layer ); } void extractAndAppendParse( xmlDoc *doc, folia::Sentence *s ){ xmlNode *root = xmlDocGetRootElement( doc ); xmlNode *pnt = root->children; while ( pnt ){ if ( folia::Name( pnt ) == "node" ){ // 1 top node i hope extractSyntax( pnt, s ); extractDependency( pnt, s ); break; } pnt = pnt->next; } } bool AlpinoParse( folia::Sentence *s ){ string txt = folia::UnicodeToUTF8(s->toktext()); // cerr << "parse line: " << txt << endl; struct stat sbuf; int res = stat( "/tmp/alpino", &sbuf ); if ( !S_ISDIR(sbuf.st_mode) ){ res = mkdir( "/tmp/alpino/", S_IRWXU|S_IRWXG ); } res = stat( "/tmp/alpino/parses", &sbuf ); if ( !S_ISDIR(sbuf.st_mode) ){ res = mkdir( "/tmp/alpino/parses", S_IRWXU|S_IRWXG ); } ofstream os( "/tmp/alpino/tempparse.txt" ); os << txt; os.close(); string parseCmd = "Alpino -fast -flag treebank /tmp/alpino/parses end_hook=xml -parse < /tmp/alpino/tempparse.txt -notk > /dev/null 2>&1"; res = system( parseCmd.c_str() ); remove( "/tmp/alpino/tempparse.txt" ); xmlDoc *xmldoc = xmlReadFile( "/tmp/alpino/parses/1.xml", 0, XML_PARSE_NOBLANKS ); if ( xmldoc ){ extractAndAppendParse( xmldoc, s ); } return (xmldoc != 0 ); } <|endoftext|>
<commit_before>/** * Clever programming language * Copyright (c) Clever Team * * This file is distributed under the MIT license. See LICENSE for details. */ #include <cmath> #include <vector> #include <cstdlib> #include <cstdio> #include <map> #include <string> #ifndef __APPLE__ # include <ffi.h> #else # include <ffi/ffi.h> #endif #ifdef CLEVER_WIN32 # include <windows.h> #else # include <dlfcn.h> #endif #include "core/clever.h" #include "modules/std/core/function.h" #include "types/type.h" #include "core/value.h" #include "modules/std/ffi/ffi.h" #include "modules/std/ffi/ffistruct.h" #include "modules/std/ffi/ffitypes.h" namespace clever { namespace modules { namespace std { extern "C" { typedef void (*ffi_call_func)(); } #if defined(CLEVER_WIN32) static const char* CLEVER_DYLIB_EXT = ".dll"; #elif defined(CLEVER_APPLE) static const char* CLEVER_DYLIB_EXT = ".dylib"; #else static const char* CLEVER_DYLIB_EXT = ".so"; #endif static ffi_type* _find_ffi_type(FFIType type) { switch (type) { case FFIINT: return &ffi_type_sint32; case FFIDOUBLE: return &ffi_type_double; case FFIBOOL: return &ffi_type_schar; case FFIPOINTER: return &ffi_type_pointer; case FFIVOID: return &ffi_type_void; case FFISTRUCT: return &ffi_type_pointer; case FFISTRING: return &ffi_type_pointer; } return NULL; } static bool _load_lib(FFIData* h, const CString* libname) { if (h->m_lib_handler != NULL) { dlclose(h->m_lib_handler); } h->m_lib_name = *libname; h->m_lib_handler = dlopen((h->m_lib_name + CLEVER_DYLIB_EXT).c_str(), RTLD_LAZY); return h->m_lib_handler != NULL; } /* XXX(heuripedes): please use this function instead of directly calling dlsym * so we don't have to maintain a zilion versions of the same code. */ static inline ffi_call_func _ffi_dlsym(void* handler, const char* name) { #ifdef CLEVER_WIN32 # error "Dynamic library symbol loading support is not yet available for windows. Please disable this module." #endif /* XXX(heuripedes): iso c++ forbids casts between pointer-to-function and * pointer-to-object as .code and .data pointers are not * garanteed to be compatible in some platforms. * THE CODE BELLOW IS A HACK TO SHUT THE COMPILER UP. */ union { void *p; ffi_call_func fp; } u; u.p = dlsym(handler, name); return u.fp; } static inline ffi_call_func _ffi_get_pf(void* lib_handler, const CString* func) { ffi_call_func fpf = _ffi_dlsym(lib_handler, func->c_str()); if (fpf == NULL) { return 0; } return fpf; } static void _ffi_call(Value* result, ffi_call_func pf, size_t n_args, FFIType rt, const ::std::vector<Value*>& args, size_t offset, ExtMemberType* ext_args_types = 0) { ffi_cif cif; ffi_type* ffi_rt = _find_ffi_type(rt); ffi_type** ffi_args = (ffi_type**) malloc(n_args * sizeof(ffi_type*)); void** ffi_values = (void**) malloc(n_args * sizeof(void*)); for (size_t i = 0; i < n_args; ++i) { Value* v = args.at(i + offset); FFIType arg_type = FFIVOID; if (ext_args_types) { arg_type = ext_args_types->at(i + 1); } if (v->isInt()) { if (arg_type == FFIVOID or arg_type == FFIINT) { ffi_args[i] = _find_ffi_type(FFIINT); int* vi= (int*) malloc(sizeof(int)); *vi = v->getInt(); ffi_values[i] = vi; } else { clever_error("Argument %N isn't a int!\n", i + 1); } } else if (v->isBool()) { if (arg_type == FFIVOID or arg_type == FFIBOOL) { ffi_args[i] = _find_ffi_type(FFIBOOL); char* b = (char*) malloc (sizeof(char)); *b = v->getBool(); ffi_values[i] = b; } else { clever_error("Argument %N isn't a bool!\n", i + 1); } } else if (v->isStr()) { if (arg_type == FFIVOID or arg_type == FFISTRING) { const char* st = v->getStr()->c_str(); char** s = (char**) malloc(sizeof(char*)); *s = (char*) malloc (sizeof(char) * (strlen(st) + 1)); strcpy(*s, st); (*s)[strlen(st)] = '\0'; ffi_args[i] = _find_ffi_type(FFISTRING); ffi_values[i] = s; } else { clever_error("Argument %N isn't a string!\n", i + 1); } } else if (v->isDouble()) { if (arg_type == FFIVOID or arg_type == FFIDOUBLE) { ffi_args[i] = _find_ffi_type(FFIDOUBLE);; double* d = (double*) malloc(sizeof(double)); *d = v->getDouble(); ffi_values[i] = d; } else { clever_error("Argument %N isn't a double!\n", i + 1); } } else { if (arg_type == FFIVOID or arg_type == FFIPOINTER) { ffi_args[i] = _find_ffi_type(FFIPOINTER); FFIStructData* obj = static_cast<FFIStructData*>(v->getObj()); ffi_values[i] = &(obj->data); } else { clever_error("Argument %N isn't a pointer!\n", i + 1); } } } if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, n_args, ffi_rt, ffi_args) != FFI_OK) { result->setBool(false); return; } #ifndef CLEVER_WIN32 if (rt == FFIINT) { int vi; ffi_call(&cif, pf, &vi, ffi_values); result->setInt(vi); } else if (rt == FFIDOUBLE) { double vd; ffi_call(&cif, pf, &vd, ffi_values); result->setDouble(vd); } else if (rt == FFIBOOL) { bool vb; ffi_call(&cif, pf, &vb, ffi_values); result->setBool(vb); } else if (rt == FFISTRING) { char* vs[1]; ffi_call(&cif, pf, &vs, ffi_values); result->setStr(CSTRING(*vs)); free(vs[0]); } else if (rt == FFIBOOL) { char vc; ffi_call(&cif, pf, &vc, ffi_values); result->setBool(vc); } else if (rt == FFIVOID) { ffi_call(&cif, pf, NULL, ffi_values); result->setBool(true); } else if (rt == FFIPOINTER) { //FFIObjectValue* x = static_cast<FFIObjectValue*> (retval->getDataValue()); //if ( x == NULL ) x = new FFIObjectValue(); //ffi_call(&cif, pf, &(x->pointer), ffi_values); //CLEVER_RETURN_DATA_VALUE(x); } else { result->setBool(true); } #endif for (size_t i = 0; i < n_args; ++i) { Value* v = args.at(i + offset); if (v->isInt()) { free((int*)ffi_values[i]); } else if (v->isBool()) { free((char*)ffi_values[i]); } else if (v->isStr()) { char** v= (char**)ffi_values[i]; free(v[0]); free(v); } else if (v->isDouble()) { free((double*)ffi_values[i]); } //else if (CLEVER_ARG_IS_INTERNAL(i)) { //} } free(ffi_args); free(ffi_values); } TypeObject* FFI::allocData(CLEVER_TYPE_CTOR_ARGS) const { FFIData* data = new FFIData(this); const CString* name = args->at(0)->getStr(); if (!_load_lib(data, name)) { clever_error("Failed to open %S!", name); } return data; } // FFILib constructor CLEVER_METHOD(FFI::ctor) { if (!clever_check_args("s")) { return; } result->setObj(this, allocData(&args)); } FFIData::~FFIData() { if (m_lib_handler) { dlclose(m_lib_handler); } } Value* FFIData::getMember(const CString* name) const { const_cast<FFIData*>(this)->m_func_name = *name; Value* fvalue = TypeObject::getMember(name); if (fvalue == NULL) { return m_ffi->getCallHandler(); } return fvalue; } CLEVER_METHOD(FFI::callThisFunction) { FFIData* handler = CLEVER_GET_OBJECT(FFIData*, CLEVER_THIS()); const CString func = handler->m_func_name; ExtStruct* ext_struct = FFITypes::getStruct(handler->m_lib_name); FFIType rt = FFIVOID; size_t n_args = args.size(); size_t offset = 0; ExtMemberType* args_types = 0; if (ext_struct) { args_types = ext_struct->getArgs(func); n_args = args_types->size() - 1; rt = args_types->at(0); } else { n_args--; offset = 1; rt = static_cast<FFIType>(args.at(0)->getInt()); } ffi_call_func pf; pf = _ffi_dlsym(handler->m_lib_handler, func.c_str()); if (pf == NULL) { clever_throw("function `%S' don't exist!", &func); return; } _ffi_call(result, pf, n_args, rt, args, offset, args_types); } // FFILib.exec() CLEVER_METHOD(FFI::exec) { if (!clever_check_args("ss*")) { return; } const CString* lib = args.at(0)->getStr(); const CString* func = args.at(1)->getStr(); FFIType rt = static_cast<FFIType>(args.at(2)->getInt()); size_t n_args = args.size() - 3; #ifndef CLEVER_WIN32 void* lib_handler = dlopen((*lib + CLEVER_DYLIB_EXT).c_str(), RTLD_LAZY); ffi_call_func pf = _ffi_get_pf(lib_handler, func); if (pf == 0) { clever_throw("function `%S' don't exist!", func); return; } #endif _ffi_call(result, pf, n_args, rt, args, 3); dlclose(lib_handler); } // FFILib.call() CLEVER_METHOD(FFI::call) { if (!clever_check_args("s*")) { return; } FFIData* handler = CLEVER_GET_OBJECT(FFIData*, CLEVER_THIS()); const CString* func = args.at(0)->getStr(); FFIType rt = static_cast<FFIType>(args.at(1)->getInt()); size_t n_args = args.size() - 2; #ifndef CLEVER_WIN32 ffi_call_func pf = _ffi_get_pf(handler->m_lib_handler, func); if (pf == 0) { clever_throw("function `%S' don't exist!", func); return; } #endif _ffi_call(result, pf, n_args, rt, args, 2); } // FFILib.load() CLEVER_METHOD(FFI::load) { FFIData* data = CLEVER_GET_OBJECT(FFIData*, CLEVER_THIS()); if (!clever_check_args("s")) { return; } result->setBool(_load_lib(data, args.at(0)->getStr())); } // FFILib.unload() CLEVER_METHOD(FFI::unload) { FFIData* data = CLEVER_GET_OBJECT(FFIData*, CLEVER_THIS()); if (data->m_lib_handler != NULL) { dlclose(data->m_lib_handler); data->m_lib_handler = NULL; } } // FFI type initialization CLEVER_TYPE_INIT(FFI::init) { setConstructor((MethodPtr) &FFI::ctor); addMethod(new Function("callThisFunction", (MethodPtr)&FFI::callThisFunction)); addMethod(new Function("call", (MethodPtr)&FFI::call)); addMethod(new Function("exec", (MethodPtr)&FFI::exec))->setStatic(); addMethod(new Function("load", (MethodPtr)&FFI::load)); addMethod(new Function("unload", (MethodPtr)&FFI::unload)); m_call_handler = new Value; m_call_handler->setObj(CLEVER_FUNC_TYPE, new Function("callThisFunction", (MethodPtr)&FFI::callThisFunction)); } // FFI module initialization CLEVER_MODULE_INIT(FFIModule) { addType(new FFI); addType(new FFIStruct); addType(new FFITypes); } }}} // clever::modules::std <commit_msg>FFI function declaration added<commit_after>/** * Clever programming language * Copyright (c) Clever Team * * This file is distributed under the MIT license. See LICENSE for details. */ #include <cmath> #include <vector> #include <cstdlib> #include <cstdio> #include <map> #include <string> #ifndef __APPLE__ # include <ffi.h> #else # include <ffi/ffi.h> #endif #ifdef CLEVER_WIN32 # include <windows.h> #else # include <dlfcn.h> #endif #include "core/clever.h" #include "modules/std/core/function.h" #include "types/type.h" #include "core/value.h" #include "modules/std/ffi/ffi.h" #include "modules/std/ffi/ffistruct.h" #include "modules/std/ffi/ffitypes.h" namespace clever { namespace modules { namespace std { extern "C" { typedef void (*ffi_call_func)(); } #if defined(CLEVER_WIN32) static const char* CLEVER_DYLIB_EXT = ".dll"; #elif defined(CLEVER_APPLE) static const char* CLEVER_DYLIB_EXT = ".dylib"; #else static const char* CLEVER_DYLIB_EXT = ".so"; #endif static ffi_type* _find_ffi_type(FFIType type) { switch (type) { case FFIINT: return &ffi_type_sint32; case FFIDOUBLE: return &ffi_type_double; case FFIBOOL: return &ffi_type_schar; case FFIPOINTER: return &ffi_type_pointer; case FFIVOID: return &ffi_type_void; case FFISTRUCT: return &ffi_type_pointer; case FFISTRING: return &ffi_type_pointer; } return NULL; } static bool _load_lib(FFIData* h, const CString* libname) { if (h->m_lib_handler != NULL) { dlclose(h->m_lib_handler); } h->m_lib_name = *libname; h->m_lib_handler = dlopen((h->m_lib_name + CLEVER_DYLIB_EXT).c_str(), RTLD_LAZY); return h->m_lib_handler != NULL; } /* XXX(heuripedes): please use this function instead of directly calling dlsym * so we don't have to maintain a zilion versions of the same code. */ static inline ffi_call_func _ffi_dlsym(void* handler, const char* name) { #ifdef CLEVER_WIN32 # error "Dynamic library symbol loading support is not yet available for windows. Please disable this module." #endif /* XXX(heuripedes): iso c++ forbids casts between pointer-to-function and * pointer-to-object as .code and .data pointers are not * garanteed to be compatible in some platforms. * THE CODE BELLOW IS A HACK TO SHUT THE COMPILER UP. */ union { void *p; ffi_call_func fp; } u; u.p = dlsym(handler, name); return u.fp; } static inline ffi_call_func _ffi_get_pf(void* lib_handler, const CString* func) { ffi_call_func fpf = _ffi_dlsym(lib_handler, func->c_str()); if (fpf == NULL) { return 0; } return fpf; } static void _ffi_call(Value* result, ffi_call_func pf, size_t n_args, FFIType rt, const ::std::vector<Value*>& args, size_t offset, ExtMemberType* ext_args_types = 0) { ffi_cif cif; ffi_type* ffi_rt = _find_ffi_type(rt); ffi_type** ffi_args = (ffi_type**) malloc(n_args * sizeof(ffi_type*)); void** ffi_values = (void**) malloc(n_args * sizeof(void*)); for (size_t i = 0; i < n_args; ++i) { Value* v = args.at(i + offset); FFIType arg_type = FFIVOID; if (ext_args_types) { arg_type = ext_args_types->at(i + 1); } if (v->isInt()) { if (arg_type == FFIVOID or arg_type == FFIINT) { ffi_args[i] = _find_ffi_type(FFIINT); int* vi= (int*) malloc(sizeof(int)); *vi = v->getInt(); ffi_values[i] = vi; } else { clever_error("Argument %N isn't a int!\n", i + 1); return; } } else if (v->isBool()) { if (arg_type == FFIVOID or arg_type == FFIBOOL) { ffi_args[i] = _find_ffi_type(FFIBOOL); char* b = (char*) malloc (sizeof(char)); *b = v->getBool(); ffi_values[i] = b; } else { clever_error("Argument %N isn't a bool!\n", i + 1); return; } } else if (v->isStr()) { if (arg_type == FFIVOID or arg_type == FFISTRING) { const char* st = v->getStr()->c_str(); char** s = (char**) malloc(sizeof(char*)); *s = (char*) malloc (sizeof(char) * (strlen(st) + 1)); strcpy(*s, st); (*s)[strlen(st)] = '\0'; ffi_args[i] = _find_ffi_type(FFISTRING); ffi_values[i] = s; } else { clever_error("Argument %N isn't a string!\n", i + 1); return; } } else if (v->isDouble()) { if (arg_type == FFIVOID or arg_type == FFIDOUBLE) { ffi_args[i] = _find_ffi_type(FFIDOUBLE);; double* d = (double*) malloc(sizeof(double)); *d = v->getDouble(); ffi_values[i] = d; } else { clever_error("Argument %N isn't a double!\n", i + 1); return; } } else { if (arg_type == FFIVOID or arg_type == FFIPOINTER) { ffi_args[i] = _find_ffi_type(FFIPOINTER); FFIStructData* obj = static_cast<FFIStructData*>(v->getObj()); ffi_values[i] = &(obj->data); } else { clever_error("Argument %N isn't a pointer!\n", i + 1); return; } } } if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, n_args, ffi_rt, ffi_args) != FFI_OK) { result->setBool(false); return; } #ifndef CLEVER_WIN32 if (rt == FFIINT) { int vi; ffi_call(&cif, pf, &vi, ffi_values); result->setInt(vi); } else if (rt == FFIDOUBLE) { double vd; ffi_call(&cif, pf, &vd, ffi_values); result->setDouble(vd); } else if (rt == FFIBOOL) { bool vb; ffi_call(&cif, pf, &vb, ffi_values); result->setBool(vb); } else if (rt == FFISTRING) { char* vs[1]; ffi_call(&cif, pf, &vs, ffi_values); result->setStr(CSTRING(*vs)); free(vs[0]); } else if (rt == FFIBOOL) { char vc; ffi_call(&cif, pf, &vc, ffi_values); result->setBool(vc); } else if (rt == FFIVOID) { ffi_call(&cif, pf, NULL, ffi_values); result->setBool(true); } else if (rt == FFIPOINTER) { //FFIObjectValue* x = static_cast<FFIObjectValue*> (retval->getDataValue()); //if ( x == NULL ) x = new FFIObjectValue(); //ffi_call(&cif, pf, &(x->pointer), ffi_values); //CLEVER_RETURN_DATA_VALUE(x); } else { result->setBool(true); } #endif for (size_t i = 0; i < n_args; ++i) { Value* v = args.at(i + offset); if (v->isInt()) { free((int*)ffi_values[i]); } else if (v->isBool()) { free((char*)ffi_values[i]); } else if (v->isStr()) { char** v= (char**)ffi_values[i]; free(v[0]); free(v); } else if (v->isDouble()) { free((double*)ffi_values[i]); } //else if (CLEVER_ARG_IS_INTERNAL(i)) { //} } free(ffi_args); free(ffi_values); } TypeObject* FFI::allocData(CLEVER_TYPE_CTOR_ARGS) const { FFIData* data = new FFIData(this); const CString* name = args->at(0)->getStr(); if (!_load_lib(data, name)) { clever_error("Failed to open %S!", name); } return data; } // FFILib constructor CLEVER_METHOD(FFI::ctor) { if (!clever_check_args("s")) { return; } result->setObj(this, allocData(&args)); } FFIData::~FFIData() { if (m_lib_handler) { dlclose(m_lib_handler); } } Value* FFIData::getMember(const CString* name) const { const_cast<FFIData*>(this)->m_func_name = *name; Value* fvalue = TypeObject::getMember(name); if (fvalue == NULL) { return m_ffi->getCallHandler(); } return fvalue; } CLEVER_METHOD(FFI::callThisFunction) { FFIData* handler = CLEVER_GET_OBJECT(FFIData*, CLEVER_THIS()); const CString func = handler->m_func_name; ExtStruct* ext_struct = FFITypes::getStruct(handler->m_lib_name); FFIType rt = FFIVOID; size_t n_args = args.size(); size_t offset = 0; ExtMemberType* args_types = 0; if (ext_struct) { args_types = ext_struct->getArgs(func); n_args = args_types->size() - 1; rt = args_types->at(0); } else { n_args--; offset = 1; rt = static_cast<FFIType>(args.at(0)->getInt()); } ffi_call_func pf; pf = _ffi_dlsym(handler->m_lib_handler, func.c_str()); if (pf == NULL) { clever_throw("function `%S' don't exist!", &func); return; } _ffi_call(result, pf, n_args, rt, args, offset, args_types); } // FFILib.exec() CLEVER_METHOD(FFI::exec) { if (!clever_check_args("ss*")) { return; } const CString* lib = args.at(0)->getStr(); const CString* func = args.at(1)->getStr(); FFIType rt = static_cast<FFIType>(args.at(2)->getInt()); size_t n_args = args.size() - 3; #ifndef CLEVER_WIN32 void* lib_handler = dlopen((*lib + CLEVER_DYLIB_EXT).c_str(), RTLD_LAZY); ffi_call_func pf = _ffi_get_pf(lib_handler, func); if (pf == 0) { clever_throw("function `%S' don't exist!", func); return; } #endif _ffi_call(result, pf, n_args, rt, args, 3); dlclose(lib_handler); } // FFILib.call() CLEVER_METHOD(FFI::call) { if (!clever_check_args("s*")) { return; } FFIData* handler = CLEVER_GET_OBJECT(FFIData*, CLEVER_THIS()); const CString* func = args.at(0)->getStr(); FFIType rt = static_cast<FFIType>(args.at(1)->getInt()); size_t n_args = args.size() - 2; #ifndef CLEVER_WIN32 ffi_call_func pf = _ffi_get_pf(handler->m_lib_handler, func); if (pf == 0) { clever_throw("function `%S' don't exist!", func); return; } #endif _ffi_call(result, pf, n_args, rt, args, 2); } // FFILib.load() CLEVER_METHOD(FFI::load) { FFIData* data = CLEVER_GET_OBJECT(FFIData*, CLEVER_THIS()); if (!clever_check_args("s")) { return; } result->setBool(_load_lib(data, args.at(0)->getStr())); } // FFILib.unload() CLEVER_METHOD(FFI::unload) { FFIData* data = CLEVER_GET_OBJECT(FFIData*, CLEVER_THIS()); if (data->m_lib_handler != NULL) { dlclose(data->m_lib_handler); data->m_lib_handler = NULL; } } // FFI type initialization CLEVER_TYPE_INIT(FFI::init) { setConstructor((MethodPtr) &FFI::ctor); addMethod(new Function("callThisFunction", (MethodPtr)&FFI::callThisFunction)); addMethod(new Function("call", (MethodPtr)&FFI::call)); addMethod(new Function("exec", (MethodPtr)&FFI::exec))->setStatic(); addMethod(new Function("load", (MethodPtr)&FFI::load)); addMethod(new Function("unload", (MethodPtr)&FFI::unload)); m_call_handler = new Value; m_call_handler->setObj(CLEVER_FUNC_TYPE, new Function("callThisFunction", (MethodPtr)&FFI::callThisFunction)); } // FFI module initialization CLEVER_MODULE_INIT(FFIModule) { addType(new FFI); addType(new FFIStruct); addType(new FFITypes); } }}} // clever::modules::std <|endoftext|>
<commit_before>// Two dimensional grid class #include <vector> #include <cassert> #include <iostream> template<class T> class Grid2D { public: // This is the default constructor. Call it without any // arguments and it will return a 0x0 matrix (initialized // with 0) // Example // Grid2D<double> g; Grid2D() : rows(0) , cols(0) , data(std::vector<T>(0)) , blocking(0) {} // This is the normal constructor. Gets you a rowsxcols matrix // with optinal default value value // Example // Grid2D<double> square(3, 3, 5.0); Grid2D(const size_t rows, const size_t cols, T value=0, const size_t blocking = 0) : rows(rows) , cols(cols) , data(std::vector<T>(rows*cols, value)) , blocking(0) {} const size_t getRows() const { return rows; } const size_t getCols() const { return cols; } const size_t getBlockingFactor() const { return blocking; } void setBlockingFactor(const size_t factor) { // assert rows and cols beeing multiple of the blocking factor assert(rows % factor == 0); assert(cols % factor == 0); assert(factor > 1 && factor <= std::min(rows, cols)); blocking = factor; } void getBlock(const size_t I, const size_t J, Grid2D<T>& block) { // assert a useful blocking factor assert(blocking > 1); assert(blocking <= std::min(rows, cols)); assert(rows % blocking == 0 && cols % blocking == 0); // assert i/j within bounds assert(I < rows/blocking && J < cols/blocking); // assert block beeing of size blocking x blocking assert(block.getCols() == blocking && block.getRows() == blocking); size_t k = 0; for(size_t i = 0; i < blocking; ++i) { for(size_t j = 0; j < blocking; ++j) { block.data[k++] = data[(I*blocking+i)*cols + J*blocking+j]; } } assert(k == blocking * blocking); } void setBlock(const size_t I, const size_t J, const Grid2D<T>& block) { // assert a useful blocking factor assert(blocking > 1); assert(blocking <= std::min(rows, cols)); assert(rows % blocking == 0 && cols % blocking == 0); // assert i/j within bounds assert(I < rows/blocking && J < cols/blocking); // assert block beeing of size blocking x blocking assert(block.getCols() == blocking && block.getRows() == blocking); size_t k = 0; for(size_t i = 0; i < blocking; ++i) { for(size_t j = 0; j < blocking; ++j) { data[(I*blocking+i)*cols + J*blocking+j] = block.data[k++]; } } } // This is the copy constructor. // Example // Grid2D<int> g(3, 3, 0); // Grid2D<int> copy(g); Grid2D(const Grid2D<T>& g) : rows(g.rows) , cols(g.cols) , data(g.data) , blocking(g.blocking) {} // This is the assignment operator // Example // Grid2D<double> g(3, 4, 5.0); // Grid2D<int> g2; // g2 = g; Grid2D& operator=(Grid2D<T> g) { using std::swap; swap(*this, g); return *this; } // This is for writing to location (i,j) T& operator()(const size_t i, const size_t j) { assert(i < rows); assert(j < cols); return data[i*cols + j]; } // This is for reading from location (i,j) const T& operator()(const size_t i, const size_t j) const { assert(i < rows); assert(j < cols); return data[i*cols + j]; } template<class U> friend void swap(Grid2D<U>& left, Grid2D<U>& right); private: size_t rows; size_t cols; std::vector<T> data; size_t blocking; }; template<class T> std::ostream& operator<<(std::ostream& out, const Grid2D<T>& g) { if(g.getBlockingFactor() > 1) { out << "Blocking factor: " << g.getBlockingFactor() << "\n"; } for(size_t i = 0; i < g.getRows(); ++i) { if(g.getBlockingFactor() > 1 && i > 0 && i % g.getBlockingFactor() == 0) { for(size_t k = 0; k < g.getCols() + g.getCols() / g.getBlockingFactor() - 1; ++k) { out << "-\t"; } out << "\n"; } for(size_t j = 0; j < g.getCols(); ++j) { if(g.getBlockingFactor() > 1 && j > 0 && j % g.getBlockingFactor() == 0) { out << "|\t"; } out << g(i, j) << "\t"; } out << "\n"; } return out; } template<class T> void swap(Grid2D<T>& left, Grid2D<T>& right) { std::swap(left.rows, right.rows); std::swap(left.cols, right.cols); std::swap(left.data, right.data); std::swap(left.blocking, right.blocking); } <commit_msg>rename blockingFactor to blockSize, what it actually is<commit_after>// Two dimensional grid class #include <vector> #include <cassert> #include <iostream> #include <limits> template<class T> class Grid2D { public: // This is the default constructor. Call it without any // arguments and it will return a 0x0 matrix (initialized // with 0) // Example // Grid2D<double> g; Grid2D() : rows(0) , cols(0) , data(std::vector<T>(0)) , blockSize(0) {} // This is the normal constructor. Gets you a rowsxcols matrix // with optinal default value value // Example // Grid2D<double> square(3, 3, 5.0); Grid2D(const size_t rows, const size_t cols, T value=0, const size_t blockSize = 0) : rows(rows) , cols(cols) , data(std::vector<T>(rows*cols, value)) , blockSize(0) {} const size_t getRows() const { return rows; } const size_t getCols() const { return cols; } const size_t getBlockSize() const { return blockSize; } void setBlockSize(const size_t size) { // assert rows and cols beeing multiple of the block size assert(rows % size == 0); assert(cols % size == 0); assert(size > 1 && size <= std::min(rows, cols)); blockSize = size; } void getBlock(const size_t I, const size_t J, Grid2D<T>& block) { // assert a useful block size assert(blockSize > 1); assert(blockSize <= std::min(rows, cols)); assert(rows % blockSize == 0 && cols % blockSize == 0); // assert i/j within bounds assert(I < rows/blockSize && J < cols/blockSize); // assert block beeing of size blockSize x blockSize assert(block.getCols() == blockSize && block.getRows() == blockSize); size_t k = 0; for(size_t i = 0; i < blockSize; ++i) { for(size_t j = 0; j < blockSize; ++j) { block.data[k++] = data[(I*blockSize+i)*cols + J*blockSize+j]; } } assert(k == blockSize * blockSize); } void setBlock(const size_t I, const size_t J, const Grid2D<T>& block) { // assert a useful blockSize factor assert(blockSize > 1); assert(blockSize <= std::min(rows, cols)); assert(rows % blockSize == 0 && cols % blockSize == 0); // assert i/j within bounds assert(I < rows/blockSize && J < cols/blockSize); // assert block beeing of size blockSize x blockSize assert(block.getCols() == blockSize && block.getRows() == blockSize); size_t k = 0; for(size_t i = 0; i < blockSize; ++i) { for(size_t j = 0; j < blockSize; ++j) { data[(I*blockSize+i)*cols + J*blockSize+j] = block.data[k++]; } } } // This is the copy constructor. // Example // Grid2D<int> g(3, 3, 0); // Grid2D<int> copy(g); Grid2D(const Grid2D<T>& g) : rows(g.rows) , cols(g.cols) , data(g.data) , blockSize(g.blockSize) {} // This is the assignment operator // Example // Grid2D<double> g(3, 4, 5.0); // Grid2D<int> g2; // g2 = g; Grid2D& operator=(Grid2D<T> g) { using std::swap; swap(*this, g); return *this; } // This is for writing to location (i,j) T& operator()(const size_t i, const size_t j) { assert(i < rows); assert(j < cols); return data[i*cols + j]; } // This is for reading from location (i,j) const T& operator()(const size_t i, const size_t j) const { assert(i < rows); assert(j < cols); return data[i*cols + j]; } template<class U> friend void swap(Grid2D<U>& left, Grid2D<U>& right); private: size_t rows; size_t cols; std::vector<T> data; size_t blockSize; }; template<class T> std::ostream& operator<<(std::ostream& out, const Grid2D<T>& g) { if(g.getBlockSize() > 1) { out << "Block size: " << g.getBlockSize() << "\n"; } for(size_t i = 0; i < g.getRows(); ++i) { if(g.getBlockSize() > 1 && i > 0 && i % g.getBlockSize() == 0) { for(size_t k = 0; k < g.getCols() + g.getCols() / g.getBlockSize() - 1; ++k) { out << "-\t"; } out << "\n"; } for(size_t j = 0; j < g.getCols(); ++j) { if(g.getBlockSize() > 1 && j > 0 && j % g.getBlockSize() == 0) { out << "|\t"; } out << ((g(i, j) == std::numeric_limits<T>::max()) ? 12345 : g(i,j)) << "\t"; } out << "\n"; } return out; } template<class T> void swap(Grid2D<T>& left, Grid2D<T>& right) { std::swap(left.rows, right.rows); std::swap(left.cols, right.cols); std::swap(left.data, right.data); std::swap(left.blockSize, right.blockSize); } <|endoftext|>
<commit_before>// Virvo - Virtual Reality Volume Rendering // Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University // Contact: Jurgen P. Schulze, [email protected] // // This file is part of Virvo. // // Virvo 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 (see license.txt); if not, write to the // Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #ifdef HAVE_CONFIG_H #include "vvconfig.h" #endif #ifdef VV_DEBUG_MEMORY #include <crtdbg.h> #define new new(_NORMAL_BLOCK,__FILE__, __LINE__) #endif #include "vvresourcemanager.h" #include "vvserver.h" #include <virvo/vvdebugmsg.h> #include <virvo/vvibrserver.h> #include <virvo/vvimageserver.h> #include <virvo/vvremoteserver.h> #include <virvo/vvrendererfactory.h> #include <virvo/vvsocketio.h> #include <virvo/vvtcpserver.h> #include <virvo/vvtcpsocket.h> #include <virvo/vvtoolshed.h> #include <virvo/vvvirvo.h> #include <virvo/vvvoldesc.h> #include <iostream> #include <limits> #include <pthread.h> const int vvServer::DEFAULTSIZE = 512; const int vvServer::DEFAULT_PORT = 31050; using std::cerr; using std::endl; vvServer::vvServer() { _port = vvServer::DEFAULT_PORT; _sm = SERVER; _useBonjour = false; } vvServer::~vvServer() { } int vvServer::run(int argc, char** argv) { vvDebugMsg::msg(3, "vvServer::run()"); cerr << "Virvo server " << virvo::getVersionMajor() << "." << virvo::getReleaseCounter() << endl; cerr << "(c) " << virvo::getYearOfRelease() << " Juergen Schulze ([email protected])" << endl; cerr << "Brown University" << endl << endl; if(!parseCommandLine(argc, argv)) return 1; if(serverLoop()) return 0; else return 1; } void vvServer::displayHelpInfo() { vvDebugMsg::msg(3, "vvServer::displayHelpInfo()"); cerr << "Syntax:" << endl; cerr << endl; cerr << " vserver [options]" << endl; cerr << endl; cerr << "Available options:" << endl; cerr << endl; cerr << "-port" << endl; cerr << " Don't use the default port (" << DEFAULT_PORT << "), but the specified one" << endl; cerr << endl; cerr << "-mode" << endl; cerr << " Start vvServer with one of the following modes:" << endl; cerr << " s single server (default)" << endl; cerr << " rm resource manager" << endl; cerr << " rm+s server and resource manager simultanously" << endl; cerr << endl; #ifdef HAVE_BONJOUR cerr << "-bonjour" << endl; cerr << " use bonjour to broadcast this service. options:" << endl; cerr << " on" << endl; cerr << " off (default)" << endl; cerr << endl; #endif cerr << "-debug" << endl; cerr << " Set debug level" << endl; cerr << endl; } bool vvServer::parseCommandLine(int argc, char** argv) { vvDebugMsg::msg(1, "vvServer::parseCommandLine()"); for (int arg=1; arg<argc; ++arg) { if (vvToolshed::strCompare(argv[arg], "-help")==0 || vvToolshed::strCompare(argv[arg], "-h")==0 || vvToolshed::strCompare(argv[arg], "-?")==0 || vvToolshed::strCompare(argv[arg], "/?")==0) { displayHelpInfo(); return false; } else if (vvToolshed::strCompare(argv[arg], "-port")==0) { if ((++arg)>=argc) { cerr << "No port specified" << endl; return false; } else { int inport = atoi(argv[arg]); if(inport > std::numeric_limits<ushort>::max() || inport <= std::numeric_limits<ushort>::min()) { cerr << "Specified port is out of range. Falling back to default: " << vvServer::DEFAULT_PORT << endl; _port = vvServer::DEFAULT_PORT; } else _port = inport; } } else if (vvToolshed::strCompare(argv[arg], "-mode")==0) { if ((++arg)>=argc) { cerr << "Mode type missing." << endl; return false; } if (vvToolshed::strCompare(argv[arg], "s")==0) { _sm = SERVER; } else if(vvToolshed::strCompare(argv[arg], "rm")==0) { _sm = RM; } else if(vvToolshed::strCompare(argv[arg], "rm+s")==0) { _sm = RM_WITH_SERVER; } else { cerr << "Unknown mode type." << endl; return false; } } #ifdef HAVE_BONJOUR else if (vvToolshed::strCompare(argv[arg], "-bonjour")==0) { if ((++arg)>=argc) { cerr << "Bonjour setting missing." << endl; return false; } if (vvToolshed::strCompare(argv[arg], "on")==0) { _useBonjour = true; } else if(vvToolshed::strCompare(argv[arg], "off")==0) { _useBonjour = false; } else { cerr << "Unknown bonjour setting." << endl; return false; } } #endif else if (vvToolshed::strCompare(argv[arg], "-debug")==0) { if ((++arg)>=argc) { cerr << "Debug level missing." << endl; return false; } int level = atoi(argv[arg]); if (level>=0 && level<=3) vvDebugMsg::setDebugLevel(level); else { cerr << "Invalid debug level." << endl; return false; } } else { cerr << "Unknown option/parameter: \"" << argv[arg] << "\", use -help for instructions" << endl; return false; } } return true; } bool vvServer::serverLoop() { vvTcpServer tcpServ = vvTcpServer(_port); if(!tcpServ.initStatus()) { cerr << "Failed to initialize server-socket on port " << _port << "." << endl; return false; } else { #ifdef HAVE_BONJOUR if(_useBonjour) registerToBonjour(); #endif } vvResourceManager *rm = NULL; if(RM == _sm) { rm = new vvResourceManager(); } else if(RM_WITH_SERVER == _sm) { rm = new vvResourceManager(this); } while (1) { cerr << "Listening on port " << _port << endl; vvTcpSocket *sock = NULL; while((sock = tcpServ.nextConnection()) == NULL) { vvDebugMsg::msg(3, "vvServer::serverLoop() Listening socket blocked, retry..."); } if(sock == NULL) { cerr << "vvServer::serverLoop() Failed to initialize server-socket on port " << _port << endl; break; } else { cerr << "Incoming connection..." << endl; if(RM == _sm || RM_WITH_SERVER == _sm) { rm->addJob(sock); } else { handleClient(sock); } } } #ifdef HAVE_BONJOUR if(_useBonjour) unregisterFromBonjour(); #endif delete rm; return true; } #ifdef HAVE_BONJOUR DNSServiceErrorType vvServer::registerToBonjour() { vvDebugMsg::msg(3, "vvServer::registerToBonjour()"); vvBonjourEntry entry = vvBonjourEntry("Virvo Server", "_vserver._tcp", ""); return _registrar.registerService(entry, _port); } void vvServer::unregisterFromBonjour() { vvDebugMsg::msg(3, "vvServer::unregisterFromBonjour()"); _registrar.unregisterService(); } #endif void vvServer::handleClient(vvTcpSocket *sock) { vvServerThreadArgs *args = new vvServerThreadArgs; args->_sock = sock; args->_exitFunc = NULL; pthread_t pthread; pthread_create(&pthread, NULL, handleClientThread, args); pthread_detach(pthread); } void * vvServer::handleClientThread(void *param) { vvServerThreadArgs *args = reinterpret_cast<vvServerThreadArgs*>(param); if(args->_exitFunc == NULL) { args->_exitFunc = &vvServer::exitCallback; } pthread_cleanup_push(args->_exitFunc, NULL); vvTcpSocket *sock = args->_sock; vvSocketIO *sockio = new vvSocketIO(sock); vvRemoteServer* server = NULL; sockio->putBool(true); // let client know we are ready int getType; sockio->getInt32(getType); vvRenderer::RendererType rType = (vvRenderer::RendererType)getType; switch(rType) { case vvRenderer::REMOTE_IMAGE: server = new vvImageServer(sockio); break; case vvRenderer::REMOTE_IBR: server = new vvIbrServer(sockio); break; default: cerr << "Unknown remote rendering type " << rType << std::endl; break; } if(!server) { pthread_exit(NULL); #ifdef _WIN32 return NULL; #endif } vvVolDesc *vd = NULL; if(server->initRenderContext(DEFAULTSIZE, DEFAULTSIZE) != vvRemoteServer::VV_OK) { cerr << "Couldn't initialize render context" << std::endl; goto cleanup; } vvGLTools::enableGLErrorBacktrace(); if(server->initData(vd) != vvRemoteServer::VV_OK) { cerr << "Could not initialize volume data" << endl; cerr << "Continuing with next client..." << endl; goto cleanup; } if(vd != NULL) { if(server->getLoadVolumeFromFile()) { vd->printInfoLine(); } // Set default color scheme if no TF present: if(vd->tf.isEmpty()) { vd->tf.setDefaultAlpha(0, 0.0, 1.0); vd->tf.setDefaultColors((vd->chan==1) ? 0 : 2, 0.0, 1.0); } vvRenderState rs; vvRenderer *renderer = vvRendererFactory::create(vd, rs, rType==vvRenderer::REMOTE_IBR ? "rayrend" : "default", ""); if(rType == vvRenderer::REMOTE_IBR) renderer->setParameter(vvRenderer::VV_USE_IBR, 1.f); while(1) { if(!server->processEvents(renderer)) { delete renderer; renderer = NULL; break; } } } cleanup: server->destroyRenderContext(); // Frames vector with bricks is deleted along with the renderer. // Don't free them here. // see setRenderer(). delete server; server = NULL; delete sockio; sockio = NULL; sock->disconnectFromHost(); delete sock; sock = NULL; delete vd; vd = NULL; pthread_exit(NULL); pthread_cleanup_pop(0); #ifdef _WIN32 return NULL; #endif } /*vvServer *s = NULL; void sigproc(int ) { // NOTE some versions of UNIX will reset signal to default // after each call. So for portability set signal each time signal(SIGINT, sigproc); cerr << "you have pressed ctrl-c" << endl; delete s; s = NULL; }*/ //------------------------------------------------------------------- /// Main entry point. int main(int argc, char** argv) { // signal(SIGINT, sigproc); #ifdef VV_DEBUG_MEMORY int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);// Get current flag flag |= _CRTDBG_LEAK_CHECK_DF; // Turn on leak-checking bit flag |= _CRTDBG_CHECK_ALWAYS_DF; _CrtSetDbgFlag(flag); // Set flag to the new value #endif #ifdef VV_DEBUG_MEMORY _CrtMemState s1, s2, s3; _CrtCheckMemory(); _CrtMemCheckpoint( &s1 ); #endif // do stuff to test memory difference for #ifdef VV_DEBUG_MEMORY _CrtMemCheckpoint( &s2 ); if ( _CrtMemDifference( &s3, &s1, &s2 ) ) _CrtMemDumpStatistics( &s3 ); _CrtCheckMemory(); #endif // do stuff to verify memory status after #ifdef VV_DEBUG_MEMORY _CrtCheckMemory(); #endif //vvDebugMsg::setDebugLevel(vvDebugMsg::NO_MESSAGES); vvServer vserver; int error = vserver.run(argc, argv); #ifdef VV_DEBUG_MEMORY _CrtDumpMemoryLeaks(); // display memory leaks, if any #endif return error; } //=================================================================== // End of File //=================================================================== // vim: sw=2:expandtab:softtabstop=2:ts=2:cino=\:0g0t0 <commit_msg>vserver fix: do not allow modes that don't work<commit_after>// Virvo - Virtual Reality Volume Rendering // Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University // Contact: Jurgen P. Schulze, [email protected] // // This file is part of Virvo. // // Virvo 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 (see license.txt); if not, write to the // Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #ifdef HAVE_CONFIG_H #include "vvconfig.h" #endif #ifdef VV_DEBUG_MEMORY #include <crtdbg.h> #define new new(_NORMAL_BLOCK,__FILE__, __LINE__) #endif #include "vvresourcemanager.h" #include "vvserver.h" #include <virvo/vvdebugmsg.h> #include <virvo/vvibrserver.h> #include <virvo/vvimageserver.h> #include <virvo/vvremoteserver.h> #include <virvo/vvrendererfactory.h> #include <virvo/vvsocketio.h> #include <virvo/vvtcpserver.h> #include <virvo/vvtcpsocket.h> #include <virvo/vvtoolshed.h> #include <virvo/vvvirvo.h> #include <virvo/vvvoldesc.h> #include <iostream> #include <limits> #include <pthread.h> const int vvServer::DEFAULTSIZE = 512; const int vvServer::DEFAULT_PORT = 31050; using std::cerr; using std::endl; vvServer::vvServer() { _port = vvServer::DEFAULT_PORT; _sm = SERVER; _useBonjour = false; } vvServer::~vvServer() { } int vvServer::run(int argc, char** argv) { vvDebugMsg::msg(3, "vvServer::run()"); cerr << "Virvo server " << virvo::getVersionMajor() << "." << virvo::getReleaseCounter() << endl; cerr << "(c) " << virvo::getYearOfRelease() << " Juergen Schulze ([email protected])" << endl; cerr << "Brown University" << endl << endl; if(!parseCommandLine(argc, argv)) return 1; if(serverLoop()) return 0; else return 1; } void vvServer::displayHelpInfo() { vvDebugMsg::msg(3, "vvServer::displayHelpInfo()"); cerr << "Syntax:" << endl; cerr << endl; cerr << " vserver [options]" << endl; cerr << endl; cerr << "Available options:" << endl; cerr << endl; cerr << "-port" << endl; cerr << " Don't use the default port (" << DEFAULT_PORT << "), but the specified one" << endl; cerr << endl; #ifdef HAVE_BONJOUR cerr << "-mode" << endl; cerr << " Start vvServer with one of the following modes:" << endl; cerr << " s single server (default)" << endl; cerr << " rm resource manager" << endl; cerr << " rm+s server and resource manager simultanously" << endl; cerr << endl; cerr << "-bonjour" << endl; cerr << " use bonjour to broadcast this service. options:" << endl; cerr << " on" << endl; cerr << " off (default)" << endl; cerr << endl; #endif cerr << "-debug" << endl; cerr << " Set debug level" << endl; cerr << endl; } bool vvServer::parseCommandLine(int argc, char** argv) { vvDebugMsg::msg(1, "vvServer::parseCommandLine()"); for (int arg=1; arg<argc; ++arg) { if (vvToolshed::strCompare(argv[arg], "-help")==0 || vvToolshed::strCompare(argv[arg], "-h")==0 || vvToolshed::strCompare(argv[arg], "-?")==0 || vvToolshed::strCompare(argv[arg], "/?")==0) { displayHelpInfo(); return false; } else if (vvToolshed::strCompare(argv[arg], "-port")==0) { if ((++arg)>=argc) { cerr << "No port specified" << endl; return false; } else { int inport = atoi(argv[arg]); if(inport > std::numeric_limits<ushort>::max() || inport <= std::numeric_limits<ushort>::min()) { cerr << "Specified port is out of range. Falling back to default: " << vvServer::DEFAULT_PORT << endl; _port = vvServer::DEFAULT_PORT; } else _port = inport; } } #ifdef HAVE_BONJOUR else if (vvToolshed::strCompare(argv[arg], "-mode")==0) { if ((++arg)>=argc) { cerr << "Mode type missing." << endl; return false; } if (vvToolshed::strCompare(argv[arg], "s")==0) { _sm = SERVER; } else if(vvToolshed::strCompare(argv[arg], "rm")==0) { _sm = RM; } else if(vvToolshed::strCompare(argv[arg], "rm+s")==0) { _sm = RM_WITH_SERVER; } else { cerr << "Unknown mode type." << endl; return false; } } else if (vvToolshed::strCompare(argv[arg], "-bonjour")==0) { if ((++arg)>=argc) { cerr << "Bonjour setting missing." << endl; return false; } if (vvToolshed::strCompare(argv[arg], "on")==0) { _useBonjour = true; } else if(vvToolshed::strCompare(argv[arg], "off")==0) { _useBonjour = false; } else { cerr << "Unknown bonjour setting." << endl; return false; } } #endif else if (vvToolshed::strCompare(argv[arg], "-debug")==0) { if ((++arg)>=argc) { cerr << "Debug level missing." << endl; return false; } int level = atoi(argv[arg]); if (level>=0 && level<=3) vvDebugMsg::setDebugLevel(level); else { cerr << "Invalid debug level." << endl; return false; } } else { cerr << "Unknown option/parameter: \"" << argv[arg] << "\", use -help for instructions" << endl; return false; } } return true; } bool vvServer::serverLoop() { vvTcpServer tcpServ = vvTcpServer(_port); if(!tcpServ.initStatus()) { cerr << "Failed to initialize server-socket on port " << _port << "." << endl; return false; } else { #ifdef HAVE_BONJOUR if(_useBonjour) registerToBonjour(); #endif } vvResourceManager *rm = NULL; if(RM == _sm) { rm = new vvResourceManager(); } else if(RM_WITH_SERVER == _sm) { rm = new vvResourceManager(this); } while (1) { cerr << "Listening on port " << _port << endl; vvTcpSocket *sock = NULL; while((sock = tcpServ.nextConnection()) == NULL) { vvDebugMsg::msg(3, "vvServer::serverLoop() Listening socket blocked, retry..."); } if(sock == NULL) { cerr << "vvServer::serverLoop() Failed to initialize server-socket on port " << _port << endl; break; } else { cerr << "Incoming connection..." << endl; if(RM == _sm || RM_WITH_SERVER == _sm) { rm->addJob(sock); } else { handleClient(sock); } } } #ifdef HAVE_BONJOUR if(_useBonjour) unregisterFromBonjour(); #endif delete rm; return true; } #ifdef HAVE_BONJOUR DNSServiceErrorType vvServer::registerToBonjour() { vvDebugMsg::msg(3, "vvServer::registerToBonjour()"); vvBonjourEntry entry = vvBonjourEntry("Virvo Server", "_vserver._tcp", ""); return _registrar.registerService(entry, _port); } void vvServer::unregisterFromBonjour() { vvDebugMsg::msg(3, "vvServer::unregisterFromBonjour()"); _registrar.unregisterService(); } #endif void vvServer::handleClient(vvTcpSocket *sock) { vvServerThreadArgs *args = new vvServerThreadArgs; args->_sock = sock; args->_exitFunc = NULL; pthread_t pthread; pthread_create(&pthread, NULL, handleClientThread, args); pthread_detach(pthread); } void * vvServer::handleClientThread(void *param) { vvServerThreadArgs *args = reinterpret_cast<vvServerThreadArgs*>(param); if(args->_exitFunc == NULL) { args->_exitFunc = &vvServer::exitCallback; } pthread_cleanup_push(args->_exitFunc, NULL); vvTcpSocket *sock = args->_sock; vvSocketIO *sockio = new vvSocketIO(sock); vvRemoteServer* server = NULL; sockio->putBool(true); // let client know we are ready int getType; sockio->getInt32(getType); vvRenderer::RendererType rType = (vvRenderer::RendererType)getType; switch(rType) { case vvRenderer::REMOTE_IMAGE: server = new vvImageServer(sockio); break; case vvRenderer::REMOTE_IBR: server = new vvIbrServer(sockio); break; default: cerr << "Unknown remote rendering type " << rType << std::endl; break; } if(!server) { pthread_exit(NULL); #ifdef _WIN32 return NULL; #endif } vvVolDesc *vd = NULL; if(server->initRenderContext(DEFAULTSIZE, DEFAULTSIZE) != vvRemoteServer::VV_OK) { cerr << "Couldn't initialize render context" << std::endl; goto cleanup; } vvGLTools::enableGLErrorBacktrace(); if(server->initData(vd) != vvRemoteServer::VV_OK) { cerr << "Could not initialize volume data" << endl; cerr << "Continuing with next client..." << endl; goto cleanup; } if(vd != NULL) { if(server->getLoadVolumeFromFile()) { vd->printInfoLine(); } // Set default color scheme if no TF present: if(vd->tf.isEmpty()) { vd->tf.setDefaultAlpha(0, 0.0, 1.0); vd->tf.setDefaultColors((vd->chan==1) ? 0 : 2, 0.0, 1.0); } vvRenderState rs; vvRenderer *renderer = vvRendererFactory::create(vd, rs, rType==vvRenderer::REMOTE_IBR ? "rayrend" : "default", ""); if(rType == vvRenderer::REMOTE_IBR) renderer->setParameter(vvRenderer::VV_USE_IBR, 1.f); while(1) { if(!server->processEvents(renderer)) { delete renderer; renderer = NULL; break; } } } cleanup: server->destroyRenderContext(); // Frames vector with bricks is deleted along with the renderer. // Don't free them here. // see setRenderer(). delete server; server = NULL; delete sockio; sockio = NULL; sock->disconnectFromHost(); delete sock; sock = NULL; delete vd; vd = NULL; pthread_exit(NULL); pthread_cleanup_pop(0); #ifdef _WIN32 return NULL; #endif } /*vvServer *s = NULL; void sigproc(int ) { // NOTE some versions of UNIX will reset signal to default // after each call. So for portability set signal each time signal(SIGINT, sigproc); cerr << "you have pressed ctrl-c" << endl; delete s; s = NULL; }*/ //------------------------------------------------------------------- /// Main entry point. int main(int argc, char** argv) { // signal(SIGINT, sigproc); #ifdef VV_DEBUG_MEMORY int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);// Get current flag flag |= _CRTDBG_LEAK_CHECK_DF; // Turn on leak-checking bit flag |= _CRTDBG_CHECK_ALWAYS_DF; _CrtSetDbgFlag(flag); // Set flag to the new value #endif #ifdef VV_DEBUG_MEMORY _CrtMemState s1, s2, s3; _CrtCheckMemory(); _CrtMemCheckpoint( &s1 ); #endif // do stuff to test memory difference for #ifdef VV_DEBUG_MEMORY _CrtMemCheckpoint( &s2 ); if ( _CrtMemDifference( &s3, &s1, &s2 ) ) _CrtMemDumpStatistics( &s3 ); _CrtCheckMemory(); #endif // do stuff to verify memory status after #ifdef VV_DEBUG_MEMORY _CrtCheckMemory(); #endif //vvDebugMsg::setDebugLevel(vvDebugMsg::NO_MESSAGES); vvServer vserver; int error = vserver.run(argc, argv); #ifdef VV_DEBUG_MEMORY _CrtDumpMemoryLeaks(); // display memory leaks, if any #endif return error; } //=================================================================== // End of File //=================================================================== // vim: sw=2:expandtab:softtabstop=2:ts=2:cino=\:0g0t0 <|endoftext|>
<commit_before>#include <telebotxx/BotApi.hpp> #include <telebotxx/Exception.hpp> #include <sstream> #include <rapidjson/document.h> #include <rapidjson/writer.h> #include <rapidjson/istreamwrapper.h> #include <curlpp/cURLpp.hpp> #include <curlpp/Easy.hpp> #include <curlpp/Options.hpp> #include <boost/log/trivial.hpp> namespace telebotxx { const rapidjson::Value& parseResponse(const rapidjson::Document& doc) { using namespace rapidjson; if (!doc.IsObject()) throw ParseError("Object expected"); // Get status if (!doc.HasMember("ok") || !doc["ok"].IsBool()) throw ParseError("Field 'ok' not found or has invalid type"); bool ok = doc["ok"].GetBool(); if (ok) { if (!doc.HasMember("result") || !doc["result"].IsObject()) throw ParseError("Field 'result' not found or has invalid type"); return doc["result"]; } else { if (!doc.HasMember("error_code") || !doc["error_code"].IsInt()) throw ParseError("Field 'error_code' not found or has invalid type"); int code = doc["error_code"].GetInt(); if (!doc.HasMember("description") || !doc["description"].IsString()) throw ParseError("Field 'description' not found or has invalid type"); std::string description(doc["description"].GetString()); throw ApiError(code, description); } } User parseUser(const rapidjson::Value& obj) { if (!obj.HasMember("id") || !obj["id"].IsInt()) throw ParseError("Field 'id' not found or has invalid type"); int id = obj["id"].GetInt(); if (!obj.HasMember("first_name") || !obj["first_name"].IsString()) throw ParseError("Field 'first_name' not found or has invalid type"); std::string firstName(obj["first_name"].GetString()); std::string lastName; if (obj.HasMember("last_name")) { if (obj["last_name"].IsString()) lastName = obj["last_name"].GetString(); else throw ParseError("Field 'last_name' has invalid type"); } std::string username; if (obj.HasMember("username")) { if (obj["username"].IsString()) username = obj["username"].GetString(); else throw ParseError("Field 'username' has invalid type"); } return User(id, firstName, lastName, username); } } using namespace telebotxx; class BotApi::Impl { public: Impl(const std::string& token) : token_(token) { telegramMainUrl_ = "https://api.telegram.org/bot" + token_; botUser_ = getMe(); } inline User getMe() { curlpp::Easy request; std::stringstream ss; request.setOpt(new curlpp::Options::Url(telegramMainUrl_ + "/getMe")); request.setOpt(new curlpp::Options::Verbose(false)); request.setOpt(new curlpp::options::WriteStream(&ss)); request.perform(); BOOST_LOG_TRIVIAL(debug) << ss.str(); using namespace rapidjson; IStreamWrapper isw(ss); Document doc; doc.ParseStream(isw); return parseUser(parseResponse(doc)); } inline void sendMessage(const std::string& chat, const std::string& text) { // Construct JSON body and istream using namespace rapidjson; StringBuffer s; Writer<StringBuffer> writer(s); writer.StartObject(); writer.String("chat_id"); writer.String(chat.c_str()); writer.String("text"); writer.String(text.c_str()); writer.EndObject(); std::istringstream requestStream(s.GetString()); BOOST_LOG_TRIVIAL(debug) << requestStream.str(); auto size = requestStream.str().size(); std::stringstream responseStream; // Construct HTTP request curlpp::Easy request; std::list<std::string> headers; // Content-Type headers.push_back("Content-Type: application/json"); // Content-Length { std::ostringstream ss; ss << "Content-Length: " << size; headers.push_back(ss.str()); } // Set options request.setOpt(new curlpp::Options::Url(telegramMainUrl_ + "/sendMessage")); request.setOpt(new curlpp::Options::Verbose(false)); request.setOpt(new curlpp::Options::ReadStream(&requestStream)); request.setOpt(new curlpp::options::WriteStream(&responseStream)); request.setOpt(new curlpp::Options::InfileSize(size)); request.setOpt(new curlpp::options::HttpHeader(headers)); request.setOpt(new curlpp::Options::Post(true)); // Perform request request.perform(); BOOST_LOG_TRIVIAL(debug) << responseStream.str(); using namespace rapidjson; IStreamWrapper isw(responseStream); Document doc; doc.ParseStream(isw); /// \todo Parse message parseResponse(doc); } inline void sendPhoto(const std::string& chat, const std::string& filename, const std::string& caption) { // Construct HTTP request curlpp::Easy request; std::stringstream responseStream; { // Forms takes ownership of pointers! curlpp::Forms formParts; formParts.push_back(new curlpp::FormParts::Content("chat_id", chat)); formParts.push_back(new curlpp::FormParts::File("photo", filename)); formParts.push_back(new curlpp::FormParts::Content("caption", caption)); request.setOpt(new curlpp::options::HttpPost(formParts)); } // Set options request.setOpt(new curlpp::Options::Url(telegramMainUrl_ + "/sendPhoto")); request.setOpt(new curlpp::Options::Verbose(false)); request.setOpt(new curlpp::options::WriteStream(&responseStream)); // Perform request request.perform(); BOOST_LOG_TRIVIAL(debug) << responseStream.str(); using namespace rapidjson; IStreamWrapper isw(responseStream); Document doc; doc.ParseStream(isw); /// \todo Parse message parseResponse(doc); } private: std::string token_; std::string telegramMainUrl_; User botUser_; }; BotApi::BotApi(const std::string& token) : impl_(std::make_unique<Impl>(token)) { } BotApi::~BotApi() = default; User BotApi::getMe() { return impl_->getMe(); } void BotApi::sendMessage(const std::string& chat, const std::string& text) { return impl_->sendMessage(chat, text); } void BotApi::sendPhoto(const std::string& chat, const std::string& filename, const std::string& caption) { return impl_->sendPhoto(chat, filename, caption); } <commit_msg>Disabled default 'Expect: 100-Continue' header in POST requests.<commit_after>#include <telebotxx/BotApi.hpp> #include <telebotxx/Exception.hpp> #include <sstream> #include <rapidjson/document.h> #include <rapidjson/writer.h> #include <rapidjson/istreamwrapper.h> #include <curlpp/cURLpp.hpp> #include <curlpp/Easy.hpp> #include <curlpp/Options.hpp> #include <boost/log/trivial.hpp> namespace telebotxx { const rapidjson::Value& parseResponse(const rapidjson::Document& doc) { using namespace rapidjson; if (!doc.IsObject()) throw ParseError("Object expected"); // Get status if (!doc.HasMember("ok") || !doc["ok"].IsBool()) throw ParseError("Field 'ok' not found or has invalid type"); bool ok = doc["ok"].GetBool(); if (ok) { if (!doc.HasMember("result") || !doc["result"].IsObject()) throw ParseError("Field 'result' not found or has invalid type"); return doc["result"]; } else { if (!doc.HasMember("error_code") || !doc["error_code"].IsInt()) throw ParseError("Field 'error_code' not found or has invalid type"); int code = doc["error_code"].GetInt(); if (!doc.HasMember("description") || !doc["description"].IsString()) throw ParseError("Field 'description' not found or has invalid type"); std::string description(doc["description"].GetString()); throw ApiError(code, description); } } User parseUser(const rapidjson::Value& obj) { if (!obj.HasMember("id") || !obj["id"].IsInt()) throw ParseError("Field 'id' not found or has invalid type"); int id = obj["id"].GetInt(); if (!obj.HasMember("first_name") || !obj["first_name"].IsString()) throw ParseError("Field 'first_name' not found or has invalid type"); std::string firstName(obj["first_name"].GetString()); std::string lastName; if (obj.HasMember("last_name")) { if (obj["last_name"].IsString()) lastName = obj["last_name"].GetString(); else throw ParseError("Field 'last_name' has invalid type"); } std::string username; if (obj.HasMember("username")) { if (obj["username"].IsString()) username = obj["username"].GetString(); else throw ParseError("Field 'username' has invalid type"); } return User(id, firstName, lastName, username); } } using namespace telebotxx; class BotApi::Impl { public: Impl(const std::string& token) : token_(token) { telegramMainUrl_ = "https://api.telegram.org/bot" + token_; botUser_ = getMe(); } inline User getMe() { curlpp::Easy request; std::stringstream ss; request.setOpt(new curlpp::Options::Url(telegramMainUrl_ + "/getMe")); request.setOpt(new curlpp::Options::Verbose(false)); request.setOpt(new curlpp::options::WriteStream(&ss)); request.perform(); BOOST_LOG_TRIVIAL(debug) << ss.str(); using namespace rapidjson; IStreamWrapper isw(ss); Document doc; doc.ParseStream(isw); return parseUser(parseResponse(doc)); } inline void sendMessage(const std::string& chat, const std::string& text) { // Construct JSON body and istream using namespace rapidjson; StringBuffer s; Writer<StringBuffer> writer(s); writer.StartObject(); writer.String("chat_id"); writer.String(chat.c_str()); writer.String("text"); writer.String(text.c_str()); writer.EndObject(); std::istringstream requestStream(s.GetString()); BOOST_LOG_TRIVIAL(debug) << requestStream.str(); auto size = requestStream.str().size(); std::stringstream responseStream; // Construct HTTP request curlpp::Easy request; std::list<std::string> headers; // Content-Type headers.push_back("Content-Type: application/json"); // Content-Length { std::ostringstream ss; ss << "Content-Length: " << size; headers.push_back(ss.str()); } headers.push_back("Expect:"); // Set options request.setOpt(new curlpp::Options::Url(telegramMainUrl_ + "/sendMessage")); request.setOpt(new curlpp::Options::Verbose(true)); request.setOpt(new curlpp::Options::ReadStream(&requestStream)); request.setOpt(new curlpp::Options::WriteStream(&responseStream)); request.setOpt(new curlpp::Options::InfileSize(size)); request.setOpt(new curlpp::Options::HttpHeader(headers)); request.setOpt(new curlpp::Options::Post(true)); // Perform request request.perform(); BOOST_LOG_TRIVIAL(debug) << responseStream.str(); using namespace rapidjson; IStreamWrapper isw(responseStream); Document doc; doc.ParseStream(isw); /// \todo Parse message parseResponse(doc); } inline void sendPhoto(const std::string& chat, const std::string& filename, const std::string& caption) { // Construct HTTP request curlpp::Easy request; std::stringstream responseStream; std::list<std::string> headers; headers.push_back("Expect:"); request.setOpt(new curlpp::Options::HttpHeader(headers)); { // Forms takes ownership of pointers! curlpp::Forms formParts; formParts.push_back(new curlpp::FormParts::Content("chat_id", chat)); formParts.push_back(new curlpp::FormParts::File("photo", filename)); formParts.push_back(new curlpp::FormParts::Content("caption", caption)); request.setOpt(new curlpp::options::HttpPost(formParts)); } // Set options request.setOpt(new curlpp::Options::Url(telegramMainUrl_ + "/sendPhoto")); request.setOpt(new curlpp::Options::Verbose(true)); request.setOpt(new curlpp::options::WriteStream(&responseStream)); // Perform request request.perform(); BOOST_LOG_TRIVIAL(debug) << responseStream.str(); using namespace rapidjson; IStreamWrapper isw(responseStream); Document doc; doc.ParseStream(isw); /// \todo Parse message parseResponse(doc); } private: std::string token_; std::string telegramMainUrl_; User botUser_; }; BotApi::BotApi(const std::string& token) : impl_(std::make_unique<Impl>(token)) { } BotApi::~BotApi() = default; User BotApi::getMe() { return impl_->getMe(); } void BotApi::sendMessage(const std::string& chat, const std::string& text) { return impl_->sendMessage(chat, text); } void BotApi::sendPhoto(const std::string& chat, const std::string& filename, const std::string& caption) { return impl_->sendPhoto(chat, filename, caption); } <|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. * **************************************************************************/ // Add the muon tracks to the generic AOD track branch during the // filtering of the ESD - R. Arnaldi 5/5/08 #include <TChain.h> #include <TFile.h> #include <TParticle.h> #include "AliAnalysisTaskESDMuonFilter.h" #include "AliAnalysisManager.h" #include "AliESDEvent.h" #include "AliAODEvent.h" #include "AliESDInputHandler.h" #include "AliAODHandler.h" #include "AliAnalysisFilter.h" #include "AliESDtrack.h" #include "AliESDMuonTrack.h" #include "AliESDVertex.h" #include "AliMultiplicity.h" #include "AliLog.h" #include "AliStack.h" #include "AliMCEvent.h" #include "AliMCEventHandler.h" #include "AliAODMCParticle.h" #include "AliAODDimuon.h" ClassImp(AliAnalysisTaskESDMuonFilter) //////////////////////////////////////////////////////////////////////// AliAnalysisTaskESDMuonFilter::AliAnalysisTaskESDMuonFilter(): AliAnalysisTaskSE(), fTrackFilter(0x0), fEnableMuonAOD(kFALSE) { // Default constructor } AliAnalysisTaskESDMuonFilter::AliAnalysisTaskESDMuonFilter(const char* name): AliAnalysisTaskSE(name), fTrackFilter(0x0), fEnableMuonAOD(kFALSE) { // Constructor } void AliAnalysisTaskESDMuonFilter::UserCreateOutputObjects() { // Create the output container if (fTrackFilter) OutputTree()->GetUserInfo()->Add(fTrackFilter); } void AliAnalysisTaskESDMuonFilter::Init() { // Initialization if (fDebug > 1) AliInfo("Init() \n"); // From Andrei AliAODHandler *aodH = (AliAODHandler*)((AliAnalysisManager::GetAnalysisManager())->GetOutputEventHandler()); if (!aodH) Fatal("UserCreateOutputObjects", "No AOD handler. Aborting."); if(fEnableMuonAOD)aodH->AddFilteredAOD("AliAOD.Muons.root", "MuonEvents"); if(fEnableDimuonAOD)aodH->AddFilteredAOD("AliAOD.Dimuons.root", "DimuonEvents"); } void AliAnalysisTaskESDMuonFilter::UserExec(Option_t */*option*/) { // Execute analysis for current event Long64_t ientry = Entry(); if(fDebug)printf("Muon Filter: Analysing event # %5d\n", (Int_t) ientry); ConvertESDtoAOD(); } void AliAnalysisTaskESDMuonFilter::ConvertESDtoAOD() { // ESD Muon Filter analysis task executed for each event AliESDEvent* esd = dynamic_cast<AliESDEvent*>(InputEvent()); // Fetch Stack for debuggging if available AliStack *pStack = 0; AliMCEventHandler *mcH = 0; if(MCEvent()){ pStack = MCEvent()->Stack(); mcH = (AliMCEventHandler*) ((AliAnalysisManager::GetAnalysisManager())->GetMCtruthEventHandler()); } // Define arrays for muons Double_t pos[3]; Double_t p[3]; Double_t pid[10]; // has to be changed once the muon pid is provided by the ESD for (Int_t i = 0; i < 10; pid[i++] = 0.) {} pid[AliAODTrack::kMuon]=1.; AliAODHeader* header = AODEvent()->GetHeader(); AliAODTrack *aodTrack = 0x0; AliESDMuonTrack *esdMuTrack = 0x0; // Access to the AOD container of tracks TClonesArray &tracks = *(AODEvent()->GetTracks()); Int_t jTracks = header->GetRefMultiplicity(); // Read primary vertex from AOD event AliAODVertex *primary = AODEvent()->GetPrimaryVertex(); if(fDebug)primary->Print(); // Loop on muon tracks to fill the AOD track branch Int_t nMuTracks = esd->GetNumberOfMuonTracks(); // Update number of positive and negative tracks from AOD event (M.G.) Int_t nPosTracks = header->GetRefMultiplicityPos(); Int_t nNegTracks = header->GetRefMultiplicityNeg(); // Access to the AOD container of dimuons TClonesArray &dimuons = *(AODEvent()->GetDimuons()); AliAODDimuon *aodDimuon = 0x0; Bool_t MuonsExist = kFALSE; Bool_t DimuonsExist = kFALSE; Int_t firstMuonTrack=0; Int_t nMuons=0; Int_t jDimuons=0; Int_t nMuonTrack[10]; for(int imuon=0;imuon<10;imuon++) nMuonTrack[imuon]=0; for (Int_t nMuTrack = 0; nMuTrack < nMuTracks; ++nMuTrack) { esdMuTrack = esd->GetMuonTrack(nMuTrack); if (!esdMuTrack->ContainTrackerData()) continue; UInt_t selectInfo = 0; // Track selection if (fTrackFilter) { selectInfo = fTrackFilter->IsSelected(esdMuTrack); if (!selectInfo) { continue; } } p[0] = esdMuTrack->Px(); p[1] = esdMuTrack->Py(); p[2] = esdMuTrack->Pz(); pos[0] = esdMuTrack->GetNonBendingCoor(); pos[1] = esdMuTrack->GetBendingCoor(); pos[2] = esdMuTrack->GetZ(); if(mcH)mcH->SelectParticle(esdMuTrack->GetLabel()); aodTrack = new(tracks[jTracks++]) AliAODTrack(esdMuTrack->GetUniqueID(), // ID esdMuTrack->GetLabel(), // label p, // momentum kTRUE, // cartesian coordinate system pos, // position kFALSE, // isDCA 0x0, // covariance matrix esdMuTrack->Charge(), // charge 0, // ITSClusterMap pid, // pid primary, // primary vertex kFALSE, // used for vertex fit? kFALSE, // used for primary vertex fit? AliAODTrack::kPrimary,// track type selectInfo); aodTrack->SetXYAtDCA(esdMuTrack->GetNonBendingCoorAtDCA(), esdMuTrack->GetBendingCoorAtDCA()); aodTrack->SetPxPyPzAtDCA(esdMuTrack->PxAtDCA(), esdMuTrack->PyAtDCA(), esdMuTrack->PzAtDCA()); aodTrack->ConvertAliPIDtoAODPID(); aodTrack->SetChi2perNDF(esdMuTrack->GetChi2() / (2.*esdMuTrack->GetNHit() - 5.)); aodTrack->SetChi2MatchTrigger(esdMuTrack->GetChi2MatchTrigger()); aodTrack->SetHitsPatternInTrigCh(esdMuTrack->GetHitsPatternInTrigCh()); aodTrack->SetMuonClusterMap(esdMuTrack->GetMuonClusterMap()); aodTrack->SetMatchTrigger(esdMuTrack->GetMatchTrigger()); aodTrack->Connected(esdMuTrack->IsConnected()); primary->AddDaughter(aodTrack); if (esdMuTrack->Charge() > 0) nPosTracks++; else nNegTracks++; nMuonTrack[nMuons]= jTracks-1.; nMuons++; } if(nMuons>=2) DimuonsExist = kTRUE; if(DimuonsExist) { for(int i=0;i<nMuons;i++){ Int_t index0 = nMuonTrack[i]; for(int j=i+1;j<nMuons;j++){ Int_t index1 = nMuonTrack[j]; aodDimuon = new(dimuons[jDimuons++]) AliAODDimuon(tracks.At(index0),tracks.At(index1)); if (fDebug > 1){ AliAODTrack *track0 = (AliAODTrack*)tracks.At(index0); AliAODTrack *track1 = (AliAODTrack*)tracks.At(index1); AliAODDimuon *dimuon0 = (AliAODDimuon*)dimuons.At(jDimuons-1); printf("Dimuon: mass = %f, px=%f, py=%f, pz=%f\n",dimuon0->M(),dimuon0->Px(),dimuon0->Py(),dimuon0->Pz()); AliAODTrack *mu0 = (AliAODTrack*) dimuon0->GetMu(0); AliAODTrack *mu1 = (AliAODTrack*) dimuon0->GetMu(1); printf("Muon0 px=%f py=%f pz=%f\n",mu0->Px(),mu0->Py(),mu0->Pz()); printf("Muon1 px=%f py=%f pz=%f\n",mu1->Px(),mu1->Py(),mu1->Pz()); } } } } header->SetRefMultiplicity(jTracks); header->SetRefMultiplicityPos(nPosTracks); header->SetRefMultiplicityNeg(nNegTracks); // From Andrei if(fEnableMuonAOD && MuonsExist){ AliAODExtension *extMuons = dynamic_cast<AliAODHandler*> ((AliAnalysisManager::GetAnalysisManager())->GetOutputEventHandler())->GetFilteredAOD("AliAOD.Muons.root"); extMuons->SelectEvent(); } if(fEnableDimuonAOD && DimuonsExist){ AliAODExtension *extDimuons = dynamic_cast<AliAODHandler*> ((AliAnalysisManager::GetAnalysisManager())->GetOutputEventHandler())->GetFilteredAOD("AliAOD.Dimuons.root"); extDimuons->SelectEvent(); } } void AliAnalysisTaskESDMuonFilter::Terminate(Option_t */*option*/) { // Terminate analysis // if (fDebug > 1) printf("AnalysisESDfilter: Terminate() \n"); } void AliAnalysisTaskESDMuonFilter::PrintMCInfo(AliStack *pStack,Int_t label){ if(!pStack)return; label = TMath::Abs(label); TParticle *part = pStack->Particle(label); Printf("########################"); Printf("%s:%d %d UniqueID %d PDG %d P %3.3f",(char*)__FILE__,__LINE__,label,part->GetUniqueID(),part->GetPdgCode(),part->P()); part->Print(); TParticle* mother = part; Int_t imo = part->GetFirstMother(); Int_t nprim = pStack->GetNprimary(); // while((imo >= nprim) && (mother->GetUniqueID() == 4)) { while((imo >= nprim)) { mother = pStack->Particle(imo); Printf("Mother %s:%d Label %d UniqueID %d PDG %d P %3.3f",(char*)__FILE__,__LINE__,imo,mother->GetUniqueID(),mother->GetPdgCode(),mother->P()); mother->Print(); imo = mother->GetFirstMother(); } Printf("########################"); } <commit_msg>Fixing compilation warnings (Roberta)<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. * **************************************************************************/ // Add the muon tracks to the generic AOD track branch during the // filtering of the ESD - R. Arnaldi 5/5/08 #include <TChain.h> #include <TFile.h> #include <TParticle.h> #include "AliAnalysisTaskESDMuonFilter.h" #include "AliAnalysisManager.h" #include "AliESDEvent.h" #include "AliAODEvent.h" #include "AliESDInputHandler.h" #include "AliAODHandler.h" #include "AliAnalysisFilter.h" #include "AliESDtrack.h" #include "AliESDMuonTrack.h" #include "AliESDVertex.h" #include "AliMultiplicity.h" #include "AliLog.h" #include "AliStack.h" #include "AliMCEvent.h" #include "AliMCEventHandler.h" #include "AliAODMCParticle.h" #include "AliAODDimuon.h" ClassImp(AliAnalysisTaskESDMuonFilter) //////////////////////////////////////////////////////////////////////// AliAnalysisTaskESDMuonFilter::AliAnalysisTaskESDMuonFilter(): AliAnalysisTaskSE(), fTrackFilter(0x0), fEnableMuonAOD(kFALSE), fEnableDimuonAOD(kFALSE) { // Default constructor } AliAnalysisTaskESDMuonFilter::AliAnalysisTaskESDMuonFilter(const char* name): AliAnalysisTaskSE(name), fTrackFilter(0x0), fEnableMuonAOD(kFALSE), fEnableDimuonAOD(kFALSE) { // Constructor } void AliAnalysisTaskESDMuonFilter::UserCreateOutputObjects() { // Create the output container if (fTrackFilter) OutputTree()->GetUserInfo()->Add(fTrackFilter); } void AliAnalysisTaskESDMuonFilter::Init() { // Initialization if (fDebug > 1) AliInfo("Init() \n"); // From Andrei AliAODHandler *aodH = (AliAODHandler*)((AliAnalysisManager::GetAnalysisManager())->GetOutputEventHandler()); if (!aodH) Fatal("UserCreateOutputObjects", "No AOD handler. Aborting."); if(fEnableMuonAOD)aodH->AddFilteredAOD("AliAOD.Muons.root", "MuonEvents"); if(fEnableDimuonAOD)aodH->AddFilteredAOD("AliAOD.Dimuons.root", "DimuonEvents"); } void AliAnalysisTaskESDMuonFilter::UserExec(Option_t */*option*/) { // Execute analysis for current event Long64_t ientry = Entry(); if(fDebug)printf("Muon Filter: Analysing event # %5d\n", (Int_t) ientry); ConvertESDtoAOD(); } void AliAnalysisTaskESDMuonFilter::ConvertESDtoAOD() { // ESD Muon Filter analysis task executed for each event AliESDEvent* esd = dynamic_cast<AliESDEvent*>(InputEvent()); // Fetch Stack for debuggging if available AliStack *pStack = 0; AliMCEventHandler *mcH = 0; if(MCEvent()){ pStack = MCEvent()->Stack(); mcH = (AliMCEventHandler*) ((AliAnalysisManager::GetAnalysisManager())->GetMCtruthEventHandler()); } // Define arrays for muons Double_t pos[3]; Double_t p[3]; Double_t pid[10]; // has to be changed once the muon pid is provided by the ESD for (Int_t i = 0; i < 10; pid[i++] = 0.) {} pid[AliAODTrack::kMuon]=1.; AliAODHeader* header = AODEvent()->GetHeader(); AliAODTrack *aodTrack = 0x0; AliESDMuonTrack *esdMuTrack = 0x0; // Access to the AOD container of tracks TClonesArray &tracks = *(AODEvent()->GetTracks()); Int_t jTracks = header->GetRefMultiplicity(); // Read primary vertex from AOD event AliAODVertex *primary = AODEvent()->GetPrimaryVertex(); if(fDebug)primary->Print(); // Loop on muon tracks to fill the AOD track branch Int_t nMuTracks = esd->GetNumberOfMuonTracks(); // Update number of positive and negative tracks from AOD event (M.G.) Int_t nPosTracks = header->GetRefMultiplicityPos(); Int_t nNegTracks = header->GetRefMultiplicityNeg(); // Access to the AOD container of dimuons TClonesArray &dimuons = *(AODEvent()->GetDimuons()); AliAODDimuon *aodDimuon = 0x0; Bool_t MuonsExist = kFALSE; Bool_t DimuonsExist = kFALSE; Int_t nMuons=0; Int_t jDimuons=0; Int_t nMuonTrack[10]; for(int imuon=0;imuon<10;imuon++) nMuonTrack[imuon]=0; for (Int_t nMuTrack = 0; nMuTrack < nMuTracks; ++nMuTrack) { esdMuTrack = esd->GetMuonTrack(nMuTrack); if (!esdMuTrack->ContainTrackerData()) continue; UInt_t selectInfo = 0; // Track selection if (fTrackFilter) { selectInfo = fTrackFilter->IsSelected(esdMuTrack); if (!selectInfo) { continue; } } p[0] = esdMuTrack->Px(); p[1] = esdMuTrack->Py(); p[2] = esdMuTrack->Pz(); pos[0] = esdMuTrack->GetNonBendingCoor(); pos[1] = esdMuTrack->GetBendingCoor(); pos[2] = esdMuTrack->GetZ(); if(mcH)mcH->SelectParticle(esdMuTrack->GetLabel()); aodTrack = new(tracks[jTracks++]) AliAODTrack(esdMuTrack->GetUniqueID(), // ID esdMuTrack->GetLabel(), // label p, // momentum kTRUE, // cartesian coordinate system pos, // position kFALSE, // isDCA 0x0, // covariance matrix esdMuTrack->Charge(), // charge 0, // ITSClusterMap pid, // pid primary, // primary vertex kFALSE, // used for vertex fit? kFALSE, // used for primary vertex fit? AliAODTrack::kPrimary,// track type selectInfo); aodTrack->SetXYAtDCA(esdMuTrack->GetNonBendingCoorAtDCA(), esdMuTrack->GetBendingCoorAtDCA()); aodTrack->SetPxPyPzAtDCA(esdMuTrack->PxAtDCA(), esdMuTrack->PyAtDCA(), esdMuTrack->PzAtDCA()); aodTrack->ConvertAliPIDtoAODPID(); aodTrack->SetChi2perNDF(esdMuTrack->GetChi2() / (2.*esdMuTrack->GetNHit() - 5.)); aodTrack->SetChi2MatchTrigger(esdMuTrack->GetChi2MatchTrigger()); aodTrack->SetHitsPatternInTrigCh(esdMuTrack->GetHitsPatternInTrigCh()); aodTrack->SetMuonClusterMap(esdMuTrack->GetMuonClusterMap()); aodTrack->SetMatchTrigger(esdMuTrack->GetMatchTrigger()); aodTrack->Connected(esdMuTrack->IsConnected()); primary->AddDaughter(aodTrack); if (esdMuTrack->Charge() > 0) nPosTracks++; else nNegTracks++; nMuonTrack[nMuons]= jTracks-1.; nMuons++; } if(nMuons>=2) DimuonsExist = kTRUE; if(DimuonsExist) { for(int i=0;i<nMuons;i++){ Int_t index0 = nMuonTrack[i]; for(int j=i+1;j<nMuons;j++){ Int_t index1 = nMuonTrack[j]; aodDimuon = new(dimuons[jDimuons++]) AliAODDimuon(tracks.At(index0),tracks.At(index1)); if (fDebug > 1){ AliAODDimuon *dimuon0 = (AliAODDimuon*)dimuons.At(jDimuons-1); printf("Dimuon: mass = %f, px=%f, py=%f, pz=%f\n",dimuon0->M(),dimuon0->Px(),dimuon0->Py(),dimuon0->Pz()); AliAODTrack *mu0 = (AliAODTrack*) dimuon0->GetMu(0); AliAODTrack *mu1 = (AliAODTrack*) dimuon0->GetMu(1); printf("Muon0 px=%f py=%f pz=%f\n",mu0->Px(),mu0->Py(),mu0->Pz()); printf("Muon1 px=%f py=%f pz=%f\n",mu1->Px(),mu1->Py(),mu1->Pz()); } } } } header->SetRefMultiplicity(jTracks); header->SetRefMultiplicityPos(nPosTracks); header->SetRefMultiplicityNeg(nNegTracks); // From Andrei if(fEnableMuonAOD && MuonsExist){ AliAODExtension *extMuons = dynamic_cast<AliAODHandler*> ((AliAnalysisManager::GetAnalysisManager())->GetOutputEventHandler())->GetFilteredAOD("AliAOD.Muons.root"); extMuons->SelectEvent(); } if(fEnableDimuonAOD && DimuonsExist){ AliAODExtension *extDimuons = dynamic_cast<AliAODHandler*> ((AliAnalysisManager::GetAnalysisManager())->GetOutputEventHandler())->GetFilteredAOD("AliAOD.Dimuons.root"); extDimuons->SelectEvent(); } } void AliAnalysisTaskESDMuonFilter::Terminate(Option_t */*option*/) { // Terminate analysis // if (fDebug > 1) printf("AnalysisESDfilter: Terminate() \n"); } void AliAnalysisTaskESDMuonFilter::PrintMCInfo(AliStack *pStack,Int_t label){ if(!pStack)return; label = TMath::Abs(label); TParticle *part = pStack->Particle(label); Printf("########################"); Printf("%s:%d %d UniqueID %d PDG %d P %3.3f",(char*)__FILE__,__LINE__,label,part->GetUniqueID(),part->GetPdgCode(),part->P()); part->Print(); TParticle* mother = part; Int_t imo = part->GetFirstMother(); Int_t nprim = pStack->GetNprimary(); // while((imo >= nprim) && (mother->GetUniqueID() == 4)) { while((imo >= nprim)) { mother = pStack->Particle(imo); Printf("Mother %s:%d Label %d UniqueID %d PDG %d P %3.3f",(char*)__FILE__,__LINE__,imo,mother->GetUniqueID(),mother->GetPdgCode(),mother->P()); mother->Print(); imo = mother->GetFirstMother(); } Printf("########################"); } <|endoftext|>
<commit_before>/* * Open Chinese Convert * * Copyright 2010-2014 BYVoid <[email protected]> * * 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 "Config.hpp" #include "ConversionChain.hpp" #include "Converter.hpp" #include "DartsDict.hpp" #include "DictGroup.hpp" #include "MaxMatchSegmentation.hpp" #include "TextDict.hpp" #include "document.h" #include <unordered_map> using namespace opencc; typedef rapidjson::GenericValue<rapidjson::UTF8<char>> JSONValue; namespace opencc { class ConfigInternal { public: string configDirectory; std::unordered_map< string, std::unordered_map<string, std::unordered_map<string, DictPtr>>> dictCache; const JSONValue& GetProperty(const JSONValue& doc, const char* name) { if (!doc.HasMember(name)) { throw InvalidFormat("Required property not found: " + string(name)); } return doc[name]; } const JSONValue& GetObjectProperty(const JSONValue& doc, const char* name) { const JSONValue& obj = GetProperty(doc, name); if (!obj.IsObject()) { throw InvalidFormat("Property must be an object: " + string(name)); } return obj; } const JSONValue& GetArrayProperty(const JSONValue& doc, const char* name) { const JSONValue& obj = GetProperty(doc, name); if (!obj.IsArray()) { throw InvalidFormat("Property must be an array: " + string(name)); } return obj; } const char* GetStringProperty(const JSONValue& doc, const char* name) { const JSONValue& obj = GetProperty(doc, name); if (!obj.IsString()) { throw InvalidFormat("Property must be a string: " + string(name)); } return obj.GetString(); } template <typename DICT> DictPtr LoadDictWithPaths(const string& fileName) { // Working directory std::shared_ptr<DICT> dict; if (SerializableDict::TryLoadFromFile<DICT>(fileName, &dict)) { return dict; } // Configuration directory if ((configDirectory != "") && SerializableDict::TryLoadFromFile<DICT>( configDirectory + fileName, &dict)) { return dict; } // Package data directory if ((PACKAGE_DATA_DIRECTORY != "") && SerializableDict::TryLoadFromFile<DICT>( PACKAGE_DATA_DIRECTORY + fileName, &dict)) { return dict; } throw FileNotFound(fileName); } DictPtr ParseDict(const JSONValue& doc) { // Required: type string type = GetStringProperty(doc, "type"); DictPtr dict; if (type == "group") { list<DictPtr> dicts; const JSONValue& docs = GetArrayProperty(doc, "dicts"); for (rapidjson::SizeType i = 0; i < docs.Size(); i++) { if (docs[i].IsObject()) { DictPtr dict = ParseDict(docs[i]); dicts.push_back(dict); } else { throw InvalidFormat("Element of the array must be an object"); } } return DictGroupPtr(new DictGroup(dicts)); } else { string fileName = GetStringProperty(doc, "file"); // Read from cache DictPtr& cache = dictCache[type][configDirectory][fileName]; if (cache != nullptr) { return cache; } if (type == "text") { dict = LoadDictWithPaths<TextDict>(fileName); } else if (type == "ocd") { dict = LoadDictWithPaths<DartsDict>(fileName); } else { throw InvalidFormat("Unknown dictionary type: " + type); } // Update Cache cache = dict; return dict; } } SegmentationPtr ParseSegmentation(const JSONValue& doc) { SegmentationPtr segmentation; // Required: type string type = GetStringProperty(doc, "type"); if (type == "mmseg") { // Required: dict DictPtr dict = ParseDict(GetObjectProperty(doc, "dict")); segmentation = SegmentationPtr(new MaxMatchSegmentation(dict)); } else { throw InvalidFormat("Unknown segmentation type: " + type); } return segmentation; } ConversionPtr ParseConversion(const JSONValue& doc) { // Required: dict DictPtr dict = ParseDict(GetObjectProperty(doc, "dict")); ConversionPtr conversion(new Conversion(dict)); return conversion; } ConversionChainPtr ParseConversionChain(const JSONValue& docs) { list<ConversionPtr> conversions; for (rapidjson::SizeType i = 0; i < docs.Size(); i++) { const JSONValue& doc = docs[i]; if (doc.IsObject()) { ConversionPtr conversion = ParseConversion(doc); conversions.push_back(conversion); } else { } } ConversionChainPtr chain(new ConversionChain(conversions)); return chain; } string FindConfigFile(string fileName) { std::ifstream ifs; // Working directory ifs.open(fileName.c_str()); if (ifs.is_open()) { return fileName; } // Package data directory if (PACKAGE_DATA_DIRECTORY != "") { string prefixedFileName = PACKAGE_DATA_DIRECTORY + fileName; ifs.open(prefixedFileName.c_str()); if (ifs.is_open()) { return prefixedFileName; } } throw FileNotFound(fileName); } }; }; Config::Config() : internal(new ConfigInternal()) {} Config::~Config() { delete (ConfigInternal*)internal; } ConverterPtr Config::NewFromFile(const string& fileName) { ConfigInternal* impl = (ConfigInternal*)internal; string prefixedFileName = impl->FindConfigFile(fileName); std::ifstream ifs(prefixedFileName); string content(std::istreambuf_iterator<char>(ifs), (std::istreambuf_iterator<char>())); #if defined(_WIN32) || defined(_WIN64) UTF8Util::ReplaceAll(prefixedFileName, "\\", "/"); #endif // if defined(_WIN32) || defined(_WIN64) size_t slashPos = prefixedFileName.rfind("/"); string configDirectory = ""; if (slashPos != string::npos) { configDirectory = prefixedFileName.substr(0, slashPos) + "/"; } return NewFromString(content, configDirectory); } ConverterPtr Config::NewFromString(const string& json, const string& configDirectory) { rapidjson::Document doc; doc.ParseInsitu<0>(const_cast<char*>(json.c_str())); if (doc.HasParseError()) { throw InvalidFormat("Error parsing JSON"); // doc.GetErrorOffset() } if (!doc.IsObject()) { throw InvalidFormat("Root of configuration must be an object"); } // Optional: name string name; if (doc.HasMember("name") && doc["name"].IsString()) { name = doc["name"].GetString(); } ConfigInternal* impl = (ConfigInternal*)internal; impl->configDirectory = configDirectory; // Required: segmentation SegmentationPtr segmentation = impl->ParseSegmentation(impl->GetObjectProperty(doc, "segmentation")); // Required: conversion_chain ConversionChainPtr chain = impl->ParseConversionChain( impl->GetArrayProperty(doc, "conversion_chain")); return ConverterPtr(new Converter(name, segmentation, chain)); } <commit_msg>Allow ext-less config filenames for package data.<commit_after>/* * Open Chinese Convert * * Copyright 2010-2014 BYVoid <[email protected]> * * 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 "Config.hpp" #include "ConversionChain.hpp" #include "Converter.hpp" #include "DartsDict.hpp" #include "DictGroup.hpp" #include "MaxMatchSegmentation.hpp" #include "TextDict.hpp" #include "document.h" #include <unordered_map> using namespace opencc; typedef rapidjson::GenericValue<rapidjson::UTF8<char>> JSONValue; namespace opencc { class ConfigInternal { public: string configDirectory; std::unordered_map< string, std::unordered_map<string, std::unordered_map<string, DictPtr>>> dictCache; const JSONValue& GetProperty(const JSONValue& doc, const char* name) { if (!doc.HasMember(name)) { throw InvalidFormat("Required property not found: " + string(name)); } return doc[name]; } const JSONValue& GetObjectProperty(const JSONValue& doc, const char* name) { const JSONValue& obj = GetProperty(doc, name); if (!obj.IsObject()) { throw InvalidFormat("Property must be an object: " + string(name)); } return obj; } const JSONValue& GetArrayProperty(const JSONValue& doc, const char* name) { const JSONValue& obj = GetProperty(doc, name); if (!obj.IsArray()) { throw InvalidFormat("Property must be an array: " + string(name)); } return obj; } const char* GetStringProperty(const JSONValue& doc, const char* name) { const JSONValue& obj = GetProperty(doc, name); if (!obj.IsString()) { throw InvalidFormat("Property must be a string: " + string(name)); } return obj.GetString(); } template <typename DICT> DictPtr LoadDictWithPaths(const string& fileName) { // Working directory std::shared_ptr<DICT> dict; if (SerializableDict::TryLoadFromFile<DICT>(fileName, &dict)) { return dict; } // Configuration directory if ((configDirectory != "") && SerializableDict::TryLoadFromFile<DICT>( configDirectory + fileName, &dict)) { return dict; } // Package data directory if ((PACKAGE_DATA_DIRECTORY != "") && SerializableDict::TryLoadFromFile<DICT>( PACKAGE_DATA_DIRECTORY + fileName, &dict)) { return dict; } throw FileNotFound(fileName); } DictPtr ParseDict(const JSONValue& doc) { // Required: type string type = GetStringProperty(doc, "type"); DictPtr dict; if (type == "group") { list<DictPtr> dicts; const JSONValue& docs = GetArrayProperty(doc, "dicts"); for (rapidjson::SizeType i = 0; i < docs.Size(); i++) { if (docs[i].IsObject()) { DictPtr dict = ParseDict(docs[i]); dicts.push_back(dict); } else { throw InvalidFormat("Element of the array must be an object"); } } return DictGroupPtr(new DictGroup(dicts)); } else { string fileName = GetStringProperty(doc, "file"); // Read from cache DictPtr& cache = dictCache[type][configDirectory][fileName]; if (cache != nullptr) { return cache; } if (type == "text") { dict = LoadDictWithPaths<TextDict>(fileName); } else if (type == "ocd") { dict = LoadDictWithPaths<DartsDict>(fileName); } else { throw InvalidFormat("Unknown dictionary type: " + type); } // Update Cache cache = dict; return dict; } } SegmentationPtr ParseSegmentation(const JSONValue& doc) { SegmentationPtr segmentation; // Required: type string type = GetStringProperty(doc, "type"); if (type == "mmseg") { // Required: dict DictPtr dict = ParseDict(GetObjectProperty(doc, "dict")); segmentation = SegmentationPtr(new MaxMatchSegmentation(dict)); } else { throw InvalidFormat("Unknown segmentation type: " + type); } return segmentation; } ConversionPtr ParseConversion(const JSONValue& doc) { // Required: dict DictPtr dict = ParseDict(GetObjectProperty(doc, "dict")); ConversionPtr conversion(new Conversion(dict)); return conversion; } ConversionChainPtr ParseConversionChain(const JSONValue& docs) { list<ConversionPtr> conversions; for (rapidjson::SizeType i = 0; i < docs.Size(); i++) { const JSONValue& doc = docs[i]; if (doc.IsObject()) { ConversionPtr conversion = ParseConversion(doc); conversions.push_back(conversion); } else { } } ConversionChainPtr chain(new ConversionChain(conversions)); return chain; } string FindConfigFile(string fileName) { std::ifstream ifs; // Working directory ifs.open(fileName.c_str()); if (ifs.is_open()) { return fileName; } // Package data directory if (PACKAGE_DATA_DIRECTORY != "") { string prefixedFileName = PACKAGE_DATA_DIRECTORY + fileName; ifs.open(prefixedFileName.c_str()); if (ifs.is_open()) { return prefixedFileName; } prefixedFileName += ".json"; ifs.open(prefixedFileName.c_str()); if (ifs.is_open()) { return prefixedFileName; } } throw FileNotFound(fileName); } }; }; Config::Config() : internal(new ConfigInternal()) {} Config::~Config() { delete (ConfigInternal*)internal; } ConverterPtr Config::NewFromFile(const string& fileName) { ConfigInternal* impl = (ConfigInternal*)internal; string prefixedFileName = impl->FindConfigFile(fileName); std::ifstream ifs(prefixedFileName); string content(std::istreambuf_iterator<char>(ifs), (std::istreambuf_iterator<char>())); #if defined(_WIN32) || defined(_WIN64) UTF8Util::ReplaceAll(prefixedFileName, "\\", "/"); #endif // if defined(_WIN32) || defined(_WIN64) size_t slashPos = prefixedFileName.rfind("/"); string configDirectory = ""; if (slashPos != string::npos) { configDirectory = prefixedFileName.substr(0, slashPos) + "/"; } return NewFromString(content, configDirectory); } ConverterPtr Config::NewFromString(const string& json, const string& configDirectory) { rapidjson::Document doc; doc.ParseInsitu<0>(const_cast<char*>(json.c_str())); if (doc.HasParseError()) { throw InvalidFormat("Error parsing JSON"); // doc.GetErrorOffset() } if (!doc.IsObject()) { throw InvalidFormat("Root of configuration must be an object"); } // Optional: name string name; if (doc.HasMember("name") && doc["name"].IsString()) { name = doc["name"].GetString(); } ConfigInternal* impl = (ConfigInternal*)internal; impl->configDirectory = configDirectory; // Required: segmentation SegmentationPtr segmentation = impl->ParseSegmentation(impl->GetObjectProperty(doc, "segmentation")); // Required: conversion_chain ConversionChainPtr chain = impl->ParseConversionChain( impl->GetArrayProperty(doc, "conversion_chain")); return ConverterPtr(new Converter(name, segmentation, chain)); } <|endoftext|>
<commit_before>/****************************************************************/ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* All contents are licensed under LGPL V2.1 */ /* See LICENSE for full restrictions */ /****************************************************************/ #include "RecomputeRadialReturnTempDepHardening.h" #include "PiecewiseLinear.h" template<> InputParameters validParams<RecomputeRadialReturnTempDepHardening>() { InputParameters params = validParams<RecomputeRadialReturnIsotropicPlasticity>(); params.set<Real>("yield_stress") = 1.0; params.set<Real>("hardening_constant") = 1.0; params.suppressParameter<Real>("yield_stress"); params.suppressParameter<FunctionName>("yield_stress_function"); params.suppressParameter<Real>("hardening_constant"); params.suppressParameter<FunctionName>("hardening_function"); params.addRequiredParam<std::vector<FunctionName> >("hardening_functions", "List of functions of true stress as function of plastic strain at different temperatures"); params.addRequiredParam<std::vector<Real> >("temperatures", "List of temperatures corresponding to the functions listed in 'hardening_functions'"); return params; } RecomputeRadialReturnTempDepHardening::RecomputeRadialReturnTempDepHardening(const InputParameters & parameters) : RecomputeRadialReturnIsotropicPlasticity(parameters), _hardening_functions_names(getParam<std::vector<FunctionName> >("hardening_functions")), _hf_temperatures(getParam<std::vector<Real> >("temperatures")) { const unsigned len = _hardening_functions_names.size(); if (len < 2) mooseError("At least two stress-strain curves must be provided in hardening_functions"); _hardening_functions.resize(len); const unsigned len_temps = _hf_temperatures.size(); if (len != len_temps) mooseError("The vector of hardening function temperatures must have the same length as the vector of temperature dependent hardening functions."); //Check that the temperatures are strictly increasing for (unsigned int i = 1; i < len_temps; ++i) { if (_hf_temperatures[i] <= _hf_temperatures[i-1]) mooseError("The temperature dependent hardening functions and corresponding temperatures should be listed in order of increasing temperature."); } std::vector<Real> yield_stress_vec; for (unsigned int i = 0; i < len; ++i) { PiecewiseLinear * const f = dynamic_cast<PiecewiseLinear*>(&getFunctionByName(_hardening_functions_names[i])); if (!f) mooseError("Function " << _hardening_functions_names[i] << " not found in " << name()); _hardening_functions[i] = f; Point p; yield_stress_vec.push_back(f->value(0.0, p)); } _interp_yield_stress = new LinearInterpolation(_hf_temperatures, yield_stress_vec); _scalar_plastic_strain_old = &declarePropertyOld<Real>("scalar_plastic_strain"); } void RecomputeRadialReturnTempDepHardening::computeStressInitialize(Real effectiveTrialStress) { _shear_modulus = getIsotropicShearModulus(); initializeHardeningFunctions(); computeYieldStress(); _yield_condition = effectiveTrialStress - _hardening_variable_old[_qp] - _yield_stress; _hardening_variable[_qp] = _hardening_variable_old[_qp]; _plastic_strain[_qp] = _plastic_strain_old[_qp]; } void RecomputeRadialReturnTempDepHardening::initializeHardeningFunctions() { Real temp = _temperature[_qp]; if (temp > _hf_temperatures[0] && temp < _hf_temperatures.back()) { for (unsigned int i = 0; i < _hf_temperatures.size() - 1; ++i) { if (temp >= _hf_temperatures[i] && temp < _hf_temperatures[i+1]) { _hf_index = i; Real temp_lo = _hf_temperatures[i]; Real temp_hi = _hf_temperatures[i+1]; _hf_fraction = (temp - temp_lo) / (temp_hi - temp_lo); } } } else if (temp <= _hf_temperatures[0]) { _hf_index = 0; _hf_fraction = 0.0; } else if (temp >= _hf_temperatures.back()) { _hf_index = _hf_temperatures.size() - 1; _hf_fraction = 1.0; } if (_hf_fraction < 0.0) mooseError("The hardening function fraction cannot be less than zero."); } Real RecomputeRadialReturnTempDepHardening::computeHardeningValue(Real scalar) { const Real strain = (*_scalar_plastic_strain_old)[_qp] + scalar; Real temp = _temperature[_qp]; Real stress = 0.0; Point p; stress += (1.0 - _hf_fraction) * _hardening_functions[_hf_index]->value(strain, p); stress += _hf_fraction * _hardening_functions[_hf_index+1]->value(strain, p); return stress - _yield_stress; } Real RecomputeRadialReturnTempDepHardening::computeHardeningDerivative(Real /*scalar*/) { const Real strain_old = (*_scalar_plastic_strain_old)[_qp]; Real temp = _temperature[_qp]; Real derivative = 0.0; Point p; derivative += (1.0 - _hf_fraction) * _hardening_functions[_hf_index]->timeDerivative(strain_old, p); derivative += _hf_fraction * _hardening_functions[_hf_index+1]->timeDerivative(strain_old, p); return derivative; } void RecomputeRadialReturnTempDepHardening::computeYieldStress() { _yield_stress = _interp_yield_stress->sample(_temperature[_qp]); if (_yield_stress <= 0.0) mooseError("The yield stress must be greater than zero, but during the simulation your yield stress became less than zero."); } <commit_msg>Remove unused variable warning (#1777)<commit_after>/****************************************************************/ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* All contents are licensed under LGPL V2.1 */ /* See LICENSE for full restrictions */ /****************************************************************/ #include "RecomputeRadialReturnTempDepHardening.h" #include "PiecewiseLinear.h" template<> InputParameters validParams<RecomputeRadialReturnTempDepHardening>() { InputParameters params = validParams<RecomputeRadialReturnIsotropicPlasticity>(); params.set<Real>("yield_stress") = 1.0; params.set<Real>("hardening_constant") = 1.0; params.suppressParameter<Real>("yield_stress"); params.suppressParameter<FunctionName>("yield_stress_function"); params.suppressParameter<Real>("hardening_constant"); params.suppressParameter<FunctionName>("hardening_function"); params.addRequiredParam<std::vector<FunctionName> >("hardening_functions", "List of functions of true stress as function of plastic strain at different temperatures"); params.addRequiredParam<std::vector<Real> >("temperatures", "List of temperatures corresponding to the functions listed in 'hardening_functions'"); return params; } RecomputeRadialReturnTempDepHardening::RecomputeRadialReturnTempDepHardening(const InputParameters & parameters) : RecomputeRadialReturnIsotropicPlasticity(parameters), _hardening_functions_names(getParam<std::vector<FunctionName> >("hardening_functions")), _hf_temperatures(getParam<std::vector<Real> >("temperatures")) { const unsigned int len = _hardening_functions_names.size(); if (len < 2) mooseError("At least two stress-strain curves must be provided in hardening_functions"); _hardening_functions.resize(len); const unsigned int len_temps = _hf_temperatures.size(); if (len != len_temps) mooseError("The vector of hardening function temperatures must have the same length as the vector of temperature dependent hardening functions."); //Check that the temperatures are strictly increasing for (unsigned int i = 1; i < len_temps; ++i) if (_hf_temperatures[i] <= _hf_temperatures[i-1]) mooseError("The temperature dependent hardening functions and corresponding temperatures should be listed in order of increasing temperature."); std::vector<Real> yield_stress_vec; for (unsigned int i = 0; i < len; ++i) { PiecewiseLinear * const f = dynamic_cast<PiecewiseLinear*>(&getFunctionByName(_hardening_functions_names[i])); if (!f) mooseError("Function " << _hardening_functions_names[i] << " not found in " << name()); _hardening_functions[i] = f; yield_stress_vec.push_back(f->value(0.0, Point())); } _interp_yield_stress = new LinearInterpolation(_hf_temperatures, yield_stress_vec); _scalar_plastic_strain_old = &declarePropertyOld<Real>("scalar_plastic_strain"); } void RecomputeRadialReturnTempDepHardening::computeStressInitialize(Real effectiveTrialStress) { _shear_modulus = getIsotropicShearModulus(); initializeHardeningFunctions(); computeYieldStress(); _yield_condition = effectiveTrialStress - _hardening_variable_old[_qp] - _yield_stress; _hardening_variable[_qp] = _hardening_variable_old[_qp]; _plastic_strain[_qp] = _plastic_strain_old[_qp]; } void RecomputeRadialReturnTempDepHardening::initializeHardeningFunctions() { const Real temp = _temperature[_qp]; if (temp > _hf_temperatures[0] && temp < _hf_temperatures.back()) { for (unsigned int i = 0; i < _hf_temperatures.size() - 1; ++i) { if (temp >= _hf_temperatures[i] && temp < _hf_temperatures[i+1]) { _hf_index = i; Real temp_lo = _hf_temperatures[i]; Real temp_hi = _hf_temperatures[i+1]; _hf_fraction = (temp - temp_lo) / (temp_hi - temp_lo); } } } else if (temp <= _hf_temperatures[0]) { _hf_index = 0; _hf_fraction = 0.0; } else if (temp >= _hf_temperatures.back()) { _hf_index = _hf_temperatures.size() - 1; _hf_fraction = 1.0; } if (_hf_fraction < 0.0) mooseError("The hardening function fraction cannot be less than zero."); } Real RecomputeRadialReturnTempDepHardening::computeHardeningValue(Real scalar) { const Real strain = (*_scalar_plastic_strain_old)[_qp] + scalar; const Point p; const Real stress = (1.0 - _hf_fraction) * _hardening_functions[_hf_index]->value(strain, p) + _hf_fraction * _hardening_functions[_hf_index+1]->value(strain, p); return stress - _yield_stress; } Real RecomputeRadialReturnTempDepHardening::computeHardeningDerivative(Real /*scalar*/) { const Real strain_old = (*_scalar_plastic_strain_old)[_qp]; const Point p; return (1.0 - _hf_fraction) * _hardening_functions[_hf_index]->timeDerivative(strain_old, p) + _hf_fraction * _hardening_functions[_hf_index+1]->timeDerivative(strain_old, p); } void RecomputeRadialReturnTempDepHardening::computeYieldStress() { _yield_stress = _interp_yield_stress->sample(_temperature[_qp]); if (_yield_stress <= 0.0) mooseError("The yield stress must be greater than zero, but during the simulation your yield stress became less than zero."); } <|endoftext|>
<commit_before>// Copyright (c) 2012-2015 Dano Pernis // See LICENSE for details #include <gtk/gtk.h> #include <glib.h> #include <fstream> #include <iostream> #include <stdexcept> #include <cassert> #include "CPU.h" namespace hcc { struct ROM : public IROM { unsigned short *data; static const unsigned int size = 0x8000; ROM() { data = new unsigned short[size]; } virtual ~ROM() { delete[] data; } bool load(const char *filename) { std::ifstream input(filename); std::string line; unsigned int counter = 0; while (input.good() && counter < size) { getline(input, line); if (line.size() == 0) continue; if (line.size() != 16) return false; unsigned int instruction = 0; for (unsigned int i = 0; i<16; ++i) { instruction <<= 1; switch (line[i]) { case '0': break; case '1': instruction |= 1; break; default: return false; } } data[counter++] = instruction; } // clear the rest while (counter < size) { data[counter++] = 0; } return true; } virtual unsigned short get(unsigned int address) const { if (address < size) { return data[address]; } else { std::cerr << "requested memory at " << address << '\n'; throw std::runtime_error("Memory::get"); } } }; } // end namespace gboolean on_draw(GtkWidget*, cairo_t* cr, gpointer data) { GdkPixbuf* pixbuf = reinterpret_cast<GdkPixbuf*>(data); gdk_cairo_set_source_pixbuf(cr, pixbuf, 0, 0); cairo_paint(cr); return FALSE; } struct GUIEmulatorRAM : public hcc::IRAM { static const unsigned int CHANNELS = 3; static const unsigned int SCREEN_WIDTH = 512; static const unsigned int SCREEN_HEIGHT = 256; static const unsigned int size = 0x6001; unsigned short *data; GdkPixbuf *pixbuf; GtkWidget *screen; void putpixel(unsigned short x, unsigned short y, bool black) { int color = black ? 0x00 : 0xff; int n_channels = gdk_pixbuf_get_n_channels (pixbuf); int rowstride = gdk_pixbuf_get_rowstride (pixbuf); guchar* pixels = gdk_pixbuf_get_pixels(pixbuf); guchar* p = pixels + y * rowstride + x * n_channels; p[0] = color; p[1] = color; p[2] = color; } public: GUIEmulatorRAM() { data = new unsigned short[size]; pixbuf = gdk_pixbuf_new(GDK_COLORSPACE_RGB, FALSE, 8, SCREEN_WIDTH, SCREEN_HEIGHT); gdk_pixbuf_fill(pixbuf, 0x0000000); screen = gtk_drawing_area_new(); gtk_widget_set_size_request(screen, SCREEN_WIDTH, SCREEN_HEIGHT); g_signal_connect(screen, "draw", G_CALLBACK(on_draw), pixbuf); } virtual ~GUIEmulatorRAM() { delete[] data; } void keyboard(unsigned short value) { data[0x6000] = value; } GtkWidget* getScreenWidget() { return screen; } virtual void set(unsigned int address, unsigned short value) { if (address >= size) { throw std::runtime_error("RAM::set"); } data[address] = value; // check if we are writing to video RAM if (0x4000 <= address && address <0x6000) { address -= 0x4000; unsigned short y = address / 32; unsigned short x = 16*(address % 32); for (int bit = 0; bit<16; ++bit) { putpixel(x + bit, y, value & 1); value = value >> 1; } gdk_threads_enter(); gtk_widget_queue_draw(screen); gdk_threads_leave(); } } virtual unsigned short get(unsigned int address) const { if (address >= size) { throw std::runtime_error("RAM::get"); } return data[address]; } }; struct emulator { emulator(); void load_clicked(); void run_clicked(); void pause_clicked(); gboolean keyboard_callback(GdkEventKey* event); void run_thread(); GtkToolItem* create_button(const gchar* stock_id, const gchar* text, GCallback callback); hcc::ROM rom; GUIEmulatorRAM ram; hcc::CPU cpu; bool running = false; GtkWidget* window; GtkWidget* load_dialog; GtkWidget* error_dialog; GtkToolItem* button_load; GtkToolItem* button_run; GtkToolItem* button_pause; }; gboolean c_keyboard_callback(GtkWidget*, GdkEventKey *event, gpointer user_data) { return reinterpret_cast<emulator*>(user_data)->keyboard_callback(event); } void c_load_clicked(GtkButton*, gpointer user_data) { reinterpret_cast<emulator*>(user_data)->load_clicked(); } void c_run_clicked(GtkButton*, gpointer user_data) { reinterpret_cast<emulator*>(user_data)->run_clicked(); } void c_pause_clicked(GtkButton*, gpointer user_data) { reinterpret_cast<emulator*>(user_data)->pause_clicked(); } gpointer c_run_thread(gpointer user_data) { reinterpret_cast<emulator*>(user_data)->run_thread(); return NULL; } // Translate special keys. See Figure 5.6 in TECS book. unsigned short translate(guint keyval) { switch (keyval) { case GDK_KEY_Return: return 128; case GDK_KEY_BackSpace: return 129; case GDK_KEY_Left: return 130; case GDK_KEY_Up: return 131; case GDK_KEY_Right: return 132; case GDK_KEY_Down: return 133; case GDK_KEY_Home: return 134; case GDK_KEY_End: return 135; case GDK_KEY_Page_Up: return 136; case GDK_KEY_Page_Down: return 137; case GDK_KEY_Insert: return 138; case GDK_KEY_Delete: return 139; case GDK_KEY_Escape: return 140; case GDK_KEY_F1: return 141; case GDK_KEY_F2: return 142; case GDK_KEY_F3: return 143; case GDK_KEY_F4: return 144; case GDK_KEY_F5: return 145; case GDK_KEY_F6: return 146; case GDK_KEY_F7: return 147; case GDK_KEY_F8: return 148; case GDK_KEY_F9: return 149; case GDK_KEY_F10: return 150; case GDK_KEY_F11: return 151; case GDK_KEY_F12: return 152; } return keyval; } emulator::emulator() { /* toolbar buttons */ button_load = create_button("document-open", "Load...", G_CALLBACK(c_load_clicked)); button_run = create_button("media-playback-start", "Run", G_CALLBACK(c_run_clicked)); button_pause = create_button("media-playback-pause", "Pause", G_CALLBACK(c_pause_clicked)); GtkToolItem *separator1 = gtk_separator_tool_item_new(); gtk_widget_set_sensitive(GTK_WIDGET(button_run), FALSE); gtk_widget_set_sensitive(GTK_WIDGET(button_pause), FALSE); /* toolbar itself */ GtkWidget *toolbar = gtk_toolbar_new(); gtk_widget_set_hexpand(toolbar, TRUE); gtk_toolbar_set_style(GTK_TOOLBAR(toolbar), GTK_TOOLBAR_ICONS); gtk_toolbar_insert(GTK_TOOLBAR(toolbar), button_load, -1); gtk_toolbar_insert(GTK_TOOLBAR(toolbar), separator1, -1); gtk_toolbar_insert(GTK_TOOLBAR(toolbar), button_run, -1); gtk_toolbar_insert(GTK_TOOLBAR(toolbar), button_pause, -1); /* keyboard */ GtkWidget *keyboard = gtk_toggle_button_new_with_label("Grab keyboard focus"); gtk_widget_add_events(keyboard, GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK); g_signal_connect(keyboard, "key-press-event", G_CALLBACK(c_keyboard_callback), this); g_signal_connect(keyboard, "key-release-event", G_CALLBACK(c_keyboard_callback), this); /* main layout */ GtkWidget *grid = gtk_grid_new(); gtk_grid_attach(GTK_GRID(grid), toolbar, 0, 0, 1, 1); gtk_grid_attach(GTK_GRID(grid), ram.getScreenWidget(), 0, 1, 1, 1); gtk_grid_attach(GTK_GRID(grid), keyboard, 0, 2, 1, 1); /* main window */ window = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(GTK_WINDOW(window), "HACK emulator"); gtk_window_set_resizable(GTK_WINDOW(window), FALSE); gtk_window_set_focus(GTK_WINDOW(window), NULL); g_signal_connect(window, "destroy", G_CALLBACK (gtk_main_quit), NULL); gtk_container_add(GTK_CONTAINER(window), grid); gtk_widget_show_all(window); gtk_widget_set_visible(GTK_WIDGET(button_pause), FALSE); load_dialog = gtk_file_chooser_dialog_new( "Load ROM", GTK_WINDOW(window), GTK_FILE_CHOOSER_ACTION_OPEN, "gtk-cancel", GTK_RESPONSE_CANCEL, "gtk-open", GTK_RESPONSE_ACCEPT, NULL); error_dialog = gtk_message_dialog_new(GTK_WINDOW(window), GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, "Error loading program"); } GtkToolItem* emulator::create_button(const gchar* stock_id, const gchar* text, GCallback callback) { GtkToolItem *button = gtk_tool_button_new(NULL, text); gtk_tool_button_set_icon_name(GTK_TOOL_BUTTON(button), stock_id); gtk_tool_item_set_tooltip_text(button, text); g_signal_connect(button, "clicked", callback, this); return button; } void emulator::load_clicked() { const gint result = gtk_dialog_run(GTK_DIALOG(load_dialog)); gtk_widget_hide(load_dialog); if (result != GTK_RESPONSE_ACCEPT) { return; } char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(load_dialog)); const bool loaded = rom.load(filename); g_free(filename); if (!loaded) { gtk_dialog_run(GTK_DIALOG(error_dialog)); gtk_widget_hide(error_dialog); return; } cpu.reset(); gtk_widget_set_sensitive(GTK_WIDGET(button_run), TRUE); } void emulator::run_clicked() { assert(!running); running = true; gtk_widget_set_sensitive(GTK_WIDGET(button_run), FALSE); gtk_widget_set_visible(GTK_WIDGET(button_run), FALSE); gtk_widget_set_sensitive(GTK_WIDGET(button_pause), TRUE); gtk_widget_set_visible(GTK_WIDGET(button_pause), TRUE); g_thread_create(c_run_thread, this, FALSE, NULL); } void emulator::pause_clicked() { assert(running); running = false; gtk_widget_set_sensitive(GTK_WIDGET(button_pause), FALSE); gtk_widget_set_visible(GTK_WIDGET(button_pause), FALSE); gtk_widget_set_sensitive(GTK_WIDGET(button_run), TRUE); gtk_widget_set_visible(GTK_WIDGET(button_run), TRUE); } gboolean emulator::keyboard_callback(GdkEventKey* event) { if (event->type == GDK_KEY_RELEASE) { ram.keyboard(0); } else { ram.keyboard(translate(event->keyval)); } return TRUE; } void emulator::run_thread() { int steps = 0; while (running) { cpu.step(&rom, &ram); if (steps>100) { g_usleep(10); steps = 0; } ++steps; } } int main(int argc, char *argv[]) { gtk_init(&argc, &argv); emulator e; gtk_main(); return 0; } <commit_msg>Use std::vector for heap allocated contiguous memory<commit_after>// Copyright (c) 2012-2015 Dano Pernis // See LICENSE for details #include <gtk/gtk.h> #include <glib.h> #include <fstream> #include <iostream> #include <stdexcept> #include <cassert> #include <vector> #include "CPU.h" struct ROM : public hcc::IROM { ROM() : data(0x8000, 0) { } bool load(const char *filename) { std::ifstream input(filename); std::string line; auto it = begin(data); while (input.good() && it != end(data)) { getline(input, line); if (line.size() == 0) { continue; } if (line.size() != 16) { return false; } unsigned int instruction = 0; for (unsigned int i = 0; i<16; ++i) { instruction <<= 1; switch (line[i]) { case '0': break; case '1': instruction |= 1; break; default: return false; } } *it++ = instruction; } // clear the rest while (it != end(data)) { *it++ = 0; } return true; } unsigned short get(unsigned int address) const override { return data.at(address); } private: std::vector<unsigned short> data; }; gboolean on_draw(GtkWidget*, cairo_t* cr, gpointer data) { GdkPixbuf* pixbuf = reinterpret_cast<GdkPixbuf*>(data); gdk_cairo_set_source_pixbuf(cr, pixbuf, 0, 0); cairo_paint(cr); return FALSE; } struct RAM : public hcc::IRAM { static const unsigned int CHANNELS = 3; static const unsigned int SCREEN_WIDTH = 512; static const unsigned int SCREEN_HEIGHT = 256; std::vector<unsigned short> data; GdkPixbuf *pixbuf; GtkWidget *screen; void putpixel(unsigned short x, unsigned short y, bool black) { int color = black ? 0x00 : 0xff; int n_channels = gdk_pixbuf_get_n_channels (pixbuf); int rowstride = gdk_pixbuf_get_rowstride (pixbuf); guchar* pixels = gdk_pixbuf_get_pixels(pixbuf); guchar* p = pixels + y * rowstride + x * n_channels; p[0] = color; p[1] = color; p[2] = color; } public: RAM() : data(0x6001, 0) { pixbuf = gdk_pixbuf_new(GDK_COLORSPACE_RGB, FALSE, 8, SCREEN_WIDTH, SCREEN_HEIGHT); gdk_pixbuf_fill(pixbuf, 0x0000000); screen = gtk_drawing_area_new(); gtk_widget_set_size_request(screen, SCREEN_WIDTH, SCREEN_HEIGHT); g_signal_connect(screen, "draw", G_CALLBACK(on_draw), pixbuf); } void keyboard(unsigned short value) { data[0x6000] = value; } GtkWidget* getScreenWidget() { return screen; } void set(unsigned int address, unsigned short value) override { data.at(address) = value; // check if we are writing to video RAM if (0x4000 <= address && address <0x6000) { address -= 0x4000; unsigned short y = address / 32; unsigned short x = 16*(address % 32); for (int bit = 0; bit<16; ++bit) { putpixel(x + bit, y, value & 1); value = value >> 1; } gdk_threads_enter(); gtk_widget_queue_draw(screen); gdk_threads_leave(); } } unsigned short get(unsigned int address) const override { return data.at(address); } }; struct emulator { emulator(); void load_clicked(); void run_clicked(); void pause_clicked(); gboolean keyboard_callback(GdkEventKey* event); void run_thread(); GtkToolItem* create_button(const gchar* stock_id, const gchar* text, GCallback callback); ROM rom; RAM ram; hcc::CPU cpu; bool running = false; GtkWidget* window; GtkWidget* load_dialog; GtkWidget* error_dialog; GtkToolItem* button_load; GtkToolItem* button_run; GtkToolItem* button_pause; }; gboolean c_keyboard_callback(GtkWidget*, GdkEventKey *event, gpointer user_data) { return reinterpret_cast<emulator*>(user_data)->keyboard_callback(event); } void c_load_clicked(GtkButton*, gpointer user_data) { reinterpret_cast<emulator*>(user_data)->load_clicked(); } void c_run_clicked(GtkButton*, gpointer user_data) { reinterpret_cast<emulator*>(user_data)->run_clicked(); } void c_pause_clicked(GtkButton*, gpointer user_data) { reinterpret_cast<emulator*>(user_data)->pause_clicked(); } gpointer c_run_thread(gpointer user_data) { reinterpret_cast<emulator*>(user_data)->run_thread(); return NULL; } // Translate special keys. See Figure 5.6 in TECS book. unsigned short translate(guint keyval) { switch (keyval) { case GDK_KEY_Return: return 128; case GDK_KEY_BackSpace: return 129; case GDK_KEY_Left: return 130; case GDK_KEY_Up: return 131; case GDK_KEY_Right: return 132; case GDK_KEY_Down: return 133; case GDK_KEY_Home: return 134; case GDK_KEY_End: return 135; case GDK_KEY_Page_Up: return 136; case GDK_KEY_Page_Down: return 137; case GDK_KEY_Insert: return 138; case GDK_KEY_Delete: return 139; case GDK_KEY_Escape: return 140; case GDK_KEY_F1: return 141; case GDK_KEY_F2: return 142; case GDK_KEY_F3: return 143; case GDK_KEY_F4: return 144; case GDK_KEY_F5: return 145; case GDK_KEY_F6: return 146; case GDK_KEY_F7: return 147; case GDK_KEY_F8: return 148; case GDK_KEY_F9: return 149; case GDK_KEY_F10: return 150; case GDK_KEY_F11: return 151; case GDK_KEY_F12: return 152; } return keyval; } emulator::emulator() { /* toolbar buttons */ button_load = create_button("document-open", "Load...", G_CALLBACK(c_load_clicked)); button_run = create_button("media-playback-start", "Run", G_CALLBACK(c_run_clicked)); button_pause = create_button("media-playback-pause", "Pause", G_CALLBACK(c_pause_clicked)); GtkToolItem *separator1 = gtk_separator_tool_item_new(); gtk_widget_set_sensitive(GTK_WIDGET(button_run), FALSE); gtk_widget_set_sensitive(GTK_WIDGET(button_pause), FALSE); /* toolbar itself */ GtkWidget *toolbar = gtk_toolbar_new(); gtk_widget_set_hexpand(toolbar, TRUE); gtk_toolbar_set_style(GTK_TOOLBAR(toolbar), GTK_TOOLBAR_ICONS); gtk_toolbar_insert(GTK_TOOLBAR(toolbar), button_load, -1); gtk_toolbar_insert(GTK_TOOLBAR(toolbar), separator1, -1); gtk_toolbar_insert(GTK_TOOLBAR(toolbar), button_run, -1); gtk_toolbar_insert(GTK_TOOLBAR(toolbar), button_pause, -1); /* keyboard */ GtkWidget *keyboard = gtk_toggle_button_new_with_label("Grab keyboard focus"); gtk_widget_add_events(keyboard, GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK); g_signal_connect(keyboard, "key-press-event", G_CALLBACK(c_keyboard_callback), this); g_signal_connect(keyboard, "key-release-event", G_CALLBACK(c_keyboard_callback), this); /* main layout */ GtkWidget *grid = gtk_grid_new(); gtk_grid_attach(GTK_GRID(grid), toolbar, 0, 0, 1, 1); gtk_grid_attach(GTK_GRID(grid), ram.getScreenWidget(), 0, 1, 1, 1); gtk_grid_attach(GTK_GRID(grid), keyboard, 0, 2, 1, 1); /* main window */ window = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_title(GTK_WINDOW(window), "HACK emulator"); gtk_window_set_resizable(GTK_WINDOW(window), FALSE); gtk_window_set_focus(GTK_WINDOW(window), NULL); g_signal_connect(window, "destroy", G_CALLBACK (gtk_main_quit), NULL); gtk_container_add(GTK_CONTAINER(window), grid); gtk_widget_show_all(window); gtk_widget_set_visible(GTK_WIDGET(button_pause), FALSE); load_dialog = gtk_file_chooser_dialog_new( "Load ROM", GTK_WINDOW(window), GTK_FILE_CHOOSER_ACTION_OPEN, "gtk-cancel", GTK_RESPONSE_CANCEL, "gtk-open", GTK_RESPONSE_ACCEPT, NULL); error_dialog = gtk_message_dialog_new(GTK_WINDOW(window), GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, "Error loading program"); } GtkToolItem* emulator::create_button(const gchar* stock_id, const gchar* text, GCallback callback) { GtkToolItem *button = gtk_tool_button_new(NULL, text); gtk_tool_button_set_icon_name(GTK_TOOL_BUTTON(button), stock_id); gtk_tool_item_set_tooltip_text(button, text); g_signal_connect(button, "clicked", callback, this); return button; } void emulator::load_clicked() { const gint result = gtk_dialog_run(GTK_DIALOG(load_dialog)); gtk_widget_hide(load_dialog); if (result != GTK_RESPONSE_ACCEPT) { return; } char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(load_dialog)); const bool loaded = rom.load(filename); g_free(filename); if (!loaded) { gtk_dialog_run(GTK_DIALOG(error_dialog)); gtk_widget_hide(error_dialog); return; } cpu.reset(); gtk_widget_set_sensitive(GTK_WIDGET(button_run), TRUE); } void emulator::run_clicked() { assert(!running); running = true; gtk_widget_set_sensitive(GTK_WIDGET(button_run), FALSE); gtk_widget_set_visible(GTK_WIDGET(button_run), FALSE); gtk_widget_set_sensitive(GTK_WIDGET(button_pause), TRUE); gtk_widget_set_visible(GTK_WIDGET(button_pause), TRUE); g_thread_create(c_run_thread, this, FALSE, NULL); } void emulator::pause_clicked() { assert(running); running = false; gtk_widget_set_sensitive(GTK_WIDGET(button_pause), FALSE); gtk_widget_set_visible(GTK_WIDGET(button_pause), FALSE); gtk_widget_set_sensitive(GTK_WIDGET(button_run), TRUE); gtk_widget_set_visible(GTK_WIDGET(button_run), TRUE); } gboolean emulator::keyboard_callback(GdkEventKey* event) { if (event->type == GDK_KEY_RELEASE) { ram.keyboard(0); } else { ram.keyboard(translate(event->keyval)); } return TRUE; } void emulator::run_thread() { int steps = 0; while (running) { cpu.step(&rom, &ram); if (steps>100) { g_usleep(10); steps = 0; } ++steps; } } int main(int argc, char *argv[]) { gtk_init(&argc, &argv); emulator e; gtk_main(); return 0; } <|endoftext|>
<commit_before>/* This file is part of Bohrium and copyright (c) 2012 the Bohrium team <http://www.bh107.org>. Bohrium 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. Bohrium 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 Lesser General Public License along with Bohrium. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <type_traits> #include <ostream> #include <bh_static_vector.hpp> #include <bhxx/BhBase.hpp> #include <bhxx/type_traits_util.hpp> #include <bhxx/array_operations.hpp> namespace bhxx { /** Class which enqueues an BhBase object for deletion * with the Bohrium Runtime, but does not actually delete * it straight away. * * \note This is needed to ensure that all BhBase objects * are still around until the list of instructions has * been emptied. */ struct RuntimeDeleter { void operator()(BhBase *ptr) const; }; /** Helper function to make shared pointers to BhBase, * which use the RuntimeDeleter as their deleter */ template<typename... Args> std::shared_ptr<BhBase> make_base_ptr(Args... args) { return std::shared_ptr<BhBase>(new BhBase(std::forward<Args>(args)...), RuntimeDeleter{}); } /** Static allocated shapes and strides that is interchangeable with standard C++ vector as long * as the vector is smaller than `BH_MAXDIM`. */ typedef BhStaticVector<uint64_t> Shape; using Stride = BhIntVec; /** Return a contiguous stride (row-major) based on `shape` */ extern inline Stride contiguous_stride(const Shape &shape) { Stride ret(shape.size()); int64_t stride = 1; for (int64_t i = shape.size() - 1; i >= 0; --i) { ret[i] = stride; stride *= shape[i]; } return ret; } /** Core class that represent the core attributes of a view that isn't typed by its dtype */ class BhArrayUnTypedCore { protected: /// The array offset (from the start of the base in number of elements) uint64_t _offset = 0; /// The array shape (size of each dimension in number of elements) Shape _shape; /// The array stride (the absolute stride of each dimension in number of elements) Stride _stride; /// Pointer to the base of this array std::shared_ptr<BhBase> _base; /// Metadata to support sliding views bh_slide _slides; public: /** Default constructor that leave the instance completely uninitialized */ BhArrayUnTypedCore() = default; /** Constructor to initiate all but the `_slides` attribute */ BhArrayUnTypedCore(uint64_t offset, Shape shape, Stride stride, std::shared_ptr<BhBase> base) : _offset(offset), _shape(std::move(shape)), _stride(std::move(stride)), _base(std::move(base)) { if (_shape.size() != _stride.size()) { throw std::runtime_error("The shape and stride must have same length"); } if (shape.prod() <= 0) { throw std::runtime_error("The total size must be greater than zero"); } } /** Return a `bh_view` of the array */ bh_view getBhView() const { bh_view view; assert(_base.use_count() > 0); view.base = _base.get(); view.start = static_cast<int64_t>(offset()); if (shape().empty()) { // Scalar views (i.e. 0-dim views) are represented as 1-dim arrays with size one. view.ndim = 1; view.shape = BhIntVec({1}); view.stride = BhIntVec({1}); } else { view.ndim = static_cast<int64_t>(shape().size()); view.shape = BhIntVec(shape().begin(), shape().end()); view.stride = BhIntVec(_stride.begin(), _stride.end());; } view.slides = _slides; return view; } /** Swapping `a` and `b` */ friend void swap(BhArrayUnTypedCore &a, BhArrayUnTypedCore &b) noexcept { using std::swap; // enable ADL swap(a._offset, b._offset); swap(a._shape, b._shape); swap(a._stride, b._stride); swap(a._base, b._base); swap(a._slides, b._slides); } /** Return the offset of the array */ uint64_t offset() const { return _offset; } /** Return the shape of the array */ const Shape &shape() const { return _shape; } /** Return the stride of the array */ const Stride &stride() const { return _stride; } /** Return the base of the array */ const std::shared_ptr<BhBase> &base() const { return _base; } /** Return the base of the array */ std::shared_ptr<BhBase> base() { return _base; } /** Set the shape and stride of the array (both must have the same lenth) */ void setShapeAndStride(Shape shape, Stride stride) { if (shape.size() != stride.size()) { throw std::runtime_error("The shape and stride must have same length"); } _shape = std::move(shape); _stride = std::move(stride); } /** Return the slides object of the array */ const bh_slide &slides() const { return _slides; } /** Return the slides object of the array */ bh_slide &slides() { return _slides; } }; /** Representation of a multidimensional array that point to a `BhBase` array. * * @tparam T The data type of the array and the underlying base array */ template<typename T> class BhArray : public BhArrayUnTypedCore { public: /// The data type of each array element typedef T scalar_type; /** Default constructor that leave the instance completely uninitialized. */ BhArray() = default; /** Create a new array. `Shape` and `Stride` must have the same length. * * @param shape Shape of the new array * @param stride Stride of the new array */ explicit BhArray(Shape shape, Stride stride) : BhArrayUnTypedCore{0, std::move(shape), std::move(stride), make_base_ptr(T(0), shape.prod())} {} /** Create a new array (contiguous stride, row-major) */ explicit BhArray(Shape shape) : BhArray(std::move(shape), contiguous_stride(shape)) {} /** Create a array that points to the given base * * \note The caller should make sure that the shared pointer * uses the RuntimeDeleter as its deleter, since this is * implicitly assumed throughout, i.e. if one wants to * construct a BhBase object, use the make_base_ptr * helper function. */ explicit BhArray(std::shared_ptr<BhBase> base, Shape shape, Stride stride, uint64_t offset = 0) : BhArrayUnTypedCore{offset, std::move(shape), std::move(stride), std::move(base)} { assert(shape.size() == stride.size()); assert(shape.prod() > 0); } /** Create a view that points to the given base (contiguous stride, row-major) * * \note The caller should make sure that the shared pointer * uses the RuntimeDeleter as its deleter, since this is * implicitly assumed throughout, i.e. if one wants to * construct a BhBase object, use the make_base_ptr * helper function. */ explicit BhArray(std::shared_ptr<BhBase> base, Shape shape) : BhArray(std::move(base), std::move(shape), contiguous_stride(shape), 0) { assert(static_cast<uint64_t>(base->nelem()) == shape.prod()); } /** Create a copy of `ary` using a Bohrium `identity` operation, which copies the underlying array data. * * \note This function implements implicit type conversion for all widening type casts */ template<typename InType, typename std::enable_if<type_traits::is_safe_numeric_cast<scalar_type, InType>::value, int>::type = 0> BhArray(const BhArray<InType> &ary) : BhArray(ary.shape()) { bhxx::identity(*this, ary); } /** Copy constructor that only copies meta data. The underlying array data is untouched */ BhArray(const BhArray &) = default; /** Move constructor that only moves meta data. The underlying array data is untouched */ BhArray(BhArray &&) noexcept = default; /** Copy the data of `other` into the array using a Bohrium `identity` operation */ BhArray<T> &operator=(const BhArray<T> &other) { bhxx::identity(*this, other); return *this; } /** Copy the data of `other` into the array using a Bohrium `identity` operation * * \note A move assignment is the same as a copy assignment. */ BhArray<T> &operator=(BhArray<T> &&other) { bhxx::identity(*this, other); other.reset(); return *this; } /** Copy the scalar of `scalar_value` into the array using a Bohrium `identity` operation */ template<typename InType, typename std::enable_if<type_traits::is_arithmetic<InType>::value, int>::type = 0> BhArray<T> &operator=(const InType &scalar_value) { bhxx::identity(*this, scalar_value); return *this; } /** Reset the array to `ary` */ void reset(BhArray<T> ary) noexcept { using std::swap; swap(*this, ary); } /** Reset the array by cleaning all meta data and leave the array uninitialized. */ void reset() noexcept { reset(BhArray()); } /** Return the rank of the BhArray */ size_t rank() const { assert(shape().size() == _stride.size()); return shape().size(); } /** Return the number of elements */ uint64_t size() const { return shape().prod(); } /** Return whether the view is contiguous and row-major */ bool isContiguous() const; /** Is the data referenced by this view's base array already * allocated, i.e. initialised */ bool isDataInitialised() const { return _base->getDataPtr() != nullptr; } /** Obtain the data pointer of the array, not taking ownership of any kind. * * \note This pointer might be a nullptr if the data in * the base data is not initialised. * * \note No flush is done automatically. The data might be * out of sync with Bohrium. */ T *data() { T *ret = static_cast<T *>(_base->getDataPtr()); if (ret == nullptr) { return nullptr; } else { return _offset + ret; } } /// The const version of `data()` const T *data() const { const T *ret = static_cast<T *>(_base->getDataPtr()); if (ret == nullptr) { return nullptr; } else { return _offset + ret; } } /// Pretty printing the content of the array void pprint(std::ostream &os) const; /// Returns a new view of the `idx` dimension. Negative index counts from the back BhArray<T> operator[](int64_t idx) const; /// Return a new transposed view BhArray<T> transpose() const; /// Return a new reshaped view (the array must be contiguous) BhArray<T> reshape(Shape shape) const; }; template<typename T> std::ostream &operator<<(std::ostream &os, const BhArray<T> &ary) { ary.pprint(os); return os; } } // namespace bhxx <commit_msg>bhxx: reset() now uses the correct swap()<commit_after>/* This file is part of Bohrium and copyright (c) 2012 the Bohrium team <http://www.bh107.org>. Bohrium 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. Bohrium 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 Lesser General Public License along with Bohrium. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <type_traits> #include <ostream> #include <bh_static_vector.hpp> #include <bhxx/BhBase.hpp> #include <bhxx/type_traits_util.hpp> #include <bhxx/array_operations.hpp> namespace bhxx { /** Class which enqueues an BhBase object for deletion * with the Bohrium Runtime, but does not actually delete * it straight away. * * \note This is needed to ensure that all BhBase objects * are still around until the list of instructions has * been emptied. */ struct RuntimeDeleter { void operator()(BhBase *ptr) const; }; /** Helper function to make shared pointers to BhBase, * which use the RuntimeDeleter as their deleter */ template<typename... Args> std::shared_ptr<BhBase> make_base_ptr(Args... args) { return std::shared_ptr<BhBase>(new BhBase(std::forward<Args>(args)...), RuntimeDeleter{}); } /** Static allocated shapes and strides that is interchangeable with standard C++ vector as long * as the vector is smaller than `BH_MAXDIM`. */ typedef BhStaticVector<uint64_t> Shape; using Stride = BhIntVec; /** Return a contiguous stride (row-major) based on `shape` */ extern inline Stride contiguous_stride(const Shape &shape) { Stride ret(shape.size()); int64_t stride = 1; for (int64_t i = shape.size() - 1; i >= 0; --i) { ret[i] = stride; stride *= shape[i]; } return ret; } /** Core class that represent the core attributes of a view that isn't typed by its dtype */ class BhArrayUnTypedCore { protected: /// The array offset (from the start of the base in number of elements) uint64_t _offset = 0; /// The array shape (size of each dimension in number of elements) Shape _shape; /// The array stride (the absolute stride of each dimension in number of elements) Stride _stride; /// Pointer to the base of this array std::shared_ptr<BhBase> _base; /// Metadata to support sliding views bh_slide _slides; public: /** Default constructor that leave the instance completely uninitialized */ BhArrayUnTypedCore() = default; /** Constructor to initiate all but the `_slides` attribute */ BhArrayUnTypedCore(uint64_t offset, Shape shape, Stride stride, std::shared_ptr<BhBase> base) : _offset(offset), _shape(std::move(shape)), _stride(std::move(stride)), _base(std::move(base)) { if (_shape.size() != _stride.size()) { throw std::runtime_error("The shape and stride must have same length"); } if (shape.prod() <= 0) { throw std::runtime_error("The total size must be greater than zero"); } } /** Return a `bh_view` of the array */ bh_view getBhView() const { bh_view view; assert(_base); view.base = _base.get(); view.start = static_cast<int64_t>(offset()); if (shape().empty()) { // Scalar views (i.e. 0-dim views) are represented as 1-dim arrays with size one. view.ndim = 1; view.shape = BhIntVec({1}); view.stride = BhIntVec({1}); } else { view.ndim = static_cast<int64_t>(shape().size()); view.shape = BhIntVec(shape().begin(), shape().end()); view.stride = BhIntVec(_stride.begin(), _stride.end());; } view.slides = _slides; return view; } /** Swapping `a` and `b` */ friend void swap(BhArrayUnTypedCore &a, BhArrayUnTypedCore &b) noexcept { using std::swap; // enable ADL swap(a._offset, b._offset); swap(a._shape, b._shape); swap(a._stride, b._stride); swap(a._base, b._base); swap(a._slides, b._slides); } /** Return the offset of the array */ uint64_t offset() const { return _offset; } /** Return the shape of the array */ const Shape &shape() const { return _shape; } /** Return the stride of the array */ const Stride &stride() const { return _stride; } /** Return the base of the array */ const std::shared_ptr<BhBase> &base() const { return _base; } /** Return the base of the array */ std::shared_ptr<BhBase> base() { return _base; } /** Set the shape and stride of the array (both must have the same lenth) */ void setShapeAndStride(Shape shape, Stride stride) { if (shape.size() != stride.size()) { throw std::runtime_error("The shape and stride must have same length"); } _shape = std::move(shape); _stride = std::move(stride); } /** Return the slides object of the array */ const bh_slide &slides() const { return _slides; } /** Return the slides object of the array */ bh_slide &slides() { return _slides; } }; /** Representation of a multidimensional array that point to a `BhBase` array. * * @tparam T The data type of the array and the underlying base array */ template<typename T> class BhArray : public BhArrayUnTypedCore { public: /// The data type of each array element typedef T scalar_type; /** Default constructor that leave the instance completely uninitialized. */ BhArray() = default; /** Create a new array. `Shape` and `Stride` must have the same length. * * @param shape Shape of the new array * @param stride Stride of the new array */ explicit BhArray(Shape shape, Stride stride) : BhArrayUnTypedCore{0, std::move(shape), std::move(stride), make_base_ptr(T(0), shape.prod())} {} /** Create a new array (contiguous stride, row-major) */ explicit BhArray(Shape shape) : BhArray(std::move(shape), contiguous_stride(shape)) {} /** Create a array that points to the given base * * \note The caller should make sure that the shared pointer * uses the RuntimeDeleter as its deleter, since this is * implicitly assumed throughout, i.e. if one wants to * construct a BhBase object, use the make_base_ptr * helper function. */ explicit BhArray(std::shared_ptr<BhBase> base, Shape shape, Stride stride, uint64_t offset = 0) : BhArrayUnTypedCore{offset, std::move(shape), std::move(stride), std::move(base)} { assert(shape.size() == stride.size()); assert(shape.prod() > 0); } /** Create a view that points to the given base (contiguous stride, row-major) * * \note The caller should make sure that the shared pointer * uses the RuntimeDeleter as its deleter, since this is * implicitly assumed throughout, i.e. if one wants to * construct a BhBase object, use the make_base_ptr * helper function. */ explicit BhArray(std::shared_ptr<BhBase> base, Shape shape) : BhArray(std::move(base), std::move(shape), contiguous_stride(shape), 0) { assert(static_cast<uint64_t>(base->nelem()) == shape.prod()); } /** Create a copy of `ary` using a Bohrium `identity` operation, which copies the underlying array data. * * \note This function implements implicit type conversion for all widening type casts */ template<typename InType, typename std::enable_if<type_traits::is_safe_numeric_cast<scalar_type, InType>::value, int>::type = 0> BhArray(const BhArray<InType> &ary) : BhArray(ary.shape()) { bhxx::identity(*this, ary); } /** Copy constructor that only copies meta data. The underlying array data is untouched */ BhArray(const BhArray &) = default; /** Move constructor that only moves meta data. The underlying array data is untouched */ BhArray(BhArray &&) noexcept = default; /** Copy the data of `other` into the array using a Bohrium `identity` operation */ BhArray<T> &operator=(const BhArray<T> &other) { bhxx::identity(*this, other); return *this; } /** Copy the data of `other` into the array using a Bohrium `identity` operation * * \note A move assignment is the same as a copy assignment. */ BhArray<T> &operator=(BhArray<T> &&other) { bhxx::identity(*this, other); other.reset(); return *this; } /** Copy the scalar of `scalar_value` into the array using a Bohrium `identity` operation */ template<typename InType, typename std::enable_if<type_traits::is_arithmetic<InType>::value, int>::type = 0> BhArray<T> &operator=(const InType &scalar_value) { bhxx::identity(*this, scalar_value); return *this; } /** Reset the array to `ary` */ void reset(BhArray<T> ary) noexcept { swap(*this, ary); } /** Reset the array by cleaning all meta data and leave the array uninitialized. */ void reset() noexcept { reset(BhArray()); } /** Return the rank of the BhArray */ size_t rank() const { assert(shape().size() == _stride.size()); return shape().size(); } /** Return the number of elements */ uint64_t size() const { return shape().prod(); } /** Return whether the view is contiguous and row-major */ bool isContiguous() const; /** Is the data referenced by this view's base array already * allocated, i.e. initialised */ bool isDataInitialised() const { return _base->getDataPtr() != nullptr; } /** Obtain the data pointer of the array, not taking ownership of any kind. * * \note This pointer might be a nullptr if the data in * the base data is not initialised. * * \note No flush is done automatically. The data might be * out of sync with Bohrium. */ T *data() { T *ret = static_cast<T *>(_base->getDataPtr()); if (ret == nullptr) { return nullptr; } else { return _offset + ret; } } /// The const version of `data()` const T *data() const { const T *ret = static_cast<T *>(_base->getDataPtr()); if (ret == nullptr) { return nullptr; } else { return _offset + ret; } } /// Pretty printing the content of the array void pprint(std::ostream &os) const; /// Returns a new view of the `idx` dimension. Negative index counts from the back BhArray<T> operator[](int64_t idx) const; /// Return a new transposed view BhArray<T> transpose() const; /// Return a new reshaped view (the array must be contiguous) BhArray<T> reshape(Shape shape) const; }; template<typename T> std::ostream &operator<<(std::ostream &os, const BhArray<T> &ary) { ary.pprint(os); return os; } } // namespace bhxx <|endoftext|>
<commit_before>#include "browser/inspectable_web_contents.h" #include "browser/inspectable_web_contents_impl.h" namespace brightray { InspectableWebContents* InspectableWebContents::Create(const content::WebContents::CreateParams& create_params) { return Create(content::WebContents::Create(create_params)); } InspectableWebContents* InspectableWebContents::Create(content::WebContents* web_contents) { return new InspectableWebContentsImpl(web_contents); } } <commit_msg>Fix flashing in WebContents we create<commit_after>#include "browser/inspectable_web_contents.h" #include "browser/inspectable_web_contents_impl.h" #include "content/public/browser/web_contents_view.h" namespace brightray { InspectableWebContents* InspectableWebContents::Create(const content::WebContents::CreateParams& create_params) { auto contents = content::WebContents::Create(create_params); #if defined(OS_MACOSX) // Work around http://crbug.com/279472. contents->GetView()->SetAllowOverlappingViews(true); #endif return Create(contents); } InspectableWebContents* InspectableWebContents::Create(content::WebContents* web_contents) { return new InspectableWebContentsImpl(web_contents); } } <|endoftext|>
<commit_before>#include "ExeBox.h" #include <Entry.h> #include <FindDirectory.h> #include <Directory.h> #include <storage/Node.h> #include <OS.h> #include <File.h> #include <storage/Path.h> #include <Locker.h> #include "ObjectList.h" #include <Volume.h> #include <VolumeRoster.h> #include <Query.h> static BObjectList<entry_ref> *sPathData = NULL; BLocker sPathDataLock; thread_id sThreadID = -1; void PrintList(const char* s) { sPathDataLock.Lock(); int len = sPathData->CountItems(); printf("Count: %i\nsPathData (%s) :\n", len, s); for ( int i = 0; i < len ; i += 3 ) { printf("%i: %-13.13s\t", i, sPathData->ItemAt(i)->name); if ( i+1 < len ) printf("%i: %-13.13s\t", i+1, sPathData->ItemAt(i+1)->name); if ( i+2 < len ) printf("%i: %-13.13s\t", i+2, sPathData->ItemAt(i+2)->name); printf("\n"); } sPathDataLock.Unlock(); } ExeBoxFilter::ExeBoxFilter(ExeBox *box) : AutoTextControlFilter(box) { } filter_result ExeBoxFilter::KeyFilter(const int32 &key, const int32 &mod) { if (key < 32 || ( (mod & B_COMMAND_KEY) && !(mod & B_SHIFT_KEY) && !(mod & B_OPTION_KEY) && !(mod & B_CONTROL_KEY)) ) return B_DISPATCH_MESSAGE; int32 start, end; TextControl()->TextView()->GetSelection(&start,&end); if (end == (int32)strlen(TextControl()->Text())) { TextControl()->TextView()->Delete(start,end); BString string; if( GetCurrentMessage()->FindString("bytes",&string) != B_OK) string = ""; string.Prepend(TextControl()->Text()); entry_ref *match = NULL, *data;; sPathDataLock.Lock(); for (int32 i = 0; i < sPathData->CountItems(); i++) { data = sPathData->ItemAt(i); BString namestr(data->name); if (!data->name) continue; if (namestr.IFindFirst(string) == 0) { match = data; break; } } sPathDataLock.Unlock(); if(match) { BMessage automsg(M_EXE_AUTOCOMPLETE); automsg.AddInt32("start",strlen(TextControl()->Text())+1); automsg.AddString("string",match->name); BMessenger msgr((BHandler*)TextControl()->Window()); msgr.SendMessage(&automsg); } } return B_DISPATCH_MESSAGE; } ExeBox::ExeBox(const BRect &frame, const char *name, const char *label, const char *text, BMessage *msg, uint32 resize, uint32 flags) : AutoTextControl(frame,name,label,text,msg,resize,flags) { if (!sPathData) InitializeAutocompletion(); SetFilter(new ExeBoxFilter(this)); SetCharacterLimit(32); } ExeBox::~ExeBox(void) { int32 value; sPathDataLock.Lock(); if (sThreadID >= 0) { sPathDataLock.Unlock(); wait_for_thread(sThreadID,&value); } else sPathDataLock.Unlock(); } entry_ref * ExeBox::FindMatch(const char *name) { // Handle the autocompletion if (!name) return NULL; entry_ref *match = NULL; sPathDataLock.Lock(); for (int32 i = 0; i < sPathData->CountItems(); i++) { entry_ref *data = sPathData->ItemAt(i); if (!data->name) continue; BString refstr(data->name); if (refstr.IFindFirst(name) == 0) { match = data; break; } } sPathDataLock.Unlock(); return match; } void ExeBox::InitializeAutocompletion(void) { sPathData = new BObjectList<entry_ref>(20,true); // Set up autocomplete BEntry entry("/boot/home/config/settings/Run Program"); BPath path; entry_ref ref; if (entry.Exists()) { BFile settingsFile("/boot/home/config/settings/Run Program",B_READ_ONLY); BMessage settings; if (settings.Unflatten(&settingsFile) == B_OK) { int32 index = 0; while (settings.FindRef("refs",index,&ref) == B_OK) { index++; entry_ref *listref = new entry_ref(ref); sPathData->AddItem(listref); } sThreadID = spawn_thread(UpdateThread, "updatethread", B_NORMAL_PRIORITY, NULL); if (sThreadID >= 0) resume_thread(sThreadID); return; } } BDirectory dir; find_directory(B_BEOS_BIN_DIRECTORY,&path); dir.SetTo(path.Path()); dir.Rewind(); while (dir.GetNextRef(&ref) == B_OK) { entry.SetTo(&ref,true); entry.GetRef(&ref); entry_ref *match = NULL; for (int32 i = 0; i < sPathData->CountItems(); i++) { entry_ref *listref = sPathData->ItemAt(i); if (*listref == ref) { match = listref; break; } } if (!match) sPathData->AddItem(new entry_ref(ref)); } find_directory(B_COMMON_BIN_DIRECTORY,&path); dir.SetTo(path.Path()); dir.Rewind(); while (dir.GetNextRef(&ref) == B_OK) { entry.SetTo(&ref, true); entry.GetRef(&ref); entry_ref *match = NULL; for (int32 i = 0; i < sPathData->CountItems(); i++) { entry_ref *listref = sPathData->ItemAt(i); if (*listref == ref) { match = listref; break; } } if (!match) sPathData->AddItem(new entry_ref(ref)); } sThreadID = spawn_thread(QueryThread, "querythread", B_NORMAL_PRIORITY, NULL); if (sThreadID >= 0) resume_thread(sThreadID); } static int CompareRefs(const entry_ref *ref1, const entry_ref *ref2) { if (!ref1) return -1; else if (!ref2) return 1; return strcmp(ref1->name,ref2->name); } int32 ExeBox::QueryThread(void *data) { BVolumeRoster roster; BVolume vol; BQuery query; entry_ref ref; roster.GetBootVolume(&vol); query.SetVolume(&vol); query.SetPredicate("((BEOS:APP_SIG==\"application*\")&&" "(BEOS:TYPE==\"application/x-vnd.Be-elfexecutable\"))"); query.Fetch(); while (query.GetNextRef(&ref) == B_OK) { if ( ref.directory == B_USER_ADDONS_DIRECTORY || ref.directory == B_BEOS_ADDONS_DIRECTORY || ref.directory == B_COMMON_ADDONS_DIRECTORY) continue; if (ref.directory == -1) { fprintf(stderr, "FATAL : Query returned invalid ref!\n"); return -1; } sPathDataLock.Lock(); sPathData->AddItem(new entry_ref(ref)); sPathDataLock.Unlock(); } BMessage settings; sPathDataLock.Lock(); for (int32 i = 0; i < sPathData->CountItems(); i++) settings.AddRef("refs", sPathData->ItemAt(i)); sPathDataLock.Unlock(); BFile settingsFile("/boot/home/config/settings/Run Program", B_READ_WRITE | B_ERASE_FILE | B_CREATE_FILE); settings.Flatten(&settingsFile); sPathDataLock.Lock(); sThreadID = -1; sPathDataLock.Unlock(); return 0; } int32 ExeBox::UpdateThread(void *data) { // This takes longer, but it's not really time-critical. Most of the time there // will only be minor differences between run sessions. // In order to save as much time as possible: // 1) Get a new ref list via scanning the usual places. This won't take long, thanks // to the file cache. :) // 2) For each item in the official list // - if entry doesn't exist, remove it // - if entry does exist, remove it from the temporary list // 3) Add any remaining entries in the temporary list to the official one // 4) Update the disk version of the settings file BObjectList<entry_ref> queryList(20,true); BDirectory dir; BPath path; entry_ref ref, *pref; BEntry entry; BVolumeRoster roster; BVolume vol; BQuery query; find_directory(B_BEOS_BIN_DIRECTORY,&path); dir.SetTo(path.Path()); dir.Rewind(); while (dir.GetNextRef(&ref) == B_OK) { entry.SetTo(&ref, true); entry.GetRef(&ref); entry.Unset(); queryList.AddItem(new entry_ref(ref)); } find_directory(B_COMMON_BIN_DIRECTORY,&path); dir.SetTo(path.Path()); dir.Rewind(); while (dir.GetNextRef(&ref) == B_OK) { entry.SetTo(&ref,true); entry.GetRef(&ref); entry.Unset(); queryList.AddItem(new entry_ref(ref)); } roster.GetBootVolume(&vol); query.SetVolume(&vol); query.SetPredicate("((BEOS:APP_SIG==\"application*\")&&" "(BEOS:TYPE==\"application/x-vnd.Be-elfexecutable\"))"); query.Fetch(); while (query.GetNextRef(&ref) == B_OK) { entry.SetTo(&ref,true); entry.GetPath(&path); entry.GetRef(&ref); entry.Unset(); if (strstr(path.Path(),"add-ons") || strstr(path.Path(),"beos/servers") || !ref.name) continue; queryList.AddItem(new entry_ref(ref)); } // Scan is finished, so start culling sPathDataLock.Lock(); int32 count = sPathData->CountItems(); sPathDataLock.Unlock(); for (int32 i = 0; i < count; i++) { sPathDataLock.Lock(); pref = sPathData->ItemAt(i); entry.SetTo(pref); if (! entry.Exists() ) sPathData->RemoveItemAt( i ); else { for (int32 j = 0; j < queryList.CountItems(); j++) { if (*pref == *queryList.ItemAt(j)) { queryList.RemoveItemAt(j); break; } } } entry.Unset(); sPathDataLock.Unlock(); } // Remaining items in queryList are new entries sPathDataLock.Lock(); for (int32 j = 0; j < queryList.CountItems(); j++) { entry_ref *qref = queryList.RemoveItemAt(j); if (qref && qref->directory >= 0) sPathData->AddItem(qref); } sPathDataLock.Unlock(); BMessage settings; sPathDataLock.Lock(); sPathData->SortItems(CompareRefs); sPathDataLock.Unlock(); sPathDataLock.Lock(); for (int32 i = 0; i < sPathData->CountItems(); i++) { entry_ref *listref = sPathData->ItemAt(i); settings.AddRef("refs",listref); } sPathDataLock.Unlock(); BFile settingsFile("/boot/home/config/settings/Run Program", B_READ_WRITE | B_ERASE_FILE | B_CREATE_FILE); settings.Flatten(&settingsFile); sPathDataLock.Lock(); sThreadID = -1; sPathDataLock.Unlock(); return 0; } <commit_msg>applying patch runprogram-1.0rc1.patch<commit_after>#include "ExeBox.h" #include <Entry.h> #include <FindDirectory.h> #include <Directory.h> #include <storage/Node.h> #include <OS.h> #include <File.h> #include <storage/Path.h> #include <Locker.h> #include "ObjectList.h" #include <Volume.h> #include <VolumeRoster.h> #include <Query.h> static BObjectList<entry_ref> *sPathData = NULL; BLocker sPathDataLock; thread_id sThreadID = -1; void PrintList(const char* s) { sPathDataLock.Lock(); int len = sPathData->CountItems(); printf("Count: %i\nsPathData (%s) :\n", len, s); for ( int i = 0; i < len ; i += 3 ) { printf("%i: %-13.13s\t", i, sPathData->ItemAt(i)->name); if ( i+1 < len ) printf("%i: %-13.13s\t", i+1, sPathData->ItemAt(i+1)->name); if ( i+2 < len ) printf("%i: %-13.13s\t", i+2, sPathData->ItemAt(i+2)->name); printf("\n"); } sPathDataLock.Unlock(); } ExeBoxFilter::ExeBoxFilter(ExeBox *box) : AutoTextControlFilter(box) { } filter_result ExeBoxFilter::KeyFilter(const int32 &key, const int32 &mod) { if (key < 32 || ( (mod & B_COMMAND_KEY) && !(mod & B_SHIFT_KEY) && !(mod & B_OPTION_KEY) && !(mod & B_CONTROL_KEY)) ) return B_DISPATCH_MESSAGE; int32 start, end; TextControl()->TextView()->GetSelection(&start,&end); if (end == (int32)strlen(TextControl()->Text())) { TextControl()->TextView()->Delete(start,end); BString string; if( GetCurrentMessage()->FindString("bytes",&string) != B_OK) string = ""; string.Prepend(TextControl()->Text()); entry_ref *match = NULL, *data;; sPathDataLock.Lock(); for (int32 i = 0; i < sPathData->CountItems(); i++) { data = sPathData->ItemAt(i); BString namestr(data->name); if (!data->name) continue; if (namestr.IFindFirst(string) == 0) { match = data; break; } } sPathDataLock.Unlock(); if(match) { BMessage automsg(M_EXE_AUTOCOMPLETE); automsg.AddInt32("start",strlen(TextControl()->Text())+1); automsg.AddString("string",match->name); BMessenger msgr((BHandler*)TextControl()->Window()); msgr.SendMessage(&automsg); } } return B_DISPATCH_MESSAGE; } ExeBox::ExeBox(const BRect &frame, const char *name, const char *label, const char *text, BMessage *msg, uint32 resize, uint32 flags) : AutoTextControl(frame,name,label,text,msg,resize,flags) { if (!sPathData) InitializeAutocompletion(); SetFilter(new ExeBoxFilter(this)); SetCharacterLimit(32); } ExeBox::~ExeBox(void) { int32 value; sPathDataLock.Lock(); if (sThreadID >= 0) { sPathDataLock.Unlock(); wait_for_thread(sThreadID,&value); } else sPathDataLock.Unlock(); } entry_ref * ExeBox::FindMatch(const char *name) { // Handle the autocompletion if (!name) return NULL; entry_ref *match = NULL; sPathDataLock.Lock(); for (int32 i = 0; i < sPathData->CountItems(); i++) { entry_ref *data = sPathData->ItemAt(i); if (!data->name) continue; BString refstr(data->name); if (refstr.IFindFirst(name) == 0) { match = data; break; } } sPathDataLock.Unlock(); return match; } void ExeBox::InitializeAutocompletion(void) { sPathData = new BObjectList<entry_ref>(20,true); // Set up autocomplete BEntry entry("/boot/home/config/settings/Run Program"); BPath path; entry_ref ref; if (entry.Exists()) { BFile settingsFile("/boot/home/config/settings/Run Program",B_READ_ONLY); BMessage settings; if (settings.Unflatten(&settingsFile) == B_OK) { int32 index = 0; while (settings.FindRef("refs",index,&ref) == B_OK) { index++; entry_ref *listref = new entry_ref(ref); sPathData->AddItem(listref); } sThreadID = spawn_thread(UpdateThread, "updatethread", B_NORMAL_PRIORITY, NULL); if (sThreadID >= 0) resume_thread(sThreadID); return; } } BDirectory dir; find_directory(B_BEOS_BIN_DIRECTORY,&path); dir.SetTo(path.Path()); dir.Rewind(); while (dir.GetNextRef(&ref) == B_OK) { entry.SetTo(&ref,true); entry.GetRef(&ref); entry_ref *match = NULL; for (int32 i = 0; i < sPathData->CountItems(); i++) { entry_ref *listref = sPathData->ItemAt(i); if (*listref == ref) { match = listref; break; } } if (!match) sPathData->AddItem(new entry_ref(ref)); } find_directory(B_SYSTEM_BIN_DIRECTORY,&path); dir.SetTo(path.Path()); dir.Rewind(); while (dir.GetNextRef(&ref) == B_OK) { entry.SetTo(&ref, true); entry.GetRef(&ref); entry_ref *match = NULL; for (int32 i = 0; i < sPathData->CountItems(); i++) { entry_ref *listref = sPathData->ItemAt(i); if (*listref == ref) { match = listref; break; } } if (!match) sPathData->AddItem(new entry_ref(ref)); } sThreadID = spawn_thread(QueryThread, "querythread", B_NORMAL_PRIORITY, NULL); if (sThreadID >= 0) resume_thread(sThreadID); } static int CompareRefs(const entry_ref *ref1, const entry_ref *ref2) { if (!ref1) return -1; else if (!ref2) return 1; return strcmp(ref1->name,ref2->name); } int32 ExeBox::QueryThread(void *data) { BVolumeRoster roster; BVolume vol; BQuery query; entry_ref ref; roster.GetBootVolume(&vol); query.SetVolume(&vol); query.SetPredicate("((BEOS:APP_SIG==\"application*\")&&" "(BEOS:TYPE==\"application/x-vnd.Be-elfexecutable\"))"); query.Fetch(); while (query.GetNextRef(&ref) == B_OK) { if ( ref.directory == B_USER_ADDONS_DIRECTORY || ref.directory == B_BEOS_ADDONS_DIRECTORY || ref.directory == B_SYSTEM_ADDONS_DIRECTORY) continue; if (ref.directory == -1) { fprintf(stderr, "FATAL : Query returned invalid ref!\n"); return -1; } sPathDataLock.Lock(); sPathData->AddItem(new entry_ref(ref)); sPathDataLock.Unlock(); } BMessage settings; sPathDataLock.Lock(); for (int32 i = 0; i < sPathData->CountItems(); i++) settings.AddRef("refs", sPathData->ItemAt(i)); sPathDataLock.Unlock(); BFile settingsFile("/boot/home/config/settings/Run Program", B_READ_WRITE | B_ERASE_FILE | B_CREATE_FILE); settings.Flatten(&settingsFile); sPathDataLock.Lock(); sThreadID = -1; sPathDataLock.Unlock(); return 0; } int32 ExeBox::UpdateThread(void *data) { // This takes longer, but it's not really time-critical. Most of the time there // will only be minor differences between run sessions. // In order to save as much time as possible: // 1) Get a new ref list via scanning the usual places. This won't take long, thanks // to the file cache. :) // 2) For each item in the official list // - if entry doesn't exist, remove it // - if entry does exist, remove it from the temporary list // 3) Add any remaining entries in the temporary list to the official one // 4) Update the disk version of the settings file BObjectList<entry_ref> queryList(20,true); BDirectory dir; BPath path; entry_ref ref, *pref; BEntry entry; BVolumeRoster roster; BVolume vol; BQuery query; find_directory(B_BEOS_BIN_DIRECTORY,&path); dir.SetTo(path.Path()); dir.Rewind(); while (dir.GetNextRef(&ref) == B_OK) { entry.SetTo(&ref, true); entry.GetRef(&ref); entry.Unset(); queryList.AddItem(new entry_ref(ref)); } find_directory(B_SYSTEM_BIN_DIRECTORY,&path); dir.SetTo(path.Path()); dir.Rewind(); while (dir.GetNextRef(&ref) == B_OK) { entry.SetTo(&ref,true); entry.GetRef(&ref); entry.Unset(); queryList.AddItem(new entry_ref(ref)); } roster.GetBootVolume(&vol); query.SetVolume(&vol); query.SetPredicate("((BEOS:APP_SIG==\"application*\")&&" "(BEOS:TYPE==\"application/x-vnd.Be-elfexecutable\"))"); query.Fetch(); while (query.GetNextRef(&ref) == B_OK) { entry.SetTo(&ref,true); entry.GetPath(&path); entry.GetRef(&ref); entry.Unset(); if (strstr(path.Path(),"add-ons") || strstr(path.Path(),"beos/servers") || !ref.name) continue; queryList.AddItem(new entry_ref(ref)); } // Scan is finished, so start culling sPathDataLock.Lock(); int32 count = sPathData->CountItems(); sPathDataLock.Unlock(); for (int32 i = 0; i < count; i++) { sPathDataLock.Lock(); pref = sPathData->ItemAt(i); entry.SetTo(pref); if (! entry.Exists() ) sPathData->RemoveItemAt( i ); else { for (int32 j = 0; j < queryList.CountItems(); j++) { if (*pref == *queryList.ItemAt(j)) { queryList.RemoveItemAt(j); break; } } } entry.Unset(); sPathDataLock.Unlock(); } // Remaining items in queryList are new entries sPathDataLock.Lock(); for (int32 j = 0; j < queryList.CountItems(); j++) { entry_ref *qref = queryList.RemoveItemAt(j); if (qref && qref->directory >= 0) sPathData->AddItem(qref); } sPathDataLock.Unlock(); BMessage settings; sPathDataLock.Lock(); sPathData->SortItems(CompareRefs); sPathDataLock.Unlock(); sPathDataLock.Lock(); for (int32 i = 0; i < sPathData->CountItems(); i++) { entry_ref *listref = sPathData->ItemAt(i); settings.AddRef("refs",listref); } sPathDataLock.Unlock(); BFile settingsFile("/boot/home/config/settings/Run Program", B_READ_WRITE | B_ERASE_FILE | B_CREATE_FILE); settings.Flatten(&settingsFile); sPathDataLock.Lock(); sThreadID = -1; sPathDataLock.Unlock(); return 0; } <|endoftext|>
<commit_before>#include "FTFace.h" #include "FTLibrary.h" #include "FTGL.h" FTFace::FTFace() : ftFace(0), numCharMaps(0), numGlyphs(0) {} FTFace::~FTFace() { if( ftFace) { Close(); delete ftFace; // is this a prob? ftFace = 0; } } bool FTFace::Open( const char* filename) { ftFace = new FT_Face; err = FT_New_Face( *FTLibrary::Instance().GetLibrary(), filename, 0, ftFace); if( err == FT_Err_Unknown_File_Format) { // ... the font file could be opened and read, but it appears // ... that its font format is unsupported delete ftFace; ftFace = 0; return false; } else if( err) { // ... another error code means that the font file could not // ... be opened or read, or simply that it is broken... delete ftFace; ftFace = 0; return false; } return true; } void FTFace::Close() { FT_Done_Face( *ftFace); } FTSize& FTFace::Size( const int size, const int res ) { charSize.CharSize( ftFace, size, res, res); return charSize; } bool FTFace::CharMap( CHARMAP encoding ) { //Insert your own code here. //End of user code. return false; } FT_Glyph FTFace::Glyph( int index ) { //Insert your own code here. //End of user code. } FT_Vector FTFace::KernAdvance( int index1, int index2 ) { //Insert your own code here. //End of user code. } <commit_msg>Tidied up the err stuff<commit_after>#include "FTFace.h" #include "FTLibrary.h" #include "FTGL.h" FTFace::FTFace() : ftFace(0), numCharMaps(0), numGlyphs(0) {} FTFace::~FTFace() { if( ftFace) { Close(); delete ftFace; // is this a prob? ftFace = 0; } } bool FTFace::Open( const char* filename) { ftFace = new FT_Face; err = FT_New_Face( *FTLibrary::Instance().GetLibrary(), filename, 0, ftFace); if( err) { delete ftFace; ftFace = 0; return false; } else { return true; } } void FTFace::Close() { FT_Done_Face( *ftFace); } FTSize& FTFace::Size( const int size, const int res ) { charSize.CharSize( ftFace, size, res, res); return charSize; } bool FTFace::CharMap( CHARMAP encoding ) { //Insert your own code here. //End of user code. return false; } FT_Glyph FTFace::Glyph( int index ) { //Insert your own code here. //End of user code. } FT_Vector FTFace::KernAdvance( int index1, int index2 ) { //Insert your own code here. //End of user code. } <|endoftext|>
<commit_before>/* This file is part of cpp-ethereum. cpp-ethereum 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. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file FileIo.cpp * @author Arkadiy Paronyan [email protected] * @date 2015 * Ethereum IDE client. */ #include <QFileSystemWatcher> #include <QDebug> #include <QDesktopServices> #include <QMimeDatabase> #include <QDirIterator> #include <QDir> #include <QFile> #include <QFileInfo> #include <QTextStream> #include <QUrl> #include <json/json.h> #include <libdevcrypto/CryptoPP.h> #include <libdevcrypto/Common.h> #include <libdevcore/RLP.h> #include <libdevcore/SHA3.h> #include "FileIo.h" using namespace dev; using namespace dev::crypto; using namespace dev::mix; FileIo::FileIo(): m_watcher(new QFileSystemWatcher(this)) { connect(m_watcher, &QFileSystemWatcher::fileChanged, this, &FileIo::fileChanged); } void FileIo::openFileBrowser(QString const& _dir) { QDesktopServices::openUrl(QUrl(_dir)); } QString FileIo::pathFromUrl(QString const& _url) { QUrl url(_url); QString path(url.path()); if (url.scheme() == "qrc") path = ":" + path; #ifdef WIN32 if (url.scheme() == "file") { if (path.startsWith("/")) path = path.right(path.length() - 1); if (!url.host().isEmpty()) path = url.host() + ":/" + path; } #endif return path; } void FileIo::makeDir(QString const& _url) { QDir dirPath(pathFromUrl(_url)); if (dirPath.exists()) dirPath.removeRecursively(); dirPath.mkpath(dirPath.path()); } void FileIo::deleteDir(QString const& _url) { QDir dirPath(pathFromUrl(_url)); if (dirPath.exists()) dirPath.removeRecursively(); } QString FileIo::readFile(QString const& _url) { QFile file(pathFromUrl(_url)); if (file.open(QIODevice::ReadOnly | QIODevice::Text)) { QTextStream stream(&file); QString data = stream.readAll(); return data; } else error(tr("Error reading file %1").arg(_url)); return QString(); } void FileIo::writeFile(QString const& _url, QString const& _data) { QString path = pathFromUrl(_url); m_watcher->removePath(path); QFile file(path); if (file.open(QIODevice::WriteOnly | QIODevice::Text)) { QTextStream stream(&file); stream << _data; } else error(tr("Error writing file %1").arg(_url)); file.close(); m_watcher->addPath(path); } void FileIo::copyFile(QString const& _sourceUrl, QString const& _destUrl) { if (QUrl(_sourceUrl).scheme() == "qrc") { writeFile(_destUrl, readFile(_sourceUrl)); return; } if (!QFile::copy(pathFromUrl(_sourceUrl), pathFromUrl(_destUrl))) error(tr("Error copying file %1 to %2").arg(_sourceUrl).arg(_destUrl)); } QString FileIo::getHomePath() const { return QDir::homePath(); } void FileIo::moveFile(QString const& _sourceUrl, QString const& _destUrl) { if (!QFile::rename(pathFromUrl(_sourceUrl), pathFromUrl(_destUrl))) error(tr("Error moving file %1 to %2").arg(_sourceUrl).arg(_destUrl)); } bool FileIo::fileExists(QString const& _url) { QFile file(pathFromUrl(_url)); return file.exists(); } QStringList FileIo::makePackage(QString const& _deploymentFolder) { Json::Value manifest; Json::Value entries(Json::arrayValue); QDir deployDir = QDir(pathFromUrl(_deploymentFolder)); dev::RLPStream rlpStr; int k = 1; std::vector<bytes> files; QMimeDatabase mimeDb; for (auto item: deployDir.entryInfoList(QDir::Files)) { QFile qFile(item.filePath()); if (qFile.open(QIODevice::ReadOnly)) { k++; QFileInfo fileInfo = QFileInfo(qFile.fileName()); Json::Value jsonValue; std::string path = fileInfo.fileName() == "index.html" ? "/" : fileInfo.fileName().toStdString(); jsonValue["path"] = path; //TODO: Manage relative sub folder jsonValue["file"] = "/" + fileInfo.fileName().toStdString(); jsonValue["contentType"] = mimeDb.mimeTypeForFile(qFile.fileName()).name().toStdString(); QByteArray a = qFile.readAll(); bytes data = bytes(a.begin(), a.end()); files.push_back(data); jsonValue["hash"] = toHex(dev::sha3(data).ref()); entries.append(jsonValue); } qFile.close(); } rlpStr.appendList(k); manifest["entries"] = entries; std::stringstream jsonStr; jsonStr << manifest; QByteArray b = QString::fromStdString(jsonStr.str()).toUtf8(); rlpStr.append(bytesConstRef((const unsigned char*)b.data(), b.size())); for (unsigned int k = 0; k < files.size(); k++) rlpStr.append(files.at(k)); bytes dapp = rlpStr.out(); dev::h256 dappHash = dev::sha3(dapp); //encrypt KeyPair key((Secret(dappHash))); Secp256k1PP *enc = Secp256k1PP::get(); enc->encrypt(key.pub(), dapp); QUrl url(_deploymentFolder + "package.dapp"); QFile compressed(url.path()); QByteArray qFileBytes((char*)dapp.data(), static_cast<int>(dapp.size())); if (compressed.open(QIODevice::WriteOnly | QIODevice::Truncate)) { compressed.write(qFileBytes); compressed.flush(); } else error(tr("Error creating package.dapp")); compressed.close(); QStringList ret; ret.append(QString::fromStdString(toHex(dappHash.ref()))); ret.append(qFileBytes.toBase64()); ret.append(url.toString()); return ret; } void FileIo::watchFileChanged(QString const& _path) { m_watcher->addPath(pathFromUrl(_path)); } void FileIo::stopWatching(QString const& _path) { m_watcher->removePath(pathFromUrl(_path)); } void FileIo::deleteFile(QString const& _path) { QFile file(pathFromUrl(_path)); file.remove(); } QUrl FileIo::pathFolder(QString const& _path) { QFileInfo info(_path); if (info.exists() && info.isDir()) return QUrl::fromLocalFile(_path); return QUrl::fromLocalFile(QFileInfo(_path).absolutePath()); } <commit_msg>Cleanup.<commit_after>/* This file is part of cpp-ethereum. cpp-ethereum 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. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file FileIo.cpp * @author Arkadiy Paronyan [email protected] * @date 2015 * Ethereum IDE client. */ #include <QFileSystemWatcher> #include <QDebug> #include <QDesktopServices> #include <QMimeDatabase> #include <QDirIterator> #include <QDir> #include <QFile> #include <QFileInfo> #include <QTextStream> #include <QUrl> #include <json/json.h> #include <libdevcrypto/CryptoPP.h> #include <libdevcrypto/Common.h> #include <libdevcore/RLP.h> #include <libdevcore/SHA3.h> #include "FileIo.h" using namespace dev; using namespace dev::crypto; using namespace dev::mix; FileIo::FileIo(): m_watcher(new QFileSystemWatcher(this)) { connect(m_watcher, &QFileSystemWatcher::fileChanged, this, &FileIo::fileChanged); } void FileIo::openFileBrowser(QString const& _dir) { QDesktopServices::openUrl(QUrl(_dir)); } QString FileIo::pathFromUrl(QString const& _url) { QUrl url(_url); QString path(url.path()); if (url.scheme() == "qrc") path = ":" + path; #ifdef WIN32 if (url.scheme() == "file") { if (path.startsWith("/")) path = path.right(path.length() - 1); if (!url.host().isEmpty()) path = url.host() + ":/" + path; } #endif return path; } void FileIo::makeDir(QString const& _url) { QDir dirPath(pathFromUrl(_url)); if (dirPath.exists()) dirPath.removeRecursively(); dirPath.mkpath(dirPath.path()); } void FileIo::deleteDir(QString const& _url) { QDir dirPath(pathFromUrl(_url)); if (dirPath.exists()) dirPath.removeRecursively(); } QString FileIo::readFile(QString const& _url) { QFile file(pathFromUrl(_url)); if (file.open(QIODevice::ReadOnly | QIODevice::Text)) { QTextStream stream(&file); QString data = stream.readAll(); return data; } else error(tr("Error reading file %1").arg(_url)); return QString(); } void FileIo::writeFile(QString const& _url, QString const& _data) { QString path = pathFromUrl(_url); m_watcher->removePath(path); QFile file(path); if (file.open(QIODevice::WriteOnly | QIODevice::Text)) { QTextStream stream(&file); stream << _data; } else error(tr("Error writing file %1").arg(_url)); file.close(); m_watcher->addPath(path); } void FileIo::copyFile(QString const& _sourceUrl, QString const& _destUrl) { if (QUrl(_sourceUrl).scheme() == "qrc") { writeFile(_destUrl, readFile(_sourceUrl)); return; } if (!QFile::copy(pathFromUrl(_sourceUrl), pathFromUrl(_destUrl))) error(tr("Error copying file %1 to %2").arg(_sourceUrl).arg(_destUrl)); } QString FileIo::getHomePath() const { return QDir::homePath(); } void FileIo::moveFile(QString const& _sourceUrl, QString const& _destUrl) { if (!QFile::rename(pathFromUrl(_sourceUrl), pathFromUrl(_destUrl))) error(tr("Error moving file %1 to %2").arg(_sourceUrl).arg(_destUrl)); } bool FileIo::fileExists(QString const& _url) { QFile file(pathFromUrl(_url)); return file.exists(); } QStringList FileIo::makePackage(QString const& _deploymentFolder) { Json::Value manifest; Json::Value entries(Json::arrayValue); QDir deployDir = QDir(pathFromUrl(_deploymentFolder)); dev::RLPStream rlpStr; int k = 1; std::vector<bytes> files; QMimeDatabase mimeDb; for (auto item: deployDir.entryInfoList(QDir::Files)) { QFile qFile(item.filePath()); if (qFile.open(QIODevice::ReadOnly)) { k++; QFileInfo fileInfo = QFileInfo(qFile.fileName()); Json::Value jsonValue; std::string path = fileInfo.fileName() == "index.html" ? "/" : fileInfo.fileName().toStdString(); jsonValue["path"] = path; //TODO: Manage relative sub folder jsonValue["file"] = "/" + fileInfo.fileName().toStdString(); jsonValue["contentType"] = mimeDb.mimeTypeForFile(qFile.fileName()).name().toStdString(); QByteArray a = qFile.readAll(); bytes data = bytes(a.begin(), a.end()); files.push_back(data); jsonValue["hash"] = toHex(dev::sha3(data).ref()); entries.append(jsonValue); } qFile.close(); } rlpStr.appendList(k); manifest["entries"] = entries; std::stringstream jsonStr; jsonStr << manifest; QByteArray b = QString::fromStdString(jsonStr.str()).toUtf8(); rlpStr.append(bytesConstRef((const unsigned char*)b.data(), b.size())); for (unsigned int k = 0; k < files.size(); k++) rlpStr.append(files.at(k)); bytes dapp = rlpStr.out(); dev::h256 dappHash = dev::sha3(dapp); //encrypt KeyPair key((Secret(dappHash))); Secp256k1PP::get()->encrypt(key.pub(), dapp); QUrl url(_deploymentFolder + "package.dapp"); QFile compressed(url.path()); QByteArray qFileBytes((char*)dapp.data(), static_cast<int>(dapp.size())); if (compressed.open(QIODevice::WriteOnly | QIODevice::Truncate)) { compressed.write(qFileBytes); compressed.flush(); } else error(tr("Error creating package.dapp")); compressed.close(); QStringList ret; ret.append(QString::fromStdString(toHex(dappHash.ref()))); ret.append(qFileBytes.toBase64()); ret.append(url.toString()); return ret; } void FileIo::watchFileChanged(QString const& _path) { m_watcher->addPath(pathFromUrl(_path)); } void FileIo::stopWatching(QString const& _path) { m_watcher->removePath(pathFromUrl(_path)); } void FileIo::deleteFile(QString const& _path) { QFile file(pathFromUrl(_path)); file.remove(); } QUrl FileIo::pathFolder(QString const& _path) { QFileInfo info(_path); if (info.exists() && info.isDir()) return QUrl::fromLocalFile(_path); return QUrl::fromLocalFile(QFileInfo(_path).absolutePath()); } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // // Copyright 2006 - 2014, Paul Beckingham, Federico Hernandez. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // http://www.opensource.org/licenses/mit-license.php // //////////////////////////////////////////////////////////////////////////////// #include <iostream> // TODO Remove #include <cmake.h> #include <Context.h> #include <Eval.h> #include <Variant.h> #include <Dates.h> #include <Filter.h> #include <i18n.h> #include <util.h> extern Context context; //////////////////////////////////////////////////////////////////////////////// // Const iterator that can be derefenced into a Task by domSource. static Task dummy; static Task& contextTask = dummy; //////////////////////////////////////////////////////////////////////////////// static bool domSource (const std::string& identifier, Variant& value) { std::string stringValue = context.dom.get (identifier, contextTask); if (stringValue != identifier) { value = Variant (stringValue); return true; } return false; } //////////////////////////////////////////////////////////////////////////////// Filter::Filter () : _startCount (0) , _endCount (0) { } //////////////////////////////////////////////////////////////////////////////// Filter::~Filter () { } //////////////////////////////////////////////////////////////////////////////// // Take an input set of tasks and filter into a subset. void Filter::subset (const std::vector <Task>& input, std::vector <Task>& output) { context.timer_filter.start (); if (context.config.getBoolean ("debug")) { Tree* t = context.parser.tree (); if (t) context.debug (t->dump ()); } std::string filterExpr = context.parser.getFilterExpression (); context.debug ("\033[1;37;42mFILTER\033[0m " + filterExpr); if (filterExpr.length ()) { Eval eval; eval.addSource (namedDates); eval.addSource (domSource); // Debug output from Eval during compilation is useful. During evaluation // it is mostly noise. eval.debug (context.config.getBoolean ("debug")); eval.compileExpression (filterExpr); eval.debug (false); std::vector <Task>::const_iterator task; for (task = input.begin (); task != input.end (); ++task) { // Set up context for any DOM references. contextTask = *task; Variant var; eval.evaluateCompiledExpression (var); if (var.get_bool ()) output.push_back (*task); } } else output = input; context.timer_filter.stop (); } //////////////////////////////////////////////////////////////////////////////// // Take the set of all tasks and filter into a subset. void Filter::subset (std::vector <Task>& output) { context.timer_filter.start (); if (context.config.getBoolean ("debug")) { Tree* t = context.parser.tree (); if (t) context.debug (t->dump ()); } std::string filterExpr = context.parser.getFilterExpression (); context.debug ("\033[1;37;42mFILTER\033[0m " + filterExpr); if (filterExpr.length ()) { context.timer_filter.stop (); const std::vector <Task>& pending = context.tdb2.pending.get_tasks (); context.timer_filter.start (); Eval eval; eval.addSource (namedDates); eval.addSource (domSource); // Debug output from Eval during compilation is useful. During evaluation // it is mostly noise. eval.debug (context.config.getBoolean ("debug")); eval.compileExpression (filterExpr); eval.debug (false); output.clear (); std::vector <Task>::const_iterator task; for (task = pending.begin (); task != pending.end (); ++task) { // Set up context for any DOM references. contextTask = *task; Variant var; eval.evaluateCompiledExpression (var); if (var.get_bool ()) output.push_back (*task); } if (! pendingOnly ()) { context.timer_filter.stop (); const std::vector <Task>& completed = context.tdb2.completed.get_tasks (); // TODO Optional context.timer_filter.start (); for (task = completed.begin (); task != completed.end (); ++task) { // Set up context for any DOM references. contextTask = *task; Variant var; eval.evaluateCompiledExpression (var); if (var.get_bool ()) output.push_back (*task); } } } else { safety (); context.timer_filter.stop (); const std::vector <Task>& pending = context.tdb2.pending.get_tasks (); const std::vector <Task>& completed = context.tdb2.completed.get_tasks (); context.timer_filter.start (); std::vector <Task>::const_iterator task; for (task = pending.begin (); task != pending.end (); ++task) output.push_back (*task); for (task = completed.begin (); task != completed.end (); ++task) output.push_back (*task); } context.timer_filter.stop (); } //////////////////////////////////////////////////////////////////////////////// // If the filter contains the restriction "status:pending", as the first filter // term, then completed.data does not need to be loaded. bool Filter::pendingOnly () { Tree* tree = context.parser.tree (); // If the filter starts with "status:pending", the completed.data does not // need to be accessed.. if (tree->_branches.size () > 0 && tree->_branches[0]->attribute ("name") == "status" && tree->_branches[0]->attribute ("value") == "pending") { context.debug ("Filter::pendingOnly - skipping completed.data (status:pending first)"); return true; } // Shortcut: If the filter contains no 'or' or 'xor' operators, IDs and no UUIDs. int countId = 0; int countUUID = 0; int countOr = 0; int countXor = 0; std::vector <Tree*>::iterator i; for (i = tree->_branches.begin (); i != tree->_branches.end (); ++i) { if ((*i)->hasTag ("OP")) { if ((*i)->attribute ("canonical") == "or") ++countOr; if ((*i)->attribute ("canonical") == "xor") ++countXor; } else if ((*i)->hasTag ("ID")) ++countId; else if ((*i)->hasTag ("UUID")) ++countUUID; } if (countOr == 0 && countXor == 0 && countUUID == 0 && countId > 0) { context.debug ("Filter::pendingOnly - skipping completed.data (IDs, no OR, no XOR, no UUID)"); return true; } return false; } //////////////////////////////////////////////////////////////////////////////// // Disaster avoidance mechanism. If a WRITECMD has no filter, then it can cause // all tasks to be modified. This is usually not intended. void Filter::safety () { Tree* tree = context.parser.tree (); std::vector <Tree*>::iterator i; for (i = tree->_branches.begin (); i != tree->_branches.end (); ++i) { if ((*i)->hasTag ("WRITECMD")) { if (context.parser.getFilterExpression () == "") { // If user is willing to be asked, this can be avoided. if (context.config.getBoolean ("confirmation") && confirm (STRING_TASK_SAFETY_VALVE)) return; // Sounds the alarm. throw std::string (STRING_TASK_SAFETY_FAIL); } // Nothing to see here. Move along. return; } } } //////////////////////////////////////////////////////////////////////////////// <commit_msg>Filter<commit_after>//////////////////////////////////////////////////////////////////////////////// // // Copyright 2006 - 2014, Paul Beckingham, Federico Hernandez. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // http://www.opensource.org/licenses/mit-license.php // //////////////////////////////////////////////////////////////////////////////// #include <iostream> // TODO Remove #include <cmake.h> #include <Context.h> #include <Eval.h> #include <Variant.h> #include <Dates.h> #include <Filter.h> #include <i18n.h> #include <text.h> #include <util.h> extern Context context; //////////////////////////////////////////////////////////////////////////////// // Const iterator that can be derefenced into a Task by domSource. static Task dummy; static Task& contextTask = dummy; //////////////////////////////////////////////////////////////////////////////// static bool domSource (const std::string& identifier, Variant& value) { std::string stringValue = context.dom.get (identifier, contextTask); if (stringValue != identifier) { value = Variant (stringValue); return true; } return false; } //////////////////////////////////////////////////////////////////////////////// Filter::Filter () : _startCount (0) , _endCount (0) { } //////////////////////////////////////////////////////////////////////////////// Filter::~Filter () { } //////////////////////////////////////////////////////////////////////////////// // Take an input set of tasks and filter into a subset. void Filter::subset (const std::vector <Task>& input, std::vector <Task>& output) { context.timer_filter.start (); _startCount = (int) input.size (); if (context.config.getBoolean ("debug")) { Tree* t = context.parser.tree (); if (t) context.debug (t->dump ()); } std::string filterExpr = context.parser.getFilterExpression (); context.debug ("\033[1;37;42mFILTER\033[0m " + filterExpr); if (filterExpr.length ()) { Eval eval; eval.addSource (namedDates); eval.addSource (domSource); // Debug output from Eval during compilation is useful. During evaluation // it is mostly noise. eval.debug (context.config.getBoolean ("debug")); eval.compileExpression (filterExpr); eval.debug (false); std::vector <Task>::const_iterator task; for (task = input.begin (); task != input.end (); ++task) { // Set up context for any DOM references. contextTask = *task; Variant var; eval.evaluateCompiledExpression (var); if (var.get_bool ()) output.push_back (*task); } } else output = input; _endCount = (int) output.size (); context.debug (format ("Filtered {1} tasks --> {2} tasks", _startCount, _endCount)); context.timer_filter.stop (); } //////////////////////////////////////////////////////////////////////////////// // Take the set of all tasks and filter into a subset. void Filter::subset (std::vector <Task>& output) { context.timer_filter.start (); if (context.config.getBoolean ("debug")) { Tree* t = context.parser.tree (); if (t) context.debug (t->dump ()); } std::string filterExpr = context.parser.getFilterExpression (); context.debug ("\033[1;37;42mFILTER\033[0m " + filterExpr); if (filterExpr.length ()) { context.timer_filter.stop (); const std::vector <Task>& pending = context.tdb2.pending.get_tasks (); context.timer_filter.start (); _startCount = (int) pending.size (); Eval eval; eval.addSource (namedDates); eval.addSource (domSource); // Debug output from Eval during compilation is useful. During evaluation // it is mostly noise. eval.debug (context.config.getBoolean ("debug")); eval.compileExpression (filterExpr); eval.debug (false); output.clear (); std::vector <Task>::const_iterator task; for (task = pending.begin (); task != pending.end (); ++task) { // Set up context for any DOM references. contextTask = *task; Variant var; eval.evaluateCompiledExpression (var); if (var.get_bool ()) output.push_back (*task); } if (! pendingOnly ()) { context.timer_filter.stop (); const std::vector <Task>& completed = context.tdb2.completed.get_tasks (); // TODO Optional context.timer_filter.start (); _startCount += (int) completed.size (); for (task = completed.begin (); task != completed.end (); ++task) { // Set up context for any DOM references. contextTask = *task; Variant var; eval.evaluateCompiledExpression (var); if (var.get_bool ()) output.push_back (*task); } } } else { safety (); context.timer_filter.stop (); const std::vector <Task>& pending = context.tdb2.pending.get_tasks (); const std::vector <Task>& completed = context.tdb2.completed.get_tasks (); context.timer_filter.start (); std::vector <Task>::const_iterator task; for (task = pending.begin (); task != pending.end (); ++task) output.push_back (*task); for (task = completed.begin (); task != completed.end (); ++task) output.push_back (*task); } _endCount = (int) output.size (); context.debug (format ("Filtered {1} tasks --> {2} tasks", _startCount, _endCount)); context.timer_filter.stop (); } //////////////////////////////////////////////////////////////////////////////// // If the filter contains the restriction "status:pending", as the first filter // term, then completed.data does not need to be loaded. bool Filter::pendingOnly () { Tree* tree = context.parser.tree (); // If the filter starts with "status:pending", the completed.data does not // need to be accessed.. if (tree->_branches.size () > 0 && tree->_branches[0]->attribute ("name") == "status" && tree->_branches[0]->attribute ("value") == "pending") { context.debug ("Filter::pendingOnly - skipping completed.data (status:pending first)"); return true; } // Shortcut: If the filter contains no 'or' or 'xor' operators, IDs and no UUIDs. int countId = 0; int countUUID = 0; int countOr = 0; int countXor = 0; std::vector <Tree*>::iterator i; for (i = tree->_branches.begin (); i != tree->_branches.end (); ++i) { if ((*i)->hasTag ("OP")) { if ((*i)->attribute ("canonical") == "or") ++countOr; if ((*i)->attribute ("canonical") == "xor") ++countXor; } else if ((*i)->hasTag ("ID")) ++countId; else if ((*i)->hasTag ("UUID")) ++countUUID; } if (countOr == 0 && countXor == 0 && countUUID == 0 && countId > 0) { context.debug ("Filter::pendingOnly - skipping completed.data (IDs, no OR, no XOR, no UUID)"); return true; } return false; } //////////////////////////////////////////////////////////////////////////////// // Disaster avoidance mechanism. If a WRITECMD has no filter, then it can cause // all tasks to be modified. This is usually not intended. void Filter::safety () { Tree* tree = context.parser.tree (); std::vector <Tree*>::iterator i; for (i = tree->_branches.begin (); i != tree->_branches.end (); ++i) { if ((*i)->hasTag ("WRITECMD")) { if (context.parser.getFilterExpression () == "") { // If user is willing to be asked, this can be avoided. if (context.config.getBoolean ("confirmation") && confirm (STRING_TASK_SAFETY_VALVE)) return; // Sounds the alarm. throw std::string (STRING_TASK_SAFETY_FAIL); } // Nothing to see here. Move along. return; } } } //////////////////////////////////////////////////////////////////////////////// <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved */ #include "../StroikaPreComp.h" #include "ProgressMonitor.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Execution; /* ******************************************************************************** **************************** ProgressMonitor *********************************** ******************************************************************************** */ ProgressMonitor::ProgressMonitor () : fRep_ (new IRep_ ()) { } ProgressMonitor::ProgressMonitor (Thread workThread) : fRep_ (new IRep_ ()) { } ProgressMonitor::~ProgressMonitor () { } void ProgressMonitor::AddOnProgressCallback (const ChangedCallbackType& progressChangedCallback) { RequireNotNull (fRep_); fRep_->fCallbacks_.Append (progressChangedCallback); } void ProgressMonitor::Cancel () { RequireNotNull (fRep_); fRep_->fCanceled_ = true; if (fRep_->fWorkThread_.GetStatus () != Thread::Status::eNull) { fRep_->fWorkThread_.Abort (); } } /* ******************************************************************************** *************************** ProgressMonitor::Updater *************************** ******************************************************************************** */ void ProgressMonitor::Updater::CallNotifyProgress_ () const { RequireNotNull (fRep_); for (ChangedCallbackType f : fRep_->fCallbacks_) { return f (ProgressMonitor (fRep_)); } } <commit_msg>mistake in ProgressMonitor - premature return<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved */ #include "../StroikaPreComp.h" #include "ProgressMonitor.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Execution; /* ******************************************************************************** **************************** ProgressMonitor *********************************** ******************************************************************************** */ ProgressMonitor::ProgressMonitor () : fRep_ (new IRep_ ()) { } ProgressMonitor::ProgressMonitor (Thread workThread) : fRep_ (new IRep_ ()) { } ProgressMonitor::~ProgressMonitor () { } void ProgressMonitor::AddOnProgressCallback (const ChangedCallbackType& progressChangedCallback) { RequireNotNull (fRep_); fRep_->fCallbacks_.Append (progressChangedCallback); } void ProgressMonitor::Cancel () { RequireNotNull (fRep_); fRep_->fCanceled_ = true; if (fRep_->fWorkThread_.GetStatus () != Thread::Status::eNull) { fRep_->fWorkThread_.Abort (); } } /* ******************************************************************************** *************************** ProgressMonitor::Updater *************************** ******************************************************************************** */ void ProgressMonitor::Updater::CallNotifyProgress_ () const { RequireNotNull (fRep_); for (ChangedCallbackType f : fRep_->fCallbacks_) { f (ProgressMonitor (fRep_)); } } <|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 "itkGibbsTrackingFilter.h" // MITK #include <itkOrientationDistributionFunction.h> #include <itkDiffusionQballGeneralizedFaImageFilter.h> #include <mitkStandardFileLocations.h> #include <mitkFiberBuilder.h> #include <mitkMetropolisHastingsSampler.h> #include <mitkEnergyComputer.h> #include <itkTensorImageToQBallImageFilter.h> // ITK #include <itkImageDuplicator.h> #include <itkResampleImageFilter.h> // MISC #include <fstream> #include <QFile> #include <tinyxml.h> #include <math.h> namespace itk{ template< class ItkQBallImageType > GibbsTrackingFilter< ItkQBallImageType >::GibbsTrackingFilter(): m_StartTemperature(0.1), m_EndTemperature(0.001), m_Iterations(500000), m_ParticleWeight(0), m_ParticleWidth(0), m_ParticleLength(0), m_ConnectionPotential(10), m_InexBalance(0), m_ParticlePotential(0.2), m_MinFiberLength(10), m_AbortTracking(false), m_NumConnections(0), m_NumParticles(0), m_NumAcceptedFibers(0), m_CurrentStep(0), m_BuildFibers(false), m_Steps(10), m_ProposalAcceptance(0), m_CurvatureThreshold(0.7), m_DuplicateImage(true), m_RandomSeed(-1), m_ParameterFile(""), m_LutPath("") { } template< class ItkQBallImageType > GibbsTrackingFilter< ItkQBallImageType >::~GibbsTrackingFilter() { } // fill output fiber bundle datastructure template< class ItkQBallImageType > typename GibbsTrackingFilter< ItkQBallImageType >::FiberPolyDataType GibbsTrackingFilter< ItkQBallImageType >::GetFiberBundle() { if (!m_AbortTracking) { m_BuildFibers = true; while (m_BuildFibers){} } return m_FiberPolyData; } template< class ItkQBallImageType > bool GibbsTrackingFilter< ItkQBallImageType > ::EstimateParticleWeight() { MITK_INFO << "GibbsTrackingFilter: estimating particle weight"; typedef itk::DiffusionQballGeneralizedFaImageFilter<float,float,QBALL_ODFSIZE> GfaFilterType; GfaFilterType::Pointer gfaFilter = GfaFilterType::New(); gfaFilter->SetInput(m_QBallImage); gfaFilter->SetComputationMethod(GfaFilterType::GFA_STANDARD); gfaFilter->Update(); ItkFloatImageType::Pointer gfaImage = gfaFilter->GetOutput(); float samplingStart = 1.0; float samplingStop = 0.66; // GFA iterator typedef ImageRegionIterator< ItkFloatImageType > GfaIteratorType; GfaIteratorType gfaIt(gfaImage, gfaImage->GetLargestPossibleRegion() ); // Mask iterator typedef ImageRegionConstIterator< ItkFloatImageType > MaskIteratorType; MaskIteratorType mit(m_MaskImage, m_MaskImage->GetLargestPossibleRegion() ); // Input iterator typedef ImageRegionConstIterator< ItkQBallImageType > InputIteratorType; InputIteratorType it(m_QBallImage, m_QBallImage->GetLargestPossibleRegion() ); float upper = 0; int count = 0; for(float thr=samplingStart; thr>samplingStop; thr-=0.01) { it.GoToBegin(); mit.GoToBegin(); gfaIt.GoToBegin(); while( !gfaIt.IsAtEnd() ) { if(gfaIt.Get()>thr && mit.Get()>0) { itk::OrientationDistributionFunction<float, QBALL_ODFSIZE> odf(it.Get().GetDataPointer()); upper += odf.GetMaxValue()-odf.GetMeanValue(); ++count; } ++it; ++mit; ++gfaIt; } } if (count>0) upper /= count; else return false; m_ParticleWeight = upper/6; return true; } // perform global tracking template< class ItkQBallImageType > void GibbsTrackingFilter< ItkQBallImageType >::GenerateData() { // check if input is qball or tensor image and generate qball if necessary if (m_QBallImage.IsNull() && m_TensorImage.IsNotNull()) { TensorImageToQBallImageFilter<float,float>::Pointer filter = TensorImageToQBallImageFilter<float,float>::New(); filter->SetInput( m_TensorImage ); filter->Update(); m_QBallImage = filter->GetOutput(); } // generate local working copy of QBall image (if not disabled) if (m_DuplicateImage) { typedef itk::ImageDuplicator< ItkQBallImageType > DuplicateFilterType; typename DuplicateFilterType::Pointer duplicator = DuplicateFilterType::New(); duplicator->SetInputImage( m_QBallImage ); duplicator->Update(); m_QBallImage = duplicator->GetOutput(); } // perform mean subtraction on odfs typedef ImageRegionIterator< ItkQBallImageType > InputIteratorType; InputIteratorType it(m_QBallImage, m_QBallImage->GetLargestPossibleRegion() ); it.GoToBegin(); while (!it.IsAtEnd()) { itk::OrientationDistributionFunction<float, QBALL_ODFSIZE> odf(it.Get().GetDataPointer()); float mean = odf.GetMeanValue(); odf -= mean; it.Set(odf.GetDataPointer()); ++it; } // check if mask image is given if it needs resampling PrepareMaskImage(); // load parameter file LoadParameters(m_ParameterFile); // prepare parameters float minSpacing; if(m_QBallImage->GetSpacing()[0]<m_QBallImage->GetSpacing()[1] && m_QBallImage->GetSpacing()[0]<m_QBallImage->GetSpacing()[2]) minSpacing = m_QBallImage->GetSpacing()[0]; else if (m_QBallImage->GetSpacing()[1] < m_QBallImage->GetSpacing()[2]) minSpacing = m_QBallImage->GetSpacing()[1]; else minSpacing = m_QBallImage->GetSpacing()[2]; if(m_ParticleLength == 0) m_ParticleLength = 1.5*minSpacing; if(m_ParticleWidth == 0) m_ParticleWidth = 0.5*minSpacing; if(m_ParticleWeight == 0) if (!EstimateParticleWeight()) { MITK_INFO << "GibbsTrackingFilter: could not estimate particle weight. using default value."; m_ParticleWeight = 0.0001; } float alpha = log(m_EndTemperature/m_StartTemperature); m_Steps = m_Iterations/10000; if (m_Steps<10) m_Steps = 10; if (m_Steps>m_Iterations) { MITK_INFO << "GibbsTrackingFilter: not enough iterations!"; m_AbortTracking = true; } if (m_CurvatureThreshold < mitk::eps) m_CurvatureThreshold = 0; unsigned long singleIts = (unsigned long)((1.0*m_Iterations) / (1.0*m_Steps)); // seed random generators Statistics::MersenneTwisterRandomVariateGenerator::Pointer randGen = Statistics::MersenneTwisterRandomVariateGenerator::New(); if (m_RandomSeed>-1) randGen->SetSeed(m_RandomSeed); // load sphere interpolator to evaluate the ODFs SphereInterpolator* interpolator = new SphereInterpolator(m_LutPath); // initialize the actual tracking components (ParticleGrid, Metropolis Hastings Sampler and Energy Computer) ParticleGrid* particleGrid = new ParticleGrid(m_MaskImage, m_ParticleLength); EnergyComputer* encomp = new EnergyComputer(m_QBallImage, m_MaskImage, particleGrid, interpolator, randGen); encomp->SetParameters(m_ParticleWeight,m_ParticleWidth,m_ConnectionPotential*m_ParticleLength*m_ParticleLength,m_CurvatureThreshold,m_InexBalance,m_ParticlePotential); MetropolisHastingsSampler* sampler = new MetropolisHastingsSampler(particleGrid, encomp, randGen, m_CurvatureThreshold); MITK_INFO << "----------------------------------------"; MITK_INFO << "Iterations: " << m_Iterations; MITK_INFO << "Steps: " << m_Steps; MITK_INFO << "Particle length: " << m_ParticleLength; MITK_INFO << "Particle width: " << m_ParticleWidth; MITK_INFO << "Particle weight: " << m_ParticleWeight; MITK_INFO << "Start temperature: " << m_StartTemperature; MITK_INFO << "End temperature: " << m_EndTemperature; MITK_INFO << "In/Ex balance: " << m_InexBalance; MITK_INFO << "Min. fiber length: " << m_MinFiberLength; MITK_INFO << "Curvature threshold: " << m_CurvatureThreshold; MITK_INFO << "Random seed: " << m_RandomSeed; MITK_INFO << "----------------------------------------"; // main loop m_NumAcceptedFibers = 0; unsigned long counter = 1; for( m_CurrentStep = 1; m_CurrentStep <= m_Steps; m_CurrentStep++ ) { // update temperatur for simulated annealing process float temperature = m_StartTemperature * exp(alpha*(((1.0)*m_CurrentStep)/((1.0)*m_Steps))); sampler->SetTemperature(temperature); for (unsigned long i=0; i<singleIts; i++) { if (m_AbortTracking) break; sampler->MakeProposal(); if (m_BuildFibers || (i==singleIts-1 && m_CurrentStep==m_Steps)) { m_ProposalAcceptance = (float)sampler->GetNumAcceptedProposals()/counter; m_NumParticles = particleGrid->m_NumParticles; m_NumConnections = particleGrid->m_NumConnections; FiberBuilder fiberBuilder(particleGrid, m_MaskImage); m_FiberPolyData = fiberBuilder.iterate(m_MinFiberLength); m_NumAcceptedFibers = m_FiberPolyData->GetNumberOfLines(); m_BuildFibers = false; } counter++; } m_ProposalAcceptance = (float)sampler->GetNumAcceptedProposals()/counter; m_NumParticles = particleGrid->m_NumParticles; m_NumConnections = particleGrid->m_NumConnections; MITK_INFO << "GibbsTrackingFilter: proposal acceptance: " << 100*m_ProposalAcceptance << "%"; MITK_INFO << "GibbsTrackingFilter: particles: " << m_NumParticles; MITK_INFO << "GibbsTrackingFilter: connections: " << m_NumConnections; MITK_INFO << "GibbsTrackingFilter: progress: " << 100*(float)m_CurrentStep/m_Steps << "%"; MITK_INFO << "----------------------------------------"; if (m_AbortTracking) break; } delete sampler; delete encomp; delete interpolator; delete particleGrid; m_AbortTracking = true; m_BuildFibers = false; MITK_INFO << "GibbsTrackingFilter: done generate data"; } template< class ItkQBallImageType > void GibbsTrackingFilter< ItkQBallImageType >::PrepareMaskImage() { if(m_MaskImage.IsNull()) { MITK_INFO << "GibbsTrackingFilter: generating default mask image"; m_MaskImage = ItkFloatImageType::New(); m_MaskImage->SetSpacing( m_QBallImage->GetSpacing() ); m_MaskImage->SetOrigin( m_QBallImage->GetOrigin() ); m_MaskImage->SetDirection( m_QBallImage->GetDirection() ); m_MaskImage->SetRegions( m_QBallImage->GetLargestPossibleRegion() ); m_MaskImage->Allocate(); m_MaskImage->FillBuffer(1.0); } else if ( m_MaskImage->GetLargestPossibleRegion().GetSize()[0]!=m_QBallImage->GetLargestPossibleRegion().GetSize()[0] || m_MaskImage->GetLargestPossibleRegion().GetSize()[1]!=m_QBallImage->GetLargestPossibleRegion().GetSize()[1] || m_MaskImage->GetLargestPossibleRegion().GetSize()[2]!=m_QBallImage->GetLargestPossibleRegion().GetSize()[2] || m_MaskImage->GetSpacing()[0]!=m_QBallImage->GetSpacing()[0] || m_MaskImage->GetSpacing()[1]!=m_QBallImage->GetSpacing()[1] || m_MaskImage->GetSpacing()[2]!=m_QBallImage->GetSpacing()[2] ) { MITK_INFO << "GibbsTrackingFilter: resampling mask image"; typedef itk::ResampleImageFilter< ItkFloatImageType, ItkFloatImageType, float > ResamplerType; ResamplerType::Pointer resampler = ResamplerType::New(); resampler->SetOutputSpacing( m_QBallImage->GetSpacing() ); resampler->SetOutputOrigin( m_QBallImage->GetOrigin() ); resampler->SetOutputDirection( m_QBallImage->GetDirection() ); resampler->SetSize( m_QBallImage->GetLargestPossibleRegion().GetSize() ); resampler->SetInput( m_MaskImage ); resampler->SetDefaultPixelValue(1.0); resampler->Update(); m_MaskImage = resampler->GetOutput(); MITK_INFO << "GibbsTrackingFilter: resampling finished"; } } // load current tracking paramters from xml file (.gtp) template< class ItkQBallImageType > bool GibbsTrackingFilter< ItkQBallImageType >::LoadParameters(std::string filename) { m_AbortTracking = true; try { if( filename.length()==0 ) { m_AbortTracking = false; return true; } MITK_INFO << "GibbsTrackingFilter: loading parameter file " << filename; TiXmlDocument doc( filename ); doc.LoadFile(); TiXmlHandle hDoc(&doc); TiXmlElement* pElem; TiXmlHandle hRoot(0); pElem = hDoc.FirstChildElement().Element(); hRoot = TiXmlHandle(pElem); pElem = hRoot.FirstChildElement("parameter_set").Element(); QString iterations(pElem->Attribute("iterations")); m_Iterations = iterations.toULong(); QString particleLength(pElem->Attribute("particle_length")); m_ParticleLength = particleLength.toFloat(); QString particleWidth(pElem->Attribute("particle_width")); m_ParticleWidth = particleWidth.toFloat(); QString partWeight(pElem->Attribute("particle_weight")); m_ParticleWeight = partWeight.toFloat(); QString startTemp(pElem->Attribute("temp_start")); m_StartTemperature = startTemp.toFloat(); QString endTemp(pElem->Attribute("temp_end")); m_EndTemperature = endTemp.toFloat(); QString inExBalance(pElem->Attribute("inexbalance")); m_InexBalance = inExBalance.toFloat(); QString fiberLength(pElem->Attribute("fiber_length")); m_MinFiberLength = fiberLength.toFloat(); QString curvThres(pElem->Attribute("curvature_threshold")); m_CurvatureThreshold = cos(curvThres.toFloat()*M_PI/180); m_AbortTracking = false; MITK_INFO << "GibbsTrackingFilter: parameter file loaded successfully"; return true; } catch(...) { MITK_INFO << "GibbsTrackingFilter: could not load parameter file"; return false; } } } <commit_msg>only copy image if it is qball<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 "itkGibbsTrackingFilter.h" // MITK #include <itkOrientationDistributionFunction.h> #include <itkDiffusionQballGeneralizedFaImageFilter.h> #include <mitkStandardFileLocations.h> #include <mitkFiberBuilder.h> #include <mitkMetropolisHastingsSampler.h> #include <mitkEnergyComputer.h> #include <itkTensorImageToQBallImageFilter.h> // ITK #include <itkImageDuplicator.h> #include <itkResampleImageFilter.h> // MISC #include <fstream> #include <QFile> #include <tinyxml.h> #include <math.h> namespace itk{ template< class ItkQBallImageType > GibbsTrackingFilter< ItkQBallImageType >::GibbsTrackingFilter(): m_StartTemperature(0.1), m_EndTemperature(0.001), m_Iterations(500000), m_ParticleWeight(0), m_ParticleWidth(0), m_ParticleLength(0), m_ConnectionPotential(10), m_InexBalance(0), m_ParticlePotential(0.2), m_MinFiberLength(10), m_AbortTracking(false), m_NumConnections(0), m_NumParticles(0), m_NumAcceptedFibers(0), m_CurrentStep(0), m_BuildFibers(false), m_Steps(10), m_ProposalAcceptance(0), m_CurvatureThreshold(0.7), m_DuplicateImage(true), m_RandomSeed(-1), m_ParameterFile(""), m_LutPath("") { } template< class ItkQBallImageType > GibbsTrackingFilter< ItkQBallImageType >::~GibbsTrackingFilter() { } // fill output fiber bundle datastructure template< class ItkQBallImageType > typename GibbsTrackingFilter< ItkQBallImageType >::FiberPolyDataType GibbsTrackingFilter< ItkQBallImageType >::GetFiberBundle() { if (!m_AbortTracking) { m_BuildFibers = true; while (m_BuildFibers){} } return m_FiberPolyData; } template< class ItkQBallImageType > bool GibbsTrackingFilter< ItkQBallImageType > ::EstimateParticleWeight() { MITK_INFO << "GibbsTrackingFilter: estimating particle weight"; typedef itk::DiffusionQballGeneralizedFaImageFilter<float,float,QBALL_ODFSIZE> GfaFilterType; GfaFilterType::Pointer gfaFilter = GfaFilterType::New(); gfaFilter->SetInput(m_QBallImage); gfaFilter->SetComputationMethod(GfaFilterType::GFA_STANDARD); gfaFilter->Update(); ItkFloatImageType::Pointer gfaImage = gfaFilter->GetOutput(); float samplingStart = 1.0; float samplingStop = 0.66; // GFA iterator typedef ImageRegionIterator< ItkFloatImageType > GfaIteratorType; GfaIteratorType gfaIt(gfaImage, gfaImage->GetLargestPossibleRegion() ); // Mask iterator typedef ImageRegionConstIterator< ItkFloatImageType > MaskIteratorType; MaskIteratorType mit(m_MaskImage, m_MaskImage->GetLargestPossibleRegion() ); // Input iterator typedef ImageRegionConstIterator< ItkQBallImageType > InputIteratorType; InputIteratorType it(m_QBallImage, m_QBallImage->GetLargestPossibleRegion() ); float upper = 0; int count = 0; for(float thr=samplingStart; thr>samplingStop; thr-=0.01) { it.GoToBegin(); mit.GoToBegin(); gfaIt.GoToBegin(); while( !gfaIt.IsAtEnd() ) { if(gfaIt.Get()>thr && mit.Get()>0) { itk::OrientationDistributionFunction<float, QBALL_ODFSIZE> odf(it.Get().GetDataPointer()); upper += odf.GetMaxValue()-odf.GetMeanValue(); ++count; } ++it; ++mit; ++gfaIt; } } if (count>0) upper /= count; else return false; m_ParticleWeight = upper/6; return true; } // perform global tracking template< class ItkQBallImageType > void GibbsTrackingFilter< ItkQBallImageType >::GenerateData() { // check if input is qball or tensor image and generate qball if necessary if (m_QBallImage.IsNull() && m_TensorImage.IsNotNull()) { TensorImageToQBallImageFilter<float,float>::Pointer filter = TensorImageToQBallImageFilter<float,float>::New(); filter->SetInput( m_TensorImage ); filter->Update(); m_QBallImage = filter->GetOutput(); } else if (m_DuplicateImage) // generate local working copy of QBall image (if not disabled) { typedef itk::ImageDuplicator< ItkQBallImageType > DuplicateFilterType; typename DuplicateFilterType::Pointer duplicator = DuplicateFilterType::New(); duplicator->SetInputImage( m_QBallImage ); duplicator->Update(); m_QBallImage = duplicator->GetOutput(); } // perform mean subtraction on odfs typedef ImageRegionIterator< ItkQBallImageType > InputIteratorType; InputIteratorType it(m_QBallImage, m_QBallImage->GetLargestPossibleRegion() ); it.GoToBegin(); while (!it.IsAtEnd()) { itk::OrientationDistributionFunction<float, QBALL_ODFSIZE> odf(it.Get().GetDataPointer()); float mean = odf.GetMeanValue(); odf -= mean; it.Set(odf.GetDataPointer()); ++it; } // check if mask image is given if it needs resampling PrepareMaskImage(); // load parameter file LoadParameters(m_ParameterFile); // prepare parameters float minSpacing; if(m_QBallImage->GetSpacing()[0]<m_QBallImage->GetSpacing()[1] && m_QBallImage->GetSpacing()[0]<m_QBallImage->GetSpacing()[2]) minSpacing = m_QBallImage->GetSpacing()[0]; else if (m_QBallImage->GetSpacing()[1] < m_QBallImage->GetSpacing()[2]) minSpacing = m_QBallImage->GetSpacing()[1]; else minSpacing = m_QBallImage->GetSpacing()[2]; if(m_ParticleLength == 0) m_ParticleLength = 1.5*minSpacing; if(m_ParticleWidth == 0) m_ParticleWidth = 0.5*minSpacing; if(m_ParticleWeight == 0) if (!EstimateParticleWeight()) { MITK_INFO << "GibbsTrackingFilter: could not estimate particle weight. using default value."; m_ParticleWeight = 0.0001; } float alpha = log(m_EndTemperature/m_StartTemperature); m_Steps = m_Iterations/10000; if (m_Steps<10) m_Steps = 10; if (m_Steps>m_Iterations) { MITK_INFO << "GibbsTrackingFilter: not enough iterations!"; m_AbortTracking = true; } if (m_CurvatureThreshold < mitk::eps) m_CurvatureThreshold = 0; unsigned long singleIts = (unsigned long)((1.0*m_Iterations) / (1.0*m_Steps)); // seed random generators Statistics::MersenneTwisterRandomVariateGenerator::Pointer randGen = Statistics::MersenneTwisterRandomVariateGenerator::New(); if (m_RandomSeed>-1) randGen->SetSeed(m_RandomSeed); // load sphere interpolator to evaluate the ODFs SphereInterpolator* interpolator = new SphereInterpolator(m_LutPath); // initialize the actual tracking components (ParticleGrid, Metropolis Hastings Sampler and Energy Computer) ParticleGrid* particleGrid = new ParticleGrid(m_MaskImage, m_ParticleLength); EnergyComputer* encomp = new EnergyComputer(m_QBallImage, m_MaskImage, particleGrid, interpolator, randGen); encomp->SetParameters(m_ParticleWeight,m_ParticleWidth,m_ConnectionPotential*m_ParticleLength*m_ParticleLength,m_CurvatureThreshold,m_InexBalance,m_ParticlePotential); MetropolisHastingsSampler* sampler = new MetropolisHastingsSampler(particleGrid, encomp, randGen, m_CurvatureThreshold); MITK_INFO << "----------------------------------------"; MITK_INFO << "Iterations: " << m_Iterations; MITK_INFO << "Steps: " << m_Steps; MITK_INFO << "Particle length: " << m_ParticleLength; MITK_INFO << "Particle width: " << m_ParticleWidth; MITK_INFO << "Particle weight: " << m_ParticleWeight; MITK_INFO << "Start temperature: " << m_StartTemperature; MITK_INFO << "End temperature: " << m_EndTemperature; MITK_INFO << "In/Ex balance: " << m_InexBalance; MITK_INFO << "Min. fiber length: " << m_MinFiberLength; MITK_INFO << "Curvature threshold: " << m_CurvatureThreshold; MITK_INFO << "Random seed: " << m_RandomSeed; MITK_INFO << "----------------------------------------"; // main loop m_NumAcceptedFibers = 0; unsigned long counter = 1; for( m_CurrentStep = 1; m_CurrentStep <= m_Steps; m_CurrentStep++ ) { // update temperatur for simulated annealing process float temperature = m_StartTemperature * exp(alpha*(((1.0)*m_CurrentStep)/((1.0)*m_Steps))); sampler->SetTemperature(temperature); for (unsigned long i=0; i<singleIts; i++) { if (m_AbortTracking) break; sampler->MakeProposal(); if (m_BuildFibers || (i==singleIts-1 && m_CurrentStep==m_Steps)) { m_ProposalAcceptance = (float)sampler->GetNumAcceptedProposals()/counter; m_NumParticles = particleGrid->m_NumParticles; m_NumConnections = particleGrid->m_NumConnections; FiberBuilder fiberBuilder(particleGrid, m_MaskImage); m_FiberPolyData = fiberBuilder.iterate(m_MinFiberLength); m_NumAcceptedFibers = m_FiberPolyData->GetNumberOfLines(); m_BuildFibers = false; } counter++; } m_ProposalAcceptance = (float)sampler->GetNumAcceptedProposals()/counter; m_NumParticles = particleGrid->m_NumParticles; m_NumConnections = particleGrid->m_NumConnections; MITK_INFO << "GibbsTrackingFilter: proposal acceptance: " << 100*m_ProposalAcceptance << "%"; MITK_INFO << "GibbsTrackingFilter: particles: " << m_NumParticles; MITK_INFO << "GibbsTrackingFilter: connections: " << m_NumConnections; MITK_INFO << "GibbsTrackingFilter: progress: " << 100*(float)m_CurrentStep/m_Steps << "%"; MITK_INFO << "GibbsTrackingFilter: cell overflows: " << particleGrid->m_NumCellOverflows; MITK_INFO << "----------------------------------------"; if (m_AbortTracking) break; } delete sampler; delete encomp; delete interpolator; delete particleGrid; m_AbortTracking = true; m_BuildFibers = false; MITK_INFO << "GibbsTrackingFilter: done generate data"; } template< class ItkQBallImageType > void GibbsTrackingFilter< ItkQBallImageType >::PrepareMaskImage() { if(m_MaskImage.IsNull()) { MITK_INFO << "GibbsTrackingFilter: generating default mask image"; m_MaskImage = ItkFloatImageType::New(); m_MaskImage->SetSpacing( m_QBallImage->GetSpacing() ); m_MaskImage->SetOrigin( m_QBallImage->GetOrigin() ); m_MaskImage->SetDirection( m_QBallImage->GetDirection() ); m_MaskImage->SetRegions( m_QBallImage->GetLargestPossibleRegion() ); m_MaskImage->Allocate(); m_MaskImage->FillBuffer(1.0); } else if ( m_MaskImage->GetLargestPossibleRegion().GetSize()[0]!=m_QBallImage->GetLargestPossibleRegion().GetSize()[0] || m_MaskImage->GetLargestPossibleRegion().GetSize()[1]!=m_QBallImage->GetLargestPossibleRegion().GetSize()[1] || m_MaskImage->GetLargestPossibleRegion().GetSize()[2]!=m_QBallImage->GetLargestPossibleRegion().GetSize()[2] || m_MaskImage->GetSpacing()[0]!=m_QBallImage->GetSpacing()[0] || m_MaskImage->GetSpacing()[1]!=m_QBallImage->GetSpacing()[1] || m_MaskImage->GetSpacing()[2]!=m_QBallImage->GetSpacing()[2] ) { MITK_INFO << "GibbsTrackingFilter: resampling mask image"; typedef itk::ResampleImageFilter< ItkFloatImageType, ItkFloatImageType, float > ResamplerType; ResamplerType::Pointer resampler = ResamplerType::New(); resampler->SetOutputSpacing( m_QBallImage->GetSpacing() ); resampler->SetOutputOrigin( m_QBallImage->GetOrigin() ); resampler->SetOutputDirection( m_QBallImage->GetDirection() ); resampler->SetSize( m_QBallImage->GetLargestPossibleRegion().GetSize() ); resampler->SetInput( m_MaskImage ); resampler->SetDefaultPixelValue(1.0); resampler->Update(); m_MaskImage = resampler->GetOutput(); MITK_INFO << "GibbsTrackingFilter: resampling finished"; } } // load current tracking paramters from xml file (.gtp) template< class ItkQBallImageType > bool GibbsTrackingFilter< ItkQBallImageType >::LoadParameters(std::string filename) { m_AbortTracking = true; try { if( filename.length()==0 ) { m_AbortTracking = false; return true; } MITK_INFO << "GibbsTrackingFilter: loading parameter file " << filename; TiXmlDocument doc( filename ); doc.LoadFile(); TiXmlHandle hDoc(&doc); TiXmlElement* pElem; TiXmlHandle hRoot(0); pElem = hDoc.FirstChildElement().Element(); hRoot = TiXmlHandle(pElem); pElem = hRoot.FirstChildElement("parameter_set").Element(); QString iterations(pElem->Attribute("iterations")); m_Iterations = iterations.toULong(); QString particleLength(pElem->Attribute("particle_length")); m_ParticleLength = particleLength.toFloat(); QString particleWidth(pElem->Attribute("particle_width")); m_ParticleWidth = particleWidth.toFloat(); QString partWeight(pElem->Attribute("particle_weight")); m_ParticleWeight = partWeight.toFloat(); QString startTemp(pElem->Attribute("temp_start")); m_StartTemperature = startTemp.toFloat(); QString endTemp(pElem->Attribute("temp_end")); m_EndTemperature = endTemp.toFloat(); QString inExBalance(pElem->Attribute("inexbalance")); m_InexBalance = inExBalance.toFloat(); QString fiberLength(pElem->Attribute("fiber_length")); m_MinFiberLength = fiberLength.toFloat(); QString curvThres(pElem->Attribute("curvature_threshold")); m_CurvatureThreshold = cos(curvThres.toFloat()*M_PI/180); m_AbortTracking = false; MITK_INFO << "GibbsTrackingFilter: parameter file loaded successfully"; return true; } catch(...) { MITK_INFO << "GibbsTrackingFilter: could not load parameter file"; return false; } } } <|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 "mitkNavigationDataToIGTLMessageFilter.h" #include "igtlQuaternionTrackingDataMessage.h" #include "igtlTrackingDataMessage.h" #include "igtlTransformMessage.h" #include "igtlPositionMessage.h" #include <mitkInteractionConst.h> #include <itksys/SystemTools.hxx> mitk::NavigationDataToIGTLMessageFilter::NavigationDataToIGTLMessageFilter() { mitk::IGTLMessage::Pointer output = mitk::IGTLMessage::New(); this->SetNumberOfRequiredOutputs(1); this->SetNthOutput(0, output.GetPointer()); this->SetNumberOfRequiredInputs(1); // m_OperationMode = Mode3D; m_CurrentTimeStep = 0; // m_RingBufferSize = 50; //the default ring buffer size // m_NumberForMean = 100; } mitk::NavigationDataToIGTLMessageFilter::~NavigationDataToIGTLMessageFilter() { } void mitk::NavigationDataToIGTLMessageFilter::GenerateData() { switch (m_OperationMode) { case ModeSendQTDataMsg: this->GenerateDataModeSendQTDataMsg(); break; case ModeSendTDataMsg: this->GenerateDataModeSendTDataMsg(); break; case ModeSendQTransMsg: this->GenerateDataModeSendQTransMsg(); break; case ModeSendTransMsg: this->GenerateDataModeSendTransMsg(); break; default: break; } igtl::MessageBase::Pointer curMessage = this->GetOutput()->GetMessage(); if (dynamic_cast<igtl::TrackingDataMessage*>(curMessage.GetPointer()) != nullptr) { igtl::TrackingDataMessage* tdMsg = (igtl::TrackingDataMessage*)(curMessage.GetPointer()); } } void mitk::NavigationDataToIGTLMessageFilter::SetInput(const NavigationData* nd) { // Process object is not const-correct so the const_cast is required here this->ProcessObject::SetNthInput(0, const_cast<NavigationData*>(nd)); this->CreateOutputsForAllInputs(); } void mitk::NavigationDataToIGTLMessageFilter::SetInput(unsigned int idx, const NavigationData* nd) { // Process object is not const-correct so the const_cast is required here this->ProcessObject::SetNthInput(idx, const_cast<NavigationData*>(nd)); this->CreateOutputsForAllInputs(); } const mitk::NavigationData* mitk::NavigationDataToIGTLMessageFilter::GetInput(void) { if (this->GetNumberOfInputs() < 1) return NULL; return static_cast<const NavigationData*>(this->ProcessObject::GetInput(0)); } const mitk::NavigationData* mitk::NavigationDataToIGTLMessageFilter::GetInput(unsigned int idx) { if (this->GetNumberOfInputs() < 1) return NULL; return static_cast<const NavigationData*>(this->ProcessObject::GetInput(idx)); } void mitk::NavigationDataToIGTLMessageFilter::CreateOutputsForAllInputs() { switch (m_OperationMode) { case ModeSendQTDataMsg: // create one message output for all navigation data inputs this->SetNumberOfIndexedOutputs(this->GetNumberOfIndexedInputs()); // set the type for this filter this->SetType("QTDATA"); break; case ModeSendTDataMsg: // create one message output for all navigation data inputs this->SetNumberOfIndexedOutputs(this->GetNumberOfIndexedInputs()); // set the type for this filter this->SetType("TDATA"); break; case ModeSendQTransMsg: // create one message output for all navigation data input together this->SetNumberOfIndexedOutputs(this->GetNumberOfIndexedInputs()); // set the type for this filter this->SetType("POSITION"); break; case ModeSendTransMsg: // create one message output for all navigation data input together this->SetNumberOfIndexedOutputs(this->GetNumberOfIndexedInputs()); // set the type for this filter this->SetType("TRANS"); break; default: break; } for (unsigned int idx = 0; idx < this->GetNumberOfIndexedOutputs(); ++idx) { if (this->GetOutput(idx) == NULL) { DataObjectPointer newOutput = this->MakeOutput(idx); this->SetNthOutput(idx, newOutput); } this->Modified(); } } void ConvertAffineTransformationIntoIGTLMatrix(mitk::AffineTransform3D* trans, igtl::Matrix4x4 igtlTransform) { const mitk::AffineTransform3D::MatrixType& matrix = trans->GetMatrix(); mitk::Vector3D position = trans->GetOffset(); //copy the data into a matrix type that igtl understands for (unsigned int r = 0; r < 3; r++) { for (unsigned int c = 0; c < 3; c++) { igtlTransform[r][c] = matrix(r, c); } igtlTransform[r][3] = position[r]; } for (unsigned int c = 0; c < 3; c++) { igtlTransform[3][c] = 0.0; } igtlTransform[3][3] = 1.0; } void mitk::NavigationDataToIGTLMessageFilter::GenerateDataModeSendQTransMsg() { // for each output message for (unsigned int i = 0; i < this->GetNumberOfIndexedOutputs(); ++i) { mitk::IGTLMessage* output = this->GetOutput(i); assert(output); const mitk::NavigationData* input = this->GetInput(i); assert(input); // do not add navigation data to message if input is invalid if (input->IsDataValid() == false) continue; //get the navigation data components mitk::NavigationData::PositionType pos = input->GetPosition(); mitk::NavigationData::OrientationType ori = input->GetOrientation(); //insert this information into the message igtl::PositionMessage::Pointer posMsg = igtl::PositionMessage::New(); posMsg->SetPosition(pos[0], pos[1], pos[2]); posMsg->SetQuaternion(ori[0], ori[1], ori[2], ori[3]); posMsg->SetTimeStamp(ConvertToIGTLTimeStamp(input->GetIGTTimeStamp())); posMsg->SetDeviceName(input->GetName()); posMsg->Pack(); //add the igtl message to the mitk::IGTLMessage output->SetMessage(posMsg.GetPointer()); } } void mitk::NavigationDataToIGTLMessageFilter::GenerateDataModeSendTransMsg() { // for each output message for (unsigned int i = 0; i < this->GetNumberOfIndexedOutputs(); ++i) { mitk::IGTLMessage* output = this->GetOutput(i); assert(output); const mitk::NavigationData* input = this->GetInput(i); assert(input); // do not add navigation data to message if input is invalid if (input->IsDataValid() == false) continue; //get the navigation data components mitk::AffineTransform3D::Pointer transform = input->GetAffineTransform3D(); mitk::NavigationData::PositionType position = transform->GetOffset(); //convert the transform into a igtl type igtl::Matrix4x4 igtlTransform; ConvertAffineTransformationIntoIGTLMatrix(transform, igtlTransform); //insert this information into the message igtl::TransformMessage::Pointer transMsg = igtl::TransformMessage::New(); transMsg->SetMatrix(igtlTransform); transMsg->SetPosition(position[0], position[1], position[2]); transMsg->SetTimeStamp(ConvertToIGTLTimeStamp(input->GetIGTTimeStamp())); transMsg->SetDeviceName(input->GetName()); transMsg->Pack(); //add the igtl message to the mitk::IGTLMessage output->SetMessage(transMsg.GetPointer()); } } igtl::TimeStamp::Pointer mitk::NavigationDataToIGTLMessageFilter::ConvertToIGTLTimeStamp(double IGTTimeStamp) { igtl::TimeStamp::Pointer timestamp = igtl::TimeStamp::New(); timestamp->SetTime(IGTTimeStamp / 1000, (int)(IGTTimeStamp) % 1000); return timestamp; } void mitk::NavigationDataToIGTLMessageFilter::GenerateDataModeSendQTDataMsg() { mitk::IGTLMessage* output = this->GetOutput(); assert(output); //create a output igtl message igtl::QuaternionTrackingDataMessage::Pointer qtdMsg = igtl::QuaternionTrackingDataMessage::New(); mitk::NavigationData::PositionType pos; mitk::NavigationData::OrientationType ori; for (unsigned int index = 0; index < this->GetNumberOfIndexedInputs(); index++) { const mitk::NavigationData* nd = GetInput(index); assert(nd); //get the navigation data components pos = nd->GetPosition(); ori = nd->GetOrientation(); //insert the information into the tracking element igtl::QuaternionTrackingDataElement::Pointer tde = igtl::QuaternionTrackingDataElement::New(); tde->SetPosition(pos[0], pos[1], pos[2]); tde->SetQuaternion(ori[0], ori[1], ori[2], ori[3]); tde->SetName(nd->GetName()); //insert this element into the tracking data message qtdMsg->AddQuaternionTrackingDataElement(tde); MITK_INFO << ConvertToIGTLTimeStamp(nd->GetIGTTimeStamp()); } qtdMsg->Pack(); //add the igtl message to the mitk::IGTLMessage output->SetMessage(qtdMsg.GetPointer()); } void mitk::NavigationDataToIGTLMessageFilter::GenerateDataModeSendTDataMsg() { bool isValidData = true; mitk::IGTLMessage* output = this->GetOutput(); assert(output); //create a output igtl message igtl::TrackingDataMessage::Pointer tdMsg = igtl::TrackingDataMessage::New(); mitk::AffineTransform3D::Pointer transform; Vector3D position; igtl::Matrix4x4 igtlTransform; vnl_matrix_fixed<ScalarType, 3, 3> rotationMatrix; vnl_matrix_fixed<ScalarType, 3, 3> rotationMatrixTransposed; for (unsigned int index = 0; index < this->GetNumberOfIndexedInputs(); index++) { const mitk::NavigationData* nd = GetInput(index); assert(nd); //create a new tracking element igtl::TrackingDataElement::Pointer tde = igtl::TrackingDataElement::New(); //get the navigation data components transform = nd->GetAffineTransform3D(); position = transform->GetOffset(); //check the rotation matrix rotationMatrix = transform->GetMatrix().GetVnlMatrix(); rotationMatrixTransposed = rotationMatrix.transpose(); // a quadratic matrix is a rotation matrix exactly when determinant is 1 // and transposed is inverse if (!Equal(1.0, vnl_det(rotationMatrix), 0.1) || !((rotationMatrix*rotationMatrixTransposed).is_identity(0.1))) { //the rotation matrix is not valid! => invalidate the current element isValidData = false; } //convert the transform into a igtl type ConvertAffineTransformationIntoIGTLMatrix(transform, igtlTransform); //fill the tracking element with life tde->SetMatrix(igtlTransform); tde->SetPosition(position[0], position[1], position[2]); std::stringstream name; name << nd->GetName(); if (name.rdbuf()->in_avail() == 0) { name << "TrackingTool" << index; } tde->SetName(name.str().c_str()); //insert this element into the tracking data message tdMsg->AddTrackingDataElement(tde); //copy the time stamp tdMsg->SetTimeStamp(ConvertToIGTLTimeStamp(nd->GetIGTTimeStamp())); } tdMsg->Pack(); //add the igtl message to the mitk::IGTLMessage output->SetMessage(tdMsg.GetPointer()); output->SetDataValid(isValidData); } void mitk::NavigationDataToIGTLMessageFilter::SetOperationMode(OperationMode mode) { m_OperationMode = mode; this->Modified(); this->CreateOutputsForAllInputs(); } void mitk::NavigationDataToIGTLMessageFilter::ConnectTo( mitk::NavigationDataSource* UpstreamFilter) { for (DataObjectPointerArraySizeType i = 0; i < UpstreamFilter->GetNumberOfOutputs(); i++) { this->SetInput(i, UpstreamFilter->GetOutput(i)); } } <commit_msg>Removed CreateOutputsForAllInputs because it caused a buggy behavior<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 "mitkNavigationDataToIGTLMessageFilter.h" #include "igtlQuaternionTrackingDataMessage.h" #include "igtlTrackingDataMessage.h" #include "igtlTransformMessage.h" #include "igtlPositionMessage.h" #include <mitkInteractionConst.h> #include <itksys/SystemTools.hxx> mitk::NavigationDataToIGTLMessageFilter::NavigationDataToIGTLMessageFilter() { mitk::IGTLMessage::Pointer output = mitk::IGTLMessage::New(); this->SetNumberOfRequiredOutputs(1); this->SetNthOutput(0, output.GetPointer()); this->SetNumberOfRequiredInputs(1); // m_OperationMode = Mode3D; m_CurrentTimeStep = 0; // m_RingBufferSize = 50; //the default ring buffer size // m_NumberForMean = 100; } mitk::NavigationDataToIGTLMessageFilter::~NavigationDataToIGTLMessageFilter() { } void mitk::NavigationDataToIGTLMessageFilter::GenerateData() { switch (m_OperationMode) { case ModeSendQTDataMsg: this->GenerateDataModeSendQTDataMsg(); break; case ModeSendTDataMsg: this->GenerateDataModeSendTDataMsg(); break; case ModeSendQTransMsg: this->GenerateDataModeSendQTransMsg(); break; case ModeSendTransMsg: this->GenerateDataModeSendTransMsg(); break; default: break; } igtl::MessageBase::Pointer curMessage = this->GetOutput()->GetMessage(); if (dynamic_cast<igtl::TrackingDataMessage*>(curMessage.GetPointer()) != nullptr) { igtl::TrackingDataMessage* tdMsg = (igtl::TrackingDataMessage*)(curMessage.GetPointer()); } } void mitk::NavigationDataToIGTLMessageFilter::SetInput(const NavigationData* nd) { // Process object is not const-correct so the const_cast is required here this->ProcessObject::SetNthInput(0, const_cast<NavigationData*>(nd)); this->CreateOutputsForAllInputs(); } void mitk::NavigationDataToIGTLMessageFilter::SetInput(unsigned int idx, const NavigationData* nd) { // Process object is not const-correct so the const_cast is required here this->ProcessObject::SetNthInput(idx, const_cast<NavigationData*>(nd)); this->CreateOutputsForAllInputs(); } const mitk::NavigationData* mitk::NavigationDataToIGTLMessageFilter::GetInput(void) { if (this->GetNumberOfInputs() < 1) return NULL; return static_cast<const NavigationData*>(this->ProcessObject::GetInput(0)); } const mitk::NavigationData* mitk::NavigationDataToIGTLMessageFilter::GetInput(unsigned int idx) { if (this->GetNumberOfInputs() < 1) return NULL; return static_cast<const NavigationData*>(this->ProcessObject::GetInput(idx)); } void mitk::NavigationDataToIGTLMessageFilter::CreateOutputsForAllInputs() { switch (m_OperationMode) { case ModeSendQTDataMsg: // create one message output for all navigation data inputs this->SetNumberOfIndexedOutputs(this->GetNumberOfIndexedInputs()); // set the type for this filter this->SetType("QTDATA"); break; case ModeSendTDataMsg: // create one message output for all navigation data inputs this->SetNumberOfIndexedOutputs(this->GetNumberOfIndexedInputs()); // set the type for this filter this->SetType("TDATA"); break; case ModeSendQTransMsg: // create one message output for all navigation data input together this->SetNumberOfIndexedOutputs(this->GetNumberOfIndexedInputs()); // set the type for this filter this->SetType("POSITION"); break; case ModeSendTransMsg: // create one message output for all navigation data input together this->SetNumberOfIndexedOutputs(this->GetNumberOfIndexedInputs()); // set the type for this filter this->SetType("TRANS"); break; default: break; } for (unsigned int idx = 0; idx < this->GetNumberOfIndexedOutputs(); ++idx) { if (this->GetOutput(idx) == NULL) { DataObjectPointer newOutput = this->MakeOutput(idx); this->SetNthOutput(idx, newOutput); } this->Modified(); } } void ConvertAffineTransformationIntoIGTLMatrix(mitk::AffineTransform3D* trans, igtl::Matrix4x4 igtlTransform) { const mitk::AffineTransform3D::MatrixType& matrix = trans->GetMatrix(); mitk::Vector3D position = trans->GetOffset(); //copy the data into a matrix type that igtl understands for (unsigned int r = 0; r < 3; r++) { for (unsigned int c = 0; c < 3; c++) { igtlTransform[r][c] = matrix(r, c); } igtlTransform[r][3] = position[r]; } for (unsigned int c = 0; c < 3; c++) { igtlTransform[3][c] = 0.0; } igtlTransform[3][3] = 1.0; } void mitk::NavigationDataToIGTLMessageFilter::GenerateDataModeSendQTransMsg() { // for each output message for (unsigned int i = 0; i < this->GetNumberOfIndexedInputs(); ++i) { mitk::IGTLMessage* output = this->GetOutput(i); assert(output); const mitk::NavigationData* input = this->GetInput(i); assert(input); // do not add navigation data to message if input is invalid if (input->IsDataValid() == false) continue; //get the navigation data components mitk::NavigationData::PositionType pos = input->GetPosition(); mitk::NavigationData::OrientationType ori = input->GetOrientation(); //insert this information into the message igtl::PositionMessage::Pointer posMsg = igtl::PositionMessage::New(); posMsg->SetPosition(pos[0], pos[1], pos[2]); posMsg->SetQuaternion(ori[0], ori[1], ori[2], ori[3]); posMsg->SetTimeStamp(ConvertToIGTLTimeStamp(input->GetIGTTimeStamp())); posMsg->SetDeviceName(input->GetName()); posMsg->Pack(); //add the igtl message to the mitk::IGTLMessage output->SetMessage(posMsg.GetPointer()); } } void mitk::NavigationDataToIGTLMessageFilter::GenerateDataModeSendTransMsg() { // for each output message for (unsigned int i = 0; i < this->GetNumberOfIndexedInputs(); ++i) { mitk::IGTLMessage* output = this->GetOutput(i); assert(output); const mitk::NavigationData* input = this->GetInput(i); assert(input); // do not add navigation data to message if input is invalid if (input->IsDataValid() == false) continue; //get the navigation data components mitk::AffineTransform3D::Pointer transform = input->GetAffineTransform3D(); mitk::NavigationData::PositionType position = transform->GetOffset(); //convert the transform into a igtl type igtl::Matrix4x4 igtlTransform; ConvertAffineTransformationIntoIGTLMatrix(transform, igtlTransform); //insert this information into the message igtl::TransformMessage::Pointer transMsg = igtl::TransformMessage::New(); transMsg->SetMatrix(igtlTransform); transMsg->SetPosition(position[0], position[1], position[2]); transMsg->SetTimeStamp(ConvertToIGTLTimeStamp(input->GetIGTTimeStamp())); transMsg->SetDeviceName(input->GetName()); transMsg->Pack(); //add the igtl message to the mitk::IGTLMessage output->SetMessage(transMsg.GetPointer()); } } igtl::TimeStamp::Pointer mitk::NavigationDataToIGTLMessageFilter::ConvertToIGTLTimeStamp(double IGTTimeStamp) { igtl::TimeStamp::Pointer timestamp = igtl::TimeStamp::New(); timestamp->SetTime(IGTTimeStamp / 1000, (int)(IGTTimeStamp) % 1000); return timestamp; } void mitk::NavigationDataToIGTLMessageFilter::GenerateDataModeSendQTDataMsg() { mitk::IGTLMessage* output = this->GetOutput(); assert(output); //create a output igtl message igtl::QuaternionTrackingDataMessage::Pointer qtdMsg = igtl::QuaternionTrackingDataMessage::New(); mitk::NavigationData::PositionType pos; mitk::NavigationData::OrientationType ori; for (unsigned int index = 0; index < this->GetNumberOfIndexedInputs(); index++) { const mitk::NavigationData* nd = GetInput(index); assert(nd); //get the navigation data components pos = nd->GetPosition(); ori = nd->GetOrientation(); //insert the information into the tracking element igtl::QuaternionTrackingDataElement::Pointer tde = igtl::QuaternionTrackingDataElement::New(); tde->SetPosition(pos[0], pos[1], pos[2]); tde->SetQuaternion(ori[0], ori[1], ori[2], ori[3]); tde->SetName(nd->GetName()); //insert this element into the tracking data message qtdMsg->AddQuaternionTrackingDataElement(tde); MITK_INFO << ConvertToIGTLTimeStamp(nd->GetIGTTimeStamp()); } qtdMsg->Pack(); //add the igtl message to the mitk::IGTLMessage output->SetMessage(qtdMsg.GetPointer()); } void mitk::NavigationDataToIGTLMessageFilter::GenerateDataModeSendTDataMsg() { bool isValidData = true; mitk::IGTLMessage* output = this->GetOutput(); assert(output); //create a output igtl message igtl::TrackingDataMessage::Pointer tdMsg = igtl::TrackingDataMessage::New(); mitk::AffineTransform3D::Pointer transform; Vector3D position; igtl::Matrix4x4 igtlTransform; vnl_matrix_fixed<ScalarType, 3, 3> rotationMatrix; vnl_matrix_fixed<ScalarType, 3, 3> rotationMatrixTransposed; for (unsigned int index = 0; index < this->GetNumberOfIndexedInputs(); index++) { const mitk::NavigationData* nd = GetInput(index); assert(nd); //create a new tracking element igtl::TrackingDataElement::Pointer tde = igtl::TrackingDataElement::New(); //get the navigation data components transform = nd->GetAffineTransform3D(); position = transform->GetOffset(); //check the rotation matrix rotationMatrix = transform->GetMatrix().GetVnlMatrix(); rotationMatrixTransposed = rotationMatrix.transpose(); // a quadratic matrix is a rotation matrix exactly when determinant is 1 // and transposed is inverse if (!Equal(1.0, vnl_det(rotationMatrix), 0.1) || !((rotationMatrix*rotationMatrixTransposed).is_identity(0.1))) { //the rotation matrix is not valid! => invalidate the current element isValidData = false; } //convert the transform into a igtl type ConvertAffineTransformationIntoIGTLMatrix(transform, igtlTransform); //fill the tracking element with life tde->SetMatrix(igtlTransform); tde->SetPosition(position[0], position[1], position[2]); std::stringstream name; name << nd->GetName(); if (name.rdbuf()->in_avail() == 0) { name << "TrackingTool" << index; } tde->SetName(name.str().c_str()); //insert this element into the tracking data message tdMsg->AddTrackingDataElement(tde); //copy the time stamp tdMsg->SetTimeStamp(ConvertToIGTLTimeStamp(nd->GetIGTTimeStamp())); } tdMsg->Pack(); //add the igtl message to the mitk::IGTLMessage output->SetMessage(tdMsg.GetPointer()); output->SetDataValid(isValidData); } void mitk::NavigationDataToIGTLMessageFilter::SetOperationMode(OperationMode mode) { m_OperationMode = mode; this->Modified(); } void mitk::NavigationDataToIGTLMessageFilter::ConnectTo( mitk::NavigationDataSource* UpstreamFilter) { for (DataObjectPointerArraySizeType i = 0; i < UpstreamFilter->GetNumberOfOutputs(); i++) { this->SetInput(i, UpstreamFilter->GetOutput(i)); } } <|endoftext|>
<commit_before>#include <QtCore> #include <random> #include "testhof.h" QString runHof(const QString& program, bool* ok, bool verbose = false, int msecsToTimeout = 5000, bool expectTimeout = false ) { QDir bin(QCoreApplication::applicationDirPath()); QProcess hof; hof.setProgram(bin.path() + QDir::separator() + "hof"); QStringList args = QStringList() << "--program" << program; if (verbose) { args.append("--verbose"); hof.setProcessChannelMode(QProcess::ForwardedErrorChannel); } hof.setArguments(args); hof.start(); bool finished = hof.waitForFinished(msecsToTimeout); if (!finished) { hof.kill(); hof.waitForFinished(); } /* special value used to indicate stack depth exceeded */ if (!expectTimeout) { *ok = hof.exitStatus() == QProcess::NormalExit && (hof.exitCode() == EXIT_SUCCESS || hof.exitCode() == 2); } else { *ok = finished != expectTimeout; } if (!*ok) { qDebug() << "exit status:" << hof.exitStatus() << " code:" << hof.exitCode() << " error:" << hof.error(); } return hof.readAll().trimmed(); } #define I "I" #define K "K" #define S "S" #define APPLY(X) "A" X #define PRINT(X) "P" X #define RANDOM(X, Y) "R" X Y #define TRUE "K" #define FALSE "V" #define IF(X, Y, Z) X Y Z #define IFNOT(X, Y, Z) X Z Y #define AND(X, Y) X Y FALSE #define OR(X, Y) X TRUE Y #define ZERO FALSE #define ONE I #define SUCC(X) "AA" S "AA" S "A" K S K X #define OMEGA S I I "AA" S I I // standard beta recursion combinator #define BETA_RECURSE(X) S "A" K X "AA" S I I "AA" S "A" K X "AA" S I I // standard y combinator #define YCOMBINATOR(X) S "A" K "AA" S I I "AA" S "AA" S "A" K S K "A" K "AA" S I I X // S (K (S I I)) (S (S (K S) K) (K (S I I))) // tromp's y combinator #define YCOMBINATOR_1(X) S S K "A" S "A" K "AA" S S "A" S "AA" S S K K X #define WHILE(COND, OPERATION, INITIAL) "" void TestHof::testHof() { bool ok = false; QString out; // print out = runHof(PRINT(I), &ok); QCOMPARE(out, QString(I)); QVERIFY(ok); // if-then-else out = runHof(IF(TRUE, APPLY(PRINT(I)), APPLY(PRINT(K))), &ok); QCOMPARE(out, QString(I)); QVERIFY(ok); out = runHof(IF(FALSE, APPLY(PRINT(I)), APPLY(PRINT(K))), &ok); QCOMPARE(out, QString(K)); QVERIFY(ok); // if-not-then-else out = runHof(IFNOT(TRUE, APPLY(PRINT(I)), APPLY(PRINT(K))), &ok); QCOMPARE(out, QString(K)); QVERIFY(ok); out = runHof(IFNOT(FALSE, APPLY(PRINT(I)), APPLY(PRINT(K))), &ok); QCOMPARE(out, QString(I)); QVERIFY(ok); //if-and-then-else out = runHof(IF(AND(TRUE, TRUE), APPLY(PRINT(I)), APPLY(PRINT(K))), &ok); QCOMPARE(out, QString(I)); QVERIFY(ok); out = runHof(IF(AND(TRUE, FALSE), APPLY(PRINT(I)), APPLY(PRINT(K))), &ok); QCOMPARE(out, QString(K)); QVERIFY(ok); // if-or-then-else out = runHof(IF(OR(TRUE, FALSE), APPLY(PRINT(I)), APPLY(PRINT(K))), &ok); QCOMPARE(out, QString(I)); QVERIFY(ok); out = runHof(IF(OR(FALSE, TRUE), APPLY(PRINT(I)), APPLY(PRINT(K))), &ok); QCOMPARE(out, QString(I)); QVERIFY(ok); out = runHof(IF(OR(FALSE, FALSE), APPLY(PRINT(I)), APPLY(PRINT(K))), &ok); QCOMPARE(out, QString(K)); QVERIFY(ok); // church numerals out = runHof(QString(SUCC(ONE)) + PRINT(I), &ok); QCOMPARE(out, QString("II")); QVERIFY(ok); out = runHof(QString(SUCC(SUCC(ONE))) + PRINT(I), &ok); QCOMPARE(out, QString("III")); QVERIFY(ok); out = runHof(QString(SUCC(SUCC(SUCC(ONE)))) + PRINT(I), &ok); QCOMPARE(out, QString("IIII")); QVERIFY(ok); out = runHof(QString(SUCC(SUCC(SUCC(SUCC(ONE))))) + PRINT(I), &ok); QCOMPARE(out, QString("IIIII")); QVERIFY(ok); // print random out = runHof(RANDOM(APPLY(PRINT(I)), APPLY(PRINT(K))), &ok); QVERIFY2(out == "I" || out == "K", qPrintable(out)); QVERIFY(ok); } void TestHof::testY() { bool ok = false; QString out; int timeout = 500; bool verbose = false; bool expectTimeout = true; out = runHof(YCOMBINATOR("API"), &ok, verbose, timeout, expectTimeout); QVERIFY(out.count('I') > 100); out.replace("I", ""); QCOMPARE(out, QString()); QVERIFY(ok); } void TestHof::testOmega() { bool ok = false; QString out; int timeout = 500; bool verbose = false; bool expectTimeout = true; out = runHof(OMEGA, &ok, verbose, timeout, expectTimeout); QCOMPARE(out, QString()); QVERIFY(ok); } void TestHof::testHofNoise() { std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<int> distLength(0, 100); std::uniform_int_distribution<int> distLetter(0, 6); for (int i = 0; i < 100; ++i) { int length = distLength(gen); QString randomHofProgram; for (int j = 0; j < length; ++j) { int letter = distLetter(gen); QChar ch; switch (letter) { case 0: ch = 'I'; break; case 1: ch = 'K'; break; case 2: ch = 'S'; break; case 3: ch = 'V'; break; case 4: ch = 'A'; break; case 5: ch = 'P'; break; case 6: ch = 'R'; break; default: Q_ASSERT(false); } randomHofProgram.append(ch); } bool ok = false; runHof(randomHofProgram, &ok, false /*verbose*/); QVERIFY2(ok, qPrintable(randomHofProgram)); } } <commit_msg>Add a crude benchmark for y combinator.<commit_after>#include <QtCore> #include <random> #include "testhof.h" QString runHof(const QString& program, bool* ok, bool verbose = false, int msecsToTimeout = 5000, bool expectTimeout = false ) { QDir bin(QCoreApplication::applicationDirPath()); QProcess hof; hof.setProgram(bin.path() + QDir::separator() + "hof"); QStringList args = QStringList() << "--program" << program; if (verbose) { args.append("--verbose"); hof.setProcessChannelMode(QProcess::ForwardedErrorChannel); } hof.setArguments(args); hof.start(); bool finished = hof.waitForFinished(msecsToTimeout); if (!finished) { hof.kill(); hof.waitForFinished(); } /* special value used to indicate stack depth exceeded */ if (!expectTimeout) { *ok = hof.exitStatus() == QProcess::NormalExit && (hof.exitCode() == EXIT_SUCCESS || hof.exitCode() == 2); } else { *ok = finished != expectTimeout; } if (!*ok) { qDebug() << "exit status:" << hof.exitStatus() << " code:" << hof.exitCode() << " error:" << hof.error(); } return hof.readAll().trimmed(); } #define I "I" #define K "K" #define S "S" #define APPLY(X) "A" X #define PRINT(X) "P" X #define RANDOM(X, Y) "R" X Y #define TRUE "K" #define FALSE "V" #define IF(X, Y, Z) X Y Z #define IFNOT(X, Y, Z) X Z Y #define AND(X, Y) X Y FALSE #define OR(X, Y) X TRUE Y #define ZERO FALSE #define ONE I #define SUCC(X) "AA" S "AA" S "A" K S K X #define OMEGA S I I "AA" S I I // standard beta recursion combinator #define BETA_RECURSE(X) S "A" K X "AA" S I I "AA" S "A" K X "AA" S I I // standard y combinator #define YCOMBINATOR(X) S "A" K "AA" S I I "AA" S "AA" S "A" K S K "A" K "AA" S I I X // S (K (S I I)) (S (S (K S) K) (K (S I I))) // tromp's y combinator #define YCOMBINATOR_1(X) S S K "A" S "A" K "AA" S S "A" S "AA" S S K K X #define WHILE(COND, OPERATION, INITIAL) "" void TestHof::testHof() { bool ok = false; QString out; // print out = runHof(PRINT(I), &ok); QCOMPARE(out, QString(I)); QVERIFY(ok); // if-then-else out = runHof(IF(TRUE, APPLY(PRINT(I)), APPLY(PRINT(K))), &ok); QCOMPARE(out, QString(I)); QVERIFY(ok); out = runHof(IF(FALSE, APPLY(PRINT(I)), APPLY(PRINT(K))), &ok); QCOMPARE(out, QString(K)); QVERIFY(ok); // if-not-then-else out = runHof(IFNOT(TRUE, APPLY(PRINT(I)), APPLY(PRINT(K))), &ok); QCOMPARE(out, QString(K)); QVERIFY(ok); out = runHof(IFNOT(FALSE, APPLY(PRINT(I)), APPLY(PRINT(K))), &ok); QCOMPARE(out, QString(I)); QVERIFY(ok); //if-and-then-else out = runHof(IF(AND(TRUE, TRUE), APPLY(PRINT(I)), APPLY(PRINT(K))), &ok); QCOMPARE(out, QString(I)); QVERIFY(ok); out = runHof(IF(AND(TRUE, FALSE), APPLY(PRINT(I)), APPLY(PRINT(K))), &ok); QCOMPARE(out, QString(K)); QVERIFY(ok); // if-or-then-else out = runHof(IF(OR(TRUE, FALSE), APPLY(PRINT(I)), APPLY(PRINT(K))), &ok); QCOMPARE(out, QString(I)); QVERIFY(ok); out = runHof(IF(OR(FALSE, TRUE), APPLY(PRINT(I)), APPLY(PRINT(K))), &ok); QCOMPARE(out, QString(I)); QVERIFY(ok); out = runHof(IF(OR(FALSE, FALSE), APPLY(PRINT(I)), APPLY(PRINT(K))), &ok); QCOMPARE(out, QString(K)); QVERIFY(ok); // church numerals out = runHof(QString(SUCC(ONE)) + PRINT(I), &ok); QCOMPARE(out, QString("II")); QVERIFY(ok); out = runHof(QString(SUCC(SUCC(ONE))) + PRINT(I), &ok); QCOMPARE(out, QString("III")); QVERIFY(ok); out = runHof(QString(SUCC(SUCC(SUCC(ONE)))) + PRINT(I), &ok); QCOMPARE(out, QString("IIII")); QVERIFY(ok); out = runHof(QString(SUCC(SUCC(SUCC(SUCC(ONE))))) + PRINT(I), &ok); QCOMPARE(out, QString("IIIII")); QVERIFY(ok); // print random out = runHof(RANDOM(APPLY(PRINT(I)), APPLY(PRINT(K))), &ok); QVERIFY2(out == "I" || out == "K", qPrintable(out)); QVERIFY(ok); } void TestHof::testY() { bool ok = false; QString out; int timeout = 500; bool verbose = false; bool expectTimeout = true; out = runHof(YCOMBINATOR("API"), &ok, verbose, timeout, expectTimeout); qDebug() << "iterations" << out.count('I'); QVERIFY(out.count('I') > 2000); // crude benchmark in debug mode out.replace("I", ""); QCOMPARE(out, QString()); QVERIFY(ok); } void TestHof::testOmega() { bool ok = false; QString out; int timeout = 500; bool verbose = false; bool expectTimeout = true; out = runHof(OMEGA, &ok, verbose, timeout, expectTimeout); QCOMPARE(out, QString()); QVERIFY(ok); } void TestHof::testHofNoise() { std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<int> distLength(0, 100); std::uniform_int_distribution<int> distLetter(0, 6); for (int i = 0; i < 100; ++i) { int length = distLength(gen); QString randomHofProgram; for (int j = 0; j < length; ++j) { int letter = distLetter(gen); QChar ch; switch (letter) { case 0: ch = 'I'; break; case 1: ch = 'K'; break; case 2: ch = 'S'; break; case 3: ch = 'V'; break; case 4: ch = 'A'; break; case 5: ch = 'P'; break; case 6: ch = 'R'; break; default: Q_ASSERT(false); } randomHofProgram.append(ch); } bool ok = false; runHof(randomHofProgram, &ok, false /*verbose*/); QVERIFY2(ok, qPrintable(randomHofProgram)); } } <|endoftext|>
<commit_before>#pragma once // `krbn::manipulator_timer` can be used safely in a multi-threaded environment. #include "boost_defs.hpp" #include "manipulator_object_id.hpp" #include "thread_utility.hpp" #include "time_utility.hpp" #include "types.hpp" #include <boost/signals2.hpp> #include <deque> #include <mach/mach_time.h> namespace krbn { namespace manipulator { class manipulator_timer final { public: manipulator_timer(bool timer_enabled = true) : timer_enabled_(timer_enabled) { dispatcher_ = std::make_unique<thread_utility::dispatcher>(); } ~manipulator_timer(void) { dispatcher_->enqueue([this] { // Stop `timer_` gracefully without timer_->cancel(). timer_ = nullptr; timer_when_ = boost::none; }); dispatcher_->terminate(); dispatcher_ = nullptr; } void enqueue(manipulator_object_id id, const std::function<void(void)>& function, absolute_time when) { dispatcher_->enqueue([this, id, function, when] { entries_.push_back(std::make_shared<entry>(id, function, when)); std::stable_sort(std::begin(entries_), std::end(entries_), [](auto& a, auto& b) { return a->get_when() < b->get_when(); }); }); } void async_erase(manipulator_object_id id, const std::function<void(void)>& erased) { dispatcher_->enqueue([this, id, erased] { entries_.erase(std::remove_if(std::begin(entries_), std::end(entries_), [&](auto&& e) { return e->get_manipulator_object_id() == id; }), std::end(entries_)); erased(); }); } void async_erase(manipulator_object_id id) { async_erase(id, [] {}); } void async_invoke(absolute_time now) { dispatcher_->enqueue([this, now] { invoke(now); }); } private: class entry final { public: entry(manipulator_object_id id, const std::function<void(void)>& function, absolute_time when) : manipulator_object_id_(id), function_(function), when_(when) { } manipulator_object_id get_manipulator_object_id(void) const { return manipulator_object_id_; } absolute_time get_when(void) const { return when_; } void call_function(void) const { function_(); } private: manipulator_object_id manipulator_object_id_; std::function<void(void)> function_; absolute_time when_; }; void set_timer(absolute_time now) { if (entries_.empty()) { if (timer_) { timer_->cancel(); timer_ = nullptr; } return; } auto e = entries_.front(); if (now < e->get_when()) { if (timer_enabled_) { // Skip if timer_ is active. if (timer_ && timer_when_ && *timer_when_ == e->get_when()) { return; } // Update timer_. if (timer_) { timer_->cancel(); timer_ = nullptr; } timer_when_ = e->get_when(); timer_ = std::make_unique<thread_utility::timer>( time_utility::to_milliseconds(e->get_when() - now), thread_utility::timer::mode::once, [this, e] { dispatcher_->enqueue([this, e] { timer_when_ = boost::none; invoke(e->get_when()); }); }); } } else { if (timer_) { timer_->cancel(); timer_ = nullptr; } invoke(now); } } void invoke(absolute_time now) { while (true) { if (entries_.empty()) { break; } auto e = entries_.front(); if (now < e->get_when()) { break; } dispatcher_->enqueue([e] { e->call_function(); }); entries_.pop_front(); } set_timer(now); } std::unique_ptr<thread_utility::dispatcher> dispatcher_; std::deque<std::shared_ptr<entry>> entries_; bool timer_enabled_; std::unique_ptr<thread_utility::timer> timer_; boost::optional<absolute_time> timer_when_; }; } // namespace manipulator } // namespace krbn <commit_msg>update #include<commit_after>#pragma once // `krbn::manipulator_timer` can be used safely in a multi-threaded environment. #include "manipulator_object_id.hpp" #include "thread_utility.hpp" #include "time_utility.hpp" #include "types.hpp" #include <deque> namespace krbn { namespace manipulator { class manipulator_timer final { public: manipulator_timer(bool timer_enabled = true) : timer_enabled_(timer_enabled) { dispatcher_ = std::make_unique<thread_utility::dispatcher>(); } ~manipulator_timer(void) { dispatcher_->enqueue([this] { // Stop `timer_` gracefully without timer_->cancel(). timer_ = nullptr; timer_when_ = boost::none; }); dispatcher_->terminate(); dispatcher_ = nullptr; } void enqueue(manipulator_object_id id, const std::function<void(void)>& function, absolute_time when) { dispatcher_->enqueue([this, id, function, when] { entries_.push_back(std::make_shared<entry>(id, function, when)); std::stable_sort(std::begin(entries_), std::end(entries_), [](auto& a, auto& b) { return a->get_when() < b->get_when(); }); }); } void async_erase(manipulator_object_id id, const std::function<void(void)>& erased) { dispatcher_->enqueue([this, id, erased] { entries_.erase(std::remove_if(std::begin(entries_), std::end(entries_), [&](auto&& e) { return e->get_manipulator_object_id() == id; }), std::end(entries_)); erased(); }); } void async_erase(manipulator_object_id id) { async_erase(id, [] {}); } void async_invoke(absolute_time now) { dispatcher_->enqueue([this, now] { invoke(now); }); } private: class entry final { public: entry(manipulator_object_id id, const std::function<void(void)>& function, absolute_time when) : manipulator_object_id_(id), function_(function), when_(when) { } manipulator_object_id get_manipulator_object_id(void) const { return manipulator_object_id_; } absolute_time get_when(void) const { return when_; } void call_function(void) const { function_(); } private: manipulator_object_id manipulator_object_id_; std::function<void(void)> function_; absolute_time when_; }; void set_timer(absolute_time now) { if (entries_.empty()) { if (timer_) { timer_->cancel(); timer_ = nullptr; } return; } auto e = entries_.front(); if (now < e->get_when()) { if (timer_enabled_) { // Skip if timer_ is active. if (timer_ && timer_when_ && *timer_when_ == e->get_when()) { return; } // Update timer_. if (timer_) { timer_->cancel(); timer_ = nullptr; } timer_when_ = e->get_when(); timer_ = std::make_unique<thread_utility::timer>( time_utility::to_milliseconds(e->get_when() - now), thread_utility::timer::mode::once, [this, e] { dispatcher_->enqueue([this, e] { timer_when_ = boost::none; invoke(e->get_when()); }); }); } } else { if (timer_) { timer_->cancel(); timer_ = nullptr; } invoke(now); } } void invoke(absolute_time now) { while (true) { if (entries_.empty()) { break; } auto e = entries_.front(); if (now < e->get_when()) { break; } dispatcher_->enqueue([e] { e->call_function(); }); entries_.pop_front(); } set_timer(now); } std::unique_ptr<thread_utility::dispatcher> dispatcher_; std::deque<std::shared_ptr<entry>> entries_; bool timer_enabled_; std::unique_ptr<thread_utility::timer> timer_; boost::optional<absolute_time> timer_when_; }; } // namespace manipulator } // namespace krbn <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: SlsFocusManager.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: kz $ $Date: 2005-01-13 17:28:46 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SD_SLIDESORTER_FOCUS_MANAGER_HXX #define SD_SLIDESORTER_FOCUS_MANAGER_HXX #include <sal/types.h> namespace sd { namespace slidesorter { namespace model { class PageDescriptor; } } } namespace sd { namespace slidesorter { namespace controller { class SlideSorterController; /** This class manages the focus of the slide sorter. There is the focus page which is or is not focused. Initialized to point to the first page it can be set to other pages by using the MoveFocus() method. The focused state of the focus page can be toggled with the ToggleFocus() method. */ class FocusManager { public: /** Create a new focus manager that operates on the pages of the model associated with the given controller. The focus page is set to the first page. Focused state is off. */ FocusManager (SlideSorterController& rController); ~FocusManager (void); enum FocusMoveDirection { FMD_NONE, FMD_LEFT, FMD_RIGHT, FMD_UP, FMD_DOWN }; /** Move the focus from the currently focused page to one that is displayed adjacent to it, either vertically or horizontally. @param eDirection Direction in which to move the focus. Wrap arround is done differently when moving vertically or horizontally. Vertical wrap arround takes place in the same column, i.e. when you are in the top row and move up you come out in the bottom row in the same column. Horizontal wrap arround moves to the next (FMD_RIGHT) or previous (FMD_LEFT) page. Moving to the right from the last page goes to the first page and vice versa. When FMD_NONE is given, the current page index is checked for being valid. If it is not, then it is set to the nearest valid page index. */ void MoveFocus (FocusMoveDirection eDirection); /** Show the focus indicator of the current slide. */ void ShowFocus (void); /** Hide the focus indicator. */ void HideFocus (void); /** Toggle the focused state of the current slide. @return Returns the focused state of the focus page after the call. */ bool ToggleFocus (void); /** Return whether the window managed by the called focus manager has the input focus of the application. */ bool HasFocus (void) const; /** Return the descriptor of the page that currently has the focus. @return When there is no page that currently has the focus then NULL is returned. */ model::PageDescriptor* GetFocusedPageDescriptor (void) const; /** Return the index of the page that currently has the focus as it is accepted by the slide sorter model. @return When there is no page that currently has the focus then -1 is returned. */ sal_Int32 GetFocusedPageIndex (void) const; /** Set the focus to the page with the given index. This does not make the focus visible. @param nPageIndex Index of a page as it is accepted by the slide sorter model. The index is not checked for validity. */ void FocusPage (sal_Int32 nPageIndex); /** Return <TRUE/> when the focus inidcator is currently shown. A prerequisite is that the window managed by this focus manager has the input focus as indicated by a <TRUE/> return value of HasFocus(). It is not necessary that the focus indicator is visible. It may have been scrolled outside the visible area. */ bool IsFocusShowing (void) const; /** Create an instance of this class to temporarily hide the focus indicator. It is restored to its former visibility state when the FocusHider is destroyed. */ class FocusHider { public: FocusHider (FocusManager&); ~FocusHider (void); private: bool mbFocusVisible; FocusManager& mrManager; }; private: /// The controller that is used for accessing the pages. SlideSorterController& mrController; /** Index of the page that may be focused. It is -1 when the model contains no page. */ sal_Int32 mnPageIndex; /** This flag indicates whether the page pointed to by mpFocusDescriptor has the focus. */ bool mbPageIsFocused; /** Reset the focus state of the given descriptor and request a repaint so that the focus indicator is hidden. @param pDescriptor When NULL is given then the call is ignored. */ void HideFocusIndicator (model::PageDescriptor* pDescriptor); /** Set the focus state of the given descriptor, scroll it into the visible area and request a repaint so that the focus indicator is made visible. @param pDescriptor When NULL is given then the call is ignored. */ void ShowFocusIndicator (model::PageDescriptor* pDescriptor); }; } } } // end of namespace ::sd::slidesorter::controller #endif <commit_msg>INTEGRATION: CWS impress29 (1.2.186); FILE MERGED 2005/01/13 10:18:45 af 1.2.186.1: #i32465# Added new SetFocusedPage() method in two variants.<commit_after>/************************************************************************* * * $RCSfile: SlsFocusManager.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2005-01-25 15:34:40 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SD_SLIDESORTER_FOCUS_MANAGER_HXX #define SD_SLIDESORTER_FOCUS_MANAGER_HXX #include <sal/types.h> namespace sd { namespace slidesorter { namespace model { class PageDescriptor; } } } namespace sd { namespace slidesorter { namespace controller { class SlideSorterController; /** This class manages the focus of the slide sorter. There is the focus page which is or is not focused. Initialized to point to the first page it can be set to other pages by using the MoveFocus() method. The focused state of the focus page can be toggled with the ToggleFocus() method. */ class FocusManager { public: /** Create a new focus manager that operates on the pages of the model associated with the given controller. The focus page is set to the first page. Focused state is off. */ FocusManager (SlideSorterController& rController); ~FocusManager (void); enum FocusMoveDirection { FMD_NONE, FMD_LEFT, FMD_RIGHT, FMD_UP, FMD_DOWN }; /** Move the focus from the currently focused page to one that is displayed adjacent to it, either vertically or horizontally. @param eDirection Direction in which to move the focus. Wrap arround is done differently when moving vertically or horizontally. Vertical wrap arround takes place in the same column, i.e. when you are in the top row and move up you come out in the bottom row in the same column. Horizontal wrap arround moves to the next (FMD_RIGHT) or previous (FMD_LEFT) page. Moving to the right from the last page goes to the first page and vice versa. When FMD_NONE is given, the current page index is checked for being valid. If it is not, then it is set to the nearest valid page index. */ void MoveFocus (FocusMoveDirection eDirection); /** Show the focus indicator of the current slide. */ void ShowFocus (void); /** Hide the focus indicator. */ void HideFocus (void); /** Toggle the focused state of the current slide. @return Returns the focused state of the focus page after the call. */ bool ToggleFocus (void); /** Return whether the window managed by the called focus manager has the input focus of the application. */ bool HasFocus (void) const; /** Return the descriptor of the page that currently has the focus. @return When there is no page that currently has the focus then NULL is returned. */ model::PageDescriptor* GetFocusedPageDescriptor (void) const; /** Return the index of the page that currently has the focus as it is accepted by the slide sorter model. @return When there is no page that currently has the focus then -1 is returned. */ sal_Int32 GetFocusedPageIndex (void) const; /** DEPRECATED. (Use equivalent SetFocusedPage(sal_Int32) instead. Set the focus to the page with the given index. This does not make the focus visible. @param nPageIndex Index of a page as it is accepted by the slide sorter model. The index is not checked for validity. */ void FocusPage (sal_Int32 nPageIndex); /** Set the focused page to the one described by the given page descriptor. The visibility of the focus indicator is not modified. @param rDescriptor One of the page descriptors that are currently managed by the SlideSorterModel. */ void SetFocusedPage (const model::PageDescriptor& rDescriptor); /** Set the focused page to the one described by the given page index. The visibility of the focus indicator is not modified. @param nPageIndex A valid page index that is understood by the SlideSorterModel. */ void SetFocusedPage (sal_Int32 nPageIndex); /** Return <TRUE/> when the focus inidcator is currently shown. A prerequisite is that the window managed by this focus manager has the input focus as indicated by a <TRUE/> return value of HasFocus(). It is not necessary that the focus indicator is visible. It may have been scrolled outside the visible area. */ bool IsFocusShowing (void) const; /** Create an instance of this class to temporarily hide the focus indicator. It is restored to its former visibility state when the FocusHider is destroyed. */ class FocusHider { public: FocusHider (FocusManager&); ~FocusHider (void); private: bool mbFocusVisible; FocusManager& mrManager; }; private: /// The controller that is used for accessing the pages. SlideSorterController& mrController; /** Index of the page that may be focused. It is -1 when the model contains no page. */ sal_Int32 mnPageIndex; /** This flag indicates whether the page pointed to by mpFocusDescriptor has the focus. */ bool mbPageIsFocused; /** Reset the focus state of the given descriptor and request a repaint so that the focus indicator is hidden. @param pDescriptor When NULL is given then the call is ignored. */ void HideFocusIndicator (model::PageDescriptor* pDescriptor); /** Set the focus state of the given descriptor, scroll it into the visible area and request a repaint so that the focus indicator is made visible. @param pDescriptor When NULL is given then the call is ignored. */ void ShowFocusIndicator (model::PageDescriptor* pDescriptor); }; } } } // end of namespace ::sd::slidesorter::controller #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: RecentlyUsedMasterPages.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: kz $ $Date: 2006-04-26 20:53: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 * ************************************************************************/ #ifndef SD_TOOLPANEL_CONTROLS_RECENTLY_USED_MASTER_PAGES_HXX #define SD_TOOLPANEL_CONTROLS_RECENTLY_USED_MASTER_PAGES_HXX #include "tools/SdGlobalResourceContainer.hxx" #include <osl/mutex.hxx> #include <tools/link.hxx> #include <vcl/image.hxx> #include <vector> #include <tools/string.hxx> #include "DrawDocShell.hxx" #include "MasterPageContainer.hxx" #ifndef _COM_SUN_STAR_UNO_XINTERFACE_HPP_ #include <com/sun/star/uno/XInterface.hpp> #endif class SdPage; namespace sd { class MasterPageObserverEvent; } namespace sd { namespace toolpanel { namespace controls { /** This singleton holds a list of the most recently used master pages. */ class RecentlyUsedMasterPages : public SdGlobalResource { public: /** Return the single instance of this class. */ static RecentlyUsedMasterPages& Instance (void); void AddEventListener (const Link& rEventListener); void RemoveEventListener (const Link& rEventListener); int GetMasterPageCount (void) const; MasterPageContainer::Token GetTokenForIndex (sal_uInt32 nIndex) const; private: /** The single instance of this class. It is created on demand when Instance() is called for the first time. */ static RecentlyUsedMasterPages* mpInstance; ::std::vector<Link> maListeners; class MasterPageList; ::std::auto_ptr<MasterPageList> mpMasterPages; unsigned long int mnMaxListSize; ::boost::shared_ptr<MasterPageContainer> mpContainer; RecentlyUsedMasterPages (void); virtual ~RecentlyUsedMasterPages (void); /** Call this method after a new object has been created. */ void LateInit (void); /// The copy constructor is not implemented. Do not use! RecentlyUsedMasterPages (const RecentlyUsedMasterPages&); /// The assignment operator is not implemented. Do not use! RecentlyUsedMasterPages& operator= (const RecentlyUsedMasterPages&); void SendEvent (void); DECL_LINK(MasterPageChangeListener, MasterPageObserverEvent*); DECL_LINK(MasterPageContainerChangeListener, MasterPageContainerChangeEvent*); /** Add a descriptor for the specified master page to the end of the list of most recently used master pages. When the page is already a member of that list the associated descriptor is moved to the end of the list to make it the most recently used entry. @param bMakePersistent When <TRUE/> is given then the new list of recently used master pages is written back into the configuration to make it persistent. Giving <FALSE/> to ommit this is used while loading the persistent list from the configuration. */ void AddMasterPage ( MasterPageContainer::Token aToken, bool bMakePersistent = true); /** Load the list of recently used master pages from the registry where it was saved to make it persistent. */ void LoadPersistentValues (void); /** Save the list of recently used master pages to the registry to make it presistent. */ void SavePersistentValues (void); ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface> OpenConfiguration ( const ::rtl::OUString& rsRootName, bool bReadOnly); ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface> GetConfigurationNode ( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface>& xRoot, const ::rtl::OUString& sPathToNode); void ResolveList (void); }; } } } // end of namespace ::sd::toolpanel::controls #endif <commit_msg>INTEGRATION: CWS components1 (1.7.52); FILE MERGED 2006/08/22 12:26:19 af 1.7.52.1: #i68075# Moved configuration handling to new ConfigurationAccess class.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: RecentlyUsedMasterPages.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2007-04-03 16:23:04 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SD_TOOLPANEL_CONTROLS_RECENTLY_USED_MASTER_PAGES_HXX #define SD_TOOLPANEL_CONTROLS_RECENTLY_USED_MASTER_PAGES_HXX #include "tools/SdGlobalResourceContainer.hxx" #include <osl/mutex.hxx> #include <tools/link.hxx> #include <vcl/image.hxx> #include <vector> #include <tools/string.hxx> #include "DrawDocShell.hxx" #include "MasterPageContainer.hxx" #ifndef _COM_SUN_STAR_UNO_XINTERFACE_HPP_ #include <com/sun/star/uno/XInterface.hpp> #endif class SdPage; namespace sd { class MasterPageObserverEvent; } namespace sd { namespace toolpanel { namespace controls { /** This singleton holds a list of the most recently used master pages. */ class RecentlyUsedMasterPages : public SdGlobalResource { public: /** Return the single instance of this class. */ static RecentlyUsedMasterPages& Instance (void); void AddEventListener (const Link& rEventListener); void RemoveEventListener (const Link& rEventListener); int GetMasterPageCount (void) const; MasterPageContainer::Token GetTokenForIndex (sal_uInt32 nIndex) const; private: /** The single instance of this class. It is created on demand when Instance() is called for the first time. */ static RecentlyUsedMasterPages* mpInstance; ::std::vector<Link> maListeners; class MasterPageList; ::std::auto_ptr<MasterPageList> mpMasterPages; unsigned long int mnMaxListSize; ::boost::shared_ptr<MasterPageContainer> mpContainer; RecentlyUsedMasterPages (void); virtual ~RecentlyUsedMasterPages (void); /** Call this method after a new object has been created. */ void LateInit (void); /// The copy constructor is not implemented. Do not use! RecentlyUsedMasterPages (const RecentlyUsedMasterPages&); /// The assignment operator is not implemented. Do not use! RecentlyUsedMasterPages& operator= (const RecentlyUsedMasterPages&); void SendEvent (void); DECL_LINK(MasterPageChangeListener, MasterPageObserverEvent*); DECL_LINK(MasterPageContainerChangeListener, MasterPageContainerChangeEvent*); /** Add a descriptor for the specified master page to the end of the list of most recently used master pages. When the page is already a member of that list the associated descriptor is moved to the end of the list to make it the most recently used entry. @param bMakePersistent When <TRUE/> is given then the new list of recently used master pages is written back into the configuration to make it persistent. Giving <FALSE/> to ommit this is used while loading the persistent list from the configuration. */ void AddMasterPage ( MasterPageContainer::Token aToken, bool bMakePersistent = true); /** Load the list of recently used master pages from the registry where it was saved to make it persistent. */ void LoadPersistentValues (void); /** Save the list of recently used master pages to the registry to make it presistent. */ void SavePersistentValues (void); void ResolveList (void); }; } } } // end of namespace ::sd::toolpanel::controls #endif <|endoftext|>
<commit_before>// Scintilla source code edit control /** @file LexLua.cxx ** Lexer for Lua language. ** ** Written by Paul Winwood. ** Folder by Alexey Yutkin. **/ #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <fcntl.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" inline bool isLuaOperator(char ch) { if (isalnum(ch)) return false; // '.' left out as it is used to make up numbers if (ch == '*' || ch == '/' || ch == '-' || ch == '+' || ch == '(' || ch == ')' || ch == '=' || ch == '{' || ch == '}' || ch == '~' || ch == '[' || ch == ']' || ch == ';' || ch == '<' || ch == '>' || ch == ',' || ch == '.' || ch == '^' || ch == '%' || ch == ':') return true; return false; } static void classifyWordLua(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler) { char s[100]; bool wordIsNumber = isdigit(styler[start]) || (styler[start] == '.'); for (unsigned int i = 0; i < end - start + 1 && i < 30; i++) { s[i] = styler[start + i]; s[i + 1] = '\0'; } char chAttr = SCE_LUA_IDENTIFIER; if (wordIsNumber) chAttr = SCE_LUA_NUMBER; else { if (keywords.InList(s)) { chAttr = SCE_LUA_WORD; } } styler.ColourTo(end, chAttr); } static void ColouriseLuaDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { WordList &keywords = *keywordlists[0]; styler.StartAt(startPos); styler.GetLine(startPos); int state = initStyle; char chPrev = ' '; char chNext = styler[startPos]; unsigned int lengthDoc = startPos + length; bool firstChar = true; int literalString = 0; styler.StartSegment(startPos); for (unsigned int i = startPos; i <= lengthDoc; i++) { char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); if (styler.IsLeadByte(ch)) { chNext = styler.SafeGetCharAt(i + 2); chPrev = ' '; i += 1; continue; } if (state == SCE_LUA_STRINGEOL) { if (ch != '\r' && ch != '\n') { styler.ColourTo(i - 1, state); state = SCE_LUA_DEFAULT; } } if (state == SCE_LUA_LITERALSTRING && ch == '[' && chNext == '[') { literalString++; } else if (state == SCE_LUA_DEFAULT) { if (ch == '-' && chNext == '-') { styler.ColourTo(i - 1, state); state = SCE_LUA_COMMENTLINE; } else if (ch == '[' && chNext == '[') { state = SCE_LUA_LITERALSTRING; literalString = 1; } else if (ch == '\"') { styler.ColourTo(i - 1, state); state = SCE_LUA_STRING; } else if (ch == '\'') { styler.ColourTo(i - 1, state); state = SCE_LUA_CHARACTER; } else if (ch == '$' && firstChar) { styler.ColourTo(i - 1, state); state = SCE_LUA_PREPROCESSOR; } else if (ch == '#' && firstChar) // Should be only on the first line of the file! Cannot be tested here { styler.ColourTo(i - 1, state); state = SCE_LUA_COMMENTLINE; } else if (isLuaOperator(ch)) { styler.ColourTo(i - 1, state); styler.ColourTo(i, SCE_LUA_OPERATOR); } else if (iswordstart(ch)) { styler.ColourTo(i - 1, state); state = SCE_LUA_WORD; } } else if (state == SCE_LUA_WORD) { if (!iswordchar(ch)) { classifyWordLua(styler.GetStartSegment(), i - 1, keywords, styler); state = SCE_LUA_DEFAULT; if (ch == '[' && chNext == '[') { literalString = 1; state = SCE_LUA_LITERALSTRING; } else if (ch == '-' && chNext == '-') { state = SCE_LUA_COMMENTLINE; } else if (ch == '\"') { state = SCE_LUA_STRING; } else if (ch == '\'') { state = SCE_LUA_CHARACTER; } else if (ch == '$' && firstChar) { state = SCE_LUA_PREPROCESSOR; } else if (isLuaOperator(ch)) { styler.ColourTo(i, SCE_LUA_OPERATOR); } } else if (ch == '.' && chNext == '.') { classifyWordLua(styler.GetStartSegment(), i - 1, keywords, styler); styler.ColourTo(i, SCE_LUA_OPERATOR); state = SCE_LUA_DEFAULT; } } else { if (state == SCE_LUA_LITERALSTRING) { if (ch == ']' && (chPrev == ']') && (--literalString == 0)) { styler.ColourTo(i, state); state = SCE_LUA_DEFAULT; } } else if (state == SCE_LUA_PREPROCESSOR) { if ((ch == '\r' || ch == '\n') && (chPrev != '\\')) { styler.ColourTo(i - 1, state); state = SCE_LUA_DEFAULT; } } else if (state == SCE_LUA_COMMENTLINE) { if (ch == '\r' || ch == '\n') { styler.ColourTo(i - 1, state); state = SCE_LUA_DEFAULT; } } else if (state == SCE_LUA_STRING) { if ((ch == '\r' || ch == '\n') && (chPrev != '\\')) { styler.ColourTo(i - 1, state); state = SCE_LUA_STRINGEOL; } else if (ch == '\\') { if (chNext == '\"' || chNext == '\\') { i++; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); } } else if (ch == '\"') { styler.ColourTo(i, state); state = SCE_LUA_DEFAULT; i++; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); } } else if (state == SCE_LUA_CHARACTER) { if ((ch == '\r' || ch == '\n') && (chPrev != '\\')) { styler.ColourTo(i - 1, state); state = SCE_LUA_STRINGEOL; } else if (ch == '\\') { if (chNext == '\'' || chNext == '\\') { i++; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); } } else if (ch == '\'') { styler.ColourTo(i, state); state = SCE_LUA_DEFAULT; i++; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); } } if (state == SCE_LUA_DEFAULT) { if (ch == '-' && chNext == '-') { state = SCE_LUA_COMMENTLINE; } else if (ch == '\"') { state = SCE_LUA_STRING; } else if (ch == '\'') { state = SCE_LUA_CHARACTER; } else if (ch == '$' && firstChar) { state = SCE_LUA_PREPROCESSOR; } else if (iswordstart(ch)) { state = SCE_LUA_WORD; } else if (isLuaOperator(ch)) { styler.ColourTo(i, SCE_LUA_OPERATOR); } } } chPrev = ch; firstChar = (ch == '\r' || ch == '\n'); } styler.ColourTo(lengthDoc - 1, state); } static void FoldLuaDoc(unsigned int startPos, int length, int initStyle, WordList *[], Accessor &styler) { unsigned int lengthDoc = startPos + length; int visibleChars = 0; int lineCurrent = styler.GetLine(startPos); int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK; int levelCurrent = levelPrev; char chNext = styler[startPos]; int styleNext = styler.StyleAt(startPos); int style = initStyle; char s[10]; for (unsigned int i = startPos; i < lengthDoc; i++) { char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); style = styleNext; styleNext = styler.StyleAt(i + 1); bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n'); if (style == SCE_LUA_WORD) if ( ch == 'e' || ch == 't' || ch == 'd' || ch == 'f') { for (unsigned int j = 0; j < 8; j++) { if (!iswordchar(styler[i + j])) break; s[j] = styler[i + j]; s[j + 1] = '\0'; } if ((strcmp(s, "then") == 0) || (strcmp(s, "do") == 0) || (strcmp(s, "function") == 0)) levelCurrent++; if (strcmp(s, "end") == 0) levelCurrent--; } if (atEOL) { int lev = levelPrev; if (visibleChars == 0) lev |= SC_FOLDLEVELWHITEFLAG; if ((levelCurrent > levelPrev) && (visibleChars > 0)) lev |= SC_FOLDLEVELHEADERFLAG; if (lev != styler.LevelAt(lineCurrent)) { styler.SetLevel(lineCurrent, lev); } lineCurrent++; levelPrev = levelCurrent; visibleChars = 0; } if (!isspacechar(ch)) visibleChars++; } // Fill in the real level of the next line, keeping the current flags as they will be filled in later int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK; styler.SetLevel(lineCurrent, levelPrev | flagsNext); } LexerModule lmLua(SCLEX_LUA, ColouriseLuaDoc, "lua", FoldLuaDoc); <commit_msg>Simplified because of warnings.<commit_after>// Scintilla source code edit control /** @file LexLua.cxx ** Lexer for Lua language. ** ** Written by Paul Winwood. ** Folder by Alexey Yutkin. **/ #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdarg.h> #include <stdio.h> #include <fcntl.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" inline bool isLuaOperator(char ch) { if (isalnum(ch)) return false; // '.' left out as it is used to make up numbers if (ch == '*' || ch == '/' || ch == '-' || ch == '+' || ch == '(' || ch == ')' || ch == '=' || ch == '{' || ch == '}' || ch == '~' || ch == '[' || ch == ']' || ch == ';' || ch == '<' || ch == '>' || ch == ',' || ch == '.' || ch == '^' || ch == '%' || ch == ':') return true; return false; } static void classifyWordLua(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler) { char s[100]; bool wordIsNumber = isdigit(styler[start]) || (styler[start] == '.'); for (unsigned int i = 0; i < end - start + 1 && i < 30; i++) { s[i] = styler[start + i]; s[i + 1] = '\0'; } char chAttr = SCE_LUA_IDENTIFIER; if (wordIsNumber) chAttr = SCE_LUA_NUMBER; else { if (keywords.InList(s)) { chAttr = SCE_LUA_WORD; } } styler.ColourTo(end, chAttr); } static void ColouriseLuaDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { WordList &keywords = *keywordlists[0]; styler.StartAt(startPos); styler.GetLine(startPos); int state = initStyle; char chPrev = ' '; char chNext = styler[startPos]; unsigned int lengthDoc = startPos + length; bool firstChar = true; int literalString = 0; styler.StartSegment(startPos); for (unsigned int i = startPos; i <= lengthDoc; i++) { char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); if (styler.IsLeadByte(ch)) { chNext = styler.SafeGetCharAt(i + 2); chPrev = ' '; i += 1; continue; } if (state == SCE_LUA_STRINGEOL) { if (ch != '\r' && ch != '\n') { styler.ColourTo(i - 1, state); state = SCE_LUA_DEFAULT; } } if (state == SCE_LUA_LITERALSTRING && ch == '[' && chNext == '[') { literalString++; } else if (state == SCE_LUA_DEFAULT) { if (ch == '-' && chNext == '-') { styler.ColourTo(i - 1, state); state = SCE_LUA_COMMENTLINE; } else if (ch == '[' && chNext == '[') { state = SCE_LUA_LITERALSTRING; literalString = 1; } else if (ch == '\"') { styler.ColourTo(i - 1, state); state = SCE_LUA_STRING; } else if (ch == '\'') { styler.ColourTo(i - 1, state); state = SCE_LUA_CHARACTER; } else if (ch == '$' && firstChar) { styler.ColourTo(i - 1, state); state = SCE_LUA_PREPROCESSOR; } else if (ch == '#' && firstChar) // Should be only on the first line of the file! Cannot be tested here { styler.ColourTo(i - 1, state); state = SCE_LUA_COMMENTLINE; } else if (isLuaOperator(ch)) { styler.ColourTo(i - 1, state); styler.ColourTo(i, SCE_LUA_OPERATOR); } else if (iswordstart(ch)) { styler.ColourTo(i - 1, state); state = SCE_LUA_WORD; } } else if (state == SCE_LUA_WORD) { if (!iswordchar(ch)) { classifyWordLua(styler.GetStartSegment(), i - 1, keywords, styler); state = SCE_LUA_DEFAULT; if (ch == '[' && chNext == '[') { literalString = 1; state = SCE_LUA_LITERALSTRING; } else if (ch == '-' && chNext == '-') { state = SCE_LUA_COMMENTLINE; } else if (ch == '\"') { state = SCE_LUA_STRING; } else if (ch == '\'') { state = SCE_LUA_CHARACTER; } else if (ch == '$' && firstChar) { state = SCE_LUA_PREPROCESSOR; } else if (isLuaOperator(ch)) { styler.ColourTo(i, SCE_LUA_OPERATOR); } } else if (ch == '.' && chNext == '.') { classifyWordLua(styler.GetStartSegment(), i - 1, keywords, styler); styler.ColourTo(i, SCE_LUA_OPERATOR); state = SCE_LUA_DEFAULT; } } else { if (state == SCE_LUA_LITERALSTRING) { if (ch == ']' && (chPrev == ']') && (--literalString == 0)) { styler.ColourTo(i, state); state = SCE_LUA_DEFAULT; } } else if (state == SCE_LUA_PREPROCESSOR) { if ((ch == '\r' || ch == '\n') && (chPrev != '\\')) { styler.ColourTo(i - 1, state); state = SCE_LUA_DEFAULT; } } else if (state == SCE_LUA_COMMENTLINE) { if (ch == '\r' || ch == '\n') { styler.ColourTo(i - 1, state); state = SCE_LUA_DEFAULT; } } else if (state == SCE_LUA_STRING) { if ((ch == '\r' || ch == '\n') && (chPrev != '\\')) { styler.ColourTo(i - 1, state); state = SCE_LUA_STRINGEOL; } else if (ch == '\\') { if (chNext == '\"' || chNext == '\\') { i++; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); } } else if (ch == '\"') { styler.ColourTo(i, state); state = SCE_LUA_DEFAULT; i++; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); } } else if (state == SCE_LUA_CHARACTER) { if ((ch == '\r' || ch == '\n') && (chPrev != '\\')) { styler.ColourTo(i - 1, state); state = SCE_LUA_STRINGEOL; } else if (ch == '\\') { if (chNext == '\'' || chNext == '\\') { i++; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); } } else if (ch == '\'') { styler.ColourTo(i, state); state = SCE_LUA_DEFAULT; i++; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); } } if (state == SCE_LUA_DEFAULT) { if (ch == '-' && chNext == '-') { state = SCE_LUA_COMMENTLINE; } else if (ch == '\"') { state = SCE_LUA_STRING; } else if (ch == '\'') { state = SCE_LUA_CHARACTER; } else if (ch == '$' && firstChar) { state = SCE_LUA_PREPROCESSOR; } else if (iswordstart(ch)) { state = SCE_LUA_WORD; } else if (isLuaOperator(ch)) { styler.ColourTo(i, SCE_LUA_OPERATOR); } } } chPrev = ch; firstChar = (ch == '\r' || ch == '\n'); } styler.ColourTo(lengthDoc - 1, state); } static void FoldLuaDoc(unsigned int startPos, int length, int /* initStyle */, WordList *[], Accessor &styler) { unsigned int lengthDoc = startPos + length; int visibleChars = 0; int lineCurrent = styler.GetLine(startPos); int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK; int levelCurrent = levelPrev; char chNext = styler[startPos]; int styleNext = styler.StyleAt(startPos); char s[10]; for (unsigned int i = startPos; i < lengthDoc; i++) { char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); int style = styleNext; styleNext = styler.StyleAt(i + 1); bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n'); if (style == SCE_LUA_WORD) if ( ch == 'e' || ch == 't' || ch == 'd' || ch == 'f') { for (unsigned int j = 0; j < 8; j++) { if (!iswordchar(styler[i + j])) break; s[j] = styler[i + j]; s[j + 1] = '\0'; } if ((strcmp(s, "then") == 0) || (strcmp(s, "do") == 0) || (strcmp(s, "function") == 0)) levelCurrent++; if (strcmp(s, "end") == 0) levelCurrent--; } if (atEOL) { int lev = levelPrev; if (visibleChars == 0) lev |= SC_FOLDLEVELWHITEFLAG; if ((levelCurrent > levelPrev) && (visibleChars > 0)) lev |= SC_FOLDLEVELHEADERFLAG; if (lev != styler.LevelAt(lineCurrent)) { styler.SetLevel(lineCurrent, lev); } lineCurrent++; levelPrev = levelCurrent; visibleChars = 0; } if (!isspacechar(ch)) visibleChars++; } // Fill in the real level of the next line, keeping the current flags as they will be filled in later int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK; styler.SetLevel(lineCurrent, levelPrev | flagsNext); } LexerModule lmLua(SCLEX_LUA, ColouriseLuaDoc, "lua", FoldLuaDoc); <|endoftext|>
<commit_before>#include "RenderingSystem.h" #include "../Components/TransformComponent.h" #include "../Components/CameraComponent.h" #include "../Components/ModelComponent.h" #include "../../Rendering/RenderSurface.h" #include "../../Rendering/Camera.h" #include "../../Rendering/Mesh.h" #include "../../Rendering/Model.h" #include "../../Rendering/VertexBuffer.h" #include "../../Rendering/IndexBuffer.h" #include "../../Rendering/Program.h" #include "../../Rendering/Texture.h" #include "../../Rendering/Material.h" void updateLodData(LodData& lodData, std::size_t totalLods, float minDist, float maxDist, float transTime, float distanceToCamera, float dt) { if (totalLods == 1) return; totalLods -= 1; if (totalLods < 0) totalLods = 0; const float factor = 1.0f - math::clamp((maxDist - distanceToCamera) / (maxDist - minDist), 0.0f, 1.0f); const int lod = (int)math::lerp(0.0f, static_cast<float>(totalLods), factor); if (lodData.targetLodIndex != lod && lodData.targetLodIndex == lodData.currentLodIndex) lodData.targetLodIndex = lod; if (lodData.currentLodIndex != lodData.targetLodIndex) lodData.currentTime += dt; if (lodData.currentTime >= transTime) { lodData.currentLodIndex = lodData.targetLodIndex; lodData.currentTime = 0.0f; } } void RenderingSystem::frameRender(EntityManager &entities, EventManager &events, TimeDelta dt) { entities.each<CameraComponent>([this, &entities, dt]( Entity ce, CameraComponent& cameraComponent ) { const auto gBufferSurface = cameraComponent.getGBufferSurface(); const auto camera = cameraComponent.getCamera(); const auto viewId = gBufferSurface->getId(); auto& cameraLods = mLodDataMap[ce]; { RenderSurfaceScope surfaceScope(gBufferSurface); gBufferSurface->clear(); gfx::setViewTransform(viewId, &camera->getView(), &camera->getProj()); entities.each<TransformComponent, ModelComponent>([this, &cameraLods, camera, dt, viewId]( Entity e, TransformComponent& transformComponent, ModelComponent& modelComponent ) { const auto& model = modelComponent.getModel(); if (!model.isValid()) return; const auto& worldTransform = transformComponent.getTransform(); const auto clip_planes = math::vec2(camera->getNearClip(), camera->getFarClip()); auto& lodData = cameraLods[e]; const auto transitionTime = model.getTransitionTime(); const auto minDistance = model.getMinDistance(); const auto maxDistance = model.getMaxDistance(); const auto lodCount = model.getLods().size(); const auto currentTime = lodData.currentTime; const auto currentLodIndex = lodData.currentLodIndex; const auto targetLodIndex = lodData.targetLodIndex; auto material = model.getMaterialForGroup({}); if (!material) return; const auto hMeshCurr = model.getLod(currentLodIndex); if (!hMeshCurr) return; const auto& frustum = camera->getFrustum(); const auto& bounds = hMeshCurr->aabb; float t = 0; const auto rayOrigin = camera->getPosition(); const auto invWorld = math::inverse(worldTransform); const auto objectRayOrigin = invWorld.transformCoord(rayOrigin); const auto objectRayDirection = math::normalize(bounds.getCenter() - objectRayOrigin); bounds.intersect(objectRayOrigin, objectRayDirection, t); // Compute final object space intersection point. auto intersectionPoint = objectRayOrigin + (objectRayDirection * t); // transform intersection point back into world space to compute // the final intersection distance. intersectionPoint = worldTransform.transformCoord(intersectionPoint); const float distance = math::length(intersectionPoint - rayOrigin); updateLodData( lodData, lodCount, minDistance, maxDistance, transitionTime, distance, dt); // Test the bounding box of the mesh if (!math::frustum::testOBB(frustum, bounds, worldTransform)) return; const auto params = math::vec3{ 0.0f, -1.0f, (transitionTime - currentTime) / transitionTime }; const auto paramsInv = math::vec3{ 1.0f, 1.0f, currentTime / transitionTime }; material->setUniform("u_camera_wpos", &camera->getPosition()); material->setUniform("u_camera_clip_planes", &clip_planes); material->setUniform("u_lod_params", &params); material->submit(); // Set render states. const auto states = material->getRenderStates(); auto program = material->getProgram(); hMeshCurr->submit(viewId, program->handle, worldTransform, states); if (currentTime != 0.0f) { material->setUniform("u_lod_params", &paramsInv); material->submit(); const auto hMeshTarget = model.getLod(targetLodIndex); if (!hMeshTarget) return; hMeshTarget->submit(viewId, program->handle, worldTransform, states); } }); } { auto surface = cameraComponent.getRenderSurface(); RenderSurfaceScope scope(surface); //this will change soon } }); } void RenderingSystem::receive(const EntityDestroyedEvent &event) { mLodDataMap.erase(event.entity); for (auto& pair : mLodDataMap) { pair.second.erase(event.entity); } } void RenderingSystem::configure(EventManager &events) { events.subscribe<EntityDestroyedEvent>(*this); } <commit_msg>cleanup<commit_after>#include "RenderingSystem.h" #include "../Components/TransformComponent.h" #include "../Components/CameraComponent.h" #include "../Components/ModelComponent.h" #include "../../Rendering/RenderSurface.h" #include "../../Rendering/Camera.h" #include "../../Rendering/Mesh.h" #include "../../Rendering/Model.h" #include "../../Rendering/VertexBuffer.h" #include "../../Rendering/IndexBuffer.h" #include "../../Rendering/Program.h" #include "../../Rendering/Texture.h" #include "../../Rendering/Material.h" void updateLodData(LodData& lodData, std::size_t totalLods, float minDist, float maxDist, float transTime, float distanceToCamera, float dt) { if (totalLods == 1) return; totalLods -= 1; if (totalLods < 0) totalLods = 0; const float factor = 1.0f - math::clamp((maxDist - distanceToCamera) / (maxDist - minDist), 0.0f, 1.0f); const int lod = (int)math::lerp(0.0f, static_cast<float>(totalLods), factor); if (lodData.targetLodIndex != lod && lodData.targetLodIndex == lodData.currentLodIndex) lodData.targetLodIndex = lod; if (lodData.currentLodIndex != lodData.targetLodIndex) lodData.currentTime += dt; if (lodData.currentTime >= transTime) { lodData.currentLodIndex = lodData.targetLodIndex; lodData.currentTime = 0.0f; } } void RenderingSystem::frameRender(EntityManager &entities, EventManager &events, TimeDelta dt) { entities.each<CameraComponent>([this, &entities, dt]( Entity ce, CameraComponent& cameraComponent ) { const auto gBufferSurface = cameraComponent.getGBufferSurface(); const auto camera = cameraComponent.getCamera(); const auto viewId = gBufferSurface->getId(); auto& cameraLods = mLodDataMap[ce]; { RenderSurfaceScope surfaceScope(gBufferSurface); gBufferSurface->clear(); gfx::setViewTransform(viewId, &camera->getView(), &camera->getProj()); entities.each<TransformComponent, ModelComponent>([this, &cameraLods, camera, dt, viewId]( Entity e, TransformComponent& transformComponent, ModelComponent& modelComponent ) { const auto& model = modelComponent.getModel(); if (!model.isValid()) return; const auto& worldTransform = transformComponent.getTransform(); const auto clip_planes = math::vec2(camera->getNearClip(), camera->getFarClip()); auto& lodData = cameraLods[e]; const auto transitionTime = model.getTransitionTime(); const auto minDistance = model.getMinDistance(); const auto maxDistance = model.getMaxDistance(); const auto lodCount = model.getLods().size(); const auto currentTime = lodData.currentTime; const auto currentLodIndex = lodData.currentLodIndex; const auto targetLodIndex = lodData.targetLodIndex; auto material = model.getMaterialForGroup({}); if (!material) return; const auto hMeshCurr = model.getLod(currentLodIndex); if (!hMeshCurr) return; const auto& frustum = camera->getFrustum(); const auto& bounds = hMeshCurr->aabb; float t = 0; const auto rayOrigin = camera->getPosition(); const auto invWorld = math::inverse(worldTransform); const auto objectRayOrigin = invWorld.transformCoord(rayOrigin); const auto objectRayDirection = math::normalize(bounds.getCenter() - objectRayOrigin); bounds.intersect(objectRayOrigin, objectRayDirection, t); // Compute final object space intersection point. auto intersectionPoint = objectRayOrigin + (objectRayDirection * t); // transform intersection point back into world space to compute // the final intersection distance. intersectionPoint = worldTransform.transformCoord(intersectionPoint); const float distance = math::length(intersectionPoint - rayOrigin); updateLodData( lodData, lodCount, minDistance, maxDistance, transitionTime, distance, dt); // Test the bounding box of the mesh if (!math::frustum::testOBB(frustum, bounds, worldTransform)) return; const auto params = math::vec3{ 0.0f, -1.0f, (transitionTime - currentTime) / transitionTime }; const auto paramsInv = math::vec3{ 1.0f, 1.0f, currentTime / transitionTime }; material->setUniform("u_camera_wpos", &camera->getPosition()); material->setUniform("u_camera_clip_planes", &clip_planes); material->setUniform("u_lod_params", &params); material->submit(); // Set render states. const auto states = material->getRenderStates(); auto program = material->getProgram(); hMeshCurr->submit(viewId, program->handle, worldTransform, states); if (currentTime != 0.0f) { material->setUniform("u_lod_params", &paramsInv); material->submit(); const auto hMeshTarget = model.getLod(targetLodIndex); if (!hMeshTarget) return; hMeshTarget->submit(viewId, program->handle, worldTransform, states); } }); } { auto surface = cameraComponent.getRenderSurface(); RenderSurfaceScope scope(surface); //this will change soon gfx::blit(surface->getId(), gfx::getTexture(surface->getBufferRaw()->handle), 0, 0, gfx::getTexture(surface->getBufferRaw()->handle)); } }); } void RenderingSystem::receive(const EntityDestroyedEvent &event) { mLodDataMap.erase(event.entity); for (auto& pair : mLodDataMap) { pair.second.erase(event.entity); } } void RenderingSystem::configure(EventManager &events) { events.subscribe<EntityDestroyedEvent>(*this); } <|endoftext|>
<commit_before><commit_msg>ant bool is not 0/1<commit_after><|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbImage.h" #include "otbVectorImage.h" #include "otbImageFileReader.h" #include "otbImageFileWriter.h" #include "otbMultiToMonoChannelExtractROI.h" #include "itkRescaleIntensityImageFilter.h" // Software Guide : BeginCommandLineArgs // INPUTS: {ROI_QB_MUL_1.png} // OUTPUTS: {InnerProductPCAOutput.tif}, {PrettyInnerProductPCAOutput1.png}, {PrettyInnerProductPCAOutput2.png}, {PrettyInnerProductPCAOutput3.png} // 3 // Software Guide : EndCommandLineArgs // Software Guide : BeginLatex // // This example illustrates the use of the // \doxygen{otb}{InnerProductPCAImageFilter}. // This filter computes a Principal Component Analysis using an // efficient method based on the inner product in order to compute the // covariance matrix. // // The first step required to use this filter is to include its header file. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "otbInnerProductPCAImageFilter.h" // Software Guide : EndCodeSnippet int main( int argc, char* argv[] ) { typedef double PixelType; const unsigned int Dimension = 2; const char * inputFileName = argv[1]; const char * outputFilename = argv[2]; const unsigned int numberOfPrincipalComponentsRequired(atoi(argv[6])); // Software Guide : BeginLatex // // We start by defining the types for the images and the reader and // the writer. We choose to work with a \doxygen{otb}{VectorImage}, // since we will produce a multi-channel image (the principal // components) from a multi-channel input image. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::VectorImage<PixelType,Dimension> ImageType; typedef otb::ImageFileReader< ImageType > ReaderType; typedef otb::ImageFileWriter< ImageType > WriterType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We instantiate now the image reader and we set the image file name. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName(inputFileName); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We define the type for the filter. It is templated over the input // and the output image types. We the instantiate the filter. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::InnerProductPCAImageFilter<ImageType,ImageType> PCAFilterType; PCAFilterType::Pointer pcafilter = PCAFilterType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The only parameter needed for the PCA is the number of principal // components required as output. We can choose to get less PCs than // the number of input bands. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet pcafilter->SetNumberOfPrincipalComponentsRequired( numberOfPrincipalComponentsRequired); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We now instantiate the writer and set the file name for the // output image. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet WriterType::Pointer writer = WriterType::New(); writer->SetFileName(outputFilename); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We finally plug the pipeline and trigger the PCA computation with // the method \code{Update()} of the writer. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet pcafilter->SetInput(reader->GetOutput()); writer->SetInput(pcafilter->GetOutput()); writer->Update(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // Figure~\ref{fig:INNERPRODUCTPCA_FILTER} shows the result of applying // the key point density filter to an image using the SIFT // detector. // \begin{figure} // \center // \includegraphics[width=0.25\textwidth]{ROI_QB_MUL_1.eps} // \includegraphics[width=0.25\textwidth]{PrettyInnerProductPCAOutput1.eps} // \includegraphics[width=0.25\textwidth]{PrettyInnerProductPCAOutput2.eps} // \includegraphics[width=0.25\textwidth]{PrettyInnerProductPCAOutput3.eps} // \itkcaption[Inner Product PCA Filter]{Result of applying the // \doxygen{otb}{InnerProductPCAImageFilter} to an image. From left // to right and top to bottom: // original image, first PC, second PC, third PC.} // \label{fig:INNERPRODUCTPCA_FILTER} // \end{figure} // // Software Guide : EndLatex typedef otb::Image<PixelType,Dimension> MonoImageType; typedef otb::MultiToMonoChannelExtractROI< PixelType, PixelType > ExtractROIFilterType; typedef otb::Image<unsigned char, 2> OutputImageType; typedef otb::ImageFileWriter< OutputImageType > WriterType2; typedef itk::RescaleIntensityImageFilter< MonoImageType, OutputImageType> RescalerType; for(unsigned int cpt=0 ; cpt < numberOfPrincipalComponentsRequired ; cpt++) { ExtractROIFilterType::Pointer extractROIFilter = ExtractROIFilterType::New(); RescalerType::Pointer rescaler = RescalerType::New(); WriterType2::Pointer writer2 = WriterType2::New(); extractROIFilter->SetInput(pcafilter->GetOutput()); extractROIFilter->SetChannel(cpt+1); rescaler->SetInput( extractROIFilter->GetOutput()); rescaler->SetOutputMinimum(0); rescaler->SetOutputMaximum(255); writer2->SetInput(rescaler->GetOutput()); writer2->SetFileName(argv[cpt+3]); writer2->Update(); } return EXIT_SUCCESS; } <commit_msg>DOC: correction of text<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbImage.h" #include "otbVectorImage.h" #include "otbImageFileReader.h" #include "otbImageFileWriter.h" #include "otbMultiToMonoChannelExtractROI.h" #include "itkRescaleIntensityImageFilter.h" // Software Guide : BeginCommandLineArgs // INPUTS: {ROI_QB_MUL_1.png} // OUTPUTS: {InnerProductPCAOutput.tif}, {PrettyInnerProductPCAOutput1.png}, {PrettyInnerProductPCAOutput2.png}, {PrettyInnerProductPCAOutput3.png} // 3 // Software Guide : EndCommandLineArgs // Software Guide : BeginLatex // // This example illustrates the use of the // \doxygen{otb}{InnerProductPCAImageFilter}. // This filter computes a Principal Component Analysis using an // efficient method based on the inner product in order to compute the // covariance matrix. // // The first step required to use this filter is to include its header file. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "otbInnerProductPCAImageFilter.h" // Software Guide : EndCodeSnippet int main( int argc, char* argv[] ) { typedef double PixelType; const unsigned int Dimension = 2; const char * inputFileName = argv[1]; const char * outputFilename = argv[2]; const unsigned int numberOfPrincipalComponentsRequired(atoi(argv[6])); // Software Guide : BeginLatex // // We start by defining the types for the images and the reader and // the writer. We choose to work with a \doxygen{otb}{VectorImage}, // since we will produce a multi-channel image (the principal // components) from a multi-channel input image. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::VectorImage<PixelType,Dimension> ImageType; typedef otb::ImageFileReader< ImageType > ReaderType; typedef otb::ImageFileWriter< ImageType > WriterType; // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We instantiate now the image reader and we set the image file name. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName(inputFileName); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We define the type for the filter. It is templated over the input // and the output image types. We the instantiate the filter. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::InnerProductPCAImageFilter<ImageType,ImageType> PCAFilterType; PCAFilterType::Pointer pcafilter = PCAFilterType::New(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The only parameter needed for the PCA is the number of principal // components required as output. We can choose to get less PCs than // the number of input bands. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet pcafilter->SetNumberOfPrincipalComponentsRequired( numberOfPrincipalComponentsRequired); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We now instantiate the writer and set the file name for the // output image. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet WriterType::Pointer writer = WriterType::New(); writer->SetFileName(outputFilename); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // We finally plug the pipeline and trigger the PCA computation with // the method \code{Update()} of the writer. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet pcafilter->SetInput(reader->GetOutput()); writer->SetInput(pcafilter->GetOutput()); writer->Update(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // Figure~\ref{fig:INNERPRODUCTPCA_FILTER} shows the result of applying // the PCA to a 3 band RGB image. // \begin{figure} // \center // \includegraphics[width=0.25\textwidth]{ROI_QB_MUL_1.eps} // \includegraphics[width=0.25\textwidth]{PrettyInnerProductPCAOutput1.eps} // \includegraphics[width=0.25\textwidth]{PrettyInnerProductPCAOutput2.eps} // \includegraphics[width=0.25\textwidth]{PrettyInnerProductPCAOutput3.eps} // \itkcaption[Inner Product PCA Filter]{Result of applying the // \doxygen{otb}{InnerProductPCAImageFilter} to an image. From left // to right and top to bottom: // original image, first PC, second PC, third PC.} // \label{fig:INNERPRODUCTPCA_FILTER} // \end{figure} // // Software Guide : EndLatex typedef otb::Image<PixelType,Dimension> MonoImageType; typedef otb::MultiToMonoChannelExtractROI< PixelType, PixelType > ExtractROIFilterType; typedef otb::Image<unsigned char, 2> OutputImageType; typedef otb::ImageFileWriter< OutputImageType > WriterType2; typedef itk::RescaleIntensityImageFilter< MonoImageType, OutputImageType> RescalerType; for(unsigned int cpt=0 ; cpt < numberOfPrincipalComponentsRequired ; cpt++) { ExtractROIFilterType::Pointer extractROIFilter = ExtractROIFilterType::New(); RescalerType::Pointer rescaler = RescalerType::New(); WriterType2::Pointer writer2 = WriterType2::New(); extractROIFilter->SetInput(pcafilter->GetOutput()); extractROIFilter->SetChannel(cpt+1); rescaler->SetInput( extractROIFilter->GetOutput()); rescaler->SetOutputMinimum(0); rescaler->SetOutputMaximum(255); writer2->SetInput(rescaler->GetOutput()); writer2->SetFileName(argv[cpt+3]); writer2->Update(); } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* * Copyright (c) 2007-2008 Digital Bazaar, Inc. All rights reserved. */ #include "db/crypto/BigDecimal.h" #include <sstream> using namespace std; using namespace db::crypto; BigDecimal::BigDecimal(long double value) { initialize(); if(value != 0) { *this = value; } } BigDecimal::BigDecimal(double value) { initialize(); if(value != 0) { *this = value; } } BigDecimal::BigDecimal(long long value) { initialize(); if(value != 0) { *this = value; } } BigDecimal::BigDecimal(unsigned long long value) { initialize(); if(value != 0) { *this = value; } } BigDecimal::BigDecimal(int value) { initialize(); if(value != 0) { *this = value; } } BigDecimal::BigDecimal(unsigned int value) { initialize(); if(value != 0) { *this = value; } } BigDecimal::BigDecimal(const char* value) { initialize(); *this = value; } BigDecimal::BigDecimal(const string& value) { initialize(); *this = value; } BigDecimal::BigDecimal(const BigDecimal& copy) { initialize(); mSignificand = copy.mSignificand; mExponent = copy.mExponent; } BigDecimal::~BigDecimal() { } void BigDecimal::initialize() { mExponent = 0; mPrecision = 10; mRoundingMode = HalfUp; } void BigDecimal::setExponent(int exponent) { if(exponent > mExponent) { // multiply significand by power difference BigInteger ten(10); mSignificand *= ten.pow(exponent - mExponent); } mExponent = exponent; } void BigDecimal::synchronizeExponents(BigDecimal& bd1, BigDecimal& bd2) { // only do work if exponents are different if(bd1.mExponent != bd2.mExponent) { // use the larger exponent to retain precision if(bd1.mExponent > bd2.mExponent) { bd2.setExponent(bd1.mExponent); } else { bd1.setExponent(bd2.mExponent); } } } BigDecimal& BigDecimal::operator=(const BigDecimal& rhs) { mSignificand = rhs.mSignificand; mExponent = rhs.mExponent; return *this; } BigDecimal& BigDecimal::operator=(long double rhs) { // convert double to string ostringstream oss; oss << rhs; return *this = oss.str(); } BigDecimal& BigDecimal::operator=(double rhs) { // convert double to string ostringstream oss; oss << rhs; return *this = oss.str(); } BigDecimal& BigDecimal::operator=(long long rhs) { // convert long to string char temp[22]; snprintf(temp, 22, "%lli", rhs); return *this = temp; } BigDecimal& BigDecimal::operator=(unsigned long long rhs) { // convert long to string char temp[22]; snprintf(temp, 22, "%llu", rhs); return *this = temp; } BigDecimal& BigDecimal::operator=(int rhs) { // convert int to string char temp[12]; snprintf(temp, 12, "%i", rhs); return *this = temp; } BigDecimal& BigDecimal::operator=(unsigned int rhs) { // convert int to string char temp[12]; snprintf(temp, 12, "%u", rhs); return *this = temp; } BigDecimal& BigDecimal::operator=(const char* rhs) { *this = string(rhs); return *this; } BigDecimal& BigDecimal::operator=(const string& rhs) { string temp; // find decimal point unsigned int dot = rhs.rfind('.'); if(dot != string::npos) { // check for scientific notation unsigned int e = rhs.rfind('e'); if(e != string::npos && e != rhs.length() - 2) { // parse exponent mExponent = -strtoll(rhs.c_str() + e + 1, NULL, 10); // add number of places between the e and the decimal point mExponent += e - dot - 1; // remove decimal point and e temp.append(rhs.substr(0, dot)); temp.append(rhs.substr(dot + 1, e - dot)); } else { // set exponent to the number of places between dot and end of string mExponent = rhs.length() - dot - 1; // remove decimal point temp.append(rhs.substr(0, dot)); if(dot != rhs.length() - 1) { temp.append(rhs.substr(dot + 1)); } } } else { // no decimal point, set exponent to 0 mExponent = 0; temp = rhs; } // parse significand mSignificand = temp; // if exponent is negative, scale the significand so the exponent is zero if(mExponent < 0) { mExponent = -mExponent; BigInteger ten(10); mSignificand *= ten.pow(mExponent); mExponent = 0; } return *this; } bool BigDecimal::operator==(const BigDecimal& rhs) { BigDecimal temp = rhs; synchronizeExponents(*this, temp); return this->mSignificand == temp.mSignificand; } bool BigDecimal::operator==(long double rhs) { return getDouble() == rhs; } bool BigDecimal::operator!=(const BigDecimal& rhs) { return !(*this == rhs); } bool BigDecimal::operator!=(long double rhs) { return !(*this == rhs); } bool BigDecimal::operator<(const BigDecimal& rhs) { bool rval = false; if(isNegative() && !rhs.isNegative()) { rval = true; } else if(isNegative() == rhs.isNegative()) { BigDecimal temp = rhs; synchronizeExponents(*this, temp); if(mSignificand < temp.mSignificand) { rval = true; } } return rval; } bool BigDecimal::operator>(const BigDecimal& rhs) { bool rval = false; if(!isNegative() && rhs.isNegative()) { rval = true; } else if(isNegative() == rhs.isNegative()) { BigDecimal temp = rhs; synchronizeExponents(*this, temp); if(mSignificand > temp.mSignificand) { rval = true; } } return rval; } bool BigDecimal::operator<=(const BigDecimal& rhs) { return *this < rhs || *this == rhs; } bool BigDecimal::operator>=(const BigDecimal& rhs) { return *this > rhs || *this == rhs; } BigDecimal BigDecimal::operator+(const BigDecimal& rhs) { BigDecimal rval = *this; BigDecimal temp = rhs; synchronizeExponents(rval, temp); rval.mSignificand += temp.mSignificand; return rval; } BigDecimal BigDecimal::operator-(const BigDecimal& rhs) { BigDecimal rval = *this; BigDecimal temp = rhs; synchronizeExponents(rval, temp); rval.mSignificand -= temp.mSignificand; return rval; } BigDecimal BigDecimal::operator*(const BigDecimal& rhs) { BigDecimal rval = *this; // perform multiplication and then add exponents rval.mSignificand *= rhs.mSignificand; rval.mExponent += rhs.mExponent; return rval; } BigDecimal BigDecimal::operator/(const BigDecimal& rhs) { BigDecimal rval = *this; // add the divisor's exponent to the dividend so that when a division is // performed, the exponents subtract to reproduce the original scale rval.setExponent(rval.mExponent + rhs.mExponent); // do division with remainder BigDecimal remainder; rval.mSignificand.divide( rhs.mSignificand, rval.mSignificand, remainder.mSignificand); // see if there is a remainder to add to the result if(remainder.mSignificand != 0) { // determine if the remainder should be rounded up bool roundUp = (mRoundingMode == Up) ? true : false; if(mRoundingMode == HalfUp) { // if twice the remainder is greater than or equal to the divisor, // then it is at least half as large as the divisor if((remainder.mSignificand + remainder.mSignificand).absCompare( rhs.mSignificand) >= 0) { roundUp = true; } } // raise remainder to digits of precision (taking into account the // remainder has the same scale as the dividend rval) unsigned int digits = 0; if(mPrecision - rval.mExponent > 0) { digits = mPrecision - rval.mExponent; BigInteger ten(10); remainder.mSignificand *= ten.pow(digits); } // perform division on significand remainder.mSignificand /= rhs.mSignificand; // set remainder exponent to digits of precision remainder.mExponent = mPrecision; // round up if appropriate if(roundUp) { BigDecimal bd; bd.mSignificand = 1; bd.mExponent = mPrecision; rval += bd; } // add remainder rval += remainder; } return rval; } BigDecimal BigDecimal::operator%(const BigDecimal& rhs) { BigDecimal rval = *this; BigDecimal temp = rhs; synchronizeExponents(rval, temp); rval.mSignificand %= temp.mSignificand; return rval; } BigDecimal& BigDecimal::operator+=(const BigDecimal& rhs) { *this = *this + rhs; return *this; } BigDecimal& BigDecimal::operator-=(const BigDecimal& rhs) { *this = *this - rhs; return *this; } BigDecimal& BigDecimal::operator*=(const BigDecimal& rhs) { *this = *this * rhs; return *this; } BigDecimal& BigDecimal::operator/=(const BigDecimal& rhs) { *this = *this / rhs; return *this; } BigDecimal& BigDecimal::operator%=(const BigDecimal& rhs) { *this = *this % rhs; return *this; } bool BigDecimal::isZero() const { return mSignificand.isZero(); } void BigDecimal::setNegative(bool negative) { mSignificand.setNegative(negative); } bool BigDecimal::isNegative() const { return mSignificand.isNegative(); } long double BigDecimal::getDouble() const { // get value as a string // parse long double return strtold(toString().c_str(), NULL); } void BigDecimal::setPrecision(unsigned int precision, RoundingMode roundingMode) { mPrecision = precision; mRoundingMode = roundingMode; } unsigned int BigDecimal::getPrecision() { return mPrecision; } void BigDecimal::round() { // write out to a string string str = toString(); // find exponent unsigned int dot = str.rfind('.'); if(dot != string::npos) { // determine if there are more digits than the precision allows if(str.length() - (dot + 1) > mPrecision) { // get the extra digits string extra = str.substr(dot + 1 + mPrecision); // set new exponent by subtracting extra length mExponent -= extra.length(); // truncate significand mSignificand = (str.substr(0, dot) + str.substr(dot + 1, mExponent)); // round significand according to rounding mode if(mRoundingMode == Up) { // must round up if there is anything but a zero in extra bool round = false; for(const char* ptr = extra.c_str(); *ptr != 0 && !round; ptr++) { if(*ptr != '0') { round = true; } } if(round) { // add 1 with the same exponent BigDecimal bd = 1; bd.mExponent = mExponent; *this += bd; } } else if(mRoundingMode == HalfUp) { if(extra.at(0) > '4' && extra.at(0) <= '9') { // add 1 with the same exponent BigDecimal bd = 1; bd.mExponent = mExponent; *this += bd; } } } } } string BigDecimal::toString() const { // write out significand string str = mSignificand.toString(); if(mExponent < 0) { // append zeros int zeros = -mExponent - str.length(); if(zeros > 0) { str.append(0, zeros, '0'); } else { // insert decimal point str.insert(str.length() + mExponent, 1, '.'); } } else if(mExponent > 0) { // prepend zeros int zeros = mExponent - str.length(); if(zeros > 0) { str.insert(0, zeros, '0'); } if((unsigned int)mExponent == str.length()) { // prepend "0." str.insert(0, 1, '.'); str.insert(0, 1, '0'); } else { // insert decimal point str.insert(str.length() - mExponent, 1, '.'); } } return str; } ostream& operator<<(ostream& os, const BigDecimal& bd) { os << bd.toString(); return os; } istream& operator>>(istream& is, BigDecimal& bd) { string str; is >> str; bd = str; return is; } <commit_msg>Fixed bug where toString() for negative small numbers was incorrect.<commit_after>/* * Copyright (c) 2007-2008 Digital Bazaar, Inc. All rights reserved. */ #include "db/crypto/BigDecimal.h" #include <sstream> using namespace std; using namespace db::crypto; BigDecimal::BigDecimal(long double value) { initialize(); if(value != 0) { *this = value; } } BigDecimal::BigDecimal(double value) { initialize(); if(value != 0) { *this = value; } } BigDecimal::BigDecimal(long long value) { initialize(); if(value != 0) { *this = value; } } BigDecimal::BigDecimal(unsigned long long value) { initialize(); if(value != 0) { *this = value; } } BigDecimal::BigDecimal(int value) { initialize(); if(value != 0) { *this = value; } } BigDecimal::BigDecimal(unsigned int value) { initialize(); if(value != 0) { *this = value; } } BigDecimal::BigDecimal(const char* value) { initialize(); *this = value; } BigDecimal::BigDecimal(const string& value) { initialize(); *this = value; } BigDecimal::BigDecimal(const BigDecimal& copy) { initialize(); mSignificand = copy.mSignificand; mExponent = copy.mExponent; } BigDecimal::~BigDecimal() { } void BigDecimal::initialize() { mExponent = 0; mPrecision = 10; mRoundingMode = HalfUp; } void BigDecimal::setExponent(int exponent) { if(exponent > mExponent) { // multiply significand by power difference BigInteger ten(10); mSignificand *= ten.pow(exponent - mExponent); } mExponent = exponent; } void BigDecimal::synchronizeExponents(BigDecimal& bd1, BigDecimal& bd2) { // only do work if exponents are different if(bd1.mExponent != bd2.mExponent) { // use the larger exponent to retain precision if(bd1.mExponent > bd2.mExponent) { bd2.setExponent(bd1.mExponent); } else { bd1.setExponent(bd2.mExponent); } } } BigDecimal& BigDecimal::operator=(const BigDecimal& rhs) { mSignificand = rhs.mSignificand; mExponent = rhs.mExponent; return *this; } BigDecimal& BigDecimal::operator=(long double rhs) { // convert double to string ostringstream oss; oss << rhs; return *this = oss.str(); } BigDecimal& BigDecimal::operator=(double rhs) { // convert double to string ostringstream oss; oss << rhs; return *this = oss.str(); } BigDecimal& BigDecimal::operator=(long long rhs) { // convert long to string char temp[22]; snprintf(temp, 22, "%lli", rhs); return *this = temp; } BigDecimal& BigDecimal::operator=(unsigned long long rhs) { // convert long to string char temp[22]; snprintf(temp, 22, "%llu", rhs); return *this = temp; } BigDecimal& BigDecimal::operator=(int rhs) { // convert int to string char temp[12]; snprintf(temp, 12, "%i", rhs); return *this = temp; } BigDecimal& BigDecimal::operator=(unsigned int rhs) { // convert int to string char temp[12]; snprintf(temp, 12, "%u", rhs); return *this = temp; } BigDecimal& BigDecimal::operator=(const char* rhs) { *this = string(rhs); return *this; } BigDecimal& BigDecimal::operator=(const string& rhs) { string temp; // find decimal point unsigned int dot = rhs.rfind('.'); if(dot != string::npos) { // check for scientific notation unsigned int e = rhs.rfind('e'); if(e != string::npos && e != rhs.length() - 2) { // parse exponent mExponent = -strtoll(rhs.c_str() + e + 1, NULL, 10); // add number of places between the e and the decimal point mExponent += e - dot - 1; // remove decimal point and e temp.append(rhs.substr(0, dot)); temp.append(rhs.substr(dot + 1, e - dot)); } else { // set exponent to the number of places between dot and end of string mExponent = rhs.length() - dot - 1; // remove decimal point temp.append(rhs.substr(0, dot)); if(dot != rhs.length() - 1) { temp.append(rhs.substr(dot + 1)); } } } else { // no decimal point, set exponent to 0 mExponent = 0; temp = rhs; } // parse significand mSignificand = temp; // if exponent is negative, scale the significand so the exponent is zero if(mExponent < 0) { mExponent = -mExponent; BigInteger ten(10); mSignificand *= ten.pow(mExponent); mExponent = 0; } return *this; } bool BigDecimal::operator==(const BigDecimal& rhs) { BigDecimal temp = rhs; synchronizeExponents(*this, temp); return this->mSignificand == temp.mSignificand; } bool BigDecimal::operator==(long double rhs) { return getDouble() == rhs; } bool BigDecimal::operator!=(const BigDecimal& rhs) { return !(*this == rhs); } bool BigDecimal::operator!=(long double rhs) { return !(*this == rhs); } bool BigDecimal::operator<(const BigDecimal& rhs) { bool rval = false; if(isNegative() && !rhs.isNegative()) { rval = true; } else if(isNegative() == rhs.isNegative()) { BigDecimal temp = rhs; synchronizeExponents(*this, temp); if(mSignificand < temp.mSignificand) { rval = true; } } return rval; } bool BigDecimal::operator>(const BigDecimal& rhs) { bool rval = false; if(!isNegative() && rhs.isNegative()) { rval = true; } else if(isNegative() == rhs.isNegative()) { BigDecimal temp = rhs; synchronizeExponents(*this, temp); if(mSignificand > temp.mSignificand) { rval = true; } } return rval; } bool BigDecimal::operator<=(const BigDecimal& rhs) { return *this < rhs || *this == rhs; } bool BigDecimal::operator>=(const BigDecimal& rhs) { return *this > rhs || *this == rhs; } BigDecimal BigDecimal::operator+(const BigDecimal& rhs) { BigDecimal rval = *this; BigDecimal temp = rhs; synchronizeExponents(rval, temp); rval.mSignificand += temp.mSignificand; return rval; } BigDecimal BigDecimal::operator-(const BigDecimal& rhs) { BigDecimal rval = *this; BigDecimal temp = rhs; synchronizeExponents(rval, temp); rval.mSignificand -= temp.mSignificand; return rval; } BigDecimal BigDecimal::operator*(const BigDecimal& rhs) { BigDecimal rval = *this; // perform multiplication and then add exponents rval.mSignificand *= rhs.mSignificand; rval.mExponent += rhs.mExponent; return rval; } BigDecimal BigDecimal::operator/(const BigDecimal& rhs) { BigDecimal rval = *this; // add the divisor's exponent to the dividend so that when a division is // performed, the exponents subtract to reproduce the original scale rval.setExponent(rval.mExponent + rhs.mExponent); // do division with remainder BigDecimal remainder; rval.mSignificand.divide( rhs.mSignificand, rval.mSignificand, remainder.mSignificand); // see if there is a remainder to add to the result if(remainder.mSignificand != 0) { // determine if the remainder should be rounded up bool roundUp = (mRoundingMode == Up) ? true : false; if(mRoundingMode == HalfUp) { // if twice the remainder is greater than or equal to the divisor, // then it is at least half as large as the divisor if((remainder.mSignificand + remainder.mSignificand).absCompare( rhs.mSignificand) >= 0) { roundUp = true; } } // raise remainder to digits of precision (taking into account the // remainder has the same scale as the dividend rval) unsigned int digits = 0; if(mPrecision - rval.mExponent > 0) { digits = mPrecision - rval.mExponent; BigInteger ten(10); remainder.mSignificand *= ten.pow(digits); } // perform division on significand remainder.mSignificand /= rhs.mSignificand; // set remainder exponent to digits of precision remainder.mExponent = mPrecision; // round up if appropriate if(roundUp) { BigDecimal bd; bd.mSignificand = 1; bd.mExponent = mPrecision; rval += bd; } // add remainder rval += remainder; } return rval; } BigDecimal BigDecimal::operator%(const BigDecimal& rhs) { BigDecimal rval = *this; BigDecimal temp = rhs; synchronizeExponents(rval, temp); rval.mSignificand %= temp.mSignificand; return rval; } BigDecimal& BigDecimal::operator+=(const BigDecimal& rhs) { *this = *this + rhs; return *this; } BigDecimal& BigDecimal::operator-=(const BigDecimal& rhs) { *this = *this - rhs; return *this; } BigDecimal& BigDecimal::operator*=(const BigDecimal& rhs) { *this = *this * rhs; return *this; } BigDecimal& BigDecimal::operator/=(const BigDecimal& rhs) { *this = *this / rhs; return *this; } BigDecimal& BigDecimal::operator%=(const BigDecimal& rhs) { *this = *this % rhs; return *this; } bool BigDecimal::isZero() const { return mSignificand.isZero(); } void BigDecimal::setNegative(bool negative) { mSignificand.setNegative(negative); } bool BigDecimal::isNegative() const { return mSignificand.isNegative(); } long double BigDecimal::getDouble() const { // get value as a string // parse long double return strtold(toString().c_str(), NULL); } void BigDecimal::setPrecision(unsigned int precision, RoundingMode roundingMode) { mPrecision = precision; mRoundingMode = roundingMode; } unsigned int BigDecimal::getPrecision() { return mPrecision; } void BigDecimal::round() { // write out to a string string str = toString(); // find exponent unsigned int dot = str.rfind('.'); if(dot != string::npos) { // determine if there are more digits than the precision allows if(str.length() - (dot + 1) > mPrecision) { // get the extra digits string extra = str.substr(dot + 1 + mPrecision); // set new exponent by subtracting extra length mExponent -= extra.length(); // truncate significand mSignificand = (str.substr(0, dot) + str.substr(dot + 1, mExponent)); // round significand according to rounding mode if(mRoundingMode == Up) { // must round up if there is anything but a zero in extra bool round = false; for(const char* ptr = extra.c_str(); *ptr != 0 && !round; ptr++) { if(*ptr != '0') { round = true; } } if(round) { // add 1 with the same exponent BigDecimal bd = 1; bd.mExponent = mExponent; *this += bd; } } else if(mRoundingMode == HalfUp) { if(extra.at(0) > '4' && extra.at(0) <= '9') { // add 1 with the same exponent BigDecimal bd = 1; bd.mExponent = mExponent; *this += bd; } } } } } string BigDecimal::toString() const { // write out significand string str = mSignificand.toString(); // erase negative sign if(mSignificand.isNegative()) { str.erase(0, 1); } if(mExponent < 0) { // append zeros int zeros = -mExponent - str.length(); if(zeros > 0) { str.append(0, zeros, '0'); } else { // insert decimal point str.insert(str.length() + mExponent, 1, '.'); } } else if(mExponent > 0) { // prepend zeros int zeros = mExponent - str.length(); if(zeros > 0) { str.insert(0, zeros, '0'); } if((unsigned int)mExponent == str.length()) { // prepend "0." str.insert(0, 1, '.'); str.insert(0, 1, '0'); } else { // insert decimal point str.insert(str.length() - mExponent, 1, '.'); } } // insert negative sign if(mSignificand.isNegative()) { str.insert(0, 1, '-'); } return str; } ostream& operator<<(ostream& os, const BigDecimal& bd) { os << bd.toString(); return os; } istream& operator>>(istream& is, BigDecimal& bd) { string str; is >> str; bd = str; return is; } <|endoftext|>
<commit_before>// Copyright (c) 2014 Dano Pernis // See LICENSE for details #include <map> #include <string> #include "ssa.h" namespace hcc { namespace ssa { void subroutine::copy_propagation() { struct replacer_algorithm { void insert(const argument& from, const argument& to) { // replace[to] = from; // find if there's a chain auto it = replace.find(from); if (it != replace.end()) { replace.emplace(to, it->second).first->second = it->second; } else { replace.emplace(to, from).first->second = from; } } void operator()(argument& a) const { auto it = replace.find(a); if (it != replace.end()) a = it->second; } std::map<argument, argument> replace; } replacer; // pass 1: find MOVs and make replacement list for_each_bb([&] (basic_block& bb) { for (auto& instruction : bb.instructions) { if (instruction.type == instruction_type::MOV) { const auto& src = instruction.arguments[1]; const auto& dst = instruction.arguments[0]; replacer.insert(src, dst); } } }); // pass 2: apply the replacement for_each_bb([&] (basic_block& bb) { for (auto& instruction : bb.instructions) { instruction.use_apply(replacer); } }); } }} // namespace hcc::ssa <commit_msg>Refactored SSA copy propagation<commit_after>// Copyright (c) 2014 Dano Pernis // See LICENSE for details #include <map> #include <string> #include "ssa.h" namespace hcc { namespace ssa { void subroutine::copy_propagation() { std::map<argument, argument> replace; auto replacer = [&] (argument& a) { auto it = replace.find(a); if (it != replace.end()) { a = it->second; } }; // pass 1: find MOVs and make replacement list for_each_bb([&] (basic_block& bb) { for (auto& instruction : bb.instructions) { if (instruction.type == instruction_type::MOV) { const auto& src = instruction.arguments[1]; const auto& dst = instruction.arguments[0]; // replace[dst] = src; // find if there's a chain auto it = replace.find(src); if (it != replace.end()) { replace.emplace(dst, it->second).first->second = it->second; } else { replace.emplace(dst, src).first->second = src; } } } }); // pass 2: apply the replacement for_each_bb([&] (basic_block& bb) { for (auto& instruction : bb.instructions) { instruction.use_apply(replacer); } }); } }} // namespace hcc::ssa <|endoftext|>
<commit_before> #include "gtest/gtest.h" TEST(ThatWeFailQUickly, TautologiesAreTrue) { EXPECT_TRUE(false); } int main(int argc, char** argv) { // run all tests ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>Make simple test pass<commit_after> #include "gtest/gtest.h" TEST(ThatWeFailQUickly, TautologiesAreTrue) { EXPECT_TRUE(true); } int main(int argc, char** argv) { // run all tests ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>/* * This file is part of OpenModelica. * * Copyright (c) 1998-CurrentYear, Linköping University, * Department of Computer and Information Science, * SE-58183 Linköping, Sweden. * * All rights reserved. * * THIS PROGRAM IS PROVIDED UNDER THE TERMS OF GPL VERSION 3 * AND THIS OSMC PUBLIC LICENSE (OSMC-PL). * ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES RECIPIENT'S * ACCEPTANCE OF THE OSMC PUBLIC LICENSE. * * The OpenModelica software and the Open Source Modelica * Consortium (OSMC) Public License (OSMC-PL) are obtained * from Linköping University, either from the above address, * from the URLs: http://www.ida.liu.se/projects/OpenModelica or * http://www.openmodelica.org, and in the OpenModelica distribution. * GNU version 3 is obtained from: http://www.gnu.org/copyleft/gpl.html. * * This program is distributed WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH * IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS * OF OSMC-PL. * * See the full OSMC Public License conditions for more details. * */ /* * HopsanGUI * Fluid and Mechatronic Systems, Department of Management and Engineering, Linköping University * Main Authors 2009-2010: Robert Braun, Björn Eriksson, Peter Nordin * Contributors 2009-2010: Mikael Axin, Alessandro Dell'Amico, Karl Pettersson, Ingo Staack */ //! //! @file SystemParametersWidget.cpp //! @author Robert Braun <[email protected]> //! @date 2010-10-04 //! //! @brief Contains a System parameter widget class //! //$Id$ #include <QtGui> #include "../MainWindow.h" #include "SystemParametersWidget.h" #include <QWidget> #include <QDialog> #include "ProjectTabWidget.h" #include "../GUIObjects/GUISystem.h" #include "../common.h" //! Construtor for System Parameters widget, where the user can see and change the System parameters in the model. //! @param parent Pointer to the main window SystemParametersWidget::SystemParametersWidget(MainWindow *parent) : QWidget(parent) { //mpParentMainWindow = parent; //Set the name and size of the main window this->setObjectName("SystemParameterWidget"); this->resize(400,500); this->setWindowTitle("System Parameters"); mpSystemParametersTable = new SystemParameterTableWidget(0,1,this); mpAddButton = new QPushButton(tr("&Set"), this); mpAddButton->setFixedHeight(30); mpAddButton->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); mpAddButton->setAutoDefault(false); QFont tempFont = mpAddButton->font(); tempFont.setBold(true); mpAddButton->setFont(tempFont); mpAddButton->setEnabled(false); mpRemoveButton = new QPushButton(tr("&Unset"), this); mpRemoveButton->setFixedHeight(30); mpRemoveButton->setAutoDefault(false); mpRemoveButton->setFont(tempFont); mpRemoveButton->setEnabled(false); mpGridLayout = new QGridLayout(this); mpGridLayout->addWidget(mpSystemParametersTable, 0, 0); mpGridLayout->addWidget(mpAddButton, 1, 0); mpGridLayout->addWidget(mpRemoveButton, 2, 0); update(); connect(mpAddButton, SIGNAL(clicked()), mpSystemParametersTable, SLOT(openComponentPropertiesDialog())); connect(mpRemoveButton, SIGNAL(clicked()), mpSystemParametersTable, SLOT(removeSelectedParameters())); connect(gpMainWindow->mpProjectTabs, SIGNAL(currentChanged(int)), this, SLOT(update()));//Strössel! connect(gpMainWindow->mpProjectTabs, SIGNAL(newTabAdded()), this, SLOT(update()));//Strössel! } void SystemParametersWidget::update() { if(gpMainWindow->mpProjectTabs->count()>0) { mpAddButton->setEnabled(true); mpRemoveButton->setEnabled(true); } else { mpAddButton->setEnabled(false); mpRemoveButton->setEnabled(false); } mpSystemParametersTable->update(); } SystemParameterTableWidget::SystemParameterTableWidget(int rows, int columns, QWidget *parent) : QTableWidget(rows, columns, parent) { setFocusPolicy(Qt::StrongFocus); setSelectionMode(QAbstractItemView::SingleSelection); setBaseSize(400, 500); horizontalHeader()->setStretchLastSection(true); horizontalHeader()->hide(); update(); connect(this, SIGNAL(itemChanged(QTableWidgetItem*)), this, SLOT(changeParameter(QTableWidgetItem*))); } void SystemParameterTableWidget::keyPressEvent(QKeyEvent *event) { QTableWidget::keyPressEvent(event); if(event->key() == Qt::Key_Delete) { std::cout << "Delete current System Parameter Widget Items" << std::endl; removeSelectedParameters(); } } //! @brief Used for parameter changes done directly in the label void SystemParameterTableWidget::changeParameter(QTableWidgetItem *item) { //Filter out value labels if(item->column() == 1) { QTableWidgetItem *neighborItem = itemAt(item->row(), item->column()-1); QString parName = neighborItem->text(); QString parValue = item->text(); //Do not do update, then crash due to the rebuild of the QTableWidgetItems setParameter(parName, parValue, false); } } double SystemParameterTableWidget::getParameter(QString name) { return gpMainWindow->mpProjectTabs->getCurrentTopLevelSystem()->getCoreSystemAccessPtr()->getSystemParameter(name); } bool SystemParameterTableWidget::hasParameter(QString name) { return gpMainWindow->mpProjectTabs->getCurrentTopLevelSystem()->getCoreSystemAccessPtr()->hasSystemParameter(name); } //! Slot that adds a System parameter value //! @param name Lookup name for the System parameter //! @param value Value of the System parameter void SystemParameterTableWidget::setParameter(QString name, double value, bool doUpdate) { //Error check if(!(gpMainWindow->mpProjectTabs->getCurrentTopLevelSystem()->getCoreSystemAccessPtr()->setSystemParameter(name, value))) { QMessageBox::critical(0, "Hopsan GUI", QString("'%1' is an invalid name for a system parameter.") .arg(name)); return; } if(doUpdate) { update(); } gpMainWindow->mpProjectTabs->getCurrentTab()->hasChanged(); emit modifiedSystemParameter(); } //! Slot that adds a System parameter value //! @param name Lookup name for the System parameter //! @param value Value of the System parameter void SystemParameterTableWidget::setParameter(QString name, QString valueTxt, bool doUpdate) { //Error check bool isDbl; double value = valueTxt.toDouble((&isDbl)); if(!(isDbl)) { QMessageBox::critical(0, "Hopsan GUI", QString("'%1' is not a valid number.") .arg(valueTxt)); QString oldValue = QString::number(gpMainWindow->mpProjectTabs->getCurrentTopLevelSystem()->getCoreSystemAccessPtr()->getSystemParameter(name)); QList<QTableWidgetItem *> items = selectedItems(); //Error if size() > 1, but it should not be! :) for(int i = 0; i<items.size(); ++i) { items[i]->setText(oldValue); } } else { setParameter(name, value, doUpdate); } } void SystemParameterTableWidget::setParameters() { // if(gpMainWindow->mpProjectTabs->getCurrentTopLevelSystem()->getCoreSystemAccessPtr()->getNumberOfSystemParameters() > 0) // { for(int i=0; i<rowCount(); ++i) { QString name = item(i, 0)->text(); double value = item(i, 1)->text().toDouble(); setParameter(name, value); } // } } //! Slot that removes all selected System parameters in parameter table //! @todo This shall remove the actual System parameters when they have been implemented, wherever they are stored. void SystemParameterTableWidget::removeSelectedParameters() { if(gpMainWindow->mpProjectTabs->count()>0) { QList<QTableWidgetItem *> pSelectedItems = selectedItems(); QStringList parametersToRemove; QString tempName; for(int i=0; i<pSelectedItems.size(); ++i) { tempName = item(pSelectedItems[i]->row(),0)->text(); if(!parametersToRemove.contains(tempName)) { parametersToRemove.append(tempName); } removeCellWidget(pSelectedItems[i]->row(), pSelectedItems[i]->column()); delete pSelectedItems[i]; } for(int j=0; j<parametersToRemove.size(); ++j) { std::cout << "Removing: " << parametersToRemove[j].toStdString() << std::endl; gpMainWindow->mpProjectTabs->getCurrentTopLevelSystem()->getCoreSystemAccessPtr()->removeSystemParameter(parametersToRemove.at(j)); } } update(); } //! Slot that opens "Add Parameter" dialog, where the user can add new System parameters void SystemParameterTableWidget::openComponentPropertiesDialog() { QDialog *pAddComponentPropertiesDialog = new QDialog(this); pAddComponentPropertiesDialog->setWindowTitle("Set System Parameter"); mpNameLabel = new QLabel("Name: ", this); mpNameBox = new QLineEdit(this); mpValueLabel = new QLabel("Value: ", this); mpValueBox = new QLineEdit(this); mpValueBox->setValidator(new QDoubleValidator(this)); mpAddInDialogButton = new QPushButton("Set", this); mpDoneInDialogButton = new QPushButton("Done", this); QDialogButtonBox *pButtonBox = new QDialogButtonBox(Qt::Horizontal); pButtonBox->addButton(mpAddInDialogButton, QDialogButtonBox::ActionRole); pButtonBox->addButton(mpDoneInDialogButton, QDialogButtonBox::ActionRole); QGridLayout *pDialogLayout = new QGridLayout(this); pDialogLayout->addWidget(mpNameLabel,0,0); pDialogLayout->addWidget(mpNameBox,0,1); pDialogLayout->addWidget(mpValueLabel,1,0); pDialogLayout->addWidget(mpValueBox,1,1); pDialogLayout->addWidget(pButtonBox,2,0,1,2); pAddComponentPropertiesDialog->setLayout(pDialogLayout); pAddComponentPropertiesDialog->show(); connect(mpDoneInDialogButton,SIGNAL(clicked()),pAddComponentPropertiesDialog,SLOT(close())); connect(mpAddInDialogButton,SIGNAL(clicked()),this,SLOT(addParameter())); } //! @Private help slot that adds a parameter from the selected name and value in "Add Parameter" dialog void SystemParameterTableWidget::addParameter() { bool ok; setParameter(mpNameBox->text(), mpValueBox->text().toDouble(&ok)); } //! Updates the parameter table from the contents list void SystemParameterTableWidget::update() { QMap<std::string, double>::iterator it; QMap<std::string, double> tempMap; tempMap.clear(); clear(); if(gpMainWindow->mpProjectTabs->count()>0) { tempMap = gpMainWindow->mpProjectTabs->getCurrentTopLevelSystem()->getCoreSystemAccessPtr()->getSystemParametersMap(); } if(tempMap.isEmpty()) { setColumnCount(1); setRowCount(1); verticalHeader()->hide(); QTableWidgetItem *item = new QTableWidgetItem(); item->setText("No System parameters set."); item->setBackgroundColor(QColor("white")); item->setTextAlignment(Qt::AlignCenter); item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable); setItem(0,0,item); } else { setRowCount(0); setColumnCount(2); setColumnWidth(0, 120); verticalHeader()->show(); for(it=tempMap.begin(); it!=tempMap.end(); ++it) { QString valueString; valueString.setNum(it.value()); insertRow(rowCount()); QTableWidgetItem *nameItem = new QTableWidgetItem(QString(it.key().c_str())); QTableWidgetItem *valueItem = new QTableWidgetItem(valueString); nameItem->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable); valueItem->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable); setItem(rowCount()-1, 0, nameItem); setItem(rowCount()-1, 1, valueItem); } } } <commit_msg>minor change<commit_after>/* * This file is part of OpenModelica. * * Copyright (c) 1998-CurrentYear, Linköping University, * Department of Computer and Information Science, * SE-58183 Linköping, Sweden. * * All rights reserved. * * THIS PROGRAM IS PROVIDED UNDER THE TERMS OF GPL VERSION 3 * AND THIS OSMC PUBLIC LICENSE (OSMC-PL). * ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES RECIPIENT'S * ACCEPTANCE OF THE OSMC PUBLIC LICENSE. * * The OpenModelica software and the Open Source Modelica * Consortium (OSMC) Public License (OSMC-PL) are obtained * from Linköping University, either from the above address, * from the URLs: http://www.ida.liu.se/projects/OpenModelica or * http://www.openmodelica.org, and in the OpenModelica distribution. * GNU version 3 is obtained from: http://www.gnu.org/copyleft/gpl.html. * * This program is distributed WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH * IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS * OF OSMC-PL. * * See the full OSMC Public License conditions for more details. * */ /* * HopsanGUI * Fluid and Mechatronic Systems, Department of Management and Engineering, Linköping University * Main Authors 2009-2010: Robert Braun, Björn Eriksson, Peter Nordin * Contributors 2009-2010: Mikael Axin, Alessandro Dell'Amico, Karl Pettersson, Ingo Staack */ //! //! @file SystemParametersWidget.cpp //! @author Robert Braun <[email protected]> //! @date 2010-10-04 //! //! @brief Contains a System parameter widget class //! //$Id$ #include <QtGui> #include "../MainWindow.h" #include "SystemParametersWidget.h" #include <QWidget> #include <QDialog> #include "ProjectTabWidget.h" #include "../GUIObjects/GUISystem.h" #include "../common.h" //! Construtor for System Parameters widget, where the user can see and change the System parameters in the model. //! @param parent Pointer to the main window SystemParametersWidget::SystemParametersWidget(MainWindow *parent) : QWidget(parent) { //mpParentMainWindow = parent; //Set the name and size of the main window this->setObjectName("SystemParameterWidget"); this->resize(400,500); this->setWindowTitle("System Parameters"); mpSystemParametersTable = new SystemParameterTableWidget(0,1,this); mpAddButton = new QPushButton(tr("&Set"), this); mpAddButton->setFixedHeight(30); mpAddButton->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); mpAddButton->setAutoDefault(false); QFont tempFont = mpAddButton->font(); tempFont.setBold(true); mpAddButton->setFont(tempFont); mpAddButton->setEnabled(false); mpRemoveButton = new QPushButton(tr("&Unset"), this); mpRemoveButton->setFixedHeight(30); mpRemoveButton->setAutoDefault(false); mpRemoveButton->setFont(tempFont); mpRemoveButton->setEnabled(false); mpGridLayout = new QGridLayout(this); mpGridLayout->addWidget(mpSystemParametersTable, 0, 0); mpGridLayout->addWidget(mpAddButton, 1, 0); mpGridLayout->addWidget(mpRemoveButton, 2, 0); update(); connect(mpAddButton, SIGNAL(clicked()), mpSystemParametersTable, SLOT(openComponentPropertiesDialog())); connect(mpRemoveButton, SIGNAL(clicked()), mpSystemParametersTable, SLOT(removeSelectedParameters())); connect(gpMainWindow->mpProjectTabs, SIGNAL(currentChanged(int)), this, SLOT(update()));//Strössel! connect(gpMainWindow->mpProjectTabs, SIGNAL(newTabAdded()), this, SLOT(update()));//Strössel! } void SystemParametersWidget::update() { if(gpMainWindow->mpProjectTabs->count()>0) { mpAddButton->setEnabled(true); mpRemoveButton->setEnabled(true); } else { mpAddButton->setEnabled(false); mpRemoveButton->setEnabled(false); } mpSystemParametersTable->update(); } SystemParameterTableWidget::SystemParameterTableWidget(int rows, int columns, QWidget *parent) : QTableWidget(rows, columns, parent) { setFocusPolicy(Qt::StrongFocus); setSelectionMode(QAbstractItemView::SingleSelection); setBaseSize(400, 500); horizontalHeader()->setStretchLastSection(true); horizontalHeader()->hide(); update(); connect(this, SIGNAL(itemChanged(QTableWidgetItem*)), this, SLOT(changeParameter(QTableWidgetItem*))); } void SystemParameterTableWidget::keyPressEvent(QKeyEvent *event) { QTableWidget::keyPressEvent(event); if(event->key() == Qt::Key_Delete) { std::cout << "Delete current System Parameter Widget Items" << std::endl; removeSelectedParameters(); } } //! @brief Used for parameter changes done directly in the label void SystemParameterTableWidget::changeParameter(QTableWidgetItem *item) { //Filter out value labels if(item->column() == 1) { QTableWidgetItem *neighborItem = itemAt(item->row(), item->column()-1); QString parName = neighborItem->text(); QString parValue = item->text(); //Do not do update, then crash due to the rebuild of the QTableWidgetItems setParameter(parName, parValue, false); } } double SystemParameterTableWidget::getParameter(QString name) { return gpMainWindow->mpProjectTabs->getCurrentTopLevelSystem()->getCoreSystemAccessPtr()->getSystemParameter(name); } bool SystemParameterTableWidget::hasParameter(QString name) { return gpMainWindow->mpProjectTabs->getCurrentTopLevelSystem()->getCoreSystemAccessPtr()->hasSystemParameter(name); } //! Slot that adds a System parameter value //! @param name Lookup name for the System parameter //! @param value Value of the System parameter void SystemParameterTableWidget::setParameter(QString name, double value, bool doUpdate) { //Error check if(!(gpMainWindow->mpProjectTabs->getCurrentTopLevelSystem()->getCoreSystemAccessPtr()->setSystemParameter(name, value))) { QMessageBox::critical(0, "Hopsan GUI", QString("'%1' is an invalid name for a system parameter.") .arg(name)); return; } if(doUpdate) { update(); } emit modifiedSystemParameter(); } //! Slot that adds a System parameter value //! @param name Lookup name for the System parameter //! @param value Value of the System parameter void SystemParameterTableWidget::setParameter(QString name, QString valueTxt, bool doUpdate) { //Error check bool isDbl; double value = valueTxt.toDouble((&isDbl)); if(!(isDbl)) { QMessageBox::critical(0, "Hopsan GUI", QString("'%1' is not a valid number.") .arg(valueTxt)); QString oldValue = QString::number(gpMainWindow->mpProjectTabs->getCurrentTopLevelSystem()->getCoreSystemAccessPtr()->getSystemParameter(name)); QList<QTableWidgetItem *> items = selectedItems(); //Error if size() > 1, but it should not be! :) for(int i = 0; i<items.size(); ++i) { items[i]->setText(oldValue); } } else { setParameter(name, value, doUpdate); } } void SystemParameterTableWidget::setParameters() { // if(gpMainWindow->mpProjectTabs->getCurrentTopLevelSystem()->getCoreSystemAccessPtr()->getNumberOfSystemParameters() > 0) // { for(int i=0; i<rowCount(); ++i) { QString name = item(i, 0)->text(); double value = item(i, 1)->text().toDouble(); setParameter(name, value); } // } } //! Slot that removes all selected System parameters in parameter table //! @todo This shall remove the actual System parameters when they have been implemented, wherever they are stored. void SystemParameterTableWidget::removeSelectedParameters() { if(gpMainWindow->mpProjectTabs->count()>0) { QList<QTableWidgetItem *> pSelectedItems = selectedItems(); QStringList parametersToRemove; QString tempName; for(int i=0; i<pSelectedItems.size(); ++i) { tempName = item(pSelectedItems[i]->row(),0)->text(); if(!parametersToRemove.contains(tempName)) { parametersToRemove.append(tempName); gpMainWindow->mpProjectTabs->getCurrentTab()->hasChanged(); } removeCellWidget(pSelectedItems[i]->row(), pSelectedItems[i]->column()); delete pSelectedItems[i]; } for(int j=0; j<parametersToRemove.size(); ++j) { std::cout << "Removing: " << parametersToRemove[j].toStdString() << std::endl; gpMainWindow->mpProjectTabs->getCurrentTopLevelSystem()->getCoreSystemAccessPtr()->removeSystemParameter(parametersToRemove.at(j)); } } update(); } //! Slot that opens "Add Parameter" dialog, where the user can add new System parameters void SystemParameterTableWidget::openComponentPropertiesDialog() { QDialog *pAddComponentPropertiesDialog = new QDialog(this); pAddComponentPropertiesDialog->setWindowTitle("Set System Parameter"); mpNameLabel = new QLabel("Name: ", this); mpNameBox = new QLineEdit(this); mpValueLabel = new QLabel("Value: ", this); mpValueBox = new QLineEdit(this); mpValueBox->setValidator(new QDoubleValidator(this)); mpAddInDialogButton = new QPushButton("Set", this); mpDoneInDialogButton = new QPushButton("Done", this); QDialogButtonBox *pButtonBox = new QDialogButtonBox(Qt::Horizontal); pButtonBox->addButton(mpAddInDialogButton, QDialogButtonBox::ActionRole); pButtonBox->addButton(mpDoneInDialogButton, QDialogButtonBox::ActionRole); QGridLayout *pDialogLayout = new QGridLayout(this); pDialogLayout->addWidget(mpNameLabel,0,0); pDialogLayout->addWidget(mpNameBox,0,1); pDialogLayout->addWidget(mpValueLabel,1,0); pDialogLayout->addWidget(mpValueBox,1,1); pDialogLayout->addWidget(pButtonBox,2,0,1,2); pAddComponentPropertiesDialog->setLayout(pDialogLayout); pAddComponentPropertiesDialog->show(); connect(mpDoneInDialogButton,SIGNAL(clicked()),pAddComponentPropertiesDialog,SLOT(close())); connect(mpAddInDialogButton,SIGNAL(clicked()),this,SLOT(addParameter())); } //! @Private help slot that adds a parameter from the selected name and value in "Add Parameter" dialog void SystemParameterTableWidget::addParameter() { bool ok; setParameter(mpNameBox->text(), mpValueBox->text().toDouble(&ok)); gpMainWindow->mpProjectTabs->getCurrentTab()->hasChanged(); } //! Updates the parameter table from the contents list void SystemParameterTableWidget::update() { QMap<std::string, double>::iterator it; QMap<std::string, double> tempMap; tempMap.clear(); clear(); if(gpMainWindow->mpProjectTabs->count()>0) { tempMap = gpMainWindow->mpProjectTabs->getCurrentTopLevelSystem()->getCoreSystemAccessPtr()->getSystemParametersMap(); } if(tempMap.isEmpty()) { setColumnCount(1); setRowCount(1); verticalHeader()->hide(); QTableWidgetItem *item = new QTableWidgetItem(); item->setText("No System parameters set."); item->setBackgroundColor(QColor("white")); item->setTextAlignment(Qt::AlignCenter); item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable); setItem(0,0,item); } else { setRowCount(0); setColumnCount(2); setColumnWidth(0, 120); verticalHeader()->show(); for(it=tempMap.begin(); it!=tempMap.end(); ++it) { QString valueString; valueString.setNum(it.value()); insertRow(rowCount()); QTableWidgetItem *nameItem = new QTableWidgetItem(QString(it.key().c_str())); QTableWidgetItem *valueItem = new QTableWidgetItem(valueString); nameItem->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable); valueItem->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable); setItem(rowCount()-1, 0, nameItem); setItem(rowCount()-1, 1, valueItem); } } } <|endoftext|>
<commit_before>#include "adskShader.h" struct KSHairParameters { ADSK_BASE_SHADER_PARAMETERS miColor ambience; miColor ambient; miColor diffuse; miColor specular; miScalar exponent; miInteger mode; }; const unsigned int KSHAIR_VERSION = 1; typedef ShaderHelper<KSHairParameters> BaseShaderHelperType; class KSHairClass : public Material<KSHairParameters, BaseShaderHelperType, KSHAIR_VERSION> { public: // Per-render init. static void init(miState *state, KSHairParameters *params) {} static void exit(miState *state, KSHairParameters *params) {} // Per-instance init. KSHairClass(miState *state, KSHairParameters *params) : Material<KSHairParameters, BaseShaderHelperType, KSHAIR_VERSION>(state, params) {} ~KSHairClass() {} miBoolean operator()(miColor *result, miState *state, KSHairParameters *params); private: typedef Material<KSHairParameters, BaseShaderHelperType, KSHAIR_VERSION> MaterialBase; }; static float smoothstep(float min, float max, float x) { float p, term, term2; /* first clamp the parameter to [min,max]. */ if (x < min) { p = min; } else if (x > max) { p = max; } else { p = x; } /* now calculate smoothstep value: -2term^3 + 3term^2, where term = (p-min)/(max-min) */ term = (p - min) / (max - min); term2 = term * term; return -2 * term * term2 + 3 * term2; } struct ksColor : public miColor { public: ksColor() {} ksColor(miColor const &other) { r = other.r; g = other.g; b = other.b; a = other.a; } ksColor(miScalar r_, miScalar g_, miScalar b_, miScalar a_) { r = r_; g = g_; b = b_; a = a_; } ksColor operator*(miScalar v) { return ksColor(r * v, g * v, b * v, a * v); } void operator+=(ksColor const &other) { r += other.r; g += other.g; b += other.b; a += other.a; } ksColor operator+(ksColor const &other) { ksColor res(*this); res += other; return res; } void operator*=(ksColor const &other) { r *= other.r; g *= other.g; b *= other.b; a *= other.a; } ksColor operator*(ksColor const &other) { ksColor res(*this); res *= other; return res; } }; miBoolean KSHairClass::operator()(miColor *result, miState *state, KSHairParameters *paras) { /* shader parameters */ miColor *ambient; miColor *diffuse; miColor *specular; miScalar exponent; miInteger mode; miInteger n_light; miTag* light; miScalar mult; /* diffuse multiplier */ miColor diffcol; /* for diffuse modification */ miInteger samples; /* for light sampling */ miScalar dot_nl; /* for diffuse colour */ miScalar dot_th; /* for specular colour */ miScalar spec; /* specular factor */ miColor Cl; miVector L, H; miVector cross, hair_n, shading_n; /* shading normal */ miColor sum; /* light contribution */ miScalar blend; /* shading normal blend */ miVector norm = state->normal; /* for nulling/restoring */ // We can't displace. if(state->type == miRAY_DISPLACE) return miFALSE; // Shortcut if we are a shadow shader. diffuse = mi_eval_color(&paras->diffuse); if (state->type == miRAY_SHADOW) { result->r *= diffuse->r; result->g *= diffuse->g; result->b *= diffuse->b; return miTRUE; } // For mental images macros. // XXX: Do we really need this?! MBS_SETUP(state) // Dealing with render passes. PassTypeInfo* passTypeInfo; FrameBufferInfo* frameBufferInfo; unsigned int numberOfFrameBuffers = getFrameBufferInfo(state, passTypeInfo, frameBufferInfo); // Shader parameters. *result = *mi_eval_color(&paras->ambience); ambient = mi_eval_color(&paras->ambient); specular = mi_eval_color(&paras->specular); exponent = *mi_eval_scalar(&paras->exponent); mode = *mi_eval_integer(&paras->mode); // Hair parameters. miScalar p = state->bary[1]; // 0 to 1 along hair. miVector T = state->derivs[0]; // Tangent to hair. miVector V = state->dir; // Eye ray. mi_vector_normalize(&T); mi_vector_neg(&V); // Darker colours near the root. mult = 0.5f + smoothstep(0.4f, 0.8f, p) * 0.5f; diffcol.r = diffuse->r * mult; diffcol.g = diffuse->g * mult; diffcol.b = diffuse->b * mult; // Base opacity (0.5 at root, 1.0 at tip). result->r *= ambient->r; result->g *= ambient->g; result->b *= ambient->b; result->a = 1.0f - smoothstep(0.3f, 1.0f, p); /* get shading normal */ mi_vector_prod(&cross, &state->normal_geom, &T); mi_vector_prod(&hair_n, &T, &cross); blend = mi_vector_dot(&state->normal_geom, &T); shading_n.x = (1.0f-blend)*hair_n.x + blend*state->normal_geom.x; shading_n.y = (1.0f-blend)*hair_n.y + blend*state->normal_geom.y; shading_n.z = (1.0f-blend)*hair_n.z + blend*state->normal_geom.z; mi_vector_normalize(&shading_n); /* null state->normal for now, for sampling lights */ /* we leave state->pri to avoid losing self-intersection */ /* handling. */ state->normal.x = state->normal.y = state->normal.z = 0.0f; // Get the light list. mi_instance_lightlist(&n_light, &light, state); for (; n_light--; light++) { samples = 0; sum.r = sum.g = sum.b = 0; // Function that initialize light sample accumulators which need to be called before the sample loop. sampleLightBegin(numberOfFrameBuffers, frameBufferInfo); while (mi_sample_light( &Cl, &L, &dot_nl, state, *light, &samples)) { // Call to enable renderpass contributions for light shaders that were not developped using the AdskShaderSDK. handleNonAdskLights(numberOfFrameBuffers, frameBufferInfo, Cl, *light, state); // Do it ourselves. dot_nl = mi_vector_dot(&shading_n, &L); if (dot_nl < 0.0f) dot_nl = 0.0f; else if (dot_nl > 1.0f) dot_nl = 1.0f; sum.r += dot_nl * diffcol.r * Cl.r; sum.g += dot_nl * diffcol.g * Cl.g; sum.b += dot_nl * diffcol.b * Cl.b; /* find the halfway vector h */ mi_vector_add(&H, &V, &L); mi_vector_normalize(&H); /* specular coefficient from auk paper */ dot_th = mi_vector_dot(&T, &H); spec = pow(1.0 - dot_th*dot_th, 0.5*exponent); /* specular colour */ if (spec > 0.0) { sum.r += spec * specular->r * Cl.r; sum.g += spec * specular->g * Cl.g; sum.b += spec * specular->b * Cl.b; } } // Function that take care of combining sample values into the material frame buffer values, // called after light sampling loop. sampleLightEnd(state, numberOfFrameBuffers, frameBufferInfo, samples, MaterialBase::mFrameBufferWriteOperation, MaterialBase::mFrameBufferWriteFlags, MaterialBase::mFrameBufferWriteFactor); if (samples) { result->r += sum.r / samples; result->g += sum.g / samples; result->b += sum.b / samples; } } /* restore state->normal */ state->normal = norm; /* if we are translucent, trace more rays */ if (result->a < 0.9999) { miScalar alphafactor; miColor col = {0.0, 0.0, 0.0, 0.0}; mi_trace_transparent(&col, state); alphafactor = 1.0f - result->a; result->r = alphafactor * col.r + result->a * result->r; result->g = alphafactor * col.g + result->a * result->g; result->b = alphafactor * col.b + result->a * result->b; result->a += alphafactor * col.a; } return miTRUE; } EXPOSE(KSHair, miColor, ); <commit_msg>Quickly add (bad) frame buffers<commit_after>#include "adskShader.h" struct KSHairParameters { ADSK_BASE_SHADER_PARAMETERS miColor ambience; miColor ambient; miColor diffuse; miColor specular; miScalar exponent; miInteger mode; }; const unsigned int KSHAIR_VERSION = 1; typedef ShaderHelper<KSHairParameters> BaseShaderHelperType; class KSHairClass : public Material<KSHairParameters, BaseShaderHelperType, KSHAIR_VERSION> { public: // Per-render init. static void init(miState *state, KSHairParameters *params) {} static void exit(miState *state, KSHairParameters *params) {} // Per-instance init. KSHairClass(miState *state, KSHairParameters *params) : Material<KSHairParameters, BaseShaderHelperType, KSHAIR_VERSION>(state, params) {} ~KSHairClass() {} miBoolean operator()(miColor *result, miState *state, KSHairParameters *params); private: typedef Material<KSHairParameters, BaseShaderHelperType, KSHAIR_VERSION> MaterialBase; }; static float smoothstep(float min, float max, float x) { float p, term, term2; /* first clamp the parameter to [min,max]. */ if (x < min) { p = min; } else if (x > max) { p = max; } else { p = x; } /* now calculate smoothstep value: -2term^3 + 3term^2, where term = (p-min)/(max-min) */ term = (p - min) / (max - min); term2 = term * term; return -2 * term * term2 + 3 * term2; } struct ksColor : public miColor { public: ksColor() {} ksColor(miColor const &other) { r = other.r; g = other.g; b = other.b; a = other.a; } ksColor(miScalar r_, miScalar g_, miScalar b_, miScalar a_) { r = r_; g = g_; b = b_; a = a_; } ksColor operator*(miScalar v) { return ksColor(r * v, g * v, b * v, a * v); } void operator+=(ksColor const &other) { r += other.r; g += other.g; b += other.b; a += other.a; } ksColor operator+(ksColor const &other) { ksColor res(*this); res += other; return res; } void operator*=(ksColor const &other) { r *= other.r; g *= other.g; b *= other.b; a *= other.a; } ksColor operator*(ksColor const &other) { ksColor res(*this); res *= other; return res; } }; miBoolean KSHairClass::operator()(miColor *result, miState *state, KSHairParameters *paras) { /* shader parameters */ miColor *ambient; miColor *diffuse; miColor *specular; miScalar exponent; miInteger mode; miInteger n_light; miTag* light; miScalar mult; /* diffuse multiplier */ miColor diffcol; /* for diffuse modification */ miInteger samples; /* for light sampling */ miScalar dot_nl; /* for diffuse colour */ miScalar dot_th; /* for specular colour */ miScalar spec; /* specular factor */ miColor Cl; miVector L, H; miVector cross, hair_n, shading_n; /* shading normal */ miColor sum; /* light contribution */ miScalar blend; /* shading normal blend */ miVector norm = state->normal; /* for nulling/restoring */ // We can't displace. if(state->type == miRAY_DISPLACE) return miFALSE; // Shortcut if we are a shadow shader. diffuse = mi_eval_color(&paras->diffuse); if (state->type == miRAY_SHADOW) { result->r *= diffuse->r; result->g *= diffuse->g; result->b *= diffuse->b; return miTRUE; } // For mental images macros. // XXX: Do we really need this?! MBS_SETUP(state) // Dealing with render passes. PassTypeInfo* passTypeInfo; FrameBufferInfo* frameBufferInfo; unsigned int numberOfFrameBuffers = getFrameBufferInfo(state, passTypeInfo, frameBufferInfo); // Shader parameters. *result = *mi_eval_color(&paras->ambience); ambient = mi_eval_color(&paras->ambient); specular = mi_eval_color(&paras->specular); exponent = *mi_eval_scalar(&paras->exponent); mode = *mi_eval_integer(&paras->mode); // Hair parameters. miScalar p = state->bary[1]; // 0 to 1 along hair. miVector T = state->derivs[0]; // Tangent to hair. miVector V = state->dir; // Eye ray. mi_vector_normalize(&T); mi_vector_neg(&V); // Darker colours near the root. mult = 0.5f + smoothstep(0.4f, 0.8f, p) * 0.5f; diffcol.r = diffuse->r * mult; diffcol.g = diffuse->g * mult; diffcol.b = diffuse->b * mult; // Base opacity (0.5 at root, 1.0 at tip). result->r *= ambient->r; result->g *= ambient->g; result->b *= ambient->b; result->a = 1.0f - smoothstep(0.3f, 1.0f, p); /* get shading normal */ mi_vector_prod(&cross, &state->normal_geom, &T); mi_vector_prod(&hair_n, &T, &cross); blend = mi_vector_dot(&state->normal_geom, &T); shading_n.x = (1.0f-blend)*hair_n.x + blend*state->normal_geom.x; shading_n.y = (1.0f-blend)*hair_n.y + blend*state->normal_geom.y; shading_n.z = (1.0f-blend)*hair_n.z + blend*state->normal_geom.z; mi_vector_normalize(&shading_n); /* null state->normal for now, for sampling lights */ /* we leave state->pri to avoid losing self-intersection */ /* handling. */ state->normal.x = state->normal.y = state->normal.z = 0.0f; miColor diff_sum, spec_sum; // Get the light list. mi_instance_lightlist(&n_light, &light, state); for (; n_light--; light++) { samples = 0; sum.r = sum.g = sum.b = 0; diff_sum.r = diff_sum.g = diff_sum.b = 0; spec_sum.r = spec_sum.g = spec_sum.b = 0; // Function that initialize light sample accumulators which need to be called before the sample loop. sampleLightBegin(numberOfFrameBuffers, frameBufferInfo); while (mi_sample_light( &Cl, &L, &dot_nl, state, *light, &samples)) { // Call to enable renderpass contributions for light shaders that were not developped using the AdskShaderSDK. handleNonAdskLights(numberOfFrameBuffers, frameBufferInfo, Cl, *light, state); // Do it ourselves. dot_nl = mi_vector_dot(&shading_n, &L); if (dot_nl < 0.0f) dot_nl = 0.0f; else if (dot_nl > 1.0f) dot_nl = 1.0f; miColor s_diff = diffcol * Cl * dot_nl; if (numberOfFrameBuffers && MaterialBase::mFrameBufferWriteOperation) { MaterialBase::writeToFrameBuffers(state, frameBufferInfo, passTypeInfo, s_diff, DIFFUSE, true); } diff_sum.r += dot_nl * diffcol.r * Cl.r; diff_sum.g += dot_nl * diffcol.g * Cl.g; diff_sum.b += dot_nl * diffcol.b * Cl.b; /* find the halfway vector h */ mi_vector_add(&H, &V, &L); mi_vector_normalize(&H); /* specular coefficient from auk paper */ dot_th = mi_vector_dot(&T, &H); spec = pow(1.0 - dot_th*dot_th, 0.5*exponent); /* specular colour */ if (spec > 0.0) { spec_sum.r += spec * specular->r * Cl.r; spec_sum.g += spec * specular->g * Cl.g; spec_sum.b += spec * specular->b * Cl.b; miColor s_spec = *specular * Cl * spec; if (numberOfFrameBuffers && MaterialBase::mFrameBufferWriteOperation) { MaterialBase::writeToFrameBuffers(state, frameBufferInfo, passTypeInfo, s_spec, SPECULAR, true); } } } // Function that take care of combining sample values into the material frame buffer values, // called after light sampling loop. sampleLightEnd(state, numberOfFrameBuffers, frameBufferInfo, samples, MaterialBase::mFrameBufferWriteOperation, MaterialBase::mFrameBufferWriteFlags, MaterialBase::mFrameBufferWriteFactor); if (samples) { result->r += (diff_sum.r + spec_sum.r) / samples; result->g += (diff_sum.g + spec_sum.g) / samples; result->b += (diff_sum.b + spec_sum.b) / samples; } } /* restore state->normal */ state->normal = norm; /* if we are translucent, trace more rays */ if (result->a < 0.9999) { miScalar alphafactor; miColor col = {0.0, 0.0, 0.0, 0.0}; mi_trace_transparent(&col, state); alphafactor = 1.0f - result->a; result->r = alphafactor * col.r + result->a * result->r; result->g = alphafactor * col.g + result->a * result->g; result->b = alphafactor * col.b + result->a * result->b; result->a += alphafactor * col.a; } return miTRUE; } EXPOSE(KSHair, miColor, ); <|endoftext|>
<commit_before> #include <libclientserver.h> Notify::Notify() { } Notify::~Notify() { if (m_map.size() != 0) abort(); //Some things still reference us. This is a bug in the callers code } void Notify::Add(INotify *p) { ScopedLock lock(&m_mutex); m_map.insert(std::make_pair<INotify *, INotify *>(p, p)); } void Notify::Remove(INotify *p) { ScopedLock lock(&m_mutex); std::map<INotify *, INotify *>::iterator it = m_map.find(p); if (it == m_map.end()) abort(); //Request to delete an item that does not exist m_map.erase(it); } void Notify::Call(void *d) { ScopedLock lock(&m_mutex); for(std::map<INotify *, INotify *>::iterator it = m_map.begin(); it != m_map.end(); it++) { it->first->Notify(d); } } <commit_msg>Fix Notify Compile error on ubuntu<commit_after> #include <libclientserver.h> Notify::Notify() { } Notify::~Notify() { #ifdef DEBUG if (m_map.size() != 0) abort(); //Some things still reference us. This is a bug in the callers code #endif } void Notify::Add(INotify *p) { ScopedLock lock(&m_mutex); #ifdef DEBUG std::map<INotify *, INotify *>::iterator it = m_map.find(p); if (it != m_map.end()) abort(); #endif m_map[p] = p; } void Notify::Remove(INotify *p) { ScopedLock lock(&m_mutex); std::map<INotify *, INotify *>::iterator it = m_map.find(p); if (it == m_map.end()) abort(); //Request to delete an item that does not exist m_map.erase(it); } void Notify::Call(void *d) { ScopedLock lock(&m_mutex); for(std::map<INotify *, INotify *>::iterator it = m_map.begin(); it != m_map.end(); it++) { it->first->Notify(d); } } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: TestRenderWindow.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen 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 notice for more information. =========================================================================*/ #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkSphereSource.h" #include "vtkPolyDataMapper.h" #include "vtkActor.h" #include "vtkUnsignedCharArray.h" #include "vtkFloatArray.h" #include "vtkProperty.h" #include "vtkRegressionTestImage.h" int main( int argc, char *argv[] ) { // Create the renderers, render window, and interactor vtkRenderWindow *renWin = vtkRenderWindow::New(); vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New(); iren->SetRenderWindow(renWin); vtkRenderer *ren = vtkRenderer::New(); renWin->AddRenderer(ren); renWin->SetSize( 200, 200 ); vtkSphereSource *sphereSource = vtkSphereSource::New(); sphereSource->SetThetaResolution(30.0); sphereSource->SetPhiResolution(30.0); vtkPolyDataMapper *mapper = vtkPolyDataMapper::New(); mapper->SetInput( sphereSource->GetOutput() ); vtkActor *actor = vtkActor::New(); actor->SetMapper(mapper); actor->GetProperty()->SetColor(1.0, 0.0, 0.0); ren->AddProp( actor ); renWin->Render(); actor->AddPosition( 0.3, 0.3, 0.0 ); renWin->Render(); vtkUnsignedCharArray *ucCharArray = vtkUnsignedCharArray::New(); renWin->GetPixelData( 0, 0, 199, 199, 1, ucCharArray ); float *fdata = renWin->GetZbufferData( 10, 10, 10, 10 ); delete [] fdata; vtkFloatArray *floatArray = vtkFloatArray::New(); renWin->GetZbufferData( 30, 30, 199, 199, floatArray ); ren->RemoveProp( actor ); renWin->Render(); renWin->Render(); renWin->EraseOff(); renWin->SetZbufferData( 0, 0, 169, 169, floatArray ); ren->AddProp( actor ); actor->GetProperty()->SetColor(1,0,1); renWin->Render(); actor->GetProperty()->SetColor(0,1,0); actor->AddPosition( -0.1, -0.1, 0.0 ); renWin->Render(); renWin->GetRGBAPixelData( 120, 120, 174, 174, 1, floatArray ); renWin->EraseOn(); renWin->Render(); ren->RemoveProp( actor ); renWin->Render(); renWin->SetPixelData( 0, 0, 199, 199, ucCharArray, 1 ); unsigned char *checks = new unsigned char [200*200*3]; int i, j; for ( i = 0; i < 200; i++ ) for ( j = 0; j < 200; j++ ) { checks[i*200*3 + j*3] = 0; checks[i*200*3 + j*3 + 1] = i; checks[i*200*3 + j*3 + 2] = j; } renWin->SetPixelData( 0, 0, 199, 199, checks, 1 ); renWin->SetRGBAPixelData( 0, 0, 54, 54, floatArray, 1, 0 ); renWin->SetRGBAPixelData( 20, 20, 74, 74, floatArray, 1, 0 ); renWin->SetRGBAPixelData( 40, 40, 94, 94, floatArray, 1, 0 ); renWin->SetRGBAPixelData( 60, 60, 114, 114, floatArray, 1, 0 ); fdata = renWin->GetRGBAPixelData( 0, 0, 99, 99, 1 ); renWin->SetRGBAPixelData( 100, 100, 199, 199, fdata, 1, 0 ); renWin->ReleaseRGBAPixelData( fdata ); renWin->SwapBuffersOff(); int retVal = vtkRegressionTestImage( renWin ); // Interact with the data at 3 frames per second iren->SetDesiredUpdateRate(3.0); iren->SetStillUpdateRate(0.001); if ( retVal == vtkRegressionTester::DO_INTERACTOR) { iren->Start(); } sphereSource->Delete(); actor->Delete(); mapper->Delete(); ren->Delete(); renWin->Delete(); iren->Delete(); return !retVal; } <commit_msg>improve coverage<commit_after>/*========================================================================= Program: Visualization Toolkit Module: TestRenderWindow.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen 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 notice for more information. =========================================================================*/ #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkSphereSource.h" #include "vtkPolyDataMapper.h" #include "vtkActor.h" #include "vtkUnsignedCharArray.h" #include "vtkFloatArray.h" #include "vtkProperty.h" #include "vtkRegressionTestImage.h" int main( int argc, char *argv[] ) { // Create the renderers, render window, and interactor vtkRenderWindow *renWin = vtkRenderWindow::New(); vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New(); iren->SetRenderWindow(renWin); vtkRenderer *ren = vtkRenderer::New(); renWin->AddRenderer(ren); renWin->SetSize( 200, 200 ); vtkSphereSource *sphereSource = vtkSphereSource::New(); sphereSource->SetThetaResolution(30.0); sphereSource->SetPhiResolution(30.0); vtkPolyDataMapper *mapper = vtkPolyDataMapper::New(); mapper->SetInput( sphereSource->GetOutput() ); vtkActor *actor = vtkActor::New(); actor->SetMapper(mapper); actor->GetProperty()->SetColor(1.0, 0.0, 0.0); ren->AddProp( actor ); renWin->Render(); actor->AddPosition( 0.3, 0.3, 0.0 ); renWin->Render(); vtkUnsignedCharArray *ucCharArray = vtkUnsignedCharArray::New(); renWin->GetPixelData( 0, 0, 199, 199, 1, ucCharArray ); float *fdata = renWin->GetZbufferData( 10, 10, 10, 10 ); delete [] fdata; vtkFloatArray *floatArray = vtkFloatArray::New(); renWin->GetZbufferData( 30, 30, 199, 199, floatArray ); ren->RemoveProp( actor ); renWin->Render(); renWin->Render(); renWin->EraseOff(); renWin->SetZbufferData( 0, 0, 169, 169, floatArray ); ren->AddProp( actor ); actor->GetProperty()->SetColor(1,0,1); renWin->Render(); actor->GetProperty()->SetColor(0,1,0); actor->AddPosition( -0.1, -0.1, 0.0 ); renWin->Render(); renWin->GetRGBAPixelData( 120, 120, 174, 174, 1, floatArray ); renWin->EraseOn(); renWin->Render(); ren->RemoveProp( actor ); renWin->Render(); renWin->SetPixelData( 0, 0, 199, 199, ucCharArray, 1 ); unsigned char *checks = new unsigned char [200*200*3]; int i, j; for ( i = 0; i < 200; i++ ) for ( j = 0; j < 200; j++ ) { checks[i*200*3 + j*3] = 0; checks[i*200*3 + j*3 + 1] = i; checks[i*200*3 + j*3 + 2] = j; } renWin->SetPixelData( 0, 0, 199, 199, checks, 1 ); renWin->SetRGBAPixelData( 0, 0, 54, 54, floatArray, 1, 0 ); renWin->SetRGBAPixelData( 20, 20, 74, 74, floatArray, 1, 0 ); renWin->SetRGBAPixelData( 40, 40, 94, 94, floatArray, 1, 0 ); renWin->SetRGBAPixelData( 60, 60, 114, 114, floatArray, 1, 0 ); fdata = renWin->GetRGBAPixelData( 0, 0, 99, 99, 1 ); renWin->SetRGBAPixelData( 100, 100, 199, 199, fdata, 1, 0 ); renWin->ReleaseRGBAPixelData( fdata ); vtkUnsignedCharArray *ucArray = vtkUnsignedCharArray::New(); renWin->GetRGBACharPixelData( 20, 150, 40, 170, 1, ucArray ); renWin->SetRGBACharPixelData( 160, 31, 180, 51, ucArray, 1, 0 ); renWin->SwapBuffersOff(); int retVal = vtkRegressionTestImage( renWin ); // Interact with the data at 3 frames per second iren->SetDesiredUpdateRate(3.0); iren->SetStillUpdateRate(0.001); if ( retVal == vtkRegressionTester::DO_INTERACTOR) { iren->Start(); } floatArray->Delete(); ucArray->Delete(); sphereSource->Delete(); actor->Delete(); mapper->Delete(); ren->Delete(); renWin->Delete(); iren->Delete(); return !retVal; } <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include "../compress-stream.hh" namespace mimosa { namespace stream { namespace { TEST(CompressStream, Compress) { } TEST(CompressStream, Decompress) { } } } } <commit_msg>fix include<commit_after>#include <gtest/gtest.h> #include "../compress.hh" namespace mimosa { namespace stream { namespace { TEST(CompressStream, Compress) { } TEST(CompressStream, Decompress) { } } } } <|endoftext|>
<commit_before>// InteractiveNotifications.cpp : Defines the exported functions for the DLL application. // #include "stdafx.h" #include "InteractiveNotifications.h" #include <NotificationActivationCallback.h> #include <Shellapi.h> #include <string> #include <iostream> #include <SDKDDKVer.h> #include <Windows.h> #include <Psapi.h> #include <strsafe.h> #include <ShObjIdl.h> #include <Shlobj.h> #include <Pathcch.h> #include <propvarutil.h> #include <propkey.h> #include <wchar.h> #include <wrl.h> #include <wrl\wrappers\corewrappers.h> #include <windows.ui.notifications.h> // Correct flow // RegisterAppForNotificationSupport() // RegisterActivator() // Name: System.AppUserModel.ToastActivatorCLSID -- PKEY_AppUserModel_ToastActivatorCLSID // Type: Guid -- VT_CLSID // FormatID: {9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3}, 26 // // Used to CoCreate an INotificationActivationCallback interface to notify about toast activations. EXTERN_C const PROPERTYKEY DECLSPEC_SELECTANY PKEY_AppUserModel_ToastActivatorCLSID = { { 0x9F4C2855, 0x9F79, 0x4B39,{ 0xA8, 0xD0, 0xE1, 0xD4, 0x2D, 0xE1, 0xD5, 0xF3 } }, 26 }; using namespace ABI::Windows::Data::Xml::Dom; using namespace ABI::Windows::UI::Notifications; using namespace Microsoft::WRL; using namespace Microsoft::WRL::Wrappers; struct CoTaskMemStringTraits { typedef PWSTR Type; inline static bool Close(_In_ Type h) throw() { ::CoTaskMemFree(h); return true; } inline static Type GetInvalidValue() throw() { return nullptr; } }; typedef HandleT<CoTaskMemStringTraits> CoTaskMemString; const wchar_t Shortcut[] = LR"(Microsoft\Windows\Start Menu\Slack.lnk)"; #define __CSID "B23D2B18-8DD7-403A-B9B7-152B40A1478C" // For the app to be activated from Action Center, it needs to provide a COM server to be called // when the notification is activated. The CLSID of the object needs to be registered with the // OS via its shortcut so that it knows who to call later. class DECLSPEC_UUID(__CSID) NotificationActivator WrlSealed WrlFinal : public RuntimeClass < RuntimeClassFlags<ClassicCom>, INotificationActivationCallback > { public: virtual HRESULT STDMETHODCALLTYPE Activate( _In_ LPCWSTR appUserModelId, _In_ LPCWSTR invokedArgs, _In_reads_(dataCount) const NOTIFICATION_USER_INPUT_DATA* data, ULONG dataCount) override { std::string args; for (int i = 0; i < dataCount; i++) { LPCWSTR lvalue = data[i].Value; LPCWSTR lkey = data[i].Key; std::wstring wvalue(lvalue); std::wstring wkey(lkey); std::string value(wvalue.begin(), wvalue.end()); std::string key(wkey.begin(), wkey.end()); args = args + "\"key\":\"" + key + "\""; args = args + ",\"value\":\"" + value + "\""; } std::wstring wToastArgs(invokedArgs); std::string toastArgs(wToastArgs.begin(), wToastArgs.end()); // If you ever want to use system() or similar calls, // you'll need to escape stuff. We're using ShellExecute, // so we don't have to. // std::string escapedArgs = ""; // for (char ch : args) { // switch (ch) { // case ' ': escapedArgs += "%20"; break; // case '&': escapedArgs += "^&"; break; // case '\\': escapedArgs += "^\\"; break; // case '<': escapedArgs += "^<"; break; // case '>': escapedArgs += "^>"; break; // case '|': escapedArgs += "^|"; break; // case '^': escapedArgs += "^^"; break; // case '"': escapedArgs += "^%22"; break; // default: escapedArgs += ch; break; // } // } // // std::string escapedToastArgs = ""; // for (char ch : toastArgs) { // switch (ch) { // case ' ': escapedToastArgs += "%20"; break; // case '&': escapedToastArgs += "^&"; break; // case '\\': escapedToastArgs += "^\\"; break; // case '<': escapedToastArgs += "^<"; break; // case '>': escapedToastArgs += "^>"; break; // case '|': escapedToastArgs += "^|"; break; // case '^': escapedToastArgs += "^^"; break; // case '"': escapedToastArgs += "%22"; break; // default: escapedToastArgs += ch; break; // } // } // std::string systemCmd = "myapp://" + escapedToastArgs + "^&userData=[{" + escapedArgs + "}]"; std::string cmd = "myapp://" + toastArgs + "&userData=[{" + args + "}]"; std::wstring wCmd = InteractiveNotifications::s2ws(cmd); ShellExecute(NULL, TEXT("open"), wCmd.c_str(), NULL, NULL, SW_SHOWNORMAL); return HRESULT(); } }; CoCreatableClass(NotificationActivator); namespace InteractiveNotifications { INTERACTIVENOTIFICATIONS_API HRESULT RegisterAppForNotificationSupport(PCWSTR shortcut, PCWSTR appId) { CoTaskMemString appData; auto hr = ::SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, appData.GetAddressOf()); if (SUCCEEDED(hr)) { wchar_t shortcutPath[MAX_PATH]; // Todo: Don't hardcode the path hr = ::PathCchCombine(shortcutPath, ARRAYSIZE(shortcutPath), appData.Get(), shortcut); if (SUCCEEDED(hr)) { DWORD attributes = ::GetFileAttributes(shortcutPath); bool fileExists = attributes < 0xFFFFFFF; if (!fileExists) { // Todo: This is probably the wrong path bc Squirrel wchar_t exePath[MAX_PATH]; DWORD charWritten = ::GetModuleFileName(nullptr, exePath, ARRAYSIZE(exePath)); hr = charWritten > 0 ? S_OK : HRESULT_FROM_WIN32(::GetLastError()); if (SUCCEEDED(hr)) { hr = InstallShortcut(shortcutPath, exePath, appId); if (SUCCEEDED(hr)) { hr = RegisterComServer(exePath); } } } } } return hr; } _Use_decl_annotations_ INTERACTIVENOTIFICATIONS_API HRESULT InstallShortcut(PCWSTR shortcutPath, PCWSTR exePath, PCWSTR appId) { ComPtr<IShellLink> shellLink; HRESULT hr = CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&shellLink)); if (!SUCCEEDED(hr)) return hr; hr = shellLink->SetPath(exePath); if (!SUCCEEDED(hr)) return hr; ComPtr<IPropertyStore> propertyStore; hr = shellLink.As(&propertyStore); if (!SUCCEEDED(hr)) return hr; PROPVARIANT propVar; propVar.vt = VT_LPWSTR; propVar.pwszVal = const_cast<PWSTR>(appId); // for _In_ scenarios, we don't need a copy hr = propertyStore->SetValue(PKEY_AppUserModel_ID, propVar); if (!SUCCEEDED(hr)) return hr; propVar.vt = VT_CLSID; propVar.puuid = const_cast<CLSID*>(&__uuidof(NotificationActivator)); hr = propertyStore->SetValue(PKEY_AppUserModel_ToastActivatorCLSID, propVar); if (!SUCCEEDED(hr)) return hr; hr = propertyStore->Commit(); if (!SUCCEEDED(hr)) return hr; ComPtr<IPersistFile> persistFile; hr = shellLink.As(&persistFile); if (!SUCCEEDED(hr)) return hr; hr = persistFile->Save(shortcutPath, TRUE); return hr; } _Use_decl_annotations_ INTERACTIVENOTIFICATIONS_API HRESULT RegisterComServer(PCWSTR exePath) { // We don't need to worry about overflow here as ::GetModuleFileName won't // return anything bigger than the max file system path (much fewer than max of DWORD). DWORD dataSize = static_cast<DWORD>((::wcslen(exePath) + 1) * sizeof(WCHAR)); auto key = LR"(SOFTWARE\Classes\CLSID\{B23D2B18-8DD7-403A-B9B7-152B40A1478C}\LocalServer32)"; return HRESULT_FROM_WIN32(::RegSetKeyValue( HKEY_CURRENT_USER, key, nullptr, REG_SZ, reinterpret_cast<const BYTE*>(exePath), dataSize)); } _Use_decl_annotations_ INTERACTIVENOTIFICATIONS_API HRESULT RegisterActivator() { // Module<OutOfProc> needs a callback registered before it can be used. // Since we don't care about when it shuts down, we'll pass an empty lambda here. // If we need to clean up, do it here (we probably don't have to) Module<OutOfProc>::Create([] {}); // If a local server process only hosts the COM object then COM expects // the COM server host to shutdown when the references drop to zero. // Since the user might still be using the program after activating the notification, // we don't want to shutdown immediately. Incrementing the object count tells COM that // we aren't done yet. Module<OutOfProc>::GetModule().IncrementObjectCount(); return Module<OutOfProc>::GetModule().RegisterObjects(); } _Use_decl_annotations_ INTERACTIVENOTIFICATIONS_API void UnregisterActivator() { Module<OutOfProc>::GetModule().UnregisterObjects(); Module<OutOfProc>::GetModule().DecrementObjectCount(); } INTERACTIVENOTIFICATIONS_API std::wstring s2ws(const std::string& s) { int len; int slength = (int)s.length() + 1; len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0); wchar_t* buf = new wchar_t[len]; MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len); std::wstring r(buf); delete[] buf; return r; } } extern "C" { __declspec(dllexport) void CRegisterForNotificationSupport(PCWSTR shortcut, PCWSTR appId) { InteractiveNotifications::RegisterAppForNotificationSupport(shortcut, appId); } __declspec(dllexport) void CRegisterActivator() { InteractiveNotifications::RegisterActivator(); } __declspec(dllexport) void CUnregisterActivator() { InteractiveNotifications::UnregisterActivator(); } }<commit_msg>:art: Unicode Support!<commit_after>// InteractiveNotifications.cpp : Defines the exported functions for the DLL application. // #include "stdafx.h" #include "InteractiveNotifications.h" #include <NotificationActivationCallback.h> #include <Shellapi.h> #include <string> #include <iostream> #include <SDKDDKVer.h> #include <Windows.h> #include <Psapi.h> #include <strsafe.h> #include <ShObjIdl.h> #include <Shlobj.h> #include <Pathcch.h> #include <propvarutil.h> #include <propkey.h> #include <wchar.h> #include <wrl.h> #include <wrl\wrappers\corewrappers.h> #include <windows.ui.notifications.h> // Correct flow // RegisterAppForNotificationSupport() // RegisterActivator() // Name: System.AppUserModel.ToastActivatorCLSID -- PKEY_AppUserModel_ToastActivatorCLSID // Type: Guid -- VT_CLSID // FormatID: {9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3}, 26 // // Used to CoCreate an INotificationActivationCallback interface to notify about toast activations. EXTERN_C const PROPERTYKEY DECLSPEC_SELECTANY PKEY_AppUserModel_ToastActivatorCLSID = { { 0x9F4C2855, 0x9F79, 0x4B39,{ 0xA8, 0xD0, 0xE1, 0xD4, 0x2D, 0xE1, 0xD5, 0xF3 } }, 26 }; using namespace ABI::Windows::Data::Xml::Dom; using namespace ABI::Windows::UI::Notifications; using namespace Microsoft::WRL; using namespace Microsoft::WRL::Wrappers; struct CoTaskMemStringTraits { typedef PWSTR Type; inline static bool Close(_In_ Type h) throw() { ::CoTaskMemFree(h); return true; } inline static Type GetInvalidValue() throw() { return nullptr; } }; typedef HandleT<CoTaskMemStringTraits> CoTaskMemString; const wchar_t Shortcut[] = LR"(Microsoft\Windows\Start Menu\Slack.lnk)"; #define __CSID "B23D2B18-8DD7-403A-B9B7-152B40A1478C" // For the app to be activated from Action Center, it needs to provide a COM server to be called // when the notification is activated. The CLSID of the object needs to be registered with the // OS via its shortcut so that it knows who to call later. class DECLSPEC_UUID(__CSID) NotificationActivator WrlSealed WrlFinal : public RuntimeClass < RuntimeClassFlags<ClassicCom>, INotificationActivationCallback > { public: virtual HRESULT STDMETHODCALLTYPE Activate( _In_ LPCWSTR appUserModelId, _In_ LPCWSTR invokedArgs, _In_reads_(dataCount) const NOTIFICATION_USER_INPUT_DATA* data, ULONG dataCount) override { std::string args; for (int i = 0; i < dataCount; i++) { LPCWSTR lvalue = data[i].Value; LPCWSTR lkey = data[i].Key; std::wstring wvalue(lvalue); std::wstring wkey(lkey); std::string value(wvalue.begin(), wvalue.end()); std::string key(wkey.begin(), wkey.end()); args = args + "\"key\":\"" + key + "\""; args = args + ",\"value\":\"" + value + "\""; } std::wstring wToastArgs(invokedArgs); std::string toastArgs(wToastArgs.begin(), wToastArgs.end()); // If you ever want to use system() or similar calls, // you'll need to escape stuff. We're using ShellExecute, // so we don't have to. // std::string escapedArgs = ""; // for (char ch : args) { // switch (ch) { // case ' ': escapedArgs += "%20"; break; // case '&': escapedArgs += "^&"; break; // case '\\': escapedArgs += "^\\"; break; // case '<': escapedArgs += "^<"; break; // case '>': escapedArgs += "^>"; break; // case '|': escapedArgs += "^|"; break; // case '^': escapedArgs += "^^"; break; // case '"': escapedArgs += "^%22"; break; // default: escapedArgs += ch; break; // } // } // // std::string escapedToastArgs = ""; // for (char ch : toastArgs) { // switch (ch) { // case ' ': escapedToastArgs += "%20"; break; // case '&': escapedToastArgs += "^&"; break; // case '\\': escapedToastArgs += "^\\"; break; // case '<': escapedToastArgs += "^<"; break; // case '>': escapedToastArgs += "^>"; break; // case '|': escapedToastArgs += "^|"; break; // case '^': escapedToastArgs += "^^"; break; // case '"': escapedToastArgs += "%22"; break; // default: escapedToastArgs += ch; break; // } // } // std::string systemCmd = "myapp://" + escapedToastArgs + "^&userData=[{" + escapedArgs + "}]"; std::string escapedToastArgs = ""; for (char ch : toastArgs) { switch (ch) { case ' ': escapedToastArgs += "%20"; break; case '"': escapedToastArgs += "%22"; break; default: escapedToastArgs += ch; break; } } std::string escapedArgs = ""; for (char ch : args) { switch (ch) { case ' ': escapedArgs += "%20"; break; case '"': escapedArgs += "%22"; break; default: escapedArgs += ch; break; } } std::string cmd = "myapp://" + escapedToastArgs + "&userData=[{" + escapedArgs + "}]"; std::wstring wCmd = InteractiveNotifications::s2ws(cmd); ShellExecuteW(NULL, TEXT("open"), wCmd.c_str(), NULL, NULL, SW_SHOWNORMAL); return HRESULT(); } }; CoCreatableClass(NotificationActivator); namespace InteractiveNotifications { INTERACTIVENOTIFICATIONS_API HRESULT RegisterAppForNotificationSupport(PCWSTR shortcut, PCWSTR appId) { CoTaskMemString appData; auto hr = ::SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, appData.GetAddressOf()); if (SUCCEEDED(hr)) { wchar_t shortcutPath[MAX_PATH]; // Todo: Don't hardcode the path hr = ::PathCchCombine(shortcutPath, ARRAYSIZE(shortcutPath), appData.Get(), shortcut); if (SUCCEEDED(hr)) { DWORD attributes = ::GetFileAttributes(shortcutPath); bool fileExists = attributes < 0xFFFFFFF; if (!fileExists) { // Todo: This is probably the wrong path bc Squirrel wchar_t exePath[MAX_PATH]; DWORD charWritten = ::GetModuleFileName(nullptr, exePath, ARRAYSIZE(exePath)); hr = charWritten > 0 ? S_OK : HRESULT_FROM_WIN32(::GetLastError()); if (SUCCEEDED(hr)) { hr = InstallShortcut(shortcutPath, exePath, appId); if (SUCCEEDED(hr)) { hr = RegisterComServer(exePath); } } } } } return hr; } _Use_decl_annotations_ INTERACTIVENOTIFICATIONS_API HRESULT InstallShortcut(PCWSTR shortcutPath, PCWSTR exePath, PCWSTR appId) { ComPtr<IShellLink> shellLink; HRESULT hr = CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&shellLink)); if (!SUCCEEDED(hr)) return hr; hr = shellLink->SetPath(exePath); if (!SUCCEEDED(hr)) return hr; ComPtr<IPropertyStore> propertyStore; hr = shellLink.As(&propertyStore); if (!SUCCEEDED(hr)) return hr; PROPVARIANT propVar; propVar.vt = VT_LPWSTR; propVar.pwszVal = const_cast<PWSTR>(appId); // for _In_ scenarios, we don't need a copy hr = propertyStore->SetValue(PKEY_AppUserModel_ID, propVar); if (!SUCCEEDED(hr)) return hr; propVar.vt = VT_CLSID; propVar.puuid = const_cast<CLSID*>(&__uuidof(NotificationActivator)); hr = propertyStore->SetValue(PKEY_AppUserModel_ToastActivatorCLSID, propVar); if (!SUCCEEDED(hr)) return hr; hr = propertyStore->Commit(); if (!SUCCEEDED(hr)) return hr; ComPtr<IPersistFile> persistFile; hr = shellLink.As(&persistFile); if (!SUCCEEDED(hr)) return hr; hr = persistFile->Save(shortcutPath, TRUE); return hr; } _Use_decl_annotations_ INTERACTIVENOTIFICATIONS_API HRESULT RegisterComServer(PCWSTR exePath) { // We don't need to worry about overflow here as ::GetModuleFileName won't // return anything bigger than the max file system path (much fewer than max of DWORD). DWORD dataSize = static_cast<DWORD>((::wcslen(exePath) + 1) * sizeof(WCHAR)); auto key = LR"(SOFTWARE\Classes\CLSID\{B23D2B18-8DD7-403A-B9B7-152B40A1478C}\LocalServer32)"; return HRESULT_FROM_WIN32(::RegSetKeyValue( HKEY_CURRENT_USER, key, nullptr, REG_SZ, reinterpret_cast<const BYTE*>(exePath), dataSize)); } _Use_decl_annotations_ INTERACTIVENOTIFICATIONS_API HRESULT RegisterActivator() { // Module<OutOfProc> needs a callback registered before it can be used. // Since we don't care about when it shuts down, we'll pass an empty lambda here. // If we need to clean up, do it here (we probably don't have to) Module<OutOfProc>::Create([] {}); // If a local server process only hosts the COM object then COM expects // the COM server host to shutdown when the references drop to zero. // Since the user might still be using the program after activating the notification, // we don't want to shutdown immediately. Incrementing the object count tells COM that // we aren't done yet. Module<OutOfProc>::GetModule().IncrementObjectCount(); return Module<OutOfProc>::GetModule().RegisterObjects(); } _Use_decl_annotations_ INTERACTIVENOTIFICATIONS_API void UnregisterActivator() { Module<OutOfProc>::GetModule().UnregisterObjects(); Module<OutOfProc>::GetModule().DecrementObjectCount(); } INTERACTIVENOTIFICATIONS_API std::wstring s2ws(const std::string& s) { int len; int slength = (int)s.length() + 1; len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0); wchar_t* buf = new wchar_t[len]; MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len); std::wstring r(buf); delete[] buf; return r; } } extern "C" { __declspec(dllexport) void CRegisterForNotificationSupport(PCWSTR shortcut, PCWSTR appId) { InteractiveNotifications::RegisterAppForNotificationSupport(shortcut, appId); } __declspec(dllexport) void CRegisterActivator() { InteractiveNotifications::RegisterActivator(); } __declspec(dllexport) void CUnregisterActivator() { InteractiveNotifications::UnregisterActivator(); } }<|endoftext|>
<commit_before>/** ========================================================================== * 2011 by KjellKod.cc. This is PUBLIC DOMAIN to use at your own risk and comes * with no warranties. This code is yours to share, use and modify with no * strings attached and no restrictions or obligations. * ============================================================================*/ #include "crashhandler.hpp" #include "g2logmessage.hpp" #include "g2LogMessageBuilder.hpp" #include <csignal> #include <cstring> #if (defined(WIN32) || defined(_WIN32) || defined(__WIN32__) && !defined(__GNUC__)) // windows and not mingw #error "crashhandler_unix.cpp used but it's a windows system" #endif #include <unistd.h> // getpid, #include <execinfo.h> #include <ucontext.h> #include <cxxabi.h> #include <cstdlib> #include <sstream> #include <iostream> namespace { // Dump of stack,. then exit through g2log background worker // ALL thanks to this thread at StackOverflow. Pretty much borrowed from: // Ref: http://stackoverflow.com/questions/77005/how-to-generate-a-stacktrace-when-my-gcc-c-app-crashes void crashHandler(int signal_number, siginfo_t *info, void *unused_context) { using namespace g2::internal; std::ostringstream oss; oss << "Received fatal signal: " << g2::internal::signalName(signal_number); oss << "(" << signal_number << ")\tPID: " << getpid() << std::endl; oss << stackdump(); { // Local scope, trigger send std::ostringstream fatal_stream; fatal_stream << oss.str() << std::endl; fatal_stream << "\n***** SIGNAL " << signalName(signal_number) << "(" << signal_number << ")" << std::endl; g2::FatalMessageBuilder trigger(fatal_stream.str(), signal_number); } // message sent to g2LogWorker by FatalMessageBuilder // wait to die -- will be inside the FatalMessageBuilder } } // end anonymous namespace // Redirecting and using signals. In case of fatal signals g2log should log the fatal signal // and flush the log queue and then "rethrow" the signal to exit namespace g2 { // References: // sigaction : change the default action if a specific signal is received // http://linux.die.net/man/2/sigaction // http://publib.boulder.ibm.com/infocenter/aix/v6r1/index.jsp?topic=%2Fcom.ibm.aix.basetechref%2Fdoc%2Fbasetrf2%2Fsigaction.html // // signal: http://linux.die.net/man/7/signal and // http://msdn.microsoft.com/en-us/library/xdkz3x12%28vs.71%29.asp // // memset + sigemptyset: Maybe unnecessary to do both but there seems to be some confusion here // ,plenty of examples when both or either are used // http://stackoverflow.com/questions/6878546/why-doesnt-parent-process-return-to-the-exact-location-after-handling-signal_number namespace internal { std::string stackdump() { const size_t max_dump_size = 50; void* dump[max_dump_size]; size_t size = backtrace(dump, max_dump_size); char** messages = backtrace_symbols(dump, size); // overwrite sigaction with caller's address // dump stack: skip first frame, since that is here std::ostringstream oss; for (size_t idx = 1; idx < size && messages != nullptr; ++idx) { char *mangled_name = 0, *offset_begin = 0, *offset_end = 0; // find parantheses and +address offset surrounding mangled name for (char *p = messages[idx]; *p; ++p) { if (*p == '(') { mangled_name = p; } else if (*p == '+') { offset_begin = p; } else if (*p == ')') { offset_end = p; break; } } // if the line could be processed, attempt to demangle the symbol if (mangled_name && offset_begin && offset_end && mangled_name < offset_begin) { *mangled_name++ = '\0'; *offset_begin++ = '\0'; *offset_end++ = '\0'; int status; char * real_name = abi::__cxa_demangle(mangled_name, 0, 0, &status); // if demangling is successful, output the demangled function name if (status == 0) { oss << "\n\tstack dump [" << idx << "] " << messages[idx] << " : " << real_name << "+"; oss << offset_begin << offset_end << std::endl; }// otherwise, output the mangled function name else { oss << "\tstack dump [" << idx << "] " << messages[idx] << mangled_name << "+"; oss << offset_begin << offset_end << std::endl; } free(real_name); // mallocated by abi::__cxa_demangle(...) } else { // no demangling done -- just dump the whole line oss << "\tstack dump [" << idx << "] " << messages[idx] << std::endl; } } // END: for(size_t idx = 1; idx < size && messages != nullptr; ++idx) free(messages); return oss.str(); } std::string signalName(int signal_number) { switch (signal_number) { case SIGABRT: return "SIGABRT"; break; case SIGFPE: return "SIGFPE"; break; case SIGSEGV: return "SIGSEGV"; break; case SIGILL: return "SIGILL"; break; case SIGTERM: return "SIGTERM"; break; default: std::ostringstream oss; oss << "UNKNOWN SIGNAL(" << signal_number << ")"; return oss.str(); } } // Triggered by g2log->g2LogWorker after receiving a FATAL trigger // which is LOG(FATAL), CHECK(false) or a fatal signal our signalhandler caught. // --- If LOG(FATAL) or CHECK(false) the signal_number will be SIGABRT void exitWithDefaultSignalHandler(int signal_number) { std::cerr << "Exiting - FATAL SIGNAL: " << signal_number << " " << std::flush; struct sigaction action; memset(&action, 0, sizeof (action)); // sigemptyset(&action.sa_mask); action.sa_handler = SIG_DFL; // take default action for the signal sigaction(signal_number, &action, NULL); kill(getpid(), signal_number); abort(); // should never reach this } } // end g2::internal void installSignalHandler() { struct sigaction action; memset(&action, 0, sizeof (action)); sigemptyset(&action.sa_mask); action.sa_sigaction = &crashHandler; // callback to crashHandler for fatal signals // sigaction to use sa_sigaction file. ref: http://www.linuxprogrammingblog.com/code-examples/sigaction action.sa_flags = SA_SIGINFO; // do it verbose style - install all signal actions if (sigaction(SIGABRT, &action, NULL) < 0) perror("sigaction - SIGABRT"); if (sigaction(SIGFPE, &action, NULL) < 0) perror("sigaction - SIGFPE"); if (sigaction(SIGILL, &action, NULL) < 0) perror("sigaction - SIGILL"); if (sigaction(SIGSEGV, &action, NULL) < 0) perror("sigaction - SIGSEGV"); if (sigaction(SIGTERM, &action, NULL) < 0) perror("sigaction - SIGTERM"); } } // end namespace g2 <commit_msg>crashhandler_unix now with support for OSX/Clang<commit_after>/** ========================================================================== * 2011 by KjellKod.cc. This is PUBLIC DOMAIN to use at your own risk and comes * with no warranties. This code is yours to share, use and modify with no * strings attached and no restrictions or obligations. * ============================================================================*/ #include "crashhandler.hpp" #include "g2logmessage.hpp" #include "g2LogMessageBuilder.hpp" #include <csignal> #include <cstring> #if (defined(WIN32) || defined(_WIN32) || defined(__WIN32__) && !defined(__GNUC__)) // windows and not mingw #error "crashhandler_unix.cpp used but it's a windows system" #endif #include <unistd.h> #include <execinfo.h> #include <cxxabi.h> #include <cstdlib> #include <sstream> #include <iostream> #ifdef __clang__ #include <sys/ucontext.h> #else #include <ucontext.h> #endif namespace { // Dump of stack,. then exit through g2log background worker // ALL thanks to this thread at StackOverflow. Pretty much borrowed from: // Ref: http://stackoverflow.com/questions/77005/how-to-generate-a-stacktrace-when-my-gcc-c-app-crashes void crashHandler(int signal_number, siginfo_t *info, void *unused_context) { using namespace g2::internal; std::ostringstream oss; oss << "Received fatal signal: " << g2::internal::signalName(signal_number); oss << "(" << signal_number << ")\tPID: " << getpid() << std::endl; oss << stackdump(); { // Local scope, trigger send std::ostringstream fatal_stream; fatal_stream << oss.str() << std::endl; fatal_stream << "\n***** SIGNAL " << signalName(signal_number) << "(" << signal_number << ")" << std::endl; g2::FatalMessageBuilder trigger(fatal_stream.str(), signal_number); } // message sent to g2LogWorker by FatalMessageBuilder // wait to die -- will be inside the FatalMessageBuilder } } // end anonymous namespace // Redirecting and using signals. In case of fatal signals g2log should log the fatal signal // and flush the log queue and then "rethrow" the signal to exit namespace g2 { // References: // sigaction : change the default action if a specific signal is received // http://linux.die.net/man/2/sigaction // http://publib.boulder.ibm.com/infocenter/aix/v6r1/index.jsp?topic=%2Fcom.ibm.aix.basetechref%2Fdoc%2Fbasetrf2%2Fsigaction.html // // signal: http://linux.die.net/man/7/signal and // http://msdn.microsoft.com/en-us/library/xdkz3x12%28vs.71%29.asp // // memset + sigemptyset: Maybe unnecessary to do both but there seems to be some confusion here // ,plenty of examples when both or either are used // http://stackoverflow.com/questions/6878546/why-doesnt-parent-process-return-to-the-exact-location-after-handling-signal_number namespace internal { std::string stackdump() { const size_t max_dump_size = 50; void* dump[max_dump_size]; size_t size = backtrace(dump, max_dump_size); char** messages = backtrace_symbols(dump, size); // overwrite sigaction with caller's address // dump stack: skip first frame, since that is here std::ostringstream oss; for (size_t idx = 1; idx < size && messages != nullptr; ++idx) { char *mangled_name = 0, *offset_begin = 0, *offset_end = 0; // find parantheses and +address offset surrounding mangled name for (char *p = messages[idx]; *p; ++p) { if (*p == '(') { mangled_name = p; } else if (*p == '+') { offset_begin = p; } else if (*p == ')') { offset_end = p; break; } } // if the line could be processed, attempt to demangle the symbol if (mangled_name && offset_begin && offset_end && mangled_name < offset_begin) { *mangled_name++ = '\0'; *offset_begin++ = '\0'; *offset_end++ = '\0'; int status; char * real_name = abi::__cxa_demangle(mangled_name, 0, 0, &status); // if demangling is successful, output the demangled function name if (status == 0) { oss << "\n\tstack dump [" << idx << "] " << messages[idx] << " : " << real_name << "+"; oss << offset_begin << offset_end << std::endl; }// otherwise, output the mangled function name else { oss << "\tstack dump [" << idx << "] " << messages[idx] << mangled_name << "+"; oss << offset_begin << offset_end << std::endl; } free(real_name); // mallocated by abi::__cxa_demangle(...) } else { // no demangling done -- just dump the whole line oss << "\tstack dump [" << idx << "] " << messages[idx] << std::endl; } } // END: for(size_t idx = 1; idx < size && messages != nullptr; ++idx) free(messages); return oss.str(); } std::string signalName(int signal_number) { switch (signal_number) { case SIGABRT: return "SIGABRT"; break; case SIGFPE: return "SIGFPE"; break; case SIGSEGV: return "SIGSEGV"; break; case SIGILL: return "SIGILL"; break; case SIGTERM: return "SIGTERM"; break; default: std::ostringstream oss; oss << "UNKNOWN SIGNAL(" << signal_number << ")"; return oss.str(); } } // Triggered by g2log->g2LogWorker after receiving a FATAL trigger // which is LOG(FATAL), CHECK(false) or a fatal signal our signalhandler caught. // --- If LOG(FATAL) or CHECK(false) the signal_number will be SIGABRT void exitWithDefaultSignalHandler(int signal_number) { std::cerr << "Exiting - FATAL SIGNAL: " << signal_number << " " << std::flush; struct sigaction action; memset(&action, 0, sizeof (action)); // sigemptyset(&action.sa_mask); action.sa_handler = SIG_DFL; // take default action for the signal sigaction(signal_number, &action, NULL); kill(getpid(), signal_number); abort(); // should never reach this } } // end g2::internal void installSignalHandler() { struct sigaction action; memset(&action, 0, sizeof (action)); sigemptyset(&action.sa_mask); action.sa_sigaction = &crashHandler; // callback to crashHandler for fatal signals // sigaction to use sa_sigaction file. ref: http://www.linuxprogrammingblog.com/code-examples/sigaction action.sa_flags = SA_SIGINFO; // do it verbose style - install all signal actions if (sigaction(SIGABRT, &action, NULL) < 0) perror("sigaction - SIGABRT"); if (sigaction(SIGFPE, &action, NULL) < 0) perror("sigaction - SIGFPE"); if (sigaction(SIGILL, &action, NULL) < 0) perror("sigaction - SIGILL"); if (sigaction(SIGSEGV, &action, NULL) < 0) perror("sigaction - SIGSEGV"); if (sigaction(SIGTERM, &action, NULL) < 0) perror("sigaction - SIGTERM"); } } // end namespace g2 <|endoftext|>
<commit_before>/* This file is part of KDE Kontact. Copyright (C) 2003 Cornelius Schumacher <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <qptrlist.h> #include <qwidgetstack.h> #include <qsignal.h> #include <qobjectlist.h> #include <qlabel.h> #include <qpainter.h> #include <qbitmap.h> #include <qfontmetrics.h> #include <qsignalmapper.h> #include <qstyle.h> #include <qframe.h> #include <qdrawutil.h> #include <kpopupmenu.h> #include <kapplication.h> #include <klocale.h> #include <kiconloader.h> #include <sidebarextension.h> #include <kdebug.h> #include "mainwindow.h" #include "plugin.h" #include "prefs.h" #include "iconsidepane.h" namespace Kontact { //ugly wrapper class for adding an operator< to the Plugin class class PluginProxy { public: PluginProxy() : m_plugin( 0 ) { } PluginProxy( Plugin * plugin ) : m_plugin( plugin ) { } PluginProxy & operator=( Plugin * plugin ) { m_plugin = plugin; return *this; } bool operator<( PluginProxy & rhs ) const { return m_plugin->weight() < rhs.m_plugin->weight(); } Plugin * plugin() const { return m_plugin; } private: Plugin * m_plugin; }; } //namespace using namespace Kontact; EntryItem::EntryItem( Navigator *parent, Kontact::Plugin *plugin ) : QListBoxItem( parent ), mPlugin( plugin ) { reloadPixmap(); setCustomHighlighting( true ); setText( plugin->title() ); } EntryItem::~EntryItem() { } void EntryItem::reloadPixmap() { int size = (int)navigator()->viewMode(); if (size != 0) mPixmap = KGlobal::iconLoader()->loadIcon( mPlugin->icon(), KIcon::Desktop, size ); else mPixmap = QPixmap(); } Navigator* EntryItem::navigator() const { return static_cast<Navigator*>(listBox()); } int EntryItem::width( const QListBox *listbox) const { int w; if ( text().isEmpty() ) w = mPixmap.width(); else w = QMAX( (int)navigator()->viewMode(), listbox->fontMetrics().width( text() ) ); return w + 36; } int EntryItem::height( const QListBox *listbox) const { int h; if ( text().isEmpty() ) h = mPixmap.height(); else h = (int)navigator()->viewMode() + listbox->fontMetrics().lineSpacing(); return h + 4; } void EntryItem::paint( QPainter *p ) { reloadPixmap(); QListBox *box = listBox(); int w = box->viewport()->width(); int y = 2; if ( !mPixmap.isNull() ) { int x = ( w - mPixmap.width() ) / 2; p->drawPixmap( x, y, mPixmap ); } QColor save; if ( isCurrent() || isSelected() ) { save = p->pen().color(); p->setPen(listBox()->colorGroup().brightText()); } if ( !text().isEmpty() ) { QFontMetrics fm = p->fontMetrics(); y += mPixmap.height() + fm.height() - fm.descent(); int x = ( w - fm.width( text() ) ) / 2; p->drawText( x, y, text() ); } // draw sunken if ( isCurrent() || isSelected() ) { p->setPen(save); QColorGroup group = box->colorGroup(); group.setColor( QColorGroup::Dark, Qt::black ); qDrawShadePanel( p, 1, 0, w - 2, height( box ), group, true, 1, 0 ); } } Navigator::Navigator( SidePaneBase *parent, const char *name) : KListBox( parent, name ), mSidePane( parent ) { mViewMode = sizeIntToEnum( Prefs::self()->sidePaneIconSize() ); setSelectionMode( KListBox::Single ); viewport()->setBackgroundMode( PaletteMid ); setHScrollBarMode( QScrollView::AlwaysOff ); setAcceptDrops( true ); connect( this, SIGNAL( selectionChanged( QListBoxItem * ) ), SLOT( slotExecuted( QListBoxItem * ) ) ); connect( this, SIGNAL( rightButtonPressed( QListBoxItem *, const QPoint& ) ), SLOT( slotShowRMBMenu( QListBoxItem *, const QPoint& ) ) ); mMapper = new QSignalMapper( this ); connect( mMapper, SIGNAL( mapped( int ) ), SLOT( shortCutSelected( int ) ) ); } QSize Navigator::sizeHint() const { return QSize( 100, 100 ); } void Navigator::setSelected( QListBoxItem *i, bool sel ) { // Reimplemented to avoid the immediate activation of // the item. might turn out it doesn't work, we check that // an confirm from MainWindow::selectPlugin() if (sel) { EntryItem *entry = static_cast<EntryItem *>( i ); emit pluginActivated( entry->plugin() ); } } void Navigator::updatePlugins( QValueList<Kontact::Plugin*> plugins_ ) { QValueList<Kontact::PluginProxy> plugins; QValueList<Kontact::Plugin*>::ConstIterator end_ = plugins_.end(); QValueList<Kontact::Plugin*>::ConstIterator it_ = plugins_.begin(); for ( ; it_ != end_; ++it_ ) plugins += PluginProxy( *it_ ); clear(); mActions.setAutoDelete( true ); mActions.clear(); mActions.setAutoDelete( false ); int counter = 0; int minWidth = 0; qBubbleSort( plugins ); QValueList<Kontact::PluginProxy>::ConstIterator end = plugins.end(); QValueList<Kontact::PluginProxy>::ConstIterator it = plugins.begin(); for ( ; it != end; ++it ) { Kontact::Plugin *plugin = ( *it ).plugin(); if ( !plugin->showInSideBar() ) continue; EntryItem *item = new EntryItem( this, plugin ); if ( item->width( this ) > minWidth ) minWidth = item->width( this ); QString name = QString( "CTRL+%1" ).arg( counter + 1 ); KAction *action = new KAction( plugin->title(), KShortcut( name ), mMapper, SLOT( map() ), mSidePane->actionCollection(), name.latin1() ); mMapper->setMapping( action, counter ); counter++; } parentWidget()->setFixedWidth( minWidth ); } void Navigator::dragEnterEvent( QDragEnterEvent *event ) { kdDebug(5600) << "Navigator::dragEnterEvent()" << endl; dragMoveEvent( event ); } void Navigator::dragMoveEvent( QDragMoveEvent *event ) { kdDebug(5600) << "Navigator::dragEnterEvent()" << endl; kdDebug(5600) << " Format: " << event->format() << endl; QListBoxItem *item = itemAt( event->pos() ); if ( !item ) { event->accept( false ); return; } EntryItem *entry = static_cast<EntryItem *>( item ); kdDebug(5600) << " PLUGIN: " << entry->plugin()->identifier() << endl; event->accept( entry->plugin()->canDecodeDrag( event ) ); } void Navigator::dropEvent( QDropEvent *event ) { kdDebug(5600) << "Navigator::dropEvent()" << endl; QListBoxItem *item = itemAt( event->pos() ); if ( !item ) { return; } EntryItem *entry = static_cast<EntryItem *>( item ); kdDebug(5600) << " PLUGIN: " << entry->plugin()->identifier() << endl; entry->plugin()->processDropEvent( event ); } void Navigator::resizeEvent( QResizeEvent *event ) { QListBox::resizeEvent( event ); triggerUpdate( true ); } void Navigator::slotExecuted( QListBoxItem *item ) { if ( !item ) return; EntryItem *entry = static_cast<EntryItem *>( item ); emit pluginActivated( entry->plugin() ); } IconViewMode Navigator::sizeIntToEnum(int size) const { switch ( size ) { case int(LargeIcons): return LargeIcons; break; case int(NormalIcons): return NormalIcons; break; case int(SmallIcons): return SmallIcons; break; case int(TextOnly): return TextOnly; break; default: // Stick with sane values return NormalIcons; kdDebug() << "View mode not implemented!" << endl; break; } } void Navigator::slotShowRMBMenu( QListBoxItem *, const QPoint& pos ) { KPopupMenu menu; menu.insertTitle( i18n("Icon Size") ); menu.insertItem( i18n("Large"), (int)LargeIcons ); menu.insertItem( i18n("Nomal "), (int)NormalIcons ); menu.insertItem( i18n("Small"), (int)SmallIcons ); menu.insertItem( i18n("Text Only"), (int)TextOnly ); int choice = menu.exec( pos ); mViewMode = sizeIntToEnum(choice); Prefs::self()->setSidePaneIconSize( choice ); triggerUpdate( true ); } void Navigator::shortCutSelected( int pos ) { setCurrentItem( pos ); } IconSidePane::IconSidePane( Core *core, QWidget *parent, const char *name ) : SidePaneBase( core, parent, name ) { mNavigator = new Navigator( this ); connect( mNavigator, SIGNAL( pluginActivated( Kontact::Plugin * ) ), SIGNAL( pluginSelected( Kontact::Plugin * ) ) ); setAcceptDrops( true ); } IconSidePane::~IconSidePane() { } void IconSidePane::updatePlugins() { mNavigator->updatePlugins( core()->pluginList() ); } void IconSidePane::selectPlugin( Kontact::Plugin *plugin ) { bool blocked = signalsBlocked(); blockSignals( true ); uint i; for ( i = 0; i < mNavigator->count(); ++i ) { EntryItem *item = static_cast<EntryItem *>( mNavigator->item( i ) ); if ( item->plugin() == plugin ) { mNavigator->setCurrentItem( i ); break; } } blockSignals( blocked ); } void IconSidePane::selectPlugin( const QString &name ) { bool blocked = signalsBlocked(); blockSignals( true ); uint i; for ( i = 0; i < mNavigator->count(); ++i ) { EntryItem *item = static_cast<EntryItem *>( mNavigator->item( i ) ); if ( item->plugin()->identifier() == name ) { mNavigator->setCurrentItem( i ); break; } } blockSignals( blocked ); } #include "iconsidepane.moc" // vim: sw=2 sts=2 et tw=80 <commit_msg>CVS_SILENT typo<commit_after>/* This file is part of KDE Kontact. Copyright (C) 2003 Cornelius Schumacher <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <qptrlist.h> #include <qwidgetstack.h> #include <qsignal.h> #include <qobjectlist.h> #include <qlabel.h> #include <qpainter.h> #include <qbitmap.h> #include <qfontmetrics.h> #include <qsignalmapper.h> #include <qstyle.h> #include <qframe.h> #include <qdrawutil.h> #include <kpopupmenu.h> #include <kapplication.h> #include <klocale.h> #include <kiconloader.h> #include <sidebarextension.h> #include <kdebug.h> #include "mainwindow.h" #include "plugin.h" #include "prefs.h" #include "iconsidepane.h" namespace Kontact { //ugly wrapper class for adding an operator< to the Plugin class class PluginProxy { public: PluginProxy() : m_plugin( 0 ) { } PluginProxy( Plugin * plugin ) : m_plugin( plugin ) { } PluginProxy & operator=( Plugin * plugin ) { m_plugin = plugin; return *this; } bool operator<( PluginProxy & rhs ) const { return m_plugin->weight() < rhs.m_plugin->weight(); } Plugin * plugin() const { return m_plugin; } private: Plugin * m_plugin; }; } //namespace using namespace Kontact; EntryItem::EntryItem( Navigator *parent, Kontact::Plugin *plugin ) : QListBoxItem( parent ), mPlugin( plugin ) { reloadPixmap(); setCustomHighlighting( true ); setText( plugin->title() ); } EntryItem::~EntryItem() { } void EntryItem::reloadPixmap() { int size = (int)navigator()->viewMode(); if (size != 0) mPixmap = KGlobal::iconLoader()->loadIcon( mPlugin->icon(), KIcon::Desktop, size ); else mPixmap = QPixmap(); } Navigator* EntryItem::navigator() const { return static_cast<Navigator*>(listBox()); } int EntryItem::width( const QListBox *listbox) const { int w; if ( text().isEmpty() ) w = mPixmap.width(); else w = QMAX( (int)navigator()->viewMode(), listbox->fontMetrics().width( text() ) ); return w + 36; } int EntryItem::height( const QListBox *listbox) const { int h; if ( text().isEmpty() ) h = mPixmap.height(); else h = (int)navigator()->viewMode() + listbox->fontMetrics().lineSpacing(); return h + 4; } void EntryItem::paint( QPainter *p ) { reloadPixmap(); QListBox *box = listBox(); int w = box->viewport()->width(); int y = 2; if ( !mPixmap.isNull() ) { int x = ( w - mPixmap.width() ) / 2; p->drawPixmap( x, y, mPixmap ); } QColor save; if ( isCurrent() || isSelected() ) { save = p->pen().color(); p->setPen(listBox()->colorGroup().brightText()); } if ( !text().isEmpty() ) { QFontMetrics fm = p->fontMetrics(); y += mPixmap.height() + fm.height() - fm.descent(); int x = ( w - fm.width( text() ) ) / 2; p->drawText( x, y, text() ); } // draw sunken if ( isCurrent() || isSelected() ) { p->setPen(save); QColorGroup group = box->colorGroup(); group.setColor( QColorGroup::Dark, Qt::black ); qDrawShadePanel( p, 1, 0, w - 2, height( box ), group, true, 1, 0 ); } } Navigator::Navigator( SidePaneBase *parent, const char *name) : KListBox( parent, name ), mSidePane( parent ) { mViewMode = sizeIntToEnum( Prefs::self()->sidePaneIconSize() ); setSelectionMode( KListBox::Single ); viewport()->setBackgroundMode( PaletteMid ); setHScrollBarMode( QScrollView::AlwaysOff ); setAcceptDrops( true ); connect( this, SIGNAL( selectionChanged( QListBoxItem * ) ), SLOT( slotExecuted( QListBoxItem * ) ) ); connect( this, SIGNAL( rightButtonPressed( QListBoxItem *, const QPoint& ) ), SLOT( slotShowRMBMenu( QListBoxItem *, const QPoint& ) ) ); mMapper = new QSignalMapper( this ); connect( mMapper, SIGNAL( mapped( int ) ), SLOT( shortCutSelected( int ) ) ); } QSize Navigator::sizeHint() const { return QSize( 100, 100 ); } void Navigator::setSelected( QListBoxItem *i, bool sel ) { // Reimplemented to avoid the immediate activation of // the item. might turn out it doesn't work, we check that // an confirm from MainWindow::selectPlugin() if (sel) { EntryItem *entry = static_cast<EntryItem *>( i ); emit pluginActivated( entry->plugin() ); } } void Navigator::updatePlugins( QValueList<Kontact::Plugin*> plugins_ ) { QValueList<Kontact::PluginProxy> plugins; QValueList<Kontact::Plugin*>::ConstIterator end_ = plugins_.end(); QValueList<Kontact::Plugin*>::ConstIterator it_ = plugins_.begin(); for ( ; it_ != end_; ++it_ ) plugins += PluginProxy( *it_ ); clear(); mActions.setAutoDelete( true ); mActions.clear(); mActions.setAutoDelete( false ); int counter = 0; int minWidth = 0; qBubbleSort( plugins ); QValueList<Kontact::PluginProxy>::ConstIterator end = plugins.end(); QValueList<Kontact::PluginProxy>::ConstIterator it = plugins.begin(); for ( ; it != end; ++it ) { Kontact::Plugin *plugin = ( *it ).plugin(); if ( !plugin->showInSideBar() ) continue; EntryItem *item = new EntryItem( this, plugin ); if ( item->width( this ) > minWidth ) minWidth = item->width( this ); QString name = QString( "CTRL+%1" ).arg( counter + 1 ); KAction *action = new KAction( plugin->title(), KShortcut( name ), mMapper, SLOT( map() ), mSidePane->actionCollection(), name.latin1() ); mMapper->setMapping( action, counter ); counter++; } parentWidget()->setFixedWidth( minWidth ); } void Navigator::dragEnterEvent( QDragEnterEvent *event ) { kdDebug(5600) << "Navigator::dragEnterEvent()" << endl; dragMoveEvent( event ); } void Navigator::dragMoveEvent( QDragMoveEvent *event ) { kdDebug(5600) << "Navigator::dragEnterEvent()" << endl; kdDebug(5600) << " Format: " << event->format() << endl; QListBoxItem *item = itemAt( event->pos() ); if ( !item ) { event->accept( false ); return; } EntryItem *entry = static_cast<EntryItem *>( item ); kdDebug(5600) << " PLUGIN: " << entry->plugin()->identifier() << endl; event->accept( entry->plugin()->canDecodeDrag( event ) ); } void Navigator::dropEvent( QDropEvent *event ) { kdDebug(5600) << "Navigator::dropEvent()" << endl; QListBoxItem *item = itemAt( event->pos() ); if ( !item ) { return; } EntryItem *entry = static_cast<EntryItem *>( item ); kdDebug(5600) << " PLUGIN: " << entry->plugin()->identifier() << endl; entry->plugin()->processDropEvent( event ); } void Navigator::resizeEvent( QResizeEvent *event ) { QListBox::resizeEvent( event ); triggerUpdate( true ); } void Navigator::slotExecuted( QListBoxItem *item ) { if ( !item ) return; EntryItem *entry = static_cast<EntryItem *>( item ); emit pluginActivated( entry->plugin() ); } IconViewMode Navigator::sizeIntToEnum(int size) const { switch ( size ) { case int(LargeIcons): return LargeIcons; break; case int(NormalIcons): return NormalIcons; break; case int(SmallIcons): return SmallIcons; break; case int(TextOnly): return TextOnly; break; default: // Stick with sane values return NormalIcons; kdDebug() << "View mode not implemented!" << endl; break; } } void Navigator::slotShowRMBMenu( QListBoxItem *, const QPoint& pos ) { KPopupMenu menu; menu.insertTitle( i18n("Icon Size") ); menu.insertItem( i18n("Large"), (int)LargeIcons ); menu.insertItem( i18n("Normal "), (int)NormalIcons ); menu.insertItem( i18n("Small"), (int)SmallIcons ); menu.insertItem( i18n("Text Only"), (int)TextOnly ); int choice = menu.exec( pos ); mViewMode = sizeIntToEnum(choice); Prefs::self()->setSidePaneIconSize( choice ); triggerUpdate( true ); } void Navigator::shortCutSelected( int pos ) { setCurrentItem( pos ); } IconSidePane::IconSidePane( Core *core, QWidget *parent, const char *name ) : SidePaneBase( core, parent, name ) { mNavigator = new Navigator( this ); connect( mNavigator, SIGNAL( pluginActivated( Kontact::Plugin * ) ), SIGNAL( pluginSelected( Kontact::Plugin * ) ) ); setAcceptDrops( true ); } IconSidePane::~IconSidePane() { } void IconSidePane::updatePlugins() { mNavigator->updatePlugins( core()->pluginList() ); } void IconSidePane::selectPlugin( Kontact::Plugin *plugin ) { bool blocked = signalsBlocked(); blockSignals( true ); uint i; for ( i = 0; i < mNavigator->count(); ++i ) { EntryItem *item = static_cast<EntryItem *>( mNavigator->item( i ) ); if ( item->plugin() == plugin ) { mNavigator->setCurrentItem( i ); break; } } blockSignals( blocked ); } void IconSidePane::selectPlugin( const QString &name ) { bool blocked = signalsBlocked(); blockSignals( true ); uint i; for ( i = 0; i < mNavigator->count(); ++i ) { EntryItem *item = static_cast<EntryItem *>( mNavigator->item( i ) ); if ( item->plugin()->identifier() == name ) { mNavigator->setCurrentItem( i ); break; } } blockSignals( blocked ); } #include "iconsidepane.moc" // vim: sw=2 sts=2 et tw=80 <|endoftext|>
<commit_before>// InteractiveNotifications.cpp : Defines the exported functions for the DLL application. // #include "stdafx.h" #include "InteractiveNotifications.h" #include <NotificationActivationCallback.h> #include <Shellapi.h> #include <string> #include <iostream> #include <SDKDDKVer.h> #include <Windows.h> #include <Psapi.h> #include <strsafe.h> #include <ShObjIdl.h> #include <Shlobj.h> #include <Pathcch.h> #include <propvarutil.h> #include <propkey.h> #include <wchar.h> #include <wrl.h> #include <wrl\wrappers\corewrappers.h> #include <windows.ui.notifications.h> // Correct flow // RegisterAppForNotificationSupport() // RegisterActivator() // Name: System.AppUserModel.ToastActivatorCLSID -- PKEY_AppUserModel_ToastActivatorCLSID // Type: Guid -- VT_CLSID // FormatID: {9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3}, 26 // // Used to CoCreate an INotificationActivationCallback interface to notify about toast activations. EXTERN_C const PROPERTYKEY DECLSPEC_SELECTANY PKEY_AppUserModel_ToastActivatorCLSID = { { 0x9F4C2855, 0x9F79, 0x4B39,{ 0xA8, 0xD0, 0xE1, 0xD4, 0x2D, 0xE1, 0xD5, 0xF3 } }, 26 }; using namespace ABI::Windows::Data::Xml::Dom; using namespace ABI::Windows::UI::Notifications; using namespace Microsoft::WRL; using namespace Microsoft::WRL::Wrappers; struct CoTaskMemStringTraits { typedef PWSTR Type; inline static bool Close(_In_ Type h) throw() { ::CoTaskMemFree(h); return true; } inline static Type GetInvalidValue() throw() { return nullptr; } }; typedef HandleT<CoTaskMemStringTraits> CoTaskMemString; const wchar_t Shortcut[] = LR"(Microsoft\Windows\Start Menu\Slack.lnk)"; #define __CSID "F4B2D0CA-5D93-41CF-9A4C-721782B3246F" // For the app to be activated from Action Center, it needs to provide a COM server to be called // when the notification is activated. The CLSID of the object needs to be registered with the // OS via its shortcut so that it knows who to call later. class DECLSPEC_UUID(__CSID) NotificationActivator WrlSealed WrlFinal : public RuntimeClass < RuntimeClassFlags<ClassicCom>, INotificationActivationCallback > { public: virtual HRESULT STDMETHODCALLTYPE Activate( _In_ LPCWSTR appUserModelId, _In_ LPCWSTR invokedArgs, _In_reads_(dataCount) const NOTIFICATION_USER_INPUT_DATA* data, ULONG dataCount) override { std::string args; for (int i = 0; i < dataCount; i++) { LPCWSTR lvalue = data[i].Value; LPCWSTR lkey = data[i].Key; std::wstring wvalue(lvalue); std::wstring wkey(lkey); std::string value(wvalue.begin(), wvalue.end()); std::string key(wkey.begin(), wkey.end()); args = args + "\"key\":\"" + key + "\""; args = args + ",\"value\":\"" + value + "\""; } std::string escapedArgs = ""; for (char ch : args) { switch (ch) { case ' ': escapedArgs += "%20"; break; case '&': escapedArgs += "^&"; break; case '\\': escapedArgs += "^\\"; break; case '<': escapedArgs += "^<"; break; case '>': escapedArgs += "^>"; break; case '|': escapedArgs += "^|"; break; case '^': escapedArgs += "^^"; break; case '"': escapedArgs += "^\""; break; default: escapedArgs += ch; break; } } std::wstring wToastArgs(invokedArgs); std::string toastArgs(wToastArgs.begin(), wToastArgs.end()); // CMD needs stuff escaped, so we'll do that here std::string escapedToastArgs = ""; for (char ch : toastArgs) { switch (ch) { case ' ': escapedToastArgs += "%20"; break; case '&': escapedToastArgs += "^&"; break; case '\\': escapedToastArgs += "^\\"; break; case '<': escapedToastArgs += "^<"; break; case '>': escapedToastArgs += "^>"; break; case '|': escapedToastArgs += "^|"; break; case '^': escapedToastArgs += "^^"; break; case '"': escapedToastArgs += "^\""; break; default: escapedToastArgs += ch; break; } } std::string cmdLine = "start slack://" + escapedToastArgs + "^&userData={" + escapedArgs + "}"; system(cmdLine.c_str()); return HRESULT(); } }; CoCreatableClass(NotificationActivator); namespace InteractiveNotifications { INTERACTIVENOTIFICATIONS_API HRESULT RegisterAppForNotificationSupport(PCWSTR shortcut, PCWSTR appId) { CoTaskMemString appData; auto hr = ::SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, appData.GetAddressOf()); if (SUCCEEDED(hr)) { wchar_t shortcutPath[MAX_PATH]; // Todo: Don't hardcode the path hr = ::PathCchCombine(shortcutPath, ARRAYSIZE(shortcutPath), appData.Get(), shortcut); if (SUCCEEDED(hr)) { DWORD attributes = ::GetFileAttributes(shortcutPath); bool fileExists = attributes < 0xFFFFFFF; if (!fileExists) { // Todo: This is probably the wrong path bc Squirrel wchar_t exePath[MAX_PATH]; DWORD charWritten = ::GetModuleFileName(nullptr, exePath, ARRAYSIZE(exePath)); hr = charWritten > 0 ? S_OK : HRESULT_FROM_WIN32(::GetLastError()); if (SUCCEEDED(hr)) { hr = InstallShortcut(shortcutPath, exePath, appId); if (SUCCEEDED(hr)) { hr = RegisterComServer(exePath); } } } } } return hr; } _Use_decl_annotations_ INTERACTIVENOTIFICATIONS_API HRESULT InstallShortcut(PCWSTR shortcutPath, PCWSTR exePath, PCWSTR appId) { ComPtr<IShellLink> shellLink; HRESULT hr = CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&shellLink)); if (!SUCCEEDED(hr)) return hr; hr = shellLink->SetPath(exePath); if (!SUCCEEDED(hr)) return hr; ComPtr<IPropertyStore> propertyStore; hr = shellLink.As(&propertyStore); if (!SUCCEEDED(hr)) return hr; PROPVARIANT propVar; propVar.vt = VT_LPWSTR; propVar.pwszVal = const_cast<PWSTR>(appId); // for _In_ scenarios, we don't need a copy hr = propertyStore->SetValue(PKEY_AppUserModel_ID, propVar); if (!SUCCEEDED(hr)) return hr; propVar.vt = VT_CLSID; propVar.puuid = const_cast<CLSID*>(&__uuidof(NotificationActivator)); hr = propertyStore->SetValue(PKEY_AppUserModel_ToastActivatorCLSID, propVar); if (!SUCCEEDED(hr)) return hr; hr = propertyStore->Commit(); if (!SUCCEEDED(hr)) return hr; ComPtr<IPersistFile> persistFile; hr = shellLink.As(&persistFile); if (!SUCCEEDED(hr)) return hr; hr = persistFile->Save(shortcutPath, TRUE); return hr; } _Use_decl_annotations_ INTERACTIVENOTIFICATIONS_API HRESULT RegisterComServer(PCWSTR exePath) { // We don't need to worry about overflow here as ::GetModuleFileName won't // return anything bigger than the max file system path (much fewer than max of DWORD). DWORD dataSize = static_cast<DWORD>((::wcslen(exePath) + 1) * sizeof(WCHAR)); auto key = LR"(SOFTWARE\Classes\CLSID\{F4B2D0CA-5D93-41CF-9A4C-721782B3246F}\LocalServer32)"; return HRESULT_FROM_WIN32(::RegSetKeyValue( HKEY_CURRENT_USER, key, nullptr, REG_SZ, reinterpret_cast<const BYTE*>(exePath), dataSize)); } _Use_decl_annotations_ INTERACTIVENOTIFICATIONS_API HRESULT RegisterActivator() { // Module<OutOfProc> needs a callback registered before it can be used. // Since we don't care about when it shuts down, we'll pass an empty lambda here. // If we need to clean up, do it here (we probably don't have to) Module<OutOfProc>::Create([] {}); // If a local server process only hosts the COM object then COM expects // the COM server host to shutdown when the references drop to zero. // Since the user might still be using the program after activating the notification, // we don't want to shutdown immediately. Incrementing the object count tells COM that // we aren't done yet. Module<OutOfProc>::GetModule().IncrementObjectCount(); return Module<OutOfProc>::GetModule().RegisterObjects(); } _Use_decl_annotations_ INTERACTIVENOTIFICATIONS_API void UnregisterActivator() { Module<OutOfProc>::GetModule().UnregisterObjects(); Module<OutOfProc>::GetModule().DecrementObjectCount(); } } extern "C" { __declspec(dllexport) void CRegisterForNotificationSupport(PCWSTR shortcut, PCWSTR appId) { InteractiveNotifications::RegisterAppForNotificationSupport(shortcut, appId); } __declspec(dllexport) void CRegisterActivator() { InteractiveNotifications::RegisterActivator(); } __declspec(dllexport) void CUnregisterActivator() { InteractiveNotifications::UnregisterActivator(); } }<commit_msg>:wrench: And even more fixes<commit_after>// InteractiveNotifications.cpp : Defines the exported functions for the DLL application. // #include "stdafx.h" #include "InteractiveNotifications.h" #include <NotificationActivationCallback.h> #include <Shellapi.h> #include <string> #include <iostream> #include <SDKDDKVer.h> #include <Windows.h> #include <Psapi.h> #include <strsafe.h> #include <ShObjIdl.h> #include <Shlobj.h> #include <Pathcch.h> #include <propvarutil.h> #include <propkey.h> #include <wchar.h> #include <wrl.h> #include <wrl\wrappers\corewrappers.h> #include <windows.ui.notifications.h> // Correct flow // RegisterAppForNotificationSupport() // RegisterActivator() // Name: System.AppUserModel.ToastActivatorCLSID -- PKEY_AppUserModel_ToastActivatorCLSID // Type: Guid -- VT_CLSID // FormatID: {9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3}, 26 // // Used to CoCreate an INotificationActivationCallback interface to notify about toast activations. EXTERN_C const PROPERTYKEY DECLSPEC_SELECTANY PKEY_AppUserModel_ToastActivatorCLSID = { { 0x9F4C2855, 0x9F79, 0x4B39,{ 0xA8, 0xD0, 0xE1, 0xD4, 0x2D, 0xE1, 0xD5, 0xF3 } }, 26 }; using namespace ABI::Windows::Data::Xml::Dom; using namespace ABI::Windows::UI::Notifications; using namespace Microsoft::WRL; using namespace Microsoft::WRL::Wrappers; struct CoTaskMemStringTraits { typedef PWSTR Type; inline static bool Close(_In_ Type h) throw() { ::CoTaskMemFree(h); return true; } inline static Type GetInvalidValue() throw() { return nullptr; } }; typedef HandleT<CoTaskMemStringTraits> CoTaskMemString; const wchar_t Shortcut[] = LR"(Microsoft\Windows\Start Menu\Slack.lnk)"; #define __CSID "F4B2D0CA-5D93-41CF-9A4C-721782B3246F" // For the app to be activated from Action Center, it needs to provide a COM server to be called // when the notification is activated. The CLSID of the object needs to be registered with the // OS via its shortcut so that it knows who to call later. class DECLSPEC_UUID(__CSID) NotificationActivator WrlSealed WrlFinal : public RuntimeClass < RuntimeClassFlags<ClassicCom>, INotificationActivationCallback > { public: virtual HRESULT STDMETHODCALLTYPE Activate( _In_ LPCWSTR appUserModelId, _In_ LPCWSTR invokedArgs, _In_reads_(dataCount) const NOTIFICATION_USER_INPUT_DATA* data, ULONG dataCount) override { std::string args; for (int i = 0; i < dataCount; i++) { LPCWSTR lvalue = data[i].Value; LPCWSTR lkey = data[i].Key; std::wstring wvalue(lvalue); std::wstring wkey(lkey); std::string value(wvalue.begin(), wvalue.end()); std::string key(wkey.begin(), wkey.end()); args = args + "\"key\":\"" + key + "\""; args = args + ",\"value\":\"" + value + "\""; } std::string escapedArgs = ""; for (char ch : args) { switch (ch) { case ' ': escapedArgs += "%20"; break; case '&': escapedArgs += "^&"; break; case '\\': escapedArgs += "^\\"; break; case '<': escapedArgs += "^<"; break; case '>': escapedArgs += "^>"; break; case '|': escapedArgs += "^|"; break; case '^': escapedArgs += "^^"; break; case '"': escapedArgs += "^%22"; break; default: escapedArgs += ch; break; } } std::wstring wToastArgs(invokedArgs); std::string toastArgs(wToastArgs.begin(), wToastArgs.end()); // CMD needs stuff escaped, so we'll do that here std::string escapedToastArgs = ""; for (char ch : toastArgs) { switch (ch) { case ' ': escapedToastArgs += "%20"; break; case '&': escapedToastArgs += "^&"; break; case '\\': escapedToastArgs += "^\\"; break; case '<': escapedToastArgs += "^<"; break; case '>': escapedToastArgs += "^>"; break; case '|': escapedToastArgs += "^|"; break; case '^': escapedToastArgs += "^^"; break; case '"': escapedToastArgs += "%22"; break; default: escapedToastArgs += ch; break; } } std::string cmdLine = "start slack://" + escapedToastArgs + "^&userData={" + escapedArgs + "}"; system(cmdLine.c_str()); return HRESULT(); } }; CoCreatableClass(NotificationActivator); namespace InteractiveNotifications { INTERACTIVENOTIFICATIONS_API HRESULT RegisterAppForNotificationSupport(PCWSTR shortcut, PCWSTR appId) { CoTaskMemString appData; auto hr = ::SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, appData.GetAddressOf()); if (SUCCEEDED(hr)) { wchar_t shortcutPath[MAX_PATH]; // Todo: Don't hardcode the path hr = ::PathCchCombine(shortcutPath, ARRAYSIZE(shortcutPath), appData.Get(), shortcut); if (SUCCEEDED(hr)) { DWORD attributes = ::GetFileAttributes(shortcutPath); bool fileExists = attributes < 0xFFFFFFF; if (!fileExists) { // Todo: This is probably the wrong path bc Squirrel wchar_t exePath[MAX_PATH]; DWORD charWritten = ::GetModuleFileName(nullptr, exePath, ARRAYSIZE(exePath)); hr = charWritten > 0 ? S_OK : HRESULT_FROM_WIN32(::GetLastError()); if (SUCCEEDED(hr)) { hr = InstallShortcut(shortcutPath, exePath, appId); if (SUCCEEDED(hr)) { hr = RegisterComServer(exePath); } } } } } return hr; } _Use_decl_annotations_ INTERACTIVENOTIFICATIONS_API HRESULT InstallShortcut(PCWSTR shortcutPath, PCWSTR exePath, PCWSTR appId) { ComPtr<IShellLink> shellLink; HRESULT hr = CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&shellLink)); if (!SUCCEEDED(hr)) return hr; hr = shellLink->SetPath(exePath); if (!SUCCEEDED(hr)) return hr; ComPtr<IPropertyStore> propertyStore; hr = shellLink.As(&propertyStore); if (!SUCCEEDED(hr)) return hr; PROPVARIANT propVar; propVar.vt = VT_LPWSTR; propVar.pwszVal = const_cast<PWSTR>(appId); // for _In_ scenarios, we don't need a copy hr = propertyStore->SetValue(PKEY_AppUserModel_ID, propVar); if (!SUCCEEDED(hr)) return hr; propVar.vt = VT_CLSID; propVar.puuid = const_cast<CLSID*>(&__uuidof(NotificationActivator)); hr = propertyStore->SetValue(PKEY_AppUserModel_ToastActivatorCLSID, propVar); if (!SUCCEEDED(hr)) return hr; hr = propertyStore->Commit(); if (!SUCCEEDED(hr)) return hr; ComPtr<IPersistFile> persistFile; hr = shellLink.As(&persistFile); if (!SUCCEEDED(hr)) return hr; hr = persistFile->Save(shortcutPath, TRUE); return hr; } _Use_decl_annotations_ INTERACTIVENOTIFICATIONS_API HRESULT RegisterComServer(PCWSTR exePath) { // We don't need to worry about overflow here as ::GetModuleFileName won't // return anything bigger than the max file system path (much fewer than max of DWORD). DWORD dataSize = static_cast<DWORD>((::wcslen(exePath) + 1) * sizeof(WCHAR)); auto key = LR"(SOFTWARE\Classes\CLSID\{F4B2D0CA-5D93-41CF-9A4C-721782B3246F}\LocalServer32)"; return HRESULT_FROM_WIN32(::RegSetKeyValue( HKEY_CURRENT_USER, key, nullptr, REG_SZ, reinterpret_cast<const BYTE*>(exePath), dataSize)); } _Use_decl_annotations_ INTERACTIVENOTIFICATIONS_API HRESULT RegisterActivator() { // Module<OutOfProc> needs a callback registered before it can be used. // Since we don't care about when it shuts down, we'll pass an empty lambda here. // If we need to clean up, do it here (we probably don't have to) Module<OutOfProc>::Create([] {}); // If a local server process only hosts the COM object then COM expects // the COM server host to shutdown when the references drop to zero. // Since the user might still be using the program after activating the notification, // we don't want to shutdown immediately. Incrementing the object count tells COM that // we aren't done yet. Module<OutOfProc>::GetModule().IncrementObjectCount(); return Module<OutOfProc>::GetModule().RegisterObjects(); } _Use_decl_annotations_ INTERACTIVENOTIFICATIONS_API void UnregisterActivator() { Module<OutOfProc>::GetModule().UnregisterObjects(); Module<OutOfProc>::GetModule().DecrementObjectCount(); } } extern "C" { __declspec(dllexport) void CRegisterForNotificationSupport(PCWSTR shortcut, PCWSTR appId) { InteractiveNotifications::RegisterAppForNotificationSupport(shortcut, appId); } __declspec(dllexport) void CRegisterActivator() { InteractiveNotifications::RegisterActivator(); } __declspec(dllexport) void CUnregisterActivator() { InteractiveNotifications::UnregisterActivator(); } }<|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Library Module: STLRead.cc Language: C++ Date: $Date$ Version: $Revision$ This file is part of the Visualization Library. No part of this file or its contents may be copied, reproduced or altered in any way without the express written consent of the authors. Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 =========================================================================*/ #include <ctype.h> #include "STLRead.hh" #include "ByteSwap.hh" #define ASCII 0 #define BINARY 1 void vlSTLReader::Execute() { FILE *fp; vlFloatPoints *newPts; vlCellArray *newPolys; // // Initialize // this->Initialize(); if ((fp = fopen(this->Filename, "r")) == NULL) { fprintf(stderr, "%s: file %s not found\n", this->GetClassName(), this->Filename); return; } newPts = new vlFloatPoints(5000,10000); newPolys = new vlCellArray(10000,20000); // // Depending upon file type, read differently // if ( this->GetSTLFileType(fp) == ASCII ) { if ( this->ReadASCIISTL(fp,newPts,newPolys) ) return; } else { if ( this->ReadBinarySTL(fp,newPts,newPolys) ) return; } vlDebugMacro(<< "Read " << newPts->NumberOfPoints() << " points\n"); vlDebugMacro(<< "Read " << newPolys->GetNumberOfCells() << " triangles\n"); // // Since we sized the dynamic arrays arbitrarily to begin with // need to resize them to fit data // newPts->Squeeze(); newPolys->Squeeze(); // // Update ourselves // this->SetPoints(newPts); this->SetPolys(newPolys); } int vlSTLReader::ReadBinarySTL(FILE *fp, vlFloatPoints *newPts, vlCellArray *newPolys) { int i, numTris, pts[3]; unsigned long ulint; unsigned short ibuff2; char header[81]; vlByteSwap swap; typedef struct {float n[3], v1[3], v2[3], v3[3];} facet_t; facet_t facet; vlDebugMacro(<< " Reading BINARY STL file\n"); // // File is read to obtain raw information as well as bounding box // fread (header, 1, 80, fp); fread (&ulint, 1, 4, fp); swap.Swap4 (&ulint); if ( (numTris = (int) ulint) <= 0 ) { vlErrorMacro(<< "Bad binary STL file\n"); return 1; } for (i=0; fread(&facet,48,1,fp) && i<numTris; i++) { fread(&ibuff2,2,1,fp); /* read extra junk */ swap.Swap4 (facet.n); swap.Swap4 (facet.n+1); swap.Swap4 (facet.n+2); swap.Swap4 (facet.v1); swap.Swap4 (facet.v1+1); swap.Swap4 (facet.v1+2); pts[0] = newPts->InsertNextPoint(facet.v1); swap.Swap4 (facet.v2); swap.Swap4 (facet.v2+1); swap.Swap4 (facet.v2+2); pts[1] = newPts->InsertNextPoint(facet.v2); swap.Swap4 (facet.v3); swap.Swap4 (facet.v3+1); swap.Swap4 (facet.v3+2); pts[2] = newPts->InsertNextPoint(facet.v3); newPolys->InsertNextCell(3,pts); if (this->Debug && (i % 5000) == 0 && i != 0 ) fprintf (stderr,"%s: triangle #%d\n", this->GetClassName(), i); } return 0; } int vlSTLReader::ReadASCIISTL(FILE *fp, vlFloatPoints *newPts, vlCellArray *newPolys) { char line[256]; int i; float x[3]; int pts[3]; vlDebugMacro(<< " Reading ASCII STL file\n"); // // Ingest header and junk to get to first vertex // fgets (line, 255, fp); /* * Go into loop, reading facet normal and vertices */ while (fscanf(fp,"%*s %*s %f %f %f\n", x, x+1, x+2)!=EOF) { fgets (line, 255, fp); fscanf (fp, "%*s %f %f %f\n", x,x+1,x+2); pts[0] = newPts->InsertNextPoint(x); fscanf (fp, "%*s %f %f %f\n", x,x+1,x+2); pts[1] = newPts->InsertNextPoint(x); fscanf (fp, "%*s %f %f %f\n", x,x+1,x+2); pts[2] = newPts->InsertNextPoint(x); fgets (line, 255, fp); /* end loop */ fgets (line, 255, fp); /* end facet */ newPolys->InsertNextCell(3,pts); if (this->Debug && ((newPolys->GetNumberOfCells() % 5000) == 0) ) fprintf (stderr,"%s: triangle #%d\n", this->GetClassName(), newPolys->GetNumberOfCells()); } return 0; } int vlSTLReader::GetSTLFileType(FILE *fp) { char header[256]; int type, i; // // Read a little from the file to figure what type it is. // fgets (header, 255, fp); /* first line is always ascii */ fgets (header, 18, fp); for (i=0, type=ASCII; i<17 && type == ASCII; i++) // don't test \0 if ( ! isprint(header[i]) ) type = BINARY; // // Reset file for reading // rewind (fp); return type; } void vlSTLReader::PrintSelf(ostream& os, vlIndent indent) { if (this->ShouldIPrint(vlSTLReader::GetClassName())) { vlPolySource::PrintSelf(os,indent); os << indent << "Filename: " << this->Filename << "\n"; } } <commit_msg>ENH: More robust reading of binary files.<commit_after>/*========================================================================= Program: Visualization Library Module: STLRead.cc Language: C++ Date: $Date$ Version: $Revision$ This file is part of the Visualization Library. No part of this file or its contents may be copied, reproduced or altered in any way without the express written consent of the authors. Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 =========================================================================*/ #include <ctype.h> #include "STLRead.hh" #include "ByteSwap.hh" #define ASCII 0 #define BINARY 1 void vlSTLReader::Execute() { FILE *fp; vlFloatPoints *newPts; vlCellArray *newPolys; // // Initialize // this->Initialize(); if ((fp = fopen(this->Filename, "r")) == NULL) { vlErrorMacro(<< "File " << this->Filename << " not found\n"); return; } newPts = new vlFloatPoints(5000,10000); newPolys = new vlCellArray(10000,20000); // // Depending upon file type, read differently // if ( this->GetSTLFileType(fp) == ASCII ) { if ( this->ReadASCIISTL(fp,newPts,newPolys) ) return; } else { if ( this->ReadBinarySTL(fp,newPts,newPolys) ) return; } vlDebugMacro(<< "Read " << newPts->NumberOfPoints() << " points\n"); vlDebugMacro(<< "Read " << newPolys->GetNumberOfCells() << " triangles\n"); // // Since we sized the dynamic arrays arbitrarily to begin with // need to resize them to fit data // newPts->Squeeze(); newPolys->Squeeze(); // // Update ourselves // this->SetPoints(newPts); this->SetPolys(newPolys); } int vlSTLReader::ReadBinarySTL(FILE *fp, vlFloatPoints *newPts, vlCellArray *newPolys) { int i, numTris, pts[3]; unsigned long ulint; unsigned short ibuff2; char header[81]; vlByteSwap swap; typedef struct {float n[3], v1[3], v2[3], v3[3];} facet_t; facet_t facet; vlDebugMacro(<< " Reading BINARY STL file\n"); // // File is read to obtain raw information as well as bounding box // fread (header, 1, 80, fp); fread (&ulint, 1, 4, fp); swap.Swap4 (&ulint); // // Many .stl files contain bogus count. Hence we will ignore and read // until end of file. // if ( (numTris = (int) ulint) <= 0 ) { vlDebugMacro(<< "Bad binary count (" << numTris << ")\n"); } while ( fread(&facet,48,1,fp) > 0 ) { fread(&ibuff2,2,1,fp); /* read extra junk */ swap.Swap4 (facet.n); swap.Swap4 (facet.n+1); swap.Swap4 (facet.n+2); swap.Swap4 (facet.v1); swap.Swap4 (facet.v1+1); swap.Swap4 (facet.v1+2); pts[0] = newPts->InsertNextPoint(facet.v1); swap.Swap4 (facet.v2); swap.Swap4 (facet.v2+1); swap.Swap4 (facet.v2+2); pts[1] = newPts->InsertNextPoint(facet.v2); swap.Swap4 (facet.v3); swap.Swap4 (facet.v3+1); swap.Swap4 (facet.v3+2); pts[2] = newPts->InsertNextPoint(facet.v3); newPolys->InsertNextCell(3,pts); if (this->Debug && (i % 5000) == 0 && i != 0 ) fprintf (stderr,"%s: triangle #%d\n", this->GetClassName(), i); } return 0; } int vlSTLReader::ReadASCIISTL(FILE *fp, vlFloatPoints *newPts, vlCellArray *newPolys) { char line[256]; int i; float x[3]; int pts[3]; vlDebugMacro(<< " Reading ASCII STL file\n"); // // Ingest header and junk to get to first vertex // fgets (line, 255, fp); /* * Go into loop, reading facet normal and vertices */ while (fscanf(fp,"%*s %*s %f %f %f\n", x, x+1, x+2)!=EOF) { fgets (line, 255, fp); fscanf (fp, "%*s %f %f %f\n", x,x+1,x+2); pts[0] = newPts->InsertNextPoint(x); fscanf (fp, "%*s %f %f %f\n", x,x+1,x+2); pts[1] = newPts->InsertNextPoint(x); fscanf (fp, "%*s %f %f %f\n", x,x+1,x+2); pts[2] = newPts->InsertNextPoint(x); fgets (line, 255, fp); /* end loop */ fgets (line, 255, fp); /* end facet */ newPolys->InsertNextCell(3,pts); if (this->Debug && ((newPolys->GetNumberOfCells() % 5000) == 0) ) fprintf (stderr,"%s: triangle #%d\n", this->GetClassName(), newPolys->GetNumberOfCells()); } return 0; } int vlSTLReader::GetSTLFileType(FILE *fp) { char header[256]; int type, i; // // Read a little from the file to figure what type it is. // fgets (header, 255, fp); /* first line is always ascii */ fgets (header, 18, fp); for (i=0, type=ASCII; i<17 && type == ASCII; i++) // don't test \0 if ( ! isprint(header[i]) ) type = BINARY; // // Reset file for reading // rewind (fp); return type; } void vlSTLReader::PrintSelf(ostream& os, vlIndent indent) { if (this->ShouldIPrint(vlSTLReader::GetClassName())) { vlPolySource::PrintSelf(os,indent); os << indent << "Filename: " << this->Filename << "\n"; } } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkRGBToVectorAdaptImageFilterTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif /** * * This program illustrates the AdaptImageFilter * * The example shows how an Accessor can be used to * convert an RGBPixel image to an image that has * vector pixel type. * * This allows to access an RGB image a an image of vectors. * */ #include <itkAdaptImageFilter.h> #include <itkImageRegionIteratorWithIndex.h> #include <itkRGBPixel.h> #include <itkRGBToVectorPixelAccessor.h> #include <vnl/vnl_sample.h> //------------------------- // // Main code // //------------------------- int itkRGBToVectorAdaptImageFilterTest(int, char* [] ) { //------------------------------------- // Typedefs for convenience //------------------------------------- typedef itk::RGBPixel< float > RGBPixelType; typedef itk::Image< RGBPixelType, 2 > RGBImageType; typedef itk::ImageRegionIteratorWithIndex< RGBImageType > myRGBIteratorType; typedef itk::Accessor::RGBToVectorPixelAccessor<float> AccessorType; typedef AccessorType::ExternalType VectorPixelType; typedef itk::Image< VectorPixelType, 2 > myImageType; typedef itk::ImageRegionIteratorWithIndex< myImageType > myVectorIteratorType; RGBImageType::SizeType size; size[0] = 2; size[1] = 2; RGBImageType::IndexType index; index[0] = 0; index[1] = 0; RGBImageType::RegionType region; region.SetIndex( index ); region.SetSize( size ); RGBImageType::Pointer myImage = RGBImageType::New(); myImage->SetRegions( region ); myImage->Allocate(); myRGBIteratorType it1( myImage, myImage->GetRequestedRegion() ); // Value to initialize the pixels RGBImageType::PixelType color; // Initializing all the pixel in the image it1.GoToBegin(); while( !it1.IsAtEnd() ) { color.Set( (float) vnl_sample_uniform(0.0, 1.0), (float) vnl_sample_uniform(0.0, 1.0), (float) vnl_sample_uniform(0.0, 1.0) ); it1.Set(color); ++it1; } // Reading the values to verify the image content std::cout << "--- Initial image --- " << std::endl; it1.GoToBegin(); while( !it1.IsAtEnd() ) { const RGBImageType::PixelType c( it1.Get() ); std::cout << c.GetRed() << " "; std::cout << c.GetGreen() << " "; std::cout << c.GetBlue() << std::endl; ++it1; } bool passed = true; // Convert to a Vector image typedef itk::AdaptImageFilter< RGBImageType, myImageType, AccessorType > AdaptFilterType; AdaptFilterType::Pointer adaptImageToVector = AdaptFilterType::New(); adaptImageToVector->SetInput(myImage); adaptImageToVector->UpdateLargestPossibleRegion(); myVectorIteratorType it( adaptImageToVector->GetOutput(), adaptImageToVector->GetOutput()->GetRequestedRegion() ); std::cout << "--- Read Vector values --- " << std::endl; it.GoToBegin(); it1.GoToBegin(); while( !it.IsAtEnd() ) { std::cout << it.Get() << std::endl; VectorPixelType v = it.Get(); RGBPixelType c = it1.Get(); if ( v[0] != c.GetRed() || v[1] != c.GetGreen() || v[2] != c.GetBlue() ) { std::cerr << "Vector pixel = " << v << std::endl; std::cerr << "does not match " << std::endl; std::cerr << "RGB pixel = " << c << std::endl; passed = false; break; } ++it; ++it1; } std::cout << std::endl; if (passed) { std::cout << "AdaptImageFilterTest passed" << std::endl; return EXIT_SUCCESS; } else { std::cout << "AdaptImageFilterTest passed" << std::endl; return EXIT_FAILURE; } } <commit_msg>ENH: just a little more info if we fail.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkRGBToVectorAdaptImageFilterTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif /** * * This program illustrates the AdaptImageFilter * * The example shows how an Accessor can be used to * convert an RGBPixel image to an image that has * vector pixel type. * * This allows to access an RGB image a an image of vectors. * */ #include <itkAdaptImageFilter.h> #include <itkImageRegionIteratorWithIndex.h> #include <itkRGBPixel.h> #include <itkRGBToVectorPixelAccessor.h> #include <vnl/vnl_sample.h> //------------------------- // // Main code // //------------------------- int itkRGBToVectorAdaptImageFilterTest(int, char* [] ) { //------------------------------------- // Typedefs for convenience //------------------------------------- typedef itk::RGBPixel< float > RGBPixelType; typedef itk::Image< RGBPixelType, 2 > RGBImageType; typedef itk::ImageRegionIteratorWithIndex< RGBImageType > myRGBIteratorType; typedef itk::Accessor::RGBToVectorPixelAccessor<float> AccessorType; typedef AccessorType::ExternalType VectorPixelType; typedef itk::Image< VectorPixelType, 2 > myImageType; typedef itk::ImageRegionIteratorWithIndex< myImageType > myVectorIteratorType; RGBImageType::SizeType size; size[0] = 2; size[1] = 2; RGBImageType::IndexType index; index[0] = 0; index[1] = 0; RGBImageType::RegionType region; region.SetIndex( index ); region.SetSize( size ); RGBImageType::Pointer myImage = RGBImageType::New(); myImage->SetRegions( region ); myImage->Allocate(); myRGBIteratorType it1( myImage, myImage->GetRequestedRegion() ); // Value to initialize the pixels RGBImageType::PixelType color; // Initializing all the pixel in the image it1.GoToBegin(); while( !it1.IsAtEnd() ) { color.Set( (float) vnl_sample_uniform(0.0, 1.0), (float) vnl_sample_uniform(0.0, 1.0), (float) vnl_sample_uniform(0.0, 1.0) ); it1.Set(color); ++it1; } // Reading the values to verify the image content std::cout << "--- Initial image --- " << std::endl; it1.GoToBegin(); while( !it1.IsAtEnd() ) { const RGBImageType::PixelType c( it1.Get() ); std::cout << c.GetRed() << " "; std::cout << c.GetGreen() << " "; std::cout << c.GetBlue() << std::endl; ++it1; } bool passed = true; // Convert to a Vector image typedef itk::AdaptImageFilter< RGBImageType, myImageType, AccessorType > AdaptFilterType; AdaptFilterType::Pointer adaptImageToVector = AdaptFilterType::New(); adaptImageToVector->SetInput(myImage); adaptImageToVector->UpdateLargestPossibleRegion(); myVectorIteratorType it( adaptImageToVector->GetOutput(), adaptImageToVector->GetOutput()->GetRequestedRegion() ); std::cout << "--- Read Vector values --- " << std::endl; it.GoToBegin(); it1.GoToBegin(); while( !it.IsAtEnd() ) { std::cout << it.Get() << std::endl; VectorPixelType v = it.Get(); RGBPixelType c = it1.Get(); if ( v[0] != c.GetRed() || v[1] != c.GetGreen() || v[2] != c.GetBlue() ) { std::cerr << "Vector pixel = " << v << std::endl; std::cerr << "does not match " << std::endl; std::cerr << "RGB pixel = " << c << std::endl; std::cerr << "myImage->GetRequestedRegion()" << myImage->GetRequestedRegion() << std::endl; std::cerr << "adaptImageToVector->GetRequestedRegion()" << adaptImageToVector->GetOutput()->GetRequestedRegion() << std::endl; passed = false; break; } ++it; ++it1; } std::cout << std::endl; if (passed) { std::cout << "AdaptImageFilterTest passed" << std::endl; return EXIT_SUCCESS; } else { std::cout << "AdaptImageFilterTest passed" << std::endl; return EXIT_FAILURE; } } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkNeighborhoodOperatorImageFunctionTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <stdio.h> #include "itkNeighborhoodOperatorImageFunction.h" #include "itkImage.h" #include "itkGaussianOperator.h" int itkNeighborhoodOperatorImageFunctionTest(int, char* [] ) { const unsigned int Dimension = 3; typedef float PixelType; typedef itk::Image< PixelType, Dimension > ImageType; typedef itk::GaussianOperator<PixelType,3> NeighborhoodOperatorType; typedef itk::NeighborhoodOperatorImageFunction< ImageType,double> FunctionType; // Create and allocate the image ImageType::Pointer image = ImageType::New(); ImageType::SizeType size; ImageType::IndexType start; ImageType::RegionType region; size[0] = 50; size[1] = 50; size[2] = 50; start.Fill( 0 ); region.SetIndex( start ); region.SetSize( size ); image->SetRegions( region ); image->Allocate(); ImageType::PixelType initialValue = 27; image->FillBuffer( initialValue ); FunctionType::Pointer function = FunctionType::New(); function->SetInputImage( image ); NeighborhoodOperatorType* oper= new NeighborhoodOperatorType; oper->CreateToRadius(3); function->SetOperator(*oper); itk::Index<3> index; index.Fill(25); FunctionType::OutputType Blur; Blur = function->EvaluateAtIndex( index ); // since the input image is constant // the should be equal to the initial value if( vnl_math_abs( initialValue - Blur ) > 10e-7 ) { std::cerr << "Error in Blur computation" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED] " << std::endl; return EXIT_SUCCESS; } <commit_msg>ERR: memory leak.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkNeighborhoodOperatorImageFunctionTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <stdio.h> #include "itkNeighborhoodOperatorImageFunction.h" #include "itkImage.h" #include "itkGaussianOperator.h" int itkNeighborhoodOperatorImageFunctionTest(int, char* [] ) { const unsigned int Dimension = 3; typedef float PixelType; typedef itk::Image< PixelType, Dimension > ImageType; typedef itk::GaussianOperator<PixelType,3> NeighborhoodOperatorType; typedef itk::NeighborhoodOperatorImageFunction< ImageType,double> FunctionType; // Create and allocate the image ImageType::Pointer image = ImageType::New(); ImageType::SizeType size; ImageType::IndexType start; ImageType::RegionType region; size[0] = 50; size[1] = 50; size[2] = 50; start.Fill( 0 ); region.SetIndex( start ); region.SetSize( size ); image->SetRegions( region ); image->Allocate(); ImageType::PixelType initialValue = 27; image->FillBuffer( initialValue ); FunctionType::Pointer function = FunctionType::New(); function->SetInputImage( image ); NeighborhoodOperatorType* oper= new NeighborhoodOperatorType; oper->CreateToRadius(3); function->SetOperator(*oper); delete oper; itk::Index<3> index; index.Fill(25); FunctionType::OutputType Blur; Blur = function->EvaluateAtIndex( index ); // since the input image is constant // the should be equal to the initial value if( vnl_math_abs( initialValue - Blur ) > 10e-7 ) { std::cerr << "Error in Blur computation" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED] " << std::endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* * Copyright (c) 2010-2014, MIT Probabilistic Computing Project * * Lead Developers: Dan Lovell and Jay Baxter * Authors: Dan Lovell, Baxter Eaves, Jay Baxter, Vikash Mansinghka * Research Leads: Vikash Mansinghka, Patrick Shafto * * 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 <iostream> // #include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/io.hpp> // #include "State.h" #include "utils.h" #include "constants.h" // typedef boost::numeric::ublas::matrix<double> matrixD; using namespace std; int n_iterations = 10; string filename = "T.csv"; // passing in a State is dangerous, if you don't pass in a reference, memory will be deallocated // and bugs/segfaults will occur void print_state_summary(const State& s) { cout << "s.num_views: " << s.get_num_views() << endl; for (int j = 0; j < s.get_num_views(); j++) { cout << "view " << j; cout << " row_paritition_model_counts: " << s.get_row_partition_model_counts_i( j) << endl; } cout << "s.column_crp_score: " << s.get_column_crp_score(); cout << "; s.data_score: " << s.get_data_score(); cout << "; s.score: " << s.get_marginal_logp(); cout << endl; return; } int main(int argc, char** argv) { cout << endl << "test_state: Hello World!" << endl; // load some data matrixD data; LoadData(filename, data); cout << "data is: " << data << endl; int num_rows = data.size1(); int num_cols = data.size2(); // create the objects to test vector<int> global_row_indices = create_sequence(data.size1()); vector<int> global_column_indices = create_sequence(data.size2()); vector<string> global_col_types; vector<int> global_col_multinomial_counts; for (int i = 0; i < global_column_indices.size(); i++) { global_col_types.push_back(CONTINUOUS_DATATYPE); global_col_multinomial_counts.push_back(0); } State s = State(data, global_col_types, global_col_multinomial_counts, global_row_indices, global_column_indices); cout << "start X_D" << endl << s.get_X_D() << endl; // cout << "State:" << endl << s << endl; vector<int> empty_int_v; for (int i = 0; i < n_iterations; i++) { cout << "transition #: " << i << endl; s.transition_column_crp_alpha(); s.transition_column_hyperparameters(empty_int_v); s.transition_row_partition_hyperparameters(empty_int_v); s.transition_features(data, empty_int_v); s.transition_row_partition_assignments(data, empty_int_v); // s.transition(data); print_state_summary(s); } // cout << "FINAL STATE" << endl; // cout << s << endl; cout << "end X_D" << endl << s.get_X_D() << endl; cout << endl << "test_state: Goodbye World!" << endl; } <commit_msg>Avoid copying State in test_state.cpp.<commit_after>/* * Copyright (c) 2010-2014, MIT Probabilistic Computing Project * * Lead Developers: Dan Lovell and Jay Baxter * Authors: Dan Lovell, Baxter Eaves, Jay Baxter, Vikash Mansinghka * Research Leads: Vikash Mansinghka, Patrick Shafto * * 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 <iostream> // #include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/io.hpp> // #include "State.h" #include "utils.h" #include "constants.h" // typedef boost::numeric::ublas::matrix<double> matrixD; using namespace std; int n_iterations = 10; string filename = "T.csv"; // passing in a State is dangerous, if you don't pass in a reference, memory will be deallocated // and bugs/segfaults will occur void print_state_summary(const State& s) { cout << "s.num_views: " << s.get_num_views() << endl; for (int j = 0; j < s.get_num_views(); j++) { cout << "view " << j; cout << " row_paritition_model_counts: " << s.get_row_partition_model_counts_i( j) << endl; } cout << "s.column_crp_score: " << s.get_column_crp_score(); cout << "; s.data_score: " << s.get_data_score(); cout << "; s.score: " << s.get_marginal_logp(); cout << endl; return; } int main(int argc, char** argv) { cout << endl << "test_state: Hello World!" << endl; // load some data matrixD data; LoadData(filename, data); cout << "data is: " << data << endl; int num_rows = data.size1(); int num_cols = data.size2(); // create the objects to test vector<int> global_row_indices = create_sequence(data.size1()); vector<int> global_column_indices = create_sequence(data.size2()); vector<string> global_col_types; vector<int> global_col_multinomial_counts; for (int i = 0; i < global_column_indices.size(); i++) { global_col_types.push_back(CONTINUOUS_DATATYPE); global_col_multinomial_counts.push_back(0); } State s(data, global_col_types, global_col_multinomial_counts, global_row_indices, global_column_indices); cout << "start X_D" << endl << s.get_X_D() << endl; // cout << "State:" << endl << s << endl; vector<int> empty_int_v; for (int i = 0; i < n_iterations; i++) { cout << "transition #: " << i << endl; s.transition_column_crp_alpha(); s.transition_column_hyperparameters(empty_int_v); s.transition_row_partition_hyperparameters(empty_int_v); s.transition_features(data, empty_int_v); s.transition_row_partition_assignments(data, empty_int_v); // s.transition(data); print_state_summary(s); } // cout << "FINAL STATE" << endl; // cout << s << endl; cout << "end X_D" << endl << s.get_X_D() << endl; cout << endl << "test_state: Goodbye World!" << endl; } <|endoftext|>
<commit_before><commit_msg>Missing const<commit_after><|endoftext|>
<commit_before>//===--- ClassHierarchyAnalysis.cpp - Class hierarchy analysis ------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "swift/SILOptimizer/Analysis/ClassHierarchyAnalysis.h" #include "swift/AST/ASTContext.h" #include "swift/AST/ASTWalker.h" #include "swift/AST/Module.h" #include "swift/SIL/SILInstruction.h" #include "swift/SIL/SILValue.h" #include "swift/SIL/SILModule.h" using namespace swift; namespace { /// A helper class to collect all nominal type declarations. class NominalTypeWalker: public ASTWalker { ClassHierarchyAnalysis::ProtocolImplementations &ProtocolImplementationsCache; public: NominalTypeWalker(ClassHierarchyAnalysis::ProtocolImplementations &ProtocolImplementationsCache) :ProtocolImplementationsCache(ProtocolImplementationsCache) { } virtual bool walkToDeclPre(Decl *D) { auto *NTD = dyn_cast<NominalTypeDecl>(D); if (!NTD) return true; auto Protocols = NTD->getAllProtocols(); // We are only interested in types implementing protocols. if (!Protocols.empty()) { for (auto &Protocol : Protocols) { auto &K = ProtocolImplementationsCache[Protocol]; K.push_back(NTD); } } return true; } }; } void ClassHierarchyAnalysis::init() { // Process all types implementing protocols. SmallVector<Decl *, 32> Decls; // TODO: It would be better if we could get all declarations // from a given module, not only the top-level ones. M->getSwiftModule()->getTopLevelDecls(Decls); NominalTypeWalker Walker(ProtocolImplementationsCache); for (auto *D: Decls) { D->walk(Walker); } // For each class declaration in our V-table list: for (auto &VT : M->getVTableList()) { ClassDecl *C = VT.getClass(); // Ignore classes that are at the top of the class hierarchy: if (!C->hasSuperclass()) continue; // Add the superclass to the list of inherited classes. ClassDecl *Super = C->getSuperclass()->getClassOrBoundGenericClass(); auto &K = DirectSubclassesCache[Super]; assert(std::find(K.begin(), K.end(), C) == K.end() && "Class vector must be unique"); K.push_back(C); } } /// \brief Get all subclasses of a given class. /// Does not include any direct subclasses of given base class. /// /// \p Base class, whose direct subclasses are to be excluded /// \p Current class, whose direct and indirect subclasses are /// to be collected. /// \p IndirectSubs placeholder for collected results void ClassHierarchyAnalysis::getIndirectSubClasses(ClassDecl *Cur, ClassList &IndirectSubs) { unsigned Idx = IndirectSubs.size(); if (!hasKnownDirectSubclasses(Cur)) return; // Produce a set of all indirect subclasses in a // breadth-first order; // First add subclasses of direct subclasses. for (auto C : getDirectSubClasses(Cur)) { // Get direct subclasses if (!hasKnownDirectSubclasses(C)) continue; auto &DirectSubclasses = getDirectSubClasses(C); // Remember all direct subclasses of the current one. for (auto S : DirectSubclasses) { IndirectSubs.push_back(S); } } // Then recursively add direct subclasses of already // added subclasses. while (Idx != IndirectSubs.size()) { auto C = IndirectSubs[Idx++]; // Get direct subclasses if (!hasKnownDirectSubclasses(C)) continue; auto &DirectSubclasses = getDirectSubClasses(C); // Remember all direct subclasses of the current one. for (auto S : DirectSubclasses) { IndirectSubs.push_back(S); } } } ClassHierarchyAnalysis::~ClassHierarchyAnalysis() {} <commit_msg>[Analysis] Adjust inline documentation in ClassHierarchyAnalysis.cpp<commit_after>//===--- ClassHierarchyAnalysis.cpp - Class hierarchy analysis ------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "swift/SILOptimizer/Analysis/ClassHierarchyAnalysis.h" #include "swift/AST/ASTContext.h" #include "swift/AST/ASTWalker.h" #include "swift/AST/Module.h" #include "swift/SIL/SILInstruction.h" #include "swift/SIL/SILValue.h" #include "swift/SIL/SILModule.h" using namespace swift; namespace { /// A helper class to collect all nominal type declarations. class NominalTypeWalker: public ASTWalker { ClassHierarchyAnalysis::ProtocolImplementations &ProtocolImplementationsCache; public: NominalTypeWalker(ClassHierarchyAnalysis::ProtocolImplementations &ProtocolImplementationsCache) :ProtocolImplementationsCache(ProtocolImplementationsCache) { } virtual bool walkToDeclPre(Decl *D) { auto *NTD = dyn_cast<NominalTypeDecl>(D); if (!NTD) return true; auto Protocols = NTD->getAllProtocols(); // We are only interested in types implementing protocols. if (!Protocols.empty()) { for (auto &Protocol : Protocols) { auto &K = ProtocolImplementationsCache[Protocol]; K.push_back(NTD); } } return true; } }; } void ClassHierarchyAnalysis::init() { // Process all types implementing protocols. SmallVector<Decl *, 32> Decls; // TODO: It would be better if we could get all declarations // from a given module, not only the top-level ones. M->getSwiftModule()->getTopLevelDecls(Decls); NominalTypeWalker Walker(ProtocolImplementationsCache); for (auto *D: Decls) { D->walk(Walker); } // For each class declaration in our V-table list: for (auto &VT : M->getVTableList()) { ClassDecl *C = VT.getClass(); // Ignore classes that are at the top of the class hierarchy: if (!C->hasSuperclass()) continue; // Add the superclass to the list of inherited classes. ClassDecl *Super = C->getSuperclass()->getClassOrBoundGenericClass(); auto &K = DirectSubclassesCache[Super]; assert(std::find(K.begin(), K.end(), C) == K.end() && "Class vector must be unique"); K.push_back(C); } } /// \brief Get all subclasses of a given class. /// /// \p Current class, whose direct and indirect subclasses are /// to be collected. /// \p IndirectSubs placeholder for collected results void ClassHierarchyAnalysis::getIndirectSubClasses(ClassDecl *Cur, ClassList &IndirectSubs) { unsigned Idx = IndirectSubs.size(); if (!hasKnownDirectSubclasses(Cur)) return; // Produce a set of all indirect subclasses in a // breadth-first order; // First add subclasses of direct subclasses. for (auto C : getDirectSubClasses(Cur)) { // Get direct subclasses if (!hasKnownDirectSubclasses(C)) continue; auto &DirectSubclasses = getDirectSubClasses(C); // Remember all direct subclasses of the current one. for (auto S : DirectSubclasses) { IndirectSubs.push_back(S); } } // Then recursively add direct subclasses of already // added subclasses. while (Idx != IndirectSubs.size()) { auto C = IndirectSubs[Idx++]; // Get direct subclasses if (!hasKnownDirectSubclasses(C)) continue; auto &DirectSubclasses = getDirectSubClasses(C); // Remember all direct subclasses of the current one. for (auto S : DirectSubclasses) { IndirectSubs.push_back(S); } } } ClassHierarchyAnalysis::~ClassHierarchyAnalysis() {} <|endoftext|>