<commit_before>/******************************************************************************
 * rendersystem_bind.cpp - bindings for Ogre::RenderSystem
 ******************************************************************************
 * This file is part of
 *     __ __              _
 *    / // /_____ ____   (_)
 *   / // // ___// __ \ / /
 *  / // // /__ / /_/ // /
 * /_//_/ \___/ \____//_/
 *
 * Low Level C Ogre Interface (llcoi)
 *
 * See http://code.google.com/p/llcoi/ for more information.
 *
 * Copyright (c) 2011, Llcoi Team
 *
 * License: MIT
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 ******************************************************************************/
#include "ogre_interface.h"

#include <OgreRoot.h>
#include <OgreRenderSystem.h>

void add_render_system(RenderSystemHandle render_system)
{
    Ogre::RenderSystem* rs = reinterpret_cast<Ogre::RenderSystem*>(render_system);
    Ogre::Root::getSingletonPtr()->addRenderSystem(rs);
}

void set_render_system(RenderSystemHandle render_system)
{
    Ogre::RenderSystem* rs = reinterpret_cast<Ogre::RenderSystem*>(render_system);
    Ogre::Root::getSingletonPtr()->setRenderSystem(rs);
}

RenderSystemHandle get_render_system_by_name(const char* render_system_name)
{
    Ogre::RenderSystem* rs = Ogre::Root::getSingletonPtr()->getRenderSystemByName(render_system_name);
    return reinterpret_cast<RenderSystemHandle>(rs);
}

RenderSystemHandle get_render_system()
{
    return reinterpret_cast<RenderSystemHandle>(Ogre::Root::getSingletonPtr()->getRenderSystem());
}

void render_system_set_config_option(RenderSystemHandle render_system_handle, const char* option, const char* value)
{
    Ogre::RenderSystem* rs = reinterpret_cast<Ogre::RenderSystem*>(render_system_handle);
    rs->setConfigOption(option, value);
}

unsigned int render_system_list_size(RenderSystemListHandle list_handle)
{
    Ogre::RenderSystemList* rs_list = reinterpret_cast<Ogre::RenderSystemList*>(list_handle);
    return rs_list->size();
}

RenderSystemHandle render_system_list_get(RenderSystemListHandle list_handle, unsigned int index)
{
    Ogre::RenderSystemList* rs_list = reinterpret_cast<Ogre::RenderSystemList*>(list_handle);
    return rs_list->at(index);
}

void destroy_render_system_list(RenderSystemListHandle handle)
{
    Ogre::RenderSystemList* rs_list = reinterpret_cast<Ogre::RenderSystemList*>(handle);
    delete rs_list;
}

<commit_msg>added wrapping for RenderSystem::getName<commit_after>/******************************************************************************
 * rendersystem_bind.cpp - bindings for Ogre::RenderSystem
 ******************************************************************************
 * This file is part of
 *     __ __              _
 *    / // /_____ ____   (_)
 *   / // // ___// __ \ / /
 *  / // // /__ / /_/ // /
 * /_//_/ \___/ \____//_/
 *
 * Low Level C Ogre Interface (llcoi)
 *
 * See http://code.google.com/p/llcoi/ for more information.
 *
 * Copyright (c) 2011, Llcoi Team
 *
 * License: MIT
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 ******************************************************************************/
#include "ogre_interface.h"

#include <OgreRoot.h>
#include <OgreRenderSystem.h>

void add_render_system(RenderSystemHandle render_system)
{
    Ogre::RenderSystem* rs = reinterpret_cast<Ogre::RenderSystem*>(render_system);
    Ogre::Root::getSingletonPtr()->addRenderSystem(rs);
}

void set_render_system(RenderSystemHandle render_system)
{
    Ogre::RenderSystem* rs = reinterpret_cast<Ogre::RenderSystem*>(render_system);
    Ogre::Root::getSingletonPtr()->setRenderSystem(rs);
}

RenderSystemHandle get_render_system_by_name(const char* render_system_name)
{
    Ogre::RenderSystem* rs = Ogre::Root::getSingletonPtr()->getRenderSystemByName(render_system_name);
    return reinterpret_cast<RenderSystemHandle>(rs);
}

RenderSystemHandle get_render_system()
{
    return reinterpret_cast<RenderSystemHandle>(Ogre::Root::getSingletonPtr()->getRenderSystem());
}

void render_system_set_config_option(RenderSystemHandle render_system_handle, const char* option, const char* value)
{
    Ogre::RenderSystem* rs = reinterpret_cast<Ogre::RenderSystem*>(render_system_handle);
    rs->setConfigOption(option, value);
}

const char * render_system_get_name(RenderSystemHandle handle)
{
    Ogre::RenderSystem* rs = reinterpret_cast<Ogre::RenderSystem*>(handle);
    return rs->getName().c_str();
}

unsigned int render_system_list_size(RenderSystemListHandle list_handle)
{
    Ogre::RenderSystemList* rs_list = reinterpret_cast<Ogre::RenderSystemList*>(list_handle);
    return rs_list->size();
}

RenderSystemHandle render_system_list_get(RenderSystemListHandle list_handle, unsigned int index)
{
    Ogre::RenderSystemList* rs_list = reinterpret_cast<Ogre::RenderSystemList*>(list_handle);
    return rs_list->at(index);
}

void destroy_render_system_list(RenderSystemListHandle handle)
{
    Ogre::RenderSystemList* rs_list = reinterpret_cast<Ogre::RenderSystemList*>(handle);
    delete rs_list;
}

<|endoftext|>


<commit_before>/*
 @ Kingsley Chen
*/

#include "memory_bin.h"
<commit_msg>remove memory_bin.cpp<commit_after><|endoftext|>


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

#ifndef _DIF_HXX
#define _DIF_HXX

#ifndef _TOOLS_DEBUG_HXX //autogen
#include <tools/debug.hxx>
#endif

#ifndef _LIST_HXX //autogen
#include <tools/list.hxx>
#endif

#ifndef _STRING_HXX //autogen
#include <tools/string.hxx>
#endif

#ifndef SC_SCGLOB_HXX
#include "global.hxx"
#endif

#ifndef SC_ADDRESS_HXX
#include "address.hxx"
#endif

class SvStream;
class SvNumberFormatter;
class ScDocument;
class ScPatternAttr;

extern const sal_Unicode pKeyTABLE[];
extern const sal_Unicode pKeyVECTORS[];
extern const sal_Unicode pKeyTUPLES[];
extern const sal_Unicode pKeyDATA[];
extern const sal_Unicode pKeyBOT[];
extern const sal_Unicode pKeyEOD[];
extern const sal_Unicode pKeyTRUE[];
extern const sal_Unicode pKeyFALSE[];
extern const sal_Unicode pKeyNA[];
extern const sal_Unicode pKeyV[];
extern const sal_Unicode pKey1_0[];

enum TOPIC
{
    T_UNKNOWN,
    T_TABLE, T_VECTORS, T_TUPLES, T_DATA, T_LABEL, T_COMMENT, T_SIZE,
    T_PERIODICITY, T_MAJORSTART, T_MINORSTART, T_TRUELENGTH, T_UINITS,
    T_DISPLAYUNITS,
    T_END
};

enum DATASET { D_BOT, D_EOD, D_NUMERIC, D_STRING, D_UNKNOWN, D_SYNT_ERROR };

class DifParser
{
public:
    String              aData;
    double              fVal;
    UINT32              nVector;
    UINT32              nVal;
    UINT32              nNumFormat;
    CharSet             eCharSet;
private:
    SvNumberFormatter*  pNumFormatter;
    SvStream&           rIn;
    BOOL                bPlain;

    static inline BOOL  IsBOT( const sal_Unicode* pRef );
    static inline BOOL  IsEOD( const sal_Unicode* pRef );
    static inline BOOL  Is1_0( const sal_Unicode* pRef );
public:
                        DifParser( SvStream&, const UINT32 nOption, ScDocument&, CharSet );

    TOPIC               GetNextTopic( void );

    DATASET             GetNextDataset( void );

    const sal_Unicode*  ScanIntVal( const sal_Unicode* pStart, UINT32& rRet );
    BOOL                ScanFloatVal( const sal_Unicode* pStart );

    inline BOOL         IsNumber( const sal_Unicode cChar );
    inline BOOL         IsNumberEnding( const sal_Unicode cChar );

    static inline BOOL  IsV( const sal_Unicode* pRef );

    inline BOOL         IsPlain( void ) const;
};

inline BOOL DifParser::IsBOT( const sal_Unicode* pRef )
{
    return  (   pRef[ 0 ] == pKeyBOT[0] &&
                pRef[ 1 ] == pKeyBOT[1] &&
                pRef[ 2 ] == pKeyBOT[2] &&
                pRef[ 3 ] == pKeyBOT[3] );
}

inline BOOL DifParser::IsEOD( const sal_Unicode* pRef )
{
    return  (   pRef[ 0 ] == pKeyEOD[0] &&
                pRef[ 1 ] == pKeyEOD[1] &&
                pRef[ 2 ] == pKeyEOD[2] &&
                pRef[ 3 ] == pKeyEOD[3] );
}

inline BOOL DifParser::Is1_0( const sal_Unicode* pRef )
{
    return  (   pRef[ 0 ] == pKey1_0[0] &&
                pRef[ 1 ] == pKey1_0[1] &&
                pRef[ 2 ] == pKey1_0[2] &&
                pRef[ 3 ] == pKey1_0[3] );
}

inline BOOL DifParser::IsV( const sal_Unicode* pRef )
{
    return  (   pRef[ 0 ] == pKeyV[0] &&
                pRef[ 1 ] == pKeyV[1]   );
}

inline BOOL DifParser::IsNumber( const sal_Unicode cChar )
{
    return ( cChar >= '0' && cChar <= '9' );
}

inline BOOL DifParser::IsNumberEnding( const sal_Unicode cChar )
{
    return ( cChar == 0x00 );
}

inline BOOL DifParser::IsPlain( void ) const
{
    return bPlain;
}

class DifAttrCache;
class ScPatternAttr;

class DifColumn : private List
{
private:
    friend class DifAttrCache;
    struct ENTRY
    {
        UINT32          nNumFormat;

        SCROW           nStart;
        SCROW           nEnd;
    };

    ENTRY*              pAkt;

    inline              DifColumn( void );
                        ~DifColumn();
    void                SetLogical( SCROW nRow );
    void                SetNumFormat( SCROW nRow, const UINT32 nNumFormat );
    void                NewEntry( const SCROW nPos, const UINT32 nNumFormat );
    void                Apply( ScDocument&, const SCCOL nCol, const SCTAB nTab, const ScPatternAttr& );
    void                Apply( ScDocument &rDoc, const SCCOL nCol, const SCTAB nTab );
public:     // geht niemanden etwas an...
};

