<commit_before>#pragma once
#ifndef OPENGM_DYNAMICPROGRAMMING_HXX
#define OPENGM_DYNAMICPROGRAMMING_HXX

#include <typeinfo>
#include <limits>
#include "opengm/inference/inference.hxx"
#include "opengm/inference/visitors/visitors.hxx"

namespace opengm {

  /// DynamicProgramming
  ///\ingroup inference
  /// \ingroup messagepassing_inference
  template<class GM, class ACC>
  class DynamicProgramming : public Inference<GM, ACC> {
  public:
    typedef ACC AccumulationType;
    typedef ACC AccumulatorType;
    typedef GM GraphicalModelType;
    OPENGM_GM_TYPE_TYPEDEFS;
    typedef LabelType  MyStateType;
    typedef ValueType  MyValueType;
    typedef visitors::VerboseVisitor<DynamicProgramming<GM, ACC> > VerboseVisitorType;
    typedef visitors::EmptyVisitor<DynamicProgramming<GM, ACC> >   EmptyVisitorType;
    typedef visitors::TimingVisitor<DynamicProgramming<GM, ACC> >  TimingVisitorType;
    struct Parameter {
      std::vector<IndexType> roots_;
    };

    DynamicProgramming(const GraphicalModelType&, const Parameter& = Parameter());
    ~DynamicProgramming();

    std::string name() const;
    const GraphicalModelType& graphicalModel() const;
    InferenceTermination infer();
    template< class VISITOR>
    InferenceTermination infer(VISITOR &);
    InferenceTermination arg(std::vector<LabelType>&, const size_t = 1) const;

    void getNodeInfo(const IndexType Inode, std::vector<ValueType>& values, std::vector<std::vector<LabelType> >& substates, std::vector<IndexType>& nodes) const;

  private:
    const GraphicalModelType& gm_;
    Parameter para_;
    MyValueType* valueBuffer_;
    MyStateType* stateBuffer_;
    std::vector<MyValueType*> valueBuffers_;
    std::vector<MyStateType*> stateBuffers_;
    std::vector<size_t> nodeOrder_;
    std::vector<size_t> orderedNodes_;
    bool inferenceStarted_;
  };

  template<class GM, class ACC>
  inline std::string
  DynamicProgramming<GM, ACC>::name() const {
    return "DynamicProgramming";
  }

  template<class GM, class ACC>
  inline const typename DynamicProgramming<GM, ACC>::GraphicalModelType&
  DynamicProgramming<GM, ACC>::graphicalModel() const {
    return gm_;
  }

  template<class GM, class ACC>
  DynamicProgramming<GM, ACC>::~DynamicProgramming()
  {
    free(valueBuffer_);
    free(stateBuffer_);
  }

  template<class GM, class ACC>
  inline DynamicProgramming<GM, ACC>::DynamicProgramming
  (
  const GraphicalModelType& gm,
  const Parameter& para
  )
  :  gm_(gm), inferenceStarted_(false)
  {
    OPENGM_ASSERT(gm_.isAcyclic());
    para_ = para;

    // Set nodeOrder
    std::vector<size_t> numChildren(gm_.numberOfVariables(),0);
    std::vector<size_t> nodeList;
    size_t orderCount = 0;
    size_t varCount   = 0;
    nodeOrder_.resize(gm_.numberOfVariables(),std::numeric_limits<std::size_t>::max());
    size_t rootCounter=0;
    while(varCount < gm_.numberOfVariables() && orderCount < gm_.numberOfVariables()){
      if(rootCounter<para_.roots_.size()){
        nodeOrder_[para_.roots_[rootCounter]] = orderCount++;
        nodeList.push_back(para_.roots_[rootCounter]);
        ++rootCounter;
      }
      else if(nodeOrder_[varCount]==std::numeric_limits<std::size_t>::max()){
        nodeOrder_[varCount] = orderCount++;
        nodeList.push_back(varCount);
      }
      ++varCount;
      while(nodeList.size()>0){
        size_t node = nodeList.back();
        nodeList.pop_back();
        for(typename GM::ConstFactorIterator it=gm_.factorsOfVariableBegin(node); it !=gm_.factorsOfVariableEnd(node); ++it){
          const typename GM::FactorType& factor = gm_[(*it)];
          if( factor.numberOfVariables() == 2 ){
            if( factor.variableIndex(1) == node && nodeOrder_[factor.variableIndex(0)]==std::numeric_limits<std::size_t>::max() ){
              nodeOrder_[factor.variableIndex(0)] = orderCount++;
              nodeList.push_back(factor.variableIndex(0));
              ++numChildren[node];
            }
            if( factor.variableIndex(0) == node && nodeOrder_[factor.variableIndex(1)]==std::numeric_limits<std::size_t>::max() ){
              nodeOrder_[factor.variableIndex(1)] = orderCount++;
              nodeList.push_back(factor.variableIndex(1));
              ++numChildren[node];
            }
          }
        }
      }
    }

    // Allocate memmory
    size_t memSizeValue = 0;
    size_t memSizeState = 0;
    for(size_t i=0; i<gm_.numberOfVariables();++i){
      memSizeValue += gm_.numberOfLabels(i);
      memSizeState += gm.numberOfLabels(i) * numChildren[i];
    }
    valueBuffer_ = (MyValueType*) malloc(memSizeValue*sizeof(MyValueType));
    stateBuffer_ = (MyStateType*) malloc(memSizeState*sizeof(MyStateType));
    valueBuffers_.resize(gm_.numberOfVariables());
    stateBuffers_.resize(gm_.numberOfVariables());

    MyValueType* valuePointer =  valueBuffer_;
    MyStateType* statePointer =  stateBuffer_;
    for(size_t i=0; i<gm_.numberOfVariables();++i){
      valueBuffers_[i] = valuePointer;
      valuePointer += gm.numberOfLabels(i);
      stateBuffers_[i] = statePointer;
      statePointer +=  gm.numberOfLabels(i) * numChildren[i];
    }

    orderedNodes_.resize(gm_.numberOfVariables(),std::numeric_limits<std::size_t>::max());
    for(size_t i=0; i<gm_.numberOfVariables(); ++i)
      orderedNodes_[nodeOrder_[i]] = i;

  }

  template<class GM, class ACC>
  inline InferenceTermination
  DynamicProgramming<GM, ACC>::infer(){
    EmptyVisitorType v;
    return infer(v);
  }

  template<class GM, class ACC>
  template<class VISITOR>
  inline InferenceTermination
  DynamicProgramming<GM, ACC>::infer
  (
  VISITOR & visitor
  ){
     visitor.begin(*this);
     inferenceStarted_ = true;
    for(size_t i=1; i<=gm_.numberOfVariables();++i){
      const size_t node = orderedNodes_[gm_.numberOfVariables()-i];
      // set buffer neutral
      for(size_t n=0; n<gm_.numberOfLabels(node); ++n){
        OperatorType::neutral(valueBuffers_[node][n]);
      }
      // accumulate messages
      size_t childrenCounter = 0;
      for(typename GM::ConstFactorIterator it=gm_.factorsOfVariableBegin(node); it !=gm_.factorsOfVariableEnd(node); ++it){
        const typename GM::FactorType& factor = gm_[(*it)];

        // unary
        if(factor.numberOfVariables()==1 ){
          for(size_t n=0; n<gm_.numberOfLabels(node); ++n){
            const ValueType fac = factor(&n);
            OperatorType::op(fac, valueBuffers_[node][n]);
          }
        }

        //pairwise
        if( factor.numberOfVariables()==2 ){
          size_t vec[] = {0,0};
          if(factor.variableIndex(0) == node && nodeOrder_[factor.variableIndex(1)]>nodeOrder_[node] ){
            const size_t node2 = factor.variableIndex(1);
            MyStateType s;
            MyValueType v,v2;
            for(vec[0]=0; vec[0]<gm_.numberOfLabels(node); ++vec[0]){
              ACC::neutral(v);
              for(vec[1]=0; vec[1]<gm_.numberOfLabels(node2); ++vec[1]){
                const ValueType fac = factor(vec);
                OperatorType::op(fac,valueBuffers_[node2][vec[1]],v2) ;
                if(ACC::bop(v2,v)){
                  v=v2;
                  s=vec[1];
                }
              }
              stateBuffers_[node][childrenCounter*gm_.numberOfLabels(node)+vec[0]] = s;
              OperatorType::op(v,valueBuffers_[node][vec[0]]);
            }
            ++childrenCounter;

          }
          if(factor.variableIndex(1) == node && nodeOrder_[factor.variableIndex(0)]>nodeOrder_[node]){
            const size_t node2 = factor.variableIndex(0);
            MyStateType s;
            MyValueType v,v2;
            for(vec[1]=0; vec[1]<gm_.numberOfLabels(node); ++vec[1]){
              ACC::neutral(v);
              for(vec[0]=0; vec[0]<gm_.numberOfLabels(node2); ++vec[0]){
                const ValueType fac = factor(vec);
                OperatorType::op(fac,valueBuffers_[node2][vec[0]],v2);
                if(ACC::bop(v2,v)){
                  v=v2;
                  s=vec[0];
                }
              }
              stateBuffers_[node][childrenCounter*gm_.numberOfLabels(node)+vec[1]] = s;
              OperatorType::op(v,valueBuffers_[node][vec[1]]);
            }
            ++childrenCounter;
          }
        }
        // higher order
        if( factor.numberOfVariables()>2 ){
           throw std::runtime_error("This implementation of Dynamic Programming does only support second order models so far, but could be extended.");
        }

      }
    }
    visitor.end(*this);
    return NORMAL;
  }

  template<class GM, class ACC>
  inline InferenceTermination DynamicProgramming<GM, ACC>::arg
  (
  std::vector<LabelType>& arg,
  const size_t n
  ) const {
    if(n > 1) {
       arg.assign(gm_.numberOfVariables(), 0);
      return UNKNOWN;
    }
    else {
       if(inferenceStarted_) {
         std::vector<size_t> nodeList;
         arg.assign(gm_.numberOfVariables(), std::numeric_limits<LabelType>::max() );
         size_t var = 0;
         while(var < gm_.numberOfVariables()){
           if(arg[var]==std::numeric_limits<LabelType>::max()){
             MyValueType v; ACC::neutral(v);
             for(size_t i=0; i<gm_.numberOfLabels(var); ++i){
               if(ACC::bop(valueBuffers_[var][i], v)){
                 v = valueBuffers_[var][i];
                 arg[var]=i;
               }
             }
             nodeList.push_back(var);
           }
           ++var;
           while(nodeList.size()>0){
             size_t node = nodeList.back();
             size_t childrenCounter = 0;
             nodeList.pop_back();
             for(typename GM::ConstFactorIterator it=gm_.factorsOfVariableBegin(node); it !=gm_.factorsOfVariableEnd(node); ++it){
               const typename GM::FactorType& factor = gm_[(*it)];
               if(factor.numberOfVariables()==2 ){
                 if(factor.variableIndex(1)==node && nodeOrder_[factor.variableIndex(0)] > nodeOrder_[node] ){
                   arg[factor.variableIndex(0)] = stateBuffers_[node][childrenCounter*gm_.numberOfLabels(node)+arg[node]];
                   nodeList.push_back(factor.variableIndex(0));
                   ++childrenCounter;
                 }
                 if(factor.variableIndex(0)==node && nodeOrder_[factor.variableIndex(1)] > nodeOrder_[node] ){
                   arg[factor.variableIndex(1)] = stateBuffers_[node][childrenCounter*gm_.numberOfLabels(node)+arg[node]];
                   nodeList.push_back(factor.variableIndex(1));
                   ++childrenCounter;
                 }
               }
             }
           }
         }
         return NORMAL;
       } else {
          arg.assign(gm_.numberOfVariables(), 0);
          return UNKNOWN;
       }
    }
  }

