<commit_before>#include "itkImageFileReader.h"
#include "itkImage.h"
#include "itkLabelImageToShapeLabelMapFilter.h"
#include "itkStatisticsLabelObject.h"
#include <iostream>
#include <string>

#include "itkTestDriverIncludeRequiredIOFactories.h"

int main( int argc, char *argv[] )
{

  RegisterRequiredFactories();

  if (argc < 4)
    {
    std::cerr << "Not enough arguments." << std::endl;
    return 0;
    }

  std::string imageFileName = argv[1];
  std::string labelImageFileName = argv[2];
  itk::SizeValueType label = atoi(argv[3]);

  const unsigned int ImageDimension = 3;
  typedef uint32_t PixelType;
  typedef itk::Image<PixelType, ImageDimension> ImageType;

  typedef itk::ImageFileReader<ImageType> ImageReaderType;
  ImageReaderType::Pointer reader = ImageReaderType::New();
  reader->SetFileName( labelImageFileName );
  reader->UpdateLargestPossibleRegion();

  ImageType::Pointer image = reader->GetOutput();

  typedef itk::StatisticsLabelObject<PixelType, ImageType::ImageDimension> LabelObjectType;

  typedef itk::LabelMap<LabelObjectType> LabelMapType;
  typedef itk::LabelImageToShapeLabelMapFilter<ImageType, LabelMapType> ShapeLabelMapFilter;

  typedef vnl_matrix<double> MatrixType;
  typedef vnl_vector<double> VectorType;

  ShapeLabelMapFilter::Pointer stats = ShapeLabelMapFilter::New();
  stats->SetInput(image);
  stats->ComputePerimeterOn();
  stats->UpdateLargestPossibleRegion();
  LabelMapType::Pointer labelCollection = stats->GetOutput();
  LabelObjectType *labelObject = labelCollection->GetLabelObject(label);

  const MatrixType rotationMatrix = labelObject->GetPrincipalAxes().GetVnlMatrix();
  const LabelObjectType::CentroidType centroid = labelObject->GetCentroid();
  const unsigned int numLines = labelObject->GetNumberOfLines();

  std::cout << "using label object: ";
  labelObject->Print(std::cout);
  std::cout << std::endl;

  // Create a matrix where the columns are the physical points of the
  // start and end of each RLE line from the label map, relative to
  // the centroid
  MatrixType pixelLocations( ImageDimension, labelObject->GetNumberOfLines()*2 );
  for( unsigned int l = 0; l < numLines; ++l )
    {
    LabelObjectType::LineType line = labelObject->GetLine(l);

    // add start index of line as physical point
    ImageType::IndexType idx = line.GetIndex();
    ImageType::PointType pt;
    image->TransformIndexToPhysicalPoint(idx, pt);
    for(unsigned int j = 0; j < ImageDimension; ++j)
      {
      pixelLocations(j,l*2) = pt[j] - centroid[j];
      }

    // add end index of line as physical point
    idx[0] +=  line.GetLength()-1;
    image->TransformIndexToPhysicalPoint(idx, pt);
    for(unsigned int j = 0; j < ImageDimension; ++j)
      {
      pixelLocations(j,l*2+1) = pt[j] - centroid[j];
      }
    }

  // Project the physical points onto principal axes
  MatrixType transformedPixelLocations = rotationMatrix * pixelLocations;

  // find the bounds in the projected domain
  VectorType proj_min(ImageDimension, 0);
  VectorType proj_max(ImageDimension, 0);

  for ( unsigned int i = 0; i < ImageDimension; ++i )
    {
    const double value = transformedPixelLocations(i, 0);
    proj_min[i] = value;
    proj_max[i] = value;
    }

  for ( unsigned int column = 1; column < transformedPixelLocations.columns(); column++ )
    {
    for ( unsigned int i = 0; i < ImageDimension; ++i )
      {
      const double value = transformedPixelLocations(i, column);
      proj_min[i] = std::min(proj_min[i], value);
      proj_max[i] = std::max(proj_max[i], value);
      }
    }

  // the center of the input voxel should the origin?
  VectorType proj_origin = proj_min;

  const itk::Vector<double, ImageDimension> gridOffset = 0.5*image->GetSpacing();
  itk::Vector<double, ImageDimension> physicalOffset;
  image->TransformLocalVectorToPhysicalVector(gridOffset, physicalOffset);
  VectorType proj_offset = rotationMatrix * physicalOffset.GetVnlVector();

  std::cout << "proj_min w/o offset: " << proj_min << std::endl;
  std::cout << "proj_max w/o offset: " << proj_max << std::endl;

  for ( unsigned int i = 0; i < ImageDimension; ++i )
    {
    proj_min[i] -= proj_offset[i];
    proj_max[i] += proj_offset[i];
    }

  VectorType origin =  rotationMatrix.transpose() *  proj_origin; // offset
                                                                  // by spacing....
  for ( unsigned int i = 0; i < ImageDimension; ++i )
    {
    origin[i] += centroid[i];
    }

  ImageType::SizeType size;
  for ( unsigned int i = 0; i < ImageDimension; ++i )
    {
    size[i] = vnl_math_abs(proj_max[i]-proj_min[i]);
    }

  std::cout << "proj_min: " << proj_min << std::endl;
  std::cout << "proj_max: " << proj_max << std::endl;
  std::cout << "origin: " << origin << std::endl;
  std::cout << "size: " << size << std::endl;

  ImageType::DirectionType direction( rotationMatrix.transpose() );
  std::cout << "direction: " << direction;

  return 0;
}
<commit_msg>Added resample intensity image to OBB example<commit_after>#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkImage.h"
#include "itkLabelImageToShapeLabelMapFilter.h"
#include "itkStatisticsLabelObject.h"
#include "itkResampleImageFilter.h"
#include <iostream>
#include <string>

#include "itkTestDriverIncludeRequiredIOFactories.h"

