<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: hw2fw.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 08:18:28 $
 *
 *  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
 *
 ************************************************************************/

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

struct hw_pair
{
    sal_Unicode         nFrom;
    sal_Unicode         nTo;
};

#define MAKE_PAIR(a,b) { a, b }

static struct hw_pair aHWPairs[] =
{
  MAKE_PAIR( 0xFF65, 0x30FB ),  // HALFWIDTH KATAKANA MIDDLE DOT --> KATAKANA MIDDLE DOT
  MAKE_PAIR( 0xFF66, 0x30F2 ),  // HALFWIDTH KATAKANA LETTER WO --> KATAKANA LETTER WO
  MAKE_PAIR( 0xFF67, 0x30A1 ),  // HALFWIDTH KATAKANA LETTER SMALL A --> KATAKANA LETTER SMALL A
  MAKE_PAIR( 0xFF68, 0x30A3 ),  // HALFWIDTH KATAKANA LETTER SMALL I --> KATAKANA LETTER SMALL I
  MAKE_PAIR( 0xFF69, 0x30A5 ),  // HALFWIDTH KATAKANA LETTER SMALL U --> KATAKANA LETTER SMALL U
  MAKE_PAIR( 0xFF6A, 0x30A7 ),  // HALFWIDTH KATAKANA LETTER SMALL E --> KATAKANA LETTER SMALL E
  MAKE_PAIR( 0xFF6B, 0x30A9 ),  // HALFWIDTH KATAKANA LETTER SMALL O --> KATAKANA LETTER SMALL O
  MAKE_PAIR( 0xFF6C, 0x30E3 ),  // HALFWIDTH KATAKANA LETTER SMALL YA --> KATAKANA LETTER SMALL YA
  MAKE_PAIR( 0xFF6D, 0x30E5 ),  // HALFWIDTH KATAKANA LETTER SMALL YU --> KATAKANA LETTER SMALL YU
  MAKE_PAIR( 0xFF6E, 0x30E7 ),  // HALFWIDTH KATAKANA LETTER SMALL YO --> KATAKANA LETTER SMALL YO
  MAKE_PAIR( 0xFF6F, 0x30C3 ),  // HALFWIDTH KATAKANA LETTER SMALL TU --> KATAKANA LETTER SMALL TU
  MAKE_PAIR( 0xFF70, 0x30FC ),  // HALFWIDTH KATAKANA-HIRAGANA PROLONGED SOUND MARK --> KATAKANA-HIRAGANA PROLONGED SOUND MARK
  MAKE_PAIR( 0xFF71, 0x30A2 ),  // HALFWIDTH KATAKANA LETTER A --> KATAKANA LETTER A
  MAKE_PAIR( 0xFF72, 0x30A4 ),  // HALFWIDTH KATAKANA LETTER I --> KATAKANA LETTER I
  MAKE_PAIR( 0xFF73, 0x30A6 ),  // HALFWIDTH KATAKANA LETTER U --> KATAKANA LETTER U
  MAKE_PAIR( 0xFF74, 0x30A8 ),  // HALFWIDTH KATAKANA LETTER E --> KATAKANA LETTER E
  MAKE_PAIR( 0xFF75, 0x30AA ),  // HALFWIDTH KATAKANA LETTER O --> KATAKANA LETTER O
  MAKE_PAIR( 0xFF76, 0x30AB ),  // HALFWIDTH KATAKANA LETTER KA --> KATAKANA LETTER KA
  MAKE_PAIR( 0xFF77, 0x30AD ),  // HALFWIDTH KATAKANA LETTER KI --> KATAKANA LETTER KI
  MAKE_PAIR( 0xFF78, 0x30AF ),  // HALFWIDTH KATAKANA LETTER KU --> KATAKANA LETTER KU
  MAKE_PAIR( 0xFF79, 0x30B1 ),  // HALFWIDTH KATAKANA LETTER KE --> KATAKANA LETTER KE
  MAKE_PAIR( 0xFF7A, 0x30B3 ),  // HALFWIDTH KATAKANA LETTER KO --> KATAKANA LETTER KO
  MAKE_PAIR( 0xFF7B, 0x30B5 ),  // HALFWIDTH KATAKANA LETTER SA --> KATAKANA LETTER SA
  MAKE_PAIR( 0xFF7C, 0x30B7 ),  // HALFWIDTH KATAKANA LETTER SI --> KATAKANA LETTER SI
  MAKE_PAIR( 0xFF7D, 0x30B9 ),  // HALFWIDTH KATAKANA LETTER SU --> KATAKANA LETTER SU
  MAKE_PAIR( 0xFF7E, 0x30BB ),  // HALFWIDTH KATAKANA LETTER SE --> KATAKANA LETTER SE
  MAKE_PAIR( 0xFF7F, 0x30BD ),  // HALFWIDTH KATAKANA LETTER SO --> KATAKANA LETTER SO
  MAKE_PAIR( 0xFF80, 0x30BF ),  // HALFWIDTH KATAKANA LETTER TA --> KATAKANA LETTER TA
  MAKE_PAIR( 0xFF81, 0x30C1 ),  // HALFWIDTH KATAKANA LETTER TI --> KATAKANA LETTER TI
  MAKE_PAIR( 0xFF82, 0x30C4 ),  // HALFWIDTH KATAKANA LETTER TU --> KATAKANA LETTER TU
  MAKE_PAIR( 0xFF83, 0x30C6 ),  // HALFWIDTH KATAKANA LETTER TE --> KATAKANA LETTER TE
  MAKE_PAIR( 0xFF84, 0x30C8 ),  // HALFWIDTH KATAKANA LETTER TO --> KATAKANA LETTER TO
  MAKE_PAIR( 0xFF85, 0x30CA ),  // HALFWIDTH KATAKANA LETTER NA --> KATAKANA LETTER NA
  MAKE_PAIR( 0xFF86, 0x30CB ),  // HALFWIDTH KATAKANA LETTER NI --> KATAKANA LETTER NI
  MAKE_PAIR( 0xFF87, 0x30CC ),  // HALFWIDTH KATAKANA LETTER NU --> KATAKANA LETTER NU
  MAKE_PAIR( 0xFF88, 0x30CD ),  // HALFWIDTH KATAKANA LETTER NE --> KATAKANA LETTER NE
  MAKE_PAIR( 0xFF89, 0x30CE ),  // HALFWIDTH KATAKANA LETTER NO --> KATAKANA LETTER NO
  MAKE_PAIR( 0xFF8A, 0x30CF ),  // HALFWIDTH KATAKANA LETTER HA --> KATAKANA LETTER HA
  MAKE_PAIR( 0xFF8B, 0x30D2 ),  // HALFWIDTH KATAKANA LETTER HI --> KATAKANA LETTER HI
  MAKE_PAIR( 0xFF8C, 0x30D5 ),  // HALFWIDTH KATAKANA LETTER HU --> KATAKANA LETTER HU
  MAKE_PAIR( 0xFF8D, 0x30D8 ),  // HALFWIDTH KATAKANA LETTER HE --> KATAKANA LETTER HE
  MAKE_PAIR( 0xFF8E, 0x30DB ),  // HALFWIDTH KATAKANA LETTER HO --> KATAKANA LETTER HO
  MAKE_PAIR( 0xFF8F, 0x30DE ),  // HALFWIDTH KATAKANA LETTER MA --> KATAKANA LETTER MA
  MAKE_PAIR( 0xFF90, 0x30DF ),  // HALFWIDTH KATAKANA LETTER MI --> KATAKANA LETTER MI
  MAKE_PAIR( 0xFF91, 0x30E0 ),  // HALFWIDTH KATAKANA LETTER MU --> KATAKANA LETTER MU
  MAKE_PAIR( 0xFF92, 0x30E1 ),  // HALFWIDTH KATAKANA LETTER ME --> KATAKANA LETTER ME
  MAKE_PAIR( 0xFF93, 0x30E2 ),  // HALFWIDTH KATAKANA LETTER MO --> KATAKANA LETTER MO
  MAKE_PAIR( 0xFF94, 0x30E4 ),  // HALFWIDTH KATAKANA LETTER YA --> KATAKANA LETTER YA
  MAKE_PAIR( 0xFF95, 0x30E6 ),  // HALFWIDTH KATAKANA LETTER YU --> KATAKANA LETTER YU
  MAKE_PAIR( 0xFF96, 0x30E8 ),  // HALFWIDTH KATAKANA LETTER YO --> KATAKANA LETTER YO
  MAKE_PAIR( 0xFF97, 0x30E9 ),  // HALFWIDTH KATAKANA LETTER RA --> KATAKANA LETTER RA
  MAKE_PAIR( 0xFF98, 0x30EA ),  // HALFWIDTH KATAKANA LETTER RI --> KATAKANA LETTER RI
  MAKE_PAIR( 0xFF99, 0x30EB ),  // HALFWIDTH KATAKANA LETTER RU --> KATAKANA LETTER RU
  MAKE_PAIR( 0xFF9A, 0x30EC ),  // HALFWIDTH KATAKANA LETTER RE --> KATAKANA LETTER RE
  MAKE_PAIR( 0xFF9B, 0x30ED ),  // HALFWIDTH KATAKANA LETTER RO --> KATAKANA LETTER RO
  MAKE_PAIR( 0xFF9C, 0x30EF ),  // HALFWIDTH KATAKANA LETTER WA --> KATAKANA LETTER WA
  MAKE_PAIR( 0xFF9D, 0x30F3 ),  // HALFWIDTH KATAKANA LETTER N --> KATAKANA LETTER N
  MAKE_PAIR( 0xFF9E, 0x3099 ),  // HALFWIDTH KATAKANA VOICED SOUND MARK --> COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
  MAKE_PAIR( 0xFF9F, 0x309A )   // HALFWIDTH KATAKANA SEMI-VOICED SOUND MARK --> COMBINING KATAKANA-
};

static struct hw_pair aCombine3099[] =
{
    { 0x30a6, 0x30f4 },
    { 0x30ab, 0x30ac },
    { 0x30ad, 0x30ae },
    { 0x30af, 0x30b0 },
    { 0x30b1, 0x30b2 },
    { 0x30b3, 0x30b4 },
    { 0x30b5, 0x30b6 },
    { 0x30b7, 0x30b8 },
    { 0x30b9, 0x30ba },
    { 0x30bb, 0x30bc },
    { 0x30bd, 0x30be },
    { 0x30bf, 0x30c0 },
    { 0x30c1, 0x30c2 },
    { 0x30c4, 0x30c5 },
    { 0x30c6, 0x30c7 },
    { 0x30c8, 0x30c9 },
    { 0x30cf, 0x30d0 },
    { 0x30d2, 0x30d3 },
    { 0x30d5, 0x30d6 },
    { 0x30d8, 0x30d9 },
    { 0x30db, 0x30dc },
    { 0x30ef, 0x30f7 },
    { 0x30f0, 0x30f8 },
    { 0x30f1, 0x30f9 },
    { 0x30f2, 0x30fa },
    { 0x30fd, 0x30fe }
};

static struct hw_pair aCombine309A[] =
{
    { 0x30cf, 0x30d1 },
    { 0x30d2, 0x30d4 },
    { 0x30d5, 0x30d7 },
    { 0x30d8, 0x30da },
    { 0x30db, 0x30dd }
};

USHORT ImplReplaceFullWidth( sal_Unicode* pString, USHORT nLen )
{
    sal_Unicode* pRead  = pString;
    sal_Unicode* pWrite = pRead;
    USHORT nNewLen = nLen;

    while( (pRead - pString) < nLen )
    {
        if( pWrite != pRead )
            *pWrite = *pRead;

        if( *pRead >= 0xff65 && *pRead <= 0xff9f )
        {
            *pWrite = aHWPairs[ *pRead - 0xff65 ].nTo;

            struct hw_pair* pTable = NULL;
            int nTableEntries = 0;
            if( *pWrite == 0x3099 )
            {
                // replace 0x3099 combinations
                pTable = aCombine3099;
                nTableEntries = sizeof(aCombine3099)/sizeof(aCombine3099[0]);
            }
            else if( *pWrite == 0x309a )
            {
                // replace 0x309a combinations
                pTable = aCombine309A;
                nTableEntries = sizeof(aCombine309A)/sizeof(aCombine309A[0]);
            }
            if( pTable )
            {
                sal_Unicode c = pWrite[-1];
                for( int i = 0; i < nTableEntries; i++ )
                    if( c == pTable[i].nFrom )
                    {
                        pWrite--;
                        *pWrite = pTable[i].nTo;
                        nNewLen--;
                        break;
                    }
            }
        }
        pRead++;
        pWrite++;
    }
    if( pWrite < pRead )
        *pWrite = 0;

    return nNewLen;
}

