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

#ifndef _COM_SUN_STAR_TEXT_XTEXTVIEWCURSOR_HPP_
#include <com/sun/star/text/XTextViewCursor.hpp>
#endif
#ifndef _COM_SUN_STAR_VIEW_XSCREENCURSOR_HPP_
#include <com/sun/star/view/XScreenCursor.hpp>
#endif

#ifndef _SFXREQUEST_HXX
#include <sfx2/request.hxx>
#endif

#ifndef _VOS_MUTEX_HXX_ //autogen
#include <vos/mutex.hxx>
#endif

#include "sdview.hxx"
#ifndef SVX_LIGHT
#include "docshell.hxx"
#endif
#include "viewshel.hxx"
#include "fuslshow.hxx"

#include <cppuhelper/implbase2.hxx>

using namespace ::vos;
using namespace ::rtl;
using namespace ::com::sun::star;

class SdXTextViewCursor : public ::cppu::WeakImplHelper2<
                                    text::XTextViewCursor,
                                    view::XScreenCursor >
{
    SdView* mpView;
public:
    SdXTextViewCursor(SdView* pVw) throw();
    virtual ~SdXTextViewCursor() throw();

    //XTextViewCursor
    virtual sal_Bool SAL_CALL isVisible(void) throw( uno::RuntimeException );
    virtual void SAL_CALL setVisible(sal_Bool bVisible) throw( uno::RuntimeException );
    virtual awt::Point SAL_CALL getPosition(void) throw( uno::RuntimeException );

    //XTextCursor
    virtual void SAL_CALL collapseToStart(void) throw( uno::RuntimeException );
    virtual void SAL_CALL collapseToEnd(void) throw( uno::RuntimeException );
    virtual sal_Bool SAL_CALL isCollapsed(void) throw( uno::RuntimeException );
    virtual sal_Bool SAL_CALL goLeft(sal_Int16 nCount, sal_Bool Expand) throw( uno::RuntimeException );
    virtual sal_Bool SAL_CALL goRight(sal_Int16 nCount, sal_Bool Expand) throw( uno::RuntimeException );
    virtual void SAL_CALL gotoStart(sal_Bool Expand) throw( uno::RuntimeException );
    virtual void SAL_CALL gotoEnd(sal_Bool Expand) throw( uno::RuntimeException );
    virtual void SAL_CALL gotoRange(const uno::Reference< text::XTextRange > & rRange, sal_Bool bExpand ) throw (::com::sun::star::uno::RuntimeException);

    //XTextRange
    virtual uno::Reference< text::XText >  SAL_CALL getText(void) throw( uno::RuntimeException );
    virtual uno::Reference< text::XTextRange >  SAL_CALL getStart(void) throw( uno::RuntimeException );
    virtual uno::Reference< text::XTextRange >  SAL_CALL getEnd(void) throw( uno::RuntimeException );
    virtual OUString SAL_CALL getString(void) throw( uno::RuntimeException );
    virtual void SAL_CALL setString(const OUString& aString) throw( uno::RuntimeException );

    //XScreenCursor
    virtual sal_Bool SAL_CALL screenDown(void) throw( uno::RuntimeException );
    virtual sal_Bool SAL_CALL screenUp(void) throw( uno::RuntimeException );

    void    Invalidate()    { mpView = 0; }
};

text::XTextViewCursor* CreateSdXTextViewCursor( SdView* mpView )
{
    return new SdXTextViewCursor( mpView );
}

SdXTextViewCursor::SdXTextViewCursor(SdView* pSdView ) throw()
:   mpView(pSdView)
{

}

SdXTextViewCursor::~SdXTextViewCursor() throw()
{
}

sal_Bool SdXTextViewCursor::isVisible(void) throw( uno::RuntimeException )
{
    DBG_WARNING("not implemented")
    return sal_True;
}

void SdXTextViewCursor::setVisible(sal_Bool bVisible) throw( uno::RuntimeException )
{
    DBG_WARNING("not implemented")
}

awt::Point SdXTextViewCursor::getPosition(void) throw( uno::RuntimeException )
{
    DBG_WARNING("not implemented")
    return awt::Point();
}

void SdXTextViewCursor::collapseToStart(void) throw( uno::RuntimeException )
{
    DBG_WARNING("not implemented")
}

void SdXTextViewCursor::collapseToEnd(void) throw( uno::RuntimeException )
{
    DBG_WARNING("not implemented")
}

sal_Bool SdXTextViewCursor::isCollapsed(void) throw( uno::RuntimeException )
{
    DBG_WARNING("not implemented")
    return sal_True;

}

sal_Bool SdXTextViewCursor::goLeft(sal_Int16 nCount, sal_Bool bExpand) throw( uno::RuntimeException )
{
    DBG_WARNING("not implemented")
    return sal_False;
}

sal_Bool SdXTextViewCursor::goRight(sal_Int16 nCount, sal_Bool bExpand) throw( uno::RuntimeException )
{
    DBG_WARNING("not implemented")
    return sal_False;
}

void SdXTextViewCursor::gotoRange(const uno::Reference< text::XTextRange > & xRange, sal_Bool bExpand) throw (::com::sun::star::uno::RuntimeException)
{
    DBG_WARNING("not implemented")
}

void SdXTextViewCursor::gotoStart(sal_Bool bExpand) throw( uno::RuntimeException )
{
    DBG_WARNING("not implemented")
}

void SdXTextViewCursor::gotoEnd(sal_Bool bExpand) throw( uno::RuntimeException )
{
    DBG_WARNING("not implemented")
}

sal_Bool SdXTextViewCursor::screenDown(void) throw( uno::RuntimeException )
{
    OGuard aGuard(Application::GetSolarMutex());
    sal_Bool bRet = sal_False;

    if( mpView && mpView->GetDocSh() )
    {
        SdViewShell* pViewSh = mpView->GetDocSh()->GetViewShell();
        if( pViewSh )
        {
            FuSlideShow* pShow = pViewSh->GetSlideShow();
            if( pShow )
            {
                pShow->KeyInput( KeyEvent( 32, KeyCode( KEY_SPACE ) ) );
                return sal_True;
            }
        }
    }
    return sal_False;
}

sal_Bool SdXTextViewCursor::screenUp(void) throw( uno::RuntimeException )
{
    OGuard aGuard(Application::GetSolarMutex());
    sal_Bool bRet = sal_False;

    if( mpView && mpView->GetDocSh() )
    {
        SdViewShell* pViewSh = mpView->GetDocSh()->GetViewShell();
        if( pViewSh )
        {
            FuSlideShow* pShow = pViewSh->GetSlideShow();
            if( pShow )
            {
                pShow->KeyInput( KeyEvent( 32, KeyCode( KEY_BACKSPACE ) ) );
                return sal_True;
            }
        }
    }
    return sal_False;
}

uno::Reference< text::XText >  SdXTextViewCursor::getText(void) throw( uno::RuntimeException )
{
    DBG_WARNING("not implemented")
    return uno::Reference< text::XText > ();
}

uno::Reference< text::XTextRange >  SdXTextViewCursor::getStart(void) throw( uno::RuntimeException )
{
    DBG_WARNING("not implemented")
    return uno::Reference< text::XTextRange > ();
}

uno::Reference< text::XTextRange >  SdXTextViewCursor::getEnd(void) throw( uno::RuntimeException )
{
    DBG_WARNING("not implemented")
    return uno::Reference< text::XTextRange > ();
}

OUString SdXTextViewCursor::getString(void) throw( uno::RuntimeException )
{
    DBG_WARNING("not implemented")
    return OUString();
}

void SdXTextViewCursor::setString(const OUString& aString) throw( uno::RuntimeException )
{
    DBG_WARNING("not implemented")
}

<commit_msg>INTEGRATION: CWS impress1 (1.3.240); FILE MERGED 2003/09/17 09:44:57 af 1.3.240.1: #111996# Transition to stacked sub-shells. Introduction of namespace sd.<commit_after>/*************************************************************************
 *
 *  $RCSfile: unovwcrs.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2004-01-20 12:36:52 $
 *
 *  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 _COM_SUN_STAR_TEXT_XTEXTVIEWCURSOR_HPP_
#include <com/sun/star/text/XTextViewCursor.hpp>
#endif
#ifndef _COM_SUN_STAR_VIEW_XSCREENCURSOR_HPP_
#include <com/sun/star/view/XScreenCursor.hpp>
#endif

#ifndef _SFXREQUEST_HXX
#include <sfx2/request.hxx>
#endif

#ifndef _VOS_MUTEX_HXX_ //autogen
#include <vos/mutex.hxx>
#endif

#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#ifndef SVX_LIGHT
#ifndef SD_DRAW_DOC_SHELL_HXX
#include "DrawDocShell.hxx"
#endif
#endif
#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif
#ifndef SD_FU_SLIDE_SHOW_HXX
#include "fuslshow.hxx"
#endif

#include <cppuhelper/implbase2.hxx>

using namespace ::vos;
using namespace ::rtl;
using namespace ::com::sun::star;

class SdXTextViewCursor
    : public ::cppu::WeakImplHelper2<
    text::XTextViewCursor,
    view::XScreenCursor >
{
public:
    SdXTextViewCursor(::sd::View* pVw) throw();
    virtual ~SdXTextViewCursor() throw();

    //XTextViewCursor
    virtual sal_Bool SAL_CALL isVisible(void) throw( uno::RuntimeException );
    virtual void SAL_CALL setVisible(sal_Bool bVisible) throw( uno::RuntimeException );
    virtual awt::Point SAL_CALL getPosition(void) throw( uno::RuntimeException );

    //XTextCursor
    virtual void SAL_CALL collapseToStart(void) throw( uno::RuntimeException );
    virtual void SAL_CALL collapseToEnd(void) throw( uno::RuntimeException );
    virtual sal_Bool SAL_CALL isCollapsed(void) throw( uno::RuntimeException );
    virtual sal_Bool SAL_CALL goLeft(sal_Int16 nCount, sal_Bool Expand) throw( uno::RuntimeException );
    virtual sal_Bool SAL_CALL goRight(sal_Int16 nCount, sal_Bool Expand) throw( uno::RuntimeException );
    virtual void SAL_CALL gotoStart(sal_Bool Expand) throw( uno::RuntimeException );
    virtual void SAL_CALL gotoEnd(sal_Bool Expand) throw( uno::RuntimeException );
    virtual void SAL_CALL gotoRange(const uno::Reference< text::XTextRange > & rRange, sal_Bool bExpand ) throw (::com::sun::star::uno::RuntimeException);

    //XTextRange
    virtual uno::Reference< text::XText >  SAL_CALL getText(void) throw( uno::RuntimeException );
    virtual uno::Reference< text::XTextRange >  SAL_CALL getStart(void) throw( uno::RuntimeException );
    virtual uno::Reference< text::XTextRange >  SAL_CALL getEnd(void) throw( uno::RuntimeException );
    virtual OUString SAL_CALL getString(void) throw( uno::RuntimeException );
    virtual void SAL_CALL setString(const OUString& aString) throw( uno::RuntimeException );

    //XScreenCursor
    virtual sal_Bool SAL_CALL screenDown(void) throw( uno::RuntimeException );
    virtual sal_Bool SAL_CALL screenUp(void) throw( uno::RuntimeException );

    void    Invalidate()    { mpView = 0; }

private:
    ::sd::View* mpView;
};

text::XTextViewCursor* CreateSdXTextViewCursor(::sd::View* mpView )
{
    return new SdXTextViewCursor( mpView );
}