inline DifColumn::DifColumn( void )
{
    pAkt = NULL;
}

class DifAttrCache
{
private:
    DifColumn**         ppCols;
    BOOL                bPlain;
public:
                        DifAttrCache( const BOOL bPlain );
                        ~DifAttrCache();
    inline void         SetLogical( const SCCOL nCol, const SCROW nRow );
    void                SetNumFormat( const SCCOL nCol, const SCROW nRow, const UINT32 nNumFormat );
    void                Apply( ScDocument&, SCTAB nTab );
};

inline void DifAttrCache::SetLogical( const SCCOL nCol, const SCROW nRow )
{
    DBG_ASSERT( ValidCol(nCol), "-DifAttrCache::SetLogical(): Col zu gross!" );
    DBG_ASSERT( bPlain, "*DifAttrCache::SetLogical(): muss Plain sein!" );

    if( !ppCols[ nCol ] )
        ppCols[ nCol ] = new DifColumn;
    ppCols[ nCol ]->SetLogical( nRow );
}

#endif

<commit_msg>INTEGRATION: CWS changefileheader (1.5.700); FILE MERGED 2008/04/01 15:30:14 thb 1.5.700.3: #i85898# Stripping all external header guards 2008/04/01 12:36:18 thb 1.5.700.2: #i85898# Stripping all external header guards 2008/03/31 17:14:42 rt 1.5.700.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: dif.hxx,v $
 * $Revision: 1.6 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _DIF_HXX
#define _DIF_HXX

#include <tools/debug.hxx>
#include <tools/list.hxx>
#include <tools/string.hxx>
#include "global.hxx"
#include "address.hxx"

class SvStream;
class SvNumberFormatter;
class ScDocument;
class ScPatternAttr;

extern const sal_Unicode pKeyTABLE[];
extern const sal_Unicode pKeyVECTORS[];
extern const sal_Unicode pKeyTUPLES[];
extern const sal_Unicode pKeyDATA[];
extern const sal_Unicode pKeyBOT[];
extern const sal_Unicode pKeyEOD[];
extern const sal_Unicode pKeyTRUE[];
extern const sal_Unicode pKeyFALSE[];
extern const sal_Unicode pKeyNA[];
extern const sal_Unicode pKeyV[];
extern const sal_Unicode pKey1_0[];

enum TOPIC
{
    T_UNKNOWN,
    T_TABLE, T_VECTORS, T_TUPLES, T_DATA, T_LABEL, T_COMMENT, T_SIZE,
    T_PERIODICITY, T_MAJORSTART, T_MINORSTART, T_TRUELENGTH, T_UINITS,
    T_DISPLAYUNITS,
    T_END
};

enum DATASET { D_BOT, D_EOD, D_NUMERIC, D_STRING, D_UNKNOWN, D_SYNT_ERROR };

class DifParser
{
public:
    String              aData;
    double              fVal;
    UINT32              nVector;
    UINT32              nVal;
    UINT32              nNumFormat;
    CharSet             eCharSet;
private:
    SvNumberFormatter*  pNumFormatter;
    SvStream&           rIn;
    BOOL                bPlain;

    static inline BOOL  IsBOT( const sal_Unicode* pRef );
    static inline BOOL  IsEOD( const sal_Unicode* pRef );
    static inline BOOL  Is1_0( const sal_Unicode* pRef );
public:
                        DifParser( SvStream&, const UINT32 nOption, ScDocument&, CharSet );

    TOPIC               GetNextTopic( void );

    DATASET             GetNextDataset( void );

    const sal_Unicode*  ScanIntVal( const sal_Unicode* pStart, UINT32& rRet );
    BOOL                ScanFloatVal( const sal_Unicode* pStart );

    inline BOOL         IsNumber( const sal_Unicode cChar );
    inline BOOL         IsNumberEnding( const sal_Unicode cChar );

    static inline BOOL  IsV( const sal_Unicode* pRef );

    inline BOOL         IsPlain( void ) const;
};

inline BOOL DifParser::IsBOT( const sal_Unicode* pRef )
{
    return  (   pRef[ 0 ] == pKeyBOT[0] &&
                pRef[ 1 ] == pKeyBOT[1] &&
                pRef[ 2 ] == pKeyBOT[2] &&
                pRef[ 3 ] == pKeyBOT[3] );
}

inline BOOL DifParser::IsEOD( const sal_Unicode* pRef )
{
    return  (   pRef[ 0 ] == pKeyEOD[0] &&
                pRef[ 1 ] == pKeyEOD[1] &&
                pRef[ 2 ] == pKeyEOD[2] &&
                pRef[ 3 ] == pKeyEOD[3] );
}

inline BOOL DifParser::Is1_0( const sal_Unicode* pRef )
{
    return  (   pRef[ 0 ] == pKey1_0[0] &&
                pRef[ 1 ] == pKey1_0[1] &&
                pRef[ 2 ] == pKey1_0[2] &&
                pRef[ 3 ] == pKey1_0[3] );
}

inline BOOL DifParser::IsV( const sal_Unicode* pRef )
{
    return  (   pRef[ 0 ] == pKeyV[0] &&
                pRef[ 1 ] == pKeyV[1]   );
}

inline BOOL DifParser::IsNumber( const sal_Unicode cChar )
{
    return ( cChar >= '0' && cChar <= '9' );
}

inline BOOL DifParser::IsNumberEnding( const sal_Unicode cChar )
{
    return ( cChar == 0x00 );
}

inline BOOL DifParser::IsPlain( void ) const
{
    return bPlain;
}

class DifAttrCache;
class ScPatternAttr;

class DifColumn : private List
{
private:
    friend class DifAttrCache;
    struct ENTRY
    {
        UINT32          nNumFormat;

        SCROW           nStart;
        SCROW           nEnd;
    };

    ENTRY*              pAkt;

    inline              DifColumn( void );
                        ~DifColumn();
    void                SetLogical( SCROW nRow );
    void                SetNumFormat( SCROW nRow, const UINT32 nNumFormat );
    void                NewEntry( const SCROW nPos, const UINT32 nNumFormat );
    void                Apply( ScDocument&, const SCCOL nCol, const SCTAB nTab, const ScPatternAttr& );
    void                Apply( ScDocument &rDoc, const SCCOL nCol, const SCTAB nTab );
public:     // geht niemanden etwas an...
};

inline DifColumn::DifColumn( void )
{
    pAkt = NULL;
}

class DifAttrCache
{
private:
    DifColumn**         ppCols;
    BOOL                bPlain;
public:
                        DifAttrCache( const BOOL bPlain );
                        ~DifAttrCache();
    inline void         SetLogical( const SCCOL nCol, const SCROW nRow );
    void                SetNumFormat( const SCCOL nCol, const SCROW nRow, const UINT32 nNumFormat );
    void                Apply( ScDocument&, SCTAB nTab );
};

inline void DifAttrCache::SetLogical( const SCCOL nCol, const SCROW nRow )
{
    DBG_ASSERT( ValidCol(nCol), "-DifAttrCache::SetLogical(): Col zu gross!" );
    DBG_ASSERT( bPlain, "*DifAttrCache::SetLogical(): muss Plain sein!" );

    if( !ppCols[ nCol ] )
        ppCols[ nCol ] = new DifColumn;
    ppCols[ nCol ]->SetLogical( nRow );
}

#endif

<|endoftext|>


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

#ifndef SC_TPTABLE_HXX
#define SC_TPTABLE_HXX

#ifndef _SFXTABDLG_HXX //autogen
#include <sfx2/tabdlg.hxx>
#endif

#ifndef _SV_FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif

#ifndef _SV_FIELD_HXX //autogen
#include <vcl/field.hxx>
#endif

//===================================================================

class ScTablePage : public SfxTabPage
{
public:
    static  SfxTabPage* Create          ( Window*           pParent,
                                          const SfxItemSet& rCoreSet );
    static  USHORT*     GetRanges       ();
    virtual BOOL        FillItemSet     ( SfxItemSet& rCoreSet );
    virtual void        Reset           ( const SfxItemSet& rCoreSet );
    virtual int         DeactivatePage  ( SfxItemSet* pSet = NULL );

private:
           ScTablePage( Window*         pParent,
                         const SfxItemSet&  rCoreSet );
            ~ScTablePage();
private:
    FixedLine       aFlPageDir;
    RadioButton     aBtnTopDown;
    RadioButton     aBtnLeftRight;
    FixedBitmap     aBmpPageDir;
    Bitmap          aImgLeftRight;
    Bitmap          aImgTopDown;
    CheckBox        aBtnPageNo;
    NumericField    aEdPageNo;

    FixedLine       aFlPrint;
    CheckBox        aBtnHeaders;
    CheckBox        aBtnGrid;
    CheckBox        aBtnNotes;
    CheckBox        aBtnObjects;
    CheckBox        aBtnCharts;
    CheckBox        aBtnDrawings;
    CheckBox        aBtnFormulas;
    CheckBox        aBtnNullVals;

    FixedLine       aFlScale;
    RadioButton     aBtnScaleAll;
    RadioButton     aBtnScalePageNum;
    MetricField     aEdScaleAll;
    NumericField    aEdScalePageNum;

#ifdef _TPTABLE_CXX
private:
    //------------------------------------
    // Handler:
    DECL_LINK( ScaleHdl,   RadioButton* );
    DECL_LINK( PageDirHdl, RadioButton* );
    DECL_LINK( PageNoHdl,  CheckBox* );
#endif
};

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

#ifndef SC_TPTABLE_HXX
#define SC_TPTABLE_HXX

#ifndef _SFXTABDLG_HXX //autogen
#include <sfx2/tabdlg.hxx>
#endif

#ifndef _SV_FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif

#ifndef _SV_FIELD_HXX //autogen
#include <vcl/field.hxx>
#endif

//===================================================================

class ScTablePage : public SfxTabPage
{
public:
    static  SfxTabPage* Create          ( Window*           pParent,
                                          const SfxItemSet& rCoreSet );
    static  USHORT*     GetRanges       ();
    virtual BOOL        FillItemSet     ( SfxItemSet& rCoreSet );
    virtual void        Reset           ( const SfxItemSet& rCoreSet );
    virtual int         DeactivatePage  ( SfxItemSet* pSet = NULL );
    virtual void        DataChanged     ( const DataChangedEvent& rDCEvt );

private:
           ScTablePage( Window*         pParent,
                         const SfxItemSet&  rCoreSet );
            ~ScTablePage();

    void            ShowImage();

private:
    FixedLine       aFlPageDir;
    RadioButton     aBtnTopDown;
    RadioButton     aBtnLeftRight;
    FixedImage      aBmpPageDir;
    Image           aImgLeftRight;
    Image           aImgTopDown;
    Image           aImgLeftRightHC;
    Image           aImgTopDownHC;
    CheckBox        aBtnPageNo;
    NumericField    aEdPageNo;