  template<class GM, class ACC>
  inline void DynamicProgramming<GM, ACC>::getNodeInfo(const IndexType Inode, std::vector<ValueType>& values, std::vector<std::vector<LabelType> >& substates, std::vector<IndexType>& nodes) const{
    values.clear();
    substates.clear();
    nodes.clear();
    values.resize(gm_.numberOfLabels(Inode));
    substates.resize(gm_.numberOfLabels(Inode));
    std::vector<LabelType> arg;
    bool firstround = true;
    std::vector<size_t> nodeList;
    for(IndexType i=0;i<gm_.numberOfLabels(Inode); ++i){
      arg.assign(gm_.numberOfVariables(), std::numeric_limits<LabelType>::max() );
      arg[Inode]=i;
      values[i]=valueBuffers_[Inode][i];
      nodeList.push_back(Inode);
      if(i!=0){
        firstround=false;
      }

      while(nodeList.size()>0){
        size_t node = nodeList.back();
        size_t childrenCounter = 0;
        nodeList.pop_back();
        for(typename GM::ConstFactorIterator it=gm_.factorsOfVariableBegin(node); it !=gm_.factorsOfVariableEnd(node); ++it){
          const typename GM::FactorType& factor = gm_[(*it)];
          if(factor.numberOfVariables()==2 ){
            if(factor.variableIndex(1)==node && nodeOrder_[factor.variableIndex(0)] > nodeOrder_[node] ){
              arg[factor.variableIndex(0)] = stateBuffers_[node][childrenCounter*gm_.numberOfLabels(node)+arg[node]];
              substates[i].push_back(stateBuffers_[node][childrenCounter*gm_.numberOfLabels(node)+arg[node]]);
              if(firstround==true){
                nodes.push_back(factor.variableIndex(0));
              }
              nodeList.push_back(factor.variableIndex(0));
              ++childrenCounter;
            }
            if(factor.variableIndex(0)==node && nodeOrder_[factor.variableIndex(1)] > nodeOrder_[node] ){
              arg[factor.variableIndex(1)] = stateBuffers_[node][childrenCounter*gm_.numberOfLabels(node)+arg[node]];
              substates[i].push_back(stateBuffers_[node][childrenCounter*gm_.numberOfLabels(node)+arg[node]]);
              if(firstround==true){
                nodes.push_back(factor.variableIndex(1));
              }
              nodeList.push_back(factor.variableIndex(1));
              ++childrenCounter;
            }
          }
        }
      }
    }
  }

} // namespace opengm

#endif // #ifndef OPENGM_DYNAMICPROGRAMMING_HXX

<commit_msg>used the new functor in dynamic programing<commit_after>#pragma once
#ifndef OPENGM_DYNAMICPROGRAMMING_HXX
#define OPENGM_DYNAMICPROGRAMMING_HXX

#include <typeinfo>
#include <limits>
#include "opengm/inference/inference.hxx"
#include "opengm/inference/visitors/visitors.hxx"

namespace opengm {

  namespace detail_dynamic_programming{
    template<class GM, class BUFFER_PTR>
    struct OpUnaries{
        typedef typename GM::IndexType IndexType;
        typedef typename GM::ValueType ValueType;
        typedef typename GM::LabelType LabelType;
        typedef typename GM::OperatorType OperatorType;
    public:
        OpUnaries(BUFFER_PTR  buffer):
        buffer_(buffer){

        }

        template<class FUNCTION>
        void operator()(const FUNCTION & f){
            for(IndexType l=0;l<f.shape(0);++l){
                OperatorType::op(f(&l),buffer_[l]);
            }
        }

        void operator()(const opengm::ExplicitFunction<ValueType, IndexType, LabelType> & f){
            for(IndexType l=0;l<f.shape(0);++l){
                OperatorType::op(f(l),buffer_[l]);
            }
        }

    private:
        BUFFER_PTR  buffer_;
    };

    template<class GM,class ACC,class VALUE_BUFFERS,class STATE_BUFFERS, class NODE_ORDER>
    struct OpBinary{
        typedef typename GM::IndexType IndexType;
        typedef typename GM::ValueType ValueType;
        typedef typename GM::LabelType LabelType;
        typedef typename GM::OperatorType OperatorType;

        OpBinary(
            const GM & gm,
            VALUE_BUFFERS & valueBuffers,
            STATE_BUFFERS & stateBuffers,
            const NODE_ORDER & nodeOrder,
            size_t & childrenCounter,
            const size_t node
        )
        :   gm_(gm),
            valueBuffers_(valueBuffers),
            stateBuffers_(stateBuffers),
            nodeOrder_(nodeOrder),
            childrenCounter_(childrenCounter),
            node_(node)
        {
        }

        template<class VI_ITER,class FUNCTION>
        void operator()(
            const VI_ITER viBegin,
            const VI_ITER viEnd,
            const FUNCTION function
        ){
            size_t vec[] = {0,0};
            if(viBegin[0] == node_ && nodeOrder_[viBegin[1]]>nodeOrder_[node_] ){
                const size_t node2 = viBegin[1];
                LabelType s;
                ValueType v,v2;
                for(vec[0]=0; vec[0]<gm_.numberOfLabels(node_); ++vec[0]){
                    ACC::neutral(v);
                    for(vec[1]=0; vec[1]<gm_.numberOfLabels(node2); ++vec[1]){
                        const ValueType fac = function(vec);
                        OperatorType::op(fac,valueBuffers_[node2][vec[1]],v2) ;
                        if(ACC::bop(v2,v)){
                            v=v2;
                            s=vec[1];
                        }
                    }
                    stateBuffers_[node_][childrenCounter_*gm_.numberOfLabels(node_)+vec[0]] = s;
                    OperatorType::op(v,valueBuffers_[node_][vec[0]]);
                }
                ++childrenCounter_;

            }
            if(viBegin[1] == node_ && nodeOrder_[viBegin[0]]>nodeOrder_[node_]){
                const size_t node2 = viBegin[0];
                LabelType s;
                ValueType v,v2;
                for(vec[1]=0; vec[1]<gm_.numberOfLabels(node_); ++vec[1]){
                    ACC::neutral(v);
                    for(vec[0]=0; vec[0]<gm_.numberOfLabels(node2); ++vec[0]){
                        const ValueType fac = function(vec);
                        OperatorType::op(fac,valueBuffers_[node2][vec[0]],v2);
                        if(ACC::bop(v2,v)){
                            v=v2;
                            s=vec[0];
                        }
                    }
                    stateBuffers_[node_][childrenCounter_*gm_.numberOfLabels(node_)+vec[1]] = s;
                    OperatorType::op(v,valueBuffers_[node_][vec[1]]);
                }
                ++childrenCounter_;
            }
        }

        const GM & gm_;
        const NODE_ORDER & nodeOrder_;
        VALUE_BUFFERS & valueBuffers_;
        STATE_BUFFERS & stateBuffers_;
        size_t & childrenCounter_;
        const size_t node_;
    };
  }

  /// DynamicProgramming
  ///\ingroup inference
  /// \ingroup messagepassing_inference
  template<class GM, class ACC>
  class DynamicProgramming : public Inference<GM, ACC> {
  public:
    typedef ACC AccumulationType;
    typedef ACC AccumulatorType;
    typedef GM GraphicalModelType;
    OPENGM_GM_TYPE_TYPEDEFS;
    typedef LabelType  MyStateType;
    typedef ValueType  MyValueType;
    typedef visitors::VerboseVisitor<DynamicProgramming<GM, ACC> > VerboseVisitorType;
    typedef visitors::EmptyVisitor<DynamicProgramming<GM, ACC> >   EmptyVisitorType;
    typedef visitors::TimingVisitor<DynamicProgramming<GM, ACC> >  TimingVisitorType;
    struct Parameter {
      std::vector<IndexType> roots_;
    };

    DynamicProgramming(const GraphicalModelType&, const Parameter& = Parameter());
    ~DynamicProgramming();

    std::string name() const;
    const GraphicalModelType& graphicalModel() const;
    InferenceTermination infer();
    template< class VISITOR>
    InferenceTermination infer(VISITOR &);
    InferenceTermination arg(std::vector<LabelType>&, const size_t = 1) const;

    void getNodeInfo(const IndexType Inode, std::vector<ValueType>& values, std::vector<std::vector<LabelType> >& substates, std::vector<IndexType>& nodes) const;

  private:
    const GraphicalModelType& gm_;
    Parameter para_;
    MyValueType* valueBuffer_;
    MyStateType* stateBuffer_;
    std::vector<MyValueType*> valueBuffers_;
    std::vector<MyStateType*> stateBuffers_;
    std::vector<size_t> nodeOrder_;
    std::vector<size_t> orderedNodes_;
    bool inferenceStarted_;
  };

  template<class GM, class ACC>
  inline std::string
  DynamicProgramming<GM, ACC>::name() const {
    return "DynamicProgramming";
  }

  template<class GM, class ACC>
  inline const typename DynamicProgramming<GM, ACC>::GraphicalModelType&
  DynamicProgramming<GM, ACC>::graphicalModel() const {
    return gm_;
  }

  template<class GM, class ACC>
  DynamicProgramming<GM, ACC>::~DynamicProgramming()
  {
    free(valueBuffer_);
    free(stateBuffer_);
  }

  template<class GM, class ACC>
  inline DynamicProgramming<GM, ACC>::DynamicProgramming
  (
  const GraphicalModelType& gm,
  const Parameter& para
  )
  :  gm_(gm), inferenceStarted_(false)
  {
    OPENGM_ASSERT(gm_.isAcyclic());
    para_ = para;

    // Set nodeOrder
    std::vector<size_t> numChildren(gm_.numberOfVariables(),0);
    std::vector<size_t> nodeList;
    size_t orderCount = 0;
    size_t varCount   = 0;
    nodeOrder_.resize(gm_.numberOfVariables(),std::numeric_limits<std::size_t>::max());
    size_t rootCounter=0;
    while(varCount < gm_.numberOfVariables() && orderCount < gm_.numberOfVariables()){
      if(rootCounter<para_.roots_.size()){
        nodeOrder_[para_.roots_[rootCounter]] = orderCount++;
        nodeList.push_back(para_.roots_[rootCounter]);
        ++rootCounter;
      }
      else if(nodeOrder_[varCount]==std::numeric_limits<std::size_t>::max()){
        nodeOrder_[varCount] = orderCount++;
        nodeList.push_back(varCount);
      }
      ++varCount;
      while(nodeList.size()>0){
        size_t node = nodeList.back();
        nodeList.pop_back();
        for(typename GM::ConstFactorIterator it=gm_.factorsOfVariableBegin(node); it !=gm_.factorsOfVariableEnd(node); ++it){
          const typename GM::FactorType& factor = gm_[(*it)];
          if( factor.numberOfVariables() == 2 ){
            if( factor.variableIndex(1) == node && nodeOrder_[factor.variableIndex(0)]==std::numeric_limits<std::size_t>::max() ){
              nodeOrder_[factor.variableIndex(0)] = orderCount++;
              nodeList.push_back(factor.variableIndex(0));
              ++numChildren[node];
            }
            if( factor.variableIndex(0) == node && nodeOrder_[factor.variableIndex(1)]==std::numeric_limits<std::size_t>::max() ){
              nodeOrder_[factor.variableIndex(1)] = orderCount++;
              nodeList.push_back(factor.variableIndex(1));
              ++numChildren[node];
            }
          }
        }
      }
    }

    // Allocate memmory
    size_t memSizeValue = 0;
    size_t memSizeState = 0;
    for(size_t i=0; i<gm_.numberOfVariables();++i){
      memSizeValue += gm_.numberOfLabels(i);
      memSizeState += gm.numberOfLabels(i) * numChildren[i];
    }
    valueBuffer_ = (MyValueType*) malloc(memSizeValue*sizeof(MyValueType));
    stateBuffer_ = (MyStateType*) malloc(memSizeState*sizeof(MyStateType));
    valueBuffers_.resize(gm_.numberOfVariables());
    stateBuffers_.resize(gm_.numberOfVariables());

    MyValueType* valuePointer =  valueBuffer_;
    MyStateType* statePointer =  stateBuffer_;
    for(size_t i=0; i<gm_.numberOfVariables();++i){
      valueBuffers_[i] = valuePointer;
      valuePointer += gm.numberOfLabels(i);
      stateBuffers_[i] = statePointer;
      statePointer +=  gm.numberOfLabels(i) * numChildren[i];
    }

    orderedNodes_.resize(gm_.numberOfVariables(),std::numeric_limits<std::size_t>::max());
    for(size_t i=0; i<gm_.numberOfVariables(); ++i)
      orderedNodes_[nodeOrder_[i]] = i;

  }