SdXTextViewCursor::SdXTextViewCursor(::sd::View* pSdView ) throw()
    :   mpView(pSdView)
{

}

SdXTextViewCursor::~SdXTextViewCursor() throw()
{
}

sal_Bool SdXTextViewCursor::isVisible(void) throw( uno::RuntimeException )
{
    DBG_WARNING("not implemented")
    return sal_True;
}

void SdXTextViewCursor::setVisible(sal_Bool bVisible) throw( uno::RuntimeException )
{
    DBG_WARNING("not implemented")
}

awt::Point SdXTextViewCursor::getPosition(void) throw( uno::RuntimeException )
{
    DBG_WARNING("not implemented")
    return awt::Point();
}

void SdXTextViewCursor::collapseToStart(void) throw( uno::RuntimeException )
{
    DBG_WARNING("not implemented")
}

void SdXTextViewCursor::collapseToEnd(void) throw( uno::RuntimeException )
{
    DBG_WARNING("not implemented")
}

sal_Bool SdXTextViewCursor::isCollapsed(void) throw( uno::RuntimeException )
{
    DBG_WARNING("not implemented")
    return sal_True;

}

sal_Bool SdXTextViewCursor::goLeft(sal_Int16 nCount, sal_Bool bExpand) throw( uno::RuntimeException )
{
    DBG_WARNING("not implemented")
    return sal_False;
}

sal_Bool SdXTextViewCursor::goRight(sal_Int16 nCount, sal_Bool bExpand) throw( uno::RuntimeException )
{
    DBG_WARNING("not implemented")
    return sal_False;
}

void SdXTextViewCursor::gotoRange(const uno::Reference< text::XTextRange > & xRange, sal_Bool bExpand) throw (::com::sun::star::uno::RuntimeException)
{
    DBG_WARNING("not implemented")
}

void SdXTextViewCursor::gotoStart(sal_Bool bExpand) throw( uno::RuntimeException )
{
    DBG_WARNING("not implemented")
}

void SdXTextViewCursor::gotoEnd(sal_Bool bExpand) throw( uno::RuntimeException )
{
    DBG_WARNING("not implemented")
}

sal_Bool SdXTextViewCursor::screenDown(void) throw( uno::RuntimeException )
{
    OGuard aGuard(Application::GetSolarMutex());
    sal_Bool bRet = sal_False;

    if( mpView && mpView->GetDocSh() )
    {
        ::sd::ViewShell* pViewSh = mpView->GetDocSh()->GetViewShell();
        if( pViewSh )
        {
            ::sd::FuSlideShow* pShow = pViewSh->GetSlideShow();
            if( pShow )
            {
                pShow->KeyInput( KeyEvent( 32, KeyCode( KEY_SPACE ) ) );
                return sal_True;
            }
        }
    }
    return sal_False;
}

sal_Bool SdXTextViewCursor::screenUp(void) throw( uno::RuntimeException )
{
    OGuard aGuard(Application::GetSolarMutex());
    sal_Bool bRet = sal_False;

    if( mpView && mpView->GetDocSh() )
    {
        ::sd::ViewShell* pViewSh = mpView->GetDocSh()->GetViewShell();
        if( pViewSh )
        {
            ::sd::FuSlideShow* pShow = pViewSh->GetSlideShow();
            if( pShow )
            {
                pShow->KeyInput( KeyEvent( 32, KeyCode( KEY_BACKSPACE ) ) );
                return sal_True;
            }
        }
    }
    return sal_False;
}

uno::Reference< text::XText >  SdXTextViewCursor::getText(void) throw( uno::RuntimeException )
{
    DBG_WARNING("not implemented")
    return uno::Reference< text::XText > ();
}

uno::Reference< text::XTextRange >  SdXTextViewCursor::getStart(void) throw( uno::RuntimeException )
{
    DBG_WARNING("not implemented")
    return uno::Reference< text::XTextRange > ();
}

uno::Reference< text::XTextRange >  SdXTextViewCursor::getEnd(void) throw( uno::RuntimeException )
{
    DBG_WARNING("not implemented")
    return uno::Reference< text::XTextRange > ();
}

OUString SdXTextViewCursor::getString(void) throw( uno::RuntimeException )
{
    DBG_WARNING("not implemented")
    return OUString();
}

void SdXTextViewCursor::setString(const OUString& aString) throw( uno::RuntimeException )
{
    DBG_WARNING("not implemented")
}

<|endoftext|>


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

// include ---------------------------------------------------------------

#ifndef _SFX_WHITER_HXX //autogen
#include <svtools/whiter.hxx>
#endif
#ifndef _SFXSTYLE_HXX //autogen
#include <svtools/style.hxx>
#endif
#ifndef _MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#pragma hdrstop

#include "styledlg.hxx"
#include "mgetempl.hxx"
#include "sfxresid.hxx"
#include "sfxuno.hxx"

#include "dialog.hrc"

// class SfxStyleDialog --------------------------------------------------

#if SUP <= 372

SfxStyleDialog::SfxStyleDialog
(
    Window* pParent,            // Parent
    const ResId& rResId,        // ResId
    SfxStyleSheetBase& rStyle,  // zu bearbeitendes StyleSheet
    BOOL bFreeRes               // Flag Resourcen freigeben
) :

/*  [Beschreibung]

    Konstruktor: Verwalten-TabPage zuf"ugen, ExampleSet vom Style setzen.
*/

    SfxTabDialog( pParent, rResId,
                  rStyle.GetItemSet().Clone(),
                  // auch ohne ParentSupport TRUE "ubergeben, aber erweitert
                  // um den StandardButton zu unterdr"ucken
                  rStyle.HasParentSupport() ? TRUE : 2 ),

    pStyle( &rStyle )

{
    AddTabPage( ID_TABPAGE_MANAGESTYLES,
                String( SfxResId( STR_TABPAGE_MANAGESTYLES ) ),
                SfxManageStyleSheetPage::Create, 0, FALSE, 0 );

    // bei neuer Vorlage immer die Verwaltungsseite als aktuelle
    // Seite setzen

    if( !rStyle.GetName().Len() )
        SetCurPageId( ID_TABPAGE_MANAGESTYLES );
    else
    {
        String sTxt( GetText() );
        sTxt += DEFINE_CONST_UNICODE(": ");
        sTxt += rStyle.GetName();
        SetText( sTxt );
    }
    delete pExampleSet; // im SfxTabDialog::Ctor() schon angelegt
    pExampleSet = &pStyle->GetItemSet();

    if ( bFreeRes )
        FreeResource();
    GetCancelButton().SetClickHdl( LINK(this, SfxStyleDialog, CancelHdl) );
}

#endif

SfxStyleDialog::SfxStyleDialog
(
    Window* pParent,            // Parent
    const ResId& rResId,        // ResId
    SfxStyleSheetBase& rStyle,  // zu bearbeitendes StyleSheet
    BOOL bFreeRes,              // Flag Resourcen freigeben
    const String* pUserBtnTxt
) :

/*  [Beschreibung]

    Konstruktor: Verwalten-TabPage zuf"ugen, ExampleSet vom Style setzen.
*/

    SfxTabDialog( pParent, rResId,
                  rStyle.GetItemSet().Clone(),
                  // auch ohne ParentSupport TRUE "ubergeben, aber erweitert
                  // um den StandardButton zu unterdr"ucken
                  rStyle.HasParentSupport() ? TRUE : 2,
                  pUserBtnTxt ),

    pStyle( &rStyle )

{
    AddTabPage( ID_TABPAGE_MANAGESTYLES,
                String( SfxResId( STR_TABPAGE_MANAGESTYLES ) ),
                SfxManageStyleSheetPage::Create, 0, FALSE, 0 );

    // bei neuer Vorlage immer die Verwaltungsseite als aktuelle
    // Seite setzen

    if( !rStyle.GetName().Len() )
        SetCurPageId( ID_TABPAGE_MANAGESTYLES );
    else
    {
        String sTxt( GetText() );
        sTxt += DEFINE_CONST_UNICODE(": ") ;
        sTxt += rStyle.GetName();
        SetText( sTxt );
    }
    delete pExampleSet; // im SfxTabDialog::Ctor() schon angelegt
    pExampleSet = &pStyle->GetItemSet();

    if ( bFreeRes )
        FreeResource();
    GetCancelButton().SetClickHdl( LINK(this, SfxStyleDialog, CancelHdl) );
}

// -----------------------------------------------------------------------

SfxStyleDialog::~SfxStyleDialog()

/*  [Beschreibung]

    Destruktor: ExampleSet auf NULL setzen, damit der SfxTabDialog nicht den
    Set vom Style l"oscht.
*/

{
    pExampleSet = 0;
    pStyle = 0;
    delete GetInputSetImpl();
}

// -----------------------------------------------------------------------

const SfxItemSet* SfxStyleDialog::GetRefreshedSet()

/*  [Beschreibung]

    Diese wird gerufen, wenn <SfxTabPage::DeactivatePage(SfxItemSet *)>
    <SfxTabPage::REFRESH_SET> liefert.
*/

{
    return GetInputSetImpl();
}

// -----------------------------------------------------------------------

short SfxStyleDialog::Ok()

/*  [Beschreibung]

    "Uberladen, damit immer RET_OK zur"uckgegeben wird.
*/

{
    SfxTabDialog::Ok();
    return RET_OK;
}

// -----------------------------------------------------------------------

IMPL_LINK( SfxStyleDialog, CancelHdl, Button *, pButton )

/*  [Beschreibung]

    Wenn der Dialog abgebrochen wurde, m"ussen alle schon eingestellten
    Attribute wieder zur"uckgesetzt werden.
*/

{
    SfxTabPage* pPage = GetTabPage( ID_TABPAGE_MANAGESTYLES );

    const SfxItemSet* pInSet = GetInputSetImpl();
    SfxWhichIter aIter( *pInSet );
    USHORT nWhich = aIter.FirstWhich();

    while ( nWhich )
    {
        SfxItemState eState = pInSet->GetItemState( nWhich, FALSE );

        if ( SFX_ITEM_DEFAULT == eState )
            pExampleSet->ClearItem( nWhich );
        else
            pExampleSet->Put( pInSet->Get( nWhich ) );
        nWhich = aIter.NextWhich();
    }

    if ( pPage )
        pPage->Reset( *GetInputSetImpl() );
    EndDialog( RET_CANCEL );
    return 0;
}

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

// include ---------------------------------------------------------------

#ifndef _SFX_WHITER_HXX //autogen
#include <svtools/whiter.hxx>
#endif
#ifndef _SFXSTYLE_HXX //autogen
#include <svtools/style.hxx>
#endif
#ifndef _MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef GCC
#pragma hdrstop
#endif

#include "styledlg.hxx"
#include "mgetempl.hxx"
#include "sfxresid.hxx"
#include "sfxuno.hxx"

#include "dialog.hrc"

// class SfxStyleDialog --------------------------------------------------

#if SUP <= 372

SfxStyleDialog::SfxStyleDialog
(
    Window* pParent,            // Parent
    const ResId& rResId,        // ResId
    SfxStyleSheetBase& rStyle,  // zu bearbeitendes StyleSheet
    BOOL bFreeRes               // Flag Resourcen freigeben
) :