    FixedLine       aFlPrint;
    CheckBox        aBtnHeaders;
    CheckBox        aBtnGrid;
    CheckBox        aBtnNotes;
    CheckBox        aBtnObjects;
    CheckBox        aBtnCharts;
    CheckBox        aBtnDrawings;
    CheckBox        aBtnFormulas;
    CheckBox        aBtnNullVals;

    FixedLine       aFlScale;
    RadioButton     aBtnScaleAll;
    RadioButton     aBtnScalePageNum;
    MetricField     aEdScaleAll;
    NumericField    aEdScalePageNum;

#ifdef _TPTABLE_CXX
private:
    //------------------------------------
    // Handler:
    DECL_LINK( ScaleHdl,   RadioButton* );
    DECL_LINK( PageDirHdl, RadioButton* );
    DECL_LINK( PageNoHdl,  CheckBox* );
#endif
};

#endif // SC_TPTABLE_HXX
<|endoftext|>


<commit_before>#include "NTClient.h"
using namespace std;

NTClient::NTClient() {
	hasError = false;
	firstConnect = true;
	connected = false;
}
bool NTClient::login(string username, string password) {
	uname = username;
	pword = password;
	bool ret = true;
	string data = string("username=");
	data += uname;
	data += "&password=";
	data += pword;
	data += "&adb=1&tz=America%2FChicago"; // No need to have anything other than Chicago timezone
	httplib::SSLClient loginReq(NITROTYPE_HOSTNAME, HTTPS_PORT);
	shared_ptr<httplib::Response> res = loginReq.post(NT_LOGIN_ENDPOINT, data, "application/x-www-form-urlencoded; charset=UTF-8");
	if (res) {
		bool foundLoginCookie = false;
		for (int i = 0; i < res->cookies.size(); ++i) {
			string cookie = res->cookies.at(i);
			addCookie(Utils::extractCKey(cookie), Utils::extractCValue(cookie));
			if (cookie.find("ntuserrem=") == 0) {
				foundLoginCookie = true;
				token = Utils::extractCValue(cookie);
				cout << "Retrieved login token: " << token << endl;
				addCookie("ntuserrem", token);
			}
		}
		if (!foundLoginCookie) {
			ret = false;
			cout << "Unable to locate the login cookie. Maybe try a different account?\n";
		}
	} else {
		ret = false;
		cout << "Login request failed. This might be a network issue. Maybe try resetting your internet connection?\n";
	}
	bool success = getPrimusSID();
	if (!success) return false;
	return ret;
}
bool NTClient::connect() {
	wsh = new Hub();
	time_t tnow = time(0);
	stringstream uristream;
	uristream  << NT_REALTIME_WS_ENDPOINT << "?_primuscb=" << tnow << "-0&EIO=3&transport=websocket&sid=" << primusSid << "&t=" << tnow << "&b64=1";
	string wsURI = uristream.str();
	cout << "Connecting to endpoint: " << wsURI << endl;
	if (firstConnect) {
		addListeners();
	}
	// cout << "Cookies: " << rawCookieStr << endl << endl;
	// Create override headers
	SMap customHeaders;
	customHeaders["Cookie"] = rawCookieStr;
	customHeaders["Origin"] = "https://www.nitrotype.com";
	customHeaders["User-Agent"] = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/55.0.2883.87 Chrome/55.0.2883.87 Safari/537.36";
	// customHeaders["Host"] = "realtime1.nitrotype.com";
	wsh->connect(wsURI, (void*)this, customHeaders, 7000);
	// wsh->connect(wsURI);
	if (firstConnect) {
		wsh->run();
		firstConnect = false;
	}
	return true;
}
void NTClient::addCookie(string key, string val) {
	SPair sp = SPair(key, val);
	cookies.push_back(sp);
}
bool NTClient::getPrimusSID() {
	time_t tnow = time(0);
	rawCookieStr = Utils::stringifyCookies(&cookies);
	stringstream squery;
	squery << "?_primuscb=" << tnow << "-0&EIO=3&transport=polling&t=" << tnow << "-0&b64=1";
	string queryStr = squery.str();

	httplib::SSLClient loginReq(NT_REALTIME_HOST, HTTPS_PORT);
	string path = NT_PRIMUS_ENDPOINT + queryStr;
	shared_ptr<httplib::Response> res = loginReq.get(path.c_str(), rawCookieStr.c_str());
	if (res) {
		json jres = json::parse(res->body.substr(4, res->body.length()));
		primusSid = jres["sid"];
		cout << "Resolved primus SID: " << primusSid << endl;
		addCookie("io", primusSid);
		rawCookieStr = Utils::stringifyCookies(&cookies);
	} else {
		cout << "Error retrieving primus handshake data.\n";
		return false;
	}
	return true;
}
string NTClient::getJoinPacket(int avgSpeed) {
	json p = {
		{"stream", "race"},
		{"msg", "join"},
		{"payload", {
			{"debugging", false},
			{"avgSpeed", avgSpeed},
			{"track", "desert"},
			{"music", "dirty_bit"},
			{"update", 3417}
		}}
	};
	string ret = "4";
	ret += p.dump();
	return ret;
}
void NTClient::addListeners() {
	assert(wsh != nullptr);
	wsh->onError([this](void* udata) {
		cout << "Failed to connect to WebSocket server." << endl;
		hasError = true;
	});
	wsh->onConnection([this](WebSocket<CLIENT>* wsocket, HttpRequest req) {
		cout << "Connected to the realtime server." << endl;
		onConnection(wsocket, req);
	});
	wsh->onDisconnection([this](WebSocket<CLIENT>* wsocket, int code, char* msg, size_t len) {
		cout << "Disconnected from the realtime server." << endl;
		onDisconnection(wsocket, code, msg, len);
	});
	wsh->onMessage([this](WebSocket<SERVER>* ws, char* msg, size_t len, OpCode opCode) {
		onMessage(ws, msg, len, opCode);
	});
}
void NTClient::onDisconnection(WebSocket<CLIENT>* wsocket, int code, char* msg, size_t len) {
	cout << "Disconn message: " << string(msg, len) << endl;
	cout << "Disconn code: " << code << endl;
}
void NTClient::onMessage(WebSocket<SERVER>* ws, char* msg, size_t len, OpCode opCode) {
	cout << "ws message" << endl; // TODO: parse incoming messages
}
void NTClient::onConnection(WebSocket<CLIENT>* wsocket, HttpRequest req) {
	// Send a probe, which is required for connection
	wsocket->send("2probe", OpCode::TEXT);
	/*
		string joinTo = getJoinPacket(100); // 100 WPM just to test
		cout << joinTo << endl;
		wsocket->send(joinTo.c_str());
	*/
}<commit_msg>Dont add extra cookies<commit_after>#include "NTClient.h"
using namespace std;

NTClient::NTClient() {
	hasError = false;
	firstConnect = true;
	connected = false;
}
bool NTClient::login(string username, string password) {
	uname = username;
	pword = password;
	bool ret = true;
	string data = string("username=");
	data += uname;
	data += "&password=";
	data += pword;
	data += "&adb=1&tz=America%2FChicago"; // No need to have anything other than Chicago timezone
	httplib::SSLClient loginReq(NITROTYPE_HOSTNAME, HTTPS_PORT);
	shared_ptr<httplib::Response> res = loginReq.post(NT_LOGIN_ENDPOINT, data, "application/x-www-form-urlencoded; charset=UTF-8");
	if (res) {
		bool foundLoginCookie = false;
		for (int i = 0; i < res->cookies.size(); ++i) {
			string cookie = res->cookies.at(i);
			addCookie(Utils::extractCKey(cookie), Utils::extractCValue(cookie));
			if (cookie.find("ntuserrem=") == 0) {
				foundLoginCookie = true;
				token = Utils::extractCValue(cookie);
				cout << "Retrieved login token: " << token << endl;
				// addCookie("ntuserrem", token);
			}
		}
		if (!foundLoginCookie) {
			ret = false;
			cout << "Unable to locate the login cookie. Maybe try a different account?\n";
		}
	} else {
		ret = false;
		cout << "Login request failed. This might be a network issue. Maybe try resetting your internet connection?\n";
	}
	bool success = getPrimusSID();
	if (!success) return false;
	return ret;
}
bool NTClient::connect() {
	wsh = new Hub();
	time_t tnow = time(0);
	stringstream uristream;
	uristream  << NT_REALTIME_WS_ENDPOINT << "?_primuscb=" << tnow << "-1&EIO=3&transport=websocket&sid=" << primusSid << "&t=" << tnow << "-2&b64=1";
	string wsURI = uristream.str();
	cout << "Connecting to endpoint: " << wsURI << endl;
	if (firstConnect) {
		addListeners();
	}
	// cout << "Cookies: " << rawCookieStr << endl << endl;
	// Create override headers
	SMap customHeaders;
	customHeaders["cookie"] = rawCookieStr;
	customHeaders["Origin"] = "https://www.nitrotype.com";
	customHeaders["User-Agent"] = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/55.0.2883.87 Chrome/55.0.2883.87 Safari/537.36";
	// customHeaders["Host"] = "realtime1.nitrotype.com";
	wsh->connect(wsURI, (void*)this, customHeaders, 7000);
	// wsh->connect(wsURI);
	if (firstConnect) {
		wsh->run();
		firstConnect = false;
	}
	return true;
}
void NTClient::addCookie(string key, string val) {
	SPair sp = SPair(key, val);
	cookies.push_back(sp);
}
bool NTClient::getPrimusSID() {
	time_t tnow = time(0);
	rawCookieStr = Utils::stringifyCookies(&cookies);
	stringstream squery;
	squery << "?_primuscb=" << tnow << "-0&EIO=3&transport=polling&t=" << tnow << "-0&b64=1";
	string queryStr = squery.str();

	httplib::SSLClient loginReq(NT_REALTIME_HOST, HTTPS_PORT);
	string path = NT_PRIMUS_ENDPOINT + queryStr;
	shared_ptr<httplib::Response> res = loginReq.get(path.c_str(), rawCookieStr.c_str());
	if (res) {
		cout << res->body << endl;
		json jres = json::parse(res->body.substr(4, res->body.length()));
		primusSid = jres["sid"];
		cout << "Resolved primus SID: " << primusSid << endl;
		addCookie("io", primusSid);
		rawCookieStr = Utils::stringifyCookies(&cookies);
	} else {
		cout << "Error retrieving primus handshake data.\n";
		return false;
	}
	return true;
}
string NTClient::getJoinPacket(int avgSpeed) {
	json p = {
		{"stream", "race"},
		{"msg", "join"},
		{"payload", {
			{"debugging", false},
			{"avgSpeed", avgSpeed},
			{"track", "desert"},
			{"music", "dirty_bit"},
			{"update", 3417}
		}}
	};
	string ret = "4";
	ret += p.dump();
	return ret;
}
void NTClient::addListeners() {
	assert(wsh != nullptr);
	wsh->onError([this](void* udata) {
		cout << "Failed to connect to WebSocket server." << endl;
		hasError = true;
	});
	wsh->onConnection([this](WebSocket<CLIENT>* wsocket, HttpRequest req) {
		cout << "Connected to the realtime server." << endl;
		cout << req.getUrl().key << endl;
		onConnection(wsocket, req);
	});
	wsh->onDisconnection([this](WebSocket<CLIENT>* wsocket, int code, char* msg, size_t len) {
		cout << "Disconnected from the realtime server." << endl;
		onDisconnection(wsocket, code, msg, len);
	});
	wsh->onMessage([this](WebSocket<SERVER>* ws, char* msg, size_t len, OpCode opCode) {
		onMessage(ws, msg, len, opCode);
	});
}
void NTClient::onDisconnection(WebSocket<CLIENT>* wsocket, int code, char* msg, size_t len) {
	cout << "Disconn message: " << string(msg, len) << endl;
	cout << "Disconn code: " << code << endl;
}
void NTClient::onMessage(WebSocket<SERVER>* ws, char* msg, size_t len, OpCode opCode) {
	cout << "ws message" << endl; // TODO: parse incoming messages
}
void NTClient::onConnection(WebSocket<CLIENT>* wsocket, HttpRequest req) {
	// Send a probe, which is required for connection
	wsocket->send("2probe", OpCode::TEXT);
	/*
	string joinTo = getJoinPacket(100); // 100 WPM just to test
	cout << joinTo << endl;
	wsocket->send(joinTo.c_str());
	*/
}<|endoftext|>