void ConvertHalfwitdhToFullwidth( String& rString )
{
    USHORT nNewLen = ImplReplaceFullWidth( rString.GetBufferAccess(), rString.Len() );
    rString.ReleaseBufferAccess( nNewLen );
}
<commit_msg>INTEGRATION: CWS changefileheader (1.3.86); FILE MERGED 2008/03/28 15:42:11 rt 1.3.86.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: hw2fw.cxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

struct hw_pair
{
    sal_Unicode         nFrom;
    sal_Unicode         nTo;
};

#define MAKE_PAIR(a,b) { a, b }

static struct hw_pair aHWPairs[] =
{
  MAKE_PAIR( 0xFF65, 0x30FB ),  // HALFWIDTH KATAKANA MIDDLE DOT --> KATAKANA MIDDLE DOT
  MAKE_PAIR( 0xFF66, 0x30F2 ),  // HALFWIDTH KATAKANA LETTER WO --> KATAKANA LETTER WO
  MAKE_PAIR( 0xFF67, 0x30A1 ),  // HALFWIDTH KATAKANA LETTER SMALL A --> KATAKANA LETTER SMALL A
  MAKE_PAIR( 0xFF68, 0x30A3 ),  // HALFWIDTH KATAKANA LETTER SMALL I --> KATAKANA LETTER SMALL I
  MAKE_PAIR( 0xFF69, 0x30A5 ),  // HALFWIDTH KATAKANA LETTER SMALL U --> KATAKANA LETTER SMALL U
  MAKE_PAIR( 0xFF6A, 0x30A7 ),  // HALFWIDTH KATAKANA LETTER SMALL E --> KATAKANA LETTER SMALL E
  MAKE_PAIR( 0xFF6B, 0x30A9 ),  // HALFWIDTH KATAKANA LETTER SMALL O --> KATAKANA LETTER SMALL O
  MAKE_PAIR( 0xFF6C, 0x30E3 ),  // HALFWIDTH KATAKANA LETTER SMALL YA --> KATAKANA LETTER SMALL YA
  MAKE_PAIR( 0xFF6D, 0x30E5 ),  // HALFWIDTH KATAKANA LETTER SMALL YU --> KATAKANA LETTER SMALL YU
  MAKE_PAIR( 0xFF6E, 0x30E7 ),  // HALFWIDTH KATAKANA LETTER SMALL YO --> KATAKANA LETTER SMALL YO
  MAKE_PAIR( 0xFF6F, 0x30C3 ),  // HALFWIDTH KATAKANA LETTER SMALL TU --> KATAKANA LETTER SMALL TU
  MAKE_PAIR( 0xFF70, 0x30FC ),  // HALFWIDTH KATAKANA-HIRAGANA PROLONGED SOUND MARK --> KATAKANA-HIRAGANA PROLONGED SOUND MARK
  MAKE_PAIR( 0xFF71, 0x30A2 ),  // HALFWIDTH KATAKANA LETTER A --> KATAKANA LETTER A
  MAKE_PAIR( 0xFF72, 0x30A4 ),  // HALFWIDTH KATAKANA LETTER I --> KATAKANA LETTER I
  MAKE_PAIR( 0xFF73, 0x30A6 ),  // HALFWIDTH KATAKANA LETTER U --> KATAKANA LETTER U
  MAKE_PAIR( 0xFF74, 0x30A8 ),  // HALFWIDTH KATAKANA LETTER E --> KATAKANA LETTER E
  MAKE_PAIR( 0xFF75, 0x30AA ),  // HALFWIDTH KATAKANA LETTER O --> KATAKANA LETTER O
  MAKE_PAIR( 0xFF76, 0x30AB ),  // HALFWIDTH KATAKANA LETTER KA --> KATAKANA LETTER KA
  MAKE_PAIR( 0xFF77, 0x30AD ),  // HALFWIDTH KATAKANA LETTER KI --> KATAKANA LETTER KI
  MAKE_PAIR( 0xFF78, 0x30AF ),  // HALFWIDTH KATAKANA LETTER KU --> KATAKANA LETTER KU
  MAKE_PAIR( 0xFF79, 0x30B1 ),  // HALFWIDTH KATAKANA LETTER KE --> KATAKANA LETTER KE
  MAKE_PAIR( 0xFF7A, 0x30B3 ),  // HALFWIDTH KATAKANA LETTER KO --> KATAKANA LETTER KO
  MAKE_PAIR( 0xFF7B, 0x30B5 ),  // HALFWIDTH KATAKANA LETTER SA --> KATAKANA LETTER SA
  MAKE_PAIR( 0xFF7C, 0x30B7 ),  // HALFWIDTH KATAKANA LETTER SI --> KATAKANA LETTER SI
  MAKE_PAIR( 0xFF7D, 0x30B9 ),  // HALFWIDTH KATAKANA LETTER SU --> KATAKANA LETTER SU
  MAKE_PAIR( 0xFF7E, 0x30BB ),  // HALFWIDTH KATAKANA LETTER SE --> KATAKANA LETTER SE
  MAKE_PAIR( 0xFF7F, 0x30BD ),  // HALFWIDTH KATAKANA LETTER SO --> KATAKANA LETTER SO
  MAKE_PAIR( 0xFF80, 0x30BF ),  // HALFWIDTH KATAKANA LETTER TA --> KATAKANA LETTER TA
  MAKE_PAIR( 0xFF81, 0x30C1 ),  // HALFWIDTH KATAKANA LETTER TI --> KATAKANA LETTER TI
  MAKE_PAIR( 0xFF82, 0x30C4 ),  // HALFWIDTH KATAKANA LETTER TU --> KATAKANA LETTER TU
  MAKE_PAIR( 0xFF83, 0x30C6 ),  // HALFWIDTH KATAKANA LETTER TE --> KATAKANA LETTER TE
  MAKE_PAIR( 0xFF84, 0x30C8 ),  // HALFWIDTH KATAKANA LETTER TO --> KATAKANA LETTER TO
  MAKE_PAIR( 0xFF85, 0x30CA ),  // HALFWIDTH KATAKANA LETTER NA --> KATAKANA LETTER NA
  MAKE_PAIR( 0xFF86, 0x30CB ),  // HALFWIDTH KATAKANA LETTER NI --> KATAKANA LETTER NI
  MAKE_PAIR( 0xFF87, 0x30CC ),  // HALFWIDTH KATAKANA LETTER NU --> KATAKANA LETTER NU
  MAKE_PAIR( 0xFF88, 0x30CD ),  // HALFWIDTH KATAKANA LETTER NE --> KATAKANA LETTER NE
  MAKE_PAIR( 0xFF89, 0x30CE ),  // HALFWIDTH KATAKANA LETTER NO --> KATAKANA LETTER NO
  MAKE_PAIR( 0xFF8A, 0x30CF ),  // HALFWIDTH KATAKANA LETTER HA --> KATAKANA LETTER HA
  MAKE_PAIR( 0xFF8B, 0x30D2 ),  // HALFWIDTH KATAKANA LETTER HI --> KATAKANA LETTER HI
  MAKE_PAIR( 0xFF8C, 0x30D5 ),  // HALFWIDTH KATAKANA LETTER HU --> KATAKANA LETTER HU
  MAKE_PAIR( 0xFF8D, 0x30D8 ),  // HALFWIDTH KATAKANA LETTER HE --> KATAKANA LETTER HE
  MAKE_PAIR( 0xFF8E, 0x30DB ),  // HALFWIDTH KATAKANA LETTER HO --> KATAKANA LETTER HO
  MAKE_PAIR( 0xFF8F, 0x30DE ),  // HALFWIDTH KATAKANA LETTER MA --> KATAKANA LETTER MA
  MAKE_PAIR( 0xFF90, 0x30DF ),  // HALFWIDTH KATAKANA LETTER MI --> KATAKANA LETTER MI
  MAKE_PAIR( 0xFF91, 0x30E0 ),  // HALFWIDTH KATAKANA LETTER MU --> KATAKANA LETTER MU
  MAKE_PAIR( 0xFF92, 0x30E1 ),  // HALFWIDTH KATAKANA LETTER ME --> KATAKANA LETTER ME
  MAKE_PAIR( 0xFF93, 0x30E2 ),  // HALFWIDTH KATAKANA LETTER MO --> KATAKANA LETTER MO
  MAKE_PAIR( 0xFF94, 0x30E4 ),  // HALFWIDTH KATAKANA LETTER YA --> KATAKANA LETTER YA
  MAKE_PAIR( 0xFF95, 0x30E6 ),  // HALFWIDTH KATAKANA LETTER YU --> KATAKANA LETTER YU
  MAKE_PAIR( 0xFF96, 0x30E8 ),  // HALFWIDTH KATAKANA LETTER YO --> KATAKANA LETTER YO
  MAKE_PAIR( 0xFF97, 0x30E9 ),  // HALFWIDTH KATAKANA LETTER RA --> KATAKANA LETTER RA
  MAKE_PAIR( 0xFF98, 0x30EA ),  // HALFWIDTH KATAKANA LETTER RI --> KATAKANA LETTER RI
  MAKE_PAIR( 0xFF99, 0x30EB ),  // HALFWIDTH KATAKANA LETTER RU --> KATAKANA LETTER RU
  MAKE_PAIR( 0xFF9A, 0x30EC ),  // HALFWIDTH KATAKANA LETTER RE --> KATAKANA LETTER RE
  MAKE_PAIR( 0xFF9B, 0x30ED ),  // HALFWIDTH KATAKANA LETTER RO --> KATAKANA LETTER RO
  MAKE_PAIR( 0xFF9C, 0x30EF ),  // HALFWIDTH KATAKANA LETTER WA --> KATAKANA LETTER WA
  MAKE_PAIR( 0xFF9D, 0x30F3 ),  // HALFWIDTH KATAKANA LETTER N --> KATAKANA LETTER N
  MAKE_PAIR( 0xFF9E, 0x3099 ),  // HALFWIDTH KATAKANA VOICED SOUND MARK --> COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
  MAKE_PAIR( 0xFF9F, 0x309A )   // HALFWIDTH KATAKANA SEMI-VOICED SOUND MARK --> COMBINING KATAKANA-
};

static struct hw_pair aCombine3099[] =
{
    { 0x30a6, 0x30f4 },
    { 0x30ab, 0x30ac },
    { 0x30ad, 0x30ae },
    { 0x30af, 0x30b0 },
    { 0x30b1, 0x30b2 },
    { 0x30b3, 0x30b4 },
    { 0x30b5, 0x30b6 },
    { 0x30b7, 0x30b8 },
    { 0x30b9, 0x30ba },
    { 0x30bb, 0x30bc },
    { 0x30bd, 0x30be },
    { 0x30bf, 0x30c0 },
    { 0x30c1, 0x30c2 },
    { 0x30c4, 0x30c5 },
    { 0x30c6, 0x30c7 },
    { 0x30c8, 0x30c9 },
    { 0x30cf, 0x30d0 },
    { 0x30d2, 0x30d3 },
    { 0x30d5, 0x30d6 },
    { 0x30d8, 0x30d9 },
    { 0x30db, 0x30dc },
    { 0x30ef, 0x30f7 },
    { 0x30f0, 0x30f8 },
    { 0x30f1, 0x30f9 },
    { 0x30f2, 0x30fa },
    { 0x30fd, 0x30fe }
};

static struct hw_pair aCombine309A[] =
{
    { 0x30cf, 0x30d1 },
    { 0x30d2, 0x30d4 },
    { 0x30d5, 0x30d7 },
    { 0x30d8, 0x30da },
    { 0x30db, 0x30dd }
};

USHORT ImplReplaceFullWidth( sal_Unicode* pString, USHORT nLen )
{
    sal_Unicode* pRead  = pString;
    sal_Unicode* pWrite = pRead;
    USHORT nNewLen = nLen;

    while( (pRead - pString) < nLen )
    {
        if( pWrite != pRead )
            *pWrite = *pRead;

        if( *pRead >= 0xff65 && *pRead <= 0xff9f )
        {
            *pWrite = aHWPairs[ *pRead - 0xff65 ].nTo;

            struct hw_pair* pTable = NULL;
            int nTableEntries = 0;
            if( *pWrite == 0x3099 )
            {
                // replace 0x3099 combinations
                pTable = aCombine3099;
                nTableEntries = sizeof(aCombine3099)/sizeof(aCombine3099[0]);
            }
            else if( *pWrite == 0x309a )
            {
                // replace 0x309a combinations
                pTable = aCombine309A;
                nTableEntries = sizeof(aCombine309A)/sizeof(aCombine309A[0]);
            }
            if( pTable )
            {
                sal_Unicode c = pWrite[-1];
                for( int i = 0; i < nTableEntries; i++ )
                    if( c == pTable[i].nFrom )
                    {
                        pWrite--;
                        *pWrite = pTable[i].nTo;
                        nNewLen--;
                        break;
                    }
            }
        }
        pRead++;
        pWrite++;
    }
    if( pWrite < pRead )
        *pWrite = 0;

    return nNewLen;
}

