<commit_before>#pragma once

#include "coding/varint.hpp"

#include "base/assert.hpp"

#include "std/string.hpp"

namespace utils
{
  template <class TSink> void WriteString(TSink & sink, string const & s)
  {
    CHECK(!s.empty(), ());

    size_t const sz = s.size();
    WriteVarUint(sink, static_cast<uint32_t>(sz-1));
    sink.Write(s.c_str(), sz);
  }

  template <class TSource> void ReadString(TSource & src, string & s)
  {
    uint32_t const sz = ReadVarUint<uint32_t>(src) + 1;
    s.resize(sz);
    src.Read(&s[0], sz);

    CHECK(!s.empty(), ());
  }
}

class StringUtf8Multilang
{
  string m_s;

  size_t GetNextIndex(size_t i) const;

public:
  static int8_t const UNSUPPORTED_LANGUAGE_CODE = -1;
  static int8_t const DEFAULT_CODE = 0;

  /// @return UNSUPPORTED_LANGUAGE_CODE if language is not recognized
  static int8_t GetLangIndex(string const & lang);
  /// @return empty string if langCode is invalid
  static char const * GetLangByCode(int8_t langCode);

  inline bool operator== (StringUtf8Multilang const & rhs) const
  {
    return (m_s == rhs.m_s);
  }

  inline void Clear() { m_s.clear(); }
  inline bool IsEmpty() const { return m_s.empty(); }

  void AddString(int8_t lang, string const & utf8s);
  void AddString(string const & lang, string const & utf8s)
  {
    int8_t const l = GetLangIndex(lang);
    if (l >= 0)
      AddString(l, utf8s);
  }

  template <class T>
  void ForEachRef(T & functor) const
  {
    size_t i = 0;
    size_t const sz = m_s.size();
    while (i < sz)
    {
      size_t const next = GetNextIndex(i);
      if (!functor((m_s[i] & 0x3F), m_s.substr(i + 1, next - i - 1)))
        return;
      i = next;
    }
  }

  bool GetString(int8_t lang, string & utf8s) const;
  bool GetString(string const & lang, string & utf8s) const
  {
    int8_t const l = GetLangIndex(lang);
    if (l >= 0)
      return GetString(l, utf8s);
    else
      return false;
  }

  int8_t FindString(string const & utf8s) const;

  template <class TSink> void Write(TSink & sink) const
  {
    utils::WriteString(sink, m_s);
  }

  template <class TSource> void Read(TSource & src)
  {
    utils::ReadString(src, m_s);
  }
};

string DebugPrint(StringUtf8Multilang const & s);
<commit_msg>Pass in-place lambdas.<commit_after>#pragma once

#include "coding/varint.hpp"

#include "base/assert.hpp"

#include "std/string.hpp"

namespace utils
{
  template <class TSink> void WriteString(TSink & sink, string const & s)
  {
    CHECK(!s.empty(), ());

    size_t const sz = s.size();
    WriteVarUint(sink, static_cast<uint32_t>(sz-1));
    sink.Write(s.c_str(), sz);
  }

  template <class TSource> void ReadString(TSource & src, string & s)
  {
    uint32_t const sz = ReadVarUint<uint32_t>(src) + 1;
    s.resize(sz);
    src.Read(&s[0], sz);

    CHECK(!s.empty(), ());
  }
}

class StringUtf8Multilang
{
  string m_s;

  size_t GetNextIndex(size_t i) const;

public:
  static int8_t const UNSUPPORTED_LANGUAGE_CODE = -1;
  static int8_t const DEFAULT_CODE = 0;

  /// @return UNSUPPORTED_LANGUAGE_CODE if language is not recognized
  static int8_t GetLangIndex(string const & lang);
  /// @return empty string if langCode is invalid
  static char const * GetLangByCode(int8_t langCode);

  inline bool operator== (StringUtf8Multilang const & rhs) const
  {
    return (m_s == rhs.m_s);
  }

  inline void Clear() { m_s.clear(); }
  inline bool IsEmpty() const { return m_s.empty(); }

  void AddString(int8_t lang, string const & utf8s);
  void AddString(string const & lang, string const & utf8s)
  {
    int8_t const l = GetLangIndex(lang);
    if (l >= 0)
      AddString(l, utf8s);
  }

  template <class T>
  void ForEachRef(T && functor) const
  {
    size_t i = 0;
    size_t const sz = m_s.size();
    while (i < sz)
    {
      size_t const next = GetNextIndex(i);
      if (!functor((m_s[i] & 0x3F), m_s.substr(i + 1, next - i - 1)))
        return;
      i = next;
    }
  }

  bool GetString(int8_t lang, string & utf8s) const;
  bool GetString(string const & lang, string & utf8s) const
  {
    int8_t const l = GetLangIndex(lang);
    if (l >= 0)
      return GetString(l, utf8s);
    else
      return false;
  }

  int8_t FindString(string const & utf8s) const;

  template <class TSink> void Write(TSink & sink) const
  {
    utils::WriteString(sink, m_s);
  }

  template <class TSource> void Read(TSource & src)
  {
    utils::ReadString(src, m_s);
  }
};

string DebugPrint(StringUtf8Multilang const & s);
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: dlgpage.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hr $ $Date: 2004-02-03 20:13: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): _______________________________________
 *
 *
 ************************************************************************/

#define ITEMID_COLOR_TABLE      SID_COLOR_TABLE
#define ITEMID_GRADIENT_LIST    SID_GRADIENT_LIST
#define ITEMID_HATCH_LIST       SID_HATCH_LIST
#define ITEMID_BITMAP_LIST      SID_BITMAP_LIST
#include <svtools/intitem.hxx> //add CHINA001
#ifndef _SVX_PAGE_HXX
#include <svx/page.hxx>
#endif
#ifndef _SVX_DIALOGS_HRC
#include <svx/dialogs.hrc>
#endif
#ifndef _SVX_TAB_AREA_HXX
#include <svx/tabarea.hxx>
#endif
#ifndef _SVX_DRAWITEM_HXX
#include <svx/drawitem.hxx>
#endif

#ifndef _SD_SDRESID_HXX
#include "sdresid.hxx"
#endif
#include "dlgpage.hxx"

#include "DrawDocShell.hxx"

/*************************************************************************
|*
|* Konstruktor des Tab-Dialogs: Fuegt die Seiten zum Dialog hinzu
|*
\************************************************************************/

SdPageDlg::SdPageDlg( SfxObjectShell* pDocSh, Window* pParent, const SfxItemSet* pAttr, BOOL bAreaPage ) :
        SfxTabDialog ( pParent, SdResId( TAB_PAGE ), pAttr ),
        rOutAttrs           ( *pAttr ),
        pDocShell           ( pDocSh )
{
    SvxColorTableItem aColorTableItem(*( (const SvxColorTableItem*)
        ( pDocShell->GetItem( SID_COLOR_TABLE ) ) ) );
    SvxGradientListItem aGradientListItem(*( (const SvxGradientListItem*)
        ( pDocShell->GetItem( SID_GRADIENT_LIST ) ) ) );
    SvxBitmapListItem aBitmapListItem(*( (const SvxBitmapListItem*)
        ( pDocShell->GetItem( SID_BITMAP_LIST ) ) ) );
    SvxHatchListItem aHatchListItem(*( (const SvxHatchListItem*)
        ( pDocShell->GetItem( SID_HATCH_LIST ) ) ) );

    pColorTab = aColorTableItem.GetColorTable();
    pGradientList = aGradientListItem.GetGradientList();
    pHatchingList = aHatchListItem.GetHatchList();
    pBitmapList = aBitmapListItem.GetBitmapList();

    FreeResource();

    AddTabPage( RID_SVXPAGE_PAGE, SvxPageDescPage::Create, 0);
    AddTabPage( RID_SVXPAGE_AREA);//CHINA001 AddTabPage( RID_SVXPAGE_AREA, SvxAreaTabPage::Create, 0 );

    nDlgType = 1; // Vorlagen-Dialog
    nPageType = 0;
    nPos = 0;

    nColorTableState = CT_NONE;
    nBitmapListState = CT_NONE;
    nGradientListState = CT_NONE;
    nHatchingListState = CT_NONE;

    if(!bAreaPage)  // I have to add the page before I remove it !
        RemoveTabPage( RID_SVXPAGE_AREA );
}

/*************************************************************************
|*
|* Seite wird erzeugt
|*
\************************************************************************/

void SdPageDlg::PageCreated(USHORT nId, SfxTabPage& rPage)
{
    switch(nId)
    {
    case RID_SVXPAGE_PAGE:
        ( (SvxPageDescPage&) rPage).SetMode(SVX_PAGE_MODE_PRESENTATION);
        ( (SvxPageDescPage&) rPage).SetPaperFormatRanges( SVX_PAPER_A0, SVX_PAPER_E );
        break;
    case RID_SVXPAGE_AREA:
//CHINA001      ( (SvxAreaTabPage&) rPage ).SetColorTable( pColorTab );
//CHINA001      ( (SvxAreaTabPage&) rPage ).SetGradientList( pGradientList );
//CHINA001      ( (SvxAreaTabPage&) rPage ).SetHatchingList( pHatchingList );
//CHINA001      ( (SvxAreaTabPage&) rPage ).SetBitmapList( pBitmapList );
//CHINA001      ( (SvxAreaTabPage&) rPage ).SetPageType( &nPageType );
//CHINA001      ( (SvxAreaTabPage&) rPage ).SetDlgType( &nDlgType );
//CHINA001      ( (SvxAreaTabPage&) rPage ).SetPos( &nPos );
//CHINA001      ( (SvxAreaTabPage&) rPage ).SetGrdChgd( &nGradientListState );
//CHINA001      ( (SvxAreaTabPage&) rPage ).SetHtchChgd( &nHatchingListState );
//CHINA001      ( (SvxAreaTabPage&) rPage ).SetBmpChgd( &nBitmapListState );
//CHINA001      ( (SvxAreaTabPage&) rPage ).SetColorChgd( &nColorTableState );
//CHINA001      ( (SvxAreaTabPage&) rPage ).Construct();
            SfxAllItemSet aSet(*(GetRefreshedSet()->GetPool()));
            aSet.Put (SvxColorTableItem(pColorTab,SID_COLOR_TABLE));
            aSet.Put (SvxGradientListItem(pGradientList,SID_GRADIENT_LIST));
            aSet.Put (SvxHatchListItem(pHatchingList,SID_HATCH_LIST));
            aSet.Put (SvxBitmapListItem(pBitmapList,SID_BITMAP_LIST));
            aSet.Put (SfxUInt16Item(SID_PAGE_TYPE,nPageType));
            aSet.Put (SfxUInt16Item(SID_DLG_TYPE,nDlgType));
            aSet.Put (SfxUInt16Item(SID_TABPAGE_POS,nPos));
            rPage.PageCreated(aSet);
        break;
    }
}

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

#define ITEMID_COLOR_TABLE      SID_COLOR_TABLE
#define ITEMID_GRADIENT_LIST    SID_GRADIENT_LIST
#define ITEMID_HATCH_LIST       SID_HATCH_LIST
#define ITEMID_BITMAP_LIST      SID_BITMAP_LIST
#include <svtools/intitem.hxx> //add CHINA001
//CHINA001 #ifndef _SVX_PAGE_HXX
//CHINA001 #include <svx/page.hxx>
//CHINA001 #endif
#ifndef _SVX_DIALOGS_HRC
#include <svx/dialogs.hrc>
#endif
#ifndef _SVX_TAB_AREA_HXX
#include <svx/tabarea.hxx>
#endif
#ifndef _SVX_DRAWITEM_HXX
#include <svx/drawitem.hxx>
#endif