  template<class GM, class ACC>
  inline InferenceTermination
  DynamicProgramming<GM, ACC>::infer(){
    EmptyVisitorType v;
    return infer(v);
  }

  template<class GM, class ACC>
  template<class VISITOR>
  inline InferenceTermination
  DynamicProgramming<GM, ACC>::infer
  (
  VISITOR & visitor
  ){
     visitor.begin(*this);
     inferenceStarted_ = true;
    for(size_t i=1; i<=gm_.numberOfVariables();++i){
      const size_t node = orderedNodes_[gm_.numberOfVariables()-i];
      // set buffer neutral
      for(size_t n=0; n<gm_.numberOfLabels(node); ++n){
        OperatorType::neutral(valueBuffers_[node][n]);
      }
      // accumulate messages
      size_t childrenCounter = 0;
      for(typename GM::ConstFactorIterator it=gm_.factorsOfVariableBegin(node); it !=gm_.factorsOfVariableEnd(node); ++it){
        const typename GM::FactorType& factor = gm_[(*it)];

        // unary

        if(factor.numberOfVariables()==1 ){
          // THE FUNCTOR DOES THE SAME AS THE OUTCOMMENTED LINES BELOW
          detail_dynamic_programming::OpUnaries<GraphicalModelType, MyValueType* > opUnariesFunctor(valueBuffers_[node]);
          factor.callFunctor(opUnariesFunctor);
          //for(size_t n=0; n<gm_.numberOfLabels(node); ++n){
          //  OperatorType::op(factor(&n), valueBuffers_[node][n]);
          //}
        }

        //pairwise
        if( factor.numberOfVariables()==2 ){

          detail_dynamic_programming::OpBinary<GM,ACC,std::vector<MyValueType*>,
            std::vector<MyStateType *>, std::vector<size_t> >
            opBinaryFunctor(gm_,valueBuffers_,stateBuffers_, nodeOrder_,childrenCounter,node);
          factor.callViFunctor(opBinaryFunctor);

          #if 0
          size_t vec[] = {0,0};
          if(factor.variableIndex(0) == node && nodeOrder_[factor.variableIndex(1)]>nodeOrder_[node] ){
            const size_t node2 = factor.variableIndex(1);
            MyStateType s;
            MyValueType v,v2;
            for(vec[0]=0; vec[0]<gm_.numberOfLabels(node); ++vec[0]){
              ACC::neutral(v);
              for(vec[1]=0; vec[1]<gm_.numberOfLabels(node2); ++vec[1]){
                const ValueType fac = factor(vec);
                OperatorType::op(fac,valueBuffers_[node2][vec[1]],v2) ;
                if(ACC::bop(v2,v)){
                  v=v2;
                  s=vec[1];
                }
              }
              stateBuffers_[node][childrenCounter*gm_.numberOfLabels(node)+vec[0]] = s;
              OperatorType::op(v,valueBuffers_[node][vec[0]]);
            }
            ++childrenCounter;

          }
          if(factor.variableIndex(1) == node && nodeOrder_[factor.variableIndex(0)]>nodeOrder_[node]){
            const size_t node2 = factor.variableIndex(0);
            MyStateType s;
            MyValueType v,v2;
            for(vec[1]=0; vec[1]<gm_.numberOfLabels(node); ++vec[1]){
              ACC::neutral(v);
              for(vec[0]=0; vec[0]<gm_.numberOfLabels(node2); ++vec[0]){
                const ValueType fac = factor(vec);
                OperatorType::op(fac,valueBuffers_[node2][vec[0]],v2);
                if(ACC::bop(v2,v)){
                  v=v2;
                  s=vec[0];
                }
              }
              stateBuffers_[node][childrenCounter*gm_.numberOfLabels(node)+vec[1]] = s;
              OperatorType::op(v,valueBuffers_[node][vec[1]]);
            }
            ++childrenCounter;
          }
          #endif

        }
        // higher order
        if( factor.numberOfVariables()>2 ){
           throw std::runtime_error("This implementation of Dynamic Programming does only support second order models so far, but could be extended.");
        }

      }
    }
    visitor.end(*this);
    return NORMAL;
  }

  template<class GM, class ACC>
  inline InferenceTermination DynamicProgramming<GM, ACC>::arg
  (
  std::vector<LabelType>& arg,
  const size_t n
  ) const {
    if(n > 1) {
       arg.assign(gm_.numberOfVariables(), 0);
      return UNKNOWN;
    }
    else {
       if(inferenceStarted_) {
         std::vector<size_t> nodeList;
         arg.assign(gm_.numberOfVariables(), std::numeric_limits<LabelType>::max() );
         size_t var = 0;
         while(var < gm_.numberOfVariables()){
           if(arg[var]==std::numeric_limits<LabelType>::max()){
             MyValueType v; ACC::neutral(v);
             for(size_t i=0; i<gm_.numberOfLabels(var); ++i){
               if(ACC::bop(valueBuffers_[var][i], v)){
                 v = valueBuffers_[var][i];
                 arg[var]=i;
               }
             }
             nodeList.push_back(var);
           }
           ++var;
           while(nodeList.size()>0){
             size_t node = nodeList.back();
             size_t childrenCounter = 0;
             nodeList.pop_back();
             for(typename GM::ConstFactorIterator it=gm_.factorsOfVariableBegin(node); it !=gm_.factorsOfVariableEnd(node); ++it){
               const typename GM::FactorType& factor = gm_[(*it)];
               if(factor.numberOfVariables()==2 ){
                 if(factor.variableIndex(1)==node && nodeOrder_[factor.variableIndex(0)] > nodeOrder_[node] ){
                   arg[factor.variableIndex(0)] = stateBuffers_[node][childrenCounter*gm_.numberOfLabels(node)+arg[node]];
                   nodeList.push_back(factor.variableIndex(0));
                   ++childrenCounter;
                 }
                 if(factor.variableIndex(0)==node && nodeOrder_[factor.variableIndex(1)] > nodeOrder_[node] ){
                   arg[factor.variableIndex(1)] = stateBuffers_[node][childrenCounter*gm_.numberOfLabels(node)+arg[node]];
                   nodeList.push_back(factor.variableIndex(1));
                   ++childrenCounter;
                 }
               }
             }
           }
         }
         return NORMAL;
       } else {
          arg.assign(gm_.numberOfVariables(), 0);
          return UNKNOWN;
       }
    }
  }

  template<class GM, class ACC>
  inline void DynamicProgramming<GM, ACC>::getNodeInfo(const IndexType Inode, std::vector<ValueType>& values, std::vector<std::vector<LabelType> >& substates, std::vector<IndexType>& nodes) const{
    values.clear();
    substates.clear();
    nodes.clear();
    values.resize(gm_.numberOfLabels(Inode));
    substates.resize(gm_.numberOfLabels(Inode));
    std::vector<LabelType> arg;
    bool firstround = true;
    std::vector<size_t> nodeList;
    for(IndexType i=0;i<gm_.numberOfLabels(Inode); ++i){
      arg.assign(gm_.numberOfVariables(), std::numeric_limits<LabelType>::max() );
      arg[Inode]=i;
      values[i]=valueBuffers_[Inode][i];
      nodeList.push_back(Inode);
      if(i!=0){
        firstround=false;
      }

      while(nodeList.size()>0){
        size_t node = nodeList.back();
        size_t childrenCounter = 0;
        nodeList.pop_back();
        for(typename GM::ConstFactorIterator it=gm_.factorsOfVariableBegin(node); it !=gm_.factorsOfVariableEnd(node); ++it){
          const typename GM::FactorType& factor = gm_[(*it)];
          if(factor.numberOfVariables()==2 ){
            if(factor.variableIndex(1)==node && nodeOrder_[factor.variableIndex(0)] > nodeOrder_[node] ){
              arg[factor.variableIndex(0)] = stateBuffers_[node][childrenCounter*gm_.numberOfLabels(node)+arg[node]];
              substates[i].push_back(stateBuffers_[node][childrenCounter*gm_.numberOfLabels(node)+arg[node]]);
              if(firstround==true){
                nodes.push_back(factor.variableIndex(0));
              }
              nodeList.push_back(factor.variableIndex(0));
              ++childrenCounter;
            }
            if(factor.variableIndex(0)==node && nodeOrder_[factor.variableIndex(1)] > nodeOrder_[node] ){
              arg[factor.variableIndex(1)] = stateBuffers_[node][childrenCounter*gm_.numberOfLabels(node)+arg[node]];
              substates[i].push_back(stateBuffers_[node][childrenCounter*gm_.numberOfLabels(node)+arg[node]]);
              if(firstround==true){
                nodes.push_back(factor.variableIndex(1));
              }
              nodeList.push_back(factor.variableIndex(1));
              ++childrenCounter;
            }
          }
        }
      }
    }
  }

} // namespace opengm

#endif // #ifndef OPENGM_DYNAMICPROGRAMMING_HXX

<|endoftext|>


<commit_before>#include "CProgramContext.h"

#include "CMainState.h"
#include "CMainMenuState.h"
#include "CLoadState.h"

CProgramContext::SScene::SScene()
	: Camera(0), OrbitCamera(0), Timer(0.f),
	LightObject(0), SkyBox(0), Terrain(0), GlyphSceneObject(0),
	VolumeSceneObject(0), Cube(0)
{}

CProgramContext::SShaders::SShaders()
	: Diffuse(0), DiffuseTexture(0), Volume(0), Terrain(0), Glyph(0), GlyphLines(0)
{}

CProgramContext::CProgramContext()
	: GUIContext(0), DataManager(0)
{}

void CProgramContext::run()
{
	// Directory Setup
	CTextureLoader::ImageDirectory = "Media/";
	CMeshLoader::MeshDirectory = "Media/";
	CShaderLoader::ShaderDirectory = "Shaders/";

	// Create Window
	CApplication & Application = CApplication::get();
	Application.init(SVector2i(1600, 900), "Underwater Volume Data Rendering");

	Application.loadEngines();

	// Create GUI Engine
	std::cout << "GUI Engine is initializing..." << std::endl;
	GUIContext = new CGUIContext();
	GUIContext->init();

	// Begin loading
	CLoadState & LoadState = CLoadState::get();
	Application.getStateManager().setState(& LoadState);

	// Run program
	Application.run();
}
<commit_msg>+ Increased window size for screenshots<commit_after>#include "CProgramContext.h"

#include "CMainState.h"
#include "CMainMenuState.h"
#include "CLoadState.h"

CProgramContext::SScene::SScene()
	: Camera(0), OrbitCamera(0), Timer(0.f),
	LightObject(0), SkyBox(0), Terrain(0), GlyphSceneObject(0),
	VolumeSceneObject(0), Cube(0)
{}

CProgramContext::SShaders::SShaders()
	: Diffuse(0), DiffuseTexture(0), Volume(0), Terrain(0), Glyph(0), GlyphLines(0)
{}

CProgramContext::CProgramContext()
	: GUIContext(0), DataManager(0)
{}