void ConvertHalfwitdhToFullwidth( String& rString )
{
    USHORT nNewLen = ImplReplaceFullWidth( rString.GetBufferAccess(), rString.Len() );
    rString.ReleaseBufferAccess( nNewLen );
}
<|endoftext|>


<commit_before>/*
 * Joey Button
 * Felix Wang
 * Peter Wang
 */

#include <stdio.h>
#include <opencv2/video/background_segm.hpp>
#include "opencv2/opencv.hpp"
#include "physics.h"

using namespace cv;
using namespace std;

const char *win = "Flying Pancake";
static bool reverseMirror = false;

int main(int argc, char **argv)
{
    if (argc > 2) {
        fprintf(stderr, "Error: Please limit arguments to 1 or none.\n");
        exit(1);
    }
    else if (argc == 2) {
        if (!strcmp(argv[1], "-m"))
            reverseMirror = true;
        else {
            fprintf(stderr, "Usage: videoBall [-m]\n");
            exit(1);
        }
    }

    int cam = 0; // default camera
    VideoCapture cap(cam);
    if (!cap.isOpened()) {
        fprintf(stderr, "Error: Cannot open camera %d\n", cam);
        exit(1);
    }

    namedWindow(win, CV_WINDOW_AUTOSIZE);

    Mat fgMaskMOG;          // foreground mask generated by MOG method
    Mat inputFrame, outFrame;
    Mat circ;
    Point pt;               // center of the ball

    BackgroundSubtractorMOG2 MOG;

    pt.x = 500;
    pt.y = 0;

    Point momentum;
    momentum.x = 10;
    momentum.y = 50;

    cap >> inputFrame;
    cvtColor(inputFrame, outFrame, CV_LOAD_IMAGE_COLOR);
    cvtColor(inputFrame, circ, CV_BGR2GRAY);

    int height = inputFrame.rows - 2 * RADIUS;
    int width = inputFrame.cols - 2 * RADIUS;

    // double overlap;
    int count = 0;
    int sum;
    Point small;
    Mat ballFrame, handFrame;
    Mat foregroundMask, backgroundMask;
    Mat reverseFrame;
    while (++count) {
        cap >> inputFrame;

        if (reverseMirror) {
            inputFrame.copyTo(reverseFrame);
            flip(reverseFrame, inputFrame, 1);      // 1 ~ flip against y axis
        }

        calcDir(&momentum, &pt, height, width);

        MOG(inputFrame, fgMaskMOG);

        // blank canvas
        circ.setTo(Scalar(0,0,0));

        Rect ballRegion(pt.x - RADIUS, pt.y - RADIUS, 2 * RADIUS, 2 * RADIUS);
        ballFrame = circ(ballRegion);

        foregroundMask = fgMaskMOG > THRESH;         // have to put here otherwise floating point exception
        backgroundMask = fgMaskMOG <= THRESH;
        fgMaskMOG.setTo(Scalar(255, 255, 255), foregroundMask);     // clean up
        fgMaskMOG.setTo(Scalar(0, 0, 0), backgroundMask);
        handFrame = fgMaskMOG(ballRegion);                          // cut to small size

        int halfRad = RADIUS / 2;
        // top left
        small.x = halfRad;    small.y = halfRad;
        sum = getOverlap(&ballFrame, &handFrame, &small);
        momentum.x += sum*3;              momentum.y += sum*3;

        // top right
        small.x = 3 * halfRad;   small.y = halfRad;
        sum = getOverlap(&ballFrame, &handFrame, &small);
        momentum.x -= sum*2;              momentum.y += sum*3;

        // bottom left
        small.x = halfRad;    small.y = 3 * halfRad;
        sum = getOverlap(&ballFrame, &handFrame, &small);
        momentum.x += sum*3;              momentum.y -= sum*2;

        // bottom right
        small.x = 3 * halfRad;   small.y = 3 * halfRad;
        sum = getOverlap(&ballFrame, &handFrame, &small);
        momentum.x -= sum*2;              momentum.y -= sum*2;

        // EVERYTHING BELOW THIS LINE SHOULD BE DRAWING THE outFrame
        outFrame.setTo(Scalar(0,0,0));      // set all of outFrame to be black
        outFrame.setTo(Scalar(255, 255, 255), foregroundMask);

        drawCircle(outFrame, pt, RADIUS);

        imshow(win, outFrame);
        if (count%30 == 0){
          printf("m.x: %d\tm.y: %d\n",momentum.x,momentum.y);
        }
        if (waitKey(1) >= 0)        // listening for key press
	        break;
    }

    return 0;
}
<commit_msg>Removing print statement<commit_after>/*
 * Joey Button
 * Felix Wang
 * Peter Wang
 */

#include <stdio.h>
#include <opencv2/video/background_segm.hpp>
#include "opencv2/opencv.hpp"
#include "physics.h"

using namespace cv;
using namespace std;

const char *win = "Flying Pancake";
static bool reverseMirror = false;

int main(int argc, char **argv)
{
    if (argc > 2) {
        fprintf(stderr, "Error: Please limit arguments to 1 or none.\n");
        exit(1);
    }
    else if (argc == 2) {
        if (!strcmp(argv[1], "-m"))
            reverseMirror = true;
        else {
            fprintf(stderr, "Usage: videoBall [-m]\n");
            exit(1);
        }
    }

    int cam = 0; // default camera
    VideoCapture cap(cam);
    if (!cap.isOpened()) {
        fprintf(stderr, "Error: Cannot open camera %d\n", cam);
        exit(1);
    }

    namedWindow(win, CV_WINDOW_AUTOSIZE);

    Mat fgMaskMOG;          // foreground mask generated by MOG method
    Mat inputFrame, outFrame;
    Mat circ;
    Point pt;               // center of the ball

    BackgroundSubtractorMOG2 MOG;

    pt.x = 500;
    pt.y = 0;

    Point momentum;
    momentum.x = 10;
    momentum.y = 50;

    cap >> inputFrame;
    cvtColor(inputFrame, outFrame, CV_LOAD_IMAGE_COLOR);
    cvtColor(inputFrame, circ, CV_BGR2GRAY);

    int height = inputFrame.rows - 2 * RADIUS;
    int width = inputFrame.cols - 2 * RADIUS;

    // double overlap;
    int count = 0;
    int sum;
    Point small;
    Mat ballFrame, handFrame;
    Mat foregroundMask, backgroundMask;
    Mat reverseFrame;
    while (++count) {
        cap >> inputFrame;

        if (reverseMirror) {
            inputFrame.copyTo(reverseFrame);
            flip(reverseFrame, inputFrame, 1);      // 1 ~ flip against y axis
        }

        calcDir(&momentum, &pt, height, width);

        MOG(inputFrame, fgMaskMOG);

        // blank canvas
        circ.setTo(Scalar(0,0,0));

        Rect ballRegion(pt.x - RADIUS, pt.y - RADIUS, 2 * RADIUS, 2 * RADIUS);
        ballFrame = circ(ballRegion);

        foregroundMask = fgMaskMOG > THRESH;         // have to put here otherwise floating point exception
        backgroundMask = fgMaskMOG <= THRESH;
        fgMaskMOG.setTo(Scalar(255, 255, 255), foregroundMask);     // clean up
        fgMaskMOG.setTo(Scalar(0, 0, 0), backgroundMask);
        handFrame = fgMaskMOG(ballRegion);                          // cut to small size

        int halfRad = RADIUS / 2;
        // top left
        small.x = halfRad;    small.y = halfRad;
        sum = getOverlap(&ballFrame, &handFrame, &small);
        momentum.x += sum*3;              momentum.y += sum*3;

        // top right
        small.x = 3 * halfRad;   small.y = halfRad;
        sum = getOverlap(&ballFrame, &handFrame, &small);
        momentum.x -= sum*2;              momentum.y += sum*3;

        // bottom left
        small.x = halfRad;    small.y = 3 * halfRad;
        sum = getOverlap(&ballFrame, &handFrame, &small);
        momentum.x += sum*3;              momentum.y -= sum*2;

        // bottom right
        small.x = 3 * halfRad;   small.y = 3 * halfRad;
        sum = getOverlap(&ballFrame, &handFrame, &small);
        momentum.x -= sum*2;              momentum.y -= sum*2;

        // EVERYTHING BELOW THIS LINE SHOULD BE DRAWING THE outFrame
        outFrame.setTo(Scalar(0,0,0));      // set all of outFrame to be black
        outFrame.setTo(Scalar(255, 255, 255), foregroundMask);

        drawCircle(outFrame, pt, RADIUS);

        imshow(win, outFrame);

        if (waitKey(1) >= 0)        // listening for key press
	        break;
    }

    return 0;
}
<|endoftext|>