#ifndef _SD_SDRESID_HXX
#include "sdresid.hxx"
#endif
#include "dlgpage.hxx"

#include "DrawDocShell.hxx"

#ifndef _AEITEM_HXX //CHINA001
#include <svtools/aeitem.hxx> //CHINA001
#endif //CHINA001
#include <svx/flagsdef.hxx> //CHINA001
#include <svx/svxenum.hxx> //CHINA001

/*************************************************************************
|*
|* Konstruktor des Tab-Dialogs: Fuegt die Seiten zum Dialog hinzu
|*
\************************************************************************/

SdPageDlg::SdPageDlg( SfxObjectShell* pDocSh, Window* pParent, const SfxItemSet* pAttr, BOOL bAreaPage ) :
        SfxTabDialog ( pParent, SdResId( TAB_PAGE ), pAttr ),
        rOutAttrs           ( *pAttr ),
        pDocShell           ( pDocSh )
{
    SvxColorTableItem aColorTableItem(*( (const SvxColorTableItem*)
        ( pDocShell->GetItem( SID_COLOR_TABLE ) ) ) );
    SvxGradientListItem aGradientListItem(*( (const SvxGradientListItem*)
        ( pDocShell->GetItem( SID_GRADIENT_LIST ) ) ) );
    SvxBitmapListItem aBitmapListItem(*( (const SvxBitmapListItem*)
        ( pDocShell->GetItem( SID_BITMAP_LIST ) ) ) );
    SvxHatchListItem aHatchListItem(*( (const SvxHatchListItem*)
        ( pDocShell->GetItem( SID_HATCH_LIST ) ) ) );

    pColorTab = aColorTableItem.GetColorTable();
    pGradientList = aGradientListItem.GetGradientList();
    pHatchingList = aHatchListItem.GetHatchList();
    pBitmapList = aBitmapListItem.GetBitmapList();

    FreeResource();

    AddTabPage( RID_SVXPAGE_PAGE); //CHINA001 AddTabPage( RID_SVXPAGE_PAGE, SvxPageDescPage::Create, 0);
    AddTabPage( RID_SVXPAGE_AREA); //CHINA001 AddTabPage( RID_SVXPAGE_AREA, SvxAreaTabPage::Create, 0 );

    nDlgType = 1; // Vorlagen-Dialog
    nPageType = 0;
    nPos = 0;

    nColorTableState = CT_NONE;
    nBitmapListState = CT_NONE;
    nGradientListState = CT_NONE;
    nHatchingListState = CT_NONE;

    if(!bAreaPage)  // I have to add the page before I remove it !
        RemoveTabPage( RID_SVXPAGE_AREA );
}

/*************************************************************************
|*
|* Seite wird erzeugt
|*
\************************************************************************/

void SdPageDlg::PageCreated(USHORT nId, SfxTabPage& rPage)
{
    SfxAllItemSet aSet(*(GetInputSetImpl()->GetPool()));
    switch(nId)
    {
    case RID_SVXPAGE_PAGE:
        //CHINA001 ( (SvxPageDescPage&) rPage).SetMode(SVX_PAGE_MODE_PRESENTATION);
        //CHINA001 ( (SvxPageDescPage&) rPage).SetPaperFormatRanges( SVX_PAPER_A0, SVX_PAPER_E );
        aSet.Put (SfxAllEnumItem((const USHORT)SID_ENUM_PAGE_MODE, SVX_PAGE_MODE_PRESENTATION)); //CHINA001
        aSet.Put (SfxAllEnumItem((const USHORT)SID_PAPER_START, SVX_PAPER_A0)); //CHINA001
        aSet.Put (SfxAllEnumItem((const USHORT)SID_PAPER_END, SVX_PAPER_E)); //CHINA001
        rPage.PageCreated(aSet); //CHINA001
        break;
    case RID_SVXPAGE_AREA:
//CHINA001      ( (SvxAreaTabPage&) rPage ).SetColorTable( pColorTab );
//CHINA001      ( (SvxAreaTabPage&) rPage ).SetGradientList( pGradientList );
//CHINA001      ( (SvxAreaTabPage&) rPage ).SetHatchingList( pHatchingList );
//CHINA001      ( (SvxAreaTabPage&) rPage ).SetBitmapList( pBitmapList );
//CHINA001      ( (SvxAreaTabPage&) rPage ).SetPageType( &nPageType );
//CHINA001      ( (SvxAreaTabPage&) rPage ).SetDlgType( &nDlgType );
//CHINA001      ( (SvxAreaTabPage&) rPage ).SetPos( &nPos );
//CHINA001      ( (SvxAreaTabPage&) rPage ).SetGrdChgd( &nGradientListState );
//CHINA001      ( (SvxAreaTabPage&) rPage ).SetHtchChgd( &nHatchingListState );
//CHINA001      ( (SvxAreaTabPage&) rPage ).SetBmpChgd( &nBitmapListState );
//CHINA001      ( (SvxAreaTabPage&) rPage ).SetColorChgd( &nColorTableState );
//CHINA001      ( (SvxAreaTabPage&) rPage ).Construct();
            aSet.Put (SvxColorTableItem(pColorTab,SID_COLOR_TABLE));
            aSet.Put (SvxGradientListItem(pGradientList,SID_GRADIENT_LIST));
            aSet.Put (SvxHatchListItem(pHatchingList,SID_HATCH_LIST));
            aSet.Put (SvxBitmapListItem(pBitmapList,SID_BITMAP_LIST));
            aSet.Put (SfxUInt16Item(SID_PAGE_TYPE,nPageType));
            aSet.Put (SfxUInt16Item(SID_DLG_TYPE,nDlgType));
            aSet.Put (SfxUInt16Item(SID_TABPAGE_POS,nPos));
            rPage.PageCreated(aSet);
        break;
    }
}

<|endoftext|>


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

#ifndef _SFX_OBJSH_HXX // SfxObjectShell
#include <sfx2/objsh.hxx>
#endif

#ifndef _SV_GDIMTF_HXX // GDIMetaFile
#include <vcl/gdimtf.hxx>
#endif

#ifndef _SV_VIRDEV_HXX // class VirtualDevice
#include <vcl/virdev.hxx>
#endif

#ifndef _COM_SUN_STAR_PRESENTATION_FADEEFFECT_HPP_
#include <com/sun/star/presentation/FadeEffect.hpp>
#endif

#ifndef _SD_FADEDEF_H // enum FadeSpeed
#include <fadedef.h>
#endif

#ifndef _SV_CTRL_HXX // class Control
#include <vcl/ctrl.hxx>
#endif

#ifndef _SD_FADER_HXX
#include "fader.hxx"
#endif

#include "docprev.hxx"
#include "drawdoc.hxx"
#include "docshell.hxx"
#include "viewshel.hxx"
#include "showview.hxx"

using namespace ::com::sun::star;

const int SdDocPreviewWin::FRAME = 4;

void SdDocPreviewWin::SetObjectShell( SfxObjectShell* pObj, USHORT nShowPage )
{

    SdDrawDocShell* pDocShell = PTR_CAST(SdDrawDocShell,pObj);
    SdDrawDocument* pDoc = pDocShell?pDocShell->GetDoc():NULL;
    if(pDoc)
    {
        const USHORT nPageCount = pDoc->GetSdPageCount(PK_STANDARD);
        USHORT nPgNum = 0;
        while( nPgNum < nPageCount )
        {
            pDoc->SetSelected( pDoc->GetSdPage( nPgNum, PK_STANDARD ), nPgNum == nShowPage );
            nPgNum++;
        }
    }

    GDIMetaFile* pFile = pObj ? pObj->GetPreviewMetaFile( ) : 0;
    delete pMetaFile;
    pMetaFile = pFile;
    m_pObj = pObj;
    Invalidate();
}

SdDocPreviewWin::SdDocPreviewWin( Window* pParent, const ResId& rResId )
: Control(pParent, rResId), pMetaFile( 0 ), bInEffect(FALSE), m_pObj(NULL)
{
    SetBorderStyle( WINDOW_BORDER_MONO );
}

SdDocPreviewWin::SdDocPreviewWin( Window* pParent )
: Control(pParent, 0 ), pMetaFile( 0 ), bInEffect(FALSE), m_pObj(NULL)
{
    SetBorderStyle( WINDOW_BORDER_MONO );
    Resize();
    Show();
}

void SdDocPreviewWin::Resize()
{
    Invalidate();
}

void SdDocPreviewWin::SetGDIFile( GDIMetaFile* pFile )
{
    delete pMetaFile;
    pMetaFile = pFile;
    Invalidate();
}

void SdDocPreviewWin::CalcSizeAndPos( GDIMetaFile* pFile, Size& rSize, Point& rPoint )
{
    Size aTmpSize = pFile ? pFile->GetPrefSize() : Size(1,1 );
    long nWidth = rSize.Width() - 2*FRAME;
    long nHeight = rSize.Height() - 2*FRAME;
    if( nWidth < 0 ) nWidth = 0;
    if( nHeight < 0 ) nHeight = 0;

    double dRatio=((double)aTmpSize.Width())/aTmpSize.Height();
    double dRatioPreV=((double) nWidth ) / nHeight;

    if (dRatio>dRatioPreV)
    {
        rSize=Size(nWidth, (USHORT)(nWidth/dRatio));
        rPoint=Point( 0, (USHORT)((nHeight-rSize.Height())/2));
    }
    else
    {
        rSize=Size((USHORT)(nHeight*dRatio), nHeight);
        rPoint=Point((USHORT)((nWidth-rSize.Width())/2),0);
    }
}

void SdDocPreviewWin::ImpPaint( GDIMetaFile* pFile, OutputDevice* pVDev )
{
    Point aPoint;
    Size aSize = pVDev->GetOutputSize();
    Point bPoint(aSize.Width()-2*FRAME, aSize.Height()-2*FRAME );
    CalcSizeAndPos( pFile, aSize, aPoint );
    bPoint -= aPoint;
    aPoint += Point( FRAME, FRAME );

    pVDev->SetLineColor();
    pVDev->SetFillColor( Color( COL_LIGHTGRAY ) );
    pVDev->DrawRect(Rectangle( Point(0,0 ), pVDev->GetOutputSize()));
    if( pFile )
    {
        pVDev->SetFillColor( Color( COL_WHITE ) );
        pVDev->DrawRect(Rectangle(aPoint, aSize));
        pFile->WindStart();
        pFile->Play( pVDev, aPoint, aSize  );
    }
}

void SdDocPreviewWin::Paint( const Rectangle& rRect )
{
    ImpPaint( pMetaFile, (VirtualDevice*)this );
}