/*  [Beschreibung]

    Konstruktor: Verwalten-TabPage zuf"ugen, ExampleSet vom Style setzen.
*/

    SfxTabDialog( pParent, rResId,
                  rStyle.GetItemSet().Clone(),
                  // auch ohne ParentSupport TRUE "ubergeben, aber erweitert
                  // um den StandardButton zu unterdr"ucken
                  rStyle.HasParentSupport() ? TRUE : 2 ),

    pStyle( &rStyle )

{
    AddTabPage( ID_TABPAGE_MANAGESTYLES,
                String( SfxResId( STR_TABPAGE_MANAGESTYLES ) ),
                SfxManageStyleSheetPage::Create, 0, FALSE, 0 );

    // bei neuer Vorlage immer die Verwaltungsseite als aktuelle
    // Seite setzen

    if( !rStyle.GetName().Len() )
        SetCurPageId( ID_TABPAGE_MANAGESTYLES );
    else
    {
        String sTxt( GetText() );
        sTxt += DEFINE_CONST_UNICODE(": ");
        sTxt += rStyle.GetName();
        SetText( sTxt );
    }
    delete pExampleSet; // im SfxTabDialog::Ctor() schon angelegt
    pExampleSet = &pStyle->GetItemSet();

    if ( bFreeRes )
        FreeResource();
    GetCancelButton().SetClickHdl( LINK(this, SfxStyleDialog, CancelHdl) );
}

#endif

SfxStyleDialog::SfxStyleDialog
(
    Window* pParent,            // Parent
    const ResId& rResId,        // ResId
    SfxStyleSheetBase& rStyle,  // zu bearbeitendes StyleSheet
    BOOL bFreeRes,              // Flag Resourcen freigeben
    const String* pUserBtnTxt
) :

/*  [Beschreibung]

    Konstruktor: Verwalten-TabPage zuf"ugen, ExampleSet vom Style setzen.
*/

    SfxTabDialog( pParent, rResId,
                  rStyle.GetItemSet().Clone(),
                  // auch ohne ParentSupport TRUE "ubergeben, aber erweitert
                  // um den StandardButton zu unterdr"ucken
                  rStyle.HasParentSupport() ? TRUE : 2,
                  pUserBtnTxt ),

    pStyle( &rStyle )

{
    AddTabPage( ID_TABPAGE_MANAGESTYLES,
                String( SfxResId( STR_TABPAGE_MANAGESTYLES ) ),
                SfxManageStyleSheetPage::Create, 0, FALSE, 0 );

    // bei neuer Vorlage immer die Verwaltungsseite als aktuelle
    // Seite setzen

    if( !rStyle.GetName().Len() )
        SetCurPageId( ID_TABPAGE_MANAGESTYLES );
    else
    {
        String sTxt( GetText() );
        sTxt += DEFINE_CONST_UNICODE(": ") ;
        sTxt += rStyle.GetName();
        SetText( sTxt );
    }
    delete pExampleSet; // im SfxTabDialog::Ctor() schon angelegt
    pExampleSet = &pStyle->GetItemSet();

    if ( bFreeRes )
        FreeResource();
    GetCancelButton().SetClickHdl( LINK(this, SfxStyleDialog, CancelHdl) );
}

// -----------------------------------------------------------------------

SfxStyleDialog::~SfxStyleDialog()

/*  [Beschreibung]

    Destruktor: ExampleSet auf NULL setzen, damit der SfxTabDialog nicht den
    Set vom Style l"oscht.
*/

{
    pExampleSet = 0;
    pStyle = 0;
    delete GetInputSetImpl();
}

// -----------------------------------------------------------------------

const SfxItemSet* SfxStyleDialog::GetRefreshedSet()

/*  [Beschreibung]

    Diese wird gerufen, wenn <SfxTabPage::DeactivatePage(SfxItemSet *)>
    <SfxTabPage::REFRESH_SET> liefert.
*/

{
    return GetInputSetImpl();
}

// -----------------------------------------------------------------------

short SfxStyleDialog::Ok()

/*  [Beschreibung]

    "Uberladen, damit immer RET_OK zur"uckgegeben wird.
*/

{
    SfxTabDialog::Ok();
    return RET_OK;
}

// -----------------------------------------------------------------------

IMPL_LINK( SfxStyleDialog, CancelHdl, Button *, pButton )

/*  [Beschreibung]

    Wenn der Dialog abgebrochen wurde, m"ussen alle schon eingestellten
    Attribute wieder zur"uckgesetzt werden.
*/

{
    SfxTabPage* pPage = GetTabPage( ID_TABPAGE_MANAGESTYLES );

    const SfxItemSet* pInSet = GetInputSetImpl();
    SfxWhichIter aIter( *pInSet );
    USHORT nWhich = aIter.FirstWhich();

    while ( nWhich )
    {
        SfxItemState eState = pInSet->GetItemState( nWhich, FALSE );

        if ( SFX_ITEM_DEFAULT == eState )
            pExampleSet->ClearItem( nWhich );
        else
            pExampleSet->Put( pInSet->Get( nWhich ) );
        nWhich = aIter.NextWhich();
    }

    if ( pPage )
        pPage->Reset( *GetInputSetImpl() );
    EndDialog( RET_CANCEL );
    return 0;
}

<|endoftext|>


<commit_before>#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/numpy.h>
#include "../src/PointSpreadFunc.cpp"
#include "../src/RawImage.cpp"
#include "../src/LayeredImage.cpp"
#include "../src/ImageStack.cpp"
#include "../src/KBMOSearch.cpp"

namespace py = pybind11;

using pf = kbmod::PointSpreadFunc;
using ri = kbmod::RawImage;
using li = kbmod::LayeredImage;
using is = kbmod::ImageStack;
using ks = kbmod::KBMOSearch;
using tj = kbmod::trajectory;
using td = kbmod::trajRegion;

using std::to_string;

PYBIND11_MODULE(kbmod, m) {
	py::class_<pf>(m, "psf", py::buffer_protocol())
		.def_buffer([](pf &m) -> py::buffer_info {
			return py::buffer_info(
				m.kernelData(),
				sizeof(float),
				py::format_descriptor<float>::format(),
				2,
				{ m.getDim(), m.getDim() },
				{ sizeof(float) * m.getDim(),
				  sizeof(float) }
			);
		})
		.def(py::init<float>())
		.def(py::init<py::array_t<float>>())
		.def("set_array", &pf::setArray)
		.def("get_stdev", &pf::getStdev)
		.def("get_sum", &pf::getSum)
		.def("get_dim", &pf::getDim)
		.def("get_radius", &pf::getRadius)
		.def("get_size", &pf::getSize)
		.def("square_psf", &pf::squarePSF)
		.def("print_psf", &pf::printPSF);

	py::class_<ri>(m, "raw_image", py::buffer_protocol())
		.def_buffer([](ri &m) -> py::buffer_info {
			return py::buffer_info(
				m.getDataRef(),
				sizeof(float),
				py::format_descriptor<float>::format(),
				2,
				{ m.getHeight(), m.getWidth() },
				{ sizeof(float) * m.getHeight(),
				  sizeof(float) }
			);
		})
		.def(py::init<int, int>())
		.def(py::init<py::array_t<float>>())
		.def("set_array", &ri::setArray)
		.def("pool", &ri::pool)
		.def("pool_min", &ri::poolMin)
		.def("pool_max", &ri::poolMax)
		.def("set_pixel", &ri::setPixel)
		.def("set_all", &ri::setAllPix)
		.def("get_pixel", &ri::getPixel)
		.def("get_pixel_interp", &ri::getPixelInterp)
		.def("get_ppi", &ri::getPPI)
		.def("convolve", &ri::convolve);

	py::class_<li>(m, "layered_image")
		.def(py::init<const std::string>())
		.def(py::init<std::string, int, int,
			double, float, float>())
		.def("apply_mask_flags", &li::applyMaskFlags)
		//.def("sci_numpy", &li::sciToNumpy)
		.def("save_layers", &li::saveLayers)
		.def("save_sci", &li::saveSci)
		.def("save_mask", &li::saveMask)
		.def("save_var", &li::saveVar)
		.def("get_science", &li::getScience)
		.def("get_mask", &li::getMask)
		.def("get_variance", &li::getVariance)
		.def("convolve", &li::convolve)
		.def("get_science_pooled", &li::poolScience)
		.def("get_variance_pooled", &li::poolVariance)
		.def("add_object", &li::addObject)
		.def("get_width", &li::getWidth)
		.def("get_height", &li::getHeight)
		.def("get_ppi", &li::getPPI)
		.def("get_time", &li::getTime);
	py::class_<is>(m, "image_stack")
		.def(py::init<std::vector<std::string>>())
		.def(py::init<std::vector<li>>())
		.def("get_images", &is::getImages)
		.def("get_times", &is::getTimes)
		.def("set_times", &is::setTimes)
		.def("img_count", &is::imgCount)
		.def("apply_mask_flags", &is::applyMaskFlags)
		.def("apply_master_mask", &is::applyMasterMask)
		.def("simple_difference", &is::simpleDifference)
		.def("save_master_mask", &is::saveMasterMask)
		.def("save_images", &is::saveImages)
		.def("get_master_mask", &is::getMasterMask)
		.def("get_sciences", &is::getSciences)
		.def("get_masks", &is::getMasks)
		.def("get_variances", &is::getVariances)
		.def("convolve", &is::convolve)
		.def("get_width", &is::getWidth)
		.def("get_height", &is::getHeight)
		.def("get_ppi", &is::getPPI);
	py::class_<ks>(m, "stack_search")
		.def(py::init<is, pf>())
		.def("save_psi_phi", &ks::savePsiPhi)
		.def("gpu", &ks::gpu)
		.def("region_search", &ks::regionSearch)
		.def("set_debug", &ks::setDebug)
		.def("filter_min_obs", &ks::filterResults)
		// For testing
		.def("extreme_in_region", &ks::findExtremeInRegion)
		.def("biggest_fit", &ks::biggestFit)
		.def("read_pixel_depth", &ks::readPixelDepth)
		.def("subdivide", &ks::subdivide)
		.def("filter_bounds", &ks::filterBounds)
		.def("square_sdf", &ks::squareSDF)
		.def("filter_lh", &ks::filterLH)
		.def("pixel_extreme", &ks::pixelExtreme)
		.def("get_psi_images", &ks::getPsiImages)
		.def("get_phi_images", &ks::getPhiImages)
		.def("get_psi_pooled", &ks::getPsiPooled)
		.def("get_phi_pooled", &ks::getPhiPooled)
		.def("clear_psi_phi", &ks::clearPsiPhi)
		.def("get_results", &ks::getResults)
		.def("save_results", &ks::saveResults);
	py::class_<tj>(m, "trajectory")
		.def(py::init<>())
		.def_readwrite("x_v", &tj::xVel)
		.def_readwrite("y_v", &tj::yVel)
		.def_readwrite("lh", &tj::lh)
		.def_readwrite("flux", &tj::flux)
		.def_readwrite("x", &tj::x)
		.def_readwrite("y", &tj::y)
		.def_readwrite("obs_count", &tj::obsCount)
		.def("__repr__", [](const tj &t) {
			return "lh: " + to_string(t.lh) +
                            " flux: " + to_string(t.flux) +
			       " x: " + to_string(t.x) +
                               " y: " + to_string(t.y) +
			      " x_v: " + to_string(t.xVel) +
                              " y_v: " + to_string(t.yVel) +
                              " obs_count: " + to_string(t.obsCount);
			}
		);
	py::class_<td>(m, "traj_region")
		.def(py::init<>())
		.def_readwrite("ix", &td::ix)
		.def_readwrite("iy", &td::iy)
		.def_readwrite("fx", &td::fx)
		.def_readwrite("fy", &td::fy)
		.def_readwrite("depth", &td::depth)
		.def_readwrite("obs_count", &td::obs_count)
		.def_readwrite("likelihood", &td::likelihood)
		.def_readwrite("flux", &td::flux)
		.def("__repr__", [](const td &t) {
			return "ix: " + to_string(t.ix) +
                              " iy: " + to_string(t.iy) +
			      " fx: " + to_string(t.fx) +
                              " fy: " + to_string(t.fy) +
			   " depth: " + to_string(static_cast<int>(t.depth)) +
                       " obs_count: " + to_string(static_cast<int>(t.obs_count)) +
			      " lh: " + to_string(t.likelihood) +
			     " flux " + to_string(t.flux);
			}
		);
}