void CProgramContext::run()
{
	// Directory Setup
	CTextureLoader::ImageDirectory = "Media/";
	CMeshLoader::MeshDirectory = "Media/";
	CShaderLoader::ShaderDirectory = "Shaders/";

	// Create Window
	CApplication & Application = CApplication::get();
	Application.init(SVector2i(1900, 1000), "Underwater Volume Data Rendering");

	Application.loadEngines();

	// Create GUI Engine
	std::cout << "GUI Engine is initializing..." << std::endl;
	GUIContext = new CGUIContext();
	GUIContext->init();

	// Begin loading
	CLoadState & LoadState = CLoadState::get();
	Application.getStateManager().setState(& LoadState);

	// Run program
	Application.run();
}
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "packet.h"
#include "module_common_types.h"

#include <assert.h>

namespace webrtc {

VCMPacket::VCMPacket(const WebRtc_UWord8* ptr,
                               const WebRtc_UWord32 size,
                               const WebRtcRTPHeader& rtpHeader) :
    payloadType(rtpHeader.header.payloadType),
    timestamp(rtpHeader.header.timestamp),
    seqNum(rtpHeader.header.sequenceNumber),
    dataPtr(ptr),
    sizeBytes(size),
    markerBit(rtpHeader.header.markerBit),

    frameType(rtpHeader.frameType),
    codec(kVideoCodecUnknown),
    isFirstPacket(rtpHeader.type.Video.isFirstPacket),
    completeNALU(kNaluComplete),
    insertStartCode(false),
    bits(false)
{
    CopyCodecSpecifics(rtpHeader.type.Video);
}

VCMPacket::VCMPacket(const WebRtc_UWord8* ptr, WebRtc_UWord32 size, WebRtc_UWord16 seq, WebRtc_UWord32 ts, bool mBit) :
    payloadType(0),
    timestamp(ts),
    seqNum(seq),
    dataPtr(ptr),
    sizeBytes(size),
    markerBit(mBit),

    frameType(kVideoFrameDelta),
    codec(kVideoCodecUnknown),
    isFirstPacket(false),
    completeNALU(kNaluComplete),
    insertStartCode(false),
    bits(false)
{}

void VCMPacket::CopyCodecSpecifics(const RTPVideoHeader& videoHeader)
{
    RTPVideoTypeHeader codecHeader = videoHeader.codecHeader;
    switch(videoHeader.codec)
    {
        case kRTPVideoVP8:
            {
                codec = kVideoCodecVP8;
                break;
            }
        case kRTPVideoI420:
            {
                codec = kVideoCodecI420;
                break;
            }
        default:
            {
                codec = kVideoCodecUnknown;
                break;
            }
    }
}

}
<commit_msg>Handle all VP8 packets within a frame as depending on the previous packet<commit_after>/*
 *  Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "packet.h"
#include "module_common_types.h"

#include <assert.h>

namespace webrtc {

VCMPacket::VCMPacket(const WebRtc_UWord8* ptr,
                               const WebRtc_UWord32 size,
                               const WebRtcRTPHeader& rtpHeader) :
    payloadType(rtpHeader.header.payloadType),
    timestamp(rtpHeader.header.timestamp),
    seqNum(rtpHeader.header.sequenceNumber),
    dataPtr(ptr),
    sizeBytes(size),
    markerBit(rtpHeader.header.markerBit),

    frameType(rtpHeader.frameType),
    codec(kVideoCodecUnknown),
    isFirstPacket(rtpHeader.type.Video.isFirstPacket),
    completeNALU(kNaluComplete),
    insertStartCode(false),
    bits(false)
{
    CopyCodecSpecifics(rtpHeader.type.Video);
}

VCMPacket::VCMPacket(const WebRtc_UWord8* ptr, WebRtc_UWord32 size, WebRtc_UWord16 seq, WebRtc_UWord32 ts, bool mBit) :
    payloadType(0),
    timestamp(ts),
    seqNum(seq),
    dataPtr(ptr),
    sizeBytes(size),
    markerBit(mBit),

    frameType(kVideoFrameDelta),
    codec(kVideoCodecUnknown),
    isFirstPacket(false),
    completeNALU(kNaluComplete),
    insertStartCode(false),
    bits(false)
{}

void VCMPacket::CopyCodecSpecifics(const RTPVideoHeader& videoHeader)
{
    RTPVideoTypeHeader codecHeader = videoHeader.codecHeader;
    switch(videoHeader.codec)
    {
        case kRTPVideoVP8:
            {
                // Handle all packets within a frame as depending on the previous packet
                // TODO(holmer): This should be changed to make fragments independent
                // when the VP8 RTP receiver supports fragments.
                if (isFirstPacket && markerBit)
                    completeNALU = kNaluComplete;
                else if (isFirstPacket)
                    completeNALU = kNaluStart;
                else if (markerBit)
                    completeNALU = kNaluEnd;
                else
                    completeNALU = kNaluIncomplete;

                codec = kVideoCodecVP8;
                break;
            }
        case kRTPVideoI420:
            {
                codec = kVideoCodecI420;
                break;
            }
        default:
            {
                codec = kVideoCodecUnknown;
                break;
            }
    }
}

}
<|endoftext|>


<commit_before>//===-- sanitizer_printf.cc -----------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is shared between AddressSanitizer and ThreadSanitizer.
//
// Internal printf function, used inside run-time libraries.
// We can't use libc printf because we intercept some of the functions used
// inside it.
//===----------------------------------------------------------------------===//

#include "sanitizer_common.h"
#include "sanitizer_flags.h"
#include "sanitizer_libc.h"

#include <stdio.h>
#include <stdarg.h>

#if SANITIZER_WINDOWS && !defined(va_copy)
# define va_copy(dst, src) ((dst) = (src))
#endif

namespace __sanitizer {

StaticSpinMutex CommonSanitizerReportMutex;

static int AppendChar(char **buff, const char *buff_end, char c) {
  if (*buff < buff_end) {
    **buff = c;
    (*buff)++;
  }
  return 1;
}

// Appends number in a given base to buffer. If its length is less than
// |minimal_num_length|, it is padded with leading zeroes or spaces, depending
// on the value of |pad_with_zero|.
static int AppendNumber(char **buff, const char *buff_end, u64 absolute_value,
                        u8 base, u8 minimal_num_length, bool pad_with_zero,
                        bool negative) {
  uptr const kMaxLen = 30;
  RAW_CHECK(base == 10 || base == 16);
  RAW_CHECK(base == 10 || !negative);
  RAW_CHECK(absolute_value || !negative);
  RAW_CHECK(minimal_num_length < kMaxLen);
  int result = 0;
  if (negative && minimal_num_length)
    --minimal_num_length;
  if (negative && pad_with_zero)
    result += AppendChar(buff, buff_end, '-');
  uptr num_buffer[kMaxLen];
  int pos = 0;
  do {
    RAW_CHECK_MSG((uptr)pos < kMaxLen, "AppendNumber buffer overflow");
    num_buffer[pos++] = absolute_value % base;
    absolute_value /= base;
  } while (absolute_value > 0);
  if (pos < minimal_num_length) {
    // Make sure compiler doesn't insert call to memset here.
    internal_memset(&num_buffer[pos], 0,
                    sizeof(num_buffer[0]) * (minimal_num_length - pos));
    pos = minimal_num_length;
  }
  RAW_CHECK(pos > 0);
  pos--;
  for (; pos >= 0 && num_buffer[pos] == 0; pos--) {
    char c = (pad_with_zero || pos == 0) ? '0' : ' ';
    result += AppendChar(buff, buff_end, c);
  }
  if (negative && !pad_with_zero) result += AppendChar(buff, buff_end, '-');
  for (; pos >= 0; pos--) {
    char digit = static_cast<char>(num_buffer[pos]);
    result += AppendChar(buff, buff_end, (digit < 10) ? '0' + digit
                                                      : 'a' + digit - 10);
  }
  return result;
}

static int AppendUnsigned(char **buff, const char *buff_end, u64 num, u8 base,
                          u8 minimal_num_length, bool pad_with_zero) {
  return AppendNumber(buff, buff_end, num, base, minimal_num_length,
                      pad_with_zero, false /* negative */);
}

static int AppendSignedDecimal(char **buff, const char *buff_end, s64 num,
                               u8 minimal_num_length, bool pad_with_zero) {
  bool negative = (num < 0);
  return AppendNumber(buff, buff_end, (u64)(negative ? -num : num), 10,
                      minimal_num_length, pad_with_zero, negative);
}

static int AppendString(char **buff, const char *buff_end, int precision,
                        const char *s) {
  if (s == 0)
    s = "<null>";
  int result = 0;
  for (; *s; s++) {
    if (precision >= 0 && result >= precision)
      break;
    result += AppendChar(buff, buff_end, *s);
  }
  return result;
}

static int AppendPointer(char **buff, const char *buff_end, u64 ptr_value) {
  int result = 0;
  result += AppendString(buff, buff_end, -1, "0x");
  result += AppendUnsigned(buff, buff_end, ptr_value, 16,
                           (SANITIZER_WORDSIZE == 64) ? 12 : 8, true);
  return result;
}

int VSNPrintf(char *buff, int buff_length,
              const char *format, va_list args) {
  static const char *kPrintfFormatsHelp =
    "Supported Printf formats: %([0-9]*)?(z|ll)?{d,u,x}; %p; %(\\.\\*)?s; %c\n";
  RAW_CHECK(format);
  RAW_CHECK(buff_length > 0);
  const char *buff_end = &buff[buff_length - 1];
  const char *cur = format;
  int result = 0;
  for (; *cur; cur++) {
    if (*cur != '%') {
      result += AppendChar(&buff, buff_end, *cur);
      continue;
    }
    cur++;
    bool have_width = (*cur >= '0' && *cur <= '9');
    bool pad_with_zero = (*cur == '0');
    int width = 0;
    if (have_width) {
      while (*cur >= '0' && *cur <= '9') {
        width = width * 10 + *cur++ - '0';
      }
    }
    bool have_precision = (cur[0] == '.' && cur[1] == '*');
    int precision = -1;
    if (have_precision) {
      cur += 2;
      precision = va_arg(args, int);
    }
    bool have_z = (*cur == 'z');
    cur += have_z;
    bool have_ll = !have_z && (cur[0] == 'l' && cur[1] == 'l');
    cur += have_ll * 2;
    s64 dval;
    u64 uval;
    bool have_flags = have_width | have_z | have_ll;
    // Only %s supports precision for now
    CHECK(!(precision >= 0 && *cur != 's'));
    switch (*cur) {
      case 'd': {
        dval = have_ll ? va_arg(args, s64)
             : have_z ? va_arg(args, sptr)
             : va_arg(args, int);
        result += AppendSignedDecimal(&buff, buff_end, dval, width,
                                      pad_with_zero);
        break;
      }
      case 'u':
      case 'x': {
        uval = have_ll ? va_arg(args, u64)
             : have_z ? va_arg(args, uptr)
             : va_arg(args, unsigned);
        result += AppendUnsigned(&buff, buff_end, uval,
                                 (*cur == 'u') ? 10 : 16, width, pad_with_zero);
        break;
      }
      case 'p': {
        RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
        result += AppendPointer(&buff, buff_end, va_arg(args, uptr));
        break;
      }
      case 's': {
        RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
        result += AppendString(&buff, buff_end, precision, va_arg(args, char*));
        break;
      }
      case 'c': {
        RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
        result += AppendChar(&buff, buff_end, va_arg(args, int));
        break;
      }
      case '%' : {
        RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
        result += AppendChar(&buff, buff_end, '%');
        break;
      }
      default: {
        RAW_CHECK_MSG(false, kPrintfFormatsHelp);
      }
    }
  }
  RAW_CHECK(buff <= buff_end);
  AppendChar(&buff, buff_end + 1, '\0');
  return result;
}

static void (*PrintfAndReportCallback)(const char *);
void SetPrintfAndReportCallback(void (*callback)(const char *)) {
  PrintfAndReportCallback = callback;
}