void SdDocPreviewWin::ShowEffect( presentation::FadeEffect eEffect, FadeSpeed eSpeed )
{
    if(bInEffect || !pMetaFile)
        return;

    bInEffect = TRUE;

    Point aPoint;
    Size aSize = GetOutputSize();
    Point bPoint( aSize.Width() - 2*FRAME, aSize.Height() - 2*FRAME );
    CalcSizeAndPos( pMetaFile, aSize, aPoint );
    bPoint -= aPoint;

    aPoint += Point( FRAME, FRAME );
    bPoint += Point( FRAME, FRAME );

    // Hintergrund Schwarz
    SetLineColor();
    SetFillColor( Color( COL_LIGHTGRAY ) );
    DrawRect(Rectangle( Point(0,0 ), GetOutputSize()));

    // korrigierte Seitengroesse, sonst kommt die letzte Pixelreihe(spalte)
    // nicht mit
    Size aPixelSize = PixelToLogic(Size(1,1));
    aSize.Width()   += aPixelSize.Width();
    aSize.Height() += aPixelSize.Height();

    // virtuelle Devices anlegen
    MapMode aMapMode = GetMapMode();
    aMapMode.SetOrigin(Point(0,0));

    VirtualDevice* pVDev = new VirtualDevice(*this);
    pVDev->SetMapMode(aMapMode);
    pVDev->SetOutputSize(aSize); // aCPageSize);

    if( pMetaFile )
    {
        pMetaFile->WindStart();
        pMetaFile->Play( pVDev, Point( 0,0 ), aSize  );
    }

    // ein Fader zum Ueberblenden
    Fader* pFader = new Fader(this);
    pFader->SetEffect( eEffect );
    pFader->SetSpeed( eSpeed );
    pFader->SetSource(Rectangle(Point(), aSize));
    pFader->SetTarget(Rectangle(aPoint, aSize));

    // virtuelle Devices an Fader uebergeben
    pFader->SetNewVirtualDevice(pVDev);

    // ueberblenden
    pFader->Fade();

    delete pFader;
    delete pVDev;

    bInEffect = FALSE;
}

long SdDocPreviewWin::Notify( NotifyEvent& rNEvt )
{
    if ( rNEvt.GetType() == EVENT_MOUSEBUTTONDOWN )
    {
        const MouseEvent* pMEvt = rNEvt.GetMouseEvent();
        if ( pMEvt->IsLeft() )
        {
            if( rNEvt.GetWindow() == this )
            {
                if(aClickHdl.IsSet())
                    aClickHdl.Call(this);
            }
        }
    }

    return Control::Notify( rNEvt );
}

<commit_msg>#101825# preview is now HC compiliant<commit_after>/*************************************************************************
 *
 *  $RCSfile: docprev.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: cl $ $Date: 2002-08-01 11:38: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): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SFX_OBJSH_HXX // SfxObjectShell
#include <sfx2/objsh.hxx>
#endif

#ifndef _SV_GDIMTF_HXX // GDIMetaFile
#include <vcl/gdimtf.hxx>
#endif

#ifndef _SV_VIRDEV_HXX // class VirtualDevice
#include <vcl/virdev.hxx>
#endif

#ifndef _COM_SUN_STAR_PRESENTATION_FADEEFFECT_HPP_
#include <com/sun/star/presentation/FadeEffect.hpp>
#endif

#ifndef _SD_FADEDEF_H // enum FadeSpeed
#include <fadedef.h>
#endif

#ifndef _SV_CTRL_HXX // class Control
#include <vcl/ctrl.hxx>
#endif

#ifndef _SD_FADER_HXX
#include "fader.hxx"
#endif

#include "docprev.hxx"
#include "drawdoc.hxx"
#include "docshell.hxx"
#include "viewshel.hxx"
#include "showview.hxx"

using namespace ::com::sun::star;

const int SdDocPreviewWin::FRAME = 4;

void SdDocPreviewWin::SetObjectShell( SfxObjectShell* pObj, USHORT nShowPage )
{

    SdDrawDocShell* pDocShell = PTR_CAST(SdDrawDocShell,pObj);
    SdDrawDocument* pDoc = pDocShell?pDocShell->GetDoc():NULL;
    if(pDoc)
    {
        const USHORT nPageCount = pDoc->GetSdPageCount(PK_STANDARD);
        USHORT nPgNum = 0;
        while( nPgNum < nPageCount )
        {
            pDoc->SetSelected( pDoc->GetSdPage( nPgNum, PK_STANDARD ), nPgNum == nShowPage );
            nPgNum++;
        }
    }

    GDIMetaFile* pFile = pObj ? pObj->GetPreviewMetaFile( ) : 0;
    delete pMetaFile;
    pMetaFile = pFile;
    m_pObj = pObj;
    Invalidate();
}

SdDocPreviewWin::SdDocPreviewWin( Window* pParent, const ResId& rResId )
: Control(pParent, rResId), pMetaFile( 0 ), bInEffect(FALSE), m_pObj(NULL)
{
    SetBorderStyle( WINDOW_BORDER_MONO );
}

SdDocPreviewWin::SdDocPreviewWin( Window* pParent )
: Control(pParent, 0 ), pMetaFile( 0 ), bInEffect(FALSE), m_pObj(NULL)
{
    SetBorderStyle( WINDOW_BORDER_MONO );
    Resize();
    Show();
}

void SdDocPreviewWin::Resize()
{
    Invalidate();
}

void SdDocPreviewWin::SetGDIFile( GDIMetaFile* pFile )
{
    delete pMetaFile;
    pMetaFile = pFile;
    Invalidate();
}

void SdDocPreviewWin::CalcSizeAndPos( GDIMetaFile* pFile, Size& rSize, Point& rPoint )
{
    Size aTmpSize = pFile ? pFile->GetPrefSize() : Size(1,1 );
    long nWidth = rSize.Width() - 2*FRAME;
    long nHeight = rSize.Height() - 2*FRAME;
    if( nWidth < 0 ) nWidth = 0;
    if( nHeight < 0 ) nHeight = 0;

    double dRatio=((double)aTmpSize.Width())/aTmpSize.Height();
    double dRatioPreV=((double) nWidth ) / nHeight;

    if (dRatio>dRatioPreV)
    {
        rSize=Size(nWidth, (USHORT)(nWidth/dRatio));
        rPoint=Point( 0, (USHORT)((nHeight-rSize.Height())/2));
    }
    else
    {
        rSize=Size((USHORT)(nHeight*dRatio), nHeight);
        rPoint=Point((USHORT)((nWidth-rSize.Width())/2),0);
    }
}

void SdDocPreviewWin::ImpPaint( GDIMetaFile* pFile, OutputDevice* pVDev )
{
    Point aPoint;
    Size aSize = pVDev->GetOutputSize();
    Point bPoint(aSize.Width()-2*FRAME, aSize.Height()-2*FRAME );
    CalcSizeAndPos( pFile, aSize, aPoint );
    bPoint -= aPoint;
    aPoint += Point( FRAME, FRAME );

    pVDev->SetLineColor();
    pVDev->SetFillColor( Color( COL_LIGHTGRAY ) );
    pVDev->DrawRect(Rectangle( Point(0,0 ), pVDev->GetOutputSize()));
    if( pFile )
    {
        pVDev->SetFillColor( Color( COL_WHITE ) );
        pVDev->DrawRect(Rectangle(aPoint, aSize));
        pFile->WindStart();
        pFile->Play( pVDev, aPoint, aSize  );
    }
}

void SdDocPreviewWin::Paint( const Rectangle& rRect )
{
    SvtAccessibilityOptions aAccOptions;
    bool bUseContrast = aAccOptions.GetIsForPagePreviews() && Application::GetSettings().GetStyleSettings().GetHighContrastMode();
    SetDrawMode( bUseContrast ? OUTPUT_DRAWMODE_CONTRAST : OUTPUT_DRAWMODE_COLOR );

    ImpPaint( pMetaFile, (VirtualDevice*)this );
}

void SdDocPreviewWin::ShowEffect( presentation::FadeEffect eEffect, FadeSpeed eSpeed )
{
    if(bInEffect || !pMetaFile)
        return;

    bInEffect = TRUE;

    Point aPoint;
    Size aSize = GetOutputSize();
    Point bPoint( aSize.Width() - 2*FRAME, aSize.Height() - 2*FRAME );
    CalcSizeAndPos( pMetaFile, aSize, aPoint );
    bPoint -= aPoint;

    aPoint += Point( FRAME, FRAME );
    bPoint += Point( FRAME, FRAME );

    // Hintergrund Schwarz
    SetLineColor();
    SetFillColor( Color( COL_LIGHTGRAY ) );
    DrawRect(Rectangle( Point(0,0 ), GetOutputSize()));

    // korrigierte Seitengroesse, sonst kommt die letzte Pixelreihe(spalte)
    // nicht mit
    Size aPixelSize = PixelToLogic(Size(1,1));
    aSize.Width()   += aPixelSize.Width();
    aSize.Height() += aPixelSize.Height();

    // virtuelle Devices anlegen
    MapMode aMapMode = GetMapMode();
    aMapMode.SetOrigin(Point(0,0));

    VirtualDevice* pVDev = new VirtualDevice(*this);
    pVDev->SetMapMode(aMapMode);
    pVDev->SetOutputSize(aSize); // aCPageSize);

    if( pMetaFile )
    {
        pMetaFile->WindStart();
        pMetaFile->Play( pVDev, Point( 0,0 ), aSize  );
    }

    // ein Fader zum Ueberblenden
    Fader* pFader = new Fader(this);
    pFader->SetEffect( eEffect );
    pFader->SetSpeed( eSpeed );
    pFader->SetSource(Rectangle(Point(), aSize));
    pFader->SetTarget(Rectangle(aPoint, aSize));

    // virtuelle Devices an Fader uebergeben
    pFader->SetNewVirtualDevice(pVDev);

    // ueberblenden
    pFader->Fade();

    delete pFader;
    delete pVDev;

    bInEffect = FALSE;
}

long SdDocPreviewWin::Notify( NotifyEvent& rNEvt )
{
    if ( rNEvt.GetType() == EVENT_MOUSEBUTTONDOWN )
    {
        const MouseEvent* pMEvt = rNEvt.GetMouseEvent();
        if ( pMEvt->IsLeft() )
        {
            if( rNEvt.GetWindow() == this )
            {
                if(aClickHdl.IsSet())
                    aClickHdl.Call(this);
            }
        }
    }

    return Control::Notify( rNEvt );
}

<|endoftext|>


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

#ifndef _SV_POLY_HXX //autogen
#include <vcl/poly.hxx>
#endif
#ifndef _SVDOPATH_HXX //autogen
#include <svx/svdograf.hxx>
#endif
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SVX_SVDOGRAF_HXX //autogen
#include <svx/svdograf.hxx>
#endif
#ifndef _SVX_SVDEDTV_HXX //autogen
#include <svx/svdedtv.hxx>
#endif

#pragma hdrstop

#include "sdview.hxx"
#include "viewshel.hxx"
#include "strings.hrc"
#include "sdresid.hxx"
#include "vectdlg.hxx"
#include "fuvect.hxx"

TYPEINIT1( FuVectorize, FuPoor );

/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/