<commit_before>//===- TpiStream.cpp - PDB Type Info (TPI) Stream 2 Access ----------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/DebugInfo/PDB/Raw/TpiStream.h"

#include "llvm/DebugInfo/CodeView/CodeView.h"
#include "llvm/DebugInfo/CodeView/StreamReader.h"
#include "llvm/DebugInfo/CodeView/TypeIndex.h"
#include "llvm/DebugInfo/CodeView/TypeRecord.h"
#include "llvm/DebugInfo/PDB/Raw/MappedBlockStream.h"
#include "llvm/DebugInfo/PDB/Raw/PDBFile.h"
#include "llvm/DebugInfo/PDB/Raw/RawConstants.h"
#include "llvm/DebugInfo/PDB/Raw/RawError.h"
#include "llvm/DebugInfo/PDB/Raw/RawTypes.h"

#include "llvm/Support/Endian.h"

using namespace llvm;
using namespace llvm::support;
using namespace llvm::pdb;

namespace {
const uint32_t MinHashBuckets = 0x1000;
const uint32_t MaxHashBuckets = 0x40000;
}

static uint32_t HashBufferV8(uint8_t *buffer, uint32_t NumBuckets) {
  // Not yet implemented, this is probably some variation of CRC32 but we need
  // to be sure of the precise implementation otherwise we won't be able to work
  // with persisted hash values.
  return 0;
}

// This corresponds to `HDR` in PDB/dbi/tpi.h.
struct TpiStream::HeaderInfo {
  struct EmbeddedBuf {
    little32_t Off;
    ulittle32_t Length;
  };

  ulittle32_t Version;
  ulittle32_t HeaderSize;
  ulittle32_t TypeIndexBegin;
  ulittle32_t TypeIndexEnd;
  ulittle32_t TypeRecordBytes;

  // The following members correspond to `TpiHash` in PDB/dbi/tpi.h.
  ulittle16_t HashStreamIndex;
  ulittle16_t HashAuxStreamIndex;
  ulittle32_t HashKeySize;
  ulittle32_t NumHashBuckets;

  EmbeddedBuf HashValueBuffer;
  EmbeddedBuf IndexOffsetBuffer;
  EmbeddedBuf HashAdjBuffer;
};

TpiStream::TpiStream(PDBFile &File, uint32_t StreamIdx)
    : Pdb(File), Stream(StreamIdx, File), HashFunction(nullptr) {}

TpiStream::~TpiStream() {}

Error TpiStream::reload() {
  codeview::StreamReader Reader(Stream);

  if (Reader.bytesRemaining() < sizeof(HeaderInfo))
    return make_error<RawError>(raw_error_code::corrupt_file,
                                "TPI Stream does not contain a header.");

  if (Reader.readObject(Header))
    return make_error<RawError>(raw_error_code::corrupt_file,
                                "TPI Stream does not contain a header.");

  if (Header->Version != PdbTpiV80)
    return make_error<RawError>(raw_error_code::corrupt_file,
                                "Unsupported TPI Version.");

  if (Header->HeaderSize != sizeof(HeaderInfo))
    return make_error<RawError>(raw_error_code::corrupt_file,
                                "Corrupt TPI Header size.");

  if (Header->HashKeySize != sizeof(ulittle32_t))
    return make_error<RawError>(raw_error_code::corrupt_file,
                                "TPI Stream expected 4 byte hash key size.");

  if (Header->NumHashBuckets < MinHashBuckets ||
      Header->NumHashBuckets > MaxHashBuckets)
    return make_error<RawError>(raw_error_code::corrupt_file,
                                "TPI Stream Invalid number of hash buckets.");

  HashFunction = HashBufferV8;

  // The actual type records themselves come from this stream
  if (auto EC = Reader.readArray(TypeRecords, Header->TypeRecordBytes))
    return EC;

  // Hash indices, hash values, etc come from the hash stream.
  HashStream.reset(new MappedBlockStream(Header->HashStreamIndex, Pdb));
  codeview::StreamReader HSR(*HashStream);
  uint32_t NumHashValues = Header->HashValueBuffer.Length / sizeof(ulittle32_t);
  HSR.setOffset(Header->HashValueBuffer.Off);
  if (auto EC = HSR.readArray(HashValues, NumHashValues))
    return EC;

  HSR.setOffset(Header->IndexOffsetBuffer.Off);
  uint32_t NumTypeIndexOffsets =
      Header->IndexOffsetBuffer.Length / sizeof(TypeIndexOffset);
  if (auto EC = HSR.readArray(TypeIndexOffsets, NumTypeIndexOffsets))
    return EC;

  HSR.setOffset(Header->HashAdjBuffer.Off);
  uint32_t NumHashAdjustments =
      Header->HashAdjBuffer.Length / sizeof(TypeIndexOffset);
  if (auto EC = HSR.readArray(HashAdjustments, NumHashAdjustments))
    return EC;

  return Error::success();
}

PdbRaw_TpiVer TpiStream::getTpiVersion() const {
  uint32_t Value = Header->Version;
  return static_cast<PdbRaw_TpiVer>(Value);
}

uint32_t TpiStream::TypeIndexBegin() const { return Header->TypeIndexBegin; }

uint32_t TpiStream::TypeIndexEnd() const { return Header->TypeIndexEnd; }

uint32_t TpiStream::NumTypeRecords() const {
  return TypeIndexEnd() - TypeIndexBegin();
}

uint16_t TpiStream::getTypeHashStreamIndex() const {
  return Header->HashStreamIndex;
}

uint16_t TpiStream::getTypeHashStreamAuxIndex() const {
  return Header->HashAuxStreamIndex;
}

codeview::FixedStreamArray<support::ulittle32_t>
TpiStream::getHashValues() const {
  return HashValues;
}

codeview::FixedStreamArray<TypeIndexOffset>
TpiStream::getTypeIndexOffsets() const {
  return TypeIndexOffsets;
}

codeview::FixedStreamArray<TypeIndexOffset>
TpiStream::getHashAdjustments() const {
  return HashAdjustments;
}

iterator_range<codeview::CVTypeArray::Iterator>
TpiStream::types(bool *HadError) const {
  return llvm::make_range(TypeRecords.begin(HadError), TypeRecords.end());
}
<commit_msg>[pdbdump] Verify the size of TPI hash records.<commit_after>//===- TpiStream.cpp - PDB Type Info (TPI) Stream 2 Access ----------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/DebugInfo/PDB/Raw/TpiStream.h"

#include "llvm/DebugInfo/CodeView/CodeView.h"
#include "llvm/DebugInfo/CodeView/StreamReader.h"
#include "llvm/DebugInfo/CodeView/TypeIndex.h"
#include "llvm/DebugInfo/CodeView/TypeRecord.h"
#include "llvm/DebugInfo/PDB/Raw/MappedBlockStream.h"
#include "llvm/DebugInfo/PDB/Raw/PDBFile.h"
#include "llvm/DebugInfo/PDB/Raw/RawConstants.h"
#include "llvm/DebugInfo/PDB/Raw/RawError.h"
#include "llvm/DebugInfo/PDB/Raw/RawTypes.h"

#include "llvm/Support/Endian.h"

using namespace llvm;
using namespace llvm::support;
using namespace llvm::pdb;

namespace {
const uint32_t MinHashBuckets = 0x1000;
const uint32_t MaxHashBuckets = 0x40000;
}

static uint32_t HashBufferV8(uint8_t *buffer, uint32_t NumBuckets) {
  // Not yet implemented, this is probably some variation of CRC32 but we need
  // to be sure of the precise implementation otherwise we won't be able to work
  // with persisted hash values.
  return 0;
}

// This corresponds to `HDR` in PDB/dbi/tpi.h.
struct TpiStream::HeaderInfo {
  struct EmbeddedBuf {
    little32_t Off;
    ulittle32_t Length;
  };

  ulittle32_t Version;
  ulittle32_t HeaderSize;
  ulittle32_t TypeIndexBegin;
  ulittle32_t TypeIndexEnd;
  ulittle32_t TypeRecordBytes;

  // The following members correspond to `TpiHash` in PDB/dbi/tpi.h.
  ulittle16_t HashStreamIndex;
  ulittle16_t HashAuxStreamIndex;
  ulittle32_t HashKeySize;
  ulittle32_t NumHashBuckets;

  EmbeddedBuf HashValueBuffer;
  EmbeddedBuf IndexOffsetBuffer;
  EmbeddedBuf HashAdjBuffer;
};

TpiStream::TpiStream(PDBFile &File, uint32_t StreamIdx)
    : Pdb(File), Stream(StreamIdx, File), HashFunction(nullptr) {}

TpiStream::~TpiStream() {}