// Can be overriden in frontend.
#if SANITIZER_SUPPORTS_WEAK_HOOKS
SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
void OnPrint(const char *str) {
  (void)str;
}
#elif defined(SANITIZER_GO) && defined(TSAN_EXTERNAL_HOOKS)
void OnPrint(const char *str);
#else
void OnPrint(const char *str) {
  (void)str;
}
#endif

static void CallPrintfAndReportCallback(const char *str) {
  OnPrint(str);
  if (PrintfAndReportCallback)
    PrintfAndReportCallback(str);
}

static void SharedPrintfCode(bool append_pid, const char *format,
                             va_list args) {
  va_list args2;
  va_copy(args2, args);
  const int kLen = 16 * 1024;
  // |local_buffer| is small enough not to overflow the stack and/or violate
  // the stack limit enforced by TSan (-Wframe-larger-than=512). On the other
  // hand, the bigger the buffer is, the more the chance the error report will
  // fit into it.
  char local_buffer[400];
  int needed_length;
  char *buffer = local_buffer;
  int buffer_size = ARRAY_SIZE(local_buffer);
  // First try to print a message using a local buffer, and then fall back to
  // mmaped buffer.
  for (int use_mmap = 0; use_mmap < 2; use_mmap++) {
    if (use_mmap) {
      va_end(args);
      va_copy(args, args2);
      buffer = (char*)MmapOrDie(kLen, "Report");
      buffer_size = kLen;
    }
    needed_length = 0;
    if (append_pid) {
      int pid = internal_getpid();
      needed_length += internal_snprintf(buffer, buffer_size, "==%d==", pid);
      if (needed_length >= buffer_size) {
        // The pid doesn't fit into the current buffer.
        if (!use_mmap)
          continue;
        RAW_CHECK_MSG(needed_length < kLen, "Buffer in Report is too short!\n");
      }
    }
    needed_length += VSNPrintf(buffer + needed_length,
                               buffer_size - needed_length, format, args);
    if (needed_length >= buffer_size) {
      // The message doesn't fit into the current buffer.
      if (!use_mmap)
        continue;
      RAW_CHECK_MSG(needed_length < kLen, "Buffer in Report is too short!\n");
    }
    // If the message fit into the buffer, print it and exit.
    break;
  }
  RawWrite(buffer);
  AndroidLogWrite(buffer);
  CallPrintfAndReportCallback(buffer);
  // If we had mapped any memory, clean up.
  if (buffer != local_buffer)
    UnmapOrDie((void *)buffer, buffer_size);
  va_end(args2);
}

FORMAT(1, 2)
void Printf(const char *format, ...) {
  va_list args;
  va_start(args, format);
  SharedPrintfCode(false, format, args);
  va_end(args);
}

// Like Printf, but prints the current PID before the output string.
FORMAT(1, 2)
void Report(const char *format, ...) {
  va_list args;
  va_start(args, format);
  SharedPrintfCode(true, format, args);
  va_end(args);
}

// Writes at most "length" symbols to "buffer" (including trailing '\0').
// Returns the number of symbols that should have been written to buffer
// (not including trailing '\0'). Thus, the string is truncated
// iff return value is not less than "length".
FORMAT(3, 4)
int internal_snprintf(char *buffer, uptr length, const char *format, ...) {
  va_list args;
  va_start(args, format);
  int needed_length = VSNPrintf(buffer, length, format, args);
  va_end(args);
  return needed_length;
}

FORMAT(2, 3)
void InternalScopedString::append(const char *format, ...) {
  CHECK_LT(length_, size());
  va_list args;
  va_start(args, format);
  VSNPrintf(data() + length_, size() - length_, format, args);
  va_end(args);
  length_ += internal_strlen(data() + length_);
  CHECK_LT(length_, size());
}

}  // namespace __sanitizer
<commit_msg>[ASan/Win] Remove a hack that seems not to be required with VS2013 anymore<commit_after>//===-- sanitizer_printf.cc -----------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is shared between AddressSanitizer and ThreadSanitizer.
//
// Internal printf function, used inside run-time libraries.
// We can't use libc printf because we intercept some of the functions used
// inside it.
//===----------------------------------------------------------------------===//

#include "sanitizer_common.h"
#include "sanitizer_flags.h"
#include "sanitizer_libc.h"

#include <stdio.h>
#include <stdarg.h>

namespace __sanitizer {

StaticSpinMutex CommonSanitizerReportMutex;

static int AppendChar(char **buff, const char *buff_end, char c) {
  if (*buff < buff_end) {
    **buff = c;
    (*buff)++;
  }
  return 1;
}

// Appends number in a given base to buffer. If its length is less than
// |minimal_num_length|, it is padded with leading zeroes or spaces, depending
// on the value of |pad_with_zero|.
static int AppendNumber(char **buff, const char *buff_end, u64 absolute_value,
                        u8 base, u8 minimal_num_length, bool pad_with_zero,
                        bool negative) {
  uptr const kMaxLen = 30;
  RAW_CHECK(base == 10 || base == 16);
  RAW_CHECK(base == 10 || !negative);
  RAW_CHECK(absolute_value || !negative);
  RAW_CHECK(minimal_num_length < kMaxLen);
  int result = 0;
  if (negative && minimal_num_length)
    --minimal_num_length;
  if (negative && pad_with_zero)
    result += AppendChar(buff, buff_end, '-');
  uptr num_buffer[kMaxLen];
  int pos = 0;
  do {
    RAW_CHECK_MSG((uptr)pos < kMaxLen, "AppendNumber buffer overflow");
    num_buffer[pos++] = absolute_value % base;
    absolute_value /= base;
  } while (absolute_value > 0);
  if (pos < minimal_num_length) {
    // Make sure compiler doesn't insert call to memset here.
    internal_memset(&num_buffer[pos], 0,
                    sizeof(num_buffer[0]) * (minimal_num_length - pos));
    pos = minimal_num_length;
  }
  RAW_CHECK(pos > 0);
  pos--;
  for (; pos >= 0 && num_buffer[pos] == 0; pos--) {
    char c = (pad_with_zero || pos == 0) ? '0' : ' ';
    result += AppendChar(buff, buff_end, c);
  }
  if (negative && !pad_with_zero) result += AppendChar(buff, buff_end, '-');
  for (; pos >= 0; pos--) {
    char digit = static_cast<char>(num_buffer[pos]);
    result += AppendChar(buff, buff_end, (digit < 10) ? '0' + digit
                                                      : 'a' + digit - 10);
  }
  return result;
}

static int AppendUnsigned(char **buff, const char *buff_end, u64 num, u8 base,
                          u8 minimal_num_length, bool pad_with_zero) {
  return AppendNumber(buff, buff_end, num, base, minimal_num_length,
                      pad_with_zero, false /* negative */);
}

static int AppendSignedDecimal(char **buff, const char *buff_end, s64 num,
                               u8 minimal_num_length, bool pad_with_zero) {
  bool negative = (num < 0);
  return AppendNumber(buff, buff_end, (u64)(negative ? -num : num), 10,
                      minimal_num_length, pad_with_zero, negative);
}

static int AppendString(char **buff, const char *buff_end, int precision,
                        const char *s) {
  if (s == 0)
    s = "<null>";
  int result = 0;
  for (; *s; s++) {
    if (precision >= 0 && result >= precision)
      break;
    result += AppendChar(buff, buff_end, *s);
  }
  return result;
}

static int AppendPointer(char **buff, const char *buff_end, u64 ptr_value) {
  int result = 0;
  result += AppendString(buff, buff_end, -1, "0x");
  result += AppendUnsigned(buff, buff_end, ptr_value, 16,
                           (SANITIZER_WORDSIZE == 64) ? 12 : 8, true);
  return result;
}

int VSNPrintf(char *buff, int buff_length,
              const char *format, va_list args) {
  static const char *kPrintfFormatsHelp =
    "Supported Printf formats: %([0-9]*)?(z|ll)?{d,u,x}; %p; %(\\.\\*)?s; %c\n";
  RAW_CHECK(format);
  RAW_CHECK(buff_length > 0);
  const char *buff_end = &buff[buff_length - 1];
  const char *cur = format;
  int result = 0;
  for (; *cur; cur++) {
    if (*cur != '%') {
      result += AppendChar(&buff, buff_end, *cur);
      continue;
    }
    cur++;
    bool have_width = (*cur >= '0' && *cur <= '9');
    bool pad_with_zero = (*cur == '0');
    int width = 0;
    if (have_width) {
      while (*cur >= '0' && *cur <= '9') {
        width = width * 10 + *cur++ - '0';
      }
    }
    bool have_precision = (cur[0] == '.' && cur[1] == '*');
    int precision = -1;
    if (have_precision) {
      cur += 2;
      precision = va_arg(args, int);
    }
    bool have_z = (*cur == 'z');
    cur += have_z;
    bool have_ll = !have_z && (cur[0] == 'l' && cur[1] == 'l');
    cur += have_ll * 2;
    s64 dval;
    u64 uval;
    bool have_flags = have_width | have_z | have_ll;
    // Only %s supports precision for now
    CHECK(!(precision >= 0 && *cur != 's'));
    switch (*cur) {
      case 'd': {
        dval = have_ll ? va_arg(args, s64)
             : have_z ? va_arg(args, sptr)
             : va_arg(args, int);
        result += AppendSignedDecimal(&buff, buff_end, dval, width,
                                      pad_with_zero);
        break;
      }
      case 'u':
      case 'x': {
        uval = have_ll ? va_arg(args, u64)
             : have_z ? va_arg(args, uptr)
             : va_arg(args, unsigned);
        result += AppendUnsigned(&buff, buff_end, uval,
                                 (*cur == 'u') ? 10 : 16, width, pad_with_zero);
        break;
      }
      case 'p': {
        RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
        result += AppendPointer(&buff, buff_end, va_arg(args, uptr));
        break;
      }
      case 's': {
        RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
        result += AppendString(&buff, buff_end, precision, va_arg(args, char*));
        break;
      }
      case 'c': {
        RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
        result += AppendChar(&buff, buff_end, va_arg(args, int));
        break;
      }
      case '%' : {
        RAW_CHECK_MSG(!have_flags, kPrintfFormatsHelp);
        result += AppendChar(&buff, buff_end, '%');
        break;
      }
      default: {
        RAW_CHECK_MSG(false, kPrintfFormatsHelp);
      }
    }
  }
  RAW_CHECK(buff <= buff_end);
  AppendChar(&buff, buff_end + 1, '\0');
  return result;
}

static void (*PrintfAndReportCallback)(const char *);
void SetPrintfAndReportCallback(void (*callback)(const char *)) {
  PrintfAndReportCallback = callback;
}

// Can be overriden in frontend.
#if SANITIZER_SUPPORTS_WEAK_HOOKS
SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
void OnPrint(const char *str) {
  (void)str;
}
#elif defined(SANITIZER_GO) && defined(TSAN_EXTERNAL_HOOKS)
void OnPrint(const char *str);
#else
void OnPrint(const char *str) {
  (void)str;
}
#endif

static void CallPrintfAndReportCallback(const char *str) {
  OnPrint(str);
  if (PrintfAndReportCallback)
    PrintfAndReportCallback(str);
}

static void SharedPrintfCode(bool append_pid, const char *format,
                             va_list args) {
  va_list args2;
  va_copy(args2, args);
  const int kLen = 16 * 1024;
  // |local_buffer| is small enough not to overflow the stack and/or violate
  // the stack limit enforced by TSan (-Wframe-larger-than=512). On the other
  // hand, the bigger the buffer is, the more the chance the error report will
  // fit into it.
  char local_buffer[400];
  int needed_length;
  char *buffer = local_buffer;
  int buffer_size = ARRAY_SIZE(local_buffer);
  // First try to print a message using a local buffer, and then fall back to
  // mmaped buffer.
  for (int use_mmap = 0; use_mmap < 2; use_mmap++) {
    if (use_mmap) {
      va_end(args);
      va_copy(args, args2);
      buffer = (char*)MmapOrDie(kLen, "Report");
      buffer_size = kLen;
    }
    needed_length = 0;
    if (append_pid) {
      int pid = internal_getpid();
      needed_length += internal_snprintf(buffer, buffer_size, "==%d==", pid);
      if (needed_length >= buffer_size) {
        // The pid doesn't fit into the current buffer.
        if (!use_mmap)
          continue;
        RAW_CHECK_MSG(needed_length < kLen, "Buffer in Report is too short!\n");
      }
    }
    needed_length += VSNPrintf(buffer + needed_length,
                               buffer_size - needed_length, format, args);
    if (needed_length >= buffer_size) {
      // The message doesn't fit into the current buffer.
      if (!use_mmap)
        continue;
      RAW_CHECK_MSG(needed_length < kLen, "Buffer in Report is too short!\n");
    }
    // If the message fit into the buffer, print it and exit.
    break;
  }
  RawWrite(buffer);
  AndroidLogWrite(buffer);
  CallPrintfAndReportCallback(buffer);
  // If we had mapped any memory, clean up.
  if (buffer != local_buffer)
    UnmapOrDie((void *)buffer, buffer_size);
  va_end(args2);
}

FORMAT(1, 2)
void Printf(const char *format, ...) {
  va_list args;
  va_start(args, format);
  SharedPrintfCode(false, format, args);
  va_end(args);
}

// Like Printf, but prints the current PID before the output string.
FORMAT(1, 2)
void Report(const char *format, ...) {
  va_list args;
  va_start(args, format);
  SharedPrintfCode(true, format, args);
  va_end(args);
}

// Writes at most "length" symbols to "buffer" (including trailing '\0').
// Returns the number of symbols that should have been written to buffer
// (not including trailing '\0'). Thus, the string is truncated
// iff return value is not less than "length".
FORMAT(3, 4)
int internal_snprintf(char *buffer, uptr length, const char *format, ...) {
  va_list args;
  va_start(args, format);
  int needed_length = VSNPrintf(buffer, length, format, args);
  va_end(args);
  return needed_length;
}

FORMAT(2, 3)
void InternalScopedString::append(const char *format, ...) {
  CHECK_LT(length_, size());
  va_list args;
  va_start(args, format);
  VSNPrintf(data() + length_, size() - length_, format, args);
  va_end(args);
  length_ += internal_strlen(data() + length_);
  CHECK_LT(length_, size());
}

}  // namespace __sanitizer
<|endoftext|>