FuVectorize::FuVectorize( SdViewShell* pViewSh, SdWindow* pWin, SdView* pView,
                          SdDrawDocument* pDoc, SfxRequest& rReq ) :
            FuPoor (pViewSh, pWin, pView, pDoc, rReq)
{
    const SdrMarkList& rMarkList = pView->GetMarkList();

    if( rMarkList.GetMarkCount() == 1 )
    {
        SdrObject* pObj = rMarkList.GetMark( 0 )->GetObj();

        if( pObj && pObj->ISA( SdrGrafObj ) )
        {
            SdVectorizeDlg aDlg( (Window*) pWin, ( (SdrGrafObj*) pObj )->GetGraphic().GetBitmap(), pDocSh );

            if( aDlg.Execute() == RET_OK )
            {
                const GDIMetaFile&  rMtf = aDlg.GetGDIMetaFile();
                SdrPageView*        pPageView = pView->GetPageViewPvNum( 0 );

                if( pPageView && rMtf.GetActionCount() )
                {
                    SdrGrafObj* pVectObj = (SdrGrafObj*) pObj->Clone();
                    String      aStr( pView->GetMarkDescription() );

                    aStr.Append( sal_Unicode(' ') );
                    aStr.Append( String( SdResId( STR_UNDO_VECTORIZE ) ) );
                    pView->BegUndo( aStr );
                    pVectObj->SetGraphic( rMtf );
                    pView->ReplaceObject( pObj, *pPageView, pVectObj );
                    pView->EndUndo();
                }
            }
        }
    }
}

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

#ifndef _TL_POLY_HXX
#include <tools/poly.hxx>
#endif
#ifndef _SVDOPATH_HXX //autogen
#include <svx/svdograf.hxx>
#endif
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SVX_SVDOGRAF_HXX //autogen
#include <svx/svdograf.hxx>
#endif
#ifndef _SVX_SVDEDTV_HXX //autogen
#include <svx/svdedtv.hxx>
#endif

#pragma hdrstop

#include "sdview.hxx"
#include "viewshel.hxx"
#include "strings.hrc"
#include "sdresid.hxx"
#include "vectdlg.hxx"
#include "fuvect.hxx"

TYPEINIT1( FuVectorize, FuPoor );

/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/

FuVectorize::FuVectorize( SdViewShell* pViewSh, SdWindow* pWin, SdView* pView,
                          SdDrawDocument* pDoc, SfxRequest& rReq ) :
            FuPoor (pViewSh, pWin, pView, pDoc, rReq)
{
    const SdrMarkList& rMarkList = pView->GetMarkList();

    if( rMarkList.GetMarkCount() == 1 )
    {
        SdrObject* pObj = rMarkList.GetMark( 0 )->GetObj();

        if( pObj && pObj->ISA( SdrGrafObj ) )
        {
            SdVectorizeDlg aDlg( (Window*) pWin, ( (SdrGrafObj*) pObj )->GetGraphic().GetBitmap(), pDocSh );

            if( aDlg.Execute() == RET_OK )
            {
                const GDIMetaFile&  rMtf = aDlg.GetGDIMetaFile();
                SdrPageView*        pPageView = pView->GetPageViewPvNum( 0 );

                if( pPageView && rMtf.GetActionCount() )
                {
                    SdrGrafObj* pVectObj = (SdrGrafObj*) pObj->Clone();
                    String      aStr( pView->GetMarkDescription() );

                    aStr.Append( sal_Unicode(' ') );
                    aStr.Append( String( SdResId( STR_UNDO_VECTORIZE ) ) );
                    pView->BegUndo( aStr );
                    pVectObj->SetGraphic( rMtf );
                    pView->ReplaceObject( pObj, *pPageView, pVectObj );
                    pView->EndUndo();
                }
            }
        }
    }
}

<|endoftext|>


<commit_before>#include <iostream>
#include <algorithm>
#include <random>

#include <simulated_annealing.hpp>

struct City{
    float x;
    float y;
};

float distance(const City& c1, const City& c2)
{
    return std::hypot(c2.x - c1.x, c2.y - c1.y);
}

using Trajectory = std::vector<City>;

std::ostream& operator<<(std::ostream& o, const Trajectory& t)
{
    for (auto& c : t)
        o << "[" << c.x << ", " << c.y << "], ";

    return o;
}

struct Generator{
    Trajectory operator()(const Trajectory& t, const SimulatedAnnealing& sa) const
    {
        Trajectory t2 = t;

        std::shuffle(begin(t2), end(t2), std::default_random_engine{});

        return t2;
    }
};

struct Energy{
    float operator()(const Trajectory& t) const
    {
        std::vector<float> distances;

        for (int i = 1; i < t.size(); ++i)
            distances.push_back(distance(t[i-1], t[i]));

        return std::accumulate(begin(distances), end(distances), 0.0);
    }
};

int main()
{
    Energy energy;
    Generator generator;

    City c0 { 200.0,  800.0};
    City c1 {3600.0, 2300.0};
    City c2 {3100.0, 3300.0};
    City c3 {4700.0, 5750.0};
    City c4 {5400.0, 5750.0};
    City c5 {5608.0, 7103.0};
    City c6 {4493.0, 7102.0};
    City c7 {3600.0, 6950.0};
    Trajectory trajectory{c0, c1, c2, c3, c4, c5, c6, c7};

    std::cout << "Optimal trajectory: " << trajectory << std::endl;
    std::cout << "Optimal distance: " << energy(trajectory) << std::endl;

    SimulatedAnnealing sim(1e3, // start temp
                           1e-1, // stop temp
                           int(1e4), // max it
                           energy(trajectory)); // energy min

    std::shuffle(begin(trajectory), end(trajectory), std::default_random_engine{});

    std::cout << "Initial trajectory: " << trajectory << std::endl;

    sim(energy, trajectory, generator);

    std::cout << "Final trajectory: " << trajectory << std::endl;

    return 0;
}
<commit_msg>[traveling_salesman] fixed warning<commit_after>#include <iostream>
#include <algorithm>
#include <random>

#include <simulated_annealing.hpp>

struct City{
    float x;
    float y;
};

float distance(const City& c1, const City& c2)
{
    return std::hypot(c2.x - c1.x, c2.y - c1.y);
}

using Trajectory = std::vector<City>;

std::ostream& operator<<(std::ostream& o, const Trajectory& t)
{
    for (auto& c : t)
        o << "[" << c.x << ", " << c.y << "], ";

    return o;
}

struct Generator{
    Trajectory operator()(const Trajectory& t, const SimulatedAnnealing& sa) const
    {
        Trajectory t2 = t;

        std::shuffle(begin(t2), end(t2), std::default_random_engine{});

        return t2;
    }
};

struct Energy{
    float operator()(const Trajectory& t) const
    {
        std::vector<float> distances;

        for (size_t i = 1; i < t.size(); ++i)
            distances.push_back(distance(t[i - 1], t[i]));

        return std::accumulate(begin(distances), end(distances), 0.0);
    }
};

int main()
{
    Energy energy;
    Generator generator;

    City c0 { 200.0,  800.0};
    City c1 {3600.0, 2300.0};
    City c2 {3100.0, 3300.0};
    City c3 {4700.0, 5750.0};
    City c4 {5400.0, 5750.0};
    City c5 {5608.0, 7103.0};
    City c6 {4493.0, 7102.0};
    City c7 {3600.0, 6950.0};
    Trajectory trajectory{c0, c1, c2, c3, c4, c5, c6, c7};

    std::cout << "Optimal trajectory: " << trajectory << std::endl;
    std::cout << "Optimal distance: " << energy(trajectory) << std::endl;

    SimulatedAnnealing sim(1e3, // start temp
                           1e-1, // stop temp
                           int(1e4), // max it
                           energy(trajectory)); // energy min

    std::shuffle(begin(trajectory), end(trajectory), std::default_random_engine{});

    std::cout << "Initial trajectory: " << trajectory << std::endl;

    sim(energy, trajectory, generator);

    std::cout << "Final trajectory: " << trajectory << std::endl;

    return 0;
}
<|endoftext|>


<commit_before>/*
    Dynamics/Kinematics modeling and simulation library.
    Copyright (C) 1999 by Michael Alexander Ewert

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

*/

#include "csphyzik/math3d.h"
#include "csphyzik/refframe.h"
#include "csphyzik/rigidbod.h"
#include "csphyzik/debug.h"
#include "csphyzik/contact.h"

ctRigidBody::ctRigidBody()
{
}

ctRigidBody::ctRigidBody( ctReferenceFrame &ref ) : ctDynamicEntity( ref )
{

}

ctRigidBody::~ctRigidBody()
{

}

ctRigidBody *ctRigidBody::new_ctRigidBody()
{
ctReferenceFrame *rf = new ctReferenceFrame();
	return new ctRigidBody( *rf );

}
ctRigidBody *ctRigidBody::new_ctRigidBody( coord x, coord y, coord z )
{
ctReferenceFrame *rf = new ctReferenceFrame();
//!me set coords
	return new ctRigidBody( *rf );

}

// w is actually a secondary value that is calculated from L
// so need to calc L to set w
void ctRigidBody::set_angular_v( const ctVector3 &pw )
{
	ctMatrix3 I_inv_world = get_I_inv_world();

	// angular speed =
	// inverse of inertia tensor in world coords * angular momentum
	w = pw;
	L = I_inv_world.get_transpose() * w;
}

// v is a secondary value that is calculated from momentum
void ctRigidBody::set_v( const ctVector3 &pv )
{
  v = pv;
  P = v*m;
}

int ctRigidBody::set_state( real *state_array )
{
int len;

	len = ctPhysicalEntity::set_state( state_array );
	state_array += len;

	*state_array++ = P[0];
	*state_array++ = P[1];
	*state_array++ = P[2];

	*state_array++ = L[0];
	*state_array++ = L[1];
	*state_array++ = L[2];

	return ctRigidBody::get_state_size();
}

int ctRigidBody::set_delta_state( real *state_array )
{
int len;

	len = ctPhysicalEntity::set_delta_state( state_array );
	state_array += len;

	// dP/dt = F     derivitive of momentum with time = applied force
	*state_array++ = F[0];
	*state_array++ = F[1];
	*state_array++ = F[2];

	// dL/dt = T     derivitive of angular momentum with time = applied torque
	*state_array++ = T[0];
	*state_array++ = T[1];
	*state_array++ = T[2];

	return ctRigidBody::get_state_size();

}

int ctRigidBody::get_state( const real *state_array )
{
int len;
	len = ctPhysicalEntity::get_state( state_array );
	state_array += len;

	// momentum
	P[0] = *state_array++;
	P[1] = *state_array++;
	P[2] = *state_array++;

	// angular momentum
	L[0] = *state_array++;
	L[1] = *state_array++;
	L[2] = *state_array++;

	// calc velocity from eqn:  p = mv    momentum = mass * velocity
	if( m >= MIN_REAL ){
		v = P/m;
	}

	// calculate inverse of inertia tensor in world coords
	// this result is used to calculate angular speed w
	ctMatrix3 I_inv_world = get_I_inv_world();

	// angular speed =
	// inverse of inertia tensor in world coords * angular momentum
	w = I_inv_world * L;

	return ctRigidBody::get_state_size();
}

// calc I for a block of given dimensions
void ctRigidBody::calc_simple_I_tensor( real x, real y, real z )
{
real k;

	if( m > MIN_REAL ){
		k = m/12.0;
	}else{
		k = MIN_REAL;
	}
	for( int i = 0; i < 3; i++ )
		for( int j = 0; j < 3; j++ )
			I[i][j] = 0.0;

	I[0][0] = (y*y + z*z)*k;
	I[1][1] = (x*x + z*z)*k;
	I[2][2] = (x*x + y*y)*k;

	I_inv[0][0] = ( y > MIN_REAL || z > MIN_REAL ) ? 1.0/I[0][0] : MAX_REAL;
	I_inv[1][1] = ( x > MIN_REAL || z > MIN_REAL ) ? 1.0/I[1][1] : MAX_REAL;
	I_inv[2][2] = ( x > MIN_REAL || y > MIN_REAL ) ? 1.0/I[2][2] : MAX_REAL;
}

