text
stringlengths
54
60.6k
<commit_before>//======================================================================= // Copyright (c) 2014-2017 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= /*! * \file * \brief Utility functions for curand */ #pragma once #include "curand.h" namespace etl { namespace impl { namespace curand { #define curand_call(call) \ { \ auto status = call; \ if (status != CURAND_STATUS_SUCCESS) { \ std::cerr << "CURAND error: " << status << " from " << #call << std::endl \ << "from " << __FILE__ << ":" << __LINE__ << std::endl; \ } \ } inline void generate_normal(curandGenerator_t generator, float* gpu_memory, size_t n, float mean, float stddev){ // Note: CURAND is dumb, cannot generate odd sequences... if(n % 2 == 0){ curand_call(curandGenerateNormal(generator, gpu_memory, n, mean, stddev)); } else { // Generate the first n - 1 numbers curand_call(curandGenerateNormal(generator, gpu_memory, n - 1, mean, stddev)); // Generate the last two numbers curand_call(curandGenerateNormal(generator, gpu_memory + (n - 3), 2, mean, stddev)); } } inline void generate_normal(curandGenerator_t generator, double* gpu_memory, size_t n, double mean, double stddev){ // Note: CURAND is dumb, cannot generate odd sequences... if(n % 2 == 0){ curand_call(curandGenerateNormalDouble(generator, gpu_memory, n, mean, stddev)); } else { // Generate the first n - 1 numbers curand_call(curandGenerateNormalDouble(generator, gpu_memory, n - 1, mean, stddev)); // Generate the last two numbers curand_call(curandGenerateNormalDouble(generator, gpu_memory + (n - 3), 2, mean, stddev)); } } inline void generate_uniform(curandGenerator_t generator, float* gpu_memory, size_t n){ curand_call(curandGenerateUniform(generator, gpu_memory, n)); } inline void generate_uniform(curandGenerator_t generator, double* gpu_memory, size_t n){ curand_call(curandGenerateUniformDouble(generator, gpu_memory, n)); } } //end of namespace curand } //end of namespace impl } //end of namespace etl <commit_msg>Complete the doc<commit_after>//======================================================================= // Copyright (c) 2014-2017 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= /*! * \file * \brief Utility functions for curand */ #pragma once #include "curand.h" namespace etl { namespace impl { namespace curand { #define curand_call(call) \ { \ auto status = call; \ if (status != CURAND_STATUS_SUCCESS) { \ std::cerr << "CURAND error: " << status << " from " << #call << std::endl \ << "from " << __FILE__ << ":" << __LINE__ << std::endl; \ } \ } /*! * \brief Generate a normal distribution with the given mean and * standard deviation with CURAND, in single-precision. * * \param generator The configured CURAND generator * \param gpu_memory Pointer to the GPU memory to fill * \param n The number of elements to set * \param mean The mean of the distribution to generate. * \param stddev The standard deviation of the distribution to generate. */ inline void generate_normal(curandGenerator_t generator, float* gpu_memory, size_t n, float mean, float stddev){ // Note: CURAND is dumb, cannot generate odd sequences... if(n % 2 == 0){ curand_call(curandGenerateNormal(generator, gpu_memory, n, mean, stddev)); } else { // Generate the first n - 1 numbers curand_call(curandGenerateNormal(generator, gpu_memory, n - 1, mean, stddev)); // Generate the last two numbers curand_call(curandGenerateNormal(generator, gpu_memory + (n - 3), 2, mean, stddev)); } } /*! * \brief Generate a normal distribution with the given mean and * standard deviation with CURAND, in double-precision. * * \param generator The configured CURAND generator * \param gpu_memory Pointer to the GPU memory to fill * \param n The number of elements to set * \param mean The mean of the distribution to generate. * \param stddev The standard deviation of the distribution to generate. */ inline void generate_normal(curandGenerator_t generator, double* gpu_memory, size_t n, double mean, double stddev){ // Note: CURAND is dumb, cannot generate odd sequences... if(n % 2 == 0){ curand_call(curandGenerateNormalDouble(generator, gpu_memory, n, mean, stddev)); } else { // Generate the first n - 1 numbers curand_call(curandGenerateNormalDouble(generator, gpu_memory, n - 1, mean, stddev)); // Generate the last two numbers curand_call(curandGenerateNormalDouble(generator, gpu_memory + (n - 3), 2, mean, stddev)); } } /*! * \brief Generate a uniform distribution between 0 and 1, in single * precision. * * \param generator The configured CURAND generator * \param gpu_memory Pointer to the GPU memory to fill * \param n The number of elements to set */ inline void generate_uniform(curandGenerator_t generator, float* gpu_memory, size_t n){ curand_call(curandGenerateUniform(generator, gpu_memory, n)); } /*! * \brief Generate a uniform distribution between 0 and 1, in single * precision. * * \param generator The configured CURAND generator * \param gpu_memory Pointer to the GPU memory to fill * \param n The number of elements to set */ inline void generate_uniform(curandGenerator_t generator, double* gpu_memory, size_t n){ curand_call(curandGenerateUniformDouble(generator, gpu_memory, n)); } } //end of namespace curand } //end of namespace impl } //end of namespace etl <|endoftext|>
<commit_before>#include "per_vertex_normals.h" #include "per_face_normals.h" #include "normalize_row_lengths.h" template <typename DerivedV, typename DerivedF> IGL_INLINE void igl::per_vertex_normals( const Eigen::PlainObjectBase<DerivedV>& V, const Eigen::PlainObjectBase<DerivedF>& F, Eigen::PlainObjectBase<DerivedV> & N) { Eigen::PlainObjectBase<DerivedV> PFN; igl::per_face_normals(V,F,PFN); return igl::per_vertex_normals(V,F,PFN,N); //// Resize for output //N = Eigen::PlainObjectBase<DerivedV>::Zero(V.rows(),3); //// loop over faces //for(int i = 0; i < F.rows();i++) //{ // // throw normal at each corner // for(int j = 0; j < 3;j++) // { // N.row(F(i,j)) += PFN.row(i); // } //} //// normalize each row //igl::normalize_row_lengths(N,N); } template <typename DerivedV, typename DerivedF> IGL_INLINE void igl::per_vertex_normals( const Eigen::PlainObjectBase<DerivedV>& V, const Eigen::PlainObjectBase<DerivedF>& F, const Eigen::PlainObjectBase<DerivedV>& FN, Eigen::PlainObjectBase<DerivedV> & N) { // Resize for output N.setZero(V.rows(),3); // loop over faces int Frows = F.rows(); #pragma omp parallel for for(int i = 0; i < Frows;i++) { // throw normal at each corner for(int j = 0; j < 3;j++) { N.row(F(i,j)) += FN.row(i); } } cout << "N.row()" << N.row(0) << endl; // normalize each row igl::normalize_row_lengths(N,N); } #ifndef IGL_HEADER_ONLY // Explicit template specialization // generated by autoexplicit.sh template void igl::per_vertex_normals<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&); template void igl::per_vertex_normals<Eigen::Matrix<double, -1, 3, 1, -1, 3>, Eigen::Matrix<unsigned int, -1, -1, 1, -1, -1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 1, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<unsigned int, -1, -1, 1, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 1, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 1, -1, 3> >&); template void igl::per_vertex_normals<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&); #endif <commit_msg>removed debugging output<commit_after>#include "per_vertex_normals.h" #include "per_face_normals.h" #include "normalize_row_lengths.h" template <typename DerivedV, typename DerivedF> IGL_INLINE void igl::per_vertex_normals( const Eigen::PlainObjectBase<DerivedV>& V, const Eigen::PlainObjectBase<DerivedF>& F, Eigen::PlainObjectBase<DerivedV> & N) { Eigen::PlainObjectBase<DerivedV> PFN; igl::per_face_normals(V,F,PFN); return igl::per_vertex_normals(V,F,PFN,N); //// Resize for output //N = Eigen::PlainObjectBase<DerivedV>::Zero(V.rows(),3); //// loop over faces //for(int i = 0; i < F.rows();i++) //{ // // throw normal at each corner // for(int j = 0; j < 3;j++) // { // N.row(F(i,j)) += PFN.row(i); // } //} //// normalize each row //igl::normalize_row_lengths(N,N); } template <typename DerivedV, typename DerivedF> IGL_INLINE void igl::per_vertex_normals( const Eigen::PlainObjectBase<DerivedV>& V, const Eigen::PlainObjectBase<DerivedF>& F, const Eigen::PlainObjectBase<DerivedV>& FN, Eigen::PlainObjectBase<DerivedV> & N) { // Resize for output N.setZero(V.rows(),3); // loop over faces int Frows = F.rows(); #pragma omp parallel for for(int i = 0; i < Frows;i++) { // throw normal at each corner for(int j = 0; j < 3;j++) { N.row(F(i,j)) += FN.row(i); } } // normalize each row igl::normalize_row_lengths(N,N); } #ifndef IGL_HEADER_ONLY // Explicit template specialization // generated by autoexplicit.sh template void igl::per_vertex_normals<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&); template void igl::per_vertex_normals<Eigen::Matrix<double, -1, 3, 1, -1, 3>, Eigen::Matrix<unsigned int, -1, -1, 1, -1, -1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 1, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<unsigned int, -1, -1, 1, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 1, -1, 3> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 1, -1, 3> >&); template void igl::per_vertex_normals<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&); #endif <|endoftext|>
<commit_before>/* * Copyright (C) 2014 Open Source Robotics Foundation * * 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 __IGN_TRANSPORT_NODE_HH_INCLUDED__ #define __IGN_TRANSPORT_NODE_HH_INCLUDED__ #include <google/protobuf/message.h> #include <memory> #include <mutex> #include <string> #include "ignition/transport/NodePrivate.hh" #include "ignition/transport/Packet.hh" #include "ignition/transport/SubscriptionHandler.hh" #include "ignition/transport/TransportTypes.hh" namespace ignition { namespace transport { /// \brief A transport node to send and receive data. class Node { /// \brief Constructor. /// \param[in] _verbose true for enabling verbose mode. public: Node(bool _verbose = true); /// \brief Destructor. public: virtual ~Node(); /// \brief Advertise a new service. /// \param[in] _topic Topic to be advertised. /// \return 0 when success. public: int Advertise(const std::string &_topic); /// \brief Unadvertise a new service. /// \param[in] _topic Topic to be unadvertised. /// \return 0 when success. public: int UnAdvertise(const std::string &_topic); /// \ Publish data. /// \param[in] _topic Topic to be published. /// \param[in] _message protobuf message. /// \return 0 when success. public: int Publish(const std::string &_topic, const transport::ProtoMsg &_msg); /// \brief Subscribe to a topic registering a callback. /// \param[in] _topic Topic to be subscribed. /// \param[in] _cb Pointer to the callback function. /// \return 0 when success. public: template<class T> int Subscribe( const std::string &_topic, void(*_cb)(const std::string &, const T &)) { std::lock_guard<std::mutex> lock(this->dataPtr->mutex); // Create a new subscription handler. std::shared_ptr<SubscriptionHandler<T>> subscrHandlerPtr( new SubscriptionHandler<T>); // Insert the callback into the handler. subscrHandlerPtr->SetCallback(_cb); // Store the subscription handler. Each subscription handler is // associated with a topic. When the receiving thread gets new data, // it will recover the subscription handler associated to the topic and // will invoke the callback. this->dataPtr->topics.AddSubscriptionHandler(_topic, subscrHandlerPtr); // I'm now subsribed to the topic. this->dataPtr->topics.SetSubscribed(_topic, true); // Discover the list of nodes that publish on the topic. return this->dataPtr->SendSubscribeMsg(transport::SubType, _topic); } /// \brief Subscribe to a topic registering a callback. /// \param[in] _topic Topic to be unsubscribed. /// \return 0 when success. public: int UnSubscribe(const std::string &_topic); /// \internal /// \brief Shared pointer to private data. protected: NodePrivatePtr dataPtr; }; } } #endif <commit_msg>Verbose false.<commit_after>/* * Copyright (C) 2014 Open Source Robotics Foundation * * 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 __IGN_TRANSPORT_NODE_HH_INCLUDED__ #define __IGN_TRANSPORT_NODE_HH_INCLUDED__ #include <google/protobuf/message.h> #include <memory> #include <mutex> #include <string> #include "ignition/transport/NodePrivate.hh" #include "ignition/transport/Packet.hh" #include "ignition/transport/SubscriptionHandler.hh" #include "ignition/transport/TransportTypes.hh" namespace ignition { namespace transport { /// \brief A transport node to send and receive data. class Node { /// \brief Constructor. /// \param[in] _verbose true for enabling verbose mode. public: Node(bool _verbose = false); /// \brief Destructor. public: virtual ~Node(); /// \brief Advertise a new service. /// \param[in] _topic Topic to be advertised. /// \return 0 when success. public: int Advertise(const std::string &_topic); /// \brief Unadvertise a new service. /// \param[in] _topic Topic to be unadvertised. /// \return 0 when success. public: int UnAdvertise(const std::string &_topic); /// \ Publish data. /// \param[in] _topic Topic to be published. /// \param[in] _message protobuf message. /// \return 0 when success. public: int Publish(const std::string &_topic, const transport::ProtoMsg &_msg); /// \brief Subscribe to a topic registering a callback. /// \param[in] _topic Topic to be subscribed. /// \param[in] _cb Pointer to the callback function. /// \return 0 when success. public: template<class T> int Subscribe( const std::string &_topic, void(*_cb)(const std::string &, const T &)) { std::lock_guard<std::mutex> lock(this->dataPtr->mutex); // Create a new subscription handler. std::shared_ptr<SubscriptionHandler<T>> subscrHandlerPtr( new SubscriptionHandler<T>); // Insert the callback into the handler. subscrHandlerPtr->SetCallback(_cb); // Store the subscription handler. Each subscription handler is // associated with a topic. When the receiving thread gets new data, // it will recover the subscription handler associated to the topic and // will invoke the callback. this->dataPtr->topics.AddSubscriptionHandler(_topic, subscrHandlerPtr); // I'm now subsribed to the topic. this->dataPtr->topics.SetSubscribed(_topic, true); // Discover the list of nodes that publish on the topic. return this->dataPtr->SendSubscribeMsg(transport::SubType, _topic); } /// \brief Subscribe to a topic registering a callback. /// \param[in] _topic Topic to be unsubscribed. /// \return 0 when success. public: int UnSubscribe(const std::string &_topic); /// \internal /// \brief Shared pointer to private data. protected: NodePrivatePtr dataPtr; }; } } #endif <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_GRID_PIXEL_HPP #define MAPNIK_GRID_PIXEL_HPP #include "agg_basics.h" namespace mapnik { //==================================================================gray16 struct gray16 { using value_type = agg::int16u; using calc_type = agg::int32u; using long_type = agg::int64 ; enum base_scale_e { base_shift = 16, base_scale = 1 << base_shift, base_mask = base_scale - 1 }; using self_type = gray16; value_type v; value_type a; //-------------------------------------------------------------------- gray16() {} //-------------------------------------------------------------------- gray16(unsigned v_, unsigned a_=base_mask) : v(agg::int16u(v_)), a(agg::int16u(a_)) {} //-------------------------------------------------------------------- gray16(const self_type& c, unsigned a_) : v(c.v), a(value_type(a_)) {} //-------------------------------------------------------------------- void clear() { v = a = 0; } //-------------------------------------------------------------------- const self_type& transparent() { a = 0; return *this; } //-------------------------------------------------------------------- void opacity(double a_) { if(a_ < 0.0) a_ = 0.0; if(a_ > 1.0) a_ = 1.0; a = (value_type)agg::uround(a_ * double(base_mask)); } //-------------------------------------------------------------------- double opacity() const { return double(a) / double(base_mask); } //-------------------------------------------------------------------- const self_type& premultiply() { if(a == base_mask) return *this; if(a == 0) { v = 0; return *this; } v = value_type((calc_type(v) * a) >> base_shift); return *this; } //-------------------------------------------------------------------- const self_type& premultiply(unsigned a_) { if(a == base_mask && a_ >= base_mask) return *this; if(a == 0 || a_ == 0) { v = a = 0; return *this; } calc_type v_ = (calc_type(v) * a_) / a; v = value_type((v_ > a_) ? a_ : v_); a = value_type(a_); return *this; } //-------------------------------------------------------------------- const self_type& demultiply() { if(a == base_mask) return *this; if(a == 0) { v = 0; return *this; } calc_type v_ = (calc_type(v) * base_mask) / a; v = value_type((v_ > base_mask) ? base_mask : v_); return *this; } //-------------------------------------------------------------------- self_type gradient(self_type c, double k) const { self_type ret; calc_type ik = agg::uround(k * base_scale); ret.v = value_type(calc_type(v) + (((calc_type(c.v) - v) * ik) >> base_shift)); ret.a = value_type(calc_type(a) + (((calc_type(c.a) - a) * ik) >> base_shift)); return ret; } //-------------------------------------------------------------------- AGG_INLINE void add(const self_type& c, unsigned cover) { calc_type cv, ca; if(cover == agg::cover_mask) { if(c.a == base_mask) { *this = c; } else { cv = v + c.v; v = (cv > calc_type(base_mask)) ? calc_type(base_mask) : cv; ca = a + c.a; a = (ca > calc_type(base_mask)) ? calc_type(base_mask) : ca; } } else { cv = v + ((c.v * cover + agg::cover_mask/2) >> agg::cover_shift); ca = a + ((c.a * cover + agg::cover_mask/2) >> agg::cover_shift); v = (cv > calc_type(base_mask)) ? calc_type(base_mask) : cv; a = (ca > calc_type(base_mask)) ? calc_type(base_mask) : ca; } } //-------------------------------------------------------------------- static self_type no_color() { return self_type(0,0); } }; //==================================================================gray32 struct gray32 { using value_type = agg::int32; using calc_type = agg::int64u; using long_type = agg::int64 ; // NOTE: don't touch this enum since enums cannot be // 64 bit and we need to ensure that alpha = base_mask // in grid_pixfmt.hpp#blend_hiline#l256 // otherwise code will get invoked that breaks // with 32 bit or 64 bit ints (blender_gray::blend_pix) enum base_scale_e { base_shift = 16, base_scale = 1 << base_shift, base_mask = base_scale - 1 }; using self_type = gray32; value_type v; value_type a; //-------------------------------------------------------------------- gray32() {} //-------------------------------------------------------------------- gray32(value_type v_, unsigned a_=base_mask) : v(v_), a(value_type(a_)) {} //-------------------------------------------------------------------- gray32(const self_type& c, unsigned a_) : v(c.v), a(value_type(a_)) {} //-------------------------------------------------------------------- void clear() { v = a = 0; } //-------------------------------------------------------------------- const self_type& transparent() { a = 0; return *this; } //-------------------------------------------------------------------- void opacity(double a_) { if(a_ < 0.0) a_ = 0.0; if(a_ > 1.0) a_ = 1.0; a = (value_type)agg::uround(a_ * double(base_mask)); } //-------------------------------------------------------------------- double opacity() const { return double(a) / double(base_mask); } //-------------------------------------------------------------------- const self_type& premultiply() { if(a == base_mask) return *this; if(a == 0) { v = 0; return *this; } v = value_type((calc_type(v) * a) >> base_shift); return *this; } //-------------------------------------------------------------------- const self_type& premultiply(unsigned a_) { if(a == base_mask && a_ >= base_mask) return *this; if(a == 0 || a_ == 0) { v = a = 0; return *this; } calc_type v_ = (calc_type(v) * a_) / a; v = value_type((v_ > a_) ? a_ : v_); a = value_type(a_); return *this; } //-------------------------------------------------------------------- const self_type& demultiply() { if(a == base_mask) return *this; if(a == 0) { v = 0; return *this; } calc_type v_ = (calc_type(v) * base_mask) / a; v = value_type((v_ > base_mask) ? base_mask : v_); return *this; } //-------------------------------------------------------------------- self_type gradient(self_type c, double k) const { self_type ret; calc_type ik = agg::uround(k * base_scale); ret.v = value_type(calc_type(v) + (((calc_type(c.v) - v) * ik) >> base_shift)); ret.a = value_type(calc_type(a) + (((calc_type(c.a) - a) * ik) >> base_shift)); return ret; } //-------------------------------------------------------------------- AGG_INLINE void add(const self_type& c, unsigned cover) { calc_type cv, ca; if(cover == agg::cover_mask) { if(c.a == base_mask) { *this = c; } else { cv = v + c.v; v = (cv > calc_type(base_mask)) ? calc_type(base_mask) : cv; ca = a + c.a; a = (ca > calc_type(base_mask)) ? calc_type(base_mask) : ca; } } else { cv = v + ((c.v * cover + agg::cover_mask/2) >> agg::cover_shift); ca = a + ((c.a * cover + agg::cover_mask/2) >> agg::cover_shift); v = (cv > calc_type(base_mask)) ? calc_type(base_mask) : cv; a = (ca > calc_type(base_mask)) ? calc_type(base_mask) : ca; } } //-------------------------------------------------------------------- static self_type no_color() { return self_type(0,0); } }; //==================================================================gray64 struct gray64 { using value_type = agg::int64; using calc_type = agg::int64u; using long_type = agg::int64 ; // NOTE: don't touch this enum since enums cannot be // 64 bit and we need to ensure that alpha = base_mask // in grid_pixfmt.hpp#blend_hiline#l256 // otherwise code will get invoked that breaks // with 32 bit or 64 bit ints (blender_gray::blend_pix) enum base_scale_e { base_shift = 16, base_scale = 1 << base_shift, base_mask = base_scale - 1 }; using self_type = gray64; value_type v; value_type a; //-------------------------------------------------------------------- gray64() {} //-------------------------------------------------------------------- gray64(value_type v_, unsigned a_=base_mask) : v(v_), a(value_type(a_)) {} //-------------------------------------------------------------------- gray64(const self_type& c, unsigned a_) : v(c.v), a(value_type(a_)) {} //-------------------------------------------------------------------- void clear() { v = a = 0; } //-------------------------------------------------------------------- const self_type& transparent() { a = 0; return *this; } //-------------------------------------------------------------------- void opacity(double a_) { if(a_ < 0.0) a_ = 0.0; if(a_ > 1.0) a_ = 1.0; a = (value_type)agg::uround(a_ * double(base_mask)); } //-------------------------------------------------------------------- double opacity() const { return double(a) / double(base_mask); } //-------------------------------------------------------------------- const self_type& premultiply() { if(a == base_mask) return *this; if(a == 0) { v = 0; return *this; } v = value_type((calc_type(v) * a) >> base_shift); return *this; } //-------------------------------------------------------------------- const self_type& premultiply(unsigned a_) { if(a == base_mask && a_ >= base_mask) return *this; if(a == 0 || a_ == 0) { v = a = 0; return *this; } calc_type v_ = (calc_type(v) * a_) / a; v = value_type((v_ > a_) ? a_ : v_); a = value_type(a_); return *this; } //-------------------------------------------------------------------- const self_type& demultiply() { if(a == base_mask) return *this; if(a == 0) { v = 0; return *this; } calc_type v_ = (calc_type(v) * base_mask) / a; v = value_type((v_ > base_mask) ? base_mask : v_); return *this; } //-------------------------------------------------------------------- self_type gradient(self_type c, double k) const { self_type ret; calc_type ik = agg::uround(k * base_scale); ret.v = value_type(calc_type(v) + (((calc_type(c.v) - v) * ik) >> base_shift)); ret.a = value_type(calc_type(a) + (((calc_type(c.a) - a) * ik) >> base_shift)); return ret; } //-------------------------------------------------------------------- AGG_INLINE void add(const self_type& c, unsigned cover) { calc_type cv, ca; if(cover == agg::cover_mask) { if(c.a == base_mask) { *this = c; } else { cv = v + c.v; v = (cv > calc_type(base_mask)) ? calc_type(base_mask) : cv; ca = a + c.a; a = (ca > calc_type(base_mask)) ? calc_type(base_mask) : ca; } } else { cv = v + ((c.v * cover + agg::cover_mask/2) >> agg::cover_shift); ca = a + ((c.a * cover + agg::cover_mask/2) >> agg::cover_shift); v = (cv > calc_type(base_mask)) ? calc_type(base_mask) : cv; a = (ca > calc_type(base_mask)) ? calc_type(base_mask) : ca; } } //-------------------------------------------------------------------- static self_type no_color() { return self_type(0,0); } }; } #endif <commit_msg>remove unused code<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_GRID_PIXEL_HPP #define MAPNIK_GRID_PIXEL_HPP #include "agg_basics.h" namespace mapnik { //==================================================================gray16 struct gray16 { using value_type = agg::int16u; using calc_type = agg::int32u; using long_type = agg::int64 ; enum base_scale_e { base_shift = 16, base_scale = 1 << base_shift, base_mask = base_scale - 1 }; using self_type = gray16; value_type v; value_type a; //-------------------------------------------------------------------- gray16() {} //-------------------------------------------------------------------- gray16(unsigned v_, unsigned a_=base_mask) : v(agg::int16u(v_)), a(agg::int16u(a_)) {} //-------------------------------------------------------------------- gray16(const self_type& c, unsigned a_) : v(c.v), a(value_type(a_)) {} //-------------------------------------------------------------------- void clear() { v = a = 0; } //-------------------------------------------------------------------- const self_type& transparent() { a = 0; return *this; } //-------------------------------------------------------------------- const self_type& premultiply() { if(a == base_mask) return *this; if(a == 0) { v = 0; return *this; } v = value_type((calc_type(v) * a) >> base_shift); return *this; } //-------------------------------------------------------------------- const self_type& premultiply(unsigned a_) { if(a == base_mask && a_ >= base_mask) return *this; if(a == 0 || a_ == 0) { v = a = 0; return *this; } calc_type v_ = (calc_type(v) * a_) / a; v = value_type((v_ > a_) ? a_ : v_); a = value_type(a_); return *this; } //-------------------------------------------------------------------- const self_type& demultiply() { if(a == base_mask) return *this; if(a == 0) { v = 0; return *this; } calc_type v_ = (calc_type(v) * base_mask) / a; v = value_type((v_ > base_mask) ? base_mask : v_); return *this; } //-------------------------------------------------------------------- self_type gradient(self_type c, double k) const { self_type ret; calc_type ik = agg::uround(k * base_scale); ret.v = value_type(calc_type(v) + (((calc_type(c.v) - v) * ik) >> base_shift)); ret.a = value_type(calc_type(a) + (((calc_type(c.a) - a) * ik) >> base_shift)); return ret; } //-------------------------------------------------------------------- AGG_INLINE void add(const self_type& c, unsigned cover) { calc_type cv, ca; if(cover == agg::cover_mask) { if(c.a == base_mask) { *this = c; } else { cv = v + c.v; v = (cv > calc_type(base_mask)) ? calc_type(base_mask) : cv; ca = a + c.a; a = (ca > calc_type(base_mask)) ? calc_type(base_mask) : ca; } } else { cv = v + ((c.v * cover + agg::cover_mask/2) >> agg::cover_shift); ca = a + ((c.a * cover + agg::cover_mask/2) >> agg::cover_shift); v = (cv > calc_type(base_mask)) ? calc_type(base_mask) : cv; a = (ca > calc_type(base_mask)) ? calc_type(base_mask) : ca; } } //-------------------------------------------------------------------- static self_type no_color() { return self_type(0,0); } }; //==================================================================gray32 struct gray32 { using value_type = agg::int32; using calc_type = agg::int64u; using long_type = agg::int64 ; // NOTE: don't touch this enum since enums cannot be // 64 bit and we need to ensure that alpha = base_mask // in grid_pixfmt.hpp#blend_hiline#l256 // otherwise code will get invoked that breaks // with 32 bit or 64 bit ints (blender_gray::blend_pix) enum base_scale_e { base_shift = 16, base_scale = 1 << base_shift, base_mask = base_scale - 1 }; using self_type = gray32; value_type v; value_type a; //-------------------------------------------------------------------- gray32() {} //-------------------------------------------------------------------- gray32(value_type v_, unsigned a_=base_mask) : v(v_), a(value_type(a_)) {} //-------------------------------------------------------------------- gray32(const self_type& c, unsigned a_) : v(c.v), a(value_type(a_)) {} //-------------------------------------------------------------------- void clear() { v = a = 0; } //-------------------------------------------------------------------- const self_type& transparent() { a = 0; return *this; } //-------------------------------------------------------------------- const self_type& premultiply() { if(a == base_mask) return *this; if(a == 0) { v = 0; return *this; } v = value_type((calc_type(v) * a) >> base_shift); return *this; } //-------------------------------------------------------------------- const self_type& premultiply(unsigned a_) { if(a == base_mask && a_ >= base_mask) return *this; if(a == 0 || a_ == 0) { v = a = 0; return *this; } calc_type v_ = (calc_type(v) * a_) / a; v = value_type((v_ > a_) ? a_ : v_); a = value_type(a_); return *this; } //-------------------------------------------------------------------- const self_type& demultiply() { if(a == base_mask) return *this; if(a == 0) { v = 0; return *this; } calc_type v_ = (calc_type(v) * base_mask) / a; v = value_type((v_ > base_mask) ? base_mask : v_); return *this; } //-------------------------------------------------------------------- self_type gradient(self_type c, double k) const { self_type ret; calc_type ik = agg::uround(k * base_scale); ret.v = value_type(calc_type(v) + (((calc_type(c.v) - v) * ik) >> base_shift)); ret.a = value_type(calc_type(a) + (((calc_type(c.a) - a) * ik) >> base_shift)); return ret; } //-------------------------------------------------------------------- AGG_INLINE void add(const self_type& c, unsigned cover) { calc_type cv, ca; if(cover == agg::cover_mask) { if(c.a == base_mask) { *this = c; } else { cv = v + c.v; v = (cv > calc_type(base_mask)) ? calc_type(base_mask) : cv; ca = a + c.a; a = (ca > calc_type(base_mask)) ? calc_type(base_mask) : ca; } } else { cv = v + ((c.v * cover + agg::cover_mask/2) >> agg::cover_shift); ca = a + ((c.a * cover + agg::cover_mask/2) >> agg::cover_shift); v = (cv > calc_type(base_mask)) ? calc_type(base_mask) : cv; a = (ca > calc_type(base_mask)) ? calc_type(base_mask) : ca; } } //-------------------------------------------------------------------- static self_type no_color() { return self_type(0,0); } }; //==================================================================gray64 struct gray64 { using value_type = agg::int64; using calc_type = agg::int64u; using long_type = agg::int64 ; // NOTE: don't touch this enum since enums cannot be // 64 bit and we need to ensure that alpha = base_mask // in grid_pixfmt.hpp#blend_hiline#l256 // otherwise code will get invoked that breaks // with 32 bit or 64 bit ints (blender_gray::blend_pix) enum base_scale_e { base_shift = 16, base_scale = 1 << base_shift, base_mask = base_scale - 1 }; using self_type = gray64; value_type v; value_type a; //-------------------------------------------------------------------- gray64() {} //-------------------------------------------------------------------- gray64(value_type v_, unsigned a_=base_mask) : v(v_), a(value_type(a_)) {} //-------------------------------------------------------------------- gray64(const self_type& c, unsigned a_) : v(c.v), a(value_type(a_)) {} //-------------------------------------------------------------------- void clear() { v = a = 0; } //-------------------------------------------------------------------- const self_type& transparent() { a = 0; return *this; } //-------------------------------------------------------------------- const self_type& premultiply() { if(a == base_mask) return *this; if(a == 0) { v = 0; return *this; } v = value_type((calc_type(v) * a) >> base_shift); return *this; } //-------------------------------------------------------------------- const self_type& premultiply(unsigned a_) { if(a == base_mask && a_ >= base_mask) return *this; if(a == 0 || a_ == 0) { v = a = 0; return *this; } calc_type v_ = (calc_type(v) * a_) / a; v = value_type((v_ > a_) ? a_ : v_); a = value_type(a_); return *this; } //-------------------------------------------------------------------- const self_type& demultiply() { if(a == base_mask) return *this; if(a == 0) { v = 0; return *this; } calc_type v_ = (calc_type(v) * base_mask) / a; v = value_type((v_ > base_mask) ? base_mask : v_); return *this; } //-------------------------------------------------------------------- self_type gradient(self_type c, double k) const { self_type ret; calc_type ik = agg::uround(k * base_scale); ret.v = value_type(calc_type(v) + (((calc_type(c.v) - v) * ik) >> base_shift)); ret.a = value_type(calc_type(a) + (((calc_type(c.a) - a) * ik) >> base_shift)); return ret; } //-------------------------------------------------------------------- AGG_INLINE void add(const self_type& c, unsigned cover) { calc_type cv, ca; if(cover == agg::cover_mask) { if(c.a == base_mask) { *this = c; } else { cv = v + c.v; v = (cv > calc_type(base_mask)) ? calc_type(base_mask) : cv; ca = a + c.a; a = (ca > calc_type(base_mask)) ? calc_type(base_mask) : ca; } } else { cv = v + ((c.v * cover + agg::cover_mask/2) >> agg::cover_shift); ca = a + ((c.a * cover + agg::cover_mask/2) >> agg::cover_shift); v = (cv > calc_type(base_mask)) ? calc_type(base_mask) : cv; a = (ca > calc_type(base_mask)) ? calc_type(base_mask) : ca; } } //-------------------------------------------------------------------- static self_type no_color() { return self_type(0,0); } }; } #endif <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2014 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_HIT_TEST_FILTER_HPP #define MAPNIK_HIT_TEST_FILTER_HPP // mapnik #include <mapnik/feature.hpp> #include <mapnik/geometry.hpp> #include <mapnik/geom_util.hpp> namespace mapnik { namespace detail { inline bool pip(double x0, double y0, double x1, double y1, double x, double y) { return ((((y1 <= y) && (y < y0)) || ((y0 <= y) && (y < y1))) && (x < (x0 - x1) * (y - y1) / (y0 - y1) + x1)); } struct hit_test_visitor { hit_test_visitor(double x, double y, double tol) : x_(x), y_(y), tol_(tol) {} bool operator() (geometry::geometry_empty const& ) const { return false; } bool operator() (geometry::point const& geom) const { return distance(geom.x, geom.y, x_, y_) <= tol_; } bool operator() (geometry::multi_point const& geom) const { for (auto const& pt : geom) { if (distance(pt.x, pt.y, x_, y_) <= tol_) return true; } return false; } bool operator() (geometry::line_string const& geom) const { std::size_t num_points = geom.num_points(); if (num_points > 1) { for (std::size_t i = 1; i < num_points; ++i) { auto const& pt0 = geom[i-1]; auto const& pt1 = geom[i]; double distance = point_to_segment_distance(x_,y_,pt0.x,pt0.y,pt1.x,pt1.y); if (distance < tol_) return true; } } return false; } bool operator() (geometry::multi_line_string const& geom) const { for (auto const& line: geom) { if (operator()(line)) return true; } return false; } bool operator() (geometry::polygon const& geom) const { auto const& exterior = geom.exterior_ring; std::size_t num_points = exterior.num_points(); if (num_points < 2) return false; bool inside = false; for (std::size_t i = 1; i < num_points; ++i) { auto const& pt0 = exterior[i-1]; auto const& pt1 = exterior[i]; // todo - account for tolerance if (pip(pt0.x,pt0.y,pt1.x,pt1.y,x_,y_)) { inside = true; break; } } if (!inside) return false; for (auto const& ring : geom.interior_rings) { std::size_t num_interior_points = ring.size(); for (std::size_t j = 1; j < num_interior_points; ++j) { auto const& pt0 = ring[j-1]; auto const& pt1 = ring[j]; if (pip(pt0.x,pt0.y,pt1.x,pt1.y,x_,y_)) { // TODO - account for tolerance inside=!inside; break; } } } return inside; } bool operator() (geometry::multi_polygon const& geom) const { for (auto const& poly: geom) { if (operator()(poly)) return true; } return false; } bool operator() (geometry::geometry_collection const& collection) const { for (auto const& geom: collection) { if (mapnik::util::apply_visitor((*this),geom)) return true; } return false; } double x_; double y_; double tol_; }; } inline bool hit_test(mapnik::geometry::geometry const& geom, double x, double y, double tol) { return mapnik::util::apply_visitor(detail::hit_test_visitor(x,y,tol), geom); } class hit_test_filter { public: hit_test_filter(double x, double y, double tol) : x_(x), y_(y), tol_(tol) {} bool pass(feature_impl const& feature) { return hit_test(feature.get_geometry(),x_,y_,tol_); } private: double x_; double y_; double tol_; }; } #endif // MAPNIK_HIT_TEST_FILTER_HPP <commit_msg>Corrected ray casting check in polygon hit test<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2014 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_HIT_TEST_FILTER_HPP #define MAPNIK_HIT_TEST_FILTER_HPP // mapnik #include <mapnik/feature.hpp> #include <mapnik/geometry.hpp> #include <mapnik/geom_util.hpp> namespace mapnik { namespace detail { inline bool pip(double x0, double y0, double x1, double y1, double x, double y) { return ((((y1 <= y) && (y < y0)) || ((y0 <= y) && (y < y1))) && (x < (x0 - x1) * (y - y1) / (y0 - y1) + x1)); } struct hit_test_visitor { hit_test_visitor(double x, double y, double tol) : x_(x), y_(y), tol_(tol) {} bool operator() (geometry::geometry_empty const& ) const { return false; } bool operator() (geometry::point const& geom) const { return distance(geom.x, geom.y, x_, y_) <= tol_; } bool operator() (geometry::multi_point const& geom) const { for (auto const& pt : geom) { if (distance(pt.x, pt.y, x_, y_) <= tol_) return true; } return false; } bool operator() (geometry::line_string const& geom) const { std::size_t num_points = geom.num_points(); if (num_points > 1) { for (std::size_t i = 1; i < num_points; ++i) { auto const& pt0 = geom[i-1]; auto const& pt1 = geom[i]; double distance = point_to_segment_distance(x_,y_,pt0.x,pt0.y,pt1.x,pt1.y); if (distance < tol_) return true; } } return false; } bool operator() (geometry::multi_line_string const& geom) const { for (auto const& line: geom) { if (operator()(line)) return true; } return false; } bool operator() (geometry::polygon const& geom) const { auto const& exterior = geom.exterior_ring; std::size_t num_points = exterior.num_points(); if (num_points < 2) return false; bool inside = false; for (std::size_t i = 1; i < num_points; ++i) { auto const& pt0 = exterior[i-1]; auto const& pt1 = exterior[i]; // todo - account for tolerance if (pip(pt0.x,pt0.y,pt1.x,pt1.y,x_,y_)) { inside = !inside; } } if (!inside) return false; for (auto const& ring : geom.interior_rings) { std::size_t num_interior_points = ring.size(); for (std::size_t j = 1; j < num_interior_points; ++j) { auto const& pt0 = ring[j-1]; auto const& pt1 = ring[j]; if (pip(pt0.x,pt0.y,pt1.x,pt1.y,x_,y_)) { // TODO - account for tolerance inside=!inside; } } } return inside; } bool operator() (geometry::multi_polygon const& geom) const { for (auto const& poly: geom) { if (operator()(poly)) return true; } return false; } bool operator() (geometry::geometry_collection const& collection) const { for (auto const& geom: collection) { if (mapnik::util::apply_visitor((*this),geom)) return true; } return false; } double x_; double y_; double tol_; }; } inline bool hit_test(mapnik::geometry::geometry const& geom, double x, double y, double tol) { return mapnik::util::apply_visitor(detail::hit_test_visitor(x,y,tol), geom); } class hit_test_filter { public: hit_test_filter(double x, double y, double tol) : x_(x), y_(y), tol_(tol) {} bool pass(feature_impl const& feature) { return hit_test(feature.get_geometry(),x_,y_,tol_); } private: double x_; double y_; double tol_; }; } #endif // MAPNIK_HIT_TEST_FILTER_HPP <|endoftext|>
<commit_before>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. 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. */ /* * Copyright (C) 2016 ScyllaDB. */ #pragma once #include <iosfwd> #include <array> #include <sys/socket.h> #include <netinet/ip.h> #include <seastar/net/byteorder.hh> namespace seastar { namespace net { class inet_address; } struct ipv4_addr; struct ipv6_addr; class socket_address { public: union { ::sockaddr_storage sas; ::sockaddr sa; ::sockaddr_in in; ::sockaddr_in6 in6; } u; socket_address(const sockaddr_in& sa) { u.in = sa; } socket_address(const sockaddr_in6& sa) { u.in6 = sa; } socket_address(uint16_t); socket_address(ipv4_addr); socket_address(const ipv6_addr&); socket_address(const net::inet_address&, uint16_t p = 0); socket_address(); ::sockaddr& as_posix_sockaddr() { return u.sa; } ::sockaddr_in& as_posix_sockaddr_in() { return u.in; } ::sockaddr_in6& as_posix_sockaddr_in6() { return u.in6; } const ::sockaddr& as_posix_sockaddr() const { return u.sa; } const ::sockaddr_in& as_posix_sockaddr_in() const { return u.in; } const ::sockaddr_in6& as_posix_sockaddr_in6() const { return u.in6; } socket_address(uint32_t, uint16_t p = 0); net::inet_address addr() const; ::in_port_t port() const; bool operator==(const socket_address&) const; }; std::ostream& operator<<(std::ostream&, const socket_address&); enum class transport { TCP = IPPROTO_TCP, SCTP = IPPROTO_SCTP }; struct ipv4_addr { uint32_t ip; uint16_t port; ipv4_addr() : ip(0), port(0) {} ipv4_addr(uint32_t ip, uint16_t port) : ip(ip), port(port) {} ipv4_addr(uint16_t port) : ip(0), port(port) {} ipv4_addr(const std::string &addr); ipv4_addr(const std::string &addr, uint16_t port); ipv4_addr(const net::inet_address&, uint16_t); ipv4_addr(const socket_address &); ipv4_addr(const ::in_addr&, uint16_t = 0); bool is_ip_unspecified() const { return ip == 0; } bool is_port_unspecified() const { return port == 0; } }; struct ipv6_addr { using ipv6_bytes = std::array<uint8_t, 16>; ipv6_bytes ip; uint16_t port; ipv6_addr(const ipv6_bytes&, uint16_t port = 0); ipv6_addr(uint16_t port = 0); ipv6_addr(const std::string&); ipv6_addr(const std::string&, uint16_t port); ipv6_addr(const net::inet_address&, uint16_t = 0); ipv6_addr(const ::in6_addr&, uint16_t = 0); ipv6_addr(const ::sockaddr_in6&); ipv6_addr(const socket_address&); bool is_ip_unspecified() const; bool is_port_unspecified() const { return port == 0; } }; std::ostream& operator<<(std::ostream&, const ipv4_addr&); std::ostream& operator<<(std::ostream&, const ipv6_addr&); } namespace std { template<> struct hash<seastar::socket_address> { size_t operator()(const seastar::socket_address&) const; }; } <commit_msg>socket_address: Add != operator<commit_after>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. 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. */ /* * Copyright (C) 2016 ScyllaDB. */ #pragma once #include <iosfwd> #include <array> #include <sys/socket.h> #include <netinet/ip.h> #include <seastar/net/byteorder.hh> namespace seastar { namespace net { class inet_address; } struct ipv4_addr; struct ipv6_addr; class socket_address { public: union { ::sockaddr_storage sas; ::sockaddr sa; ::sockaddr_in in; ::sockaddr_in6 in6; } u; socket_address(const sockaddr_in& sa) { u.in = sa; } socket_address(const sockaddr_in6& sa) { u.in6 = sa; } socket_address(uint16_t); socket_address(ipv4_addr); socket_address(const ipv6_addr&); socket_address(const net::inet_address&, uint16_t p = 0); socket_address(); ::sockaddr& as_posix_sockaddr() { return u.sa; } ::sockaddr_in& as_posix_sockaddr_in() { return u.in; } ::sockaddr_in6& as_posix_sockaddr_in6() { return u.in6; } const ::sockaddr& as_posix_sockaddr() const { return u.sa; } const ::sockaddr_in& as_posix_sockaddr_in() const { return u.in; } const ::sockaddr_in6& as_posix_sockaddr_in6() const { return u.in6; } socket_address(uint32_t, uint16_t p = 0); net::inet_address addr() const; ::in_port_t port() const; bool operator==(const socket_address&) const; bool operator!=(const socket_address& a) const { return !(*this == a); } }; std::ostream& operator<<(std::ostream&, const socket_address&); enum class transport { TCP = IPPROTO_TCP, SCTP = IPPROTO_SCTP }; struct ipv4_addr { uint32_t ip; uint16_t port; ipv4_addr() : ip(0), port(0) {} ipv4_addr(uint32_t ip, uint16_t port) : ip(ip), port(port) {} ipv4_addr(uint16_t port) : ip(0), port(port) {} ipv4_addr(const std::string &addr); ipv4_addr(const std::string &addr, uint16_t port); ipv4_addr(const net::inet_address&, uint16_t); ipv4_addr(const socket_address &); ipv4_addr(const ::in_addr&, uint16_t = 0); bool is_ip_unspecified() const { return ip == 0; } bool is_port_unspecified() const { return port == 0; } }; struct ipv6_addr { using ipv6_bytes = std::array<uint8_t, 16>; ipv6_bytes ip; uint16_t port; ipv6_addr(const ipv6_bytes&, uint16_t port = 0); ipv6_addr(uint16_t port = 0); ipv6_addr(const std::string&); ipv6_addr(const std::string&, uint16_t port); ipv6_addr(const net::inet_address&, uint16_t = 0); ipv6_addr(const ::in6_addr&, uint16_t = 0); ipv6_addr(const ::sockaddr_in6&); ipv6_addr(const socket_address&); bool is_ip_unspecified() const; bool is_port_unspecified() const { return port == 0; } }; std::ostream& operator<<(std::ostream&, const ipv4_addr&); std::ostream& operator<<(std::ostream&, const ipv6_addr&); } namespace std { template<> struct hash<seastar::socket_address> { size_t operator()(const seastar::socket_address&) const; }; } <|endoftext|>
<commit_before>#pragma once // blas_l1.hpp: BLAS Level 1 functions // // Copyright (C) 2017-2021 Stillwater Supercomputing, Inc. // // This file is part of the universal numbers project, which is released under an MIT Open Source license. #include <cmath> #include <universal/number/posit/posit> #include <universal/blas/vector.hpp> namespace sw { namespace universal { namespace blas { // 1-norm of a vector: sum of magnitudes of the vector elements, default increment stride is 1 template<typename Vector> typename Vector::value_type asum(size_t n, const Vector& x, size_t incx = 1) { typename Vector::value_type sum = 0; size_t ix; for (ix = 0; ix < n; ix += incx) { sum += (x[ix] < 0 ? -x[ix] : x[ix]); } return sum; } // sum of the vector elements, default increment stride is 1 template<typename Vector> typename Vector::value_type sum(const Vector& x) { typename Vector::value_type sum = 0; size_t ix; for (ix = 0; ix < size(x); ++ix) { sum += x[ix]; } return sum; } // a time x plus y template<typename Scalar, typename Vector> void axpy(size_t n, Scalar a, const Vector& x, size_t incx, Vector& y, size_t incy) { size_t cnt, ix, iy; for (cnt = 0, ix = 0, iy = 0; cnt < n && ix < size(x) && iy < size(y); ++cnt, ix += incx, iy += incy) { y[iy] += a * x[ix]; } } // vector copy template<typename Vector> void copy(size_t n, const Vector& x, size_t incx, Vector& y, size_t incy) { size_t cnt, ix, iy; for (cnt = 0, ix = 0, iy = 0; cnt < n && ix < size(x) && iy < size(y); ++cnt, ix += incx, iy += incy) { y[iy] = x[ix]; } } // adapter for STL vectors template<typename Scalar> auto size(const std::vector<Scalar>& v) { return v.size(); } // dot product: the operator vector::x[index] is limited to uint32_t, so the arguments are limited to uint32_t as well // The library does support arbitrary posit configuration conversions, but to simplify the // behavior of the dot product, the element type of the vectors x and y are declared to be the same. // TODO: investigate if the vector<> index is always a 32bit entity? template<typename Vector> typename Vector::value_type dot(size_t n, const Vector& x, size_t incx, const Vector& y, size_t incy) { using value_type = typename Vector::value_type; value_type sum_of_products = value_type(0); size_t cnt, ix, iy; for (cnt = 0, ix = 0, iy = 0; cnt < n && ix < size(x) && iy < size(y); ++cnt, ix += incx, iy += incy) { sum_of_products += x[ix] * y[iy]; } return sum_of_products; } // specialized dot product assuming constant stride template<typename Vector> typename Vector::value_type dot(const Vector& x, const Vector& y) { using value_type = typename Vector::value_type; value_type sum_of_products = value_type(0); size_t nx = size(x); if (nx <= size(y)) { for (size_t i = 0; i < nx; ++i) { sum_of_products += x[i] * y[i]; } } return sum_of_products; } // rotation of points in the plane template<typename Rotation, typename Vector> void rot(size_t n, Vector& x, size_t incx, Vector& y, size_t incy, Rotation c, Rotation s) { // x_i = c*x_i + s*y_i // y_i = c*y_i - s*x_i size_t cnt, ix, iy; for (cnt = 0, ix = 0, iy = 0; cnt < n && ix < size(x) && iy < size(y); ++cnt, ix += incx, iy += incy) { Rotation x_i = c * x[ix] + s * y[iy]; Rotation y_i = c * y[iy] - s * x[ix]; y[iy] = y_i; x[ix] = x_i; } } // compute parameters for a Givens rotation template<typename T> void rotg(T& a, T& b, T& c, T&s) { // Given Cartesian coordinates (a,b) of a point, return parameters c,s,r, and z associated with the Givens rotation. } // scale a vector template<typename Scalar, typename Vector> void scale(size_t n, Scalar alpha, Vector& x, size_t incx) { size_t cnt, ix; for (cnt = 0, ix = 0; cnt < n && ix < size(x); ix += incx) { x[ix] *= alpha; } } // swap two vectors template<typename Vector> void swap(size_t n, Vector& x, size_t incx, Vector& y, size_t incy) { size_t cnt, ix, iy; for (cnt = 0, ix = 0, iy = 0; cnt < n && ix < size(x) && iy < size(y); ++cnt, ix += incx, iy += incy) { typename Vector::value_type tmp = x[ix]; x[ix] = y[iy]; y[iy] = tmp; } } // find the index of the element with maximum absolute value template<typename Vector> size_t amax(size_t n, const Vector& x, size_t incx) { typename Vector::value_type running_max = -INFINITY; size_t ix, index; for (ix = 0; ix < size(x); ix += incx) { if (x[ix] > running_max) { index = ix; running_max = x[ix]; } } return index; } // find the index of the element with minimum absolute value template<typename Vector> size_t amin(size_t n, const Vector& x, size_t incx) { typename Vector::value_type running_min = INFINITY; size_t ix, index; for (ix = 0; ix < size(x); ix += incx) { if (x[ix] < running_min) { index = ix; running_min = x[ix]; } } return index; } // absolute value of a complex number template<typename T> T cabs(T z) { } // print a vector template<typename Vector> void strided_print(std::ostream& ostr, size_t n, Vector& x, size_t incx = 1) { size_t cnt, ix; for (cnt = 0, ix = 0; cnt < n && ix < size(x); ++cnt, ix += incx) { cnt == 0 ? ostr << "[" << x[ix] : ostr << ", " << x[ix]; } ostr << "]"; } } } } // namespace sw::universal::blas // free function norms // norm's of a vector template<typename Scalar, typename String> Scalar norm(const std::vector<Scalar>& v, const String s="one_norm"){ Scalar ans=0; if(strcmp(s, "one_norm")){ for(auto i:v){ ans+=abs(i); } } if(strcmp(s, "two_norm")){ for(auto i:v){ ans+=i*i; } ans=Scalar(sqrt(ans)); } if(strcmp(s, "inf_norm")){ for(auto i:v){ ans=Scalar(-1e9); ans=std::max(ans,abs(i)); } } if(strcmp(s, "frobenius_norm")){ for(auto i:v){ ans+=abs(i*i); } ans=Scalar(sqrt(ans)); } return ans; } // specializations for STL vectors template<typename Ty> Ty minValue(const std::vector<Ty>& samples) { typename std::vector<Ty>::const_iterator it = min_element(samples.begin(), samples.end()); return *it; } template<typename Ty> Ty maxValue(const std::vector<Ty>& samples) { typename std::vector<Ty>::const_iterator it = max_element(samples.begin(), samples.end()); return *it; } <commit_msg>Updated norm's<commit_after>#pragma once // blas_l1.hpp: BLAS Level 1 functions // // Copyright (C) 2017-2021 Stillwater Supercomputing, Inc. // // This file is part of the universal numbers project, which is released under an MIT Open Source license. #include <cmath> #include <universal/number/posit/posit> #include <universal/blas/vector.hpp> namespace sw { namespace universal { namespace blas { // 1-norm of a vector: sum of magnitudes of the vector elements, default increment stride is 1 template<typename Vector> typename Vector::value_type asum(size_t n, const Vector& x, size_t incx = 1) { typename Vector::value_type sum = 0; size_t ix; for (ix = 0; ix < n; ix += incx) { sum += (x[ix] < 0 ? -x[ix] : x[ix]); } return sum; } // sum of the vector elements, default increment stride is 1 template<typename Vector> typename Vector::value_type sum(const Vector& x) { typename Vector::value_type sum = 0; size_t ix; for (ix = 0; ix < size(x); ++ix) { sum += x[ix]; } return sum; } // a time x plus y template<typename Scalar, typename Vector> void axpy(size_t n, Scalar a, const Vector& x, size_t incx, Vector& y, size_t incy) { size_t cnt, ix, iy; for (cnt = 0, ix = 0, iy = 0; cnt < n && ix < size(x) && iy < size(y); ++cnt, ix += incx, iy += incy) { y[iy] += a * x[ix]; } } // vector copy template<typename Vector> void copy(size_t n, const Vector& x, size_t incx, Vector& y, size_t incy) { size_t cnt, ix, iy; for (cnt = 0, ix = 0, iy = 0; cnt < n && ix < size(x) && iy < size(y); ++cnt, ix += incx, iy += incy) { y[iy] = x[ix]; } } // adapter for STL vectors template<typename Scalar> auto size(const std::vector<Scalar>& v) { return v.size(); } // dot product: the operator vector::x[index] is limited to uint32_t, so the arguments are limited to uint32_t as well // The library does support arbitrary posit configuration conversions, but to simplify the // behavior of the dot product, the element type of the vectors x and y are declared to be the same. // TODO: investigate if the vector<> index is always a 32bit entity? template<typename Vector> typename Vector::value_type dot(size_t n, const Vector& x, size_t incx, const Vector& y, size_t incy) { using value_type = typename Vector::value_type; value_type sum_of_products = value_type(0); size_t cnt, ix, iy; for (cnt = 0, ix = 0, iy = 0; cnt < n && ix < size(x) && iy < size(y); ++cnt, ix += incx, iy += incy) { sum_of_products += x[ix] * y[iy]; } return sum_of_products; } // specialized dot product assuming constant stride template<typename Vector> typename Vector::value_type dot(const Vector& x, const Vector& y) { using value_type = typename Vector::value_type; value_type sum_of_products = value_type(0); size_t nx = size(x); if (nx <= size(y)) { for (size_t i = 0; i < nx; ++i) { sum_of_products += x[i] * y[i]; } } return sum_of_products; } // rotation of points in the plane template<typename Rotation, typename Vector> void rot(size_t n, Vector& x, size_t incx, Vector& y, size_t incy, Rotation c, Rotation s) { // x_i = c*x_i + s*y_i // y_i = c*y_i - s*x_i size_t cnt, ix, iy; for (cnt = 0, ix = 0, iy = 0; cnt < n && ix < size(x) && iy < size(y); ++cnt, ix += incx, iy += incy) { Rotation x_i = c * x[ix] + s * y[iy]; Rotation y_i = c * y[iy] - s * x[ix]; y[iy] = y_i; x[ix] = x_i; } } // compute parameters for a Givens rotation template<typename T> void rotg(T& a, T& b, T& c, T&s) { // Given Cartesian coordinates (a,b) of a point, return parameters c,s,r, and z associated with the Givens rotation. } // scale a vector template<typename Scalar, typename Vector> void scale(size_t n, Scalar alpha, Vector& x, size_t incx) { size_t cnt, ix; for (cnt = 0, ix = 0; cnt < n && ix < size(x); ix += incx) { x[ix] *= alpha; } } // swap two vectors template<typename Vector> void swap(size_t n, Vector& x, size_t incx, Vector& y, size_t incy) { size_t cnt, ix, iy; for (cnt = 0, ix = 0, iy = 0; cnt < n && ix < size(x) && iy < size(y); ++cnt, ix += incx, iy += incy) { typename Vector::value_type tmp = x[ix]; x[ix] = y[iy]; y[iy] = tmp; } } // find the index of the element with maximum absolute value template<typename Vector> size_t amax(size_t n, const Vector& x, size_t incx) { typename Vector::value_type running_max = -INFINITY; size_t ix, index; for (ix = 0; ix < size(x); ix += incx) { if (x[ix] > running_max) { index = ix; running_max = x[ix]; } } return index; } // find the index of the element with minimum absolute value template<typename Vector> size_t amin(size_t n, const Vector& x, size_t incx) { typename Vector::value_type running_min = INFINITY; size_t ix, index; for (ix = 0; ix < size(x); ix += incx) { if (x[ix] < running_min) { index = ix; running_min = x[ix]; } } return index; } // absolute value of a complex number template<typename T> T cabs(T z) { } // print a vector template<typename Vector> void strided_print(std::ostream& ostr, size_t n, Vector& x, size_t incx = 1) { size_t cnt, ix; for (cnt = 0, ix = 0; cnt < n && ix < size(x); ++cnt, ix += incx) { cnt == 0 ? ostr << "[" << x[ix] : ostr << ", " << x[ix]; } ostr << "]"; } } } } // namespace sw::universal::blas // free function norms // norm's of a vector template<typename Scalar, typename String> Scalar norm(const std::vector<Scalar>& v, String s="one_norm"){ Scalar ans=0; if(strcmp(s, "one_norm")){ for(auto i:v){ ans+=abs(i); } } if(strcmp(s, "two_norm")){ for(auto i:v){ ans+=i*i; } ans=Scalar(sqrt(ans)); } if(strcmp(s, "inf_norm")){ for(auto i:v){ ans=Scalar(-1e9); ans=std::max(ans,abs(i)); } } if(strcmp(s, "frobenius_norm")){ for(auto i:v){ ans+=abs(i*i); } ans=Scalar(sqrt(ans)); } return ans; } // specializations for STL vectors template<typename Ty> Ty minValue(const std::vector<Ty>& samples) { typename std::vector<Ty>::const_iterator it = min_element(samples.begin(), samples.end()); return *it; } template<typename Ty> Ty maxValue(const std::vector<Ty>& samples) { typename std::vector<Ty>::const_iterator it = max_element(samples.begin(), samples.end()); return *it; } <|endoftext|>
<commit_before>/* * Copyright (C) 2009, 2010, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ #ifndef CXX_OBJECT_HXX # define CXX_OBJECT_HXX # include <boost/function.hpp> # include <libport/bind.hh> # include <urbi/object/cxx-conversions.hh> # include <urbi/object/cxx-primitive.hh> # include <urbi/object/primitive.hh> # include <urbi/object/string.hh> # include <urbi/runner/raise.hh> namespace urbi { namespace object { inline void check_arg_count(unsigned effective, unsigned formal) { if (formal != effective) runner::raise_arity_error(effective, formal); } inline void check_arg_count(unsigned effective, unsigned min, unsigned max) { if (min == max) check_arg_count(effective, min); else if (effective < min || effective > max) runner::raise_arity_error(effective, min, max); } namespace { template <typename T> rObject cxx_object_clone(objects_type args) { check_arg_count(args.size() - 1, 0); rObject tgt = args[0]; aver(tgt->as<T>()); libport::intrusive_ptr<T> res = new T(tgt->as<T>()); // If the user didn't specify a prototype, use the model. if (res->protos_get().empty()) res->proto_add(tgt); return res; } template <typename T> rObject cxx_object_id(objects_type args) { check_arg_count(args.size() - 1, 0); return args[0]; } } template <typename T> void CxxObject::add(const std::string& ns) { GD_CATEGORY(Urbi.CxxObject); using boost::bind; rObject dest = global_class; if (!ns.empty()) { GD_FINFO_TRACE("register C++ object %s in namespace %s", T::type_name(), ns); if (dest->hasLocalSlot(ns)) dest = dest->getSlot(ns); else { // FIXME: this is a 'Namespace' dest = dest->setSlot(ns, new Object); dest->proto_add(Object::proto); dest->setSlot(libport::Symbol("asString"), to_urbi(ns)); } } else GD_FINFO_TRACE("register C++ object %s", T::type_name()); libport::intrusive_ptr<T> res; if (!T::proto) { res = new T(FirstPrototypeFlag()); T::proto = res; } else res = T::proto; // If the user didn't specify a prototype, use Object. if (res->protos_get().empty()) res->proto_add(Object::proto); aver(res); Binder<T> b(res); T::initialize(b); // type. static libport::Symbol type("type"); res->slot_set(type, new String(T::type_name()), true); // clone. static libport::Symbol clone("clone"); res->slot_set(clone, new Primitive(bind(cxx_object_clone<T>, _1)), true); // asFoo. libport::Symbol name(std::string("as") + T::type_name()); if (!res->slot_locate(name, false).first) res->slot_set(name, new Primitive(bind(cxx_object_id<T>, _1)), true); dest->setSlot(libport::Symbol(T::type_name()), res); } // BINDER template <typename T> CxxObject::Binder<T>::Binder(rObject tgt) : tgt_(tgt) {} template <typename T> template <typename M> void CxxObject::Binder<T>::operator()(const libport::Symbol& name, M method) { tgt_->slot_set(name, primitive(method), true); } template <typename C, typename T> static rObject getter(libport::intrusive_ptr<C> self, T (C::* value)) { return to_urbi(self.get()->*value); } template <typename C, typename T> static rObject setter(T (C::* attr), libport::intrusive_ptr<C> self, const std::string&, const T& value) { self.get()->*attr = value; return 0; } template <typename T> template <typename A> void CxxObject::Binder<T>::var(const libport::Symbol& name, A (T::*attr)) { using libport::intrusive_ptr; typedef boost::function1<rObject, intrusive_ptr<T> > urbi_getter_type; typedef boost::function3<rObject, intrusive_ptr<T>, const std::string&, const A&> urbi_setter_type; urbi_getter_type get(boost::bind(&getter<T, A>, _1, attr)); tgt_->slot_set(name, primitive(get), true); urbi_setter_type set(boost::bind(&setter<T, A>, attr, _1, _2, _3)); #define S(Name) Symbol(#Name) tgt_->property_set(name, libport::S(updateHook), primitive(set)); #undef S } template <typename C, typename T> static rObject refgetter(libport::intrusive_ptr<C> self, T* (C::* ref)()) { return to_urbi(*((self.get()->*ref)())); } template <typename C, typename T> static rObject refsetter(T* (C::* ref)(), libport::intrusive_ptr<C> self, const std::string&, const T& value) { *((self.get()->*ref)()) = value; return 0; } template <typename T> template <typename A> void CxxObject::Binder<T>::var(const libport::Symbol& name, A* (T::*ref)()) { using libport::intrusive_ptr; typedef boost::function1<rObject, intrusive_ptr<T> > urbi_getter_type; typedef boost::function3<rObject, intrusive_ptr<T>, const std::string&, const A&> urbi_setter_type; urbi_getter_type get(boost::bind(&refgetter<T, A>, _1, ref)); tgt_->slot_set(name, primitive(get), true); urbi_setter_type set(boost::bind(&refsetter<T, A>, ref, _1, _2, _3)); #define S(Name) Symbol(#Name) tgt_->property_set(name, libport::S(updateHook), primitive(set)); #undef S } template<typename T> inline libport::intrusive_ptr<T> type_check(const rObject& o, boost::optional<unsigned> idx) { // If we do not have the right type, bounce onto the slower version // which will take care of throwing the appropriate exception. The // check will be done again, but this is harmless and only happens // when there is actually a mismatch. if (!is_a<T>(o)) type_check(o, T::proto, idx); return o->as<T>(); } } } #endif <commit_msg>CxxObject registration: enable to specify a composite namespace.<commit_after>/* * Copyright (C) 2009, 2010, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ #ifndef CXX_OBJECT_HXX # define CXX_OBJECT_HXX # include <boost/function.hpp> # include <libport/bind.hh> # include <urbi/object/cxx-conversions.hh> # include <urbi/object/cxx-primitive.hh> # include <urbi/object/primitive.hh> # include <urbi/object/string.hh> # include <urbi/runner/raise.hh> namespace urbi { namespace object { inline void check_arg_count(unsigned effective, unsigned formal) { if (formal != effective) runner::raise_arity_error(effective, formal); } inline void check_arg_count(unsigned effective, unsigned min, unsigned max) { if (min == max) check_arg_count(effective, min); else if (effective < min || effective > max) runner::raise_arity_error(effective, min, max); } namespace { template <typename T> rObject cxx_object_clone(objects_type args) { check_arg_count(args.size() - 1, 0); rObject tgt = args[0]; aver(tgt->as<T>()); libport::intrusive_ptr<T> res = new T(tgt->as<T>()); // If the user didn't specify a prototype, use the model. if (res->protos_get().empty()) res->proto_add(tgt); return res; } template <typename T> rObject cxx_object_id(objects_type args) { check_arg_count(args.size() - 1, 0); return args[0]; } } template <typename T> void CxxObject::add(const std::string& ns) { using boost::bind; std::string name = (ns.empty() ? "" : ns + ".") + T::type_name(); rObject dest = resolve_namespace(name); GD_CATEGORY(Urbi.CxxObject); if (ns.empty()) GD_FINFO_TRACE("register C++ object %s", name); else GD_FINFO_TRACE("register C++ object %s as %s", name, ns); libport::intrusive_ptr<T> res; if (!T::proto) { res = new T(FirstPrototypeFlag()); T::proto = res; } else res = T::proto; // If the user didn't specify a prototype, use Object. if (res->protos_get().empty()) res->proto_add(Object::proto); aver(res); Binder<T> b(res); T::initialize(b); // type. static libport::Symbol type("type"); res->slot_set(type, new String(name), true); // clone. static libport::Symbol clone("clone"); res->slot_set(clone, new Primitive(bind(cxx_object_clone<T>, _1)), true); // asFoo. libport::Symbol as(std::string("as") + name); if (!res->slot_locate(as, false).first) res->slot_set(as, new Primitive(bind(cxx_object_id<T>, _1)), true); dest->setSlot(libport::Symbol(name), res); } // BINDER template <typename T> CxxObject::Binder<T>::Binder(rObject tgt) : tgt_(tgt) {} template <typename T> template <typename M> void CxxObject::Binder<T>::operator()(const libport::Symbol& name, M method) { tgt_->slot_set(name, primitive(method), true); } template <typename C, typename T> static rObject getter(libport::intrusive_ptr<C> self, T (C::* value)) { return to_urbi(self.get()->*value); } template <typename C, typename T> static rObject setter(T (C::* attr), libport::intrusive_ptr<C> self, const std::string&, const T& value) { self.get()->*attr = value; return 0; } template <typename T> template <typename A> void CxxObject::Binder<T>::var(const libport::Symbol& name, A (T::*attr)) { using libport::intrusive_ptr; typedef boost::function1<rObject, intrusive_ptr<T> > urbi_getter_type; typedef boost::function3<rObject, intrusive_ptr<T>, const std::string&, const A&> urbi_setter_type; urbi_getter_type get(boost::bind(&getter<T, A>, _1, attr)); tgt_->slot_set(name, primitive(get), true); urbi_setter_type set(boost::bind(&setter<T, A>, attr, _1, _2, _3)); #define S(Name) Symbol(#Name) tgt_->property_set(name, libport::S(updateHook), primitive(set)); #undef S } template <typename C, typename T> static rObject refgetter(libport::intrusive_ptr<C> self, T* (C::* ref)()) { return to_urbi(*((self.get()->*ref)())); } template <typename C, typename T> static rObject refsetter(T* (C::* ref)(), libport::intrusive_ptr<C> self, const std::string&, const T& value) { *((self.get()->*ref)()) = value; return 0; } template <typename T> template <typename A> void CxxObject::Binder<T>::var(const libport::Symbol& name, A* (T::*ref)()) { using libport::intrusive_ptr; typedef boost::function1<rObject, intrusive_ptr<T> > urbi_getter_type; typedef boost::function3<rObject, intrusive_ptr<T>, const std::string&, const A&> urbi_setter_type; urbi_getter_type get(boost::bind(&refgetter<T, A>, _1, ref)); tgt_->slot_set(name, primitive(get), true); urbi_setter_type set(boost::bind(&refsetter<T, A>, ref, _1, _2, _3)); #define S(Name) Symbol(#Name) tgt_->property_set(name, libport::S(updateHook), primitive(set)); #undef S } template<typename T> inline libport::intrusive_ptr<T> type_check(const rObject& o, boost::optional<unsigned> idx) { // If we do not have the right type, bounce onto the slower version // which will take care of throwing the appropriate exception. The // check will be done again, but this is harmless and only happens // when there is actually a mismatch. if (!is_a<T>(o)) type_check(o, T::proto, idx); return o->as<T>(); } } } #endif <|endoftext|>
<commit_before>/// \file RPageSourceFriends.cxx /// \ingroup NTuple ROOT7 /// \author Jakob Blomer <jblomer@cern.ch> /// \date 2019-08-10 /// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback /// is welcome! /************************************************************************* * Copyright (C) 1995-2020, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include <ROOT/RCluster.hxx> #include <ROOT/RError.hxx> #include <ROOT/RLogger.hxx> #include <ROOT/RNTupleOptions.hxx> #include <ROOT/RPageSourceFriends.hxx> #include <utility> ROOT::Experimental::Detail::RPageSourceFriends::RPageSourceFriends( std::string_view ntupleName, std::span<std::unique_ptr<RPageSource>> sources) : RPageSource(ntupleName, RNTupleReadOptions()) , fMetrics(std::string(ntupleName)) { for (auto &s : sources) { fSources.emplace_back(std::move(s)); fMetrics.ObserveMetrics(fSources.back()->GetMetrics()); } } ROOT::Experimental::Detail::RPageSourceFriends::~RPageSourceFriends() = default; void ROOT::Experimental::Detail::RPageSourceFriends::AddVirtualField( std::size_t originIdx, const RFieldDescriptor &originField, DescriptorId_t virtualParent, const std::string &virtualName) { auto virtualFieldId = fNextId++; auto virtualField = RDanglingFieldDescriptor(originField) .FieldId(virtualFieldId) .FieldName(virtualName) .MakeDescriptor().Unwrap(); fBuilder.AddField(virtualField); fBuilder.AddFieldLink(virtualParent, virtualFieldId); fIdBiMap.Insert({originIdx, originField.GetId()}, virtualFieldId); const auto &originDesc = fSources[originIdx]->GetDescriptor(); for (const auto &f : originDesc.GetFieldIterable(originField)) AddVirtualField(originIdx, f, virtualFieldId, f.GetFieldName()); for (const auto &c: originDesc.GetColumnIterable(originField)) { fBuilder.AddColumn(fNextId, virtualFieldId, c.GetVersion(), c.GetModel(), c.GetIndex()); fIdBiMap.Insert({originIdx, c.GetId()}, fNextId); fNextId++; } } ROOT::Experimental::RNTupleDescriptor ROOT::Experimental::Detail::RPageSourceFriends::AttachImpl() { fBuilder.SetNTuple(fNTupleName, "", "", RNTupleVersion(), RNTupleUuid()); fBuilder.AddField(RDanglingFieldDescriptor() .FieldId(0) .Structure(ENTupleStructure::kRecord) .MakeDescriptor() .Unwrap()); for (std::size_t i = 0; i < fSources.size(); ++i) { fSources[i]->Attach(); const auto &desc = fSources[i]->GetDescriptor(); if (fSources[i]->GetNEntries() != fSources[0]->GetNEntries()) { fNextId = 1; fIdBiMap.Clear(); fBuilder.Reset(); throw RException(R__FAIL("mismatch in the number of entries of friend RNTuples")); } for (unsigned j = 0; j < i; ++j) { if (fSources[j]->GetDescriptor().GetName() == desc.GetName()) { fNextId = 1; fIdBiMap.Clear(); fBuilder.Reset(); throw RException(R__FAIL("duplicate names of friend RNTuples")); } } AddVirtualField(i, desc.GetFieldZero(), 0, desc.GetName()); for (const auto &c : desc.GetClusterIterable()) { fBuilder.AddCluster(fNextId, c.GetVersion(), c.GetFirstEntryIndex(), c.GetNEntries()); fBuilder.SetClusterLocator(fNextId, c.GetLocator()); for (auto originColumnId : c.GetColumnIds()) { DescriptorId_t virtualColumnId = fIdBiMap.GetVirtualId({i, originColumnId}); auto columnRange = c.GetColumnRange(originColumnId); columnRange.fColumnId = virtualColumnId; fBuilder.AddClusterColumnRange(fNextId, columnRange); auto pageRange = c.GetPageRange(originColumnId).Clone(); pageRange.fColumnId = virtualColumnId; fBuilder.AddClusterPageRange(fNextId, std::move(pageRange)); } fIdBiMap.Insert({i, c.GetId()}, fNextId); fNextId++; } } fBuilder.EnsureValidDescriptor(); return fBuilder.MoveDescriptor(); } std::unique_ptr<ROOT::Experimental::Detail::RPageSource> ROOT::Experimental::Detail::RPageSourceFriends::Clone() const { std::vector<std::unique_ptr<RPageSource>> cloneSources; for (const auto &f : fSources) cloneSources.emplace_back(f->Clone()); return std::make_unique<RPageSourceFriends>(fNTupleName, cloneSources); } ROOT::Experimental::Detail::RPageStorage::ColumnHandle_t ROOT::Experimental::Detail::RPageSourceFriends::AddColumn(DescriptorId_t fieldId, const RColumn &column) { auto originFieldId = fIdBiMap.GetOriginId(fieldId); fSources[originFieldId.fSourceIdx]->AddColumn(originFieldId.fId, column); return RPageSource::AddColumn(fieldId, column); } void ROOT::Experimental::Detail::RPageSourceFriends::DropColumn(ColumnHandle_t columnHandle) { RPageSource::DropColumn(columnHandle); auto originColumnId = fIdBiMap.GetOriginId(columnHandle.fId); columnHandle.fId = originColumnId.fId; fSources[originColumnId.fSourceIdx]->DropColumn(columnHandle); } ROOT::Experimental::Detail::RPage ROOT::Experimental::Detail::RPageSourceFriends::PopulatePage( ColumnHandle_t columnHandle, NTupleSize_t globalIndex) { auto virtualColumnId = columnHandle.fId; auto originColumnId = fIdBiMap.GetOriginId(virtualColumnId); columnHandle.fId = originColumnId.fId; auto page = fSources[originColumnId.fSourceIdx]->PopulatePage(columnHandle, globalIndex); auto virtualClusterId = fIdBiMap.GetVirtualId({originColumnId.fSourceIdx, page.GetClusterInfo().GetId()}); page.ChangeIds(virtualColumnId, virtualClusterId); return page; } ROOT::Experimental::Detail::RPage ROOT::Experimental::Detail::RPageSourceFriends::PopulatePage( ColumnHandle_t columnHandle, const RClusterIndex &clusterIndex) { auto virtualColumnId = columnHandle.fId; auto originColumnId = fIdBiMap.GetOriginId(virtualColumnId); RClusterIndex originClusterIndex( fIdBiMap.GetOriginId(clusterIndex.GetClusterId()).fId, clusterIndex.GetIndex()); columnHandle.fId = originColumnId.fId; auto page = fSources[originColumnId.fSourceIdx]->PopulatePage(columnHandle, originClusterIndex); page.ChangeIds(virtualColumnId, clusterIndex.GetClusterId()); return page; } void ROOT::Experimental::Detail::RPageSourceFriends::LoadSealedPage( DescriptorId_t columnId, const RClusterIndex &clusterIndex, RSealedPage &sealedPage) { auto originColumnId = fIdBiMap.GetOriginId(columnId); RClusterIndex originClusterIndex( fIdBiMap.GetOriginId(clusterIndex.GetClusterId()).fId, clusterIndex.GetIndex()); fSources[originColumnId.fSourceIdx]->LoadSealedPage(columnId, originClusterIndex, sealedPage); } void ROOT::Experimental::Detail::RPageSourceFriends::ReleasePage(RPage &page) { if (page.IsNull()) return; auto sourceIdx = fIdBiMap.GetOriginId(page.GetClusterInfo().GetId()).fSourceIdx; fSources[sourceIdx]->ReleasePage(page); } std::vector<std::unique_ptr<ROOT::Experimental::Detail::RCluster>> ROOT::Experimental::Detail::RPageSourceFriends::LoadClusters(std::span<RCluster::RKey> clusterKeys) { // The virtual friends page source does not pre-load any clusters itself. However, the underlying page sources // that are combined may well do it. return std::vector<std::unique_ptr<ROOT::Experimental::Detail::RCluster>>(clusterKeys.size(), nullptr); } <commit_msg>Revert "[ntuple] Simplify vector construction in friend page source"<commit_after>/// \file RPageSourceFriends.cxx /// \ingroup NTuple ROOT7 /// \author Jakob Blomer <jblomer@cern.ch> /// \date 2019-08-10 /// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback /// is welcome! /************************************************************************* * Copyright (C) 1995-2020, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include <ROOT/RCluster.hxx> #include <ROOT/RError.hxx> #include <ROOT/RLogger.hxx> #include <ROOT/RNTupleOptions.hxx> #include <ROOT/RPageSourceFriends.hxx> #include <utility> ROOT::Experimental::Detail::RPageSourceFriends::RPageSourceFriends( std::string_view ntupleName, std::span<std::unique_ptr<RPageSource>> sources) : RPageSource(ntupleName, RNTupleReadOptions()) , fMetrics(std::string(ntupleName)) { for (auto &s : sources) { fSources.emplace_back(std::move(s)); fMetrics.ObserveMetrics(fSources.back()->GetMetrics()); } } ROOT::Experimental::Detail::RPageSourceFriends::~RPageSourceFriends() = default; void ROOT::Experimental::Detail::RPageSourceFriends::AddVirtualField( std::size_t originIdx, const RFieldDescriptor &originField, DescriptorId_t virtualParent, const std::string &virtualName) { auto virtualFieldId = fNextId++; auto virtualField = RDanglingFieldDescriptor(originField) .FieldId(virtualFieldId) .FieldName(virtualName) .MakeDescriptor().Unwrap(); fBuilder.AddField(virtualField); fBuilder.AddFieldLink(virtualParent, virtualFieldId); fIdBiMap.Insert({originIdx, originField.GetId()}, virtualFieldId); const auto &originDesc = fSources[originIdx]->GetDescriptor(); for (const auto &f : originDesc.GetFieldIterable(originField)) AddVirtualField(originIdx, f, virtualFieldId, f.GetFieldName()); for (const auto &c: originDesc.GetColumnIterable(originField)) { fBuilder.AddColumn(fNextId, virtualFieldId, c.GetVersion(), c.GetModel(), c.GetIndex()); fIdBiMap.Insert({originIdx, c.GetId()}, fNextId); fNextId++; } } ROOT::Experimental::RNTupleDescriptor ROOT::Experimental::Detail::RPageSourceFriends::AttachImpl() { fBuilder.SetNTuple(fNTupleName, "", "", RNTupleVersion(), RNTupleUuid()); fBuilder.AddField(RDanglingFieldDescriptor() .FieldId(0) .Structure(ENTupleStructure::kRecord) .MakeDescriptor() .Unwrap()); for (std::size_t i = 0; i < fSources.size(); ++i) { fSources[i]->Attach(); const auto &desc = fSources[i]->GetDescriptor(); if (fSources[i]->GetNEntries() != fSources[0]->GetNEntries()) { fNextId = 1; fIdBiMap.Clear(); fBuilder.Reset(); throw RException(R__FAIL("mismatch in the number of entries of friend RNTuples")); } for (unsigned j = 0; j < i; ++j) { if (fSources[j]->GetDescriptor().GetName() == desc.GetName()) { fNextId = 1; fIdBiMap.Clear(); fBuilder.Reset(); throw RException(R__FAIL("duplicate names of friend RNTuples")); } } AddVirtualField(i, desc.GetFieldZero(), 0, desc.GetName()); for (const auto &c : desc.GetClusterIterable()) { fBuilder.AddCluster(fNextId, c.GetVersion(), c.GetFirstEntryIndex(), c.GetNEntries()); fBuilder.SetClusterLocator(fNextId, c.GetLocator()); for (auto originColumnId : c.GetColumnIds()) { DescriptorId_t virtualColumnId = fIdBiMap.GetVirtualId({i, originColumnId}); auto columnRange = c.GetColumnRange(originColumnId); columnRange.fColumnId = virtualColumnId; fBuilder.AddClusterColumnRange(fNextId, columnRange); auto pageRange = c.GetPageRange(originColumnId).Clone(); pageRange.fColumnId = virtualColumnId; fBuilder.AddClusterPageRange(fNextId, std::move(pageRange)); } fIdBiMap.Insert({i, c.GetId()}, fNextId); fNextId++; } } fBuilder.EnsureValidDescriptor(); return fBuilder.MoveDescriptor(); } std::unique_ptr<ROOT::Experimental::Detail::RPageSource> ROOT::Experimental::Detail::RPageSourceFriends::Clone() const { std::vector<std::unique_ptr<RPageSource>> cloneSources; for (const auto &f : fSources) cloneSources.emplace_back(f->Clone()); return std::make_unique<RPageSourceFriends>(fNTupleName, cloneSources); } ROOT::Experimental::Detail::RPageStorage::ColumnHandle_t ROOT::Experimental::Detail::RPageSourceFriends::AddColumn(DescriptorId_t fieldId, const RColumn &column) { auto originFieldId = fIdBiMap.GetOriginId(fieldId); fSources[originFieldId.fSourceIdx]->AddColumn(originFieldId.fId, column); return RPageSource::AddColumn(fieldId, column); } void ROOT::Experimental::Detail::RPageSourceFriends::DropColumn(ColumnHandle_t columnHandle) { RPageSource::DropColumn(columnHandle); auto originColumnId = fIdBiMap.GetOriginId(columnHandle.fId); columnHandle.fId = originColumnId.fId; fSources[originColumnId.fSourceIdx]->DropColumn(columnHandle); } ROOT::Experimental::Detail::RPage ROOT::Experimental::Detail::RPageSourceFriends::PopulatePage( ColumnHandle_t columnHandle, NTupleSize_t globalIndex) { auto virtualColumnId = columnHandle.fId; auto originColumnId = fIdBiMap.GetOriginId(virtualColumnId); columnHandle.fId = originColumnId.fId; auto page = fSources[originColumnId.fSourceIdx]->PopulatePage(columnHandle, globalIndex); auto virtualClusterId = fIdBiMap.GetVirtualId({originColumnId.fSourceIdx, page.GetClusterInfo().GetId()}); page.ChangeIds(virtualColumnId, virtualClusterId); return page; } ROOT::Experimental::Detail::RPage ROOT::Experimental::Detail::RPageSourceFriends::PopulatePage( ColumnHandle_t columnHandle, const RClusterIndex &clusterIndex) { auto virtualColumnId = columnHandle.fId; auto originColumnId = fIdBiMap.GetOriginId(virtualColumnId); RClusterIndex originClusterIndex( fIdBiMap.GetOriginId(clusterIndex.GetClusterId()).fId, clusterIndex.GetIndex()); columnHandle.fId = originColumnId.fId; auto page = fSources[originColumnId.fSourceIdx]->PopulatePage(columnHandle, originClusterIndex); page.ChangeIds(virtualColumnId, clusterIndex.GetClusterId()); return page; } void ROOT::Experimental::Detail::RPageSourceFriends::LoadSealedPage( DescriptorId_t columnId, const RClusterIndex &clusterIndex, RSealedPage &sealedPage) { auto originColumnId = fIdBiMap.GetOriginId(columnId); RClusterIndex originClusterIndex( fIdBiMap.GetOriginId(clusterIndex.GetClusterId()).fId, clusterIndex.GetIndex()); fSources[originColumnId.fSourceIdx]->LoadSealedPage(columnId, originClusterIndex, sealedPage); } void ROOT::Experimental::Detail::RPageSourceFriends::ReleasePage(RPage &page) { if (page.IsNull()) return; auto sourceIdx = fIdBiMap.GetOriginId(page.GetClusterInfo().GetId()).fSourceIdx; fSources[sourceIdx]->ReleasePage(page); } std::vector<std::unique_ptr<ROOT::Experimental::Detail::RCluster>> ROOT::Experimental::Detail::RPageSourceFriends::LoadClusters(std::span<RCluster::RKey> clusterKeys) { // The virtual friends page source does not pre-load any clusters itself. However, the underlying page sources // that are combined may well do it. std::vector<std::unique_ptr<ROOT::Experimental::Detail::RCluster>> result; for (unsigned i = 0; i < clusterKeys.size(); ++i) result.push_back(nullptr); return result; } <|endoftext|>
<commit_before>#include "ntuple_test.hxx" TEST(RNTuple, Descriptor) { RNTupleDescriptorBuilder descBuilder; descBuilder.SetNTuple("MyTuple", "Description", "Me", RNTupleVersion(1, 2, 3), ROOT::Experimental::RNTupleUuid()); descBuilder.AddField(0, RNTupleVersion(), RNTupleVersion(), "", "", 0, ENTupleStructure::kRecord); descBuilder.AddField(1, RNTupleVersion(), RNTupleVersion(), "list", "std::vector<std::int32_t>", 0, ENTupleStructure::kCollection); descBuilder.AddFieldLink(0, 1); descBuilder.AddField(2, RNTupleVersion(), RNTupleVersion(), "list", "std::int32_t", 0, ENTupleStructure::kLeaf); descBuilder.AddFieldLink(1, 2); descBuilder.AddField(42, RNTupleVersion(), RNTupleVersion(), "x", "std::string", 0, ENTupleStructure::kLeaf); descBuilder.AddFieldLink(0, 42); descBuilder.AddColumn(3, 42, RNTupleVersion(), RColumnModel(EColumnType::kIndex, true), 0); descBuilder.AddColumn(4, 42, RNTupleVersion(), RColumnModel(EColumnType::kByte, true), 1); ROOT::Experimental::RClusterDescriptor::RColumnRange columnRange; ROOT::Experimental::RClusterDescriptor::RPageRange::RPageInfo pageInfo; // Description of cluster #0 descBuilder.AddCluster(0, RNTupleVersion(), 0, ROOT::Experimental::ClusterSize_t(100)); columnRange.fColumnId = 3; columnRange.fFirstElementIndex = 0; columnRange.fNElements = 100; descBuilder.AddClusterColumnRange(0, columnRange); ROOT::Experimental::RClusterDescriptor::RPageRange pageRange0; pageRange0.fPageInfos.clear(); pageRange0.fColumnId = 3; pageInfo.fNElements = 40; pageInfo.fLocator.fPosition = 0; pageRange0.fPageInfos.emplace_back(pageInfo); pageInfo.fNElements = 60; pageInfo.fLocator.fPosition = 1024; pageRange0.fPageInfos.emplace_back(pageInfo); descBuilder.AddClusterPageRange(0, std::move(pageRange0)); columnRange.fColumnId = 4; columnRange.fFirstElementIndex = 0; columnRange.fNElements = 300; descBuilder.AddClusterColumnRange(0, columnRange); ROOT::Experimental::RClusterDescriptor::RPageRange pageRange1; pageRange1.fColumnId = 4; pageInfo.fNElements = 200; pageInfo.fLocator.fPosition = 2048; pageRange1.fPageInfos.emplace_back(pageInfo); pageInfo.fNElements = 100; pageInfo.fLocator.fPosition = 4096; pageRange1.fPageInfos.emplace_back(pageInfo); descBuilder.AddClusterPageRange(0, std::move(pageRange1)); // Description of cluster #1 descBuilder.AddCluster(1, RNTupleVersion(), 100, ROOT::Experimental::ClusterSize_t(1000)); columnRange.fColumnId = 3; columnRange.fFirstElementIndex = 100; columnRange.fNElements = 1000; descBuilder.AddClusterColumnRange(1, columnRange); ROOT::Experimental::RClusterDescriptor::RPageRange pageRange2; pageRange2.fColumnId = 3; pageInfo.fNElements = 1000; pageInfo.fLocator.fPosition = 8192; pageRange2.fPageInfos.emplace_back(pageInfo); descBuilder.AddClusterPageRange(1, std::move(pageRange2)); columnRange.fColumnId = 4; columnRange.fFirstElementIndex = 300; columnRange.fNElements = 3000; descBuilder.AddClusterColumnRange(1, columnRange); ROOT::Experimental::RClusterDescriptor::RPageRange pageRange3; pageRange3.fColumnId = 4; pageInfo.fNElements = 3000; pageInfo.fLocator.fPosition = 16384; pageRange3.fPageInfos.emplace_back(pageInfo); descBuilder.AddClusterPageRange(1, std::move(pageRange3)); const auto &reference = descBuilder.GetDescriptor(); EXPECT_EQ("MyTuple", reference.GetName()); EXPECT_EQ(1U, reference.GetVersion().GetVersionUse()); EXPECT_EQ(2U, reference.GetVersion().GetVersionMin()); EXPECT_EQ(3U, reference.GetVersion().GetFlags()); auto szHeader = reference.SerializeHeader(nullptr); auto headerBuffer = new unsigned char[szHeader]; reference.SerializeHeader(headerBuffer); auto szFooter = reference.SerializeFooter(nullptr); auto footerBuffer = new unsigned char[szFooter]; reference.SerializeFooter(footerBuffer); const auto nbytesPostscript = RNTupleDescriptor::kNBytesPostscript; ASSERT_GE(szFooter, nbytesPostscript); std::uint32_t szPsHeader; std::uint32_t szPsFooter; RNTupleDescriptor::LocateMetadata(footerBuffer + szFooter - nbytesPostscript, szPsHeader, szPsFooter); EXPECT_EQ(szHeader, szPsHeader); EXPECT_EQ(szFooter, szPsFooter); RNTupleDescriptorBuilder reco; reco.SetFromHeader(headerBuffer); reco.AddClustersFromFooter(footerBuffer); EXPECT_EQ(reference, reco.GetDescriptor()); EXPECT_EQ(NTupleSize_t(1100), reference.GetNEntries()); EXPECT_EQ(NTupleSize_t(1100), reference.GetNElements(3)); EXPECT_EQ(NTupleSize_t(3300), reference.GetNElements(4)); EXPECT_EQ(DescriptorId_t(0), reference.GetFieldZeroId()); EXPECT_EQ(DescriptorId_t(1), reference.FindFieldId("list", 0)); EXPECT_EQ(DescriptorId_t(1), reference.FindFieldId("list")); EXPECT_EQ(DescriptorId_t(2), reference.FindFieldId("list", 1)); EXPECT_EQ(DescriptorId_t(42), reference.FindFieldId("x", 0)); EXPECT_EQ(DescriptorId_t(42), reference.FindFieldId("x")); EXPECT_EQ(ROOT::Experimental::kInvalidDescriptorId, reference.FindFieldId("listX", 1)); EXPECT_EQ(ROOT::Experimental::kInvalidDescriptorId, reference.FindFieldId("list", 1024)); EXPECT_EQ(DescriptorId_t(3), reference.FindColumnId(42, 0)); EXPECT_EQ(DescriptorId_t(4), reference.FindColumnId(42, 1)); EXPECT_EQ(ROOT::Experimental::kInvalidDescriptorId, reference.FindColumnId(42, 2)); EXPECT_EQ(ROOT::Experimental::kInvalidDescriptorId, reference.FindColumnId(43, 0)); EXPECT_EQ(DescriptorId_t(0), reference.FindClusterId(3, 0)); EXPECT_EQ(DescriptorId_t(1), reference.FindClusterId(3, 100)); EXPECT_EQ(ROOT::Experimental::kInvalidDescriptorId, reference.FindClusterId(3, 40000)); delete[] footerBuffer; delete[] headerBuffer; } TEST(RFieldDescriptorRange, IterateOverFieldNames) { auto model = RNTupleModel::Create(); auto floats = model->MakeField<std::vector<float>>("jets"); auto bools = model->MakeField<std::vector<bool>>("bools"); auto bool_vec_vec = model->MakeField<std::vector<std::vector<bool>>>("bool_vec_vec"); auto ints = model->MakeField<std::int32_t>("ints"); FileRaii fileGuard("test_field_iterator.root"); auto modelRead = std::unique_ptr<RNTupleModel>(model->Clone()); { RNTupleWriter ntuple(std::move(model), std::make_unique<RPageSinkFile>("ntuple", fileGuard.GetPath(), RNTupleWriteOptions())); ntuple.Fill(); } RNTupleReader ntuple(std::move(modelRead), std::make_unique<RPageSourceFile>("ntuple", fileGuard.GetPath(), RNTupleReadOptions())); // iterate over top-level fields std::vector<std::string> names{}; for (auto& f: ntuple.GetDescriptor().GetTopLevelFields()) { names.push_back(f.GetFieldName()); } EXPECT_EQ(names.size(), 4); EXPECT_EQ(names[0], std::string("jets")); EXPECT_EQ(names[1], std::string("bools")); EXPECT_EQ(names[2], std::string("bool_vec_vec")); EXPECT_EQ(names[3], std::string("ints")); const auto& ntuple_desc = ntuple.GetDescriptor(); auto top_level_fields = ntuple_desc.GetTopLevelFields(); // iterate over child field ranges const auto& float_vec_desc = *top_level_fields.begin(); EXPECT_EQ(float_vec_desc.GetFieldName(), std::string("jets")); auto float_vec_child_range = ntuple_desc.GetFieldRange(float_vec_desc); std::vector<std::string> child_names{}; for (auto& child_field: float_vec_child_range) { child_names.push_back(child_field.GetFieldName()); // check the empty range auto float_child_range = ntuple_desc.GetFieldRange(child_field); EXPECT_EQ(float_child_range.begin(), float_child_range.end()); } EXPECT_EQ(child_names.size(), 1); EXPECT_EQ(child_names[0], std::string("float")); // check if canonical iterator methods work auto iter = top_level_fields.begin(); std::advance(iter, 2); const auto& bool_vec_vec_desc = *iter; EXPECT_EQ(bool_vec_vec_desc.GetFieldName(), std::string("bool_vec_vec")); child_names.clear(); for (auto& child_field: ntuple_desc.GetFieldRange(bool_vec_vec_desc)) { child_names.push_back(child_field.GetFieldName()); } EXPECT_EQ(child_names.size(), 1); EXPECT_EQ(child_names[0], std::string("std::vector<bool>")); } TEST(RFieldDescriptorRange, SortByLambda) { auto model = RNTupleModel::Create(); auto floats = model->MakeField<std::vector<float>>("jets"); auto bools = model->MakeField<std::vector<bool>>("bools"); auto bool_vec_vec = model->MakeField<std::vector<std::vector<bool>>>("bool_vec_vec"); auto ints = model->MakeField<std::int32_t>("ints"); FileRaii fileGuard("test_field_iterator.root"); auto modelRead = std::unique_ptr<RNTupleModel>(model->Clone()); { RNTupleWriter ntuple(std::move(model), std::make_unique<RPageSinkFile>("ntuple", fileGuard.GetPath(), RNTupleWriteOptions())); ntuple.Fill(); } RNTupleReader ntuple(std::move(modelRead), std::make_unique<RPageSourceFile>("ntuple", fileGuard.GetPath(), RNTupleReadOptions())); const auto& ntuple_desc = ntuple.GetDescriptor(); auto alpha_order = [&](auto lhs, auto rhs) { return ntuple_desc.GetFieldDescriptor(lhs).GetFieldName() < ntuple_desc.GetFieldDescriptor(rhs).GetFieldName(); }; std::vector<std::string> sorted_names = {}; for (auto& f: ntuple_desc.GetTopLevelFields(alpha_order)) { sorted_names.push_back(f.GetFieldName()); } EXPECT_EQ(sorted_names.size(), 4); EXPECT_EQ(sorted_names[0], std::string("bool_vec_vec")); EXPECT_EQ(sorted_names[1], std::string("bools")); EXPECT_EQ(sorted_names[2], std::string("ints")); EXPECT_EQ(sorted_names[3], std::string("jets")); // reverse alphabetical sorted_names.clear(); for (auto& f: ntuple_desc.GetTopLevelFields( [&](auto lhs, auto rhs) { return !alpha_order(lhs, rhs); })) { sorted_names.push_back(f.GetFieldName()); } EXPECT_EQ(sorted_names.size(), 4); EXPECT_EQ(sorted_names[0], std::string("jets")); EXPECT_EQ(sorted_names[1], std::string("ints")); EXPECT_EQ(sorted_names[2], std::string("bools")); EXPECT_EQ(sorted_names[3], std::string("bool_vec_vec")); // alphabetical by type name std::vector<std::string> sorted_by_typename = {}; for (auto& f: ntuple_desc.GetTopLevelFields( [&](auto lhs, auto rhs) { return ntuple_desc.GetFieldDescriptor(lhs).GetTypeName() < ntuple_desc.GetFieldDescriptor(rhs).GetTypeName(); })) { sorted_by_typename.push_back(f.GetFieldName()); } // int32_t, vector<bool>, vector<float>, vector<vector<bool> EXPECT_EQ(sorted_by_typename.size(), 4); EXPECT_EQ(sorted_by_typename[0], std::string("ints")); EXPECT_EQ(sorted_by_typename[1], std::string("bools")); EXPECT_EQ(sorted_by_typename[2], std::string("jets")); EXPECT_EQ(sorted_by_typename[3], std::string("bool_vec_vec")); } <commit_msg>[ntuple] polish field descriptor iterator unit tests<commit_after>#include "ntuple_test.hxx" TEST(RNTuple, Descriptor) { RNTupleDescriptorBuilder descBuilder; descBuilder.SetNTuple("MyTuple", "Description", "Me", RNTupleVersion(1, 2, 3), ROOT::Experimental::RNTupleUuid()); descBuilder.AddField(0, RNTupleVersion(), RNTupleVersion(), "", "", 0, ENTupleStructure::kRecord); descBuilder.AddField(1, RNTupleVersion(), RNTupleVersion(), "list", "std::vector<std::int32_t>", 0, ENTupleStructure::kCollection); descBuilder.AddFieldLink(0, 1); descBuilder.AddField(2, RNTupleVersion(), RNTupleVersion(), "list", "std::int32_t", 0, ENTupleStructure::kLeaf); descBuilder.AddFieldLink(1, 2); descBuilder.AddField(42, RNTupleVersion(), RNTupleVersion(), "x", "std::string", 0, ENTupleStructure::kLeaf); descBuilder.AddFieldLink(0, 42); descBuilder.AddColumn(3, 42, RNTupleVersion(), RColumnModel(EColumnType::kIndex, true), 0); descBuilder.AddColumn(4, 42, RNTupleVersion(), RColumnModel(EColumnType::kByte, true), 1); ROOT::Experimental::RClusterDescriptor::RColumnRange columnRange; ROOT::Experimental::RClusterDescriptor::RPageRange::RPageInfo pageInfo; // Description of cluster #0 descBuilder.AddCluster(0, RNTupleVersion(), 0, ROOT::Experimental::ClusterSize_t(100)); columnRange.fColumnId = 3; columnRange.fFirstElementIndex = 0; columnRange.fNElements = 100; descBuilder.AddClusterColumnRange(0, columnRange); ROOT::Experimental::RClusterDescriptor::RPageRange pageRange0; pageRange0.fPageInfos.clear(); pageRange0.fColumnId = 3; pageInfo.fNElements = 40; pageInfo.fLocator.fPosition = 0; pageRange0.fPageInfos.emplace_back(pageInfo); pageInfo.fNElements = 60; pageInfo.fLocator.fPosition = 1024; pageRange0.fPageInfos.emplace_back(pageInfo); descBuilder.AddClusterPageRange(0, std::move(pageRange0)); columnRange.fColumnId = 4; columnRange.fFirstElementIndex = 0; columnRange.fNElements = 300; descBuilder.AddClusterColumnRange(0, columnRange); ROOT::Experimental::RClusterDescriptor::RPageRange pageRange1; pageRange1.fColumnId = 4; pageInfo.fNElements = 200; pageInfo.fLocator.fPosition = 2048; pageRange1.fPageInfos.emplace_back(pageInfo); pageInfo.fNElements = 100; pageInfo.fLocator.fPosition = 4096; pageRange1.fPageInfos.emplace_back(pageInfo); descBuilder.AddClusterPageRange(0, std::move(pageRange1)); // Description of cluster #1 descBuilder.AddCluster(1, RNTupleVersion(), 100, ROOT::Experimental::ClusterSize_t(1000)); columnRange.fColumnId = 3; columnRange.fFirstElementIndex = 100; columnRange.fNElements = 1000; descBuilder.AddClusterColumnRange(1, columnRange); ROOT::Experimental::RClusterDescriptor::RPageRange pageRange2; pageRange2.fColumnId = 3; pageInfo.fNElements = 1000; pageInfo.fLocator.fPosition = 8192; pageRange2.fPageInfos.emplace_back(pageInfo); descBuilder.AddClusterPageRange(1, std::move(pageRange2)); columnRange.fColumnId = 4; columnRange.fFirstElementIndex = 300; columnRange.fNElements = 3000; descBuilder.AddClusterColumnRange(1, columnRange); ROOT::Experimental::RClusterDescriptor::RPageRange pageRange3; pageRange3.fColumnId = 4; pageInfo.fNElements = 3000; pageInfo.fLocator.fPosition = 16384; pageRange3.fPageInfos.emplace_back(pageInfo); descBuilder.AddClusterPageRange(1, std::move(pageRange3)); const auto &reference = descBuilder.GetDescriptor(); EXPECT_EQ("MyTuple", reference.GetName()); EXPECT_EQ(1U, reference.GetVersion().GetVersionUse()); EXPECT_EQ(2U, reference.GetVersion().GetVersionMin()); EXPECT_EQ(3U, reference.GetVersion().GetFlags()); auto szHeader = reference.SerializeHeader(nullptr); auto headerBuffer = new unsigned char[szHeader]; reference.SerializeHeader(headerBuffer); auto szFooter = reference.SerializeFooter(nullptr); auto footerBuffer = new unsigned char[szFooter]; reference.SerializeFooter(footerBuffer); const auto nbytesPostscript = RNTupleDescriptor::kNBytesPostscript; ASSERT_GE(szFooter, nbytesPostscript); std::uint32_t szPsHeader; std::uint32_t szPsFooter; RNTupleDescriptor::LocateMetadata(footerBuffer + szFooter - nbytesPostscript, szPsHeader, szPsFooter); EXPECT_EQ(szHeader, szPsHeader); EXPECT_EQ(szFooter, szPsFooter); RNTupleDescriptorBuilder reco; reco.SetFromHeader(headerBuffer); reco.AddClustersFromFooter(footerBuffer); EXPECT_EQ(reference, reco.GetDescriptor()); EXPECT_EQ(NTupleSize_t(1100), reference.GetNEntries()); EXPECT_EQ(NTupleSize_t(1100), reference.GetNElements(3)); EXPECT_EQ(NTupleSize_t(3300), reference.GetNElements(4)); EXPECT_EQ(DescriptorId_t(0), reference.GetFieldZeroId()); EXPECT_EQ(DescriptorId_t(1), reference.FindFieldId("list", 0)); EXPECT_EQ(DescriptorId_t(1), reference.FindFieldId("list")); EXPECT_EQ(DescriptorId_t(2), reference.FindFieldId("list", 1)); EXPECT_EQ(DescriptorId_t(42), reference.FindFieldId("x", 0)); EXPECT_EQ(DescriptorId_t(42), reference.FindFieldId("x")); EXPECT_EQ(ROOT::Experimental::kInvalidDescriptorId, reference.FindFieldId("listX", 1)); EXPECT_EQ(ROOT::Experimental::kInvalidDescriptorId, reference.FindFieldId("list", 1024)); EXPECT_EQ(DescriptorId_t(3), reference.FindColumnId(42, 0)); EXPECT_EQ(DescriptorId_t(4), reference.FindColumnId(42, 1)); EXPECT_EQ(ROOT::Experimental::kInvalidDescriptorId, reference.FindColumnId(42, 2)); EXPECT_EQ(ROOT::Experimental::kInvalidDescriptorId, reference.FindColumnId(43, 0)); EXPECT_EQ(DescriptorId_t(0), reference.FindClusterId(3, 0)); EXPECT_EQ(DescriptorId_t(1), reference.FindClusterId(3, 100)); EXPECT_EQ(ROOT::Experimental::kInvalidDescriptorId, reference.FindClusterId(3, 40000)); delete[] footerBuffer; delete[] headerBuffer; } TEST(RFieldDescriptorRange, IterateOverFieldNames) { auto model = RNTupleModel::Create(); auto floats = model->MakeField<std::vector<float>>("jets"); auto bools = model->MakeField<std::vector<bool>>("bools"); auto bool_vec_vec = model->MakeField<std::vector<std::vector<bool>>>("bool_vec_vec"); auto ints = model->MakeField<std::int32_t>("ints"); FileRaii fileGuard("test_field_iterator.root"); { RNTupleWriter ntuple(std::move(model), std::make_unique<RPageSinkFile>("ntuple", fileGuard.GetPath(), RNTupleWriteOptions())); ntuple.Fill(); } auto ntuple = RNTupleReader::Open("ntuple", fileGuard.GetPath()); // iterate over top-level fields std::vector<std::string> names{}; for (auto& f: ntuple->GetDescriptor().GetTopLevelFields()) { names.push_back(f.GetFieldName()); } ASSERT_EQ(names.size(), 4); EXPECT_EQ(names[0], std::string("jets")); EXPECT_EQ(names[1], std::string("bools")); EXPECT_EQ(names[2], std::string("bool_vec_vec")); EXPECT_EQ(names[3], std::string("ints")); const auto& ntuple_desc = ntuple->GetDescriptor(); auto top_level_fields = ntuple_desc.GetTopLevelFields(); // iterate over child field ranges const auto& float_vec_desc = *top_level_fields.begin(); EXPECT_EQ(float_vec_desc.GetFieldName(), std::string("jets")); auto float_vec_child_range = ntuple_desc.GetFieldRange(float_vec_desc); std::vector<std::string> child_names{}; for (auto& child_field: float_vec_child_range) { child_names.push_back(child_field.GetFieldName()); // check the empty range auto float_child_range = ntuple_desc.GetFieldRange(child_field); EXPECT_EQ(float_child_range.begin(), float_child_range.end()); } ASSERT_EQ(child_names.size(), 1); EXPECT_EQ(child_names[0], std::string("float")); // check if canonical iterator methods work auto iter = top_level_fields.begin(); std::advance(iter, 2); const auto& bool_vec_vec_desc = *iter; EXPECT_EQ(bool_vec_vec_desc.GetFieldName(), std::string("bool_vec_vec")); child_names.clear(); for (auto& child_field: ntuple_desc.GetFieldRange(bool_vec_vec_desc)) { child_names.push_back(child_field.GetFieldName()); } ASSERT_EQ(child_names.size(), 1); EXPECT_EQ(child_names[0], std::string("std::vector<bool>")); } TEST(RFieldDescriptorRange, SortByLambda) { auto model = RNTupleModel::Create(); auto floats = model->MakeField<std::vector<float>>("jets"); auto bools = model->MakeField<std::vector<bool>>("bools"); auto bool_vec_vec = model->MakeField<std::vector<std::vector<bool>>>("bool_vec_vec"); auto ints = model->MakeField<std::int32_t>("ints"); FileRaii fileGuard("test_field_iterator.root"); { RNTupleWriter ntuple(std::move(model), std::make_unique<RPageSinkFile>("ntuple", fileGuard.GetPath(), RNTupleWriteOptions())); ntuple.Fill(); } auto ntuple = RNTupleReader::Open("ntuple", fileGuard.GetPath()); const auto& ntuple_desc = ntuple->GetDescriptor(); auto alpha_order = [&](auto lhs, auto rhs) { return ntuple_desc.GetFieldDescriptor(lhs).GetFieldName() < ntuple_desc.GetFieldDescriptor(rhs).GetFieldName(); }; std::vector<std::string> sorted_names = {}; for (auto& f: ntuple_desc.GetTopLevelFields(alpha_order)) { sorted_names.push_back(f.GetFieldName()); } ASSERT_EQ(sorted_names.size(), 4); EXPECT_EQ(sorted_names[0], std::string("bool_vec_vec")); EXPECT_EQ(sorted_names[1], std::string("bools")); EXPECT_EQ(sorted_names[2], std::string("ints")); EXPECT_EQ(sorted_names[3], std::string("jets")); // reverse alphabetical sorted_names.clear(); for (auto& f: ntuple_desc.GetTopLevelFields( [&](auto lhs, auto rhs) { return !alpha_order(lhs, rhs); })) { sorted_names.push_back(f.GetFieldName()); } ASSERT_EQ(sorted_names.size(), 4); EXPECT_EQ(sorted_names[0], std::string("jets")); EXPECT_EQ(sorted_names[1], std::string("ints")); EXPECT_EQ(sorted_names[2], std::string("bools")); EXPECT_EQ(sorted_names[3], std::string("bool_vec_vec")); // alphabetical by type name std::vector<std::string> sorted_by_typename = {}; for (auto& f: ntuple_desc.GetTopLevelFields( [&](auto lhs, auto rhs) { return ntuple_desc.GetFieldDescriptor(lhs).GetTypeName() < ntuple_desc.GetFieldDescriptor(rhs).GetTypeName(); })) { sorted_by_typename.push_back(f.GetFieldName()); } // int32_t, vector<bool>, vector<float>, vector<vector<bool> ASSERT_EQ(sorted_by_typename.size(), 4); EXPECT_EQ(sorted_by_typename[0], std::string("ints")); EXPECT_EQ(sorted_by_typename[1], std::string("bools")); EXPECT_EQ(sorted_by_typename[2], std::string("jets")); EXPECT_EQ(sorted_by_typename[3], std::string("bool_vec_vec")); } <|endoftext|>
<commit_before> #include "dobby.h" #include "logging/logging.h" #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <string.h> #include <pthread.h> #include <map> std::map<void *, const char *> *func_map; void common_handler(RegisterContext *ctx, const HookEntryInfo *info) { auto iter = func_map->find(info->function_address); if (iter != func_map->end()) { LOG(1, "func %s:%p invoke", iter->second, iter->first); } } // clang-format off const char *func_array[] = { "__loader_dlopen", "dlsym", "dlclose", "open", "write", "read", "close", "socket", "connect", "bind", "listen", "accept", "send", "recv", }; // clang-format on typeof(pthread_create) *orig_pthread_create; int fake_pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg) { LOG(1, "pthread_create: %p", start_routine); return orig_pthread_create(thread, attr, start_routine, arg); } #if 1 __attribute__((constructor)) static void ctor() { void *func = NULL; log_set_level(0); func_map = new std::map<void *, const char *>(); for (int i = 0; i < sizeof(func_array) / sizeof(char *); ++i) { func = DobbySymbolResolver(NULL, func_array[i]); if (func == NULL) { LOG(1, "func %s not resolve", func_array[i]); continue; } func_map->insert(std::pair<void *, const char *>(func, func_array[i])); DobbyInstrument(func, common_handler); } DobbyGlobalOffsetTableReplace(NULL, "_pthread_create", (void *)fake_pthread_create, (void **)&orig_pthread_create); pthread_t socket_server; uint64_t socket_demo_server(void *ctx); pthread_create(&socket_server, NULL, (void *(*)(void *))socket_demo_server, NULL); usleep(1000); pthread_t socket_client; uint64_t socket_demo_client(void *ctx); pthread_create(&socket_client, NULL, (void *(*)(void *))socket_demo_client, NULL); pthread_join(socket_client, 0); pthread_join(socket_server, 0); } #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #define PORT 8989 uint64_t socket_demo_server(void *ctx) { int server_fd, new_socket, valread; struct sockaddr_in address; int opt = 1; int addrlen = sizeof(address); char buffer[1024] = {0}; char * hello = "Hello from server"; // Creating socket file descriptor if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) { perror("socket failed"); exit(EXIT_FAILURE); } // Forcefully attaching socket to the port 8080 if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt))) { perror("setsockopt"); exit(EXIT_FAILURE); } address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons(PORT); // Forcefully attaching socket to the port 8080 if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) { perror("bind failed"); exit(EXIT_FAILURE); } if (listen(server_fd, 3) < 0) { perror("listen"); exit(EXIT_FAILURE); } if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t *)&addrlen)) < 0) { perror("accept"); exit(EXIT_FAILURE); } valread = recv(new_socket, buffer, 1024, 0); printf("%s\n", buffer); send(new_socket, hello, strlen(hello), 0); printf("Hello message sent\n"); return 0; } uint64_t socket_demo_client(void *ctx) { int sock = 0, valread; struct sockaddr_in serv_addr; char * hello = "Hello from client"; char buffer[1024] = {0}; if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) { printf("\n Socket creation error \n"); return -1; } serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(PORT); // Convert IPv4 and IPv6 addresses from text to binary form if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0) { printf("\nInvalid address/ Address not supported \n"); return -1; } if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { printf("\nConnection Failed \n"); return -1; } send(sock, hello, strlen(hello), 0); printf("Hello message sent\n"); valread = recv(sock, buffer, 1024, 0); printf("%s\n", buffer); return 0; } #endif <commit_msg>Update example<commit_after> #include "dobby.h" #include "logging/logging.h" #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <string.h> #include <pthread.h> #include <map> std::map<void *, const char *> *func_map; void common_handler(RegisterContext *ctx, const HookEntryInfo *info) { auto iter = func_map->find(info->function_address); if (iter != func_map->end()) { LOG(1, "func %s:%p invoke", iter->second, iter->first); } } // clang-format off const char *func_array[] = { "__loader_dlopen", "dlsym", "dlclose", "open", "write", "read", "close", "socket", "connect", "bind", "listen", "accept", "send", "recv", }; // clang-format on typeof(pthread_create) *orig_pthread_create; int fake_pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg) { LOG(1, "pthread_create: %p", start_routine); return orig_pthread_create(thread, attr, start_routine, arg); } #if 1 __attribute__((constructor)) static void ctor() { void *func = NULL; log_set_level(1); func_map = new std::map<void *, const char *>(); for (int i = 0; i < sizeof(func_array) / sizeof(char *); ++i) { func = DobbySymbolResolver(NULL, func_array[i]); if (func == NULL) { LOG(1, "func %s not resolve", func_array[i]); continue; } func_map->insert(std::pair<void *, const char *>(func, func_array[i])); } for(auto i = func_map->begin(), e = func_map->end(); i !=e ; i++) { DobbyInstrument(i->first, common_handler); } DobbyGlobalOffsetTableReplace(NULL, "_pthread_create", (void *)fake_pthread_create, (void **)&orig_pthread_create); pthread_t socket_server; uint64_t socket_demo_server(void *ctx); pthread_create(&socket_server, NULL, (void *(*)(void *))socket_demo_server, NULL); usleep(1000); pthread_t socket_client; uint64_t socket_demo_client(void *ctx); pthread_create(&socket_client, NULL, (void *(*)(void *))socket_demo_client, NULL); pthread_join(socket_client, 0); pthread_join(socket_server, 0); } #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #define PORT 8989 uint64_t socket_demo_server(void *ctx) { int server_fd, new_socket, valread; struct sockaddr_in address; int opt = 1; int addrlen = sizeof(address); char buffer[1024] = {0}; char * hello = "Hello from server"; // Creating socket file descriptor if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket failed"); exit(EXIT_FAILURE); } // Forcefully attaching socket to the port 8080 if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt))) { perror("setsockopt"); exit(EXIT_FAILURE); } address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons(PORT); // Forcefully attaching socket to the port 8080 if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) { perror("bind failed"); exit(EXIT_FAILURE); } if (listen(server_fd, 3) < 0) { perror("listen"); exit(EXIT_FAILURE); } if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t *)&addrlen)) < 0) { perror("accept"); exit(EXIT_FAILURE); } valread = recv(new_socket, buffer, 1024, 0); printf("%s\n", buffer); send(new_socket, hello, strlen(hello), 0); printf("Hello message sent\n"); return 0; } uint64_t socket_demo_client(void *ctx) { int sock = 0, valread; struct sockaddr_in serv_addr; char * hello = "Hello from client"; char buffer[1024] = {0}; if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) { printf("\n Socket creation error \n"); return -1; } serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(PORT); // Convert IPv4 and IPv6 addresses from text to binary form if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0) { printf("\nInvalid address/ Address not supported \n"); return -1; } if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { printf("\nConnection Failed \n"); return -1; } send(sock, hello, strlen(hello), 0); printf("Hello message sent\n"); valread = recv(sock, buffer, 1024, 0); printf("%s\n", buffer); return 0; } #endif <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include <cppcrate/record.h> TEST(RecordTests, Contructors) { using CppCrate::Record; using CppCrate::CrateDataType; using CppCrate::Value; Record r; EXPECT_EQ(r.size(), 0); EXPECT_TRUE(r.value(0).isInvalid()); EXPECT_TRUE(r.value("a").isInvalid()); Record r2("[1,\"Hobbes\"]", {"a", "b"}, {CrateDataType(CrateDataType::Integer), CrateDataType(CrateDataType::String)}); EXPECT_EQ(r2.size(), 2); Value v1 = r2.value(0); EXPECT_EQ(v1, r2.value("a")); EXPECT_EQ(v1.name(), "a"); EXPECT_EQ(v1.crateType().type(), CrateDataType::Integer); EXPECT_EQ(v1.asInt16(), 1); Value v2 = r2.value(1); EXPECT_EQ(v2, r2.value("b")); EXPECT_EQ(v2.name(), "b"); EXPECT_EQ(v2.crateType().type(), CrateDataType::String); Record r3("invalid", {}, {}); EXPECT_EQ(r3.size(), 0); } struct ConstructorData { std::string data; std::vector<std::string> names; std::vector<CppCrate::CrateDataType::Type> types; bool success; }; class RecordTests : public testing::TestWithParam<ConstructorData> {}; TEST_P(RecordTests, ContructorsVariants) { using CppCrate::Record; using CppCrate::CrateDataType; using CppCrate::Value; ConstructorData data = GetParam(); std::vector<CrateDataType> types; for (CrateDataType::Type t : data.types) types.emplace_back(t); Record r(data.data, data.names, types); EXPECT_EQ(r.size(), 1); EXPECT_EQ(r.value(0).crateType(), types.front()); if (!data.success) EXPECT_EQ(r.value(0).type(), Value::StringType); } INSTANTIATE_TEST_CASE_P( ContructorsVariants, RecordTests, ::testing::Values( ConstructorData{"[null]", {"a"}, {CppCrate::CrateDataType::Null}, true}, ConstructorData{"[1]", {"a"}, {CppCrate::CrateDataType::NotSupported}, true}, ConstructorData{"[1]", {"a"}, {CppCrate::CrateDataType::Byte}, true}, ConstructorData{"[true]", {"a"}, {CppCrate::CrateDataType::Boolean}, true}, ConstructorData{"[\"Calvin\"]", {"a"}, {CppCrate::CrateDataType::String}, true}, ConstructorData{"[\"1.1.1.1\"]", {"a"}, {CppCrate::CrateDataType::Ip}, true}, ConstructorData{"[1.2]", {"a"}, {CppCrate::CrateDataType::Double}, true}, ConstructorData{"[1.3]", {"a"}, {CppCrate::CrateDataType::Float}, true}, ConstructorData{"[1]", {"a"}, {CppCrate::CrateDataType::Short}, true}, ConstructorData{"[1]", {"a"}, {CppCrate::CrateDataType::Integer}, true}, ConstructorData{"[1]", {"a"}, {CppCrate::CrateDataType::Long}, true}, ConstructorData{"[1]", {"a"}, {CppCrate::CrateDataType::Timestamp}, true}, ConstructorData{"[{}]", {"a"}, {CppCrate::CrateDataType::Object}, true}, ConstructorData{"[{}]", {"a"}, {CppCrate::CrateDataType::GeoPoint}, true}, ConstructorData{"[{}]", {"a"}, {CppCrate::CrateDataType::GeoShape}, true}, ConstructorData{"[[]]", {"a"}, {CppCrate::CrateDataType::Array}, true}, ConstructorData{"[1]", {"a"}, {CppCrate::CrateDataType::Set}, true}, ConstructorData{"[1.2]", {"a"}, {CppCrate::CrateDataType::Byte}, false}, ConstructorData{"[1.2]", {"a"}, {CppCrate::CrateDataType::Integer}, false}, ConstructorData{"[1.2]", {"a"}, {CppCrate::CrateDataType::Long}, false}, ConstructorData{"[1.2]", {"a"}, {CppCrate::CrateDataType::Timestamp}, false})); TEST(RecordTests, Size) { using CppCrate::Record; using CppCrate::CrateDataType; using CppCrate::Value; const CrateDataType type(CrateDataType::Integer); Record r; EXPECT_EQ(r.size(), 0); r = Record("[1]", {"a"}, {type}); EXPECT_EQ(r.size(), 1); // name and type did not affect size r = Record("[1]", {"a", "b"}, {type}); EXPECT_EQ(r.size(), 1); r = Record("[1]", {"a", "b"}, {type, type}); EXPECT_EQ(r.size(), 1); r = Record("[1]", {"a"}, {type, type}); EXPECT_EQ(r.size(), 1); // Mismatch in data, name, and type are irrelevant r = Record("[1, 2]", {"a"}, {type}); EXPECT_EQ(r.size(), 2); EXPECT_EQ(r.value(1).type(), Value::StringType); EXPECT_EQ(r.value(1).crateType().type(), CrateDataType::NotSupported); EXPECT_EQ(r.value(1).name(), ""); } TEST(RecordTests, Value) { using CppCrate::Record; using CppCrate::CrateDataType; using CppCrate::Value; const CrateDataType type(CrateDataType::Integer); Record r("[1, 2]", {"a", "b"}, {type, type}); EXPECT_EQ(r.value(0), r.value("a")); EXPECT_EQ(r.value(1), r.value("b")); EXPECT_EQ(r.value(-1), Value()); EXPECT_EQ(r.value(20), Value()); EXPECT_EQ(r.value(""), Value()); EXPECT_EQ(r.value("Calvin"), Value()); } TEST(RecordTests, Equal) { using CppCrate::Record; using CppCrate::CrateDataType; EXPECT_EQ(Record(), Record()); const CrateDataType type(CrateDataType::Integer); Record r("[1]", {"a"}, {type}); EXPECT_EQ(r, r); EXPECT_NE(r, Record("[2]", {"a"}, {type})); EXPECT_NE(r, Record("[1]", {"b"}, {type})); EXPECT_NE(r, Record("[1]", {"a"}, {CrateDataType(CrateDataType::String)})); } TEST(RecordTests, Iterators) { using CppCrate::Record; using CppCrate::Value; using CppCrate::CrateDataType; const CrateDataType type(CrateDataType::Integer); Record r("[1, 2, 3]", {"a", "b", "c"}, {type, type, type}); CppCrate::Record::const_iterator b = r.begin(); CppCrate::Record::const_iterator e = r.end(); ASSERT_NE(b, e); EXPECT_EQ(b->name(), "a"); ++b; ASSERT_NE(b, e); EXPECT_EQ(b->name(), "b"); ++b; ASSERT_NE(b, e); EXPECT_EQ(b->name(), "c"); ++b; ASSERT_EQ(b, e); } int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>Add test coverage for Record cbegin() and cend()<commit_after>#include <gtest/gtest.h> #include <cppcrate/record.h> TEST(RecordTests, Contructors) { using CppCrate::Record; using CppCrate::CrateDataType; using CppCrate::Value; Record r; EXPECT_EQ(r.size(), 0); EXPECT_TRUE(r.value(0).isInvalid()); EXPECT_TRUE(r.value("a").isInvalid()); Record r2("[1,\"Hobbes\"]", {"a", "b"}, {CrateDataType(CrateDataType::Integer), CrateDataType(CrateDataType::String)}); EXPECT_EQ(r2.size(), 2); Value v1 = r2.value(0); EXPECT_EQ(v1, r2.value("a")); EXPECT_EQ(v1.name(), "a"); EXPECT_EQ(v1.crateType().type(), CrateDataType::Integer); EXPECT_EQ(v1.asInt16(), 1); Value v2 = r2.value(1); EXPECT_EQ(v2, r2.value("b")); EXPECT_EQ(v2.name(), "b"); EXPECT_EQ(v2.crateType().type(), CrateDataType::String); Record r3("invalid", {}, {}); EXPECT_EQ(r3.size(), 0); } struct ConstructorData { std::string data; std::vector<std::string> names; std::vector<CppCrate::CrateDataType::Type> types; bool success; }; class RecordTests : public testing::TestWithParam<ConstructorData> {}; TEST_P(RecordTests, ContructorsVariants) { using CppCrate::Record; using CppCrate::CrateDataType; using CppCrate::Value; ConstructorData data = GetParam(); std::vector<CrateDataType> types; for (CrateDataType::Type t : data.types) types.emplace_back(t); Record r(data.data, data.names, types); EXPECT_EQ(r.size(), 1); EXPECT_EQ(r.value(0).crateType(), types.front()); if (!data.success) EXPECT_EQ(r.value(0).type(), Value::StringType); } INSTANTIATE_TEST_CASE_P( ContructorsVariants, RecordTests, ::testing::Values( ConstructorData{"[null]", {"a"}, {CppCrate::CrateDataType::Null}, true}, ConstructorData{"[1]", {"a"}, {CppCrate::CrateDataType::NotSupported}, true}, ConstructorData{"[1]", {"a"}, {CppCrate::CrateDataType::Byte}, true}, ConstructorData{"[true]", {"a"}, {CppCrate::CrateDataType::Boolean}, true}, ConstructorData{"[\"Calvin\"]", {"a"}, {CppCrate::CrateDataType::String}, true}, ConstructorData{"[\"1.1.1.1\"]", {"a"}, {CppCrate::CrateDataType::Ip}, true}, ConstructorData{"[1.2]", {"a"}, {CppCrate::CrateDataType::Double}, true}, ConstructorData{"[1.3]", {"a"}, {CppCrate::CrateDataType::Float}, true}, ConstructorData{"[1]", {"a"}, {CppCrate::CrateDataType::Short}, true}, ConstructorData{"[1]", {"a"}, {CppCrate::CrateDataType::Integer}, true}, ConstructorData{"[1]", {"a"}, {CppCrate::CrateDataType::Long}, true}, ConstructorData{"[1]", {"a"}, {CppCrate::CrateDataType::Timestamp}, true}, ConstructorData{"[{}]", {"a"}, {CppCrate::CrateDataType::Object}, true}, ConstructorData{"[{}]", {"a"}, {CppCrate::CrateDataType::GeoPoint}, true}, ConstructorData{"[{}]", {"a"}, {CppCrate::CrateDataType::GeoShape}, true}, ConstructorData{"[[]]", {"a"}, {CppCrate::CrateDataType::Array}, true}, ConstructorData{"[1]", {"a"}, {CppCrate::CrateDataType::Set}, true}, ConstructorData{"[1.2]", {"a"}, {CppCrate::CrateDataType::Byte}, false}, ConstructorData{"[1.2]", {"a"}, {CppCrate::CrateDataType::Integer}, false}, ConstructorData{"[1.2]", {"a"}, {CppCrate::CrateDataType::Long}, false}, ConstructorData{"[1.2]", {"a"}, {CppCrate::CrateDataType::Timestamp}, false})); TEST(RecordTests, Size) { using CppCrate::Record; using CppCrate::CrateDataType; using CppCrate::Value; const CrateDataType type(CrateDataType::Integer); Record r; EXPECT_EQ(r.size(), 0); r = Record("[1]", {"a"}, {type}); EXPECT_EQ(r.size(), 1); // name and type did not affect size r = Record("[1]", {"a", "b"}, {type}); EXPECT_EQ(r.size(), 1); r = Record("[1]", {"a", "b"}, {type, type}); EXPECT_EQ(r.size(), 1); r = Record("[1]", {"a"}, {type, type}); EXPECT_EQ(r.size(), 1); // Mismatch in data, name, and type are irrelevant r = Record("[1, 2]", {"a"}, {type}); EXPECT_EQ(r.size(), 2); EXPECT_EQ(r.value(1).type(), Value::StringType); EXPECT_EQ(r.value(1).crateType().type(), CrateDataType::NotSupported); EXPECT_EQ(r.value(1).name(), ""); } TEST(RecordTests, Value) { using CppCrate::Record; using CppCrate::CrateDataType; using CppCrate::Value; const CrateDataType type(CrateDataType::Integer); Record r("[1, 2]", {"a", "b"}, {type, type}); EXPECT_EQ(r.value(0), r.value("a")); EXPECT_EQ(r.value(1), r.value("b")); EXPECT_EQ(r.value(-1), Value()); EXPECT_EQ(r.value(20), Value()); EXPECT_EQ(r.value(""), Value()); EXPECT_EQ(r.value("Calvin"), Value()); } TEST(RecordTests, Equal) { using CppCrate::Record; using CppCrate::CrateDataType; EXPECT_EQ(Record(), Record()); const CrateDataType type(CrateDataType::Integer); Record r("[1]", {"a"}, {type}); EXPECT_EQ(r, r); EXPECT_NE(r, Record("[2]", {"a"}, {type})); EXPECT_NE(r, Record("[1]", {"b"}, {type})); EXPECT_NE(r, Record("[1]", {"a"}, {CrateDataType(CrateDataType::String)})); } TEST(RecordTests, Iterators) { using CppCrate::Record; using CppCrate::Value; using CppCrate::CrateDataType; const CrateDataType type(CrateDataType::Integer); Record r("[1, 2, 3]", {"a", "b", "c"}, {type, type, type}); CppCrate::Record::const_iterator b = r.begin(); CppCrate::Record::const_iterator e = r.end(); ASSERT_NE(b, e); EXPECT_EQ(b->name(), "a"); ++b; ASSERT_NE(b, e); EXPECT_EQ(b->name(), "b"); ++b; ASSERT_NE(b, e); EXPECT_EQ(b->name(), "c"); ++b; ASSERT_EQ(b, e); Record empty; EXPECT_EQ(empty.begin(), empty.end()); EXPECT_EQ(empty.cbegin(), empty.cend()); } int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>#include "posit.h" #include <cstdio> #include <cmath> #define POW2(n) \ (1 << n) POSIT_UTYPE Posit::buildMask(unsigned size) { return POSIT_MASK << (POSIT_SIZE - size); } Posit::Posit(POSIT_UTYPE bits, unsigned nbits, unsigned es, bool nan) : mBits(bits), mNbits(nbits), mEs(es), mNan(nan) { } Posit::Posit(unsigned nbits, unsigned es, bool nan) : Posit(0, nbits, es, nan) { } Posit::Posit(unsigned nbits, unsigned es) : Posit(nbits, es, false) { } bool Posit::isZero() { return mBits == POSIT_ZERO; } bool Posit::isOne() { return mBits == POSIT_ONE || mBits == POSIT_MONE; } bool Posit::isInf() { return mBits == POSIT_INF; } bool Posit::isNeg() { return (POSIT_STYPE)mBits < 0 && mBits != POSIT_INF; } bool Posit::isNan() { return mNan; } unsigned Posit::nbits() { return mNbits; } unsigned Posit::rs() { signed lastBit = -1; unsigned rs = 0; // find a bit that changes, ignoring sign bit for (signed i = POSIT_SIZE - 2; i >= (signed)(POSIT_SIZE - mNbits); i--) { bool bit = (mBits >> i) & 1; rs++; if (bit != lastBit && lastBit >= 0) { break; } lastBit = bit; } return rs; } unsigned Posit::es() { unsigned efs = mNbits - 1 - rs(); unsigned es = mEs < efs ? mEs : efs; return (es >= 0 ? es : 0); } unsigned Posit::fs() { return mNbits - 1 - rs() - es(); } unsigned Posit::useed() { return POW2(POW2(mEs)); } signed Posit::regime() { POSIT_UTYPE bits = (isNeg() ? neg().mBits : mBits) << 1; POSIT_UTYPE himask = 1 << (POSIT_SIZE - 1); signed r = 0; // out of bounds regime for error handling if (isZero()) { return -mNbits + 1; } else if (isInf()) { return mNbits - 1; } if (bits & himask) { // >0 while (1) { bits <<= 1; if (!(bits & himask)) break; r++; } } else { // <=0 while (1) { bits <<= 1; r--; if (bits & himask) break; } } return r; } POSIT_UTYPE Posit::exponent() { POSIT_UTYPE expBits = (mBits & (buildMask(mEs) >> (1 + rs()))); return expBits >> (POSIT_SIZE - mNbits + fs()); } POSIT_UTYPE Posit::fraction() { POSIT_UTYPE fracBits = (mBits & (buildMask(fs()) >> (1 + rs() + es()))); return fracBits >> (POSIT_SIZE - mNbits); } Posit Posit::zero() { return Posit(POSIT_ZERO, mNbits, mEs, false); } Posit Posit::one() { return Posit(POSIT_ONE, mNbits, mEs, false); } Posit Posit::inf() { return Posit(POSIT_INF, mNbits, mEs, false); } Posit Posit::nan() { return Posit(mNbits, mEs, true); } Posit Posit::neg() { Posit p = Posit(mNbits, mEs); POSIT_UTYPE mask = buildMask(mNbits); // reverse all bits and add one p.mBits = ((mBits ^ POSIT_MASK) + 1) & mask; return p; } Posit Posit::rec() { Posit p = Posit(mNbits, mEs); POSIT_UTYPE mask = buildMask(mNbits); // reverse all bits but the first one and add one p.mBits = ((mBits ^ (POSIT_MASK >> 1)) + 1) & mask; return p; } Posit Posit::add(Posit& p) { // fast exit if (isZero()) { return p; } else if (p.isZero()) { return *this; } else if (isInf() && p.isInf()) { return nan(); } else if (isInf() || p.isInf()) { return inf(); } else if (neg().eq(p)) { return zero(); } // TODO implement return *this; } Posit Posit::sub(Posit& p) { // no loss on negation Posit np = p.neg(); return add(np); } Posit Posit::mul(Posit& p) { // fast exit if (isZero()) { return (p.isInf() ? nan() : zero()); } else if (p.isZero()) { return (isInf() ? nan() : zero()); } else if (isOne()) { return (isNeg() ? p.neg() : p); } else if (p.isOne()) { return (p.isNeg() ? neg() : *this); } else if (isInf() || p.isInf()) { return inf(); } else if (rec().eq(p)) { return one(); } else if (rec().neg().eq(p)) { return one().neg(); } // TODO implement return *this; } Posit Posit::div(Posit& p) { // no loss on reciprocation! Posit rp = p.rec(); return mul(rp); } bool Posit::eq(Posit& p) { return mBits == p.mBits; } bool Posit::gt(Posit& p) { if (isInf() || p.isInf()) { return false; } return mBits > p.mBits; } bool Posit::ge(Posit& p) { return gt(p) || eq(p); } bool Posit::lt(Posit& p) { return !gt(p) && !eq(p); } bool Posit::le(Posit& p) { return !gt(p); } void Posit::set(int n) { // TODO implement } void Posit::set(float n) { // TODO implement } void Posit::set(double n) { // TODO implement } int Posit::getInt() { return (int)roundf(getFloat()); } float Posit::getFloat() { if (isZero()) { return 0.f; } else if (isInf()) { return 1.f / 0.f; } Posit p = (isNeg() ? neg() : *this); return (isNeg() ? -1 : 1) * powf(p.useed(), p.regime()) * POW2(p.exponent()) * (1 + (float)p.fraction() / POW2(p.fs())); } double Posit::getDouble() { if (isZero()) { return 0.0; } else if (isInf()) { return 1.0 / 0.0; } Posit p = (isNeg() ? neg() : *this); return (isNeg() ? -1 : 1) * pow(p.useed(), p.regime()) * POW2(p.exponent()) * (1 + (double)p.fraction() / POW2(p.fs())); } void Posit::setBits(POSIT_UTYPE bits) { mBits = bits << (POSIT_SIZE - mNbits); } POSIT_UTYPE Posit::getBits() { return mBits >> (POSIT_SIZE - mNbits); } void Posit::print() { Posit p = isNeg() || isInf() ? neg() : *this; printf("{%d, %d} ", mNbits, mEs); for (signed i = POSIT_SIZE - 1; i >= (signed)(POSIT_SIZE - mNbits); i--) { printf("%d", (mBits >> i) & 1); } printf(" (%d) -> ", regime()); printf(isNeg() || isInf() ? "-" : "+"); for (signed i = POSIT_SIZE - 2; i >= (signed)(POSIT_SIZE - mNbits); i--) { printf("%d", (p.mBits >> i) & 1); if (i != (signed)(POSIT_SIZE - mNbits) && (((unsigned)i == (POSIT_SIZE - 1 - p.rs())) || ((unsigned)i == (POSIT_SIZE - 1 - p.rs() - mEs)))) { printf(" "); } } printf(" = %lg\n", getDouble()); } <commit_msg>lib: use clz instruction for rs()<commit_after>#include "posit.h" #include <cstdio> #include <cmath> #ifdef __GNUC__ #define CLZ(n) \ __builtin_clz(n) #endif #define POW2(n) \ (1 << n) POSIT_UTYPE Posit::buildMask(unsigned size) { return POSIT_MASK << (POSIT_SIZE - size); } Posit::Posit(POSIT_UTYPE bits, unsigned nbits, unsigned es, bool nan) : mBits(bits), mNbits(nbits), mEs(es), mNan(nan) { } Posit::Posit(unsigned nbits, unsigned es, bool nan) : Posit(0, nbits, es, nan) { } Posit::Posit(unsigned nbits, unsigned es) : Posit(nbits, es, false) { } bool Posit::isZero() { return mBits == POSIT_ZERO; } bool Posit::isOne() { return mBits == POSIT_ONE || mBits == POSIT_MONE; } bool Posit::isInf() { return mBits == POSIT_INF; } bool Posit::isNeg() { return (POSIT_STYPE)mBits < 0 && mBits != POSIT_INF; } bool Posit::isNan() { return mNan; } unsigned Posit::nbits() { return mNbits; } unsigned Posit::rs() { unsigned lz = CLZ(mBits << 1); unsigned lo = CLZ(~mBits << 1); unsigned rs = (lz > lo ? lz : lo) + 1; return rs < mNbits - 1 ? rs : mNbits - 1; } unsigned Posit::es() { unsigned efs = mNbits - 1 - rs(); unsigned es = mEs < efs ? mEs : efs; return (es >= 0 ? es : 0); } unsigned Posit::fs() { return mNbits - 1 - rs() - es(); } unsigned Posit::useed() { return POW2(POW2(mEs)); } signed Posit::regime() { POSIT_UTYPE bits = (isNeg() ? neg().mBits : mBits) << 1; POSIT_UTYPE himask = 1 << (POSIT_SIZE - 1); signed r = 0; // out of bounds regime for error handling if (isZero()) { return -mNbits + 1; } else if (isInf()) { return mNbits - 1; } if (bits & himask) { // >0 while (1) { bits <<= 1; if (!(bits & himask)) break; r++; } } else { // <=0 while (1) { bits <<= 1; r--; if (bits & himask) break; } } return r; } POSIT_UTYPE Posit::exponent() { POSIT_UTYPE expBits = (mBits & (buildMask(mEs) >> (1 + rs()))); return expBits >> (POSIT_SIZE - mNbits + fs()); } POSIT_UTYPE Posit::fraction() { POSIT_UTYPE fracBits = (mBits & (buildMask(fs()) >> (1 + rs() + es()))); return fracBits >> (POSIT_SIZE - mNbits); } Posit Posit::zero() { return Posit(POSIT_ZERO, mNbits, mEs, false); } Posit Posit::one() { return Posit(POSIT_ONE, mNbits, mEs, false); } Posit Posit::inf() { return Posit(POSIT_INF, mNbits, mEs, false); } Posit Posit::nan() { return Posit(mNbits, mEs, true); } Posit Posit::neg() { Posit p = Posit(mNbits, mEs); POSIT_UTYPE mask = buildMask(mNbits); // reverse all bits and add one p.mBits = ((mBits ^ POSIT_MASK) + 1) & mask; return p; } Posit Posit::rec() { Posit p = Posit(mNbits, mEs); POSIT_UTYPE mask = buildMask(mNbits); // reverse all bits but the first one and add one p.mBits = ((mBits ^ (POSIT_MASK >> 1)) + 1) & mask; return p; } Posit Posit::add(Posit& p) { // fast exit if (isZero()) { return p; } else if (p.isZero()) { return *this; } else if (isInf() && p.isInf()) { return nan(); } else if (isInf() || p.isInf()) { return inf(); } else if (neg().eq(p)) { return zero(); } // TODO implement return *this; } Posit Posit::sub(Posit& p) { // no loss on negation Posit np = p.neg(); return add(np); } Posit Posit::mul(Posit& p) { // fast exit if (isZero()) { return (p.isInf() ? nan() : zero()); } else if (p.isZero()) { return (isInf() ? nan() : zero()); } else if (isOne()) { return (isNeg() ? p.neg() : p); } else if (p.isOne()) { return (p.isNeg() ? neg() : *this); } else if (isInf() || p.isInf()) { return inf(); } else if (rec().eq(p)) { return one(); } else if (rec().neg().eq(p)) { return one().neg(); } // TODO implement return *this; } Posit Posit::div(Posit& p) { // no loss on reciprocation! Posit rp = p.rec(); return mul(rp); } bool Posit::eq(Posit& p) { return mBits == p.mBits; } bool Posit::gt(Posit& p) { if (isInf() || p.isInf()) { return false; } return mBits > p.mBits; } bool Posit::ge(Posit& p) { return gt(p) || eq(p); } bool Posit::lt(Posit& p) { return !gt(p) && !eq(p); } bool Posit::le(Posit& p) { return !gt(p); } void Posit::set(int n) { // TODO implement } void Posit::set(float n) { // TODO implement } void Posit::set(double n) { // TODO implement } int Posit::getInt() { return (int)roundf(getFloat()); } float Posit::getFloat() { if (isZero()) { return 0.f; } else if (isInf()) { return 1.f / 0.f; } Posit p = (isNeg() ? neg() : *this); return (isNeg() ? -1 : 1) * powf(p.useed(), p.regime()) * POW2(p.exponent()) * (1 + (float)p.fraction() / POW2(p.fs())); } double Posit::getDouble() { if (isZero()) { return 0.0; } else if (isInf()) { return 1.0 / 0.0; } Posit p = (isNeg() ? neg() : *this); return (isNeg() ? -1 : 1) * pow(p.useed(), p.regime()) * POW2(p.exponent()) * (1 + (double)p.fraction() / POW2(p.fs())); } void Posit::setBits(POSIT_UTYPE bits) { mBits = bits << (POSIT_SIZE - mNbits); } POSIT_UTYPE Posit::getBits() { return mBits >> (POSIT_SIZE - mNbits); } void Posit::print() { Posit p = isNeg() || isInf() ? neg() : *this; printf("{%d, %d} ", mNbits, mEs); for (signed i = POSIT_SIZE - 1; i >= (signed)(POSIT_SIZE - mNbits); i--) { printf("%d", (mBits >> i) & 1); } printf(" (%d) -> ", regime()); printf(isNeg() || isInf() ? "-" : "+"); for (signed i = POSIT_SIZE - 2; i >= (signed)(POSIT_SIZE - mNbits); i--) { printf("%d", (p.mBits >> i) & 1); if (i != (signed)(POSIT_SIZE - mNbits) && (((unsigned)i == (POSIT_SIZE - 1 - p.rs())) || ((unsigned)i == (POSIT_SIZE - 1 - p.rs() - mEs)))) { printf(" "); } } printf(" = %lg\n", getDouble()); } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <iterator> #include <string> #include <cstdlib> void doCopy(const std::string infilename, const std::string outfilename={}) { using namespace std; using CharInputStreamBufIter = istreambuf_iterator<char>; using CharOutputStreamBufIter = ostreambuf_iterator<char>; ifstream infile { infilename }; if(!infile) { cout << "Unable to open input file: " << infilename << endl; exit(1); } ofstream outfile { }; ostream *output = nullptr; if( outfilename.empty() ) { output = &cout; cout << "Copying text to standard output instead.." << endl; } else { outfile.open(outfilename); if(!outfile) { cout << "Unable to open output file: " << outfilename << endl; exit(1); } output = &outfile; cout << infilename << " -> " << outfilename << endl; } copy(CharInputStreamBufIter(infile), CharInputStreamBufIter(), CharOutputStreamBufIter(*output)); } int main(int argc, char *argv[]) { using namespace std; switch (argc) { case 1: cout << argv[0] << ": missing file operand" << endl; exit(EXIT_FAILURE); break; case 2: cout << argv[0] << ": missing destination file operand after " << argv[1] << endl; doCopy(argv[1]); break; case 3: doCopy(argv[1], argv[2]); break; default: cout << "Should we even reach here?" << endl; break; } return EXIT_SUCCESS; } <commit_msg>Handle the case with more than one destination file is specified<commit_after>#include <iostream> #include <fstream> #include <iterator> #include <string> #include <cstdlib> void doCopy(const std::string infilename, const std::string outfilename={}) { using namespace std; using CharInputStreamBufIter = istreambuf_iterator<char>; using CharOutputStreamBufIter = ostreambuf_iterator<char>; ifstream infile { infilename }; if(!infile) { cout << "Unable to open input file: " << infilename << endl; exit(EXIT_FAILURE); } ofstream outfile { }; ostream *output = nullptr; if( outfilename.empty() ) { output = &cout; cout << "Copying text to standard output instead.." << endl; } else { outfile.open(outfilename); if(!outfile) { cout << "Unable to open output file: " << outfilename << endl; exit(EXIT_FAILURE); } output = &outfile; cout << infilename << " -> " << outfilename << endl; } copy(CharInputStreamBufIter(infile), CharInputStreamBufIter(), CharOutputStreamBufIter(*output)); } int main(int argc, char *argv[]) { using namespace std; switch (argc) { case 1: cout << argv[0] << ": missing file operand" << endl; exit(EXIT_FAILURE); break; case 2: cout << argv[0] << ": missing destination file operand after " << argv[1] << endl; doCopy(argv[1]); break; case 3: doCopy(argv[1], argv[2]); break; default: cout << "You cany only copy from one source to one destination." << endl; cout << "Usage: " << argv[0] << " <source file> <destination file>" << endl; exit(EXIT_FAILURE); break; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/** \file EmailSender.cc * \brief Utility functions etc. related to the sending of email messages. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2015 Universitätsbiblothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "EmailSender.h" #include <stdexcept> #include <vector> #include <cstdlib> #include "Compiler.h" #include "ExecUtil.h" #include "FileUtil.h" #include "util.h" namespace { /** \brief Temorarily replace an environment variable's value. */ class ReplaceEnvVar { std::string variable_name_; std::string old_value_; public: /** \brief Replace the value w/ "temp_value". */ ReplaceEnvVar(const std::string &variable_name, const std::string &temp_value) ; /** \brief Restore the old value. */ ~ReplaceEnvVar(); }; ReplaceEnvVar::ReplaceEnvVar(const std::string &variable_name, const std::string &temp_value) { const char * const old_value(::getenv(variable_name.c_str())); if (old_value != nullptr) { variable_name_ = variable_name; old_value_ = old_value; } if (unlikely(::setenv(variable_name.c_str(), temp_value.c_str(), /* overwrite = */ true) != 0)) Error("setenv(3) failed in ReplaceEnvVar::ReplaceEnvVar! (errno: " + std::to_string(errno) + ")"); } ReplaceEnvVar:: ~ReplaceEnvVar() { if (not variable_name_.empty()) { if (unlikely(::setenv(variable_name_.c_str(), old_value_.c_str(), /* overwrite = */ true) != 0)) Error("setenv(3) failed in ReplaceEnvVar::~ReplaceEnvVar! (errno: " + std::to_string(errno) + ")"); } } } // unnamed namespace namespace EmailSender { bool SendEmail(const std::string &sender, const std::string &recipient, const std::string &subject, const std::string &message_body) { ReplaceEnvVar replace_env_var("PATH", "/bin:/usr/bin"); const std::string MAILX_PATH(ExecUtil::Which("mailx")); if (unlikely(MAILX_PATH.empty())) Error("in EmailSender::SendEmail: can't find \"mailx\"!"); FileUtil::AutoTempFile auto_temp_file; const std::string &stdin_replacement_for_mailx(auto_temp_file.getFilePath()); if (not FileUtil::WriteString(stdin_replacement_for_mailx, message_body)) Error("in EmailSender::SendEmail: can't write the message body into a temporary file!"); return ExecUtil::Exec(MAILX_PATH, { "-a", "Reply-To: " + sender, "-s ", subject, recipient }, stdin_replacement_for_mailx) == 0; } } // namespace EmailSender <commit_msg>Fixed a parameter that is being passed to mailx.<commit_after>/** \file EmailSender.cc * \brief Utility functions etc. related to the sending of email messages. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2015 Universitätsbiblothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "EmailSender.h" #include <stdexcept> #include <vector> #include <cstdlib> #include "Compiler.h" #include "ExecUtil.h" #include "FileUtil.h" #include "util.h" namespace { /** \brief Temorarily replace an environment variable's value. */ class ReplaceEnvVar { std::string variable_name_; std::string old_value_; public: /** \brief Replace the value w/ "temp_value". */ ReplaceEnvVar(const std::string &variable_name, const std::string &temp_value) ; /** \brief Restore the old value. */ ~ReplaceEnvVar(); }; ReplaceEnvVar::ReplaceEnvVar(const std::string &variable_name, const std::string &temp_value) { const char * const old_value(::getenv(variable_name.c_str())); if (old_value != nullptr) { variable_name_ = variable_name; old_value_ = old_value; } if (unlikely(::setenv(variable_name.c_str(), temp_value.c_str(), /* overwrite = */ true) != 0)) Error("setenv(3) failed in ReplaceEnvVar::ReplaceEnvVar! (errno: " + std::to_string(errno) + ")"); } ReplaceEnvVar:: ~ReplaceEnvVar() { if (not variable_name_.empty()) { if (unlikely(::setenv(variable_name_.c_str(), old_value_.c_str(), /* overwrite = */ true) != 0)) Error("setenv(3) failed in ReplaceEnvVar::~ReplaceEnvVar! (errno: " + std::to_string(errno) + ")"); } } } // unnamed namespace namespace EmailSender { bool SendEmail(const std::string &sender, const std::string &recipient, const std::string &subject, const std::string &message_body) { ReplaceEnvVar replace_env_var("PATH", "/bin:/usr/bin"); const std::string MAILX_PATH(ExecUtil::Which("mailx")); if (unlikely(MAILX_PATH.empty())) Error("in EmailSender::SendEmail: can't find \"mailx\"!"); FileUtil::AutoTempFile auto_temp_file; const std::string &stdin_replacement_for_mailx(auto_temp_file.getFilePath()); if (not FileUtil::WriteString(stdin_replacement_for_mailx, message_body)) Error("in EmailSender::SendEmail: can't write the message body into a temporary file!"); return ExecUtil::Exec(MAILX_PATH, { "-a", "Reply-To: " + sender, "-s", subject, recipient }, stdin_replacement_for_mailx) == 0; } } // namespace EmailSender <|endoftext|>
<commit_before>// Copyright (C) 2011, 2012 Strahinja Val Markovic <val@markovic.io> // // This file is part of YouCompleteMe. // // YouCompleteMe 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. // // YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>. #include "LetterHash.h" #include "standard.h" namespace YouCompleteMe { const int kNumLetters = NUM_LETTERS; static const int kLettersIndexStart = 0; static const int kNumbersIndexStart = 26; bool IsUppercase( char letter ) { return 'A' <= letter && letter <= 'Z'; } int IndexForChar( char letter ) { if ( IsUppercase( letter ) ) return letter + ( 'a' - 'A' ); return letter; } LetterHash::LetterHash() { letters_.resize( kNumLetters ); for ( uint i = 0; i < letters_.size(); ++i ) { letters_[ i ] = NULL; } } LetterHash::~LetterHash() { for ( uint i = 0; i < letters_.size(); ++i ) { delete letters_[ i ]; } } bool LetterHash::HasLetter( char letter ) { int letter_index = IndexForChar( letter ); std::list< LetterNode* > *list = letters_[ letter_index ]; return list; } std::list< LetterNode* >& LetterHash::operator[] ( char letter ) { int letter_index = IndexForChar( letter ); std::list< LetterNode* > *list = letters_[ letter_index ]; if ( list ) return *list; letters_[ letter_index ] = new std::list< LetterNode* >(); return *letters_[ letter_index ]; } std::list< LetterNode* >* LetterHash::ListPointerAt( char letter ) { return letters_[ IndexForChar( letter ) ]; } bool LetterHash::HasLetter( char letter ) const { return letters_[ IndexForChar( letter ) ] != NULL; } } // namespace YouCompleteMe <commit_msg>Small whitespace fix<commit_after>// Copyright (C) 2011, 2012 Strahinja Val Markovic <val@markovic.io> // // This file is part of YouCompleteMe. // // YouCompleteMe 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. // // YouCompleteMe 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 YouCompleteMe. If not, see <http://www.gnu.org/licenses/>. #include "LetterHash.h" #include "standard.h" namespace YouCompleteMe { const int kNumLetters = NUM_LETTERS; static const int kLettersIndexStart = 0; static const int kNumbersIndexStart = 26; bool IsUppercase( char letter ) { return 'A' <= letter && letter <= 'Z'; } int IndexForChar( char letter ) { if ( IsUppercase( letter ) ) return letter + ( 'a' - 'A' ); return letter; } LetterHash::LetterHash() { letters_.resize( kNumLetters ); for ( uint i = 0; i < letters_.size(); ++i ) { letters_[ i ] = NULL; } } LetterHash::~LetterHash() { for ( uint i = 0; i < letters_.size(); ++i ) { delete letters_[ i ]; } } bool LetterHash::HasLetter( char letter ) { int letter_index = IndexForChar( letter ); std::list< LetterNode* > *list = letters_[ letter_index ]; return list; } std::list< LetterNode* >& LetterHash::operator[] ( char letter ) { int letter_index = IndexForChar( letter ); std::list< LetterNode* > *list = letters_[ letter_index ]; if ( list ) return *list; letters_[ letter_index ] = new std::list< LetterNode* >(); return *letters_[ letter_index ]; } std::list< LetterNode* >* LetterHash::ListPointerAt( char letter ) { return letters_[ IndexForChar( letter ) ]; } bool LetterHash::HasLetter( char letter ) const { return letters_[ IndexForChar( letter ) ] != NULL; } } // namespace YouCompleteMe <|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "SSLImpl.hpp" #include <cstdint> #include <stdexcept> #include <ace/Guard_T.h> namespace apache { namespace geode { namespace client { ACE_Recursive_Thread_Mutex SSLImpl::s_mutex; volatile bool SSLImpl::s_initialized = false; void *gf_create_SslImpl(ACE_HANDLE sock, const char *pubkeyfile, const char *privkeyfile, const char *pemPassword) { return reinterpret_cast<void *>( new SSLImpl(sock, pubkeyfile, privkeyfile, pemPassword)); } void gf_destroy_SslImpl(void *impl) { SSLImpl *theLib = reinterpret_cast<SSLImpl *>(impl); delete theLib; } extern "C" { static int pem_passwd_cb(char *buf, int size, int /*rwflag*/, void *passwd) { strncpy(buf, (char *)passwd, size); buf[size - 1] = '\0'; return static_cast<int>(strlen(buf)); } } SSLImpl::SSLImpl(ACE_HANDLE sock, const char *pubkeyfile, const char *privkeyfile, const char *password) { ACE_Guard<ACE_Recursive_Thread_Mutex> guard(SSLImpl::s_mutex); if (SSLImpl::s_initialized == false) { ACE_SSL_Context *sslctx = ACE_SSL_Context::instance(); SSL_CTX_set_cipher_list(sslctx->context(), "DEFAULT"); sslctx->set_mode(ACE_SSL_Context::SSLv23_client); if (sslctx->load_trusted_ca(pubkeyfile) != 0) { throw std::invalid_argument("Failed to read SSL trust store."); } if (strlen(password) > 0) { SSL_CTX_set_default_passwd_cb(sslctx->context(), pem_passwd_cb); SSL_CTX_set_default_passwd_cb_userdata(sslctx->context(), const_cast<char *>(password)); } if (sslctx->private_key(privkeyfile) != 0) { throw std::invalid_argument("Invalid SSL keystore password."); } if (sslctx->certificate(privkeyfile) != 0) { throw std::invalid_argument("Failed to read SSL certificate."); } if (::SSL_CTX_use_certificate_chain_file(sslctx->context(), privkeyfile) <= 0) { throw std::invalid_argument("Failed to read SSL certificate chain."); } SSLImpl::s_initialized = true; } m_io = new ACE_SSL_SOCK_Stream(); m_io->set_handle(sock); } SSLImpl::~SSLImpl() { ACE_Guard<ACE_Recursive_Thread_Mutex> guard(SSLImpl::s_mutex); if (m_io) { delete m_io; } } void SSLImpl::close() { ACE_Guard<ACE_Recursive_Thread_Mutex> guard(SSLImpl::s_mutex); if (m_io) { m_io->close(); } } int SSLImpl::setOption(int level, int option, void *optval, int optlen) { return m_io->set_option(level, option, optval, optlen); } int SSLImpl::listen(ACE_INET_Addr addr, std::chrono::microseconds waitSeconds) { ACE_SSL_SOCK_Acceptor listener(addr, 1); if (waitSeconds > std::chrono::microseconds::zero()) { ACE_Time_Value wtime(waitSeconds); return listener.accept(*m_io, nullptr, &wtime); } else { return listener.accept(*m_io, nullptr); } } int SSLImpl::connect(ACE_INET_Addr ipaddr, std::chrono::microseconds waitSeconds) { ACE_SSL_SOCK_Connector conn; if (waitSeconds > std::chrono::microseconds::zero()) { ACE_Time_Value wtime(waitSeconds); return conn.connect(*m_io, ipaddr, &wtime); } else { return conn.connect(*m_io, ipaddr); } } ssize_t SSLImpl::recv(void *buf, size_t len, const ACE_Time_Value *timeout, size_t *bytes_transferred) { return m_io->recv_n(buf, len, 0, timeout, bytes_transferred); } ssize_t SSLImpl::send(const void *buf, size_t len, const ACE_Time_Value *timeout, size_t *bytes_transferred) { return m_io->send_n(buf, len, 0, timeout, bytes_transferred); } int SSLImpl::getLocalAddr(ACE_Addr &addr) { return m_io->get_local_addr(addr); } } // namespace client } // namespace geode } // namespace apache <commit_msg>GEODE-7451: Fix cert & priv key add order (#550)<commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "SSLImpl.hpp" #include <cstdint> #include <stdexcept> #include <ace/Guard_T.h> namespace apache { namespace geode { namespace client { ACE_Recursive_Thread_Mutex SSLImpl::s_mutex; volatile bool SSLImpl::s_initialized = false; void *gf_create_SslImpl(ACE_HANDLE sock, const char *pubkeyfile, const char *privkeyfile, const char *pemPassword) { return reinterpret_cast<void *>( new SSLImpl(sock, pubkeyfile, privkeyfile, pemPassword)); } void gf_destroy_SslImpl(void *impl) { SSLImpl *theLib = reinterpret_cast<SSLImpl *>(impl); delete theLib; } extern "C" { static int pem_passwd_cb(char *buf, int size, int /*rwflag*/, void *passwd) { strncpy(buf, (char *)passwd, size); buf[size - 1] = '\0'; return static_cast<int>(strlen(buf)); } } SSLImpl::SSLImpl(ACE_HANDLE sock, const char *pubkeyfile, const char *privkeyfile, const char *password) { ACE_Guard<ACE_Recursive_Thread_Mutex> guard(SSLImpl::s_mutex); if (SSLImpl::s_initialized == false) { ACE_SSL_Context *sslctx = ACE_SSL_Context::instance(); SSL_CTX_set_cipher_list(sslctx->context(), "DEFAULT"); sslctx->set_mode(ACE_SSL_Context::SSLv23_client); if (sslctx->load_trusted_ca(pubkeyfile) != 0) { throw std::invalid_argument("Failed to read SSL trust store."); } if (strlen(password) > 0) { SSL_CTX_set_default_passwd_cb(sslctx->context(), pem_passwd_cb); SSL_CTX_set_default_passwd_cb_userdata(sslctx->context(), const_cast<char *>(password)); } if (sslctx->certificate(privkeyfile) != 0) { throw std::invalid_argument("Failed to read SSL certificate."); } if (sslctx->private_key(privkeyfile) != 0) { throw std::invalid_argument("Invalid SSL keystore password."); } if (::SSL_CTX_use_certificate_chain_file(sslctx->context(), privkeyfile) <= 0) { throw std::invalid_argument("Failed to read SSL certificate chain."); } SSLImpl::s_initialized = true; } m_io = new ACE_SSL_SOCK_Stream(); m_io->set_handle(sock); } SSLImpl::~SSLImpl() { ACE_Guard<ACE_Recursive_Thread_Mutex> guard(SSLImpl::s_mutex); if (m_io) { delete m_io; } } void SSLImpl::close() { ACE_Guard<ACE_Recursive_Thread_Mutex> guard(SSLImpl::s_mutex); if (m_io) { m_io->close(); } } int SSLImpl::setOption(int level, int option, void *optval, int optlen) { return m_io->set_option(level, option, optval, optlen); } int SSLImpl::listen(ACE_INET_Addr addr, std::chrono::microseconds waitSeconds) { ACE_SSL_SOCK_Acceptor listener(addr, 1); if (waitSeconds > std::chrono::microseconds::zero()) { ACE_Time_Value wtime(waitSeconds); return listener.accept(*m_io, nullptr, &wtime); } else { return listener.accept(*m_io, nullptr); } } int SSLImpl::connect(ACE_INET_Addr ipaddr, std::chrono::microseconds waitSeconds) { ACE_SSL_SOCK_Connector conn; if (waitSeconds > std::chrono::microseconds::zero()) { ACE_Time_Value wtime(waitSeconds); return conn.connect(*m_io, ipaddr, &wtime); } else { return conn.connect(*m_io, ipaddr); } } ssize_t SSLImpl::recv(void *buf, size_t len, const ACE_Time_Value *timeout, size_t *bytes_transferred) { return m_io->recv_n(buf, len, 0, timeout, bytes_transferred); } ssize_t SSLImpl::send(const void *buf, size_t len, const ACE_Time_Value *timeout, size_t *bytes_transferred) { return m_io->send_n(buf, len, 0, timeout, bytes_transferred); } int SSLImpl::getLocalAddr(ACE_Addr &addr) { return m_io->get_local_addr(addr); } } // namespace client } // namespace geode } // namespace apache <|endoftext|>
<commit_before>#include "samples.hpp" #include <powerset.hpp> #include <range.hpp> #include <vector> #include <iostream> using iter::powerset; int main() { std::vector<int> vec {1,2,3,4,5,6,7,8,9}; for (auto v : powerset(vec)) { for (auto i : v) std::cout << i << " "; std::cout << std::endl; } std::cout << "with temporary\n"; for (auto v : powerset(std::vector<int>{1,2,3})) { for (auto i : v) std::cout << i << " "; std::cout << std::endl; } std::cout << "with initializer_list\n"; for (auto v : powerset({1,2,3})) { for (auto i : v) std::cout << i << " "; std::cout << std::endl; } std::cout << "with container of move-only objects\n"; std::vector<itertest::MoveOnly> mv; for (auto i : iter::range(3)) { mv.emplace_back(i); } return 0; } <commit_msg>actually adds the test for move-only objects<commit_after>#include "samples.hpp" #include <powerset.hpp> #include <range.hpp> #include <vector> #include <iostream> using iter::powerset; int main() { std::vector<int> vec {1,2,3,4,5,6,7,8,9}; for (auto v : powerset(vec)) { for (auto i : v) std::cout << i << " "; std::cout << std::endl; } std::cout << "with temporary\n"; for (auto v : powerset(std::vector<int>{1,2,3})) { for (auto i : v) std::cout << i << " "; std::cout << std::endl; } std::cout << "with initializer_list\n"; for (auto v : powerset({1,2,3})) { for (auto i : v) std::cout << i << " "; std::cout << std::endl; } std::cout << "with container of move-only objects\n"; std::vector<itertest::MoveOnly> mv; for (auto i : iter::range(3)) { mv.emplace_back(i); } for (auto v : powerset(mv)) { for (auto i : v) std::cout << i << " "; std::cout << std::endl; } return 0; } <|endoftext|>
<commit_before> #include <gtest/gtest.h> #include <ValueElement.h> namespace tests { namespace valueElementSuite { template<typename T, bool U> bool exactlyEqual(const ValueElement<T, U>& a, const ValueElement<T, U>& b) { return a.value() == b.value() && a.uncertainty() == b.uncertainty(); } #define testComp(a, b, eq, ne, le, ge, lt, gt) { \ EXPECT_EQ(a==b, eq) << a << " == " << b << " = " << (a==b) << " != " << eq; \ EXPECT_EQ(a!=b, ne) << a << " != " << b << " = " << (a!=b) << " != " << ne; \ EXPECT_EQ(a<=b, le) << a << " <= " << b << " = " << (a<=b) << " != " << le; \ EXPECT_EQ(a>=b, ge) << a << " >= " << b << " = " << (a>=b) << " != " << ge; \ EXPECT_EQ(a<b, lt) << a << " < " << b << " = " << (a<b) << " != " << lt; \ EXPECT_EQ(a>b, gt) << a << " > " << b << " = " << (a>b) << " != " << gt; \ } #define testOp(a, b, add, sub, mul, div) { \ EXPECT_TRUE(exactlyEqual(a+b, add)) << a << " + " << b << " = " << (a+b) << " != " << add; \ EXPECT_TRUE(exactlyEqual(a-b, sub)) << a << " - " << b << " = " << (a-b) << " != " << sub; \ EXPECT_TRUE(exactlyEqual(a*b, mul)) << a << " * " << b << " = " << (a*b) << " != " << mul; \ EXPECT_TRUE(exactlyEqual(a/b, div)) << a << " / " << b << " = " << (a/b) << " != " << div; \ } TEST(ValueElementSuite, certainBoolTest) { using V=ValueElement<bool, false>; V e0 = {false}; V e1 = { true}; testComp(e0, e1, false, true , true, false, true , false); testOp(e0, e1, e1, e0, e0, e0); } TEST(ValueElementSuite, uncertainBoolTest) { using V=ValueElement<bool, false>; V e0 = {false, false}; V e1 = { true, false}; V e2 = {false, true}; V e3 = { true, true}; testComp(e0, e1, false, true , true , false, true , false); testOp(e0, e1, e1, e0, e0, e0); testComp(e0, e2, true , false, true , true , false, false); testOp(e0, e2, e2, e2, e0, e2); testComp(e1, e3, true , false, true , true , false, false); testOp(e1, e3, e3, e2, e3, e2); } TEST(ValueElementSuite, certainUInt8Test) { using V=ValueElement<uint8_t, false>; V e0 = { 0}; V e1 = {255}; V a = { 13}; V b = { 73}; V c = { 3}; testComp(a, b, false, true , true , false, true , false); testComp(a, c, false, true , false, true , false, true ); testComp(b, c, false, true , false, true , false, true ); testOp(a, e0, a, a, V({ 0}), V({ 0})); testOp(a, e1, V({255}), V({ 0}), V({255}), V({ 0})); testOp(a, b, V({ 86}), V({ 0}), V({255}), V({ 0})); testOp(a, c, V({ 16}), V({10}), V({ 39}), V({ 4})); } TEST(ValueElementSuite, certainInt8Test) { using V=ValueElement<int8_t, false>; V e0 = { 0}; V e1 = { 127}; V e2 = {-128}; V a = { 13}; V b = {- 73}; V c = { 3}; testComp(a, b, false, true , false, true , false, true ); testComp(a, c, false, true , false, true , false, true ); testComp(b, c, false, true , true , false, true , false); testOp(a, e0, a, a, V({ 0}), V({ 0})); testOp(a, e1, V({ 127}), V({-114}), V({ 127}), V({ 0})); testOp(a, e2, V({-115}), V({ 127}), V({-128}), V({ 0})); testOp(a, b, V({- 60}), V({ 86}), V({-128}), V({ 0})); testOp(a, c, V({ 16}), V({ 10}), V({ 39}), V({ 4})); } TEST(ValueElementSuite, uncertainUInt8Test) { using V=ValueElement<uint8_t, true>; V e0 = {0, 0}; V e1 = {0, 255}; V e2 = {255, 0}; V e3 = {255, 255}; V a={13, 37}; V b={73, 1}; V c={3, 2}; testComp(a, b, false, true , true , false, true , false); testComp(a, c, true , false, true , true , false, false); testComp(b, c, false, true , false, true , false, true ); testOp(a, e0, a, a, V({0, 0}), V({0, 255})); testOp(a, e1, V({13, 255}) , V({13, 255}), V({0, 255}) , V({0, 255})); testOp(a, e2, V({255, 255}), V({0, 255}) , V({255, 255}), V({0, 1}) ); testOp(a, e3, V({255, 255}), V({0, 255}) , V({255, 255}), V({0, 255})); testOp(a, b, V({86, 38}), V({0, 255}), V({255, 255}), V({0, 1})); testOp(a, c, V({16, 39}), V({10, 39}), V({65, 185}), V({13, 37})); } TEST(ValueElementSuite, uncertainInt8Test) { using V=ValueElement<int8_t, true>; V e0 = {0, 0}; V e1 = {0, 255}; V e2 = {127, 0}; V e3 = {127, 255}; V e4 = {-128, 0}; V e5 = {-128, 255}; V a={13, 37}; V b={-73, 1}; V c={3, 2}; testComp(a, b, false, true , false, true , false, true ); testComp(a, c, true , false, true , true , false, false); testComp(b, c, false, true , true , false, true , false); testOp(a, e0, a, a, V({ 0, 0}), V({ 0, 255})); testOp(a, e1, V({ 13, 255}), V({ 13, 255}), V({ 0, 255}), V({ 0, 255})); testOp(a, e2, V({ 127, 255}), V({-114, 37}), V({ 127, 255}), V({ 0, 1})); testOp(a, e3, V({ 127, 255}), V({-114, 255}), V({ 127, 255}), V({ 0, 255})); testOp(a, e4, V({-115, 37}), V({ 127, 255}), V({-128, 255}), V({ 0, 1})); testOp(a, e5, V({-115, 255}), V({ 127, 255}), V({-128, 255}), V({ 0, 255})); testOp(a, b, V({- 60, 38}), V({ 86, 38}), V({-128, 255}), V({ 0, 1})); testOp(a, c, V({ 16, 39}), V({ 10, 39}), V({ 65, 185}), V({13, 37})); } TEST(ValueElementSuite, castTest) { using I8 = ValueElement<int8_t, true>; using U8 = ValueElement<uint8_t, true>; using U16 = ValueElement<uint16_t, true>; using U32 = ValueElement<uint32_t, true>; using F = ValueElement<float, true>; using D = ValueElement<double, true>; I8 i8 = {-127, 0}; U8 u8 = {255, 0}; U32 u32 = {1234, 1}; F f = {1234.5678, 0}; EXPECT_EQ(U8(i8).value(), 0); EXPECT_EQ(U8(i8).uncertainty(), 127); EXPECT_EQ(I8(u8).value(), 127); EXPECT_EQ(I8(u8).uncertainty(), 128); EXPECT_EQ(U16(f).value(), 1234); EXPECT_EQ(U16(f).uncertainty(), 1); EXPECT_EQ(U32(f).value(), 1234); EXPECT_EQ(U32(f).uncertainty(), 1); EXPECT_EQ(D(u32).value(), 1234); EXPECT_EQ(D(u32).uncertainty(), 1); } }} <commit_msg>Unit-test: formatting and warning removal<commit_after> #include <gtest/gtest.h> #include <ValueElement.h> namespace tests { namespace valueElementSuite { template<typename T, bool U> bool exactlyEqual(const ValueElement<T, U>& a, const ValueElement<T, U>& b) { return a.value() == b.value() && a.uncertainty() == b.uncertainty(); } #define testComp(a, b, eq, ne, le, ge, lt, gt) { \ EXPECT_EQ(a==b, eq) << a << " == " << b << " = " << (a==b) << " != " << eq; \ EXPECT_EQ(a!=b, ne) << a << " != " << b << " = " << (a!=b) << " != " << ne; \ EXPECT_EQ(a<=b, le) << a << " <= " << b << " = " << (a<=b) << " != " << le; \ EXPECT_EQ(a>=b, ge) << a << " >= " << b << " = " << (a>=b) << " != " << ge; \ EXPECT_EQ(a<b, lt) << a << " < " << b << " = " << (a<b) << " != " << lt; \ EXPECT_EQ(a>b, gt) << a << " > " << b << " = " << (a>b) << " != " << gt; \ } #define testOp(a, b, add, sub, mul, div) { \ EXPECT_TRUE(exactlyEqual(a+b, add)) << a << " + " << b << " = " << (a+b) << " != " << add; \ EXPECT_TRUE(exactlyEqual(a-b, sub)) << a << " - " << b << " = " << (a-b) << " != " << sub; \ EXPECT_TRUE(exactlyEqual(a*b, mul)) << a << " * " << b << " = " << (a*b) << " != " << mul; \ EXPECT_TRUE(exactlyEqual(a/b, div)) << a << " / " << b << " = " << (a/b) << " != " << div; \ } TEST(ValueElementSuite, certainBoolTest) { using V=ValueElement<bool, false>; V e0 = {false}; V e1 = { true}; testComp(e0, e1, false, true , true, false, true , false); testOp(e0, e1, e1, e0, e0, e0); } TEST(ValueElementSuite, uncertainBoolTest) { using V=ValueElement<bool, false>; V e0 = {false, false}; V e1 = { true, false}; V e2 = {false, true}; V e3 = { true, true}; testComp(e0, e1, false, true , true , false, true , false); testOp(e0, e1, e1, e0, e0, e0); testComp(e0, e2, true , false, true , true , false, false); testOp(e0, e2, e2, e2, e0, e2); testComp(e1, e3, true , false, true , true , false, false); testOp(e1, e3, e3, e2, e3, e2); } TEST(ValueElementSuite, certainUInt8Test) { using V=ValueElement<uint8_t, false>; V e0 = { 0}; V e1 = {255}; V a = { 13}; V b = { 73}; V c = { 3}; testComp(a, b, false, true , true , false, true , false); testComp(a, c, false, true , false, true , false, true ); testComp(b, c, false, true , false, true , false, true ); testOp(a, e0, a, a, V({ 0}), V({ 0})); testOp(a, e1, V({255}), V({ 0}), V({255}), V({ 0})); testOp(a, b, V({ 86}), V({ 0}), V({255}), V({ 0})); testOp(a, c, V({ 16}), V({10}), V({ 39}), V({ 4})); } TEST(ValueElementSuite, certainInt8Test) { using V=ValueElement<int8_t, false>; V e0 = { 0}; V e1 = { 127}; V e2 = {-128}; V a = { 13}; V b = {- 73}; V c = { 3}; testComp(a, b, false, true , false, true , false, true ); testComp(a, c, false, true , false, true , false, true ); testComp(b, c, false, true , true , false, true , false); testOp(a, e0, a, a, V({ 0}), V({ 0})); testOp(a, e1, V({ 127}), V({-114}), V({ 127}), V({ 0})); testOp(a, e2, V({-115}), V({ 127}), V({-128}), V({ 0})); testOp(a, b, V({- 60}), V({ 86}), V({-128}), V({ 0})); testOp(a, c, V({ 16}), V({ 10}), V({ 39}), V({ 4})); } TEST(ValueElementSuite, uncertainUInt8Test) { using V=ValueElement<uint8_t, true>; V e0 = {0, 0}; V e1 = {0, 255}; V e2 = {255, 0}; V e3 = {255, 255}; V a={13, 37}; V b={73, 1}; V c={3, 2}; testComp(a, b, false, true , true , false, true , false); testComp(a, c, true , false, true , true , false, false); testComp(b, c, false, true , false, true , false, true ); testOp(a, e0, a, a, V({0, 0}), V({0, 255})); testOp(a, e1, V({13, 255}) , V({13, 255}), V({0, 255}) , V({0, 255})); testOp(a, e2, V({255, 255}), V({0, 255}) , V({255, 255}), V({0, 1}) ); testOp(a, e3, V({255, 255}), V({0, 255}) , V({255, 255}), V({0, 255})); testOp(a, b, V({86, 38}), V({0, 255}), V({255, 255}), V({0, 1})); testOp(a, c, V({16, 39}), V({10, 39}), V({65, 185}), V({13, 37})); } TEST(ValueElementSuite, uncertainInt8Test) { using V=ValueElement<int8_t, true>; V e0 = {0, 0}; V e1 = {0, 255}; V e2 = {127, 0}; V e3 = {127, 255}; V e4 = {-128, 0}; V e5 = {-128, 255}; V a={13, 37}; V b={-73, 1}; V c={3, 2}; testComp(a, b, false, true , false, true , false, true ); testComp(a, c, true , false, true , true , false, false); testComp(b, c, false, true , true , false, true , false); testOp(a, e0, a, a, V({ 0, 0}), V({ 0, 255})); testOp(a, e1, V({ 13, 255}), V({ 13, 255}), V({ 0, 255}), V({ 0, 255})); testOp(a, e2, V({ 127, 255}), V({-114, 37}), V({ 127, 255}), V({ 0, 1})); testOp(a, e3, V({ 127, 255}), V({-114, 255}), V({ 127, 255}), V({ 0, 255})); testOp(a, e4, V({-115, 37}), V({ 127, 255}), V({-128, 255}), V({ 0, 1})); testOp(a, e5, V({-115, 255}), V({ 127, 255}), V({-128, 255}), V({ 0, 255})); testOp(a, b, V({- 60, 38}), V({ 86, 38}), V({-128, 255}), V({ 0, 1})); testOp(a, c, V({ 16, 39}), V({ 10, 39}), V({ 65, 185}), V({13, 37})); } TEST(ValueElementSuite, castTest) { using I8 = ValueElement<int8_t, true>; using U8 = ValueElement<uint8_t, true>; using U16 = ValueElement<uint16_t, true>; using U32 = ValueElement<uint32_t, true>; using F = ValueElement<float, true>; using D = ValueElement<double, true>; I8 i8 = {-127 , 0U }; U8 u8 = {255U , 0U }; U32 u32 = {1234U , 1U }; F f = {1234.5678f, 0.0f}; EXPECT_EQ(U8(i8).value(), 0U); EXPECT_EQ(U8(i8).uncertainty(), 127U); EXPECT_EQ(I8(u8).value(), 127); EXPECT_EQ(I8(u8).uncertainty(), 128); EXPECT_EQ(U16(f).value(), 1234U); EXPECT_EQ(U16(f).uncertainty(), 1U); EXPECT_EQ(U32(f).value(), 1234U); EXPECT_EQ(U32(f).uncertainty(), 1U); EXPECT_EQ(D(u32).value(), 1234); EXPECT_EQ(D(u32).uncertainty(), 1); } }} <|endoftext|>
<commit_before>// Copyright 2016 Benjamin Glatzel // // 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. // Precompiled header file #include "stdafx.h" #include "stdafx_editor.h" #include "IntrinsicEdManagerWindowBase.h" // Ui #include "ui_IntrinsicEdManagerWindow.h" IntrinsicEdManagerWindowBase::IntrinsicEdManagerWindowBase(QWidget* parent) : QWidget(parent) { _ui.setupUi(this); QObject::connect(_ui.resourceView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(onShowResourceContextMenu(QPoint))); QObject::connect(_ui.createResource, SIGNAL(clicked()), this, SLOT(onCreateResource())); QObject::connect(_ui.saveManager, SIGNAL(clicked()), this, SLOT(onSaveManager())); QObject::connect(_ui.refreshManager, SIGNAL(clicked()), this, SLOT(onPopulateResourceTree())); QObject::connect( _ui.resourceView, SIGNAL(currentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*)), this, SLOT(onItemSelected(QTreeWidgetItem*, QTreeWidgetItem*))); QObject::connect(_ui.resourceView, SIGNAL(itemChanged(QTreeWidgetItem*, int)), this, SLOT(onItemChanged(QTreeWidgetItem*, int))); _ui.propertyView->setFeatures(0); _ui.splitter->setStretchFactor(0, 1); _ui.splitter->setStretchFactor(1, 2); _ui.resourceView->setSortingEnabled(true); _ui.resourceView->sortByColumn(0u, Qt::AscendingOrder); _resourceName = "Resource"; setWindowFlags(Qt::WindowStaysOnTopHint); } void IntrinsicEdManagerWindowBase::onPopulateResourceTree() { _ui.resourceView->clear(); _resourceToItemMapping.clear(); _itemToResourceMapping.clear(); rapidjson::Document doc; const uint32_t resourceCount = (uint32_t)_resourceManagerEntry.getActiveResourceCountFunction(); QTreeWidgetItem* volatileResourcesItem = new QTreeWidgetItem(); volatileResourcesItem->setText(0, "Volatile"); volatileResourcesItem->setIcon(0, QIcon(":/Icons/folder")); _ui.resourceView->addTopLevelItem(volatileResourcesItem); QTreeWidgetItem* storedResourcesItem = new QTreeWidgetItem(); storedResourcesItem->setText(0, "Stored"); storedResourcesItem->setIcon(0, QIcon(":/Icons/folder")); _ui.resourceView->addTopLevelItem(storedResourcesItem); for (uint32_t i = 0u; i < resourceCount; ++i) { Dod::Ref resource = _resourceManagerEntry.getActiveResourceAtIndexFunction(i); _INTR_ASSERT(resource.isValid()); rapidjson::Value properties = rapidjson::Value(rapidjson::kObjectType); _propertyCompilerEntry.compileFunction(resource, true, properties, doc); QTreeWidgetItem* item = new QTreeWidgetItem(); item->setText(0, properties["name"]["value"].GetString()); item->setIcon(0, _resourceIcon); item->setFlags(item->flags() | Qt::ItemIsEditable); _itemToResourceMapping[item] = resource; _resourceToItemMapping[resource] = item; _INTR_ASSERT(_resourceManagerEntry.getResourceFlagsFunction); if ((_resourceManagerEntry.getResourceFlagsFunction(resource) & Dod::Resources::ResourceFlags::kResourceVolatile) > 0u) { volatileResourcesItem->addChild(item); } else { storedResourcesItem->addChild(item); } } storedResourcesItem->setExpanded(true); emit resourceTreePopulated(); } void IntrinsicEdManagerWindowBase::onShowResourceContextMenu(QPoint p_Pos) { QMenu* contextMenu = new QMenu(this); initContextMenu(contextMenu); contextMenu->popup(_ui.resourceView->viewport()->mapToGlobal(p_Pos)); } void IntrinsicEdManagerWindowBase::onItemChanged(QTreeWidgetItem* item, int column) { if (item) { rapidjson::Document doc; Dod::Ref resource = _itemToResourceMapping[item]; rapidjson::Value properties = rapidjson::Value(rapidjson::kObjectType); _propertyCompilerEntry.compileFunction(resource, true, properties, doc); if (strcmp(properties["name"]["value"].GetString(), item->text(0).toStdString().c_str()) != 0) { _INTR_STRING newResourceName = makeResourceNameUnique(item->text(0).toStdString().c_str()); properties["name"]["value"].SetString(newResourceName.c_str(), doc.GetAllocator()); item->setText(0, newResourceName.c_str()); _propertyCompilerEntry.initFunction(resource, properties); _ui.propertyView->clearAndUpdatePropertyView(); } } } _INTR_STRING IntrinsicEdManagerWindowBase::makeResourceNameUnique(const char* p_Name) { rapidjson::Document doc; _INTR_STRING newResourceName = p_Name; uint32_t resourceIndex = 1; while (true) { bool found = false; for (uint32_t i = 0u; i < _resourceManagerEntry.getActiveResourceCountFunction(); ++i) { Dod::Ref resource = _resourceManagerEntry.getActiveResourceAtIndexFunction(i); rapidjson::Value properties = rapidjson::Value(rapidjson::kObjectType); _propertyCompilerEntry.compileFunction(resource, false, properties, doc); if (properties["name"]["value"].GetString() == newResourceName) { const _INTR_STRING nameWithoutSuffix = StringUtil::stripNumberSuffix(p_Name); newResourceName = nameWithoutSuffix + StringUtil::toString<uint32_t>(resourceIndex++).c_str(); found = true; } } if (!found) { break; } } return newResourceName; } void IntrinsicEdManagerWindowBase::onCreateResource() { _INTR_STRING newResourceName = makeResourceNameUnique(_resourceName.toStdString().c_str()); Dod::Ref newResourceRef = _resourceManagerEntry.createFunction(newResourceName.c_str()); if (_resourceManagerEntry.resetToDefaultFunction) { _resourceManagerEntry.resetToDefaultFunction(newResourceRef); } onPopulateResourceTree(); } void IntrinsicEdManagerWindowBase::onCloneResource() { Dod::Ref templateResourceRef = _itemToResourceMapping[_ui.resourceView->currentItem()]; if (templateResourceRef.isValid()) { Dod::Ref cloneedResourceRef = _resourceManagerEntry.createFunction(_N(Dummy)); if (_resourceManagerEntry.resetToDefaultFunction) { _resourceManagerEntry.resetToDefaultFunction(cloneedResourceRef); } rapidjson::Document doc; rapidjson::Value properties = rapidjson::Value(rapidjson::kObjectType); _propertyCompilerEntry.compileFunction(templateResourceRef, false, properties, doc); properties["name"]["value"].SetString( makeResourceNameUnique(properties["name"]["value"].GetString()).c_str(), doc.GetAllocator()); _propertyCompilerEntry.initFunction(cloneedResourceRef, properties); if (_resourceManagerEntry.createResourcesFunction) { Dod::RefArray resourcesToCreate = {cloneedResourceRef}; _resourceManagerEntry.createResourcesFunction(resourcesToCreate); } onPopulateResourceTree(); } } void IntrinsicEdManagerWindowBase::onDestroyResource() { Dod::Ref resource = _itemToResourceMapping[_ui.resourceView->currentItem()]; if (resource.isValid()) { _resourceManagerEntry.destroyFunction(resource); onPopulateResourceTree(); _ui.propertyView->clearPropertySet(); _ui.propertyView->clearAndUpdatePropertyView(); } } void IntrinsicEdManagerWindowBase::onSaveManager() { if (_resourceManagerEntry.saveToSingleFileFunction) { _resourceManagerEntry.saveToSingleFileFunction( _managerFilePath.toStdString().c_str()); } if (_resourceManagerEntry.saveToMultipleFilesFunction) { _resourceManagerEntry.saveToMultipleFilesFunction( _managerPath.toStdString().c_str(), _managerExtension.toStdString().c_str()); } new IntrinsicEdNotificationSimple(this, "Saved manager to file..."); } void IntrinsicEdManagerWindowBase::initContextMenu(QMenu* p_ContextMenu) { QAction* createResource = new QAction(QIcon(":/Icons/plus"), "Create " + _resourceName, this); p_ContextMenu->addAction(createResource); QObject::connect(createResource, SIGNAL(triggered()), this, SLOT(onCreateResource())); QTreeWidgetItem* currIt = _ui.resourceView->currentItem(); Dod::Ref resRef = _itemToResourceMapping[currIt]; if (resRef.isValid()) { QAction* destroyResource = new QAction(QIcon(":/Icons/minus"), "Delete " + _resourceName, this); p_ContextMenu->addAction(destroyResource); QObject::connect(destroyResource, SIGNAL(triggered()), this, SLOT(onDestroyResource())); p_ContextMenu->addSeparator(); QAction* cloneResource = new QAction(QIcon(":/Icons/plus"), "Clone " + _resourceName, this); p_ContextMenu->addAction(cloneResource); QObject::connect(cloneResource, SIGNAL(triggered()), this, SLOT(onCloneResource())); } } void IntrinsicEdManagerWindowBase::onItemSelected(QTreeWidgetItem* current, QTreeWidgetItem* previous) { if (current) { Dod::Ref resource = _itemToResourceMapping[current]; if (resource.isValid()) { Dod::PropertyCompilerEntry entry; entry.compileFunction = _propertyCompilerEntry.compileFunction; entry.initFunction = _propertyCompilerEntry.initFunction; entry.ref = resource; _ui.propertyView->clearPropertySet(); _ui.propertyView->addPropertySet(entry, _resourceManagerEntry); _ui.propertyView->clearAndUpdatePropertyView(); } } } <commit_msg>Removed "window stays on top hint" for manager windows<commit_after>// Copyright 2016 Benjamin Glatzel // // 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. // Precompiled header file #include "stdafx.h" #include "stdafx_editor.h" #include "IntrinsicEdManagerWindowBase.h" // Ui #include "ui_IntrinsicEdManagerWindow.h" IntrinsicEdManagerWindowBase::IntrinsicEdManagerWindowBase(QWidget* parent) : QWidget(parent) { _ui.setupUi(this); QObject::connect(_ui.resourceView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(onShowResourceContextMenu(QPoint))); QObject::connect(_ui.createResource, SIGNAL(clicked()), this, SLOT(onCreateResource())); QObject::connect(_ui.saveManager, SIGNAL(clicked()), this, SLOT(onSaveManager())); QObject::connect(_ui.refreshManager, SIGNAL(clicked()), this, SLOT(onPopulateResourceTree())); QObject::connect( _ui.resourceView, SIGNAL(currentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*)), this, SLOT(onItemSelected(QTreeWidgetItem*, QTreeWidgetItem*))); QObject::connect(_ui.resourceView, SIGNAL(itemChanged(QTreeWidgetItem*, int)), this, SLOT(onItemChanged(QTreeWidgetItem*, int))); _ui.propertyView->setFeatures(0); _ui.splitter->setStretchFactor(0, 1); _ui.splitter->setStretchFactor(1, 2); _ui.resourceView->setSortingEnabled(true); _ui.resourceView->sortByColumn(0u, Qt::AscendingOrder); _resourceName = "Resource"; } void IntrinsicEdManagerWindowBase::onPopulateResourceTree() { _ui.resourceView->clear(); _resourceToItemMapping.clear(); _itemToResourceMapping.clear(); rapidjson::Document doc; const uint32_t resourceCount = (uint32_t)_resourceManagerEntry.getActiveResourceCountFunction(); QTreeWidgetItem* volatileResourcesItem = new QTreeWidgetItem(); volatileResourcesItem->setText(0, "Volatile"); volatileResourcesItem->setIcon(0, QIcon(":/Icons/folder")); _ui.resourceView->addTopLevelItem(volatileResourcesItem); QTreeWidgetItem* storedResourcesItem = new QTreeWidgetItem(); storedResourcesItem->setText(0, "Stored"); storedResourcesItem->setIcon(0, QIcon(":/Icons/folder")); _ui.resourceView->addTopLevelItem(storedResourcesItem); for (uint32_t i = 0u; i < resourceCount; ++i) { Dod::Ref resource = _resourceManagerEntry.getActiveResourceAtIndexFunction(i); _INTR_ASSERT(resource.isValid()); rapidjson::Value properties = rapidjson::Value(rapidjson::kObjectType); _propertyCompilerEntry.compileFunction(resource, true, properties, doc); QTreeWidgetItem* item = new QTreeWidgetItem(); item->setText(0, properties["name"]["value"].GetString()); item->setIcon(0, _resourceIcon); item->setFlags(item->flags() | Qt::ItemIsEditable); _itemToResourceMapping[item] = resource; _resourceToItemMapping[resource] = item; _INTR_ASSERT(_resourceManagerEntry.getResourceFlagsFunction); if ((_resourceManagerEntry.getResourceFlagsFunction(resource) & Dod::Resources::ResourceFlags::kResourceVolatile) > 0u) { volatileResourcesItem->addChild(item); } else { storedResourcesItem->addChild(item); } } storedResourcesItem->setExpanded(true); emit resourceTreePopulated(); } void IntrinsicEdManagerWindowBase::onShowResourceContextMenu(QPoint p_Pos) { QMenu* contextMenu = new QMenu(this); initContextMenu(contextMenu); contextMenu->popup(_ui.resourceView->viewport()->mapToGlobal(p_Pos)); } void IntrinsicEdManagerWindowBase::onItemChanged(QTreeWidgetItem* item, int column) { if (item) { rapidjson::Document doc; Dod::Ref resource = _itemToResourceMapping[item]; rapidjson::Value properties = rapidjson::Value(rapidjson::kObjectType); _propertyCompilerEntry.compileFunction(resource, true, properties, doc); if (strcmp(properties["name"]["value"].GetString(), item->text(0).toStdString().c_str()) != 0) { _INTR_STRING newResourceName = makeResourceNameUnique(item->text(0).toStdString().c_str()); properties["name"]["value"].SetString(newResourceName.c_str(), doc.GetAllocator()); item->setText(0, newResourceName.c_str()); _propertyCompilerEntry.initFunction(resource, properties); _ui.propertyView->clearAndUpdatePropertyView(); } } } _INTR_STRING IntrinsicEdManagerWindowBase::makeResourceNameUnique(const char* p_Name) { rapidjson::Document doc; _INTR_STRING newResourceName = p_Name; uint32_t resourceIndex = 1; while (true) { bool found = false; for (uint32_t i = 0u; i < _resourceManagerEntry.getActiveResourceCountFunction(); ++i) { Dod::Ref resource = _resourceManagerEntry.getActiveResourceAtIndexFunction(i); rapidjson::Value properties = rapidjson::Value(rapidjson::kObjectType); _propertyCompilerEntry.compileFunction(resource, false, properties, doc); if (properties["name"]["value"].GetString() == newResourceName) { const _INTR_STRING nameWithoutSuffix = StringUtil::stripNumberSuffix(p_Name); newResourceName = nameWithoutSuffix + StringUtil::toString<uint32_t>(resourceIndex++).c_str(); found = true; } } if (!found) { break; } } return newResourceName; } void IntrinsicEdManagerWindowBase::onCreateResource() { _INTR_STRING newResourceName = makeResourceNameUnique(_resourceName.toStdString().c_str()); Dod::Ref newResourceRef = _resourceManagerEntry.createFunction(newResourceName.c_str()); if (_resourceManagerEntry.resetToDefaultFunction) { _resourceManagerEntry.resetToDefaultFunction(newResourceRef); } onPopulateResourceTree(); } void IntrinsicEdManagerWindowBase::onCloneResource() { Dod::Ref templateResourceRef = _itemToResourceMapping[_ui.resourceView->currentItem()]; if (templateResourceRef.isValid()) { Dod::Ref cloneedResourceRef = _resourceManagerEntry.createFunction(_N(Dummy)); if (_resourceManagerEntry.resetToDefaultFunction) { _resourceManagerEntry.resetToDefaultFunction(cloneedResourceRef); } rapidjson::Document doc; rapidjson::Value properties = rapidjson::Value(rapidjson::kObjectType); _propertyCompilerEntry.compileFunction(templateResourceRef, false, properties, doc); properties["name"]["value"].SetString( makeResourceNameUnique(properties["name"]["value"].GetString()).c_str(), doc.GetAllocator()); _propertyCompilerEntry.initFunction(cloneedResourceRef, properties); if (_resourceManagerEntry.createResourcesFunction) { Dod::RefArray resourcesToCreate = {cloneedResourceRef}; _resourceManagerEntry.createResourcesFunction(resourcesToCreate); } onPopulateResourceTree(); } } void IntrinsicEdManagerWindowBase::onDestroyResource() { Dod::Ref resource = _itemToResourceMapping[_ui.resourceView->currentItem()]; if (resource.isValid()) { _resourceManagerEntry.destroyFunction(resource); onPopulateResourceTree(); _ui.propertyView->clearPropertySet(); _ui.propertyView->clearAndUpdatePropertyView(); } } void IntrinsicEdManagerWindowBase::onSaveManager() { if (_resourceManagerEntry.saveToSingleFileFunction) { _resourceManagerEntry.saveToSingleFileFunction( _managerFilePath.toStdString().c_str()); } if (_resourceManagerEntry.saveToMultipleFilesFunction) { _resourceManagerEntry.saveToMultipleFilesFunction( _managerPath.toStdString().c_str(), _managerExtension.toStdString().c_str()); } new IntrinsicEdNotificationSimple(this, "Saved manager to file..."); } void IntrinsicEdManagerWindowBase::initContextMenu(QMenu* p_ContextMenu) { QAction* createResource = new QAction(QIcon(":/Icons/plus"), "Create " + _resourceName, this); p_ContextMenu->addAction(createResource); QObject::connect(createResource, SIGNAL(triggered()), this, SLOT(onCreateResource())); QTreeWidgetItem* currIt = _ui.resourceView->currentItem(); Dod::Ref resRef = _itemToResourceMapping[currIt]; if (resRef.isValid()) { QAction* destroyResource = new QAction(QIcon(":/Icons/minus"), "Delete " + _resourceName, this); p_ContextMenu->addAction(destroyResource); QObject::connect(destroyResource, SIGNAL(triggered()), this, SLOT(onDestroyResource())); p_ContextMenu->addSeparator(); QAction* cloneResource = new QAction(QIcon(":/Icons/plus"), "Clone " + _resourceName, this); p_ContextMenu->addAction(cloneResource); QObject::connect(cloneResource, SIGNAL(triggered()), this, SLOT(onCloneResource())); } } void IntrinsicEdManagerWindowBase::onItemSelected(QTreeWidgetItem* current, QTreeWidgetItem* previous) { if (current) { Dod::Ref resource = _itemToResourceMapping[current]; if (resource.isValid()) { Dod::PropertyCompilerEntry entry; entry.compileFunction = _propertyCompilerEntry.compileFunction; entry.initFunction = _propertyCompilerEntry.initFunction; entry.ref = resource; _ui.propertyView->clearPropertySet(); _ui.propertyView->addPropertySet(entry, _resourceManagerEntry); _ui.propertyView->clearAndUpdatePropertyView(); } } } <|endoftext|>
<commit_before>#include "Application.hpp" #include <cmath> #include <random> #include "ContactPoint.hpp" #include "TextureLoader.hpp" std::unique_ptr<std::string> message_profiling, message_collision; noob::actor_handle ah; std::string test_message; noob::vec3f random_vec3(float x, float y, float z) { return noob::vec3f(noob::random::get() * x, noob::random::get() * y, noob::random::get() * z); } noob::versorf random_versor() { return noob::normalize(noob::versorf(noob::random::get(), noob::random::get(), noob::random::get(), noob::random::get())); } bool noob::application::user_init() { message_profiling = std::make_unique<std::string>(""); message_collision = std::make_unique<std::string>(""); noob::logger::log(noob::importance::INFO, "[Application] Begin user init!"); noob::reflectance r; r.set_specular(noob::vec3f(0.1, 0.1, 0.1)); r.set_diffuse(noob::vec3f(0.1, 0.1, 0.1)); r.set_emissive(noob::vec3f(0.0, 0.0, 0.0)); r.set_shine(8.0); r.set_albedo(0.3); r.set_fresnel(0.2); noob::globals& g = noob::get_globals(); const noob::shape_handle scenery_shp = g.sphere_shape(10.0);// g.box_shape(50.0, 20.0, 50.0); const noob::scenery_handle sc_h = stage.scenery(scenery_shp, noob::vec3f(0.0, 0.0, 0.0), noob::versorf(0.0, 0.0, 0.0, 1.0));//versor_from_axis_rad(0.0, 0.0, 0.0, 1.0)); // 0 rad rotation, facing up const noob::reflectance_handle rh = g.reflectances.add(r); /* const float actor_dims = 2.0; // const noob::shape_handle shp = g.sphere_shape(actor_dims); const noob::shape_handle actor_shp = g.box_shape(actor_dims, actor_dims, actor_dims); const uint32_t actor_count = 200; // TODO: Fixup noob::actor_blueprints bp; bp.bounds = actor_shp; bp.reflect = rh; bp.model = g.model_from_shape(actor_shp, actor_count*8); noob::actor_blueprints_handle bph = stage.add_actor_blueprints(bp); const float stage_dim = static_cast<float>(actor_count); stage.reserve_actors(bph, actor_count * 8); for (uint32_t i = 0; i < actor_count; ++i) { ah = stage.actor(bph, 0, random_vec3(stage_dim, stage_dim, stage_dim), random_versor()); } for (uint32_t i = 0; i < actor_count; ++i) { ah = stage.actor(bph, 1, random_vec3(stage_dim, stage_dim, -stage_dim), random_versor()); } for (uint32_t i = 0; i < actor_count; ++i) { ah = stage.actor(bph, 2, random_vec3(stage_dim, -stage_dim, stage_dim), random_versor()); } for (uint32_t i = 0; i < actor_count; ++i) { ah = stage.actor(bph, 3, random_vec3(stage_dim, -stage_dim, -stage_dim), random_versor()); } for (uint32_t i = 0; i < actor_count; ++i) { ah = stage.actor(bph, 4, random_vec3(-stage_dim, stage_dim, stage_dim), random_versor()); } for (uint32_t i = 0; i < actor_count; ++i) { ah = stage.actor(bph, 5, random_vec3(-stage_dim, stage_dim, -stage_dim), random_versor()); } for (uint32_t i = 0; i < actor_count; ++i) { ah = stage.actor(bph, 6, random_vec3(-stage_dim, -stage_dim, stage_dim), random_versor()); } for (uint32_t i = 0; i < actor_count; ++i) { ah = stage.actor(bph, 7, random_vec3(-stage_dim, -stage_dim, -stage_dim), random_versor()); } */ logger::log(noob::importance::INFO, "[Application] Successfully done (C++) user init."); return true; } void noob::application::user_update(double dt) { noob::globals& g = noob::get_globals(); const noob::time nowtime = noob::clock::now(); const noob::duration time_since_update = nowtime - last_ui_update; const uint64_t profiling_interval = 3000; if (noob::millis(time_since_update) > profiling_interval - 1) { const noob::profiler_snap snap = g.profile_run; message_profiling = std::make_unique<std::string>(noob::concat("[User Update] Frame time: ", noob::to_string(divide_duration(snap.total_time, profiling_interval)), std::string(", draw time: "), noob::to_string(divide_duration(snap.stage_draw_duration, profiling_interval)), ", physics time: ", noob::to_string(divide_duration(snap.stage_physics_duration, profiling_interval)))); noob::logger::log(noob::importance::INFO, *message_profiling); g.profile_run.total_time = g.profile_run.stage_physics_duration = g.profile_run.stage_draw_duration = g.profile_run.sound_render_duration = noob::duration(0); g.profile_run.num_sound_callbacks = 0; last_ui_update = nowtime; } } <commit_msg>Another cleanup<commit_after>#include "Application.hpp" std::unique_ptr<std::string> message_profiling, message_collision; noob::actor_handle ah; std::string test_message; noob::vec3f random_vec3(float x, float y, float z) { return noob::vec3f(noob::random::get() * x, noob::random::get() * y, noob::random::get() * z); } noob::versorf random_versor() { return noob::normalize(noob::versorf(noob::random::get(), noob::random::get(), noob::random::get(), noob::random::get())); } bool noob::application::user_init() { message_profiling = std::make_unique<std::string>(""); message_collision = std::make_unique<std::string>(""); noob::logger::log(noob::importance::INFO, "[Application] Begin user init!"); noob::reflectance r; r.set_specular(noob::vec3f(0.1, 0.1, 0.1)); r.set_diffuse(noob::vec3f(0.1, 0.1, 0.1)); r.set_emissive(noob::vec3f(0.0, 0.0, 0.0)); r.set_shine(8.0); r.set_albedo(0.3); r.set_fresnel(0.2); noob::globals& g = noob::get_globals(); const noob::shape_handle scenery_shp = g.sphere_shape(10.0);// g.box_shape(50.0, 20.0, 50.0); const noob::scenery_handle sc_h = stage.scenery(scenery_shp, noob::vec3f(0.0, 0.0, 0.0), noob::versorf(0.0, 0.0, 0.0, 1.0));//versor_from_axis_rad(0.0, 0.0, 0.0, 1.0)); // 0 rad rotation, facing up const noob::reflectance_handle rh = g.reflectances.add(r); /* const float actor_dims = 2.0; // const noob::shape_handle shp = g.sphere_shape(actor_dims); const noob::shape_handle actor_shp = g.box_shape(actor_dims, actor_dims, actor_dims); const uint32_t actor_count = 200; // TODO: Fixup noob::actor_blueprints bp; bp.bounds = actor_shp; bp.reflect = rh; bp.model = g.model_from_shape(actor_shp, actor_count*8); noob::actor_blueprints_handle bph = stage.add_actor_blueprints(bp); const float stage_dim = static_cast<float>(actor_count); stage.reserve_actors(bph, actor_count * 8); for (uint32_t i = 0; i < actor_count; ++i) { ah = stage.actor(bph, 0, random_vec3(stage_dim, stage_dim, stage_dim), random_versor()); } for (uint32_t i = 0; i < actor_count; ++i) { ah = stage.actor(bph, 1, random_vec3(stage_dim, stage_dim, -stage_dim), random_versor()); } for (uint32_t i = 0; i < actor_count; ++i) { ah = stage.actor(bph, 2, random_vec3(stage_dim, -stage_dim, stage_dim), random_versor()); } for (uint32_t i = 0; i < actor_count; ++i) { ah = stage.actor(bph, 3, random_vec3(stage_dim, -stage_dim, -stage_dim), random_versor()); } for (uint32_t i = 0; i < actor_count; ++i) { ah = stage.actor(bph, 4, random_vec3(-stage_dim, stage_dim, stage_dim), random_versor()); } for (uint32_t i = 0; i < actor_count; ++i) { ah = stage.actor(bph, 5, random_vec3(-stage_dim, stage_dim, -stage_dim), random_versor()); } for (uint32_t i = 0; i < actor_count; ++i) { ah = stage.actor(bph, 6, random_vec3(-stage_dim, -stage_dim, stage_dim), random_versor()); } for (uint32_t i = 0; i < actor_count; ++i) { ah = stage.actor(bph, 7, random_vec3(-stage_dim, -stage_dim, -stage_dim), random_versor()); } */ logger::log(noob::importance::INFO, "[Application] Successfully done (C++) user init."); return true; } void noob::application::user_update(double dt) { noob::globals& g = noob::get_globals(); const noob::time nowtime = noob::clock::now(); const noob::duration time_since_update = nowtime - last_ui_update; const uint64_t profiling_interval = 3000; if (noob::millis(time_since_update) > profiling_interval - 1) { const noob::profiler_snap snap = g.profile_run; message_profiling = std::make_unique<std::string>(noob::concat("[User Update] Frame time: ", noob::to_string(divide_duration(snap.total_time, profiling_interval)), std::string(", draw time: "), noob::to_string(divide_duration(snap.stage_draw_duration, profiling_interval)), ", physics time: ", noob::to_string(divide_duration(snap.stage_physics_duration, profiling_interval)))); noob::logger::log(noob::importance::INFO, *message_profiling); g.profile_run.total_time = g.profile_run.stage_physics_duration = g.profile_run.stage_draw_duration = g.profile_run.sound_render_duration = noob::duration(0); g.profile_run.num_sound_callbacks = 0; last_ui_update = nowtime; } } <|endoftext|>
<commit_before>// @(#)root/io:$Id$ // Author: Philippe Canal, May 2011 /************************************************************************* * Copyright (C) 1995-2002, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TMemFile // // // // A TMemFile is like a normal TFile except that it reads and writes // // only from memory. // // // ////////////////////////////////////////////////////////////////////////// #include "TMemFile.h" #include "TError.h" #include "TSystem.h" #include "TROOT.h" #include "TArrayC.h" #include "TKey.h" #include "TClass.h" #include "TVirtualMutex.h" #include <errno.h> #include <stdio.h> #include <sys/stat.h> // The following snippet is used for developer-level debugging #define TMemFile_TRACE #ifndef TMemFile_TRACE #define TRACE(x) \ Debug("TMemFile", "%s", x); #else #define TRACE(x); #endif ClassImp(TMemFile) Long64_t TMemFile::fgDefaultBlockSize = 32*1024*1024; //______________________________________________________________________________ TMemFile::TMemFile(const char *path, Option_t *option, const char *ftitle, Int_t compress): TFile(path, "WEB", ftitle, compress), fBuffer(0) { // Usual Constructor. See the TFile constructor for details. fSize = -1; fSysOffset = 0; fOption = option; fOption.ToUpper(); Bool_t create = (fOption == "CREATE") ? kTRUE : kFALSE; Bool_t recreate = (fOption == "RECREATE") ? kTRUE : kFALSE; Bool_t update = (fOption == "UPDATE") ? kTRUE : kFALSE; Bool_t read = (fOption == "READ") ? kTRUE : kFALSE; if (!create && !recreate && !update && !read) { read = kTRUE; fOption = "READ"; } if (create || update || recreate) { Int_t mode = O_RDWR | O_CREAT; if (recreate) mode |= O_TRUNC; fD = SysOpen(path, O_RDWR | O_CREAT, 0644); if (fD == -1) { SysError("TMemFile", "file %s can not be opened", path); goto zombie; } fWritable = kTRUE; } else { fD = SysOpen(path, O_RDONLY, 0644); if (fD == -1) { SysError("TMemFile", "file %s can not be opened for reading", path); goto zombie; } fWritable = kFALSE; } Init(create || recreate); return; zombie: // Error in opening file; make this a zombie MakeZombie(); gDirectory = gROOT; } //______________________________________________________________________________ TMemFile::TMemFile(const char *path, char *buffer, Long64_t size, Option_t *option, const char *ftitle, Int_t compress): TFile(path, "WEB", ftitle, compress), fBuffer(0) { // Usual Constructor. See the TFile constructor for details. fSize = -1; fSysOffset = 0; fOption = option; fOption.ToUpper(); Bool_t create = (fOption == "CREATE") ? kTRUE : kFALSE; Bool_t recreate = (fOption == "RECREATE") ? kTRUE : kFALSE; Bool_t update = (fOption == "UPDATE") ? kTRUE : kFALSE; Bool_t read = (fOption == "READ") ? kTRUE : kFALSE; if (!create && !recreate && !update && !read) { read = kTRUE; fOption = "READ"; } if (create || update || recreate) { Int_t mode = O_RDWR | O_CREAT; if (recreate) mode |= O_TRUNC; fD = SysOpen(path, O_RDWR | O_CREAT, 0644); if (fD == -1) { SysError("TMemFile", "file %s can not be opened", path); goto zombie; } fWritable = kTRUE; } else { fD = SysOpen(path, O_RDONLY, 0644); if (fD == -1) { SysError("TMemFile", "file %s can not be opened for reading", path); goto zombie; } fWritable = kFALSE; } fBuffer = new UChar_t[fgDefaultBlockSize]; fSize = fgDefaultBlockSize; memcpy(fBuffer,buffer,size); Init(create || recreate); return; zombie: // Error in opening file; make this a zombie MakeZombie(); gDirectory = gROOT; } //______________________________________________________________________________ TMemFile::~TMemFile() { // Close and clean-up HDFS file. // Need to call close, now as it will need both our virtual table // and the content of fBuffer Close(); delete [] fBuffer; fBuffer = 0; TRACE("destroy") } //______________________________________________________________________________ Long64_t TMemFile::GetSize() const { // Return the current size of the memory file // We could also attempt to read it from the beginning of the buffer return fSize; } //______________________________________________________________________________ void TMemFile::ResetAfterMerge(TFileMergeInfo *info) { // Wipe all the data from the permanent buffer but keep, the in-memory object // alive. ResetObjects(this,info); fNbytesKeys = 0; fSeekKeys = 0; fMustFlush = kTRUE; fInitDone = kFALSE; fFree = 0; fWritten = 0; fSumBuffer = 0; fSum2Buffer = 0; fBytesRead = 0; fBytesReadExtra = 0; fBytesWrite = 0; delete fClassIndex; fClassIndex = 0; fSeekInfo = 0; fNbytesInfo = 0; fProcessIDs = 0; fNProcessIDs = 0; fOffset = 0; fCacheRead = 0; fCacheWrite = 0; fReadCalls = 0; if (fFree) { fFree->Delete(); delete fFree; fFree = 0; } fSysOffset = 0; { R__LOCKGUARD2(gROOTMutex); gROOT->GetListOfFiles()->Remove(this); } { TDirectory::TContext ctxt(gDirectory, this); Init(kTRUE); // And now we need re-initilize the directories ... TIter next(this->GetList()); TObject *idcur; while ((idcur = next())) { if (idcur->IsA() == TDirectoryFile::Class()) { ((TDirectoryFile*)idcur)->ResetAfterMerge(info); } } } } //______________________________________________________________________________ void TMemFile::ResetObjects(TDirectoryFile *directory, TFileMergeInfo *info) const { // Wipe all the data from the permanent buffer but keep, the in-memory object // alive. if (directory->GetListOfKeys()) { TIter next(directory->GetListOfKeys()); TKey *key; while( (key = (TKey*)next()) ) { if (0 == directory->GetList()->FindObject(key->GetName())) { Warning("ResetObjects","Key/Object %s is not attached to the directory %s and can not be ResetAfterMerge correctly", key->GetName(),directory->GetName()); } } directory->GetListOfKeys()->Delete("slow"); } TString listHargs; listHargs.Form("(TFileMergeInfo*)0x%lx",(ULong_t)info); TIter next(directory->GetList()); TObject *idcur; while ((idcur = next())) { TClass *objcl = idcur->IsA(); if (objcl == TDirectoryFile::Class()) { ResetObjects((TDirectoryFile*)idcur,info); } else if (objcl->GetResetAfterMerge()) { (objcl->GetResetAfterMerge())(idcur,info); } else if (idcur->IsA()->GetMethodWithPrototype("ResetAfterMerge", "TFileMergeInfo*") ) { Int_t error = 0; idcur->Execute("ResetAfterMerge", listHargs.Data(), &error); if (error) { Error("ResetObjects", "calling ResetAfterMerge() on '%s' failed.", idcur->GetName()); } } else { Error("ResetObjects","In %s, we can not reset %s (not ResetAfterMerge function)", directory->GetName(),idcur->GetName()); } } } //______________________________________________________________________________ Int_t TMemFile::SysRead(Int_t, void *buf, Int_t len) { // Read specified number of bytes from current offset into the buffer. // See documentation for TFile::SysRead(). TRACE("READ") if (fBuffer == 0) { errno = EBADF; gSystem->SetErrorStr("The memory file is not open."); return 0; } else { if (fSysOffset + len > fSize) { len = fSize - fSysOffset; } memcpy(buf,fBuffer+fSysOffset,len); fSysOffset += len; return len; } } //______________________________________________________________________________ Long64_t TMemFile::SysSeek(Int_t, Long64_t offset, Int_t whence) { // Seek to a specified position in the file. See TFile::SysSeek(). // Note that TMemFile does not support seeks when the file is open for write. TRACE("SEEK") if (whence == SEEK_SET) fSysOffset = offset; else if (whence == SEEK_CUR) fSysOffset += offset; else if (whence == SEEK_END) { if (offset > 0) { SysError("TMemFile", "Unable to seek past end of file"); return -1; } if (fSize == -1) { SysError("TMemFile", "Unable to seek to end of file"); return -1; } fSysOffset = fSize; } else { SysError("TMemFile", "Unknown whence!"); return -1; } return fSysOffset; } //______________________________________________________________________________ Int_t TMemFile::SysOpen(const char * /* pathname */, Int_t /* flags */, UInt_t /* mode */) { // Open a file in 'MemFile'. if (!fBuffer) { fBuffer = new UChar_t[fgDefaultBlockSize]; fSize = fgDefaultBlockSize; } if (fBuffer) { return 0; } else { return -1; } } //______________________________________________________________________________ Int_t TMemFile::SysClose(Int_t /* fd */) { // Close the mem file. return 0; } //______________________________________________________________________________ Int_t TMemFile::SysWrite(Int_t /* fd */, const void *buf, Int_t len) { // Write a buffer into the file; if (fSysOffset + len > fSize) { len = fSize - fSysOffset; } memcpy(fBuffer+fSysOffset,buf,len); fSysOffset += len; return len; } //______________________________________________________________________________ Int_t TMemFile::SysStat(Int_t, Long_t* /* id */, Long64_t* /* size */, Long_t* /* flags */, Long_t* /* modtime */) { // Perform a stat on the HDFS file; see TFile::SysStat(). MayNotUse("SysStat"); return 0; } //______________________________________________________________________________ Int_t TMemFile::SysSync(Int_t) { // Sync remaining data to disk; // Nothing to do here. return 0; } //______________________________________________________________________________ void TMemFile::ResetErrno() const { // ResetErrno; simply calls TSystem::ResetErrno(). TSystem::ResetErrno(); } <commit_msg>Fix memory leak<commit_after>// @(#)root/io:$Id$ // Author: Philippe Canal, May 2011 /************************************************************************* * Copyright (C) 1995-2002, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TMemFile // // // // A TMemFile is like a normal TFile except that it reads and writes // // only from memory. // // // ////////////////////////////////////////////////////////////////////////// #include "TMemFile.h" #include "TError.h" #include "TSystem.h" #include "TROOT.h" #include "TArrayC.h" #include "TKey.h" #include "TClass.h" #include "TVirtualMutex.h" #include <errno.h> #include <stdio.h> #include <sys/stat.h> // The following snippet is used for developer-level debugging #define TMemFile_TRACE #ifndef TMemFile_TRACE #define TRACE(x) \ Debug("TMemFile", "%s", x); #else #define TRACE(x); #endif ClassImp(TMemFile) Long64_t TMemFile::fgDefaultBlockSize = 32*1024*1024; //______________________________________________________________________________ TMemFile::TMemFile(const char *path, Option_t *option, const char *ftitle, Int_t compress): TFile(path, "WEB", ftitle, compress), fBuffer(0) { // Usual Constructor. See the TFile constructor for details. fSize = -1; fSysOffset = 0; fOption = option; fOption.ToUpper(); Bool_t create = (fOption == "CREATE") ? kTRUE : kFALSE; Bool_t recreate = (fOption == "RECREATE") ? kTRUE : kFALSE; Bool_t update = (fOption == "UPDATE") ? kTRUE : kFALSE; Bool_t read = (fOption == "READ") ? kTRUE : kFALSE; if (!create && !recreate && !update && !read) { read = kTRUE; fOption = "READ"; } if (create || update || recreate) { Int_t mode = O_RDWR | O_CREAT; if (recreate) mode |= O_TRUNC; fD = SysOpen(path, O_RDWR | O_CREAT, 0644); if (fD == -1) { SysError("TMemFile", "file %s can not be opened", path); goto zombie; } fWritable = kTRUE; } else { fD = SysOpen(path, O_RDONLY, 0644); if (fD == -1) { SysError("TMemFile", "file %s can not be opened for reading", path); goto zombie; } fWritable = kFALSE; } Init(create || recreate); return; zombie: // Error in opening file; make this a zombie MakeZombie(); gDirectory = gROOT; } //______________________________________________________________________________ TMemFile::TMemFile(const char *path, char *buffer, Long64_t size, Option_t *option, const char *ftitle, Int_t compress): TFile(path, "WEB", ftitle, compress), fBuffer(0) { // Usual Constructor. See the TFile constructor for details. fSize = -1; fSysOffset = 0; fOption = option; fOption.ToUpper(); Bool_t create = (fOption == "CREATE") ? kTRUE : kFALSE; Bool_t recreate = (fOption == "RECREATE") ? kTRUE : kFALSE; Bool_t update = (fOption == "UPDATE") ? kTRUE : kFALSE; Bool_t read = (fOption == "READ") ? kTRUE : kFALSE; if (!create && !recreate && !update && !read) { read = kTRUE; fOption = "READ"; } if (create || update || recreate) { Int_t mode = O_RDWR | O_CREAT; if (recreate) mode |= O_TRUNC; fD = SysOpen(path, O_RDWR | O_CREAT, 0644); if (fD == -1) { SysError("TMemFile", "file %s can not be opened", path); goto zombie; } fWritable = kTRUE; } else { fD = SysOpen(path, O_RDONLY, 0644); if (fD == -1) { SysError("TMemFile", "file %s can not be opened for reading", path); goto zombie; } fWritable = kFALSE; } memcpy(fBuffer,buffer,size); Init(create || recreate); return; zombie: // Error in opening file; make this a zombie MakeZombie(); gDirectory = gROOT; } //______________________________________________________________________________ TMemFile::~TMemFile() { // Close and clean-up HDFS file. // Need to call close, now as it will need both our virtual table // and the content of fBuffer Close(); delete [] fBuffer; fBuffer = 0; TRACE("destroy") } //______________________________________________________________________________ Long64_t TMemFile::GetSize() const { // Return the current size of the memory file // We could also attempt to read it from the beginning of the buffer return fSize; } //______________________________________________________________________________ void TMemFile::ResetAfterMerge(TFileMergeInfo *info) { // Wipe all the data from the permanent buffer but keep, the in-memory object // alive. ResetObjects(this,info); fNbytesKeys = 0; fSeekKeys = 0; fMustFlush = kTRUE; fInitDone = kFALSE; if (fFree) { fFree->Delete(); delete fFree; fFree = 0; } fWritten = 0; fSumBuffer = 0; fSum2Buffer = 0; fBytesRead = 0; fBytesReadExtra = 0; fBytesWrite = 0; delete fClassIndex; fClassIndex = 0; fSeekInfo = 0; fNbytesInfo = 0; delete fProcessIDs; fProcessIDs = 0; fNProcessIDs = 0; fOffset = 0; fCacheRead = 0; fCacheWrite = 0; fReadCalls = 0; if (fFree) { fFree->Delete(); delete fFree; fFree = 0; } fSysOffset = 0; { R__LOCKGUARD2(gROOTMutex); gROOT->GetListOfFiles()->Remove(this); } { TDirectory::TContext ctxt(gDirectory, this); Init(kTRUE); // And now we need re-initilize the directories ... TIter next(this->GetList()); TObject *idcur; while ((idcur = next())) { if (idcur->IsA() == TDirectoryFile::Class()) { ((TDirectoryFile*)idcur)->ResetAfterMerge(info); } } } } //______________________________________________________________________________ void TMemFile::ResetObjects(TDirectoryFile *directory, TFileMergeInfo *info) const { // Wipe all the data from the permanent buffer but keep, the in-memory object // alive. if (directory->GetListOfKeys()) { TIter next(directory->GetListOfKeys()); TKey *key; while( (key = (TKey*)next()) ) { if (0 == directory->GetList()->FindObject(key->GetName())) { Warning("ResetObjects","Key/Object %s is not attached to the directory %s and can not be ResetAfterMerge correctly", key->GetName(),directory->GetName()); } } directory->GetListOfKeys()->Delete("slow"); } TString listHargs; listHargs.Form("(TFileMergeInfo*)0x%lx",(ULong_t)info); TIter next(directory->GetList()); TObject *idcur; while ((idcur = next())) { TClass *objcl = idcur->IsA(); if (objcl == TDirectoryFile::Class()) { ResetObjects((TDirectoryFile*)idcur,info); } else if (objcl->GetResetAfterMerge()) { (objcl->GetResetAfterMerge())(idcur,info); } else if (idcur->IsA()->GetMethodWithPrototype("ResetAfterMerge", "TFileMergeInfo*") ) { Int_t error = 0; idcur->Execute("ResetAfterMerge", listHargs.Data(), &error); if (error) { Error("ResetObjects", "calling ResetAfterMerge() on '%s' failed.", idcur->GetName()); } } else { Error("ResetObjects","In %s, we can not reset %s (not ResetAfterMerge function)", directory->GetName(),idcur->GetName()); } } } //______________________________________________________________________________ Int_t TMemFile::SysRead(Int_t, void *buf, Int_t len) { // Read specified number of bytes from current offset into the buffer. // See documentation for TFile::SysRead(). TRACE("READ") if (fBuffer == 0) { errno = EBADF; gSystem->SetErrorStr("The memory file is not open."); return 0; } else { if (fSysOffset + len > fSize) { len = fSize - fSysOffset; } memcpy(buf,fBuffer+fSysOffset,len); fSysOffset += len; return len; } } //______________________________________________________________________________ Long64_t TMemFile::SysSeek(Int_t, Long64_t offset, Int_t whence) { // Seek to a specified position in the file. See TFile::SysSeek(). // Note that TMemFile does not support seeks when the file is open for write. TRACE("SEEK") if (whence == SEEK_SET) fSysOffset = offset; else if (whence == SEEK_CUR) fSysOffset += offset; else if (whence == SEEK_END) { if (offset > 0) { SysError("TMemFile", "Unable to seek past end of file"); return -1; } if (fSize == -1) { SysError("TMemFile", "Unable to seek to end of file"); return -1; } fSysOffset = fSize; } else { SysError("TMemFile", "Unknown whence!"); return -1; } return fSysOffset; } //______________________________________________________________________________ Int_t TMemFile::SysOpen(const char * /* pathname */, Int_t /* flags */, UInt_t /* mode */) { // Open a file in 'MemFile'. if (!fBuffer) { fBuffer = new UChar_t[fgDefaultBlockSize]; fSize = fgDefaultBlockSize; } if (fBuffer) { return 0; } else { return -1; } } //______________________________________________________________________________ Int_t TMemFile::SysClose(Int_t /* fd */) { // Close the mem file. return 0; } //______________________________________________________________________________ Int_t TMemFile::SysWrite(Int_t /* fd */, const void *buf, Int_t len) { // Write a buffer into the file; if (fSysOffset + len > fSize) { len = fSize - fSysOffset; } memcpy(fBuffer+fSysOffset,buf,len); fSysOffset += len; return len; } //______________________________________________________________________________ Int_t TMemFile::SysStat(Int_t, Long_t* /* id */, Long64_t* /* size */, Long_t* /* flags */, Long_t* /* modtime */) { // Perform a stat on the HDFS file; see TFile::SysStat(). MayNotUse("SysStat"); return 0; } //______________________________________________________________________________ Int_t TMemFile::SysSync(Int_t) { // Sync remaining data to disk; // Nothing to do here. return 0; } //______________________________________________________________________________ void TMemFile::ResetErrno() const { // ResetErrno; simply calls TSystem::ResetErrno(). TSystem::ResetErrno(); } <|endoftext|>
<commit_before>#include "robotont_driver/robotont_hardware.h" namespace robotont { RobotontHW::RobotontHW() { ROS_DEBUG("Robotont driver is starting..."); // Get parameters from ROS parameter server std::string robotont_port; int robotont_baudrate; std::string odom_frame; std::string odom_child_frame; nh_.param("serial/port", robotont_port, std::string("/dev/ttyACM0")); nh_.param("serial/baudrate", robotont_baudrate, 115200); nh_.param("odom/frame", odom_frame, std::string("odom")); nh_.param("odom/child_frame", odom_child_frame, std::string("base_link")); // configure serial serial_.setPort(robotont_port); serial_.setBaudrate(robotont_baudrate); serial::Timeout timeout = serial::Timeout::simpleTimeout(1000); serial_.setTimeout(timeout); // Configure odom frames odom_.setFrameId(odom_frame); odom_.setChildFrameId(odom_child_frame); // Try to open the serial port do { try { serial_.open(); } catch(serial::IOException e) { ROS_ERROR_STREAM("Unable to open port '" << robotont_port << "': " << e.what()); } catch(serial::SerialException e) { ROS_ERROR_STREAM("Unable to open port '" << robotont_port << "': " << e.what()); } if (serial_.isOpen()) ROS_DEBUG("Serial port is open"); else ROS_WARN("Failed to open Serial port, retrying after 1 sec..."); ros::Duration(1).sleep(); } while(!serial_.isOpen()); //Port is open, ready to communicate. // Create a timer to periodically read data from the serial buffer timer_ = nh_.createTimer(ros::Duration(0.01), &RobotontHW::read, this); // Subscribe to command velocity topic cmd_vel_sub_ = nh_.subscribe("cmd_vel", 1, &RobotontHW::cmd_vel_callback, this); } RobotontHW::~RobotontHW() { std::string packet = "\x1B"; write(packet); } void RobotontHW::read(const ros::TimerEvent& event) { if (!serial_.isOpen()) { //TODO: reconnect return; } size_t bytes_available = serial_.available(); // ROS_DEBUG("bytes available: %lu", bytes_available); if(!bytes_available) { return; } std::string buffer = ""; serial_.read(buffer, bytes_available); while(buffer.size()) { if(buffer[0] == '\r' || buffer[0] == '\n') { processPacket(); packet_ = ""; } else { packet_.push_back(buffer[0]); } buffer.erase(buffer.begin()); } } void RobotontHW::processPacket() { if(packet_.length() <= 2) { return; } std::stringstream ss(packet_); std::string arg[7]; std::getline(ss, arg[0], ':'); // parse motor speeds packet format [SPEED:speed_m0:speed_m1:speed_m2] if (arg[0] == "ODOM") { for (int i = 1; i < 7; i++) { std::getline(ss, arg[i], ':'); if (!arg[i].length()) { return; // invalid packet } } float pos_x = atof(arg[1].c_str()); float pos_y = atof(arg[2].c_str()); float ori_z = atof(arg[3].c_str()); float lin_vel_x = atof(arg[4].c_str()); float lin_vel_y = atof(arg[5].c_str()); float ang_vel_z = atof(arg[6].c_str()); odom_.update(pos_x, pos_y, ori_z, lin_vel_x, lin_vel_y, ang_vel_z); odom_.publish(); } } void RobotontHW::writeMotorSpeed(float speed_m1, float speed_m2, float speed_m3) { std::stringstream ss; ss << "MS:"; ss << speed_m1 << ":"; ss << speed_m2 << ":"; ss << speed_m3 << "\r\n"; write(ss.str()); } void RobotontHW::writeRobotSpeed(float lin_vel_x, float lin_vel_y, float ang_vel_z) { std::stringstream ss; ss << "RS:"; ss << lin_vel_x << ":"; ss << lin_vel_y << ":"; ss << ang_vel_z << "\r\n"; write(ss.str()); } void RobotontHW::write(const std::string& packet) { if (!serial_.isOpen()) { //TODO: reconnect return; } serial_.write(packet); } void RobotontHW::cmd_vel_callback(const geometry_msgs::Twist& cmd_vel_msg) { // ROS_INFO_STREAM("I heard: \r\n" << cmd_vel_msg); writeRobotSpeed(cmd_vel_msg.linear.x, cmd_vel_msg.linear.y, cmd_vel_msg.angular.z); } /* float vel_x = cmd_vel_msg.linear.x; float vel_y = -cmd_vel_msg.linear.y; float vel_t = cmd_vel_msg.angular.z; int motorCount = wheelAmount; float robotSpeed = 0; if (vel_x == 0) { robotSpeed = std::abs(vel_y); } else if (vel_y == 0) { robotSpeed = std::abs(vel_x); } else { robotSpeed = sqrt(vel_x * vel_x + vel_y * vel_y); } float robotDirectionAngle = atan2(vel_x, vel_y); // ROS_INFO_STREAM("robotDirectionAngle: " << (float)wheelAngles[0]); //debug purpouse float robotAngularVelocity = -vel_t * angular_vel_scaler; float wheelLinearVelocity[motorCount]; float wheelAngularSpeedMainboardUnits[motorCount]; for (int i = 0; i < motorCount; i++) { wheelLinearVelocity[i] = robotSpeed * cos(robotDirectionAngle - wheelAngles[i]) + wheelDistanceFromCenter * robotAngularVelocity; wheelAngularSpeedMainboardUnits[i] = wheelLinearVelocity[i] * wheelSpeedToMainboardUnits; } if (vel_x == 0 and vel_y == 0 and vel_t == 0){ m0 = m1 = m2 = 0; output_cmd = "\x1B\r\n"; //send ESC, which means stop } else { m0 = wheelAngularSpeedMainboardUnits[0] * wheel_ang_scaler; m1 = wheelAngularSpeedMainboardUnits[1] * wheel_ang_scaler; m2 = wheelAngularSpeedMainboardUnits[2] * wheel_ang_scaler; std::stringstream sstm; // sstm << 'a' << static_cast<int>(m0) << 'b' << static_cast<int>(m1) << 'c' << static_cast<int>(m2) << '\n'; // for previous firmware implementation sstm << static_cast<int>(m0) << ':' << static_cast<int>(m1) << ':' << static_cast<int>(m2) << '\r' <<'\n'; } */ } // namespace robotont <commit_msg>fixed odom tf<commit_after>#include "robotont_driver/robotont_hardware.h" namespace robotont { RobotontHW::RobotontHW() { ROS_DEBUG("Robotont driver is starting..."); // Get parameters from ROS parameter server std::string robotont_port; int robotont_baudrate; std::string odom_frame; std::string odom_child_frame; nh_.param("serial/port", robotont_port, std::string("/dev/ttyACM0")); nh_.param("serial/baudrate", robotont_baudrate, 115200); nh_.param("odom/frame", odom_frame, std::string("odom")); nh_.param("odom/child_frame", odom_child_frame, std::string("base_footprint")); // configure serial serial_.setPort(robotont_port); serial_.setBaudrate(robotont_baudrate); serial::Timeout timeout = serial::Timeout::simpleTimeout(1000); serial_.setTimeout(timeout); // Configure odom frames odom_.setFrameId(odom_frame); odom_.setChildFrameId(odom_child_frame); // Try to open the serial port do { try { serial_.open(); } catch(serial::IOException e) { ROS_ERROR_STREAM("Unable to open port '" << robotont_port << "': " << e.what()); } catch(serial::SerialException e) { ROS_ERROR_STREAM("Unable to open port '" << robotont_port << "': " << e.what()); } if (serial_.isOpen()) ROS_DEBUG("Serial port is open"); else ROS_WARN("Failed to open Serial port, retrying after 1 sec..."); ros::Duration(1).sleep(); } while(!serial_.isOpen()); //Port is open, ready to communicate. // Create a timer to periodically read data from the serial buffer timer_ = nh_.createTimer(ros::Duration(0.01), &RobotontHW::read, this); // Subscribe to command velocity topic cmd_vel_sub_ = nh_.subscribe("cmd_vel", 1, &RobotontHW::cmd_vel_callback, this); } RobotontHW::~RobotontHW() { std::string packet = "\x1B"; write(packet); } void RobotontHW::read(const ros::TimerEvent& event) { if (!serial_.isOpen()) { //TODO: reconnect return; } size_t bytes_available = serial_.available(); // ROS_DEBUG("bytes available: %lu", bytes_available); if(!bytes_available) { return; } std::string buffer = ""; serial_.read(buffer, bytes_available); while(buffer.size()) { if(buffer[0] == '\r' || buffer[0] == '\n') { processPacket(); packet_ = ""; } else { packet_.push_back(buffer[0]); } buffer.erase(buffer.begin()); } } void RobotontHW::processPacket() { if(packet_.length() <= 2) { return; } std::stringstream ss(packet_); std::string arg[7]; std::getline(ss, arg[0], ':'); // parse motor speeds packet format [SPEED:speed_m0:speed_m1:speed_m2] if (arg[0] == "ODOM") { for (int i = 1; i < 7; i++) { std::getline(ss, arg[i], ':'); if (!arg[i].length()) { return; // invalid packet } } float pos_x = atof(arg[1].c_str()); float pos_y = atof(arg[2].c_str()); float ori_z = atof(arg[3].c_str()); float lin_vel_x = atof(arg[4].c_str()); float lin_vel_y = atof(arg[5].c_str()); float ang_vel_z = atof(arg[6].c_str()); odom_.update(pos_x, pos_y, ori_z, lin_vel_x, lin_vel_y, ang_vel_z); odom_.publish(); } } void RobotontHW::writeMotorSpeed(float speed_m1, float speed_m2, float speed_m3) { std::stringstream ss; ss << "MS:"; ss << speed_m1 << ":"; ss << speed_m2 << ":"; ss << speed_m3 << "\r\n"; write(ss.str()); } void RobotontHW::writeRobotSpeed(float lin_vel_x, float lin_vel_y, float ang_vel_z) { std::stringstream ss; ss << "RS:"; ss << lin_vel_x << ":"; ss << lin_vel_y << ":"; ss << ang_vel_z << "\r\n"; write(ss.str()); } void RobotontHW::write(const std::string& packet) { if (!serial_.isOpen()) { //TODO: reconnect return; } serial_.write(packet); } void RobotontHW::cmd_vel_callback(const geometry_msgs::Twist& cmd_vel_msg) { // ROS_INFO_STREAM("I heard: \r\n" << cmd_vel_msg); writeRobotSpeed(cmd_vel_msg.linear.x, cmd_vel_msg.linear.y, cmd_vel_msg.angular.z); } /* float vel_x = cmd_vel_msg.linear.x; float vel_y = -cmd_vel_msg.linear.y; float vel_t = cmd_vel_msg.angular.z; int motorCount = wheelAmount; float robotSpeed = 0; if (vel_x == 0) { robotSpeed = std::abs(vel_y); } else if (vel_y == 0) { robotSpeed = std::abs(vel_x); } else { robotSpeed = sqrt(vel_x * vel_x + vel_y * vel_y); } float robotDirectionAngle = atan2(vel_x, vel_y); // ROS_INFO_STREAM("robotDirectionAngle: " << (float)wheelAngles[0]); //debug purpouse float robotAngularVelocity = -vel_t * angular_vel_scaler; float wheelLinearVelocity[motorCount]; float wheelAngularSpeedMainboardUnits[motorCount]; for (int i = 0; i < motorCount; i++) { wheelLinearVelocity[i] = robotSpeed * cos(robotDirectionAngle - wheelAngles[i]) + wheelDistanceFromCenter * robotAngularVelocity; wheelAngularSpeedMainboardUnits[i] = wheelLinearVelocity[i] * wheelSpeedToMainboardUnits; } if (vel_x == 0 and vel_y == 0 and vel_t == 0){ m0 = m1 = m2 = 0; output_cmd = "\x1B\r\n"; //send ESC, which means stop } else { m0 = wheelAngularSpeedMainboardUnits[0] * wheel_ang_scaler; m1 = wheelAngularSpeedMainboardUnits[1] * wheel_ang_scaler; m2 = wheelAngularSpeedMainboardUnits[2] * wheel_ang_scaler; std::stringstream sstm; // sstm << 'a' << static_cast<int>(m0) << 'b' << static_cast<int>(m1) << 'c' << static_cast<int>(m2) << '\n'; // for previous firmware implementation sstm << static_cast<int>(m0) << ':' << static_cast<int>(m1) << ':' << static_cast<int>(m2) << '\r' <<'\n'; } */ } // namespace robotont <|endoftext|>
<commit_before>// Copyright (c) 2011 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 "ui/gfx/surface/accelerated_surface_win.h" #include <windows.h> #include <list> #include "base/bind.h" #include "base/callback.h" #include "base/command_line.h" #include "base/debug/trace_event.h" #include "base/file_path.h" #include "base/lazy_instance.h" #include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/stringprintf.h" #include "base/threading/thread.h" #include "base/tracked_objects.h" #include "base/win/wrapped_window_proc.h" #include "ipc/ipc_message.h" #include "ui/base/win/hwnd_util.h" #include "ui/gfx/gl/gl_switches.h" namespace { typedef HRESULT (WINAPI *Direct3DCreate9ExFunc)(UINT sdk_version, IDirect3D9Ex **d3d); const wchar_t kD3D9ModuleName[] = L"d3d9.dll"; const char kCreate3D9DeviceExName[] = "Direct3DCreate9Ex"; class PresentThreadPool { public: static const int kNumPresentThreads = 4; PresentThreadPool(); int NextThread(); void PostTask(int thread, const tracked_objects::Location& from_here, const base::Closure& task); private: int next_thread_; scoped_ptr<base::Thread> present_threads_[kNumPresentThreads]; DISALLOW_COPY_AND_ASSIGN(PresentThreadPool); }; base::LazyInstance<PresentThreadPool> g_present_thread_pool = LAZY_INSTANCE_INITIALIZER; PresentThreadPool::PresentThreadPool() : next_thread_(0) { for (int i = 0; i < kNumPresentThreads; ++i) { present_threads_[i].reset(new base::Thread( base::StringPrintf("PresentThread #%d", i).c_str())); present_threads_[i]->Start(); } } int PresentThreadPool::NextThread() { next_thread_ = (next_thread_ + 1) % kNumPresentThreads; return next_thread_; } void PresentThreadPool::PostTask(int thread, const tracked_objects::Location& from_here, const base::Closure& task) { DCHECK_GE(thread, 0); DCHECK_LT(thread, kNumPresentThreads); present_threads_[thread]->message_loop()->PostTask(from_here, task); } UINT GetPresentationInterval() { if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableGpuVsync)) return D3DPRESENT_INTERVAL_IMMEDIATE; else return D3DPRESENT_INTERVAL_ONE; } } // namespace anonymous AcceleratedSurface::AcceleratedSurface(HWND parent) : thread_affinity_(g_present_thread_pool.Pointer()->NextThread()), window_(parent), num_pending_resizes_(0) { } AcceleratedSurface::~AcceleratedSurface() { // Destroy should have been called prior to the last reference going away. DCHECK(!device_); } void AcceleratedSurface::Initialize() { g_present_thread_pool.Pointer()->PostTask( thread_affinity_, FROM_HERE, base::Bind(&AcceleratedSurface::DoInitialize, this)); } void AcceleratedSurface::Destroy() { g_present_thread_pool.Pointer()->PostTask( thread_affinity_, FROM_HERE, base::Bind(&AcceleratedSurface::DoDestroy, this)); } void AcceleratedSurface::AsyncPresentAndAcknowledge( const gfx::Size& size, int64 surface_id, const base::Closure& completion_task) { const int kRound = 64; gfx::Size quantized_size( std::max(1, (size.width() + kRound - 1) / kRound * kRound), std::max(1, (size.height() + kRound - 1) / kRound * kRound)); if (pending_size_ != quantized_size) { pending_size_ = quantized_size; base::AtomicRefCountInc(&num_pending_resizes_); g_present_thread_pool.Pointer()->PostTask( thread_affinity_, FROM_HERE, base::Bind(&AcceleratedSurface::DoResize, this, quantized_size)); } // This might unnecessarily post to the thread with which the swap chain has // affinity. This will only result in potentially delaying the present. g_present_thread_pool.Pointer()->PostTask( num_pending_resizes_ ? thread_affinity_ : g_present_thread_pool.Pointer()->NextThread(), FROM_HERE, base::Bind(&AcceleratedSurface::DoPresentAndAcknowledge, this, size, surface_id, completion_task)); } bool AcceleratedSurface::Present() { TRACE_EVENT0("surface", "Present"); HRESULT hr; base::AutoLock locked(lock_); if (!device_) return true; RECT rect; if (!GetClientRect(window_, &rect)) return true; { TRACE_EVENT0("surface", "PresentEx"); hr = device_->PresentEx(&rect, &rect, NULL, NULL, D3DPRESENT_INTERVAL_IMMEDIATE); // If the device hung, force a resize to reset the device. if (hr == D3DERR_DEVICELOST || hr == D3DERR_DEVICEHUNG) { base::AtomicRefCountInc(&num_pending_resizes_); g_present_thread_pool.Pointer()->PostTask( thread_affinity_, FROM_HERE, base::Bind(&AcceleratedSurface::DoReset, this)); // A device hang destroys the contents of the back buffer so no point in // scheduling a present. } if (FAILED(hr)) return false; } hr = query_->Issue(D3DISSUE_END); if (FAILED(hr)) return true; { TRACE_EVENT0("surface", "spin"); do { hr = query_->GetData(NULL, 0, D3DGETDATA_FLUSH); if (hr == S_FALSE) Sleep(0); } while (hr == S_FALSE); } return true; } void AcceleratedSurface::DoInitialize() { TRACE_EVENT0("surface", "DoInitialize"); HRESULT hr; d3d_module_.Reset(base::LoadNativeLibrary(FilePath(kD3D9ModuleName), NULL)); Direct3DCreate9ExFunc create_func = reinterpret_cast<Direct3DCreate9ExFunc>( d3d_module_.GetFunctionPointer(kCreate3D9DeviceExName)); if (!create_func) return; base::win::ScopedComPtr<IDirect3D9Ex> d3d; hr = create_func(D3D_SDK_VERSION, d3d.Receive()); if (FAILED(hr)) return; D3DPRESENT_PARAMETERS parameters = { 0 }; parameters.BackBufferWidth = 1; parameters.BackBufferHeight = 1; parameters.BackBufferCount = 1; parameters.BackBufferFormat = D3DFMT_A8R8G8B8; parameters.hDeviceWindow = window_; parameters.Windowed = TRUE; parameters.Flags = 0; parameters.PresentationInterval = GetPresentationInterval(); parameters.SwapEffect = D3DSWAPEFFECT_COPY; hr = d3d->CreateDeviceEx( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, window_, D3DCREATE_FPU_PRESERVE | D3DCREATE_SOFTWARE_VERTEXPROCESSING | D3DCREATE_MULTITHREADED, &parameters, NULL, device_.Receive()); if (FAILED(hr)) return; hr = device_->CreateQuery(D3DQUERYTYPE_EVENT, query_.Receive()); if (FAILED(hr)) { device_ = NULL; return; } return; } void AcceleratedSurface::DoDestroy() { TRACE_EVENT0("surface", "DoDestroy"); base::AutoLock locked(lock_); query_ = NULL; device_ = NULL; } void AcceleratedSurface::DoResize(const gfx::Size& size) { TRACE_EVENT0("surface", "DoResize"); size_ = size; DoReset(); } void AcceleratedSurface::DoReset() { TRACE_EVENT0("surface", "DoReset"); HRESULT hr; base::AtomicRefCountDec(&num_pending_resizes_); base::AutoLock locked(lock_); if (!device_) return; D3DPRESENT_PARAMETERS parameters = { 0 }; parameters.BackBufferWidth = size_.width(); parameters.BackBufferHeight = size_.height(); parameters.BackBufferCount = 1; parameters.BackBufferFormat = D3DFMT_A8R8G8B8; parameters.hDeviceWindow = window_; parameters.Windowed = TRUE; parameters.Flags = 0; parameters.PresentationInterval = GetPresentationInterval(); parameters.SwapEffect = D3DSWAPEFFECT_COPY; hr = device_->ResetEx(&parameters, NULL); if (FAILED(hr)) return; device_->Clear(0, NULL, D3DCLEAR_TARGET, 0xFFFFFFFF, 0, 0); } void AcceleratedSurface::DoPresentAndAcknowledge( const gfx::Size& size, int64 surface_id, const base::Closure& completion_task) { TRACE_EVENT1("surface", "DoPresentAndAcknowledge", "surface_id", surface_id); HRESULT hr; base::AutoLock locked(lock_); // Ensure the task is always run and while the lock is taken. base::ScopedClosureRunner scoped_completion_runner(completion_task); if (!device_) return; if (!window_) return; HANDLE handle = reinterpret_cast<HANDLE>(surface_id); if (!handle) return; base::win::ScopedComPtr<IDirect3DTexture9> source_texture; { TRACE_EVENT0("surface", "CreateTexture"); hr = device_->CreateTexture(size.width(), size.height(), 1, D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, source_texture.Receive(), &handle); if (FAILED(hr)) return; } base::win::ScopedComPtr<IDirect3DSurface9> source_surface; hr = source_texture->GetSurfaceLevel(0, source_surface.Receive()); if (FAILED(hr)) return; base::win::ScopedComPtr<IDirect3DSurface9> dest_surface; hr = device_->GetRenderTarget(0, dest_surface.Receive()); if (FAILED(hr)) return; RECT rect = { 0, 0, size.width(), size.height() }; { TRACE_EVENT0("surface", "StretchRect"); hr = device_->StretchRect(source_surface, &rect, dest_surface, &rect, D3DTEXF_NONE); if (FAILED(hr)) return; } hr = query_->Issue(D3DISSUE_END); if (FAILED(hr)) return; // Flush so the StretchRect can be processed by the GPU while the window is // being resized. query_->GetData(NULL, 0, D3DGETDATA_FLUSH); ::SetWindowPos( window_, NULL, 0, 0, size.width(), size.height(), SWP_NOACTIVATE | SWP_NOCOPYBITS | SWP_NOMOVE |SWP_NOOWNERZORDER | SWP_NOREDRAW | SWP_NOSENDCHANGING | SWP_NOSENDCHANGING | SWP_ASYNCWINDOWPOS); // Wait for the StretchRect to complete before notifying the GPU process // that it is safe to write to its backing store again. { TRACE_EVENT0("surface", "spin"); do { hr = query_->GetData(NULL, 0, D3DGETDATA_FLUSH); if (hr == S_FALSE) Sleep(0); } while (hr == S_FALSE); } scoped_completion_runner.Release(); if (!completion_task.is_null()) completion_task.Run(); { TRACE_EVENT0("surface", "Present"); hr = device_->Present(&rect, &rect, NULL, NULL); // If the device hung, force a resize to reset the device. if (hr == D3DERR_DEVICELOST || hr == D3DERR_DEVICEHUNG) { base::AtomicRefCountInc(&num_pending_resizes_); g_present_thread_pool.Pointer()->PostTask( thread_affinity_, FROM_HERE, base::Bind(&AcceleratedSurface::DoReset, this)); // A device hang destroys the contents of the back buffer so no point in // scheduling a present. } } } <commit_msg>Prevent Windows AcceleratedSurface from positioning the compositing window above plugin windows.<commit_after>// Copyright (c) 2011 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 "ui/gfx/surface/accelerated_surface_win.h" #include <windows.h> #include <list> #include "base/bind.h" #include "base/callback.h" #include "base/command_line.h" #include "base/debug/trace_event.h" #include "base/file_path.h" #include "base/lazy_instance.h" #include "base/memory/scoped_ptr.h" #include "base/memory/weak_ptr.h" #include "base/stringprintf.h" #include "base/threading/thread.h" #include "base/tracked_objects.h" #include "base/win/wrapped_window_proc.h" #include "ipc/ipc_message.h" #include "ui/base/win/hwnd_util.h" #include "ui/gfx/gl/gl_switches.h" namespace { typedef HRESULT (WINAPI *Direct3DCreate9ExFunc)(UINT sdk_version, IDirect3D9Ex **d3d); const wchar_t kD3D9ModuleName[] = L"d3d9.dll"; const char kCreate3D9DeviceExName[] = "Direct3DCreate9Ex"; class PresentThreadPool { public: static const int kNumPresentThreads = 4; PresentThreadPool(); int NextThread(); void PostTask(int thread, const tracked_objects::Location& from_here, const base::Closure& task); private: int next_thread_; scoped_ptr<base::Thread> present_threads_[kNumPresentThreads]; DISALLOW_COPY_AND_ASSIGN(PresentThreadPool); }; base::LazyInstance<PresentThreadPool> g_present_thread_pool = LAZY_INSTANCE_INITIALIZER; PresentThreadPool::PresentThreadPool() : next_thread_(0) { for (int i = 0; i < kNumPresentThreads; ++i) { present_threads_[i].reset(new base::Thread( base::StringPrintf("PresentThread #%d", i).c_str())); present_threads_[i]->Start(); } } int PresentThreadPool::NextThread() { next_thread_ = (next_thread_ + 1) % kNumPresentThreads; return next_thread_; } void PresentThreadPool::PostTask(int thread, const tracked_objects::Location& from_here, const base::Closure& task) { DCHECK_GE(thread, 0); DCHECK_LT(thread, kNumPresentThreads); present_threads_[thread]->message_loop()->PostTask(from_here, task); } UINT GetPresentationInterval() { if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableGpuVsync)) return D3DPRESENT_INTERVAL_IMMEDIATE; else return D3DPRESENT_INTERVAL_ONE; } } // namespace anonymous AcceleratedSurface::AcceleratedSurface(HWND parent) : thread_affinity_(g_present_thread_pool.Pointer()->NextThread()), window_(parent), num_pending_resizes_(0) { } AcceleratedSurface::~AcceleratedSurface() { // Destroy should have been called prior to the last reference going away. DCHECK(!device_); } void AcceleratedSurface::Initialize() { g_present_thread_pool.Pointer()->PostTask( thread_affinity_, FROM_HERE, base::Bind(&AcceleratedSurface::DoInitialize, this)); } void AcceleratedSurface::Destroy() { g_present_thread_pool.Pointer()->PostTask( thread_affinity_, FROM_HERE, base::Bind(&AcceleratedSurface::DoDestroy, this)); } void AcceleratedSurface::AsyncPresentAndAcknowledge( const gfx::Size& size, int64 surface_id, const base::Closure& completion_task) { const int kRound = 64; gfx::Size quantized_size( std::max(1, (size.width() + kRound - 1) / kRound * kRound), std::max(1, (size.height() + kRound - 1) / kRound * kRound)); if (pending_size_ != quantized_size) { pending_size_ = quantized_size; base::AtomicRefCountInc(&num_pending_resizes_); g_present_thread_pool.Pointer()->PostTask( thread_affinity_, FROM_HERE, base::Bind(&AcceleratedSurface::DoResize, this, quantized_size)); } // This might unnecessarily post to the thread with which the swap chain has // affinity. This will only result in potentially delaying the present. g_present_thread_pool.Pointer()->PostTask( num_pending_resizes_ ? thread_affinity_ : g_present_thread_pool.Pointer()->NextThread(), FROM_HERE, base::Bind(&AcceleratedSurface::DoPresentAndAcknowledge, this, size, surface_id, completion_task)); } bool AcceleratedSurface::Present() { TRACE_EVENT0("surface", "Present"); HRESULT hr; base::AutoLock locked(lock_); if (!device_) return true; RECT rect; if (!GetClientRect(window_, &rect)) return true; { TRACE_EVENT0("surface", "PresentEx"); hr = device_->PresentEx(&rect, &rect, NULL, NULL, D3DPRESENT_INTERVAL_IMMEDIATE); // If the device hung, force a resize to reset the device. if (hr == D3DERR_DEVICELOST || hr == D3DERR_DEVICEHUNG) { base::AtomicRefCountInc(&num_pending_resizes_); g_present_thread_pool.Pointer()->PostTask( thread_affinity_, FROM_HERE, base::Bind(&AcceleratedSurface::DoReset, this)); // A device hang destroys the contents of the back buffer so no point in // scheduling a present. } if (FAILED(hr)) return false; } hr = query_->Issue(D3DISSUE_END); if (FAILED(hr)) return true; { TRACE_EVENT0("surface", "spin"); do { hr = query_->GetData(NULL, 0, D3DGETDATA_FLUSH); if (hr == S_FALSE) Sleep(0); } while (hr == S_FALSE); } return true; } void AcceleratedSurface::DoInitialize() { TRACE_EVENT0("surface", "DoInitialize"); HRESULT hr; d3d_module_.Reset(base::LoadNativeLibrary(FilePath(kD3D9ModuleName), NULL)); Direct3DCreate9ExFunc create_func = reinterpret_cast<Direct3DCreate9ExFunc>( d3d_module_.GetFunctionPointer(kCreate3D9DeviceExName)); if (!create_func) return; base::win::ScopedComPtr<IDirect3D9Ex> d3d; hr = create_func(D3D_SDK_VERSION, d3d.Receive()); if (FAILED(hr)) return; D3DPRESENT_PARAMETERS parameters = { 0 }; parameters.BackBufferWidth = 1; parameters.BackBufferHeight = 1; parameters.BackBufferCount = 1; parameters.BackBufferFormat = D3DFMT_A8R8G8B8; parameters.hDeviceWindow = window_; parameters.Windowed = TRUE; parameters.Flags = 0; parameters.PresentationInterval = GetPresentationInterval(); parameters.SwapEffect = D3DSWAPEFFECT_COPY; hr = d3d->CreateDeviceEx( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, window_, D3DCREATE_FPU_PRESERVE | D3DCREATE_SOFTWARE_VERTEXPROCESSING | D3DCREATE_MULTITHREADED, &parameters, NULL, device_.Receive()); if (FAILED(hr)) return; hr = device_->CreateQuery(D3DQUERYTYPE_EVENT, query_.Receive()); if (FAILED(hr)) { device_ = NULL; return; } return; } void AcceleratedSurface::DoDestroy() { TRACE_EVENT0("surface", "DoDestroy"); base::AutoLock locked(lock_); query_ = NULL; device_ = NULL; } void AcceleratedSurface::DoResize(const gfx::Size& size) { TRACE_EVENT0("surface", "DoResize"); size_ = size; DoReset(); } void AcceleratedSurface::DoReset() { TRACE_EVENT0("surface", "DoReset"); HRESULT hr; base::AtomicRefCountDec(&num_pending_resizes_); base::AutoLock locked(lock_); if (!device_) return; D3DPRESENT_PARAMETERS parameters = { 0 }; parameters.BackBufferWidth = size_.width(); parameters.BackBufferHeight = size_.height(); parameters.BackBufferCount = 1; parameters.BackBufferFormat = D3DFMT_A8R8G8B8; parameters.hDeviceWindow = window_; parameters.Windowed = TRUE; parameters.Flags = 0; parameters.PresentationInterval = GetPresentationInterval(); parameters.SwapEffect = D3DSWAPEFFECT_COPY; hr = device_->ResetEx(&parameters, NULL); if (FAILED(hr)) return; device_->Clear(0, NULL, D3DCLEAR_TARGET, 0xFFFFFFFF, 0, 0); } void AcceleratedSurface::DoPresentAndAcknowledge( const gfx::Size& size, int64 surface_id, const base::Closure& completion_task) { TRACE_EVENT1("surface", "DoPresentAndAcknowledge", "surface_id", surface_id); HRESULT hr; base::AutoLock locked(lock_); // Ensure the task is always run and while the lock is taken. base::ScopedClosureRunner scoped_completion_runner(completion_task); if (!device_) return; if (!window_) return; HANDLE handle = reinterpret_cast<HANDLE>(surface_id); if (!handle) return; base::win::ScopedComPtr<IDirect3DTexture9> source_texture; { TRACE_EVENT0("surface", "CreateTexture"); hr = device_->CreateTexture(size.width(), size.height(), 1, D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, source_texture.Receive(), &handle); if (FAILED(hr)) return; } base::win::ScopedComPtr<IDirect3DSurface9> source_surface; hr = source_texture->GetSurfaceLevel(0, source_surface.Receive()); if (FAILED(hr)) return; base::win::ScopedComPtr<IDirect3DSurface9> dest_surface; hr = device_->GetRenderTarget(0, dest_surface.Receive()); if (FAILED(hr)) return; RECT rect = { 0, 0, size.width(), size.height() }; { TRACE_EVENT0("surface", "StretchRect"); hr = device_->StretchRect(source_surface, &rect, dest_surface, &rect, D3DTEXF_NONE); if (FAILED(hr)) return; } hr = query_->Issue(D3DISSUE_END); if (FAILED(hr)) return; // Flush so the StretchRect can be processed by the GPU while the window is // being resized. query_->GetData(NULL, 0, D3DGETDATA_FLUSH); ::SetWindowPos( window_, HWND_BOTTOM, 0, 0, size.width(), size.height(), SWP_NOACTIVATE | SWP_NOCOPYBITS | SWP_NOMOVE |SWP_NOOWNERZORDER | SWP_NOREDRAW | SWP_NOSENDCHANGING | SWP_NOSENDCHANGING | SWP_ASYNCWINDOWPOS); // Wait for the StretchRect to complete before notifying the GPU process // that it is safe to write to its backing store again. { TRACE_EVENT0("surface", "spin"); do { hr = query_->GetData(NULL, 0, D3DGETDATA_FLUSH); if (hr == S_FALSE) Sleep(0); } while (hr == S_FALSE); } scoped_completion_runner.Release(); if (!completion_task.is_null()) completion_task.Run(); { TRACE_EVENT0("surface", "Present"); hr = device_->Present(&rect, &rect, NULL, NULL); // If the device hung, force a resize to reset the device. if (hr == D3DERR_DEVICELOST || hr == D3DERR_DEVICEHUNG) { base::AtomicRefCountInc(&num_pending_resizes_); g_present_thread_pool.Pointer()->PostTask( thread_affinity_, FROM_HERE, base::Bind(&AcceleratedSurface::DoReset, this)); // A device hang destroys the contents of the back buffer so no point in // scheduling a present. } } } <|endoftext|>
<commit_before>/* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <iostream> #include <string> #include <gtest/gtest.h> #include "folly/Benchmark.h" #include "mcrouter/lib/fbi/cpp/Trie.h" using facebook::memcache::Trie; static int const kNumGetKeys = 7; static std::string keysToGet[kNumGetKeys] = { "abacaba", "abacabaddd", "b1", "", "abacabadabacab", "qwerty:qwerty:qwerty:123456", "abd", }; static Trie<long> randTrie; static long x = 0; static void prepareRand() { static std::string keys[] = { "abacaba", "abacabadabacaba", "b123", "qwerty:qwerty:qwerty:123456", }; auto numKeys = sizeof(keys) / sizeof(keys[0]); for (long i = 0; i < numKeys; ++i) { randTrie.emplace(keys[i], i + 1); } } BENCHMARK(Trie_get) { for (int i = 0; i < kNumGetKeys; ++i) { auto r = randTrie.find(keysToGet[i]); x += r == randTrie.end() ? 0 : r->second; } } BENCHMARK(Trie_get_prefix) { for (int i = 0; i < kNumGetKeys; ++i) { auto r = randTrie.findPrefix(keysToGet[i]); x += r == randTrie.end() ? 0 : r->second; } } int main(int argc, char **argv){ prepareRand(); google::ParseCommandLineFlags(&argc, &argv, true); folly::runBenchmarksOnFlag(); std::cout << "check (should be num of iters*12): " << x << std::endl; return 0; } <commit_msg>More benchmarks for Trie<commit_after>/* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <string> #include <vector> #include <glog/logging.h> #include <gtest/gtest.h> #include <folly/Benchmark.h> #include <folly/experimental/StringKeyedUnorderedMap.h> #include "mcrouter/lib/fbi/cpp/Trie.h" using facebook::memcache::Trie; namespace { template <class Value> class KeyPrefixMap : public folly::StringKeyedUnorderedMap<Value> { using Base = folly::StringKeyedUnorderedMap<Value>; public: using iterator = typename Base::iterator; std::pair<iterator, bool> emplace(folly::StringPiece key, Value v) { auto it = std::lower_bound(prefixLength_.begin(), prefixLength_.end(), key.size()); if (it == prefixLength_.end() || *it != key.size()) { prefixLength_.insert(it, key.size()); } return Base::emplace(key, std::move(v)); } iterator findPrefix(folly::StringPiece key) { auto result = end(); for (auto len : prefixLength_) { if (len > key.size()) { return result; } auto it = find(key.subpiece(0, len)); if (it != end()) { result = it; } } return result; } using Base::find; using Base::begin; using Base::end; private: std::vector<size_t> prefixLength_; }; std::vector<std::string> keysToGet[3]; Trie<int> randTrie[3]; KeyPrefixMap<int> randMap[3]; int x = 0; void prepareRand() { std::vector<std::string> keys[3] = { { "abacaba", "abacabadabacaba", "b123", "qwerty:qwerty:qwerty:123456", }, { "AMC", "ayk", "brq", "bxj", "fgn", "fkr", "fm0", "gig", "gtg", "gtm", "iag", "kkb", "kki", "kkx", "kkz", "kqf", "kqg", "mbf", "mft", "mgg", "mgj", "mgr", "mhk", "mun", "rmg", "rak", "rdk", "rxg", "tm2", "tzb", "tzh", "zbg", "zgq", "zug", }, { "hsdfbfda.ghu", "hsdfbfda.abc", "rbfdhkjs.abc", "rbjfyvbl.abc", "rbl.fsgjhdfb", "rbl.fdnolfbv", "rblkmvnf.abc", "rblplmbf.ghu", "rblplmbf.abc", "rubajvnr.ghu", "rubajvnr.abc", } }; std::string missKeys[] = { "zahskjsdf", "aba", "", "z", "asdjl:dafnsjsdf" }; for (int i = 0 ; i < 3; ++i) { for (int j = 0; j < keys[i].size(); ++j) { randTrie[i].emplace(keys[i][j], i + j + 1); randMap[i].emplace(keys[i][j], i + j + 1); } for (int j = 0; j < keys[i].size(); ++j) { keysToGet[i].push_back(keys[i][j] + ":hit"); } for (int j = 0; j < 5; ++j) { keysToGet[i].push_back(missKeys[j]); } LOG(INFO) << "#" << i << " uses " << keysToGet[i].size() << " keys"; } } template <class Container> void runGet(Container& c, int id) { auto& keys = keysToGet[id]; for (int i = 0; i < keys.size(); ++i) { auto r = c.find(keys[i]); x += r == c.end() ? 0 : r->second; } } template <class Container> void runGetPrefix(Container& c, int id) { auto& keys = keysToGet[id]; for (int i = 0; i < keys.size(); ++i) { auto r = c.findPrefix(keys[i]); x += r == c.end() ? 0 : r->second; } } } // anonymous namespace BENCHMARK(Trie_get0) { runGet(randTrie[0], 0); } BENCHMARK_RELATIVE(Map_get0) { runGet(randMap[0], 0); } BENCHMARK(Trie_get1) { runGet(randTrie[1], 1); } BENCHMARK_RELATIVE(Map_get1) { runGet(randMap[1], 1); } BENCHMARK(Trie_get2) { runGet(randTrie[2], 2); } BENCHMARK_RELATIVE(Map_get2) { runGet(randMap[2], 2); } BENCHMARK(Trie_get_prefix0) { runGetPrefix(randTrie[0], 0); } BENCHMARK_RELATIVE(Map_get_prefix0) { runGet(randMap[0], 0); } BENCHMARK(Trie_get_prefix1) { runGetPrefix(randTrie[1], 1); } BENCHMARK_RELATIVE(Map_get_prefix1) { runGet(randMap[1], 1); } BENCHMARK(Trie_get_prefix2) { runGetPrefix(randTrie[2], 2); } BENCHMARK_RELATIVE(Map_get_prefix2) { runGet(randMap[2], 2); } int main(int argc, char **argv){ google::ParseCommandLineFlags(&argc, &argv, true); google::InitGoogleLogging(argv[0]); prepareRand(); folly::runBenchmarks(); LOG(INFO) << "check: " << x; return 0; } /* * ============================================================================ * mcrouter/lib/fbi/cpp/test/TrieBenchmarks.cpp relative time/iter iters/s * ============================================================================ * Trie_get0 123.68ns 8.09M * Map_get0 41.39% 298.80ns 3.35M * Trie_get1 340.15ns 2.94M * Map_get1 28.16% 1.21us 827.88K * Trie_get2 274.89ns 3.64M * Map_get2 46.64% 589.39ns 1.70M * Trie_get_prefix0 145.53ns 6.87M * Map_get_prefix0 48.55% 299.78ns 3.34M * Trie_get_prefix1 405.26ns 2.47M * Map_get_prefix1 33.60% 1.21us 829.21K * Trie_get_prefix2 342.24ns 2.92M * Map_get_prefix2 58.28% 587.22ns 1.70M * ============================================================================ */ <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef SC_CHARTARR_HXX #define SC_CHARTARR_HXX // ----------------------------------------------------------------------- #include "collect.hxx" #include "rangelst.hxx" #include "chartpos.hxx" #include <boost/ptr_container/ptr_vector.hpp> class ScAddress; class Table; class ScDocument; // ScMemChart is a stripped-down SchMemChart from old chart, // used only to transport a rectangular data array for the UNO API, // contains only column/row header text and data values. class ScMemChart { short nRowCnt; short nColCnt; double* pData; ::rtl::OUString* pColText; ::rtl::OUString* pRowText; ScMemChart(const ScMemChart& rMemChart); // not implemented public: ScMemChart(short nCols, short nRows); ~ScMemChart(); short GetColCount() const { return nColCnt; } short GetRowCount() const { return nRowCnt; } const ::rtl::OUString& GetColText(short nCol) const { return pColText[nCol]; } const ::rtl::OUString& GetRowText(short nRow) const { return pRowText[nRow]; } double GetData(short nCol, short nRow) const { return pData[nCol * nRowCnt + nRow]; } void SetData(short nCol, short nRow, const double& rVal) { pData[nCol * nRowCnt + nRow] = rVal; } void SetColText(short nCol, const ::rtl::OUString& rText) { pColText[nCol] = rText; } void SetRowText(short nRow, const ::rtl::OUString& rText) { pRowText[nRow] = rText; } }; class SC_DLLPUBLIC ScChartArray // only parameter-struct { ::rtl::OUString aName; ScDocument* pDocument; ScChartPositioner aPositioner; bool bValid; // for creation out of SchMemChart private: ScMemChart* CreateMemChartSingle(); ScMemChart* CreateMemChartMulti(); public: ScChartArray( ScDocument* pDoc, SCTAB nTab, SCCOL nStartColP, SCROW nStartRowP, SCCOL nEndColP, SCROW nEndRowP, const ::rtl::OUString& rChartName ); ScChartArray( ScDocument* pDoc, const ScRangeListRef& rRangeList, const ::rtl::OUString& rChartName ); ScChartArray( const ScChartArray& rArr ); ~ScChartArray(); const ScRangeListRef& GetRangeList() const { return aPositioner.GetRangeList(); } void SetRangeList( const ScRangeListRef& rNew ) { aPositioner.SetRangeList(rNew); } void SetRangeList( const ScRange& rNew ) { aPositioner.SetRangeList(rNew); } const ScChartPositionMap* GetPositionMap() { return aPositioner.GetPositionMap(); } void SetHeaders(bool bCol, bool bRow) { aPositioner.SetHeaders(bCol, bRow); } bool HasColHeaders() const { return aPositioner.HasColHeaders(); } bool HasRowHeaders() const { return aPositioner.HasRowHeaders(); } bool IsValid() const { return bValid; } void SetName(const ::rtl::OUString& rNew) { aName = rNew; } const ::rtl::OUString& GetName() const { return aName; } bool operator==(const ScChartArray& rCmp) const; ScMemChart* CreateMemChart(); }; class ScChartCollection { typedef ::boost::ptr_vector<ScChartArray> DataType; DataType maData; public: ScChartCollection(); ScChartCollection(const ScChartCollection& rColl); SC_DLLPUBLIC void push_back(ScChartArray* p); void clear(); size_t size() const; bool empty() const; ScChartArray* operator[](size_t nIndex); const ScChartArray* operator[](size_t nIndex) const; bool operator==(const ScChartCollection& rCmp) const; }; #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>This header no longer needed.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef SC_CHARTARR_HXX #define SC_CHARTARR_HXX // ----------------------------------------------------------------------- #include "rangelst.hxx" #include "chartpos.hxx" #include <boost/ptr_container/ptr_vector.hpp> class ScAddress; class Table; class ScDocument; // ScMemChart is a stripped-down SchMemChart from old chart, // used only to transport a rectangular data array for the UNO API, // contains only column/row header text and data values. class ScMemChart { short nRowCnt; short nColCnt; double* pData; ::rtl::OUString* pColText; ::rtl::OUString* pRowText; ScMemChart(const ScMemChart& rMemChart); // not implemented public: ScMemChart(short nCols, short nRows); ~ScMemChart(); short GetColCount() const { return nColCnt; } short GetRowCount() const { return nRowCnt; } const ::rtl::OUString& GetColText(short nCol) const { return pColText[nCol]; } const ::rtl::OUString& GetRowText(short nRow) const { return pRowText[nRow]; } double GetData(short nCol, short nRow) const { return pData[nCol * nRowCnt + nRow]; } void SetData(short nCol, short nRow, const double& rVal) { pData[nCol * nRowCnt + nRow] = rVal; } void SetColText(short nCol, const ::rtl::OUString& rText) { pColText[nCol] = rText; } void SetRowText(short nRow, const ::rtl::OUString& rText) { pRowText[nRow] = rText; } }; class SC_DLLPUBLIC ScChartArray // only parameter-struct { ::rtl::OUString aName; ScDocument* pDocument; ScChartPositioner aPositioner; bool bValid; // for creation out of SchMemChart private: ScMemChart* CreateMemChartSingle(); ScMemChart* CreateMemChartMulti(); public: ScChartArray( ScDocument* pDoc, SCTAB nTab, SCCOL nStartColP, SCROW nStartRowP, SCCOL nEndColP, SCROW nEndRowP, const ::rtl::OUString& rChartName ); ScChartArray( ScDocument* pDoc, const ScRangeListRef& rRangeList, const ::rtl::OUString& rChartName ); ScChartArray( const ScChartArray& rArr ); ~ScChartArray(); const ScRangeListRef& GetRangeList() const { return aPositioner.GetRangeList(); } void SetRangeList( const ScRangeListRef& rNew ) { aPositioner.SetRangeList(rNew); } void SetRangeList( const ScRange& rNew ) { aPositioner.SetRangeList(rNew); } const ScChartPositionMap* GetPositionMap() { return aPositioner.GetPositionMap(); } void SetHeaders(bool bCol, bool bRow) { aPositioner.SetHeaders(bCol, bRow); } bool HasColHeaders() const { return aPositioner.HasColHeaders(); } bool HasRowHeaders() const { return aPositioner.HasRowHeaders(); } bool IsValid() const { return bValid; } void SetName(const ::rtl::OUString& rNew) { aName = rNew; } const ::rtl::OUString& GetName() const { return aName; } bool operator==(const ScChartArray& rCmp) const; ScMemChart* CreateMemChart(); }; class ScChartCollection { typedef ::boost::ptr_vector<ScChartArray> DataType; DataType maData; public: ScChartCollection(); ScChartCollection(const ScChartCollection& rColl); SC_DLLPUBLIC void push_back(ScChartArray* p); void clear(); size_t size() const; bool empty() const; ScChartArray* operator[](size_t nIndex); const ScChartArray* operator[](size_t nIndex) const; bool operator==(const ScChartCollection& rCmp) const; }; #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: drwlayer.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: rt $ $Date: 2003-11-24 17:23:37 $ * * 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 SC_DRWLAYER_HXX #define SC_DRWLAYER_HXX #ifndef _SV_GRAPH_HXX //autogen #include <vcl/graph.hxx> #endif #ifndef _FM_FMMODEL_HXX #include <svx/fmmodel.hxx> #endif #ifndef _SVSTOR_HXX #include <so3/svstor.hxx> #endif #ifndef SC_SCGLOB_HXX #include "global.hxx" #endif class ScDocument; class SfxViewShell; class ScDrawObjData; class ScIMapInfo; class IMapObject; class ScMarkData; class SdrOle2Obj; // ----------------------------------------------------------------------- class ScTabDeletedHint : public SfxHint { private: USHORT nTab; public: TYPEINFO(); ScTabDeletedHint( USHORT nTabNo = USHRT_MAX ); virtual ~ScTabDeletedHint(); USHORT GetTab() { return nTab; } }; class ScTabSizeChangedHint : public SfxHint { private: USHORT nTab; public: TYPEINFO(); ScTabSizeChangedHint( USHORT nTabNo = USHRT_MAX ); virtual ~ScTabSizeChangedHint(); USHORT GetTab() { return nTab; } }; // ----------------------------------------------------------------------- class ScDrawLayer: public FmFormModel { private: SvStorageRef xPictureStorage; String aName; ScDocument* pDoc; SdrUndoGroup* pUndoGroup; BOOL bRecording; BOOL bAdjustEnabled; BOOL bHyphenatorSet; private: void MoveAreaTwips( USHORT nTab, const Rectangle& rArea, const Point& rMove, const Point& rTopLeft ); void MoveCells( USHORT nTab, USHORT nCol1,USHORT nRow1, USHORT nCol2,USHORT nRow2, short nDx,short nDy ); void RecalcPos( SdrObject* pObj, ScDrawObjData* pData ); public: ScDrawLayer( ScDocument* pDocument, const String& rName ); virtual ~ScDrawLayer(); virtual SdrPage* AllocPage(FASTBOOL bMasterPage); virtual SdrModel* AllocModel() const; virtual void SetChanged( sal_Bool bFlg = sal_True ); virtual Window* GetCurDocViewWin(); virtual SvStream* GetDocumentStream(SdrDocumentStreamInfo& rStreamInfo) const; virtual SdrLayerID GetControlExportLayerId( const SdrObject & ) const; void ReleasePictureStorage(); BOOL HasObjects() const; void ScAddPage( USHORT nTab ); void ScRemovePage( USHORT nTab ); void ScRenamePage( USHORT nTab, const String& rNewName ); void ScMovePage( USHORT nOldPos, USHORT nNewPos ); // inkl. Inhalt, bAlloc=FALSE -> nur Inhalt void ScCopyPage( USHORT nOldPos, USHORT nNewPos, BOOL bAlloc ); ScDocument* GetDocument() const { return pDoc; } void UpdateBasic(); // DocShell-Basic in DrawPages setzen void UseHyphenator(); void Load( SvStream& rStream ); void Store( SvStream& rStream ) const; BOOL GetPrintArea( ScRange& rRange, BOOL bSetHor, BOOL bSetVer ) const; // automatische Anpassungen void EnableAdjust( BOOL bSet = TRUE ) { bAdjustEnabled = bSet; } void BeginCalcUndo(); SdrUndoGroup* GetCalcUndo(); BOOL IsRecording() { return bRecording; } void AddCalcUndo( SdrUndoAction* pUndo ); void MoveArea( USHORT nTab, USHORT nCol1,USHORT nRow1, USHORT nCol2,USHORT nRow2, short nDx,short nDy, BOOL bInsDel ); void WidthChanged( USHORT nTab, USHORT nCol, long nDifTwips ); void HeightChanged( USHORT nTab, USHORT nRow, long nDifTwips ); BOOL HasObjectsInRows( USHORT nTab, USHORT nStartRow, USHORT nEndRow ); void DeleteObjectsInArea( USHORT nTab, USHORT nCol1,USHORT nRow1, USHORT nCol2,USHORT nRow2 ); void DeleteObjectsInSelection( const ScMarkData& rMark ); void DeleteObjects( USHORT nTab ); void CopyToClip( ScDocument* pClipDoc, USHORT nTab, const Rectangle& rRange ); void CopyFromClip( ScDrawLayer* pClipModel, USHORT nSourceTab, const Rectangle& rSourceRange, const ScAddress& rDestPos, const Rectangle& rDestRange ); void SetPageSize( USHORT nPageNo, const Size& rSize ); ULONG GetDefTextHeight() const; // GetVisibleName: name for navigator etc: GetPersistName or GetName // (ChartListenerCollection etc. must use GetPersistName directly) static String GetVisibleName( SdrObject* pObj ); SdrObject* GetNamedObject( const String& rName, USHORT nId, USHORT& rFoundTab ) const; // if pnCounter != NULL, the search for a name starts with this index + 1, // and the index really used is returned. String GetNewGraphicName( long* pnCounter = NULL ) const; void EnsureGraphicNames(); // Verankerung setzen und ermitteln static void SetAnchor( SdrObject*, ScAnchorType ); static ScAnchorType GetAnchor( const SdrObject* ); // Positionen fuer Detektivlinien static ScDrawObjData* GetObjData( SdrObject* pObj, BOOL bCreate=FALSE ); // Image-Map static ScIMapInfo* GetIMapInfo( SdrObject* pObj ); static Graphic GetGraphicFromOle2Obj( const SdrOle2Obj* pOle2Obj ); static IMapObject* GetHitIMapObject( SdrObject* pObject, const Point& rWinPoint, const Window& rCmpWnd ); private: static SvPersist* pGlobalDrawPersist; // fuer AllocModel public: static void SetGlobalDrawPersist(SvPersist* pPersist); }; #endif <commit_msg>INTEGRATION: CWS calcrtl (1.8.84); FILE MERGED 2003/11/27 11:32:20 nn 1.8.84.2: RESYNC: (1.8-1.9); FILE MERGED 2003/07/25 16:49:30 nn 1.8.84.1: #106948# RTL handling of drawing objects<commit_after>/************************************************************************* * * $RCSfile: drwlayer.hxx,v $ * * $Revision: 1.10 $ * * last change: $Author: hr $ $Date: 2004-02-03 12:10:36 $ * * 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 SC_DRWLAYER_HXX #define SC_DRWLAYER_HXX #ifndef _SV_GRAPH_HXX //autogen #include <vcl/graph.hxx> #endif #ifndef _FM_FMMODEL_HXX #include <svx/fmmodel.hxx> #endif #ifndef _SVSTOR_HXX #include <so3/svstor.hxx> #endif #ifndef SC_SCGLOB_HXX #include "global.hxx" #endif class ScDocument; class SfxViewShell; class ScDrawObjData; class ScIMapInfo; class IMapObject; class ScMarkData; class SdrOle2Obj; // ----------------------------------------------------------------------- class ScTabDeletedHint : public SfxHint { private: USHORT nTab; public: TYPEINFO(); ScTabDeletedHint( USHORT nTabNo = USHRT_MAX ); virtual ~ScTabDeletedHint(); USHORT GetTab() { return nTab; } }; class ScTabSizeChangedHint : public SfxHint { private: USHORT nTab; public: TYPEINFO(); ScTabSizeChangedHint( USHORT nTabNo = USHRT_MAX ); virtual ~ScTabSizeChangedHint(); USHORT GetTab() { return nTab; } }; // ----------------------------------------------------------------------- class ScDrawLayer: public FmFormModel { private: SvStorageRef xPictureStorage; String aName; ScDocument* pDoc; SdrUndoGroup* pUndoGroup; BOOL bRecording; BOOL bAdjustEnabled; BOOL bHyphenatorSet; private: void MoveAreaTwips( USHORT nTab, const Rectangle& rArea, const Point& rMove, const Point& rTopLeft ); void MoveCells( USHORT nTab, USHORT nCol1,USHORT nRow1, USHORT nCol2,USHORT nRow2, short nDx,short nDy ); void RecalcPos( SdrObject* pObj, ScDrawObjData* pData, BOOL bNegativePage ); public: ScDrawLayer( ScDocument* pDocument, const String& rName ); virtual ~ScDrawLayer(); virtual SdrPage* AllocPage(FASTBOOL bMasterPage); virtual SdrModel* AllocModel() const; virtual void SetChanged( sal_Bool bFlg = sal_True ); virtual Window* GetCurDocViewWin(); virtual SvStream* GetDocumentStream(SdrDocumentStreamInfo& rStreamInfo) const; virtual SdrLayerID GetControlExportLayerId( const SdrObject & ) const; void ReleasePictureStorage(); BOOL HasObjects() const; void ScAddPage( USHORT nTab ); void ScRemovePage( USHORT nTab ); void ScRenamePage( USHORT nTab, const String& rNewName ); void ScMovePage( USHORT nOldPos, USHORT nNewPos ); // inkl. Inhalt, bAlloc=FALSE -> nur Inhalt void ScCopyPage( USHORT nOldPos, USHORT nNewPos, BOOL bAlloc ); ScDocument* GetDocument() const { return pDoc; } void UpdateBasic(); // DocShell-Basic in DrawPages setzen void UseHyphenator(); void Load( SvStream& rStream ); void Store( SvStream& rStream ) const; BOOL GetPrintArea( ScRange& rRange, BOOL bSetHor, BOOL bSetVer ) const; // automatische Anpassungen void EnableAdjust( BOOL bSet = TRUE ) { bAdjustEnabled = bSet; } void BeginCalcUndo(); SdrUndoGroup* GetCalcUndo(); BOOL IsRecording() { return bRecording; } void AddCalcUndo( SdrUndoAction* pUndo ); void MoveArea( USHORT nTab, USHORT nCol1,USHORT nRow1, USHORT nCol2,USHORT nRow2, short nDx,short nDy, BOOL bInsDel ); void WidthChanged( USHORT nTab, USHORT nCol, long nDifTwips ); void HeightChanged( USHORT nTab, USHORT nRow, long nDifTwips ); BOOL HasObjectsInRows( USHORT nTab, USHORT nStartRow, USHORT nEndRow ); void DeleteObjectsInArea( USHORT nTab, USHORT nCol1,USHORT nRow1, USHORT nCol2,USHORT nRow2 ); void DeleteObjectsInSelection( const ScMarkData& rMark ); void DeleteObjects( USHORT nTab ); void CopyToClip( ScDocument* pClipDoc, USHORT nTab, const Rectangle& rRange ); void CopyFromClip( ScDrawLayer* pClipModel, USHORT nSourceTab, const Rectangle& rSourceRange, const ScAddress& rDestPos, const Rectangle& rDestRange ); void SetPageSize( USHORT nPageNo, const Size& rSize ); ULONG GetDefTextHeight() const; // mirror or move between positive and negative positions for RTL void MirrorRTL( SdrObject* pObj ); static void MirrorRectRTL( Rectangle& rRect ); // for bounding rectangles etc. // GetVisibleName: name for navigator etc: GetPersistName or GetName // (ChartListenerCollection etc. must use GetPersistName directly) static String GetVisibleName( SdrObject* pObj ); SdrObject* GetNamedObject( const String& rName, USHORT nId, USHORT& rFoundTab ) const; // if pnCounter != NULL, the search for a name starts with this index + 1, // and the index really used is returned. String GetNewGraphicName( long* pnCounter = NULL ) const; void EnsureGraphicNames(); // Verankerung setzen und ermitteln static void SetAnchor( SdrObject*, ScAnchorType ); static ScAnchorType GetAnchor( const SdrObject* ); // Positionen fuer Detektivlinien static ScDrawObjData* GetObjData( SdrObject* pObj, BOOL bCreate=FALSE ); // Image-Map static ScIMapInfo* GetIMapInfo( SdrObject* pObj ); static Graphic GetGraphicFromOle2Obj( const SdrOle2Obj* pOle2Obj ); static IMapObject* GetHitIMapObject( SdrObject* pObject, const Point& rWinPoint, const Window& rCmpWnd ); private: static SvPersist* pGlobalDrawPersist; // fuer AllocModel public: static void SetGlobalDrawPersist(SvPersist* pPersist); }; #endif <|endoftext|>
<commit_before>#pragma once #include <utility> #include <supermarx/id_t.hpp> #include <supermarx/data/product.hpp> #include <supermarx/data/productdetails.hpp> #include <boost/optional.hpp> #include <boost/fusion/include/adapt_struct.hpp> namespace supermarx { namespace data { struct productclass; } namespace message { struct product_summary { std::string identifier; // Internal reference as used by scrapers std::string name; reference<data::productclass> productclass_id; uint64_t volume; measure volume_measure; uint64_t orig_price; // In (euro)cents uint64_t price; // In (euro)cents, with discount applied uint64_t discount_amount; datetime valid_on; boost::optional<reference<data::imagecitation>> imagecitation_id; static product_summary merge(data::product const& p, data::productdetails const& pd) { return product_summary({ p.identifier, p.name, p.productclass_id, p.volume, p.volume_measure, pd.orig_price, pd.price, pd.discount_amount, pd.valid_on, p.imagecitation_id }); } }; } } BOOST_FUSION_ADAPT_STRUCT( supermarx::message::product_summary, (std::string, identifier) (std::string, name) (supermarx::reference<supermarx::data::productclass>, productclass_id) (uint64_t, volume) (supermarx::measure, volume_measure) (uint64_t, orig_price) (uint64_t, price) (uint64_t, discount_amount) (supermarx::datetime, valid_on) (boost::optional<supermarx::id_t>, imagecitation_id) ) <commit_msg>Fixed wrong fusion adaptation<commit_after>#pragma once #include <utility> #include <supermarx/id_t.hpp> #include <supermarx/data/product.hpp> #include <supermarx/data/productdetails.hpp> #include <boost/optional.hpp> #include <boost/fusion/include/adapt_struct.hpp> namespace supermarx { namespace data { struct productclass; } namespace message { struct product_summary { std::string identifier; // Internal reference as used by scrapers std::string name; reference<data::productclass> productclass_id; uint64_t volume; measure volume_measure; uint64_t orig_price; // In (euro)cents uint64_t price; // In (euro)cents, with discount applied uint64_t discount_amount; datetime valid_on; boost::optional<reference<data::imagecitation>> imagecitation_id; static product_summary merge(data::product const& p, data::productdetails const& pd) { return product_summary({ p.identifier, p.name, p.productclass_id, p.volume, p.volume_measure, pd.orig_price, pd.price, pd.discount_amount, pd.valid_on, p.imagecitation_id }); } }; } } BOOST_FUSION_ADAPT_STRUCT( supermarx::message::product_summary, (std::string, identifier) (std::string, name) (supermarx::reference<supermarx::data::productclass>, productclass_id) (uint64_t, volume) (supermarx::measure, volume_measure) (uint64_t, orig_price) (uint64_t, price) (uint64_t, discount_amount) (supermarx::datetime, valid_on) (boost::optional<supermarx::reference<supermarx::data::imagecitation>>, imagecitation_id) ) <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: shellids.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: obo $ $Date: 2004-08-12 09:27:02 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SC_SHELLIDS_HXX #define SC_SHELLIDS_HXX // Sfx Interface-IDs #define SCID_APP (SFX_INTERFACE_SC_START+0) #define SCID_DOC_SHELL (SFX_INTERFACE_SC_START+1) #define SCID_TABVIEW_SHELL (SFX_INTERFACE_SC_START+2) #define SCID_TABPOP_SHELL (SFX_INTERFACE_SC_START+3) #define SCID_EDIT_SHELL (SFX_INTERFACE_SC_START+4) #define SCID_DRAW_SHELL (SFX_INTERFACE_SC_START+5) #define SCID_DRAW_TEXT_SHELL (SFX_INTERFACE_SC_START+6) #define SCID_PREVIEW_SHELL (SFX_INTERFACE_SC_START+7) #define SCID_PIVOT_SHELL (SFX_INTERFACE_SC_START+8) #define SCID_AUDITING_SHELL (SFX_INTERFACE_SC_START+9) #define SCID_FORM_SHELL (SFX_INTERFACE_SC_START+10) #define SCID_FORMAT_SHELL (SFX_INTERFACE_SC_START+11) #define SCID_CELL_SHELL (SFX_INTERFACE_SC_START+12) #define SCID_OLEOBJECT_SHELL (SFX_INTERFACE_SC_START+13) #define SCID_CHART_SHELL (SFX_INTERFACE_SC_START+14) #define SCID_GRAPHIC_SHELL (SFX_INTERFACE_SC_START+15) #define SCID_PAGEBREAK_SHELL (SFX_INTERFACE_SC_START+16) #define SCID_MEDIA_SHELL (SFX_INTERFACE_SC_START+17) #endif <commit_msg>INTEGRATION: CWS ooo19126 (1.2.354); FILE MERGED 2005/09/05 15:01:00 rt 1.2.354.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: shellids.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-08 17:57:29 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SC_SHELLIDS_HXX #define SC_SHELLIDS_HXX // Sfx Interface-IDs #define SCID_APP (SFX_INTERFACE_SC_START+0) #define SCID_DOC_SHELL (SFX_INTERFACE_SC_START+1) #define SCID_TABVIEW_SHELL (SFX_INTERFACE_SC_START+2) #define SCID_TABPOP_SHELL (SFX_INTERFACE_SC_START+3) #define SCID_EDIT_SHELL (SFX_INTERFACE_SC_START+4) #define SCID_DRAW_SHELL (SFX_INTERFACE_SC_START+5) #define SCID_DRAW_TEXT_SHELL (SFX_INTERFACE_SC_START+6) #define SCID_PREVIEW_SHELL (SFX_INTERFACE_SC_START+7) #define SCID_PIVOT_SHELL (SFX_INTERFACE_SC_START+8) #define SCID_AUDITING_SHELL (SFX_INTERFACE_SC_START+9) #define SCID_FORM_SHELL (SFX_INTERFACE_SC_START+10) #define SCID_FORMAT_SHELL (SFX_INTERFACE_SC_START+11) #define SCID_CELL_SHELL (SFX_INTERFACE_SC_START+12) #define SCID_OLEOBJECT_SHELL (SFX_INTERFACE_SC_START+13) #define SCID_CHART_SHELL (SFX_INTERFACE_SC_START+14) #define SCID_GRAPHIC_SHELL (SFX_INTERFACE_SC_START+15) #define SCID_PAGEBREAK_SHELL (SFX_INTERFACE_SC_START+16) #define SCID_MEDIA_SHELL (SFX_INTERFACE_SC_START+17) #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2007 Digital Bazaar, Inc. All rights reserved. */ #include "Operation.h" using namespace db::modest; using namespace db::rt; Operation::Operation(Runnable* r, OperationEnvironment* e, StateMutator* m) { mRunnable = r; mEnvironment = e; mStateMutator = m; mStarted = false; mInterrupted = false; mFinished = false; mCanceled = false; } Operation::~Operation() { } void Operation::waitFor() { lock(); { // wait until Operation finishes or is canceled while(!finished() && !canceled()) { wait(); } } unlock(); } bool Operation::started() { return mStarted; } void Operation::interrupt() { // synchronize lock(); { mInterrupted = true; if(mThread != NULL) { mThread->interrupt(); } } unlock(); } bool Operation::isInterrupted() { return mInterrupted; } bool Operation::finished() { return mFinished; } bool Operation::canceled() { return mCanceled; } Runnable* Operation::getRunnable() { return mRunnable; } OperationEnvironment* Operation::getEnvironment() { return mEnvironment; } StateMutator* Operation::getStateMutator() { return mStateMutator; } bool Operation::interrupted() { return Thread::interrupted(); } <commit_msg>Fixed some formatting issues.<commit_after>/* * Copyright (c) 2007 Digital Bazaar, Inc. All rights reserved. */ #include "Operation.h" using namespace db::modest; using namespace db::rt; Operation::Operation(Runnable* r, OperationEnvironment* e, StateMutator* m) { mRunnable = r; mEnvironment = e; mStateMutator = m; mStarted = false; mInterrupted = false; mFinished = false; mCanceled = false; } Operation::~Operation() { } void Operation::waitFor() { lock(); { // wait until Operation finishes or is canceled while(!finished() && !canceled()) { wait(); } } unlock(); } bool Operation::started() { return mStarted; } void Operation::interrupt() { mInterrupted = true; if(mThread != NULL) { mThread->interrupt(); } } bool Operation::isInterrupted() { return mInterrupted; } bool Operation::finished() { return mFinished; } bool Operation::canceled() { return mCanceled; } Runnable* Operation::getRunnable() { return mRunnable; } OperationEnvironment* Operation::getEnvironment() { return mEnvironment; } StateMutator* Operation::getStateMutator() { return mStateMutator; } bool Operation::interrupted() { return Thread::interrupted(); } <|endoftext|>
<commit_before><commit_msg>legion: fix a disjoint ready race that could cause realm hangs<commit_after><|endoftext|>
<commit_before><commit_msg>legion: fix copy-paste error<commit_after><|endoftext|>
<commit_before><commit_msg>INTEGRATION: CWS presentationengine01 (1.5.12); FILE MERGED 2004/09/06 11:22:43 cl 1.5.12.2: added preview support 2004/08/25 16:42:58 cl 1.5.12.1: replaced old FuSlideShow with new SlideShow<commit_after><|endoftext|>
<commit_before>/* * Copyright © 2008, 2009 Intel Corporation * * 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 (including the next * paragraph) 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 <getopt.h> #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <string.h> #include <inttypes.h> /** @file main.cpp * * This file is the main() routine and scaffolding for producing * builtin_compiler (which doesn't include builtins itself and is used * to generate the profile information for builtin_function.cpp), and * for glsl_compiler (which does include builtins and can be used to * offline compile GLSL code and examine the resulting GLSL IR. */ #include "gpu.h" #include "pipeline.h" #include "compiler_interface.h" #include "compiler/mesa-utils/src/glsl/ralloc.h" #include "pipeline_compiler_interface.h" static char* load_spv_file(const char *filename, size_t *psize) { long int size; void *shader_code; FILE *fp = fopen(filename, "rb"); if (!fp) return NULL; fseek(fp, 0L, SEEK_END); size = ftell(fp); fseek(fp, 0L, SEEK_SET); shader_code = malloc(size); size_t tmp = fread(shader_code, size, 1, fp); (void) tmp; *psize = size; return (char *) shader_code; } static char* load_glsl_file(const char *filename, size_t *psize, VkShaderStageFlagBits stage) { long int size; void *shader_code; FILE *fp = fopen(filename, "r"); if (!fp) return NULL; fseek(fp, 0L, SEEK_END); size = ftell(fp) + sizeof(icd_spv_header) + 1; fseek(fp, 0L, SEEK_SET); shader_code = malloc(size); size_t s = fread((char *)shader_code + sizeof(icd_spv_header), size - sizeof(icd_spv_header), 1, fp); (void) s; ((char *)shader_code)[size-1] = 0; icd_spv_header* header = (icd_spv_header*)shader_code; header->magic = ICD_SPV_MAGIC; header->version = 0; // not SPV header->gen_magic = stage; *psize = size; return (char *) shader_code; } int dump_ast = 0; int dump_hir = 0; int dump_lir = 0; int do_link = 0; const struct option compiler_opts[] = { { "dump-ast", no_argument, &dump_ast, 1 }, { "dump-hir", no_argument, &dump_hir, 1 }, { "dump-lir", no_argument, &dump_lir, 1 }, { "link", no_argument, &do_link, 1 }, { "version", required_argument, NULL, 'v' }, { NULL, 0, NULL, 0 } }; bool checkFileName(char* fileName) { const unsigned fileNameLength = strlen(fileName); if (fileNameLength < 5 || strncmp(".spv", &fileName[fileNameLength - 4], 4) != 0) { printf("file must be .spv, .vert, .geom, or .frag\n"); return false; } return true; } bool checkFileExt(char* fileName, const char* ext) { const unsigned fileNameLength = strlen(fileName); if (strncmp(ext, &fileName[fileNameLength - strlen(ext)], strlen(ext)) != 0) { return false; } return true; } int main(int argc, char **argv) { int status = EXIT_SUCCESS; switch (argc) { case 2: { // Call vkCreateShader on the single shader printf("Frontend compile %s\n", argv[1]); fflush(stdout); void *shaderCode; size_t size = 0; VkShaderStageFlagBits stage = VK_SHADER_STAGE_VERTEX_BIT; if (checkFileExt(argv[1], ".spv")) { shaderCode = load_spv_file(argv[1], &size); } else if (checkFileExt(argv[1], ".vert")) { stage = VK_SHADER_STAGE_VERTEX_BIT; } else if (checkFileExt(argv[1], ".geom")) { stage = VK_SHADER_STAGE_GEOMETRY_BIT; } else if (checkFileExt(argv[1], ".frag")) { stage = VK_SHADER_STAGE_FRAGMENT_BIT; } else { return EXIT_FAILURE; } shaderCode = load_glsl_file(argv[1], &size, stage); assert(shaderCode); struct intel_ir *shader_program = shader_create_ir(NULL, shaderCode, size, stage); assert(shader_program); // Set up only the fields needed for backend compile struct intel_gpu gpu = { 0 }; gpu.gen_opaque = INTEL_GEN(7.5); gpu.gt = 3; printf("Backend compile %s\n", argv[1]); fflush(stdout); // struct timespec before; // clock_gettime(CLOCK_MONOTONIC, &before); // uint64_t beforeNanoSeconds = before.tv_nsec + before.tv_sec*INT64_C(1000000000); struct intel_pipeline_shader pipe_shader; VkResult ret = intel_pipeline_shader_compile(&pipe_shader, &gpu, NULL, NULL, shader_program); // struct timespec after; // clock_gettime(CLOCK_MONOTONIC, &after); // uint64_t afterNanoSeconds = after.tv_nsec + after.tv_sec*INT64_C(1000000000); // printf("file: %s, intel_pipeline_shader_compile = %" PRIu64 " milliseconds\n", argv[1], (afterNanoSeconds - beforeNanoSeconds)/1000000); // fflush(stdout); if (ret != VK_SUCCESS) return ret; intel_pipeline_shader_cleanup(&pipe_shader, &gpu); shader_destroy_ir(shader_program); } break; case 3: // Call vkCreateShader on both shaders, then call vkCreateGraphicsPipeline? // Only need to hook this up if we start invoking the backend once for the whole pipeline printf("Multiple shaders not hooked up yet\n"); break; // Ensure both filenames have a .spv extension if (!checkFileName(argv[1])) return EXIT_FAILURE; if (!checkFileName(argv[2])) return EXIT_FAILURE; void *shaderCode[2]; size_t size[2]; struct intel_ir *result[2]; // Compile first shader shaderCode[0] = load_spv_file(argv[1], &size[0]); assert(shaderCode[0]); printf("Compiling %s\n", argv[1]); result[0] = shader_create_ir(NULL, shaderCode[0], size[0], VK_SHADER_STAGE_VERTEX_BIT); assert(result[0]); // Compile second shader shaderCode[1] = load_spv_file(argv[2], &size[1]); assert(shaderCode[1]); printf("Compiling %s\n", argv[2]); result[1] = shader_create_ir(NULL, shaderCode[1], size[1], VK_SHADER_STAGE_FRAGMENT_BIT); assert(result[1]); shader_destroy_ir(result[0]); shader_destroy_ir(result[1]); break; case 0: case 1: default: printf("Please provide one .spv, .vert or .frag file as input\n"); break; } return status; } <commit_msg>standalone_compiler: recognize [frag|vert|geom].spv suffixes<commit_after>/* * Copyright © 2008, 2009 Intel Corporation * * 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 (including the next * paragraph) 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 <getopt.h> #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <string.h> #include <inttypes.h> /** @file main.cpp * * This file is the main() routine and scaffolding for producing * builtin_compiler (which doesn't include builtins itself and is used * to generate the profile information for builtin_function.cpp), and * for glsl_compiler (which does include builtins and can be used to * offline compile GLSL code and examine the resulting GLSL IR. */ #include "gpu.h" #include "pipeline.h" #include "compiler_interface.h" #include "compiler/mesa-utils/src/glsl/ralloc.h" #include "pipeline_compiler_interface.h" static char* load_spv_file(const char *filename, size_t *psize) { long int size; void *shader_code; FILE *fp = fopen(filename, "rb"); if (!fp) return NULL; fseek(fp, 0L, SEEK_END); size = ftell(fp); fseek(fp, 0L, SEEK_SET); shader_code = malloc(size); size_t tmp = fread(shader_code, size, 1, fp); (void) tmp; *psize = size; return (char *) shader_code; } static char* load_glsl_file(const char *filename, size_t *psize, VkShaderStageFlagBits stage) { long int size; void *shader_code; FILE *fp = fopen(filename, "r"); if (!fp) return NULL; fseek(fp, 0L, SEEK_END); size = ftell(fp) + sizeof(icd_spv_header) + 1; fseek(fp, 0L, SEEK_SET); shader_code = malloc(size); size_t s = fread((char *)shader_code + sizeof(icd_spv_header), size - sizeof(icd_spv_header), 1, fp); (void) s; ((char *)shader_code)[size-1] = 0; icd_spv_header* header = (icd_spv_header*)shader_code; header->magic = ICD_SPV_MAGIC; header->version = 0; // not SPV header->gen_magic = stage; *psize = size; return (char *) shader_code; } int dump_ast = 0; int dump_hir = 0; int dump_lir = 0; int do_link = 0; const struct option compiler_opts[] = { { "dump-ast", no_argument, &dump_ast, 1 }, { "dump-hir", no_argument, &dump_hir, 1 }, { "dump-lir", no_argument, &dump_lir, 1 }, { "link", no_argument, &do_link, 1 }, { "version", required_argument, NULL, 'v' }, { NULL, 0, NULL, 0 } }; bool checkFileName(char* fileName) { const unsigned fileNameLength = strlen(fileName); if (fileNameLength < 5 || strncmp(".spv", &fileName[fileNameLength - 4], 4) != 0) { printf("file must be .spv, .vert, .geom, or .frag\n"); return false; } return true; } bool checkFileExt(char* fileName, const char* ext) { const unsigned fileNameLength = strlen(fileName); if (strncmp(ext, &fileName[fileNameLength - strlen(ext)], strlen(ext)) != 0) { return false; } return true; } int main(int argc, char **argv) { int status = EXIT_SUCCESS; switch (argc) { case 2: { // Call vkCreateShader on the single shader printf("Frontend compile %s\n", argv[1]); fflush(stdout); void *shaderCode = 0; size_t size = 0; VkShaderStageFlagBits stage = VK_SHADER_STAGE_VERTEX_BIT; if (checkFileExt(argv[1], "vert.spv")) { shaderCode = load_spv_file(argv[1], &size); stage = VK_SHADER_STAGE_VERTEX_BIT; } else if (checkFileExt(argv[1], "frag.spv")) { shaderCode = load_spv_file(argv[1], &size); stage = VK_SHADER_STAGE_FRAGMENT_BIT; } else if (checkFileExt(argv[1], "geom.spv")) { shaderCode = load_spv_file(argv[1], &size); stage = VK_SHADER_STAGE_GEOMETRY_BIT; } else if (checkFileExt(argv[1], ".spv")) { shaderCode = load_spv_file(argv[1], &size); } else if (checkFileExt(argv[1], ".vert")) { stage = VK_SHADER_STAGE_VERTEX_BIT; } else if (checkFileExt(argv[1], ".geom")) { stage = VK_SHADER_STAGE_GEOMETRY_BIT; } else if (checkFileExt(argv[1], ".frag")) { stage = VK_SHADER_STAGE_FRAGMENT_BIT; } else { return EXIT_FAILURE; } if (!shaderCode) shaderCode = load_glsl_file(argv[1], &size, stage); assert(shaderCode); struct intel_ir *shader_program = shader_create_ir(NULL, shaderCode, size, stage); assert(shader_program); // Set up only the fields needed for backend compile struct intel_gpu gpu = { 0 }; gpu.gen_opaque = INTEL_GEN(7.5); gpu.gt = 3; printf("Backend compile %s\n", argv[1]); fflush(stdout); // struct timespec before; // clock_gettime(CLOCK_MONOTONIC, &before); // uint64_t beforeNanoSeconds = before.tv_nsec + before.tv_sec*INT64_C(1000000000); struct intel_pipeline_shader pipe_shader; VkResult ret = intel_pipeline_shader_compile(&pipe_shader, &gpu, NULL, NULL, shader_program); // struct timespec after; // clock_gettime(CLOCK_MONOTONIC, &after); // uint64_t afterNanoSeconds = after.tv_nsec + after.tv_sec*INT64_C(1000000000); // printf("file: %s, intel_pipeline_shader_compile = %" PRIu64 " milliseconds\n", argv[1], (afterNanoSeconds - beforeNanoSeconds)/1000000); // fflush(stdout); if (ret != VK_SUCCESS) return ret; intel_pipeline_shader_cleanup(&pipe_shader, &gpu); shader_destroy_ir(shader_program); } break; case 3: // Call vkCreateShader on both shaders, then call vkCreateGraphicsPipeline? // Only need to hook this up if we start invoking the backend once for the whole pipeline printf("Multiple shaders not hooked up yet\n"); break; // Ensure both filenames have a .spv extension if (!checkFileName(argv[1])) return EXIT_FAILURE; if (!checkFileName(argv[2])) return EXIT_FAILURE; void *shaderCode[2]; size_t size[2]; struct intel_ir *result[2]; // Compile first shader shaderCode[0] = load_spv_file(argv[1], &size[0]); assert(shaderCode[0]); printf("Compiling %s\n", argv[1]); result[0] = shader_create_ir(NULL, shaderCode[0], size[0], VK_SHADER_STAGE_VERTEX_BIT); assert(result[0]); // Compile second shader shaderCode[1] = load_spv_file(argv[2], &size[1]); assert(shaderCode[1]); printf("Compiling %s\n", argv[2]); result[1] = shader_create_ir(NULL, shaderCode[1], size[1], VK_SHADER_STAGE_FRAGMENT_BIT); assert(result[1]); shader_destroy_ir(result[0]); shader_destroy_ir(result[1]); break; case 0: case 1: default: printf("Please provide one .spv, .vert or .frag file as input\n"); break; } return status; } <|endoftext|>
<commit_before>#include "operation.h" #include <lambda_p_script/times/operation.h> #include <lambda_p/errors/error_list.h> #include <lambda_p_script/integer/subtract.h> #include <lambda_p_script/integer/node.h> #include <lambda_p_script_io/builder.h> #include <lambda_p_io/source.h> #include <lambda_p_script/routine.h> #include <boost/bind.hpp> void lambda_p_script_test::times::operation::run () { run_1 (); run_2 (); } void lambda_p_script_test::times::operation::run_1 () { auto errors (boost::shared_ptr <lambda_p::errors::error_list> (new lambda_p::errors::error_list)); lambda_p_script::times::operation times; std::vector <boost::shared_ptr <lambda_p::node>> arguments; auto n1 (boost::shared_ptr <lambda_p::node> (new lambda_p_script::integer::node (0))); arguments.push_back (n1); auto n2 (boost::shared_ptr <lambda_p::node> (new lambda_p_script::integer::subtract)); arguments.push_back (n2); auto n3 (boost::shared_ptr <lambda_p::node> (new lambda_p_script::integer::node (5))); arguments.push_back (n3); auto n4 (boost::shared_ptr <lambda_p::node> (new lambda_p_script::integer::node (1))); arguments.push_back (n4); std::vector <boost::shared_ptr <lambda_p::node>> results; times.perform (errors, arguments, results); assert (errors->errors.empty ()); assert (results.size () == 2); assert (results [0] == n3); assert (results [1] == n4); } void lambda_p_script_test::times::operation::run_2 () { //lambda_p_script_io::builder builder; //lambda_p_io::source source (boost::bind (&lambda_p_io::lexer::lexer::operator(), &builder.lexer, _1)); //source (L"[[:~; subtract number amount] .id subtract [subtract number amount] amount]"); //assert (builder.errors->errors.empty ()); //lambda_p_script::times::operation times; //std::vector <boost::shared_ptr <lambda_p::node>> arguments; //auto n1 (boost::shared_ptr <lambda_p::node> (new lambda_p_script::integer::node (2))); //arguments.push_back (n1); //auto n2 (builder.routines [0]); //arguments.push_back (n2); //auto n3 (boost::shared_ptr <lambda_p::node> (new lambda_p_script::integer::subtract)); //arguments.push_back (n3); //auto n4 (boost::shared_ptr <lambda_p::node> (new lambda_p_script::integer::node (5))); //arguments.push_back (n4); //auto n5 (boost::shared_ptr <lambda_p::node> (new lambda_p_script::integer::node (1))); //arguments.push_back (n5); //std::vector <boost::shared_ptr <lambda_p::node>> results; //times.perform (builder.errors, arguments, results); //assert (builder.errors->errors.empty ()); //assert (results.size () == 2); }<commit_msg>Fixing times test.<commit_after>#include "operation.h" #include <lambda_p_script/times/operation.h> #include <lambda_p/errors/error_list.h> #include <lambda_p_script/integer/subtract.h> #include <lambda_p_script/integer/node.h> #include <lambda_p_script_io/builder.h> #include <lambda_p_io/source.h> #include <lambda_p_script/routine.h> #include <boost/bind.hpp> void lambda_p_script_test::times::operation::run () { run_1 (); run_2 (); } void lambda_p_script_test::times::operation::run_1 () { auto errors (boost::shared_ptr <lambda_p::errors::error_list> (new lambda_p::errors::error_list)); lambda_p_script::times::operation times; std::vector <boost::shared_ptr <lambda_p::node>> arguments; auto n1 (boost::shared_ptr <lambda_p::node> (new lambda_p_script::integer::node (0))); arguments.push_back (n1); auto n2 (boost::shared_ptr <lambda_p::node> (new lambda_p_script::integer::subtract)); arguments.push_back (n2); auto n3 (boost::shared_ptr <lambda_p::node> (new lambda_p_script::integer::node (5))); arguments.push_back (n3); auto n4 (boost::shared_ptr <lambda_p::node> (new lambda_p_script::integer::node (1))); arguments.push_back (n4); std::vector <boost::shared_ptr <lambda_p::node>> results; times.perform (errors, arguments, results); assert (errors->errors.empty ()); assert (results.size () == 2); assert (results [0] == n3); assert (results [1] == n4); } void lambda_p_script_test::times::operation::run_2 () { lambda_p_script_io::builder builder; lambda_p_io::source source (boost::bind (&lambda_p_io::lexer::lexer::operator(), &builder.lexer, _1)); source (L"[[:~; subtract number amount] subtract [subtract number amount] amount]"); assert (builder.errors->errors.empty ()); lambda_p_script::times::operation times; std::vector <boost::shared_ptr <lambda_p::node>> arguments; auto n1 (boost::shared_ptr <lambda_p::node> (new lambda_p_script::integer::node (2))); arguments.push_back (n1); auto n2 (builder.routines [0]); arguments.push_back (n2); auto n3 (boost::shared_ptr <lambda_p::node> (new lambda_p_script::integer::subtract)); arguments.push_back (n3); auto n4 (boost::shared_ptr <lambda_p::node> (new lambda_p_script::integer::node (5))); arguments.push_back (n4); auto n5 (boost::shared_ptr <lambda_p::node> (new lambda_p_script::integer::node (1))); arguments.push_back (n5); std::vector <boost::shared_ptr <lambda_p::node>> results; times.perform (builder.errors, arguments, results); assert (builder.errors->errors.empty ()); assert (results.size () == 3); auto r1 (boost::dynamic_pointer_cast <lambda_p_script::integer::subtract> (results [0])); assert (r1.get () != nullptr); auto r2 (boost::dynamic_pointer_cast <lambda_p_script::integer::node> (results [1])); assert (r2.get () != nullptr); assert (r2->value == 3); auto r3 (boost::dynamic_pointer_cast <lambda_p_script::integer::node> (results [2])); assert (r3.get () != nullptr); assert (r3->value == 1); }<|endoftext|>
<commit_before>/* * Copyright (C) 2013 by Glenn Hickey (hickey@soe.ucsc.edu) * * Released under the MIT license, see LICENSE.txt */ #include <deque> #include <cassert> #include <map> #include <sstream> #include "hal.h" #include "halChain.h" #include "halBlockViz.h" using namespace std; using namespace hal; // We bend over backwards to cope with stone-age interface typedef pair<AlignmentConstPtr, const Genome*> OpenGenome; struct OGLess { bool operator()(const OpenGenome& og1, const OpenGenome& og2) { return og1.first.get() < og2.first.get() || ( og1.first.get() == og2.first.get() && og1.second < og2.second); } }; static map<string, AlignmentConstPtr> halPathMap; static map<int, OpenGenome> halHandleMap; static map<OpenGenome, int, OGLess> halHandleReverseMap; static block* readBlocks(BottomSegmentIteratorConstPtr bottom, hal_index_t childIndex, hal_index_t absEnd, int getSequenceString); static void readBlock(block* cur, BottomSegmentIteratorConstPtr bottom, TopSegmentIteratorConstPtr top, int getSequenceString, const string& genomeName, string& seqBuffer, string& dnaBuffer); extern "C" int halOpen(char *halFileName, char* qSpeciesName) { int handle = -1; try { // if path has been opened before, find the alignment AlignmentConstPtr alignment; map<string, AlignmentConstPtr>::iterator pmi = halPathMap.find(halFileName); if (pmi != halPathMap.end()) { alignment = pmi->second; } else { alignment = hdf5AlignmentInstanceReadOnly(); alignment->open(halFileName); halPathMap.insert(pair<string, AlignmentConstPtr>( qSpeciesName, alignment)); } const Genome* genome = alignment->openGenome(qSpeciesName); if (genome == NULL) { throw hal_exception(string(qSpeciesName) + " not found"); } OpenGenome og(alignment, genome); // if the path and genome have been open before, return the existing // handle map<OpenGenome, int, OGLess>::iterator hri = halHandleReverseMap.find(og); if (hri != halHandleReverseMap.end()) { handle = hri->second; } else { // create new handle and return it. updating both maps handle = 0; if (halHandleMap.empty() == false) { handle = halHandleMap.rbegin()->first + 1; } halHandleMap.insert(pair<int, OpenGenome>(handle, og)); halHandleReverseMap.insert(pair<OpenGenome, int>(og, handle)); } } catch(exception& e) { cerr << "Exception caught: " << e.what() << endl; handle = -1; } return handle; } extern "C" int halClose(int handle) { try { map<int, OpenGenome>::iterator hmi = halHandleMap.find(handle); if (hmi == halHandleMap.end()) { stringstream ss; ss << "error closing handle " << handle << ": not found"; throw hal_exception(ss.str()); } OpenGenome og(hmi->second.first, hmi->second.second); AlignmentConstPtr alignment = og.first; // remove from handle maps halHandleMap.erase(hmi); halHandleReverseMap.erase(halHandleReverseMap.find(og)); // close the genome alignment->closeGenome(og.second); bool last = true; for (hmi = halHandleMap.begin(); last && hmi != halHandleMap.end(); ++hmi) { AlignmentConstPtr alInMap = hmi->second.first; if (alInMap.get() == alignment.get()) { last = false; } } // this was the last reference to the alignment. so we close it if (last == true) { map<string, AlignmentConstPtr>::iterator hpi = halPathMap.begin(); for (; hpi != halPathMap.end(); ++hpi) { AlignmentConstPtr alInMap = hpi->second; if (alInMap.get() == alignment.get()) { alignment->close(); halPathMap.erase(hpi); break; } } } } catch(exception& e) { cerr << "Exception caught: " << e.what() << endl; return -1; } return 0; } extern "C" void halFreeBlocks(block* head) { while (head != NULL) { block* next = head->next; free(head->sequence); free(head->qChrom); free(head); head = next; } } extern "C" struct block *halGetBlocksInTargetRange(int halHandle, char* tChrom, int tStart, int tEnd, int getSequenceString) { try { map<int, OpenGenome>::iterator hmi = halHandleMap.find(halHandle); if (hmi == halHandleMap.end()) { stringstream ss; ss << "Handle " << halHandle << " not found"; throw hal_exception(ss.str()); } AlignmentConstPtr alignment = hmi->second.first; const Genome* genome = hmi->second.second; const Genome* parent = genome->getParent(); if (parent == NULL) { stringstream ss; ss << "Open genome " << genome->getName() << " is root in HAL tree" " and therefore has no reference and cannot be used to get blocks"; throw hal_exception(ss.str()); } const Sequence* sequence = parent->getSequence(tChrom); // cactus pipeline presently adds species name as prefix of // sequence name. check if this caused confusion string sequenceName; if (sequence == NULL) { sequenceName = tChrom; sequenceName += '.'; sequenceName += tChrom; sequence = parent->getSequence(sequenceName); } if (sequence == NULL || (hal_size_t)tStart >= sequence->getSequenceLength() || (hal_size_t)tEnd > sequence->getSequenceLength()) { stringstream ss; ss << "Unable to locate sequence " << tChrom << "(or " << sequenceName << ") in genome " << parent->getName(); throw hal_exception(ss.str()); } hal_index_t myEnd = tEnd > 0 ? tEnd : sequence->getSequenceLength(); hal_index_t absStart = sequence->getStartPosition() + tStart; hal_index_t absEnd = sequence->getStartPosition() + myEnd; hal_index_t childIndex = parent->getChildIndex(genome); if (absStart >= absEnd) { throw hal_exception("Invalid range"); } BottomSegmentIteratorConstPtr bottom = parent->getBottomSegmentIterator(childIndex); bottom->toSite(absStart, false); hal_offset_t startOffset = absStart - bottom->getStartPosition(); hal_offset_t endOffset = 0; if (absEnd <= bottom->getEndPosition()) { endOffset = bottom->getEndPosition() - absEnd + 1; } bottom->slice(startOffset, endOffset); assert(bottom->getStartPosition() == absStart); assert(bottom->getEndPosition() <= absEnd); if (bottom->getLength() == 0) { throw hal_exception("Error generating blocks. " "Invalid range specified?"); } block* head = readBlocks(bottom, childIndex, absEnd, getSequenceString); return head; } catch(exception& e) { cerr << "Exception caught: " << e.what() << endl; } return NULL; } block* readBlocks(BottomSegmentIteratorConstPtr bottom, hal_index_t childIndex, hal_index_t absEnd, int getSequenceString) { block* head = NULL; block* prev = NULL; TopSegmentIteratorConstPtr top = bottom->getGenome()->getChild(childIndex)->getTopSegmentIterator(); string genomeName = top->getGenome()->getName(); string seqBuffer, dnaBuffer; hal_index_t lastIndex = (hal_index_t)bottom->getGenome()->getNumBottomSegments(); cout << lastIndex << endl; while (bottom->getArrayIndex() < lastIndex && bottom->getStartPosition() < absEnd - 1) { if (bottom->hasChild(childIndex)) { block* cur = (block*)malloc(sizeof(block)); if (head == NULL) { head = cur; } else { prev->next = cur; } top->toChild(bottom, childIndex); readBlock(cur, bottom, top, getSequenceString, genomeName, seqBuffer, dnaBuffer); prev = cur; } bottom->toRight(absEnd - 1); } return head; } void readBlock(block* cur, BottomSegmentIteratorConstPtr bottom, TopSegmentIteratorConstPtr top, int getSequenceString, const string& genomeName, string& seqBuffer, string& dnaBuffer) { const Sequence* tSequence = top->getSequence(); cur->next = NULL; seqBuffer = tSequence->getName(); size_t prefix = seqBuffer.find(genomeName + '.') != 0 ? 0 : genomeName.length() + 1; cur->qChrom = (char*)malloc(seqBuffer.length() + 1 - prefix); strcpy(cur->qChrom, seqBuffer.c_str() + prefix); cur->tStart = bottom->getStartPosition(); cur->qStart = top->getStartPosition(); if (top->getReversed() == true) { cur->qStart = tSequence->getSequenceLength() - cur->qStart; } cur->size = bottom->getLength(); cur->strand = top->getReversed() ? '-' : '+'; cur->sequence = NULL; if (getSequenceString != 0) { top->getString(dnaBuffer); cur->sequence = (char*)malloc(dnaBuffer.length() + 1); strcpy(cur->sequence, dnaBuffer.c_str()); } } <commit_msg>more coordinate bugs<commit_after>/* * Copyright (C) 2013 by Glenn Hickey (hickey@soe.ucsc.edu) * * Released under the MIT license, see LICENSE.txt */ #include <deque> #include <cassert> #include <map> #include <sstream> #include "hal.h" #include "halChain.h" #include "halBlockViz.h" using namespace std; using namespace hal; // We bend over backwards to cope with stone-age interface typedef pair<AlignmentConstPtr, const Genome*> OpenGenome; struct OGLess { bool operator()(const OpenGenome& og1, const OpenGenome& og2) { return og1.first.get() < og2.first.get() || ( og1.first.get() == og2.first.get() && og1.second < og2.second); } }; static map<string, AlignmentConstPtr> halPathMap; static map<int, OpenGenome> halHandleMap; static map<OpenGenome, int, OGLess> halHandleReverseMap; static block* readBlocks(BottomSegmentIteratorConstPtr bottom, hal_index_t childIndex, hal_index_t absEnd, int getSequenceString); static void readBlock(block* cur, BottomSegmentIteratorConstPtr bottom, TopSegmentIteratorConstPtr top, int getSequenceString, const string& genomeName, string& seqBuffer, string& dnaBuffer); extern "C" int halOpen(char *halFileName, char* qSpeciesName) { int handle = -1; try { // if path has been opened before, find the alignment AlignmentConstPtr alignment; map<string, AlignmentConstPtr>::iterator pmi = halPathMap.find(halFileName); if (pmi != halPathMap.end()) { alignment = pmi->second; } else { alignment = hdf5AlignmentInstanceReadOnly(); alignment->open(halFileName); halPathMap.insert(pair<string, AlignmentConstPtr>( qSpeciesName, alignment)); } const Genome* genome = alignment->openGenome(qSpeciesName); if (genome == NULL) { throw hal_exception(string(qSpeciesName) + " not found"); } OpenGenome og(alignment, genome); // if the path and genome have been open before, return the existing // handle map<OpenGenome, int, OGLess>::iterator hri = halHandleReverseMap.find(og); if (hri != halHandleReverseMap.end()) { handle = hri->second; } else { // create new handle and return it. updating both maps handle = 0; if (halHandleMap.empty() == false) { handle = halHandleMap.rbegin()->first + 1; } halHandleMap.insert(pair<int, OpenGenome>(handle, og)); halHandleReverseMap.insert(pair<OpenGenome, int>(og, handle)); } } catch(exception& e) { cerr << "Exception caught: " << e.what() << endl; handle = -1; } return handle; } extern "C" int halClose(int handle) { try { map<int, OpenGenome>::iterator hmi = halHandleMap.find(handle); if (hmi == halHandleMap.end()) { stringstream ss; ss << "error closing handle " << handle << ": not found"; throw hal_exception(ss.str()); } OpenGenome og(hmi->second.first, hmi->second.second); AlignmentConstPtr alignment = og.first; // remove from handle maps halHandleMap.erase(hmi); halHandleReverseMap.erase(halHandleReverseMap.find(og)); // close the genome alignment->closeGenome(og.second); bool last = true; for (hmi = halHandleMap.begin(); last && hmi != halHandleMap.end(); ++hmi) { AlignmentConstPtr alInMap = hmi->second.first; if (alInMap.get() == alignment.get()) { last = false; } } // this was the last reference to the alignment. so we close it if (last == true) { map<string, AlignmentConstPtr>::iterator hpi = halPathMap.begin(); for (; hpi != halPathMap.end(); ++hpi) { AlignmentConstPtr alInMap = hpi->second; if (alInMap.get() == alignment.get()) { alignment->close(); halPathMap.erase(hpi); break; } } } } catch(exception& e) { cerr << "Exception caught: " << e.what() << endl; return -1; } return 0; } extern "C" void halFreeBlocks(block* head) { while (head != NULL) { block* next = head->next; free(head->sequence); free(head->qChrom); free(head); head = next; } } extern "C" struct block *halGetBlocksInTargetRange(int halHandle, char* tChrom, int tStart, int tEnd, int getSequenceString) { try { map<int, OpenGenome>::iterator hmi = halHandleMap.find(halHandle); if (hmi == halHandleMap.end()) { stringstream ss; ss << "Handle " << halHandle << " not found"; throw hal_exception(ss.str()); } AlignmentConstPtr alignment = hmi->second.first; const Genome* genome = hmi->second.second; const Genome* parent = genome->getParent(); if (parent == NULL) { stringstream ss; ss << "Open genome " << genome->getName() << " is root in HAL tree" " and therefore has no reference and cannot be used to get blocks"; throw hal_exception(ss.str()); } const Sequence* sequence = parent->getSequence(tChrom); // cactus pipeline presently adds species name as prefix of // sequence name. check if this caused confusion string sequenceName; if (sequence == NULL) { sequenceName = parent->getName(); sequenceName += '.'; sequenceName += tChrom; sequence = parent->getSequence(sequenceName); } if (sequence == NULL || (hal_size_t)tStart >= sequence->getSequenceLength() || (hal_size_t)tEnd > sequence->getSequenceLength()) { stringstream ss; ss << "Unable to locate sequence " << tChrom << "(or " << sequenceName << ") in genome " << parent->getName(); throw hal_exception(ss.str()); } hal_index_t myEnd = tEnd > 0 ? tEnd : sequence->getSequenceLength(); hal_index_t absStart = sequence->getStartPosition() + tStart; hal_index_t absEnd = sequence->getStartPosition() + myEnd; hal_index_t childIndex = parent->getChildIndex(genome); if (absStart >= absEnd) { throw hal_exception("Invalid range"); } BottomSegmentIteratorConstPtr bottom = parent->getBottomSegmentIterator(childIndex); bottom->toSite(absStart, false); hal_offset_t startOffset = absStart - bottom->getStartPosition(); hal_offset_t endOffset = 0; if (absEnd <= bottom->getEndPosition()) { endOffset = bottom->getEndPosition() - absEnd + 1; } bottom->slice(startOffset, endOffset); assert(bottom->getStartPosition() == absStart); assert(bottom->getEndPosition() <= absEnd); if (bottom->getLength() == 0) { throw hal_exception("Error generating blocks. " "Invalid range specified?"); } block* head = readBlocks(bottom, childIndex, absEnd, getSequenceString); return head; } catch(exception& e) { cerr << "Exception caught: " << e.what() << endl; } return NULL; } block* readBlocks(BottomSegmentIteratorConstPtr bottom, hal_index_t childIndex, hal_index_t absEnd, int getSequenceString) { block* head = NULL; block* prev = NULL; TopSegmentIteratorConstPtr top = bottom->getGenome()->getChild(childIndex)->getTopSegmentIterator(); string genomeName = top->getGenome()->getName(); string seqBuffer, dnaBuffer; hal_index_t lastIndex = (hal_index_t)bottom->getGenome()->getNumBottomSegments(); cout << lastIndex << endl; while (bottom->getArrayIndex() < lastIndex && bottom->getStartPosition() < absEnd - 1) { if (bottom->hasChild(childIndex)) { block* cur = (block*)malloc(sizeof(block)); if (head == NULL) { head = cur; } else { prev->next = cur; } top->toChild(bottom, childIndex); readBlock(cur, bottom, top, getSequenceString, genomeName, seqBuffer, dnaBuffer); prev = cur; } bottom->toRight(absEnd - 1); } return head; } void readBlock(block* cur, BottomSegmentIteratorConstPtr bottom, TopSegmentIteratorConstPtr top, int getSequenceString, const string& genomeName, string& seqBuffer, string& dnaBuffer) { const Sequence* qSequence = top->getSequence(); const Sequence* tSequence = bottom->getSequence(); cur->next = NULL; seqBuffer = qSequence->getName(); size_t prefix = seqBuffer.find(genomeName + '.') != 0 ? 0 : genomeName.length() + 1; cur->qChrom = (char*)malloc(seqBuffer.length() + 1 - prefix); strcpy(cur->qChrom, seqBuffer.c_str() + prefix); cur->tStart = bottom->getStartPosition() - tSequence->getStartPosition(); cur->qStart = top->getStartPosition() - qSequence->getStartPosition(); assert(cur->tStart >= 0); assert(cur->qStart >= 0); if (top->getReversed() == true) { cur->qStart = qSequence->getSequenceLength() - cur->qStart; } cur->size = bottom->getLength(); cur->strand = top->getReversed() ? '-' : '+'; cur->sequence = NULL; if (getSequenceString != 0) { top->getString(dnaBuffer); cur->sequence = (char*)malloc(dnaBuffer.length() + 1); strcpy(cur->sequence, dnaBuffer.c_str()); } } <|endoftext|>
<commit_before><commit_msg>add option to set block_idx in write_array<commit_after><|endoftext|>
<commit_before>#include "pixmap.h" #include "lodepng/lodepng.h" #include "logger.h" #include "helper.inl" Pixmap::Pixmap(const std::string &a) { auto error = lodepng::decode(data, width, height, a); if(error) LOG(info) << "png error " << error << ": " << lodepng_error_text(error) << " for " << a; } Pixmap::Pixmap(glm::vec2 size) { width = (int) size.x; height = (int) size.y; data.resize((int)(size.x * size.y) * 4, 0); } Pixmap::~Pixmap() { } void Pixmap::Blit(const Pixmap &source, const glm::vec2 &pos) { assert(pos.x >= 0 && pos.y >= 0); if(width <= source.width + pos.x || height <= source.height + pos.y) { LOG(error) << "Blit error. Target image not enough large. " << string_format("(%g, %g) to (%g, %g) into (%d, %d)", pos.x, pos.y, source.width + pos.x, source.height + pos.y, width, height); throw std::out_of_range("target pixmap not enough large"); } for(unsigned i = 0; i < source.height; i++) memcpy(&data[(height * (i + (int) pos.y) + (int) pos.x)*4], &source.data[(source.height * i)*4], sizeof(unsigned char) * 4 * source.width); } <commit_msg>pixmap tinyfix<commit_after>#include "pixmap.h" #include "lodepng/lodepng.h" #include "logger.h" #include "helper.inl" Pixmap::Pixmap(const std::string &a) { auto error = lodepng::decode(data, width, height, a); if(error) LOG(info) << "png error " << error << ": " << lodepng_error_text(error) << " for " << a; } Pixmap::Pixmap(glm::vec2 size) { width = (int) size.x; height = (int) size.y; data.resize((int)(size.x * size.y) * 4, 0); } Pixmap::Pixmap() { } Pixmap::~Pixmap() { } void Pixmap::Blit(const Pixmap &source, const glm::vec2 &pos) { assert(pos.x >= 0 && pos.y >= 0); if(width <= source.width + pos.x || height <= source.height + pos.y) { LOG(error) << "Blit error. Target image not enough large. " << string_format("(%g, %g) to (%g, %g) into (%d, %d)", pos.x, pos.y, source.width + pos.x, source.height + pos.y, width, height); throw std::out_of_range("target pixmap not enough large"); } for(unsigned i = 0; i < source.height; i++) memcpy(&data[(height * (i + (int) pos.y) + (int) pos.x)*4], &source.data[(source.height * i)*4], sizeof(unsigned char) * 4 * source.width); } <|endoftext|>
<commit_before>#include <stdlib.h> #include <stdio.h> #include <string.h> #include <err.h> #include <errno.h> #include <linux/limits.h> #include <pwd.h> #include <fcntl.h> #include <unistd.h> #include <sched.h> #include <signal.h> #include <sys/mount.h> #include <sys/resource.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/epoll.h> #include <sys/signalfd.h> #include <sys/timerfd.h> #include <seccomp.h> static int epoll_fd; static const char *const username = "rust"; static const char *const memory_limit = "128M"; static const char *const root = "sandbox"; static const char *const hostname = "playpen"; static const int timeout = 5; static void write_to(const char *path, const char *string) { FILE *fp = fopen(path, "w"); if (!fp) { err(EXIT_FAILURE, "failed to open %s", path); } fputs(string, fp); fclose(fp); } static void init_cgroup() { if (mkdir("/sys/fs/cgroup/memory/playpen", 0755) < 0 && errno != EEXIST) { err(EXIT_FAILURE, "failed to create memory cgroup"); } write_to("/sys/fs/cgroup/memory/playpen/tasks", "0"); write_to("/sys/fs/cgroup/memory/playpen/memory.limit_in_bytes", memory_limit); if (mkdir("/sys/fs/cgroup/devices/playpen", 0755) < 0 && errno != EEXIST) { err(EXIT_FAILURE, "failed to create memory cgroup"); } write_to("/sys/fs/cgroup/devices/playpen/tasks", "0"); write_to("/sys/fs/cgroup/devices/playpen/devices.deny", "a"); write_to("/sys/fs/cgroup/devices/playpen/devices.allow", "c 1:9 rw"); // urandom } static void epoll_watch(int fd) { struct epoll_event event = { .data.fd = fd, .events = EPOLLIN | EPOLLET }; if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &event) < 0) err(1, "epoll_ctl"); } static void copy_pipe_to(int in_fd, int out_fd) { while (true) { ssize_t bytes_s = splice(in_fd, NULL, out_fd, NULL, BUFSIZ, SPLICE_F_MOVE | SPLICE_F_NONBLOCK); if (bytes_s < 0) { if (errno == EAGAIN) break; err(1, "splice"); } } } int main(int argc, char **argv) { if (argc < 2) { errx(1, "need at least one argument"); } epoll_fd = epoll_create1(EPOLL_CLOEXEC); if (epoll_fd < 0) { err(1, "epoll"); } sigset_t mask; sigemptyset(&mask); sigaddset(&mask, SIGCHLD); if (sigprocmask(SIG_BLOCK, &mask, NULL) < 0) { err(1, "sigprocmask"); } int sig_fd = signalfd(-1, &mask, SFD_CLOEXEC); if (sig_fd < 0) { err(1, "signalfd"); } epoll_watch(sig_fd); int timer_fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK|TFD_CLOEXEC); if (timer_fd < 0) err(EXIT_FAILURE, "timerfd_create"); epoll_watch(timer_fd); int pipe_out[2]; int pipe_err[2]; if (pipe(pipe_out) < 0) { err(1, "pipe"); } if (pipe(pipe_err) < 0) { err(1, "pipe"); } epoll_watch(pipe_out[0]); epoll_watch(pipe_err[0]); int pid = syscall(__NR_clone, SIGCHLD|CLONE_NEWIPC|CLONE_NEWNS|CLONE_NEWPID|CLONE_NEWUTS|CLONE_NEWNET, NULL); if (pid == 0) { close(0); dup2(pipe_out[1], 1); dup2(pipe_err[1], 2); close(pipe_out[0]); close(pipe_out[1]); close(pipe_err[0]); close(pipe_err[1]); init_cgroup(); if (sethostname(hostname, strlen(hostname)) < 0) { err(1, "sethostname"); } // avoid propagating mounts to the real root if (mount(NULL, "/", NULL, MS_SLAVE|MS_REC, NULL) < 0) { err(1, "mount /"); } // turn directory into a bind mount if (mount(root, root, "bind", MS_BIND|MS_REC, NULL) < 0) { err(1, "bind mount"); } // re-mount as read-only if (mount(root, root, "bind", MS_BIND|MS_REMOUNT|MS_RDONLY|MS_REC, NULL) < 0) { err(1, "remount bind mount"); } if (chroot(root) < 0) { err(1, "chroot"); } if (chdir("/") < 0) { err(1, "chdir"); } if (mount(NULL, "/proc", "proc", MS_NOSUID|MS_NOEXEC|MS_NODEV, NULL) < 0) { err(1, "mount /proc"); } if (mount(NULL, "/tmp", "tmpfs", MS_NOSUID|MS_NODEV, NULL) < 0) { err(1, "mount /tmp"); } struct passwd pw; size_t buffer_len = sysconf(_SC_GETPW_R_SIZE_MAX); char *buffer = (char *)malloc(buffer_len); if (!buffer) { err(1, NULL); } struct passwd *p_pw = &pw; getpwnam_r(username, &pw, buffer, buffer_len, &p_pw); if (!p_pw) { fprintf(stderr, "getpwnam_r failed to find requested entry.\n"); return 1; } if (pw.pw_dir) { if (mount(NULL, pw.pw_dir, "tmpfs", MS_NOSUID|MS_NODEV, NULL) < 0) { err(1, "mount %s", pw.pw_dir); } } // create a new session if (setsid() < 0) { err(1, "setsid"); } if (setgid(pw.pw_gid) < 0) { err(1, "setgid"); } if (setuid(pw.pw_uid) < 0) { err(1, "setuid"); } scmp_filter_ctx ctx = seccomp_init(SCMP_ACT_KILL); if (!ctx) { return 1; } auto check = [](int rc) { if (rc < 0) { errx(1, "%s", strerror(-rc)); } }; #define ALLOW(x) do { check(seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(x), 0)); } while (0) ALLOW(access); ALLOW(arch_prctl); ALLOW(brk); ALLOW(chdir); ALLOW(chmod); ALLOW(clone); ALLOW(close); ALLOW(dup); ALLOW(dup2); ALLOW(execve); ALLOW(exit); ALLOW(exit_group); ALLOW(faccessat); ALLOW(fadvise64); ALLOW(fcntl); ALLOW(fstat); ALLOW(futex); ALLOW(getcwd); ALLOW(getdents); ALLOW(getegid); ALLOW(geteuid); ALLOW(getgid); ALLOW(getpgrp); ALLOW(getpid); ALLOW(getppid); ALLOW(getrlimit); ALLOW(getrusage); ALLOW(getuid); ALLOW(ioctl); ALLOW(lseek); ALLOW(lstat); ALLOW(madvise); ALLOW(mmap); ALLOW(mprotect); ALLOW(mremap); ALLOW(munmap); ALLOW(nanosleep); ALLOW(open); ALLOW(openat); ALLOW(pipe); ALLOW(read); ALLOW(readlink); ALLOW(rt_sigaction); ALLOW(rt_sigprocmask); ALLOW(rt_sigreturn); ALLOW(setrlimit); ALLOW(set_robust_list); ALLOW(set_tid_address); ALLOW(stat); ALLOW(statfs); ALLOW(umask); ALLOW(uname); ALLOW(unlink); ALLOW(vfork); ALLOW(wait4); ALLOW(write); #undef ALLOW check(seccomp_load(ctx)); char path[] = "PATH=/usr/local/bin:/usr/bin:/bin"; char *env[] = {path, NULL}; if (execve(argv[1], argv + 1, env) < 0) { err(1, "execve"); } } else if (pid < 0) { err(1, "clone"); } close(pipe_out[1]); close(pipe_err[1]); struct epoll_event events[4]; struct itimerspec spec = { .it_value.tv_sec = timeout }; if (timerfd_settime(timer_fd, 0, &spec, NULL) < 0) err(EXIT_FAILURE, "timerfd_settime"); while (true) { int i, n = epoll_wait(epoll_fd, events, 4, -1); if (n < 0) { if (errno == EINTR) continue; err(1, "epoll_wait"); } for (i = 0; i < n; ++i) { struct epoll_event *evt = &events[i]; if (evt->events & EPOLLERR || evt->events & EPOLLHUP) { close(evt->data.fd); } else if (evt->data.fd == timer_fd) { fprintf(stderr, "timeout triggered!\n"); return 1; } else if (evt->data.fd == sig_fd) { struct signalfd_siginfo si; ssize_t bytes_r = read(sig_fd, &si, sizeof(si)); if (bytes_r < 0) { err(1, "read"); } else if (bytes_r != sizeof(si)) { fprintf(stderr, "read the wrong about of bytes\n"); return 1; } else if (si.ssi_signo != SIGCHLD) { fprintf(stderr, "got an unexpected signal\n"); return 1; } return si.ssi_status; } else if (evt->data.fd == pipe_out[0]) { copy_pipe_to(pipe_out[0], 1); } else if (evt->data.fd == pipe_err[0]) { copy_pipe_to(pipe_err[0], 2); } } } } <commit_msg>kill and remove the cgroups on exit<commit_after>#include <stdlib.h> #include <stdio.h> #include <string.h> #include <fstream> #include <err.h> #include <errno.h> #include <linux/limits.h> #include <pwd.h> #include <fcntl.h> #include <unistd.h> #include <sched.h> #include <signal.h> #include <sys/mount.h> #include <sys/resource.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/epoll.h> #include <sys/signalfd.h> #include <sys/timerfd.h> #include <seccomp.h> static int epoll_fd; static const char *const username = "rust"; static const char *const memory_limit = "128M"; static const char *const root = "sandbox"; static const char *const hostname = "playpen"; static const int timeout = 5; static void write_to(const char *path, const char *string) { FILE *fp = fopen(path, "w"); if (!fp) { err(EXIT_FAILURE, "failed to open %s", path); } fputs(string, fp); fclose(fp); } static void init_cgroup() { if (mkdir("/sys/fs/cgroup/memory/playpen", 0755) < 0 && errno != EEXIST) { err(EXIT_FAILURE, "failed to create memory cgroup"); } write_to("/sys/fs/cgroup/memory/playpen/tasks", "0"); write_to("/sys/fs/cgroup/memory/playpen/memory.limit_in_bytes", memory_limit); if (mkdir("/sys/fs/cgroup/devices/playpen", 0755) < 0 && errno != EEXIST) { err(EXIT_FAILURE, "failed to create memory cgroup"); } write_to("/sys/fs/cgroup/devices/playpen/tasks", "0"); write_to("/sys/fs/cgroup/devices/playpen/devices.deny", "a"); write_to("/sys/fs/cgroup/devices/playpen/devices.allow", "c 1:9 rw"); // urandom } static void epoll_watch(int fd) { struct epoll_event event = { .data.fd = fd, .events = EPOLLIN | EPOLLET }; if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &event) < 0) err(1, "epoll_ctl"); } static void copy_pipe_to(int in_fd, int out_fd) { while (true) { ssize_t bytes_s = splice(in_fd, NULL, out_fd, NULL, BUFSIZ, SPLICE_F_MOVE | SPLICE_F_NONBLOCK); if (bytes_s < 0) { if (errno == EAGAIN) break; err(1, "splice"); } } } static void kill_group() { bool done = false; do { std::ifstream procs("/sys/fs/cgroup/memory/playpen/cgroup.procs"); pid_t pid; done = true; while (procs >> pid) { kill(pid, SIGKILL); done = false; } } while (!done); if (rmdir("/sys/fs/cgroup/memory/playpen") < 0) { err(1, "rmdir"); } if (rmdir("/sys/fs/cgroup/devices/playpen") < 0) { err(1, "rmdir"); } } int main(int argc, char **argv) { if (argc < 2) { errx(1, "need at least one argument"); } atexit(kill_group); epoll_fd = epoll_create1(EPOLL_CLOEXEC); if (epoll_fd < 0) { err(1, "epoll"); } sigset_t mask; sigemptyset(&mask); sigaddset(&mask, SIGCHLD); if (sigprocmask(SIG_BLOCK, &mask, NULL) < 0) { err(1, "sigprocmask"); } int sig_fd = signalfd(-1, &mask, SFD_CLOEXEC); if (sig_fd < 0) { err(1, "signalfd"); } epoll_watch(sig_fd); int timer_fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK|TFD_CLOEXEC); if (timer_fd < 0) err(EXIT_FAILURE, "timerfd_create"); epoll_watch(timer_fd); int pipe_out[2]; int pipe_err[2]; if (pipe(pipe_out) < 0) { err(1, "pipe"); } if (pipe(pipe_err) < 0) { err(1, "pipe"); } epoll_watch(pipe_out[0]); epoll_watch(pipe_err[0]); int pid = syscall(__NR_clone, SIGCHLD|CLONE_NEWIPC|CLONE_NEWNS|CLONE_NEWPID|CLONE_NEWUTS|CLONE_NEWNET, NULL); if (pid == 0) { close(0); dup2(pipe_out[1], 1); dup2(pipe_err[1], 2); close(pipe_out[0]); close(pipe_out[1]); close(pipe_err[0]); close(pipe_err[1]); init_cgroup(); if (sethostname(hostname, strlen(hostname)) < 0) { err(1, "sethostname"); } // avoid propagating mounts to the real root if (mount(NULL, "/", NULL, MS_SLAVE|MS_REC, NULL) < 0) { err(1, "mount /"); } // turn directory into a bind mount if (mount(root, root, "bind", MS_BIND|MS_REC, NULL) < 0) { err(1, "bind mount"); } // re-mount as read-only if (mount(root, root, "bind", MS_BIND|MS_REMOUNT|MS_RDONLY|MS_REC, NULL) < 0) { err(1, "remount bind mount"); } if (chroot(root) < 0) { err(1, "chroot"); } if (chdir("/") < 0) { err(1, "chdir"); } if (mount(NULL, "/proc", "proc", MS_NOSUID|MS_NOEXEC|MS_NODEV, NULL) < 0) { err(1, "mount /proc"); } if (mount(NULL, "/tmp", "tmpfs", MS_NOSUID|MS_NODEV, NULL) < 0) { err(1, "mount /tmp"); } struct passwd pw; size_t buffer_len = sysconf(_SC_GETPW_R_SIZE_MAX); char *buffer = (char *)malloc(buffer_len); if (!buffer) { err(1, NULL); } struct passwd *p_pw = &pw; getpwnam_r(username, &pw, buffer, buffer_len, &p_pw); if (!p_pw) { fprintf(stderr, "getpwnam_r failed to find requested entry.\n"); return 1; } if (pw.pw_dir) { if (mount(NULL, pw.pw_dir, "tmpfs", MS_NOSUID|MS_NODEV, NULL) < 0) { err(1, "mount %s", pw.pw_dir); } } // create a new session if (setsid() < 0) { err(1, "setsid"); } if (setgid(pw.pw_gid) < 0) { err(1, "setgid"); } if (setuid(pw.pw_uid) < 0) { err(1, "setuid"); } scmp_filter_ctx ctx = seccomp_init(SCMP_ACT_KILL); if (!ctx) { return 1; } auto check = [](int rc) { if (rc < 0) { errx(1, "%s", strerror(-rc)); } }; #define ALLOW(x) do { check(seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(x), 0)); } while (0) ALLOW(access); ALLOW(arch_prctl); ALLOW(brk); ALLOW(chdir); ALLOW(chmod); ALLOW(clone); ALLOW(close); ALLOW(dup); ALLOW(dup2); ALLOW(execve); ALLOW(exit); ALLOW(exit_group); ALLOW(faccessat); ALLOW(fadvise64); ALLOW(fcntl); ALLOW(fstat); ALLOW(futex); ALLOW(getcwd); ALLOW(getdents); ALLOW(getegid); ALLOW(geteuid); ALLOW(getgid); ALLOW(getpgrp); ALLOW(getpid); ALLOW(getppid); ALLOW(getrlimit); ALLOW(getrusage); ALLOW(getuid); ALLOW(ioctl); ALLOW(lseek); ALLOW(lstat); ALLOW(madvise); ALLOW(mmap); ALLOW(mprotect); ALLOW(mremap); ALLOW(munmap); ALLOW(nanosleep); ALLOW(open); ALLOW(openat); ALLOW(pipe); ALLOW(read); ALLOW(readlink); ALLOW(rt_sigaction); ALLOW(rt_sigprocmask); ALLOW(rt_sigreturn); ALLOW(setrlimit); ALLOW(set_robust_list); ALLOW(set_tid_address); ALLOW(stat); ALLOW(statfs); ALLOW(umask); ALLOW(uname); ALLOW(unlink); ALLOW(vfork); ALLOW(wait4); ALLOW(write); #undef ALLOW check(seccomp_load(ctx)); char path[] = "PATH=/usr/local/bin:/usr/bin:/bin"; char *env[] = {path, NULL}; if (execve(argv[1], argv + 1, env) < 0) { err(1, "execve"); } } else if (pid < 0) { err(1, "clone"); } close(pipe_out[1]); close(pipe_err[1]); struct epoll_event events[4]; struct itimerspec spec = { .it_value.tv_sec = timeout }; if (timerfd_settime(timer_fd, 0, &spec, NULL) < 0) err(EXIT_FAILURE, "timerfd_settime"); while (true) { int i, n = epoll_wait(epoll_fd, events, 4, -1); if (n < 0) { if (errno == EINTR) continue; err(1, "epoll_wait"); } for (i = 0; i < n; ++i) { struct epoll_event *evt = &events[i]; if (evt->events & EPOLLERR || evt->events & EPOLLHUP) { close(evt->data.fd); } else if (evt->data.fd == timer_fd) { fprintf(stderr, "timeout triggered!\n"); return 1; } else if (evt->data.fd == sig_fd) { struct signalfd_siginfo si; ssize_t bytes_r = read(sig_fd, &si, sizeof(si)); if (bytes_r < 0) { err(1, "read"); } else if (bytes_r != sizeof(si)) { fprintf(stderr, "read the wrong about of bytes\n"); return 1; } else if (si.ssi_signo != SIGCHLD) { fprintf(stderr, "got an unexpected signal\n"); return 1; } return si.ssi_status; } else if (evt->data.fd == pipe_out[0]) { copy_pipe_to(pipe_out[0], 1); } else if (evt->data.fd == pipe_err[0]) { copy_pipe_to(pipe_err[0], 2); } } } } <|endoftext|>
<commit_before>#include <stdlib.h> #include <stdio.h> #include <string.h> #include <err.h> #include <errno.h> #include <linux/limits.h> #include <pwd.h> #include <fcntl.h> #include <unistd.h> #include <sched.h> #include <signal.h> #include <sys/mount.h> #include <sys/resource.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/epoll.h> #include <sys/signalfd.h> #include <sys/timerfd.h> #include <seccomp.h> static int epoll_fd; static const char *const username = "rust"; static const char *const memory_limit = "128M"; static const char *const root = "sandbox"; static const char *const hostname = "playpen"; static const int timeout = 5; static void write_to(const char *path, const char *string) { FILE *fp = fopen(path, "w"); if (!fp) { err(EXIT_FAILURE, "failed to open %s", path); } fputs(string, fp); fclose(fp); } static void init_cgroup() { if (mkdir("/sys/fs/cgroup/memory/playpen", 0755) < 0 && errno != EEXIST) { err(EXIT_FAILURE, "failed to create memory cgroup"); } write_to("/sys/fs/cgroup/memory/playpen/tasks", "0"); write_to("/sys/fs/cgroup/memory/playpen/memory.limit_in_bytes", memory_limit); if (mkdir("/sys/fs/cgroup/devices/playpen", 0755) < 0 && errno != EEXIST) { err(EXIT_FAILURE, "failed to create memory cgroup"); } write_to("/sys/fs/cgroup/devices/playpen/tasks", "0"); write_to("/sys/fs/cgroup/devices/playpen/devices.deny", "a"); write_to("/sys/fs/cgroup/devices/playpen/devices.allow", "c 1:9 rw"); // urandom } static void epoll_watch(int fd) { struct epoll_event event = { .data.fd = fd, .events = EPOLLIN | EPOLLET }; if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &event) < 0) err(1, "epoll_ctl"); } static void copy_pipe_to(int in_fd, int out_fd) { while (true) { ssize_t bytes_s = splice(in_fd, NULL, out_fd, NULL, BUFSIZ, SPLICE_F_MOVE | SPLICE_F_NONBLOCK); if (bytes_s < 0) { if (errno == EAGAIN) break; err(1, "splice"); } } } int main(int argc, char **argv) { if (argc < 2) { errx(1, "need at least one argument"); } epoll_fd = epoll_create1(EPOLL_CLOEXEC); if (epoll_fd < 0) { err(1, "epoll"); } sigset_t mask; sigemptyset(&mask); sigaddset(&mask, SIGCHLD); if (sigprocmask(SIG_BLOCK, &mask, NULL) < 0) { err(1, "sigprocmask"); } int sig_fd = signalfd(-1, &mask, SFD_CLOEXEC); if (sig_fd < 0) { err(1, "signalfd"); } epoll_watch(sig_fd); int timer_fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK|TFD_CLOEXEC); if (timer_fd < 0) err(EXIT_FAILURE, "timerfd_create"); epoll_watch(timer_fd); int pipe_out[2]; int pipe_err[2]; if (pipe(pipe_out) < 0) { err(1, "pipe"); } if (pipe(pipe_err) < 0) { err(1, "pipe"); } epoll_watch(pipe_out[0]); epoll_watch(pipe_err[0]); int pid = syscall(__NR_clone, SIGCHLD|CLONE_NEWIPC|CLONE_NEWNS|CLONE_NEWPID|CLONE_NEWUTS|CLONE_NEWNET, NULL); if (pid == 0) { close(0); dup2(pipe_out[1], 1); dup2(pipe_err[1], 2); close(pipe_out[0]); close(pipe_out[1]); close(pipe_err[0]); close(pipe_err[1]); init_cgroup(); if (sethostname(hostname, strlen(hostname)) < 0) { err(1, "sethostname"); } // avoid propagating mounts to the real root if (mount(NULL, "/", NULL, MS_SLAVE|MS_REC, NULL) < 0) { err(1, "mount"); } // turn directory into a bind mount if (mount(root, root, "bind", MS_BIND|MS_REC, NULL) < 0) { err(1, "mount"); } // re-mount as read-only if (mount(root, root, "bind", MS_BIND|MS_REMOUNT|MS_RDONLY|MS_REC, NULL) < 0) { err(1, "mount"); } if (chroot(root) < 0) { err(1, "chroot"); } if (chdir("/") < 0) { err(1, "chdir"); } if (mount(NULL, "/proc", "proc", MS_NOSUID|MS_NOEXEC|MS_NODEV, NULL) < 0) { err(1, "mount"); } if (mount(NULL, "/tmp", "tmpfs", MS_NOSUID|MS_NODEV, NULL) < 0) { err(1, "mount"); } struct passwd pw; size_t buffer_len = sysconf(_SC_GETPW_R_SIZE_MAX); char *buffer = (char *)malloc(buffer_len); if (!buffer) { err(1, NULL); } struct passwd *p_pw = &pw; getpwnam_r(username, &pw, buffer, buffer_len, &p_pw); if (!p_pw) { fprintf(stderr, "getpwnam_r failed to find requested entry.\n"); return 1; } if (pw.pw_dir) { if (mount(NULL, pw.pw_dir, "tmpfs", MS_NOSUID|MS_NODEV, NULL) < 0) { err(1, "mount"); } } // create a new session if (setsid() < 0) { err(1, "setsid"); } if (setgid(pw.pw_gid) < 0) { err(1, "setgid"); } if (setuid(pw.pw_uid) < 0) { err(1, "setuid"); } scmp_filter_ctx ctx = seccomp_init(SCMP_ACT_KILL); if (!ctx) { return 1; } auto check = [](int rc) { if (rc < 0) { errx(1, "%s", strerror(-rc)); } }; #define ALLOW(x) do { check(seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(x), 0)); } while (0) ALLOW(access); ALLOW(arch_prctl); ALLOW(brk); ALLOW(chdir); ALLOW(chmod); ALLOW(clone); ALLOW(close); ALLOW(dup); ALLOW(dup2); ALLOW(execve); ALLOW(exit); ALLOW(exit_group); ALLOW(faccessat); ALLOW(fadvise64); ALLOW(fcntl); ALLOW(fstat); ALLOW(futex); ALLOW(getcwd); ALLOW(getdents); ALLOW(getegid); ALLOW(geteuid); ALLOW(getgid); ALLOW(getpgrp); ALLOW(getpid); ALLOW(getppid); ALLOW(getrlimit); ALLOW(getrusage); ALLOW(getuid); ALLOW(ioctl); ALLOW(lseek); ALLOW(lstat); ALLOW(madvise); ALLOW(mmap); ALLOW(mprotect); ALLOW(mremap); ALLOW(munmap); ALLOW(nanosleep); ALLOW(open); ALLOW(openat); ALLOW(pipe); ALLOW(read); ALLOW(readlink); ALLOW(rt_sigaction); ALLOW(rt_sigprocmask); ALLOW(rt_sigreturn); ALLOW(setrlimit); ALLOW(set_robust_list); ALLOW(set_tid_address); ALLOW(stat); ALLOW(statfs); ALLOW(umask); ALLOW(uname); ALLOW(unlink); ALLOW(vfork); ALLOW(wait4); ALLOW(write); #undef ALLOW check(seccomp_load(ctx)); char path[] = "PATH=/usr/local/bin:/usr/bin:/bin"; char *env[] = {path, NULL}; if (execve(argv[1], argv + 1, env) < 0) { err(1, "execve"); } } else if (pid < 0) { err(1, "clone"); } close(pipe_out[1]); close(pipe_err[1]); struct epoll_event events[4]; struct itimerspec spec = { .it_value.tv_sec = timeout }; if (timerfd_settime(timer_fd, 0, &spec, NULL) < 0) err(EXIT_FAILURE, "timerfd_settime"); while (true) { int i, n = epoll_wait(epoll_fd, events, 4, -1); if (n < 0) { if (errno == EINTR) continue; err(1, "epoll_wait"); } for (i = 0; i < n; ++i) { struct epoll_event *evt = &events[i]; if (evt->events & EPOLLERR || evt->events & EPOLLHUP) { close(evt->data.fd); } else if (evt->data.fd == timer_fd) { fprintf(stderr, "timeout triggered!\n"); return 1; } else if (evt->data.fd == sig_fd) { struct signalfd_siginfo si; ssize_t bytes_r = read(sig_fd, &si, sizeof(si)); if (bytes_r < 0) { err(1, "read"); } else if (bytes_r != sizeof(si)) { fprintf(stderr, "read the wrong about of bytes\n"); return 1; } else if (si.ssi_signo != SIGCHLD) { fprintf(stderr, "got an unexpected signal\n"); return 1; } return si.ssi_status; } else if (evt->data.fd == pipe_out[0]) { copy_pipe_to(pipe_out[0], 1); } else if (evt->data.fd == pipe_err[0]) { copy_pipe_to(pipe_err[0], 2); } } } } <commit_msg>slightly friendlier error message for mounts<commit_after>#include <stdlib.h> #include <stdio.h> #include <string.h> #include <err.h> #include <errno.h> #include <linux/limits.h> #include <pwd.h> #include <fcntl.h> #include <unistd.h> #include <sched.h> #include <signal.h> #include <sys/mount.h> #include <sys/resource.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/epoll.h> #include <sys/signalfd.h> #include <sys/timerfd.h> #include <seccomp.h> static int epoll_fd; static const char *const username = "rust"; static const char *const memory_limit = "128M"; static const char *const root = "sandbox"; static const char *const hostname = "playpen"; static const int timeout = 5; static void write_to(const char *path, const char *string) { FILE *fp = fopen(path, "w"); if (!fp) { err(EXIT_FAILURE, "failed to open %s", path); } fputs(string, fp); fclose(fp); } static void init_cgroup() { if (mkdir("/sys/fs/cgroup/memory/playpen", 0755) < 0 && errno != EEXIST) { err(EXIT_FAILURE, "failed to create memory cgroup"); } write_to("/sys/fs/cgroup/memory/playpen/tasks", "0"); write_to("/sys/fs/cgroup/memory/playpen/memory.limit_in_bytes", memory_limit); if (mkdir("/sys/fs/cgroup/devices/playpen", 0755) < 0 && errno != EEXIST) { err(EXIT_FAILURE, "failed to create memory cgroup"); } write_to("/sys/fs/cgroup/devices/playpen/tasks", "0"); write_to("/sys/fs/cgroup/devices/playpen/devices.deny", "a"); write_to("/sys/fs/cgroup/devices/playpen/devices.allow", "c 1:9 rw"); // urandom } static void epoll_watch(int fd) { struct epoll_event event = { .data.fd = fd, .events = EPOLLIN | EPOLLET }; if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &event) < 0) err(1, "epoll_ctl"); } static void copy_pipe_to(int in_fd, int out_fd) { while (true) { ssize_t bytes_s = splice(in_fd, NULL, out_fd, NULL, BUFSIZ, SPLICE_F_MOVE | SPLICE_F_NONBLOCK); if (bytes_s < 0) { if (errno == EAGAIN) break; err(1, "splice"); } } } int main(int argc, char **argv) { if (argc < 2) { errx(1, "need at least one argument"); } epoll_fd = epoll_create1(EPOLL_CLOEXEC); if (epoll_fd < 0) { err(1, "epoll"); } sigset_t mask; sigemptyset(&mask); sigaddset(&mask, SIGCHLD); if (sigprocmask(SIG_BLOCK, &mask, NULL) < 0) { err(1, "sigprocmask"); } int sig_fd = signalfd(-1, &mask, SFD_CLOEXEC); if (sig_fd < 0) { err(1, "signalfd"); } epoll_watch(sig_fd); int timer_fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK|TFD_CLOEXEC); if (timer_fd < 0) err(EXIT_FAILURE, "timerfd_create"); epoll_watch(timer_fd); int pipe_out[2]; int pipe_err[2]; if (pipe(pipe_out) < 0) { err(1, "pipe"); } if (pipe(pipe_err) < 0) { err(1, "pipe"); } epoll_watch(pipe_out[0]); epoll_watch(pipe_err[0]); int pid = syscall(__NR_clone, SIGCHLD|CLONE_NEWIPC|CLONE_NEWNS|CLONE_NEWPID|CLONE_NEWUTS|CLONE_NEWNET, NULL); if (pid == 0) { close(0); dup2(pipe_out[1], 1); dup2(pipe_err[1], 2); close(pipe_out[0]); close(pipe_out[1]); close(pipe_err[0]); close(pipe_err[1]); init_cgroup(); if (sethostname(hostname, strlen(hostname)) < 0) { err(1, "sethostname"); } // avoid propagating mounts to the real root if (mount(NULL, "/", NULL, MS_SLAVE|MS_REC, NULL) < 0) { err(1, "mount /"); } // turn directory into a bind mount if (mount(root, root, "bind", MS_BIND|MS_REC, NULL) < 0) { err(1, "bind mount"); } // re-mount as read-only if (mount(root, root, "bind", MS_BIND|MS_REMOUNT|MS_RDONLY|MS_REC, NULL) < 0) { err(1, "remount bind mount"); } if (chroot(root) < 0) { err(1, "chroot"); } if (chdir("/") < 0) { err(1, "chdir"); } if (mount(NULL, "/proc", "proc", MS_NOSUID|MS_NOEXEC|MS_NODEV, NULL) < 0) { err(1, "mount /proc"); } if (mount(NULL, "/tmp", "tmpfs", MS_NOSUID|MS_NODEV, NULL) < 0) { err(1, "mount /tmp"); } struct passwd pw; size_t buffer_len = sysconf(_SC_GETPW_R_SIZE_MAX); char *buffer = (char *)malloc(buffer_len); if (!buffer) { err(1, NULL); } struct passwd *p_pw = &pw; getpwnam_r(username, &pw, buffer, buffer_len, &p_pw); if (!p_pw) { fprintf(stderr, "getpwnam_r failed to find requested entry.\n"); return 1; } if (pw.pw_dir) { if (mount(NULL, pw.pw_dir, "tmpfs", MS_NOSUID|MS_NODEV, NULL) < 0) { err(1, "mount %s", pw.pw_dir); } } // create a new session if (setsid() < 0) { err(1, "setsid"); } if (setgid(pw.pw_gid) < 0) { err(1, "setgid"); } if (setuid(pw.pw_uid) < 0) { err(1, "setuid"); } scmp_filter_ctx ctx = seccomp_init(SCMP_ACT_KILL); if (!ctx) { return 1; } auto check = [](int rc) { if (rc < 0) { errx(1, "%s", strerror(-rc)); } }; #define ALLOW(x) do { check(seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(x), 0)); } while (0) ALLOW(access); ALLOW(arch_prctl); ALLOW(brk); ALLOW(chdir); ALLOW(chmod); ALLOW(clone); ALLOW(close); ALLOW(dup); ALLOW(dup2); ALLOW(execve); ALLOW(exit); ALLOW(exit_group); ALLOW(faccessat); ALLOW(fadvise64); ALLOW(fcntl); ALLOW(fstat); ALLOW(futex); ALLOW(getcwd); ALLOW(getdents); ALLOW(getegid); ALLOW(geteuid); ALLOW(getgid); ALLOW(getpgrp); ALLOW(getpid); ALLOW(getppid); ALLOW(getrlimit); ALLOW(getrusage); ALLOW(getuid); ALLOW(ioctl); ALLOW(lseek); ALLOW(lstat); ALLOW(madvise); ALLOW(mmap); ALLOW(mprotect); ALLOW(mremap); ALLOW(munmap); ALLOW(nanosleep); ALLOW(open); ALLOW(openat); ALLOW(pipe); ALLOW(read); ALLOW(readlink); ALLOW(rt_sigaction); ALLOW(rt_sigprocmask); ALLOW(rt_sigreturn); ALLOW(setrlimit); ALLOW(set_robust_list); ALLOW(set_tid_address); ALLOW(stat); ALLOW(statfs); ALLOW(umask); ALLOW(uname); ALLOW(unlink); ALLOW(vfork); ALLOW(wait4); ALLOW(write); #undef ALLOW check(seccomp_load(ctx)); char path[] = "PATH=/usr/local/bin:/usr/bin:/bin"; char *env[] = {path, NULL}; if (execve(argv[1], argv + 1, env) < 0) { err(1, "execve"); } } else if (pid < 0) { err(1, "clone"); } close(pipe_out[1]); close(pipe_err[1]); struct epoll_event events[4]; struct itimerspec spec = { .it_value.tv_sec = timeout }; if (timerfd_settime(timer_fd, 0, &spec, NULL) < 0) err(EXIT_FAILURE, "timerfd_settime"); while (true) { int i, n = epoll_wait(epoll_fd, events, 4, -1); if (n < 0) { if (errno == EINTR) continue; err(1, "epoll_wait"); } for (i = 0; i < n; ++i) { struct epoll_event *evt = &events[i]; if (evt->events & EPOLLERR || evt->events & EPOLLHUP) { close(evt->data.fd); } else if (evt->data.fd == timer_fd) { fprintf(stderr, "timeout triggered!\n"); return 1; } else if (evt->data.fd == sig_fd) { struct signalfd_siginfo si; ssize_t bytes_r = read(sig_fd, &si, sizeof(si)); if (bytes_r < 0) { err(1, "read"); } else if (bytes_r != sizeof(si)) { fprintf(stderr, "read the wrong about of bytes\n"); return 1; } else if (si.ssi_signo != SIGCHLD) { fprintf(stderr, "got an unexpected signal\n"); return 1; } return si.ssi_status; } else if (evt->data.fd == pipe_out[0]) { copy_pipe_to(pipe_out[0], 1); } else if (evt->data.fd == pipe_err[0]) { copy_pipe_to(pipe_err[0], 2); } } } } <|endoftext|>
<commit_before>// Copyright 2014 Toggl Desktop developers. #include "./aboutdialog.h" #include "./ui_aboutdialog.h" #include <QDebug> // NOLINT #include <QDesktopServices> // NOLINT #include <QApplication> // NOLINT #include "./toggl.h" AboutDialog::AboutDialog(QWidget *parent) : QDialog(parent), ui(new Ui::AboutDialog) { ui->setupUi(this); ui->releaseChannel->addItem("stable"); ui->releaseChannel->addItem("beta"); ui->releaseChannel->addItem("dev"); ui->version->setText(QApplication::applicationVersion()); connect(TogglApi::instance, SIGNAL(displayUpdate(QString)), // NOLINT this, SLOT(displayUpdate(QString))); // NOLINT } AboutDialog::~AboutDialog() { delete ui; } void AboutDialog::displayUpdate(const QString update_url) { qDebug() << "displayUpdate update_url=" << update_url; url = update_url; QString channel = TogglApi::instance->updateChannel(); ui->releaseChannel->setCurrentText(channel); ui->releaseChannel->setEnabled(true); ui->updateButton->setEnabled(!update_url.isEmpty()); if (!url.isEmpty()) { ui->updateButton->setText( "Click here to download update!"); } else { ui->updateButton->setText("Toggl Desktop is up to date"); } } void AboutDialog::on_updateButton_clicked() { qDebug() << "on_updateButton_clicked url=" << url; QDesktopServices::openUrl(QUrl(url)); TogglApi::instance->shutdown = true; qApp->exit(0); } void AboutDialog::on_releaseChannel_activated(const QString &arg1) { qDebug() << "on_releaseChannel_activated channel=" << arg1; ui->updateButton->setEnabled(false); ui->updateButton->setText("Checking for update"); TogglApi::instance->setUpdateChannel(arg1); } <commit_msg>refactor a bit (linux)<commit_after>// Copyright 2014 Toggl Desktop developers. #include "./aboutdialog.h" #include "./ui_aboutdialog.h" #include <QDebug> // NOLINT #include <QDesktopServices> // NOLINT #include <QApplication> // NOLINT #include "./toggl.h" AboutDialog::AboutDialog(QWidget *parent) : QDialog(parent), ui(new Ui::AboutDialog) { ui->setupUi(this); ui->releaseChannel->addItem("stable"); ui->releaseChannel->addItem("beta"); ui->releaseChannel->addItem("dev"); ui->version->setText(QApplication::applicationVersion()); connect(TogglApi::instance, SIGNAL(displayUpdate(QString)), // NOLINT this, SLOT(displayUpdate(QString))); // NOLINT } AboutDialog::~AboutDialog() { delete ui; } void AboutDialog::displayUpdate(const QString update_url) { qDebug() << "displayUpdate update_url=" << update_url; url = update_url; QString channel = TogglApi::instance->updateChannel(); ui->releaseChannel->setCurrentText(channel); ui->releaseChannel->setEnabled(true); ui->updateButton->setEnabled(!url.isEmpty()); if (!url.isEmpty()) { ui->updateButton->setText( "Click here to download update!"); } else { ui->updateButton->setText("Toggl Desktop is up to date"); } } void AboutDialog::on_updateButton_clicked() { qDebug() << "on_updateButton_clicked url=" << url; QDesktopServices::openUrl(QUrl(url)); TogglApi::instance->shutdown = true; qApp->exit(0); } void AboutDialog::on_releaseChannel_activated(const QString &arg1) { qDebug() << "on_releaseChannel_activated channel=" << arg1; ui->updateButton->setEnabled(false); ui->updateButton->setText("Checking for update"); TogglApi::instance->setUpdateChannel(arg1); } <|endoftext|>
<commit_before>// Base header file. Must be first. #include <Include/PlatformDefinitions.hpp> #include <cassert> #if defined(XALAN_CLASSIC_IOSTREAMS) #include <iostream.h> #else #include <iostream> #endif #include <xercesc/util/PlatformUtils.hpp> #include <xercesc/framework/LocalFileInputSource.hpp> #include <XalanDOM/XalanDocument.hpp> #include <XalanDOM/XalanElement.hpp> #include <XPath/XObject.hpp> #include <XPath/XPathEvaluator.hpp> #include <XalanSourceTree/XalanSourceTreeDOMSupport.hpp> #include <XalanSourceTree/XalanSourceTreeInit.hpp> #include <XalanSourceTree/XalanSourceTreeParserLiaison.hpp> XALAN_USING_XALAN(XalanNode) XALAN_USING_XALAN(XalanElement) const XalanElement* getPrefixResolver(const XalanNode* node) { if (node == 0) { return 0; } else if (node->getNodeType() == XalanNode::ELEMENT_NODE) { return static_cast<const XalanElement*>(node); } else if (node->getNodeType() == XalanNode::DOCUMENT_NODE) { XALAN_USING_XALAN(XalanDocument) return static_cast<const XalanDocument*>(node)->getDocumentElement(); } else { return getPrefixResolver(node->getParentNode()); } } int main( int argc, const char* argv[]) { XALAN_USING_STD(cerr) XALAN_USING_STD(cout) XALAN_USING_STD(endl) int theResult = 0; if (argc != 4) { cerr << "Usage: SimpleXPathAPI XMLFilePath Context XPathExpression" << endl; theResult = -1; } else { try { XALAN_USING_XERCES(XMLPlatformUtils) XALAN_USING_XALAN(XPathEvaluator) XMLPlatformUtils::Initialize(); XPathEvaluator::initialize(); { XALAN_USING_XERCES(LocalFileInputSource) XALAN_USING_XALAN(XalanDocument) XALAN_USING_XALAN(XalanDOMString) XALAN_USING_XALAN(XalanNode) XALAN_USING_XALAN(XalanSourceTreeInit) XALAN_USING_XALAN(XalanSourceTreeDOMSupport) XALAN_USING_XALAN(XalanSourceTreeParserLiaison) XALAN_USING_XALAN(XObjectPtr) // Initialize the XalanSourceTree subsystem... XalanSourceTreeInit theSourceTreeInit; // We'll use these to parse the XML file. XalanSourceTreeDOMSupport theDOMSupport; XalanSourceTreeParserLiaison theLiaison(theDOMSupport); // Hook the two together... theDOMSupport.setParserLiaison(&theLiaison); const XalanDOMString theFileName(argv[1]); // Create an input source that represents a local file... const LocalFileInputSource theInputSource(theFileName.c_str()); // Parse the document... XalanDocument* const theDocument = theLiaison.parseXMLStream(theInputSource); assert(theDocument != 0); XPathEvaluator theEvaluator; // OK, let's find the context node... XalanNode* const theContextNode = theEvaluator.selectSingleNode( theDOMSupport, theDocument, XalanDOMString(argv[2]).c_str(), theDocument->getDocumentElement()); if (theContextNode == 0) { cerr << "Warning -- No nodes matched the location path \"" << argv[2] << "\"." << endl << "Execution cannot continue..." << endl << endl; } else { // OK, let's evaluate the expression... const XObjectPtr theResult( theEvaluator.evaluate( theDOMSupport, theContextNode, XalanDOMString(argv[3]).c_str(), getPrefixResolver(theContextNode))); assert(theResult.null() == false); cout << "The string value of the result is:" << endl << theResult->str() << endl << endl; } } XPathEvaluator::terminate(); XMLPlatformUtils::Terminate(); } catch(...) { cerr << "Exception caught!" << endl; theResult = -1; } } return theResult; } <commit_msg>Fixed casts for older compilers.<commit_after>// Base header file. Must be first. #include <Include/PlatformDefinitions.hpp> #include <cassert> #if defined(XALAN_CLASSIC_IOSTREAMS) #include <iostream.h> #else #include <iostream> #endif #include <xercesc/util/PlatformUtils.hpp> #include <xercesc/framework/LocalFileInputSource.hpp> #include <XalanDOM/XalanDocument.hpp> #include <XalanDOM/XalanElement.hpp> #include <XPath/XObject.hpp> #include <XPath/XPathEvaluator.hpp> #include <XalanSourceTree/XalanSourceTreeDOMSupport.hpp> #include <XalanSourceTree/XalanSourceTreeInit.hpp> #include <XalanSourceTree/XalanSourceTreeParserLiaison.hpp> XALAN_USING_XALAN(XalanNode) XALAN_USING_XALAN(XalanElement) const XalanElement* getPrefixResolver(const XalanNode* node) { if (node == 0) { return 0; } else if (node->getNodeType() == XalanNode::ELEMENT_NODE) { #if defined(XALAN_OLD_STYLE_CASTS) return (const XalanElement*)node; #else return static_cast<const XalanElement*>(node); #endif } else if (node->getNodeType() == XalanNode::DOCUMENT_NODE) { XALAN_USING_XALAN(XalanDocument) #if defined(XALAN_OLD_STYLE_CASTS) return ((const XalanDocument*)node)->getDocumentElement(); #else return static_cast<const XalanDocument*>(node)->getDocumentElement(); #endif } else { return getPrefixResolver(node->getParentNode()); } } int main( int argc, const char* argv[]) { XALAN_USING_STD(cerr) XALAN_USING_STD(cout) XALAN_USING_STD(endl) int theResult = 0; if (argc != 4) { cerr << "Usage: SimpleXPathAPI XMLFilePath Context XPathExpression" << endl; theResult = -1; } else { try { XALAN_USING_XERCES(XMLPlatformUtils) XALAN_USING_XALAN(XPathEvaluator) XMLPlatformUtils::Initialize(); XPathEvaluator::initialize(); { XALAN_USING_XERCES(LocalFileInputSource) XALAN_USING_XALAN(XalanDocument) XALAN_USING_XALAN(XalanDOMString) XALAN_USING_XALAN(XalanNode) XALAN_USING_XALAN(XalanSourceTreeInit) XALAN_USING_XALAN(XalanSourceTreeDOMSupport) XALAN_USING_XALAN(XalanSourceTreeParserLiaison) XALAN_USING_XALAN(XObjectPtr) // Initialize the XalanSourceTree subsystem... XalanSourceTreeInit theSourceTreeInit; // We'll use these to parse the XML file. XalanSourceTreeDOMSupport theDOMSupport; XalanSourceTreeParserLiaison theLiaison(theDOMSupport); // Hook the two together... theDOMSupport.setParserLiaison(&theLiaison); const XalanDOMString theFileName(argv[1]); // Create an input source that represents a local file... const LocalFileInputSource theInputSource(theFileName.c_str()); // Parse the document... XalanDocument* const theDocument = theLiaison.parseXMLStream(theInputSource); assert(theDocument != 0); XPathEvaluator theEvaluator; // OK, let's find the context node... XalanNode* const theContextNode = theEvaluator.selectSingleNode( theDOMSupport, theDocument, XalanDOMString(argv[2]).c_str(), theDocument->getDocumentElement()); if (theContextNode == 0) { cerr << "Warning -- No nodes matched the location path \"" << argv[2] << "\"." << endl << "Execution cannot continue..." << endl << endl; } else { // OK, let's evaluate the expression... const XObjectPtr theResult( theEvaluator.evaluate( theDOMSupport, theContextNode, XalanDOMString(argv[3]).c_str(), getPrefixResolver(theContextNode))); assert(theResult.null() == false); cout << "The string value of the result is:" << endl << theResult->str() << endl << endl; } } XPathEvaluator::terminate(); XMLPlatformUtils::Terminate(); } catch(...) { cerr << "Exception caught!" << endl; theResult = -1; } } return theResult; } <|endoftext|>
<commit_before>#ifndef __ARUCO_UNITY_DICTIONARY_HPP__ #define __ARUCO_UNITY_DICTIONARY_HPP__ #include <opencv2/aruco.hpp> #include "aruco_unity/exports.hpp" //! @defgroup dictionary Dictionary //! \brief Set of markers. //! //! See the OpenCV documentation for more information: http://docs.opencv.org/3.1.0/d5/d0b/classcv_1_1aruco_1_1Dictionary.html. //! @{ extern "C" { //! \name Constructors & Destructors //! @{ //! @brief Returns one of the predefined dictionaries defined in PREDEFINED_DICTIONARY_NAME. ARUCO_UNITY_API cv::Ptr<cv::aruco::Dictionary>* auGetPredefinedDictionary(cv::aruco::PREDEFINED_DICTIONARY_NAME name); //! \brief Deletes any Dictionary. //! \param parameters The Dictionary used. ARUCO_UNITY_API void auDeleteDictionary(cv::Ptr<cv::aruco::Dictionary>* dictionary); //! @} Constructors & Destructors //! \name Functions //! @{ //! \brief Draw a canonical marker image. //! \param parameters The Dictionary used. ARUCO_UNITY_API void auDictionaryDrawMarker(cv::Ptr<cv::aruco::Dictionary>* dictionary, int id, int sidePixels, cv::Mat* img, int borderBits); //! @} Functions //! \name Variables //! @{ //! \brief Returns the marker size. //! \param parameters The Dictionary used. ARUCO_UNITY_API int auGetDictionaryMarkerSize(cv::Ptr<cv::aruco::Dictionary>* dictionary); //! @} Variables } //! @} dictionary #endif<commit_msg>fix(dictionnary.hpp): fix the doc<commit_after>#ifndef __ARUCO_UNITY_DICTIONARY_HPP__ #define __ARUCO_UNITY_DICTIONARY_HPP__ #include <opencv2/aruco.hpp> #include "aruco_unity/exports.hpp" //! @defgroup dictionary Dictionary //! \brief Set of markers. //! //! See the OpenCV documentation for more information: http://docs.opencv.org/3.1.0/d5/d0b/classcv_1_1aruco_1_1Dictionary.html. //! @{ extern "C" { //! \name Constructors & Destructors //! @{ //! @brief Returns one of the predefined dictionaries defined in PREDEFINED_DICTIONARY_NAME. ARUCO_UNITY_API cv::Ptr<cv::aruco::Dictionary>* auGetPredefinedDictionary(cv::aruco::PREDEFINED_DICTIONARY_NAME name); //! \brief Deletes any Dictionary. //! \param dictionary The Dictionary used. ARUCO_UNITY_API void auDeleteDictionary(cv::Ptr<cv::aruco::Dictionary>* dictionary); //! @} Constructors & Destructors //! \name Functions //! @{ //! \brief Draw a canonical marker image. //! \param dictionary The Dictionary used. //! \param id The marker id. //! \param sidePixels The number of pixel per side of the marker. //! \param img The marker's pixels returned. //! \param borderBits The number of bits forming the marker border. ARUCO_UNITY_API void auDictionaryDrawMarker(cv::Ptr<cv::aruco::Dictionary>* dictionary, int id, int sidePixels, cv::Mat* img, int borderBits); //! @} Functions //! \name Variables //! @{ //! \brief Returns the marker size. //! \param dictionary The Dictionary used. ARUCO_UNITY_API int auGetDictionaryMarkerSize(cv::Ptr<cv::aruco::Dictionary>* dictionary); //! @} Variables } //! @} dictionary #endif<|endoftext|>
<commit_before>#pragma once #include <cstdint> #include <string> #include <type_traits> #include <vector> #include <zmq.h> #include "helpers.hpp" namespace boost { namespace asio { namespace zmq { namespace socket_option { std::size_t const max_buff_size = 255; template <int option, typename T> struct socket_option_impl { static int const id = option; typedef T option_value_type; socket_option_impl(option_value_type value) : value_(value) {} option_value_type value() const { return value_; } option_value_type& value() { return value_; } private: option_value_type value_; }; template <int option> struct socket_option_impl<option, void*> { static int const id = option; typedef void* option_value_type; socket_option_impl() {} socket_option_impl(void const* value, std::size_t size) : value_(static_cast<std::uint8_t const*>(value), static_cast<std::uint8_t const*>(value) + size) { } void const* value() const { return static_cast<void const*>(value_.data()); } void* value() { return static_cast<void*>(value_.data()); } std::size_t size() const { return value_.size(); } private: std::vector<std::uint8_t> value_; }; struct events : public socket_option_impl<ZMQ_EVENTS, int> { static int const default_value = -1; explicit events(int v = default_value) : socket_option_impl<ZMQ_EVENTS, int>(v) {} }; struct send_buff_hwm : public socket_option_impl<ZMQ_SNDHWM, int> { static int const default_value = 1000; explicit send_buff_hwm(int v = default_value) : socket_option_impl<ZMQ_SNDHWM, int>(v) {} }; struct recv_more : public socket_option_impl<ZMQ_RCVMORE, bool> { static bool const default_value = false; explicit recv_more(int v = default_value) : socket_option_impl<ZMQ_RCVMORE, bool>(v) {} }; struct identity : public socket_option_impl<ZMQ_IDENTITY, void*> { identity() {} identity(void const* value, std::size_t size) : socket_option_impl<ZMQ_IDENTITY, void*>(value, size) { } identity(const std::string& value) : socket_option_impl<ZMQ_IDENTITY, void*>(value.c_str(),value.size()) { } }; struct fd : public socket_option_impl<ZMQ_FD, native_handle_type> { static native_handle_type const default_value = -1; explicit fd(native_handle_type v = default_value) : socket_option_impl<ZMQ_FD, native_handle_type>(v) { } }; struct linger : public socket_option_impl<ZMQ_LINGER, int> { static int const default_value = -1; explicit linger(int v = default_value) : socket_option_impl<ZMQ_LINGER, int>(v) {} }; template <typename OptionType> struct is_binary_option : public std::is_base_of<socket_option_impl<OptionType::id, void*>, OptionType> { }; template <typename OptionType> struct enable_if_binary : public std::enable_if<is_binary_option<OptionType>::value> { }; template <typename OptionType> struct is_bool_option : public std::is_base_of<socket_option_impl<OptionType::id, bool>, OptionType> { }; template <typename OptionType> struct enable_if_bool : public std::enable_if<is_bool_option<OptionType>::value> { }; template <typename OptionType> struct is_raw_option : public std::integral_constant< bool, std::is_base_of< socket_option_impl<OptionType::id, typename OptionType::option_value_type>, OptionType>::value && !is_bool_option<OptionType>::value && !is_binary_option<OptionType>::value> { }; template <typename OptionType> struct enable_if_raw : public std::enable_if<is_raw_option<OptionType>::value> { }; } // namespace socket_option } // namespace zmq } // namespace asio } // namespace boost <commit_msg>Implemented the ZMQ_SUBSCRIBE option.<commit_after>#pragma once #include <cstdint> #include <string> #include <type_traits> #include <vector> #include <zmq.h> #include "helpers.hpp" namespace boost { namespace asio { namespace zmq { namespace socket_option { std::size_t const max_buff_size = 255; template <int option, typename T> struct socket_option_impl { static int const id = option; typedef T option_value_type; socket_option_impl(option_value_type value) : value_(value) {} option_value_type value() const { return value_; } option_value_type& value() { return value_; } private: option_value_type value_; }; template <int option> struct socket_option_impl<option, void*> { static int const id = option; typedef void* option_value_type; socket_option_impl() {} socket_option_impl(void const* value, std::size_t size) : value_(static_cast<std::uint8_t const*>(value), static_cast<std::uint8_t const*>(value) + size) { } void const* value() const { return static_cast<void const*>(value_.data()); } void* value() { return static_cast<void*>(value_.data()); } std::size_t size() const { return value_.size(); } private: std::vector<std::uint8_t> value_; }; struct events : public socket_option_impl<ZMQ_EVENTS, int> { static int const default_value = -1; explicit events(int v = default_value) : socket_option_impl<ZMQ_EVENTS, int>(v) {} }; struct send_buff_hwm : public socket_option_impl<ZMQ_SNDHWM, int> { static int const default_value = 1000; explicit send_buff_hwm(int v = default_value) : socket_option_impl<ZMQ_SNDHWM, int>(v) {} }; struct recv_more : public socket_option_impl<ZMQ_RCVMORE, bool> { static bool const default_value = false; explicit recv_more(int v = default_value) : socket_option_impl<ZMQ_RCVMORE, bool>(v) {} }; struct identity : public socket_option_impl<ZMQ_IDENTITY, void*> { identity() {} identity(void const* value, std::size_t size) : socket_option_impl<ZMQ_IDENTITY, void*>(value, size) { } identity(const std::string& value) : socket_option_impl<ZMQ_IDENTITY, void*>(value.c_str(),value.size()) { } }; struct subscribe : public socket_option_impl<ZMQ_SUBSCRIBE, void*> { subscribe() {} subscribe(void const* value, std::size_t size) : socket_option_impl<ZMQ_SUBSCRIBE, void*>(value, size) { } }; struct fd : public socket_option_impl<ZMQ_FD, native_handle_type> { static native_handle_type const default_value = -1; explicit fd(native_handle_type v = default_value) : socket_option_impl<ZMQ_FD, native_handle_type>(v) { } }; struct linger : public socket_option_impl<ZMQ_LINGER, int> { static int const default_value = -1; explicit linger(int v = default_value) : socket_option_impl<ZMQ_LINGER, int>(v) {} }; template <typename OptionType> struct is_binary_option : public std::is_base_of<socket_option_impl<OptionType::id, void*>, OptionType> { }; template <typename OptionType> struct enable_if_binary : public std::enable_if<is_binary_option<OptionType>::value> { }; template <typename OptionType> struct is_bool_option : public std::is_base_of<socket_option_impl<OptionType::id, bool>, OptionType> { }; template <typename OptionType> struct enable_if_bool : public std::enable_if<is_bool_option<OptionType>::value> { }; template <typename OptionType> struct is_raw_option : public std::integral_constant< bool, std::is_base_of< socket_option_impl<OptionType::id, typename OptionType::option_value_type>, OptionType>::value && !is_bool_option<OptionType>::value && !is_binary_option<OptionType>::value> { }; template <typename OptionType> struct enable_if_raw : public std::enable_if<is_raw_option<OptionType>::value> { }; } // namespace socket_option } // namespace zmq } // namespace asio } // namespace boost <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/defaults.h" namespace browser_defaults { #if defined(OS_CHROMEOS) const double kAutocompleteEditFontPixelSize = 12.0; const double kAutocompleteEditFontPixelSizeInPopup = 10; // This is only used by AutocompletePopupViewGtk which is unused // unless TOOLKIT_VIEWS is undefined: const int kAutocompletePopupFontSize = 7; const SessionStartupPref::Type kDefaultSessionStartupType = SessionStartupPref::LAST; const int kMiniTabWidth = 64; const bool kCanToggleSystemTitleBar = false; const bool kRestorePopups = true; const bool kShowImportOnBookmarkBar = false; const bool kShowExitMenuItem = true; const bool kShowAboutMenuItem = true; const bool kOSSupportsOtherBrowsers = false; const bool kDownloadPageHasShowInFolder = true; const bool kSizeTabButtonToTopOfTabStrip = true; const bool kBootstrapSyncAuthentication = true; const bool kShowOtherBrowsersInAboutMemory = false; const bool kAlwaysOpenIncognitoWindow = true; #elif defined(TOOLKIT_USES_GTK) // 13.4px = 10pt @ 96dpi. const double kAutocompleteEditFontPixelSize = 13.4; // On Windows, popup windows' autocomplete box have a font 5/6 the size of a // regular window, which we duplicate here for GTK. const double kAutocompleteEditFontPixelSizeInPopup = kAutocompleteEditFontPixelSize * 5.0 / 6.0; const int kAutocompletePopupFontSize = 10; #if defined(TOOLKIT_VIEWS) const bool kCanToggleSystemTitleBar = false; #else const bool kCanToggleSystemTitleBar = true; #endif #endif #if !defined(OS_CHROMEOS) const SessionStartupPref::Type kDefaultSessionStartupType = SessionStartupPref::DEFAULT; const int kMiniTabWidth = 56; const bool kRestorePopups = false; const bool kShowImportOnBookmarkBar = true; const bool kDownloadPageHasShowInFolder = true; #if defined(OS_MACOSX) const bool kShowExitMenuItem = false; const bool kShowAboutMenuItem = false; #else const bool kShowExitMenuItem = true; const bool kShowAboutMenuItem = true; #endif const bool kOSSupportsOtherBrowsers = true; const bool kSizeTabButtonToTopOfTabStrip = false; const bool kBootstrapSyncAuthentication = false; const bool kShowOtherBrowsersInAboutMemory = true; const bool kAlwaysOpenIncognitoWindow = false; #endif #if defined(OS_MACOSX) const bool kBrowserAliveWithNoWindows = true; #else const bool kBrowserAliveWithNoWindows = false; #endif const bool kPhantomTabsEnabled = false; bool bookmarks_enabled = true; } // namespace browser_defaults <commit_msg>chromeos: Increase omnibox font size.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/defaults.h" namespace browser_defaults { #if defined(OS_CHROMEOS) // Make the regular omnibox text two points larger than the nine-point font // used in the tab strip (11pt / 72pt/in * 96px/in = 14.667px). const double kAutocompleteEditFontPixelSize = 14.7; const double kAutocompleteEditFontPixelSizeInPopup = 10.0; // This is only used by AutocompletePopupViewGtk which is unused // unless TOOLKIT_VIEWS is undefined: const int kAutocompletePopupFontSize = 7; const SessionStartupPref::Type kDefaultSessionStartupType = SessionStartupPref::LAST; const int kMiniTabWidth = 64; const bool kCanToggleSystemTitleBar = false; const bool kRestorePopups = true; const bool kShowImportOnBookmarkBar = false; const bool kShowExitMenuItem = true; const bool kShowAboutMenuItem = true; const bool kOSSupportsOtherBrowsers = false; const bool kDownloadPageHasShowInFolder = true; const bool kSizeTabButtonToTopOfTabStrip = true; const bool kBootstrapSyncAuthentication = true; const bool kShowOtherBrowsersInAboutMemory = false; const bool kAlwaysOpenIncognitoWindow = true; #elif defined(TOOLKIT_USES_GTK) // 13.4px = 10pt @ 96dpi. const double kAutocompleteEditFontPixelSize = 13.4; // On Windows, popup windows' autocomplete box have a font 5/6 the size of a // regular window, which we duplicate here for GTK. const double kAutocompleteEditFontPixelSizeInPopup = kAutocompleteEditFontPixelSize * 5.0 / 6.0; const int kAutocompletePopupFontSize = 10; #if defined(TOOLKIT_VIEWS) const bool kCanToggleSystemTitleBar = false; #else const bool kCanToggleSystemTitleBar = true; #endif #endif #if !defined(OS_CHROMEOS) const SessionStartupPref::Type kDefaultSessionStartupType = SessionStartupPref::DEFAULT; const int kMiniTabWidth = 56; const bool kRestorePopups = false; const bool kShowImportOnBookmarkBar = true; const bool kDownloadPageHasShowInFolder = true; #if defined(OS_MACOSX) const bool kShowExitMenuItem = false; const bool kShowAboutMenuItem = false; #else const bool kShowExitMenuItem = true; const bool kShowAboutMenuItem = true; #endif const bool kOSSupportsOtherBrowsers = true; const bool kSizeTabButtonToTopOfTabStrip = false; const bool kBootstrapSyncAuthentication = false; const bool kShowOtherBrowsersInAboutMemory = true; const bool kAlwaysOpenIncognitoWindow = false; #endif #if defined(OS_MACOSX) const bool kBrowserAliveWithNoWindows = true; #else const bool kBrowserAliveWithNoWindows = false; #endif const bool kPhantomTabsEnabled = false; bool bookmarks_enabled = true; } // namespace browser_defaults <|endoftext|>
<commit_before>#ifndef FITNESS_GUARD_HPP_ #define FITNESS_GUARD_HPP_ #include "clotho/fitness/fitness_bitset.hpp" #endif // FITNESS_GUARD_HPP_ <commit_msg>Initial definition of fitness; Using boost libraries like bimap as an example of how to organize such functionality<commit_after>#ifndef FITNESS_GUARD_HPP_ #define FITNESS_GUARD_HPP_ //#include "clotho/fitness/fitness_bitset.hpp" // #include "clotho/fitness/detail/fitness_core.hpp" template < class Result, class Individual, class SelectionTag > class fitness : public clotho::fitness::detail::fitness_core< Result, Individual, SelectionTag >, public clotho::fitness::detail::fitness_core< Result, Individual, SelectionTag >::evaluation_type { public: typedef clotho::fitness::detail::fitness_core< Result, Individual, SelectionTag > core; typedef core::evaluation_type eval_type; typedef eval_type::hom_policy_type hom_policy_type; typedef eval_type::het_policy_type het_policy_type; fitness( const hom_policy_type & hom, const het_policy_type & het ) : eval_type( hom, het ) {} }; #endif // FITNESS_GUARD_HPP_ <|endoftext|>
<commit_before>#pragma once /* * Covariant Script Version Info * * Licensed under the Covariant Innovation General Public License, * Version 1.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://covariant.cn/licenses/LICENSE-1.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. * * Copyright (C) 2019 Michael Lee(李登淳) * Email: mikecovlee@163.com * Github: https://github.com/mikecovlee * * Version Format: * 1 . 0 . 0 [Version Code](Preview/Unstable/Stable) Build 1 * | | | | * | | Minor Status * | Major * Master * */ #define COVSCRIPT_VERSION_NUM 3,2,1,4 #define COVSCRIPT_VERSION_STR "3.2.1 Psephurus gladius(Unstable) Build 4" #define COVSCRIPT_STD_VERSION 190601 #define COVSCRIPT_API_VERSION 190621 #define COVSCRIPT_ABI_VERSION 190510 <commit_msg>Update version.hpp<commit_after>#pragma once /* * Covariant Script Version Info * * Licensed under the Covariant Innovation General Public License, * Version 1.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://covariant.cn/licenses/LICENSE-1.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. * * Copyright (C) 2019 Michael Lee(李登淳) * Email: mikecovlee@163.com * Github: https://github.com/mikecovlee * * Version Format: * 1 . 0 . 0 [Version Code](Preview/Unstable/Stable) Build 1 * | | | | * | | Minor Status * | Major * Master * */ #define COVSCRIPT_VERSION_NUM 3,2,1,5 #define COVSCRIPT_VERSION_STR "3.2.1 Psephurus gladius(Unstable) Build 5" #define COVSCRIPT_STD_VERSION 190501 #define COVSCRIPT_API_VERSION 190622 #define COVSCRIPT_ABI_VERSION 190510 <|endoftext|>
<commit_before>/** * \file * \brief RawCircularBuffer class header * * \author Copyright (C) 2016-2019 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef ESTD_RAWCIRCULARBUFFER_HPP_ #define ESTD_RAWCIRCULARBUFFER_HPP_ #include <utility> #include <cstddef> #include <cstdint> namespace estd { /** * \brief Thread-safe, lock-free raw circular buffer for single-producer and single-consumer * * Distinction between empty and full buffer is possible because most significant bits of read and write positions are * used as single-bit counters or wrap-arounds. This limits the size of buffer to SIZE_MAX / 2, but allows full * utilization of storage (no free slot is needed). */ class RawCircularBuffer { public: /** * \brief RawCircularBuffer's constructor * * \param [in] buffer is a buffer for data * \param [in] size is the size of \a buffer, bytes, must be less than or equal to SIZE_MAX / 2 */ constexpr RawCircularBuffer(void* const buffer, const size_t size) : buffer_{static_cast<uint8_t*>(buffer)}, size_{size & sizeMask_}, readPosition_{}, writePosition_{} { } /** * \brief RawCircularBuffer's constructor, read-only variant * * \param [in] buffer is a read-only buffer with data * \param [in] size is the size of \a buffer, bytes, must be less than or equal to SIZE_MAX / 2 */ constexpr RawCircularBuffer(const void* const buffer, const size_t size) : buffer_{static_cast<uint8_t*>(const_cast<void*>(buffer))}, size_{(size & sizeMask_) | readOnlyMask_}, readPosition_{}, writePosition_{} { } /** * \brief Clears raw circular buffer */ void clear() { readPosition_ = {}; writePosition_ = {}; } /** * \return total capacity of raw circular buffer, bytes */ size_t getCapacity() const { return size_ & sizeMask_; } /** * \return first contiguous block (as a pair with pointer and size) available for reading */ std::pair<const void*, size_t> getReadBlock() const { const auto readPosition = readPosition_ ; const auto writePosition = writePosition_; if (isEmpty(readPosition, writePosition) == true) return {{}, {}}; return getBlock(readPosition, writePosition); } /** * \return total amount of valid data in raw circular buffer, bytes */ size_t getSize() const { const auto readPosition = readPosition_ ; const auto writePosition = writePosition_; if (isEmpty(readPosition, writePosition) == true) return 0; const auto capacity = getCapacity(); if (isFull(readPosition, writePosition) == true) return capacity; return (capacity - (readPosition & positionMask_) + (writePosition & positionMask_)) % capacity; } /** * \return first contiguous block (as a pair with pointer and size) available for writing */ std::pair<void*, size_t> getWriteBlock() const { if (isReadOnly() == true) return {{}, {}}; const auto readPosition = readPosition_ ; const auto writePosition = writePosition_; if (isFull(readPosition, writePosition) == true) return {{}, {}}; return getBlock(writePosition, readPosition); } /** * \brief Increases read position by given value. * * \param [in] value is the value which will be added to read position, must be less than or equal to the value from * last call to getReadBlock() */ void increaseReadPosition(const size_t value) { readPosition_ = increasePosition(readPosition_, value); } /** * \brief Increases write position by given value. * * \param [in] value is the value which will be added to write position, must be less than or equal to the value * from last call to getWriteBlock() */ void increaseWritePosition(const size_t value) { writePosition_ = increasePosition(writePosition_, value); } /** * \return true if raw circular buffer is empty, false otherwise */ bool isEmpty() const { return isEmpty(readPosition_, writePosition_); } /** * \return true if raw circular buffer is full, false otherwise */ bool isFull() const { return isFull(readPosition_, writePosition_); } /** * \return true if raw circular buffer is read-only, false otherwise */ bool isReadOnly() const { return (size_ & readOnlyMask_) != 0; } private: /** * \brief Gets first contiguous block between \a position1 and \a position2. * * This function does not treat empty or full buffer in any special way. * * \param [in] begin is the beginning position * \param [in] end is the ending position * * \return first contiguous block (as a pair with pointer and size) starting at \a begin and not crossing \a end or * end of buffer */ std::pair<void*, size_t> getBlock(const size_t begin, const size_t end) const { const auto maskedBegin = begin & positionMask_; const auto maskedEnd = end & positionMask_; return {buffer_ + maskedBegin, (maskedEnd > maskedBegin ? maskedEnd : getCapacity()) - maskedBegin}; } /** * \brief Increases given position by given value. * * \param [in] position is the position that will be incremented * \param [in] value is the value which will be added to \a position, must come from previous call to * getReadBlock() / getWriteBlock() * * \return \a position incremented by \a value */ size_t increasePosition(const size_t position, const size_t value) { const auto maskedPosition = position & positionMask_; const auto msb = position & msbMask_; // in case of wrap-around MSB is inverted and position is 0 return maskedPosition + value != getCapacity() ? msb | (maskedPosition + value) : msb ^ msbMask_; } /** * \brief Tests for empty raw circular buffer. * * The buffer is empty if read and write positions are equal, including their MSBs. * * \param [in] readPosition is the value of \a readPosition_ * \param [in] writePosition is the value of \a writePosition_ * * \return true if raw circular buffer is empty, false otherwise */ constexpr static bool isEmpty(const size_t readPosition, const size_t writePosition) { return readPosition == writePosition; } /** * \brief Tests for full raw circular buffer. * * The buffer is full if masked read and write positions are equal, but their MSBs are different. * * \param [in] readPosition is the value of \a readPosition_ * \param [in] writePosition is the value of \a writePosition_ * * \return true if raw circular buffer is full, false otherwise */ constexpr static bool isFull(const size_t readPosition, const size_t writePosition) { return (readPosition ^ writePosition) == msbMask_; } /// bitmask used to extract position from \a readPosition_ or \a writePosition_ constexpr static size_t positionMask_ {SIZE_MAX >> 1}; /// bitmask used to extract MSB from \a readPosition_ or \a writePosition_ constexpr static size_t msbMask_ {~positionMask_}; /// bitmask used to extract size from \a size_ constexpr static size_t sizeMask_ {SIZE_MAX >> 1}; /// bitmask used to extract "read-only" flag from \a size_ constexpr static size_t readOnlyMask_ {~sizeMask_}; /// pointer to beginning of buffer uint8_t* buffer_; /// size of \a buffer_, bytes size_t size_; /// current read position volatile size_t readPosition_; /// current write position volatile size_t writePosition_; }; } // namespace estd #endif // ESTD_RAWCIRCULARBUFFER_HPP_ <commit_msg>Fix some minor errors in comments for RawCircularBuffer<commit_after>/** * \file * \brief RawCircularBuffer class header * * \author Copyright (C) 2016-2019 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef ESTD_RAWCIRCULARBUFFER_HPP_ #define ESTD_RAWCIRCULARBUFFER_HPP_ #include <utility> #include <cstddef> #include <cstdint> namespace estd { /** * \brief Thread-safe, lock-free raw circular buffer for single-producer and single-consumer * * Distinction between empty and full buffer is possible because most significant bits of read and write positions are * used as single-bit counters of wrap-arounds. This limits the size of buffer to SIZE_MAX / 2, but allows full * utilization of storage (no free slot is needed). */ class RawCircularBuffer { public: /** * \brief RawCircularBuffer's constructor * * \param [in] buffer is a buffer for data * \param [in] size is the size of \a buffer, bytes, must be less than or equal to SIZE_MAX / 2 */ constexpr RawCircularBuffer(void* const buffer, const size_t size) : buffer_{static_cast<uint8_t*>(buffer)}, size_{size & sizeMask_}, readPosition_{}, writePosition_{} { } /** * \brief RawCircularBuffer's constructor, read-only variant * * \param [in] buffer is a read-only buffer with data * \param [in] size is the size of \a buffer, bytes, must be less than or equal to SIZE_MAX / 2 */ constexpr RawCircularBuffer(const void* const buffer, const size_t size) : buffer_{static_cast<uint8_t*>(const_cast<void*>(buffer))}, size_{(size & sizeMask_) | readOnlyMask_}, readPosition_{}, writePosition_{} { } /** * \brief Clears raw circular buffer */ void clear() { readPosition_ = {}; writePosition_ = {}; } /** * \return total capacity of raw circular buffer, bytes */ size_t getCapacity() const { return size_ & sizeMask_; } /** * \return first contiguous block (as a pair with pointer and size) available for reading */ std::pair<const void*, size_t> getReadBlock() const { const auto readPosition = readPosition_ ; const auto writePosition = writePosition_; if (isEmpty(readPosition, writePosition) == true) return {{}, {}}; return getBlock(readPosition, writePosition); } /** * \return total amount of valid data in raw circular buffer, bytes */ size_t getSize() const { const auto readPosition = readPosition_ ; const auto writePosition = writePosition_; if (isEmpty(readPosition, writePosition) == true) return 0; const auto capacity = getCapacity(); if (isFull(readPosition, writePosition) == true) return capacity; return (capacity - (readPosition & positionMask_) + (writePosition & positionMask_)) % capacity; } /** * \return first contiguous block (as a pair with pointer and size) available for writing */ std::pair<void*, size_t> getWriteBlock() const { if (isReadOnly() == true) return {{}, {}}; const auto readPosition = readPosition_ ; const auto writePosition = writePosition_; if (isFull(readPosition, writePosition) == true) return {{}, {}}; return getBlock(writePosition, readPosition); } /** * \brief Increases read position by given value. * * \param [in] value is the value which will be added to read position, must be less than or equal to the value from * last call to getReadBlock() */ void increaseReadPosition(const size_t value) { readPosition_ = increasePosition(readPosition_, value); } /** * \brief Increases write position by given value. * * \param [in] value is the value which will be added to write position, must be less than or equal to the value * from last call to getWriteBlock() */ void increaseWritePosition(const size_t value) { writePosition_ = increasePosition(writePosition_, value); } /** * \return true if raw circular buffer is empty, false otherwise */ bool isEmpty() const { return isEmpty(readPosition_, writePosition_); } /** * \return true if raw circular buffer is full, false otherwise */ bool isFull() const { return isFull(readPosition_, writePosition_); } /** * \return true if raw circular buffer is read-only, false otherwise */ bool isReadOnly() const { return (size_ & readOnlyMask_) != 0; } private: /** * \brief Gets first contiguous block between \a position1 and \a position2. * * This function does not treat empty or full buffer in any special way. * * \param [in] begin is the beginning position * \param [in] end is the ending position * * \return first contiguous block (as a pair with pointer and size) starting at \a begin and not crossing \a end or * end of buffer */ std::pair<void*, size_t> getBlock(const size_t begin, const size_t end) const { const auto maskedBegin = begin & positionMask_; const auto maskedEnd = end & positionMask_; return {buffer_ + maskedBegin, (maskedEnd > maskedBegin ? maskedEnd : getCapacity()) - maskedBegin}; } /** * \brief Increases given position by given value. * * \param [in] position is the position that will be incremented * \param [in] value is the value which will be added to \a position, must be less than or equal to the value from * last call to getReadBlock() / getWriteBlock() * * \return \a position incremented by \a value */ size_t increasePosition(const size_t position, const size_t value) { const auto maskedPosition = position & positionMask_; const auto msb = position & msbMask_; // in case of wrap-around MSB is inverted and position is 0 return maskedPosition + value != getCapacity() ? msb | (maskedPosition + value) : msb ^ msbMask_; } /** * \brief Tests for empty raw circular buffer. * * The buffer is empty if read and write positions are equal, including their MSBs. * * \param [in] readPosition is the value of \a readPosition_ * \param [in] writePosition is the value of \a writePosition_ * * \return true if raw circular buffer is empty, false otherwise */ constexpr static bool isEmpty(const size_t readPosition, const size_t writePosition) { return readPosition == writePosition; } /** * \brief Tests for full raw circular buffer. * * The buffer is full if masked read and write positions are equal, but their MSBs are different. * * \param [in] readPosition is the value of \a readPosition_ * \param [in] writePosition is the value of \a writePosition_ * * \return true if raw circular buffer is full, false otherwise */ constexpr static bool isFull(const size_t readPosition, const size_t writePosition) { return (readPosition ^ writePosition) == msbMask_; } /// bitmask used to extract position from \a readPosition_ or \a writePosition_ constexpr static size_t positionMask_ {SIZE_MAX >> 1}; /// bitmask used to extract MSB from \a readPosition_ or \a writePosition_ constexpr static size_t msbMask_ {~positionMask_}; /// bitmask used to extract size from \a size_ constexpr static size_t sizeMask_ {SIZE_MAX >> 1}; /// bitmask used to extract "read-only" flag from \a size_ constexpr static size_t readOnlyMask_ {~sizeMask_}; /// pointer to beginning of buffer uint8_t* buffer_; /// size of \a buffer_, bytes size_t size_; /// current read position volatile size_t readPosition_; /// current write position volatile size_t writePosition_; }; } // namespace estd #endif // ESTD_RAWCIRCULARBUFFER_HPP_ <|endoftext|>
<commit_before>/* /% C %/ */ /*********************************************************************** * cint (C/C++ interpreter) ************************************************************************ * Source file bc_debug.cxx ************************************************************************ * Description: * debugging features ************************************************************************ * Copyright(c) 2004~2004 Masaharu Goto * * For the licensing terms see the file COPYING * ************************************************************************/ #include "bc_debug.h" /*********************************************************************** * G__bc_funccall ***********************************************************************/ //////////////////////////////////////////////////////////////// struct G__input_file G__bc_funccall::getifile() const { struct G__input_file ifile; ifile.str = 0; // ifile.pos = 0; ifile.vindex = 0; if(!m_bytecode) { ifile=G__ifile; } else { struct G__ifunc_table_internal *ifunc = m_bytecode->ifunc; int ifn = m_bytecode->ifn; ifile.filenum = ifunc->pentry[ifn]->filenum; ifile.fp = G__srcfile[ifile.filenum].fp; ifile.line_number = m_line_number; strcpy(ifile.name,G__srcfile[ifile.filenum].filename); } return(ifile); } //////////////////////////////////////////////////////////////// int G__bc_funccall::setstackenv(struct G__view* pview) const { // todo, need some review pview->file = getifile(); if(!m_bytecode) { pview->var_local = G__p_local; pview->struct_offset = G__store_struct_offset; pview->tagnum = G__tagnum; pview->exec_memberfunc = G__exec_memberfunc; pview->localmem = 0; return(0); } else { struct G__ifunc_table_internal *ifunc = m_bytecode->ifunc; //int ifn = m_bytecode->ifn; pview->var_local = m_bytecode->var; pview->struct_offset = m_struct_offset; pview->tagnum = ifunc->tagnum; pview->exec_memberfunc=(-1!=ifunc->tagnum)?1:0; pview->localmem = m_localmem; return(1); } } //////////////////////////////////////////////////////////////// int G__bc_funccall::disp(FILE* fout) const { // todo, need some review if(!m_bytecode) return(0); G__FastAllocString msg(G__LONGLINE); struct G__ifunc_table_internal *ifunc = m_bytecode->ifunc; int ifn = m_bytecode->ifn; int tagnum=ifunc->tagnum; int filenum = ifunc->pentry[ifn]->filenum; struct G__param* libp=m_libp; // class name if member function if(-1!=tagnum) { msg.Format("%s::",G__struct.name[tagnum]); if(G__more(fout,msg())) return(1); } // function name msg.Format("%s(",ifunc->funcname[ifn]); if(G__more(fout,msg())) return(1); // function parameter for(int temp1=0;temp1<libp->paran;temp1++) { if(temp1) { msg = ","; if(G__more(fout,msg())) return(1); } G__valuemonitor(libp->para[temp1],msg); if(G__more(fout,msg())) return(1); } if(-1!=filenum) { msg.Format(") [%s:%d]\n" ,G__stripfilename(G__srcfile[filenum].filename) ,m_line_number); if(G__more(fout,msg())) return(1); } else { if(G__more(fout,") [entry]\n")) return(1); } return(0); } /*********************************************************************** * G__bc_funccallstack ***********************************************************************/ //////////////////////////////////////////////////////////////// G__bc_funccallstack::G__bc_funccallstack() { //m_funccallstack.push_front(G__bc_funccall()); } //////////////////////////////////////////////////////////////// G__bc_funccallstack::~G__bc_funccallstack() { // do nothing } //////////////////////////////////////////////////////////////// G__bc_funccall& G__bc_funccallstack::getStackPosition(int i) { if(0==m_funccallstack.size()) return(m_staticenv); if(i<0 || i>=(int)m_funccallstack.size()) { // error, stack isn't that deep G__fprinterr(G__serr,"!!!Function call stack isn't that deep!!!\n"); return(m_staticenv); } return(m_funccallstack[i]); } //////////////////////////////////////////////////////////////// int G__bc_funccallstack::setstackenv(int i,struct G__view* pview) { return(getStackPosition(i).setstackenv(pview)); } //////////////////////////////////////////////////////////////// int G__bc_funccallstack::disp(FILE* fout) const { //deque<G__bc_funccall>::iterator i; G__FastAllocString msg(100); for(int i=0;i<(int)m_funccallstack.size();++i) { msg.Format("%d ",i); if(G__more(fout,msg())) return(1); if(m_funccallstack[i].disp(fout)) return(1); } return(0); } //////////////////////////////////////////////////////////////// /*********************************************************************** * static objects ***********************************************************************/ G__bc_funccallstack G__bc_funccallstack_obj; /*********************************************************************** * C function wrappers ***********************************************************************/ //////////////////////////////////////////////////////////////// extern "C" int G__bc_setdebugview(int i,struct G__view* pview) { return(G__bc_funccallstack_obj.setstackenv(i,pview)); } //////////////////////////////////////////////////////////////// extern "C" int G__bc_showstack(FILE* fout) { return(G__bc_funccallstack_obj.disp(fout)); } //////////////////////////////////////////////////////////////// extern "C" void G__bc_setlinenum(int line) { G__bc_funccallstack_obj.setlinenum(line); } <commit_msg>Missing member initialization (G__ifile's pos); strcpy (Coverity)<commit_after>/* /% C %/ */ /*********************************************************************** * cint (C/C++ interpreter) ************************************************************************ * Source file bc_debug.cxx ************************************************************************ * Description: * debugging features ************************************************************************ * Copyright(c) 2004~2004 Masaharu Goto * * For the licensing terms see the file COPYING * ************************************************************************/ #include "bc_debug.h" /*********************************************************************** * G__bc_funccall ***********************************************************************/ //////////////////////////////////////////////////////////////// struct G__input_file G__bc_funccall::getifile() const { struct G__input_file ifile; ifile.str = 0; ifile.pos = 0; ifile.vindex = 0; if(!m_bytecode) { ifile=G__ifile; } else { struct G__ifunc_table_internal *ifunc = m_bytecode->ifunc; int ifn = m_bytecode->ifn; ifile.filenum = ifunc->pentry[ifn]->filenum; ifile.fp = G__srcfile[ifile.filenum].fp; ifile.line_number = m_line_number; strncpy(ifile.name,G__srcfile[ifile.filenum].filename, sizeof(ifile.name) - 1); } return(ifile); } //////////////////////////////////////////////////////////////// int G__bc_funccall::setstackenv(struct G__view* pview) const { // todo, need some review pview->file = getifile(); if(!m_bytecode) { pview->var_local = G__p_local; pview->struct_offset = G__store_struct_offset; pview->tagnum = G__tagnum; pview->exec_memberfunc = G__exec_memberfunc; pview->localmem = 0; return(0); } else { struct G__ifunc_table_internal *ifunc = m_bytecode->ifunc; //int ifn = m_bytecode->ifn; pview->var_local = m_bytecode->var; pview->struct_offset = m_struct_offset; pview->tagnum = ifunc->tagnum; pview->exec_memberfunc=(-1!=ifunc->tagnum)?1:0; pview->localmem = m_localmem; return(1); } } //////////////////////////////////////////////////////////////// int G__bc_funccall::disp(FILE* fout) const { // todo, need some review if(!m_bytecode) return(0); G__FastAllocString msg(G__LONGLINE); struct G__ifunc_table_internal *ifunc = m_bytecode->ifunc; int ifn = m_bytecode->ifn; int tagnum=ifunc->tagnum; int filenum = ifunc->pentry[ifn]->filenum; struct G__param* libp=m_libp; // class name if member function if(-1!=tagnum) { msg.Format("%s::",G__struct.name[tagnum]); if(G__more(fout,msg())) return(1); } // function name msg.Format("%s(",ifunc->funcname[ifn]); if(G__more(fout,msg())) return(1); // function parameter for(int temp1=0;temp1<libp->paran;temp1++) { if(temp1) { msg = ","; if(G__more(fout,msg())) return(1); } G__valuemonitor(libp->para[temp1],msg); if(G__more(fout,msg())) return(1); } if(-1!=filenum) { msg.Format(") [%s:%d]\n" ,G__stripfilename(G__srcfile[filenum].filename) ,m_line_number); if(G__more(fout,msg())) return(1); } else { if(G__more(fout,") [entry]\n")) return(1); } return(0); } /*********************************************************************** * G__bc_funccallstack ***********************************************************************/ //////////////////////////////////////////////////////////////// G__bc_funccallstack::G__bc_funccallstack() { //m_funccallstack.push_front(G__bc_funccall()); } //////////////////////////////////////////////////////////////// G__bc_funccallstack::~G__bc_funccallstack() { // do nothing } //////////////////////////////////////////////////////////////// G__bc_funccall& G__bc_funccallstack::getStackPosition(int i) { if(0==m_funccallstack.size()) return(m_staticenv); if(i<0 || i>=(int)m_funccallstack.size()) { // error, stack isn't that deep G__fprinterr(G__serr,"!!!Function call stack isn't that deep!!!\n"); return(m_staticenv); } return(m_funccallstack[i]); } //////////////////////////////////////////////////////////////// int G__bc_funccallstack::setstackenv(int i,struct G__view* pview) { return(getStackPosition(i).setstackenv(pview)); } //////////////////////////////////////////////////////////////// int G__bc_funccallstack::disp(FILE* fout) const { //deque<G__bc_funccall>::iterator i; G__FastAllocString msg(100); for(int i=0;i<(int)m_funccallstack.size();++i) { msg.Format("%d ",i); if(G__more(fout,msg())) return(1); if(m_funccallstack[i].disp(fout)) return(1); } return(0); } //////////////////////////////////////////////////////////////// /*********************************************************************** * static objects ***********************************************************************/ G__bc_funccallstack G__bc_funccallstack_obj; /*********************************************************************** * C function wrappers ***********************************************************************/ //////////////////////////////////////////////////////////////// extern "C" int G__bc_setdebugview(int i,struct G__view* pview) { return(G__bc_funccallstack_obj.setstackenv(i,pview)); } //////////////////////////////////////////////////////////////// extern "C" int G__bc_showstack(FILE* fout) { return(G__bc_funccallstack_obj.disp(fout)); } //////////////////////////////////////////////////////////////// extern "C" void G__bc_setlinenum(int line) { G__bc_funccallstack_obj.setlinenum(line); } <|endoftext|>
<commit_before>/* Copyright (c) 2012, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_STRING_UTIL_HPP_INCLUDED #define TORRENT_STRING_UTIL_HPP_INCLUDED #include "libtorrent/config.hpp" namespace libtorrent { TORRENT_EXTRA_EXPORT bool is_alpha(char c); TORRENT_EXTRA_EXPORT bool is_digit(char c); TORRENT_EXTRA_EXPORT bool is_print(char c); TORRENT_EXTRA_EXPORT bool is_space(char c); TORRENT_EXTRA_EXPORT char to_lower(char c); TORRENT_EXTRA_EXPORT int split_string(char const** tags, int buf_size, char* in); TORRENT_EXTRA_EXPORT bool string_begins_no_case(char const* s1, char const* s2); TORRENT_EXTRA_EXPORT bool string_equal_no_case(char const* s1, char const* s2); TORRENT_EXTRA_EXPORT void url_random(char* begin, char* end); // strdup is not part of the C standard. Some systems // don't have it and it won't be available when building // in strict ansi mode char* allocate_string_copy(char const* str); // returns p + x such that the pointer is 8 bytes aligned // x cannot be greater than 7 void* align_pointer(void* p); } #endif <commit_msg>fix python binding build with shared linking<commit_after>/* Copyright (c) 2012, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_STRING_UTIL_HPP_INCLUDED #define TORRENT_STRING_UTIL_HPP_INCLUDED #include "libtorrent/config.hpp" namespace libtorrent { TORRENT_EXTRA_EXPORT bool is_alpha(char c); // this is used by bdecode_recursive's header file TORRENT_EXPORT bool is_digit(char c); TORRENT_EXTRA_EXPORT bool is_print(char c); TORRENT_EXTRA_EXPORT bool is_space(char c); TORRENT_EXTRA_EXPORT char to_lower(char c); TORRENT_EXTRA_EXPORT int split_string(char const** tags, int buf_size, char* in); TORRENT_EXTRA_EXPORT bool string_begins_no_case(char const* s1, char const* s2); TORRENT_EXTRA_EXPORT bool string_equal_no_case(char const* s1, char const* s2); TORRENT_EXTRA_EXPORT void url_random(char* begin, char* end); // strdup is not part of the C standard. Some systems // don't have it and it won't be available when building // in strict ansi mode char* allocate_string_copy(char const* str); // returns p + x such that the pointer is 8 bytes aligned // x cannot be greater than 7 void* align_pointer(void* p); } #endif <|endoftext|>
<commit_before>#include <argtable3/argtable3.h> #include <sstream> #include <babylon/babylon_version.h> #include <babylon/core/delegates/delegate.h> #include <babylon/core/logging.h> #include <babylon/core/string.h> #include <babylon/samples/sample_launcher.h> #include <babylon/samples/samples_index.h> #if _MSC_VER #include <windows.h> #endif struct ConsoleLogger { using log_message_t = SA::delegate<void(const BABYLON::LogMessage&)>; static void onLogMessage(const BABYLON::LogMessage& logMessage) { printf("%s\n", logMessage.toString().c_str()); #if _MSC_VER OutputDebugString(logMessage.toString().c_str()); #endif } static log_message_t logListenerDelegate; }; // end of struct ConsoleLogger ConsoleLogger::log_message_t ConsoleLogger::logListenerDelegate = SA::delegate<void( const BABYLON::LogMessage&)>::create<&ConsoleLogger::onLogMessage>(); /** * @brief Initializes the logging. */ void initializeLogging() { static_assert( std::is_same<SA::delegate<void(const BABYLON::LogMessage&)>, decltype(ConsoleLogger::logListenerDelegate)>::value, "!"); // Intialize log levels std::vector<std::pair<unsigned int, std::string>> _logLevels; for (auto& logLevel : BABYLON::LogLevels::Levels) { unsigned int logType = logLevel.first; if ((logType != BABYLON::LogLevels::LEVEL_QUIET) && (logType != BABYLON::LogLevels::LEVEL_TRACE)) { _logLevels.emplace_back(logLevel); } } // Subscribe to channels for (auto& logLevel : _logLevels) { unsigned int logType = logLevel.first; if (logType != BABYLON::LogLevels::LEVEL_QUIET) { BABYLON::Logger::Instance().registerLogMessageListener( logType, ConsoleLogger::logListenerDelegate); } } } /** * @brief Runs a sample with the specified name * @param samples list with available samples * @param sampleName name of the sample to run * @param showInspectorWindow whether or not to shoz the inspector window * @return exit code */ int runSample(const BABYLON::Samples::SamplesIndex& samples, const std::string& sampleName, bool showInspectorWindow, long runTimeMillis = 0) { using namespace BABYLON::Samples; int exitcode = 0; // Create the sample launcher SampleLauncherOptions options; options.showInspectorWindow = showInspectorWindow; SampleLauncher sampleLauncher{options}; if (sampleLauncher.intialize()) { // Create the renderable scene auto canvas = sampleLauncher.getRenderCanvas(); auto scene = samples.createRenderableScene(sampleName, canvas); sampleLauncher.setRenderableScene(scene); // Run the example exitcode = sampleLauncher.run(runTimeMillis); } return exitcode; } /** * @brief The sample launcher. * @param l list samples if l > 0 * @param v enable verbose mode if v > 0 * @param sample name of the sample to run * @return exit code */ int sampleLauncherMain(int l, int v, int i, const char* sampleGroup, const char* sample) { using namespace BABYLON::Samples; SamplesIndex samples; int exitcode = 0; if (l > 0) { std::ostringstream oss; // Get sample names and category names auto sampleNames = samples.getSampleNames(); auto categoryNames = samples.getCategoryNames(); oss << "Found " << sampleNames.size() << " in " << categoryNames.size() << " categories:\n"; // Print categorized samples for (const auto& categoryName : categoryNames) { sampleNames = samples.getSampleNamesInCategory(categoryName); oss << " |- "; if (sampleNames.size() < 10) { oss << " " << sampleNames.size(); } else if (sampleNames.size() < 100) { oss << sampleNames.size(); } oss << " sample(s) in category \"" << categoryName.c_str() << "\"\n"; for (const auto& sampleName : sampleNames) { oss << " |- " << sampleName.c_str() << "\n"; } } printf("%s", oss.str().c_str()); } else { if (v > 0) { // Enable console logging initializeLogging(); } // Check for rendering of sample group const std::string categoryName{sampleGroup}; if (!categoryName.empty() && (samples.categoryExists(categoryName) || categoryName == "All")) { std::vector<std::string> categoryNames; if (categoryName == "All") { categoryNames = samples.getCategoryNames(); } else { categoryNames = {categoryName}; } for (const auto& _categoryName : categoryNames) { const auto sampleNames = samples.getSampleNamesInCategory(_categoryName); for (const auto& sampleName : sampleNames) { exitcode = runSample(samples, sampleName, i > 0, 10000); if (exitcode == 0) { break; } } } } else { // Check for rendering of sample const std::string sampleName{sample}; if (!samples.sampleExists(sampleName)) { printf("Sample with name \"%s\" does not exists.\n", sample); return 1; } if (!samples.isSampleEnabled(sampleName)) { printf("Sample with name \"%s\" is not enabled.\n", sample); return 1; } // Run the sample exitcode = runSample(samples, sampleName, i > 0); } } return exitcode; } int main(int argc, char** argv) { /** Program arguments definition **/ struct arg_lit* list = arg_lit0("lL", NULL, "list samples"); struct arg_str* sample = arg_str0( "S", "sample", "<SAMPE>", "sample to launch (default is \"BasicScene\")"); struct arg_str* sampleGroup = arg_str0( "G", "sample-group", "<SAMPE-GROUP>", "sample group to launch (sample-group \"All\" contains all samples)"); struct arg_lit* verbose = arg_lit0("v", "verbose,debug", "verbose messages"); struct arg_lit* inspector = arg_lit0("i", "inspector", "show inspector window"); struct arg_lit* help = arg_lit0(NULL, "help", "print this help and exit"); struct arg_lit* version = arg_lit0(NULL, "version", "print version information and exit"); struct arg_end* end = arg_end(20); void* argtable[] = {list, sample, sampleGroup, verbose, inspector, help, version, end}; const char* progname = "SampleLauncher"; int nerrors; int exitcode = 0; /** Verify the argtable[] entries were allocated sucessfully **/ if (arg_nullcheck(argtable) != 0) { /** NULL entries were detected, some allocations must have failed **/ printf("%s: insufficient memory\n", progname); exitcode = 1; arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0])); return exitcode; } /** Set the default sample values prior to parsing **/ sample->sval[0] = "BasicScene"; /** Set the default sample group prior to parsing */ sampleGroup->sval[0] = ""; /** Parse the command line as defined by argtable[] **/ nerrors = arg_parse(argc, argv, argtable); /** Special case: '--help' takes precedence over error reporting **/ if (help->count > 0) { printf("Usage: %s", progname); arg_print_syntax(stdout, argtable, "\n"); printf( "This program acts as a sample launcher for demonstrating the usage of " "the BabylonCpp library\n"); arg_print_glossary(stdout, argtable, " %-35s %s\n"); exitcode = 0; arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0])); return exitcode; } /** Special case: '--version' takes precedence error reporting **/ if (version->count > 0) { printf("%s\n", BABYLONCPP_NAME_VERSION); exitcode = 0; arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0])); return exitcode; } /** If the parser returned any errors then display them and exit **/ if (nerrors > 0) { /** Display the error details contained in the arg_end struct. **/ arg_print_errors(stdout, end, progname); printf("Try '%s --help' for more information.\n", progname); exitcode = 1; arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0])); return exitcode; } /** Normal case: run sample **/ exitcode = sampleLauncherMain(list->count, verbose->count, inspector->count, sampleGroup->sval[0], sample->sval[0]); /** Deallocate each non-null entry in argtable[] **/ arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0])); return exitcode; } <commit_msg>main.cpp: ChdirToExePath under windows<commit_after>#include <argtable3/argtable3.h> #include <filesystem> #include <sstream> #include <babylon/babylon_version.h> #include <babylon/core/delegates/delegate.h> #include <babylon/core/logging.h> #include <babylon/core/string.h> #include <babylon/samples/sample_launcher.h> #include <babylon/samples/samples_index.h> #if _MSC_VER #include <windows.h> #include <direct.h> #endif struct ConsoleLogger { using log_message_t = SA::delegate<void(const BABYLON::LogMessage&)>; static void onLogMessage(const BABYLON::LogMessage& logMessage) { printf("%s\n", logMessage.toString().c_str()); #if _MSC_VER OutputDebugString(logMessage.toString().c_str()); #endif } static log_message_t logListenerDelegate; }; // end of struct ConsoleLogger ConsoleLogger::log_message_t ConsoleLogger::logListenerDelegate = SA::delegate<void( const BABYLON::LogMessage&)>::create<&ConsoleLogger::onLogMessage>(); /** * @brief Initializes the logging. */ void initializeLogging() { static_assert( std::is_same<SA::delegate<void(const BABYLON::LogMessage&)>, decltype(ConsoleLogger::logListenerDelegate)>::value, "!"); // Intialize log levels std::vector<std::pair<unsigned int, std::string>> _logLevels; for (auto& logLevel : BABYLON::LogLevels::Levels) { unsigned int logType = logLevel.first; if ((logType != BABYLON::LogLevels::LEVEL_QUIET) && (logType != BABYLON::LogLevels::LEVEL_TRACE)) { _logLevels.emplace_back(logLevel); } } // Subscribe to channels for (auto& logLevel : _logLevels) { unsigned int logType = logLevel.first; if (logType != BABYLON::LogLevels::LEVEL_QUIET) { BABYLON::Logger::Instance().registerLogMessageListener( logType, ConsoleLogger::logListenerDelegate); } } } /** * @brief Runs a sample with the specified name * @param samples list with available samples * @param sampleName name of the sample to run * @param showInspectorWindow whether or not to shoz the inspector window * @return exit code */ int runSample(const BABYLON::Samples::SamplesIndex& samples, const std::string& sampleName, bool showInspectorWindow, long runTimeMillis = 0) { using namespace BABYLON::Samples; int exitcode = 0; // Create the sample launcher SampleLauncherOptions options; options.showInspectorWindow = showInspectorWindow; SampleLauncher sampleLauncher{options}; if (sampleLauncher.intialize()) { // Create the renderable scene auto canvas = sampleLauncher.getRenderCanvas(); auto scene = samples.createRenderableScene(sampleName, canvas); sampleLauncher.setRenderableScene(scene); // Run the example exitcode = sampleLauncher.run(runTimeMillis); } return exitcode; } /** * @brief The sample launcher. * @param l list samples if l > 0 * @param v enable verbose mode if v > 0 * @param sample name of the sample to run * @return exit code */ int sampleLauncherMain(int l, int v, int i, const char* sampleGroup, const char* sample) { using namespace BABYLON::Samples; SamplesIndex samples; int exitcode = 0; if (l > 0) { std::ostringstream oss; // Get sample names and category names auto sampleNames = samples.getSampleNames(); auto categoryNames = samples.getCategoryNames(); oss << "Found " << sampleNames.size() << " in " << categoryNames.size() << " categories:\n"; // Print categorized samples for (const auto& categoryName : categoryNames) { sampleNames = samples.getSampleNamesInCategory(categoryName); oss << " |- "; if (sampleNames.size() < 10) { oss << " " << sampleNames.size(); } else if (sampleNames.size() < 100) { oss << sampleNames.size(); } oss << " sample(s) in category \"" << categoryName.c_str() << "\"\n"; for (const auto& sampleName : sampleNames) { oss << " |- " << sampleName.c_str() << "\n"; } } printf("%s", oss.str().c_str()); } else { if (v > 0) { // Enable console logging initializeLogging(); } // Check for rendering of sample group const std::string categoryName{sampleGroup}; if (!categoryName.empty() && (samples.categoryExists(categoryName) || categoryName == "All")) { std::vector<std::string> categoryNames; if (categoryName == "All") { categoryNames = samples.getCategoryNames(); } else { categoryNames = {categoryName}; } for (const auto& _categoryName : categoryNames) { const auto sampleNames = samples.getSampleNamesInCategory(_categoryName); for (const auto& sampleName : sampleNames) { exitcode = runSample(samples, sampleName, i > 0, 10000); if (exitcode == 0) { break; } } } } else { // Check for rendering of sample const std::string sampleName{sample}; if (!samples.sampleExists(sampleName)) { printf("Sample with name \"%s\" does not exists.\n", sample); return 1; } if (!samples.isSampleEnabled(sampleName)) { printf("Sample with name \"%s\" is not enabled.\n", sample); return 1; } // Run the sample exitcode = runSample(samples, sampleName, i > 0); } } return exitcode; } void ChdirToExePath(char *argv0) { std::filesystem::path exeFolder = std::filesystem::weakly_canonical(std::filesystem::path(argv0)).parent_path(); #ifdef _WIN32 _chdir(exeFolder.string().c_str()); #else chdir(exeFolder.string().c_str()); #endif } int main(int argc, char** argv) { #ifdef _MSC_VER ChdirToExePath(argv[0]); #endif /** Program arguments definition **/ struct arg_lit* list = arg_lit0("lL", NULL, "list samples"); struct arg_str* sample = arg_str0( "S", "sample", "<SAMPE>", "sample to launch (default is \"BasicScene\")"); struct arg_str* sampleGroup = arg_str0( "G", "sample-group", "<SAMPE-GROUP>", "sample group to launch (sample-group \"All\" contains all samples)"); struct arg_lit* verbose = arg_lit0("v", "verbose,debug", "verbose messages"); struct arg_lit* inspector = arg_lit0("i", "inspector", "show inspector window"); struct arg_lit* help = arg_lit0(NULL, "help", "print this help and exit"); struct arg_lit* version = arg_lit0(NULL, "version", "print version information and exit"); struct arg_end* end = arg_end(20); void* argtable[] = {list, sample, sampleGroup, verbose, inspector, help, version, end}; const char* progname = "SampleLauncher"; int nerrors; int exitcode = 0; /** Verify the argtable[] entries were allocated sucessfully **/ if (arg_nullcheck(argtable) != 0) { /** NULL entries were detected, some allocations must have failed **/ printf("%s: insufficient memory\n", progname); exitcode = 1; arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0])); return exitcode; } /** Set the default sample values prior to parsing **/ sample->sval[0] = "BasicScene"; /** Set the default sample group prior to parsing */ sampleGroup->sval[0] = ""; /** Parse the command line as defined by argtable[] **/ nerrors = arg_parse(argc, argv, argtable); /** Special case: '--help' takes precedence over error reporting **/ if (help->count > 0) { printf("Usage: %s", progname); arg_print_syntax(stdout, argtable, "\n"); printf( "This program acts as a sample launcher for demonstrating the usage of " "the BabylonCpp library\n"); arg_print_glossary(stdout, argtable, " %-35s %s\n"); exitcode = 0; arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0])); return exitcode; } /** Special case: '--version' takes precedence error reporting **/ if (version->count > 0) { printf("%s\n", BABYLONCPP_NAME_VERSION); exitcode = 0; arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0])); return exitcode; } /** If the parser returned any errors then display them and exit **/ if (nerrors > 0) { /** Display the error details contained in the arg_end struct. **/ arg_print_errors(stdout, end, progname); printf("Try '%s --help' for more information.\n", progname); exitcode = 1; arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0])); return exitcode; } /** Normal case: run sample **/ exitcode = sampleLauncherMain(list->count, verbose->count, inspector->count, sampleGroup->sval[0], sample->sval[0]); /** Deallocate each non-null entry in argtable[] **/ arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0])); return exitcode; } <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #include "FunctionSubstring.hpp" #include <PlatformSupport/DoubleSupport.hpp> #include "XObjectFactory.hpp" const XObjectPtr FunctionSubstring::s_nullXObjectPtr; FunctionSubstring::FunctionSubstring() { } FunctionSubstring::~FunctionSubstring() { } /* * Get the value for the start index (C-style, not XPath). */ inline XalanDOMString::size_type getStartIndex( double theSecondArgValue, XalanDOMString::size_type theStringLength) { // We always subtract 1 for C-style index, since XPath indexes from 1. // Anything less than, or equal to 1 is 0. if (theSecondArgValue <= 1 || DoubleSupport::isNaN(theSecondArgValue) == true) { return 0; } else if (DoubleSupport::isPositiveInfinity(theSecondArgValue) == true) { return theStringLength; } else { return XalanDOMString::size_type(DoubleSupport::round(theSecondArgValue)) - 1; } } /* * Get the length of the substring. */ inline XalanDOMString::size_type getSubstringLength( XalanDOMString::size_type theSourceStringLength, XalanDOMString::size_type theStartIndex, double theThirdArgValue) { // The last index must be less than theThirdArgValue. Since it has // already been rounded, subtracting 1 will do the job. const XalanDOMString::size_type theLastIndex = XalanDOMString::size_type(theThirdArgValue - 1); if (theLastIndex >= theSourceStringLength) { return theSourceStringLength - theStartIndex; } else { return theLastIndex - theStartIndex; } } /* * Get the total of the second and third arguments. */ inline double getTotal( XalanDOMString::size_type theSourceStringLength, double theSecondArgValue, const XObjectPtr& arg3) { // Total the second and third arguments. If the third argument is // missing, make it the length of the string + 1 (for XPath // indexing style). if (arg3.null() == true) { return double(theSourceStringLength + 1); } else { const double theRoundedValue = DoubleSupport::round(DoubleSupport::add(theSecondArgValue, arg3->num())); // If there's overflow, then we should return the length of the string + 1. if (DoubleSupport::isPositiveInfinity(theRoundedValue) == true) { return double(theSourceStringLength + 1); } else { return theRoundedValue; } } } static const XalanDOMString theEmptyString; inline XObjectPtr createEmptyString(XPathExecutionContext& executionContext) { return executionContext.getXObjectFactory().createString(theEmptyString); } XObjectPtr FunctionSubstring::execute( XPathExecutionContext& executionContext, XalanNode* context, const XObjectPtr arg1, const XObjectPtr arg2, const Locator* locator) const { assert(arg1.null() == false && arg2.null() == false); return execute(executionContext, context, arg1, arg2, s_nullXObjectPtr, locator); } XObjectPtr FunctionSubstring::execute( XPathExecutionContext& executionContext, XalanNode* /* context */, const XObjectPtr arg1, const XObjectPtr arg2, const XObjectPtr arg3, const Locator* /* locator */) const { assert(arg1.null() == false && arg2.null() == false); const XalanDOMString& theSourceString = arg1->str(); const XalanDOMString::size_type theSourceStringLength = length(theSourceString); if (theSourceStringLength == 0) { return createEmptyString(executionContext); } else { // Get the value of the second argument... const double theSecondArgValue = DoubleSupport::round(arg2->num()); // XPath indexes from 1, so this is the first XPath index.... const XalanDOMString::size_type theStartIndex = getStartIndex(theSecondArgValue, theSourceStringLength); if (theStartIndex >= theSourceStringLength) { return createEmptyString(executionContext); } else { const double theTotal = getTotal(theSourceStringLength, theSecondArgValue, arg3); if (DoubleSupport::isNaN(theSecondArgValue) == true || DoubleSupport::isNaN(theTotal) == true || DoubleSupport::isNegativeInfinity(theTotal) == true || theTotal < double(theStartIndex)) { return createEmptyString(executionContext); } else { const XalanDOMString::size_type theSubstringLength = getSubstringLength( theSourceStringLength, theStartIndex, theTotal); XPathExecutionContext::GetAndReleaseCachedString theResult(executionContext); XalanDOMString& theString = theResult.get(); assign( theString, toCharArray(theSourceString) + theStartIndex, theSubstringLength); return executionContext.getXObjectFactory().createString(theResult); } } } } #if defined(XALAN_NO_COVARIANT_RETURN_TYPE) Function* #else FunctionSubstring* #endif FunctionSubstring::clone() const { return new FunctionSubstring(*this); } const XalanDOMString FunctionSubstring::getError() const { return StaticStringToDOMString(XALAN_STATIC_UCODE_STRING("The substring() function takes two or three arguments!")); } <commit_msg>Fixed bug.<commit_after>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #include "FunctionSubstring.hpp" #include <PlatformSupport/DoubleSupport.hpp> #include "XObjectFactory.hpp" const XObjectPtr FunctionSubstring::s_nullXObjectPtr; FunctionSubstring::FunctionSubstring() { } FunctionSubstring::~FunctionSubstring() { } /* * Get the value for the start index (C-style, not XPath). */ inline XalanDOMString::size_type getStartIndex( double theSecondArgValue, XalanDOMString::size_type theStringLength) { // We always subtract 1 for C-style index, since XPath indexes from 1. // Anything less than, or equal to 1 is 0. if (theSecondArgValue <= 1 || DoubleSupport::isNaN(theSecondArgValue) == true) { return 0; } else if (DoubleSupport::isPositiveInfinity(theSecondArgValue) == true) { return theStringLength; } else { return XalanDOMString::size_type(DoubleSupport::round(theSecondArgValue)) - 1; } } /* * Get the length of the substring. */ inline XalanDOMString::size_type getSubstringLength( XalanDOMString::size_type theSourceStringLength, XalanDOMString::size_type theStartIndex, double theThirdArgValue) { // The last index must be less than theThirdArgValue. Since it has // already been rounded, subtracting 1 will do the job. const XalanDOMString::size_type theLastIndex = XalanDOMString::size_type(theThirdArgValue - 1); if (theLastIndex >= theSourceStringLength) { return theSourceStringLength - theStartIndex; } else { return theLastIndex - theStartIndex; } } /* * Get the total of the second and third arguments. */ inline double getTotal( XalanDOMString::size_type theSourceStringLength, double theSecondArgValue, const XObjectPtr& arg3) { // Total the second and third arguments. If the third argument is // missing, make it the length of the string + 1 (for XPath // indexing style). if (arg3.null() == true) { return double(theSourceStringLength + 1); } else { const double theRoundedValue = DoubleSupport::round(DoubleSupport::add(theSecondArgValue, arg3->num())); // If there's overflow, then we should return the length of the string + 1. if (DoubleSupport::isPositiveInfinity(theRoundedValue) == true) { return double(theSourceStringLength + 1); } else { return theRoundedValue; } } } static const XalanDOMString theEmptyString; inline XObjectPtr createEmptyString(XPathExecutionContext& executionContext) { return executionContext.getXObjectFactory().createString(theEmptyString); } XObjectPtr FunctionSubstring::execute( XPathExecutionContext& executionContext, XalanNode* context, const XObjectPtr arg1, const XObjectPtr arg2, const Locator* locator) const { assert(arg1.null() == false && arg2.null() == false); return execute(executionContext, context, arg1, arg2, s_nullXObjectPtr, locator); } XObjectPtr FunctionSubstring::execute( XPathExecutionContext& executionContext, XalanNode* /* context */, const XObjectPtr arg1, const XObjectPtr arg2, const XObjectPtr arg3, const Locator* /* locator */) const { assert(arg1.null() == false && arg2.null() == false); const XalanDOMString& theSourceString = arg1->str(); const XalanDOMString::size_type theSourceStringLength = length(theSourceString); if (theSourceStringLength == 0) { return createEmptyString(executionContext); } else { // Get the value of the second argument... const double theSecondArgValue = DoubleSupport::round(arg2->num()); // XPath indexes from 1, so this is the first XPath index.... const XalanDOMString::size_type theStartIndex = getStartIndex(theSecondArgValue, theSourceStringLength); if (theStartIndex >= theSourceStringLength) { return createEmptyString(executionContext); } else { const double theTotal = getTotal(theSourceStringLength, theSecondArgValue, arg3); if (DoubleSupport::isNaN(theSecondArgValue) == true || DoubleSupport::isNaN(theTotal) == true || DoubleSupport::isNegativeInfinity(theTotal) == true || theTotal == 0.0 || theTotal < double(theStartIndex)) { return createEmptyString(executionContext); } else { const XalanDOMString::size_type theSubstringLength = getSubstringLength( theSourceStringLength, theStartIndex, theTotal); XPathExecutionContext::GetAndReleaseCachedString theResult(executionContext); XalanDOMString& theString = theResult.get(); assign( theString, toCharArray(theSourceString) + theStartIndex, theSubstringLength); return executionContext.getXObjectFactory().createString(theResult); } } } } #if defined(XALAN_NO_COVARIANT_RETURN_TYPE) Function* #else FunctionSubstring* #endif FunctionSubstring::clone() const { return new FunctionSubstring(*this); } const XalanDOMString FunctionSubstring::getError() const { return StaticStringToDOMString(XALAN_STATIC_UCODE_STRING("The substring() function takes two or three arguments!")); } <|endoftext|>
<commit_before>#include "CppSimulation.hpp" #include "CppSystem.hpp" #include "StoreHandler.hpp" #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> #include <sstream> #include <boost/algorithm/string/replace.hpp> #include <iostream> #include <windows.h> namespace pt = boost::property_tree; typedef pysim::CppSystem*(__cdecl *funcpt)(const char* name); struct systeminfo { std::string name; std::string type; std::string module; std::vector<std::pair<std::string, std::double_t>> inputs; std::vector<std::string> stores; }; int main(int argc, char *argv[]) { using std::string; using std::pair; string simfilename; string modulerootpath; if (argc < 3) { std::cout << "warning: using default filename and modulepath" << std::endl; simfilename = "simplesim.json"; modulerootpath = "C:\\dev\\pysims\\pysim\\"; } else { simfilename = string(argv[1]); modulerootpath = string(argv[2]); } pt::ptree root; pt::read_json(simfilename, root); std::vector<systeminfo> system_infos; for (pt::ptree::value_type &json_system : root.get_child("systems")) { systeminfo sys; sys.name = json_system.first; sys.type = json_system.second.get_child("type").data(); sys.module = json_system.second.get_child("module").data(); for (pt::ptree::value_type & json_input : json_system.second.get_child("inputs")) { string key = json_input.first; string value(json_input.second.data()); sys.inputs.push_back(std::make_pair(key, std::stod(value))); } for (pt::ptree::value_type & json_store : json_system.second.get_child("stores")) { sys.stores.push_back(json_store.second.data()); } system_infos.push_back(sys); } std::map<string, funcpt> factorymap; for (systeminfo &sys : system_infos) { if (factorymap.count(sys.module) == 0) { std::stringstream ss; ss << modulerootpath; string module(sys.module); boost::algorithm::replace_all(module, ".", "\\"); ss << module << ".cp35-win32.pyd"; HINSTANCE hGetProcIDDLL = LoadLibrary(ss.str().c_str()); if (!hGetProcIDDLL) { int errorcode = GetLastError(); std::cout << "could not load the dynamic library: " << errorcode << std::endl; return 1; } funcpt funci = (funcpt)GetProcAddress(hGetProcIDDLL, "getCppSystem"); if (!funci) { std::cout << "could not locate the function" << std::endl; return 1; } factorymap[sys.module] = funci; } } pysim::Simulation sim; std::map<string, pysim::CppSystem*> systems; for (systeminfo& sys_info : system_infos) { pysim::CppSystem* sys = factorymap[sys_info.module](sys_info.type.c_str()); systems[sys_info.name] = sys; sim.addSystem(sys); } sim.simulate(200, 0.1,"rk4",0.1,0.1,false); //std::vector<double> v; //v = sys->getStoreHandlerP()->getStoreVector("x"); //std::cout << v.at(20) << std::endl; } <commit_msg>reading stored values<commit_after>#include "CppSimulation.hpp" #include "CppSystem.hpp" #include "StoreHandler.hpp" #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> #include <sstream> #include <boost/algorithm/string/replace.hpp> #include <iostream> #include <windows.h> namespace pt = boost::property_tree; typedef pysim::CppSystem*(__cdecl *funcpt)(const char* name); struct systeminfo { std::string name; std::string type; std::string module; std::vector<std::pair<std::string, std::double_t>> inputs; std::vector<std::string> stores; }; int main(int argc, char *argv[]) { using std::string; using std::pair; string simfilename; string modulerootpath; if (argc < 3) { std::cout << "warning: using default filename and modulepath" << std::endl; simfilename = "simplesim.json"; modulerootpath = "C:\\dev\\pysims\\pysim\\"; } else { simfilename = string(argv[1]); modulerootpath = string(argv[2]); } pt::ptree root; pt::read_json(simfilename, root); std::vector<systeminfo> system_infos; for (pt::ptree::value_type &json_system : root.get_child("systems")) { systeminfo sys; sys.name = json_system.first; sys.type = json_system.second.get_child("type").data(); sys.module = json_system.second.get_child("module").data(); for (pt::ptree::value_type & json_input : json_system.second.get_child("inputs")) { string key = json_input.first; string value(json_input.second.data()); sys.inputs.push_back(std::make_pair(key, std::stod(value))); } for (pt::ptree::value_type & json_store : json_system.second.get_child("stores")) { sys.stores.push_back(json_store.second.data()); } system_infos.push_back(sys); } std::map<string, funcpt> factorymap; for (systeminfo &sys : system_infos) { if (factorymap.count(sys.module) == 0) { std::stringstream ss; ss << modulerootpath; string module(sys.module); boost::algorithm::replace_all(module, ".", "\\"); ss << module << ".cp35-win32.pyd"; HINSTANCE hGetProcIDDLL = LoadLibrary(ss.str().c_str()); if (!hGetProcIDDLL) { int errorcode = GetLastError(); std::cout << "could not load the dynamic library: " << errorcode << std::endl; return 1; } funcpt funci = (funcpt)GetProcAddress(hGetProcIDDLL, "getCppSystem"); if (!funci) { std::cout << "could not locate the function" << std::endl; return 1; } factorymap[sys.module] = funci; } } pysim::Simulation sim; std::map<string, pysim::CppSystem*> systems; for (systeminfo& sys_info : system_infos) { pysim::CppSystem* sys = factorymap[sys_info.module](sys_info.type.c_str()); for (std::string name: sys_info.stores){ //sys->store(name.c_str()); } systems[sys_info.name] = sys; sim.addSystem(sys); } sim.simulate(200, 0.1,"rk4",0.1,0.1,false); std::vector<double> v; pysim::CppSystem* sys = systems["vanderpol"]; v = sys->getStoreHandlerP()->getStoreVector("x"); std::cout << v.at(20) << std::endl; } <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2009 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* interface header */ #include "PointShotStrategy.h" /* system implementation headers */ #include <assert.h> /* common implementation headers */ #include "BZDBCache.h" #include "WallObstacle.h" #include "Intersect.h" /* local implementation headers */ #include "LocalPlayer.h" #include "playing.h" PointShotStrategy::PointShotStrategy(ShotPath* _path) : ShotStrategy(_path) { doBoxTest = false; } PointShotStrategy::~PointShotStrategy() { } float PointShotStrategy::checkShotHit(const ShotCollider& tank, fvec3& position, float radius) const { float minTime = Infinity; // expired shot can't hit anything if (getPath().isExpired()) return minTime; static BZDB_fvec3 shotProxy(BZDBNAMES.TANKSHOTPROXIMITY); const fvec3 &proxySize = shotProxy.getData(); // get tank radius const float radius2 = tank.radius * tank.radius; // tank is positioned from it's bottom so shift position up by // half a tank height. const float tankHeight = tank.size.z; fvec3 lastTankPositionRaw = tank.motion.getOrigin(); lastTankPositionRaw.z += 0.5f * tankHeight; Ray tankLastMotion(lastTankPositionRaw, tank.motion.getDirection()); const Extents& tankBBox = tank.bbox; // if bounding box of tank and entire shot doesn't overlap then no hit // we only do this for shots that keep the bbox updated if (doBoxTest) { if (!bbox.touches(tankBBox)) return minTime; } float shotRadius = radius; // check each segment in interval (prevTime,currentTime] const float dt = float(currentTime - prevTime); const int numSegments = (const int)segments.size(); for (int i = lastSegment; i <= segment && i < numSegments; i++) { // can never hit your own first laser segment if ((i == 0) && tank.testLastSegment && (getPath().getShotType() == LaserShot)) continue; /* // skip segments that don't overlap in time with current interval if (segments[i].end <= prevTime) continue; if (currentTime <= segments[i].start) break; */ // if shot segment and tank bboxes don't overlap then no hit, // or if it's a shot that is out of the world boundary const ShotPathSegment& s = segments[i]; if (!s.bbox.touches(tankBBox) || (s.reason == ShotPathSegment::Boundary)) continue; // construct relative shot ray: origin and velocity relative to // my tank as a function of time (t=0 is start of the interval). Ray relativeRay(Intersect::rayMinusRay(s.ray, float(prevTime - s.start), tankLastMotion, 0.0f)); // get hit time float t; if (tank.test2D) // for now just test as a box, the box -> sphere test does not use the same volume and may cause more problems then it tries to solve by being fast { // find closest approach to narrow box around tank. width of box // is shell radius so you can actually hit narrow tank head on. static fvec3 tankBase(0.0f, 0.0f, -0.5f * tankHeight); t = Intersect::timeRayHitsBlock(relativeRay, tankBase, tank.angle, (0.5f * tank.length) + proxySize.x, shotRadius, tankHeight + proxySize.z); } else// find time when shot hits sphere around tank { // old sphere code, has problems when the hit is inside the smaller "prehit" box // t = Intersect::rayAtDistanceFromOrigin(relativeRay, 0.99f * tank.radius); // find closest approach to wide box around tank. width of box // is tank radius so you get a little fudge factor on the side static fvec3 tankBase(0.0f, 0.0f, -0.5f * tankHeight); t = Intersect::timeRayHitsBlock(relativeRay, tankBase, tank.angle, tank.size.x + proxySize.x, tank.size.y + proxySize.y, tankHeight + proxySize.z); } // short circuit if time is greater then smallest time so far if (t > minTime) continue; // make sure time falls within segment if ((t < 0.0f) || (t > dt)) continue; if (t > (s.end - prevTime)) continue; // check if shot hits tank -- get position at time t, see if in radius fvec3 closestPos; relativeRay.getPoint(t, closestPos); // save best time so far minTime = t; // compute location of tank at time of hit fvec3 tankPos; tank.motion.getPoint(t, tankPos); // compute position of intersection position = tankPos + closestPos + fvec3(0,0,0.5f * tankHeight); //printf("%u:%u %u:%u\n", tank->getId().port, tank->getId().number, getPath().getPlayer().port, getPath().getPlayer().number); } return minTime; } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>what's a radius between friends!<commit_after>/* bzflag * Copyright (c) 1993 - 2009 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* interface header */ #include "PointShotStrategy.h" /* system implementation headers */ #include <assert.h> /* common implementation headers */ #include "BZDBCache.h" #include "WallObstacle.h" #include "Intersect.h" /* local implementation headers */ #include "LocalPlayer.h" #include "playing.h" PointShotStrategy::PointShotStrategy(ShotPath* _path) : ShotStrategy(_path) { doBoxTest = false; } PointShotStrategy::~PointShotStrategy() { } float PointShotStrategy::checkShotHit(const ShotCollider& tank, fvec3& position, float radius) const { float minTime = Infinity; // expired shot can't hit anything if (getPath().isExpired()) return minTime; static BZDB_fvec3 shotProxy(BZDBNAMES.TANKSHOTPROXIMITY); const fvec3 &proxySize = shotProxy.getData(); // tank is positioned from it's bottom so shift position up by // half a tank height. const float tankHeight = tank.size.z; fvec3 lastTankPositionRaw = tank.motion.getOrigin(); lastTankPositionRaw.z += 0.5f * tankHeight; Ray tankLastMotion(lastTankPositionRaw, tank.motion.getDirection()); const Extents& tankBBox = tank.bbox; // if bounding box of tank and entire shot doesn't overlap then no hit // we only do this for shots that keep the bbox updated if (doBoxTest) { if (!bbox.touches(tankBBox)) return minTime; } float shotRadius = radius; // check each segment in interval (prevTime,currentTime] const float dt = float(currentTime - prevTime); const int numSegments = (const int)segments.size(); for (int i = lastSegment; i <= segment && i < numSegments; i++) { // can never hit your own first laser segment if ((i == 0) && tank.testLastSegment && (getPath().getShotType() == LaserShot)) continue; /* // skip segments that don't overlap in time with current interval if (segments[i].end <= prevTime) continue; if (currentTime <= segments[i].start) break; */ // if shot segment and tank bboxes don't overlap then no hit, // or if it's a shot that is out of the world boundary const ShotPathSegment& s = segments[i]; if (!s.bbox.touches(tankBBox) || (s.reason == ShotPathSegment::Boundary)) continue; // construct relative shot ray: origin and velocity relative to // my tank as a function of time (t=0 is start of the interval). Ray relativeRay(Intersect::rayMinusRay(s.ray, float(prevTime - s.start), tankLastMotion, 0.0f)); // get hit time float t; if (tank.test2D) // for now just test as a box, the box -> sphere test does not use the same volume and may cause more problems then it tries to solve by being fast { // find closest approach to narrow box around tank. width of box // is shell radius so you can actually hit narrow tank head on. static fvec3 tankBase(0.0f, 0.0f, -0.5f * tankHeight); t = Intersect::timeRayHitsBlock(relativeRay, tankBase, tank.angle, (0.5f * tank.length) + proxySize.x, shotRadius, tankHeight + proxySize.z); } else// find time when shot hits sphere around tank { // old sphere code, has problems when the hit is inside the smaller "prehit" box // t = Intersect::rayAtDistanceFromOrigin(relativeRay, 0.99f * tank.radius); // find closest approach to wide box around tank. width of box // is tank radius so you get a little fudge factor on the side static fvec3 tankBase(0.0f, 0.0f, -0.5f * tankHeight); t = Intersect::timeRayHitsBlock(relativeRay, tankBase, tank.angle, tank.size.x + proxySize.x, tank.size.y + proxySize.y, tankHeight + proxySize.z); } // short circuit if time is greater then smallest time so far if (t > minTime) continue; // make sure time falls within segment if ((t < 0.0f) || (t > dt)) continue; if (t > (s.end - prevTime)) continue; // check if shot hits tank -- get position at time t, see if in radius fvec3 closestPos; relativeRay.getPoint(t, closestPos); // save best time so far minTime = t; // compute location of tank at time of hit fvec3 tankPos; tank.motion.getPoint(t, tankPos); // compute position of intersection position = tankPos + closestPos + fvec3(0,0,0.5f * tankHeight); //printf("%u:%u %u:%u\n", tank->getId().port, tank->getId().number, getPath().getPlayer().port, getPath().getPlayer().number); } return minTime; } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: testbasi.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2006-09-17 09:58:16 $ * * 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_basic.hxx" #define testtool #include "mybasic.cxx" <commit_msg>INTEGRATION: CWS changefileheader (1.3.166); FILE MERGED 2008/03/28 16:07:06 rt 1.3.166.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: testbasi.cxx,v $ * $Revision: 1.4 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_basic.hxx" #define testtool #include "mybasic.cxx" <|endoftext|>
<commit_before>#include "stdafx.h" #include "ipclistener.h" #include <afxwin.h> namespace myodd { namespace os { static HWND _pParentWnd = nullptr; class IpcListenerWnd : public CWnd { protected: enum class IpcMessageType : unsigned int { None = 0, SendMessage = 1, PostMessage = 2, }; struct IpcMessageStruct { // https://www.displayfusion.com/Discussions/View/converting-c-data-types-to-c/?ID=38db6001-45e5-41a3-ab39-8004450204b3 unsigned int uMsg; unsigned __int64 wParam; __int64 lParam; }; public: explicit IpcListenerWnd(const wchar_t* pszClassName, HWND pParent) { // save the parent _pParentWnd = pParent; // the instance of this module auto hInstance = GetModuleHandle( nullptr ); WNDCLASS wndcls; if (GetClassInfo(hInstance, pszClassName, &wndcls)) { throw "The server already exists."; } wndcls.style = 0; wndcls.lpfnWndProc = WindowProc; wndcls.cbClsExtra = wndcls.cbWndExtra = 0; wndcls.hInstance = hInstance; wndcls.hIcon = nullptr; wndcls.hCursor = LoadCursor(nullptr, IDC_ARROW); wndcls.hbrBackground = GetSysColorBrush(COLOR_WINDOW); wndcls.lpszMenuName = nullptr; wndcls.lpszClassName = pszClassName; if (!RegisterClass(&wndcls)) { throw "Can't register IpcListener window class."; } // one way or another the class was created. // so we can create our listener accordingly. if (!this->CWnd::CreateEx(0, pszClassName, L"", 0, 0, 0, 0, 0, HWND_MESSAGE, nullptr)) { throw "Can't create IpcListener window."; } } protected: static bool MessageStructFromCopyData(const COPYDATASTRUCT& cds, IpcMessageStruct& ipcMessageStructure) { // clear the values memset(&ipcMessageStructure, 0, sizeof(ipcMessageStructure)); // is the data we were given the right size? if (cds.cbData != sizeof(ipcMessageStructure)) { // nope, it is not, something is wrong. return false; } // copy the data over. memcpy_s(&ipcMessageStructure, sizeof(ipcMessageStructure), cds.lpData, cds.cbData); // success. return true; } public: static LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { // is it a copy data message? // if not, then it is just a message for this window. if (uMsg != WM_COPYDATA) { // pass this to our window... return ::DefWindowProc(hwnd, uMsg, wParam, lParam); } // cast it to COPYDATASTRUCT auto pcds = (COPYDATASTRUCT*)lParam; // then simply reconstruct the message switch ( (IpcMessageType)pcds->dwData) { case IpcMessageType::SendMessage: { // pass this to the parent window IpcMessageStruct ims; if (MessageStructFromCopyData(*pcds, ims)) { #if defined(_WIN64) return ::SendMessage(_pParentWnd, ims.uMsg, ims.wParam, ims.lParam); #else return ::SendMessage(_pParentWnd, ims.uMsg, static_cast<unsigned int>(ims.wParam), static_cast<long>(ims.lParam)); #endif // X64 } } break; case IpcMessageType::PostMessage: { // pass this to the parent window IpcMessageStruct ims; if (MessageStructFromCopyData(*pcds, ims)) { // pass this to the parent window #if defined(_WIN64) return ::PostMessage(_pParentWnd, ims.uMsg, ims.wParam, ims.lParam); #else return ::SendMessage(_pParentWnd, ims.uMsg, static_cast<unsigned int>(ims.wParam), static_cast<long>(ims.lParam)); #endif // X64 } } break; default: // unknown message type break; } // if we reach this then we have an unknwon type. return 0; } }; IpcListener::IpcListener(const wchar_t* serverName, void* parent ) : _pServer( nullptr ) { // create the server Create(serverName, parent ); } IpcListener::~IpcListener() { // remove the server. delete static_cast<IpcListenerWnd*>(_pServer); } /** * Create the server window that will be listening to messages. * @param const wchar_t* serverName the server name we wish to use. * @param void* pParent the parent that we want to pass the messages to. * @return none */ void IpcListener::Create(const wchar_t* serverName, void* pParent) { _pServer = new IpcListenerWnd( serverName, (HWND)pParent ); } } } <commit_msg>IPC Post message tries to manage x64/x86 a little better.<commit_after>#include "stdafx.h" #include "ipclistener.h" #include <afxwin.h> namespace myodd { namespace os { static HWND _pParentWnd = nullptr; class IpcListenerWnd : public CWnd { protected: enum class IpcMessageType : unsigned int { None = 0, SendMessage = 1, PostMessage = 2, }; struct IpcMessageStruct { // https://www.displayfusion.com/Discussions/View/converting-c-data-types-to-c/?ID=38db6001-45e5-41a3-ab39-8004450204b3 unsigned int uMsg; unsigned __int64 wParam; __int64 lParam; }; public: explicit IpcListenerWnd(const wchar_t* pszClassName, HWND pParent) { // save the parent _pParentWnd = pParent; // the instance of this module auto hInstance = GetModuleHandle( nullptr ); WNDCLASS wndcls; if (GetClassInfo(hInstance, pszClassName, &wndcls)) { throw "The server already exists."; } wndcls.style = 0; wndcls.lpfnWndProc = WindowProc; wndcls.cbClsExtra = wndcls.cbWndExtra = 0; wndcls.hInstance = hInstance; wndcls.hIcon = nullptr; wndcls.hCursor = LoadCursor(nullptr, IDC_ARROW); wndcls.hbrBackground = GetSysColorBrush(COLOR_WINDOW); wndcls.lpszMenuName = nullptr; wndcls.lpszClassName = pszClassName; if (!RegisterClass(&wndcls)) { throw "Can't register IpcListener window class."; } // one way or another the class was created. // so we can create our listener accordingly. if (!this->CWnd::CreateEx(0, pszClassName, L"", 0, 0, 0, 0, 0, HWND_MESSAGE, nullptr)) { throw "Can't create IpcListener window."; } } protected: static bool MessageStructFromCopyData(const COPYDATASTRUCT& cds, IpcMessageStruct& ipcMessageStructure) { // clear the values memset(&ipcMessageStructure, 0, sizeof(ipcMessageStructure)); // is the data we were given the right size? if (cds.cbData != sizeof(ipcMessageStructure)) { // nope, it is not, something is wrong. return false; } // copy the data over. memcpy_s(&ipcMessageStructure, sizeof(ipcMessageStructure), cds.lpData, cds.cbData); // success. return true; } public: static LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { // is it a copy data message? // if not, then it is just a message for this window. if (uMsg != WM_COPYDATA) { // pass this to our window... return ::DefWindowProc(hwnd, uMsg, wParam, lParam); } // cast it to COPYDATASTRUCT auto pcds = (COPYDATASTRUCT*)lParam; // then simply reconstruct the message switch ( (IpcMessageType)pcds->dwData) { case IpcMessageType::SendMessage: { // pass this to the parent window IpcMessageStruct ims; if (MessageStructFromCopyData(*pcds, ims)) { #if defined(_WIN64) return ::SendMessage(_pParentWnd, ims.uMsg, ims.wParam, ims.lParam); #else return ::SendMessage(_pParentWnd, ims.uMsg, static_cast<unsigned int>(ims.wParam), static_cast<long>(ims.lParam)); #endif // X64 } } break; case IpcMessageType::PostMessage: { // pass this to the parent window IpcMessageStruct ims; if (MessageStructFromCopyData(*pcds, ims)) { // pass this to the parent window #if defined(_WIN64) return ::PostMessage(_pParentWnd, ims.uMsg, ims.wParam, ims.lParam); #else return ::PostMessage(_pParentWnd, ims.uMsg, static_cast<unsigned int>(ims.wParam), static_cast<long>(ims.lParam)); #endif // X64 } } break; default: // unknown message type break; } // if we reach this then we have an unknwon type. return 0; } }; IpcListener::IpcListener(const wchar_t* serverName, void* parent ) : _pServer( nullptr ) { // create the server Create(serverName, parent ); } IpcListener::~IpcListener() { // remove the server. delete static_cast<IpcListenerWnd*>(_pServer); } /** * Create the server window that will be listening to messages. * @param const wchar_t* serverName the server name we wish to use. * @param void* pParent the parent that we want to pass the messages to. * @return none */ void IpcListener::Create(const wchar_t* serverName, void* pParent) { _pServer = new IpcListenerWnd( serverName, (HWND)pParent ); } } } <|endoftext|>
<commit_before>// code goes here!<commit_msg>created psudeo code for Trapezium series.<commit_after>draw(){ for (int row = 0; row < [[numWide]]; row++){ for (int column = 0; column < [[numWide]]; column++){ drawTrapezium(row, column); } } } drawTrapezium(int row, int column){ point startCenter = gridCenter(row, column); targets myTargets = getTargets[row][column]; float center = startCenter * (1. - [[centerNoise]]) + myTargets.center * [[centerNoise]]; point topLeft = {center.x - [[baseSize]] / 2, center.y - [[baseSize]] / 2}; point topRight = {center.x + [[baseSize]] / 2, center.y - [[baseSize]] / 2}; point bottomRight = {center.x + [[baseSize]] / 2, center.y + [[baseSize]] / 2}; point bottomLeft = {center.x - [[baseSize]] / 2, center.y + [[baseSize]] / 2}; float cornerMagnitude = [[cornerNoise]] * [[baseSize]]; topLeft.x += myTargets.topLeft * cornerMagnitude; topRight.x += myTargets.topRight * cornerMagnitude; bottomRight.x += myTargets.bottomRight * cornerMagnitude; bottomLeft.x += myTargets.bottomLeft * cornerMagnitude; drawLine(topLeft, topRight); drawLine(topRight, bottomRight); drawLine(bottomRight, bottomLeft); drawLine(bottomLeft, topLeft); } <|endoftext|>
<commit_before>#include <pthread.h> #include <climits> #include <cassert> #include "thread.hh" namespace mimosa { static void* startWrapper(std::function<void ()> * fct) { (*fct)(); delete fct; return 0; } Thread::Thread(std::function<void ()> && fct) : thread_(), fct_(new std::function<void ()>(fct)), state_(kNotRunning), //stack_size_(64 * 1024) stack_size_(PTHREAD_STACK_MIN) { } bool Thread::start() { assert(state_ == kNotRunning); pthread_attr_t attrs; if (pthread_attr_init(&attrs)) return false; if (pthread_attr_setstacksize(&attrs, stack_size_)) { pthread_attr_destroy(&attrs); return false; } if (::pthread_create(&thread_, &attrs, reinterpret_cast<void*(*)(void*)>(startWrapper), static_cast<void*>(fct_))) { pthread_attr_destroy(&attrs); return false; } pthread_attr_destroy(&attrs); fct_ = nullptr; state_ = kRunning; return true; } Thread::~Thread() { delete fct_; detach(); } void Thread::join() { if (state_ != kRunning) return; ::pthread_join(thread_, NULL); state_ = kJoined; } bool Thread::tryJoin() { if (state_ != kRunning) return false; if (::pthread_tryjoin_np(thread_, NULL)) return false; state_ = kJoined; return true; } bool Thread::timedJoin(Time timeout) { if (state_ != kRunning) return false; ::timespec tp; toTimeSpec(timeout, &tp); if (::pthread_timedjoin_np(thread_, NULL, &tp)) return false; state_ = kJoined; return true; } void Thread::detach() { if (state_ != kRunning) return; ::pthread_detach(thread_); state_ = kDetached; } } <commit_msg>I need at least 64k stack as gnutls will segv otherwise...<commit_after>#include <pthread.h> #include <climits> #include <cassert> #include "thread.hh" namespace mimosa { static void* startWrapper(std::function<void ()> * fct) { (*fct)(); delete fct; return 0; } Thread::Thread(std::function<void ()> && fct) : thread_(), fct_(new std::function<void ()>(fct)), state_(kNotRunning), stack_size_(64 * 1024) //stack_size_(PTHREAD_STACK_MIN) { } bool Thread::start() { assert(state_ == kNotRunning); pthread_attr_t attrs; if (pthread_attr_init(&attrs)) return false; if (pthread_attr_setstacksize(&attrs, stack_size_)) { pthread_attr_destroy(&attrs); return false; } if (::pthread_create(&thread_, &attrs, reinterpret_cast<void*(*)(void*)>(startWrapper), static_cast<void*>(fct_))) { pthread_attr_destroy(&attrs); return false; } pthread_attr_destroy(&attrs); fct_ = nullptr; state_ = kRunning; return true; } Thread::~Thread() { delete fct_; detach(); } void Thread::join() { if (state_ != kRunning) return; ::pthread_join(thread_, NULL); state_ = kJoined; } bool Thread::tryJoin() { if (state_ != kRunning) return false; if (::pthread_tryjoin_np(thread_, NULL)) return false; state_ = kJoined; return true; } bool Thread::timedJoin(Time timeout) { if (state_ != kRunning) return false; ::timespec tp; toTimeSpec(timeout, &tp); if (::pthread_timedjoin_np(thread_, NULL, &tp)) return false; state_ = kJoined; return true; } void Thread::detach() { if (state_ != kRunning) return; ::pthread_detach(thread_); state_ = kDetached; } } <|endoftext|>
<commit_before>#include <assert.h> #include <cstdio> #ifndef HAVE_LLVM #error "This code needs LLVM enabled" #endif #include <llvm/IR/LLVMContext.h> #include <llvm/IR/Module.h> #include <llvm/Support/SourceMgr.h> #include <llvm/Support/raw_ostream.h> #include <llvm/IRReader/IRReader.h> #include <iostream> #include <string> #include <queue> #include <set> #include "../src/llvm/DependenceGraph.h" using namespace dg::llvmdg; using llvm::errs; typedef DependenceGraph::BBlock BBlock; static struct { bool printCFG; bool printRevCFG; bool printBB; bool printBBonly; bool printPostDom; bool printControlDep; bool printDataDep; } OPTIONS; std::queue<DependenceGraph *> toPrint; static std::string& getValueName(const llvm::Value *val, std::string &str) { llvm::raw_string_ostream s(str); str.clear(); if (!val) { s << "[NULL]"; return s.str(); } if (llvm::isa<llvm::Function>(val)) s << "ENTRY " << val->getName(); else s << *val; return s.str(); } static void dump_to_dot(Node *n, std::ostream& out) { const llvm::Value *val; /* do not draw multiple edges */ if (n->getDFSRunId() != 0) return; else n->setDFSRunId(1); if (OPTIONS.printControlDep) for (auto I = n->control_begin(), E = n->control_end(); I != E; ++I) out << "\tNODE" << n << " -> NODE" << *I << "\n"; if (OPTIONS.printDataDep) for (auto I = n->data_begin(), E = n->data_end(); I != E; ++I) out << "\tNODE" << n << " -> NODE" << *I << " [color=red]\n"; if (OPTIONS.printCFG && !OPTIONS.printBBonly) { if (n->hasSuccessor()) { Node *succ = n->getSuccessor(); if (!succ) errs() << "n hasSuccessor NULL!\n"; out << "\tNODE" << n << " -> NODE" << succ << " [style=dotted rank=source]\n"; } } if (OPTIONS.printRevCFG && !OPTIONS.printBBonly) { if (n->hasPredcessor()) { out << "\tNODE" << n << " -> NODE" << n->getPredcessor() << " [style=dotted color=gray]\n"; } } // print edges between blocks if (OPTIONS.printCFG || OPTIONS.printBB) { auto BB = n->getBasicBlock(); if (BB && BB->getLastNode() == n) { for (auto pred : BB->successors()) { auto fn = pred->getFirstNode(); out << "\tNODE" << n << " -> NODE" << fn << " [style=dotted color=red]\n"; } } } /* if (OPTIONS.printRevCFG || OPTIONS.printBB) { auto BB = n->getBasicBlock(); // if this is BB header, print the edges if (BB && BB->getFirstNode() == n) { auto fn = BB->getFirstNode(); for (auto pred : BB->predcessors()) { auto ln = pred->getLastNode(); out << "\tNODE" << fn << " -> NODE" << ln << " [style=dotted color=purple]\n"; } } } */ if (OPTIONS.printPostDom) { auto BB = n->getBasicBlock(); if (BB && BB->getFirstNode() == n && BB->getIPostDomBy()) { auto pdBB = BB->getIPostDomBy(); if (pdBB) { out << "\tNODE" << pdBB->getLastNode() << " -> NODE" << n << " [style=dashed color=purple rank=source]\n"; } else { errs() << "WARN: No post-dom by for basic block for " << BB << "\n"; } } } } static void print_to_dot(DependenceGraph *dg, std::ostream& out = std::cout); static void printNode(Node *n, std::ostream& out = std::cout) { std::string valName; BBlock *BB = n->getBasicBlock(); const llvm::Value *val = n->getValue(); bool isBBHead = BB && n == BB->getFirstNode(); bool isBBTail = BB && n == BB->getLastNode(); assert(n); for (auto sub : n->getSubgraphs()) toPrint.push(sub); DependenceGraph *params = n->getParameters(); if (params) { toPrint.push(params); } // do not print node if we'd like to print only bblocks if (!(isBBHead || isBBTail) && OPTIONS.printBBonly) return; getValueName(val, valName); out << "\tNODE" << n << " ["; if (isBBHead) { out << "style=\"filled\" fillcolor=\"lightgray\""; } out << " label=\"" << valName; if (OPTIONS.printBB && BB) { auto fn = BB->getFirstNode(); if (!fn) { errs() << "CRITICAL: No first value for " << valName << "\n"; } else { auto fval = fn->getValue(); if (!fval) { errs() << "WARN: No value in first value for " << valName << "\n"; } else { getValueName(fval, valName); out << "\\nBB: " << valName; if (n == fn) out << "\\nBB head (preds " << BB->predcessorsNum() << ")"; if (BB->getLastNode() == n) out << "\\nBB tail (succs " << BB->successorsNum() << ")"; } } } for (auto d : n->getDefs()) { getValueName(d->getValue(), valName); out << "\\nDEF " << valName; } for (auto d : n->getPtrs()) { getValueName(d->getValue(), valName); out << "\\nPTR " << valName; } out << "\"];\n"; //<<" (runid=" << n->getDFSrun() << ")\"];\n"; } static void printBB(DependenceGraph *dg, BBlock *BB, std::ostream& out) { assert(BB); Node *n = BB->getFirstNode(); static unsigned int bbid = 0; if (!n) { std::string valName; getValueName(dg->getEntry()->getValue(), valName); errs() << "WARN no first value in a block for " << valName << "\n"; return; } out << "subgraph cluster_bb_" << bbid++; out << "{\n"; out << "\tstyle=dotted\n"; out << "label=\"BBlock " << BB; if (BB == dg->getEntryBB()) out << " |> ENTRY <|"; if (BB == dg->getExitBB()) out << " |> EXIT <|"; if (OPTIONS.printPostDom) { out << "\\n"; for (BBlock *b : BB->getPostdominates()) out << "\\nPDOM " << b; } out << "\"\n"; do { printNode(n, out); n = n->getSuccessor(); } while (n); out << "}\n"; } static void printNodesOnly(DependenceGraph *dg, std::ostream& out) { for (auto I = dg->begin(), E = dg->end(); I != E; ++I) { printNode(I->second, out); } } static void dg_print_edges(DependenceGraph *dg, std::ostream& out) { for (auto I = dg->begin(), E = dg->end(); I != E; ++I) { auto n = I->second; if (!n) { errs() << "WARN [" << dg << "]: Node is NULL for value: " << *I->first << "\n"; continue; } dump_to_dot(I->second, out); } // if this is a params dg, print edge from callsite to // this dg // add control edge from call-site to the parameters subgraph //out << "\tNODE" << n << " -> NODE" << params->getEntry() // << "[label=\"params\"]\n"; // // if this is a function, print edges here from callsites //for (auto sub : n->getSubgraphs()) { // out << "\tNODE" << n << " -> NODE" << sub->getEntry() // << " [style=dashed label=\"call\"]\n"; //} } static void print_to_dot(DependenceGraph *dg, std::ostream& out) { static unsigned subgraph_no = 0; const llvm::Value *val; std::string valName; if (!dg) return; out << "subgraph \"cluster_" << subgraph_no++; out << "\" {\n"; getValueName(dg->getEntry()->getValue(), valName); out << "label=\"<" << valName << ">"; out << "\\n Nodes: " << dg->size() << "\""; out << " style=\"solid\""; std::queue<BBlock *> queue; auto entryBB = dg->getEntryBB(); if (!entryBB) { errs() << "No entry block in graph for " << valName << "\n"; errs() << " ^^^ printing only nodes\n"; printNodesOnly(dg, out); out << "}\n"; return; } printNodesOnly(dg, out); unsigned int runid = entryBB->getDFSRunId(); ++runid; queue.push(dg->getEntryBB()); while (!queue.empty()) { auto BB = queue.front(); queue.pop(); BB->setDFSRunId(runid); printBB(dg, BB, out); for (auto S : BB->successors()) { if (S->getDFSRunId() != runid) queue.push(S); } } // print edges in dg dg_print_edges(dg, out); out << "}\n"; } int main(int argc, char *argv[]) { llvm::LLVMContext context; llvm::SMDiagnostic SMD; std::unique_ptr<llvm::Module> M; const char *module = NULL; // default OPTIONS.printControlDep = true; OPTIONS.printDataDep = true; // parse options for (int i = 1; i < argc; ++i) { if (strcmp(argv[i], "-no-control") == 0) { OPTIONS.printControlDep = false; } else if (strcmp(argv[i], "-no-data") == 0) { OPTIONS.printDataDep = false; } else if (strcmp(argv[i], "-bb") == 0) { OPTIONS.printBB = true; } else if (strcmp(argv[i], "-bbonly") == 0) { OPTIONS.printBB = true; OPTIONS.printBBonly = true; OPTIONS.printDataDep = false; } else if (strcmp(argv[i], "-cfg") == 0) { OPTIONS.printCFG = true; } else if (strcmp(argv[i], "-cfgall") == 0) { OPTIONS.printCFG = true; OPTIONS.printRevCFG = true; } else if (strcmp(argv[i], "-pd") == 0) { OPTIONS.printPostDom = true; } else { module = argv[i]; } } if (!module) { errs() << "Usage: % IR_module [output_file]\n"; return 1; } M = llvm::parseIRFile(module, SMD, context); if (!M) { SMD.print(argv[0], errs()); return 1; } DependenceGraph d; d.build(&*M); d.computePDTree(); std::ostream& out = std::cout; std::set<DependenceGraph *> printed; out << "digraph \"DependencyGraph\" {\n"; // print main procedure toPrint.push(&d); // print subgraphs that should be printed while (!toPrint.empty()) { auto sg = toPrint.front(); toPrint.pop(); if (printed.insert(sg).second) print_to_dot(sg, out); } out << "}\n"; return 0; } <commit_msg>llvm-dump: changes colors of edges<commit_after>#include <assert.h> #include <cstdio> #ifndef HAVE_LLVM #error "This code needs LLVM enabled" #endif #include <llvm/IR/LLVMContext.h> #include <llvm/IR/Module.h> #include <llvm/Support/SourceMgr.h> #include <llvm/Support/raw_ostream.h> #include <llvm/IRReader/IRReader.h> #include <iostream> #include <string> #include <queue> #include <set> #include "../src/llvm/DependenceGraph.h" using namespace dg::llvmdg; using llvm::errs; typedef DependenceGraph::BBlock BBlock; static struct { bool printCFG; bool printRevCFG; bool printBB; bool printBBonly; bool printPostDom; bool printControlDep; bool printDataDep; } OPTIONS; std::queue<DependenceGraph *> toPrint; static std::string& getValueName(const llvm::Value *val, std::string &str) { llvm::raw_string_ostream s(str); str.clear(); if (!val) { s << "[NULL]"; return s.str(); } if (llvm::isa<llvm::Function>(val)) s << "ENTRY " << val->getName(); else s << *val; return s.str(); } static void dump_to_dot(Node *n, std::ostream& out) { const llvm::Value *val; /* do not draw multiple edges */ if (n->getDFSRunId() != 0) return; else n->setDFSRunId(1); if (OPTIONS.printControlDep) for (auto I = n->control_begin(), E = n->control_end(); I != E; ++I) out << "\tNODE" << n << " -> NODE" << *I << "[color=green]\n"; if (OPTIONS.printDataDep) for (auto I = n->data_begin(), E = n->data_end(); I != E; ++I) out << "\tNODE" << n << " -> NODE" << *I << " [color=red]\n"; if (OPTIONS.printCFG && !OPTIONS.printBBonly) { if (n->hasSuccessor()) { Node *succ = n->getSuccessor(); if (!succ) errs() << "n hasSuccessor NULL!\n"; out << "\tNODE" << n << " -> NODE" << succ << " [style=dotted rank=source]\n"; } } if (OPTIONS.printRevCFG && !OPTIONS.printBBonly) { if (n->hasPredcessor()) { out << "\tNODE" << n << " -> NODE" << n->getPredcessor() << " [style=dotted color=gray]\n"; } } // print edges between blocks if (OPTIONS.printCFG || OPTIONS.printBB) { auto BB = n->getBasicBlock(); if (BB && BB->getLastNode() == n) { for (auto pred : BB->successors()) { auto fn = pred->getFirstNode(); out << "\tNODE" << n << " -> NODE" << fn << " [color=black]\n"; } } } /* if (OPTIONS.printRevCFG || OPTIONS.printBB) { auto BB = n->getBasicBlock(); // if this is BB header, print the edges if (BB && BB->getFirstNode() == n) { auto fn = BB->getFirstNode(); for (auto pred : BB->predcessors()) { auto ln = pred->getLastNode(); out << "\tNODE" << fn << " -> NODE" << ln << " [style=dotted color=purple]\n"; } } } */ if (OPTIONS.printPostDom) { auto BB = n->getBasicBlock(); if (BB && BB->getFirstNode() == n && BB->getIPostDomBy()) { auto pdBB = BB->getIPostDomBy(); if (pdBB) { out << "\tNODE" << pdBB->getLastNode() << " -> NODE" << n << " [style=dashed color=purple rank=source]\n"; } else { errs() << "WARN: No post-dom by for basic block for " << BB << "\n"; } } } } static void print_to_dot(DependenceGraph *dg, std::ostream& out = std::cout); static void printNode(Node *n, std::ostream& out = std::cout) { std::string valName; BBlock *BB = n->getBasicBlock(); const llvm::Value *val = n->getValue(); bool isBBHead = BB && n == BB->getFirstNode(); bool isBBTail = BB && n == BB->getLastNode(); assert(n); for (auto sub : n->getSubgraphs()) toPrint.push(sub); DependenceGraph *params = n->getParameters(); if (params) { toPrint.push(params); } // do not print node if we'd like to print only bblocks if (!(isBBHead || isBBTail) && OPTIONS.printBBonly) return; getValueName(val, valName); out << "\tNODE" << n << " ["; if (isBBHead) { out << "style=\"filled\" fillcolor=\"lightgray\""; } out << " label=\"" << valName; if (OPTIONS.printBB && BB) { auto fn = BB->getFirstNode(); if (!fn) { errs() << "CRITICAL: No first value for " << valName << "\n"; } else { auto fval = fn->getValue(); if (!fval) { errs() << "WARN: No value in first value for " << valName << "\n"; } else { getValueName(fval, valName); out << "\\nBB: " << valName; if (n == fn) out << "\\nBB head (preds " << BB->predcessorsNum() << ")"; if (BB->getLastNode() == n) out << "\\nBB tail (succs " << BB->successorsNum() << ")"; } } } for (auto d : n->getDefs()) { getValueName(d->getValue(), valName); out << "\\nDEF " << valName; } for (auto d : n->getPtrs()) { getValueName(d->getValue(), valName); out << "\\nPTR " << valName; } out << "\"];\n"; //<<" (runid=" << n->getDFSrun() << ")\"];\n"; } static void printBB(DependenceGraph *dg, BBlock *BB, std::ostream& out) { assert(BB); Node *n = BB->getFirstNode(); static unsigned int bbid = 0; if (!n) { std::string valName; getValueName(dg->getEntry()->getValue(), valName); errs() << "WARN no first value in a block for " << valName << "\n"; return; } out << "subgraph cluster_bb_" << bbid++; out << "{\n"; out << "\tstyle=dotted\n"; out << "label=\"BBlock " << BB; if (BB == dg->getEntryBB()) out << " |> ENTRY <|"; if (BB == dg->getExitBB()) out << " |> EXIT <|"; if (OPTIONS.printPostDom) { out << "\\n"; for (BBlock *b : BB->getPostdominates()) out << "\\nPDOM " << b; } out << "\"\n"; do { printNode(n, out); n = n->getSuccessor(); } while (n); out << "}\n"; } static void printNodesOnly(DependenceGraph *dg, std::ostream& out) { for (auto I = dg->begin(), E = dg->end(); I != E; ++I) { printNode(I->second, out); } } static void dg_print_edges(DependenceGraph *dg, std::ostream& out) { for (auto I = dg->begin(), E = dg->end(); I != E; ++I) { auto n = I->second; if (!n) { errs() << "WARN [" << dg << "]: Node is NULL for value: " << *I->first << "\n"; continue; } dump_to_dot(I->second, out); } // if this is a params dg, print edge from callsite to // this dg // add control edge from call-site to the parameters subgraph //out << "\tNODE" << n << " -> NODE" << params->getEntry() // << "[label=\"params\"]\n"; // // if this is a function, print edges here from callsites //for (auto sub : n->getSubgraphs()) { // out << "\tNODE" << n << " -> NODE" << sub->getEntry() // << " [style=dashed label=\"call\"]\n"; //} } static void print_to_dot(DependenceGraph *dg, std::ostream& out) { static unsigned subgraph_no = 0; const llvm::Value *val; std::string valName; if (!dg) return; out << "subgraph \"cluster_" << subgraph_no++; out << "\" {\n"; getValueName(dg->getEntry()->getValue(), valName); out << "label=\"<" << valName << ">"; out << "\\n Nodes: " << dg->size() << "\""; out << " style=\"solid\""; std::queue<BBlock *> queue; auto entryBB = dg->getEntryBB(); if (!entryBB) { errs() << "No entry block in graph for " << valName << "\n"; errs() << " ^^^ printing only nodes\n"; printNodesOnly(dg, out); out << "}\n"; return; } printNodesOnly(dg, out); unsigned int runid = entryBB->getDFSRunId(); ++runid; queue.push(dg->getEntryBB()); while (!queue.empty()) { auto BB = queue.front(); queue.pop(); BB->setDFSRunId(runid); printBB(dg, BB, out); for (auto S : BB->successors()) { if (S->getDFSRunId() != runid) queue.push(S); } } // print edges in dg dg_print_edges(dg, out); out << "}\n"; } int main(int argc, char *argv[]) { llvm::LLVMContext context; llvm::SMDiagnostic SMD; std::unique_ptr<llvm::Module> M; const char *module = NULL; // default OPTIONS.printControlDep = true; OPTIONS.printDataDep = true; // parse options for (int i = 1; i < argc; ++i) { if (strcmp(argv[i], "-no-control") == 0) { OPTIONS.printControlDep = false; } else if (strcmp(argv[i], "-no-data") == 0) { OPTIONS.printDataDep = false; } else if (strcmp(argv[i], "-bb") == 0) { OPTIONS.printBB = true; } else if (strcmp(argv[i], "-bbonly") == 0) { OPTIONS.printBB = true; OPTIONS.printBBonly = true; OPTIONS.printDataDep = false; } else if (strcmp(argv[i], "-cfg") == 0) { OPTIONS.printCFG = true; } else if (strcmp(argv[i], "-cfgall") == 0) { OPTIONS.printCFG = true; OPTIONS.printRevCFG = true; } else if (strcmp(argv[i], "-pd") == 0) { OPTIONS.printPostDom = true; } else { module = argv[i]; } } if (!module) { errs() << "Usage: % IR_module [output_file]\n"; return 1; } M = llvm::parseIRFile(module, SMD, context); if (!M) { SMD.print(argv[0], errs()); return 1; } DependenceGraph d; d.build(&*M); d.computePDTree(); std::ostream& out = std::cout; std::set<DependenceGraph *> printed; out << "digraph \"DependencyGraph\" {\n"; // print main procedure toPrint.push(&d); // print subgraphs that should be printed while (!toPrint.empty()) { auto sg = toPrint.front(); toPrint.pop(); if (printed.insert(sg).second) print_to_dot(sg, out); } out << "}\n"; return 0; } <|endoftext|>
<commit_before><commit_msg>iprevent violation of exception spec<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: graphicshapecontext.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2008-01-17 08:05:51 $ * * 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 * ************************************************************************/ #include <osl/diagnose.h> #include "oox/drawingml/fillpropertiesgroupcontext.hxx" #include "oox/drawingml/graphicshapecontext.hxx" #include "oox/drawingml/diagram/diagramfragmenthandler.hxx" #include "oox/core/namespaces.hxx" #include "oox/drawingml/drawingmltypes.hxx" #include "tokens.hxx" #ifndef _COMPHELPER_PROCESSFACTORY_HXX_ #include <comphelper/processfactory.hxx> #endif #include "com/sun/star/container/XNameAccess.hpp" #include "com/sun/star/io/XStream.hpp" #include "com/sun/star/beans/XPropertySet.hpp" #include "com/sun/star/document/XEmbeddedObjectResolver.hpp" #include <com/sun/star/graphic/XGraphicProvider.hpp> using ::rtl::OUString; using namespace ::com::sun::star; using namespace ::com::sun::star::io; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::beans; using namespace ::oox::core; using namespace ::com::sun::star::xml::sax; namespace oox { namespace drawingml { // ==================================================================== // CT_Picture GraphicShapeContext::GraphicShapeContext( const FragmentHandlerRef& xHandler, ShapePtr pMasterShapePtr, ShapePtr pShapePtr ) : ShapeContext( xHandler, pMasterShapePtr, pShapePtr ) { } Reference< XFastContextHandler > GraphicShapeContext::createFastChildContext( sal_Int32 aElementToken, const Reference< XFastAttributeList >& xAttribs ) throw (SAXException, RuntimeException) { Reference< XFastContextHandler > xRet; switch( aElementToken &(~NMSP_MASK) ) { // CT_ShapeProperties case XML_xfrm: xRet.set( new Transform2DContext( getHandler(), xAttribs, *(mpShapePtr.get()) ) ); break; case XML_blipFill: xRet.set( new BlipFillPropertiesContext( getHandler(), xAttribs, *(mpShapePtr->getGraphicProperties().get()) ) ); break; } if( !xRet.is() ) xRet.set( ShapeContext::createFastChildContext( aElementToken, xAttribs ) ); return xRet; } // ==================================================================== // CT_GraphicalObjectFrameContext GraphicalObjectFrameContext::GraphicalObjectFrameContext( const FragmentHandlerRef& xHandler, ShapePtr pMasterShapePtr, ShapePtr pShapePtr ) : ShapeContext( xHandler, pMasterShapePtr, pShapePtr ) { } Reference< XFastContextHandler > GraphicalObjectFrameContext::createFastChildContext( sal_Int32 aElementToken, const Reference< XFastAttributeList >& xAttribs ) throw (SAXException, RuntimeException) { Reference< XFastContextHandler > xRet; switch( aElementToken &(~NMSP_MASK) ) { // CT_ShapeProperties case XML_nvGraphicFramePr: // CT_GraphicalObjectFrameNonVisual break; case XML_xfrm: // CT_Transform2D xRet.set( new Transform2DContext( getHandler(), xAttribs, *(mpShapePtr.get()) ) ); break; case XML_graphic: // CT_GraphicalObject xRet.set( this ); break; case XML_graphicData : // CT_GraphicalObjectData { rtl::OUString sUri( xAttribs->getOptionalValue( XML_uri ) ); if ( sUri.compareToAscii( "http://schemas.openxmlformats.org/presentationml/2006/ole" ) == 0 ) xRet.set( new PresentationOle2006Context( mxHandler, mpShapePtr ) ); else if ( sUri.compareToAscii( "http://schemas.openxmlformats.org/drawingml/2006/diagram" ) == 0 ) xRet.set( new DiagramGraphicDataContext( mxHandler, mpShapePtr ) ); else if ( sUri.compareToAscii( "http://schemas.openxmlformats.org/drawingml/2006/table" ) == 0 ) // TODO deal with tables too. xRet.set( this ); else { OSL_TRACE( "OOX: Ignore graphicsData of %s", OUSTRING_TO_CSTR( sUri ) ); return xRet; } } break; } if( !xRet.is() ) xRet.set( ShapeContext::createFastChildContext( aElementToken, xAttribs ) ); return xRet; } // ==================================================================== PresentationOle2006Context::PresentationOle2006Context( const FragmentHandlerRef& xHandler, ShapePtr pShapePtr ) : ShapeContext( xHandler, ShapePtr(), pShapePtr ) { } PresentationOle2006Context::~PresentationOle2006Context() { XmlFilterRef xFilter = getHandler()->getFilter(); const OUString aFragmentPath = getHandler()->getFragmentPathFromRelId( msId ); if( aFragmentPath.getLength() > 0 ) { Reference< ::com::sun::star::io::XInputStream > xInputStream( xFilter->openInputStream( aFragmentPath ), UNO_QUERY_THROW ); Sequence< sal_Int8 > aData; xInputStream->readBytes( aData, 0x7fffffff ); uno::Reference< lang::XMultiServiceFactory > xMSF( xFilter->getModel(), UNO_QUERY ); Reference< com::sun::star::document::XEmbeddedObjectResolver > xEmbeddedResolver( xMSF->createInstance( OUString::createFromAscii( "com.sun.star.document.ImportEmbeddedObjectResolver" ) ), UNO_QUERY ); if ( xEmbeddedResolver.is() ) { Reference< com::sun::star::container::XNameAccess > xNA( xEmbeddedResolver, UNO_QUERY ); if( xNA.is() ) { Reference < XOutputStream > xOLEStream; OUString aURL = CREATE_OUSTRING( "Obj12345678" ); Any aAny( xNA->getByName( aURL ) ); aAny >>= xOLEStream; if ( xOLEStream.is() ) { xOLEStream->writeBytes( aData ); xOLEStream->closeOutput(); const OUString sProtocol = CREATE_OUSTRING( "vnd.sun.star.EmbeddedObject:" ); rtl::OUString aPersistName( xEmbeddedResolver->resolveEmbeddedObjectURL( aURL ) ); aPersistName = aPersistName.copy( sProtocol.getLength() ); static const OUString sPersistName = CREATE_OUSTRING( "PersistName" ); mpShapePtr->getShapeProperties()[ sPersistName ] <<= aPersistName; } } Reference< XComponent > xComp( xEmbeddedResolver, UNO_QUERY ); xComp->dispose(); } } // taking care of the representation graphic if ( msSpid.getLength() ) { oox::vml::DrawingPtr pDrawingPtr = xFilter->getDrawings(); if ( pDrawingPtr.get() ) { rtl::OUString aGraphicURL( pDrawingPtr->getGraphicUrlById( msSpid ) ); if ( aGraphicURL.getLength() ) { try { uno::Reference< lang::XMultiServiceFactory > xMSF( ::comphelper::getProcessServiceFactory() ); Reference< io::XInputStream > xInputStream( xFilter->openInputStream( aGraphicURL ), UNO_QUERY_THROW ); Reference< graphic::XGraphicProvider > xGraphicProvider( xMSF->createInstance( OUString::createFromAscii( "com.sun.star.graphic.GraphicProvider" ) ), UNO_QUERY_THROW ); if ( xInputStream.is() && xGraphicProvider.is() ) { Sequence< PropertyValue > aArgs( 1 ); const OUString sInputStream = CREATE_OUSTRING( "InputStream" ); aArgs[ 0 ].Name = sInputStream; aArgs[ 0 ].Value <<= xInputStream; Reference< graphic::XGraphic > xGraphic = xGraphicProvider->queryGraphic( aArgs ); if ( xGraphic.is() ) { static const OUString sEmptyGraphicURL; static const OUString sGraphicURL = CREATE_OUSTRING( "GraphicURL" ); mpShapePtr->getShapeProperties()[ sGraphicURL ] <<= sEmptyGraphicURL; static const OUString sThumbnailGraphic = CREATE_OUSTRING( "Graphic" ); mpShapePtr->getShapeProperties()[ sThumbnailGraphic ] <<= xGraphic; } } } catch( Exception& ) { } } } } } Reference< XFastContextHandler > PresentationOle2006Context::createFastChildContext( sal_Int32 aElementToken, const Reference< XFastAttributeList >& xAttribs ) throw (SAXException, RuntimeException) { Reference< XFastContextHandler > xRet; switch( aElementToken &(~NMSP_MASK) ) { case XML_oleObj: { msSpid = xAttribs->getOptionalValue( XML_spid ); msName = xAttribs->getOptionalValue( XML_name ); msId = xAttribs->getOptionalValue( NMSP_RELATIONSHIPS|XML_id ); mnWidth = GetCoordinate( xAttribs->getOptionalValue( XML_imgW ) ); mnHeight = GetCoordinate( xAttribs->getOptionalValue( XML_imgH ) ); msProgId = xAttribs->getOptionalValue( XML_progId ); } break; case XML_embed: { mnFollowColorSchemeToken = xAttribs->getOptionalValueToken( XML_followColorScheme, XML_full ); } break; } if( !xRet.is() ) xRet.set( ShapeContext::createFastChildContext( aElementToken, xAttribs ) ); return xRet; } DiagramGraphicDataContext::DiagramGraphicDataContext( const ::oox::core::FragmentHandlerRef& xHandler, ShapePtr pShapePtr ) : ShapeContext( xHandler, ShapePtr(), pShapePtr ) { } DiagramGraphicDataContext::~DiagramGraphicDataContext() { } DiagramPtr DiagramGraphicDataContext::loadDiagram() { DiagramPtr pDiagram( new Diagram() ); const oox::core::XmlFilterRef& xFilter( getHandler()->getFilter() ); // data OUString sDmPath = getHandler()->getFragmentPathFromRelId( msDm ); if( sDmPath.getLength() > 0 ) { DiagramDataPtr pData( new DiagramData() ); pDiagram->setData( pData ); xFilter->importFragment( new DiagramDataFragmentHandler( xFilter, sDmPath, pData ) ); } // layout OUString sLoPath = getHandler()->getFragmentPathFromRelId( msLo ); if( sLoPath.getLength() > 0 ) { DiagramLayoutPtr pLayout( new DiagramLayout() ); pDiagram->setLayout( pLayout ); xFilter->importFragment( new DiagramLayoutFragmentHandler( xFilter, sLoPath, pLayout ) ); } // style OUString sQsPath = getHandler()->getFragmentPathFromRelId( msQs ); if( sQsPath.getLength() > 0 ) { DiagramQStylesPtr pStyles( new DiagramQStyles() ); pDiagram->setQStyles( pStyles ); xFilter->importFragment( new DiagramQStylesFragmentHandler( xFilter, sQsPath, pStyles ) ); } // colors OUString sCsPath = getHandler()->getFragmentPathFromRelId( msCs ); if( sCsPath.getLength() > 0 ) { DiagramColorsPtr pColors( new DiagramColors() ); pDiagram->setColors( pColors ); xFilter->importFragment( new DiagramColorsFragmentHandler( xFilter, sCsPath, pColors ) ) ; } return pDiagram; } Reference< XFastContextHandler > DiagramGraphicDataContext::createFastChildContext( ::sal_Int32 aElementToken, const Reference< XFastAttributeList >& xAttribs ) throw (SAXException, RuntimeException) { Reference< XFastContextHandler > xRet; switch( aElementToken ) { case NMSP_DIAGRAM|XML_relIds: { msDm = xAttribs->getOptionalValue( NMSP_RELATIONSHIPS|XML_dm ); msLo = xAttribs->getOptionalValue( NMSP_RELATIONSHIPS|XML_lo ); msQs = xAttribs->getOptionalValue( NMSP_RELATIONSHIPS|XML_qs ); msCs = xAttribs->getOptionalValue( NMSP_RELATIONSHIPS|XML_cs ); DiagramPtr pDiagram = loadDiagram(); pDiagram->addTo( mpShapePtr ); break; } default: break; } if( !xRet.is() ) xRet.set( ShapeContext::createFastChildContext( aElementToken, xAttribs ) ); return xRet; } } } <commit_msg>INTEGRATION: CWS xmlfilter03_DEV300 (1.2.4); FILE MERGED 2008/02/06 20:51:11 hub 1.2.4.6: using get() to check a shared_ptr nullness is just bad style. 2008/02/05 14:09:00 dr 1.2.4.5: oox::core::ContextHandler2 and oox::core::FragmentHandler2 for convenience 2008/02/04 13:32:35 dr 1.2.4.4: rework of fragment handler/context handler base classes 2008/01/31 10:22:50 hbrinkm 1.2.4.3: handle vml shapes 2008/01/30 15:32:41 sj 1.2.4.2: using unique names for ole container 2008/01/24 22:01:50 hub 1.2.4.1: More work on SmartArt. Non-functionnal layout.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: graphicshapecontext.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: kz $ $Date: 2008-03-05 18:22:57 $ * * 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 * ************************************************************************/ #include <osl/diagnose.h> #include "oox/drawingml/fillpropertiesgroupcontext.hxx" #include "oox/drawingml/graphicshapecontext.hxx" #include "oox/drawingml/diagram/diagramfragmenthandler.hxx" #include "oox/core/namespaces.hxx" #include "oox/drawingml/drawingmltypes.hxx" #include "tokens.hxx" #include <comphelper/processfactory.hxx> #include "com/sun/star/container/XNameAccess.hpp" #include "com/sun/star/io/XStream.hpp" #include "com/sun/star/beans/XPropertySet.hpp" #include "com/sun/star/document/XEmbeddedObjectResolver.hpp" #include <com/sun/star/graphic/XGraphicProvider.hpp> using ::rtl::OUString; using namespace ::com::sun::star; using namespace ::com::sun::star::io; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::beans; using namespace ::oox::core; using namespace ::com::sun::star::xml::sax; namespace oox { namespace drawingml { // ==================================================================== // CT_Picture GraphicShapeContext::GraphicShapeContext( ContextHandler& rParent, ShapePtr pMasterShapePtr, ShapePtr pShapePtr ) : ShapeContext( rParent, pMasterShapePtr, pShapePtr ) { } Reference< XFastContextHandler > GraphicShapeContext::createFastChildContext( sal_Int32 aElementToken, const Reference< XFastAttributeList >& xAttribs ) throw (SAXException, RuntimeException) { Reference< XFastContextHandler > xRet; switch( getToken( aElementToken ) ) { // CT_ShapeProperties case XML_xfrm: xRet.set( new Transform2DContext( *this, xAttribs, *mpShapePtr ) ); break; case XML_blipFill: xRet.set( new BlipFillPropertiesContext( *this, xAttribs, *mpShapePtr->getGraphicProperties() ) ); break; } if (getNamespace( aElementToken ) == NMSP_VML && mpShapePtr) { mpShapePtr->setServiceName("com.sun.star.drawing.CustomShape"); CustomShapePropertiesPtr pCstmShpProps (mpShapePtr->getCustomShapeProperties()); sal_uInt32 nType = aElementToken & (~ NMSP_MASK); OUString sType(GetShapeType(nType)); if (sType.getLength() > 0) pCstmShpProps->setShapePresetType(sType); } if( !xRet.is() ) xRet.set( ShapeContext::createFastChildContext( aElementToken, xAttribs ) ); return xRet; } // ==================================================================== // CT_GraphicalObjectFrameContext GraphicalObjectFrameContext::GraphicalObjectFrameContext( ContextHandler& rParent, ShapePtr pMasterShapePtr, ShapePtr pShapePtr ) : ShapeContext( rParent, pMasterShapePtr, pShapePtr ) { } Reference< XFastContextHandler > GraphicalObjectFrameContext::createFastChildContext( sal_Int32 aElementToken, const Reference< XFastAttributeList >& xAttribs ) throw (SAXException, RuntimeException) { Reference< XFastContextHandler > xRet; switch( aElementToken &(~NMSP_MASK) ) { // CT_ShapeProperties case XML_nvGraphicFramePr: // CT_GraphicalObjectFrameNonVisual break; case XML_xfrm: // CT_Transform2D xRet.set( new Transform2DContext( *this, xAttribs, *mpShapePtr ) ); break; case XML_graphic: // CT_GraphicalObject xRet.set( this ); break; case XML_graphicData : // CT_GraphicalObjectData { rtl::OUString sUri( xAttribs->getOptionalValue( XML_uri ) ); if ( sUri.compareToAscii( "http://schemas.openxmlformats.org/presentationml/2006/ole" ) == 0 ) xRet.set( new PresentationOle2006Context( *this, mpShapePtr ) ); else if ( sUri.compareToAscii( "http://schemas.openxmlformats.org/drawingml/2006/diagram" ) == 0 ) xRet.set( new DiagramGraphicDataContext( *this, mpShapePtr ) ); else if ( sUri.compareToAscii( "http://schemas.openxmlformats.org/drawingml/2006/table" ) == 0 ) // TODO deal with tables too. xRet.set( this ); else { OSL_TRACE( "OOX: Ignore graphicsData of %s", OUSTRING_TO_CSTR( sUri ) ); return xRet; } } break; } if( !xRet.is() ) xRet.set( ShapeContext::createFastChildContext( aElementToken, xAttribs ) ); return xRet; } // ==================================================================== PresentationOle2006Context::PresentationOle2006Context( ContextHandler& rParent, ShapePtr pShapePtr ) : ShapeContext( rParent, ShapePtr(), pShapePtr ) { } PresentationOle2006Context::~PresentationOle2006Context() { static sal_Int32 nObjectCount = 100; XmlFilterBase& rFilter = getFilter(); const OUString aFragmentPath = getFragmentPathFromRelId( msId ); if( aFragmentPath.getLength() > 0 ) { Reference< ::com::sun::star::io::XInputStream > xInputStream( rFilter.openInputStream( aFragmentPath ), UNO_QUERY_THROW ); Sequence< sal_Int8 > aData; xInputStream->readBytes( aData, 0x7fffffff ); uno::Reference< lang::XMultiServiceFactory > xMSF( rFilter.getModel(), UNO_QUERY ); Reference< com::sun::star::document::XEmbeddedObjectResolver > xEmbeddedResolver( xMSF->createInstance( OUString::createFromAscii( "com.sun.star.document.ImportEmbeddedObjectResolver" ) ), UNO_QUERY ); if ( xEmbeddedResolver.is() ) { Reference< com::sun::star::container::XNameAccess > xNA( xEmbeddedResolver, UNO_QUERY ); if( xNA.is() ) { Reference < XOutputStream > xOLEStream; const OUString sObj( RTL_CONSTASCII_USTRINGPARAM( "Obj" ) ); OUString aURL( sObj.concat( rtl::OUString::valueOf( nObjectCount++ ) ) ); Any aAny( xNA->getByName( aURL ) ); aAny >>= xOLEStream; if ( xOLEStream.is() ) { xOLEStream->writeBytes( aData ); xOLEStream->closeOutput(); const OUString sProtocol = CREATE_OUSTRING( "vnd.sun.star.EmbeddedObject:" ); rtl::OUString aPersistName( xEmbeddedResolver->resolveEmbeddedObjectURL( aURL ) ); aPersistName = aPersistName.copy( sProtocol.getLength() ); static const OUString sPersistName = CREATE_OUSTRING( "PersistName" ); mpShapePtr->getShapeProperties()[ sPersistName ] <<= aPersistName; } } Reference< XComponent > xComp( xEmbeddedResolver, UNO_QUERY ); xComp->dispose(); } } // taking care of the representation graphic if ( msSpid.getLength() ) { oox::vml::DrawingPtr pDrawingPtr = rFilter.getDrawings(); if ( pDrawingPtr ) { rtl::OUString aGraphicURL( pDrawingPtr->getGraphicUrlById( msSpid ) ); if ( aGraphicURL.getLength() ) { try { uno::Reference< lang::XMultiServiceFactory > xMSF( ::comphelper::getProcessServiceFactory() ); Reference< io::XInputStream > xInputStream( rFilter.openInputStream( aGraphicURL ), UNO_QUERY_THROW ); Reference< graphic::XGraphicProvider > xGraphicProvider( xMSF->createInstance( OUString::createFromAscii( "com.sun.star.graphic.GraphicProvider" ) ), UNO_QUERY_THROW ); if ( xInputStream.is() && xGraphicProvider.is() ) { Sequence< PropertyValue > aArgs( 1 ); const OUString sInputStream = CREATE_OUSTRING( "InputStream" ); aArgs[ 0 ].Name = sInputStream; aArgs[ 0 ].Value <<= xInputStream; Reference< graphic::XGraphic > xGraphic = xGraphicProvider->queryGraphic( aArgs ); if ( xGraphic.is() ) { static const OUString sEmptyGraphicURL; static const OUString sGraphicURL = CREATE_OUSTRING( "GraphicURL" ); mpShapePtr->getShapeProperties()[ sGraphicURL ] <<= sEmptyGraphicURL; static const OUString sThumbnailGraphic = CREATE_OUSTRING( "Graphic" ); mpShapePtr->getShapeProperties()[ sThumbnailGraphic ] <<= xGraphic; } } } catch( Exception& ) { } } } } } Reference< XFastContextHandler > PresentationOle2006Context::createFastChildContext( sal_Int32 aElementToken, const Reference< XFastAttributeList >& xAttribs ) throw (SAXException, RuntimeException) { Reference< XFastContextHandler > xRet; switch( aElementToken &(~NMSP_MASK) ) { case XML_oleObj: { msSpid = xAttribs->getOptionalValue( XML_spid ); msName = xAttribs->getOptionalValue( XML_name ); msId = xAttribs->getOptionalValue( NMSP_RELATIONSHIPS|XML_id ); mnWidth = GetCoordinate( xAttribs->getOptionalValue( XML_imgW ) ); mnHeight = GetCoordinate( xAttribs->getOptionalValue( XML_imgH ) ); msProgId = xAttribs->getOptionalValue( XML_progId ); } break; case XML_embed: { mnFollowColorSchemeToken = xAttribs->getOptionalValueToken( XML_followColorScheme, XML_full ); } break; } if( !xRet.is() ) xRet.set( ShapeContext::createFastChildContext( aElementToken, xAttribs ) ); return xRet; } DiagramGraphicDataContext::DiagramGraphicDataContext( ContextHandler& rParent, ShapePtr pShapePtr ) : ShapeContext( rParent, ShapePtr(), pShapePtr ) { pShapePtr->setServiceName( "com.sun.star.drawing.GroupShape" ); pShapePtr->setSubType( 0 ); } DiagramGraphicDataContext::~DiagramGraphicDataContext() { } DiagramPtr DiagramGraphicDataContext::loadDiagram() { DiagramPtr pDiagram( new Diagram() ); XmlFilterBase& rFilter = getFilter(); // data OUString sDmPath = getFragmentPathFromRelId( msDm ); if( sDmPath.getLength() > 0 ) { DiagramDataPtr pData( new DiagramData() ); pDiagram->setData( pData ); rFilter.importFragment( new DiagramDataFragmentHandler( rFilter, sDmPath, pData ) ); } // layout OUString sLoPath = getFragmentPathFromRelId( msLo ); if( sLoPath.getLength() > 0 ) { DiagramLayoutPtr pLayout( new DiagramLayout() ); pDiagram->setLayout( pLayout ); rFilter.importFragment( new DiagramLayoutFragmentHandler( rFilter, sLoPath, pLayout ) ); } // style OUString sQsPath = getFragmentPathFromRelId( msQs ); if( sQsPath.getLength() > 0 ) { DiagramQStylesPtr pStyles( new DiagramQStyles() ); pDiagram->setQStyles( pStyles ); rFilter.importFragment( new DiagramQStylesFragmentHandler( rFilter, sQsPath, pStyles ) ); } // colors OUString sCsPath = getFragmentPathFromRelId( msCs ); if( sCsPath.getLength() > 0 ) { DiagramColorsPtr pColors( new DiagramColors() ); pDiagram->setColors( pColors ); rFilter.importFragment( new DiagramColorsFragmentHandler( rFilter, sCsPath, pColors ) ) ; } return pDiagram; } Reference< XFastContextHandler > DiagramGraphicDataContext::createFastChildContext( ::sal_Int32 aElementToken, const Reference< XFastAttributeList >& xAttribs ) throw (SAXException, RuntimeException) { Reference< XFastContextHandler > xRet; switch( aElementToken ) { case NMSP_DIAGRAM|XML_relIds: { msDm = xAttribs->getOptionalValue( NMSP_RELATIONSHIPS|XML_dm ); msLo = xAttribs->getOptionalValue( NMSP_RELATIONSHIPS|XML_lo ); msQs = xAttribs->getOptionalValue( NMSP_RELATIONSHIPS|XML_qs ); msCs = xAttribs->getOptionalValue( NMSP_RELATIONSHIPS|XML_cs ); DiagramPtr pDiagram = loadDiagram(); pDiagram->addTo( mpShapePtr ); OSL_TRACE("diagram added shape %s of type %s", OUSTRING_TO_CSTR( mpShapePtr->getName() ), OUSTRING_TO_CSTR( mpShapePtr->getServiceName() ) ); break; } default: break; } if( !xRet.is() ) xRet.set( ShapeContext::createFastChildContext( aElementToken, xAttribs ) ); return xRet; } } } <|endoftext|>
<commit_before>#include "pixelboost/audio/soundManager.h" #include "pixelboost/debug/debugVariableManager.h" #include "pixelboost/graphics/device/device.h" #include "pixelboost/graphics/render/common/renderer.h" #include "pixelboost/graphics/render/custom/customRenderer.h" #include "pixelboost/graphics/render/font/fontRenderer.h" #include "pixelboost/graphics/render/model/modelRenderer.h" #include "pixelboost/graphics/render/particle/particleRenderer.h" #include "pixelboost/graphics/render/primitive/primitiveRenderer.h" #include "pixelboost/graphics/render/sprite/spriteRenderer.h" #include "pixelboost/input/touchManager.h" #include "pixelboost/logic/game.h" #include "pixelboost/logic/screen.h" #include "pixelboost/network/gameCenter.h" #include "pixelboost/network/networkServer.h" namespace pixelboost { Game* Game::_Instance = 0; Game::Game(void* viewController) : _GameTime(0) , _TotalTime(0) , _ViewController(viewController) { _Instance = this; _TouchManager = new TouchManager(); _GameCenter = new GameCenter(); _CustomRenderer = new CustomRenderer(); _FontRenderer = new FontRenderer(); _ModelRenderer = new ModelRenderer(); _ParticleRenderer = new ParticleRenderer(); _PrimitiveRenderer = new PrimitiveRenderer(); _Renderer = new Renderer(); _SpriteRenderer = new SpriteRenderer(); _Renderer->AddRenderer(_SpriteRenderer); _Renderer->AddRenderer(_CustomRenderer); _Renderer->AddRenderer(_ParticleRenderer); _Renderer->AddRenderer(_PrimitiveRenderer); _Renderer->AddRenderer(_FontRenderer); _SoundManager = new SoundManager(); #ifndef PIXELBOOST_DISABLE_GAMECENTER _GameCenter->Connect(); #endif } Game::~Game() { _Instance = 0; _Renderer->RemoveRenderer(_CustomRenderer); _Renderer->RemoveRenderer(_ParticleRenderer); _Renderer->RemoveRenderer(_PrimitiveRenderer); _Renderer->RemoveRenderer(_SpriteRenderer); delete _CustomRenderer; delete _FontRenderer; delete _GameCenter; delete _ModelRenderer; delete _ParticleRenderer; delete _PrimitiveRenderer; delete _Renderer; delete _ResourceManager; delete _SoundManager; delete _SpriteRenderer; delete _TouchManager; } Game* Game::Instance() { return _Instance; } void Game::Initialise() { } CustomRenderer* Game::GetCustomRenderer() const { return _CustomRenderer; } FontRenderer* Game::GetFontRenderer() const { return _FontRenderer; } GameCenter* Game::GetGameCenter() const { return _GameCenter; } ModelRenderer* Game::GetModelRenderer() const { return _ModelRenderer; } ResourceManager* Game::GetResourceManager() const { return _ResourceManager; } ParticleRenderer* Game::GetParticleRenderer() const { return _ParticleRenderer; } PrimitiveRenderer* Game::GetPrimitiveRenderer() const { return _PrimitiveRenderer; } Renderer* Game::GetRenderer() const { return _Renderer; } SoundManager* Game::GetSoundManager() const { return _SoundManager; } SpriteRenderer* Game::GetSpriteRenderer() const { return _SpriteRenderer; } TouchManager* Game::GetTouchManager() const { return _TouchManager; } float Game::GetGameTime() { return _GameTime; } float Game::GetTotalTime() { return _TotalTime; } bool Game::IsLandscape() { return false; } void Game::Update(float time) { _GameTime += time; _TotalTime += time; _Renderer->Update(time); } void Game::Render() { _Renderer->Render(); } void* Game::GetViewController() { return _ViewController; } } <commit_msg>Resource manager is never created, no need to delete<commit_after>#include "pixelboost/audio/soundManager.h" #include "pixelboost/debug/debugVariableManager.h" #include "pixelboost/graphics/device/device.h" #include "pixelboost/graphics/render/common/renderer.h" #include "pixelboost/graphics/render/custom/customRenderer.h" #include "pixelboost/graphics/render/font/fontRenderer.h" #include "pixelboost/graphics/render/model/modelRenderer.h" #include "pixelboost/graphics/render/particle/particleRenderer.h" #include "pixelboost/graphics/render/primitive/primitiveRenderer.h" #include "pixelboost/graphics/render/sprite/spriteRenderer.h" #include "pixelboost/input/touchManager.h" #include "pixelboost/logic/game.h" #include "pixelboost/logic/screen.h" #include "pixelboost/network/gameCenter.h" #include "pixelboost/network/networkServer.h" namespace pixelboost { Game* Game::_Instance = 0; Game::Game(void* viewController) : _GameTime(0) , _TotalTime(0) , _ViewController(viewController) { _Instance = this; _TouchManager = new TouchManager(); _GameCenter = new GameCenter(); _CustomRenderer = new CustomRenderer(); _FontRenderer = new FontRenderer(); _ModelRenderer = new ModelRenderer(); _ParticleRenderer = new ParticleRenderer(); _PrimitiveRenderer = new PrimitiveRenderer(); _Renderer = new Renderer(); _SpriteRenderer = new SpriteRenderer(); _Renderer->AddRenderer(_SpriteRenderer); _Renderer->AddRenderer(_CustomRenderer); _Renderer->AddRenderer(_ParticleRenderer); _Renderer->AddRenderer(_PrimitiveRenderer); _Renderer->AddRenderer(_FontRenderer); _SoundManager = new SoundManager(); #ifndef PIXELBOOST_DISABLE_GAMECENTER _GameCenter->Connect(); #endif } Game::~Game() { _Instance = 0; _Renderer->RemoveRenderer(_CustomRenderer); _Renderer->RemoveRenderer(_ParticleRenderer); _Renderer->RemoveRenderer(_PrimitiveRenderer); _Renderer->RemoveRenderer(_SpriteRenderer); delete _CustomRenderer; delete _FontRenderer; delete _GameCenter; delete _ModelRenderer; delete _ParticleRenderer; delete _PrimitiveRenderer; delete _Renderer; delete _SoundManager; delete _SpriteRenderer; delete _TouchManager; } Game* Game::Instance() { return _Instance; } void Game::Initialise() { } CustomRenderer* Game::GetCustomRenderer() const { return _CustomRenderer; } FontRenderer* Game::GetFontRenderer() const { return _FontRenderer; } GameCenter* Game::GetGameCenter() const { return _GameCenter; } ModelRenderer* Game::GetModelRenderer() const { return _ModelRenderer; } ResourceManager* Game::GetResourceManager() const { return _ResourceManager; } ParticleRenderer* Game::GetParticleRenderer() const { return _ParticleRenderer; } PrimitiveRenderer* Game::GetPrimitiveRenderer() const { return _PrimitiveRenderer; } Renderer* Game::GetRenderer() const { return _Renderer; } SoundManager* Game::GetSoundManager() const { return _SoundManager; } SpriteRenderer* Game::GetSpriteRenderer() const { return _SpriteRenderer; } TouchManager* Game::GetTouchManager() const { return _TouchManager; } float Game::GetGameTime() { return _GameTime; } float Game::GetTotalTime() { return _TotalTime; } bool Game::IsLandscape() { return false; } void Game::Update(float time) { _GameTime += time; _TotalTime += time; _Renderer->Update(time); } void Game::Render() { _Renderer->Render(); } void* Game::GetViewController() { return _ViewController; } } <|endoftext|>
<commit_before>// // Copyright © 2017 Arm Ltd. All rights reserved. // SPDX-License-Identifier: MIT // #include "ArmnnDriverImpl.hpp" #include "../ArmnnPreparedModel_1_2.hpp" #include "../ModelToINetworkConverter.hpp" #include "../SystemPropertiesUtils.hpp" #include <log/log.h> namespace { const char *g_RelaxedFloat32toFloat16PerformanceExecTime = "ArmNN.relaxedFloat32toFloat16Performance.execTime"; const char *g_OperandTypeTensorFloat32PerformanceExecTime = "Armnn.operandTypeTensorFloat32Performance.execTime"; const char *g_OperandTypeTensorFloat32PerformancePowerUsage = "Armnn.operandTypeTensorFloat32Performance.powerUsage"; const char *g_OperandTypeFloat32PerformanceExecTime = "Armnn.operandTypeFloat32Performance.execTime"; const char *g_OperandTypeFloat32PerformancePowerUsage = "Armnn.operandTypeFloat32Performance.powerUsage"; const char *g_OperandTypeTensorFloat16PerformanceExecTime = "Armnn.operandTypeTensorFloat16Performance.execTime"; const char *g_OperandTypeTensorFloat16PerformancePowerUsage = "Armnn.operandTypeTensorFloat16Performance.powerUsage"; const char *g_OperandTypeFloat16PerformanceExecTime = "Armnn.operandTypeFloat16Performance.execTime"; const char *g_OperandTypeFloat16PerformancePowerUsage = "Armnn.operandTypeFloat16Performance.powerUsage"; const char *g_OperandTypeTensorQuant8AsymmPerformanceExecTime = "Armnn.operandTypeTensorQuant8AsymmPerformance.execTime"; const char *g_OperandTypeTensorQuant8AsymmPerformancePowerUsage = "Armnn.operandTypeTensorQuant8AsymmPerformance.powerUsage"; const char *g_OperandTypeTensorQuant16SymmPerformanceExecTime = "Armnn.operandTypeTensorQuant16SymmPerformance.execTime"; const char *g_OperandTypeTensorQuant16SymmPerformancePowerUsage = "Armnn.operandTypeTensorQuant16SymmPerformance.powerUsage"; const char *g_OperandTypeTensorInt32PerformanceExecTime = "Armnn.operandTypeTensorInt32Performance.execTime"; const char *g_OperandTypeTensorInt32PerformancePowerUsage = "Armnn.operandTypeTensorInt32Performance.powerUsage"; const char *g_OperandTypeInt32PerformanceExecTime = "Armnn.operandTypeInt32Performance.execTime"; const char *g_OperandTypeInt32PerformancePowerUsage = "Armnn.operandTypeInt32Performance.powerUsage"; void NotifyCallbackAndCheck(const sp<V1_2::IPreparedModelCallback>& callback, ErrorStatus errorStatus, const sp<V1_2::IPreparedModel>& preparedModelPtr) { Return<void> returned = callback->notify(errorStatus, preparedModelPtr); // This check is required, if the callback fails and it isn't checked it will bring down the service if (!returned.isOk()) { ALOGE("ArmnnDriverImpl::prepareModel: hidl callback failed to return properly: %s ", returned.description().c_str()); } } Return<ErrorStatus> FailPrepareModel(ErrorStatus error, const std::string& message, const sp<V1_2::IPreparedModelCallback>& callback) { ALOGW("ArmnnDriverImpl::prepareModel: %s", message.c_str()); NotifyCallbackAndCheck(callback, error, nullptr); return error; } } // anonymous namespace namespace armnn_driver { namespace hal_1_2 { Return<ErrorStatus> ArmnnDriverImpl::prepareArmnnModel_1_2(const armnn::IRuntimePtr& runtime, const armnn::IGpuAccTunedParametersPtr& clTunedParameters, const DriverOptions& options, const V1_2::Model& model, const sp<V1_2::IPreparedModelCallback>& cb, bool float32ToFloat16) { ALOGV("ArmnnDriverImpl::prepareArmnnModel_1_2()"); if (cb.get() == nullptr) { ALOGW("ArmnnDriverImpl::prepareModel: Invalid callback passed to prepareModel"); return ErrorStatus::INVALID_ARGUMENT; } if (!runtime) { return FailPrepareModel(ErrorStatus::DEVICE_UNAVAILABLE, "Device unavailable", cb); } if (!android::nn::validateModel(model)) { return FailPrepareModel(ErrorStatus::INVALID_ARGUMENT, "Invalid model passed as input", cb); } // Deliberately ignore any unsupported operations requested by the options - // at this point we're being asked to prepare a model that we've already declared support for // and the operation indices may be different to those in getSupportedOperations anyway. std::set<unsigned int> unsupportedOperations; ModelToINetworkConverter<HalPolicy> modelConverter(options.GetBackends(), model, unsupportedOperations); if (modelConverter.GetConversionResult() != ConversionResult::Success) { FailPrepareModel(ErrorStatus::GENERAL_FAILURE, "ModelToINetworkConverter failed", cb); return ErrorStatus::NONE; } // Optimize the network armnn::IOptimizedNetworkPtr optNet(nullptr, nullptr); armnn::OptimizerOptions OptOptions; OptOptions.m_ReduceFp32ToFp16 = float32ToFloat16; std::vector<std::string> errMessages; try { optNet = armnn::Optimize(*modelConverter.GetINetwork(), options.GetBackends(), runtime->GetDeviceSpec(), OptOptions, errMessages); } catch (armnn::Exception &e) { std::stringstream message; message << "armnn::Exception (" << e.what() << ") caught from optimize."; FailPrepareModel(ErrorStatus::GENERAL_FAILURE, message.str(), cb); return ErrorStatus::NONE; } // Check that the optimized network is valid. if (!optNet) { std::stringstream message; message << "Invalid optimized network"; for (const std::string& msg : errMessages) { message << "\n" << msg; } FailPrepareModel(ErrorStatus::GENERAL_FAILURE, message.str(), cb); return ErrorStatus::NONE; } // Export the optimized network graph to a dot file if an output dump directory // has been specified in the drivers' arguments. ExportNetworkGraphToDotFile<hal_1_2::HalPolicy::Model>(*optNet, options.GetRequestInputsAndOutputsDumpDir(), model); // Load it into the runtime. armnn::NetworkId netId = 0; try { if (runtime->LoadNetwork(netId, move(optNet)) != armnn::Status::Success) { return FailPrepareModel(ErrorStatus::GENERAL_FAILURE, "Network could not be loaded", cb); } } catch (armnn::Exception& e) { std::stringstream message; message << "armnn::Exception (" << e.what()<< ") caught from LoadNetwork."; FailPrepareModel(ErrorStatus::GENERAL_FAILURE, message.str(), cb); return ErrorStatus::NONE; } std::unique_ptr<ArmnnPreparedModel_1_2<hal_1_2::HalPolicy>> preparedModel( new ArmnnPreparedModel_1_2<hal_1_2::HalPolicy>( netId, runtime.get(), model, options.GetRequestInputsAndOutputsDumpDir(), options.IsGpuProfilingEnabled())); // Run a single 'dummy' inference of the model. This means that CL kernels will get compiled (and tuned if // this is enabled) before the first 'real' inference which removes the overhead of the first inference. if (!preparedModel->ExecuteWithDummyInputs()) { return FailPrepareModel(ErrorStatus::GENERAL_FAILURE, "Network could not be executed", cb); } if (clTunedParameters && options.GetClTunedParametersMode() == armnn::IGpuAccTunedParameters::Mode::UpdateTunedParameters) { // Now that we've done one inference the CL kernel parameters will have been tuned, so save the updated file. try { clTunedParameters->Save(options.GetClTunedParametersFile().c_str()); } catch (const armnn::Exception& error) { ALOGE("ArmnnDriverImpl::prepareModel: Failed to save CL tuned parameters file '%s': %s", options.GetClTunedParametersFile().c_str(), error.what()); } } NotifyCallbackAndCheck(cb, ErrorStatus::NONE, preparedModel.release()); return ErrorStatus::NONE; } Return<void> ArmnnDriverImpl::getCapabilities_1_2(const armnn::IRuntimePtr& runtime, V1_2::IDevice::getCapabilities_1_2_cb cb) { ALOGV("hal_1_2::ArmnnDriverImpl::getCapabilities()"); V1_2::Capabilities capabilities; float defaultValue = .1f; if (runtime) { capabilities.relaxedFloat32toFloat16PerformanceScalar.execTime = ParseSystemProperty(g_RelaxedFloat32toFloat16PerformanceExecTime, defaultValue); capabilities.relaxedFloat32toFloat16PerformanceTensor.execTime = ParseSystemProperty(g_RelaxedFloat32toFloat16PerformanceExecTime, defaultValue); // Set the base value for all operand types capabilities.operandPerformance = nonExtensionOperandPerformance({FLT_MAX, FLT_MAX}); // Load supported operand types update(&capabilities.operandPerformance, OperandType::TENSOR_FLOAT32, { .execTime = ParseSystemProperty(g_OperandTypeTensorFloat32PerformanceExecTime, defaultValue), .powerUsage = ParseSystemProperty(g_OperandTypeTensorFloat32PerformancePowerUsage, defaultValue) }); update(&capabilities.operandPerformance, OperandType::FLOAT32, { .execTime = ParseSystemProperty(g_OperandTypeFloat32PerformanceExecTime, defaultValue), .powerUsage = ParseSystemProperty(g_OperandTypeFloat32PerformancePowerUsage, defaultValue) }); update(&capabilities.operandPerformance, OperandType::TENSOR_FLOAT16, { .execTime = ParseSystemProperty(g_OperandTypeTensorFloat16PerformanceExecTime, defaultValue), .powerUsage = ParseSystemProperty(g_OperandTypeTensorFloat16PerformancePowerUsage, defaultValue) }); update(&capabilities.operandPerformance, OperandType::FLOAT16, { .execTime = ParseSystemProperty(g_OperandTypeFloat16PerformanceExecTime, defaultValue), .powerUsage = ParseSystemProperty(g_OperandTypeFloat16PerformancePowerUsage, defaultValue) }); update(&capabilities.operandPerformance, OperandType::TENSOR_QUANT8_ASYMM, { .execTime = ParseSystemProperty(g_OperandTypeTensorQuant8AsymmPerformanceExecTime, defaultValue), .powerUsage = ParseSystemProperty(g_OperandTypeTensorQuant8AsymmPerformancePowerUsage, defaultValue) }); update(&capabilities.operandPerformance, OperandType::TENSOR_QUANT16_SYMM, { .execTime = ParseSystemProperty(g_OperandTypeTensorQuant16SymmPerformanceExecTime, defaultValue), .powerUsage = ParseSystemProperty(g_OperandTypeTensorQuant16SymmPerformancePowerUsage, defaultValue) }); update(&capabilities.operandPerformance, OperandType::TENSOR_INT32, { .execTime = ParseSystemProperty(g_OperandTypeTensorInt32PerformanceExecTime, defaultValue), .powerUsage = ParseSystemProperty(g_OperandTypeTensorInt32PerformancePowerUsage, defaultValue) }); update(&capabilities.operandPerformance, OperandType::INT32, { .execTime = ParseSystemProperty(g_OperandTypeInt32PerformanceExecTime, defaultValue), .powerUsage = ParseSystemProperty(g_OperandTypeInt32PerformancePowerUsage, defaultValue) }); cb(ErrorStatus::NONE, capabilities); } else { capabilities.relaxedFloat32toFloat16PerformanceScalar.execTime = 0; capabilities.relaxedFloat32toFloat16PerformanceTensor.execTime = 0; // Set the base value for all operand types capabilities.operandPerformance = nonExtensionOperandPerformance({0.f, 0.0f}); cb(ErrorStatus::DEVICE_UNAVAILABLE, capabilities); } return Void(); } } // namespace hal_1_2 } // namespace armnn_driver <commit_msg>IVGCVSW-3496 Fix VTS NeuralnetworksHidlTest.GetCapabilitiesTest<commit_after>// // Copyright © 2017 Arm Ltd. All rights reserved. // SPDX-License-Identifier: MIT // #include "ArmnnDriverImpl.hpp" #include "../ArmnnPreparedModel_1_2.hpp" #include "../ModelToINetworkConverter.hpp" #include "../SystemPropertiesUtils.hpp" #include <log/log.h> namespace { const char *g_RelaxedFloat32toFloat16PerformanceExecTime = "ArmNN.relaxedFloat32toFloat16Performance.execTime"; const char *g_RelaxedFloat32toFloat16PerformancePowerUsage = "ArmNN.relaxedFloat32toFloat16Performance.powerUsage"; const char *g_OperandTypeTensorFloat32PerformanceExecTime = "Armnn.operandTypeTensorFloat32Performance.execTime"; const char *g_OperandTypeTensorFloat32PerformancePowerUsage = "Armnn.operandTypeTensorFloat32Performance.powerUsage"; const char *g_OperandTypeFloat32PerformanceExecTime = "Armnn.operandTypeFloat32Performance.execTime"; const char *g_OperandTypeFloat32PerformancePowerUsage = "Armnn.operandTypeFloat32Performance.powerUsage"; const char *g_OperandTypeTensorFloat16PerformanceExecTime = "Armnn.operandTypeTensorFloat16Performance.execTime"; const char *g_OperandTypeTensorFloat16PerformancePowerUsage = "Armnn.operandTypeTensorFloat16Performance.powerUsage"; const char *g_OperandTypeFloat16PerformanceExecTime = "Armnn.operandTypeFloat16Performance.execTime"; const char *g_OperandTypeFloat16PerformancePowerUsage = "Armnn.operandTypeFloat16Performance.powerUsage"; const char *g_OperandTypeTensorQuant8AsymmPerformanceExecTime = "Armnn.operandTypeTensorQuant8AsymmPerformance.execTime"; const char *g_OperandTypeTensorQuant8AsymmPerformancePowerUsage = "Armnn.operandTypeTensorQuant8AsymmPerformance.powerUsage"; const char *g_OperandTypeTensorQuant16SymmPerformanceExecTime = "Armnn.operandTypeTensorQuant16SymmPerformance.execTime"; const char *g_OperandTypeTensorQuant16SymmPerformancePowerUsage = "Armnn.operandTypeTensorQuant16SymmPerformance.powerUsage"; const char *g_OperandTypeTensorInt32PerformanceExecTime = "Armnn.operandTypeTensorInt32Performance.execTime"; const char *g_OperandTypeTensorInt32PerformancePowerUsage = "Armnn.operandTypeTensorInt32Performance.powerUsage"; const char *g_OperandTypeInt32PerformanceExecTime = "Armnn.operandTypeInt32Performance.execTime"; const char *g_OperandTypeInt32PerformancePowerUsage = "Armnn.operandTypeInt32Performance.powerUsage"; void NotifyCallbackAndCheck(const sp<V1_2::IPreparedModelCallback>& callback, ErrorStatus errorStatus, const sp<V1_2::IPreparedModel>& preparedModelPtr) { Return<void> returned = callback->notify(errorStatus, preparedModelPtr); // This check is required, if the callback fails and it isn't checked it will bring down the service if (!returned.isOk()) { ALOGE("ArmnnDriverImpl::prepareModel: hidl callback failed to return properly: %s ", returned.description().c_str()); } } Return<ErrorStatus> FailPrepareModel(ErrorStatus error, const std::string& message, const sp<V1_2::IPreparedModelCallback>& callback) { ALOGW("ArmnnDriverImpl::prepareModel: %s", message.c_str()); NotifyCallbackAndCheck(callback, error, nullptr); return error; } } // anonymous namespace namespace armnn_driver { namespace hal_1_2 { Return<ErrorStatus> ArmnnDriverImpl::prepareArmnnModel_1_2(const armnn::IRuntimePtr& runtime, const armnn::IGpuAccTunedParametersPtr& clTunedParameters, const DriverOptions& options, const V1_2::Model& model, const sp<V1_2::IPreparedModelCallback>& cb, bool float32ToFloat16) { ALOGV("ArmnnDriverImpl::prepareArmnnModel_1_2()"); if (cb.get() == nullptr) { ALOGW("ArmnnDriverImpl::prepareModel: Invalid callback passed to prepareModel"); return ErrorStatus::INVALID_ARGUMENT; } if (!runtime) { return FailPrepareModel(ErrorStatus::DEVICE_UNAVAILABLE, "Device unavailable", cb); } if (!android::nn::validateModel(model)) { return FailPrepareModel(ErrorStatus::INVALID_ARGUMENT, "Invalid model passed as input", cb); } // Deliberately ignore any unsupported operations requested by the options - // at this point we're being asked to prepare a model that we've already declared support for // and the operation indices may be different to those in getSupportedOperations anyway. std::set<unsigned int> unsupportedOperations; ModelToINetworkConverter<HalPolicy> modelConverter(options.GetBackends(), model, unsupportedOperations); if (modelConverter.GetConversionResult() != ConversionResult::Success) { FailPrepareModel(ErrorStatus::GENERAL_FAILURE, "ModelToINetworkConverter failed", cb); return ErrorStatus::NONE; } // Optimize the network armnn::IOptimizedNetworkPtr optNet(nullptr, nullptr); armnn::OptimizerOptions OptOptions; OptOptions.m_ReduceFp32ToFp16 = float32ToFloat16; std::vector<std::string> errMessages; try { optNet = armnn::Optimize(*modelConverter.GetINetwork(), options.GetBackends(), runtime->GetDeviceSpec(), OptOptions, errMessages); } catch (armnn::Exception &e) { std::stringstream message; message << "armnn::Exception (" << e.what() << ") caught from optimize."; FailPrepareModel(ErrorStatus::GENERAL_FAILURE, message.str(), cb); return ErrorStatus::NONE; } // Check that the optimized network is valid. if (!optNet) { std::stringstream message; message << "Invalid optimized network"; for (const std::string& msg : errMessages) { message << "\n" << msg; } FailPrepareModel(ErrorStatus::GENERAL_FAILURE, message.str(), cb); return ErrorStatus::NONE; } // Export the optimized network graph to a dot file if an output dump directory // has been specified in the drivers' arguments. ExportNetworkGraphToDotFile<hal_1_2::HalPolicy::Model>(*optNet, options.GetRequestInputsAndOutputsDumpDir(), model); // Load it into the runtime. armnn::NetworkId netId = 0; try { if (runtime->LoadNetwork(netId, move(optNet)) != armnn::Status::Success) { return FailPrepareModel(ErrorStatus::GENERAL_FAILURE, "Network could not be loaded", cb); } } catch (armnn::Exception& e) { std::stringstream message; message << "armnn::Exception (" << e.what()<< ") caught from LoadNetwork."; FailPrepareModel(ErrorStatus::GENERAL_FAILURE, message.str(), cb); return ErrorStatus::NONE; } std::unique_ptr<ArmnnPreparedModel_1_2<hal_1_2::HalPolicy>> preparedModel( new ArmnnPreparedModel_1_2<hal_1_2::HalPolicy>( netId, runtime.get(), model, options.GetRequestInputsAndOutputsDumpDir(), options.IsGpuProfilingEnabled())); // Run a single 'dummy' inference of the model. This means that CL kernels will get compiled (and tuned if // this is enabled) before the first 'real' inference which removes the overhead of the first inference. if (!preparedModel->ExecuteWithDummyInputs()) { return FailPrepareModel(ErrorStatus::GENERAL_FAILURE, "Network could not be executed", cb); } if (clTunedParameters && options.GetClTunedParametersMode() == armnn::IGpuAccTunedParameters::Mode::UpdateTunedParameters) { // Now that we've done one inference the CL kernel parameters will have been tuned, so save the updated file. try { clTunedParameters->Save(options.GetClTunedParametersFile().c_str()); } catch (const armnn::Exception& error) { ALOGE("ArmnnDriverImpl::prepareModel: Failed to save CL tuned parameters file '%s': %s", options.GetClTunedParametersFile().c_str(), error.what()); } } NotifyCallbackAndCheck(cb, ErrorStatus::NONE, preparedModel.release()); return ErrorStatus::NONE; } Return<void> ArmnnDriverImpl::getCapabilities_1_2(const armnn::IRuntimePtr& runtime, V1_2::IDevice::getCapabilities_1_2_cb cb) { ALOGV("hal_1_2::ArmnnDriverImpl::getCapabilities()"); V1_2::Capabilities capabilities; float defaultValue = .1f; if (runtime) { capabilities.relaxedFloat32toFloat16PerformanceScalar.execTime = ParseSystemProperty(g_RelaxedFloat32toFloat16PerformanceExecTime, defaultValue); capabilities.relaxedFloat32toFloat16PerformanceTensor.powerUsage = ParseSystemProperty(g_RelaxedFloat32toFloat16PerformancePowerUsage, defaultValue); // Set the base value for all operand types capabilities.operandPerformance = nonExtensionOperandPerformance({FLT_MAX, FLT_MAX}); // Load supported operand types update(&capabilities.operandPerformance, OperandType::TENSOR_FLOAT32, { .execTime = ParseSystemProperty(g_OperandTypeTensorFloat32PerformanceExecTime, defaultValue), .powerUsage = ParseSystemProperty(g_OperandTypeTensorFloat32PerformancePowerUsage, defaultValue) }); update(&capabilities.operandPerformance, OperandType::FLOAT32, { .execTime = ParseSystemProperty(g_OperandTypeFloat32PerformanceExecTime, defaultValue), .powerUsage = ParseSystemProperty(g_OperandTypeFloat32PerformancePowerUsage, defaultValue) }); update(&capabilities.operandPerformance, OperandType::TENSOR_FLOAT16, { .execTime = ParseSystemProperty(g_OperandTypeTensorFloat16PerformanceExecTime, defaultValue), .powerUsage = ParseSystemProperty(g_OperandTypeTensorFloat16PerformancePowerUsage, defaultValue) }); update(&capabilities.operandPerformance, OperandType::FLOAT16, { .execTime = ParseSystemProperty(g_OperandTypeFloat16PerformanceExecTime, defaultValue), .powerUsage = ParseSystemProperty(g_OperandTypeFloat16PerformancePowerUsage, defaultValue) }); update(&capabilities.operandPerformance, OperandType::TENSOR_QUANT8_ASYMM, { .execTime = ParseSystemProperty(g_OperandTypeTensorQuant8AsymmPerformanceExecTime, defaultValue), .powerUsage = ParseSystemProperty(g_OperandTypeTensorQuant8AsymmPerformancePowerUsage, defaultValue) }); update(&capabilities.operandPerformance, OperandType::TENSOR_QUANT16_SYMM, { .execTime = ParseSystemProperty(g_OperandTypeTensorQuant16SymmPerformanceExecTime, defaultValue), .powerUsage = ParseSystemProperty(g_OperandTypeTensorQuant16SymmPerformancePowerUsage, defaultValue) }); update(&capabilities.operandPerformance, OperandType::TENSOR_INT32, { .execTime = ParseSystemProperty(g_OperandTypeTensorInt32PerformanceExecTime, defaultValue), .powerUsage = ParseSystemProperty(g_OperandTypeTensorInt32PerformancePowerUsage, defaultValue) }); update(&capabilities.operandPerformance, OperandType::INT32, { .execTime = ParseSystemProperty(g_OperandTypeInt32PerformanceExecTime, defaultValue), .powerUsage = ParseSystemProperty(g_OperandTypeInt32PerformancePowerUsage, defaultValue) }); cb(ErrorStatus::NONE, capabilities); } else { capabilities.relaxedFloat32toFloat16PerformanceScalar.execTime = 0; capabilities.relaxedFloat32toFloat16PerformanceTensor.execTime = 0; // Set the base value for all operand types capabilities.operandPerformance = nonExtensionOperandPerformance({0.f, 0.0f}); cb(ErrorStatus::DEVICE_UNAVAILABLE, capabilities); } return Void(); } } // namespace hal_1_2 } // namespace armnn_driver <|endoftext|>
<commit_before>#include <math.h> #include <mpi.h> #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <time.h> #include <fj_tool/fapp.h> #include <fjcoll.h> #include "pearson-3d.h" int T_MAX; int T_MONITOR; int mpi_my_rank; const double PI=3.14159265358979323846; float frand() { return rand() / float(RAND_MAX); } double wctime() { struct timeval tv; gettimeofday(&tv,NULL); return (double)tv.tv_sec + (double)tv.tv_usec*1e-6; } void init() { for(int ix = navi.lower_x; ix < navi.upper_x; ++ix) { for(int iy = navi.lower_y; iy < navi.upper_y; ++iy) { for(int iz = navi.lower_z; iz < navi.upper_z; ++iz) { double x = (navi.offset_x + ix)/(double)NX; double y = (navi.offset_y + iy)/(double)NY; double z = (navi.offset_z + iz)/(double)NZ; U[ix][iy][iz] = 1.0; V[ix][iy][iz] = 0.0; if (x*x+y*y+z*z < 0.01) { U[ix][iy][iz] = 0.5; V[ix][iy][iz] = 0.25; } } } } } void write_monitor() { printf("#%d: t = %d\n", mpi_my_rank, navi.time_step); char fn[256]; sprintf(fn, "out/monitor-%06d-%d.txt", navi.time_step, mpi_my_rank); FILE *fp = fopen(fn,"wb"); int global_position[6]; global_position[0] = navi.offset_x + navi.lower_x; global_position[1] = navi.offset_y + navi.lower_y; global_position[2] = navi.offset_z + navi.lower_z; global_position[3] = navi.upper_x - navi.lower_x; global_position[4] = navi.upper_y - navi.lower_y; global_position[5] = navi.upper_z - navi.lower_z; fwrite(global_position, sizeof(int), 6, fp); int x_size = navi.upper_x - navi.lower_x; int y_size = navi.upper_y - navi.lower_y; int z_size = navi.upper_z - navi.lower_z; { const int y=navi.lower_y + y_size/2; for(int x = navi.lower_x; x < navi.upper_x; ++x) fwrite(U[x][y]+navi.lower_z, sizeof(double),z_size, fp); for(int x = navi.lower_x; x < navi.upper_x; ++x) fwrite(V[x][y]+navi.lower_z, sizeof(double),z_size, fp); } { const int x=navi.lower_x + x_size/2; for(int y = navi.lower_y; y < navi.upper_y; ++y) fwrite(U[x][y]+navi.lower_z, sizeof(double),z_size, fp); for(int y = navi.lower_y; y < navi.upper_y; ++y) fwrite(V[x][y]+navi.lower_z, sizeof(double),z_size, fp); } fclose(fp); } int main (int argc, char **argv) { srand(time(NULL)); MPI_Init(&argc, &argv); Formura_Init(&navi, MPI_COMM_WORLD); MPI_Comm_rank(MPI_COMM_WORLD, &mpi_my_rank); if (argc <= 1) { T_MAX=1000; }else{ sscanf(argv[1], "%d", &T_MAX); } if (argc <= 2) { T_MONITOR=1000; }else{ sscanf(argv[2], "%d", &T_MONITOR); } init(); double t_begin = wctime(), t_end; for(;;){ double t = wctime(); if(navi.time_step % T_MONITOR == 0 || navi.time_step <= 3 * T_MONITOR ) { printf("%d step @ %lf sec\n", navi.time_step, t-t_begin); } if(navi.time_step % T_MONITOR == 0) { write_monitor(); } if (navi.time_step >= T_MAX) break; if (navi.time_step == 0) { t_begin = wctime(); start_collection("main"); } Formura_Forward(&navi); // navi.time_step increases MPI_Barrier(MPI_COMM_WORLD); // TODO: test the effect of synchronization if (navi.time_step >= T_MAX) { t_end = wctime(); stop_collection("main"); } } printf("wct = %lf sec\n",t_end - t_begin); MPI_Barrier(MPI_COMM_WORLD); MPI_Finalize(); } <commit_msg>Attempt sinudal initial condition<commit_after>#include <math.h> #include <mpi.h> #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <time.h> #include <fj_tool/fapp.h> #include <fjcoll.h> #include "pearson-3d.h" int T_MAX; int T_MONITOR; int mpi_my_rank; const double PI=3.14159265358979323846; float frand() { return rand() / float(RAND_MAX); } double wctime() { struct timeval tv; gettimeofday(&tv,NULL); return (double)tv.tv_sec + (double)tv.tv_usec*1e-6; } void init() { for(int ix = navi.lower_x; ix < navi.upper_x; ++ix) { for(int iy = navi.lower_y; iy < navi.upper_y; ++iy) { for(int iz = navi.lower_z; iz < navi.upper_z; ++iz) { double k = (2*PI) / fmin(NX,fmin(NY,NZ)); double x = k * (navi.offset_x + ix); double y = k * (navi.offset_y + iy); double z = k * (navi.offset_z + iz); U[ix][iy][iz] = 1.0; V[ix][iy][iz] = 0.0; if (sin(x) * sin(y) * sin(z) > 0.9) { U[ix][iy][iz] = 0.5; V[ix][iy][iz] = 0.25; } } } } } void write_monitor() { printf("#%d: t = %d\n", mpi_my_rank, navi.time_step); char fn[256]; sprintf(fn, "out/monitor-%06d-%d.txt", navi.time_step, mpi_my_rank); FILE *fp = fopen(fn,"wb"); int global_position[6]; global_position[0] = navi.offset_x + navi.lower_x; global_position[1] = navi.offset_y + navi.lower_y; global_position[2] = navi.offset_z + navi.lower_z; global_position[3] = navi.upper_x - navi.lower_x; global_position[4] = navi.upper_y - navi.lower_y; global_position[5] = navi.upper_z - navi.lower_z; fwrite(global_position, sizeof(int), 6, fp); int x_size = navi.upper_x - navi.lower_x; int y_size = navi.upper_y - navi.lower_y; int z_size = navi.upper_z - navi.lower_z; { const int y=navi.lower_y + y_size/2; for(int x = navi.lower_x; x < navi.upper_x; ++x) fwrite(U[x][y]+navi.lower_z, sizeof(double),z_size, fp); for(int x = navi.lower_x; x < navi.upper_x; ++x) fwrite(V[x][y]+navi.lower_z, sizeof(double),z_size, fp); } { const int x=navi.lower_x + x_size/2; for(int y = navi.lower_y; y < navi.upper_y; ++y) fwrite(U[x][y]+navi.lower_z, sizeof(double),z_size, fp); for(int y = navi.lower_y; y < navi.upper_y; ++y) fwrite(V[x][y]+navi.lower_z, sizeof(double),z_size, fp); } fclose(fp); } int main (int argc, char **argv) { srand(time(NULL)); MPI_Init(&argc, &argv); Formura_Init(&navi, MPI_COMM_WORLD); MPI_Comm_rank(MPI_COMM_WORLD, &mpi_my_rank); if (argc <= 1) { T_MAX=1000; }else{ sscanf(argv[1], "%d", &T_MAX); } if (argc <= 2) { T_MONITOR=1000; }else{ sscanf(argv[2], "%d", &T_MONITOR); } init(); double t_begin = wctime(), t_end; for(;;){ double t = wctime(); if(navi.time_step % T_MONITOR == 0 || navi.time_step <= 3 * T_MONITOR ) { printf("%d step @ %lf sec\n", navi.time_step, t-t_begin); } if(navi.time_step % T_MONITOR == 0) { write_monitor(); } if (navi.time_step >= T_MAX) break; if (navi.time_step == 0) { t_begin = wctime(); start_collection("main"); } Formura_Forward(&navi); // navi.time_step increases MPI_Barrier(MPI_COMM_WORLD); // TODO: test the effect of synchronization if (navi.time_step >= T_MAX) { t_end = wctime(); stop_collection("main"); } } printf("wct = %lf sec\n",t_end - t_begin); MPI_Barrier(MPI_COMM_WORLD); MPI_Finalize(); } <|endoftext|>
<commit_before>/* -*- mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */ // vim:sts=8:sw=8:ts=8:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s /* Copyright (c) FFLAS-FFPACK * Written by Clément Pernet <clement.pernet@imag.fr> and Philippe Ledent * ========LICENCE======== * This file is part of the library FFLAS-FFPACK. * * FFLAS-FFPACK is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ========LICENCE======== */ #include "fflas-ffpack/fflas-ffpack-config.h" #include <iostream> #include <givaro/modular.h> #include "fflas-ffpack/fflas-ffpack.h" #include "fflas-ffpack/utils/timer.h" #include "fflas-ffpack/utils/fflas_io.h" #include "fflas-ffpack/utils/args-parser.h" using namespace std; int main(int argc, char** argv) { size_t iter = 3; int q = 131071; size_t n = 2000; size_t t = 0; std::string file = ""; Argument as[] = { { 'q', "-q Q", "Set the field characteristic (-1 for random).", TYPE_INT , &q }, { 'n', "-n N", "Set the dimension of the matrix.", TYPE_INT , &n }, { 't', "-t T", "Set the base case threshold.", TYPE_INT , &t }, { 'i', "-i R", "Set number of repetitions.", TYPE_INT , &iter }, { 'f', "-f FILE", "Set the input file (empty for random).", TYPE_STR , &file }, END_OF_ARGUMENTS }; FFLAS::parseArguments(argc,argv,as); typedef Givaro::ModularBalanced<double> Field; typedef Field::Element Element; Field F(q); Field::Element * A, *B; FFLAS::Timer chrono; double time=0.0; A = FFLAS::fflas_new<Element>(n*n); B = FFLAS::fflas_new<Element>(n*n); FFPACK::RandomTriangularMatrix (F, n, n, FFLAS::FflasUpper,FFLAS::FflasNonUnit,true,B,n); for (size_t i=0;i<=iter;++i){ if (!file.empty()){ FFLAS::ReadMatrix (file.c_str(),F,n,n,A); } else { FFLAS::fassign(F,n,n,B,n,A,n); } chrono.clear(); if (i) chrono.start(); if (t) FFPACK::ftrtri(F, FFLAS::FflasUpper, FFLAS::FflasNonUnit, n, A, n, t); else FFPACK::ftrtri(F, FFLAS::FflasUpper, FFLAS::FflasNonUnit, n, A, n); if (i) chrono.stop(); time+=chrono.usertime(); } FFLAS::fflas_delete (A); FFLAS::fflas_delete (B); // ----------- // Standard output for benchmark - Alexis Breust 2014/11/14 #define CUBE(x) ((x)*(x)*(x)) std::cout << "Time: " << time / double(iter) << " Gfops: " << CUBE(double(n)/1000.)/(3*time) * double(iter); FFLAS::writeCommandString(std::cout, as) << std::endl; return 0; } <commit_msg>changed usertime to real time<commit_after>/* -*- mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */ // vim:sts=8:sw=8:ts=8:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s /* Copyright (c) FFLAS-FFPACK * Written by Clément Pernet <clement.pernet@imag.fr> and Philippe Ledent * ========LICENCE======== * This file is part of the library FFLAS-FFPACK. * * FFLAS-FFPACK is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ========LICENCE======== */ #include "fflas-ffpack/fflas-ffpack-config.h" #include <iostream> #include <givaro/modular.h> #include "fflas-ffpack/fflas-ffpack.h" #include "fflas-ffpack/utils/timer.h" #include "fflas-ffpack/utils/fflas_io.h" #include "fflas-ffpack/utils/args-parser.h" using namespace std; int main(int argc, char** argv) { size_t iter = 3; int q = 131071; size_t n = 2000; size_t t = 0; std::string file = ""; Argument as[] = { { 'q', "-q Q", "Set the field characteristic (-1 for random).", TYPE_INT , &q }, { 'n', "-n N", "Set the dimension of the matrix.", TYPE_INT , &n }, { 't', "-t T", "Set the base case threshold.", TYPE_INT , &t }, { 'i', "-i R", "Set number of repetitions.", TYPE_INT , &iter }, { 'f', "-f FILE", "Set the input file (empty for random).", TYPE_STR , &file }, END_OF_ARGUMENTS }; FFLAS::parseArguments(argc,argv,as); typedef Givaro::ModularBalanced<double> Field; typedef Field::Element Element; Field F(q); Field::Element * A, *B; FFLAS::Timer chrono; double time=0.0; A = FFLAS::fflas_new<Element>(n*n); B = FFLAS::fflas_new<Element>(n*n); FFPACK::RandomTriangularMatrix (F, n, n, FFLAS::FflasUpper,FFLAS::FflasNonUnit,true,B,n); for (size_t i=0;i<=iter;++i){ if (!file.empty()){ FFLAS::ReadMatrix (file.c_str(),F,n,n,A); } else { FFLAS::fassign(F,n,n,B,n,A,n); } chrono.clear(); if (i) chrono.start(); if (t) FFPACK::ftrtri(F, FFLAS::FflasUpper, FFLAS::FflasNonUnit, n, A, n, t); else FFPACK::ftrtri(F, FFLAS::FflasUpper, FFLAS::FflasNonUnit, n, A, n); if (i) chrono.stop(); time+=chrono.realtime(); } FFLAS::fflas_delete (A); FFLAS::fflas_delete (B); // ----------- // Standard output for benchmark - Alexis Breust 2014/11/14 #define CUBE(x) ((x)*(x)*(x)) std::cout << "Time: " << time / double(iter) << " Gfops: " << CUBE(double(n)/1000.)/(3*time) * double(iter); FFLAS::writeCommandString(std::cout, as) << std::endl; return 0; } <|endoftext|>
<commit_before>/** * * Copyright (c) 2020 Project CHIP Authors * Copyright (c) 2018 Google LLC. * Copyright (c) 2016-2017 Nest Labs, 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. */ /** * @file * This file defines Status Information Block in Interaction Model * */ #include "StatusIB.h" #include "MessageDefHelper.h" #include <inttypes.h> #include <stdarg.h> #include <stdio.h> #include <app/AppBuildConfig.h> #include <lib/core/CHIPCore.h> #include <lib/support/ErrorStr.h> using namespace chip; using namespace chip::TLV; using namespace chip::Protocols::InteractionModel; namespace chip { namespace app { CHIP_ERROR StatusIB::Parser::DecodeStatusIB(StatusIB & aStatusIB) const { TLV::TLVReader reader; reader.Init(mReader); while (CHIP_NO_ERROR == reader.Next()) { VerifyOrReturnError(TLV::IsContextTag(reader.GetTag()), CHIP_ERROR_INVALID_TLV_TAG); switch (TLV::TagNumFromTag(reader.GetTag())) { case to_underlying(Tag::kStatus): ReturnErrorOnFailure(reader.Get(aStatusIB.mStatus)); break; case to_underlying(Tag::kClusterStatus): ClusterStatus clusterStatus; ReturnErrorOnFailure(reader.Get(clusterStatus)); aStatusIB.mClusterStatus.SetValue(clusterStatus); break; } } return CHIP_NO_ERROR; } #if CHIP_CONFIG_IM_ENABLE_SCHEMA_CHECK CHIP_ERROR StatusIB::Parser::CheckSchemaValidity() const { CHIP_ERROR err = CHIP_NO_ERROR; int TagPresenceMask = 0; TLV::TLVReader reader; PRETTY_PRINT("StatusIB ="); PRETTY_PRINT("{"); // make a copy of the reader reader.Init(mReader); while (CHIP_NO_ERROR == (err = reader.Next())) { VerifyOrReturnError(TLV::IsContextTag(reader.GetTag()), CHIP_ERROR_INVALID_TLV_TAG); if (!(TagPresenceMask & (1 << to_underlying(Tag::kStatus)))) { TagPresenceMask |= (1 << to_underlying(Tag::kStatus)); #if CHIP_DETAIL_LOGGING { uint16_t status; ReturnErrorOnFailure(reader.Get(status)); PRETTY_PRINT("\tstatus = 0x%" PRIx16 ",", status); } #endif // CHIP_DETAIL_LOGGING } else if (!(TagPresenceMask & (1 << to_underlying(Tag::kClusterStatus)))) { TagPresenceMask |= (1 << to_underlying(Tag::kClusterStatus)); #if CHIP_DETAIL_LOGGING { ClusterStatus clusterStatus; ReturnErrorOnFailure(reader.Get(clusterStatus)); PRETTY_PRINT("\tstatus = 0x%" PRIx8 ",", clusterStatus); } #endif // CHIP_DETAIL_LOGGING } else { PRETTY_PRINT("\tExtra element in StatusIB"); } } PRETTY_PRINT("},"); PRETTY_PRINT(""); // if we have exhausted this container if (CHIP_END_OF_TLV == err) { // check for required fields: const int RequiredFields = (1 << to_underlying(Tag::kStatus)); if ((TagPresenceMask & RequiredFields) == RequiredFields) { err = CHIP_NO_ERROR; } else { err = CHIP_ERROR_IM_MALFORMED_STATUS_CODE; } } ReturnErrorOnFailure(err); ReturnErrorOnFailure(reader.ExitContainer(mOuterContainerType)); return CHIP_NO_ERROR; } #endif // CHIP_CONFIG_IM_ENABLE_SCHEMA_CHECK StatusIB::Builder & StatusIB::Builder::EncodeStatusIB(const StatusIB & aStatusIB) { mError = mpWriter->Put(TLV::ContextTag(to_underlying(Tag::kStatus)), aStatusIB.mStatus); SuccessOrExit(mError); if (aStatusIB.mClusterStatus.HasValue()) { mError = mpWriter->Put(TLV::ContextTag(to_underlying(Tag::kClusterStatus)), aStatusIB.mClusterStatus.Value()); SuccessOrExit(mError); } EndOfContainer(); exit: return *this; } CHIP_ERROR StatusIB::ToChipError() const { if (mStatus == Status::Success) { return CHIP_NO_ERROR; } if (mClusterStatus.HasValue()) { return ChipError(ChipError::SdkPart::kIMClusterStatus, mClusterStatus.Value()); } return ChipError(ChipError::SdkPart::kIMGlobalStatus, to_underlying(mStatus)); } void StatusIB::InitFromChipError(CHIP_ERROR aError) { if (aError.IsPart(ChipError::SdkPart::kIMClusterStatus)) { mStatus = Status::Failure; mClusterStatus = MakeOptional(aError.GetSdkCode()); return; } mClusterStatus = NullOptional; if (aError == CHIP_NO_ERROR) { mStatus = Status::Success; return; } if (aError.IsPart(ChipError::SdkPart::kIMGlobalStatus)) { mStatus = static_cast<Status>(aError.GetSdkCode()); return; } mStatus = Status::Failure; } namespace { bool FormatStatusIBError(char * buf, uint16_t bufSize, CHIP_ERROR err) { if (!err.IsIMStatus()) { return false; } const char * desc = nullptr; #if !CHIP_CONFIG_SHORT_ERROR_STR constexpr char generalFormat[] = "General error: 0x%02" PRIx8; constexpr char clusterFormat[] = "Cluster-specific error: 0x%02" PRIx8; // Formatting an 8-bit int will take at most 2 chars, and replace the '%' // and the format letter(s) for PRIx8, so a buffer big enough to hold our // format string will also hold our formatted string. constexpr size_t formattedSize = max(sizeof(generalFormat), sizeof(clusterFormat)); char formattedString[formattedSize]; StatusIB status; status.InitFromChipError(err); if (status.mClusterStatus.HasValue()) { snprintf(formattedString, formattedSize, clusterFormat, status.mClusterStatus.Value()); } else { snprintf(formattedString, formattedSize, generalFormat, to_underlying(status.mStatus)); } desc = formattedString; #endif // !CHIP_CONFIG_SHORT_ERROR_STR FormatError(buf, bufSize, "IM", err, desc); return true; } } // anonymous namespace void StatusIB::RegisterErrorFormatter() { static ErrorFormatter sStatusIBErrorFormatter = { FormatStatusIBError, nullptr }; ::RegisterErrorFormatter(&sStatusIBErrorFormatter); } }; // namespace app }; // namespace chip <commit_msg>Fix cluster-status printing (#13883)<commit_after>/** * * Copyright (c) 2020 Project CHIP Authors * Copyright (c) 2018 Google LLC. * Copyright (c) 2016-2017 Nest Labs, 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. */ /** * @file * This file defines Status Information Block in Interaction Model * */ #include "StatusIB.h" #include "MessageDefHelper.h" #include <inttypes.h> #include <stdarg.h> #include <stdio.h> #include <app/AppBuildConfig.h> #include <lib/core/CHIPCore.h> #include <lib/support/ErrorStr.h> using namespace chip; using namespace chip::TLV; using namespace chip::Protocols::InteractionModel; namespace chip { namespace app { CHIP_ERROR StatusIB::Parser::DecodeStatusIB(StatusIB & aStatusIB) const { TLV::TLVReader reader; reader.Init(mReader); while (CHIP_NO_ERROR == reader.Next()) { VerifyOrReturnError(TLV::IsContextTag(reader.GetTag()), CHIP_ERROR_INVALID_TLV_TAG); switch (TLV::TagNumFromTag(reader.GetTag())) { case to_underlying(Tag::kStatus): ReturnErrorOnFailure(reader.Get(aStatusIB.mStatus)); break; case to_underlying(Tag::kClusterStatus): ClusterStatus clusterStatus; ReturnErrorOnFailure(reader.Get(clusterStatus)); aStatusIB.mClusterStatus.SetValue(clusterStatus); break; } } return CHIP_NO_ERROR; } #if CHIP_CONFIG_IM_ENABLE_SCHEMA_CHECK CHIP_ERROR StatusIB::Parser::CheckSchemaValidity() const { CHIP_ERROR err = CHIP_NO_ERROR; int TagPresenceMask = 0; TLV::TLVReader reader; PRETTY_PRINT("StatusIB ="); PRETTY_PRINT("{"); // make a copy of the reader reader.Init(mReader); while (CHIP_NO_ERROR == (err = reader.Next())) { VerifyOrReturnError(TLV::IsContextTag(reader.GetTag()), CHIP_ERROR_INVALID_TLV_TAG); if (!(TagPresenceMask & (1 << to_underlying(Tag::kStatus)))) { TagPresenceMask |= (1 << to_underlying(Tag::kStatus)); #if CHIP_DETAIL_LOGGING { uint16_t status; ReturnErrorOnFailure(reader.Get(status)); PRETTY_PRINT("\tstatus = 0x%" PRIx16 ",", status); } #endif // CHIP_DETAIL_LOGGING } else if (!(TagPresenceMask & (1 << to_underlying(Tag::kClusterStatus)))) { TagPresenceMask |= (1 << to_underlying(Tag::kClusterStatus)); #if CHIP_DETAIL_LOGGING { ClusterStatus clusterStatus; ReturnErrorOnFailure(reader.Get(clusterStatus)); PRETTY_PRINT("\tcluster-status = 0x%" PRIx8 ",", clusterStatus); } #endif // CHIP_DETAIL_LOGGING } else { PRETTY_PRINT("\tExtra element in StatusIB"); } } PRETTY_PRINT("},"); PRETTY_PRINT(""); // if we have exhausted this container if (CHIP_END_OF_TLV == err) { // check for required fields: const int RequiredFields = (1 << to_underlying(Tag::kStatus)); if ((TagPresenceMask & RequiredFields) == RequiredFields) { err = CHIP_NO_ERROR; } else { err = CHIP_ERROR_IM_MALFORMED_STATUS_CODE; } } ReturnErrorOnFailure(err); ReturnErrorOnFailure(reader.ExitContainer(mOuterContainerType)); return CHIP_NO_ERROR; } #endif // CHIP_CONFIG_IM_ENABLE_SCHEMA_CHECK StatusIB::Builder & StatusIB::Builder::EncodeStatusIB(const StatusIB & aStatusIB) { mError = mpWriter->Put(TLV::ContextTag(to_underlying(Tag::kStatus)), aStatusIB.mStatus); SuccessOrExit(mError); if (aStatusIB.mClusterStatus.HasValue()) { mError = mpWriter->Put(TLV::ContextTag(to_underlying(Tag::kClusterStatus)), aStatusIB.mClusterStatus.Value()); SuccessOrExit(mError); } EndOfContainer(); exit: return *this; } CHIP_ERROR StatusIB::ToChipError() const { if (mStatus == Status::Success) { return CHIP_NO_ERROR; } if (mClusterStatus.HasValue()) { return ChipError(ChipError::SdkPart::kIMClusterStatus, mClusterStatus.Value()); } return ChipError(ChipError::SdkPart::kIMGlobalStatus, to_underlying(mStatus)); } void StatusIB::InitFromChipError(CHIP_ERROR aError) { if (aError.IsPart(ChipError::SdkPart::kIMClusterStatus)) { mStatus = Status::Failure; mClusterStatus = MakeOptional(aError.GetSdkCode()); return; } mClusterStatus = NullOptional; if (aError == CHIP_NO_ERROR) { mStatus = Status::Success; return; } if (aError.IsPart(ChipError::SdkPart::kIMGlobalStatus)) { mStatus = static_cast<Status>(aError.GetSdkCode()); return; } mStatus = Status::Failure; } namespace { bool FormatStatusIBError(char * buf, uint16_t bufSize, CHIP_ERROR err) { if (!err.IsIMStatus()) { return false; } const char * desc = nullptr; #if !CHIP_CONFIG_SHORT_ERROR_STR constexpr char generalFormat[] = "General error: 0x%02" PRIx8; constexpr char clusterFormat[] = "Cluster-specific error: 0x%02" PRIx8; // Formatting an 8-bit int will take at most 2 chars, and replace the '%' // and the format letter(s) for PRIx8, so a buffer big enough to hold our // format string will also hold our formatted string. constexpr size_t formattedSize = max(sizeof(generalFormat), sizeof(clusterFormat)); char formattedString[formattedSize]; StatusIB status; status.InitFromChipError(err); if (status.mClusterStatus.HasValue()) { snprintf(formattedString, formattedSize, clusterFormat, status.mClusterStatus.Value()); } else { snprintf(formattedString, formattedSize, generalFormat, to_underlying(status.mStatus)); } desc = formattedString; #endif // !CHIP_CONFIG_SHORT_ERROR_STR FormatError(buf, bufSize, "IM", err, desc); return true; } } // anonymous namespace void StatusIB::RegisterErrorFormatter() { static ErrorFormatter sStatusIBErrorFormatter = { FormatStatusIBError, nullptr }; ::RegisterErrorFormatter(&sStatusIBErrorFormatter); } }; // namespace app }; // namespace chip <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Copyright (C) 2015 Ruslan Baratov ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Multimedia module. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <cassert> // assert #include <QGuiApplication> #include <QQuickView> #include <QQuickItem> #include <QCamera> #include <QQuickWindow> #include <QCameraInfo> #include "VideoFilter.hpp" #include "InfoFilter.hpp" #include "graphics/Logger.h" #include <iostream> #if defined(Q_OS_IOS) extern "C" int qtmn(int argc, char** argv) { #else int main(int argc, char **argv) { #endif #ifdef Q_OS_WIN // avoid ANGLE on Windows QCoreApplication::setAttribute(Qt::AA_UseDesktopOpenGL); #endif QGuiApplication app(argc, argv); auto logger = gatherer::graphics::Logger::create("qmlvideofilter"); logger->info() << "Start"; qmlRegisterType<VideoFilter>("qmlvideofilter.test", 1, 0, "VideoFilter"); qmlRegisterType<InfoFilter>("qmlvideofilter.test", 1, 0, "InfoFilter"); //QQuickWindow view; QQuickView view; view.setSource(QUrl("qrc:///main.qml")); view.setResizeMode( QQuickView::SizeRootObjectToView ); view.reportContentOrientationChange(Qt::PortraitOrientation); // Note available: //view.setAttribute(Qt::PortraitOrientation, true); // Default camera on iOS is not setting good parameters by default QQuickItem* root = view.rootObject(); QObject* qmlCamera = root->findChild<QObject*>("CameraObject"); assert(qmlCamera != nullptr); QCamera* camera = qvariant_cast<QCamera*>(qmlCamera->property("mediaObject")); assert(camera != nullptr); QObject * qmlVideoOutput = root->findChild<QObject*>("VideoOutput"); assert(qmlVideoOutput); QCameraInfo cameraInfo(*camera); qmlVideoOutput->setProperty("rotation", cameraInfo.orientation()); #if defined(Q_OS_IOS) // Try the highest resolution NV{12,21} format format: // This should work for both Android and iOS std::vector<QVideoFrame::PixelFormat> desiredFormats { QVideoFrame::Format_NV12, QVideoFrame::Format_NV21 }; auto viewfinderSettings = camera->supportedViewfinderSettings(); logger->info() << "# of settings: " << viewfinderSettings.size() << "\n"; std::pair<int, QCameraViewfinderSettings> best; for (auto i: viewfinderSettings) { logger->info() << "settings: " << i.resolution().width() << "x" << i.resolution().height() << " : " << int(i.pixelFormat()) << "\n"; if(std::find(desiredFormats.begin(), desiredFormats.end(), i.pixelFormat()) != desiredFormats.end()) { int area = (i.resolution().height() * i.resolution().width()); if(area > best.first) { best = { area, i }; } } } assert(!best.second.isNull()); camera->setViewfinderSettings(best.second); #endif // Q_OS_IOS view.showFullScreen(); return app.exec(); } <commit_msg>EOL will be added automatically<commit_after>/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Copyright (C) 2015 Ruslan Baratov ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Multimedia module. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <cassert> // assert #include <QGuiApplication> #include <QQuickView> #include <QQuickItem> #include <QCamera> #include <QQuickWindow> #include <QCameraInfo> #include "VideoFilter.hpp" #include "InfoFilter.hpp" #include "graphics/Logger.h" #include <iostream> #if defined(Q_OS_IOS) extern "C" int qtmn(int argc, char** argv) { #else int main(int argc, char **argv) { #endif #ifdef Q_OS_WIN // avoid ANGLE on Windows QCoreApplication::setAttribute(Qt::AA_UseDesktopOpenGL); #endif QGuiApplication app(argc, argv); auto logger = gatherer::graphics::Logger::create("qmlvideofilter"); logger->info() << "Start"; qmlRegisterType<VideoFilter>("qmlvideofilter.test", 1, 0, "VideoFilter"); qmlRegisterType<InfoFilter>("qmlvideofilter.test", 1, 0, "InfoFilter"); //QQuickWindow view; QQuickView view; view.setSource(QUrl("qrc:///main.qml")); view.setResizeMode( QQuickView::SizeRootObjectToView ); view.reportContentOrientationChange(Qt::PortraitOrientation); // Note available: //view.setAttribute(Qt::PortraitOrientation, true); // Default camera on iOS is not setting good parameters by default QQuickItem* root = view.rootObject(); QObject* qmlCamera = root->findChild<QObject*>("CameraObject"); assert(qmlCamera != nullptr); QCamera* camera = qvariant_cast<QCamera*>(qmlCamera->property("mediaObject")); assert(camera != nullptr); QObject * qmlVideoOutput = root->findChild<QObject*>("VideoOutput"); assert(qmlVideoOutput); QCameraInfo cameraInfo(*camera); qmlVideoOutput->setProperty("rotation", cameraInfo.orientation()); #if defined(Q_OS_IOS) // Try the highest resolution NV{12,21} format format: // This should work for both Android and iOS std::vector<QVideoFrame::PixelFormat> desiredFormats { QVideoFrame::Format_NV12, QVideoFrame::Format_NV21 }; auto viewfinderSettings = camera->supportedViewfinderSettings(); logger->info() << "# of settings: " << viewfinderSettings.size(); std::pair<int, QCameraViewfinderSettings> best; for (auto i: viewfinderSettings) { logger->info() << "settings: " << i.resolution().width() << "x" << i.resolution().height() << " : " << int(i.pixelFormat()); if(std::find(desiredFormats.begin(), desiredFormats.end(), i.pixelFormat()) != desiredFormats.end()) { int area = (i.resolution().height() * i.resolution().width()); if(area > best.first) { best = { area, i }; } } } assert(!best.second.isNull()); camera->setViewfinderSettings(best.second); #endif // Q_OS_IOS view.showFullScreen(); return app.exec(); } <|endoftext|>
<commit_before>#include "toolbar.h" #include <regex> #include <fstream> #include <streambuf> #include <sstream> #include <boost/filesystem.hpp> #include <QToolBar> #include <QToolButton> #include <possumwood_sdk/app.h> #include <actions/actions.h> #include "main_window.h" Toolbar::Toolbar() { const boost::filesystem::path path = possumwood::App::instance().expandPath("$TOOLBARS"); if(boost::filesystem::exists(path)) { std::map<boost::filesystem::path, std::string> paths; for(auto& entry : boost::make_iterator_range(boost::filesystem::directory_iterator(path), {})) { static const std::regex regex("^[0-9]+_.*"); std::string dir = entry.path().filename().string(); if(std::regex_match(dir, regex)) dir = dir.substr(dir.find('_')+1); paths[entry.path().filename()] = dir; } for(auto& toolbarIt : paths) { QToolBar* tb = new QToolBar(); tb->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); tb->setIconSize(QSize(32, 32)); QFont font = tb->font(); font.setPointSize(8); tb->setFont(font); addTab(tb, toolbarIt.second.c_str()); std::map<boost::filesystem::path, std::string> setups; for(auto& entry : boost::make_iterator_range(boost::filesystem::directory_iterator(path / toolbarIt.first), {})) if(entry.path().extension() == ".psw") { static const std::regex regex("^[0-9]+_.*"); std::string name = entry.path().filename().stem().string(); if(std::regex_match(name, regex)) name = name.substr(name.find('_')+1); std::replace(name.begin(), name.end(), '_', ' '); setups[entry.path().filename()] = name; } unsigned currentIndex = 1; for(auto& i : setups) { const boost::filesystem::path setupPath = path / toolbarIt.first / i.first; boost::filesystem::path iconPath = setupPath; iconPath.replace_extension(".png"); { std::stringstream fnss(setupPath.filename().string()); unsigned index; fnss >> index; if(index > currentIndex) { tb->addSeparator(); currentIndex = index; } ++currentIndex; } QAction* action = tb->addAction(i.second.c_str()); if(boost::filesystem::exists(iconPath)) action->setIcon(QIcon(iconPath.c_str())); QToolButton* toolButton = (QToolButton*)tb->widgetForAction(action); toolButton->setAutoRaise(false); QAction::connect(action, &QAction::triggered, [setupPath]() { try { std::ifstream file(setupPath.string()); std::string setup = std::string(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()); QMainWindow* win = possumwood::App::instance().mainWindow(); MainWindow* mw = dynamic_cast<MainWindow*>(win); assert(mw); dependency_graph::Selection selection; possumwood::actions::paste(mw->adaptor().currentNetwork(), selection, setup); mw->adaptor().setSelection(selection); } catch(std::exception& e) { std::cout << "Error inserting setup - " << e.what() << std::endl; } catch(...) { std::cout << "Error inserting setup." << std::endl; } }); } } } } <commit_msg>Tiny toolbar font<commit_after>#include "toolbar.h" #include <regex> #include <fstream> #include <streambuf> #include <sstream> #include <boost/filesystem.hpp> #include <QToolBar> #include <QToolButton> #include <possumwood_sdk/app.h> #include <actions/actions.h> #include "main_window.h" Toolbar::Toolbar() { const boost::filesystem::path path = possumwood::App::instance().expandPath("$TOOLBARS"); if(boost::filesystem::exists(path)) { std::map<boost::filesystem::path, std::string> paths; for(auto& entry : boost::make_iterator_range(boost::filesystem::directory_iterator(path), {})) { static const std::regex regex("^[0-9]+_.*"); std::string dir = entry.path().filename().string(); if(std::regex_match(dir, regex)) dir = dir.substr(dir.find('_')+1); paths[entry.path().filename()] = dir; } for(auto& toolbarIt : paths) { QToolBar* tb = new QToolBar(); tb->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); tb->setIconSize(QSize(32, 32)); QFont font = tb->font(); font.setPointSize(8); tb->setFont(font); addTab(tb, toolbarIt.second.c_str()); std::map<boost::filesystem::path, std::string> setups; for(auto& entry : boost::make_iterator_range(boost::filesystem::directory_iterator(path / toolbarIt.first), {})) if(entry.path().extension() == ".psw") { static const std::regex regex("^[0-9]+_.*"); std::string name = entry.path().filename().stem().string(); if(std::regex_match(name, regex)) name = name.substr(name.find('_')+1); std::replace(name.begin(), name.end(), '_', ' '); setups[entry.path().filename()] = name; } unsigned currentIndex = 1; for(auto& i : setups) { const boost::filesystem::path setupPath = path / toolbarIt.first / i.first; boost::filesystem::path iconPath = setupPath; iconPath.replace_extension(".png"); { std::stringstream fnss(setupPath.filename().string()); unsigned index; fnss >> index; if(index > currentIndex) { tb->addSeparator(); currentIndex = index; } ++currentIndex; } QAction* action = tb->addAction(i.second.c_str()); if(boost::filesystem::exists(iconPath)) action->setIcon(QIcon(iconPath.c_str())); QToolButton* toolButton = (QToolButton*)tb->widgetForAction(action); toolButton->setAutoRaise(false); QFont font = toolButton->font(); font.setPointSize(7); toolButton->setFont(font); QAction::connect(action, &QAction::triggered, [setupPath]() { try { std::ifstream file(setupPath.string()); std::string setup = std::string(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()); QMainWindow* win = possumwood::App::instance().mainWindow(); MainWindow* mw = dynamic_cast<MainWindow*>(win); assert(mw); dependency_graph::Selection selection; possumwood::actions::paste(mw->adaptor().currentNetwork(), selection, setup); mw->adaptor().setSelection(selection); } catch(std::exception& e) { std::cout << "Error inserting setup - " << e.what() << std::endl; } catch(...) { std::cout << "Error inserting setup." << std::endl; } }); } } } } <|endoftext|>
<commit_before>/* * Copyright (c) 2003-2004 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: Steve Reinhardt */ #ifndef __ALPHA_LINUX_PROCESS_HH__ #define __ALPHA_LINUX_PROCESS_HH__ #include "arch/alpha/process.hh" namespace AlphaISA { /// A process with emulated Alpha/Linux syscalls. class AlphaLinuxProcess : public AlphaLiveProcess { public: /// Constructor. AlphaLinuxProcess(const std::string &name, ObjectFile *objFile, System *system, int stdin_fd, int stdout_fd, int stderr_fd, std::vector<std::string> &argv, std::vector<std::string> &envp, const std::string &cwd, uint64_t _uid, uint64_t _euid, uint64_t _gid, uint64_t _egid, uint64_t _pid, uint64_t _ppid); virtual SyscallDesc* getDesc(int callnum); /// The target system's hostname. static const char *hostname; /// Array of syscall descriptors, indexed by call number. static SyscallDesc syscallDescs[]; const int Num_Syscall_Descs; }; } // namespace AlphaISA #endif // __ALPHA_LINUX_PROCESS_HH__ <commit_msg>The "hostname" variable isn't used in the process classes. It should be removed from the other ones as well.<commit_after>/* * Copyright (c) 2003-2004 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: Steve Reinhardt */ #ifndef __ALPHA_LINUX_PROCESS_HH__ #define __ALPHA_LINUX_PROCESS_HH__ #include "arch/alpha/process.hh" namespace AlphaISA { /// A process with emulated Alpha/Linux syscalls. class AlphaLinuxProcess : public AlphaLiveProcess { public: /// Constructor. AlphaLinuxProcess(const std::string &name, ObjectFile *objFile, System *system, int stdin_fd, int stdout_fd, int stderr_fd, std::vector<std::string> &argv, std::vector<std::string> &envp, const std::string &cwd, uint64_t _uid, uint64_t _euid, uint64_t _gid, uint64_t _egid, uint64_t _pid, uint64_t _ppid); virtual SyscallDesc* getDesc(int callnum); /// Array of syscall descriptors, indexed by call number. static SyscallDesc syscallDescs[]; const int Num_Syscall_Descs; }; } // namespace AlphaISA #endif // __ALPHA_LINUX_PROCESS_HH__ <|endoftext|>
<commit_before> inline kth_cv::kth_cv(const std::string in_path, const std::string in_actionNames, const field<std::string> in_all_people, const int in_scale_factor, const int in_shift, const int in_scene, //only for kth const int in_segment_length, const int in_dim ):path(in_path), actionNames(in_actionNames), all_people (in_all_people), scale_factor(in_scale_factor), shift(in_shift), scene(in_scene), segment_length(in_segment_length), dim(in_dim) { actions.load( actionNames ); total_sc = 1; } inline void kth_cv::logEucl() { int n_actions = actions.n_rows; int n_peo = all_people.n_rows; vec acc; acc.zeros(n_peo*total_sc); for (int sc = 1; sc<=total_sc; ++sc) //scene { for (int pe = 0; pe< n_peo; ++pe) { for (int act=0; act<n_actions; ++act) { //load number of segments vec total_seg; int num_s; std::stringstream load_sub_path; std::stringstream load_num_seg; load_sub_path << path << "/kth-cov-mat/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ; load_num_seg << load_sub_path.str() << "/num_seg_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".dat"; total_seg.load( load_num_seg.str()); num_s = total_seg(0); uvec est_lab_segm; est_lab_segm.zeros(num_s); for (int s=0; s<num_s; ++s) { std::stringstream load_cov_seg; load_cov_seg << load_sub_path.str() << "/cov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; cout << "cov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5" << endl; //debe devolver el est_labe de ese segmento est_lab_segm(s) = one_seg_est_lab( pe, load_sub_path.str(), load_cov_seg.str()); //getchar(); } } } } } inline uword kth_cv::one_seg_est_lab(int pe_test, std::string load_sub_path, std::string segm_name) { ri_metrics Ri_met; mat test_cov; test_cov.load(segm_name); int n_actions = actions.n_rows; int n_peo = all_people.n_rows; double dist, tmp_dist; tmp_dist = datum::inf; double est_lab; for (int pe_tr = 0; pe_tr< n_peo; ++pe_tr) { while (pe_tr!= pe_test) { for (int sc = 1; sc<=total_sc; ++sc) //scene { for (int act=0; act<n_actions; ++act) { vec total_seg; int num_s; std::stringstream load_num_seg; load_num_seg << load_sub_path << "/num_seg_"<< all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".dat"; total_seg.load( load_num_seg.str()); num_s = total_seg(0); for (int s_tr=0; s_tr<num_s; ++s_tr) { std::stringstream load_cov_seg_tr; load_cov_seg_tr << load_sub_path << "/cov_seg" << s_tr << "_" << all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".h5"; cout << "Comparing with cov_seg" << s_tr << "_"<< all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".h5" << endl; mat train_cov; train_cov.load( load_cov_seg_tr.str() ); //test_cov.print("test_cov"); //train_cov.print("train_cov"); dist = Ri_met.logEucl(test_cov, train_cov); //cout << "dist " << dist << endl; if (dist < tmp_dist) { cout << "Es menor" << endl; tmp_dist = dist; est_lab = act; } //cout << "Press a key" << endl; //getchar(); } } } } } cout << "est_lab "<< est_lab << endl; getchar(); return est_lab; }<commit_msg>Bug found<commit_after> inline kth_cv::kth_cv(const std::string in_path, const std::string in_actionNames, const field<std::string> in_all_people, const int in_scale_factor, const int in_shift, const int in_scene, //only for kth const int in_segment_length, const int in_dim ):path(in_path), actionNames(in_actionNames), all_people (in_all_people), scale_factor(in_scale_factor), shift(in_shift), scene(in_scene), segment_length(in_segment_length), dim(in_dim) { actions.load( actionNames ); total_sc = 1; } inline void kth_cv::logEucl() { int n_actions = actions.n_rows; int n_peo = all_people.n_rows; vec acc; acc.zeros(n_peo*total_sc); for (int sc = 1; sc<=total_sc; ++sc) //scene { for (int pe = 0; pe< n_peo; ++pe) { for (int act=0; act<n_actions; ++act) { //load number of segments vec total_seg; int num_s; std::stringstream load_sub_path; std::stringstream load_num_seg; load_sub_path << path << "/kth-cov-mat/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ; load_num_seg << load_sub_path.str() << "/num_seg_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".dat"; total_seg.load( load_num_seg.str()); num_s = total_seg(0); uvec est_lab_segm; est_lab_segm.zeros(num_s); for (int s=0; s<num_s; ++s) { std::stringstream load_cov_seg; load_cov_seg << load_sub_path.str() << "/cov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; cout << "cov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5" << endl; //debe devolver el est_labe de ese segmento est_lab_segm(s) = one_seg_est_lab( pe, load_sub_path.str(), load_cov_seg.str()); //getchar(); } } } } } inline uword kth_cv::one_seg_est_lab(int pe_test, std::string load_sub_path, std::string segm_name) { ri_metrics Ri_met; mat test_cov; test_cov.load(segm_name); int n_actions = actions.n_rows; int n_peo = all_people.n_rows; double dist, tmp_dist; tmp_dist = datum::inf; double est_lab; for (int pe_tr = 0; pe_tr< n_peo; ++pe_tr) { while (pe_tr!= pe_test) { for (int sc = 1; sc<=total_sc; ++sc) //scene { for (int act=0; act<n_actions; ++act) { vec total_seg; int num_s; std::stringstream load_num_seg; load_num_seg << load_sub_path << "/num_seg_"<< all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".dat"; total_seg.load( load_num_seg.str()); num_s = total_seg(0); for (int s_tr=0; s_tr<num_s; ++s_tr) { std::stringstream load_cov_seg_tr; load_cov_seg_tr << load_sub_path << "/cov_seg" << s_tr << "_" << all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".h5"; //cout << "Comparing with cov_seg" << s_tr << "_"<< all_people (pe_tr) << "_" << actions(act) << "_dim" << dim << ".h5" << endl; mat train_cov; train_cov.load( load_cov_seg_tr.str() ); //test_cov.print("test_cov"); //train_cov.print("train_cov"); dist = Ri_met.logEucl(test_cov, train_cov); //cout << "dist " << dist << endl; if (dist < tmp_dist) { cout << "Es menor" << endl; tmp_dist = dist; est_lab = act; } //cout << "Press a key" << endl; //getchar(); } } } } } cout << "est_lab "<< est_lab << endl; getchar(); return est_lab; }<|endoftext|>
<commit_before>#include <vector> #include "caffe/layers/conv_layer.hpp" namespace caffe { template <typename Dtype> void ConvolutionLayer<Dtype>::compute_output_shape() { const int* kernel_shape_data = this->kernel_shape_.cpu_data(); const int* stride_data = this->stride_.cpu_data(); const int* pad_data = this->pad_.cpu_data(); const int* dilation_data = this->dilation_.cpu_data(); this->output_shape_.clear(); for (int i = 0; i < this->num_spatial_axes_; ++i) { // i + 1 to skip channel axis const int input_dim = this->input_shape(i + 1); const int kernel_extent = dilation_data[i] * (kernel_shape_data[i] - 1) + 1; const int output_dim = (input_dim + 2 * pad_data[i] - kernel_extent) / stride_data[i] + 1; this->output_shape_.push_back(output_dim); } } template <typename Dtype> void ConvolutionLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const Dtype* weight = this->blobs_[0]->cpu_data(); for (int i = 0; i < bottom.size(); ++i) { const Dtype* bottom_data = bottom[i]->cpu_data(); Dtype* top_data = top[i]->mutable_cpu_data(); for (int n = 0; n < this->num_; ++n) { this->forward_cpu_gemm(bottom_data + n * this->bottom_dim_, weight, top_data + n * this->top_dim_); if (this->bias_term_) { const Dtype* bias = this->blobs_[1]->cpu_data(); this->forward_cpu_bias(top_data + n * this->top_dim_, bias); } } } } template <typename Dtype> void ConvolutionLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { const Dtype* weight = this->blobs_[0]->cpu_data(); Dtype* weight_diff = this->blobs_[0]->mutable_cpu_diff(); for (int i = 0; i < top.size(); ++i) { const Dtype* top_diff = top[i]->cpu_diff(); const Dtype* bottom_data = bottom[i]->cpu_data(); Dtype* bottom_diff = bottom[i]->mutable_cpu_diff(); // Bias gradient, if necessary. if (this->bias_term_ && this->param_propagate_down_[1]) { Dtype* bias_diff = this->blobs_[1]->mutable_cpu_diff(); for (int n = 0; n < this->num_; ++n) { this->backward_cpu_bias(bias_diff, top_diff + n * this->top_dim_); } } if (this->param_propagate_down_[0] || propagate_down[i]) { for (int n = 0; n < this->num_; ++n) { // gradient w.r.t. weight. Note that we will accumulate diffs. if (this->param_propagate_down_[0]) { this->weight_cpu_gemm(bottom_data + n * this->bottom_dim_, top_diff + n * this->top_dim_, weight_diff); } // gradient w.r.t. bottom data, if necessary. if (propagate_down[i]) { this->backward_cpu_gemm(top_diff + n * this->top_dim_, weight, bottom_diff + n * this->bottom_dim_); } } } } } template <typename Dtype> void ConvolutionLayer<Dtype>::Backward_relevance(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { const float eps = .00001; float top_sum = 0; for(int i = 0; i < top[0]->count(); ++i) { top_sum += top[0]->cpu_diff()[i]; } std::cout << "CONV TOP SUM: " << top_sum << '\n'; const Dtype* weight = this->blobs_[0]->cpu_data(); for (int i = 0; i < top.size(); ++i) { const Dtype* top_diff = top[i]->cpu_diff(); const Dtype* bottom_data = bottom[i]->cpu_data(); Dtype* bottom_diff = bottom[i]->mutable_cpu_diff(); caffe_set(bottom[i]->count(), Dtype(0.0), bottom_diff); const Dtype* top_data = top[i]->cpu_data(); int Mfull = this->num_output_; const int first_spatial_axis = this->channel_axis_ + 1; int N = bottom[i]->count(first_spatial_axis); int K = this->blobs_[0]->count(1); Blob<Dtype> top_data_with_eps((top[i])->shape()); int outcount = top_data_with_eps.count(); Dtype* relevance = top_data_with_eps.mutable_cpu_data(); caffe_copy<Dtype>(outcount, top_diff, relevance); for(int c = 0; c < outcount; ++c) { Dtype bias = this->blobs_[1]->cpu_data()[c/N]; Dtype val = top_data[c] - bias; if(val > 0) { relevance[c] /= val + eps; } else if(val < 0) { relevance[c] /= val - eps; } } for (int n = 0; n < this->num_; ++n) { this->backward_cpu_gemm(relevance + n * this->top_dim_, weight, bottom_diff + n * this->bottom_dim_); for(int d = 0; d < this->bottom_dim_; ++d) { bottom_diff[d + n * this->bottom_dim_] *= bottom_data[d + n * this->bottom_dim_]; } } } /* float top_sum = 0; for (int i = 0; i < top[0]->count(); ++i) { top_sum += top[0]->cpu_diff()[i]; //std::cout << top[0]->cpu_diff()[i] << "|"; //std::cout << bottom[0]->cpu_diff()[i] << "|"; } std::cout << "CONV TOP SUM: " << top_sum << '\n'; // std::cout << top[0]->count() << "\n"; //std::cout << bottom[0]->count() << "\n"; int i = 0; //assume only using top[0] const Dtype* weight = this->blobs_[i]->cpu_data(); const Dtype* top_diff = top[i]->cpu_diff(); const Dtype* bottom_data = bottom[i]->cpu_data(); Dtype* bottom_diff = bottom[i]->mutable_cpu_diff(); caffe_set(bottom[i]->count(), Dtype(0.), bottom_diff); for (int n = 0; n < this->num_; ++n) { Dtype* alphabetas = this->alphabeta(top_diff+n *this->top_dim_, weight, bottom_data + n * this->bottom_dim_, bottom_diff + n * this->bottom_dim_); //std::cout << "AB CONV DATA: " << '\n'; //for (int i = 0; i < 1000; ++i) //{ // std::cout << alphabetas[i] << "|"; //} caffe_copy(bottom[i]->count(), alphabetas, bottom_diff); } */ float bottom_sum = 0; for (int i = 0; i < bottom[0]->count(); ++i) { bottom_sum += bottom[0]->cpu_diff()[i]; //std::cout << bottom[0]->cpu_diff()[i] << "|"; } std::cout << "CONV BOTTOM SUM: " << bottom_sum << '\n'; } #ifdef CPU_ONLY STUB_GPU(ConvolutionLayer); #endif INSTANTIATE_CLASS(ConvolutionLayer); } // namespace caffe <commit_msg>remove warning<commit_after>#include <vector> #include "caffe/layers/conv_layer.hpp" namespace caffe { template <typename Dtype> void ConvolutionLayer<Dtype>::compute_output_shape() { const int* kernel_shape_data = this->kernel_shape_.cpu_data(); const int* stride_data = this->stride_.cpu_data(); const int* pad_data = this->pad_.cpu_data(); const int* dilation_data = this->dilation_.cpu_data(); this->output_shape_.clear(); for (int i = 0; i < this->num_spatial_axes_; ++i) { // i + 1 to skip channel axis const int input_dim = this->input_shape(i + 1); const int kernel_extent = dilation_data[i] * (kernel_shape_data[i] - 1) + 1; const int output_dim = (input_dim + 2 * pad_data[i] - kernel_extent) / stride_data[i] + 1; this->output_shape_.push_back(output_dim); } } template <typename Dtype> void ConvolutionLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const Dtype* weight = this->blobs_[0]->cpu_data(); for (int i = 0; i < bottom.size(); ++i) { const Dtype* bottom_data = bottom[i]->cpu_data(); Dtype* top_data = top[i]->mutable_cpu_data(); for (int n = 0; n < this->num_; ++n) { this->forward_cpu_gemm(bottom_data + n * this->bottom_dim_, weight, top_data + n * this->top_dim_); if (this->bias_term_) { const Dtype* bias = this->blobs_[1]->cpu_data(); this->forward_cpu_bias(top_data + n * this->top_dim_, bias); } } } } template <typename Dtype> void ConvolutionLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { const Dtype* weight = this->blobs_[0]->cpu_data(); Dtype* weight_diff = this->blobs_[0]->mutable_cpu_diff(); for (int i = 0; i < top.size(); ++i) { const Dtype* top_diff = top[i]->cpu_diff(); const Dtype* bottom_data = bottom[i]->cpu_data(); Dtype* bottom_diff = bottom[i]->mutable_cpu_diff(); // Bias gradient, if necessary. if (this->bias_term_ && this->param_propagate_down_[1]) { Dtype* bias_diff = this->blobs_[1]->mutable_cpu_diff(); for (int n = 0; n < this->num_; ++n) { this->backward_cpu_bias(bias_diff, top_diff + n * this->top_dim_); } } if (this->param_propagate_down_[0] || propagate_down[i]) { for (int n = 0; n < this->num_; ++n) { // gradient w.r.t. weight. Note that we will accumulate diffs. if (this->param_propagate_down_[0]) { this->weight_cpu_gemm(bottom_data + n * this->bottom_dim_, top_diff + n * this->top_dim_, weight_diff); } // gradient w.r.t. bottom data, if necessary. if (propagate_down[i]) { this->backward_cpu_gemm(top_diff + n * this->top_dim_, weight, bottom_diff + n * this->bottom_dim_); } } } } } template <typename Dtype> void ConvolutionLayer<Dtype>::Backward_relevance(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { const float eps = .00001; float top_sum = 0; for(int i = 0; i < top[0]->count(); ++i) { top_sum += top[0]->cpu_diff()[i]; } std::cout << "CONV TOP SUM: " << top_sum << '\n'; const Dtype* weight = this->blobs_[0]->cpu_data(); for (int i = 0; i < top.size(); ++i) { const Dtype* top_diff = top[i]->cpu_diff(); const Dtype* bottom_data = bottom[i]->cpu_data(); Dtype* bottom_diff = bottom[i]->mutable_cpu_diff(); caffe_set(bottom[i]->count(), Dtype(0.0), bottom_diff); const Dtype* top_data = top[i]->cpu_data(); int Mfull = this->num_output_; const int first_spatial_axis = this->channel_axis_ + 1; int N = bottom[i]->count(first_spatial_axis); Blob<Dtype> top_data_with_eps((top[i])->shape()); int outcount = top_data_with_eps.count(); Dtype* relevance = top_data_with_eps.mutable_cpu_data(); caffe_copy<Dtype>(outcount, top_diff, relevance); for(int c = 0; c < outcount; ++c) { Dtype bias = this->blobs_[1]->cpu_data()[c/N]; Dtype val = top_data[c] - bias; if(val > 0) { relevance[c] /= val + eps; } else if(val < 0) { relevance[c] /= val - eps; } } for (int n = 0; n < this->num_; ++n) { this->backward_cpu_gemm(relevance + n * this->top_dim_, weight, bottom_diff + n * this->bottom_dim_); for(int d = 0; d < this->bottom_dim_; ++d) { bottom_diff[d + n * this->bottom_dim_] *= bottom_data[d + n * this->bottom_dim_]; } } } /* float top_sum = 0; for (int i = 0; i < top[0]->count(); ++i) { top_sum += top[0]->cpu_diff()[i]; //std::cout << top[0]->cpu_diff()[i] << "|"; //std::cout << bottom[0]->cpu_diff()[i] << "|"; } std::cout << "CONV TOP SUM: " << top_sum << '\n'; // std::cout << top[0]->count() << "\n"; //std::cout << bottom[0]->count() << "\n"; int i = 0; //assume only using top[0] const Dtype* weight = this->blobs_[i]->cpu_data(); const Dtype* top_diff = top[i]->cpu_diff(); const Dtype* bottom_data = bottom[i]->cpu_data(); Dtype* bottom_diff = bottom[i]->mutable_cpu_diff(); caffe_set(bottom[i]->count(), Dtype(0.), bottom_diff); for (int n = 0; n < this->num_; ++n) { Dtype* alphabetas = this->alphabeta(top_diff+n *this->top_dim_, weight, bottom_data + n * this->bottom_dim_, bottom_diff + n * this->bottom_dim_); //std::cout << "AB CONV DATA: " << '\n'; //for (int i = 0; i < 1000; ++i) //{ // std::cout << alphabetas[i] << "|"; //} caffe_copy(bottom[i]->count(), alphabetas, bottom_diff); } */ float bottom_sum = 0; for (int i = 0; i < bottom[0]->count(); ++i) { bottom_sum += bottom[0]->cpu_diff()[i]; //std::cout << bottom[0]->cpu_diff()[i] << "|"; } std::cout << "CONV BOTTOM SUM: " << bottom_sum << '\n'; } #ifdef CPU_ONLY STUB_GPU(ConvolutionLayer); #endif INSTANTIATE_CLASS(ConvolutionLayer); } // namespace caffe <|endoftext|>
<commit_before>// Copyright 2013 Yangqing Jia #include <stdint.h> #include <leveldb/db.h> #include <pthread.h> #include <string> #include <vector> #include "caffe/layer.hpp" #include "caffe/util/io.hpp" #include "caffe/vision_layers.hpp" using std::string; namespace caffe { template <typename Dtype> void* DataLayerPrefetch(void* layer_pointer) { DataLayer<Dtype>* layer = reinterpret_cast<DataLayer<Dtype>*>(layer_pointer); Datum datum; Dtype* top_data = layer->prefetch_data_->mutable_cpu_data(); Dtype* top_label = layer->prefetch_label_->mutable_cpu_data(); const Dtype scale = layer->layer_param_.scale(); const int batchsize = layer->layer_param_.batchsize(); const int cropsize = layer->layer_param_.cropsize(); const bool mirror = layer->layer_param_.mirror(); if (mirror && cropsize == 0) { LOG(FATAL) << "Current implementation requires mirror and cropsize to be " << "set at the same time."; } // datum scales const int channels = layer->datum_channels_; const int height = layer->datum_height_; const int width = layer->datum_width_; const int size = layer->datum_size_; const Dtype* mean = layer->data_mean_.cpu_data(); for (int itemid = 0; itemid < batchsize; ++itemid) { // get a blob datum.ParseFromString(layer->iter_->value().ToString()); const string& data = datum.data(); if (cropsize) { CHECK(data.size()) << "Image cropping only support uint8 data"; int h_off, w_off; // We only do random crop when we do training. if (Caffe::phase() == Caffe::TRAIN) { h_off = rand() % (height - cropsize); w_off = rand() % (width - cropsize); } else { h_off = (height - cropsize) / 2; w_off = (width - cropsize) / 2; } if (mirror && rand() % 2) { // Copy mirrored version for (int c = 0; c < channels; ++c) { for (int h = 0; h < cropsize; ++h) { for (int w = 0; w < cropsize; ++w) { top_data[((itemid * channels + c) * cropsize + h) * cropsize + cropsize - 1 - w] = (static_cast<Dtype>( (uint8_t)data[(c * height + h + h_off) * width + w + w_off]) - mean[(c * height + h + h_off) * width + w + w_off]) * scale; } } } } else { // Normal copy for (int c = 0; c < channels; ++c) { for (int h = 0; h < cropsize; ++h) { for (int w = 0; w < cropsize; ++w) { top_data[((itemid * channels + c) * cropsize + h) * cropsize + w] = (static_cast<Dtype>( (uint8_t)data[(c * height + h + h_off) * width + w + w_off]) - mean[(c * height + h + h_off) * width + w + w_off]) * scale; } } } } } else { // we will prefer to use data() first, and then try float_data() if (data.size()) { for (int j = 0; j < size; ++j) { top_data[itemid * size + j] = (static_cast<Dtype>((uint8_t)data[j]) - mean[j]) * scale; } } else { for (int j = 0; j < size; ++j) { top_data[itemid * size + j] = (datum.float_data(j) - mean[j]) * scale; } } } top_label[itemid] = datum.label(); // go to the next iter layer->iter_->Next(); if (!layer->iter_->Valid()) { // We have reached the end. Restart from the first. DLOG(INFO) << "Restarting data prefetching from start."; layer->iter_->SeekToFirst(); } } return (void*)NULL; } template <typename Dtype> void DataLayer<Dtype>::SetUp(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) { CHECK_EQ(bottom.size(), 0) << "Data Layer takes no input blobs."; CHECK_EQ(top->size(), 2) << "Data Layer takes two blobs as output."; // Initialize the leveldb leveldb::DB* db_temp; leveldb::Options options; options.create_if_missing = false; LOG(INFO) << "Opening leveldb " << this->layer_param_.source(); leveldb::Status status = leveldb::DB::Open( options, this->layer_param_.source(), &db_temp); CHECK(status.ok()) << "Failed to open leveldb " << this->layer_param_.source(); db_.reset(db_temp); iter_.reset(db_->NewIterator(leveldb::ReadOptions())); iter_->SeekToFirst(); // Check if we would need to randomly skip a few data points if (this->layer_param_.rand_skip()) { unsigned int skip = rand() % this->layer_param_.rand_skip(); LOG(INFO) << "Skipping first " << skip << " data points."; while (skip-- > 0) { iter_->Next(); if (!iter_->Valid()) { iter_->SeekToFirst(); } } } // Read a data point, and use it to initialize the top blob. Datum datum; datum.ParseFromString(iter_->value().ToString()); // image int cropsize = this->layer_param_.cropsize(); if (cropsize > 0) { (*top)[0]->Reshape( this->layer_param_.batchsize(), datum.channels(), cropsize, cropsize); prefetch_data_.reset(new Blob<Dtype>( this->layer_param_.batchsize(), datum.channels(), cropsize, cropsize)); } else { (*top)[0]->Reshape( this->layer_param_.batchsize(), datum.channels(), datum.height(), datum.width()); prefetch_data_.reset(new Blob<Dtype>( this->layer_param_.batchsize(), datum.channels(), datum.height(), datum.width())); } LOG(INFO) << "output data size: " << (*top)[0]->num() << "," << (*top)[0]->channels() << "," << (*top)[0]->height() << "," << (*top)[0]->width(); // label (*top)[1]->Reshape(this->layer_param_.batchsize(), 1, 1, 1); prefetch_label_.reset( new Blob<Dtype>(this->layer_param_.batchsize(), 1, 1, 1)); // datum size datum_channels_ = datum.channels(); datum_height_ = datum.height(); datum_width_ = datum.width(); datum_size_ = datum.channels() * datum.height() * datum.width(); CHECK_GT(datum_height_, cropsize); CHECK_GT(datum_width_, cropsize); // check if we want to have mean if (this->layer_param_.has_meanfile()) { BlobProto blob_proto; LOG(INFO) << "Loading mean file from" << this->layer_param_.meanfile(); ReadProtoFromBinaryFile(this->layer_param_.meanfile().c_str(), &blob_proto); data_mean_.FromProto(blob_proto); CHECK_EQ(data_mean_.num(), 1); CHECK_EQ(data_mean_.channels(), datum_channels_); CHECK_EQ(data_mean_.height(), datum_height_); CHECK_EQ(data_mean_.width(), datum_width_); } else { // Simply initialize an all-empty mean. data_mean_.Reshape(1, datum_channels_, datum_height_, datum_width_); } // Now, start the prefetch thread. Before calling prefetch, we make two // cpu_data calls so that the prefetch thread does not accidentally make // simultaneous cudaMalloc calls when the main thread is running. In some // GPUs this seems to cause failures if we do not so. prefetch_data_->mutable_cpu_data(); prefetch_label_->mutable_cpu_data(); data_mean_.cpu_data(); DLOG(INFO) << "Initializing prefetch"; CHECK(!pthread_create(&thread_, NULL, DataLayerPrefetch<Dtype>, reinterpret_cast<void*>(this))) << "Pthread execution failed."; DLOG(INFO) << "Prefetch initialized."; } template <typename Dtype> void DataLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) { // First, join the thread CHECK(!pthread_join(thread_, NULL)) << "Pthread joining failed."; // Copy the data memcpy((*top)[0]->mutable_cpu_data(), prefetch_data_->cpu_data(), sizeof(Dtype) * prefetch_data_->count()); memcpy((*top)[1]->mutable_cpu_data(), prefetch_label_->cpu_data(), sizeof(Dtype) * prefetch_label_->count()); // Start a new prefetch thread CHECK(!pthread_create(&thread_, NULL, DataLayerPrefetch<Dtype>, reinterpret_cast<void*>(this))) << "Pthread execution failed."; } template <typename Dtype> void DataLayer<Dtype>::Forward_gpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) { // First, join the thread CHECK(!pthread_join(thread_, NULL)) << "Pthread joining failed."; // Copy the data CUDA_CHECK(cudaMemcpy((*top)[0]->mutable_gpu_data(), prefetch_data_->cpu_data(), sizeof(Dtype) * prefetch_data_->count(), cudaMemcpyHostToDevice)); CUDA_CHECK(cudaMemcpy((*top)[1]->mutable_gpu_data(), prefetch_label_->cpu_data(), sizeof(Dtype) * prefetch_label_->count(), cudaMemcpyHostToDevice)); // Start a new prefetch thread CHECK(!pthread_create(&thread_, NULL, DataLayerPrefetch<Dtype>, reinterpret_cast<void*>(this))) << "Pthread execution failed."; } // The backward operations are dummy - they do not carry any computation. template <typename Dtype> Dtype DataLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const bool propagate_down, vector<Blob<Dtype>*>* bottom) { return Dtype(0.); } template <typename Dtype> Dtype DataLayer<Dtype>::Backward_gpu(const vector<Blob<Dtype>*>& top, const bool propagate_down, vector<Blob<Dtype>*>* bottom) { return Dtype(0.); } INSTANTIATE_CLASS(DataLayer); } // namespace caffe <commit_msg>print status message on error opening leveldb<commit_after>// Copyright 2013 Yangqing Jia #include <stdint.h> #include <leveldb/db.h> #include <pthread.h> #include <string> #include <vector> #include "caffe/layer.hpp" #include "caffe/util/io.hpp" #include "caffe/vision_layers.hpp" using std::string; namespace caffe { template <typename Dtype> void* DataLayerPrefetch(void* layer_pointer) { DataLayer<Dtype>* layer = reinterpret_cast<DataLayer<Dtype>*>(layer_pointer); Datum datum; Dtype* top_data = layer->prefetch_data_->mutable_cpu_data(); Dtype* top_label = layer->prefetch_label_->mutable_cpu_data(); const Dtype scale = layer->layer_param_.scale(); const int batchsize = layer->layer_param_.batchsize(); const int cropsize = layer->layer_param_.cropsize(); const bool mirror = layer->layer_param_.mirror(); if (mirror && cropsize == 0) { LOG(FATAL) << "Current implementation requires mirror and cropsize to be " << "set at the same time."; } // datum scales const int channels = layer->datum_channels_; const int height = layer->datum_height_; const int width = layer->datum_width_; const int size = layer->datum_size_; const Dtype* mean = layer->data_mean_.cpu_data(); for (int itemid = 0; itemid < batchsize; ++itemid) { // get a blob datum.ParseFromString(layer->iter_->value().ToString()); const string& data = datum.data(); if (cropsize) { CHECK(data.size()) << "Image cropping only support uint8 data"; int h_off, w_off; // We only do random crop when we do training. if (Caffe::phase() == Caffe::TRAIN) { h_off = rand() % (height - cropsize); w_off = rand() % (width - cropsize); } else { h_off = (height - cropsize) / 2; w_off = (width - cropsize) / 2; } if (mirror && rand() % 2) { // Copy mirrored version for (int c = 0; c < channels; ++c) { for (int h = 0; h < cropsize; ++h) { for (int w = 0; w < cropsize; ++w) { top_data[((itemid * channels + c) * cropsize + h) * cropsize + cropsize - 1 - w] = (static_cast<Dtype>( (uint8_t)data[(c * height + h + h_off) * width + w + w_off]) - mean[(c * height + h + h_off) * width + w + w_off]) * scale; } } } } else { // Normal copy for (int c = 0; c < channels; ++c) { for (int h = 0; h < cropsize; ++h) { for (int w = 0; w < cropsize; ++w) { top_data[((itemid * channels + c) * cropsize + h) * cropsize + w] = (static_cast<Dtype>( (uint8_t)data[(c * height + h + h_off) * width + w + w_off]) - mean[(c * height + h + h_off) * width + w + w_off]) * scale; } } } } } else { // we will prefer to use data() first, and then try float_data() if (data.size()) { for (int j = 0; j < size; ++j) { top_data[itemid * size + j] = (static_cast<Dtype>((uint8_t)data[j]) - mean[j]) * scale; } } else { for (int j = 0; j < size; ++j) { top_data[itemid * size + j] = (datum.float_data(j) - mean[j]) * scale; } } } top_label[itemid] = datum.label(); // go to the next iter layer->iter_->Next(); if (!layer->iter_->Valid()) { // We have reached the end. Restart from the first. DLOG(INFO) << "Restarting data prefetching from start."; layer->iter_->SeekToFirst(); } } return (void*)NULL; } template <typename Dtype> void DataLayer<Dtype>::SetUp(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) { CHECK_EQ(bottom.size(), 0) << "Data Layer takes no input blobs."; CHECK_EQ(top->size(), 2) << "Data Layer takes two blobs as output."; // Initialize the leveldb leveldb::DB* db_temp; leveldb::Options options; options.create_if_missing = false; LOG(INFO) << "Opening leveldb " << this->layer_param_.source(); leveldb::Status status = leveldb::DB::Open( options, this->layer_param_.source(), &db_temp); CHECK(status.ok()) << "Failed to open leveldb " << this->layer_param_.source() << std::endl << status.ToString(); db_.reset(db_temp); iter_.reset(db_->NewIterator(leveldb::ReadOptions())); iter_->SeekToFirst(); // Check if we would need to randomly skip a few data points if (this->layer_param_.rand_skip()) { unsigned int skip = rand() % this->layer_param_.rand_skip(); LOG(INFO) << "Skipping first " << skip << " data points."; while (skip-- > 0) { iter_->Next(); if (!iter_->Valid()) { iter_->SeekToFirst(); } } } // Read a data point, and use it to initialize the top blob. Datum datum; datum.ParseFromString(iter_->value().ToString()); // image int cropsize = this->layer_param_.cropsize(); if (cropsize > 0) { (*top)[0]->Reshape( this->layer_param_.batchsize(), datum.channels(), cropsize, cropsize); prefetch_data_.reset(new Blob<Dtype>( this->layer_param_.batchsize(), datum.channels(), cropsize, cropsize)); } else { (*top)[0]->Reshape( this->layer_param_.batchsize(), datum.channels(), datum.height(), datum.width()); prefetch_data_.reset(new Blob<Dtype>( this->layer_param_.batchsize(), datum.channels(), datum.height(), datum.width())); } LOG(INFO) << "output data size: " << (*top)[0]->num() << "," << (*top)[0]->channels() << "," << (*top)[0]->height() << "," << (*top)[0]->width(); // label (*top)[1]->Reshape(this->layer_param_.batchsize(), 1, 1, 1); prefetch_label_.reset( new Blob<Dtype>(this->layer_param_.batchsize(), 1, 1, 1)); // datum size datum_channels_ = datum.channels(); datum_height_ = datum.height(); datum_width_ = datum.width(); datum_size_ = datum.channels() * datum.height() * datum.width(); CHECK_GT(datum_height_, cropsize); CHECK_GT(datum_width_, cropsize); // check if we want to have mean if (this->layer_param_.has_meanfile()) { BlobProto blob_proto; LOG(INFO) << "Loading mean file from" << this->layer_param_.meanfile(); ReadProtoFromBinaryFile(this->layer_param_.meanfile().c_str(), &blob_proto); data_mean_.FromProto(blob_proto); CHECK_EQ(data_mean_.num(), 1); CHECK_EQ(data_mean_.channels(), datum_channels_); CHECK_EQ(data_mean_.height(), datum_height_); CHECK_EQ(data_mean_.width(), datum_width_); } else { // Simply initialize an all-empty mean. data_mean_.Reshape(1, datum_channels_, datum_height_, datum_width_); } // Now, start the prefetch thread. Before calling prefetch, we make two // cpu_data calls so that the prefetch thread does not accidentally make // simultaneous cudaMalloc calls when the main thread is running. In some // GPUs this seems to cause failures if we do not so. prefetch_data_->mutable_cpu_data(); prefetch_label_->mutable_cpu_data(); data_mean_.cpu_data(); DLOG(INFO) << "Initializing prefetch"; CHECK(!pthread_create(&thread_, NULL, DataLayerPrefetch<Dtype>, reinterpret_cast<void*>(this))) << "Pthread execution failed."; DLOG(INFO) << "Prefetch initialized."; } template <typename Dtype> void DataLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) { // First, join the thread CHECK(!pthread_join(thread_, NULL)) << "Pthread joining failed."; // Copy the data memcpy((*top)[0]->mutable_cpu_data(), prefetch_data_->cpu_data(), sizeof(Dtype) * prefetch_data_->count()); memcpy((*top)[1]->mutable_cpu_data(), prefetch_label_->cpu_data(), sizeof(Dtype) * prefetch_label_->count()); // Start a new prefetch thread CHECK(!pthread_create(&thread_, NULL, DataLayerPrefetch<Dtype>, reinterpret_cast<void*>(this))) << "Pthread execution failed."; } template <typename Dtype> void DataLayer<Dtype>::Forward_gpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) { // First, join the thread CHECK(!pthread_join(thread_, NULL)) << "Pthread joining failed."; // Copy the data CUDA_CHECK(cudaMemcpy((*top)[0]->mutable_gpu_data(), prefetch_data_->cpu_data(), sizeof(Dtype) * prefetch_data_->count(), cudaMemcpyHostToDevice)); CUDA_CHECK(cudaMemcpy((*top)[1]->mutable_gpu_data(), prefetch_label_->cpu_data(), sizeof(Dtype) * prefetch_label_->count(), cudaMemcpyHostToDevice)); // Start a new prefetch thread CHECK(!pthread_create(&thread_, NULL, DataLayerPrefetch<Dtype>, reinterpret_cast<void*>(this))) << "Pthread execution failed."; } // The backward operations are dummy - they do not carry any computation. template <typename Dtype> Dtype DataLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const bool propagate_down, vector<Blob<Dtype>*>* bottom) { return Dtype(0.); } template <typename Dtype> Dtype DataLayer<Dtype>::Backward_gpu(const vector<Blob<Dtype>*>& top, const bool propagate_down, vector<Blob<Dtype>*>* bottom) { return Dtype(0.); } INSTANTIATE_CLASS(DataLayer); } // namespace caffe <|endoftext|>
<commit_before>/* * CameraController.cpp * * Created on: Sep 4, 2016 * Author: sebastian */ #include "CameraController.h" #include "CameraSimulator.h" CameraController::CameraController(bool simulator) { cout << "CameraController() constructor" << endl; if (simulator) { m_camera.reset(new CameraSimulator()); } } CameraController::~CameraController() { cout << "CameraController() destructor" << endl; if (m_camera) { m_camera.reset(); } } void CameraController::start() { cout << "CameraController - start()" << endl; if (m_camera) { m_camera->startGrab(); } } void CameraController::stop() { cout << "CameraController - stop()" << endl; if (m_camera) { m_camera->stopGrab(); } } void CameraController::addCameraObserver(CameraObserverInterface* observer) { m_observers.push_back(observer); } <commit_msg>Added explicit namespace for 'cout' calls.<commit_after>/* * CameraController.cpp * * Created on: Sep 4, 2016 * Author: sebastian */ #include "CameraController.h" #include "CameraSimulator.h" CameraController::CameraController(bool simulator) { std::cout << "CameraController() constructor" << endl; if (simulator) { m_camera.reset(new CameraSimulator()); } } CameraController::~CameraController() { std::cout << "CameraController() destructor" << endl; if (m_camera) { m_camera.reset(); } } void CameraController::start() { std::cout << "CameraController - start()" << endl; if (m_camera) { m_camera->startGrab(); } } void CameraController::stop() { std::cout << "CameraController - stop()" << endl; if (m_camera) { m_camera->stopGrab(); } } void CameraController::addCameraObserver(CameraObserverInterface* observer) { m_observers.push_back(observer); } <|endoftext|>
<commit_before>/* Copyright 2008 Brain Research Institute, Melbourne, Australia Written by J-Donald Tournier, 27/06/08. This file is part of MRtrix. MRtrix 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. MRtrix 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 MRtrix. If not, see <http://www.gnu.org/licenses/>. */ #include <iomanip> #include "app.h" #include "point.h" #include "image/voxel.h" #include "image/buffer.h" #include "image/loop.h" MRTRIX_APPLICATION using namespace MR; using namespace App; void usage () { DESCRIPTION + "compute images statistics."; ARGUMENTS + Argument ("image", "the input image from which statistics will be computed.") .type_image_in (); OPTIONS + Option ("mask", "only perform computation within the specified binary brain mask image.") + Argument ("image").type_image_in () + Option ("voxel", "only perform computation within the specified voxel, supplied as a " "comma-separated vector of 3 integer values (multiple voxels can be included).") .allow_multiple() + Argument ("pos").type_sequence_int () + Option ("histogram", "generate histogram of intensities and store in specified text file. Note " "that the first line of the histogram gives the centre of the bins.") + Argument ("file").type_file () + Option ("bins", "the number of bins to use to generate the histogram (default = 100).") + Argument ("num").type_integer (2, 100, std::numeric_limits<int>::max()) + Option ("dump", "dump the voxel intensities to a text file.") + Argument ("file").type_file () + Option ("position", "dump the position of the voxels in the mask to a text file.") + Argument ("file").type_file (); } typedef float value_type; typedef cfloat complex_type; class CalibrateHistogram { public: CalibrateHistogram (int nbins) : min (INFINITY), max (-INFINITY), width (0.0), bins (nbins) { } value_type min, max, width; int bins; void operator() (value_type val) { if (finite (val)) { if (val < min) min = val; if (val > max) max = val; } } void init (std::ostream& stream) { width = (max - min) / float (bins+1); for (int i = 0; i < bins; i++) stream << (min + width/2.0) + i* width << " "; stream << "\n"; } }; class Stats { public: Stats (bool complex = false) : mean (0.0, 0.0), std (0.0, 0.0), min (INFINITY, INFINITY), max (-INFINITY, -INFINITY), count (0), dump (NULL) { is_complex = complex; } void generate_histogram (const CalibrateHistogram& cal) { hmin = cal.min; hwidth = cal.width; hist.resize (cal.bins); } void dump_to (std::ostream& stream) { dump = &stream; } void write_histogram (std::ostream& stream) { for (size_t i = 0; i < hist.size(); ++i) stream << hist[i] << " "; stream << "\n"; } void operator() (complex_type val) { if (finite (val.real()) && finite (val.imag())) { mean += val; std += cdouble (val.real()*val.real(), val.imag()*val.imag()); if (min.real() > val.real()) min.real() = val.real(); if (min.imag() > val.imag()) min.imag() = val.imag(); if (max.real() < val.real()) max.real() = val.real(); if (max.imag() < val.imag()) max.imag() = val.imag(); count++; if (dump) *dump << str(val) << "\n"; if (!is_complex) values.push_back(val.real()); if (hist.size()) { int bin = int ( (val.real()-hmin) / hwidth); if (bin < 0) bin = 0; else if (bin >= int (hist.size())) bin = hist.size()-1; hist[bin]++; } } } template <class Set> void print (Set& ima) { if (count == 0) throw Exception ("no voxels in mask - aborting"); mean /= double (count); std.real() = sqrt (std.real()/double(count) - mean.real()*mean.real()); std.imag() = sqrt (std.imag()/double(count) - mean.imag()*mean.imag()); std::string s = "[ "; for (size_t n = 3; n < ima.ndim(); n++) s += str (ima[n]) + " "; s += "] "; if (!is_complex) { std::sort(values.rbegin(), values.rend()); } int width = is_complex ? 24 : 12; std::cout << std::setw(15) << std::right << s << " " << std::setw(width) << std::right << str(mean); if (!is_complex) { std::cout << " " << std::setw(width) << std::right << values[round(float(values.size()) / 2.0)]; } std::cout << " " << std::setw(width) << std::right << ( count > 1 ? str(std) : "N/A" ) << " " << std::setw(width) << std::right << str(min) << " " << std::setw(width) << std::right << str(max) << " " << std::setw(12) << std::right << count << "\n"; } private: cdouble mean, std; complex_type min, max; size_t count; value_type hmin, hwidth; std::vector<size_t> hist; std::ostream* dump; bool is_complex; std::vector<float> values; }; void print_header (bool is_complex) { int width = is_complex ? 24 : 12; std::cout << std::setw(15) << std::right << "channel" << " " << std::setw(width) << std::right << "mean"; if (!is_complex) std::cout << " " << std::setw(width) << std::right << "median"; std::cout << " " << std::setw(width) << std::right << "std. dev." << " " << std::setw(width) << std::right << "min" << " " << std::setw(width) << std::right << "max" << " " << std::setw(12) << std::right << "count\n"; } void run () { Image::Buffer<complex_type> data (argument[0]); Image::Buffer<complex_type>::voxel_type vox (data); Image::Loop inner_loop (0, 3); Image::Loop outer_loop (3); bool header_shown (!App::log_level); Ptr<std::ostream> dumpstream, hist_stream, position_stream; Options opt = get_options ("histogram"); if (opt.size()) { if (data.datatype().is_complex()) throw Exception ("histogram generation not supported for complex data types"); hist_stream = new std::ofstream (opt[0][0].c_str()); if (!*hist_stream) throw Exception ("error opening histogram file \"" + opt[0][0] + "\": " + strerror (errno)); } int nbins = 100; opt = get_options ("bins"); if (opt.size()) nbins = opt[0][0]; CalibrateHistogram calibrate (nbins); opt = get_options ("dump"); if (opt.size()) { dumpstream = new std::ofstream (opt[0][0].c_str()); if (!*dumpstream) throw Exception ("error opening dump file \"" + opt[0][0] + "\": " + strerror (errno)); } opt = get_options ("position"); if (opt.size()) { position_stream = new std::ofstream (opt[0][0].c_str()); if (!*position_stream) throw Exception ("error opening positions file \"" + opt[0][0] + "\": " + strerror (errno)); } Options voxels = get_options ("voxel"); opt = get_options ("mask"); if (opt.size()) { // within mask: if (voxels.size()) throw Exception ("cannot use mask with -voxel option"); Image::Buffer<bool> mask_data (opt[0][0]); check_dimensions (mask_data, data); Image::Buffer<bool>::voxel_type mask (mask_data); if (hist_stream) { ProgressBar progress ("calibrating histogram...", Image::voxel_count (vox)); for (outer_loop.start (vox); outer_loop.ok(); outer_loop.next (vox)) { for (inner_loop.start (mask, vox); inner_loop.ok(); inner_loop.next (mask, vox)) { if (mask.value()) calibrate (complex_type(vox.value()).real()); ++progress; } } calibrate.init (*hist_stream); } for (outer_loop.start (vox); outer_loop.ok(); outer_loop.next (vox)) { Stats stats (vox.datatype().is_complex()); if (dumpstream) stats.dump_to (*dumpstream); if (hist_stream) stats.generate_histogram (calibrate); for (inner_loop.start (mask, vox); inner_loop.ok(); inner_loop.next (mask, vox)) { if (mask.value() > 0.5) { stats (vox.value()); if (position_stream) { for (size_t i = 0; i < vox.ndim(); ++i) *position_stream << vox[i] << " "; *position_stream << "\n"; } } } if (!header_shown) print_header (vox.datatype().is_complex()); header_shown = true; stats.print (vox); if (hist_stream) stats.write_histogram (*hist_stream); } return; } if (!voxels.size()) { // whole data set: if (hist_stream) { ProgressBar progress ("calibrating histogram...", Image::voxel_count (vox)); for (outer_loop.start (vox); outer_loop.ok(); outer_loop.next (vox)) { for (inner_loop.start (vox); inner_loop.ok(); inner_loop.next (vox)) { calibrate (complex_type(vox.value()).real()); ++progress; } } calibrate.init (*hist_stream); } for (outer_loop.start (vox); outer_loop.ok(); outer_loop.next (vox)) { Stats stats (vox.datatype().is_complex()); if (dumpstream) stats.dump_to (*dumpstream); if (hist_stream) stats.generate_histogram (calibrate); for (inner_loop.start (vox); inner_loop.ok(); inner_loop.next (vox)) { stats (vox.value()); if (position_stream) { for (size_t i = 0; i < vox.ndim(); ++i) *position_stream << vox[i] << " "; *position_stream << "\n"; } } if (!header_shown) print_header (vox.datatype().is_complex()); header_shown = true; stats.print (vox); if (hist_stream) stats.write_histogram (*hist_stream); } return; } // voxels: std::vector<Point<ssize_t> > voxel (voxels.size()); for (size_t i = 0; i < voxels.size(); ++i) { std::vector<int> x = parse_ints (voxels[i][0]); if (x.size() != 3) throw Exception ("vector positions must be supplied as x,y,z"); if (x[0] < 0 || x[0] >= vox.dim (0) || x[1] < 0 || x[1] >= vox.dim (1) || x[2] < 0 || x[2] >= vox.dim (2)) throw Exception ("voxel at [ " + str (x[0]) + " " + str (x[1]) + " " + str (x[2]) + " ] is out of bounds"); voxel[i].set (x[0], x[1], x[2]); } if (hist_stream) { ProgressBar progress ("calibrating histogram...", voxel.size()); for (outer_loop.start (vox); outer_loop.ok(); outer_loop.next (vox)) { for (size_t i = 0; i < voxel.size(); ++i) { vox[0] = voxel[i][0]; vox[1] = voxel[i][1]; vox[2] = voxel[i][2]; calibrate (complex_type(vox.value()).real()); ++progress; } } calibrate.init (*hist_stream); } for (outer_loop.start (vox); outer_loop.ok(); outer_loop.next (vox)) { Stats stats (vox.datatype().is_complex()); if (dumpstream) stats.dump_to (*dumpstream); if (hist_stream) stats.generate_histogram (calibrate); for (size_t i = 0; i < voxel.size(); ++i) { vox[0] = voxel[i][0]; vox[1] = voxel[i][1]; vox[2] = voxel[i][2]; stats (vox.value()); if (position_stream) { for (size_t i = 0; i < vox.ndim(); ++i) *position_stream << vox[i] << " "; *position_stream << "\n"; } } if (!header_shown) print_header (vox.datatype().is_complex()); header_shown = true; stats.print (vox); if (hist_stream) stats.write_histogram (*hist_stream); } } <commit_msg>fix minor bug whereby 3D mask couldn't be used with 4D image<commit_after>/* Copyright 2008 Brain Research Institute, Melbourne, Australia Written by J-Donald Tournier, 27/06/08. This file is part of MRtrix. MRtrix 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. MRtrix 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 MRtrix. If not, see <http://www.gnu.org/licenses/>. */ #include <iomanip> #include "app.h" #include "point.h" #include "image/voxel.h" #include "image/buffer.h" #include "image/loop.h" MRTRIX_APPLICATION using namespace MR; using namespace App; void usage () { DESCRIPTION + "compute images statistics."; ARGUMENTS + Argument ("image", "the input image from which statistics will be computed.") .type_image_in (); OPTIONS + Option ("mask", "only perform computation within the specified binary brain mask image.") + Argument ("image").type_image_in () + Option ("voxel", "only perform computation within the specified voxel, supplied as a " "comma-separated vector of 3 integer values (multiple voxels can be included).") .allow_multiple() + Argument ("pos").type_sequence_int () + Option ("histogram", "generate histogram of intensities and store in specified text file. Note " "that the first line of the histogram gives the centre of the bins.") + Argument ("file").type_file () + Option ("bins", "the number of bins to use to generate the histogram (default = 100).") + Argument ("num").type_integer (2, 100, std::numeric_limits<int>::max()) + Option ("dump", "dump the voxel intensities to a text file.") + Argument ("file").type_file () + Option ("position", "dump the position of the voxels in the mask to a text file.") + Argument ("file").type_file (); } typedef float value_type; typedef cfloat complex_type; class CalibrateHistogram { public: CalibrateHistogram (int nbins) : min (INFINITY), max (-INFINITY), width (0.0), bins (nbins) { } value_type min, max, width; int bins; void operator() (value_type val) { if (finite (val)) { if (val < min) min = val; if (val > max) max = val; } } void init (std::ostream& stream) { width = (max - min) / float (bins+1); for (int i = 0; i < bins; i++) stream << (min + width/2.0) + i* width << " "; stream << "\n"; } }; class Stats { public: Stats (bool complex = false) : mean (0.0, 0.0), std (0.0, 0.0), min (INFINITY, INFINITY), max (-INFINITY, -INFINITY), count (0), dump (NULL) { is_complex = complex; } void generate_histogram (const CalibrateHistogram& cal) { hmin = cal.min; hwidth = cal.width; hist.resize (cal.bins); } void dump_to (std::ostream& stream) { dump = &stream; } void write_histogram (std::ostream& stream) { for (size_t i = 0; i < hist.size(); ++i) stream << hist[i] << " "; stream << "\n"; } void operator() (complex_type val) { if (finite (val.real()) && finite (val.imag())) { mean += val; std += cdouble (val.real()*val.real(), val.imag()*val.imag()); if (min.real() > val.real()) min.real() = val.real(); if (min.imag() > val.imag()) min.imag() = val.imag(); if (max.real() < val.real()) max.real() = val.real(); if (max.imag() < val.imag()) max.imag() = val.imag(); count++; if (dump) *dump << str(val) << "\n"; if (!is_complex) values.push_back(val.real()); if (hist.size()) { int bin = int ( (val.real()-hmin) / hwidth); if (bin < 0) bin = 0; else if (bin >= int (hist.size())) bin = hist.size()-1; hist[bin]++; } } } template <class Set> void print (Set& ima) { if (count == 0) throw Exception ("no voxels in mask - aborting"); mean /= double (count); std.real() = sqrt (std.real()/double(count) - mean.real()*mean.real()); std.imag() = sqrt (std.imag()/double(count) - mean.imag()*mean.imag()); std::string s = "[ "; for (size_t n = 3; n < ima.ndim(); n++) s += str (ima[n]) + " "; s += "] "; if (!is_complex) { std::sort(values.rbegin(), values.rend()); } int width = is_complex ? 24 : 12; std::cout << std::setw(15) << std::right << s << " " << std::setw(width) << std::right << str(mean); if (!is_complex) { std::cout << " " << std::setw(width) << std::right << values[round(float(values.size()) / 2.0)]; } std::cout << " " << std::setw(width) << std::right << ( count > 1 ? str(std) : "N/A" ) << " " << std::setw(width) << std::right << str(min) << " " << std::setw(width) << std::right << str(max) << " " << std::setw(12) << std::right << count << "\n"; } private: cdouble mean, std; complex_type min, max; size_t count; value_type hmin, hwidth; std::vector<size_t> hist; std::ostream* dump; bool is_complex; std::vector<float> values; }; void print_header (bool is_complex) { int width = is_complex ? 24 : 12; std::cout << std::setw(15) << std::right << "channel" << " " << std::setw(width) << std::right << "mean"; if (!is_complex) std::cout << " " << std::setw(width) << std::right << "median"; std::cout << " " << std::setw(width) << std::right << "std. dev." << " " << std::setw(width) << std::right << "min" << " " << std::setw(width) << std::right << "max" << " " << std::setw(12) << std::right << "count\n"; } void run () { Image::Buffer<complex_type> data (argument[0]); Image::Buffer<complex_type>::voxel_type vox (data); Image::Loop inner_loop (0, 3); Image::Loop outer_loop (3); bool header_shown (!App::log_level); Ptr<std::ostream> dumpstream, hist_stream, position_stream; Options opt = get_options ("histogram"); if (opt.size()) { if (data.datatype().is_complex()) throw Exception ("histogram generation not supported for complex data types"); hist_stream = new std::ofstream (opt[0][0].c_str()); if (!*hist_stream) throw Exception ("error opening histogram file \"" + opt[0][0] + "\": " + strerror (errno)); } int nbins = 100; opt = get_options ("bins"); if (opt.size()) nbins = opt[0][0]; CalibrateHistogram calibrate (nbins); opt = get_options ("dump"); if (opt.size()) { dumpstream = new std::ofstream (opt[0][0].c_str()); if (!*dumpstream) throw Exception ("error opening dump file \"" + opt[0][0] + "\": " + strerror (errno)); } opt = get_options ("position"); if (opt.size()) { position_stream = new std::ofstream (opt[0][0].c_str()); if (!*position_stream) throw Exception ("error opening positions file \"" + opt[0][0] + "\": " + strerror (errno)); } Options voxels = get_options ("voxel"); opt = get_options ("mask"); if (opt.size()) { // within mask: if (voxels.size()) throw Exception ("cannot use mask with -voxel option"); Image::Buffer<bool> mask_data (opt[0][0]); check_dimensions (mask_data, data, 0, 3); Image::Buffer<bool>::voxel_type mask (mask_data); if (hist_stream) { ProgressBar progress ("calibrating histogram...", Image::voxel_count (vox)); for (outer_loop.start (vox); outer_loop.ok(); outer_loop.next (vox)) { for (inner_loop.start (mask, vox); inner_loop.ok(); inner_loop.next (mask, vox)) { if (mask.value()) calibrate (complex_type(vox.value()).real()); ++progress; } } calibrate.init (*hist_stream); } for (outer_loop.start (vox); outer_loop.ok(); outer_loop.next (vox)) { Stats stats (vox.datatype().is_complex()); if (dumpstream) stats.dump_to (*dumpstream); if (hist_stream) stats.generate_histogram (calibrate); for (inner_loop.start (mask, vox); inner_loop.ok(); inner_loop.next (mask, vox)) { if (mask.value() > 0.5) { stats (vox.value()); if (position_stream) { for (size_t i = 0; i < vox.ndim(); ++i) *position_stream << vox[i] << " "; *position_stream << "\n"; } } } if (!header_shown) print_header (vox.datatype().is_complex()); header_shown = true; stats.print (vox); if (hist_stream) stats.write_histogram (*hist_stream); } return; } if (!voxels.size()) { // whole data set: if (hist_stream) { ProgressBar progress ("calibrating histogram...", Image::voxel_count (vox)); for (outer_loop.start (vox); outer_loop.ok(); outer_loop.next (vox)) { for (inner_loop.start (vox); inner_loop.ok(); inner_loop.next (vox)) { calibrate (complex_type(vox.value()).real()); ++progress; } } calibrate.init (*hist_stream); } for (outer_loop.start (vox); outer_loop.ok(); outer_loop.next (vox)) { Stats stats (vox.datatype().is_complex()); if (dumpstream) stats.dump_to (*dumpstream); if (hist_stream) stats.generate_histogram (calibrate); for (inner_loop.start (vox); inner_loop.ok(); inner_loop.next (vox)) { stats (vox.value()); if (position_stream) { for (size_t i = 0; i < vox.ndim(); ++i) *position_stream << vox[i] << " "; *position_stream << "\n"; } } if (!header_shown) print_header (vox.datatype().is_complex()); header_shown = true; stats.print (vox); if (hist_stream) stats.write_histogram (*hist_stream); } return; } // voxels: std::vector<Point<ssize_t> > voxel (voxels.size()); for (size_t i = 0; i < voxels.size(); ++i) { std::vector<int> x = parse_ints (voxels[i][0]); if (x.size() != 3) throw Exception ("vector positions must be supplied as x,y,z"); if (x[0] < 0 || x[0] >= vox.dim (0) || x[1] < 0 || x[1] >= vox.dim (1) || x[2] < 0 || x[2] >= vox.dim (2)) throw Exception ("voxel at [ " + str (x[0]) + " " + str (x[1]) + " " + str (x[2]) + " ] is out of bounds"); voxel[i].set (x[0], x[1], x[2]); } if (hist_stream) { ProgressBar progress ("calibrating histogram...", voxel.size()); for (outer_loop.start (vox); outer_loop.ok(); outer_loop.next (vox)) { for (size_t i = 0; i < voxel.size(); ++i) { vox[0] = voxel[i][0]; vox[1] = voxel[i][1]; vox[2] = voxel[i][2]; calibrate (complex_type(vox.value()).real()); ++progress; } } calibrate.init (*hist_stream); } for (outer_loop.start (vox); outer_loop.ok(); outer_loop.next (vox)) { Stats stats (vox.datatype().is_complex()); if (dumpstream) stats.dump_to (*dumpstream); if (hist_stream) stats.generate_histogram (calibrate); for (size_t i = 0; i < voxel.size(); ++i) { vox[0] = voxel[i][0]; vox[1] = voxel[i][1]; vox[2] = voxel[i][2]; stats (vox.value()); if (position_stream) { for (size_t i = 0; i < vox.ndim(); ++i) *position_stream << vox[i] << " "; *position_stream << "\n"; } } if (!header_shown) print_header (vox.datatype().is_complex()); header_shown = true; stats.print (vox); if (hist_stream) stats.write_histogram (*hist_stream); } } <|endoftext|>
<commit_before>/* Highly Optimized Object-Oriented Molecular Dynamics (HOOMD) Open Source Software License Copyright (c) 2008 Ames Laboratory Iowa State University All rights reserved. Redistribution and use of HOOMD, 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 holder nor the names HOOMD's contributors may be used to endorse or promote products derived from this software without specific prior written permission. Disclaimer THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // $Id: FENEBondForceCompute.cc 1127 2008-08-31 19:54:39Z phillicl $ // $URL: https://svn2.assembla.com/svn/hoomd/tags/hoomd-0.7.0/src/computes/FENEBondForceCompute.cc $ // Maintainer: phillicl #ifdef WIN32 #pragma warning( push ) #pragma warning( disable : 4103 4244 ) #endif #include <boost/python.hpp> using namespace boost::python; #include "FENEBondForceCompute.h" #include <iostream> #include <sstream> #include <stdexcept> #include <math.h> using namespace std; /*! \file FENEBondForceCompute.cc \brief Defines the FENEBondForceCompute class */ /*! \param sysdef System to compute forces on \post Memory is allocated, default parameters are set and forces are zeroed. */ FENEBondForceCompute::FENEBondForceCompute(boost::shared_ptr<SystemDefinition> sysdef) : ForceCompute(sysdef), m_K(NULL), m_r_0(NULL), m_lj1(NULL), m_lj2(NULL), m_epsilon(NULL) { // access the bond data for later use m_bond_data = m_sysdef->getBondData(); // check for some silly errors a user could make if (m_bond_data->getNBondTypes() == 0) { cout << endl << "***Error! No bond types specified" << endl << endl; throw runtime_error("Error initializing FENEBondForceCompute"); } // allocate the parameters m_K = new Scalar[m_bond_data->getNBondTypes()]; m_r_0 = new Scalar[m_bond_data->getNBondTypes()]; m_lj1 = new Scalar[m_bond_data->getNBondTypes()]; m_lj2 = new Scalar[m_bond_data->getNBondTypes()]; m_epsilon = new Scalar[m_bond_data->getNBondTypes()]; // initialize parameters memset(m_K, 0, sizeof(Scalar) * m_bond_data->getNBondTypes()); memset(m_r_0, 0, sizeof(Scalar) * m_bond_data->getNBondTypes()); for (unsigned int i = 0; i < m_bond_data->getNBondTypes(); i++) m_lj1[i]=Scalar(1.0); for (unsigned int i = 0; i < m_bond_data->getNBondTypes(); i++) m_lj2[i]=Scalar(1.0); memset(m_epsilon, 0, sizeof(Scalar) * m_bond_data->getNBondTypes()); } FENEBondForceCompute::~FENEBondForceCompute() { delete[] m_K; delete[] m_r_0; delete[] m_lj1; delete[] m_lj2; delete[] m_epsilon; } /*! \param type Type of the bond to set parameters for \param K Stiffness parameter for the force computation \param r_0 maximum bond length for the force computation \param sigma Value of sigma in the force calculation \param epsilon Value of epsilon in the force calculation Sets parameters for the potential of a particular bond type */ void FENEBondForceCompute::setParams(unsigned int type, Scalar K, Scalar r_0, Scalar sigma, Scalar epsilon) { // make sure the type is valid if (type >= m_bond_data->getNBondTypes()) { cout << endl << "***Error! Invalid bond type specified" << endl << endl; throw runtime_error("Error setting parameters in FENEBondForceCompute"); } m_K[type] = K; m_r_0[type] = r_0; m_lj1[type] = 4*epsilon*pow(sigma,12); m_lj2[type] = 4*epsilon*pow(sigma,6); m_epsilon[type] = epsilon; //cout << "Setting FENE parameters K=" << K << ", r0=" << r_0 << ", sigma=" << sigma << ", lj1=" << m_lj1[type] << ", lj2=" << m_lj2[type] << ", epsilon=" << m_epsilon[type] << endl; // check for some silly errors a user could make if (K <= 0) cout << "***Warning! K <= 0 specified for fene bond" << endl; if (r_0 <= 0) cout << "***Warning! r_0 <= 0 specified for fene bond" << endl; if (sigma <= 0) cout << "***Warning! sigma <= 0 specified for fene bond" << endl; if (epsilon <= 0) cout << "***Warning! epsilon <= 0 specified for fene bond" << endl; } /*! BondForceCompute provides - \c fene_energy */ std::vector< std::string > FENEBondForceCompute::getProvidedLogQuantities() { vector<string> list; list.push_back("bond_fene_energy"); return list; } /*! \param quantity Name of the quantity to get the log value of \param timestep Current time step of the simulation */ Scalar FENEBondForceCompute::getLogValue(const std::string& quantity, unsigned int timestep) { if (quantity == string("bond_fene_energy")) { compute(timestep); return calcEnergySum(); } else { cerr << endl << "***Error! " << quantity << " is not a valid log quantity for FENEBondForceCompute" << endl << endl; throw runtime_error("Error getting log value"); } } /*! Actually perform the force computation \param timestep Current time step */ void FENEBondForceCompute::computeForces(unsigned int timestep) { if (m_prof) m_prof->push("FENE"); assert(m_pdata); // access the particle data arrays ParticleDataArraysConst arrays = m_pdata->acquireReadOnly(); // there are enough other checks on the input data: but it doesn't hurt to be safe assert(m_fx); assert(m_fy); assert(m_fz); assert(m_pe); assert(arrays.x); assert(arrays.y); assert(arrays.z); assert(arrays.diameter); // get a local copy of the simulation box too const BoxDim& box = m_pdata->getBox(); // sanity check assert(box.xhi > box.xlo && box.yhi > box.ylo && box.zhi > box.zlo); // precalculate box lengths Scalar Lx = box.xhi - box.xlo; Scalar Ly = box.yhi - box.ylo; Scalar Lz = box.zhi - box.zlo; Scalar Lx2 = Lx / Scalar(2.0); Scalar Ly2 = Ly / Scalar(2.0); Scalar Lz2 = Lz / Scalar(2.0); // need to start from a zero force, potential energy and virial // (MEM TRANSFER: 5 Scalars) memset((void*)m_fx, 0, sizeof(Scalar) * m_pdata->getN()); memset((void*)m_fy, 0, sizeof(Scalar) * m_pdata->getN()); memset((void*)m_fz, 0, sizeof(Scalar) * m_pdata->getN()); memset((void*)m_pe, 0, sizeof(Scalar) * m_pdata->getN()); memset((void*)m_virial, 0, sizeof(Scalar) * m_pdata->getN()); // for each of the bonds const unsigned int size = (unsigned int)m_bond_data->getNumBonds(); for (unsigned int i = 0; i < size; i++) { // lookup the tag of each of the particles participating in the bond const Bond& bond = m_bond_data->getBond(i); assert(bond.a < m_pdata->getN()); assert(bond.b < m_pdata->getN()); // transform a and b into indicies into the particle data arrays // (MEM TRANSFER: 4 integers) unsigned int idx_a = arrays.rtag[bond.a]; unsigned int idx_b = arrays.rtag[bond.b]; assert(idx_a < m_pdata->getN()); assert(idx_b < m_pdata->getN()); // calculate d\vec{r} // (MEM TRANSFER: 6 Scalars / FLOPS: 3) Scalar dx = arrays.x[idx_b] - arrays.x[idx_a]; Scalar dy = arrays.y[idx_b] - arrays.y[idx_a]; Scalar dz = arrays.z[idx_b] - arrays.z[idx_a]; Scalar diameter_a = arrays.diameter[idx_a]; Scalar diameter_b = arrays.diameter[idx_b]; // if the vector crosses the box, pull it back // (FLOPS: 9 (worst case: first branch is missed, the 2nd is taken and the add is done)) if (dx >= Lx2) dx -= Lx; else if (dx < -Lx2) dx += Lx; if (dy >= Ly2) dy -= Ly; else if (dy < -Ly2) dy += Ly; if (dz >= Lz2) dz -= Lz; else if (dz < -Lz2) dz += Lz; // sanity check assert(dx >= box.xlo && dx < box.xhi); assert(dy >= box.ylo && dx < box.yhi); assert(dz >= box.zlo && dx < box.zhi); //ALL FLOPS NEED TO BE FIXED // on paper, the formula turns out to be: F = -K/(1-(r/r_0)^2) * \vec{r} + (12*lj1/r^12 - 6*lj2/r^6) *\vec{r} // FLOPS: 5 Scalar rsq = dx*dx+dy*dy+dz*dz; //If appropriate, correct the rsq for particles that are not unit in size. if (diameter_a != 1.0 || diameter_b != 1.0) { Scalar rtemp = sqrt(rsq) - diameter_a/2 - diameter_b/2 - 1.0; rsq = rtemp*rtemp; } // compute the force magnitude/r in forcemag_divr (FLOPS: 9) Scalar r2inv = Scalar(1.0)/rsq; Scalar r6inv = r2inv * r2inv * r2inv; Scalar WCAforcemag_divr; Scalar pair_eng; if (rsq < 1.2599210498) { //wcalimit squared (2^(1/6))^2 WCAforcemag_divr = r2inv * r6inv * (Scalar(12.0)*m_lj1[bond.type]*r6inv - Scalar(6.0)*m_lj2[bond.type]); pair_eng = Scalar(0.5) * (r6inv * (m_lj1[bond.type]*r6inv - m_lj2[bond.type]) + m_epsilon[bond.type]); } else { WCAforcemag_divr = 0; pair_eng = 0; } // Additional check for FENE spring assert(rsq < m_r_0[bond.type]*m_r_0[bond.type]); // calculate force and energy // MEM TRANSFER 2 Scalars: FLOPS: 13 Scalar forcemag_divr = -m_K[bond.type] / (Scalar(1.0) - rsq /(m_r_0[bond.type]*m_r_0[bond.type])) + WCAforcemag_divr; //FLOPS 4 Scalar bond_eng = -Scalar(0.5) * Scalar(0.5) * m_K[bond.type] * (m_r_0[bond.type] * m_r_0[bond.type]) * log(Scalar(1.0) - rsq/(m_r_0[bond.type] * m_r_0[bond.type])); // calculate virial (FLOPS: 2) Scalar bond_virial = Scalar(1.0/6.0) * rsq * forcemag_divr; // add the force to the particles // (MEM TRANSFER: 20 Scalars / FLOPS 16) m_fx[idx_b] += forcemag_divr * dx; m_fy[idx_b] += forcemag_divr * dy; m_fz[idx_b] += forcemag_divr * dz; m_pe[idx_b] += bond_eng + pair_eng; m_virial[idx_b] += bond_virial; m_fx[idx_a] -= forcemag_divr * dx; m_fy[idx_a] -= forcemag_divr * dy; m_fz[idx_a] -= forcemag_divr * dz; m_pe[idx_a] += bond_eng + pair_eng; m_virial[idx_a] += bond_virial; } m_pdata->release(); #ifdef ENABLE_CUDA // the data is now only up to date on the CPU m_data_location = cpu; #endif if (m_prof) m_prof->pop(m_bond_data->getNumBonds() * (3+9+5+13+2+16), m_pdata->getN() * 5 * sizeof(Scalar) + m_bond_data->getNumBonds() * ( (4) * sizeof(unsigned int) + (6+2+20) ) ); } void export_FENEBondForceCompute() { class_<FENEBondForceCompute, boost::shared_ptr<FENEBondForceCompute>, bases<ForceCompute>, boost::noncopyable > ("FENEBondForceCompute", init< boost::shared_ptr<SystemDefinition> >()) .def("setParams", &FENEBondForceCompute::setParams) ; } #ifdef WIN32 #pragma warning( pop ) #endif <commit_msg>Stupid sign error<commit_after>/* Highly Optimized Object-Oriented Molecular Dynamics (HOOMD) Open Source Software License Copyright (c) 2008 Ames Laboratory Iowa State University All rights reserved. Redistribution and use of HOOMD, 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 holder nor the names HOOMD's contributors may be used to endorse or promote products derived from this software without specific prior written permission. Disclaimer THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // $Id: FENEBondForceCompute.cc 1127 2008-08-31 19:54:39Z phillicl $ // $URL: https://svn2.assembla.com/svn/hoomd/tags/hoomd-0.7.0/src/computes/FENEBondForceCompute.cc $ // Maintainer: phillicl #ifdef WIN32 #pragma warning( push ) #pragma warning( disable : 4103 4244 ) #endif #include <boost/python.hpp> using namespace boost::python; #include "FENEBondForceCompute.h" #include <iostream> #include <sstream> #include <stdexcept> #include <math.h> using namespace std; /*! \file FENEBondForceCompute.cc \brief Defines the FENEBondForceCompute class */ /*! \param sysdef System to compute forces on \post Memory is allocated, default parameters are set and forces are zeroed. */ FENEBondForceCompute::FENEBondForceCompute(boost::shared_ptr<SystemDefinition> sysdef) : ForceCompute(sysdef), m_K(NULL), m_r_0(NULL), m_lj1(NULL), m_lj2(NULL), m_epsilon(NULL) { // access the bond data for later use m_bond_data = m_sysdef->getBondData(); // check for some silly errors a user could make if (m_bond_data->getNBondTypes() == 0) { cout << endl << "***Error! No bond types specified" << endl << endl; throw runtime_error("Error initializing FENEBondForceCompute"); } // allocate the parameters m_K = new Scalar[m_bond_data->getNBondTypes()]; m_r_0 = new Scalar[m_bond_data->getNBondTypes()]; m_lj1 = new Scalar[m_bond_data->getNBondTypes()]; m_lj2 = new Scalar[m_bond_data->getNBondTypes()]; m_epsilon = new Scalar[m_bond_data->getNBondTypes()]; // initialize parameters memset(m_K, 0, sizeof(Scalar) * m_bond_data->getNBondTypes()); memset(m_r_0, 0, sizeof(Scalar) * m_bond_data->getNBondTypes()); for (unsigned int i = 0; i < m_bond_data->getNBondTypes(); i++) m_lj1[i]=Scalar(1.0); for (unsigned int i = 0; i < m_bond_data->getNBondTypes(); i++) m_lj2[i]=Scalar(1.0); memset(m_epsilon, 0, sizeof(Scalar) * m_bond_data->getNBondTypes()); } FENEBondForceCompute::~FENEBondForceCompute() { delete[] m_K; delete[] m_r_0; delete[] m_lj1; delete[] m_lj2; delete[] m_epsilon; } /*! \param type Type of the bond to set parameters for \param K Stiffness parameter for the force computation \param r_0 maximum bond length for the force computation \param sigma Value of sigma in the force calculation \param epsilon Value of epsilon in the force calculation Sets parameters for the potential of a particular bond type */ void FENEBondForceCompute::setParams(unsigned int type, Scalar K, Scalar r_0, Scalar sigma, Scalar epsilon) { // make sure the type is valid if (type >= m_bond_data->getNBondTypes()) { cout << endl << "***Error! Invalid bond type specified" << endl << endl; throw runtime_error("Error setting parameters in FENEBondForceCompute"); } m_K[type] = K; m_r_0[type] = r_0; m_lj1[type] = 4*epsilon*pow(sigma,12); m_lj2[type] = 4*epsilon*pow(sigma,6); m_epsilon[type] = epsilon; //cout << "Setting FENE parameters K=" << K << ", r0=" << r_0 << ", sigma=" << sigma << ", lj1=" << m_lj1[type] << ", lj2=" << m_lj2[type] << ", epsilon=" << m_epsilon[type] << endl; // check for some silly errors a user could make if (K <= 0) cout << "***Warning! K <= 0 specified for fene bond" << endl; if (r_0 <= 0) cout << "***Warning! r_0 <= 0 specified for fene bond" << endl; if (sigma <= 0) cout << "***Warning! sigma <= 0 specified for fene bond" << endl; if (epsilon <= 0) cout << "***Warning! epsilon <= 0 specified for fene bond" << endl; } /*! BondForceCompute provides - \c fene_energy */ std::vector< std::string > FENEBondForceCompute::getProvidedLogQuantities() { vector<string> list; list.push_back("bond_fene_energy"); return list; } /*! \param quantity Name of the quantity to get the log value of \param timestep Current time step of the simulation */ Scalar FENEBondForceCompute::getLogValue(const std::string& quantity, unsigned int timestep) { if (quantity == string("bond_fene_energy")) { compute(timestep); return calcEnergySum(); } else { cerr << endl << "***Error! " << quantity << " is not a valid log quantity for FENEBondForceCompute" << endl << endl; throw runtime_error("Error getting log value"); } } /*! Actually perform the force computation \param timestep Current time step */ void FENEBondForceCompute::computeForces(unsigned int timestep) { if (m_prof) m_prof->push("FENE"); assert(m_pdata); // access the particle data arrays ParticleDataArraysConst arrays = m_pdata->acquireReadOnly(); // there are enough other checks on the input data: but it doesn't hurt to be safe assert(m_fx); assert(m_fy); assert(m_fz); assert(m_pe); assert(arrays.x); assert(arrays.y); assert(arrays.z); assert(arrays.diameter); // get a local copy of the simulation box too const BoxDim& box = m_pdata->getBox(); // sanity check assert(box.xhi > box.xlo && box.yhi > box.ylo && box.zhi > box.zlo); // precalculate box lengths Scalar Lx = box.xhi - box.xlo; Scalar Ly = box.yhi - box.ylo; Scalar Lz = box.zhi - box.zlo; Scalar Lx2 = Lx / Scalar(2.0); Scalar Ly2 = Ly / Scalar(2.0); Scalar Lz2 = Lz / Scalar(2.0); // need to start from a zero force, potential energy and virial // (MEM TRANSFER: 5 Scalars) memset((void*)m_fx, 0, sizeof(Scalar) * m_pdata->getN()); memset((void*)m_fy, 0, sizeof(Scalar) * m_pdata->getN()); memset((void*)m_fz, 0, sizeof(Scalar) * m_pdata->getN()); memset((void*)m_pe, 0, sizeof(Scalar) * m_pdata->getN()); memset((void*)m_virial, 0, sizeof(Scalar) * m_pdata->getN()); // for each of the bonds const unsigned int size = (unsigned int)m_bond_data->getNumBonds(); for (unsigned int i = 0; i < size; i++) { // lookup the tag of each of the particles participating in the bond const Bond& bond = m_bond_data->getBond(i); assert(bond.a < m_pdata->getN()); assert(bond.b < m_pdata->getN()); // transform a and b into indicies into the particle data arrays // (MEM TRANSFER: 4 integers) unsigned int idx_a = arrays.rtag[bond.a]; unsigned int idx_b = arrays.rtag[bond.b]; assert(idx_a < m_pdata->getN()); assert(idx_b < m_pdata->getN()); // calculate d\vec{r} // (MEM TRANSFER: 6 Scalars / FLOPS: 3) Scalar dx = arrays.x[idx_b] - arrays.x[idx_a]; Scalar dy = arrays.y[idx_b] - arrays.y[idx_a]; Scalar dz = arrays.z[idx_b] - arrays.z[idx_a]; Scalar diameter_a = arrays.diameter[idx_a]; Scalar diameter_b = arrays.diameter[idx_b]; // if the vector crosses the box, pull it back // (FLOPS: 9 (worst case: first branch is missed, the 2nd is taken and the add is done)) if (dx >= Lx2) dx -= Lx; else if (dx < -Lx2) dx += Lx; if (dy >= Ly2) dy -= Ly; else if (dy < -Ly2) dy += Ly; if (dz >= Lz2) dz -= Lz; else if (dz < -Lz2) dz += Lz; // sanity check assert(dx >= box.xlo && dx < box.xhi); assert(dy >= box.ylo && dx < box.yhi); assert(dz >= box.zlo && dx < box.zhi); //ALL FLOPS NEED TO BE FIXED // on paper, the formula turns out to be: F = -K/(1-(r/r_0)^2) * \vec{r} + (12*lj1/r^12 - 6*lj2/r^6) *\vec{r} // FLOPS: 5 Scalar rsq = dx*dx+dy*dy+dz*dz; //If appropriate, correct the rsq for particles that are not unit in size. if (diameter_a != 1.0 || diameter_b != 1.0) { Scalar rtemp = sqrt(rsq) - diameter_a/2 - diameter_b/2 + 1.0; rsq = rtemp*rtemp; } // compute the force magnitude/r in forcemag_divr (FLOPS: 9) Scalar r2inv = Scalar(1.0)/rsq; Scalar r6inv = r2inv * r2inv * r2inv; Scalar WCAforcemag_divr; Scalar pair_eng; if (rsq < 1.2599210498) { //wcalimit squared (2^(1/6))^2 WCAforcemag_divr = r2inv * r6inv * (Scalar(12.0)*m_lj1[bond.type]*r6inv - Scalar(6.0)*m_lj2[bond.type]); pair_eng = Scalar(0.5) * (r6inv * (m_lj1[bond.type]*r6inv - m_lj2[bond.type]) + m_epsilon[bond.type]); } else { WCAforcemag_divr = 0; pair_eng = 0; } // Additional check for FENE spring assert(rsq < m_r_0[bond.type]*m_r_0[bond.type]); // calculate force and energy // MEM TRANSFER 2 Scalars: FLOPS: 13 Scalar forcemag_divr = -m_K[bond.type] / (Scalar(1.0) - rsq /(m_r_0[bond.type]*m_r_0[bond.type])) + WCAforcemag_divr; //FLOPS 4 Scalar bond_eng = -Scalar(0.5) * Scalar(0.5) * m_K[bond.type] * (m_r_0[bond.type] * m_r_0[bond.type]) * log(Scalar(1.0) - rsq/(m_r_0[bond.type] * m_r_0[bond.type])); // calculate virial (FLOPS: 2) Scalar bond_virial = Scalar(1.0/6.0) * rsq * forcemag_divr; // add the force to the particles // (MEM TRANSFER: 20 Scalars / FLOPS 16) m_fx[idx_b] += forcemag_divr * dx; m_fy[idx_b] += forcemag_divr * dy; m_fz[idx_b] += forcemag_divr * dz; m_pe[idx_b] += bond_eng + pair_eng; m_virial[idx_b] += bond_virial; m_fx[idx_a] -= forcemag_divr * dx; m_fy[idx_a] -= forcemag_divr * dy; m_fz[idx_a] -= forcemag_divr * dz; m_pe[idx_a] += bond_eng + pair_eng; m_virial[idx_a] += bond_virial; } m_pdata->release(); #ifdef ENABLE_CUDA // the data is now only up to date on the CPU m_data_location = cpu; #endif if (m_prof) m_prof->pop(m_bond_data->getNumBonds() * (3+9+5+13+2+16), m_pdata->getN() * 5 * sizeof(Scalar) + m_bond_data->getNumBonds() * ( (4) * sizeof(unsigned int) + (6+2+20) ) ); } void export_FENEBondForceCompute() { class_<FENEBondForceCompute, boost::shared_ptr<FENEBondForceCompute>, bases<ForceCompute>, boost::noncopyable > ("FENEBondForceCompute", init< boost::shared_ptr<SystemDefinition> >()) .def("setParams", &FENEBondForceCompute::setParams) ; } #ifdef WIN32 #pragma warning( pop ) #endif <|endoftext|>
<commit_before>/*===========================================================================*\ | | FILE: Plugin.cpp | Skeleton project and code for a Texture Map | 3D Studio MAX R3.0 | | AUTH: Harry Denholm | Developer Consulting Group | Copyright(c) Discreet 1999 | | HIST: Started 11-3-99 | \*===========================================================================*/ #include "Texmap.h" HINSTANCE hInstance; int controlsInit = FALSE; BOOL WINAPI DllMain(HINSTANCE hinstDLL,ULONG fdwReason,LPVOID lpvReserved) { #ifndef MAX_RELEASE_R9 hInstance = hinstDLL; if ( !controlsInit ) { controlsInit = TRUE; InitCustomControls(hInstance); InitCommonControls(); } switch(fdwReason) { case DLL_PROCESS_ATTACH: break; case DLL_THREAD_ATTACH: break; case DLL_THREAD_DETACH: break; case DLL_PROCESS_DETACH: break; } #else if( fdwReason == DLL_PROCESS_ATTACH ) { hInstance = hinstDLL; DisableThreadLibraryCalls(hInstance); } #endif return(TRUE); } __declspec( dllexport ) const TCHAR * LibDescription() { return GetString(IDS_LIBDESC); } __declspec( dllexport ) int LibNumberClasses() { return 1; } __declspec( dllexport ) ClassDesc* LibClassDesc(int i) { switch(i) { case 0: return GetStressTexmapDesc(); default: return 0; } } __declspec( dllexport ) ULONG LibVersion() { return VERSION_3DSMAX; } TCHAR *GetString(int id) { static TCHAR buf[256]; if(hInstance) return LoadString(hInstance, id, buf, sizeof(buf)) ? buf : NULL; return NULL; } <commit_msg>Added support for Max 2012 to 2015<commit_after>/*===========================================================================*\ | | FILE: Plugin.cpp | Skeleton project and code for a Texture Map | 3D Studio MAX R3.0 | | AUTH: Harry Denholm | Developer Consulting Group | Copyright(c) Discreet 1999 | | HIST: Started 11-3-99 | \*===========================================================================*/ #include "Texmap.h" HINSTANCE hInstance; #if MAX_VERSION_MAJOR < 10 int controlsInit = FALSE; #endif BOOL WINAPI DllMain(HINSTANCE hinstDLL,ULONG fdwReason,LPVOID lpvReserved) { #if MAX_VERSION_MAJOR < 10 hInstance = hinstDLL; if ( !controlsInit ) { controlsInit = TRUE; InitCustomControls(hInstance); InitCommonControls(); } switch(fdwReason) { case DLL_PROCESS_ATTACH: break; case DLL_THREAD_ATTACH: break; case DLL_THREAD_DETACH: break; case DLL_PROCESS_DETACH: break; } #else if( fdwReason == DLL_PROCESS_ATTACH ) { hInstance = hinstDLL; DisableThreadLibraryCalls(hInstance); } #endif return(TRUE); } __declspec( dllexport ) const TCHAR * LibDescription() { return GetString(IDS_LIBDESC); } __declspec( dllexport ) int LibNumberClasses() { return 1; } __declspec( dllexport ) ClassDesc* LibClassDesc(int i) { switch(i) { case 0: return GetStressTexmapDesc(); default: return 0; } } __declspec( dllexport ) ULONG LibVersion() { return VERSION_3DSMAX; } __declspec( dllexport ) ULONG CanAutoDefer() { return 1; } TCHAR *GetString(int id) { static TCHAR buf[256]; if(hInstance) #if MAX_VERSION_MAJOR < 15 return LoadString(hInstance, id, buf, sizeof(buf)) ? buf : NULL; #else return LoadString(hInstance, id, buf, _countof(buf)) ? buf : NULL; #endif return NULL; } <|endoftext|>
<commit_before>// [WriteFile Name=ServiceArea, Category=Routing] // [Legal] // Copyright 2017 Esri. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [Legal] #include "ServiceArea.h" #include "Map.h" #include "MapQuickView.h" #include "PictureMarkerSymbol.h" #include "PolylineBuilder.h" #include "ServiceAreaTask.h" #include "SimpleFillSymbol.h" #include "SimpleLineSymbol.h" #include "SimpleRenderer.h" using namespace Esri::ArcGISRuntime; ServiceArea::ServiceArea(QQuickItem* parent /* = nullptr */): QQuickItem(parent), m_task(new ServiceAreaTask( QUrl("http://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/ServiceArea"), this)) { } ServiceArea::~ServiceArea() { } void ServiceArea::init() { qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView"); qmlRegisterType<ServiceArea>("Esri.Samples", 1, 0, "ServiceAreaSample"); } void ServiceArea::componentComplete() { QQuickItem::componentComplete(); // find QML MapView component m_mapView = findChild<MapQuickView*>("mapView"); m_mapView->setWrapAroundMode(WrapAroundMode::Disabled); // set view to be over San Diego m_map = new Map(Basemap::streets(this), this); m_map->setInitialViewpoint(Viewpoint(Point(-13041154, 3858170, SpatialReference(3857)), 1e5)); // Set map to map view m_mapView->setMap(m_map); connect(m_task, &ServiceAreaTask::doneLoading, this, [this](Esri::ArcGISRuntime::Error loadError) { if (!loadError.isEmpty()) return; if (m_task->loadStatus() != LoadStatus::Loaded) return; setupRouting(); }); m_task->load(); setupGraphics(); } void ServiceArea::setFacilityMode() { m_mode = SampleMode::Facility; } void ServiceArea::setBarrierMode() { if (m_barrierBuilder != nullptr) return; m_barrierBuilder = new PolylineBuilder(SpatialReference::webMercator(), this); m_mode = SampleMode::Barrier; } void ServiceArea::solveServiceArea() { setBusy(true); m_parameters.clearFacilities(); m_parameters.clearPolylineBarriers(); GraphicListModel* facilitiesGraphics = m_facilitiesOverlay->graphics(); if (facilitiesGraphics == nullptr || facilitiesGraphics->rowCount() == 0) { setBusy(false); m_message = "At least 1 Facility is required."; emit messageChanged(); return; } QList<ServiceAreaFacility> facilities; facilities.reserve(facilitiesGraphics->rowCount()); for (int f = 0; f < facilitiesGraphics->rowCount(); ++f) { Graphic* g = facilitiesGraphics->at(f); if (!g) continue; facilities.append(ServiceAreaFacility(g->geometry())); } m_parameters.setFacilities(facilities); GraphicListModel* barrierGraphics = m_barrierOverlay->graphics(); QList<PolylineBarrier> barriers; barriers.reserve(barrierGraphics->rowCount()); for (int b = 0; b < barrierGraphics->rowCount(); ++b) { Graphic* g = barrierGraphics->at(b); if (!g) continue; barriers.append(PolylineBarrier(g->geometry())); } if (!barriers.isEmpty()) m_parameters.setPolylineBarriers(barriers); m_task->solveServiceArea(m_parameters); } void ServiceArea::reset() { m_facilitiesOverlay->graphics()->clear(); m_barrierOverlay->graphics()->clear(); if (m_barrierBuilder) { delete m_barrierBuilder; m_barrierBuilder = new PolylineBuilder(SpatialReference::webMercator(), this); } m_areasOverlay->graphics()->clear(); if (m_graphicParent) { delete m_graphicParent; m_graphicParent = nullptr; } } void ServiceArea::newBarrier() { if (m_barrierBuilder) { delete m_barrierBuilder; m_barrierBuilder = nullptr; } setBarrierMode(); if (!m_graphicParent) m_graphicParent = new QObject(this); m_barrierOverlay->graphics()->append(new Graphic(m_barrierBuilder->toPolyline(), m_graphicParent)); } bool ServiceArea::busy() const { return m_busy; } QString ServiceArea::message() const { return m_message; } void ServiceArea::setBusy(bool val) { if (m_busy == val) return; m_message.clear(); m_busy = val; emit busyChanged(); emit messageChanged(); } void ServiceArea::setupGraphics() { // create a symbol for the incidents PictureMarkerSymbol* facilitySymbol = new PictureMarkerSymbol( QUrl(QStringLiteral("http://static.arcgis.com/images/Symbols/SafetyHealth/Hospital.png")), this); facilitySymbol->setHeight(30); facilitySymbol->setWidth(30); // create a graphics overlay for the facilities and add a renderer for the symbol m_facilitiesOverlay = new GraphicsOverlay(this); SimpleRenderer* renderer = new SimpleRenderer(facilitySymbol, this); m_facilitiesOverlay->setRenderer(renderer); m_mapView->graphicsOverlays()->append(m_facilitiesOverlay); // create a symbol for the barriers float lineWidth = 3.0f; SimpleLineSymbol* lineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle::Solid, Qt::black, lineWidth, this); m_barrierOverlay = new GraphicsOverlay(this); SimpleRenderer* lineRenderer = new SimpleRenderer(lineSymbol, this); m_barrierOverlay->setRenderer(lineRenderer); m_mapView->graphicsOverlays()->append(m_barrierOverlay); //create a symbol for the service areas SimpleFillSymbol* fillSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle::Solid, Qt::green, lineSymbol, this); m_areasOverlay = new GraphicsOverlay(this); SimpleRenderer* areaRenderer = new SimpleRenderer(fillSymbol, this); m_areasOverlay->setRenderer(areaRenderer); m_areasOverlay->setOpacity(0.5f); m_mapView->graphicsOverlays()->append(m_areasOverlay); } void ServiceArea::setupRouting() { connect(m_task, &ServiceAreaTask::createDefaultParametersCompleted, this, [this] (QUuid, Esri::ArcGISRuntime::ServiceAreaParameters defaultParameters) { m_parameters = defaultParameters; m_parameters.setOutputSpatialReference(SpatialReference::webMercator()); m_parameters.setReturnPolygons(true); m_parameters.setPolygonDetail(ServiceAreaPolygonDetail::High); setBusy(false); }); connect(m_task, &ServiceAreaTask::solveServiceAreaCompleted, this, [this] (QUuid, Esri::ArcGISRuntime::ServiceAreaResult serviceAreaResult) { setBusy(false); if (serviceAreaResult.isEmpty()) { m_message = "No Serice Areas calculated!"; emit messageChanged(); } int numFacilities = m_facilitiesOverlay->graphics()->size(); for (int i = 0; i < numFacilities; ++i) { QList<ServiceAreaPolygon> results = serviceAreaResult.resultPolygons(i); if (!m_graphicParent) m_graphicParent = new QObject(this); for (const ServiceAreaPolygon& poly : results) m_areasOverlay->graphics()->append(new Graphic(poly.geometry(), m_graphicParent)); } }); connect(m_mapView, &MapQuickView::mouseClicked, this, [this](QMouseEvent& mouseEvent) { if (busy()) return; switch (m_mode) { case SampleMode::Barrier: case SampleMode::Facility: break; default: return; } setBusy(true); Point mapPoint = m_mapView->screenToLocation(mouseEvent.x(), mouseEvent.y()); Point projectedPoint(mapPoint.x(), mapPoint.y(), SpatialReference::webMercator()); if (m_mode == SampleMode::Barrier) handleBarrierPoint(projectedPoint); else if(m_mode == SampleMode::Facility) handleFacilityPoint(projectedPoint); setBusy(false); }); m_task->createDefaultParameters(); } void ServiceArea::handleFacilityPoint(const Point &p) { if (!m_graphicParent) m_graphicParent = new QObject(this); m_facilitiesOverlay->graphics()->append(new Graphic(p, m_graphicParent)); } void ServiceArea::handleBarrierPoint(const Point &p) { if (!m_graphicParent) m_graphicParent = new QObject(this); m_barrierBuilder->addPoint(p); // update the geometry for the current barrier - or create 1 if it does not exist Graphic* barrier = m_barrierOverlay->graphics()->isEmpty() ? nullptr : m_barrierOverlay->graphics()->last(); if (barrier) barrier->setGeometry(m_barrierBuilder->toPolyline()); else m_barrierOverlay->graphics()->append(new Graphic(m_barrierBuilder->toPolyline(), m_graphicParent)); } <commit_msg>this still needs to get set, even if builder is not null<commit_after>// [WriteFile Name=ServiceArea, Category=Routing] // [Legal] // Copyright 2017 Esri. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [Legal] #include "ServiceArea.h" #include "Map.h" #include "MapQuickView.h" #include "PictureMarkerSymbol.h" #include "PolylineBuilder.h" #include "ServiceAreaTask.h" #include "SimpleFillSymbol.h" #include "SimpleLineSymbol.h" #include "SimpleRenderer.h" using namespace Esri::ArcGISRuntime; ServiceArea::ServiceArea(QQuickItem* parent /* = nullptr */): QQuickItem(parent), m_task(new ServiceAreaTask( QUrl("http://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/ServiceArea"), this)) { } ServiceArea::~ServiceArea() { } void ServiceArea::init() { qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView"); qmlRegisterType<ServiceArea>("Esri.Samples", 1, 0, "ServiceAreaSample"); } void ServiceArea::componentComplete() { QQuickItem::componentComplete(); // find QML MapView component m_mapView = findChild<MapQuickView*>("mapView"); m_mapView->setWrapAroundMode(WrapAroundMode::Disabled); // set view to be over San Diego m_map = new Map(Basemap::streets(this), this); m_map->setInitialViewpoint(Viewpoint(Point(-13041154, 3858170, SpatialReference(3857)), 1e5)); // Set map to map view m_mapView->setMap(m_map); connect(m_task, &ServiceAreaTask::doneLoading, this, [this](Esri::ArcGISRuntime::Error loadError) { if (!loadError.isEmpty()) return; if (m_task->loadStatus() != LoadStatus::Loaded) return; setupRouting(); }); m_task->load(); setupGraphics(); } void ServiceArea::setFacilityMode() { m_mode = SampleMode::Facility; } void ServiceArea::setBarrierMode() { m_mode = SampleMode::Barrier; if (m_barrierBuilder != nullptr) return; m_barrierBuilder = new PolylineBuilder(SpatialReference::webMercator(), this); } void ServiceArea::solveServiceArea() { setBusy(true); m_parameters.clearFacilities(); m_parameters.clearPolylineBarriers(); GraphicListModel* facilitiesGraphics = m_facilitiesOverlay->graphics(); if (facilitiesGraphics == nullptr || facilitiesGraphics->rowCount() == 0) { setBusy(false); m_message = "At least 1 Facility is required."; emit messageChanged(); return; } QList<ServiceAreaFacility> facilities; facilities.reserve(facilitiesGraphics->rowCount()); for (int f = 0; f < facilitiesGraphics->rowCount(); ++f) { Graphic* g = facilitiesGraphics->at(f); if (!g) continue; facilities.append(ServiceAreaFacility(g->geometry())); } m_parameters.setFacilities(facilities); GraphicListModel* barrierGraphics = m_barrierOverlay->graphics(); QList<PolylineBarrier> barriers; barriers.reserve(barrierGraphics->rowCount()); for (int b = 0; b < barrierGraphics->rowCount(); ++b) { Graphic* g = barrierGraphics->at(b); if (!g) continue; barriers.append(PolylineBarrier(g->geometry())); } if (!barriers.isEmpty()) m_parameters.setPolylineBarriers(barriers); m_task->solveServiceArea(m_parameters); } void ServiceArea::reset() { m_facilitiesOverlay->graphics()->clear(); m_barrierOverlay->graphics()->clear(); if (m_barrierBuilder) { delete m_barrierBuilder; m_barrierBuilder = new PolylineBuilder(SpatialReference::webMercator(), this); } m_areasOverlay->graphics()->clear(); if (m_graphicParent) { delete m_graphicParent; m_graphicParent = nullptr; } } void ServiceArea::newBarrier() { if (m_barrierBuilder) { delete m_barrierBuilder; m_barrierBuilder = nullptr; } setBarrierMode(); if (!m_graphicParent) m_graphicParent = new QObject(this); m_barrierOverlay->graphics()->append(new Graphic(m_barrierBuilder->toPolyline(), m_graphicParent)); } bool ServiceArea::busy() const { return m_busy; } QString ServiceArea::message() const { return m_message; } void ServiceArea::setBusy(bool val) { if (m_busy == val) return; m_message.clear(); m_busy = val; emit busyChanged(); emit messageChanged(); } void ServiceArea::setupGraphics() { // create a symbol for the incidents PictureMarkerSymbol* facilitySymbol = new PictureMarkerSymbol( QUrl(QStringLiteral("http://static.arcgis.com/images/Symbols/SafetyHealth/Hospital.png")), this); facilitySymbol->setHeight(30); facilitySymbol->setWidth(30); // create a graphics overlay for the facilities and add a renderer for the symbol m_facilitiesOverlay = new GraphicsOverlay(this); SimpleRenderer* renderer = new SimpleRenderer(facilitySymbol, this); m_facilitiesOverlay->setRenderer(renderer); m_mapView->graphicsOverlays()->append(m_facilitiesOverlay); // create a symbol for the barriers float lineWidth = 3.0f; SimpleLineSymbol* lineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle::Solid, Qt::black, lineWidth, this); m_barrierOverlay = new GraphicsOverlay(this); SimpleRenderer* lineRenderer = new SimpleRenderer(lineSymbol, this); m_barrierOverlay->setRenderer(lineRenderer); m_mapView->graphicsOverlays()->append(m_barrierOverlay); //create a symbol for the service areas SimpleFillSymbol* fillSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle::Solid, Qt::green, lineSymbol, this); m_areasOverlay = new GraphicsOverlay(this); SimpleRenderer* areaRenderer = new SimpleRenderer(fillSymbol, this); m_areasOverlay->setRenderer(areaRenderer); m_areasOverlay->setOpacity(0.5f); m_mapView->graphicsOverlays()->append(m_areasOverlay); } void ServiceArea::setupRouting() { connect(m_task, &ServiceAreaTask::createDefaultParametersCompleted, this, [this] (QUuid, Esri::ArcGISRuntime::ServiceAreaParameters defaultParameters) { m_parameters = defaultParameters; m_parameters.setOutputSpatialReference(SpatialReference::webMercator()); m_parameters.setReturnPolygons(true); m_parameters.setPolygonDetail(ServiceAreaPolygonDetail::High); setBusy(false); }); connect(m_task, &ServiceAreaTask::solveServiceAreaCompleted, this, [this] (QUuid, Esri::ArcGISRuntime::ServiceAreaResult serviceAreaResult) { setBusy(false); if (serviceAreaResult.isEmpty()) { m_message = "No Serice Areas calculated!"; emit messageChanged(); } int numFacilities = m_facilitiesOverlay->graphics()->size(); for (int i = 0; i < numFacilities; ++i) { QList<ServiceAreaPolygon> results = serviceAreaResult.resultPolygons(i); if (!m_graphicParent) m_graphicParent = new QObject(this); for (const ServiceAreaPolygon& poly : results) m_areasOverlay->graphics()->append(new Graphic(poly.geometry(), m_graphicParent)); } }); connect(m_mapView, &MapQuickView::mouseClicked, this, [this](QMouseEvent& mouseEvent) { if (busy()) return; switch (m_mode) { case SampleMode::Barrier: case SampleMode::Facility: break; default: return; } setBusy(true); Point mapPoint = m_mapView->screenToLocation(mouseEvent.x(), mouseEvent.y()); Point projectedPoint(mapPoint.x(), mapPoint.y(), SpatialReference::webMercator()); if (m_mode == SampleMode::Barrier) handleBarrierPoint(projectedPoint); else if(m_mode == SampleMode::Facility) handleFacilityPoint(projectedPoint); setBusy(false); }); m_task->createDefaultParameters(); } void ServiceArea::handleFacilityPoint(const Point &p) { if (!m_graphicParent) m_graphicParent = new QObject(this); m_facilitiesOverlay->graphics()->append(new Graphic(p, m_graphicParent)); } void ServiceArea::handleBarrierPoint(const Point &p) { if (!m_graphicParent) m_graphicParent = new QObject(this); m_barrierBuilder->addPoint(p); // update the geometry for the current barrier - or create 1 if it does not exist Graphic* barrier = m_barrierOverlay->graphics()->isEmpty() ? nullptr : m_barrierOverlay->graphics()->last(); if (barrier) barrier->setGeometry(m_barrierBuilder->toPolyline()); else m_barrierOverlay->graphics()->append(new Graphic(m_barrierBuilder->toPolyline(), m_graphicParent)); } <|endoftext|>
<commit_before>/* Copyright (C) 2014 P.L. Lucas <selairi@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "main.h" #include <LXQt/SingleApplication> #include <LXQt/ConfigDialog> #include <LXQt/Settings> #include "monitorsettingsdialog.h" #include "quickoptions.h" #include "xrandr.h" #include "applydialog.h" int main(int argc, char** argv) { LxQt::SingleApplication app(argc, argv); QByteArray configName = qgetenv("LXQT_SESSION_CONFIG"); if(configName.isEmpty()) configName = "session"; LxQt::Settings settings(configName); LxQt::ConfigDialog dlg(QObject::tr("Monitor Settings"), &settings); app.setActivationWindow(&dlg); dlg.setWindowIcon(QIcon::fromTheme("preferences-desktop-display")); XRandRBackend *xrandr = new XRandRBackend(); MonitorSettingsDialog *monitorSettingsDialog = new MonitorSettingsDialog(xrandr); { QList<MonitorInfo*> monitorsInfo = xrandr->getMonitorsInfo(); // If this is a laptop and there is an external monitor, offer quick options if(monitorsInfo.length() == 2) { QuickOptions *quickOptions = new QuickOptions(); monitorSettingsDialog->connect(quickOptions->ui.useBoth, SIGNAL(clicked(bool)), SLOT(onUseBoth())); monitorSettingsDialog->connect(quickOptions->ui.externalOnly, SIGNAL(clicked(bool)), SLOT(onExternalOnly())); monitorSettingsDialog->connect(quickOptions->ui.laptopOnly, SIGNAL(clicked(bool)), SLOT(onLaptopOnly())); monitorSettingsDialog->connect(quickOptions->ui.extended, SIGNAL(clicked(bool)), SLOT(onExtended())); dlg.addPage(quickOptions, QObject::tr("Quick Options"), "format-justify-left"); } } dlg.addPage(monitorSettingsDialog, QObject::tr("Settings"), "preferences-desktop-display"); ApplyDialog *apply = new ApplyDialog(); monitorSettingsDialog->connect(apply->ui.apply, SIGNAL(clicked(bool)), SLOT(applySettings())); monitorSettingsDialog->connect(apply->ui.save, SIGNAL(clicked(bool)), SLOT(saveSettings())); dlg.addPage(apply, QObject::tr("Apply"), "system-run"); dlg.exec(); return 0; } <commit_msg>Added reset values.<commit_after>/* Copyright (C) 2014 P.L. Lucas <selairi@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "main.h" #include <LXQt/SingleApplication> #include <LXQt/ConfigDialog> #include <LXQt/Settings> #include <QDebug> #include "monitorsettingsdialog.h" #include "quickoptions.h" #include "xrandr.h" #include "applydialog.h" int main(int argc, char** argv) { LxQt::SingleApplication app(argc, argv); QByteArray configName = qgetenv("LXQT_SESSION_CONFIG"); if(configName.isEmpty()) configName = "session"; LxQt::Settings settings(configName); LxQt::ConfigDialog dlg(QObject::tr("Monitor Settings"), &settings); app.setActivationWindow(&dlg); dlg.setWindowIcon(QIcon::fromTheme("preferences-desktop-display")); XRandRBackend *xrandr = new XRandRBackend(); MonitorSettingsDialog *monitorSettingsDialog = new MonitorSettingsDialog(xrandr); { QList<MonitorInfo*> monitorsInfo = xrandr->getMonitorsInfo(); // If this is a laptop and there is an external monitor, offer quick options if(monitorsInfo.length() == 2) { QuickOptions *quickOptions = new QuickOptions(); monitorSettingsDialog->connect(quickOptions->ui.useBoth, SIGNAL(clicked(bool)), SLOT(onUseBoth())); monitorSettingsDialog->connect(quickOptions->ui.externalOnly, SIGNAL(clicked(bool)), SLOT(onExternalOnly())); monitorSettingsDialog->connect(quickOptions->ui.laptopOnly, SIGNAL(clicked(bool)), SLOT(onLaptopOnly())); monitorSettingsDialog->connect(quickOptions->ui.extended, SIGNAL(clicked(bool)), SLOT(onExtended())); dlg.addPage(quickOptions, QObject::tr("Quick Options"), "format-justify-left"); } } dlg.addPage(monitorSettingsDialog, QObject::tr("Settings"), "preferences-desktop-display"); ApplyDialog *apply = new ApplyDialog(); monitorSettingsDialog->connect(apply->ui.apply, SIGNAL(clicked(bool)), SLOT(applySettings())); monitorSettingsDialog->connect(apply->ui.save, SIGNAL(clicked(bool)), SLOT(saveSettings())); dlg.addPage(apply, QObject::tr("Apply"), "system-run"); QObject::connect(&dlg, SIGNAL(reset()), &dlg, SLOT(accept())); if(QDialog::Accepted == dlg.exec() ) { main(argc, argv); } return 0; } <|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 "mitkBaseData.h" #include <itkObjectFactoryBase.h> #include <mitkException.h> #include <mitkGeometry3D.h> #include <mitkProportionalTimeGeometry.h> #include <mitkStringProperty.h> mitk::BaseData::BaseData() : m_SourceOutputIndexDuplicate(0), m_Initialized(true) { m_TimeGeometry = mitk::ProportionalTimeGeometry::New(); m_PropertyList = PropertyList::New(); } mitk::BaseData::BaseData(const BaseData &other) : itk::DataObject(), mitk::OperationActor(), m_SourceOutputIndexDuplicate(other.m_SourceOutputIndexDuplicate), m_Initialized(other.m_Initialized) { m_TimeGeometry = dynamic_cast<TimeGeometry *>(other.m_TimeGeometry->Clone().GetPointer()); m_PropertyList = other.m_PropertyList->Clone(); } mitk::BaseData::~BaseData() { } void mitk::BaseData::InitializeTimeGeometry(unsigned int timeSteps) { mitk::Geometry3D::Pointer geo3D = mitk::Geometry3D::New(); mitk::BaseGeometry::Pointer baseGeo = dynamic_cast<BaseGeometry *>(geo3D.GetPointer()); baseGeo->Initialize(); // The geometry is propagated automatically to the other items, // if EvenlyTimed is true... // Old timeGeometry->InitializeEvenlyTimed( g3d.GetPointer(), timeSteps ); TimeGeometry::Pointer timeGeometry = this->GetTimeGeometry(); timeGeometry->Initialize(); timeGeometry->Expand(timeSteps); for (TimeStepType step = 0; step < timeSteps; ++step) { timeGeometry->SetTimeStepGeometry(baseGeo.GetPointer(), step); } } void mitk::BaseData::UpdateOutputInformation() { if (this->GetSource()) { this->GetSource()->UpdateOutputInformation(); } if (m_TimeGeometry.IsNotNull()) { m_TimeGeometry->UpdateBoundingBox(); } } const mitk::TimeGeometry *mitk::BaseData::GetUpdatedTimeGeometry() { SetRequestedRegionToLargestPossibleRegion(); UpdateOutputInformation(); return GetTimeGeometry(); } void mitk::BaseData::Expand(unsigned int timeSteps) { if (m_TimeGeometry.IsNotNull()) { m_TimeGeometry->Expand(timeSteps); } else { this->InitializeTimeGeometry(timeSteps); } } const mitk::BaseGeometry *mitk::BaseData::GetUpdatedGeometry(int t) { SetRequestedRegionToLargestPossibleRegion(); UpdateOutputInformation(); return GetGeometry(t); } void mitk::BaseData::SetGeometry(BaseGeometry *geometry) { ProportionalTimeGeometry::Pointer timeGeometry = ProportionalTimeGeometry::New(); if (geometry != nullptr) { timeGeometry->Initialize(geometry, 1); } SetTimeGeometry(timeGeometry); return; } void mitk::BaseData::SetTimeGeometry(TimeGeometry *geometry) { m_TimeGeometry = geometry; this->Modified(); } void mitk::BaseData::SetClonedGeometry(const BaseGeometry *aGeometry3D) { SetGeometry(static_cast<mitk::BaseGeometry *>(aGeometry3D->Clone().GetPointer())); } void mitk::BaseData::SetClonedTimeGeometry(const TimeGeometry *geometry) { TimeGeometry::Pointer clonedGeometry = geometry->Clone(); SetTimeGeometry(clonedGeometry.GetPointer()); } void mitk::BaseData::SetClonedGeometry(const BaseGeometry *aGeometry3D, unsigned int time) { if (m_TimeGeometry) { m_TimeGeometry->SetTimeStepGeometry(static_cast<mitk::BaseGeometry *>(aGeometry3D->Clone().GetPointer()), time); } } bool mitk::BaseData::IsEmptyTimeStep(unsigned int) const { return IsInitialized() == false; } bool mitk::BaseData::IsEmpty() const { if (IsInitialized() == false) return true; const TimeGeometry *timeGeometry = const_cast<BaseData *>(this)->GetUpdatedTimeGeometry(); if (timeGeometry == nullptr) return true; unsigned int timeSteps = timeGeometry->CountTimeSteps(); for (unsigned int t = 0; t < timeSteps; ++t) { if (IsEmptyTimeStep(t) == false) return false; } return true; } itk::SmartPointer<mitk::BaseDataSource> mitk::BaseData::GetSource() const { return static_cast<mitk::BaseDataSource *>(Superclass::GetSource().GetPointer()); } mitk::PropertyList::Pointer mitk::BaseData::GetPropertyList() const { return m_PropertyList; } mitk::BaseProperty::Pointer mitk::BaseData::GetProperty(const char *propertyKey) const { return m_PropertyList->GetProperty(propertyKey); } void mitk::BaseData::SetProperty(const char *propertyKey, BaseProperty *propertyValue) { m_PropertyList->SetProperty(propertyKey, propertyValue); } void mitk::BaseData::SetPropertyList(PropertyList *pList) { m_PropertyList = pList; } void mitk::BaseData::SetOrigin(const mitk::Point3D &origin) { TimeGeometry *timeGeom = GetTimeGeometry(); assert(timeGeom != nullptr); TimeStepType steps = timeGeom->CountTimeSteps(); for (TimeStepType timestep = 0; timestep < steps; ++timestep) { auto geometry = GetGeometry(timestep); if (geometry != nullptr) { geometry->SetOrigin(origin); } } } unsigned long mitk::BaseData::GetMTime() const { unsigned long time = Superclass::GetMTime(); if (m_TimeGeometry.IsNotNull()) { if ((time < m_TimeGeometry->GetMTime())) { Modified(); return Superclass::GetMTime(); } } return time; } void mitk::BaseData::Graft(const itk::DataObject *) { itkExceptionMacro(<< "Graft not implemented for mitk::BaseData subclass " << this->GetNameOfClass()) } void mitk::BaseData::CopyInformation(const itk::DataObject *data) { const auto *bd = dynamic_cast<const Self *>(data); if (bd != nullptr) { m_PropertyList = bd->GetPropertyList()->Clone(); if (bd->GetTimeGeometry() != nullptr) { m_TimeGeometry = bd->GetTimeGeometry()->Clone(); } } else { // pointer could not be cast back down; this can be the case if your filters input // and output objects differ in type; then you have to write your own GenerateOutputInformation method itkExceptionMacro(<< "mitk::BaseData::CopyInformation() cannot cast " << typeid(data).name() << " to " << typeid(Self *).name()); } } bool mitk::BaseData::IsInitialized() const { return m_Initialized; } void mitk::BaseData::Clear() { this->ClearData(); this->InitializeEmpty(); } void mitk::BaseData::ClearData() { if (m_Initialized) { ReleaseData(); m_Initialized = false; } } void mitk::BaseData::ExecuteOperation(mitk::Operation * /*operation*/) { // empty by default. override if needed! } void mitk::BaseData::PrintSelf(std::ostream &os, itk::Indent indent) const { os << std::endl; os << indent << " TimeGeometry: "; if (GetTimeGeometry() == nullptr) os << "nullptr" << std::endl; else GetTimeGeometry()->Print(os, indent); // print out all properties PropertyList::Pointer propertyList = this->GetPropertyList(); if (propertyList.IsNotNull() && !propertyList->IsEmpty()) { // general headline os << "Properties of BaseData:" << std::endl; const PropertyList::PropertyMap *map = propertyList->GetMap(); for (auto iter = map->begin(); iter != map->end(); ++iter) { os << " " << (*iter).first << " " << (*iter).second->GetValueAsString() << std::endl; } } } mitk::IIdentifiable::UIDType mitk::BaseData::GetUID() const { auto uidProperty = dynamic_cast<StringProperty *>(this->GetProperty("uid").GetPointer()); return nullptr != uidProperty ? uidProperty->GetValue() : ""; } <commit_msg>Generate UID on creation<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 "mitkBaseData.h" #include <itkObjectFactoryBase.h> #include <mitkException.h> #include <mitkGeometry3D.h> #include <mitkProportionalTimeGeometry.h> #include <mitkStringProperty.h> #include <mitkUIDGenerator.h> mitk::BaseData::BaseData() : m_SourceOutputIndexDuplicate(0), m_Initialized(true), m_PropertyList(PropertyList::New()), m_TimeGeometry(ProportionalTimeGeometry::New()) { UIDGenerator generator; this->SetProperty("uid", StringProperty::New(generator.GetUID())); } mitk::BaseData::BaseData(const BaseData &other) : itk::DataObject(), mitk::OperationActor(), m_SourceOutputIndexDuplicate(other.m_SourceOutputIndexDuplicate), m_Initialized(other.m_Initialized), m_PropertyList(other.m_PropertyList->Clone()), m_TimeGeometry(other.m_TimeGeometry->Clone()) { } mitk::BaseData::~BaseData() { } void mitk::BaseData::InitializeTimeGeometry(unsigned int timeSteps) { mitk::Geometry3D::Pointer geo3D = mitk::Geometry3D::New(); mitk::BaseGeometry::Pointer baseGeo = dynamic_cast<BaseGeometry *>(geo3D.GetPointer()); baseGeo->Initialize(); // The geometry is propagated automatically to the other items, // if EvenlyTimed is true... // Old timeGeometry->InitializeEvenlyTimed( g3d.GetPointer(), timeSteps ); TimeGeometry::Pointer timeGeometry = this->GetTimeGeometry(); timeGeometry->Initialize(); timeGeometry->Expand(timeSteps); for (TimeStepType step = 0; step < timeSteps; ++step) { timeGeometry->SetTimeStepGeometry(baseGeo.GetPointer(), step); } } void mitk::BaseData::UpdateOutputInformation() { if (this->GetSource()) { this->GetSource()->UpdateOutputInformation(); } if (m_TimeGeometry.IsNotNull()) { m_TimeGeometry->UpdateBoundingBox(); } } const mitk::TimeGeometry *mitk::BaseData::GetUpdatedTimeGeometry() { SetRequestedRegionToLargestPossibleRegion(); UpdateOutputInformation(); return GetTimeGeometry(); } void mitk::BaseData::Expand(unsigned int timeSteps) { if (m_TimeGeometry.IsNotNull()) { m_TimeGeometry->Expand(timeSteps); } else { this->InitializeTimeGeometry(timeSteps); } } const mitk::BaseGeometry *mitk::BaseData::GetUpdatedGeometry(int t) { SetRequestedRegionToLargestPossibleRegion(); UpdateOutputInformation(); return GetGeometry(t); } void mitk::BaseData::SetGeometry(BaseGeometry *geometry) { ProportionalTimeGeometry::Pointer timeGeometry = ProportionalTimeGeometry::New(); if (geometry != nullptr) { timeGeometry->Initialize(geometry, 1); } SetTimeGeometry(timeGeometry); return; } void mitk::BaseData::SetTimeGeometry(TimeGeometry *geometry) { m_TimeGeometry = geometry; this->Modified(); } void mitk::BaseData::SetClonedGeometry(const BaseGeometry *aGeometry3D) { SetGeometry(static_cast<mitk::BaseGeometry *>(aGeometry3D->Clone().GetPointer())); } void mitk::BaseData::SetClonedTimeGeometry(const TimeGeometry *geometry) { TimeGeometry::Pointer clonedGeometry = geometry->Clone(); SetTimeGeometry(clonedGeometry.GetPointer()); } void mitk::BaseData::SetClonedGeometry(const BaseGeometry *aGeometry3D, unsigned int time) { if (m_TimeGeometry) { m_TimeGeometry->SetTimeStepGeometry(static_cast<mitk::BaseGeometry *>(aGeometry3D->Clone().GetPointer()), time); } } bool mitk::BaseData::IsEmptyTimeStep(unsigned int) const { return IsInitialized() == false; } bool mitk::BaseData::IsEmpty() const { if (IsInitialized() == false) return true; const TimeGeometry *timeGeometry = const_cast<BaseData *>(this)->GetUpdatedTimeGeometry(); if (timeGeometry == nullptr) return true; unsigned int timeSteps = timeGeometry->CountTimeSteps(); for (unsigned int t = 0; t < timeSteps; ++t) { if (IsEmptyTimeStep(t) == false) return false; } return true; } itk::SmartPointer<mitk::BaseDataSource> mitk::BaseData::GetSource() const { return static_cast<mitk::BaseDataSource *>(Superclass::GetSource().GetPointer()); } mitk::PropertyList::Pointer mitk::BaseData::GetPropertyList() const { return m_PropertyList; } mitk::BaseProperty::Pointer mitk::BaseData::GetProperty(const char *propertyKey) const { return m_PropertyList->GetProperty(propertyKey); } void mitk::BaseData::SetProperty(const char *propertyKey, BaseProperty *propertyValue) { m_PropertyList->SetProperty(propertyKey, propertyValue); } void mitk::BaseData::SetPropertyList(PropertyList *pList) { m_PropertyList = pList; } void mitk::BaseData::SetOrigin(const mitk::Point3D &origin) { TimeGeometry *timeGeom = GetTimeGeometry(); assert(timeGeom != nullptr); TimeStepType steps = timeGeom->CountTimeSteps(); for (TimeStepType timestep = 0; timestep < steps; ++timestep) { auto geometry = GetGeometry(timestep); if (geometry != nullptr) { geometry->SetOrigin(origin); } } } unsigned long mitk::BaseData::GetMTime() const { unsigned long time = Superclass::GetMTime(); if (m_TimeGeometry.IsNotNull()) { if ((time < m_TimeGeometry->GetMTime())) { Modified(); return Superclass::GetMTime(); } } return time; } void mitk::BaseData::Graft(const itk::DataObject *) { itkExceptionMacro(<< "Graft not implemented for mitk::BaseData subclass " << this->GetNameOfClass()) } void mitk::BaseData::CopyInformation(const itk::DataObject *data) { const auto *bd = dynamic_cast<const Self *>(data); if (bd != nullptr) { m_PropertyList = bd->GetPropertyList()->Clone(); if (bd->GetTimeGeometry() != nullptr) { m_TimeGeometry = bd->GetTimeGeometry()->Clone(); } } else { // pointer could not be cast back down; this can be the case if your filters input // and output objects differ in type; then you have to write your own GenerateOutputInformation method itkExceptionMacro(<< "mitk::BaseData::CopyInformation() cannot cast " << typeid(data).name() << " to " << typeid(Self *).name()); } } bool mitk::BaseData::IsInitialized() const { return m_Initialized; } void mitk::BaseData::Clear() { this->ClearData(); this->InitializeEmpty(); } void mitk::BaseData::ClearData() { if (m_Initialized) { ReleaseData(); m_Initialized = false; } } void mitk::BaseData::ExecuteOperation(mitk::Operation * /*operation*/) { // empty by default. override if needed! } void mitk::BaseData::PrintSelf(std::ostream &os, itk::Indent indent) const { os << std::endl; os << indent << " TimeGeometry: "; if (GetTimeGeometry() == nullptr) os << "nullptr" << std::endl; else GetTimeGeometry()->Print(os, indent); // print out all properties PropertyList::Pointer propertyList = this->GetPropertyList(); if (propertyList.IsNotNull() && !propertyList->IsEmpty()) { // general headline os << "Properties of BaseData:" << std::endl; const PropertyList::PropertyMap *map = propertyList->GetMap(); for (auto iter = map->begin(); iter != map->end(); ++iter) { os << " " << (*iter).first << " " << (*iter).second->GetValueAsString() << std::endl; } } } mitk::IIdentifiable::UIDType mitk::BaseData::GetUID() const { auto uidProperty = dynamic_cast<StringProperty *>(this->GetProperty("uid").GetPointer()); return nullptr != uidProperty ? uidProperty->GetValue() : ""; } <|endoftext|>
<commit_before>#ifndef ALEPH_TOPOLOGY_IO_VTK_HH__ #define ALEPH_TOPOLOGY_IO_VTK_HH__ #include <cstddef> #include <algorithm> #include <fstream> #include <regex> #include <stdexcept> #include <sstream> #include <string> #include <vector> #include "utilities/String.hh" namespace aleph { namespace topology { namespace io { /** @class VTKStructuredGridReader @brief Simple reader class for VTK structured grids This class is a simple parser for VTK files in 'legacy format'. It is capable of parsing a structured grid and converting it to a simplicial complex. Data and weights of the simplicial complex will be taken from the VTK file. */ class VTKStructuredGridReader { public: template <class SimplicialComplex> void operator()( const std::string& filename, SimplicialComplex& K ) { using Simplex = typename SimplicialComplex::ValueType; using DataType = typename Simplex::DataType; this->operator()( filename, K, [] ( DataType a, DataType b ) { return std::max(a,b); } ); } template <class SimplicialComplex, class Functor> void operator()( const std::string& filename, SimplicialComplex& K, Functor f ) { std::ifstream in( filename ); if( !in ) throw std::runtime_error( "Unable to read input file" ); this->operator()( in, K, f ); } template <class SimplicialComplex> void operator()( std::ifstream& in, SimplicialComplex& K ) { using Simplex = typename SimplicialComplex::ValueType; using DataType = typename Simplex::DataType; this->operator()( in, K, [] ( DataType a, DataType b ) { return std::max(a,b); } ); } template <class SimplicialComplex, class Functor> void operator()( std::ifstream& in, SimplicialComplex& K, Functor f ) { using namespace aleph::utilities; using Simplex = typename SimplicialComplex::ValueType; using DataType = typename Simplex::DataType; using VertexType = typename Simplex::VertexType; std::string line; // Parse header first ---------------------------------------------- std::size_t nx, ny, nz, n, s; bool parsedHeader = this->parseHeader( in, nx, ny, nz, n, s ); if( !parsedHeader ) return; // TODO: Check data type size against 's' and report if there are // issues such as insufficient storage space // Parse body ------------------------------------------------------ // // The body contains coordinates for each of the points, which are // dutifully ignored for now, and attributes. For now, point-based // attributes are supported. std::regex rePointData( "POINT_DATA[[:space:]]+([[:digit:]]+)" ); std::regex reScalars( "SCALARS[[:space:]]+([[:alnum:]]+)[[:space:]]+([[:alnum:]]+)[[:space:]]*([[:digit:]]*)" ); std::regex reLookupTable( "LOOKUP_TABLE[[:space:]]+([[:alnum:]]+)" ); std::vector<DataType> coordinates; coordinates.reserve( n*3 ); while( std::getline( in, line ) ) { line = trim( line ); auto strings = split( line ); for( auto&& coordinate : strings ) coordinates.push_back( convert<DataType>( coordinate ) ); if( coordinates.size() == n*3 ) break; } std::vector<DataType> values; values.reserve( n ); { std::smatch matches; while( std::getline( in, line ) ) { if( std::regex_match( line, matches, rePointData ) ) { auto sn = matches[1]; if( static_cast<std::size_t>( std::stoull( sn ) ) != n ) throw std::runtime_error( "Format error: number of point data attributes does not match number of points" ); } else if( std::regex_match( line, matches, reScalars ) ) { auto name = matches[1]; auto type = matches[2]; auto components = matches[3]; // TODO: // - Use name // - Check type // - Check number of components (if present) (void) name; (void) type; (void) components; } else if( std::regex_match( line, matches, reLookupTable ) ) { auto name = matches[1]; if( name != "default" ) throw std::runtime_error( "Handling non-default lookup tables is not yet implemented" ); } else { line = trim( line ); auto strings = split( line ); for( auto&& value : strings ) values.push_back( convert<DataType>( value ) ); } } } // Create topology ------------------------------------------------- // // The first dimension (x) is increasing fastest. We first need some // mapping functions that assign indices based on x,y,z offsets. // // nx = 3 // ny = 3 // nz = 3 // // [0,0,0] [1,0,0] [2,0,0] | 0, 1, 2 // [0,1,0] [1,1,0] [2,1,0] | 3, 4, 5 // [0,2,0] [1,2,0] [2,2,0] | 6, 7, 8 // [0,0,1] [1,0,1] [2,0,1] | 9,10,11 // [0,1,1] [1,1,1] [2,1,1] | 12,13,14 // [0,2,1] [1,2,1] [2,2,1] | 15,16,17 // [0,0,2] [1,0,2] [2,0,2] | 18,19,20 // [0,1,2] [1,1,2] [2,1,2] | 21,22,23 // [0,2,2] [1,2,2] [2,2,2] | 24,25,26 // // nx = 1 // ny = 2 // nz = 3 // // [0,0,0] [0,1,0] | 0,1 // [0,0,1] [0,1,1] | 2,3 // [0,0,2] [0,1,2] | 4,5 // // [0,0,0] | 0 // [0,1,0] | 1 // [0,0,1] | 2 // [0,1,1] | 3 // [0,0,2] | 4 // [0,1,2] | 5 std::vector<Simplex> simplices; // Create 0-simplices ---------------------------------------------- { VertexType v = VertexType(); for( auto&& value : values ) simplices.push_back( Simplex(v, value) ); } // Create 1-simplices ---------------------------------------------- for( std::size_t z = 0; z < nz; z++ ) { for( std::size_t y = 0; y < ny; y++ ) { for( std::size_t x = 0; x < nx; x++ ) { auto i = coordinatesToIndex(nx,ny,x,y,z); auto N = neighbours(nx,ny,nz,x,y,z); for( auto&& j : N ) { auto wi = simplices.at(i).data(); auto wj = simplices.at(j).data(); // Use the functor specified by the client in order to // assign a weight for the new simplex. auto w = f(wi, wj); simplices.push_back( Simplex( {i,j}, w ) ); } } } } K = SimplicialComplex( simplices.begin(), simplices.end() ); #if 0 auto indexToCoordinates = [nx,ny] ( std::size_t i, std::size_t& x, std::size_t& y, std::size_t& z ) { x = i % nx; y = static_cast<std::size_t>( i / (nx) ) % ny; z = static_cast<std::size_t>( i / (nx*ny) ); }; auto coordinatesToIndex = [nx,ny] ( std::size_t x, std::size_t y, std::size_t z ) { return z * nx*ny + x % nx + y * nx; }; #endif } private: /** Converts x,y,z coordinates to the corresponding index in the array of values. */ static std::size_t coordinatesToIndex( const std::size_t nx, const std::size_t ny, const std::size_t x , const std::size_t y, const std::size_t z ) noexcept { return z * nx*ny + x % nx + y * nx; } /** Enumerates all valid neighbours of a vertex and returns their indices. A valid neighbour is a neighbour whose index doesn't exceed the bounds of the grid. At present, the diagonal isn't used. */ static std::vector<std::size_t> neighbours( const std::size_t nx, const std::size_t ny, const std::size_t nz, std::size_t x, std::size_t y, std::size_t z ) { std::vector<std::size_t> neighbours; neighbours.reserve( 6 ); // left if( x > 0 ) neighbours.push_back( coordinatesToIndex(nx, ny, x-1, y, z) ); // right else if( x+1 < nx ) neighbours.push_back( coordinatesToIndex(nx, ny, x+1, y, z) ); // bottom if( y > 0 ) neighbours.push_back( coordinatesToIndex(nx, ny, x, y-1, z) ); // top else if( y+1 < ny ) neighbours.push_back( coordinatesToIndex(nx, ny, x, y+1, z) ); // back if( z > 0 ) neighbours.push_back( coordinatesToIndex(nx, ny, x, y, z-1) ); // front else if( z+1 < nz ) neighbours.push_back( coordinatesToIndex(nx, ny, x, y, z+1) ); return neighbours; } /** Attempts parsing the header of a structured VTK file. If successful, returns true and sets all output variables: - x: x dimension - y: y dimension - z: z dimension - n: number of data points This function expects the header to conform to the VTK legacy file format. */ bool parseHeader( std::ifstream& in, std::size_t& x, std::size_t& y, std::size_t& z, std::size_t& n, std::size_t& s ) { using namespace aleph::utilities; std::string identifier; // e.g. '# vtk DataFile Version 3.0' std::string header; // e.g. 'VTK Output' std::string format; // e.g. 'ASCII' std::string structure; // e.g. 'DATASET STRUCTURED_GRID' std::string dimensions; // e.g. 'DIMENSIONS 100 10 1' std::string points; // e.g. 'POINTS 1000 float' std::getline( in, identifier ); std::getline( in, header ); std::getline( in, format ); if( !in ) return false; identifier = trim( identifier ); format = trim( format ); // This identifier is a little bit more lenient than the original // documentation requires: it will also accept if some fields are // joined by multiple spaces. std::regex reIdentifier( "#[[:space:]]+vtk[[:space:]]+DataFile[[:space:]]+Version[[:space:]]+([[:digit:]]+)\\.([[:digit:]]+)" ); if( !std::regex_match( identifier, reIdentifier ) ) return false; if( format != "ASCII" ) throw std::runtime_error( "Binary file parsing is not yet supported" ); std::getline( in, structure ); std::getline( in, dimensions ); std::getline( in, points ); if( !in ) return false; structure = trim( structure ); dimensions = trim( dimensions ); points = trim( points ); std::regex reStructure( "DATASET[[:space:]]+STRUCTURED_GRID" ); if( !std::regex_match( structure, reStructure ) ) return false; std::regex reDimensions( "DIMENSIONS[[:space:]]+([[:digit:]]+)[[:space:]]+([[:digit:]]+)[[:space:]]+([[:digit:]]+)" ); std::smatch matches; if( !std::regex_match( dimensions, matches, reDimensions ) ) return false; auto sx = matches[1]; auto sy = matches[2]; auto sz = matches[3]; x = std::size_t( std::stoull( sx ) ); y = std::size_t( std::stoull( sy ) ); z = std::size_t( std::stoull( sz ) ); std::regex rePoints( "POINTS[[:space:]]+([[:digit:]]+)[[:space:]]+([[:alpha:]]+)" ); if( !std::regex_match( points, matches, rePoints ) ) return false; auto sn = matches[1]; auto st = matches[2]; n = std::size_t( std::stoull( sn ) ); if( st == "double" ) s = sizeof(double); else if( st == "float" ) s = sizeof(float); else if( st == "long" ) s = sizeof(long); else if( st == "unsigned_long" ) s = sizeof(unsigned long); else if( st == "int" ) s = sizeof(int); else if( st == "unsigned_int" ) s = sizeof(unsigned int); else if( st == "short" ) s = sizeof(short); else if( st == "unsigned_short" ) s = sizeof(unsigned short); else if( st == "char" ) s = sizeof(char); else if( st == "unsigned char" ) s = sizeof(unsigned char); else if( st == "bit" ) s = sizeof(bool); return true; } }; } // namespace io } // namespace topology } // namespace aleph #endif <commit_msg>Added some comments & removed obsolete code<commit_after>#ifndef ALEPH_TOPOLOGY_IO_VTK_HH__ #define ALEPH_TOPOLOGY_IO_VTK_HH__ #include <cstddef> #include <algorithm> #include <fstream> #include <regex> #include <stdexcept> #include <sstream> #include <string> #include <vector> #include "utilities/String.hh" namespace aleph { namespace topology { namespace io { /** @class VTKStructuredGridReader @brief Simple reader class for VTK structured grids This class is a simple parser for VTK files in 'legacy format'. It is capable of parsing a structured grid and converting it to a simplicial complex. Data and weights of the simplicial complex will be taken from the VTK file. */ class VTKStructuredGridReader { public: template <class SimplicialComplex> void operator()( const std::string& filename, SimplicialComplex& K ) { using Simplex = typename SimplicialComplex::ValueType; using DataType = typename Simplex::DataType; this->operator()( filename, K, [] ( DataType a, DataType b ) { return std::max(a,b); } ); } template <class SimplicialComplex, class Functor> void operator()( const std::string& filename, SimplicialComplex& K, Functor f ) { std::ifstream in( filename ); if( !in ) throw std::runtime_error( "Unable to read input file" ); this->operator()( in, K, f ); } template <class SimplicialComplex> void operator()( std::ifstream& in, SimplicialComplex& K ) { using Simplex = typename SimplicialComplex::ValueType; using DataType = typename Simplex::DataType; this->operator()( in, K, [] ( DataType a, DataType b ) { return std::max(a,b); } ); } template <class SimplicialComplex, class Functor> void operator()( std::ifstream& in, SimplicialComplex& K, Functor f ) { using namespace aleph::utilities; using Simplex = typename SimplicialComplex::ValueType; using DataType = typename Simplex::DataType; using VertexType = typename Simplex::VertexType; std::string line; // Parse header first ---------------------------------------------- std::size_t nx, ny, nz, n, s; bool parsedHeader = this->parseHeader( in, nx, ny, nz, n, s ); if( !parsedHeader ) return; // TODO: Check data type size against 's' and report if there are // issues such as insufficient storage space // Parse body ------------------------------------------------------ // // The body contains coordinates for each of the points, which are // dutifully ignored for now, and attributes. For now, point-based // attributes are supported. std::regex rePointData( "POINT_DATA[[:space:]]+([[:digit:]]+)" ); std::regex reScalars( "SCALARS[[:space:]]+([[:alnum:]]+)[[:space:]]+([[:alnum:]]+)[[:space:]]*([[:digit:]]*)" ); std::regex reLookupTable( "LOOKUP_TABLE[[:space:]]+([[:alnum:]]+)" ); std::vector<DataType> coordinates; coordinates.reserve( n*3 ); while( std::getline( in, line ) ) { line = trim( line ); auto strings = split( line ); for( auto&& coordinate : strings ) coordinates.push_back( convert<DataType>( coordinate ) ); if( coordinates.size() == n*3 ) break; } std::vector<DataType> values; values.reserve( n ); { std::smatch matches; while( std::getline( in, line ) ) { if( std::regex_match( line, matches, rePointData ) ) { auto sn = matches[1]; if( static_cast<std::size_t>( std::stoull( sn ) ) != n ) throw std::runtime_error( "Format error: number of point data attributes does not match number of points" ); } else if( std::regex_match( line, matches, reScalars ) ) { auto name = matches[1]; auto type = matches[2]; auto components = matches[3]; // TODO: // - Use name // - Check type // - Check number of components (if present) (void) name; (void) type; (void) components; } else if( std::regex_match( line, matches, reLookupTable ) ) { auto name = matches[1]; if( name != "default" ) throw std::runtime_error( "Handling non-default lookup tables is not yet implemented" ); } else { line = trim( line ); auto strings = split( line ); for( auto&& value : strings ) values.push_back( convert<DataType>( value ) ); } } } // Create topology ------------------------------------------------- // // Notice that this class only adds 0-simplices and 1-simplices to // the simplicial complex for now. While it is possible to include // triangles (i.e. 2-simplices), their creation order is not clear // and may subtly influence calculations. std::vector<Simplex> simplices; // Create 0-simplices ---------------------------------------------- { VertexType v = VertexType(); for( auto&& value : values ) simplices.push_back( Simplex(v, value) ); } // Create 1-simplices ---------------------------------------------- for( std::size_t z = 0; z < nz; z++ ) { for( std::size_t y = 0; y < ny; y++ ) { for( std::size_t x = 0; x < nx; x++ ) { auto i = coordinatesToIndex(nx,ny,x,y,z); auto N = neighbours(nx,ny,nz,x,y,z); for( auto&& j : N ) { auto wi = simplices.at(i).data(); auto wj = simplices.at(j).data(); // Use the functor specified by the client in order to // assign a weight for the new simplex. auto w = f(wi, wj); simplices.push_back( Simplex( {i,j}, w ) ); } } } } K = SimplicialComplex( simplices.begin(), simplices.end() ); } private: /** Converts an index in the array of values to the corresponding set of coordinates. */ static void indexToCoordinates ( const std::size_t nx, const std::size_t ny, const std::size_t i, std::size_t& x, // out: x std::size_t& y, // out: y std::size_t& z ) // out: z { x = i % nx; y = static_cast<std::size_t>( i / (nx) ) % ny; z = static_cast<std::size_t>( i / (nx*ny) ); }; /** Converts x,y,z coordinates to the corresponding index in the array of values. */ static std::size_t coordinatesToIndex( const std::size_t nx, const std::size_t ny, const std::size_t x , const std::size_t y, const std::size_t z ) noexcept { return z * nx*ny + x % nx + y * nx; } /** Enumerates all valid neighbours of a vertex and returns their indices. A valid neighbour is a neighbour whose index doesn't exceed the bounds of the grid. At present, the diagonal isn't used. */ static std::vector<std::size_t> neighbours( const std::size_t nx, const std::size_t ny, const std::size_t nz, std::size_t x, std::size_t y, std::size_t z ) { std::vector<std::size_t> neighbours; neighbours.reserve( 6 ); // left if( x > 0 ) neighbours.push_back( coordinatesToIndex(nx, ny, x-1, y, z) ); // right else if( x+1 < nx ) neighbours.push_back( coordinatesToIndex(nx, ny, x+1, y, z) ); // bottom if( y > 0 ) neighbours.push_back( coordinatesToIndex(nx, ny, x, y-1, z) ); // top else if( y+1 < ny ) neighbours.push_back( coordinatesToIndex(nx, ny, x, y+1, z) ); // back if( z > 0 ) neighbours.push_back( coordinatesToIndex(nx, ny, x, y, z-1) ); // front else if( z+1 < nz ) neighbours.push_back( coordinatesToIndex(nx, ny, x, y, z+1) ); return neighbours; } /** Attempts parsing the header of a structured VTK file. If successful, returns true and sets all output variables: - x: x dimension - y: y dimension - z: z dimension - n: number of data points This function expects the header to conform to the VTK legacy file format. */ bool parseHeader( std::ifstream& in, std::size_t& x, std::size_t& y, std::size_t& z, std::size_t& n, std::size_t& s ) { using namespace aleph::utilities; std::string identifier; // e.g. '# vtk DataFile Version 3.0' std::string header; // e.g. 'VTK Output' std::string format; // e.g. 'ASCII' std::string structure; // e.g. 'DATASET STRUCTURED_GRID' std::string dimensions; // e.g. 'DIMENSIONS 100 10 1' std::string points; // e.g. 'POINTS 1000 float' std::getline( in, identifier ); std::getline( in, header ); std::getline( in, format ); if( !in ) return false; identifier = trim( identifier ); format = trim( format ); // This identifier is a little bit more lenient than the original // documentation requires: it will also accept if some fields are // joined by multiple spaces. std::regex reIdentifier( "#[[:space:]]+vtk[[:space:]]+DataFile[[:space:]]+Version[[:space:]]+([[:digit:]]+)\\.([[:digit:]]+)" ); if( !std::regex_match( identifier, reIdentifier ) ) return false; if( format != "ASCII" ) throw std::runtime_error( "Binary file parsing is not yet supported" ); std::getline( in, structure ); std::getline( in, dimensions ); std::getline( in, points ); if( !in ) return false; structure = trim( structure ); dimensions = trim( dimensions ); points = trim( points ); std::regex reStructure( "DATASET[[:space:]]+STRUCTURED_GRID" ); if( !std::regex_match( structure, reStructure ) ) return false; std::regex reDimensions( "DIMENSIONS[[:space:]]+([[:digit:]]+)[[:space:]]+([[:digit:]]+)[[:space:]]+([[:digit:]]+)" ); std::smatch matches; if( !std::regex_match( dimensions, matches, reDimensions ) ) return false; auto sx = matches[1]; auto sy = matches[2]; auto sz = matches[3]; x = std::size_t( std::stoull( sx ) ); y = std::size_t( std::stoull( sy ) ); z = std::size_t( std::stoull( sz ) ); std::regex rePoints( "POINTS[[:space:]]+([[:digit:]]+)[[:space:]]+([[:alpha:]]+)" ); if( !std::regex_match( points, matches, rePoints ) ) return false; auto sn = matches[1]; auto st = matches[2]; n = std::size_t( std::stoull( sn ) ); if( st == "double" ) s = sizeof(double); else if( st == "float" ) s = sizeof(float); else if( st == "long" ) s = sizeof(long); else if( st == "unsigned_long" ) s = sizeof(unsigned long); else if( st == "int" ) s = sizeof(int); else if( st == "unsigned_int" ) s = sizeof(unsigned int); else if( st == "short" ) s = sizeof(short); else if( st == "unsigned_short" ) s = sizeof(unsigned short); else if( st == "char" ) s = sizeof(char); else if( st == "unsigned char" ) s = sizeof(unsigned char); else if( st == "bit" ) s = sizeof(bool); return true; } }; } // namespace io } // namespace topology } // namespace aleph #endif <|endoftext|>
<commit_before>#include "atom-map.h" #include "details/reporting/report.h" #include "details/errors/errors.h" using namespace Yuni; namespace ny { namespace { auto createDummyAtom() { auto atom = yuni::make_ref<Atom>("", Atom::Type::classdef); atom->builtinMapping = nyt_void; return atom; } auto findCoreObject(nytype_t kind, const AnyString& name, Atom& root) { Atom* atom = nullptr; switch (root.findClassAtom(atom, name)) { case 1: { assert(atom != nullptr); atom->builtinMapping = kind; return Ref<Atom>{atom}; } case 0: { error() << "failed to find builtin 'class " << name << "' from nsl"; break; } default: error() << "multiple definition for 'class" << name << "'"; } throw std::runtime_error("not found"); } } // anonymous namespace AtomMap::AtomMap(StringRefs& stringrefs) : root(AnyString(), Atom::Type::namespacedef) // global namespace , stringrefs(stringrefs) { // since `m_atomGrpID` will start from 1 m_byIndex.emplace_back(nullptr); } Atom& AtomMap::createNewAtom(Atom::Type type, Atom& parent, const AnyString& name) { auto newnode = yuni::make_ref<Atom>(parent, stringrefs.refstr(name), type); newnode->atomid = ++m_atomGrpID; m_byIndex.emplace_back(newnode); return *newnode; } Atom& AtomMap::createVardef(Atom& parent, const AnyString& name) { assert(not name.empty()); auto& atom = createNewAtom(Atom::Type::vardef, parent, name); auto fieldindex = parent.classinfo.nextFieldIndex++; atom.varinfo.fieldindex = fieldindex; atom.varinfo.effectiveFieldIndex = fieldindex; return atom; } AnyString AtomMap::symbolname(uint32_t atomid, uint32_t index) const { if (atomid < m_byIndex.size()) return m_byIndex[atomid]->instances[index].symbolname(); return AnyString{}; } bool AtomMap::fetchAndIndexCoreObjects() { if (unlikely(!!core.object[nyt_bool])) return true; if (not config::importNSL) { for (auto& object: core.object) object = createDummyAtom(); return true; } try { core.object[nyt_bool] = findCoreObject(nyt_bool, "bool", root); core.object[nyt_i8] = findCoreObject(nyt_i8, "i8", root); core.object[nyt_i16] = findCoreObject(nyt_i16, "i16", root); core.object[nyt_i32] = findCoreObject(nyt_i32, "i32", root); core.object[nyt_i64] = findCoreObject(nyt_i64, "i64", root); core.object[nyt_u8] = findCoreObject(nyt_u8, "u8", root); core.object[nyt_u16] = findCoreObject(nyt_u16, "u16", root); core.object[nyt_u32] = findCoreObject(nyt_u32, "u32", root); core.object[nyt_u64] = findCoreObject(nyt_u64, "u64", root); core.object[nyt_f32] = findCoreObject(nyt_f32, "f32", root); core.object[nyt_f64] = findCoreObject(nyt_f64, "f64", root); core.object[nyt_ptr] = findCoreObject(nyt_ptr, "pointer", root); return true; } catch (const std::exception&) { // invalidate core.object[nyt_bool] = nullptr; } return false; } } // namespace ny <commit_msg>atom-map: builtin atoms: rename func, reorder parameters<commit_after>#include "atom-map.h" #include "details/reporting/report.h" #include "details/errors/errors.h" using namespace Yuni; namespace ny { namespace { auto createDummyAtom() { auto atom = yuni::make_ref<Atom>("", Atom::Type::classdef); atom->builtinMapping = nyt_void; return atom; } auto findBuiltinAtom(Atom& root, nytype_t kind, const AnyString& name) { Atom* atom = nullptr; switch (root.findClassAtom(atom, name)) { case 1: { assert(atom != nullptr); atom->builtinMapping = kind; return Ref<Atom>{atom}; } case 0: { error() << "failed to find builtin 'class " << name << "' from nsl"; break; } default: error() << "multiple definition for 'class" << name << "'"; } throw std::runtime_error("not found"); } } // anonymous namespace AtomMap::AtomMap(StringRefs& stringrefs) : root(AnyString(), Atom::Type::namespacedef) // global namespace , stringrefs(stringrefs) { // since `m_atomGrpID` will start from 1 m_byIndex.emplace_back(nullptr); } Atom& AtomMap::createNewAtom(Atom::Type type, Atom& parent, const AnyString& name) { auto newnode = yuni::make_ref<Atom>(parent, stringrefs.refstr(name), type); newnode->atomid = ++m_atomGrpID; m_byIndex.emplace_back(newnode); return *newnode; } Atom& AtomMap::createVardef(Atom& parent, const AnyString& name) { assert(not name.empty()); auto& atom = createNewAtom(Atom::Type::vardef, parent, name); auto fieldindex = parent.classinfo.nextFieldIndex++; atom.varinfo.fieldindex = fieldindex; atom.varinfo.effectiveFieldIndex = fieldindex; return atom; } AnyString AtomMap::symbolname(uint32_t atomid, uint32_t index) const { if (atomid < m_byIndex.size()) return m_byIndex[atomid]->instances[index].symbolname(); return AnyString{}; } bool AtomMap::fetchAndIndexCoreObjects() { if (unlikely(!!core.object[nyt_bool])) return true; if (not config::importNSL) { for (auto& object: core.object) object = createDummyAtom(); return true; } try { core.object[nyt_bool] = findBuiltinAtom(root, nyt_bool, "bool"); core.object[nyt_i8] = findBuiltinAtom(root, nyt_i8, "i8"); core.object[nyt_i16] = findBuiltinAtom(root, nyt_i16, "i16"); core.object[nyt_i32] = findBuiltinAtom(root, nyt_i32, "i32"); core.object[nyt_i64] = findBuiltinAtom(root, nyt_i64, "i64"); core.object[nyt_u8] = findBuiltinAtom(root, nyt_u8, "u8"); core.object[nyt_u16] = findBuiltinAtom(root, nyt_u16, "u16"); core.object[nyt_u32] = findBuiltinAtom(root, nyt_u32, "u32"); core.object[nyt_u64] = findBuiltinAtom(root, nyt_u64, "u64"); core.object[nyt_f32] = findBuiltinAtom(root, nyt_f32, "f32"); core.object[nyt_f64] = findBuiltinAtom(root, nyt_f64, "f64"); core.object[nyt_ptr] = findBuiltinAtom(root, nyt_ptr, "pointer"); return true; } catch (const std::exception&) { // invalidate core.object[nyt_bool] = nullptr; } return false; } } // namespace ny <|endoftext|>
<commit_before>#include "vector.h" #include "MinIMU9.h" #include <iostream> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <sys/time.h> #include <system_error> #include <boost/program_options.hpp> namespace opts = boost::program_options; // TODO: see if we can switch from Eigen to boost for the math stuff // TODO: print warning if accelerometer magnitude is not close to 1 when starting up int millis() { struct timeval tv; gettimeofday(&tv, NULL); return (tv.tv_sec) * 1000 + (tv.tv_usec)/1000; } void print(matrix m) { printf("%7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f", m(0,0), m(0,1), m(0,2), m(1,0), m(1,1), m(1,2), m(2,0), m(2,1), m(2,2)); } void streamRawValues(IMU& imu) { imu.enable(); while(1) { imu.read(); printf("%7d %7d %7d %7d %7d %7d %7d %7d %7d\n", imu.raw_m[0], imu.raw_m[1], imu.raw_m[2], imu.raw_a[0], imu.raw_a[1], imu.raw_a[2], imu.raw_g[0], imu.raw_g[1], imu.raw_g[2] ); usleep(20*1000); } } matrix rotationFromCompass(const vector& acceleration, const vector& magnetic_field) { vector up = acceleration; // usually true vector east = magnetic_field.cross(up); // actual it's magnetic east vector north = up.cross(east); matrix rotationFromCompass; rotationFromCompass.row(0) = east; rotationFromCompass.row(1) = north; rotationFromCompass.row(2) = up; rotationFromCompass.row(0).normalize(); rotationFromCompass.row(1).normalize(); rotationFromCompass.row(2).normalize(); return rotationFromCompass; } float heading(matrix rotation) { // The board's x axis in earth coordinates. vector x = rotation.col(0); x.normalize(); x(2) = 0; // 0 = east, pi/2 = north return atan2(x(1), x(0)); } typedef void fuse_function(quaternion& rotation, float dt, const vector& angular_velocity, const vector& acceleration, const vector& magnetic_field); void fuse_compass_only(quaternion& rotation, float dt, const vector& angular_velocity, const vector& acceleration, const vector& magnetic_field) { // Implicit conversion of rotation matrix to quaternion. rotation = rotationFromCompass(acceleration, magnetic_field); } // w is angular velocity in radiands per second. // dt is the time. void rotate(quaternion& rotation, const vector& w, float dt) { // First order approximation of the quaternion representing this rotation. quaternion q = quaternion(1, w(0)*dt/2, w(1)*dt/2, w(2)*dt/2); rotation *= q; rotation.normalize(); } void fuse_gyro_only(quaternion& rotation, float dt, const vector& angular_velocity, const vector& acceleration, const vector& magnetic_field) { rotate(rotation, angular_velocity, dt); } void fuse_default(quaternion& rotation, float dt, const vector& angular_velocity, const vector& acceleration, const vector& magnetic_field) { vector correction = vector(0, 0, 0); if (abs(acceleration.norm() - 1) <= 0.3) { // The magnetidude of acceleration is close to 1 g, so // it might be pointing up and we can do drift correction. const float correction_strength = 1; matrix rotationCompass = rotationFromCompass(acceleration, magnetic_field); matrix rotationMatrix = rotation.toRotationMatrix(); correction = ( rotationCompass.row(0).cross(rotationMatrix.row(0)) + rotationCompass.row(1).cross(rotationMatrix.row(1)) + rotationCompass.row(2).cross(rotationMatrix.row(2)) ) * correction_strength; } rotate(rotation, angular_velocity + correction, dt); } void ahrs(IMU& imu, fuse_function * fuse_func) { imu.loadCalibration(); imu.enable(); imu.measureOffsets(); // The quaternion that can convert a vector in body coordinates // to ground coordinates when it its changed to a matrix. quaternion rotation = quaternion::Identity(); int start = millis(); // truncate 64-bit return value while(1) { int last_start = start; start = millis(); float dt = (start-last_start)/1000.0; if (dt < 0){ throw std::runtime_error("time went backwards"); } vector angular_velocity = imu.readGyro(); vector acceleration = imu.readAcc(); vector magnetic_field = imu.readMag(); fuse_func(rotation, dt, angular_velocity, acceleration, magnetic_field); matrix r = rotation.toRotationMatrix(); printf("%7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f\n", r(0,0), r(0,1), r(0,2), r(1,0), r(1,1), r(1,2), r(2,0), r(2,1), r(2,2), acceleration(0), acceleration(1), acceleration(2), magnetic_field(0), magnetic_field(1), magnetic_field(2)); fflush(stdout); // Ensure that each iteration of the loop takes at least 20 ms. while(millis() - start < 20) { usleep(1000); } } } std::pair<std::string, std::string> option_translator(const std::string& s) { if (s == "--gyro-only") { return std::make_pair("mode", "gyro-only"); } else if (s == "--compass-only") { return std::make_pair("mode", "compass-only"); } else if (s == "--raw") { return std::make_pair("mode", "raw"); } else { return std::make_pair(std::string(), std::string()); } } int main(int argc, char *argv[]) { try { std::string mode; opts::options_description desc("Allowed options"); desc.add_options() ("help", "produce help message") ("mode", opts::value<std::string>(&mode)->default_value("normal"), "normal (default): Fuse compass and gyro.\n" "gyro-only: Use only gyro (drifts).\n" "compass-only: Use only compass (noisy).\n" "raw: Just print raw values from sensors.") ; opts::variables_map vm; opts::store(opts::command_line_parser(argc, argv).options(desc).extra_parser(option_translator).run(), vm); opts::notify(vm); if(vm.count("help")) { std::cout << desc << std::endl; return 0; } MinIMU9 imu("/dev/i2c-0"); imu.checkConnection(); if (mode == "raw") { streamRawValues(imu); } else if (mode == "gyro-only") { ahrs(imu, &fuse_gyro_only); } else if (mode == "compass-only") { ahrs(imu, &fuse_compass_only); } else if (mode == "normal") { ahrs(imu, &fuse_default); } else { std::cerr << "Unknown mode '" << mode << "'" << std::endl; return 1; } return 0; } catch(const std::system_error & error) { auto what = error.what(); const std::error_code & code = error.code(); std::cerr << "Error: " << what << " " << code.message() << " (" << code << ")" << std::endl; return 2; } catch(const opts::multiple_occurrences & error) { std::cerr << "Error: " << error.what() << " of " << error.get_option_name() << " option." << std::endl; return 1; } catch(const std::exception & error) { std::cerr << "Error: " << error.what() << std::endl; return 9; } } <commit_msg>Succeeded in making a custom insertion operator for printing matrices!<commit_after>#include "vector.h" #include "MinIMU9.h" #include "version.h" #include <iostream> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <sys/time.h> #include <system_error> #include <boost/program_options.hpp> namespace opts = boost::program_options; // TODO: print warning if accelerometer magnitude is not close to 1 when starting up int millis() { struct timeval tv; gettimeofday(&tv, NULL); return (tv.tv_sec) * 1000 + (tv.tv_usec)/1000; } void print(matrix m) { printf("%7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f", m(0,0), m(0,1), m(0,2), m(1,0), m(1,1), m(1,2), m(2,0), m(2,1), m(2,2)); } void streamRawValues(IMU& imu) { imu.enable(); while(1) { imu.read(); printf("%7d %7d %7d %7d %7d %7d %7d %7d %7d\n", imu.raw_m[0], imu.raw_m[1], imu.raw_m[2], imu.raw_a[0], imu.raw_a[1], imu.raw_a[2], imu.raw_g[0], imu.raw_g[1], imu.raw_g[2] ); usleep(20*1000); } } matrix rotationFromCompass(const vector& acceleration, const vector& magnetic_field) { vector up = acceleration; // usually true vector east = magnetic_field.cross(up); // actual it's magnetic east vector north = up.cross(east); matrix rotationFromCompass; rotationFromCompass.row(0) = east; rotationFromCompass.row(1) = north; rotationFromCompass.row(2) = up; rotationFromCompass.row(0).normalize(); rotationFromCompass.row(1).normalize(); rotationFromCompass.row(2).normalize(); return rotationFromCompass; } float heading(matrix rotation) { // The board's x axis in earth coordinates. vector x = rotation.col(0); x.normalize(); x(2) = 0; // 0 = east, pi/2 = north return atan2(x(1), x(0)); } typedef void fuse_function(quaternion& rotation, float dt, const vector& angular_velocity, const vector& acceleration, const vector& magnetic_field); void fuse_compass_only(quaternion& rotation, float dt, const vector& angular_velocity, const vector& acceleration, const vector& magnetic_field) { // Implicit conversion of rotation matrix to quaternion. rotation = rotationFromCompass(acceleration, magnetic_field); } // w is angular velocity in radiands per second. // dt is the time. void rotate(quaternion& rotation, const vector& w, float dt) { // First order approximation of the quaternion representing this rotation. quaternion q = quaternion(1, w(0)*dt/2, w(1)*dt/2, w(2)*dt/2); rotation *= q; rotation.normalize(); } void fuse_gyro_only(quaternion& rotation, float dt, const vector& angular_velocity, const vector& acceleration, const vector& magnetic_field) { rotate(rotation, angular_velocity, dt); } void fuse_default(quaternion& rotation, float dt, const vector& angular_velocity, const vector& acceleration, const vector& magnetic_field) { vector correction = vector(0, 0, 0); if (abs(acceleration.norm() - 1) <= 0.3) { // The magnetidude of acceleration is close to 1 g, so // it might be pointing up and we can do drift correction. const float correction_strength = 1; matrix rotationCompass = rotationFromCompass(acceleration, magnetic_field); matrix rotationMatrix = rotation.toRotationMatrix(); correction = ( rotationCompass.row(0).cross(rotationMatrix.row(0)) + rotationCompass.row(1).cross(rotationMatrix.row(1)) + rotationCompass.row(2).cross(rotationMatrix.row(2)) ) * correction_strength; } rotate(rotation, angular_velocity + correction, dt); } std::ostream& operator << (std::ostream& os, const matrix& mc) { os << "woohoo! "; return os; } void ahrs(IMU& imu, fuse_function * fuse_func) { imu.loadCalibration(); imu.enable(); imu.measureOffsets(); // The quaternion that can convert a vector in body coordinates // to ground coordinates when it its changed to a matrix. quaternion rotation = quaternion::Identity(); int start = millis(); // truncate 64-bit return value while(1) { int last_start = start; start = millis(); float dt = (start-last_start)/1000.0; if (dt < 0){ throw std::runtime_error("time went backwards"); } vector angular_velocity = imu.readGyro(); vector acceleration = imu.readAcc(); vector magnetic_field = imu.readMag(); fuse_func(rotation, dt, angular_velocity, acceleration, magnetic_field); matrix r = rotation.toRotationMatrix(); std::cout << r; printf("%7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f\n", r(0,0), r(0,1), r(0,2), r(1,0), r(1,1), r(1,2), r(2,0), r(2,1), r(2,2), acceleration(0), acceleration(1), acceleration(2), magnetic_field(0), magnetic_field(1), magnetic_field(2)); fflush(stdout); // Ensure that each iteration of the loop takes at least 20 ms. while(millis() - start < 20) { usleep(1000); } } } std::pair<std::string, std::string> option_translator(const std::string& s) { if (s == "--gyro-only") { return std::make_pair("mode", "gyro-only"); } else if (s == "--compass-only") { return std::make_pair("mode", "compass-only"); } else if (s == "--raw") { return std::make_pair("mode", "raw"); } else { return std::make_pair(std::string(), std::string()); } } int main(int argc, char *argv[]) { try { std::string mode; opts::options_description desc("Allowed options"); desc.add_options() ("help,h", "produce help message") ("version,v", "print version number") ("mode", opts::value<std::string>(&mode)->default_value("normal"), "normal (default): Fuse compass and gyro.\n" "gyro-only: Use only gyro (drifts).\n" "compass-only: Use only compass (noisy).\n" "raw: Just print raw values from sensors.") ; opts::variables_map options; opts::store(opts::command_line_parser(argc, argv).options(desc).extra_parser(option_translator).run(), options); opts::notify(options); if(options.count("help")) { std::cout << desc << std::endl; return 0; } if (options.count("version")) { std::cout << VERSION << std::endl; return 0; } MinIMU9 imu("/dev/i2c-0"); imu.checkConnection(); if (mode == "raw") { streamRawValues(imu); } else if (mode == "gyro-only") { ahrs(imu, &fuse_gyro_only); } else if (mode == "compass-only") { ahrs(imu, &fuse_compass_only); } else if (mode == "normal") { ahrs(imu, &fuse_default); } else { std::cerr << "Unknown mode '" << mode << "'" << std::endl; return 1; } return 0; } catch(const std::system_error & error) { std::string what = error.what(); const std::error_code & code = error.code(); std::cerr << "Error: " << what << " " << code.message() << " (" << code << ")" << std::endl; return 2; } catch(const opts::multiple_occurrences & error) { std::cerr << "Error: " << error.what() << " of " << error.get_option_name() << " option." << std::endl; return 1; } catch(const std::exception & error) { std::cerr << "Error: " << error.what() << std::endl; return 9; } } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved */ #include "../../StroikaPreComp.h" #include "../../Execution/ErrNoException.h" #include "InternetAddress.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Memory; using namespace Stroika::Foundation::IO; using namespace Stroika::Foundation::IO::Network; #define qSupportPTONAndPTON_ (qPlatform_POSIX || (qPlatformWindows && (NTDDI_VERSION >= NTDDI_VISTA))) namespace { constexpr in_addr kV4AddrAny_ = { 0 }; constexpr in6_addr kV6AddrAny_ = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 } }; } const InternetAddress V4::kAddrAny = InternetAddress (kV4AddrAny_); const InternetAddress V6::kAddrAny = InternetAddress (kV6AddrAny_); namespace { inline const in_addr kV4Localhost_ () { // @todo - check if this localhost is right? May have byte order backwards - net or host byteorder??? in_addr p; p.s_addr = INADDR_LOOPBACK; return p; } constexpr in6_addr kV6Localhost_ = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 } }; } const InternetAddress V4::kLocalhost = InternetAddress (kV4Localhost_ ()); const InternetAddress V6::kLocalhost = InternetAddress (kV6Localhost_); /* ******************************************************************************** ********************* IO::Network::InternetAddress ***************************** ******************************************************************************** */ InternetAddress::InternetAddress (const string& s, AddressFamily af) : fAddressFamily_ (AddressFamily::UNKNOWN) { if (not s.empty ()) { if (af == AddressFamily::UNKNOWN) { // guess format - based on '.' versus ':' in name if (s.find ('.') != string::npos) { af = AddressFamily::V4; } else if (s.find (':') != string::npos) { af = AddressFamily::V6; } } switch (af) { case AddressFamily::V4: { #if qSupportPTONAndPTON_ Execution::ThrowErrNoIfNegative (inet_pton (AF_INET, s.c_str (), &fV4_)); #elif qPlatform_Windows fV4_.s_addr = ::inet_addr (s.c_str ()); #else AssertNotImplemented (); #endif fAddressFamily_ = af; } break; case AddressFamily::V6: { #if qSupportPTONAndPTON_ Execution::ThrowErrNoIfNegative (inet_pton (AF_INET6, s.c_str (), &fV6_)); #else AssertNotImplemented (); #endif fAddressFamily_ = af; } break; default: { // @todo need better exception Execution::DoThrow (Execution::StringException (L"Unrecognized address family")); } break; } } } InternetAddress::InternetAddress (const String& s, AddressFamily af) : fAddressFamily_ (AddressFamily::UNKNOWN) { *this = InternetAddress (s.AsUTF8 (), af); } namespace Stroika { namespace Foundation { namespace IO { namespace Network { template <> String InternetAddress::As<String> () const { switch (fAddressFamily_) { case AddressFamily::UNKNOWN: { return String (); } break; case AddressFamily::V4: { #if qSupportPTONAndPTON_ char buf[INET_ADDRSTRLEN + 1]; const char* result = ::inet_ntop (AF_INET, &fV4_, buf, sizeof (buf)); return result == nullptr ? String () : String::FromUTF8 (result); #else return String::FromUTF8 (::inet_ntoa (fV4_)); #endif } break; case AddressFamily::V6: { #if qSupportPTONAndPTON_ char buf[INET6_ADDRSTRLEN + 1]; const char* result = ::inet_ntop (AF_INET6, &fV6_, buf, sizeof (buf)); return result == nullptr ? String () : String::FromUTF8 (result); #else AssertNotImplemented (); return String (); #endif } break; default: { RequireNotReached (); return String (); } break; } } } } } } bool InternetAddress::IsLocalhostAddress () const { Require (not empty ()); switch (fAddressFamily_) { case AddressFamily::V4: { // 127.0.0.x return (fV4_.s_addr & 0xff000000) == 0x7f000000; } break; case AddressFamily::V6: { return fV6_.s6_addr[0] == 0 and fV6_.s6_addr[1] == 0 and fV6_.s6_addr[2] == 0 and fV6_.s6_addr[3] == 0 and fV6_.s6_addr[4] == 0 and fV6_.s6_addr[5] == 0 and fV6_.s6_addr[6] == 0 and fV6_.s6_addr[7] == 0 and fV6_.s6_addr[8] == 0 and fV6_.s6_addr[9] == 0 and fV6_.s6_addr[10] == 0 and fV6_.s6_addr[11] == 0 and fV6_.s6_addr[12] == 0 and fV6_.s6_addr[13] == 0 and fV6_.s6_addr[14] == 1 and fV6_.s6_addr[15] == 0 ; } break; } AssertNotReached (); return false; } bool InternetAddress::IsPrivateAddress () const { AssertNotImplemented (); return false; } bool InternetAddress::IsMulticastAddress () const { Require (not empty ()); switch (fAddressFamily_) { case AddressFamily::V4: { // Not sure - might have byte order backwards??? or totally wrong - a bit of a guess? return (fV4_.s_addr & 0xf0000000) == 0xe0000000; } break; case AddressFamily::V6: { return (fV6_.s6_addr[0] == 0xff); } break; } AssertNotReached (); return false; } <commit_msg>fixed in6_addr initializers<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved */ #include "../../StroikaPreComp.h" #include "../../Execution/ErrNoException.h" #include "InternetAddress.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Memory; using namespace Stroika::Foundation::IO; using namespace Stroika::Foundation::IO::Network; #define qSupportPTONAndPTON_ (qPlatform_POSIX || (qPlatformWindows && (NTDDI_VERSION >= NTDDI_VISTA))) namespace { constexpr in_addr kV4AddrAny_ = { 0 }; constexpr in6_addr kV6AddrAny_ = { { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 } } }; } const InternetAddress V4::kAddrAny = InternetAddress (kV4AddrAny_); const InternetAddress V6::kAddrAny = InternetAddress (kV6AddrAny_); namespace { inline const in_addr kV4Localhost_ () { // @todo - check if this localhost is right? May have byte order backwards - net or host byteorder??? in_addr p; p.s_addr = INADDR_LOOPBACK; return p; } constexpr in6_addr kV6Localhost_ = { { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 } } }; } const InternetAddress V4::kLocalhost = InternetAddress (kV4Localhost_ ()); const InternetAddress V6::kLocalhost = InternetAddress (kV6Localhost_); /* ******************************************************************************** ********************* IO::Network::InternetAddress ***************************** ******************************************************************************** */ InternetAddress::InternetAddress (const string& s, AddressFamily af) : fAddressFamily_ (AddressFamily::UNKNOWN) { if (not s.empty ()) { if (af == AddressFamily::UNKNOWN) { // guess format - based on '.' versus ':' in name if (s.find ('.') != string::npos) { af = AddressFamily::V4; } else if (s.find (':') != string::npos) { af = AddressFamily::V6; } } switch (af) { case AddressFamily::V4: { #if qSupportPTONAndPTON_ Execution::ThrowErrNoIfNegative (inet_pton (AF_INET, s.c_str (), &fV4_)); #elif qPlatform_Windows fV4_.s_addr = ::inet_addr (s.c_str ()); #else AssertNotImplemented (); #endif fAddressFamily_ = af; } break; case AddressFamily::V6: { #if qSupportPTONAndPTON_ Execution::ThrowErrNoIfNegative (inet_pton (AF_INET6, s.c_str (), &fV6_)); #else AssertNotImplemented (); #endif fAddressFamily_ = af; } break; default: { // @todo need better exception Execution::DoThrow (Execution::StringException (L"Unrecognized address family")); } break; } } } InternetAddress::InternetAddress (const String& s, AddressFamily af) : fAddressFamily_ (AddressFamily::UNKNOWN) { *this = InternetAddress (s.AsUTF8 (), af); } namespace Stroika { namespace Foundation { namespace IO { namespace Network { template <> String InternetAddress::As<String> () const { switch (fAddressFamily_) { case AddressFamily::UNKNOWN: { return String (); } break; case AddressFamily::V4: { #if qSupportPTONAndPTON_ char buf[INET_ADDRSTRLEN + 1]; const char* result = ::inet_ntop (AF_INET, &fV4_, buf, sizeof (buf)); return result == nullptr ? String () : String::FromUTF8 (result); #else return String::FromUTF8 (::inet_ntoa (fV4_)); #endif } break; case AddressFamily::V6: { #if qSupportPTONAndPTON_ char buf[INET6_ADDRSTRLEN + 1]; const char* result = ::inet_ntop (AF_INET6, &fV6_, buf, sizeof (buf)); return result == nullptr ? String () : String::FromUTF8 (result); #else AssertNotImplemented (); return String (); #endif } break; default: { RequireNotReached (); return String (); } break; } } } } } } bool InternetAddress::IsLocalhostAddress () const { Require (not empty ()); switch (fAddressFamily_) { case AddressFamily::V4: { // 127.0.0.x return (fV4_.s_addr & 0xff000000) == 0x7f000000; } break; case AddressFamily::V6: { return fV6_.s6_addr[0] == 0 and fV6_.s6_addr[1] == 0 and fV6_.s6_addr[2] == 0 and fV6_.s6_addr[3] == 0 and fV6_.s6_addr[4] == 0 and fV6_.s6_addr[5] == 0 and fV6_.s6_addr[6] == 0 and fV6_.s6_addr[7] == 0 and fV6_.s6_addr[8] == 0 and fV6_.s6_addr[9] == 0 and fV6_.s6_addr[10] == 0 and fV6_.s6_addr[11] == 0 and fV6_.s6_addr[12] == 0 and fV6_.s6_addr[13] == 0 and fV6_.s6_addr[14] == 1 and fV6_.s6_addr[15] == 0 ; } break; } AssertNotReached (); return false; } bool InternetAddress::IsPrivateAddress () const { AssertNotImplemented (); return false; } bool InternetAddress::IsMulticastAddress () const { Require (not empty ()); switch (fAddressFamily_) { case AddressFamily::V4: { // Not sure - might have byte order backwards??? or totally wrong - a bit of a guess? return (fV4_.s_addr & 0xf0000000) == 0xe0000000; } break; case AddressFamily::V6: { return (fV6_.s6_addr[0] == 0xff); } break; } AssertNotReached (); return false; } <|endoftext|>
<commit_before>/** * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com> * All Rights Reserved. * * This file is CONFIDENTIAL -- Distribution or duplication of this material or * the information contained herein is strictly forbidden unless prior written * permission is obtained. */ #include "stx/SHA1.h" #include "zbase/mapreduce/tasks/MapTableTask.h" #include "zbase/mapreduce/MapReduceScheduler.h" using namespace stx; namespace zbase { MapTableTask::MapTableTask( const AnalyticsSession& session, RefPtr<MapReduceJobSpec> job_spec, const TSDBTableRef& table_ref, AnalyticsAuth* auth, zbase::PartitionMap* pmap, zbase::ReplicationScheme* repl) : session_(session), job_spec_(job_spec), table_ref_(table_ref), auth_(auth), pmap_(pmap), repl_(repl) {} Vector<size_t> MapTableTask::build(MapReduceShardList* shards) { auto table = pmap_->findTable(session_.customer(), table_ref_.table_key); if (table.isEmpty()) { RAISEF(kNotFoundError, "table not found: $0", table_ref_.table_key); } auto partitioner = table.get()->partitioner(); auto partitions = partitioner->partitionKeysFor(table_ref_); Vector<size_t> indexes; for (const auto& partition : partitions) { auto shard = mkRef(new MapTableTaskShard()); shard->task = this; shard->table_ref = table_ref_; shard->table_ref.partition_key = partition; indexes.emplace_back(shards->size()); shards->emplace_back(shard.get()); } return indexes; } MapReduceShardResult MapTableTask::execute( RefPtr<MapReduceTaskShard> shard_base, RefPtr<MapReduceScheduler> job) { auto shard = shard_base.asInstanceOf<MapTableTaskShard>(); Vector<String> errors; auto hosts = repl_->replicasFor(table_ref_.partition_key.get()); for (const auto& host : hosts) { try { return executeRemote(shard, job, host); } catch (const StandardException& e) { logError( "z1.mapreduce", e, "MapTableTask::execute failed"); errors.emplace_back(e.what()); } } if (!errors.empty()) { RAISEF( kRuntimeError, "MapTableTask::execute failed: $0", StringUtil::join(errors, ", ")); } } MapReduceShardResult MapTableTask::executeRemote( RefPtr<MapTableTaskShard> shard_base, RefPtr<MapReduceScheduler> job, const ReplicaRef& host) { iputs("tbl ref: $0", table_ref_.partition_key); logDebug( "z1.mapreduce", "Executing map table shard on $0/$1/$2 on $3", session_.customer(), table_ref_.table_key, table_ref_.partition_key.get().toString(), host.addr.hostAndPort()); auto url = StringUtil::format( "http://$0/api/v1/mapreduce/tasks/map_partition?table=$1&partition=$2", host.addr.ipAndPort(), URI::urlEncode(table_ref_.table_key), table_ref_.partition_key.get().toString()); auto api_token = auth_->encodeAuthToken(session_); http::HTTPMessage::HeaderList auth_headers; auth_headers.emplace_back( "Authorization", StringUtil::format("Token $0", api_token)); http::HTTPClient http_client; auto req = http::HTTPRequest::mkGet(url, auth_headers); auto res = http_client.executeRequest(req); if (res.statusCode() != 201) { RAISEF( kRuntimeError, "received non-201 response: $0", res.body().toString()); } MapReduceShardResult result { .host = host, .result_id = SHA1Hash::fromHexString(res.body().toString()) }; return result; } } // namespace zbase <commit_msg>use shard table ref<commit_after>/** * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com> * All Rights Reserved. * * This file is CONFIDENTIAL -- Distribution or duplication of this material or * the information contained herein is strictly forbidden unless prior written * permission is obtained. */ #include "stx/SHA1.h" #include "zbase/mapreduce/tasks/MapTableTask.h" #include "zbase/mapreduce/MapReduceScheduler.h" using namespace stx; namespace zbase { MapTableTask::MapTableTask( const AnalyticsSession& session, RefPtr<MapReduceJobSpec> job_spec, const TSDBTableRef& table_ref, AnalyticsAuth* auth, zbase::PartitionMap* pmap, zbase::ReplicationScheme* repl) : session_(session), job_spec_(job_spec), table_ref_(table_ref), auth_(auth), pmap_(pmap), repl_(repl) {} Vector<size_t> MapTableTask::build(MapReduceShardList* shards) { auto table = pmap_->findTable(session_.customer(), table_ref_.table_key); if (table.isEmpty()) { RAISEF(kNotFoundError, "table not found: $0", table_ref_.table_key); } auto partitioner = table.get()->partitioner(); auto partitions = partitioner->partitionKeysFor(table_ref_); Vector<size_t> indexes; for (const auto& partition : partitions) { auto shard = mkRef(new MapTableTaskShard()); shard->task = this; shard->table_ref = table_ref_; shard->table_ref.partition_key = partition; indexes.emplace_back(shards->size()); shards->emplace_back(shard.get()); } return indexes; } MapReduceShardResult MapTableTask::execute( RefPtr<MapReduceTaskShard> shard_base, RefPtr<MapReduceScheduler> job) { auto shard = shard_base.asInstanceOf<MapTableTaskShard>(); Vector<String> errors; auto hosts = repl_->replicasFor(shard->table_ref.partition_key.get()); for (const auto& host : hosts) { try { return executeRemote(shard, job, host); } catch (const StandardException& e) { logError( "z1.mapreduce", e, "MapTableTask::execute failed"); errors.emplace_back(e.what()); } } RAISEF( kRuntimeError, "MapTableTask::execute failed: $0", StringUtil::join(errors, ", ")); } MapReduceShardResult MapTableTask::executeRemote( RefPtr<MapTableTaskShard> shard, RefPtr<MapReduceScheduler> job, const ReplicaRef& host) { logDebug( "z1.mapreduce", "Executing map table shard on $0/$1/$2 on $3", session_.customer(), shard->table_ref.table_key, shard->table_ref.partition_key.get().toString(), host.addr.hostAndPort()); auto url = StringUtil::format( "http://$0/api/v1/mapreduce/tasks/map_partition?table=$1&partition=$2", host.addr.ipAndPort(), URI::urlEncode(shard->table_ref.table_key), shard->table_ref.partition_key.get().toString()); auto api_token = auth_->encodeAuthToken(session_); http::HTTPMessage::HeaderList auth_headers; auth_headers.emplace_back( "Authorization", StringUtil::format("Token $0", api_token)); http::HTTPClient http_client; auto req = http::HTTPRequest::mkGet(url, auth_headers); auto res = http_client.executeRequest(req); if (res.statusCode() != 201) { RAISEF( kRuntimeError, "received non-201 response: $0", res.body().toString()); } MapReduceShardResult result { .host = host, .result_id = SHA1Hash::fromHexString(res.body().toString()) }; return result; } } // namespace zbase <|endoftext|>
<commit_before>// ------------------------------------------------------------------------- // @FileName : NFGameServerPlugin.cpp // @Author : LvSheng.Huang // @Date : 2012-07-14 08:51 // @Module : NFGameServerPlugin // // ------------------------------------------------------------------------- #include "NFGameLogicPlugin.h" #include "NFCGameLogicModule.h" #include "NFCBuffModule.h" #include "NFCItemModule.h" #include "NFCPackModule.h" #include "NFCSkillModule.h" #include "NFCBulletSkillConsumeProcessModule.h" #include "NFCBriefSkillConsumeProcessModule.h" #include "NFCSkillConsumeManagerModule.h" #include "NFCPotionItemConsumeProcessModule.h" #include "NFCCardItemConsumeProcessModule.h" #include "NFCItemConsumeManagerModule.h" #include "NFCNPCRefreshModule.h" #include "NFCRebornItemConsumeProcessModule.h" #include "NFCAwardPackModule.h" #ifdef NF_DYNAMIC_PLUGIN extern "C" __declspec( dllexport ) void DllStartPlugin( NFIPluginManager* pm ) { CREATE_PLUGIN( pm, NFGameLogicPlugin ) }; extern "C" __declspec( dllexport ) void DllStopPlugin( NFIPluginManager* pm ) { DESTROY_PLUGIN( pm, NFGameLogicPlugin ) }; #endif ////////////////////////////////////////////////////////////////////////// const int NFGameLogicPlugin::GetPluginVersion() { return 0; } const std::string NFGameLogicPlugin::GetPluginName() { GET_PLUGIN_NAME( NFGameLogicPlugin ) } void NFGameLogicPlugin::Install() { REGISTER_MODULE( pPluginManager, NFCGameLogicModule ) REGISTER_MODULE( pPluginManager, NFCBuffModule ) REGISTER_MODULE( pPluginManager, NFCItemModule ) REGISTER_MODULE( pPluginManager, NFCPackModule ) REGISTER_MODULE( pPluginManager, NFCSkillModule ) REGISTER_MODULE( pPluginManager, NFCRebornItemConsumeProcessModule ) REGISTER_MODULE( pPluginManager, NFCItemConsumeManagerModule ) REGISTER_MODULE( pPluginManager, NFCPotionItemConsumeProcessModule ) REGISTER_MODULE( pPluginManager, NFCCardItemConsumeProcessModule ) //Continue to add other item types of consumption REGISTER_MODULE( pPluginManager, NFCSkillConsumeManagerModule ) REGISTER_MODULE( pPluginManager, NFCBriefSkillConsumeProcessModule ) REGISTER_MODULE( pPluginManager, NFCBulletSkillConsumeProcessModule ) //Continue to add other skill types of consumption REGISTER_MODULE( pPluginManager, NFCNPCRefreshModule ) REGISTER_MODULE(pPluginManager, NFCAwardPackModule) } void NFGameLogicPlugin::Uninstall() { UNREGISTER_MODULE(pPluginManager, NFCAwardPackModule) UNREGISTER_MODULE( pPluginManager, NFCNPCRefreshModule ) UNREGISTER_MODULE( pPluginManager, NFCBulletSkillConsumeProcessModule ) UNREGISTER_MODULE( pPluginManager, NFCBriefSkillConsumeProcessModule ) UNREGISTER_MODULE( pPluginManager, NFCSkillConsumeManagerModule ) UNREGISTER_MODULE( pPluginManager, NFCCardItemConsumeProcessModule ) UNREGISTER_MODULE( pPluginManager, NFCPotionItemConsumeProcessModule ) UNREGISTER_MODULE( pPluginManager, NFCItemConsumeManagerModule ) UNREGISTER_MODULE( pPluginManager, NFCRebornItemConsumeProcessModule ) UNREGISTER_MODULE( pPluginManager, NFCSkillModule ) UNREGISTER_MODULE( pPluginManager, NFCPackModule ) UNREGISTER_MODULE( pPluginManager, NFCItemModule ) UNREGISTER_MODULE( pPluginManager, NFCBuffModule ) UNREGISTER_MODULE( pPluginManager, NFCGameLogicModule ) } <commit_msg>register NFCEctypeModule<commit_after>// ------------------------------------------------------------------------- // @FileName : NFGameServerPlugin.cpp // @Author : LvSheng.Huang // @Date : 2012-07-14 08:51 // @Module : NFGameServerPlugin // // ------------------------------------------------------------------------- #include "NFGameLogicPlugin.h" #include "NFCGameLogicModule.h" #include "NFCBuffModule.h" #include "NFCItemModule.h" #include "NFCPackModule.h" #include "NFCSkillModule.h" #include "NFCBulletSkillConsumeProcessModule.h" #include "NFCBriefSkillConsumeProcessModule.h" #include "NFCSkillConsumeManagerModule.h" #include "NFCPotionItemConsumeProcessModule.h" #include "NFCCardItemConsumeProcessModule.h" #include "NFCItemConsumeManagerModule.h" #include "NFCNPCRefreshModule.h" #include "NFCRebornItemConsumeProcessModule.h" #include "NFCAwardPackModule.h" #include "NFCEctypeModule.h" #ifdef NF_DYNAMIC_PLUGIN extern "C" __declspec( dllexport ) void DllStartPlugin( NFIPluginManager* pm ) { CREATE_PLUGIN( pm, NFGameLogicPlugin ) }; extern "C" __declspec( dllexport ) void DllStopPlugin( NFIPluginManager* pm ) { DESTROY_PLUGIN( pm, NFGameLogicPlugin ) }; #endif ////////////////////////////////////////////////////////////////////////// const int NFGameLogicPlugin::GetPluginVersion() { return 0; } const std::string NFGameLogicPlugin::GetPluginName() { GET_PLUGIN_NAME( NFGameLogicPlugin ) } void NFGameLogicPlugin::Install() { REGISTER_MODULE( pPluginManager, NFCGameLogicModule ) REGISTER_MODULE( pPluginManager, NFCBuffModule ) REGISTER_MODULE( pPluginManager, NFCItemModule ) REGISTER_MODULE( pPluginManager, NFCPackModule ) REGISTER_MODULE( pPluginManager, NFCSkillModule ) REGISTER_MODULE( pPluginManager, NFCRebornItemConsumeProcessModule ) REGISTER_MODULE( pPluginManager, NFCItemConsumeManagerModule ) REGISTER_MODULE( pPluginManager, NFCPotionItemConsumeProcessModule ) REGISTER_MODULE( pPluginManager, NFCCardItemConsumeProcessModule ) //Continue to add other item types of consumption REGISTER_MODULE( pPluginManager, NFCSkillConsumeManagerModule ) REGISTER_MODULE( pPluginManager, NFCBriefSkillConsumeProcessModule ) REGISTER_MODULE( pPluginManager, NFCBulletSkillConsumeProcessModule ) //Continue to add other skill types of consumption REGISTER_MODULE( pPluginManager, NFCNPCRefreshModule ) REGISTER_MODULE(pPluginManager, NFCAwardPackModule) REGISTER_MODULE(pPluginManager, NFCEctypeModule) } void NFGameLogicPlugin::Uninstall() { UNREGISTER_MODULE(pPluginManager, NFCEctypeModule) UNREGISTER_MODULE(pPluginManager, NFCAwardPackModule) UNREGISTER_MODULE( pPluginManager, NFCNPCRefreshModule ) UNREGISTER_MODULE( pPluginManager, NFCBulletSkillConsumeProcessModule ) UNREGISTER_MODULE( pPluginManager, NFCBriefSkillConsumeProcessModule ) UNREGISTER_MODULE( pPluginManager, NFCSkillConsumeManagerModule ) UNREGISTER_MODULE( pPluginManager, NFCCardItemConsumeProcessModule ) UNREGISTER_MODULE( pPluginManager, NFCPotionItemConsumeProcessModule ) UNREGISTER_MODULE( pPluginManager, NFCItemConsumeManagerModule ) UNREGISTER_MODULE( pPluginManager, NFCRebornItemConsumeProcessModule ) UNREGISTER_MODULE( pPluginManager, NFCSkillModule ) UNREGISTER_MODULE( pPluginManager, NFCPackModule ) UNREGISTER_MODULE( pPluginManager, NFCItemModule ) UNREGISTER_MODULE( pPluginManager, NFCBuffModule ) UNREGISTER_MODULE( pPluginManager, NFCGameLogicModule ) } <|endoftext|>
<commit_before>// Copyright (c) 2006, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <string.h> #include "common/convert_UTF.h" #include "common/string_conversion.h" #include "common/using_std_string.h" #include "processor/scoped_ptr.h" namespace google_breakpad { using std::vector; void UTF8ToUTF16(const char *in, vector<u_int16_t> *out) { size_t source_length = strlen(in); const UTF8 *source_ptr = reinterpret_cast<const UTF8 *>(in); const UTF8 *source_end_ptr = source_ptr + source_length; // Erase the contents and zero fill to the expected size out->clear(); out->insert(out->begin(), source_length, 0); u_int16_t *target_ptr = &(*out)[0]; u_int16_t *target_end_ptr = target_ptr + out->capacity() * sizeof(u_int16_t); ConversionResult result = ConvertUTF8toUTF16(&source_ptr, source_end_ptr, &target_ptr, target_end_ptr, strictConversion); // Resize to be the size of the # of converted characters + NULL out->resize(result == conversionOK ? target_ptr - &(*out)[0] + 1: 0); } int UTF8ToUTF16Char(const char *in, int in_length, u_int16_t out[2]) { const UTF8 *source_ptr = reinterpret_cast<const UTF8 *>(in); const UTF8 *source_end_ptr = source_ptr + sizeof(char); u_int16_t *target_ptr = out; u_int16_t *target_end_ptr = target_ptr + 2 * sizeof(u_int16_t); out[0] = out[1] = 0; // Process one character at a time while (1) { ConversionResult result = ConvertUTF8toUTF16(&source_ptr, source_end_ptr, &target_ptr, target_end_ptr, strictConversion); if (result == conversionOK) return static_cast<int>(source_ptr - reinterpret_cast<const UTF8 *>(in)); // Add another character to the input stream and try again source_ptr = reinterpret_cast<const UTF8 *>(in); ++source_end_ptr; if (source_end_ptr > reinterpret_cast<const UTF8 *>(in) + in_length) break; } return 0; } void UTF32ToUTF16(const wchar_t *in, vector<u_int16_t> *out) { size_t source_length = wcslen(in); const UTF32 *source_ptr = reinterpret_cast<const UTF32 *>(in); const UTF32 *source_end_ptr = source_ptr + source_length; // Erase the contents and zero fill to the expected size out->clear(); out->insert(out->begin(), source_length, 0); u_int16_t *target_ptr = &(*out)[0]; u_int16_t *target_end_ptr = target_ptr + out->capacity() * sizeof(u_int16_t); ConversionResult result = ConvertUTF32toUTF16(&source_ptr, source_end_ptr, &target_ptr, target_end_ptr, strictConversion); // Resize to be the size of the # of converted characters + NULL out->resize(result == conversionOK ? target_ptr - &(*out)[0] + 1: 0); } void UTF32ToUTF16Char(wchar_t in, u_int16_t out[2]) { const UTF32 *source_ptr = reinterpret_cast<const UTF32 *>(&in); const UTF32 *source_end_ptr = source_ptr + 1; u_int16_t *target_ptr = out; u_int16_t *target_end_ptr = target_ptr + 2 * sizeof(u_int16_t); out[0] = out[1] = 0; ConversionResult result = ConvertUTF32toUTF16(&source_ptr, source_end_ptr, &target_ptr, target_end_ptr, strictConversion); if (result != conversionOK) { out[0] = out[1] = 0; } } static inline u_int16_t Swap(u_int16_t value) { return (value >> 8) | static_cast<uint16_t>(value << 8); } string UTF16ToUTF8(const vector<u_int16_t> &in, bool swap) { const UTF16 *source_ptr = &in[0]; scoped_ptr<u_int16_t> source_buffer; // If we're to swap, we need to make a local copy and swap each byte pair if (swap) { int idx = 0; source_buffer.reset(new u_int16_t[in.size()]); UTF16 *source_buffer_ptr = source_buffer.get(); for (vector<u_int16_t>::const_iterator it = in.begin(); it != in.end(); ++it, ++idx) source_buffer_ptr[idx] = Swap(*it); source_ptr = source_buffer.get(); } // The maximum expansion would be 4x the size of the input string. const UTF16 *source_end_ptr = source_ptr + in.size(); size_t target_capacity = in.size() * 4; scoped_array<UTF8> target_buffer(new UTF8[target_capacity]); UTF8 *target_ptr = target_buffer.get(); UTF8 *target_end_ptr = target_ptr + target_capacity; ConversionResult result = ConvertUTF16toUTF8(&source_ptr, source_end_ptr, &target_ptr, target_end_ptr, strictConversion); if (result == conversionOK) { const char *targetPtr = reinterpret_cast<const char *>(target_buffer.get()); return targetPtr; } return ""; } } // namespace google_breakpad <commit_msg>Fix type in string_conversion.cc introduced in r1046<commit_after>// Copyright (c) 2006, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <string.h> #include "common/convert_UTF.h" #include "common/string_conversion.h" #include "common/using_std_string.h" #include "processor/scoped_ptr.h" namespace google_breakpad { using std::vector; void UTF8ToUTF16(const char *in, vector<u_int16_t> *out) { size_t source_length = strlen(in); const UTF8 *source_ptr = reinterpret_cast<const UTF8 *>(in); const UTF8 *source_end_ptr = source_ptr + source_length; // Erase the contents and zero fill to the expected size out->clear(); out->insert(out->begin(), source_length, 0); u_int16_t *target_ptr = &(*out)[0]; u_int16_t *target_end_ptr = target_ptr + out->capacity() * sizeof(u_int16_t); ConversionResult result = ConvertUTF8toUTF16(&source_ptr, source_end_ptr, &target_ptr, target_end_ptr, strictConversion); // Resize to be the size of the # of converted characters + NULL out->resize(result == conversionOK ? target_ptr - &(*out)[0] + 1: 0); } int UTF8ToUTF16Char(const char *in, int in_length, u_int16_t out[2]) { const UTF8 *source_ptr = reinterpret_cast<const UTF8 *>(in); const UTF8 *source_end_ptr = source_ptr + sizeof(char); u_int16_t *target_ptr = out; u_int16_t *target_end_ptr = target_ptr + 2 * sizeof(u_int16_t); out[0] = out[1] = 0; // Process one character at a time while (1) { ConversionResult result = ConvertUTF8toUTF16(&source_ptr, source_end_ptr, &target_ptr, target_end_ptr, strictConversion); if (result == conversionOK) return static_cast<int>(source_ptr - reinterpret_cast<const UTF8 *>(in)); // Add another character to the input stream and try again source_ptr = reinterpret_cast<const UTF8 *>(in); ++source_end_ptr; if (source_end_ptr > reinterpret_cast<const UTF8 *>(in) + in_length) break; } return 0; } void UTF32ToUTF16(const wchar_t *in, vector<u_int16_t> *out) { size_t source_length = wcslen(in); const UTF32 *source_ptr = reinterpret_cast<const UTF32 *>(in); const UTF32 *source_end_ptr = source_ptr + source_length; // Erase the contents and zero fill to the expected size out->clear(); out->insert(out->begin(), source_length, 0); u_int16_t *target_ptr = &(*out)[0]; u_int16_t *target_end_ptr = target_ptr + out->capacity() * sizeof(u_int16_t); ConversionResult result = ConvertUTF32toUTF16(&source_ptr, source_end_ptr, &target_ptr, target_end_ptr, strictConversion); // Resize to be the size of the # of converted characters + NULL out->resize(result == conversionOK ? target_ptr - &(*out)[0] + 1: 0); } void UTF32ToUTF16Char(wchar_t in, u_int16_t out[2]) { const UTF32 *source_ptr = reinterpret_cast<const UTF32 *>(&in); const UTF32 *source_end_ptr = source_ptr + 1; u_int16_t *target_ptr = out; u_int16_t *target_end_ptr = target_ptr + 2 * sizeof(u_int16_t); out[0] = out[1] = 0; ConversionResult result = ConvertUTF32toUTF16(&source_ptr, source_end_ptr, &target_ptr, target_end_ptr, strictConversion); if (result != conversionOK) { out[0] = out[1] = 0; } } static inline u_int16_t Swap(u_int16_t value) { return (value >> 8) | static_cast<u_int16_t>(value << 8); } string UTF16ToUTF8(const vector<u_int16_t> &in, bool swap) { const UTF16 *source_ptr = &in[0]; scoped_ptr<u_int16_t> source_buffer; // If we're to swap, we need to make a local copy and swap each byte pair if (swap) { int idx = 0; source_buffer.reset(new u_int16_t[in.size()]); UTF16 *source_buffer_ptr = source_buffer.get(); for (vector<u_int16_t>::const_iterator it = in.begin(); it != in.end(); ++it, ++idx) source_buffer_ptr[idx] = Swap(*it); source_ptr = source_buffer.get(); } // The maximum expansion would be 4x the size of the input string. const UTF16 *source_end_ptr = source_ptr + in.size(); size_t target_capacity = in.size() * 4; scoped_array<UTF8> target_buffer(new UTF8[target_capacity]); UTF8 *target_ptr = target_buffer.get(); UTF8 *target_end_ptr = target_ptr + target_capacity; ConversionResult result = ConvertUTF16toUTF8(&source_ptr, source_end_ptr, &target_ptr, target_end_ptr, strictConversion); if (result == conversionOK) { const char *targetPtr = reinterpret_cast<const char *>(target_buffer.get()); return targetPtr; } return ""; } } // namespace google_breakpad <|endoftext|>
<commit_before>#ifndef STAN_MATH_REV_FUN_HMM_MARGINAL_LPDF_HPP #define STAN_MATH_REV_FUN_HMM_MARGINAL_LPDF_HPP #include <stan/math/prim/meta.hpp> #include <stan/math/prim/err.hpp> #include <stan/math/prim/fun/row.hpp> #include <stan/math/prim/fun/col.hpp> #include <stan/math/prim/fun/transpose.hpp> #include <stan/math/prim/fun/exp.hpp> #include <stan/math/prim/fun/value_of.hpp> #include <stan/math/prim/core.hpp> #include <vector> #include <iostream> namespace stan { namespace math { /** * For a Hidden Markov Model with observation y, hidden state x, * and parameters theta, return the log marginal density, log * p(y | theta). In this setting, the hidden states are discrete * and take values over the finite space {1, ..., K}. * The marginal lpdf is obtained via a forward pass, and * the derivative is calculated with an adjoint method, * see (Betancourt, Margossian, & Leos-Barajas, 2020). * * @tparam T_omega type of the log likelihood matrix * @tparam T_Gamma type of the transition matrix * @tparam T_rho type of the initial guess vector * * @param[in] log_omega log matrix of observational densities. * The (i, j)th entry corresponds to the * density of the ith observation, y_i, * given x_i = j. * @param[in] Gamma transition density between hidden states. * The (i, j)th entry is the probability that x_n = j, * given x_{n - 1} = i. The rows of Gamma are simplexes. * @param[in] rho initial state * @throw `std::domain_error` if Gamma is not square. * @throw `std::invalid_argument` if the size of rho is not * the number of rows of Gamma. * @throw `std::domain_error` if rho is not a simplex. * @throw `std::domain_error` if the rows of Gamma are * not a simplex. * @return log marginal density. */ template <typename T_omega, typename T_Gamma, typename T_rho> inline return_type_t<T_omega, T_Gamma, T_rho> hmm_marginal_lpdf( const Eigen::Matrix<T_omega, Eigen::Dynamic, Eigen::Dynamic>& log_omegas, const Eigen::Matrix<T_Gamma, Eigen::Dynamic, Eigen::Dynamic>& Gamma, const Eigen::Matrix<T_rho, Eigen::Dynamic, 1>& rho) { using T_partial_type = partials_return_t<T_omega, T_Gamma, T_rho>; using eig_matrix_partial = Eigen::Matrix<T_partial_type, Eigen::Dynamic, Eigen::Dynamic>; using eig_vector_partial = Eigen::Matrix<T_partial_type, Eigen::Dynamic, 1>; int n_states = log_omegas.rows(); int n_transitions = log_omegas.cols() - 1; check_square("hmm_marginal_lpdf", "Gamma", Gamma); check_consistent_size("hmm_marginal_lpdf", "Gamma", row(Gamma, 1), n_states); check_consistent_size("hmm_marginal_lpdf", "rho", rho, n_states); check_simplex("hmm_marginal_lpdf", "rho", rho); for (int i = 0; i < Gamma.rows(); ++i) { check_simplex("hmm_marginal_lpdf", "Gamma[i, ]", row(Gamma, i + 1)); } operands_and_partials<Eigen::Matrix<T_omega, Eigen::Dynamic, Eigen::Dynamic>, Eigen::Matrix<T_Gamma, Eigen::Dynamic, Eigen::Dynamic>, Eigen::Matrix<T_rho, Eigen::Dynamic, 1> > ops_partials(log_omegas, Gamma, rho); eig_matrix_partial alphas(n_states, n_transitions + 1); eig_vector_partial alpha_log_norms(n_transitions + 1); eig_matrix_partial omegas; auto Gamma_val = value_of(Gamma).eval(); // compute the density using the forward algorithm. { const auto log_omegas_val = value_of(log_omegas).eval(); const auto rho_val = value_of(rho).eval(); omegas = log_omegas_val.array().exp(); const int n_states = log_omegas_val.rows(); const int n_transitions = log_omegas_val.cols() - 1; alphas.col(0) = omegas.col(0).cwiseProduct(rho_val); const auto norm = alphas.col(0).maxCoeff(); alphas.col(0) /= norm; alpha_log_norms(0) = log(norm); for (int n = 0; n < n_transitions; ++n) { alphas.col(n + 1) = omegas.col(n + 1).cwiseProduct(Gamma_val.transpose() * alphas.col(n)); const auto col_norm = alphas.col(n + 1).maxCoeff(); alphas.col(n + 1) /= col_norm; alpha_log_norms(n + 1) = log(col_norm) + alpha_log_norms(n); } } const auto log_marginal_density = log(alphas.col(n_transitions).sum()) + alpha_log_norms(n_transitions); // Variables required for all three Jacobian-adjoint products. const auto norm_norm = alpha_log_norms(n_transitions); const auto unnormed_marginal = alphas.col(n_transitions).sum(); std::vector<eig_vector_partial> kappa(n_transitions); eig_vector_partial kappa_log_norms(n_transitions); std::vector<T_partial_type> grad_corr(n_transitions, 0); if (n_transitions > 0) { kappa[n_transitions - 1] = Eigen::VectorXd::Ones(n_states); kappa_log_norms(n_transitions - 1) = 0; grad_corr[n_transitions - 1] = exp(alpha_log_norms(n_transitions - 1) - norm_norm); } for (int n = n_transitions - 2; n >= 0; --n) { kappa[n] = Gamma_val * (omegas.col(n + 2).cwiseProduct(kappa[n + 1])); const auto norm = kappa[n].maxCoeff(); kappa[n] /= norm; kappa_log_norms[n] = log(norm) + kappa_log_norms[n + 1]; grad_corr[n] = exp(alpha_log_norms[n] + kappa_log_norms[n] - norm_norm); } if (!is_constant_all<T_Gamma>::value) { eig_matrix_partial Gamma_jacad = Eigen::MatrixXd::Zero(n_states, n_states); for (int n = n_transitions - 1; n >= 0; --n) { Gamma_jacad += (grad_corr[n] * kappa[n].cwiseProduct(omegas.col(n + 1)) * alphas.col(n).transpose()) .transpose(); } Gamma_jacad /= unnormed_marginal; ops_partials.edge2_.partials_ = Gamma_jacad; } const bool sensitivities_for_omega_or_rho = (!is_constant_all<T_omega>::value) || (!is_constant_all<T_rho>::value); if (sensitivities_for_omega_or_rho) { eig_matrix_partial log_omega_jacad = Eigen::MatrixXd::Zero(n_states, n_transitions + 1); if (!is_constant_all<T_omega>::value) { for (int n = n_transitions - 1; n >= 0; --n) log_omega_jacad.col(n + 1) = grad_corr[n] * kappa[n].cwiseProduct(Gamma_val.transpose() * alphas.col(n)); } // Boundary terms if (n_transitions == 0) { if (!is_constant_all<T_omega>::value) { log_omega_jacad.col(0) = omegas.col(0).cwiseProduct(value_of(rho)) / exp(log_marginal_density); ops_partials.edge1_.partials_ = log_omega_jacad; } if (!is_constant_all<T_rho>::value) { ops_partials.edge3_.partials_ = omegas.col(0) / exp(log_marginal_density); } } else { const auto grad_corr_boundary = exp(kappa_log_norms(0) - norm_norm); auto C = Gamma_val * omegas.col(1).cwiseProduct(kappa[0]); if (!is_constant_all<T_omega>::value) { log_omega_jacad.col(0) = grad_corr_boundary * C.cwiseProduct(value_of(rho)); ops_partials.edge1_.partials_ = log_omega_jacad.cwiseProduct(omegas / unnormed_marginal); } if (!is_constant_all<T_rho>::value) { ops_partials.edge3_.partials_ = grad_corr_boundary * C.cwiseProduct(omegas.col(0)) / unnormed_marginal; } } } return ops_partials.build(log_marginal_density); } } // namespace math } // namespace stan #endif <commit_msg>Remove auto from C in hmm so it's only computed once<commit_after>#ifndef STAN_MATH_REV_FUN_HMM_MARGINAL_LPDF_HPP #define STAN_MATH_REV_FUN_HMM_MARGINAL_LPDF_HPP #include <stan/math/prim/meta.hpp> #include <stan/math/prim/err.hpp> #include <stan/math/prim/fun/row.hpp> #include <stan/math/prim/fun/col.hpp> #include <stan/math/prim/fun/transpose.hpp> #include <stan/math/prim/fun/exp.hpp> #include <stan/math/prim/fun/value_of.hpp> #include <stan/math/prim/core.hpp> #include <vector> #include <iostream> namespace stan { namespace math { /** * For a Hidden Markov Model with observation y, hidden state x, * and parameters theta, return the log marginal density, log * p(y | theta). In this setting, the hidden states are discrete * and take values over the finite space {1, ..., K}. * The marginal lpdf is obtained via a forward pass, and * the derivative is calculated with an adjoint method, * see (Betancourt, Margossian, & Leos-Barajas, 2020). * * @tparam T_omega type of the log likelihood matrix * @tparam T_Gamma type of the transition matrix * @tparam T_rho type of the initial guess vector * * @param[in] log_omega log matrix of observational densities. * The (i, j)th entry corresponds to the * density of the ith observation, y_i, * given x_i = j. * @param[in] Gamma transition density between hidden states. * The (i, j)th entry is the probability that x_n = j, * given x_{n - 1} = i. The rows of Gamma are simplexes. * @param[in] rho initial state * @throw `std::domain_error` if Gamma is not square. * @throw `std::invalid_argument` if the size of rho is not * the number of rows of Gamma. * @throw `std::domain_error` if rho is not a simplex. * @throw `std::domain_error` if the rows of Gamma are * not a simplex. * @return log marginal density. */ template <typename T_omega, typename T_Gamma, typename T_rho> inline return_type_t<T_omega, T_Gamma, T_rho> hmm_marginal_lpdf( const Eigen::Matrix<T_omega, Eigen::Dynamic, Eigen::Dynamic>& log_omegas, const Eigen::Matrix<T_Gamma, Eigen::Dynamic, Eigen::Dynamic>& Gamma, const Eigen::Matrix<T_rho, Eigen::Dynamic, 1>& rho) { using T_partial_type = partials_return_t<T_omega, T_Gamma, T_rho>; using eig_matrix_partial = Eigen::Matrix<T_partial_type, Eigen::Dynamic, Eigen::Dynamic>; using eig_vector_partial = Eigen::Matrix<T_partial_type, Eigen::Dynamic, 1>; int n_states = log_omegas.rows(); int n_transitions = log_omegas.cols() - 1; check_square("hmm_marginal_lpdf", "Gamma", Gamma); check_consistent_size("hmm_marginal_lpdf", "Gamma", row(Gamma, 1), n_states); check_consistent_size("hmm_marginal_lpdf", "rho", rho, n_states); check_simplex("hmm_marginal_lpdf", "rho", rho); for (int i = 0; i < Gamma.rows(); ++i) { check_simplex("hmm_marginal_lpdf", "Gamma[i, ]", row(Gamma, i + 1)); } operands_and_partials<Eigen::Matrix<T_omega, Eigen::Dynamic, Eigen::Dynamic>, Eigen::Matrix<T_Gamma, Eigen::Dynamic, Eigen::Dynamic>, Eigen::Matrix<T_rho, Eigen::Dynamic, 1> > ops_partials(log_omegas, Gamma, rho); eig_matrix_partial alphas(n_states, n_transitions + 1); eig_vector_partial alpha_log_norms(n_transitions + 1); eig_matrix_partial omegas; auto Gamma_val = value_of(Gamma).eval(); // compute the density using the forward algorithm. { const auto log_omegas_val = value_of(log_omegas).eval(); const auto rho_val = value_of(rho).eval(); omegas = log_omegas_val.array().exp(); const int n_states = log_omegas_val.rows(); const int n_transitions = log_omegas_val.cols() - 1; alphas.col(0) = omegas.col(0).cwiseProduct(rho_val); const auto norm = alphas.col(0).maxCoeff(); alphas.col(0) /= norm; alpha_log_norms(0) = log(norm); for (int n = 0; n < n_transitions; ++n) { alphas.col(n + 1) = omegas.col(n + 1).cwiseProduct(Gamma_val.transpose() * alphas.col(n)); const auto col_norm = alphas.col(n + 1).maxCoeff(); alphas.col(n + 1) /= col_norm; alpha_log_norms(n + 1) = log(col_norm) + alpha_log_norms(n); } } const auto log_marginal_density = log(alphas.col(n_transitions).sum()) + alpha_log_norms(n_transitions); // Variables required for all three Jacobian-adjoint products. const auto norm_norm = alpha_log_norms(n_transitions); const auto unnormed_marginal = alphas.col(n_transitions).sum(); std::vector<eig_vector_partial> kappa(n_transitions); eig_vector_partial kappa_log_norms(n_transitions); std::vector<T_partial_type> grad_corr(n_transitions, 0); if (n_transitions > 0) { kappa[n_transitions - 1] = Eigen::VectorXd::Ones(n_states); kappa_log_norms(n_transitions - 1) = 0; grad_corr[n_transitions - 1] = exp(alpha_log_norms(n_transitions - 1) - norm_norm); } for (int n = n_transitions - 2; n >= 0; --n) { kappa[n] = Gamma_val * (omegas.col(n + 2).cwiseProduct(kappa[n + 1])); const auto norm = kappa[n].maxCoeff(); kappa[n] /= norm; kappa_log_norms[n] = log(norm) + kappa_log_norms[n + 1]; grad_corr[n] = exp(alpha_log_norms[n] + kappa_log_norms[n] - norm_norm); } if (!is_constant_all<T_Gamma>::value) { eig_matrix_partial Gamma_jacad = Eigen::MatrixXd::Zero(n_states, n_states); for (int n = n_transitions - 1; n >= 0; --n) { Gamma_jacad += (grad_corr[n] * kappa[n].cwiseProduct(omegas.col(n + 1)) * alphas.col(n).transpose()) .transpose(); } Gamma_jacad /= unnormed_marginal; ops_partials.edge2_.partials_ = Gamma_jacad; } const bool sensitivities_for_omega_or_rho = (!is_constant_all<T_omega>::value) || (!is_constant_all<T_rho>::value); if (sensitivities_for_omega_or_rho) { eig_matrix_partial log_omega_jacad = Eigen::MatrixXd::Zero(n_states, n_transitions + 1); if (!is_constant_all<T_omega>::value) { for (int n = n_transitions - 1; n >= 0; --n) log_omega_jacad.col(n + 1) = grad_corr[n] * kappa[n].cwiseProduct(Gamma_val.transpose() * alphas.col(n)); } // Boundary terms if (n_transitions == 0) { if (!is_constant_all<T_omega>::value) { log_omega_jacad.col(0) = omegas.col(0).cwiseProduct(value_of(rho)) / exp(log_marginal_density); ops_partials.edge1_.partials_ = log_omega_jacad; } if (!is_constant_all<T_rho>::value) { ops_partials.edge3_.partials_ = omegas.col(0) / exp(log_marginal_density); } } else { const auto grad_corr_boundary = exp(kappa_log_norms(0) - norm_norm); eig_vector_partial C = Gamma_val * omegas.col(1).cwiseProduct(kappa[0]); if (!is_constant_all<T_omega>::value) { log_omega_jacad.col(0) = grad_corr_boundary * C.cwiseProduct(value_of(rho)); ops_partials.edge1_.partials_ = log_omega_jacad.cwiseProduct(omegas / unnormed_marginal); } if (!is_constant_all<T_rho>::value) { ops_partials.edge3_.partials_ = grad_corr_boundary * C.cwiseProduct(omegas.col(0)) / unnormed_marginal; } } } return ops_partials.build(log_marginal_density); } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>/* * The MIT License (MIT) * * Copyright (c) 2016 Julian Ganz * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef CMOH_ATTRIBUTE_BY_METHOD_HPP__ #define CMOH_ATTRIBUTE_BY_METHOD_HPP__ // std includes #include <type_traits> #include <utility> namespace cmoh { namespace accessors { namespace attribute { /** * Attribute accessor using methods * * This accessor provides read-only access to the attribute via methods of the * target C++ struct/class. It is constructed from an appropriate getter. * * Users are discouraged from constructing method accessors directly. Use * one of the `accessor()` overloads provided by the attribute instead. */ template < typename Attribute, ///< attribute type being accessed typename ObjType, ///< type of the class or struct with the attribute typename GetterVal ///< type of the value returned from the getter > struct by_method_const { typedef Attribute attribute; ///< type of attribute being accessed typedef ObjType object_type; ///< object being accessed typedef GetterVal(object_type::* getter)() const; static_assert( std::is_convertible<GetterVal, typename attribute::type>::value, "Value returned by getter is not convertible to attribute type" ); by_method_const(getter getter) : _getter(getter) {}; by_method_const(by_method_const const&) = default; by_method_const(by_method_const&&) = default; /** * Get the attribute from an object * * \returns the attribute's value */ typename attribute::type get( object_type const& obj ///< object from which to get the value ) const { return (obj.*_getter)(); } private: getter _getter; }; /** * Attribute accessor using methods * * This accessor provides access to the attribute via methods of the target * C++ struct/class. It is constructed from an appropriate getter and a setter. * * Users are discouraged from constructing method accessors directly. Use * one of the `accessor()` overloads provided by the attribute instead. */ template < typename Attribute, ///< attribute type being accessed typename ObjType, ///< type of the class or struct with the attribute typename GetterVal, ///< type of the value returned from the getter typename SetterArg ///< effective type of the setter argument > struct by_method : by_method_const<Attribute, ObjType, GetterVal> { typedef Attribute attribute; ///< type of attribute being accessed typedef ObjType object_type; ///< object being accessed typedef GetterVal(object_type::* getter)() const; typedef void(object_type::* setter)(SetterArg); static_assert( std::is_convertible<typename attribute::type, SetterArg>::value, "Attribute's type is not convertible to type required by setter" ); by_method(getter getter, setter setter) : by_method_const<Attribute, ObjType, GetterVal>(getter), _setter(setter) {}; by_method(by_method const&) = default; by_method(by_method&&) = default; /** * Set the attribute on an object */ void set( object_type& obj, ///< object on which to set the attribute typename attribute::type&& value ///< value to set ) const { (obj.*_setter)(std::forward<typename attribute::type>(value)); } private: setter _setter; }; // accessor factory overlaods for the `cmoh::accessor::attribute::by_method` template < typename Attribute, ///< attribute being accessed typename ObjType, ///< type of the class or struct with the attribute typename Value ///< type of the value in the concrete C++ type > constexpr typename std::enable_if< Attribute::is_const, by_method_const<Attribute, ObjType, Value> >::type make_accessor( typename by_method_const<Attribute, ObjType, Value>::getter getter ) { return by_method_const<Attribute, ObjType, Value>(getter); } template < typename Attribute, ///< attribute being accessed typename ObjType, ///< type of the class or struct with the attribute typename Value ///< type of the value in the concrete C++ type > constexpr typename std::enable_if< !Attribute::is_const, by_method<Attribute, ObjType, Value, Value> >::type make_accessor( typename by_method<Attribute, ObjType, Value, Value>::getter getter, typename by_method<Attribute, ObjType, Value, Value>::setter setter ) { return by_method<Attribute, ObjType, Value, Value>(getter, setter); } template < typename Attribute, ///< attribute being accessed typename ObjType, ///< type of the class or struct with the attribute typename Value ///< type of the value in the concrete C++ type > constexpr typename std::enable_if< !Attribute::is_const, by_method<Attribute, ObjType, Value, Value const&> >::type make_accessor( typename by_method<Attribute, ObjType, Value, Value const&>::getter getter, typename by_method<Attribute, ObjType, Value, Value const&>::setter setter ) { return by_method<Attribute, ObjType, Value, Value const&>(getter, setter); } template < typename Attribute, ///< attribute being accessed typename ObjType, ///< type of the class or struct with the attribute typename Value ///< type of the value in the concrete C++ type > constexpr typename std::enable_if< !Attribute::is_const, by_method<Attribute, ObjType, Value, Value&&> >::type make_accessor( typename by_method<Attribute, ObjType, Value, Value&&>::getter getter, typename by_method<Attribute, ObjType, Value, Value&&>::setter setter ) { return by_method<Attribute, ObjType, Value, Value&&>(getter, setter); } } } } #endif <commit_msg>Remove old accessor for accessing attributes by method<commit_after><|endoftext|>
<commit_before>#ifndef STAN_MATH_PRIM_SCAL_FUN_GRAD_INC_BETA_HPP #define STAN_MATH_PRIM_SCAL_FUN_GRAD_INC_BETA_HPP #include <stan/math/prim/scal/fun/lbeta.hpp> #include <stan/math/prim/scal/fun/log1m.hpp> #include <stan/math/prim/scal/fun/inc_beta.hpp> #include <stan/math/prim/scal/fun/grad_2F1.hpp> #include <cmath> namespace stan { namespace math { // Gradient of the incomplete beta function beta(a, b, z) // with respect to the first two arguments, using the // equivalence to a hypergeometric function. // See http://dlmf.nist.gov/8.17#ii inline void grad_inc_beta(double& g1, double& g2, double a, double b, double z) { using stan::math::lbeta; using stan::math::inc_beta; using stan::math::log1m; using stan::math::grad_2F1; using std::exp; using std::log; double c1 = log(z); double c2 = log1m(z); double c3 = exp(lbeta(a, b)) * inc_beta(a, b, z); double C = exp(a * c1 + b * c2) / a; double dF1 = 0; double dF2 = 0; if (C) grad_2F1(dF1, dF2, a + b, 1.0, a + 1, z); g1 = (c1 - 1.0 / a) * c3 + C * (dF1 + dF2); g2 = c2 * c3 + C * dF1; } } } #endif <commit_msg>Inline instantiated functions.<commit_after>#ifndef STAN_MATH_PRIM_SCAL_FUN_GRAD_INC_BETA_HPP #define STAN_MATH_PRIM_SCAL_FUN_GRAD_INC_BETA_HPP #include <stan/math/prim/scal/fun/lbeta.hpp> #include <stan/math/prim/scal/fun/log1m.hpp> #include <stan/math/prim/scal/fun/inc_beta.hpp> #include <stan/math/prim/scal/fun/grad_2F1.hpp> #include <cmath> namespace stan { namespace math { // Gradient of the incomplete beta function beta(a, b, z) // with respect to the first two arguments, using the // equivalence to a hypergeometric function. // See http://dlmf.nist.gov/8.17#ii inline void grad_inc_beta(double& g1, double& g2, double a, double b, double z) { using stan::math::lbeta; using stan::math::inc_beta; using stan::math::log1m; using stan::math::grad_2F1; using std::exp; using std::log; double c1 = log(z); double c2 = log1m(z); double c3 = exp(lbeta(a, b)) * inc_beta(a, b, z); double C = exp(a * c1 + b * c2) / a; double dF1 = 0; double dF2 = 0; if (C) grad_2F1(dF1, dF2, a + b, 1.0, a + 1, z); g1 = (c1 - 1.0 / a) * c3 + C * (dF1 + dF2); g2 = c2 * c3 + C * dF1; } } } #endif <|endoftext|>
<commit_before>/* * CUDArrays is a library for easy multi-GPU program development. * * The MIT License (MIT) * * Copyright (c) 2013-2015 Barcelona Supercomputing Center and * University of Illinois * * Developed by: Javier Cabezas <javier.cabezas@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #pragma once #ifndef CUDARRAYS_DETAIL_DYNARRAY_ITERATOR_HPP_ #define CUDARRAYS_DETAIL_DYNARRAY_ITERATOR_HPP_ #include <iterator> #include "../../compiler.hpp" #include "../../common.hpp" #include "../../utils.hpp" namespace cudarrays { template <typename Array, bool Const> struct array_iterator_traits { using difference_type = typename Array::difference_type; using value_type = typename Array::value_type; using reference = typename std::conditional<Const, const value_type &, value_type &>::type; using pointer = typename std::conditional<Const, const value_type *, value_type *>::type; }; template <typename ValueType, bool Const, typename DiffType = std::ptrdiff_t> struct iterator_traits { using value_type = ValueType; using difference_type = DiffType; using reference = typename std::conditional<Const, const value_type &, value_type &>::type; using pointer = typename std::conditional<Const, const value_type *, value_type *>::type; }; template <typename Array, bool Const, unsigned Current = Array::dimensions - 1> struct array_iterator_dereference { using array_reference = typename std::conditional<Const, const Array &, Array &>::type; using next_type = array_iterator_dereference<Array, Const, Current - 1>; template <typename... IdxType> static inline typename array_iterator_traits<Array, Const>::reference unwrap(array_reference array, const array_index_t cursor[Array::dimensions], IdxType... idxs) { return next_type::unwrap(array, cursor, cursor[Current], idxs...); } }; template <typename Array, bool Const> struct array_iterator_dereference<Array, Const, 0> { using array_reference = typename std::conditional<Const, const Array &, Array &>::type; template <typename... IdxType> static inline typename array_iterator_traits<Array, Const>::reference unwrap(array_reference array, const array_index_t cursor[Array::dimensions], IdxType... idxs) { return array(cursor[0], idxs...); } }; template <typename Array, bool Const> class array_iterator_access_detail { using traits_base = array_iterator_traits<Array, Const>; public: using difference_type = typename traits_base::difference_type; using value_type = typename traits_base::value_type; using reference = typename traits_base::reference; using pointer = typename traits_base::pointer; using array_reference = typename std::conditional<Const, const Array &, Array &>::type; using array_pointer = typename std::conditional<Const, const Array *, Array *>::type; using dereference_type = array_iterator_dereference<Array, Const>; inline reference operator*() const { return dereference_type::unwrap(*parent_, idx_); } inline pointer operator->() const { return &(operator*()); } protected: inline array_iterator_access_detail() : parent_(NULL) { fill(idx_, -1); } inline array_iterator_access_detail(array_reference parent) : parent_(&parent) { fill(idx_, 0); } inline array_iterator_access_detail(array_reference parent, array_index_t off[Array::dimensions]) : parent_(&parent) { std::copy(off, off + Array::dimensions, idx_); } template <bool Unit> void inc(array_index_t off) { for (int dim = Array::dimensions - 1; dim >= 0; --dim) { difference_type i = idx_[dim] + off; if (dim > 0 && i >= difference_type(parent_->dim(dim))) { // Next iteration will update dim - 1 if (Unit) { idx_[dim] = 0; off = 1; } else { idx_[dim] = i % difference_type(parent_->dim(dim)); off = i / difference_type(parent_->dim(dim)); } } else { // No overflow, we are done idx_[dim] = i; break; } } for (auto dim : utils::make_range(Array::dimensions)) { printf("%u ", idx_[dim]); } printf("\n"); } template <bool Unit> void dec(array_index_t off) { for (int dim = Array::dimensions - 1; dim >= 0; --dim) { difference_type i = idx_[dim] - off; if (dim > 0 && i < 0) { // Next iteration will update dim - 1 if (Unit) { idx_[dim] = difference_type(parent_->dim(dim)) - 1; off = 1; } else { idx_[dim] = difference_type(parent_->dim(dim)) - (i % difference_type(parent_->dim(dim))); off = i / difference_type(parent_->dim(dim)); } } else { // No underflow, we are done idx_[dim] = i; break; } } } inline bool less_than(const array_iterator_access_detail &it) const { return less<false>(it); } inline bool less_eq_than(const array_iterator_access_detail &it) const { return less<true>(it); } inline bool greater_than(const array_iterator_access_detail &it) const { return greater<false>(it); } inline bool greater_eq_than(const array_iterator_access_detail &it) const { return greater<true>(it); } difference_type subtract(const array_iterator_access_detail &it) const { // TODO: optimize difference_type ret = 0; difference_type inc = 1; for (int dim = Array::dimensions - 1; dim >= 0; --dim) { ret += (idx_[dim] - it.idx_[dim]) * inc; inc *= difference_type(parent_->dim(dim)); } return ret; } array_pointer parent_; array_index_t idx_[Array::dimensions]; private: template <bool Equal> bool less(const array_iterator_access_detail &it) const { for (auto dim : utils::make_range(Array::dimensions)) { if (idx_[dim] > it.idx_[dim]) { return false; } else if (idx_[dim] < it.idx_[dim]) { return true; } // If equal, keep comparing } return Equal; } template <bool Equal> inline bool greater(const array_iterator_access_detail &it) const { for (auto dim : utils::make_range(Array::dimensions)) { if (idx_[dim] < it.idx_[dim]) { return false; } else if (idx_[dim] > it.idx_[dim]) { return true; } // If equal, keep comparing } return Equal; } CUDARRAYS_TESTED(iterator_test, iterator1d) CUDARRAYS_TESTED(iterator_test, iterator2d) }; template <typename Array, bool Const> class array_iterator : public array_iterator_access_detail<Array, Const> { using parent_type = array_iterator_access_detail<Array, Const>; public: using array_reference = typename parent_type::array_reference; using iterator_traits_base = array_iterator_traits<Array, Const>; using difference_type = typename iterator_traits_base::difference_type; using value_type = typename iterator_traits_base::value_type; using reference = typename iterator_traits_base::reference; using pointer = typename iterator_traits_base::pointer; using iterator_category = std::random_access_iterator_tag; static constexpr bool is_const = Const; inline array_iterator(array_reference parent) : parent_type(parent) { } inline array_iterator(array_reference parent, array_index_t off[Array::dimensions]) : parent_type(parent, off) { } inline bool operator==(array_iterator it) const { return parent_type::parent_ == it.parent_ && utils::equal(parent_type::idx_, it.idx_); } inline bool operator!=(array_iterator it) const { return !(*this == it); } inline array_iterator &operator++() { parent_type::template inc<true>(1); return *this; } inline array_iterator operator++(int) { array_iterator res(*this); ++(*this); return res; } inline array_iterator &operator--() { parent_type::template dec<true>(1); return *this; } inline array_iterator operator--(int) { array_iterator res(*this); --(*this); return res; } inline array_iterator &operator+=(difference_type off) { parent_type::template inc<false>(off); return *this; } inline array_iterator &operator-=(difference_type off) { parent_type::template dec<false>(off); return *this; } inline array_iterator operator+(difference_type inc) const { array_iterator res(*this); res += inc; return res; } inline array_iterator operator-(difference_type dec) const { array_iterator res(*this); res -= dec; return res; } inline difference_type operator-(const array_iterator &i) const { return parent_type::subtract(i); } inline bool operator<(const array_iterator &i) const { return parent_type::less_than(i); } inline bool operator<=(const array_iterator &i) const { return parent_type::less_eq_than(i); } inline bool operator>(const array_iterator &i) const { return parent_type::greater_than(i); } inline bool operator>=(const array_iterator &i) const { return parent_type::greater_eq_than(i); } inline value_type &operator[](difference_type i) { return *((*this) + i); } }; template <typename T, bool Const> class array_iterator_facade { public: static constexpr bool is_const = Const; using iterator_type = array_iterator<T, Const>; using array_reference = typename iterator_type::array_reference; using array_type = T; // // Iterator interface // using iterator = array_iterator<array_type, false>; using const_iterator = array_iterator<array_type, true>; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; array_iterator_facade(array_reference a) : parent_{a} { } iterator begin() { array_index_t dims[array_type::dimensions]; std::fill(dims, dims + array_type::dimensions, 0); return iterator{parent_, dims}; } const_iterator begin() const { return cbegin(); } const_iterator cbegin() const { array_index_t dims[array_type::dimensions]; std::fill(dims, dims + array_type::dimensions, 0); return const_iterator{parent_, dims}; } reverse_iterator rbegin() { array_index_t dims[array_type::dimensions]; for (unsigned i = 0; i < array_type::dimensions; ++i) { dims[i] = parent_.dim(i) - 1; } return reverse_iterator(iterator(parent_, dims)); } iterator end() { array_index_t dims[array_type::dimensions]; dims[0] = parent_.dim(0); if (array_type::dimensions > 1) { std::fill(dims + 1, dims + array_type::dimensions, 0); } return iterator(parent_, dims); } const_iterator end() const { return cend(); } const_iterator cend() const { array_index_t dims[array_type::dimensions]; dims[0] = parent_.dim(0); if (array_type::dimensions > 1) { std::fill(dims + 1, dims + array_type::dimensions, 0); } return const_iterator(parent_, dims); } reverse_iterator rend() { array_index_t dims[array_type::dimensions]; dims[0] = -1; for (unsigned i = 0; i < array_type::dimensions; ++i) { dims[i] = parent_.dim(i) - 1; } return reverse_iterator(iterator(parent_, dims)); } const_reverse_iterator rend() const { return crend(); } const_reverse_iterator crend() const { array_index_t dims[array_type::dimensions]; dims[0] = -1; for (unsigned i = 0; i < array_type::dimensions; ++i) { dims[i] = parent_.dim(i) - 1; } return const_reverse_iterator(const_iterator(parent_, dims)); } private: array_reference parent_; }; } #endif // CUDARRAYS_ITERATOR_HPP_ /* vim:set ft=cpp backspace=2 tabstop=4 shiftwidth=4 textwidth=120 foldmethod=marker expandtab: */ <commit_msg>Remove unnecessary printf in value_iterator<commit_after>/* * CUDArrays is a library for easy multi-GPU program development. * * The MIT License (MIT) * * Copyright (c) 2013-2015 Barcelona Supercomputing Center and * University of Illinois * * Developed by: Javier Cabezas <javier.cabezas@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #pragma once #ifndef CUDARRAYS_DETAIL_DYNARRAY_ITERATOR_HPP_ #define CUDARRAYS_DETAIL_DYNARRAY_ITERATOR_HPP_ #include <iterator> #include "../../compiler.hpp" #include "../../common.hpp" #include "../../utils.hpp" namespace cudarrays { template <typename Array, bool Const> struct array_iterator_traits { using difference_type = typename Array::difference_type; using value_type = typename Array::value_type; using reference = typename std::conditional<Const, const value_type &, value_type &>::type; using pointer = typename std::conditional<Const, const value_type *, value_type *>::type; }; template <typename ValueType, bool Const, typename DiffType = std::ptrdiff_t> struct iterator_traits { using value_type = ValueType; using difference_type = DiffType; using reference = typename std::conditional<Const, const value_type &, value_type &>::type; using pointer = typename std::conditional<Const, const value_type *, value_type *>::type; }; template <typename Array, bool Const, unsigned Current = Array::dimensions - 1> struct array_iterator_dereference { using array_reference = typename std::conditional<Const, const Array &, Array &>::type; using next_type = array_iterator_dereference<Array, Const, Current - 1>; template <typename... IdxType> static inline typename array_iterator_traits<Array, Const>::reference unwrap(array_reference array, const array_index_t cursor[Array::dimensions], IdxType... idxs) { return next_type::unwrap(array, cursor, cursor[Current], idxs...); } }; template <typename Array, bool Const> struct array_iterator_dereference<Array, Const, 0> { using array_reference = typename std::conditional<Const, const Array &, Array &>::type; template <typename... IdxType> static inline typename array_iterator_traits<Array, Const>::reference unwrap(array_reference array, const array_index_t cursor[Array::dimensions], IdxType... idxs) { return array(cursor[0], idxs...); } }; template <typename Array, bool Const> class array_iterator_access_detail { using traits_base = array_iterator_traits<Array, Const>; public: using difference_type = typename traits_base::difference_type; using value_type = typename traits_base::value_type; using reference = typename traits_base::reference; using pointer = typename traits_base::pointer; using array_reference = typename std::conditional<Const, const Array &, Array &>::type; using array_pointer = typename std::conditional<Const, const Array *, Array *>::type; using dereference_type = array_iterator_dereference<Array, Const>; inline reference operator*() const { return dereference_type::unwrap(*parent_, idx_); } inline pointer operator->() const { return &(operator*()); } protected: inline array_iterator_access_detail() : parent_(NULL) { fill(idx_, -1); } inline array_iterator_access_detail(array_reference parent) : parent_(&parent) { fill(idx_, 0); } inline array_iterator_access_detail(array_reference parent, array_index_t off[Array::dimensions]) : parent_(&parent) { std::copy(off, off + Array::dimensions, idx_); } template <bool Unit> void inc(array_index_t off) { for (int dim = Array::dimensions - 1; dim >= 0; --dim) { difference_type i = idx_[dim] + off; if (dim > 0 && i >= difference_type(parent_->dim(dim))) { // Next iteration will update dim - 1 if (Unit) { idx_[dim] = 0; off = 1; } else { idx_[dim] = i % difference_type(parent_->dim(dim)); off = i / difference_type(parent_->dim(dim)); } } else { // No overflow, we are done idx_[dim] = i; break; } } } template <bool Unit> void dec(array_index_t off) { for (int dim = Array::dimensions - 1; dim >= 0; --dim) { difference_type i = idx_[dim] - off; if (dim > 0 && i < 0) { // Next iteration will update dim - 1 if (Unit) { idx_[dim] = difference_type(parent_->dim(dim)) - 1; off = 1; } else { idx_[dim] = difference_type(parent_->dim(dim)) - (i % difference_type(parent_->dim(dim))); off = i / difference_type(parent_->dim(dim)); } } else { // No underflow, we are done idx_[dim] = i; break; } } } inline bool less_than(const array_iterator_access_detail &it) const { return less<false>(it); } inline bool less_eq_than(const array_iterator_access_detail &it) const { return less<true>(it); } inline bool greater_than(const array_iterator_access_detail &it) const { return greater<false>(it); } inline bool greater_eq_than(const array_iterator_access_detail &it) const { return greater<true>(it); } difference_type subtract(const array_iterator_access_detail &it) const { // TODO: optimize difference_type ret = 0; difference_type inc = 1; for (int dim = Array::dimensions - 1; dim >= 0; --dim) { ret += (idx_[dim] - it.idx_[dim]) * inc; inc *= difference_type(parent_->dim(dim)); } return ret; } array_pointer parent_; array_index_t idx_[Array::dimensions]; private: template <bool Equal> bool less(const array_iterator_access_detail &it) const { for (auto dim : utils::make_range(Array::dimensions)) { if (idx_[dim] > it.idx_[dim]) { return false; } else if (idx_[dim] < it.idx_[dim]) { return true; } // If equal, keep comparing } return Equal; } template <bool Equal> inline bool greater(const array_iterator_access_detail &it) const { for (auto dim : utils::make_range(Array::dimensions)) { if (idx_[dim] < it.idx_[dim]) { return false; } else if (idx_[dim] > it.idx_[dim]) { return true; } // If equal, keep comparing } return Equal; } CUDARRAYS_TESTED(iterator_test, iterator1d) CUDARRAYS_TESTED(iterator_test, iterator2d) }; template <typename Array, bool Const> class array_iterator : public array_iterator_access_detail<Array, Const> { using parent_type = array_iterator_access_detail<Array, Const>; public: using array_reference = typename parent_type::array_reference; using iterator_traits_base = array_iterator_traits<Array, Const>; using difference_type = typename iterator_traits_base::difference_type; using value_type = typename iterator_traits_base::value_type; using reference = typename iterator_traits_base::reference; using pointer = typename iterator_traits_base::pointer; using iterator_category = std::random_access_iterator_tag; static constexpr bool is_const = Const; inline array_iterator(array_reference parent) : parent_type(parent) { } inline array_iterator(array_reference parent, array_index_t off[Array::dimensions]) : parent_type(parent, off) { } inline bool operator==(array_iterator it) const { return parent_type::parent_ == it.parent_ && utils::equal(parent_type::idx_, it.idx_); } inline bool operator!=(array_iterator it) const { return !(*this == it); } inline array_iterator &operator++() { parent_type::template inc<true>(1); return *this; } inline array_iterator operator++(int) { array_iterator res(*this); ++(*this); return res; } inline array_iterator &operator--() { parent_type::template dec<true>(1); return *this; } inline array_iterator operator--(int) { array_iterator res(*this); --(*this); return res; } inline array_iterator &operator+=(difference_type off) { parent_type::template inc<false>(off); return *this; } inline array_iterator &operator-=(difference_type off) { parent_type::template dec<false>(off); return *this; } inline array_iterator operator+(difference_type inc) const { array_iterator res(*this); res += inc; return res; } inline array_iterator operator-(difference_type dec) const { array_iterator res(*this); res -= dec; return res; } inline difference_type operator-(const array_iterator &i) const { return parent_type::subtract(i); } inline bool operator<(const array_iterator &i) const { return parent_type::less_than(i); } inline bool operator<=(const array_iterator &i) const { return parent_type::less_eq_than(i); } inline bool operator>(const array_iterator &i) const { return parent_type::greater_than(i); } inline bool operator>=(const array_iterator &i) const { return parent_type::greater_eq_than(i); } inline value_type &operator[](difference_type i) { return *((*this) + i); } }; template <typename T, bool Const> class array_iterator_facade { public: static constexpr bool is_const = Const; using iterator_type = array_iterator<T, Const>; using array_reference = typename iterator_type::array_reference; using array_type = T; // // Iterator interface // using iterator = array_iterator<array_type, false>; using const_iterator = array_iterator<array_type, true>; using reverse_iterator = std::reverse_iterator<iterator>; using const_reverse_iterator = std::reverse_iterator<const_iterator>; array_iterator_facade(array_reference a) : parent_{a} { } iterator begin() { array_index_t dims[array_type::dimensions]; std::fill(dims, dims + array_type::dimensions, 0); return iterator{parent_, dims}; } const_iterator begin() const { return cbegin(); } const_iterator cbegin() const { array_index_t dims[array_type::dimensions]; std::fill(dims, dims + array_type::dimensions, 0); return const_iterator{parent_, dims}; } reverse_iterator rbegin() { array_index_t dims[array_type::dimensions]; for (unsigned i = 0; i < array_type::dimensions; ++i) { dims[i] = parent_.dim(i) - 1; } return reverse_iterator(iterator(parent_, dims)); } iterator end() { array_index_t dims[array_type::dimensions]; dims[0] = parent_.dim(0); if (array_type::dimensions > 1) { std::fill(dims + 1, dims + array_type::dimensions, 0); } return iterator(parent_, dims); } const_iterator end() const { return cend(); } const_iterator cend() const { array_index_t dims[array_type::dimensions]; dims[0] = parent_.dim(0); if (array_type::dimensions > 1) { std::fill(dims + 1, dims + array_type::dimensions, 0); } return const_iterator(parent_, dims); } reverse_iterator rend() { array_index_t dims[array_type::dimensions]; dims[0] = -1; for (unsigned i = 0; i < array_type::dimensions; ++i) { dims[i] = parent_.dim(i) - 1; } return reverse_iterator(iterator(parent_, dims)); } const_reverse_iterator rend() const { return crend(); } const_reverse_iterator crend() const { array_index_t dims[array_type::dimensions]; dims[0] = -1; for (unsigned i = 0; i < array_type::dimensions; ++i) { dims[i] = parent_.dim(i) - 1; } return const_reverse_iterator(const_iterator(parent_, dims)); } private: array_reference parent_; }; } #endif // CUDARRAYS_ITERATOR_HPP_ /* vim:set ft=cpp backspace=2 tabstop=4 shiftwidth=4 textwidth=120 foldmethod=marker expandtab: */ <|endoftext|>
<commit_before>#ifndef STAN_MATH_REV_MAT_FUN_GP_EXP_QUAD_COV_HPP #define STAN_MATH_REV_MAT_FUN_GP_EXP_QUAD_COV_HPP #include <boost/math/tools/promotion.hpp> #include <boost/type_traits.hpp> #include <boost/utility/enable_if.hpp> #include <cmath> #include <stan/math/prim/mat/fun/Eigen.hpp> #include <stan/math/prim/scal/err/check_not_nan.hpp> #include <stan/math/prim/scal/err/check_positive.hpp> #include <stan/math/prim/scal/fun/exp.hpp> #include <stan/math/prim/scal/fun/square.hpp> #include <stan/math/prim/scal/fun/squared_distance.hpp> #include <stan/math/prim/scal/meta/scalar_type.hpp> #include <stan/math/rev/core.hpp> #include <stan/math/rev/scal/fun/value_of.hpp> #include <vector> namespace stan { namespace math { /** * This is a subclass of the vari class for precomputed * gradients of gp_exp_quad_cov. * * The class stores the double values for the distance * matrix, pointers to the varis for the covariance * matrix, along with a pointer to the vari for sigma, * and the vari for length_scale. * * @tparam T_x type of std::vector of elements * @tparam T_sigma type of sigma * @tparam T_l type of length scale */ template <typename T_x, typename T_sigma, typename T_l> class gp_exp_quad_cov_vari : public vari { public: const size_t size_; const size_t size_ltri_; const double l_d_; const double sigma_d_; const double sigma_sq_d_; double *dist_; vari *l_vari_; vari *sigma_vari_; vari **cov_lower_; vari **cov_diag_; /** * Constructor for gp_exp_quad_cov. * * All memory allocated in * ChainableStack's stack_alloc arena. * * It is critical for the efficiency of this object * that the constructor create new varis that aren't * popped onto the var_stack_, but rather are * popped onto the var_nochain_stack_. This is * controlled to the second argument to * vari's constructor. * * @param x std::vector input that can be used in square distance * Assumes each element of x is the same size * @param sigma standard deviation * @param length_scale length scale */ gp_exp_quad_cov_vari(const std::vector<T_x> &x, const T_sigma &sigma, const T_l &length_scale) : vari(0.0), size_(x.size()), size_ltri_(size_ * (size_ - 1) / 2), l_d_(value_of(length_scale)), sigma_d_(value_of(sigma)), sigma_sq_d_(sigma_d_ * sigma_d_), dist_(ChainableStack::memalloc_.alloc_array<double>(size_ltri_)), l_vari_(length_scale.vi_), sigma_vari_(sigma.vi_), cov_lower_(ChainableStack::memalloc_.alloc_array<vari *>(size_ltri_)), cov_diag_(ChainableStack::memalloc_.alloc_array<vari *>(size_)) { double inv_half_sq_l_d = 0.5 / (l_d_ * l_d_); size_t pos = 0; for (size_t j = 0; j < size_ - 1; ++j) { for (size_t i = j + 1; i < size_; ++i) { double dist_sq = squared_distance(x[i], x[j]); dist_[pos] = dist_sq; cov_lower_[pos] = new vari( sigma_sq_d_ * std::exp(-dist_sq * inv_half_sq_l_d), false); ++pos; } } for (size_t i = 0; i < size_; ++i) cov_diag_[i] = new vari(sigma_sq_d_, false); } virtual void chain() { double adjl = 0; double adjsigma = 0; for (size_t i = 0; i < size_ltri_; ++i) { vari *el_low = cov_lower_[i]; double prod_add = el_low->adj_ * el_low->val_; adjl += prod_add * dist_[i]; adjsigma += prod_add; } for (size_t i = 0; i < size_; ++i) { vari *el = cov_diag_[i]; adjsigma += el->adj_ * el->val_; } l_vari_->adj_ += adjl / (l_d_ * l_d_ * l_d_); sigma_vari_->adj_ += adjsigma * 2 / sigma_d_; } }; /** * This is a subclass of the vari class for precomputed * gradients of gp_exp_quad_cov. * * The class stores the double values for the distance * matrix, pointers to the varis for the covariance * matrix, along with a pointer to the vari for sigma, * and the vari for length_scale. * * @tparam T_x type of std::vector of elements * @tparam T_l type of length scale */ template <typename T_x, typename T_l> class gp_exp_quad_cov_vari<T_x, double, T_l> : public vari { public: const size_t size_; const size_t size_ltri_; const double l_d_; const double sigma_d_; const double sigma_sq_d_; double *dist_; vari *l_vari_; vari **cov_lower_; vari **cov_diag_; /** * Constructor for gp_exp_quad_cov. * * All memory allocated in * ChainableStack's stack_alloc arena. * * It is critical for the efficiency of this object * that the constructor create new varis that aren't * popped onto the var_stack_, but rather are * popped onto the var_nochain_stack_. This is * controlled to the second argument to * vari's constructor. * * @param x std::vector input that can be used in square distance * Assumes each element of x is the same size * @param sigma standard deviation * @param length_scale length scale */ gp_exp_quad_cov_vari(const std::vector<T_x> &x, double sigma, const T_l &length_scale) : vari(0.0), size_(x.size()), size_ltri_(size_ * (size_ - 1) / 2), l_d_(value_of(length_scale)), sigma_d_(value_of(sigma)), sigma_sq_d_(sigma_d_ * sigma_d_), dist_(ChainableStack::memalloc_.alloc_array<double>(size_ltri_)), l_vari_(length_scale.vi_), cov_lower_(ChainableStack::memalloc_.alloc_array<vari *>(size_ltri_)), cov_diag_(ChainableStack::memalloc_.alloc_array<vari *>(size_)) { double inv_half_sq_l_d = 0.5 / (l_d_ * l_d_); size_t pos = 0; for (size_t j = 0; j < size_ - 1; ++j) { for (size_t i = j + 1; i < size_; ++i) { double dist_sq = squared_distance(x[i], x[j]); dist_[pos] = dist_sq; cov_lower_[pos] = new vari( sigma_sq_d_ * std::exp(-dist_sq * inv_half_sq_l_d), false); ++pos; } } for (size_t i = 0; i < size_; ++i) cov_diag_[i] = new vari(sigma_sq_d_, false); } virtual void chain() { double adjl = 0; for (size_t i = 0; i < size_ltri_; ++i) { vari *el_low = cov_lower_[i]; adjl += el_low->adj_ * el_low->val_ * dist_[i]; } l_vari_->adj_ += adjl / (l_d_ * l_d_ * l_d_); } }; /** * Returns a squared exponential kernel. * * @param x std::vector input that can be used in square distance * Assumes each element of x is the same size * @param sigma standard deviation * @param length_scale length scale * @return squared distance * @throw std::domain_error if sigma <= 0, l <= 0, or * x is nan or infinite */ template <typename T_x> inline typename boost::enable_if_c< boost::is_same<typename scalar_type<T_x>::type, double>::value, Eigen::Matrix<var, -1, -1>>::type gp_exp_quad_cov(const std::vector<T_x> &x, const var &sigma, const var &length_scale) { check_positive("gp_exp_quad_cov", "sigma", sigma); check_positive("gp_exp_quad_cov", "length_scale", length_scale); size_t x_size = x.size(); for (size_t i = 0; i < x_size; ++i) check_not_nan("gp_exp_quad_cov", "x", x[i]); Eigen::Matrix<var, -1, -1> cov(x_size, x_size); if (x_size == 0) return cov; gp_exp_quad_cov_vari<T_x, var, var> *baseVari = new gp_exp_quad_cov_vari<T_x, var, var>(x, sigma, length_scale); size_t pos = 0; for (size_t j = 0; j < x_size - 1; ++j) { for (size_t i = (j + 1); i < x_size; ++i) { cov.coeffRef(i, j).vi_ = baseVari->cov_lower_[pos]; cov.coeffRef(j, i).vi_ = cov.coeffRef(i, j).vi_; ++pos; } cov.coeffRef(j, j).vi_ = baseVari->cov_diag_[j]; } cov.coeffRef(x_size - 1, x_size - 1).vi_ = baseVari->cov_diag_[x_size - 1]; return cov; } /** * Returns a squared exponential kernel. * * @param x std::vector input that can be used in square distance * Assumes each element of x is the same size * @param sigma standard deviation * @param length_scale length scale * @return squared distance * @throw std::domain_error if sigma <= 0, l <= 0, or * x is nan or infinite */ template <typename T_x> inline typename boost::enable_if_c< boost::is_same<typename scalar_type<T_x>::type, double>::value, Eigen::Matrix<var, -1, -1>>::type gp_exp_quad_cov(const std::vector<T_x> &x, double sigma, const var &length_scale) { check_positive("gp_exp_quad_cov", "marginal variance", sigma); check_positive("gp_exp_quad_cov", "length-scale", length_scale); size_t x_size = x.size(); for (size_t i = 0; i < x_size; ++i) check_not_nan("gp_exp_quad_cov", "x", x[i]); Eigen::Matrix<var, -1, -1> cov(x_size, x_size); if (x_size == 0) return cov; gp_exp_quad_cov_vari<T_x, double, var> *baseVari = new gp_exp_quad_cov_vari<T_x, double, var>(x, sigma, length_scale); size_t pos = 0; for (size_t j = 0; j < x_size - 1; ++j) { for (size_t i = (j + 1); i < x_size; ++i) { cov.coeffRef(i, j).vi_ = baseVari->cov_lower_[pos]; cov.coeffRef(j, i).vi_ = cov.coeffRef(i, j).vi_; ++pos; } cov.coeffRef(j, j).vi_ = baseVari->cov_diag_[j]; } cov.coeffRef(x_size - 1, x_size - 1).vi_ = baseVari->cov_diag_[x_size - 1]; return cov; } } // namespace math } // namespace stan #endif <commit_msg>change order of includes<commit_after>#ifndef STAN_MATH_REV_MAT_FUN_GP_EXP_QUAD_COV_HPP #define STAN_MATH_REV_MAT_FUN_GP_EXP_QUAD_COV_HPP #include <boost/math/tools/promotion.hpp> #include <boost/type_traits.hpp> #include <boost/utility/enable_if.hpp> #include <stan/math/prim/mat/fun/Eigen.hpp> #include <stan/math/prim/scal/err/check_not_nan.hpp> #include <stan/math/prim/scal/err/check_positive.hpp> #include <stan/math/prim/scal/fun/exp.hpp> #include <stan/math/prim/scal/fun/square.hpp> #include <stan/math/prim/scal/fun/squared_distance.hpp> #include <stan/math/prim/scal/meta/scalar_type.hpp> #include <stan/math/rev/core.hpp> #include <stan/math/rev/scal/fun/value_of.hpp> #include <vector> #include <cmath> namespace stan { namespace math { /** * This is a subclass of the vari class for precomputed * gradients of gp_exp_quad_cov. * * The class stores the double values for the distance * matrix, pointers to the varis for the covariance * matrix, along with a pointer to the vari for sigma, * and the vari for length_scale. * * @tparam T_x type of std::vector of elements * @tparam T_sigma type of sigma * @tparam T_l type of length scale */ template <typename T_x, typename T_sigma, typename T_l> class gp_exp_quad_cov_vari : public vari { public: const size_t size_; const size_t size_ltri_; const double l_d_; const double sigma_d_; const double sigma_sq_d_; double *dist_; vari *l_vari_; vari *sigma_vari_; vari **cov_lower_; vari **cov_diag_; /** * Constructor for gp_exp_quad_cov. * * All memory allocated in * ChainableStack's stack_alloc arena. * * It is critical for the efficiency of this object * that the constructor create new varis that aren't * popped onto the var_stack_, but rather are * popped onto the var_nochain_stack_. This is * controlled to the second argument to * vari's constructor. * * @param x std::vector input that can be used in square distance * Assumes each element of x is the same size * @param sigma standard deviation * @param length_scale length scale */ gp_exp_quad_cov_vari(const std::vector<T_x> &x, const T_sigma &sigma, const T_l &length_scale) : vari(0.0), size_(x.size()), size_ltri_(size_ * (size_ - 1) / 2), l_d_(value_of(length_scale)), sigma_d_(value_of(sigma)), sigma_sq_d_(sigma_d_ * sigma_d_), dist_(ChainableStack::memalloc_.alloc_array<double>(size_ltri_)), l_vari_(length_scale.vi_), sigma_vari_(sigma.vi_), cov_lower_(ChainableStack::memalloc_.alloc_array<vari *>(size_ltri_)), cov_diag_(ChainableStack::memalloc_.alloc_array<vari *>(size_)) { double inv_half_sq_l_d = 0.5 / (l_d_ * l_d_); size_t pos = 0; for (size_t j = 0; j < size_ - 1; ++j) { for (size_t i = j + 1; i < size_; ++i) { double dist_sq = squared_distance(x[i], x[j]); dist_[pos] = dist_sq; cov_lower_[pos] = new vari(sigma_sq_d_ * std::exp(-dist_sq * inv_half_sq_l_d), false); ++pos; } } for (size_t i = 0; i < size_; ++i) cov_diag_[i] = new vari(sigma_sq_d_, false); } virtual void chain() { double adjl = 0; double adjsigma = 0; for (size_t i = 0; i < size_ltri_; ++i) { vari *el_low = cov_lower_[i]; double prod_add = el_low->adj_ * el_low->val_; adjl += prod_add * dist_[i]; adjsigma += prod_add; } for (size_t i = 0; i < size_; ++i) { vari *el = cov_diag_[i]; adjsigma += el->adj_ * el->val_; } l_vari_->adj_ += adjl / (l_d_ * l_d_ * l_d_); sigma_vari_->adj_ += adjsigma * 2 / sigma_d_; } }; /** * This is a subclass of the vari class for precomputed * gradients of gp_exp_quad_cov. * * The class stores the double values for the distance * matrix, pointers to the varis for the covariance * matrix, along with a pointer to the vari for sigma, * and the vari for length_scale. * * @tparam T_x type of std::vector of elements * @tparam T_l type of length scale */ template <typename T_x, typename T_l> class gp_exp_quad_cov_vari<T_x, double, T_l> : public vari { public: const size_t size_; const size_t size_ltri_; const double l_d_; const double sigma_d_; const double sigma_sq_d_; double *dist_; vari *l_vari_; vari **cov_lower_; vari **cov_diag_; /** * Constructor for gp_exp_quad_cov. * * All memory allocated in * ChainableStack's stack_alloc arena. * * It is critical for the efficiency of this object * that the constructor create new varis that aren't * popped onto the var_stack_, but rather are * popped onto the var_nochain_stack_. This is * controlled to the second argument to * vari's constructor. * * @param x std::vector input that can be used in square distance * Assumes each element of x is the same size * @param sigma standard deviation * @param length_scale length scale */ gp_exp_quad_cov_vari(const std::vector<T_x> &x, double sigma, const T_l &length_scale) : vari(0.0), size_(x.size()), size_ltri_(size_ * (size_ - 1) / 2), l_d_(value_of(length_scale)), sigma_d_(value_of(sigma)), sigma_sq_d_(sigma_d_ * sigma_d_), dist_(ChainableStack::memalloc_.alloc_array<double>(size_ltri_)), l_vari_(length_scale.vi_), cov_lower_(ChainableStack::memalloc_.alloc_array<vari *>(size_ltri_)), cov_diag_(ChainableStack::memalloc_.alloc_array<vari *>(size_)) { double inv_half_sq_l_d = 0.5 / (l_d_ * l_d_); size_t pos = 0; for (size_t j = 0; j < size_ - 1; ++j) { for (size_t i = j + 1; i < size_; ++i) { double dist_sq = squared_distance(x[i], x[j]); dist_[pos] = dist_sq; cov_lower_[pos] = new vari(sigma_sq_d_ * std::exp(-dist_sq * inv_half_sq_l_d), false); ++pos; } } for (size_t i = 0; i < size_; ++i) cov_diag_[i] = new vari(sigma_sq_d_, false); } virtual void chain() { double adjl = 0; for (size_t i = 0; i < size_ltri_; ++i) { vari *el_low = cov_lower_[i]; adjl += el_low->adj_ * el_low->val_ * dist_[i]; } l_vari_->adj_ += adjl / (l_d_ * l_d_ * l_d_); } }; /** * Returns a squared exponential kernel. * * @param x std::vector input that can be used in square distance * Assumes each element of x is the same size * @param sigma standard deviation * @param length_scale length scale * @return squared distance * @throw std::domain_error if sigma <= 0, l <= 0, or * x is nan or infinite */ template <typename T_x> inline typename boost::enable_if_c< boost::is_same<typename scalar_type<T_x>::type, double>::value, Eigen::Matrix<var, -1, -1>>::type gp_exp_quad_cov(const std::vector<T_x> &x, const var &sigma, const var &length_scale) { check_positive("gp_exp_quad_cov", "sigma", sigma); check_positive("gp_exp_quad_cov", "length_scale", length_scale); size_t x_size = x.size(); for (size_t i = 0; i < x_size; ++i) check_not_nan("gp_exp_quad_cov", "x", x[i]); Eigen::Matrix<var, -1, -1> cov(x_size, x_size); if (x_size == 0) return cov; gp_exp_quad_cov_vari<T_x, var, var> *baseVari = new gp_exp_quad_cov_vari<T_x, var, var>(x, sigma, length_scale); size_t pos = 0; for (size_t j = 0; j < x_size - 1; ++j) { for (size_t i = (j + 1); i < x_size; ++i) { cov.coeffRef(i, j).vi_ = baseVari->cov_lower_[pos]; cov.coeffRef(j, i).vi_ = cov.coeffRef(i, j).vi_; ++pos; } cov.coeffRef(j, j).vi_ = baseVari->cov_diag_[j]; } cov.coeffRef(x_size - 1, x_size - 1).vi_ = baseVari->cov_diag_[x_size - 1]; return cov; } /** * Returns a squared exponential kernel. * * @param x std::vector input that can be used in square distance * Assumes each element of x is the same size * @param sigma standard deviation * @param length_scale length scale * @return squared distance * @throw std::domain_error if sigma <= 0, l <= 0, or * x is nan or infinite */ template <typename T_x> inline typename boost::enable_if_c< boost::is_same<typename scalar_type<T_x>::type, double>::value, Eigen::Matrix<var, -1, -1>>::type gp_exp_quad_cov(const std::vector<T_x> &x, double sigma, const var &length_scale) { check_positive("gp_exp_quad_cov", "marginal variance", sigma); check_positive("gp_exp_quad_cov", "length-scale", length_scale); size_t x_size = x.size(); for (size_t i = 0; i < x_size; ++i) check_not_nan("gp_exp_quad_cov", "x", x[i]); Eigen::Matrix<var, -1, -1> cov(x_size, x_size); if (x_size == 0) return cov; gp_exp_quad_cov_vari<T_x, double, var> *baseVari = new gp_exp_quad_cov_vari<T_x, double, var>(x, sigma, length_scale); size_t pos = 0; for (size_t j = 0; j < x_size - 1; ++j) { for (size_t i = (j + 1); i < x_size; ++i) { cov.coeffRef(i, j).vi_ = baseVari->cov_lower_[pos]; cov.coeffRef(j, i).vi_ = cov.coeffRef(i, j).vi_; ++pos; } cov.coeffRef(j, j).vi_ = baseVari->cov_diag_[j]; } cov.coeffRef(x_size - 1, x_size - 1).vi_ = baseVari->cov_diag_[x_size - 1]; return cov; } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>// This file is distributed under the MIT license. // See the LICENSE file for details. #include <cstddef> #include <visionaray/array.h> #include <visionaray/material.h> namespace visionaray { //------------------------------------------------------------------------------------------------- // Public interface // template <typename T, typename ...Ts> template <template <typename> class M> inline generic_material<T, Ts...>::generic_material(M<typename T::scalar_type> const& material) : generic_material<T, Ts...>::base_type(material) { } template <typename T, typename ...Ts> VSNRAY_FUNC inline spectrum<typename T::scalar_type> generic_material<T, Ts...>::ambient() const { return apply_visitor( ambient_visitor(), *this ); } template <typename T, typename ...Ts> template <typename SR> VSNRAY_FUNC inline spectrum<typename SR::scalar_type> generic_material<T, Ts...>::shade(SR const& sr) const { return apply_visitor( shade_visitor<SR>(sr), *this ); } template <typename T, typename ...Ts> template <typename SR, typename U, typename Interaction, typename Generator> VSNRAY_FUNC inline spectrum<U> generic_material<T, Ts...>::sample( SR const& sr, vector<3, U>& refl_dir, U& pdf, Interaction& inter, Generator& gen ) const { return apply_visitor( sample_visitor<SR, U, Interaction, Generator>(sr, refl_dir, pdf, inter, gen), *this ); } template <typename T, typename ...Ts> template <typename SR, typename Interaction> VSNRAY_FUNC inline typename SR::scalar_type generic_material<T, Ts...>::pdf( SR const& sr, Interaction const& inter ) const { return apply_visitor( pdf_visitor<SR, Interaction>(sr, inter), *this ); } //------------------------------------------------------------------------------------------------- // Private variant visitors // template <typename T, typename ...Ts> struct generic_material<T, Ts...>::ambient_visitor { using Base = generic_material<T, Ts...>; using return_type = spectrum<typename Base::scalar_type>; template <typename X> VSNRAY_FUNC return_type operator()(X const& ref) const { return ref.ambient(); } }; template <typename T, typename ...Ts> template <typename SR> struct generic_material<T, Ts...>::shade_visitor { using return_type = spectrum<typename SR::scalar_type>; VSNRAY_FUNC shade_visitor(SR const& sr) : sr_(sr) {} template <typename X> VSNRAY_FUNC return_type operator()(X const& ref) const { return ref.shade(sr_); } SR const& sr_; }; template <typename T, typename ...Ts> template <typename SR, typename U, typename Interaction, typename Generator> struct generic_material<T, Ts...>::sample_visitor { using return_type = spectrum<typename SR::scalar_type>; VSNRAY_FUNC sample_visitor(SR const& sr, vector<3, U>& refl_dir, U& pdf, Interaction& inter, Generator& gen) : sr_(sr) , refl_dir_(refl_dir) , pdf_(pdf) , inter_(inter) , gen_(gen) { } template <typename X> VSNRAY_FUNC return_type operator()(X const& ref) const { return ref.sample(sr_, refl_dir_, pdf_, inter_, gen_); } SR const& sr_; vector<3, U>& refl_dir_; U& pdf_; Interaction& inter_; Generator& gen_; }; template <typename T, typename ...Ts> template <typename SR, typename Interaction> struct generic_material<T, Ts...>::pdf_visitor { using return_type = typename SR::scalar_type; VSNRAY_FUNC pdf_visitor(SR const& sr, Interaction const& inter) : sr_(sr) , inter_(inter) { } template <typename X> VSNRAY_FUNC return_type operator()(X const& ref) const { return ref.pdf(sr_, inter_); } SR const& sr_; Interaction const& inter_; }; namespace simd { //------------------------------------------------------------------------------------------------- // SIMD type used internally. Contains N generic materials // template <size_t N, typename ...Ts> class generic_material { public: using scalar_type = float_from_simd_width_t<N>; using single_material = visionaray::generic_material<Ts...>; public: VSNRAY_FUNC generic_material(array<single_material, N> const& mats) : mats_(mats) { } VSNRAY_FUNC single_material& get(int i) { return mats_[i]; } VSNRAY_FUNC single_material const& get(int i) const { return mats_[i]; } VSNRAY_FUNC spectrum<scalar_type> ambient() const { array<spectrum<float>, N> amb; for (size_t i = 0; i < N; ++i) { amb[i] = mats_[i].ambient(); } return pack(amb); } template <typename SR> VSNRAY_FUNC spectrum<scalar_type> shade(SR const& sr) const { auto srs = unpack(sr); array<spectrum<float>, N> shaded; for (size_t i = 0; i < N; ++i) { shaded[i] = mats_[i].shade(srs[i]); } return pack(shaded); } template <typename SR, typename Generator> VSNRAY_FUNC spectrum<scalar_type> sample( SR const& sr, vector<3, scalar_type>& refl_dir, scalar_type& pdf, int_type_t<scalar_type>& inter, Generator& gen ) const { using float_array = aligned_array_t<scalar_type>; using int_array = aligned_array_t<int_type_t<scalar_type>>; auto srs = unpack(sr); array<vector<3, float>, N> rds; float_array pdfs; int_array inters; array<spectrum<float>, N> sampled; for (size_t i = 0; i < N; ++i) { sampled[i] = mats_[i].sample(srs[i], rds[i], pdfs[i], inters[i], gen.get_generator(i)); } refl_dir = pack(rds); pdf = scalar_type(pdfs); inter = int_type_t<scalar_type>(inters); return pack(sampled); } template <typename SR, typename Interaction> VSNRAY_FUNC scalar_type pdf(SR const& sr, Interaction const& inter) const { using float_array = aligned_array_t<scalar_type>; using int_array = aligned_array_t<int_type_t<scalar_type>>; auto srs = unpack(sr); int_array inters; store(inters, inter); float_array pdfs; for (size_t i = 0; i < N; ++i) { pdfs[i] = mats_[i].pdf(srs[i], inters[i]); } return scalar_type(pdfs); } private: array<single_material, N> mats_; }; //------------------------------------------------------------------------------------------------- // Pack and unpack // template <typename ...Ts> VSNRAY_FUNC inline generic_material<4, Ts...> pack(array<visionaray::generic_material<Ts...>, 4> const& mats) { return generic_material<4, Ts...>(mats); } template <typename ...Ts> VSNRAY_FUNC inline array<visionaray::generic_material<Ts...>, 4> unpack(generic_material<4, Ts...> const& m4) { return array<visionaray::generic_material<Ts...>, 4>{{ m4.get(0), m4.get(1), m4.get(2), m4.get(3) }}; } template <typename ...Ts> inline generic_material<8, Ts...> pack(array<visionaray::generic_material<Ts...>, 8> const& mats) { return generic_material<8, Ts...>(mats); } template <typename ...Ts> inline array<visionaray::generic_material<Ts...>, 8> unpack(generic_material<8, Ts...> const& m8) { return array<visionaray::generic_material<Ts...>, 8>{{ m8.get(0), m8.get(1), m8.get(2), m8.get(3), m8.get(4), m8.get(5), m8.get(6), m8.get(7) }}; } template <typename ...Ts> inline generic_material<16, Ts...> pack(array<visionaray::generic_material<Ts...>, 16> const& mats) { return generic_material<16, Ts...>(mats); } template <typename ...Ts> inline array<visionaray::generic_material<Ts...>, 16> unpack(generic_material<16, Ts...> const& m16) { return array<visionaray::generic_material<Ts...>, 16>{{ m16.get( 0), m16.get( 1), m16.get( 2), m16.get( 3), m16.get( 4), m16.get( 5), m16.get( 6), m16.get( 7), m16.get( 8), m16.get( 9), m16.get(10), m16.get(11), m16.get(12), m16.get(13), m16.get(14), m16.get(15) }}; } } // simd } // visionaray <commit_msg>Don't use 64 bit indices to iterate over SIMD lane<commit_after>// This file is distributed under the MIT license. // See the LICENSE file for details. #include <visionaray/array.h> #include <visionaray/material.h> namespace visionaray { //------------------------------------------------------------------------------------------------- // Public interface // template <typename T, typename ...Ts> template <template <typename> class M> inline generic_material<T, Ts...>::generic_material(M<typename T::scalar_type> const& material) : generic_material<T, Ts...>::base_type(material) { } template <typename T, typename ...Ts> VSNRAY_FUNC inline spectrum<typename T::scalar_type> generic_material<T, Ts...>::ambient() const { return apply_visitor( ambient_visitor(), *this ); } template <typename T, typename ...Ts> template <typename SR> VSNRAY_FUNC inline spectrum<typename SR::scalar_type> generic_material<T, Ts...>::shade(SR const& sr) const { return apply_visitor( shade_visitor<SR>(sr), *this ); } template <typename T, typename ...Ts> template <typename SR, typename U, typename Interaction, typename Generator> VSNRAY_FUNC inline spectrum<U> generic_material<T, Ts...>::sample( SR const& sr, vector<3, U>& refl_dir, U& pdf, Interaction& inter, Generator& gen ) const { return apply_visitor( sample_visitor<SR, U, Interaction, Generator>(sr, refl_dir, pdf, inter, gen), *this ); } template <typename T, typename ...Ts> template <typename SR, typename Interaction> VSNRAY_FUNC inline typename SR::scalar_type generic_material<T, Ts...>::pdf( SR const& sr, Interaction const& inter ) const { return apply_visitor( pdf_visitor<SR, Interaction>(sr, inter), *this ); } //------------------------------------------------------------------------------------------------- // Private variant visitors // template <typename T, typename ...Ts> struct generic_material<T, Ts...>::ambient_visitor { using Base = generic_material<T, Ts...>; using return_type = spectrum<typename Base::scalar_type>; template <typename X> VSNRAY_FUNC return_type operator()(X const& ref) const { return ref.ambient(); } }; template <typename T, typename ...Ts> template <typename SR> struct generic_material<T, Ts...>::shade_visitor { using return_type = spectrum<typename SR::scalar_type>; VSNRAY_FUNC shade_visitor(SR const& sr) : sr_(sr) {} template <typename X> VSNRAY_FUNC return_type operator()(X const& ref) const { return ref.shade(sr_); } SR const& sr_; }; template <typename T, typename ...Ts> template <typename SR, typename U, typename Interaction, typename Generator> struct generic_material<T, Ts...>::sample_visitor { using return_type = spectrum<typename SR::scalar_type>; VSNRAY_FUNC sample_visitor(SR const& sr, vector<3, U>& refl_dir, U& pdf, Interaction& inter, Generator& gen) : sr_(sr) , refl_dir_(refl_dir) , pdf_(pdf) , inter_(inter) , gen_(gen) { } template <typename X> VSNRAY_FUNC return_type operator()(X const& ref) const { return ref.sample(sr_, refl_dir_, pdf_, inter_, gen_); } SR const& sr_; vector<3, U>& refl_dir_; U& pdf_; Interaction& inter_; Generator& gen_; }; template <typename T, typename ...Ts> template <typename SR, typename Interaction> struct generic_material<T, Ts...>::pdf_visitor { using return_type = typename SR::scalar_type; VSNRAY_FUNC pdf_visitor(SR const& sr, Interaction const& inter) : sr_(sr) , inter_(inter) { } template <typename X> VSNRAY_FUNC return_type operator()(X const& ref) const { return ref.pdf(sr_, inter_); } SR const& sr_; Interaction const& inter_; }; namespace simd { //------------------------------------------------------------------------------------------------- // SIMD type used internally. Contains N generic materials // template <unsigned N, typename ...Ts> class generic_material { public: using scalar_type = float_from_simd_width_t<N>; using single_material = visionaray::generic_material<Ts...>; public: VSNRAY_FUNC generic_material(array<single_material, N> const& mats) : mats_(mats) { } VSNRAY_FUNC single_material& get(int i) { return mats_[i]; } VSNRAY_FUNC single_material const& get(int i) const { return mats_[i]; } VSNRAY_FUNC spectrum<scalar_type> ambient() const { array<spectrum<float>, N> amb; for (unsigned i = 0; i < N; ++i) { amb[i] = mats_[i].ambient(); } return pack(amb); } template <typename SR> VSNRAY_FUNC spectrum<scalar_type> shade(SR const& sr) const { auto srs = unpack(sr); array<spectrum<float>, N> shaded; for (unsigned i = 0; i < N; ++i) { shaded[i] = mats_[i].shade(srs[i]); } return pack(shaded); } template <typename SR, typename Generator> VSNRAY_FUNC spectrum<scalar_type> sample( SR const& sr, vector<3, scalar_type>& refl_dir, scalar_type& pdf, int_type_t<scalar_type>& inter, Generator& gen ) const { using float_array = aligned_array_t<scalar_type>; using int_array = aligned_array_t<int_type_t<scalar_type>>; auto srs = unpack(sr); array<vector<3, float>, N> rds; float_array pdfs; int_array inters; array<spectrum<float>, N> sampled; for (unsigned i = 0; i < N; ++i) { sampled[i] = mats_[i].sample(srs[i], rds[i], pdfs[i], inters[i], gen.get_generator(i)); } refl_dir = pack(rds); pdf = scalar_type(pdfs); inter = int_type_t<scalar_type>(inters); return pack(sampled); } template <typename SR, typename Interaction> VSNRAY_FUNC scalar_type pdf(SR const& sr, Interaction const& inter) const { using float_array = aligned_array_t<scalar_type>; using int_array = aligned_array_t<int_type_t<scalar_type>>; auto srs = unpack(sr); int_array inters; store(inters, inter); float_array pdfs; for (unsigned i = 0; i < N; ++i) { pdfs[i] = mats_[i].pdf(srs[i], inters[i]); } return scalar_type(pdfs); } private: array<single_material, N> mats_; }; //------------------------------------------------------------------------------------------------- // Pack and unpack // template <typename ...Ts> VSNRAY_FUNC inline generic_material<4, Ts...> pack(array<visionaray::generic_material<Ts...>, 4> const& mats) { return generic_material<4, Ts...>(mats); } template <typename ...Ts> VSNRAY_FUNC inline array<visionaray::generic_material<Ts...>, 4> unpack(generic_material<4, Ts...> const& m4) { return array<visionaray::generic_material<Ts...>, 4>{{ m4.get(0), m4.get(1), m4.get(2), m4.get(3) }}; } template <typename ...Ts> inline generic_material<8, Ts...> pack(array<visionaray::generic_material<Ts...>, 8> const& mats) { return generic_material<8, Ts...>(mats); } template <typename ...Ts> inline array<visionaray::generic_material<Ts...>, 8> unpack(generic_material<8, Ts...> const& m8) { return array<visionaray::generic_material<Ts...>, 8>{{ m8.get(0), m8.get(1), m8.get(2), m8.get(3), m8.get(4), m8.get(5), m8.get(6), m8.get(7) }}; } template <typename ...Ts> inline generic_material<16, Ts...> pack(array<visionaray::generic_material<Ts...>, 16> const& mats) { return generic_material<16, Ts...>(mats); } template <typename ...Ts> inline array<visionaray::generic_material<Ts...>, 16> unpack(generic_material<16, Ts...> const& m16) { return array<visionaray::generic_material<Ts...>, 16>{{ m16.get( 0), m16.get( 1), m16.get( 2), m16.get( 3), m16.get( 4), m16.get( 5), m16.get( 6), m16.get( 7), m16.get( 8), m16.get( 9), m16.get(10), m16.get(11), m16.get(12), m16.get(13), m16.get(14), m16.get(15) }}; } } // simd } // visionaray <|endoftext|>
<commit_before>#ifndef VSMC_UNIFORM_REAL_DISTRIBUTION_HPP #define VSMC_UNIFORM_REAL_DISTRIBUTION_HPP #include <vsmc/internal/common.hpp> #include <vsmc/rng/u01.h> #define VSMC_STATIC_ASSERT_RNG_UNIFORM_REAL_DISTRIBUTION_ENG_MIN(engmin) \ VSMC_STATIC_ASSERT((engmin == 0), \ USE_UniformRealDistribution_WITH_A_RNG_ENGINE_HAVING_NONZERO_MIN) #define VSMC_STATIC_ASSERT_RNG_UNIFORM_REAL_DISTRIBUTION_ENG_MAX(engmax) \ VSMC_STATIC_ASSERT( \ ((static_cast<uint64_t>(engmax) == \ static_cast<uint64_t>(~(static_cast<uint32_t>(0)))) || \ (static_cast<uint64_t>(engmax) == \ (~(static_cast<uint32_t>(0))))), \ USE_UniformRealDistribution_WITH_A_RNG_ENGINE_HAVING_MAX_THAT_DOES_NOT_COVER_THE_FULL_RANGE) #define VSMC_RUNTIME_ASSERT_RNG_UNIFORM_REAL_DISTRIBUTION_ENG_MIN \ VSMC_RUNTIME_ASSERT(false, \ ("**UniformRealDistribution::operator()** " \ "ENGINE MEMBER FUNCTION min() RETURN A VALUE OTHER THAN ZERO")) #define VSMC_RUNTIME_ASSERT_RNG_UNIFORM_REAL_DISTRIBUTION_ENG_MAX \ VSMC_RUNTIME_ASSERT(false, \ ("**UniformRealDistribution::operator()** " \ "ENGINE MEMBER FUNCTION max() RETURN A VALUE OTHER THAN " \ "THE MAXIMUM OF uint32_t OR uint64_t")) namespace vsmc { namespace internal { template<uint64_t, uint64_t> struct FullRangeIntgerType; template<> struct FullRangeIntgerType<0, ~(static_cast<uint32_t>(0))> {typedef uint32_t type;}; template<> struct FullRangeIntgerType<0, ~(static_cast<uint64_t>(0))> {typedef uint64_t type;}; } // namespace vsmc::interal /// \brief Parameter type for open interval /// \ingroup RNG struct Open {}; /// \brief Parameter type for closed interval /// \ingroup RNG struct Closed {}; /// \brief Uniform real distribution with variants open/closed variants /// \ingroup RNG /// /// \details /// This distribution is almost identical to C++11 /// `std::uniform_real_distribution`. But it differs in two important aspects /// - It allows the interval to be either open or closed on both sides. /// - It requires that the uniform random number generator to produce integers /// on the full range of either `uint32_t` or `uint64_t`. template <typename FPType, typename Left, typename Right> class UniformRealDistribution { private : typedef cxx11::integral_constant<std::size_t, sizeof(float)> f24; typedef cxx11::integral_constant<std::size_t, sizeof(double)> f53; typedef cxx11::integral_constant<std::size_t, sizeof(uint32_t)> u32; typedef cxx11::integral_constant<std::size_t, sizeof(uint64_t)> u64; public : typedef FPType result_type; class param_type { public : typedef FPType result_type; typedef UniformRealDistribution<FPType, Left, Right> distribution_type; explicit param_type (result_type a = 0, result_type b = 1) : a_(a), b_(b) {} result_type a () const {return a_;} result_type b () const {return b_;} friend inline bool operator== ( const param_type &param1, const param_type &param2) { if (param1.a() < param2.a() || param1.a() > param2.a()) return false; if (param1.b() < param2.b() || param1.b() > param2.b()) return false; return true; } friend inline bool operator!= ( const param_type param1, const param_type param2) {return !(param1 == param2);} template <typename CharT, typename Traits> friend inline std::basic_ostream<CharT, Traits> &operator<< ( std::basic_ostream<CharT, Traits> &os, const param_type &param) { os << param.a() << ' ' << param.b(); return os; } template <typename CharT, typename Traits> friend inline std::basic_istream<CharT, Traits> &operator>> ( std::basic_istream<CharT, Traits> &is, param_type &param) { result_type a; result_type b; if (is >> a >> std::ws >> b) { if (a <= b) param = param_type(param_type(a, b)); else is.setstate(std::ios_base::failbit); } return is; } private : result_type a_; result_type b_; }; // class param_type explicit UniformRealDistribution (result_type a = 0, result_type b = 1) : a_(a), b_(b) {} UniformRealDistribution (const param_type &param) : a_(param.a()), b_(param.b()) {} param_type param () const {return param_type(a_, b_);} void param (const param_type &param) { a_ = param.a(); b_ = param.b(); } void reset () const {} result_type a () const {return a_;} result_type b () const {return b_;} result_type min VSMC_MNE () const {return a_;} result_type max VSMC_MNE () const {return b_;} template <typename Eng> result_type operator() (Eng &eng) const { typedef cxx11::integral_constant<std::size_t, sizeof(result_type)> fp_bits; #if VSMC_HAS_CXX11LIB_RANDOM_CONSTEXPR_MINMAX VSMC_STATIC_ASSERT_RNG_UNIFORM_REAL_DISTRIBUTION_ENG_MIN( (Eng::min VSMC_MNE ())); VSMC_STATIC_ASSERT_RNG_UNIFORM_REAL_DISTRIBUTION_ENG_MAX( (Eng::max VSMC_MNE ())); typedef typename internal::FullRangeIntgerType< Eng::min VSMC_MNE (), Eng::max VSMC_MNE ()>::type eng_uint_t; typedef cxx11::integral_constant<std::size_t, sizeof(eng_uint_t)> u_bits; result_type u = u01(static_cast<eng_uint_t>(eng()), Left(), Right(), u_bits(), fp_bits()); #else // VSMC_HAS_CXX11LIB_RANDOM_CONSTEXPR_MINMAX static VSMC_CONSTEXPR const uint64_t eng_min = static_cast<uint64_t>( eng.min VSMC_MNE ()); if (eng_min != 0) { VSMC_RUNTIME_ASSERT_RNG_UNIFORM_REAL_DISTRIBUTION_ENG_MIN; return 0; } static VSMC_CONSTEXPR const uint64_t eng_max = static_cast<uint64_t>( eng.max VSMC_MNE ()); if (eng_max != uint32_t_max_ && eng_max != uint64_t_max_) { VSMC_RUNTIME_ASSERT_RNG_UNIFORM_REAL_DISTRIBUTION_ENG_MAX; return 0; } result_type u = 0; switch (eng_max) { case uint32_t_max_ : u = u01(static_cast<uint32_t>(eng()), Left(), Right(), u32(), fp_bits()); break; case uint64_t_max_ : u = u01(static_cast<uint64_t>(eng()), Left(), Right(), u64(), fp_bits()); break; default : return 0; } #endif // VSMC_HAS_CXX11LIB_RANDOM_CONSTEXPR_MINMAX return u * (b_ - a_) + a_; } private : result_type a_; result_type b_; #if !VSMC_HAS_CXX11LIB_RANDOM_CONSTEXPR_MINMAX static VSMC_CONSTEXPR const uint64_t uint32_t_max_ = ~(static_cast<uint32_t>(0)); static VSMC_CONSTEXPR const uint64_t uint64_t_max_ = ~(static_cast<uint64_t>(0)); #endif static float u01(uint32_t i, Open, Open, u32, f24) {return ::u01_open_open_32_24(i);} static float u01(uint32_t i, Open, Closed, u32, f24) {return ::u01_open_closed_32_24(i);} static float u01(uint32_t i, Closed, Open, u32, f24) {return ::u01_closed_open_32_24(i);} static float u01(uint32_t i, Closed, Closed, u32, f24) {return ::u01_closed_closed_32_24(i);} static double u01(uint32_t i, Open, Open, u32, f53) {return ::u01_open_open_32_53(i);} static double u01(uint32_t i, Open, Closed, u32, f53) {return ::u01_open_closed_32_53(i);} static double u01(uint32_t i, Closed, Open, u32, f53) {return ::u01_closed_open_32_53(i);} static double u01(uint32_t i, Closed, Closed, u32, f53) {return ::u01_closed_closed_32_53(i);} static float u01(uint64_t i, Open, Open, u64, f24) {return static_cast<float>(::u01_open_open_64_53(i));} static float u01(uint64_t i, Open, Closed, u64, f24) {return static_cast<float>(::u01_open_closed_64_53(i));} static float u01(uint64_t i, Closed, Open, u64, f24) {return static_cast<float>(::u01_closed_open_64_53(i));} static float u01(uint64_t i, Closed, Closed, u64, f24) {return static_cast<float>(::u01_closed_closed_64_53(i));} static double u01(uint64_t i, Open, Open, u64, f53) {return ::u01_open_open_64_53(i);} static double u01(uint64_t i, Open, Closed, u64, f53) {return ::u01_open_closed_64_53(i);} static double u01(uint64_t i, Closed, Open, u64, f53) {return ::u01_closed_open_64_53(i);} static double u01(uint64_t i, Closed, Closed, u64, f53) {return ::u01_closed_closed_64_53(i);} }; // class UniformRealDistributionBase /// \brief UniformRealDistribution operator== /// \ingroup RNG template <typename FPType, typename Left, typename Right> inline bool operator== ( const UniformRealDistribution<FPType, Left, Right> &runif1, const UniformRealDistribution<FPType, Left, Right> &runif2) { if (runif1.a() < runif2.a() ||runif1.a() > runif1.a()) return false; if (runif1.b() < runif2.b() ||runif1.b() > runif1.b()) return false; return true; } /// \brief UniformRealDistribution operator!= /// \ingroup RNG template <typename FPType, typename Left, typename Right> inline bool operator!= ( const UniformRealDistribution<FPType, Left, Right> &runif1, const UniformRealDistribution<FPType, Left, Right> &runif2) {return !(runif1 == runif2);} /// \brief UniformRealDistribution operator<< /// \ingroup RNG template <typename CharT, typename Traits, typename FPType, typename Left, typename Right> inline std::basic_ostream<CharT, Traits> &operator<< ( std::basic_ostream<CharT, Traits> &os, const UniformRealDistribution<FPType, Left, Right> &runif) { os << runif.a() << ' ' << runif.b(); return os; } /// \brief UniformRealDistribution operator>> /// \ingroup RNG template <typename CharT, typename Traits, typename FPType, typename Left, typename Right> inline std::basic_istream<CharT, Traits> &operator>> ( std::basic_istream<CharT, Traits> &is, UniformRealDistribution<FPType, Left, Right> &runif) { typedef typename UniformRealDistribution<FPType, Left, Right>::param_type param_type; FPType a = 0; FPType b = 0; if (is >> a >> std::ws >> b) { if (a <= b) runif.param(param_type(a, b)); else is.setstate(std::ios_base::failbit); } return is; } } // namespace vsmc #endif // VSMC_UNIFORM_REAL_DISTRIBUTION_HPP <commit_msg>fix typo in static assertions<commit_after>#ifndef VSMC_UNIFORM_REAL_DISTRIBUTION_HPP #define VSMC_UNIFORM_REAL_DISTRIBUTION_HPP #include <vsmc/internal/common.hpp> #include <vsmc/rng/u01.h> #define VSMC_STATIC_ASSERT_RNG_UNIFORM_REAL_DISTRIBUTION_ENG_MIN(engmin) \ VSMC_STATIC_ASSERT((engmin == 0), \ USE_UniformRealDistribution_WITH_A_RNG_ENGINE_HAVING_NONZERO_MIN) #define VSMC_STATIC_ASSERT_RNG_UNIFORM_REAL_DISTRIBUTION_ENG_MAX(engmax) \ VSMC_STATIC_ASSERT( \ ((static_cast<uint64_t>(engmax) == \ static_cast<uint64_t>(~(static_cast<uint32_t>(0)))) || \ (static_cast<uint64_t>(engmax) == \ (~(static_cast<uint64_t>(0))))), \ USE_UniformRealDistribution_WITH_A_RNG_ENGINE_HAVING_MAX_THAT_DOES_NOT_COVER_THE_FULL_RANGE) #define VSMC_RUNTIME_ASSERT_RNG_UNIFORM_REAL_DISTRIBUTION_ENG_MIN \ VSMC_RUNTIME_ASSERT(false, \ ("**UniformRealDistribution::operator()** " \ "ENGINE MEMBER FUNCTION min() RETURN A VALUE OTHER THAN ZERO")) #define VSMC_RUNTIME_ASSERT_RNG_UNIFORM_REAL_DISTRIBUTION_ENG_MAX \ VSMC_RUNTIME_ASSERT(false, \ ("**UniformRealDistribution::operator()** " \ "ENGINE MEMBER FUNCTION max() RETURN A VALUE OTHER THAN " \ "THE MAXIMUM OF uint32_t OR uint64_t")) namespace vsmc { namespace internal { template<uint64_t, uint64_t> struct FullRangeIntgerType; template<> struct FullRangeIntgerType<0, ~(static_cast<uint32_t>(0))> {typedef uint32_t type;}; template<> struct FullRangeIntgerType<0, ~(static_cast<uint64_t>(0))> {typedef uint64_t type;}; } // namespace vsmc::interal /// \brief Parameter type for open interval /// \ingroup RNG struct Open {}; /// \brief Parameter type for closed interval /// \ingroup RNG struct Closed {}; /// \brief Uniform real distribution with variants open/closed variants /// \ingroup RNG /// /// \details /// This distribution is almost identical to C++11 /// `std::uniform_real_distribution`. But it differs in two important aspects /// - It allows the interval to be either open or closed on both sides. /// - It requires that the uniform random number generator to produce integers /// on the full range of either `uint32_t` or `uint64_t`. template <typename FPType, typename Left, typename Right> class UniformRealDistribution { private : typedef cxx11::integral_constant<std::size_t, sizeof(float)> f24; typedef cxx11::integral_constant<std::size_t, sizeof(double)> f53; typedef cxx11::integral_constant<std::size_t, sizeof(uint32_t)> u32; typedef cxx11::integral_constant<std::size_t, sizeof(uint64_t)> u64; public : typedef FPType result_type; class param_type { public : typedef FPType result_type; typedef UniformRealDistribution<FPType, Left, Right> distribution_type; explicit param_type (result_type a = 0, result_type b = 1) : a_(a), b_(b) {} result_type a () const {return a_;} result_type b () const {return b_;} friend inline bool operator== ( const param_type &param1, const param_type &param2) { if (param1.a() < param2.a() || param1.a() > param2.a()) return false; if (param1.b() < param2.b() || param1.b() > param2.b()) return false; return true; } friend inline bool operator!= ( const param_type param1, const param_type param2) {return !(param1 == param2);} template <typename CharT, typename Traits> friend inline std::basic_ostream<CharT, Traits> &operator<< ( std::basic_ostream<CharT, Traits> &os, const param_type &param) { os << param.a() << ' ' << param.b(); return os; } template <typename CharT, typename Traits> friend inline std::basic_istream<CharT, Traits> &operator>> ( std::basic_istream<CharT, Traits> &is, param_type &param) { result_type a; result_type b; if (is >> a >> std::ws >> b) { if (a <= b) param = param_type(param_type(a, b)); else is.setstate(std::ios_base::failbit); } return is; } private : result_type a_; result_type b_; }; // class param_type explicit UniformRealDistribution (result_type a = 0, result_type b = 1) : a_(a), b_(b) {} UniformRealDistribution (const param_type &param) : a_(param.a()), b_(param.b()) {} param_type param () const {return param_type(a_, b_);} void param (const param_type &param) { a_ = param.a(); b_ = param.b(); } void reset () const {} result_type a () const {return a_;} result_type b () const {return b_;} result_type min VSMC_MNE () const {return a_;} result_type max VSMC_MNE () const {return b_;} template <typename Eng> result_type operator() (Eng &eng) const { typedef cxx11::integral_constant<std::size_t, sizeof(result_type)> fp_bits; #if VSMC_HAS_CXX11LIB_RANDOM_CONSTEXPR_MINMAX VSMC_STATIC_ASSERT_RNG_UNIFORM_REAL_DISTRIBUTION_ENG_MIN( (Eng::min VSMC_MNE ())); VSMC_STATIC_ASSERT_RNG_UNIFORM_REAL_DISTRIBUTION_ENG_MAX( (Eng::max VSMC_MNE ())); typedef typename internal::FullRangeIntgerType< Eng::min VSMC_MNE (), Eng::max VSMC_MNE ()>::type eng_uint_t; typedef cxx11::integral_constant<std::size_t, sizeof(eng_uint_t)> u_bits; result_type u = u01(static_cast<eng_uint_t>(eng()), Left(), Right(), u_bits(), fp_bits()); #else // VSMC_HAS_CXX11LIB_RANDOM_CONSTEXPR_MINMAX static VSMC_CONSTEXPR const uint64_t eng_min = static_cast<uint64_t>( eng.min VSMC_MNE ()); if (eng_min != 0) { VSMC_RUNTIME_ASSERT_RNG_UNIFORM_REAL_DISTRIBUTION_ENG_MIN; return 0; } static VSMC_CONSTEXPR const uint64_t eng_max = static_cast<uint64_t>( eng.max VSMC_MNE ()); if (eng_max != uint32_t_max_ && eng_max != uint64_t_max_) { VSMC_RUNTIME_ASSERT_RNG_UNIFORM_REAL_DISTRIBUTION_ENG_MAX; return 0; } result_type u = 0; switch (eng_max) { case uint32_t_max_ : u = u01(static_cast<uint32_t>(eng()), Left(), Right(), u32(), fp_bits()); break; case uint64_t_max_ : u = u01(static_cast<uint64_t>(eng()), Left(), Right(), u64(), fp_bits()); break; default : return 0; } #endif // VSMC_HAS_CXX11LIB_RANDOM_CONSTEXPR_MINMAX return u * (b_ - a_) + a_; } private : result_type a_; result_type b_; #if !VSMC_HAS_CXX11LIB_RANDOM_CONSTEXPR_MINMAX static VSMC_CONSTEXPR const uint64_t uint32_t_max_ = ~(static_cast<uint32_t>(0)); static VSMC_CONSTEXPR const uint64_t uint64_t_max_ = ~(static_cast<uint64_t>(0)); #endif static float u01(uint32_t i, Open, Open, u32, f24) {return ::u01_open_open_32_24(i);} static float u01(uint32_t i, Open, Closed, u32, f24) {return ::u01_open_closed_32_24(i);} static float u01(uint32_t i, Closed, Open, u32, f24) {return ::u01_closed_open_32_24(i);} static float u01(uint32_t i, Closed, Closed, u32, f24) {return ::u01_closed_closed_32_24(i);} static double u01(uint32_t i, Open, Open, u32, f53) {return ::u01_open_open_32_53(i);} static double u01(uint32_t i, Open, Closed, u32, f53) {return ::u01_open_closed_32_53(i);} static double u01(uint32_t i, Closed, Open, u32, f53) {return ::u01_closed_open_32_53(i);} static double u01(uint32_t i, Closed, Closed, u32, f53) {return ::u01_closed_closed_32_53(i);} static float u01(uint64_t i, Open, Open, u64, f24) {return static_cast<float>(::u01_open_open_64_53(i));} static float u01(uint64_t i, Open, Closed, u64, f24) {return static_cast<float>(::u01_open_closed_64_53(i));} static float u01(uint64_t i, Closed, Open, u64, f24) {return static_cast<float>(::u01_closed_open_64_53(i));} static float u01(uint64_t i, Closed, Closed, u64, f24) {return static_cast<float>(::u01_closed_closed_64_53(i));} static double u01(uint64_t i, Open, Open, u64, f53) {return ::u01_open_open_64_53(i);} static double u01(uint64_t i, Open, Closed, u64, f53) {return ::u01_open_closed_64_53(i);} static double u01(uint64_t i, Closed, Open, u64, f53) {return ::u01_closed_open_64_53(i);} static double u01(uint64_t i, Closed, Closed, u64, f53) {return ::u01_closed_closed_64_53(i);} }; // class UniformRealDistributionBase /// \brief UniformRealDistribution operator== /// \ingroup RNG template <typename FPType, typename Left, typename Right> inline bool operator== ( const UniformRealDistribution<FPType, Left, Right> &runif1, const UniformRealDistribution<FPType, Left, Right> &runif2) { if (runif1.a() < runif2.a() ||runif1.a() > runif1.a()) return false; if (runif1.b() < runif2.b() ||runif1.b() > runif1.b()) return false; return true; } /// \brief UniformRealDistribution operator!= /// \ingroup RNG template <typename FPType, typename Left, typename Right> inline bool operator!= ( const UniformRealDistribution<FPType, Left, Right> &runif1, const UniformRealDistribution<FPType, Left, Right> &runif2) {return !(runif1 == runif2);} /// \brief UniformRealDistribution operator<< /// \ingroup RNG template <typename CharT, typename Traits, typename FPType, typename Left, typename Right> inline std::basic_ostream<CharT, Traits> &operator<< ( std::basic_ostream<CharT, Traits> &os, const UniformRealDistribution<FPType, Left, Right> &runif) { os << runif.a() << ' ' << runif.b(); return os; } /// \brief UniformRealDistribution operator>> /// \ingroup RNG template <typename CharT, typename Traits, typename FPType, typename Left, typename Right> inline std::basic_istream<CharT, Traits> &operator>> ( std::basic_istream<CharT, Traits> &is, UniformRealDistribution<FPType, Left, Right> &runif) { typedef typename UniformRealDistribution<FPType, Left, Right>::param_type param_type; FPType a = 0; FPType b = 0; if (is >> a >> std::ws >> b) { if (a <= b) runif.param(param_type(a, b)); else is.setstate(std::ios_base::failbit); } return is; } } // namespace vsmc #endif // VSMC_UNIFORM_REAL_DISTRIBUTION_HPP <|endoftext|>
<commit_before>/* * Copyright (c) 2015 Samsung Electronics Co., Ltd 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 "common/application_data.h" #include <manifest_handlers/application_manifest_constants.h> #include <manifest_handlers/widget_config_parser.h> #include <package_manager.h> #include <vector> #include "common/file_utils.h" #include "common/logger.h" #include "common/profiler.h" namespace common { namespace { const char* kPathSeparator = "/"; const char* kConfigXml = "config.xml"; const char* kResWgtPath = "res/wgt"; static std::string GetPackageIdByAppId(const std::string& appid) { char* pkgid = NULL; package_manager_get_package_id_by_app_id(appid.c_str(), &pkgid); std::unique_ptr<char, decltype(std::free)*> pkgid_ptr {pkgid, std::free}; if (pkgid != NULL) { return std::string(pkgid_ptr.get()); } else { LOGGER(ERROR) << "Failed to get package id"; return std::string(); } } static std::string GetPackageRootPath(const std::string& pkgid) { package_info_h pkg_info = NULL; if (package_manager_get_package_info( pkgid.c_str(), &pkg_info) != PACKAGE_MANAGER_ERROR_NONE) { return std::string(); } char* pkg_root_path = NULL; package_info_get_root_path(pkg_info, &pkg_root_path); std::unique_ptr<char, decltype(std::free)*> path_ptr {pkg_root_path, std::free}; package_info_destroy(pkg_info); if (pkg_root_path != NULL) { return std::string(path_ptr.get()); } else { LOGGER(ERROR) << "Failed to get package root path"; return std::string(); } } } // namespace ApplicationData::ApplicationData(const std::string& appid) : app_id_(appid) { pkg_id_ = GetPackageIdByAppId(appid); if (!pkg_id_.empty()) application_path_ = GetPackageRootPath(pkg_id_) + kPathSeparator + kResWgtPath + kPathSeparator; } ApplicationData::~ApplicationData() {} std::shared_ptr<const wgt::parse::AppControlInfoList> ApplicationData::app_control_info_list() const { return app_control_info_list_; } std::shared_ptr<const wgt::parse::CategoryInfoList> ApplicationData::category_info_list() const { return category_info_list_; } std::shared_ptr<const wgt::parse::MetaDataInfo> ApplicationData::meta_data_info() const { return meta_data_info_; } std::shared_ptr<const wgt::parse::AllowedNavigationInfo> ApplicationData::allowed_navigation_info() const { return allowed_navigation_info_; } std::shared_ptr<const wgt::parse::PermissionsInfo> ApplicationData::permissions_info() const { return permissions_info_; } std::shared_ptr<const wgt::parse::SettingInfo> ApplicationData::setting_info() const { return setting_info_; } std::shared_ptr<const wgt::parse::SplashScreenInfo> ApplicationData::splash_screen_info() const { return splash_screen_info_; } std::shared_ptr<const wgt::parse::TizenApplicationInfo> ApplicationData::tizen_application_info() const { return tizen_application_info_; } std::shared_ptr<const wgt::parse::WidgetInfo> ApplicationData::widget_info() const { return widget_info_; } std::shared_ptr<const wgt::parse::ContentInfo> ApplicationData::content_info() const { return content_info_; } std::shared_ptr<const wgt::parse::WarpInfo> ApplicationData::warp_info() const { return warp_info_; } std::shared_ptr<const wgt::parse::CSPInfo> ApplicationData::csp_info() const { return csp_info_; } std::shared_ptr<const wgt::parse::CSPInfo> ApplicationData::csp_report_info() const { return csp_report_info_; } bool ApplicationData::LoadManifestData() { SCOPE_PROFILE(); std::string config_xml_path(application_path_ + kConfigXml); if (!utils::Exists(config_xml_path)) { LOGGER(ERROR) << "Failed to load manifest data : No such file '" << config_xml_path << "'."; return false; } std::unique_ptr<wgt::parse::WidgetConfigParser> widget_config_parser; widget_config_parser.reset(new wgt::parse::WidgetConfigParser()); if (!widget_config_parser->ParseManifest(config_xml_path)) { LOGGER(ERROR) << "Failed to load widget config parser data: " << widget_config_parser->GetErrorMessage(); return false; } app_control_info_list_ = std::static_pointer_cast<const wgt::parse::AppControlInfoList>( widget_config_parser->GetManifestData( wgt::application_widget_keys::kTizenApplicationAppControlsKey)); category_info_list_ = std::static_pointer_cast<const wgt::parse::CategoryInfoList>( widget_config_parser->GetManifestData( wgt::application_widget_keys::kTizenCategoryKey)); meta_data_info_ = std::static_pointer_cast<const wgt::parse::MetaDataInfo>( widget_config_parser->GetManifestData( wgt::application_widget_keys::kTizenMetaDataKey)); allowed_navigation_info_ = std::static_pointer_cast<const wgt::parse::AllowedNavigationInfo>( widget_config_parser->GetManifestData( wgt::application_widget_keys::kAllowNavigationKey)); permissions_info_ = std::static_pointer_cast<const wgt::parse::PermissionsInfo>( widget_config_parser->GetManifestData( wgt::application_widget_keys::kTizenPermissionsKey)); setting_info_ = std::static_pointer_cast<const wgt::parse::SettingInfo>( widget_config_parser->GetManifestData( wgt::application_widget_keys::kTizenSettingKey)); splash_screen_info_ = std::static_pointer_cast<const wgt::parse::SplashScreenInfo>( widget_config_parser->GetManifestData( wgt::application_widget_keys::kTizenSplashScreenKey)); tizen_application_info_ = std::static_pointer_cast<const wgt::parse::TizenApplicationInfo>( widget_config_parser->GetManifestData( wgt::application_widget_keys::kTizenApplicationKey)); widget_info_ = std::static_pointer_cast<const wgt::parse::WidgetInfo>( widget_config_parser->GetManifestData( wgt::application_widget_keys::kTizenWidgetKey)); content_info_ = std::static_pointer_cast<const wgt::parse::ContentInfo>( widget_config_parser->GetManifestData( wgt::application_widget_keys::kTizenContentKey)); warp_info_ = std::static_pointer_cast<const wgt::parse::WarpInfo>( widget_config_parser->GetManifestData( wgt::application_widget_keys::kAccessKey)); csp_info_ = std::static_pointer_cast<const wgt::parse::CSPInfo>( widget_config_parser->GetManifestData( wgt::application_widget_keys::kCSPKey)); csp_report_info_ = std::static_pointer_cast<const wgt::parse::CSPInfo>( widget_config_parser->GetManifestData( wgt::application_widget_keys::kCSPReportOnlyKey)); // Set default empty object if (widget_info_.get() == NULL) { widget_info_.reset(new wgt::parse::WidgetInfo); } if (setting_info_.get() == NULL) { setting_info_.reset(new wgt::parse::SettingInfo); } return true; } } // namespace common <commit_msg>Replace key constants with key method<commit_after>/* * Copyright (c) 2015 Samsung Electronics Co., Ltd 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 "common/application_data.h" #include <manifest_handlers/application_manifest_constants.h> #include <manifest_handlers/widget_config_parser.h> #include <package_manager.h> #include <vector> #include "common/file_utils.h" #include "common/logger.h" #include "common/profiler.h" namespace common { namespace { const char* kPathSeparator = "/"; const char* kConfigXml = "config.xml"; const char* kResWgtPath = "res/wgt"; static std::string GetPackageIdByAppId(const std::string& appid) { char* pkgid = NULL; package_manager_get_package_id_by_app_id(appid.c_str(), &pkgid); std::unique_ptr<char, decltype(std::free)*> pkgid_ptr {pkgid, std::free}; if (pkgid != NULL) { return std::string(pkgid_ptr.get()); } else { LOGGER(ERROR) << "Failed to get package id"; return std::string(); } } static std::string GetPackageRootPath(const std::string& pkgid) { package_info_h pkg_info = NULL; if (package_manager_get_package_info( pkgid.c_str(), &pkg_info) != PACKAGE_MANAGER_ERROR_NONE) { return std::string(); } char* pkg_root_path = NULL; package_info_get_root_path(pkg_info, &pkg_root_path); std::unique_ptr<char, decltype(std::free)*> path_ptr {pkg_root_path, std::free}; package_info_destroy(pkg_info); if (pkg_root_path != NULL) { return std::string(path_ptr.get()); } else { LOGGER(ERROR) << "Failed to get package root path"; return std::string(); } } } // namespace ApplicationData::ApplicationData(const std::string& appid) : app_id_(appid) { pkg_id_ = GetPackageIdByAppId(appid); if (!pkg_id_.empty()) application_path_ = GetPackageRootPath(pkg_id_) + kPathSeparator + kResWgtPath + kPathSeparator; } ApplicationData::~ApplicationData() {} std::shared_ptr<const wgt::parse::AppControlInfoList> ApplicationData::app_control_info_list() const { return app_control_info_list_; } std::shared_ptr<const wgt::parse::CategoryInfoList> ApplicationData::category_info_list() const { return category_info_list_; } std::shared_ptr<const wgt::parse::MetaDataInfo> ApplicationData::meta_data_info() const { return meta_data_info_; } std::shared_ptr<const wgt::parse::AllowedNavigationInfo> ApplicationData::allowed_navigation_info() const { return allowed_navigation_info_; } std::shared_ptr<const wgt::parse::PermissionsInfo> ApplicationData::permissions_info() const { return permissions_info_; } std::shared_ptr<const wgt::parse::SettingInfo> ApplicationData::setting_info() const { return setting_info_; } std::shared_ptr<const wgt::parse::SplashScreenInfo> ApplicationData::splash_screen_info() const { return splash_screen_info_; } std::shared_ptr<const wgt::parse::TizenApplicationInfo> ApplicationData::tizen_application_info() const { return tizen_application_info_; } std::shared_ptr<const wgt::parse::WidgetInfo> ApplicationData::widget_info() const { return widget_info_; } std::shared_ptr<const wgt::parse::ContentInfo> ApplicationData::content_info() const { return content_info_; } std::shared_ptr<const wgt::parse::WarpInfo> ApplicationData::warp_info() const { return warp_info_; } std::shared_ptr<const wgt::parse::CSPInfo> ApplicationData::csp_info() const { return csp_info_; } std::shared_ptr<const wgt::parse::CSPInfo> ApplicationData::csp_report_info() const { return csp_report_info_; } bool ApplicationData::LoadManifestData() { SCOPE_PROFILE(); std::string config_xml_path(application_path_ + kConfigXml); if (!utils::Exists(config_xml_path)) { LOGGER(ERROR) << "Failed to load manifest data : No such file '" << config_xml_path << "'."; return false; } std::unique_ptr<wgt::parse::WidgetConfigParser> widget_config_parser; widget_config_parser.reset(new wgt::parse::WidgetConfigParser()); if (!widget_config_parser->ParseManifest(config_xml_path)) { LOGGER(ERROR) << "Failed to load widget config parser data: " << widget_config_parser->GetErrorMessage(); return false; } app_control_info_list_ = std::static_pointer_cast<const wgt::parse::AppControlInfoList>( widget_config_parser->GetManifestData( wgt::parse::AppControlInfo::Key())); category_info_list_ = std::static_pointer_cast<const wgt::parse::CategoryInfoList>( widget_config_parser->GetManifestData( wgt::parse::CategoryInfoList::Key())); meta_data_info_ = std::static_pointer_cast<const wgt::parse::MetaDataInfo>( widget_config_parser->GetManifestData( wgt::parse::MetaDataInfo::Key())); allowed_navigation_info_ = std::static_pointer_cast<const wgt::parse::AllowedNavigationInfo>( widget_config_parser->GetManifestData( wgt::parse::AllowedNavigationInfo::Key())); permissions_info_ = std::static_pointer_cast<const wgt::parse::PermissionsInfo>( widget_config_parser->GetManifestData( wgt::parse::PermissionsInfo::Key())); setting_info_ = std::static_pointer_cast<const wgt::parse::SettingInfo>( widget_config_parser->GetManifestData( wgt::parse::SettingInfo::Key())); splash_screen_info_ = std::static_pointer_cast<const wgt::parse::SplashScreenInfo>( widget_config_parser->GetManifestData( wgt::parse::SplashScreenInfo::Key())); tizen_application_info_ = std::static_pointer_cast<const wgt::parse::TizenApplicationInfo>( widget_config_parser->GetManifestData( wgt::parse::TizenApplicationInfo::Key())); widget_info_ = std::static_pointer_cast<const wgt::parse::WidgetInfo>( widget_config_parser->GetManifestData( wgt::parse::WidgetInfo::Key())); content_info_ = std::static_pointer_cast<const wgt::parse::ContentInfo>( widget_config_parser->GetManifestData( wgt::parse::ContentInfo::Key())); warp_info_ = std::static_pointer_cast<const wgt::parse::WarpInfo>( widget_config_parser->GetManifestData( wgt::parse::WarpInfo::Key())); csp_info_ = std::static_pointer_cast<const wgt::parse::CSPInfo>( widget_config_parser->GetManifestData( wgt::parse::CSPInfo::Key())); csp_report_info_ = std::static_pointer_cast<const wgt::parse::CSPInfo>( widget_config_parser->GetManifestData( wgt::parse::CSPInfo::Report_only_key())); // Set default empty object if (widget_info_.get() == NULL) { widget_info_.reset(new wgt::parse::WidgetInfo); } if (setting_info_.get() == NULL) { setting_info_.reset(new wgt::parse::SettingInfo); } return true; } } // namespace common <|endoftext|>
<commit_before><commit_msg>warp blend updates<commit_after><|endoftext|>
<commit_before>// This file is part of the "x0" project, http://xzero.io/ // (c) 2009-2014 Christian Parpart <trapni@gmail.com> // // Licensed under the MIT License (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of // the License at: http://opensource.org/licenses/MIT #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <signal.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/wait.h> #include <fcntl.h> #include <initializer_list> #include <vector> #include <fstream> #include <iostream> #include <string> // supervisor [-f|--fork] [-p|--pidfile=PATH] -- cmd ... // // -f,--fork whether to fork the supervisor process into background // -p,--pidfile=PATH location to store the current supervisor PID // -r,--restart Automatically restart program, if crashed. // -c,--cgroups Use cgroups to track PIDs // // Examples: // supervisor /usr/sbin/x0d --no-fork // supervisor -p /var/run/xzero/supervisor.pid -- /usr/sbin/x0d --no-fork class PidTracker { public: PidTracker(); ~PidTracker(); void add(int pid); std::vector<int> get(); void dump(); }; PidTracker::PidTracker() { char path[80]; snprintf(path, sizeof(path), "/sys/fs/cgroup/cpu/%d.supervisor", getpid()); int rv = mkdir(path, 0777); if (rv < 0) { perror("PidTracker: mkdir"); } } PidTracker::~PidTracker() { char path[80]; snprintf(path, sizeof(path), "/sys/fs/cgroup/cpu/%d.supervisor", getpid()); rmdir(path); } void PidTracker::add(int pid) { char path[80]; snprintf(path, sizeof(path), "/sys/fs/cgroup/cpu/%d.supervisor/tasks", getpid()); char buf[64]; ssize_t n = snprintf(buf, sizeof(buf), "%d", pid); int fd = open(path, O_WRONLY); write(fd, buf, n); close(fd); } std::vector<int> PidTracker::get() { std::vector<int> result; char path[80]; snprintf(path, sizeof(path), "/sys/fs/cgroup/cpu/%d.supervisor/tasks", getpid()); std::ifstream tasksFile(path); std::string line; while (std::getline(tasksFile, line)) { result.push_back(stoi(line)); } return result; } void PidTracker::dump() { printf("PID tracking: "); const auto pids = get(); for (int pid: pids) { printf(" %d", pid); } printf("\n"); } static PidTracker pidTracker; static int childPid = 0; static int lastSignum = 0; static std::string programPath; static std::vector<std::string> programArgs; static int retryCount = 5; void runProgram() { printf("Running program...\n"); pid_t pid = fork(); if (pid < 0) { fprintf(stderr, "fork failed. %s\n", strerror(errno)); abort(); } else if (pid > 0) { // parent childPid = pid; pidTracker.add(pid); printf("supervisor: child pid is %d\n", pid); pidTracker.dump(); } else { // child std::vector<char*> argv; argv.push_back(const_cast<char*>(programPath.c_str())); for (const std::string& arg : programArgs) { argv.push_back(const_cast<char*>(arg.c_str())); } argv.push_back(nullptr); execvp(programPath.c_str(), argv.data()); fprintf(stderr, "execvp failed. %s\n", strerror(errno)); abort(); } } void restartProgram() { pidTracker.dump(); const auto pids = pidTracker.get(); if (pids.size() == 1) { childPid = pids[0]; printf("supervisor: reattaching to child PID %d\n", childPid); return; } printf("Restarting program (retry count: %d)\n", retryCount); if (retryCount == 0) { throw EXIT_FAILURE; } retryCount--; runProgram(); } void sighandler(int signum) { lastSignum = signum; if (childPid) { printf("Signal %s (%d) received. Forwarding to child PID %d.\n", strsignal(signum), signum, childPid); // forward to child process kill(childPid, signum); } } bool parseArgs(int argc, const char* argv[]) { if (argc <= 1) { fprintf(stderr, "usage error\n"); return false; } int i = 1; programPath = argv[i]; i++; while (argv[i] != nullptr) { programArgs.push_back(argv[i]); i++; } return true; } int main(int argc, const char* argv[]) { try { if (!parseArgs(argc, argv)) return 1; printf("Installing signal handler...\n"); for (int sig : {SIGINT, SIGTERM, SIGQUIT, SIGHUP}) { signal(sig, &sighandler); } // if (setsid() < 0) { // fprintf(stderr, "Error creating session. %s\n", strerror(errno)); // return EXIT_FAILURE; // } if (setpgrp() < 0) { fprintf(stderr, "Error creating process group. %s\n", strerror(errno)); return EXIT_FAILURE; } runProgram(); for (;;) { int status = 0; if (waitpid(childPid, &status, 0) < 0) { perror("waitpid"); throw EXIT_FAILURE; } if (WIFEXITED(status)) { printf("Child %d terminated with exit code %d\n", childPid, WEXITSTATUS(status)); restartProgram(); } if (WIFSIGNALED(status)) { printf("Child %d terminated with signal %s (%d)\n", childPid, strsignal(WTERMSIG(status)), WTERMSIG(status)); restartProgram(); } fprintf(stderr, "Child %d terminated. Status code %d\n", childPid, status); restartProgram(); } } catch (int exitCode) { return exitCode; } } // vim:ts=2:sw=2 <commit_msg>supervisor: add prctl(PR_SET_CHILD_SUBREAPER) to make sure we catch them all<commit_after>// This file is part of the "x0" project, http://xzero.io/ // (c) 2009-2014 Christian Parpart <trapni@gmail.com> // // Licensed under the MIT License (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of // the License at: http://opensource.org/licenses/MIT #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <signal.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/wait.h> #include <sys/prctl.h> #include <fcntl.h> #include <initializer_list> #include <vector> #include <fstream> #include <iostream> #include <string> // supervisor [-f|--fork] [-p|--pidfile=PATH] -- cmd ... // // -f,--fork whether to fork the supervisor process into background // -p,--pidfile=PATH location to store the current supervisor PID // -r,--restart Automatically restart program, if crashed. // -c,--cgroups Use cgroups to track PIDs // // Examples: // supervisor /usr/sbin/x0d --no-fork // supervisor -p /var/run/xzero/supervisor.pid -- /usr/sbin/x0d --no-fork class PidTracker { public: PidTracker(); ~PidTracker(); void add(int pid); std::vector<int> get(); void dump(); }; PidTracker::PidTracker() { char path[80]; snprintf(path, sizeof(path), "/sys/fs/cgroup/cpu/%d.supervisor", getpid()); int rv = mkdir(path, 0777); if (rv < 0) { perror("PidTracker: mkdir"); } } PidTracker::~PidTracker() { char path[80]; snprintf(path, sizeof(path), "/sys/fs/cgroup/cpu/%d.supervisor", getpid()); rmdir(path); } void PidTracker::add(int pid) { char path[80]; snprintf(path, sizeof(path), "/sys/fs/cgroup/cpu/%d.supervisor/tasks", getpid()); char buf[64]; ssize_t n = snprintf(buf, sizeof(buf), "%d", pid); int fd = open(path, O_WRONLY); write(fd, buf, n); close(fd); } std::vector<int> PidTracker::get() { std::vector<int> result; char path[80]; snprintf(path, sizeof(path), "/sys/fs/cgroup/cpu/%d.supervisor/tasks", getpid()); std::ifstream tasksFile(path); std::string line; while (std::getline(tasksFile, line)) { result.push_back(stoi(line)); } return result; } void PidTracker::dump() { printf("PID tracking: "); const auto pids = get(); for (int pid : pids) { printf(" %d", pid); } printf("\n"); } static PidTracker pidTracker; static int childPid = 0; static int lastSignum = 0; static std::string programPath; static std::vector<std::string> programArgs; static int retryCount = 5; void runProgram() { printf("Running program...\n"); pid_t pid = fork(); if (pid < 0) { fprintf(stderr, "fork failed. %s\n", strerror(errno)); abort(); } else if (pid > 0) { // parent childPid = pid; pidTracker.add(pid); printf("supervisor: child pid is %d\n", pid); pidTracker.dump(); if (prctl(PR_SET_CHILD_SUBREAPER, 1) < 0) { fprintf(stderr, "supervisor: prctl(PR_SET_CHILD_SUBREAPER) failed. %s", strerror(errno)); } } else { // child std::vector<char*> argv; argv.push_back(const_cast<char*>(programPath.c_str())); for (const std::string& arg : programArgs) { argv.push_back(const_cast<char*>(arg.c_str())); } argv.push_back(nullptr); execvp(programPath.c_str(), argv.data()); fprintf(stderr, "execvp failed. %s\n", strerror(errno)); abort(); } } void restartProgram() { pidTracker.dump(); const auto pids = pidTracker.get(); if (pids.size() == 1) { childPid = pids[0]; printf("supervisor: reattaching to child PID %d\n", childPid); return; } printf("Restarting program (retry count: %d)\n", retryCount); if (retryCount == 0) { throw EXIT_FAILURE; } retryCount--; runProgram(); } void sighandler(int signum) { lastSignum = signum; if (childPid) { printf("Signal %s (%d) received. Forwarding to child PID %d.\n", strsignal(signum), signum, childPid); // forward to child process kill(childPid, signum); } } bool parseArgs(int argc, const char* argv[]) { if (argc <= 1) { fprintf(stderr, "usage error\n"); return false; } int i = 1; programPath = argv[i]; i++; while (argv[i] != nullptr) { programArgs.push_back(argv[i]); i++; } return true; } int main(int argc, const char* argv[]) { try { if (!parseArgs(argc, argv)) return 1; printf("Installing signal handler...\n"); for (int sig : {SIGINT, SIGTERM, SIGQUIT, SIGHUP}) { signal(sig, &sighandler); } // if (setsid() < 0) { // fprintf(stderr, "Error creating session. %s\n", strerror(errno)); // return EXIT_FAILURE; // } if (setpgrp() < 0) { fprintf(stderr, "Error creating process group. %s\n", strerror(errno)); return EXIT_FAILURE; } runProgram(); for (;;) { int status = 0; if (waitpid(childPid, &status, 0) < 0) { perror("waitpid"); throw EXIT_FAILURE; } if (WIFEXITED(status)) { printf("Child %d terminated with exit code %d\n", childPid, WEXITSTATUS(status)); restartProgram(); } if (WIFSIGNALED(status)) { printf("Child %d terminated with signal %s (%d)\n", childPid, strsignal(WTERMSIG(status)), WTERMSIG(status)); restartProgram(); } fprintf(stderr, "Child %d terminated. Status code %d\n", childPid, status); restartProgram(); } } catch (int exitCode) { return exitCode; } } // vim:ts=2:sw=2 <|endoftext|>
<commit_before>#include "locked_hash.h" using namespace std; LockedHash::LockedHash(UInt64 size) : _size(size), _bins(new Bucket[size]), _locks(new Lock[size]) { } LockedHash::~LockedHash() { delete [] _bins; delete [] _locks; } pair<bool, UInt64> LockedHash::find(UInt64 key) { UInt64 index = key % _size; pair<bool, UInt64> res; res.first = false; _locks[index].acquire(); map<UInt64,UInt64>::iterator iter = _bins[index].find(key); if (iter != _bins[index].end()) { res.first = true; res.second = iter->second; } _locks[index].release(); return res; } void LockedHash::remove(UInt64 key) { UInt64 index = key % _size; _locks[index].acquire(); map<UInt64,UInt64>::iterator iter = _bins[index].find(key); if (iter != _bins[index].end()) { _bins[index].erase(iter); } _locks[index].release(); } bool LockedHash::insert(UInt64 key, UInt64 value) { UInt64 index = key % _size; _locks[index].acquire(); _bins[index].insert(make_pair(key, value)); _locks[index].release(); return true; } #ifdef DEBUG_LOCKED_HASH int main(int argc, char* argv[]) { LockedHash hash(100); UInt64 ids[4] = {1001, 1050, 1011, 1099}; for (int i = 0; i < 4; i++) hash.insert(ids[i], i); for (int i = 3; i >= 0; i--) assert(hash.find(ids[i]).first == true); cerr << "Test 1 passed" << endl; cerr << "Test 2 should fail in assertion" << endl; ids[3] = ids[0] + 100; for (int i = 0; i < 4; i++) hash.insert(ids[i], i); cerr << "All tests passed" << endl; return 0; } #endif <commit_msg>[locked_hash] **FIXME** Don't delete data in dtor. This is a huge hack to avoid segfault in CoreManager dtor.<commit_after>#include "locked_hash.h" using namespace std; LockedHash::LockedHash(UInt64 size) : _size(size), _bins(new Bucket[size]), _locks(new Lock[size]) { } LockedHash::~LockedHash() { // FIXME: For some reason, this seg faults. Only deleted during // shutdown, so maybe this OK? But still a huge hack. // delete [] _bins; // delete [] _locks; } pair<bool, UInt64> LockedHash::find(UInt64 key) { UInt64 index = key % _size; pair<bool, UInt64> res; res.first = false; _locks[index].acquire(); map<UInt64,UInt64>::iterator iter = _bins[index].find(key); if (iter != _bins[index].end()) { res.first = true; res.second = iter->second; } _locks[index].release(); return res; } void LockedHash::remove(UInt64 key) { UInt64 index = key % _size; _locks[index].acquire(); map<UInt64,UInt64>::iterator iter = _bins[index].find(key); if (iter != _bins[index].end()) { _bins[index].erase(iter); } _locks[index].release(); } bool LockedHash::insert(UInt64 key, UInt64 value) { UInt64 index = key % _size; _locks[index].acquire(); _bins[index].insert(make_pair(key, value)); _locks[index].release(); return true; } #ifdef DEBUG_LOCKED_HASH int main(int argc, char* argv[]) { LockedHash hash(100); UInt64 ids[4] = {1001, 1050, 1011, 1099}; for (int i = 0; i < 4; i++) hash.insert(ids[i], i); for (int i = 3; i >= 0; i--) assert(hash.find(ids[i]).first == true); cerr << "Test 1 passed" << endl; cerr << "Test 2 should fail in assertion" << endl; ids[3] = ids[0] + 100; for (int i = 0; i < 4; i++) hash.insert(ids[i], i); cerr << "All tests passed" << endl; return 0; } #endif <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: objectcontact.hxx,v $ * $Revision: 1.13 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _SDR_CONTACT_OBJECTCONTACT_HXX #define _SDR_CONTACT_OBJECTCONTACT_HXX #include <svx/sdr/animation/objectanimator.hxx> #include "svx/svxdllapi.h" #include <drawinglayer/geometry/viewinformation2d.hxx> ////////////////////////////////////////////////////////////////////////////// // predeclarations class SetOfByte; class Rectangle; class SdrPageView; class OutputDevice; namespace sdr { namespace contact { class DisplayInfo; class ViewContact; class ViewObjectContactRedirector; }} namespace sdr { namespace event { class TimerEventHandler; }} namespace basegfx { class B2DRange; class B2DHomMatrix; } ////////////////////////////////////////////////////////////////////////////// namespace sdr { namespace contact { class SVX_DLLPUBLIC ObjectContact { private: // make ViewObjectContact a friend to exclusively allow it to use // AddViewObjectContact/RemoveViewObjectContact friend class ViewObjectContact; // All VOCs which are created using this OC, thus remembering this OC // as a reference. All those VOCs need to be deleted when the OC goes down. // Registering and de-registering is done in the VOC constructors/destructors. std::vector< ViewObjectContact* > maViewObjectContactVector; // A new ViewObjectContact was created and shall be remembered. void AddViewObjectContact(ViewObjectContact& rVOContact); // A ViewObjectContact was deleted and shall be forgotten. virtual void RemoveViewObjectContact(ViewObjectContact& rVOContact); // the primitiveAnimator which is used if this View and/or the contained primitives // support animatedSwitchPrimitives sdr::animation::primitiveAnimator maPrimitiveAnimator; // the EventHandler for e.g. asynchronious loading of graphics sdr::event::TimerEventHandler* mpEventHandler; // The redirector. If set it is used to pipe all supported calls // to the redirector. When one is set at the ViewContact too, the one at // the ViewContact will win. ViewObjectContactRedirector* mpViewObjectContactRedirector; // the Primitive2DParameters containing view information drawinglayer::geometry::ViewInformation2D maViewInformation2D; // bitfield // flag for preview renderer unsigned mbIsPreviewRenderer : 1; // method to create a EventHandler. Needs to give a result. sdr::event::TimerEventHandler* CreateEventHandler(); protected: // Interface to allow derivates to travel over the registered VOC's sal_uInt32 getViewObjectContactCount() const { return maViewObjectContactVector.size(); } ViewObjectContact* getViewObjectContact(sal_uInt32 a) const { return maViewObjectContactVector[a]; } // interface to allow derivates to set PreviewRenderer flag void setPreviewRenderer(bool bNew) { mbIsPreviewRenderer = bNew; } // interface to allow derivates to set ViewInformation2D void updateViewInformation2D(const drawinglayer::geometry::ViewInformation2D& rViewInformation2D) { maViewInformation2D = rViewInformation2D; } public: // basic constructor ObjectContact(); virtual ~ObjectContact(); // LazyInvalidate request. This is used from the VOCs to mark that they // got invalidated by an ActionCanged() call. An active view needs to remember // this and take action on it. Default implementation directly calls back // triggerLazyInvalidate() wich promptly handles the request virtual void setLazyInvalidate(ViewObjectContact& rVOC); // call this to support evtl. preparations for repaint. Default does nothing virtual void PrepareProcessDisplay(); // Process the whole displaying virtual void ProcessDisplay(DisplayInfo& rDisplayInfo); // test if visualizing of entered groups is switched on at all. Default // implementation returns sal_False. virtual bool DoVisualizeEnteredGroup() const; // get active group's (the entered group) ViewContact virtual const ViewContact* getActiveViewContact() const; // Invalidate given rectangle at the window/output which is represented by // this ObjectContact. Default does nothing. virtual void InvalidatePartOfView(const basegfx::B2DRange& rRange) const; // Get info if given Rectangle is visible in this view virtual bool IsAreaVisible(const basegfx::B2DRange& rRange) const; // Get info about the need to visualize GluePoints. The default // is that it is not necessary. virtual bool AreGluePointsVisible() const; // method to get the primitiveAnimator sdr::animation::primitiveAnimator& getPrimitiveAnimator(); // method to get the EventHandler. It will // return a existing one or create a new one using CreateEventHandler(). sdr::event::TimerEventHandler& GetEventHandler() const; // delete the EventHandler void DeleteEventHandler(); // test if there is an EventHandler without creating one on demand bool HasEventHandler() const; // check if text animation is allowed. Default is sal_true. virtual bool IsTextAnimationAllowed() const; // check if graphic animation is allowed. Default is sal_true. virtual bool IsGraphicAnimationAllowed() const; // check if asynchronious graphis loading is allowed. Default is sal_False. virtual bool IsAsynchronGraphicsLoadingAllowed() const; // access to ViewObjectContactRedirector ViewObjectContactRedirector* GetViewObjectContactRedirector() const; void SetViewObjectContactRedirector(ViewObjectContactRedirector* pNew); // check if buffering of MasterPages is allowed. Default is sal_False. virtual bool IsMasterPageBufferingAllowed() const; // print? Default is false virtual bool isOutputToPrinter() const; // window? Default is true virtual bool isOutputToWindow() const; // VirtualDevice? Default is false virtual bool isOutputToVirtualDevice() const; // recording MetaFile? Default is false virtual bool isOutputToRecordingMetaFile() const; // pdf export? Default is false virtual bool isOutputToPDFFile() const; // gray display mode virtual bool isDrawModeGray() const; // gray display mode virtual bool isDrawModeBlackWhite() const; // high contrast display mode virtual bool isDrawModeHighContrast() const; // check if this is a preview renderer. Default is sal_False. bool IsPreviewRenderer() const { return mbIsPreviewRenderer; } // get Primitive2DParameters for this view const drawinglayer::geometry::ViewInformation2D& getViewInformation2D() const { return maViewInformation2D; } // access to SdrPageView. May return 0L like the default implementations do. Needs to be overloaded as needed. virtual SdrPageView* TryToGetSdrPageView() const; // access to OutputDevice. May return 0L like the default implementations do. Needs to be overloaded as needed. virtual OutputDevice* TryToGetOutputDevice() const; // reset ViewPort at internal ViewInformation2D. This is needed when the OC is used // not for ProcessDisplay() but to get a VOC associated with it. When trying to get // a sequence of primitives from the VOC then, the last initialized ViewPort from // the last ProcessDisplay() is used for geometric visibility testing. If this is not // wanted (like in such cases) this method is used. It will reuse the current // ViewInformation2D, but clear the ViewPort (no ViewPort means all is visible) void resetViewPort(); }; } // end of namespace contact } // end of namespace sdr ////////////////////////////////////////////////////////////////////////////// #endif //_SDR_CONTACT_OBJECTCONTACT_HXX // eof <commit_msg>#i97509# corrected comment<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: objectcontact.hxx,v $ * $Revision: 1.13 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _SDR_CONTACT_OBJECTCONTACT_HXX #define _SDR_CONTACT_OBJECTCONTACT_HXX #include <svx/sdr/animation/objectanimator.hxx> #include "svx/svxdllapi.h" #include <drawinglayer/geometry/viewinformation2d.hxx> ////////////////////////////////////////////////////////////////////////////// // predeclarations class SetOfByte; class Rectangle; class SdrPageView; class OutputDevice; namespace sdr { namespace contact { class DisplayInfo; class ViewContact; class ViewObjectContactRedirector; }} namespace sdr { namespace event { class TimerEventHandler; }} namespace basegfx { class B2DRange; class B2DHomMatrix; } ////////////////////////////////////////////////////////////////////////////// namespace sdr { namespace contact { class SVX_DLLPUBLIC ObjectContact { private: // make ViewObjectContact a friend to exclusively allow it to use // AddViewObjectContact/RemoveViewObjectContact friend class ViewObjectContact; // All VOCs which are created using this OC, thus remembering this OC // as a reference. All those VOCs need to be deleted when the OC goes down. // Registering and de-registering is done in the VOC constructors/destructors. std::vector< ViewObjectContact* > maViewObjectContactVector; // A new ViewObjectContact was created and shall be remembered. void AddViewObjectContact(ViewObjectContact& rVOContact); // A ViewObjectContact was deleted and shall be forgotten. virtual void RemoveViewObjectContact(ViewObjectContact& rVOContact); // the primitiveAnimator which is used if this View and/or the contained primitives // support animatedSwitchPrimitives sdr::animation::primitiveAnimator maPrimitiveAnimator; // the EventHandler for e.g. asynchronious loading of graphics sdr::event::TimerEventHandler* mpEventHandler; // The redirector. If set it is used to pipe all supported calls // to the redirector ViewObjectContactRedirector* mpViewObjectContactRedirector; // the Primitive2DParameters containing view information drawinglayer::geometry::ViewInformation2D maViewInformation2D; // bitfield // flag for preview renderer unsigned mbIsPreviewRenderer : 1; // method to create a EventHandler. Needs to give a result. sdr::event::TimerEventHandler* CreateEventHandler(); protected: // Interface to allow derivates to travel over the registered VOC's sal_uInt32 getViewObjectContactCount() const { return maViewObjectContactVector.size(); } ViewObjectContact* getViewObjectContact(sal_uInt32 a) const { return maViewObjectContactVector[a]; } // interface to allow derivates to set PreviewRenderer flag void setPreviewRenderer(bool bNew) { mbIsPreviewRenderer = bNew; } // interface to allow derivates to set ViewInformation2D void updateViewInformation2D(const drawinglayer::geometry::ViewInformation2D& rViewInformation2D) { maViewInformation2D = rViewInformation2D; } public: // basic constructor ObjectContact(); virtual ~ObjectContact(); // LazyInvalidate request. This is used from the VOCs to mark that they // got invalidated by an ActionCanged() call. An active view needs to remember // this and take action on it. Default implementation directly calls back // triggerLazyInvalidate() wich promptly handles the request virtual void setLazyInvalidate(ViewObjectContact& rVOC); // call this to support evtl. preparations for repaint. Default does nothing virtual void PrepareProcessDisplay(); // Process the whole displaying virtual void ProcessDisplay(DisplayInfo& rDisplayInfo); // test if visualizing of entered groups is switched on at all. Default // implementation returns sal_False. virtual bool DoVisualizeEnteredGroup() const; // get active group's (the entered group) ViewContact virtual const ViewContact* getActiveViewContact() const; // Invalidate given rectangle at the window/output which is represented by // this ObjectContact. Default does nothing. virtual void InvalidatePartOfView(const basegfx::B2DRange& rRange) const; // Get info if given Rectangle is visible in this view virtual bool IsAreaVisible(const basegfx::B2DRange& rRange) const; // Get info about the need to visualize GluePoints. The default // is that it is not necessary. virtual bool AreGluePointsVisible() const; // method to get the primitiveAnimator sdr::animation::primitiveAnimator& getPrimitiveAnimator(); // method to get the EventHandler. It will // return a existing one or create a new one using CreateEventHandler(). sdr::event::TimerEventHandler& GetEventHandler() const; // delete the EventHandler void DeleteEventHandler(); // test if there is an EventHandler without creating one on demand bool HasEventHandler() const; // check if text animation is allowed. Default is sal_true. virtual bool IsTextAnimationAllowed() const; // check if graphic animation is allowed. Default is sal_true. virtual bool IsGraphicAnimationAllowed() const; // check if asynchronious graphis loading is allowed. Default is sal_False. virtual bool IsAsynchronGraphicsLoadingAllowed() const; // access to ViewObjectContactRedirector ViewObjectContactRedirector* GetViewObjectContactRedirector() const; void SetViewObjectContactRedirector(ViewObjectContactRedirector* pNew); // check if buffering of MasterPages is allowed. Default is sal_False. virtual bool IsMasterPageBufferingAllowed() const; // print? Default is false virtual bool isOutputToPrinter() const; // window? Default is true virtual bool isOutputToWindow() const; // VirtualDevice? Default is false virtual bool isOutputToVirtualDevice() const; // recording MetaFile? Default is false virtual bool isOutputToRecordingMetaFile() const; // pdf export? Default is false virtual bool isOutputToPDFFile() const; // gray display mode virtual bool isDrawModeGray() const; // gray display mode virtual bool isDrawModeBlackWhite() const; // high contrast display mode virtual bool isDrawModeHighContrast() const; // check if this is a preview renderer. Default is sal_False. bool IsPreviewRenderer() const { return mbIsPreviewRenderer; } // get Primitive2DParameters for this view const drawinglayer::geometry::ViewInformation2D& getViewInformation2D() const { return maViewInformation2D; } // access to SdrPageView. May return 0L like the default implementations do. Needs to be overloaded as needed. virtual SdrPageView* TryToGetSdrPageView() const; // access to OutputDevice. May return 0L like the default implementations do. Needs to be overloaded as needed. virtual OutputDevice* TryToGetOutputDevice() const; // reset ViewPort at internal ViewInformation2D. This is needed when the OC is used // not for ProcessDisplay() but to get a VOC associated with it. When trying to get // a sequence of primitives from the VOC then, the last initialized ViewPort from // the last ProcessDisplay() is used for geometric visibility testing. If this is not // wanted (like in such cases) this method is used. It will reuse the current // ViewInformation2D, but clear the ViewPort (no ViewPort means all is visible) void resetViewPort(); }; } // end of namespace contact } // end of namespace sdr ////////////////////////////////////////////////////////////////////////////// #endif //_SDR_CONTACT_OBJECTCONTACT_HXX // eof <|endoftext|>
<commit_before>/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "include/core/SkData.h" #include "include/core/SkStream.h" #include "src/core/SkFontDescriptor.h" enum { kInvalid = 0x00, // these must match the sfnt 'name' enums kFontFamilyName = 0x01, kFullName = 0x04, kPostscriptName = 0x06, // These count backwards from 0xFF, so as not to collide with the SFNT // defines for names in its 'name' table. kFontVariation = 0xFA, kFontAxes = 0xFB, // Only picture version 79 and eariler. kFontIndex = 0xFD, kSentinel = 0xFF, }; SkFontDescriptor::SkFontDescriptor() { } static bool SK_WARN_UNUSED_RESULT read_string(SkStream* stream, SkString* string) { size_t length; if (!stream->readPackedUInt(&length)) { return false; } if (length > 0) { string->resize(length); if (stream->read(string->writable_str(), length) != length) { return false; } } return true; } static bool write_string(SkWStream* stream, const SkString& string, uint32_t id) { if (string.isEmpty()) { return true; } return stream->writePackedUInt(id) && stream->writePackedUInt(string.size()) && stream->write(string.c_str(), string.size()); } static bool write_uint(SkWStream* stream, size_t n, uint32_t id) { return stream->writePackedUInt(id) && stream->writePackedUInt(n); } static size_t SK_WARN_UNUSED_RESULT read_id(SkStream* stream) { size_t i; if (!stream->readPackedUInt(&i)) { return kInvalid; } return i; } std::unique_ptr<SkFontData> SkFontDescriptor::maybeAsSkFontData() { if (!fVariationDataIsOldAndBad) { return nullptr; } SkFontArguments args; args.setCollectionIndex(this->getCollectionIndex()); args.setVariationDesignPosition({this->getVariation(), this->getVariationCoordinateCount()}); return std::make_unique<SkFontData>(this->dupStream(), args); } bool SkFontDescriptor::Deserialize(SkStream* stream, SkFontDescriptor* result) { size_t styleBits; if (!stream->readPackedUInt(&styleBits)) { return false; } result->fStyle = SkFontStyle((styleBits >> 16) & 0xFFFF, (styleBits >> 8 ) & 0xFF, static_cast<SkFontStyle::Slant>(styleBits & 0xFF)); bool variationDataIsNewAndGood = false; result->fVariationDataIsOldAndBad = false; SkFixed oldBadVariationValue; size_t coordinateCount; using CoordinateCountType = decltype(result->fCoordinateCount); size_t index; using CollectionIndexType = decltype(result->fCollectionIndex); for (size_t id; (id = read_id(stream)) != kSentinel;) { switch (id) { case kFontFamilyName: if (!read_string(stream, &result->fFamilyName)) { return false; } break; case kFullName: if (!read_string(stream, &result->fFullName)) { return false; } break; case kPostscriptName: if (!read_string(stream, &result->fPostscriptName)) { return false; } break; case kFontAxes: if (variationDataIsNewAndGood) { if (!stream->readPackedUInt(&coordinateCount)) { return false; } for (size_t i = 0; i < coordinateCount; ++i) { if (!stream->readS32(&oldBadVariationValue)) { return false; } } } else { if (!stream->readPackedUInt(&coordinateCount)) { return false; } if (!SkTFitsIn<CoordinateCountType>(coordinateCount)) { return false; } result->fCoordinateCount = SkTo<CoordinateCountType>(coordinateCount); result->fVariation.reset(coordinateCount); for (size_t i = 0; i < coordinateCount; ++i) { if (!stream->readS32(&oldBadVariationValue)) { return false; } result->fVariation[i].axis = 0; result->fVariation[i].value = SkFixedToScalar(oldBadVariationValue); } result->fVariationDataIsOldAndBad = true; } break; case kFontVariation: if (!stream->readPackedUInt(&coordinateCount)) { return false; } if (!SkTFitsIn<CoordinateCountType>(coordinateCount)) { return false; } result->fCoordinateCount = SkTo<CoordinateCountType>(coordinateCount); result->fVariation.reset(coordinateCount); for (size_t i = 0; i < coordinateCount; ++i) { if (!stream->readU32(&result->fVariation[i].axis)) { return false; } if (!stream->readScalar(&result->fVariation[i].value)) { return false; } } variationDataIsNewAndGood = true; result->fVariationDataIsOldAndBad = false; break; case kFontIndex: if (!stream->readPackedUInt(&index)) { return false; } if (!SkTFitsIn<CollectionIndexType>(index)) { return false; } result->fCollectionIndex = SkTo<CollectionIndexType>(index); break; default: SkDEBUGFAIL("Unknown id used by a font descriptor"); return false; } } size_t length; if (!stream->readPackedUInt(&length)) { return false; } if (length > 0) { sk_sp<SkData> data(SkData::MakeUninitialized(length)); if (stream->read(data->writable_data(), length) != length) { SkDEBUGFAIL("Could not read font data"); return false; } result->fStream = SkMemoryStream::Make(std::move(data)); } return true; } void SkFontDescriptor::serialize(SkWStream* stream) const { uint32_t styleBits = (fStyle.weight() << 16) | (fStyle.width() << 8) | (fStyle.slant()); stream->writePackedUInt(styleBits); write_string(stream, fFamilyName, kFontFamilyName); write_string(stream, fFullName, kFullName); write_string(stream, fPostscriptName, kPostscriptName); if (fCollectionIndex) { write_uint(stream, fCollectionIndex, kFontIndex); } if (fCoordinateCount) { write_uint(stream, fCoordinateCount, kFontVariation); for (int i = 0; i < fCoordinateCount; ++i) { stream->write32(fVariation[i].axis); stream->writeScalar(fVariation[i].value); } } stream->writePackedUInt(kSentinel); if (fStream) { std::unique_ptr<SkStreamAsset> fontStream = fStream->duplicate(); size_t length = fontStream->getLength(); stream->writePackedUInt(length); stream->writeStream(fontStream.get(), length); } else { stream->writePackedUInt(0); } } <commit_msg>Cannot create SkFontData with no data.<commit_after>/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "include/core/SkData.h" #include "include/core/SkStream.h" #include "src/core/SkFontDescriptor.h" enum { kInvalid = 0x00, // these must match the sfnt 'name' enums kFontFamilyName = 0x01, kFullName = 0x04, kPostscriptName = 0x06, // These count backwards from 0xFF, so as not to collide with the SFNT // defines for names in its 'name' table. kFontVariation = 0xFA, kFontAxes = 0xFB, // Only picture version 79 and eariler. kFontIndex = 0xFD, kSentinel = 0xFF, }; SkFontDescriptor::SkFontDescriptor() { } static bool SK_WARN_UNUSED_RESULT read_string(SkStream* stream, SkString* string) { size_t length; if (!stream->readPackedUInt(&length)) { return false; } if (length > 0) { string->resize(length); if (stream->read(string->writable_str(), length) != length) { return false; } } return true; } static bool write_string(SkWStream* stream, const SkString& string, uint32_t id) { if (string.isEmpty()) { return true; } return stream->writePackedUInt(id) && stream->writePackedUInt(string.size()) && stream->write(string.c_str(), string.size()); } static bool write_uint(SkWStream* stream, size_t n, uint32_t id) { return stream->writePackedUInt(id) && stream->writePackedUInt(n); } static size_t SK_WARN_UNUSED_RESULT read_id(SkStream* stream) { size_t i; if (!stream->readPackedUInt(&i)) { return kInvalid; } return i; } std::unique_ptr<SkFontData> SkFontDescriptor::maybeAsSkFontData() { if (!fVariationDataIsOldAndBad || !this->hasStream()) { return nullptr; } SkFontArguments args; args.setCollectionIndex(this->getCollectionIndex()); args.setVariationDesignPosition({this->getVariation(), this->getVariationCoordinateCount()}); return std::make_unique<SkFontData>(this->dupStream(), args); } bool SkFontDescriptor::Deserialize(SkStream* stream, SkFontDescriptor* result) { size_t styleBits; if (!stream->readPackedUInt(&styleBits)) { return false; } result->fStyle = SkFontStyle((styleBits >> 16) & 0xFFFF, (styleBits >> 8 ) & 0xFF, static_cast<SkFontStyle::Slant>(styleBits & 0xFF)); bool variationDataIsNewAndGood = false; result->fVariationDataIsOldAndBad = false; SkFixed oldBadVariationValue; size_t coordinateCount; using CoordinateCountType = decltype(result->fCoordinateCount); size_t index; using CollectionIndexType = decltype(result->fCollectionIndex); for (size_t id; (id = read_id(stream)) != kSentinel;) { switch (id) { case kFontFamilyName: if (!read_string(stream, &result->fFamilyName)) { return false; } break; case kFullName: if (!read_string(stream, &result->fFullName)) { return false; } break; case kPostscriptName: if (!read_string(stream, &result->fPostscriptName)) { return false; } break; case kFontAxes: if (variationDataIsNewAndGood) { if (!stream->readPackedUInt(&coordinateCount)) { return false; } for (size_t i = 0; i < coordinateCount; ++i) { if (!stream->readS32(&oldBadVariationValue)) { return false; } } } else { if (!stream->readPackedUInt(&coordinateCount)) { return false; } if (!SkTFitsIn<CoordinateCountType>(coordinateCount)) { return false; } result->fCoordinateCount = SkTo<CoordinateCountType>(coordinateCount); result->fVariation.reset(coordinateCount); for (size_t i = 0; i < coordinateCount; ++i) { if (!stream->readS32(&oldBadVariationValue)) { return false; } result->fVariation[i].axis = 0; result->fVariation[i].value = SkFixedToScalar(oldBadVariationValue); } result->fVariationDataIsOldAndBad = true; } break; case kFontVariation: if (!stream->readPackedUInt(&coordinateCount)) { return false; } if (!SkTFitsIn<CoordinateCountType>(coordinateCount)) { return false; } result->fCoordinateCount = SkTo<CoordinateCountType>(coordinateCount); result->fVariation.reset(coordinateCount); for (size_t i = 0; i < coordinateCount; ++i) { if (!stream->readU32(&result->fVariation[i].axis)) { return false; } if (!stream->readScalar(&result->fVariation[i].value)) { return false; } } variationDataIsNewAndGood = true; result->fVariationDataIsOldAndBad = false; break; case kFontIndex: if (!stream->readPackedUInt(&index)) { return false; } if (!SkTFitsIn<CollectionIndexType>(index)) { return false; } result->fCollectionIndex = SkTo<CollectionIndexType>(index); break; default: SkDEBUGFAIL("Unknown id used by a font descriptor"); return false; } } size_t length; if (!stream->readPackedUInt(&length)) { return false; } if (length > 0) { sk_sp<SkData> data(SkData::MakeUninitialized(length)); if (stream->read(data->writable_data(), length) != length) { SkDEBUGFAIL("Could not read font data"); return false; } result->fStream = SkMemoryStream::Make(std::move(data)); } return true; } void SkFontDescriptor::serialize(SkWStream* stream) const { uint32_t styleBits = (fStyle.weight() << 16) | (fStyle.width() << 8) | (fStyle.slant()); stream->writePackedUInt(styleBits); write_string(stream, fFamilyName, kFontFamilyName); write_string(stream, fFullName, kFullName); write_string(stream, fPostscriptName, kPostscriptName); if (fCollectionIndex) { write_uint(stream, fCollectionIndex, kFontIndex); } if (fCoordinateCount) { write_uint(stream, fCoordinateCount, kFontVariation); for (int i = 0; i < fCoordinateCount; ++i) { stream->write32(fVariation[i].axis); stream->writeScalar(fVariation[i].value); } } stream->writePackedUInt(kSentinel); if (fStream) { std::unique_ptr<SkStreamAsset> fontStream = fStream->duplicate(); size_t length = fontStream->getLength(); stream->writePackedUInt(length); stream->writeStream(fontStream.get(), length); } else { stream->writePackedUInt(0); } } <|endoftext|>
<commit_before>/************************************************************************** * * Copyright 2011 Zack Rusin * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * **************************************************************************/ #include "trace_file.hpp" #include <assert.h> #include <string.h> #include <zlib.h> #include <gzguts.h> // for lseek #ifdef _WIN32 #include <io.h> #else #include <sys/types.h> #include <unistd.h> #endif #include "os.hpp" #include <iostream> using namespace trace; class ZLibFile : public File { public: ZLibFile(const std::string &filename = std::string(), File::Mode mode = File::Read); virtual ~ZLibFile(); virtual bool supportsOffsets() const; virtual File::Offset currentOffset(); protected: virtual bool rawOpen(const std::string &filename, File::Mode mode); virtual bool rawWrite(const void *buffer, size_t length); virtual size_t rawRead(void *buffer, size_t length); virtual int rawGetc(); virtual void rawClose(); virtual void rawFlush(); virtual bool rawSkip(size_t length); virtual int rawPercentRead(); private: gzFile m_gzFile; double m_endOffset; }; ZLibFile::ZLibFile(const std::string &filename, File::Mode mode) : File(filename, mode), m_gzFile(NULL) { } ZLibFile::~ZLibFile() { close(); } bool ZLibFile::rawOpen(const std::string &filename, File::Mode mode) { m_gzFile = gzopen(filename.c_str(), (mode == File::Write) ? "wb" : "rb"); if (mode == File::Read && m_gzFile) { //XXX: unfortunately zlib doesn't support // SEEK_END or we could've done: //m_endOffset = gzseek(m_gzFile, 0, SEEK_END); //gzrewind(m_gzFile); gz_state *state = (gz_state *)m_gzFile; off_t loc = lseek(state->fd, 0, SEEK_CUR); m_endOffset = lseek(state->fd, 0, SEEK_END); lseek(state->fd, loc, SEEK_SET); } return m_gzFile != NULL; } bool ZLibFile::rawWrite(const void *buffer, size_t length) { return gzwrite(m_gzFile, buffer, unsigned(length)) != -1; } size_t ZLibFile::rawRead(void *buffer, size_t length) { int ret = gzread(m_gzFile, buffer, unsigned(length)); return ret < 0 ? 0 : ret; } int ZLibFile::rawGetc() { return gzgetc(m_gzFile); } void ZLibFile::rawClose() { if (m_gzFile) { gzclose(m_gzFile); m_gzFile = NULL; } } void ZLibFile::rawFlush() { gzflush(m_gzFile, Z_SYNC_FLUSH); } File::Offset ZLibFile::currentOffset() { return File::Offset(gztell(m_gzFile)); } bool ZLibFile::supportsOffsets() const { return false; } bool ZLibFile::rawSkip(size_t) { return false; } int ZLibFile::rawPercentRead() { gz_state *state = (gz_state *)m_gzFile; return int(100 * (lseek(state->fd, 0, SEEK_CUR) / m_endOffset)); } File * File::createZLib(void) { return new ZLibFile; } <commit_msg>common: Don't rely on zlib internals.<commit_after>/************************************************************************** * * Copyright 2011 Zack Rusin * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * **************************************************************************/ #include "trace_file.hpp" #include <assert.h> #include <string.h> #include <zlib.h> #include <fcntl.h> #ifdef _WIN32 #include <io.h> #else #include <sys/types.h> #include <unistd.h> #endif #include "os.hpp" #include <iostream> using namespace trace; class ZLibFile : public File { public: ZLibFile(const std::string &filename = std::string(), File::Mode mode = File::Read); virtual ~ZLibFile(); virtual bool supportsOffsets() const; virtual File::Offset currentOffset(); protected: virtual bool rawOpen(const std::string &filename, File::Mode mode); virtual bool rawWrite(const void *buffer, size_t length); virtual size_t rawRead(void *buffer, size_t length); virtual int rawGetc(); virtual void rawClose(); virtual void rawFlush(); virtual bool rawSkip(size_t length); virtual int rawPercentRead(); private: int fd; gzFile m_gzFile; double m_endOffset; }; ZLibFile::ZLibFile(const std::string &filename, File::Mode mode) : File(filename, mode), m_gzFile(NULL) { } ZLibFile::~ZLibFile() { close(); } bool ZLibFile::rawOpen(const std::string &filename, File::Mode mode) { int flags; const char *fmode; if (mode == File::Write) { flags = O_WRONLY | O_CREAT | O_TRUNC; fmode = "wb"; } else { flags = O_RDONLY; fmode = "rb"; } #ifdef O_BINARY flags |= O_BINARY; #endif #ifdef O_LARGEFILE flags |= O_LARGEFILE; #endif #ifdef _WIN32 fd = _open(filename.c_str(), flags, 0666); #else fd = ::open(filename.c_str(), flags, 0666); #endif if (fd < 0) { return false; } m_gzFile = gzdopen(fd, fmode); if (mode == File::Read && m_gzFile) { //XXX: unfortunately zlib doesn't support // SEEK_END or we could've done: //m_endOffset = gzseek(m_gzFile, 0, SEEK_END); //gzrewind(m_gzFile); off_t loc = lseek(fd, 0, SEEK_CUR); m_endOffset = lseek(fd, 0, SEEK_END); lseek(fd, loc, SEEK_SET); } return m_gzFile != NULL; } bool ZLibFile::rawWrite(const void *buffer, size_t length) { return gzwrite(m_gzFile, buffer, unsigned(length)) != -1; } size_t ZLibFile::rawRead(void *buffer, size_t length) { int ret = gzread(m_gzFile, buffer, unsigned(length)); return ret < 0 ? 0 : ret; } int ZLibFile::rawGetc() { return gzgetc(m_gzFile); } void ZLibFile::rawClose() { if (m_gzFile) { gzclose(m_gzFile); m_gzFile = NULL; } } void ZLibFile::rawFlush() { gzflush(m_gzFile, Z_SYNC_FLUSH); } File::Offset ZLibFile::currentOffset() { return File::Offset(gztell(m_gzFile)); } bool ZLibFile::supportsOffsets() const { return false; } bool ZLibFile::rawSkip(size_t) { return false; } int ZLibFile::rawPercentRead() { return int(100 * (lseek(fd, 0, SEEK_CUR) / m_endOffset)); } File * File::createZLib(void) { return new ZLibFile; } <|endoftext|>