Error TpiStream::reload() {
  codeview::StreamReader Reader(Stream);

  if (Reader.bytesRemaining() < sizeof(HeaderInfo))
    return make_error<RawError>(raw_error_code::corrupt_file,
                                "TPI Stream does not contain a header.");

  if (Reader.readObject(Header))
    return make_error<RawError>(raw_error_code::corrupt_file,
                                "TPI Stream does not contain a header.");

  if (Header->Version != PdbTpiV80)
    return make_error<RawError>(raw_error_code::corrupt_file,
                                "Unsupported TPI Version.");

  if (Header->HeaderSize != sizeof(HeaderInfo))
    return make_error<RawError>(raw_error_code::corrupt_file,
                                "Corrupt TPI Header size.");

  if (Header->HashKeySize != sizeof(ulittle32_t))
    return make_error<RawError>(raw_error_code::corrupt_file,
                                "TPI Stream expected 4 byte hash key size.");

  if (Header->NumHashBuckets < MinHashBuckets ||
      Header->NumHashBuckets > MaxHashBuckets)
    return make_error<RawError>(raw_error_code::corrupt_file,
                                "TPI Stream Invalid number of hash buckets.");

  HashFunction = HashBufferV8;

  // The actual type records themselves come from this stream
  if (auto EC = Reader.readArray(TypeRecords, Header->TypeRecordBytes))
    return EC;

  // Hash indices, hash values, etc come from the hash stream.
  HashStream.reset(new MappedBlockStream(Header->HashStreamIndex, Pdb));
  codeview::StreamReader HSR(*HashStream);

  uint32_t NumHashValues = Header->HashValueBuffer.Length / sizeof(ulittle32_t);
  if (NumHashValues != NumTypeRecords())
    return make_error<RawError>(
        raw_error_code::corrupt_file,
        "TPI hash count does not match with the number of type records.");
  HSR.setOffset(Header->HashValueBuffer.Off);
  if (auto EC = HSR.readArray(HashValues, NumHashValues))
    return EC;

  HSR.setOffset(Header->IndexOffsetBuffer.Off);
  uint32_t NumTypeIndexOffsets =
      Header->IndexOffsetBuffer.Length / sizeof(TypeIndexOffset);
  if (auto EC = HSR.readArray(TypeIndexOffsets, NumTypeIndexOffsets))
    return EC;

  HSR.setOffset(Header->HashAdjBuffer.Off);
  uint32_t NumHashAdjustments =
      Header->HashAdjBuffer.Length / sizeof(TypeIndexOffset);
  if (auto EC = HSR.readArray(HashAdjustments, NumHashAdjustments))
    return EC;

  return Error::success();
}

PdbRaw_TpiVer TpiStream::getTpiVersion() const {
  uint32_t Value = Header->Version;
  return static_cast<PdbRaw_TpiVer>(Value);
}

uint32_t TpiStream::TypeIndexBegin() const { return Header->TypeIndexBegin; }

uint32_t TpiStream::TypeIndexEnd() const { return Header->TypeIndexEnd; }

uint32_t TpiStream::NumTypeRecords() const {
  return TypeIndexEnd() - TypeIndexBegin();
}

uint16_t TpiStream::getTypeHashStreamIndex() const {
  return Header->HashStreamIndex;
}

uint16_t TpiStream::getTypeHashStreamAuxIndex() const {
  return Header->HashAuxStreamIndex;
}

codeview::FixedStreamArray<support::ulittle32_t>
TpiStream::getHashValues() const {
  return HashValues;
}

codeview::FixedStreamArray<TypeIndexOffset>
TpiStream::getTypeIndexOffsets() const {
  return TypeIndexOffsets;
}

codeview::FixedStreamArray<TypeIndexOffset>
TpiStream::getHashAdjustments() const {
  return HashAdjustments;
}

iterator_range<codeview::CVTypeArray::Iterator>
TpiStream::types(bool *HadError) const {
  return llvm::make_range(TypeRecords.begin(HadError), TypeRecords.end());
}
<|endoftext|>


<commit_before>///
/// @file  P2_mpi.cpp
/// @brief 2nd partial sieve function.
///        P2(x, y) counts the numbers <= x that have exactly 2 prime
///        factors each exceeding the a-th prime.
///
/// Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <primecount.hpp>
#include <primecount-internal.hpp>
#include <primesieve.hpp>
#include <aligned_vector.hpp>
#include <int128.hpp>
#include <min_max.hpp>
#include <mpi_reduce_sum.hpp>
#include <pmath.hpp>
#include <print.hpp>

#include <stdint.h>
#include <algorithm>
#include <iostream>
#include <iomanip>

#ifdef _OPENMP
  #include <omp.h>
#endif

using namespace std;
using namespace primecount;

namespace {

/// Calculate the segment_size per thread.
/// The idea is to gradually increase the segment_size per
/// thread in order to keep all CPU cores busy.
///
int64_t balanceLoad(int64_t segment_size, double start_time)
{
  double seconds = get_wtime() - start_time;
  int min_segment_size = 1 << 20;

  if (seconds < 30)
    segment_size *= 2;
  else if (segment_size > min_segment_size)
    segment_size -= segment_size / 4;

  return segment_size;
}

template <typename T>
int64_t count_primes(primesieve::iterator& it,
                     int64_t& prime,
                     T stop)
{
  int64_t count = 0;

  for (; prime <= stop; count++)
    prime = it.next_prime();

  return count;
}

template <typename T>
T P2_OpenMP_thread(T x,
                   int64_t y,
                   int64_t z,
                   int64_t segment_size,
                   int64_t thread_num,
                   int64_t low,
                   int64_t& pix,
                   int64_t& pix_count)
{
  pix = 0;
  pix_count = 0;
  low += thread_num * segment_size;
  z = min(low + segment_size, z);
  int64_t start = (int64_t) max(x / z, y);
  int64_t stop = (int64_t) min(x / low, isqrt(x));

  primesieve::iterator rit(stop + 1, start);
  primesieve::iterator it(low - 1, z);

  int64_t next = it.next_prime();
  int64_t prime = rit.previous_prime();
  T P2_thread = 0;

  // \sum_{i = pi[start]+1}^{pi[stop]} pi(x / primes[i])
  while (prime > start &&
         x / prime < z)
  {
    pix += count_primes(it, next, x / prime);
    P2_thread += pix;
    pix_count++;
    prime = rit.previous_prime();
  }

  pix += count_primes(it, next, z - 1);

  return P2_thread;
}

/// P2_mpi_master(x, y) counts the numbers <= x that have exactly 2
/// prime factors each exceeding the a-th prime, a = pi(y).
/// Space complexity: O((x / y)^(1/2)).
///
template <typename T>
T P2_mpi_master(T x, int64_t y, int threads)
{
#if __cplusplus >= 201103L
  static_assert(prt::is_signed<T>::value,
                "P2(T x, ...): T must be signed integer type");
#endif

  if (x < 4)
    return 0;

  T a = pi_legendre(y, threads);
  T b = pi_legendre((int64_t) isqrt(x), threads);

  if (a >= b)
    return 0;

  int64_t low = 2;
  int64_t z = (int64_t)(x / max(y, 1));
  int64_t segment_size = 1 << 20;
  threads = ideal_num_threads(threads, z);

  aligned_vector<int64_t> pix(threads);
  aligned_vector<int64_t> pix_counts(threads);

  int proc_id = mpi_proc_id();
  int procs = mpi_num_procs();

  int64_t distance = z - low;
  int64_t proc_distance = ceil_div(distance, procs);
  low += proc_distance * proc_id;
  z = min(low + proc_distance, z);

  // \sum_{i=a+1}^{b} pi(x / primes[i]) - (i - 1)
  T p2 = 0;

  // \sum_{i=a+1}^{b} -(i - 1)
  if (is_mpi_master_proc())
    p2 = (a - 2) * (a + 1) / 2 - (b - 2) * (b + 1) / 2;

  T pix_total = pi_legendre(low - 1, threads);

  // \sum_{i=a+1}^{b} pi(x / primes[i])
  while (low < z)
  {
    int64_t segments = ceil_div(z - low, segment_size);
    threads = in_between(1, threads, segments);
    double time = get_wtime();

    #pragma omp parallel for num_threads(threads) reduction(+: p2)
    for (int i = 0; i < threads; i++)
      p2 += P2_OpenMP_thread(x, y, z, segment_size,
        i, low, pix[i], pix_counts[i]);

    low += segment_size * threads;
    segment_size = balanceLoad(segment_size, time);

    // Add missing sum contributions in order
    for (int i = 0; i < threads; i++)
    {
      p2 += pix_total * pix_counts[i];
      pix_total += pix[i];
    }

    if (print_status())
    {
      double percent = get_percent((double) low, (double) z);
      cout << "\rStatus: " << fixed << setprecision(get_status_precision(x))
           << percent << '%' << flush;
    }
  }

  p2 = mpi_reduce_sum(p2);

  return p2;
}

} // namespace

namespace primecount {

int64_t P2_mpi(int64_t x, int64_t y, int threads)
{
  print("");
  print("=== P2_mpi(x, y) ===");
  print("Computation of the 2nd partial sieve function");
  print(x, y, threads);

  double time = get_wtime();
  int64_t p2 = P2_mpi_master(x, y, threads);

  print("P2", p2, time);
  return p2;
}

#ifdef HAVE_INT128_T

int128_t P2_mpi(int128_t x, int64_t y, int threads)
{
  print("");
  print("=== P2_mpi(x, y) ===");
  print("Computation of the 2nd partial sieve function");
  print(x, y, threads);

  double time = get_wtime();
  int128_t p2 = P2_mpi_master(x, y, threads);

  print("P2", p2, time);
  return p2;
}

#endif

} // namespace
<commit_msg>Refactor<commit_after>///
/// @file  P2_mpi.cpp
/// @brief 2nd partial sieve function.
///        P2(x, y) counts the numbers <= x that have exactly 2 prime
///        factors each exceeding the a-th prime.
///
/// Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <primecount.hpp>
#include <primecount-internal.hpp>
#include <primesieve.hpp>
#include <aligned_vector.hpp>
#include <int128.hpp>
#include <min_max.hpp>
#include <mpi_reduce_sum.hpp>
#include <pmath.hpp>
#include <print.hpp>

#include <stdint.h>
#include <algorithm>
#include <iostream>
#include <iomanip>

#ifdef _OPENMP
  #include <omp.h>
#endif

using namespace std;
using namespace primecount;