void ctRigidBody::set_m( real pm )
{
	if( pm > MIN_REAL ){
		I *= ( pm/m );
		I_inv *= ( m/pm );
		m = pm;
	}
}

// collision response
void ctRigidBody::resolve_collision( ctCollidingContact *cont )
{
ctVector3 j;
real v_rel;       // relative velocity of collision points
ctVector3 ra_v, rb_v;
real j_magnitude;
real bottom;
real ma_inv, mb_inv;   // 1/mass_body
real rota, rotb;       // contribution from rotational inertia
ctVector3 & n = cont->n;
ctVector3 ra, rb;      // center of body to collision point in inertail ref frame
// keep track of previous object collided with.
// in simultaneous collisions with the same object the restituion should
// only be factored in once.  So all subsequent collisions are handled as
// seperate collisions, but with a restitution of 1.0
// if they are different objects then treat them as multiple collisions with
// normal restitution.
//!me this isn't actually a very good method.... maybe something better can be
//!me implemented once contact force solver is implemented
ctPhysicalEntity *prev;

//!debug
//int hit_cout = 0;

  // since NULL is used for an immovable object we need a
  // different "nothing" pointer
  prev = this;

  while( cont != NULL ){

    ctVector3 body_x = get_pos();
    ra = cont->contact_p - body_x;

    ra_v = get_angular_v()%ra + get_v();

    if( cont->body_b == NULL ){
      v_rel = n*ra_v;
    }else{
      //rb = (cont->body_b->get_this_to_world())*cont->p_b;
      rb = cont->contact_p - cont->body_b->get_pos();
      rb_v = cont->body_b->get_angular_v()%rb + cont->body_b->get_v();
      v_rel = n*(ra_v - rb_v);
    }

    // if the objects are traveling towards each other do collision response
    if( v_rel < 0 ){

 //         DEBUGLOGF2( "contact %lf o %lf, ", cont->contact_p[0], body_x[0] );
 //   DEBUGLOGF2( "contact %lf o %lf, ", cont->contact_p[1], body_x[1] );
 //   DEBUGLOGF2( "contact %lf o %lf\n ", cont->contact_p[2], body_x[2] );

      ma_inv = 1.0/get_impulse_m();
      rota = n * ((get_impulse_I_inv()*( ra%n ) )%ra);

      if( cont->body_b == NULL ){
        // hit some kind of immovable object
        mb_inv = 0;
        rotb = 0;
      }else{
        mb_inv = 1.0/cont->body_b->get_impulse_m();
        rotb = n * ((cont->body_b->get_impulse_I_inv()*( rb%n ) )%rb);
      }

      // bottom part of equation
      bottom = ma_inv + mb_inv + rota + rotb;

      if( prev != cont->body_b ){
        j_magnitude = -(1.0 + cont->restitution ) * v_rel / bottom;
      }else{
        // if we are dealing with a simulatneous collisin with with
        // same object.
        j_magnitude = -(1.0 + 1.0 ) * v_rel / bottom;
      }

      j = n*j_magnitude;
      apply_impulse( ra, j );

      if( cont->body_b != NULL ){
        cont->body_b->apply_impulse( rb, j*(-1.0) );
      }

      // treat next simultaneous collision as a seperate collision.
      prev = cont->body_b;

  //    DEBUGLOGF( "respond %d\n", ++hit_cout );
    }
    cont = cont->next;
  }
}

void ctRigidBody::apply_impulse( ctVector3 jx, ctVector3 jv )
{
real mass = get_impulse_m();

  P += jv;
  v = P * (( mass > MIN_REAL ) ? 1.0/mass : MAX_REAL);

  L += jx % jv;

	ctMatrix3 I_inv_world = get_I_inv_world();
  w = I_inv_world * L;

}<commit_msg>Converted tabs to spaces.  I'm also testing CVS.<commit_after>/*
    Dynamics/Kinematics modeling and simulation library.
    Copyright (C) 1999 by Michael Alexander Ewert

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

*/

#include "csphyzik/math3d.h"
#include "csphyzik/refframe.h"
#include "csphyzik/rigidbod.h"
#include "csphyzik/debug.h"
#include "csphyzik/contact.h"

ctRigidBody::ctRigidBody()
{
}

ctRigidBody::ctRigidBody( ctReferenceFrame &ref ) : ctDynamicEntity( ref )
{

}

ctRigidBody::~ctRigidBody()
{

}

ctRigidBody *ctRigidBody::new_ctRigidBody()
{
ctReferenceFrame *rf = new ctReferenceFrame();
  return new ctRigidBody( *rf );

}
ctRigidBody *ctRigidBody::new_ctRigidBody( coord x, coord y, coord z )
{
ctReferenceFrame *rf = new ctReferenceFrame();
//!me set coords
  return new ctRigidBody( *rf );

}

// w is actually a secondary value that is calculated from L
// so need to calc L to set w
void ctRigidBody::set_angular_v( const ctVector3 &pw )
{
  ctMatrix3 I_inv_world = get_I_inv_world();

  // angular speed =
  // inverse of inertia tensor in world coords * angular momentum
  w = pw;
  L = I_inv_world.get_transpose() * w;
}

// v is a secondary value that is calculated from momentum
void ctRigidBody::set_v( const ctVector3 &pv )
{
  v = pv;
  P = v*m;
}

int ctRigidBody::set_state( real *state_array )
{
int len;

  len = ctPhysicalEntity::set_state( state_array );
  state_array += len;

  *state_array++ = P[0];
  *state_array++ = P[1];
  *state_array++ = P[2];

  *state_array++ = L[0];
  *state_array++ = L[1];
  *state_array++ = L[2];

  return ctRigidBody::get_state_size();
}

int ctRigidBody::set_delta_state( real *state_array )
{
int len;

  len = ctPhysicalEntity::set_delta_state( state_array );
  state_array += len;

  // dP/dt = F     derivitive of momentum with time = applied force
  *state_array++ = F[0];
  *state_array++ = F[1];
  *state_array++ = F[2];

  // dL/dt = T     derivitive of angular momentum with time = applied torque
  *state_array++ = T[0];
  *state_array++ = T[1];
  *state_array++ = T[2];

  return ctRigidBody::get_state_size();

}

int ctRigidBody::get_state( const real *state_array )
{
int len;
  len = ctPhysicalEntity::get_state( state_array );
  state_array += len;

  // momentum
  P[0] = *state_array++;
  P[1] = *state_array++;
  P[2] = *state_array++;

  // angular momentum
  L[0] = *state_array++;
  L[1] = *state_array++;
  L[2] = *state_array++;

  // calc velocity from eqn:  p = mv    momentum = mass * velocity
  if( m >= MIN_REAL ){
    v = P/m;
  }

  // calculate inverse of inertia tensor in world coords
  // this result is used to calculate angular speed w
  ctMatrix3 I_inv_world = get_I_inv_world();

  // angular speed =
  // inverse of inertia tensor in world coords * angular momentum
  w = I_inv_world * L;

  return ctRigidBody::get_state_size();
}

// calc I for a block of given dimensions
void ctRigidBody::calc_simple_I_tensor( real x, real y, real z )
{
real k;

  if( m > MIN_REAL ){
    k = m/12.0;
  }else{
    k = MIN_REAL;
  }
  for( int i = 0; i < 3; i++ )
    for( int j = 0; j < 3; j++ )
      I[i][j] = 0.0;

  I[0][0] = (y*y + z*z)*k;
  I[1][1] = (x*x + z*z)*k;
  I[2][2] = (x*x + y*y)*k;

  I_inv[0][0] = ( y > MIN_REAL || z > MIN_REAL ) ? 1.0/I[0][0] : MAX_REAL;
  I_inv[1][1] = ( x > MIN_REAL || z > MIN_REAL ) ? 1.0/I[1][1] : MAX_REAL;
  I_inv[2][2] = ( x > MIN_REAL || y > MIN_REAL ) ? 1.0/I[2][2] : MAX_REAL;
}

void ctRigidBody::set_m( real pm )
{
  if( pm > MIN_REAL ){
    I *= ( pm/m );
    I_inv *= ( m/pm );
    m = pm;
  }
}

// collision response
void ctRigidBody::resolve_collision( ctCollidingContact *cont )
{
ctVector3 j;
real v_rel;       // relative velocity of collision points
ctVector3 ra_v, rb_v;
real j_magnitude;
real bottom;
real ma_inv, mb_inv;   // 1/mass_body
real rota, rotb;       // contribution from rotational inertia
ctVector3 & n = cont->n;
ctVector3 ra, rb;      // center of body to collision point in inertail ref frame
// keep track of previous object collided with.
// in simultaneous collisions with the same object the restituion should
// only be factored in once.  So all subsequent collisions are handled as
// seperate collisions, but with a restitution of 1.0
// if they are different objects then treat them as multiple collisions with
// normal restitution.
//!me this isn't actually a very good method.... maybe something better can be
//!me implemented once contact force solver is implemented
ctPhysicalEntity *prev;

//!debug
//int hit_cout = 0;

  // since NULL is used for an immovable object we need a
  // different "nothing" pointer
  prev = this;

  while( cont != NULL ){

    ctVector3 body_x = get_pos();
    ra = cont->contact_p - body_x;

    ra_v = get_angular_v()%ra + get_v();

    if( cont->body_b == NULL ){
      v_rel = n*ra_v;
    }else{
      //rb = (cont->body_b->get_this_to_world())*cont->p_b;
      rb = cont->contact_p - cont->body_b->get_pos();
      rb_v = cont->body_b->get_angular_v()%rb + cont->body_b->get_v();
      v_rel = n*(ra_v - rb_v);
    }

    // if the objects are traveling towards each other do collision response
    if( v_rel < 0 ){

 //         DEBUGLOGF2( "contact %lf o %lf, ", cont->contact_p[0], body_x[0] );
 //   DEBUGLOGF2( "contact %lf o %lf, ", cont->contact_p[1], body_x[1] );
 //   DEBUGLOGF2( "contact %lf o %lf\n ", cont->contact_p[2], body_x[2] );

      ma_inv = 1.0/get_impulse_m();
      rota = n * ((get_impulse_I_inv()*( ra%n ) )%ra);

      if( cont->body_b == NULL ){
        // hit some kind of immovable object
        mb_inv = 0;
        rotb = 0;
      }else{
        mb_inv = 1.0/cont->body_b->get_impulse_m();
        rotb = n * ((cont->body_b->get_impulse_I_inv()*( rb%n ) )%rb);
      }

      // bottom part of equation
      bottom = ma_inv + mb_inv + rota + rotb;

      if( prev != cont->body_b ){
        j_magnitude = -(1.0 + cont->restitution ) * v_rel / bottom;
      }else{
        // if we are dealing with a simulatneous collisin with with
        // same object.
        j_magnitude = -(1.0 + 1.0 ) * v_rel / bottom;
      }

      j = n*j_magnitude;
      apply_impulse( ra, j );

      if( cont->body_b != NULL ){
        cont->body_b->apply_impulse( rb, j*(-1.0) );
      }

      // treat next simultaneous collision as a seperate collision.
      prev = cont->body_b;

  //    DEBUGLOGF( "respond %d\n", ++hit_cout );
    }
    cont = cont->next;
  }
}