<commit_before>/*
 screen.cpp
 Classic Invaders

 Copyright (c) 2013, Todd Steinackle, Simon Que
 All rights reserved.

 Redistribution and use in source and binary forms, with or without modification, are permitted
 provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice, this list of conditions
 and the following disclaimer.

 * Redistributions in binary form must reproduce the above copyright
 notice, this list of conditions and the following disclaimer in the documentation and/or other
 materials provided with the distribution.

 * Neither the name of The No Quarter Arcade (http://www.noquarterarcade.com/)  nor the names of
 its contributors may be used to endorse or promote products derived from this software without
 specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
 IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
 IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
 THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

#include "screen.h"

#include <stdio.h>

#include <DuinoCube.h>

#include "game_entity.h"
#include "printf.h"

// TODO: This should be included from a ChronoCube library file.
#define MAX_NUM_SPRITES      128

#define DEFAULT_COLOR_KEY   0xff

#define SPRITE_LAYER_INDEX     3

extern uint16_t g_vram_offsets[];

namespace {

    // Values of the sprite dimension fields in the sprite control register.
    enum {
        SPRITE_DIMENSION_8,
        SPRITE_DIMENSION_16,
        SPRITE_DIMENSION_32,
        SPRITE_DIMENSION_64,
    };

    // Gets the sprite dimension code for a given dimension that is one of:
    // 8, 16, 32, 64.
    // If it doesn't match any of these, returns the code for 8.
    uint8_t get_sprite_dimension(uint8_t size) {
        switch(size) {
        case 64:
            return SPRITE_DIMENSION_64;
        case 32:
            return SPRITE_DIMENSION_32;
        case 16:
            return SPRITE_DIMENSION_16;
        case 8:
        default:
            return SPRITE_DIMENSION_8;
        }
    }

}

namespace Graphics {
    Screen::Screen() : allocated_vram_size(0) {}

    bool Screen::init() {
        memset(num_sprites_per_type, 0, sizeof(num_sprites_per_type));
        memset(sprite_index_bases, 0, sizeof(sprite_index_bases));

        DC.Core.writeWord(REG_SPRITE_Z, SPRITE_LAYER_INDEX);

        return true;
    }

    void Screen::begin_update() {
        // Wait for the start of vertical blank, at which point it is safe to
        // modify the contents of the video controller.
        while (!(DC.Core.readWord(REG_OUTPUT_STATUS) & (1 << REG_VBLANK)));
    }

    void Screen::update() {
        // Wait for the end of vertical blank.  This is when the drawing
        // actually begins.
        while ((DC.Core.readWord(REG_OUTPUT_STATUS) & (1 << REG_VBLANK)));
    }

    void Screen::allocate_sprites(const int* num_objects_per_type) {
        uint16_t sprite_index = 0;
        for (int type = 0;
             type < NUM_GAME_ENTITY_TYPES && sprite_index < MAX_NUM_SPRITES;
             ++type) {
            // Store the number of sprites and first sprite index for each type.
            int num_objects_of_type = num_objects_per_type[type];
            num_sprites_per_type[type] = num_objects_of_type;
            sprite_index_bases[type] = sprite_index;
            printf_P("Allocated %u sprites starting at %u for object type %d\n",
                     num_objects_of_type, sprite_index, type);

            if (num_objects_of_type == 0)
                continue;

            const GameEntities::GameEntityTypeProperties* properties =
                GameEntities::GameEntity::get_type_property(type);

            uint8_t sprite_w = get_sprite_dimension(properties->sprite_w);
            uint8_t sprite_h = get_sprite_dimension(properties->sprite_h);
            // Initialize each sprite's dimensions, color key, and data offset.
            for (int i = 0; i < num_objects_of_type; ++i) {
                DC.Core.writeWord(SPRITE_REG(i, SPRITE_CTRL_1),
                                  (sprite_w << SPRITE_HSIZE_0) |
                                  (sprite_h << SPRITE_VSIZE_0));
                DC.Core.writeWord(SPRITE_REG(i, SPRITE_COLOR_KEY),
                                  DEFAULT_COLOR_KEY);
                DC.Core.writeWord(SPRITE_REG(i, SPRITE_DATA_OFFSET),
                                  get_image_offset(type));
            }

            sprite_index += num_objects_of_type;
        }
        if (sprite_index == MAX_NUM_SPRITES) {
            printf_P("Attempted to allocate too many sprites: %d\n",
                     sprite_index);
        }
    }

    void Screen::set_palette_data(uint8_t palette, const void* palette_data,
                                  uint16_t size) {
        DC.Core.writeData(PALETTE(palette), palette_data, size);
    }

    void Screen::set_palette_entry(uint8_t palette, uint8_t entry,
                                   uint8_t r, uint8_t g, uint8_t b) {
        struct {
            uint8_t r;
            uint8_t g;
            uint8_t b;
            uint8_t padding;
        } palette_entry;
        palette_entry.r = r;
        palette_entry.g = g;
        palette_entry.b = b;
        palette_entry.padding = 0;
        DC.Core.writeData(PALETTE(palette) + sizeof(palette_entry) * entry,
                          &palette_entry, sizeof(palette_entry));
    }

    void Screen::setup_tile_layer(uint8_t layer, bool enabled, uint8_t palette,
                                  uint16_t data_offset, uint16_t color_key) {
        uint16_t tile_ctrl0_value =
            ((enabled ? 1 : 0) << TILE_LAYER_ENABLED) |
            (1 << TILE_ENABLE_NOP) |
            (1 << TILE_ENABLE_TRANSP) |
            (1 << TILE_ENABLE_FLIP) |
            (palette << TILE_PALETTE_START);
        DC.Core.writeWord(TILE_LAYER_REG(layer, TILE_CTRL_0), tile_ctrl0_value);
        DC.Core.writeWord(TILE_LAYER_REG(layer, TILE_DATA_OFFSET), data_offset);
        DC.Core.writeWord(TILE_LAYER_REG(layer, TILE_EMPTY_VALUE), 0);
        DC.Core.writeWord(TILE_LAYER_REG(layer, TILE_COLOR_KEY), color_key);
    }

    void Screen::scroll_tile_layer(uint8_t layer, int16_t x, int16_t y) {
        DC.Core.writeWord(TILE_LAYER_REG(layer, TILE_OFFSET_X), x);
        DC.Core.writeWord(TILE_LAYER_REG(layer, TILE_OFFSET_Y), y);
    }

    void Screen::set_tilemap_data(uint8_t layer, uint8_t x, uint8_t y,
                                  const void* tilemap_data, uint16_t size) {
#define TILEMAP_WIDTH     32
        uint16_t offset = (x + y * TILEMAP_WIDTH) * sizeof(uint16_t);
        DC.Core.writeData(TILEMAP(layer) + offset, tilemap_data, size);
#undef TILEMAP_WIDTH;
    }

    uint16_t Screen::get_image_offset(int type) const {
        return g_vram_offsets[type];
    }

    void Screen::update_sprite(const GameEntities::GameEntity* object) {
        uint8_t type = object->get_type();
        if (num_sprites_per_type[type] == 0)
            return;
        uint8_t index = object->get_index();

        int x = object->get_x();
        int y = object->get_y();

        const GameEntities::GameEntityTypeProperties* properties =
            GameEntities::GameEntity::get_type_property(type);
        uint8_t sprite_w = properties->sprite_w;
        uint8_t sprite_h = properties->sprite_h;
        uint16_t offset = get_image_offset(type) +
                (sprite_w * sprite_h) * object->get_current_image();
        uint16_t sprite_index = sprite_index_bases[type] + index;
        DC.Core.writeWord(SPRITE_REG(sprite_index, SPRITE_CTRL_0),
                          object->is_alive() |
                          (1 << SPRITE_ENABLE_TRANSP));
        DC.Core.writeWord(SPRITE_REG(sprite_index, SPRITE_DATA_OFFSET), offset);
        // TODO: this needs to be faster.
        DC.Core.writeWord(SPRITE_REG(sprite_index, SPRITE_OFFSET_X), x);
        DC.Core.writeWord(SPRITE_REG(sprite_index, SPRITE_OFFSET_Y), y);
    }

}
<commit_msg>Fix sprite assignments in Screen<commit_after>/*
 screen.cpp
 Classic Invaders

 Copyright (c) 2013, Todd Steinackle, Simon Que
 All rights reserved.

 Redistribution and use in source and binary forms, with or without modification, are permitted
 provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice, this list of conditions
 and the following disclaimer.

 * Redistributions in binary form must reproduce the above copyright
 notice, this list of conditions and the following disclaimer in the documentation and/or other
 materials provided with the distribution.

 * Neither the name of The No Quarter Arcade (http://www.noquarterarcade.com/)  nor the names of
 its contributors may be used to endorse or promote products derived from this software without
 specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
 IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
 IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
 THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

#include "screen.h"

#include <stdio.h>

#include <DuinoCube.h>

#include "game_entity.h"
#include "printf.h"

// TODO: This should be included from a ChronoCube library file.
#define MAX_NUM_SPRITES      128

#define DEFAULT_COLOR_KEY   0xff

#define SPRITE_LAYER_INDEX     3

extern uint16_t g_vram_offsets[];

namespace {

    // Values of the sprite dimension fields in the sprite control register.
    enum {
        SPRITE_DIMENSION_8,
        SPRITE_DIMENSION_16,
        SPRITE_DIMENSION_32,
        SPRITE_DIMENSION_64,
    };

    // Gets the sprite dimension code for a given dimension that is one of:
    // 8, 16, 32, 64.
    // If it doesn't match any of these, returns the code for 8.
    uint8_t get_sprite_dimension(uint8_t size) {
        switch(size) {
        case 64:
            return SPRITE_DIMENSION_64;
        case 32:
            return SPRITE_DIMENSION_32;
        case 16:
            return SPRITE_DIMENSION_16;
        case 8:
        default:
            return SPRITE_DIMENSION_8;
        }
    }

}

namespace Graphics {
    Screen::Screen() : allocated_vram_size(0) {}

    bool Screen::init() {
        memset(num_sprites_per_type, 0, sizeof(num_sprites_per_type));
        memset(sprite_index_bases, 0, sizeof(sprite_index_bases));

        DC.Core.writeWord(REG_SPRITE_Z, SPRITE_LAYER_INDEX);

        return true;
    }

    void Screen::begin_update() {
        // Wait for the start of vertical blank, at which point it is safe to
        // modify the contents of the video controller.
        while (!(DC.Core.readWord(REG_OUTPUT_STATUS) & (1 << REG_VBLANK)));
    }

    void Screen::update() {
        // Wait for the end of vertical blank.  This is when the drawing
        // actually begins.
        while ((DC.Core.readWord(REG_OUTPUT_STATUS) & (1 << REG_VBLANK)));
    }

    void Screen::allocate_sprites(const int* num_objects_per_type) {
        uint16_t sprite_index = 0;
        for (int type = 0; type < NUM_GAME_ENTITY_TYPES; ++type) {
            int num_objects_of_type = num_objects_per_type[type];

            // Make sure there's enough room for these sprites.
            if (sprite_index + num_objects_of_type >= MAX_NUM_SPRITES) {
                printf_P("Attempted to allocate too many sprites: %d\n",
                         sprite_index);
                break;
            }

            // Store the number of sprites and first sprite index for each type.
            num_sprites_per_type[type] = num_objects_of_type;
            sprite_index_bases[type] = sprite_index;
            printf_P("Allocated %u sprites starting at %u for object type %d\n",
                     num_objects_of_type, sprite_index, type);

            if (num_objects_of_type == 0)
                continue;

            const GameEntities::GameEntityTypeProperties* properties =
                GameEntities::GameEntity::get_type_property(type);

            uint8_t sprite_w = get_sprite_dimension(properties->sprite_w);
            uint8_t sprite_h = get_sprite_dimension(properties->sprite_h);
            // Initialize each sprite's dimensions, color key, and data offset.
            for (int i = 0; i < num_objects_of_type; ++i, ++sprite_index) {
                DC.Core.writeWord(SPRITE_REG(sprite_index, SPRITE_CTRL_1),
                                  (sprite_w << SPRITE_HSIZE_0) |
                                  (sprite_h << SPRITE_VSIZE_0));
                DC.Core.writeWord(SPRITE_REG(sprite_index, SPRITE_COLOR_KEY),
                                  DEFAULT_COLOR_KEY);
                DC.Core.writeWord(SPRITE_REG(sprite_index, SPRITE_DATA_OFFSET),
                                  get_image_offset(type));
            }
        }
    }

    void Screen::set_palette_data(uint8_t palette, const void* palette_data,
                                  uint16_t size) {
        DC.Core.writeData(PALETTE(palette), palette_data, size);
    }

    void Screen::set_palette_entry(uint8_t palette, uint8_t entry,
                                   uint8_t r, uint8_t g, uint8_t b) {
        struct {
            uint8_t r;
            uint8_t g;
            uint8_t b;
            uint8_t padding;
        } palette_entry;
        palette_entry.r = r;
        palette_entry.g = g;
        palette_entry.b = b;
        palette_entry.padding = 0;
        DC.Core.writeData(PALETTE(palette) + sizeof(palette_entry) * entry,
                          &palette_entry, sizeof(palette_entry));
    }

    void Screen::setup_tile_layer(uint8_t layer, bool enabled, uint8_t palette,
                                  uint16_t data_offset, uint16_t color_key) {
        uint16_t tile_ctrl0_value =
            ((enabled ? 1 : 0) << TILE_LAYER_ENABLED) |
            (1 << TILE_ENABLE_NOP) |
            (1 << TILE_ENABLE_TRANSP) |
            (1 << TILE_ENABLE_FLIP) |
            (palette << TILE_PALETTE_START);
        DC.Core.writeWord(TILE_LAYER_REG(layer, TILE_CTRL_0), tile_ctrl0_value);
        DC.Core.writeWord(TILE_LAYER_REG(layer, TILE_DATA_OFFSET), data_offset);
        DC.Core.writeWord(TILE_LAYER_REG(layer, TILE_EMPTY_VALUE), 0);
        DC.Core.writeWord(TILE_LAYER_REG(layer, TILE_COLOR_KEY), color_key);
    }

    void Screen::scroll_tile_layer(uint8_t layer, int16_t x, int16_t y) {
        DC.Core.writeWord(TILE_LAYER_REG(layer, TILE_OFFSET_X), x);
        DC.Core.writeWord(TILE_LAYER_REG(layer, TILE_OFFSET_Y), y);
    }

    void Screen::set_tilemap_data(uint8_t layer, uint8_t x, uint8_t y,
                                  const void* tilemap_data, uint16_t size) {
#define TILEMAP_WIDTH     32
        uint16_t offset = (x + y * TILEMAP_WIDTH) * sizeof(uint16_t);
        DC.Core.writeData(TILEMAP(layer) + offset, tilemap_data, size);
#undef TILEMAP_WIDTH;
    }

    uint16_t Screen::get_image_offset(int type) const {
        return g_vram_offsets[type];
    }

    void Screen::update_sprite(const GameEntities::GameEntity* object) {
        uint8_t type = object->get_type();
        if (num_sprites_per_type[type] == 0)
            return;
        uint8_t index = object->get_index();

        int x = object->get_x();
        int y = object->get_y();

        const GameEntities::GameEntityTypeProperties* properties =
            GameEntities::GameEntity::get_type_property(type);
        uint8_t sprite_w = properties->sprite_w;
        uint8_t sprite_h = properties->sprite_h;
        uint16_t offset = get_image_offset(type) +
                (sprite_w * sprite_h) * object->get_current_image();
        uint16_t sprite_index = sprite_index_bases[type] + index;
        DC.Core.writeWord(SPRITE_REG(sprite_index, SPRITE_CTRL_0),
                          object->is_alive() |
                          (1 << SPRITE_ENABLE_TRANSP));
        DC.Core.writeWord(SPRITE_REG(sprite_index, SPRITE_DATA_OFFSET), offset);
        // TODO: this needs to be faster.
        DC.Core.writeWord(SPRITE_REG(sprite_index, SPRITE_OFFSET_X), x);
        DC.Core.writeWord(SPRITE_REG(sprite_index, SPRITE_OFFSET_Y), y);
    }

}
<|endoftext|>


<commit_before>/*  This file is part of the KDE project
    Copyright (C) 2005-2006 Matthias Kretz <kretz@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License version 2 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.

*/
#include "videopath.h"
#include "videopath_p.h"
#include "factory.h"

#include "videoeffect.h"
#include "abstractvideooutput.h"

#define PHONON_CLASSNAME VideoPath