<commit_msg>bindings for seting sci mask var + others<commit_after>#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/numpy.h>
#include "../src/PointSpreadFunc.cpp"
#include "../src/RawImage.cpp"
#include "../src/LayeredImage.cpp"
#include "../src/ImageStack.cpp"
#include "../src/KBMOSearch.cpp"

namespace py = pybind11;

using pf = kbmod::PointSpreadFunc;
using ri = kbmod::RawImage;
using li = kbmod::LayeredImage;
using is = kbmod::ImageStack;
using ks = kbmod::KBMOSearch;
using tj = kbmod::trajectory;
using td = kbmod::trajRegion;

using std::to_string;

PYBIND11_MODULE(kbmod, m) {
	py::class_<pf>(m, "psf", py::buffer_protocol())
		.def_buffer([](pf &m) -> py::buffer_info {
			return py::buffer_info(
				m.kernelData(),
				sizeof(float),
				py::format_descriptor<float>::format(),
				2,
				{ m.getDim(), m.getDim() },
				{ sizeof(float) * m.getDim(),
				  sizeof(float) }
			);
		})
		.def(py::init<float>())
		.def(py::init<py::array_t<float>>())
		.def("set_array", &pf::setArray)
		.def("get_stdev", &pf::getStdev)
		.def("get_sum", &pf::getSum)
		.def("get_dim", &pf::getDim)
		.def("get_radius", &pf::getRadius)
		.def("get_size", &pf::getSize)
		.def("square_psf", &pf::squarePSF)
		.def("print_psf", &pf::printPSF);

	py::class_<ri>(m, "raw_image", py::buffer_protocol())
		.def_buffer([](ri &m) -> py::buffer_info {
			return py::buffer_info(
				m.getDataRef(),
				sizeof(float),
				py::format_descriptor<float>::format(),
				2,
				{ m.getHeight(), m.getWidth() },
				{ sizeof(float) * m.getHeight(),
				  sizeof(float) }
			);
		})
		.def(py::init<int, int>())
		.def(py::init<py::array_t<float>>())
		.def("set_array", &ri::setArray)
		.def("pool", &ri::pool)
		.def("pool_min", &ri::poolMin)
		.def("pool_max", &ri::poolMax)
		.def("set_pixel", &ri::setPixel)
		.def("add_pixel", &ri::addToPixel)
		.def("mask_object", &ri::maskObject)
		.def("set_all", &ri::setAllPix)
		.def("get_pixel", &ri::getPixel)
		.def("get_pixel_interp", &ri::getPixelInterp)
		.def("get_ppi", &ri::getPPI)
		.def("convolve", &ri::convolve)
		.def("save_fits", &ri::saveToFile);

	py::class_<li>(m, "layered_image")
		.def(py::init<const std::string>())
		.def(py::init<std::string, int, int,
			double, float, float>())
		.def("apply_mask_flags", &li::applyMaskFlags)
		.def("sub_template", &li::subtractTemplate)
		.def("save_layers", &li::saveLayers)
		.def("save_sci", &li::saveSci)
		.def("save_mask", &li::saveMask)
		.def("save_var", &li::saveVar)
		.def("get_science", &li::getScience)
		.def("get_mask", &li::getMask)
		.def("get_variance", &li::getVariance)
		.def("set_science", &li::setScience)
		.def("set_mask", &li::setMask)
		.def("set_variance", &li::setVariance)
		.def("convolve", &li::convolve)
		.def("get_science_pooled", &li::poolScience)
		.def("get_variance_pooled", &li::poolVariance)
		.def("add_object", &li::addObject)
		.def("mask_object", &li::addObject)
		.def("get_name", &li::getName)
		.def("get_width", &li::getWidth)
		.def("get_height", &li::getHeight)
		.def("get_ppi", &li::getPPI)
		.def("get_time", &li::getTime);
	py::class_<is>(m, "image_stack")
		.def(py::init<std::vector<std::string>>())
		.def(py::init<std::vector<li>>())
		.def("get_images", &is::getImages)
		.def("get_times", &is::getTimes)
		.def("set_times", &is::setTimes)
		.def("img_count", &is::imgCount)
		.def("apply_mask_flags", &is::applyMaskFlags)
		.def("apply_master_mask", &is::applyMasterMask)
		.def("simple_difference", &is::simpleDifference)
		.def("save_master_mask", &is::saveMasterMask)
		.def("save_images", &is::saveImages)
		.def("get_master_mask", &is::getMasterMask)
		.def("get_sciences", &is::getSciences)
		.def("get_masks", &is::getMasks)
		.def("get_variances", &is::getVariances)
		.def("convolve", &is::convolve)
		.def("get_width", &is::getWidth)
		.def("get_height", &is::getHeight)
		.def("get_ppi", &is::getPPI);
	py::class_<ks>(m, "stack_search")
		.def(py::init<is, pf>())
		.def("save_psi_phi", &ks::savePsiPhi)
		.def("gpu", &ks::gpu)
		.def("region_search", &ks::regionSearch)
		.def("set_debug", &ks::setDebug)
		.def("filter_min_obs", &ks::filterResults)
		// For testing
		.def("extreme_in_region", &ks::findExtremeInRegion)
		.def("biggest_fit", &ks::biggestFit)
		.def("read_pixel_depth", &ks::readPixelDepth)
		.def("subdivide", &ks::subdivide)
		.def("filter_bounds", &ks::filterBounds)
		.def("square_sdf", &ks::squareSDF)
		.def("filter_lh", &ks::filterLH)
		.def("pixel_extreme", &ks::pixelExtreme)
		.def("get_psi_images", &ks::getPsiImages)
		.def("get_phi_images", &ks::getPhiImages)
		.def("get_psi_pooled", &ks::getPsiPooled)
		.def("get_phi_pooled", &ks::getPhiPooled)
		.def("clear_psi_phi", &ks::clearPsiPhi)
		.def("get_results", &ks::getResults)
		.def("save_results", &ks::saveResults);
	py::class_<tj>(m, "trajectory")
		.def(py::init<>())
		.def_readwrite("x_v", &tj::xVel)
		.def_readwrite("y_v", &tj::yVel)
		.def_readwrite("lh", &tj::lh)
		.def_readwrite("flux", &tj::flux)
		.def_readwrite("x", &tj::x)
		.def_readwrite("y", &tj::y)
		.def_readwrite("obs_count", &tj::obsCount)
		.def("__repr__", [](const tj &t) {
			return "lh: " + to_string(t.lh) +
                            " flux: " + to_string(t.flux) +
			       " x: " + to_string(t.x) +
                               " y: " + to_string(t.y) +
			      " x_v: " + to_string(t.xVel) +
                              " y_v: " + to_string(t.yVel) +
                              " obs_count: " + to_string(t.obsCount);
			}
		);
	py::class_<td>(m, "traj_region")
		.def(py::init<>())
		.def_readwrite("ix", &td::ix)
		.def_readwrite("iy", &td::iy)
		.def_readwrite("fx", &td::fx)
		.def_readwrite("fy", &td::fy)
		.def_readwrite("depth", &td::depth)
		.def_readwrite("obs_count", &td::obs_count)
		.def_readwrite("likelihood", &td::likelihood)
		.def_readwrite("flux", &td::flux)
		.def("__repr__", [](const td &t) {
			return "ix: " + to_string(t.ix) +
                              " iy: " + to_string(t.iy) +
			      " fx: " + to_string(t.fx) +
                              " fy: " + to_string(t.fy) +
			   " depth: " + to_string(static_cast<int>(t.depth)) +
                       " obs_count: " + to_string(static_cast<int>(t.obs_count)) +
			      " lh: " + to_string(t.likelihood) +
			     " flux " + to_string(t.flux);
			}
		);
}

<|endoftext|>


<commit_before>#include <geometry_msgs/Quaternion.h>
#include <ros/ros.h>
#include <serial/serial.h>
#include <sensor_msgs/Imu.h>
#include <std_msgs/String.h>
#include <std_srvs/Empty.h>
#include <string>
#include <tf/transform_broadcaster.h>
#include <tf/transform_datatypes.h>

bool zero_orientation_set = false;

bool set_zero_orientation(std_srvs::Empty::Request&,
                          std_srvs::Empty::Response&)
{
  ROS_INFO("Zero Orientation Set.");
  zero_orientation_set = false;
  return true;
}