void ctRigidBody::apply_impulse( ctVector3 jx, ctVector3 jv )
{
real mass = get_impulse_m();

  P += jv;
  v = P * (( mass > MIN_REAL ) ? 1.0/mass : MAX_REAL);

  L += jx % jv;

  ctMatrix3 I_inv_world = get_I_inv_world();
  w = I_inv_world * L;

}<|endoftext|>


<commit_before>//
// Copyright (c) 2018, University of Edinburgh
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//  * Redistributions of source code must retain the above copyright notice,
//    this list of conditions and the following disclaimer.
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
//  * Neither the name of  nor the names of its contributors may be used to
//    endorse or promote products derived from this software without specific
//    prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//

#include <exotica_core/problems/bounded_end_pose_problem.h>
#include <exotica_core/setup.h>

#include <exotica_core/task_initializer.h>

REGISTER_PROBLEM_TYPE("BoundedEndPoseProblem", exotica::BoundedEndPoseProblem)

namespace exotica
{
BoundedEndPoseProblem::BoundedEndPoseProblem()
{
    flags_ = KIN_FK | KIN_J;
}

BoundedEndPoseProblem::~BoundedEndPoseProblem() = default;

Eigen::MatrixXd BoundedEndPoseProblem::GetBounds() const
{
    return scene_->GetKinematicTree().GetJointLimits();
}

void BoundedEndPoseProblem::Instantiate(const BoundedEndPoseProblemInitializer& init)
{
    num_tasks = tasks_.size();
    length_Phi = 0;
    length_jacobian = 0;
    for (int i = 0; i < num_tasks; ++i)
    {
        AppendVector(Phi.map, tasks_[i]->GetLieGroupIndices());
        length_Phi += tasks_[i]->length;
        length_jacobian += tasks_[i]->length_jacobian;
    }
    Phi.SetZero(length_Phi);
    W = Eigen::MatrixXd::Identity(N, N);
    if (init.W.rows() > 0)
    {
        if (init.W.rows() == N)
        {
            W.diagonal() = init.W;
        }
        else
        {
            ThrowNamed("W dimension mismatch! Expected " << N << ", got " << init.W.rows());
        }
    }
    if (flags_ & KIN_J) jacobian = Eigen::MatrixXd(length_jacobian, N);
    if (flags_ & KIN_J_DOT) hessian.setConstant(length_jacobian, Eigen::MatrixXd::Zero(N, N));

    if (init.LowerBound.rows() == N)
    {
        scene_->GetKinematicTree().SetJointLimitsLower(init.LowerBound);
    }
    else if (init.LowerBound.rows() != 0)
    {
        ThrowNamed("Lower bound size incorrect! Expected " << N << " got " << init.LowerBound.rows());
    }
    if (init.UpperBound.rows() == N)
    {
        scene_->GetKinematicTree().SetJointLimitsUpper(init.UpperBound);
    }
    else if (init.UpperBound.rows() != 0)
    {
        ThrowNamed("Lower bound size incorrect! Expected " << N << " got " << init.UpperBound.rows());
    }

    TaskSpaceVector dummy;
    cost.Initialize(init.Cost, shared_from_this(), dummy);
    ApplyStartState(false);
    PreUpdate();
}

void BoundedEndPoseProblem::PreUpdate()
{
    PlanningProblem::PreUpdate();
    for (int i = 0; i < tasks_.size(); ++i) tasks_[i]->is_used = false;
    cost.UpdateS();
}

double BoundedEndPoseProblem::GetScalarCost() const
{
    return cost.ydiff.transpose() * cost.S * cost.ydiff;
}

Eigen::RowVectorXd BoundedEndPoseProblem::GetScalarJacobian() const
{
    return cost.jacobian.transpose() * cost.S * cost.ydiff * 2.0;
}

double BoundedEndPoseProblem::GetScalarTaskCost(const std::string& task_name) const
{
    for (int i = 0; i < cost.indexing.size(); ++i)
    {
        if (cost.tasks[i]->GetObjectName() == task_name)
        {
            return cost.ydiff.segment(cost.indexing[i].start, cost.indexing[i].length).transpose() * cost.rho(cost.indexing[i].id) * cost.ydiff.segment(cost.indexing[i].start, cost.indexing[i].length);
        }
    }
    ThrowPretty("Cannot get scalar task cost. Task map '" << task_name << "' does not exist.");
}

void BoundedEndPoseProblem::Update(Eigen::VectorXdRefConst x)
{
    scene_->Update(x, t_start);
    Phi.SetZero(length_Phi);
    if (flags_ & KIN_J) jacobian.setZero();
    if (flags_ & KIN_J_DOT)
        for (int i = 0; i < length_jacobian; ++i) hessian(i).setZero();
    for (int i = 0; i < tasks_.size(); ++i)
    {
        if (tasks_[i]->is_used)
        {
            if (flags_ & KIN_J_DOT)
            {
                tasks_[i]->Update(x, Phi.data.segment(tasks_[i]->start, tasks_[i]->length), jacobian.middleRows(tasks_[i]->start_jacobian, tasks_[i]->length_jacobian), hessian.segment(tasks_[i]->start, tasks_[i]->length));
            }
            else if (flags_ & KIN_J)
            {
                tasks_[i]->Update(x, Phi.data.segment(tasks_[i]->start, tasks_[i]->length), jacobian.middleRows(tasks_[i]->start_jacobian, tasks_[i]->length_jacobian));
            }
            else
            {
                tasks_[i]->Update(x, Phi.data.segment(tasks_[i]->start, tasks_[i]->length));
            }
        }
    }
    if (flags_ & KIN_J_DOT)
    {
        cost.Update(Phi, jacobian, hessian);
    }
    else if (flags_ & KIN_J)
    {
        cost.Update(Phi, jacobian);
    }
    else
    {
        cost.Update(Phi);
    }
    ++number_of_problem_updates_;
}

void BoundedEndPoseProblem::SetGoal(const std::string& task_name, Eigen::VectorXdRefConst goal)
{
    for (int i = 0; i < cost.indexing.size(); ++i)
    {
        if (cost.tasks[i]->GetObjectName() == task_name)
        {
            if (goal.rows() != cost.indexing[i].length) ThrowPretty("Expected length of " << cost.indexing[i].length << " and got " << goal.rows());
            cost.y.data.segment(cost.indexing[i].start, cost.indexing[i].length) = goal;
            return;
        }
    }
    ThrowPretty("Cannot set Goal. Task map '" << task_name << "' does not exist.");
}

void BoundedEndPoseProblem::SetRho(const std::string& task_name, const double& rho)
{
    for (int i = 0; i < cost.indexing.size(); ++i)
    {
        if (cost.tasks[i]->GetObjectName() == task_name)
        {
            cost.rho(cost.indexing[i].id) = rho;
            PreUpdate();
            return;
        }
    }
    ThrowPretty("Cannot set rho. Task map '" << task_name << "' does not exist.");
}

Eigen::VectorXd BoundedEndPoseProblem::GetGoal(const std::string& task_name)
{
    for (int i = 0; i < cost.indexing.size(); ++i)
    {
        if (cost.tasks[i]->GetObjectName() == task_name)
        {
            return cost.y.data.segment(cost.indexing[i].start, cost.indexing[i].length);
        }
    }
    ThrowPretty("Cannot get Goal. Task map '" << task_name << "' does not exist.");
}

double BoundedEndPoseProblem::GetRho(const std::string& task_name)
{
    for (int i = 0; i < cost.indexing.size(); ++i)
    {
        if (cost.tasks[i]->GetObjectName() == task_name)
        {
            return cost.rho(cost.indexing[i].id);
        }
    }
    ThrowPretty("Cannot get rho. Task map '" << task_name << "' does not exist.");
}

bool BoundedEndPoseProblem::IsValid()
{
    Eigen::VectorXd x = scene_->GetKinematicTree().GetControlledState();
    Eigen::MatrixXd bounds = scene_->GetKinematicTree().GetJointLimits();
    for (unsigned int i = 0; i < N; ++i)
    {
        if (x(i) < bounds(i, 0) || x(i) > bounds(i, 1)) return false;
    }
    return true;
}
}
<commit_msg>[exotica_core] BoundedEndPoseProblem: Fix IsValid<commit_after>//
// Copyright (c) 2018, University of Edinburgh
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//  * Redistributions of source code must retain the above copyright notice,
//    this list of conditions and the following disclaimer.
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
//  * Neither the name of  nor the names of its contributors may be used to
//    endorse or promote products derived from this software without specific
//    prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//

#include <exotica_core/problems/bounded_end_pose_problem.h>
#include <exotica_core/setup.h>

#include <exotica_core/task_initializer.h>

REGISTER_PROBLEM_TYPE("BoundedEndPoseProblem", exotica::BoundedEndPoseProblem)