<commit_before>//
// Created by permal on 8/19/17.
//

#include <vector>
#include <sstream>
#include <smooth/application/io/i2c/BME280.h>
#include <smooth/core/util/FixedBuffer.h>
#include <smooth/core/util/ByteSet.h>

namespace smooth
{
    namespace application
    {
        namespace sensor
        {
            BME280::BME280(i2c_port_t port, uint8_t address, std::mutex& guard)
                    : I2CMasterDevice(port, address, guard)
            {
            }

            uint8_t BME280::read_id()
            {
                core::util::FixedBuffer<uint8_t, 1> data;
                auto res = read(address, ID_REG, data);
                return res ? data[0] : 0;
            }

            bool BME280::reset()
            {
                // Write the magic number to the reset register
                std::vector<uint8_t> data{RESET_REG, 0xB6};
                return write(address, data, true);
            }

            bool BME280::read_status(bool& is_measuring, bool& updating_from_nvm)
            {
                core::util::FixedBuffer<uint8_t, 1> status_reg;

                bool res = read(address, STATUS_REG, status_reg);
                if (res)
                {
                    is_measuring = status_reg[0] & 0x4;
                    updating_from_nvm = status_reg[0] & 0x1;
                }

                return res;
            }

            bool BME280::configure_sensor(SensorMode mode,
                                          OverSampling humidity,
                                          OverSampling pressure,
                                          OverSampling temperature,
                                          StandbyTimeMS standby,
                                          FilterCoeff filter_coeff)
            {
                std::vector<uint8_t> data;

                data.push_back(CTRL_HUM_REG);
                data.push_back(humidity);

                data.push_back(CTRL_MEAS_REG);
                auto meas_data = static_cast<uint8_t>(temperature << 5);
                meas_data = static_cast<uint8_t>(meas_data | (pressure << 2));
                meas_data = static_cast<uint8_t>(meas_data | mode);
                data.push_back(meas_data);

                data.push_back(CONFIG_REG);
                auto config_data = static_cast<uint8_t>((standby << 5) | (filter_coeff << 2));
                data.push_back(config_data);

                return write(address, data, true);
            }

            bool BME280::read_configuration(SensorMode& mode,
                                            OverSampling& humidity,
                                            OverSampling& pressure,
                                            OverSampling& temperature,
                                            StandbyTimeMS& standby,
                                            FilterCoeff& filter)
            {
                core::util::FixedBuffer<uint8_t, 1> hum;
                core::util::FixedBuffer<uint8_t, 1> rest;
                core::util::FixedBuffer<uint8_t, 1> config;

                bool res = read(address, CTRL_HUM_REG, hum);
                res &= read(address, CTRL_MEAS_REG, rest);
                res &= read(address, CONFIG_REG, config);

                if (res)
                {
                    core::util::ByteSet h(hum[0]);
                    humidity = static_cast<OverSampling>(h.get_bits_as_byte(0, 2));

                    core::util::ByteSet r(rest[0]);
                    mode = static_cast<SensorMode>(r.get_bits_as_byte(0, 1));
                    pressure = static_cast<OverSampling>(r.get_bits_as_byte(2, 4));
                    temperature = static_cast<OverSampling>(r.get_bits_as_byte(5, 7));

                    core::util::ByteSet c(config[0]);
                    standby = static_cast<StandbyTimeMS>(c.get_bits_as_byte(5, 7));
                    filter = static_cast<FilterCoeff>(c.get_bits_as_byte(2, 4));
                }
                return res;
            }

            bool BME280::read_trimming_parameters()
            {
                if (!trimming_read)
                {
                    uint8_t h4, h4_1, h5, h5_1;

                    trimming_read =
                            read_16bit(DIG_T1_REG, trimming.dig_T1)
                            && read_16bit(DIG_T2_REG, trimming.dig_T2)
                            && read_16bit(DIG_T3_REG, trimming.dig_T3)
                            && read_16bit(DIG_P1_REG, trimming.dig_P1)
                            && read_16bit(DIG_P2_REG, trimming.dig_P2)
                            && read_16bit(DIG_P3_REG, trimming.dig_P3)
                            && read_16bit(DIG_P4_REG, trimming.dig_P4)
                            && read_16bit(DIG_P5_REG, trimming.dig_P5)
                            && read_16bit(DIG_P6_REG, trimming.dig_P6)
                            && read_16bit(DIG_P7_REG, trimming.dig_P7)
                            && read_16bit(DIG_P8_REG, trimming.dig_P8)
                            && read_16bit(DIG_P9_REG, trimming.dig_P8)
                            && read_8bit(DIG_H1_REG, trimming.dig_H1)
                            && read_16bit(DIG_H2_REG, trimming.dig_H2)
                            && read_8bit(DIG_H3_REG, trimming.dig_H3)
                            && read_8bit(DIG_H6_REG, trimming.dig_H6)

                            // The following data is a bit tricky as it is split over multiple bytes.
                            // dig_H4: Bits 11:4 located in DIG_H4_REG, bits 3:0 located in DIG_H4_REG+1
                            // dig_H5: bits 3:0 located in DIG_H5_REG[7:4], bits 11:4 in DIG_H5_REG+1

                            && read_8bit(DIG_H4_REG, h4)
                            && read_8bit(static_cast<uint8_t>(DIG_H4_REG + 1), h4_1)
                            && read_8bit(DIG_H5_REG, h5)
                            && read_8bit(static_cast<uint8_t>(DIG_H5_REG + 1), h5_1);

                    // Adjust values so they are directly usable.
                    trimming.dig_H4 = static_cast<int16_t>((h4 << 4) | (h4_1 & 0xF));
                    trimming.dig_H5 = static_cast<int16_t>((h5 >> 4) | (h5_1 << 4));
                }

                return trimming_read;
            }

            bool BME280::read_measurements(float& humidity, float& pressure, float& temperature)
            {
                core::util::FixedBuffer<uint8_t, 8> measurement{};

                humidity = 0;
                pressure = 0;
                temperature = 0;

                bool res = read_trimming_parameters();
                res = res && read(address, PRESS_MSB_REG, measurement);

                if (res)
                {
                    // Temperature data is at index: MSB: 3, LSB: 4, XLSB: 5
                    auto temp = measurement[5] & 0x0F;
                    temp |= measurement[4] << 4;
                    temp |= measurement[3] << (4 + 8);

                    temperature = static_cast<float>(BME280_compensate_T_int32(temp) / 100.0);

                    // Pressure data is at index: MSB: 0, LSB: 1, XLSB: 2
                    int32_t press = measurement[2] & 0xF;
                    press |= measurement[1] << 4;
                    press |= measurement[0] << (4 + 8);

                    pressure = static_cast<float>(BME280_compensate_P_int64(press) / 256.0);

                    // Humidity data is at index: MSB: 6, LSB: 7

                    int32_t hum = measurement[7];
                    hum |= measurement[6] << 8;

                    humidity = static_cast<float>(BME280_compensate_H_int32(hum) / 1024);
                }

                return res;
            }

            BME280::BME280_S32_t BME280::BME280_compensate_T_int32(BME280_S32_t adc_T)
            {
                BME280_S32_t var1, var2, T;
                var1 = ((((adc_T >> 3) - ((BME280_S32_t) trimming.dig_T1 << 1)))
                        * ((BME280_S32_t) trimming.dig_T2)) >> 11;

                var2 = (((((adc_T >> 4) - ((BME280_S32_t) trimming.dig_T1)) *
                          ((adc_T >> 4) - ((BME280_S32_t) trimming.dig_T1))) >> 12) *
                        ((BME280_S32_t) trimming.dig_T3)) >> 14;
                t_fine = var1 + var2;
                T = (t_fine * 5 + 128) >> 8;
                return T;
            }

            BME280::BME280_U32_t BME280::BME280_compensate_P_int64(BME280_S32_t adc_P)
            {
                BME280_S64_t var1, var2, p;
                var1 = ((BME280_S64_t) t_fine) - 128000;
                var2 = var1 * var1 * (BME280_S64_t) trimming.dig_P6;
                var2 = var2 + ((var1 * (BME280_S64_t) trimming.dig_P5) << 17);
                var2 = var2 + (((BME280_S64_t) trimming.dig_P4) << 35);
                var1 = ((var1 * var1 * (BME280_S64_t) trimming.dig_P3) >> 8) +
                       ((var1 * (BME280_S64_t) trimming.dig_P2) << 12);
                var1 = (((((BME280_S64_t) 1) << 47) + var1)) * ((BME280_S64_t) trimming.dig_P1) >> 33;
                if (var1 == 0)
                {
                    return 0; // avoid exception caused by division by zero
                }
                p = 1048576 - adc_P;
                p = (((p << 31) - var2) * 3125) / var1;
                var1 = (((BME280_S64_t) trimming.dig_P9) * (p >> 13) * (p >> 13)) >> 25;
                var2 = (((BME280_S64_t) trimming.dig_P8) * p) >> 19;
                p = ((p + var1 + var2) >> 8) + (((BME280_S64_t) trimming.dig_P7) << 4);
                return (BME280_U32_t) p;
            }

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wuseless-cast"
            BME280::BME280_U32_t BME280::BME280_compensate_H_int32(BME280_S32_t adc_H)
            {
                BME280_S32_t v_x1_u32r;
                v_x1_u32r = (t_fine - ((BME280_S32_t) 76800));
                v_x1_u32r = (((((adc_H << 14) - (((BME280_S32_t) trimming.dig_H4) << 20) -
                                (((BME280_S32_t) trimming.dig_H5) *
                                 v_x1_u32r)) +
                               ((BME280_S32_t) 16384)) >> 15) * (
                                     ((((((v_x1_u32r * ((BME280_S32_t) trimming.dig_H6)) >> 10) * (((v_x1_u32r *
                                                                                ((BME280_S32_t) trimming.dig_H3))
                                             >> 11) +
                                                                                ((BME280_S32_t) 32768)))
                                             >> 10) +
                                       ((BME280_S32_t) 2097152)) *
                                      ((BME280_S32_t) trimming.dig_H2) + 8192) >> 14));
                v_x1_u32r = (v_x1_u32r -
                             (((((v_x1_u32r >> 15) * (v_x1_u32r >> 15)) >> 7) * ((BME280_S32_t) trimming.dig_H1))
                                     >> 4));
                v_x1_u32r = (v_x1_u32r < 0 ? 0 : v_x1_u32r);
                v_x1_u32r = (v_x1_u32r > 419430400 ? 419430400 : v_x1_u32r);
                return (BME280_U32_t) (v_x1_u32r >> 12);
            }
        }
#pragma GCC diagnostic pop
    }
}