namespace Phonon
{
PHONON_OBJECT_IMPL

VideoPath::~VideoPath()
{
	K_D( VideoPath );
    foreach(AbstractVideoOutput* vo, d->outputs)
        d->removeDestructionHandler(vo, d);
    foreach(VideoEffect* ve, d->effects)
        d->removeDestructionHandler(ve, d);
}

bool VideoPath::addOutput( AbstractVideoOutput* videoOutput )
{
	K_D( VideoPath );
	if( d->outputs.contains( videoOutput ) )
		return false;

	if( iface() )
	{
		bool success;
		BACKEND_GET1( bool, success, "addOutput", QObject*, videoOutput->iface() );
		if( success )
		{
            d->addDestructionHandler(videoOutput, d);
			d->outputs << videoOutput;
			return true;
		}
	}
	return false;
}

bool VideoPath::removeOutput( AbstractVideoOutput* videoOutput )
{
	K_D( VideoPath );
	if( !d->outputs.contains( videoOutput ) )
		return false;

	if( d->backendObject )
	{
		bool success;
		BACKEND_GET1( bool, success, "removeOutput", QObject*, videoOutput->iface() );
		if( success )
		{
			d->outputs.removeAll( videoOutput );
			return true;
		}
	}
	return false;
}

const QList<AbstractVideoOutput*>& VideoPath::outputs() const
{
	K_D( const VideoPath );
	return d->outputs;
}

bool VideoPath::insertEffect( VideoEffect* newEffect, VideoEffect* insertBefore )
{
	// effects may be added multiple times, but that means the objects are
	// different (the class is still the same)
	K_D( VideoPath );
	if( d->effects.contains( newEffect ) )
		return false;

	if( iface() )
	{
		bool success;
		BACKEND_GET2( bool, success, "insertEffect", QObject*, newEffect->iface(), QObject*, insertBefore ? insertBefore->iface() : 0 );
		if( success )
		{
            d->addDestructionHandler(newEffect, d);
			if( insertBefore )
				d->effects.insert( d->effects.indexOf( insertBefore ), newEffect );
			else
				d->effects << newEffect;
			return true;
		}
	}
	return false;
}

bool VideoPath::removeEffect( VideoEffect* effect )
{
	K_D( VideoPath );
	if( !d->effects.contains( effect ) )
		return false;

	if( d->backendObject )
	{
		bool success;
		BACKEND_GET1( bool, success, "removeEffect", QObject*, effect->iface() );
		if( success )
		{
			d->effects.removeAll( effect );
			return true;
		}
	}
	return false;
}

const QList<VideoEffect*>& VideoPath::effects() const
{
	K_D( const VideoPath );
	return d->effects;
}

bool VideoPathPrivate::aboutToDeleteIface()
{
	return true;
}

void VideoPath::setupIface()
{
	K_D( VideoPath );
	Q_ASSERT( d->backendObject );

	// set up attributes
	bool success;
	QList<AbstractVideoOutput*> outputList = d->outputs;
	foreach( AbstractVideoOutput* output, outputList )
	{
		BACKEND_GET1( bool, success, "addOutput", QObject*, output->iface() );
		if( !success )
			d->outputs.removeAll( output );
	}

	QList<VideoEffect*> effectList = d->effects;
	foreach( VideoEffect* effect, effectList )
	{
		BACKEND_GET1( bool, success, "insertEffect", QObject*, effect->iface() );
		if( !success )
			d->effects.removeAll( effect );
	}
}

void VideoPathPrivate::phononObjectDestroyed( Base* o )
{
	// this method is called from Phonon::Base::~Base(), meaning the VideoEffect
	// dtor has already been called, also virtual functions don't work anymore
	// (therefore qobject_cast can only downcast from Base)
	Q_ASSERT( o );
	AbstractVideoOutput* output = static_cast<AbstractVideoOutput*>( o );
	VideoEffect* videoEffect = static_cast<VideoEffect*>( o );
	if( outputs.contains( output ) )
	{
		if( backendObject )
			pBACKEND_CALL1( "removeOutput", QObject*, output->iface() );
		outputs.removeAll( output );
	}
	else if( effects.contains( videoEffect ) )
	{
		if( backendObject )
			pBACKEND_CALL1( "removeEffect", QObject*, videoEffect->iface() );
		effects.removeAll( videoEffect );
	}
}

} //namespace Phonon

#include "videopath.moc"

#undef PHONON_CLASSNAME
// vim: sw=4 ts=4 tw=80
<commit_msg>don't call the backend for invalid frontend objects (a frontend object is !isValid() if there's no backend object, and none can be created)<commit_after>/*  This file is part of the KDE project
    Copyright (C) 2005-2006 Matthias Kretz <kretz@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License version 2 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.

*/
#include "videopath.h"
#include "videopath_p.h"
#include "factory.h"

#include "videoeffect.h"
#include "abstractvideooutput.h"

#define PHONON_CLASSNAME VideoPath

namespace Phonon
{
PHONON_OBJECT_IMPL

VideoPath::~VideoPath()
{
	K_D( VideoPath );
    foreach(AbstractVideoOutput* vo, d->outputs)
        d->removeDestructionHandler(vo, d);
    foreach(VideoEffect* ve, d->effects)
        d->removeDestructionHandler(ve, d);
}

bool VideoPath::addOutput( AbstractVideoOutput* videoOutput )
{
	K_D( VideoPath );
	if( d->outputs.contains( videoOutput ) )
		return false;

    if (iface() && videoOutput->iface()) {
		bool success;
		BACKEND_GET1( bool, success, "addOutput", QObject*, videoOutput->iface() );
		if( success )
		{
            d->addDestructionHandler(videoOutput, d);
			d->outputs << videoOutput;
			return true;
		}
	}
	return false;
}

bool VideoPath::removeOutput( AbstractVideoOutput* videoOutput )
{
	K_D( VideoPath );
	if( !d->outputs.contains( videoOutput ) )
		return false;

    if (d->backendObject && videoOutput->iface()) {
		bool success;
		BACKEND_GET1( bool, success, "removeOutput", QObject*, videoOutput->iface() );
		if( success )
		{
			d->outputs.removeAll( videoOutput );
			return true;
		}
	}
	return false;
}

const QList<AbstractVideoOutput*>& VideoPath::outputs() const
{
	K_D( const VideoPath );
	return d->outputs;
}

bool VideoPath::insertEffect( VideoEffect* newEffect, VideoEffect* insertBefore )
{
	// effects may be added multiple times, but that means the objects are
	// different (the class is still the same)
	K_D( VideoPath );
	if( d->effects.contains( newEffect ) )
		return false;

    if (iface() && newEffect->iface()) {
		bool success;
		BACKEND_GET2( bool, success, "insertEffect", QObject*, newEffect->iface(), QObject*, insertBefore ? insertBefore->iface() : 0 );
		if( success )
		{
            d->addDestructionHandler(newEffect, d);
			if( insertBefore )
				d->effects.insert( d->effects.indexOf( insertBefore ), newEffect );
			else
				d->effects << newEffect;
			return true;
		}
	}
	return false;
}

bool VideoPath::removeEffect( VideoEffect* effect )
{
	K_D( VideoPath );
	if( !d->effects.contains( effect ) )
		return false;

	if( d->backendObject )
	{
		bool success;
		BACKEND_GET1( bool, success, "removeEffect", QObject*, effect->iface() );
		if( success )
		{
			d->effects.removeAll( effect );
			return true;
		}
	}
	return false;
}

const QList<VideoEffect*>& VideoPath::effects() const
{
	K_D( const VideoPath );
	return d->effects;
}

bool VideoPathPrivate::aboutToDeleteIface()
{
	return true;
}

void VideoPath::setupIface()
{
	K_D( VideoPath );
	Q_ASSERT( d->backendObject );

	// set up attributes
	bool success;
	QList<AbstractVideoOutput*> outputList = d->outputs;
	foreach( AbstractVideoOutput* output, outputList )
	{
        if (output->iface()) {
            BACKEND_GET1(bool, success, "addOutput", QObject*, output->iface());
        } else {
            success = false;
        }
		if( !success )
			d->outputs.removeAll( output );
	}

	QList<VideoEffect*> effectList = d->effects;
	foreach( VideoEffect* effect, effectList )
	{
        if (effect->iface()) {
            BACKEND_GET1( bool, success, "insertEffect", QObject*, effect->iface() );
        } else {
            success = false;
        }
		if( !success )
			d->effects.removeAll( effect );
	}
}

void VideoPathPrivate::phononObjectDestroyed( Base* o )
{
	// this method is called from Phonon::Base::~Base(), meaning the VideoEffect
	// dtor has already been called, also virtual functions don't work anymore
	// (therefore qobject_cast can only downcast from Base)
	Q_ASSERT( o );
	AbstractVideoOutput* output = static_cast<AbstractVideoOutput*>( o );
	VideoEffect* videoEffect = static_cast<VideoEffect*>( o );
	if( outputs.contains( output ) )
	{
        if (backendObject && output->iface()) {
			pBACKEND_CALL1( "removeOutput", QObject*, output->iface() );
        }
		outputs.removeAll( output );
	}
	else if( effects.contains( videoEffect ) )
	{
        if (backendObject && videoEffect->iface()) {
			pBACKEND_CALL1( "removeEffect", QObject*, videoEffect->iface() );
        }
		effects.removeAll( videoEffect );
	}
}

} //namespace Phonon

#include "videopath.moc"

#undef PHONON_CLASSNAME
// vim: sw=4 ts=4 tw=80
<|endoftext|>


<commit_before>/*
 * OSG Keyboard handler
 *
 * Copyright (c) 2015 Jérémie Decock
 *
 * See "OpenSceneGraph 3.0" by Rui Wang and Xuelei Qian (ed. Packt publishing) p.232
 * and http://jeux.developpez.com/tutoriels/openscenegraph/evenements/
 */

#include <osgViewer/Viewer>
#include <iostream>

#include <osgGA/GUIEventHandler>

class KeyboardEventHandler : public osgGA::GUIEventHandler {
    public:
        KeyboardEventHandler() {
            // Put here the data to manipulate...
        }

        /**
         * osgGA::GUIEventAdapter  supplies the received events
         * osgGA::GUIActionAdapter parameter for feedback
         */
        virtual bool handle(const osgGA::GUIEventAdapter& event_adapter, osgGA::GUIActionAdapter& action_adapter) {

            switch(event_adapter.getEventType()) {

                case(osgGA::GUIEventAdapter::KEYDOWN):
                    {
                        switch(event_adapter.getKey()) {
                            // See http://trac.openscenegraph.org/documentation/OpenSceneGraphReferenceDocs/a00359.html for the list of OSG key symbols

                            case 'q':
                                std::cout << "q key pressed (KEYDOWN)" << std::endl;
                                break;

                            case osgGA::GUIEventAdapter::KEY_Escape:
                                std::cout << "Escape key pressed (KEYDOWN)" << std::endl;
                                break;

                            case osgGA::GUIEventAdapter::KEY_Space:
                                std::cout << "Space key pressed (KEYDOWN)" << std::endl;
                                break;

                            case osgGA::GUIEventAdapter::KEY_Up:
                                std::cout << "Up key pressed (KEYDOWN)" << std::endl;
                                break;

                            case osgGA::GUIEventAdapter::KEY_Down:
                                std::cout << "Down key pressed (KEYDOWN)" << std::endl;
                                break;

                            case osgGA::GUIEventAdapter::KEY_Left:
                                std::cout << "Left key pressed (KEYDOWN)" << std::endl;
                                break;

                            case osgGA::GUIEventAdapter::KEY_Right:
                                std::cout << "Right key pressed (KEYDOWN)" << std::endl;
                                break;
                        }
                    }
                    break;

                case(osgGA::GUIEventAdapter::KEYUP):
                    {
                        switch(event_adapter.getKey()) {
                            case 'q':
                                std::cout << "q key pressed (KEYUP)" << std::endl;
                                break;
                        }
                    }
                    break;

                default: // To avoid a warning during compilation
                    break;
            }

            return false;
        }
};

int main(int, char **) {

    // Create an empty scene
    osg::ref_ptr<osg::Group> root = new osg::Group;

    // Viewer
    osgViewer::Viewer viewer;
    viewer.setSceneData(root);

    // Set the keyboard handler
    osg::ref_ptr<KeyboardEventHandler> keyboard_event_handler = new KeyboardEventHandler();
    viewer.addEventHandler(keyboard_event_handler);

    // Run the viewer
    viewer.run();

    return 0;
}
<commit_msg>Add comments.<commit_after>/*
 * OSG Keyboard handler
 *
 * Copyright (c) 2015 Jérémie Decock
 *
 * See "OpenSceneGraph 3.0" by Rui Wang and Xuelei Qian (ed. Packt publishing) p.232
 * and http://jeux.developpez.com/tutoriels/openscenegraph/evenements/
 */

#include <osgViewer/Viewer>
#include <iostream>

#include <osgGA/GUIEventHandler>

class KeyboardEventHandler : public osgGA::GUIEventHandler {
    public:
        KeyboardEventHandler() {
            // Put here the data to manipulate...
        }