int main(int argc, char** argv)
{
  serial::Serial ser;
  std::string port;
  std::string tf_parent_frame_id;
  std::string tf_frame_id;
  std::string imu_frame_id;
  double time_offset_in_seconds;

  tf::Quaternion orientation;
  tf::Quaternion zero_orientation;

  std::string partial_line = "";

  ros::init(argc, argv, "mpu6050_serial_to_imu_node");

  ros::NodeHandle private_node_handle("~");
  private_node_handle.param<std::string>("port", port, "/dev/ttyACM0");
  private_node_handle.param<std::string>("tf_parent_frame_id", tf_parent_frame_id, "imu_base");
  private_node_handle.param<std::string>("tf_frame_id", tf_frame_id, "imu");
  private_node_handle.param<std::string>("imu_frame_id", imu_frame_id, "imu_base");
  private_node_handle.param<double>("time_offset_in_seconds", time_offset_in_seconds, 0.0);

  ros::NodeHandle nh;
  ros::Publisher imu_pub = nh.advertise<sensor_msgs::Imu>("imu", 50);
  ros::ServiceServer service = nh.advertiseService("set_zero_orientation", set_zero_orientation);

  ros::Rate r(1000); // 1000 hz

  while(ros::ok())
  {
    try
    {
      if (ser.isOpen())
      {
        // read string from serial device
        if(ser.available())
        {
          std_msgs::String result;
          result.data = ser.readline(ser.available(), "\n");

          std::string input = partial_line + result.data;

          if (input.at( input.length() - 1 ) == '\n')
          {
            // line complete, delete partial_line var
            partial_line = "";

            // TODO check if line is long enough??
            if (input.compare(0,53,"Send any character to begin DMP programming and demo:") == 0 )
            {
              ROS_DEBUG("Sending 'A'");
              ser.write("A");
            }

            // parse line, get quaternion values
            if (input.compare(0,2,"$\x02") == 0 && (input.size() == 14))
            {
              uint w = (((0xff &(char)input[2]) << 8) | 0xff &(char)input[3]);
              ROS_DEBUG("w = %04x", w );

              uint x = (((0xff &(char)input[4]) << 8) | 0xff &(char)input[5]);
              ROS_DEBUG("x = %04x", x );

              uint y = (((0xff &(char)input[6]) << 8) | 0xff &(char)input[7]);
              ROS_DEBUG("y = %04x", y );

              uint z = (((0xff &(char)input[8]) << 8) | 0xff &(char)input[9]);
              ROS_DEBUG("z = %04x", z );

              double wf = w/16384.0;
              double xf = x/16384.0;
              double yf = y/16384.0;
              double zf = z/16384.0;

              if (wf >= 2.0)
              {
                wf = -4.0 +wf;
              }

              if (xf >= 2.0)
              {
                xf = -4.0 +xf;
              }

              if (yf >= 2.0)
              {
                yf = -4.0 +yf;
              }

              if (zf >= 2.0)
              {
                zf = -4.0 +zf;
              }

              tf::Quaternion orientation(xf, yf, zf, wf);

              if (!zero_orientation_set)
              {
                zero_orientation = orientation;
                zero_orientation_set = true;
              }

              //http://answers.ros.org/question/10124/relative-rotation-between-two-quaternions/
              tf::Quaternion differential_rotation;
              differential_rotation = zero_orientation.inverse() * orientation;

              // calculate measurement time
              ros::Time measurement_time = ros::Time::now() + ros::Duration(time_offset_in_seconds);

              // publish imu message
              sensor_msgs::Imu imu;
              imu.header.stamp = measurement_time;
              imu.header.frame_id = imu_frame_id;

              quaternionTFToMsg(differential_rotation, imu.orientation);

              // i do not know the orientation covariance
              imu.orientation_covariance[0] = 0;
              imu.orientation_covariance[1] = 0;
              imu.orientation_covariance[2] = 0;
              imu.orientation_covariance[3] = 0;
              imu.orientation_covariance[4] = 0;
              imu.orientation_covariance[5] = 0;
              imu.orientation_covariance[6] = 0;
              imu.orientation_covariance[7] = 0;
              imu.orientation_covariance[8] = 0;

              // angular velocity is not provided
              imu.angular_velocity_covariance[0] = -1;

              // linear acceleration is not provided
              imu.linear_acceleration_covariance[0] = -1;

              imu_pub.publish(imu);

              // publish tf transform
              static tf::TransformBroadcaster br;
              tf::Transform transform;
              transform.setRotation(differential_rotation);
              br.sendTransform(tf::StampedTransform(transform, measurement_time, tf_parent_frame_id, tf_frame_id));
            }
          }
          else
          {
            // line incomplete, remember already received characters
            partial_line = input;
          }
        }
        else  // ser not available
        {

        }
      }
      else
      {
        // try and open the serial port
        try
        {
          ser.setPort(port);
          ser.setBaudrate(115200);
          serial::Timeout to = serial::Timeout::simpleTimeout(1000);
          ser.setTimeout(to);
          ser.open();
        }
        catch (serial::IOException& e)
        {
          ROS_ERROR_STREAM("Unable to open serial port " << ser.getPort() << ". Trying again in 5 seconds.");
          ros::Duration(5).sleep();
        }

        if(ser.isOpen())
        {
          ROS_DEBUG_STREAM("Serial port " << ser.getPort() << " initialized.");
        }
        else
        {
          //ROS_INFO_STREAM("Could not initialize serial port.");
        }

      }
    }
    catch (serial::IOException& e)
    {
      ROS_ERROR_STREAM("Error reading from the serial port " << ser.getPort() << ". Closing connection.");
      ser.close();
    }
    ros::spinOnce();
    r.sleep();
  }
}

<commit_msg>changed comment and output<commit_after>#include <geometry_msgs/Quaternion.h>
#include <ros/ros.h>
#include <serial/serial.h>
#include <sensor_msgs/Imu.h>
#include <std_msgs/String.h>
#include <std_srvs/Empty.h>
#include <string>
#include <tf/transform_broadcaster.h>
#include <tf/transform_datatypes.h>

bool zero_orientation_set = false;

bool set_zero_orientation(std_srvs::Empty::Request&,
                          std_srvs::Empty::Response&)
{
  ROS_INFO("Zero Orientation Set.");
  zero_orientation_set = false;
  return true;
}

int main(int argc, char** argv)
{
  serial::Serial ser;
  std::string port;
  std::string tf_parent_frame_id;
  std::string tf_frame_id;
  std::string imu_frame_id;
  double time_offset_in_seconds;

  tf::Quaternion orientation;
  tf::Quaternion zero_orientation;

  std::string partial_line = "";

  ros::init(argc, argv, "mpu6050_serial_to_imu_node");

  ros::NodeHandle private_node_handle("~");
  private_node_handle.param<std::string>("port", port, "/dev/ttyACM0");
  private_node_handle.param<std::string>("tf_parent_frame_id", tf_parent_frame_id, "imu_base");
  private_node_handle.param<std::string>("tf_frame_id", tf_frame_id, "imu");
  private_node_handle.param<std::string>("imu_frame_id", imu_frame_id, "imu_base");
  private_node_handle.param<double>("time_offset_in_seconds", time_offset_in_seconds, 0.0);

  ros::NodeHandle nh;
  ros::Publisher imu_pub = nh.advertise<sensor_msgs::Imu>("imu", 50);
  ros::ServiceServer service = nh.advertiseService("set_zero_orientation", set_zero_orientation);

  ros::Rate r(1000); // 1000 hz

  while(ros::ok())
  {
    try
    {
      if (ser.isOpen())
      {
        // read string from serial device
        if(ser.available())
        {
          std_msgs::String result;
          result.data = ser.readline(ser.available(), "\n");

          std::string input = partial_line + result.data;

          if (input.at( input.length() - 1 ) == '\n')
          {
            // line complete, delete partial_line var
            partial_line = "";

            // TODO: check if line is long enough??

            if (input.compare(0,53,"Send any character to begin DMP programming and demo:") == 0 )
            {
              ROS_DEBUG("Sending 'A' to start sending of IMU data.");
              ser.write("A");
            }

            // parse line, get quaternion values
            if (input.compare(0,2,"$\x02") == 0 && (input.size() == 14))
            {
              uint w = (((0xff &(char)input[2]) << 8) | 0xff &(char)input[3]);
              ROS_DEBUG("w = %04x", w );

              uint x = (((0xff &(char)input[4]) << 8) | 0xff &(char)input[5]);
              ROS_DEBUG("x = %04x", x );

              uint y = (((0xff &(char)input[6]) << 8) | 0xff &(char)input[7]);
              ROS_DEBUG("y = %04x", y );

              uint z = (((0xff &(char)input[8]) << 8) | 0xff &(char)input[9]);
              ROS_DEBUG("z = %04x", z );

              double wf = w/16384.0;
              double xf = x/16384.0;
              double yf = y/16384.0;
              double zf = z/16384.0;

              if (wf >= 2.0)
              {
                wf = -4.0 +wf;
              }

              if (xf >= 2.0)
              {
                xf = -4.0 +xf;
              }

              if (yf >= 2.0)
              {
                yf = -4.0 +yf;
              }

              if (zf >= 2.0)
              {
                zf = -4.0 +zf;
              }

              tf::Quaternion orientation(xf, yf, zf, wf);

              if (!zero_orientation_set)
              {
                zero_orientation = orientation;
                zero_orientation_set = true;
              }

              //http://answers.ros.org/question/10124/relative-rotation-between-two-quaternions/
              tf::Quaternion differential_rotation;
              differential_rotation = zero_orientation.inverse() * orientation;

              // calculate measurement time
              ros::Time measurement_time = ros::Time::now() + ros::Duration(time_offset_in_seconds);

              // publish imu message
              sensor_msgs::Imu imu;
              imu.header.stamp = measurement_time;
              imu.header.frame_id = imu_frame_id;

              quaternionTFToMsg(differential_rotation, imu.orientation);

              // i do not know the orientation covariance
              imu.orientation_covariance[0] = 0;
              imu.orientation_covariance[1] = 0;
              imu.orientation_covariance[2] = 0;
              imu.orientation_covariance[3] = 0;
              imu.orientation_covariance[4] = 0;
              imu.orientation_covariance[5] = 0;
              imu.orientation_covariance[6] = 0;
              imu.orientation_covariance[7] = 0;
              imu.orientation_covariance[8] = 0;

              // angular velocity is not provided
              imu.angular_velocity_covariance[0] = -1;

              // linear acceleration is not provided
              imu.linear_acceleration_covariance[0] = -1;

              imu_pub.publish(imu);

              // publish tf transform
              static tf::TransformBroadcaster br;
              tf::Transform transform;
              transform.setRotation(differential_rotation);
              br.sendTransform(tf::StampedTransform(transform, measurement_time, tf_parent_frame_id, tf_frame_id));
            }
          }
          else
          {
            // line incomplete, remember already received characters
            partial_line = input;
          }
        }
        else  // ser not available
        {

        }
      }
      else
      {
        // try and open the serial port
        try
        {
          ser.setPort(port);
          ser.setBaudrate(115200);
          serial::Timeout to = serial::Timeout::simpleTimeout(1000);
          ser.setTimeout(to);
          ser.open();
        }
        catch (serial::IOException& e)
        {
          ROS_ERROR_STREAM("Unable to open serial port " << ser.getPort() << ". Trying again in 5 seconds.");
          ros::Duration(5).sleep();
        }

        if(ser.isOpen())
        {
          ROS_DEBUG_STREAM("Serial port " << ser.getPort() << " initialized.");
        }
        else
        {
          //ROS_INFO_STREAM("Could not initialize serial port.");
        }

      }
    }
    catch (serial::IOException& e)
    {
      ROS_ERROR_STREAM("Error reading from the serial port " << ser.getPort() << ". Closing connection.");
      ser.close();
    }
    ros::spinOnce();
    r.sleep();
  }
}

<|endoftext|>


<commit_before>// sample.hxx -- Sound sample encapsulation class
//
// Written by Curtis Olson, started April 2004.
//
// Copyright (C) 2004  Curtis L. Olson - curt@flightgear.org
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// $Id$

/**
 * \file sample.hxx
 * Provides a sound sample encapsulation
 */

#ifndef _SG_SAMPLE_HXX
#define _SG_SAMPLE_HXX 1

#ifndef __cplusplus
# error This library requires C++
#endif

#include <simgear/compiler.h>

#include <AL/al.h>

#include <simgear/debug/logstream.hxx>

/**
 * manages everything we need to know for an individual sound sample
 */

class SGSoundSample {

private:

    // Buffers hold sound data.
    ALuint buffer;

    // Sources are points emitting sound.
    ALuint source;

    // Position of the source sound.
    ALfloat source_pos[3];

    // Velocity of the source sound.
    ALfloat source_vel[3];

    // configuration values
    ALenum format;
    ALsizei size;
    ALvoid* data;
    ALsizei freq;

    double pitch;
    double volume;
    ALboolean loop;

public:

    SGSoundSample( const char *path, const char *file );
    SGSoundSample( unsigned char *_data, int len, int _freq );
    ~SGSoundSample();

    /**
     * Start playing this sample.
     *
     * @param looped Define wether the sound should be played in a loop.
     */
    void play( bool _loop );

    /**
     * Stop playing this sample.
     *
     * @param sched A pointer to the appropriate scheduler.
     */
    void stop();

    /**
     * Play this sample once.
     * @see #play
     */
    inline void play_once() { play(false); }

    /**
     * Play this sample looped.
     * @see #play
     */
    inline void play_looped() { play(true); }