namespace exotica
{
BoundedEndPoseProblem::BoundedEndPoseProblem()
{
    flags_ = KIN_FK | KIN_J;
}

BoundedEndPoseProblem::~BoundedEndPoseProblem() = default;

Eigen::MatrixXd BoundedEndPoseProblem::GetBounds() const
{
    return scene_->GetKinematicTree().GetJointLimits();
}

void BoundedEndPoseProblem::Instantiate(const BoundedEndPoseProblemInitializer& init)
{
    num_tasks = tasks_.size();
    length_Phi = 0;
    length_jacobian = 0;
    for (int i = 0; i < num_tasks; ++i)
    {
        AppendVector(Phi.map, tasks_[i]->GetLieGroupIndices());
        length_Phi += tasks_[i]->length;
        length_jacobian += tasks_[i]->length_jacobian;
    }
    Phi.SetZero(length_Phi);
    W = Eigen::MatrixXd::Identity(N, N);
    if (init.W.rows() > 0)
    {
        if (init.W.rows() == N)
        {
            W.diagonal() = init.W;
        }
        else
        {
            ThrowNamed("W dimension mismatch! Expected " << N << ", got " << init.W.rows());
        }
    }
    if (flags_ & KIN_J) jacobian = Eigen::MatrixXd(length_jacobian, N);
    if (flags_ & KIN_J_DOT) hessian.setConstant(length_jacobian, Eigen::MatrixXd::Zero(N, N));

    if (init.LowerBound.rows() == N)
    {
        scene_->GetKinematicTree().SetJointLimitsLower(init.LowerBound);
    }
    else if (init.LowerBound.rows() != 0)
    {
        ThrowNamed("Lower bound size incorrect! Expected " << N << " got " << init.LowerBound.rows());
    }
    if (init.UpperBound.rows() == N)
    {
        scene_->GetKinematicTree().SetJointLimitsUpper(init.UpperBound);
    }
    else if (init.UpperBound.rows() != 0)
    {
        ThrowNamed("Lower bound size incorrect! Expected " << N << " got " << init.UpperBound.rows());
    }

    TaskSpaceVector dummy;
    cost.Initialize(init.Cost, shared_from_this(), dummy);
    ApplyStartState(false);
    PreUpdate();
}

void BoundedEndPoseProblem::PreUpdate()
{
    PlanningProblem::PreUpdate();
    for (int i = 0; i < tasks_.size(); ++i) tasks_[i]->is_used = false;
    cost.UpdateS();
}

double BoundedEndPoseProblem::GetScalarCost() const
{
    return cost.ydiff.transpose() * cost.S * cost.ydiff;
}

Eigen::RowVectorXd BoundedEndPoseProblem::GetScalarJacobian() const
{
    return cost.jacobian.transpose() * cost.S * cost.ydiff * 2.0;
}

double BoundedEndPoseProblem::GetScalarTaskCost(const std::string& task_name) const
{
    for (int i = 0; i < cost.indexing.size(); ++i)
    {
        if (cost.tasks[i]->GetObjectName() == task_name)
        {
            return cost.ydiff.segment(cost.indexing[i].start, cost.indexing[i].length).transpose() * cost.rho(cost.indexing[i].id) * cost.ydiff.segment(cost.indexing[i].start, cost.indexing[i].length);
        }
    }
    ThrowPretty("Cannot get scalar task cost. Task map '" << task_name << "' does not exist.");
}

void BoundedEndPoseProblem::Update(Eigen::VectorXdRefConst x)
{
    scene_->Update(x, t_start);
    Phi.SetZero(length_Phi);
    if (flags_ & KIN_J) jacobian.setZero();
    if (flags_ & KIN_J_DOT)
        for (int i = 0; i < length_jacobian; ++i) hessian(i).setZero();
    for (int i = 0; i < tasks_.size(); ++i)
    {
        if (tasks_[i]->is_used)
        {
            if (flags_ & KIN_J_DOT)
            {
                tasks_[i]->Update(x, Phi.data.segment(tasks_[i]->start, tasks_[i]->length), jacobian.middleRows(tasks_[i]->start_jacobian, tasks_[i]->length_jacobian), hessian.segment(tasks_[i]->start, tasks_[i]->length));
            }
            else if (flags_ & KIN_J)
            {
                tasks_[i]->Update(x, Phi.data.segment(tasks_[i]->start, tasks_[i]->length), jacobian.middleRows(tasks_[i]->start_jacobian, tasks_[i]->length_jacobian));
            }
            else
            {
                tasks_[i]->Update(x, Phi.data.segment(tasks_[i]->start, tasks_[i]->length));
            }
        }
    }
    if (flags_ & KIN_J_DOT)
    {
        cost.Update(Phi, jacobian, hessian);
    }
    else if (flags_ & KIN_J)
    {
        cost.Update(Phi, jacobian);
    }
    else
    {
        cost.Update(Phi);
    }
    ++number_of_problem_updates_;
}

void BoundedEndPoseProblem::SetGoal(const std::string& task_name, Eigen::VectorXdRefConst goal)
{
    for (int i = 0; i < cost.indexing.size(); ++i)
    {
        if (cost.tasks[i]->GetObjectName() == task_name)
        {
            if (goal.rows() != cost.indexing[i].length) ThrowPretty("Expected length of " << cost.indexing[i].length << " and got " << goal.rows());
            cost.y.data.segment(cost.indexing[i].start, cost.indexing[i].length) = goal;
            return;
        }
    }
    ThrowPretty("Cannot set Goal. Task map '" << task_name << "' does not exist.");
}

void BoundedEndPoseProblem::SetRho(const std::string& task_name, const double& rho)
{
    for (int i = 0; i < cost.indexing.size(); ++i)
    {
        if (cost.tasks[i]->GetObjectName() == task_name)
        {
            cost.rho(cost.indexing[i].id) = rho;
            PreUpdate();
            return;
        }
    }
    ThrowPretty("Cannot set rho. Task map '" << task_name << "' does not exist.");
}

Eigen::VectorXd BoundedEndPoseProblem::GetGoal(const std::string& task_name)
{
    for (int i = 0; i < cost.indexing.size(); ++i)
    {
        if (cost.tasks[i]->GetObjectName() == task_name)
        {
            return cost.y.data.segment(cost.indexing[i].start, cost.indexing[i].length);
        }
    }
    ThrowPretty("Cannot get Goal. Task map '" << task_name << "' does not exist.");
}

double BoundedEndPoseProblem::GetRho(const std::string& task_name)
{
    for (int i = 0; i < cost.indexing.size(); ++i)
    {
        if (cost.tasks[i]->GetObjectName() == task_name)
        {
            return cost.rho(cost.indexing[i].id);
        }
    }
    ThrowPretty("Cannot get rho. Task map '" << task_name << "' does not exist.");
}

bool BoundedEndPoseProblem::IsValid()
{
    Eigen::VectorXd x = scene_->GetKinematicTree().GetControlledState();
    Eigen::MatrixXd bounds = scene_->GetKinematicTree().GetJointLimits();

    std::cout.precision(4);
    constexpr double tolerance = 1.e-3;

    bool succeeded = true;
    for (unsigned int i = 0; i < N; ++i)
    {
        if (x(i) < bounds(i, 0) - tolerance || x(i) > bounds(i, 1) + tolerance)
        {
            if (debug_) HIGHLIGHT_NAMED("BoundedEndPoseProblem::IsValid", "Out of bounds (joint #" << i << "): " << bounds(i, 0) << " < " << x(i) << " < " << bounds(i, 1));
            succeeded = false;
        }
    }
    return succeeded;
}
}  // namespace exotica
<|endoftext|>


<commit_before>/* $Id$ */
/* Author: Toby Young, Polish Academy of Sciences,                */
/*         Wolfgang Bangerth, Texas A&M University                */
/*    $Id$        */
/*                                                                */
/*    Copyright (C) 2009 by the deal.II authors */
/*                                                                */
/*    This file is subject to QPL and may not be  distributed     */
/*    without copyright and license information. Please refer     */
/*    to the file deal.II/doc/license.html for the  text  and     */
/*    further information on this license.                        */

                                 // @sect3{Include files}

#include <base/logstream.h>
#include <base/quadrature_lib.h>
#include <base/function.h>
#include <base/function_parser.h>
#include <base/parameter_handler.h>
#include <base/utilities.h>
#include <lac/full_matrix.h>
#include <lac/petsc_sparse_matrix.h>
#include <lac/petsc_vector.h>
#include <lac/solver_cg.h>
#include <lac/precondition.h>
#include <lac/compressed_simple_sparsity_pattern.h>
#include <grid/tria.h>
#include <grid/grid_generator.h>
#include <grid/tria_accessor.h>
#include <grid/tria_iterator.h>
#include <dofs/dof_handler.h>
#include <dofs/dof_accessor.h>
#include <dofs/dof_tools.h>
#include <fe/fe_q.h>
#include <fe/fe_values.h>
#include <numerics/vectors.h>
#include <numerics/matrices.h>
#include <numerics/data_out.h>

#include <fstream>
#include <iostream>

				 // The final step, as in previous
				 // programs, is to import all the
				 // deal.II class and function names
				 // into the global namespace:
using namespace dealii;

                                 // @sect3{The EigenvalueProblem class template}

template <int dim>
class EigenvalueProblem
{
  public:
    EigenvalueProblem (const std::string &prm_file);
    void run ();

  private:
    void make_grid_and_dofs ();
    void assemble_system ();
    void solve ();
    void output_results () const;

    Triangulation<dim>   triangulation;
    FE_Q<dim>            fe;
    DoFHandler<dim>      dof_handler;

    PETScWrappers::SparseMatrix        stiffness_matrix, mass_matrix;
    std::vector<PETScWrappers::Vector> eigenfunctions;

    ParameterHandler parameters;
};

                                 // @sect3{Implementation of the EigenvalueProblem class}

                                 // @sect4{EigenvalueProblem::EigenvalueProblem}

template <int dim>
EigenvalueProblem<dim>::EigenvalueProblem (const std::string &prm_file)
		:
                fe (1),
		dof_handler (triangulation)
{
  parameters.declare_entry ("Number of eigenvalues/eigenfunctions", "10",
			    Patterns::Integer (0, 100),
			    "The number of eigenvalues/eigenfunctions "
			    "to be computed.");
  parameters.declare_entry ("Potential", "0",
			    Patterns::Anything(),
			    "A functional description of the potential.");

  parameters.read_input (prm_file);
}

                                 // @sect4{EigenvalueProblem::make_grid_and_dofs}
template <int dim>
void EigenvalueProblem<dim>::make_grid_and_dofs ()
{
  GridGenerator::hyper_cube (triangulation, -1, 1);
  triangulation.refine_global (4);
  dof_handler.distribute_dofs (fe);

  CompressedSimpleSparsityPattern csp (dof_handler.n_dofs(),
				       dof_handler.n_dofs());
  DoFTools::make_sparsity_pattern (dof_handler, csp);
  stiffness_matrix.reinit (csp);
  mass_matrix.reinit (csp);

  eigenfunctions
    .resize (parameters.get_integer ("Number of eigenvalues/eigenfunctions"));
  for (unsigned int i=0; i<eigenfunctions.size(); ++i)
    eigenfunctions[i].reinit (dof_handler.n_dofs());
}

                                 // @sect4{EigenvalueProblem::assemble_system}
template <int dim>
void EigenvalueProblem<dim>::assemble_system ()
{
  QGauss<dim>  quadrature_formula(2);

  FEValues<dim> fe_values (fe, quadrature_formula,
			   update_values   | update_gradients |
                           update_quadrature_points | update_JxW_values);

  const unsigned int dofs_per_cell = fe.dofs_per_cell;
  const unsigned int n_q_points    = quadrature_formula.size();

  FullMatrix<double> cell_stiffness_matrix (dofs_per_cell, dofs_per_cell);
  FullMatrix<double> cell_mass_matrix (dofs_per_cell, dofs_per_cell);

  std::vector<unsigned int> local_dof_indices (dofs_per_cell);

  FunctionParser<dim> potential;
  potential.initialize ((dim == 2 ?
			 "x,y" :
			 "x,y,z"),
			parameters.get ("Potential"),
			typename FunctionParser<dim>::ConstMap());
  std::vector<double> potential_values (n_q_points);

  ConstraintMatrix constraints;
  VectorTools::interpolate_boundary_values (dof_handler,
					    0,
					    ZeroFunction<dim>(),
					    constraints);
  constraints.close ();

  typename DoFHandler<dim>::active_cell_iterator
    cell = dof_handler.begin_active(),
    endc = dof_handler.end();
  for (; cell!=endc; ++cell)
    {
      fe_values.reinit (cell);
      cell_stiffness_matrix = 0;
      cell_mass_matrix = 0;

      potential.value_list (fe_values.get_quadrature_points(),
			    potential_values);

      for (unsigned int q_point=0; q_point<n_q_points; ++q_point)
	for (unsigned int i=0; i<dofs_per_cell; ++i)
	  for (unsigned int j=0; j<dofs_per_cell; ++j)
	    {
	      cell_stiffness_matrix(i,j)
		+= ((fe_values.shape_grad (i, q_point) *
		     fe_values.shape_grad (j, q_point)
		     +
		     potential_values[q_point] *
		     fe_values.shape_value (i, q_point) *
		     fe_values.shape_value (j, q_point)) *
		    fe_values.JxW (q_point));
	      cell_mass_matrix(i,j)
		+= (fe_values.shape_value (i, q_point) *
		    fe_values.shape_value (j, q_point) *
		    fe_values.JxW (q_point));
	    }

      cell->get_dof_indices (local_dof_indices);

      constraints.distribute_local_to_global (cell_stiffness_matrix,
					      local_dof_indices,
					      stiffness_matrix);
      constraints.distribute_local_to_global (cell_mass_matrix,
					      local_dof_indices,
					      mass_matrix);
    }
}

                                 // @sect4{EigenvalueProblem::solve}