        /**
         * osgGA::GUIEventAdapter  supplies the received events
         * osgGA::GUIActionAdapter parameter for feedback
         */
        virtual bool handle(const osgGA::GUIEventAdapter& event_adapter, osgGA::GUIActionAdapter& action_adapter) {

            switch(event_adapter.getEventType()) {

                case(osgGA::GUIEventAdapter::KEYDOWN):  // KEYDOWN == key pressed
                    {
                        switch(event_adapter.getKey()) {
                            // See http://trac.openscenegraph.org/documentation/OpenSceneGraphReferenceDocs/a00359.html for the list of OSG key symbols

                            case 'q':
                                std::cout << "q key pressed (KEYDOWN)" << std::endl;
                                break;

                            case osgGA::GUIEventAdapter::KEY_Escape:
                                std::cout << "Escape key pressed (KEYDOWN)" << std::endl;
                                break;

                            case osgGA::GUIEventAdapter::KEY_Space:
                                std::cout << "Space key pressed (KEYDOWN)" << std::endl;
                                break;

                            case osgGA::GUIEventAdapter::KEY_Up:
                                std::cout << "Up key pressed (KEYDOWN)" << std::endl;
                                break;

                            case osgGA::GUIEventAdapter::KEY_Down:
                                std::cout << "Down key pressed (KEYDOWN)" << std::endl;
                                break;

                            case osgGA::GUIEventAdapter::KEY_Left:
                                std::cout << "Left key pressed (KEYDOWN)" << std::endl;
                                break;

                            case osgGA::GUIEventAdapter::KEY_Right:
                                std::cout << "Right key pressed (KEYDOWN)" << std::endl;
                                break;
                        }
                    }
                    break;

                case(osgGA::GUIEventAdapter::KEYUP):  // KEYUP == key released
                    {
                        switch(event_adapter.getKey()) {
                            case 'q':
                                std::cout << "q key pressed (KEYUP)" << std::endl;
                                break;
                        }
                    }
                    break;

                default: // To avoid a warning during compilation
                    break;
            }

            return false;
        }
};

int main(int, char **) {

    // Create an empty scene
    osg::ref_ptr<osg::Group> root = new osg::Group;

    // Viewer
    osgViewer::Viewer viewer;
    viewer.setSceneData(root);

    // Set the keyboard handler
    osg::ref_ptr<KeyboardEventHandler> keyboard_event_handler = new KeyboardEventHandler();
    viewer.addEventHandler(keyboard_event_handler);

    // Run the viewer
    viewer.run();

    return 0;
}
<|endoftext|>


<commit_before>/*
    Copyright (c) 2006 Volker Krause <vkrause@kde.org>

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

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

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to the
    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.
*/

#include "searchproviderbase.h"
#include "searchprovideradaptor.h"

#include <QtCore/QCoreApplication>
#include <QtCore/QDebug>
#include <QtCore/QHash>
#include <QtCore/QStringList>

class Akonadi::SearchProviderBasePrivate
{
  public:
};

Akonadi::SearchProviderBase::SearchProviderBase( const QString &id ) :
    d( new SearchProviderBasePrivate )
{
  new SearchProviderAdaptor( this );
  Q_ASSERT( QDBusConnection::sessionBus().registerService( "org.kde.Akonadi.SearchProvider." + id ) );
  Q_ASSERT( QDBusConnection::sessionBus().registerObject( "/", this, QDBusConnection::ExportAdaptors ) );
}

Akonadi::SearchProviderBase::~ SearchProviderBase()
{
  delete d;
}

void Akonadi::SearchProviderBase::quit()
{
  QCoreApplication::quit();
}

#include  "searchproviderbase.moc"
<commit_msg>Guys, this code will be compiled in release mode one day...<commit_after>/*
    Copyright (c) 2006 Volker Krause <vkrause@kde.org>

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

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

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to the
    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.
*/

#include "searchproviderbase.h"
#include "searchprovideradaptor.h"

#include <QtCore/QCoreApplication>
#include <QtCore/QDebug>
#include <QtCore/QHash>
#include <QtCore/QStringList>

class Akonadi::SearchProviderBasePrivate
{
  public:
};

Akonadi::SearchProviderBase::SearchProviderBase( const QString &id ) :
    d( new SearchProviderBasePrivate )
{
  new SearchProviderAdaptor( this );
  bool ok = QDBusConnection::sessionBus().registerService( "org.kde.Akonadi.SearchProvider." + id );
  Q_ASSERT( ok );
  ok = QDBusConnection::sessionBus().registerObject( "/", this, QDBusConnection::ExportAdaptors );
  Q_ASSERT( ok );
}

Akonadi::SearchProviderBase::~ SearchProviderBase()
{
  delete d;
}

void Akonadi::SearchProviderBase::quit()
{
  QCoreApplication::quit();
}

#include  "searchproviderbase.moc"
<|endoftext|>


<commit_before>#ifndef INCLUDE_AL_GRAPHICS_BUFFEROBJECT_HPP
#define INCLUDE_AL_GRAPHICS_BUFFEROBJECT_HPP

/*	Allocore --
	Multimedia / virtual environment application class library

	Copyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB.
	Copyright (C) 2012. The Regents of the University of California.
	All rights reserved.

	Redistribution and use in source and binary forms, with or without
	modification, are permitted provided that the following conditions are met:

		Redistributions of source code must retain the above copyright notice,
		this list of conditions and the following disclaimer.

		Redistributions in binary form must reproduce the above copyright
		notice, this list of conditions and the following disclaimer in the
		documentation and/or other materials provided with the distribution.

		Neither the name of the University of California nor the names of its
		contributors may be used to endorse or promote products derived from
		this software without specific prior written permission.

	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
	AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
	IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
	ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
	LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
	CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
	SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
	INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
	CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
	POSSIBILITY OF SUCH DAMAGE.

	File description:
	GPU buffer object helper

	File author(s):
	Lance Putnam, 2010, putnam.lance@gmail.com
*/

#include <vector>
#include "allocore/graphics/al_GPUObject.hpp"
#include "allocore/graphics/al_Graphics.hpp"

namespace al{

/// Generic buffer object
/// @ingroup allocore

/**
Vertex Buffer Objects (VBOs) create buffer memory for vertex attributes in
high-performance memory (in contrast, Vertex Arrays store buffer memory in the
client CPU, incurring the overhead of data transfer). If the buffer object is
used to store pixel data, it is called Pixel Buffer Object (PBO).

VBOs provide an interface to access these buffers in a similar fashion to vertex
arrays. Hints of 'target' and 'mode' help the implementation determine whether
to use system, AGP or video memory.

Unlike display lists, the data in vertex buffer object can be read and updated
by mapping the buffer into client's memory space.

Another important advantage of VBO is sharing the buffer objects with many
clients, like display lists and textures. Since VBO is on the server's side,
multiple clients will be able to access the same buffer with the corresponding
identifier.
*/
class BufferObject : public GPUObject {
public:

	/// Buffer access mode
	enum AccessMode{
		READ_ONLY				= GL_READ_ONLY,
		WRITE_ONLY				= GL_WRITE_ONLY,
		READ_WRITE				= GL_READ_WRITE
	};

	/// Array type
	enum ArrayType{
		VERTEX_ARRAY			= GL_VERTEX_ARRAY,
		NORMAL_ARRAY			= GL_NORMAL_ARRAY,
		COLOR_ARRAY				= GL_COLOR_ARRAY,
		INDEX_ARRAY				= GL_INDEX_ARRAY,
		TEXTURE_COORD_ARRAY		= GL_TEXTURE_COORD_ARRAY,
		EDGE_FLAG_ARRAY			= GL_EDGE_FLAG_ARRAY
	};

	/// Buffer type
	enum BufferType{
		ARRAY_BUFFER			= GL_ARRAY_BUFFER,
		ELEMENT_ARRAY_BUFFER	= GL_ELEMENT_ARRAY_BUFFER,
		PIXEL_PACK_BUFFER		= GL_PIXEL_PACK_BUFFER,			/**< Transfer to PBO */
		PIXEL_UNPACK_BUFFER		= GL_PIXEL_UNPACK_BUFFER		/**< Transfer from PBO */
	};

	/*
	"Static" means the data in VBO will not be changed, "Dynamic" means the data
	will be changed frequently, and "Stream" means the data will be changed every
	frame. "Draw" means the data will be sent to the GPU from the application,
	"Read" means the data will be read by the application from the GPU, and "Copy"
	means the data will be copied internally on the GPU.
	*/
	enum BufferUsage{
		STREAM_DRAW		= GL_STREAM_DRAW,
		//STREAM_READ		= GL_STREAM_READ,
		//STREAM_COPY		= GL_STREAM_COPY,
		STATIC_DRAW		= GL_STATIC_DRAW,
		//STATIC_READ		= GL_STATIC_READ,
		//STATIC_COPY		= GL_STATIC_COPY,
		DYNAMIC_DRAW	= GL_DYNAMIC_DRAW,
		//DYNAMIC_READ	= GL_DYNAMIC_READ,
		//DYNAMIC_COPY	= GL_DYNAMIC_COPY
	};

	/// @param[in] bufType	buffer type (array, element, etc.)
	/// @param[in] bufUsage	buffer usage (stream, static, etc.)
	BufferObject(BufferType bufType, BufferUsage bufUsage);

	virtual ~BufferObject();

	/// Get buffer store size, in bytes
	int size() const;

	/// Set buffer type
	void bufferType(BufferType v);

	/// Set buffer usage
	void usage(BufferUsage v);

	/// Set size, in bytes, of buffer without sending data
	void resize(int numBytes);

	/// Set buffer data store and copy over client data
	void data(const void * src, Graphics::DataType dataType, int numElems, int numComps=1);

	/// Set buffer data store and copy over client data
	template <class T>
	void data(const T * src, int numElems, int numComps=1);

	/// Set buffer data store without copying client data
	void data(Graphics::DataType dataType, int numElems, int numComps=1);

	/// Set buffer data store using cached values
	void data();

	/// Set subregion of buffer store
	template <class T>
	int subData(const T * src, int numElems, int byteOffset=0);

	/// Bind buffer
	void bind();

	/// Unbind buffer
	void unbind() const;

	void operator()();
	void send();

	void print() const;

	#ifdef AL_GRAPHICS_USE_OPENGL
	/* Warning: these are not supported in OpenGL ES */

	/// Set map mode
	void mapMode(AccessMode v);

	/// Map data store to client address space

	/// If successful, returns a valid pointer to the data, otherwise, it returns
	/// NULL.
	/// After using the pointer, call unmap() as soon as possible
	void * map();

	/// Map data store to client address space

	/// If successful, returns true and sets argument to address of data,
	/// otherwise, returns false and leaves argument unaffected.
	/// After using the pointer, call unmap() as soon as possible
	template <class T>
	bool map(T *& buf){
		if(Graphics::toDataType<T>() == mDataType){
			void * r = map();
			if(r){ buf=(T *)r; return true; }
		}
		return false;
	}

	/// Unmaps data store from client address
	/// After unmap(), the mapped pointer is invalid
	bool unmap();
	#endif

protected:
	AccessMode mMapMode;
	BufferType mType;
	BufferUsage mUsage;
	Graphics::DataType mDataType;
	int mNumComps;
	int mNumElems;
	void * mData;
	struct SubData{
		SubData(const void * data_=NULL, unsigned size_=0, unsigned offset_=0)
		:	data(data_), size(size_), offset(offset_){}
		const void * data;
		unsigned size;
		unsigned offset;
	};
	std::vector<SubData> mSubData;

	virtual void onCreate();
	virtual void onDestroy();
	virtual void onPointerFunc(){};
};

/// Vertex buffer object
class VBO : public BufferObject {
public:
	VBO(BufferUsage usage=STREAM_DRAW);

	static void enable();
	static void disable();

protected:
	virtual void onPointerFunc();
};

/// Color buffer object
class CBO : public BufferObject {
public:
	CBO(BufferUsage usage=STREAM_DRAW);

	static void enable();
	static void disable();

protected:
	virtual void onPointerFunc();
};

/// Pixel buffer object
class PBO : public BufferObject {
public:
	PBO(bool packMode, BufferUsage usage=STREAM_DRAW);

protected:
	virtual void onPointerFunc();
};

/// Element object buffer
class EBO : public BufferObject {
public:
	EBO(Graphics::Primitive prim=Graphics::POINTS, BufferUsage usage=STATIC_DRAW);

	EBO& primitive(Graphics::Primitive v);
	EBO& range(int start, int end);

protected:
	Graphics::Primitive mPrim;
	int mStart, mEnd;