    /**
     * Test if a sample is curretnly playing.
     * @return true if is is playing, false otherwise.
     */
    inline bool is_playing( ) {
        ALint result;
        alGetSourcei( source, AL_SOURCE_STATE, &result );
        if ( alGetError() != AL_NO_ERROR) {
            SG_LOG( SG_GENERAL, SG_ALERT,
                    "Oops AL error in sample is_playing()!" );
        }
        return (result == AL_PLAYING) ;
    }

    /**
     * Get the current pitch setting of this sample.
     */
    inline double get_pitch() const { return pitch; }

    /**
     * Set the pitch of this sample.
     */
    inline void set_pitch( double p ) {
        pitch = p;
        alSourcef( source, AL_PITCH, pitch );
        if ( alGetError() != AL_NO_ERROR) {
            SG_LOG( SG_GENERAL, SG_ALERT,
                    "Oops AL error in sample set_pitch()! " << p );
        }
    }

    /**
     * Get the current volume setting of this sample.
     */
    inline double get_volume() const { return volume; }

    /**
     * Set the volume of this sample.
     */
    inline void set_volume( double v ) {
        volume = v;
        alSourcef( source, AL_GAIN, volume );
        if ( alGetError() != AL_NO_ERROR) {
            SG_LOG( SG_GENERAL, SG_ALERT,
                    "Oops AL error in sample set_volume()!" );
        }
    }

    /**
     * Returns the size of the sounds sample
     */
    inline int get_size() {
        return size;
    }

    /**
     * Return a pointer to the raw data
     */
    inline char *get_data() {
        return (char *)data;
    }
};

#endif // _SG_SAMPLE_HXX

<commit_msg>Clamp pitch values rather than just dumping an error message.<commit_after>// sample.hxx -- Sound sample encapsulation class
//
// Written by Curtis Olson, started April 2004.
//
// Copyright (C) 2004  Curtis L. Olson - curt@flightgear.org
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// $Id$

/**
 * \file sample.hxx
 * Provides a sound sample encapsulation
 */

#ifndef _SG_SAMPLE_HXX
#define _SG_SAMPLE_HXX 1

#ifndef __cplusplus
# error This library requires C++
#endif

#include <simgear/compiler.h>

#include <AL/al.h>

#include <simgear/debug/logstream.hxx>

/**
 * manages everything we need to know for an individual sound sample
 */

class SGSoundSample {

private:

    // Buffers hold sound data.
    ALuint buffer;

    // Sources are points emitting sound.
    ALuint source;

    // Position of the source sound.
    ALfloat source_pos[3];

    // Velocity of the source sound.
    ALfloat source_vel[3];

    // configuration values
    ALenum format;
    ALsizei size;
    ALvoid* data;
    ALsizei freq;

    double pitch;
    double volume;
    ALboolean loop;

public:

    SGSoundSample( const char *path, const char *file );
    SGSoundSample( unsigned char *_data, int len, int _freq );
    ~SGSoundSample();

    /**
     * Start playing this sample.
     *
     * @param looped Define wether the sound should be played in a loop.
     */
    void play( bool _loop );

    /**
     * Stop playing this sample.
     *
     * @param sched A pointer to the appropriate scheduler.
     */
    void stop();

    /**
     * Play this sample once.
     * @see #play
     */
    inline void play_once() { play(false); }

    /**
     * Play this sample looped.
     * @see #play
     */
    inline void play_looped() { play(true); }

    /**
     * Test if a sample is curretnly playing.
     * @return true if is is playing, false otherwise.
     */
    inline bool is_playing( ) {
        ALint result;
        alGetSourcei( source, AL_SOURCE_STATE, &result );
        if ( alGetError() != AL_NO_ERROR) {
            SG_LOG( SG_GENERAL, SG_ALERT,
                    "Oops AL error in sample is_playing()!" );
        }
        return (result == AL_PLAYING) ;
    }

    /**
     * Get the current pitch setting of this sample.
     */
    inline double get_pitch() const { return pitch; }

    /**
     * Set the pitch of this sample.
     */
    inline void set_pitch( double p ) {
        // clamp in the range of 0.01 to 2.0
        if ( p < 0.01 ) { p = 0.01; }
        if ( p > 2.0 ) { p = 2.0; }
        pitch = p;
        alSourcef( source, AL_PITCH, pitch );
        if ( alGetError() != AL_NO_ERROR) {
            SG_LOG( SG_GENERAL, SG_ALERT,
                    "Oops AL error in sample set_pitch()! " << p );
        }
    }

    /**
     * Get the current volume setting of this sample.
     */
    inline double get_volume() const { return volume; }

    /**
     * Set the volume of this sample.
     */
    inline void set_volume( double v ) {
        volume = v;
        alSourcef( source, AL_GAIN, volume );
        if ( alGetError() != AL_NO_ERROR) {
            SG_LOG( SG_GENERAL, SG_ALERT,
                    "Oops AL error in sample set_volume()!" );
        }
    }

    /**
     * Returns the size of the sounds sample
     */
    inline int get_size() {
        return size;
    }

    /**
     * Return a pointer to the raw data
     */
    inline char *get_data() {
        return (char *)data;
    }
};

#endif // _SG_SAMPLE_HXX

<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
//                         PelotonDB
//
// simple_optimizer.cpp
//
// Identification: /peloton/src/optimizer/simple_optimizer.cpp
//
// Copyright (c) 2016, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "optimizer/simple_optimizer.h"
#include "parser/peloton/abstract_parse.h"
#include "planner/abstract_plan.h"

#include "common/logger.h"

#include <memory>

namespace peloton {
namespace optimizer {

SimpleOptimizer::SimpleOptimizer() {
}
;

SimpleOptimizer::~SimpleOptimizer() {
}
;

std::shared_ptr<planner::AbstractPlan> SimpleOptimizer::BuildPlanTree(
    const std::unique_ptr<parser::AbstractParse>& parse_tree) {

  std::shared_ptr<planner::AbstractPlan> plan_tree;
  if (parse_tree.get() == nullptr)
     return plan_tree;

// std::unique_ptr<planner::AbstractPlan> child_plan;
//
//  // TODO: Transform the parse tree
//
//  // One to one Mapping
//  auto parse_item_node_type = parse_tree->GetParseNodeType();
//
//  switch(parse_item_node_type){
//    case PARSE_NODE_TYPE_DROP:
//      child_plan = std::make_unique(new planner::DropPlan("department-table"));
//      break;
//
//    case PARSE_NODE_TYPE_SCAN:
//      child_plan = std::make_unique(new planner::SeqScanPlan());
//      break;
//
//    default:
//      LOG_INFO("Unsupported Parse Node Type");
//  }
//
//// Need to recurse and give base case. for every child in parse tree.
//
//  if (child_plan != nullptr) {
//      if (plan_tree != nullptr)
//        plan_tree->AddChild(std::move(child_plan));
//      else
//        plan_tree = child_plan;
//    }

  return plan_tree;
}

}  // namespace optimizer
}  // namespace peloton
<commit_msg>uncommented simple optimizer .. checking for more bugs<commit_after>//===----------------------------------------------------------------------===//
//
//                         PelotonDB
//
// simple_optimizer.cpp
//
// Identification: /peloton/src/optimizer/simple_optimizer.cpp
//
// Copyright (c) 2016, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "optimizer/simple_optimizer.h"
#include "parser/peloton/abstract_parse.h"
#include "planner/abstract_plan.h"

#include "common/logger.h"

#include <memory>

namespace peloton {
namespace optimizer {

SimpleOptimizer::SimpleOptimizer() {
}
;

SimpleOptimizer::~SimpleOptimizer() {
}
;

std::shared_ptr<planner::AbstractPlan> SimpleOptimizer::BuildPlanTree(
    const std::unique_ptr<parser::AbstractParse>& parse_tree) {

  std::shared_ptr<planner::AbstractPlan> plan_tree;
  if (parse_tree.get() == nullptr)
     return plan_tree;

 std::unique_ptr<planner::AbstractPlan> child_plan;

  // TODO: Transform the parse tree

  // One to one Mapping
  auto parse_item_node_type = parse_tree->GetParseNodeType();

  switch(parse_item_node_type){
    case PARSE_NODE_TYPE_DROP:
      child_plan = std::make_unique(new planner::DropPlan("department-table"));
      break;

    case PARSE_NODE_TYPE_SCAN:
      child_plan = std::make_unique(new planner::SeqScanPlan());
      break;

    default:
      LOG_INFO("Unsupported Parse Node Type");
  }

// Need to recurse and give base case. for every child in parse tree.

  if (child_plan != nullptr) {
      if (plan_tree != nullptr)
        plan_tree->AddChild(std::move(child_plan));
      else
        plan_tree = child_plan;
    }

  return plan_tree;
}

}  // namespace optimizer
}  // namespace peloton
<|endoftext|>


<commit_before>/** @file
    @brief Implementation

    @date 2015

    @author
    Sensics, Inc.
    <http://sensics.com/osvr>
*/

// Copyright 2015 Sensics, Inc.
//
// All rights reserved.
//
// (Final version intended to be licensed under
// the Apache License, Version 2.0)

// Internal Includes
#include <osvr/Server/RouteContainer.h>

// Library/third-party includes
#include <json/value.h>
#include <json/reader.h>
#include <json/writer.h>

// Standard includes
#include <stdexcept>
#include <functional>
#include <algorithm>

namespace osvr {
namespace server {

    static inline Json::Value
    parseRoutingDirective(std::string const &routingDirective) {
        Json::Reader reader;
        Json::Value val;
        if (!reader.parse(routingDirective, val)) {
            throw std::runtime_error("Invalid JSON routing directive: " +
                                     routingDirective);
        }
        return val;
    }

    static const char DESTINATION_KEY[] = "destination";
    static inline std::string
    getDestination(Json::Value const &routingDirective) {
        return routingDirective.get(DESTINATION_KEY, "").asString();
    }
    static inline std::string toFastString(Json::Value const &val) {
        Json::FastWriter writer;
        return writer.write(val);
    }
    RouteContainer::RouteContainer() {}

    RouteContainer::RouteContainer(std::string const &routes) {
        Json::Reader reader;
        Json::Value routesVal;
        if (!reader.parse(routes, routesVal)) {
            throw std::runtime_error("Invalid JSON routing directive array: " +
                                     routes);
        }
        for (Json::ArrayIndex i = 0, e = routesVal.size(); i < e; ++i) {
            const Json::Value thisRoute = routesVal[i];
            m_addRoute(getDestination(thisRoute), toFastString(thisRoute));
        }
    }

    bool RouteContainer::addRoute(std::string const &routingDirective) {
        auto route = parseRoutingDirective(routingDirective);
        return m_addRoute(getDestination(route), routingDirective);
    }

    std::string RouteContainer::getRoutes(bool styled) const {
        Json::Value routes(Json::arrayValue);
        for (auto const &r : m_routingDirectives) {
            routes.append(parseRoutingDirective(r));
        }
        if (styled) {
            return routes.toStyledString();
        } else {
            return toFastString(routes);
        }
    }

    std::string
    RouteContainer::getSource(std::string const &destination) const {
        auto it =
            std::find_if(begin(m_routingDirectives), end(m_routingDirectives),
                         [&](std::string const &directive) {
            return (getDestination(parseRoutingDirective(directive)) ==
                    destination);
        });
        if (it != end(m_routingDirectives)) {
            return *it;
        } else {
            return std::string();
        }
    }