namespace {

/// Calculate the segment_size per thread.
/// The idea is to gradually increase the segment_size per
/// thread in order to keep all CPU cores busy.
///
int64_t balanceLoad(int64_t segment_size, double start_time)
{
  double seconds = get_wtime() - start_time;
  int min_segment_size = 1 << 20;

  if (seconds < 30)
    segment_size *= 2;
  else if (segment_size > min_segment_size)
    segment_size -= segment_size / 4;

  return segment_size;
}

template <typename T>
int64_t count_primes(primesieve::iterator& it, int64_t& prime, T stop)
{
  int64_t count = 0;

  for (; prime <= stop; count++)
    prime = it.next_prime();

  return count;
}

template <typename T>
T P2_OpenMP_thread(T x,
                   int64_t y,
                   int64_t z,
                   int64_t segment_size,
                   int64_t thread_num,
                   int64_t low,
                   int64_t& pix,
                   int64_t& pix_count)
{
  pix = 0;
  pix_count = 0;
  low += thread_num * segment_size;
  z = min(low + segment_size, z);
  int64_t start = (int64_t) max(x / z, y);
  int64_t stop = (int64_t) min(x / low, isqrt(x));

  primesieve::iterator rit(stop + 1, start);
  primesieve::iterator it(low - 1, z);

  int64_t next = it.next_prime();
  int64_t prime = rit.previous_prime();
  T P2_thread = 0;

  // \sum_{i = pi[start]+1}^{pi[stop]} pi(x / primes[i])
  while (prime > start &&
         x / prime < z)
  {
    pix += count_primes(it, next, x / prime);
    P2_thread += pix;
    pix_count++;
    prime = rit.previous_prime();
  }

  pix += count_primes(it, next, z - 1);

  return P2_thread;
}

/// P2_mpi_master(x, y) counts the numbers <= x that have exactly 2
/// prime factors each exceeding the a-th prime, a = pi(y).
/// Space complexity: O((x / y)^(1/2)).
///
template <typename T>
T P2_mpi_master(T x, int64_t y, int threads)
{
#if __cplusplus >= 201103L
  static_assert(prt::is_signed<T>::value,
                "P2(T x, ...): T must be signed integer type");
#endif

  if (x < 4)
    return 0;

  T a = pi_legendre(y, threads);
  T b = pi_legendre((int64_t) isqrt(x), threads);

  if (a >= b)
    return 0;

  T p2 = 0;
  T pix_total = pi_legendre(low - 1, threads);

  if (is_mpi_master_proc())
    p2 = (a - 2) * (a + 1) / 2 - (b - 2) * (b + 1) / 2;

  int64_t low = 2;
  int64_t z = (int64_t)(x / max(y, 1));
  int64_t segment_size = 1 << 20;

  threads = ideal_num_threads(threads, z);
  aligned_vector<int64_t> pix(threads);
  aligned_vector<int64_t> pix_counts(threads);

  int proc_id = mpi_proc_id();
  int procs = mpi_num_procs();

  int64_t distance = z - low;
  int64_t proc_distance = ceil_div(distance, procs);
  low += proc_distance * proc_id;
  z = min(low + proc_distance, z);

  // \sum_{i=a+1}^{b} pi(x / primes[i])
  while (low < z)
  {
    int64_t segments = ceil_div(z - low, segment_size);
    threads = in_between(1, threads, segments);
    double time = get_wtime();

    #pragma omp parallel for num_threads(threads) reduction(+: p2)
    for (int i = 0; i < threads; i++)
      p2 += P2_OpenMP_thread(x, y, z, segment_size,
        i, low, pix[i], pix_counts[i]);

    low += segment_size * threads;
    segment_size = balanceLoad(segment_size, time);

    // Add missing sum contributions in order
    for (int i = 0; i < threads; i++)
    {
      p2 += pix_total * pix_counts[i];
      pix_total += pix[i];
    }

    if (print_status())
    {
      double percent = get_percent((double) low, (double) z);
      cout << "\rStatus: " << fixed << setprecision(get_status_precision(x))
           << percent << '%' << flush;
    }
  }

  p2 = mpi_reduce_sum(p2);

  return p2;
}

} // namespace

namespace primecount {

int64_t P2_mpi(int64_t x, int64_t y, int threads)
{
  print("");
  print("=== P2_mpi(x, y) ===");
  print("Computation of the 2nd partial sieve function");
  print(x, y, threads);

  double time = get_wtime();
  int64_t p2 = P2_mpi_master(x, y, threads);

  print("P2", p2, time);
  return p2;
}

#ifdef HAVE_INT128_T

int128_t P2_mpi(int128_t x, int64_t y, int threads)
{
  print("");
  print("=== P2_mpi(x, y) ===");
  print("Computation of the 2nd partial sieve function");
  print(x, y, threads);

  double time = get_wtime();
  int128_t p2 = P2_mpi_master(x, y, threads);

  print("P2", p2, time);
  return p2;
}

#endif

} // namespace
<|endoftext|>


<commit_before>#include <Surface.h>

#include <Color.h>
#include <Image.h>

#include <cstring>
#include <vector>
#include <cmath>
#include <cassert>
#include <iostream>

using namespace std;
using namespace canvas;

static vector<int> make_kernel(float radius) {
  int r = (int)ceil(radius);
  int rows = 2 * r + 1;
  float sigma = radius / 3;
  float sigma22 = 2.0f * sigma * sigma;
  float sigmaPi2 = 2.0f * float(M_PI) * sigma;
  float sqrtSigmaPi2 = sqrt(sigmaPi2);
  // float radius2 = radius*radius;
  vector<int> kernel;
  kernel.reserve(rows);

  int row = -r;
  float first_value = exp(-row*row/sigma22) / sqrtSigmaPi2;
  kernel.push_back(1);

  for (unsigned int i = 1; i < rows; i++, row++) {
    // for (row++; row <= r; row++) {
    kernel.push_back(int(exp(-row * row / sigma22) / sqrtSigmaPi2 / first_value));
  }
  return kernel;
}

// standard deviation, number of boxes
static vector<int> boxesForGauss(float sigma, unsigned int n) {
  // Ideal averaging filter width
  float wIdeal = sqrtf((12.0f * sigma * sigma / n) + 1);
  int wl = int(floor(wIdeal));
  if (wl % 2 == 0) wl--;
  int wu = wl + 2;

  float mIdeal = (12.0f * sigma * sigma - n*wl*wl - 4*n*wl - 3*n) / (-4*wl - 4);
  int m = int(round(mIdeal));
  // var sigmaActual = Math.sqrt( (m*wl*wl + (n-m)*wu*wu - n)/12 );

  vector<int> sizes;
  for (int i = 0; i < n; i++) sizes.push_back(i < m ? wl : wu);
  return sizes;
}

static void boxBlurH_4(unsigned char * scl, unsigned char * tcl, int w, int h, int r) {
  float iarr = 1 / (r+r+1);
  for (int ch = 0; ch < 4; ch++) {
    for (int i=0; i < h; i++) {
      int ti = i*w;
      int li = ti;
      int ri = ti + r;
      int fv = scl[4 * ti + ch];
      int lv = scl[4 * (ti + w - 1) + ch];
      int val = (r+1)*fv;
      for (int j = 0; j  < r; j++) val += scl[4 * (ti + j) + ch];
      for (int j = 0; j <= r; j++) {
	val += scl[4 * ri++ + ch] - fv;
	tcl[4 * ti++ + ch] = int(round(val * iarr));
      }
      for (int j = r+1; j < w-r; j++) {
	val += scl[4 * ri++ + ch] - scl[4 * li++ + ch];
	tcl[4 * ti++ + ch] = int(round(val*iarr));
      }
      for (int j = w-r; j < w; j++) {
	val += lv - scl[4 * li++ + ch];
	tcl[4 * ti++ + ch] = int(round(val*iarr));
      }
    }
  }
}

static void boxBlurT_4(unsigned char * scl, unsigned char * tcl, int w, int h, int r) {
  float iarr = 1 / (r+r+1);
  for (int ch = 0; ch < 4; ch++) {
    for (int i = 0; i < w; i++) {
      int ti = i;
      int li = ti;
      int ri = ti + r * w;
      int fv = scl[4 * ti + ch];
      int lv = scl[4 * (ti+w*(h-1)) + ch];
      int val = (r+1)*fv;
      for (int j = 0; j < r; j++) val += scl[4 * (ti+j*w) + ch];
      for (int j = 0; j <= r; j++) {
	val += scl[4 * ri + ch] - fv;
	tcl[4 * ti + ch] = int(round(val*iarr));
	ri += w;
	ti += w;
      }
      for (int j = r+1; j<h-r; j++) {
	val += scl[4 * ri + ch] - scl[4 * li + ch];
	tcl[4 * ti + ch] = int(round(val*iarr));
	li += w;
	ri += w;
	ti += w;
      }
      for (int j = h-r; j < h; j++) {
	val += lv - scl[4 * li + ch];
	tcl[4 * ti + ch] = int(round(val*iarr));
	li += w;
	ti += w;
      }
    }
  }
}

static void boxBlur_4(unsigned char * scl, unsigned char * tcl, int w, int h, int r) {
  for (int i = 0; i < 4 * w * h; i++) tcl[i] = scl[i];
  boxBlurH_4(tcl, scl, w, h, r);
  boxBlurT_4(scl, tcl, w, h, r);
}

void
Surface::blur(float r) {
  auto bxs = boxesForGauss(r, 3);

  int w = getActualWidth(), h = getActualHeight();
  unsigned char * scl = (unsigned char *)lockMemory(true);
  unsigned char * tcl = new unsigned char[w * h * 4];

  cerr << "boxes: " << bxs[0] << ", " << bxs[1] << ", " << bxs[2] << endl;

  boxBlur_4(scl, tcl, w, h, (bxs[0]-1) / 2);
  boxBlur_4(tcl, scl, w, h, (bxs[1]-1) / 2);
  boxBlur_4(scl, tcl, w, h, (bxs[2]-1) / 2);

  memcpy(scl, tcl, w * h * 4);
  delete[] tcl;
  releaseMemory();
}