	virtual void onPointerFunc();
};

const char * toString(BufferObject::BufferType v);
const char * toString(BufferObject::BufferUsage v);

// IMPLEMENTATION --------------------------------------------------------------

template <class T>
void BufferObject::data(const T * src, int numElems, int numComps){
	data(src, Graphics::toDataType<T>(), numElems, numComps);
}

template <class T>
int BufferObject::subData(const T * src, int numElems, int byteOffset){
	if(numElems){
		bind();
		glBufferSubData(mType, byteOffset, numElems*sizeof(T), src);
		unbind();
		mSubData.push_back(SubData(src, numElems*sizeof(T), byteOffset));
	}
	return numElems*sizeof(T) + byteOffset;
}

} // al::
#endif
<commit_msg>BufferObject: add some getters<commit_after>#ifndef INCLUDE_AL_GRAPHICS_BUFFEROBJECT_HPP
#define INCLUDE_AL_GRAPHICS_BUFFEROBJECT_HPP

/*	Allocore --
	Multimedia / virtual environment application class library

	Copyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB.
	Copyright (C) 2012. The Regents of the University of California.
	All rights reserved.

	Redistribution and use in source and binary forms, with or without
	modification, are permitted provided that the following conditions are met:

		Redistributions of source code must retain the above copyright notice,
		this list of conditions and the following disclaimer.

		Redistributions in binary form must reproduce the above copyright
		notice, this list of conditions and the following disclaimer in the
		documentation and/or other materials provided with the distribution.

		Neither the name of the University of California nor the names of its
		contributors may be used to endorse or promote products derived from
		this software without specific prior written permission.

	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
	AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
	IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
	ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
	LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
	CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
	SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
	INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
	CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
	POSSIBILITY OF SUCH DAMAGE.

	File description:
	GPU buffer object helper

	File author(s):
	Lance Putnam, 2010, putnam.lance@gmail.com
*/

#include <vector>
#include "allocore/graphics/al_GPUObject.hpp"
#include "allocore/graphics/al_Graphics.hpp"

namespace al{

/// Generic buffer object
/// @ingroup allocore

/**
Vertex Buffer Objects (VBOs) create buffer memory for vertex attributes in
high-performance memory (in contrast, Vertex Arrays store buffer memory in the
client CPU, incurring the overhead of data transfer). If the buffer object is
used to store pixel data, it is called Pixel Buffer Object (PBO).

VBOs provide an interface to access these buffers in a similar fashion to vertex
arrays. Hints of 'target' and 'mode' help the implementation determine whether
to use system, AGP or video memory.

Unlike display lists, the data in vertex buffer object can be read and updated
by mapping the buffer into client's memory space.

Another important advantage of VBO is sharing the buffer objects with many
clients, like display lists and textures. Since VBO is on the server's side,
multiple clients will be able to access the same buffer with the corresponding
identifier.
*/
class BufferObject : public GPUObject {
public:

	/// Buffer access mode
	enum AccessMode{
		READ_ONLY				= GL_READ_ONLY,
		WRITE_ONLY				= GL_WRITE_ONLY,
		READ_WRITE				= GL_READ_WRITE
	};

	/// Array type
	enum ArrayType{
		VERTEX_ARRAY			= GL_VERTEX_ARRAY,
		NORMAL_ARRAY			= GL_NORMAL_ARRAY,
		COLOR_ARRAY				= GL_COLOR_ARRAY,
		INDEX_ARRAY				= GL_INDEX_ARRAY,
		TEXTURE_COORD_ARRAY		= GL_TEXTURE_COORD_ARRAY,
		EDGE_FLAG_ARRAY			= GL_EDGE_FLAG_ARRAY
	};

	/// Buffer type
	enum BufferType{
		ARRAY_BUFFER			= GL_ARRAY_BUFFER,
		ELEMENT_ARRAY_BUFFER	= GL_ELEMENT_ARRAY_BUFFER,
		PIXEL_PACK_BUFFER		= GL_PIXEL_PACK_BUFFER,			/**< Transfer to PBO */
		PIXEL_UNPACK_BUFFER		= GL_PIXEL_UNPACK_BUFFER		/**< Transfer from PBO */
	};

	/*
	"Static" means the data in VBO will not be changed, "Dynamic" means the data
	will be changed frequently, and "Stream" means the data will be changed every
	frame. "Draw" means the data will be sent to the GPU from the application,
	"Read" means the data will be read by the application from the GPU, and "Copy"
	means the data will be copied internally on the GPU.
	*/
	enum BufferUsage{
		STREAM_DRAW		= GL_STREAM_DRAW,
		//STREAM_READ		= GL_STREAM_READ,
		//STREAM_COPY		= GL_STREAM_COPY,
		STATIC_DRAW		= GL_STATIC_DRAW,
		//STATIC_READ		= GL_STATIC_READ,
		//STATIC_COPY		= GL_STATIC_COPY,
		DYNAMIC_DRAW	= GL_DYNAMIC_DRAW,
		//DYNAMIC_READ	= GL_DYNAMIC_READ,
		//DYNAMIC_COPY	= GL_DYNAMIC_COPY
	};

	/// @param[in] bufType	buffer type (array, element, etc.)
	/// @param[in] bufUsage	buffer usage (stream, static, etc.)
	BufferObject(BufferType bufType, BufferUsage bufUsage);

	virtual ~BufferObject();

	/// Get buffer store size, in bytes
	int size() const;

	/// Get data type
	Graphics::DataType dataType() const { return mDataType; }

	/// Get number of components in each data element (e.g., 4 for RGBA)
	int numComps() const { return mNumComps; }

	/// Get number of elements (e.g., colors)
	int numElems() const { return mNumElems; }

	/// Set buffer type
	void bufferType(BufferType v);

	/// Set buffer usage
	void usage(BufferUsage v);

	/// Set size, in bytes, of buffer without sending data
	void resize(int numBytes);

	/// Set buffer data store and copy over client data
	void data(const void * src, Graphics::DataType dataType, int numElems, int numComps=1);

	/// Set buffer data store and copy over client data
	template <class T>
	void data(const T * src, int numElems, int numComps=1);

	/// Set buffer data store without copying client data
	void data(Graphics::DataType dataType, int numElems, int numComps=1);

	/// Set buffer data store using cached values
	void data();

	/// Set subregion of buffer store
	template <class T>
	int subData(const T * src, int numElems, int byteOffset=0);

	/// Bind buffer
	void bind();

	/// Unbind buffer
	void unbind() const;

	void operator()();
	void send();

	void print() const;

	#ifdef AL_GRAPHICS_USE_OPENGL
	/* Warning: these are not supported in OpenGL ES */

	/// Set map mode
	void mapMode(AccessMode v);

	/// Map data store to client address space

	/// If successful, returns a valid pointer to the data, otherwise, it returns
	/// NULL.
	/// After using the pointer, call unmap() as soon as possible
	void * map();

	/// Map data store to client address space

	/// If successful, returns true and sets argument to address of data,
	/// otherwise, returns false and leaves argument unaffected.
	/// After using the pointer, call unmap() as soon as possible
	template <class T>
	bool map(T *& buf){
		if(Graphics::toDataType<T>() == mDataType){
			void * r = map();
			if(r){ buf=(T *)r; return true; }
		}
		return false;
	}

	/// Unmaps data store from client address
	/// After unmap(), the mapped pointer is invalid
	bool unmap();
	#endif

protected:
	AccessMode mMapMode;
	BufferType mType;
	BufferUsage mUsage;
	Graphics::DataType mDataType;
	int mNumComps;
	int mNumElems;
	void * mData;
	struct SubData{
		SubData(const void * data_=NULL, unsigned size_=0, unsigned offset_=0)
		:	data(data_), size(size_), offset(offset_){}
		const void * data;
		unsigned size;
		unsigned offset;
	};
	std::vector<SubData> mSubData;

	virtual void onCreate();
	virtual void onDestroy();
	virtual void onPointerFunc(){};
};

/// Vertex buffer object
class VBO : public BufferObject {
public:
	VBO(BufferUsage usage=STREAM_DRAW);

	static void enable();
	static void disable();

protected:
	virtual void onPointerFunc();
};

/// Color buffer object
class CBO : public BufferObject {
public:
	CBO(BufferUsage usage=STREAM_DRAW);

	static void enable();
	static void disable();

protected:
	virtual void onPointerFunc();
};

/// Pixel buffer object
class PBO : public BufferObject {
public:
	PBO(bool packMode, BufferUsage usage=STREAM_DRAW);

protected:
	virtual void onPointerFunc();
};

/// Element object buffer
class EBO : public BufferObject {
public:
	EBO(Graphics::Primitive prim=Graphics::POINTS, BufferUsage usage=STATIC_DRAW);

	EBO& primitive(Graphics::Primitive v);
	EBO& range(int start, int end);

protected:
	Graphics::Primitive mPrim;
	int mStart, mEnd;

	virtual void onPointerFunc();
};

const char * toString(BufferObject::BufferType v);
const char * toString(BufferObject::BufferUsage v);

// IMPLEMENTATION --------------------------------------------------------------

template <class T>
void BufferObject::data(const T * src, int numElems, int numComps){
	data(src, Graphics::toDataType<T>(), numElems, numComps);
}

template <class T>
int BufferObject::subData(const T * src, int numElems, int byteOffset){
	if(numElems){
		bind();
		glBufferSubData(mType, byteOffset, numElems*sizeof(T), src);
		unbind();
		mSubData.push_back(SubData(src, numElems*sizeof(T), byteOffset));
	}
	return numElems*sizeof(T) + byteOffset;
}

} // al::
#endif
<|endoftext|>


<commit_before>#include <iostream>
#include <stdio.h>

#include <algorithm>
#include <initializer_list>
#include <stdexcept>

// http://thenewcpp.wordpress.com/2011/11/23/variadic-templates-part-1-2/

template <typename T, char current, char ... others>  // forward declare
class TinyFixMap;

template <typename T, char current>
class TinyFixMap<T, current>
{
  T val[1];
  int as_index(char c) {
    return c == current ? 0 : -1;
  }
};

template <char current>
size_t get_index(char c) {
  return c == curent ? 0 : -1;
}
template <char current, char ... par>
size_t get_index(char c) {
  return c == current ? sizeof ... (par) : get_index<par>(c);
}

template <typename T, char current, char ... others> // actual declare
class TinyFixMap
{
  //typedef typename TinyFixMap<T, others...> next;
  T val[sizeof...(others) + 1];
//  int as_index(char c) {
   // return c == current ? 0 : nt::as_index(c);

public:
  T& operator[](char c) {
    int i = get_index<current, others>(c);
    if ( i != -1)  {
       return vals[i];
    }
    else {
       throw std::out_of_range("Not a valid index");
    }
  }
};

 //: TinyFixMap<T, others...>

//template <typename T, char index, char ... others>

#if 0
template <typename... Args>
struct find_biggest;

//the biggest of one thing is that one thing
template <typename First>
struct find_biggest<First>
{
  typedef First type;
};

//the biggest of everything in Args and First
template <typename First, typename... Args>
struct find_biggest<First, Args...>
{
  typedef typename find_biggest<Args...>::type next;
  typedef typename std::conditional
  <
    sizeof(First) >= sizeof(next),
    First,
    next
  >::type type;
};

//  TinyFixMap<double, "abc"> var;
//  printf("var['a'] = %f \n", var['a']);
#endif

#if 0
template <typename T, char index>
class TinyFixMap
{
protected:
  T val[1];

  int as_index(char c) {
    if (c == index) {
      return 0;
    } else {
      return -1;
    }
  }

public
  T& operator[char c] {
    if ( as_index(c) !== -1 ) {
      return val[as_index(c)]
    } else {
      throw std::out_of_range();
    }
  }
}
template <typename T, char... index>
class TinyFixMap;
#endif
//    auto it = std::find(std::begin(index...), std::end(index...), c);
//    return it != std::end(index...) ? it - std::begin(index...) : -1 ;

// ? vals[as_index(c)] : vals[-1];

#if 0
template <typename T, char index, char ...nextIndex>
class TinyFixMap
{

}

template <typename T, std::string Indexes>
class TinyFixMap2
{

};
#endif

#if 0
template <typename T, char... index>
class TinyFixMap
{
  T vals[sizeof ...(index) ];
  int as_index(char c) {
    auto list = {index...};
    auto it = std::find(list.begin(), list.end(), c);
    return it != list.end() ? it - list.begin() : -1;
  }
public:
  T& operator[](char c) {
    int i = as_index(c);
    if ( i != -1)  {
       return vals[i];
    }
    else {
       throw std::out_of_range("Not a valid index");
    }
  }
};
#endif

int main()
{
#if 0
  TinyFixMap<double, 'a', 'b', 'c'> var;
  var['a'] = 10.2;
  var['b'] = 13;
  using namespace std;

  cout << "var['a'] = " << var['a'] << endl;
  cout << "var['b'] = " << var['b'] << endl;
  cout << "var['c'] = " << var['c'] << endl;
  cout << "var['d'] = " << var['d'] << endl;
#endif
}