int main( int argc, char *argv[] )
{

  RegisterRequiredFactories();

  if (argc < 5)
    {
    std::cerr << "Usage: " << argv[0] << "imageFileName labelImageFileName outputImageFileName labelID" << std::endl;
    return 0;
    }

  std::string imageFileName = argv[1];
  std::string labelImageFileName = argv[2];
  std::string outputImageFileName = argv[3];
  itk::SizeValueType label = atoi(argv[4]);

  const unsigned int ImageDimension = 3;
  typedef uint32_t LabelPixelType;
  typedef itk::Image<LabelPixelType, ImageDimension> LabelImageType;

  typedef itk::Image<float, ImageDimension> ImageType;

  LabelImageType::Pointer labelImage;
  {
  typedef itk::ImageFileReader<LabelImageType> ImageReaderType;
  ImageReaderType::Pointer reader = ImageReaderType::New();
  reader->SetFileName( labelImageFileName );

  std::cout << "Reading labelImage..." << std::endl;
  reader->UpdateLargestPossibleRegion();
  labelImage = reader->GetOutput();
  }

  typedef itk::StatisticsLabelObject<LabelPixelType, ImageDimension> LabelObjectType;

  typedef itk::LabelMap<LabelObjectType> LabelMapType;
  typedef itk::LabelImageToShapeLabelMapFilter<LabelImageType, LabelMapType> ShapeLabelMapFilter;

  typedef vnl_matrix<double> MatrixType;
  typedef vnl_vector<double> VectorType;

  ShapeLabelMapFilter::Pointer stats = ShapeLabelMapFilter::New();
  stats->SetInput(labelImage);
  stats->ComputePerimeterOn();
  std::cout << "Computing shape labels..." << std::endl;
  stats->UpdateLargestPossibleRegion();

  LabelMapType::Pointer labelCollection = stats->GetOutput();
  LabelObjectType *labelObject = labelCollection->GetLabelObject(label);

  std::cout << "Computing label OBB..." << std::endl;
  const MatrixType rotationMatrix = labelObject->GetPrincipalAxes().GetVnlMatrix();
  const LabelObjectType::CentroidType centroid = labelObject->GetCentroid();
  const unsigned int numLines = labelObject->GetNumberOfLines();

  // Create a matrix where the columns are the physical points of the
  // start and end of each RLE line from the label map, relative to
  // the centroid
  MatrixType pixelLocations( ImageDimension, labelObject->GetNumberOfLines()*2 );
  for( unsigned int l = 0; l < numLines; ++l )
    {
    LabelObjectType::LineType line = labelObject->GetLine(l);

    // add start index of line as physical point
    LabelImageType::IndexType idx = line.GetIndex();
    LabelImageType::PointType pt;
    labelImage->TransformIndexToPhysicalPoint(idx, pt);
    for(unsigned int j = 0; j < ImageDimension; ++j)
      {
      pixelLocations(j,l*2) = pt[j] - centroid[j];
      }

    // add end index of line as physical point
    idx[0] +=  line.GetLength()-1;
    labelImage->TransformIndexToPhysicalPoint(idx, pt);
    for(unsigned int j = 0; j < ImageDimension; ++j)
      {
      pixelLocations(j,l*2+1) = pt[j] - centroid[j];
      }
    }

  // Project the physical points onto principal axes
  MatrixType transformedPixelLocations = rotationMatrix * pixelLocations;

  // find the bounds in the projected domain
  assert( transformedPixelLocations.columns() != 0 );
  VectorType proj_min = transformedPixelLocations.get_column(0);
  VectorType proj_max = transformedPixelLocations.get_column(0);

  for ( unsigned int column = 1; column < transformedPixelLocations.columns(); column++ )
    {
    for ( unsigned int i = 0; i < ImageDimension; ++i )
      {
      const double value = transformedPixelLocations(i, column);
      proj_min[i] = std::min(proj_min[i], value);
      proj_max[i] = std::max(proj_max[i], value);
      }
    }

  std::cout << "proj_min w/o offset: " << proj_min << std::endl;
  std::cout << "proj_max w/o offset: " << proj_max << std::endl;

  // the center of the input voxel should the origin?
  VectorType proj_origin = proj_min;

  // The proj_min/max is from center of pixel to center of pixel. The
  // full extent of the pixels needs to include the offset bits to the
  // corners, projected onto the principle axis basis (rotationMatrix).
  const itk::Vector<double, ImageDimension> gridOffset = 0.5*labelImage->GetSpacing();
  itk::Vector<double, ImageDimension> physicalOffset;
  labelImage->TransformLocalVectorToPhysicalVector(gridOffset, physicalOffset);
  VectorType proj_offset = rotationMatrix * physicalOffset.GetVnlVector();

  for ( unsigned int i = 0; i < ImageDimension; ++i )
    {
    proj_min[i] -= proj_offset[i];
    proj_max[i] += proj_offset[i];
    }

  LabelImageType::PointType outOrigin((rotationMatrix.transpose()*proj_origin).data_block()); // offset by spacing....

  for ( unsigned int i = 0; i < ImageDimension; ++i )
    {
    outOrigin[i] += centroid[i];
    }

  itk::Vector<double, ImageDimension> rsize; // real physical size
  for ( unsigned int i = 0; i < ImageDimension; ++i )
    {
    rsize[i] = vnl_math_abs(proj_max[i]-proj_min[i]);
    }

  std::cout << "proj_min: " << proj_min << std::endl;
  std::cout << "proj_max: " << proj_max << std::endl;
  std::cout << "origin: " << outOrigin << std::endl;
  std::cout << "size: " << rsize << std::endl;

  LabelImageType::DirectionType outDirection( rotationMatrix.transpose() );
  std::cout << "outDirection: " << outDirection;

  LabelImageType::SpacingType outSpacing;
  outSpacing.Fill(10.0);

  LabelImageType::SizeType outSize;
  for ( unsigned int i = 0; i < ImageDimension; ++i )
    {
    outSize[i] = itk::Math::Floor<itk::SizeValueType>( rsize[i]/ outSpacing[i] );
    }

  typedef itk::ImageFileReader<ImageType> ImageReaderType;
  ImageReaderType::Pointer reader = ImageReaderType::New();
  reader->SetFileName( imageFileName );
  reader->UpdateLargestPossibleRegion();
  ImageType::Pointer image = reader->GetOutput();

  std::cout << "Read Real image..." << std::endl;

  typedef itk::ResampleImageFilter<ImageType, ImageType> ResampleFilter;
  ResampleFilter::Pointer resampler = ResampleFilter::New();

  resampler->SetOutputDirection(outDirection);
  resampler->SetOutputOrigin(outOrigin);
  resampler->SetOutputSpacing(outSpacing);
  resampler->SetSize(outSize);

  resampler->SetInput(image);

  resampler->UpdateLargestPossibleRegion();

  typedef itk::ImageFileWriter<ImageType> WriterType;
  WriterType::Pointer writer = WriterType::New();
  writer->SetFileName(outputImageFileName);
  writer->SetInput(resampler->GetOutput());
  writer->Update();

  return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: menubarwrapper.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: kz $ $Date: 2006-12-13 15:05:05 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef __FRAMEWORK_UIELEMENT_MENUBARWRAPPER_HXX_
#define __FRAMEWORK_UIELEMENT_MENUBARWRAPPER_HXX_

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_HELPER_UICONFIGELEMENTWRAPPERBASE_HXX_
#include <helper/uiconfigelementwrapperbase.hxx>
#endif
#ifndef __FRAMEWORK_UIELEMENT_MENUBARMANAGER_HXX_
#include <uielement/menubarmanager.hxx>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_
#include <com/sun/star/frame/XDispatchProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef __COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

#include <stl/hash_map>

namespace framework
{

class MenuBarWrapper : public UIConfigElementWrapperBase,
                       public ::com::sun::star::container::XNameAccess

{
    public:
        // #110897#
        MenuBarWrapper(
            const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& xServiceManager );
        virtual ~MenuBarWrapper();

        //---------------------------------------------------------------------------------------------------------
        //  XInterface, XTypeProvider
        //---------------------------------------------------------------------------------------------------------
        FWK_DECLARE_XINTERFACE
        FWK_DECLARE_XTYPEPROVIDER

        // #110897#
        const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& getServiceFactory();

        MenuBarManager* GetMenuBarManager() const { return static_cast< MenuBarManager* >( m_xMenuBarManager.get() ); }
        void            InvalidatePopupControllerCache() { m_bRefreshPopupControllerCache = sal_True; }

        // XComponent
        virtual void SAL_CALL dispose() throw (::com::sun::star::uno::RuntimeException);

        // XInitialization
        virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);

        // XUIElement
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL getRealInterface() throw (::com::sun::star::uno::RuntimeException);

        // XUIElementSettings
        virtual void SAL_CALL updateSettings(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess > SAL_CALL getSettings( sal_Bool bWriteable ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL setSettings( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess >& UISettings ) throw (::com::sun::star::uno::RuntimeException);

        // XElementAccess
        virtual ::com::sun::star::uno::Type SAL_CALL getElementType() throw (::com::sun::star::uno::RuntimeException);
        virtual ::sal_Bool SAL_CALL hasElements() throw (::com::sun::star::uno::RuntimeException);

        // XNameAccess
        virtual ::com::sun::star::uno::Any SAL_CALL getByName( const ::rtl::OUString& aName ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getElementNames() throw (::com::sun::star::uno::RuntimeException);
        virtual ::sal_Bool SAL_CALL hasByName( const ::rtl::OUString& aName ) throw (::com::sun::star::uno::RuntimeException);

    private:
        void fillPopupControllerCache();

        sal_Bool                                                                                m_bRefreshPopupControllerCache : 1;
        com::sun::star::uno::Reference< com::sun::star::lang::XComponent >                      m_xMenuBarManager;
        const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& mxServiceFactory;
        PopupControllerCache                                                                    m_aPopupControllerCache;
};

} // namespace framework

#endif // __FRAMEWORK_UIELEMENT_MENUBARWRAPPER_HXX_
<commit_msg>INTEGRATION: CWS fwk64 (1.6.44); FILE MERGED 2007/02/15 11:40:35 cd 1.6.44.1: #i74551# Fixed wrong include<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: menubarwrapper.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: ihi $ $Date: 2007-04-19 09:20:23 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef __FRAMEWORK_UIELEMENT_MENUBARWRAPPER_HXX_
#define __FRAMEWORK_UIELEMENT_MENUBARWRAPPER_HXX_

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_HELPER_UICONFIGELEMENTWRAPPERBASE_HXX_
#include <helper/uiconfigelementwrapperbase.hxx>
#endif
#ifndef __FRAMEWORK_UIELEMENT_MENUBARMANAGER_HXX_
#include <uielement/menubarmanager.hxx>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_
#include <com/sun/star/frame/XDispatchProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef __COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

#include <hash_map>

namespace framework
{

class MenuBarWrapper : public UIConfigElementWrapperBase,
                       public ::com::sun::star::container::XNameAccess

{
    public:
        // #110897#
        MenuBarWrapper(
            const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& xServiceManager );
        virtual ~MenuBarWrapper();

        //---------------------------------------------------------------------------------------------------------
        //  XInterface, XTypeProvider
        //---------------------------------------------------------------------------------------------------------
        FWK_DECLARE_XINTERFACE
        FWK_DECLARE_XTYPEPROVIDER

        // #110897#
        const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& getServiceFactory();

        MenuBarManager* GetMenuBarManager() const { return static_cast< MenuBarManager* >( m_xMenuBarManager.get() ); }
        void            InvalidatePopupControllerCache() { m_bRefreshPopupControllerCache = sal_True; }

        // XComponent
        virtual void SAL_CALL dispose() throw (::com::sun::star::uno::RuntimeException);

        // XInitialization
        virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);

        // XUIElement
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL getRealInterface() throw (::com::sun::star::uno::RuntimeException);

        // XUIElementSettings
        virtual void SAL_CALL updateSettings(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess > SAL_CALL getSettings( sal_Bool bWriteable ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL setSettings( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess >& UISettings ) throw (::com::sun::star::uno::RuntimeException);

        // XElementAccess
        virtual ::com::sun::star::uno::Type SAL_CALL getElementType() throw (::com::sun::star::uno::RuntimeException);
        virtual ::sal_Bool SAL_CALL hasElements() throw (::com::sun::star::uno::RuntimeException);

        // XNameAccess
        virtual ::com::sun::star::uno::Any SAL_CALL getByName( const ::rtl::OUString& aName ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getElementNames() throw (::com::sun::star::uno::RuntimeException);
        virtual ::sal_Bool SAL_CALL hasByName( const ::rtl::OUString& aName ) throw (::com::sun::star::uno::RuntimeException);

    private:
        void fillPopupControllerCache();

        sal_Bool                                                                                m_bRefreshPopupControllerCache : 1;
        com::sun::star::uno::Reference< com::sun::star::lang::XComponent >                      m_xMenuBarManager;
        const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& mxServiceFactory;
        PopupControllerCache                                                                    m_aPopupControllerCache;
};

} // namespace framework

#endif // __FRAMEWORK_UIELEMENT_MENUBARWRAPPER_HXX_
<|endoftext|>


<commit_before>/***************************************************************************//**
 * FILE : graphicsmodule.hpp
 */
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is libZinc.
 *
 * The Initial Developer of the Original Code is
 * Auckland Uniservices Ltd, Auckland, New Zealand.
 * Portions created by the Initial Developer are Copyright (C) 2012
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */
#ifndef __ZN_GRAPHICS_MODULE_HPP__
#define __ZN_GRAPHICS_MODULE_HPP__

#include "zinc/graphicsmodule.h"
#include "zinc/region.hpp"
#include "zinc/scene.hpp"
#include "zinc/glyph.hpp"
#include "zinc/graphic.hpp"
#include "zinc/graphicsmaterial.hpp"
#include "zinc/graphicsfilter.hpp"
#include "zinc/font.hpp"
#include "zinc/sceneviewer.hpp"
#include "zinc/spectrum.hpp"
#include "zinc/tessellation.hpp"

namespace zinc
{

class GraphicsModule
{

protected:
	Cmiss_graphics_module_id id;

public:

	GraphicsModule() : id(0)
	{ }

	// takes ownership of C handle, responsibility for destroying it
	explicit GraphicsModule(Cmiss_graphics_module_id graphics_module_id) :
		id(graphics_module_id)
	{ }

	GraphicsModule(const GraphicsModule& graphicsModule) :
		id(Cmiss_graphics_module_access(graphicsModule.id))
	{ }

	GraphicsModule& operator=(const GraphicsModule& graphicsModule)
	{
		Cmiss_graphics_module_id temp_id = Cmiss_graphics_module_access(graphicsModule.id);
		if (0 != id)
		{
			Cmiss_graphics_module_destroy(&id);
		}
		id = temp_id;
		return *this;
	}

	~GraphicsModule()
	{
		if (0 != id)
		{
			Cmiss_graphics_module_destroy(&id);
		}
	}

	bool isValid()
	{
		return (0 != id);
	}

	Cmiss_graphics_module_id getId()
	{
		return id;
	}

	Scene getScene(Region& region)
	{
		return Scene(Cmiss_graphics_module_get_scene(id, region.getId()));
	}

	GlyphModule getGlyphModule()
	{
		return GlyphModule(Cmiss_graphics_module_get_glyph_module(id));
	}

	GraphicsMaterialModule getGraphicsMaterialModule()
	{
		return GraphicsMaterialModule(Cmiss_graphics_module_get_material_module(id));
	}

	GraphicsFilterModule getFilterModule()
	{
		return GraphicsFilterModule(Cmiss_graphics_module_get_filter_module(id));
	}

	SceneViewerModule getSceneViewerModule()
	{
		return SceneViewerModule(Cmiss_graphics_module_get_scene_viewer_module(id));
	}

	SpectrumModule getSpectrumModule()
	{
		return SpectrumModule(Cmiss_graphics_module_get_spectrum_module(id));
	}

	FontModule getFontModule()
	{
		return FontModule(Cmiss_graphics_module_get_font_module(id));
	}

	TessellationModule getTessellationModule()
	{
		return TessellationModule(Cmiss_graphics_module_get_tessellation_module(id));
	}

};

} // namespace zinc

#endif /* __ZN_GRAPHICS_MODULE_HPP__ */
<commit_msg>Fix C++ API GraphicsModule::getMaterialModule, was getGraphicsMaterialModule. Issue 3589.<commit_after>/***************************************************************************//**
 * FILE : graphicsmodule.hpp
 */
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is libZinc.
 *
 * The Initial Developer of the Original Code is
 * Auckland Uniservices Ltd, Auckland, New Zealand.
 * Portions created by the Initial Developer are Copyright (C) 2012
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */
#ifndef __ZN_GRAPHICS_MODULE_HPP__
#define __ZN_GRAPHICS_MODULE_HPP__

#include "zinc/graphicsmodule.h"
#include "zinc/region.hpp"
#include "zinc/scene.hpp"
#include "zinc/glyph.hpp"
#include "zinc/graphic.hpp"
#include "zinc/graphicsmaterial.hpp"
#include "zinc/graphicsfilter.hpp"
#include "zinc/font.hpp"
#include "zinc/sceneviewer.hpp"
#include "zinc/spectrum.hpp"
#include "zinc/tessellation.hpp"

namespace zinc
{

class GraphicsModule
{

protected:
	Cmiss_graphics_module_id id;

public:

	GraphicsModule() : id(0)
	{ }

	// takes ownership of C handle, responsibility for destroying it
	explicit GraphicsModule(Cmiss_graphics_module_id graphics_module_id) :
		id(graphics_module_id)
	{ }

	GraphicsModule(const GraphicsModule& graphicsModule) :
		id(Cmiss_graphics_module_access(graphicsModule.id))
	{ }

	GraphicsModule& operator=(const GraphicsModule& graphicsModule)
	{
		Cmiss_graphics_module_id temp_id = Cmiss_graphics_module_access(graphicsModule.id);
		if (0 != id)
		{
			Cmiss_graphics_module_destroy(&id);
		}
		id = temp_id;
		return *this;
	}

	~GraphicsModule()
	{
		if (0 != id)
		{
			Cmiss_graphics_module_destroy(&id);
		}
	}

	bool isValid()
	{
		return (0 != id);
	}

	Cmiss_graphics_module_id getId()
	{
		return id;
	}

	Scene getScene(Region& region)
	{
		return Scene(Cmiss_graphics_module_get_scene(id, region.getId()));
	}

	GlyphModule getGlyphModule()
	{
		return GlyphModule(Cmiss_graphics_module_get_glyph_module(id));
	}

	GraphicsMaterialModule getMaterialModule()
	{
		return GraphicsMaterialModule(Cmiss_graphics_module_get_material_module(id));
	}

	GraphicsFilterModule getFilterModule()
	{
		return GraphicsFilterModule(Cmiss_graphics_module_get_filter_module(id));
	}

	SceneViewerModule getSceneViewerModule()
	{
		return SceneViewerModule(Cmiss_graphics_module_get_scene_viewer_module(id));
	}

	SpectrumModule getSpectrumModule()
	{
		return SpectrumModule(Cmiss_graphics_module_get_spectrum_module(id));
	}

	FontModule getFontModule()
	{
		return FontModule(Cmiss_graphics_module_get_font_module(id));
	}

	TessellationModule getTessellationModule()
	{
		return TessellationModule(Cmiss_graphics_module_get_tessellation_module(id));
	}

};

} // namespace zinc

#endif /* __ZN_GRAPHICS_MODULE_HPP__ */
<|endoftext|>


<commit_before>#include <fftw3.h>
#include <cstdlib>
#include <stdio.h>
#include <unistd.h>
#include <string>
#include <string.h>
#include <iostream>
#include <complex>
#include <cassert>
#include <climits>

#include "vsn.h"

bool quiet = false;
int dbglvl = 0;

std::string libgpufftw_file(const char* type="")
{
   return std::string(std::string("./libgpufftw") + type + ".so");
}

void exec_other(int argc, char* argv[],char *envp[],bool dblsquash)
{
   const int MAXSIZE = 512;
   char* newenvp[MAXSIZE];
   std::string tmp("LD_PRELOAD=");
   tmp+=libgpufftw_file("f");
   if (dblsquash) {
      tmp+=":" + libgpufftw_file();
   }

   //Copy environment and add LD_PRELOAD
   int i=0;
   while (envp[i] && i < MAXSIZE - 3) {
      newenvp[i] = envp[i];
      i++;
   }
   newenvp[i++] = const_cast<char*>(tmp.c_str());
   if (dbglvl>0) {
      tmp = "GPU_FFTW_DEBUG=" + std::to_string(dbglvl+5);
      newenvp[i++] = const_cast<char*>(tmp.c_str());
   }
   newenvp[i] = nullptr;

   if (argc < 2) {
      std::cerr << "Usage: " << argv[0] << " <program to run> [arguments...]" << std::endl;
      return;
   }

   if (!quiet) {
      std::cerr << "Running '" << argv[1] << " ";
      i=2;
      while (argv[i]) {
         std::cerr << argv[i] << ((i==argc-1) ? "":" ");
         i++;
      }
      std::cerr << "' with gpu_fftw enabled"
         << (dblsquash ? " and double squash":"") << std::endl;
   }

   execve(argv[1], &(argv[1]), newenvp);

   // execve() only returns on error
   std::cerr << "Error executing " << argv[1] << ": '"
      << strerror(errno) << "'" << std::endl;
}

/************************
 *  Tests & Benchmarks  *
 ************************/
bool gpu_fftw_running(void)
{
   return getenv("GPU_FFTW_ACTIVE")!=nullptr;
}

unsigned long usec_time(void)
{
   struct timespec ts;
   clock_gettime(CLOCK_REALTIME, &ts);
   return ts.tv_sec*1000000 + ts.tv_nsec/1000;
}

unsigned long run_fft(int n,fftwf_complex* in,fftwf_complex* out,bool print,int loops=1)
{
   auto plan= fftwf_plan_dft_1d(n, in, out, FFTW_FORWARD, FFTW_ESTIMATE);
   auto t1 = usec_time();
   for (int i = 0; i < loops; ++i)
      fftwf_execute(plan);
   auto t2 = usec_time();

   fftwf_destroy_plan(plan);
   if (print) {
      for (int i=0; i<n; ++i) {
         std::cerr << out[i][0] << "+ i" << out[i][1] << ",\t";
      }
      std::cerr << "*************************************" << std::endl;
      std::cerr << "*************************************" << std::endl;
   }
   return t2-t1;
}

void print_test(const char* hdr,bool pass)
{
   // + Jesus is the Way, the Truth, and the Life
   std::cout << hdr << "..." << (pass ? "PASSED":" **** FAILED ****") << std::endl;
}

bool test_override_fftw3()
{
   bool pass = false;
   fftwf_complex in[256]= {1,2,3,4,5,6,7,8,9,10};
   fftwf_complex in2[256]= {1,2,3,4,5,6,7,8,9,10};
   fftwf_complex out[256];
   fftwf_complex out2[256];

   // Should run fftw plan
   run_fft(255,in,out,false);
   pass=!gpu_fftw_running();

   // Should run gpu_fftw plan
   run_fft(256,in2,out2,false);
   pass&=gpu_fftw_running();

   print_test("Override FFT3W",pass);
   return pass;
}

void show_accuracy(int N)
{
   fftwf_complex in[N]= {1,2,3,4,5,6,7,8,9,10};
   fftwf_complex out[N];
   fftwf_complex out2[N];
   const int rmax=INT_MAX/10,rmin=INT_MIN/10;

   srand((int)clock());
   for (int i = 0; i < N; ++i)
   {
      in[i][0]=rmax - rand() % rmax - rmin;
      in[i][1]=rmax - rand() % rmax - rmin;
   }

   // Should run fftw plan
   setenv("GPU_FFTW_DISABLE","1",1);
   run_fft(N,in,out,false);
   assert(gpu_fftw_running()==false);

   // Should run gpu_fftw plan
   unsetenv("GPU_FFTW_DISABLE");
   run_fft(N,in,out2,false);
   //assert(gpu_fftw_running()==true);

   double err,err_re,err_im;
   err    = 0;
   err_re = 0;
   err_im = 0;
   for (int i = 0; i < N; ++i)
   {
      err_re = out2[i][0]-out[i][0];
      err_im = out2[i][1]-out[i][1];
      err += err_re*err_re + err_im*err_im;
   }
   err = sqrt(err/N)/(rmax-rmin);

   std::cout << "GPU_FFTW/FFTW difference = " << 1000000.0*err << "ppm (nrms error)"
      << std::endl;
}

void show_speed(int N,int loops)
{
   fftwf_complex in[N]= {1,2,3,4,5,6,7,8,9,10};
   fftwf_complex out[N];
   fftwf_complex out2[N];
   const int rmax=INT_MAX/10,rmin=INT_MIN/10;

   srand((int)clock());
   for (int i = 0; i < N; ++i)
   {
      in[i][0]=rmax - rand() % rmax - rmin;
      in[i][1]=rmax - rand() % rmax - rmin;
   }

   // Should run fftw plan
   setenv("GPU_FFTW_DISABLE","1",1);
   auto fusecs = run_fft(N,in,out,false,loops);
   double fftw3_spd=loops*1000000.0/(double) fusecs;
   assert(gpu_fftw_running()==false);

   // Should run gpu_fftw plan
   unsetenv("GPU_FFTW_DISABLE");
   auto gusecs = run_fft(N,in,out2,false,loops);
   double gfftw3_spd=loops*1000000.0/(double)(gusecs);
   double gfftw3_tim=(double)(gusecs)/loops;

   //assert(gpu_fftw_running()==true);

   double err,err_re,err_im;
   err    = 0;
   err_re = 0;
   err_im = 0;
   for (int i = 0; i < N; ++i)
   {
      err_re = out2[i][0]-out[i][0];
      err_im = out2[i][1]-out[i][1];
      err += err_re*err_re + err_im*err_im;
   }
   err = sqrt(err/N)/(rmax-rmin);

   std::cout << "GPU FFTW " << (float) gfftw3_spd/fftw3_spd
      << " times faster (" << gfftw3_spd << " ffts/sec, "
      <<  gfftw3_tim << " usec/fft, fftw3: "<< fftw3_spd
      << " ffts/sec)" << std::endl;
}

void vsn()
{
   if (!quiet)
      std::cout << "gpu_fftw - Version " << GPU_FFTW_VSN << std::endl
         << std::endl;
}

bool tests()
{
   bool pass=false;
   pass&=test_override_fftw3();
   show_accuracy(256);
   show_speed(pow(2,10),1000);
   return pass;
}

void usage(char *name)
{
   vsn();
   std::cerr << "Usage: " << name << " <program> [arguments...]"
      << std::endl;
   std::cerr << "       " << name << " -t" << std::endl;
   std::cerr <<  std::endl <<
      "The first form runs <program> with gpu_fftw enabled,\n"
      "the second runs tests and prints benchmark information.\n";
}

int main(int argc,char **argv, char* envp[])
{
   int opt;
   bool dblsquash=false;
   char *test_argv[] = { argv[0], argv[0], (char*) "-z", nullptr };

   if (argc < 2) {
      usage(argv[0]);
      return 2;
   }

   while ((opt = getopt(argc, argv, "ztqhdD:")) != -1) {
      switch (opt) {
         case 'z': //Used only internally
            return tests() ? 0:1;
         case 't':
            vsn();
            quiet=true;
            exec_other(3,test_argv,envp,true);
            return 3;
            break;
         case 'q':
            quiet = true;
            break;
         case 'D':
            dbglvl= std::stoi(optarg);
            break;
         case 'd':
            dblsquash=true;
            break;
         case 'h':
            usage(argv[0]);
            return 2;
      }
   }

   vsn();
   exec_other(argc,&argv[optind-1],envp,dblsquash);
   return 3; //if exec_other returns it is an error
}
<commit_msg>exec_other: proper value of argc (and argv)<commit_after>#include <fftw3.h>
#include <cstdlib>
#include <stdio.h>
#include <unistd.h>
#include <string>
#include <string.h>
#include <iostream>
#include <complex>
#include <cassert>
#include <climits>

#include "vsn.h"

bool quiet = false;
int dbglvl = 0;

std::string libgpufftw_file(const char* type="")
{
   return std::string(std::string("./libgpufftw") + type + ".so");
}

void vsn()
{
   if (!quiet)
      std::cout << "gpu_fftw - Version " << GPU_FFTW_VSN << std::endl
         << std::endl;
}

void usage(const char *name="gpu_fftw")
{
   vsn();
   std::cerr << "Usage: " << name << " <program> [arguments...]"
      << std::endl;
   std::cerr << "       " << name << " -t" << std::endl;
   std::cerr <<  std::endl <<
      "The first form runs <program> with gpu_fftw enabled,\n"
      "the second runs tests and prints benchmark information.\n";
}

// Argc and argv are the values for the program to be executed
void exec_other(int argc, char* argv[],char *envp[],bool dblsquash)
{
   const int MAXSIZE = 512;
   char* newenvp[MAXSIZE];
   std::string tmp("LD_PRELOAD=");
   tmp+=libgpufftw_file("f");
   if (dblsquash) {
      tmp+=":" + libgpufftw_file();
   }

   //Copy environment and add LD_PRELOAD
   int i=0;
   while (envp[i] && i < MAXSIZE - 3) {
      newenvp[i] = envp[i];
      i++;
   }
   newenvp[i++] = const_cast<char*>(tmp.c_str());
   if (dbglvl>0) {
      tmp = "GPU_FFTW_DEBUG=" + std::to_string(dbglvl+5);
      newenvp[i++] = const_cast<char*>(tmp.c_str());
   }
   newenvp[i] = nullptr;

   if (argc < 1) {
      usage();
      return;
   }

   if (!quiet) {
      std::cerr << "Running '" << argv[0] << " ";
      i=1;
      while (argv[i]) {
         std::cerr << argv[i] << ((i==argc-1) ? "":" ");
         i++;
      }
      std::cerr << "' with gpu_fftw enabled"
         << (dblsquash ? " and double squash":"") << std::endl;
   }

   execve(argv[0], &(argv[0]), newenvp);

   // execve() only returns on error
   std::cerr << "Error executing " << argv[0] << ": '"
      << strerror(errno) << "'" << std::endl;
}

/************************
 *  Tests & Benchmarks  *
 ************************/
bool gpu_fftw_running(void)
{
   return getenv("GPU_FFTW_ACTIVE")!=nullptr;
}

unsigned long usec_time(void)
{
   struct timespec ts;
   clock_gettime(CLOCK_REALTIME, &ts);
   return ts.tv_sec*1000000 + ts.tv_nsec/1000;
}

unsigned long run_fft(int n,fftwf_complex* in,fftwf_complex* out,bool print,int loops=1)
{
   auto plan= fftwf_plan_dft_1d(n, in, out, FFTW_FORWARD, FFTW_ESTIMATE);
   auto t1 = usec_time();
   for (int i = 0; i < loops; ++i)
      fftwf_execute(plan);
   auto t2 = usec_time();

   fftwf_destroy_plan(plan);
   if (print) {
      for (int i=0; i<n; ++i) {
         std::cerr << out[i][0] << "+ i" << out[i][1] << ",\t";
      }
      std::cerr << "*************************************" << std::endl;
      std::cerr << "*************************************" << std::endl;
   }
   return t2-t1;
}

void print_test(const char* hdr,bool pass)
{
   // + Jesus is the Way, the Truth, and the Life
   std::cout << hdr << "..." << (pass ? "PASSED":" **** FAILED ****") << std::endl;
}

bool test_override_fftw3()
{
   bool pass = false;
   fftwf_complex in[256]= {1,2,3,4,5,6,7,8,9,10};
   fftwf_complex in2[256]= {1,2,3,4,5,6,7,8,9,10};
   fftwf_complex out[256];
   fftwf_complex out2[256];

   // Should run fftw plan
   run_fft(255,in,out,false);
   pass=!gpu_fftw_running();

   // Should run gpu_fftw plan
   run_fft(256,in2,out2,false);
   pass&=gpu_fftw_running();

   print_test("Override FFT3W",pass);
   return pass;
}

void show_accuracy(int N)
{
   fftwf_complex in[N]= {1,2,3,4,5,6,7,8,9,10};
   fftwf_complex out[N];
   fftwf_complex out2[N];
   const int rmax=INT_MAX/10,rmin=INT_MIN/10;

   srand((int)clock());
   for (int i = 0; i < N; ++i)
   {
      in[i][0]=rmax - rand() % rmax - rmin;
      in[i][1]=rmax - rand() % rmax - rmin;
   }

   // Should run fftw plan
   setenv("GPU_FFTW_DISABLE","1",1);
   run_fft(N,in,out,false);
   assert(gpu_fftw_running()==false);

   // Should run gpu_fftw plan
   unsetenv("GPU_FFTW_DISABLE");
   run_fft(N,in,out2,false);
   //assert(gpu_fftw_running()==true);

   double err,err_re,err_im;
   err    = 0;
   err_re = 0;
   err_im = 0;
   for (int i = 0; i < N; ++i)
   {
      err_re = out2[i][0]-out[i][0];
      err_im = out2[i][1]-out[i][1];
      err += err_re*err_re + err_im*err_im;
   }
   err = sqrt(err/N)/(rmax-rmin);

   std::cout << "GPU_FFTW/FFTW difference = " << 1000000.0*err << "ppm (nrms error)"
      << std::endl;
}

void show_speed(int N,int loops)
{
   fftwf_complex in[N]= {1,2,3,4,5,6,7,8,9,10};
   fftwf_complex out[N];
   fftwf_complex out2[N];
   const int rmax=INT_MAX/10,rmin=INT_MIN/10;

   srand((int)clock());
   for (int i = 0; i < N; ++i)
   {
      in[i][0]=rmax - rand() % rmax - rmin;
      in[i][1]=rmax - rand() % rmax - rmin;
   }

   // Should run fftw plan
   setenv("GPU_FFTW_DISABLE","1",1);
   auto fusecs = run_fft(N,in,out,false,loops);
   double fftw3_spd=loops*1000000.0/(double) fusecs;
   assert(gpu_fftw_running()==false);

   // Should run gpu_fftw plan
   unsetenv("GPU_FFTW_DISABLE");
   auto gusecs = run_fft(N,in,out2,false,loops);
   double gfftw3_spd=loops*1000000.0/(double)(gusecs);
   double gfftw3_tim=(double)(gusecs)/loops;

   //assert(gpu_fftw_running()==true);

   double err,err_re,err_im;
   err    = 0;
   err_re = 0;
   err_im = 0;
   for (int i = 0; i < N; ++i)
   {
      err_re = out2[i][0]-out[i][0];
      err_im = out2[i][1]-out[i][1];
      err += err_re*err_re + err_im*err_im;
   }
   err = sqrt(err/N)/(rmax-rmin);

   std::cout << "GPU FFTW " << (float) gfftw3_spd/fftw3_spd
      << " times faster (" << gfftw3_spd << " ffts/sec, "
      <<  gfftw3_tim << " usec/fft, fftw3: "<< fftw3_spd
      << " ffts/sec)" << std::endl;
}

bool tests()
{
   bool pass=false;
   pass&=test_override_fftw3();
   show_accuracy(256);
   show_speed(pow(2,10),1000);
   return pass;
}

int main(int argc,char **argv, char* envp[])
{
   int opt;
   bool dblsquash=false;
   char *test_argv[] = { argv[0], (char*) "-z", nullptr };

   if (argc < 2) {
      usage(argv[0]);
      return 2;
   }

   while ((opt = getopt(argc, argv, "ztqhdD:")) != -1) {
      switch (opt) {
         case 'z': //Used only internally
            return tests() ? 0:1;
         case 't':
            vsn();
            quiet=true;
            exec_other(2,test_argv,envp,true);
            return 3;
            break;
         case 'q':
            quiet = true;
            break;
         case 'D':
            dbglvl= std::stoi(optarg);
            break;
         case 'd':
            dblsquash=true;
            break;
         case 'h':
            usage(argv[0]);
            return 2;
      }
   }

   vsn();
   exec_other(argc-optind,&argv[optind],envp,dblsquash);
   return 3; //if exec_other returns it is an error
}
<|endoftext|>


<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 20013 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

static int nb_temporaries;

void on_temporary_creation(int size) {
  // here's a great place to set a breakpoint when debugging failures in this test!
  if(size!=0) nb_temporaries++;
}

#define EIGEN_DENSE_STORAGE_CTOR_PLUGIN { on_temporary_creation(size); }

#include "main.h"

#define VERIFY_EVALUATION_COUNT(XPR,N) {\
    nb_temporaries = 0; \
    XPR; \
    if(nb_temporaries!=N) std::cerr << "nb_temporaries == " << nb_temporaries << "\n"; \
    VERIFY( (#XPR) && nb_temporaries==N ); \
  }

// test Ref.h

template<typename MatrixType> void ref_matrix(const MatrixType& m)
{
  typedef typename MatrixType::Index Index;
  typedef typename MatrixType::Scalar Scalar;
  typedef typename MatrixType::RealScalar RealScalar;
  typedef Matrix<Scalar,Dynamic,Dynamic,MatrixType::Options> DynMatrixType;
  typedef Matrix<RealScalar,Dynamic,Dynamic,MatrixType::Options> RealDynMatrixType;

  typedef Ref<MatrixType> RefMat;
  typedef Ref<DynMatrixType> RefDynMat;
  typedef Ref<const DynMatrixType> ConstRefDynMat;
  typedef Ref<RealDynMatrixType , 0, Stride<Dynamic,Dynamic> > RefRealMatWithStride;

  Index rows = m.rows(), cols = m.cols();

  MatrixType  m1 = MatrixType::Random(rows, cols),
              m2 = m1;

  Index i = internal::random<Index>(0,rows-1);
  Index j = internal::random<Index>(0,cols-1);
  Index brows = internal::random<Index>(1,rows-i);
  Index bcols = internal::random<Index>(1,cols-j);

  RefMat rm0 = m1;
  VERIFY_IS_EQUAL(rm0, m1);
  RefDynMat rm1 = m1;
  VERIFY_IS_EQUAL(rm1, m1);
  RefDynMat rm2 = m1.block(i,j,brows,bcols);
  VERIFY_IS_EQUAL(rm2, m1.block(i,j,brows,bcols));
  rm2.setOnes();
  m2.block(i,j,brows,bcols).setOnes();
  VERIFY_IS_EQUAL(m1, m2);

  m2.block(i,j,brows,bcols).setRandom();
  rm2 = m2.block(i,j,brows,bcols);
  VERIFY_IS_EQUAL(m1, m2);

  ConstRefDynMat rm3 = m1.block(i,j,brows,bcols);
  m1.block(i,j,brows,bcols) *= 2;
  m2.block(i,j,brows,bcols) *= 2;
  VERIFY_IS_EQUAL(rm3, m2.block(i,j,brows,bcols));
  RefRealMatWithStride rm4 = m1.real();
  VERIFY_IS_EQUAL(rm4, m2.real());
  rm4.array() += 1;
  m2.real().array() += 1;
  VERIFY_IS_EQUAL(m1, m2);
}

template<typename VectorType> void ref_vector(const VectorType& m)
{
  typedef typename VectorType::Index Index;
  typedef typename VectorType::Scalar Scalar;
  typedef typename VectorType::RealScalar RealScalar;
  typedef Matrix<Scalar,Dynamic,1,VectorType::Options> DynMatrixType;
  typedef Matrix<Scalar,Dynamic,Dynamic,ColMajor> MatrixType;
  typedef Matrix<RealScalar,Dynamic,1,VectorType::Options> RealDynMatrixType;

  typedef Ref<VectorType> RefMat;
  typedef Ref<DynMatrixType> RefDynMat;
  typedef Ref<const DynMatrixType> ConstRefDynMat;
  typedef Ref<RealDynMatrixType , 0, InnerStride<> > RefRealMatWithStride;
  typedef Ref<DynMatrixType , 0, InnerStride<> > RefMatWithStride;

  Index size = m.size();

  VectorType  v1 = VectorType::Random(size),
              v2 = v1;
  MatrixType mat1 = MatrixType::Random(size,size),
             mat2 = mat1,
             mat3 = MatrixType::Random(size,size);

  Index i = internal::random<Index>(0,size-1);
  Index bsize = internal::random<Index>(1,size-i);

  RefMat rm0 = v1;
  VERIFY_IS_EQUAL(rm0, v1);
  RefDynMat rv1 = v1;
  VERIFY_IS_EQUAL(rv1, v1);
  RefDynMat rv2 = v1.segment(i,bsize);
  VERIFY_IS_EQUAL(rv2, v1.segment(i,bsize));
  rv2.setOnes();
  v2.segment(i,bsize).setOnes();
  VERIFY_IS_EQUAL(v1, v2);

  v2.segment(i,bsize).setRandom();
  rv2 = v2.segment(i,bsize);
  VERIFY_IS_EQUAL(v1, v2);

  ConstRefDynMat rm3 = v1.segment(i,bsize);
  v1.segment(i,bsize) *= 2;
  v2.segment(i,bsize) *= 2;
  VERIFY_IS_EQUAL(rm3, v2.segment(i,bsize));

  RefRealMatWithStride rm4 = v1.real();
  VERIFY_IS_EQUAL(rm4, v2.real());
  rm4.array() += 1;
  v2.real().array() += 1;
  VERIFY_IS_EQUAL(v1, v2);

  RefMatWithStride rm5 = mat1.row(i).transpose();
  VERIFY_IS_EQUAL(rm5, mat1.row(i).transpose());
  rm5.array() += 1;
  mat2.row(i).array() += 1;
  VERIFY_IS_EQUAL(mat1, mat2);
  rm5.noalias() = rm4.transpose() * mat3;
  mat2.row(i) = v2.real().transpose() * mat3;
  VERIFY_IS_APPROX(mat1, mat2);
}

template<typename PlainObjectType> void check_const_correctness(const PlainObjectType&)
{
  typedef typename PlainObjectType::Index Index;
  typedef typename PlainObjectType::Scalar Scalar;

  // verify that ref-to-const don't have LvalueBit
  typedef typename internal::add_const<PlainObjectType>::type ConstPlainObjectType;
  VERIFY( !(internal::traits<Ref<ConstPlainObjectType> >::Flags & LvalueBit) );
  VERIFY( !(internal::traits<Ref<ConstPlainObjectType, Aligned> >::Flags & LvalueBit) );
  VERIFY( !(Ref<ConstPlainObjectType>::Flags & LvalueBit) );
  VERIFY( !(Ref<ConstPlainObjectType, Aligned>::Flags & LvalueBit) );
}

EIGEN_DONT_INLINE void call_ref_1(Ref<VectorXf> ) { }
EIGEN_DONT_INLINE void call_ref_2(const Ref<const VectorXf>& ) { }
EIGEN_DONT_INLINE void call_ref_3(Ref<VectorXf,0,InnerStride<> > ) { }
EIGEN_DONT_INLINE void call_ref_4(const Ref<const VectorXf,0,InnerStride<> >& ) { }
EIGEN_DONT_INLINE void call_ref_5(Ref<MatrixXf,0,OuterStride<> > ) { }
EIGEN_DONT_INLINE void call_ref_6(const Ref<const MatrixXf,0,OuterStride<> >& ) { }

void call_ref()
{
  VectorXcf ca(10);
  VectorXf a(10);
  const VectorXf& ac(a);
  VectorBlock<VectorXf> ab(a,0,3);
  MatrixXf A(10,10);
  const VectorBlock<VectorXf> abc(a,0,3);

  VERIFY_EVALUATION_COUNT( call_ref_1(a), 0);
  //call_ref_1(ac);           // does not compile because ac is const
  VERIFY_EVALUATION_COUNT( call_ref_1(ab), 0);
  VERIFY_EVALUATION_COUNT( call_ref_1(a.head(4)), 0);
  VERIFY_EVALUATION_COUNT( call_ref_1(abc), 0);
  VERIFY_EVALUATION_COUNT( call_ref_1(A.col(3)), 0);
  // call_ref_1(A.row(3));    // does not compile because innerstride!=1
  VERIFY_EVALUATION_COUNT( call_ref_3(A.row(3)), 0);
  VERIFY_EVALUATION_COUNT( call_ref_4(A.row(3)), 0);
  //call_ref_1(a+a);          // does not compile for obvious reason

  VERIFY_EVALUATION_COUNT( call_ref_2(A*A.col(1)), 1);     // evaluated into a temp
  VERIFY_EVALUATION_COUNT( call_ref_2(ac.head(5)), 0);
  VERIFY_EVALUATION_COUNT( call_ref_2(ac), 0);
  VERIFY_EVALUATION_COUNT( call_ref_2(a), 0);
  VERIFY_EVALUATION_COUNT( call_ref_2(ab), 0);
  VERIFY_EVALUATION_COUNT( call_ref_2(a.head(4)), 0);
  VERIFY_EVALUATION_COUNT( call_ref_2(a+a), 1);            // evaluated into a temp
  VERIFY_EVALUATION_COUNT( call_ref_2(ca.imag()), 1);      // evaluated into a temp

  VERIFY_EVALUATION_COUNT( call_ref_4(ac.head(5)), 0);
  VERIFY_EVALUATION_COUNT( call_ref_4(a+a), 1);           // evaluated into a temp
  VERIFY_EVALUATION_COUNT( call_ref_4(ca.imag()), 0);

  VERIFY_EVALUATION_COUNT( call_ref_5(a), 0);
  VERIFY_EVALUATION_COUNT( call_ref_5(a.head(3)), 0);
  VERIFY_EVALUATION_COUNT( call_ref_5(A), 0);
  // call_ref_5(A.transpose());   // does not compile
  VERIFY_EVALUATION_COUNT( call_ref_5(A.block(1,1,2,2)), 0);

  VERIFY_EVALUATION_COUNT( call_ref_6(a), 0);
  VERIFY_EVALUATION_COUNT( call_ref_6(a.head(3)), 0);
  VERIFY_EVALUATION_COUNT( call_ref_6(A.row(3)), 1);           // evaluated into a temp thouth it could be avoided by viewing it as a 1xn matrix
  VERIFY_EVALUATION_COUNT( call_ref_6(A+A), 1);                // evaluated into a temp
  VERIFY_EVALUATION_COUNT( call_ref_6(A), 0);
  VERIFY_EVALUATION_COUNT( call_ref_6(A.transpose()), 1);      // evaluated into a temp because the storage orders do not match
  VERIFY_EVALUATION_COUNT( call_ref_6(A.block(1,1,2,2)), 0);
}

void test_ref()
{
  for(int i = 0; i < g_repeat; i++) {
    CALL_SUBTEST_1( ref_vector(Matrix<float, 1, 1>()) );
    CALL_SUBTEST_1( check_const_correctness(Matrix<float, 1, 1>()) );
    CALL_SUBTEST_2( ref_vector(Vector4d()) );
    CALL_SUBTEST_2( check_const_correctness(Matrix4d()) );
    CALL_SUBTEST_3( ref_vector(Vector4cf()) );
    CALL_SUBTEST_4( ref_vector(VectorXcf(8)) );
    CALL_SUBTEST_5( ref_vector(VectorXi(12)) );
    CALL_SUBTEST_5( check_const_correctness(VectorXi(12)) );

    CALL_SUBTEST_1( ref_matrix(Matrix<float, 1, 1>()) );
    CALL_SUBTEST_2( ref_matrix(Matrix4d()) );
    CALL_SUBTEST_1( ref_matrix(Matrix<float,3,5>()) );
    CALL_SUBTEST_4( ref_matrix(MatrixXcf(internal::random<int>(1,10),internal::random<int>(1,10))) );
    CALL_SUBTEST_4( ref_matrix(Matrix<std::complex<double>,10,15>()) );
    CALL_SUBTEST_5( ref_matrix(MatrixXi(internal::random<int>(1,10),internal::random<int>(1,10))) );
    CALL_SUBTEST_6( call_ref() );
  }
}
<commit_msg>The ref unit test cannot be easily written to work with EIGEN_DEFAULT_TO_ROW_MAJOR<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 20013 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

// This unit test cannot be easily written to work with EIGEN_DEFAULT_TO_ROW_MAJOR
#ifdef EIGEN_DEFAULT_TO_ROW_MAJOR
#undef EIGEN_DEFAULT_TO_ROW_MAJOR
#endif

static int nb_temporaries;

void on_temporary_creation(int size) {
  // here's a great place to set a breakpoint when debugging failures in this test!
  if(size!=0) nb_temporaries++;
}

#define EIGEN_DENSE_STORAGE_CTOR_PLUGIN { on_temporary_creation(size); }

#include "main.h"

#define VERIFY_EVALUATION_COUNT(XPR,N) {\
    nb_temporaries = 0; \
    XPR; \
    if(nb_temporaries!=N) std::cerr << "nb_temporaries == " << nb_temporaries << "\n"; \
    VERIFY( (#XPR) && nb_temporaries==N ); \
  }

// test Ref.h

template<typename MatrixType> void ref_matrix(const MatrixType& m)
{
  typedef typename MatrixType::Index Index;
  typedef typename MatrixType::Scalar Scalar;
  typedef typename MatrixType::RealScalar RealScalar;
  typedef Matrix<Scalar,Dynamic,Dynamic,MatrixType::Options> DynMatrixType;
  typedef Matrix<RealScalar,Dynamic,Dynamic,MatrixType::Options> RealDynMatrixType;

  typedef Ref<MatrixType> RefMat;
  typedef Ref<DynMatrixType> RefDynMat;
  typedef Ref<const DynMatrixType> ConstRefDynMat;
  typedef Ref<RealDynMatrixType , 0, Stride<Dynamic,Dynamic> > RefRealMatWithStride;

  Index rows = m.rows(), cols = m.cols();

  MatrixType  m1 = MatrixType::Random(rows, cols),
              m2 = m1;

  Index i = internal::random<Index>(0,rows-1);
  Index j = internal::random<Index>(0,cols-1);
  Index brows = internal::random<Index>(1,rows-i);
  Index bcols = internal::random<Index>(1,cols-j);

  RefMat rm0 = m1;
  VERIFY_IS_EQUAL(rm0, m1);
  RefDynMat rm1 = m1;
  VERIFY_IS_EQUAL(rm1, m1);
  RefDynMat rm2 = m1.block(i,j,brows,bcols);
  VERIFY_IS_EQUAL(rm2, m1.block(i,j,brows,bcols));
  rm2.setOnes();
  m2.block(i,j,brows,bcols).setOnes();
  VERIFY_IS_EQUAL(m1, m2);

  m2.block(i,j,brows,bcols).setRandom();
  rm2 = m2.block(i,j,brows,bcols);
  VERIFY_IS_EQUAL(m1, m2);

  ConstRefDynMat rm3 = m1.block(i,j,brows,bcols);
  m1.block(i,j,brows,bcols) *= 2;
  m2.block(i,j,brows,bcols) *= 2;
  VERIFY_IS_EQUAL(rm3, m2.block(i,j,brows,bcols));
  RefRealMatWithStride rm4 = m1.real();
  VERIFY_IS_EQUAL(rm4, m2.real());
  rm4.array() += 1;
  m2.real().array() += 1;
  VERIFY_IS_EQUAL(m1, m2);
}

template<typename VectorType> void ref_vector(const VectorType& m)
{
  typedef typename VectorType::Index Index;
  typedef typename VectorType::Scalar Scalar;
  typedef typename VectorType::RealScalar RealScalar;
  typedef Matrix<Scalar,Dynamic,1,VectorType::Options> DynMatrixType;
  typedef Matrix<Scalar,Dynamic,Dynamic,ColMajor> MatrixType;
  typedef Matrix<RealScalar,Dynamic,1,VectorType::Options> RealDynMatrixType;

  typedef Ref<VectorType> RefMat;
  typedef Ref<DynMatrixType> RefDynMat;
  typedef Ref<const DynMatrixType> ConstRefDynMat;
  typedef Ref<RealDynMatrixType , 0, InnerStride<> > RefRealMatWithStride;
  typedef Ref<DynMatrixType , 0, InnerStride<> > RefMatWithStride;

  Index size = m.size();

  VectorType  v1 = VectorType::Random(size),
              v2 = v1;
  MatrixType mat1 = MatrixType::Random(size,size),
             mat2 = mat1,
             mat3 = MatrixType::Random(size,size);

  Index i = internal::random<Index>(0,size-1);
  Index bsize = internal::random<Index>(1,size-i);

  RefMat rm0 = v1;
  VERIFY_IS_EQUAL(rm0, v1);
  RefDynMat rv1 = v1;
  VERIFY_IS_EQUAL(rv1, v1);
  RefDynMat rv2 = v1.segment(i,bsize);
  VERIFY_IS_EQUAL(rv2, v1.segment(i,bsize));
  rv2.setOnes();
  v2.segment(i,bsize).setOnes();
  VERIFY_IS_EQUAL(v1, v2);

  v2.segment(i,bsize).setRandom();
  rv2 = v2.segment(i,bsize);
  VERIFY_IS_EQUAL(v1, v2);

  ConstRefDynMat rm3 = v1.segment(i,bsize);
  v1.segment(i,bsize) *= 2;
  v2.segment(i,bsize) *= 2;
  VERIFY_IS_EQUAL(rm3, v2.segment(i,bsize));

  RefRealMatWithStride rm4 = v1.real();
  VERIFY_IS_EQUAL(rm4, v2.real());
  rm4.array() += 1;
  v2.real().array() += 1;
  VERIFY_IS_EQUAL(v1, v2);

  RefMatWithStride rm5 = mat1.row(i).transpose();
  VERIFY_IS_EQUAL(rm5, mat1.row(i).transpose());
  rm5.array() += 1;
  mat2.row(i).array() += 1;
  VERIFY_IS_EQUAL(mat1, mat2);
  rm5.noalias() = rm4.transpose() * mat3;
  mat2.row(i) = v2.real().transpose() * mat3;
  VERIFY_IS_APPROX(mat1, mat2);
}

template<typename PlainObjectType> void check_const_correctness(const PlainObjectType&)
{
  typedef typename PlainObjectType::Index Index;
  typedef typename PlainObjectType::Scalar Scalar;

  // verify that ref-to-const don't have LvalueBit
  typedef typename internal::add_const<PlainObjectType>::type ConstPlainObjectType;
  VERIFY( !(internal::traits<Ref<ConstPlainObjectType> >::Flags & LvalueBit) );
  VERIFY( !(internal::traits<Ref<ConstPlainObjectType, Aligned> >::Flags & LvalueBit) );
  VERIFY( !(Ref<ConstPlainObjectType>::Flags & LvalueBit) );
  VERIFY( !(Ref<ConstPlainObjectType, Aligned>::Flags & LvalueBit) );
}

EIGEN_DONT_INLINE void call_ref_1(Ref<VectorXf> ) { }
EIGEN_DONT_INLINE void call_ref_2(const Ref<const VectorXf>& ) { }
EIGEN_DONT_INLINE void call_ref_3(Ref<VectorXf,0,InnerStride<> > ) { }
EIGEN_DONT_INLINE void call_ref_4(const Ref<const VectorXf,0,InnerStride<> >& ) { }
EIGEN_DONT_INLINE void call_ref_5(Ref<MatrixXf,0,OuterStride<> > ) { }
EIGEN_DONT_INLINE void call_ref_6(const Ref<const MatrixXf,0,OuterStride<> >& ) { }

void call_ref()
{
  VectorXcf ca(10);
  VectorXf a(10);
  const VectorXf& ac(a);
  VectorBlock<VectorXf> ab(a,0,3);
  MatrixXf A(10,10);
  const VectorBlock<VectorXf> abc(a,0,3);

  VERIFY_EVALUATION_COUNT( call_ref_1(a), 0);
  //call_ref_1(ac);           // does not compile because ac is const
  VERIFY_EVALUATION_COUNT( call_ref_1(ab), 0);
  VERIFY_EVALUATION_COUNT( call_ref_1(a.head(4)), 0);
  VERIFY_EVALUATION_COUNT( call_ref_1(abc), 0);
  VERIFY_EVALUATION_COUNT( call_ref_1(A.col(3)), 0);
  // call_ref_1(A.row(3));    // does not compile because innerstride!=1
  VERIFY_EVALUATION_COUNT( call_ref_3(A.row(3)), 0);
  VERIFY_EVALUATION_COUNT( call_ref_4(A.row(3)), 0);
  //call_ref_1(a+a);          // does not compile for obvious reason

  VERIFY_EVALUATION_COUNT( call_ref_2(A*A.col(1)), 1);     // evaluated into a temp
  VERIFY_EVALUATION_COUNT( call_ref_2(ac.head(5)), 0);
  VERIFY_EVALUATION_COUNT( call_ref_2(ac), 0);
  VERIFY_EVALUATION_COUNT( call_ref_2(a), 0);
  VERIFY_EVALUATION_COUNT( call_ref_2(ab), 0);
  VERIFY_EVALUATION_COUNT( call_ref_2(a.head(4)), 0);
  VERIFY_EVALUATION_COUNT( call_ref_2(a+a), 1);            // evaluated into a temp
  VERIFY_EVALUATION_COUNT( call_ref_2(ca.imag()), 1);      // evaluated into a temp

  VERIFY_EVALUATION_COUNT( call_ref_4(ac.head(5)), 0);
  VERIFY_EVALUATION_COUNT( call_ref_4(a+a), 1);           // evaluated into a temp
  VERIFY_EVALUATION_COUNT( call_ref_4(ca.imag()), 0);

  VERIFY_EVALUATION_COUNT( call_ref_5(a), 0);
  VERIFY_EVALUATION_COUNT( call_ref_5(a.head(3)), 0);
  VERIFY_EVALUATION_COUNT( call_ref_5(A), 0);
  // call_ref_5(A.transpose());   // does not compile
  VERIFY_EVALUATION_COUNT( call_ref_5(A.block(1,1,2,2)), 0);

  VERIFY_EVALUATION_COUNT( call_ref_6(a), 0);
  VERIFY_EVALUATION_COUNT( call_ref_6(a.head(3)), 0);
  VERIFY_EVALUATION_COUNT( call_ref_6(A.row(3)), 1);           // evaluated into a temp thouth it could be avoided by viewing it as a 1xn matrix
  VERIFY_EVALUATION_COUNT( call_ref_6(A+A), 1);                // evaluated into a temp
  VERIFY_EVALUATION_COUNT( call_ref_6(A), 0);
  VERIFY_EVALUATION_COUNT( call_ref_6(A.transpose()), 1);      // evaluated into a temp because the storage orders do not match
  VERIFY_EVALUATION_COUNT( call_ref_6(A.block(1,1,2,2)), 0);
}

void test_ref()
{
  for(int i = 0; i < g_repeat; i++) {
    CALL_SUBTEST_1( ref_vector(Matrix<float, 1, 1>()) );
    CALL_SUBTEST_1( check_const_correctness(Matrix<float, 1, 1>()) );
    CALL_SUBTEST_2( ref_vector(Vector4d()) );
    CALL_SUBTEST_2( check_const_correctness(Matrix4d()) );
    CALL_SUBTEST_3( ref_vector(Vector4cf()) );
    CALL_SUBTEST_4( ref_vector(VectorXcf(8)) );
    CALL_SUBTEST_5( ref_vector(VectorXi(12)) );
    CALL_SUBTEST_5( check_const_correctness(VectorXi(12)) );

    CALL_SUBTEST_1( ref_matrix(Matrix<float, 1, 1>()) );
    CALL_SUBTEST_2( ref_matrix(Matrix4d()) );
    CALL_SUBTEST_1( ref_matrix(Matrix<float,3,5>()) );
    CALL_SUBTEST_4( ref_matrix(MatrixXcf(internal::random<int>(1,10),internal::random<int>(1,10))) );
    CALL_SUBTEST_4( ref_matrix(Matrix<std::complex<double>,10,15>()) );
    CALL_SUBTEST_5( ref_matrix(MatrixXi(internal::random<int>(1,10),internal::random<int>(1,10))) );
    CALL_SUBTEST_6( call_ref() );
  }
}
<|endoftext|>


<commit_before>#define MS_CLASS "RTC::TransportTuple"

#include "RTC/TransportTuple.h"
#include "Logger.h"
#include "Utils.h"
#include <string>

namespace RTC
{
	/* Instance methods. */

	Json::Value TransportTuple::toJson()
	{
		MS_TRACE();

		static const Json::StaticString k_local("local");
		static const Json::StaticString k_remote("remote");
		static const Json::StaticString k_ip("ip");
		static const Json::StaticString k_port("port");
		static const Json::StaticString k_protocol("protocol");
		static const Json::StaticString v_udp("udp");
		static const Json::StaticString v_tcp("tcp");

		Json::Value json(Json::objectValue);
		Json::Value json_local(Json::objectValue);
		Json::Value json_remote(Json::objectValue);
		int ip_family;
		std::string ip;
		uint16_t port;

		Utils::IP::GetAddressInfo(this->GetLocalAddress(), &ip_family, ip, &port);
		json_local[k_ip] = ip;
		json_local[k_port] = (Json::UInt)port;
		if (this->GetProtocol() == RTC::TransportTuple::Protocol::UDP)
			json_local[k_protocol] = v_udp;
		else
			json_local[k_protocol] = v_tcp;

		Utils::IP::GetAddressInfo(this->GetRemoteAddress(), &ip_family, ip, &port);
		json_remote[k_ip] = ip;
		json_remote[k_port] = (Json::UInt)port;
		if (this->GetProtocol() == RTC::TransportTuple::Protocol::UDP)
			json_remote[k_protocol] = v_udp;
		else
			json_remote[k_protocol] = v_tcp;

		json[k_local] = json_local;
		json[k_remote] = json_remote;

		return json;
	}

	// TODO: TMP
	void TransportTuple::Dump()
	{
		MS_TRACE();

		if (!Logger::HasDebugLevel())
			return;

		switch (this->protocol)
		{
			case Protocol::UDP:
			{
				int remote_family;
				std::string remote_ip;
				uint16_t remote_port;

				Utils::IP::GetAddressInfo(GetRemoteAddress(), &remote_family, remote_ip, &remote_port);

				MS_DEBUG("[UDP, local:%s :%" PRIu16 ", remote:%s :%" PRIu16 "]",
					this->udpSocket->GetLocalIP().c_str(), this->udpSocket->GetLocalPort(),
					remote_ip.c_str(), remote_port);
				break;
			}

			case Protocol::TCP:
			{
				MS_DEBUG("[TCP, local:%s :%" PRIu16 ", remote:%s :%" PRIu16 "]",
					this->tcpConnection->GetLocalIP().c_str(), this->tcpConnection->GetLocalPort(),
					this->tcpConnection->GetPeerIP().c_str(), this->tcpConnection->GetPeerPort());
				break;
			}
		}
	}
}
<commit_msg>Refactor TransportTuple json output<commit_after>#define MS_CLASS "RTC::TransportTuple"

#include "RTC/TransportTuple.h"
#include "Logger.h"
#include "Utils.h"
#include <string>

namespace RTC
{
	/* Instance methods. */

	Json::Value TransportTuple::toJson()
	{
		MS_TRACE();

		static const Json::StaticString k_localIP("localIP");
		static const Json::StaticString k_remoteIP("remoteIP");
		static const Json::StaticString k_localPort("localPort");
		static const Json::StaticString k_remotePort("remotePort");
		static const Json::StaticString k_protocol("protocol");
		static const Json::StaticString v_udp("udp");
		static const Json::StaticString v_tcp("tcp");

		Json::Value json(Json::objectValue);
		int ip_family;
		std::string ip;
		uint16_t port;

		Utils::IP::GetAddressInfo(this->GetLocalAddress(), &ip_family, ip, &port);
		json[k_localIP] = ip;
		json[k_localPort] = (Json::UInt)port;
		if (this->GetProtocol() == RTC::TransportTuple::Protocol::UDP)
			json[k_protocol] = v_udp;
		else
			json[k_protocol] = v_tcp;

		Utils::IP::GetAddressInfo(this->GetRemoteAddress(), &ip_family, ip, &port);
		json[k_remoteIP] = ip;
		json[k_remotePort] = (Json::UInt)port;

		return json;
	}

	// TODO: TMP
	void TransportTuple::Dump()
	{
		MS_TRACE();

		if (!Logger::HasDebugLevel())
			return;

		switch (this->protocol)
		{
			case Protocol::UDP:
			{
				int remote_family;
				std::string remote_ip;
				uint16_t remote_port;

				Utils::IP::GetAddressInfo(GetRemoteAddress(), &remote_family, remote_ip, &remote_port);

				MS_DEBUG("[UDP, local:%s :%" PRIu16 ", remote:%s :%" PRIu16 "]",
					this->udpSocket->GetLocalIP().c_str(), this->udpSocket->GetLocalPort(),
					remote_ip.c_str(), remote_port);
				break;
			}

			case Protocol::TCP:
			{
				MS_DEBUG("[TCP, local:%s :%" PRIu16 ", remote:%s :%" PRIu16 "]",
					this->tcpConnection->GetLocalIP().c_str(), this->tcpConnection->GetLocalPort(),
					this->tcpConnection->GetPeerIP().c_str(), this->tcpConnection->GetPeerPort());
				break;
			}
		}
	}
}
<|endoftext|>


<commit_before>/*===================================================================

 The Medical Imaging Interaction Toolkit (MITK)

 Copyright (c) German Cancer Research Center,
 Division of Medical and Biological Informatics.
 All rights reserved.

 This software is distributed WITHOUT ANY WARRANTY; without
 even the implied warranty of MERCHANTABILITY or FITNESS FOR
 A PARTICULAR PURPOSE.

 See LICENSE.txt or http://www.mitk.org for details.

 ===================================================================*/

#include "mitkBindDispatcherInteractor.h"
#include "mitkMessage.h"
#include <string.h>

// us
#include "mitkGetModuleContext.h"
#include "mitkModule.h"
#include "mitkModuleRegistry.h"
#include "mitkInformer.h"

mitk::BindDispatcherInteractor::BindDispatcherInteractor() :
    m_InformerService(NULL)
{
  ModuleContext* context = ModuleRegistry::GetModule(1)->GetModuleContext();
  ServiceReference serviceRef = context->GetServiceReference<InformerService>();

  if (!serviceRef)
  {
    m_InformerService = new InformerService();
    context->RegisterService<InformerService>(m_InformerService);
  }
  m_Dispatcher = Dispatcher::New();
}

void mitk::BindDispatcherInteractor::SetDataStorage(mitk::DataStorage::Pointer dataStorage)
{
  // Set/Change Datastorage. This registers BDI to listen for events of DataStorage, to be informed when
  // a DataNode with a Interactor is added/modified/removed.

  // clean up events from previous datastorage
  UnRegisterDataStorageEvents();
  m_DataStorage = dataStorage;
  RegisterDataStorageEvents();

}

mitk::BindDispatcherInteractor::~BindDispatcherInteractor()
{
  if (m_DataStorage.IsNotNull())
  {
    UnRegisterDataStorageEvents();
  }
}

void mitk::BindDispatcherInteractor::RegisterInteractor(const mitk::DataNode* dataNode)
{
  if (m_Dispatcher.IsNotNull())
  {
    m_Dispatcher->AddDataInteractor(dataNode);
  }

}

void mitk::BindDispatcherInteractor::RegisterDataStorageEvents()
{
  if (m_DataStorage.IsNotNull())
  {
    m_DataStorage->AddNodeEvent.AddListener(
        MessageDelegate1<BindDispatcherInteractor, const DataNode*>(this, &BindDispatcherInteractor::RegisterInteractor));
    m_DataStorage->RemoveNodeEvent.AddListener(
        MessageDelegate1<BindDispatcherInteractor, const DataNode*>(this, &BindDispatcherInteractor::UnRegisterInteractor));
    m_DataStorage->ChangedNodeEvent.AddListener(
        MessageDelegate1<BindDispatcherInteractor, const DataNode*>(this, &BindDispatcherInteractor::RegisterInteractor));
  }
}

void mitk::BindDispatcherInteractor::UnRegisterInteractor(const DataNode* dataNode)
{
  if (m_Dispatcher.IsNotNull())
  {
    m_Dispatcher->RemoveDataInteractor(dataNode);
  }
}

mitk::Dispatcher::Pointer mitk::BindDispatcherInteractor::GetDispatcher()
{
  return m_Dispatcher;
}

void mitk::BindDispatcherInteractor::SetDispatcher(Dispatcher::Pointer dispatcher)
{
  m_Dispatcher = dispatcher;
}

void mitk::BindDispatcherInteractor::UnRegisterDataStorageEvents()
{
  if (m_DataStorage.IsNotNull())
  {
    m_DataStorage->AddNodeEvent.RemoveListener(
        MessageDelegate1<BindDispatcherInteractor, const DataNode*>(this, &BindDispatcherInteractor::RegisterInteractor));
    m_DataStorage->RemoveNodeEvent.RemoveListener(
        MessageDelegate1<BindDispatcherInteractor, const DataNode*>(this, &BindDispatcherInteractor::UnRegisterInteractor));
    m_DataStorage->ChangedNodeEvent.RemoveListener(
        MessageDelegate1<BindDispatcherInteractor, const DataNode*>(this, &BindDispatcherInteractor::RegisterInteractor));
  }
}
<commit_msg>Init members Error output<commit_after>/*===================================================================

 The Medical Imaging Interaction Toolkit (MITK)

 Copyright (c) German Cancer Research Center,
 Division of Medical and Biological Informatics.
 All rights reserved.

 This software is distributed WITHOUT ANY WARRANTY; without
 even the implied warranty of MERCHANTABILITY or FITNESS FOR
 A PARTICULAR PURPOSE.

 See LICENSE.txt or http://www.mitk.org for details.

 ===================================================================*/

#include "mitkBindDispatcherInteractor.h"
#include "mitkMessage.h"
#include <string.h>

// us
#include "mitkGetModuleContext.h"
#include "mitkModule.h"
#include "mitkModuleRegistry.h"
#include "mitkInformer.h"

mitk::BindDispatcherInteractor::BindDispatcherInteractor() :
    m_DataStorage(NULL),m_InformerService(NULL)
{
  ModuleContext* context = ModuleRegistry::GetModule(1)->GetModuleContext();
  if (context == NULL)
  {
    MITK_ERROR<< "BindDispatcherInteractor() - Context could not be obtained.";
    return;
  }
  ServiceReference serviceRef = context->GetServiceReference<InformerService>();

  if (!serviceRef)
  { // the service should only be registered once
    m_InformerService = new InformerService();
    context->RegisterService<InformerService>(m_InformerService);
  }
  m_Dispatcher = Dispatcher::New();
}

void mitk::BindDispatcherInteractor::SetDataStorage(mitk::DataStorage::Pointer dataStorage)
{
  // Set/Change Datastorage. This registers BDI to listen for events of DataStorage, to be informed when
  // a DataNode with a Interactor is added/modified/removed.

  // clean up events from previous datastorage
  UnRegisterDataStorageEvents();
  m_DataStorage = dataStorage;
  RegisterDataStorageEvents();

}

mitk::BindDispatcherInteractor::~BindDispatcherInteractor()
{
  if (m_DataStorage.IsNotNull())
  {
    UnRegisterDataStorageEvents();
  }
}

void mitk::BindDispatcherInteractor::RegisterInteractor(const mitk::DataNode* dataNode)
{
  if (m_Dispatcher.IsNotNull())
  {
    m_Dispatcher->AddDataInteractor(dataNode);
  }

}

void mitk::BindDispatcherInteractor::RegisterDataStorageEvents()
{
  if (m_DataStorage.IsNotNull())
  {
    m_DataStorage->AddNodeEvent.AddListener(
        MessageDelegate1<BindDispatcherInteractor, const DataNode*>(this, &BindDispatcherInteractor::RegisterInteractor));
    m_DataStorage->RemoveNodeEvent.AddListener(
        MessageDelegate1<BindDispatcherInteractor, const DataNode*>(this, &BindDispatcherInteractor::UnRegisterInteractor));
    m_DataStorage->ChangedNodeEvent.AddListener(
        MessageDelegate1<BindDispatcherInteractor, const DataNode*>(this, &BindDispatcherInteractor::RegisterInteractor));
  }
}

void mitk::BindDispatcherInteractor::UnRegisterInteractor(const DataNode* dataNode)
{
  if (m_Dispatcher.IsNotNull())
  {
    m_Dispatcher->RemoveDataInteractor(dataNode);
  }
}

mitk::Dispatcher::Pointer mitk::BindDispatcherInteractor::GetDispatcher()
{
  return m_Dispatcher;
}

void mitk::BindDispatcherInteractor::SetDispatcher(Dispatcher::Pointer dispatcher)
{
  m_Dispatcher = dispatcher;
}

void mitk::BindDispatcherInteractor::UnRegisterDataStorageEvents()
{
  if (m_DataStorage.IsNotNull())
  {
    m_DataStorage->AddNodeEvent.RemoveListener(
        MessageDelegate1<BindDispatcherInteractor, const DataNode*>(this, &BindDispatcherInteractor::RegisterInteractor));
    m_DataStorage->RemoveNodeEvent.RemoveListener(
        MessageDelegate1<BindDispatcherInteractor, const DataNode*>(this, &BindDispatcherInteractor::UnRegisterInteractor));
    m_DataStorage->ChangedNodeEvent.RemoveListener(
        MessageDelegate1<BindDispatcherInteractor, const DataNode*>(this, &BindDispatcherInteractor::RegisterInteractor));
  }
}
<|endoftext|>


<commit_before>#pragma once
//=====================================================================//
/*!	@file
	@brief	メニュー・クラス
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2017 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include <cstdint>

namespace graphics {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief	メニュー・クラス
		@param[in]	GR		描画クラス
		@param[in]	MAX		最大メニュー数
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <class GR, uint16_t MAX>
	class menu {

	public:
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief	オブジェクト・タイプ
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		enum class type : uint8_t {
			TEXT,	///< 等幅フォント
			PROP,	///< プロポーショナル・フォント
			MOBJ,	///< モーション・オブジェクト
		};

	private:
		GR&	gr_;

		uint16_t	size_;

		struct obj_t {
			type		type_;
			const void* src_;
			uint8_t		w_;
			uint8_t		h_;

			obj_t() : type_(type::TEXT), src_(nullptr), w_(0), h_(0) { }
		};
		obj_t	obj_[MAX];

		int16_t		mx_;
		int16_t		my_;

		int16_t		spc_;

		uint16_t	pos_;

		bool		focus_;

	public:
		//-----------------------------------------------------------------//
		/*!
			@brief	コンストラクター
		*/
		//-----------------------------------------------------------------//
		menu(GR& gr) : gr_(gr), size_(0), mx_(0), my_(0),
					   spc_(0), pos_(0), focus_(true)
		{ }

		//-----------------------------------------------------------------//
		/*!
			@brief	隙間の設定
			@param[in]	spc	隙間
		*/
		//-----------------------------------------------------------------//
		void set_space(int16_t spc) { spc_ = spc; }

		//-----------------------------------------------------------------//
		/*!
			@brief	サイズを返す（登録されているメニュー数）
		*/
		//-----------------------------------------------------------------//
		uint16_t size() const { return size_; }

		//-----------------------------------------------------------------//
		/*!
			@brief	フォーカスを許可
		*/
		//-----------------------------------------------------------------//
		void enable_focus(bool f = true)
		{
			focus_ = f;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	フォーカスを戻す
		*/
		//-----------------------------------------------------------------//
		void focus_prev()
		{
			if(!focus_) return;

			if(pos_ > 0) {
				pos_--;
			}
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	フォーカスを進める
		*/
		//-----------------------------------------------------------------//
		void focus_next()
		{
			if(!focus_) return;

			++pos_;
			if(pos_ >= size_) {
				pos_ = size_ - 1;
			}
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	メニュー位置を取得
			@return メニュー位置
		*/
		//-----------------------------------------------------------------//
		uint16_t get_pos() const { return pos_; }

		//-----------------------------------------------------------------//
		/*!
			@brief	クリア
		*/
		//-----------------------------------------------------------------//
		void clear()
		{
			size_ = 0;
			mx_ = 0;
			my_ = 0;
			pos_ = 0;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	オブジェクトを追加
			@param[in]	t	オブジェクト・タイプ
			@param[in]	src	オブジェクト・ソース
		*/
		//-----------------------------------------------------------------//
		void add(type t, const void* src) {
			if(size_ >= MAX) return;

			if(t == type::TEXT) {
				obj_[size_].w_ = gr_.draw_text_length(static_cast<const char*>(src), false);
				obj_[size_].h_ = gr_.get_afont_height();
			} else if(t == type::PROP) {
				obj_[size_].w_ = gr_.draw_text_length(static_cast<const char*>(src), true);
				obj_[size_].h_ = gr_.get_afont_height();
			} else if(t == type::MOBJ) {
				uint8_t w;
				uint8_t h;
				gr_.get_mobj_size(src, w, h);
				obj_[size_].w_ = w;
				obj_[size_].h_ = h;
			} else {
				return;
			}
			obj_[size_].type_ = t;
			obj_[size_].src_  = src;
			++size_;

			int16_t x = 0;
			int16_t y = 0;
			for(auto i = 0; i < size_; ++i) {
				if(x < obj_[i].w_) x = obj_[i].w_;
				y += obj_[i].h_;
				y += spc_;
			}
			mx_ = x;
			my_ = y;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	レンダリング
			@param[in]	ox	描画オフセットＸ
			@param[in]	oy	描画オフセットＹ
		*/
		//-----------------------------------------------------------------//
		void render(int16_t ox = 0, int16_t oy = 0) const
		{
			if(size_ == 0) return;

			int16_t x = (gr_.get_width()  - ox - mx_) / 2;
			int16_t y = (gr_.get_height() - oy - my_) / 2;
			x += ox;
			y += oy;
			for(auto i = 0; i < size_; ++i) {
				y += spc_ / 2;
				uint8_t w;
				uint8_t h;
				if(obj_[i].type_ == type::TEXT) {
					gr_.draw_text(x, y, static_cast<const char*>(obj_[i].src_), false);
				} else if(obj_[i].type_ == type::PROP) {
					gr_.draw_text(x, y, static_cast<const char*>(obj_[i].src_), true);
				} else if(obj_[i].type_ == type::MOBJ) {
					gr_.draw_mobj(x, y, obj_[i].src_);
				}
				if(focus_ && i == pos_) {
					gr_.reverse(x - 1, y, obj_[i].w_ + 2, obj_[i].h_);
				}
				y += gr_.get_afont_height();
				y += spc_ / 2;
			}
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	GR インスタンスへの参照
		*/
		//-----------------------------------------------------------------//
		GR& at() { return gr_; }
	};
}
<commit_msg>update: manage menu system<commit_after>#pragma once
//=====================================================================//
/*!	@file
	@brief	メニュー・クラス
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2017, 2018 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include <cstdint>

namespace graphics {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief	メニュー・クラス
		@param[in]	REND	描画クラス
		@param[in]	MAX		最大メニュー数
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <class REND, uint16_t MAX>
	class menu {

	public:
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief	オブジェクト・タイプ
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		enum class type : uint8_t {
			TEXT,	///< 等幅フォント
			PROP,	///< プロポーショナル・フォント
			MOBJ,	///< モーション・オブジェクト
		};

	private:
		REND&		rend_;

		uint16_t	size_;

		struct obj_t {
			type		type_;
			uint8_t		w_;
			uint8_t		h_;
			const void* src_;

			obj_t() : type_(type::TEXT), w_(0), h_(0), src_(nullptr) { }
		};
		obj_t	obj_[MAX];

		int16_t		mx_;
		int16_t		my_;

		int8_t		gap_;
		int8_t		space_w_;
		int8_t		space_h_;

		uint16_t	pos_;

		typename REND::value_type	fc_;
		typename REND::value_type	bc_;

		bool		frame_;
		bool		focus_;

	public:
		//-----------------------------------------------------------------//
		/*!
			@brief	コンストラクター
			@param[in]	rend	描画クラス
		*/
		//-----------------------------------------------------------------//
		menu(REND& rend) noexcept : rend_(rend), size_(0), mx_(0), my_(0),
			gap_(0), space_w_(0), space_h_(0), pos_(0),
			fc_(REND::COLOR::Black), bc_(REND::COLOR::White),
			frame_(true), focus_(true)
		{ }

		//-----------------------------------------------------------------//
		/*!
			@brief	スペースの設定
			@param[in]	w	横幅
			@param[in]	h	高さ
		*/
		//-----------------------------------------------------------------//
		void set_space(int16_t w, int16_t h) noexcept
		{
			space_w_ = w;
			space_h_ = h;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	ギャップの設定
			@param[in]	gap	ギャップ
		*/
		//-----------------------------------------------------------------//
		void set_gap(int16_t gap) noexcept { gap_ = gap; }

		//-----------------------------------------------------------------//
		/*!
			@brief	サイズを返す（登録されているメニュー数）
		*/
		//-----------------------------------------------------------------//
		uint16_t size() const noexcept { return size_; }

		//-----------------------------------------------------------------//
		/*!
			@brief	フォーカスを許可
			@param[in]	f	不許可の場合「false」
		*/
		//-----------------------------------------------------------------//
		void enable_focus(bool f = true) noexcept
		{
			focus_ = f;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	フレームの描画
			@param[in]	f	不許可の場合「false」
		*/
		//-----------------------------------------------------------------//
		void draw_frame(bool f = true) noexcept
		{
			frame_ = f;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	フォーカスを戻す
		*/
		//-----------------------------------------------------------------//
		void focus_prev() noexcept
		{
			if(!focus_) return;

			if(pos_ > 0) {
				pos_--;
			}
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	フォーカスを進める
		*/
		//-----------------------------------------------------------------//
		void focus_next() noexcept
		{
			if(!focus_) return;

			++pos_;
			if(pos_ >= size_) {
				pos_ = size_ - 1;
			}
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	メニュー位置を取得
			@return メニュー位置
		*/
		//-----------------------------------------------------------------//
		uint16_t get_pos() const noexcept { return pos_; }

		//-----------------------------------------------------------------//
		/*!
			@brief	クリア
		*/
		//-----------------------------------------------------------------//
		void clear() noexcept
		{
			size_ = 0;
			mx_ = 0;
			my_ = 0;
			pos_ = 0;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	オブジェクトを追加
			@param[in]	t	オブジェクト・タイプ
			@param[in]	src	オブジェクト・ソース
		*/
		//-----------------------------------------------------------------//
		void add(type t, const void* src) noexcept {
			if(size_ >= MAX) return;

			if(t == type::TEXT) {
				obj_[size_].w_ = rend_.get_text_length(static_cast<const char*>(src), false);
				obj_[size_].h_ = REND::font_height;
			} else if(t == type::PROP) {
				obj_[size_].w_ = rend_.get_text_length(static_cast<const char*>(src), true);
				obj_[size_].h_ = REND::font_height;
			} else if(t == type::MOBJ) {
				uint8_t w;
				uint8_t h;
				rend_.get_mobj_size(src, w, h);
				obj_[size_].w_ = w;
				obj_[size_].h_ = h;
			} else {
				return;
			}
			obj_[size_].type_ = t;
			obj_[size_].src_  = src;
			++size_;

			int16_t x = 0;
			int16_t y = 0;
			for(auto i = 0; i < size_; ++i) {
				if(x < obj_[i].w_) x = obj_[i].w_;
				y += obj_[i].h_;
				y += gap_;
				y += space_h_ * 2;
			}
			mx_ = x;
			my_ = y;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	レンダリング
			@param[in]	ox	描画オフセットＸ
			@param[in]	oy	描画オフセットＹ
		*/
		//-----------------------------------------------------------------//
		void render(int16_t ox = 0, int16_t oy = 0) const noexcept
		{
			if(size_ == 0) return;

			int16_t x = (REND::width  - ox - mx_) / 2;
			int16_t y = (REND::height - oy - my_) / 2;
			x += ox;
			y += oy;
			auto tmp_fc = rend_.get_fore_color();
			rend_.set_fore_color(fc_);
			for(auto i = 0; i < size_; ++i) {
				y += gap_ / 2;
				uint8_t w;
				uint8_t h;
				if(obj_[i].type_ == type::TEXT) {
					rend_.fill_r(x, y, mx_ + space_w_ * 2, obj_[i].h_ + space_h_ * 2, bc_);
					y += space_h_;
					auto t = static_cast<const char*>(obj_[i].src_);
					rend_.draw_text(x + space_w_, y, t);

				} else if(obj_[i].type_ == type::PROP) {
					rend_.fill_r(x, y, mx_ + space_w_ * 2, obj_[i].h_ + space_h_ * 2, bc_);
					y += space_h_;
					auto t = static_cast<const char*>(obj_[i].src_);
					rend_.draw_text(x + space_w_, y, t, true);
				} else if(obj_[i].type_ == type::MOBJ) {
					y += space_h_;
					rend_.draw_mobj(x, y, obj_[i].src_);
				}
//				if(focus_ && i == pos_) {
//					rend_.reverse(x - 1, y, obj_[i].w_ + 2, obj_[i].h_);
//				}
				y += REND::font_height;
				y += space_h_;
				y += gap_ - (gap_ / 2);
			}
			rend_.set_fore_color(tmp_fc);
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	REND クラスの参照
			@return REND クラス
		*/
		//-----------------------------------------------------------------//
		REND& at() noexcept { return rend_; }
	};
}
<|endoftext|>


<commit_before>#include "matrix.hpp"

using namespace std;

Matrix::Matrix(): st(0), cl(0), matr{nullptr}
{
}

Matrix::Matrix(int m, int n) : st(m), cl(n)
{
	matr = new int *[m];
	for (int i = 0; i < m; i++)
		matr[i] = new int[n]();
}

Matrix::Matrix(const Matrix  &matrc)
{
	matr = new int*[matrc.st];
	for (int i = 0; i < matrc.st; i++)
		matr[i] = new int[matrc.cl];
	st = matrc.st;
	cl = matrc.cl;
	for (int i = 0; i < matrc.st; i++)
	for (int j = 0; j < matrc.cl; j++)
		matr[i][j] = matrc.matr[i][j];
}

Matrix::~Matrix()
{
	for (int i = 0; i < st; i++)
		delete[] matr[i];
	delete[] matr;
}

Matrix Matrix::operator+ (const Matrix &mat_2) const
{
	if (st != mat_2.st || cl != mat_2.cl)
	{
		cout << "Add error\n";
		system("pause");
		exit(1);
	}
	Matrix result(st, cl);
	for (int i = 0; i < st; i++)
	{
		for (int j = 0; j < cl; j++)
			result.matr[i][j] = matr[i][j] + mat_2.matr[i][j];
	}
	return result;
}
Matrix Matrix::operator*(const Matrix &mat_2) const
{
	if (st != mat_2.cl)
	{
		cout << "Mult error\n";
		system("pause");
		exit(1);
	}
	Matrix result(st, mat_2.cl);
	for (int i = 0; i < st; i++)
	for (int j = 0; j < mat_2.cl; j++)
	{
		result.matr[i][j] = 0;
		for (int k = 0; k < cl; k++)
			result.matr[i][j] += matr[i][k] * mat_2.matr[k][j];
	}
	return result;
}

Matrix& Matrix::operator =(Matrix &matrc)
{
	for (int i = 0; i < st; i++)
		delete[] matr[i];
	delete[] matr;
	st = matrc.st;
	cl = matrc.cl;
	for (int i = 0; i < matrc.st; i++)
		matr[i] = new int[matrc.cl];
	for (int i = 0; i < st; i++)
	for (int j = 0; j < cl; j++)
		matr[i][j] = matrc.matr[i][j];
	return *this;
}

bool Matrix::operator==(const Matrix& com)const
{
	bool res = true;
	if (st != com.st || cl != com.cl)
	{
		cout << "Comp error" << endl;
		system("pause");
		exit(1);
	}
	else
	{
		for (int i = 0; i < st; i++)
		for (int j = 0; j < cl; j++)
		if (matr[i][j] != com.matr[i][j])
			res = false;
	}
	return res;
}

istream& operator >> (istream& in, Matrix& mat)
{
	for (int i = 0; i < mat.st; i++)
	for (int j = 0; j < mat.cl; j++)
		in >> mat.matr[i][j];
	return in;
}

ostream& operator << (ostream& out, const Matrix& mat)
{
	for (int i = 0; i < mat.st; i++)
	{
		for (int j = 0; j < mat.cl; j++)
			out << " " << mat.matr[i][j];
		out << endl;
	}
	return out;
}

int Matrix::rows() const
{
	return st;
}

int Matrix::columns() const
{
	return cl;
}
<commit_msg>Update matrix.cpp<commit_after>#include "matrix.hpp"

<|endoftext|>


<commit_before><commit_msg>Migrate unsupported hosted app launch settings to new bookmark app world<commit_after><|endoftext|>