<commit_msg>#38 - Used dig_P8 instead if dig_P9.<commit_after>//
// Created by permal on 8/19/17.
//

#include <vector>
#include <sstream>
#include <smooth/application/io/i2c/BME280.h>
#include <smooth/core/util/FixedBuffer.h>
#include <smooth/core/util/ByteSet.h>

namespace smooth
{
    namespace application
    {
        namespace sensor
        {
            BME280::BME280(i2c_port_t port, uint8_t address, std::mutex& guard)
                    : I2CMasterDevice(port, address, guard)
            {
            }

            uint8_t BME280::read_id()
            {
                core::util::FixedBuffer<uint8_t, 1> data;
                auto res = read(address, ID_REG, data);
                return res ? data[0] : 0;
            }

            bool BME280::reset()
            {
                // Write the magic number to the reset register
                std::vector<uint8_t> data{RESET_REG, 0xB6};
                return write(address, data, true);
            }

            bool BME280::read_status(bool& is_measuring, bool& updating_from_nvm)
            {
                core::util::FixedBuffer<uint8_t, 1> status_reg;

                bool res = read(address, STATUS_REG, status_reg);
                if (res)
                {
                    is_measuring = status_reg[0] & 0x4;
                    updating_from_nvm = status_reg[0] & 0x1;
                }

                return res;
            }

            bool BME280::configure_sensor(SensorMode mode,
                                          OverSampling humidity,
                                          OverSampling pressure,
                                          OverSampling temperature,
                                          StandbyTimeMS standby,
                                          FilterCoeff filter_coeff)
            {
                std::vector<uint8_t> data;

                data.push_back(CTRL_HUM_REG);
                data.push_back(humidity);

                data.push_back(CTRL_MEAS_REG);
                auto meas_data = static_cast<uint8_t>(temperature << 5);
                meas_data = static_cast<uint8_t>(meas_data | (pressure << 2));
                meas_data = static_cast<uint8_t>(meas_data | mode);
                data.push_back(meas_data);

                data.push_back(CONFIG_REG);
                auto config_data = static_cast<uint8_t>((standby << 5) | (filter_coeff << 2));
                data.push_back(config_data);

                return write(address, data, true);
            }

            bool BME280::read_configuration(SensorMode& mode,
                                            OverSampling& humidity,
                                            OverSampling& pressure,
                                            OverSampling& temperature,
                                            StandbyTimeMS& standby,
                                            FilterCoeff& filter)
            {
                core::util::FixedBuffer<uint8_t, 1> hum;
                core::util::FixedBuffer<uint8_t, 1> rest;
                core::util::FixedBuffer<uint8_t, 1> config;

                bool res = read(address, CTRL_HUM_REG, hum);
                res &= read(address, CTRL_MEAS_REG, rest);
                res &= read(address, CONFIG_REG, config);

                if (res)
                {
                    core::util::ByteSet h(hum[0]);
                    humidity = static_cast<OverSampling>(h.get_bits_as_byte(0, 2));

                    core::util::ByteSet r(rest[0]);
                    mode = static_cast<SensorMode>(r.get_bits_as_byte(0, 1));
                    pressure = static_cast<OverSampling>(r.get_bits_as_byte(2, 4));
                    temperature = static_cast<OverSampling>(r.get_bits_as_byte(5, 7));

                    core::util::ByteSet c(config[0]);
                    standby = static_cast<StandbyTimeMS>(c.get_bits_as_byte(5, 7));
                    filter = static_cast<FilterCoeff>(c.get_bits_as_byte(2, 4));
                }
                return res;
            }

            bool BME280::read_trimming_parameters()
            {
                if (!trimming_read)
                {
                    uint8_t h4, h4_1, h5, h5_1;

                    trimming_read =
                            read_16bit(DIG_T1_REG, trimming.dig_T1)
                            && read_16bit(DIG_T2_REG, trimming.dig_T2)
                            && read_16bit(DIG_T3_REG, trimming.dig_T3)
                            && read_16bit(DIG_P1_REG, trimming.dig_P1)
                            && read_16bit(DIG_P2_REG, trimming.dig_P2)
                            && read_16bit(DIG_P3_REG, trimming.dig_P3)
                            && read_16bit(DIG_P4_REG, trimming.dig_P4)
                            && read_16bit(DIG_P5_REG, trimming.dig_P5)
                            && read_16bit(DIG_P6_REG, trimming.dig_P6)
                            && read_16bit(DIG_P7_REG, trimming.dig_P7)
                            && read_16bit(DIG_P8_REG, trimming.dig_P8)
                            && read_16bit(DIG_P9_REG, trimming.dig_P9)
                            && read_8bit(DIG_H1_REG, trimming.dig_H1)
                            && read_16bit(DIG_H2_REG, trimming.dig_H2)
                            && read_8bit(DIG_H3_REG, trimming.dig_H3)
                            && read_8bit(DIG_H6_REG, trimming.dig_H6)

                            // The following data is a bit tricky as it is split over multiple bytes.
                            // dig_H4: Bits 11:4 located in DIG_H4_REG, bits 3:0 located in DIG_H4_REG+1
                            // dig_H5: bits 3:0 located in DIG_H5_REG[7:4], bits 11:4 in DIG_H5_REG+1

                            && read_8bit(DIG_H4_REG, h4)
                            && read_8bit(static_cast<uint8_t>(DIG_H4_REG + 1), h4_1)
                            && read_8bit(DIG_H5_REG, h5)
                            && read_8bit(static_cast<uint8_t>(DIG_H5_REG + 1), h5_1);

                    // Adjust values so they are directly usable.
                    trimming.dig_H4 = static_cast<int16_t>((h4 << 4) | (h4_1 & 0xF));
                    trimming.dig_H5 = static_cast<int16_t>((h5 >> 4) | (h5_1 << 4));
                }

                return trimming_read;
            }

            bool BME280::read_measurements(float& humidity, float& pressure, float& temperature)
            {
                core::util::FixedBuffer<uint8_t, 8> measurement{};

                humidity = 0;
                pressure = 0;
                temperature = 0;

                bool res = read_trimming_parameters();
                res = res && read(address, PRESS_MSB_REG, measurement);

                if (res)
                {
                    // Temperature data is at index: MSB: 3, LSB: 4, XLSB: 5
                    auto temp = measurement[5] & 0x0F;
                    temp |= measurement[4] << 4;
                    temp |= measurement[3] << (4 + 8);

                    temperature = static_cast<float>(BME280_compensate_T_int32(temp) / 100.0);

                    // Pressure data is at index: MSB: 0, LSB: 1, XLSB: 2
                    int32_t press = measurement[2] & 0xF;
                    press |= measurement[1] << 4;
                    press |= measurement[0] << (4 + 8);

                    pressure = static_cast<float>(BME280_compensate_P_int64(press) / 256.0);

                    // Humidity data is at index: MSB: 6, LSB: 7

                    int32_t hum = measurement[7];
                    hum |= measurement[6] << 8;

                    humidity = static_cast<float>(BME280_compensate_H_int32(hum) / 1024);
                }

                return res;
            }

            BME280::BME280_S32_t BME280::BME280_compensate_T_int32(BME280_S32_t adc_T)
            {
                BME280_S32_t var1, var2, T;
                var1 = ((((adc_T >> 3) - ((BME280_S32_t) trimming.dig_T1 << 1)))
                        * ((BME280_S32_t) trimming.dig_T2)) >> 11;

                var2 = (((((adc_T >> 4) - ((BME280_S32_t) trimming.dig_T1)) *
                          ((adc_T >> 4) - ((BME280_S32_t) trimming.dig_T1))) >> 12) *
                        ((BME280_S32_t) trimming.dig_T3)) >> 14;
                t_fine = var1 + var2;
                T = (t_fine * 5 + 128) >> 8;
                return T;
            }

            BME280::BME280_U32_t BME280::BME280_compensate_P_int64(BME280_S32_t adc_P)
            {
                BME280_S64_t var1, var2, p;
                var1 = ((BME280_S64_t) t_fine) - 128000;
                var2 = var1 * var1 * (BME280_S64_t) trimming.dig_P6;
                var2 = var2 + ((var1 * (BME280_S64_t) trimming.dig_P5) << 17);
                var2 = var2 + (((BME280_S64_t) trimming.dig_P4) << 35);
                var1 = ((var1 * var1 * (BME280_S64_t) trimming.dig_P3) >> 8) +
                       ((var1 * (BME280_S64_t) trimming.dig_P2) << 12);
                var1 = (((((BME280_S64_t) 1) << 47) + var1)) * ((BME280_S64_t) trimming.dig_P1) >> 33;
                if (var1 == 0)
                {
                    return 0; // avoid exception caused by division by zero
                }
                p = 1048576 - adc_P;
                p = (((p << 31) - var2) * 3125) / var1;
                var1 = (((BME280_S64_t) trimming.dig_P9) * (p >> 13) * (p >> 13)) >> 25;
                var2 = (((BME280_S64_t) trimming.dig_P8) * p) >> 19;
                p = ((p + var1 + var2) >> 8) + (((BME280_S64_t) trimming.dig_P7) << 4);
                return (BME280_U32_t) p;
            }

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wuseless-cast"
            BME280::BME280_U32_t BME280::BME280_compensate_H_int32(BME280_S32_t adc_H)
            {
                BME280_S32_t v_x1_u32r;
                v_x1_u32r = (t_fine - ((BME280_S32_t) 76800));
                v_x1_u32r = (((((adc_H << 14) - (((BME280_S32_t) trimming.dig_H4) << 20) -
                                (((BME280_S32_t) trimming.dig_H5) *
                                 v_x1_u32r)) +
                               ((BME280_S32_t) 16384)) >> 15) * (
                                     ((((((v_x1_u32r * ((BME280_S32_t) trimming.dig_H6)) >> 10) * (((v_x1_u32r *
                                                                                ((BME280_S32_t) trimming.dig_H3))
                                             >> 11) +
                                                                                ((BME280_S32_t) 32768)))
                                             >> 10) +
                                       ((BME280_S32_t) 2097152)) *
                                      ((BME280_S32_t) trimming.dig_H2) + 8192) >> 14));
                v_x1_u32r = (v_x1_u32r -
                             (((((v_x1_u32r >> 15) * (v_x1_u32r >> 15)) >> 7) * ((BME280_S32_t) trimming.dig_H1))
                                     >> 4));
                v_x1_u32r = (v_x1_u32r < 0 ? 0 : v_x1_u32r);
                v_x1_u32r = (v_x1_u32r > 419430400 ? 419430400 : v_x1_u32r);
                return (BME280_U32_t) (v_x1_u32r >> 12);
            }
        }
#pragma GCC diagnostic pop
    }
}