    bool RouteContainer::m_addRoute(std::string const &destination,
                                    std::string const &routingDirective) {
        bool replaced = false;
        /// If a route already exists with the same destination, replace it
        /// with this new one.
        std::replace_if(
            begin(m_routingDirectives),
            end(m_routingDirectives), [&](std::string const &directive) {
            Json::Value candidate = parseRoutingDirective(directive);
            bool match = (getDestination(candidate) == destination);
            if (match) {
                replaced = true;
            }
            return match;
        }, routingDirective);

        /// If we didn't replace an existing route, just add this one.
        if (!replaced) {
            m_routingDirectives.push_back(routingDirective);
        }
        return !replaced;
    }
} // namespace server
} // namespace osvr<commit_msg>Fix getSource to do what it says it will.<commit_after>/** @file
    @brief Implementation

    @date 2015

    @author
    Sensics, Inc.
    <http://sensics.com/osvr>
*/

// Copyright 2015 Sensics, Inc.
//
// All rights reserved.
//
// (Final version intended to be licensed under
// the Apache License, Version 2.0)

// Internal Includes
#include <osvr/Server/RouteContainer.h>

// Library/third-party includes
#include <json/value.h>
#include <json/reader.h>
#include <json/writer.h>

// Standard includes
#include <stdexcept>
#include <functional>
#include <algorithm>

namespace osvr {
namespace server {

    static inline Json::Value
    parseRoutingDirective(std::string const &routingDirective) {
        Json::Reader reader;
        Json::Value val;
        if (!reader.parse(routingDirective, val)) {
            throw std::runtime_error("Invalid JSON routing directive: " +
                                     routingDirective);
        }
        return val;
    }

    static const char DESTINATION_KEY[] = "destination";

    static inline std::string
    getDestination(Json::Value const &routingDirective) {
        return routingDirective.get(DESTINATION_KEY, "").asString();
    }
    static inline std::string toFastString(Json::Value const &val) {
        Json::FastWriter writer;
        return writer.write(val);
    }
    RouteContainer::RouteContainer() {}

    RouteContainer::RouteContainer(std::string const &routes) {
        Json::Reader reader;
        Json::Value routesVal;
        if (!reader.parse(routes, routesVal)) {
            throw std::runtime_error("Invalid JSON routing directive array: " +
                                     routes);
        }
        for (Json::ArrayIndex i = 0, e = routesVal.size(); i < e; ++i) {
            const Json::Value thisRoute = routesVal[i];
            m_addRoute(getDestination(thisRoute), toFastString(thisRoute));
        }
    }

    bool RouteContainer::addRoute(std::string const &routingDirective) {
        auto route = parseRoutingDirective(routingDirective);
        return m_addRoute(getDestination(route), routingDirective);
    }

    std::string RouteContainer::getRoutes(bool styled) const {
        Json::Value routes(Json::arrayValue);
        for (auto const &r : m_routingDirectives) {
            routes.append(parseRoutingDirective(r));
        }
        if (styled) {
            return routes.toStyledString();
        } else {
            return toFastString(routes);
        }
    }

    static const char SOURCE_KEY[] = "source";
    std::string
    RouteContainer::getSource(std::string const &destination) const {
        auto it =
            std::find_if(begin(m_routingDirectives), end(m_routingDirectives),
                         [&](std::string const &directive) {
            return (getDestination(parseRoutingDirective(directive)) ==
                    destination);
        });
        if (it != end(m_routingDirectives)) {
            Json::Value directive = parseRoutingDirective(*it);
            if (directive.isMember(SOURCE_KEY)) {
                return directive[SOURCE_KEY].toStyledString();
            }
        }
        return std::string();
    }

    bool RouteContainer::m_addRoute(std::string const &destination,
                                    std::string const &routingDirective) {
        bool replaced = false;
        /// If a route already exists with the same destination, replace it
        /// with this new one.
        std::replace_if(
            begin(m_routingDirectives),
            end(m_routingDirectives), [&](std::string const &directive) {
            Json::Value candidate = parseRoutingDirective(directive);
            bool match = (getDestination(candidate) == destination);
            if (match) {
                replaced = true;
            }
            return match;
        }, routingDirective);

        /// If we didn't replace an existing route, just add this one.
        if (!replaced) {
            m_routingDirectives.push_back(routingDirective);
        }
        return !replaced;
    }
} // namespace server
} // namespace osvr<|endoftext|>


<commit_before>#include "DartResource.h"
#include "private/AbstractResource_p.h"

#include <QtCore/QDebug>
#include <QtCore/QProcess>

namespace web
{
namespace page
{
namespace resource
{

class DartResourcePrivate : public AbstractResourcePrivate
{
    public:
        QString dartFileName;
};

const QString DART2JS_SCRIPT = QStringLiteral("../../../../dart/dart-sdk/bin/dart2js");

DartResource::DartResource(const QString &dartFile, const QString &jsFile) :
    AbstractResource(new DartResourcePrivate)
{
    Q_D(DartResource);

    d->fileName = jsFile;
    d->dartFileName = dartFile;

    compileDartFile();
}

void DartResource::compileDartFile()
{
    Q_D(DartResource);
    QStringList arguments;
#ifdef QT_WEBFRAMEWORK_DEBUG
    arguments << QStringLiteral("--checked")
              << QStringLiteral("--out=") + d->fileName
              << d->dartFileName;
#else
#endif

    QProcess::startDetached(DART2JS_SCRIPT, arguments);
}

}
}
}
<commit_msg>Different arguments for the dart2js executable<commit_after>#include "DartResource.h"
#include "private/AbstractResource_p.h"

#include <QtCore/QDebug>
#include <QtCore/QProcess>

namespace web
{
namespace page
{
namespace resource
{

class DartResourcePrivate : public AbstractResourcePrivate
{
    public:
        QString dartFileName;
};

const QString DART2JS_SCRIPT = QStringLiteral("../../../../dart/dart-sdk/bin/dart2js");

DartResource::DartResource(const QString &dartFile, const QString &jsFile) :
    AbstractResource(new DartResourcePrivate)
{
    Q_D(DartResource);

    d->fileName = jsFile;
    d->dartFileName = dartFile;

    compileDartFile();
}

void DartResource::compileDartFile()
{
    Q_D(DartResource);
    QStringList arguments;
#ifdef QT_WEBFRAMEWORK_DEBUG
    arguments << QStringLiteral("--checked")
              << QStringLiteral("--out=") + d->fileName
              << d->dartFileName;
#else
    arguments << QStringLiteral("--minify")
              << QStringLiteral("--out=") + d->fileName
              << d->dartFileName;
#endif

    QProcess::startDetached(DART2JS_SCRIPT, arguments);
}

}
}
}
<|endoftext|>


<commit_before>#include "MotionControl.hpp"
#include <Geometry2d/Util.hpp>
#include <Robot.hpp>
#include <RobotConfig.hpp>
#include <SystemState.hpp>
#include <Utils.hpp>
#include <planning/MotionInstant.hpp>
#include "TrapezoidalMotion.hpp"

#include <stdio.h>
#include <algorithm>

using namespace std;
using namespace Geometry2d;
using namespace Planning;

#pragma mark Config Variables

REGISTER_CONFIGURABLE(MotionControl);

ConfigDouble* MotionControl::_max_acceleration;
ConfigDouble* MotionControl::_max_velocity;

void MotionControl::createConfiguration(Configuration* cfg) {
    _max_acceleration =
        new ConfigDouble(cfg, "MotionControl/Max Acceleration", 1.5);
    _max_velocity = new ConfigDouble(cfg, "MotionControl/Max Velocity", 2.0);
}

#pragma mark MotionControl

MotionControl::MotionControl(OurRobot* robot) : _angleController(0, 0, 0, 50) {
    _robot = robot;

    _robot->robotPacket.set_uid(_robot->shell());
}

void MotionControl::run() {
    if (!_robot) return;

    const MotionConstraints& constraints = _robot->motionConstraints();

    // update PID parameters
    _positionXController.kp = *_robot->config->translation.p;
    _positionXController.ki = *_robot->config->translation.i;
    _positionXController.setWindup(*_robot->config->translation.i_windup);
    _positionXController.kd = *_robot->config->translation.d;
    _positionYController.kp = *_robot->config->translation.p;
    _positionYController.ki = *_robot->config->translation.i;
    _positionYController.setWindup(*_robot->config->translation.i_windup);
    _positionYController.kd = *_robot->config->translation.d;
    _angleController.kp = *_robot->config->rotation.p;
    _angleController.ki = *_robot->config->rotation.i;
    _angleController.kd = *_robot->config->rotation.d;

    RJ::Seconds timeIntoPath =
        (RJ::now() - _robot->path().startTime()) + RJ::Seconds(1.0 / 60);

    // evaluate path - where should we be right now?
    boost::optional<RobotInstant> optTarget =
        _robot->path().evaluate(timeIntoPath);

    if (!optTarget) {
        optTarget = _robot->path().end();
        _robot->state()->drawCircle(optTarget->motion.pos, .15, Qt::red,
                                    "Planning");
    } else {
        Point start = _robot->pos;
        _robot->state()->drawCircle(optTarget->motion.pos, .15, Qt::green,
                                    "Planning");
    }

    // Angle control //////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////

    float targetW = 0;
    auto& rotationCommand = _robot->rotationCommand();
    const auto& rotationConstraints = _robot->rotationConstraints();

    boost::optional<Geometry2d::Point> targetPt;
    const auto& motionCommand = _robot->motionCommand();

    boost::optional<float> targetAngleFinal;
    // if (motionCommand->getCommandType() == MotionCommand::Pivot) {
    //    PivotCommand command =
    //    *static_cast<PivotCommand*>(motionCommand.get());
    //    targetPt = command.pivotTarget;
    //} else {
    if (optTarget) {
        if (optTarget->angle) {
            if (optTarget->angle->angle) {
                targetAngleFinal = *optTarget->angle->angle;
            }
        }
    }
    //}

    if (targetPt) {
        // fixing the angle ensures that we don't go the long way around to get
        // to our final angle
        targetAngleFinal = (*targetPt - _robot->pos).angle();
    }

    if (!targetAngleFinal) {
        _targetAngleVel(0);
    } else {
        float angleError = fixAngleRadians(*targetAngleFinal - _robot->angle);

        targetW = _angleController.run(angleError);

        // limit W
        if (abs(targetW) > (rotationConstraints.maxSpeed)) {
            if (targetW > 0) {
                targetW = (rotationConstraints.maxSpeed);
            } else {
                targetW = -(rotationConstraints.maxSpeed);
            }
        }

        /*
        _robot->addText(QString("targetW: %1").arg(targetW));
        _robot->addText(QString("angleError: %1").arg(angleError));
        _robot->addText(QString("targetGlobalAngle: %1").arg(targetAngleFinal));
        _robot->addText(QString("angle: %1").arg(_robot->angle));
        */
        _targetAngleVel(targetW);
    }

    // handle body velocity for pivot command
    /*
    if (motionCommand->getCommandType() == MotionCommand::Pivot) {
        float r = Robot_Radius;
        const float FudgeFactor = *_robot->config->pivotVelMultiplier;
        float speed = RadiansToDegrees(r * targetW * FudgeFactor);
        Point vel(speed, 0);

        // the robot body coordinate system is wierd...
        vel.rotate(-M_PI_2);

        _targetBodyVel(vel);

        return;  // pivot handles both angle and position
    }
     */

    // Position control ///////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////
    MotionInstant target = optTarget->motion;

    // tracking error
    Point posError = target.pos - _robot->pos;

    // acceleration factor
    Point acceleration;
    boost::optional<RobotInstant> nextTarget =
        _robot->path().evaluate(timeIntoPath + RJ::Seconds(1) / 60.0);
    if (nextTarget) {
        acceleration = (nextTarget->motion.vel - target.vel) / 60.0f;
    } else {
        acceleration = {0, 0};
    }
    Point accelFactor =
        acceleration * 60.0f * (*_robot->config->accelerationMultiplier);

    target.vel += accelFactor;

    // PID on position
    target.vel.x() += _positionXController.run(posError.x());
    target.vel.y() += _positionYController.run(posError.y());

    // draw target pt
    _robot->state()->drawCircle(target.pos, .04, Qt::red, "MotionControl");
    _robot->state()->drawLine(target.pos, target.pos + target.vel, Qt::blue,
                              "MotionControl");

    // Clamp World Acceleration
    auto dt = RJ::Seconds(RJ::now() - _lastCmdTime);
    Point targetAccel = (target.vel - _lastWorldVelCmd) / dt.count();
    targetAccel.clamp(*_max_acceleration);

    target.vel = _lastWorldVelCmd + targetAccel * dt.count();

    _lastWorldVelCmd = target.vel;
    _lastCmdTime = RJ::now();

    // convert from world to body coordinates
    // the +y axis of the robot points forwards
    target.vel = target.vel.rotated(M_PI_2 - _robot->angle);

    this->_targetBodyVel(target.vel);
}