void
Surface::slowBlur(float hradius, float vradius) {
  if (!(hradius > 0 || vradius > 0)) {
    return;
  }

  unsigned char * buffer = (unsigned char *)lockMemory(true);
  assert(buffer);

  if (format == RGBA8) {
    unsigned char * tmp = new unsigned char[actual_width * actual_height * 4];
    if (hradius > 0.0f) {
      vector<int> hkernel = make_kernel(hradius);
      unsigned short hsize = hkernel.size();
      int htotal = 0;
      for (vector<int>::iterator it = hkernel.begin(); it != hkernel.end(); it++) {
	htotal += *it;
      }
      memset(tmp, 0, actual_width * actual_height * 4);
      for (unsigned int row = 0; row < actual_height; row++) {
	for (unsigned int col = 0; col + hsize < actual_width; col++) {
	  int c0 = 0, c1 = 0, c2 = 0, c3 = 0;
	  for (unsigned int i = 0; i < hsize; i++) {
	    unsigned char * ptr = buffer + (row * actual_width + col + i) * 4;
	    c0 += *ptr++ * hkernel[i];
	    c1 += *ptr++ * hkernel[i];
	    c2 += *ptr++ * hkernel[i];
	    c3 += *ptr++ * hkernel[i];
	  }
	  unsigned char * ptr = tmp + (row * actual_width + col + hsize / 2) * 4;
	  *ptr++ = (unsigned char)(c0 / htotal);
	  *ptr++ = (unsigned char)(c1 / htotal);
	  *ptr++ = (unsigned char)(c2 / htotal);
	  *ptr++ = (unsigned char)(c3 / htotal);
	}
      }
    } else {
      memcpy(tmp, buffer, actual_width * actual_height * 4);
    }
    if (vradius > 0) {
      vector<int> vkernel = make_kernel(vradius);
      unsigned short vsize = vkernel.size();
      int vtotal = 0;
      for (vector<int>::iterator it = vkernel.begin(); it != vkernel.end(); it++) {
	vtotal += *it;
      }

      memset(buffer, 0, actual_width * actual_height * 4);
      for (unsigned int col = 0; col < actual_width; col++) {
	for (unsigned int row = 0; row + vsize < actual_height; row++) {
	  int c0 = 0, c1 = 0, c2 = 0, c3 = 0;
	  for (unsigned int i = 0; i < vsize; i++) {
	    unsigned char * ptr = tmp + ((row + i) * actual_width + col) * 4;
	    c0 += *ptr++ * vkernel[i];
	    c1 += *ptr++ * vkernel[i];
	    c2 += *ptr++ * vkernel[i];
	    c3 += *ptr++ * vkernel[i];
	  }
	  unsigned char * ptr = buffer + ((row + vsize / 2) * actual_width + col) * 4;
	  *ptr++ = (unsigned char)(c0 / vtotal);
	  *ptr++ = (unsigned char)(c1 / vtotal);
	  *ptr++ = (unsigned char)(c2 / vtotal);
	  *ptr++ = (unsigned char)(c3 / vtotal);
	}
      }
    } else {
      memcpy(buffer, tmp, actual_width * actual_height * 4);
    }
    delete[] tmp;
  } else if (format == R8) {
    unsigned char * tmp = new unsigned char[actual_width * actual_height];
    if (hradius > 0.0f) {
      vector<int> hkernel = make_kernel(hradius);
      unsigned short hsize = hkernel.size();
      int htotal = 0;
      for (vector<int>::iterator it = hkernel.begin(); it != hkernel.end(); it++) {
	htotal += *it;
      }
      memset(tmp, 0, actual_width * actual_height);
      for (unsigned int row = 0; row < actual_height; row++) {
	for (unsigned int col = 0; col + hsize < actual_width; col++) {
	  int c0 = 0;
	  for (unsigned int i = 0; i < hsize; i++) {
	    unsigned char * ptr = buffer + (row * actual_width + col + i);
	    c0 += *ptr * hkernel[i];
	  }
	  unsigned char * ptr = tmp + (row * actual_width + col + hsize / 2);
	  *ptr = (unsigned char)(c0 / htotal);
	}
      }
    } else {
      memcpy(tmp, buffer, actual_width * actual_height);
    }
    if (vradius > 0) {
      vector<int> vkernel = make_kernel(vradius);
      unsigned short vsize = vkernel.size();
      int vtotal = 0;
      for (vector<int>::iterator it = vkernel.begin(); it != vkernel.end(); it++) {
	vtotal += *it;
      }

      memset(buffer, 0, actual_width * actual_height);
      for (unsigned int col = 0; col < actual_width; col++) {
	for (unsigned int row = 0; row + vsize < actual_height; row++) {
	  int c0 = 0;
	  for (unsigned int i = 0; i < vsize; i++) {
	    unsigned char * ptr = tmp + ((row + i) * actual_width + col);
	    c0 += *ptr++ * vkernel[i];
	  }
	  unsigned char * ptr = buffer + ((row + vsize / 2) * actual_width + col);
	  *ptr = (unsigned char)(c0 / vtotal);
	}
      }
    } else {
      memcpy(buffer, tmp, actual_width * actual_height);
    }
    delete[] tmp;
  }
  releaseMemory();
}

void
Surface::colorize(const Color & input_color, Surface & target) {
  Color color = input_color;
  color.red *= color.alpha;
  color.green *= color.alpha;
  color.blue *= color.alpha;

  assert(getFormat() == R8 && target.getFormat() == RGBA8);
  assert(getActualWidth() == target.getActualWidth() && getActualHeight() == target.getActualHeight());
  unsigned char * buffer = (unsigned char *)lockMemory(false);
  unsigned char * target_buffer = (unsigned char *)target.lockMemory(true);

  for (unsigned int i = 0; i < actual_width * actual_height; i++) {
    float input_alpha = buffer[i] / 255.0f;
    target_buffer[4 * i + 0] = (unsigned char)(color.red * input_alpha * 255);
    target_buffer[4 * i + 1] = (unsigned char)(color.green * input_alpha * 255);
    target_buffer[4 * i + 2] = (unsigned char)(color.blue * input_alpha * 255);
    target_buffer[4 * i + 3] = (unsigned char)(color.alpha * input_alpha * 255);
  }

  releaseMemory();
  target.releaseMemory();
}

#if 0
void
Surface::multiply(const Color & color) {
  assert(getFormat() == RGBA8);
  unsigned char * buffer = (unsigned char *)lockMemory(true);
  assert(buffer);
  unsigned int red = toByte(color.red);
  unsigned int green = toByte(color.green);
  unsigned int blue = toByte(color.blue);
  unsigned int alpha = toByte(color.alpha);
  for (unsigned int i = 0; i < actual_width * actual_height; i++) {
    unsigned char * ptr = buffer + (i * 4);
    ptr[0] = (unsigned char)(ptr[0] * red / 255);
    ptr[1] = (unsigned char)(ptr[1] * green / 255);
    ptr[2] = (unsigned char)(ptr[2] * blue / 255);
    ptr[3] = (unsigned char)(ptr[3] * alpha / 255);
  }
  releaseMemory();
}
#endif

#if 0
void *
Surface::lockMemoryPartial(unsigned int x0, unsigned int y0, unsigned int required_width, unsigned int required_height) {
  unsigned int * buffer = (unsigned int *)lockMemory();
  assert(buffer);

  delete[] scaled_buffer;
  scaled_buffer = new unsigned int[required_width * required_height];

  unsigned int offset = 0;
  for (unsigned int y = y0; y < y0 + required_height; y++) {
    for (unsigned int x = x0; x < x0 + required_width; x++) {
      scaled_buffer[offset++] = buffer[y * actual_width + x];
    }
  }

  return scaled_buffer;
}
#endif

bool
Surface::isPNG(const unsigned char * buffer, size_t size) {
  return size >= 4 && buffer[0] == 0x89 && buffer[1] == 0x50 && buffer[2] == 0x4e && buffer[3] == 0x47;
}

bool
Surface::isJPEG(const unsigned char * buffer, size_t size) {
  return size >= 3 && buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff;
}

bool
Surface::isGIF(const unsigned char * buffer, size_t size) {
  return size >= 6 && buffer[0] == 'G' && buffer[1] == 'I' && buffer[2] == 'F' && buffer[3] == '8' && (buffer[4] == '7' || buffer[4] == '9') && buffer[5] == 'a';
}

bool
Surface::isBMP(const unsigned char * buffer, size_t size) {
  return size > 2 && buffer[0] == 0x42 && buffer[1] == 0x4d;
}

bool
Surface::isXML(const unsigned char * buffer, size_t size) {
  return size >= 6 && buffer[0] == '<' && buffer[1] == '!' && buffer[2] == 'D' && buffer[3] == 'O' && buffer[4] == 'C' && buffer[5] == 'T';
}
<commit_msg>refactor<commit_after>#include <Surface.h>

#include <Color.h>
#include <Image.h>

#include <cstring>
#include <vector>
#include <cmath>
#include <cassert>
#include <iostream>

using namespace std;
using namespace canvas;

static vector<int> make_kernel(float radius) {
  int r = (int)ceil(radius);
  int rows = 2 * r + 1;
  float sigma = radius / 3;
  float sigma22 = 2.0f * sigma * sigma;
  float sigmaPi2 = 2.0f * float(M_PI) * sigma;
  float sqrtSigmaPi2 = sqrt(sigmaPi2);
  // float radius2 = radius*radius;
  vector<int> kernel;
  kernel.reserve(rows);

  int row = -r;
  float first_value = exp(-row*row/sigma22) / sqrtSigmaPi2;
  kernel.push_back(1);

  for (unsigned int i = 1; i < rows; i++, row++) {
    // for (row++; row <= r; row++) {
    kernel.push_back(int(exp(-row * row / sigma22) / sqrtSigmaPi2 / first_value));
  }
  return kernel;
}

// standard deviation, number of boxes
static vector<int> boxesForGauss(float sigma, unsigned int n) {
  // Ideal averaging filter width
  float wIdeal = sqrtf((12.0f * sigma * sigma / n) + 1);
  int wl = int(floor(wIdeal));
  if (wl % 2 == 0) wl--;
  int wu = wl + 2;

  float mIdeal = (12.0f * sigma * sigma - n*wl*wl - 4*n*wl - 3*n) / (-4*wl - 4);
  int m = int(round(mIdeal));
  // var sigmaActual = Math.sqrt( (m*wl*wl + (n-m)*wu*wu - n)/12 );

  vector<int> sizes;
  for (int i = 0; i < n; i++) sizes.push_back(i < m ? wl : wu);
  return sizes;
}

static void boxBlurH_4(unsigned char * scl, unsigned char * tcl, int w, int h, int r) {
  float iarr = 1 / (r+r+1);
  for (int ch = 0; ch < 4; ch++) {
    for (int i=0; i < h; i++) {
      int ti = i*w;
      int li = ti;
      int ri = ti + r;
      int fv = scl[4 * ti + ch];
      int lv = scl[4 * (ti + w - 1) + ch];
      int val = (r+1)*fv;
      for (int j = 0; j  < r; j++) val += scl[4 * (ti + j) + ch];
      for (int j = 0; j <= r; j++) {
	val += scl[4 * ri++ + ch] - fv;
	tcl[4 * ti++ + ch] = int(round(val * iarr));
      }
      for (int j = r+1; j < w-r; j++) {
	val += scl[4 * ri++ + ch] - scl[4 * li++ + ch];
	tcl[4 * ti++ + ch] = int(round(val*iarr));
      }
      for (int j = w-r; j < w; j++) {
	val += lv - scl[4 * li++ + ch];
	tcl[4 * ti++ + ch] = int(round(val*iarr));
      }
    }
  }
}