template <int dim>
void EigenvalueProblem<dim>::solve ()
{
// do whatever is necessary here. use stiffness_matrix, mass_matrix, and the
// eigenfunctions[] array
}

                                 // @sect4{EigenvalueProblem::output_results}

template <int dim>
void EigenvalueProblem<dim>::output_results () const
{
  DataOut<dim> data_out;

  data_out.attach_dof_handler (dof_handler);

  for (unsigned int i=0; i<eigenfunctions.size(); ++i)
    data_out.add_data_vector (eigenfunctions[i],
			      std::string("solution") +
			      Utilities::int_to_string(i));

  data_out.build_patches ();

  std::ofstream output ("eigenvectors.vtk");
  data_out.write_vtk (output);
}

                                 // @sect4{EigenvalueProblem::run}

                                 // This is the function which has the
				 // top-level control over everything. It is
				 // the same as for the previous example.
template <int dim>
void EigenvalueProblem<dim>::run ()
{
  std::cout << "Solving problem in " << dim << " space dimensions." << std::endl;

  make_grid_and_dofs();
  assemble_system ();
  solve ();
  output_results ();
}

                                 // @sect3{The main function}

int main (int argc, char **argv)
{
  try
    {
      PetscInitialize(&argc,&argv,0,0);
      deallog.depth_console (0);

      EigenvalueProblem<2> problem ("step-36.prm");
      problem.run ();
    }
  catch (std::exception &exc)
    {
      std::cerr << std::endl << std::endl
		<< "----------------------------------------------------"
		<< std::endl;
      std::cerr << "Exception on processing: " << std::endl
		<< exc.what() << std::endl
		<< "Aborting!" << std::endl
		<< "----------------------------------------------------"
		<< std::endl;

      return 1;
    }
  catch (...)
    {
      std::cerr << std::endl << std::endl
		<< "----------------------------------------------------"
		<< std::endl;
      std::cerr << "Unknown exception!" << std::endl
		<< "Aborting!" << std::endl
		<< "----------------------------------------------------"
		<< std::endl;
      return 1;
    }

  return 0;
}
<commit_msg>Interpolate potential and put it into the output. Refine once more.<commit_after>/* $Id$ */
/* Author: Toby Young, Polish Academy of Sciences,                */
/*         Wolfgang Bangerth, Texas A&M University                */
/*    $Id$        */
/*                                                                */
/*    Copyright (C) 2009 by the deal.II authors */
/*                                                                */
/*    This file is subject to QPL and may not be  distributed     */
/*    without copyright and license information. Please refer     */
/*    to the file deal.II/doc/license.html for the  text  and     */
/*    further information on this license.                        */

                                 // @sect3{Include files}

#include <base/logstream.h>
#include <base/quadrature_lib.h>
#include <base/function.h>
#include <base/function_parser.h>
#include <base/parameter_handler.h>
#include <base/utilities.h>
#include <lac/full_matrix.h>
#include <lac/petsc_sparse_matrix.h>
#include <lac/petsc_vector.h>
#include <lac/solver_cg.h>
#include <lac/precondition.h>
#include <lac/compressed_simple_sparsity_pattern.h>
#include <grid/tria.h>
#include <grid/grid_generator.h>
#include <grid/tria_accessor.h>
#include <grid/tria_iterator.h>
#include <dofs/dof_handler.h>
#include <dofs/dof_accessor.h>
#include <dofs/dof_tools.h>
#include <fe/fe_q.h>
#include <fe/fe_values.h>
#include <numerics/vectors.h>
#include <numerics/matrices.h>
#include <numerics/data_out.h>

#include <fstream>
#include <iostream>

				 // The final step, as in previous
				 // programs, is to import all the
				 // deal.II class and function names
				 // into the global namespace:
using namespace dealii;

                                 // @sect3{The EigenvalueProblem class template}

template <int dim>
class EigenvalueProblem
{
  public:
    EigenvalueProblem (const std::string &prm_file);
    void run ();

  private:
    void make_grid_and_dofs ();
    void assemble_system ();
    void solve ();
    void output_results () const;

    Triangulation<dim>   triangulation;
    FE_Q<dim>            fe;
    DoFHandler<dim>      dof_handler;

    PETScWrappers::SparseMatrix        stiffness_matrix, mass_matrix;
    std::vector<PETScWrappers::Vector> eigenfunctions;

    ParameterHandler parameters;
};

                                 // @sect3{Implementation of the EigenvalueProblem class}

                                 // @sect4{EigenvalueProblem::EigenvalueProblem}

template <int dim>
EigenvalueProblem<dim>::EigenvalueProblem (const std::string &prm_file)
		:
                fe (1),
		dof_handler (triangulation)
{
  parameters.declare_entry ("Number of eigenvalues/eigenfunctions", "10",
			    Patterns::Integer (0, 100),
			    "The number of eigenvalues/eigenfunctions "
			    "to be computed.");
  parameters.declare_entry ("Potential", "0",
			    Patterns::Anything(),
			    "A functional description of the potential.");

  parameters.read_input (prm_file);
}

                                 // @sect4{EigenvalueProblem::make_grid_and_dofs}
template <int dim>
void EigenvalueProblem<dim>::make_grid_and_dofs ()
{
  GridGenerator::hyper_cube (triangulation, -1, 1);
  triangulation.refine_global (5);
  dof_handler.distribute_dofs (fe);

  CompressedSimpleSparsityPattern csp (dof_handler.n_dofs(),
				       dof_handler.n_dofs());
  DoFTools::make_sparsity_pattern (dof_handler, csp);
  stiffness_matrix.reinit (csp);
  mass_matrix.reinit (csp);

  eigenfunctions
    .resize (parameters.get_integer ("Number of eigenvalues/eigenfunctions"));
  for (unsigned int i=0; i<eigenfunctions.size(); ++i)
    eigenfunctions[i].reinit (dof_handler.n_dofs());
}

                                 // @sect4{EigenvalueProblem::assemble_system}
template <int dim>
void EigenvalueProblem<dim>::assemble_system ()
{
  QGauss<dim>  quadrature_formula(2);

  FEValues<dim> fe_values (fe, quadrature_formula,
			   update_values   | update_gradients |
                           update_quadrature_points | update_JxW_values);

  const unsigned int dofs_per_cell = fe.dofs_per_cell;
  const unsigned int n_q_points    = quadrature_formula.size();

  FullMatrix<double> cell_stiffness_matrix (dofs_per_cell, dofs_per_cell);
  FullMatrix<double> cell_mass_matrix (dofs_per_cell, dofs_per_cell);

  std::vector<unsigned int> local_dof_indices (dofs_per_cell);

  FunctionParser<dim> potential;
  potential.initialize ((dim == 2 ?
			 "x,y" :
			 "x,y,z"),
			parameters.get ("Potential"),
			typename FunctionParser<dim>::ConstMap());
  std::vector<double> potential_values (n_q_points);

  ConstraintMatrix constraints;
  VectorTools::interpolate_boundary_values (dof_handler,
					    0,
					    ZeroFunction<dim>(),
					    constraints);
  constraints.close ();

  typename DoFHandler<dim>::active_cell_iterator
    cell = dof_handler.begin_active(),
    endc = dof_handler.end();
  for (; cell!=endc; ++cell)
    {
      fe_values.reinit (cell);
      cell_stiffness_matrix = 0;
      cell_mass_matrix = 0;

      potential.value_list (fe_values.get_quadrature_points(),
			    potential_values);

      for (unsigned int q_point=0; q_point<n_q_points; ++q_point)
	for (unsigned int i=0; i<dofs_per_cell; ++i)
	  for (unsigned int j=0; j<dofs_per_cell; ++j)
	    {
	      cell_stiffness_matrix(i,j)
		+= ((fe_values.shape_grad (i, q_point) *
		     fe_values.shape_grad (j, q_point)
		     +
		     potential_values[q_point] *
		     fe_values.shape_value (i, q_point) *
		     fe_values.shape_value (j, q_point)) *
		    fe_values.JxW (q_point));
	      cell_mass_matrix(i,j)
		+= (fe_values.shape_value (i, q_point) *
		    fe_values.shape_value (j, q_point) *
		    fe_values.JxW (q_point));
	    }

      cell->get_dof_indices (local_dof_indices);

      constraints.distribute_local_to_global (cell_stiffness_matrix,
					      local_dof_indices,
					      stiffness_matrix);
      constraints.distribute_local_to_global (cell_mass_matrix,
					      local_dof_indices,
					      mass_matrix);
    }
}

                                 // @sect4{EigenvalueProblem::solve}
template <int dim>
void EigenvalueProblem<dim>::solve ()
{
// do whatever is necessary here. use stiffness_matrix, mass_matrix, and the
// eigenfunctions[] array
}

                                 // @sect4{EigenvalueProblem::output_results}

template <int dim>
void EigenvalueProblem<dim>::output_results () const
{
  DataOut<dim> data_out;

  data_out.attach_dof_handler (dof_handler);

  for (unsigned int i=0; i<eigenfunctions.size(); ++i)
    data_out.add_data_vector (eigenfunctions[i],
			      std::string("solution") +
			      Utilities::int_to_string(i));

  Vector<double> projected_potential (dof_handler.n_dofs());
  FunctionParser<dim> potential;
  potential.initialize ((dim == 2 ?
			 "x,y" :
			 "x,y,z"),
			parameters.get ("Potential"),
			typename FunctionParser<dim>::ConstMap());
  VectorTools::interpolate (dof_handler, potential, projected_potential);
  data_out.add_data_vector (projected_potential, "interpolated_potential");

  data_out.build_patches ();

  std::ofstream output ("eigenvectors.vtk");
  data_out.write_vtk (output);
}

                                 // @sect4{EigenvalueProblem::run}

                                 // This is the function which has the
				 // top-level control over everything. It is
				 // the same as for the previous example.
template <int dim>
void EigenvalueProblem<dim>::run ()
{
  std::cout << "Solving problem in " << dim << " space dimensions." << std::endl;

  make_grid_and_dofs();
  assemble_system ();
  solve ();
  output_results ();
}

                                 // @sect3{The main function}

int main (int argc, char **argv)
{
  try
    {
      PetscInitialize(&argc,&argv,0,0);
      deallog.depth_console (0);

      EigenvalueProblem<2> problem ("step-36.prm");
      problem.run ();
    }
  catch (std::exception &exc)
    {
      std::cerr << std::endl << std::endl
		<< "----------------------------------------------------"
		<< std::endl;
      std::cerr << "Exception on processing: " << std::endl
		<< exc.what() << std::endl
		<< "Aborting!" << std::endl
		<< "----------------------------------------------------"
		<< std::endl;

      return 1;
    }
  catch (...)
    {
      std::cerr << std::endl << std::endl
		<< "----------------------------------------------------"
		<< std::endl;
      std::cerr << "Unknown exception!" << std::endl
		<< "Aborting!" << std::endl
		<< "----------------------------------------------------"
		<< std::endl;
      return 1;
    }

  return 0;
}
<|endoftext|>