void MotionControl::stopped() {
    _targetBodyVel(Point(0, 0));
    _targetAngleVel(0);
}

void MotionControl::_targetAngleVel(float angleVel) {
    // velocity multiplier
    angleVel *= *_robot->config->angleVelMultiplier;

    // If the angular speed is very low, it won't make the robot move at all, so
    // we make sure it's above a threshold value
    float minEffectiveAngularSpeed = *_robot->config->minEffectiveAngularSpeed;
    if (std::abs(angleVel) < minEffectiveAngularSpeed &&
        std::abs(angleVel) > .05) {
        angleVel =
            angleVel > 0 ? minEffectiveAngularSpeed : -minEffectiveAngularSpeed;
    }

    // the robot firmware still speaks degrees, so that's how we send it over
    _robot->control->set_avelocity(angleVel);
}

void MotionControl::_targetBodyVel(Point targetVel) {
    // Limit Velocity
    targetVel.clamp(*_max_velocity);

    // Limit Acceleration

    // make sure we don't send any bad values
    if (std::isnan(targetVel.x()) || std::isnan(targetVel.y())) {
        targetVel = Point(0, 0);
        debugThrow("A bad value was calculated.");
    }

    // track these values so we can limit acceleration

    // velocity multiplier
    targetVel *= *_robot->config->velMultiplier;

    // if the velocity is nonzero, make sure it's not so small that the robot
    // doesn't even move
    float minEffectiveVelocity = *_robot->config->minEffectiveVelocity;
    if (targetVel.mag() < minEffectiveVelocity && targetVel.mag() > 0.02) {
        targetVel = targetVel.normalized() * minEffectiveVelocity;
    }

    // set control values
    _robot->control->set_xvelocity(targetVel.x());
    _robot->control->set_yvelocity(targetVel.y());
}
<commit_msg>Change AngleController constructor to match<commit_after>#include "MotionControl.hpp"
#include <Geometry2d/Util.hpp>
#include <Robot.hpp>
#include <RobotConfig.hpp>
#include <SystemState.hpp>
#include <Utils.hpp>
#include <planning/MotionInstant.hpp>
#include "TrapezoidalMotion.hpp"

#include <stdio.h>
#include <algorithm>

using namespace std;
using namespace Geometry2d;
using namespace Planning;

#pragma mark Config Variables

REGISTER_CONFIGURABLE(MotionControl);

ConfigDouble* MotionControl::_max_acceleration;
ConfigDouble* MotionControl::_max_velocity;

void MotionControl::createConfiguration(Configuration* cfg) {
    _max_acceleration =
        new ConfigDouble(cfg, "MotionControl/Max Acceleration", 1.5);
    _max_velocity = new ConfigDouble(cfg, "MotionControl/Max Velocity", 2.0);
}

#pragma mark MotionControl

MotionControl::MotionControl(OurRobot* robot) : _angleController(0, 0, 0, 0, 50) {
    _robot = robot;

    _robot->robotPacket.set_uid(_robot->shell());
}

void MotionControl::run() {
    if (!_robot) return;

    const MotionConstraints& constraints = _robot->motionConstraints();

    // update PID parameters
    _positionXController.kp = *_robot->config->translation.p;
    _positionXController.ki = *_robot->config->translation.i;
    _positionXController.setWindup(*_robot->config->translation.i_windup);
    _positionXController.kd = *_robot->config->translation.d;
    _positionYController.kp = *_robot->config->translation.p;
    _positionYController.ki = *_robot->config->translation.i;
    _positionYController.setWindup(*_robot->config->translation.i_windup);
    _positionYController.kd = *_robot->config->translation.d;
    _angleController.kp = *_robot->config->rotation.p;
    _angleController.ki = *_robot->config->rotation.i;
    _angleController.kd = *_robot->config->rotation.d;

    RJ::Seconds timeIntoPath =
        (RJ::now() - _robot->path().startTime()) + RJ::Seconds(1.0 / 60);

    // evaluate path - where should we be right now?
    boost::optional<RobotInstant> optTarget =
        _robot->path().evaluate(timeIntoPath);

    if (!optTarget) {
        optTarget = _robot->path().end();
        _robot->state()->drawCircle(optTarget->motion.pos, .15, Qt::red,
                                    "Planning");
    } else {
        Point start = _robot->pos;
        _robot->state()->drawCircle(optTarget->motion.pos, .15, Qt::green,
                                    "Planning");
    }

    // Angle control //////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////

    float targetW = 0;
    auto& rotationCommand = _robot->rotationCommand();
    const auto& rotationConstraints = _robot->rotationConstraints();

    boost::optional<Geometry2d::Point> targetPt;
    const auto& motionCommand = _robot->motionCommand();

    boost::optional<float> targetAngleFinal;
    // if (motionCommand->getCommandType() == MotionCommand::Pivot) {
    //    PivotCommand command =
    //    *static_cast<PivotCommand*>(motionCommand.get());
    //    targetPt = command.pivotTarget;
    //} else {
    if (optTarget) {
        if (optTarget->angle) {
            if (optTarget->angle->angle) {
                targetAngleFinal = *optTarget->angle->angle;
            }
        }
    }
    //}

    if (targetPt) {
        // fixing the angle ensures that we don't go the long way around to get
        // to our final angle
        targetAngleFinal = (*targetPt - _robot->pos).angle();
    }

    if (!targetAngleFinal) {
        _targetAngleVel(0);
    } else {
        float angleError = fixAngleRadians(*targetAngleFinal - _robot->angle);

        targetW = _angleController.run(angleError);

        // limit W
        if (abs(targetW) > (rotationConstraints.maxSpeed)) {
            if (targetW > 0) {
                targetW = (rotationConstraints.maxSpeed);
            } else {
                targetW = -(rotationConstraints.maxSpeed);
            }
        }

        /*
        _robot->addText(QString("targetW: %1").arg(targetW));
        _robot->addText(QString("angleError: %1").arg(angleError));
        _robot->addText(QString("targetGlobalAngle: %1").arg(targetAngleFinal));
        _robot->addText(QString("angle: %1").arg(_robot->angle));
        */
        _targetAngleVel(targetW);
    }

    // handle body velocity for pivot command
    /*
    if (motionCommand->getCommandType() == MotionCommand::Pivot) {
        float r = Robot_Radius;
        const float FudgeFactor = *_robot->config->pivotVelMultiplier;
        float speed = RadiansToDegrees(r * targetW * FudgeFactor);
        Point vel(speed, 0);

        // the robot body coordinate system is wierd...
        vel.rotate(-M_PI_2);

        _targetBodyVel(vel);

        return;  // pivot handles both angle and position
    }
     */

    // Position control ///////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////
    MotionInstant target = optTarget->motion;

    // tracking error
    Point posError = target.pos - _robot->pos;

    // acceleration factor
    Point acceleration;
    boost::optional<RobotInstant> nextTarget =
        _robot->path().evaluate(timeIntoPath + RJ::Seconds(1) / 60.0);
    if (nextTarget) {
        acceleration = (nextTarget->motion.vel - target.vel) / 60.0f;
    } else {
        acceleration = {0, 0};
    }
    Point accelFactor =
        acceleration * 60.0f * (*_robot->config->accelerationMultiplier);

    target.vel += accelFactor;

    // PID on position
    target.vel.x() += _positionXController.run(posError.x());
    target.vel.y() += _positionYController.run(posError.y());

    // draw target pt
    _robot->state()->drawCircle(target.pos, .04, Qt::red, "MotionControl");
    _robot->state()->drawLine(target.pos, target.pos + target.vel, Qt::blue,
                              "MotionControl");

    // Clamp World Acceleration
    auto dt = RJ::Seconds(RJ::now() - _lastCmdTime);
    Point targetAccel = (target.vel - _lastWorldVelCmd) / dt.count();
    targetAccel.clamp(*_max_acceleration);

    target.vel = _lastWorldVelCmd + targetAccel * dt.count();

    _lastWorldVelCmd = target.vel;
    _lastCmdTime = RJ::now();

    // convert from world to body coordinates
    // the +y axis of the robot points forwards
    target.vel = target.vel.rotated(M_PI_2 - _robot->angle);

    this->_targetBodyVel(target.vel);
}

void MotionControl::stopped() {
    _targetBodyVel(Point(0, 0));
    _targetAngleVel(0);
}

void MotionControl::_targetAngleVel(float angleVel) {
    // velocity multiplier
    angleVel *= *_robot->config->angleVelMultiplier;

    // If the angular speed is very low, it won't make the robot move at all, so
    // we make sure it's above a threshold value
    float minEffectiveAngularSpeed = *_robot->config->minEffectiveAngularSpeed;
    if (std::abs(angleVel) < minEffectiveAngularSpeed &&
        std::abs(angleVel) > .05) {
        angleVel =
            angleVel > 0 ? minEffectiveAngularSpeed : -minEffectiveAngularSpeed;
    }

    // the robot firmware still speaks degrees, so that's how we send it over
    _robot->control->set_avelocity(angleVel);
}

void MotionControl::_targetBodyVel(Point targetVel) {
    // Limit Velocity
    targetVel.clamp(*_max_velocity);

    // Limit Acceleration

    // make sure we don't send any bad values
    if (std::isnan(targetVel.x()) || std::isnan(targetVel.y())) {
        targetVel = Point(0, 0);
        debugThrow("A bad value was calculated.");
    }

    // track these values so we can limit acceleration

    // velocity multiplier
    targetVel *= *_robot->config->velMultiplier;

    // if the velocity is nonzero, make sure it's not so small that the robot
    // doesn't even move
    float minEffectiveVelocity = *_robot->config->minEffectiveVelocity;
    if (targetVel.mag() < minEffectiveVelocity && targetVel.mag() > 0.02) {
        targetVel = targetVel.normalized() * minEffectiveVelocity;
    }

    // set control values
    _robot->control->set_xvelocity(targetVel.x());
    _robot->control->set_yvelocity(targetVel.y());
}
<|endoftext|>