<commit_msg>back mobile phone editting<commit_after>#include <iostream>
#include <stdio.h>

#include <algorithm>
#include <initializer_list>
#include <stdexcept>

// http://thenewcpp.wordpress.com/2011/11/23/variadic-templates-part-1-2/

template <typename T, char current, char ... others>  // forward declare
class TinyFixMap;

template <typename T, char current>
class TinyFixMap<T, current>
{
  T val[1];
  int as_index(char c) {
    return c == current ? 0 : -1;
  }
};

// 一般式，对 N 成立(之形式)
template <char ...>
size_t find_index(char);

// 特殊式，对 1 成立
template <>
site_t find_index<char current>(char c)
{

}

template <char current>
size_t get_index(char c) {
  return c == curent ? 0 : -1;
}
template <char current, char ... par>
size_t get_index(char c) {
  return c == current ? sizeof ... (par) : get_index<par>(c);
}

template <typename T, char current, char ... others> // actual declare
class TinyFixMap
{
  //typedef typename TinyFixMap<T, others...> next;
  T val[sizeof...(others) + 1];
//  int as_index(char c) {
   // return c == current ? 0 : nt::as_index(c);

public:
  T& operator[](char c) {
    int i = get_index<current, others>(c);
    if ( i != -1)  {
       return vals[i];
    }
    else {
       throw std::out_of_range("Not a valid index");
    }
  }
};

 //: TinyFixMap<T, others...>

//template <typename T, char index, char ... others>

#if 0
template <typename... Args>
struct find_biggest;

//the biggest of one thing is that one thing
template <typename First>
struct find_biggest<First>
{
  typedef First type;
};

//the biggest of everything in Args and First
template <typename First, typename... Args>
struct find_biggest<First, Args...>
{
  typedef typename find_biggest<Args...>::type next;
  typedef typename std::conditional
  <
    sizeof(First) >= sizeof(next),
    First,
    next
  >::type type;
};

//  TinyFixMap<double, "abc"> var;
//  printf("var['a'] = %f \n", var['a']);
#endif

#if 0
template <typename T, char index>
class TinyFixMap
{
protected:
  T val[1];

  int as_index(char c) {
    if (c == index) {
      return 0;
    } else {
      return -1;
    }
  }

public
  T& operator[char c] {
    if ( as_index(c) !== -1 ) {
      return val[as_index(c)]
    } else {
      throw std::out_of_range();
    }
  }
}
template <typename T, char... index>
class TinyFixMap;
#endif
//    auto it = std::find(std::begin(index...), std::end(index...), c);
//    return it != std::end(index...) ? it - std::begin(index...) : -1 ;

// ? vals[as_index(c)] : vals[-1];

#if 0
template <typename T, char index, char ...nextIndex>
class TinyFixMap
{

}

template <typename T, std::string Indexes>
class TinyFixMap2
{

};
#endif

#if 0
template <typename T, char... index>
class TinyFixMap
{
  T vals[sizeof ...(index) ];
  int as_index(char c) {
    auto list = {index...};
    auto it = std::find(list.begin(), list.end(), c);
    return it != list.end() ? it - list.begin() : -1;
  }
public:
  T& operator[](char c) {
    int i = as_index(c);
    if ( i != -1)  {
       return vals[i];
    }
    else {
       throw std::out_of_range("Not a valid index");
    }
  }
};
#endif

int main()
{
#if 0
  TinyFixMap<double, 'a', 'b', 'c'> var;
  var['a'] = 10.2;
  var['b'] = 13;
  using namespace std;

  cout << "var['a'] = " << var['a'] << endl;
  cout << "var['b'] = " << var['b'] << endl;
  cout << "var['c'] = " << var['c'] << endl;
  cout << "var['d'] = " << var['d'] << endl;
#endif
}

<|endoftext|>


<commit_before>/// \file
/// \ingroup tutorial_hist
/// Illustrates the advantages of a TH1K histogram
///
/// \macro_image
/// \macro_code
///
/// \author Victor Perevovchikov

void padRefresh(TPad *pad,int flag=0);
void hksimple()
{
// Create a new canvas.
  c1 = new TCanvas("c1","Dynamic Filling Example",200,10,600,900);
  c1->SetFillColor(42);

// Create a normal histogram and two TH1K histograms
  TH1 *hpx[3];
  hpx[0]    = new TH1F("hp0","Normal histogram",1000,-4,4);
  hpx[1]    = new TH1K("hk1","Nearest Neighbour of order 3",1000,-4,4);
  hpx[2]    = new TH1K("hk2","Nearest Neighbour of order 16",1000,-4,4,16);
  c1->Divide(1,3);
  Int_t j;
  for (j=0;j<3;j++) {
     c1->cd(j+1);
     gPad->SetFrameFillColor(33);
     hpx[j]->SetFillColor(48);
     hpx[j]->Draw();
  }

// Fill histograms randomly
  gRandom->SetSeed();
  Float_t px, py, pz;
  const Int_t kUPDATE = 10;
  for (Int_t i = 0; i <= 300; i++) {
     gRandom->Rannor(px,py);
     for (j=0;j<3;j++) {hpx[j]->Fill(px);}
     if (i && (i%kUPDATE) == 0) {
           padRefresh(c1);
     }
  }

  for (j=0;j<3;j++) hpx[j]->Fit("gaus");
  padRefresh(c1);
}
void padRefresh(TPad *pad,int flag)
{
  if (!pad) return;
  pad->Modified();
  pad->Update();
  TList *tl = pad->GetListOfPrimitives();
  if (!tl) return;
  TListIter next(tl);
  TObject *to;
  while ((to=next())) {
    if (to->InheritsFrom(TPad::Class())) padRefresh((TPad*)to,1);}
  if (flag) return;
  gSystem->ProcessEvents();
}
<commit_msg>Do not randomize the test results<commit_after>/// \file
/// \ingroup tutorial_hist
/// Illustrates the advantages of a TH1K histogram
///
/// \macro_image
/// \macro_code
///
/// \author Victor Perevovchikov

void padRefresh(TPad *pad,int flag=0);
void hksimple()
{
// Create a new canvas.
  c1 = new TCanvas("c1","Dynamic Filling Example",200,10,600,900);
  c1->SetFillColor(42);

// Create a normal histogram and two TH1K histograms
  TH1 *hpx[3];
  hpx[0]    = new TH1F("hp0","Normal histogram",1000,-4,4);
  hpx[1]    = new TH1K("hk1","Nearest Neighbour of order 3",1000,-4,4);
  hpx[2]    = new TH1K("hk2","Nearest Neighbour of order 16",1000,-4,4,16);
  c1->Divide(1,3);
  Int_t j;
  for (j=0;j<3;j++) {
     c1->cd(j+1);
     gPad->SetFrameFillColor(33);
     hpx[j]->SetFillColor(48);
     hpx[j]->Draw();
  }

// Fill histograms randomly
  gRandom->SetSeed(12345);
  Float_t px, py, pz;
  const Int_t kUPDATE = 10;
  for (Int_t i = 0; i <= 300; i++) {
     gRandom->Rannor(px,py);
     for (j=0;j<3;j++) {hpx[j]->Fill(px);}
     if (i && (i%kUPDATE) == 0) {
           padRefresh(c1);
     }
  }

  for (j=0;j<3;j++) hpx[j]->Fit("gaus");
  padRefresh(c1);
}
void padRefresh(TPad *pad,int flag)
{
  if (!pad) return;
  pad->Modified();
  pad->Update();
  TList *tl = pad->GetListOfPrimitives();
  if (!tl) return;
  TListIter next(tl);
  TObject *to;
  while ((to=next())) {
    if (to->InheritsFrom(TPad::Class())) padRefresh((TPad*)to,1);}
  if (flag) return;
  gSystem->ProcessEvents();
}
<|endoftext|>


<commit_before>#ifndef DUNE_FEM_FUNCTIONALS_COMMON_LOCALMATRIX_HH
#define DUNE_FEM_FUNCTIONALS_COMMON_LOCALMATRIX_HH

// dunefem-functionals include
#include "localvector.hh"

namespace Dune
{

namespace Functionals
{

namespace Common
{

/**
  * \brief      This class represents a local DoF Matrix.
  *
  *             It is based upon std::vector and should be replaced by something clever in the future!
  *
  * \todo       Doc me, please!
  **/
template< class ElementType >
class LocalMatrix
{
public:
  /**
    * \brief    Initializes an empty matrix, according to the given size.
    **/
  LocalMatrix( const unsigned int rows, const unsigned int cols )
    : rows_( rows ),
      cols_( cols )
  {
    // resize
    storage_.resize( rows_ * cols_, 0.0 );
  }

//  /**
//   * @brief     Resizes the storage size (rows*cols).
//   */
//  void resize( const unsigned int rows, const unsigned int cols )
//  {
//    storage_.resize( rows * cols, 0.0 );
//  }

  /**
    * \brief    Returns the storage size (n*m).
    */
  const unsigned int size() const
  {
    return rows_*cols_;
  }

  ElementType get( const unsigned int i, const unsigned int j ) const
  {
    return storage_[i*cols_+j];
  }

  void set( const unsigned int i, const unsigned int j, ElementType val )
  {
    storage_[i*cols_+j] = val;
  }

  /**
    * \brief    Matrix product with a local DoF vector.
    **/
  LocalVector< ElementType > operator*( const LocalVector< ElementType >& other ) const
  {
    assert( cols_ == other.size() );

    LocalVector< ElementType > result( rows_ );

    for(  unsigned ii = 0; ii < rows_; ++ii )
    {

      for(  unsigned jj = 0; jj < cols_; ++jj )
      {

        result[ii] += get( ii, jj ) * other[jj];

      }

    }

    return result;
  }

  /**
   * @brief Return number of rows.
   */
  unsigned int N() const
  {
    return rows_;
  }

  /**
   * @brief Return number of cols.
   */
  unsigned int M() const
  {
    return cols_;
  }

private:
  std::vector< ElementType > storage_;
  unsigned int rows_;
  unsigned int cols_;

}; // end class LocalDoFVector

} // end namespace Functionals

} // end namespace Common

} // end namespace Dune

#endif // end of include guard: DUNE_FEM_FUNCTIONALS_COMMON_LOCALMATRIX_HH
<commit_msg>some Doxygen docu in Common::LocalMatrix<commit_after>#ifndef DUNE_FEM_FUNCTIONALS_COMMON_LOCALMATRIX_HH
#define DUNE_FEM_FUNCTIONALS_COMMON_LOCALMATRIX_HH

// dunefem-functionals include
#include "localvector.hh"

namespace Dune
{

namespace Functionals
{

namespace Common
{

/**
  * \brief  This class represents a local DoF Matrix.
  *         It is based upon std::vector and should be replaced by something clever in the future!
  *
  * \tparam ElementType
  *         Type of one element, usually double or RangeFieldType.
  *
  * \todo   Doc me, please!
  **/
template< class ElementType >
class LocalMatrix
{
public:

  /**
    * \brief      Initializes an empty matrix, according to the given size.
    *
    * \param[in]  rows
    *             Number of rows, the matrix will have.
    *
    * \param[in]  cols
    *             Number of collumns, the matrix will have.
    **/
  LocalMatrix( const unsigned int rows, const unsigned int cols )
    : rows_( rows ),
      cols_( cols )
  {
    // resize
    storage_.resize( rows_ * cols_, 0.0 );
  }

  /**
    * \brief    Returns the storage size (n*m).
    */
  const unsigned int size() const
  {
    return rows_*cols_;
  }

  ElementType get( const unsigned int i, const unsigned int j ) const
  {
    return storage_[i*cols_+j];
  }

  void set( const unsigned int i, const unsigned int j, ElementType val )
  {
    storage_[i*cols_+j] = val;
  }

  /**
    * \brief    Matrix product with a local DoF vector.
    **/
  LocalVector< ElementType > operator*( const LocalVector< ElementType >& other ) const
  {
    assert( cols_ == other.size() );

    LocalVector< ElementType > result( rows_ );

    for(  unsigned ii = 0; ii < rows_; ++ii )
    {

      for(  unsigned jj = 0; jj < cols_; ++jj )
      {

        result[ii] += get( ii, jj ) * other[jj];

      }

    }

    return result;
  }

  /**
   * @brief Return number of rows.
   */
  unsigned int N() const
  {
    return rows_;
  }

  /**
   * @brief Return number of cols.
   */
  unsigned int M() const
  {
    return cols_;
  }

private:
  std::vector< ElementType > storage_;
  unsigned int rows_;
  unsigned int cols_;

}; // end class LocalDoFVector

} // end namespace Functionals

} // end namespace Common

} // end namespace Dune

#endif // end of include guard: DUNE_FEM_FUNCTIONALS_COMMON_LOCALMATRIX_HH
<|endoftext|>