<|endoftext|>


<commit_before><commit_msg>Perception: Fix blinking traffic light in dreamview<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: basdoc.cxx,v $
 *
 *  $Revision: 1.1.1.1 $
 *
 *  last change: $Author: mh $ $Date: 2000-09-29 11:02:35 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <ide_pch.hxx>

#pragma hdrstop

#define GLOBALOVERFLOW2

#include <sfx2/docfac.hxx>

#ifndef _SV_STATUS_HXX //autogen
#include <vcl/status.hxx>
#endif

#include <basdoc.hxx>
#include <basidesh.hrc>

#define BasicDocShell
#include <baside.hxx>

SFX_IMPL_SIMPLE_OBJECTFACTORY( BasicDocShell, SFXOBJECTSHELL_STD_SPECIAL | SFXOBJECTSHELL_DONTREPLACE, side3 )
{
    Factory().SetExplorerImageId( IMG_SFX_EXP_MACROLIB );
    Factory().RegisterHelpFile( String( RTL_CONSTASCII_USTRINGPARAM( "sbasic" ) ) );
}

SFX_IMPL_INTERFACE( BasicDocShell, SfxObjectShell, IDEResId( 0 ) )
{
    SFX_STATUSBAR_REGISTRATION( SID_BASICIDE_STATUSBAR );
//  SFX_CHILDWINDOW_REGISTRATION( SID_SHOW_BROWSER );
}

BasicDocShell::BasicDocShell( SfxObjectCreateMode eMode ) : SfxObjectShell( eMode )
{
    pPrinter = 0;
    SetPool( &SFX_APP()->GetPool() );
}

__EXPORT BasicDocShell::~BasicDocShell()
{
    delete pPrinter;
}

void __EXPORT BasicDocShell::Execute( SfxRequest& rReq )
{
}

void __EXPORT BasicDocShell::GetState(SfxItemSet &rSet)
{
}

SfxPrinter* BasicDocShell::GetPrinter( BOOL bCreate )
{
    if ( !pPrinter && bCreate )
        pPrinter = new SfxPrinter( new SfxItemSet( GetPool(), SID_PRINTER_NOTFOUND_WARN , SID_PRINTER_NOTFOUND_WARN ) );

    return pPrinter;
}

void BasicDocShell::SetPrinter( SfxPrinter* pPr )
{
    if ( pPr != pPrinter )
    {
        delete pPrinter;
        pPrinter = pPr;
    }
}

void BasicDocShell::FillStatusBar( StatusBar& rStatusBar )
{
    String aTmp;

    // Titel
    aTmp.Fill( 30, 'X' );
    rStatusBar.InsertItem( SID_BASICIDE_STAT_TITLE,
        rStatusBar.GetTextWidth( aTmp ), SIB_AUTOSIZE | SIB_LEFT);

    // Modify
    rStatusBar.InsertItem( SID_DOC_MODIFIED,
        rStatusBar.GetTextWidth( '*' ) );

    // Position
    aTmp.Erase();
    aTmp.Fill( 15, 'X' );
    rStatusBar.InsertItem( SID_BASICIDE_STAT_POS,
        rStatusBar.GetTextWidth( aTmp ), SIB_LEFT);

    // Insert/Overwrite
    rStatusBar.InsertItem( SID_ATTR_INSERT,
        rStatusBar.GetTextWidth( String( RTL_CONSTASCII_USTRINGPARAM( "XXXXX" /* "EINFG" */ ) ) ) );

    // Uhrzeit
    aTmp.Fill( 20, 'X' );
    rStatusBar.InsertItem( SID_ATTR_SIZE,
        rStatusBar.GetTextWidth( aTmp ), SIB_AUTOSIZE | SIB_LEFT | SIB_USERDRAW );

//  return pStatusBar;

}

<commit_msg>img defines now from svtools<commit_after>/*************************************************************************
 *
 *  $RCSfile: basdoc.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: kz $ $Date: 2001-05-08 13:52:00 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <ide_pch.hxx>

#pragma hdrstop

#define GLOBALOVERFLOW2

#include <sfx2/docfac.hxx>

#ifndef _SV_STATUS_HXX //autogen
#include <vcl/status.hxx>
#endif

#include <basdoc.hxx>
#include <basidesh.hrc>

#define BasicDocShell
#include <baside.hxx>

SFX_IMPL_SIMPLE_OBJECTFACTORY( BasicDocShell, SFXOBJECTSHELL_STD_SPECIAL | SFXOBJECTSHELL_DONTREPLACE, side3 )
{
    Factory().SetExplorerImageId( IMG_MACROLIB );
    Factory().RegisterHelpFile( String( RTL_CONSTASCII_USTRINGPARAM( "sbasic" ) ) );
}

SFX_IMPL_INTERFACE( BasicDocShell, SfxObjectShell, IDEResId( 0 ) )
{
    SFX_STATUSBAR_REGISTRATION( SID_BASICIDE_STATUSBAR );
//  SFX_CHILDWINDOW_REGISTRATION( SID_SHOW_BROWSER );
}

BasicDocShell::BasicDocShell( SfxObjectCreateMode eMode ) : SfxObjectShell( eMode )
{
    pPrinter = 0;
    SetPool( &SFX_APP()->GetPool() );
}

__EXPORT BasicDocShell::~BasicDocShell()
{
    delete pPrinter;
}

void __EXPORT BasicDocShell::Execute( SfxRequest& rReq )
{
}

void __EXPORT BasicDocShell::GetState(SfxItemSet &rSet)
{
}

SfxPrinter* BasicDocShell::GetPrinter( BOOL bCreate )
{
    if ( !pPrinter && bCreate )
        pPrinter = new SfxPrinter( new SfxItemSet( GetPool(), SID_PRINTER_NOTFOUND_WARN , SID_PRINTER_NOTFOUND_WARN ) );

    return pPrinter;
}

void BasicDocShell::SetPrinter( SfxPrinter* pPr )
{
    if ( pPr != pPrinter )
    {
        delete pPrinter;
        pPrinter = pPr;
    }
}

void BasicDocShell::FillStatusBar( StatusBar& rStatusBar )
{
    String aTmp;

    // Titel
    aTmp.Fill( 30, 'X' );
    rStatusBar.InsertItem( SID_BASICIDE_STAT_TITLE,
        rStatusBar.GetTextWidth( aTmp ), SIB_AUTOSIZE | SIB_LEFT);

    // Modify
    rStatusBar.InsertItem( SID_DOC_MODIFIED,
        rStatusBar.GetTextWidth( '*' ) );

    // Position
    aTmp.Erase();
    aTmp.Fill( 15, 'X' );
    rStatusBar.InsertItem( SID_BASICIDE_STAT_POS,
        rStatusBar.GetTextWidth( aTmp ), SIB_LEFT);

    // Insert/Overwrite
    rStatusBar.InsertItem( SID_ATTR_INSERT,
        rStatusBar.GetTextWidth( String( RTL_CONSTASCII_USTRINGPARAM( "XXXXX" /* "EINFG" */ ) ) ) );

    // Uhrzeit
    aTmp.Fill( 20, 'X' );
    rStatusBar.InsertItem( SID_ATTR_SIZE,
        rStatusBar.GetTextWidth( aTmp ), SIB_AUTOSIZE | SIB_LEFT | SIB_USERDRAW );

//  return pStatusBar;

}

<|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.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_basctl.hxx"

#include <ide_pch.hxx>
#include <svx/svxids.hrc>

#include <sfx2/docfac.hxx>
#include <sfx2/sfxmodelfactory.hxx>
#include <vcl/status.hxx>

#include <svx/xmlsecctrl.hxx>

#include <basdoc.hxx>

#define BasicDocShell
#include <basslots.hxx>

#include "basicmod.hxx"
#include "unomodel.hxx"

TYPEINIT1(BasicDocShell, SfxObjectShell);
DBG_NAME(BasicDocShell);

SFX_IMPL_OBJECTFACTORY( BasicDocShell, SvGlobalName(), SFXOBJECTSHELL_STD_NORMAL, "sbasic" )

SFX_IMPL_INTERFACE( BasicDocShell, SfxObjectShell, IDEResId( 0 ) )
{
    SFX_STATUSBAR_REGISTRATION( IDEResId( SID_BASICIDE_STATUSBAR ) );
}

BasicDocShell::BasicDocShell()
    :SfxObjectShell( SFXMODEL_DISABLE_EMBEDDED_SCRIPTS | SFXMODEL_DISABLE_DOCUMENT_RECOVERY )
{
    pPrinter = 0;
    SetPool( &SFX_APP()->GetPool() );
    SetBaseModel( new SIDEModel(this) );
}

BasicDocShell::~BasicDocShell()
{
    delete pPrinter;
}

SfxPrinter* BasicDocShell::GetPrinter( sal_Bool bCreate )
{
    if ( !pPrinter && bCreate )
        pPrinter = new SfxPrinter( new SfxItemSet( GetPool(), SID_PRINTER_NOTFOUND_WARN , SID_PRINTER_NOTFOUND_WARN ) );

    return pPrinter;
}

void BasicDocShell::SetPrinter( SfxPrinter* pPr )
{
    if ( pPr != pPrinter )
    {
        delete pPrinter;
        pPrinter = pPr;
    }
}

void BasicDocShell::FillClass( SvGlobalName*, sal_uInt32*, String*, String*, String*, sal_Int32, sal_Bool bTemplate) const
{
    (void)bTemplate;
    DBG_ASSERT( bTemplate == sal_False, "No template for Basic" );
}

void BasicDocShell::Draw( OutputDevice *, const JobSetup &, sal_uInt16 )
{}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Remove unnecessary includes<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.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_basctl.hxx"
#include <ide_pch.hxx>

#include "unomodel.hxx"

#include <basdoc.hxx>
#define BasicDocShell     // This CANNOT come before basdoc apparently
#include <basslots.hxx>
#include <sfx2/sfxmodelfactory.hxx>
#include <svx/svxids.hrc>

TYPEINIT1(BasicDocShell, SfxObjectShell);
DBG_NAME(BasicDocShell);

SFX_IMPL_OBJECTFACTORY( BasicDocShell, SvGlobalName(), SFXOBJECTSHELL_STD_NORMAL, "sbasic" )

SFX_IMPL_INTERFACE( BasicDocShell, SfxObjectShell, IDEResId( 0 ) )
{
    SFX_STATUSBAR_REGISTRATION( IDEResId( SID_BASICIDE_STATUSBAR ) );
}

BasicDocShell::BasicDocShell()
    :SfxObjectShell( SFXMODEL_DISABLE_EMBEDDED_SCRIPTS | SFXMODEL_DISABLE_DOCUMENT_RECOVERY )
{
    pPrinter = 0;
    SetPool( &SFX_APP()->GetPool() );
    SetBaseModel( new SIDEModel(this) );
}

BasicDocShell::~BasicDocShell()
{
    delete pPrinter;
}

SfxPrinter* BasicDocShell::GetPrinter( sal_Bool bCreate )
{
    if ( !pPrinter && bCreate )
        pPrinter = new SfxPrinter( new SfxItemSet( GetPool(), SID_PRINTER_NOTFOUND_WARN , SID_PRINTER_NOTFOUND_WARN ) );

    return pPrinter;
}

void BasicDocShell::SetPrinter( SfxPrinter* pPr )
{
    if ( pPr != pPrinter )
    {
        delete pPrinter;
        pPrinter = pPr;
    }
}

void BasicDocShell::FillClass( SvGlobalName*, sal_uInt32*, String*, String*, String*, sal_Int32, sal_Bool bTemplate) const
{
    (void)bTemplate;
    DBG_ASSERT( bTemplate == sal_False, "No template for Basic" );
}

void BasicDocShell::Draw( OutputDevice *, const JobSetup &, sal_uInt16 )
{}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>