static void boxBlurT_4(unsigned char * scl, unsigned char * tcl, int w, int h, int r) {
  float iarr = 1 / (r+r+1);
  for (int ch = 0; ch < 4; ch++) {
    for (int i = 0; i < w; i++) {
      int ti = i;
      int li = ti;
      int ri = ti + r * w;
      int fv = scl[4 * ti + ch];
      int lv = scl[4 * (ti+w*(h-1)) + ch];
      int val = (r+1)*fv;
      for (int j = 0; j < r; j++) val += scl[4 * (ti+j*w) + ch];
      for (int j = 0; j <= r; j++) {
	val += scl[4 * ri + ch] - fv;
	tcl[4 * ti + ch] = int(round(val*iarr));
	ri += w;
	ti += w;
      }
      for (int j = r+1; j<h-r; j++) {
	val += scl[4 * ri + ch] - scl[4 * li + ch];
	tcl[4 * ti + ch] = int(round(val*iarr));
	li += w;
	ri += w;
	ti += w;
      }
      for (int j = h-r; j < h; j++) {
	val += lv - scl[4 * li + ch];
	tcl[4 * ti + ch] = int(round(val*iarr));
	li += w;
	ti += w;
      }
    }
  }
}

static void boxBlur_4(unsigned char * scl, unsigned char * tcl, int w, int h, int r) {
  for (int i = 0; i < 4 * w * h; i++) tcl[i] = scl[i];
  boxBlurH_4(tcl, scl, w, h, r);
  boxBlurT_4(scl, tcl, w, h, r);
}

void
Surface::blur(float r) {
  auto bxs = boxesForGauss(r, 3);

  int w = getActualWidth(), h = getActualHeight();
  unsigned char * scl = (unsigned char *)lockMemory(true);
  unsigned char * tcl = new unsigned char[w * h * 4];

  cerr << "boxes: " << bxs[0] << ", " << bxs[1] << ", " << bxs[2] << endl;

  boxBlur_4(scl, tcl, w, h, (bxs[0]-1) / 2);
  boxBlur_4(tcl, scl, w, h, (bxs[1]-1) / 2);
  boxBlur_4(scl, tcl, w, h, (bxs[2]-1) / 2);

  memcpy(scl, tcl, w * h * 4);
  delete[] tcl;
  releaseMemory();
}

void
Surface::slowBlur(float hradius, float vradius) {
  if (!(hradius > 0 || vradius > 0)) {
    return;
  }

  unsigned char * buffer = (unsigned char *)lockMemory(true);
  assert(buffer);

  if (format == RGBA8) {
    unsigned char * tmp = new unsigned char[actual_width * actual_height * 4];
    if (hradius > 0.0f) {
      vector<int> hkernel = make_kernel(hradius);
      unsigned short hsize = hkernel.size();

      int htotal = 0;
      for (auto & a : hkernel) htotal += a;

      memset(tmp, 0, actual_width * actual_height * 4);
      for (unsigned int row = 0; row < actual_height; row++) {
	for (unsigned int col = 0; col + hsize <= actual_width; col++) {
	  int c0 = 0, c1 = 0, c2 = 0, c3 = 0;
	  for (unsigned int i = 0; i < hsize; i++) {
	    unsigned char * ptr = buffer + (row * actual_width + col + i) * 4;
	    c0 += *ptr++ * hkernel[i];
	    c1 += *ptr++ * hkernel[i];
	    c2 += *ptr++ * hkernel[i];
	    c3 += *ptr++ * hkernel[i];
	  }
	  unsigned char * ptr = tmp + (row * actual_width + col + hsize / 2) * 4;
	  *ptr++ = (unsigned char)(c0 / htotal);
	  *ptr++ = (unsigned char)(c1 / htotal);
	  *ptr++ = (unsigned char)(c2 / htotal);
	  *ptr++ = (unsigned char)(c3 / htotal);
	}
      }
    } else {
      memcpy(tmp, buffer, actual_width * actual_height * 4);
    }
    if (vradius > 0) {
      vector<int> vkernel = make_kernel(vradius);
      unsigned short vsize = vkernel.size();

      int vtotal = 0;
      for (auto & a : vkernel) vtotal += a;

      memset(buffer, 0, actual_width * actual_height * 4);
      for (unsigned int col = 0; col < actual_width; col++) {
	for (unsigned int row = 0; row + vsize <= actual_height; row++) {
	  int c0 = 0, c1 = 0, c2 = 0, c3 = 0;
	  for (unsigned int i = 0; i < vsize; i++) {
	    unsigned char * ptr = tmp + ((row + i) * actual_width + col) * 4;
	    c0 += *ptr++ * vkernel[i];
	    c1 += *ptr++ * vkernel[i];
	    c2 += *ptr++ * vkernel[i];
	    c3 += *ptr++ * vkernel[i];
	  }
	  unsigned char * ptr = buffer + ((row + vsize / 2) * actual_width + col) * 4;
	  *ptr++ = (unsigned char)(c0 / vtotal);
	  *ptr++ = (unsigned char)(c1 / vtotal);
	  *ptr++ = (unsigned char)(c2 / vtotal);
	  *ptr++ = (unsigned char)(c3 / vtotal);
	}
      }
    } else {
      memcpy(buffer, tmp, actual_width * actual_height * 4);
    }
    delete[] tmp;
  } else if (format == R8) {
    unsigned char * tmp = new unsigned char[actual_width * actual_height];
    if (hradius > 0.0f) {
      vector<int> hkernel = make_kernel(hradius);
      unsigned short hsize = hkernel.size();

      int htotal = 0;
      for (auto & a : hkernel) htotal += a;

      memset(tmp, 0, actual_width * actual_height);
      for (unsigned int row = 0; row < actual_height; row++) {
	for (unsigned int col = 0; col + hsize <= actual_width; col++) {
	  int c0 = 0;
	  for (unsigned int i = 0; i < hsize; i++) {
	    unsigned char * ptr = buffer + (row * actual_width + col + i);
	    c0 += *ptr * hkernel[i];
	  }
	  unsigned char * ptr = tmp + (row * actual_width + col + hsize / 2);
	  *ptr = (unsigned char)(c0 / htotal);
	}
      }
    } else {
      memcpy(tmp, buffer, actual_width * actual_height);
    }
    if (vradius > 0) {
      vector<int> vkernel = make_kernel(vradius);
      unsigned short vsize = vkernel.size();
      int vtotal = 0;
      for (auto & a : vkernel) vtotal += a;

      memset(buffer, 0, actual_width * actual_height);
      for (unsigned int col = 0; col < actual_width; col++) {
	for (unsigned int row = 0; row + vsize <= actual_height; row++) {
	  int c0 = 0;
	  for (unsigned int i = 0; i < vsize; i++) {
	    unsigned char * ptr = tmp + ((row + i) * actual_width + col);
	    c0 += *ptr * vkernel[i];
	  }
	  unsigned char * ptr = buffer + ((row + vsize / 2) * actual_width + col);
	  *ptr = (unsigned char)(c0 / vtotal);
	}
      }
    } else {
      memcpy(buffer, tmp, actual_width * actual_height);
    }
    delete[] tmp;
  }
  releaseMemory();
}

void
Surface::colorize(const Color & input_color, Surface & target) {
  Color color = input_color;
  color.red *= color.alpha;
  color.green *= color.alpha;
  color.blue *= color.alpha;

  assert(getFormat() == R8 && target.getFormat() == RGBA8);
  assert(getActualWidth() == target.getActualWidth() && getActualHeight() == target.getActualHeight());
  unsigned char * buffer = (unsigned char *)lockMemory(false);
  unsigned char * target_buffer = (unsigned char *)target.lockMemory(true);

  for (unsigned int i = 0; i < actual_width * actual_height; i++) {
    float input_alpha = buffer[i] / 255.0f;
    target_buffer[4 * i + 0] = (unsigned char)(color.red * input_alpha * 255);
    target_buffer[4 * i + 1] = (unsigned char)(color.green * input_alpha * 255);
    target_buffer[4 * i + 2] = (unsigned char)(color.blue * input_alpha * 255);
    target_buffer[4 * i + 3] = (unsigned char)(color.alpha * input_alpha * 255);
  }

  releaseMemory();
  target.releaseMemory();
}

#if 0
void
Surface::multiply(const Color & color) {
  assert(getFormat() == RGBA8);
  unsigned char * buffer = (unsigned char *)lockMemory(true);
  assert(buffer);
  unsigned int red = toByte(color.red);
  unsigned int green = toByte(color.green);
  unsigned int blue = toByte(color.blue);
  unsigned int alpha = toByte(color.alpha);
  for (unsigned int i = 0; i < actual_width * actual_height; i++) {
    unsigned char * ptr = buffer + (i * 4);
    ptr[0] = (unsigned char)(ptr[0] * red / 255);
    ptr[1] = (unsigned char)(ptr[1] * green / 255);
    ptr[2] = (unsigned char)(ptr[2] * blue / 255);
    ptr[3] = (unsigned char)(ptr[3] * alpha / 255);
  }
  releaseMemory();
}
#endif

#if 0
void *
Surface::lockMemoryPartial(unsigned int x0, unsigned int y0, unsigned int required_width, unsigned int required_height) {
  unsigned int * buffer = (unsigned int *)lockMemory();
  assert(buffer);

  delete[] scaled_buffer;
  scaled_buffer = new unsigned int[required_width * required_height];

  unsigned int offset = 0;
  for (unsigned int y = y0; y < y0 + required_height; y++) {
    for (unsigned int x = x0; x < x0 + required_width; x++) {
      scaled_buffer[offset++] = buffer[y * actual_width + x];
    }
  }

  return scaled_buffer;
}
#endif

bool
Surface::isPNG(const unsigned char * buffer, size_t size) {
  return size >= 4 && buffer[0] == 0x89 && buffer[1] == 0x50 && buffer[2] == 0x4e && buffer[3] == 0x47;
}

bool
Surface::isJPEG(const unsigned char * buffer, size_t size) {
  return size >= 3 && buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff;
}

bool
Surface::isGIF(const unsigned char * buffer, size_t size) {
  return size >= 6 && buffer[0] == 'G' && buffer[1] == 'I' && buffer[2] == 'F' && buffer[3] == '8' && (buffer[4] == '7' || buffer[4] == '9') && buffer[5] == 'a';
}

bool
Surface::isBMP(const unsigned char * buffer, size_t size) {
  return size > 2 && buffer[0] == 0x42 && buffer[1] == 0x4d;
}

bool
Surface::isXML(const unsigned char * buffer, size_t size) {
  return size >= 6 && buffer[0] == '<' && buffer[1] == '!' && buffer[2] == 'D' && buffer[3] == 'O' && buffer[4] == 'C' && buffer[5] == 'T';
}
<|endoftext|>